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/json.h>
55 #include <mono/utils/mono-threads-coop.h>
57 #include "aot-compiler.h"
58 #include "seq-points.h"
59 #include "image-writer.h"
60 #include "dwarfwriter.h"
62 #include "mini-llvm.h"
64 #if !defined(DISABLE_AOT) && !defined(DISABLE_JIT)
66 #if defined(__linux__) || defined(__native_client_codegen__)
67 #define RODATA_SECT ".rodata"
68 #elif defined(TARGET_MACH)
69 #define RODATA_SECT ".section __TEXT, __const"
71 #define RODATA_SECT ".text"
74 #define TV_DECLARE(name) gint64 name
75 #define TV_GETTIME(tv) tv = mono_100ns_ticks ()
76 #define TV_ELAPSED(start,end) (((end) - (start)) / 10)
78 #define ALIGN_TO(val,align) ((((guint64)val) + ((align) - 1)) & ~((align) - 1))
79 #define ALIGN_PTR_TO(ptr,align) (gpointer)((((gssize)(ptr)) + (align - 1)) & (~(align - 1)))
80 #define ROUND_DOWN(VALUE,SIZE) ((VALUE) & ~((SIZE) - 1))
82 /* predefined values for static readonly fields without needed to run the .cctor */
83 typedef struct _ReadOnlyValue ReadOnlyValue;
84 struct _ReadOnlyValue {
87 int type; /* to be used later for typechecking to prevent user errors */
96 static ReadOnlyValue *readonly_values;
98 typedef struct MonoAotOptions {
103 gboolean write_symbols;
104 gboolean metadata_only;
105 gboolean bind_to_runtime_version;
108 gboolean static_link;
112 gboolean dwarf_debug;
114 gboolean log_generics;
115 gboolean log_instances;
116 gboolean gen_seq_points_file;
117 char *gen_seq_points_file_path;
118 gboolean direct_pinvoke;
119 gboolean direct_icalls;
120 gboolean no_direct_calls;
121 gboolean use_trampolines_page;
122 gboolean no_instances;
128 int nrgctx_trampolines;
129 int nimt_trampolines;
130 int ngsharedvt_arg_trampolines;
131 int nrgctx_fetch_trampolines;
132 gboolean print_skipped_methods;
139 char *instances_logfile_path;
146 METHOD_CAT_GSHAREDVT,
152 typedef struct MonoAotStats {
153 int ccount, mcount, lmfcount, abscount, gcount, ocount, genericcount;
154 gint64 code_size, info_size, ex_info_size, unwind_info_size, got_size, class_info_size, got_info_size, plt_size;
155 int methods_without_got_slots, direct_calls, all_calls, llvm_count;
156 int got_slots, offsets_size;
157 int method_categories [METHOD_CAT_NUM];
158 int got_slot_types [MONO_PATCH_INFO_NUM];
159 int got_slot_info_sizes [MONO_PATCH_INFO_NUM];
160 int jit_time, gen_time, link_time;
163 typedef struct GotInfo {
164 GHashTable *patch_to_got_offset;
165 GHashTable **patch_to_got_offset_by_type;
166 GPtrArray *got_patches;
169 typedef struct MonoAotCompile {
172 GHashTable *method_indexes;
173 GHashTable *method_depth;
176 GHashTable **patch_to_plt_entry;
177 GHashTable *plt_offset_to_entry;
178 //GHashTable *patch_to_got_offset;
179 //GHashTable **patch_to_got_offset_by_type;
180 //GPtrArray *got_patches;
181 GotInfo got_info, llvm_got_info;
182 GHashTable *image_hash;
183 GHashTable *method_to_cfg;
184 GHashTable *token_info_hash;
185 GHashTable *method_to_pinvoke_import;
186 GPtrArray *extra_methods;
187 GPtrArray *image_table;
189 GPtrArray *method_order;
190 GHashTable *export_names;
191 /* Maps MonoClass* -> blob offset */
192 GHashTable *klass_blob_hash;
193 /* Maps MonoMethod* -> blob offset */
194 GHashTable *method_blob_hash;
195 GHashTable *gsharedvt_in_signatures;
196 GHashTable *gsharedvt_out_signatures;
197 guint32 *plt_got_info_offsets;
198 guint32 got_offset, llvm_got_offset, plt_offset, plt_got_offset_base, nshared_got_entries;
199 /* Number of GOT entries reserved for trampolines */
200 guint32 num_trampoline_got_entries;
201 guint32 tramp_page_size;
203 guint32 table_offsets [MONO_AOT_TABLE_NUM];
204 guint32 num_trampolines [MONO_AOT_TRAMP_NUM];
205 guint32 trampoline_got_offset_base [MONO_AOT_TRAMP_NUM];
206 guint32 trampoline_size [MONO_AOT_TRAMP_NUM];
207 guint32 tramp_page_code_offsets [MONO_AOT_TRAMP_NUM];
209 MonoAotOptions aot_opts;
213 MonoMemPool *mempool;
216 char *static_linking_symbol;
218 gboolean gas_line_numbers;
219 /* Whenever to emit an object file directly from llc */
220 gboolean llvm_owriter;
222 MonoDwarfWriter *dwarf;
229 GHashTable *unwind_info_offsets;
230 GPtrArray *unwind_ops;
231 guint32 unwind_info_offset;
234 char *llvm_got_symbol;
236 char *llvm_eh_frame_symbol;
237 GHashTable *method_label_hash;
238 const char *temp_prefix;
239 const char *user_symbol_prefix;
240 const char *llvm_label_prefix;
241 const char *inst_directive;
243 guint32 label_generator;
245 gboolean has_jitted_code;
246 MonoAotFileFlags flags;
247 MonoDynamicStream blob;
248 gboolean blob_closed;
249 GHashTable *typespec_classes;
252 char *assembly_name_sym;
253 GHashTable *plt_entry_debug_sym_cache;
254 gboolean thumb_mixed, need_no_dead_strip, need_pt_gnu_stack;
255 GHashTable *ginst_hash;
256 GHashTable *dwarf_ln_filenames;
257 gboolean global_symbols;
258 int objc_selector_index, objc_selector_index_2;
259 GPtrArray *objc_selectors;
260 GHashTable *objc_selector_to_index;
262 FILE *instances_logfile;
270 char *symbol, *llvm_symbol, *debug_sym;
272 gboolean jit_used, llvm_used;
275 #define mono_acfg_lock(acfg) mono_os_mutex_lock (&((acfg)->mutex))
276 #define mono_acfg_unlock(acfg) mono_os_mutex_unlock (&((acfg)->mutex))
278 /* This points to the current acfg in LLVM mode */
279 static MonoAotCompile *llvm_acfg;
281 #ifdef HAVE_ARRAY_ELEM_INIT
282 #define MSGSTRFIELD(line) MSGSTRFIELD1(line)
283 #define MSGSTRFIELD1(line) str##line
284 static const struct msgstr_t {
285 #define PATCH_INFO(a,b) char MSGSTRFIELD(__LINE__) [sizeof (b)];
286 #include "patch-info.h"
289 #define PATCH_INFO(a,b) b,
290 #include "patch-info.h"
293 static const gint16 opidx [] = {
294 #define PATCH_INFO(a,b) [MONO_PATCH_INFO_ ## a] = offsetof (struct msgstr_t, MSGSTRFIELD(__LINE__)),
295 #include "patch-info.h"
299 static G_GNUC_UNUSED const char*
300 get_patch_name (int info)
302 return (const char*)&opstr + opidx [info];
306 #define PATCH_INFO(a,b) b,
307 static const char* const
308 patch_types [MONO_PATCH_INFO_NUM + 1] = {
309 #include "patch-info.h"
313 static G_GNUC_UNUSED const char*
314 get_patch_name (int info)
316 return patch_types [info];
322 get_unwind_info_offset (MonoAotCompile *acfg, guint8 *encoded, guint32 encoded_len);
325 get_plt_entry_debug_sym (MonoAotCompile *acfg, MonoJumpInfo *ji, GHashTable *cache);
328 aot_printf (MonoAotCompile *acfg, const gchar *format, ...)
334 output = acfg->logfile;
338 va_start (args, format);
339 vfprintf (output, format, args);
344 aot_printerrf (MonoAotCompile *acfg, const gchar *format, ...)
350 output = acfg->logfile;
354 va_start (args, format);
355 vfprintf (output, format, args);
360 report_loader_error (MonoAotCompile *acfg, MonoError *error, const char *format, ...)
365 if (mono_error_ok (error))
369 output = acfg->logfile;
373 va_start (args, format);
374 vfprintf (output, format, args);
376 mono_error_cleanup (error);
378 g_error ("FullAOT cannot continue if there are loader errors");
381 /* Wrappers around the image writer functions */
383 #define MAX_SYMBOL_SIZE 256
385 static inline const char *
386 mangle_symbol (const char * symbol, char * mangled_symbol, gsize length)
388 gsize needed_size = length;
390 g_assert (NULL != symbol);
391 g_assert (NULL != mangled_symbol);
392 g_assert (0 != length);
394 #if defined(TARGET_WIN32) && defined(TARGET_X86)
395 if (symbol && '_' != symbol [0]) {
396 needed_size = g_snprintf (mangled_symbol, length, "_%s", symbol);
398 needed_size = g_snprintf (mangled_symbol, length, "%s", symbol);
401 needed_size = g_snprintf (mangled_symbol, length, "%s", symbol);
404 g_assert (0 <= needed_size && needed_size < length);
405 return mangled_symbol;
409 mangle_symbol_alloc (const char * symbol)
411 g_assert (NULL != symbol);
413 #if defined(TARGET_WIN32) && defined(TARGET_X86)
414 if (symbol && '_' != symbol [0]) {
415 return g_strdup_printf ("_%s", symbol);
418 return g_strdup_printf ("%s", symbol);
421 return g_strdup_printf ("%s", symbol);
426 emit_section_change (MonoAotCompile *acfg, const char *section_name, int subsection_index)
428 mono_img_writer_emit_section_change (acfg->w, section_name, subsection_index);
431 #if defined(TARGET_WIN32) && defined(TARGET_X86)
434 emit_local_symbol (MonoAotCompile *acfg, const char *name, const char *end_label, gboolean func)
436 const char * mangled_symbol_name = name;
437 char * mangled_symbol_name_alloc = NULL;
440 mangled_symbol_name_alloc = mangle_symbol_alloc (name);
441 mangled_symbol_name = mangled_symbol_name_alloc;
444 if (name != mangled_symbol_name && 0 != g_strcasecmp (name, mangled_symbol_name)) {
445 mono_img_writer_emit_label (acfg->w, mangled_symbol_name);
447 mono_img_writer_emit_local_symbol (acfg->w, mangled_symbol_name, end_label, func);
449 if (NULL != mangled_symbol_name_alloc) {
450 g_free (mangled_symbol_name_alloc);
457 emit_local_symbol (MonoAotCompile *acfg, const char *name, const char *end_label, gboolean func)
459 mono_img_writer_emit_local_symbol (acfg->w, name, end_label, func);
465 emit_label (MonoAotCompile *acfg, const char *name)
467 mono_img_writer_emit_label (acfg->w, name);
471 emit_bytes (MonoAotCompile *acfg, const guint8* buf, int size)
473 mono_img_writer_emit_bytes (acfg->w, buf, size);
477 emit_string (MonoAotCompile *acfg, const char *value)
479 mono_img_writer_emit_string (acfg->w, value);
483 emit_line (MonoAotCompile *acfg)
485 mono_img_writer_emit_line (acfg->w);
489 emit_alignment (MonoAotCompile *acfg, int size)
491 mono_img_writer_emit_alignment (acfg->w, size);
495 emit_alignment_code (MonoAotCompile *acfg, int size)
497 if (acfg->align_pad_value)
498 mono_img_writer_emit_alignment_fill (acfg->w, size, acfg->align_pad_value);
500 mono_img_writer_emit_alignment (acfg->w, size);
504 emit_padding (MonoAotCompile *acfg, int size)
509 if (acfg->align_pad_value) {
510 for (i = 0; i < 16; ++i)
511 buf [i] = acfg->align_pad_value;
513 memset (buf, 0, sizeof (buf));
516 for (i = 0; i < size; i += 16) {
518 emit_bytes (acfg, buf, size - i);
520 emit_bytes (acfg, buf, 16);
525 emit_pointer (MonoAotCompile *acfg, const char *target)
527 mono_img_writer_emit_pointer (acfg->w, target);
531 emit_pointer_2 (MonoAotCompile *acfg, const char *prefix, const char *target)
533 if (prefix [0] != '\0') {
534 char *s = g_strdup_printf ("%s%s", prefix, target);
535 mono_img_writer_emit_pointer (acfg->w, s);
538 mono_img_writer_emit_pointer (acfg->w, target);
543 emit_int16 (MonoAotCompile *acfg, int value)
545 mono_img_writer_emit_int16 (acfg->w, value);
549 emit_int32 (MonoAotCompile *acfg, int value)
551 mono_img_writer_emit_int32 (acfg->w, value);
555 emit_symbol_diff (MonoAotCompile *acfg, const char *end, const char* start, int offset)
557 mono_img_writer_emit_symbol_diff (acfg->w, end, start, offset);
561 emit_zero_bytes (MonoAotCompile *acfg, int num)
563 mono_img_writer_emit_zero_bytes (acfg->w, num);
567 emit_byte (MonoAotCompile *acfg, guint8 val)
569 mono_img_writer_emit_byte (acfg->w, val);
572 #if defined(TARGET_WIN32) && defined(TARGET_X86)
574 static G_GNUC_UNUSED void
575 emit_global_inner (MonoAotCompile *acfg, const char *name, gboolean func)
577 const char * mangled_symbol_name = name;
578 char * mangled_symbol_name_alloc = NULL;
580 mangled_symbol_name_alloc = mangle_symbol_alloc (name);
581 mangled_symbol_name = mangled_symbol_name_alloc;
583 if (0 != g_strcasecmp (name, mangled_symbol_name)) {
584 mono_img_writer_emit_label (acfg->w, mangled_symbol_name);
586 mono_img_writer_emit_global (acfg->w, mangled_symbol_name, func);
588 if (NULL != mangled_symbol_name_alloc) {
589 g_free (mangled_symbol_name_alloc);
595 static G_GNUC_UNUSED void
596 emit_global_inner (MonoAotCompile *acfg, const char *name, gboolean func)
598 mono_img_writer_emit_global (acfg->w, name, func);
604 emit_global (MonoAotCompile *acfg, const char *name, gboolean func)
606 if (acfg->aot_opts.no_dlsym) {
607 g_ptr_array_add (acfg->globals, g_strdup (name));
608 mono_img_writer_emit_local_symbol (acfg->w, name, NULL, func);
610 emit_global_inner (acfg, name, func);
615 emit_symbol_size (MonoAotCompile *acfg, const char *name, const char *end_label)
617 mono_img_writer_emit_symbol_size (acfg->w, name, end_label);
620 /* Emit a symbol which is referenced by the MonoAotFileInfo structure */
622 emit_info_symbol (MonoAotCompile *acfg, const char *name)
624 char symbol [MAX_SYMBOL_SIZE];
627 emit_label (acfg, name);
628 /* LLVM generated code references this */
629 sprintf (symbol, "%s%s%s", acfg->user_symbol_prefix, acfg->global_prefix, name);
630 emit_label (acfg, symbol);
631 emit_global_inner (acfg, symbol, FALSE);
633 emit_label (acfg, name);
638 emit_string_symbol (MonoAotCompile *acfg, const char *name, const char *value)
641 mono_llvm_emit_aot_data (name, (guint8*)value, strlen (value) + 1);
645 mono_img_writer_emit_section_change (acfg->w, RODATA_SECT, 1);
647 /* On apple, all symbols need to be aligned to avoid warnings from ld */
648 emit_alignment (acfg, 4);
650 mono_img_writer_emit_label (acfg->w, name);
651 mono_img_writer_emit_string (acfg->w, value);
654 static G_GNUC_UNUSED void
655 emit_uleb128 (MonoAotCompile *acfg, guint32 value)
658 guint8 b = value & 0x7f;
660 if (value != 0) /* more bytes to come */
666 static G_GNUC_UNUSED void
667 emit_sleb128 (MonoAotCompile *acfg, gint64 value)
670 gboolean negative = (value < 0);
677 /* the following is unnecessary if the
678 * implementation of >>= uses an arithmetic rather
679 * than logical shift for a signed left operand
683 value |= - ((gint64)1 <<(size - 7));
684 /* sign bit of byte is second high order bit (0x40) */
685 if ((value == 0 && !(byte & 0x40)) ||
686 (value == -1 && (byte & 0x40)))
690 emit_byte (acfg, byte);
694 static G_GNUC_UNUSED void
695 encode_uleb128 (guint32 value, guint8 *buf, guint8 **endbuf)
700 guint8 b = value & 0x7f;
702 if (value != 0) /* more bytes to come */
710 static G_GNUC_UNUSED void
711 encode_sleb128 (gint32 value, guint8 *buf, guint8 **endbuf)
714 gboolean negative = (value < 0);
722 /* the following is unnecessary if the
723 * implementation of >>= uses an arithmetic rather
724 * than logical shift for a signed left operand
728 value |= - (1 <<(size - 7));
729 /* sign bit of byte is second high order bit (0x40) */
730 if ((value == 0 && !(byte & 0x40)) ||
731 (value == -1 && (byte & 0x40)))
742 encode_int (gint32 val, guint8 *buf, guint8 **endbuf)
745 buf [0] = (val >> 0) & 0xff;
746 buf [1] = (val >> 8) & 0xff;
747 buf [2] = (val >> 16) & 0xff;
748 buf [3] = (val >> 24) & 0xff;
754 encode_int16 (guint16 val, guint8 *buf, guint8 **endbuf)
756 buf [0] = (val >> 0) & 0xff;
757 buf [1] = (val >> 8) & 0xff;
763 encode_string (const char *s, guint8 *buf, guint8 **endbuf)
765 int len = strlen (s);
767 memcpy (buf, s, len + 1);
768 *endbuf = buf + len + 1;
772 emit_unset_mode (MonoAotCompile *acfg)
774 mono_img_writer_emit_unset_mode (acfg->w);
777 static G_GNUC_UNUSED void
778 emit_set_thumb_mode (MonoAotCompile *acfg)
780 emit_unset_mode (acfg);
781 fprintf (acfg->fp, ".code 16\n");
784 static G_GNUC_UNUSED void
785 emit_set_arm_mode (MonoAotCompile *acfg)
787 emit_unset_mode (acfg);
788 fprintf (acfg->fp, ".code 32\n");
792 emit_code_bytes (MonoAotCompile *acfg, const guint8* buf, int size)
797 g_assert (size % 4 == 0);
798 emit_unset_mode (acfg);
799 for (i = 0; i < size; i += 4)
800 fprintf (acfg->fp, "%s 0x%x\n", acfg->inst_directive, *(guint32*)(buf + i));
802 emit_bytes (acfg, buf, size);
806 /* ARCHITECTURE SPECIFIC CODE */
808 #if defined(TARGET_X86) || defined(TARGET_AMD64) || defined(TARGET_ARM) || defined(TARGET_POWERPC) || defined(TARGET_ARM64)
809 #define EMIT_DWARF_INFO 1
812 #if defined(TARGET_ARM)
813 #define AOT_FUNC_ALIGNMENT 4
815 #define AOT_FUNC_ALIGNMENT 16
818 #if defined(TARGET_POWERPC64) && !defined(__mono_ilp32__)
819 #define PPC_LD_OP "ld"
820 #define PPC_LDX_OP "ldx"
822 #define PPC_LD_OP "lwz"
823 #define PPC_LDX_OP "lwzx"
827 #define AOT_TARGET_STR "AMD64"
832 #define AOT_TARGET_STR "ARM (MACH)"
834 #define AOT_TARGET_STR "ARM (!MACH)"
840 #define AOT_TARGET_STR "ARM64 (MACH)"
842 #define AOT_TARGET_STR "ARM64 (!MACH)"
846 #ifdef TARGET_POWERPC64
847 #ifdef __mono_ilp32__
848 #define AOT_TARGET_STR "POWERPC64 (mono ilp32)"
850 #define AOT_TARGET_STR "POWERPC64 (!mono ilp32)"
853 #ifdef TARGET_POWERPC
854 #ifdef __mono_ilp32__
855 #define AOT_TARGET_STR "POWERPC (mono ilp32)"
857 #define AOT_TARGET_STR "POWERPC (!mono ilp32)"
864 #define AOT_TARGET_STR "X86 (WIN32)"
865 #elif defined(__native_client_codegen__)
866 #define AOT_TARGET_STR "X86 (native client codegen)"
868 #define AOT_TARGET_STR "X86 (!native client codegen)"
872 #ifndef AOT_TARGET_STR
873 #define AOT_TARGET_STR ""
877 arch_init (MonoAotCompile *acfg)
879 acfg->llc_args = g_string_new ("");
880 acfg->as_args = g_string_new ("");
883 * The prefix LLVM likes to put in front of symbol names on darwin.
884 * The mach-os specs require this for globals, but LLVM puts them in front of all
885 * symbols. We need to handle this, since we need to refer to LLVM generated
888 acfg->llvm_label_prefix = "";
889 acfg->user_symbol_prefix = "";
891 #if defined(TARGET_X86)
892 g_string_append (acfg->llc_args, " -march=x86 -mattr=sse4.1");
895 #if defined(TARGET_AMD64)
896 g_string_append (acfg->llc_args, " -march=x86-64 -mattr=sse4.1");
898 acfg->align_pad_value = 0x90;
902 if (acfg->aot_opts.mtriple && strstr (acfg->aot_opts.mtriple, "darwin")) {
903 g_string_append (acfg->llc_args, "-mattr=+v6");
906 g_string_append (acfg->llc_args, " -mattr=+vfp2,-neon,+d16");
907 g_string_append (acfg->as_args, " -mfpu=vfp3");
909 g_string_append (acfg->llc_args, " -soft-float");
912 if (acfg->aot_opts.mtriple && strstr (acfg->aot_opts.mtriple, "thumb"))
913 acfg->thumb_mixed = TRUE;
915 if (acfg->aot_opts.mtriple)
916 mono_arch_set_target (acfg->aot_opts.mtriple);
920 acfg->inst_directive = ".inst";
921 if (acfg->aot_opts.mtriple)
922 mono_arch_set_target (acfg->aot_opts.mtriple);
926 acfg->user_symbol_prefix = "_";
927 acfg->llvm_label_prefix = "_";
928 acfg->inst_directive = ".word";
929 acfg->need_no_dead_strip = TRUE;
930 acfg->aot_opts.gnu_asm = TRUE;
933 #if defined(__linux__) && !defined(TARGET_ARM)
934 acfg->need_pt_gnu_stack = TRUE;
938 acfg->global_symbols = TRUE;
945 /* Load the contents of GOT_SLOT into dreg, clobbering ip0 */
947 arm64_emit_load_got_slot (MonoAotCompile *acfg, int dreg, int got_slot)
952 emit_unset_mode (acfg);
954 offset = (int)(got_slot * sizeof (gpointer));
956 /* clang's integrated assembler */
957 fprintf (acfg->fp, "adrp x16, %s@PAGE+%d\n", acfg->got_symbol, offset & 0xfffff000);
958 fprintf (acfg->fp, "add x16, x16, %s@PAGEOFF\n", acfg->got_symbol);
959 fprintf (acfg->fp, "ldr x%d, [x16, #%d]\n", dreg, offset & 0xfff);
962 fprintf (acfg->fp, "adrp x16, %s+%d\n", acfg->got_symbol, offset & 0xfffff000);
963 fprintf (acfg->fp, "add x16, x16, :lo12:%s\n", acfg->got_symbol);
964 fprintf (acfg->fp, "ldr x%d, [x16, %d]\n", dreg, offset & 0xfff);
969 arm64_emit_objc_selector_ref (MonoAotCompile *acfg, guint8 *code, int index, int *code_size)
974 emit_unset_mode (acfg);
977 reg = arm_get_ldr_lit_reg (code);
979 fprintf (acfg->fp, "adrp x%d, L_OBJC_SELECTOR_REFERENCES_%d@PAGE\n", reg, index);
980 fprintf (acfg->fp, "add x%d, x%d, L_OBJC_SELECTOR_REFERENCES_%d@PAGEOFF\n", reg, reg, index);
981 fprintf (acfg->fp, "ldr x%d, [x%d]\n", reg, reg);
987 arm64_emit_direct_call (MonoAotCompile *acfg, const char *target, gboolean external, gboolean thumb, MonoJumpInfo *ji, int *call_size)
990 emit_unset_mode (acfg);
991 if (ji && ji->relocation == MONO_R_ARM64_B) {
992 fprintf (acfg->fp, "b %s\n", target);
995 g_assert (ji->relocation == MONO_R_ARM64_BL);
996 fprintf (acfg->fp, "bl %s\n", target);
1002 arm64_emit_got_access (MonoAotCompile *acfg, guint8 *code, int got_slot, int *code_size)
1006 /* ldr rt, target */
1007 reg = arm_get_ldr_lit_reg (code);
1008 arm64_emit_load_got_slot (acfg, reg, got_slot);
1013 arm64_emit_plt_entry (MonoAotCompile *acfg, const char *got_symbol, int offset, int info_offset)
1015 arm64_emit_load_got_slot (acfg, ARMREG_R16, offset / sizeof (gpointer));
1016 fprintf (acfg->fp, "br x16\n");
1017 /* Used by mono_aot_get_plt_info_offset () */
1018 fprintf (acfg->fp, "%s %d\n", acfg->inst_directive, info_offset);
1022 arm64_emit_tramp_page_common_code (MonoAotCompile *acfg, int pagesize, int arg_reg, int *size)
1028 /* The common code */
1031 /* The trampoline address is in IP0 */
1032 arm_movzx (code, ARMREG_IP1, imm & 0xffff, 0);
1033 arm_movkx (code, ARMREG_IP1, (imm >> 16) & 0xffff, 16);
1034 /* Compute the data slot address */
1035 arm_subx (code, ARMREG_IP0, ARMREG_IP0, ARMREG_IP1);
1036 /* Trampoline argument */
1037 arm_ldrx (code, arg_reg, ARMREG_IP0, 0);
1039 arm_ldrx (code, ARMREG_IP0, ARMREG_IP0, 8);
1040 arm_brx (code, ARMREG_IP0);
1043 emit_code_bytes (acfg, buf, code - buf);
1049 arm64_emit_tramp_page_specific_code (MonoAotCompile *acfg, int pagesize, int common_tramp_size, int specific_tramp_size)
1055 count = (pagesize - common_tramp_size) / specific_tramp_size;
1056 for (i = 0; i < count; ++i) {
1058 arm_adrx (code, ARMREG_IP0, code);
1059 /* Branch to the generic code */
1060 arm_b (code, code - 4 - (i * specific_tramp_size) - common_tramp_size);
1061 /* This has to be 2 pointers long */
1064 g_assert (code - buf == specific_tramp_size);
1065 emit_code_bytes (acfg, buf, code - buf);
1070 arm64_emit_specific_trampoline_pages (MonoAotCompile *acfg)
1074 guint8 *labels [16];
1075 int common_tramp_size;
1076 int specific_tramp_size = 2 * 8;
1080 if (!acfg->aot_opts.use_trampolines_page)
1084 /* Have to match the target pagesize */
1087 pagesize = mono_pagesize ();
1089 acfg->tramp_page_size = pagesize;
1091 /* The specific trampolines */
1092 sprintf (symbol, "%sspecific_trampolines_page", acfg->user_symbol_prefix);
1093 emit_alignment (acfg, pagesize);
1094 emit_global (acfg, symbol, TRUE);
1095 emit_label (acfg, symbol);
1097 /* The common code */
1098 arm64_emit_tramp_page_common_code (acfg, pagesize, ARMREG_IP1, &common_tramp_size);
1099 acfg->tramp_page_code_offsets [MONO_AOT_TRAMP_SPECIFIC] = common_tramp_size;
1101 arm64_emit_tramp_page_specific_code (acfg, pagesize, common_tramp_size, specific_tramp_size);
1103 /* The rgctx trampolines */
1104 /* These are the same as the specific trampolines, but they load the argument into MONO_ARCH_RGCTX_REG */
1105 sprintf (symbol, "%srgctx_trampolines_page", acfg->user_symbol_prefix);
1106 emit_alignment (acfg, pagesize);
1107 emit_global (acfg, symbol, TRUE);
1108 emit_label (acfg, symbol);
1110 /* The common code */
1111 arm64_emit_tramp_page_common_code (acfg, pagesize, MONO_ARCH_RGCTX_REG, &common_tramp_size);
1112 acfg->tramp_page_code_offsets [MONO_AOT_TRAMP_STATIC_RGCTX] = common_tramp_size;
1114 arm64_emit_tramp_page_specific_code (acfg, pagesize, common_tramp_size, specific_tramp_size);
1116 /* The gsharedvt arg trampolines */
1117 /* These are the same as the specific trampolines */
1118 sprintf (symbol, "%sgsharedvt_arg_trampolines_page", acfg->user_symbol_prefix);
1119 emit_alignment (acfg, pagesize);
1120 emit_global (acfg, symbol, TRUE);
1121 emit_label (acfg, symbol);
1123 arm64_emit_tramp_page_common_code (acfg, pagesize, ARMREG_IP1, &common_tramp_size);
1124 acfg->tramp_page_code_offsets [MONO_AOT_TRAMP_GSHAREDVT_ARG] = common_tramp_size;
1126 arm64_emit_tramp_page_specific_code (acfg, pagesize, common_tramp_size, specific_tramp_size);
1128 /* The IMT trampolines */
1129 sprintf (symbol, "%simt_trampolines_page", acfg->user_symbol_prefix);
1130 emit_alignment (acfg, pagesize);
1131 emit_global (acfg, symbol, TRUE);
1132 emit_label (acfg, symbol);
1136 /* The trampoline address is in IP0 */
1137 arm_movzx (code, ARMREG_IP1, imm & 0xffff, 0);
1138 arm_movkx (code, ARMREG_IP1, (imm >> 16) & 0xffff, 16);
1139 /* Compute the data slot address */
1140 arm_subx (code, ARMREG_IP0, ARMREG_IP0, ARMREG_IP1);
1141 /* Trampoline argument */
1142 arm_ldrx (code, ARMREG_IP1, ARMREG_IP0, 0);
1144 /* Same as arch_emit_imt_thunk () */
1146 arm_ldrx (code, ARMREG_IP0, ARMREG_IP1, 0);
1147 arm_cmpx (code, ARMREG_IP0, MONO_ARCH_RGCTX_REG);
1149 arm_bcc (code, ARMCOND_EQ, 0);
1151 /* End-of-loop check */
1153 arm_cbzx (code, ARMREG_IP0, 0);
1156 arm_addx_imm (code, ARMREG_IP1, ARMREG_IP1, 2 * 8);
1157 arm_b (code, labels [0]);
1160 mono_arm_patch (labels [1], code, MONO_R_ARM64_BCC);
1161 /* Load vtable slot addr */
1162 arm_ldrx (code, ARMREG_IP0, ARMREG_IP1, 8);
1163 /* Load vtable slot */
1164 arm_ldrx (code, ARMREG_IP0, ARMREG_IP0, 0);
1165 arm_brx (code, ARMREG_IP0);
1168 mono_arm_patch (labels [2], code, MONO_R_ARM64_CBZ);
1169 /* Load fail addr */
1170 arm_ldrx (code, ARMREG_IP0, ARMREG_IP1, 8);
1171 arm_brx (code, ARMREG_IP0);
1173 emit_code_bytes (acfg, buf, code - buf);
1175 common_tramp_size = code - buf;
1176 acfg->tramp_page_code_offsets [MONO_AOT_TRAMP_IMT_THUNK] = common_tramp_size;
1178 arm64_emit_tramp_page_specific_code (acfg, pagesize, common_tramp_size, specific_tramp_size);
1182 arm64_emit_specific_trampoline (MonoAotCompile *acfg, int offset, int *tramp_size)
1184 /* Load argument from second GOT slot */
1185 arm64_emit_load_got_slot (acfg, ARMREG_R17, offset + 1);
1186 /* Load generic trampoline address from first GOT slot */
1187 arm64_emit_load_got_slot (acfg, ARMREG_R16, offset);
1188 fprintf (acfg->fp, "br x16\n");
1189 *tramp_size = 7 * 4;
1193 arm64_emit_unbox_trampoline (MonoAotCompile *acfg, MonoCompile *cfg, MonoMethod *method, const char *call_target)
1195 emit_unset_mode (acfg);
1196 fprintf (acfg->fp, "add x0, x0, %d\n", (int)(sizeof (MonoObject)));
1197 fprintf (acfg->fp, "b %s\n", call_target);
1201 arm64_emit_static_rgctx_trampoline (MonoAotCompile *acfg, int offset, int *tramp_size)
1203 /* Similar to the specific trampolines, but use the rgctx reg instead of ip1 */
1205 /* Load argument from first GOT slot */
1206 arm64_emit_load_got_slot (acfg, MONO_ARCH_RGCTX_REG, offset);
1207 /* Load generic trampoline address from second GOT slot */
1208 arm64_emit_load_got_slot (acfg, ARMREG_R16, offset + 1);
1209 fprintf (acfg->fp, "br x16\n");
1210 *tramp_size = 7 * 4;
1214 arm64_emit_imt_thunk (MonoAotCompile *acfg, int offset, int *tramp_size)
1217 guint8 *code, *labels [16];
1219 /* Load parameter from GOT slot into ip1 */
1220 arm64_emit_load_got_slot (acfg, ARMREG_R17, offset);
1224 arm_ldrx (code, ARMREG_IP0, ARMREG_IP1, 0);
1225 arm_cmpx (code, ARMREG_IP0, MONO_ARCH_RGCTX_REG);
1227 arm_bcc (code, ARMCOND_EQ, 0);
1229 /* End-of-loop check */
1231 arm_cbzx (code, ARMREG_IP0, 0);
1234 arm_addx_imm (code, ARMREG_IP1, ARMREG_IP1, 2 * 8);
1235 arm_b (code, labels [0]);
1238 mono_arm_patch (labels [1], code, MONO_R_ARM64_BCC);
1239 /* Load vtable slot addr */
1240 arm_ldrx (code, ARMREG_IP0, ARMREG_IP1, 8);
1241 /* Load vtable slot */
1242 arm_ldrx (code, ARMREG_IP0, ARMREG_IP0, 0);
1243 arm_brx (code, ARMREG_IP0);
1246 mono_arm_patch (labels [2], code, MONO_R_ARM64_CBZ);
1247 /* Load fail addr */
1248 arm_ldrx (code, ARMREG_IP0, ARMREG_IP1, 8);
1249 arm_brx (code, ARMREG_IP0);
1251 emit_code_bytes (acfg, buf, code - buf);
1253 *tramp_size = code - buf + (3 * 4);
1257 arm64_emit_gsharedvt_arg_trampoline (MonoAotCompile *acfg, int offset, int *tramp_size)
1259 /* Similar to the specific trampolines, but the address is in the second slot */
1260 /* Load argument from first GOT slot */
1261 arm64_emit_load_got_slot (acfg, ARMREG_R17, offset);
1262 /* Load generic trampoline address from second GOT slot */
1263 arm64_emit_load_got_slot (acfg, ARMREG_R16, offset + 1);
1264 fprintf (acfg->fp, "br x16\n");
1265 *tramp_size = 7 * 4;
1271 #ifdef MONO_ARCH_AOT_SUPPORTED
1273 * arch_emit_direct_call:
1275 * Emit a direct call to the symbol TARGET. CALL_SIZE is set to the size of the
1279 arch_emit_direct_call (MonoAotCompile *acfg, const char *target, gboolean external, gboolean thumb, MonoJumpInfo *ji, int *call_size)
1281 #if defined(TARGET_X86) || defined(TARGET_AMD64)
1282 /* Need to make sure this is exactly 5 bytes long */
1283 emit_unset_mode (acfg);
1284 fprintf (acfg->fp, "call %s\n", target);
1286 #elif defined(TARGET_ARM)
1287 emit_unset_mode (acfg);
1289 fprintf (acfg->fp, "blx %s\n", target);
1291 fprintf (acfg->fp, "bl %s\n", target);
1293 #elif defined(TARGET_ARM64)
1294 arm64_emit_direct_call (acfg, target, external, thumb, ji, call_size);
1295 #elif defined(TARGET_POWERPC)
1296 emit_unset_mode (acfg);
1297 fprintf (acfg->fp, "bl %s\n", target);
1300 g_assert_not_reached ();
1307 * - we use an approach similar to the x86 abi: reserve a register (r30) to hold
1309 * - The full-aot trampolines need access to the GOT of mscorlib, so we store
1310 * in in the 2. slot of every GOT, and require every method to place the GOT
1311 * address in r30, even when it doesn't access the GOT otherwise. This way,
1312 * the trampolines can compute the mscorlib GOT address by loading 4(r30).
1317 * PPC64 uses function descriptors which greatly complicate all code, since
1318 * these are used very inconsistently in the runtime. Some functions like
1319 * mono_compile_method () return ftn descriptors, while others like the
1320 * trampoline creation functions do not.
1321 * We assume that all GOT slots contain function descriptors, and create
1322 * descriptors in aot-runtime.c when needed.
1323 * The ppc64 abi uses r2 to hold the address of the TOC/GOT, which is loaded
1324 * from function descriptors, we could do the same, but it would require
1325 * rewriting all the ppc/aot code to handle function descriptors properly.
1326 * So instead, we use the same approach as on PPC32.
1327 * This is a horrible mess, but fixing it would probably lead to an even bigger
1333 * - similar to the PPC32 design, we reserve EBX to hold the GOT pointer.
1336 #ifdef MONO_ARCH_AOT_SUPPORTED
1338 * arch_emit_got_offset:
1340 * The memory pointed to by CODE should hold native code for computing the GOT
1341 * address (OP_LOAD_GOTADDR). Emit this code while patching it with the offset
1342 * between code and the GOT. CODE_SIZE is set to the number of bytes emitted.
1345 arch_emit_got_offset (MonoAotCompile *acfg, guint8 *code, int *code_size)
1347 #if defined(TARGET_POWERPC64)
1348 emit_unset_mode (acfg);
1350 * The ppc32 code doesn't seem to work on ppc64, the assembler complains about
1351 * unsupported relocations. So we store the got address into the .Lgot_addr
1352 * symbol which is in the text segment, compute its address, and load it.
1354 fprintf (acfg->fp, ".L%d:\n", acfg->label_generator);
1355 fprintf (acfg->fp, "lis 0, (.Lgot_addr + 4 - .L%d)@h\n", acfg->label_generator);
1356 fprintf (acfg->fp, "ori 0, 0, (.Lgot_addr + 4 - .L%d)@l\n", acfg->label_generator);
1357 fprintf (acfg->fp, "add 30, 30, 0\n");
1358 fprintf (acfg->fp, "%s 30, 0(30)\n", PPC_LD_OP);
1359 acfg->label_generator ++;
1361 #elif defined(TARGET_POWERPC)
1362 emit_unset_mode (acfg);
1363 fprintf (acfg->fp, ".L%d:\n", acfg->label_generator);
1364 fprintf (acfg->fp, "lis 0, (%s + 4 - .L%d)@h\n", acfg->got_symbol, acfg->label_generator);
1365 fprintf (acfg->fp, "ori 0, 0, (%s + 4 - .L%d)@l\n", acfg->got_symbol, acfg->label_generator);
1366 acfg->label_generator ++;
1369 guint32 offset = mono_arch_get_patch_offset (code);
1370 emit_bytes (acfg, code, offset);
1371 emit_symbol_diff (acfg, acfg->got_symbol, ".", offset);
1373 *code_size = offset + 4;
1378 * arch_emit_got_access:
1380 * The memory pointed to by CODE should hold native code for loading a GOT
1381 * slot (OP_AOTCONST/OP_GOT_ENTRY). Emit this code while patching it so it accesses the
1382 * GOT slot GOT_SLOT. CODE_SIZE is set to the number of bytes emitted.
1385 arch_emit_got_access (MonoAotCompile *acfg, const char *got_symbol, guint8 *code, int got_slot, int *code_size)
1388 /* mov reg, got+offset(%rip) */
1390 /* The GOT symbol is in the LLVM module, the clang assembler has problems emitting symbol diffs for it */
1394 /* Decode reg, see amd64_mov_reg_membase () */
1395 rex_r = code [0] & AMD64_REX_R;
1396 g_assert (code [0] == 0x49 + rex_r);
1397 g_assert (code [1] == 0x8b);
1398 dreg = ((code [2] >> 3) & 0x7) + (rex_r ? 8 : 0);
1400 emit_unset_mode (acfg);
1401 fprintf (acfg->fp, "mov %s+%d(%%rip), %s\n", got_symbol, (unsigned int) ((got_slot * sizeof (gpointer))), mono_arch_regname (dreg));
1404 emit_bytes (acfg, code, mono_arch_get_patch_offset (code));
1405 emit_symbol_diff (acfg, got_symbol, ".", (unsigned int) ((got_slot * sizeof (gpointer)) - 4));
1406 *code_size = mono_arch_get_patch_offset (code) + 4;
1408 #elif defined(TARGET_X86)
1409 emit_bytes (acfg, code, mono_arch_get_patch_offset (code));
1410 emit_int32 (acfg, (unsigned int) ((got_slot * sizeof (gpointer))));
1411 *code_size = mono_arch_get_patch_offset (code) + 4;
1412 #elif defined(TARGET_ARM)
1413 emit_bytes (acfg, code, mono_arch_get_patch_offset (code));
1414 emit_symbol_diff (acfg, got_symbol, ".", (unsigned int) ((got_slot * sizeof (gpointer))) - 12);
1415 *code_size = mono_arch_get_patch_offset (code) + 4;
1416 #elif defined(TARGET_ARM64)
1417 emit_bytes (acfg, code, mono_arch_get_patch_offset (code));
1418 arm64_emit_got_access (acfg, code, got_slot, code_size);
1419 #elif defined(TARGET_POWERPC)
1424 emit_bytes (acfg, code, mono_arch_get_patch_offset (code));
1426 ppc_load32 (code, ppc_r0, got_slot * sizeof (gpointer));
1427 g_assert (code - buf == 8);
1428 emit_bytes (acfg, buf, code - buf);
1429 *code_size = code - buf;
1432 g_assert_not_reached ();
1438 #ifdef MONO_ARCH_AOT_SUPPORTED
1440 * arch_emit_objc_selector_ref:
1442 * Emit the implementation of OP_OBJC_GET_SELECTOR, which itself implements @selector(foo:) in objective-c.
1445 arch_emit_objc_selector_ref (MonoAotCompile *acfg, guint8 *code, int index, int *code_size)
1447 #if defined(TARGET_ARM)
1448 char symbol1 [MAX_SYMBOL_SIZE];
1449 char symbol2 [MAX_SYMBOL_SIZE];
1450 int lindex = acfg->objc_selector_index_2 ++;
1452 /* Emit ldr.imm/b */
1453 emit_bytes (acfg, code, 8);
1455 sprintf (symbol1, "L_OBJC_SELECTOR_%d", lindex);
1456 sprintf (symbol2, "L_OBJC_SELECTOR_REFERENCES_%d", index);
1458 emit_label (acfg, symbol1);
1459 mono_img_writer_emit_unset_mode (acfg->w);
1460 fprintf (acfg->fp, ".long %s-(%s+12)", symbol2, symbol1);
1463 #elif defined(TARGET_ARM64)
1464 arm64_emit_objc_selector_ref (acfg, code, index, code_size);
1466 g_assert_not_reached ();
1472 * arch_emit_plt_entry:
1474 * Emit code for the PLT entry.
1475 * The plt entry should look like this:
1476 * <indirect jump to GOT_SYMBOL + OFFSET>
1477 * <INFO_OFFSET embedded into the instruction stream>
1480 arch_emit_plt_entry (MonoAotCompile *acfg, const char *got_symbol, int offset, int info_offset)
1482 #if defined(TARGET_X86)
1483 /* jmp *<offset>(%ebx) */
1484 emit_byte (acfg, 0xff);
1485 emit_byte (acfg, 0xa3);
1486 emit_int32 (acfg, offset);
1487 /* Used by mono_aot_get_plt_info_offset */
1488 emit_int32 (acfg, info_offset);
1489 #elif defined(TARGET_AMD64)
1490 emit_unset_mode (acfg);
1491 fprintf (acfg->fp, "jmp *%s+%d(%%rip)\n", got_symbol, offset);
1492 /* Used by mono_aot_get_plt_info_offset */
1493 emit_int32 (acfg, info_offset);
1494 acfg->stats.plt_size += 10;
1495 #elif defined(TARGET_ARM)
1500 ARM_LDR_IMM (code, ARMREG_IP, ARMREG_PC, 0);
1501 ARM_LDR_REG_REG (code, ARMREG_PC, ARMREG_PC, ARMREG_IP);
1502 emit_bytes (acfg, buf, code - buf);
1503 emit_symbol_diff (acfg, got_symbol, ".", offset - 4);
1504 /* Used by mono_aot_get_plt_info_offset */
1505 emit_int32 (acfg, info_offset);
1506 #elif defined(TARGET_ARM64)
1507 arm64_emit_plt_entry (acfg, got_symbol, offset, info_offset);
1508 #elif defined(TARGET_POWERPC)
1509 /* The GOT address is guaranteed to be in r30 by OP_LOAD_GOTADDR */
1510 emit_unset_mode (acfg);
1511 fprintf (acfg->fp, "lis 11, %d@h\n", offset);
1512 fprintf (acfg->fp, "ori 11, 11, %d@l\n", offset);
1513 fprintf (acfg->fp, "add 11, 11, 30\n");
1514 fprintf (acfg->fp, "%s 11, 0(11)\n", PPC_LD_OP);
1515 #ifdef PPC_USES_FUNCTION_DESCRIPTOR
1516 fprintf (acfg->fp, "%s 2, %d(11)\n", PPC_LD_OP, (int)sizeof (gpointer));
1517 fprintf (acfg->fp, "%s 11, 0(11)\n", PPC_LD_OP);
1519 fprintf (acfg->fp, "mtctr 11\n");
1520 fprintf (acfg->fp, "bctr\n");
1521 emit_int32 (acfg, info_offset);
1523 g_assert_not_reached ();
1528 * arch_emit_llvm_plt_entry:
1530 * Same as arch_emit_plt_entry, but handles calls from LLVM generated code.
1531 * This is only needed on arm to handle thumb interop.
1534 arch_emit_llvm_plt_entry (MonoAotCompile *acfg, const char *got_symbol, int offset, int info_offset)
1536 #if defined(TARGET_ARM)
1537 /* LLVM calls the PLT entries using bl, so these have to be thumb2 */
1538 /* The caller already transitioned to thumb */
1539 /* The code below should be 12 bytes long */
1540 /* clang has trouble encoding these instructions, so emit the binary */
1542 fprintf (acfg->fp, "ldr ip, [pc, #8]\n");
1543 /* thumb can't encode ld pc, [pc, ip] */
1544 fprintf (acfg->fp, "add ip, pc, ip\n");
1545 fprintf (acfg->fp, "ldr ip, [ip, #0]\n");
1546 fprintf (acfg->fp, "bx ip\n");
1548 emit_set_thumb_mode (acfg);
1549 fprintf (acfg->fp, ".4byte 0xc008f8df\n");
1550 fprintf (acfg->fp, ".2byte 0x44fc\n");
1551 fprintf (acfg->fp, ".4byte 0xc000f8dc\n");
1552 fprintf (acfg->fp, ".2byte 0x4760\n");
1553 emit_symbol_diff (acfg, got_symbol, ".", offset + 4);
1554 emit_int32 (acfg, info_offset);
1555 emit_unset_mode (acfg);
1556 emit_set_arm_mode (acfg);
1558 g_assert_not_reached ();
1562 /* Save unwind_info in the module and emit the offset to the information at symbol */
1563 static void save_unwind_info (MonoAotCompile *acfg, char *symbol, GSList *unwind_ops)
1565 guint32 uw_offset, encoded_len;
1568 emit_section_change (acfg, RODATA_SECT, 0);
1569 emit_global (acfg, symbol, FALSE);
1570 emit_label (acfg, symbol);
1572 encoded = mono_unwind_ops_encode (unwind_ops, &encoded_len);
1573 uw_offset = get_unwind_info_offset (acfg, encoded, encoded_len);
1575 emit_int32 (acfg, uw_offset);
1579 * arch_emit_specific_trampoline_pages:
1581 * Emits a page full of trampolines: each trampoline uses its own address to
1582 * lookup both the generic trampoline code and the data argument.
1583 * This page can be remapped in process multiple times so we can get an
1584 * unlimited number of trampolines.
1585 * Specifically this implementation uses the following trick: two memory pages
1586 * are allocated, with the first containing the data and the second containing the trampolines.
1587 * To reduce trampoline size, each trampoline jumps at the start of the page where a common
1588 * implementation does all the lifting.
1589 * Note that the ARM single trampoline size is 8 bytes, exactly like the data that needs to be stored
1590 * on the arm 32 bit system.
1593 arch_emit_specific_trampoline_pages (MonoAotCompile *acfg)
1595 #if defined(TARGET_ARM)
1598 guint8 *loop_start, *loop_branch_back, *loop_end_check, *imt_found_check;
1600 int pagesize = MONO_AOT_TRAMP_PAGE_SIZE;
1601 GSList *unwind_ops = NULL;
1602 #define COMMON_TRAMP_SIZE 16
1603 int count = (pagesize - COMMON_TRAMP_SIZE) / 8;
1604 int imm8, rot_amount;
1607 if (!acfg->aot_opts.use_trampolines_page)
1610 acfg->tramp_page_size = pagesize;
1612 sprintf (symbol, "%sspecific_trampolines_page", acfg->user_symbol_prefix);
1613 emit_alignment (acfg, pagesize);
1614 emit_global (acfg, symbol, TRUE);
1615 emit_label (acfg, symbol);
1617 /* emit the generic code first, the trampoline address + 8 is in the lr register */
1619 imm8 = mono_arm_is_rotated_imm8 (pagesize, &rot_amount);
1620 ARM_SUB_REG_IMM (code, ARMREG_LR, ARMREG_LR, imm8, rot_amount);
1621 ARM_LDR_IMM (code, ARMREG_R1, ARMREG_LR, -8);
1622 ARM_LDR_IMM (code, ARMREG_PC, ARMREG_LR, -4);
1624 g_assert (code - buf == COMMON_TRAMP_SIZE);
1627 emit_bytes (acfg, buf, code - buf);
1629 for (i = 0; i < count; ++i) {
1631 ARM_PUSH (code, 0x5fff);
1633 arm_patch (code - 4, code - COMMON_TRAMP_SIZE - 8 * (i + 1));
1634 g_assert (code - buf == 8);
1635 emit_bytes (acfg, buf, code - buf);
1638 /* now the rgctx trampolines: each specific trampolines puts in the ip register
1639 * the instruction pointer address, so the generic trampoline at the start of the page
1640 * subtracts 4096 to get to the data page and loads the values
1641 * We again fit the generic trampiline in 16 bytes.
1643 sprintf (symbol, "%srgctx_trampolines_page", acfg->user_symbol_prefix);
1644 emit_global (acfg, symbol, TRUE);
1645 emit_label (acfg, symbol);
1647 imm8 = mono_arm_is_rotated_imm8 (pagesize, &rot_amount);
1648 ARM_SUB_REG_IMM (code, ARMREG_IP, ARMREG_IP, imm8, rot_amount);
1649 ARM_LDR_IMM (code, MONO_ARCH_RGCTX_REG, ARMREG_IP, -8);
1650 ARM_LDR_IMM (code, ARMREG_PC, ARMREG_IP, -4);
1652 g_assert (code - buf == COMMON_TRAMP_SIZE);
1655 emit_bytes (acfg, buf, code - buf);
1657 for (i = 0; i < count; ++i) {
1659 ARM_MOV_REG_REG (code, ARMREG_IP, ARMREG_PC);
1661 arm_patch (code - 4, code - COMMON_TRAMP_SIZE - 8 * (i + 1));
1662 g_assert (code - buf == 8);
1663 emit_bytes (acfg, buf, code - buf);
1667 * gsharedvt arg trampolines: see arch_emit_gsharedvt_arg_trampoline ()
1669 sprintf (symbol, "%sgsharedvt_arg_trampolines_page", acfg->user_symbol_prefix);
1670 emit_global (acfg, symbol, TRUE);
1671 emit_label (acfg, symbol);
1673 ARM_PUSH (code, (1 << ARMREG_R0) | (1 << ARMREG_R1) | (1 << ARMREG_R2) | (1 << ARMREG_R3));
1674 imm8 = mono_arm_is_rotated_imm8 (pagesize, &rot_amount);
1675 ARM_SUB_REG_IMM (code, ARMREG_IP, ARMREG_IP, imm8, rot_amount);
1676 ARM_LDR_IMM (code, ARMREG_R0, ARMREG_IP, -8);
1677 ARM_LDR_IMM (code, ARMREG_PC, ARMREG_IP, -4);
1678 g_assert (code - buf == COMMON_TRAMP_SIZE);
1680 emit_bytes (acfg, buf, code - buf);
1682 for (i = 0; i < count; ++i) {
1684 ARM_MOV_REG_REG (code, ARMREG_IP, ARMREG_PC);
1686 arm_patch (code - 4, code - COMMON_TRAMP_SIZE - 8 * (i + 1));
1687 g_assert (code - buf == 8);
1688 emit_bytes (acfg, buf, code - buf);
1691 /* now the imt trampolines: each specific trampolines puts in the ip register
1692 * the instruction pointer address, so the generic trampoline at the start of the page
1693 * subtracts 4096 to get to the data page and loads the values
1695 #define IMT_TRAMP_SIZE 72
1696 sprintf (symbol, "%simt_trampolines_page", acfg->user_symbol_prefix);
1697 emit_global (acfg, symbol, TRUE);
1698 emit_label (acfg, symbol);
1700 /* Need at least two free registers, plus a slot for storing the pc */
1701 ARM_PUSH (code, (1 << ARMREG_R0)|(1 << ARMREG_R1)|(1 << ARMREG_R2));
1703 imm8 = mono_arm_is_rotated_imm8 (pagesize, &rot_amount);
1704 ARM_SUB_REG_IMM (code, ARMREG_IP, ARMREG_IP, imm8, rot_amount);
1705 ARM_LDR_IMM (code, ARMREG_R0, ARMREG_IP, -8);
1707 /* The IMT method is in v5, r0 has the imt array address */
1710 ARM_LDR_IMM (code, ARMREG_R1, ARMREG_R0, 0);
1711 ARM_CMP_REG_REG (code, ARMREG_R1, ARMREG_V5);
1712 imt_found_check = code;
1713 ARM_B_COND (code, ARMCOND_EQ, 0);
1715 /* End-of-loop check */
1716 ARM_CMP_REG_IMM (code, ARMREG_R1, 0, 0);
1717 loop_end_check = code;
1718 ARM_B_COND (code, ARMCOND_EQ, 0);
1721 ARM_ADD_REG_IMM8 (code, ARMREG_R0, ARMREG_R0, sizeof (gpointer) * 2);
1722 loop_branch_back = code;
1724 arm_patch (loop_branch_back, loop_start);
1727 arm_patch (imt_found_check, code);
1728 ARM_LDR_IMM (code, ARMREG_R0, ARMREG_R0, 4);
1729 ARM_LDR_IMM (code, ARMREG_R0, ARMREG_R0, 0);
1730 /* Save it to the third stack slot */
1731 ARM_STR_IMM (code, ARMREG_R0, ARMREG_SP, 8);
1732 /* Restore the registers and branch */
1733 ARM_POP (code, (1 << ARMREG_R0)|(1 << ARMREG_R1)|(1 << ARMREG_PC));
1736 arm_patch (loop_end_check, code);
1737 ARM_LDR_IMM (code, ARMREG_R0, ARMREG_R0, 4);
1738 ARM_STR_IMM (code, ARMREG_R0, ARMREG_SP, 8);
1739 ARM_POP (code, (1 << ARMREG_R0)|(1 << ARMREG_R1)|(1 << ARMREG_PC));
1743 g_assert (code - buf == IMT_TRAMP_SIZE);
1744 emit_bytes (acfg, buf, code - buf);
1746 for (i = 0; i < count; ++i) {
1748 ARM_MOV_REG_REG (code, ARMREG_IP, ARMREG_PC);
1750 arm_patch (code - 4, code - IMT_TRAMP_SIZE - 8 * (i + 1));
1751 g_assert (code - buf == 8);
1752 emit_bytes (acfg, buf, code - buf);
1755 acfg->tramp_page_code_offsets [MONO_AOT_TRAMP_SPECIFIC] = 16;
1756 acfg->tramp_page_code_offsets [MONO_AOT_TRAMP_STATIC_RGCTX] = 16;
1757 acfg->tramp_page_code_offsets [MONO_AOT_TRAMP_IMT_THUNK] = 72;
1758 acfg->tramp_page_code_offsets [MONO_AOT_TRAMP_GSHAREDVT_ARG] = 16;
1760 /* Unwind info for specifc trampolines */
1761 sprintf (symbol, "%sspecific_trampolines_page_gen_p", acfg->user_symbol_prefix);
1762 /* We unwind to the original caller, from the stack, since lr is clobbered */
1763 mono_add_unwind_op_def_cfa (unwind_ops, 0, 0, ARMREG_SP, 14 * sizeof (mgreg_t));
1764 mono_add_unwind_op_offset (unwind_ops, 0, 0, ARMREG_LR, -4);
1765 save_unwind_info (acfg, symbol, unwind_ops);
1766 mono_free_unwind_info (unwind_ops);
1768 sprintf (symbol, "%sspecific_trampolines_page_sp_p", acfg->user_symbol_prefix);
1769 mono_add_unwind_op_def_cfa (unwind_ops, 0, 0, ARMREG_SP, 0);
1770 mono_add_unwind_op_def_cfa_offset (unwind_ops, 4, 0, 14 * sizeof (mgreg_t));
1771 save_unwind_info (acfg, symbol, unwind_ops);
1772 mono_free_unwind_info (unwind_ops);
1774 /* Unwind info for rgctx trampolines */
1775 sprintf (symbol, "%srgctx_trampolines_page_gen_p", acfg->user_symbol_prefix);
1776 mono_add_unwind_op_def_cfa (unwind_ops, 0, 0, ARMREG_SP, 0);
1777 save_unwind_info (acfg, symbol, unwind_ops);
1779 sprintf (symbol, "%srgctx_trampolines_page_sp_p", acfg->user_symbol_prefix);
1780 save_unwind_info (acfg, symbol, unwind_ops);
1781 mono_free_unwind_info (unwind_ops);
1783 /* Unwind info for gsharedvt trampolines */
1784 sprintf (symbol, "%sgsharedvt_trampolines_page_gen_p", acfg->user_symbol_prefix);
1785 mono_add_unwind_op_def_cfa (unwind_ops, 0, 0, ARMREG_SP, 0);
1786 mono_add_unwind_op_def_cfa_offset (unwind_ops, 4, 0, 4 * sizeof (mgreg_t));
1787 save_unwind_info (acfg, symbol, unwind_ops);
1788 mono_free_unwind_info (unwind_ops);
1790 sprintf (symbol, "%sgsharedvt_trampolines_page_sp_p", acfg->user_symbol_prefix);
1791 mono_add_unwind_op_def_cfa (unwind_ops, 0, 0, ARMREG_SP, 0);
1792 save_unwind_info (acfg, symbol, unwind_ops);
1793 mono_free_unwind_info (unwind_ops);
1795 /* Unwind info for imt trampolines */
1796 sprintf (symbol, "%simt_trampolines_page_gen_p", acfg->user_symbol_prefix);
1797 mono_add_unwind_op_def_cfa (unwind_ops, 0, 0, ARMREG_SP, 0);
1798 mono_add_unwind_op_def_cfa_offset (unwind_ops, 4, 0, 3 * sizeof (mgreg_t));
1799 save_unwind_info (acfg, symbol, unwind_ops);
1800 mono_free_unwind_info (unwind_ops);
1802 sprintf (symbol, "%simt_trampolines_page_sp_p", acfg->user_symbol_prefix);
1803 mono_add_unwind_op_def_cfa (unwind_ops, 0, 0, ARMREG_SP, 0);
1804 save_unwind_info (acfg, symbol, unwind_ops);
1805 mono_free_unwind_info (unwind_ops);
1806 #elif defined(TARGET_ARM64)
1807 arm64_emit_specific_trampoline_pages (acfg);
1812 * arch_emit_specific_trampoline:
1814 * Emit code for a specific trampoline. OFFSET is the offset of the first of
1815 * two GOT slots which contain the generic trampoline address and the trampoline
1816 * argument. TRAMP_SIZE is set to the size of the emitted trampoline.
1819 arch_emit_specific_trampoline (MonoAotCompile *acfg, int offset, int *tramp_size)
1822 * The trampolines created here are variations of the specific
1823 * trampolines created in mono_arch_create_specific_trampoline (). The
1825 * - the generic trampoline address is taken from a got slot.
1826 * - the offset of the got slot where the trampoline argument is stored
1827 * is embedded in the instruction stream, and the generic trampoline
1828 * can load the argument by loading the offset, adding it to the
1829 * address of the trampoline to get the address of the got slot, and
1830 * loading the argument from there.
1831 * - all the trampolines should be of the same length.
1833 #if defined(TARGET_AMD64)
1834 /* This should be exactly 8 bytes long */
1836 /* call *<offset>(%rip) */
1838 emit_unset_mode (acfg);
1839 fprintf (acfg->fp, "call *%s+%d(%%rip)\n", acfg->got_symbol, (int)(offset * sizeof (gpointer)));
1840 emit_zero_bytes (acfg, 2);
1842 emit_byte (acfg, '\x41');
1843 emit_byte (acfg, '\xff');
1844 emit_byte (acfg, '\x15');
1845 emit_symbol_diff (acfg, acfg->got_symbol, ".", (offset * sizeof (gpointer)) - 4);
1846 emit_zero_bytes (acfg, 1);
1848 #elif defined(TARGET_ARM)
1852 /* This should be exactly 20 bytes long */
1855 ARM_PUSH (code, 0x5fff);
1856 ARM_LDR_IMM (code, ARMREG_R1, ARMREG_PC, 4);
1857 /* Load the value from the GOT */
1858 ARM_LDR_REG_REG (code, ARMREG_R1, ARMREG_PC, ARMREG_R1);
1860 ARM_BLX_REG (code, ARMREG_R1);
1862 g_assert (code - buf == 16);
1865 emit_bytes (acfg, buf, code - buf);
1867 * Only one offset is needed, since the second one would be equal to the
1870 emit_symbol_diff (acfg, acfg->got_symbol, ".", (offset * sizeof (gpointer)) - 4 + 4);
1871 //emit_symbol_diff (acfg, acfg->got_symbol, ".", ((offset + 1) * sizeof (gpointer)) - 4 + 8);
1872 #elif defined(TARGET_ARM64)
1873 arm64_emit_specific_trampoline (acfg, offset, tramp_size);
1874 #elif defined(TARGET_POWERPC)
1882 * PPC has no ip relative addressing, so we need to compute the address
1883 * of the mscorlib got. That is slow and complex, so instead, we store it
1884 * in the second got slot of every aot image. The caller already computed
1885 * the address of its got and placed it into r30.
1887 emit_unset_mode (acfg);
1888 /* Load mscorlib got address */
1889 fprintf (acfg->fp, "%s 0, %d(30)\n", PPC_LD_OP, (int)sizeof (gpointer));
1890 /* Load generic trampoline address */
1891 fprintf (acfg->fp, "lis 11, %d@h\n", (int)(offset * sizeof (gpointer)));
1892 fprintf (acfg->fp, "ori 11, 11, %d@l\n", (int)(offset * sizeof (gpointer)));
1893 fprintf (acfg->fp, "%s 11, 11, 0\n", PPC_LDX_OP);
1894 #ifdef PPC_USES_FUNCTION_DESCRIPTOR
1895 fprintf (acfg->fp, "%s 11, 0(11)\n", PPC_LD_OP);
1897 fprintf (acfg->fp, "mtctr 11\n");
1898 /* Load trampoline argument */
1899 /* On ppc, we pass it normally to the generic trampoline */
1900 fprintf (acfg->fp, "lis 11, %d@h\n", (int)((offset + 1) * sizeof (gpointer)));
1901 fprintf (acfg->fp, "ori 11, 11, %d@l\n", (int)((offset + 1) * sizeof (gpointer)));
1902 fprintf (acfg->fp, "%s 0, 11, 0\n", PPC_LDX_OP);
1903 /* Branch to generic trampoline */
1904 fprintf (acfg->fp, "bctr\n");
1906 #ifdef PPC_USES_FUNCTION_DESCRIPTOR
1907 *tramp_size = 10 * 4;
1909 *tramp_size = 9 * 4;
1911 #elif defined(TARGET_X86)
1915 /* Similar to the PPC code above */
1917 /* FIXME: Could this clobber the register needed by get_vcall_slot () ? */
1920 /* Load mscorlib got address */
1921 x86_mov_reg_membase (code, X86_ECX, MONO_ARCH_GOT_REG, sizeof (gpointer), 4);
1922 /* Push trampoline argument */
1923 x86_push_membase (code, X86_ECX, (offset + 1) * sizeof (gpointer));
1924 /* Load generic trampoline address */
1925 x86_mov_reg_membase (code, X86_ECX, X86_ECX, offset * sizeof (gpointer), 4);
1926 /* Branch to generic trampoline */
1927 x86_jump_reg (code, X86_ECX);
1929 emit_bytes (acfg, buf, code - buf);
1932 g_assert (code - buf == *tramp_size);
1934 g_assert_not_reached ();
1939 * arch_emit_unbox_trampoline:
1941 * Emit code for the unbox trampoline for METHOD used in the full-aot case.
1942 * CALL_TARGET is the symbol pointing to the native code of METHOD.
1945 arch_emit_unbox_trampoline (MonoAotCompile *acfg, MonoCompile *cfg, MonoMethod *method, const char *call_target)
1947 #if defined(TARGET_AMD64)
1952 this_reg = mono_arch_get_this_arg_reg (NULL);
1954 amd64_alu_reg_imm (code, X86_ADD, this_reg, sizeof (MonoObject));
1956 emit_bytes (acfg, buf, code - buf);
1959 emit_unset_mode (acfg);
1960 fprintf (acfg->fp, "jmp %s\n", call_target);
1962 emit_byte (acfg, '\xe9');
1963 emit_symbol_diff (acfg, call_target, ".", -4);
1965 #elif defined(TARGET_X86)
1972 x86_alu_membase_imm (code, X86_ADD, X86_ESP, this_pos, sizeof (MonoObject));
1974 emit_bytes (acfg, buf, code - buf);
1977 emit_byte (acfg, '\xe9');
1978 emit_symbol_diff (acfg, call_target, ".", -4);
1979 #elif defined(TARGET_ARM)
1983 if (acfg->thumb_mixed && cfg->compile_llvm) {
1984 fprintf (acfg->fp, "add r0, r0, #%d\n", (int)sizeof (MonoObject));
1985 fprintf (acfg->fp, "b %s\n", call_target);
1986 fprintf (acfg->fp, ".arm\n");
1987 fprintf (acfg->fp, ".align 2\n");
1993 ARM_ADD_REG_IMM8 (code, ARMREG_R0, ARMREG_R0, sizeof (MonoObject));
1995 emit_bytes (acfg, buf, code - buf);
1996 /* jump to method */
1997 if (acfg->thumb_mixed && cfg->compile_llvm)
1998 fprintf (acfg->fp, "\n\tbx %s\n", call_target);
2000 fprintf (acfg->fp, "\n\tb %s\n", call_target);
2001 #elif defined(TARGET_ARM64)
2002 arm64_emit_unbox_trampoline (acfg, cfg, method, call_target);
2003 #elif defined(TARGET_POWERPC)
2006 fprintf (acfg->fp, "\n\taddi %d, %d, %d\n", this_pos, this_pos, (int)sizeof (MonoObject));
2007 fprintf (acfg->fp, "\n\tb %s\n", call_target);
2009 g_assert_not_reached ();
2014 * arch_emit_static_rgctx_trampoline:
2016 * Emit code for a static rgctx trampoline. OFFSET is the offset of the first of
2017 * two GOT slots which contain the rgctx argument, and the method to jump to.
2018 * TRAMP_SIZE is set to the size of the emitted trampoline.
2019 * These kinds of trampolines cannot be enumerated statically, since there could
2020 * be one trampoline per method instantiation, so we emit the same code for all
2021 * trampolines, and parameterize them using two GOT slots.
2024 arch_emit_static_rgctx_trampoline (MonoAotCompile *acfg, int offset, int *tramp_size)
2026 #if defined(TARGET_AMD64)
2027 /* This should be exactly 13 bytes long */
2031 emit_unset_mode (acfg);
2032 fprintf (acfg->fp, "mov %s+%d(%%rip), %%r10\n", acfg->got_symbol, (int)(offset * sizeof (gpointer)));
2033 fprintf (acfg->fp, "jmp *%s+%d(%%rip)\n", acfg->got_symbol, (int)((offset + 1) * sizeof (gpointer)));
2035 /* mov <OFFSET>(%rip), %r10 */
2036 emit_byte (acfg, '\x4d');
2037 emit_byte (acfg, '\x8b');
2038 emit_byte (acfg, '\x15');
2039 emit_symbol_diff (acfg, acfg->got_symbol, ".", (offset * sizeof (gpointer)) - 4);
2041 /* jmp *<offset>(%rip) */
2042 emit_byte (acfg, '\xff');
2043 emit_byte (acfg, '\x25');
2044 emit_symbol_diff (acfg, acfg->got_symbol, ".", ((offset + 1) * sizeof (gpointer)) - 4);
2046 #elif defined(TARGET_ARM)
2050 /* This should be exactly 24 bytes long */
2053 /* Load rgctx value */
2054 ARM_LDR_IMM (code, ARMREG_IP, ARMREG_PC, 8);
2055 ARM_LDR_REG_REG (code, MONO_ARCH_RGCTX_REG, ARMREG_PC, ARMREG_IP);
2056 /* Load branch addr + branch */
2057 ARM_LDR_IMM (code, ARMREG_IP, ARMREG_PC, 4);
2058 ARM_LDR_REG_REG (code, ARMREG_PC, ARMREG_PC, ARMREG_IP);
2060 g_assert (code - buf == 16);
2063 emit_bytes (acfg, buf, code - buf);
2064 emit_symbol_diff (acfg, acfg->got_symbol, ".", (offset * sizeof (gpointer)) - 4 + 8);
2065 emit_symbol_diff (acfg, acfg->got_symbol, ".", ((offset + 1) * sizeof (gpointer)) - 4 + 4);
2066 #elif defined(TARGET_ARM64)
2067 arm64_emit_static_rgctx_trampoline (acfg, offset, tramp_size);
2068 #elif defined(TARGET_POWERPC)
2076 * PPC has no ip relative addressing, so we need to compute the address
2077 * of the mscorlib got. That is slow and complex, so instead, we store it
2078 * in the second got slot of every aot image. The caller already computed
2079 * the address of its got and placed it into r30.
2081 emit_unset_mode (acfg);
2082 /* Load mscorlib got address */
2083 fprintf (acfg->fp, "%s 0, %d(30)\n", PPC_LD_OP, (int)sizeof (gpointer));
2085 fprintf (acfg->fp, "lis 11, %d@h\n", (int)(offset * sizeof (gpointer)));
2086 fprintf (acfg->fp, "ori 11, 11, %d@l\n", (int)(offset * sizeof (gpointer)));
2087 fprintf (acfg->fp, "%s %d, 11, 0\n", PPC_LDX_OP, MONO_ARCH_RGCTX_REG);
2088 /* Load target address */
2089 fprintf (acfg->fp, "lis 11, %d@h\n", (int)((offset + 1) * sizeof (gpointer)));
2090 fprintf (acfg->fp, "ori 11, 11, %d@l\n", (int)((offset + 1) * sizeof (gpointer)));
2091 fprintf (acfg->fp, "%s 11, 11, 0\n", PPC_LDX_OP);
2092 #ifdef PPC_USES_FUNCTION_DESCRIPTOR
2093 fprintf (acfg->fp, "%s 2, %d(11)\n", PPC_LD_OP, (int)sizeof (gpointer));
2094 fprintf (acfg->fp, "%s 11, 0(11)\n", PPC_LD_OP);
2096 fprintf (acfg->fp, "mtctr 11\n");
2097 /* Branch to the target address */
2098 fprintf (acfg->fp, "bctr\n");
2100 #ifdef PPC_USES_FUNCTION_DESCRIPTOR
2101 *tramp_size = 11 * 4;
2103 *tramp_size = 9 * 4;
2106 #elif defined(TARGET_X86)
2110 /* Similar to the PPC code above */
2112 g_assert (MONO_ARCH_RGCTX_REG != X86_ECX);
2115 /* Load mscorlib got address */
2116 x86_mov_reg_membase (code, X86_ECX, MONO_ARCH_GOT_REG, sizeof (gpointer), 4);
2118 x86_mov_reg_membase (code, MONO_ARCH_RGCTX_REG, X86_ECX, offset * sizeof (gpointer), 4);
2119 /* Branch to the target address */
2120 x86_jump_membase (code, X86_ECX, (offset + 1) * sizeof (gpointer));
2122 emit_bytes (acfg, buf, code - buf);
2125 g_assert (code - buf == *tramp_size);
2127 g_assert_not_reached ();
2132 * arch_emit_imt_thunk:
2134 * Emit an IMT thunk usable in full-aot mode. The thunk uses 1 got slot which
2135 * points to an array of pointer pairs. The pairs of the form [key, ptr], where
2136 * key is the IMT key, and ptr holds the address of a memory location holding
2137 * the address to branch to if the IMT arg matches the key. The array is
2138 * terminated by a pair whose key is NULL, and whose ptr is the address of the
2140 * TRAMP_SIZE is set to the size of the emitted trampoline.
2143 arch_emit_imt_thunk (MonoAotCompile *acfg, int offset, int *tramp_size)
2145 #if defined(TARGET_AMD64)
2147 guint8 *labels [16];
2149 guint8 *mov_buf_ptr = mov_buf;
2151 const int kSizeOfMove = 7;
2153 code = buf = (guint8 *)g_malloc (256);
2155 /* FIXME: Optimize this, i.e. use binary search etc. */
2156 /* Maybe move the body into a separate function (slower, but much smaller) */
2158 /* MONO_ARCH_IMT_SCRATCH_REG is a free register */
2161 emit_unset_mode (acfg);
2162 fprintf (acfg->fp, "mov %s+%d(%%rip), %s\n", acfg->got_symbol, (int)(offset * sizeof (gpointer)), mono_arch_regname (MONO_ARCH_IMT_SCRATCH_REG));
2166 amd64_alu_membase_imm (code, X86_CMP, MONO_ARCH_IMT_SCRATCH_REG, 0, 0);
2168 amd64_branch8 (code, X86_CC_Z, 0, FALSE);
2171 amd64_alu_membase_reg_size (code, X86_CMP, MONO_ARCH_IMT_SCRATCH_REG, 0, MONO_ARCH_IMT_REG, sizeof (gpointer));
2173 amd64_branch8 (code, X86_CC_Z, 0, FALSE);
2176 amd64_alu_reg_imm (code, X86_ADD, MONO_ARCH_IMT_SCRATCH_REG, 2 * sizeof (gpointer));
2177 amd64_jump_code (code, labels [0]);
2180 mono_amd64_patch (labels [2], code);
2181 amd64_mov_reg_membase (code, MONO_ARCH_IMT_SCRATCH_REG, MONO_ARCH_IMT_SCRATCH_REG, sizeof (gpointer), sizeof (gpointer));
2182 amd64_jump_membase (code, MONO_ARCH_IMT_SCRATCH_REG, 0);
2185 mono_amd64_patch (labels [1], code);
2186 /* Load fail tramp */
2187 amd64_alu_reg_imm (code, X86_ADD, MONO_ARCH_IMT_SCRATCH_REG, sizeof (gpointer));
2188 /* Check if there is a fail tramp */
2189 amd64_alu_membase_imm (code, X86_CMP, MONO_ARCH_IMT_SCRATCH_REG, 0, 0);
2191 amd64_branch8 (code, X86_CC_Z, 0, FALSE);
2192 /* Jump to fail tramp */
2193 amd64_jump_membase (code, MONO_ARCH_IMT_SCRATCH_REG, 0);
2196 mono_amd64_patch (labels [3], code);
2197 x86_breakpoint (code);
2200 /* mov <OFFSET>(%rip), MONO_ARCH_IMT_SCRATCH_REG */
2201 amd64_emit_rex (mov_buf_ptr, sizeof(gpointer), MONO_ARCH_IMT_SCRATCH_REG, 0, AMD64_RIP);
2202 *(mov_buf_ptr)++ = (unsigned char)0x8b; /* mov opcode */
2203 x86_address_byte (mov_buf_ptr, 0, MONO_ARCH_IMT_SCRATCH_REG & 0x7, 5);
2204 emit_bytes (acfg, mov_buf, mov_buf_ptr - mov_buf);
2205 emit_symbol_diff (acfg, acfg->got_symbol, ".", (offset * sizeof (gpointer)) - 4);
2207 emit_bytes (acfg, buf, code - buf);
2209 *tramp_size = code - buf + kSizeOfMove;
2213 #elif defined(TARGET_X86)
2215 guint8 *labels [16];
2217 code = buf = g_malloc (256);
2219 /* Allocate a temporary stack slot */
2220 x86_push_reg (code, X86_EAX);
2222 x86_push_reg (code, X86_EAX);
2224 /* Load mscorlib got address */
2225 x86_mov_reg_membase (code, X86_EAX, MONO_ARCH_GOT_REG, sizeof (gpointer), 4);
2227 x86_mov_reg_membase (code, X86_EAX, X86_EAX, offset * sizeof (gpointer), 4);
2230 x86_alu_membase_imm (code, X86_CMP, X86_EAX, 0, 0);
2232 x86_branch8 (code, X86_CC_Z, FALSE, 0);
2235 x86_alu_membase_reg (code, X86_CMP, X86_EAX, 0, MONO_ARCH_IMT_REG);
2237 x86_branch8 (code, X86_CC_Z, FALSE, 0);
2240 x86_alu_reg_imm (code, X86_ADD, X86_EAX, 2 * sizeof (gpointer));
2241 x86_jump_code (code, labels [0]);
2244 mono_x86_patch (labels [2], code);
2245 x86_mov_reg_membase (code, X86_EAX, X86_EAX, sizeof (gpointer), 4);
2246 x86_mov_reg_membase (code, X86_EAX, X86_EAX, 0, 4);
2247 /* Save the target address to the temporary stack location */
2248 x86_mov_membase_reg (code, X86_ESP, 4, X86_EAX, 4);
2250 x86_pop_reg (code, X86_EAX);
2251 /* Jump to the target address */
2255 mono_x86_patch (labels [1], code);
2256 /* Load fail tramp */
2257 x86_mov_reg_membase (code, X86_EAX, X86_EAX, sizeof (gpointer), 4);
2258 x86_alu_membase_imm (code, X86_CMP, X86_EAX, 0, 0);
2260 x86_branch8 (code, X86_CC_Z, FALSE, 0);
2261 /* Jump to fail tramp */
2262 x86_mov_membase_reg (code, X86_ESP, 4, X86_EAX, 4);
2263 x86_pop_reg (code, X86_EAX);
2267 mono_x86_patch (labels [3], code);
2268 x86_breakpoint (code);
2270 emit_bytes (acfg, buf, code - buf);
2272 *tramp_size = code - buf;
2276 #elif defined(TARGET_ARM)
2278 guint8 *code, *code2, *labels [16];
2282 /* The IMT method is in v5 */
2284 /* Need at least two free registers, plus a slot for storing the pc */
2285 ARM_PUSH (code, (1 << ARMREG_R0)|(1 << ARMREG_R1)|(1 << ARMREG_R2));
2287 /* Load the parameter from the GOT */
2288 ARM_LDR_IMM (code, ARMREG_R0, ARMREG_PC, 0);
2289 ARM_LDR_REG_REG (code, ARMREG_R0, ARMREG_PC, ARMREG_R0);
2292 ARM_LDR_IMM (code, ARMREG_R1, ARMREG_R0, 0);
2293 ARM_CMP_REG_REG (code, ARMREG_R1, ARMREG_V5);
2295 ARM_B_COND (code, ARMCOND_EQ, 0);
2297 /* End-of-loop check */
2298 ARM_CMP_REG_IMM (code, ARMREG_R1, 0, 0);
2300 ARM_B_COND (code, ARMCOND_EQ, 0);
2303 ARM_ADD_REG_IMM8 (code, ARMREG_R0, ARMREG_R0, sizeof (gpointer) * 2);
2306 arm_patch (labels [4], labels [1]);
2309 arm_patch (labels [2], code);
2310 ARM_LDR_IMM (code, ARMREG_R0, ARMREG_R0, 4);
2311 ARM_LDR_IMM (code, ARMREG_R0, ARMREG_R0, 0);
2312 /* Save it to the third stack slot */
2313 ARM_STR_IMM (code, ARMREG_R0, ARMREG_SP, 8);
2314 /* Restore the registers and branch */
2315 ARM_POP (code, (1 << ARMREG_R0)|(1 << ARMREG_R1)|(1 << ARMREG_PC));
2318 arm_patch (labels [3], code);
2319 ARM_LDR_IMM (code, ARMREG_R0, ARMREG_R0, 4);
2320 ARM_STR_IMM (code, ARMREG_R0, ARMREG_SP, 8);
2321 ARM_POP (code, (1 << ARMREG_R0)|(1 << ARMREG_R1)|(1 << ARMREG_PC));
2325 ARM_LDR_IMM (code2, ARMREG_R0, ARMREG_PC, (code - (labels [0] + 8)));
2327 emit_bytes (acfg, buf, code - buf);
2328 emit_symbol_diff (acfg, acfg->got_symbol, ".", (offset * sizeof (gpointer)) + (code - (labels [0] + 8)) - 4);
2330 *tramp_size = code - buf + 4;
2331 #elif defined(TARGET_ARM64)
2332 arm64_emit_imt_thunk (acfg, offset, tramp_size);
2333 #elif defined(TARGET_POWERPC)
2335 guint8 *code, *labels [16];
2339 /* Load the mscorlib got address */
2340 ppc_ldptr (code, ppc_r12, sizeof (gpointer), ppc_r30);
2341 /* Load the parameter from the GOT */
2342 ppc_load (code, ppc_r0, offset * sizeof (gpointer));
2343 ppc_ldptr_indexed (code, ppc_r12, ppc_r12, ppc_r0);
2345 /* Load and check key */
2347 ppc_ldptr (code, ppc_r0, 0, ppc_r12);
2348 ppc_cmp (code, 0, sizeof (gpointer) == 8 ? 1 : 0, ppc_r0, MONO_ARCH_IMT_REG);
2350 ppc_bc (code, PPC_BR_TRUE, PPC_BR_EQ, 0);
2352 /* End-of-loop check */
2353 ppc_cmpi (code, 0, sizeof (gpointer) == 8 ? 1 : 0, ppc_r0, 0);
2355 ppc_bc (code, PPC_BR_TRUE, PPC_BR_EQ, 0);
2358 ppc_addi (code, ppc_r12, ppc_r12, 2 * sizeof (gpointer));
2361 mono_ppc_patch (labels [4], labels [1]);
2364 mono_ppc_patch (labels [2], code);
2365 ppc_ldptr (code, ppc_r12, sizeof (gpointer), ppc_r12);
2366 /* r12 now contains the value of the vtable slot */
2367 /* this is not a function descriptor on ppc64 */
2368 ppc_ldptr (code, ppc_r12, 0, ppc_r12);
2369 ppc_mtctr (code, ppc_r12);
2370 ppc_bcctr (code, PPC_BR_ALWAYS, 0);
2373 mono_ppc_patch (labels [3], code);
2377 *tramp_size = code - buf;
2379 emit_bytes (acfg, buf, code - buf);
2381 g_assert_not_reached ();
2386 #if defined (TARGET_AMD64)
2389 amd64_emit_load_got_slot (MonoAotCompile *acfg, int dreg, int got_slot)
2392 g_assert (acfg->fp);
2393 emit_unset_mode (acfg);
2395 fprintf (acfg->fp, "mov %s+%d(%%rip), %s\n", acfg->got_symbol, (unsigned int) ((got_slot * sizeof (gpointer))), mono_arch_regname (dreg));
2402 * arch_emit_gsharedvt_arg_trampoline:
2404 * Emit code for a gsharedvt arg trampoline. OFFSET is the offset of the first of
2405 * two GOT slots which contain the argument, and the code to jump to.
2406 * TRAMP_SIZE is set to the size of the emitted trampoline.
2407 * These kinds of trampolines cannot be enumerated statically, since there could
2408 * be one trampoline per method instantiation, so we emit the same code for all
2409 * trampolines, and parameterize them using two GOT slots.
2412 arch_emit_gsharedvt_arg_trampoline (MonoAotCompile *acfg, int offset, int *tramp_size)
2414 #if defined(TARGET_X86)
2418 /* Similar to the PPC code above */
2420 g_assert (MONO_ARCH_RGCTX_REG != X86_ECX);
2423 /* Load mscorlib got address */
2424 x86_mov_reg_membase (code, X86_ECX, MONO_ARCH_GOT_REG, sizeof (gpointer), 4);
2426 x86_mov_reg_membase (code, X86_EAX, X86_ECX, offset * sizeof (gpointer), 4);
2427 /* Branch to the target address */
2428 x86_jump_membase (code, X86_ECX, (offset + 1) * sizeof (gpointer));
2430 emit_bytes (acfg, buf, code - buf);
2433 g_assert (code - buf == *tramp_size);
2434 #elif defined(TARGET_ARM)
2438 /* The same as mono_arch_get_gsharedvt_arg_trampoline (), but for AOT */
2439 /* Similar to arch_emit_specific_trampoline () */
2442 ARM_PUSH (code, (1 << ARMREG_R0) | (1 << ARMREG_R1) | (1 << ARMREG_R2) | (1 << ARMREG_R3));
2443 ARM_LDR_IMM (code, ARMREG_R1, ARMREG_PC, 8);
2444 /* Load the arg value from the GOT */
2445 ARM_LDR_REG_REG (code, ARMREG_R0, ARMREG_PC, ARMREG_R1);
2446 /* Load the addr from the GOT */
2447 ARM_LDR_REG_REG (code, ARMREG_R1, ARMREG_PC, ARMREG_R1);
2449 ARM_BX (code, ARMREG_R1);
2451 g_assert (code - buf == 20);
2454 emit_bytes (acfg, buf, code - buf);
2455 emit_symbol_diff (acfg, acfg->got_symbol, ".", (offset * sizeof (gpointer)) + 4);
2456 #elif defined(TARGET_ARM64)
2457 arm64_emit_gsharedvt_arg_trampoline (acfg, offset, tramp_size);
2458 #elif defined (TARGET_AMD64)
2460 amd64_emit_load_got_slot (acfg, AMD64_RAX, offset);
2461 amd64_emit_load_got_slot (acfg, MONO_ARCH_IMT_SCRATCH_REG, offset + 1);
2462 g_assert (AMD64_R11 == MONO_ARCH_IMT_SCRATCH_REG);
2463 fprintf (acfg->fp, "jmp *%%r11\n");
2467 g_assert_not_reached ();
2471 /* END OF ARCH SPECIFIC CODE */
2474 mono_get_field_token (MonoClassField *field)
2476 MonoClass *klass = field->parent;
2479 for (i = 0; i < klass->field.count; ++i) {
2480 if (field == &klass->fields [i])
2481 return MONO_TOKEN_FIELD_DEF | (klass->field.first + 1 + i);
2484 g_assert_not_reached ();
2489 encode_value (gint32 value, guint8 *buf, guint8 **endbuf)
2493 //printf ("ENCODE: %d 0x%x.\n", value, value);
2496 * Same encoding as the one used in the metadata, extended to handle values
2497 * greater than 0x1fffffff.
2499 if ((value >= 0) && (value <= 127))
2501 else if ((value >= 0) && (value <= 16383)) {
2502 p [0] = 0x80 | (value >> 8);
2503 p [1] = value & 0xff;
2505 } else if ((value >= 0) && (value <= 0x1fffffff)) {
2506 p [0] = (value >> 24) | 0xc0;
2507 p [1] = (value >> 16) & 0xff;
2508 p [2] = (value >> 8) & 0xff;
2509 p [3] = value & 0xff;
2514 p [1] = (value >> 24) & 0xff;
2515 p [2] = (value >> 16) & 0xff;
2516 p [3] = (value >> 8) & 0xff;
2517 p [4] = value & 0xff;
2525 stream_init (MonoDynamicStream *sh)
2528 sh->alloc_size = 4096;
2529 sh->data = (char *)g_malloc (4096);
2531 /* So offsets are > 0 */
2537 make_room_in_stream (MonoDynamicStream *stream, int size)
2539 if (size <= stream->alloc_size)
2542 while (stream->alloc_size <= size) {
2543 if (stream->alloc_size < 4096)
2544 stream->alloc_size = 4096;
2546 stream->alloc_size *= 2;
2549 stream->data = (char *)g_realloc (stream->data, stream->alloc_size);
2553 add_stream_data (MonoDynamicStream *stream, const char *data, guint32 len)
2557 make_room_in_stream (stream, stream->index + len);
2558 memcpy (stream->data + stream->index, data, len);
2559 idx = stream->index;
2560 stream->index += len;
2567 * Add data to the binary blob inside the aot image. Returns the offset inside the
2568 * blob where the data was stored.
2571 add_to_blob (MonoAotCompile *acfg, const guint8 *data, guint32 data_len)
2573 g_assert (!acfg->blob_closed);
2575 if (acfg->blob.alloc_size == 0)
2576 stream_init (&acfg->blob);
2578 return add_stream_data (&acfg->blob, (char*)data, data_len);
2582 add_to_blob_aligned (MonoAotCompile *acfg, const guint8 *data, guint32 data_len, guint32 align)
2587 if (acfg->blob.alloc_size == 0)
2588 stream_init (&acfg->blob);
2590 count = acfg->blob.index % align;
2592 /* we assume the stream data will be aligned */
2594 add_stream_data (&acfg->blob, buf, 4 - count);
2596 return add_stream_data (&acfg->blob, (char*)data, data_len);
2599 /* Emit a table of data into the aot image */
2601 emit_aot_data (MonoAotCompile *acfg, MonoAotFileTable table, const char *symbol, guint8 *data, int size)
2603 if (acfg->data_outfile) {
2604 acfg->table_offsets [(int)table] = acfg->datafile_offset;
2605 fwrite (data,1, size, acfg->data_outfile);
2606 acfg->datafile_offset += size;
2607 // align the data to 8 bytes. Put zeros in the file (so that every build results in consistent output).
2608 int align = 8 - size % 8;
2609 acfg->datafile_offset += align;
2610 guint8 align_buf [16];
2611 memset (&align_buf, 0, sizeof (align_buf));
2612 fwrite (align_buf, align, 1, acfg->data_outfile);
2613 } else if (acfg->llvm) {
2614 mono_llvm_emit_aot_data (symbol, data, size);
2616 emit_section_change (acfg, RODATA_SECT, 0);
2617 emit_alignment (acfg, 8);
2618 emit_label (acfg, symbol);
2619 emit_bytes (acfg, data, size);
2624 * emit_offset_table:
2626 * Emit a table of increasing offsets in a compact form using differential encoding.
2627 * There is an index entry for each GROUP_SIZE number of entries. The greater the
2628 * group size, the more compact the table becomes, but the slower it becomes to compute
2629 * a given entry. Returns the size of the table.
2632 emit_offset_table (MonoAotCompile *acfg, const char *symbol, MonoAotFileTable table, int noffsets, int group_size, gint32 *offsets)
2634 gint32 current_offset;
2635 int i, buf_size, ngroups, index_entry_size;
2637 guint8 *data_p, *data_buf;
2638 guint32 *index_offsets;
2640 ngroups = (noffsets + (group_size - 1)) / group_size;
2642 index_offsets = g_new0 (guint32, ngroups);
2644 buf_size = noffsets * 4;
2645 p = buf = (guint8 *)g_malloc0 (buf_size);
2648 for (i = 0; i < noffsets; ++i) {
2649 //printf ("D: %d -> %d\n", i, offsets [i]);
2650 if ((i % group_size) == 0) {
2651 index_offsets [i / group_size] = p - buf;
2652 /* Emit the full value for these entries */
2653 encode_value (offsets [i], p, &p);
2655 /* The offsets are allowed to be non-increasing */
2656 //g_assert (offsets [i] >= current_offset);
2657 encode_value (offsets [i] - current_offset, p, &p);
2659 current_offset = offsets [i];
2664 if (ngroups && index_offsets [ngroups - 1] < 65000)
2665 index_entry_size = 2;
2667 index_entry_size = 4;
2669 buf_size = (data_p - data_buf) + (ngroups * 4) + 16;
2670 p = buf = (guint8 *)g_malloc0 (buf_size);
2672 /* Emit the header */
2673 encode_int (noffsets, p, &p);
2674 encode_int (group_size, p, &p);
2675 encode_int (ngroups, p, &p);
2676 encode_int (index_entry_size, p, &p);
2678 /* Emit the index */
2679 for (i = 0; i < ngroups; ++i) {
2680 if (index_entry_size == 2)
2681 encode_int16 (index_offsets [i], p, &p);
2683 encode_int (index_offsets [i], p, &p);
2686 memcpy (p, data_buf, data_p - data_buf);
2687 p += data_p - data_buf;
2689 g_assert (p - buf <= buf_size);
2691 emit_aot_data (acfg, table, symbol, buf, p - buf);
2696 return (int)(p - buf);
2700 get_image_index (MonoAotCompile *cfg, MonoImage *image)
2704 index = GPOINTER_TO_UINT (g_hash_table_lookup (cfg->image_hash, image));
2708 index = g_hash_table_size (cfg->image_hash);
2709 g_hash_table_insert (cfg->image_hash, image, GUINT_TO_POINTER (index + 1));
2710 g_ptr_array_add (cfg->image_table, image);
2716 find_typespec_for_class (MonoAotCompile *acfg, MonoClass *klass)
2719 int len = acfg->image->tables [MONO_TABLE_TYPESPEC].rows;
2721 /* FIXME: Search referenced images as well */
2722 if (!acfg->typespec_classes) {
2723 acfg->typespec_classes = g_hash_table_new (NULL, NULL);
2724 for (i = 0; i < len; i++) {
2726 int typespec = MONO_TOKEN_TYPE_SPEC | (i + 1);
2727 MonoClass *klass_key = mono_class_get_and_inflate_typespec_checked (acfg->image, typespec, NULL, &error);
2728 if (!is_ok (&error)) {
2729 mono_error_cleanup (&error);
2732 g_hash_table_insert (acfg->typespec_classes, klass_key, GINT_TO_POINTER (typespec));
2735 return GPOINTER_TO_INT (g_hash_table_lookup (acfg->typespec_classes, klass));
2739 encode_method_ref (MonoAotCompile *acfg, MonoMethod *method, guint8 *buf, guint8 **endbuf);
2742 encode_klass_ref (MonoAotCompile *acfg, MonoClass *klass, guint8 *buf, guint8 **endbuf);
2745 encode_ginst (MonoAotCompile *acfg, MonoGenericInst *inst, guint8 *buf, guint8 **endbuf);
2748 encode_type (MonoAotCompile *acfg, MonoType *t, guint8 *buf, guint8 **endbuf);
2751 encode_klass_ref_inner (MonoAotCompile *acfg, MonoClass *klass, guint8 *buf, guint8 **endbuf)
2756 * The encoding begins with one of the MONO_AOT_TYPEREF values, followed by additional
2760 if (klass->generic_class) {
2762 g_assert (klass->type_token);
2764 /* Find a typespec for a class if possible */
2765 token = find_typespec_for_class (acfg, klass);
2767 encode_value (MONO_AOT_TYPEREF_TYPESPEC_TOKEN, p, &p);
2768 encode_value (token, p, &p);
2770 MonoClass *gclass = klass->generic_class->container_class;
2771 MonoGenericInst *inst = klass->generic_class->context.class_inst;
2772 static int count = 0;
2775 encode_value (MONO_AOT_TYPEREF_GINST, p, &p);
2776 encode_klass_ref (acfg, gclass, p, &p);
2777 encode_ginst (acfg, inst, p, &p);
2781 } else if (klass->type_token) {
2782 int iindex = get_image_index (acfg, klass->image);
2784 g_assert (mono_metadata_token_code (klass->type_token) == MONO_TOKEN_TYPE_DEF);
2786 encode_value (MONO_AOT_TYPEREF_TYPEDEF_INDEX, p, &p);
2787 encode_value (klass->type_token - MONO_TOKEN_TYPE_DEF, p, &p);
2789 encode_value (MONO_AOT_TYPEREF_TYPEDEF_INDEX_IMAGE, p, &p);
2790 encode_value (klass->type_token - MONO_TOKEN_TYPE_DEF, p, &p);
2791 encode_value (get_image_index (acfg, klass->image), p, &p);
2793 } else if ((klass->byval_arg.type == MONO_TYPE_VAR) || (klass->byval_arg.type == MONO_TYPE_MVAR)) {
2794 MonoGenericContainer *container = mono_type_get_generic_param_owner (&klass->byval_arg);
2795 MonoGenericParam *par = klass->byval_arg.data.generic_param;
2797 encode_value (MONO_AOT_TYPEREF_VAR, p, &p);
2799 encode_value (par->gshared_constraint ? 1 : 0, p, &p);
2800 if (par->gshared_constraint) {
2801 MonoGSharedGenericParam *gpar = (MonoGSharedGenericParam*)par;
2802 encode_type (acfg, par->gshared_constraint, p, &p);
2803 encode_klass_ref (acfg, mono_class_from_generic_parameter (gpar->parent, NULL, klass->byval_arg.type == MONO_TYPE_MVAR), p, &p);
2805 encode_value (klass->byval_arg.type, p, &p);
2806 encode_value (mono_type_get_generic_param_num (&klass->byval_arg), p, &p);
2808 encode_value (container->is_anonymous ? 0 : 1, p, &p);
2810 if (!container->is_anonymous) {
2811 encode_value (container->is_method, p, &p);
2812 if (container->is_method)
2813 encode_method_ref (acfg, container->owner.method, p, &p);
2815 encode_klass_ref (acfg, container->owner.klass, p, &p);
2818 } else if (klass->byval_arg.type == MONO_TYPE_PTR) {
2819 encode_value (MONO_AOT_TYPEREF_PTR, p, &p);
2820 encode_type (acfg, &klass->byval_arg, p, &p);
2823 g_assert (klass->rank > 0);
2824 encode_value (MONO_AOT_TYPEREF_ARRAY, p, &p);
2825 encode_value (klass->rank, p, &p);
2826 encode_klass_ref (acfg, klass->element_class, p, &p);
2834 * Encode a reference to KLASS. We use our home-grown encoding instead of the
2835 * standard metadata encoding.
2838 encode_klass_ref (MonoAotCompile *acfg, MonoClass *klass, guint8 *buf, guint8 **endbuf)
2840 gboolean shared = FALSE;
2843 * The encoding of generic instances is large so emit them only once.
2845 if (klass->generic_class) {
2847 g_assert (klass->type_token);
2849 /* Find a typespec for a class if possible */
2850 token = find_typespec_for_class (acfg, klass);
2853 } else if ((klass->byval_arg.type == MONO_TYPE_VAR) || (klass->byval_arg.type == MONO_TYPE_MVAR)) {
2858 guint offset = GPOINTER_TO_UINT (g_hash_table_lookup (acfg->klass_blob_hash, klass));
2862 buf2 = (guint8 *)g_malloc (1024);
2865 encode_klass_ref_inner (acfg, klass, p, &p);
2866 g_assert (p - buf2 < 1024);
2868 offset = add_to_blob (acfg, buf2, p - buf2);
2871 g_hash_table_insert (acfg->klass_blob_hash, klass, GUINT_TO_POINTER (offset + 1));
2877 encode_value (MONO_AOT_TYPEREF_BLOB_INDEX, p, &p);
2878 encode_value (offset, p, &p);
2883 encode_klass_ref_inner (acfg, klass, buf, endbuf);
2887 encode_field_info (MonoAotCompile *cfg, MonoClassField *field, guint8 *buf, guint8 **endbuf)
2889 guint32 token = mono_get_field_token (field);
2892 encode_klass_ref (cfg, field->parent, p, &p);
2893 g_assert (mono_metadata_token_code (token) == MONO_TOKEN_FIELD_DEF);
2894 encode_value (token - MONO_TOKEN_FIELD_DEF, p, &p);
2899 encode_ginst (MonoAotCompile *acfg, MonoGenericInst *inst, guint8 *buf, guint8 **endbuf)
2904 encode_value (inst->type_argc, p, &p);
2905 for (i = 0; i < inst->type_argc; ++i)
2906 encode_klass_ref (acfg, mono_class_from_mono_type (inst->type_argv [i]), p, &p);
2911 encode_generic_context (MonoAotCompile *acfg, MonoGenericContext *context, guint8 *buf, guint8 **endbuf)
2914 MonoGenericInst *inst;
2916 inst = context->class_inst;
2918 g_assert (inst->type_argc);
2919 encode_ginst (acfg, inst, p, &p);
2921 encode_value (0, p, &p);
2923 inst = context->method_inst;
2925 g_assert (inst->type_argc);
2926 encode_ginst (acfg, inst, p, &p);
2928 encode_value (0, p, &p);
2934 encode_type (MonoAotCompile *acfg, MonoType *t, guint8 *buf, guint8 **endbuf)
2938 g_assert (t->num_mods == 0);
2939 /* t->attrs can be ignored */
2940 //g_assert (t->attrs == 0);
2943 *p = MONO_TYPE_PINNED;
2947 *p = MONO_TYPE_BYREF;
2955 case MONO_TYPE_VOID:
2956 case MONO_TYPE_BOOLEAN:
2957 case MONO_TYPE_CHAR:
2970 case MONO_TYPE_STRING:
2971 case MONO_TYPE_OBJECT:
2972 case MONO_TYPE_TYPEDBYREF:
2974 case MONO_TYPE_VALUETYPE:
2975 case MONO_TYPE_CLASS:
2976 encode_klass_ref (acfg, mono_class_from_mono_type (t), p, &p);
2978 case MONO_TYPE_SZARRAY:
2979 encode_klass_ref (acfg, t->data.klass, p, &p);
2982 encode_type (acfg, t->data.type, p, &p);
2984 case MONO_TYPE_GENERICINST: {
2985 MonoClass *gclass = t->data.generic_class->container_class;
2986 MonoGenericInst *inst = t->data.generic_class->context.class_inst;
2988 encode_klass_ref (acfg, gclass, p, &p);
2989 encode_ginst (acfg, inst, p, &p);
2992 case MONO_TYPE_ARRAY: {
2993 MonoArrayType *array = t->data.array;
2996 encode_klass_ref (acfg, array->eklass, p, &p);
2997 encode_value (array->rank, p, &p);
2998 encode_value (array->numsizes, p, &p);
2999 for (i = 0; i < array->numsizes; ++i)
3000 encode_value (array->sizes [i], p, &p);
3001 encode_value (array->numlobounds, p, &p);
3002 for (i = 0; i < array->numlobounds; ++i)
3003 encode_value (array->lobounds [i], p, &p);
3007 case MONO_TYPE_MVAR:
3008 encode_klass_ref (acfg, mono_class_from_mono_type (t), p, &p);
3011 g_assert_not_reached ();
3018 encode_signature (MonoAotCompile *acfg, MonoMethodSignature *sig, guint8 *buf, guint8 **endbuf)
3024 /* Similar to the metadata encoding */
3025 if (sig->generic_param_count)
3029 if (sig->explicit_this)
3031 flags |= (sig->call_convention & 0x0F);
3035 if (sig->generic_param_count)
3036 encode_value (sig->generic_param_count, p, &p);
3037 encode_value (sig->param_count, p, &p);
3039 encode_type (acfg, sig->ret, p, &p);
3040 for (i = 0; i < sig->param_count; ++i) {
3041 if (sig->sentinelpos == i) {
3042 *p = MONO_TYPE_SENTINEL;
3045 encode_type (acfg, sig->params [i], p, &p);
3051 #define MAX_IMAGE_INDEX 250
3054 encode_method_ref (MonoAotCompile *acfg, MonoMethod *method, guint8 *buf, guint8 **endbuf)
3056 guint32 image_index = get_image_index (acfg, method->klass->image);
3057 guint32 token = method->token;
3058 MonoJumpInfoToken *ji;
3062 * The encoding for most methods is as follows:
3063 * - image index encoded as a leb128
3064 * - token index encoded as a leb128
3065 * Values of image index >= MONO_AOT_METHODREF_MIN are used to mark additional
3066 * types of method encodings.
3069 /* Mark methods which can't use aot trampolines because they need the further
3070 * processing in mono_magic_trampoline () which requires a MonoMethod*.
3072 if ((method->is_generic && (method->flags & METHOD_ATTRIBUTE_VIRTUAL)) ||
3073 (method->iflags & METHOD_IMPL_ATTRIBUTE_SYNCHRONIZED))
3074 encode_value ((MONO_AOT_METHODREF_NO_AOT_TRAMPOLINE << 24), p, &p);
3076 if (method->wrapper_type) {
3077 WrapperInfo *info = mono_marshal_get_wrapper_info (method);
3079 encode_value ((MONO_AOT_METHODREF_WRAPPER << 24), p, &p);
3081 encode_value (method->wrapper_type, p, &p);
3083 switch (method->wrapper_type) {
3084 case MONO_WRAPPER_REMOTING_INVOKE:
3085 case MONO_WRAPPER_REMOTING_INVOKE_WITH_CHECK:
3086 case MONO_WRAPPER_XDOMAIN_INVOKE: {
3089 m = mono_marshal_method_from_wrapper (method);
3091 encode_method_ref (acfg, m, p, &p);
3094 case MONO_WRAPPER_PROXY_ISINST:
3095 case MONO_WRAPPER_LDFLD:
3096 case MONO_WRAPPER_LDFLDA:
3097 case MONO_WRAPPER_STFLD:
3098 case MONO_WRAPPER_ISINST: {
3100 encode_klass_ref (acfg, info->d.proxy.klass, p, &p);
3103 case MONO_WRAPPER_STFLD_REMOTE:
3105 case MONO_WRAPPER_ALLOC: {
3106 /* The GC name is saved once in MonoAotFileInfo */
3107 g_assert (info->d.alloc.alloc_type != -1);
3108 encode_value (info->d.alloc.alloc_type, p, &p);
3111 case MONO_WRAPPER_WRITE_BARRIER: {
3115 case MONO_WRAPPER_STELEMREF: {
3117 encode_value (info->subtype, p, &p);
3118 if (info->subtype == WRAPPER_SUBTYPE_VIRTUAL_STELEMREF)
3119 encode_value (info->d.virtual_stelemref.kind, p, &p);
3122 case MONO_WRAPPER_UNKNOWN: {
3124 encode_value (info->subtype, p, &p);
3125 if (info->subtype == WRAPPER_SUBTYPE_PTR_TO_STRUCTURE ||
3126 info->subtype == WRAPPER_SUBTYPE_STRUCTURE_TO_PTR)
3127 encode_klass_ref (acfg, method->klass, p, &p);
3128 else if (info->subtype == WRAPPER_SUBTYPE_SYNCHRONIZED_INNER)
3129 encode_method_ref (acfg, info->d.synchronized_inner.method, p, &p);
3130 else if (info->subtype == WRAPPER_SUBTYPE_ARRAY_ACCESSOR)
3131 encode_method_ref (acfg, info->d.array_accessor.method, p, &p);
3132 else if (info->subtype == WRAPPER_SUBTYPE_GSHAREDVT_IN_SIG)
3133 encode_signature (acfg, info->d.gsharedvt.sig, p, &p);
3134 else if (info->subtype == WRAPPER_SUBTYPE_GSHAREDVT_OUT_SIG)
3135 encode_signature (acfg, info->d.gsharedvt.sig, p, &p);
3138 case MONO_WRAPPER_MANAGED_TO_NATIVE: {
3140 encode_value (info->subtype, p, &p);
3141 if (info->subtype == WRAPPER_SUBTYPE_ICALL_WRAPPER) {
3142 strcpy ((char*)p, method->name);
3143 p += strlen (method->name) + 1;
3144 } else if (info->subtype == WRAPPER_SUBTYPE_NATIVE_FUNC_AOT) {
3145 encode_method_ref (acfg, info->d.managed_to_native.method, p, &p);
3147 g_assert (info->subtype == WRAPPER_SUBTYPE_NONE || info->subtype == WRAPPER_SUBTYPE_PINVOKE);
3148 encode_method_ref (acfg, info->d.managed_to_native.method, p, &p);
3152 case MONO_WRAPPER_SYNCHRONIZED: {
3155 m = mono_marshal_method_from_wrapper (method);
3157 g_assert (m != method);
3158 encode_method_ref (acfg, m, p, &p);
3161 case MONO_WRAPPER_MANAGED_TO_MANAGED: {
3163 encode_value (info->subtype, p, &p);
3165 if (info->subtype == WRAPPER_SUBTYPE_ELEMENT_ADDR) {
3166 encode_value (info->d.element_addr.rank, p, &p);
3167 encode_value (info->d.element_addr.elem_size, p, &p);
3168 } else if (info->subtype == WRAPPER_SUBTYPE_STRING_CTOR) {
3169 encode_method_ref (acfg, info->d.string_ctor.method, p, &p);
3171 g_assert_not_reached ();
3175 case MONO_WRAPPER_CASTCLASS: {
3177 encode_value (info->subtype, p, &p);
3180 case MONO_WRAPPER_RUNTIME_INVOKE: {
3182 encode_value (info->subtype, p, &p);
3183 if (info->subtype == WRAPPER_SUBTYPE_RUNTIME_INVOKE_DIRECT || info->subtype == WRAPPER_SUBTYPE_RUNTIME_INVOKE_VIRTUAL)
3184 encode_method_ref (acfg, info->d.runtime_invoke.method, p, &p);
3185 else if (info->subtype == WRAPPER_SUBTYPE_RUNTIME_INVOKE_NORMAL)
3186 encode_signature (acfg, info->d.runtime_invoke.sig, p, &p);
3189 case MONO_WRAPPER_DELEGATE_INVOKE:
3190 case MONO_WRAPPER_DELEGATE_BEGIN_INVOKE:
3191 case MONO_WRAPPER_DELEGATE_END_INVOKE: {
3192 if (method->is_inflated) {
3193 /* These wrappers are identified by their class */
3194 encode_value (1, p, &p);
3195 encode_klass_ref (acfg, method->klass, p, &p);
3197 MonoMethodSignature *sig = mono_method_signature (method);
3198 WrapperInfo *info = mono_marshal_get_wrapper_info (method);
3200 encode_value (0, p, &p);
3201 if (method->wrapper_type == MONO_WRAPPER_DELEGATE_INVOKE)
3202 encode_value (info ? info->subtype : 0, p, &p);
3203 encode_signature (acfg, sig, p, &p);
3207 case MONO_WRAPPER_NATIVE_TO_MANAGED: {
3209 encode_method_ref (acfg, info->d.native_to_managed.method, p, &p);
3210 encode_klass_ref (acfg, info->d.native_to_managed.klass, p, &p);
3214 g_assert_not_reached ();
3216 } else if (mono_method_signature (method)->is_inflated) {
3218 * This is a generic method, find the original token which referenced it and
3220 * Obtain the token from information recorded by the JIT.
3222 ji = (MonoJumpInfoToken *)g_hash_table_lookup (acfg->token_info_hash, method);
3224 image_index = get_image_index (acfg, ji->image);
3225 g_assert (image_index < MAX_IMAGE_INDEX);
3228 encode_value ((MONO_AOT_METHODREF_METHODSPEC << 24), p, &p);
3229 encode_value (image_index, p, &p);
3230 encode_value (token, p, &p);
3232 MonoMethod *declaring;
3233 MonoGenericContext *context = mono_method_get_context (method);
3235 g_assert (method->is_inflated);
3236 declaring = ((MonoMethodInflated*)method)->declaring;
3239 * This might be a non-generic method of a generic instance, which
3240 * doesn't have a token since the reference is generated by the JIT
3241 * like Nullable:Box/Unbox, or by generic sharing.
3243 encode_value ((MONO_AOT_METHODREF_GINST << 24), p, &p);
3244 /* Encode the klass */
3245 encode_klass_ref (acfg, method->klass, p, &p);
3246 /* Encode the method */
3247 image_index = get_image_index (acfg, method->klass->image);
3248 g_assert (image_index < MAX_IMAGE_INDEX);
3249 g_assert (declaring->token);
3250 token = declaring->token;
3251 g_assert (mono_metadata_token_table (token) == MONO_TABLE_METHOD);
3252 encode_value (image_index, p, &p);
3253 encode_value (token, p, &p);
3254 encode_generic_context (acfg, context, p, &p);
3256 } else if (token == 0) {
3257 /* This might be a method of a constructed type like int[,].Set */
3258 /* Obtain the token from information recorded by the JIT */
3259 ji = (MonoJumpInfoToken *)g_hash_table_lookup (acfg->token_info_hash, method);
3261 image_index = get_image_index (acfg, ji->image);
3262 g_assert (image_index < MAX_IMAGE_INDEX);
3265 encode_value ((MONO_AOT_METHODREF_METHODSPEC << 24), p, &p);
3266 encode_value (image_index, p, &p);
3267 encode_value (token, p, &p);
3270 g_assert (method->klass->rank);
3272 /* Encode directly */
3273 encode_value ((MONO_AOT_METHODREF_ARRAY << 24), p, &p);
3274 encode_klass_ref (acfg, method->klass, p, &p);
3275 if (!strcmp (method->name, ".ctor") && mono_method_signature (method)->param_count == method->klass->rank)
3276 encode_value (0, p, &p);
3277 else if (!strcmp (method->name, ".ctor") && mono_method_signature (method)->param_count == method->klass->rank * 2)
3278 encode_value (1, p, &p);
3279 else if (!strcmp (method->name, "Get"))
3280 encode_value (2, p, &p);
3281 else if (!strcmp (method->name, "Address"))
3282 encode_value (3, p, &p);
3283 else if (!strcmp (method->name, "Set"))
3284 encode_value (4, p, &p);
3286 g_assert_not_reached ();
3289 g_assert (mono_metadata_token_table (token) == MONO_TABLE_METHOD);
3291 if (image_index >= MONO_AOT_METHODREF_MIN) {
3292 encode_value ((MONO_AOT_METHODREF_LARGE_IMAGE_INDEX << 24), p, &p);
3293 encode_value (image_index, p, &p);
3294 encode_value (mono_metadata_token_index (token), p, &p);
3296 encode_value ((image_index << 24) | mono_metadata_token_index (token), p, &p);
3303 compare_patches (gconstpointer a, gconstpointer b)
3307 i = (*(MonoJumpInfo**)a)->ip.i;
3308 j = (*(MonoJumpInfo**)b)->ip.i;
3319 static G_GNUC_UNUSED char*
3320 patch_to_string (MonoJumpInfo *patch_info)
3324 str = g_string_new ("");
3326 g_string_append_printf (str, "%s(", get_patch_name (patch_info->type));
3328 switch (patch_info->type) {
3329 case MONO_PATCH_INFO_VTABLE:
3330 mono_type_get_desc (str, &patch_info->data.klass->byval_arg, TRUE);
3335 g_string_append_printf (str, ")");
3336 return g_string_free (str, FALSE);
3342 * Return whenever PATCH_INFO refers to a direct call, and thus requires a
3345 static inline gboolean
3346 is_plt_patch (MonoJumpInfo *patch_info)
3348 switch (patch_info->type) {
3349 case MONO_PATCH_INFO_METHOD:
3350 case MONO_PATCH_INFO_INTERNAL_METHOD:
3351 case MONO_PATCH_INFO_JIT_ICALL_ADDR:
3352 case MONO_PATCH_INFO_ICALL_ADDR_CALL:
3353 case MONO_PATCH_INFO_RGCTX_FETCH:
3363 * Return the symbol identifying the plt entry PLT_OFFSET.
3366 get_plt_symbol (MonoAotCompile *acfg, int plt_offset, MonoJumpInfo *patch_info)
3370 * The Apple linker reorganizes object files, so it doesn't like branches to local
3371 * labels, since those have no relocations.
3373 return g_strdup_printf ("%sp_%d", acfg->llvm_label_prefix, plt_offset);
3375 return g_strdup_printf ("%sp_%d", acfg->temp_prefix, plt_offset);
3382 * Return a PLT entry which belongs to the method identified by PATCH_INFO.
3384 static MonoPltEntry*
3385 get_plt_entry (MonoAotCompile *acfg, MonoJumpInfo *patch_info)
3388 gboolean synchronized = FALSE;
3389 static int synchronized_symbol_idx;
3391 if (!is_plt_patch (patch_info))
3394 if (!acfg->patch_to_plt_entry [patch_info->type])
3395 acfg->patch_to_plt_entry [patch_info->type] = g_hash_table_new (mono_patch_info_hash, mono_patch_info_equal);
3396 res = (MonoPltEntry *)g_hash_table_lookup (acfg->patch_to_plt_entry [patch_info->type], patch_info);
3398 if (!acfg->llvm && patch_info->type == MONO_PATCH_INFO_METHOD && (patch_info->data.method->iflags & METHOD_IMPL_ATTRIBUTE_SYNCHRONIZED)) {
3400 * Allocate a separate PLT slot for each such patch, since some plt
3401 * entries will refer to the method itself, and some will refer to the
3405 synchronized = TRUE;
3409 MonoJumpInfo *new_ji;
3411 new_ji = mono_patch_info_dup_mp (acfg->mempool, patch_info);
3413 res = (MonoPltEntry *)mono_mempool_alloc0 (acfg->mempool, sizeof (MonoPltEntry));
3414 res->plt_offset = acfg->plt_offset;
3416 res->symbol = get_plt_symbol (acfg, res->plt_offset, patch_info);
3417 if (acfg->aot_opts.write_symbols)
3418 res->debug_sym = get_plt_entry_debug_sym (acfg, res->ji, acfg->plt_entry_debug_sym_cache);
3420 /* Avoid duplicate symbols because we don't cache */
3421 res->symbol = g_strdup_printf ("%s_%d", res->symbol, synchronized_symbol_idx);
3423 res->debug_sym = g_strdup_printf ("%s_%d", res->debug_sym, synchronized_symbol_idx);
3424 synchronized_symbol_idx ++;
3427 res->llvm_symbol = g_strdup_printf ("%s_%s_llvm", res->symbol, res->debug_sym);
3429 res->llvm_symbol = g_strdup_printf ("%s_llvm", res->symbol);
3431 g_hash_table_insert (acfg->patch_to_plt_entry [new_ji->type], new_ji, res);
3433 g_hash_table_insert (acfg->plt_offset_to_entry, GUINT_TO_POINTER (res->plt_offset), res);
3435 //g_assert (mono_patch_info_equal (patch_info, new_ji));
3436 //mono_print_ji (patch_info); printf ("\n");
3437 //g_hash_table_print_stats (acfg->patch_to_plt_entry);
3439 acfg->plt_offset ++;
3448 * Returns the offset of the GOT slot where the runtime object resulting from resolving
3449 * JI could be found if it exists, otherwise allocates a new one.
3452 get_got_offset (MonoAotCompile *acfg, gboolean llvm, MonoJumpInfo *ji)
3455 GotInfo *info = llvm ? &acfg->llvm_got_info : &acfg->got_info;
3457 got_offset = GPOINTER_TO_UINT (g_hash_table_lookup (info->patch_to_got_offset_by_type [ji->type], ji));
3459 return got_offset - 1;
3462 got_offset = acfg->llvm_got_offset;
3463 acfg->llvm_got_offset ++;
3465 got_offset = acfg->got_offset;
3466 acfg->got_offset ++;
3469 acfg->stats.got_slots ++;
3470 acfg->stats.got_slot_types [ji->type] ++;
3472 g_hash_table_insert (info->patch_to_got_offset, ji, GUINT_TO_POINTER (got_offset + 1));
3473 g_hash_table_insert (info->patch_to_got_offset_by_type [ji->type], ji, GUINT_TO_POINTER (got_offset + 1));
3474 g_ptr_array_add (info->got_patches, ji);
3479 /* Add a method to the list of methods which need to be emitted */
3481 add_method_with_index (MonoAotCompile *acfg, MonoMethod *method, int index, gboolean extra)
3484 if (!g_hash_table_lookup (acfg->method_indexes, method)) {
3485 g_ptr_array_add (acfg->methods, method);
3486 g_hash_table_insert (acfg->method_indexes, method, GUINT_TO_POINTER (index + 1));
3487 acfg->nmethods = acfg->methods->len + 1;
3490 if (method->wrapper_type || extra)
3491 g_ptr_array_add (acfg->extra_methods, method);
3495 prefer_gsharedvt_method (MonoAotCompile *acfg, MonoMethod *method)
3497 /* One instantiation with valuetypes is generated for each async method */
3498 if (method->klass->image == mono_defaults.corlib && (!strcmp (method->klass->name, "AsyncMethodBuilderCore") || !strcmp (method->klass->name, "AsyncVoidMethodBuilder")))
3505 get_method_index (MonoAotCompile *acfg, MonoMethod *method)
3507 int index = GPOINTER_TO_UINT (g_hash_table_lookup (acfg->method_indexes, method));
3515 add_method_full (MonoAotCompile *acfg, MonoMethod *method, gboolean extra, int depth)
3519 index = GPOINTER_TO_UINT (g_hash_table_lookup (acfg->method_indexes, method));
3523 index = acfg->method_index;
3524 add_method_with_index (acfg, method, index, extra);
3526 g_ptr_array_add (acfg->method_order, GUINT_TO_POINTER (index));
3528 g_hash_table_insert (acfg->method_depth, method, GUINT_TO_POINTER (depth));
3530 acfg->method_index ++;
3536 add_method (MonoAotCompile *acfg, MonoMethod *method)
3538 return add_method_full (acfg, method, FALSE, 0);
3542 add_extra_method_with_depth (MonoAotCompile *acfg, MonoMethod *method, int depth)
3544 if (mono_method_is_generic_sharable_full (method, TRUE, TRUE, FALSE))
3545 method = mini_get_shared_method (method);
3546 else if ((acfg->opts & MONO_OPT_GSHAREDVT) && prefer_gsharedvt_method (acfg, method) && mono_method_is_generic_sharable_full (method, FALSE, FALSE, TRUE))
3547 /* Use the gsharedvt version */
3548 method = mini_get_shared_method_full (method, TRUE, TRUE);
3550 if (acfg->aot_opts.log_generics)
3551 aot_printf (acfg, "%*sAdding method %s.\n", depth, "", mono_method_get_full_name (method));
3553 add_method_full (acfg, method, TRUE, depth);
3557 add_extra_method (MonoAotCompile *acfg, MonoMethod *method)
3559 add_extra_method_with_depth (acfg, method, 0);
3563 add_jit_icall_wrapper (gpointer key, gpointer value, gpointer user_data)
3565 MonoAotCompile *acfg = (MonoAotCompile *)user_data;
3566 MonoJitICallInfo *callinfo = (MonoJitICallInfo *)value;
3567 MonoMethod *wrapper;
3573 name = g_strdup_printf ("__icall_wrapper_%s", callinfo->name);
3574 wrapper = mono_marshal_get_icall_wrapper (callinfo->sig, name, callinfo->func, TRUE);
3577 add_method (acfg, wrapper);
3581 get_runtime_invoke_sig (MonoMethodSignature *sig)
3583 MonoMethodBuilder *mb;
3586 mb = mono_mb_new (mono_defaults.object_class, "FOO", MONO_WRAPPER_NONE);
3587 m = mono_mb_create_method (mb, sig, 16);
3588 return mono_marshal_get_runtime_invoke (m, FALSE);
3592 get_runtime_invoke (MonoAotCompile *acfg, MonoMethod *method, gboolean virtual_)
3594 return mono_marshal_get_runtime_invoke (method, virtual_);
3598 can_marshal_struct (MonoClass *klass)
3600 MonoClassField *field;
3601 gboolean can_marshal = TRUE;
3602 gpointer iter = NULL;
3603 MonoMarshalType *info;
3606 if ((klass->flags & TYPE_ATTRIBUTE_LAYOUT_MASK) == TYPE_ATTRIBUTE_AUTO_LAYOUT)
3609 info = mono_marshal_load_type_info (klass);
3611 /* Only allow a few field types to avoid asserts in the marshalling code */
3612 while ((field = mono_class_get_fields (klass, &iter))) {
3613 if ((field->type->attrs & FIELD_ATTRIBUTE_STATIC))
3616 switch (field->type->type) {
3621 case MONO_TYPE_BOOLEAN:
3624 case MONO_TYPE_CHAR:
3632 case MONO_TYPE_STRING:
3634 case MONO_TYPE_VALUETYPE:
3635 if (!mono_class_from_mono_type (field->type)->enumtype && !can_marshal_struct (mono_class_from_mono_type (field->type)))
3636 can_marshal = FALSE;
3638 case MONO_TYPE_SZARRAY: {
3639 gboolean has_mspec = FALSE;
3642 for (i = 0; i < info->num_fields; ++i) {
3643 if (info->fields [i].field == field && info->fields [i].mspec)
3648 can_marshal = FALSE;
3652 can_marshal = FALSE;
3658 /* Its hard to compute whenever these can be marshalled or not */
3659 if (!strcmp (klass->name_space, "System.Net.NetworkInformation.MacOsStructs") && strcmp (klass->name, "sockaddr_dl"))
3666 create_gsharedvt_inst (MonoAotCompile *acfg, MonoMethod *method, MonoGenericContext *ctx)
3668 /* Create a vtype instantiation */
3669 MonoGenericContext shared_context;
3671 MonoGenericInst *inst;
3672 MonoGenericContainer *container;
3673 MonoClass **constraints;
3676 memset (ctx, 0, sizeof (MonoGenericContext));
3678 if (method->klass->generic_container) {
3679 shared_context = method->klass->generic_container->context;
3680 inst = shared_context.class_inst;
3682 args = g_new0 (MonoType*, inst->type_argc);
3683 for (i = 0; i < inst->type_argc; ++i) {
3684 args [i] = &mono_defaults.int_class->byval_arg;
3686 ctx->class_inst = mono_metadata_get_generic_inst (inst->type_argc, args);
3688 if (method->is_generic) {
3689 container = mono_method_get_generic_container (method);
3690 shared_context = container->context;
3691 inst = shared_context.method_inst;
3693 args = g_new0 (MonoType*, inst->type_argc);
3694 for (i = 0; i < container->type_argc; ++i) {
3695 MonoGenericParamInfo *info = &container->type_params [i].info;
3696 gboolean ref_only = FALSE;
3698 if (info && info->constraints) {
3699 constraints = info->constraints;
3701 while (*constraints) {
3702 MonoClass *cklass = *constraints;
3703 if (!(cklass == mono_defaults.object_class || (cklass->image == mono_defaults.corlib && !strcmp (cklass->name, "ValueType"))))
3704 /* Inflaring the method with our vtype would not be valid */
3711 args [i] = &mono_defaults.object_class->byval_arg;
3713 args [i] = &mono_defaults.int_class->byval_arg;
3715 ctx->method_inst = mono_metadata_get_generic_inst (inst->type_argc, args);
3720 add_wrappers (MonoAotCompile *acfg)
3722 MonoMethod *method, *m;
3724 MonoMethodSignature *sig, *csig;
3728 * FIXME: Instead of AOTing all the wrappers, it might be better to redesign them
3729 * so there is only one wrapper of a given type, or inlining their contents into their
3732 for (i = 0; i < acfg->image->tables [MONO_TABLE_METHOD].rows; ++i) {
3735 guint32 token = MONO_TOKEN_METHOD_DEF | (i + 1);
3736 gboolean skip = FALSE;
3738 method = mono_get_method_checked (acfg->image, token, NULL, NULL, &error);
3739 report_loader_error (acfg, &error, "Failed to load method token 0x%x due to %s\n", i, mono_error_get_message (&error));
3741 if ((method->flags & METHOD_ATTRIBUTE_PINVOKE_IMPL) ||
3742 (method->iflags & METHOD_IMPL_ATTRIBUTE_RUNTIME) ||
3743 (method->flags & METHOD_ATTRIBUTE_ABSTRACT))
3746 /* Skip methods which can not be handled by get_runtime_invoke () */
3747 sig = mono_method_signature (method);
3750 if ((sig->ret->type == MONO_TYPE_PTR) ||
3751 (sig->ret->type == MONO_TYPE_TYPEDBYREF))
3753 if (mono_class_is_open_constructed_type (sig->ret))
3756 for (j = 0; j < sig->param_count; j++) {
3757 if (sig->params [j]->type == MONO_TYPE_TYPEDBYREF)
3759 if (mono_class_is_open_constructed_type (sig->params [j]))
3763 #ifdef MONO_ARCH_DYN_CALL_SUPPORTED
3764 if (!mono_class_is_contextbound (method->klass)) {
3765 MonoDynCallInfo *info = mono_arch_dyn_call_prepare (sig);
3766 gboolean has_nullable = FALSE;
3768 for (j = 0; j < sig->param_count; j++) {
3769 if (sig->params [j]->type == MONO_TYPE_GENERICINST && mono_class_is_nullable (mono_class_from_mono_type (sig->params [j])))
3770 has_nullable = TRUE;
3773 if (info && !has_nullable && !acfg->aot_opts.llvm_only) {
3774 /* Supported by the dynamic runtime-invoke wrapper */
3778 mono_arch_dyn_call_free (info);
3782 if (acfg->aot_opts.llvm_only)
3783 /* Supported by the gsharedvt based runtime-invoke wrapper */
3787 //printf ("%s\n", mono_method_full_name (method, TRUE));
3788 add_method (acfg, get_runtime_invoke (acfg, method, FALSE));
3792 if (strcmp (acfg->image->assembly->aname.name, "mscorlib") == 0) {
3795 /* Runtime invoke wrappers */
3797 /* void runtime-invoke () [.cctor] */
3798 csig = mono_metadata_signature_alloc (mono_defaults.corlib, 0);
3799 csig->ret = &mono_defaults.void_class->byval_arg;
3800 add_method (acfg, get_runtime_invoke_sig (csig));
3802 /* void runtime-invoke () [Finalize] */
3803 csig = mono_metadata_signature_alloc (mono_defaults.corlib, 0);
3805 csig->ret = &mono_defaults.void_class->byval_arg;
3806 add_method (acfg, get_runtime_invoke_sig (csig));
3808 /* void runtime-invoke (string) [exception ctor] */
3809 csig = mono_metadata_signature_alloc (mono_defaults.corlib, 1);
3811 csig->ret = &mono_defaults.void_class->byval_arg;
3812 csig->params [0] = &mono_defaults.string_class->byval_arg;
3813 add_method (acfg, get_runtime_invoke_sig (csig));
3815 /* void runtime-invoke (string, string) [exception ctor] */
3816 csig = mono_metadata_signature_alloc (mono_defaults.corlib, 2);
3818 csig->ret = &mono_defaults.void_class->byval_arg;
3819 csig->params [0] = &mono_defaults.string_class->byval_arg;
3820 csig->params [1] = &mono_defaults.string_class->byval_arg;
3821 add_method (acfg, get_runtime_invoke_sig (csig));
3823 /* string runtime-invoke () [Exception.ToString ()] */
3824 csig = mono_metadata_signature_alloc (mono_defaults.corlib, 0);
3826 csig->ret = &mono_defaults.string_class->byval_arg;
3827 add_method (acfg, get_runtime_invoke_sig (csig));
3829 /* void runtime-invoke (string, Exception) [exception ctor] */
3830 csig = mono_metadata_signature_alloc (mono_defaults.corlib, 2);
3832 csig->ret = &mono_defaults.void_class->byval_arg;
3833 csig->params [0] = &mono_defaults.string_class->byval_arg;
3834 csig->params [1] = &mono_defaults.exception_class->byval_arg;
3835 add_method (acfg, get_runtime_invoke_sig (csig));
3837 /* Assembly runtime-invoke (string, bool) [DoAssemblyResolve] */
3838 csig = mono_metadata_signature_alloc (mono_defaults.corlib, 2);
3840 csig->ret = &(mono_class_load_from_name (
3841 mono_defaults.corlib, "System.Reflection", "Assembly"))->byval_arg;
3842 csig->params [0] = &mono_defaults.string_class->byval_arg;
3843 csig->params [1] = &mono_defaults.boolean_class->byval_arg;
3844 add_method (acfg, get_runtime_invoke_sig (csig));
3846 /* runtime-invoke used by finalizers */
3847 add_method (acfg, get_runtime_invoke (acfg, mono_class_get_method_from_name_flags (mono_defaults.object_class, "Finalize", 0, 0), TRUE));
3849 /* This is used by mono_runtime_capture_context () */
3850 method = mono_get_context_capture_method ();
3852 add_method (acfg, get_runtime_invoke (acfg, method, FALSE));
3854 #ifdef MONO_ARCH_DYN_CALL_SUPPORTED
3855 if (!acfg->aot_opts.llvm_only)
3856 add_method (acfg, mono_marshal_get_runtime_invoke_dynamic ());
3859 /* These are used by mono_jit_runtime_invoke () to calls gsharedvt out wrappers */
3860 if (acfg->aot_opts.llvm_only) {
3863 /* Create simplified signatures which match the signature used by the gsharedvt out wrappers */
3864 for (variants = 0; variants < 4; ++variants) {
3865 for (i = 0; i < 16; ++i) {
3866 sig = mini_get_gsharedvt_out_sig_wrapper_signature ((variants & 1) > 0, (variants & 2) > 0, i);
3867 add_extra_method (acfg, mono_marshal_get_runtime_invoke_for_sig (sig));
3875 add_method (acfg, mono_marshal_get_stelemref ());
3877 if (MONO_ARCH_HAVE_TLS_GET) {
3878 /* Managed Allocators */
3879 nallocators = mono_gc_get_managed_allocator_types ();
3880 for (i = 0; i < nallocators; ++i) {
3881 if ((m = mono_gc_get_managed_allocator_by_type (i, MANAGED_ALLOCATOR_REGULAR)))
3882 add_method (acfg, m);
3883 if ((m = mono_gc_get_managed_allocator_by_type (i, MANAGED_ALLOCATOR_SLOW_PATH)))
3884 add_method (acfg, m);
3888 /* write barriers */
3889 if (mono_gc_is_moving ()) {
3890 add_method (acfg, mono_gc_get_specific_write_barrier (FALSE));
3891 add_method (acfg, mono_gc_get_specific_write_barrier (TRUE));
3894 /* Stelemref wrappers */
3896 MonoMethod **wrappers;
3899 wrappers = mono_marshal_get_virtual_stelemref_wrappers (&nwrappers);
3900 for (i = 0; i < nwrappers; ++i)
3901 add_method (acfg, wrappers [i]);
3905 /* castclass_with_check wrapper */
3906 add_method (acfg, mono_marshal_get_castclass_with_cache ());
3907 /* isinst_with_check wrapper */
3908 add_method (acfg, mono_marshal_get_isinst_with_cache ());
3910 /* JIT icall wrappers */
3911 /* FIXME: locking - this is "safe" as full-AOT threads don't mutate the icall hash*/
3912 g_hash_table_foreach (mono_get_jit_icall_info (), add_jit_icall_wrapper, acfg);
3916 * remoting-invoke-with-check wrappers are very frequent, so avoid emitting them,
3917 * we use the original method instead at runtime.
3918 * Since full-aot doesn't support remoting, this is not a problem.
3921 /* remoting-invoke wrappers */
3922 for (i = 0; i < acfg->image->tables [MONO_TABLE_METHOD].rows; ++i) {
3924 MonoMethodSignature *sig;
3926 token = MONO_TOKEN_METHOD_DEF | (i + 1);
3927 method = mono_get_method_checked (acfg->image, token, NULL, NULL, &error);
3928 g_assert (mono_error_ok (&error)); /* FIXME don't swallow the error */
3930 sig = mono_method_signature (method);
3932 if (sig->hasthis && (method->klass->marshalbyref || method->klass == mono_defaults.object_class)) {
3933 m = mono_marshal_get_remoting_invoke_with_check (method);
3935 add_method (acfg, m);
3940 /* delegate-invoke wrappers */
3941 for (i = 0; i < acfg->image->tables [MONO_TABLE_TYPEDEF].rows; ++i) {
3944 MonoCustomAttrInfo *cattr;
3946 token = MONO_TOKEN_TYPE_DEF | (i + 1);
3947 klass = mono_class_get_checked (acfg->image, token, &error);
3950 mono_error_cleanup (&error);
3954 if (!klass->delegate || klass == mono_defaults.delegate_class || klass == mono_defaults.multicastdelegate_class)
3957 if (!klass->generic_container) {
3958 method = mono_get_delegate_invoke (klass);
3960 m = mono_marshal_get_delegate_invoke (method, NULL);
3962 add_method (acfg, m);
3964 method = mono_class_get_method_from_name_flags (klass, "BeginInvoke", -1, 0);
3966 add_method (acfg, mono_marshal_get_delegate_begin_invoke (method));
3968 method = mono_class_get_method_from_name_flags (klass, "EndInvoke", -1, 0);
3970 add_method (acfg, mono_marshal_get_delegate_end_invoke (method));
3972 cattr = mono_custom_attrs_from_class_checked (klass, &error);
3973 if (!is_ok (&error)) {
3974 mono_error_cleanup (&error);
3981 for (j = 0; j < cattr->num_attrs; ++j)
3982 if (cattr->attrs [j].ctor && (!strcmp (cattr->attrs [j].ctor->klass->name, "MonoNativeFunctionWrapperAttribute") || !strcmp (cattr->attrs [j].ctor->klass->name, "UnmanagedFunctionPointerAttribute")))
3984 if (j < cattr->num_attrs) {
3986 MonoMethod *wrapper;
3987 MonoMethod *del_invoke;
3989 /* Add wrappers needed by mono_ftnptr_to_delegate () */
3990 invoke = mono_get_delegate_invoke (klass);
3991 wrapper = mono_marshal_get_native_func_wrapper_aot (klass);
3992 del_invoke = mono_marshal_get_delegate_invoke_internal (invoke, FALSE, TRUE, wrapper);
3993 add_method (acfg, wrapper);
3994 add_method (acfg, del_invoke);
3997 } else if ((acfg->opts & MONO_OPT_GSHAREDVT) && klass->generic_container) {
3999 MonoGenericContext ctx;
4000 MonoMethod *inst, *gshared;
4003 * Emit gsharedvt versions of the generic delegate-invoke wrappers
4006 method = mono_get_delegate_invoke (klass);
4007 create_gsharedvt_inst (acfg, method, &ctx);
4009 inst = mono_class_inflate_generic_method_checked (method, &ctx, &error);
4010 g_assert (mono_error_ok (&error)); /* FIXME don't swallow the error */
4012 m = mono_marshal_get_delegate_invoke (inst, NULL);
4013 g_assert (m->is_inflated);
4015 gshared = mini_get_shared_method_full (m, FALSE, TRUE);
4016 add_extra_method (acfg, gshared);
4019 method = mono_get_delegate_begin_invoke (klass);
4020 create_gsharedvt_inst (acfg, method, &ctx);
4022 inst = mono_class_inflate_generic_method_checked (method, &ctx, &error);
4023 g_assert (mono_error_ok (&error)); /* FIXME don't swallow the error */
4025 m = mono_marshal_get_delegate_begin_invoke (inst);
4026 g_assert (m->is_inflated);
4028 gshared = mini_get_shared_method_full (m, FALSE, TRUE);
4029 add_extra_method (acfg, gshared);
4032 method = mono_get_delegate_end_invoke (klass);
4033 create_gsharedvt_inst (acfg, method, &ctx);
4035 inst = mono_class_inflate_generic_method_checked (method, &ctx, &error);
4036 g_assert (mono_error_ok (&error)); /* FIXME don't swallow the error */
4038 m = mono_marshal_get_delegate_end_invoke (inst);
4039 g_assert (m->is_inflated);
4041 gshared = mini_get_shared_method_full (m, FALSE, TRUE);
4042 add_extra_method (acfg, gshared);
4047 /* array access wrappers */
4048 for (i = 0; i < acfg->image->tables [MONO_TABLE_TYPESPEC].rows; ++i) {
4052 token = MONO_TOKEN_TYPE_SPEC | (i + 1);
4053 klass = mono_class_get_checked (acfg->image, token, &error);
4056 mono_error_cleanup (&error);
4060 if (klass->rank && MONO_TYPE_IS_PRIMITIVE (&klass->element_class->byval_arg)) {
4061 MonoMethod *m, *wrapper;
4063 /* Add runtime-invoke wrappers too */
4065 m = mono_class_get_method_from_name (klass, "Get", -1);
4067 wrapper = mono_marshal_get_array_accessor_wrapper (m);
4068 add_extra_method (acfg, wrapper);
4069 if (!acfg->aot_opts.llvm_only)
4070 add_extra_method (acfg, get_runtime_invoke (acfg, wrapper, FALSE));
4072 m = mono_class_get_method_from_name (klass, "Set", -1);
4074 wrapper = mono_marshal_get_array_accessor_wrapper (m);
4075 add_extra_method (acfg, wrapper);
4076 if (!acfg->aot_opts.llvm_only)
4077 add_extra_method (acfg, get_runtime_invoke (acfg, wrapper, FALSE));
4081 /* Synchronized wrappers */
4082 for (i = 0; i < acfg->image->tables [MONO_TABLE_METHOD].rows; ++i) {
4084 token = MONO_TOKEN_METHOD_DEF | (i + 1);
4085 method = mono_get_method_checked (acfg->image, token, NULL, NULL, &error);
4086 report_loader_error (acfg, &error, "Failed to load method token 0x%x due to %s\n", i, mono_error_get_message (&error));
4088 if (method->iflags & METHOD_IMPL_ATTRIBUTE_SYNCHRONIZED) {
4089 if (method->is_generic) {
4091 } else if ((acfg->opts & MONO_OPT_GSHAREDVT) && method->klass->generic_container) {
4093 MonoGenericContext ctx;
4094 MonoMethod *inst, *gshared, *m;
4097 * Create a generic wrapper for a generic instance, and AOT that.
4099 create_gsharedvt_inst (acfg, method, &ctx);
4100 inst = mono_class_inflate_generic_method_checked (method, &ctx, &error);
4101 g_assert (mono_error_ok (&error)); /* FIXME don't swallow the error */
4102 m = mono_marshal_get_synchronized_wrapper (inst);
4103 g_assert (m->is_inflated);
4104 gshared = mini_get_shared_method_full (m, FALSE, TRUE);
4105 add_method (acfg, gshared);
4107 add_method (acfg, mono_marshal_get_synchronized_wrapper (method));
4112 /* pinvoke wrappers */
4113 for (i = 0; i < acfg->image->tables [MONO_TABLE_METHOD].rows; ++i) {
4116 guint32 token = MONO_TOKEN_METHOD_DEF | (i + 1);
4118 method = mono_get_method_checked (acfg->image, token, NULL, NULL, &error);
4119 report_loader_error (acfg, &error, "Failed to load method token 0x%x due to %s\n", i, mono_error_get_message (&error));
4121 if ((method->flags & METHOD_ATTRIBUTE_PINVOKE_IMPL) ||
4122 (method->iflags & METHOD_IMPL_ATTRIBUTE_INTERNAL_CALL)) {
4123 add_method (acfg, mono_marshal_get_native_wrapper (method, TRUE, TRUE));
4127 /* native-to-managed wrappers */
4128 for (i = 0; i < acfg->image->tables [MONO_TABLE_METHOD].rows; ++i) {
4131 guint32 token = MONO_TOKEN_METHOD_DEF | (i + 1);
4132 MonoCustomAttrInfo *cattr;
4135 method = mono_get_method_checked (acfg->image, token, NULL, NULL, &error);
4136 report_loader_error (acfg, &error, "Failed to load method token 0x%x due to %s\n", i, mono_error_get_message (&error));
4139 * Only generate native-to-managed wrappers for methods which have an
4140 * attribute named MonoPInvokeCallbackAttribute. We search for the attribute by
4141 * name to avoid defining a new assembly to contain it.
4143 cattr = mono_custom_attrs_from_method_checked (method, &error);
4144 if (!is_ok (&error)) {
4145 char *name = mono_method_get_full_name (method);
4146 report_loader_error (acfg, &error, "Failed to load custom attributes from method %s due to %s\n", name, mono_error_get_message (&error));
4151 for (j = 0; j < cattr->num_attrs; ++j)
4152 if (cattr->attrs [j].ctor && !strcmp (cattr->attrs [j].ctor->klass->name, "MonoPInvokeCallbackAttribute"))
4154 if (j < cattr->num_attrs) {
4155 MonoCustomAttrEntry *e = &cattr->attrs [j];
4156 MonoMethodSignature *sig = mono_method_signature (e->ctor);
4157 const char *p = (const char*)e->data;
4159 int slen, num_named, named_type;
4163 char *export_name = NULL;
4164 MonoMethod *wrapper;
4166 /* this cannot be enforced by the C# compiler so we must give the user some warning before aborting */
4167 if (!(method->flags & METHOD_ATTRIBUTE_STATIC)) {
4168 g_warning ("AOT restriction: Method '%s' must be static since it is decorated with [MonoPInvokeCallback]. See http://ios.xamarin.com/Documentation/Limitations#Reverse_Callbacks",
4169 mono_method_full_name (method, TRUE));
4173 g_assert (sig->param_count == 1);
4174 g_assert (sig->params [0]->type == MONO_TYPE_CLASS && !strcmp (mono_class_from_mono_type (sig->params [0])->name, "Type"));
4177 * Decode the cattr manually since we can't create objects
4178 * during aot compilation.
4184 /* From load_cattr_value () in reflection.c */
4185 slen = mono_metadata_decode_value (p, &p);
4186 n = (char *)g_memdup (p, slen + 1);
4188 t = mono_reflection_type_from_name_checked (n, acfg->image, &error);
4190 mono_error_assert_ok (&error);
4193 klass = mono_class_from_mono_type (t);
4194 g_assert (klass->parent == mono_defaults.multicastdelegate_class);
4198 num_named = read16 (p);
4201 g_assert (num_named < 2);
4202 if (num_named == 1) {
4206 /* parse ExportSymbol attribute */
4208 named_type = *named;
4210 /* data_type = *named; */
4213 name_len = mono_metadata_decode_blob_size (named, &named);
4214 name = (char *)g_malloc (name_len + 1);
4215 memcpy (name, named, name_len);
4216 name [name_len] = 0;
4219 g_assert (named_type == 0x54);
4220 g_assert (!strcmp (name, "ExportSymbol"));
4222 /* load_cattr_value (), string case */
4223 g_assert (*named != (char)0xff);
4224 slen = mono_metadata_decode_value (named, &named);
4225 export_name = (char *)g_malloc (slen + 1);
4226 memcpy (export_name, named, slen);
4227 export_name [slen] = 0;
4231 wrapper = mono_marshal_get_managed_wrapper (method, klass, 0);
4232 add_method (acfg, wrapper);
4234 g_hash_table_insert (acfg->export_names, wrapper, export_name);
4238 if ((method->flags & METHOD_ATTRIBUTE_PINVOKE_IMPL) ||
4239 (method->iflags & METHOD_IMPL_ATTRIBUTE_INTERNAL_CALL)) {
4240 add_method (acfg, mono_marshal_get_native_wrapper (method, TRUE, TRUE));
4244 /* StructureToPtr/PtrToStructure wrappers */
4245 for (i = 0; i < acfg->image->tables [MONO_TABLE_TYPEDEF].rows; ++i) {
4249 token = MONO_TOKEN_TYPE_DEF | (i + 1);
4250 klass = mono_class_get_checked (acfg->image, token, &error);
4253 mono_error_cleanup (&error);
4257 if (klass->valuetype && !klass->generic_container && can_marshal_struct (klass) &&
4258 !(klass->nested_in && strstr (klass->nested_in->name, "<PrivateImplementationDetails>") == klass->nested_in->name)) {
4259 add_method (acfg, mono_marshal_get_struct_to_ptr (klass));
4260 add_method (acfg, mono_marshal_get_ptr_to_struct (klass));
4266 has_type_vars (MonoClass *klass)
4268 if ((klass->byval_arg.type == MONO_TYPE_VAR) || (klass->byval_arg.type == MONO_TYPE_MVAR))
4271 return has_type_vars (klass->element_class);
4272 if (klass->generic_class) {
4273 MonoGenericContext *context = &klass->generic_class->context;
4274 if (context->class_inst) {
4277 for (i = 0; i < context->class_inst->type_argc; ++i)
4278 if (has_type_vars (mono_class_from_mono_type (context->class_inst->type_argv [i])))
4282 if (klass->generic_container)
4288 is_vt_inst (MonoGenericInst *inst)
4292 for (i = 0; i < inst->type_argc; ++i) {
4293 MonoType *t = inst->type_argv [i];
4294 if (MONO_TYPE_ISSTRUCT (t) || t->type == MONO_TYPE_VALUETYPE)
4301 method_has_type_vars (MonoMethod *method)
4303 if (has_type_vars (method->klass))
4306 if (method->is_inflated) {
4307 MonoGenericContext *context = mono_method_get_context (method);
4308 if (context->method_inst) {
4311 for (i = 0; i < context->method_inst->type_argc; ++i)
4312 if (has_type_vars (mono_class_from_mono_type (context->method_inst->type_argv [i])))
4320 gboolean mono_aot_mode_is_full (MonoAotOptions *opts)
4322 return opts->mode == MONO_AOT_MODE_FULL;
4325 static void add_generic_class_with_depth (MonoAotCompile *acfg, MonoClass *klass, int depth, const char *ref);
4328 add_generic_class (MonoAotCompile *acfg, MonoClass *klass, gboolean force, const char *ref)
4330 /* This might lead to a huge code blowup so only do it if neccesary */
4331 if (!mono_aot_mode_is_full (&acfg->aot_opts) && !force)
4334 add_generic_class_with_depth (acfg, klass, 0, ref);
4338 check_type_depth (MonoType *t, int depth)
4346 case MONO_TYPE_GENERICINST: {
4347 MonoGenericClass *gklass = t->data.generic_class;
4348 MonoGenericInst *ginst = gklass->context.class_inst;
4351 for (i = 0; i < ginst->type_argc; ++i) {
4352 if (check_type_depth (ginst->type_argv [i], depth + 1))
4366 add_types_from_method_header (MonoAotCompile *acfg, MonoMethod *method);
4369 * add_generic_class:
4371 * Add all methods of a generic class.
4374 add_generic_class_with_depth (MonoAotCompile *acfg, MonoClass *klass, int depth, const char *ref)
4377 MonoClassField *field;
4379 gboolean use_gsharedvt = FALSE;
4381 if (!acfg->ginst_hash)
4382 acfg->ginst_hash = g_hash_table_new (NULL, NULL);
4384 mono_class_init (klass);
4386 if (klass->generic_class && klass->generic_class->context.class_inst->is_open)
4389 if (has_type_vars (klass))
4392 if (!klass->generic_class && !klass->rank)
4395 if (mono_class_has_failure (klass))
4398 if (!acfg->ginst_hash)
4399 acfg->ginst_hash = g_hash_table_new (NULL, NULL);
4401 if (g_hash_table_lookup (acfg->ginst_hash, klass))
4404 if (check_type_depth (&klass->byval_arg, 0))
4407 if (acfg->aot_opts.log_generics)
4408 aot_printf (acfg, "%*sAdding generic instance %s [%s].\n", depth, "", mono_type_full_name (&klass->byval_arg), ref);
4410 g_hash_table_insert (acfg->ginst_hash, klass, klass);
4413 * Use gsharedvt for generic collections with vtype arguments to avoid code blowup.
4414 * Enable this only for some classes since gsharedvt might not support all methods.
4416 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) &&
4417 (!strcmp (klass->name, "Dictionary`2") || !strcmp (klass->name, "List`1") || !strcmp (klass->name, "ReadOnlyCollection`1")))
4418 use_gsharedvt = TRUE;
4421 while ((method = mono_class_get_methods (klass, &iter))) {
4422 if ((acfg->opts & MONO_OPT_GSHAREDVT) && method->is_inflated && mono_method_get_context (method)->method_inst) {
4424 * This is partial sharing, and we can't handle it yet
4429 if (mono_method_is_generic_sharable_full (method, FALSE, FALSE, use_gsharedvt)) {
4431 add_types_from_method_header (acfg, method);
4435 if (method->is_generic)
4440 * FIXME: Instances which are referenced by these methods are not added,
4441 * for example Array.Resize<int> for List<int>.Add ().
4443 add_extra_method_with_depth (acfg, method, depth + 1);
4447 while ((field = mono_class_get_fields (klass, &iter))) {
4448 if (field->type->type == MONO_TYPE_GENERICINST)
4449 add_generic_class_with_depth (acfg, mono_class_from_mono_type (field->type), depth + 1, "field");
4452 if (klass->delegate) {
4453 method = mono_get_delegate_invoke (klass);
4455 method = mono_marshal_get_delegate_invoke (method, NULL);
4457 if (acfg->aot_opts.log_generics)
4458 aot_printf (acfg, "%*sAdding method %s.\n", depth, "", mono_method_get_full_name (method));
4460 add_method (acfg, method);
4463 /* Add superclasses */
4465 add_generic_class_with_depth (acfg, klass->parent, depth, "parent");
4468 * For ICollection<T>, add instances of the helper methods
4469 * in Array, since a T[] could be cast to ICollection<T>.
4471 if (klass->image == mono_defaults.corlib && !strcmp (klass->name_space, "System.Collections.Generic") &&
4472 (!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"))) {
4473 MonoClass *tclass = mono_class_from_mono_type (klass->generic_class->context.class_inst->type_argv [0]);
4474 MonoClass *array_class = mono_bounded_array_class_get (tclass, 1, FALSE);
4478 if (!strcmp (klass->name, "IEnumerator`1"))
4479 name_prefix = g_strdup_printf ("%s.%s", klass->name_space, "IEnumerable`1");
4481 name_prefix = g_strdup_printf ("%s.%s", klass->name_space, klass->name);
4483 /* Add the T[]/InternalEnumerator class */
4484 if (!strcmp (klass->name, "IEnumerable`1") || !strcmp (klass->name, "IEnumerator`1")) {
4489 while ((nclass = mono_class_get_nested_types (array_class->parent, &iter))) {
4490 if (!strcmp (nclass->name, "InternalEnumerator`1"))
4494 nclass = mono_class_inflate_generic_class_checked (nclass, mono_generic_class_get_context (klass->generic_class), &error);
4495 mono_error_assert_ok (&error); /* FIXME don't swallow the error */
4496 add_generic_class (acfg, nclass, FALSE, "ICollection<T>");
4500 while ((method = mono_class_get_methods (array_class, &iter))) {
4501 if (strstr (method->name, name_prefix)) {
4502 MonoMethod *m = mono_aot_get_array_helper_from_wrapper (method);
4504 add_extra_method_with_depth (acfg, m, depth);
4508 g_free (name_prefix);
4511 /* Add an instance of GenericComparer<T> which is created dynamically by Comparer<T> */
4512 if (klass->image == mono_defaults.corlib && !strcmp (klass->name_space, "System.Collections.Generic") && !strcmp (klass->name, "Comparer`1")) {
4514 MonoClass *tclass = mono_class_from_mono_type (klass->generic_class->context.class_inst->type_argv [0]);
4515 MonoClass *icomparable, *gcomparer, *icomparable_inst;
4516 MonoGenericContext ctx;
4517 MonoType *args [16];
4519 memset (&ctx, 0, sizeof (ctx));
4521 icomparable = mono_class_load_from_name (mono_defaults.corlib, "System", "IComparable`1");
4523 args [0] = &tclass->byval_arg;
4524 ctx.class_inst = mono_metadata_get_generic_inst (1, args);
4526 icomparable_inst = mono_class_inflate_generic_class_checked (icomparable, &ctx, &error);
4527 mono_error_assert_ok (&error); /* FIXME don't swallow the error */
4529 if (mono_class_is_assignable_from (icomparable_inst, tclass)) {
4530 MonoClass *gcomparer_inst;
4531 gcomparer = mono_class_load_from_name (mono_defaults.corlib, "System.Collections.Generic", "GenericComparer`1");
4532 gcomparer_inst = mono_class_inflate_generic_class_checked (gcomparer, &ctx, &error);
4533 mono_error_assert_ok (&error); /* FIXME don't swallow the error */
4535 add_generic_class (acfg, gcomparer_inst, FALSE, "Comparer<T>");
4539 /* Add an instance of GenericEqualityComparer<T> which is created dynamically by EqualityComparer<T> */
4540 if (klass->image == mono_defaults.corlib && !strcmp (klass->name_space, "System.Collections.Generic") && !strcmp (klass->name, "EqualityComparer`1")) {
4542 MonoClass *tclass = mono_class_from_mono_type (klass->generic_class->context.class_inst->type_argv [0]);
4543 MonoClass *iface, *gcomparer, *iface_inst;
4544 MonoGenericContext ctx;
4545 MonoType *args [16];
4547 memset (&ctx, 0, sizeof (ctx));
4549 iface = mono_class_load_from_name (mono_defaults.corlib, "System", "IEquatable`1");
4551 args [0] = &tclass->byval_arg;
4552 ctx.class_inst = mono_metadata_get_generic_inst (1, args);
4554 iface_inst = mono_class_inflate_generic_class_checked (iface, &ctx, &error);
4555 mono_error_assert_ok (&error); /* FIXME don't swallow the error */
4557 if (mono_class_is_assignable_from (iface_inst, tclass)) {
4558 MonoClass *gcomparer_inst;
4561 gcomparer = mono_class_load_from_name (mono_defaults.corlib, "System.Collections.Generic", "GenericEqualityComparer`1");
4562 gcomparer_inst = mono_class_inflate_generic_class_checked (gcomparer, &ctx, &error);
4563 mono_error_assert_ok (&error); /* FIXME don't swallow the error */
4564 add_generic_class (acfg, gcomparer_inst, FALSE, "EqualityComparer<T>");
4568 /* Add an instance of EnumComparer<T> which is created dynamically by EqualityComparer<T> for enums */
4569 if (klass->image == mono_defaults.corlib && !strcmp (klass->name_space, "System.Collections.Generic") && !strcmp (klass->name, "EqualityComparer`1")) {
4570 MonoClass *enum_comparer;
4571 MonoClass *tclass = mono_class_from_mono_type (klass->generic_class->context.class_inst->type_argv [0]);
4572 MonoGenericContext ctx;
4573 MonoType *args [16];
4575 if (mono_class_is_enum (tclass)) {
4576 MonoClass *enum_comparer_inst;
4579 memset (&ctx, 0, sizeof (ctx));
4580 args [0] = &tclass->byval_arg;
4581 ctx.class_inst = mono_metadata_get_generic_inst (1, args);
4583 enum_comparer = mono_class_load_from_name (mono_defaults.corlib, "System.Collections.Generic", "EnumEqualityComparer`1");
4584 enum_comparer_inst = mono_class_inflate_generic_class_checked (enum_comparer, &ctx, &error);
4585 mono_error_assert_ok (&error); /* FIXME don't swallow the error */
4586 add_generic_class (acfg, enum_comparer_inst, FALSE, "EqualityComparer<T>");
4590 /* Add an instance of ObjectComparer<T> which is created dynamically by Comparer<T> for enums */
4591 if (klass->image == mono_defaults.corlib && !strcmp (klass->name_space, "System.Collections.Generic") && !strcmp (klass->name, "Comparer`1")) {
4592 MonoClass *comparer;
4593 MonoClass *tclass = mono_class_from_mono_type (klass->generic_class->context.class_inst->type_argv [0]);
4594 MonoGenericContext ctx;
4595 MonoType *args [16];
4597 if (mono_class_is_enum (tclass)) {
4598 MonoClass *comparer_inst;
4601 memset (&ctx, 0, sizeof (ctx));
4602 args [0] = &tclass->byval_arg;
4603 ctx.class_inst = mono_metadata_get_generic_inst (1, args);
4605 comparer = mono_class_load_from_name (mono_defaults.corlib, "System.Collections.Generic", "ObjectComparer`1");
4606 comparer_inst = mono_class_inflate_generic_class_checked (comparer, &ctx, &error);
4607 mono_error_assert_ok (&error); /* FIXME don't swallow the error */
4608 add_generic_class (acfg, comparer_inst, FALSE, "Comparer<T>");
4614 add_instances_of (MonoAotCompile *acfg, MonoClass *klass, MonoType **insts, int ninsts, gboolean force)
4617 MonoGenericContext ctx;
4618 MonoType *args [16];
4620 if (acfg->aot_opts.no_instances)
4623 memset (&ctx, 0, sizeof (ctx));
4625 for (i = 0; i < ninsts; ++i) {
4627 MonoClass *generic_inst;
4628 args [0] = insts [i];
4629 ctx.class_inst = mono_metadata_get_generic_inst (1, args);
4630 generic_inst = mono_class_inflate_generic_class_checked (klass, &ctx, &error);
4631 mono_error_assert_ok (&error); /* FIXME don't swallow the error */
4632 add_generic_class (acfg, generic_inst, force, "");
4637 add_types_from_method_header (MonoAotCompile *acfg, MonoMethod *method)
4640 MonoMethodHeader *header;
4641 MonoMethodSignature *sig;
4644 depth = GPOINTER_TO_UINT (g_hash_table_lookup (acfg->method_depth, method));
4646 sig = mono_method_signature (method);
4649 for (j = 0; j < sig->param_count; ++j)
4650 if (sig->params [j]->type == MONO_TYPE_GENERICINST)
4651 add_generic_class_with_depth (acfg, mono_class_from_mono_type (sig->params [j]), depth + 1, "arg");
4654 header = mono_method_get_header_checked (method, &error);
4657 for (j = 0; j < header->num_locals; ++j)
4658 if (header->locals [j]->type == MONO_TYPE_GENERICINST)
4659 add_generic_class_with_depth (acfg, mono_class_from_mono_type (header->locals [j]), depth + 1, "local");
4661 mono_error_cleanup (&error); /* FIXME report the error */
4666 * add_generic_instances:
4668 * Add instances referenced by the METHODSPEC/TYPESPEC table.
4671 add_generic_instances (MonoAotCompile *acfg)
4676 MonoGenericContext *context;
4678 if (acfg->aot_opts.no_instances)
4681 for (i = 0; i < acfg->image->tables [MONO_TABLE_METHODSPEC].rows; ++i) {
4683 token = MONO_TOKEN_METHOD_SPEC | (i + 1);
4684 method = mono_get_method_checked (acfg->image, token, NULL, NULL, &error);
4687 aot_printerrf (acfg, "Failed to load methodspec 0x%x due to %s.\n", token, mono_error_get_message (&error));
4688 aot_printerrf (acfg, "Run with MONO_LOG_LEVEL=debug for more information.\n");
4689 mono_error_cleanup (&error);
4693 if (method->klass->image != acfg->image)
4696 context = mono_method_get_context (method);
4698 if (context && ((context->class_inst && context->class_inst->is_open)))
4702 * For open methods, create an instantiation which can be passed to the JIT.
4703 * FIXME: Handle class_inst as well.
4705 if (context && context->method_inst && context->method_inst->is_open) {
4707 MonoGenericContext shared_context;
4708 MonoGenericInst *inst;
4709 MonoType **type_argv;
4711 MonoMethod *declaring_method;
4712 gboolean supported = TRUE;
4714 /* Check that the context doesn't contain open constructed types */
4715 if (context->class_inst) {
4716 inst = context->class_inst;
4717 for (i = 0; i < inst->type_argc; ++i) {
4718 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)
4720 if (mono_class_is_open_constructed_type (inst->type_argv [i]))
4724 if (context->method_inst) {
4725 inst = context->method_inst;
4726 for (i = 0; i < inst->type_argc; ++i) {
4727 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)
4729 if (mono_class_is_open_constructed_type (inst->type_argv [i]))
4737 memset (&shared_context, 0, sizeof (MonoGenericContext));
4739 inst = context->class_inst;
4741 type_argv = g_new0 (MonoType*, inst->type_argc);
4742 for (i = 0; i < inst->type_argc; ++i) {
4743 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)
4744 type_argv [i] = &mono_defaults.object_class->byval_arg;
4746 type_argv [i] = inst->type_argv [i];
4749 shared_context.class_inst = mono_metadata_get_generic_inst (inst->type_argc, type_argv);
4753 inst = context->method_inst;
4755 type_argv = g_new0 (MonoType*, inst->type_argc);
4756 for (i = 0; i < inst->type_argc; ++i) {
4757 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)
4758 type_argv [i] = &mono_defaults.object_class->byval_arg;
4760 type_argv [i] = inst->type_argv [i];
4763 shared_context.method_inst = mono_metadata_get_generic_inst (inst->type_argc, type_argv);
4767 if (method->is_generic || method->klass->generic_container)
4768 declaring_method = method;
4770 declaring_method = mono_method_get_declaring_generic_method (method);
4772 method = mono_class_inflate_generic_method_checked (declaring_method, &shared_context, &error);
4773 g_assert (mono_error_ok (&error)); /* FIXME don't swallow the error */
4777 * If the method is fully sharable, it was already added in place of its
4778 * generic definition.
4780 if (mono_method_is_generic_sharable_full (method, FALSE, FALSE, FALSE))
4784 * FIXME: Partially shared methods are not shared here, so we end up with
4785 * many identical methods.
4787 add_extra_method (acfg, method);
4790 for (i = 0; i < acfg->image->tables [MONO_TABLE_TYPESPEC].rows; ++i) {
4794 token = MONO_TOKEN_TYPE_SPEC | (i + 1);
4796 klass = mono_class_get_checked (acfg->image, token, &error);
4797 if (!klass || klass->rank) {
4798 mono_error_cleanup (&error);
4802 add_generic_class (acfg, klass, FALSE, "typespec");
4805 /* Add types of args/locals */
4806 for (i = 0; i < acfg->methods->len; ++i) {
4807 method = (MonoMethod *)g_ptr_array_index (acfg->methods, i);
4808 add_types_from_method_header (acfg, method);
4811 if (acfg->image == mono_defaults.corlib) {
4813 MonoType *insts [256];
4816 insts [ninsts ++] = &mono_defaults.byte_class->byval_arg;
4817 insts [ninsts ++] = &mono_defaults.sbyte_class->byval_arg;
4818 insts [ninsts ++] = &mono_defaults.int16_class->byval_arg;
4819 insts [ninsts ++] = &mono_defaults.uint16_class->byval_arg;
4820 insts [ninsts ++] = &mono_defaults.int32_class->byval_arg;
4821 insts [ninsts ++] = &mono_defaults.uint32_class->byval_arg;
4822 insts [ninsts ++] = &mono_defaults.int64_class->byval_arg;
4823 insts [ninsts ++] = &mono_defaults.uint64_class->byval_arg;
4824 insts [ninsts ++] = &mono_defaults.single_class->byval_arg;
4825 insts [ninsts ++] = &mono_defaults.double_class->byval_arg;
4826 insts [ninsts ++] = &mono_defaults.char_class->byval_arg;
4827 insts [ninsts ++] = &mono_defaults.boolean_class->byval_arg;
4829 /* Add GenericComparer<T> instances for primitive types for Enum.ToString () */
4830 klass = mono_class_try_load_from_name (acfg->image, "System.Collections.Generic", "GenericComparer`1");
4832 add_instances_of (acfg, klass, insts, ninsts, TRUE);
4833 klass = mono_class_try_load_from_name (acfg->image, "System.Collections.Generic", "GenericEqualityComparer`1");
4835 add_instances_of (acfg, klass, insts, ninsts, TRUE);
4837 /* Add instances of EnumEqualityComparer which are created by EqualityComparer<T> for enums */
4839 MonoClass *enum_comparer;
4840 MonoType *insts [16];
4844 insts [ninsts ++] = &mono_defaults.int32_class->byval_arg;
4845 insts [ninsts ++] = &mono_defaults.uint32_class->byval_arg;
4846 insts [ninsts ++] = &mono_defaults.uint16_class->byval_arg;
4847 insts [ninsts ++] = &mono_defaults.byte_class->byval_arg;
4848 enum_comparer = mono_class_load_from_name (mono_defaults.corlib, "System.Collections.Generic", "EnumEqualityComparer`1");
4849 add_instances_of (acfg, enum_comparer, insts, ninsts, FALSE);
4852 insts [ninsts ++] = &mono_defaults.int16_class->byval_arg;
4853 enum_comparer = mono_class_load_from_name (mono_defaults.corlib, "System.Collections.Generic", "ShortEnumEqualityComparer`1");
4854 add_instances_of (acfg, enum_comparer, insts, ninsts, FALSE);
4857 insts [ninsts ++] = &mono_defaults.sbyte_class->byval_arg;
4858 enum_comparer = mono_class_load_from_name (mono_defaults.corlib, "System.Collections.Generic", "SByteEnumEqualityComparer`1");
4859 add_instances_of (acfg, enum_comparer, insts, ninsts, FALSE);
4861 enum_comparer = mono_class_load_from_name (mono_defaults.corlib, "System.Collections.Generic", "LongEnumEqualityComparer`1");
4863 insts [ninsts ++] = &mono_defaults.int64_class->byval_arg;
4864 insts [ninsts ++] = &mono_defaults.uint64_class->byval_arg;
4865 add_instances_of (acfg, enum_comparer, insts, ninsts, FALSE);
4868 /* Add instances of the array generic interfaces for primitive types */
4869 /* This will add instances of the InternalArray_ helper methods in Array too */
4870 klass = mono_class_try_load_from_name (acfg->image, "System.Collections.Generic", "ICollection`1");
4872 add_instances_of (acfg, klass, insts, ninsts, TRUE);
4874 klass = mono_class_try_load_from_name (acfg->image, "System.Collections.Generic", "IList`1");
4876 add_instances_of (acfg, klass, insts, ninsts, TRUE);
4878 klass = mono_class_try_load_from_name (acfg->image, "System.Collections.Generic", "IEnumerable`1");
4880 add_instances_of (acfg, klass, insts, ninsts, TRUE);
4883 * Add a managed-to-native wrapper of Array.GetGenericValueImpl<object>, which is
4884 * used for all instances of GetGenericValueImpl by the AOT runtime.
4887 MonoGenericContext ctx;
4888 MonoType *args [16];
4889 MonoMethod *get_method;
4890 MonoClass *array_klass = mono_array_class_get (mono_defaults.object_class, 1)->parent;
4892 get_method = mono_class_get_method_from_name (array_klass, "GetGenericValueImpl", 2);
4896 memset (&ctx, 0, sizeof (ctx));
4897 args [0] = &mono_defaults.object_class->byval_arg;
4898 ctx.method_inst = mono_metadata_get_generic_inst (1, args);
4899 add_extra_method (acfg, mono_marshal_get_native_wrapper (mono_class_inflate_generic_method_checked (get_method, &ctx, &error), TRUE, TRUE));
4900 g_assert (mono_error_ok (&error)); /* FIXME don't swallow the error */
4904 /* Same for CompareExchange<T>/Exchange<T> */
4906 MonoGenericContext ctx;
4907 MonoType *args [16];
4909 MonoClass *interlocked_klass = mono_class_load_from_name (mono_defaults.corlib, "System.Threading", "Interlocked");
4910 gpointer iter = NULL;
4912 while ((m = mono_class_get_methods (interlocked_klass, &iter))) {
4913 if ((!strcmp (m->name, "CompareExchange") || !strcmp (m->name, "Exchange")) && m->is_generic) {
4915 memset (&ctx, 0, sizeof (ctx));
4916 args [0] = &mono_defaults.object_class->byval_arg;
4917 ctx.method_inst = mono_metadata_get_generic_inst (1, args);
4918 add_extra_method (acfg, mono_marshal_get_native_wrapper (mono_class_inflate_generic_method_checked (m, &ctx, &error), TRUE, TRUE));
4919 g_assert (mono_error_ok (&error)); /* FIXME don't swallow the error */
4924 /* Same for Volatile.Read/Write<T> */
4926 MonoGenericContext ctx;
4927 MonoType *args [16];
4929 MonoClass *volatile_klass = mono_class_try_load_from_name (mono_defaults.corlib, "System.Threading", "Volatile");
4930 gpointer iter = NULL;
4932 if (volatile_klass) {
4933 while ((m = mono_class_get_methods (volatile_klass, &iter))) {
4934 if ((!strcmp (m->name, "Read") || !strcmp (m->name, "Write")) && m->is_generic) {
4936 memset (&ctx, 0, sizeof (ctx));
4937 args [0] = &mono_defaults.object_class->byval_arg;
4938 ctx.method_inst = mono_metadata_get_generic_inst (1, args);
4939 add_extra_method (acfg, mono_marshal_get_native_wrapper (mono_class_inflate_generic_method_checked (m, &ctx, &error), TRUE, TRUE));
4940 g_assert (mono_error_ok (&error)); /* FIXME don't swallow the error */
4946 /* object[] accessor wrappers. */
4947 for (i = 1; i < 4; ++i) {
4948 MonoClass *obj_array_class = mono_array_class_get (mono_defaults.object_class, i);
4951 m = mono_class_get_method_from_name (obj_array_class, "Get", i);
4954 m = mono_marshal_get_array_accessor_wrapper (m);
4955 add_extra_method (acfg, m);
4957 m = mono_class_get_method_from_name (obj_array_class, "Address", i);
4960 m = mono_marshal_get_array_accessor_wrapper (m);
4961 add_extra_method (acfg, m);
4963 m = mono_class_get_method_from_name (obj_array_class, "Set", i + 1);
4966 m = mono_marshal_get_array_accessor_wrapper (m);
4967 add_extra_method (acfg, m);
4973 * is_direct_callable:
4975 * Return whenever the method identified by JI is directly callable without
4976 * going through the PLT.
4979 is_direct_callable (MonoAotCompile *acfg, MonoMethod *method, MonoJumpInfo *patch_info)
4981 if ((patch_info->type == MONO_PATCH_INFO_METHOD) && (patch_info->data.method->klass->image == acfg->image)) {
4982 MonoCompile *callee_cfg = (MonoCompile *)g_hash_table_lookup (acfg->method_to_cfg, patch_info->data.method);
4984 gboolean direct_callable = TRUE;
4986 if (direct_callable && !(!callee_cfg->has_got_slots && (callee_cfg->method->klass->flags & TYPE_ATTRIBUTE_BEFORE_FIELD_INIT)))
4987 direct_callable = FALSE;
4988 if ((callee_cfg->method->iflags & METHOD_IMPL_ATTRIBUTE_SYNCHRONIZED) && (!method || method->wrapper_type != MONO_WRAPPER_SYNCHRONIZED))
4989 // FIXME: Maybe call the wrapper directly ?
4990 direct_callable = FALSE;
4992 if (acfg->aot_opts.soft_debug || acfg->aot_opts.no_direct_calls) {
4993 /* Disable this so all calls go through load_method (), see the
4994 * mini_get_debug_options ()->load_aot_jit_info_eagerly = TRUE; line in
4995 * mono_debugger_agent_init ().
4997 direct_callable = FALSE;
5000 if (callee_cfg->method->wrapper_type == MONO_WRAPPER_ALLOC)
5001 /* sgen does some initialization when the allocator method is created */
5002 direct_callable = FALSE;
5003 if (callee_cfg->method->wrapper_type == MONO_WRAPPER_WRITE_BARRIER)
5004 /* we don't know at compile time whether sgen is concurrent or not */
5005 direct_callable = FALSE;
5007 if (direct_callable)
5010 } else if ((patch_info->type == MONO_PATCH_INFO_ICALL_ADDR_CALL && patch_info->data.method->flags & METHOD_ATTRIBUTE_PINVOKE_IMPL)) {
5011 if (acfg->aot_opts.direct_pinvoke)
5013 } else if (patch_info->type == MONO_PATCH_INFO_ICALL_ADDR_CALL) {
5014 if (acfg->aot_opts.direct_icalls)
5022 #ifdef MONO_ARCH_AOT_SUPPORTED
5024 get_pinvoke_import (MonoAotCompile *acfg, MonoMethod *method)
5026 MonoImage *image = method->klass->image;
5027 MonoMethodPInvoke *piinfo = (MonoMethodPInvoke *) method;
5028 MonoTableInfo *tables = image->tables;
5029 MonoTableInfo *im = &tables [MONO_TABLE_IMPLMAP];
5030 MonoTableInfo *mr = &tables [MONO_TABLE_MODULEREF];
5031 guint32 im_cols [MONO_IMPLMAP_SIZE];
5034 import = (char *)g_hash_table_lookup (acfg->method_to_pinvoke_import, method);
5038 if (!piinfo->implmap_idx || piinfo->implmap_idx > im->rows)
5041 mono_metadata_decode_row (im, piinfo->implmap_idx - 1, im_cols, MONO_IMPLMAP_SIZE);
5043 if (!im_cols [MONO_IMPLMAP_SCOPE] || im_cols [MONO_IMPLMAP_SCOPE] > mr->rows)
5046 import = g_strdup_printf ("%s", mono_metadata_string_heap (image, im_cols [MONO_IMPLMAP_NAME]));
5048 g_hash_table_insert (acfg->method_to_pinvoke_import, method, import);
5054 get_pinvoke_import (MonoAotCompile *acfg, MonoMethod *method)
5061 compare_lne (MonoDebugLineNumberEntry *a, MonoDebugLineNumberEntry *b)
5063 if (a->native_offset == b->native_offset)
5064 return a->il_offset - b->il_offset;
5066 return a->native_offset - b->native_offset;
5070 * compute_line_numbers:
5072 * Returns a sparse array of size CODE_SIZE containing MonoDebugSourceLocation* entries for the native offsets which have a corresponding line number
5075 static MonoDebugSourceLocation**
5076 compute_line_numbers (MonoMethod *method, int code_size, MonoDebugMethodJitInfo *debug_info)
5078 MonoDebugMethodInfo *minfo;
5079 MonoDebugLineNumberEntry *ln_array;
5080 MonoDebugSourceLocation *loc;
5081 int i, prev_line, prev_il_offset;
5082 int *native_to_il_offset = NULL;
5083 MonoDebugSourceLocation **res;
5086 minfo = mono_debug_lookup_method (method);
5089 // FIXME: This seems to happen when two methods have the same cfg->method_to_register
5090 if (debug_info->code_size != code_size)
5093 g_assert (code_size);
5095 /* Compute the native->IL offset mapping */
5097 ln_array = g_new0 (MonoDebugLineNumberEntry, debug_info->num_line_numbers);
5098 memcpy (ln_array, debug_info->line_numbers, debug_info->num_line_numbers * sizeof (MonoDebugLineNumberEntry));
5100 qsort (ln_array, debug_info->num_line_numbers, sizeof (MonoDebugLineNumberEntry), (int (*)(const void *, const void *))compare_lne);
5102 native_to_il_offset = g_new0 (int, code_size + 1);
5104 for (i = 0; i < debug_info->num_line_numbers; ++i) {
5106 MonoDebugLineNumberEntry *lne = &ln_array [i];
5109 for (j = 0; j < lne->native_offset; ++j)
5110 native_to_il_offset [j] = -1;
5113 if (i < debug_info->num_line_numbers - 1) {
5114 MonoDebugLineNumberEntry *lne_next = &ln_array [i + 1];
5116 for (j = lne->native_offset; j < lne_next->native_offset; ++j)
5117 native_to_il_offset [j] = lne->il_offset;
5119 for (j = lne->native_offset; j < code_size; ++j)
5120 native_to_il_offset [j] = lne->il_offset;
5125 /* Compute the native->line number mapping */
5126 res = g_new0 (MonoDebugSourceLocation*, code_size);
5127 prev_il_offset = -1;
5130 for (i = 0; i < code_size; ++i) {
5131 int il_offset = native_to_il_offset [i];
5133 if (il_offset == -1 || il_offset == prev_il_offset)
5135 prev_il_offset = il_offset;
5136 loc = mono_debug_symfile_lookup_location (minfo, il_offset);
5137 if (!(loc && loc->source_file))
5139 if (loc->row == prev_line) {
5140 mono_debug_symfile_free_location (loc);
5143 prev_line = loc->row;
5144 //printf ("D: %s:%d il=%x native=%x\n", loc->source_file, loc->row, il_offset, i);
5146 /* This will cover the prolog too */
5156 get_file_index (MonoAotCompile *acfg, const char *source_file)
5160 // FIXME: Free these
5161 if (!acfg->dwarf_ln_filenames)
5162 acfg->dwarf_ln_filenames = g_hash_table_new (g_str_hash, g_str_equal);
5163 findex = GPOINTER_TO_INT (g_hash_table_lookup (acfg->dwarf_ln_filenames, source_file));
5165 findex = g_hash_table_size (acfg->dwarf_ln_filenames) + 1;
5166 g_hash_table_insert (acfg->dwarf_ln_filenames, g_strdup (source_file), GINT_TO_POINTER (findex));
5167 emit_unset_mode (acfg);
5168 fprintf (acfg->fp, ".file %d \"%s\"\n", findex, mono_dwarf_escape_path (source_file));
5180 * emit_and_reloc_code:
5182 * Emit the native code in CODE, handling relocations along the way. If GOT_ONLY
5183 * is true, calls are made through the GOT too. This is used for emitting trampolines
5184 * in full-aot mode, since calls made from trampolines couldn't go through the PLT,
5185 * since trampolines are needed to make PTL work.
5188 emit_and_reloc_code (MonoAotCompile *acfg, MonoMethod *method, guint8 *code, guint32 code_len, MonoJumpInfo *relocs, gboolean got_only, MonoDebugMethodJitInfo *debug_info)
5190 int i, pindex, start_index;
5192 MonoJumpInfo *patch_info;
5193 MonoDebugSourceLocation **locs = NULL;
5194 gboolean skip, prologue_end = FALSE;
5195 #ifdef MONO_ARCH_AOT_SUPPORTED
5196 gboolean direct_call, external_call;
5198 const char *direct_call_target = 0;
5199 const char *direct_pinvoke;
5202 if (acfg->gas_line_numbers && method && debug_info) {
5203 locs = compute_line_numbers (method, code_len, debug_info);
5205 int findex = get_file_index (acfg, "<unknown>");
5206 emit_unset_mode (acfg);
5207 fprintf (acfg->fp, ".loc %d %d 0\n", findex, 1);
5211 /* Collect and sort relocations */
5212 patches = g_ptr_array_new ();
5213 for (patch_info = relocs; patch_info; patch_info = patch_info->next)
5214 g_ptr_array_add (patches, patch_info);
5215 g_ptr_array_sort (patches, compare_patches);
5218 for (i = 0; i < code_len; i += INST_LEN) {
5220 for (pindex = start_index; pindex < patches->len; ++pindex) {
5221 patch_info = (MonoJumpInfo *)g_ptr_array_index (patches, pindex);
5222 if (patch_info->ip.i >= i)
5226 if (locs && locs [i]) {
5227 MonoDebugSourceLocation *loc = locs [i];
5229 const char *options;
5231 findex = get_file_index (acfg, loc->source_file);
5232 emit_unset_mode (acfg);
5234 options = " prologue_end";
5237 prologue_end = TRUE;
5238 fprintf (acfg->fp, ".loc %d %d 0%s\n", findex, loc->row, options);
5239 mono_debug_symfile_free_location (loc);
5243 #ifdef MONO_ARCH_AOT_SUPPORTED
5244 if (patch_info && (patch_info->ip.i == i) && (pindex < patches->len)) {
5245 start_index = pindex;
5247 switch (patch_info->type) {
5248 case MONO_PATCH_INFO_NONE:
5250 case MONO_PATCH_INFO_GOT_OFFSET: {
5253 arch_emit_got_offset (acfg, code + i, &code_size);
5254 i += code_size - INST_LEN;
5256 patch_info->type = MONO_PATCH_INFO_NONE;
5259 case MONO_PATCH_INFO_OBJC_SELECTOR_REF: {
5260 int code_size, index;
5261 char *selector = (char *)patch_info->data.target;
5263 if (!acfg->objc_selector_to_index)
5264 acfg->objc_selector_to_index = g_hash_table_new (g_str_hash, g_str_equal);
5265 if (!acfg->objc_selectors)
5266 acfg->objc_selectors = g_ptr_array_new ();
5267 index = GPOINTER_TO_UINT (g_hash_table_lookup (acfg->objc_selector_to_index, selector));
5271 index = acfg->objc_selector_index;
5272 g_ptr_array_add (acfg->objc_selectors, (void*)patch_info->data.target);
5273 g_hash_table_insert (acfg->objc_selector_to_index, selector, GUINT_TO_POINTER (index + 1));
5274 acfg->objc_selector_index ++;
5277 arch_emit_objc_selector_ref (acfg, code + i, index, &code_size);
5278 i += code_size - INST_LEN;
5280 patch_info->type = MONO_PATCH_INFO_NONE;
5285 * If this patch is a call, try emitting a direct call instead of
5286 * through a PLT entry. This is possible if the called method is in
5287 * the same assembly and requires no initialization.
5289 direct_call = FALSE;
5290 external_call = FALSE;
5291 if ((patch_info->type == MONO_PATCH_INFO_METHOD) && (patch_info->data.method->klass->image == acfg->image)) {
5292 if (!got_only && is_direct_callable (acfg, method, patch_info)) {
5293 MonoCompile *callee_cfg = (MonoCompile *)g_hash_table_lookup (acfg->method_to_cfg, patch_info->data.method);
5294 //printf ("DIRECT: %s %s\n", method ? mono_method_full_name (method, TRUE) : "", mono_method_full_name (callee_cfg->method, TRUE));
5296 direct_call_target = callee_cfg->asm_symbol;
5297 patch_info->type = MONO_PATCH_INFO_NONE;
5298 acfg->stats.direct_calls ++;
5301 acfg->stats.all_calls ++;
5302 } else if (patch_info->type == MONO_PATCH_INFO_ICALL_ADDR_CALL) {
5303 if (!got_only && is_direct_callable (acfg, method, patch_info)) {
5304 if (!(patch_info->data.method->flags & METHOD_ATTRIBUTE_PINVOKE_IMPL))
5305 direct_pinvoke = mono_lookup_icall_symbol (patch_info->data.method);
5307 direct_pinvoke = get_pinvoke_import (acfg, patch_info->data.method);
5308 if (direct_pinvoke) {
5310 g_assert (strlen (direct_pinvoke) < 1000);
5311 direct_call_target = g_strdup_printf ("%s%s", acfg->user_symbol_prefix, direct_pinvoke);
5314 } else if (patch_info->type == MONO_PATCH_INFO_JIT_ICALL_ADDR) {
5315 const char *sym = mono_lookup_jit_icall_symbol (patch_info->data.name);
5316 if (!got_only && sym && acfg->aot_opts.direct_icalls) {
5317 /* Call to a C function implementing a jit icall */
5319 external_call = TRUE;
5320 g_assert (strlen (sym) < 1000);
5321 direct_call_target = g_strdup_printf ("%s%s", acfg->user_symbol_prefix, sym);
5323 } else if (patch_info->type == MONO_PATCH_INFO_INTERNAL_METHOD) {
5324 MonoJitICallInfo *info = mono_find_jit_icall_by_name (patch_info->data.name);
5325 const char *sym = mono_lookup_jit_icall_symbol (patch_info->data.name);
5326 if (!got_only && sym && acfg->aot_opts.direct_icalls && info->func == info->wrapper) {
5327 /* Call to a jit icall without a wrapper */
5329 external_call = TRUE;
5330 g_assert (strlen (sym) < 1000);
5331 direct_call_target = g_strdup_printf ("%s%s", acfg->user_symbol_prefix, sym);
5336 patch_info->type = MONO_PATCH_INFO_NONE;
5337 acfg->stats.direct_calls ++;
5340 if (!got_only && !direct_call) {
5341 MonoPltEntry *plt_entry = get_plt_entry (acfg, patch_info);
5343 /* This patch has a PLT entry, so we must emit a call to the PLT entry */
5345 direct_call_target = plt_entry->symbol;
5347 /* Nullify the patch */
5348 patch_info->type = MONO_PATCH_INFO_NONE;
5349 plt_entry->jit_used = TRUE;
5356 arch_emit_direct_call (acfg, direct_call_target, external_call, FALSE, patch_info, &call_size);
5357 i += call_size - INST_LEN;
5361 got_slot = get_got_offset (acfg, FALSE, patch_info);
5363 arch_emit_got_access (acfg, acfg->got_symbol, code + i, got_slot, &code_size);
5364 i += code_size - INST_LEN;
5370 #endif /* MONO_ARCH_AOT_SUPPORTED */
5373 /* Find next patch */
5375 for (pindex = start_index; pindex < patches->len; ++pindex) {
5376 patch_info = (MonoJumpInfo *)g_ptr_array_index (patches, pindex);
5377 if (patch_info->ip.i >= i)
5381 /* Try to emit multiple bytes at once */
5382 if (pindex < patches->len && patch_info->ip.i > i) {
5385 for (limit = i + INST_LEN; limit < patch_info->ip.i; limit += INST_LEN) {
5386 if (locs && locs [limit])
5390 emit_code_bytes (acfg, code + i, limit - i);
5391 i = limit - INST_LEN;
5393 emit_code_bytes (acfg, code + i, INST_LEN);
5404 * Return a modified version of S which only includes characters permissible in symbols.
5407 sanitize_symbol (MonoAotCompile *acfg, char *s)
5409 gboolean process = FALSE;
5418 for (i = 0; i < len; ++i)
5419 if (!(s [i] <= 0x7f && (isalnum (s [i]) || s [i] == '_')))
5424 gs = g_string_sized_new (len);
5425 for (i = 0; i < len; ++i) {
5427 if (c <= 0x7f && (isalnum (c) || c == '_')) {
5428 g_string_append_c (gs, c);
5429 } else if (c > 0x7f) {
5430 /* multi-byte utf8 */
5431 g_string_append_printf (gs, "_0x%x", c);
5434 while (c >> 6 == 0x2) {
5435 g_string_append_printf (gs, "%x", c);
5439 g_string_append_printf (gs, "_");
5442 g_string_append_c (gs, '_');
5446 res = mono_mempool_strdup (acfg->mempool, gs->str);
5447 g_string_free (gs, TRUE);
5452 get_debug_sym (MonoMethod *method, const char *prefix, GHashTable *cache)
5454 char *name1, *name2, *cached;
5455 int i, j, len, count;
5456 MonoMethod *cached_method;
5458 name1 = mono_method_full_name (method, TRUE);
5461 // This is so that we don't accidentally create a local symbol (which starts with 'L')
5462 if ((!prefix || !*prefix) && name1 [0] == 'L')
5466 #if defined(TARGET_WIN32) && defined(TARGET_X86)
5467 char adjustedPrefix [MAX_SYMBOL_SIZE];
5468 prefix = mangle_symbol (prefix, adjustedPrefix, G_N_ELEMENTS (adjustedPrefix));
5471 len = strlen (name1);
5472 name2 = (char *)malloc (strlen (prefix) + len + 16);
5473 memcpy (name2, prefix, strlen (prefix));
5474 j = strlen (prefix);
5475 for (i = 0; i < len; ++i) {
5476 if (i == 0 && name1 [0] >= '0' && name1 [0] <= '9') {
5478 } else if (isalnum (name1 [i])) {
5479 name2 [j ++] = name1 [i];
5480 } else if (name1 [i] == ' ' && name1 [i + 1] == '(' && name1 [i + 2] == ')') {
5482 } else if (name1 [i] == ',' && name1 [i + 1] == ' ') {
5485 } else if (name1 [i] == '(' || name1 [i] == ')' || name1 [i] == '>') {
5495 cached_method = (MonoMethod *)g_hash_table_lookup (cache, name2);
5496 if (!(cached_method && cached_method != method))
5498 sprintf (name2 + j, "_%d", count);
5502 cached = g_strdup (name2);
5503 g_hash_table_insert (cache, cached, method);
5509 emit_method_code (MonoAotCompile *acfg, MonoCompile *cfg)
5514 char *debug_sym = NULL;
5515 char *symbol = NULL;
5516 int func_alignment = AOT_FUNC_ALIGNMENT;
5519 method = cfg->orig_method;
5520 code = cfg->native_code;
5522 method_index = get_method_index (acfg, method);
5523 symbol = g_strdup_printf ("%sme_%x", acfg->temp_prefix, method_index);
5525 /* Make the labels local */
5526 emit_section_change (acfg, ".text", 0);
5527 emit_alignment_code (acfg, func_alignment);
5529 if (acfg->global_symbols && acfg->need_no_dead_strip)
5530 fprintf (acfg->fp, " .no_dead_strip %s\n", cfg->asm_symbol);
5532 emit_label (acfg, cfg->asm_symbol);
5534 if (acfg->aot_opts.write_symbols && !acfg->global_symbols && !acfg->llvm) {
5536 * Write a C style symbol for every method, this has two uses:
5537 * - it works on platforms where the dwarf debugging info is not
5539 * - it allows the setting of breakpoints of aot-ed methods.
5541 debug_sym = get_debug_sym (method, "", acfg->method_label_hash);
5542 cfg->asm_debug_symbol = g_strdup (debug_sym);
5544 if (acfg->need_no_dead_strip)
5545 fprintf (acfg->fp, " .no_dead_strip %s\n", debug_sym);
5546 emit_local_symbol (acfg, debug_sym, symbol, TRUE);
5547 emit_label (acfg, debug_sym);
5550 export_name = (char *)g_hash_table_lookup (acfg->export_names, method);
5552 /* Emit a global symbol for the method */
5553 emit_global_inner (acfg, export_name, TRUE);
5554 emit_label (acfg, export_name);
5557 if (cfg->verbose_level > 0)
5558 g_print ("Method %s emitted as %s\n", mono_method_get_full_name (method), cfg->asm_symbol);
5560 acfg->stats.code_size += cfg->code_len;
5562 acfg->cfgs [method_index]->got_offset = acfg->got_offset;
5564 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 ()));
5568 if (acfg->aot_opts.write_symbols) {
5570 emit_symbol_size (acfg, debug_sym, ".");
5572 emit_symbol_size (acfg, cfg->asm_symbol, ".");
5576 emit_label (acfg, symbol);
5583 * Encode PATCH_INFO into its disk representation.
5586 encode_patch (MonoAotCompile *acfg, MonoJumpInfo *patch_info, guint8 *buf, guint8 **endbuf)
5590 switch (patch_info->type) {
5591 case MONO_PATCH_INFO_NONE:
5593 case MONO_PATCH_INFO_IMAGE:
5594 encode_value (get_image_index (acfg, patch_info->data.image), p, &p);
5596 case MONO_PATCH_INFO_MSCORLIB_GOT_ADDR:
5597 case MONO_PATCH_INFO_JIT_TLS_ID:
5598 case MONO_PATCH_INFO_GC_CARD_TABLE_ADDR:
5599 case MONO_PATCH_INFO_GC_NURSERY_START:
5600 case MONO_PATCH_INFO_GC_NURSERY_BITS:
5602 case MONO_PATCH_INFO_CASTCLASS_CACHE:
5603 encode_value (patch_info->data.index, p, &p);
5605 case MONO_PATCH_INFO_METHOD_REL:
5606 encode_value ((gint)patch_info->data.offset, p, &p);
5608 case MONO_PATCH_INFO_SWITCH: {
5609 gpointer *table = (gpointer *)patch_info->data.table->table;
5612 encode_value (patch_info->data.table->table_size, p, &p);
5613 for (k = 0; k < patch_info->data.table->table_size; k++)
5614 encode_value ((int)(gssize)table [k], p, &p);
5617 case MONO_PATCH_INFO_METHODCONST:
5618 case MONO_PATCH_INFO_METHOD:
5619 case MONO_PATCH_INFO_METHOD_JUMP:
5620 case MONO_PATCH_INFO_ICALL_ADDR:
5621 case MONO_PATCH_INFO_ICALL_ADDR_CALL:
5622 case MONO_PATCH_INFO_METHOD_RGCTX:
5623 case MONO_PATCH_INFO_METHOD_CODE_SLOT:
5624 encode_method_ref (acfg, patch_info->data.method, p, &p);
5626 case MONO_PATCH_INFO_AOT_JIT_INFO:
5627 encode_value (patch_info->data.index, p, &p);
5629 case MONO_PATCH_INFO_INTERNAL_METHOD:
5630 case MONO_PATCH_INFO_JIT_ICALL_ADDR: {
5631 guint32 len = strlen (patch_info->data.name);
5633 encode_value (len, p, &p);
5635 memcpy (p, patch_info->data.name, len);
5640 case MONO_PATCH_INFO_LDSTR: {
5641 guint32 image_index = get_image_index (acfg, patch_info->data.token->image);
5642 guint32 token = patch_info->data.token->token;
5643 g_assert (mono_metadata_token_code (token) == MONO_TOKEN_STRING);
5644 encode_value (image_index, p, &p);
5645 encode_value (patch_info->data.token->token - MONO_TOKEN_STRING, p, &p);
5648 case MONO_PATCH_INFO_RVA:
5649 case MONO_PATCH_INFO_DECLSEC:
5650 case MONO_PATCH_INFO_LDTOKEN:
5651 case MONO_PATCH_INFO_TYPE_FROM_HANDLE:
5652 encode_value (get_image_index (acfg, patch_info->data.token->image), p, &p);
5653 encode_value (patch_info->data.token->token, p, &p);
5654 encode_value (patch_info->data.token->has_context, p, &p);
5655 if (patch_info->data.token->has_context)
5656 encode_generic_context (acfg, &patch_info->data.token->context, p, &p);
5658 case MONO_PATCH_INFO_EXC_NAME: {
5659 MonoClass *ex_class;
5662 mono_class_load_from_name (mono_defaults.exception_class->image,
5663 "System", (const char *)patch_info->data.target);
5664 encode_klass_ref (acfg, ex_class, p, &p);
5667 case MONO_PATCH_INFO_R4:
5668 encode_value (*((guint32 *)patch_info->data.target), p, &p);
5670 case MONO_PATCH_INFO_R8:
5671 encode_value (((guint32 *)patch_info->data.target) [MINI_LS_WORD_IDX], p, &p);
5672 encode_value (((guint32 *)patch_info->data.target) [MINI_MS_WORD_IDX], p, &p);
5674 case MONO_PATCH_INFO_VTABLE:
5675 case MONO_PATCH_INFO_CLASS:
5676 case MONO_PATCH_INFO_IID:
5677 case MONO_PATCH_INFO_ADJUSTED_IID:
5678 encode_klass_ref (acfg, patch_info->data.klass, p, &p);
5680 case MONO_PATCH_INFO_DELEGATE_TRAMPOLINE:
5681 encode_klass_ref (acfg, patch_info->data.del_tramp->klass, p, &p);
5682 if (patch_info->data.del_tramp->method) {
5683 encode_value (1, p, &p);
5684 encode_method_ref (acfg, patch_info->data.del_tramp->method, p, &p);
5686 encode_value (0, p, &p);
5688 encode_value (patch_info->data.del_tramp->is_virtual, p, &p);
5690 case MONO_PATCH_INFO_FIELD:
5691 case MONO_PATCH_INFO_SFLDA:
5692 encode_field_info (acfg, patch_info->data.field, p, &p);
5694 case MONO_PATCH_INFO_INTERRUPTION_REQUEST_FLAG:
5696 case MONO_PATCH_INFO_RGCTX_FETCH:
5697 case MONO_PATCH_INFO_RGCTX_SLOT_INDEX: {
5698 MonoJumpInfoRgctxEntry *entry = patch_info->data.rgctx_entry;
5703 * entry->method has a lenghtly encoding and multiple rgctx_fetch entries
5704 * reference the same method, so encode the method only once.
5706 offset = GPOINTER_TO_UINT (g_hash_table_lookup (acfg->method_blob_hash, entry->method));
5708 buf2 = (guint8 *)g_malloc (1024);
5711 encode_method_ref (acfg, entry->method, p2, &p2);
5712 g_assert (p2 - buf2 < 1024);
5714 offset = add_to_blob (acfg, buf2, p2 - buf2);
5717 g_hash_table_insert (acfg->method_blob_hash, entry->method, GUINT_TO_POINTER (offset + 1));
5722 encode_value (offset, p, &p);
5723 g_assert ((int)entry->info_type < 256);
5724 g_assert (entry->data->type < 256);
5725 encode_value ((entry->in_mrgctx ? 1 : 0) | (entry->info_type << 1) | (entry->data->type << 9), p, &p);
5726 encode_patch (acfg, entry->data, p, &p);
5729 case MONO_PATCH_INFO_SEQ_POINT_INFO:
5730 case MONO_PATCH_INFO_AOT_MODULE:
5732 case MONO_PATCH_INFO_SIGNATURE:
5733 case MONO_PATCH_INFO_GSHAREDVT_IN_WRAPPER:
5734 encode_signature (acfg, (MonoMethodSignature*)patch_info->data.target, p, &p);
5736 case MONO_PATCH_INFO_TLS_OFFSET:
5737 encode_value (GPOINTER_TO_INT (patch_info->data.target), p, &p);
5739 case MONO_PATCH_INFO_GSHAREDVT_CALL:
5740 encode_signature (acfg, (MonoMethodSignature*)patch_info->data.gsharedvt->sig, p, &p);
5741 encode_method_ref (acfg, patch_info->data.gsharedvt->method, p, &p);
5743 case MONO_PATCH_INFO_GSHAREDVT_METHOD: {
5744 MonoGSharedVtMethodInfo *info = patch_info->data.gsharedvt_method;
5747 encode_method_ref (acfg, info->method, p, &p);
5748 encode_value (info->num_entries, p, &p);
5749 for (i = 0; i < info->num_entries; ++i) {
5750 MonoRuntimeGenericContextInfoTemplate *template_ = &info->entries [i];
5752 encode_value (template_->info_type, p, &p);
5753 switch (mini_rgctx_info_type_to_patch_info_type (template_->info_type)) {
5754 case MONO_PATCH_INFO_CLASS:
5755 encode_klass_ref (acfg, mono_class_from_mono_type ((MonoType *)template_->data), p, &p);
5757 case MONO_PATCH_INFO_FIELD:
5758 encode_field_info (acfg, (MonoClassField *)template_->data, p, &p);
5761 g_assert_not_reached ();
5767 case MONO_PATCH_INFO_LDSTR_LIT: {
5768 const char *s = (const char *)patch_info->data.target;
5769 int len = strlen (s);
5771 encode_value (len, p, &p);
5772 memcpy (p, s, len + 1);
5776 case MONO_PATCH_INFO_VIRT_METHOD:
5777 encode_klass_ref (acfg, patch_info->data.virt_method->klass, p, &p);
5778 encode_method_ref (acfg, patch_info->data.virt_method->method, p, &p);
5780 case MONO_PATCH_INFO_GC_SAFE_POINT_FLAG:
5783 g_warning ("unable to handle jump info %d", patch_info->type);
5784 g_assert_not_reached ();
5791 encode_patch_list (MonoAotCompile *acfg, GPtrArray *patches, int n_patches, gboolean llvm, int first_got_offset, guint8 *buf, guint8 **endbuf)
5794 guint32 pindex, offset;
5795 MonoJumpInfo *patch_info;
5797 encode_value (n_patches, p, &p);
5799 for (pindex = 0; pindex < patches->len; ++pindex) {
5800 patch_info = (MonoJumpInfo *)g_ptr_array_index (patches, pindex);
5802 if (patch_info->type == MONO_PATCH_INFO_NONE || patch_info->type == MONO_PATCH_INFO_BB)
5806 offset = get_got_offset (acfg, llvm, patch_info);
5807 encode_value (offset, p, &p);
5814 emit_method_info (MonoAotCompile *acfg, MonoCompile *cfg)
5817 int pindex, buf_size, n_patches;
5819 MonoJumpInfo *patch_info;
5820 guint32 method_index;
5822 guint32 first_got_offset;
5824 method = cfg->orig_method;
5826 method_index = get_method_index (acfg, method);
5828 /* Sort relocations */
5829 patches = g_ptr_array_new ();
5830 for (patch_info = cfg->patch_info; patch_info; patch_info = patch_info->next)
5831 g_ptr_array_add (patches, patch_info);
5832 g_ptr_array_sort (patches, compare_patches);
5834 first_got_offset = acfg->cfgs [method_index]->got_offset;
5836 /**********************/
5837 /* Encode method info */
5838 /**********************/
5840 buf_size = (patches->len < 1000) ? 40960 : 40960 + (patches->len * 64);
5841 p = buf = (guint8 *)g_malloc (buf_size);
5843 if (mono_class_get_cctor (method->klass)) {
5844 encode_value (1, p, &p);
5845 encode_klass_ref (acfg, method->klass, p, &p);
5847 /* Not needed when loading the method */
5848 encode_value (0, p, &p);
5851 g_assert (!(cfg->opt & MONO_OPT_SHARED));
5854 for (pindex = 0; pindex < patches->len; ++pindex) {
5855 patch_info = (MonoJumpInfo *)g_ptr_array_index (patches, pindex);
5857 if ((patch_info->type == MONO_PATCH_INFO_GOT_OFFSET) ||
5858 (patch_info->type == MONO_PATCH_INFO_NONE)) {
5859 patch_info->type = MONO_PATCH_INFO_NONE;
5864 if ((patch_info->type == MONO_PATCH_INFO_IMAGE) && (patch_info->data.image == acfg->image)) {
5865 /* Stored in a GOT slot initialized at module load time */
5866 patch_info->type = MONO_PATCH_INFO_NONE;
5870 if (patch_info->type == MONO_PATCH_INFO_GC_CARD_TABLE_ADDR ||
5871 patch_info->type == MONO_PATCH_INFO_GC_NURSERY_START ||
5872 patch_info->type == MONO_PATCH_INFO_GC_NURSERY_BITS ||
5873 patch_info->type == MONO_PATCH_INFO_AOT_MODULE) {
5874 /* Stored in a GOT slot initialized at module load time */
5875 patch_info->type = MONO_PATCH_INFO_NONE;
5879 if (is_plt_patch (patch_info) && !(cfg->compile_llvm && acfg->aot_opts.llvm_only)) {
5880 /* Calls are made through the PLT */
5881 patch_info->type = MONO_PATCH_INFO_NONE;
5889 g_assert (cfg->has_got_slots);
5891 encode_patch_list (acfg, patches, n_patches, cfg->compile_llvm, first_got_offset, p, &p);
5893 g_ptr_array_free (patches, TRUE);
5895 acfg->stats.info_size += p - buf;
5897 g_assert (p - buf < buf_size);
5899 cfg->method_info_offset = add_to_blob (acfg, buf, p - buf);
5904 get_unwind_info_offset (MonoAotCompile *acfg, guint8 *encoded, guint32 encoded_len)
5906 guint32 cache_index;
5909 /* Reuse the unwind module to canonize and store unwind info entries */
5910 cache_index = mono_cache_unwind_info (encoded, encoded_len);
5912 /* Use +/- 1 to distinguish 0s from missing entries */
5913 offset = GPOINTER_TO_UINT (g_hash_table_lookup (acfg->unwind_info_offsets, GUINT_TO_POINTER (cache_index + 1)));
5921 * It would be easier to use assembler symbols, but the caller needs an
5924 offset = acfg->unwind_info_offset;
5925 g_hash_table_insert (acfg->unwind_info_offsets, GUINT_TO_POINTER (cache_index + 1), GUINT_TO_POINTER (offset + 1));
5926 g_ptr_array_add (acfg->unwind_ops, GUINT_TO_POINTER (cache_index));
5929 encode_value (encoded_len, p, &p);
5931 acfg->unwind_info_offset += encoded_len + (p - buf);
5937 emit_exception_debug_info (MonoAotCompile *acfg, MonoCompile *cfg, gboolean store_seq_points)
5940 guint32 debug_info_size, seq_points_size;
5942 MonoMethodHeader *header;
5943 guint8 *p, *buf, *debug_info;
5944 MonoJitInfo *jinfo = cfg->jit_info;
5946 gboolean use_unwind_ops = FALSE;
5947 MonoSeqPointInfo *seq_points;
5949 code = cfg->native_code;
5950 header = cfg->header;
5952 if (!acfg->aot_opts.nodebug) {
5953 mono_debug_serialize_debug_info (cfg, &debug_info, &debug_info_size);
5956 debug_info_size = 0;
5959 seq_points = cfg->seq_point_info;
5960 seq_points_size = (store_seq_points)? mono_seq_point_info_get_write_size (seq_points) : 0;
5962 buf_size = header->num_clauses * 256 + debug_info_size + 2048 + seq_points_size + cfg->gc_map_size;
5964 p = buf = (guint8 *)g_malloc (buf_size);
5966 use_unwind_ops = cfg->unwind_ops != NULL;
5968 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);
5970 encode_value (flags, p, &p);
5972 if (use_unwind_ops) {
5973 guint32 encoded_len;
5975 guint32 unwind_desc;
5977 encoded = mono_unwind_ops_encode (cfg->unwind_ops, &encoded_len);
5979 unwind_desc = get_unwind_info_offset (acfg, encoded, encoded_len);
5980 encode_value (unwind_desc, p, &p);
5982 encode_value (jinfo->unwind_info, p, &p);
5985 /*Encode the number of holes before the number of clauses to make decoding easier*/
5986 if (jinfo->has_try_block_holes) {
5987 MonoTryBlockHoleTableJitInfo *table = mono_jit_info_get_try_block_hole_table_info (jinfo);
5988 encode_value (table->num_holes, p, &p);
5991 if (jinfo->has_arch_eh_info) {
5993 * In AOT mode, the code length is calculated from the address of the previous method,
5994 * which could include alignment padding, so calculating the start of the epilog as
5995 * code_len - epilog_size is correct any more. Save the real code len as a workaround.
5997 encode_value (jinfo->code_size, p, &p);
6000 /* Exception table */
6001 if (cfg->compile_llvm) {
6003 * When using LLVM, we can't emit some data, like pc offsets, this reg/offset etc.,
6004 * since the information is only available to llc. Instead, we let llc save the data
6005 * into the LSDA, and read it from there at runtime.
6007 /* The assembly might be CIL stripped so emit the data ourselves */
6008 if (header->num_clauses)
6009 encode_value (header->num_clauses, p, &p);
6011 for (k = 0; k < header->num_clauses; ++k) {
6012 MonoExceptionClause *clause;
6014 clause = &header->clauses [k];
6016 encode_value (clause->flags, p, &p);
6017 if (clause->data.catch_class) {
6018 encode_value (1, p, &p);
6019 encode_klass_ref (acfg, clause->data.catch_class, p, &p);
6021 encode_value (0, p, &p);
6024 /* Emit the IL ranges too, since they might not be available at runtime */
6025 encode_value (clause->try_offset, p, &p);
6026 encode_value (clause->try_len, p, &p);
6027 encode_value (clause->handler_offset, p, &p);
6028 encode_value (clause->handler_len, p, &p);
6030 /* Emit a list of nesting clauses */
6031 for (i = 0; i < header->num_clauses; ++i) {
6033 MonoExceptionClause *clause1 = &header->clauses [cindex1];
6035 MonoExceptionClause *clause2 = &header->clauses [cindex2];
6037 if (cindex1 != cindex2 && clause1->try_offset >= clause2->try_offset && clause1->handler_offset <= clause2->handler_offset)
6038 encode_value (i, p, &p);
6040 encode_value (-1, p, &p);
6043 if (jinfo->num_clauses)
6044 encode_value (jinfo->num_clauses, p, &p);
6046 for (k = 0; k < jinfo->num_clauses; ++k) {
6047 MonoJitExceptionInfo *ei = &jinfo->clauses [k];
6049 encode_value (ei->flags, p, &p);
6050 #ifdef MONO_CONTEXT_SET_LLVM_EXC_REG
6051 /* Not used for catch clauses */
6052 if (ei->flags != MONO_EXCEPTION_CLAUSE_NONE)
6053 encode_value (ei->exvar_offset, p, &p);
6055 encode_value (ei->exvar_offset, p, &p);
6058 if (ei->flags == MONO_EXCEPTION_CLAUSE_FILTER || ei->flags == MONO_EXCEPTION_CLAUSE_FINALLY)
6059 encode_value ((gint)((guint8*)ei->data.filter - code), p, &p);
6061 if (ei->data.catch_class) {
6065 buf2 = (guint8 *)g_malloc (4096);
6067 encode_klass_ref (acfg, ei->data.catch_class, p2, &p2);
6069 g_assert (len < 4096);
6070 encode_value (len, p, &p);
6071 memcpy (p, buf2, len);
6075 encode_value (0, p, &p);
6079 encode_value ((gint)((guint8*)ei->try_start - code), p, &p);
6080 encode_value ((gint)((guint8*)ei->try_end - code), p, &p);
6081 encode_value ((gint)((guint8*)ei->handler_start - code), p, &p);
6085 if (jinfo->has_try_block_holes) {
6086 MonoTryBlockHoleTableJitInfo *table = mono_jit_info_get_try_block_hole_table_info (jinfo);
6087 for (i = 0; i < table->num_holes; ++i) {
6088 MonoTryBlockHoleJitInfo *hole = &table->holes [i];
6089 encode_value (hole->clause, p, &p);
6090 encode_value (hole->length, p, &p);
6091 encode_value (hole->offset, p, &p);
6095 if (jinfo->has_arch_eh_info) {
6096 MonoArchEHJitInfo *eh_info;
6098 eh_info = mono_jit_info_get_arch_eh_info (jinfo);
6099 encode_value (eh_info->stack_size, p, &p);
6100 encode_value (eh_info->epilog_size, p, &p);
6103 if (jinfo->has_generic_jit_info) {
6104 MonoGenericJitInfo *gi = mono_jit_info_get_generic_jit_info (jinfo);
6105 MonoGenericSharingContext* gsctx = gi->generic_sharing_context;
6109 encode_value (gi->nlocs, p, &p);
6111 for (i = 0; i < gi->nlocs; ++i) {
6112 MonoDwarfLocListEntry *entry = &gi->locations [i];
6114 encode_value (entry->is_reg ? 1 : 0, p, &p);
6115 encode_value (entry->reg, p, &p);
6117 encode_value (entry->offset, p, &p);
6119 g_assert (entry->from == 0);
6121 encode_value (entry->from, p, &p);
6122 encode_value (entry->to, p, &p);
6125 if (!cfg->compile_llvm) {
6126 encode_value (gi->has_this ? 1 : 0, p, &p);
6127 encode_value (gi->this_reg, p, &p);
6128 encode_value (gi->this_offset, p, &p);
6133 * Need to encode jinfo->method too, since it is not equal to 'method'
6134 * when using generic sharing.
6136 buf2 = (guint8 *)g_malloc (4096);
6138 encode_method_ref (acfg, jinfo->d.method, p2, &p2);
6140 g_assert (len < 4096);
6141 encode_value (len, p, &p);
6142 memcpy (p, buf2, len);
6146 if (gsctx && gsctx->is_gsharedvt) {
6147 encode_value (1, p, &p);
6149 encode_value (0, p, &p);
6153 if (seq_points_size)
6154 p += mono_seq_point_info_write (seq_points, p);
6156 g_assert (debug_info_size < buf_size);
6158 encode_value (debug_info_size, p, &p);
6159 if (debug_info_size) {
6160 memcpy (p, debug_info, debug_info_size);
6161 p += debug_info_size;
6162 g_free (debug_info);
6167 encode_value (cfg->gc_map_size, p, &p);
6168 /* The GC map requires 4 bytes of alignment */
6169 while ((gsize)p % 4)
6171 memcpy (p, cfg->gc_map, cfg->gc_map_size);
6172 p += cfg->gc_map_size;
6175 acfg->stats.ex_info_size += p - buf;
6177 g_assert (p - buf < buf_size);
6180 /* The GC Map requires 4 byte alignment */
6181 cfg->ex_info_offset = add_to_blob_aligned (acfg, buf, p - buf, cfg->gc_map ? 4 : 1);
6186 emit_klass_info (MonoAotCompile *acfg, guint32 token)
6189 MonoClass *klass = mono_class_get_checked (acfg->image, token, &error);
6191 int i, buf_size, res;
6192 gboolean no_special_static, cant_encode;
6193 gpointer iter = NULL;
6196 mono_error_cleanup (&error);
6200 p = buf = (guint8 *)g_malloc (buf_size);
6202 /* Mark as unusable */
6203 encode_value (-1, p, &p);
6205 res = add_to_blob (acfg, buf, p - buf);
6211 buf_size = 10240 + (klass->vtable_size * 16);
6212 p = buf = (guint8 *)g_malloc (buf_size);
6216 mono_class_init (klass);
6218 mono_class_get_nested_types (klass, &iter);
6219 g_assert (klass->nested_classes_inited);
6221 mono_class_setup_vtable (klass);
6224 * Emit all the information which is required for creating vtables so
6225 * the runtime does not need to create the MonoMethod structures which
6226 * take up a lot of space.
6229 no_special_static = !mono_class_has_special_static_fields (klass);
6231 /* Check whenever we have enough info to encode the vtable */
6232 cant_encode = FALSE;
6233 for (i = 0; i < klass->vtable_size; ++i) {
6234 MonoMethod *cm = klass->vtable [i];
6236 if (cm && mono_method_signature (cm)->is_inflated && !g_hash_table_lookup (acfg->token_info_hash, cm))
6240 mono_class_has_finalizer (klass);
6242 if (klass->generic_container || cant_encode) {
6243 encode_value (-1, p, &p);
6245 encode_value (klass->vtable_size, p, &p);
6246 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);
6247 if (klass->has_cctor)
6248 encode_method_ref (acfg, mono_class_get_cctor (klass), p, &p);
6249 if (klass->has_finalize)
6250 encode_method_ref (acfg, mono_class_get_finalizer (klass), p, &p);
6252 encode_value (klass->instance_size, p, &p);
6253 encode_value (mono_class_data_size (klass), p, &p);
6254 encode_value (klass->packing_size, p, &p);
6255 encode_value (klass->min_align, p, &p);
6257 for (i = 0; i < klass->vtable_size; ++i) {
6258 MonoMethod *cm = klass->vtable [i];
6261 encode_method_ref (acfg, cm, p, &p);
6263 encode_value (0, p, &p);
6267 acfg->stats.class_info_size += p - buf;
6269 g_assert (p - buf < buf_size);
6270 res = add_to_blob (acfg, buf, p - buf);
6277 get_plt_entry_debug_sym (MonoAotCompile *acfg, MonoJumpInfo *ji, GHashTable *cache)
6279 char *debug_sym = NULL;
6282 if (acfg->llvm && llvm_acfg->aot_opts.static_link) {
6283 /* Need to add a prefix to create unique symbols */
6284 prefix = g_strdup_printf ("plt_%s_", acfg->assembly_name_sym);
6286 #if defined(TARGET_WIN32) && defined(TARGET_X86)
6287 prefix = mangle_symbol_alloc ("plt_");
6289 prefix = g_strdup ("plt_");
6294 case MONO_PATCH_INFO_METHOD:
6295 debug_sym = get_debug_sym (ji->data.method, prefix, cache);
6297 case MONO_PATCH_INFO_INTERNAL_METHOD:
6298 debug_sym = g_strdup_printf ("%s_jit_icall_%s", prefix, ji->data.name);
6300 case MONO_PATCH_INFO_RGCTX_FETCH:
6301 debug_sym = g_strdup_printf ("%s_rgctx_fetch_%d", prefix, acfg->label_generator ++);
6303 case MONO_PATCH_INFO_ICALL_ADDR:
6304 case MONO_PATCH_INFO_ICALL_ADDR_CALL: {
6305 char *s = get_debug_sym (ji->data.method, "", cache);
6307 debug_sym = g_strdup_printf ("%s_icall_native_%s", prefix, s);
6311 case MONO_PATCH_INFO_JIT_ICALL_ADDR:
6312 debug_sym = g_strdup_printf ("%s_jit_icall_native_%s", prefix, ji->data.name);
6320 return sanitize_symbol (acfg, debug_sym);
6324 * Calls made from AOTed code are routed through a table of jumps similar to the
6325 * ELF PLT (Program Linkage Table). Initially the PLT entries jump to code which transfers
6326 * control to the AOT runtime through a trampoline.
6329 emit_plt (MonoAotCompile *acfg)
6333 if (acfg->aot_opts.llvm_only) {
6334 g_assert (acfg->plt_offset == 1);
6340 emit_section_change (acfg, ".text", 0);
6341 emit_alignment_code (acfg, 16);
6342 emit_info_symbol (acfg, "plt");
6343 emit_label (acfg, acfg->plt_symbol);
6345 for (i = 0; i < acfg->plt_offset; ++i) {
6346 char *debug_sym = NULL;
6347 MonoPltEntry *plt_entry = NULL;
6351 * The first plt entry is unused.
6355 plt_entry = (MonoPltEntry *)g_hash_table_lookup (acfg->plt_offset_to_entry, GUINT_TO_POINTER (i));
6357 debug_sym = plt_entry->debug_sym;
6359 if (acfg->thumb_mixed && !plt_entry->jit_used)
6360 /* Emit only a thumb version */
6363 /* Skip plt entries not actually called */
6364 if (!plt_entry->jit_used && !plt_entry->llvm_used)
6367 if (acfg->llvm && !acfg->thumb_mixed) {
6368 emit_label (acfg, plt_entry->llvm_symbol);
6370 emit_global_inner (acfg, plt_entry->llvm_symbol, TRUE);
6371 #if defined(TARGET_MACH)
6372 fprintf (acfg->fp, ".private_extern %s\n", plt_entry->llvm_symbol);
6378 if (acfg->need_no_dead_strip) {
6379 emit_unset_mode (acfg);
6380 fprintf (acfg->fp, " .no_dead_strip %s\n", debug_sym);
6382 emit_local_symbol (acfg, debug_sym, NULL, TRUE);
6383 emit_label (acfg, debug_sym);
6386 emit_label (acfg, plt_entry->symbol);
6388 arch_emit_plt_entry (acfg, acfg->got_symbol, (acfg->plt_got_offset_base + i) * sizeof (gpointer), acfg->plt_got_info_offsets [i]);
6391 emit_symbol_size (acfg, debug_sym, ".");
6394 if (acfg->thumb_mixed) {
6395 /* Make sure the ARM symbols don't alias the thumb ones */
6396 emit_zero_bytes (acfg, 16);
6399 * Emit a separate set of PLT entries using thumb2 which is called by LLVM generated
6402 for (i = 0; i < acfg->plt_offset; ++i) {
6403 char *debug_sym = NULL;
6404 MonoPltEntry *plt_entry = NULL;
6409 plt_entry = (MonoPltEntry *)g_hash_table_lookup (acfg->plt_offset_to_entry, GUINT_TO_POINTER (i));
6411 /* Skip plt entries not actually called by LLVM code */
6412 if (!plt_entry->llvm_used)
6415 if (acfg->aot_opts.write_symbols) {
6416 if (plt_entry->debug_sym)
6417 debug_sym = g_strdup_printf ("%s_thumb", plt_entry->debug_sym);
6421 #if defined(TARGET_MACH)
6422 fprintf (acfg->fp, " .thumb_func %s\n", debug_sym);
6423 fprintf (acfg->fp, " .no_dead_strip %s\n", debug_sym);
6425 emit_local_symbol (acfg, debug_sym, NULL, TRUE);
6426 emit_label (acfg, debug_sym);
6428 fprintf (acfg->fp, "\n.thumb_func\n");
6430 emit_label (acfg, plt_entry->llvm_symbol);
6433 emit_global_inner (acfg, plt_entry->llvm_symbol, TRUE);
6435 arch_emit_llvm_plt_entry (acfg, acfg->got_symbol, (acfg->plt_got_offset_base + i) * sizeof (gpointer), acfg->plt_got_info_offsets [i]);
6438 emit_symbol_size (acfg, debug_sym, ".");
6444 emit_symbol_size (acfg, acfg->plt_symbol, ".");
6446 emit_info_symbol (acfg, "plt_end");
6450 * emit_trampoline_full:
6452 * If EMIT_TINFO is TRUE, emit additional information which can be used to create a MonoJitInfo for this trampoline by
6453 * create_jit_info_for_trampoline ().
6455 static G_GNUC_UNUSED void
6456 emit_trampoline_full (MonoAotCompile *acfg, int got_offset, MonoTrampInfo *info, gboolean emit_tinfo)
6458 char start_symbol [MAX_SYMBOL_SIZE];
6459 char end_symbol [MAX_SYMBOL_SIZE];
6460 char symbol [MAX_SYMBOL_SIZE];
6461 guint32 buf_size, info_offset;
6462 MonoJumpInfo *patch_info;
6475 code_size = info->code_size;
6477 unwind_ops = info->unwind_ops;
6481 sprintf (start_symbol, "%s%s", acfg->user_symbol_prefix, name);
6483 emit_section_change (acfg, ".text", 0);
6484 emit_global (acfg, start_symbol, TRUE);
6485 emit_alignment_code (acfg, AOT_FUNC_ALIGNMENT);
6486 emit_label (acfg, start_symbol);
6488 sprintf (symbol, "%snamed_%s", acfg->temp_prefix, name);
6489 emit_label (acfg, symbol);
6492 * The code should access everything through the GOT, so we pass
6495 emit_and_reloc_code (acfg, NULL, code, code_size, ji, TRUE, NULL);
6497 emit_symbol_size (acfg, start_symbol, ".");
6500 sprintf (end_symbol, "%snamede_%s", acfg->temp_prefix, name);
6501 emit_label (acfg, end_symbol);
6506 /* Sort relocations */
6507 patches = g_ptr_array_new ();
6508 for (patch_info = ji; patch_info; patch_info = patch_info->next)
6509 if (patch_info->type != MONO_PATCH_INFO_NONE)
6510 g_ptr_array_add (patches, patch_info);
6511 g_ptr_array_sort (patches, compare_patches);
6513 buf_size = patches->len * 128 + 128;
6514 buf = (guint8 *)g_malloc (buf_size);
6517 encode_patch_list (acfg, patches, patches->len, FALSE, got_offset, p, &p);
6518 g_assert (p - buf < buf_size);
6520 sprintf (symbol, "%s%s_p", acfg->user_symbol_prefix, name);
6522 info_offset = add_to_blob (acfg, buf, p - buf);
6524 emit_section_change (acfg, RODATA_SECT, 0);
6525 emit_global (acfg, symbol, FALSE);
6526 emit_label (acfg, symbol);
6528 emit_int32 (acfg, info_offset);
6532 guint32 encoded_len;
6536 * Emit additional information which can be used to reconstruct a partial MonoTrampInfo.
6538 encoded = mono_unwind_ops_encode (info->unwind_ops, &encoded_len);
6539 uw_offset = get_unwind_info_offset (acfg, encoded, encoded_len);
6542 emit_symbol_diff (acfg, end_symbol, start_symbol, 0);
6543 emit_int32 (acfg, uw_offset);
6546 /* Emit debug info */
6548 char symbol2 [MAX_SYMBOL_SIZE];
6550 sprintf (symbol, "%s", name);
6551 sprintf (symbol2, "%snamed_%s", acfg->temp_prefix, name);
6554 mono_dwarf_writer_emit_trampoline (acfg->dwarf, symbol, symbol2, NULL, NULL, code_size, unwind_ops);
6558 static G_GNUC_UNUSED void
6559 emit_trampoline (MonoAotCompile *acfg, int got_offset, MonoTrampInfo *info)
6561 emit_trampoline_full (acfg, got_offset, info, TRUE);
6565 emit_trampolines (MonoAotCompile *acfg)
6567 char symbol [MAX_SYMBOL_SIZE];
6568 char end_symbol [MAX_SYMBOL_SIZE];
6569 int i, tramp_got_offset;
6571 #ifdef MONO_ARCH_HAVE_FULL_AOT_TRAMPOLINES
6575 if (!mono_aot_mode_is_full (&acfg->aot_opts) || acfg->aot_opts.llvm_only)
6578 g_assert (acfg->image->assembly);
6580 /* Currently, we emit most trampolines into the mscorlib AOT image. */
6581 if (strcmp (acfg->image->assembly->aname.name, "mscorlib") == 0) {
6582 #ifdef MONO_ARCH_HAVE_FULL_AOT_TRAMPOLINES
6583 MonoTrampInfo *info;
6586 * Emit the generic trampolines.
6588 * We could save some code by treating the generic trampolines as a wrapper
6589 * method, but that approach has its own complexities, so we choose the simpler
6592 for (tramp_type = 0; tramp_type < MONO_TRAMPOLINE_NUM; ++tramp_type) {
6593 /* we overload the boolean here to indicate the slightly different trampoline needed, see mono_arch_create_generic_trampoline() */
6594 #ifdef DISABLE_REMOTING
6595 if (tramp_type == MONO_TRAMPOLINE_GENERIC_VIRTUAL_REMOTING)
6598 #ifndef MONO_ARCH_HAVE_HANDLER_BLOCK_GUARD
6599 if (tramp_type == MONO_TRAMPOLINE_HANDLER_BLOCK_GUARD)
6602 mono_arch_create_generic_trampoline ((MonoTrampolineType)tramp_type, &info, acfg->aot_opts.use_trampolines_page? 2: TRUE);
6603 emit_trampoline (acfg, acfg->got_offset, info);
6606 /* Emit the exception related code pieces */
6607 mono_arch_get_restore_context (&info, TRUE);
6608 emit_trampoline (acfg, acfg->got_offset, info);
6609 mono_arch_get_call_filter (&info, TRUE);
6610 emit_trampoline (acfg, acfg->got_offset, info);
6611 mono_arch_get_throw_exception (&info, TRUE);
6612 emit_trampoline (acfg, acfg->got_offset, info);
6613 mono_arch_get_rethrow_exception (&info, TRUE);
6614 emit_trampoline (acfg, acfg->got_offset, info);
6615 mono_arch_get_throw_corlib_exception (&info, TRUE);
6616 emit_trampoline (acfg, acfg->got_offset, info);
6618 #ifdef MONO_ARCH_HAVE_SDB_TRAMPOLINES
6619 mono_arch_create_sdb_trampoline (TRUE, &info, TRUE);
6620 emit_trampoline (acfg, acfg->got_offset, info);
6621 mono_arch_create_sdb_trampoline (FALSE, &info, TRUE);
6622 emit_trampoline (acfg, acfg->got_offset, info);
6625 #ifdef MONO_ARCH_GSHAREDVT_SUPPORTED
6626 mono_arch_get_gsharedvt_trampoline (&info, TRUE);
6628 emit_trampoline_full (acfg, acfg->got_offset, info, TRUE);
6630 /* Create a separate out trampoline for more information in stack traces */
6631 info->name = g_strdup ("gsharedvt_out_trampoline");
6632 emit_trampoline_full (acfg, acfg->got_offset, info, TRUE);
6636 #if defined(MONO_ARCH_HAVE_GET_TRAMPOLINES)
6638 GSList *l = mono_arch_get_trampolines (TRUE);
6641 MonoTrampInfo *info = (MonoTrampInfo *)l->data;
6643 emit_trampoline (acfg, acfg->got_offset, info);
6649 for (i = 0; i < acfg->aot_opts.nrgctx_fetch_trampolines; ++i) {
6652 offset = MONO_RGCTX_SLOT_MAKE_RGCTX (i);
6653 mono_arch_create_rgctx_lazy_fetch_trampoline (offset, &info, TRUE);
6654 emit_trampoline (acfg, acfg->got_offset, info);
6656 offset = MONO_RGCTX_SLOT_MAKE_MRGCTX (i);
6657 mono_arch_create_rgctx_lazy_fetch_trampoline (offset, &info, TRUE);
6658 emit_trampoline (acfg, acfg->got_offset, info);
6661 #ifdef MONO_ARCH_HAVE_GENERAL_RGCTX_LAZY_FETCH_TRAMPOLINE
6662 mono_arch_create_general_rgctx_lazy_fetch_trampoline (&info, TRUE);
6663 emit_trampoline (acfg, acfg->got_offset, info);
6669 /* delegate_invoke_impl trampolines */
6670 l = mono_arch_get_delegate_invoke_impls ();
6672 MonoTrampInfo *info = (MonoTrampInfo *)l->data;
6674 emit_trampoline (acfg, acfg->got_offset, info);
6679 #endif /* #ifdef MONO_ARCH_HAVE_FULL_AOT_TRAMPOLINES */
6681 /* Emit trampolines which are numerous */
6684 * These include the following:
6685 * - specific trampolines
6686 * - static rgctx invoke trampolines
6688 * These trampolines have the same code, they are parameterized by GOT
6690 * They are defined in this file, in the arch_... routines instead of
6691 * in tramp-<ARCH>.c, since it is easier to do it this way.
6695 * When running in aot-only mode, we can't create specific trampolines at
6696 * runtime, so we create a few, and save them in the AOT file.
6697 * Normal trampolines embed their argument as a literal inside the
6698 * trampoline code, we can't do that here, so instead we embed an offset
6699 * which needs to be added to the trampoline address to get the address of
6700 * the GOT slot which contains the argument value.
6701 * The generated trampolines jump to the generic trampolines using another
6702 * GOT slot, which will be setup by the AOT loader to point to the
6703 * generic trampoline code of the given type.
6707 * FIXME: Maybe we should use more specific trampolines (i.e. one class init for
6711 emit_section_change (acfg, ".text", 0);
6713 tramp_got_offset = acfg->got_offset;
6715 for (ntype = 0; ntype < MONO_AOT_TRAMP_NUM; ++ntype) {
6717 case MONO_AOT_TRAMP_SPECIFIC:
6718 sprintf (symbol, "specific_trampolines");
6720 case MONO_AOT_TRAMP_STATIC_RGCTX:
6721 sprintf (symbol, "static_rgctx_trampolines");
6723 case MONO_AOT_TRAMP_IMT_THUNK:
6724 sprintf (symbol, "imt_thunks");
6726 case MONO_AOT_TRAMP_GSHAREDVT_ARG:
6727 sprintf (symbol, "gsharedvt_arg_trampolines");
6730 g_assert_not_reached ();
6733 sprintf (end_symbol, "%s_e", symbol);
6735 if (acfg->aot_opts.write_symbols)
6736 emit_local_symbol (acfg, symbol, end_symbol, TRUE);
6738 emit_alignment_code (acfg, AOT_FUNC_ALIGNMENT);
6739 emit_info_symbol (acfg, symbol);
6741 acfg->trampoline_got_offset_base [ntype] = tramp_got_offset;
6743 for (i = 0; i < acfg->num_trampolines [ntype]; ++i) {
6747 case MONO_AOT_TRAMP_SPECIFIC:
6748 arch_emit_specific_trampoline (acfg, tramp_got_offset, &tramp_size);
6749 tramp_got_offset += 2;
6751 case MONO_AOT_TRAMP_STATIC_RGCTX:
6752 arch_emit_static_rgctx_trampoline (acfg, tramp_got_offset, &tramp_size);
6753 tramp_got_offset += 2;
6755 case MONO_AOT_TRAMP_IMT_THUNK:
6756 arch_emit_imt_thunk (acfg, tramp_got_offset, &tramp_size);
6757 tramp_got_offset += 1;
6759 case MONO_AOT_TRAMP_GSHAREDVT_ARG:
6760 arch_emit_gsharedvt_arg_trampoline (acfg, tramp_got_offset, &tramp_size);
6761 tramp_got_offset += 2;
6764 g_assert_not_reached ();
6766 if (!acfg->trampoline_size [ntype]) {
6767 g_assert (tramp_size);
6768 acfg->trampoline_size [ntype] = tramp_size;
6772 emit_label (acfg, end_symbol);
6773 emit_int32 (acfg, 0);
6776 arch_emit_specific_trampoline_pages (acfg);
6778 /* Reserve some entries at the end of the GOT for our use */
6779 acfg->num_trampoline_got_entries = tramp_got_offset - acfg->got_offset;
6782 acfg->got_offset += acfg->num_trampoline_got_entries;
6786 str_begins_with (const char *str1, const char *str2)
6788 int len = strlen (str2);
6789 return strncmp (str1, str2, len) == 0;
6793 mono_aot_readonly_field_override (MonoClassField *field)
6796 for (rdv = readonly_values; rdv; rdv = rdv->next) {
6797 char *p = rdv->name;
6799 len = strlen (field->parent->name_space);
6800 if (strncmp (p, field->parent->name_space, len))
6805 len = strlen (field->parent->name);
6806 if (strncmp (p, field->parent->name, len))
6811 if (strcmp (p, field->name))
6813 switch (rdv->type) {
6815 return &rdv->value.i1;
6817 return &rdv->value.i2;
6819 return &rdv->value.i4;
6828 add_readonly_value (MonoAotOptions *opts, const char *val)
6833 /* the format of val is:
6834 * namespace.typename.fieldname=type/value
6835 * type can be i1 for uint8/int8/boolean, i2 for uint16/int16/char, i4 for uint32/int32
6837 fval = strrchr (val, '/');
6839 fprintf (stderr, "AOT : invalid format for readonly field '%s', missing /.\n", val);
6842 tval = strrchr (val, '=');
6844 fprintf (stderr, "AOT : invalid format for readonly field '%s', missing =.\n", val);
6847 rdv = g_new0 (ReadOnlyValue, 1);
6848 rdv->name = (char *)g_malloc0 (tval - val + 1);
6849 memcpy (rdv->name, val, tval - val);
6852 if (strncmp (tval, "i1", 2) == 0) {
6853 rdv->value.i1 = atoi (fval);
6854 rdv->type = MONO_TYPE_I1;
6855 } else if (strncmp (tval, "i2", 2) == 0) {
6856 rdv->value.i2 = atoi (fval);
6857 rdv->type = MONO_TYPE_I2;
6858 } else if (strncmp (tval, "i4", 2) == 0) {
6859 rdv->value.i4 = atoi (fval);
6860 rdv->type = MONO_TYPE_I4;
6862 fprintf (stderr, "AOT : unsupported type for readonly field '%s'.\n", tval);
6865 rdv->next = readonly_values;
6866 readonly_values = rdv;
6870 clean_path (gchar * path)
6875 if (g_str_has_suffix (path, G_DIR_SEPARATOR_S))
6878 gchar *clean = g_strconcat (path, G_DIR_SEPARATOR_S, NULL);
6885 wrap_path (gchar * path)
6891 // If the string contains no spaces, just return the original string.
6892 if (strstr (path, " ") == NULL)
6895 // If the string is already wrapped in quotes, return it.
6896 len = strlen (path);
6897 if (len >= 2 && path[0] == '\"' && path[len-1] == '\"')
6900 // If the string contains spaces, then wrap it in quotes.
6901 gchar *clean = g_strdup_printf ("\"%s\"", path);
6906 // Duplicate a char range and add it to a ptrarray, but only if it is nonempty
6908 ptr_array_add_range_if_nonempty(GPtrArray *args, gchar const *start, gchar const *end)
6910 ptrdiff_t len = end-start;
6912 g_ptr_array_add (args, g_strndup (start, len));
6916 mono_aot_split_options (const char *aot_options)
6918 enum MonoAotOptionState {
6919 MONO_AOT_OPTION_STATE_DEFAULT,
6920 MONO_AOT_OPTION_STATE_STRING,
6921 MONO_AOT_OPTION_STATE_ESCAPE,
6924 GPtrArray *args = g_ptr_array_new ();
6925 enum MonoAotOptionState state = MONO_AOT_OPTION_STATE_DEFAULT;
6926 gchar const *opt_start = aot_options;
6927 gboolean end_of_string = FALSE;
6930 g_return_val_if_fail (aot_options != NULL, NULL);
6932 while ((cur = *aot_options) != '\0') {
6933 if (state == MONO_AOT_OPTION_STATE_ESCAPE)
6938 // If we find a quote, then if we're in the default case then
6939 // it means we've found the start of a string, if not then it
6940 // means we've found the end of the string and should switch
6941 // back to the default case.
6943 case MONO_AOT_OPTION_STATE_DEFAULT:
6944 state = MONO_AOT_OPTION_STATE_STRING;
6946 case MONO_AOT_OPTION_STATE_STRING:
6947 state = MONO_AOT_OPTION_STATE_DEFAULT;
6949 case MONO_AOT_OPTION_STATE_ESCAPE:
6950 g_assert_not_reached ();
6955 // If we've found an escaping operator, then this means we
6956 // should not process the next character if inside a string.
6957 if (state == MONO_AOT_OPTION_STATE_STRING)
6958 state = MONO_AOT_OPTION_STATE_ESCAPE;
6961 // If we're in the default state then this means we've found
6962 // an option, store it for later processing.
6963 if (state == MONO_AOT_OPTION_STATE_DEFAULT)
6971 // If the next character is end of string, then process the last option.
6972 if (*(aot_options) == '\0') {
6973 end_of_string = TRUE;
6979 ptr_array_add_range_if_nonempty (args, opt_start, aot_options);
6980 opt_start = ++aot_options;
6983 goto restart; // Check for null and continue loop
6990 mono_aot_parse_options (const char *aot_options, MonoAotOptions *opts)
6994 args = mono_aot_split_options (aot_options ? aot_options : "");
6995 for (int i = 0; i < args->len; ++i) {
6996 const char *arg = (const char *)g_ptr_array_index (args, i);
6998 if (str_begins_with (arg, "outfile=")) {
6999 opts->outfile = g_strdup (arg + strlen ("outfile="));
7000 } else if (str_begins_with (arg, "llvm-outfile=")) {
7001 opts->llvm_outfile = g_strdup (arg + strlen ("llvm-outfile="));
7002 } else if (str_begins_with (arg, "temp-path=")) {
7003 opts->temp_path = clean_path (g_strdup (arg + strlen ("temp-path=")));
7004 } else if (str_begins_with (arg, "save-temps")) {
7005 opts->save_temps = TRUE;
7006 } else if (str_begins_with (arg, "keep-temps")) {
7007 opts->save_temps = TRUE;
7008 } else if (str_begins_with (arg, "write-symbols")) {
7009 opts->write_symbols = TRUE;
7010 } else if (str_begins_with (arg, "no-write-symbols")) {
7011 opts->write_symbols = FALSE;
7012 } else if (str_begins_with (arg, "metadata-only")) {
7013 opts->metadata_only = TRUE;
7014 } else if (str_begins_with (arg, "bind-to-runtime-version")) {
7015 opts->bind_to_runtime_version = TRUE;
7016 } else if (str_begins_with (arg, "full")) {
7017 opts->mode = MONO_AOT_MODE_FULL;
7018 } else if (str_begins_with (arg, "hybrid")) {
7019 opts->mode = MONO_AOT_MODE_HYBRID;
7020 } else if (str_begins_with (arg, "threads=")) {
7021 opts->nthreads = atoi (arg + strlen ("threads="));
7022 } else if (str_begins_with (arg, "static")) {
7023 opts->static_link = TRUE;
7024 opts->no_dlsym = TRUE;
7025 } else if (str_begins_with (arg, "asmonly")) {
7026 opts->asm_only = TRUE;
7027 } else if (str_begins_with (arg, "asmwriter")) {
7028 opts->asm_writer = TRUE;
7029 } else if (str_begins_with (arg, "nodebug")) {
7030 opts->nodebug = TRUE;
7031 } else if (str_begins_with (arg, "dwarfdebug")) {
7032 opts->dwarf_debug = TRUE;
7033 } else if (str_begins_with (arg, "nopagetrampolines")) {
7034 opts->use_trampolines_page = FALSE;
7035 } else if (str_begins_with (arg, "ntrampolines=")) {
7036 opts->ntrampolines = atoi (arg + strlen ("ntrampolines="));
7037 } else if (str_begins_with (arg, "nrgctx-trampolines=")) {
7038 opts->nrgctx_trampolines = atoi (arg + strlen ("nrgctx-trampolines="));
7039 } else if (str_begins_with (arg, "nrgctx-fetch-trampolines=")) {
7040 opts->nrgctx_fetch_trampolines = atoi (arg + strlen ("nrgctx-fetch-trampolines="));
7041 } else if (str_begins_with (arg, "nimt-trampolines=")) {
7042 opts->nimt_trampolines = atoi (arg + strlen ("nimt-trampolines="));
7043 } else if (str_begins_with (arg, "ngsharedvt-trampolines=")) {
7044 opts->ngsharedvt_arg_trampolines = atoi (arg + strlen ("ngsharedvt-trampolines="));
7045 } else if (str_begins_with (arg, "tool-prefix=")) {
7046 opts->tool_prefix = g_strdup (arg + strlen ("tool-prefix="));
7047 } else if (str_begins_with (arg, "ld-flags=")) {
7048 opts->ld_flags = g_strdup (arg + strlen ("ld-flags="));
7049 } else if (str_begins_with (arg, "soft-debug")) {
7050 opts->soft_debug = TRUE;
7051 } else if (str_begins_with (arg, "gen-seq-points-file=")) {
7052 debug_options.gen_seq_points_compact_data = TRUE;
7053 opts->gen_seq_points_file = TRUE;
7054 opts->gen_seq_points_file_path = g_strdup (arg + strlen ("gen-seq-points-file="));;
7055 } else if (str_begins_with (arg, "gen-seq-points-file")) {
7056 debug_options.gen_seq_points_compact_data = TRUE;
7057 opts->gen_seq_points_file = TRUE;
7058 } else if (str_begins_with (arg, "direct-pinvoke")) {
7059 opts->direct_pinvoke = TRUE;
7060 } else if (str_begins_with (arg, "direct-icalls")) {
7061 opts->direct_icalls = TRUE;
7062 } else if (str_begins_with (arg, "no-direct-calls")) {
7063 opts->no_direct_calls = TRUE;
7064 } else if (str_begins_with (arg, "print-skipped")) {
7065 opts->print_skipped_methods = TRUE;
7066 } else if (str_begins_with (arg, "stats")) {
7068 } else if (str_begins_with (arg, "no-instances")) {
7069 opts->no_instances = TRUE;
7070 } else if (str_begins_with (arg, "log-generics")) {
7071 opts->log_generics = TRUE;
7072 } else if (str_begins_with (arg, "log-instances=")) {
7073 opts->log_instances = TRUE;
7074 opts->instances_logfile_path = g_strdup (arg + strlen ("log-instances="));
7075 } else if (str_begins_with (arg, "log-instances")) {
7076 opts->log_instances = TRUE;
7077 } else if (str_begins_with (arg, "internal-logfile=")) {
7078 opts->logfile = g_strdup (arg + strlen ("internal-logfile="));
7079 } else if (str_begins_with (arg, "mtriple=")) {
7080 opts->mtriple = g_strdup (arg + strlen ("mtriple="));
7081 } else if (str_begins_with (arg, "llvm-path=")) {
7082 opts->llvm_path = clean_path (g_strdup (arg + strlen ("llvm-path=")));
7083 } else if (!strcmp (arg, "llvm")) {
7085 } else if (str_begins_with (arg, "readonly-value=")) {
7086 add_readonly_value (opts, arg + strlen ("readonly-value="));
7087 } else if (str_begins_with (arg, "info")) {
7088 printf ("AOT target setup: %s.\n", AOT_TARGET_STR);
7090 } else if (str_begins_with (arg, "gc-maps")) {
7091 mini_gc_enable_gc_maps_for_aot ();
7092 } else if (str_begins_with (arg, "dump")) {
7093 opts->dump_json = TRUE;
7094 } else if (str_begins_with (arg, "llvmonly")) {
7095 opts->mode = MONO_AOT_MODE_FULL;
7097 opts->llvm_only = TRUE;
7098 } else if (str_begins_with (arg, "data-outfile=")) {
7099 opts->data_outfile = g_strdup (arg + strlen ("data-outfile="));
7100 } else if (str_begins_with (arg, "help") || str_begins_with (arg, "?")) {
7101 printf ("Supported options for --aot:\n");
7102 printf (" outfile=\n");
7103 printf (" llvm-outfile=\n");
7104 printf (" llvm-path=\n");
7105 printf (" temp-path=\n");
7106 printf (" save-temps\n");
7107 printf (" keep-temps\n");
7108 printf (" write-symbols\n");
7109 printf (" metadata-only\n");
7110 printf (" bind-to-runtime-version\n");
7112 printf (" threads=\n");
7113 printf (" static\n");
7114 printf (" asmonly\n");
7115 printf (" asmwriter\n");
7116 printf (" nodebug\n");
7117 printf (" dwarfdebug\n");
7118 printf (" ntrampolines=\n");
7119 printf (" nrgctx-trampolines=\n");
7120 printf (" nimt-trampolines=\n");
7121 printf (" ngsharedvt-trampolines=\n");
7122 printf (" tool-prefix=\n");
7123 printf (" readonly-value=\n");
7124 printf (" soft-debug\n");
7125 printf (" gen-seq-points-file\n");
7126 printf (" gc-maps\n");
7127 printf (" print-skipped\n");
7128 printf (" no-instances\n");
7129 printf (" stats\n");
7132 printf (" help/?\n");
7135 fprintf (stderr, "AOT : Unknown argument '%s'.\n", arg);
7139 g_free ((gpointer) arg);
7142 if (opts->use_trampolines_page) {
7143 opts->ntrampolines = 0;
7144 opts->nrgctx_trampolines = 0;
7145 opts->nimt_trampolines = 0;
7146 opts->ngsharedvt_arg_trampolines = 0;
7149 g_ptr_array_free (args, /*free_seg=*/TRUE);
7153 add_token_info_hash (gpointer key, gpointer value, gpointer user_data)
7155 MonoMethod *method = (MonoMethod*)key;
7156 MonoJumpInfoToken *ji = (MonoJumpInfoToken*)value;
7157 MonoAotCompile *acfg = (MonoAotCompile *)user_data;
7158 MonoJumpInfoToken *new_ji;
7160 new_ji = (MonoJumpInfoToken *)mono_mempool_alloc0 (acfg->mempool, sizeof (MonoJumpInfoToken));
7161 new_ji->image = ji->image;
7162 new_ji->token = ji->token;
7163 g_hash_table_insert (acfg->token_info_hash, method, new_ji);
7167 can_encode_class (MonoAotCompile *acfg, MonoClass *klass)
7169 if (klass->type_token)
7171 if ((klass->byval_arg.type == MONO_TYPE_VAR) || (klass->byval_arg.type == MONO_TYPE_MVAR) || (klass->byval_arg.type == MONO_TYPE_PTR))
7174 return can_encode_class (acfg, klass->element_class);
7179 can_encode_method (MonoAotCompile *acfg, MonoMethod *method)
7181 if (method->wrapper_type) {
7182 switch (method->wrapper_type) {
7183 case MONO_WRAPPER_NONE:
7184 case MONO_WRAPPER_REMOTING_INVOKE_WITH_CHECK:
7185 case MONO_WRAPPER_XDOMAIN_INVOKE:
7186 case MONO_WRAPPER_STFLD:
7187 case MONO_WRAPPER_LDFLD:
7188 case MONO_WRAPPER_LDFLDA:
7189 case MONO_WRAPPER_STFLD_REMOTE:
7190 case MONO_WRAPPER_STELEMREF:
7191 case MONO_WRAPPER_ISINST:
7192 case MONO_WRAPPER_PROXY_ISINST:
7193 case MONO_WRAPPER_ALLOC:
7194 case MONO_WRAPPER_REMOTING_INVOKE:
7195 case MONO_WRAPPER_UNKNOWN:
7196 case MONO_WRAPPER_WRITE_BARRIER:
7197 case MONO_WRAPPER_DELEGATE_INVOKE:
7198 case MONO_WRAPPER_DELEGATE_BEGIN_INVOKE:
7199 case MONO_WRAPPER_DELEGATE_END_INVOKE:
7200 case MONO_WRAPPER_SYNCHRONIZED:
7202 case MONO_WRAPPER_MANAGED_TO_MANAGED:
7203 case MONO_WRAPPER_CASTCLASS: {
7204 WrapperInfo *info = mono_marshal_get_wrapper_info (method);
7213 //printf ("Skip (wrapper call): %d -> %s\n", patch_info->type, mono_method_full_name (patch_info->data.method, TRUE));
7217 if (!method->token) {
7218 /* The method is part of a constructed type like Int[,].Set (). */
7219 if (!g_hash_table_lookup (acfg->token_info_hash, method)) {
7220 if (method->klass->rank)
7230 can_encode_patch (MonoAotCompile *acfg, MonoJumpInfo *patch_info)
7232 switch (patch_info->type) {
7233 case MONO_PATCH_INFO_METHOD:
7234 case MONO_PATCH_INFO_METHODCONST:
7235 case MONO_PATCH_INFO_METHOD_CODE_SLOT: {
7236 MonoMethod *method = patch_info->data.method;
7238 return can_encode_method (acfg, method);
7240 case MONO_PATCH_INFO_VTABLE:
7241 case MONO_PATCH_INFO_CLASS:
7242 case MONO_PATCH_INFO_IID:
7243 case MONO_PATCH_INFO_ADJUSTED_IID:
7244 if (!can_encode_class (acfg, patch_info->data.klass)) {
7245 //printf ("Skip: %s\n", mono_type_full_name (&patch_info->data.klass->byval_arg));
7249 case MONO_PATCH_INFO_DELEGATE_TRAMPOLINE: {
7250 if (!can_encode_class (acfg, patch_info->data.del_tramp->klass)) {
7251 //printf ("Skip: %s\n", mono_type_full_name (&patch_info->data.klass->byval_arg));
7256 case MONO_PATCH_INFO_RGCTX_FETCH:
7257 case MONO_PATCH_INFO_RGCTX_SLOT_INDEX: {
7258 MonoJumpInfoRgctxEntry *entry = patch_info->data.rgctx_entry;
7260 if (!can_encode_method (acfg, entry->method))
7262 if (!can_encode_patch (acfg, entry->data))
7274 is_concrete_type (MonoType *t)
7279 if (t->type == MONO_TYPE_VAR || t->type == MONO_TYPE_MVAR)
7281 if (t->type == MONO_TYPE_GENERICINST) {
7282 MonoGenericContext *orig_ctx;
7283 MonoGenericInst *inst;
7286 if (!MONO_TYPE_ISSTRUCT (t))
7288 klass = mono_class_from_mono_type (t);
7289 orig_ctx = &klass->generic_class->context;
7291 inst = orig_ctx->class_inst;
7293 for (i = 0; i < inst->type_argc; ++i) {
7294 arg = mini_get_underlying_type (inst->type_argv [i]);
7295 if (!is_concrete_type (arg))
7299 inst = orig_ctx->method_inst;
7301 for (i = 0; i < inst->type_argc; ++i) {
7302 arg = mini_get_underlying_type (inst->type_argv [i]);
7303 if (!is_concrete_type (arg))
7311 /* LOCKING: Assumes the loader lock is held */
7313 add_gsharedvt_wrappers (MonoAotCompile *acfg, MonoMethodSignature *sig, gboolean gsharedvt_in, gboolean gsharedvt_out)
7315 MonoMethod *wrapper;
7316 gboolean concrete = TRUE;
7317 gboolean add_in = gsharedvt_in;
7318 gboolean add_out = gsharedvt_out;
7320 if (gsharedvt_in && g_hash_table_lookup (acfg->gsharedvt_in_signatures, sig))
7322 if (gsharedvt_out && g_hash_table_lookup (acfg->gsharedvt_out_signatures, sig))
7325 if (!add_in && !add_out)
7328 if (mini_is_gsharedvt_variable_signature (sig))
7332 g_hash_table_insert (acfg->gsharedvt_in_signatures, sig, sig);
7334 g_hash_table_insert (acfg->gsharedvt_out_signatures, sig, sig);
7336 if (!sig->has_type_parameters) {
7337 //printf ("%s\n", mono_signature_full_name (sig));
7340 wrapper = mini_get_gsharedvt_in_sig_wrapper (sig);
7341 add_extra_method (acfg, wrapper);
7343 if (gsharedvt_out) {
7344 wrapper = mini_get_gsharedvt_out_sig_wrapper (sig);
7345 add_extra_method (acfg, wrapper);
7348 /* For signatures creared during generic sharing, convert them to a concrete signature if possible */
7349 MonoMethodSignature *copy = mono_metadata_signature_dup (sig);
7352 //printf ("%s\n", mono_signature_full_name (sig));
7354 copy->ret = mini_get_underlying_type (sig->ret);
7355 if (!is_concrete_type (copy->ret))
7357 for (i = 0; i < sig->param_count; ++i) {
7358 copy->params [i] = mini_get_underlying_type (sig->params [i]);
7359 if (!is_concrete_type (copy->params [i]))
7363 copy->has_type_parameters = 0;
7366 wrapper = mini_get_gsharedvt_in_sig_wrapper (copy);
7367 add_extra_method (acfg, wrapper);
7370 if (gsharedvt_out) {
7371 wrapper = mini_get_gsharedvt_out_sig_wrapper (copy);
7372 add_extra_method (acfg, wrapper);
7375 //printf ("%s\n", mono_method_full_name (wrapper, 1));
7383 * AOT compile a given method.
7384 * This function might be called by multiple threads, so it must be thread-safe.
7387 compile_method (MonoAotCompile *acfg, MonoMethod *method)
7390 MonoJumpInfo *patch_info;
7393 MonoMethod *wrapped;
7397 if (acfg->aot_opts.metadata_only)
7400 mono_acfg_lock (acfg);
7401 index = get_method_index (acfg, method);
7402 mono_acfg_unlock (acfg);
7404 /* fixme: maybe we can also precompile wrapper methods */
7405 if ((method->flags & METHOD_ATTRIBUTE_PINVOKE_IMPL) ||
7406 (method->iflags & METHOD_IMPL_ATTRIBUTE_RUNTIME) ||
7407 (method->flags & METHOD_ATTRIBUTE_ABSTRACT)) {
7408 //printf ("Skip (impossible): %s\n", mono_method_full_name (method, TRUE));
7412 if (method->iflags & METHOD_IMPL_ATTRIBUTE_INTERNAL_CALL)
7415 wrapped = mono_marshal_method_from_wrapper (method);
7416 if (wrapped && (wrapped->iflags & METHOD_IMPL_ATTRIBUTE_INTERNAL_CALL) && wrapped->is_generic)
7417 // FIXME: The wrapper should be generic too, but it is not
7420 if (method->wrapper_type == MONO_WRAPPER_COMINTEROP)
7423 InterlockedIncrement (&acfg->stats.mcount);
7426 if (method->is_generic || method->klass->generic_container) {
7427 InterlockedIncrement (&acfg->stats.genericcount);
7432 //acfg->aot_opts.print_skipped_methods = TRUE;
7435 * Since these methods are the only ones which are compiled with
7436 * AOT support, and they are not used by runtime startup/shutdown code,
7437 * the runtime will not see AOT methods during AOT compilation,so it
7438 * does not need to support them by creating a fake GOT etc.
7440 flags = JIT_FLAG_AOT;
7441 if (mono_aot_mode_is_full (&acfg->aot_opts))
7442 flags = (JitFlags)(flags | JIT_FLAG_FULL_AOT);
7444 flags = (JitFlags)(flags | JIT_FLAG_LLVM);
7445 if (acfg->aot_opts.llvm_only)
7446 flags = (JitFlags)(flags | JIT_FLAG_LLVM_ONLY | JIT_FLAG_EXPLICIT_NULL_CHECKS);
7447 if (acfg->aot_opts.no_direct_calls)
7448 flags = (JitFlags)(flags | JIT_FLAG_NO_DIRECT_ICALLS);
7450 jit_timer = mono_time_track_start ();
7451 cfg = mini_method_compile (method, acfg->opts, mono_get_root_domain (), flags, 0, index);
7452 mono_time_track_end (&mono_jit_stats.jit_time, jit_timer);
7454 if (cfg->exception_type == MONO_EXCEPTION_GENERIC_SHARING_FAILED) {
7455 if (acfg->aot_opts.print_skipped_methods)
7456 printf ("Skip (gshared failure): %s (%s)\n", mono_method_get_full_name (method), cfg->exception_message);
7457 InterlockedIncrement (&acfg->stats.genericcount);
7460 if (cfg->exception_type != MONO_EXCEPTION_NONE) {
7461 if (acfg->aot_opts.print_skipped_methods)
7462 printf ("Skip (JIT failure): %s\n", mono_method_get_full_name (method));
7463 /* Let the exception happen at runtime */
7467 if (cfg->disable_aot) {
7468 if (acfg->aot_opts.print_skipped_methods)
7469 printf ("Skip (disabled): %s\n", mono_method_get_full_name (method));
7470 InterlockedIncrement (&acfg->stats.ocount);
7473 cfg->method_index = index;
7475 /* Nullify patches which need no aot processing */
7476 for (patch_info = cfg->patch_info; patch_info; patch_info = patch_info->next) {
7477 switch (patch_info->type) {
7478 case MONO_PATCH_INFO_LABEL:
7479 case MONO_PATCH_INFO_BB:
7480 patch_info->type = MONO_PATCH_INFO_NONE;
7487 /* Collect method->token associations from the cfg */
7488 mono_acfg_lock (acfg);
7489 g_hash_table_foreach (cfg->token_info_hash, add_token_info_hash, acfg);
7490 mono_acfg_unlock (acfg);
7491 g_hash_table_destroy (cfg->token_info_hash);
7492 cfg->token_info_hash = NULL;
7495 * Check for absolute addresses.
7498 for (patch_info = cfg->patch_info; patch_info; patch_info = patch_info->next) {
7499 switch (patch_info->type) {
7500 case MONO_PATCH_INFO_ABS:
7501 /* unable to handle this */
7510 if (acfg->aot_opts.print_skipped_methods)
7511 printf ("Skip (abs call): %s\n", mono_method_get_full_name (method));
7512 InterlockedIncrement (&acfg->stats.abscount);
7516 /* Lock for the rest of the code */
7517 mono_acfg_lock (acfg);
7520 acfg->stats.method_categories [METHOD_CAT_GSHAREDVT] ++;
7521 else if (cfg->gshared)
7522 acfg->stats.method_categories [METHOD_CAT_INST] ++;
7523 else if (cfg->method->wrapper_type)
7524 acfg->stats.method_categories [METHOD_CAT_WRAPPER] ++;
7526 acfg->stats.method_categories [METHOD_CAT_NORMAL] ++;
7529 * Check for methods/klasses we can't encode.
7532 for (patch_info = cfg->patch_info; patch_info; patch_info = patch_info->next) {
7533 if (!can_encode_patch (acfg, patch_info))
7538 if (acfg->aot_opts.print_skipped_methods)
7539 printf ("Skip (patches): %s\n", mono_method_get_full_name (method));
7540 acfg->stats.ocount++;
7541 mono_acfg_unlock (acfg);
7545 if (!cfg->compile_llvm)
7546 acfg->has_jitted_code = TRUE;
7548 if (method->is_inflated && acfg->aot_opts.log_instances) {
7549 if (acfg->instances_logfile)
7550 fprintf (acfg->instances_logfile, "%s ### %d\n", mono_method_get_full_name (method), cfg->code_size);
7552 printf ("%s ### %d\n", mono_method_get_full_name (method), cfg->code_size);
7555 /* Adds generic instances referenced by this method */
7557 * The depth is used to avoid infinite loops when generic virtual recursion is
7560 depth = GPOINTER_TO_UINT (g_hash_table_lookup (acfg->method_depth, method));
7561 if (!acfg->aot_opts.no_instances && depth < 32) {
7562 for (patch_info = cfg->patch_info; patch_info; patch_info = patch_info->next) {
7563 switch (patch_info->type) {
7564 case MONO_PATCH_INFO_RGCTX_FETCH:
7565 case MONO_PATCH_INFO_RGCTX_SLOT_INDEX:
7566 case MONO_PATCH_INFO_METHOD: {
7567 MonoMethod *m = NULL;
7569 if (patch_info->type == MONO_PATCH_INFO_RGCTX_FETCH || patch_info->type == MONO_PATCH_INFO_RGCTX_SLOT_INDEX) {
7570 MonoJumpInfoRgctxEntry *e = patch_info->data.rgctx_entry;
7572 if (e->info_type == MONO_RGCTX_INFO_GENERIC_METHOD_CODE)
7573 m = e->data->data.method;
7575 m = patch_info->data.method;
7580 if (m->is_inflated) {
7581 if (!(mono_class_generic_sharing_enabled (m->klass) &&
7582 mono_method_is_generic_sharable_full (m, FALSE, FALSE, FALSE)) &&
7583 (!method_has_type_vars (m) || mono_method_is_generic_sharable_full (m, TRUE, TRUE, FALSE))) {
7584 if (m->iflags & METHOD_IMPL_ATTRIBUTE_INTERNAL_CALL) {
7585 if (mono_aot_mode_is_full (&acfg->aot_opts) && !method_has_type_vars (m))
7586 add_extra_method_with_depth (acfg, mono_marshal_get_native_wrapper (m, TRUE, TRUE), depth + 1);
7588 add_extra_method_with_depth (acfg, m, depth + 1);
7589 add_types_from_method_header (acfg, m);
7592 add_generic_class_with_depth (acfg, m->klass, depth + 5, "method");
7594 if (m->wrapper_type == MONO_WRAPPER_MANAGED_TO_MANAGED) {
7595 WrapperInfo *info = mono_marshal_get_wrapper_info (m);
7597 if (info && info->subtype == WRAPPER_SUBTYPE_ELEMENT_ADDR)
7598 add_extra_method_with_depth (acfg, m, depth + 1);
7602 case MONO_PATCH_INFO_VTABLE: {
7603 MonoClass *klass = patch_info->data.klass;
7605 if (klass->generic_class && !mini_class_is_generic_sharable (klass))
7606 add_generic_class_with_depth (acfg, klass, depth + 5, "vtable");
7609 case MONO_PATCH_INFO_SFLDA: {
7610 MonoClass *klass = patch_info->data.field->parent;
7612 /* The .cctor needs to run at runtime. */
7613 if (klass->generic_class && !mono_generic_context_is_sharable_full (&klass->generic_class->context, FALSE, FALSE) && mono_class_get_cctor (klass))
7614 add_extra_method_with_depth (acfg, mono_class_get_cctor (klass), depth + 1);
7623 /* Determine whenever the method has GOT slots */
7624 for (patch_info = cfg->patch_info; patch_info; patch_info = patch_info->next) {
7625 switch (patch_info->type) {
7626 case MONO_PATCH_INFO_GOT_OFFSET:
7627 case MONO_PATCH_INFO_NONE:
7628 case MONO_PATCH_INFO_GC_CARD_TABLE_ADDR:
7629 case MONO_PATCH_INFO_GC_NURSERY_START:
7630 case MONO_PATCH_INFO_GC_NURSERY_BITS:
7632 case MONO_PATCH_INFO_IMAGE:
7633 /* The assembly is stored in GOT slot 0 */
7634 if (patch_info->data.image != acfg->image)
7635 cfg->has_got_slots = TRUE;
7638 if (!is_plt_patch (patch_info) || (cfg->compile_llvm && acfg->aot_opts.llvm_only))
7639 cfg->has_got_slots = TRUE;
7644 if (!cfg->has_got_slots)
7645 InterlockedIncrement (&acfg->stats.methods_without_got_slots);
7647 /* Add gsharedvt wrappers for signatures used by the method */
7648 if (acfg->aot_opts.llvm_only) {
7651 if (!cfg->method->wrapper_type || cfg->method->wrapper_type == MONO_WRAPPER_DELEGATE_INVOKE)
7652 /* These only need out wrappers */
7653 add_gsharedvt_wrappers (acfg, mono_method_signature (cfg->method), FALSE, TRUE);
7655 for (l = cfg->signatures; l; l = l->next) {
7656 MonoMethodSignature *sig = mono_metadata_signature_dup ((MonoMethodSignature*)l->data);
7658 /* These only need in wrappers */
7659 add_gsharedvt_wrappers (acfg, sig, TRUE, FALSE);
7664 * FIXME: Instead of this mess, allocate the patches from the aot mempool.
7666 /* Make a copy of the patch info which is in the mempool */
7668 MonoJumpInfo *patches = NULL, *patches_end = NULL;
7670 for (patch_info = cfg->patch_info; patch_info; patch_info = patch_info->next) {
7671 MonoJumpInfo *new_patch_info = mono_patch_info_dup_mp (acfg->mempool, patch_info);
7674 patches = new_patch_info;
7676 patches_end->next = new_patch_info;
7677 patches_end = new_patch_info;
7679 cfg->patch_info = patches;
7681 /* Make a copy of the unwind info */
7683 GSList *l, *unwind_ops;
7687 for (l = cfg->unwind_ops; l; l = l->next) {
7688 op = (MonoUnwindOp *)mono_mempool_alloc (acfg->mempool, sizeof (MonoUnwindOp));
7689 memcpy (op, l->data, sizeof (MonoUnwindOp));
7690 unwind_ops = g_slist_prepend_mempool (acfg->mempool, unwind_ops, op);
7692 cfg->unwind_ops = g_slist_reverse (unwind_ops);
7694 /* Make a copy of the argument/local info */
7697 MonoInst **args, **locals;
7698 MonoMethodSignature *sig;
7699 MonoMethodHeader *header;
7702 sig = mono_method_signature (method);
7703 args = (MonoInst **)mono_mempool_alloc (acfg->mempool, sizeof (MonoInst*) * (sig->param_count + sig->hasthis));
7704 for (i = 0; i < sig->param_count + sig->hasthis; ++i) {
7705 args [i] = (MonoInst *)mono_mempool_alloc (acfg->mempool, sizeof (MonoInst));
7706 memcpy (args [i], cfg->args [i], sizeof (MonoInst));
7710 header = mono_method_get_header_checked (method, &error);
7711 mono_error_assert_ok (&error); /* FIXME don't swallow the error */
7712 locals = (MonoInst **)mono_mempool_alloc (acfg->mempool, sizeof (MonoInst*) * header->num_locals);
7713 for (i = 0; i < header->num_locals; ++i) {
7714 locals [i] = (MonoInst *)mono_mempool_alloc (acfg->mempool, sizeof (MonoInst));
7715 memcpy (locals [i], cfg->locals [i], sizeof (MonoInst));
7717 cfg->locals = locals;
7720 /* Free some fields used by cfg to conserve memory */
7721 mono_free_loop_info (cfg);
7722 mono_mempool_destroy (cfg->mempool);
7723 cfg->mempool = NULL;
7724 g_free (cfg->varinfo);
7725 cfg->varinfo = NULL;
7729 mono_regstate_free (cfg->rs);
7733 //printf ("Compile: %s\n", mono_method_full_name (method, TRUE));
7735 while (index >= acfg->cfgs_size) {
7736 MonoCompile **new_cfgs;
7739 new_size = acfg->cfgs_size * 2;
7740 new_cfgs = g_new0 (MonoCompile*, new_size);
7741 memcpy (new_cfgs, acfg->cfgs, sizeof (MonoCompile*) * acfg->cfgs_size);
7742 g_free (acfg->cfgs);
7743 acfg->cfgs = new_cfgs;
7744 acfg->cfgs_size = new_size;
7746 acfg->cfgs [index] = cfg;
7748 g_hash_table_insert (acfg->method_to_cfg, cfg->orig_method, cfg);
7750 mono_update_jit_stats (cfg);
7753 if (cfg->orig_method->wrapper_type)
7754 g_ptr_array_add (acfg->extra_methods, cfg->orig_method);
7757 mono_acfg_unlock (acfg);
7759 InterlockedIncrement (&acfg->stats.ccount);
7763 compile_thread_main (gpointer *user_data)
7765 MonoDomain *domain = (MonoDomain *)user_data [0];
7766 MonoAotCompile *acfg = (MonoAotCompile *)user_data [1];
7767 GPtrArray *methods = (GPtrArray *)user_data [2];
7771 MonoThread *thread = mono_thread_attach (domain);
7772 mono_thread_set_name_internal (thread->internal_thread, mono_string_new (mono_get_root_domain (), "AOT compiler"), TRUE, &error);
7773 mono_error_assert_ok (&error);
7775 for (i = 0; i < methods->len; ++i)
7776 compile_method (acfg, (MonoMethod *)g_ptr_array_index (methods, i));
7780 load_profile_files (MonoAotCompile *acfg)
7784 int file_index, res, method_index, i;
7787 GList *unordered, *l;
7792 tmp = g_strdup_printf ("%s/.mono/aot-profile-data/%s-%d", g_get_home_dir (), acfg->image->assembly_name, file_index);
7794 if (!g_file_test (tmp, G_FILE_TEST_IS_REGULAR)) {
7799 infile = fopen (tmp, "r");
7802 printf ("Using profile data file '%s'\n", tmp);
7807 res = fscanf (infile, "%32s\n", ver);
7808 if ((res != 1) || strcmp (ver, "#VER:2") != 0) {
7809 printf ("Profile file has wrong version or invalid.\n");
7816 MonoMethodDesc *desc;
7819 if (fgets (name, 1023, infile) == NULL)
7822 /* Kill the newline */
7823 if (strlen (name) > 0)
7824 name [strlen (name) - 1] = '\0';
7826 desc = mono_method_desc_new (name, TRUE);
7828 method = mono_method_desc_search_in_image (desc, acfg->image);
7830 if (method && mono_method_get_token (method)) {
7831 token = mono_method_get_token (method);
7832 method_index = mono_metadata_token_index (token) - 1;
7835 for (i = 0; i < acfg->method_order->len; ++i) {
7836 if (g_ptr_array_index (acfg->method_order, i) == GUINT_TO_POINTER (method_index)) {
7842 g_ptr_array_add (acfg->method_order, GUINT_TO_POINTER (method_index));
7844 //printf ("No method found matching '%s'.\n", name);
7850 /* Add missing methods */
7852 for (method_index = 0; method_index < acfg->image->tables [MONO_TABLE_METHOD].rows; ++method_index) {
7854 for (i = 0; i < acfg->method_order->len; ++i) {
7855 if (g_ptr_array_index (acfg->method_order, i) == GUINT_TO_POINTER (method_index)) {
7861 unordered = g_list_prepend (unordered, GUINT_TO_POINTER (method_index));
7863 unordered = g_list_reverse (unordered);
7864 for (l = unordered; l; l = l->next)
7865 g_ptr_array_add (acfg->method_order, l->data);
7868 /* Used by the LLVM backend */
7870 mono_aot_get_got_offset (MonoJumpInfo *ji)
7872 return get_got_offset (llvm_acfg, TRUE, ji);
7876 * mono_aot_is_shared_got_offset:
7878 * Return whenever OFFSET refers to a GOT slot which is preinitialized
7879 * when the AOT image is loaded.
7882 mono_aot_is_shared_got_offset (int offset)
7884 return offset < llvm_acfg->nshared_got_entries;
7888 mono_aot_get_method_name (MonoCompile *cfg)
7890 if (llvm_acfg->aot_opts.static_link)
7891 /* Include the assembly name too to avoid duplicate symbol errors */
7892 return g_strdup_printf ("%s_%s", llvm_acfg->assembly_name_sym, get_debug_sym (cfg->orig_method, "", llvm_acfg->method_label_hash));
7894 return get_debug_sym (cfg->orig_method, "", llvm_acfg->method_label_hash);
7898 * mono_aot_is_linkonce_method:
7900 * Return whenever METHOD should be emitted with linkonce linkage,
7901 * eliminating duplicate copies when compiling in static mode.
7904 mono_aot_is_linkonce_method (MonoMethod *method)
7910 // FIXME: Add more cases
7911 if (method->wrapper_type != MONO_WRAPPER_UNKNOWN)
7913 info = mono_marshal_get_wrapper_info (method);
7914 if ((info && (info->subtype == WRAPPER_SUBTYPE_GSHAREDVT_IN_SIG || info->subtype == WRAPPER_SUBTYPE_GSHAREDVT_OUT_SIG)))
7921 append_mangled_type (GString *s, MonoType *t)
7924 g_string_append_printf (s, "b");
7926 case MONO_TYPE_VOID:
7927 g_string_append_printf (s, "void_");
7930 g_string_append_printf (s, "i1");
7933 g_string_append_printf (s, "u1");
7936 g_string_append_printf (s, "i2");
7939 g_string_append_printf (s, "u2");
7942 g_string_append_printf (s, "i4");
7945 g_string_append_printf (s, "u4");
7948 g_string_append_printf (s, "i8");
7951 g_string_append_printf (s, "u8");
7954 g_string_append_printf (s, "ii");
7957 g_string_append_printf (s, "ui");
7960 g_string_append_printf (s, "fl");
7963 g_string_append_printf (s, "do");
7966 char *fullname = mono_type_full_name (t);
7972 * Have to create a mangled name which is:
7976 temp = g_string_new ("");
7977 len = strlen (fullname);
7978 for (i = 0; i < len; ++i) {
7979 char c = fullname [i];
7981 g_string_append_c (temp, c);
7982 } else if (c == '_') {
7983 g_string_append_c (temp, '_');
7984 g_string_append_c (temp, '_');
7986 g_string_append_c (temp, '_');
7987 g_string_append_printf (temp, "%x", (int)c);
7990 temps = g_string_free (temp, FALSE);
7991 /* Include the length to avoid different length type names aliasing each other */
7992 g_string_append_printf (s, "cl%x_%s_", strlen (temps), temps);
8001 append_mangled_signature (GString *s, MonoMethodSignature *sig)
8006 supported = append_mangled_type (s, sig->ret);
8010 g_string_append_printf (s, "this_");
8011 for (i = 0; i < sig->param_count; ++i) {
8012 supported = append_mangled_type (s, sig->params [i]);
8021 * mono_aot_get_mangled_method_name:
8023 * Return a unique mangled name for METHOD, or NULL.
8026 mono_aot_get_mangled_method_name (MonoMethod *method)
8032 // FIXME: Add more cases
8033 if (method->wrapper_type != MONO_WRAPPER_UNKNOWN)
8035 info = mono_marshal_get_wrapper_info (method);
8036 if (!(info && (info->subtype == WRAPPER_SUBTYPE_GSHAREDVT_IN_SIG || info->subtype == WRAPPER_SUBTYPE_GSHAREDVT_OUT_SIG)))
8039 s = g_string_new ("");
8041 g_string_append_printf (s, "aot_method_w_");
8043 switch (info->subtype) {
8044 case WRAPPER_SUBTYPE_GSHAREDVT_IN_SIG:
8045 g_string_append_printf (s, "gsharedvt_in_");
8047 case WRAPPER_SUBTYPE_GSHAREDVT_OUT_SIG:
8048 g_string_append_printf (s, "gsharedvt_out_");
8051 g_assert_not_reached ();
8055 supported = append_mangled_signature (s, info->d.gsharedvt.sig);
8057 g_string_free (s, TRUE);
8061 return g_string_free (s, FALSE);
8065 mono_aot_is_direct_callable (MonoJumpInfo *patch_info)
8067 return is_direct_callable (llvm_acfg, NULL, patch_info);
8071 mono_aot_mark_unused_llvm_plt_entry (MonoJumpInfo *patch_info)
8073 MonoPltEntry *plt_entry;
8075 plt_entry = get_plt_entry (llvm_acfg, patch_info);
8076 plt_entry->llvm_used = FALSE;
8080 mono_aot_get_direct_call_symbol (MonoJumpInfoType type, gconstpointer data)
8082 const char *sym = NULL;
8084 if (llvm_acfg->aot_opts.direct_icalls) {
8085 if (type == MONO_PATCH_INFO_JIT_ICALL_ADDR) {
8086 /* Call to a C function implementing a jit icall */
8087 sym = mono_lookup_jit_icall_symbol ((const char *)data);
8088 } else if (type == MONO_PATCH_INFO_ICALL_ADDR_CALL) {
8089 MonoMethod *method = (MonoMethod *)data;
8090 if (!(method->flags & METHOD_ATTRIBUTE_PINVOKE_IMPL))
8091 sym = mono_lookup_icall_symbol (method);
8092 else if (llvm_acfg->aot_opts.direct_pinvoke)
8093 sym = get_pinvoke_import (llvm_acfg, method);
8096 return g_strdup (sym);
8102 mono_aot_get_plt_symbol (MonoJumpInfoType type, gconstpointer data)
8104 MonoJumpInfo *ji = (MonoJumpInfo *)mono_mempool_alloc (llvm_acfg->mempool, sizeof (MonoJumpInfo));
8105 MonoPltEntry *plt_entry;
8106 const char *sym = NULL;
8109 ji->data.target = data;
8111 if (!can_encode_patch (llvm_acfg, ji))
8114 if (llvm_acfg->aot_opts.direct_icalls) {
8115 if (type == MONO_PATCH_INFO_JIT_ICALL_ADDR) {
8116 /* Call to a C function implementing a jit icall */
8117 sym = mono_lookup_jit_icall_symbol ((const char *)data);
8118 } else if (type == MONO_PATCH_INFO_ICALL_ADDR_CALL) {
8119 MonoMethod *method = (MonoMethod *)data;
8120 if (!(method->flags & METHOD_ATTRIBUTE_PINVOKE_IMPL))
8121 sym = mono_lookup_icall_symbol (method);
8124 return g_strdup (sym);
8127 plt_entry = get_plt_entry (llvm_acfg, ji);
8128 plt_entry->llvm_used = TRUE;
8130 #if defined(TARGET_MACH)
8131 return g_strdup_printf (plt_entry->llvm_symbol + strlen (llvm_acfg->llvm_label_prefix));
8133 return g_strdup_printf (plt_entry->llvm_symbol);
8138 mono_aot_get_method_index (MonoMethod *method)
8140 g_assert (llvm_acfg);
8141 return get_method_index (llvm_acfg, method);
8145 mono_aot_patch_info_dup (MonoJumpInfo* ji)
8149 mono_acfg_lock (llvm_acfg);
8150 res = mono_patch_info_dup_mp (llvm_acfg->mempool, ji);
8151 mono_acfg_unlock (llvm_acfg);
8157 execute_system (const char * command)
8162 // We need an extra set of quotes around the whole command to properly handle commands
8163 // with spaces since internally the command is called through "cmd /c.
8164 command = g_strdup_printf ("\"%s\"", command);
8166 int size = MultiByteToWideChar (CP_UTF8, 0 , command , -1, NULL , 0);
8167 wchar_t* wstr = g_malloc (sizeof (wchar_t) * size);
8168 MultiByteToWideChar (CP_UTF8, 0, command, -1, wstr , size);
8169 status = _wsystem (wstr);
8173 #elif defined (HAVE_SYSTEM)
8174 status = system (command);
8176 g_assert_not_reached ();
8187 * Emit the LLVM code into an LLVM bytecode file, and compile it using the LLVM
8191 emit_llvm_file (MonoAotCompile *acfg)
8193 char *command, *opts, *tempbc, *optbc, *output_fname;
8195 if (acfg->aot_opts.llvm_only && acfg->aot_opts.asm_only) {
8196 tempbc = g_strdup_printf ("%s.bc", acfg->tmpbasename);
8197 optbc = g_strdup (acfg->aot_opts.llvm_outfile);
8199 tempbc = g_strdup_printf ("%s.bc", acfg->tmpbasename);
8200 optbc = g_strdup_printf ("%s.opt.bc", acfg->tmpbasename);
8203 mono_llvm_emit_aot_module (tempbc, g_path_get_basename (acfg->image->name));
8206 * FIXME: Experiment with adding optimizations, the -std-compile-opts set takes
8207 * a lot of time, and doesn't seem to save much space.
8208 * The following optimizations cannot be enabled:
8210 * - 'jump-threading' changes our blockaddress references to int constants.
8211 * - 'basiccg' fails because it contains:
8212 * if (CS && !isa<IntrinsicInst>(II)) {
8213 * and isa<IntrinsicInst> is false for invokes to intrinsics (iltests.exe).
8214 * - 'prune-eh' and 'functionattrs' depend on 'basiccg'.
8215 * The opt list below was produced by taking the output of:
8216 * llvm-as < /dev/null | opt -O2 -disable-output -debug-pass=Arguments
8217 * then removing tailcallelim + the global opts.
8218 * strip-dead-prototypes deletes unused intrinsics definitions.
8220 /* The dse pass is disabled because of #13734 and #17616 */
8222 * The dse bug is in DeadStoreElimination.cpp:isOverwrite ():
8223 * // If we have no DataLayout information around, then the size of the store
8224 * // is inferrable from the pointee type. If they are the same type, then
8225 * // we know that the store is safe.
8226 * if (AA.getDataLayout() == 0 &&
8227 * Later.Ptr->getType() == Earlier.Ptr->getType()) {
8228 * return OverwriteComplete;
8229 * Here, if 'Earlier' refers to a memset, and Later has no size info, it mistakenly thinks the memset is redundant.
8231 if (acfg->aot_opts.llvm_only)
8232 // FIXME: This doesn't work yet
8233 opts = g_strdup ("");
8235 #if LLVM_API_VERSION > 100
8236 opts = g_strdup ("-O2");
8238 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");
8240 command = g_strdup_printf ("\"%sopt\" -f %s -o \"%s\" \"%s\"", acfg->aot_opts.llvm_path, opts, optbc, tempbc);
8241 aot_printf (acfg, "Executing opt: %s\n", command);
8242 if (execute_system (command) != 0)
8246 if (acfg->aot_opts.llvm_only && acfg->aot_opts.asm_only)
8247 /* Nothing else to do */
8250 if (acfg->aot_opts.llvm_only) {
8251 /* Use the stock clang from xcode */
8253 command = g_strdup_printf ("clang -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);
8255 aot_printf (acfg, "Executing clang: %s\n", command);
8256 if (execute_system (command) != 0)
8261 if (!acfg->llc_args)
8262 acfg->llc_args = g_string_new ("");
8264 /* Verbose asm slows down llc greatly */
8265 g_string_append (acfg->llc_args, " -asm-verbose=false");
8267 if (acfg->aot_opts.mtriple)
8268 g_string_append_printf (acfg->llc_args, " -mtriple=%s", acfg->aot_opts.mtriple);
8270 g_string_append (acfg->llc_args, " -disable-gnu-eh-frame -enable-mono-eh-frame");
8272 g_string_append_printf (acfg->llc_args, " -mono-eh-frame-symbol=%s%s", acfg->user_symbol_prefix, acfg->llvm_eh_frame_symbol);
8274 #if LLVM_API_VERSION > 100
8275 g_string_append_printf (acfg->llc_args, " -disable-tail-calls");
8278 #if defined(TARGET_MACH) && defined(TARGET_ARM)
8279 /* ios requires PIC code now */
8280 g_string_append_printf (acfg->llc_args, " -relocation-model=pic");
8282 if (llvm_acfg->aot_opts.static_link)
8283 g_string_append_printf (acfg->llc_args, " -relocation-model=static");
8285 g_string_append_printf (acfg->llc_args, " -relocation-model=pic");
8288 if (acfg->llvm_owriter) {
8289 /* Emit an object file directly */
8290 output_fname = g_strdup_printf ("%s", acfg->llvm_ofile);
8291 g_string_append_printf (acfg->llc_args, " -filetype=obj");
8293 output_fname = g_strdup_printf ("%s", acfg->llvm_sfile);
8295 command = g_strdup_printf ("\"%sllc\" %s -o \"%s\" \"%s.opt.bc\"", acfg->aot_opts.llvm_path, acfg->llc_args->str, output_fname, acfg->tmpbasename);
8296 g_free (output_fname);
8298 aot_printf (acfg, "Executing llc: %s\n", command);
8300 if (execute_system (command) != 0)
8307 emit_code (MonoAotCompile *acfg)
8309 int oindex, i, prev_index;
8310 gboolean saved_unbox_info = FALSE;
8311 char symbol [MAX_SYMBOL_SIZE];
8313 if (acfg->aot_opts.llvm_only)
8316 #if defined(TARGET_POWERPC64)
8317 sprintf (symbol, ".Lgot_addr");
8318 emit_section_change (acfg, ".text", 0);
8319 emit_alignment (acfg, 8);
8320 emit_label (acfg, symbol);
8321 emit_pointer (acfg, acfg->got_symbol);
8325 * This global symbol is used to compute the address of each method using the
8326 * code_offsets array. It is also used to compute the memory ranges occupied by
8327 * AOT code, so it must be equal to the address of the first emitted method.
8329 emit_section_change (acfg, ".text", 0);
8330 emit_alignment_code (acfg, 8);
8331 emit_info_symbol (acfg, "jit_code_start");
8334 * Emit some padding so the local symbol for the first method doesn't have the
8335 * same address as 'methods'.
8337 emit_padding (acfg, 16);
8339 for (oindex = 0; oindex < acfg->method_order->len; ++oindex) {
8343 i = GPOINTER_TO_UINT (g_ptr_array_index (acfg->method_order, oindex));
8345 cfg = acfg->cfgs [i];
8350 method = cfg->orig_method;
8352 /* Emit unbox trampoline */
8353 if (mono_aot_mode_is_full (&acfg->aot_opts) && cfg->orig_method->klass->valuetype && !(acfg->aot_opts.llvm_only && cfg->compile_llvm)) {
8354 sprintf (symbol, "ut_%d", get_method_index (acfg, method));
8356 emit_section_change (acfg, ".text", 0);
8358 if (acfg->thumb_mixed && cfg->compile_llvm) {
8359 emit_set_thumb_mode (acfg);
8360 fprintf (acfg->fp, "\n.thumb_func\n");
8363 emit_label (acfg, symbol);
8365 arch_emit_unbox_trampoline (acfg, cfg, cfg->orig_method, cfg->asm_symbol);
8367 if (acfg->thumb_mixed && cfg->compile_llvm)
8368 emit_set_arm_mode (acfg);
8370 if (!saved_unbox_info) {
8371 char user_symbol [128];
8373 sprintf (user_symbol, "%sunbox_trampoline_p", acfg->user_symbol_prefix);
8375 emit_label (acfg, "ut_end");
8377 unwind_ops = mono_unwind_get_cie_program ();
8378 save_unwind_info (acfg, user_symbol, unwind_ops);
8379 mono_free_unwind_info (unwind_ops);
8381 /* Save the unbox trampoline size */
8382 emit_symbol_diff (acfg, "ut_end", symbol, 0);
8384 saved_unbox_info = TRUE;
8388 if (cfg->compile_llvm)
8389 acfg->stats.llvm_count ++;
8391 emit_method_code (acfg, cfg);
8394 emit_section_change (acfg, ".text", 0);
8395 emit_alignment_code (acfg, 8);
8396 emit_info_symbol (acfg, "jit_code_end");
8398 /* To distinguish it from the next symbol */
8399 emit_padding (acfg, 4);
8402 * Add .no_dead_strip directives for all LLVM methods to prevent the OSX linker
8403 * from optimizing them away, since it doesn't see that code_offsets references them.
8404 * JITted methods don't need this since they are referenced using assembler local
8406 * FIXME: This is why write-symbols doesn't work on OSX ?
8408 if (acfg->llvm && acfg->need_no_dead_strip) {
8409 fprintf (acfg->fp, "\n");
8410 for (i = 0; i < acfg->nmethods; ++i) {
8411 if (acfg->cfgs [i] && acfg->cfgs [i]->compile_llvm)
8412 fprintf (acfg->fp, ".no_dead_strip %s\n", acfg->cfgs [i]->asm_symbol);
8417 * To work around linker issues, we emit a table of branches, and disassemble them at runtime.
8418 * This is PIE code, and the linker can update it if needed.
8421 sprintf (symbol, "method_addresses");
8422 emit_section_change (acfg, ".text", 1);
8423 emit_alignment_code (acfg, 8);
8424 emit_info_symbol (acfg, symbol);
8425 emit_local_symbol (acfg, symbol, "method_addresses_end", TRUE);
8426 emit_unset_mode (acfg);
8427 if (acfg->need_no_dead_strip)
8428 fprintf (acfg->fp, " .no_dead_strip %s\n", symbol);
8430 for (i = 0; i < acfg->nmethods; ++i) {
8431 #ifdef MONO_ARCH_AOT_SUPPORTED
8434 if (acfg->cfgs [i]) {
8435 if (acfg->aot_opts.llvm_only && acfg->cfgs [i]->compile_llvm)
8436 /* Obtained by calling a generated function in the LLVM image */
8437 arch_emit_direct_call (acfg, symbol, FALSE, FALSE, NULL, &call_size);
8439 arch_emit_direct_call (acfg, acfg->cfgs [i]->asm_symbol, FALSE, acfg->thumb_mixed && acfg->cfgs [i]->compile_llvm, NULL, &call_size);
8441 arch_emit_direct_call (acfg, symbol, FALSE, FALSE, NULL, &call_size);
8446 sprintf (symbol, "method_addresses_end");
8447 emit_label (acfg, symbol);
8450 /* Emit a sorted table mapping methods to the index of their unbox trampolines */
8451 sprintf (symbol, "unbox_trampolines");
8452 emit_section_change (acfg, RODATA_SECT, 0);
8453 emit_alignment (acfg, 8);
8454 emit_info_symbol (acfg, symbol);
8457 for (i = 0; i < acfg->nmethods; ++i) {
8462 cfg = acfg->cfgs [i];
8466 method = cfg->orig_method;
8468 if (mono_aot_mode_is_full (&acfg->aot_opts) && cfg->orig_method->klass->valuetype && !(acfg->aot_opts.llvm_only && cfg->compile_llvm)) {
8469 index = get_method_index (acfg, method);
8471 emit_int32 (acfg, index);
8472 /* Make sure the table is sorted by index */
8473 g_assert (index > prev_index);
8477 sprintf (symbol, "unbox_trampolines_end");
8478 emit_info_symbol (acfg, symbol);
8479 emit_int32 (acfg, 0);
8481 /* Emit a separate table with the trampoline addresses/offsets */
8482 sprintf (symbol, "unbox_trampoline_addresses");
8483 emit_section_change (acfg, ".text", 0);
8484 emit_alignment_code (acfg, 8);
8485 emit_info_symbol (acfg, symbol);
8487 for (i = 0; i < acfg->nmethods; ++i) {
8492 cfg = acfg->cfgs [i];
8496 method = cfg->orig_method;
8498 if (mono_aot_mode_is_full (&acfg->aot_opts) && cfg->orig_method->klass->valuetype && !(acfg->aot_opts.llvm_only && cfg->compile_llvm)) {
8499 #ifdef MONO_ARCH_AOT_SUPPORTED
8502 index = get_method_index (acfg, method);
8503 sprintf (symbol, "ut_%d", index);
8505 arch_emit_direct_call (acfg, symbol, FALSE, acfg->thumb_mixed && cfg->compile_llvm, NULL, &call_size);
8509 emit_int32 (acfg, 0);
8513 emit_info (MonoAotCompile *acfg)
8518 offsets = g_new0 (gint32, acfg->nmethods);
8520 for (oindex = 0; oindex < acfg->method_order->len; ++oindex) {
8521 i = GPOINTER_TO_UINT (g_ptr_array_index (acfg->method_order, oindex));
8523 if (acfg->cfgs [i]) {
8524 emit_method_info (acfg, acfg->cfgs [i]);
8525 offsets [i] = acfg->cfgs [i]->method_info_offset;
8531 acfg->stats.offsets_size += emit_offset_table (acfg, "method_info_offsets", MONO_AOT_TABLE_METHOD_INFO_OFFSETS, acfg->nmethods, 10, offsets);
8536 #endif /* #if !defined(DISABLE_AOT) && !defined(DISABLE_JIT) */
8538 #define rot(x,k) (((x)<<(k)) | ((x)>>(32-(k))))
8539 #define mix(a,b,c) { \
8540 a -= c; a ^= rot(c, 4); c += b; \
8541 b -= a; b ^= rot(a, 6); a += c; \
8542 c -= b; c ^= rot(b, 8); b += a; \
8543 a -= c; a ^= rot(c,16); c += b; \
8544 b -= a; b ^= rot(a,19); a += c; \
8545 c -= b; c ^= rot(b, 4); b += a; \
8547 #define final(a,b,c) { \
8548 c ^= b; c -= rot(b,14); \
8549 a ^= c; a -= rot(c,11); \
8550 b ^= a; b -= rot(a,25); \
8551 c ^= b; c -= rot(b,16); \
8552 a ^= c; a -= rot(c,4); \
8553 b ^= a; b -= rot(a,14); \
8554 c ^= b; c -= rot(b,24); \
8558 mono_aot_type_hash (MonoType *t1)
8560 guint hash = t1->type;
8562 hash |= t1->byref << 6; /* do not collide with t1->type values */
8564 case MONO_TYPE_VALUETYPE:
8565 case MONO_TYPE_CLASS:
8566 case MONO_TYPE_SZARRAY:
8567 /* check if the distribution is good enough */
8568 return ((hash << 5) - hash) ^ mono_metadata_str_hash (t1->data.klass->name);
8570 return ((hash << 5) - hash) ^ mono_metadata_type_hash (t1->data.type);
8571 case MONO_TYPE_ARRAY:
8572 return ((hash << 5) - hash) ^ mono_metadata_type_hash (&t1->data.array->eklass->byval_arg);
8573 case MONO_TYPE_GENERICINST:
8574 return ((hash << 5) - hash) ^ 0;
8581 * mono_aot_method_hash:
8583 * Return a hash code for methods which only depends on metadata.
8586 mono_aot_method_hash (MonoMethod *method)
8588 MonoMethodSignature *sig;
8592 guint32 *hashes_start, *hashes;
8594 MonoGenericInst *class_ginst = NULL;
8595 MonoGenericInst *ginst = NULL;
8597 /* Similar to the hash in mono_method_get_imt_slot () */
8599 sig = mono_method_signature (method);
8601 if (method->klass->generic_class)
8602 class_ginst = method->klass->generic_class->context.class_inst;
8603 if (method->is_inflated)
8604 ginst = ((MonoMethodInflated*)method)->context.method_inst;
8606 hashes_count = sig->param_count + 5 + (class_ginst ? class_ginst->type_argc : 0) + (ginst ? ginst->type_argc : 0);
8607 hashes_start = (guint32 *)g_malloc0 (hashes_count * sizeof (guint32));
8608 hashes = hashes_start;
8610 /* Some wrappers are assigned to random classes */
8611 if (!method->wrapper_type || method->wrapper_type == MONO_WRAPPER_REMOTING_INVOKE_WITH_CHECK)
8612 klass = method->klass;
8614 klass = mono_defaults.object_class;
8616 if (!method->wrapper_type) {
8619 if (klass->generic_class)
8620 full_name = mono_type_full_name (&klass->generic_class->container_class->byval_arg);
8622 full_name = mono_type_full_name (&klass->byval_arg);
8624 hashes [0] = mono_metadata_str_hash (full_name);
8628 hashes [0] = mono_metadata_str_hash (klass->name);
8629 hashes [1] = mono_metadata_str_hash (klass->name_space);
8631 if (method->wrapper_type == MONO_WRAPPER_STFLD || method->wrapper_type == MONO_WRAPPER_LDFLD || method->wrapper_type == MONO_WRAPPER_LDFLDA)
8632 /* The method name includes a stringified pointer */
8635 hashes [2] = mono_metadata_str_hash (method->name);
8636 hashes [3] = method->wrapper_type;
8637 hashes [4] = mono_aot_type_hash (sig->ret);
8639 for (i = 0; i < sig->param_count; i++) {
8640 hashes [hindex ++] = mono_aot_type_hash (sig->params [i]);
8643 for (i = 0; i < class_ginst->type_argc; ++i)
8644 hashes [hindex ++] = mono_aot_type_hash (class_ginst->type_argv [i]);
8647 for (i = 0; i < ginst->type_argc; ++i)
8648 hashes [hindex ++] = mono_aot_type_hash (ginst->type_argv [i]);
8650 g_assert (hindex == hashes_count);
8652 /* Setup internal state */
8653 a = b = c = 0xdeadbeef + (((guint32)hashes_count)<<2);
8655 /* Handle most of the hashes */
8656 while (hashes_count > 3) {
8665 /* Handle the last 3 hashes (all the case statements fall through) */
8666 switch (hashes_count) {
8667 case 3 : c += hashes [2];
8668 case 2 : b += hashes [1];
8669 case 1 : a += hashes [0];
8671 case 0: /* nothing left to add */
8675 free (hashes_start);
8684 * mono_aot_get_array_helper_from_wrapper;
8686 * Get the helper method in Array called by an array wrapper method.
8689 mono_aot_get_array_helper_from_wrapper (MonoMethod *method)
8693 MonoGenericContext ctx;
8694 MonoType *args [16];
8695 char *mname, *iname, *s, *s2, *helper_name = NULL;
8697 prefix = "System.Collections.Generic";
8698 s = g_strdup_printf ("%s", method->name + strlen (prefix) + 1);
8699 s2 = strstr (s, "`1.");
8705 //printf ("X: %s %s\n", iname, mname);
8707 if (!strcmp (iname, "IList"))
8708 helper_name = g_strdup_printf ("InternalArray__%s", mname);
8710 helper_name = g_strdup_printf ("InternalArray__%s_%s", iname, mname);
8711 m = mono_class_get_method_from_name (mono_defaults.array_class, helper_name, mono_method_signature (method)->param_count);
8713 g_free (helper_name);
8716 if (m->is_generic) {
8718 memset (&ctx, 0, sizeof (ctx));
8719 args [0] = &method->klass->element_class->byval_arg;
8720 ctx.method_inst = mono_metadata_get_generic_inst (1, args);
8721 m = mono_class_inflate_generic_method_checked (m, &ctx, &error);
8722 g_assert (mono_error_ok (&error)); /* FIXME don't swallow the error */
8728 #if !defined(DISABLE_AOT) && !defined(DISABLE_JIT)
8730 typedef struct HashEntry {
8731 guint32 key, value, index;
8732 struct HashEntry *next;
8736 * emit_extra_methods:
8738 * Emit methods which are not in the METHOD table, like wrappers.
8741 emit_extra_methods (MonoAotCompile *acfg)
8743 int i, table_size, buf_size;
8745 guint32 *info_offsets;
8748 HashEntry *entry, *new_entry;
8749 int nmethods, max_chain_length;
8752 info_offsets = g_new0 (guint32, acfg->extra_methods->len);
8754 /* Emit method info */
8756 for (i = 0; i < acfg->extra_methods->len; ++i) {
8757 MonoMethod *method = (MonoMethod *)g_ptr_array_index (acfg->extra_methods, i);
8758 MonoCompile *cfg = (MonoCompile *)g_hash_table_lookup (acfg->method_to_cfg, method);
8764 p = buf = (guint8 *)g_malloc (buf_size);
8768 method = cfg->method_to_register;
8770 encode_method_ref (acfg, method, p, &p);
8772 g_assert ((p - buf) < buf_size);
8774 info_offsets [i] = add_to_blob (acfg, buf, p - buf);
8779 * Construct a chained hash table for mapping indexes in extra_method_info to
8782 table_size = g_spaced_primes_closest ((int)(nmethods * 1.5));
8783 table = g_ptr_array_sized_new (table_size);
8784 for (i = 0; i < table_size; ++i)
8785 g_ptr_array_add (table, NULL);
8786 chain_lengths = g_new0 (int, table_size);
8787 max_chain_length = 0;
8788 for (i = 0; i < acfg->extra_methods->len; ++i) {
8789 MonoMethod *method = (MonoMethod *)g_ptr_array_index (acfg->extra_methods, i);
8790 MonoCompile *cfg = (MonoCompile *)g_hash_table_lookup (acfg->method_to_cfg, method);
8796 key = info_offsets [i];
8797 value = get_method_index (acfg, method);
8799 hash = mono_aot_method_hash (method) % table_size;
8800 //printf ("X: %s %x\n", mono_method_get_full_name (method), mono_aot_method_hash (method));
8802 chain_lengths [hash] ++;
8803 max_chain_length = MAX (max_chain_length, chain_lengths [hash]);
8805 new_entry = (HashEntry *)mono_mempool_alloc0 (acfg->mempool, sizeof (HashEntry));
8806 new_entry->key = key;
8807 new_entry->value = value;
8809 entry = (HashEntry *)g_ptr_array_index (table, hash);
8810 if (entry == NULL) {
8811 new_entry->index = hash;
8812 g_ptr_array_index (table, hash) = new_entry;
8815 entry = entry->next;
8817 entry->next = new_entry;
8818 new_entry->index = table->len;
8819 g_ptr_array_add (table, new_entry);
8823 //printf ("MAX: %d\n", max_chain_length);
8825 buf_size = table->len * 12 + 4;
8826 p = buf = (guint8 *)g_malloc (buf_size);
8827 encode_int (table_size, p, &p);
8829 for (i = 0; i < table->len; ++i) {
8830 HashEntry *entry = (HashEntry *)g_ptr_array_index (table, i);
8832 if (entry == NULL) {
8833 encode_int (0, p, &p);
8834 encode_int (0, p, &p);
8835 encode_int (0, p, &p);
8837 //g_assert (entry->key > 0);
8838 encode_int (entry->key, p, &p);
8839 encode_int (entry->value, p, &p);
8841 encode_int (entry->next->index, p, &p);
8843 encode_int (0, p, &p);
8846 g_assert (p - buf <= buf_size);
8848 /* Emit the table */
8849 emit_aot_data (acfg, MONO_AOT_TABLE_EXTRA_METHOD_TABLE, "extra_method_table", buf, p - buf);
8852 * Emit a table reverse mapping method indexes to their index in extra_method_info.
8853 * This is used by mono_aot_find_jit_info ().
8855 buf_size = acfg->extra_methods->len * 8 + 4;
8856 p = buf = (guint8 *)g_malloc (buf_size);
8857 encode_int (acfg->extra_methods->len, p, &p);
8858 for (i = 0; i < acfg->extra_methods->len; ++i) {
8859 MonoMethod *method = (MonoMethod *)g_ptr_array_index (acfg->extra_methods, i);
8861 encode_int (get_method_index (acfg, method), p, &p);
8862 encode_int (info_offsets [i], p, &p);
8864 emit_aot_data (acfg, MONO_AOT_TABLE_EXTRA_METHOD_INFO_OFFSETS, "extra_method_info_offsets", buf, p - buf);
8868 emit_exception_info (MonoAotCompile *acfg)
8872 SeqPointData sp_data;
8873 gboolean seq_points_to_file = FALSE;
8875 offsets = g_new0 (gint32, acfg->nmethods);
8876 for (i = 0; i < acfg->nmethods; ++i) {
8877 if (acfg->cfgs [i]) {
8878 MonoCompile *cfg = acfg->cfgs [i];
8880 // By design aot-runtime decode_exception_debug_info is not able to load sequence point debug data from a file.
8881 // As it is not possible to load debug data from a file its is also not possible to store it in a file.
8882 gboolean method_seq_points_to_file = acfg->aot_opts.gen_seq_points_file &&
8883 cfg->gen_seq_points && !cfg->gen_sdb_seq_points;
8884 gboolean method_seq_points_to_binary = cfg->gen_seq_points && !method_seq_points_to_file;
8886 emit_exception_debug_info (acfg, cfg, method_seq_points_to_binary);
8887 offsets [i] = cfg->ex_info_offset;
8889 if (method_seq_points_to_file) {
8890 if (!seq_points_to_file) {
8891 mono_seq_point_data_init (&sp_data, acfg->nmethods);
8892 seq_points_to_file = TRUE;
8894 mono_seq_point_data_add (&sp_data, cfg->method->token, cfg->method_index, cfg->seq_point_info);
8901 if (seq_points_to_file) {
8902 char *seq_points_aot_file = acfg->aot_opts.gen_seq_points_file_path ? acfg->aot_opts.gen_seq_points_file_path
8903 : g_strdup_printf("%s%s", acfg->image->name, SEQ_POINT_AOT_EXT);
8904 mono_seq_point_data_write (&sp_data, seq_points_aot_file);
8905 mono_seq_point_data_free (&sp_data);
8906 g_free (seq_points_aot_file);
8909 acfg->stats.offsets_size += emit_offset_table (acfg, "ex_info_offsets", MONO_AOT_TABLE_EX_INFO_OFFSETS, acfg->nmethods, 10, offsets);
8914 emit_unwind_info (MonoAotCompile *acfg)
8919 if (acfg->aot_opts.llvm_only) {
8920 g_assert (acfg->unwind_ops->len == 0);
8925 * The unwind info contains a lot of duplicates so we emit each unique
8926 * entry once, and only store the offset from the start of the table in the
8930 sprintf (symbol, "unwind_info");
8931 emit_section_change (acfg, RODATA_SECT, 1);
8932 emit_alignment (acfg, 8);
8933 emit_info_symbol (acfg, symbol);
8935 for (i = 0; i < acfg->unwind_ops->len; ++i) {
8936 guint32 index = GPOINTER_TO_UINT (g_ptr_array_index (acfg->unwind_ops, i));
8937 guint8 *unwind_info;
8938 guint32 unwind_info_len;
8942 unwind_info = mono_get_cached_unwind_info (index, &unwind_info_len);
8945 encode_value (unwind_info_len, p, &p);
8946 emit_bytes (acfg, buf, p - buf);
8947 emit_bytes (acfg, unwind_info, unwind_info_len);
8949 acfg->stats.unwind_info_size += (p - buf) + unwind_info_len;
8954 emit_class_info (MonoAotCompile *acfg)
8959 offsets = g_new0 (gint32, acfg->image->tables [MONO_TABLE_TYPEDEF].rows);
8960 for (i = 0; i < acfg->image->tables [MONO_TABLE_TYPEDEF].rows; ++i)
8961 offsets [i] = emit_klass_info (acfg, MONO_TOKEN_TYPE_DEF | (i + 1));
8963 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);
8967 typedef struct ClassNameTableEntry {
8968 guint32 token, index;
8969 struct ClassNameTableEntry *next;
8970 } ClassNameTableEntry;
8973 emit_class_name_table (MonoAotCompile *acfg)
8975 int i, table_size, buf_size;
8976 guint32 token, hash;
8981 ClassNameTableEntry *entry, *new_entry;
8984 * Construct a chained hash table for mapping class names to typedef tokens.
8986 table_size = g_spaced_primes_closest ((int)(acfg->image->tables [MONO_TABLE_TYPEDEF].rows * 1.5));
8987 table = g_ptr_array_sized_new (table_size);
8988 for (i = 0; i < table_size; ++i)
8989 g_ptr_array_add (table, NULL);
8990 for (i = 0; i < acfg->image->tables [MONO_TABLE_TYPEDEF].rows; ++i) {
8992 token = MONO_TOKEN_TYPE_DEF | (i + 1);
8993 klass = mono_class_get_checked (acfg->image, token, &error);
8995 mono_error_cleanup (&error);
8998 full_name = mono_type_get_name_full (mono_class_get_type (klass), MONO_TYPE_NAME_FORMAT_FULL_NAME);
8999 hash = mono_metadata_str_hash (full_name) % table_size;
9002 /* FIXME: Allocate from the mempool */
9003 new_entry = g_new0 (ClassNameTableEntry, 1);
9004 new_entry->token = token;
9006 entry = (ClassNameTableEntry *)g_ptr_array_index (table, hash);
9007 if (entry == NULL) {
9008 new_entry->index = hash;
9009 g_ptr_array_index (table, hash) = new_entry;
9012 entry = entry->next;
9014 entry->next = new_entry;
9015 new_entry->index = table->len;
9016 g_ptr_array_add (table, new_entry);
9020 /* Emit the table */
9021 buf_size = table->len * 4 + 4;
9022 p = buf = (guint8 *)g_malloc0 (buf_size);
9024 /* FIXME: Optimize memory usage */
9025 g_assert (table_size < 65000);
9026 encode_int16 (table_size, p, &p);
9027 g_assert (table->len < 65000);
9028 for (i = 0; i < table->len; ++i) {
9029 ClassNameTableEntry *entry = (ClassNameTableEntry *)g_ptr_array_index (table, i);
9031 if (entry == NULL) {
9032 encode_int16 (0, p, &p);
9033 encode_int16 (0, p, &p);
9035 encode_int16 (mono_metadata_token_index (entry->token), p, &p);
9037 encode_int16 (entry->next->index, p, &p);
9039 encode_int16 (0, p, &p);
9042 g_assert (p - buf <= buf_size);
9044 emit_aot_data (acfg, MONO_AOT_TABLE_CLASS_NAME, "class_name_table", buf, p - buf);
9048 emit_image_table (MonoAotCompile *acfg)
9054 * The image table is small but referenced in a lot of places.
9055 * So we emit it at once, and reference its elements by an index.
9057 buf_size = acfg->image_table->len * 28 + 4;
9058 for (i = 0; i < acfg->image_table->len; i++) {
9059 MonoImage *image = (MonoImage*)g_ptr_array_index (acfg->image_table, i);
9060 MonoAssemblyName *aname = &image->assembly->aname;
9062 buf_size += strlen (image->assembly_name) + strlen (image->guid) + (aname->culture ? strlen (aname->culture) : 1) + strlen ((char*)aname->public_key_token) + 4;
9065 buf = p = (guint8 *)g_malloc0 (buf_size);
9066 encode_int (acfg->image_table->len, p, &p);
9067 for (i = 0; i < acfg->image_table->len; i++) {
9068 MonoImage *image = (MonoImage*)g_ptr_array_index (acfg->image_table, i);
9069 MonoAssemblyName *aname = &image->assembly->aname;
9071 /* FIXME: Support multi-module assemblies */
9072 g_assert (image->assembly->image == image);
9074 encode_string (image->assembly_name, p, &p);
9075 encode_string (image->guid, p, &p);
9076 encode_string (aname->culture ? aname->culture : "", p, &p);
9077 encode_string ((const char*)aname->public_key_token, p, &p);
9079 while (GPOINTER_TO_UINT (p) % 8 != 0)
9082 encode_int (aname->flags, p, &p);
9083 encode_int (aname->major, p, &p);
9084 encode_int (aname->minor, p, &p);
9085 encode_int (aname->build, p, &p);
9086 encode_int (aname->revision, p, &p);
9088 g_assert (p - buf <= buf_size);
9090 emit_aot_data (acfg, MONO_AOT_TABLE_IMAGE_TABLE, "image_table", buf, p - buf);
9096 emit_got_info (MonoAotCompile *acfg, gboolean llvm)
9098 int i, first_plt_got_patch = 0, buf_size;
9100 guint32 *got_info_offsets;
9101 GotInfo *info = llvm ? &acfg->llvm_got_info : &acfg->got_info;
9103 /* Add the patches needed by the PLT to the GOT */
9105 acfg->plt_got_offset_base = acfg->got_offset;
9106 first_plt_got_patch = info->got_patches->len;
9107 for (i = 1; i < acfg->plt_offset; ++i) {
9108 MonoPltEntry *plt_entry = (MonoPltEntry *)g_hash_table_lookup (acfg->plt_offset_to_entry, GUINT_TO_POINTER (i));
9110 g_ptr_array_add (info->got_patches, plt_entry->ji);
9112 acfg->stats.got_slot_types [plt_entry->ji->type] ++;
9115 acfg->got_offset += acfg->plt_offset;
9120 * - optimize offsets table.
9121 * - reduce number of exported symbols.
9122 * - emit info for a klass only once.
9123 * - determine when a method uses a GOT slot which is guaranteed to be already
9125 * - clean up and document the code.
9126 * - use String.Empty in class libs.
9129 /* Encode info required to decode shared GOT entries */
9130 buf_size = info->got_patches->len * 128;
9131 p = buf = (guint8 *)mono_mempool_alloc (acfg->mempool, buf_size);
9132 got_info_offsets = (guint32 *)mono_mempool_alloc (acfg->mempool, info->got_patches->len * sizeof (guint32));
9134 acfg->plt_got_info_offsets = (guint32 *)mono_mempool_alloc (acfg->mempool, acfg->plt_offset * sizeof (guint32));
9136 if (acfg->plt_offset)
9137 acfg->plt_got_info_offsets [0] = 0;
9139 for (i = 0; i < info->got_patches->len; ++i) {
9140 MonoJumpInfo *ji = (MonoJumpInfo *)g_ptr_array_index (info->got_patches, i);
9145 encode_value (ji->type, p, &p);
9147 encode_patch (acfg, ji, p, &p);
9148 acfg->stats.got_slot_info_sizes [ji->type] += p - p2;
9149 g_assert (p - buf <= buf_size);
9150 got_info_offsets [i] = add_to_blob (acfg, buf, p - buf);
9152 if (!llvm && i >= first_plt_got_patch)
9153 acfg->plt_got_info_offsets [i - first_plt_got_patch + 1] = got_info_offsets [i];
9154 acfg->stats.got_info_size += p - buf;
9157 /* Emit got_info_offsets table */
9159 /* No need to emit offsets for the got plt entries, the plt embeds them directly */
9160 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);
9164 emit_got (MonoAotCompile *acfg)
9166 char symbol [MAX_SYMBOL_SIZE];
9168 if (acfg->aot_opts.llvm_only)
9171 /* Don't make GOT global so accesses to it don't need relocations */
9172 sprintf (symbol, "%s", acfg->got_symbol);
9175 emit_unset_mode (acfg);
9176 fprintf (acfg->fp, ".section __DATA, __bss\n");
9177 emit_alignment (acfg, 8);
9179 emit_info_symbol (acfg, "jit_got");
9180 fprintf (acfg->fp, ".lcomm %s, %d\n", acfg->got_symbol, (int)(acfg->got_offset * sizeof (gpointer)));
9182 emit_section_change (acfg, ".bss", 0);
9183 emit_alignment (acfg, 8);
9184 emit_local_symbol (acfg, symbol, "got_end", FALSE);
9185 emit_label (acfg, symbol);
9187 emit_info_symbol (acfg, "jit_got");
9188 if (acfg->got_offset > 0)
9189 emit_zero_bytes (acfg, (int)(acfg->got_offset * sizeof (gpointer)));
9192 sprintf (symbol, "got_end");
9193 emit_label (acfg, symbol);
9196 typedef struct GlobalsTableEntry {
9197 guint32 value, index;
9198 struct GlobalsTableEntry *next;
9199 } GlobalsTableEntry;
9202 emit_globals (MonoAotCompile *acfg)
9208 GlobalsTableEntry *entry, *new_entry;
9210 if (!acfg->aot_opts.static_link)
9212 if (acfg->aot_opts.llvm_only) {
9213 g_assert (acfg->globals->len == 0);
9218 * When static linking, we emit a table containing our globals.
9222 * Construct a chained hash table for mapping global names to their index in
9223 * the globals table.
9225 table_size = g_spaced_primes_closest ((int)(acfg->globals->len * 1.5));
9226 table = g_ptr_array_sized_new (table_size);
9227 for (i = 0; i < table_size; ++i)
9228 g_ptr_array_add (table, NULL);
9229 for (i = 0; i < acfg->globals->len; ++i) {
9230 char *name = (char *)g_ptr_array_index (acfg->globals, i);
9232 hash = mono_metadata_str_hash (name) % table_size;
9234 /* FIXME: Allocate from the mempool */
9235 new_entry = g_new0 (GlobalsTableEntry, 1);
9236 new_entry->value = i;
9238 entry = (GlobalsTableEntry *)g_ptr_array_index (table, hash);
9239 if (entry == NULL) {
9240 new_entry->index = hash;
9241 g_ptr_array_index (table, hash) = new_entry;
9244 entry = entry->next;
9246 entry->next = new_entry;
9247 new_entry->index = table->len;
9248 g_ptr_array_add (table, new_entry);
9252 /* Emit the table */
9253 sprintf (symbol, ".Lglobals_hash");
9254 emit_section_change (acfg, RODATA_SECT, 0);
9255 emit_alignment (acfg, 8);
9256 emit_label (acfg, symbol);
9258 /* FIXME: Optimize memory usage */
9259 g_assert (table_size < 65000);
9260 emit_int16 (acfg, table_size);
9261 for (i = 0; i < table->len; ++i) {
9262 GlobalsTableEntry *entry = (GlobalsTableEntry *)g_ptr_array_index (table, i);
9264 if (entry == NULL) {
9265 emit_int16 (acfg, 0);
9266 emit_int16 (acfg, 0);
9268 emit_int16 (acfg, entry->value + 1);
9270 emit_int16 (acfg, entry->next->index);
9272 emit_int16 (acfg, 0);
9276 /* Emit the names */
9277 for (i = 0; i < acfg->globals->len; ++i) {
9278 char *name = (char *)g_ptr_array_index (acfg->globals, i);
9280 sprintf (symbol, "name_%d", i);
9281 emit_section_change (acfg, RODATA_SECT, 1);
9283 emit_alignment (acfg, 4);
9285 emit_label (acfg, symbol);
9286 emit_string (acfg, name);
9289 /* Emit the globals table */
9290 sprintf (symbol, "globals");
9291 emit_section_change (acfg, ".data", 0);
9292 /* This is not a global, since it is accessed by the init function */
9293 emit_alignment (acfg, 8);
9294 emit_info_symbol (acfg, symbol);
9296 sprintf (symbol, "%sglobals_hash", acfg->temp_prefix);
9297 emit_pointer (acfg, symbol);
9299 for (i = 0; i < acfg->globals->len; ++i) {
9300 char *name = (char *)g_ptr_array_index (acfg->globals, i);
9302 sprintf (symbol, "name_%d", i);
9303 emit_pointer (acfg, symbol);
9305 g_assert (strlen (name) < sizeof (symbol));
9306 sprintf (symbol, "%s", name);
9307 emit_pointer (acfg, symbol);
9309 /* Null terminate the table */
9310 emit_int32 (acfg, 0);
9311 emit_int32 (acfg, 0);
9315 emit_mem_end (MonoAotCompile *acfg)
9319 if (acfg->aot_opts.llvm_only)
9322 sprintf (symbol, "mem_end");
9323 emit_section_change (acfg, ".text", 1);
9324 emit_alignment_code (acfg, 8);
9325 emit_label (acfg, symbol);
9329 init_aot_file_info (MonoAotCompile *acfg, MonoAotFileInfo *info)
9333 info->version = MONO_AOT_FILE_VERSION;
9334 info->plt_got_offset_base = acfg->plt_got_offset_base;
9335 info->got_size = acfg->got_offset * sizeof (gpointer);
9336 info->plt_size = acfg->plt_offset;
9337 info->nmethods = acfg->nmethods;
9338 info->flags = acfg->flags;
9339 info->opts = acfg->opts;
9340 info->simd_opts = acfg->simd_opts;
9341 info->gc_name_index = acfg->gc_name_offset;
9342 info->datafile_size = acfg->datafile_offset;
9343 for (i = 0; i < MONO_AOT_TABLE_NUM; ++i)
9344 info->table_offsets [i] = acfg->table_offsets [i];
9345 for (i = 0; i < MONO_AOT_TRAMP_NUM; ++i)
9346 info->num_trampolines [i] = acfg->num_trampolines [i];
9347 for (i = 0; i < MONO_AOT_TRAMP_NUM; ++i)
9348 info->trampoline_got_offset_base [i] = acfg->trampoline_got_offset_base [i];
9349 for (i = 0; i < MONO_AOT_TRAMP_NUM; ++i)
9350 info->trampoline_size [i] = acfg->trampoline_size [i];
9351 info->num_rgctx_fetch_trampolines = acfg->aot_opts.nrgctx_fetch_trampolines;
9353 info->double_align = MONO_ABI_ALIGNOF (double);
9354 info->long_align = MONO_ABI_ALIGNOF (gint64);
9355 info->generic_tramp_num = MONO_TRAMPOLINE_NUM;
9356 info->tramp_page_size = acfg->tramp_page_size;
9357 info->nshared_got_entries = acfg->nshared_got_entries;
9358 for (i = 0; i < MONO_AOT_TRAMP_NUM; ++i)
9359 info->tramp_page_code_offsets [i] = acfg->tramp_page_code_offsets [i];
9363 emit_aot_file_info (MonoAotCompile *acfg, MonoAotFileInfo *info)
9365 char symbol [MAX_SYMBOL_SIZE];
9367 const char **symbols;
9369 symbols = g_new0 (const char *, MONO_AOT_FILE_INFO_NUM_SYMBOLS);
9371 symbols [sindex ++] = acfg->got_symbol;
9373 symbols [sindex ++] = g_strdup_printf ("%s%s", acfg->user_symbol_prefix, acfg->llvm_got_symbol);
9374 symbols [sindex ++] = acfg->llvm_eh_frame_symbol;
9376 symbols [sindex ++] = NULL;
9377 symbols [sindex ++] = NULL;
9379 /* llvm_get_method */
9380 symbols [sindex ++] = NULL;
9381 /* llvm_get_unbox_tramp */
9382 symbols [sindex ++] = NULL;
9383 if (!acfg->aot_opts.llvm_only) {
9384 symbols [sindex ++] = "jit_code_start";
9385 symbols [sindex ++] = "jit_code_end";
9386 symbols [sindex ++] = "method_addresses";
9388 symbols [sindex ++] = NULL;
9389 symbols [sindex ++] = NULL;
9390 symbols [sindex ++] = NULL;
9392 if (acfg->data_outfile) {
9393 for (i = 0; i < MONO_AOT_TABLE_NUM; ++i)
9394 symbols [sindex ++] = NULL;
9396 symbols [sindex ++] = "blob";
9397 symbols [sindex ++] = "class_name_table";
9398 symbols [sindex ++] = "class_info_offsets";
9399 symbols [sindex ++] = "method_info_offsets";
9400 symbols [sindex ++] = "ex_info_offsets";
9401 symbols [sindex ++] = "extra_method_info_offsets";
9402 symbols [sindex ++] = "extra_method_table";
9403 symbols [sindex ++] = "got_info_offsets";
9405 symbols [sindex ++] = "llvm_got_info_offsets";
9407 symbols [sindex ++] = NULL;
9408 symbols [sindex ++] = "image_table";
9410 symbols [sindex ++] = "mem_end";
9411 symbols [sindex ++] = "assembly_guid";
9412 symbols [sindex ++] = "runtime_version";
9413 if (acfg->num_trampoline_got_entries) {
9414 symbols [sindex ++] = "specific_trampolines";
9415 symbols [sindex ++] = "static_rgctx_trampolines";
9416 symbols [sindex ++] = "imt_thunks";
9417 symbols [sindex ++] = "gsharedvt_arg_trampolines";
9419 symbols [sindex ++] = NULL;
9420 symbols [sindex ++] = NULL;
9421 symbols [sindex ++] = NULL;
9422 symbols [sindex ++] = NULL;
9424 if (acfg->aot_opts.static_link) {
9425 symbols [sindex ++] = "globals";
9427 symbols [sindex ++] = NULL;
9429 symbols [sindex ++] = "assembly_name";
9430 symbols [sindex ++] = "plt";
9431 symbols [sindex ++] = "plt_end";
9432 symbols [sindex ++] = "unwind_info";
9433 if (!acfg->aot_opts.llvm_only) {
9434 symbols [sindex ++] = "unbox_trampolines";
9435 symbols [sindex ++] = "unbox_trampolines_end";
9436 symbols [sindex ++] = "unbox_trampoline_addresses";
9438 symbols [sindex ++] = NULL;
9439 symbols [sindex ++] = NULL;
9440 symbols [sindex ++] = NULL;
9443 g_assert (sindex == MONO_AOT_FILE_INFO_NUM_SYMBOLS);
9445 sprintf (symbol, "%smono_aot_file_info", acfg->user_symbol_prefix);
9446 emit_section_change (acfg, ".data", 0);
9447 emit_alignment (acfg, 8);
9448 emit_label (acfg, symbol);
9449 if (!acfg->aot_opts.static_link)
9450 emit_global (acfg, symbol, FALSE);
9452 /* The data emitted here must match MonoAotFileInfo. */
9454 emit_int32 (acfg, info->version);
9455 emit_int32 (acfg, info->dummy);
9458 * We emit pointers to our data structures instead of emitting global symbols which
9459 * point to them, to reduce the number of globals, and because using globals leads to
9460 * various problems (i.e. arm/thumb).
9462 for (i = 0; i < MONO_AOT_FILE_INFO_NUM_SYMBOLS; ++i)
9463 emit_pointer (acfg, symbols [i]);
9465 emit_int32 (acfg, info->plt_got_offset_base);
9466 emit_int32 (acfg, info->got_size);
9467 emit_int32 (acfg, info->plt_size);
9468 emit_int32 (acfg, info->nmethods);
9469 emit_int32 (acfg, info->flags);
9470 emit_int32 (acfg, info->opts);
9471 emit_int32 (acfg, info->simd_opts);
9472 emit_int32 (acfg, info->gc_name_index);
9473 emit_int32 (acfg, info->num_rgctx_fetch_trampolines);
9474 emit_int32 (acfg, info->double_align);
9475 emit_int32 (acfg, info->long_align);
9476 emit_int32 (acfg, info->generic_tramp_num);
9477 emit_int32 (acfg, info->tramp_page_size);
9478 emit_int32 (acfg, info->nshared_got_entries);
9479 emit_int32 (acfg, info->datafile_size);
9481 for (i = 0; i < MONO_AOT_TABLE_NUM; ++i)
9482 emit_int32 (acfg, info->table_offsets [i]);
9483 for (i = 0; i < MONO_AOT_TRAMP_NUM; ++i)
9484 emit_int32 (acfg, info->num_trampolines [i]);
9485 for (i = 0; i < MONO_AOT_TRAMP_NUM; ++i)
9486 emit_int32 (acfg, info->trampoline_got_offset_base [i]);
9487 for (i = 0; i < MONO_AOT_TRAMP_NUM; ++i)
9488 emit_int32 (acfg, info->trampoline_size [i]);
9489 for (i = 0; i < MONO_AOT_TRAMP_NUM; ++i)
9490 emit_int32 (acfg, info->tramp_page_code_offsets [i]);
9492 if (acfg->aot_opts.static_link) {
9493 emit_global_inner (acfg, acfg->static_linking_symbol, FALSE);
9494 emit_alignment (acfg, sizeof (gpointer));
9495 emit_label (acfg, acfg->static_linking_symbol);
9496 emit_pointer_2 (acfg, acfg->user_symbol_prefix, "mono_aot_file_info");
9501 * Emit a structure containing all the information not stored elsewhere.
9504 emit_file_info (MonoAotCompile *acfg)
9507 MonoAotFileInfo *info;
9509 if (acfg->aot_opts.bind_to_runtime_version) {
9510 build_info = mono_get_runtime_build_info ();
9511 emit_string_symbol (acfg, "runtime_version", build_info);
9512 g_free (build_info);
9514 emit_string_symbol (acfg, "runtime_version", "");
9517 emit_string_symbol (acfg, "assembly_guid" , acfg->image->guid);
9519 /* Emit a string holding the assembly name */
9520 emit_string_symbol (acfg, "assembly_name", acfg->image->assembly->aname.name);
9522 info = g_new0 (MonoAotFileInfo, 1);
9523 init_aot_file_info (acfg, info);
9525 if (acfg->aot_opts.static_link) {
9526 char symbol [MAX_SYMBOL_SIZE];
9530 * Emit a global symbol which can be passed by an embedding app to
9531 * mono_aot_register_module (). The symbol points to a pointer to the the file info
9534 sprintf (symbol, "%smono_aot_module_%s_info", acfg->user_symbol_prefix, acfg->image->assembly->aname.name);
9536 /* Get rid of characters which cannot occur in symbols */
9538 for (p = symbol; *p; ++p) {
9539 if (!(isalnum (*p) || *p == '_'))
9542 acfg->static_linking_symbol = g_strdup (symbol);
9546 mono_llvm_emit_aot_file_info (info, acfg->has_jitted_code);
9548 emit_aot_file_info (acfg, info);
9552 emit_blob (MonoAotCompile *acfg)
9554 acfg->blob_closed = TRUE;
9556 emit_aot_data (acfg, MONO_AOT_TABLE_BLOB, "blob", (guint8*)acfg->blob.data, acfg->blob.index);
9560 emit_objc_selectors (MonoAotCompile *acfg)
9565 if (!acfg->objc_selectors || acfg->objc_selectors->len == 0)
9570 * cat > foo.m << EOF
9573 * return @selector(print:);
9578 mono_img_writer_emit_unset_mode (acfg->w);
9579 g_assert (acfg->fp);
9580 fprintf (acfg->fp, ".section __DATA,__objc_selrefs,literal_pointers,no_dead_strip\n");
9581 fprintf (acfg->fp, ".align 3\n");
9582 for (i = 0; i < acfg->objc_selectors->len; ++i) {
9583 sprintf (symbol, "L_OBJC_SELECTOR_REFERENCES_%d", i);
9584 emit_label (acfg, symbol);
9585 sprintf (symbol, "L_OBJC_METH_VAR_NAME_%d", i);
9586 emit_pointer (acfg, symbol);
9589 fprintf (acfg->fp, ".section __TEXT,__cstring,cstring_literals\n");
9590 for (i = 0; i < acfg->objc_selectors->len; ++i) {
9591 fprintf (acfg->fp, "L_OBJC_METH_VAR_NAME_%d:\n", i);
9592 fprintf (acfg->fp, ".asciz \"%s\"\n", (char*)g_ptr_array_index (acfg->objc_selectors, i));
9595 fprintf (acfg->fp, ".section __DATA,__objc_imageinfo,regular,no_dead_strip\n");
9596 fprintf (acfg->fp, ".align 3\n");
9597 fprintf (acfg->fp, "L_OBJC_IMAGE_INFO:\n");
9598 fprintf (acfg->fp, ".long 0\n");
9599 fprintf (acfg->fp, ".long 16\n");
9603 emit_dwarf_info (MonoAotCompile *acfg)
9605 #ifdef EMIT_DWARF_INFO
9609 /* DIEs for methods */
9610 for (i = 0; i < acfg->nmethods; ++i) {
9611 MonoCompile *cfg = acfg->cfgs [i];
9616 // FIXME: LLVM doesn't define .Lme_...
9617 if (cfg->compile_llvm)
9620 sprintf (symbol2, "%sme_%x", acfg->temp_prefix, i);
9622 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 ()));
9628 collect_methods (MonoAotCompile *acfg)
9631 MonoImage *image = acfg->image;
9633 /* Collect methods */
9634 for (i = 0; i < image->tables [MONO_TABLE_METHOD].rows; ++i) {
9637 guint32 token = MONO_TOKEN_METHOD_DEF | (i + 1);
9639 method = mono_get_method_checked (acfg->image, token, NULL, NULL, &error);
9642 aot_printerrf (acfg, "Failed to load method 0x%x from '%s' due to %s.\n", token, image->name, mono_error_get_message (&error));
9643 aot_printerrf (acfg, "Run with MONO_LOG_LEVEL=debug for more information.\n");
9644 mono_error_cleanup (&error);
9648 /* Load all methods eagerly to skip the slower lazy loading code */
9649 mono_class_setup_methods (method->klass);
9651 if (mono_aot_mode_is_full (&acfg->aot_opts) && method->iflags & METHOD_IMPL_ATTRIBUTE_INTERNAL_CALL) {
9652 /* Compile the wrapper instead */
9653 /* We do this here instead of add_wrappers () because it is easy to do it here */
9654 MonoMethod *wrapper = mono_marshal_get_native_wrapper (method, TRUE, TRUE);
9658 /* FIXME: Some mscorlib methods don't have debug info */
9660 if (acfg->aot_opts.soft_debug && !method->wrapper_type) {
9661 if (!((method->flags & METHOD_ATTRIBUTE_PINVOKE_IMPL) ||
9662 (method->iflags & METHOD_IMPL_ATTRIBUTE_RUNTIME) ||
9663 (method->flags & METHOD_ATTRIBUTE_ABSTRACT) ||
9664 (method->iflags & METHOD_IMPL_ATTRIBUTE_INTERNAL_CALL))) {
9665 if (!mono_debug_lookup_method (method)) {
9666 fprintf (stderr, "Method %s has no debug info, probably the .mdb file for the assembly is missing.\n", mono_method_get_full_name (method));
9673 if (method->is_generic || method->klass->generic_container)
9674 /* Compile the ref shared version instead */
9675 method = mini_get_shared_method (method);
9677 /* Since we add the normal methods first, their index will be equal to their zero based token index */
9678 add_method_with_index (acfg, method, i, FALSE);
9679 acfg->method_index ++;
9682 /* gsharedvt methods */
9683 for (mindex = 0; mindex < image->tables [MONO_TABLE_METHOD].rows; ++mindex) {
9686 guint32 token = MONO_TOKEN_METHOD_DEF | (mindex + 1);
9688 if (!(acfg->opts & MONO_OPT_GSHAREDVT))
9691 method = mono_get_method_checked (acfg->image, token, NULL, NULL, &error);
9692 report_loader_error (acfg, &error, "Failed to load method token 0x%x due to %s\n", i, mono_error_get_message (&error));
9694 if (method->is_generic || method->klass->generic_container) {
9695 MonoMethod *gshared;
9697 gshared = mini_get_shared_method_full (method, TRUE, TRUE);
9698 add_extra_method (acfg, gshared);
9702 add_generic_instances (acfg);
9704 if (mono_aot_mode_is_full (&acfg->aot_opts))
9705 add_wrappers (acfg);
9710 compile_methods (MonoAotCompile *acfg)
9714 if (acfg->aot_opts.nthreads > 0) {
9719 gpointer *user_data;
9720 MonoMethod **methods;
9723 methods_len = acfg->methods->len;
9725 len = acfg->methods->len / acfg->aot_opts.nthreads;
9728 * Partition the list of methods into fragments, and hand it to threads to
9731 threads = g_ptr_array_new ();
9732 /* Make a copy since acfg->methods is modified by compile_method () */
9733 methods = g_new0 (MonoMethod*, methods_len);
9734 //memcpy (methods, g_ptr_array_index (acfg->methods, 0), sizeof (MonoMethod*) * methods_len);
9735 for (i = 0; i < methods_len; ++i)
9736 methods [i] = (MonoMethod *)g_ptr_array_index (acfg->methods, i);
9738 while (i < methods_len) {
9739 frag = g_ptr_array_new ();
9740 for (j = 0; j < len; ++j) {
9741 if (i < methods_len) {
9742 g_ptr_array_add (frag, methods [i]);
9747 user_data = g_new0 (gpointer, 3);
9748 user_data [0] = mono_domain_get ();
9749 user_data [1] = acfg;
9750 user_data [2] = frag;
9754 tp.creation_flags = 0;
9755 handle = mono_threads_create_thread ((LPTHREAD_START_ROUTINE)compile_thread_main, user_data, &tp, NULL);
9756 g_ptr_array_add (threads, handle);
9760 for (i = 0; i < threads->len; ++i) {
9761 WaitForSingleObjectEx (g_ptr_array_index (threads, i), INFINITE, FALSE);
9767 /* Compile methods added by compile_method () or all methods if nthreads == 0 */
9768 for (i = methods_len; i < acfg->methods->len; ++i) {
9769 /* This can new methods to acfg->methods */
9770 compile_method (acfg, (MonoMethod *)g_ptr_array_index (acfg->methods, i));
9775 compile_asm (MonoAotCompile *acfg)
9777 char *command, *objfile;
9778 char *outfile_name, *tmp_outfile_name, *llvm_ofile;
9779 const char *tool_prefix = acfg->aot_opts.tool_prefix ? acfg->aot_opts.tool_prefix : "";
9780 char *ld_flags = acfg->aot_opts.ld_flags ? acfg->aot_opts.ld_flags : g_strdup("");
9782 #if defined(TARGET_AMD64) && !defined(TARGET_MACH)
9783 #define AS_OPTIONS "--64"
9784 #elif defined(TARGET_POWERPC64)
9785 #define AS_OPTIONS "-a64 -mppc64"
9786 #elif defined(sparc) && SIZEOF_VOID_P == 8
9787 #define AS_OPTIONS "-xarch=v9"
9788 #elif defined(TARGET_X86) && defined(TARGET_MACH) && !defined(__native_client_codegen__)
9789 #define AS_OPTIONS "-arch i386"
9791 #define AS_OPTIONS ""
9794 #ifdef __native_client_codegen__
9795 #if defined(TARGET_AMD64)
9796 #define AS_NAME "nacl64-as"
9798 #define AS_NAME "nacl-as"
9800 #elif defined(TARGET_OSX)
9801 #define AS_NAME "clang"
9803 #define AS_NAME "as"
9807 #define LD_NAME "ld"
9808 #define LD_OPTIONS "-shared -G"
9809 #elif defined(__ppc__) && defined(TARGET_MACH)
9810 #define LD_NAME "gcc"
9811 #define LD_OPTIONS "-dynamiclib"
9812 #elif defined(TARGET_AMD64) && defined(TARGET_MACH)
9813 #define LD_NAME "clang"
9814 #define LD_OPTIONS "--shared"
9815 #elif defined(TARGET_WIN32) && !defined(TARGET_ANDROID)
9816 #define LD_NAME "gcc"
9817 #define LD_OPTIONS "-shared"
9818 #elif defined(TARGET_X86) && defined(TARGET_MACH) && !defined(__native_client_codegen__)
9819 #define LD_NAME "clang"
9820 #define LD_OPTIONS "-m32 -dynamiclib"
9821 #elif defined(TARGET_ARM) && !defined(TARGET_ANDROID)
9822 #define LD_NAME "gcc"
9823 #define LD_OPTIONS "--shared"
9824 #elif defined(TARGET_POWERPC64)
9825 #define LD_OPTIONS "-m elf64ppc"
9829 #define LD_OPTIONS ""
9832 if (acfg->aot_opts.asm_only) {
9833 aot_printf (acfg, "Output file: '%s'.\n", acfg->tmpfname);
9834 if (acfg->aot_opts.static_link)
9835 aot_printf (acfg, "Linking symbol: '%s'.\n", acfg->static_linking_symbol);
9837 aot_printf (acfg, "LLVM output file: '%s'.\n", acfg->llvm_sfile);
9841 if (acfg->aot_opts.static_link) {
9842 if (acfg->aot_opts.outfile)
9843 objfile = g_strdup_printf ("%s", acfg->aot_opts.outfile);
9845 objfile = g_strdup_printf ("%s.o", acfg->image->name);
9847 objfile = g_strdup_printf ("%s.o", acfg->tmpfname);
9851 g_string_append (acfg->as_args, "-c -x assembler");
9854 command = g_strdup_printf ("\"%s%s\" %s %s -o %s %s", tool_prefix, AS_NAME, AS_OPTIONS,
9855 acfg->as_args ? acfg->as_args->str : "",
9856 wrap_path (objfile), wrap_path (acfg->tmpfname));
9857 aot_printf (acfg, "Executing the native assembler: %s\n", command);
9858 if (execute_system (command) != 0) {
9864 if (acfg->llvm && !acfg->llvm_owriter) {
9865 command = g_strdup_printf ("\"%s%s\" %s %s -o %s %s", tool_prefix, AS_NAME, AS_OPTIONS,
9866 acfg->as_args ? acfg->as_args->str : "",
9867 wrap_path (acfg->llvm_ofile), wrap_path (acfg->llvm_sfile));
9868 aot_printf (acfg, "Executing the native assembler: %s\n", command);
9869 if (execute_system (command) != 0) {
9878 if (acfg->aot_opts.static_link) {
9879 aot_printf (acfg, "Output file: '%s'.\n", objfile);
9880 aot_printf (acfg, "Linking symbol: '%s'.\n", acfg->static_linking_symbol);
9885 if (acfg->aot_opts.outfile)
9886 outfile_name = g_strdup_printf ("%s", acfg->aot_opts.outfile);
9888 outfile_name = g_strdup_printf ("%s%s", acfg->image->name, MONO_SOLIB_EXT);
9890 tmp_outfile_name = g_strdup_printf ("%s.tmp", outfile_name);
9893 llvm_ofile = g_strdup_printf ("\"%s\"", acfg->llvm_ofile);
9895 llvm_ofile = g_strdup ("");
9898 /* replace the ; flags separators with spaces */
9899 g_strdelimit (ld_flags, ";", ' ');
9901 if (acfg->aot_opts.llvm_only)
9902 ld_flags = g_strdup_printf ("%s %s", ld_flags, "-lstdc++");
9905 command = g_strdup_printf ("%s%s %s -o %s %s %s %s", tool_prefix, LD_NAME, LD_OPTIONS,
9906 wrap_path (tmp_outfile_name), wrap_path (llvm_ofile),
9907 wrap_path (g_strdup_printf ("%s.o", acfg->tmpfname)), ld_flags);
9910 command = g_strdup_printf ("\"%sld\" %s -shared -o %s %s %s %s", tool_prefix, LD_OPTIONS,
9911 wrap_path (tmp_outfile_name), wrap_path (llvm_ofile),
9912 wrap_path (g_strdup_printf ("%s.o", acfg->tmpfname)), ld_flags);
9914 aot_printf (acfg, "Executing the native linker: %s\n", command);
9915 if (execute_system (command) != 0) {
9916 g_free (tmp_outfile_name);
9917 g_free (outfile_name);
9926 /*com = g_strdup_printf ("strip --strip-unneeded %s%s", acfg->image->name, MONO_SOLIB_EXT);
9927 printf ("Stripping the binary: %s\n", com);
9928 execute_system (com);
9931 #if defined(TARGET_ARM) && !defined(TARGET_MACH)
9933 * gas generates 'mapping symbols' each time code and data is mixed, which
9934 * happens a lot in emit_and_reloc_code (), so we need to get rid of them.
9936 command = g_strdup_printf ("\"%sstrip\" --strip-symbol=\\$a --strip-symbol=\\$d %s", tool_prefix, tmp_outfile_name);
9937 aot_printf (acfg, "Stripping the binary: %s\n", command);
9938 if (execute_system (command) != 0) {
9939 g_free (tmp_outfile_name);
9940 g_free (outfile_name);
9947 if (0 != rename (tmp_outfile_name, outfile_name)) {
9948 if (G_FILE_ERROR_EXIST == g_file_error_from_errno (errno)) {
9949 /* Since we are rebuilding the module we need to be able to replace any old copies. Remove old file and retry rename operation. */
9950 unlink (outfile_name);
9951 rename (tmp_outfile_name, outfile_name);
9955 #if defined(TARGET_MACH)
9956 command = g_strdup_printf ("dsymutil \"%s\"", outfile_name);
9957 aot_printf (acfg, "Executing dsymutil: %s\n", command);
9958 if (execute_system (command) != 0) {
9963 if (!acfg->aot_opts.save_temps)
9966 g_free (tmp_outfile_name);
9967 g_free (outfile_name);
9970 if (acfg->aot_opts.save_temps)
9971 aot_printf (acfg, "Retained input file.\n");
9973 unlink (acfg->tmpfname);
9978 static void init_got_info (GotInfo *info)
9982 info->patch_to_got_offset = g_hash_table_new (mono_patch_info_hash, mono_patch_info_equal);
9983 info->patch_to_got_offset_by_type = g_new0 (GHashTable*, MONO_PATCH_INFO_NUM);
9984 for (i = 0; i < MONO_PATCH_INFO_NUM; ++i)
9985 info->patch_to_got_offset_by_type [i] = g_hash_table_new (mono_patch_info_hash, mono_patch_info_equal);
9986 info->got_patches = g_ptr_array_new ();
9989 static MonoAotCompile*
9990 acfg_create (MonoAssembly *ass, guint32 opts)
9992 MonoImage *image = ass->image;
9993 MonoAotCompile *acfg;
9995 acfg = g_new0 (MonoAotCompile, 1);
9996 acfg->methods = g_ptr_array_new ();
9997 acfg->method_indexes = g_hash_table_new (NULL, NULL);
9998 acfg->method_depth = g_hash_table_new (NULL, NULL);
9999 acfg->plt_offset_to_entry = g_hash_table_new (NULL, NULL);
10000 acfg->patch_to_plt_entry = g_new0 (GHashTable*, MONO_PATCH_INFO_NUM);
10001 acfg->method_to_cfg = g_hash_table_new (NULL, NULL);
10002 acfg->token_info_hash = g_hash_table_new_full (NULL, NULL, NULL, NULL);
10003 acfg->method_to_pinvoke_import = g_hash_table_new_full (NULL, NULL, NULL, g_free);
10004 acfg->image_hash = g_hash_table_new (NULL, NULL);
10005 acfg->image_table = g_ptr_array_new ();
10006 acfg->globals = g_ptr_array_new ();
10007 acfg->image = image;
10009 /* TODO: Write out set of SIMD instructions used, rather than just those available */
10010 acfg->simd_opts = mono_arch_cpu_enumerate_simd_versions ();
10011 acfg->mempool = mono_mempool_new ();
10012 acfg->extra_methods = g_ptr_array_new ();
10013 acfg->unwind_info_offsets = g_hash_table_new (NULL, NULL);
10014 acfg->unwind_ops = g_ptr_array_new ();
10015 acfg->method_label_hash = g_hash_table_new_full (g_str_hash, g_str_equal, g_free, NULL);
10016 acfg->method_order = g_ptr_array_new ();
10017 acfg->export_names = g_hash_table_new (NULL, NULL);
10018 acfg->klass_blob_hash = g_hash_table_new (NULL, NULL);
10019 acfg->method_blob_hash = g_hash_table_new (NULL, NULL);
10020 acfg->plt_entry_debug_sym_cache = g_hash_table_new (g_str_hash, g_str_equal);
10021 acfg->gsharedvt_in_signatures = g_hash_table_new ((GHashFunc)mono_signature_hash, (GEqualFunc)mono_metadata_signature_equal);
10022 acfg->gsharedvt_out_signatures = g_hash_table_new ((GHashFunc)mono_signature_hash, (GEqualFunc)mono_metadata_signature_equal);
10023 mono_os_mutex_init_recursive (&acfg->mutex);
10025 init_got_info (&acfg->got_info);
10026 init_got_info (&acfg->llvm_got_info);
10032 got_info_free (GotInfo *info)
10036 for (i = 0; i < MONO_PATCH_INFO_NUM; ++i)
10037 g_hash_table_destroy (info->patch_to_got_offset_by_type [i]);
10038 g_free (info->patch_to_got_offset_by_type);
10039 g_hash_table_destroy (info->patch_to_got_offset);
10040 g_ptr_array_free (info->got_patches, TRUE);
10044 acfg_free (MonoAotCompile *acfg)
10048 mono_img_writer_destroy (acfg->w);
10049 for (i = 0; i < acfg->nmethods; ++i)
10050 if (acfg->cfgs [i])
10051 mono_destroy_compile (acfg->cfgs [i]);
10053 g_free (acfg->cfgs);
10055 g_free (acfg->static_linking_symbol);
10056 g_free (acfg->got_symbol);
10057 g_free (acfg->plt_symbol);
10058 g_ptr_array_free (acfg->methods, TRUE);
10059 g_ptr_array_free (acfg->image_table, TRUE);
10060 g_ptr_array_free (acfg->globals, TRUE);
10061 g_ptr_array_free (acfg->unwind_ops, TRUE);
10062 g_hash_table_destroy (acfg->method_indexes);
10063 g_hash_table_destroy (acfg->method_depth);
10064 g_hash_table_destroy (acfg->plt_offset_to_entry);
10065 for (i = 0; i < MONO_PATCH_INFO_NUM; ++i) {
10066 if (acfg->patch_to_plt_entry [i])
10067 g_hash_table_destroy (acfg->patch_to_plt_entry [i]);
10069 g_free (acfg->patch_to_plt_entry);
10070 g_hash_table_destroy (acfg->method_to_cfg);
10071 g_hash_table_destroy (acfg->token_info_hash);
10072 g_hash_table_destroy (acfg->method_to_pinvoke_import);
10073 g_hash_table_destroy (acfg->image_hash);
10074 g_hash_table_destroy (acfg->unwind_info_offsets);
10075 g_hash_table_destroy (acfg->method_label_hash);
10076 if (acfg->typespec_classes)
10077 g_hash_table_destroy (acfg->typespec_classes);
10078 g_hash_table_destroy (acfg->export_names);
10079 g_hash_table_destroy (acfg->plt_entry_debug_sym_cache);
10080 g_hash_table_destroy (acfg->klass_blob_hash);
10081 g_hash_table_destroy (acfg->method_blob_hash);
10082 got_info_free (&acfg->got_info);
10083 got_info_free (&acfg->llvm_got_info);
10084 mono_mempool_destroy (acfg->mempool);
10088 #define WRAPPER(e,n) n,
10089 static const char* const
10090 wrapper_type_names [MONO_WRAPPER_NUM + 1] = {
10091 #include "mono/metadata/wrapper-types.h"
10095 static G_GNUC_UNUSED const char*
10096 get_wrapper_type_name (int type)
10098 return wrapper_type_names [type];
10104 static void aot_dump (MonoAotCompile *acfg)
10110 mono_json_writer_init (&writer);
10112 mono_json_writer_object_begin(&writer);
10115 mono_json_writer_indent (&writer);
10116 mono_json_writer_object_key(&writer, "methods");
10117 mono_json_writer_array_begin (&writer);
10120 for (i = 0; i < acfg->nmethods; ++i) {
10122 MonoMethod *method;
10125 cfg = acfg->cfgs [i];
10129 method = cfg->orig_method;
10131 mono_json_writer_indent (&writer);
10132 mono_json_writer_object_begin(&writer);
10134 mono_json_writer_indent (&writer);
10135 mono_json_writer_object_key(&writer, "name");
10136 mono_json_writer_printf (&writer, "\"%s\",\n", method->name);
10138 mono_json_writer_indent (&writer);
10139 mono_json_writer_object_key(&writer, "signature");
10140 mono_json_writer_printf (&writer, "\"%s\",\n", mono_method_get_full_name (method));
10142 mono_json_writer_indent (&writer);
10143 mono_json_writer_object_key(&writer, "code_size");
10144 mono_json_writer_printf (&writer, "\"%d\",\n", cfg->code_size);
10146 klass = method->klass;
10148 mono_json_writer_indent (&writer);
10149 mono_json_writer_object_key(&writer, "class");
10150 mono_json_writer_printf (&writer, "\"%s\",\n", klass->name);
10152 mono_json_writer_indent (&writer);
10153 mono_json_writer_object_key(&writer, "namespace");
10154 mono_json_writer_printf (&writer, "\"%s\",\n", klass->name_space);
10156 mono_json_writer_indent (&writer);
10157 mono_json_writer_object_key(&writer, "wrapper_type");
10158 mono_json_writer_printf (&writer, "\"%s\",\n", get_wrapper_type_name(method->wrapper_type));
10160 mono_json_writer_indent_pop (&writer);
10161 mono_json_writer_indent (&writer);
10162 mono_json_writer_object_end (&writer);
10163 mono_json_writer_printf (&writer, ",\n");
10166 mono_json_writer_indent_pop (&writer);
10167 mono_json_writer_indent (&writer);
10168 mono_json_writer_array_end (&writer);
10169 mono_json_writer_printf (&writer, ",\n");
10173 mono_json_writer_indent_push (&writer);
10174 mono_json_writer_indent (&writer);
10175 mono_json_writer_object_key(&writer, "plt");
10176 mono_json_writer_array_begin (&writer);
10178 for (i = 0; i < acfg->plt_offset; ++i) {
10179 MonoPltEntry *plt_entry = NULL;
10184 * The first plt entry is unused.
10188 plt_entry = g_hash_table_lookup (acfg->plt_offset_to_entry, GUINT_TO_POINTER (i));
10189 ji = plt_entry->ji;
10191 mono_json_writer_indent (&writer);
10192 mono_json_writer_printf (&writer, "{ ");
10193 mono_json_writer_object_key(&writer, "symbol");
10194 mono_json_writer_printf (&writer, "\"%s\" },\n", plt_entry->symbol);
10197 mono_json_writer_indent_pop (&writer);
10198 mono_json_writer_indent (&writer);
10199 mono_json_writer_array_end (&writer);
10200 mono_json_writer_printf (&writer, ",\n");
10205 mono_json_writer_indent_push (&writer);
10206 mono_json_writer_indent (&writer);
10207 mono_json_writer_object_key(&writer, "got");
10208 mono_json_writer_array_begin (&writer);
10210 mono_json_writer_indent_push (&writer);
10211 for (i = 0; i < acfg->got_info.got_patches->len; ++i) {
10212 MonoJumpInfo *ji = g_ptr_array_index (acfg->got_info.got_patches, i);
10214 mono_json_writer_indent (&writer);
10215 mono_json_writer_printf (&writer, "{ ");
10216 mono_json_writer_object_key(&writer, "patch_name");
10217 mono_json_writer_printf (&writer, "\"%s\" },\n", get_patch_name (ji->type));
10220 mono_json_writer_indent_pop (&writer);
10221 mono_json_writer_indent (&writer);
10222 mono_json_writer_array_end (&writer);
10223 mono_json_writer_printf (&writer, ",\n");
10226 mono_json_writer_indent_pop (&writer);
10227 mono_json_writer_indent (&writer);
10228 mono_json_writer_object_end (&writer);
10230 dumpname = g_strdup_printf ("%s.json", g_path_get_basename (acfg->image->name));
10231 dumpfile = fopen (dumpname, "w+");
10234 fprintf (dumpfile, "%s", writer.text->str);
10237 mono_json_writer_destroy (&writer);
10240 static const char *preinited_jit_icalls[] = {
10241 "mono_aot_init_llvm_method",
10242 "mono_aot_init_gshared_method_this",
10243 "mono_aot_init_gshared_method_mrgctx",
10244 "mono_aot_init_gshared_method_vtable",
10245 "mono_llvm_throw_corlib_exception",
10246 "mono_init_vtable_slot",
10247 "mono_helper_ldstr_mscorlib"
10251 add_preinit_got_slots (MonoAotCompile *acfg)
10257 * Allocate the first few GOT entries to information which is needed frequently, or it is needed
10258 * during method initialization etc.
10261 ji = (MonoJumpInfo *)mono_mempool_alloc0 (acfg->mempool, sizeof (MonoJumpInfo));
10262 ji->type = MONO_PATCH_INFO_IMAGE;
10263 ji->data.image = acfg->image;
10264 get_got_offset (acfg, FALSE, ji);
10265 get_got_offset (acfg, TRUE, ji);
10267 ji = (MonoJumpInfo *)mono_mempool_alloc0 (acfg->mempool, sizeof (MonoJumpInfo));
10268 ji->type = MONO_PATCH_INFO_MSCORLIB_GOT_ADDR;
10269 get_got_offset (acfg, FALSE, ji);
10270 get_got_offset (acfg, TRUE, ji);
10272 ji = (MonoJumpInfo *)mono_mempool_alloc0 (acfg->mempool, sizeof (MonoJumpInfo));
10273 ji->type = MONO_PATCH_INFO_GC_CARD_TABLE_ADDR;
10274 get_got_offset (acfg, FALSE, ji);
10275 get_got_offset (acfg, TRUE, ji);
10277 ji = (MonoJumpInfo *)mono_mempool_alloc0 (acfg->mempool, sizeof (MonoJumpInfo));
10278 ji->type = MONO_PATCH_INFO_GC_NURSERY_START;
10279 get_got_offset (acfg, FALSE, ji);
10280 get_got_offset (acfg, TRUE, ji);
10282 ji = (MonoJumpInfo *)mono_mempool_alloc0 (acfg->mempool, sizeof (MonoJumpInfo));
10283 ji->type = MONO_PATCH_INFO_JIT_TLS_ID;
10284 get_got_offset (acfg, FALSE, ji);
10285 get_got_offset (acfg, TRUE, ji);
10287 ji = (MonoJumpInfo *)mono_mempool_alloc0 (acfg->mempool, sizeof (MonoJumpInfo));
10288 ji->type = MONO_PATCH_INFO_AOT_MODULE;
10289 get_got_offset (acfg, FALSE, ji);
10290 get_got_offset (acfg, TRUE, ji);
10292 ji = (MonoJumpInfo *)mono_mempool_alloc0 (acfg->mempool, sizeof (MonoJumpInfo));
10293 ji->type = MONO_PATCH_INFO_GC_NURSERY_BITS;
10294 get_got_offset (acfg, FALSE, ji);
10295 get_got_offset (acfg, TRUE, ji);
10297 for (i = 0; i < sizeof (preinited_jit_icalls) / sizeof (char*); ++i) {
10298 ji = (MonoJumpInfo *)mono_mempool_alloc0 (acfg->mempool, sizeof (MonoAotCompile));
10299 ji->type = MONO_PATCH_INFO_INTERNAL_METHOD;
10300 ji->data.name = preinited_jit_icalls [i];
10301 get_got_offset (acfg, FALSE, ji);
10302 get_got_offset (acfg, TRUE, ji);
10305 acfg->nshared_got_entries = acfg->got_offset;
10309 mono_compile_assembly (MonoAssembly *ass, guint32 opts, const char *aot_options)
10311 MonoImage *image = ass->image;
10314 MonoAotCompile *acfg;
10315 char *outfile_name, *tmp_outfile_name, *p;
10316 char llvm_stats_msg [256];
10320 acfg = acfg_create (ass, opts);
10322 memset (&acfg->aot_opts, 0, sizeof (acfg->aot_opts));
10323 acfg->aot_opts.write_symbols = TRUE;
10324 acfg->aot_opts.ntrampolines = 4096;
10325 acfg->aot_opts.nrgctx_trampolines = 4096;
10326 acfg->aot_opts.nimt_trampolines = 512;
10327 acfg->aot_opts.nrgctx_fetch_trampolines = 128;
10328 acfg->aot_opts.ngsharedvt_arg_trampolines = 512;
10329 acfg->aot_opts.llvm_path = g_strdup ("");
10330 acfg->aot_opts.temp_path = g_strdup ("");
10332 acfg->aot_opts.use_trampolines_page = TRUE;
10335 mono_aot_parse_options (aot_options, &acfg->aot_opts);
10337 if (acfg->aot_opts.logfile) {
10338 acfg->logfile = fopen (acfg->aot_opts.logfile, "a+");
10341 if (acfg->aot_opts.data_outfile) {
10342 acfg->data_outfile = fopen (acfg->aot_opts.data_outfile, "w+");
10343 if (!acfg->data_outfile) {
10344 aot_printerrf (acfg, "Unable to create file '%s': %s\n", acfg->aot_opts.data_outfile, strerror (errno));
10347 acfg->flags = (MonoAotFileFlags)(acfg->flags | MONO_AOT_FILE_FLAG_SEPARATE_DATA);
10350 //acfg->aot_opts.print_skipped_methods = TRUE;
10352 #if !defined(MONO_ARCH_GSHAREDVT_SUPPORTED)
10353 if (opts & MONO_OPT_GSHAREDVT) {
10354 aot_printerrf (acfg, "-O=gsharedvt not supported on this platform.\n");
10359 #if !defined(MONO_ARCH_GSHAREDVT_SUPPORTED)
10360 if (!acfg->aot_opts.llvm_only && (opts & MONO_OPT_GSHAREDVT)) {
10361 aot_printerrf (acfg, "-O=gsharedvt not supported on this platform.\n");
10366 if (acfg->aot_opts.llvm_only) {
10367 #ifndef MONO_ARCH_GSHAREDVT_SUPPORTED
10368 aot_printerrf (acfg, "--aot=llvmonly requires a runtime that supports gsharedvt.\n");
10373 #if defined(MONO_ARCH_GSHAREDVT_SUPPORTED)
10374 if (acfg->aot_opts.llvm_only || mono_aot_mode_is_full (&acfg->aot_opts)) {
10375 acfg->opts |= MONO_OPT_GSHAREDVT;
10376 opts |= MONO_OPT_GSHAREDVT;
10380 if (opts & MONO_OPT_GSHAREDVT)
10381 mono_set_generic_sharing_vt_supported (TRUE);
10383 aot_printf (acfg, "Mono Ahead of Time compiler - compiling assembly %s\n", image->name);
10385 #ifndef MONO_ARCH_HAVE_FULL_AOT_TRAMPOLINES
10386 if (mono_aot_mode_is_full (&acfg->aot_opts)) {
10387 aot_printerrf (acfg, "--aot=full is not supported on this platform.\n");
10392 if (acfg->aot_opts.direct_pinvoke && !acfg->aot_opts.static_link) {
10393 aot_printerrf (acfg, "The 'direct-pinvoke' AOT option also requires the 'static' AOT option.\n");
10397 if (acfg->aot_opts.static_link)
10398 acfg->aot_opts.asm_writer = TRUE;
10400 if (acfg->aot_opts.soft_debug) {
10401 MonoDebugOptions *opt = mini_get_debug_options ();
10403 opt->mdb_optimizations = TRUE;
10404 opt->gen_sdb_seq_points = TRUE;
10406 if (!mono_debug_enabled ()) {
10407 aot_printerrf (acfg, "The soft-debug AOT option requires the --debug option.\n");
10410 acfg->flags = (MonoAotFileFlags)(acfg->flags | MONO_AOT_FILE_FLAG_DEBUG);
10413 if (mono_use_llvm || acfg->aot_opts.llvm) {
10415 acfg->aot_opts.asm_writer = TRUE;
10416 acfg->flags = (MonoAotFileFlags)(acfg->flags | MONO_AOT_FILE_FLAG_WITH_LLVM);
10418 if (acfg->aot_opts.soft_debug) {
10419 aot_printerrf (acfg, "The 'soft-debug' option is not supported when compiling with LLVM.\n");
10425 if (acfg->aot_opts.asm_only && !acfg->aot_opts.llvm_outfile) {
10426 aot_printerrf (acfg, "Compiling with LLVM and the asm-only option requires the llvm-outputfile= option.");
10431 * Emit all LLVM code into a separate assembly/object file and link with it
10434 if (!acfg->aot_opts.asm_only) {
10435 acfg->llvm_owriter = TRUE;
10436 } else if (acfg->aot_opts.llvm_outfile) {
10437 int len = strlen (acfg->aot_opts.llvm_outfile);
10439 if (len >= 2 && acfg->aot_opts.llvm_outfile [len - 2] == '.' && acfg->aot_opts.llvm_outfile [len - 1] == 'o')
10440 acfg->llvm_owriter = TRUE;
10444 if (mono_aot_mode_is_full (&acfg->aot_opts))
10445 acfg->flags = (MonoAotFileFlags)(acfg->flags | MONO_AOT_FILE_FLAG_FULL_AOT);
10447 if (mono_threads_is_coop_enabled ())
10448 acfg->flags = (MonoAotFileFlags)(acfg->flags | MONO_AOT_FILE_FLAG_SAFEPOINTS);
10450 if (acfg->aot_opts.instances_logfile_path) {
10451 acfg->instances_logfile = fopen (acfg->aot_opts.instances_logfile_path, "w");
10452 if (!acfg->instances_logfile) {
10453 aot_printerrf (acfg, "Unable to create logfile: '%s'.\n", acfg->aot_opts.instances_logfile_path);
10458 load_profile_files (acfg);
10460 acfg->num_trampolines [MONO_AOT_TRAMP_SPECIFIC] = mono_aot_mode_is_full (&acfg->aot_opts) ? acfg->aot_opts.ntrampolines : 0;
10461 #ifdef MONO_ARCH_GSHARED_SUPPORTED
10462 acfg->num_trampolines [MONO_AOT_TRAMP_STATIC_RGCTX] = mono_aot_mode_is_full (&acfg->aot_opts) ? acfg->aot_opts.nrgctx_trampolines : 0;
10464 acfg->num_trampolines [MONO_AOT_TRAMP_IMT_THUNK] = mono_aot_mode_is_full (&acfg->aot_opts) ? acfg->aot_opts.nimt_trampolines : 0;
10465 #ifdef MONO_ARCH_GSHAREDVT_SUPPORTED
10466 if (acfg->opts & MONO_OPT_GSHAREDVT)
10467 acfg->num_trampolines [MONO_AOT_TRAMP_GSHAREDVT_ARG] = mono_aot_mode_is_full (&acfg->aot_opts) ? acfg->aot_opts.ngsharedvt_arg_trampolines : 0;
10470 acfg->temp_prefix = mono_img_writer_get_temp_label_prefix (NULL);
10474 if (acfg->llvm && acfg->thumb_mixed)
10475 acfg->flags = (MonoAotFileFlags)(acfg->flags | MONO_AOT_FILE_FLAG_LLVM_THUMB);
10476 if (acfg->aot_opts.llvm_only)
10477 acfg->flags = (MonoAotFileFlags)(acfg->flags | MONO_AOT_FILE_FLAG_LLVM_ONLY);
10479 acfg->assembly_name_sym = g_strdup (acfg->image->assembly->aname.name);
10480 /* Get rid of characters which cannot occur in symbols */
10481 for (p = acfg->assembly_name_sym; *p; ++p) {
10482 if (!(isalnum (*p) || *p == '_'))
10486 acfg->global_prefix = g_strdup_printf ("mono_aot_%s", acfg->assembly_name_sym);
10487 acfg->plt_symbol = g_strdup_printf ("%s_plt", acfg->global_prefix);
10488 acfg->got_symbol = g_strdup_printf ("%s_got", acfg->global_prefix);
10490 acfg->llvm_got_symbol = g_strdup_printf ("%s_llvm_got", acfg->global_prefix);
10491 acfg->llvm_eh_frame_symbol = g_strdup_printf ("%s_eh_frame", acfg->global_prefix);
10494 acfg->method_index = 1;
10496 if (mono_aot_mode_is_full (&acfg->aot_opts))
10497 mono_set_partial_sharing_supported (TRUE);
10499 res = collect_methods (acfg);
10503 acfg->cfgs_size = acfg->methods->len + 32;
10504 acfg->cfgs = g_new0 (MonoCompile*, acfg->cfgs_size);
10506 /* PLT offset 0 is reserved for the PLT trampoline */
10507 acfg->plt_offset = 1;
10508 add_preinit_got_slots (acfg);
10513 mono_llvm_create_aot_module (acfg->image->assembly, acfg->global_prefix, TRUE, acfg->aot_opts.static_link, acfg->aot_opts.llvm_only);
10519 compile_methods (acfg);
10523 acfg->stats.jit_time = TV_ELAPSED (atv, btv);
10529 if (acfg->aot_opts.asm_only) {
10530 if (acfg->aot_opts.outfile) {
10531 acfg->tmpfname = g_strdup_printf ("%s", acfg->aot_opts.outfile);
10532 acfg->tmpbasename = g_strdup (acfg->tmpfname);
10534 acfg->tmpbasename = g_strdup_printf ("%s", acfg->image->name);
10535 acfg->tmpfname = g_strdup_printf ("%s.s", acfg->tmpbasename);
10537 g_assert (acfg->aot_opts.llvm_outfile);
10538 acfg->llvm_sfile = g_strdup (acfg->aot_opts.llvm_outfile);
10539 if (acfg->llvm_owriter)
10540 acfg->llvm_ofile = g_strdup (acfg->aot_opts.llvm_outfile);
10542 acfg->llvm_sfile = g_strdup (acfg->aot_opts.llvm_outfile);
10544 acfg->tmpbasename = (strcmp (acfg->aot_opts.temp_path, "") == 0) ?
10545 g_strdup_printf ("%s", "temp") :
10546 g_build_filename (acfg->aot_opts.temp_path, "temp", NULL);
10548 acfg->tmpfname = g_strdup_printf ("%s.s", acfg->tmpbasename);
10549 acfg->llvm_sfile = g_strdup_printf ("%s-llvm.s", acfg->tmpbasename);
10550 acfg->llvm_ofile = g_strdup_printf ("%s-llvm.o", acfg->tmpbasename);
10555 if (acfg->aot_opts.asm_only && !acfg->aot_opts.llvm_only) {
10556 if (acfg->aot_opts.outfile)
10557 acfg->tmpfname = g_strdup_printf ("%s", acfg->aot_opts.outfile);
10559 acfg->tmpfname = g_strdup_printf ("%s.s", acfg->image->name);
10560 acfg->fp = fopen (acfg->tmpfname, "w+");
10562 int i = g_file_open_tmp ("mono_aot_XXXXXX", &acfg->tmpfname, NULL);
10563 acfg->fp = fdopen (i, "w+");
10565 if (acfg->fp == 0 && !acfg->aot_opts.llvm_only) {
10566 aot_printerrf (acfg, "Unable to open file '%s': %s\n", acfg->tmpfname, strerror (errno));
10570 acfg->w = mono_img_writer_create (acfg->fp, FALSE);
10572 tmp_outfile_name = NULL;
10573 outfile_name = NULL;
10575 /* Compute symbols for methods */
10576 for (i = 0; i < acfg->nmethods; ++i) {
10577 if (acfg->cfgs [i]) {
10578 MonoCompile *cfg = acfg->cfgs [i];
10579 int method_index = get_method_index (acfg, cfg->orig_method);
10581 if (COMPILE_LLVM (cfg))
10582 cfg->asm_symbol = g_strdup_printf ("%s%s", acfg->llvm_label_prefix, cfg->llvm_method_name);
10583 else if (acfg->global_symbols || acfg->llvm)
10584 cfg->asm_symbol = get_debug_sym (cfg->orig_method, "", acfg->method_label_hash);
10586 cfg->asm_symbol = g_strdup_printf ("%s%sm_%x", acfg->temp_prefix, acfg->llvm_label_prefix, method_index);
10587 cfg->asm_debug_symbol = cfg->asm_symbol;
10591 if (acfg->aot_opts.dwarf_debug && acfg->aot_opts.gnu_asm) {
10593 * CLANG supports GAS .file/.loc directives, so emit line number information this way
10595 acfg->gas_line_numbers = TRUE;
10598 if ((!acfg->aot_opts.nodebug || acfg->aot_opts.dwarf_debug) && acfg->has_jitted_code) {
10599 if (acfg->aot_opts.dwarf_debug && !mono_debug_enabled ()) {
10600 aot_printerrf (acfg, "The dwarf AOT option requires the --debug option.\n");
10603 acfg->dwarf = mono_dwarf_writer_create (acfg->w, NULL, 0, !acfg->gas_line_numbers);
10607 mono_img_writer_emit_start (acfg->w);
10610 mono_dwarf_writer_emit_base_info (acfg->dwarf, g_path_get_basename (acfg->image->name), mono_unwind_get_cie_program ());
10616 emit_extra_methods (acfg);
10618 emit_trampolines (acfg);
10620 emit_class_name_table (acfg);
10622 emit_got_info (acfg, FALSE);
10624 emit_got_info (acfg, TRUE);
10626 emit_exception_info (acfg);
10628 emit_unwind_info (acfg);
10630 emit_class_info (acfg);
10634 emit_image_table (acfg);
10640 * The managed allocators are GC specific, so can't use an AOT image created by one GC
10643 const char *gc_name = mono_gc_get_gc_name ();
10644 acfg->gc_name_offset = add_to_blob (acfg, (guint8*)gc_name, strlen (gc_name) + 1);
10649 emit_objc_selectors (acfg);
10651 emit_globals (acfg);
10653 emit_file_info (acfg);
10656 emit_dwarf_info (acfg);
10657 mono_dwarf_writer_close (acfg->dwarf);
10660 emit_mem_end (acfg);
10662 if (acfg->need_pt_gnu_stack) {
10663 /* This is required so the .so doesn't have an executable stack */
10664 /* The bin writer already emits this */
10665 fprintf (acfg->fp, "\n.section .note.GNU-stack,\"\",@progbits\n");
10668 if (acfg->aot_opts.data_outfile)
10669 fclose (acfg->data_outfile);
10675 res = emit_llvm_file (acfg);
10683 acfg->stats.gen_time = TV_ELAPSED (atv, btv);
10686 sprintf (llvm_stats_msg, ", LLVM: %d (%d%%)", acfg->stats.llvm_count, acfg->stats.mcount ? (acfg->stats.llvm_count * 100) / acfg->stats.mcount : 100);
10688 strcpy (llvm_stats_msg, "");
10690 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;
10692 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",
10693 (int)acfg->stats.code_size, (int)(acfg->stats.code_size * 100 / all_sizes),
10694 (int)acfg->stats.info_size, (int)(acfg->stats.info_size * 100 / all_sizes),
10695 (int)acfg->stats.ex_info_size, (int)(acfg->stats.ex_info_size * 100 / all_sizes),
10696 (int)acfg->stats.unwind_info_size, (int)(acfg->stats.unwind_info_size * 100 / all_sizes),
10697 (int)acfg->stats.class_info_size, (int)(acfg->stats.class_info_size * 100 / all_sizes),
10698 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,
10699 (int)acfg->stats.got_info_size, (int)(acfg->stats.got_info_size * 100 / all_sizes),
10700 (int)acfg->stats.offsets_size, (int)(acfg->stats.offsets_size * 100 / all_sizes),
10701 (int)(acfg->got_offset * sizeof (gpointer)));
10702 aot_printf (acfg, "Compiled: %d/%d (%d%%)%s, No GOT slots: %d (%d%%), Direct calls: %d (%d%%)\n",
10703 acfg->stats.ccount, acfg->stats.mcount, acfg->stats.mcount ? (acfg->stats.ccount * 100) / acfg->stats.mcount : 100,
10705 acfg->stats.methods_without_got_slots, acfg->stats.mcount ? (acfg->stats.methods_without_got_slots * 100) / acfg->stats.mcount : 100,
10706 acfg->stats.direct_calls, acfg->stats.all_calls ? (acfg->stats.direct_calls * 100) / acfg->stats.all_calls : 100);
10707 if (acfg->stats.genericcount)
10708 aot_printf (acfg, "%d methods are generic (%d%%)\n", acfg->stats.genericcount, acfg->stats.mcount ? (acfg->stats.genericcount * 100) / acfg->stats.mcount : 100);
10709 if (acfg->stats.abscount)
10710 aot_printf (acfg, "%d methods contain absolute addresses (%d%%)\n", acfg->stats.abscount, acfg->stats.mcount ? (acfg->stats.abscount * 100) / acfg->stats.mcount : 100);
10711 if (acfg->stats.lmfcount)
10712 aot_printf (acfg, "%d methods contain lmf pointers (%d%%)\n", acfg->stats.lmfcount, acfg->stats.mcount ? (acfg->stats.lmfcount * 100) / acfg->stats.mcount : 100);
10713 if (acfg->stats.ocount)
10714 aot_printf (acfg, "%d methods have other problems (%d%%)\n", acfg->stats.ocount, acfg->stats.mcount ? (acfg->stats.ocount * 100) / acfg->stats.mcount : 100);
10718 res = mono_img_writer_emit_writeout (acfg->w);
10723 res = compile_asm (acfg);
10730 acfg->stats.link_time = TV_ELAPSED (atv, btv);
10732 if (acfg->aot_opts.stats) {
10735 aot_printf (acfg, "GOT slot distribution:\n");
10736 for (i = 0; i < MONO_PATCH_INFO_NUM; ++i)
10737 if (acfg->stats.got_slot_types [i])
10738 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]);
10739 aot_printf (acfg, "\nMethod stats:\n");
10740 aot_printf (acfg, "\tNormal: %d\n", acfg->stats.method_categories [METHOD_CAT_NORMAL]);
10741 aot_printf (acfg, "\tInstance: %d\n", acfg->stats.method_categories [METHOD_CAT_INST]);
10742 aot_printf (acfg, "\tGSharedvt: %d\n", acfg->stats.method_categories [METHOD_CAT_GSHAREDVT]);
10743 aot_printf (acfg, "\tWrapper: %d\n", acfg->stats.method_categories [METHOD_CAT_WRAPPER]);
10746 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);
10748 if (acfg->aot_opts.dump_json)
10761 mono_aot_readonly_field_override (MonoClassField *field)
10767 mono_compile_assembly (MonoAssembly *ass, guint32 opts, const char *aot_options)
10773 mono_aot_is_shared_got_offset (int offset)