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)
14 #include <sys/types.h>
34 #include <mono/metadata/abi-details.h>
35 #include <mono/metadata/tabledefs.h>
36 #include <mono/metadata/class.h>
37 #include <mono/metadata/object.h>
38 #include <mono/metadata/tokentype.h>
39 #include <mono/metadata/appdomain.h>
40 #include <mono/metadata/debug-helpers.h>
41 #include <mono/metadata/assembly.h>
42 #include <mono/metadata/metadata-internals.h>
43 #include <mono/metadata/marshal.h>
44 #include <mono/metadata/gc-internal.h>
45 #include <mono/metadata/monitor.h>
46 #include <mono/metadata/mempool-internals.h>
47 #include <mono/metadata/mono-endian.h>
48 #include <mono/metadata/threads-types.h>
49 #include <mono/utils/mono-logger-internal.h>
50 #include <mono/utils/mono-compiler.h>
51 #include <mono/utils/mono-time.h>
52 #include <mono/utils/mono-mmap.h>
53 #include <mono/utils/json.h>
56 #include "seq-points.h"
57 #include "image-writer.h"
58 #include "dwarfwriter.h"
61 #if !defined(DISABLE_AOT) && !defined(DISABLE_JIT)
63 #if defined(__linux__) || defined(__native_client_codegen__)
64 #define RODATA_SECT ".rodata"
65 #elif defined(TARGET_MACH)
66 #define RODATA_SECT ".section __TEXT, __const"
68 #define RODATA_SECT ".text"
71 #define TV_DECLARE(name) gint64 name
72 #define TV_GETTIME(tv) tv = mono_100ns_ticks ()
73 #define TV_ELAPSED(start,end) (((end) - (start)) / 10)
75 #define ALIGN_TO(val,align) ((((guint64)val) + ((align) - 1)) & ~((align) - 1))
76 #define ALIGN_PTR_TO(ptr,align) (gpointer)((((gssize)(ptr)) + (align - 1)) & (~(align - 1)))
77 #define ROUND_DOWN(VALUE,SIZE) ((VALUE) & ~((SIZE) - 1))
79 /* predefined values for static readonly fields without needed to run the .cctor */
80 typedef struct _ReadOnlyValue ReadOnlyValue;
81 struct _ReadOnlyValue {
84 int type; /* to be used later for typechecking to prevent user errors */
93 static ReadOnlyValue *readonly_values;
95 typedef struct MonoAotOptions {
99 gboolean write_symbols;
100 gboolean metadata_only;
101 gboolean bind_to_runtime_version;
104 gboolean static_link;
108 gboolean dwarf_debug;
110 gboolean log_generics;
111 gboolean log_instances;
112 gboolean gen_seq_points_file;
113 gboolean direct_pinvoke;
114 gboolean direct_icalls;
115 gboolean no_direct_calls;
116 gboolean use_trampolines_page;
117 gboolean no_instances;
122 int nrgctx_trampolines;
123 int nimt_trampolines;
124 int ngsharedvt_arg_trampolines;
125 int nrgctx_fetch_trampolines;
126 gboolean print_skipped_methods;
134 char *instances_logfile_path;
139 typedef struct MonoAotStats {
140 int ccount, mcount, lmfcount, abscount, gcount, ocount, genericcount;
141 gint64 code_size, info_size, ex_info_size, unwind_info_size, got_size, class_info_size, got_info_size, plt_size;
142 int methods_without_got_slots, direct_calls, all_calls, llvm_count;
143 int got_slots, offsets_size;
144 int got_slot_types [MONO_PATCH_INFO_NONE];
145 int got_slot_info_sizes [MONO_PATCH_INFO_NONE];
146 int jit_time, gen_time, link_time;
149 typedef struct GotInfo {
150 GHashTable *patch_to_got_offset;
151 GHashTable **patch_to_got_offset_by_type;
152 GPtrArray *got_patches;
155 typedef struct MonoAotCompile {
158 GHashTable *method_indexes;
159 GHashTable *method_depth;
162 GHashTable **patch_to_plt_entry;
163 GHashTable *plt_offset_to_entry;
164 //GHashTable *patch_to_got_offset;
165 //GHashTable **patch_to_got_offset_by_type;
166 //GPtrArray *got_patches;
167 GotInfo got_info, llvm_got_info;
168 GHashTable *image_hash;
169 GHashTable *method_to_cfg;
170 GHashTable *token_info_hash;
171 GHashTable *method_to_pinvoke_import;
172 GPtrArray *extra_methods;
173 GPtrArray *image_table;
175 GPtrArray *method_order;
176 GHashTable *export_names;
177 /* Maps MonoClass* -> blob offset */
178 GHashTable *klass_blob_hash;
179 /* Maps MonoMethod* -> blob offset */
180 GHashTable *method_blob_hash;
181 guint32 *plt_got_info_offsets;
182 guint32 got_offset, llvm_got_offset, plt_offset, plt_got_offset_base;
183 /* Number of GOT entries reserved for trampolines */
184 guint32 num_trampoline_got_entries;
185 guint32 tramp_page_size;
187 guint32 num_trampolines [MONO_AOT_TRAMP_NUM];
188 guint32 trampoline_got_offset_base [MONO_AOT_TRAMP_NUM];
189 guint32 trampoline_size [MONO_AOT_TRAMP_NUM];
190 guint32 tramp_page_code_offsets [MONO_AOT_TRAMP_NUM];
192 MonoAotOptions aot_opts;
196 MonoMemPool *mempool;
199 char *static_linking_symbol;
201 gboolean use_bin_writer;
202 gboolean gas_line_numbers;
203 /* Whenever to emit an object file directly from llc */
204 gboolean llvm_owriter;
206 MonoDwarfWriter *dwarf;
213 GHashTable *unwind_info_offsets;
214 GPtrArray *unwind_ops;
215 guint32 unwind_info_offset;
218 char *llvm_got_symbol;
220 char *llvm_eh_frame_symbol;
221 GHashTable *method_label_hash;
222 const char *temp_prefix;
223 const char *user_symbol_prefix;
224 const char *llvm_label_prefix;
225 const char *inst_directive;
227 guint32 label_generator;
229 gboolean has_jitted_code;
230 MonoAotFileFlags flags;
231 MonoDynamicStream blob;
232 MonoClass **typespec_classes;
235 char *assembly_name_sym;
236 GHashTable *plt_entry_debug_sym_cache;
237 gboolean thumb_mixed, need_no_dead_strip, need_pt_gnu_stack;
238 GHashTable *ginst_hash;
239 GHashTable *dwarf_ln_filenames;
240 gboolean global_symbols;
241 int objc_selector_index, objc_selector_index_2;
242 GPtrArray *objc_selectors;
243 GHashTable *objc_selector_to_index;
245 FILE *instances_logfile;
250 char *symbol, *llvm_symbol, *debug_sym;
252 gboolean jit_used, llvm_used;
255 #define mono_acfg_lock(acfg) mono_mutex_lock (&((acfg)->mutex))
256 #define mono_acfg_unlock(acfg) mono_mutex_unlock (&((acfg)->mutex))
258 /* This points to the current acfg in LLVM mode */
259 static MonoAotCompile *llvm_acfg;
261 #ifdef HAVE_ARRAY_ELEM_INIT
262 #define MSGSTRFIELD(line) MSGSTRFIELD1(line)
263 #define MSGSTRFIELD1(line) str##line
264 static const struct msgstr_t {
265 #define PATCH_INFO(a,b) char MSGSTRFIELD(__LINE__) [sizeof (b)];
266 #include "patch-info.h"
269 #define PATCH_INFO(a,b) b,
270 #include "patch-info.h"
273 static const gint16 opidx [] = {
274 #define PATCH_INFO(a,b) [MONO_PATCH_INFO_ ## a] = offsetof (struct msgstr_t, MSGSTRFIELD(__LINE__)),
275 #include "patch-info.h"
279 static G_GNUC_UNUSED const char*
280 get_patch_name (int info)
282 return (const char*)&opstr + opidx [info];
286 #define PATCH_INFO(a,b) b,
287 static const char* const
288 patch_types [MONO_PATCH_INFO_NUM + 1] = {
289 #include "patch-info.h"
293 static G_GNUC_UNUSED const char*
294 get_patch_name (int info)
296 return patch_types [info];
302 get_plt_entry_debug_sym (MonoAotCompile *acfg, MonoJumpInfo *ji, GHashTable *cache);
305 aot_printf (MonoAotCompile *acfg, const gchar *format, ...)
311 output = acfg->logfile;
315 va_start (args, format);
316 vfprintf (output, format, args);
321 aot_printerrf (MonoAotCompile *acfg, const gchar *format, ...)
327 output = acfg->logfile;
331 va_start (args, format);
332 vfprintf (output, format, args);
337 report_loader_error (MonoAotCompile *acfg, MonoError *error, const char *format, ...)
342 if (mono_error_ok (error))
346 output = acfg->logfile;
350 va_start (args, format);
351 vfprintf (output, format, args);
353 mono_error_cleanup (error);
355 g_error ("FullAOT cannot continue if there are loader errors");
358 /* Wrappers around the image writer functions */
361 emit_section_change (MonoAotCompile *acfg, const char *section_name, int subsection_index)
363 mono_img_writer_emit_section_change (acfg->w, section_name, subsection_index);
367 emit_local_symbol (MonoAotCompile *acfg, const char *name, const char *end_label, gboolean func)
369 mono_img_writer_emit_local_symbol (acfg->w, name, end_label, func);
373 emit_label (MonoAotCompile *acfg, const char *name)
375 mono_img_writer_emit_label (acfg->w, name);
379 emit_bytes (MonoAotCompile *acfg, const guint8* buf, int size)
381 mono_img_writer_emit_bytes (acfg->w, buf, size);
385 emit_string (MonoAotCompile *acfg, const char *value)
387 mono_img_writer_emit_string (acfg->w, value);
391 emit_line (MonoAotCompile *acfg)
393 mono_img_writer_emit_line (acfg->w);
397 emit_alignment (MonoAotCompile *acfg, int size)
399 mono_img_writer_emit_alignment (acfg->w, size);
403 emit_alignment_code (MonoAotCompile *acfg, int size)
405 if (acfg->align_pad_value)
406 mono_img_writer_emit_alignment_fill (acfg->w, size, acfg->align_pad_value);
408 mono_img_writer_emit_alignment (acfg->w, size);
412 emit_padding (MonoAotCompile *acfg, int size)
417 if (acfg->align_pad_value) {
418 for (i = 0; i < 16; ++i)
419 buf [i] = acfg->align_pad_value;
421 memset (buf, 0, sizeof (buf));
424 for (i = 0; i < size; i += 16) {
426 emit_bytes (acfg, buf, size - i);
428 emit_bytes (acfg, buf, 16);
433 emit_pointer (MonoAotCompile *acfg, const char *target)
435 mono_img_writer_emit_pointer (acfg->w, target);
439 emit_pointer_2 (MonoAotCompile *acfg, const char *prefix, const char *target)
441 if (prefix [0] != '\0') {
442 char *s = g_strdup_printf ("%s%s", prefix, target);
443 mono_img_writer_emit_pointer (acfg->w, s);
446 mono_img_writer_emit_pointer (acfg->w, target);
451 emit_int16 (MonoAotCompile *acfg, int value)
453 mono_img_writer_emit_int16 (acfg->w, value);
457 emit_int32 (MonoAotCompile *acfg, int value)
459 mono_img_writer_emit_int32 (acfg->w, value);
463 emit_symbol_diff (MonoAotCompile *acfg, const char *end, const char* start, int offset)
465 mono_img_writer_emit_symbol_diff (acfg->w, end, start, offset);
469 emit_zero_bytes (MonoAotCompile *acfg, int num)
471 mono_img_writer_emit_zero_bytes (acfg->w, num);
475 emit_byte (MonoAotCompile *acfg, guint8 val)
477 mono_img_writer_emit_byte (acfg->w, val);
480 #ifdef __native_client_codegen__
482 emit_nacl_call_alignment (MonoAotCompile *acfg)
484 mono_img_writer_emit_nacl_call_alignment (acfg->w);
488 static G_GNUC_UNUSED void
489 emit_global_inner (MonoAotCompile *acfg, const char *name, gboolean func)
491 mono_img_writer_emit_global (acfg->w, name, func);
495 emit_global (MonoAotCompile *acfg, const char *name, gboolean func)
497 if (acfg->aot_opts.no_dlsym) {
498 g_ptr_array_add (acfg->globals, g_strdup (name));
499 mono_img_writer_emit_local_symbol (acfg->w, name, NULL, func);
501 mono_img_writer_emit_global (acfg->w, name, func);
506 emit_symbol_size (MonoAotCompile *acfg, const char *name, const char *end_label)
508 mono_img_writer_emit_symbol_size (acfg->w, name, end_label);
512 emit_string_symbol (MonoAotCompile *acfg, const char *name, const char *value)
514 mono_img_writer_emit_section_change (acfg->w, RODATA_SECT, 1);
516 /* On apple, all symbols need to be aligned to avoid warnings from ld */
517 emit_alignment (acfg, 4);
519 mono_img_writer_emit_label (acfg->w, name);
520 mono_img_writer_emit_string (acfg->w, value);
523 static G_GNUC_UNUSED void
524 emit_uleb128 (MonoAotCompile *acfg, guint32 value)
527 guint8 b = value & 0x7f;
529 if (value != 0) /* more bytes to come */
535 static G_GNUC_UNUSED void
536 emit_sleb128 (MonoAotCompile *acfg, gint64 value)
539 gboolean negative = (value < 0);
546 /* the following is unnecessary if the
547 * implementation of >>= uses an arithmetic rather
548 * than logical shift for a signed left operand
552 value |= - ((gint64)1 <<(size - 7));
553 /* sign bit of byte is second high order bit (0x40) */
554 if ((value == 0 && !(byte & 0x40)) ||
555 (value == -1 && (byte & 0x40)))
559 emit_byte (acfg, byte);
563 static G_GNUC_UNUSED void
564 encode_uleb128 (guint32 value, guint8 *buf, guint8 **endbuf)
569 guint8 b = value & 0x7f;
571 if (value != 0) /* more bytes to come */
579 static G_GNUC_UNUSED void
580 encode_sleb128 (gint32 value, guint8 *buf, guint8 **endbuf)
583 gboolean negative = (value < 0);
591 /* the following is unnecessary if the
592 * implementation of >>= uses an arithmetic rather
593 * than logical shift for a signed left operand
597 value |= - (1 <<(size - 7));
598 /* sign bit of byte is second high order bit (0x40) */
599 if ((value == 0 && !(byte & 0x40)) ||
600 (value == -1 && (byte & 0x40)))
611 encode_int (gint32 val, guint8 *buf, guint8 **endbuf)
614 buf [0] = (val >> 0) & 0xff;
615 buf [1] = (val >> 8) & 0xff;
616 buf [2] = (val >> 16) & 0xff;
617 buf [3] = (val >> 24) & 0xff;
623 encode_int16 (guint16 val, guint8 *buf, guint8 **endbuf)
625 buf [0] = (val >> 0) & 0xff;
626 buf [1] = (val >> 8) & 0xff;
632 encode_string (const char *s, guint8 *buf, guint8 **endbuf)
634 int len = strlen (s);
636 memcpy (buf, s, len + 1);
637 *endbuf = buf + len + 1;
641 emit_unset_mode (MonoAotCompile *acfg)
643 mono_img_writer_emit_unset_mode (acfg->w);
646 static G_GNUC_UNUSED void
647 emit_set_thumb_mode (MonoAotCompile *acfg)
649 emit_unset_mode (acfg);
650 fprintf (acfg->fp, ".code 16\n");
653 static G_GNUC_UNUSED void
654 emit_set_arm_mode (MonoAotCompile *acfg)
656 emit_unset_mode (acfg);
657 fprintf (acfg->fp, ".code 32\n");
661 emit_code_bytes (MonoAotCompile *acfg, const guint8* buf, int size)
666 g_assert (size % 4 == 0);
667 emit_unset_mode (acfg);
668 for (i = 0; i < size; i += 4)
669 fprintf (acfg->fp, "%s 0x%x\n", acfg->inst_directive, *(guint32*)(buf + i));
671 emit_bytes (acfg, buf, size);
675 /* ARCHITECTURE SPECIFIC CODE */
677 #if defined(TARGET_X86) || defined(TARGET_AMD64) || defined(TARGET_ARM) || defined(TARGET_POWERPC) || defined(TARGET_ARM64)
678 #define EMIT_DWARF_INFO 1
681 #if defined(TARGET_ARM)
682 #define AOT_FUNC_ALIGNMENT 4
684 #define AOT_FUNC_ALIGNMENT 16
686 #if (defined(TARGET_X86) || defined(TARGET_AMD64)) && defined(__native_client_codegen__)
687 #undef AOT_FUNC_ALIGNMENT
688 #define AOT_FUNC_ALIGNMENT 32
691 #if defined(TARGET_POWERPC64) && !defined(__mono_ilp32__)
692 #define PPC_LD_OP "ld"
693 #define PPC_LDX_OP "ldx"
695 #define PPC_LD_OP "lwz"
696 #define PPC_LDX_OP "lwzx"
700 #define AOT_TARGET_STR "AMD64"
705 #define AOT_TARGET_STR "ARM (MACH)"
707 #define AOT_TARGET_STR "ARM (!MACH)"
713 #define AOT_TARGET_STR "ARM64 (MACH)"
715 #define AOT_TARGET_STR "ARM64 (!MACH)"
719 #ifdef TARGET_POWERPC64
720 #ifdef __mono_ilp32__
721 #define AOT_TARGET_STR "POWERPC64 (mono ilp32)"
723 #define AOT_TARGET_STR "POWERPC64 (!mono ilp32)"
726 #ifdef TARGET_POWERPC
727 #ifdef __mono_ilp32__
728 #define AOT_TARGET_STR "POWERPC (mono ilp32)"
730 #define AOT_TARGET_STR "POWERPC (!mono ilp32)"
737 #define AOT_TARGET_STR "X86 (WIN32)"
738 #elif defined(__native_client_codegen__)
739 #define AOT_TARGET_STR "X86 (native client codegen)"
741 #define AOT_TARGET_STR "X86 (!native client codegen)"
745 #ifndef AOT_TARGET_STR
746 #define AOT_TARGET_STR ""
750 arch_init (MonoAotCompile *acfg)
752 acfg->llc_args = g_string_new ("");
753 acfg->as_args = g_string_new ("");
756 * The prefix LLVM likes to put in front of symbol names on darwin.
757 * The mach-os specs require this for globals, but LLVM puts them in front of all
758 * symbols. We need to handle this, since we need to refer to LLVM generated
761 acfg->llvm_label_prefix = "";
762 acfg->user_symbol_prefix = "";
764 #if defined(TARGET_X86)
765 g_string_append (acfg->llc_args, " -march=x86 -mattr=sse4.1");
768 #if defined(TARGET_AMD64)
769 g_string_append (acfg->llc_args, " -march=x86-64 -mattr=sse4.1");
771 acfg->align_pad_value = 0x90;
775 if (acfg->aot_opts.mtriple && strstr (acfg->aot_opts.mtriple, "darwin")) {
776 g_string_append (acfg->llc_args, "-mattr=+v6");
779 g_string_append (acfg->llc_args, " -mattr=+vfp2,-neon,+d16");
780 g_string_append (acfg->as_args, " -mfpu=vfp3");
782 g_string_append (acfg->llc_args, " -soft-float");
785 if (acfg->aot_opts.mtriple && strstr (acfg->aot_opts.mtriple, "thumb"))
786 acfg->thumb_mixed = TRUE;
788 if (acfg->aot_opts.mtriple)
789 mono_arch_set_target (acfg->aot_opts.mtriple);
793 acfg->inst_directive = ".inst";
794 if (acfg->aot_opts.mtriple)
795 mono_arch_set_target (acfg->aot_opts.mtriple);
799 acfg->user_symbol_prefix = "_";
800 acfg->llvm_label_prefix = "_";
801 acfg->inst_directive = ".word";
802 acfg->need_no_dead_strip = TRUE;
803 acfg->aot_opts.gnu_asm = TRUE;
806 #if defined(__linux__) && !defined(TARGET_ARM)
807 acfg->need_pt_gnu_stack = TRUE;
811 acfg->global_symbols = TRUE;
817 #include "../../../mono-extensions/mono/mini/aot-compiler-arm64.c"
821 #ifdef MONO_ARCH_AOT_SUPPORTED
823 * arch_emit_direct_call:
825 * Emit a direct call to the symbol TARGET. CALL_SIZE is set to the size of the
829 arch_emit_direct_call (MonoAotCompile *acfg, const char *target, gboolean external, gboolean thumb, MonoJumpInfo *ji, int *call_size)
831 #if defined(TARGET_X86) || defined(TARGET_AMD64)
832 /* Need to make sure this is exactly 5 bytes long */
833 if (!acfg->use_bin_writer) {
834 emit_unset_mode (acfg);
835 fprintf (acfg->fp, "call %s\n", target);
837 emit_byte (acfg, '\xe8');
838 emit_symbol_diff (acfg, target, ".", -4);
841 #elif defined(TARGET_ARM)
842 if (acfg->use_bin_writer) {
849 mono_img_writer_emit_reloc (acfg->w, R_ARM_CALL, target, -8);
850 emit_bytes (acfg, buf, 4);
852 emit_unset_mode (acfg);
854 fprintf (acfg->fp, "blx %s\n", target);
856 fprintf (acfg->fp, "bl %s\n", target);
859 #elif defined(TARGET_ARM64)
860 arm64_emit_direct_call (acfg, target, external, thumb, ji, call_size);
861 #elif defined(TARGET_POWERPC)
862 if (acfg->use_bin_writer) {
863 g_assert_not_reached ();
865 emit_unset_mode (acfg);
866 fprintf (acfg->fp, "bl %s\n", target);
870 g_assert_not_reached ();
877 * - we use an approach similar to the x86 abi: reserve a register (r30) to hold
879 * - The full-aot trampolines need access to the GOT of mscorlib, so we store
880 * in in the 2. slot of every GOT, and require every method to place the GOT
881 * address in r30, even when it doesn't access the GOT otherwise. This way,
882 * the trampolines can compute the mscorlib GOT address by loading 4(r30).
887 * PPC64 uses function descriptors which greatly complicate all code, since
888 * these are used very inconsistently in the runtime. Some functions like
889 * mono_compile_method () return ftn descriptors, while others like the
890 * trampoline creation functions do not.
891 * We assume that all GOT slots contain function descriptors, and create
892 * descriptors in aot-runtime.c when needed.
893 * The ppc64 abi uses r2 to hold the address of the TOC/GOT, which is loaded
894 * from function descriptors, we could do the same, but it would require
895 * rewriting all the ppc/aot code to handle function descriptors properly.
896 * So instead, we use the same approach as on PPC32.
897 * This is a horrible mess, but fixing it would probably lead to an even bigger
903 * - similar to the PPC32 design, we reserve EBX to hold the GOT pointer.
906 #ifdef MONO_ARCH_AOT_SUPPORTED
908 * arch_emit_got_offset:
910 * The memory pointed to by CODE should hold native code for computing the GOT
911 * address (OP_LOAD_GOTADDR). Emit this code while patching it with the offset
912 * between code and the GOT. CODE_SIZE is set to the number of bytes emitted.
915 arch_emit_got_offset (MonoAotCompile *acfg, guint8 *code, int *code_size)
917 #if defined(TARGET_POWERPC64)
918 g_assert (!acfg->use_bin_writer);
919 emit_unset_mode (acfg);
921 * The ppc32 code doesn't seem to work on ppc64, the assembler complains about
922 * unsupported relocations. So we store the got address into the .Lgot_addr
923 * symbol which is in the text segment, compute its address, and load it.
925 fprintf (acfg->fp, ".L%d:\n", acfg->label_generator);
926 fprintf (acfg->fp, "lis 0, (.Lgot_addr + 4 - .L%d)@h\n", acfg->label_generator);
927 fprintf (acfg->fp, "ori 0, 0, (.Lgot_addr + 4 - .L%d)@l\n", acfg->label_generator);
928 fprintf (acfg->fp, "add 30, 30, 0\n");
929 fprintf (acfg->fp, "%s 30, 0(30)\n", PPC_LD_OP);
930 acfg->label_generator ++;
932 #elif defined(TARGET_POWERPC)
933 g_assert (!acfg->use_bin_writer);
934 emit_unset_mode (acfg);
935 fprintf (acfg->fp, ".L%d:\n", acfg->label_generator);
936 fprintf (acfg->fp, "lis 0, (%s + 4 - .L%d)@h\n", acfg->got_symbol, acfg->label_generator);
937 fprintf (acfg->fp, "ori 0, 0, (%s + 4 - .L%d)@l\n", acfg->got_symbol, acfg->label_generator);
938 acfg->label_generator ++;
941 guint32 offset = mono_arch_get_patch_offset (code);
942 emit_bytes (acfg, code, offset);
943 emit_symbol_diff (acfg, acfg->got_symbol, ".", offset);
945 *code_size = offset + 4;
950 * arch_emit_got_access:
952 * The memory pointed to by CODE should hold native code for loading a GOT
953 * slot (OP_AOTCONST/OP_GOT_ENTRY). Emit this code while patching it so it accesses the
954 * GOT slot GOT_SLOT. CODE_SIZE is set to the number of bytes emitted.
957 arch_emit_got_access (MonoAotCompile *acfg, const char *got_symbol, guint8 *code, int got_slot, int *code_size)
960 /* mov reg, got+offset(%rip) */
962 /* The GOT symbol is in the LLVM module, the clang assembler has problems emitting symbol diffs for it */
966 /* Decode reg, see amd64_mov_reg_membase () */
967 rex_r = code [0] & AMD64_REX_R;
968 g_assert (code [0] == 0x49 + rex_r);
969 g_assert (code [1] == 0x8b);
970 dreg = ((code [2] >> 3) & 0x7) + (rex_r ? 8 : 0);
972 emit_unset_mode (acfg);
973 fprintf (acfg->fp, "mov %s+%d(%%rip), %s\n", got_symbol, (unsigned int) ((got_slot * sizeof (gpointer))), mono_arch_regname (dreg));
976 emit_bytes (acfg, code, mono_arch_get_patch_offset (code));
977 emit_symbol_diff (acfg, got_symbol, ".", (unsigned int) ((got_slot * sizeof (gpointer)) - 4));
978 *code_size = mono_arch_get_patch_offset (code) + 4;
980 #elif defined(TARGET_X86)
981 emit_bytes (acfg, code, mono_arch_get_patch_offset (code));
982 emit_int32 (acfg, (unsigned int) ((got_slot * sizeof (gpointer))));
983 *code_size = mono_arch_get_patch_offset (code) + 4;
984 #elif defined(TARGET_ARM)
985 emit_bytes (acfg, code, mono_arch_get_patch_offset (code));
986 emit_symbol_diff (acfg, got_symbol, ".", (unsigned int) ((got_slot * sizeof (gpointer))) - 12);
987 *code_size = mono_arch_get_patch_offset (code) + 4;
988 #elif defined(TARGET_ARM64)
989 emit_bytes (acfg, code, mono_arch_get_patch_offset (code));
990 arm64_emit_got_access (acfg, code, got_slot, code_size);
991 #elif defined(TARGET_POWERPC)
996 emit_bytes (acfg, code, mono_arch_get_patch_offset (code));
998 ppc_load32 (code, ppc_r0, got_slot * sizeof (gpointer));
999 g_assert (code - buf == 8);
1000 emit_bytes (acfg, buf, code - buf);
1001 *code_size = code - buf;
1004 g_assert_not_reached ();
1010 #ifdef MONO_ARCH_AOT_SUPPORTED
1012 * arch_emit_objc_selector_ref:
1014 * Emit the implementation of OP_OBJC_GET_SELECTOR, which itself implements @selector(foo:) in objective-c.
1017 arch_emit_objc_selector_ref (MonoAotCompile *acfg, guint8 *code, int index, int *code_size)
1019 #if defined(TARGET_ARM)
1022 int lindex = acfg->objc_selector_index_2 ++;
1024 /* Emit ldr.imm/b */
1025 emit_bytes (acfg, code, 8);
1027 sprintf (symbol1, "L_OBJC_SELECTOR_%d", lindex);
1028 sprintf (symbol2, "L_OBJC_SELECTOR_REFERENCES_%d", index);
1030 emit_label (acfg, symbol1);
1031 mono_img_writer_emit_unset_mode (acfg->w);
1032 fprintf (acfg->fp, ".long %s-(%s+12)", symbol2, symbol1);
1035 #elif defined(TARGET_ARM64)
1036 arm64_emit_objc_selector_ref (acfg, code, index, code_size);
1038 g_assert_not_reached ();
1044 * arch_emit_plt_entry:
1046 * Emit code for the PLT entry.
1047 * The plt entry should look like this:
1048 * <indirect jump to GOT_SYMBOL + OFFSET>
1049 * <INFO_OFFSET embedded into the instruction stream>
1052 arch_emit_plt_entry (MonoAotCompile *acfg, const char *got_symbol, int offset, int info_offset)
1054 #if defined(TARGET_X86)
1055 #if defined(__default_codegen__)
1056 /* jmp *<offset>(%ebx) */
1057 emit_byte (acfg, 0xff);
1058 emit_byte (acfg, 0xa3);
1059 emit_int32 (acfg, offset);
1060 /* Used by mono_aot_get_plt_info_offset */
1061 emit_int32 (acfg, info_offset);
1062 #elif defined(__native_client_codegen__)
1063 const guint8 kSizeOfNaClJmp = 11;
1064 guint8 bytes[kSizeOfNaClJmp];
1065 guint8 *pbytes = &bytes[0];
1067 x86_jump_membase32 (pbytes, X86_EBX, offset);
1068 emit_bytes (acfg, bytes, kSizeOfNaClJmp);
1069 /* four bytes of data, used by mono_arch_patch_plt_entry */
1070 /* For Native Client, make this work with data embedded in push. */
1071 emit_byte (acfg, 0x68); /* hide data in a push */
1072 emit_int32 (acfg, info_offset);
1073 emit_alignment (acfg, AOT_FUNC_ALIGNMENT);
1074 #endif /*__native_client_codegen__*/
1075 #elif defined(TARGET_AMD64)
1076 #if defined(__default_codegen__)
1077 if (acfg->use_bin_writer) {
1078 emit_byte (acfg, '\xff');
1079 emit_byte (acfg, '\x25');
1080 emit_symbol_diff (acfg, got_symbol, ".", offset - 4);
1082 emit_unset_mode (acfg);
1083 fprintf (acfg->fp, "jmp *%s+%d(%%rip)\n", got_symbol, offset);
1085 /* Used by mono_aot_get_plt_info_offset */
1086 emit_int32 (acfg, info_offset);
1087 acfg->stats.plt_size += 10;
1088 #elif defined(__native_client_codegen__)
1090 guint8 *buf_aligned = ALIGN_TO(buf, kNaClAlignment);
1091 guint8 *code = buf_aligned;
1093 /* mov <OFFSET>(%rip), %r11d */
1094 emit_byte (acfg, '\x45');
1095 emit_byte (acfg, '\x8b');
1096 emit_byte (acfg, '\x1d');
1097 emit_symbol_diff (acfg, got_symbol, ".", offset - 4);
1099 amd64_jump_reg (code, AMD64_R11);
1100 /* This should be constant for the plt patch */
1101 g_assert ((size_t)(code-buf_aligned) == 10);
1102 emit_bytes (acfg, buf_aligned, code - buf_aligned);
1104 /* Hide data in a push imm32 so it passes validation */
1105 emit_byte (acfg, 0x68); /* push */
1106 emit_int32 (acfg, info_offset);
1107 emit_alignment (acfg, AOT_FUNC_ALIGNMENT);
1108 #endif /*__native_client_codegen__*/
1109 #elif defined(TARGET_ARM)
1114 ARM_LDR_IMM (code, ARMREG_IP, ARMREG_PC, 0);
1115 ARM_LDR_REG_REG (code, ARMREG_PC, ARMREG_PC, ARMREG_IP);
1116 emit_bytes (acfg, buf, code - buf);
1117 emit_symbol_diff (acfg, got_symbol, ".", offset - 4);
1118 /* Used by mono_aot_get_plt_info_offset */
1119 emit_int32 (acfg, info_offset);
1120 #elif defined(TARGET_ARM64)
1121 arm64_emit_plt_entry (acfg, got_symbol, offset, info_offset);
1122 #elif defined(TARGET_POWERPC)
1123 /* The GOT address is guaranteed to be in r30 by OP_LOAD_GOTADDR */
1124 g_assert (!acfg->use_bin_writer);
1125 emit_unset_mode (acfg);
1126 fprintf (acfg->fp, "lis 11, %d@h\n", offset);
1127 fprintf (acfg->fp, "ori 11, 11, %d@l\n", offset);
1128 fprintf (acfg->fp, "add 11, 11, 30\n");
1129 fprintf (acfg->fp, "%s 11, 0(11)\n", PPC_LD_OP);
1130 #ifdef PPC_USES_FUNCTION_DESCRIPTOR
1131 fprintf (acfg->fp, "%s 2, %d(11)\n", PPC_LD_OP, (int)sizeof (gpointer));
1132 fprintf (acfg->fp, "%s 11, 0(11)\n", PPC_LD_OP);
1134 fprintf (acfg->fp, "mtctr 11\n");
1135 fprintf (acfg->fp, "bctr\n");
1136 emit_int32 (acfg, info_offset);
1138 g_assert_not_reached ();
1143 * arch_emit_llvm_plt_entry:
1145 * Same as arch_emit_plt_entry, but handles calls from LLVM generated code.
1146 * This is only needed on arm to handle thumb interop.
1149 arch_emit_llvm_plt_entry (MonoAotCompile *acfg, const char *got_symbol, int offset, int info_offset)
1151 #if defined(TARGET_ARM)
1152 /* LLVM calls the PLT entries using bl, so these have to be thumb2 */
1153 /* The caller already transitioned to thumb */
1154 /* The code below should be 12 bytes long */
1155 /* clang has trouble encoding these instructions, so emit the binary */
1157 fprintf (acfg->fp, "ldr ip, [pc, #8]\n");
1158 /* thumb can't encode ld pc, [pc, ip] */
1159 fprintf (acfg->fp, "add ip, pc, ip\n");
1160 fprintf (acfg->fp, "ldr ip, [ip, #0]\n");
1161 fprintf (acfg->fp, "bx ip\n");
1163 emit_set_thumb_mode (acfg);
1164 fprintf (acfg->fp, ".4byte 0xc008f8df\n");
1165 fprintf (acfg->fp, ".2byte 0x44fc\n");
1166 fprintf (acfg->fp, ".4byte 0xc000f8dc\n");
1167 fprintf (acfg->fp, ".2byte 0x4760\n");
1168 emit_symbol_diff (acfg, got_symbol, ".", offset + 4);
1169 emit_int32 (acfg, info_offset);
1170 emit_unset_mode (acfg);
1171 emit_set_arm_mode (acfg);
1173 g_assert_not_reached ();
1178 * arch_emit_specific_trampoline_pages:
1180 * Emits a page full of trampolines: each trampoline uses its own address to
1181 * lookup both the generic trampoline code and the data argument.
1182 * This page can be remapped in process multiple times so we can get an
1183 * unlimited number of trampolines.
1184 * Specifically this implementation uses the following trick: two memory pages
1185 * are allocated, with the first containing the data and the second containing the trampolines.
1186 * To reduce trampoline size, each trampoline jumps at the start of the page where a common
1187 * implementation does all the lifting.
1188 * Note that the ARM single trampoline size is 8 bytes, exactly like the data that needs to be stored
1189 * on the arm 32 bit system.
1192 arch_emit_specific_trampoline_pages (MonoAotCompile *acfg)
1194 #if defined(TARGET_ARM)
1197 guint8 *loop_start, *loop_branch_back, *loop_end_check, *imt_found_check;
1199 int pagesize = MONO_AOT_TRAMP_PAGE_SIZE;
1200 #define COMMON_TRAMP_SIZE 16
1201 int count = (pagesize - COMMON_TRAMP_SIZE) / 8;
1202 int imm8, rot_amount;
1205 if (!acfg->aot_opts.use_trampolines_page)
1208 acfg->tramp_page_size = pagesize;
1210 sprintf (symbol, "%sspecific_trampolines_page", acfg->user_symbol_prefix);
1211 emit_alignment (acfg, pagesize);
1212 emit_global (acfg, symbol, TRUE);
1213 emit_label (acfg, symbol);
1215 /* emit the generic code first, the trampoline address + 8 is in the lr register */
1217 imm8 = mono_arm_is_rotated_imm8 (pagesize, &rot_amount);
1218 ARM_SUB_REG_IMM (code, ARMREG_LR, ARMREG_LR, imm8, rot_amount);
1219 ARM_LDR_IMM (code, ARMREG_R1, ARMREG_LR, -8);
1220 ARM_LDR_IMM (code, ARMREG_PC, ARMREG_LR, -4);
1222 g_assert (code - buf == COMMON_TRAMP_SIZE);
1225 emit_bytes (acfg, buf, code - buf);
1227 for (i = 0; i < count; ++i) {
1229 ARM_PUSH (code, 0x5fff);
1231 arm_patch (code - 4, code - COMMON_TRAMP_SIZE - 8 * (i + 1));
1232 g_assert (code - buf == 8);
1233 emit_bytes (acfg, buf, code - buf);
1236 /* now the rgctx trampolines: each specific trampolines puts in the ip register
1237 * the instruction pointer address, so the generic trampoline at the start of the page
1238 * subtracts 4096 to get to the data page and loads the values
1239 * We again fit the generic trampiline in 16 bytes.
1241 sprintf (symbol, "%srgctx_trampolines_page", acfg->user_symbol_prefix);
1242 emit_global (acfg, symbol, TRUE);
1243 emit_label (acfg, symbol);
1245 imm8 = mono_arm_is_rotated_imm8 (pagesize, &rot_amount);
1246 ARM_SUB_REG_IMM (code, ARMREG_IP, ARMREG_IP, imm8, rot_amount);
1247 ARM_LDR_IMM (code, MONO_ARCH_RGCTX_REG, ARMREG_IP, -8);
1248 ARM_LDR_IMM (code, ARMREG_PC, ARMREG_IP, -4);
1250 g_assert (code - buf == COMMON_TRAMP_SIZE);
1253 emit_bytes (acfg, buf, code - buf);
1255 for (i = 0; i < count; ++i) {
1257 ARM_MOV_REG_REG (code, ARMREG_IP, ARMREG_PC);
1259 arm_patch (code - 4, code - COMMON_TRAMP_SIZE - 8 * (i + 1));
1260 g_assert (code - buf == 8);
1261 emit_bytes (acfg, buf, code - buf);
1265 * gsharedvt arg trampolines: see arch_emit_gsharedvt_arg_trampoline ()
1267 sprintf (symbol, "%sgsharedvt_arg_trampolines_page", acfg->user_symbol_prefix);
1268 emit_global (acfg, symbol, TRUE);
1269 emit_label (acfg, symbol);
1271 ARM_PUSH (code, (1 << ARMREG_R0) | (1 << ARMREG_R1) | (1 << ARMREG_R2) | (1 << ARMREG_R3));
1272 imm8 = mono_arm_is_rotated_imm8 (pagesize, &rot_amount);
1273 ARM_SUB_REG_IMM (code, ARMREG_IP, ARMREG_IP, imm8, rot_amount);
1274 ARM_LDR_IMM (code, ARMREG_R0, ARMREG_IP, -8);
1275 ARM_LDR_IMM (code, ARMREG_PC, ARMREG_IP, -4);
1276 g_assert (code - buf == COMMON_TRAMP_SIZE);
1278 emit_bytes (acfg, buf, code - buf);
1280 for (i = 0; i < count; ++i) {
1282 ARM_MOV_REG_REG (code, ARMREG_IP, ARMREG_PC);
1284 arm_patch (code - 4, code - COMMON_TRAMP_SIZE - 8 * (i + 1));
1285 g_assert (code - buf == 8);
1286 emit_bytes (acfg, buf, code - buf);
1289 /* now the imt trampolines: each specific trampolines puts in the ip register
1290 * the instruction pointer address, so the generic trampoline at the start of the page
1291 * subtracts 4096 to get to the data page and loads the values
1292 * We again fit the generic trampiline in 16 bytes.
1294 #define IMT_TRAMP_SIZE 72
1295 sprintf (symbol, "%simt_trampolines_page", acfg->user_symbol_prefix);
1296 emit_global (acfg, symbol, TRUE);
1297 emit_label (acfg, symbol);
1299 /* Need at least two free registers, plus a slot for storing the pc */
1300 ARM_PUSH (code, (1 << ARMREG_R0)|(1 << ARMREG_R1)|(1 << ARMREG_R2));
1302 imm8 = mono_arm_is_rotated_imm8 (pagesize, &rot_amount);
1303 ARM_SUB_REG_IMM (code, ARMREG_IP, ARMREG_IP, imm8, rot_amount);
1304 ARM_LDR_IMM (code, ARMREG_R0, ARMREG_IP, -8);
1306 /* The IMT method is in v5, r0 has the imt array address */
1309 ARM_LDR_IMM (code, ARMREG_R1, ARMREG_R0, 0);
1310 ARM_CMP_REG_REG (code, ARMREG_R1, ARMREG_V5);
1311 imt_found_check = code;
1312 ARM_B_COND (code, ARMCOND_EQ, 0);
1314 /* End-of-loop check */
1315 ARM_CMP_REG_IMM (code, ARMREG_R1, 0, 0);
1316 loop_end_check = code;
1317 ARM_B_COND (code, ARMCOND_EQ, 0);
1320 ARM_ADD_REG_IMM8 (code, ARMREG_R0, ARMREG_R0, sizeof (gpointer) * 2);
1321 loop_branch_back = code;
1323 arm_patch (loop_branch_back, loop_start);
1326 arm_patch (imt_found_check, code);
1327 ARM_LDR_IMM (code, ARMREG_R0, ARMREG_R0, 4);
1328 ARM_LDR_IMM (code, ARMREG_R0, ARMREG_R0, 0);
1329 /* Save it to the third stack slot */
1330 ARM_STR_IMM (code, ARMREG_R0, ARMREG_SP, 8);
1331 /* Restore the registers and branch */
1332 ARM_POP (code, (1 << ARMREG_R0)|(1 << ARMREG_R1)|(1 << ARMREG_PC));
1335 arm_patch (loop_end_check, code);
1336 ARM_LDR_IMM (code, ARMREG_R0, ARMREG_R0, 4);
1337 ARM_STR_IMM (code, ARMREG_R0, ARMREG_SP, 8);
1338 ARM_POP (code, (1 << ARMREG_R0)|(1 << ARMREG_R1)|(1 << ARMREG_PC));
1342 g_assert (code - buf == IMT_TRAMP_SIZE);
1343 emit_bytes (acfg, buf, code - buf);
1345 for (i = 0; i < count; ++i) {
1347 ARM_MOV_REG_REG (code, ARMREG_IP, ARMREG_PC);
1349 arm_patch (code - 4, code - IMT_TRAMP_SIZE - 8 * (i + 1));
1350 g_assert (code - buf == 8);
1351 emit_bytes (acfg, buf, code - buf);
1354 acfg->tramp_page_code_offsets [MONO_AOT_TRAMP_SPECIFIC] = 16;
1355 acfg->tramp_page_code_offsets [MONO_AOT_TRAMP_STATIC_RGCTX] = 16;
1356 acfg->tramp_page_code_offsets [MONO_AOT_TRAMP_IMT_THUNK] = 72;
1357 acfg->tramp_page_code_offsets [MONO_AOT_TRAMP_GSHAREDVT_ARG] = 16;
1358 #elif defined(TARGET_ARM64)
1359 arm64_emit_specific_trampoline_pages (acfg);
1364 * arch_emit_specific_trampoline:
1366 * Emit code for a specific trampoline. OFFSET is the offset of the first of
1367 * two GOT slots which contain the generic trampoline address and the trampoline
1368 * argument. TRAMP_SIZE is set to the size of the emitted trampoline.
1371 arch_emit_specific_trampoline (MonoAotCompile *acfg, int offset, int *tramp_size)
1374 * The trampolines created here are variations of the specific
1375 * trampolines created in mono_arch_create_specific_trampoline (). The
1377 * - the generic trampoline address is taken from a got slot.
1378 * - the offset of the got slot where the trampoline argument is stored
1379 * is embedded in the instruction stream, and the generic trampoline
1380 * can load the argument by loading the offset, adding it to the
1381 * address of the trampoline to get the address of the got slot, and
1382 * loading the argument from there.
1383 * - all the trampolines should be of the same length.
1385 #if defined(TARGET_AMD64)
1386 #if defined(__default_codegen__)
1387 /* This should be exactly 8 bytes long */
1389 /* call *<offset>(%rip) */
1391 emit_unset_mode (acfg);
1392 fprintf (acfg->fp, "call *%s+%d(%%rip)\n", acfg->got_symbol, (int)(offset * sizeof (gpointer)));
1393 emit_zero_bytes (acfg, 2);
1395 emit_byte (acfg, '\x41');
1396 emit_byte (acfg, '\xff');
1397 emit_byte (acfg, '\x15');
1398 emit_symbol_diff (acfg, acfg->got_symbol, ".", (offset * sizeof (gpointer)) - 4);
1399 emit_zero_bytes (acfg, 1);
1401 #elif defined(__native_client_codegen__)
1403 guint8 *buf_aligned = ALIGN_TO(buf, kNaClAlignment);
1404 guint8 *code = buf_aligned;
1409 /* Emit this call in 'code' so we can find out how long it is. */
1410 amd64_call_reg (code, AMD64_R11);
1411 call_start = mono_arch_nacl_skip_nops (buf_aligned);
1412 call_len = code - call_start;
1414 /* The tramp_size is twice the NaCl alignment because it starts with */
1415 /* a call which needs to be aligned to the end of the boundary. */
1416 *tramp_size = kNaClAlignment*2;
1418 /* Emit nops to align call site below which is 7 bytes plus */
1419 /* the length of the call sequence emitted above. */
1420 /* Note: this requires the specific trampoline starts on a */
1421 /* kNaclAlignedment aligned address, which it does because */
1422 /* it's its own function that is aligned. */
1423 guint8 nop_buf[256];
1424 guint8 *nopbuf_aligned = ALIGN_TO (nop_buf, kNaClAlignment);
1425 guint8 *nopbuf_end = mono_arch_nacl_pad (nopbuf_aligned, kNaClAlignment - 7 - (call_len));
1426 emit_bytes (acfg, nopbuf_aligned, nopbuf_end - nopbuf_aligned);
1428 /* The trampoline is stored at the offset'th pointer, the -4 is */
1429 /* present because RIP relative addressing starts at the end of */
1430 /* the current instruction, while the label "." is relative to */
1431 /* the beginning of the current asm location, which in this case */
1432 /* is not the mov instruction, but the offset itself, due to the */
1433 /* way the bytes and ints are emitted here. */
1434 got_offset = (offset * sizeof(gpointer)) - 4;
1436 /* mov <OFFSET>(%rip), %r11d */
1437 emit_byte (acfg, '\x45');
1438 emit_byte (acfg, '\x8b');
1439 emit_byte (acfg, '\x1d');
1440 emit_symbol_diff (acfg, acfg->got_symbol, ".", got_offset);
1443 emit_bytes (acfg, call_start, call_len);
1445 /* The arg is stored at the offset+1 pointer, relative to beginning */
1446 /* of trampoline: 7 for mov, plus the call length, and 1 for push. */
1447 got_offset = ((offset + 1) * sizeof(gpointer)) + 7 + call_len + 1;
1449 /* We can't emit this data directly, hide in a "push imm32" */
1450 emit_byte (acfg, '\x68'); /* push */
1451 emit_symbol_diff (acfg, acfg->got_symbol, ".", got_offset);
1452 emit_alignment (acfg, kNaClAlignment);
1453 #endif /*__native_client_codegen__*/
1454 #elif defined(TARGET_ARM)
1458 /* This should be exactly 20 bytes long */
1461 ARM_PUSH (code, 0x5fff);
1462 ARM_LDR_IMM (code, ARMREG_R1, ARMREG_PC, 4);
1463 /* Load the value from the GOT */
1464 ARM_LDR_REG_REG (code, ARMREG_R1, ARMREG_PC, ARMREG_R1);
1466 ARM_BLX_REG (code, ARMREG_R1);
1468 g_assert (code - buf == 16);
1471 emit_bytes (acfg, buf, code - buf);
1473 * Only one offset is needed, since the second one would be equal to the
1476 emit_symbol_diff (acfg, acfg->got_symbol, ".", (offset * sizeof (gpointer)) - 4 + 4);
1477 //emit_symbol_diff (acfg, acfg->got_symbol, ".", ((offset + 1) * sizeof (gpointer)) - 4 + 8);
1478 #elif defined(TARGET_ARM64)
1479 arm64_emit_specific_trampoline (acfg, offset, tramp_size);
1480 #elif defined(TARGET_POWERPC)
1487 g_assert (!acfg->use_bin_writer);
1490 * PPC has no ip relative addressing, so we need to compute the address
1491 * of the mscorlib got. That is slow and complex, so instead, we store it
1492 * in the second got slot of every aot image. The caller already computed
1493 * the address of its got and placed it into r30.
1495 emit_unset_mode (acfg);
1496 /* Load mscorlib got address */
1497 fprintf (acfg->fp, "%s 0, %d(30)\n", PPC_LD_OP, (int)sizeof (gpointer));
1498 /* Load generic trampoline address */
1499 fprintf (acfg->fp, "lis 11, %d@h\n", (int)(offset * sizeof (gpointer)));
1500 fprintf (acfg->fp, "ori 11, 11, %d@l\n", (int)(offset * sizeof (gpointer)));
1501 fprintf (acfg->fp, "%s 11, 11, 0\n", PPC_LDX_OP);
1502 #ifdef PPC_USES_FUNCTION_DESCRIPTOR
1503 fprintf (acfg->fp, "%s 11, 0(11)\n", PPC_LD_OP);
1505 fprintf (acfg->fp, "mtctr 11\n");
1506 /* Load trampoline argument */
1507 /* On ppc, we pass it normally to the generic trampoline */
1508 fprintf (acfg->fp, "lis 11, %d@h\n", (int)((offset + 1) * sizeof (gpointer)));
1509 fprintf (acfg->fp, "ori 11, 11, %d@l\n", (int)((offset + 1) * sizeof (gpointer)));
1510 fprintf (acfg->fp, "%s 0, 11, 0\n", PPC_LDX_OP);
1511 /* Branch to generic trampoline */
1512 fprintf (acfg->fp, "bctr\n");
1514 #ifdef PPC_USES_FUNCTION_DESCRIPTOR
1515 *tramp_size = 10 * 4;
1517 *tramp_size = 9 * 4;
1519 #elif defined(TARGET_X86)
1523 /* Similar to the PPC code above */
1525 /* FIXME: Could this clobber the register needed by get_vcall_slot () ? */
1527 /* We clobber ECX, since EAX is used as MONO_ARCH_MONITOR_OBJECT_REG */
1528 #ifdef MONO_ARCH_MONITOR_OBJECT_REG
1529 g_assert (MONO_ARCH_MONITOR_OBJECT_REG != X86_ECX);
1530 #ifdef MONO_ARCH_MONITOR_LOCK_TAKEN_REG
1531 g_assert (MONO_ARCH_MONITOR_LOCK_TAKEN_REG != X86_ECX);
1536 /* Load mscorlib got address */
1537 x86_mov_reg_membase (code, X86_ECX, MONO_ARCH_GOT_REG, sizeof (gpointer), 4);
1538 /* Push trampoline argument */
1539 x86_push_membase (code, X86_ECX, (offset + 1) * sizeof (gpointer));
1540 /* Load generic trampoline address */
1541 x86_mov_reg_membase (code, X86_ECX, X86_ECX, offset * sizeof (gpointer), 4);
1542 /* Branch to generic trampoline */
1543 x86_jump_reg (code, X86_ECX);
1545 #ifdef __native_client_codegen__
1547 /* emit nops to next 32 byte alignment */
1548 int a = (~kNaClAlignmentMask) & ((code - buf) + kNaClAlignment - 1);
1549 while (code < (buf + a)) x86_nop(code);
1552 emit_bytes (acfg, buf, code - buf);
1554 *tramp_size = NACL_SIZE(17, kNaClAlignment);
1555 g_assert (code - buf == *tramp_size);
1557 g_assert_not_reached ();
1562 * arch_emit_unbox_trampoline:
1564 * Emit code for the unbox trampoline for METHOD used in the full-aot case.
1565 * CALL_TARGET is the symbol pointing to the native code of METHOD.
1568 arch_emit_unbox_trampoline (MonoAotCompile *acfg, MonoCompile *cfg, MonoMethod *method, const char *call_target)
1570 #if defined(TARGET_AMD64)
1575 this_reg = mono_arch_get_this_arg_reg (NULL);
1577 amd64_alu_reg_imm (code, X86_ADD, this_reg, sizeof (MonoObject));
1579 emit_bytes (acfg, buf, code - buf);
1582 emit_unset_mode (acfg);
1583 fprintf (acfg->fp, "jmp %s\n", call_target);
1585 emit_byte (acfg, '\xe9');
1586 emit_symbol_diff (acfg, call_target, ".", -4);
1588 #elif defined(TARGET_X86)
1595 x86_alu_membase_imm (code, X86_ADD, X86_ESP, this_pos, sizeof (MonoObject));
1597 emit_bytes (acfg, buf, code - buf);
1600 emit_byte (acfg, '\xe9');
1601 emit_symbol_diff (acfg, call_target, ".", -4);
1602 #elif defined(TARGET_ARM)
1606 if (acfg->thumb_mixed && cfg->compile_llvm) {
1607 fprintf (acfg->fp, "add r0, r0, #%d\n", (int)sizeof (MonoObject));
1608 fprintf (acfg->fp, "b %s\n", call_target);
1609 fprintf (acfg->fp, ".arm\n");
1610 fprintf (acfg->fp, ".align 2\n");
1616 ARM_ADD_REG_IMM8 (code, ARMREG_R0, ARMREG_R0, sizeof (MonoObject));
1618 emit_bytes (acfg, buf, code - buf);
1619 /* jump to method */
1620 if (acfg->use_bin_writer) {
1627 mono_img_writer_emit_reloc (acfg->w, R_ARM_JUMP24, call_target, -8);
1628 emit_bytes (acfg, buf, 4);
1630 if (acfg->thumb_mixed && cfg->compile_llvm)
1631 fprintf (acfg->fp, "\n\tbx %s\n", call_target);
1633 fprintf (acfg->fp, "\n\tb %s\n", call_target);
1635 #elif defined(TARGET_ARM64)
1636 arm64_emit_unbox_trampoline (acfg, cfg, method, call_target);
1637 #elif defined(TARGET_POWERPC)
1640 g_assert (!acfg->use_bin_writer);
1642 fprintf (acfg->fp, "\n\taddi %d, %d, %d\n", this_pos, this_pos, (int)sizeof (MonoObject));
1643 fprintf (acfg->fp, "\n\tb %s\n", call_target);
1645 g_assert_not_reached ();
1650 * arch_emit_static_rgctx_trampoline:
1652 * Emit code for a static rgctx trampoline. OFFSET is the offset of the first of
1653 * two GOT slots which contain the rgctx argument, and the method to jump to.
1654 * TRAMP_SIZE is set to the size of the emitted trampoline.
1655 * These kinds of trampolines cannot be enumerated statically, since there could
1656 * be one trampoline per method instantiation, so we emit the same code for all
1657 * trampolines, and parameterize them using two GOT slots.
1660 arch_emit_static_rgctx_trampoline (MonoAotCompile *acfg, int offset, int *tramp_size)
1662 #if defined(TARGET_AMD64)
1663 #if defined(__default_codegen__)
1664 /* This should be exactly 13 bytes long */
1668 emit_unset_mode (acfg);
1669 fprintf (acfg->fp, "mov %s+%d(%%rip), %%r10\n", acfg->got_symbol, (int)(offset * sizeof (gpointer)));
1670 fprintf (acfg->fp, "jmp *%s+%d(%%rip)\n", acfg->got_symbol, (int)((offset + 1) * sizeof (gpointer)));
1672 /* mov <OFFSET>(%rip), %r10 */
1673 emit_byte (acfg, '\x4d');
1674 emit_byte (acfg, '\x8b');
1675 emit_byte (acfg, '\x15');
1676 emit_symbol_diff (acfg, acfg->got_symbol, ".", (offset * sizeof (gpointer)) - 4);
1678 /* jmp *<offset>(%rip) */
1679 emit_byte (acfg, '\xff');
1680 emit_byte (acfg, '\x25');
1681 emit_symbol_diff (acfg, acfg->got_symbol, ".", ((offset + 1) * sizeof (gpointer)) - 4);
1683 #elif defined(__native_client_codegen__)
1685 guint8 *buf_aligned = ALIGN_TO(buf, kNaClAlignment);
1686 guint8 *code = buf_aligned;
1688 /* mov <OFFSET>(%rip), %r10d */
1689 emit_byte (acfg, '\x45');
1690 emit_byte (acfg, '\x8b');
1691 emit_byte (acfg, '\x15');
1692 emit_symbol_diff (acfg, acfg->got_symbol, ".", (offset * sizeof (gpointer)) - 4);
1694 /* mov <OFFSET>(%rip), %r11d */
1695 emit_byte (acfg, '\x45');
1696 emit_byte (acfg, '\x8b');
1697 emit_byte (acfg, '\x1d');
1698 emit_symbol_diff (acfg, acfg->got_symbol, ".", ((offset + 1) * sizeof (gpointer)) - 4);
1701 amd64_jump_reg (code, AMD64_R11);
1702 emit_bytes (acfg, buf_aligned, code - buf_aligned);
1704 emit_alignment (acfg, kNaClAlignment);
1705 *tramp_size = kNaClAlignment;
1706 #endif /*__native_client_codegen__*/
1708 #elif defined(TARGET_ARM)
1712 /* This should be exactly 24 bytes long */
1715 /* Load rgctx value */
1716 ARM_LDR_IMM (code, ARMREG_IP, ARMREG_PC, 8);
1717 ARM_LDR_REG_REG (code, MONO_ARCH_RGCTX_REG, ARMREG_PC, ARMREG_IP);
1718 /* Load branch addr + branch */
1719 ARM_LDR_IMM (code, ARMREG_IP, ARMREG_PC, 4);
1720 ARM_LDR_REG_REG (code, ARMREG_PC, ARMREG_PC, ARMREG_IP);
1722 g_assert (code - buf == 16);
1725 emit_bytes (acfg, buf, code - buf);
1726 emit_symbol_diff (acfg, acfg->got_symbol, ".", (offset * sizeof (gpointer)) - 4 + 8);
1727 emit_symbol_diff (acfg, acfg->got_symbol, ".", ((offset + 1) * sizeof (gpointer)) - 4 + 4);
1728 #elif defined(TARGET_ARM64)
1729 arm64_emit_static_rgctx_trampoline (acfg, offset, tramp_size);
1730 #elif defined(TARGET_POWERPC)
1737 g_assert (!acfg->use_bin_writer);
1740 * PPC has no ip relative addressing, so we need to compute the address
1741 * of the mscorlib got. That is slow and complex, so instead, we store it
1742 * in the second got slot of every aot image. The caller already computed
1743 * the address of its got and placed it into r30.
1745 emit_unset_mode (acfg);
1746 /* Load mscorlib got address */
1747 fprintf (acfg->fp, "%s 0, %d(30)\n", PPC_LD_OP, (int)sizeof (gpointer));
1749 fprintf (acfg->fp, "lis 11, %d@h\n", (int)(offset * sizeof (gpointer)));
1750 fprintf (acfg->fp, "ori 11, 11, %d@l\n", (int)(offset * sizeof (gpointer)));
1751 fprintf (acfg->fp, "%s %d, 11, 0\n", PPC_LDX_OP, MONO_ARCH_RGCTX_REG);
1752 /* Load target address */
1753 fprintf (acfg->fp, "lis 11, %d@h\n", (int)((offset + 1) * sizeof (gpointer)));
1754 fprintf (acfg->fp, "ori 11, 11, %d@l\n", (int)((offset + 1) * sizeof (gpointer)));
1755 fprintf (acfg->fp, "%s 11, 11, 0\n", PPC_LDX_OP);
1756 #ifdef PPC_USES_FUNCTION_DESCRIPTOR
1757 fprintf (acfg->fp, "%s 2, %d(11)\n", PPC_LD_OP, (int)sizeof (gpointer));
1758 fprintf (acfg->fp, "%s 11, 0(11)\n", PPC_LD_OP);
1760 fprintf (acfg->fp, "mtctr 11\n");
1761 /* Branch to the target address */
1762 fprintf (acfg->fp, "bctr\n");
1764 #ifdef PPC_USES_FUNCTION_DESCRIPTOR
1765 *tramp_size = 11 * 4;
1767 *tramp_size = 9 * 4;
1770 #elif defined(TARGET_X86)
1774 /* Similar to the PPC code above */
1776 g_assert (MONO_ARCH_RGCTX_REG != X86_ECX);
1779 /* Load mscorlib got address */
1780 x86_mov_reg_membase (code, X86_ECX, MONO_ARCH_GOT_REG, sizeof (gpointer), 4);
1782 x86_mov_reg_membase (code, MONO_ARCH_RGCTX_REG, X86_ECX, offset * sizeof (gpointer), 4);
1783 /* Branch to the target address */
1784 x86_jump_membase (code, X86_ECX, (offset + 1) * sizeof (gpointer));
1786 #ifdef __native_client_codegen__
1788 /* emit nops to next 32 byte alignment */
1789 int a = (~kNaClAlignmentMask) & ((code - buf) + kNaClAlignment - 1);
1790 while (code < (buf + a)) x86_nop(code);
1794 emit_bytes (acfg, buf, code - buf);
1796 *tramp_size = NACL_SIZE (15, kNaClAlignment);
1797 g_assert (code - buf == *tramp_size);
1799 g_assert_not_reached ();
1804 * arch_emit_imt_thunk:
1806 * Emit an IMT thunk usable in full-aot mode. The thunk uses 1 got slot which
1807 * points to an array of pointer pairs. The pairs of the form [key, ptr], where
1808 * key is the IMT key, and ptr holds the address of a memory location holding
1809 * the address to branch to if the IMT arg matches the key. The array is
1810 * terminated by a pair whose key is NULL, and whose ptr is the address of the
1812 * TRAMP_SIZE is set to the size of the emitted trampoline.
1815 arch_emit_imt_thunk (MonoAotCompile *acfg, int offset, int *tramp_size)
1817 #if defined(TARGET_AMD64)
1819 #if defined(__native_client_codegen__)
1822 guint8 *labels [16];
1824 guint8 *mov_buf_ptr = mov_buf;
1826 const int kSizeOfMove = 7;
1827 #if defined(__default_codegen__)
1828 code = buf = g_malloc (256);
1829 #elif defined(__native_client_codegen__)
1830 buf_alloc = g_malloc (256 + kNaClAlignment + kSizeOfMove);
1831 buf = ((guint)buf_alloc + kNaClAlignment) & ~kNaClAlignmentMask;
1832 /* The RIP relative move below is emitted first */
1837 /* FIXME: Optimize this, i.e. use binary search etc. */
1838 /* Maybe move the body into a separate function (slower, but much smaller) */
1840 /* MONO_ARCH_IMT_SCRATCH_REG is a free register */
1843 emit_unset_mode (acfg);
1844 fprintf (acfg->fp, "mov %s+%d(%%rip), %s\n", acfg->got_symbol, (int)(offset * sizeof (gpointer)), mono_arch_regname (MONO_ARCH_IMT_SCRATCH_REG));
1848 amd64_alu_membase_imm (code, X86_CMP, MONO_ARCH_IMT_SCRATCH_REG, 0, 0);
1850 amd64_branch8 (code, X86_CC_Z, 0, FALSE);
1853 amd64_alu_membase_reg_size (code, X86_CMP, MONO_ARCH_IMT_SCRATCH_REG, 0, MONO_ARCH_IMT_REG, sizeof (gpointer));
1855 amd64_branch8 (code, X86_CC_Z, 0, FALSE);
1858 amd64_alu_reg_imm (code, X86_ADD, MONO_ARCH_IMT_SCRATCH_REG, 2 * sizeof (gpointer));
1859 amd64_jump_code (code, labels [0]);
1862 mono_amd64_patch (labels [2], code);
1863 amd64_mov_reg_membase (code, MONO_ARCH_IMT_SCRATCH_REG, MONO_ARCH_IMT_SCRATCH_REG, sizeof (gpointer), sizeof (gpointer));
1864 amd64_jump_membase (code, MONO_ARCH_IMT_SCRATCH_REG, 0);
1867 mono_amd64_patch (labels [1], code);
1868 /* Load fail tramp */
1869 amd64_alu_reg_imm (code, X86_ADD, MONO_ARCH_IMT_SCRATCH_REG, sizeof (gpointer));
1870 /* Check if there is a fail tramp */
1871 amd64_alu_membase_imm (code, X86_CMP, MONO_ARCH_IMT_SCRATCH_REG, 0, 0);
1873 amd64_branch8 (code, X86_CC_Z, 0, FALSE);
1874 /* Jump to fail tramp */
1875 amd64_jump_membase (code, MONO_ARCH_IMT_SCRATCH_REG, 0);
1878 mono_amd64_patch (labels [3], code);
1879 x86_breakpoint (code);
1882 /* mov <OFFSET>(%rip), MONO_ARCH_IMT_SCRATCH_REG */
1883 amd64_emit_rex (mov_buf_ptr, sizeof(gpointer), MONO_ARCH_IMT_SCRATCH_REG, 0, AMD64_RIP);
1884 *(mov_buf_ptr)++ = (unsigned char)0x8b; /* mov opcode */
1885 x86_address_byte (mov_buf_ptr, 0, MONO_ARCH_IMT_SCRATCH_REG & 0x7, 5);
1886 emit_bytes (acfg, mov_buf, mov_buf_ptr - mov_buf);
1887 emit_symbol_diff (acfg, acfg->got_symbol, ".", (offset * sizeof (gpointer)) - 4);
1889 emit_bytes (acfg, buf, code - buf);
1891 *tramp_size = code - buf + kSizeOfMove;
1892 #if defined(__native_client_codegen__)
1893 /* The tramp will be padded to the next kNaClAlignment bundle. */
1894 *tramp_size = ALIGN_TO ((*tramp_size), kNaClAlignment);
1897 #if defined(__default_codegen__)
1899 #elif defined(__native_client_codegen__)
1903 #elif defined(TARGET_X86)
1905 #ifdef __native_client_codegen__
1908 guint8 *labels [16];
1910 #if defined(__default_codegen__)
1911 code = buf = g_malloc (256);
1912 #elif defined(__native_client_codegen__)
1913 buf_alloc = g_malloc (256 + kNaClAlignment);
1914 code = buf = ((guint)buf_alloc + kNaClAlignment) & ~kNaClAlignmentMask;
1917 /* Allocate a temporary stack slot */
1918 x86_push_reg (code, X86_EAX);
1920 x86_push_reg (code, X86_EAX);
1922 /* Load mscorlib got address */
1923 x86_mov_reg_membase (code, X86_EAX, MONO_ARCH_GOT_REG, sizeof (gpointer), 4);
1925 x86_mov_reg_membase (code, X86_EAX, X86_EAX, offset * sizeof (gpointer), 4);
1928 x86_alu_membase_imm (code, X86_CMP, X86_EAX, 0, 0);
1930 x86_branch8 (code, X86_CC_Z, FALSE, 0);
1933 x86_alu_membase_reg (code, X86_CMP, X86_EAX, 0, MONO_ARCH_IMT_REG);
1935 x86_branch8 (code, X86_CC_Z, FALSE, 0);
1938 x86_alu_reg_imm (code, X86_ADD, X86_EAX, 2 * sizeof (gpointer));
1939 x86_jump_code (code, labels [0]);
1942 mono_x86_patch (labels [2], code);
1943 x86_mov_reg_membase (code, X86_EAX, X86_EAX, sizeof (gpointer), 4);
1944 x86_mov_reg_membase (code, X86_EAX, X86_EAX, 0, 4);
1945 /* Save the target address to the temporary stack location */
1946 x86_mov_membase_reg (code, X86_ESP, 4, X86_EAX, 4);
1948 x86_pop_reg (code, X86_EAX);
1949 /* Jump to the target address */
1953 mono_x86_patch (labels [1], code);
1954 /* Load fail tramp */
1955 x86_mov_reg_membase (code, X86_EAX, X86_EAX, sizeof (gpointer), 4);
1956 x86_alu_membase_imm (code, X86_CMP, X86_EAX, 0, 0);
1958 x86_branch8 (code, X86_CC_Z, FALSE, 0);
1959 /* Jump to fail tramp */
1960 x86_mov_membase_reg (code, X86_ESP, 4, X86_EAX, 4);
1961 x86_pop_reg (code, X86_EAX);
1965 mono_x86_patch (labels [3], code);
1966 x86_breakpoint (code);
1968 #ifdef __native_client_codegen__
1970 /* emit nops to next 32 byte alignment */
1971 int a = (~kNaClAlignmentMask) & ((code - buf) + kNaClAlignment - 1);
1972 while (code < (buf + a)) x86_nop(code);
1975 emit_bytes (acfg, buf, code - buf);
1977 *tramp_size = code - buf;
1979 #if defined(__default_codegen__)
1981 #elif defined(__native_client_codegen__)
1985 #elif defined(TARGET_ARM)
1987 guint8 *code, *code2, *labels [16];
1991 /* The IMT method is in v5 */
1993 /* Need at least two free registers, plus a slot for storing the pc */
1994 ARM_PUSH (code, (1 << ARMREG_R0)|(1 << ARMREG_R1)|(1 << ARMREG_R2));
1996 /* Load the parameter from the GOT */
1997 ARM_LDR_IMM (code, ARMREG_R0, ARMREG_PC, 0);
1998 ARM_LDR_REG_REG (code, ARMREG_R0, ARMREG_PC, ARMREG_R0);
2001 ARM_LDR_IMM (code, ARMREG_R1, ARMREG_R0, 0);
2002 ARM_CMP_REG_REG (code, ARMREG_R1, ARMREG_V5);
2004 ARM_B_COND (code, ARMCOND_EQ, 0);
2006 /* End-of-loop check */
2007 ARM_CMP_REG_IMM (code, ARMREG_R1, 0, 0);
2009 ARM_B_COND (code, ARMCOND_EQ, 0);
2012 ARM_ADD_REG_IMM8 (code, ARMREG_R0, ARMREG_R0, sizeof (gpointer) * 2);
2015 arm_patch (labels [4], labels [1]);
2018 arm_patch (labels [2], code);
2019 ARM_LDR_IMM (code, ARMREG_R0, ARMREG_R0, 4);
2020 ARM_LDR_IMM (code, ARMREG_R0, ARMREG_R0, 0);
2021 /* Save it to the third stack slot */
2022 ARM_STR_IMM (code, ARMREG_R0, ARMREG_SP, 8);
2023 /* Restore the registers and branch */
2024 ARM_POP (code, (1 << ARMREG_R0)|(1 << ARMREG_R1)|(1 << ARMREG_PC));
2027 arm_patch (labels [3], code);
2028 ARM_LDR_IMM (code, ARMREG_R0, ARMREG_R0, 4);
2029 ARM_STR_IMM (code, ARMREG_R0, ARMREG_SP, 8);
2030 ARM_POP (code, (1 << ARMREG_R0)|(1 << ARMREG_R1)|(1 << ARMREG_PC));
2034 ARM_LDR_IMM (code2, ARMREG_R0, ARMREG_PC, (code - (labels [0] + 8)));
2036 emit_bytes (acfg, buf, code - buf);
2037 emit_symbol_diff (acfg, acfg->got_symbol, ".", (offset * sizeof (gpointer)) + (code - (labels [0] + 8)) - 4);
2039 *tramp_size = code - buf + 4;
2040 #elif defined(TARGET_ARM64)
2041 arm64_emit_imt_thunk (acfg, offset, tramp_size);
2042 #elif defined(TARGET_POWERPC)
2044 guint8 *code, *labels [16];
2048 /* Load the mscorlib got address */
2049 ppc_ldptr (code, ppc_r12, sizeof (gpointer), ppc_r30);
2050 /* Load the parameter from the GOT */
2051 ppc_load (code, ppc_r0, offset * sizeof (gpointer));
2052 ppc_ldptr_indexed (code, ppc_r12, ppc_r12, ppc_r0);
2054 /* Load and check key */
2056 ppc_ldptr (code, ppc_r0, 0, ppc_r12);
2057 ppc_cmp (code, 0, sizeof (gpointer) == 8 ? 1 : 0, ppc_r0, MONO_ARCH_IMT_REG);
2059 ppc_bc (code, PPC_BR_TRUE, PPC_BR_EQ, 0);
2061 /* End-of-loop check */
2062 ppc_cmpi (code, 0, sizeof (gpointer) == 8 ? 1 : 0, ppc_r0, 0);
2064 ppc_bc (code, PPC_BR_TRUE, PPC_BR_EQ, 0);
2067 ppc_addi (code, ppc_r12, ppc_r12, 2 * sizeof (gpointer));
2070 mono_ppc_patch (labels [4], labels [1]);
2073 mono_ppc_patch (labels [2], code);
2074 ppc_ldptr (code, ppc_r12, sizeof (gpointer), ppc_r12);
2075 /* r12 now contains the value of the vtable slot */
2076 /* this is not a function descriptor on ppc64 */
2077 ppc_ldptr (code, ppc_r12, 0, ppc_r12);
2078 ppc_mtctr (code, ppc_r12);
2079 ppc_bcctr (code, PPC_BR_ALWAYS, 0);
2082 mono_ppc_patch (labels [3], code);
2086 *tramp_size = code - buf;
2088 emit_bytes (acfg, buf, code - buf);
2090 g_assert_not_reached ();
2095 * arch_emit_gsharedvt_arg_trampoline:
2097 * Emit code for a gsharedvt arg trampoline. OFFSET is the offset of the first of
2098 * two GOT slots which contain the argument, and the code to jump to.
2099 * TRAMP_SIZE is set to the size of the emitted trampoline.
2100 * These kinds of trampolines cannot be enumerated statically, since there could
2101 * be one trampoline per method instantiation, so we emit the same code for all
2102 * trampolines, and parameterize them using two GOT slots.
2105 arch_emit_gsharedvt_arg_trampoline (MonoAotCompile *acfg, int offset, int *tramp_size)
2107 #if defined(TARGET_X86)
2111 /* Similar to the PPC code above */
2113 g_assert (MONO_ARCH_RGCTX_REG != X86_ECX);
2116 /* Load mscorlib got address */
2117 x86_mov_reg_membase (code, X86_ECX, MONO_ARCH_GOT_REG, sizeof (gpointer), 4);
2119 x86_mov_reg_membase (code, X86_EAX, X86_ECX, offset * sizeof (gpointer), 4);
2120 /* Branch to the target address */
2121 x86_jump_membase (code, X86_ECX, (offset + 1) * sizeof (gpointer));
2123 #ifdef __native_client_codegen__
2125 /* emit nops to next 32 byte alignment */
2126 int a = (~kNaClAlignmentMask) & ((code - buf) + kNaClAlignment - 1);
2127 while (code < (buf + a)) x86_nop(code);
2131 emit_bytes (acfg, buf, code - buf);
2133 *tramp_size = NACL_SIZE (15, kNaClAlignment);
2134 g_assert (code - buf == *tramp_size);
2135 #elif defined(TARGET_ARM)
2139 /* The same as mono_arch_get_gsharedvt_arg_trampoline (), but for AOT */
2140 /* Similar to arch_emit_specific_trampoline () */
2143 ARM_PUSH (code, (1 << ARMREG_R0) | (1 << ARMREG_R1) | (1 << ARMREG_R2) | (1 << ARMREG_R3));
2144 ARM_LDR_IMM (code, ARMREG_R1, ARMREG_PC, 8);
2145 /* Load the arg value from the GOT */
2146 ARM_LDR_REG_REG (code, ARMREG_R0, ARMREG_PC, ARMREG_R1);
2147 /* Load the addr from the GOT */
2148 ARM_LDR_REG_REG (code, ARMREG_R1, ARMREG_PC, ARMREG_R1);
2150 ARM_BX (code, ARMREG_R1);
2152 g_assert (code - buf == 20);
2155 emit_bytes (acfg, buf, code - buf);
2156 emit_symbol_diff (acfg, acfg->got_symbol, ".", (offset * sizeof (gpointer)) + 4);
2157 #elif defined(TARGET_ARM64)
2158 arm64_emit_gsharedvt_arg_trampoline (acfg, offset, tramp_size);
2160 g_assert_not_reached ();
2165 arch_emit_autoreg (MonoAotCompile *acfg, char *symbol)
2167 #if defined(TARGET_POWERPC) && defined(__mono_ilp32__)
2168 /* Based on code generated by gcc */
2169 emit_unset_mode (acfg);
2172 #if defined(_MSC_VER) || defined(MONO_CROSS_COMPILE)
2173 ".section .ctors,\"aw\",@progbits\n"
2177 ".section .opd,\"aw\"\n"
2180 ".long .%s,.TOC.@tocbase32\n"
2183 ".type .%s,@function\n"
2185 ".%s:\n", symbol, symbol, symbol, symbol, symbol, symbol, symbol, symbol);
2187 ".section .ctors,\"aw\",@progbits\n"
2191 ".section .opd,\"aw\"\n"
2194 ".long .%1$s,.TOC.@tocbase32\n"
2195 ".size %1$s,.-%1$s\n"
2197 ".type .%1$s,@function\n"
2199 ".%1$s:\n", symbol);
2210 "lis 3, .Lglobals@h\n"
2211 "ori 3, 3, .Lglobals@l\n"
2212 "bl .mono_aot_register_module\n"
2220 #if defined(_MSC_VER) || defined(MONO_CROSS_COMPILE)
2222 ".size .%s,.-.%s\n", symbol, symbol);
2225 ".size .%1$s,.-.%1$s\n", symbol);
2231 /* END OF ARCH SPECIFIC CODE */
2234 mono_get_field_token (MonoClassField *field)
2236 MonoClass *klass = field->parent;
2239 for (i = 0; i < klass->field.count; ++i) {
2240 if (field == &klass->fields [i])
2241 return MONO_TOKEN_FIELD_DEF | (klass->field.first + 1 + i);
2244 g_assert_not_reached ();
2249 encode_value (gint32 value, guint8 *buf, guint8 **endbuf)
2253 //printf ("ENCODE: %d 0x%x.\n", value, value);
2256 * Same encoding as the one used in the metadata, extended to handle values
2257 * greater than 0x1fffffff.
2259 if ((value >= 0) && (value <= 127))
2261 else if ((value >= 0) && (value <= 16383)) {
2262 p [0] = 0x80 | (value >> 8);
2263 p [1] = value & 0xff;
2265 } else if ((value >= 0) && (value <= 0x1fffffff)) {
2266 p [0] = (value >> 24) | 0xc0;
2267 p [1] = (value >> 16) & 0xff;
2268 p [2] = (value >> 8) & 0xff;
2269 p [3] = value & 0xff;
2274 p [1] = (value >> 24) & 0xff;
2275 p [2] = (value >> 16) & 0xff;
2276 p [3] = (value >> 8) & 0xff;
2277 p [4] = value & 0xff;
2285 stream_init (MonoDynamicStream *sh)
2288 sh->alloc_size = 4096;
2289 sh->data = g_malloc (4096);
2291 /* So offsets are > 0 */
2297 make_room_in_stream (MonoDynamicStream *stream, int size)
2299 if (size <= stream->alloc_size)
2302 while (stream->alloc_size <= size) {
2303 if (stream->alloc_size < 4096)
2304 stream->alloc_size = 4096;
2306 stream->alloc_size *= 2;
2309 stream->data = g_realloc (stream->data, stream->alloc_size);
2313 add_stream_data (MonoDynamicStream *stream, const char *data, guint32 len)
2317 make_room_in_stream (stream, stream->index + len);
2318 memcpy (stream->data + stream->index, data, len);
2319 idx = stream->index;
2320 stream->index += len;
2327 * Add data to the binary blob inside the aot image. Returns the offset inside the
2328 * blob where the data was stored.
2331 add_to_blob (MonoAotCompile *acfg, const guint8 *data, guint32 data_len)
2333 if (acfg->blob.alloc_size == 0)
2334 stream_init (&acfg->blob);
2336 return add_stream_data (&acfg->blob, (char*)data, data_len);
2340 add_to_blob_aligned (MonoAotCompile *acfg, const guint8 *data, guint32 data_len, guint32 align)
2345 if (acfg->blob.alloc_size == 0)
2346 stream_init (&acfg->blob);
2348 count = acfg->blob.index % align;
2350 /* we assume the stream data will be aligned */
2352 add_stream_data (&acfg->blob, buf, 4 - count);
2354 return add_stream_data (&acfg->blob, (char*)data, data_len);
2358 * emit_offset_table:
2360 * Emit a table of increasing offsets in a compact form using differential encoding.
2361 * There is an index entry for each GROUP_SIZE number of entries. The greater the
2362 * group size, the more compact the table becomes, but the slower it becomes to compute
2363 * a given entry. Returns the size of the table.
2366 emit_offset_table (MonoAotCompile *acfg, const char *symbol, int noffsets, int group_size, gint32 *offsets)
2368 gint32 current_offset;
2369 int i, buf_size, ngroups, index_entry_size;
2371 guint8 *data_p, *data_buf;
2372 guint32 *index_offsets;
2374 ngroups = (noffsets + (group_size - 1)) / group_size;
2376 index_offsets = g_new0 (guint32, ngroups);
2378 buf_size = noffsets * 4;
2379 p = buf = g_malloc0 (buf_size);
2382 for (i = 0; i < noffsets; ++i) {
2383 //printf ("D: %d -> %d\n", i, offsets [i]);
2384 if ((i % group_size) == 0) {
2385 index_offsets [i / group_size] = p - buf;
2386 /* Emit the full value for these entries */
2387 encode_value (offsets [i], p, &p);
2389 /* The offsets are allowed to be non-increasing */
2390 //g_assert (offsets [i] >= current_offset);
2391 encode_value (offsets [i] - current_offset, p, &p);
2393 current_offset = offsets [i];
2398 if (ngroups && index_offsets [ngroups - 1] < 65000)
2399 index_entry_size = 2;
2401 index_entry_size = 4;
2403 buf_size = (data_p - data_buf) + (ngroups * 4) + 16;
2404 p = buf = g_malloc0 (buf_size);
2406 /* Emit the header */
2407 encode_int (noffsets, p, &p);
2408 encode_int (group_size, p, &p);
2409 encode_int (ngroups, p, &p);
2410 encode_int (index_entry_size, p, &p);
2412 /* Emit the index */
2413 for (i = 0; i < ngroups; ++i) {
2414 if (index_entry_size == 2)
2415 encode_int16 (index_offsets [i], p, &p);
2417 encode_int (index_offsets [i], p, &p);
2420 memcpy (p, data_buf, data_p - data_buf);
2421 p += data_p - data_buf;
2423 g_assert (p - buf <= buf_size);
2425 emit_section_change (acfg, RODATA_SECT, 1);
2426 emit_alignment (acfg, 8);
2427 emit_label (acfg, symbol);
2429 emit_bytes (acfg, buf, p - buf);
2434 return (int)(p - buf);
2438 get_image_index (MonoAotCompile *cfg, MonoImage *image)
2442 index = GPOINTER_TO_UINT (g_hash_table_lookup (cfg->image_hash, image));
2446 index = g_hash_table_size (cfg->image_hash);
2447 g_hash_table_insert (cfg->image_hash, image, GUINT_TO_POINTER (index + 1));
2448 g_ptr_array_add (cfg->image_table, image);
2454 find_typespec_for_class (MonoAotCompile *acfg, MonoClass *klass)
2457 int len = acfg->image->tables [MONO_TABLE_TYPESPEC].rows;
2459 /* FIXME: Search referenced images as well */
2460 if (!acfg->typespec_classes) {
2461 acfg->typespec_classes = mono_mempool_alloc0 (acfg->mempool, sizeof (MonoClass*) * len);
2462 for (i = 0; i < len; ++i) {
2464 acfg->typespec_classes [i] = mono_class_get_and_inflate_typespec_checked (acfg->image, MONO_TOKEN_TYPE_SPEC | (i + 1), NULL, &error);
2465 g_assert (mono_error_ok (&error)); /* FIXME error handling */
2468 for (i = 0; i < len; ++i) {
2469 if (acfg->typespec_classes [i] == klass)
2474 return MONO_TOKEN_TYPE_SPEC | (i + 1);
2480 encode_method_ref (MonoAotCompile *acfg, MonoMethod *method, guint8 *buf, guint8 **endbuf);
2483 encode_klass_ref (MonoAotCompile *acfg, MonoClass *klass, guint8 *buf, guint8 **endbuf);
2486 encode_ginst (MonoAotCompile *acfg, MonoGenericInst *inst, guint8 *buf, guint8 **endbuf);
2489 encode_type (MonoAotCompile *acfg, MonoType *t, guint8 *buf, guint8 **endbuf);
2492 encode_klass_ref_inner (MonoAotCompile *acfg, MonoClass *klass, guint8 *buf, guint8 **endbuf)
2497 * The encoding begins with one of the MONO_AOT_TYPEREF values, followed by additional
2501 if (klass->generic_class) {
2503 g_assert (klass->type_token);
2505 /* Find a typespec for a class if possible */
2506 token = find_typespec_for_class (acfg, klass);
2508 encode_value (MONO_AOT_TYPEREF_TYPESPEC_TOKEN, p, &p);
2509 encode_value (token, p, &p);
2511 MonoClass *gclass = klass->generic_class->container_class;
2512 MonoGenericInst *inst = klass->generic_class->context.class_inst;
2513 static int count = 0;
2516 encode_value (MONO_AOT_TYPEREF_GINST, p, &p);
2517 encode_klass_ref (acfg, gclass, p, &p);
2518 encode_ginst (acfg, inst, p, &p);
2522 } else if (klass->type_token) {
2523 int iindex = get_image_index (acfg, klass->image);
2525 g_assert (mono_metadata_token_code (klass->type_token) == MONO_TOKEN_TYPE_DEF);
2527 encode_value (MONO_AOT_TYPEREF_TYPEDEF_INDEX, p, &p);
2528 encode_value (klass->type_token - MONO_TOKEN_TYPE_DEF, p, &p);
2530 encode_value (MONO_AOT_TYPEREF_TYPEDEF_INDEX_IMAGE, p, &p);
2531 encode_value (klass->type_token - MONO_TOKEN_TYPE_DEF, p, &p);
2532 encode_value (get_image_index (acfg, klass->image), p, &p);
2534 } else if ((klass->byval_arg.type == MONO_TYPE_VAR) || (klass->byval_arg.type == MONO_TYPE_MVAR)) {
2535 MonoGenericContainer *container = mono_type_get_generic_param_owner (&klass->byval_arg);
2536 MonoGenericParam *par = klass->byval_arg.data.generic_param;
2538 encode_value (MONO_AOT_TYPEREF_VAR, p, &p);
2539 encode_value (klass->byval_arg.type, p, &p);
2540 encode_value (mono_type_get_generic_param_num (&klass->byval_arg), p, &p);
2542 encode_value (container ? 1 : 0, p, &p);
2544 encode_value (container->is_method, p, &p);
2545 g_assert (!par->gshared_constraint);
2546 if (container->is_method)
2547 encode_method_ref (acfg, container->owner.method, p, &p);
2549 encode_klass_ref (acfg, container->owner.klass, p, &p);
2551 encode_value (par->gshared_constraint ? 1 : 0, p, &p);
2552 if (par->gshared_constraint) {
2555 encode_type (acfg, par->gshared_constraint, p, &p);
2557 name = mono_generic_param_name (par);
2559 int len = strlen (name);
2561 encode_value (len, p, &p);
2562 memcpy (p, name, len);
2565 encode_value (0, p, &p);
2569 } else if (klass->byval_arg.type == MONO_TYPE_PTR) {
2570 encode_value (MONO_AOT_TYPEREF_PTR, p, &p);
2571 encode_type (acfg, &klass->byval_arg, p, &p);
2574 g_assert (klass->rank > 0);
2575 encode_value (MONO_AOT_TYPEREF_ARRAY, p, &p);
2576 encode_value (klass->rank, p, &p);
2577 encode_klass_ref (acfg, klass->element_class, p, &p);
2585 * Encode a reference to KLASS. We use our home-grown encoding instead of the
2586 * standard metadata encoding.
2589 encode_klass_ref (MonoAotCompile *acfg, MonoClass *klass, guint8 *buf, guint8 **endbuf)
2591 gboolean shared = FALSE;
2594 * The encoding of generic instances is large so emit them only once.
2596 if (klass->generic_class) {
2598 g_assert (klass->type_token);
2600 /* Find a typespec for a class if possible */
2601 token = find_typespec_for_class (acfg, klass);
2604 } else if ((klass->byval_arg.type == MONO_TYPE_VAR) || (klass->byval_arg.type == MONO_TYPE_MVAR)) {
2609 guint offset = GPOINTER_TO_UINT (g_hash_table_lookup (acfg->klass_blob_hash, klass));
2613 buf2 = g_malloc (1024);
2616 encode_klass_ref_inner (acfg, klass, p, &p);
2617 g_assert (p - buf2 < 1024);
2619 offset = add_to_blob (acfg, buf2, p - buf2);
2622 g_hash_table_insert (acfg->klass_blob_hash, klass, GUINT_TO_POINTER (offset + 1));
2628 encode_value (MONO_AOT_TYPEREF_BLOB_INDEX, p, &p);
2629 encode_value (offset, p, &p);
2634 encode_klass_ref_inner (acfg, klass, buf, endbuf);
2638 encode_field_info (MonoAotCompile *cfg, MonoClassField *field, guint8 *buf, guint8 **endbuf)
2640 guint32 token = mono_get_field_token (field);
2643 encode_klass_ref (cfg, field->parent, p, &p);
2644 g_assert (mono_metadata_token_code (token) == MONO_TOKEN_FIELD_DEF);
2645 encode_value (token - MONO_TOKEN_FIELD_DEF, p, &p);
2650 encode_ginst (MonoAotCompile *acfg, MonoGenericInst *inst, guint8 *buf, guint8 **endbuf)
2655 encode_value (inst->type_argc, p, &p);
2656 for (i = 0; i < inst->type_argc; ++i)
2657 encode_klass_ref (acfg, mono_class_from_mono_type (inst->type_argv [i]), p, &p);
2662 encode_generic_context (MonoAotCompile *acfg, MonoGenericContext *context, guint8 *buf, guint8 **endbuf)
2665 MonoGenericInst *inst;
2667 inst = context->class_inst;
2669 g_assert (inst->type_argc);
2670 encode_ginst (acfg, inst, p, &p);
2672 encode_value (0, p, &p);
2674 inst = context->method_inst;
2676 g_assert (inst->type_argc);
2677 encode_ginst (acfg, inst, p, &p);
2679 encode_value (0, p, &p);
2685 encode_type (MonoAotCompile *acfg, MonoType *t, guint8 *buf, guint8 **endbuf)
2689 g_assert (t->num_mods == 0);
2690 /* t->attrs can be ignored */
2691 //g_assert (t->attrs == 0);
2694 *p = MONO_TYPE_PINNED;
2698 *p = MONO_TYPE_BYREF;
2706 case MONO_TYPE_VOID:
2707 case MONO_TYPE_BOOLEAN:
2708 case MONO_TYPE_CHAR:
2721 case MONO_TYPE_STRING:
2722 case MONO_TYPE_OBJECT:
2723 case MONO_TYPE_TYPEDBYREF:
2725 case MONO_TYPE_VALUETYPE:
2726 case MONO_TYPE_CLASS:
2727 encode_klass_ref (acfg, mono_class_from_mono_type (t), p, &p);
2729 case MONO_TYPE_SZARRAY:
2730 encode_klass_ref (acfg, t->data.klass, p, &p);
2733 encode_type (acfg, t->data.type, p, &p);
2735 case MONO_TYPE_GENERICINST: {
2736 MonoClass *gclass = t->data.generic_class->container_class;
2737 MonoGenericInst *inst = t->data.generic_class->context.class_inst;
2739 encode_klass_ref (acfg, gclass, p, &p);
2740 encode_ginst (acfg, inst, p, &p);
2743 case MONO_TYPE_ARRAY: {
2744 MonoArrayType *array = t->data.array;
2747 encode_klass_ref (acfg, array->eklass, p, &p);
2748 encode_value (array->rank, p, &p);
2749 encode_value (array->numsizes, p, &p);
2750 for (i = 0; i < array->numsizes; ++i)
2751 encode_value (array->sizes [i], p, &p);
2752 encode_value (array->numlobounds, p, &p);
2753 for (i = 0; i < array->numlobounds; ++i)
2754 encode_value (array->lobounds [i], p, &p);
2758 case MONO_TYPE_MVAR:
2759 encode_klass_ref (acfg, mono_class_from_mono_type (t), p, &p);
2762 g_assert_not_reached ();
2769 encode_signature (MonoAotCompile *acfg, MonoMethodSignature *sig, guint8 *buf, guint8 **endbuf)
2775 /* Similar to the metadata encoding */
2776 if (sig->generic_param_count)
2780 if (sig->explicit_this)
2782 flags |= (sig->call_convention & 0x0F);
2786 if (sig->generic_param_count)
2787 encode_value (sig->generic_param_count, p, &p);
2788 encode_value (sig->param_count, p, &p);
2790 encode_type (acfg, sig->ret, p, &p);
2791 for (i = 0; i < sig->param_count; ++i) {
2792 if (sig->sentinelpos == i) {
2793 *p = MONO_TYPE_SENTINEL;
2796 encode_type (acfg, sig->params [i], p, &p);
2802 #define MAX_IMAGE_INDEX 250
2805 encode_method_ref (MonoAotCompile *acfg, MonoMethod *method, guint8 *buf, guint8 **endbuf)
2807 guint32 image_index = get_image_index (acfg, method->klass->image);
2808 guint32 token = method->token;
2809 MonoJumpInfoToken *ji;
2813 * The encoding for most methods is as follows:
2814 * - image index encoded as a leb128
2815 * - token index encoded as a leb128
2816 * Values of image index >= MONO_AOT_METHODREF_MIN are used to mark additional
2817 * types of method encodings.
2820 /* Mark methods which can't use aot trampolines because they need the further
2821 * processing in mono_magic_trampoline () which requires a MonoMethod*.
2823 if ((method->is_generic && (method->flags & METHOD_ATTRIBUTE_VIRTUAL)) ||
2824 (method->iflags & METHOD_IMPL_ATTRIBUTE_SYNCHRONIZED))
2825 encode_value ((MONO_AOT_METHODREF_NO_AOT_TRAMPOLINE << 24), p, &p);
2827 if (method->wrapper_type) {
2828 encode_value ((MONO_AOT_METHODREF_WRAPPER << 24), p, &p);
2830 encode_value (method->wrapper_type, p, &p);
2832 switch (method->wrapper_type) {
2833 case MONO_WRAPPER_REMOTING_INVOKE:
2834 case MONO_WRAPPER_REMOTING_INVOKE_WITH_CHECK:
2835 case MONO_WRAPPER_XDOMAIN_INVOKE: {
2838 m = mono_marshal_method_from_wrapper (method);
2840 encode_method_ref (acfg, m, p, &p);
2843 case MONO_WRAPPER_PROXY_ISINST:
2844 case MONO_WRAPPER_LDFLD:
2845 case MONO_WRAPPER_LDFLDA:
2846 case MONO_WRAPPER_STFLD:
2847 case MONO_WRAPPER_ISINST: {
2848 WrapperInfo *info = mono_marshal_get_wrapper_info (method);
2851 encode_klass_ref (acfg, info->d.proxy.klass, p, &p);
2854 case MONO_WRAPPER_LDFLD_REMOTE:
2855 case MONO_WRAPPER_STFLD_REMOTE:
2857 case MONO_WRAPPER_ALLOC: {
2858 AllocatorWrapperInfo *info = mono_marshal_get_wrapper_info (method);
2860 /* The GC name is saved once in MonoAotFileInfo */
2861 g_assert (info->alloc_type != -1);
2862 encode_value (info->alloc_type, p, &p);
2865 case MONO_WRAPPER_WRITE_BARRIER:
2867 case MONO_WRAPPER_STELEMREF: {
2868 WrapperInfo *info = mono_marshal_get_wrapper_info (method);
2871 encode_value (info->subtype, p, &p);
2872 if (info->subtype == WRAPPER_SUBTYPE_VIRTUAL_STELEMREF)
2873 encode_value (info->d.virtual_stelemref.kind, p, &p);
2876 case MONO_WRAPPER_UNKNOWN: {
2877 WrapperInfo *info = mono_marshal_get_wrapper_info (method);
2880 encode_value (info->subtype, p, &p);
2881 if (info->subtype == WRAPPER_SUBTYPE_PTR_TO_STRUCTURE ||
2882 info->subtype == WRAPPER_SUBTYPE_STRUCTURE_TO_PTR)
2883 encode_klass_ref (acfg, method->klass, p, &p);
2884 else if (info->subtype == WRAPPER_SUBTYPE_SYNCHRONIZED_INNER)
2885 encode_method_ref (acfg, info->d.synchronized_inner.method, p, &p);
2886 else if (info->subtype == WRAPPER_SUBTYPE_ARRAY_ACCESSOR)
2887 encode_method_ref (acfg, info->d.array_accessor.method, p, &p);
2890 case MONO_WRAPPER_MANAGED_TO_NATIVE: {
2891 WrapperInfo *info = mono_marshal_get_wrapper_info (method);
2894 encode_value (info->subtype, p, &p);
2895 if (info->subtype == WRAPPER_SUBTYPE_ICALL_WRAPPER) {
2896 strcpy ((char*)p, method->name);
2897 p += strlen (method->name) + 1;
2898 } else if (info->subtype == WRAPPER_SUBTYPE_NATIVE_FUNC_AOT) {
2899 encode_method_ref (acfg, info->d.managed_to_native.method, p, &p);
2901 g_assert (info->subtype == WRAPPER_SUBTYPE_NONE || info->subtype == WRAPPER_SUBTYPE_PINVOKE);
2902 encode_method_ref (acfg, info->d.managed_to_native.method, p, &p);
2906 case MONO_WRAPPER_SYNCHRONIZED: {
2909 m = mono_marshal_method_from_wrapper (method);
2911 g_assert (m != method);
2912 encode_method_ref (acfg, m, p, &p);
2915 case MONO_WRAPPER_MANAGED_TO_MANAGED: {
2916 WrapperInfo *info = mono_marshal_get_wrapper_info (method);
2919 encode_value (info->subtype, p, &p);
2921 if (info->subtype == WRAPPER_SUBTYPE_ELEMENT_ADDR) {
2922 encode_value (info->d.element_addr.rank, p, &p);
2923 encode_value (info->d.element_addr.elem_size, p, &p);
2924 } else if (info->subtype == WRAPPER_SUBTYPE_STRING_CTOR) {
2925 encode_method_ref (acfg, info->d.string_ctor.method, p, &p);
2927 g_assert_not_reached ();
2931 case MONO_WRAPPER_CASTCLASS: {
2932 WrapperInfo *info = mono_marshal_get_wrapper_info (method);
2935 encode_value (info->subtype, p, &p);
2938 case MONO_WRAPPER_RUNTIME_INVOKE: {
2939 WrapperInfo *info = mono_marshal_get_wrapper_info (method);
2942 encode_value (info->subtype, p, &p);
2943 if (info->subtype == WRAPPER_SUBTYPE_RUNTIME_INVOKE_DIRECT || info->subtype == WRAPPER_SUBTYPE_RUNTIME_INVOKE_VIRTUAL)
2944 encode_method_ref (acfg, info->d.runtime_invoke.method, p, &p);
2945 else if (info->subtype == WRAPPER_SUBTYPE_RUNTIME_INVOKE_NORMAL)
2946 encode_signature (acfg, info->d.runtime_invoke.sig, p, &p);
2949 case MONO_WRAPPER_DELEGATE_INVOKE:
2950 case MONO_WRAPPER_DELEGATE_BEGIN_INVOKE:
2951 case MONO_WRAPPER_DELEGATE_END_INVOKE: {
2952 if (method->is_inflated) {
2953 /* These wrappers are identified by their class */
2954 encode_value (1, p, &p);
2955 encode_klass_ref (acfg, method->klass, p, &p);
2957 MonoMethodSignature *sig = mono_method_signature (method);
2958 WrapperInfo *info = mono_marshal_get_wrapper_info (method);
2960 encode_value (0, p, &p);
2961 if (method->wrapper_type == MONO_WRAPPER_DELEGATE_INVOKE)
2962 encode_value (info ? info->subtype : 0, p, &p);
2963 encode_signature (acfg, sig, p, &p);
2967 case MONO_WRAPPER_NATIVE_TO_MANAGED: {
2968 WrapperInfo *info = mono_marshal_get_wrapper_info (method);
2971 encode_method_ref (acfg, info->d.native_to_managed.method, p, &p);
2972 encode_klass_ref (acfg, info->d.native_to_managed.klass, p, &p);
2976 g_assert_not_reached ();
2978 } else if (mono_method_signature (method)->is_inflated) {
2980 * This is a generic method, find the original token which referenced it and
2982 * Obtain the token from information recorded by the JIT.
2984 ji = g_hash_table_lookup (acfg->token_info_hash, method);
2986 image_index = get_image_index (acfg, ji->image);
2987 g_assert (image_index < MAX_IMAGE_INDEX);
2990 encode_value ((MONO_AOT_METHODREF_METHODSPEC << 24), p, &p);
2991 encode_value (image_index, p, &p);
2992 encode_value (token, p, &p);
2994 MonoMethod *declaring;
2995 MonoGenericContext *context = mono_method_get_context (method);
2997 g_assert (method->is_inflated);
2998 declaring = ((MonoMethodInflated*)method)->declaring;
3001 * This might be a non-generic method of a generic instance, which
3002 * doesn't have a token since the reference is generated by the JIT
3003 * like Nullable:Box/Unbox, or by generic sharing.
3005 encode_value ((MONO_AOT_METHODREF_GINST << 24), p, &p);
3006 /* Encode the klass */
3007 encode_klass_ref (acfg, method->klass, p, &p);
3008 /* Encode the method */
3009 image_index = get_image_index (acfg, method->klass->image);
3010 g_assert (image_index < MAX_IMAGE_INDEX);
3011 g_assert (declaring->token);
3012 token = declaring->token;
3013 g_assert (mono_metadata_token_table (token) == MONO_TABLE_METHOD);
3014 encode_value (image_index, p, &p);
3015 encode_value (token, p, &p);
3016 encode_generic_context (acfg, context, p, &p);
3018 } else if (token == 0) {
3019 /* This might be a method of a constructed type like int[,].Set */
3020 /* Obtain the token from information recorded by the JIT */
3021 ji = g_hash_table_lookup (acfg->token_info_hash, method);
3023 image_index = get_image_index (acfg, ji->image);
3024 g_assert (image_index < MAX_IMAGE_INDEX);
3027 encode_value ((MONO_AOT_METHODREF_METHODSPEC << 24), p, &p);
3028 encode_value (image_index, p, &p);
3029 encode_value (token, p, &p);
3032 g_assert (method->klass->rank);
3034 /* Encode directly */
3035 encode_value ((MONO_AOT_METHODREF_ARRAY << 24), p, &p);
3036 encode_klass_ref (acfg, method->klass, p, &p);
3037 if (!strcmp (method->name, ".ctor") && mono_method_signature (method)->param_count == method->klass->rank)
3038 encode_value (0, p, &p);
3039 else if (!strcmp (method->name, ".ctor") && mono_method_signature (method)->param_count == method->klass->rank * 2)
3040 encode_value (1, p, &p);
3041 else if (!strcmp (method->name, "Get"))
3042 encode_value (2, p, &p);
3043 else if (!strcmp (method->name, "Address"))
3044 encode_value (3, p, &p);
3045 else if (!strcmp (method->name, "Set"))
3046 encode_value (4, p, &p);
3048 g_assert_not_reached ();
3051 g_assert (mono_metadata_token_table (token) == MONO_TABLE_METHOD);
3053 if (image_index >= MONO_AOT_METHODREF_MIN) {
3054 encode_value ((MONO_AOT_METHODREF_LARGE_IMAGE_INDEX << 24), p, &p);
3055 encode_value (image_index, p, &p);
3056 encode_value (mono_metadata_token_index (token), p, &p);
3058 encode_value ((image_index << 24) | mono_metadata_token_index (token), p, &p);
3065 compare_patches (gconstpointer a, gconstpointer b)
3069 i = (*(MonoJumpInfo**)a)->ip.i;
3070 j = (*(MonoJumpInfo**)b)->ip.i;
3081 static G_GNUC_UNUSED char*
3082 patch_to_string (MonoJumpInfo *patch_info)
3086 str = g_string_new ("");
3088 g_string_append_printf (str, "%s(", get_patch_name (patch_info->type));
3090 switch (patch_info->type) {
3091 case MONO_PATCH_INFO_VTABLE:
3092 mono_type_get_desc (str, &patch_info->data.klass->byval_arg, TRUE);
3097 g_string_append_printf (str, ")");
3098 return g_string_free (str, FALSE);
3104 * Return whenever PATCH_INFO refers to a direct call, and thus requires a
3107 static inline gboolean
3108 is_plt_patch (MonoJumpInfo *patch_info)
3110 switch (patch_info->type) {
3111 case MONO_PATCH_INFO_METHOD:
3112 case MONO_PATCH_INFO_INTERNAL_METHOD:
3113 case MONO_PATCH_INFO_JIT_ICALL_ADDR:
3114 case MONO_PATCH_INFO_ICALL_ADDR:
3115 case MONO_PATCH_INFO_CLASS_INIT:
3116 case MONO_PATCH_INFO_RGCTX_FETCH:
3117 case MONO_PATCH_INFO_MONITOR_ENTER:
3118 case MONO_PATCH_INFO_MONITOR_ENTER_V4:
3119 case MONO_PATCH_INFO_MONITOR_EXIT:
3120 case MONO_PATCH_INFO_LLVM_IMT_TRAMPOLINE:
3130 * Return the symbol identifying the plt entry PLT_OFFSET.
3133 get_plt_symbol (MonoAotCompile *acfg, int plt_offset, MonoJumpInfo *patch_info)
3137 * The Apple linker reorganizes object files, so it doesn't like branches to local
3138 * labels, since those have no relocations.
3140 return g_strdup_printf ("%sp_%d", acfg->llvm_label_prefix, plt_offset);
3142 return g_strdup_printf ("%sp_%d", acfg->temp_prefix, plt_offset);
3149 * Return a PLT entry which belongs to the method identified by PATCH_INFO.
3151 static MonoPltEntry*
3152 get_plt_entry (MonoAotCompile *acfg, MonoJumpInfo *patch_info)
3155 gboolean synchronized = FALSE;
3156 static int synchronized_symbol_idx;
3158 if (!is_plt_patch (patch_info))
3161 if (!acfg->patch_to_plt_entry [patch_info->type])
3162 acfg->patch_to_plt_entry [patch_info->type] = g_hash_table_new (mono_patch_info_hash, mono_patch_info_equal);
3163 res = g_hash_table_lookup (acfg->patch_to_plt_entry [patch_info->type], patch_info);
3165 if (!acfg->llvm && patch_info->type == MONO_PATCH_INFO_METHOD && (patch_info->data.method->iflags & METHOD_IMPL_ATTRIBUTE_SYNCHRONIZED)) {
3167 * Allocate a separate PLT slot for each such patch, since some plt
3168 * entries will refer to the method itself, and some will refer to the
3172 synchronized = TRUE;
3176 MonoJumpInfo *new_ji;
3178 new_ji = mono_patch_info_dup_mp (acfg->mempool, patch_info);
3180 res = mono_mempool_alloc0 (acfg->mempool, sizeof (MonoPltEntry));
3181 res->plt_offset = acfg->plt_offset;
3183 res->symbol = get_plt_symbol (acfg, res->plt_offset, patch_info);
3184 if (acfg->aot_opts.write_symbols)
3185 res->debug_sym = get_plt_entry_debug_sym (acfg, res->ji, acfg->plt_entry_debug_sym_cache);
3187 /* Avoid duplicate symbols because we don't cache */
3188 res->symbol = g_strdup_printf ("%s_%d", res->symbol, synchronized_symbol_idx);
3190 res->debug_sym = g_strdup_printf ("%s_%d", res->debug_sym, synchronized_symbol_idx);
3191 synchronized_symbol_idx ++;
3194 res->llvm_symbol = g_strdup_printf ("%s_%s_llvm", res->symbol, res->debug_sym);
3196 res->llvm_symbol = g_strdup_printf ("%s_llvm", res->symbol);
3198 g_hash_table_insert (acfg->patch_to_plt_entry [new_ji->type], new_ji, res);
3200 g_hash_table_insert (acfg->plt_offset_to_entry, GUINT_TO_POINTER (res->plt_offset), res);
3202 //g_assert (mono_patch_info_equal (patch_info, new_ji));
3203 //mono_print_ji (patch_info); printf ("\n");
3204 //g_hash_table_print_stats (acfg->patch_to_plt_entry);
3206 acfg->plt_offset ++;
3215 * Returns the offset of the GOT slot where the runtime object resulting from resolving
3216 * JI could be found if it exists, otherwise allocates a new one.
3219 get_got_offset (MonoAotCompile *acfg, gboolean llvm, MonoJumpInfo *ji)
3222 GotInfo *info = llvm ? &acfg->llvm_got_info : &acfg->got_info;
3224 got_offset = GPOINTER_TO_UINT (g_hash_table_lookup (info->patch_to_got_offset_by_type [ji->type], ji));
3226 return got_offset - 1;
3229 got_offset = acfg->llvm_got_offset;
3230 acfg->llvm_got_offset ++;
3232 got_offset = acfg->got_offset;
3233 acfg->got_offset ++;
3236 acfg->stats.got_slots ++;
3237 acfg->stats.got_slot_types [ji->type] ++;
3239 g_hash_table_insert (info->patch_to_got_offset, ji, GUINT_TO_POINTER (got_offset + 1));
3240 g_hash_table_insert (info->patch_to_got_offset_by_type [ji->type], ji, GUINT_TO_POINTER (got_offset + 1));
3241 g_ptr_array_add (info->got_patches, ji);
3246 /* Add a method to the list of methods which need to be emitted */
3248 add_method_with_index (MonoAotCompile *acfg, MonoMethod *method, int index, gboolean extra)
3251 if (!g_hash_table_lookup (acfg->method_indexes, method)) {
3252 g_ptr_array_add (acfg->methods, method);
3253 g_hash_table_insert (acfg->method_indexes, method, GUINT_TO_POINTER (index + 1));
3254 acfg->nmethods = acfg->methods->len + 1;
3257 if (method->wrapper_type || extra)
3258 g_ptr_array_add (acfg->extra_methods, method);
3262 prefer_gsharedvt_method (MonoAotCompile *acfg, MonoMethod *method)
3264 /* One instantiation with valuetypes is generated for each async method */
3265 if (method->klass->image == mono_defaults.corlib && (!strcmp (method->klass->name, "AsyncMethodBuilderCore") || !strcmp (method->klass->name, "AsyncVoidMethodBuilder")))
3272 get_method_index (MonoAotCompile *acfg, MonoMethod *method)
3274 int index = GPOINTER_TO_UINT (g_hash_table_lookup (acfg->method_indexes, method));
3282 add_method_full (MonoAotCompile *acfg, MonoMethod *method, gboolean extra, int depth)
3286 index = GPOINTER_TO_UINT (g_hash_table_lookup (acfg->method_indexes, method));
3290 index = acfg->method_index;
3291 add_method_with_index (acfg, method, index, extra);
3293 g_ptr_array_add (acfg->method_order, GUINT_TO_POINTER (index));
3295 g_hash_table_insert (acfg->method_depth, method, GUINT_TO_POINTER (depth));
3297 acfg->method_index ++;
3303 add_method (MonoAotCompile *acfg, MonoMethod *method)
3305 return add_method_full (acfg, method, FALSE, 0);
3309 add_extra_method_with_depth (MonoAotCompile *acfg, MonoMethod *method, int depth)
3311 if (mono_method_is_generic_sharable_full (method, TRUE, TRUE, FALSE))
3312 method = mini_get_shared_method (method);
3313 else if ((acfg->opts & MONO_OPT_GSHAREDVT) && prefer_gsharedvt_method (acfg, method) && mono_method_is_generic_sharable_full (method, FALSE, FALSE, TRUE))
3314 /* Use the gsharedvt version */
3317 if (acfg->aot_opts.log_generics)
3318 aot_printf (acfg, "%*sAdding method %s.\n", depth, "", mono_method_full_name (method, TRUE));
3320 add_method_full (acfg, method, TRUE, depth);
3324 add_extra_method (MonoAotCompile *acfg, MonoMethod *method)
3326 add_extra_method_with_depth (acfg, method, 0);
3330 add_jit_icall_wrapper (gpointer key, gpointer value, gpointer user_data)
3332 MonoAotCompile *acfg = user_data;
3333 MonoJitICallInfo *callinfo = value;
3334 MonoMethod *wrapper;
3340 name = g_strdup_printf ("__icall_wrapper_%s", callinfo->name);
3341 wrapper = mono_marshal_get_icall_wrapper (callinfo->sig, name, callinfo->func, check_for_pending_exc);
3344 add_method (acfg, wrapper);
3348 get_runtime_invoke_sig (MonoMethodSignature *sig)
3350 MonoMethodBuilder *mb;
3353 mb = mono_mb_new (mono_defaults.object_class, "FOO", MONO_WRAPPER_NONE);
3354 m = mono_mb_create_method (mb, sig, 16);
3355 return mono_marshal_get_runtime_invoke (m, FALSE);
3359 can_marshal_struct (MonoClass *klass)
3361 MonoClassField *field;
3362 gboolean can_marshal = TRUE;
3363 gpointer iter = NULL;
3364 MonoMarshalType *info;
3367 if ((klass->flags & TYPE_ATTRIBUTE_LAYOUT_MASK) == TYPE_ATTRIBUTE_AUTO_LAYOUT)
3370 info = mono_marshal_load_type_info (klass);
3372 /* Only allow a few field types to avoid asserts in the marshalling code */
3373 while ((field = mono_class_get_fields (klass, &iter))) {
3374 if ((field->type->attrs & FIELD_ATTRIBUTE_STATIC))
3377 switch (field->type->type) {
3382 case MONO_TYPE_BOOLEAN:
3385 case MONO_TYPE_CHAR:
3393 case MONO_TYPE_STRING:
3395 case MONO_TYPE_VALUETYPE:
3396 if (!mono_class_from_mono_type (field->type)->enumtype && !can_marshal_struct (mono_class_from_mono_type (field->type)))
3397 can_marshal = FALSE;
3399 case MONO_TYPE_SZARRAY: {
3400 gboolean has_mspec = FALSE;
3403 for (i = 0; i < info->num_fields; ++i) {
3404 if (info->fields [i].field == field && info->fields [i].mspec)
3409 can_marshal = FALSE;
3413 can_marshal = FALSE;
3419 /* Its hard to compute whenever these can be marshalled or not */
3420 if (!strcmp (klass->name_space, "System.Net.NetworkInformation.MacOsStructs") && strcmp (klass->name, "sockaddr_dl"))
3427 create_gsharedvt_inst (MonoAotCompile *acfg, MonoMethod *method, MonoGenericContext *ctx)
3429 /* Create a vtype instantiation */
3430 MonoGenericContext shared_context;
3432 MonoGenericInst *inst;
3433 MonoGenericContainer *container;
3434 MonoClass **constraints;
3437 memset (ctx, 0, sizeof (MonoGenericContext));
3439 if (method->klass->generic_container) {
3440 shared_context = method->klass->generic_container->context;
3441 inst = shared_context.class_inst;
3443 args = g_new0 (MonoType*, inst->type_argc);
3444 for (i = 0; i < inst->type_argc; ++i) {
3445 args [i] = &mono_defaults.int_class->byval_arg;
3447 ctx->class_inst = mono_metadata_get_generic_inst (inst->type_argc, args);
3449 if (method->is_generic) {
3450 container = mono_method_get_generic_container (method);
3451 shared_context = container->context;
3452 inst = shared_context.method_inst;
3454 args = g_new0 (MonoType*, inst->type_argc);
3455 for (i = 0; i < container->type_argc; ++i) {
3456 MonoGenericParamInfo *info = &container->type_params [i].info;
3457 gboolean ref_only = FALSE;
3459 if (info && info->constraints) {
3460 constraints = info->constraints;
3462 while (*constraints) {
3463 MonoClass *cklass = *constraints;
3464 if (!(cklass == mono_defaults.object_class || (cklass->image == mono_defaults.corlib && !strcmp (cklass->name, "ValueType"))))
3465 /* Inflaring the method with our vtype would not be valid */
3472 args [i] = &mono_defaults.object_class->byval_arg;
3474 args [i] = &mono_defaults.int_class->byval_arg;
3476 ctx->method_inst = mono_metadata_get_generic_inst (inst->type_argc, args);
3481 add_wrappers (MonoAotCompile *acfg)
3483 MonoMethod *method, *m;
3485 MonoMethodSignature *sig, *csig;
3489 * FIXME: Instead of AOTing all the wrappers, it might be better to redesign them
3490 * so there is only one wrapper of a given type, or inlining their contents into their
3493 for (i = 0; i < acfg->image->tables [MONO_TABLE_METHOD].rows; ++i) {
3496 guint32 token = MONO_TOKEN_METHOD_DEF | (i + 1);
3497 gboolean skip = FALSE;
3499 method = mono_get_method_checked (acfg->image, token, NULL, NULL, &error);
3500 report_loader_error (acfg, &error, "Failed to load method token 0x%x due to %s\n", i, mono_error_get_message (&error));
3502 if ((method->flags & METHOD_ATTRIBUTE_PINVOKE_IMPL) ||
3503 (method->iflags & METHOD_IMPL_ATTRIBUTE_RUNTIME) ||
3504 (method->flags & METHOD_ATTRIBUTE_ABSTRACT))
3507 /* Skip methods which can not be handled by get_runtime_invoke () */
3508 sig = mono_method_signature (method);
3511 if ((sig->ret->type == MONO_TYPE_PTR) ||
3512 (sig->ret->type == MONO_TYPE_TYPEDBYREF))
3514 if (mono_class_is_open_constructed_type (sig->ret))
3517 for (j = 0; j < sig->param_count; j++) {
3518 if (sig->params [j]->type == MONO_TYPE_TYPEDBYREF)
3520 if (mono_class_is_open_constructed_type (sig->params [j]))
3524 #ifdef MONO_ARCH_DYN_CALL_SUPPORTED
3525 if (!mono_class_is_contextbound (method->klass)) {
3526 MonoDynCallInfo *info = mono_arch_dyn_call_prepare (sig);
3527 gboolean has_nullable = FALSE;
3529 for (j = 0; j < sig->param_count; j++) {
3530 if (sig->params [j]->type == MONO_TYPE_GENERICINST && mono_class_is_nullable (mono_class_from_mono_type (sig->params [j])))
3531 has_nullable = TRUE;
3534 if (info && !has_nullable) {
3535 /* Supported by the dynamic runtime-invoke wrapper */
3539 mono_arch_dyn_call_free (info);
3544 //printf ("%s\n", mono_method_full_name (method, TRUE));
3545 add_method (acfg, mono_marshal_get_runtime_invoke (method, FALSE));
3549 if (strcmp (acfg->image->assembly->aname.name, "mscorlib") == 0) {
3552 /* Runtime invoke wrappers */
3554 /* void runtime-invoke () [.cctor] */
3555 csig = mono_metadata_signature_alloc (mono_defaults.corlib, 0);
3556 csig->ret = &mono_defaults.void_class->byval_arg;
3557 add_method (acfg, get_runtime_invoke_sig (csig));
3559 /* void runtime-invoke () [Finalize] */
3560 csig = mono_metadata_signature_alloc (mono_defaults.corlib, 0);
3562 csig->ret = &mono_defaults.void_class->byval_arg;
3563 add_method (acfg, get_runtime_invoke_sig (csig));
3565 /* void runtime-invoke (string) [exception ctor] */
3566 csig = mono_metadata_signature_alloc (mono_defaults.corlib, 1);
3568 csig->ret = &mono_defaults.void_class->byval_arg;
3569 csig->params [0] = &mono_defaults.string_class->byval_arg;
3570 add_method (acfg, get_runtime_invoke_sig (csig));
3572 /* void runtime-invoke (string, string) [exception ctor] */
3573 csig = mono_metadata_signature_alloc (mono_defaults.corlib, 2);
3575 csig->ret = &mono_defaults.void_class->byval_arg;
3576 csig->params [0] = &mono_defaults.string_class->byval_arg;
3577 csig->params [1] = &mono_defaults.string_class->byval_arg;
3578 add_method (acfg, get_runtime_invoke_sig (csig));
3580 /* string runtime-invoke () [Exception.ToString ()] */
3581 csig = mono_metadata_signature_alloc (mono_defaults.corlib, 0);
3583 csig->ret = &mono_defaults.string_class->byval_arg;
3584 add_method (acfg, get_runtime_invoke_sig (csig));
3586 /* void runtime-invoke (string, Exception) [exception ctor] */
3587 csig = mono_metadata_signature_alloc (mono_defaults.corlib, 2);
3589 csig->ret = &mono_defaults.void_class->byval_arg;
3590 csig->params [0] = &mono_defaults.string_class->byval_arg;
3591 csig->params [1] = &mono_defaults.exception_class->byval_arg;
3592 add_method (acfg, get_runtime_invoke_sig (csig));
3594 /* Assembly runtime-invoke (string, bool) [DoAssemblyResolve] */
3595 csig = mono_metadata_signature_alloc (mono_defaults.corlib, 2);
3597 csig->ret = &(mono_class_from_name (
3598 mono_defaults.corlib, "System.Reflection", "Assembly"))->byval_arg;
3599 csig->params [0] = &mono_defaults.string_class->byval_arg;
3600 csig->params [1] = &mono_defaults.boolean_class->byval_arg;
3601 add_method (acfg, get_runtime_invoke_sig (csig));
3603 /* runtime-invoke used by finalizers */
3604 add_method (acfg, mono_marshal_get_runtime_invoke (mono_class_get_method_from_name_flags (mono_defaults.object_class, "Finalize", 0, 0), TRUE));
3606 /* This is used by mono_runtime_capture_context () */
3607 method = mono_get_context_capture_method ();
3609 add_method (acfg, mono_marshal_get_runtime_invoke (method, FALSE));
3611 #ifdef MONO_ARCH_DYN_CALL_SUPPORTED
3612 add_method (acfg, mono_marshal_get_runtime_invoke_dynamic ());
3616 add_method (acfg, mono_marshal_get_stelemref ());
3618 if (MONO_ARCH_HAVE_TLS_GET) {
3619 /* Managed Allocators */
3620 nallocators = mono_gc_get_managed_allocator_types ();
3621 for (i = 0; i < nallocators; ++i) {
3622 m = mono_gc_get_managed_allocator_by_type (i, TRUE);
3624 add_method (acfg, m);
3626 for (i = 0; i < nallocators; ++i) {
3627 m = mono_gc_get_managed_allocator_by_type (i, FALSE);
3629 add_method (acfg, m);
3633 /* write barriers */
3634 if (mono_gc_is_moving ()) {
3635 add_method (acfg, mono_gc_get_specific_write_barrier (FALSE));
3636 add_method (acfg, mono_gc_get_specific_write_barrier (TRUE));
3639 /* Stelemref wrappers */
3641 MonoMethod **wrappers;
3644 wrappers = mono_marshal_get_virtual_stelemref_wrappers (&nwrappers);
3645 for (i = 0; i < nwrappers; ++i)
3646 add_method (acfg, wrappers [i]);
3650 /* castclass_with_check wrapper */
3651 add_method (acfg, mono_marshal_get_castclass_with_cache ());
3652 /* isinst_with_check wrapper */
3653 add_method (acfg, mono_marshal_get_isinst_with_cache ());
3655 /* JIT icall wrappers */
3656 /* FIXME: locking - this is "safe" as full-AOT threads don't mutate the icall hash*/
3657 g_hash_table_foreach (mono_get_jit_icall_info (), add_jit_icall_wrapper, acfg);
3661 * remoting-invoke-with-check wrappers are very frequent, so avoid emitting them,
3662 * we use the original method instead at runtime.
3663 * Since full-aot doesn't support remoting, this is not a problem.
3666 /* remoting-invoke wrappers */
3667 for (i = 0; i < acfg->image->tables [MONO_TABLE_METHOD].rows; ++i) {
3668 MonoMethodSignature *sig;
3670 token = MONO_TOKEN_METHOD_DEF | (i + 1);
3671 method = mono_get_method (acfg->image, token, NULL);
3673 sig = mono_method_signature (method);
3675 if (sig->hasthis && (method->klass->marshalbyref || method->klass == mono_defaults.object_class)) {
3676 m = mono_marshal_get_remoting_invoke_with_check (method);
3678 add_method (acfg, m);
3683 /* delegate-invoke wrappers */
3684 for (i = 0; i < acfg->image->tables [MONO_TABLE_TYPEDEF].rows; ++i) {
3687 MonoCustomAttrInfo *cattr;
3689 token = MONO_TOKEN_TYPE_DEF | (i + 1);
3690 klass = mono_class_get_checked (acfg->image, token, &error);
3693 mono_error_cleanup (&error);
3697 if (!klass->delegate || klass == mono_defaults.delegate_class || klass == mono_defaults.multicastdelegate_class)
3700 if (!klass->generic_container) {
3701 method = mono_get_delegate_invoke (klass);
3703 m = mono_marshal_get_delegate_invoke (method, NULL);
3705 add_method (acfg, m);
3707 method = mono_class_get_method_from_name_flags (klass, "BeginInvoke", -1, 0);
3709 add_method (acfg, mono_marshal_get_delegate_begin_invoke (method));
3711 method = mono_class_get_method_from_name_flags (klass, "EndInvoke", -1, 0);
3713 add_method (acfg, mono_marshal_get_delegate_end_invoke (method));
3715 cattr = mono_custom_attrs_from_class (klass);
3720 for (j = 0; j < cattr->num_attrs; ++j)
3721 if (cattr->attrs [j].ctor && (!strcmp (cattr->attrs [j].ctor->klass->name, "MonoNativeFunctionWrapperAttribute") || !strcmp (cattr->attrs [j].ctor->klass->name, "UnmanagedFunctionPointerAttribute")))
3723 if (j < cattr->num_attrs) {
3725 MonoMethod *wrapper;
3726 MonoMethod *del_invoke;
3728 /* Add wrappers needed by mono_ftnptr_to_delegate () */
3729 invoke = mono_get_delegate_invoke (klass);
3730 wrapper = mono_marshal_get_native_func_wrapper_aot (klass);
3731 del_invoke = mono_marshal_get_delegate_invoke_internal (invoke, FALSE, TRUE, wrapper);
3732 add_method (acfg, wrapper);
3733 add_method (acfg, del_invoke);
3736 } else if ((acfg->opts & MONO_OPT_GSHAREDVT) && klass->generic_container) {
3738 MonoGenericContext ctx;
3739 MonoMethod *inst, *gshared;
3742 * Emit gsharedvt versions of the generic delegate-invoke wrappers
3745 method = mono_get_delegate_invoke (klass);
3746 create_gsharedvt_inst (acfg, method, &ctx);
3748 inst = mono_class_inflate_generic_method_checked (method, &ctx, &error);
3749 g_assert (mono_error_ok (&error)); /* FIXME don't swallow the error */
3751 m = mono_marshal_get_delegate_invoke (inst, NULL);
3752 g_assert (m->is_inflated);
3754 gshared = mini_get_shared_method_full (m, FALSE, TRUE);
3755 add_extra_method (acfg, gshared);
3758 method = mono_get_delegate_begin_invoke (klass);
3759 create_gsharedvt_inst (acfg, method, &ctx);
3761 inst = mono_class_inflate_generic_method_checked (method, &ctx, &error);
3762 g_assert (mono_error_ok (&error)); /* FIXME don't swallow the error */
3764 m = mono_marshal_get_delegate_begin_invoke (inst);
3765 g_assert (m->is_inflated);
3767 gshared = mini_get_shared_method_full (m, FALSE, TRUE);
3768 add_extra_method (acfg, gshared);
3771 method = mono_get_delegate_end_invoke (klass);
3772 create_gsharedvt_inst (acfg, method, &ctx);
3774 inst = mono_class_inflate_generic_method_checked (method, &ctx, &error);
3775 g_assert (mono_error_ok (&error)); /* FIXME don't swallow the error */
3777 m = mono_marshal_get_delegate_end_invoke (inst);
3778 g_assert (m->is_inflated);
3780 gshared = mini_get_shared_method_full (m, FALSE, TRUE);
3781 add_extra_method (acfg, gshared);
3786 /* array access wrappers */
3787 for (i = 0; i < acfg->image->tables [MONO_TABLE_TYPESPEC].rows; ++i) {
3791 token = MONO_TOKEN_TYPE_SPEC | (i + 1);
3792 klass = mono_class_get_checked (acfg->image, token, &error);
3795 mono_error_cleanup (&error);
3799 if (klass->rank && MONO_TYPE_IS_PRIMITIVE (&klass->element_class->byval_arg)) {
3800 MonoMethod *m, *wrapper;
3802 /* Add runtime-invoke wrappers too */
3804 m = mono_class_get_method_from_name (klass, "Get", -1);
3806 wrapper = mono_marshal_get_array_accessor_wrapper (m);
3807 add_extra_method (acfg, wrapper);
3808 add_extra_method (acfg, mono_marshal_get_runtime_invoke (wrapper, FALSE));
3810 m = mono_class_get_method_from_name (klass, "Set", -1);
3812 wrapper = mono_marshal_get_array_accessor_wrapper (m);
3813 add_extra_method (acfg, wrapper);
3814 add_extra_method (acfg, mono_marshal_get_runtime_invoke (wrapper, FALSE));
3818 /* Synchronized wrappers */
3819 for (i = 0; i < acfg->image->tables [MONO_TABLE_METHOD].rows; ++i) {
3821 token = MONO_TOKEN_METHOD_DEF | (i + 1);
3822 method = mono_get_method_checked (acfg->image, token, NULL, NULL, &error);
3823 report_loader_error (acfg, &error, "Failed to load method token 0x%x due to %s\n", i, mono_error_get_message (&error));
3825 if (method->iflags & METHOD_IMPL_ATTRIBUTE_SYNCHRONIZED) {
3826 if (method->is_generic) {
3828 } else if ((acfg->opts & MONO_OPT_GSHAREDVT) && method->klass->generic_container) {
3830 MonoGenericContext ctx;
3831 MonoMethod *inst, *gshared, *m;
3834 * Create a generic wrapper for a generic instance, and AOT that.
3836 create_gsharedvt_inst (acfg, method, &ctx);
3837 inst = mono_class_inflate_generic_method_checked (method, &ctx, &error);
3838 g_assert (mono_error_ok (&error)); /* FIXME don't swallow the error */
3839 m = mono_marshal_get_synchronized_wrapper (inst);
3840 g_assert (m->is_inflated);
3841 gshared = mini_get_shared_method_full (m, FALSE, TRUE);
3842 add_method (acfg, gshared);
3844 add_method (acfg, mono_marshal_get_synchronized_wrapper (method));
3849 /* pinvoke wrappers */
3850 for (i = 0; i < acfg->image->tables [MONO_TABLE_METHOD].rows; ++i) {
3853 guint32 token = MONO_TOKEN_METHOD_DEF | (i + 1);
3855 method = mono_get_method_checked (acfg->image, token, NULL, NULL, &error);
3856 report_loader_error (acfg, &error, "Failed to load method token 0x%x due to %s\n", i, mono_error_get_message (&error));
3858 if ((method->flags & METHOD_ATTRIBUTE_PINVOKE_IMPL) ||
3859 (method->iflags & METHOD_IMPL_ATTRIBUTE_INTERNAL_CALL)) {
3860 add_method (acfg, mono_marshal_get_native_wrapper (method, TRUE, TRUE));
3864 /* native-to-managed wrappers */
3865 for (i = 0; i < acfg->image->tables [MONO_TABLE_METHOD].rows; ++i) {
3868 guint32 token = MONO_TOKEN_METHOD_DEF | (i + 1);
3869 MonoCustomAttrInfo *cattr;
3872 method = mono_get_method_checked (acfg->image, token, NULL, NULL, &error);
3873 report_loader_error (acfg, &error, "Failed to load method token 0x%x due to %s\n", i, mono_error_get_message (&error));
3876 * Only generate native-to-managed wrappers for methods which have an
3877 * attribute named MonoPInvokeCallbackAttribute. We search for the attribute by
3878 * name to avoid defining a new assembly to contain it.
3880 cattr = mono_custom_attrs_from_method (method);
3883 for (j = 0; j < cattr->num_attrs; ++j)
3884 if (cattr->attrs [j].ctor && !strcmp (cattr->attrs [j].ctor->klass->name, "MonoPInvokeCallbackAttribute"))
3886 if (j < cattr->num_attrs) {
3887 MonoCustomAttrEntry *e = &cattr->attrs [j];
3888 MonoMethodSignature *sig = mono_method_signature (e->ctor);
3889 const char *p = (const char*)e->data;
3891 int slen, num_named, named_type;
3895 char *export_name = NULL;
3896 MonoMethod *wrapper;
3898 /* this cannot be enforced by the C# compiler so we must give the user some warning before aborting */
3899 if (!(method->flags & METHOD_ATTRIBUTE_STATIC)) {
3900 g_warning ("AOT restriction: Method '%s' must be static since it is decorated with [MonoPInvokeCallback]. See http://ios.xamarin.com/Documentation/Limitations#Reverse_Callbacks",
3901 mono_method_full_name (method, TRUE));
3905 g_assert (sig->param_count == 1);
3906 g_assert (sig->params [0]->type == MONO_TYPE_CLASS && !strcmp (mono_class_from_mono_type (sig->params [0])->name, "Type"));
3909 * Decode the cattr manually since we can't create objects
3910 * during aot compilation.
3916 /* From load_cattr_value () in reflection.c */
3917 slen = mono_metadata_decode_value (p, &p);
3918 n = g_memdup (p, slen + 1);
3920 t = mono_reflection_type_from_name (n, acfg->image);
3924 klass = mono_class_from_mono_type (t);
3925 g_assert (klass->parent == mono_defaults.multicastdelegate_class);
3929 num_named = read16 (p);
3932 g_assert (num_named < 2);
3933 if (num_named == 1) {
3937 /* parse ExportSymbol attribute */
3939 named_type = *named;
3941 /* data_type = *named; */
3944 name_len = mono_metadata_decode_blob_size (named, &named);
3945 name = g_malloc (name_len + 1);
3946 memcpy (name, named, name_len);
3947 name [name_len] = 0;
3950 g_assert (named_type == 0x54);
3951 g_assert (!strcmp (name, "ExportSymbol"));
3953 /* load_cattr_value (), string case */
3954 g_assert (*named != (char)0xff);
3955 slen = mono_metadata_decode_value (named, &named);
3956 export_name = g_malloc (slen + 1);
3957 memcpy (export_name, named, slen);
3958 export_name [slen] = 0;
3962 wrapper = mono_marshal_get_managed_wrapper (method, klass, 0);
3963 add_method (acfg, wrapper);
3965 g_hash_table_insert (acfg->export_names, wrapper, export_name);
3969 if ((method->flags & METHOD_ATTRIBUTE_PINVOKE_IMPL) ||
3970 (method->iflags & METHOD_IMPL_ATTRIBUTE_INTERNAL_CALL)) {
3971 add_method (acfg, mono_marshal_get_native_wrapper (method, TRUE, TRUE));
3975 /* StructureToPtr/PtrToStructure wrappers */
3976 for (i = 0; i < acfg->image->tables [MONO_TABLE_TYPEDEF].rows; ++i) {
3980 token = MONO_TOKEN_TYPE_DEF | (i + 1);
3981 klass = mono_class_get_checked (acfg->image, token, &error);
3984 mono_error_cleanup (&error);
3988 if (klass->valuetype && !klass->generic_container && can_marshal_struct (klass) &&
3989 !(klass->nested_in && strstr (klass->nested_in->name, "<PrivateImplementationDetails>") == klass->nested_in->name)) {
3990 add_method (acfg, mono_marshal_get_struct_to_ptr (klass));
3991 add_method (acfg, mono_marshal_get_ptr_to_struct (klass));
3997 has_type_vars (MonoClass *klass)
3999 if ((klass->byval_arg.type == MONO_TYPE_VAR) || (klass->byval_arg.type == MONO_TYPE_MVAR))
4002 return has_type_vars (klass->element_class);
4003 if (klass->generic_class) {
4004 MonoGenericContext *context = &klass->generic_class->context;
4005 if (context->class_inst) {
4008 for (i = 0; i < context->class_inst->type_argc; ++i)
4009 if (has_type_vars (mono_class_from_mono_type (context->class_inst->type_argv [i])))
4013 if (klass->generic_container)
4019 is_vt_inst (MonoGenericInst *inst)
4023 for (i = 0; i < inst->type_argc; ++i) {
4024 MonoType *t = inst->type_argv [i];
4025 if (MONO_TYPE_ISSTRUCT (t) || t->type == MONO_TYPE_VALUETYPE)
4032 method_has_type_vars (MonoMethod *method)
4034 if (has_type_vars (method->klass))
4037 if (method->is_inflated) {
4038 MonoGenericContext *context = mono_method_get_context (method);
4039 if (context->method_inst) {
4042 for (i = 0; i < context->method_inst->type_argc; ++i)
4043 if (has_type_vars (mono_class_from_mono_type (context->method_inst->type_argv [i])))
4051 gboolean mono_aot_mode_is_full (MonoAotOptions *opts)
4053 return opts->mode == MONO_AOT_MODE_FULL;
4056 static void add_generic_class_with_depth (MonoAotCompile *acfg, MonoClass *klass, int depth, const char *ref);
4059 add_generic_class (MonoAotCompile *acfg, MonoClass *klass, gboolean force, const char *ref)
4061 /* This might lead to a huge code blowup so only do it if neccesary */
4062 if (!mono_aot_mode_is_full (&acfg->aot_opts) && !force)
4065 add_generic_class_with_depth (acfg, klass, 0, ref);
4069 check_type_depth (MonoType *t, int depth)
4077 case MONO_TYPE_GENERICINST: {
4078 MonoGenericClass *gklass = t->data.generic_class;
4079 MonoGenericInst *ginst = gklass->context.class_inst;
4082 for (i = 0; i < ginst->type_argc; ++i) {
4083 if (check_type_depth (ginst->type_argv [i], depth + 1))
4097 add_types_from_method_header (MonoAotCompile *acfg, MonoMethod *method);
4100 * add_generic_class:
4102 * Add all methods of a generic class.
4105 add_generic_class_with_depth (MonoAotCompile *acfg, MonoClass *klass, int depth, const char *ref)
4108 MonoClassField *field;
4110 gboolean use_gsharedvt = FALSE;
4112 if (!acfg->ginst_hash)
4113 acfg->ginst_hash = g_hash_table_new (NULL, NULL);
4115 mono_class_init (klass);
4117 if (klass->generic_class && klass->generic_class->context.class_inst->is_open)
4120 if (has_type_vars (klass))
4123 if (!klass->generic_class && !klass->rank)
4126 if (klass->exception_type)
4129 if (!acfg->ginst_hash)
4130 acfg->ginst_hash = g_hash_table_new (NULL, NULL);
4132 if (g_hash_table_lookup (acfg->ginst_hash, klass))
4135 if (check_type_depth (&klass->byval_arg, 0))
4138 if (acfg->aot_opts.log_generics)
4139 aot_printf (acfg, "%*sAdding generic instance %s [%s].\n", depth, "", mono_type_full_name (&klass->byval_arg), ref);
4141 g_hash_table_insert (acfg->ginst_hash, klass, klass);
4144 * Use gsharedvt for generic collections with vtype arguments to avoid code blowup.
4145 * Enable this only for some classes since gsharedvt might not support all methods.
4147 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) &&
4148 (!strcmp (klass->name, "Dictionary`2") || !strcmp (klass->name, "List`1") || !strcmp (klass->name, "ReadOnlyCollection`1")))
4149 use_gsharedvt = TRUE;
4152 while ((method = mono_class_get_methods (klass, &iter))) {
4153 if ((acfg->opts & MONO_OPT_GSHAREDVT) && method->is_inflated && mono_method_get_context (method)->method_inst) {
4155 * This is partial sharing, and we can't handle it yet
4160 if (mono_method_is_generic_sharable_full (method, FALSE, FALSE, use_gsharedvt)) {
4162 add_types_from_method_header (acfg, method);
4166 if (method->is_generic)
4171 * FIXME: Instances which are referenced by these methods are not added,
4172 * for example Array.Resize<int> for List<int>.Add ().
4174 add_extra_method_with_depth (acfg, method, depth + 1);
4178 while ((field = mono_class_get_fields (klass, &iter))) {
4179 if (field->type->type == MONO_TYPE_GENERICINST)
4180 add_generic_class_with_depth (acfg, mono_class_from_mono_type (field->type), depth + 1, "field");
4183 if (klass->delegate) {
4184 method = mono_get_delegate_invoke (klass);
4186 method = mono_marshal_get_delegate_invoke (method, NULL);
4188 if (acfg->aot_opts.log_generics)
4189 aot_printf (acfg, "%*sAdding method %s.\n", depth, "", mono_method_full_name (method, TRUE));
4191 add_method (acfg, method);
4194 /* Add superclasses */
4196 add_generic_class_with_depth (acfg, klass->parent, depth, "parent");
4199 * For ICollection<T>, add instances of the helper methods
4200 * in Array, since a T[] could be cast to ICollection<T>.
4202 if (klass->image == mono_defaults.corlib && !strcmp (klass->name_space, "System.Collections.Generic") &&
4203 (!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"))) {
4204 MonoClass *tclass = mono_class_from_mono_type (klass->generic_class->context.class_inst->type_argv [0]);
4205 MonoClass *array_class = mono_bounded_array_class_get (tclass, 1, FALSE);
4209 if (!strcmp (klass->name, "IEnumerator`1"))
4210 name_prefix = g_strdup_printf ("%s.%s", klass->name_space, "IEnumerable`1");
4212 name_prefix = g_strdup_printf ("%s.%s", klass->name_space, klass->name);
4214 /* Add the T[]/InternalEnumerator class */
4215 if (!strcmp (klass->name, "IEnumerable`1") || !strcmp (klass->name, "IEnumerator`1")) {
4219 while ((nclass = mono_class_get_nested_types (array_class->parent, &iter))) {
4220 if (!strcmp (nclass->name, "InternalEnumerator`1"))
4224 nclass = mono_class_inflate_generic_class (nclass, mono_generic_class_get_context (klass->generic_class));
4225 add_generic_class (acfg, nclass, FALSE, "ICollection<T>");
4229 while ((method = mono_class_get_methods (array_class, &iter))) {
4230 if (strstr (method->name, name_prefix)) {
4231 MonoMethod *m = mono_aot_get_array_helper_from_wrapper (method);
4233 add_extra_method_with_depth (acfg, m, depth);
4237 g_free (name_prefix);
4240 /* Add an instance of GenericComparer<T> which is created dynamically by Comparer<T> */
4241 if (klass->image == mono_defaults.corlib && !strcmp (klass->name_space, "System.Collections.Generic") && !strcmp (klass->name, "Comparer`1")) {
4242 MonoClass *tclass = mono_class_from_mono_type (klass->generic_class->context.class_inst->type_argv [0]);
4243 MonoClass *icomparable, *gcomparer;
4244 MonoGenericContext ctx;
4245 MonoType *args [16];
4247 memset (&ctx, 0, sizeof (ctx));
4249 icomparable = mono_class_from_name (mono_defaults.corlib, "System", "IComparable`1");
4250 g_assert (icomparable);
4251 args [0] = &tclass->byval_arg;
4252 ctx.class_inst = mono_metadata_get_generic_inst (1, args);
4254 if (mono_class_is_assignable_from (mono_class_inflate_generic_class (icomparable, &ctx), tclass)) {
4255 gcomparer = mono_class_from_name (mono_defaults.corlib, "System.Collections.Generic", "GenericComparer`1");
4256 g_assert (gcomparer);
4257 add_generic_class (acfg, mono_class_inflate_generic_class (gcomparer, &ctx), FALSE, "Comparer<T>");
4261 /* Add an instance of GenericEqualityComparer<T> which is created dynamically by EqualityComparer<T> */
4262 if (klass->image == mono_defaults.corlib && !strcmp (klass->name_space, "System.Collections.Generic") && !strcmp (klass->name, "EqualityComparer`1")) {
4263 MonoClass *tclass = mono_class_from_mono_type (klass->generic_class->context.class_inst->type_argv [0]);
4264 MonoClass *iface, *gcomparer;
4265 MonoGenericContext ctx;
4266 MonoType *args [16];
4268 memset (&ctx, 0, sizeof (ctx));
4270 iface = mono_class_from_name (mono_defaults.corlib, "System", "IEquatable`1");
4272 args [0] = &tclass->byval_arg;
4273 ctx.class_inst = mono_metadata_get_generic_inst (1, args);
4275 if (mono_class_is_assignable_from (mono_class_inflate_generic_class (iface, &ctx), tclass)) {
4276 gcomparer = mono_class_from_name (mono_defaults.corlib, "System.Collections.Generic", "GenericEqualityComparer`1");
4277 g_assert (gcomparer);
4278 add_generic_class (acfg, mono_class_inflate_generic_class (gcomparer, &ctx), FALSE, "EqualityComparer<T>");
4282 /* Add an instance of EnumComparer<T> which is created dynamically by EqualityComparer<T> for enums */
4283 if (klass->image == mono_defaults.corlib && !strcmp (klass->name_space, "System.Collections.Generic") && !strcmp (klass->name, "EqualityComparer`1")) {
4284 MonoClass *enum_comparer;
4285 MonoClass *tclass = mono_class_from_mono_type (klass->generic_class->context.class_inst->type_argv [0]);
4286 MonoGenericContext ctx;
4287 MonoType *args [16];
4289 if (mono_class_is_enum (tclass)) {
4290 memset (&ctx, 0, sizeof (ctx));
4291 args [0] = &tclass->byval_arg;
4292 ctx.class_inst = mono_metadata_get_generic_inst (1, args);
4294 enum_comparer = mono_class_from_name (mono_defaults.corlib, "System.Collections.Generic", "EnumEqualityComparer`1");
4295 g_assert (enum_comparer);
4296 add_generic_class (acfg, mono_class_inflate_generic_class (enum_comparer, &ctx), FALSE, "EqualityComparer<T>");
4300 /* Add an instance of ObjectComparer<T> which is created dynamically by Comparer<T> for enums */
4301 if (klass->image == mono_defaults.corlib && !strcmp (klass->name_space, "System.Collections.Generic") && !strcmp (klass->name, "Comparer`1")) {
4302 MonoClass *comparer;
4303 MonoClass *tclass = mono_class_from_mono_type (klass->generic_class->context.class_inst->type_argv [0]);
4304 MonoGenericContext ctx;
4305 MonoType *args [16];
4307 if (mono_class_is_enum (tclass)) {
4308 memset (&ctx, 0, sizeof (ctx));
4309 args [0] = &tclass->byval_arg;
4310 ctx.class_inst = mono_metadata_get_generic_inst (1, args);
4312 comparer = mono_class_from_name (mono_defaults.corlib, "System.Collections.Generic", "ObjectComparer`1");
4313 g_assert (comparer);
4314 add_generic_class (acfg, mono_class_inflate_generic_class (comparer, &ctx), FALSE, "Comparer<T>");
4320 add_instances_of (MonoAotCompile *acfg, MonoClass *klass, MonoType **insts, int ninsts, gboolean force)
4323 MonoGenericContext ctx;
4324 MonoType *args [16];
4326 if (acfg->aot_opts.no_instances)
4329 memset (&ctx, 0, sizeof (ctx));
4331 for (i = 0; i < ninsts; ++i) {
4332 args [0] = insts [i];
4333 ctx.class_inst = mono_metadata_get_generic_inst (1, args);
4334 add_generic_class (acfg, mono_class_inflate_generic_class (klass, &ctx), force, "");
4339 add_types_from_method_header (MonoAotCompile *acfg, MonoMethod *method)
4341 MonoMethodHeader *header;
4342 MonoMethodSignature *sig;
4345 depth = GPOINTER_TO_UINT (g_hash_table_lookup (acfg->method_depth, method));
4347 sig = mono_method_signature (method);
4350 for (j = 0; j < sig->param_count; ++j)
4351 if (sig->params [j]->type == MONO_TYPE_GENERICINST)
4352 add_generic_class_with_depth (acfg, mono_class_from_mono_type (sig->params [j]), depth + 1, "arg");
4355 header = mono_method_get_header (method);
4358 for (j = 0; j < header->num_locals; ++j)
4359 if (header->locals [j]->type == MONO_TYPE_GENERICINST)
4360 add_generic_class_with_depth (acfg, mono_class_from_mono_type (header->locals [j]), depth + 1, "local");
4362 mono_loader_clear_error ();
4367 * add_generic_instances:
4369 * Add instances referenced by the METHODSPEC/TYPESPEC table.
4372 add_generic_instances (MonoAotCompile *acfg)
4377 MonoGenericContext *context;
4379 if (acfg->aot_opts.no_instances)
4382 for (i = 0; i < acfg->image->tables [MONO_TABLE_METHODSPEC].rows; ++i) {
4384 token = MONO_TOKEN_METHOD_SPEC | (i + 1);
4385 method = mono_get_method_checked (acfg->image, token, NULL, NULL, &error);
4388 aot_printerrf (acfg, "Failed to load methodspec 0x%x due to %s.\n", token, mono_error_get_message (&error));
4389 aot_printerrf (acfg, "Run with MONO_LOG_LEVEL=debug for more information.\n");
4390 mono_error_cleanup (&error);
4394 if (method->klass->image != acfg->image)
4397 context = mono_method_get_context (method);
4399 if (context && ((context->class_inst && context->class_inst->is_open)))
4403 * For open methods, create an instantiation which can be passed to the JIT.
4404 * FIXME: Handle class_inst as well.
4406 if (context && context->method_inst && context->method_inst->is_open) {
4408 MonoGenericContext shared_context;
4409 MonoGenericInst *inst;
4410 MonoType **type_argv;
4412 MonoMethod *declaring_method;
4413 gboolean supported = TRUE;
4415 /* Check that the context doesn't contain open constructed types */
4416 if (context->class_inst) {
4417 inst = context->class_inst;
4418 for (i = 0; i < inst->type_argc; ++i) {
4419 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)
4421 if (mono_class_is_open_constructed_type (inst->type_argv [i]))
4425 if (context->method_inst) {
4426 inst = context->method_inst;
4427 for (i = 0; i < inst->type_argc; ++i) {
4428 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)
4430 if (mono_class_is_open_constructed_type (inst->type_argv [i]))
4438 memset (&shared_context, 0, sizeof (MonoGenericContext));
4440 inst = context->class_inst;
4442 type_argv = g_new0 (MonoType*, inst->type_argc);
4443 for (i = 0; i < inst->type_argc; ++i) {
4444 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)
4445 type_argv [i] = &mono_defaults.object_class->byval_arg;
4447 type_argv [i] = inst->type_argv [i];
4450 shared_context.class_inst = mono_metadata_get_generic_inst (inst->type_argc, type_argv);
4454 inst = context->method_inst;
4456 type_argv = g_new0 (MonoType*, inst->type_argc);
4457 for (i = 0; i < inst->type_argc; ++i) {
4458 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)
4459 type_argv [i] = &mono_defaults.object_class->byval_arg;
4461 type_argv [i] = inst->type_argv [i];
4464 shared_context.method_inst = mono_metadata_get_generic_inst (inst->type_argc, type_argv);
4468 if (method->is_generic || method->klass->generic_container)
4469 declaring_method = method;
4471 declaring_method = mono_method_get_declaring_generic_method (method);
4473 method = mono_class_inflate_generic_method_checked (declaring_method, &shared_context, &error);
4474 g_assert (mono_error_ok (&error)); /* FIXME don't swallow the error */
4478 * If the method is fully sharable, it was already added in place of its
4479 * generic definition.
4481 if (mono_method_is_generic_sharable_full (method, FALSE, FALSE, FALSE))
4485 * FIXME: Partially shared methods are not shared here, so we end up with
4486 * many identical methods.
4488 add_extra_method (acfg, method);
4491 for (i = 0; i < acfg->image->tables [MONO_TABLE_TYPESPEC].rows; ++i) {
4495 token = MONO_TOKEN_TYPE_SPEC | (i + 1);
4497 klass = mono_class_get_checked (acfg->image, token, &error);
4498 if (!klass || klass->rank) {
4499 mono_error_cleanup (&error);
4503 add_generic_class (acfg, klass, FALSE, "typespec");
4506 /* Add types of args/locals */
4507 for (i = 0; i < acfg->methods->len; ++i) {
4508 method = g_ptr_array_index (acfg->methods, i);
4509 add_types_from_method_header (acfg, method);
4512 if (acfg->image == mono_defaults.corlib) {
4514 MonoType *insts [256];
4517 insts [ninsts ++] = &mono_defaults.byte_class->byval_arg;
4518 insts [ninsts ++] = &mono_defaults.sbyte_class->byval_arg;
4519 insts [ninsts ++] = &mono_defaults.int16_class->byval_arg;
4520 insts [ninsts ++] = &mono_defaults.uint16_class->byval_arg;
4521 insts [ninsts ++] = &mono_defaults.int32_class->byval_arg;
4522 insts [ninsts ++] = &mono_defaults.uint32_class->byval_arg;
4523 insts [ninsts ++] = &mono_defaults.int64_class->byval_arg;
4524 insts [ninsts ++] = &mono_defaults.uint64_class->byval_arg;
4525 insts [ninsts ++] = &mono_defaults.single_class->byval_arg;
4526 insts [ninsts ++] = &mono_defaults.double_class->byval_arg;
4527 insts [ninsts ++] = &mono_defaults.char_class->byval_arg;
4528 insts [ninsts ++] = &mono_defaults.boolean_class->byval_arg;
4530 /* Add GenericComparer<T> instances for primitive types for Enum.ToString () */
4531 klass = mono_class_from_name (acfg->image, "System.Collections.Generic", "GenericComparer`1");
4533 add_instances_of (acfg, klass, insts, ninsts, TRUE);
4534 klass = mono_class_from_name (acfg->image, "System.Collections.Generic", "GenericEqualityComparer`1");
4536 add_instances_of (acfg, klass, insts, ninsts, TRUE);
4538 /* Add instances of the array generic interfaces for primitive types */
4539 /* This will add instances of the InternalArray_ helper methods in Array too */
4540 klass = mono_class_from_name (acfg->image, "System.Collections.Generic", "ICollection`1");
4542 add_instances_of (acfg, klass, insts, ninsts, TRUE);
4543 klass = mono_class_from_name (acfg->image, "System.Collections.Generic", "IList`1");
4545 add_instances_of (acfg, klass, insts, ninsts, TRUE);
4546 klass = mono_class_from_name (acfg->image, "System.Collections.Generic", "IEnumerable`1");
4548 add_instances_of (acfg, klass, insts, ninsts, TRUE);
4551 * Add a managed-to-native wrapper of Array.GetGenericValueImpl<object>, which is
4552 * used for all instances of GetGenericValueImpl by the AOT runtime.
4555 MonoGenericContext ctx;
4556 MonoType *args [16];
4557 MonoMethod *get_method;
4558 MonoClass *array_klass = mono_array_class_get (mono_defaults.object_class, 1)->parent;
4560 get_method = mono_class_get_method_from_name (array_klass, "GetGenericValueImpl", 2);
4564 memset (&ctx, 0, sizeof (ctx));
4565 args [0] = &mono_defaults.object_class->byval_arg;
4566 ctx.method_inst = mono_metadata_get_generic_inst (1, args);
4567 add_extra_method (acfg, mono_marshal_get_native_wrapper (mono_class_inflate_generic_method_checked (get_method, &ctx, &error), TRUE, TRUE));
4568 g_assert (mono_error_ok (&error)); /* FIXME don't swallow the error */
4572 /* Same for CompareExchange<T>/Exchange<T> */
4574 MonoGenericContext ctx;
4575 MonoType *args [16];
4577 MonoClass *interlocked_klass = mono_class_from_name (mono_defaults.corlib, "System.Threading", "Interlocked");
4578 gpointer iter = NULL;
4580 while ((m = mono_class_get_methods (interlocked_klass, &iter))) {
4581 if ((!strcmp (m->name, "CompareExchange") || !strcmp (m->name, "Exchange")) && m->is_generic) {
4583 memset (&ctx, 0, sizeof (ctx));
4584 args [0] = &mono_defaults.object_class->byval_arg;
4585 ctx.method_inst = mono_metadata_get_generic_inst (1, args);
4586 add_extra_method (acfg, mono_marshal_get_native_wrapper (mono_class_inflate_generic_method_checked (m, &ctx, &error), TRUE, TRUE));
4587 g_assert (mono_error_ok (&error)); /* FIXME don't swallow the error */
4592 /* Same for Volatile.Read/Write<T> */
4594 MonoGenericContext ctx;
4595 MonoType *args [16];
4597 MonoClass *volatile_klass = mono_class_from_name (mono_defaults.corlib, "System.Threading", "Volatile");
4598 gpointer iter = NULL;
4600 if (volatile_klass) {
4601 while ((m = mono_class_get_methods (volatile_klass, &iter))) {
4602 if ((!strcmp (m->name, "Read") || !strcmp (m->name, "Write")) && m->is_generic) {
4604 memset (&ctx, 0, sizeof (ctx));
4605 args [0] = &mono_defaults.object_class->byval_arg;
4606 ctx.method_inst = mono_metadata_get_generic_inst (1, args);
4607 add_extra_method (acfg, mono_marshal_get_native_wrapper (mono_class_inflate_generic_method_checked (m, &ctx, &error), TRUE, TRUE));
4608 g_assert (mono_error_ok (&error)); /* FIXME don't swallow the error */
4617 * is_direct_callable:
4619 * Return whenever the method identified by JI is directly callable without
4620 * going through the PLT.
4623 is_direct_callable (MonoAotCompile *acfg, MonoMethod *method, MonoJumpInfo *patch_info)
4625 if ((patch_info->type == MONO_PATCH_INFO_METHOD) && (patch_info->data.method->klass->image == acfg->image)) {
4626 MonoCompile *callee_cfg = g_hash_table_lookup (acfg->method_to_cfg, patch_info->data.method);
4628 gboolean direct_callable = TRUE;
4630 if (direct_callable && !(!callee_cfg->has_got_slots && (callee_cfg->method->klass->flags & TYPE_ATTRIBUTE_BEFORE_FIELD_INIT)))
4631 direct_callable = FALSE;
4632 if ((callee_cfg->method->iflags & METHOD_IMPL_ATTRIBUTE_SYNCHRONIZED) && (!method || method->wrapper_type != MONO_WRAPPER_SYNCHRONIZED))
4633 // FIXME: Maybe call the wrapper directly ?
4634 direct_callable = FALSE;
4636 if (acfg->aot_opts.soft_debug || acfg->aot_opts.no_direct_calls) {
4637 /* Disable this so all calls go through load_method (), see the
4638 * mini_get_debug_options ()->load_aot_jit_info_eagerly = TRUE; line in
4639 * mono_debugger_agent_init ().
4641 direct_callable = FALSE;
4644 if (callee_cfg->method->wrapper_type == MONO_WRAPPER_ALLOC)
4645 /* sgen does some initialization when the allocator method is created */
4646 direct_callable = FALSE;
4647 if (callee_cfg->method->wrapper_type == MONO_WRAPPER_WRITE_BARRIER)
4648 /* we don't know at compile time whether sgen is concurrent or not */
4649 direct_callable = FALSE;
4651 if (direct_callable)
4654 } else if ((patch_info->type == MONO_PATCH_INFO_ICALL_ADDR && patch_info->data.method->flags & METHOD_ATTRIBUTE_PINVOKE_IMPL)) {
4655 if (acfg->aot_opts.direct_pinvoke)
4657 } else if (patch_info->type == MONO_PATCH_INFO_ICALL_ADDR) {
4658 if (acfg->aot_opts.direct_icalls)
4666 #ifdef MONO_ARCH_AOT_SUPPORTED
4668 get_pinvoke_import (MonoAotCompile *acfg, MonoMethod *method)
4670 MonoImage *image = method->klass->image;
4671 MonoMethodPInvoke *piinfo = (MonoMethodPInvoke *) method;
4672 MonoTableInfo *tables = image->tables;
4673 MonoTableInfo *im = &tables [MONO_TABLE_IMPLMAP];
4674 MonoTableInfo *mr = &tables [MONO_TABLE_MODULEREF];
4675 guint32 im_cols [MONO_IMPLMAP_SIZE];
4678 import = g_hash_table_lookup (acfg->method_to_pinvoke_import, method);
4682 if (!piinfo->implmap_idx || piinfo->implmap_idx > im->rows)
4685 mono_metadata_decode_row (im, piinfo->implmap_idx - 1, im_cols, MONO_IMPLMAP_SIZE);
4687 if (!im_cols [MONO_IMPLMAP_SCOPE] || im_cols [MONO_IMPLMAP_SCOPE] > mr->rows)
4690 import = g_strdup_printf ("%s", mono_metadata_string_heap (image, im_cols [MONO_IMPLMAP_NAME]));
4692 g_hash_table_insert (acfg->method_to_pinvoke_import, method, import);
4699 compare_lne (MonoDebugLineNumberEntry *a, MonoDebugLineNumberEntry *b)
4701 if (a->native_offset == b->native_offset)
4702 return a->il_offset - b->il_offset;
4704 return a->native_offset - b->native_offset;
4708 * compute_line_numbers:
4710 * Returns a sparse array of size CODE_SIZE containing MonoDebugSourceLocation* entries for the native offsets which have a corresponding line number
4713 static MonoDebugSourceLocation**
4714 compute_line_numbers (MonoMethod *method, int code_size, MonoDebugMethodJitInfo *debug_info)
4716 MonoDebugMethodInfo *minfo;
4717 MonoDebugLineNumberEntry *ln_array;
4718 MonoDebugSourceLocation *loc;
4719 int i, prev_line, prev_il_offset;
4720 int *native_to_il_offset = NULL;
4721 MonoDebugSourceLocation **res;
4724 minfo = mono_debug_lookup_method (method);
4727 // FIXME: This seems to happen when two methods have the same cfg->method_to_register
4728 if (debug_info->code_size != code_size)
4731 g_assert (code_size);
4733 /* Compute the native->IL offset mapping */
4735 ln_array = g_new0 (MonoDebugLineNumberEntry, debug_info->num_line_numbers);
4736 memcpy (ln_array, debug_info->line_numbers, debug_info->num_line_numbers * sizeof (MonoDebugLineNumberEntry));
4738 qsort (ln_array, debug_info->num_line_numbers, sizeof (MonoDebugLineNumberEntry), (gpointer)compare_lne);
4740 native_to_il_offset = g_new0 (int, code_size + 1);
4742 for (i = 0; i < debug_info->num_line_numbers; ++i) {
4744 MonoDebugLineNumberEntry *lne = &ln_array [i];
4747 for (j = 0; j < lne->native_offset; ++j)
4748 native_to_il_offset [j] = -1;
4751 if (i < debug_info->num_line_numbers - 1) {
4752 MonoDebugLineNumberEntry *lne_next = &ln_array [i + 1];
4754 for (j = lne->native_offset; j < lne_next->native_offset; ++j)
4755 native_to_il_offset [j] = lne->il_offset;
4757 for (j = lne->native_offset; j < code_size; ++j)
4758 native_to_il_offset [j] = lne->il_offset;
4763 /* Compute the native->line number mapping */
4764 res = g_new0 (MonoDebugSourceLocation*, code_size);
4765 prev_il_offset = -1;
4768 for (i = 0; i < code_size; ++i) {
4769 int il_offset = native_to_il_offset [i];
4771 if (il_offset == -1 || il_offset == prev_il_offset)
4773 prev_il_offset = il_offset;
4774 loc = mono_debug_symfile_lookup_location (minfo, il_offset);
4775 if (!(loc && loc->source_file))
4777 if (loc->row == prev_line) {
4778 mono_debug_symfile_free_location (loc);
4781 prev_line = loc->row;
4782 //printf ("D: %s:%d il=%x native=%x\n", loc->source_file, loc->row, il_offset, i);
4784 /* This will cover the prolog too */
4794 get_file_index (MonoAotCompile *acfg, const char *source_file)
4798 // FIXME: Free these
4799 if (!acfg->dwarf_ln_filenames)
4800 acfg->dwarf_ln_filenames = g_hash_table_new (g_str_hash, g_str_equal);
4801 findex = GPOINTER_TO_INT (g_hash_table_lookup (acfg->dwarf_ln_filenames, source_file));
4803 findex = g_hash_table_size (acfg->dwarf_ln_filenames) + 1;
4804 g_hash_table_insert (acfg->dwarf_ln_filenames, g_strdup (source_file), GINT_TO_POINTER (findex));
4805 emit_unset_mode (acfg);
4806 fprintf (acfg->fp, ".file %d \"%s\"\n", findex, mono_dwarf_escape_path (source_file));
4818 * emit_and_reloc_code:
4820 * Emit the native code in CODE, handling relocations along the way. If GOT_ONLY
4821 * is true, calls are made through the GOT too. This is used for emitting trampolines
4822 * in full-aot mode, since calls made from trampolines couldn't go through the PLT,
4823 * since trampolines are needed to make PTL work.
4826 emit_and_reloc_code (MonoAotCompile *acfg, MonoMethod *method, guint8 *code, guint32 code_len, MonoJumpInfo *relocs, gboolean got_only, MonoDebugMethodJitInfo *debug_info)
4828 int i, pindex, start_index;
4830 MonoJumpInfo *patch_info;
4831 MonoDebugSourceLocation **locs = NULL;
4833 #ifdef MONO_ARCH_AOT_SUPPORTED
4834 gboolean direct_call, external_call;
4836 const char *direct_call_target = 0;
4837 const char *direct_pinvoke;
4840 if (acfg->gas_line_numbers && method && debug_info) {
4841 locs = compute_line_numbers (method, code_len, debug_info);
4843 int findex = get_file_index (acfg, "<unknown>");
4844 emit_unset_mode (acfg);
4845 fprintf (acfg->fp, ".loc %d %d 0\n", findex, 1);
4849 /* Collect and sort relocations */
4850 patches = g_ptr_array_new ();
4851 for (patch_info = relocs; patch_info; patch_info = patch_info->next)
4852 g_ptr_array_add (patches, patch_info);
4853 g_ptr_array_sort (patches, compare_patches);
4856 for (i = 0; i < code_len; i += INST_LEN) {
4858 for (pindex = start_index; pindex < patches->len; ++pindex) {
4859 patch_info = g_ptr_array_index (patches, pindex);
4860 if (patch_info->ip.i >= i)
4864 if (locs && locs [i]) {
4865 MonoDebugSourceLocation *loc = locs [i];
4868 findex = get_file_index (acfg, loc->source_file);
4869 emit_unset_mode (acfg);
4870 fprintf (acfg->fp, ".loc %d %d 0\n", findex, loc->row);
4871 mono_debug_symfile_free_location (loc);
4875 #ifdef MONO_ARCH_AOT_SUPPORTED
4876 if (patch_info && (patch_info->ip.i == i) && (pindex < patches->len)) {
4877 start_index = pindex;
4879 switch (patch_info->type) {
4880 case MONO_PATCH_INFO_NONE:
4882 case MONO_PATCH_INFO_GOT_OFFSET: {
4885 arch_emit_got_offset (acfg, code + i, &code_size);
4886 i += code_size - INST_LEN;
4888 patch_info->type = MONO_PATCH_INFO_NONE;
4891 case MONO_PATCH_INFO_OBJC_SELECTOR_REF: {
4892 int code_size, index;
4893 char *selector = (void*)patch_info->data.target;
4895 if (!acfg->objc_selector_to_index)
4896 acfg->objc_selector_to_index = g_hash_table_new (g_str_hash, g_str_equal);
4897 if (!acfg->objc_selectors)
4898 acfg->objc_selectors = g_ptr_array_new ();
4899 index = GPOINTER_TO_UINT (g_hash_table_lookup (acfg->objc_selector_to_index, selector));
4903 index = acfg->objc_selector_index;
4904 g_ptr_array_add (acfg->objc_selectors, (void*)patch_info->data.target);
4905 g_hash_table_insert (acfg->objc_selector_to_index, selector, GUINT_TO_POINTER (index + 1));
4906 acfg->objc_selector_index ++;
4909 arch_emit_objc_selector_ref (acfg, code + i, index, &code_size);
4910 i += code_size - INST_LEN;
4912 patch_info->type = MONO_PATCH_INFO_NONE;
4917 * If this patch is a call, try emitting a direct call instead of
4918 * through a PLT entry. This is possible if the called method is in
4919 * the same assembly and requires no initialization.
4921 direct_call = FALSE;
4922 external_call = FALSE;
4923 if ((patch_info->type == MONO_PATCH_INFO_METHOD) && (patch_info->data.method->klass->image == acfg->image)) {
4924 if (!got_only && is_direct_callable (acfg, method, patch_info)) {
4925 MonoCompile *callee_cfg = g_hash_table_lookup (acfg->method_to_cfg, patch_info->data.method);
4926 //printf ("DIRECT: %s %s\n", method ? mono_method_full_name (method, TRUE) : "", mono_method_full_name (callee_cfg->method, TRUE));
4928 direct_call_target = callee_cfg->asm_symbol;
4929 patch_info->type = MONO_PATCH_INFO_NONE;
4930 acfg->stats.direct_calls ++;
4933 acfg->stats.all_calls ++;
4934 } else if (patch_info->type == MONO_PATCH_INFO_ICALL_ADDR) {
4935 if (!got_only && is_direct_callable (acfg, method, patch_info)) {
4936 if (!(patch_info->data.method->flags & METHOD_ATTRIBUTE_PINVOKE_IMPL))
4937 direct_pinvoke = mono_lookup_icall_symbol (patch_info->data.method);
4939 direct_pinvoke = get_pinvoke_import (acfg, patch_info->data.method);
4940 if (direct_pinvoke) {
4942 g_assert (strlen (direct_pinvoke) < 1000);
4943 direct_call_target = g_strdup_printf ("%s%s", acfg->user_symbol_prefix, direct_pinvoke);
4946 } else if (patch_info->type == MONO_PATCH_INFO_JIT_ICALL_ADDR) {
4947 const char *sym = mono_lookup_jit_icall_symbol (patch_info->data.name);
4948 if (!got_only && sym && acfg->aot_opts.direct_icalls) {
4949 /* Call to a C function implementing a jit icall */
4951 external_call = TRUE;
4952 g_assert (strlen (sym) < 1000);
4953 direct_call_target = g_strdup_printf ("%s%s", acfg->user_symbol_prefix, sym);
4955 } else if (patch_info->type == MONO_PATCH_INFO_INTERNAL_METHOD) {
4956 MonoJitICallInfo *info = mono_find_jit_icall_by_name (patch_info->data.name);
4957 const char *sym = mono_lookup_jit_icall_symbol (patch_info->data.name);
4958 if (!got_only && sym && acfg->aot_opts.direct_icalls && info->func == info->wrapper) {
4959 /* Call to a jit icall without a wrapper */
4961 external_call = TRUE;
4962 g_assert (strlen (sym) < 1000);
4963 direct_call_target = g_strdup_printf ("%s%s", acfg->user_symbol_prefix, sym);
4968 patch_info->type = MONO_PATCH_INFO_NONE;
4969 acfg->stats.direct_calls ++;
4972 if (!got_only && !direct_call) {
4973 MonoPltEntry *plt_entry = get_plt_entry (acfg, patch_info);
4975 /* This patch has a PLT entry, so we must emit a call to the PLT entry */
4977 direct_call_target = plt_entry->symbol;
4979 /* Nullify the patch */
4980 patch_info->type = MONO_PATCH_INFO_NONE;
4981 plt_entry->jit_used = TRUE;
4988 arch_emit_direct_call (acfg, direct_call_target, external_call, FALSE, patch_info, &call_size);
4989 i += call_size - INST_LEN;
4993 got_slot = get_got_offset (acfg, FALSE, patch_info);
4995 arch_emit_got_access (acfg, acfg->got_symbol, code + i, got_slot, &code_size);
4996 i += code_size - INST_LEN;
5002 #endif /* MONO_ARCH_AOT_SUPPORTED */
5005 /* Find next patch */
5007 for (pindex = start_index; pindex < patches->len; ++pindex) {
5008 patch_info = g_ptr_array_index (patches, pindex);
5009 if (patch_info->ip.i >= i)
5013 /* Try to emit multiple bytes at once */
5014 if (pindex < patches->len && patch_info->ip.i > i) {
5017 for (limit = i + INST_LEN; limit < patch_info->ip.i; limit += INST_LEN) {
5018 if (locs && locs [limit])
5022 emit_code_bytes (acfg, code + i, limit - i);
5023 i = limit - INST_LEN;
5025 emit_code_bytes (acfg, code + i, INST_LEN);
5036 * Return a modified version of S which only includes characters permissible in symbols.
5039 sanitize_symbol (MonoAotCompile *acfg, char *s)
5041 gboolean process = FALSE;
5050 for (i = 0; i < len; ++i)
5051 if (!(s [i] <= 0x7f && (isalnum (s [i]) || s [i] == '_')))
5056 gs = g_string_sized_new (len);
5057 for (i = 0; i < len; ++i) {
5059 if (c <= 0x7f && (isalnum (c) || c == '_')) {
5060 g_string_append_c (gs, c);
5061 } else if (c > 0x7f) {
5062 /* multi-byte utf8 */
5063 g_string_append_printf (gs, "_0x%x", c);
5066 while (c >> 6 == 0x2) {
5067 g_string_append_printf (gs, "%x", c);
5071 g_string_append_printf (gs, "_");
5074 g_string_append_c (gs, '_');
5078 res = mono_mempool_strdup (acfg->mempool, gs->str);
5079 g_string_free (gs, TRUE);
5084 get_debug_sym (MonoMethod *method, const char *prefix, GHashTable *cache)
5086 char *name1, *name2, *cached;
5087 int i, j, len, count;
5088 MonoMethod *cached_method;
5090 name1 = mono_method_full_name (method, TRUE);
5093 // This is so that we don't accidentally create a local symbol (which starts with 'L')
5094 if ((!prefix || !*prefix) && name1 [0] == 'L')
5098 len = strlen (name1);
5099 name2 = malloc (strlen (prefix) + len + 16);
5100 memcpy (name2, prefix, strlen (prefix));
5101 j = strlen (prefix);
5102 for (i = 0; i < len; ++i) {
5103 if (i == 0 && name1 [0] >= '0' && name1 [0] <= '9') {
5105 } else if (isalnum (name1 [i])) {
5106 name2 [j ++] = name1 [i];
5107 } else if (name1 [i] == ' ' && name1 [i + 1] == '(' && name1 [i + 2] == ')') {
5109 } else if (name1 [i] == ',' && name1 [i + 1] == ' ') {
5112 } else if (name1 [i] == '(' || name1 [i] == ')' || name1 [i] == '>') {
5122 cached_method = g_hash_table_lookup (cache, name2);
5123 if (!(cached_method && cached_method != method))
5125 sprintf (name2 + j, "_%d", count);
5129 cached = g_strdup (name2);
5130 g_hash_table_insert (cache, cached, method);
5136 emit_method_code (MonoAotCompile *acfg, MonoCompile *cfg)
5141 char *debug_sym = NULL;
5142 char *symbol = NULL;
5143 int func_alignment = AOT_FUNC_ALIGNMENT;
5146 method = cfg->orig_method;
5147 code = cfg->native_code;
5149 method_index = get_method_index (acfg, method);
5150 symbol = g_strdup_printf ("%sme_%x", acfg->temp_prefix, method_index);
5152 /* Make the labels local */
5153 emit_section_change (acfg, ".text", 0);
5154 emit_alignment_code (acfg, func_alignment);
5156 if (acfg->global_symbols && acfg->need_no_dead_strip)
5157 fprintf (acfg->fp, " .no_dead_strip %s\n", cfg->asm_symbol);
5159 emit_label (acfg, cfg->asm_symbol);
5161 if (acfg->aot_opts.write_symbols && !acfg->global_symbols && !acfg->llvm) {
5163 * Write a C style symbol for every method, this has two uses:
5164 * - it works on platforms where the dwarf debugging info is not
5166 * - it allows the setting of breakpoints of aot-ed methods.
5168 debug_sym = get_debug_sym (method, "", acfg->method_label_hash);
5169 cfg->asm_debug_symbol = g_strdup (debug_sym);
5171 if (acfg->need_no_dead_strip)
5172 fprintf (acfg->fp, " .no_dead_strip %s\n", debug_sym);
5173 emit_local_symbol (acfg, debug_sym, symbol, TRUE);
5174 emit_label (acfg, debug_sym);
5177 export_name = g_hash_table_lookup (acfg->export_names, method);
5179 /* Emit a global symbol for the method */
5180 emit_global_inner (acfg, export_name, TRUE);
5181 emit_label (acfg, export_name);
5184 if (cfg->verbose_level > 0)
5185 g_print ("Method %s emitted as %s\n", mono_method_full_name (method, TRUE), cfg->asm_symbol);
5187 acfg->stats.code_size += cfg->code_len;
5189 acfg->cfgs [method_index]->got_offset = acfg->got_offset;
5191 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 ()));
5195 if (acfg->aot_opts.write_symbols) {
5197 emit_symbol_size (acfg, debug_sym, ".");
5199 emit_symbol_size (acfg, cfg->asm_symbol, ".");
5203 emit_label (acfg, symbol);
5210 * Encode PATCH_INFO into its disk representation.
5213 encode_patch (MonoAotCompile *acfg, MonoJumpInfo *patch_info, guint8 *buf, guint8 **endbuf)
5217 switch (patch_info->type) {
5218 case MONO_PATCH_INFO_NONE:
5220 case MONO_PATCH_INFO_IMAGE:
5221 encode_value (get_image_index (acfg, patch_info->data.image), p, &p);
5223 case MONO_PATCH_INFO_MSCORLIB_GOT_ADDR:
5224 case MONO_PATCH_INFO_JIT_TLS_ID:
5225 case MONO_PATCH_INFO_GC_CARD_TABLE_ADDR:
5226 case MONO_PATCH_INFO_GC_NURSERY_START:
5228 case MONO_PATCH_INFO_CASTCLASS_CACHE:
5229 encode_value (patch_info->data.index, p, &p);
5231 case MONO_PATCH_INFO_METHOD_REL:
5232 encode_value ((gint)patch_info->data.offset, p, &p);
5234 case MONO_PATCH_INFO_SWITCH: {
5235 gpointer *table = (gpointer *)patch_info->data.table->table;
5238 encode_value (patch_info->data.table->table_size, p, &p);
5239 for (k = 0; k < patch_info->data.table->table_size; k++)
5240 encode_value ((int)(gssize)table [k], p, &p);
5243 case MONO_PATCH_INFO_METHODCONST:
5244 case MONO_PATCH_INFO_METHOD:
5245 case MONO_PATCH_INFO_METHOD_JUMP:
5246 case MONO_PATCH_INFO_ICALL_ADDR:
5247 case MONO_PATCH_INFO_METHOD_RGCTX:
5248 case MONO_PATCH_INFO_METHOD_CODE_SLOT:
5249 encode_method_ref (acfg, patch_info->data.method, p, &p);
5251 case MONO_PATCH_INFO_INTERNAL_METHOD:
5252 case MONO_PATCH_INFO_JIT_ICALL_ADDR: {
5253 guint32 len = strlen (patch_info->data.name);
5255 encode_value (len, p, &p);
5257 memcpy (p, patch_info->data.name, len);
5262 case MONO_PATCH_INFO_LDSTR: {
5263 guint32 image_index = get_image_index (acfg, patch_info->data.token->image);
5264 guint32 token = patch_info->data.token->token;
5265 g_assert (mono_metadata_token_code (token) == MONO_TOKEN_STRING);
5266 encode_value (image_index, p, &p);
5267 encode_value (patch_info->data.token->token - MONO_TOKEN_STRING, p, &p);
5270 case MONO_PATCH_INFO_RVA:
5271 case MONO_PATCH_INFO_DECLSEC:
5272 case MONO_PATCH_INFO_LDTOKEN:
5273 case MONO_PATCH_INFO_TYPE_FROM_HANDLE:
5274 encode_value (get_image_index (acfg, patch_info->data.token->image), p, &p);
5275 encode_value (patch_info->data.token->token, p, &p);
5276 encode_value (patch_info->data.token->has_context, p, &p);
5277 if (patch_info->data.token->has_context)
5278 encode_generic_context (acfg, &patch_info->data.token->context, p, &p);
5280 case MONO_PATCH_INFO_EXC_NAME: {
5281 MonoClass *ex_class;
5284 mono_class_from_name (mono_defaults.exception_class->image,
5285 "System", patch_info->data.target);
5286 g_assert (ex_class);
5287 encode_klass_ref (acfg, ex_class, p, &p);
5290 case MONO_PATCH_INFO_R4:
5291 encode_value (*((guint32 *)patch_info->data.target), p, &p);
5293 case MONO_PATCH_INFO_R8:
5294 encode_value (((guint32 *)patch_info->data.target) [MINI_LS_WORD_IDX], p, &p);
5295 encode_value (((guint32 *)patch_info->data.target) [MINI_MS_WORD_IDX], p, &p);
5297 case MONO_PATCH_INFO_VTABLE:
5298 case MONO_PATCH_INFO_CLASS:
5299 case MONO_PATCH_INFO_IID:
5300 case MONO_PATCH_INFO_ADJUSTED_IID:
5301 case MONO_PATCH_INFO_CLASS_INIT:
5302 encode_klass_ref (acfg, patch_info->data.klass, p, &p);
5304 case MONO_PATCH_INFO_DELEGATE_TRAMPOLINE:
5305 encode_klass_ref (acfg, patch_info->data.del_tramp->klass, p, &p);
5306 if (patch_info->data.del_tramp->method) {
5307 encode_value (1, p, &p);
5308 encode_method_ref (acfg, patch_info->data.del_tramp->method, p, &p);
5310 encode_value (0, p, &p);
5312 encode_value (patch_info->data.del_tramp->virtual, p, &p);
5314 case MONO_PATCH_INFO_FIELD:
5315 case MONO_PATCH_INFO_SFLDA:
5316 encode_field_info (acfg, patch_info->data.field, p, &p);
5318 case MONO_PATCH_INFO_INTERRUPTION_REQUEST_FLAG:
5320 case MONO_PATCH_INFO_RGCTX_FETCH: {
5321 MonoJumpInfoRgctxEntry *entry = patch_info->data.rgctx_entry;
5326 * entry->method has a lenghtly encoding and multiple rgctx_fetch entries
5327 * reference the same method, so encode the method only once.
5329 offset = GPOINTER_TO_UINT (g_hash_table_lookup (acfg->method_blob_hash, entry->method));
5331 buf2 = g_malloc (1024);
5334 encode_method_ref (acfg, entry->method, p2, &p2);
5335 g_assert (p2 - buf2 < 1024);
5337 offset = add_to_blob (acfg, buf2, p2 - buf2);
5340 g_hash_table_insert (acfg->method_blob_hash, entry->method, GUINT_TO_POINTER (offset + 1));
5345 encode_value (offset, p, &p);
5346 g_assert ((int)entry->info_type < 256);
5347 g_assert (entry->data->type < 256);
5348 encode_value ((entry->in_mrgctx ? 1 : 0) | (entry->info_type << 1) | (entry->data->type << 9), p, &p);
5349 encode_patch (acfg, entry->data, p, &p);
5352 case MONO_PATCH_INFO_MONITOR_ENTER:
5353 case MONO_PATCH_INFO_MONITOR_ENTER_V4:
5354 case MONO_PATCH_INFO_MONITOR_EXIT:
5355 case MONO_PATCH_INFO_SEQ_POINT_INFO:
5357 case MONO_PATCH_INFO_LLVM_IMT_TRAMPOLINE:
5358 encode_method_ref (acfg, patch_info->data.imt_tramp->method, p, &p);
5359 encode_value (patch_info->data.imt_tramp->vt_offset, p, &p);
5361 case MONO_PATCH_INFO_SIGNATURE:
5362 encode_signature (acfg, (MonoMethodSignature*)patch_info->data.target, p, &p);
5364 case MONO_PATCH_INFO_TLS_OFFSET:
5365 encode_value (GPOINTER_TO_INT (patch_info->data.target), p, &p);
5367 case MONO_PATCH_INFO_GSHAREDVT_CALL:
5368 encode_signature (acfg, (MonoMethodSignature*)patch_info->data.gsharedvt->sig, p, &p);
5369 encode_method_ref (acfg, patch_info->data.gsharedvt->method, p, &p);
5371 case MONO_PATCH_INFO_GSHAREDVT_METHOD: {
5372 MonoGSharedVtMethodInfo *info = patch_info->data.gsharedvt_method;
5375 encode_method_ref (acfg, info->method, p, &p);
5376 encode_value (info->num_entries, p, &p);
5377 for (i = 0; i < info->num_entries; ++i) {
5378 MonoRuntimeGenericContextInfoTemplate *template = &info->entries [i];
5380 encode_value (template->info_type, p, &p);
5381 switch (mini_rgctx_info_type_to_patch_info_type (template->info_type)) {
5382 case MONO_PATCH_INFO_CLASS:
5383 encode_klass_ref (acfg, mono_class_from_mono_type (template->data), p, &p);
5385 case MONO_PATCH_INFO_FIELD:
5386 encode_field_info (acfg, template->data, p, &p);
5389 g_assert_not_reached ();
5395 case MONO_PATCH_INFO_LDSTR_LIT: {
5396 const char *s = patch_info->data.target;
5397 int len = strlen (s);
5399 encode_value (len, p, &p);
5400 memcpy (p, s, len + 1);
5404 case MONO_PATCH_INFO_VIRT_METHOD:
5405 encode_klass_ref (acfg, patch_info->data.virt_method->klass, p, &p);
5406 encode_method_ref (acfg, patch_info->data.virt_method->method, p, &p);
5408 case MONO_PATCH_INFO_GC_SAFE_POINT_FLAG:
5411 g_warning ("unable to handle jump info %d", patch_info->type);
5412 g_assert_not_reached ();
5419 encode_patch_list (MonoAotCompile *acfg, GPtrArray *patches, int n_patches, gboolean llvm, int first_got_offset, guint8 *buf, guint8 **endbuf)
5422 guint32 pindex, offset;
5423 MonoJumpInfo *patch_info;
5425 encode_value (n_patches, p, &p);
5427 for (pindex = 0; pindex < patches->len; ++pindex) {
5428 patch_info = g_ptr_array_index (patches, pindex);
5430 if (patch_info->type == MONO_PATCH_INFO_NONE || patch_info->type == MONO_PATCH_INFO_BB)
5434 offset = get_got_offset (acfg, llvm, patch_info);
5435 encode_value (offset, p, &p);
5442 emit_method_info (MonoAotCompile *acfg, MonoCompile *cfg)
5445 int pindex, buf_size, n_patches;
5447 MonoJumpInfo *patch_info;
5448 guint32 method_index;
5450 guint32 first_got_offset;
5452 method = cfg->orig_method;
5454 method_index = get_method_index (acfg, method);
5456 /* Sort relocations */
5457 patches = g_ptr_array_new ();
5458 for (patch_info = cfg->patch_info; patch_info; patch_info = patch_info->next)
5459 g_ptr_array_add (patches, patch_info);
5460 g_ptr_array_sort (patches, compare_patches);
5462 first_got_offset = acfg->cfgs [method_index]->got_offset;
5464 /**********************/
5465 /* Encode method info */
5466 /**********************/
5468 buf_size = (patches->len < 1000) ? 40960 : 40960 + (patches->len * 64);
5469 p = buf = g_malloc (buf_size);
5471 if (mono_class_get_cctor (method->klass))
5472 encode_klass_ref (acfg, method->klass, p, &p);
5474 /* Not needed when loading the method */
5475 encode_value (0, p, &p);
5477 g_assert (!(cfg->opt & MONO_OPT_SHARED));
5480 for (pindex = 0; pindex < patches->len; ++pindex) {
5481 patch_info = g_ptr_array_index (patches, pindex);
5483 if ((patch_info->type == MONO_PATCH_INFO_GOT_OFFSET) ||
5484 (patch_info->type == MONO_PATCH_INFO_NONE)) {
5485 patch_info->type = MONO_PATCH_INFO_NONE;
5490 if ((patch_info->type == MONO_PATCH_INFO_IMAGE) && (patch_info->data.image == acfg->image)) {
5491 /* Stored in a GOT slot initialized at module load time */
5492 patch_info->type = MONO_PATCH_INFO_NONE;
5496 if (patch_info->type == MONO_PATCH_INFO_GC_CARD_TABLE_ADDR ||
5497 patch_info->type == MONO_PATCH_INFO_GC_NURSERY_START) {
5498 /* Stored in a GOT slot initialized at module load time */
5499 patch_info->type = MONO_PATCH_INFO_NONE;
5503 if (is_plt_patch (patch_info)) {
5504 /* Calls are made through the PLT */
5505 patch_info->type = MONO_PATCH_INFO_NONE;
5513 g_assert (cfg->has_got_slots);
5515 encode_patch_list (acfg, patches, n_patches, cfg->compile_llvm, first_got_offset, p, &p);
5517 acfg->stats.info_size += p - buf;
5519 g_assert (p - buf < buf_size);
5521 cfg->method_info_offset = add_to_blob (acfg, buf, p - buf);
5526 get_unwind_info_offset (MonoAotCompile *acfg, guint8 *encoded, guint32 encoded_len)
5528 guint32 cache_index;
5531 /* Reuse the unwind module to canonize and store unwind info entries */
5532 cache_index = mono_cache_unwind_info (encoded, encoded_len);
5534 /* Use +/- 1 to distinguish 0s from missing entries */
5535 offset = GPOINTER_TO_UINT (g_hash_table_lookup (acfg->unwind_info_offsets, GUINT_TO_POINTER (cache_index + 1)));
5543 * It would be easier to use assembler symbols, but the caller needs an
5546 offset = acfg->unwind_info_offset;
5547 g_hash_table_insert (acfg->unwind_info_offsets, GUINT_TO_POINTER (cache_index + 1), GUINT_TO_POINTER (offset + 1));
5548 g_ptr_array_add (acfg->unwind_ops, GUINT_TO_POINTER (cache_index));
5551 encode_value (encoded_len, p, &p);
5553 acfg->unwind_info_offset += encoded_len + (p - buf);
5559 emit_exception_debug_info (MonoAotCompile *acfg, MonoCompile *cfg, gboolean store_seq_points)
5562 guint32 debug_info_size, seq_points_size;
5564 MonoMethodHeader *header;
5565 guint8 *p, *buf, *debug_info;
5566 MonoJitInfo *jinfo = cfg->jit_info;
5568 gboolean use_unwind_ops = FALSE;
5569 MonoSeqPointInfo *seq_points;
5571 code = cfg->native_code;
5572 header = cfg->header;
5574 if (!acfg->aot_opts.nodebug) {
5575 mono_debug_serialize_debug_info (cfg, &debug_info, &debug_info_size);
5578 debug_info_size = 0;
5581 seq_points = cfg->seq_point_info;
5582 seq_points_size = (store_seq_points)? mono_seq_point_info_get_write_size (seq_points) : 0;
5584 buf_size = header->num_clauses * 256 + debug_info_size + 2048 + seq_points_size + cfg->gc_map_size;
5586 p = buf = g_malloc (buf_size);
5588 use_unwind_ops = cfg->unwind_ops != NULL;
5590 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);
5592 encode_value (flags, p, &p);
5594 if (use_unwind_ops) {
5595 guint32 encoded_len;
5597 guint32 unwind_desc;
5599 encoded = mono_unwind_ops_encode (cfg->unwind_ops, &encoded_len);
5601 unwind_desc = get_unwind_info_offset (acfg, encoded, encoded_len);
5602 encode_value (unwind_desc, p, &p);
5604 encode_value (jinfo->unwind_info, p, &p);
5607 /*Encode the number of holes before the number of clauses to make decoding easier*/
5608 if (jinfo->has_try_block_holes) {
5609 MonoTryBlockHoleTableJitInfo *table = mono_jit_info_get_try_block_hole_table_info (jinfo);
5610 encode_value (table->num_holes, p, &p);
5613 if (jinfo->has_arch_eh_info) {
5615 * In AOT mode, the code length is calculated from the address of the previous method,
5616 * which could include alignment padding, so calculating the start of the epilog as
5617 * code_len - epilog_size is correct any more. Save the real code len as a workaround.
5619 encode_value (jinfo->code_size, p, &p);
5622 /* Exception table */
5623 if (cfg->compile_llvm) {
5625 * When using LLVM, we can't emit some data, like pc offsets, this reg/offset etc.,
5626 * since the information is only available to llc. Instead, we let llc save the data
5627 * into the LSDA, and read it from there at runtime.
5629 /* The assembly might be CIL stripped so emit the data ourselves */
5630 if (header->num_clauses)
5631 encode_value (header->num_clauses, p, &p);
5633 for (k = 0; k < header->num_clauses; ++k) {
5634 MonoExceptionClause *clause;
5636 clause = &header->clauses [k];
5638 encode_value (clause->flags, p, &p);
5639 if (clause->data.catch_class) {
5640 encode_value (1, p, &p);
5641 encode_klass_ref (acfg, clause->data.catch_class, p, &p);
5643 encode_value (0, p, &p);
5646 /* Emit a list of nesting clauses */
5647 for (i = 0; i < header->num_clauses; ++i) {
5649 MonoExceptionClause *clause1 = &header->clauses [cindex1];
5651 MonoExceptionClause *clause2 = &header->clauses [cindex2];
5653 if (cindex1 != cindex2 && clause1->try_offset >= clause2->try_offset && clause1->handler_offset <= clause2->handler_offset)
5654 encode_value (i, p, &p);
5656 encode_value (-1, p, &p);
5659 if (jinfo->num_clauses)
5660 encode_value (jinfo->num_clauses, p, &p);
5662 for (k = 0; k < jinfo->num_clauses; ++k) {
5663 MonoJitExceptionInfo *ei = &jinfo->clauses [k];
5665 encode_value (ei->flags, p, &p);
5666 #ifdef MONO_CONTEXT_SET_LLVM_EXC_REG
5667 /* Not used for catch clauses */
5668 if (ei->flags != MONO_EXCEPTION_CLAUSE_NONE)
5669 encode_value (ei->exvar_offset, p, &p);
5671 encode_value (ei->exvar_offset, p, &p);
5674 if (ei->flags == MONO_EXCEPTION_CLAUSE_FILTER || ei->flags == MONO_EXCEPTION_CLAUSE_FINALLY)
5675 encode_value ((gint)((guint8*)ei->data.filter - code), p, &p);
5677 if (ei->data.catch_class) {
5681 buf2 = g_malloc (4096);
5683 encode_klass_ref (acfg, ei->data.catch_class, p2, &p2);
5685 g_assert (len < 4096);
5686 encode_value (len, p, &p);
5687 memcpy (p, buf2, len);
5691 encode_value (0, p, &p);
5695 encode_value ((gint)((guint8*)ei->try_start - code), p, &p);
5696 encode_value ((gint)((guint8*)ei->try_end - code), p, &p);
5697 encode_value ((gint)((guint8*)ei->handler_start - code), p, &p);
5701 if (jinfo->has_try_block_holes) {
5702 MonoTryBlockHoleTableJitInfo *table = mono_jit_info_get_try_block_hole_table_info (jinfo);
5703 for (i = 0; i < table->num_holes; ++i) {
5704 MonoTryBlockHoleJitInfo *hole = &table->holes [i];
5705 encode_value (hole->clause, p, &p);
5706 encode_value (hole->length, p, &p);
5707 encode_value (hole->offset, p, &p);
5711 if (jinfo->has_arch_eh_info) {
5712 MonoArchEHJitInfo *eh_info;
5714 eh_info = mono_jit_info_get_arch_eh_info (jinfo);
5715 encode_value (eh_info->stack_size, p, &p);
5716 encode_value (eh_info->epilog_size, p, &p);
5719 if (jinfo->has_generic_jit_info) {
5720 MonoGenericJitInfo *gi = mono_jit_info_get_generic_jit_info (jinfo);
5721 MonoGenericSharingContext* gsctx = gi->generic_sharing_context;
5725 encode_value (gi->nlocs, p, &p);
5727 for (i = 0; i < gi->nlocs; ++i) {
5728 MonoDwarfLocListEntry *entry = &gi->locations [i];
5730 encode_value (entry->is_reg ? 1 : 0, p, &p);
5731 encode_value (entry->reg, p, &p);
5733 encode_value (entry->offset, p, &p);
5735 g_assert (entry->from == 0);
5737 encode_value (entry->from, p, &p);
5738 encode_value (entry->to, p, &p);
5741 if (!cfg->compile_llvm) {
5742 encode_value (gi->has_this ? 1 : 0, p, &p);
5743 encode_value (gi->this_reg, p, &p);
5744 encode_value (gi->this_offset, p, &p);
5749 * Need to encode jinfo->method too, since it is not equal to 'method'
5750 * when using generic sharing.
5752 buf2 = g_malloc (4096);
5754 encode_method_ref (acfg, jinfo->d.method, p2, &p2);
5756 g_assert (len < 4096);
5757 encode_value (len, p, &p);
5758 memcpy (p, buf2, len);
5762 if (gsctx && gsctx->is_gsharedvt) {
5763 encode_value (1, p, &p);
5765 encode_value (0, p, &p);
5769 if (seq_points_size)
5770 p += mono_seq_point_info_write (seq_points, p);
5772 g_assert (debug_info_size < buf_size);
5774 encode_value (debug_info_size, p, &p);
5775 if (debug_info_size) {
5776 memcpy (p, debug_info, debug_info_size);
5777 p += debug_info_size;
5778 g_free (debug_info);
5783 encode_value (cfg->gc_map_size, p, &p);
5784 /* The GC map requires 4 bytes of alignment */
5785 while ((gsize)p % 4)
5787 memcpy (p, cfg->gc_map, cfg->gc_map_size);
5788 p += cfg->gc_map_size;
5791 acfg->stats.ex_info_size += p - buf;
5793 g_assert (p - buf < buf_size);
5796 /* The GC Map requires 4 byte alignment */
5797 cfg->ex_info_offset = add_to_blob_aligned (acfg, buf, p - buf, cfg->gc_map ? 4 : 1);
5802 emit_klass_info (MonoAotCompile *acfg, guint32 token)
5805 MonoClass *klass = mono_class_get_checked (acfg->image, token, &error);
5807 int i, buf_size, res;
5808 gboolean no_special_static, cant_encode;
5809 gpointer iter = NULL;
5812 mono_error_cleanup (&error);
5816 p = buf = g_malloc (buf_size);
5818 /* Mark as unusable */
5819 encode_value (-1, p, &p);
5821 res = add_to_blob (acfg, buf, p - buf);
5827 buf_size = 10240 + (klass->vtable_size * 16);
5828 p = buf = g_malloc (buf_size);
5832 mono_class_init (klass);
5834 mono_class_get_nested_types (klass, &iter);
5835 g_assert (klass->nested_classes_inited);
5837 mono_class_setup_vtable (klass);
5840 * Emit all the information which is required for creating vtables so
5841 * the runtime does not need to create the MonoMethod structures which
5842 * take up a lot of space.
5845 no_special_static = !mono_class_has_special_static_fields (klass);
5847 /* Check whenever we have enough info to encode the vtable */
5848 cant_encode = FALSE;
5849 for (i = 0; i < klass->vtable_size; ++i) {
5850 MonoMethod *cm = klass->vtable [i];
5852 if (cm && mono_method_signature (cm)->is_inflated && !g_hash_table_lookup (acfg->token_info_hash, cm))
5856 mono_class_has_finalizer (klass);
5858 if (klass->generic_container || cant_encode) {
5859 encode_value (-1, p, &p);
5861 encode_value (klass->vtable_size, p, &p);
5862 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);
5863 if (klass->has_cctor)
5864 encode_method_ref (acfg, mono_class_get_cctor (klass), p, &p);
5865 if (klass->has_finalize)
5866 encode_method_ref (acfg, mono_class_get_finalizer (klass), p, &p);
5868 encode_value (klass->instance_size, p, &p);
5869 encode_value (mono_class_data_size (klass), p, &p);
5870 encode_value (klass->packing_size, p, &p);
5871 encode_value (klass->min_align, p, &p);
5873 for (i = 0; i < klass->vtable_size; ++i) {
5874 MonoMethod *cm = klass->vtable [i];
5877 encode_method_ref (acfg, cm, p, &p);
5879 encode_value (0, p, &p);
5883 acfg->stats.class_info_size += p - buf;
5885 g_assert (p - buf < buf_size);
5886 res = add_to_blob (acfg, buf, p - buf);
5893 get_plt_entry_debug_sym (MonoAotCompile *acfg, MonoJumpInfo *ji, GHashTable *cache)
5895 char *debug_sym = NULL;
5899 if (acfg->llvm && llvm_acfg->aot_opts.static_link) {
5900 /* Need to add a prefix to create unique symbols */
5901 prefix = g_strdup_printf ("plt_%s_", acfg->assembly_name_sym);
5903 prefix = g_strdup ("plt_");
5907 case MONO_PATCH_INFO_METHOD:
5908 debug_sym = get_debug_sym (ji->data.method, prefix, cache);
5910 case MONO_PATCH_INFO_INTERNAL_METHOD:
5911 debug_sym = g_strdup_printf ("%s_jit_icall_%s", prefix, ji->data.name);
5913 case MONO_PATCH_INFO_CLASS_INIT:
5914 s = mono_type_get_name (&ji->data.klass->byval_arg);
5915 debug_sym = g_strdup_printf ("%s__class_init_%s", prefix, s);
5918 case MONO_PATCH_INFO_RGCTX_FETCH:
5919 debug_sym = g_strdup_printf ("%s_rgctx_fetch_%d", prefix, acfg->label_generator ++);
5921 case MONO_PATCH_INFO_ICALL_ADDR: {
5922 char *s = get_debug_sym (ji->data.method, "", cache);
5924 debug_sym = g_strdup_printf ("%s_icall_native_%s", prefix, s);
5928 case MONO_PATCH_INFO_JIT_ICALL_ADDR:
5929 debug_sym = g_strdup_printf ("%s_jit_icall_native_%s", prefix, ji->data.name);
5937 return sanitize_symbol (acfg, debug_sym);
5941 * Calls made from AOTed code are routed through a table of jumps similar to the
5942 * ELF PLT (Program Linkage Table). Initially the PLT entries jump to code which transfers
5943 * control to the AOT runtime through a trampoline.
5946 emit_plt (MonoAotCompile *acfg)
5952 sprintf (symbol, "plt");
5954 emit_section_change (acfg, ".text", 0);
5955 emit_alignment_code (acfg, NACL_SIZE(16, kNaClAlignment));
5956 emit_label (acfg, symbol);
5957 emit_label (acfg, acfg->plt_symbol);
5959 for (i = 0; i < acfg->plt_offset; ++i) {
5960 char *debug_sym = NULL;
5961 MonoPltEntry *plt_entry = NULL;
5965 * The first plt entry is unused.
5969 plt_entry = g_hash_table_lookup (acfg->plt_offset_to_entry, GUINT_TO_POINTER (i));
5971 debug_sym = plt_entry->debug_sym;
5973 if (acfg->thumb_mixed && !plt_entry->jit_used)
5974 /* Emit only a thumb version */
5977 /* Skip plt entries not actually called */
5978 if (!plt_entry->jit_used && !plt_entry->llvm_used)
5981 if (acfg->llvm && !acfg->thumb_mixed) {
5982 emit_label (acfg, plt_entry->llvm_symbol);
5984 emit_global_inner (acfg, plt_entry->llvm_symbol, TRUE);
5985 #if defined(TARGET_MACH)
5986 fprintf (acfg->fp, ".private_extern %s\n", plt_entry->llvm_symbol);
5992 if (acfg->need_no_dead_strip) {
5993 emit_unset_mode (acfg);
5994 fprintf (acfg->fp, " .no_dead_strip %s\n", debug_sym);
5996 emit_local_symbol (acfg, debug_sym, NULL, TRUE);
5997 emit_label (acfg, debug_sym);
6000 emit_label (acfg, plt_entry->symbol);
6002 arch_emit_plt_entry (acfg, acfg->got_symbol, (acfg->plt_got_offset_base + i) * sizeof (gpointer), acfg->plt_got_info_offsets [i]);
6005 emit_symbol_size (acfg, debug_sym, ".");
6008 if (acfg->thumb_mixed) {
6009 /* Make sure the ARM symbols don't alias the thumb ones */
6010 emit_zero_bytes (acfg, 16);
6013 * Emit a separate set of PLT entries using thumb2 which is called by LLVM generated
6016 for (i = 0; i < acfg->plt_offset; ++i) {
6017 char *debug_sym = NULL;
6018 MonoPltEntry *plt_entry = NULL;
6023 plt_entry = g_hash_table_lookup (acfg->plt_offset_to_entry, GUINT_TO_POINTER (i));
6025 /* Skip plt entries not actually called by LLVM code */
6026 if (!plt_entry->llvm_used)
6029 if (acfg->aot_opts.write_symbols) {
6030 if (plt_entry->debug_sym)
6031 debug_sym = g_strdup_printf ("%s_thumb", plt_entry->debug_sym);
6035 #if defined(TARGET_MACH)
6036 fprintf (acfg->fp, " .thumb_func %s\n", debug_sym);
6037 fprintf (acfg->fp, " .no_dead_strip %s\n", debug_sym);
6039 emit_local_symbol (acfg, debug_sym, NULL, TRUE);
6040 emit_label (acfg, debug_sym);
6042 fprintf (acfg->fp, "\n.thumb_func\n");
6044 emit_label (acfg, plt_entry->llvm_symbol);
6047 emit_global_inner (acfg, plt_entry->llvm_symbol, TRUE);
6049 arch_emit_llvm_plt_entry (acfg, acfg->got_symbol, (acfg->plt_got_offset_base + i) * sizeof (gpointer), acfg->plt_got_info_offsets [i]);
6052 emit_symbol_size (acfg, debug_sym, ".");
6058 emit_symbol_size (acfg, acfg->plt_symbol, ".");
6060 sprintf (symbol, "plt_end");
6061 emit_label (acfg, symbol);
6065 * emit_trampoline_full:
6067 * If EMIT_TINFO is TRUE, emit additional information which can be used to create a MonoJitInfo for this trampoline by
6068 * create_jit_info_for_trampoline ().
6070 static G_GNUC_UNUSED void
6071 emit_trampoline_full (MonoAotCompile *acfg, int got_offset, MonoTrampInfo *info, gboolean emit_tinfo)
6073 char start_symbol [256];
6074 char end_symbol [256];
6076 guint32 buf_size, info_offset;
6077 MonoJumpInfo *patch_info;
6090 code_size = info->code_size;
6092 unwind_ops = info->unwind_ops;
6094 #ifdef __native_client_codegen__
6095 mono_nacl_fix_patches (code, ji);
6100 sprintf (start_symbol, "%s%s", acfg->user_symbol_prefix, name);
6102 emit_section_change (acfg, ".text", 0);
6103 emit_global (acfg, start_symbol, TRUE);
6104 emit_alignment_code (acfg, AOT_FUNC_ALIGNMENT);
6105 emit_label (acfg, start_symbol);
6107 sprintf (symbol, "%snamed_%s", acfg->temp_prefix, name);
6108 emit_label (acfg, symbol);
6111 * The code should access everything through the GOT, so we pass
6114 emit_and_reloc_code (acfg, NULL, code, code_size, ji, TRUE, NULL);
6116 emit_symbol_size (acfg, start_symbol, ".");
6119 sprintf (end_symbol, "%snamede_%s", acfg->temp_prefix, name);
6120 emit_label (acfg, end_symbol);
6125 /* Sort relocations */
6126 patches = g_ptr_array_new ();
6127 for (patch_info = ji; patch_info; patch_info = patch_info->next)
6128 if (patch_info->type != MONO_PATCH_INFO_NONE)
6129 g_ptr_array_add (patches, patch_info);
6130 g_ptr_array_sort (patches, compare_patches);
6132 buf_size = patches->len * 128 + 128;
6133 buf = g_malloc (buf_size);
6136 encode_patch_list (acfg, patches, patches->len, FALSE, got_offset, p, &p);
6137 g_assert (p - buf < buf_size);
6139 sprintf (symbol, "%s%s_p", acfg->user_symbol_prefix, name);
6141 info_offset = add_to_blob (acfg, buf, p - buf);
6143 emit_section_change (acfg, RODATA_SECT, 0);
6144 emit_global (acfg, symbol, FALSE);
6145 emit_label (acfg, symbol);
6147 emit_int32 (acfg, info_offset);
6151 guint32 encoded_len;
6155 * Emit additional information which can be used to reconstruct a partial MonoTrampInfo.
6157 encoded = mono_unwind_ops_encode (info->unwind_ops, &encoded_len);
6158 uw_offset = get_unwind_info_offset (acfg, encoded, encoded_len);
6161 emit_symbol_diff (acfg, end_symbol, start_symbol, 0);
6162 emit_int32 (acfg, uw_offset);
6165 /* Emit debug info */
6169 sprintf (symbol, "%s", name);
6170 sprintf (symbol2, "%snamed_%s", acfg->temp_prefix, name);
6173 mono_dwarf_writer_emit_trampoline (acfg->dwarf, symbol, symbol2, NULL, NULL, code_size, unwind_ops);
6177 static G_GNUC_UNUSED void
6178 emit_trampoline (MonoAotCompile *acfg, int got_offset, MonoTrampInfo *info)
6180 emit_trampoline_full (acfg, got_offset, info, FALSE);
6184 emit_trampolines (MonoAotCompile *acfg)
6187 char end_symbol [256];
6188 int i, tramp_got_offset;
6189 MonoAotTrampoline ntype;
6190 #ifdef MONO_ARCH_HAVE_FULL_AOT_TRAMPOLINES
6194 if (!mono_aot_mode_is_full (&acfg->aot_opts))
6197 g_assert (acfg->image->assembly);
6199 /* Currently, we emit most trampolines into the mscorlib AOT image. */
6200 if (strcmp (acfg->image->assembly->aname.name, "mscorlib") == 0) {
6201 #ifdef MONO_ARCH_HAVE_FULL_AOT_TRAMPOLINES
6202 MonoTrampInfo *info;
6205 * Emit the generic trampolines.
6207 * We could save some code by treating the generic trampolines as a wrapper
6208 * method, but that approach has its own complexities, so we choose the simpler
6211 for (tramp_type = 0; tramp_type < MONO_TRAMPOLINE_NUM; ++tramp_type) {
6212 /* we overload the boolean here to indicate the slightly different trampoline needed, see mono_arch_create_generic_trampoline() */
6213 #ifdef DISABLE_REMOTING
6214 if (tramp_type == MONO_TRAMPOLINE_GENERIC_VIRTUAL_REMOTING)
6217 #ifndef MONO_ARCH_HAVE_HANDLER_BLOCK_GUARD
6218 if (tramp_type == MONO_TRAMPOLINE_HANDLER_BLOCK_GUARD)
6221 mono_arch_create_generic_trampoline (tramp_type, &info, acfg->aot_opts.use_trampolines_page? 2: TRUE);
6222 emit_trampoline (acfg, acfg->got_offset, info);
6225 #if defined(MONO_ARCH_MONITOR_OBJECT_REG)
6226 mono_arch_create_monitor_enter_trampoline (&info, FALSE, TRUE);
6227 emit_trampoline (acfg, acfg->got_offset, info);
6228 #if defined(MONO_ARCH_MONITOR_LOCK_TAKEN_REG)
6229 mono_arch_create_monitor_enter_trampoline (&info, TRUE, TRUE);
6230 emit_trampoline (acfg, acfg->got_offset, info);
6232 mono_arch_create_monitor_exit_trampoline (&info, TRUE);
6233 emit_trampoline (acfg, acfg->got_offset, info);
6236 /* Emit the exception related code pieces */
6237 mono_arch_get_restore_context (&info, TRUE);
6238 emit_trampoline (acfg, acfg->got_offset, info);
6239 mono_arch_get_call_filter (&info, TRUE);
6240 emit_trampoline (acfg, acfg->got_offset, info);
6241 mono_arch_get_throw_exception (&info, TRUE);
6242 emit_trampoline (acfg, acfg->got_offset, info);
6243 mono_arch_get_rethrow_exception (&info, TRUE);
6244 emit_trampoline (acfg, acfg->got_offset, info);
6245 mono_arch_get_throw_corlib_exception (&info, TRUE);
6246 emit_trampoline (acfg, acfg->got_offset, info);
6248 #ifdef MONO_ARCH_HAVE_SDB_TRAMPOLINES
6249 mono_arch_create_sdb_trampoline (TRUE, &info, TRUE);
6250 emit_trampoline (acfg, acfg->got_offset, info);
6251 mono_arch_create_sdb_trampoline (FALSE, &info, TRUE);
6252 emit_trampoline (acfg, acfg->got_offset, info);
6255 #ifdef MONO_ARCH_GSHAREDVT_SUPPORTED
6256 mono_arch_get_gsharedvt_trampoline (&info, TRUE);
6258 emit_trampoline_full (acfg, acfg->got_offset, info, TRUE);
6260 /* Create a separate out trampoline for more information in stack traces */
6261 info->name = g_strdup ("gsharedvt_out_trampoline");
6262 emit_trampoline_full (acfg, acfg->got_offset, info, TRUE);
6266 #if defined(MONO_ARCH_HAVE_GET_TRAMPOLINES)
6268 GSList *l = mono_arch_get_trampolines (TRUE);
6271 MonoTrampInfo *info = l->data;
6273 emit_trampoline (acfg, acfg->got_offset, info);
6279 for (i = 0; i < acfg->aot_opts.nrgctx_fetch_trampolines; ++i) {
6282 offset = MONO_RGCTX_SLOT_MAKE_RGCTX (i);
6283 mono_arch_create_rgctx_lazy_fetch_trampoline (offset, &info, TRUE);
6284 emit_trampoline (acfg, acfg->got_offset, info);
6286 offset = MONO_RGCTX_SLOT_MAKE_MRGCTX (i);
6287 mono_arch_create_rgctx_lazy_fetch_trampoline (offset, &info, TRUE);
6288 emit_trampoline (acfg, acfg->got_offset, info);
6291 #ifdef MONO_ARCH_HAVE_GENERAL_RGCTX_LAZY_FETCH_TRAMPOLINE
6292 mono_arch_create_general_rgctx_lazy_fetch_trampoline (&info, TRUE);
6293 emit_trampoline (acfg, acfg->got_offset, info);
6299 /* delegate_invoke_impl trampolines */
6300 l = mono_arch_get_delegate_invoke_impls ();
6302 MonoTrampInfo *info = l->data;
6304 emit_trampoline (acfg, acfg->got_offset, info);
6309 #endif /* #ifdef MONO_ARCH_HAVE_FULL_AOT_TRAMPOLINES */
6311 /* Emit trampolines which are numerous */
6314 * These include the following:
6315 * - specific trampolines
6316 * - static rgctx invoke trampolines
6318 * These trampolines have the same code, they are parameterized by GOT
6320 * They are defined in this file, in the arch_... routines instead of
6321 * in tramp-<ARCH>.c, since it is easier to do it this way.
6325 * When running in aot-only mode, we can't create specific trampolines at
6326 * runtime, so we create a few, and save them in the AOT file.
6327 * Normal trampolines embed their argument as a literal inside the
6328 * trampoline code, we can't do that here, so instead we embed an offset
6329 * which needs to be added to the trampoline address to get the address of
6330 * the GOT slot which contains the argument value.
6331 * The generated trampolines jump to the generic trampolines using another
6332 * GOT slot, which will be setup by the AOT loader to point to the
6333 * generic trampoline code of the given type.
6337 * FIXME: Maybe we should use more specific trampolines (i.e. one class init for
6341 emit_section_change (acfg, ".text", 0);
6343 tramp_got_offset = acfg->got_offset;
6345 for (ntype = 0; ntype < MONO_AOT_TRAMP_NUM; ++ntype) {
6347 case MONO_AOT_TRAMP_SPECIFIC:
6348 sprintf (symbol, "specific_trampolines");
6350 case MONO_AOT_TRAMP_STATIC_RGCTX:
6351 sprintf (symbol, "static_rgctx_trampolines");
6353 case MONO_AOT_TRAMP_IMT_THUNK:
6354 sprintf (symbol, "imt_thunks");
6356 case MONO_AOT_TRAMP_GSHAREDVT_ARG:
6357 sprintf (symbol, "gsharedvt_arg_trampolines");
6360 g_assert_not_reached ();
6363 sprintf (end_symbol, "%s_e", symbol);
6365 if (acfg->aot_opts.write_symbols)
6366 emit_local_symbol (acfg, symbol, end_symbol, TRUE);
6368 emit_alignment_code (acfg, AOT_FUNC_ALIGNMENT);
6369 emit_label (acfg, symbol);
6371 acfg->trampoline_got_offset_base [ntype] = tramp_got_offset;
6373 for (i = 0; i < acfg->num_trampolines [ntype]; ++i) {
6377 case MONO_AOT_TRAMP_SPECIFIC:
6378 arch_emit_specific_trampoline (acfg, tramp_got_offset, &tramp_size);
6379 tramp_got_offset += 2;
6381 case MONO_AOT_TRAMP_STATIC_RGCTX:
6382 arch_emit_static_rgctx_trampoline (acfg, tramp_got_offset, &tramp_size);
6383 tramp_got_offset += 2;
6385 case MONO_AOT_TRAMP_IMT_THUNK:
6386 arch_emit_imt_thunk (acfg, tramp_got_offset, &tramp_size);
6387 tramp_got_offset += 1;
6389 case MONO_AOT_TRAMP_GSHAREDVT_ARG:
6390 arch_emit_gsharedvt_arg_trampoline (acfg, tramp_got_offset, &tramp_size);
6391 tramp_got_offset += 2;
6394 g_assert_not_reached ();
6396 #ifdef __native_client_codegen__
6397 /* align to avoid 32-byte boundary crossings */
6398 emit_alignment (acfg, AOT_FUNC_ALIGNMENT);
6401 if (!acfg->trampoline_size [ntype]) {
6402 g_assert (tramp_size);
6403 acfg->trampoline_size [ntype] = tramp_size;
6407 emit_label (acfg, end_symbol);
6408 emit_int32 (acfg, 0);
6411 arch_emit_specific_trampoline_pages (acfg);
6413 /* Reserve some entries at the end of the GOT for our use */
6414 acfg->num_trampoline_got_entries = tramp_got_offset - acfg->got_offset;
6417 acfg->got_offset += acfg->num_trampoline_got_entries;
6421 str_begins_with (const char *str1, const char *str2)
6423 int len = strlen (str2);
6424 return strncmp (str1, str2, len) == 0;
6428 mono_aot_readonly_field_override (MonoClassField *field)
6431 for (rdv = readonly_values; rdv; rdv = rdv->next) {
6432 char *p = rdv->name;
6434 len = strlen (field->parent->name_space);
6435 if (strncmp (p, field->parent->name_space, len))
6440 len = strlen (field->parent->name);
6441 if (strncmp (p, field->parent->name, len))
6446 if (strcmp (p, field->name))
6448 switch (rdv->type) {
6450 return &rdv->value.i1;
6452 return &rdv->value.i2;
6454 return &rdv->value.i4;
6463 add_readonly_value (MonoAotOptions *opts, const char *val)
6468 /* the format of val is:
6469 * namespace.typename.fieldname=type/value
6470 * type can be i1 for uint8/int8/boolean, i2 for uint16/int16/char, i4 for uint32/int32
6472 fval = strrchr (val, '/');
6474 fprintf (stderr, "AOT : invalid format for readonly field '%s', missing /.\n", val);
6477 tval = strrchr (val, '=');
6479 fprintf (stderr, "AOT : invalid format for readonly field '%s', missing =.\n", val);
6482 rdv = g_new0 (ReadOnlyValue, 1);
6483 rdv->name = g_malloc0 (tval - val + 1);
6484 memcpy (rdv->name, val, tval - val);
6487 if (strncmp (tval, "i1", 2) == 0) {
6488 rdv->value.i1 = atoi (fval);
6489 rdv->type = MONO_TYPE_I1;
6490 } else if (strncmp (tval, "i2", 2) == 0) {
6491 rdv->value.i2 = atoi (fval);
6492 rdv->type = MONO_TYPE_I2;
6493 } else if (strncmp (tval, "i4", 2) == 0) {
6494 rdv->value.i4 = atoi (fval);
6495 rdv->type = MONO_TYPE_I4;
6497 fprintf (stderr, "AOT : unsupported type for readonly field '%s'.\n", tval);
6500 rdv->next = readonly_values;
6501 readonly_values = rdv;
6505 clean_path (gchar * path)
6510 if (g_str_has_suffix (path, G_DIR_SEPARATOR_S))
6513 gchar *clean = g_strconcat (path, G_DIR_SEPARATOR_S, NULL);
6520 mono_aot_parse_options (const char *aot_options, MonoAotOptions *opts)
6522 gchar **args, **ptr;
6524 args = g_strsplit (aot_options ? aot_options : "", ",", -1);
6525 for (ptr = args; ptr && *ptr; ptr ++) {
6526 const char *arg = *ptr;
6528 if (str_begins_with (arg, "outfile=")) {
6529 opts->outfile = g_strdup (arg + strlen ("outfile="));
6530 } else if (str_begins_with (arg, "llvm-outfile=")) {
6531 opts->llvm_outfile = g_strdup (arg + strlen ("llvm-outfile="));
6532 } else if (str_begins_with (arg, "temp-path=")) {
6533 opts->temp_path = clean_path (g_strdup (arg + strlen ("temp-path=")));
6534 } else if (str_begins_with (arg, "save-temps")) {
6535 opts->save_temps = TRUE;
6536 } else if (str_begins_with (arg, "keep-temps")) {
6537 opts->save_temps = TRUE;
6538 } else if (str_begins_with (arg, "write-symbols")) {
6539 opts->write_symbols = TRUE;
6540 } else if (str_begins_with (arg, "no-write-symbols")) {
6541 opts->write_symbols = FALSE;
6542 } else if (str_begins_with (arg, "metadata-only")) {
6543 opts->metadata_only = TRUE;
6544 } else if (str_begins_with (arg, "bind-to-runtime-version")) {
6545 opts->bind_to_runtime_version = TRUE;
6546 } else if (str_begins_with (arg, "full")) {
6547 opts->mode = MONO_AOT_MODE_FULL;
6548 } else if (str_begins_with (arg, "hybrid")) {
6549 opts->mode = MONO_AOT_MODE_HYBRID;
6550 } else if (str_begins_with (arg, "threads=")) {
6551 opts->nthreads = atoi (arg + strlen ("threads="));
6552 } else if (str_begins_with (arg, "static")) {
6553 opts->static_link = TRUE;
6554 opts->no_dlsym = TRUE;
6555 } else if (str_begins_with (arg, "asmonly")) {
6556 opts->asm_only = TRUE;
6557 } else if (str_begins_with (arg, "asmwriter")) {
6558 opts->asm_writer = TRUE;
6559 } else if (str_begins_with (arg, "nodebug")) {
6560 opts->nodebug = TRUE;
6561 } else if (str_begins_with (arg, "dwarfdebug")) {
6562 opts->dwarf_debug = TRUE;
6563 } else if (str_begins_with (arg, "nopagetrampolines")) {
6564 opts->use_trampolines_page = FALSE;
6565 } else if (str_begins_with (arg, "ntrampolines=")) {
6566 opts->ntrampolines = atoi (arg + strlen ("ntrampolines="));
6567 } else if (str_begins_with (arg, "nrgctx-trampolines=")) {
6568 opts->nrgctx_trampolines = atoi (arg + strlen ("nrgctx-trampolines="));
6569 } else if (str_begins_with (arg, "nimt-trampolines=")) {
6570 opts->nimt_trampolines = atoi (arg + strlen ("nimt-trampolines="));
6571 } else if (str_begins_with (arg, "ngsharedvt-trampolines=")) {
6572 opts->ngsharedvt_arg_trampolines = atoi (arg + strlen ("ngsharedvt-trampolines="));
6573 } else if (str_begins_with (arg, "autoreg")) {
6574 opts->autoreg = TRUE;
6575 } else if (str_begins_with (arg, "tool-prefix=")) {
6576 opts->tool_prefix = g_strdup (arg + strlen ("tool-prefix="));
6577 } else if (str_begins_with (arg, "ld-flags=")) {
6578 opts->ld_flags = g_strdup (arg + strlen ("ld-flags="));
6579 } else if (str_begins_with (arg, "soft-debug")) {
6580 opts->soft_debug = TRUE;
6581 } else if (str_begins_with (arg, "gen-seq-points-file")) {
6582 opts->gen_seq_points_file = TRUE;
6583 } else if (str_begins_with (arg, "direct-pinvoke")) {
6584 opts->direct_pinvoke = TRUE;
6585 } else if (str_begins_with (arg, "direct-icalls")) {
6586 opts->direct_icalls = TRUE;
6587 } else if (str_begins_with (arg, "no-direct-calls")) {
6588 opts->no_direct_calls = TRUE;
6589 } else if (str_begins_with (arg, "print-skipped")) {
6590 opts->print_skipped_methods = TRUE;
6591 } else if (str_begins_with (arg, "stats")) {
6593 } else if (str_begins_with (arg, "no-instances")) {
6594 opts->no_instances = TRUE;
6595 } else if (str_begins_with (arg, "log-generics")) {
6596 opts->log_generics = TRUE;
6597 } else if (str_begins_with (arg, "log-instances=")) {
6598 opts->log_instances = TRUE;
6599 opts->instances_logfile_path = g_strdup (arg + strlen ("log-instances="));
6600 } else if (str_begins_with (arg, "log-instances")) {
6601 opts->log_instances = TRUE;
6602 } else if (str_begins_with (arg, "internal-logfile=")) {
6603 opts->logfile = g_strdup (arg + strlen ("internal-logfile="));
6604 } else if (str_begins_with (arg, "mtriple=")) {
6605 opts->mtriple = g_strdup (arg + strlen ("mtriple="));
6606 } else if (str_begins_with (arg, "llvm-path=")) {
6607 opts->llvm_path = clean_path (g_strdup (arg + strlen ("llvm-path=")));
6608 } else if (!strcmp (arg, "llvm")) {
6610 } else if (str_begins_with (arg, "readonly-value=")) {
6611 add_readonly_value (opts, arg + strlen ("readonly-value="));
6612 } else if (str_begins_with (arg, "info")) {
6613 printf ("AOT target setup: %s.\n", AOT_TARGET_STR);
6615 } else if (str_begins_with (arg, "gc-maps")) {
6616 mini_gc_enable_gc_maps_for_aot ();
6617 } else if (str_begins_with (arg, "dump")) {
6618 opts->dump_json = TRUE;
6619 } else if (str_begins_with (arg, "help") || str_begins_with (arg, "?")) {
6620 printf ("Supported options for --aot:\n");
6621 printf (" outfile=\n");
6622 printf (" llvm-outfile=\n");
6623 printf (" llvm-path=\n");
6624 printf (" temp-path=\n");
6625 printf (" save-temps\n");
6626 printf (" keep-temps\n");
6627 printf (" write-symbols\n");
6628 printf (" metadata-only\n");
6629 printf (" bind-to-runtime-version\n");
6631 printf (" threads=\n");
6632 printf (" static\n");
6633 printf (" asmonly\n");
6634 printf (" asmwriter\n");
6635 printf (" nodebug\n");
6636 printf (" dwarfdebug\n");
6637 printf (" ntrampolines=\n");
6638 printf (" nrgctx-trampolines=\n");
6639 printf (" nimt-trampolines=\n");
6640 printf (" ngsharedvt-trampolines=\n");
6641 printf (" autoreg\n");
6642 printf (" tool-prefix=\n");
6643 printf (" readonly-value=\n");
6644 printf (" soft-debug\n");
6645 printf (" gen-seq-points-file\n");
6646 printf (" gc-maps\n");
6647 printf (" print-skipped\n");
6648 printf (" no-instances\n");
6649 printf (" stats\n");
6652 printf (" help/?\n");
6655 fprintf (stderr, "AOT : Unknown argument '%s'.\n", arg);
6660 if (opts->use_trampolines_page) {
6661 opts->ntrampolines = 0;
6662 opts->nrgctx_trampolines = 0;
6663 opts->nimt_trampolines = 0;
6664 opts->ngsharedvt_arg_trampolines = 0;
6670 add_token_info_hash (gpointer key, gpointer value, gpointer user_data)
6672 MonoMethod *method = (MonoMethod*)key;
6673 MonoJumpInfoToken *ji = (MonoJumpInfoToken*)value;
6674 MonoAotCompile *acfg = user_data;
6675 MonoJumpInfoToken *new_ji;
6677 new_ji = mono_mempool_alloc0 (acfg->mempool, sizeof (MonoJumpInfoToken));
6678 new_ji->image = ji->image;
6679 new_ji->token = ji->token;
6680 g_hash_table_insert (acfg->token_info_hash, method, new_ji);
6684 can_encode_class (MonoAotCompile *acfg, MonoClass *klass)
6686 if (klass->type_token)
6688 if ((klass->byval_arg.type == MONO_TYPE_VAR) || (klass->byval_arg.type == MONO_TYPE_MVAR) || (klass->byval_arg.type == MONO_TYPE_PTR))
6691 return can_encode_class (acfg, klass->element_class);
6696 can_encode_method (MonoAotCompile *acfg, MonoMethod *method)
6698 if (method->wrapper_type) {
6699 switch (method->wrapper_type) {
6700 case MONO_WRAPPER_NONE:
6701 case MONO_WRAPPER_REMOTING_INVOKE_WITH_CHECK:
6702 case MONO_WRAPPER_XDOMAIN_INVOKE:
6703 case MONO_WRAPPER_STFLD:
6704 case MONO_WRAPPER_LDFLD:
6705 case MONO_WRAPPER_LDFLDA:
6706 case MONO_WRAPPER_LDFLD_REMOTE:
6707 case MONO_WRAPPER_STFLD_REMOTE:
6708 case MONO_WRAPPER_STELEMREF:
6709 case MONO_WRAPPER_ISINST:
6710 case MONO_WRAPPER_PROXY_ISINST:
6711 case MONO_WRAPPER_ALLOC:
6712 case MONO_WRAPPER_REMOTING_INVOKE:
6713 case MONO_WRAPPER_UNKNOWN:
6714 case MONO_WRAPPER_WRITE_BARRIER:
6715 case MONO_WRAPPER_DELEGATE_INVOKE:
6716 case MONO_WRAPPER_DELEGATE_BEGIN_INVOKE:
6717 case MONO_WRAPPER_DELEGATE_END_INVOKE:
6718 case MONO_WRAPPER_SYNCHRONIZED:
6720 case MONO_WRAPPER_MANAGED_TO_MANAGED:
6721 case MONO_WRAPPER_CASTCLASS: {
6722 WrapperInfo *info = mono_marshal_get_wrapper_info (method);
6731 //printf ("Skip (wrapper call): %d -> %s\n", patch_info->type, mono_method_full_name (patch_info->data.method, TRUE));
6735 if (!method->token) {
6736 /* The method is part of a constructed type like Int[,].Set (). */
6737 if (!g_hash_table_lookup (acfg->token_info_hash, method)) {
6738 if (method->klass->rank)
6748 can_encode_patch (MonoAotCompile *acfg, MonoJumpInfo *patch_info)
6750 switch (patch_info->type) {
6751 case MONO_PATCH_INFO_METHOD:
6752 case MONO_PATCH_INFO_METHODCONST:
6753 case MONO_PATCH_INFO_METHOD_CODE_SLOT: {
6754 MonoMethod *method = patch_info->data.method;
6756 return can_encode_method (acfg, method);
6758 case MONO_PATCH_INFO_VTABLE:
6759 case MONO_PATCH_INFO_CLASS_INIT:
6760 case MONO_PATCH_INFO_CLASS:
6761 case MONO_PATCH_INFO_IID:
6762 case MONO_PATCH_INFO_ADJUSTED_IID:
6763 if (!can_encode_class (acfg, patch_info->data.klass)) {
6764 //printf ("Skip: %s\n", mono_type_full_name (&patch_info->data.klass->byval_arg));
6768 case MONO_PATCH_INFO_DELEGATE_TRAMPOLINE: {
6769 if (!can_encode_class (acfg, patch_info->data.del_tramp->klass)) {
6770 //printf ("Skip: %s\n", mono_type_full_name (&patch_info->data.klass->byval_arg));
6775 case MONO_PATCH_INFO_RGCTX_FETCH: {
6776 MonoJumpInfoRgctxEntry *entry = patch_info->data.rgctx_entry;
6778 if (!can_encode_method (acfg, entry->method))
6780 if (!can_encode_patch (acfg, entry->data))
6794 * AOT compile a given method.
6795 * This function might be called by multiple threads, so it must be thread-safe.
6798 compile_method (MonoAotCompile *acfg, MonoMethod *method)
6801 MonoJumpInfo *patch_info;
6804 MonoMethod *wrapped;
6807 if (acfg->aot_opts.metadata_only)
6810 mono_acfg_lock (acfg);
6811 index = get_method_index (acfg, method);
6812 mono_acfg_unlock (acfg);
6814 /* fixme: maybe we can also precompile wrapper methods */
6815 if ((method->flags & METHOD_ATTRIBUTE_PINVOKE_IMPL) ||
6816 (method->iflags & METHOD_IMPL_ATTRIBUTE_RUNTIME) ||
6817 (method->flags & METHOD_ATTRIBUTE_ABSTRACT)) {
6818 //printf ("Skip (impossible): %s\n", mono_method_full_name (method, TRUE));
6822 if (method->iflags & METHOD_IMPL_ATTRIBUTE_INTERNAL_CALL)
6825 wrapped = mono_marshal_method_from_wrapper (method);
6826 if (wrapped && (wrapped->iflags & METHOD_IMPL_ATTRIBUTE_INTERNAL_CALL) && wrapped->is_generic)
6827 // FIXME: The wrapper should be generic too, but it is not
6830 if (method->wrapper_type == MONO_WRAPPER_COMINTEROP)
6833 InterlockedIncrement (&acfg->stats.mcount);
6836 if (method->is_generic || method->klass->generic_container) {
6837 InterlockedIncrement (&acfg->stats.genericcount);
6842 //acfg->aot_opts.print_skipped_methods = TRUE;
6845 * Since these methods are the only ones which are compiled with
6846 * AOT support, and they are not used by runtime startup/shutdown code,
6847 * the runtime will not see AOT methods during AOT compilation,so it
6848 * does not need to support them by creating a fake GOT etc.
6850 flags = JIT_FLAG_AOT;
6851 if (mono_aot_mode_is_full (&acfg->aot_opts))
6852 flags |= JIT_FLAG_FULL_AOT;
6854 flags |= JIT_FLAG_LLVM;
6855 if (acfg->aot_opts.no_direct_calls)
6856 flags |= JIT_FLAG_NO_DIRECT_ICALLS;
6857 cfg = mini_method_compile (method, acfg->opts, mono_get_root_domain (), flags, 0, index);
6858 mono_loader_clear_error ();
6860 if (cfg->exception_type == MONO_EXCEPTION_GENERIC_SHARING_FAILED) {
6861 if (acfg->aot_opts.print_skipped_methods)
6862 printf ("Skip (gshared failure): %s (%s)\n", mono_method_full_name (method, TRUE), cfg->exception_message);
6863 InterlockedIncrement (&acfg->stats.genericcount);
6866 if (cfg->exception_type != MONO_EXCEPTION_NONE) {
6867 if (acfg->aot_opts.print_skipped_methods)
6868 printf ("Skip (JIT failure): %s\n", mono_method_full_name (method, TRUE));
6869 /* Let the exception happen at runtime */
6873 if (cfg->disable_aot) {
6874 if (acfg->aot_opts.print_skipped_methods)
6875 printf ("Skip (disabled): %s\n", mono_method_full_name (method, TRUE));
6876 InterlockedIncrement (&acfg->stats.ocount);
6877 mono_destroy_compile (cfg);
6880 cfg->method_index = index;
6882 /* Nullify patches which need no aot processing */
6883 for (patch_info = cfg->patch_info; patch_info; patch_info = patch_info->next) {
6884 switch (patch_info->type) {
6885 case MONO_PATCH_INFO_LABEL:
6886 case MONO_PATCH_INFO_BB:
6887 patch_info->type = MONO_PATCH_INFO_NONE;
6894 /* Collect method->token associations from the cfg */
6895 mono_acfg_lock (acfg);
6896 g_hash_table_foreach (cfg->token_info_hash, add_token_info_hash, acfg);
6897 mono_acfg_unlock (acfg);
6898 g_hash_table_destroy (cfg->token_info_hash);
6899 cfg->token_info_hash = NULL;
6902 * Check for absolute addresses.
6905 for (patch_info = cfg->patch_info; patch_info; patch_info = patch_info->next) {
6906 switch (patch_info->type) {
6907 case MONO_PATCH_INFO_ABS:
6908 /* unable to handle this */
6917 if (acfg->aot_opts.print_skipped_methods)
6918 printf ("Skip (abs call): %s\n", mono_method_full_name (method, TRUE));
6919 InterlockedIncrement (&acfg->stats.abscount);
6920 mono_destroy_compile (cfg);
6924 /* Lock for the rest of the code */
6925 mono_acfg_lock (acfg);
6928 * Check for methods/klasses we can't encode.
6931 for (patch_info = cfg->patch_info; patch_info; patch_info = patch_info->next) {
6932 if (!can_encode_patch (acfg, patch_info))
6937 if (acfg->aot_opts.print_skipped_methods)
6938 printf ("Skip (patches): %s\n", mono_method_full_name (method, TRUE));
6939 acfg->stats.ocount++;
6940 mono_destroy_compile (cfg);
6941 mono_acfg_unlock (acfg);
6945 if (!cfg->compile_llvm)
6946 acfg->has_jitted_code = TRUE;
6948 if (method->is_inflated && acfg->aot_opts.log_instances) {
6949 if (acfg->instances_logfile)
6950 fprintf (acfg->instances_logfile, "%s ### %d\n", mono_method_full_name (method, TRUE), cfg->code_size);
6952 printf ("%s ### %d\n", mono_method_full_name (method, TRUE), cfg->code_size);
6955 /* Adds generic instances referenced by this method */
6957 * The depth is used to avoid infinite loops when generic virtual recursion is
6960 depth = GPOINTER_TO_UINT (g_hash_table_lookup (acfg->method_depth, method));
6961 if (!acfg->aot_opts.no_instances && depth < 32) {
6962 for (patch_info = cfg->patch_info; patch_info; patch_info = patch_info->next) {
6963 switch (patch_info->type) {
6964 case MONO_PATCH_INFO_METHOD: {
6965 MonoMethod *m = patch_info->data.method;
6966 if (m->is_inflated) {
6967 if (!(mono_class_generic_sharing_enabled (m->klass) &&
6968 mono_method_is_generic_sharable_full (m, FALSE, FALSE, FALSE)) &&
6969 (!method_has_type_vars (m) || mono_method_is_generic_sharable_full (m, TRUE, TRUE, FALSE))) {
6970 if (m->iflags & METHOD_IMPL_ATTRIBUTE_INTERNAL_CALL) {
6971 if (mono_aot_mode_is_full (&acfg->aot_opts) && !method_has_type_vars (m))
6972 add_extra_method_with_depth (acfg, mono_marshal_get_native_wrapper (m, TRUE, TRUE), depth + 1);
6974 add_extra_method_with_depth (acfg, m, depth + 1);
6975 add_types_from_method_header (acfg, m);
6978 add_generic_class_with_depth (acfg, m->klass, depth + 5, "method");
6980 if (m->wrapper_type == MONO_WRAPPER_MANAGED_TO_MANAGED) {
6981 WrapperInfo *info = mono_marshal_get_wrapper_info (m);
6983 if (info && info->subtype == WRAPPER_SUBTYPE_ELEMENT_ADDR)
6984 add_extra_method_with_depth (acfg, m, depth + 1);
6988 case MONO_PATCH_INFO_VTABLE: {
6989 MonoClass *klass = patch_info->data.klass;
6991 if (klass->generic_class && !mini_class_is_generic_sharable (klass))
6992 add_generic_class_with_depth (acfg, klass, depth + 5, "vtable");
6995 case MONO_PATCH_INFO_SFLDA: {
6996 MonoClass *klass = patch_info->data.field->parent;
6998 /* The .cctor needs to run at runtime. */
6999 if (klass->generic_class && !mono_generic_context_is_sharable (&klass->generic_class->context, FALSE) && mono_class_get_cctor (klass))
7000 add_extra_method_with_depth (acfg, mono_class_get_cctor (klass), depth + 1);
7009 /* Determine whenever the method has GOT slots */
7010 for (patch_info = cfg->patch_info; patch_info; patch_info = patch_info->next) {
7011 switch (patch_info->type) {
7012 case MONO_PATCH_INFO_GOT_OFFSET:
7013 case MONO_PATCH_INFO_NONE:
7014 case MONO_PATCH_INFO_GC_CARD_TABLE_ADDR:
7015 case MONO_PATCH_INFO_GC_NURSERY_START:
7017 case MONO_PATCH_INFO_IMAGE:
7018 /* The assembly is stored in GOT slot 0 */
7019 if (patch_info->data.image != acfg->image)
7020 cfg->has_got_slots = TRUE;
7023 if (!is_plt_patch (patch_info))
7024 cfg->has_got_slots = TRUE;
7029 if (!cfg->has_got_slots)
7030 InterlockedIncrement (&acfg->stats.methods_without_got_slots);
7033 * FIXME: Instead of this mess, allocate the patches from the aot mempool.
7035 /* Make a copy of the patch info which is in the mempool */
7037 MonoJumpInfo *patches = NULL, *patches_end = NULL;
7039 for (patch_info = cfg->patch_info; patch_info; patch_info = patch_info->next) {
7040 MonoJumpInfo *new_patch_info = mono_patch_info_dup_mp (acfg->mempool, patch_info);
7043 patches = new_patch_info;
7045 patches_end->next = new_patch_info;
7046 patches_end = new_patch_info;
7048 cfg->patch_info = patches;
7050 /* Make a copy of the unwind info */
7052 GSList *l, *unwind_ops;
7056 for (l = cfg->unwind_ops; l; l = l->next) {
7057 op = mono_mempool_alloc (acfg->mempool, sizeof (MonoUnwindOp));
7058 memcpy (op, l->data, sizeof (MonoUnwindOp));
7059 unwind_ops = g_slist_prepend_mempool (acfg->mempool, unwind_ops, op);
7061 cfg->unwind_ops = g_slist_reverse (unwind_ops);
7063 /* Make a copy of the argument/local info */
7065 MonoInst **args, **locals;
7066 MonoMethodSignature *sig;
7067 MonoMethodHeader *header;
7070 sig = mono_method_signature (method);
7071 args = mono_mempool_alloc (acfg->mempool, sizeof (MonoInst*) * (sig->param_count + sig->hasthis));
7072 for (i = 0; i < sig->param_count + sig->hasthis; ++i) {
7073 args [i] = mono_mempool_alloc (acfg->mempool, sizeof (MonoInst));
7074 memcpy (args [i], cfg->args [i], sizeof (MonoInst));
7078 header = mono_method_get_header (method);
7079 locals = mono_mempool_alloc (acfg->mempool, sizeof (MonoInst*) * header->num_locals);
7080 for (i = 0; i < header->num_locals; ++i) {
7081 locals [i] = mono_mempool_alloc (acfg->mempool, sizeof (MonoInst));
7082 memcpy (locals [i], cfg->locals [i], sizeof (MonoInst));
7084 cfg->locals = locals;
7087 /* Free some fields used by cfg to conserve memory */
7088 mono_mempool_destroy (cfg->mempool);
7089 cfg->mempool = NULL;
7090 g_free (cfg->varinfo);
7091 cfg->varinfo = NULL;
7095 mono_regstate_free (cfg->rs);
7099 //printf ("Compile: %s\n", mono_method_full_name (method, TRUE));
7101 while (index >= acfg->cfgs_size) {
7102 MonoCompile **new_cfgs;
7105 new_size = acfg->cfgs_size * 2;
7106 new_cfgs = g_new0 (MonoCompile*, new_size);
7107 memcpy (new_cfgs, acfg->cfgs, sizeof (MonoCompile*) * acfg->cfgs_size);
7108 g_free (acfg->cfgs);
7109 acfg->cfgs = new_cfgs;
7110 acfg->cfgs_size = new_size;
7112 acfg->cfgs [index] = cfg;
7114 g_hash_table_insert (acfg->method_to_cfg, cfg->orig_method, cfg);
7117 if (cfg->orig_method->wrapper_type)
7118 g_ptr_array_add (acfg->extra_methods, cfg->orig_method);
7121 mono_acfg_unlock (acfg);
7123 InterlockedIncrement (&acfg->stats.ccount);
7127 compile_thread_main (gpointer *user_data)
7129 MonoDomain *domain = user_data [0];
7130 MonoAotCompile *acfg = user_data [1];
7131 GPtrArray *methods = user_data [2];
7134 mono_thread_attach (domain);
7136 for (i = 0; i < methods->len; ++i)
7137 compile_method (acfg, g_ptr_array_index (methods, i));
7141 load_profile_files (MonoAotCompile *acfg)
7145 int file_index, res, method_index, i;
7148 GList *unordered, *l;
7153 tmp = g_strdup_printf ("%s/.mono/aot-profile-data/%s-%d", g_get_home_dir (), acfg->image->assembly_name, file_index);
7155 if (!g_file_test (tmp, G_FILE_TEST_IS_REGULAR)) {
7160 infile = fopen (tmp, "r");
7163 printf ("Using profile data file '%s'\n", tmp);
7168 res = fscanf (infile, "%32s\n", ver);
7169 if ((res != 1) || strcmp (ver, "#VER:2") != 0) {
7170 printf ("Profile file has wrong version or invalid.\n");
7177 MonoMethodDesc *desc;
7180 if (fgets (name, 1023, infile) == NULL)
7183 /* Kill the newline */
7184 if (strlen (name) > 0)
7185 name [strlen (name) - 1] = '\0';
7187 desc = mono_method_desc_new (name, TRUE);
7189 method = mono_method_desc_search_in_image (desc, acfg->image);
7191 if (method && mono_method_get_token (method)) {
7192 token = mono_method_get_token (method);
7193 method_index = mono_metadata_token_index (token) - 1;
7196 for (i = 0; i < acfg->method_order->len; ++i) {
7197 if (g_ptr_array_index (acfg->method_order, i) == GUINT_TO_POINTER (method_index)) {
7203 g_ptr_array_add (acfg->method_order, GUINT_TO_POINTER (method_index));
7205 //printf ("No method found matching '%s'.\n", name);
7211 /* Add missing methods */
7213 for (method_index = 0; method_index < acfg->image->tables [MONO_TABLE_METHOD].rows; ++method_index) {
7215 for (i = 0; i < acfg->method_order->len; ++i) {
7216 if (g_ptr_array_index (acfg->method_order, i) == GUINT_TO_POINTER (method_index)) {
7222 unordered = g_list_prepend (unordered, GUINT_TO_POINTER (method_index));
7224 unordered = g_list_reverse (unordered);
7225 for (l = unordered; l; l = l->next)
7226 g_ptr_array_add (acfg->method_order, l->data);
7229 /* Used by the LLVM backend */
7231 mono_aot_get_got_offset (MonoJumpInfo *ji)
7233 return get_got_offset (llvm_acfg, TRUE, ji);
7237 mono_aot_get_method_name (MonoCompile *cfg)
7239 if (llvm_acfg->aot_opts.static_link)
7240 /* Include the assembly name too to avoid duplicate symbol errors */
7241 return g_strdup_printf ("%s_%s", llvm_acfg->assembly_name_sym, get_debug_sym (cfg->orig_method, "", llvm_acfg->method_label_hash));
7243 return get_debug_sym (cfg->orig_method, "", llvm_acfg->method_label_hash);
7247 mono_aot_is_direct_callable (MonoJumpInfo *patch_info)
7249 return is_direct_callable (llvm_acfg, NULL, patch_info);
7253 mono_aot_mark_unused_llvm_plt_entry (MonoJumpInfo *patch_info)
7255 MonoPltEntry *plt_entry;
7257 plt_entry = get_plt_entry (llvm_acfg, patch_info);
7258 plt_entry->llvm_used = FALSE;
7262 mono_aot_get_plt_symbol (MonoJumpInfoType type, gconstpointer data)
7264 MonoJumpInfo *ji = mono_mempool_alloc (llvm_acfg->mempool, sizeof (MonoJumpInfo));
7265 MonoPltEntry *plt_entry;
7266 const char *sym = NULL;
7269 ji->data.target = data;
7271 if (!can_encode_patch (llvm_acfg, ji))
7274 if (llvm_acfg->aot_opts.direct_icalls) {
7275 if (type == MONO_PATCH_INFO_JIT_ICALL_ADDR) {
7276 /* Call to a C function implementing a jit icall */
7277 sym = mono_lookup_jit_icall_symbol (data);
7278 } else if (type == MONO_PATCH_INFO_ICALL_ADDR) {
7279 MonoMethod *method = (gpointer)data;
7280 if (!(method->flags & METHOD_ATTRIBUTE_PINVOKE_IMPL))
7281 sym = mono_lookup_icall_symbol (method);
7284 return g_strdup (sym);
7287 plt_entry = get_plt_entry (llvm_acfg, ji);
7288 plt_entry->llvm_used = TRUE;
7290 #if defined(TARGET_MACH)
7291 return g_strdup_printf (plt_entry->llvm_symbol + strlen (llvm_acfg->llvm_label_prefix));
7293 return g_strdup_printf (plt_entry->llvm_symbol);
7298 mono_aot_get_method_index (MonoMethod *method)
7300 g_assert (llvm_acfg);
7301 return get_method_index (llvm_acfg, method);
7305 mono_aot_patch_info_dup (MonoJumpInfo* ji)
7309 mono_acfg_lock (llvm_acfg);
7310 res = mono_patch_info_dup_mp (llvm_acfg->mempool, ji);
7311 mono_acfg_unlock (llvm_acfg);
7317 execute_system (const char * command)
7322 // We need an extra set of quotes around the whole command to properly handle commands
7323 // with spaces since internally the command is called through "cmd /c.
7324 command = g_strdup_printf ("\"%s\"", command);
7326 int size = MultiByteToWideChar (CP_UTF8, 0 , command , -1, NULL , 0);
7327 wchar_t* wstr = g_malloc (sizeof (wchar_t) * size);
7328 MultiByteToWideChar (CP_UTF8, 0, command, -1, wstr , size);
7329 status = _wsystem (wstr);
7333 #elif defined (HAVE_SYSTEM)
7334 status = system (command);
7336 g_assert_not_reached ();
7347 * Emit the LLVM code into an LLVM bytecode file, and compile it using the LLVM
7351 emit_llvm_file (MonoAotCompile *acfg)
7353 char *command, *opts, *tempbc, *output_fname;
7355 tempbc = g_strdup_printf ("%s.bc", acfg->tmpbasename);
7356 mono_llvm_emit_aot_module (tempbc, g_path_get_basename (acfg->image->name));
7360 * FIXME: Experiment with adding optimizations, the -std-compile-opts set takes
7361 * a lot of time, and doesn't seem to save much space.
7362 * The following optimizations cannot be enabled:
7364 * - 'jump-threading' changes our blockaddress references to int constants.
7365 * - 'basiccg' fails because it contains:
7366 * if (CS && !isa<IntrinsicInst>(II)) {
7367 * and isa<IntrinsicInst> is false for invokes to intrinsics (iltests.exe).
7368 * - 'prune-eh' and 'functionattrs' depend on 'basiccg'.
7369 * The opt list below was produced by taking the output of:
7370 * llvm-as < /dev/null | opt -O2 -disable-output -debug-pass=Arguments
7371 * then removing tailcallelim + the global opts.
7372 * strip-dead-prototypes deletes unused intrinsics definitions.
7374 opts = g_strdup ("-instcombine -simplifycfg");
7375 //opts = g_strdup ("-simplifycfg -domtree -domfrontier -scalarrepl -instcombine -simplifycfg -domtree -domfrontier -scalarrepl -simplify-libcalls -instcombine -simplifycfg -instcombine -simplifycfg -reassociate -domtree -loops -loop-simplify -domfrontier -loop-simplify -lcssa -loop-rotate -licm -lcssa -loop-unswitch -instcombine -scalar-evolution -loop-simplify -lcssa -iv-users -indvars -loop-deletion -loop-simplify -lcssa -loop-unroll -instcombine -memdep -gvn -memdep -memcpyopt -sccp -instcombine -domtree -memdep -dse -adce -simplifycfg -domtree -verify");
7376 /* The dse pass is disabled because of #13734 and #17616 */
7378 * The dse bug is in DeadStoreElimination.cpp:isOverwrite ():
7379 * // If we have no DataLayout information around, then the size of the store
7380 * // is inferrable from the pointee type. If they are the same type, then
7381 * // we know that the store is safe.
7382 * if (AA.getDataLayout() == 0 &&
7383 * Later.Ptr->getType() == Earlier.Ptr->getType()) {
7384 * return OverwriteComplete;
7385 * Here, if 'Earlier' refers to a memset, and Later has no size info, it mistakenly thinks the memset is redundant.
7387 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");
7389 command = g_strdup_printf ("\"%sopt\" -f %s -o \"%s.opt.bc\" \"%s.bc\"", acfg->aot_opts.llvm_path, opts, acfg->tmpbasename, acfg->tmpbasename);
7390 aot_printf (acfg, "Executing opt: %s\n", command);
7391 if (execute_system (command) != 0)
7396 if (!acfg->llc_args)
7397 acfg->llc_args = g_string_new ("");
7399 /* Verbose asm slows down llc greatly */
7400 g_string_append (acfg->llc_args, " -asm-verbose=false");
7402 g_string_append (acfg->llc_args, " -disable-gnu-eh-frame -enable-mono-eh-frame");
7404 if (acfg->aot_opts.mtriple)
7405 g_string_append_printf (acfg->llc_args, " -mtriple=%s", acfg->aot_opts.mtriple);
7407 g_string_append_printf (acfg->llc_args, " -mono-eh-frame-symbol=%s", acfg->llvm_eh_frame_symbol);
7409 #if defined(TARGET_MACH) && defined(TARGET_ARM)
7410 /* ios requires PIC code now */
7411 g_string_append_printf (acfg->llc_args, " -relocation-model=pic");
7413 if (llvm_acfg->aot_opts.static_link)
7414 g_string_append_printf (acfg->llc_args, " -relocation-model=static");
7416 g_string_append_printf (acfg->llc_args, " -relocation-model=pic");
7418 unlink (acfg->tmpfname);
7420 if (acfg->llvm_owriter) {
7421 /* Emit an object file directly */
7422 output_fname = g_strdup_printf ("%s", acfg->llvm_ofile);
7423 g_string_append_printf (acfg->llc_args, " -filetype=obj");
7425 output_fname = g_strdup_printf ("%s", acfg->llvm_sfile);
7427 command = g_strdup_printf ("\"%sllc\" %s -o \"%s\" \"%s.opt.bc\"", acfg->aot_opts.llvm_path, acfg->llc_args->str, output_fname, acfg->tmpbasename);
7428 g_free (output_fname);
7430 aot_printf (acfg, "Executing llc: %s\n", command);
7432 if (execute_system (command) != 0)
7439 emit_code (MonoAotCompile *acfg)
7441 int oindex, i, prev_index;
7444 #if defined(TARGET_POWERPC64)
7445 sprintf (symbol, ".Lgot_addr");
7446 emit_section_change (acfg, ".text", 0);
7447 emit_alignment (acfg, 8);
7448 emit_label (acfg, symbol);
7449 emit_pointer (acfg, acfg->got_symbol);
7453 * This global symbol is used to compute the address of each method using the
7454 * code_offsets array. It is also used to compute the memory ranges occupied by
7455 * AOT code, so it must be equal to the address of the first emitted method.
7457 emit_section_change (acfg, ".text", 0);
7458 emit_alignment_code (acfg, 8);
7459 emit_label (acfg, "jit_code_start");
7462 * Emit some padding so the local symbol for the first method doesn't have the
7463 * same address as 'methods'.
7465 #if defined(__default_codegen__)
7466 emit_padding (acfg, 16);
7467 #elif defined(__native_client_codegen__)
7469 const int kPaddingSize = 16;
7470 guint8 pad_buffer[kPaddingSize];
7471 mono_arch_nacl_pad (pad_buffer, kPaddingSize);
7472 emit_bytes (acfg, pad_buffer, kPaddingSize);
7476 for (oindex = 0; oindex < acfg->method_order->len; ++oindex) {
7480 i = GPOINTER_TO_UINT (g_ptr_array_index (acfg->method_order, oindex));
7482 cfg = acfg->cfgs [i];
7487 method = cfg->orig_method;
7489 /* Emit unbox trampoline */
7490 if (mono_aot_mode_is_full (&acfg->aot_opts) && cfg->orig_method->klass->valuetype) {
7491 sprintf (symbol, "ut_%d", get_method_index (acfg, method));
7493 emit_section_change (acfg, ".text", 0);
7494 #ifdef __native_client_codegen__
7495 emit_alignment (acfg, AOT_FUNC_ALIGNMENT);
7498 if (acfg->thumb_mixed && cfg->compile_llvm) {
7499 emit_set_thumb_mode (acfg);
7500 fprintf (acfg->fp, "\n.thumb_func\n");
7503 emit_label (acfg, symbol);
7505 arch_emit_unbox_trampoline (acfg, cfg, cfg->orig_method, cfg->asm_symbol);
7507 if (acfg->thumb_mixed && cfg->compile_llvm)
7508 emit_set_arm_mode (acfg);
7511 if (cfg->compile_llvm)
7512 acfg->stats.llvm_count ++;
7514 emit_method_code (acfg, cfg);
7517 emit_section_change (acfg, ".text", 0);
7518 emit_alignment_code (acfg, 8);
7519 emit_label (acfg, "jit_code_end");
7521 /* To distinguish it from the next symbol */
7522 emit_padding (acfg, 4);
7525 * Add .no_dead_strip directives for all LLVM methods to prevent the OSX linker
7526 * from optimizing them away, since it doesn't see that code_offsets references them.
7527 * JITted methods don't need this since they are referenced using assembler local
7529 * FIXME: This is why write-symbols doesn't work on OSX ?
7531 if (acfg->llvm && acfg->need_no_dead_strip) {
7532 fprintf (acfg->fp, "\n");
7533 for (i = 0; i < acfg->nmethods; ++i) {
7534 if (acfg->cfgs [i] && acfg->cfgs [i]->compile_llvm)
7535 fprintf (acfg->fp, ".no_dead_strip %s\n", acfg->cfgs [i]->asm_symbol);
7540 * To work around linker issues, we emit a table of branches, and disassemble them at runtime.
7541 * This is PIE code, and the linker can update it if needed.
7543 sprintf (symbol, "method_addresses");
7544 emit_section_change (acfg, ".text", 1);
7545 emit_alignment_code (acfg, 8);
7546 emit_label (acfg, symbol);
7547 emit_local_symbol (acfg, symbol, "method_addresses_end", TRUE);
7548 emit_unset_mode (acfg);
7549 if (acfg->need_no_dead_strip)
7550 fprintf (acfg->fp, " .no_dead_strip %s\n", symbol);
7552 for (i = 0; i < acfg->nmethods; ++i) {
7553 #ifdef MONO_ARCH_AOT_SUPPORTED
7557 arch_emit_direct_call (acfg, acfg->cfgs [i]->asm_symbol, FALSE, acfg->thumb_mixed && acfg->cfgs [i]->compile_llvm, NULL, &call_size);
7559 arch_emit_direct_call (acfg, "method_addresses", FALSE, FALSE, NULL, &call_size);
7563 sprintf (symbol, "method_addresses_end");
7564 emit_label (acfg, symbol);
7567 /* Emit a sorted table mapping methods to the index of their unbox trampolines */
7568 sprintf (symbol, "unbox_trampolines");
7569 emit_section_change (acfg, RODATA_SECT, 0);
7570 emit_alignment (acfg, 8);
7571 emit_label (acfg, symbol);
7574 for (i = 0; i < acfg->nmethods; ++i) {
7579 cfg = acfg->cfgs [i];
7583 method = cfg->orig_method;
7585 if (mono_aot_mode_is_full (&acfg->aot_opts) && cfg->orig_method->klass->valuetype) {
7586 index = get_method_index (acfg, method);
7588 emit_int32 (acfg, index);
7589 /* Make sure the table is sorted by index */
7590 g_assert (index > prev_index);
7594 sprintf (symbol, "unbox_trampolines_end");
7595 emit_label (acfg, symbol);
7596 emit_int32 (acfg, 0);
7598 /* Emit a separate table with the trampoline addresses/offsets */
7599 sprintf (symbol, "unbox_trampoline_addresses");
7600 emit_section_change (acfg, ".text", 0);
7601 emit_alignment_code (acfg, 8);
7602 emit_label (acfg, symbol);
7604 for (i = 0; i < acfg->nmethods; ++i) {
7609 cfg = acfg->cfgs [i];
7613 method = cfg->orig_method;
7615 if (mono_aot_mode_is_full (&acfg->aot_opts) && cfg->orig_method->klass->valuetype) {
7616 #ifdef MONO_ARCH_AOT_SUPPORTED
7619 index = get_method_index (acfg, method);
7620 sprintf (symbol, "ut_%d", index);
7622 arch_emit_direct_call (acfg, symbol, FALSE, acfg->thumb_mixed && cfg->compile_llvm, NULL, &call_size);
7626 emit_int32 (acfg, 0);
7630 emit_info (MonoAotCompile *acfg)
7635 offsets = g_new0 (gint32, acfg->nmethods);
7637 for (oindex = 0; oindex < acfg->method_order->len; ++oindex) {
7638 i = GPOINTER_TO_UINT (g_ptr_array_index (acfg->method_order, oindex));
7640 if (acfg->cfgs [i]) {
7641 emit_method_info (acfg, acfg->cfgs [i]);
7642 offsets [i] = acfg->cfgs [i]->method_info_offset;
7648 acfg->stats.offsets_size += emit_offset_table (acfg, "method_info_offsets", acfg->nmethods, 10, offsets);
7653 #endif /* #if !defined(DISABLE_AOT) && !defined(DISABLE_JIT) */
7655 #define rot(x,k) (((x)<<(k)) | ((x)>>(32-(k))))
7656 #define mix(a,b,c) { \
7657 a -= c; a ^= rot(c, 4); c += b; \
7658 b -= a; b ^= rot(a, 6); a += c; \
7659 c -= b; c ^= rot(b, 8); b += a; \
7660 a -= c; a ^= rot(c,16); c += b; \
7661 b -= a; b ^= rot(a,19); a += c; \
7662 c -= b; c ^= rot(b, 4); b += a; \
7664 #define final(a,b,c) { \
7665 c ^= b; c -= rot(b,14); \
7666 a ^= c; a -= rot(c,11); \
7667 b ^= a; b -= rot(a,25); \
7668 c ^= b; c -= rot(b,16); \
7669 a ^= c; a -= rot(c,4); \
7670 b ^= a; b -= rot(a,14); \
7671 c ^= b; c -= rot(b,24); \
7675 mono_aot_type_hash (MonoType *t1)
7677 guint hash = t1->type;
7679 hash |= t1->byref << 6; /* do not collide with t1->type values */
7681 case MONO_TYPE_VALUETYPE:
7682 case MONO_TYPE_CLASS:
7683 case MONO_TYPE_SZARRAY:
7684 /* check if the distribution is good enough */
7685 return ((hash << 5) - hash) ^ mono_metadata_str_hash (t1->data.klass->name);
7687 return ((hash << 5) - hash) ^ mono_metadata_type_hash (t1->data.type);
7688 case MONO_TYPE_ARRAY:
7689 return ((hash << 5) - hash) ^ mono_metadata_type_hash (&t1->data.array->eklass->byval_arg);
7690 case MONO_TYPE_GENERICINST:
7691 return ((hash << 5) - hash) ^ 0;
7698 * mono_aot_method_hash:
7700 * Return a hash code for methods which only depends on metadata.
7703 mono_aot_method_hash (MonoMethod *method)
7705 MonoMethodSignature *sig;
7709 guint32 *hashes_start, *hashes;
7711 MonoGenericInst *class_ginst = NULL;
7712 MonoGenericInst *ginst = NULL;
7714 /* Similar to the hash in mono_method_get_imt_slot () */
7716 sig = mono_method_signature (method);
7718 if (method->klass->generic_class)
7719 class_ginst = method->klass->generic_class->context.class_inst;
7720 if (method->is_inflated)
7721 ginst = ((MonoMethodInflated*)method)->context.method_inst;
7723 hashes_count = sig->param_count + 5 + (class_ginst ? class_ginst->type_argc : 0) + (ginst ? ginst->type_argc : 0);
7724 hashes_start = g_malloc0 (hashes_count * sizeof (guint32));
7725 hashes = hashes_start;
7727 /* Some wrappers are assigned to random classes */
7728 if (!method->wrapper_type || method->wrapper_type == MONO_WRAPPER_REMOTING_INVOKE_WITH_CHECK)
7729 klass = method->klass;
7731 klass = mono_defaults.object_class;
7733 if (!method->wrapper_type) {
7736 if (klass->generic_class)
7737 full_name = mono_type_full_name (&klass->generic_class->container_class->byval_arg);
7739 full_name = mono_type_full_name (&klass->byval_arg);
7741 hashes [0] = mono_metadata_str_hash (full_name);
7745 hashes [0] = mono_metadata_str_hash (klass->name);
7746 hashes [1] = mono_metadata_str_hash (klass->name_space);
7748 if (method->wrapper_type == MONO_WRAPPER_STFLD || method->wrapper_type == MONO_WRAPPER_LDFLD || method->wrapper_type == MONO_WRAPPER_LDFLDA)
7749 /* The method name includes a stringified pointer */
7752 hashes [2] = mono_metadata_str_hash (method->name);
7753 hashes [3] = method->wrapper_type;
7754 hashes [4] = mono_aot_type_hash (sig->ret);
7756 for (i = 0; i < sig->param_count; i++) {
7757 hashes [hindex ++] = mono_aot_type_hash (sig->params [i]);
7760 for (i = 0; i < class_ginst->type_argc; ++i)
7761 hashes [hindex ++] = mono_aot_type_hash (class_ginst->type_argv [i]);
7764 for (i = 0; i < ginst->type_argc; ++i)
7765 hashes [hindex ++] = mono_aot_type_hash (ginst->type_argv [i]);
7767 g_assert (hindex == hashes_count);
7769 /* Setup internal state */
7770 a = b = c = 0xdeadbeef + (((guint32)hashes_count)<<2);
7772 /* Handle most of the hashes */
7773 while (hashes_count > 3) {
7782 /* Handle the last 3 hashes (all the case statements fall through) */
7783 switch (hashes_count) {
7784 case 3 : c += hashes [2];
7785 case 2 : b += hashes [1];
7786 case 1 : a += hashes [0];
7788 case 0: /* nothing left to add */
7792 free (hashes_start);
7801 * mono_aot_get_array_helper_from_wrapper;
7803 * Get the helper method in Array called by an array wrapper method.
7806 mono_aot_get_array_helper_from_wrapper (MonoMethod *method)
7810 MonoGenericContext ctx;
7811 MonoType *args [16];
7812 char *mname, *iname, *s, *s2, *helper_name = NULL;
7814 prefix = "System.Collections.Generic";
7815 s = g_strdup_printf ("%s", method->name + strlen (prefix) + 1);
7816 s2 = strstr (s, "`1.");
7822 //printf ("X: %s %s\n", iname, mname);
7824 if (!strcmp (iname, "IList"))
7825 helper_name = g_strdup_printf ("InternalArray__%s", mname);
7827 helper_name = g_strdup_printf ("InternalArray__%s_%s", iname, mname);
7828 m = mono_class_get_method_from_name (mono_defaults.array_class, helper_name, mono_method_signature (method)->param_count);
7830 g_free (helper_name);
7833 if (m->is_generic) {
7835 memset (&ctx, 0, sizeof (ctx));
7836 args [0] = &method->klass->element_class->byval_arg;
7837 ctx.method_inst = mono_metadata_get_generic_inst (1, args);
7838 m = mono_class_inflate_generic_method_checked (m, &ctx, &error);
7839 g_assert (mono_error_ok (&error)); /* FIXME don't swallow the error */
7845 #if !defined(DISABLE_AOT) && !defined(DISABLE_JIT)
7847 typedef struct HashEntry {
7848 guint32 key, value, index;
7849 struct HashEntry *next;
7853 * emit_extra_methods:
7855 * Emit methods which are not in the METHOD table, like wrappers.
7858 emit_extra_methods (MonoAotCompile *acfg)
7860 int i, table_size, buf_size;
7863 guint32 *info_offsets;
7866 HashEntry *entry, *new_entry;
7867 int nmethods, max_chain_length;
7870 info_offsets = g_new0 (guint32, acfg->extra_methods->len);
7872 /* Emit method info */
7874 for (i = 0; i < acfg->extra_methods->len; ++i) {
7875 MonoMethod *method = g_ptr_array_index (acfg->extra_methods, i);
7876 MonoCompile *cfg = g_hash_table_lookup (acfg->method_to_cfg, method);
7882 p = buf = g_malloc (buf_size);
7886 method = cfg->method_to_register;
7888 encode_method_ref (acfg, method, p, &p);
7890 g_assert ((p - buf) < buf_size);
7892 info_offsets [i] = add_to_blob (acfg, buf, p - buf);
7897 * Construct a chained hash table for mapping indexes in extra_method_info to
7900 table_size = g_spaced_primes_closest ((int)(nmethods * 1.5));
7901 table = g_ptr_array_sized_new (table_size);
7902 for (i = 0; i < table_size; ++i)
7903 g_ptr_array_add (table, NULL);
7904 chain_lengths = g_new0 (int, table_size);
7905 max_chain_length = 0;
7906 for (i = 0; i < acfg->extra_methods->len; ++i) {
7907 MonoMethod *method = g_ptr_array_index (acfg->extra_methods, i);
7908 MonoCompile *cfg = g_hash_table_lookup (acfg->method_to_cfg, method);
7914 key = info_offsets [i];
7915 value = get_method_index (acfg, method);
7917 hash = mono_aot_method_hash (method) % table_size;
7918 //printf ("X: %s %x\n", mono_method_full_name (method, 1), mono_aot_method_hash (method));
7920 chain_lengths [hash] ++;
7921 max_chain_length = MAX (max_chain_length, chain_lengths [hash]);
7923 new_entry = mono_mempool_alloc0 (acfg->mempool, sizeof (HashEntry));
7924 new_entry->key = key;
7925 new_entry->value = value;
7927 entry = g_ptr_array_index (table, hash);
7928 if (entry == NULL) {
7929 new_entry->index = hash;
7930 g_ptr_array_index (table, hash) = new_entry;
7933 entry = entry->next;
7935 entry->next = new_entry;
7936 new_entry->index = table->len;
7937 g_ptr_array_add (table, new_entry);
7941 //printf ("MAX: %d\n", max_chain_length);
7943 buf_size = table->len * 12 + 4;
7944 p = buf = g_malloc (buf_size);
7945 encode_int (table_size, p, &p);
7947 for (i = 0; i < table->len; ++i) {
7948 HashEntry *entry = g_ptr_array_index (table, i);
7950 if (entry == NULL) {
7951 encode_int (0, p, &p);
7952 encode_int (0, p, &p);
7953 encode_int (0, p, &p);
7955 //g_assert (entry->key > 0);
7956 encode_int (entry->key, p, &p);
7957 encode_int (entry->value, p, &p);
7959 encode_int (entry->next->index, p, &p);
7961 encode_int (0, p, &p);
7964 g_assert (p - buf <= buf_size);
7966 /* Emit the table */
7967 sprintf (symbol, "extra_method_table");
7968 emit_section_change (acfg, RODATA_SECT, 0);
7969 emit_alignment (acfg, 8);
7970 emit_label (acfg, symbol);
7971 emit_bytes (acfg, buf, p - buf);
7974 * Emit a table reverse mapping method indexes to their index in extra_method_info.
7975 * This is used by mono_aot_find_jit_info ().
7977 buf_size = acfg->extra_methods->len * 8 + 4;
7978 p = buf = g_malloc (buf_size);
7979 encode_int (acfg->extra_methods->len, p, &p);
7980 for (i = 0; i < acfg->extra_methods->len; ++i) {
7981 MonoMethod *method = g_ptr_array_index (acfg->extra_methods, i);
7983 encode_int (get_method_index (acfg, method), p, &p);
7984 encode_int (info_offsets [i], p, &p);
7986 sprintf (symbol, "extra_method_info_offsets");
7987 emit_section_change (acfg, RODATA_SECT, 0);
7988 emit_alignment (acfg, 8);
7989 emit_label (acfg, symbol);
7990 emit_bytes (acfg, buf, p - buf);
7994 emit_exception_info (MonoAotCompile *acfg)
7998 SeqPointData sp_data;
7999 gboolean seq_points_to_file = FALSE;
8001 offsets = g_new0 (gint32, acfg->nmethods);
8002 for (i = 0; i < acfg->nmethods; ++i) {
8003 if (acfg->cfgs [i]) {
8004 MonoCompile *cfg = acfg->cfgs [i];
8006 // By design aot-runtime decode_exception_debug_info is not able to load sequence point debug data from a file.
8007 // As it is not possible to load debug data from a file its is also not possible to store it in a file.
8008 gboolean method_seq_points_to_file = acfg->aot_opts.gen_seq_points_file &&
8009 cfg->gen_seq_points && !cfg->gen_sdb_seq_points;
8010 gboolean method_seq_points_to_binary = cfg->gen_seq_points && !method_seq_points_to_file;
8012 emit_exception_debug_info (acfg, cfg, method_seq_points_to_binary);
8013 offsets [i] = cfg->ex_info_offset;
8015 if (method_seq_points_to_file) {
8016 if (!seq_points_to_file) {
8017 mono_seq_point_data_init (&sp_data, acfg->nmethods);
8018 seq_points_to_file = TRUE;
8020 mono_seq_point_data_add (&sp_data, cfg->method->token, cfg->method_index, cfg->seq_point_info);
8027 if (seq_points_to_file) {
8028 char *seq_points_aot_file;
8029 mono_image_get_aot_seq_point_path (acfg->image, &seq_points_aot_file);
8030 mono_seq_point_data_write (&sp_data, seq_points_aot_file);
8031 mono_seq_point_data_free (&sp_data);
8032 g_free (seq_points_aot_file);
8035 acfg->stats.offsets_size += emit_offset_table (acfg, "ex_info_offsets", acfg->nmethods, 10, offsets);
8040 emit_unwind_info (MonoAotCompile *acfg)
8046 * The unwind info contains a lot of duplicates so we emit each unique
8047 * entry once, and only store the offset from the start of the table in the
8051 sprintf (symbol, "unwind_info");
8052 emit_section_change (acfg, RODATA_SECT, 1);
8053 emit_alignment (acfg, 8);
8054 emit_label (acfg, symbol);
8056 for (i = 0; i < acfg->unwind_ops->len; ++i) {
8057 guint32 index = GPOINTER_TO_UINT (g_ptr_array_index (acfg->unwind_ops, i));
8058 guint8 *unwind_info;
8059 guint32 unwind_info_len;
8063 unwind_info = mono_get_cached_unwind_info (index, &unwind_info_len);
8066 encode_value (unwind_info_len, p, &p);
8067 emit_bytes (acfg, buf, p - buf);
8068 emit_bytes (acfg, unwind_info, unwind_info_len);
8070 acfg->stats.unwind_info_size += (p - buf) + unwind_info_len;
8075 emit_class_info (MonoAotCompile *acfg)
8080 offsets = g_new0 (gint32, acfg->image->tables [MONO_TABLE_TYPEDEF].rows);
8081 for (i = 0; i < acfg->image->tables [MONO_TABLE_TYPEDEF].rows; ++i)
8082 offsets [i] = emit_klass_info (acfg, MONO_TOKEN_TYPE_DEF | (i + 1));
8084 acfg->stats.offsets_size += emit_offset_table (acfg, "class_info_offsets", acfg->image->tables [MONO_TABLE_TYPEDEF].rows, 10, offsets);
8088 typedef struct ClassNameTableEntry {
8089 guint32 token, index;
8090 struct ClassNameTableEntry *next;
8091 } ClassNameTableEntry;
8094 emit_class_name_table (MonoAotCompile *acfg)
8096 int i, table_size, buf_size;
8097 guint32 token, hash;
8103 ClassNameTableEntry *entry, *new_entry;
8106 * Construct a chained hash table for mapping class names to typedef tokens.
8108 table_size = g_spaced_primes_closest ((int)(acfg->image->tables [MONO_TABLE_TYPEDEF].rows * 1.5));
8109 table = g_ptr_array_sized_new (table_size);
8110 for (i = 0; i < table_size; ++i)
8111 g_ptr_array_add (table, NULL);
8112 for (i = 0; i < acfg->image->tables [MONO_TABLE_TYPEDEF].rows; ++i) {
8114 token = MONO_TOKEN_TYPE_DEF | (i + 1);
8115 klass = mono_class_get_checked (acfg->image, token, &error);
8117 mono_error_cleanup (&error);
8120 full_name = mono_type_get_name_full (mono_class_get_type (klass), MONO_TYPE_NAME_FORMAT_FULL_NAME);
8121 hash = mono_metadata_str_hash (full_name) % table_size;
8124 /* FIXME: Allocate from the mempool */
8125 new_entry = g_new0 (ClassNameTableEntry, 1);
8126 new_entry->token = token;
8128 entry = g_ptr_array_index (table, hash);
8129 if (entry == NULL) {
8130 new_entry->index = hash;
8131 g_ptr_array_index (table, hash) = new_entry;
8134 entry = entry->next;
8136 entry->next = new_entry;
8137 new_entry->index = table->len;
8138 g_ptr_array_add (table, new_entry);
8142 /* Emit the table */
8143 buf_size = table->len * 4 + 4;
8144 p = buf = g_malloc0 (buf_size);
8146 /* FIXME: Optimize memory usage */
8147 g_assert (table_size < 65000);
8148 encode_int16 (table_size, p, &p);
8149 g_assert (table->len < 65000);
8150 for (i = 0; i < table->len; ++i) {
8151 ClassNameTableEntry *entry = g_ptr_array_index (table, i);
8153 if (entry == NULL) {
8154 encode_int16 (0, p, &p);
8155 encode_int16 (0, p, &p);
8157 encode_int16 (mono_metadata_token_index (entry->token), p, &p);
8159 encode_int16 (entry->next->index, p, &p);
8161 encode_int16 (0, p, &p);
8164 g_assert (p - buf <= buf_size);
8166 sprintf (symbol, "class_name_table");
8167 emit_section_change (acfg, RODATA_SECT, 0);
8168 emit_alignment (acfg, 8);
8169 emit_label (acfg, symbol);
8170 emit_bytes (acfg, buf, p - buf);
8174 emit_image_table (MonoAotCompile *acfg)
8181 * The image table is small but referenced in a lot of places.
8182 * So we emit it at once, and reference its elements by an index.
8184 buf_size = acfg->image_table->len * 28 + 4;
8185 for (i = 0; i < acfg->image_table->len; i++) {
8186 MonoImage *image = (MonoImage*)g_ptr_array_index (acfg->image_table, i);
8187 MonoAssemblyName *aname = &image->assembly->aname;
8189 buf_size += strlen (image->assembly_name) + strlen (image->guid) + (aname->culture ? strlen (aname->culture) : 1) + strlen ((char*)aname->public_key_token) + 4;
8192 buf = p = g_malloc0 (buf_size);
8193 encode_int (acfg->image_table->len, p, &p);
8194 for (i = 0; i < acfg->image_table->len; i++) {
8195 MonoImage *image = (MonoImage*)g_ptr_array_index (acfg->image_table, i);
8196 MonoAssemblyName *aname = &image->assembly->aname;
8198 /* FIXME: Support multi-module assemblies */
8199 g_assert (image->assembly->image == image);
8201 encode_string (image->assembly_name, p, &p);
8202 encode_string (image->guid, p, &p);
8203 encode_string (aname->culture ? aname->culture : "", p, &p);
8204 encode_string ((const char*)aname->public_key_token, p, &p);
8206 while (GPOINTER_TO_UINT (p) % 8 != 0)
8209 encode_int (aname->flags, p, &p);
8210 encode_int (aname->major, p, &p);
8211 encode_int (aname->minor, p, &p);
8212 encode_int (aname->build, p, &p);
8213 encode_int (aname->revision, p, &p);
8215 g_assert (p - buf <= buf_size);
8217 sprintf (symbol, "image_table");
8218 emit_section_change (acfg, RODATA_SECT, 1);
8219 emit_alignment (acfg, 8);
8220 emit_label (acfg, symbol);
8221 emit_bytes (acfg, buf, p - buf);
8227 emit_got_info (MonoAotCompile *acfg, gboolean llvm)
8229 int i, first_plt_got_patch = 0, buf_size;
8231 guint32 *got_info_offsets;
8232 GotInfo *info = llvm ? &acfg->llvm_got_info : &acfg->got_info;
8234 /* Add the patches needed by the PLT to the GOT */
8236 acfg->plt_got_offset_base = acfg->got_offset;
8237 first_plt_got_patch = info->got_patches->len;
8238 for (i = 1; i < acfg->plt_offset; ++i) {
8239 MonoPltEntry *plt_entry = g_hash_table_lookup (acfg->plt_offset_to_entry, GUINT_TO_POINTER (i));
8241 g_ptr_array_add (info->got_patches, plt_entry->ji);
8243 acfg->stats.got_slot_types [plt_entry->ji->type] ++;
8246 acfg->got_offset += acfg->plt_offset;
8251 * - optimize offsets table.
8252 * - reduce number of exported symbols.
8253 * - emit info for a klass only once.
8254 * - determine when a method uses a GOT slot which is guaranteed to be already
8256 * - clean up and document the code.
8257 * - use String.Empty in class libs.
8260 /* Encode info required to decode shared GOT entries */
8261 buf_size = info->got_patches->len * 128;
8262 p = buf = mono_mempool_alloc (acfg->mempool, buf_size);
8263 got_info_offsets = mono_mempool_alloc (acfg->mempool, info->got_patches->len * sizeof (guint32));
8265 acfg->plt_got_info_offsets = mono_mempool_alloc (acfg->mempool, acfg->plt_offset * sizeof (guint32));
8267 if (acfg->plt_offset)
8268 acfg->plt_got_info_offsets [0] = 0;
8270 for (i = 0; i < info->got_patches->len; ++i) {
8271 MonoJumpInfo *ji = g_ptr_array_index (info->got_patches, i);
8276 encode_value (ji->type, p, &p);
8278 encode_patch (acfg, ji, p, &p);
8279 acfg->stats.got_slot_info_sizes [ji->type] += p - p2;
8280 g_assert (p - buf <= buf_size);
8281 got_info_offsets [i] = add_to_blob (acfg, buf, p - buf);
8283 if (!llvm && i >= first_plt_got_patch)
8284 acfg->plt_got_info_offsets [i - first_plt_got_patch + 1] = got_info_offsets [i];
8285 acfg->stats.got_info_size += p - buf;
8288 /* Emit got_info_offsets table */
8290 /* No need to emit offsets for the got plt entries, the plt embeds them directly */
8291 acfg->stats.offsets_size += emit_offset_table (acfg, llvm ? "llvm_got_info_offsets" : "got_info_offsets", llvm ? acfg->llvm_got_offset : first_plt_got_patch, 10, (gint32*)got_info_offsets);
8295 emit_got (MonoAotCompile *acfg)
8299 /* Don't make GOT global so accesses to it don't need relocations */
8300 sprintf (symbol, "%s", acfg->got_symbol);
8301 emit_section_change (acfg, ".bss", 0);
8302 emit_alignment (acfg, 8);
8303 emit_local_symbol (acfg, symbol, "got_end", FALSE);
8304 emit_label (acfg, symbol);
8305 if (acfg->got_offset > 0)
8306 emit_zero_bytes (acfg, (int)(acfg->got_offset * sizeof (gpointer)));
8308 sprintf (symbol, "got_end");
8309 emit_label (acfg, symbol);
8312 typedef struct GlobalsTableEntry {
8313 guint32 value, index;
8314 struct GlobalsTableEntry *next;
8315 } GlobalsTableEntry;
8318 emit_globals (MonoAotCompile *acfg)
8324 GlobalsTableEntry *entry, *new_entry;
8326 if (!acfg->aot_opts.static_link)
8330 * When static linking, we emit a table containing our globals.
8334 * Construct a chained hash table for mapping global names to their index in
8335 * the globals table.
8337 table_size = g_spaced_primes_closest ((int)(acfg->globals->len * 1.5));
8338 table = g_ptr_array_sized_new (table_size);
8339 for (i = 0; i < table_size; ++i)
8340 g_ptr_array_add (table, NULL);
8341 for (i = 0; i < acfg->globals->len; ++i) {
8342 char *name = g_ptr_array_index (acfg->globals, i);
8344 hash = mono_metadata_str_hash (name) % table_size;
8346 /* FIXME: Allocate from the mempool */
8347 new_entry = g_new0 (GlobalsTableEntry, 1);
8348 new_entry->value = i;
8350 entry = g_ptr_array_index (table, hash);
8351 if (entry == NULL) {
8352 new_entry->index = hash;
8353 g_ptr_array_index (table, hash) = new_entry;
8356 entry = entry->next;
8358 entry->next = new_entry;
8359 new_entry->index = table->len;
8360 g_ptr_array_add (table, new_entry);
8364 /* Emit the table */
8365 sprintf (symbol, ".Lglobals_hash");
8366 emit_section_change (acfg, RODATA_SECT, 0);
8367 emit_alignment (acfg, 8);
8368 emit_label (acfg, symbol);
8370 /* FIXME: Optimize memory usage */
8371 g_assert (table_size < 65000);
8372 emit_int16 (acfg, table_size);
8373 for (i = 0; i < table->len; ++i) {
8374 GlobalsTableEntry *entry = g_ptr_array_index (table, i);
8376 if (entry == NULL) {
8377 emit_int16 (acfg, 0);
8378 emit_int16 (acfg, 0);
8380 emit_int16 (acfg, entry->value + 1);
8382 emit_int16 (acfg, entry->next->index);
8384 emit_int16 (acfg, 0);
8388 /* Emit the names */
8389 for (i = 0; i < acfg->globals->len; ++i) {
8390 char *name = g_ptr_array_index (acfg->globals, i);
8392 sprintf (symbol, "name_%d", i);
8393 emit_section_change (acfg, RODATA_SECT, 1);
8395 emit_alignment (acfg, 4);
8397 emit_label (acfg, symbol);
8398 emit_string (acfg, name);
8401 /* Emit the globals table */
8402 sprintf (symbol, "globals");
8403 emit_section_change (acfg, ".data", 0);
8404 /* This is not a global, since it is accessed by the init function */
8405 emit_alignment (acfg, 8);
8406 emit_label (acfg, symbol);
8408 sprintf (symbol, "%sglobals_hash", acfg->temp_prefix);
8409 emit_pointer (acfg, symbol);
8411 for (i = 0; i < acfg->globals->len; ++i) {
8412 char *name = g_ptr_array_index (acfg->globals, i);
8414 sprintf (symbol, "name_%d", i);
8415 emit_pointer (acfg, symbol);
8417 g_assert (strlen (name) < sizeof (symbol));
8418 sprintf (symbol, "%s", name);
8419 emit_pointer (acfg, symbol);
8421 /* Null terminate the table */
8422 emit_int32 (acfg, 0);
8423 emit_int32 (acfg, 0);
8427 emit_autoreg (MonoAotCompile *acfg)
8432 * Emit a function into the .ctor section which will be called by the ELF
8433 * loader to register this module with the runtime.
8435 if (! (!acfg->use_bin_writer && acfg->aot_opts.static_link && acfg->aot_opts.autoreg))
8438 symbol = g_strdup_printf ("_%s_autoreg", acfg->static_linking_symbol);
8440 arch_emit_autoreg (acfg, symbol);
8446 emit_mem_end (MonoAotCompile *acfg)
8450 sprintf (symbol, "mem_end");
8451 emit_section_change (acfg, ".text", 1);
8452 emit_alignment_code (acfg, 8);
8453 emit_label (acfg, symbol);
8457 init_aot_file_info (MonoAotCompile *acfg, MonoAotFileInfo *info, int gc_name_offset)
8461 info->version = MONO_AOT_FILE_VERSION;
8462 info->plt_got_offset_base = acfg->plt_got_offset_base;
8463 info->got_size = acfg->got_offset * sizeof (gpointer);
8464 info->plt_size = acfg->plt_offset;
8465 info->nmethods = acfg->nmethods;
8466 info->flags = acfg->flags;
8467 info->opts = acfg->opts;
8468 info->simd_opts = acfg->simd_opts;
8469 info->gc_name_index = gc_name_offset;
8470 for (i = 0; i < MONO_AOT_TRAMP_NUM; ++i)
8471 info->num_trampolines [i] = acfg->num_trampolines [i];
8472 for (i = 0; i < MONO_AOT_TRAMP_NUM; ++i)
8473 info->trampoline_got_offset_base [i] = acfg->trampoline_got_offset_base [i];
8474 for (i = 0; i < MONO_AOT_TRAMP_NUM; ++i)
8475 info->trampoline_size [i] = acfg->trampoline_size [i];
8476 info->num_rgctx_fetch_trampolines = acfg->aot_opts.nrgctx_fetch_trampolines;
8478 #if defined (TARGET_ARM) && defined (TARGET_MACH)
8483 memset (&t, 0, sizeof (MonoType));
8484 t.type = MONO_TYPE_R8;
8485 mono_type_size (&t, &align);
8486 info->double_align = align;
8488 memset (&t, 0, sizeof (MonoType));
8489 t.type = MONO_TYPE_I8;
8490 mono_type_size (&t, &align);
8491 info->long_align = align;
8494 info->double_align = MONO_ABI_ALIGNOF (double);
8495 info->long_align = MONO_ABI_ALIGNOF (gint64);
8497 info->generic_tramp_num = MONO_TRAMPOLINE_NUM;
8498 info->tramp_page_size = acfg->tramp_page_size;
8499 for (i = 0; i < MONO_AOT_TRAMP_NUM; ++i)
8500 info->tramp_page_code_offsets [i] = acfg->tramp_page_code_offsets [i];
8504 emit_aot_file_info (MonoAotCompile *acfg, MonoAotFileInfo *info)
8508 const char **symbols;
8510 symbols = g_new0 (const char *, MONO_AOT_FILE_INFO_NUM_SYMBOLS);
8512 symbols [sindex ++] = acfg->got_symbol;
8514 symbols [sindex ++] = g_strdup_printf ("%s%s", acfg->user_symbol_prefix, acfg->llvm_got_symbol);
8515 symbols [sindex ++] = acfg->llvm_eh_frame_symbol;
8517 symbols [sindex ++] = NULL;
8518 symbols [sindex ++] = NULL;
8520 symbols [sindex ++] = "jit_code_start";
8521 symbols [sindex ++] = "jit_code_end";
8522 symbols [sindex ++] = "method_addresses";
8523 symbols [sindex ++] = "blob";
8524 symbols [sindex ++] = "class_name_table";
8525 symbols [sindex ++] = "class_info_offsets";
8526 symbols [sindex ++] = "method_info_offsets";
8527 symbols [sindex ++] = "ex_info_offsets";
8528 symbols [sindex ++] = "extra_method_info_offsets";
8529 symbols [sindex ++] = "extra_method_table";
8530 symbols [sindex ++] = "got_info_offsets";
8532 symbols [sindex ++] = "llvm_got_info_offsets";
8534 symbols [sindex ++] = NULL;
8535 symbols [sindex ++] = "mem_end";
8536 symbols [sindex ++] = "image_table";
8537 symbols [sindex ++] = "assembly_guid";
8538 symbols [sindex ++] = "runtime_version";
8539 if (acfg->num_trampoline_got_entries) {
8540 symbols [sindex ++] = "specific_trampolines";
8541 symbols [sindex ++] = "static_rgctx_trampolines";
8542 symbols [sindex ++] = "imt_thunks";
8543 symbols [sindex ++] = "gsharedvt_arg_trampolines";
8545 symbols [sindex ++] = NULL;
8546 symbols [sindex ++] = NULL;
8547 symbols [sindex ++] = NULL;
8548 symbols [sindex ++] = NULL;
8550 if (acfg->aot_opts.static_link) {
8551 symbols [sindex ++] = "globals";
8553 symbols [sindex ++] = NULL;
8555 symbols [sindex ++] = "assembly_name";
8556 symbols [sindex ++] = "plt";
8557 symbols [sindex ++] = "plt_end";
8558 symbols [sindex ++] = "unwind_info";
8559 symbols [sindex ++] = "unbox_trampolines";
8560 symbols [sindex ++] = "unbox_trampolines_end";
8561 symbols [sindex ++] = "unbox_trampoline_addresses";
8562 g_assert (sindex == MONO_AOT_FILE_INFO_NUM_SYMBOLS);
8564 sprintf (symbol, "%smono_aot_file_info", acfg->user_symbol_prefix);
8565 emit_section_change (acfg, ".data", 0);
8566 emit_alignment (acfg, 8);
8567 emit_label (acfg, symbol);
8568 if (!acfg->aot_opts.static_link)
8569 emit_global (acfg, symbol, FALSE);
8571 /* The data emitted here must match MonoAotFileInfo. */
8573 emit_int32 (acfg, info->version);
8574 emit_int32 (acfg, info->dummy);
8577 * We emit pointers to our data structures instead of emitting global symbols which
8578 * point to them, to reduce the number of globals, and because using globals leads to
8579 * various problems (i.e. arm/thumb).
8581 for (i = 0; i < MONO_AOT_FILE_INFO_NUM_SYMBOLS; ++i)
8582 emit_pointer (acfg, symbols [i]);
8584 emit_int32 (acfg, info->plt_got_offset_base);
8585 emit_int32 (acfg, info->got_size);
8586 emit_int32 (acfg, info->plt_size);
8587 emit_int32 (acfg, info->nmethods);
8588 emit_int32 (acfg, info->flags);
8589 emit_int32 (acfg, info->opts);
8590 emit_int32 (acfg, info->simd_opts);
8591 emit_int32 (acfg, info->gc_name_index);
8592 emit_int32 (acfg, info->num_rgctx_fetch_trampolines);
8593 emit_int32 (acfg, info->double_align);
8594 emit_int32 (acfg, info->long_align);
8595 emit_int32 (acfg, info->generic_tramp_num);
8596 emit_int32 (acfg, info->tramp_page_size);
8598 for (i = 0; i < MONO_AOT_TRAMP_NUM; ++i)
8599 emit_int32 (acfg, info->num_trampolines [i]);
8600 for (i = 0; i < MONO_AOT_TRAMP_NUM; ++i)
8601 emit_int32 (acfg, info->trampoline_got_offset_base [i]);
8602 for (i = 0; i < MONO_AOT_TRAMP_NUM; ++i)
8603 emit_int32 (acfg, info->trampoline_size [i]);
8604 for (i = 0; i < MONO_AOT_TRAMP_NUM; ++i)
8605 emit_int32 (acfg, info->tramp_page_code_offsets [i]);
8607 if (acfg->aot_opts.static_link) {
8611 * Emit a global symbol which can be passed by an embedding app to
8612 * mono_aot_register_module (). The symbol points to a pointer to the the file info
8615 sprintf (symbol, "%smono_aot_module_%s_info", acfg->user_symbol_prefix, acfg->image->assembly->aname.name);
8617 /* Get rid of characters which cannot occur in symbols */
8619 for (p = symbol; *p; ++p) {
8620 if (!(isalnum (*p) || *p == '_'))
8623 acfg->static_linking_symbol = g_strdup (symbol);
8624 emit_global_inner (acfg, symbol, FALSE);
8625 emit_alignment (acfg, sizeof (gpointer));
8626 emit_label (acfg, symbol);
8627 emit_pointer_2 (acfg, acfg->user_symbol_prefix, "mono_aot_file_info");
8632 * Emit a structure containing all the information not stored elsewhere.
8635 emit_file_info (MonoAotCompile *acfg)
8638 const char *gc_name;
8640 MonoAotFileInfo *info;
8642 if (acfg->aot_opts.bind_to_runtime_version) {
8643 build_info = mono_get_runtime_build_info ();
8644 emit_string_symbol (acfg, "runtime_version", build_info);
8645 g_free (build_info);
8647 emit_string_symbol (acfg, "runtime_version", "");
8650 emit_string_symbol (acfg, "assembly_guid" , acfg->image->guid);
8652 /* Emit a string holding the assembly name */
8653 emit_string_symbol (acfg, "assembly_name", acfg->image->assembly->aname.name);
8656 * The managed allocators are GC specific, so can't use an AOT image created by one GC
8659 gc_name = mono_gc_get_gc_name ();
8660 gc_name_offset = add_to_blob (acfg, (guint8*)gc_name, strlen (gc_name) + 1);
8662 info = g_new0 (MonoAotFileInfo, 1);
8663 init_aot_file_info (acfg, info, gc_name_offset);
8665 emit_aot_file_info (acfg, info);
8669 emit_blob (MonoAotCompile *acfg)
8673 sprintf (symbol, "blob");
8674 emit_section_change (acfg, RODATA_SECT, 1);
8675 emit_alignment (acfg, 8);
8676 emit_label (acfg, symbol);
8678 emit_bytes (acfg, (guint8*)acfg->blob.data, acfg->blob.index);
8682 emit_objc_selectors (MonoAotCompile *acfg)
8687 if (!acfg->objc_selectors || acfg->objc_selectors->len == 0)
8692 * cat > foo.m << EOF
8695 * return @selector(print:);
8700 mono_img_writer_emit_unset_mode (acfg->w);
8701 g_assert (acfg->fp);
8702 fprintf (acfg->fp, ".section __DATA,__objc_selrefs,literal_pointers,no_dead_strip\n");
8703 fprintf (acfg->fp, ".align 3\n");
8704 for (i = 0; i < acfg->objc_selectors->len; ++i) {
8705 sprintf (symbol, "L_OBJC_SELECTOR_REFERENCES_%d", i);
8706 emit_label (acfg, symbol);
8707 sprintf (symbol, "L_OBJC_METH_VAR_NAME_%d", i);
8708 emit_pointer (acfg, symbol);
8711 fprintf (acfg->fp, ".section __TEXT,__cstring,cstring_literals\n");
8712 for (i = 0; i < acfg->objc_selectors->len; ++i) {
8713 fprintf (acfg->fp, "L_OBJC_METH_VAR_NAME_%d:\n", i);
8714 fprintf (acfg->fp, ".asciz \"%s\"\n", (char*)g_ptr_array_index (acfg->objc_selectors, i));
8717 fprintf (acfg->fp, ".section __DATA,__objc_imageinfo,regular,no_dead_strip\n");
8718 fprintf (acfg->fp, ".align 3\n");
8719 fprintf (acfg->fp, "L_OBJC_IMAGE_INFO:\n");
8720 fprintf (acfg->fp, ".long 0\n");
8721 fprintf (acfg->fp, ".long 16\n");
8725 emit_dwarf_info (MonoAotCompile *acfg)
8727 #ifdef EMIT_DWARF_INFO
8731 /* DIEs for methods */
8732 for (i = 0; i < acfg->nmethods; ++i) {
8733 MonoCompile *cfg = acfg->cfgs [i];
8738 // FIXME: LLVM doesn't define .Lme_...
8739 if (cfg->compile_llvm)
8742 sprintf (symbol2, "%sme_%x", acfg->temp_prefix, i);
8744 mono_dwarf_writer_emit_method (acfg->dwarf, cfg, cfg->method, cfg->asm_symbol, symbol2, cfg->asm_debug_symbol, 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 ()));
8750 collect_methods (MonoAotCompile *acfg)
8753 MonoImage *image = acfg->image;
8755 /* Collect methods */
8756 for (i = 0; i < image->tables [MONO_TABLE_METHOD].rows; ++i) {
8759 guint32 token = MONO_TOKEN_METHOD_DEF | (i + 1);
8761 method = mono_get_method_checked (acfg->image, token, NULL, NULL, &error);
8764 aot_printerrf (acfg, "Failed to load method 0x%x from '%s' due to %s.\n", token, image->name, mono_error_get_message (&error));
8765 aot_printerrf (acfg, "Run with MONO_LOG_LEVEL=debug for more information.\n");
8766 mono_error_cleanup (&error);
8770 /* Load all methods eagerly to skip the slower lazy loading code */
8771 mono_class_setup_methods (method->klass);
8773 if (mono_aot_mode_is_full (&acfg->aot_opts) && method->iflags & METHOD_IMPL_ATTRIBUTE_INTERNAL_CALL) {
8774 /* Compile the wrapper instead */
8775 /* We do this here instead of add_wrappers () because it is easy to do it here */
8776 MonoMethod *wrapper = mono_marshal_get_native_wrapper (method, check_for_pending_exc, TRUE);
8780 /* FIXME: Some mscorlib methods don't have debug info */
8782 if (acfg->aot_opts.soft_debug && !method->wrapper_type) {
8783 if (!((method->flags & METHOD_ATTRIBUTE_PINVOKE_IMPL) ||
8784 (method->iflags & METHOD_IMPL_ATTRIBUTE_RUNTIME) ||
8785 (method->flags & METHOD_ATTRIBUTE_ABSTRACT) ||
8786 (method->iflags & METHOD_IMPL_ATTRIBUTE_INTERNAL_CALL))) {
8787 if (!mono_debug_lookup_method (method)) {
8788 fprintf (stderr, "Method %s has no debug info, probably the .mdb file for the assembly is missing.\n", mono_method_full_name (method, TRUE));
8795 if (method->is_generic || method->klass->generic_container)
8796 /* Compile the ref shared version instead */
8797 method = mini_get_shared_method (method);
8799 /* Since we add the normal methods first, their index will be equal to their zero based token index */
8800 add_method_with_index (acfg, method, i, FALSE);
8801 acfg->method_index ++;
8804 /* gsharedvt methods */
8805 for (mindex = 0; mindex < image->tables [MONO_TABLE_METHOD].rows; ++mindex) {
8808 guint32 token = MONO_TOKEN_METHOD_DEF | (mindex + 1);
8810 if (!(acfg->opts & MONO_OPT_GSHAREDVT))
8813 method = mono_get_method_checked (acfg->image, token, NULL, NULL, &error);
8814 report_loader_error (acfg, &error, "Failed to load method token 0x%x due to %s\n", i, mono_error_get_message (&error));
8816 if (method->is_generic || method->klass->generic_container) {
8817 MonoMethod *gshared;
8819 gshared = mini_get_shared_method_full (method, TRUE, TRUE);
8820 add_extra_method (acfg, gshared);
8824 add_generic_instances (acfg);
8826 if (mono_aot_mode_is_full (&acfg->aot_opts))
8827 add_wrappers (acfg);
8832 compile_methods (MonoAotCompile *acfg)
8836 if (acfg->aot_opts.nthreads > 0) {
8841 gpointer *user_data;
8842 MonoMethod **methods;
8844 methods_len = acfg->methods->len;
8846 len = acfg->methods->len / acfg->aot_opts.nthreads;
8849 * Partition the list of methods into fragments, and hand it to threads to
8852 threads = g_ptr_array_new ();
8853 /* Make a copy since acfg->methods is modified by compile_method () */
8854 methods = g_new0 (MonoMethod*, methods_len);
8855 //memcpy (methods, g_ptr_array_index (acfg->methods, 0), sizeof (MonoMethod*) * methods_len);
8856 for (i = 0; i < methods_len; ++i)
8857 methods [i] = g_ptr_array_index (acfg->methods, i);
8859 while (i < methods_len) {
8860 frag = g_ptr_array_new ();
8861 for (j = 0; j < len; ++j) {
8862 if (i < methods_len) {
8863 g_ptr_array_add (frag, methods [i]);
8868 user_data = g_new0 (gpointer, 3);
8869 user_data [0] = mono_domain_get ();
8870 user_data [1] = acfg;
8871 user_data [2] = frag;
8873 handle = mono_threads_create_thread ((gpointer)compile_thread_main, user_data, 0, 0, NULL);
8874 g_ptr_array_add (threads, handle);
8878 for (i = 0; i < threads->len; ++i) {
8879 WaitForSingleObjectEx (g_ptr_array_index (threads, i), INFINITE, FALSE);
8885 /* Compile methods added by compile_method () or all methods if nthreads == 0 */
8886 for (i = methods_len; i < acfg->methods->len; ++i) {
8887 /* This can new methods to acfg->methods */
8888 compile_method (acfg, g_ptr_array_index (acfg->methods, i));
8893 compile_asm (MonoAotCompile *acfg)
8895 char *command, *objfile;
8896 char *outfile_name, *tmp_outfile_name, *llvm_ofile;
8897 const char *tool_prefix = acfg->aot_opts.tool_prefix ? acfg->aot_opts.tool_prefix : "";
8898 char *ld_flags = acfg->aot_opts.ld_flags ? acfg->aot_opts.ld_flags : g_strdup("");
8900 #if defined(TARGET_AMD64) && !defined(TARGET_MACH)
8901 #define AS_OPTIONS "--64"
8902 #elif defined(TARGET_POWERPC64)
8903 #define AS_OPTIONS "-a64 -mppc64"
8904 #define LD_OPTIONS "-m elf64ppc"
8905 #elif defined(sparc) && SIZEOF_VOID_P == 8
8906 #define AS_OPTIONS "-xarch=v9"
8907 #elif defined(TARGET_X86) && defined(TARGET_MACH) && !defined(__native_client_codegen__)
8908 #define AS_OPTIONS "-arch i386"
8910 #define AS_OPTIONS ""
8913 #ifdef __native_client_codegen__
8914 #if defined(TARGET_AMD64)
8915 #define AS_NAME "nacl64-as"
8917 #define AS_NAME "nacl-as"
8919 #elif defined(TARGET_OSX)
8920 #define AS_NAME "clang"
8922 #define AS_NAME "as"
8926 #define LD_OPTIONS ""
8930 #define LD_NAME "ld -shared -G"
8931 #elif defined(__ppc__) && defined(TARGET_MACH)
8932 #define LD_NAME "gcc -dynamiclib"
8933 #elif defined(TARGET_AMD64) && defined(TARGET_MACH)
8934 #define LD_NAME "clang --shared"
8935 #elif defined(TARGET_WIN32) && !defined(TARGET_ANDROID)
8936 #define LD_NAME "gcc -shared --dll"
8937 #elif defined(TARGET_X86) && defined(TARGET_MACH) && !defined(__native_client_codegen__)
8938 #define LD_NAME "clang -m32 -dynamiclib"
8939 #elif defined(TARGET_ARM) && !defined(TARGET_ANDROID)
8940 #define LD_NAME "gcc --shared"
8943 if (acfg->aot_opts.asm_only) {
8944 aot_printf (acfg, "Output file: '%s'.\n", acfg->tmpfname);
8945 if (acfg->aot_opts.static_link)
8946 aot_printf (acfg, "Linking symbol: '%s'.\n", acfg->static_linking_symbol);
8948 aot_printf (acfg, "LLVM output file: '%s'.\n", acfg->llvm_sfile);
8952 if (acfg->aot_opts.static_link) {
8953 if (acfg->aot_opts.outfile)
8954 objfile = g_strdup_printf ("%s", acfg->aot_opts.outfile);
8956 objfile = g_strdup_printf ("%s.o", acfg->image->name);
8958 objfile = g_strdup_printf ("%s.o", acfg->tmpfname);
8962 g_string_append (acfg->as_args, "-c -x assembler");
8965 command = g_strdup_printf ("\"%s%s\" %s %s -o %s %s", tool_prefix, AS_NAME, AS_OPTIONS, acfg->as_args ? acfg->as_args->str : "", objfile, acfg->tmpfname);
8966 aot_printf (acfg, "Executing the native assembler: %s\n", command);
8967 if (execute_system (command) != 0) {
8973 if (acfg->llvm && !acfg->llvm_owriter) {
8974 command = g_strdup_printf ("\"%s%s\" %s %s -o %s %s", tool_prefix, AS_NAME, AS_OPTIONS, acfg->as_args ? acfg->as_args->str : "", acfg->llvm_ofile, acfg->llvm_sfile);
8975 aot_printf (acfg, "Executing the native assembler: %s\n", command);
8976 if (execute_system (command) != 0) {
8985 if (acfg->aot_opts.static_link) {
8986 aot_printf (acfg, "Output file: '%s'.\n", objfile);
8987 aot_printf (acfg, "Linking symbol: '%s'.\n", acfg->static_linking_symbol);
8992 if (acfg->aot_opts.outfile)
8993 outfile_name = g_strdup_printf ("%s", acfg->aot_opts.outfile);
8995 outfile_name = g_strdup_printf ("%s%s", acfg->image->name, MONO_SOLIB_EXT);
8997 tmp_outfile_name = g_strdup_printf ("%s.tmp", outfile_name);
9000 llvm_ofile = g_strdup (acfg->llvm_ofile);
9002 llvm_ofile = g_strdup ("");
9005 /* replace the ; flags separators with spaces */
9006 g_strdelimit (ld_flags, ";", ' ');
9009 command = g_strdup_printf ("%s -o %s %s %s.o %s", LD_NAME, tmp_outfile_name, llvm_ofile, acfg->tmpfname, ld_flags);
9011 command = g_strdup_printf ("\"%sld\" %s -shared -o %s %s %s.o %s", tool_prefix, LD_OPTIONS, tmp_outfile_name, llvm_ofile,
9012 acfg->tmpfname, ld_flags);
9014 aot_printf (acfg, "Executing the native linker: %s\n", command);
9015 if (execute_system (command) != 0) {
9016 g_free (tmp_outfile_name);
9017 g_free (outfile_name);
9026 /*com = g_strdup_printf ("strip --strip-unneeded %s%s", acfg->image->name, MONO_SOLIB_EXT);
9027 printf ("Stripping the binary: %s\n", com);
9028 execute_system (com);
9031 #if defined(TARGET_ARM) && !defined(TARGET_MACH)
9033 * gas generates 'mapping symbols' each time code and data is mixed, which
9034 * happens a lot in emit_and_reloc_code (), so we need to get rid of them.
9036 command = g_strdup_printf ("\"%sstrip\" --strip-symbol=\\$a --strip-symbol=\\$d %s", tool_prefix, tmp_outfile_name);
9037 aot_printf (acfg, "Stripping the binary: %s\n", command);
9038 if (execute_system (command) != 0) {
9039 g_free (tmp_outfile_name);
9040 g_free (outfile_name);
9047 rename (tmp_outfile_name, outfile_name);
9049 #if defined(TARGET_MACH)
9050 command = g_strdup_printf ("dsymutil %s", outfile_name);
9051 aot_printf (acfg, "Executing dsymutil: %s\n", command);
9052 if (execute_system (command) != 0) {
9057 if (!acfg->aot_opts.save_temps)
9060 g_free (tmp_outfile_name);
9061 g_free (outfile_name);
9064 if (acfg->aot_opts.save_temps)
9065 aot_printf (acfg, "Retained input file.\n");
9067 unlink (acfg->tmpfname);
9072 static void init_got_info (GotInfo *info)
9076 info->patch_to_got_offset = g_hash_table_new (mono_patch_info_hash, mono_patch_info_equal);
9077 info->patch_to_got_offset_by_type = g_new0 (GHashTable*, MONO_PATCH_INFO_NUM);
9078 for (i = 0; i < MONO_PATCH_INFO_NUM; ++i)
9079 info->patch_to_got_offset_by_type [i] = g_hash_table_new (mono_patch_info_hash, mono_patch_info_equal);
9080 info->got_patches = g_ptr_array_new ();
9083 static MonoAotCompile*
9084 acfg_create (MonoAssembly *ass, guint32 opts)
9086 MonoImage *image = ass->image;
9087 MonoAotCompile *acfg;
9089 acfg = g_new0 (MonoAotCompile, 1);
9090 acfg->methods = g_ptr_array_new ();
9091 acfg->method_indexes = g_hash_table_new (NULL, NULL);
9092 acfg->method_depth = g_hash_table_new (NULL, NULL);
9093 acfg->plt_offset_to_entry = g_hash_table_new (NULL, NULL);
9094 acfg->patch_to_plt_entry = g_new0 (GHashTable*, MONO_PATCH_INFO_NUM);
9095 acfg->method_to_cfg = g_hash_table_new (NULL, NULL);
9096 acfg->token_info_hash = g_hash_table_new_full (NULL, NULL, NULL, NULL);
9097 acfg->method_to_pinvoke_import = g_hash_table_new_full (NULL, NULL, NULL, g_free);
9098 acfg->image_hash = g_hash_table_new (NULL, NULL);
9099 acfg->image_table = g_ptr_array_new ();
9100 acfg->globals = g_ptr_array_new ();
9101 acfg->image = image;
9103 /* TODO: Write out set of SIMD instructions used, rather than just those available */
9104 acfg->simd_opts = mono_arch_cpu_enumerate_simd_versions ();
9105 acfg->mempool = mono_mempool_new ();
9106 acfg->extra_methods = g_ptr_array_new ();
9107 acfg->unwind_info_offsets = g_hash_table_new (NULL, NULL);
9108 acfg->unwind_ops = g_ptr_array_new ();
9109 acfg->method_label_hash = g_hash_table_new_full (g_str_hash, g_str_equal, g_free, NULL);
9110 acfg->method_order = g_ptr_array_new ();
9111 acfg->export_names = g_hash_table_new (NULL, NULL);
9112 acfg->klass_blob_hash = g_hash_table_new (NULL, NULL);
9113 acfg->method_blob_hash = g_hash_table_new (NULL, NULL);
9114 acfg->plt_entry_debug_sym_cache = g_hash_table_new (g_str_hash, g_str_equal);
9115 mono_mutex_init_recursive (&acfg->mutex);
9117 init_got_info (&acfg->got_info);
9118 init_got_info (&acfg->llvm_got_info);
9124 got_info_free (GotInfo *info)
9128 for (i = 0; i < MONO_PATCH_INFO_NUM; ++i)
9129 g_hash_table_destroy (info->patch_to_got_offset_by_type [i]);
9130 g_free (info->patch_to_got_offset_by_type);
9131 g_hash_table_destroy (info->patch_to_got_offset);
9132 g_ptr_array_free (info->got_patches, TRUE);
9136 acfg_free (MonoAotCompile *acfg)
9140 mono_img_writer_destroy (acfg->w);
9141 for (i = 0; i < acfg->nmethods; ++i)
9143 g_free (acfg->cfgs [i]);
9144 g_free (acfg->cfgs);
9145 g_free (acfg->static_linking_symbol);
9146 g_free (acfg->got_symbol);
9147 g_free (acfg->plt_symbol);
9148 g_ptr_array_free (acfg->methods, TRUE);
9149 g_ptr_array_free (acfg->image_table, TRUE);
9150 g_ptr_array_free (acfg->globals, TRUE);
9151 g_ptr_array_free (acfg->unwind_ops, TRUE);
9152 g_hash_table_destroy (acfg->method_indexes);
9153 g_hash_table_destroy (acfg->method_depth);
9154 g_hash_table_destroy (acfg->plt_offset_to_entry);
9155 for (i = 0; i < MONO_PATCH_INFO_NUM; ++i) {
9156 if (acfg->patch_to_plt_entry [i])
9157 g_hash_table_destroy (acfg->patch_to_plt_entry [i]);
9159 g_free (acfg->patch_to_plt_entry);
9160 g_hash_table_destroy (acfg->method_to_cfg);
9161 g_hash_table_destroy (acfg->token_info_hash);
9162 g_hash_table_destroy (acfg->method_to_pinvoke_import);
9163 g_hash_table_destroy (acfg->image_hash);
9164 g_hash_table_destroy (acfg->unwind_info_offsets);
9165 g_hash_table_destroy (acfg->method_label_hash);
9166 g_hash_table_destroy (acfg->export_names);
9167 g_hash_table_destroy (acfg->plt_entry_debug_sym_cache);
9168 g_hash_table_destroy (acfg->klass_blob_hash);
9169 g_hash_table_destroy (acfg->method_blob_hash);
9170 got_info_free (&acfg->got_info);
9171 got_info_free (&acfg->llvm_got_info);
9172 mono_mempool_destroy (acfg->mempool);
9176 #define WRAPPER(e,n) n,
9177 static const char* const
9178 wrapper_type_names [MONO_WRAPPER_NUM + 1] = {
9179 #include "mono/metadata/wrapper-types.h"
9183 static G_GNUC_UNUSED const char*
9184 get_wrapper_type_name (int type)
9186 return wrapper_type_names [type];
9192 static void aot_dump (MonoAotCompile *acfg)
9198 mono_json_writer_init (&writer);
9200 mono_json_writer_object_begin(&writer);
9203 mono_json_writer_indent (&writer);
9204 mono_json_writer_object_key(&writer, "methods");
9205 mono_json_writer_array_begin (&writer);
9208 for (i = 0; i < acfg->nmethods; ++i) {
9213 cfg = acfg->cfgs [i];
9217 method = cfg->orig_method;
9219 mono_json_writer_indent (&writer);
9220 mono_json_writer_object_begin(&writer);
9222 mono_json_writer_indent (&writer);
9223 mono_json_writer_object_key(&writer, "name");
9224 mono_json_writer_printf (&writer, "\"%s\",\n", method->name);
9226 mono_json_writer_indent (&writer);
9227 mono_json_writer_object_key(&writer, "signature");
9228 mono_json_writer_printf (&writer, "\"%s\",\n", mono_method_full_name (method,
9229 /*signature=*/TRUE));
9231 mono_json_writer_indent (&writer);
9232 mono_json_writer_object_key(&writer, "code_size");
9233 mono_json_writer_printf (&writer, "\"%d\",\n", cfg->code_size);
9235 klass = method->klass;
9237 mono_json_writer_indent (&writer);
9238 mono_json_writer_object_key(&writer, "class");
9239 mono_json_writer_printf (&writer, "\"%s\",\n", klass->name);
9241 mono_json_writer_indent (&writer);
9242 mono_json_writer_object_key(&writer, "namespace");
9243 mono_json_writer_printf (&writer, "\"%s\",\n", klass->name_space);
9245 mono_json_writer_indent (&writer);
9246 mono_json_writer_object_key(&writer, "wrapper_type");
9247 mono_json_writer_printf (&writer, "\"%s\",\n", get_wrapper_type_name(method->wrapper_type));
9249 mono_json_writer_indent_pop (&writer);
9250 mono_json_writer_indent (&writer);
9251 mono_json_writer_object_end (&writer);
9252 mono_json_writer_printf (&writer, ",\n");
9255 mono_json_writer_indent_pop (&writer);
9256 mono_json_writer_indent (&writer);
9257 mono_json_writer_array_end (&writer);
9258 mono_json_writer_printf (&writer, ",\n");
9262 mono_json_writer_indent_push (&writer);
9263 mono_json_writer_indent (&writer);
9264 mono_json_writer_object_key(&writer, "plt");
9265 mono_json_writer_array_begin (&writer);
9267 for (i = 0; i < acfg->plt_offset; ++i) {
9268 MonoPltEntry *plt_entry = NULL;
9273 * The first plt entry is unused.
9277 plt_entry = g_hash_table_lookup (acfg->plt_offset_to_entry, GUINT_TO_POINTER (i));
9280 mono_json_writer_indent (&writer);
9281 mono_json_writer_printf (&writer, "{ ");
9282 mono_json_writer_object_key(&writer, "symbol");
9283 mono_json_writer_printf (&writer, "\"%s\" },\n", plt_entry->symbol);
9286 mono_json_writer_indent_pop (&writer);
9287 mono_json_writer_indent (&writer);
9288 mono_json_writer_array_end (&writer);
9289 mono_json_writer_printf (&writer, ",\n");
9294 mono_json_writer_indent_push (&writer);
9295 mono_json_writer_indent (&writer);
9296 mono_json_writer_object_key(&writer, "got");
9297 mono_json_writer_array_begin (&writer);
9299 mono_json_writer_indent_push (&writer);
9300 for (i = 0; i < acfg->got_info.got_patches->len; ++i) {
9301 MonoJumpInfo *ji = g_ptr_array_index (acfg->got_info.got_patches, i);
9303 mono_json_writer_indent (&writer);
9304 mono_json_writer_printf (&writer, "{ ");
9305 mono_json_writer_object_key(&writer, "patch_name");
9306 mono_json_writer_printf (&writer, "\"%s\" },\n", get_patch_name (ji->type));
9309 mono_json_writer_indent_pop (&writer);
9310 mono_json_writer_indent (&writer);
9311 mono_json_writer_array_end (&writer);
9312 mono_json_writer_printf (&writer, ",\n");
9315 mono_json_writer_indent_pop (&writer);
9316 mono_json_writer_indent (&writer);
9317 mono_json_writer_object_end (&writer);
9319 dumpname = g_strdup_printf ("%s.json", g_path_get_basename (acfg->image->name));
9320 dumpfile = fopen (dumpname, "w+");
9323 fprintf (dumpfile, "%s", writer.text->str);
9326 mono_json_writer_destroy (&writer);
9330 mono_compile_assembly (MonoAssembly *ass, guint32 opts, const char *aot_options)
9332 MonoImage *image = ass->image;
9335 MonoAotCompile *acfg;
9336 char *outfile_name, *tmp_outfile_name, *p;
9337 char llvm_stats_msg [256];
9341 acfg = acfg_create (ass, opts);
9343 memset (&acfg->aot_opts, 0, sizeof (acfg->aot_opts));
9344 acfg->aot_opts.write_symbols = TRUE;
9345 acfg->aot_opts.ntrampolines = 1024;
9346 acfg->aot_opts.nrgctx_trampolines = 1024;
9347 acfg->aot_opts.nimt_trampolines = 128;
9348 acfg->aot_opts.nrgctx_fetch_trampolines = 128;
9349 acfg->aot_opts.ngsharedvt_arg_trampolines = 128;
9350 acfg->aot_opts.llvm_path = g_strdup ("");
9351 acfg->aot_opts.temp_path = g_strdup ("");
9353 acfg->aot_opts.use_trampolines_page = TRUE;
9356 mono_aot_parse_options (aot_options, &acfg->aot_opts);
9358 if (acfg->aot_opts.logfile) {
9359 acfg->logfile = fopen (acfg->aot_opts.logfile, "a+");
9362 if (acfg->aot_opts.static_link)
9363 acfg->aot_opts.autoreg = TRUE;
9365 //acfg->aot_opts.print_skipped_methods = TRUE;
9367 #if !defined(MONO_ARCH_GSHAREDVT_SUPPORTED) || !defined(ENABLE_GSHAREDVT)
9368 if (opts & MONO_OPT_GSHAREDVT) {
9369 aot_printerrf (acfg, "-O=gsharedvt not supported on this platform.\n");
9374 aot_printf (acfg, "Mono Ahead of Time compiler - compiling assembly %s\n", image->name);
9376 #ifndef MONO_ARCH_HAVE_FULL_AOT_TRAMPOLINES
9377 if (mono_aot_mode_is_full (&acfg->aot_opts)) {
9378 aot_printerrf (acfg, "--aot=full is not supported on this platform.\n");
9383 if (acfg->aot_opts.direct_pinvoke && !acfg->aot_opts.static_link) {
9384 aot_printerrf (acfg, "The 'direct-pinvoke' AOT option also requires the 'static' AOT option.\n");
9388 if (acfg->aot_opts.static_link)
9389 acfg->aot_opts.asm_writer = TRUE;
9391 if (acfg->aot_opts.soft_debug) {
9392 MonoDebugOptions *opt = mini_get_debug_options ();
9394 opt->mdb_optimizations = TRUE;
9395 opt->gen_sdb_seq_points = TRUE;
9397 if (!mono_debug_enabled ()) {
9398 aot_printerrf (acfg, "The soft-debug AOT option requires the --debug option.\n");
9401 acfg->flags |= MONO_AOT_FILE_FLAG_DEBUG;
9404 if (mono_use_llvm || acfg->aot_opts.llvm) {
9406 acfg->aot_opts.asm_writer = TRUE;
9407 acfg->flags |= MONO_AOT_FILE_FLAG_WITH_LLVM;
9409 if (acfg->aot_opts.soft_debug) {
9410 aot_printerrf (acfg, "The 'soft-debug' option is not supported when compiling with LLVM.\n");
9416 if (acfg->aot_opts.asm_only && !acfg->aot_opts.llvm_outfile) {
9417 aot_printerrf (acfg, "Compiling with LLVM and the asm-only option requires the llvm-outputfile= option.");
9422 * Emit all LLVM code into a separate assembly/object file and link with it
9425 if (!acfg->aot_opts.asm_only) {
9426 acfg->llvm_owriter = TRUE;
9427 } else if (acfg->aot_opts.llvm_outfile) {
9428 int len = strlen (acfg->aot_opts.llvm_outfile);
9430 if (len >= 2 && acfg->aot_opts.llvm_outfile [len - 2] == '.' && acfg->aot_opts.llvm_outfile [len - 1] == 'o')
9431 acfg->llvm_owriter = TRUE;
9435 if (mono_aot_mode_is_full (&acfg->aot_opts))
9436 acfg->flags |= MONO_AOT_FILE_FLAG_FULL_AOT;
9438 if (acfg->aot_opts.instances_logfile_path) {
9439 acfg->instances_logfile = fopen (acfg->aot_opts.instances_logfile_path, "w");
9440 if (!acfg->instances_logfile) {
9441 aot_printerrf (acfg, "Unable to create logfile: '%s'.\n", acfg->aot_opts.instances_logfile_path);
9446 load_profile_files (acfg);
9448 acfg->num_trampolines [MONO_AOT_TRAMP_SPECIFIC] = mono_aot_mode_is_full (&acfg->aot_opts) ? acfg->aot_opts.ntrampolines : 0;
9449 #ifdef MONO_ARCH_GSHARED_SUPPORTED
9450 acfg->num_trampolines [MONO_AOT_TRAMP_STATIC_RGCTX] = mono_aot_mode_is_full (&acfg->aot_opts) ? acfg->aot_opts.nrgctx_trampolines : 0;
9452 acfg->num_trampolines [MONO_AOT_TRAMP_IMT_THUNK] = mono_aot_mode_is_full (&acfg->aot_opts) ? acfg->aot_opts.nimt_trampolines : 0;
9453 #ifdef MONO_ARCH_GSHAREDVT_SUPPORTED
9454 if (acfg->opts & MONO_OPT_GSHAREDVT)
9455 acfg->num_trampolines [MONO_AOT_TRAMP_GSHAREDVT_ARG] = mono_aot_mode_is_full (&acfg->aot_opts) ? acfg->aot_opts.ngsharedvt_arg_trampolines : 0;
9458 acfg->temp_prefix = mono_img_writer_get_temp_label_prefix (NULL);
9462 if (acfg->llvm && acfg->thumb_mixed)
9463 acfg->flags |= MONO_AOT_FILE_FLAG_LLVM_THUMB;
9465 acfg->assembly_name_sym = g_strdup (acfg->image->assembly->aname.name);
9466 /* Get rid of characters which cannot occur in symbols */
9467 for (p = acfg->assembly_name_sym; *p; ++p) {
9468 if (!(isalnum (*p) || *p == '_'))
9472 acfg->global_prefix = g_strdup_printf ("mono_aot_%s", acfg->assembly_name_sym);
9473 acfg->plt_symbol = g_strdup_printf ("%s_plt", acfg->global_prefix);
9474 acfg->got_symbol = g_strdup_printf ("%s_got", acfg->global_prefix);
9476 acfg->llvm_got_symbol = g_strdup_printf ("%s_llvm_got", acfg->global_prefix);
9477 acfg->llvm_eh_frame_symbol = g_strdup_printf ("%s_eh_frame", acfg->global_prefix);
9480 acfg->method_index = 1;
9482 if (mono_aot_mode_is_full (&acfg->aot_opts))
9483 mono_set_partial_sharing_supported (TRUE);
9485 res = collect_methods (acfg);
9489 acfg->cfgs_size = acfg->methods->len + 32;
9490 acfg->cfgs = g_new0 (MonoCompile*, acfg->cfgs_size);
9492 /* PLT offset 0 is reserved for the PLT trampoline */
9493 acfg->plt_offset = 1;
9498 mono_llvm_create_aot_module (acfg->global_prefix, TRUE);
9502 /* GOT offset 0 is reserved for the address of the current assembly */
9506 ji = mono_mempool_alloc0 (acfg->mempool, sizeof (MonoJumpInfo));
9507 ji->type = MONO_PATCH_INFO_IMAGE;
9508 ji->data.image = acfg->image;
9510 get_got_offset (acfg, FALSE, ji);
9511 get_got_offset (acfg, TRUE, ji);
9513 /* Slot 1 is reserved for the mscorlib got addr */
9514 ji = mono_mempool_alloc0 (acfg->mempool, sizeof (MonoJumpInfo));
9515 ji->type = MONO_PATCH_INFO_MSCORLIB_GOT_ADDR;
9516 get_got_offset (acfg, FALSE, ji);
9517 get_got_offset (acfg, TRUE, ji);
9519 /* This is very common */
9520 ji = mono_mempool_alloc0 (acfg->mempool, sizeof (MonoJumpInfo));
9521 ji->type = MONO_PATCH_INFO_GC_CARD_TABLE_ADDR;
9522 get_got_offset (acfg, FALSE, ji);
9523 get_got_offset (acfg, TRUE, ji);
9525 ji = mono_mempool_alloc0 (acfg->mempool, sizeof (MonoJumpInfo));
9526 ji->type = MONO_PATCH_INFO_GC_NURSERY_START;
9527 get_got_offset (acfg, FALSE, ji);
9528 get_got_offset (acfg, TRUE, ji);
9530 ji = mono_mempool_alloc0 (acfg->mempool, sizeof (MonoJumpInfo));
9531 ji->type = MONO_PATCH_INFO_JIT_TLS_ID;
9532 get_got_offset (acfg, FALSE, ji);
9533 get_got_offset (acfg, TRUE, ji);
9538 compile_methods (acfg);
9542 acfg->stats.jit_time = TV_ELAPSED (atv, btv);
9550 if (acfg->aot_opts.asm_only) {
9551 if (acfg->aot_opts.outfile) {
9552 acfg->tmpfname = g_strdup_printf ("%s", acfg->aot_opts.outfile);
9553 acfg->tmpbasename = g_strdup (acfg->tmpfname);
9555 acfg->tmpbasename = g_strdup_printf ("%s", acfg->image->name);
9556 acfg->tmpfname = g_strdup_printf ("%s.s", acfg->tmpbasename);
9558 g_assert (acfg->aot_opts.llvm_outfile);
9559 acfg->llvm_sfile = g_strdup (acfg->aot_opts.llvm_outfile);
9560 if (acfg->llvm_owriter)
9561 acfg->llvm_ofile = g_strdup (acfg->aot_opts.llvm_outfile);
9563 acfg->llvm_sfile = g_strdup (acfg->aot_opts.llvm_outfile);
9565 acfg->tmpbasename = (strcmp (acfg->aot_opts.temp_path, "") == 0) ?
9566 g_strdup_printf ("%s", "temp") :
9567 g_build_filename (acfg->aot_opts.temp_path, "temp", NULL);
9569 acfg->tmpfname = g_strdup_printf ("%s.s", acfg->tmpbasename);
9570 acfg->llvm_sfile = g_strdup_printf ("%s-llvm.s", acfg->tmpbasename);
9571 acfg->llvm_ofile = g_strdup_printf ("%s-llvm.o", acfg->tmpbasename);
9574 res = emit_llvm_file (acfg);
9580 if (!acfg->aot_opts.asm_only && !acfg->aot_opts.asm_writer && mono_bin_writer_supported ()) {
9581 if (acfg->aot_opts.outfile)
9582 outfile_name = g_strdup_printf ("%s", acfg->aot_opts.outfile);
9584 outfile_name = g_strdup_printf ("%s%s", acfg->image->name, MONO_SOLIB_EXT);
9587 * Can't use g_file_open_tmp () as it will be deleted at exit, and
9588 * it might be in another file system so the rename () won't work.
9590 tmp_outfile_name = g_strdup_printf ("%s.tmp", outfile_name);
9592 acfg->fp = fopen (tmp_outfile_name, "w");
9594 aot_printf (acfg, "Unable to create temporary file '%s': %s\n", tmp_outfile_name, strerror (errno));
9598 acfg->w = mono_img_writer_create (acfg->fp, TRUE);
9599 acfg->use_bin_writer = TRUE;
9601 if (acfg->aot_opts.asm_only) {
9602 if (acfg->aot_opts.outfile)
9603 acfg->tmpfname = g_strdup_printf ("%s", acfg->aot_opts.outfile);
9605 acfg->tmpfname = g_strdup_printf ("%s.s", acfg->image->name);
9606 acfg->fp = fopen (acfg->tmpfname, "w+");
9608 int i = g_file_open_tmp ("mono_aot_XXXXXX", &acfg->tmpfname, NULL);
9609 acfg->fp = fdopen (i, "w+");
9611 if (acfg->fp == 0) {
9612 aot_printerrf (acfg, "Unable to open file '%s': %s\n", acfg->tmpfname, strerror (errno));
9615 acfg->w = mono_img_writer_create (acfg->fp, FALSE);
9617 tmp_outfile_name = NULL;
9618 outfile_name = NULL;
9621 /* Compute symbols for methods */
9622 for (i = 0; i < acfg->nmethods; ++i) {
9623 if (acfg->cfgs [i]) {
9624 MonoCompile *cfg = acfg->cfgs [i];
9625 int method_index = get_method_index (acfg, cfg->orig_method);
9627 if (COMPILE_LLVM (cfg))
9628 cfg->asm_symbol = g_strdup_printf ("%s%s", acfg->llvm_label_prefix, cfg->llvm_method_name);
9629 else if (acfg->global_symbols || acfg->llvm)
9630 cfg->asm_symbol = get_debug_sym (cfg->orig_method, "", acfg->method_label_hash);
9632 cfg->asm_symbol = g_strdup_printf ("%s%sm_%x", acfg->temp_prefix, acfg->llvm_label_prefix, method_index);
9633 cfg->asm_debug_symbol = cfg->asm_symbol;
9637 if (acfg->aot_opts.dwarf_debug && acfg->aot_opts.asm_only && acfg->aot_opts.gnu_asm) {
9639 * CLANG supports GAS .file/.loc directives, so emit line number information this way
9640 * FIXME: CLANG only emits line number info for .loc directives followed by assembly, not
9643 //acfg->gas_line_numbers = TRUE;
9646 if (!acfg->aot_opts.nodebug || acfg->aot_opts.dwarf_debug) {
9647 if (acfg->aot_opts.dwarf_debug && !mono_debug_enabled ()) {
9648 aot_printerrf (acfg, "The dwarf AOT option requires the --debug option.\n");
9651 acfg->dwarf = mono_dwarf_writer_create (acfg->w, NULL, 0, FALSE, !acfg->gas_line_numbers);
9654 mono_img_writer_emit_start (acfg->w);
9657 mono_dwarf_writer_emit_base_info (acfg->dwarf, g_path_get_basename (acfg->image->name), mono_unwind_get_cie_program ());
9663 emit_extra_methods (acfg);
9665 emit_trampolines (acfg);
9667 emit_class_name_table (acfg);
9669 emit_got_info (acfg, FALSE);
9671 emit_got_info (acfg, TRUE);
9673 emit_exception_info (acfg);
9675 emit_unwind_info (acfg);
9677 emit_class_info (acfg);
9681 emit_image_table (acfg);
9685 emit_file_info (acfg);
9689 emit_objc_selectors (acfg);
9691 emit_globals (acfg);
9693 emit_autoreg (acfg);
9696 emit_dwarf_info (acfg);
9697 mono_dwarf_writer_close (acfg->dwarf);
9700 emit_mem_end (acfg);
9702 if (acfg->need_pt_gnu_stack) {
9703 /* This is required so the .so doesn't have an executable stack */
9704 /* The bin writer already emits this */
9705 if (!acfg->use_bin_writer)
9706 fprintf (acfg->fp, "\n.section .note.GNU-stack,\"\",@progbits\n");
9711 acfg->stats.gen_time = TV_ELAPSED (atv, btv);
9714 sprintf (llvm_stats_msg, ", LLVM: %d (%d%%)", acfg->stats.llvm_count, acfg->stats.mcount ? (acfg->stats.llvm_count * 100) / acfg->stats.mcount : 100);
9716 strcpy (llvm_stats_msg, "");
9718 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;
9720 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",
9721 (int)acfg->stats.code_size, (int)(acfg->stats.code_size * 100 / all_sizes),
9722 (int)acfg->stats.info_size, (int)(acfg->stats.info_size * 100 / all_sizes),
9723 (int)acfg->stats.ex_info_size, (int)(acfg->stats.ex_info_size * 100 / all_sizes),
9724 (int)acfg->stats.unwind_info_size, (int)(acfg->stats.unwind_info_size * 100 / all_sizes),
9725 (int)acfg->stats.class_info_size, (int)(acfg->stats.class_info_size * 100 / all_sizes),
9726 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,
9727 (int)acfg->stats.got_info_size, (int)(acfg->stats.got_info_size * 100 / all_sizes),
9728 (int)acfg->stats.offsets_size, (int)(acfg->stats.offsets_size * 100 / all_sizes),
9729 (int)(acfg->got_offset * sizeof (gpointer)));
9730 aot_printf (acfg, "Compiled: %d/%d (%d%%)%s, No GOT slots: %d (%d%%), Direct calls: %d (%d%%)\n",
9731 acfg->stats.ccount, acfg->stats.mcount, acfg->stats.mcount ? (acfg->stats.ccount * 100) / acfg->stats.mcount : 100,
9733 acfg->stats.methods_without_got_slots, acfg->stats.mcount ? (acfg->stats.methods_without_got_slots * 100) / acfg->stats.mcount : 100,
9734 acfg->stats.direct_calls, acfg->stats.all_calls ? (acfg->stats.direct_calls * 100) / acfg->stats.all_calls : 100);
9735 if (acfg->stats.genericcount)
9736 aot_printf (acfg, "%d methods are generic (%d%%)\n", acfg->stats.genericcount, acfg->stats.mcount ? (acfg->stats.genericcount * 100) / acfg->stats.mcount : 100);
9737 if (acfg->stats.abscount)
9738 aot_printf (acfg, "%d methods contain absolute addresses (%d%%)\n", acfg->stats.abscount, acfg->stats.mcount ? (acfg->stats.abscount * 100) / acfg->stats.mcount : 100);
9739 if (acfg->stats.lmfcount)
9740 aot_printf (acfg, "%d methods contain lmf pointers (%d%%)\n", acfg->stats.lmfcount, acfg->stats.mcount ? (acfg->stats.lmfcount * 100) / acfg->stats.mcount : 100);
9741 if (acfg->stats.ocount)
9742 aot_printf (acfg, "%d methods have other problems (%d%%)\n", acfg->stats.ocount, acfg->stats.mcount ? (acfg->stats.ocount * 100) / acfg->stats.mcount : 100);
9745 res = mono_img_writer_emit_writeout (acfg->w);
9750 if (acfg->use_bin_writer) {
9751 int err = rename (tmp_outfile_name, outfile_name);
9754 aot_printf (acfg, "Unable to rename '%s' to '%s': %s\n", tmp_outfile_name, outfile_name, strerror (errno));
9758 res = compile_asm (acfg);
9765 acfg->stats.link_time = TV_ELAPSED (atv, btv);
9767 if (acfg->aot_opts.stats) {
9770 aot_printf (acfg, "GOT slot distribution:\n");
9771 for (i = 0; i < MONO_PATCH_INFO_NONE; ++i)
9772 if (acfg->stats.got_slot_types [i])
9773 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]);
9776 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);
9778 if (acfg->aot_opts.dump_json)
9791 mono_aot_readonly_field_override (MonoClassField *field)
9797 mono_compile_assembly (MonoAssembly *ass, guint32 opts, const char *aot_options)