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>
56 #include "aot-compiler.h"
57 #include "seq-points.h"
58 #include "image-writer.h"
59 #include "dwarfwriter.h"
61 #include "mini-llvm.h"
63 #if !defined(DISABLE_AOT) && !defined(DISABLE_JIT)
65 #if defined(__linux__) || defined(__native_client_codegen__)
66 #define RODATA_SECT ".rodata"
67 #elif defined(TARGET_MACH)
68 #define RODATA_SECT ".section __TEXT, __const"
70 #define RODATA_SECT ".text"
73 #define TV_DECLARE(name) gint64 name
74 #define TV_GETTIME(tv) tv = mono_100ns_ticks ()
75 #define TV_ELAPSED(start,end) (((end) - (start)) / 10)
77 #define ALIGN_TO(val,align) ((((guint64)val) + ((align) - 1)) & ~((align) - 1))
78 #define ALIGN_PTR_TO(ptr,align) (gpointer)((((gssize)(ptr)) + (align - 1)) & (~(align - 1)))
79 #define ROUND_DOWN(VALUE,SIZE) ((VALUE) & ~((SIZE) - 1))
81 /* predefined values for static readonly fields without needed to run the .cctor */
82 typedef struct _ReadOnlyValue ReadOnlyValue;
83 struct _ReadOnlyValue {
86 int type; /* to be used later for typechecking to prevent user errors */
95 static ReadOnlyValue *readonly_values;
97 typedef struct MonoAotOptions {
102 gboolean write_symbols;
103 gboolean metadata_only;
104 gboolean bind_to_runtime_version;
107 gboolean static_link;
111 gboolean dwarf_debug;
113 gboolean log_generics;
114 gboolean log_instances;
115 gboolean gen_seq_points_file;
116 char *gen_seq_points_file_path;
117 gboolean direct_pinvoke;
118 gboolean direct_icalls;
119 gboolean no_direct_calls;
120 gboolean use_trampolines_page;
121 gboolean no_instances;
127 int nrgctx_trampolines;
128 int nimt_trampolines;
129 int ngsharedvt_arg_trampolines;
130 int nrgctx_fetch_trampolines;
131 gboolean print_skipped_methods;
138 char *instances_logfile_path;
145 METHOD_CAT_GSHAREDVT,
151 typedef struct MonoAotStats {
152 int ccount, mcount, lmfcount, abscount, gcount, ocount, genericcount;
153 gint64 code_size, info_size, ex_info_size, unwind_info_size, got_size, class_info_size, got_info_size, plt_size;
154 int methods_without_got_slots, direct_calls, all_calls, llvm_count;
155 int got_slots, offsets_size;
156 int method_categories [METHOD_CAT_NUM];
157 int got_slot_types [MONO_PATCH_INFO_NUM];
158 int got_slot_info_sizes [MONO_PATCH_INFO_NUM];
159 int jit_time, gen_time, link_time;
162 typedef struct GotInfo {
163 GHashTable *patch_to_got_offset;
164 GHashTable **patch_to_got_offset_by_type;
165 GPtrArray *got_patches;
168 typedef struct MonoAotCompile {
171 GHashTable *method_indexes;
172 GHashTable *method_depth;
175 GHashTable **patch_to_plt_entry;
176 GHashTable *plt_offset_to_entry;
177 //GHashTable *patch_to_got_offset;
178 //GHashTable **patch_to_got_offset_by_type;
179 //GPtrArray *got_patches;
180 GotInfo got_info, llvm_got_info;
181 GHashTable *image_hash;
182 GHashTable *method_to_cfg;
183 GHashTable *token_info_hash;
184 GHashTable *method_to_pinvoke_import;
185 GPtrArray *extra_methods;
186 GPtrArray *image_table;
188 GPtrArray *method_order;
189 GHashTable *export_names;
190 /* Maps MonoClass* -> blob offset */
191 GHashTable *klass_blob_hash;
192 /* Maps MonoMethod* -> blob offset */
193 GHashTable *method_blob_hash;
194 GHashTable *gsharedvt_in_signatures;
195 GHashTable *gsharedvt_out_signatures;
196 guint32 *plt_got_info_offsets;
197 guint32 got_offset, llvm_got_offset, plt_offset, plt_got_offset_base, nshared_got_entries;
198 /* Number of GOT entries reserved for trampolines */
199 guint32 num_trampoline_got_entries;
200 guint32 tramp_page_size;
202 guint32 table_offsets [MONO_AOT_TABLE_NUM];
203 guint32 num_trampolines [MONO_AOT_TRAMP_NUM];
204 guint32 trampoline_got_offset_base [MONO_AOT_TRAMP_NUM];
205 guint32 trampoline_size [MONO_AOT_TRAMP_NUM];
206 guint32 tramp_page_code_offsets [MONO_AOT_TRAMP_NUM];
208 MonoAotOptions aot_opts;
212 MonoMemPool *mempool;
215 char *static_linking_symbol;
217 gboolean gas_line_numbers;
218 /* Whenever to emit an object file directly from llc */
219 gboolean llvm_owriter;
221 MonoDwarfWriter *dwarf;
228 GHashTable *unwind_info_offsets;
229 GPtrArray *unwind_ops;
230 guint32 unwind_info_offset;
233 char *llvm_got_symbol;
235 char *llvm_eh_frame_symbol;
236 GHashTable *method_label_hash;
237 const char *temp_prefix;
238 const char *user_symbol_prefix;
239 const char *llvm_label_prefix;
240 const char *inst_directive;
242 guint32 label_generator;
244 gboolean has_jitted_code;
245 MonoAotFileFlags flags;
246 MonoDynamicStream blob;
247 gboolean blob_closed;
248 MonoClass **typespec_classes;
251 char *assembly_name_sym;
252 GHashTable *plt_entry_debug_sym_cache;
253 gboolean thumb_mixed, need_no_dead_strip, need_pt_gnu_stack;
254 GHashTable *ginst_hash;
255 GHashTable *dwarf_ln_filenames;
256 gboolean global_symbols;
257 int objc_selector_index, objc_selector_index_2;
258 GPtrArray *objc_selectors;
259 GHashTable *objc_selector_to_index;
261 FILE *instances_logfile;
269 char *symbol, *llvm_symbol, *debug_sym;
271 gboolean jit_used, llvm_used;
274 #define mono_acfg_lock(acfg) mono_os_mutex_lock (&((acfg)->mutex))
275 #define mono_acfg_unlock(acfg) mono_os_mutex_unlock (&((acfg)->mutex))
277 /* This points to the current acfg in LLVM mode */
278 static MonoAotCompile *llvm_acfg;
280 #ifdef HAVE_ARRAY_ELEM_INIT
281 #define MSGSTRFIELD(line) MSGSTRFIELD1(line)
282 #define MSGSTRFIELD1(line) str##line
283 static const struct msgstr_t {
284 #define PATCH_INFO(a,b) char MSGSTRFIELD(__LINE__) [sizeof (b)];
285 #include "patch-info.h"
288 #define PATCH_INFO(a,b) b,
289 #include "patch-info.h"
292 static const gint16 opidx [] = {
293 #define PATCH_INFO(a,b) [MONO_PATCH_INFO_ ## a] = offsetof (struct msgstr_t, MSGSTRFIELD(__LINE__)),
294 #include "patch-info.h"
298 static G_GNUC_UNUSED const char*
299 get_patch_name (int info)
301 return (const char*)&opstr + opidx [info];
305 #define PATCH_INFO(a,b) b,
306 static const char* const
307 patch_types [MONO_PATCH_INFO_NUM + 1] = {
308 #include "patch-info.h"
312 static G_GNUC_UNUSED const char*
313 get_patch_name (int info)
315 return patch_types [info];
321 get_unwind_info_offset (MonoAotCompile *acfg, guint8 *encoded, guint32 encoded_len);
324 get_plt_entry_debug_sym (MonoAotCompile *acfg, MonoJumpInfo *ji, GHashTable *cache);
327 aot_printf (MonoAotCompile *acfg, const gchar *format, ...)
333 output = acfg->logfile;
337 va_start (args, format);
338 vfprintf (output, format, args);
343 aot_printerrf (MonoAotCompile *acfg, const gchar *format, ...)
349 output = acfg->logfile;
353 va_start (args, format);
354 vfprintf (output, format, args);
359 report_loader_error (MonoAotCompile *acfg, MonoError *error, const char *format, ...)
364 if (mono_error_ok (error))
368 output = acfg->logfile;
372 va_start (args, format);
373 vfprintf (output, format, args);
375 mono_error_cleanup (error);
377 g_error ("FullAOT cannot continue if there are loader errors");
380 /* Wrappers around the image writer functions */
382 #define MAX_SYMBOL_SIZE 256
384 static inline const char *
385 mangle_symbol (const char * symbol, char * mangled_symbol, gsize length)
387 gsize needed_size = length;
389 g_assert (NULL != symbol);
390 g_assert (NULL != mangled_symbol);
391 g_assert (0 != length);
393 #if defined(TARGET_WIN32) && defined(TARGET_X86)
394 if (symbol && '_' != symbol [0]) {
395 needed_size = g_snprintf (mangled_symbol, length, "_%s", symbol);
397 needed_size = g_snprintf (mangled_symbol, length, "%s", symbol);
400 needed_size = g_snprintf (mangled_symbol, length, "%s", symbol);
403 g_assert (0 <= needed_size && needed_size < length);
404 return mangled_symbol;
408 mangle_symbol_alloc (const char * symbol)
410 g_assert (NULL != symbol);
412 #if defined(TARGET_WIN32) && defined(TARGET_X86)
413 if (symbol && '_' != symbol [0]) {
414 return g_strdup_printf ("_%s", symbol);
417 return g_strdup_printf ("%s", symbol);
420 return g_strdup_printf ("%s", symbol);
425 emit_section_change (MonoAotCompile *acfg, const char *section_name, int subsection_index)
427 mono_img_writer_emit_section_change (acfg->w, section_name, subsection_index);
430 #if defined(TARGET_WIN32) && defined(TARGET_X86)
433 emit_local_symbol (MonoAotCompile *acfg, const char *name, const char *end_label, gboolean func)
435 const char * mangled_symbol_name = name;
436 char * mangled_symbol_name_alloc = NULL;
439 mangled_symbol_name_alloc = mangle_symbol_alloc (name);
440 mangled_symbol_name = mangled_symbol_name_alloc;
443 if (name != mangled_symbol_name && 0 != g_strcasecmp (name, mangled_symbol_name)) {
444 mono_img_writer_emit_label (acfg->w, mangled_symbol_name);
446 mono_img_writer_emit_local_symbol (acfg->w, mangled_symbol_name, end_label, func);
448 if (NULL != mangled_symbol_name_alloc) {
449 g_free (mangled_symbol_name_alloc);
456 emit_local_symbol (MonoAotCompile *acfg, const char *name, const char *end_label, gboolean func)
458 mono_img_writer_emit_local_symbol (acfg->w, name, end_label, func);
464 emit_label (MonoAotCompile *acfg, const char *name)
466 mono_img_writer_emit_label (acfg->w, name);
470 emit_bytes (MonoAotCompile *acfg, const guint8* buf, int size)
472 mono_img_writer_emit_bytes (acfg->w, buf, size);
476 emit_string (MonoAotCompile *acfg, const char *value)
478 mono_img_writer_emit_string (acfg->w, value);
482 emit_line (MonoAotCompile *acfg)
484 mono_img_writer_emit_line (acfg->w);
488 emit_alignment (MonoAotCompile *acfg, int size)
490 mono_img_writer_emit_alignment (acfg->w, size);
494 emit_alignment_code (MonoAotCompile *acfg, int size)
496 if (acfg->align_pad_value)
497 mono_img_writer_emit_alignment_fill (acfg->w, size, acfg->align_pad_value);
499 mono_img_writer_emit_alignment (acfg->w, size);
503 emit_padding (MonoAotCompile *acfg, int size)
508 if (acfg->align_pad_value) {
509 for (i = 0; i < 16; ++i)
510 buf [i] = acfg->align_pad_value;
512 memset (buf, 0, sizeof (buf));
515 for (i = 0; i < size; i += 16) {
517 emit_bytes (acfg, buf, size - i);
519 emit_bytes (acfg, buf, 16);
524 emit_pointer (MonoAotCompile *acfg, const char *target)
526 mono_img_writer_emit_pointer (acfg->w, target);
530 emit_pointer_2 (MonoAotCompile *acfg, const char *prefix, const char *target)
532 if (prefix [0] != '\0') {
533 char *s = g_strdup_printf ("%s%s", prefix, target);
534 mono_img_writer_emit_pointer (acfg->w, s);
537 mono_img_writer_emit_pointer (acfg->w, target);
542 emit_int16 (MonoAotCompile *acfg, int value)
544 mono_img_writer_emit_int16 (acfg->w, value);
548 emit_int32 (MonoAotCompile *acfg, int value)
550 mono_img_writer_emit_int32 (acfg->w, value);
554 emit_symbol_diff (MonoAotCompile *acfg, const char *end, const char* start, int offset)
556 mono_img_writer_emit_symbol_diff (acfg->w, end, start, offset);
560 emit_zero_bytes (MonoAotCompile *acfg, int num)
562 mono_img_writer_emit_zero_bytes (acfg->w, num);
566 emit_byte (MonoAotCompile *acfg, guint8 val)
568 mono_img_writer_emit_byte (acfg->w, val);
571 #ifdef __native_client_codegen__
573 emit_nacl_call_alignment (MonoAotCompile *acfg)
575 mono_img_writer_emit_nacl_call_alignment (acfg->w);
579 #if defined(TARGET_WIN32) && defined(TARGET_X86)
581 static G_GNUC_UNUSED void
582 emit_global_inner (MonoAotCompile *acfg, const char *name, gboolean func)
584 const char * mangled_symbol_name = name;
585 char * mangled_symbol_name_alloc = NULL;
587 mangled_symbol_name_alloc = mangle_symbol_alloc (name);
588 mangled_symbol_name = mangled_symbol_name_alloc;
590 if (0 != g_strcasecmp (name, mangled_symbol_name)) {
591 mono_img_writer_emit_label (acfg->w, mangled_symbol_name);
593 mono_img_writer_emit_global (acfg->w, mangled_symbol_name, func);
595 if (NULL != mangled_symbol_name_alloc) {
596 g_free (mangled_symbol_name_alloc);
602 static G_GNUC_UNUSED void
603 emit_global_inner (MonoAotCompile *acfg, const char *name, gboolean func)
605 mono_img_writer_emit_global (acfg->w, name, func);
611 emit_global (MonoAotCompile *acfg, const char *name, gboolean func)
613 if (acfg->aot_opts.no_dlsym) {
614 g_ptr_array_add (acfg->globals, g_strdup (name));
615 mono_img_writer_emit_local_symbol (acfg->w, name, NULL, func);
617 emit_global_inner (acfg, name, func);
622 emit_symbol_size (MonoAotCompile *acfg, const char *name, const char *end_label)
624 mono_img_writer_emit_symbol_size (acfg->w, name, end_label);
627 /* Emit a symbol which is referenced by the MonoAotFileInfo structure */
629 emit_info_symbol (MonoAotCompile *acfg, const char *name)
631 char symbol [MAX_SYMBOL_SIZE];
634 emit_label (acfg, name);
635 /* LLVM generated code references this */
636 sprintf (symbol, "%s%s%s", acfg->user_symbol_prefix, acfg->global_prefix, name);
637 emit_label (acfg, symbol);
638 emit_global_inner (acfg, symbol, FALSE);
640 emit_label (acfg, name);
645 emit_string_symbol (MonoAotCompile *acfg, const char *name, const char *value)
648 mono_llvm_emit_aot_data (name, (guint8*)value, strlen (value) + 1);
652 mono_img_writer_emit_section_change (acfg->w, RODATA_SECT, 1);
654 /* On apple, all symbols need to be aligned to avoid warnings from ld */
655 emit_alignment (acfg, 4);
657 mono_img_writer_emit_label (acfg->w, name);
658 mono_img_writer_emit_string (acfg->w, value);
661 static G_GNUC_UNUSED void
662 emit_uleb128 (MonoAotCompile *acfg, guint32 value)
665 guint8 b = value & 0x7f;
667 if (value != 0) /* more bytes to come */
673 static G_GNUC_UNUSED void
674 emit_sleb128 (MonoAotCompile *acfg, gint64 value)
677 gboolean negative = (value < 0);
684 /* the following is unnecessary if the
685 * implementation of >>= uses an arithmetic rather
686 * than logical shift for a signed left operand
690 value |= - ((gint64)1 <<(size - 7));
691 /* sign bit of byte is second high order bit (0x40) */
692 if ((value == 0 && !(byte & 0x40)) ||
693 (value == -1 && (byte & 0x40)))
697 emit_byte (acfg, byte);
701 static G_GNUC_UNUSED void
702 encode_uleb128 (guint32 value, guint8 *buf, guint8 **endbuf)
707 guint8 b = value & 0x7f;
709 if (value != 0) /* more bytes to come */
717 static G_GNUC_UNUSED void
718 encode_sleb128 (gint32 value, guint8 *buf, guint8 **endbuf)
721 gboolean negative = (value < 0);
729 /* the following is unnecessary if the
730 * implementation of >>= uses an arithmetic rather
731 * than logical shift for a signed left operand
735 value |= - (1 <<(size - 7));
736 /* sign bit of byte is second high order bit (0x40) */
737 if ((value == 0 && !(byte & 0x40)) ||
738 (value == -1 && (byte & 0x40)))
749 encode_int (gint32 val, guint8 *buf, guint8 **endbuf)
752 buf [0] = (val >> 0) & 0xff;
753 buf [1] = (val >> 8) & 0xff;
754 buf [2] = (val >> 16) & 0xff;
755 buf [3] = (val >> 24) & 0xff;
761 encode_int16 (guint16 val, guint8 *buf, guint8 **endbuf)
763 buf [0] = (val >> 0) & 0xff;
764 buf [1] = (val >> 8) & 0xff;
770 encode_string (const char *s, guint8 *buf, guint8 **endbuf)
772 int len = strlen (s);
774 memcpy (buf, s, len + 1);
775 *endbuf = buf + len + 1;
779 emit_unset_mode (MonoAotCompile *acfg)
781 mono_img_writer_emit_unset_mode (acfg->w);
784 static G_GNUC_UNUSED void
785 emit_set_thumb_mode (MonoAotCompile *acfg)
787 emit_unset_mode (acfg);
788 fprintf (acfg->fp, ".code 16\n");
791 static G_GNUC_UNUSED void
792 emit_set_arm_mode (MonoAotCompile *acfg)
794 emit_unset_mode (acfg);
795 fprintf (acfg->fp, ".code 32\n");
799 emit_code_bytes (MonoAotCompile *acfg, const guint8* buf, int size)
804 g_assert (size % 4 == 0);
805 emit_unset_mode (acfg);
806 for (i = 0; i < size; i += 4)
807 fprintf (acfg->fp, "%s 0x%x\n", acfg->inst_directive, *(guint32*)(buf + i));
809 emit_bytes (acfg, buf, size);
813 /* ARCHITECTURE SPECIFIC CODE */
815 #if defined(TARGET_X86) || defined(TARGET_AMD64) || defined(TARGET_ARM) || defined(TARGET_POWERPC) || defined(TARGET_ARM64)
816 #define EMIT_DWARF_INFO 1
819 #if defined(TARGET_ARM)
820 #define AOT_FUNC_ALIGNMENT 4
822 #define AOT_FUNC_ALIGNMENT 16
824 #if (defined(TARGET_X86) || defined(TARGET_AMD64)) && defined(__native_client_codegen__)
825 #undef AOT_FUNC_ALIGNMENT
826 #define AOT_FUNC_ALIGNMENT 32
829 #if defined(TARGET_POWERPC64) && !defined(__mono_ilp32__)
830 #define PPC_LD_OP "ld"
831 #define PPC_LDX_OP "ldx"
833 #define PPC_LD_OP "lwz"
834 #define PPC_LDX_OP "lwzx"
838 #define AOT_TARGET_STR "AMD64"
843 #define AOT_TARGET_STR "ARM (MACH)"
845 #define AOT_TARGET_STR "ARM (!MACH)"
851 #define AOT_TARGET_STR "ARM64 (MACH)"
853 #define AOT_TARGET_STR "ARM64 (!MACH)"
857 #ifdef TARGET_POWERPC64
858 #ifdef __mono_ilp32__
859 #define AOT_TARGET_STR "POWERPC64 (mono ilp32)"
861 #define AOT_TARGET_STR "POWERPC64 (!mono ilp32)"
864 #ifdef TARGET_POWERPC
865 #ifdef __mono_ilp32__
866 #define AOT_TARGET_STR "POWERPC (mono ilp32)"
868 #define AOT_TARGET_STR "POWERPC (!mono ilp32)"
875 #define AOT_TARGET_STR "X86 (WIN32)"
876 #elif defined(__native_client_codegen__)
877 #define AOT_TARGET_STR "X86 (native client codegen)"
879 #define AOT_TARGET_STR "X86 (!native client codegen)"
883 #ifndef AOT_TARGET_STR
884 #define AOT_TARGET_STR ""
888 arch_init (MonoAotCompile *acfg)
890 acfg->llc_args = g_string_new ("");
891 acfg->as_args = g_string_new ("");
894 * The prefix LLVM likes to put in front of symbol names on darwin.
895 * The mach-os specs require this for globals, but LLVM puts them in front of all
896 * symbols. We need to handle this, since we need to refer to LLVM generated
899 acfg->llvm_label_prefix = "";
900 acfg->user_symbol_prefix = "";
902 #if defined(TARGET_X86)
903 g_string_append (acfg->llc_args, " -march=x86 -mattr=sse4.1");
906 #if defined(TARGET_AMD64)
907 g_string_append (acfg->llc_args, " -march=x86-64 -mattr=sse4.1");
909 acfg->align_pad_value = 0x90;
913 if (acfg->aot_opts.mtriple && strstr (acfg->aot_opts.mtriple, "darwin")) {
914 g_string_append (acfg->llc_args, "-mattr=+v6");
917 g_string_append (acfg->llc_args, " -mattr=+vfp2,-neon,+d16");
918 g_string_append (acfg->as_args, " -mfpu=vfp3");
920 g_string_append (acfg->llc_args, " -soft-float");
923 if (acfg->aot_opts.mtriple && strstr (acfg->aot_opts.mtriple, "thumb"))
924 acfg->thumb_mixed = TRUE;
926 if (acfg->aot_opts.mtriple)
927 mono_arch_set_target (acfg->aot_opts.mtriple);
931 acfg->inst_directive = ".inst";
932 if (acfg->aot_opts.mtriple)
933 mono_arch_set_target (acfg->aot_opts.mtriple);
937 acfg->user_symbol_prefix = "_";
938 acfg->llvm_label_prefix = "_";
939 acfg->inst_directive = ".word";
940 acfg->need_no_dead_strip = TRUE;
941 acfg->aot_opts.gnu_asm = TRUE;
944 #if defined(__linux__) && !defined(TARGET_ARM)
945 acfg->need_pt_gnu_stack = TRUE;
949 acfg->global_symbols = TRUE;
956 /* Load the contents of GOT_SLOT into dreg, clobbering ip0 */
958 arm64_emit_load_got_slot (MonoAotCompile *acfg, int dreg, int got_slot)
963 emit_unset_mode (acfg);
965 offset = (int)(got_slot * sizeof (gpointer));
967 /* clang's integrated assembler */
968 fprintf (acfg->fp, "adrp x16, %s@PAGE+%d\n", acfg->got_symbol, offset & 0xfffff000);
969 fprintf (acfg->fp, "add x16, x16, %s@PAGEOFF\n", acfg->got_symbol);
970 fprintf (acfg->fp, "ldr x%d, [x16, #%d]\n", dreg, offset & 0xfff);
973 fprintf (acfg->fp, "adrp x16, %s+%d\n", acfg->got_symbol, offset & 0xfffff000);
974 fprintf (acfg->fp, "add x16, x16, :lo12:%s\n", acfg->got_symbol);
975 fprintf (acfg->fp, "ldr x%d, [x16, %d]\n", dreg, offset & 0xfff);
980 arm64_emit_objc_selector_ref (MonoAotCompile *acfg, guint8 *code, int index, int *code_size)
985 emit_unset_mode (acfg);
988 reg = arm_get_ldr_lit_reg (code);
990 fprintf (acfg->fp, "adrp x%d, L_OBJC_SELECTOR_REFERENCES_%d@PAGE\n", reg, index);
991 fprintf (acfg->fp, "add x%d, x%d, L_OBJC_SELECTOR_REFERENCES_%d@PAGEOFF\n", reg, reg, index);
992 fprintf (acfg->fp, "ldr x%d, [x%d]\n", reg, reg);
998 arm64_emit_direct_call (MonoAotCompile *acfg, const char *target, gboolean external, gboolean thumb, MonoJumpInfo *ji, int *call_size)
1000 g_assert (acfg->fp);
1001 emit_unset_mode (acfg);
1002 if (ji && ji->relocation == MONO_R_ARM64_B) {
1003 fprintf (acfg->fp, "b %s\n", target);
1006 g_assert (ji->relocation == MONO_R_ARM64_BL);
1007 fprintf (acfg->fp, "bl %s\n", target);
1013 arm64_emit_got_access (MonoAotCompile *acfg, guint8 *code, int got_slot, int *code_size)
1017 /* ldr rt, target */
1018 reg = arm_get_ldr_lit_reg (code);
1019 arm64_emit_load_got_slot (acfg, reg, got_slot);
1024 arm64_emit_plt_entry (MonoAotCompile *acfg, const char *got_symbol, int offset, int info_offset)
1026 arm64_emit_load_got_slot (acfg, ARMREG_R16, offset / sizeof (gpointer));
1027 fprintf (acfg->fp, "br x16\n");
1028 /* Used by mono_aot_get_plt_info_offset () */
1029 fprintf (acfg->fp, "%s %d\n", acfg->inst_directive, info_offset);
1033 arm64_emit_tramp_page_common_code (MonoAotCompile *acfg, int pagesize, int arg_reg, int *size)
1039 /* The common code */
1042 /* The trampoline address is in IP0 */
1043 arm_movzx (code, ARMREG_IP1, imm & 0xffff, 0);
1044 arm_movkx (code, ARMREG_IP1, (imm >> 16) & 0xffff, 16);
1045 /* Compute the data slot address */
1046 arm_subx (code, ARMREG_IP0, ARMREG_IP0, ARMREG_IP1);
1047 /* Trampoline argument */
1048 arm_ldrx (code, arg_reg, ARMREG_IP0, 0);
1050 arm_ldrx (code, ARMREG_IP0, ARMREG_IP0, 8);
1051 arm_brx (code, ARMREG_IP0);
1054 emit_code_bytes (acfg, buf, code - buf);
1060 arm64_emit_tramp_page_specific_code (MonoAotCompile *acfg, int pagesize, int common_tramp_size, int specific_tramp_size)
1066 count = (pagesize - common_tramp_size) / specific_tramp_size;
1067 for (i = 0; i < count; ++i) {
1069 arm_adrx (code, ARMREG_IP0, code);
1070 /* Branch to the generic code */
1071 arm_b (code, code - 4 - (i * specific_tramp_size) - common_tramp_size);
1072 /* This has to be 2 pointers long */
1075 g_assert (code - buf == specific_tramp_size);
1076 emit_code_bytes (acfg, buf, code - buf);
1081 arm64_emit_specific_trampoline_pages (MonoAotCompile *acfg)
1085 guint8 *labels [16];
1086 int common_tramp_size;
1087 int specific_tramp_size = 2 * 8;
1091 if (!acfg->aot_opts.use_trampolines_page)
1095 /* Have to match the target pagesize */
1098 pagesize = mono_pagesize ();
1100 acfg->tramp_page_size = pagesize;
1102 /* The specific trampolines */
1103 sprintf (symbol, "%sspecific_trampolines_page", acfg->user_symbol_prefix);
1104 emit_alignment (acfg, pagesize);
1105 emit_global (acfg, symbol, TRUE);
1106 emit_label (acfg, symbol);
1108 /* The common code */
1109 arm64_emit_tramp_page_common_code (acfg, pagesize, ARMREG_IP1, &common_tramp_size);
1110 acfg->tramp_page_code_offsets [MONO_AOT_TRAMP_SPECIFIC] = common_tramp_size;
1112 arm64_emit_tramp_page_specific_code (acfg, pagesize, common_tramp_size, specific_tramp_size);
1114 /* The rgctx trampolines */
1115 /* These are the same as the specific trampolines, but they load the argument into MONO_ARCH_RGCTX_REG */
1116 sprintf (symbol, "%srgctx_trampolines_page", acfg->user_symbol_prefix);
1117 emit_alignment (acfg, pagesize);
1118 emit_global (acfg, symbol, TRUE);
1119 emit_label (acfg, symbol);
1121 /* The common code */
1122 arm64_emit_tramp_page_common_code (acfg, pagesize, MONO_ARCH_RGCTX_REG, &common_tramp_size);
1123 acfg->tramp_page_code_offsets [MONO_AOT_TRAMP_STATIC_RGCTX] = common_tramp_size;
1125 arm64_emit_tramp_page_specific_code (acfg, pagesize, common_tramp_size, specific_tramp_size);
1127 /* The gsharedvt arg trampolines */
1128 /* These are the same as the specific trampolines */
1129 sprintf (symbol, "%sgsharedvt_arg_trampolines_page", acfg->user_symbol_prefix);
1130 emit_alignment (acfg, pagesize);
1131 emit_global (acfg, symbol, TRUE);
1132 emit_label (acfg, symbol);
1134 arm64_emit_tramp_page_common_code (acfg, pagesize, ARMREG_IP1, &common_tramp_size);
1135 acfg->tramp_page_code_offsets [MONO_AOT_TRAMP_GSHAREDVT_ARG] = common_tramp_size;
1137 arm64_emit_tramp_page_specific_code (acfg, pagesize, common_tramp_size, specific_tramp_size);
1139 /* The IMT trampolines */
1140 sprintf (symbol, "%simt_trampolines_page", acfg->user_symbol_prefix);
1141 emit_alignment (acfg, pagesize);
1142 emit_global (acfg, symbol, TRUE);
1143 emit_label (acfg, symbol);
1147 /* The trampoline address is in IP0 */
1148 arm_movzx (code, ARMREG_IP1, imm & 0xffff, 0);
1149 arm_movkx (code, ARMREG_IP1, (imm >> 16) & 0xffff, 16);
1150 /* Compute the data slot address */
1151 arm_subx (code, ARMREG_IP0, ARMREG_IP0, ARMREG_IP1);
1152 /* Trampoline argument */
1153 arm_ldrx (code, ARMREG_IP1, ARMREG_IP0, 0);
1155 /* Same as arch_emit_imt_thunk () */
1157 arm_ldrx (code, ARMREG_IP0, ARMREG_IP1, 0);
1158 arm_cmpx (code, ARMREG_IP0, MONO_ARCH_RGCTX_REG);
1160 arm_bcc (code, ARMCOND_EQ, 0);
1162 /* End-of-loop check */
1164 arm_cbzx (code, ARMREG_IP0, 0);
1167 arm_addx_imm (code, ARMREG_IP1, ARMREG_IP1, 2 * 8);
1168 arm_b (code, labels [0]);
1171 mono_arm_patch (labels [1], code, MONO_R_ARM64_BCC);
1172 /* Load vtable slot addr */
1173 arm_ldrx (code, ARMREG_IP0, ARMREG_IP1, 8);
1174 /* Load vtable slot */
1175 arm_ldrx (code, ARMREG_IP0, ARMREG_IP0, 0);
1176 arm_brx (code, ARMREG_IP0);
1179 mono_arm_patch (labels [2], code, MONO_R_ARM64_CBZ);
1180 /* Load fail addr */
1181 arm_ldrx (code, ARMREG_IP0, ARMREG_IP1, 8);
1182 arm_brx (code, ARMREG_IP0);
1184 emit_code_bytes (acfg, buf, code - buf);
1186 common_tramp_size = code - buf;
1187 acfg->tramp_page_code_offsets [MONO_AOT_TRAMP_IMT_THUNK] = common_tramp_size;
1189 arm64_emit_tramp_page_specific_code (acfg, pagesize, common_tramp_size, specific_tramp_size);
1193 arm64_emit_specific_trampoline (MonoAotCompile *acfg, int offset, int *tramp_size)
1195 /* Load argument from second GOT slot */
1196 arm64_emit_load_got_slot (acfg, ARMREG_R17, offset + 1);
1197 /* Load generic trampoline address from first GOT slot */
1198 arm64_emit_load_got_slot (acfg, ARMREG_R16, offset);
1199 fprintf (acfg->fp, "br x16\n");
1200 *tramp_size = 7 * 4;
1204 arm64_emit_unbox_trampoline (MonoAotCompile *acfg, MonoCompile *cfg, MonoMethod *method, const char *call_target)
1206 emit_unset_mode (acfg);
1207 fprintf (acfg->fp, "add x0, x0, %d\n", (int)(sizeof (MonoObject)));
1208 fprintf (acfg->fp, "b %s\n", call_target);
1212 arm64_emit_static_rgctx_trampoline (MonoAotCompile *acfg, int offset, int *tramp_size)
1214 /* Similar to the specific trampolines, but use the rgctx reg instead of ip1 */
1216 /* Load argument from first GOT slot */
1217 arm64_emit_load_got_slot (acfg, MONO_ARCH_RGCTX_REG, offset);
1218 /* Load generic trampoline address from second GOT slot */
1219 arm64_emit_load_got_slot (acfg, ARMREG_R16, offset + 1);
1220 fprintf (acfg->fp, "br x16\n");
1221 *tramp_size = 7 * 4;
1225 arm64_emit_imt_thunk (MonoAotCompile *acfg, int offset, int *tramp_size)
1228 guint8 *code, *labels [16];
1230 /* Load parameter from GOT slot into ip1 */
1231 arm64_emit_load_got_slot (acfg, ARMREG_R17, offset);
1235 arm_ldrx (code, ARMREG_IP0, ARMREG_IP1, 0);
1236 arm_cmpx (code, ARMREG_IP0, MONO_ARCH_RGCTX_REG);
1238 arm_bcc (code, ARMCOND_EQ, 0);
1240 /* End-of-loop check */
1242 arm_cbzx (code, ARMREG_IP0, 0);
1245 arm_addx_imm (code, ARMREG_IP1, ARMREG_IP1, 2 * 8);
1246 arm_b (code, labels [0]);
1249 mono_arm_patch (labels [1], code, MONO_R_ARM64_BCC);
1250 /* Load vtable slot addr */
1251 arm_ldrx (code, ARMREG_IP0, ARMREG_IP1, 8);
1252 /* Load vtable slot */
1253 arm_ldrx (code, ARMREG_IP0, ARMREG_IP0, 0);
1254 arm_brx (code, ARMREG_IP0);
1257 mono_arm_patch (labels [2], code, MONO_R_ARM64_CBZ);
1258 /* Load fail addr */
1259 arm_ldrx (code, ARMREG_IP0, ARMREG_IP1, 8);
1260 arm_brx (code, ARMREG_IP0);
1262 emit_code_bytes (acfg, buf, code - buf);
1264 *tramp_size = code - buf + (3 * 4);
1268 arm64_emit_gsharedvt_arg_trampoline (MonoAotCompile *acfg, int offset, int *tramp_size)
1270 /* Similar to the specific trampolines, but the address is in the second slot */
1271 /* Load argument from first GOT slot */
1272 arm64_emit_load_got_slot (acfg, ARMREG_R17, offset);
1273 /* Load generic trampoline address from second GOT slot */
1274 arm64_emit_load_got_slot (acfg, ARMREG_R16, offset + 1);
1275 fprintf (acfg->fp, "br x16\n");
1276 *tramp_size = 7 * 4;
1282 #ifdef MONO_ARCH_AOT_SUPPORTED
1284 * arch_emit_direct_call:
1286 * Emit a direct call to the symbol TARGET. CALL_SIZE is set to the size of the
1290 arch_emit_direct_call (MonoAotCompile *acfg, const char *target, gboolean external, gboolean thumb, MonoJumpInfo *ji, int *call_size)
1292 #if defined(TARGET_X86) || defined(TARGET_AMD64)
1293 /* Need to make sure this is exactly 5 bytes long */
1294 emit_unset_mode (acfg);
1295 fprintf (acfg->fp, "call %s\n", target);
1297 #elif defined(TARGET_ARM)
1298 emit_unset_mode (acfg);
1300 fprintf (acfg->fp, "blx %s\n", target);
1302 fprintf (acfg->fp, "bl %s\n", target);
1304 #elif defined(TARGET_ARM64)
1305 arm64_emit_direct_call (acfg, target, external, thumb, ji, call_size);
1306 #elif defined(TARGET_POWERPC)
1307 emit_unset_mode (acfg);
1308 fprintf (acfg->fp, "bl %s\n", target);
1311 g_assert_not_reached ();
1318 * - we use an approach similar to the x86 abi: reserve a register (r30) to hold
1320 * - The full-aot trampolines need access to the GOT of mscorlib, so we store
1321 * in in the 2. slot of every GOT, and require every method to place the GOT
1322 * address in r30, even when it doesn't access the GOT otherwise. This way,
1323 * the trampolines can compute the mscorlib GOT address by loading 4(r30).
1328 * PPC64 uses function descriptors which greatly complicate all code, since
1329 * these are used very inconsistently in the runtime. Some functions like
1330 * mono_compile_method () return ftn descriptors, while others like the
1331 * trampoline creation functions do not.
1332 * We assume that all GOT slots contain function descriptors, and create
1333 * descriptors in aot-runtime.c when needed.
1334 * The ppc64 abi uses r2 to hold the address of the TOC/GOT, which is loaded
1335 * from function descriptors, we could do the same, but it would require
1336 * rewriting all the ppc/aot code to handle function descriptors properly.
1337 * So instead, we use the same approach as on PPC32.
1338 * This is a horrible mess, but fixing it would probably lead to an even bigger
1344 * - similar to the PPC32 design, we reserve EBX to hold the GOT pointer.
1347 #ifdef MONO_ARCH_AOT_SUPPORTED
1349 * arch_emit_got_offset:
1351 * The memory pointed to by CODE should hold native code for computing the GOT
1352 * address (OP_LOAD_GOTADDR). Emit this code while patching it with the offset
1353 * between code and the GOT. CODE_SIZE is set to the number of bytes emitted.
1356 arch_emit_got_offset (MonoAotCompile *acfg, guint8 *code, int *code_size)
1358 #if defined(TARGET_POWERPC64)
1359 emit_unset_mode (acfg);
1361 * The ppc32 code doesn't seem to work on ppc64, the assembler complains about
1362 * unsupported relocations. So we store the got address into the .Lgot_addr
1363 * symbol which is in the text segment, compute its address, and load it.
1365 fprintf (acfg->fp, ".L%d:\n", acfg->label_generator);
1366 fprintf (acfg->fp, "lis 0, (.Lgot_addr + 4 - .L%d)@h\n", acfg->label_generator);
1367 fprintf (acfg->fp, "ori 0, 0, (.Lgot_addr + 4 - .L%d)@l\n", acfg->label_generator);
1368 fprintf (acfg->fp, "add 30, 30, 0\n");
1369 fprintf (acfg->fp, "%s 30, 0(30)\n", PPC_LD_OP);
1370 acfg->label_generator ++;
1372 #elif defined(TARGET_POWERPC)
1373 emit_unset_mode (acfg);
1374 fprintf (acfg->fp, ".L%d:\n", acfg->label_generator);
1375 fprintf (acfg->fp, "lis 0, (%s + 4 - .L%d)@h\n", acfg->got_symbol, acfg->label_generator);
1376 fprintf (acfg->fp, "ori 0, 0, (%s + 4 - .L%d)@l\n", acfg->got_symbol, acfg->label_generator);
1377 acfg->label_generator ++;
1380 guint32 offset = mono_arch_get_patch_offset (code);
1381 emit_bytes (acfg, code, offset);
1382 emit_symbol_diff (acfg, acfg->got_symbol, ".", offset);
1384 *code_size = offset + 4;
1389 * arch_emit_got_access:
1391 * The memory pointed to by CODE should hold native code for loading a GOT
1392 * slot (OP_AOTCONST/OP_GOT_ENTRY). Emit this code while patching it so it accesses the
1393 * GOT slot GOT_SLOT. CODE_SIZE is set to the number of bytes emitted.
1396 arch_emit_got_access (MonoAotCompile *acfg, const char *got_symbol, guint8 *code, int got_slot, int *code_size)
1399 /* mov reg, got+offset(%rip) */
1401 /* The GOT symbol is in the LLVM module, the clang assembler has problems emitting symbol diffs for it */
1405 /* Decode reg, see amd64_mov_reg_membase () */
1406 rex_r = code [0] & AMD64_REX_R;
1407 g_assert (code [0] == 0x49 + rex_r);
1408 g_assert (code [1] == 0x8b);
1409 dreg = ((code [2] >> 3) & 0x7) + (rex_r ? 8 : 0);
1411 emit_unset_mode (acfg);
1412 fprintf (acfg->fp, "mov %s+%d(%%rip), %s\n", got_symbol, (unsigned int) ((got_slot * sizeof (gpointer))), mono_arch_regname (dreg));
1415 emit_bytes (acfg, code, mono_arch_get_patch_offset (code));
1416 emit_symbol_diff (acfg, got_symbol, ".", (unsigned int) ((got_slot * sizeof (gpointer)) - 4));
1417 *code_size = mono_arch_get_patch_offset (code) + 4;
1419 #elif defined(TARGET_X86)
1420 emit_bytes (acfg, code, mono_arch_get_patch_offset (code));
1421 emit_int32 (acfg, (unsigned int) ((got_slot * sizeof (gpointer))));
1422 *code_size = mono_arch_get_patch_offset (code) + 4;
1423 #elif defined(TARGET_ARM)
1424 emit_bytes (acfg, code, mono_arch_get_patch_offset (code));
1425 emit_symbol_diff (acfg, got_symbol, ".", (unsigned int) ((got_slot * sizeof (gpointer))) - 12);
1426 *code_size = mono_arch_get_patch_offset (code) + 4;
1427 #elif defined(TARGET_ARM64)
1428 emit_bytes (acfg, code, mono_arch_get_patch_offset (code));
1429 arm64_emit_got_access (acfg, code, got_slot, code_size);
1430 #elif defined(TARGET_POWERPC)
1435 emit_bytes (acfg, code, mono_arch_get_patch_offset (code));
1437 ppc_load32 (code, ppc_r0, got_slot * sizeof (gpointer));
1438 g_assert (code - buf == 8);
1439 emit_bytes (acfg, buf, code - buf);
1440 *code_size = code - buf;
1443 g_assert_not_reached ();
1449 #ifdef MONO_ARCH_AOT_SUPPORTED
1451 * arch_emit_objc_selector_ref:
1453 * Emit the implementation of OP_OBJC_GET_SELECTOR, which itself implements @selector(foo:) in objective-c.
1456 arch_emit_objc_selector_ref (MonoAotCompile *acfg, guint8 *code, int index, int *code_size)
1458 #if defined(TARGET_ARM)
1459 char symbol1 [MAX_SYMBOL_SIZE];
1460 char symbol2 [MAX_SYMBOL_SIZE];
1461 int lindex = acfg->objc_selector_index_2 ++;
1463 /* Emit ldr.imm/b */
1464 emit_bytes (acfg, code, 8);
1466 sprintf (symbol1, "L_OBJC_SELECTOR_%d", lindex);
1467 sprintf (symbol2, "L_OBJC_SELECTOR_REFERENCES_%d", index);
1469 emit_label (acfg, symbol1);
1470 mono_img_writer_emit_unset_mode (acfg->w);
1471 fprintf (acfg->fp, ".long %s-(%s+12)", symbol2, symbol1);
1474 #elif defined(TARGET_ARM64)
1475 arm64_emit_objc_selector_ref (acfg, code, index, code_size);
1477 g_assert_not_reached ();
1483 * arch_emit_plt_entry:
1485 * Emit code for the PLT entry.
1486 * The plt entry should look like this:
1487 * <indirect jump to GOT_SYMBOL + OFFSET>
1488 * <INFO_OFFSET embedded into the instruction stream>
1491 arch_emit_plt_entry (MonoAotCompile *acfg, const char *got_symbol, int offset, int info_offset)
1493 #if defined(TARGET_X86)
1494 #if defined(__default_codegen__)
1495 /* jmp *<offset>(%ebx) */
1496 emit_byte (acfg, 0xff);
1497 emit_byte (acfg, 0xa3);
1498 emit_int32 (acfg, offset);
1499 /* Used by mono_aot_get_plt_info_offset */
1500 emit_int32 (acfg, info_offset);
1501 #elif defined(__native_client_codegen__)
1502 const guint8 kSizeOfNaClJmp = 11;
1503 guint8 bytes[kSizeOfNaClJmp];
1504 guint8 *pbytes = &bytes[0];
1506 x86_jump_membase32 (pbytes, X86_EBX, offset);
1507 emit_bytes (acfg, bytes, kSizeOfNaClJmp);
1508 /* four bytes of data, used by mono_arch_patch_plt_entry */
1509 /* For Native Client, make this work with data embedded in push. */
1510 emit_byte (acfg, 0x68); /* hide data in a push */
1511 emit_int32 (acfg, info_offset);
1512 emit_alignment (acfg, AOT_FUNC_ALIGNMENT);
1513 #endif /*__native_client_codegen__*/
1514 #elif defined(TARGET_AMD64)
1515 #if defined(__default_codegen__)
1516 emit_unset_mode (acfg);
1517 fprintf (acfg->fp, "jmp *%s+%d(%%rip)\n", got_symbol, offset);
1518 /* Used by mono_aot_get_plt_info_offset */
1519 emit_int32 (acfg, info_offset);
1520 acfg->stats.plt_size += 10;
1521 #elif defined(__native_client_codegen__)
1523 guint8 *buf_aligned = ALIGN_TO(buf, kNaClAlignment);
1524 guint8 *code = buf_aligned;
1526 /* mov <OFFSET>(%rip), %r11d */
1527 emit_byte (acfg, '\x45');
1528 emit_byte (acfg, '\x8b');
1529 emit_byte (acfg, '\x1d');
1530 emit_symbol_diff (acfg, got_symbol, ".", offset - 4);
1532 amd64_jump_reg (code, AMD64_R11);
1533 /* This should be constant for the plt patch */
1534 g_assert ((size_t)(code-buf_aligned) == 10);
1535 emit_bytes (acfg, buf_aligned, code - buf_aligned);
1537 /* Hide data in a push imm32 so it passes validation */
1538 emit_byte (acfg, 0x68); /* push */
1539 emit_int32 (acfg, info_offset);
1540 emit_alignment (acfg, AOT_FUNC_ALIGNMENT);
1541 #endif /*__native_client_codegen__*/
1542 #elif defined(TARGET_ARM)
1547 ARM_LDR_IMM (code, ARMREG_IP, ARMREG_PC, 0);
1548 ARM_LDR_REG_REG (code, ARMREG_PC, ARMREG_PC, ARMREG_IP);
1549 emit_bytes (acfg, buf, code - buf);
1550 emit_symbol_diff (acfg, got_symbol, ".", offset - 4);
1551 /* Used by mono_aot_get_plt_info_offset */
1552 emit_int32 (acfg, info_offset);
1553 #elif defined(TARGET_ARM64)
1554 arm64_emit_plt_entry (acfg, got_symbol, offset, info_offset);
1555 #elif defined(TARGET_POWERPC)
1556 /* The GOT address is guaranteed to be in r30 by OP_LOAD_GOTADDR */
1557 emit_unset_mode (acfg);
1558 fprintf (acfg->fp, "lis 11, %d@h\n", offset);
1559 fprintf (acfg->fp, "ori 11, 11, %d@l\n", offset);
1560 fprintf (acfg->fp, "add 11, 11, 30\n");
1561 fprintf (acfg->fp, "%s 11, 0(11)\n", PPC_LD_OP);
1562 #ifdef PPC_USES_FUNCTION_DESCRIPTOR
1563 fprintf (acfg->fp, "%s 2, %d(11)\n", PPC_LD_OP, (int)sizeof (gpointer));
1564 fprintf (acfg->fp, "%s 11, 0(11)\n", PPC_LD_OP);
1566 fprintf (acfg->fp, "mtctr 11\n");
1567 fprintf (acfg->fp, "bctr\n");
1568 emit_int32 (acfg, info_offset);
1570 g_assert_not_reached ();
1575 * arch_emit_llvm_plt_entry:
1577 * Same as arch_emit_plt_entry, but handles calls from LLVM generated code.
1578 * This is only needed on arm to handle thumb interop.
1581 arch_emit_llvm_plt_entry (MonoAotCompile *acfg, const char *got_symbol, int offset, int info_offset)
1583 #if defined(TARGET_ARM)
1584 /* LLVM calls the PLT entries using bl, so these have to be thumb2 */
1585 /* The caller already transitioned to thumb */
1586 /* The code below should be 12 bytes long */
1587 /* clang has trouble encoding these instructions, so emit the binary */
1589 fprintf (acfg->fp, "ldr ip, [pc, #8]\n");
1590 /* thumb can't encode ld pc, [pc, ip] */
1591 fprintf (acfg->fp, "add ip, pc, ip\n");
1592 fprintf (acfg->fp, "ldr ip, [ip, #0]\n");
1593 fprintf (acfg->fp, "bx ip\n");
1595 emit_set_thumb_mode (acfg);
1596 fprintf (acfg->fp, ".4byte 0xc008f8df\n");
1597 fprintf (acfg->fp, ".2byte 0x44fc\n");
1598 fprintf (acfg->fp, ".4byte 0xc000f8dc\n");
1599 fprintf (acfg->fp, ".2byte 0x4760\n");
1600 emit_symbol_diff (acfg, got_symbol, ".", offset + 4);
1601 emit_int32 (acfg, info_offset);
1602 emit_unset_mode (acfg);
1603 emit_set_arm_mode (acfg);
1605 g_assert_not_reached ();
1609 /* Save unwind_info in the module and emit the offset to the information at symbol */
1610 static void save_unwind_info (MonoAotCompile *acfg, char *symbol, GSList *unwind_ops)
1612 guint32 uw_offset, encoded_len;
1615 emit_section_change (acfg, RODATA_SECT, 0);
1616 emit_global (acfg, symbol, FALSE);
1617 emit_label (acfg, symbol);
1619 encoded = mono_unwind_ops_encode (unwind_ops, &encoded_len);
1620 uw_offset = get_unwind_info_offset (acfg, encoded, encoded_len);
1622 emit_int32 (acfg, uw_offset);
1626 * arch_emit_specific_trampoline_pages:
1628 * Emits a page full of trampolines: each trampoline uses its own address to
1629 * lookup both the generic trampoline code and the data argument.
1630 * This page can be remapped in process multiple times so we can get an
1631 * unlimited number of trampolines.
1632 * Specifically this implementation uses the following trick: two memory pages
1633 * are allocated, with the first containing the data and the second containing the trampolines.
1634 * To reduce trampoline size, each trampoline jumps at the start of the page where a common
1635 * implementation does all the lifting.
1636 * Note that the ARM single trampoline size is 8 bytes, exactly like the data that needs to be stored
1637 * on the arm 32 bit system.
1640 arch_emit_specific_trampoline_pages (MonoAotCompile *acfg)
1642 #if defined(TARGET_ARM)
1645 guint8 *loop_start, *loop_branch_back, *loop_end_check, *imt_found_check;
1647 int pagesize = MONO_AOT_TRAMP_PAGE_SIZE;
1648 GSList *unwind_ops = NULL;
1649 #define COMMON_TRAMP_SIZE 16
1650 int count = (pagesize - COMMON_TRAMP_SIZE) / 8;
1651 int imm8, rot_amount;
1654 if (!acfg->aot_opts.use_trampolines_page)
1657 acfg->tramp_page_size = pagesize;
1659 sprintf (symbol, "%sspecific_trampolines_page", acfg->user_symbol_prefix);
1660 emit_alignment (acfg, pagesize);
1661 emit_global (acfg, symbol, TRUE);
1662 emit_label (acfg, symbol);
1664 /* emit the generic code first, the trampoline address + 8 is in the lr register */
1666 imm8 = mono_arm_is_rotated_imm8 (pagesize, &rot_amount);
1667 ARM_SUB_REG_IMM (code, ARMREG_LR, ARMREG_LR, imm8, rot_amount);
1668 ARM_LDR_IMM (code, ARMREG_R1, ARMREG_LR, -8);
1669 ARM_LDR_IMM (code, ARMREG_PC, ARMREG_LR, -4);
1671 g_assert (code - buf == COMMON_TRAMP_SIZE);
1674 emit_bytes (acfg, buf, code - buf);
1676 for (i = 0; i < count; ++i) {
1678 ARM_PUSH (code, 0x5fff);
1680 arm_patch (code - 4, code - COMMON_TRAMP_SIZE - 8 * (i + 1));
1681 g_assert (code - buf == 8);
1682 emit_bytes (acfg, buf, code - buf);
1685 /* now the rgctx trampolines: each specific trampolines puts in the ip register
1686 * the instruction pointer address, so the generic trampoline at the start of the page
1687 * subtracts 4096 to get to the data page and loads the values
1688 * We again fit the generic trampiline in 16 bytes.
1690 sprintf (symbol, "%srgctx_trampolines_page", acfg->user_symbol_prefix);
1691 emit_global (acfg, symbol, TRUE);
1692 emit_label (acfg, symbol);
1694 imm8 = mono_arm_is_rotated_imm8 (pagesize, &rot_amount);
1695 ARM_SUB_REG_IMM (code, ARMREG_IP, ARMREG_IP, imm8, rot_amount);
1696 ARM_LDR_IMM (code, MONO_ARCH_RGCTX_REG, ARMREG_IP, -8);
1697 ARM_LDR_IMM (code, ARMREG_PC, ARMREG_IP, -4);
1699 g_assert (code - buf == COMMON_TRAMP_SIZE);
1702 emit_bytes (acfg, buf, code - buf);
1704 for (i = 0; i < count; ++i) {
1706 ARM_MOV_REG_REG (code, ARMREG_IP, ARMREG_PC);
1708 arm_patch (code - 4, code - COMMON_TRAMP_SIZE - 8 * (i + 1));
1709 g_assert (code - buf == 8);
1710 emit_bytes (acfg, buf, code - buf);
1714 * gsharedvt arg trampolines: see arch_emit_gsharedvt_arg_trampoline ()
1716 sprintf (symbol, "%sgsharedvt_arg_trampolines_page", acfg->user_symbol_prefix);
1717 emit_global (acfg, symbol, TRUE);
1718 emit_label (acfg, symbol);
1720 ARM_PUSH (code, (1 << ARMREG_R0) | (1 << ARMREG_R1) | (1 << ARMREG_R2) | (1 << ARMREG_R3));
1721 imm8 = mono_arm_is_rotated_imm8 (pagesize, &rot_amount);
1722 ARM_SUB_REG_IMM (code, ARMREG_IP, ARMREG_IP, imm8, rot_amount);
1723 ARM_LDR_IMM (code, ARMREG_R0, ARMREG_IP, -8);
1724 ARM_LDR_IMM (code, ARMREG_PC, ARMREG_IP, -4);
1725 g_assert (code - buf == COMMON_TRAMP_SIZE);
1727 emit_bytes (acfg, buf, code - buf);
1729 for (i = 0; i < count; ++i) {
1731 ARM_MOV_REG_REG (code, ARMREG_IP, ARMREG_PC);
1733 arm_patch (code - 4, code - COMMON_TRAMP_SIZE - 8 * (i + 1));
1734 g_assert (code - buf == 8);
1735 emit_bytes (acfg, buf, code - buf);
1738 /* now the imt trampolines: each specific trampolines puts in the ip register
1739 * the instruction pointer address, so the generic trampoline at the start of the page
1740 * subtracts 4096 to get to the data page and loads the values
1742 #define IMT_TRAMP_SIZE 72
1743 sprintf (symbol, "%simt_trampolines_page", acfg->user_symbol_prefix);
1744 emit_global (acfg, symbol, TRUE);
1745 emit_label (acfg, symbol);
1747 /* Need at least two free registers, plus a slot for storing the pc */
1748 ARM_PUSH (code, (1 << ARMREG_R0)|(1 << ARMREG_R1)|(1 << ARMREG_R2));
1750 imm8 = mono_arm_is_rotated_imm8 (pagesize, &rot_amount);
1751 ARM_SUB_REG_IMM (code, ARMREG_IP, ARMREG_IP, imm8, rot_amount);
1752 ARM_LDR_IMM (code, ARMREG_R0, ARMREG_IP, -8);
1754 /* The IMT method is in v5, r0 has the imt array address */
1757 ARM_LDR_IMM (code, ARMREG_R1, ARMREG_R0, 0);
1758 ARM_CMP_REG_REG (code, ARMREG_R1, ARMREG_V5);
1759 imt_found_check = code;
1760 ARM_B_COND (code, ARMCOND_EQ, 0);
1762 /* End-of-loop check */
1763 ARM_CMP_REG_IMM (code, ARMREG_R1, 0, 0);
1764 loop_end_check = code;
1765 ARM_B_COND (code, ARMCOND_EQ, 0);
1768 ARM_ADD_REG_IMM8 (code, ARMREG_R0, ARMREG_R0, sizeof (gpointer) * 2);
1769 loop_branch_back = code;
1771 arm_patch (loop_branch_back, loop_start);
1774 arm_patch (imt_found_check, code);
1775 ARM_LDR_IMM (code, ARMREG_R0, ARMREG_R0, 4);
1776 ARM_LDR_IMM (code, ARMREG_R0, ARMREG_R0, 0);
1777 /* Save it to the third stack slot */
1778 ARM_STR_IMM (code, ARMREG_R0, ARMREG_SP, 8);
1779 /* Restore the registers and branch */
1780 ARM_POP (code, (1 << ARMREG_R0)|(1 << ARMREG_R1)|(1 << ARMREG_PC));
1783 arm_patch (loop_end_check, code);
1784 ARM_LDR_IMM (code, ARMREG_R0, ARMREG_R0, 4);
1785 ARM_STR_IMM (code, ARMREG_R0, ARMREG_SP, 8);
1786 ARM_POP (code, (1 << ARMREG_R0)|(1 << ARMREG_R1)|(1 << ARMREG_PC));
1790 g_assert (code - buf == IMT_TRAMP_SIZE);
1791 emit_bytes (acfg, buf, code - buf);
1793 for (i = 0; i < count; ++i) {
1795 ARM_MOV_REG_REG (code, ARMREG_IP, ARMREG_PC);
1797 arm_patch (code - 4, code - IMT_TRAMP_SIZE - 8 * (i + 1));
1798 g_assert (code - buf == 8);
1799 emit_bytes (acfg, buf, code - buf);
1802 acfg->tramp_page_code_offsets [MONO_AOT_TRAMP_SPECIFIC] = 16;
1803 acfg->tramp_page_code_offsets [MONO_AOT_TRAMP_STATIC_RGCTX] = 16;
1804 acfg->tramp_page_code_offsets [MONO_AOT_TRAMP_IMT_THUNK] = 72;
1805 acfg->tramp_page_code_offsets [MONO_AOT_TRAMP_GSHAREDVT_ARG] = 16;
1807 /* Unwind info for specifc trampolines */
1808 sprintf (symbol, "%sspecific_trampolines_page_gen_p", acfg->user_symbol_prefix);
1809 /* We unwind to the original caller, from the stack, since lr is clobbered */
1810 mono_add_unwind_op_def_cfa (unwind_ops, 0, 0, ARMREG_SP, 14 * sizeof (mgreg_t));
1811 mono_add_unwind_op_offset (unwind_ops, 0, 0, ARMREG_LR, -4);
1812 save_unwind_info (acfg, symbol, unwind_ops);
1813 mono_free_unwind_info (unwind_ops);
1815 sprintf (symbol, "%sspecific_trampolines_page_sp_p", acfg->user_symbol_prefix);
1816 mono_add_unwind_op_def_cfa (unwind_ops, 0, 0, ARMREG_SP, 0);
1817 mono_add_unwind_op_def_cfa_offset (unwind_ops, 4, 0, 14 * sizeof (mgreg_t));
1818 save_unwind_info (acfg, symbol, unwind_ops);
1819 mono_free_unwind_info (unwind_ops);
1821 /* Unwind info for rgctx trampolines */
1822 sprintf (symbol, "%srgctx_trampolines_page_gen_p", acfg->user_symbol_prefix);
1823 mono_add_unwind_op_def_cfa (unwind_ops, 0, 0, ARMREG_SP, 0);
1824 save_unwind_info (acfg, symbol, unwind_ops);
1826 sprintf (symbol, "%srgctx_trampolines_page_sp_p", acfg->user_symbol_prefix);
1827 save_unwind_info (acfg, symbol, unwind_ops);
1828 mono_free_unwind_info (unwind_ops);
1830 /* Unwind info for gsharedvt trampolines */
1831 sprintf (symbol, "%sgsharedvt_trampolines_page_gen_p", acfg->user_symbol_prefix);
1832 mono_add_unwind_op_def_cfa (unwind_ops, 0, 0, ARMREG_SP, 0);
1833 mono_add_unwind_op_def_cfa_offset (unwind_ops, 4, 0, 4 * sizeof (mgreg_t));
1834 save_unwind_info (acfg, symbol, unwind_ops);
1835 mono_free_unwind_info (unwind_ops);
1837 sprintf (symbol, "%sgsharedvt_trampolines_page_sp_p", acfg->user_symbol_prefix);
1838 mono_add_unwind_op_def_cfa (unwind_ops, 0, 0, ARMREG_SP, 0);
1839 save_unwind_info (acfg, symbol, unwind_ops);
1840 mono_free_unwind_info (unwind_ops);
1842 /* Unwind info for imt trampolines */
1843 sprintf (symbol, "%simt_trampolines_page_gen_p", acfg->user_symbol_prefix);
1844 mono_add_unwind_op_def_cfa (unwind_ops, 0, 0, ARMREG_SP, 0);
1845 mono_add_unwind_op_def_cfa_offset (unwind_ops, 4, 0, 3 * sizeof (mgreg_t));
1846 save_unwind_info (acfg, symbol, unwind_ops);
1847 mono_free_unwind_info (unwind_ops);
1849 sprintf (symbol, "%simt_trampolines_page_sp_p", acfg->user_symbol_prefix);
1850 mono_add_unwind_op_def_cfa (unwind_ops, 0, 0, ARMREG_SP, 0);
1851 save_unwind_info (acfg, symbol, unwind_ops);
1852 mono_free_unwind_info (unwind_ops);
1853 #elif defined(TARGET_ARM64)
1854 arm64_emit_specific_trampoline_pages (acfg);
1859 * arch_emit_specific_trampoline:
1861 * Emit code for a specific trampoline. OFFSET is the offset of the first of
1862 * two GOT slots which contain the generic trampoline address and the trampoline
1863 * argument. TRAMP_SIZE is set to the size of the emitted trampoline.
1866 arch_emit_specific_trampoline (MonoAotCompile *acfg, int offset, int *tramp_size)
1869 * The trampolines created here are variations of the specific
1870 * trampolines created in mono_arch_create_specific_trampoline (). The
1872 * - the generic trampoline address is taken from a got slot.
1873 * - the offset of the got slot where the trampoline argument is stored
1874 * is embedded in the instruction stream, and the generic trampoline
1875 * can load the argument by loading the offset, adding it to the
1876 * address of the trampoline to get the address of the got slot, and
1877 * loading the argument from there.
1878 * - all the trampolines should be of the same length.
1880 #if defined(TARGET_AMD64)
1881 #if defined(__default_codegen__)
1882 /* This should be exactly 8 bytes long */
1884 /* call *<offset>(%rip) */
1886 emit_unset_mode (acfg);
1887 fprintf (acfg->fp, "call *%s+%d(%%rip)\n", acfg->got_symbol, (int)(offset * sizeof (gpointer)));
1888 emit_zero_bytes (acfg, 2);
1890 emit_byte (acfg, '\x41');
1891 emit_byte (acfg, '\xff');
1892 emit_byte (acfg, '\x15');
1893 emit_symbol_diff (acfg, acfg->got_symbol, ".", (offset * sizeof (gpointer)) - 4);
1894 emit_zero_bytes (acfg, 1);
1896 #elif defined(__native_client_codegen__)
1898 guint8 *buf_aligned = ALIGN_TO(buf, kNaClAlignment);
1899 guint8 *code = buf_aligned;
1904 /* Emit this call in 'code' so we can find out how long it is. */
1905 amd64_call_reg (code, AMD64_R11);
1906 call_start = mono_arch_nacl_skip_nops (buf_aligned);
1907 call_len = code - call_start;
1909 /* The tramp_size is twice the NaCl alignment because it starts with */
1910 /* a call which needs to be aligned to the end of the boundary. */
1911 *tramp_size = kNaClAlignment*2;
1913 /* Emit nops to align call site below which is 7 bytes plus */
1914 /* the length of the call sequence emitted above. */
1915 /* Note: this requires the specific trampoline starts on a */
1916 /* kNaclAlignedment aligned address, which it does because */
1917 /* it's its own function that is aligned. */
1918 guint8 nop_buf[256];
1919 guint8 *nopbuf_aligned = ALIGN_TO (nop_buf, kNaClAlignment);
1920 guint8 *nopbuf_end = mono_arch_nacl_pad (nopbuf_aligned, kNaClAlignment - 7 - (call_len));
1921 emit_bytes (acfg, nopbuf_aligned, nopbuf_end - nopbuf_aligned);
1923 /* The trampoline is stored at the offset'th pointer, the -4 is */
1924 /* present because RIP relative addressing starts at the end of */
1925 /* the current instruction, while the label "." is relative to */
1926 /* the beginning of the current asm location, which in this case */
1927 /* is not the mov instruction, but the offset itself, due to the */
1928 /* way the bytes and ints are emitted here. */
1929 got_offset = (offset * sizeof(gpointer)) - 4;
1931 /* mov <OFFSET>(%rip), %r11d */
1932 emit_byte (acfg, '\x45');
1933 emit_byte (acfg, '\x8b');
1934 emit_byte (acfg, '\x1d');
1935 emit_symbol_diff (acfg, acfg->got_symbol, ".", got_offset);
1938 emit_bytes (acfg, call_start, call_len);
1940 /* The arg is stored at the offset+1 pointer, relative to beginning */
1941 /* of trampoline: 7 for mov, plus the call length, and 1 for push. */
1942 got_offset = ((offset + 1) * sizeof(gpointer)) + 7 + call_len + 1;
1944 /* We can't emit this data directly, hide in a "push imm32" */
1945 emit_byte (acfg, '\x68'); /* push */
1946 emit_symbol_diff (acfg, acfg->got_symbol, ".", got_offset);
1947 emit_alignment (acfg, kNaClAlignment);
1948 #endif /*__native_client_codegen__*/
1949 #elif defined(TARGET_ARM)
1953 /* This should be exactly 20 bytes long */
1956 ARM_PUSH (code, 0x5fff);
1957 ARM_LDR_IMM (code, ARMREG_R1, ARMREG_PC, 4);
1958 /* Load the value from the GOT */
1959 ARM_LDR_REG_REG (code, ARMREG_R1, ARMREG_PC, ARMREG_R1);
1961 ARM_BLX_REG (code, ARMREG_R1);
1963 g_assert (code - buf == 16);
1966 emit_bytes (acfg, buf, code - buf);
1968 * Only one offset is needed, since the second one would be equal to the
1971 emit_symbol_diff (acfg, acfg->got_symbol, ".", (offset * sizeof (gpointer)) - 4 + 4);
1972 //emit_symbol_diff (acfg, acfg->got_symbol, ".", ((offset + 1) * sizeof (gpointer)) - 4 + 8);
1973 #elif defined(TARGET_ARM64)
1974 arm64_emit_specific_trampoline (acfg, offset, tramp_size);
1975 #elif defined(TARGET_POWERPC)
1983 * PPC has no ip relative addressing, so we need to compute the address
1984 * of the mscorlib got. That is slow and complex, so instead, we store it
1985 * in the second got slot of every aot image. The caller already computed
1986 * the address of its got and placed it into r30.
1988 emit_unset_mode (acfg);
1989 /* Load mscorlib got address */
1990 fprintf (acfg->fp, "%s 0, %d(30)\n", PPC_LD_OP, (int)sizeof (gpointer));
1991 /* Load generic trampoline address */
1992 fprintf (acfg->fp, "lis 11, %d@h\n", (int)(offset * sizeof (gpointer)));
1993 fprintf (acfg->fp, "ori 11, 11, %d@l\n", (int)(offset * sizeof (gpointer)));
1994 fprintf (acfg->fp, "%s 11, 11, 0\n", PPC_LDX_OP);
1995 #ifdef PPC_USES_FUNCTION_DESCRIPTOR
1996 fprintf (acfg->fp, "%s 11, 0(11)\n", PPC_LD_OP);
1998 fprintf (acfg->fp, "mtctr 11\n");
1999 /* Load trampoline argument */
2000 /* On ppc, we pass it normally to the generic trampoline */
2001 fprintf (acfg->fp, "lis 11, %d@h\n", (int)((offset + 1) * sizeof (gpointer)));
2002 fprintf (acfg->fp, "ori 11, 11, %d@l\n", (int)((offset + 1) * sizeof (gpointer)));
2003 fprintf (acfg->fp, "%s 0, 11, 0\n", PPC_LDX_OP);
2004 /* Branch to generic trampoline */
2005 fprintf (acfg->fp, "bctr\n");
2007 #ifdef PPC_USES_FUNCTION_DESCRIPTOR
2008 *tramp_size = 10 * 4;
2010 *tramp_size = 9 * 4;
2012 #elif defined(TARGET_X86)
2016 /* Similar to the PPC code above */
2018 /* FIXME: Could this clobber the register needed by get_vcall_slot () ? */
2021 /* Load mscorlib got address */
2022 x86_mov_reg_membase (code, X86_ECX, MONO_ARCH_GOT_REG, sizeof (gpointer), 4);
2023 /* Push trampoline argument */
2024 x86_push_membase (code, X86_ECX, (offset + 1) * sizeof (gpointer));
2025 /* Load generic trampoline address */
2026 x86_mov_reg_membase (code, X86_ECX, X86_ECX, offset * sizeof (gpointer), 4);
2027 /* Branch to generic trampoline */
2028 x86_jump_reg (code, X86_ECX);
2030 #ifdef __native_client_codegen__
2032 /* emit nops to next 32 byte alignment */
2033 int a = (~kNaClAlignmentMask) & ((code - buf) + kNaClAlignment - 1);
2034 while (code < (buf + a)) x86_nop(code);
2037 emit_bytes (acfg, buf, code - buf);
2039 *tramp_size = NACL_SIZE(17, kNaClAlignment);
2040 g_assert (code - buf == *tramp_size);
2042 g_assert_not_reached ();
2047 * arch_emit_unbox_trampoline:
2049 * Emit code for the unbox trampoline for METHOD used in the full-aot case.
2050 * CALL_TARGET is the symbol pointing to the native code of METHOD.
2053 arch_emit_unbox_trampoline (MonoAotCompile *acfg, MonoCompile *cfg, MonoMethod *method, const char *call_target)
2055 #if defined(TARGET_AMD64)
2060 this_reg = mono_arch_get_this_arg_reg (NULL);
2062 amd64_alu_reg_imm (code, X86_ADD, this_reg, sizeof (MonoObject));
2064 emit_bytes (acfg, buf, code - buf);
2067 emit_unset_mode (acfg);
2068 fprintf (acfg->fp, "jmp %s\n", call_target);
2070 emit_byte (acfg, '\xe9');
2071 emit_symbol_diff (acfg, call_target, ".", -4);
2073 #elif defined(TARGET_X86)
2080 x86_alu_membase_imm (code, X86_ADD, X86_ESP, this_pos, sizeof (MonoObject));
2082 emit_bytes (acfg, buf, code - buf);
2085 emit_byte (acfg, '\xe9');
2086 emit_symbol_diff (acfg, call_target, ".", -4);
2087 #elif defined(TARGET_ARM)
2091 if (acfg->thumb_mixed && cfg->compile_llvm) {
2092 fprintf (acfg->fp, "add r0, r0, #%d\n", (int)sizeof (MonoObject));
2093 fprintf (acfg->fp, "b %s\n", call_target);
2094 fprintf (acfg->fp, ".arm\n");
2095 fprintf (acfg->fp, ".align 2\n");
2101 ARM_ADD_REG_IMM8 (code, ARMREG_R0, ARMREG_R0, sizeof (MonoObject));
2103 emit_bytes (acfg, buf, code - buf);
2104 /* jump to method */
2105 if (acfg->thumb_mixed && cfg->compile_llvm)
2106 fprintf (acfg->fp, "\n\tbx %s\n", call_target);
2108 fprintf (acfg->fp, "\n\tb %s\n", call_target);
2109 #elif defined(TARGET_ARM64)
2110 arm64_emit_unbox_trampoline (acfg, cfg, method, call_target);
2111 #elif defined(TARGET_POWERPC)
2114 fprintf (acfg->fp, "\n\taddi %d, %d, %d\n", this_pos, this_pos, (int)sizeof (MonoObject));
2115 fprintf (acfg->fp, "\n\tb %s\n", call_target);
2117 g_assert_not_reached ();
2122 * arch_emit_static_rgctx_trampoline:
2124 * Emit code for a static rgctx trampoline. OFFSET is the offset of the first of
2125 * two GOT slots which contain the rgctx argument, and the method to jump to.
2126 * TRAMP_SIZE is set to the size of the emitted trampoline.
2127 * These kinds of trampolines cannot be enumerated statically, since there could
2128 * be one trampoline per method instantiation, so we emit the same code for all
2129 * trampolines, and parameterize them using two GOT slots.
2132 arch_emit_static_rgctx_trampoline (MonoAotCompile *acfg, int offset, int *tramp_size)
2134 #if defined(TARGET_AMD64)
2135 #if defined(__default_codegen__)
2136 /* This should be exactly 13 bytes long */
2140 emit_unset_mode (acfg);
2141 fprintf (acfg->fp, "mov %s+%d(%%rip), %%r10\n", acfg->got_symbol, (int)(offset * sizeof (gpointer)));
2142 fprintf (acfg->fp, "jmp *%s+%d(%%rip)\n", acfg->got_symbol, (int)((offset + 1) * sizeof (gpointer)));
2144 /* mov <OFFSET>(%rip), %r10 */
2145 emit_byte (acfg, '\x4d');
2146 emit_byte (acfg, '\x8b');
2147 emit_byte (acfg, '\x15');
2148 emit_symbol_diff (acfg, acfg->got_symbol, ".", (offset * sizeof (gpointer)) - 4);
2150 /* jmp *<offset>(%rip) */
2151 emit_byte (acfg, '\xff');
2152 emit_byte (acfg, '\x25');
2153 emit_symbol_diff (acfg, acfg->got_symbol, ".", ((offset + 1) * sizeof (gpointer)) - 4);
2155 #elif defined(__native_client_codegen__)
2157 guint8 *buf_aligned = ALIGN_TO(buf, kNaClAlignment);
2158 guint8 *code = buf_aligned;
2160 /* mov <OFFSET>(%rip), %r10d */
2161 emit_byte (acfg, '\x45');
2162 emit_byte (acfg, '\x8b');
2163 emit_byte (acfg, '\x15');
2164 emit_symbol_diff (acfg, acfg->got_symbol, ".", (offset * sizeof (gpointer)) - 4);
2166 /* mov <OFFSET>(%rip), %r11d */
2167 emit_byte (acfg, '\x45');
2168 emit_byte (acfg, '\x8b');
2169 emit_byte (acfg, '\x1d');
2170 emit_symbol_diff (acfg, acfg->got_symbol, ".", ((offset + 1) * sizeof (gpointer)) - 4);
2173 amd64_jump_reg (code, AMD64_R11);
2174 emit_bytes (acfg, buf_aligned, code - buf_aligned);
2176 emit_alignment (acfg, kNaClAlignment);
2177 *tramp_size = kNaClAlignment;
2178 #endif /*__native_client_codegen__*/
2180 #elif defined(TARGET_ARM)
2184 /* This should be exactly 24 bytes long */
2187 /* Load rgctx value */
2188 ARM_LDR_IMM (code, ARMREG_IP, ARMREG_PC, 8);
2189 ARM_LDR_REG_REG (code, MONO_ARCH_RGCTX_REG, ARMREG_PC, ARMREG_IP);
2190 /* Load branch addr + branch */
2191 ARM_LDR_IMM (code, ARMREG_IP, ARMREG_PC, 4);
2192 ARM_LDR_REG_REG (code, ARMREG_PC, ARMREG_PC, ARMREG_IP);
2194 g_assert (code - buf == 16);
2197 emit_bytes (acfg, buf, code - buf);
2198 emit_symbol_diff (acfg, acfg->got_symbol, ".", (offset * sizeof (gpointer)) - 4 + 8);
2199 emit_symbol_diff (acfg, acfg->got_symbol, ".", ((offset + 1) * sizeof (gpointer)) - 4 + 4);
2200 #elif defined(TARGET_ARM64)
2201 arm64_emit_static_rgctx_trampoline (acfg, offset, tramp_size);
2202 #elif defined(TARGET_POWERPC)
2210 * PPC has no ip relative addressing, so we need to compute the address
2211 * of the mscorlib got. That is slow and complex, so instead, we store it
2212 * in the second got slot of every aot image. The caller already computed
2213 * the address of its got and placed it into r30.
2215 emit_unset_mode (acfg);
2216 /* Load mscorlib got address */
2217 fprintf (acfg->fp, "%s 0, %d(30)\n", PPC_LD_OP, (int)sizeof (gpointer));
2219 fprintf (acfg->fp, "lis 11, %d@h\n", (int)(offset * sizeof (gpointer)));
2220 fprintf (acfg->fp, "ori 11, 11, %d@l\n", (int)(offset * sizeof (gpointer)));
2221 fprintf (acfg->fp, "%s %d, 11, 0\n", PPC_LDX_OP, MONO_ARCH_RGCTX_REG);
2222 /* Load target address */
2223 fprintf (acfg->fp, "lis 11, %d@h\n", (int)((offset + 1) * sizeof (gpointer)));
2224 fprintf (acfg->fp, "ori 11, 11, %d@l\n", (int)((offset + 1) * sizeof (gpointer)));
2225 fprintf (acfg->fp, "%s 11, 11, 0\n", PPC_LDX_OP);
2226 #ifdef PPC_USES_FUNCTION_DESCRIPTOR
2227 fprintf (acfg->fp, "%s 2, %d(11)\n", PPC_LD_OP, (int)sizeof (gpointer));
2228 fprintf (acfg->fp, "%s 11, 0(11)\n", PPC_LD_OP);
2230 fprintf (acfg->fp, "mtctr 11\n");
2231 /* Branch to the target address */
2232 fprintf (acfg->fp, "bctr\n");
2234 #ifdef PPC_USES_FUNCTION_DESCRIPTOR
2235 *tramp_size = 11 * 4;
2237 *tramp_size = 9 * 4;
2240 #elif defined(TARGET_X86)
2244 /* Similar to the PPC code above */
2246 g_assert (MONO_ARCH_RGCTX_REG != X86_ECX);
2249 /* Load mscorlib got address */
2250 x86_mov_reg_membase (code, X86_ECX, MONO_ARCH_GOT_REG, sizeof (gpointer), 4);
2252 x86_mov_reg_membase (code, MONO_ARCH_RGCTX_REG, X86_ECX, offset * sizeof (gpointer), 4);
2253 /* Branch to the target address */
2254 x86_jump_membase (code, X86_ECX, (offset + 1) * sizeof (gpointer));
2256 #ifdef __native_client_codegen__
2258 /* emit nops to next 32 byte alignment */
2259 int a = (~kNaClAlignmentMask) & ((code - buf) + kNaClAlignment - 1);
2260 while (code < (buf + a)) x86_nop(code);
2264 emit_bytes (acfg, buf, code - buf);
2266 *tramp_size = NACL_SIZE (15, kNaClAlignment);
2267 g_assert (code - buf == *tramp_size);
2269 g_assert_not_reached ();
2274 * arch_emit_imt_thunk:
2276 * Emit an IMT thunk usable in full-aot mode. The thunk uses 1 got slot which
2277 * points to an array of pointer pairs. The pairs of the form [key, ptr], where
2278 * key is the IMT key, and ptr holds the address of a memory location holding
2279 * the address to branch to if the IMT arg matches the key. The array is
2280 * terminated by a pair whose key is NULL, and whose ptr is the address of the
2282 * TRAMP_SIZE is set to the size of the emitted trampoline.
2285 arch_emit_imt_thunk (MonoAotCompile *acfg, int offset, int *tramp_size)
2287 #if defined(TARGET_AMD64)
2289 #if defined(__native_client_codegen__)
2292 guint8 *labels [16];
2294 guint8 *mov_buf_ptr = mov_buf;
2296 const int kSizeOfMove = 7;
2297 #if defined(__default_codegen__)
2298 code = buf = (guint8 *)g_malloc (256);
2299 #elif defined(__native_client_codegen__)
2300 buf_alloc = g_malloc (256 + kNaClAlignment + kSizeOfMove);
2301 buf = ((guint)buf_alloc + kNaClAlignment) & ~kNaClAlignmentMask;
2302 /* The RIP relative move below is emitted first */
2307 /* FIXME: Optimize this, i.e. use binary search etc. */
2308 /* Maybe move the body into a separate function (slower, but much smaller) */
2310 /* MONO_ARCH_IMT_SCRATCH_REG is a free register */
2313 emit_unset_mode (acfg);
2314 fprintf (acfg->fp, "mov %s+%d(%%rip), %s\n", acfg->got_symbol, (int)(offset * sizeof (gpointer)), mono_arch_regname (MONO_ARCH_IMT_SCRATCH_REG));
2318 amd64_alu_membase_imm (code, X86_CMP, MONO_ARCH_IMT_SCRATCH_REG, 0, 0);
2320 amd64_branch8 (code, X86_CC_Z, 0, FALSE);
2323 amd64_alu_membase_reg_size (code, X86_CMP, MONO_ARCH_IMT_SCRATCH_REG, 0, MONO_ARCH_IMT_REG, sizeof (gpointer));
2325 amd64_branch8 (code, X86_CC_Z, 0, FALSE);
2328 amd64_alu_reg_imm (code, X86_ADD, MONO_ARCH_IMT_SCRATCH_REG, 2 * sizeof (gpointer));
2329 amd64_jump_code (code, labels [0]);
2332 mono_amd64_patch (labels [2], code);
2333 amd64_mov_reg_membase (code, MONO_ARCH_IMT_SCRATCH_REG, MONO_ARCH_IMT_SCRATCH_REG, sizeof (gpointer), sizeof (gpointer));
2334 amd64_jump_membase (code, MONO_ARCH_IMT_SCRATCH_REG, 0);
2337 mono_amd64_patch (labels [1], code);
2338 /* Load fail tramp */
2339 amd64_alu_reg_imm (code, X86_ADD, MONO_ARCH_IMT_SCRATCH_REG, sizeof (gpointer));
2340 /* Check if there is a fail tramp */
2341 amd64_alu_membase_imm (code, X86_CMP, MONO_ARCH_IMT_SCRATCH_REG, 0, 0);
2343 amd64_branch8 (code, X86_CC_Z, 0, FALSE);
2344 /* Jump to fail tramp */
2345 amd64_jump_membase (code, MONO_ARCH_IMT_SCRATCH_REG, 0);
2348 mono_amd64_patch (labels [3], code);
2349 x86_breakpoint (code);
2352 /* mov <OFFSET>(%rip), MONO_ARCH_IMT_SCRATCH_REG */
2353 amd64_emit_rex (mov_buf_ptr, sizeof(gpointer), MONO_ARCH_IMT_SCRATCH_REG, 0, AMD64_RIP);
2354 *(mov_buf_ptr)++ = (unsigned char)0x8b; /* mov opcode */
2355 x86_address_byte (mov_buf_ptr, 0, MONO_ARCH_IMT_SCRATCH_REG & 0x7, 5);
2356 emit_bytes (acfg, mov_buf, mov_buf_ptr - mov_buf);
2357 emit_symbol_diff (acfg, acfg->got_symbol, ".", (offset * sizeof (gpointer)) - 4);
2359 emit_bytes (acfg, buf, code - buf);
2361 *tramp_size = code - buf + kSizeOfMove;
2362 #if defined(__native_client_codegen__)
2363 /* The tramp will be padded to the next kNaClAlignment bundle. */
2364 *tramp_size = ALIGN_TO ((*tramp_size), kNaClAlignment);
2367 #if defined(__default_codegen__)
2369 #elif defined(__native_client_codegen__)
2373 #elif defined(TARGET_X86)
2375 #ifdef __native_client_codegen__
2378 guint8 *labels [16];
2380 #if defined(__default_codegen__)
2381 code = buf = g_malloc (256);
2382 #elif defined(__native_client_codegen__)
2383 buf_alloc = g_malloc (256 + kNaClAlignment);
2384 code = buf = ((guint)buf_alloc + kNaClAlignment) & ~kNaClAlignmentMask;
2387 /* Allocate a temporary stack slot */
2388 x86_push_reg (code, X86_EAX);
2390 x86_push_reg (code, X86_EAX);
2392 /* Load mscorlib got address */
2393 x86_mov_reg_membase (code, X86_EAX, MONO_ARCH_GOT_REG, sizeof (gpointer), 4);
2395 x86_mov_reg_membase (code, X86_EAX, X86_EAX, offset * sizeof (gpointer), 4);
2398 x86_alu_membase_imm (code, X86_CMP, X86_EAX, 0, 0);
2400 x86_branch8 (code, X86_CC_Z, FALSE, 0);
2403 x86_alu_membase_reg (code, X86_CMP, X86_EAX, 0, MONO_ARCH_IMT_REG);
2405 x86_branch8 (code, X86_CC_Z, FALSE, 0);
2408 x86_alu_reg_imm (code, X86_ADD, X86_EAX, 2 * sizeof (gpointer));
2409 x86_jump_code (code, labels [0]);
2412 mono_x86_patch (labels [2], code);
2413 x86_mov_reg_membase (code, X86_EAX, X86_EAX, sizeof (gpointer), 4);
2414 x86_mov_reg_membase (code, X86_EAX, X86_EAX, 0, 4);
2415 /* Save the target address to the temporary stack location */
2416 x86_mov_membase_reg (code, X86_ESP, 4, X86_EAX, 4);
2418 x86_pop_reg (code, X86_EAX);
2419 /* Jump to the target address */
2423 mono_x86_patch (labels [1], code);
2424 /* Load fail tramp */
2425 x86_mov_reg_membase (code, X86_EAX, X86_EAX, sizeof (gpointer), 4);
2426 x86_alu_membase_imm (code, X86_CMP, X86_EAX, 0, 0);
2428 x86_branch8 (code, X86_CC_Z, FALSE, 0);
2429 /* Jump to fail tramp */
2430 x86_mov_membase_reg (code, X86_ESP, 4, X86_EAX, 4);
2431 x86_pop_reg (code, X86_EAX);
2435 mono_x86_patch (labels [3], code);
2436 x86_breakpoint (code);
2438 #ifdef __native_client_codegen__
2440 /* emit nops to next 32 byte alignment */
2441 int a = (~kNaClAlignmentMask) & ((code - buf) + kNaClAlignment - 1);
2442 while (code < (buf + a)) x86_nop(code);
2445 emit_bytes (acfg, buf, code - buf);
2447 *tramp_size = code - buf;
2449 #if defined(__default_codegen__)
2451 #elif defined(__native_client_codegen__)
2455 #elif defined(TARGET_ARM)
2457 guint8 *code, *code2, *labels [16];
2461 /* The IMT method is in v5 */
2463 /* Need at least two free registers, plus a slot for storing the pc */
2464 ARM_PUSH (code, (1 << ARMREG_R0)|(1 << ARMREG_R1)|(1 << ARMREG_R2));
2466 /* Load the parameter from the GOT */
2467 ARM_LDR_IMM (code, ARMREG_R0, ARMREG_PC, 0);
2468 ARM_LDR_REG_REG (code, ARMREG_R0, ARMREG_PC, ARMREG_R0);
2471 ARM_LDR_IMM (code, ARMREG_R1, ARMREG_R0, 0);
2472 ARM_CMP_REG_REG (code, ARMREG_R1, ARMREG_V5);
2474 ARM_B_COND (code, ARMCOND_EQ, 0);
2476 /* End-of-loop check */
2477 ARM_CMP_REG_IMM (code, ARMREG_R1, 0, 0);
2479 ARM_B_COND (code, ARMCOND_EQ, 0);
2482 ARM_ADD_REG_IMM8 (code, ARMREG_R0, ARMREG_R0, sizeof (gpointer) * 2);
2485 arm_patch (labels [4], labels [1]);
2488 arm_patch (labels [2], code);
2489 ARM_LDR_IMM (code, ARMREG_R0, ARMREG_R0, 4);
2490 ARM_LDR_IMM (code, ARMREG_R0, ARMREG_R0, 0);
2491 /* Save it to the third stack slot */
2492 ARM_STR_IMM (code, ARMREG_R0, ARMREG_SP, 8);
2493 /* Restore the registers and branch */
2494 ARM_POP (code, (1 << ARMREG_R0)|(1 << ARMREG_R1)|(1 << ARMREG_PC));
2497 arm_patch (labels [3], code);
2498 ARM_LDR_IMM (code, ARMREG_R0, ARMREG_R0, 4);
2499 ARM_STR_IMM (code, ARMREG_R0, ARMREG_SP, 8);
2500 ARM_POP (code, (1 << ARMREG_R0)|(1 << ARMREG_R1)|(1 << ARMREG_PC));
2504 ARM_LDR_IMM (code2, ARMREG_R0, ARMREG_PC, (code - (labels [0] + 8)));
2506 emit_bytes (acfg, buf, code - buf);
2507 emit_symbol_diff (acfg, acfg->got_symbol, ".", (offset * sizeof (gpointer)) + (code - (labels [0] + 8)) - 4);
2509 *tramp_size = code - buf + 4;
2510 #elif defined(TARGET_ARM64)
2511 arm64_emit_imt_thunk (acfg, offset, tramp_size);
2512 #elif defined(TARGET_POWERPC)
2514 guint8 *code, *labels [16];
2518 /* Load the mscorlib got address */
2519 ppc_ldptr (code, ppc_r12, sizeof (gpointer), ppc_r30);
2520 /* Load the parameter from the GOT */
2521 ppc_load (code, ppc_r0, offset * sizeof (gpointer));
2522 ppc_ldptr_indexed (code, ppc_r12, ppc_r12, ppc_r0);
2524 /* Load and check key */
2526 ppc_ldptr (code, ppc_r0, 0, ppc_r12);
2527 ppc_cmp (code, 0, sizeof (gpointer) == 8 ? 1 : 0, ppc_r0, MONO_ARCH_IMT_REG);
2529 ppc_bc (code, PPC_BR_TRUE, PPC_BR_EQ, 0);
2531 /* End-of-loop check */
2532 ppc_cmpi (code, 0, sizeof (gpointer) == 8 ? 1 : 0, ppc_r0, 0);
2534 ppc_bc (code, PPC_BR_TRUE, PPC_BR_EQ, 0);
2537 ppc_addi (code, ppc_r12, ppc_r12, 2 * sizeof (gpointer));
2540 mono_ppc_patch (labels [4], labels [1]);
2543 mono_ppc_patch (labels [2], code);
2544 ppc_ldptr (code, ppc_r12, sizeof (gpointer), ppc_r12);
2545 /* r12 now contains the value of the vtable slot */
2546 /* this is not a function descriptor on ppc64 */
2547 ppc_ldptr (code, ppc_r12, 0, ppc_r12);
2548 ppc_mtctr (code, ppc_r12);
2549 ppc_bcctr (code, PPC_BR_ALWAYS, 0);
2552 mono_ppc_patch (labels [3], code);
2556 *tramp_size = code - buf;
2558 emit_bytes (acfg, buf, code - buf);
2560 g_assert_not_reached ();
2565 #if defined (TARGET_AMD64)
2568 amd64_emit_load_got_slot (MonoAotCompile *acfg, int dreg, int got_slot)
2571 g_assert (acfg->fp);
2572 emit_unset_mode (acfg);
2574 fprintf (acfg->fp, "mov %s+%d(%%rip), %s\n", acfg->got_symbol, (unsigned int) ((got_slot * sizeof (gpointer))), mono_arch_regname (dreg));
2581 * arch_emit_gsharedvt_arg_trampoline:
2583 * Emit code for a gsharedvt arg trampoline. OFFSET is the offset of the first of
2584 * two GOT slots which contain the argument, and the code to jump to.
2585 * TRAMP_SIZE is set to the size of the emitted trampoline.
2586 * These kinds of trampolines cannot be enumerated statically, since there could
2587 * be one trampoline per method instantiation, so we emit the same code for all
2588 * trampolines, and parameterize them using two GOT slots.
2591 arch_emit_gsharedvt_arg_trampoline (MonoAotCompile *acfg, int offset, int *tramp_size)
2593 #if defined(TARGET_X86)
2597 /* Similar to the PPC code above */
2599 g_assert (MONO_ARCH_RGCTX_REG != X86_ECX);
2602 /* Load mscorlib got address */
2603 x86_mov_reg_membase (code, X86_ECX, MONO_ARCH_GOT_REG, sizeof (gpointer), 4);
2605 x86_mov_reg_membase (code, X86_EAX, X86_ECX, offset * sizeof (gpointer), 4);
2606 /* Branch to the target address */
2607 x86_jump_membase (code, X86_ECX, (offset + 1) * sizeof (gpointer));
2609 #ifdef __native_client_codegen__
2611 /* emit nops to next 32 byte alignment */
2612 int a = (~kNaClAlignmentMask) & ((code - buf) + kNaClAlignment - 1);
2613 while (code < (buf + a)) x86_nop(code);
2617 emit_bytes (acfg, buf, code - buf);
2619 *tramp_size = NACL_SIZE (15, kNaClAlignment);
2620 g_assert (code - buf == *tramp_size);
2621 #elif defined(TARGET_ARM)
2625 /* The same as mono_arch_get_gsharedvt_arg_trampoline (), but for AOT */
2626 /* Similar to arch_emit_specific_trampoline () */
2629 ARM_PUSH (code, (1 << ARMREG_R0) | (1 << ARMREG_R1) | (1 << ARMREG_R2) | (1 << ARMREG_R3));
2630 ARM_LDR_IMM (code, ARMREG_R1, ARMREG_PC, 8);
2631 /* Load the arg value from the GOT */
2632 ARM_LDR_REG_REG (code, ARMREG_R0, ARMREG_PC, ARMREG_R1);
2633 /* Load the addr from the GOT */
2634 ARM_LDR_REG_REG (code, ARMREG_R1, ARMREG_PC, ARMREG_R1);
2636 ARM_BX (code, ARMREG_R1);
2638 g_assert (code - buf == 20);
2641 emit_bytes (acfg, buf, code - buf);
2642 emit_symbol_diff (acfg, acfg->got_symbol, ".", (offset * sizeof (gpointer)) + 4);
2643 #elif defined(TARGET_ARM64)
2644 arm64_emit_gsharedvt_arg_trampoline (acfg, offset, tramp_size);
2645 #elif defined (TARGET_AMD64)
2647 amd64_emit_load_got_slot (acfg, AMD64_RAX, offset);
2648 amd64_emit_load_got_slot (acfg, MONO_ARCH_IMT_SCRATCH_REG, offset + 1);
2649 g_assert (AMD64_R11 == MONO_ARCH_IMT_SCRATCH_REG);
2650 fprintf (acfg->fp, "jmp *%%r11\n");
2654 g_assert_not_reached ();
2658 /* END OF ARCH SPECIFIC CODE */
2661 mono_get_field_token (MonoClassField *field)
2663 MonoClass *klass = field->parent;
2666 for (i = 0; i < klass->field.count; ++i) {
2667 if (field == &klass->fields [i])
2668 return MONO_TOKEN_FIELD_DEF | (klass->field.first + 1 + i);
2671 g_assert_not_reached ();
2676 encode_value (gint32 value, guint8 *buf, guint8 **endbuf)
2680 //printf ("ENCODE: %d 0x%x.\n", value, value);
2683 * Same encoding as the one used in the metadata, extended to handle values
2684 * greater than 0x1fffffff.
2686 if ((value >= 0) && (value <= 127))
2688 else if ((value >= 0) && (value <= 16383)) {
2689 p [0] = 0x80 | (value >> 8);
2690 p [1] = value & 0xff;
2692 } else if ((value >= 0) && (value <= 0x1fffffff)) {
2693 p [0] = (value >> 24) | 0xc0;
2694 p [1] = (value >> 16) & 0xff;
2695 p [2] = (value >> 8) & 0xff;
2696 p [3] = value & 0xff;
2701 p [1] = (value >> 24) & 0xff;
2702 p [2] = (value >> 16) & 0xff;
2703 p [3] = (value >> 8) & 0xff;
2704 p [4] = value & 0xff;
2712 stream_init (MonoDynamicStream *sh)
2715 sh->alloc_size = 4096;
2716 sh->data = (char *)g_malloc (4096);
2718 /* So offsets are > 0 */
2724 make_room_in_stream (MonoDynamicStream *stream, int size)
2726 if (size <= stream->alloc_size)
2729 while (stream->alloc_size <= size) {
2730 if (stream->alloc_size < 4096)
2731 stream->alloc_size = 4096;
2733 stream->alloc_size *= 2;
2736 stream->data = (char *)g_realloc (stream->data, stream->alloc_size);
2740 add_stream_data (MonoDynamicStream *stream, const char *data, guint32 len)
2744 make_room_in_stream (stream, stream->index + len);
2745 memcpy (stream->data + stream->index, data, len);
2746 idx = stream->index;
2747 stream->index += len;
2754 * Add data to the binary blob inside the aot image. Returns the offset inside the
2755 * blob where the data was stored.
2758 add_to_blob (MonoAotCompile *acfg, const guint8 *data, guint32 data_len)
2760 g_assert (!acfg->blob_closed);
2762 if (acfg->blob.alloc_size == 0)
2763 stream_init (&acfg->blob);
2765 return add_stream_data (&acfg->blob, (char*)data, data_len);
2769 add_to_blob_aligned (MonoAotCompile *acfg, const guint8 *data, guint32 data_len, guint32 align)
2774 if (acfg->blob.alloc_size == 0)
2775 stream_init (&acfg->blob);
2777 count = acfg->blob.index % align;
2779 /* we assume the stream data will be aligned */
2781 add_stream_data (&acfg->blob, buf, 4 - count);
2783 return add_stream_data (&acfg->blob, (char*)data, data_len);
2786 /* Emit a table of data into the aot image */
2788 emit_aot_data (MonoAotCompile *acfg, MonoAotFileTable table, const char *symbol, guint8 *data, int size)
2790 if (acfg->data_outfile) {
2791 acfg->table_offsets [(int)table] = acfg->datafile_offset;
2792 fwrite (data,1, size, acfg->data_outfile);
2793 acfg->datafile_offset += size;
2794 // align the data to 8 bytes. Put zeros in the file (so that every build results in consistent output).
2795 int align = 8 - size % 8;
2796 acfg->datafile_offset += align;
2797 guint8 align_buf [16];
2798 memset (&align_buf, 0, sizeof (align_buf));
2799 fwrite (align_buf, align, 1, acfg->data_outfile);
2800 } else if (acfg->llvm) {
2801 mono_llvm_emit_aot_data (symbol, data, size);
2803 emit_section_change (acfg, RODATA_SECT, 0);
2804 emit_alignment (acfg, 8);
2805 emit_label (acfg, symbol);
2806 emit_bytes (acfg, data, size);
2811 * emit_offset_table:
2813 * Emit a table of increasing offsets in a compact form using differential encoding.
2814 * There is an index entry for each GROUP_SIZE number of entries. The greater the
2815 * group size, the more compact the table becomes, but the slower it becomes to compute
2816 * a given entry. Returns the size of the table.
2819 emit_offset_table (MonoAotCompile *acfg, const char *symbol, MonoAotFileTable table, int noffsets, int group_size, gint32 *offsets)
2821 gint32 current_offset;
2822 int i, buf_size, ngroups, index_entry_size;
2824 guint8 *data_p, *data_buf;
2825 guint32 *index_offsets;
2827 ngroups = (noffsets + (group_size - 1)) / group_size;
2829 index_offsets = g_new0 (guint32, ngroups);
2831 buf_size = noffsets * 4;
2832 p = buf = (guint8 *)g_malloc0 (buf_size);
2835 for (i = 0; i < noffsets; ++i) {
2836 //printf ("D: %d -> %d\n", i, offsets [i]);
2837 if ((i % group_size) == 0) {
2838 index_offsets [i / group_size] = p - buf;
2839 /* Emit the full value for these entries */
2840 encode_value (offsets [i], p, &p);
2842 /* The offsets are allowed to be non-increasing */
2843 //g_assert (offsets [i] >= current_offset);
2844 encode_value (offsets [i] - current_offset, p, &p);
2846 current_offset = offsets [i];
2851 if (ngroups && index_offsets [ngroups - 1] < 65000)
2852 index_entry_size = 2;
2854 index_entry_size = 4;
2856 buf_size = (data_p - data_buf) + (ngroups * 4) + 16;
2857 p = buf = (guint8 *)g_malloc0 (buf_size);
2859 /* Emit the header */
2860 encode_int (noffsets, p, &p);
2861 encode_int (group_size, p, &p);
2862 encode_int (ngroups, p, &p);
2863 encode_int (index_entry_size, p, &p);
2865 /* Emit the index */
2866 for (i = 0; i < ngroups; ++i) {
2867 if (index_entry_size == 2)
2868 encode_int16 (index_offsets [i], p, &p);
2870 encode_int (index_offsets [i], p, &p);
2873 memcpy (p, data_buf, data_p - data_buf);
2874 p += data_p - data_buf;
2876 g_assert (p - buf <= buf_size);
2878 emit_aot_data (acfg, table, symbol, buf, p - buf);
2883 return (int)(p - buf);
2887 get_image_index (MonoAotCompile *cfg, MonoImage *image)
2891 index = GPOINTER_TO_UINT (g_hash_table_lookup (cfg->image_hash, image));
2895 index = g_hash_table_size (cfg->image_hash);
2896 g_hash_table_insert (cfg->image_hash, image, GUINT_TO_POINTER (index + 1));
2897 g_ptr_array_add (cfg->image_table, image);
2903 find_typespec_for_class (MonoAotCompile *acfg, MonoClass *klass)
2906 int len = acfg->image->tables [MONO_TABLE_TYPESPEC].rows;
2908 /* FIXME: Search referenced images as well */
2909 if (!acfg->typespec_classes) {
2910 acfg->typespec_classes = (MonoClass **)mono_mempool_alloc0 (acfg->mempool, sizeof (MonoClass*) * len);
2911 for (i = 0; i < len; ++i) {
2913 acfg->typespec_classes [i] = mono_class_get_and_inflate_typespec_checked (acfg->image, MONO_TOKEN_TYPE_SPEC | (i + 1), NULL, &error);
2914 g_assert (mono_error_ok (&error)); /* FIXME error handling */
2917 for (i = 0; i < len; ++i) {
2918 if (acfg->typespec_classes [i] == klass)
2923 return MONO_TOKEN_TYPE_SPEC | (i + 1);
2929 encode_method_ref (MonoAotCompile *acfg, MonoMethod *method, guint8 *buf, guint8 **endbuf);
2932 encode_klass_ref (MonoAotCompile *acfg, MonoClass *klass, guint8 *buf, guint8 **endbuf);
2935 encode_ginst (MonoAotCompile *acfg, MonoGenericInst *inst, guint8 *buf, guint8 **endbuf);
2938 encode_type (MonoAotCompile *acfg, MonoType *t, guint8 *buf, guint8 **endbuf);
2941 encode_klass_ref_inner (MonoAotCompile *acfg, MonoClass *klass, guint8 *buf, guint8 **endbuf)
2946 * The encoding begins with one of the MONO_AOT_TYPEREF values, followed by additional
2950 if (klass->generic_class) {
2952 g_assert (klass->type_token);
2954 /* Find a typespec for a class if possible */
2955 token = find_typespec_for_class (acfg, klass);
2957 encode_value (MONO_AOT_TYPEREF_TYPESPEC_TOKEN, p, &p);
2958 encode_value (token, p, &p);
2960 MonoClass *gclass = klass->generic_class->container_class;
2961 MonoGenericInst *inst = klass->generic_class->context.class_inst;
2962 static int count = 0;
2965 encode_value (MONO_AOT_TYPEREF_GINST, p, &p);
2966 encode_klass_ref (acfg, gclass, p, &p);
2967 encode_ginst (acfg, inst, p, &p);
2971 } else if (klass->type_token) {
2972 int iindex = get_image_index (acfg, klass->image);
2974 g_assert (mono_metadata_token_code (klass->type_token) == MONO_TOKEN_TYPE_DEF);
2976 encode_value (MONO_AOT_TYPEREF_TYPEDEF_INDEX, p, &p);
2977 encode_value (klass->type_token - MONO_TOKEN_TYPE_DEF, p, &p);
2979 encode_value (MONO_AOT_TYPEREF_TYPEDEF_INDEX_IMAGE, p, &p);
2980 encode_value (klass->type_token - MONO_TOKEN_TYPE_DEF, p, &p);
2981 encode_value (get_image_index (acfg, klass->image), p, &p);
2983 } else if ((klass->byval_arg.type == MONO_TYPE_VAR) || (klass->byval_arg.type == MONO_TYPE_MVAR)) {
2984 MonoGenericContainer *container = mono_type_get_generic_param_owner (&klass->byval_arg);
2985 MonoGenericParam *par = klass->byval_arg.data.generic_param;
2987 encode_value (MONO_AOT_TYPEREF_VAR, p, &p);
2989 encode_value (par->gshared_constraint ? 1 : 0, p, &p);
2990 if (par->gshared_constraint) {
2991 MonoGSharedGenericParam *gpar = (MonoGSharedGenericParam*)par;
2992 encode_type (acfg, par->gshared_constraint, p, &p);
2993 encode_klass_ref (acfg, mono_class_from_generic_parameter (gpar->parent, NULL, klass->byval_arg.type == MONO_TYPE_MVAR), p, &p);
2995 encode_value (klass->byval_arg.type, p, &p);
2996 encode_value (mono_type_get_generic_param_num (&klass->byval_arg), p, &p);
2998 encode_value (container->is_anonymous ? 0 : 1, p, &p);
3000 if (!container->is_anonymous) {
3001 encode_value (container->is_method, p, &p);
3002 if (container->is_method)
3003 encode_method_ref (acfg, container->owner.method, p, &p);
3005 encode_klass_ref (acfg, container->owner.klass, p, &p);
3008 } else if (klass->byval_arg.type == MONO_TYPE_PTR) {
3009 encode_value (MONO_AOT_TYPEREF_PTR, p, &p);
3010 encode_type (acfg, &klass->byval_arg, p, &p);
3013 g_assert (klass->rank > 0);
3014 encode_value (MONO_AOT_TYPEREF_ARRAY, p, &p);
3015 encode_value (klass->rank, p, &p);
3016 encode_klass_ref (acfg, klass->element_class, p, &p);
3024 * Encode a reference to KLASS. We use our home-grown encoding instead of the
3025 * standard metadata encoding.
3028 encode_klass_ref (MonoAotCompile *acfg, MonoClass *klass, guint8 *buf, guint8 **endbuf)
3030 gboolean shared = FALSE;
3033 * The encoding of generic instances is large so emit them only once.
3035 if (klass->generic_class) {
3037 g_assert (klass->type_token);
3039 /* Find a typespec for a class if possible */
3040 token = find_typespec_for_class (acfg, klass);
3043 } else if ((klass->byval_arg.type == MONO_TYPE_VAR) || (klass->byval_arg.type == MONO_TYPE_MVAR)) {
3048 guint offset = GPOINTER_TO_UINT (g_hash_table_lookup (acfg->klass_blob_hash, klass));
3052 buf2 = (guint8 *)g_malloc (1024);
3055 encode_klass_ref_inner (acfg, klass, p, &p);
3056 g_assert (p - buf2 < 1024);
3058 offset = add_to_blob (acfg, buf2, p - buf2);
3061 g_hash_table_insert (acfg->klass_blob_hash, klass, GUINT_TO_POINTER (offset + 1));
3067 encode_value (MONO_AOT_TYPEREF_BLOB_INDEX, p, &p);
3068 encode_value (offset, p, &p);
3073 encode_klass_ref_inner (acfg, klass, buf, endbuf);
3077 encode_field_info (MonoAotCompile *cfg, MonoClassField *field, guint8 *buf, guint8 **endbuf)
3079 guint32 token = mono_get_field_token (field);
3082 encode_klass_ref (cfg, field->parent, p, &p);
3083 g_assert (mono_metadata_token_code (token) == MONO_TOKEN_FIELD_DEF);
3084 encode_value (token - MONO_TOKEN_FIELD_DEF, p, &p);
3089 encode_ginst (MonoAotCompile *acfg, MonoGenericInst *inst, guint8 *buf, guint8 **endbuf)
3094 encode_value (inst->type_argc, p, &p);
3095 for (i = 0; i < inst->type_argc; ++i)
3096 encode_klass_ref (acfg, mono_class_from_mono_type (inst->type_argv [i]), p, &p);
3101 encode_generic_context (MonoAotCompile *acfg, MonoGenericContext *context, guint8 *buf, guint8 **endbuf)
3104 MonoGenericInst *inst;
3106 inst = context->class_inst;
3108 g_assert (inst->type_argc);
3109 encode_ginst (acfg, inst, p, &p);
3111 encode_value (0, p, &p);
3113 inst = context->method_inst;
3115 g_assert (inst->type_argc);
3116 encode_ginst (acfg, inst, p, &p);
3118 encode_value (0, p, &p);
3124 encode_type (MonoAotCompile *acfg, MonoType *t, guint8 *buf, guint8 **endbuf)
3128 g_assert (t->num_mods == 0);
3129 /* t->attrs can be ignored */
3130 //g_assert (t->attrs == 0);
3133 *p = MONO_TYPE_PINNED;
3137 *p = MONO_TYPE_BYREF;
3145 case MONO_TYPE_VOID:
3146 case MONO_TYPE_BOOLEAN:
3147 case MONO_TYPE_CHAR:
3160 case MONO_TYPE_STRING:
3161 case MONO_TYPE_OBJECT:
3162 case MONO_TYPE_TYPEDBYREF:
3164 case MONO_TYPE_VALUETYPE:
3165 case MONO_TYPE_CLASS:
3166 encode_klass_ref (acfg, mono_class_from_mono_type (t), p, &p);
3168 case MONO_TYPE_SZARRAY:
3169 encode_klass_ref (acfg, t->data.klass, p, &p);
3172 encode_type (acfg, t->data.type, p, &p);
3174 case MONO_TYPE_GENERICINST: {
3175 MonoClass *gclass = t->data.generic_class->container_class;
3176 MonoGenericInst *inst = t->data.generic_class->context.class_inst;
3178 encode_klass_ref (acfg, gclass, p, &p);
3179 encode_ginst (acfg, inst, p, &p);
3182 case MONO_TYPE_ARRAY: {
3183 MonoArrayType *array = t->data.array;
3186 encode_klass_ref (acfg, array->eklass, p, &p);
3187 encode_value (array->rank, p, &p);
3188 encode_value (array->numsizes, p, &p);
3189 for (i = 0; i < array->numsizes; ++i)
3190 encode_value (array->sizes [i], p, &p);
3191 encode_value (array->numlobounds, p, &p);
3192 for (i = 0; i < array->numlobounds; ++i)
3193 encode_value (array->lobounds [i], p, &p);
3197 case MONO_TYPE_MVAR:
3198 encode_klass_ref (acfg, mono_class_from_mono_type (t), p, &p);
3201 g_assert_not_reached ();
3208 encode_signature (MonoAotCompile *acfg, MonoMethodSignature *sig, guint8 *buf, guint8 **endbuf)
3214 /* Similar to the metadata encoding */
3215 if (sig->generic_param_count)
3219 if (sig->explicit_this)
3221 flags |= (sig->call_convention & 0x0F);
3225 if (sig->generic_param_count)
3226 encode_value (sig->generic_param_count, p, &p);
3227 encode_value (sig->param_count, p, &p);
3229 encode_type (acfg, sig->ret, p, &p);
3230 for (i = 0; i < sig->param_count; ++i) {
3231 if (sig->sentinelpos == i) {
3232 *p = MONO_TYPE_SENTINEL;
3235 encode_type (acfg, sig->params [i], p, &p);
3241 #define MAX_IMAGE_INDEX 250
3244 encode_method_ref (MonoAotCompile *acfg, MonoMethod *method, guint8 *buf, guint8 **endbuf)
3246 guint32 image_index = get_image_index (acfg, method->klass->image);
3247 guint32 token = method->token;
3248 MonoJumpInfoToken *ji;
3252 * The encoding for most methods is as follows:
3253 * - image index encoded as a leb128
3254 * - token index encoded as a leb128
3255 * Values of image index >= MONO_AOT_METHODREF_MIN are used to mark additional
3256 * types of method encodings.
3259 /* Mark methods which can't use aot trampolines because they need the further
3260 * processing in mono_magic_trampoline () which requires a MonoMethod*.
3262 if ((method->is_generic && (method->flags & METHOD_ATTRIBUTE_VIRTUAL)) ||
3263 (method->iflags & METHOD_IMPL_ATTRIBUTE_SYNCHRONIZED))
3264 encode_value ((MONO_AOT_METHODREF_NO_AOT_TRAMPOLINE << 24), p, &p);
3266 if (method->wrapper_type) {
3267 WrapperInfo *info = mono_marshal_get_wrapper_info (method);
3269 encode_value ((MONO_AOT_METHODREF_WRAPPER << 24), p, &p);
3271 encode_value (method->wrapper_type, p, &p);
3273 switch (method->wrapper_type) {
3274 case MONO_WRAPPER_REMOTING_INVOKE:
3275 case MONO_WRAPPER_REMOTING_INVOKE_WITH_CHECK:
3276 case MONO_WRAPPER_XDOMAIN_INVOKE: {
3279 m = mono_marshal_method_from_wrapper (method);
3281 encode_method_ref (acfg, m, p, &p);
3284 case MONO_WRAPPER_PROXY_ISINST:
3285 case MONO_WRAPPER_LDFLD:
3286 case MONO_WRAPPER_LDFLDA:
3287 case MONO_WRAPPER_STFLD:
3288 case MONO_WRAPPER_ISINST: {
3290 encode_klass_ref (acfg, info->d.proxy.klass, p, &p);
3293 case MONO_WRAPPER_LDFLD_REMOTE:
3294 case MONO_WRAPPER_STFLD_REMOTE:
3296 case MONO_WRAPPER_ALLOC: {
3297 /* The GC name is saved once in MonoAotFileInfo */
3298 g_assert (info->d.alloc.alloc_type != -1);
3299 encode_value (info->d.alloc.alloc_type, p, &p);
3302 case MONO_WRAPPER_WRITE_BARRIER: {
3306 case MONO_WRAPPER_STELEMREF: {
3308 encode_value (info->subtype, p, &p);
3309 if (info->subtype == WRAPPER_SUBTYPE_VIRTUAL_STELEMREF)
3310 encode_value (info->d.virtual_stelemref.kind, p, &p);
3313 case MONO_WRAPPER_UNKNOWN: {
3315 encode_value (info->subtype, p, &p);
3316 if (info->subtype == WRAPPER_SUBTYPE_PTR_TO_STRUCTURE ||
3317 info->subtype == WRAPPER_SUBTYPE_STRUCTURE_TO_PTR)
3318 encode_klass_ref (acfg, method->klass, p, &p);
3319 else if (info->subtype == WRAPPER_SUBTYPE_SYNCHRONIZED_INNER)
3320 encode_method_ref (acfg, info->d.synchronized_inner.method, p, &p);
3321 else if (info->subtype == WRAPPER_SUBTYPE_ARRAY_ACCESSOR)
3322 encode_method_ref (acfg, info->d.array_accessor.method, p, &p);
3323 else if (info->subtype == WRAPPER_SUBTYPE_GSHAREDVT_IN_SIG)
3324 encode_signature (acfg, info->d.gsharedvt.sig, p, &p);
3325 else if (info->subtype == WRAPPER_SUBTYPE_GSHAREDVT_OUT_SIG)
3326 encode_signature (acfg, info->d.gsharedvt.sig, p, &p);
3329 case MONO_WRAPPER_MANAGED_TO_NATIVE: {
3331 encode_value (info->subtype, p, &p);
3332 if (info->subtype == WRAPPER_SUBTYPE_ICALL_WRAPPER) {
3333 strcpy ((char*)p, method->name);
3334 p += strlen (method->name) + 1;
3335 } else if (info->subtype == WRAPPER_SUBTYPE_NATIVE_FUNC_AOT) {
3336 encode_method_ref (acfg, info->d.managed_to_native.method, p, &p);
3338 g_assert (info->subtype == WRAPPER_SUBTYPE_NONE || info->subtype == WRAPPER_SUBTYPE_PINVOKE);
3339 encode_method_ref (acfg, info->d.managed_to_native.method, p, &p);
3343 case MONO_WRAPPER_SYNCHRONIZED: {
3346 m = mono_marshal_method_from_wrapper (method);
3348 g_assert (m != method);
3349 encode_method_ref (acfg, m, p, &p);
3352 case MONO_WRAPPER_MANAGED_TO_MANAGED: {
3354 encode_value (info->subtype, p, &p);
3356 if (info->subtype == WRAPPER_SUBTYPE_ELEMENT_ADDR) {
3357 encode_value (info->d.element_addr.rank, p, &p);
3358 encode_value (info->d.element_addr.elem_size, p, &p);
3359 } else if (info->subtype == WRAPPER_SUBTYPE_STRING_CTOR) {
3360 encode_method_ref (acfg, info->d.string_ctor.method, p, &p);
3362 g_assert_not_reached ();
3366 case MONO_WRAPPER_CASTCLASS: {
3368 encode_value (info->subtype, p, &p);
3371 case MONO_WRAPPER_RUNTIME_INVOKE: {
3373 encode_value (info->subtype, p, &p);
3374 if (info->subtype == WRAPPER_SUBTYPE_RUNTIME_INVOKE_DIRECT || info->subtype == WRAPPER_SUBTYPE_RUNTIME_INVOKE_VIRTUAL)
3375 encode_method_ref (acfg, info->d.runtime_invoke.method, p, &p);
3376 else if (info->subtype == WRAPPER_SUBTYPE_RUNTIME_INVOKE_NORMAL)
3377 encode_signature (acfg, info->d.runtime_invoke.sig, p, &p);
3380 case MONO_WRAPPER_DELEGATE_INVOKE:
3381 case MONO_WRAPPER_DELEGATE_BEGIN_INVOKE:
3382 case MONO_WRAPPER_DELEGATE_END_INVOKE: {
3383 if (method->is_inflated) {
3384 /* These wrappers are identified by their class */
3385 encode_value (1, p, &p);
3386 encode_klass_ref (acfg, method->klass, p, &p);
3388 MonoMethodSignature *sig = mono_method_signature (method);
3389 WrapperInfo *info = mono_marshal_get_wrapper_info (method);
3391 encode_value (0, p, &p);
3392 if (method->wrapper_type == MONO_WRAPPER_DELEGATE_INVOKE)
3393 encode_value (info ? info->subtype : 0, p, &p);
3394 encode_signature (acfg, sig, p, &p);
3398 case MONO_WRAPPER_NATIVE_TO_MANAGED: {
3400 encode_method_ref (acfg, info->d.native_to_managed.method, p, &p);
3401 encode_klass_ref (acfg, info->d.native_to_managed.klass, p, &p);
3405 g_assert_not_reached ();
3407 } else if (mono_method_signature (method)->is_inflated) {
3409 * This is a generic method, find the original token which referenced it and
3411 * Obtain the token from information recorded by the JIT.
3413 ji = (MonoJumpInfoToken *)g_hash_table_lookup (acfg->token_info_hash, method);
3415 image_index = get_image_index (acfg, ji->image);
3416 g_assert (image_index < MAX_IMAGE_INDEX);
3419 encode_value ((MONO_AOT_METHODREF_METHODSPEC << 24), p, &p);
3420 encode_value (image_index, p, &p);
3421 encode_value (token, p, &p);
3423 MonoMethod *declaring;
3424 MonoGenericContext *context = mono_method_get_context (method);
3426 g_assert (method->is_inflated);
3427 declaring = ((MonoMethodInflated*)method)->declaring;
3430 * This might be a non-generic method of a generic instance, which
3431 * doesn't have a token since the reference is generated by the JIT
3432 * like Nullable:Box/Unbox, or by generic sharing.
3434 encode_value ((MONO_AOT_METHODREF_GINST << 24), p, &p);
3435 /* Encode the klass */
3436 encode_klass_ref (acfg, method->klass, p, &p);
3437 /* Encode the method */
3438 image_index = get_image_index (acfg, method->klass->image);
3439 g_assert (image_index < MAX_IMAGE_INDEX);
3440 g_assert (declaring->token);
3441 token = declaring->token;
3442 g_assert (mono_metadata_token_table (token) == MONO_TABLE_METHOD);
3443 encode_value (image_index, p, &p);
3444 encode_value (token, p, &p);
3445 encode_generic_context (acfg, context, p, &p);
3447 } else if (token == 0) {
3448 /* This might be a method of a constructed type like int[,].Set */
3449 /* Obtain the token from information recorded by the JIT */
3450 ji = (MonoJumpInfoToken *)g_hash_table_lookup (acfg->token_info_hash, method);
3452 image_index = get_image_index (acfg, ji->image);
3453 g_assert (image_index < MAX_IMAGE_INDEX);
3456 encode_value ((MONO_AOT_METHODREF_METHODSPEC << 24), p, &p);
3457 encode_value (image_index, p, &p);
3458 encode_value (token, p, &p);
3461 g_assert (method->klass->rank);
3463 /* Encode directly */
3464 encode_value ((MONO_AOT_METHODREF_ARRAY << 24), p, &p);
3465 encode_klass_ref (acfg, method->klass, p, &p);
3466 if (!strcmp (method->name, ".ctor") && mono_method_signature (method)->param_count == method->klass->rank)
3467 encode_value (0, p, &p);
3468 else if (!strcmp (method->name, ".ctor") && mono_method_signature (method)->param_count == method->klass->rank * 2)
3469 encode_value (1, p, &p);
3470 else if (!strcmp (method->name, "Get"))
3471 encode_value (2, p, &p);
3472 else if (!strcmp (method->name, "Address"))
3473 encode_value (3, p, &p);
3474 else if (!strcmp (method->name, "Set"))
3475 encode_value (4, p, &p);
3477 g_assert_not_reached ();
3480 g_assert (mono_metadata_token_table (token) == MONO_TABLE_METHOD);
3482 if (image_index >= MONO_AOT_METHODREF_MIN) {
3483 encode_value ((MONO_AOT_METHODREF_LARGE_IMAGE_INDEX << 24), p, &p);
3484 encode_value (image_index, p, &p);
3485 encode_value (mono_metadata_token_index (token), p, &p);
3487 encode_value ((image_index << 24) | mono_metadata_token_index (token), p, &p);
3494 compare_patches (gconstpointer a, gconstpointer b)
3498 i = (*(MonoJumpInfo**)a)->ip.i;
3499 j = (*(MonoJumpInfo**)b)->ip.i;
3510 static G_GNUC_UNUSED char*
3511 patch_to_string (MonoJumpInfo *patch_info)
3515 str = g_string_new ("");
3517 g_string_append_printf (str, "%s(", get_patch_name (patch_info->type));
3519 switch (patch_info->type) {
3520 case MONO_PATCH_INFO_VTABLE:
3521 mono_type_get_desc (str, &patch_info->data.klass->byval_arg, TRUE);
3526 g_string_append_printf (str, ")");
3527 return g_string_free (str, FALSE);
3533 * Return whenever PATCH_INFO refers to a direct call, and thus requires a
3536 static inline gboolean
3537 is_plt_patch (MonoJumpInfo *patch_info)
3539 switch (patch_info->type) {
3540 case MONO_PATCH_INFO_METHOD:
3541 case MONO_PATCH_INFO_INTERNAL_METHOD:
3542 case MONO_PATCH_INFO_JIT_ICALL_ADDR:
3543 case MONO_PATCH_INFO_ICALL_ADDR_CALL:
3544 case MONO_PATCH_INFO_RGCTX_FETCH:
3554 * Return the symbol identifying the plt entry PLT_OFFSET.
3557 get_plt_symbol (MonoAotCompile *acfg, int plt_offset, MonoJumpInfo *patch_info)
3561 * The Apple linker reorganizes object files, so it doesn't like branches to local
3562 * labels, since those have no relocations.
3564 return g_strdup_printf ("%sp_%d", acfg->llvm_label_prefix, plt_offset);
3566 return g_strdup_printf ("%sp_%d", acfg->temp_prefix, plt_offset);
3573 * Return a PLT entry which belongs to the method identified by PATCH_INFO.
3575 static MonoPltEntry*
3576 get_plt_entry (MonoAotCompile *acfg, MonoJumpInfo *patch_info)
3579 gboolean synchronized = FALSE;
3580 static int synchronized_symbol_idx;
3582 if (!is_plt_patch (patch_info))
3585 if (!acfg->patch_to_plt_entry [patch_info->type])
3586 acfg->patch_to_plt_entry [patch_info->type] = g_hash_table_new (mono_patch_info_hash, mono_patch_info_equal);
3587 res = (MonoPltEntry *)g_hash_table_lookup (acfg->patch_to_plt_entry [patch_info->type], patch_info);
3589 if (!acfg->llvm && patch_info->type == MONO_PATCH_INFO_METHOD && (patch_info->data.method->iflags & METHOD_IMPL_ATTRIBUTE_SYNCHRONIZED)) {
3591 * Allocate a separate PLT slot for each such patch, since some plt
3592 * entries will refer to the method itself, and some will refer to the
3596 synchronized = TRUE;
3600 MonoJumpInfo *new_ji;
3602 new_ji = mono_patch_info_dup_mp (acfg->mempool, patch_info);
3604 res = (MonoPltEntry *)mono_mempool_alloc0 (acfg->mempool, sizeof (MonoPltEntry));
3605 res->plt_offset = acfg->plt_offset;
3607 res->symbol = get_plt_symbol (acfg, res->plt_offset, patch_info);
3608 if (acfg->aot_opts.write_symbols)
3609 res->debug_sym = get_plt_entry_debug_sym (acfg, res->ji, acfg->plt_entry_debug_sym_cache);
3611 /* Avoid duplicate symbols because we don't cache */
3612 res->symbol = g_strdup_printf ("%s_%d", res->symbol, synchronized_symbol_idx);
3614 res->debug_sym = g_strdup_printf ("%s_%d", res->debug_sym, synchronized_symbol_idx);
3615 synchronized_symbol_idx ++;
3618 res->llvm_symbol = g_strdup_printf ("%s_%s_llvm", res->symbol, res->debug_sym);
3620 res->llvm_symbol = g_strdup_printf ("%s_llvm", res->symbol);
3622 g_hash_table_insert (acfg->patch_to_plt_entry [new_ji->type], new_ji, res);
3624 g_hash_table_insert (acfg->plt_offset_to_entry, GUINT_TO_POINTER (res->plt_offset), res);
3626 //g_assert (mono_patch_info_equal (patch_info, new_ji));
3627 //mono_print_ji (patch_info); printf ("\n");
3628 //g_hash_table_print_stats (acfg->patch_to_plt_entry);
3630 acfg->plt_offset ++;
3639 * Returns the offset of the GOT slot where the runtime object resulting from resolving
3640 * JI could be found if it exists, otherwise allocates a new one.
3643 get_got_offset (MonoAotCompile *acfg, gboolean llvm, MonoJumpInfo *ji)
3646 GotInfo *info = llvm ? &acfg->llvm_got_info : &acfg->got_info;
3648 got_offset = GPOINTER_TO_UINT (g_hash_table_lookup (info->patch_to_got_offset_by_type [ji->type], ji));
3650 return got_offset - 1;
3653 got_offset = acfg->llvm_got_offset;
3654 acfg->llvm_got_offset ++;
3656 got_offset = acfg->got_offset;
3657 acfg->got_offset ++;
3660 acfg->stats.got_slots ++;
3661 acfg->stats.got_slot_types [ji->type] ++;
3663 g_hash_table_insert (info->patch_to_got_offset, ji, GUINT_TO_POINTER (got_offset + 1));
3664 g_hash_table_insert (info->patch_to_got_offset_by_type [ji->type], ji, GUINT_TO_POINTER (got_offset + 1));
3665 g_ptr_array_add (info->got_patches, ji);
3670 /* Add a method to the list of methods which need to be emitted */
3672 add_method_with_index (MonoAotCompile *acfg, MonoMethod *method, int index, gboolean extra)
3675 if (!g_hash_table_lookup (acfg->method_indexes, method)) {
3676 g_ptr_array_add (acfg->methods, method);
3677 g_hash_table_insert (acfg->method_indexes, method, GUINT_TO_POINTER (index + 1));
3678 acfg->nmethods = acfg->methods->len + 1;
3681 if (method->wrapper_type || extra)
3682 g_ptr_array_add (acfg->extra_methods, method);
3686 prefer_gsharedvt_method (MonoAotCompile *acfg, MonoMethod *method)
3688 /* One instantiation with valuetypes is generated for each async method */
3689 if (method->klass->image == mono_defaults.corlib && (!strcmp (method->klass->name, "AsyncMethodBuilderCore") || !strcmp (method->klass->name, "AsyncVoidMethodBuilder")))
3696 get_method_index (MonoAotCompile *acfg, MonoMethod *method)
3698 int index = GPOINTER_TO_UINT (g_hash_table_lookup (acfg->method_indexes, method));
3706 add_method_full (MonoAotCompile *acfg, MonoMethod *method, gboolean extra, int depth)
3710 index = GPOINTER_TO_UINT (g_hash_table_lookup (acfg->method_indexes, method));
3714 index = acfg->method_index;
3715 add_method_with_index (acfg, method, index, extra);
3717 g_ptr_array_add (acfg->method_order, GUINT_TO_POINTER (index));
3719 g_hash_table_insert (acfg->method_depth, method, GUINT_TO_POINTER (depth));
3721 acfg->method_index ++;
3727 add_method (MonoAotCompile *acfg, MonoMethod *method)
3729 return add_method_full (acfg, method, FALSE, 0);
3733 add_extra_method_with_depth (MonoAotCompile *acfg, MonoMethod *method, int depth)
3735 if (mono_method_is_generic_sharable_full (method, TRUE, TRUE, FALSE))
3736 method = mini_get_shared_method (method);
3737 else if ((acfg->opts & MONO_OPT_GSHAREDVT) && prefer_gsharedvt_method (acfg, method) && mono_method_is_generic_sharable_full (method, FALSE, FALSE, TRUE))
3738 /* Use the gsharedvt version */
3739 method = mini_get_shared_method_full (method, TRUE, TRUE);
3741 if (acfg->aot_opts.log_generics)
3742 aot_printf (acfg, "%*sAdding method %s.\n", depth, "", mono_method_get_full_name (method));
3744 add_method_full (acfg, method, TRUE, depth);
3748 add_extra_method (MonoAotCompile *acfg, MonoMethod *method)
3750 add_extra_method_with_depth (acfg, method, 0);
3754 add_jit_icall_wrapper (gpointer key, gpointer value, gpointer user_data)
3756 MonoAotCompile *acfg = (MonoAotCompile *)user_data;
3757 MonoJitICallInfo *callinfo = (MonoJitICallInfo *)value;
3758 MonoMethod *wrapper;
3764 name = g_strdup_printf ("__icall_wrapper_%s", callinfo->name);
3765 wrapper = mono_marshal_get_icall_wrapper (callinfo->sig, name, callinfo->func, TRUE);
3768 add_method (acfg, wrapper);
3772 get_runtime_invoke_sig (MonoMethodSignature *sig)
3774 MonoMethodBuilder *mb;
3777 mb = mono_mb_new (mono_defaults.object_class, "FOO", MONO_WRAPPER_NONE);
3778 m = mono_mb_create_method (mb, sig, 16);
3779 return mono_marshal_get_runtime_invoke (m, FALSE);
3783 get_runtime_invoke (MonoAotCompile *acfg, MonoMethod *method, gboolean virtual_)
3785 return mono_marshal_get_runtime_invoke (method, virtual_);
3789 can_marshal_struct (MonoClass *klass)
3791 MonoClassField *field;
3792 gboolean can_marshal = TRUE;
3793 gpointer iter = NULL;
3794 MonoMarshalType *info;
3797 if ((klass->flags & TYPE_ATTRIBUTE_LAYOUT_MASK) == TYPE_ATTRIBUTE_AUTO_LAYOUT)
3800 info = mono_marshal_load_type_info (klass);
3802 /* Only allow a few field types to avoid asserts in the marshalling code */
3803 while ((field = mono_class_get_fields (klass, &iter))) {
3804 if ((field->type->attrs & FIELD_ATTRIBUTE_STATIC))
3807 switch (field->type->type) {
3812 case MONO_TYPE_BOOLEAN:
3815 case MONO_TYPE_CHAR:
3823 case MONO_TYPE_STRING:
3825 case MONO_TYPE_VALUETYPE:
3826 if (!mono_class_from_mono_type (field->type)->enumtype && !can_marshal_struct (mono_class_from_mono_type (field->type)))
3827 can_marshal = FALSE;
3829 case MONO_TYPE_SZARRAY: {
3830 gboolean has_mspec = FALSE;
3833 for (i = 0; i < info->num_fields; ++i) {
3834 if (info->fields [i].field == field && info->fields [i].mspec)
3839 can_marshal = FALSE;
3843 can_marshal = FALSE;
3849 /* Its hard to compute whenever these can be marshalled or not */
3850 if (!strcmp (klass->name_space, "System.Net.NetworkInformation.MacOsStructs") && strcmp (klass->name, "sockaddr_dl"))
3857 create_gsharedvt_inst (MonoAotCompile *acfg, MonoMethod *method, MonoGenericContext *ctx)
3859 /* Create a vtype instantiation */
3860 MonoGenericContext shared_context;
3862 MonoGenericInst *inst;
3863 MonoGenericContainer *container;
3864 MonoClass **constraints;
3867 memset (ctx, 0, sizeof (MonoGenericContext));
3869 if (method->klass->generic_container) {
3870 shared_context = method->klass->generic_container->context;
3871 inst = shared_context.class_inst;
3873 args = g_new0 (MonoType*, inst->type_argc);
3874 for (i = 0; i < inst->type_argc; ++i) {
3875 args [i] = &mono_defaults.int_class->byval_arg;
3877 ctx->class_inst = mono_metadata_get_generic_inst (inst->type_argc, args);
3879 if (method->is_generic) {
3880 container = mono_method_get_generic_container (method);
3881 shared_context = container->context;
3882 inst = shared_context.method_inst;
3884 args = g_new0 (MonoType*, inst->type_argc);
3885 for (i = 0; i < container->type_argc; ++i) {
3886 MonoGenericParamInfo *info = &container->type_params [i].info;
3887 gboolean ref_only = FALSE;
3889 if (info && info->constraints) {
3890 constraints = info->constraints;
3892 while (*constraints) {
3893 MonoClass *cklass = *constraints;
3894 if (!(cklass == mono_defaults.object_class || (cklass->image == mono_defaults.corlib && !strcmp (cklass->name, "ValueType"))))
3895 /* Inflaring the method with our vtype would not be valid */
3902 args [i] = &mono_defaults.object_class->byval_arg;
3904 args [i] = &mono_defaults.int_class->byval_arg;
3906 ctx->method_inst = mono_metadata_get_generic_inst (inst->type_argc, args);
3911 add_wrappers (MonoAotCompile *acfg)
3913 MonoMethod *method, *m;
3915 MonoMethodSignature *sig, *csig;
3919 * FIXME: Instead of AOTing all the wrappers, it might be better to redesign them
3920 * so there is only one wrapper of a given type, or inlining their contents into their
3923 for (i = 0; i < acfg->image->tables [MONO_TABLE_METHOD].rows; ++i) {
3926 guint32 token = MONO_TOKEN_METHOD_DEF | (i + 1);
3927 gboolean skip = FALSE;
3929 method = mono_get_method_checked (acfg->image, token, NULL, NULL, &error);
3930 report_loader_error (acfg, &error, "Failed to load method token 0x%x due to %s\n", i, mono_error_get_message (&error));
3932 if ((method->flags & METHOD_ATTRIBUTE_PINVOKE_IMPL) ||
3933 (method->iflags & METHOD_IMPL_ATTRIBUTE_RUNTIME) ||
3934 (method->flags & METHOD_ATTRIBUTE_ABSTRACT))
3937 /* Skip methods which can not be handled by get_runtime_invoke () */
3938 sig = mono_method_signature (method);
3941 if ((sig->ret->type == MONO_TYPE_PTR) ||
3942 (sig->ret->type == MONO_TYPE_TYPEDBYREF))
3944 if (mono_class_is_open_constructed_type (sig->ret))
3947 for (j = 0; j < sig->param_count; j++) {
3948 if (sig->params [j]->type == MONO_TYPE_TYPEDBYREF)
3950 if (mono_class_is_open_constructed_type (sig->params [j]))
3954 #ifdef MONO_ARCH_DYN_CALL_SUPPORTED
3955 if (!mono_class_is_contextbound (method->klass)) {
3956 MonoDynCallInfo *info = mono_arch_dyn_call_prepare (sig);
3957 gboolean has_nullable = FALSE;
3959 for (j = 0; j < sig->param_count; j++) {
3960 if (sig->params [j]->type == MONO_TYPE_GENERICINST && mono_class_is_nullable (mono_class_from_mono_type (sig->params [j])))
3961 has_nullable = TRUE;
3964 if (info && !has_nullable && !acfg->aot_opts.llvm_only) {
3965 /* Supported by the dynamic runtime-invoke wrapper */
3969 mono_arch_dyn_call_free (info);
3973 if (acfg->aot_opts.llvm_only)
3974 /* Supported by the gsharedvt based runtime-invoke wrapper */
3978 //printf ("%s\n", mono_method_full_name (method, TRUE));
3979 add_method (acfg, get_runtime_invoke (acfg, method, FALSE));
3983 if (strcmp (acfg->image->assembly->aname.name, "mscorlib") == 0) {
3986 /* Runtime invoke wrappers */
3988 /* void runtime-invoke () [.cctor] */
3989 csig = mono_metadata_signature_alloc (mono_defaults.corlib, 0);
3990 csig->ret = &mono_defaults.void_class->byval_arg;
3991 add_method (acfg, get_runtime_invoke_sig (csig));
3993 /* void runtime-invoke () [Finalize] */
3994 csig = mono_metadata_signature_alloc (mono_defaults.corlib, 0);
3996 csig->ret = &mono_defaults.void_class->byval_arg;
3997 add_method (acfg, get_runtime_invoke_sig (csig));
3999 /* void runtime-invoke (string) [exception ctor] */
4000 csig = mono_metadata_signature_alloc (mono_defaults.corlib, 1);
4002 csig->ret = &mono_defaults.void_class->byval_arg;
4003 csig->params [0] = &mono_defaults.string_class->byval_arg;
4004 add_method (acfg, get_runtime_invoke_sig (csig));
4006 /* void runtime-invoke (string, string) [exception ctor] */
4007 csig = mono_metadata_signature_alloc (mono_defaults.corlib, 2);
4009 csig->ret = &mono_defaults.void_class->byval_arg;
4010 csig->params [0] = &mono_defaults.string_class->byval_arg;
4011 csig->params [1] = &mono_defaults.string_class->byval_arg;
4012 add_method (acfg, get_runtime_invoke_sig (csig));
4014 /* string runtime-invoke () [Exception.ToString ()] */
4015 csig = mono_metadata_signature_alloc (mono_defaults.corlib, 0);
4017 csig->ret = &mono_defaults.string_class->byval_arg;
4018 add_method (acfg, get_runtime_invoke_sig (csig));
4020 /* void runtime-invoke (string, Exception) [exception ctor] */
4021 csig = mono_metadata_signature_alloc (mono_defaults.corlib, 2);
4023 csig->ret = &mono_defaults.void_class->byval_arg;
4024 csig->params [0] = &mono_defaults.string_class->byval_arg;
4025 csig->params [1] = &mono_defaults.exception_class->byval_arg;
4026 add_method (acfg, get_runtime_invoke_sig (csig));
4028 /* Assembly runtime-invoke (string, bool) [DoAssemblyResolve] */
4029 csig = mono_metadata_signature_alloc (mono_defaults.corlib, 2);
4031 csig->ret = &(mono_class_load_from_name (
4032 mono_defaults.corlib, "System.Reflection", "Assembly"))->byval_arg;
4033 csig->params [0] = &mono_defaults.string_class->byval_arg;
4034 csig->params [1] = &mono_defaults.boolean_class->byval_arg;
4035 add_method (acfg, get_runtime_invoke_sig (csig));
4037 /* runtime-invoke used by finalizers */
4038 add_method (acfg, get_runtime_invoke (acfg, mono_class_get_method_from_name_flags (mono_defaults.object_class, "Finalize", 0, 0), TRUE));
4040 /* This is used by mono_runtime_capture_context () */
4041 method = mono_get_context_capture_method ();
4043 add_method (acfg, get_runtime_invoke (acfg, method, FALSE));
4045 #ifdef MONO_ARCH_DYN_CALL_SUPPORTED
4046 if (!acfg->aot_opts.llvm_only)
4047 add_method (acfg, mono_marshal_get_runtime_invoke_dynamic ());
4050 /* These are used by mono_jit_runtime_invoke () to calls gsharedvt out wrappers */
4051 if (acfg->aot_opts.llvm_only) {
4054 /* Create simplified signatures which match the signature used by the gsharedvt out wrappers */
4055 for (variants = 0; variants < 4; ++variants) {
4056 for (i = 0; i < 16; ++i) {
4057 sig = mini_get_gsharedvt_out_sig_wrapper_signature ((variants & 1) > 0, (variants & 2) > 0, i);
4058 add_extra_method (acfg, mono_marshal_get_runtime_invoke_for_sig (sig));
4066 add_method (acfg, mono_marshal_get_stelemref ());
4068 if (MONO_ARCH_HAVE_TLS_GET) {
4069 /* Managed Allocators */
4070 nallocators = mono_gc_get_managed_allocator_types ();
4071 for (i = 0; i < nallocators; ++i) {
4072 m = mono_gc_get_managed_allocator_by_type (i, TRUE);
4074 add_method (acfg, m);
4076 for (i = 0; i < nallocators; ++i) {
4077 m = mono_gc_get_managed_allocator_by_type (i, FALSE);
4079 add_method (acfg, m);
4083 /* write barriers */
4084 if (mono_gc_is_moving ()) {
4085 add_method (acfg, mono_gc_get_specific_write_barrier (FALSE));
4086 add_method (acfg, mono_gc_get_specific_write_barrier (TRUE));
4089 /* Stelemref wrappers */
4091 MonoMethod **wrappers;
4094 wrappers = mono_marshal_get_virtual_stelemref_wrappers (&nwrappers);
4095 for (i = 0; i < nwrappers; ++i)
4096 add_method (acfg, wrappers [i]);
4100 /* castclass_with_check wrapper */
4101 add_method (acfg, mono_marshal_get_castclass_with_cache ());
4102 /* isinst_with_check wrapper */
4103 add_method (acfg, mono_marshal_get_isinst_with_cache ());
4105 /* JIT icall wrappers */
4106 /* FIXME: locking - this is "safe" as full-AOT threads don't mutate the icall hash*/
4107 g_hash_table_foreach (mono_get_jit_icall_info (), add_jit_icall_wrapper, acfg);
4111 * remoting-invoke-with-check wrappers are very frequent, so avoid emitting them,
4112 * we use the original method instead at runtime.
4113 * Since full-aot doesn't support remoting, this is not a problem.
4116 /* remoting-invoke wrappers */
4117 for (i = 0; i < acfg->image->tables [MONO_TABLE_METHOD].rows; ++i) {
4119 MonoMethodSignature *sig;
4121 token = MONO_TOKEN_METHOD_DEF | (i + 1);
4122 method = mono_get_method_checked (acfg->image, token, NULL, NULL, &error);
4123 g_assert (mono_error_ok (&error)); /* FIXME don't swallow the error */
4125 sig = mono_method_signature (method);
4127 if (sig->hasthis && (method->klass->marshalbyref || method->klass == mono_defaults.object_class)) {
4128 m = mono_marshal_get_remoting_invoke_with_check (method);
4130 add_method (acfg, m);
4135 /* delegate-invoke wrappers */
4136 for (i = 0; i < acfg->image->tables [MONO_TABLE_TYPEDEF].rows; ++i) {
4139 MonoCustomAttrInfo *cattr;
4141 token = MONO_TOKEN_TYPE_DEF | (i + 1);
4142 klass = mono_class_get_checked (acfg->image, token, &error);
4145 mono_error_cleanup (&error);
4149 if (!klass->delegate || klass == mono_defaults.delegate_class || klass == mono_defaults.multicastdelegate_class)
4152 if (!klass->generic_container) {
4153 method = mono_get_delegate_invoke (klass);
4155 m = mono_marshal_get_delegate_invoke (method, NULL);
4157 add_method (acfg, m);
4159 method = mono_class_get_method_from_name_flags (klass, "BeginInvoke", -1, 0);
4161 add_method (acfg, mono_marshal_get_delegate_begin_invoke (method));
4163 method = mono_class_get_method_from_name_flags (klass, "EndInvoke", -1, 0);
4165 add_method (acfg, mono_marshal_get_delegate_end_invoke (method));
4167 cattr = mono_custom_attrs_from_class_checked (klass, &error);
4168 if (!is_ok (&error)) {
4169 mono_error_cleanup (&error);
4176 for (j = 0; j < cattr->num_attrs; ++j)
4177 if (cattr->attrs [j].ctor && (!strcmp (cattr->attrs [j].ctor->klass->name, "MonoNativeFunctionWrapperAttribute") || !strcmp (cattr->attrs [j].ctor->klass->name, "UnmanagedFunctionPointerAttribute")))
4179 if (j < cattr->num_attrs) {
4181 MonoMethod *wrapper;
4182 MonoMethod *del_invoke;
4184 /* Add wrappers needed by mono_ftnptr_to_delegate () */
4185 invoke = mono_get_delegate_invoke (klass);
4186 wrapper = mono_marshal_get_native_func_wrapper_aot (klass);
4187 del_invoke = mono_marshal_get_delegate_invoke_internal (invoke, FALSE, TRUE, wrapper);
4188 add_method (acfg, wrapper);
4189 add_method (acfg, del_invoke);
4192 } else if ((acfg->opts & MONO_OPT_GSHAREDVT) && klass->generic_container) {
4194 MonoGenericContext ctx;
4195 MonoMethod *inst, *gshared;
4198 * Emit gsharedvt versions of the generic delegate-invoke wrappers
4201 method = mono_get_delegate_invoke (klass);
4202 create_gsharedvt_inst (acfg, method, &ctx);
4204 inst = mono_class_inflate_generic_method_checked (method, &ctx, &error);
4205 g_assert (mono_error_ok (&error)); /* FIXME don't swallow the error */
4207 m = mono_marshal_get_delegate_invoke (inst, NULL);
4208 g_assert (m->is_inflated);
4210 gshared = mini_get_shared_method_full (m, FALSE, TRUE);
4211 add_extra_method (acfg, gshared);
4214 method = mono_get_delegate_begin_invoke (klass);
4215 create_gsharedvt_inst (acfg, method, &ctx);
4217 inst = mono_class_inflate_generic_method_checked (method, &ctx, &error);
4218 g_assert (mono_error_ok (&error)); /* FIXME don't swallow the error */
4220 m = mono_marshal_get_delegate_begin_invoke (inst);
4221 g_assert (m->is_inflated);
4223 gshared = mini_get_shared_method_full (m, FALSE, TRUE);
4224 add_extra_method (acfg, gshared);
4227 method = mono_get_delegate_end_invoke (klass);
4228 create_gsharedvt_inst (acfg, method, &ctx);
4230 inst = mono_class_inflate_generic_method_checked (method, &ctx, &error);
4231 g_assert (mono_error_ok (&error)); /* FIXME don't swallow the error */
4233 m = mono_marshal_get_delegate_end_invoke (inst);
4234 g_assert (m->is_inflated);
4236 gshared = mini_get_shared_method_full (m, FALSE, TRUE);
4237 add_extra_method (acfg, gshared);
4242 /* array access wrappers */
4243 for (i = 0; i < acfg->image->tables [MONO_TABLE_TYPESPEC].rows; ++i) {
4247 token = MONO_TOKEN_TYPE_SPEC | (i + 1);
4248 klass = mono_class_get_checked (acfg->image, token, &error);
4251 mono_error_cleanup (&error);
4255 if (!acfg->aot_opts.llvm_only && klass->rank && MONO_TYPE_IS_PRIMITIVE (&klass->element_class->byval_arg)) {
4256 MonoMethod *m, *wrapper;
4258 /* Add runtime-invoke wrappers too */
4260 m = mono_class_get_method_from_name (klass, "Get", -1);
4262 wrapper = mono_marshal_get_array_accessor_wrapper (m);
4263 add_extra_method (acfg, wrapper);
4264 add_extra_method (acfg, get_runtime_invoke (acfg, wrapper, FALSE));
4266 m = mono_class_get_method_from_name (klass, "Set", -1);
4268 wrapper = mono_marshal_get_array_accessor_wrapper (m);
4269 add_extra_method (acfg, wrapper);
4270 add_extra_method (acfg, get_runtime_invoke (acfg, wrapper, FALSE));
4274 /* Synchronized wrappers */
4275 for (i = 0; i < acfg->image->tables [MONO_TABLE_METHOD].rows; ++i) {
4277 token = MONO_TOKEN_METHOD_DEF | (i + 1);
4278 method = mono_get_method_checked (acfg->image, token, NULL, NULL, &error);
4279 report_loader_error (acfg, &error, "Failed to load method token 0x%x due to %s\n", i, mono_error_get_message (&error));
4281 if (method->iflags & METHOD_IMPL_ATTRIBUTE_SYNCHRONIZED) {
4282 if (method->is_generic) {
4284 } else if ((acfg->opts & MONO_OPT_GSHAREDVT) && method->klass->generic_container) {
4286 MonoGenericContext ctx;
4287 MonoMethod *inst, *gshared, *m;
4290 * Create a generic wrapper for a generic instance, and AOT that.
4292 create_gsharedvt_inst (acfg, method, &ctx);
4293 inst = mono_class_inflate_generic_method_checked (method, &ctx, &error);
4294 g_assert (mono_error_ok (&error)); /* FIXME don't swallow the error */
4295 m = mono_marshal_get_synchronized_wrapper (inst);
4296 g_assert (m->is_inflated);
4297 gshared = mini_get_shared_method_full (m, FALSE, TRUE);
4298 add_method (acfg, gshared);
4300 add_method (acfg, mono_marshal_get_synchronized_wrapper (method));
4305 /* pinvoke wrappers */
4306 for (i = 0; i < acfg->image->tables [MONO_TABLE_METHOD].rows; ++i) {
4309 guint32 token = MONO_TOKEN_METHOD_DEF | (i + 1);
4311 method = mono_get_method_checked (acfg->image, token, NULL, NULL, &error);
4312 report_loader_error (acfg, &error, "Failed to load method token 0x%x due to %s\n", i, mono_error_get_message (&error));
4314 if ((method->flags & METHOD_ATTRIBUTE_PINVOKE_IMPL) ||
4315 (method->iflags & METHOD_IMPL_ATTRIBUTE_INTERNAL_CALL)) {
4316 add_method (acfg, mono_marshal_get_native_wrapper (method, TRUE, TRUE));
4320 /* native-to-managed wrappers */
4321 for (i = 0; i < acfg->image->tables [MONO_TABLE_METHOD].rows; ++i) {
4324 guint32 token = MONO_TOKEN_METHOD_DEF | (i + 1);
4325 MonoCustomAttrInfo *cattr;
4328 method = mono_get_method_checked (acfg->image, token, NULL, NULL, &error);
4329 report_loader_error (acfg, &error, "Failed to load method token 0x%x due to %s\n", i, mono_error_get_message (&error));
4332 * Only generate native-to-managed wrappers for methods which have an
4333 * attribute named MonoPInvokeCallbackAttribute. We search for the attribute by
4334 * name to avoid defining a new assembly to contain it.
4336 cattr = mono_custom_attrs_from_method_checked (method, &error);
4337 if (!is_ok (&error)) {
4338 char *name = mono_method_get_full_name (method);
4339 report_loader_error (acfg, &error, "Failed to load custom attributes from method %s due to %s\n", name, mono_error_get_message (&error));
4344 for (j = 0; j < cattr->num_attrs; ++j)
4345 if (cattr->attrs [j].ctor && !strcmp (cattr->attrs [j].ctor->klass->name, "MonoPInvokeCallbackAttribute"))
4347 if (j < cattr->num_attrs) {
4348 MonoCustomAttrEntry *e = &cattr->attrs [j];
4349 MonoMethodSignature *sig = mono_method_signature (e->ctor);
4350 const char *p = (const char*)e->data;
4352 int slen, num_named, named_type;
4356 char *export_name = NULL;
4357 MonoMethod *wrapper;
4359 /* this cannot be enforced by the C# compiler so we must give the user some warning before aborting */
4360 if (!(method->flags & METHOD_ATTRIBUTE_STATIC)) {
4361 g_warning ("AOT restriction: Method '%s' must be static since it is decorated with [MonoPInvokeCallback]. See http://ios.xamarin.com/Documentation/Limitations#Reverse_Callbacks",
4362 mono_method_full_name (method, TRUE));
4366 g_assert (sig->param_count == 1);
4367 g_assert (sig->params [0]->type == MONO_TYPE_CLASS && !strcmp (mono_class_from_mono_type (sig->params [0])->name, "Type"));
4370 * Decode the cattr manually since we can't create objects
4371 * during aot compilation.
4377 /* From load_cattr_value () in reflection.c */
4378 slen = mono_metadata_decode_value (p, &p);
4379 n = (char *)g_memdup (p, slen + 1);
4381 t = mono_reflection_type_from_name_checked (n, acfg->image, &error);
4383 mono_error_assert_ok (&error);
4386 klass = mono_class_from_mono_type (t);
4387 g_assert (klass->parent == mono_defaults.multicastdelegate_class);
4391 num_named = read16 (p);
4394 g_assert (num_named < 2);
4395 if (num_named == 1) {
4399 /* parse ExportSymbol attribute */
4401 named_type = *named;
4403 /* data_type = *named; */
4406 name_len = mono_metadata_decode_blob_size (named, &named);
4407 name = (char *)g_malloc (name_len + 1);
4408 memcpy (name, named, name_len);
4409 name [name_len] = 0;
4412 g_assert (named_type == 0x54);
4413 g_assert (!strcmp (name, "ExportSymbol"));
4415 /* load_cattr_value (), string case */
4416 g_assert (*named != (char)0xff);
4417 slen = mono_metadata_decode_value (named, &named);
4418 export_name = (char *)g_malloc (slen + 1);
4419 memcpy (export_name, named, slen);
4420 export_name [slen] = 0;
4424 wrapper = mono_marshal_get_managed_wrapper (method, klass, 0);
4425 add_method (acfg, wrapper);
4427 g_hash_table_insert (acfg->export_names, wrapper, export_name);
4431 if ((method->flags & METHOD_ATTRIBUTE_PINVOKE_IMPL) ||
4432 (method->iflags & METHOD_IMPL_ATTRIBUTE_INTERNAL_CALL)) {
4433 add_method (acfg, mono_marshal_get_native_wrapper (method, TRUE, TRUE));
4437 /* StructureToPtr/PtrToStructure wrappers */
4438 for (i = 0; i < acfg->image->tables [MONO_TABLE_TYPEDEF].rows; ++i) {
4442 token = MONO_TOKEN_TYPE_DEF | (i + 1);
4443 klass = mono_class_get_checked (acfg->image, token, &error);
4446 mono_error_cleanup (&error);
4450 if (klass->valuetype && !klass->generic_container && can_marshal_struct (klass) &&
4451 !(klass->nested_in && strstr (klass->nested_in->name, "<PrivateImplementationDetails>") == klass->nested_in->name)) {
4452 add_method (acfg, mono_marshal_get_struct_to_ptr (klass));
4453 add_method (acfg, mono_marshal_get_ptr_to_struct (klass));
4459 has_type_vars (MonoClass *klass)
4461 if ((klass->byval_arg.type == MONO_TYPE_VAR) || (klass->byval_arg.type == MONO_TYPE_MVAR))
4464 return has_type_vars (klass->element_class);
4465 if (klass->generic_class) {
4466 MonoGenericContext *context = &klass->generic_class->context;
4467 if (context->class_inst) {
4470 for (i = 0; i < context->class_inst->type_argc; ++i)
4471 if (has_type_vars (mono_class_from_mono_type (context->class_inst->type_argv [i])))
4475 if (klass->generic_container)
4481 is_vt_inst (MonoGenericInst *inst)
4485 for (i = 0; i < inst->type_argc; ++i) {
4486 MonoType *t = inst->type_argv [i];
4487 if (MONO_TYPE_ISSTRUCT (t) || t->type == MONO_TYPE_VALUETYPE)
4494 method_has_type_vars (MonoMethod *method)
4496 if (has_type_vars (method->klass))
4499 if (method->is_inflated) {
4500 MonoGenericContext *context = mono_method_get_context (method);
4501 if (context->method_inst) {
4504 for (i = 0; i < context->method_inst->type_argc; ++i)
4505 if (has_type_vars (mono_class_from_mono_type (context->method_inst->type_argv [i])))
4513 gboolean mono_aot_mode_is_full (MonoAotOptions *opts)
4515 return opts->mode == MONO_AOT_MODE_FULL;
4518 static void add_generic_class_with_depth (MonoAotCompile *acfg, MonoClass *klass, int depth, const char *ref);
4521 add_generic_class (MonoAotCompile *acfg, MonoClass *klass, gboolean force, const char *ref)
4523 /* This might lead to a huge code blowup so only do it if neccesary */
4524 if (!mono_aot_mode_is_full (&acfg->aot_opts) && !force)
4527 add_generic_class_with_depth (acfg, klass, 0, ref);
4531 check_type_depth (MonoType *t, int depth)
4539 case MONO_TYPE_GENERICINST: {
4540 MonoGenericClass *gklass = t->data.generic_class;
4541 MonoGenericInst *ginst = gklass->context.class_inst;
4544 for (i = 0; i < ginst->type_argc; ++i) {
4545 if (check_type_depth (ginst->type_argv [i], depth + 1))
4559 add_types_from_method_header (MonoAotCompile *acfg, MonoMethod *method);
4562 * add_generic_class:
4564 * Add all methods of a generic class.
4567 add_generic_class_with_depth (MonoAotCompile *acfg, MonoClass *klass, int depth, const char *ref)
4570 MonoClassField *field;
4572 gboolean use_gsharedvt = FALSE;
4574 if (!acfg->ginst_hash)
4575 acfg->ginst_hash = g_hash_table_new (NULL, NULL);
4577 mono_class_init (klass);
4579 if (klass->generic_class && klass->generic_class->context.class_inst->is_open)
4582 if (has_type_vars (klass))
4585 if (!klass->generic_class && !klass->rank)
4588 if (mono_class_has_failure (klass))
4591 if (!acfg->ginst_hash)
4592 acfg->ginst_hash = g_hash_table_new (NULL, NULL);
4594 if (g_hash_table_lookup (acfg->ginst_hash, klass))
4597 if (check_type_depth (&klass->byval_arg, 0))
4600 if (acfg->aot_opts.log_generics)
4601 aot_printf (acfg, "%*sAdding generic instance %s [%s].\n", depth, "", mono_type_full_name (&klass->byval_arg), ref);
4603 g_hash_table_insert (acfg->ginst_hash, klass, klass);
4606 * Use gsharedvt for generic collections with vtype arguments to avoid code blowup.
4607 * Enable this only for some classes since gsharedvt might not support all methods.
4609 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) &&
4610 (!strcmp (klass->name, "Dictionary`2") || !strcmp (klass->name, "List`1") || !strcmp (klass->name, "ReadOnlyCollection`1")))
4611 use_gsharedvt = TRUE;
4614 while ((method = mono_class_get_methods (klass, &iter))) {
4615 if ((acfg->opts & MONO_OPT_GSHAREDVT) && method->is_inflated && mono_method_get_context (method)->method_inst) {
4617 * This is partial sharing, and we can't handle it yet
4622 if (mono_method_is_generic_sharable_full (method, FALSE, FALSE, use_gsharedvt)) {
4624 add_types_from_method_header (acfg, method);
4628 if (method->is_generic)
4633 * FIXME: Instances which are referenced by these methods are not added,
4634 * for example Array.Resize<int> for List<int>.Add ().
4636 add_extra_method_with_depth (acfg, method, depth + 1);
4640 while ((field = mono_class_get_fields (klass, &iter))) {
4641 if (field->type->type == MONO_TYPE_GENERICINST)
4642 add_generic_class_with_depth (acfg, mono_class_from_mono_type (field->type), depth + 1, "field");
4645 if (klass->delegate) {
4646 method = mono_get_delegate_invoke (klass);
4648 method = mono_marshal_get_delegate_invoke (method, NULL);
4650 if (acfg->aot_opts.log_generics)
4651 aot_printf (acfg, "%*sAdding method %s.\n", depth, "", mono_method_get_full_name (method));
4653 add_method (acfg, method);
4656 /* Add superclasses */
4658 add_generic_class_with_depth (acfg, klass->parent, depth, "parent");
4661 * For ICollection<T>, add instances of the helper methods
4662 * in Array, since a T[] could be cast to ICollection<T>.
4664 if (klass->image == mono_defaults.corlib && !strcmp (klass->name_space, "System.Collections.Generic") &&
4665 (!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"))) {
4666 MonoClass *tclass = mono_class_from_mono_type (klass->generic_class->context.class_inst->type_argv [0]);
4667 MonoClass *array_class = mono_bounded_array_class_get (tclass, 1, FALSE);
4671 if (!strcmp (klass->name, "IEnumerator`1"))
4672 name_prefix = g_strdup_printf ("%s.%s", klass->name_space, "IEnumerable`1");
4674 name_prefix = g_strdup_printf ("%s.%s", klass->name_space, klass->name);
4676 /* Add the T[]/InternalEnumerator class */
4677 if (!strcmp (klass->name, "IEnumerable`1") || !strcmp (klass->name, "IEnumerator`1")) {
4682 while ((nclass = mono_class_get_nested_types (array_class->parent, &iter))) {
4683 if (!strcmp (nclass->name, "InternalEnumerator`1"))
4687 nclass = mono_class_inflate_generic_class_checked (nclass, mono_generic_class_get_context (klass->generic_class), &error);
4688 mono_error_assert_ok (&error); /* FIXME don't swallow the error */
4689 add_generic_class (acfg, nclass, FALSE, "ICollection<T>");
4693 while ((method = mono_class_get_methods (array_class, &iter))) {
4694 if (strstr (method->name, name_prefix)) {
4695 MonoMethod *m = mono_aot_get_array_helper_from_wrapper (method);
4697 add_extra_method_with_depth (acfg, m, depth);
4701 g_free (name_prefix);
4704 /* Add an instance of GenericComparer<T> which is created dynamically by Comparer<T> */
4705 if (klass->image == mono_defaults.corlib && !strcmp (klass->name_space, "System.Collections.Generic") && !strcmp (klass->name, "Comparer`1")) {
4707 MonoClass *tclass = mono_class_from_mono_type (klass->generic_class->context.class_inst->type_argv [0]);
4708 MonoClass *icomparable, *gcomparer, *icomparable_inst;
4709 MonoGenericContext ctx;
4710 MonoType *args [16];
4712 memset (&ctx, 0, sizeof (ctx));
4714 icomparable = mono_class_load_from_name (mono_defaults.corlib, "System", "IComparable`1");
4716 args [0] = &tclass->byval_arg;
4717 ctx.class_inst = mono_metadata_get_generic_inst (1, args);
4719 icomparable_inst = mono_class_inflate_generic_class_checked (icomparable, &ctx, &error);
4720 mono_error_assert_ok (&error); /* FIXME don't swallow the error */
4722 if (mono_class_is_assignable_from (icomparable_inst, tclass)) {
4723 MonoClass *gcomparer_inst;
4724 gcomparer = mono_class_load_from_name (mono_defaults.corlib, "System.Collections.Generic", "GenericComparer`1");
4725 gcomparer_inst = mono_class_inflate_generic_class_checked (gcomparer, &ctx, &error);
4726 mono_error_assert_ok (&error); /* FIXME don't swallow the error */
4728 add_generic_class (acfg, gcomparer_inst, FALSE, "Comparer<T>");
4732 /* Add an instance of GenericEqualityComparer<T> which is created dynamically by EqualityComparer<T> */
4733 if (klass->image == mono_defaults.corlib && !strcmp (klass->name_space, "System.Collections.Generic") && !strcmp (klass->name, "EqualityComparer`1")) {
4735 MonoClass *tclass = mono_class_from_mono_type (klass->generic_class->context.class_inst->type_argv [0]);
4736 MonoClass *iface, *gcomparer, *iface_inst;
4737 MonoGenericContext ctx;
4738 MonoType *args [16];
4740 memset (&ctx, 0, sizeof (ctx));
4742 iface = mono_class_load_from_name (mono_defaults.corlib, "System", "IEquatable`1");
4744 args [0] = &tclass->byval_arg;
4745 ctx.class_inst = mono_metadata_get_generic_inst (1, args);
4747 iface_inst = mono_class_inflate_generic_class_checked (iface, &ctx, &error);
4748 mono_error_assert_ok (&error); /* FIXME don't swallow the error */
4750 if (mono_class_is_assignable_from (iface_inst, tclass)) {
4751 MonoClass *gcomparer_inst;
4754 gcomparer = mono_class_load_from_name (mono_defaults.corlib, "System.Collections.Generic", "GenericEqualityComparer`1");
4755 gcomparer_inst = mono_class_inflate_generic_class_checked (gcomparer, &ctx, &error);
4756 mono_error_assert_ok (&error); /* FIXME don't swallow the error */
4757 add_generic_class (acfg, gcomparer_inst, FALSE, "EqualityComparer<T>");
4761 /* Add an instance of EnumComparer<T> which is created dynamically by EqualityComparer<T> for enums */
4762 if (klass->image == mono_defaults.corlib && !strcmp (klass->name_space, "System.Collections.Generic") && !strcmp (klass->name, "EqualityComparer`1")) {
4763 MonoClass *enum_comparer;
4764 MonoClass *tclass = mono_class_from_mono_type (klass->generic_class->context.class_inst->type_argv [0]);
4765 MonoGenericContext ctx;
4766 MonoType *args [16];
4768 if (mono_class_is_enum (tclass)) {
4769 MonoClass *enum_comparer_inst;
4772 memset (&ctx, 0, sizeof (ctx));
4773 args [0] = &tclass->byval_arg;
4774 ctx.class_inst = mono_metadata_get_generic_inst (1, args);
4776 enum_comparer = mono_class_load_from_name (mono_defaults.corlib, "System.Collections.Generic", "EnumEqualityComparer`1");
4777 enum_comparer_inst = mono_class_inflate_generic_class_checked (enum_comparer, &ctx, &error);
4778 mono_error_assert_ok (&error); /* FIXME don't swallow the error */
4779 add_generic_class (acfg, enum_comparer_inst, FALSE, "EqualityComparer<T>");
4783 /* Add an instance of ObjectComparer<T> which is created dynamically by Comparer<T> for enums */
4784 if (klass->image == mono_defaults.corlib && !strcmp (klass->name_space, "System.Collections.Generic") && !strcmp (klass->name, "Comparer`1")) {
4785 MonoClass *comparer;
4786 MonoClass *tclass = mono_class_from_mono_type (klass->generic_class->context.class_inst->type_argv [0]);
4787 MonoGenericContext ctx;
4788 MonoType *args [16];
4790 if (mono_class_is_enum (tclass)) {
4791 MonoClass *comparer_inst;
4794 memset (&ctx, 0, sizeof (ctx));
4795 args [0] = &tclass->byval_arg;
4796 ctx.class_inst = mono_metadata_get_generic_inst (1, args);
4798 comparer = mono_class_load_from_name (mono_defaults.corlib, "System.Collections.Generic", "ObjectComparer`1");
4799 comparer_inst = mono_class_inflate_generic_class_checked (comparer, &ctx, &error);
4800 mono_error_assert_ok (&error); /* FIXME don't swallow the error */
4801 add_generic_class (acfg, comparer_inst, FALSE, "Comparer<T>");
4807 add_instances_of (MonoAotCompile *acfg, MonoClass *klass, MonoType **insts, int ninsts, gboolean force)
4810 MonoGenericContext ctx;
4811 MonoType *args [16];
4813 if (acfg->aot_opts.no_instances)
4816 memset (&ctx, 0, sizeof (ctx));
4818 for (i = 0; i < ninsts; ++i) {
4820 MonoClass *generic_inst;
4821 args [0] = insts [i];
4822 ctx.class_inst = mono_metadata_get_generic_inst (1, args);
4823 generic_inst = mono_class_inflate_generic_class_checked (klass, &ctx, &error);
4824 mono_error_assert_ok (&error); /* FIXME don't swallow the error */
4825 add_generic_class (acfg, generic_inst, force, "");
4830 add_types_from_method_header (MonoAotCompile *acfg, MonoMethod *method)
4833 MonoMethodHeader *header;
4834 MonoMethodSignature *sig;
4837 depth = GPOINTER_TO_UINT (g_hash_table_lookup (acfg->method_depth, method));
4839 sig = mono_method_signature (method);
4842 for (j = 0; j < sig->param_count; ++j)
4843 if (sig->params [j]->type == MONO_TYPE_GENERICINST)
4844 add_generic_class_with_depth (acfg, mono_class_from_mono_type (sig->params [j]), depth + 1, "arg");
4847 header = mono_method_get_header_checked (method, &error);
4850 for (j = 0; j < header->num_locals; ++j)
4851 if (header->locals [j]->type == MONO_TYPE_GENERICINST)
4852 add_generic_class_with_depth (acfg, mono_class_from_mono_type (header->locals [j]), depth + 1, "local");
4854 mono_error_cleanup (&error); /* FIXME report the error */
4859 * add_generic_instances:
4861 * Add instances referenced by the METHODSPEC/TYPESPEC table.
4864 add_generic_instances (MonoAotCompile *acfg)
4869 MonoGenericContext *context;
4871 if (acfg->aot_opts.no_instances)
4874 for (i = 0; i < acfg->image->tables [MONO_TABLE_METHODSPEC].rows; ++i) {
4876 token = MONO_TOKEN_METHOD_SPEC | (i + 1);
4877 method = mono_get_method_checked (acfg->image, token, NULL, NULL, &error);
4880 aot_printerrf (acfg, "Failed to load methodspec 0x%x due to %s.\n", token, mono_error_get_message (&error));
4881 aot_printerrf (acfg, "Run with MONO_LOG_LEVEL=debug for more information.\n");
4882 mono_error_cleanup (&error);
4886 if (method->klass->image != acfg->image)
4889 context = mono_method_get_context (method);
4891 if (context && ((context->class_inst && context->class_inst->is_open)))
4895 * For open methods, create an instantiation which can be passed to the JIT.
4896 * FIXME: Handle class_inst as well.
4898 if (context && context->method_inst && context->method_inst->is_open) {
4900 MonoGenericContext shared_context;
4901 MonoGenericInst *inst;
4902 MonoType **type_argv;
4904 MonoMethod *declaring_method;
4905 gboolean supported = TRUE;
4907 /* Check that the context doesn't contain open constructed types */
4908 if (context->class_inst) {
4909 inst = context->class_inst;
4910 for (i = 0; i < inst->type_argc; ++i) {
4911 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)
4913 if (mono_class_is_open_constructed_type (inst->type_argv [i]))
4917 if (context->method_inst) {
4918 inst = context->method_inst;
4919 for (i = 0; i < inst->type_argc; ++i) {
4920 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)
4922 if (mono_class_is_open_constructed_type (inst->type_argv [i]))
4930 memset (&shared_context, 0, sizeof (MonoGenericContext));
4932 inst = context->class_inst;
4934 type_argv = g_new0 (MonoType*, inst->type_argc);
4935 for (i = 0; i < inst->type_argc; ++i) {
4936 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)
4937 type_argv [i] = &mono_defaults.object_class->byval_arg;
4939 type_argv [i] = inst->type_argv [i];
4942 shared_context.class_inst = mono_metadata_get_generic_inst (inst->type_argc, type_argv);
4946 inst = context->method_inst;
4948 type_argv = g_new0 (MonoType*, inst->type_argc);
4949 for (i = 0; i < inst->type_argc; ++i) {
4950 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)
4951 type_argv [i] = &mono_defaults.object_class->byval_arg;
4953 type_argv [i] = inst->type_argv [i];
4956 shared_context.method_inst = mono_metadata_get_generic_inst (inst->type_argc, type_argv);
4960 if (method->is_generic || method->klass->generic_container)
4961 declaring_method = method;
4963 declaring_method = mono_method_get_declaring_generic_method (method);
4965 method = mono_class_inflate_generic_method_checked (declaring_method, &shared_context, &error);
4966 g_assert (mono_error_ok (&error)); /* FIXME don't swallow the error */
4970 * If the method is fully sharable, it was already added in place of its
4971 * generic definition.
4973 if (mono_method_is_generic_sharable_full (method, FALSE, FALSE, FALSE))
4977 * FIXME: Partially shared methods are not shared here, so we end up with
4978 * many identical methods.
4980 add_extra_method (acfg, method);
4983 for (i = 0; i < acfg->image->tables [MONO_TABLE_TYPESPEC].rows; ++i) {
4987 token = MONO_TOKEN_TYPE_SPEC | (i + 1);
4989 klass = mono_class_get_checked (acfg->image, token, &error);
4990 if (!klass || klass->rank) {
4991 mono_error_cleanup (&error);
4995 add_generic_class (acfg, klass, FALSE, "typespec");
4998 /* Add types of args/locals */
4999 for (i = 0; i < acfg->methods->len; ++i) {
5000 method = (MonoMethod *)g_ptr_array_index (acfg->methods, i);
5001 add_types_from_method_header (acfg, method);
5004 if (acfg->image == mono_defaults.corlib) {
5006 MonoType *insts [256];
5009 insts [ninsts ++] = &mono_defaults.byte_class->byval_arg;
5010 insts [ninsts ++] = &mono_defaults.sbyte_class->byval_arg;
5011 insts [ninsts ++] = &mono_defaults.int16_class->byval_arg;
5012 insts [ninsts ++] = &mono_defaults.uint16_class->byval_arg;
5013 insts [ninsts ++] = &mono_defaults.int32_class->byval_arg;
5014 insts [ninsts ++] = &mono_defaults.uint32_class->byval_arg;
5015 insts [ninsts ++] = &mono_defaults.int64_class->byval_arg;
5016 insts [ninsts ++] = &mono_defaults.uint64_class->byval_arg;
5017 insts [ninsts ++] = &mono_defaults.single_class->byval_arg;
5018 insts [ninsts ++] = &mono_defaults.double_class->byval_arg;
5019 insts [ninsts ++] = &mono_defaults.char_class->byval_arg;
5020 insts [ninsts ++] = &mono_defaults.boolean_class->byval_arg;
5022 /* Add GenericComparer<T> instances for primitive types for Enum.ToString () */
5023 klass = mono_class_try_load_from_name (acfg->image, "System.Collections.Generic", "GenericComparer`1");
5025 add_instances_of (acfg, klass, insts, ninsts, TRUE);
5026 klass = mono_class_try_load_from_name (acfg->image, "System.Collections.Generic", "GenericEqualityComparer`1");
5028 add_instances_of (acfg, klass, insts, ninsts, TRUE);
5030 /* Add instances of EnumEqualityComparer which are created by EqualityComparer<T> for enums */
5032 MonoClass *enum_comparer;
5033 MonoType *insts [16];
5037 insts [ninsts ++] = &mono_defaults.int32_class->byval_arg;
5038 insts [ninsts ++] = &mono_defaults.uint32_class->byval_arg;
5039 insts [ninsts ++] = &mono_defaults.uint16_class->byval_arg;
5040 insts [ninsts ++] = &mono_defaults.byte_class->byval_arg;
5041 enum_comparer = mono_class_load_from_name (mono_defaults.corlib, "System.Collections.Generic", "EnumEqualityComparer`1");
5042 add_instances_of (acfg, enum_comparer, insts, ninsts, FALSE);
5045 insts [ninsts ++] = &mono_defaults.int16_class->byval_arg;
5046 enum_comparer = mono_class_load_from_name (mono_defaults.corlib, "System.Collections.Generic", "ShortEnumEqualityComparer`1");
5047 add_instances_of (acfg, enum_comparer, insts, ninsts, FALSE);
5050 insts [ninsts ++] = &mono_defaults.sbyte_class->byval_arg;
5051 enum_comparer = mono_class_load_from_name (mono_defaults.corlib, "System.Collections.Generic", "SByteEnumEqualityComparer`1");
5052 add_instances_of (acfg, enum_comparer, insts, ninsts, FALSE);
5054 enum_comparer = mono_class_load_from_name (mono_defaults.corlib, "System.Collections.Generic", "LongEnumEqualityComparer`1");
5056 insts [ninsts ++] = &mono_defaults.int64_class->byval_arg;
5057 insts [ninsts ++] = &mono_defaults.uint64_class->byval_arg;
5058 add_instances_of (acfg, enum_comparer, insts, ninsts, FALSE);
5061 /* Add instances of the array generic interfaces for primitive types */
5062 /* This will add instances of the InternalArray_ helper methods in Array too */
5063 klass = mono_class_try_load_from_name (acfg->image, "System.Collections.Generic", "ICollection`1");
5065 add_instances_of (acfg, klass, insts, ninsts, TRUE);
5067 klass = mono_class_try_load_from_name (acfg->image, "System.Collections.Generic", "IList`1");
5069 add_instances_of (acfg, klass, insts, ninsts, TRUE);
5071 klass = mono_class_try_load_from_name (acfg->image, "System.Collections.Generic", "IEnumerable`1");
5073 add_instances_of (acfg, klass, insts, ninsts, TRUE);
5076 * Add a managed-to-native wrapper of Array.GetGenericValueImpl<object>, which is
5077 * used for all instances of GetGenericValueImpl by the AOT runtime.
5080 MonoGenericContext ctx;
5081 MonoType *args [16];
5082 MonoMethod *get_method;
5083 MonoClass *array_klass = mono_array_class_get (mono_defaults.object_class, 1)->parent;
5085 get_method = mono_class_get_method_from_name (array_klass, "GetGenericValueImpl", 2);
5089 memset (&ctx, 0, sizeof (ctx));
5090 args [0] = &mono_defaults.object_class->byval_arg;
5091 ctx.method_inst = mono_metadata_get_generic_inst (1, args);
5092 add_extra_method (acfg, mono_marshal_get_native_wrapper (mono_class_inflate_generic_method_checked (get_method, &ctx, &error), TRUE, TRUE));
5093 g_assert (mono_error_ok (&error)); /* FIXME don't swallow the error */
5097 /* Same for CompareExchange<T>/Exchange<T> */
5099 MonoGenericContext ctx;
5100 MonoType *args [16];
5102 MonoClass *interlocked_klass = mono_class_load_from_name (mono_defaults.corlib, "System.Threading", "Interlocked");
5103 gpointer iter = NULL;
5105 while ((m = mono_class_get_methods (interlocked_klass, &iter))) {
5106 if ((!strcmp (m->name, "CompareExchange") || !strcmp (m->name, "Exchange")) && m->is_generic) {
5108 memset (&ctx, 0, sizeof (ctx));
5109 args [0] = &mono_defaults.object_class->byval_arg;
5110 ctx.method_inst = mono_metadata_get_generic_inst (1, args);
5111 add_extra_method (acfg, mono_marshal_get_native_wrapper (mono_class_inflate_generic_method_checked (m, &ctx, &error), TRUE, TRUE));
5112 g_assert (mono_error_ok (&error)); /* FIXME don't swallow the error */
5117 /* Same for Volatile.Read/Write<T> */
5119 MonoGenericContext ctx;
5120 MonoType *args [16];
5122 MonoClass *volatile_klass = mono_class_try_load_from_name (mono_defaults.corlib, "System.Threading", "Volatile");
5123 gpointer iter = NULL;
5125 if (volatile_klass) {
5126 while ((m = mono_class_get_methods (volatile_klass, &iter))) {
5127 if ((!strcmp (m->name, "Read") || !strcmp (m->name, "Write")) && m->is_generic) {
5129 memset (&ctx, 0, sizeof (ctx));
5130 args [0] = &mono_defaults.object_class->byval_arg;
5131 ctx.method_inst = mono_metadata_get_generic_inst (1, args);
5132 add_extra_method (acfg, mono_marshal_get_native_wrapper (mono_class_inflate_generic_method_checked (m, &ctx, &error), TRUE, TRUE));
5133 g_assert (mono_error_ok (&error)); /* FIXME don't swallow the error */
5139 /* object[] accessor wrappers. */
5141 MonoClass *obj_array_class = mono_array_class_get (mono_defaults.object_class, 1);
5144 m = mono_class_get_method_from_name (obj_array_class, "Get", 1);
5147 m = mono_marshal_get_array_accessor_wrapper (m);
5148 add_extra_method (acfg, m);
5150 m = mono_class_get_method_from_name (obj_array_class, "Address", 1);
5153 m = mono_marshal_get_array_accessor_wrapper (m);
5154 add_extra_method (acfg, m);
5156 m = mono_class_get_method_from_name (obj_array_class, "Set", 2);
5159 m = mono_marshal_get_array_accessor_wrapper (m);
5160 add_extra_method (acfg, m);
5166 * is_direct_callable:
5168 * Return whenever the method identified by JI is directly callable without
5169 * going through the PLT.
5172 is_direct_callable (MonoAotCompile *acfg, MonoMethod *method, MonoJumpInfo *patch_info)
5174 if ((patch_info->type == MONO_PATCH_INFO_METHOD) && (patch_info->data.method->klass->image == acfg->image)) {
5175 MonoCompile *callee_cfg = (MonoCompile *)g_hash_table_lookup (acfg->method_to_cfg, patch_info->data.method);
5177 gboolean direct_callable = TRUE;
5179 if (direct_callable && !(!callee_cfg->has_got_slots && (callee_cfg->method->klass->flags & TYPE_ATTRIBUTE_BEFORE_FIELD_INIT)))
5180 direct_callable = FALSE;
5181 if ((callee_cfg->method->iflags & METHOD_IMPL_ATTRIBUTE_SYNCHRONIZED) && (!method || method->wrapper_type != MONO_WRAPPER_SYNCHRONIZED))
5182 // FIXME: Maybe call the wrapper directly ?
5183 direct_callable = FALSE;
5185 if (acfg->aot_opts.soft_debug || acfg->aot_opts.no_direct_calls) {
5186 /* Disable this so all calls go through load_method (), see the
5187 * mini_get_debug_options ()->load_aot_jit_info_eagerly = TRUE; line in
5188 * mono_debugger_agent_init ().
5190 direct_callable = FALSE;
5193 if (callee_cfg->method->wrapper_type == MONO_WRAPPER_ALLOC)
5194 /* sgen does some initialization when the allocator method is created */
5195 direct_callable = FALSE;
5196 if (callee_cfg->method->wrapper_type == MONO_WRAPPER_WRITE_BARRIER)
5197 /* we don't know at compile time whether sgen is concurrent or not */
5198 direct_callable = FALSE;
5200 if (direct_callable)
5203 } else if ((patch_info->type == MONO_PATCH_INFO_ICALL_ADDR_CALL && patch_info->data.method->flags & METHOD_ATTRIBUTE_PINVOKE_IMPL)) {
5204 if (acfg->aot_opts.direct_pinvoke)
5206 } else if (patch_info->type == MONO_PATCH_INFO_ICALL_ADDR_CALL) {
5207 if (acfg->aot_opts.direct_icalls)
5215 #ifdef MONO_ARCH_AOT_SUPPORTED
5217 get_pinvoke_import (MonoAotCompile *acfg, MonoMethod *method)
5219 MonoImage *image = method->klass->image;
5220 MonoMethodPInvoke *piinfo = (MonoMethodPInvoke *) method;
5221 MonoTableInfo *tables = image->tables;
5222 MonoTableInfo *im = &tables [MONO_TABLE_IMPLMAP];
5223 MonoTableInfo *mr = &tables [MONO_TABLE_MODULEREF];
5224 guint32 im_cols [MONO_IMPLMAP_SIZE];
5227 import = (char *)g_hash_table_lookup (acfg->method_to_pinvoke_import, method);
5231 if (!piinfo->implmap_idx || piinfo->implmap_idx > im->rows)
5234 mono_metadata_decode_row (im, piinfo->implmap_idx - 1, im_cols, MONO_IMPLMAP_SIZE);
5236 if (!im_cols [MONO_IMPLMAP_SCOPE] || im_cols [MONO_IMPLMAP_SCOPE] > mr->rows)
5239 import = g_strdup_printf ("%s", mono_metadata_string_heap (image, im_cols [MONO_IMPLMAP_NAME]));
5241 g_hash_table_insert (acfg->method_to_pinvoke_import, method, import);
5247 get_pinvoke_import (MonoAotCompile *acfg, MonoMethod *method)
5254 compare_lne (MonoDebugLineNumberEntry *a, MonoDebugLineNumberEntry *b)
5256 if (a->native_offset == b->native_offset)
5257 return a->il_offset - b->il_offset;
5259 return a->native_offset - b->native_offset;
5263 * compute_line_numbers:
5265 * Returns a sparse array of size CODE_SIZE containing MonoDebugSourceLocation* entries for the native offsets which have a corresponding line number
5268 static MonoDebugSourceLocation**
5269 compute_line_numbers (MonoMethod *method, int code_size, MonoDebugMethodJitInfo *debug_info)
5271 MonoDebugMethodInfo *minfo;
5272 MonoDebugLineNumberEntry *ln_array;
5273 MonoDebugSourceLocation *loc;
5274 int i, prev_line, prev_il_offset;
5275 int *native_to_il_offset = NULL;
5276 MonoDebugSourceLocation **res;
5279 minfo = mono_debug_lookup_method (method);
5282 // FIXME: This seems to happen when two methods have the same cfg->method_to_register
5283 if (debug_info->code_size != code_size)
5286 g_assert (code_size);
5288 /* Compute the native->IL offset mapping */
5290 ln_array = g_new0 (MonoDebugLineNumberEntry, debug_info->num_line_numbers);
5291 memcpy (ln_array, debug_info->line_numbers, debug_info->num_line_numbers * sizeof (MonoDebugLineNumberEntry));
5293 qsort (ln_array, debug_info->num_line_numbers, sizeof (MonoDebugLineNumberEntry), (int (*)(const void *, const void *))compare_lne);
5295 native_to_il_offset = g_new0 (int, code_size + 1);
5297 for (i = 0; i < debug_info->num_line_numbers; ++i) {
5299 MonoDebugLineNumberEntry *lne = &ln_array [i];
5302 for (j = 0; j < lne->native_offset; ++j)
5303 native_to_il_offset [j] = -1;
5306 if (i < debug_info->num_line_numbers - 1) {
5307 MonoDebugLineNumberEntry *lne_next = &ln_array [i + 1];
5309 for (j = lne->native_offset; j < lne_next->native_offset; ++j)
5310 native_to_il_offset [j] = lne->il_offset;
5312 for (j = lne->native_offset; j < code_size; ++j)
5313 native_to_il_offset [j] = lne->il_offset;
5318 /* Compute the native->line number mapping */
5319 res = g_new0 (MonoDebugSourceLocation*, code_size);
5320 prev_il_offset = -1;
5323 for (i = 0; i < code_size; ++i) {
5324 int il_offset = native_to_il_offset [i];
5326 if (il_offset == -1 || il_offset == prev_il_offset)
5328 prev_il_offset = il_offset;
5329 loc = mono_debug_symfile_lookup_location (minfo, il_offset);
5330 if (!(loc && loc->source_file))
5332 if (loc->row == prev_line) {
5333 mono_debug_symfile_free_location (loc);
5336 prev_line = loc->row;
5337 //printf ("D: %s:%d il=%x native=%x\n", loc->source_file, loc->row, il_offset, i);
5339 /* This will cover the prolog too */
5349 get_file_index (MonoAotCompile *acfg, const char *source_file)
5353 // FIXME: Free these
5354 if (!acfg->dwarf_ln_filenames)
5355 acfg->dwarf_ln_filenames = g_hash_table_new (g_str_hash, g_str_equal);
5356 findex = GPOINTER_TO_INT (g_hash_table_lookup (acfg->dwarf_ln_filenames, source_file));
5358 findex = g_hash_table_size (acfg->dwarf_ln_filenames) + 1;
5359 g_hash_table_insert (acfg->dwarf_ln_filenames, g_strdup (source_file), GINT_TO_POINTER (findex));
5360 emit_unset_mode (acfg);
5361 fprintf (acfg->fp, ".file %d \"%s\"\n", findex, mono_dwarf_escape_path (source_file));
5373 * emit_and_reloc_code:
5375 * Emit the native code in CODE, handling relocations along the way. If GOT_ONLY
5376 * is true, calls are made through the GOT too. This is used for emitting trampolines
5377 * in full-aot mode, since calls made from trampolines couldn't go through the PLT,
5378 * since trampolines are needed to make PTL work.
5381 emit_and_reloc_code (MonoAotCompile *acfg, MonoMethod *method, guint8 *code, guint32 code_len, MonoJumpInfo *relocs, gboolean got_only, MonoDebugMethodJitInfo *debug_info)
5383 int i, pindex, start_index;
5385 MonoJumpInfo *patch_info;
5386 MonoDebugSourceLocation **locs = NULL;
5387 gboolean skip, prologue_end = FALSE;
5388 #ifdef MONO_ARCH_AOT_SUPPORTED
5389 gboolean direct_call, external_call;
5391 const char *direct_call_target = 0;
5392 const char *direct_pinvoke;
5395 if (acfg->gas_line_numbers && method && debug_info) {
5396 locs = compute_line_numbers (method, code_len, debug_info);
5398 int findex = get_file_index (acfg, "<unknown>");
5399 emit_unset_mode (acfg);
5400 fprintf (acfg->fp, ".loc %d %d 0\n", findex, 1);
5404 /* Collect and sort relocations */
5405 patches = g_ptr_array_new ();
5406 for (patch_info = relocs; patch_info; patch_info = patch_info->next)
5407 g_ptr_array_add (patches, patch_info);
5408 g_ptr_array_sort (patches, compare_patches);
5411 for (i = 0; i < code_len; i += INST_LEN) {
5413 for (pindex = start_index; pindex < patches->len; ++pindex) {
5414 patch_info = (MonoJumpInfo *)g_ptr_array_index (patches, pindex);
5415 if (patch_info->ip.i >= i)
5419 if (locs && locs [i]) {
5420 MonoDebugSourceLocation *loc = locs [i];
5422 const char *options;
5424 findex = get_file_index (acfg, loc->source_file);
5425 emit_unset_mode (acfg);
5427 options = " prologue_end";
5430 prologue_end = TRUE;
5431 fprintf (acfg->fp, ".loc %d %d 0%s\n", findex, loc->row, options);
5432 mono_debug_symfile_free_location (loc);
5436 #ifdef MONO_ARCH_AOT_SUPPORTED
5437 if (patch_info && (patch_info->ip.i == i) && (pindex < patches->len)) {
5438 start_index = pindex;
5440 switch (patch_info->type) {
5441 case MONO_PATCH_INFO_NONE:
5443 case MONO_PATCH_INFO_GOT_OFFSET: {
5446 arch_emit_got_offset (acfg, code + i, &code_size);
5447 i += code_size - INST_LEN;
5449 patch_info->type = MONO_PATCH_INFO_NONE;
5452 case MONO_PATCH_INFO_OBJC_SELECTOR_REF: {
5453 int code_size, index;
5454 char *selector = (char *)patch_info->data.target;
5456 if (!acfg->objc_selector_to_index)
5457 acfg->objc_selector_to_index = g_hash_table_new (g_str_hash, g_str_equal);
5458 if (!acfg->objc_selectors)
5459 acfg->objc_selectors = g_ptr_array_new ();
5460 index = GPOINTER_TO_UINT (g_hash_table_lookup (acfg->objc_selector_to_index, selector));
5464 index = acfg->objc_selector_index;
5465 g_ptr_array_add (acfg->objc_selectors, (void*)patch_info->data.target);
5466 g_hash_table_insert (acfg->objc_selector_to_index, selector, GUINT_TO_POINTER (index + 1));
5467 acfg->objc_selector_index ++;
5470 arch_emit_objc_selector_ref (acfg, code + i, index, &code_size);
5471 i += code_size - INST_LEN;
5473 patch_info->type = MONO_PATCH_INFO_NONE;
5478 * If this patch is a call, try emitting a direct call instead of
5479 * through a PLT entry. This is possible if the called method is in
5480 * the same assembly and requires no initialization.
5482 direct_call = FALSE;
5483 external_call = FALSE;
5484 if ((patch_info->type == MONO_PATCH_INFO_METHOD) && (patch_info->data.method->klass->image == acfg->image)) {
5485 if (!got_only && is_direct_callable (acfg, method, patch_info)) {
5486 MonoCompile *callee_cfg = (MonoCompile *)g_hash_table_lookup (acfg->method_to_cfg, patch_info->data.method);
5487 //printf ("DIRECT: %s %s\n", method ? mono_method_full_name (method, TRUE) : "", mono_method_full_name (callee_cfg->method, TRUE));
5489 direct_call_target = callee_cfg->asm_symbol;
5490 patch_info->type = MONO_PATCH_INFO_NONE;
5491 acfg->stats.direct_calls ++;
5494 acfg->stats.all_calls ++;
5495 } else if (patch_info->type == MONO_PATCH_INFO_ICALL_ADDR_CALL) {
5496 if (!got_only && is_direct_callable (acfg, method, patch_info)) {
5497 if (!(patch_info->data.method->flags & METHOD_ATTRIBUTE_PINVOKE_IMPL))
5498 direct_pinvoke = mono_lookup_icall_symbol (patch_info->data.method);
5500 direct_pinvoke = get_pinvoke_import (acfg, patch_info->data.method);
5501 if (direct_pinvoke) {
5503 g_assert (strlen (direct_pinvoke) < 1000);
5504 direct_call_target = g_strdup_printf ("%s%s", acfg->user_symbol_prefix, direct_pinvoke);
5507 } else if (patch_info->type == MONO_PATCH_INFO_JIT_ICALL_ADDR) {
5508 const char *sym = mono_lookup_jit_icall_symbol (patch_info->data.name);
5509 if (!got_only && sym && acfg->aot_opts.direct_icalls) {
5510 /* Call to a C function implementing a jit icall */
5512 external_call = TRUE;
5513 g_assert (strlen (sym) < 1000);
5514 direct_call_target = g_strdup_printf ("%s%s", acfg->user_symbol_prefix, sym);
5516 } else if (patch_info->type == MONO_PATCH_INFO_INTERNAL_METHOD) {
5517 MonoJitICallInfo *info = mono_find_jit_icall_by_name (patch_info->data.name);
5518 const char *sym = mono_lookup_jit_icall_symbol (patch_info->data.name);
5519 if (!got_only && sym && acfg->aot_opts.direct_icalls && info->func == info->wrapper) {
5520 /* Call to a jit icall without a wrapper */
5522 external_call = TRUE;
5523 g_assert (strlen (sym) < 1000);
5524 direct_call_target = g_strdup_printf ("%s%s", acfg->user_symbol_prefix, sym);
5529 patch_info->type = MONO_PATCH_INFO_NONE;
5530 acfg->stats.direct_calls ++;
5533 if (!got_only && !direct_call) {
5534 MonoPltEntry *plt_entry = get_plt_entry (acfg, patch_info);
5536 /* This patch has a PLT entry, so we must emit a call to the PLT entry */
5538 direct_call_target = plt_entry->symbol;
5540 /* Nullify the patch */
5541 patch_info->type = MONO_PATCH_INFO_NONE;
5542 plt_entry->jit_used = TRUE;
5549 arch_emit_direct_call (acfg, direct_call_target, external_call, FALSE, patch_info, &call_size);
5550 i += call_size - INST_LEN;
5554 got_slot = get_got_offset (acfg, FALSE, patch_info);
5556 arch_emit_got_access (acfg, acfg->got_symbol, code + i, got_slot, &code_size);
5557 i += code_size - INST_LEN;
5563 #endif /* MONO_ARCH_AOT_SUPPORTED */
5566 /* Find next patch */
5568 for (pindex = start_index; pindex < patches->len; ++pindex) {
5569 patch_info = (MonoJumpInfo *)g_ptr_array_index (patches, pindex);
5570 if (patch_info->ip.i >= i)
5574 /* Try to emit multiple bytes at once */
5575 if (pindex < patches->len && patch_info->ip.i > i) {
5578 for (limit = i + INST_LEN; limit < patch_info->ip.i; limit += INST_LEN) {
5579 if (locs && locs [limit])
5583 emit_code_bytes (acfg, code + i, limit - i);
5584 i = limit - INST_LEN;
5586 emit_code_bytes (acfg, code + i, INST_LEN);
5597 * Return a modified version of S which only includes characters permissible in symbols.
5600 sanitize_symbol (MonoAotCompile *acfg, char *s)
5602 gboolean process = FALSE;
5611 for (i = 0; i < len; ++i)
5612 if (!(s [i] <= 0x7f && (isalnum (s [i]) || s [i] == '_')))
5617 gs = g_string_sized_new (len);
5618 for (i = 0; i < len; ++i) {
5620 if (c <= 0x7f && (isalnum (c) || c == '_')) {
5621 g_string_append_c (gs, c);
5622 } else if (c > 0x7f) {
5623 /* multi-byte utf8 */
5624 g_string_append_printf (gs, "_0x%x", c);
5627 while (c >> 6 == 0x2) {
5628 g_string_append_printf (gs, "%x", c);
5632 g_string_append_printf (gs, "_");
5635 g_string_append_c (gs, '_');
5639 res = mono_mempool_strdup (acfg->mempool, gs->str);
5640 g_string_free (gs, TRUE);
5645 get_debug_sym (MonoMethod *method, const char *prefix, GHashTable *cache)
5647 char *name1, *name2, *cached;
5648 int i, j, len, count;
5649 MonoMethod *cached_method;
5651 name1 = mono_method_full_name (method, TRUE);
5654 // This is so that we don't accidentally create a local symbol (which starts with 'L')
5655 if ((!prefix || !*prefix) && name1 [0] == 'L')
5659 #if defined(TARGET_WIN32) && defined(TARGET_X86)
5660 char adjustedPrefix [MAX_SYMBOL_SIZE];
5661 prefix = mangle_symbol (prefix, adjustedPrefix, G_N_ELEMENTS (adjustedPrefix));
5664 len = strlen (name1);
5665 name2 = (char *)malloc (strlen (prefix) + len + 16);
5666 memcpy (name2, prefix, strlen (prefix));
5667 j = strlen (prefix);
5668 for (i = 0; i < len; ++i) {
5669 if (i == 0 && name1 [0] >= '0' && name1 [0] <= '9') {
5671 } else if (isalnum (name1 [i])) {
5672 name2 [j ++] = name1 [i];
5673 } else if (name1 [i] == ' ' && name1 [i + 1] == '(' && name1 [i + 2] == ')') {
5675 } else if (name1 [i] == ',' && name1 [i + 1] == ' ') {
5678 } else if (name1 [i] == '(' || name1 [i] == ')' || name1 [i] == '>') {
5688 cached_method = (MonoMethod *)g_hash_table_lookup (cache, name2);
5689 if (!(cached_method && cached_method != method))
5691 sprintf (name2 + j, "_%d", count);
5695 cached = g_strdup (name2);
5696 g_hash_table_insert (cache, cached, method);
5702 emit_method_code (MonoAotCompile *acfg, MonoCompile *cfg)
5707 char *debug_sym = NULL;
5708 char *symbol = NULL;
5709 int func_alignment = AOT_FUNC_ALIGNMENT;
5712 method = cfg->orig_method;
5713 code = cfg->native_code;
5715 method_index = get_method_index (acfg, method);
5716 symbol = g_strdup_printf ("%sme_%x", acfg->temp_prefix, method_index);
5718 /* Make the labels local */
5719 emit_section_change (acfg, ".text", 0);
5720 emit_alignment_code (acfg, func_alignment);
5722 if (acfg->global_symbols && acfg->need_no_dead_strip)
5723 fprintf (acfg->fp, " .no_dead_strip %s\n", cfg->asm_symbol);
5725 emit_label (acfg, cfg->asm_symbol);
5727 if (acfg->aot_opts.write_symbols && !acfg->global_symbols && !acfg->llvm) {
5729 * Write a C style symbol for every method, this has two uses:
5730 * - it works on platforms where the dwarf debugging info is not
5732 * - it allows the setting of breakpoints of aot-ed methods.
5734 debug_sym = get_debug_sym (method, "", acfg->method_label_hash);
5735 cfg->asm_debug_symbol = g_strdup (debug_sym);
5737 if (acfg->need_no_dead_strip)
5738 fprintf (acfg->fp, " .no_dead_strip %s\n", debug_sym);
5739 emit_local_symbol (acfg, debug_sym, symbol, TRUE);
5740 emit_label (acfg, debug_sym);
5743 export_name = (char *)g_hash_table_lookup (acfg->export_names, method);
5745 /* Emit a global symbol for the method */
5746 emit_global_inner (acfg, export_name, TRUE);
5747 emit_label (acfg, export_name);
5750 if (cfg->verbose_level > 0)
5751 g_print ("Method %s emitted as %s\n", mono_method_get_full_name (method), cfg->asm_symbol);
5753 acfg->stats.code_size += cfg->code_len;
5755 acfg->cfgs [method_index]->got_offset = acfg->got_offset;
5757 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 ()));
5761 if (acfg->aot_opts.write_symbols) {
5763 emit_symbol_size (acfg, debug_sym, ".");
5765 emit_symbol_size (acfg, cfg->asm_symbol, ".");
5769 emit_label (acfg, symbol);
5776 * Encode PATCH_INFO into its disk representation.
5779 encode_patch (MonoAotCompile *acfg, MonoJumpInfo *patch_info, guint8 *buf, guint8 **endbuf)
5783 switch (patch_info->type) {
5784 case MONO_PATCH_INFO_NONE:
5786 case MONO_PATCH_INFO_IMAGE:
5787 encode_value (get_image_index (acfg, patch_info->data.image), p, &p);
5789 case MONO_PATCH_INFO_MSCORLIB_GOT_ADDR:
5790 case MONO_PATCH_INFO_JIT_TLS_ID:
5791 case MONO_PATCH_INFO_GC_CARD_TABLE_ADDR:
5792 case MONO_PATCH_INFO_GC_NURSERY_START:
5793 case MONO_PATCH_INFO_GC_NURSERY_BITS:
5795 case MONO_PATCH_INFO_CASTCLASS_CACHE:
5796 encode_value (patch_info->data.index, p, &p);
5798 case MONO_PATCH_INFO_METHOD_REL:
5799 encode_value ((gint)patch_info->data.offset, p, &p);
5801 case MONO_PATCH_INFO_SWITCH: {
5802 gpointer *table = (gpointer *)patch_info->data.table->table;
5805 encode_value (patch_info->data.table->table_size, p, &p);
5806 for (k = 0; k < patch_info->data.table->table_size; k++)
5807 encode_value ((int)(gssize)table [k], p, &p);
5810 case MONO_PATCH_INFO_METHODCONST:
5811 case MONO_PATCH_INFO_METHOD:
5812 case MONO_PATCH_INFO_METHOD_JUMP:
5813 case MONO_PATCH_INFO_ICALL_ADDR:
5814 case MONO_PATCH_INFO_ICALL_ADDR_CALL:
5815 case MONO_PATCH_INFO_METHOD_RGCTX:
5816 case MONO_PATCH_INFO_METHOD_CODE_SLOT:
5817 encode_method_ref (acfg, patch_info->data.method, p, &p);
5819 case MONO_PATCH_INFO_AOT_JIT_INFO:
5820 encode_value (patch_info->data.index, p, &p);
5822 case MONO_PATCH_INFO_INTERNAL_METHOD:
5823 case MONO_PATCH_INFO_JIT_ICALL_ADDR: {
5824 guint32 len = strlen (patch_info->data.name);
5826 encode_value (len, p, &p);
5828 memcpy (p, patch_info->data.name, len);
5833 case MONO_PATCH_INFO_LDSTR: {
5834 guint32 image_index = get_image_index (acfg, patch_info->data.token->image);
5835 guint32 token = patch_info->data.token->token;
5836 g_assert (mono_metadata_token_code (token) == MONO_TOKEN_STRING);
5837 encode_value (image_index, p, &p);
5838 encode_value (patch_info->data.token->token - MONO_TOKEN_STRING, p, &p);
5841 case MONO_PATCH_INFO_RVA:
5842 case MONO_PATCH_INFO_DECLSEC:
5843 case MONO_PATCH_INFO_LDTOKEN:
5844 case MONO_PATCH_INFO_TYPE_FROM_HANDLE:
5845 encode_value (get_image_index (acfg, patch_info->data.token->image), p, &p);
5846 encode_value (patch_info->data.token->token, p, &p);
5847 encode_value (patch_info->data.token->has_context, p, &p);
5848 if (patch_info->data.token->has_context)
5849 encode_generic_context (acfg, &patch_info->data.token->context, p, &p);
5851 case MONO_PATCH_INFO_EXC_NAME: {
5852 MonoClass *ex_class;
5855 mono_class_load_from_name (mono_defaults.exception_class->image,
5856 "System", (const char *)patch_info->data.target);
5857 encode_klass_ref (acfg, ex_class, p, &p);
5860 case MONO_PATCH_INFO_R4:
5861 encode_value (*((guint32 *)patch_info->data.target), p, &p);
5863 case MONO_PATCH_INFO_R8:
5864 encode_value (((guint32 *)patch_info->data.target) [MINI_LS_WORD_IDX], p, &p);
5865 encode_value (((guint32 *)patch_info->data.target) [MINI_MS_WORD_IDX], p, &p);
5867 case MONO_PATCH_INFO_VTABLE:
5868 case MONO_PATCH_INFO_CLASS:
5869 case MONO_PATCH_INFO_IID:
5870 case MONO_PATCH_INFO_ADJUSTED_IID:
5871 encode_klass_ref (acfg, patch_info->data.klass, p, &p);
5873 case MONO_PATCH_INFO_DELEGATE_TRAMPOLINE:
5874 encode_klass_ref (acfg, patch_info->data.del_tramp->klass, p, &p);
5875 if (patch_info->data.del_tramp->method) {
5876 encode_value (1, p, &p);
5877 encode_method_ref (acfg, patch_info->data.del_tramp->method, p, &p);
5879 encode_value (0, p, &p);
5881 encode_value (patch_info->data.del_tramp->is_virtual, p, &p);
5883 case MONO_PATCH_INFO_FIELD:
5884 case MONO_PATCH_INFO_SFLDA:
5885 encode_field_info (acfg, patch_info->data.field, p, &p);
5887 case MONO_PATCH_INFO_INTERRUPTION_REQUEST_FLAG:
5889 case MONO_PATCH_INFO_RGCTX_FETCH:
5890 case MONO_PATCH_INFO_RGCTX_SLOT_INDEX: {
5891 MonoJumpInfoRgctxEntry *entry = patch_info->data.rgctx_entry;
5896 * entry->method has a lenghtly encoding and multiple rgctx_fetch entries
5897 * reference the same method, so encode the method only once.
5899 offset = GPOINTER_TO_UINT (g_hash_table_lookup (acfg->method_blob_hash, entry->method));
5901 buf2 = (guint8 *)g_malloc (1024);
5904 encode_method_ref (acfg, entry->method, p2, &p2);
5905 g_assert (p2 - buf2 < 1024);
5907 offset = add_to_blob (acfg, buf2, p2 - buf2);
5910 g_hash_table_insert (acfg->method_blob_hash, entry->method, GUINT_TO_POINTER (offset + 1));
5915 encode_value (offset, p, &p);
5916 g_assert ((int)entry->info_type < 256);
5917 g_assert (entry->data->type < 256);
5918 encode_value ((entry->in_mrgctx ? 1 : 0) | (entry->info_type << 1) | (entry->data->type << 9), p, &p);
5919 encode_patch (acfg, entry->data, p, &p);
5922 case MONO_PATCH_INFO_SEQ_POINT_INFO:
5923 case MONO_PATCH_INFO_AOT_MODULE:
5925 case MONO_PATCH_INFO_SIGNATURE:
5926 case MONO_PATCH_INFO_GSHAREDVT_IN_WRAPPER:
5927 encode_signature (acfg, (MonoMethodSignature*)patch_info->data.target, p, &p);
5929 case MONO_PATCH_INFO_TLS_OFFSET:
5930 encode_value (GPOINTER_TO_INT (patch_info->data.target), p, &p);
5932 case MONO_PATCH_INFO_GSHAREDVT_CALL:
5933 encode_signature (acfg, (MonoMethodSignature*)patch_info->data.gsharedvt->sig, p, &p);
5934 encode_method_ref (acfg, patch_info->data.gsharedvt->method, p, &p);
5936 case MONO_PATCH_INFO_GSHAREDVT_METHOD: {
5937 MonoGSharedVtMethodInfo *info = patch_info->data.gsharedvt_method;
5940 encode_method_ref (acfg, info->method, p, &p);
5941 encode_value (info->num_entries, p, &p);
5942 for (i = 0; i < info->num_entries; ++i) {
5943 MonoRuntimeGenericContextInfoTemplate *template_ = &info->entries [i];
5945 encode_value (template_->info_type, p, &p);
5946 switch (mini_rgctx_info_type_to_patch_info_type (template_->info_type)) {
5947 case MONO_PATCH_INFO_CLASS:
5948 encode_klass_ref (acfg, mono_class_from_mono_type ((MonoType *)template_->data), p, &p);
5950 case MONO_PATCH_INFO_FIELD:
5951 encode_field_info (acfg, (MonoClassField *)template_->data, p, &p);
5954 g_assert_not_reached ();
5960 case MONO_PATCH_INFO_LDSTR_LIT: {
5961 const char *s = (const char *)patch_info->data.target;
5962 int len = strlen (s);
5964 encode_value (len, p, &p);
5965 memcpy (p, s, len + 1);
5969 case MONO_PATCH_INFO_VIRT_METHOD:
5970 encode_klass_ref (acfg, patch_info->data.virt_method->klass, p, &p);
5971 encode_method_ref (acfg, patch_info->data.virt_method->method, p, &p);
5973 case MONO_PATCH_INFO_GC_SAFE_POINT_FLAG:
5976 g_warning ("unable to handle jump info %d", patch_info->type);
5977 g_assert_not_reached ();
5984 encode_patch_list (MonoAotCompile *acfg, GPtrArray *patches, int n_patches, gboolean llvm, int first_got_offset, guint8 *buf, guint8 **endbuf)
5987 guint32 pindex, offset;
5988 MonoJumpInfo *patch_info;
5990 encode_value (n_patches, p, &p);
5992 for (pindex = 0; pindex < patches->len; ++pindex) {
5993 patch_info = (MonoJumpInfo *)g_ptr_array_index (patches, pindex);
5995 if (patch_info->type == MONO_PATCH_INFO_NONE || patch_info->type == MONO_PATCH_INFO_BB)
5999 offset = get_got_offset (acfg, llvm, patch_info);
6000 encode_value (offset, p, &p);
6007 emit_method_info (MonoAotCompile *acfg, MonoCompile *cfg)
6010 int pindex, buf_size, n_patches;
6012 MonoJumpInfo *patch_info;
6013 guint32 method_index;
6015 guint32 first_got_offset;
6017 method = cfg->orig_method;
6019 method_index = get_method_index (acfg, method);
6021 /* Sort relocations */
6022 patches = g_ptr_array_new ();
6023 for (patch_info = cfg->patch_info; patch_info; patch_info = patch_info->next)
6024 g_ptr_array_add (patches, patch_info);
6025 g_ptr_array_sort (patches, compare_patches);
6027 first_got_offset = acfg->cfgs [method_index]->got_offset;
6029 /**********************/
6030 /* Encode method info */
6031 /**********************/
6033 buf_size = (patches->len < 1000) ? 40960 : 40960 + (patches->len * 64);
6034 p = buf = (guint8 *)g_malloc (buf_size);
6036 if (mono_class_get_cctor (method->klass)) {
6037 encode_value (1, p, &p);
6038 encode_klass_ref (acfg, method->klass, p, &p);
6040 /* Not needed when loading the method */
6041 encode_value (0, p, &p);
6044 g_assert (!(cfg->opt & MONO_OPT_SHARED));
6047 for (pindex = 0; pindex < patches->len; ++pindex) {
6048 patch_info = (MonoJumpInfo *)g_ptr_array_index (patches, pindex);
6050 if ((patch_info->type == MONO_PATCH_INFO_GOT_OFFSET) ||
6051 (patch_info->type == MONO_PATCH_INFO_NONE)) {
6052 patch_info->type = MONO_PATCH_INFO_NONE;
6057 if ((patch_info->type == MONO_PATCH_INFO_IMAGE) && (patch_info->data.image == acfg->image)) {
6058 /* Stored in a GOT slot initialized at module load time */
6059 patch_info->type = MONO_PATCH_INFO_NONE;
6063 if (patch_info->type == MONO_PATCH_INFO_GC_CARD_TABLE_ADDR ||
6064 patch_info->type == MONO_PATCH_INFO_GC_NURSERY_START ||
6065 patch_info->type == MONO_PATCH_INFO_GC_NURSERY_BITS ||
6066 patch_info->type == MONO_PATCH_INFO_AOT_MODULE) {
6067 /* Stored in a GOT slot initialized at module load time */
6068 patch_info->type = MONO_PATCH_INFO_NONE;
6072 if (is_plt_patch (patch_info) && !(cfg->compile_llvm && acfg->aot_opts.llvm_only)) {
6073 /* Calls are made through the PLT */
6074 patch_info->type = MONO_PATCH_INFO_NONE;
6082 g_assert (cfg->has_got_slots);
6084 encode_patch_list (acfg, patches, n_patches, cfg->compile_llvm, first_got_offset, p, &p);
6086 acfg->stats.info_size += p - buf;
6088 g_assert (p - buf < buf_size);
6090 cfg->method_info_offset = add_to_blob (acfg, buf, p - buf);
6095 get_unwind_info_offset (MonoAotCompile *acfg, guint8 *encoded, guint32 encoded_len)
6097 guint32 cache_index;
6100 /* Reuse the unwind module to canonize and store unwind info entries */
6101 cache_index = mono_cache_unwind_info (encoded, encoded_len);
6103 /* Use +/- 1 to distinguish 0s from missing entries */
6104 offset = GPOINTER_TO_UINT (g_hash_table_lookup (acfg->unwind_info_offsets, GUINT_TO_POINTER (cache_index + 1)));
6112 * It would be easier to use assembler symbols, but the caller needs an
6115 offset = acfg->unwind_info_offset;
6116 g_hash_table_insert (acfg->unwind_info_offsets, GUINT_TO_POINTER (cache_index + 1), GUINT_TO_POINTER (offset + 1));
6117 g_ptr_array_add (acfg->unwind_ops, GUINT_TO_POINTER (cache_index));
6120 encode_value (encoded_len, p, &p);
6122 acfg->unwind_info_offset += encoded_len + (p - buf);
6128 emit_exception_debug_info (MonoAotCompile *acfg, MonoCompile *cfg, gboolean store_seq_points)
6131 guint32 debug_info_size, seq_points_size;
6133 MonoMethodHeader *header;
6134 guint8 *p, *buf, *debug_info;
6135 MonoJitInfo *jinfo = cfg->jit_info;
6137 gboolean use_unwind_ops = FALSE;
6138 MonoSeqPointInfo *seq_points;
6140 code = cfg->native_code;
6141 header = cfg->header;
6143 if (!acfg->aot_opts.nodebug) {
6144 mono_debug_serialize_debug_info (cfg, &debug_info, &debug_info_size);
6147 debug_info_size = 0;
6150 seq_points = cfg->seq_point_info;
6151 seq_points_size = (store_seq_points)? mono_seq_point_info_get_write_size (seq_points) : 0;
6153 buf_size = header->num_clauses * 256 + debug_info_size + 2048 + seq_points_size + cfg->gc_map_size;
6155 p = buf = (guint8 *)g_malloc (buf_size);
6157 use_unwind_ops = cfg->unwind_ops != NULL;
6159 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);
6161 encode_value (flags, p, &p);
6163 if (use_unwind_ops) {
6164 guint32 encoded_len;
6166 guint32 unwind_desc;
6168 encoded = mono_unwind_ops_encode (cfg->unwind_ops, &encoded_len);
6170 unwind_desc = get_unwind_info_offset (acfg, encoded, encoded_len);
6171 encode_value (unwind_desc, p, &p);
6173 encode_value (jinfo->unwind_info, p, &p);
6176 /*Encode the number of holes before the number of clauses to make decoding easier*/
6177 if (jinfo->has_try_block_holes) {
6178 MonoTryBlockHoleTableJitInfo *table = mono_jit_info_get_try_block_hole_table_info (jinfo);
6179 encode_value (table->num_holes, p, &p);
6182 if (jinfo->has_arch_eh_info) {
6184 * In AOT mode, the code length is calculated from the address of the previous method,
6185 * which could include alignment padding, so calculating the start of the epilog as
6186 * code_len - epilog_size is correct any more. Save the real code len as a workaround.
6188 encode_value (jinfo->code_size, p, &p);
6191 /* Exception table */
6192 if (cfg->compile_llvm) {
6194 * When using LLVM, we can't emit some data, like pc offsets, this reg/offset etc.,
6195 * since the information is only available to llc. Instead, we let llc save the data
6196 * into the LSDA, and read it from there at runtime.
6198 /* The assembly might be CIL stripped so emit the data ourselves */
6199 if (header->num_clauses)
6200 encode_value (header->num_clauses, p, &p);
6202 for (k = 0; k < header->num_clauses; ++k) {
6203 MonoExceptionClause *clause;
6205 clause = &header->clauses [k];
6207 encode_value (clause->flags, p, &p);
6208 if (clause->data.catch_class) {
6209 encode_value (1, p, &p);
6210 encode_klass_ref (acfg, clause->data.catch_class, p, &p);
6212 encode_value (0, p, &p);
6215 /* Emit the IL ranges too, since they might not be available at runtime */
6216 encode_value (clause->try_offset, p, &p);
6217 encode_value (clause->try_len, p, &p);
6218 encode_value (clause->handler_offset, p, &p);
6219 encode_value (clause->handler_len, p, &p);
6221 /* Emit a list of nesting clauses */
6222 for (i = 0; i < header->num_clauses; ++i) {
6224 MonoExceptionClause *clause1 = &header->clauses [cindex1];
6226 MonoExceptionClause *clause2 = &header->clauses [cindex2];
6228 if (cindex1 != cindex2 && clause1->try_offset >= clause2->try_offset && clause1->handler_offset <= clause2->handler_offset)
6229 encode_value (i, p, &p);
6231 encode_value (-1, p, &p);
6234 if (jinfo->num_clauses)
6235 encode_value (jinfo->num_clauses, p, &p);
6237 for (k = 0; k < jinfo->num_clauses; ++k) {
6238 MonoJitExceptionInfo *ei = &jinfo->clauses [k];
6240 encode_value (ei->flags, p, &p);
6241 #ifdef MONO_CONTEXT_SET_LLVM_EXC_REG
6242 /* Not used for catch clauses */
6243 if (ei->flags != MONO_EXCEPTION_CLAUSE_NONE)
6244 encode_value (ei->exvar_offset, p, &p);
6246 encode_value (ei->exvar_offset, p, &p);
6249 if (ei->flags == MONO_EXCEPTION_CLAUSE_FILTER || ei->flags == MONO_EXCEPTION_CLAUSE_FINALLY)
6250 encode_value ((gint)((guint8*)ei->data.filter - code), p, &p);
6252 if (ei->data.catch_class) {
6256 buf2 = (guint8 *)g_malloc (4096);
6258 encode_klass_ref (acfg, ei->data.catch_class, p2, &p2);
6260 g_assert (len < 4096);
6261 encode_value (len, p, &p);
6262 memcpy (p, buf2, len);
6266 encode_value (0, p, &p);
6270 encode_value ((gint)((guint8*)ei->try_start - code), p, &p);
6271 encode_value ((gint)((guint8*)ei->try_end - code), p, &p);
6272 encode_value ((gint)((guint8*)ei->handler_start - code), p, &p);
6276 if (jinfo->has_try_block_holes) {
6277 MonoTryBlockHoleTableJitInfo *table = mono_jit_info_get_try_block_hole_table_info (jinfo);
6278 for (i = 0; i < table->num_holes; ++i) {
6279 MonoTryBlockHoleJitInfo *hole = &table->holes [i];
6280 encode_value (hole->clause, p, &p);
6281 encode_value (hole->length, p, &p);
6282 encode_value (hole->offset, p, &p);
6286 if (jinfo->has_arch_eh_info) {
6287 MonoArchEHJitInfo *eh_info;
6289 eh_info = mono_jit_info_get_arch_eh_info (jinfo);
6290 encode_value (eh_info->stack_size, p, &p);
6291 encode_value (eh_info->epilog_size, p, &p);
6294 if (jinfo->has_generic_jit_info) {
6295 MonoGenericJitInfo *gi = mono_jit_info_get_generic_jit_info (jinfo);
6296 MonoGenericSharingContext* gsctx = gi->generic_sharing_context;
6300 encode_value (gi->nlocs, p, &p);
6302 for (i = 0; i < gi->nlocs; ++i) {
6303 MonoDwarfLocListEntry *entry = &gi->locations [i];
6305 encode_value (entry->is_reg ? 1 : 0, p, &p);
6306 encode_value (entry->reg, p, &p);
6308 encode_value (entry->offset, p, &p);
6310 g_assert (entry->from == 0);
6312 encode_value (entry->from, p, &p);
6313 encode_value (entry->to, p, &p);
6316 if (!cfg->compile_llvm) {
6317 encode_value (gi->has_this ? 1 : 0, p, &p);
6318 encode_value (gi->this_reg, p, &p);
6319 encode_value (gi->this_offset, p, &p);
6324 * Need to encode jinfo->method too, since it is not equal to 'method'
6325 * when using generic sharing.
6327 buf2 = (guint8 *)g_malloc (4096);
6329 encode_method_ref (acfg, jinfo->d.method, p2, &p2);
6331 g_assert (len < 4096);
6332 encode_value (len, p, &p);
6333 memcpy (p, buf2, len);
6337 if (gsctx && gsctx->is_gsharedvt) {
6338 encode_value (1, p, &p);
6340 encode_value (0, p, &p);
6344 if (seq_points_size)
6345 p += mono_seq_point_info_write (seq_points, p);
6347 g_assert (debug_info_size < buf_size);
6349 encode_value (debug_info_size, p, &p);
6350 if (debug_info_size) {
6351 memcpy (p, debug_info, debug_info_size);
6352 p += debug_info_size;
6353 g_free (debug_info);
6358 encode_value (cfg->gc_map_size, p, &p);
6359 /* The GC map requires 4 bytes of alignment */
6360 while ((gsize)p % 4)
6362 memcpy (p, cfg->gc_map, cfg->gc_map_size);
6363 p += cfg->gc_map_size;
6366 acfg->stats.ex_info_size += p - buf;
6368 g_assert (p - buf < buf_size);
6371 /* The GC Map requires 4 byte alignment */
6372 cfg->ex_info_offset = add_to_blob_aligned (acfg, buf, p - buf, cfg->gc_map ? 4 : 1);
6377 emit_klass_info (MonoAotCompile *acfg, guint32 token)
6380 MonoClass *klass = mono_class_get_checked (acfg->image, token, &error);
6382 int i, buf_size, res;
6383 gboolean no_special_static, cant_encode;
6384 gpointer iter = NULL;
6387 mono_error_cleanup (&error);
6391 p = buf = (guint8 *)g_malloc (buf_size);
6393 /* Mark as unusable */
6394 encode_value (-1, p, &p);
6396 res = add_to_blob (acfg, buf, p - buf);
6402 buf_size = 10240 + (klass->vtable_size * 16);
6403 p = buf = (guint8 *)g_malloc (buf_size);
6407 mono_class_init (klass);
6409 mono_class_get_nested_types (klass, &iter);
6410 g_assert (klass->nested_classes_inited);
6412 mono_class_setup_vtable (klass);
6415 * Emit all the information which is required for creating vtables so
6416 * the runtime does not need to create the MonoMethod structures which
6417 * take up a lot of space.
6420 no_special_static = !mono_class_has_special_static_fields (klass);
6422 /* Check whenever we have enough info to encode the vtable */
6423 cant_encode = FALSE;
6424 for (i = 0; i < klass->vtable_size; ++i) {
6425 MonoMethod *cm = klass->vtable [i];
6427 if (cm && mono_method_signature (cm)->is_inflated && !g_hash_table_lookup (acfg->token_info_hash, cm))
6431 mono_class_has_finalizer (klass);
6433 if (klass->generic_container || cant_encode) {
6434 encode_value (-1, p, &p);
6436 encode_value (klass->vtable_size, p, &p);
6437 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);
6438 if (klass->has_cctor)
6439 encode_method_ref (acfg, mono_class_get_cctor (klass), p, &p);
6440 if (klass->has_finalize)
6441 encode_method_ref (acfg, mono_class_get_finalizer (klass), p, &p);
6443 encode_value (klass->instance_size, p, &p);
6444 encode_value (mono_class_data_size (klass), p, &p);
6445 encode_value (klass->packing_size, p, &p);
6446 encode_value (klass->min_align, p, &p);
6448 for (i = 0; i < klass->vtable_size; ++i) {
6449 MonoMethod *cm = klass->vtable [i];
6452 encode_method_ref (acfg, cm, p, &p);
6454 encode_value (0, p, &p);
6458 acfg->stats.class_info_size += p - buf;
6460 g_assert (p - buf < buf_size);
6461 res = add_to_blob (acfg, buf, p - buf);
6468 get_plt_entry_debug_sym (MonoAotCompile *acfg, MonoJumpInfo *ji, GHashTable *cache)
6470 char *debug_sym = NULL;
6473 if (acfg->llvm && llvm_acfg->aot_opts.static_link) {
6474 /* Need to add a prefix to create unique symbols */
6475 prefix = g_strdup_printf ("plt_%s_", acfg->assembly_name_sym);
6477 #if defined(TARGET_WIN32) && defined(TARGET_X86)
6478 prefix = mangle_symbol_alloc ("plt_");
6480 prefix = g_strdup ("plt_");
6485 case MONO_PATCH_INFO_METHOD:
6486 debug_sym = get_debug_sym (ji->data.method, prefix, cache);
6488 case MONO_PATCH_INFO_INTERNAL_METHOD:
6489 debug_sym = g_strdup_printf ("%s_jit_icall_%s", prefix, ji->data.name);
6491 case MONO_PATCH_INFO_RGCTX_FETCH:
6492 debug_sym = g_strdup_printf ("%s_rgctx_fetch_%d", prefix, acfg->label_generator ++);
6494 case MONO_PATCH_INFO_ICALL_ADDR:
6495 case MONO_PATCH_INFO_ICALL_ADDR_CALL: {
6496 char *s = get_debug_sym (ji->data.method, "", cache);
6498 debug_sym = g_strdup_printf ("%s_icall_native_%s", prefix, s);
6502 case MONO_PATCH_INFO_JIT_ICALL_ADDR:
6503 debug_sym = g_strdup_printf ("%s_jit_icall_native_%s", prefix, ji->data.name);
6511 return sanitize_symbol (acfg, debug_sym);
6515 * Calls made from AOTed code are routed through a table of jumps similar to the
6516 * ELF PLT (Program Linkage Table). Initially the PLT entries jump to code which transfers
6517 * control to the AOT runtime through a trampoline.
6520 emit_plt (MonoAotCompile *acfg)
6524 if (acfg->aot_opts.llvm_only) {
6525 g_assert (acfg->plt_offset == 1);
6531 emit_section_change (acfg, ".text", 0);
6532 emit_alignment_code (acfg, NACL_SIZE(16, kNaClAlignment));
6533 emit_info_symbol (acfg, "plt");
6534 emit_label (acfg, acfg->plt_symbol);
6536 for (i = 0; i < acfg->plt_offset; ++i) {
6537 char *debug_sym = NULL;
6538 MonoPltEntry *plt_entry = NULL;
6542 * The first plt entry is unused.
6546 plt_entry = (MonoPltEntry *)g_hash_table_lookup (acfg->plt_offset_to_entry, GUINT_TO_POINTER (i));
6548 debug_sym = plt_entry->debug_sym;
6550 if (acfg->thumb_mixed && !plt_entry->jit_used)
6551 /* Emit only a thumb version */
6554 /* Skip plt entries not actually called */
6555 if (!plt_entry->jit_used && !plt_entry->llvm_used)
6558 if (acfg->llvm && !acfg->thumb_mixed) {
6559 emit_label (acfg, plt_entry->llvm_symbol);
6561 emit_global_inner (acfg, plt_entry->llvm_symbol, TRUE);
6562 #if defined(TARGET_MACH)
6563 fprintf (acfg->fp, ".private_extern %s\n", plt_entry->llvm_symbol);
6569 if (acfg->need_no_dead_strip) {
6570 emit_unset_mode (acfg);
6571 fprintf (acfg->fp, " .no_dead_strip %s\n", debug_sym);
6573 emit_local_symbol (acfg, debug_sym, NULL, TRUE);
6574 emit_label (acfg, debug_sym);
6577 emit_label (acfg, plt_entry->symbol);
6579 arch_emit_plt_entry (acfg, acfg->got_symbol, (acfg->plt_got_offset_base + i) * sizeof (gpointer), acfg->plt_got_info_offsets [i]);
6582 emit_symbol_size (acfg, debug_sym, ".");
6585 if (acfg->thumb_mixed) {
6586 /* Make sure the ARM symbols don't alias the thumb ones */
6587 emit_zero_bytes (acfg, 16);
6590 * Emit a separate set of PLT entries using thumb2 which is called by LLVM generated
6593 for (i = 0; i < acfg->plt_offset; ++i) {
6594 char *debug_sym = NULL;
6595 MonoPltEntry *plt_entry = NULL;
6600 plt_entry = (MonoPltEntry *)g_hash_table_lookup (acfg->plt_offset_to_entry, GUINT_TO_POINTER (i));
6602 /* Skip plt entries not actually called by LLVM code */
6603 if (!plt_entry->llvm_used)
6606 if (acfg->aot_opts.write_symbols) {
6607 if (plt_entry->debug_sym)
6608 debug_sym = g_strdup_printf ("%s_thumb", plt_entry->debug_sym);
6612 #if defined(TARGET_MACH)
6613 fprintf (acfg->fp, " .thumb_func %s\n", debug_sym);
6614 fprintf (acfg->fp, " .no_dead_strip %s\n", debug_sym);
6616 emit_local_symbol (acfg, debug_sym, NULL, TRUE);
6617 emit_label (acfg, debug_sym);
6619 fprintf (acfg->fp, "\n.thumb_func\n");
6621 emit_label (acfg, plt_entry->llvm_symbol);
6624 emit_global_inner (acfg, plt_entry->llvm_symbol, TRUE);
6626 arch_emit_llvm_plt_entry (acfg, acfg->got_symbol, (acfg->plt_got_offset_base + i) * sizeof (gpointer), acfg->plt_got_info_offsets [i]);
6629 emit_symbol_size (acfg, debug_sym, ".");
6635 emit_symbol_size (acfg, acfg->plt_symbol, ".");
6637 emit_info_symbol (acfg, "plt_end");
6641 * emit_trampoline_full:
6643 * If EMIT_TINFO is TRUE, emit additional information which can be used to create a MonoJitInfo for this trampoline by
6644 * create_jit_info_for_trampoline ().
6646 static G_GNUC_UNUSED void
6647 emit_trampoline_full (MonoAotCompile *acfg, int got_offset, MonoTrampInfo *info, gboolean emit_tinfo)
6649 char start_symbol [MAX_SYMBOL_SIZE];
6650 char end_symbol [MAX_SYMBOL_SIZE];
6651 char symbol [MAX_SYMBOL_SIZE];
6652 guint32 buf_size, info_offset;
6653 MonoJumpInfo *patch_info;
6666 code_size = info->code_size;
6668 unwind_ops = info->unwind_ops;
6670 #ifdef __native_client_codegen__
6671 mono_nacl_fix_patches (code, ji);
6676 sprintf (start_symbol, "%s%s", acfg->user_symbol_prefix, name);
6678 emit_section_change (acfg, ".text", 0);
6679 emit_global (acfg, start_symbol, TRUE);
6680 emit_alignment_code (acfg, AOT_FUNC_ALIGNMENT);
6681 emit_label (acfg, start_symbol);
6683 sprintf (symbol, "%snamed_%s", acfg->temp_prefix, name);
6684 emit_label (acfg, symbol);
6687 * The code should access everything through the GOT, so we pass
6690 emit_and_reloc_code (acfg, NULL, code, code_size, ji, TRUE, NULL);
6692 emit_symbol_size (acfg, start_symbol, ".");
6695 sprintf (end_symbol, "%snamede_%s", acfg->temp_prefix, name);
6696 emit_label (acfg, end_symbol);
6701 /* Sort relocations */
6702 patches = g_ptr_array_new ();
6703 for (patch_info = ji; patch_info; patch_info = patch_info->next)
6704 if (patch_info->type != MONO_PATCH_INFO_NONE)
6705 g_ptr_array_add (patches, patch_info);
6706 g_ptr_array_sort (patches, compare_patches);
6708 buf_size = patches->len * 128 + 128;
6709 buf = (guint8 *)g_malloc (buf_size);
6712 encode_patch_list (acfg, patches, patches->len, FALSE, got_offset, p, &p);
6713 g_assert (p - buf < buf_size);
6715 sprintf (symbol, "%s%s_p", acfg->user_symbol_prefix, name);
6717 info_offset = add_to_blob (acfg, buf, p - buf);
6719 emit_section_change (acfg, RODATA_SECT, 0);
6720 emit_global (acfg, symbol, FALSE);
6721 emit_label (acfg, symbol);
6723 emit_int32 (acfg, info_offset);
6727 guint32 encoded_len;
6731 * Emit additional information which can be used to reconstruct a partial MonoTrampInfo.
6733 encoded = mono_unwind_ops_encode (info->unwind_ops, &encoded_len);
6734 uw_offset = get_unwind_info_offset (acfg, encoded, encoded_len);
6737 emit_symbol_diff (acfg, end_symbol, start_symbol, 0);
6738 emit_int32 (acfg, uw_offset);
6741 /* Emit debug info */
6743 char symbol2 [MAX_SYMBOL_SIZE];
6745 sprintf (symbol, "%s", name);
6746 sprintf (symbol2, "%snamed_%s", acfg->temp_prefix, name);
6749 mono_dwarf_writer_emit_trampoline (acfg->dwarf, symbol, symbol2, NULL, NULL, code_size, unwind_ops);
6753 static G_GNUC_UNUSED void
6754 emit_trampoline (MonoAotCompile *acfg, int got_offset, MonoTrampInfo *info)
6756 emit_trampoline_full (acfg, got_offset, info, TRUE);
6760 emit_trampolines (MonoAotCompile *acfg)
6762 char symbol [MAX_SYMBOL_SIZE];
6763 char end_symbol [MAX_SYMBOL_SIZE];
6764 int i, tramp_got_offset;
6766 #ifdef MONO_ARCH_HAVE_FULL_AOT_TRAMPOLINES
6770 if (!mono_aot_mode_is_full (&acfg->aot_opts) || acfg->aot_opts.llvm_only)
6773 g_assert (acfg->image->assembly);
6775 /* Currently, we emit most trampolines into the mscorlib AOT image. */
6776 if (strcmp (acfg->image->assembly->aname.name, "mscorlib") == 0) {
6777 #ifdef MONO_ARCH_HAVE_FULL_AOT_TRAMPOLINES
6778 MonoTrampInfo *info;
6781 * Emit the generic trampolines.
6783 * We could save some code by treating the generic trampolines as a wrapper
6784 * method, but that approach has its own complexities, so we choose the simpler
6787 for (tramp_type = 0; tramp_type < MONO_TRAMPOLINE_NUM; ++tramp_type) {
6788 /* we overload the boolean here to indicate the slightly different trampoline needed, see mono_arch_create_generic_trampoline() */
6789 #ifdef DISABLE_REMOTING
6790 if (tramp_type == MONO_TRAMPOLINE_GENERIC_VIRTUAL_REMOTING)
6793 #ifndef MONO_ARCH_HAVE_HANDLER_BLOCK_GUARD
6794 if (tramp_type == MONO_TRAMPOLINE_HANDLER_BLOCK_GUARD)
6797 mono_arch_create_generic_trampoline ((MonoTrampolineType)tramp_type, &info, acfg->aot_opts.use_trampolines_page? 2: TRUE);
6798 emit_trampoline (acfg, acfg->got_offset, info);
6801 /* Emit the exception related code pieces */
6802 mono_arch_get_restore_context (&info, TRUE);
6803 emit_trampoline (acfg, acfg->got_offset, info);
6804 mono_arch_get_call_filter (&info, TRUE);
6805 emit_trampoline (acfg, acfg->got_offset, info);
6806 mono_arch_get_throw_exception (&info, TRUE);
6807 emit_trampoline (acfg, acfg->got_offset, info);
6808 mono_arch_get_rethrow_exception (&info, TRUE);
6809 emit_trampoline (acfg, acfg->got_offset, info);
6810 mono_arch_get_throw_corlib_exception (&info, TRUE);
6811 emit_trampoline (acfg, acfg->got_offset, info);
6813 #ifdef MONO_ARCH_HAVE_SDB_TRAMPOLINES
6814 mono_arch_create_sdb_trampoline (TRUE, &info, TRUE);
6815 emit_trampoline (acfg, acfg->got_offset, info);
6816 mono_arch_create_sdb_trampoline (FALSE, &info, TRUE);
6817 emit_trampoline (acfg, acfg->got_offset, info);
6820 #ifdef MONO_ARCH_GSHAREDVT_SUPPORTED
6821 mono_arch_get_gsharedvt_trampoline (&info, TRUE);
6823 emit_trampoline_full (acfg, acfg->got_offset, info, TRUE);
6825 /* Create a separate out trampoline for more information in stack traces */
6826 info->name = g_strdup ("gsharedvt_out_trampoline");
6827 emit_trampoline_full (acfg, acfg->got_offset, info, TRUE);
6831 #if defined(MONO_ARCH_HAVE_GET_TRAMPOLINES)
6833 GSList *l = mono_arch_get_trampolines (TRUE);
6836 MonoTrampInfo *info = (MonoTrampInfo *)l->data;
6838 emit_trampoline (acfg, acfg->got_offset, info);
6844 for (i = 0; i < acfg->aot_opts.nrgctx_fetch_trampolines; ++i) {
6847 offset = MONO_RGCTX_SLOT_MAKE_RGCTX (i);
6848 mono_arch_create_rgctx_lazy_fetch_trampoline (offset, &info, TRUE);
6849 emit_trampoline (acfg, acfg->got_offset, info);
6851 offset = MONO_RGCTX_SLOT_MAKE_MRGCTX (i);
6852 mono_arch_create_rgctx_lazy_fetch_trampoline (offset, &info, TRUE);
6853 emit_trampoline (acfg, acfg->got_offset, info);
6856 #ifdef MONO_ARCH_HAVE_GENERAL_RGCTX_LAZY_FETCH_TRAMPOLINE
6857 mono_arch_create_general_rgctx_lazy_fetch_trampoline (&info, TRUE);
6858 emit_trampoline (acfg, acfg->got_offset, info);
6864 /* delegate_invoke_impl trampolines */
6865 l = mono_arch_get_delegate_invoke_impls ();
6867 MonoTrampInfo *info = (MonoTrampInfo *)l->data;
6869 emit_trampoline (acfg, acfg->got_offset, info);
6874 #endif /* #ifdef MONO_ARCH_HAVE_FULL_AOT_TRAMPOLINES */
6876 /* Emit trampolines which are numerous */
6879 * These include the following:
6880 * - specific trampolines
6881 * - static rgctx invoke trampolines
6883 * These trampolines have the same code, they are parameterized by GOT
6885 * They are defined in this file, in the arch_... routines instead of
6886 * in tramp-<ARCH>.c, since it is easier to do it this way.
6890 * When running in aot-only mode, we can't create specific trampolines at
6891 * runtime, so we create a few, and save them in the AOT file.
6892 * Normal trampolines embed their argument as a literal inside the
6893 * trampoline code, we can't do that here, so instead we embed an offset
6894 * which needs to be added to the trampoline address to get the address of
6895 * the GOT slot which contains the argument value.
6896 * The generated trampolines jump to the generic trampolines using another
6897 * GOT slot, which will be setup by the AOT loader to point to the
6898 * generic trampoline code of the given type.
6902 * FIXME: Maybe we should use more specific trampolines (i.e. one class init for
6906 emit_section_change (acfg, ".text", 0);
6908 tramp_got_offset = acfg->got_offset;
6910 for (ntype = 0; ntype < MONO_AOT_TRAMP_NUM; ++ntype) {
6912 case MONO_AOT_TRAMP_SPECIFIC:
6913 sprintf (symbol, "specific_trampolines");
6915 case MONO_AOT_TRAMP_STATIC_RGCTX:
6916 sprintf (symbol, "static_rgctx_trampolines");
6918 case MONO_AOT_TRAMP_IMT_THUNK:
6919 sprintf (symbol, "imt_thunks");
6921 case MONO_AOT_TRAMP_GSHAREDVT_ARG:
6922 sprintf (symbol, "gsharedvt_arg_trampolines");
6925 g_assert_not_reached ();
6928 sprintf (end_symbol, "%s_e", symbol);
6930 if (acfg->aot_opts.write_symbols)
6931 emit_local_symbol (acfg, symbol, end_symbol, TRUE);
6933 emit_alignment_code (acfg, AOT_FUNC_ALIGNMENT);
6934 emit_info_symbol (acfg, symbol);
6936 acfg->trampoline_got_offset_base [ntype] = tramp_got_offset;
6938 for (i = 0; i < acfg->num_trampolines [ntype]; ++i) {
6942 case MONO_AOT_TRAMP_SPECIFIC:
6943 arch_emit_specific_trampoline (acfg, tramp_got_offset, &tramp_size);
6944 tramp_got_offset += 2;
6946 case MONO_AOT_TRAMP_STATIC_RGCTX:
6947 arch_emit_static_rgctx_trampoline (acfg, tramp_got_offset, &tramp_size);
6948 tramp_got_offset += 2;
6950 case MONO_AOT_TRAMP_IMT_THUNK:
6951 arch_emit_imt_thunk (acfg, tramp_got_offset, &tramp_size);
6952 tramp_got_offset += 1;
6954 case MONO_AOT_TRAMP_GSHAREDVT_ARG:
6955 arch_emit_gsharedvt_arg_trampoline (acfg, tramp_got_offset, &tramp_size);
6956 tramp_got_offset += 2;
6959 g_assert_not_reached ();
6961 #ifdef __native_client_codegen__
6962 /* align to avoid 32-byte boundary crossings */
6963 emit_alignment (acfg, AOT_FUNC_ALIGNMENT);
6966 if (!acfg->trampoline_size [ntype]) {
6967 g_assert (tramp_size);
6968 acfg->trampoline_size [ntype] = tramp_size;
6972 emit_label (acfg, end_symbol);
6973 emit_int32 (acfg, 0);
6976 arch_emit_specific_trampoline_pages (acfg);
6978 /* Reserve some entries at the end of the GOT for our use */
6979 acfg->num_trampoline_got_entries = tramp_got_offset - acfg->got_offset;
6982 acfg->got_offset += acfg->num_trampoline_got_entries;
6986 str_begins_with (const char *str1, const char *str2)
6988 int len = strlen (str2);
6989 return strncmp (str1, str2, len) == 0;
6993 mono_aot_readonly_field_override (MonoClassField *field)
6996 for (rdv = readonly_values; rdv; rdv = rdv->next) {
6997 char *p = rdv->name;
6999 len = strlen (field->parent->name_space);
7000 if (strncmp (p, field->parent->name_space, len))
7005 len = strlen (field->parent->name);
7006 if (strncmp (p, field->parent->name, len))
7011 if (strcmp (p, field->name))
7013 switch (rdv->type) {
7015 return &rdv->value.i1;
7017 return &rdv->value.i2;
7019 return &rdv->value.i4;
7028 add_readonly_value (MonoAotOptions *opts, const char *val)
7033 /* the format of val is:
7034 * namespace.typename.fieldname=type/value
7035 * type can be i1 for uint8/int8/boolean, i2 for uint16/int16/char, i4 for uint32/int32
7037 fval = strrchr (val, '/');
7039 fprintf (stderr, "AOT : invalid format for readonly field '%s', missing /.\n", val);
7042 tval = strrchr (val, '=');
7044 fprintf (stderr, "AOT : invalid format for readonly field '%s', missing =.\n", val);
7047 rdv = g_new0 (ReadOnlyValue, 1);
7048 rdv->name = (char *)g_malloc0 (tval - val + 1);
7049 memcpy (rdv->name, val, tval - val);
7052 if (strncmp (tval, "i1", 2) == 0) {
7053 rdv->value.i1 = atoi (fval);
7054 rdv->type = MONO_TYPE_I1;
7055 } else if (strncmp (tval, "i2", 2) == 0) {
7056 rdv->value.i2 = atoi (fval);
7057 rdv->type = MONO_TYPE_I2;
7058 } else if (strncmp (tval, "i4", 2) == 0) {
7059 rdv->value.i4 = atoi (fval);
7060 rdv->type = MONO_TYPE_I4;
7062 fprintf (stderr, "AOT : unsupported type for readonly field '%s'.\n", tval);
7065 rdv->next = readonly_values;
7066 readonly_values = rdv;
7070 clean_path (gchar * path)
7075 if (g_str_has_suffix (path, G_DIR_SEPARATOR_S))
7078 gchar *clean = g_strconcat (path, G_DIR_SEPARATOR_S, NULL);
7085 wrap_path (gchar * path)
7091 // If the string contains no spaces, just return the original string.
7092 if (strstr (path, " ") == NULL)
7095 // If the string is already wrapped in quotes, return it.
7096 len = strlen (path);
7097 if (len >= 2 && path[0] == '\"' && path[len-1] == '\"')
7100 // If the string contains spaces, then wrap it in quotes.
7101 gchar *clean = g_strdup_printf ("\"%s\"", path);
7106 // Duplicate a char range and add it to a ptrarray, but only if it is nonempty
7108 ptr_array_add_range_if_nonempty(GPtrArray *args, gchar const *start, gchar const *end)
7110 ptrdiff_t len = end-start;
7112 g_ptr_array_add (args, g_strndup (start, len));
7116 mono_aot_split_options (const char *aot_options)
7118 enum MonoAotOptionState {
7119 MONO_AOT_OPTION_STATE_DEFAULT,
7120 MONO_AOT_OPTION_STATE_STRING,
7121 MONO_AOT_OPTION_STATE_ESCAPE,
7124 GPtrArray *args = g_ptr_array_new ();
7125 enum MonoAotOptionState state = MONO_AOT_OPTION_STATE_DEFAULT;
7126 gchar const *opt_start = aot_options;
7127 gboolean end_of_string = FALSE;
7130 g_return_val_if_fail (aot_options != NULL, NULL);
7132 while ((cur = *aot_options) != '\0') {
7133 if (state == MONO_AOT_OPTION_STATE_ESCAPE)
7138 // If we find a quote, then if we're in the default case then
7139 // it means we've found the start of a string, if not then it
7140 // means we've found the end of the string and should switch
7141 // back to the default case.
7143 case MONO_AOT_OPTION_STATE_DEFAULT:
7144 state = MONO_AOT_OPTION_STATE_STRING;
7146 case MONO_AOT_OPTION_STATE_STRING:
7147 state = MONO_AOT_OPTION_STATE_DEFAULT;
7149 case MONO_AOT_OPTION_STATE_ESCAPE:
7150 g_assert_not_reached ();
7155 // If we've found an escaping operator, then this means we
7156 // should not process the next character if inside a string.
7157 if (state == MONO_AOT_OPTION_STATE_STRING)
7158 state = MONO_AOT_OPTION_STATE_ESCAPE;
7161 // If we're in the default state then this means we've found
7162 // an option, store it for later processing.
7163 if (state == MONO_AOT_OPTION_STATE_DEFAULT)
7171 // If the next character is end of string, then process the last option.
7172 if (*(aot_options) == '\0') {
7173 end_of_string = TRUE;
7179 ptr_array_add_range_if_nonempty (args, opt_start, aot_options);
7180 opt_start = ++aot_options;
7183 goto restart; // Check for null and continue loop
7190 mono_aot_parse_options (const char *aot_options, MonoAotOptions *opts)
7194 args = mono_aot_split_options (aot_options ? aot_options : "");
7195 for (int i = 0; i < args->len; ++i) {
7196 const char *arg = (const char *)g_ptr_array_index (args, i);
7198 if (str_begins_with (arg, "outfile=")) {
7199 opts->outfile = g_strdup (arg + strlen ("outfile="));
7200 } else if (str_begins_with (arg, "llvm-outfile=")) {
7201 opts->llvm_outfile = g_strdup (arg + strlen ("llvm-outfile="));
7202 } else if (str_begins_with (arg, "temp-path=")) {
7203 opts->temp_path = clean_path (g_strdup (arg + strlen ("temp-path=")));
7204 } else if (str_begins_with (arg, "save-temps")) {
7205 opts->save_temps = TRUE;
7206 } else if (str_begins_with (arg, "keep-temps")) {
7207 opts->save_temps = TRUE;
7208 } else if (str_begins_with (arg, "write-symbols")) {
7209 opts->write_symbols = TRUE;
7210 } else if (str_begins_with (arg, "no-write-symbols")) {
7211 opts->write_symbols = FALSE;
7212 } else if (str_begins_with (arg, "metadata-only")) {
7213 opts->metadata_only = TRUE;
7214 } else if (str_begins_with (arg, "bind-to-runtime-version")) {
7215 opts->bind_to_runtime_version = TRUE;
7216 } else if (str_begins_with (arg, "full")) {
7217 opts->mode = MONO_AOT_MODE_FULL;
7218 } else if (str_begins_with (arg, "hybrid")) {
7219 opts->mode = MONO_AOT_MODE_HYBRID;
7220 } else if (str_begins_with (arg, "threads=")) {
7221 opts->nthreads = atoi (arg + strlen ("threads="));
7222 } else if (str_begins_with (arg, "static")) {
7223 opts->static_link = TRUE;
7224 opts->no_dlsym = TRUE;
7225 } else if (str_begins_with (arg, "asmonly")) {
7226 opts->asm_only = TRUE;
7227 } else if (str_begins_with (arg, "asmwriter")) {
7228 opts->asm_writer = TRUE;
7229 } else if (str_begins_with (arg, "nodebug")) {
7230 opts->nodebug = TRUE;
7231 } else if (str_begins_with (arg, "dwarfdebug")) {
7232 opts->dwarf_debug = TRUE;
7233 } else if (str_begins_with (arg, "nopagetrampolines")) {
7234 opts->use_trampolines_page = FALSE;
7235 } else if (str_begins_with (arg, "ntrampolines=")) {
7236 opts->ntrampolines = atoi (arg + strlen ("ntrampolines="));
7237 } else if (str_begins_with (arg, "nrgctx-trampolines=")) {
7238 opts->nrgctx_trampolines = atoi (arg + strlen ("nrgctx-trampolines="));
7239 } else if (str_begins_with (arg, "nimt-trampolines=")) {
7240 opts->nimt_trampolines = atoi (arg + strlen ("nimt-trampolines="));
7241 } else if (str_begins_with (arg, "ngsharedvt-trampolines=")) {
7242 opts->ngsharedvt_arg_trampolines = atoi (arg + strlen ("ngsharedvt-trampolines="));
7243 } else if (str_begins_with (arg, "tool-prefix=")) {
7244 opts->tool_prefix = g_strdup (arg + strlen ("tool-prefix="));
7245 } else if (str_begins_with (arg, "ld-flags=")) {
7246 opts->ld_flags = g_strdup (arg + strlen ("ld-flags="));
7247 } else if (str_begins_with (arg, "soft-debug")) {
7248 opts->soft_debug = TRUE;
7249 } else if (str_begins_with (arg, "gen-seq-points-file=")) {
7250 debug_options.gen_seq_points_compact_data = TRUE;
7251 opts->gen_seq_points_file = TRUE;
7252 opts->gen_seq_points_file_path = g_strdup (arg + strlen ("gen-seq-points-file="));;
7253 } else if (str_begins_with (arg, "gen-seq-points-file")) {
7254 debug_options.gen_seq_points_compact_data = TRUE;
7255 opts->gen_seq_points_file = TRUE;
7256 } else if (str_begins_with (arg, "direct-pinvoke")) {
7257 opts->direct_pinvoke = TRUE;
7258 } else if (str_begins_with (arg, "direct-icalls")) {
7259 opts->direct_icalls = TRUE;
7260 } else if (str_begins_with (arg, "no-direct-calls")) {
7261 opts->no_direct_calls = TRUE;
7262 } else if (str_begins_with (arg, "print-skipped")) {
7263 opts->print_skipped_methods = TRUE;
7264 } else if (str_begins_with (arg, "stats")) {
7266 } else if (str_begins_with (arg, "no-instances")) {
7267 opts->no_instances = TRUE;
7268 } else if (str_begins_with (arg, "log-generics")) {
7269 opts->log_generics = TRUE;
7270 } else if (str_begins_with (arg, "log-instances=")) {
7271 opts->log_instances = TRUE;
7272 opts->instances_logfile_path = g_strdup (arg + strlen ("log-instances="));
7273 } else if (str_begins_with (arg, "log-instances")) {
7274 opts->log_instances = TRUE;
7275 } else if (str_begins_with (arg, "internal-logfile=")) {
7276 opts->logfile = g_strdup (arg + strlen ("internal-logfile="));
7277 } else if (str_begins_with (arg, "mtriple=")) {
7278 opts->mtriple = g_strdup (arg + strlen ("mtriple="));
7279 } else if (str_begins_with (arg, "llvm-path=")) {
7280 opts->llvm_path = clean_path (g_strdup (arg + strlen ("llvm-path=")));
7281 } else if (!strcmp (arg, "llvm")) {
7283 } else if (str_begins_with (arg, "readonly-value=")) {
7284 add_readonly_value (opts, arg + strlen ("readonly-value="));
7285 } else if (str_begins_with (arg, "info")) {
7286 printf ("AOT target setup: %s.\n", AOT_TARGET_STR);
7288 } else if (str_begins_with (arg, "gc-maps")) {
7289 mini_gc_enable_gc_maps_for_aot ();
7290 } else if (str_begins_with (arg, "dump")) {
7291 opts->dump_json = TRUE;
7292 } else if (str_begins_with (arg, "llvmonly")) {
7293 opts->mode = MONO_AOT_MODE_FULL;
7295 opts->llvm_only = TRUE;
7296 } else if (str_begins_with (arg, "data-outfile=")) {
7297 opts->data_outfile = g_strdup (arg + strlen ("data-outfile="));
7298 } else if (str_begins_with (arg, "help") || str_begins_with (arg, "?")) {
7299 printf ("Supported options for --aot:\n");
7300 printf (" outfile=\n");
7301 printf (" llvm-outfile=\n");
7302 printf (" llvm-path=\n");
7303 printf (" temp-path=\n");
7304 printf (" save-temps\n");
7305 printf (" keep-temps\n");
7306 printf (" write-symbols\n");
7307 printf (" metadata-only\n");
7308 printf (" bind-to-runtime-version\n");
7310 printf (" threads=\n");
7311 printf (" static\n");
7312 printf (" asmonly\n");
7313 printf (" asmwriter\n");
7314 printf (" nodebug\n");
7315 printf (" dwarfdebug\n");
7316 printf (" ntrampolines=\n");
7317 printf (" nrgctx-trampolines=\n");
7318 printf (" nimt-trampolines=\n");
7319 printf (" ngsharedvt-trampolines=\n");
7320 printf (" tool-prefix=\n");
7321 printf (" readonly-value=\n");
7322 printf (" soft-debug\n");
7323 printf (" gen-seq-points-file\n");
7324 printf (" gc-maps\n");
7325 printf (" print-skipped\n");
7326 printf (" no-instances\n");
7327 printf (" stats\n");
7330 printf (" help/?\n");
7333 fprintf (stderr, "AOT : Unknown argument '%s'.\n", arg);
7337 g_free ((gpointer) arg);
7340 if (opts->use_trampolines_page) {
7341 opts->ntrampolines = 0;
7342 opts->nrgctx_trampolines = 0;
7343 opts->nimt_trampolines = 0;
7344 opts->ngsharedvt_arg_trampolines = 0;
7347 g_ptr_array_free (args, /*free_seg=*/TRUE);
7351 add_token_info_hash (gpointer key, gpointer value, gpointer user_data)
7353 MonoMethod *method = (MonoMethod*)key;
7354 MonoJumpInfoToken *ji = (MonoJumpInfoToken*)value;
7355 MonoAotCompile *acfg = (MonoAotCompile *)user_data;
7356 MonoJumpInfoToken *new_ji;
7358 new_ji = (MonoJumpInfoToken *)mono_mempool_alloc0 (acfg->mempool, sizeof (MonoJumpInfoToken));
7359 new_ji->image = ji->image;
7360 new_ji->token = ji->token;
7361 g_hash_table_insert (acfg->token_info_hash, method, new_ji);
7365 can_encode_class (MonoAotCompile *acfg, MonoClass *klass)
7367 if (klass->type_token)
7369 if ((klass->byval_arg.type == MONO_TYPE_VAR) || (klass->byval_arg.type == MONO_TYPE_MVAR) || (klass->byval_arg.type == MONO_TYPE_PTR))
7372 return can_encode_class (acfg, klass->element_class);
7377 can_encode_method (MonoAotCompile *acfg, MonoMethod *method)
7379 if (method->wrapper_type) {
7380 switch (method->wrapper_type) {
7381 case MONO_WRAPPER_NONE:
7382 case MONO_WRAPPER_REMOTING_INVOKE_WITH_CHECK:
7383 case MONO_WRAPPER_XDOMAIN_INVOKE:
7384 case MONO_WRAPPER_STFLD:
7385 case MONO_WRAPPER_LDFLD:
7386 case MONO_WRAPPER_LDFLDA:
7387 case MONO_WRAPPER_LDFLD_REMOTE:
7388 case MONO_WRAPPER_STFLD_REMOTE:
7389 case MONO_WRAPPER_STELEMREF:
7390 case MONO_WRAPPER_ISINST:
7391 case MONO_WRAPPER_PROXY_ISINST:
7392 case MONO_WRAPPER_ALLOC:
7393 case MONO_WRAPPER_REMOTING_INVOKE:
7394 case MONO_WRAPPER_UNKNOWN:
7395 case MONO_WRAPPER_WRITE_BARRIER:
7396 case MONO_WRAPPER_DELEGATE_INVOKE:
7397 case MONO_WRAPPER_DELEGATE_BEGIN_INVOKE:
7398 case MONO_WRAPPER_DELEGATE_END_INVOKE:
7399 case MONO_WRAPPER_SYNCHRONIZED:
7401 case MONO_WRAPPER_MANAGED_TO_MANAGED:
7402 case MONO_WRAPPER_CASTCLASS: {
7403 WrapperInfo *info = mono_marshal_get_wrapper_info (method);
7412 //printf ("Skip (wrapper call): %d -> %s\n", patch_info->type, mono_method_full_name (patch_info->data.method, TRUE));
7416 if (!method->token) {
7417 /* The method is part of a constructed type like Int[,].Set (). */
7418 if (!g_hash_table_lookup (acfg->token_info_hash, method)) {
7419 if (method->klass->rank)
7429 can_encode_patch (MonoAotCompile *acfg, MonoJumpInfo *patch_info)
7431 switch (patch_info->type) {
7432 case MONO_PATCH_INFO_METHOD:
7433 case MONO_PATCH_INFO_METHODCONST:
7434 case MONO_PATCH_INFO_METHOD_CODE_SLOT: {
7435 MonoMethod *method = patch_info->data.method;
7437 return can_encode_method (acfg, method);
7439 case MONO_PATCH_INFO_VTABLE:
7440 case MONO_PATCH_INFO_CLASS:
7441 case MONO_PATCH_INFO_IID:
7442 case MONO_PATCH_INFO_ADJUSTED_IID:
7443 if (!can_encode_class (acfg, patch_info->data.klass)) {
7444 //printf ("Skip: %s\n", mono_type_full_name (&patch_info->data.klass->byval_arg));
7448 case MONO_PATCH_INFO_DELEGATE_TRAMPOLINE: {
7449 if (!can_encode_class (acfg, patch_info->data.del_tramp->klass)) {
7450 //printf ("Skip: %s\n", mono_type_full_name (&patch_info->data.klass->byval_arg));
7455 case MONO_PATCH_INFO_RGCTX_FETCH:
7456 case MONO_PATCH_INFO_RGCTX_SLOT_INDEX: {
7457 MonoJumpInfoRgctxEntry *entry = patch_info->data.rgctx_entry;
7459 if (!can_encode_method (acfg, entry->method))
7461 if (!can_encode_patch (acfg, entry->data))
7473 is_concrete_type (MonoType *t)
7478 if (t->type == MONO_TYPE_VAR || t->type == MONO_TYPE_MVAR)
7480 if (t->type == MONO_TYPE_GENERICINST) {
7481 MonoGenericContext *orig_ctx;
7482 MonoGenericInst *inst;
7485 if (!MONO_TYPE_ISSTRUCT (t))
7487 klass = mono_class_from_mono_type (t);
7488 orig_ctx = &klass->generic_class->context;
7490 inst = orig_ctx->class_inst;
7492 for (i = 0; i < inst->type_argc; ++i) {
7493 arg = mini_get_underlying_type (inst->type_argv [i]);
7494 if (!is_concrete_type (arg))
7498 inst = orig_ctx->method_inst;
7500 for (i = 0; i < inst->type_argc; ++i) {
7501 arg = mini_get_underlying_type (inst->type_argv [i]);
7502 if (!is_concrete_type (arg))
7510 /* LOCKING: Assumes the loader lock is held */
7512 add_gsharedvt_wrappers (MonoAotCompile *acfg, MonoMethodSignature *sig, gboolean gsharedvt_in, gboolean gsharedvt_out)
7514 MonoMethod *wrapper;
7515 gboolean concrete = TRUE;
7516 gboolean add_in = gsharedvt_in;
7517 gboolean add_out = gsharedvt_out;
7519 if (gsharedvt_in && g_hash_table_lookup (acfg->gsharedvt_in_signatures, sig))
7521 if (gsharedvt_out && g_hash_table_lookup (acfg->gsharedvt_out_signatures, sig))
7524 if (!add_in && !add_out)
7527 if (mini_is_gsharedvt_variable_signature (sig))
7531 g_hash_table_insert (acfg->gsharedvt_in_signatures, sig, sig);
7533 g_hash_table_insert (acfg->gsharedvt_out_signatures, sig, sig);
7535 if (!sig->has_type_parameters) {
7536 //printf ("%s\n", mono_signature_full_name (sig));
7539 wrapper = mini_get_gsharedvt_in_sig_wrapper (sig);
7540 add_extra_method (acfg, wrapper);
7542 if (gsharedvt_out) {
7543 wrapper = mini_get_gsharedvt_out_sig_wrapper (sig);
7544 add_extra_method (acfg, wrapper);
7547 /* For signatures creared during generic sharing, convert them to a concrete signature if possible */
7548 MonoMethodSignature *copy = mono_metadata_signature_dup (sig);
7551 //printf ("%s\n", mono_signature_full_name (sig));
7553 copy->ret = mini_get_underlying_type (sig->ret);
7554 if (!is_concrete_type (copy->ret))
7556 for (i = 0; i < sig->param_count; ++i) {
7557 copy->params [i] = mini_get_underlying_type (sig->params [i]);
7558 if (!is_concrete_type (copy->params [i]))
7562 copy->has_type_parameters = 0;
7565 wrapper = mini_get_gsharedvt_in_sig_wrapper (copy);
7566 add_extra_method (acfg, wrapper);
7569 if (gsharedvt_out) {
7570 wrapper = mini_get_gsharedvt_out_sig_wrapper (copy);
7571 add_extra_method (acfg, wrapper);
7574 //printf ("%s\n", mono_method_full_name (wrapper, 1));
7582 * AOT compile a given method.
7583 * This function might be called by multiple threads, so it must be thread-safe.
7586 compile_method (MonoAotCompile *acfg, MonoMethod *method)
7589 MonoJumpInfo *patch_info;
7592 MonoMethod *wrapped;
7596 if (acfg->aot_opts.metadata_only)
7599 mono_acfg_lock (acfg);
7600 index = get_method_index (acfg, method);
7601 mono_acfg_unlock (acfg);
7603 /* fixme: maybe we can also precompile wrapper methods */
7604 if ((method->flags & METHOD_ATTRIBUTE_PINVOKE_IMPL) ||
7605 (method->iflags & METHOD_IMPL_ATTRIBUTE_RUNTIME) ||
7606 (method->flags & METHOD_ATTRIBUTE_ABSTRACT)) {
7607 //printf ("Skip (impossible): %s\n", mono_method_full_name (method, TRUE));
7611 if (method->iflags & METHOD_IMPL_ATTRIBUTE_INTERNAL_CALL)
7614 wrapped = mono_marshal_method_from_wrapper (method);
7615 if (wrapped && (wrapped->iflags & METHOD_IMPL_ATTRIBUTE_INTERNAL_CALL) && wrapped->is_generic)
7616 // FIXME: The wrapper should be generic too, but it is not
7619 if (method->wrapper_type == MONO_WRAPPER_COMINTEROP)
7622 InterlockedIncrement (&acfg->stats.mcount);
7625 if (method->is_generic || method->klass->generic_container) {
7626 InterlockedIncrement (&acfg->stats.genericcount);
7631 //acfg->aot_opts.print_skipped_methods = TRUE;
7634 * Since these methods are the only ones which are compiled with
7635 * AOT support, and they are not used by runtime startup/shutdown code,
7636 * the runtime will not see AOT methods during AOT compilation,so it
7637 * does not need to support them by creating a fake GOT etc.
7639 flags = JIT_FLAG_AOT;
7640 if (mono_aot_mode_is_full (&acfg->aot_opts))
7641 flags = (JitFlags)(flags | JIT_FLAG_FULL_AOT);
7643 flags = (JitFlags)(flags | JIT_FLAG_LLVM);
7644 if (acfg->aot_opts.llvm_only)
7645 flags = (JitFlags)(flags | JIT_FLAG_LLVM_ONLY | JIT_FLAG_EXPLICIT_NULL_CHECKS);
7646 if (acfg->aot_opts.no_direct_calls)
7647 flags = (JitFlags)(flags | JIT_FLAG_NO_DIRECT_ICALLS);
7649 jit_timer = mono_time_track_start ();
7650 cfg = mini_method_compile (method, acfg->opts, mono_get_root_domain (), flags, 0, index);
7651 mono_time_track_end (&mono_jit_stats.jit_time, jit_timer);
7653 if (cfg->exception_type == MONO_EXCEPTION_GENERIC_SHARING_FAILED) {
7654 if (acfg->aot_opts.print_skipped_methods)
7655 printf ("Skip (gshared failure): %s (%s)\n", mono_method_get_full_name (method), cfg->exception_message);
7656 InterlockedIncrement (&acfg->stats.genericcount);
7659 if (cfg->exception_type != MONO_EXCEPTION_NONE) {
7660 if (acfg->aot_opts.print_skipped_methods)
7661 printf ("Skip (JIT failure): %s\n", mono_method_get_full_name (method));
7662 /* Let the exception happen at runtime */
7666 if (cfg->disable_aot) {
7667 if (acfg->aot_opts.print_skipped_methods)
7668 printf ("Skip (disabled): %s\n", mono_method_get_full_name (method));
7669 InterlockedIncrement (&acfg->stats.ocount);
7670 mono_destroy_compile (cfg);
7673 cfg->method_index = index;
7675 /* Nullify patches which need no aot processing */
7676 for (patch_info = cfg->patch_info; patch_info; patch_info = patch_info->next) {
7677 switch (patch_info->type) {
7678 case MONO_PATCH_INFO_LABEL:
7679 case MONO_PATCH_INFO_BB:
7680 patch_info->type = MONO_PATCH_INFO_NONE;
7687 /* Collect method->token associations from the cfg */
7688 mono_acfg_lock (acfg);
7689 g_hash_table_foreach (cfg->token_info_hash, add_token_info_hash, acfg);
7690 mono_acfg_unlock (acfg);
7691 g_hash_table_destroy (cfg->token_info_hash);
7692 cfg->token_info_hash = NULL;
7695 * Check for absolute addresses.
7698 for (patch_info = cfg->patch_info; patch_info; patch_info = patch_info->next) {
7699 switch (patch_info->type) {
7700 case MONO_PATCH_INFO_ABS:
7701 /* unable to handle this */
7710 if (acfg->aot_opts.print_skipped_methods)
7711 printf ("Skip (abs call): %s\n", mono_method_get_full_name (method));
7712 InterlockedIncrement (&acfg->stats.abscount);
7713 mono_destroy_compile (cfg);
7717 /* Lock for the rest of the code */
7718 mono_acfg_lock (acfg);
7721 acfg->stats.method_categories [METHOD_CAT_GSHAREDVT] ++;
7722 else if (cfg->gshared)
7723 acfg->stats.method_categories [METHOD_CAT_INST] ++;
7724 else if (cfg->method->wrapper_type)
7725 acfg->stats.method_categories [METHOD_CAT_WRAPPER] ++;
7727 acfg->stats.method_categories [METHOD_CAT_NORMAL] ++;
7730 * Check for methods/klasses we can't encode.
7733 for (patch_info = cfg->patch_info; patch_info; patch_info = patch_info->next) {
7734 if (!can_encode_patch (acfg, patch_info))
7739 if (acfg->aot_opts.print_skipped_methods)
7740 printf ("Skip (patches): %s\n", mono_method_get_full_name (method));
7741 acfg->stats.ocount++;
7742 mono_destroy_compile (cfg);
7743 mono_acfg_unlock (acfg);
7747 if (!cfg->compile_llvm)
7748 acfg->has_jitted_code = TRUE;
7750 if (method->is_inflated && acfg->aot_opts.log_instances) {
7751 if (acfg->instances_logfile)
7752 fprintf (acfg->instances_logfile, "%s ### %d\n", mono_method_get_full_name (method), cfg->code_size);
7754 printf ("%s ### %d\n", mono_method_get_full_name (method), cfg->code_size);
7757 /* Adds generic instances referenced by this method */
7759 * The depth is used to avoid infinite loops when generic virtual recursion is
7762 depth = GPOINTER_TO_UINT (g_hash_table_lookup (acfg->method_depth, method));
7763 if (!acfg->aot_opts.no_instances && depth < 32) {
7764 for (patch_info = cfg->patch_info; patch_info; patch_info = patch_info->next) {
7765 switch (patch_info->type) {
7766 case MONO_PATCH_INFO_RGCTX_FETCH:
7767 case MONO_PATCH_INFO_RGCTX_SLOT_INDEX:
7768 case MONO_PATCH_INFO_METHOD: {
7769 MonoMethod *m = NULL;
7771 if (patch_info->type == MONO_PATCH_INFO_RGCTX_FETCH || patch_info->type == MONO_PATCH_INFO_RGCTX_SLOT_INDEX) {
7772 MonoJumpInfoRgctxEntry *e = patch_info->data.rgctx_entry;
7774 if (e->info_type == MONO_RGCTX_INFO_GENERIC_METHOD_CODE)
7775 m = e->data->data.method;
7777 m = patch_info->data.method;
7782 if (m->is_inflated) {
7783 if (!(mono_class_generic_sharing_enabled (m->klass) &&
7784 mono_method_is_generic_sharable_full (m, FALSE, FALSE, FALSE)) &&
7785 (!method_has_type_vars (m) || mono_method_is_generic_sharable_full (m, TRUE, TRUE, FALSE))) {
7786 if (m->iflags & METHOD_IMPL_ATTRIBUTE_INTERNAL_CALL) {
7787 if (mono_aot_mode_is_full (&acfg->aot_opts) && !method_has_type_vars (m))
7788 add_extra_method_with_depth (acfg, mono_marshal_get_native_wrapper (m, TRUE, TRUE), depth + 1);
7790 add_extra_method_with_depth (acfg, m, depth + 1);
7791 add_types_from_method_header (acfg, m);
7794 add_generic_class_with_depth (acfg, m->klass, depth + 5, "method");
7796 if (m->wrapper_type == MONO_WRAPPER_MANAGED_TO_MANAGED) {
7797 WrapperInfo *info = mono_marshal_get_wrapper_info (m);
7799 if (info && info->subtype == WRAPPER_SUBTYPE_ELEMENT_ADDR)
7800 add_extra_method_with_depth (acfg, m, depth + 1);
7804 case MONO_PATCH_INFO_VTABLE: {
7805 MonoClass *klass = patch_info->data.klass;
7807 if (klass->generic_class && !mini_class_is_generic_sharable (klass))
7808 add_generic_class_with_depth (acfg, klass, depth + 5, "vtable");
7811 case MONO_PATCH_INFO_SFLDA: {
7812 MonoClass *klass = patch_info->data.field->parent;
7814 /* The .cctor needs to run at runtime. */
7815 if (klass->generic_class && !mono_generic_context_is_sharable (&klass->generic_class->context, FALSE) && mono_class_get_cctor (klass))
7816 add_extra_method_with_depth (acfg, mono_class_get_cctor (klass), depth + 1);
7825 /* Determine whenever the method has GOT slots */
7826 for (patch_info = cfg->patch_info; patch_info; patch_info = patch_info->next) {
7827 switch (patch_info->type) {
7828 case MONO_PATCH_INFO_GOT_OFFSET:
7829 case MONO_PATCH_INFO_NONE:
7830 case MONO_PATCH_INFO_GC_CARD_TABLE_ADDR:
7831 case MONO_PATCH_INFO_GC_NURSERY_START:
7832 case MONO_PATCH_INFO_GC_NURSERY_BITS:
7834 case MONO_PATCH_INFO_IMAGE:
7835 /* The assembly is stored in GOT slot 0 */
7836 if (patch_info->data.image != acfg->image)
7837 cfg->has_got_slots = TRUE;
7840 if (!is_plt_patch (patch_info) || (cfg->compile_llvm && acfg->aot_opts.llvm_only))
7841 cfg->has_got_slots = TRUE;
7846 if (!cfg->has_got_slots)
7847 InterlockedIncrement (&acfg->stats.methods_without_got_slots);
7849 /* Add gsharedvt wrappers for signatures used by the method */
7850 if (acfg->aot_opts.llvm_only) {
7853 if (!cfg->method->wrapper_type || cfg->method->wrapper_type == MONO_WRAPPER_DELEGATE_INVOKE)
7854 /* These only need out wrappers */
7855 add_gsharedvt_wrappers (acfg, mono_method_signature (cfg->method), FALSE, TRUE);
7857 for (l = cfg->signatures; l; l = l->next) {
7858 MonoMethodSignature *sig = mono_metadata_signature_dup ((MonoMethodSignature*)l->data);
7860 /* These only need in wrappers */
7861 add_gsharedvt_wrappers (acfg, sig, TRUE, FALSE);
7866 * FIXME: Instead of this mess, allocate the patches from the aot mempool.
7868 /* Make a copy of the patch info which is in the mempool */
7870 MonoJumpInfo *patches = NULL, *patches_end = NULL;
7872 for (patch_info = cfg->patch_info; patch_info; patch_info = patch_info->next) {
7873 MonoJumpInfo *new_patch_info = mono_patch_info_dup_mp (acfg->mempool, patch_info);
7876 patches = new_patch_info;
7878 patches_end->next = new_patch_info;
7879 patches_end = new_patch_info;
7881 cfg->patch_info = patches;
7883 /* Make a copy of the unwind info */
7885 GSList *l, *unwind_ops;
7889 for (l = cfg->unwind_ops; l; l = l->next) {
7890 op = (MonoUnwindOp *)mono_mempool_alloc (acfg->mempool, sizeof (MonoUnwindOp));
7891 memcpy (op, l->data, sizeof (MonoUnwindOp));
7892 unwind_ops = g_slist_prepend_mempool (acfg->mempool, unwind_ops, op);
7894 cfg->unwind_ops = g_slist_reverse (unwind_ops);
7896 /* Make a copy of the argument/local info */
7899 MonoInst **args, **locals;
7900 MonoMethodSignature *sig;
7901 MonoMethodHeader *header;
7904 sig = mono_method_signature (method);
7905 args = (MonoInst **)mono_mempool_alloc (acfg->mempool, sizeof (MonoInst*) * (sig->param_count + sig->hasthis));
7906 for (i = 0; i < sig->param_count + sig->hasthis; ++i) {
7907 args [i] = (MonoInst *)mono_mempool_alloc (acfg->mempool, sizeof (MonoInst));
7908 memcpy (args [i], cfg->args [i], sizeof (MonoInst));
7912 header = mono_method_get_header_checked (method, &error);
7913 mono_error_assert_ok (&error); /* FIXME don't swallow the error */
7914 locals = (MonoInst **)mono_mempool_alloc (acfg->mempool, sizeof (MonoInst*) * header->num_locals);
7915 for (i = 0; i < header->num_locals; ++i) {
7916 locals [i] = (MonoInst *)mono_mempool_alloc (acfg->mempool, sizeof (MonoInst));
7917 memcpy (locals [i], cfg->locals [i], sizeof (MonoInst));
7919 cfg->locals = locals;
7922 /* Free some fields used by cfg to conserve memory */
7923 mono_mempool_destroy (cfg->mempool);
7924 cfg->mempool = NULL;
7925 g_free (cfg->varinfo);
7926 cfg->varinfo = NULL;
7930 mono_regstate_free (cfg->rs);
7934 //printf ("Compile: %s\n", mono_method_full_name (method, TRUE));
7936 while (index >= acfg->cfgs_size) {
7937 MonoCompile **new_cfgs;
7940 new_size = acfg->cfgs_size * 2;
7941 new_cfgs = g_new0 (MonoCompile*, new_size);
7942 memcpy (new_cfgs, acfg->cfgs, sizeof (MonoCompile*) * acfg->cfgs_size);
7943 g_free (acfg->cfgs);
7944 acfg->cfgs = new_cfgs;
7945 acfg->cfgs_size = new_size;
7947 acfg->cfgs [index] = cfg;
7949 g_hash_table_insert (acfg->method_to_cfg, cfg->orig_method, cfg);
7951 mono_update_jit_stats (cfg);
7954 if (cfg->orig_method->wrapper_type)
7955 g_ptr_array_add (acfg->extra_methods, cfg->orig_method);
7958 mono_acfg_unlock (acfg);
7960 InterlockedIncrement (&acfg->stats.ccount);
7964 compile_thread_main (gpointer *user_data)
7966 MonoDomain *domain = (MonoDomain *)user_data [0];
7967 MonoAotCompile *acfg = (MonoAotCompile *)user_data [1];
7968 GPtrArray *methods = (GPtrArray *)user_data [2];
7972 MonoThread *thread = mono_thread_attach (domain);
7973 mono_thread_set_name_internal (thread->internal_thread, mono_string_new (mono_get_root_domain (), "AOT compiler"), TRUE, &error);
7974 mono_error_assert_ok (&error);
7976 for (i = 0; i < methods->len; ++i)
7977 compile_method (acfg, (MonoMethod *)g_ptr_array_index (methods, i));
7981 load_profile_files (MonoAotCompile *acfg)
7985 int file_index, res, method_index, i;
7988 GList *unordered, *l;
7993 tmp = g_strdup_printf ("%s/.mono/aot-profile-data/%s-%d", g_get_home_dir (), acfg->image->assembly_name, file_index);
7995 if (!g_file_test (tmp, G_FILE_TEST_IS_REGULAR)) {
8000 infile = fopen (tmp, "r");
8003 printf ("Using profile data file '%s'\n", tmp);
8008 res = fscanf (infile, "%32s\n", ver);
8009 if ((res != 1) || strcmp (ver, "#VER:2") != 0) {
8010 printf ("Profile file has wrong version or invalid.\n");
8017 MonoMethodDesc *desc;
8020 if (fgets (name, 1023, infile) == NULL)
8023 /* Kill the newline */
8024 if (strlen (name) > 0)
8025 name [strlen (name) - 1] = '\0';
8027 desc = mono_method_desc_new (name, TRUE);
8029 method = mono_method_desc_search_in_image (desc, acfg->image);
8031 if (method && mono_method_get_token (method)) {
8032 token = mono_method_get_token (method);
8033 method_index = mono_metadata_token_index (token) - 1;
8036 for (i = 0; i < acfg->method_order->len; ++i) {
8037 if (g_ptr_array_index (acfg->method_order, i) == GUINT_TO_POINTER (method_index)) {
8043 g_ptr_array_add (acfg->method_order, GUINT_TO_POINTER (method_index));
8045 //printf ("No method found matching '%s'.\n", name);
8051 /* Add missing methods */
8053 for (method_index = 0; method_index < acfg->image->tables [MONO_TABLE_METHOD].rows; ++method_index) {
8055 for (i = 0; i < acfg->method_order->len; ++i) {
8056 if (g_ptr_array_index (acfg->method_order, i) == GUINT_TO_POINTER (method_index)) {
8062 unordered = g_list_prepend (unordered, GUINT_TO_POINTER (method_index));
8064 unordered = g_list_reverse (unordered);
8065 for (l = unordered; l; l = l->next)
8066 g_ptr_array_add (acfg->method_order, l->data);
8069 /* Used by the LLVM backend */
8071 mono_aot_get_got_offset (MonoJumpInfo *ji)
8073 return get_got_offset (llvm_acfg, TRUE, ji);
8077 * mono_aot_is_shared_got_offset:
8079 * Return whenever OFFSET refers to a GOT slot which is preinitialized
8080 * when the AOT image is loaded.
8083 mono_aot_is_shared_got_offset (int offset)
8085 return offset < llvm_acfg->nshared_got_entries;
8089 mono_aot_get_method_name (MonoCompile *cfg)
8091 if (llvm_acfg->aot_opts.static_link)
8092 /* Include the assembly name too to avoid duplicate symbol errors */
8093 return g_strdup_printf ("%s_%s", llvm_acfg->assembly_name_sym, get_debug_sym (cfg->orig_method, "", llvm_acfg->method_label_hash));
8095 return get_debug_sym (cfg->orig_method, "", llvm_acfg->method_label_hash);
8099 * mono_aot_is_linkonce_method:
8101 * Return whenever METHOD should be emitted with linkonce linkage,
8102 * eliminating duplicate copies when compiling in static mode.
8105 mono_aot_is_linkonce_method (MonoMethod *method)
8109 // FIXME: Add more cases
8110 if (method->wrapper_type != MONO_WRAPPER_UNKNOWN)
8112 info = mono_marshal_get_wrapper_info (method);
8113 if ((info && (info->subtype == WRAPPER_SUBTYPE_GSHAREDVT_IN_SIG || info->subtype == WRAPPER_SUBTYPE_GSHAREDVT_OUT_SIG)))
8119 append_mangled_type (GString *s, MonoType *t)
8122 g_string_append_printf (s, "b");
8124 case MONO_TYPE_VOID:
8125 g_string_append_printf (s, "void_");
8128 g_string_append_printf (s, "i1");
8131 g_string_append_printf (s, "u1");
8134 g_string_append_printf (s, "i2");
8137 g_string_append_printf (s, "u2");
8140 g_string_append_printf (s, "i4");
8143 g_string_append_printf (s, "u4");
8146 g_string_append_printf (s, "i8");
8149 g_string_append_printf (s, "u8");
8152 g_string_append_printf (s, "ii");
8155 g_string_append_printf (s, "ui");
8158 g_string_append_printf (s, "fl");
8161 g_string_append_printf (s, "do");
8164 char *fullname = mono_type_full_name (t);
8170 * Have to create a mangled name which is:
8174 temp = g_string_new ("");
8175 len = strlen (fullname);
8176 for (i = 0; i < len; ++i) {
8177 char c = fullname [i];
8179 g_string_append_c (temp, c);
8180 } else if (c == '_') {
8181 g_string_append_c (temp, '_');
8182 g_string_append_c (temp, '_');
8184 g_string_append_c (temp, '_');
8185 g_string_append_printf (temp, "%x", (int)c);
8188 temps = g_string_free (temp, FALSE);
8189 /* Include the length to avoid different length type names aliasing each other */
8190 g_string_append_printf (s, "cl%x_%s_", strlen (temps), temps);
8199 append_mangled_signature (GString *s, MonoMethodSignature *sig)
8204 supported = append_mangled_type (s, sig->ret);
8208 g_string_append_printf (s, "this_");
8209 for (i = 0; i < sig->param_count; ++i) {
8210 supported = append_mangled_type (s, sig->params [i]);
8219 * mono_aot_get_mangled_method_name:
8221 * Return a unique mangled name for METHOD, or NULL.
8224 mono_aot_get_mangled_method_name (MonoMethod *method)
8230 // FIXME: Add more cases
8231 if (method->wrapper_type != MONO_WRAPPER_UNKNOWN)
8233 info = mono_marshal_get_wrapper_info (method);
8234 if (!(info && (info->subtype == WRAPPER_SUBTYPE_GSHAREDVT_IN_SIG || info->subtype == WRAPPER_SUBTYPE_GSHAREDVT_OUT_SIG)))
8237 s = g_string_new ("");
8239 g_string_append_printf (s, "aot_method_w_");
8241 switch (info->subtype) {
8242 case WRAPPER_SUBTYPE_GSHAREDVT_IN_SIG:
8243 g_string_append_printf (s, "gsharedvt_in_");
8245 case WRAPPER_SUBTYPE_GSHAREDVT_OUT_SIG:
8246 g_string_append_printf (s, "gsharedvt_out_");
8249 g_assert_not_reached ();
8253 supported = append_mangled_signature (s, info->d.gsharedvt.sig);
8255 g_string_free (s, TRUE);
8259 return g_string_free (s, FALSE);
8263 mono_aot_is_direct_callable (MonoJumpInfo *patch_info)
8265 return is_direct_callable (llvm_acfg, NULL, patch_info);
8269 mono_aot_mark_unused_llvm_plt_entry (MonoJumpInfo *patch_info)
8271 MonoPltEntry *plt_entry;
8273 plt_entry = get_plt_entry (llvm_acfg, patch_info);
8274 plt_entry->llvm_used = FALSE;
8278 mono_aot_get_direct_call_symbol (MonoJumpInfoType type, gconstpointer data)
8280 const char *sym = NULL;
8282 if (llvm_acfg->aot_opts.direct_icalls) {
8283 if (type == MONO_PATCH_INFO_JIT_ICALL_ADDR) {
8284 /* Call to a C function implementing a jit icall */
8285 sym = mono_lookup_jit_icall_symbol ((const char *)data);
8286 } else if (type == MONO_PATCH_INFO_ICALL_ADDR_CALL) {
8287 MonoMethod *method = (MonoMethod *)data;
8288 if (!(method->flags & METHOD_ATTRIBUTE_PINVOKE_IMPL))
8289 sym = mono_lookup_icall_symbol (method);
8290 else if (llvm_acfg->aot_opts.direct_pinvoke)
8291 sym = get_pinvoke_import (llvm_acfg, method);
8294 return g_strdup (sym);
8300 mono_aot_get_plt_symbol (MonoJumpInfoType type, gconstpointer data)
8302 MonoJumpInfo *ji = (MonoJumpInfo *)mono_mempool_alloc (llvm_acfg->mempool, sizeof (MonoJumpInfo));
8303 MonoPltEntry *plt_entry;
8304 const char *sym = NULL;
8307 ji->data.target = data;
8309 if (!can_encode_patch (llvm_acfg, ji))
8312 if (llvm_acfg->aot_opts.direct_icalls) {
8313 if (type == MONO_PATCH_INFO_JIT_ICALL_ADDR) {
8314 /* Call to a C function implementing a jit icall */
8315 sym = mono_lookup_jit_icall_symbol ((const char *)data);
8316 } else if (type == MONO_PATCH_INFO_ICALL_ADDR_CALL) {
8317 MonoMethod *method = (MonoMethod *)data;
8318 if (!(method->flags & METHOD_ATTRIBUTE_PINVOKE_IMPL))
8319 sym = mono_lookup_icall_symbol (method);
8322 return g_strdup (sym);
8325 plt_entry = get_plt_entry (llvm_acfg, ji);
8326 plt_entry->llvm_used = TRUE;
8328 #if defined(TARGET_MACH)
8329 return g_strdup_printf (plt_entry->llvm_symbol + strlen (llvm_acfg->llvm_label_prefix));
8331 return g_strdup_printf (plt_entry->llvm_symbol);
8336 mono_aot_get_method_index (MonoMethod *method)
8338 g_assert (llvm_acfg);
8339 return get_method_index (llvm_acfg, method);
8343 mono_aot_patch_info_dup (MonoJumpInfo* ji)
8347 mono_acfg_lock (llvm_acfg);
8348 res = mono_patch_info_dup_mp (llvm_acfg->mempool, ji);
8349 mono_acfg_unlock (llvm_acfg);
8355 execute_system (const char * command)
8360 // We need an extra set of quotes around the whole command to properly handle commands
8361 // with spaces since internally the command is called through "cmd /c.
8362 command = g_strdup_printf ("\"%s\"", command);
8364 int size = MultiByteToWideChar (CP_UTF8, 0 , command , -1, NULL , 0);
8365 wchar_t* wstr = g_malloc (sizeof (wchar_t) * size);
8366 MultiByteToWideChar (CP_UTF8, 0, command, -1, wstr , size);
8367 status = _wsystem (wstr);
8371 #elif defined (HAVE_SYSTEM)
8372 status = system (command);
8374 g_assert_not_reached ();
8385 * Emit the LLVM code into an LLVM bytecode file, and compile it using the LLVM
8389 emit_llvm_file (MonoAotCompile *acfg)
8391 char *command, *opts, *tempbc, *optbc, *output_fname;
8393 if (acfg->aot_opts.llvm_only && acfg->aot_opts.asm_only) {
8394 tempbc = g_strdup_printf ("%s.bc", acfg->tmpbasename);
8395 optbc = g_strdup (acfg->aot_opts.llvm_outfile);
8397 tempbc = g_strdup_printf ("%s.bc", acfg->tmpbasename);
8398 optbc = g_strdup_printf ("%s.opt.bc", acfg->tmpbasename);
8401 mono_llvm_emit_aot_module (tempbc, g_path_get_basename (acfg->image->name));
8404 * FIXME: Experiment with adding optimizations, the -std-compile-opts set takes
8405 * a lot of time, and doesn't seem to save much space.
8406 * The following optimizations cannot be enabled:
8408 * - 'jump-threading' changes our blockaddress references to int constants.
8409 * - 'basiccg' fails because it contains:
8410 * if (CS && !isa<IntrinsicInst>(II)) {
8411 * and isa<IntrinsicInst> is false for invokes to intrinsics (iltests.exe).
8412 * - 'prune-eh' and 'functionattrs' depend on 'basiccg'.
8413 * The opt list below was produced by taking the output of:
8414 * llvm-as < /dev/null | opt -O2 -disable-output -debug-pass=Arguments
8415 * then removing tailcallelim + the global opts.
8416 * strip-dead-prototypes deletes unused intrinsics definitions.
8418 /* The dse pass is disabled because of #13734 and #17616 */
8420 * The dse bug is in DeadStoreElimination.cpp:isOverwrite ():
8421 * // If we have no DataLayout information around, then the size of the store
8422 * // is inferrable from the pointee type. If they are the same type, then
8423 * // we know that the store is safe.
8424 * if (AA.getDataLayout() == 0 &&
8425 * Later.Ptr->getType() == Earlier.Ptr->getType()) {
8426 * return OverwriteComplete;
8427 * Here, if 'Earlier' refers to a memset, and Later has no size info, it mistakenly thinks the memset is redundant.
8429 if (acfg->aot_opts.llvm_only)
8430 // FIXME: This doesn't work yet
8431 opts = g_strdup ("");
8433 #if LLVM_API_VERSION > 100
8434 opts = g_strdup ("-O2");
8436 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");
8438 command = g_strdup_printf ("\"%sopt\" -f %s -o \"%s\" \"%s\"", acfg->aot_opts.llvm_path, opts, optbc, tempbc);
8439 aot_printf (acfg, "Executing opt: %s\n", command);
8440 if (execute_system (command) != 0)
8444 if (acfg->aot_opts.llvm_only && acfg->aot_opts.asm_only)
8445 /* Nothing else to do */
8448 if (acfg->aot_opts.llvm_only) {
8449 /* Use the stock clang from xcode */
8451 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);
8453 aot_printf (acfg, "Executing clang: %s\n", command);
8454 if (execute_system (command) != 0)
8459 if (!acfg->llc_args)
8460 acfg->llc_args = g_string_new ("");
8462 /* Verbose asm slows down llc greatly */
8463 g_string_append (acfg->llc_args, " -asm-verbose=false");
8465 if (acfg->aot_opts.mtriple)
8466 g_string_append_printf (acfg->llc_args, " -mtriple=%s", acfg->aot_opts.mtriple);
8468 g_string_append (acfg->llc_args, " -disable-gnu-eh-frame -enable-mono-eh-frame");
8470 g_string_append_printf (acfg->llc_args, " -mono-eh-frame-symbol=%s%s", acfg->user_symbol_prefix, acfg->llvm_eh_frame_symbol);
8472 #if LLVM_API_VERSION > 100
8473 g_string_append_printf (acfg->llc_args, " -disable-tail-calls");
8476 #if defined(TARGET_MACH) && defined(TARGET_ARM)
8477 /* ios requires PIC code now */
8478 g_string_append_printf (acfg->llc_args, " -relocation-model=pic");
8480 if (llvm_acfg->aot_opts.static_link)
8481 g_string_append_printf (acfg->llc_args, " -relocation-model=static");
8483 g_string_append_printf (acfg->llc_args, " -relocation-model=pic");
8486 if (acfg->llvm_owriter) {
8487 /* Emit an object file directly */
8488 output_fname = g_strdup_printf ("%s", acfg->llvm_ofile);
8489 g_string_append_printf (acfg->llc_args, " -filetype=obj");
8491 output_fname = g_strdup_printf ("%s", acfg->llvm_sfile);
8493 command = g_strdup_printf ("\"%sllc\" %s -o \"%s\" \"%s.opt.bc\"", acfg->aot_opts.llvm_path, acfg->llc_args->str, output_fname, acfg->tmpbasename);
8494 g_free (output_fname);
8496 aot_printf (acfg, "Executing llc: %s\n", command);
8498 if (execute_system (command) != 0)
8505 emit_code (MonoAotCompile *acfg)
8507 int oindex, i, prev_index;
8508 gboolean saved_unbox_info = FALSE;
8509 char symbol [MAX_SYMBOL_SIZE];
8511 if (acfg->aot_opts.llvm_only)
8514 #if defined(TARGET_POWERPC64)
8515 sprintf (symbol, ".Lgot_addr");
8516 emit_section_change (acfg, ".text", 0);
8517 emit_alignment (acfg, 8);
8518 emit_label (acfg, symbol);
8519 emit_pointer (acfg, acfg->got_symbol);
8523 * This global symbol is used to compute the address of each method using the
8524 * code_offsets array. It is also used to compute the memory ranges occupied by
8525 * AOT code, so it must be equal to the address of the first emitted method.
8527 emit_section_change (acfg, ".text", 0);
8528 emit_alignment_code (acfg, 8);
8529 emit_info_symbol (acfg, "jit_code_start");
8532 * Emit some padding so the local symbol for the first method doesn't have the
8533 * same address as 'methods'.
8535 #if defined(__default_codegen__)
8536 emit_padding (acfg, 16);
8537 #elif defined(__native_client_codegen__)
8539 const int kPaddingSize = 16;
8540 guint8 pad_buffer[kPaddingSize];
8541 mono_arch_nacl_pad (pad_buffer, kPaddingSize);
8542 emit_bytes (acfg, pad_buffer, kPaddingSize);
8546 for (oindex = 0; oindex < acfg->method_order->len; ++oindex) {
8550 i = GPOINTER_TO_UINT (g_ptr_array_index (acfg->method_order, oindex));
8552 cfg = acfg->cfgs [i];
8557 method = cfg->orig_method;
8559 /* Emit unbox trampoline */
8560 if (mono_aot_mode_is_full (&acfg->aot_opts) && cfg->orig_method->klass->valuetype && !(acfg->aot_opts.llvm_only && cfg->compile_llvm)) {
8561 sprintf (symbol, "ut_%d", get_method_index (acfg, method));
8563 emit_section_change (acfg, ".text", 0);
8564 #ifdef __native_client_codegen__
8565 emit_alignment (acfg, AOT_FUNC_ALIGNMENT);
8568 if (acfg->thumb_mixed && cfg->compile_llvm) {
8569 emit_set_thumb_mode (acfg);
8570 fprintf (acfg->fp, "\n.thumb_func\n");
8573 emit_label (acfg, symbol);
8575 arch_emit_unbox_trampoline (acfg, cfg, cfg->orig_method, cfg->asm_symbol);
8577 if (acfg->thumb_mixed && cfg->compile_llvm)
8578 emit_set_arm_mode (acfg);
8580 if (!saved_unbox_info) {
8581 char user_symbol [128];
8583 sprintf (user_symbol, "%sunbox_trampoline_p", acfg->user_symbol_prefix);
8585 emit_label (acfg, "ut_end");
8587 unwind_ops = mono_unwind_get_cie_program ();
8588 save_unwind_info (acfg, user_symbol, unwind_ops);
8589 mono_free_unwind_info (unwind_ops);
8591 /* Save the unbox trampoline size */
8592 emit_symbol_diff (acfg, "ut_end", symbol, 0);
8594 saved_unbox_info = TRUE;
8598 if (cfg->compile_llvm)
8599 acfg->stats.llvm_count ++;
8601 emit_method_code (acfg, cfg);
8604 emit_section_change (acfg, ".text", 0);
8605 emit_alignment_code (acfg, 8);
8606 emit_info_symbol (acfg, "jit_code_end");
8608 /* To distinguish it from the next symbol */
8609 emit_padding (acfg, 4);
8612 * Add .no_dead_strip directives for all LLVM methods to prevent the OSX linker
8613 * from optimizing them away, since it doesn't see that code_offsets references them.
8614 * JITted methods don't need this since they are referenced using assembler local
8616 * FIXME: This is why write-symbols doesn't work on OSX ?
8618 if (acfg->llvm && acfg->need_no_dead_strip) {
8619 fprintf (acfg->fp, "\n");
8620 for (i = 0; i < acfg->nmethods; ++i) {
8621 if (acfg->cfgs [i] && acfg->cfgs [i]->compile_llvm)
8622 fprintf (acfg->fp, ".no_dead_strip %s\n", acfg->cfgs [i]->asm_symbol);
8627 * To work around linker issues, we emit a table of branches, and disassemble them at runtime.
8628 * This is PIE code, and the linker can update it if needed.
8631 sprintf (symbol, "method_addresses");
8632 emit_section_change (acfg, ".text", 1);
8633 emit_alignment_code (acfg, 8);
8634 emit_info_symbol (acfg, symbol);
8635 emit_local_symbol (acfg, symbol, "method_addresses_end", TRUE);
8636 emit_unset_mode (acfg);
8637 if (acfg->need_no_dead_strip)
8638 fprintf (acfg->fp, " .no_dead_strip %s\n", symbol);
8640 for (i = 0; i < acfg->nmethods; ++i) {
8641 #ifdef MONO_ARCH_AOT_SUPPORTED
8644 if (acfg->cfgs [i]) {
8645 if (acfg->aot_opts.llvm_only && acfg->cfgs [i]->compile_llvm)
8646 /* Obtained by calling a generated function in the LLVM image */
8647 arch_emit_direct_call (acfg, symbol, FALSE, FALSE, NULL, &call_size);
8649 arch_emit_direct_call (acfg, acfg->cfgs [i]->asm_symbol, FALSE, acfg->thumb_mixed && acfg->cfgs [i]->compile_llvm, NULL, &call_size);
8651 arch_emit_direct_call (acfg, symbol, FALSE, FALSE, NULL, &call_size);
8656 sprintf (symbol, "method_addresses_end");
8657 emit_label (acfg, symbol);
8660 /* Emit a sorted table mapping methods to the index of their unbox trampolines */
8661 sprintf (symbol, "unbox_trampolines");
8662 emit_section_change (acfg, RODATA_SECT, 0);
8663 emit_alignment (acfg, 8);
8664 emit_info_symbol (acfg, symbol);
8667 for (i = 0; i < acfg->nmethods; ++i) {
8672 cfg = acfg->cfgs [i];
8676 method = cfg->orig_method;
8678 if (mono_aot_mode_is_full (&acfg->aot_opts) && cfg->orig_method->klass->valuetype && !(acfg->aot_opts.llvm_only && cfg->compile_llvm)) {
8679 index = get_method_index (acfg, method);
8681 emit_int32 (acfg, index);
8682 /* Make sure the table is sorted by index */
8683 g_assert (index > prev_index);
8687 sprintf (symbol, "unbox_trampolines_end");
8688 emit_info_symbol (acfg, symbol);
8689 emit_int32 (acfg, 0);
8691 /* Emit a separate table with the trampoline addresses/offsets */
8692 sprintf (symbol, "unbox_trampoline_addresses");
8693 emit_section_change (acfg, ".text", 0);
8694 emit_alignment_code (acfg, 8);
8695 emit_info_symbol (acfg, symbol);
8697 for (i = 0; i < acfg->nmethods; ++i) {
8702 cfg = acfg->cfgs [i];
8706 method = cfg->orig_method;
8708 if (mono_aot_mode_is_full (&acfg->aot_opts) && cfg->orig_method->klass->valuetype && !(acfg->aot_opts.llvm_only && cfg->compile_llvm)) {
8709 #ifdef MONO_ARCH_AOT_SUPPORTED
8712 index = get_method_index (acfg, method);
8713 sprintf (symbol, "ut_%d", index);
8715 arch_emit_direct_call (acfg, symbol, FALSE, acfg->thumb_mixed && cfg->compile_llvm, NULL, &call_size);
8719 emit_int32 (acfg, 0);
8723 emit_info (MonoAotCompile *acfg)
8728 offsets = g_new0 (gint32, acfg->nmethods);
8730 for (oindex = 0; oindex < acfg->method_order->len; ++oindex) {
8731 i = GPOINTER_TO_UINT (g_ptr_array_index (acfg->method_order, oindex));
8733 if (acfg->cfgs [i]) {
8734 emit_method_info (acfg, acfg->cfgs [i]);
8735 offsets [i] = acfg->cfgs [i]->method_info_offset;
8741 acfg->stats.offsets_size += emit_offset_table (acfg, "method_info_offsets", MONO_AOT_TABLE_METHOD_INFO_OFFSETS, acfg->nmethods, 10, offsets);
8746 #endif /* #if !defined(DISABLE_AOT) && !defined(DISABLE_JIT) */
8748 #define rot(x,k) (((x)<<(k)) | ((x)>>(32-(k))))
8749 #define mix(a,b,c) { \
8750 a -= c; a ^= rot(c, 4); c += b; \
8751 b -= a; b ^= rot(a, 6); a += c; \
8752 c -= b; c ^= rot(b, 8); b += a; \
8753 a -= c; a ^= rot(c,16); c += b; \
8754 b -= a; b ^= rot(a,19); a += c; \
8755 c -= b; c ^= rot(b, 4); b += a; \
8757 #define final(a,b,c) { \
8758 c ^= b; c -= rot(b,14); \
8759 a ^= c; a -= rot(c,11); \
8760 b ^= a; b -= rot(a,25); \
8761 c ^= b; c -= rot(b,16); \
8762 a ^= c; a -= rot(c,4); \
8763 b ^= a; b -= rot(a,14); \
8764 c ^= b; c -= rot(b,24); \
8768 mono_aot_type_hash (MonoType *t1)
8770 guint hash = t1->type;
8772 hash |= t1->byref << 6; /* do not collide with t1->type values */
8774 case MONO_TYPE_VALUETYPE:
8775 case MONO_TYPE_CLASS:
8776 case MONO_TYPE_SZARRAY:
8777 /* check if the distribution is good enough */
8778 return ((hash << 5) - hash) ^ mono_metadata_str_hash (t1->data.klass->name);
8780 return ((hash << 5) - hash) ^ mono_metadata_type_hash (t1->data.type);
8781 case MONO_TYPE_ARRAY:
8782 return ((hash << 5) - hash) ^ mono_metadata_type_hash (&t1->data.array->eklass->byval_arg);
8783 case MONO_TYPE_GENERICINST:
8784 return ((hash << 5) - hash) ^ 0;
8791 * mono_aot_method_hash:
8793 * Return a hash code for methods which only depends on metadata.
8796 mono_aot_method_hash (MonoMethod *method)
8798 MonoMethodSignature *sig;
8802 guint32 *hashes_start, *hashes;
8804 MonoGenericInst *class_ginst = NULL;
8805 MonoGenericInst *ginst = NULL;
8807 /* Similar to the hash in mono_method_get_imt_slot () */
8809 sig = mono_method_signature (method);
8811 if (method->klass->generic_class)
8812 class_ginst = method->klass->generic_class->context.class_inst;
8813 if (method->is_inflated)
8814 ginst = ((MonoMethodInflated*)method)->context.method_inst;
8816 hashes_count = sig->param_count + 5 + (class_ginst ? class_ginst->type_argc : 0) + (ginst ? ginst->type_argc : 0);
8817 hashes_start = (guint32 *)g_malloc0 (hashes_count * sizeof (guint32));
8818 hashes = hashes_start;
8820 /* Some wrappers are assigned to random classes */
8821 if (!method->wrapper_type || method->wrapper_type == MONO_WRAPPER_REMOTING_INVOKE_WITH_CHECK)
8822 klass = method->klass;
8824 klass = mono_defaults.object_class;
8826 if (!method->wrapper_type) {
8829 if (klass->generic_class)
8830 full_name = mono_type_full_name (&klass->generic_class->container_class->byval_arg);
8832 full_name = mono_type_full_name (&klass->byval_arg);
8834 hashes [0] = mono_metadata_str_hash (full_name);
8838 hashes [0] = mono_metadata_str_hash (klass->name);
8839 hashes [1] = mono_metadata_str_hash (klass->name_space);
8841 if (method->wrapper_type == MONO_WRAPPER_STFLD || method->wrapper_type == MONO_WRAPPER_LDFLD || method->wrapper_type == MONO_WRAPPER_LDFLDA)
8842 /* The method name includes a stringified pointer */
8845 hashes [2] = mono_metadata_str_hash (method->name);
8846 hashes [3] = method->wrapper_type;
8847 hashes [4] = mono_aot_type_hash (sig->ret);
8849 for (i = 0; i < sig->param_count; i++) {
8850 hashes [hindex ++] = mono_aot_type_hash (sig->params [i]);
8853 for (i = 0; i < class_ginst->type_argc; ++i)
8854 hashes [hindex ++] = mono_aot_type_hash (class_ginst->type_argv [i]);
8857 for (i = 0; i < ginst->type_argc; ++i)
8858 hashes [hindex ++] = mono_aot_type_hash (ginst->type_argv [i]);
8860 g_assert (hindex == hashes_count);
8862 /* Setup internal state */
8863 a = b = c = 0xdeadbeef + (((guint32)hashes_count)<<2);
8865 /* Handle most of the hashes */
8866 while (hashes_count > 3) {
8875 /* Handle the last 3 hashes (all the case statements fall through) */
8876 switch (hashes_count) {
8877 case 3 : c += hashes [2];
8878 case 2 : b += hashes [1];
8879 case 1 : a += hashes [0];
8881 case 0: /* nothing left to add */
8885 free (hashes_start);
8894 * mono_aot_get_array_helper_from_wrapper;
8896 * Get the helper method in Array called by an array wrapper method.
8899 mono_aot_get_array_helper_from_wrapper (MonoMethod *method)
8903 MonoGenericContext ctx;
8904 MonoType *args [16];
8905 char *mname, *iname, *s, *s2, *helper_name = NULL;
8907 prefix = "System.Collections.Generic";
8908 s = g_strdup_printf ("%s", method->name + strlen (prefix) + 1);
8909 s2 = strstr (s, "`1.");
8915 //printf ("X: %s %s\n", iname, mname);
8917 if (!strcmp (iname, "IList"))
8918 helper_name = g_strdup_printf ("InternalArray__%s", mname);
8920 helper_name = g_strdup_printf ("InternalArray__%s_%s", iname, mname);
8921 m = mono_class_get_method_from_name (mono_defaults.array_class, helper_name, mono_method_signature (method)->param_count);
8923 g_free (helper_name);
8926 if (m->is_generic) {
8928 memset (&ctx, 0, sizeof (ctx));
8929 args [0] = &method->klass->element_class->byval_arg;
8930 ctx.method_inst = mono_metadata_get_generic_inst (1, args);
8931 m = mono_class_inflate_generic_method_checked (m, &ctx, &error);
8932 g_assert (mono_error_ok (&error)); /* FIXME don't swallow the error */
8938 #if !defined(DISABLE_AOT) && !defined(DISABLE_JIT)
8940 typedef struct HashEntry {
8941 guint32 key, value, index;
8942 struct HashEntry *next;
8946 * emit_extra_methods:
8948 * Emit methods which are not in the METHOD table, like wrappers.
8951 emit_extra_methods (MonoAotCompile *acfg)
8953 int i, table_size, buf_size;
8955 guint32 *info_offsets;
8958 HashEntry *entry, *new_entry;
8959 int nmethods, max_chain_length;
8962 info_offsets = g_new0 (guint32, acfg->extra_methods->len);
8964 /* Emit method info */
8966 for (i = 0; i < acfg->extra_methods->len; ++i) {
8967 MonoMethod *method = (MonoMethod *)g_ptr_array_index (acfg->extra_methods, i);
8968 MonoCompile *cfg = (MonoCompile *)g_hash_table_lookup (acfg->method_to_cfg, method);
8974 p = buf = (guint8 *)g_malloc (buf_size);
8978 method = cfg->method_to_register;
8980 encode_method_ref (acfg, method, p, &p);
8982 g_assert ((p - buf) < buf_size);
8984 info_offsets [i] = add_to_blob (acfg, buf, p - buf);
8989 * Construct a chained hash table for mapping indexes in extra_method_info to
8992 table_size = g_spaced_primes_closest ((int)(nmethods * 1.5));
8993 table = g_ptr_array_sized_new (table_size);
8994 for (i = 0; i < table_size; ++i)
8995 g_ptr_array_add (table, NULL);
8996 chain_lengths = g_new0 (int, table_size);
8997 max_chain_length = 0;
8998 for (i = 0; i < acfg->extra_methods->len; ++i) {
8999 MonoMethod *method = (MonoMethod *)g_ptr_array_index (acfg->extra_methods, i);
9000 MonoCompile *cfg = (MonoCompile *)g_hash_table_lookup (acfg->method_to_cfg, method);
9006 key = info_offsets [i];
9007 value = get_method_index (acfg, method);
9009 hash = mono_aot_method_hash (method) % table_size;
9010 //printf ("X: %s %x\n", mono_method_get_full_name (method), mono_aot_method_hash (method));
9012 chain_lengths [hash] ++;
9013 max_chain_length = MAX (max_chain_length, chain_lengths [hash]);
9015 new_entry = (HashEntry *)mono_mempool_alloc0 (acfg->mempool, sizeof (HashEntry));
9016 new_entry->key = key;
9017 new_entry->value = value;
9019 entry = (HashEntry *)g_ptr_array_index (table, hash);
9020 if (entry == NULL) {
9021 new_entry->index = hash;
9022 g_ptr_array_index (table, hash) = new_entry;
9025 entry = entry->next;
9027 entry->next = new_entry;
9028 new_entry->index = table->len;
9029 g_ptr_array_add (table, new_entry);
9033 //printf ("MAX: %d\n", max_chain_length);
9035 buf_size = table->len * 12 + 4;
9036 p = buf = (guint8 *)g_malloc (buf_size);
9037 encode_int (table_size, p, &p);
9039 for (i = 0; i < table->len; ++i) {
9040 HashEntry *entry = (HashEntry *)g_ptr_array_index (table, i);
9042 if (entry == NULL) {
9043 encode_int (0, p, &p);
9044 encode_int (0, p, &p);
9045 encode_int (0, p, &p);
9047 //g_assert (entry->key > 0);
9048 encode_int (entry->key, p, &p);
9049 encode_int (entry->value, p, &p);
9051 encode_int (entry->next->index, p, &p);
9053 encode_int (0, p, &p);
9056 g_assert (p - buf <= buf_size);
9058 /* Emit the table */
9059 emit_aot_data (acfg, MONO_AOT_TABLE_EXTRA_METHOD_TABLE, "extra_method_table", buf, p - buf);
9062 * Emit a table reverse mapping method indexes to their index in extra_method_info.
9063 * This is used by mono_aot_find_jit_info ().
9065 buf_size = acfg->extra_methods->len * 8 + 4;
9066 p = buf = (guint8 *)g_malloc (buf_size);
9067 encode_int (acfg->extra_methods->len, p, &p);
9068 for (i = 0; i < acfg->extra_methods->len; ++i) {
9069 MonoMethod *method = (MonoMethod *)g_ptr_array_index (acfg->extra_methods, i);
9071 encode_int (get_method_index (acfg, method), p, &p);
9072 encode_int (info_offsets [i], p, &p);
9074 emit_aot_data (acfg, MONO_AOT_TABLE_EXTRA_METHOD_INFO_OFFSETS, "extra_method_info_offsets", buf, p - buf);
9078 emit_exception_info (MonoAotCompile *acfg)
9082 SeqPointData sp_data;
9083 gboolean seq_points_to_file = FALSE;
9085 offsets = g_new0 (gint32, acfg->nmethods);
9086 for (i = 0; i < acfg->nmethods; ++i) {
9087 if (acfg->cfgs [i]) {
9088 MonoCompile *cfg = acfg->cfgs [i];
9090 // By design aot-runtime decode_exception_debug_info is not able to load sequence point debug data from a file.
9091 // As it is not possible to load debug data from a file its is also not possible to store it in a file.
9092 gboolean method_seq_points_to_file = acfg->aot_opts.gen_seq_points_file &&
9093 cfg->gen_seq_points && !cfg->gen_sdb_seq_points;
9094 gboolean method_seq_points_to_binary = cfg->gen_seq_points && !method_seq_points_to_file;
9096 emit_exception_debug_info (acfg, cfg, method_seq_points_to_binary);
9097 offsets [i] = cfg->ex_info_offset;
9099 if (method_seq_points_to_file) {
9100 if (!seq_points_to_file) {
9101 mono_seq_point_data_init (&sp_data, acfg->nmethods);
9102 seq_points_to_file = TRUE;
9104 mono_seq_point_data_add (&sp_data, cfg->method->token, cfg->method_index, cfg->seq_point_info);
9111 if (seq_points_to_file) {
9112 char *seq_points_aot_file = acfg->aot_opts.gen_seq_points_file_path ? acfg->aot_opts.gen_seq_points_file_path
9113 : g_strdup_printf("%s%s", acfg->image->name, SEQ_POINT_AOT_EXT);
9114 mono_seq_point_data_write (&sp_data, seq_points_aot_file);
9115 mono_seq_point_data_free (&sp_data);
9116 g_free (seq_points_aot_file);
9119 acfg->stats.offsets_size += emit_offset_table (acfg, "ex_info_offsets", MONO_AOT_TABLE_EX_INFO_OFFSETS, acfg->nmethods, 10, offsets);
9124 emit_unwind_info (MonoAotCompile *acfg)
9129 if (acfg->aot_opts.llvm_only) {
9130 g_assert (acfg->unwind_ops->len == 0);
9135 * The unwind info contains a lot of duplicates so we emit each unique
9136 * entry once, and only store the offset from the start of the table in the
9140 sprintf (symbol, "unwind_info");
9141 emit_section_change (acfg, RODATA_SECT, 1);
9142 emit_alignment (acfg, 8);
9143 emit_info_symbol (acfg, symbol);
9145 for (i = 0; i < acfg->unwind_ops->len; ++i) {
9146 guint32 index = GPOINTER_TO_UINT (g_ptr_array_index (acfg->unwind_ops, i));
9147 guint8 *unwind_info;
9148 guint32 unwind_info_len;
9152 unwind_info = mono_get_cached_unwind_info (index, &unwind_info_len);
9155 encode_value (unwind_info_len, p, &p);
9156 emit_bytes (acfg, buf, p - buf);
9157 emit_bytes (acfg, unwind_info, unwind_info_len);
9159 acfg->stats.unwind_info_size += (p - buf) + unwind_info_len;
9164 emit_class_info (MonoAotCompile *acfg)
9169 offsets = g_new0 (gint32, acfg->image->tables [MONO_TABLE_TYPEDEF].rows);
9170 for (i = 0; i < acfg->image->tables [MONO_TABLE_TYPEDEF].rows; ++i)
9171 offsets [i] = emit_klass_info (acfg, MONO_TOKEN_TYPE_DEF | (i + 1));
9173 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);
9177 typedef struct ClassNameTableEntry {
9178 guint32 token, index;
9179 struct ClassNameTableEntry *next;
9180 } ClassNameTableEntry;
9183 emit_class_name_table (MonoAotCompile *acfg)
9185 int i, table_size, buf_size;
9186 guint32 token, hash;
9191 ClassNameTableEntry *entry, *new_entry;
9194 * Construct a chained hash table for mapping class names to typedef tokens.
9196 table_size = g_spaced_primes_closest ((int)(acfg->image->tables [MONO_TABLE_TYPEDEF].rows * 1.5));
9197 table = g_ptr_array_sized_new (table_size);
9198 for (i = 0; i < table_size; ++i)
9199 g_ptr_array_add (table, NULL);
9200 for (i = 0; i < acfg->image->tables [MONO_TABLE_TYPEDEF].rows; ++i) {
9202 token = MONO_TOKEN_TYPE_DEF | (i + 1);
9203 klass = mono_class_get_checked (acfg->image, token, &error);
9205 mono_error_cleanup (&error);
9208 full_name = mono_type_get_name_full (mono_class_get_type (klass), MONO_TYPE_NAME_FORMAT_FULL_NAME);
9209 hash = mono_metadata_str_hash (full_name) % table_size;
9212 /* FIXME: Allocate from the mempool */
9213 new_entry = g_new0 (ClassNameTableEntry, 1);
9214 new_entry->token = token;
9216 entry = (ClassNameTableEntry *)g_ptr_array_index (table, hash);
9217 if (entry == NULL) {
9218 new_entry->index = hash;
9219 g_ptr_array_index (table, hash) = new_entry;
9222 entry = entry->next;
9224 entry->next = new_entry;
9225 new_entry->index = table->len;
9226 g_ptr_array_add (table, new_entry);
9230 /* Emit the table */
9231 buf_size = table->len * 4 + 4;
9232 p = buf = (guint8 *)g_malloc0 (buf_size);
9234 /* FIXME: Optimize memory usage */
9235 g_assert (table_size < 65000);
9236 encode_int16 (table_size, p, &p);
9237 g_assert (table->len < 65000);
9238 for (i = 0; i < table->len; ++i) {
9239 ClassNameTableEntry *entry = (ClassNameTableEntry *)g_ptr_array_index (table, i);
9241 if (entry == NULL) {
9242 encode_int16 (0, p, &p);
9243 encode_int16 (0, p, &p);
9245 encode_int16 (mono_metadata_token_index (entry->token), p, &p);
9247 encode_int16 (entry->next->index, p, &p);
9249 encode_int16 (0, p, &p);
9252 g_assert (p - buf <= buf_size);
9254 emit_aot_data (acfg, MONO_AOT_TABLE_CLASS_NAME, "class_name_table", buf, p - buf);
9258 emit_image_table (MonoAotCompile *acfg)
9264 * The image table is small but referenced in a lot of places.
9265 * So we emit it at once, and reference its elements by an index.
9267 buf_size = acfg->image_table->len * 28 + 4;
9268 for (i = 0; i < acfg->image_table->len; i++) {
9269 MonoImage *image = (MonoImage*)g_ptr_array_index (acfg->image_table, i);
9270 MonoAssemblyName *aname = &image->assembly->aname;
9272 buf_size += strlen (image->assembly_name) + strlen (image->guid) + (aname->culture ? strlen (aname->culture) : 1) + strlen ((char*)aname->public_key_token) + 4;
9275 buf = p = (guint8 *)g_malloc0 (buf_size);
9276 encode_int (acfg->image_table->len, p, &p);
9277 for (i = 0; i < acfg->image_table->len; i++) {
9278 MonoImage *image = (MonoImage*)g_ptr_array_index (acfg->image_table, i);
9279 MonoAssemblyName *aname = &image->assembly->aname;
9281 /* FIXME: Support multi-module assemblies */
9282 g_assert (image->assembly->image == image);
9284 encode_string (image->assembly_name, p, &p);
9285 encode_string (image->guid, p, &p);
9286 encode_string (aname->culture ? aname->culture : "", p, &p);
9287 encode_string ((const char*)aname->public_key_token, p, &p);
9289 while (GPOINTER_TO_UINT (p) % 8 != 0)
9292 encode_int (aname->flags, p, &p);
9293 encode_int (aname->major, p, &p);
9294 encode_int (aname->minor, p, &p);
9295 encode_int (aname->build, p, &p);
9296 encode_int (aname->revision, p, &p);
9298 g_assert (p - buf <= buf_size);
9300 emit_aot_data (acfg, MONO_AOT_TABLE_IMAGE_TABLE, "image_table", buf, p - buf);
9306 emit_got_info (MonoAotCompile *acfg, gboolean llvm)
9308 int i, first_plt_got_patch = 0, buf_size;
9310 guint32 *got_info_offsets;
9311 GotInfo *info = llvm ? &acfg->llvm_got_info : &acfg->got_info;
9313 /* Add the patches needed by the PLT to the GOT */
9315 acfg->plt_got_offset_base = acfg->got_offset;
9316 first_plt_got_patch = info->got_patches->len;
9317 for (i = 1; i < acfg->plt_offset; ++i) {
9318 MonoPltEntry *plt_entry = (MonoPltEntry *)g_hash_table_lookup (acfg->plt_offset_to_entry, GUINT_TO_POINTER (i));
9320 g_ptr_array_add (info->got_patches, plt_entry->ji);
9322 acfg->stats.got_slot_types [plt_entry->ji->type] ++;
9325 acfg->got_offset += acfg->plt_offset;
9330 * - optimize offsets table.
9331 * - reduce number of exported symbols.
9332 * - emit info for a klass only once.
9333 * - determine when a method uses a GOT slot which is guaranteed to be already
9335 * - clean up and document the code.
9336 * - use String.Empty in class libs.
9339 /* Encode info required to decode shared GOT entries */
9340 buf_size = info->got_patches->len * 128;
9341 p = buf = (guint8 *)mono_mempool_alloc (acfg->mempool, buf_size);
9342 got_info_offsets = (guint32 *)mono_mempool_alloc (acfg->mempool, info->got_patches->len * sizeof (guint32));
9344 acfg->plt_got_info_offsets = (guint32 *)mono_mempool_alloc (acfg->mempool, acfg->plt_offset * sizeof (guint32));
9346 if (acfg->plt_offset)
9347 acfg->plt_got_info_offsets [0] = 0;
9349 for (i = 0; i < info->got_patches->len; ++i) {
9350 MonoJumpInfo *ji = (MonoJumpInfo *)g_ptr_array_index (info->got_patches, i);
9355 encode_value (ji->type, p, &p);
9357 encode_patch (acfg, ji, p, &p);
9358 acfg->stats.got_slot_info_sizes [ji->type] += p - p2;
9359 g_assert (p - buf <= buf_size);
9360 got_info_offsets [i] = add_to_blob (acfg, buf, p - buf);
9362 if (!llvm && i >= first_plt_got_patch)
9363 acfg->plt_got_info_offsets [i - first_plt_got_patch + 1] = got_info_offsets [i];
9364 acfg->stats.got_info_size += p - buf;
9367 /* Emit got_info_offsets table */
9369 /* No need to emit offsets for the got plt entries, the plt embeds them directly */
9370 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);
9374 emit_got (MonoAotCompile *acfg)
9376 char symbol [MAX_SYMBOL_SIZE];
9378 if (acfg->aot_opts.llvm_only)
9381 /* Don't make GOT global so accesses to it don't need relocations */
9382 sprintf (symbol, "%s", acfg->got_symbol);
9385 emit_unset_mode (acfg);
9386 fprintf (acfg->fp, ".section __DATA, __bss\n");
9387 emit_alignment (acfg, 8);
9389 emit_info_symbol (acfg, "jit_got");
9390 fprintf (acfg->fp, ".lcomm %s, %d\n", acfg->got_symbol, (int)(acfg->got_offset * sizeof (gpointer)));
9392 emit_section_change (acfg, ".bss", 0);
9393 emit_alignment (acfg, 8);
9394 emit_local_symbol (acfg, symbol, "got_end", FALSE);
9395 emit_label (acfg, symbol);
9397 emit_info_symbol (acfg, "jit_got");
9398 if (acfg->got_offset > 0)
9399 emit_zero_bytes (acfg, (int)(acfg->got_offset * sizeof (gpointer)));
9402 sprintf (symbol, "got_end");
9403 emit_label (acfg, symbol);
9406 typedef struct GlobalsTableEntry {
9407 guint32 value, index;
9408 struct GlobalsTableEntry *next;
9409 } GlobalsTableEntry;
9412 emit_globals (MonoAotCompile *acfg)
9418 GlobalsTableEntry *entry, *new_entry;
9420 if (!acfg->aot_opts.static_link)
9422 if (acfg->aot_opts.llvm_only) {
9423 g_assert (acfg->globals->len == 0);
9428 * When static linking, we emit a table containing our globals.
9432 * Construct a chained hash table for mapping global names to their index in
9433 * the globals table.
9435 table_size = g_spaced_primes_closest ((int)(acfg->globals->len * 1.5));
9436 table = g_ptr_array_sized_new (table_size);
9437 for (i = 0; i < table_size; ++i)
9438 g_ptr_array_add (table, NULL);
9439 for (i = 0; i < acfg->globals->len; ++i) {
9440 char *name = (char *)g_ptr_array_index (acfg->globals, i);
9442 hash = mono_metadata_str_hash (name) % table_size;
9444 /* FIXME: Allocate from the mempool */
9445 new_entry = g_new0 (GlobalsTableEntry, 1);
9446 new_entry->value = i;
9448 entry = (GlobalsTableEntry *)g_ptr_array_index (table, hash);
9449 if (entry == NULL) {
9450 new_entry->index = hash;
9451 g_ptr_array_index (table, hash) = new_entry;
9454 entry = entry->next;
9456 entry->next = new_entry;
9457 new_entry->index = table->len;
9458 g_ptr_array_add (table, new_entry);
9462 /* Emit the table */
9463 sprintf (symbol, ".Lglobals_hash");
9464 emit_section_change (acfg, RODATA_SECT, 0);
9465 emit_alignment (acfg, 8);
9466 emit_label (acfg, symbol);
9468 /* FIXME: Optimize memory usage */
9469 g_assert (table_size < 65000);
9470 emit_int16 (acfg, table_size);
9471 for (i = 0; i < table->len; ++i) {
9472 GlobalsTableEntry *entry = (GlobalsTableEntry *)g_ptr_array_index (table, i);
9474 if (entry == NULL) {
9475 emit_int16 (acfg, 0);
9476 emit_int16 (acfg, 0);
9478 emit_int16 (acfg, entry->value + 1);
9480 emit_int16 (acfg, entry->next->index);
9482 emit_int16 (acfg, 0);
9486 /* Emit the names */
9487 for (i = 0; i < acfg->globals->len; ++i) {
9488 char *name = (char *)g_ptr_array_index (acfg->globals, i);
9490 sprintf (symbol, "name_%d", i);
9491 emit_section_change (acfg, RODATA_SECT, 1);
9493 emit_alignment (acfg, 4);
9495 emit_label (acfg, symbol);
9496 emit_string (acfg, name);
9499 /* Emit the globals table */
9500 sprintf (symbol, "globals");
9501 emit_section_change (acfg, ".data", 0);
9502 /* This is not a global, since it is accessed by the init function */
9503 emit_alignment (acfg, 8);
9504 emit_info_symbol (acfg, symbol);
9506 sprintf (symbol, "%sglobals_hash", acfg->temp_prefix);
9507 emit_pointer (acfg, symbol);
9509 for (i = 0; i < acfg->globals->len; ++i) {
9510 char *name = (char *)g_ptr_array_index (acfg->globals, i);
9512 sprintf (symbol, "name_%d", i);
9513 emit_pointer (acfg, symbol);
9515 g_assert (strlen (name) < sizeof (symbol));
9516 sprintf (symbol, "%s", name);
9517 emit_pointer (acfg, symbol);
9519 /* Null terminate the table */
9520 emit_int32 (acfg, 0);
9521 emit_int32 (acfg, 0);
9525 emit_mem_end (MonoAotCompile *acfg)
9529 if (acfg->aot_opts.llvm_only)
9532 sprintf (symbol, "mem_end");
9533 emit_section_change (acfg, ".text", 1);
9534 emit_alignment_code (acfg, 8);
9535 emit_label (acfg, symbol);
9539 init_aot_file_info (MonoAotCompile *acfg, MonoAotFileInfo *info)
9543 info->version = MONO_AOT_FILE_VERSION;
9544 info->plt_got_offset_base = acfg->plt_got_offset_base;
9545 info->got_size = acfg->got_offset * sizeof (gpointer);
9546 info->plt_size = acfg->plt_offset;
9547 info->nmethods = acfg->nmethods;
9548 info->flags = acfg->flags;
9549 info->opts = acfg->opts;
9550 info->simd_opts = acfg->simd_opts;
9551 info->gc_name_index = acfg->gc_name_offset;
9552 info->datafile_size = acfg->datafile_offset;
9553 for (i = 0; i < MONO_AOT_TABLE_NUM; ++i)
9554 info->table_offsets [i] = acfg->table_offsets [i];
9555 for (i = 0; i < MONO_AOT_TRAMP_NUM; ++i)
9556 info->num_trampolines [i] = acfg->num_trampolines [i];
9557 for (i = 0; i < MONO_AOT_TRAMP_NUM; ++i)
9558 info->trampoline_got_offset_base [i] = acfg->trampoline_got_offset_base [i];
9559 for (i = 0; i < MONO_AOT_TRAMP_NUM; ++i)
9560 info->trampoline_size [i] = acfg->trampoline_size [i];
9561 info->num_rgctx_fetch_trampolines = acfg->aot_opts.nrgctx_fetch_trampolines;
9563 info->double_align = MONO_ABI_ALIGNOF (double);
9564 info->long_align = MONO_ABI_ALIGNOF (gint64);
9565 info->generic_tramp_num = MONO_TRAMPOLINE_NUM;
9566 info->tramp_page_size = acfg->tramp_page_size;
9567 info->nshared_got_entries = acfg->nshared_got_entries;
9568 for (i = 0; i < MONO_AOT_TRAMP_NUM; ++i)
9569 info->tramp_page_code_offsets [i] = acfg->tramp_page_code_offsets [i];
9573 emit_aot_file_info (MonoAotCompile *acfg, MonoAotFileInfo *info)
9575 char symbol [MAX_SYMBOL_SIZE];
9577 const char **symbols;
9579 symbols = g_new0 (const char *, MONO_AOT_FILE_INFO_NUM_SYMBOLS);
9581 symbols [sindex ++] = acfg->got_symbol;
9583 symbols [sindex ++] = g_strdup_printf ("%s%s", acfg->user_symbol_prefix, acfg->llvm_got_symbol);
9584 symbols [sindex ++] = acfg->llvm_eh_frame_symbol;
9586 symbols [sindex ++] = NULL;
9587 symbols [sindex ++] = NULL;
9589 /* llvm_get_method */
9590 symbols [sindex ++] = NULL;
9591 /* llvm_get_unbox_tramp */
9592 symbols [sindex ++] = NULL;
9593 if (!acfg->aot_opts.llvm_only) {
9594 symbols [sindex ++] = "jit_code_start";
9595 symbols [sindex ++] = "jit_code_end";
9596 symbols [sindex ++] = "method_addresses";
9598 symbols [sindex ++] = NULL;
9599 symbols [sindex ++] = NULL;
9600 symbols [sindex ++] = NULL;
9602 if (acfg->data_outfile) {
9603 for (i = 0; i < MONO_AOT_TABLE_NUM; ++i)
9604 symbols [sindex ++] = NULL;
9606 symbols [sindex ++] = "blob";
9607 symbols [sindex ++] = "class_name_table";
9608 symbols [sindex ++] = "class_info_offsets";
9609 symbols [sindex ++] = "method_info_offsets";
9610 symbols [sindex ++] = "ex_info_offsets";
9611 symbols [sindex ++] = "extra_method_info_offsets";
9612 symbols [sindex ++] = "extra_method_table";
9613 symbols [sindex ++] = "got_info_offsets";
9615 symbols [sindex ++] = "llvm_got_info_offsets";
9617 symbols [sindex ++] = NULL;
9618 symbols [sindex ++] = "image_table";
9620 symbols [sindex ++] = "mem_end";
9621 symbols [sindex ++] = "assembly_guid";
9622 symbols [sindex ++] = "runtime_version";
9623 if (acfg->num_trampoline_got_entries) {
9624 symbols [sindex ++] = "specific_trampolines";
9625 symbols [sindex ++] = "static_rgctx_trampolines";
9626 symbols [sindex ++] = "imt_thunks";
9627 symbols [sindex ++] = "gsharedvt_arg_trampolines";
9629 symbols [sindex ++] = NULL;
9630 symbols [sindex ++] = NULL;
9631 symbols [sindex ++] = NULL;
9632 symbols [sindex ++] = NULL;
9634 if (acfg->aot_opts.static_link) {
9635 symbols [sindex ++] = "globals";
9637 symbols [sindex ++] = NULL;
9639 symbols [sindex ++] = "assembly_name";
9640 symbols [sindex ++] = "plt";
9641 symbols [sindex ++] = "plt_end";
9642 symbols [sindex ++] = "unwind_info";
9643 if (!acfg->aot_opts.llvm_only) {
9644 symbols [sindex ++] = "unbox_trampolines";
9645 symbols [sindex ++] = "unbox_trampolines_end";
9646 symbols [sindex ++] = "unbox_trampoline_addresses";
9648 symbols [sindex ++] = NULL;
9649 symbols [sindex ++] = NULL;
9650 symbols [sindex ++] = NULL;
9653 g_assert (sindex == MONO_AOT_FILE_INFO_NUM_SYMBOLS);
9655 sprintf (symbol, "%smono_aot_file_info", acfg->user_symbol_prefix);
9656 emit_section_change (acfg, ".data", 0);
9657 emit_alignment (acfg, 8);
9658 emit_label (acfg, symbol);
9659 if (!acfg->aot_opts.static_link)
9660 emit_global (acfg, symbol, FALSE);
9662 /* The data emitted here must match MonoAotFileInfo. */
9664 emit_int32 (acfg, info->version);
9665 emit_int32 (acfg, info->dummy);
9668 * We emit pointers to our data structures instead of emitting global symbols which
9669 * point to them, to reduce the number of globals, and because using globals leads to
9670 * various problems (i.e. arm/thumb).
9672 for (i = 0; i < MONO_AOT_FILE_INFO_NUM_SYMBOLS; ++i)
9673 emit_pointer (acfg, symbols [i]);
9675 emit_int32 (acfg, info->plt_got_offset_base);
9676 emit_int32 (acfg, info->got_size);
9677 emit_int32 (acfg, info->plt_size);
9678 emit_int32 (acfg, info->nmethods);
9679 emit_int32 (acfg, info->flags);
9680 emit_int32 (acfg, info->opts);
9681 emit_int32 (acfg, info->simd_opts);
9682 emit_int32 (acfg, info->gc_name_index);
9683 emit_int32 (acfg, info->num_rgctx_fetch_trampolines);
9684 emit_int32 (acfg, info->double_align);
9685 emit_int32 (acfg, info->long_align);
9686 emit_int32 (acfg, info->generic_tramp_num);
9687 emit_int32 (acfg, info->tramp_page_size);
9688 emit_int32 (acfg, info->nshared_got_entries);
9689 emit_int32 (acfg, info->datafile_size);
9691 for (i = 0; i < MONO_AOT_TABLE_NUM; ++i)
9692 emit_int32 (acfg, info->table_offsets [i]);
9693 for (i = 0; i < MONO_AOT_TRAMP_NUM; ++i)
9694 emit_int32 (acfg, info->num_trampolines [i]);
9695 for (i = 0; i < MONO_AOT_TRAMP_NUM; ++i)
9696 emit_int32 (acfg, info->trampoline_got_offset_base [i]);
9697 for (i = 0; i < MONO_AOT_TRAMP_NUM; ++i)
9698 emit_int32 (acfg, info->trampoline_size [i]);
9699 for (i = 0; i < MONO_AOT_TRAMP_NUM; ++i)
9700 emit_int32 (acfg, info->tramp_page_code_offsets [i]);
9702 if (acfg->aot_opts.static_link) {
9703 emit_global_inner (acfg, acfg->static_linking_symbol, FALSE);
9704 emit_alignment (acfg, sizeof (gpointer));
9705 emit_label (acfg, acfg->static_linking_symbol);
9706 emit_pointer_2 (acfg, acfg->user_symbol_prefix, "mono_aot_file_info");
9711 * Emit a structure containing all the information not stored elsewhere.
9714 emit_file_info (MonoAotCompile *acfg)
9717 MonoAotFileInfo *info;
9719 if (acfg->aot_opts.bind_to_runtime_version) {
9720 build_info = mono_get_runtime_build_info ();
9721 emit_string_symbol (acfg, "runtime_version", build_info);
9722 g_free (build_info);
9724 emit_string_symbol (acfg, "runtime_version", "");
9727 emit_string_symbol (acfg, "assembly_guid" , acfg->image->guid);
9729 /* Emit a string holding the assembly name */
9730 emit_string_symbol (acfg, "assembly_name", acfg->image->assembly->aname.name);
9732 info = g_new0 (MonoAotFileInfo, 1);
9733 init_aot_file_info (acfg, info);
9735 if (acfg->aot_opts.static_link) {
9736 char symbol [MAX_SYMBOL_SIZE];
9740 * Emit a global symbol which can be passed by an embedding app to
9741 * mono_aot_register_module (). The symbol points to a pointer to the the file info
9744 sprintf (symbol, "%smono_aot_module_%s_info", acfg->user_symbol_prefix, acfg->image->assembly->aname.name);
9746 /* Get rid of characters which cannot occur in symbols */
9748 for (p = symbol; *p; ++p) {
9749 if (!(isalnum (*p) || *p == '_'))
9752 acfg->static_linking_symbol = g_strdup (symbol);
9756 mono_llvm_emit_aot_file_info (info, acfg->has_jitted_code);
9758 emit_aot_file_info (acfg, info);
9762 emit_blob (MonoAotCompile *acfg)
9764 acfg->blob_closed = TRUE;
9766 emit_aot_data (acfg, MONO_AOT_TABLE_BLOB, "blob", (guint8*)acfg->blob.data, acfg->blob.index);
9770 emit_objc_selectors (MonoAotCompile *acfg)
9775 if (!acfg->objc_selectors || acfg->objc_selectors->len == 0)
9780 * cat > foo.m << EOF
9783 * return @selector(print:);
9788 mono_img_writer_emit_unset_mode (acfg->w);
9789 g_assert (acfg->fp);
9790 fprintf (acfg->fp, ".section __DATA,__objc_selrefs,literal_pointers,no_dead_strip\n");
9791 fprintf (acfg->fp, ".align 3\n");
9792 for (i = 0; i < acfg->objc_selectors->len; ++i) {
9793 sprintf (symbol, "L_OBJC_SELECTOR_REFERENCES_%d", i);
9794 emit_label (acfg, symbol);
9795 sprintf (symbol, "L_OBJC_METH_VAR_NAME_%d", i);
9796 emit_pointer (acfg, symbol);
9799 fprintf (acfg->fp, ".section __TEXT,__cstring,cstring_literals\n");
9800 for (i = 0; i < acfg->objc_selectors->len; ++i) {
9801 fprintf (acfg->fp, "L_OBJC_METH_VAR_NAME_%d:\n", i);
9802 fprintf (acfg->fp, ".asciz \"%s\"\n", (char*)g_ptr_array_index (acfg->objc_selectors, i));
9805 fprintf (acfg->fp, ".section __DATA,__objc_imageinfo,regular,no_dead_strip\n");
9806 fprintf (acfg->fp, ".align 3\n");
9807 fprintf (acfg->fp, "L_OBJC_IMAGE_INFO:\n");
9808 fprintf (acfg->fp, ".long 0\n");
9809 fprintf (acfg->fp, ".long 16\n");
9813 emit_dwarf_info (MonoAotCompile *acfg)
9815 #ifdef EMIT_DWARF_INFO
9819 /* DIEs for methods */
9820 for (i = 0; i < acfg->nmethods; ++i) {
9821 MonoCompile *cfg = acfg->cfgs [i];
9826 // FIXME: LLVM doesn't define .Lme_...
9827 if (cfg->compile_llvm)
9830 sprintf (symbol2, "%sme_%x", acfg->temp_prefix, i);
9832 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 ()));
9838 collect_methods (MonoAotCompile *acfg)
9841 MonoImage *image = acfg->image;
9843 /* Collect methods */
9844 for (i = 0; i < image->tables [MONO_TABLE_METHOD].rows; ++i) {
9847 guint32 token = MONO_TOKEN_METHOD_DEF | (i + 1);
9849 method = mono_get_method_checked (acfg->image, token, NULL, NULL, &error);
9852 aot_printerrf (acfg, "Failed to load method 0x%x from '%s' due to %s.\n", token, image->name, mono_error_get_message (&error));
9853 aot_printerrf (acfg, "Run with MONO_LOG_LEVEL=debug for more information.\n");
9854 mono_error_cleanup (&error);
9858 /* Load all methods eagerly to skip the slower lazy loading code */
9859 mono_class_setup_methods (method->klass);
9861 if (mono_aot_mode_is_full (&acfg->aot_opts) && method->iflags & METHOD_IMPL_ATTRIBUTE_INTERNAL_CALL) {
9862 /* Compile the wrapper instead */
9863 /* We do this here instead of add_wrappers () because it is easy to do it here */
9864 MonoMethod *wrapper = mono_marshal_get_native_wrapper (method, TRUE, TRUE);
9868 /* FIXME: Some mscorlib methods don't have debug info */
9870 if (acfg->aot_opts.soft_debug && !method->wrapper_type) {
9871 if (!((method->flags & METHOD_ATTRIBUTE_PINVOKE_IMPL) ||
9872 (method->iflags & METHOD_IMPL_ATTRIBUTE_RUNTIME) ||
9873 (method->flags & METHOD_ATTRIBUTE_ABSTRACT) ||
9874 (method->iflags & METHOD_IMPL_ATTRIBUTE_INTERNAL_CALL))) {
9875 if (!mono_debug_lookup_method (method)) {
9876 fprintf (stderr, "Method %s has no debug info, probably the .mdb file for the assembly is missing.\n", mono_method_get_full_name (method));
9883 if (method->is_generic || method->klass->generic_container)
9884 /* Compile the ref shared version instead */
9885 method = mini_get_shared_method (method);
9887 /* Since we add the normal methods first, their index will be equal to their zero based token index */
9888 add_method_with_index (acfg, method, i, FALSE);
9889 acfg->method_index ++;
9892 /* gsharedvt methods */
9893 for (mindex = 0; mindex < image->tables [MONO_TABLE_METHOD].rows; ++mindex) {
9896 guint32 token = MONO_TOKEN_METHOD_DEF | (mindex + 1);
9898 if (!(acfg->opts & MONO_OPT_GSHAREDVT))
9901 method = mono_get_method_checked (acfg->image, token, NULL, NULL, &error);
9902 report_loader_error (acfg, &error, "Failed to load method token 0x%x due to %s\n", i, mono_error_get_message (&error));
9904 if (method->is_generic || method->klass->generic_container) {
9905 MonoMethod *gshared;
9907 gshared = mini_get_shared_method_full (method, TRUE, TRUE);
9908 add_extra_method (acfg, gshared);
9912 add_generic_instances (acfg);
9914 if (mono_aot_mode_is_full (&acfg->aot_opts))
9915 add_wrappers (acfg);
9920 compile_methods (MonoAotCompile *acfg)
9924 if (acfg->aot_opts.nthreads > 0) {
9929 gpointer *user_data;
9930 MonoMethod **methods;
9932 methods_len = acfg->methods->len;
9934 len = acfg->methods->len / acfg->aot_opts.nthreads;
9937 * Partition the list of methods into fragments, and hand it to threads to
9940 threads = g_ptr_array_new ();
9941 /* Make a copy since acfg->methods is modified by compile_method () */
9942 methods = g_new0 (MonoMethod*, methods_len);
9943 //memcpy (methods, g_ptr_array_index (acfg->methods, 0), sizeof (MonoMethod*) * methods_len);
9944 for (i = 0; i < methods_len; ++i)
9945 methods [i] = (MonoMethod *)g_ptr_array_index (acfg->methods, i);
9947 while (i < methods_len) {
9948 frag = g_ptr_array_new ();
9949 for (j = 0; j < len; ++j) {
9950 if (i < methods_len) {
9951 g_ptr_array_add (frag, methods [i]);
9956 user_data = g_new0 (gpointer, 3);
9957 user_data [0] = mono_domain_get ();
9958 user_data [1] = acfg;
9959 user_data [2] = frag;
9961 handle = mono_threads_create_thread ((LPTHREAD_START_ROUTINE)compile_thread_main, user_data, 0, 0, NULL);
9962 g_ptr_array_add (threads, handle);
9966 for (i = 0; i < threads->len; ++i) {
9967 WaitForSingleObjectEx (g_ptr_array_index (threads, i), INFINITE, FALSE);
9973 /* Compile methods added by compile_method () or all methods if nthreads == 0 */
9974 for (i = methods_len; i < acfg->methods->len; ++i) {
9975 /* This can new methods to acfg->methods */
9976 compile_method (acfg, (MonoMethod *)g_ptr_array_index (acfg->methods, i));
9981 compile_asm (MonoAotCompile *acfg)
9983 char *command, *objfile;
9984 char *outfile_name, *tmp_outfile_name, *llvm_ofile;
9985 const char *tool_prefix = acfg->aot_opts.tool_prefix ? acfg->aot_opts.tool_prefix : "";
9986 char *ld_flags = acfg->aot_opts.ld_flags ? acfg->aot_opts.ld_flags : g_strdup("");
9988 #if defined(TARGET_AMD64) && !defined(TARGET_MACH)
9989 #define AS_OPTIONS "--64"
9990 #elif defined(TARGET_POWERPC64)
9991 #define AS_OPTIONS "-a64 -mppc64"
9992 #elif defined(sparc) && SIZEOF_VOID_P == 8
9993 #define AS_OPTIONS "-xarch=v9"
9994 #elif defined(TARGET_X86) && defined(TARGET_MACH) && !defined(__native_client_codegen__)
9995 #define AS_OPTIONS "-arch i386"
9997 #define AS_OPTIONS ""
10000 #ifdef __native_client_codegen__
10001 #if defined(TARGET_AMD64)
10002 #define AS_NAME "nacl64-as"
10004 #define AS_NAME "nacl-as"
10006 #elif defined(TARGET_OSX)
10007 #define AS_NAME "clang"
10009 #define AS_NAME "as"
10013 #define LD_NAME "ld"
10014 #define LD_OPTIONS "-shared -G"
10015 #elif defined(__ppc__) && defined(TARGET_MACH)
10016 #define LD_NAME "gcc"
10017 #define LD_OPTIONS "-dynamiclib"
10018 #elif defined(TARGET_AMD64) && defined(TARGET_MACH)
10019 #define LD_NAME "clang"
10020 #define LD_OPTIONS "--shared"
10021 #elif defined(TARGET_WIN32) && !defined(TARGET_ANDROID)
10022 #define LD_NAME "gcc"
10023 #define LD_OPTIONS "-shared"
10024 #elif defined(TARGET_X86) && defined(TARGET_MACH) && !defined(__native_client_codegen__)
10025 #define LD_NAME "clang"
10026 #define LD_OPTIONS "-m32 -dynamiclib"
10027 #elif defined(TARGET_ARM) && !defined(TARGET_ANDROID)
10028 #define LD_NAME "gcc"
10029 #define LD_OPTIONS "--shared"
10030 #elif defined(TARGET_POWERPC64)
10031 #define LD_OPTIONS "-m elf64ppc"
10035 #define LD_OPTIONS ""
10038 if (acfg->aot_opts.asm_only) {
10039 aot_printf (acfg, "Output file: '%s'.\n", acfg->tmpfname);
10040 if (acfg->aot_opts.static_link)
10041 aot_printf (acfg, "Linking symbol: '%s'.\n", acfg->static_linking_symbol);
10043 aot_printf (acfg, "LLVM output file: '%s'.\n", acfg->llvm_sfile);
10047 if (acfg->aot_opts.static_link) {
10048 if (acfg->aot_opts.outfile)
10049 objfile = g_strdup_printf ("%s", acfg->aot_opts.outfile);
10051 objfile = g_strdup_printf ("%s.o", acfg->image->name);
10053 objfile = g_strdup_printf ("%s.o", acfg->tmpfname);
10057 g_string_append (acfg->as_args, "-c -x assembler");
10060 command = g_strdup_printf ("\"%s%s\" %s %s -o %s %s", tool_prefix, AS_NAME, AS_OPTIONS,
10061 acfg->as_args ? acfg->as_args->str : "",
10062 wrap_path (objfile), wrap_path (acfg->tmpfname));
10063 aot_printf (acfg, "Executing the native assembler: %s\n", command);
10064 if (execute_system (command) != 0) {
10070 if (acfg->llvm && !acfg->llvm_owriter) {
10071 command = g_strdup_printf ("\"%s%s\" %s %s -o %s %s", tool_prefix, AS_NAME, AS_OPTIONS,
10072 acfg->as_args ? acfg->as_args->str : "",
10073 wrap_path (acfg->llvm_ofile), wrap_path (acfg->llvm_sfile));
10074 aot_printf (acfg, "Executing the native assembler: %s\n", command);
10075 if (execute_system (command) != 0) {
10084 if (acfg->aot_opts.static_link) {
10085 aot_printf (acfg, "Output file: '%s'.\n", objfile);
10086 aot_printf (acfg, "Linking symbol: '%s'.\n", acfg->static_linking_symbol);
10091 if (acfg->aot_opts.outfile)
10092 outfile_name = g_strdup_printf ("%s", acfg->aot_opts.outfile);
10094 outfile_name = g_strdup_printf ("%s%s", acfg->image->name, MONO_SOLIB_EXT);
10096 tmp_outfile_name = g_strdup_printf ("%s.tmp", outfile_name);
10099 llvm_ofile = g_strdup_printf ("\"%s\"", acfg->llvm_ofile);
10101 llvm_ofile = g_strdup ("");
10104 /* replace the ; flags separators with spaces */
10105 g_strdelimit (ld_flags, ";", ' ');
10107 if (acfg->aot_opts.llvm_only)
10108 ld_flags = g_strdup_printf ("%s %s", ld_flags, "-lstdc++");
10111 command = g_strdup_printf ("%s%s %s -o %s %s %s %s", tool_prefix, LD_NAME, LD_OPTIONS,
10112 wrap_path (tmp_outfile_name), wrap_path (llvm_ofile),
10113 wrap_path (g_strdup_printf ("%s.o", acfg->tmpfname)), ld_flags);
10116 command = g_strdup_printf ("\"%sld\" %s -shared -o %s %s %s %s", tool_prefix, LD_OPTIONS,
10117 wrap_path (tmp_outfile_name), wrap_path (llvm_ofile),
10118 wrap_path (g_strdup_printf ("%s.o", acfg->tmpfname)), ld_flags);
10120 aot_printf (acfg, "Executing the native linker: %s\n", command);
10121 if (execute_system (command) != 0) {
10122 g_free (tmp_outfile_name);
10123 g_free (outfile_name);
10132 /*com = g_strdup_printf ("strip --strip-unneeded %s%s", acfg->image->name, MONO_SOLIB_EXT);
10133 printf ("Stripping the binary: %s\n", com);
10134 execute_system (com);
10137 #if defined(TARGET_ARM) && !defined(TARGET_MACH)
10139 * gas generates 'mapping symbols' each time code and data is mixed, which
10140 * happens a lot in emit_and_reloc_code (), so we need to get rid of them.
10142 command = g_strdup_printf ("\"%sstrip\" --strip-symbol=\\$a --strip-symbol=\\$d %s", tool_prefix, tmp_outfile_name);
10143 aot_printf (acfg, "Stripping the binary: %s\n", command);
10144 if (execute_system (command) != 0) {
10145 g_free (tmp_outfile_name);
10146 g_free (outfile_name);
10153 if (0 != rename (tmp_outfile_name, outfile_name)) {
10154 if (G_FILE_ERROR_EXIST == g_file_error_from_errno (errno)) {
10155 /* Since we are rebuilding the module we need to be able to replace any old copies. Remove old file and retry rename operation. */
10156 unlink (outfile_name);
10157 rename (tmp_outfile_name, outfile_name);
10161 #if defined(TARGET_MACH)
10162 command = g_strdup_printf ("dsymutil \"%s\"", outfile_name);
10163 aot_printf (acfg, "Executing dsymutil: %s\n", command);
10164 if (execute_system (command) != 0) {
10169 if (!acfg->aot_opts.save_temps)
10172 g_free (tmp_outfile_name);
10173 g_free (outfile_name);
10176 if (acfg->aot_opts.save_temps)
10177 aot_printf (acfg, "Retained input file.\n");
10179 unlink (acfg->tmpfname);
10184 static void init_got_info (GotInfo *info)
10188 info->patch_to_got_offset = g_hash_table_new (mono_patch_info_hash, mono_patch_info_equal);
10189 info->patch_to_got_offset_by_type = g_new0 (GHashTable*, MONO_PATCH_INFO_NUM);
10190 for (i = 0; i < MONO_PATCH_INFO_NUM; ++i)
10191 info->patch_to_got_offset_by_type [i] = g_hash_table_new (mono_patch_info_hash, mono_patch_info_equal);
10192 info->got_patches = g_ptr_array_new ();
10195 static MonoAotCompile*
10196 acfg_create (MonoAssembly *ass, guint32 opts)
10198 MonoImage *image = ass->image;
10199 MonoAotCompile *acfg;
10201 acfg = g_new0 (MonoAotCompile, 1);
10202 acfg->methods = g_ptr_array_new ();
10203 acfg->method_indexes = g_hash_table_new (NULL, NULL);
10204 acfg->method_depth = g_hash_table_new (NULL, NULL);
10205 acfg->plt_offset_to_entry = g_hash_table_new (NULL, NULL);
10206 acfg->patch_to_plt_entry = g_new0 (GHashTable*, MONO_PATCH_INFO_NUM);
10207 acfg->method_to_cfg = g_hash_table_new (NULL, NULL);
10208 acfg->token_info_hash = g_hash_table_new_full (NULL, NULL, NULL, NULL);
10209 acfg->method_to_pinvoke_import = g_hash_table_new_full (NULL, NULL, NULL, g_free);
10210 acfg->image_hash = g_hash_table_new (NULL, NULL);
10211 acfg->image_table = g_ptr_array_new ();
10212 acfg->globals = g_ptr_array_new ();
10213 acfg->image = image;
10215 /* TODO: Write out set of SIMD instructions used, rather than just those available */
10216 acfg->simd_opts = mono_arch_cpu_enumerate_simd_versions ();
10217 acfg->mempool = mono_mempool_new ();
10218 acfg->extra_methods = g_ptr_array_new ();
10219 acfg->unwind_info_offsets = g_hash_table_new (NULL, NULL);
10220 acfg->unwind_ops = g_ptr_array_new ();
10221 acfg->method_label_hash = g_hash_table_new_full (g_str_hash, g_str_equal, g_free, NULL);
10222 acfg->method_order = g_ptr_array_new ();
10223 acfg->export_names = g_hash_table_new (NULL, NULL);
10224 acfg->klass_blob_hash = g_hash_table_new (NULL, NULL);
10225 acfg->method_blob_hash = g_hash_table_new (NULL, NULL);
10226 acfg->plt_entry_debug_sym_cache = g_hash_table_new (g_str_hash, g_str_equal);
10227 acfg->gsharedvt_in_signatures = g_hash_table_new ((GHashFunc)mono_signature_hash, (GEqualFunc)mono_metadata_signature_equal);
10228 acfg->gsharedvt_out_signatures = g_hash_table_new ((GHashFunc)mono_signature_hash, (GEqualFunc)mono_metadata_signature_equal);
10229 mono_os_mutex_init_recursive (&acfg->mutex);
10231 init_got_info (&acfg->got_info);
10232 init_got_info (&acfg->llvm_got_info);
10238 got_info_free (GotInfo *info)
10242 for (i = 0; i < MONO_PATCH_INFO_NUM; ++i)
10243 g_hash_table_destroy (info->patch_to_got_offset_by_type [i]);
10244 g_free (info->patch_to_got_offset_by_type);
10245 g_hash_table_destroy (info->patch_to_got_offset);
10246 g_ptr_array_free (info->got_patches, TRUE);
10250 acfg_free (MonoAotCompile *acfg)
10254 mono_img_writer_destroy (acfg->w);
10255 for (i = 0; i < acfg->nmethods; ++i)
10256 if (acfg->cfgs [i])
10257 g_free (acfg->cfgs [i]);
10258 g_free (acfg->cfgs);
10259 g_free (acfg->static_linking_symbol);
10260 g_free (acfg->got_symbol);
10261 g_free (acfg->plt_symbol);
10262 g_ptr_array_free (acfg->methods, TRUE);
10263 g_ptr_array_free (acfg->image_table, TRUE);
10264 g_ptr_array_free (acfg->globals, TRUE);
10265 g_ptr_array_free (acfg->unwind_ops, TRUE);
10266 g_hash_table_destroy (acfg->method_indexes);
10267 g_hash_table_destroy (acfg->method_depth);
10268 g_hash_table_destroy (acfg->plt_offset_to_entry);
10269 for (i = 0; i < MONO_PATCH_INFO_NUM; ++i) {
10270 if (acfg->patch_to_plt_entry [i])
10271 g_hash_table_destroy (acfg->patch_to_plt_entry [i]);
10273 g_free (acfg->patch_to_plt_entry);
10274 g_hash_table_destroy (acfg->method_to_cfg);
10275 g_hash_table_destroy (acfg->token_info_hash);
10276 g_hash_table_destroy (acfg->method_to_pinvoke_import);
10277 g_hash_table_destroy (acfg->image_hash);
10278 g_hash_table_destroy (acfg->unwind_info_offsets);
10279 g_hash_table_destroy (acfg->method_label_hash);
10280 g_hash_table_destroy (acfg->export_names);
10281 g_hash_table_destroy (acfg->plt_entry_debug_sym_cache);
10282 g_hash_table_destroy (acfg->klass_blob_hash);
10283 g_hash_table_destroy (acfg->method_blob_hash);
10284 got_info_free (&acfg->got_info);
10285 got_info_free (&acfg->llvm_got_info);
10286 mono_mempool_destroy (acfg->mempool);
10290 #define WRAPPER(e,n) n,
10291 static const char* const
10292 wrapper_type_names [MONO_WRAPPER_NUM + 1] = {
10293 #include "mono/metadata/wrapper-types.h"
10297 static G_GNUC_UNUSED const char*
10298 get_wrapper_type_name (int type)
10300 return wrapper_type_names [type];
10306 static void aot_dump (MonoAotCompile *acfg)
10312 mono_json_writer_init (&writer);
10314 mono_json_writer_object_begin(&writer);
10317 mono_json_writer_indent (&writer);
10318 mono_json_writer_object_key(&writer, "methods");
10319 mono_json_writer_array_begin (&writer);
10322 for (i = 0; i < acfg->nmethods; ++i) {
10324 MonoMethod *method;
10327 cfg = acfg->cfgs [i];
10331 method = cfg->orig_method;
10333 mono_json_writer_indent (&writer);
10334 mono_json_writer_object_begin(&writer);
10336 mono_json_writer_indent (&writer);
10337 mono_json_writer_object_key(&writer, "name");
10338 mono_json_writer_printf (&writer, "\"%s\",\n", method->name);
10340 mono_json_writer_indent (&writer);
10341 mono_json_writer_object_key(&writer, "signature");
10342 mono_json_writer_printf (&writer, "\"%s\",\n", mono_method_get_full_name (method));
10344 mono_json_writer_indent (&writer);
10345 mono_json_writer_object_key(&writer, "code_size");
10346 mono_json_writer_printf (&writer, "\"%d\",\n", cfg->code_size);
10348 klass = method->klass;
10350 mono_json_writer_indent (&writer);
10351 mono_json_writer_object_key(&writer, "class");
10352 mono_json_writer_printf (&writer, "\"%s\",\n", klass->name);
10354 mono_json_writer_indent (&writer);
10355 mono_json_writer_object_key(&writer, "namespace");
10356 mono_json_writer_printf (&writer, "\"%s\",\n", klass->name_space);
10358 mono_json_writer_indent (&writer);
10359 mono_json_writer_object_key(&writer, "wrapper_type");
10360 mono_json_writer_printf (&writer, "\"%s\",\n", get_wrapper_type_name(method->wrapper_type));
10362 mono_json_writer_indent_pop (&writer);
10363 mono_json_writer_indent (&writer);
10364 mono_json_writer_object_end (&writer);
10365 mono_json_writer_printf (&writer, ",\n");
10368 mono_json_writer_indent_pop (&writer);
10369 mono_json_writer_indent (&writer);
10370 mono_json_writer_array_end (&writer);
10371 mono_json_writer_printf (&writer, ",\n");
10375 mono_json_writer_indent_push (&writer);
10376 mono_json_writer_indent (&writer);
10377 mono_json_writer_object_key(&writer, "plt");
10378 mono_json_writer_array_begin (&writer);
10380 for (i = 0; i < acfg->plt_offset; ++i) {
10381 MonoPltEntry *plt_entry = NULL;
10386 * The first plt entry is unused.
10390 plt_entry = g_hash_table_lookup (acfg->plt_offset_to_entry, GUINT_TO_POINTER (i));
10391 ji = plt_entry->ji;
10393 mono_json_writer_indent (&writer);
10394 mono_json_writer_printf (&writer, "{ ");
10395 mono_json_writer_object_key(&writer, "symbol");
10396 mono_json_writer_printf (&writer, "\"%s\" },\n", plt_entry->symbol);
10399 mono_json_writer_indent_pop (&writer);
10400 mono_json_writer_indent (&writer);
10401 mono_json_writer_array_end (&writer);
10402 mono_json_writer_printf (&writer, ",\n");
10407 mono_json_writer_indent_push (&writer);
10408 mono_json_writer_indent (&writer);
10409 mono_json_writer_object_key(&writer, "got");
10410 mono_json_writer_array_begin (&writer);
10412 mono_json_writer_indent_push (&writer);
10413 for (i = 0; i < acfg->got_info.got_patches->len; ++i) {
10414 MonoJumpInfo *ji = g_ptr_array_index (acfg->got_info.got_patches, i);
10416 mono_json_writer_indent (&writer);
10417 mono_json_writer_printf (&writer, "{ ");
10418 mono_json_writer_object_key(&writer, "patch_name");
10419 mono_json_writer_printf (&writer, "\"%s\" },\n", get_patch_name (ji->type));
10422 mono_json_writer_indent_pop (&writer);
10423 mono_json_writer_indent (&writer);
10424 mono_json_writer_array_end (&writer);
10425 mono_json_writer_printf (&writer, ",\n");
10428 mono_json_writer_indent_pop (&writer);
10429 mono_json_writer_indent (&writer);
10430 mono_json_writer_object_end (&writer);
10432 dumpname = g_strdup_printf ("%s.json", g_path_get_basename (acfg->image->name));
10433 dumpfile = fopen (dumpname, "w+");
10436 fprintf (dumpfile, "%s", writer.text->str);
10439 mono_json_writer_destroy (&writer);
10442 static const char *preinited_jit_icalls[] = {
10443 "mono_aot_init_llvm_method",
10444 "mono_aot_init_gshared_method_this",
10445 "mono_aot_init_gshared_method_mrgctx",
10446 "mono_aot_init_gshared_method_vtable",
10447 "mono_llvm_throw_corlib_exception",
10448 "mono_init_vtable_slot",
10449 "mono_helper_ldstr_mscorlib"
10453 add_preinit_got_slots (MonoAotCompile *acfg)
10459 * Allocate the first few GOT entries to information which is needed frequently, or it is needed
10460 * during method initialization etc.
10463 ji = (MonoJumpInfo *)mono_mempool_alloc0 (acfg->mempool, sizeof (MonoJumpInfo));
10464 ji->type = MONO_PATCH_INFO_IMAGE;
10465 ji->data.image = acfg->image;
10466 get_got_offset (acfg, FALSE, ji);
10467 get_got_offset (acfg, TRUE, ji);
10469 ji = (MonoJumpInfo *)mono_mempool_alloc0 (acfg->mempool, sizeof (MonoJumpInfo));
10470 ji->type = MONO_PATCH_INFO_MSCORLIB_GOT_ADDR;
10471 get_got_offset (acfg, FALSE, ji);
10472 get_got_offset (acfg, TRUE, ji);
10474 ji = (MonoJumpInfo *)mono_mempool_alloc0 (acfg->mempool, sizeof (MonoJumpInfo));
10475 ji->type = MONO_PATCH_INFO_GC_CARD_TABLE_ADDR;
10476 get_got_offset (acfg, FALSE, ji);
10477 get_got_offset (acfg, TRUE, ji);
10479 ji = (MonoJumpInfo *)mono_mempool_alloc0 (acfg->mempool, sizeof (MonoJumpInfo));
10480 ji->type = MONO_PATCH_INFO_GC_NURSERY_START;
10481 get_got_offset (acfg, FALSE, ji);
10482 get_got_offset (acfg, TRUE, ji);
10484 ji = (MonoJumpInfo *)mono_mempool_alloc0 (acfg->mempool, sizeof (MonoJumpInfo));
10485 ji->type = MONO_PATCH_INFO_JIT_TLS_ID;
10486 get_got_offset (acfg, FALSE, ji);
10487 get_got_offset (acfg, TRUE, ji);
10489 ji = (MonoJumpInfo *)mono_mempool_alloc0 (acfg->mempool, sizeof (MonoJumpInfo));
10490 ji->type = MONO_PATCH_INFO_AOT_MODULE;
10491 get_got_offset (acfg, FALSE, ji);
10492 get_got_offset (acfg, TRUE, ji);
10494 ji = (MonoJumpInfo *)mono_mempool_alloc0 (acfg->mempool, sizeof (MonoJumpInfo));
10495 ji->type = MONO_PATCH_INFO_GC_NURSERY_BITS;
10496 get_got_offset (acfg, FALSE, ji);
10497 get_got_offset (acfg, TRUE, ji);
10499 for (i = 0; i < sizeof (preinited_jit_icalls) / sizeof (char*); ++i) {
10500 ji = (MonoJumpInfo *)mono_mempool_alloc0 (acfg->mempool, sizeof (MonoAotCompile));
10501 ji->type = MONO_PATCH_INFO_INTERNAL_METHOD;
10502 ji->data.name = preinited_jit_icalls [i];
10503 get_got_offset (acfg, FALSE, ji);
10504 get_got_offset (acfg, TRUE, ji);
10507 acfg->nshared_got_entries = acfg->got_offset;
10511 mono_compile_assembly (MonoAssembly *ass, guint32 opts, const char *aot_options)
10513 MonoImage *image = ass->image;
10516 MonoAotCompile *acfg;
10517 char *outfile_name, *tmp_outfile_name, *p;
10518 char llvm_stats_msg [256];
10522 acfg = acfg_create (ass, opts);
10524 memset (&acfg->aot_opts, 0, sizeof (acfg->aot_opts));
10525 acfg->aot_opts.write_symbols = TRUE;
10526 acfg->aot_opts.ntrampolines = 4096;
10527 acfg->aot_opts.nrgctx_trampolines = 4096;
10528 acfg->aot_opts.nimt_trampolines = 512;
10529 acfg->aot_opts.nrgctx_fetch_trampolines = 128;
10530 acfg->aot_opts.ngsharedvt_arg_trampolines = 512;
10531 acfg->aot_opts.llvm_path = g_strdup ("");
10532 acfg->aot_opts.temp_path = g_strdup ("");
10534 acfg->aot_opts.use_trampolines_page = TRUE;
10537 mono_aot_parse_options (aot_options, &acfg->aot_opts);
10539 if (acfg->aot_opts.logfile) {
10540 acfg->logfile = fopen (acfg->aot_opts.logfile, "a+");
10543 if (acfg->aot_opts.data_outfile) {
10544 acfg->data_outfile = fopen (acfg->aot_opts.data_outfile, "w+");
10545 if (!acfg->data_outfile) {
10546 aot_printerrf (acfg, "Unable to create file '%s': %s\n", acfg->aot_opts.data_outfile, strerror (errno));
10549 acfg->flags = (MonoAotFileFlags)(acfg->flags | MONO_AOT_FILE_FLAG_SEPARATE_DATA);
10552 //acfg->aot_opts.print_skipped_methods = TRUE;
10554 #if !defined(MONO_ARCH_GSHAREDVT_SUPPORTED)
10555 if (opts & MONO_OPT_GSHAREDVT) {
10556 aot_printerrf (acfg, "-O=gsharedvt not supported on this platform.\n");
10561 #if !defined(MONO_ARCH_GSHAREDVT_SUPPORTED)
10562 if (!acfg->aot_opts.llvm_only && (opts & MONO_OPT_GSHAREDVT)) {
10563 aot_printerrf (acfg, "-O=gsharedvt not supported on this platform.\n");
10568 if (acfg->aot_opts.llvm_only) {
10569 #ifndef MONO_ARCH_GSHAREDVT_SUPPORTED
10570 aot_printerrf (acfg, "--aot=llvmonly requires a runtime that supports gsharedvt.\n");
10575 #if defined(MONO_ARCH_GSHAREDVT_SUPPORTED)
10576 if (acfg->aot_opts.llvm_only || mono_aot_mode_is_full (&acfg->aot_opts)) {
10577 acfg->opts |= MONO_OPT_GSHAREDVT;
10578 opts |= MONO_OPT_GSHAREDVT;
10582 if (opts & MONO_OPT_GSHAREDVT)
10583 mono_set_generic_sharing_vt_supported (TRUE);
10585 aot_printf (acfg, "Mono Ahead of Time compiler - compiling assembly %s\n", image->name);
10587 #ifndef MONO_ARCH_HAVE_FULL_AOT_TRAMPOLINES
10588 if (mono_aot_mode_is_full (&acfg->aot_opts)) {
10589 aot_printerrf (acfg, "--aot=full is not supported on this platform.\n");
10594 if (acfg->aot_opts.direct_pinvoke && !acfg->aot_opts.static_link) {
10595 aot_printerrf (acfg, "The 'direct-pinvoke' AOT option also requires the 'static' AOT option.\n");
10599 if (acfg->aot_opts.static_link)
10600 acfg->aot_opts.asm_writer = TRUE;
10602 if (acfg->aot_opts.soft_debug) {
10603 MonoDebugOptions *opt = mini_get_debug_options ();
10605 opt->mdb_optimizations = TRUE;
10606 opt->gen_sdb_seq_points = TRUE;
10608 if (!mono_debug_enabled ()) {
10609 aot_printerrf (acfg, "The soft-debug AOT option requires the --debug option.\n");
10612 acfg->flags = (MonoAotFileFlags)(acfg->flags | MONO_AOT_FILE_FLAG_DEBUG);
10615 if (mono_use_llvm || acfg->aot_opts.llvm) {
10617 acfg->aot_opts.asm_writer = TRUE;
10618 acfg->flags = (MonoAotFileFlags)(acfg->flags | MONO_AOT_FILE_FLAG_WITH_LLVM);
10620 if (acfg->aot_opts.soft_debug) {
10621 aot_printerrf (acfg, "The 'soft-debug' option is not supported when compiling with LLVM.\n");
10627 if (acfg->aot_opts.asm_only && !acfg->aot_opts.llvm_outfile) {
10628 aot_printerrf (acfg, "Compiling with LLVM and the asm-only option requires the llvm-outputfile= option.");
10633 * Emit all LLVM code into a separate assembly/object file and link with it
10636 if (!acfg->aot_opts.asm_only) {
10637 acfg->llvm_owriter = TRUE;
10638 } else if (acfg->aot_opts.llvm_outfile) {
10639 int len = strlen (acfg->aot_opts.llvm_outfile);
10641 if (len >= 2 && acfg->aot_opts.llvm_outfile [len - 2] == '.' && acfg->aot_opts.llvm_outfile [len - 1] == 'o')
10642 acfg->llvm_owriter = TRUE;
10646 if (mono_aot_mode_is_full (&acfg->aot_opts))
10647 acfg->flags = (MonoAotFileFlags)(acfg->flags | MONO_AOT_FILE_FLAG_FULL_AOT);
10649 if (mono_threads_is_coop_enabled ())
10650 acfg->flags = (MonoAotFileFlags)(acfg->flags | MONO_AOT_FILE_FLAG_SAFEPOINTS);
10652 if (acfg->aot_opts.instances_logfile_path) {
10653 acfg->instances_logfile = fopen (acfg->aot_opts.instances_logfile_path, "w");
10654 if (!acfg->instances_logfile) {
10655 aot_printerrf (acfg, "Unable to create logfile: '%s'.\n", acfg->aot_opts.instances_logfile_path);
10660 load_profile_files (acfg);
10662 acfg->num_trampolines [MONO_AOT_TRAMP_SPECIFIC] = mono_aot_mode_is_full (&acfg->aot_opts) ? acfg->aot_opts.ntrampolines : 0;
10663 #ifdef MONO_ARCH_GSHARED_SUPPORTED
10664 acfg->num_trampolines [MONO_AOT_TRAMP_STATIC_RGCTX] = mono_aot_mode_is_full (&acfg->aot_opts) ? acfg->aot_opts.nrgctx_trampolines : 0;
10666 acfg->num_trampolines [MONO_AOT_TRAMP_IMT_THUNK] = mono_aot_mode_is_full (&acfg->aot_opts) ? acfg->aot_opts.nimt_trampolines : 0;
10667 #ifdef MONO_ARCH_GSHAREDVT_SUPPORTED
10668 if (acfg->opts & MONO_OPT_GSHAREDVT)
10669 acfg->num_trampolines [MONO_AOT_TRAMP_GSHAREDVT_ARG] = mono_aot_mode_is_full (&acfg->aot_opts) ? acfg->aot_opts.ngsharedvt_arg_trampolines : 0;
10672 acfg->temp_prefix = mono_img_writer_get_temp_label_prefix (NULL);
10676 if (acfg->llvm && acfg->thumb_mixed)
10677 acfg->flags = (MonoAotFileFlags)(acfg->flags | MONO_AOT_FILE_FLAG_LLVM_THUMB);
10678 if (acfg->aot_opts.llvm_only)
10679 acfg->flags = (MonoAotFileFlags)(acfg->flags | MONO_AOT_FILE_FLAG_LLVM_ONLY);
10681 acfg->assembly_name_sym = g_strdup (acfg->image->assembly->aname.name);
10682 /* Get rid of characters which cannot occur in symbols */
10683 for (p = acfg->assembly_name_sym; *p; ++p) {
10684 if (!(isalnum (*p) || *p == '_'))
10688 acfg->global_prefix = g_strdup_printf ("mono_aot_%s", acfg->assembly_name_sym);
10689 acfg->plt_symbol = g_strdup_printf ("%s_plt", acfg->global_prefix);
10690 acfg->got_symbol = g_strdup_printf ("%s_got", acfg->global_prefix);
10692 acfg->llvm_got_symbol = g_strdup_printf ("%s_llvm_got", acfg->global_prefix);
10693 acfg->llvm_eh_frame_symbol = g_strdup_printf ("%s_eh_frame", acfg->global_prefix);
10696 acfg->method_index = 1;
10698 if (mono_aot_mode_is_full (&acfg->aot_opts))
10699 mono_set_partial_sharing_supported (TRUE);
10701 res = collect_methods (acfg);
10705 acfg->cfgs_size = acfg->methods->len + 32;
10706 acfg->cfgs = g_new0 (MonoCompile*, acfg->cfgs_size);
10708 /* PLT offset 0 is reserved for the PLT trampoline */
10709 acfg->plt_offset = 1;
10710 add_preinit_got_slots (acfg);
10715 mono_llvm_create_aot_module (acfg->image->assembly, acfg->global_prefix, TRUE, acfg->aot_opts.static_link, acfg->aot_opts.llvm_only);
10721 compile_methods (acfg);
10725 acfg->stats.jit_time = TV_ELAPSED (atv, btv);
10731 if (acfg->aot_opts.asm_only) {
10732 if (acfg->aot_opts.outfile) {
10733 acfg->tmpfname = g_strdup_printf ("%s", acfg->aot_opts.outfile);
10734 acfg->tmpbasename = g_strdup (acfg->tmpfname);
10736 acfg->tmpbasename = g_strdup_printf ("%s", acfg->image->name);
10737 acfg->tmpfname = g_strdup_printf ("%s.s", acfg->tmpbasename);
10739 g_assert (acfg->aot_opts.llvm_outfile);
10740 acfg->llvm_sfile = g_strdup (acfg->aot_opts.llvm_outfile);
10741 if (acfg->llvm_owriter)
10742 acfg->llvm_ofile = g_strdup (acfg->aot_opts.llvm_outfile);
10744 acfg->llvm_sfile = g_strdup (acfg->aot_opts.llvm_outfile);
10746 acfg->tmpbasename = (strcmp (acfg->aot_opts.temp_path, "") == 0) ?
10747 g_strdup_printf ("%s", "temp") :
10748 g_build_filename (acfg->aot_opts.temp_path, "temp", NULL);
10750 acfg->tmpfname = g_strdup_printf ("%s.s", acfg->tmpbasename);
10751 acfg->llvm_sfile = g_strdup_printf ("%s-llvm.s", acfg->tmpbasename);
10752 acfg->llvm_ofile = g_strdup_printf ("%s-llvm.o", acfg->tmpbasename);
10757 if (acfg->aot_opts.asm_only && !acfg->aot_opts.llvm_only) {
10758 if (acfg->aot_opts.outfile)
10759 acfg->tmpfname = g_strdup_printf ("%s", acfg->aot_opts.outfile);
10761 acfg->tmpfname = g_strdup_printf ("%s.s", acfg->image->name);
10762 acfg->fp = fopen (acfg->tmpfname, "w+");
10764 int i = g_file_open_tmp ("mono_aot_XXXXXX", &acfg->tmpfname, NULL);
10765 acfg->fp = fdopen (i, "w+");
10767 if (acfg->fp == 0 && !acfg->aot_opts.llvm_only) {
10768 aot_printerrf (acfg, "Unable to open file '%s': %s\n", acfg->tmpfname, strerror (errno));
10772 acfg->w = mono_img_writer_create (acfg->fp, FALSE);
10774 tmp_outfile_name = NULL;
10775 outfile_name = NULL;
10777 /* Compute symbols for methods */
10778 for (i = 0; i < acfg->nmethods; ++i) {
10779 if (acfg->cfgs [i]) {
10780 MonoCompile *cfg = acfg->cfgs [i];
10781 int method_index = get_method_index (acfg, cfg->orig_method);
10783 if (COMPILE_LLVM (cfg))
10784 cfg->asm_symbol = g_strdup_printf ("%s%s", acfg->llvm_label_prefix, cfg->llvm_method_name);
10785 else if (acfg->global_symbols || acfg->llvm)
10786 cfg->asm_symbol = get_debug_sym (cfg->orig_method, "", acfg->method_label_hash);
10788 cfg->asm_symbol = g_strdup_printf ("%s%sm_%x", acfg->temp_prefix, acfg->llvm_label_prefix, method_index);
10789 cfg->asm_debug_symbol = cfg->asm_symbol;
10793 if (acfg->aot_opts.dwarf_debug && acfg->aot_opts.gnu_asm) {
10795 * CLANG supports GAS .file/.loc directives, so emit line number information this way
10797 acfg->gas_line_numbers = TRUE;
10800 if ((!acfg->aot_opts.nodebug || acfg->aot_opts.dwarf_debug) && acfg->has_jitted_code) {
10801 if (acfg->aot_opts.dwarf_debug && !mono_debug_enabled ()) {
10802 aot_printerrf (acfg, "The dwarf AOT option requires the --debug option.\n");
10805 acfg->dwarf = mono_dwarf_writer_create (acfg->w, NULL, 0, !acfg->gas_line_numbers);
10809 mono_img_writer_emit_start (acfg->w);
10812 mono_dwarf_writer_emit_base_info (acfg->dwarf, g_path_get_basename (acfg->image->name), mono_unwind_get_cie_program ());
10818 emit_extra_methods (acfg);
10820 emit_trampolines (acfg);
10822 emit_class_name_table (acfg);
10824 emit_got_info (acfg, FALSE);
10826 emit_got_info (acfg, TRUE);
10828 emit_exception_info (acfg);
10830 emit_unwind_info (acfg);
10832 emit_class_info (acfg);
10836 emit_image_table (acfg);
10842 * The managed allocators are GC specific, so can't use an AOT image created by one GC
10845 const char *gc_name = mono_gc_get_gc_name ();
10846 acfg->gc_name_offset = add_to_blob (acfg, (guint8*)gc_name, strlen (gc_name) + 1);
10851 emit_objc_selectors (acfg);
10853 emit_globals (acfg);
10855 emit_file_info (acfg);
10858 emit_dwarf_info (acfg);
10859 mono_dwarf_writer_close (acfg->dwarf);
10862 emit_mem_end (acfg);
10864 if (acfg->need_pt_gnu_stack) {
10865 /* This is required so the .so doesn't have an executable stack */
10866 /* The bin writer already emits this */
10867 fprintf (acfg->fp, "\n.section .note.GNU-stack,\"\",@progbits\n");
10870 if (acfg->aot_opts.data_outfile)
10871 fclose (acfg->data_outfile);
10877 res = emit_llvm_file (acfg);
10885 acfg->stats.gen_time = TV_ELAPSED (atv, btv);
10888 sprintf (llvm_stats_msg, ", LLVM: %d (%d%%)", acfg->stats.llvm_count, acfg->stats.mcount ? (acfg->stats.llvm_count * 100) / acfg->stats.mcount : 100);
10890 strcpy (llvm_stats_msg, "");
10892 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;
10894 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",
10895 (int)acfg->stats.code_size, (int)(acfg->stats.code_size * 100 / all_sizes),
10896 (int)acfg->stats.info_size, (int)(acfg->stats.info_size * 100 / all_sizes),
10897 (int)acfg->stats.ex_info_size, (int)(acfg->stats.ex_info_size * 100 / all_sizes),
10898 (int)acfg->stats.unwind_info_size, (int)(acfg->stats.unwind_info_size * 100 / all_sizes),
10899 (int)acfg->stats.class_info_size, (int)(acfg->stats.class_info_size * 100 / all_sizes),
10900 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,
10901 (int)acfg->stats.got_info_size, (int)(acfg->stats.got_info_size * 100 / all_sizes),
10902 (int)acfg->stats.offsets_size, (int)(acfg->stats.offsets_size * 100 / all_sizes),
10903 (int)(acfg->got_offset * sizeof (gpointer)));
10904 aot_printf (acfg, "Compiled: %d/%d (%d%%)%s, No GOT slots: %d (%d%%), Direct calls: %d (%d%%)\n",
10905 acfg->stats.ccount, acfg->stats.mcount, acfg->stats.mcount ? (acfg->stats.ccount * 100) / acfg->stats.mcount : 100,
10907 acfg->stats.methods_without_got_slots, acfg->stats.mcount ? (acfg->stats.methods_without_got_slots * 100) / acfg->stats.mcount : 100,
10908 acfg->stats.direct_calls, acfg->stats.all_calls ? (acfg->stats.direct_calls * 100) / acfg->stats.all_calls : 100);
10909 if (acfg->stats.genericcount)
10910 aot_printf (acfg, "%d methods are generic (%d%%)\n", acfg->stats.genericcount, acfg->stats.mcount ? (acfg->stats.genericcount * 100) / acfg->stats.mcount : 100);
10911 if (acfg->stats.abscount)
10912 aot_printf (acfg, "%d methods contain absolute addresses (%d%%)\n", acfg->stats.abscount, acfg->stats.mcount ? (acfg->stats.abscount * 100) / acfg->stats.mcount : 100);
10913 if (acfg->stats.lmfcount)
10914 aot_printf (acfg, "%d methods contain lmf pointers (%d%%)\n", acfg->stats.lmfcount, acfg->stats.mcount ? (acfg->stats.lmfcount * 100) / acfg->stats.mcount : 100);
10915 if (acfg->stats.ocount)
10916 aot_printf (acfg, "%d methods have other problems (%d%%)\n", acfg->stats.ocount, acfg->stats.mcount ? (acfg->stats.ocount * 100) / acfg->stats.mcount : 100);
10920 res = mono_img_writer_emit_writeout (acfg->w);
10925 res = compile_asm (acfg);
10932 acfg->stats.link_time = TV_ELAPSED (atv, btv);
10934 if (acfg->aot_opts.stats) {
10937 aot_printf (acfg, "GOT slot distribution:\n");
10938 for (i = 0; i < MONO_PATCH_INFO_NUM; ++i)
10939 if (acfg->stats.got_slot_types [i])
10940 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]);
10941 aot_printf (acfg, "\nMethod stats:\n");
10942 aot_printf (acfg, "\tNormal: %d\n", acfg->stats.method_categories [METHOD_CAT_NORMAL]);
10943 aot_printf (acfg, "\tInstance: %d\n", acfg->stats.method_categories [METHOD_CAT_INST]);
10944 aot_printf (acfg, "\tGSharedvt: %d\n", acfg->stats.method_categories [METHOD_CAT_GSHAREDVT]);
10945 aot_printf (acfg, "\tWrapper: %d\n", acfg->stats.method_categories [METHOD_CAT_WRAPPER]);
10948 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);
10950 if (acfg->aot_opts.dump_json)
10963 mono_aot_readonly_field_override (MonoClassField *field)
10969 mono_compile_assembly (MonoAssembly *ass, guint32 opts, const char *aot_options)
10975 mono_aot_is_shared_got_offset (int offset)