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-internals.h>
45 #include <mono/metadata/mempool-internals.h>
46 #include <mono/metadata/mono-endian.h>
47 #include <mono/metadata/threads-types.h>
48 #include <mono/utils/mono-logger-internals.h>
49 #include <mono/utils/mono-compiler.h>
50 #include <mono/utils/mono-time.h>
51 #include <mono/utils/mono-mmap.h>
52 #include <mono/utils/json.h>
54 #include "aot-compiler.h"
55 #include "seq-points.h"
56 #include "image-writer.h"
57 #include "dwarfwriter.h"
59 #include "mini-llvm.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;
123 int nrgctx_trampolines;
124 int nimt_trampolines;
125 int ngsharedvt_arg_trampolines;
126 int nrgctx_fetch_trampolines;
127 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 GHashTable *signatures;
182 guint32 *plt_got_info_offsets;
183 guint32 got_offset, llvm_got_offset, plt_offset, plt_got_offset_base, nshared_got_entries;
184 /* Number of GOT entries reserved for trampolines */
185 guint32 num_trampoline_got_entries;
186 guint32 tramp_page_size;
188 guint32 num_trampolines [MONO_AOT_TRAMP_NUM];
189 guint32 trampoline_got_offset_base [MONO_AOT_TRAMP_NUM];
190 guint32 trampoline_size [MONO_AOT_TRAMP_NUM];
191 guint32 tramp_page_code_offsets [MONO_AOT_TRAMP_NUM];
193 MonoAotOptions aot_opts;
197 MonoMemPool *mempool;
200 char *static_linking_symbol;
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_os_mutex_lock (&((acfg)->mutex))
256 #define mono_acfg_unlock(acfg) mono_os_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_unwind_info_offset (MonoAotCompile *acfg, guint8 *encoded, guint32 encoded_len);
305 get_plt_entry_debug_sym (MonoAotCompile *acfg, MonoJumpInfo *ji, GHashTable *cache);
308 aot_printf (MonoAotCompile *acfg, const gchar *format, ...)
314 output = acfg->logfile;
318 va_start (args, format);
319 vfprintf (output, format, args);
324 aot_printerrf (MonoAotCompile *acfg, const gchar *format, ...)
330 output = acfg->logfile;
334 va_start (args, format);
335 vfprintf (output, format, args);
340 report_loader_error (MonoAotCompile *acfg, MonoError *error, const char *format, ...)
345 if (mono_error_ok (error))
349 output = acfg->logfile;
353 va_start (args, format);
354 vfprintf (output, format, args);
356 mono_error_cleanup (error);
358 g_error ("FullAOT cannot continue if there are loader errors");
361 /* Wrappers around the image writer functions */
364 emit_section_change (MonoAotCompile *acfg, const char *section_name, int subsection_index)
366 mono_img_writer_emit_section_change (acfg->w, section_name, subsection_index);
370 emit_local_symbol (MonoAotCompile *acfg, const char *name, const char *end_label, gboolean func)
372 mono_img_writer_emit_local_symbol (acfg->w, name, end_label, func);
376 emit_label (MonoAotCompile *acfg, const char *name)
378 mono_img_writer_emit_label (acfg->w, name);
382 emit_bytes (MonoAotCompile *acfg, const guint8* buf, int size)
384 mono_img_writer_emit_bytes (acfg->w, buf, size);
388 emit_string (MonoAotCompile *acfg, const char *value)
390 mono_img_writer_emit_string (acfg->w, value);
394 emit_line (MonoAotCompile *acfg)
396 mono_img_writer_emit_line (acfg->w);
400 emit_alignment (MonoAotCompile *acfg, int size)
402 mono_img_writer_emit_alignment (acfg->w, size);
406 emit_alignment_code (MonoAotCompile *acfg, int size)
408 if (acfg->align_pad_value)
409 mono_img_writer_emit_alignment_fill (acfg->w, size, acfg->align_pad_value);
411 mono_img_writer_emit_alignment (acfg->w, size);
415 emit_padding (MonoAotCompile *acfg, int size)
420 if (acfg->align_pad_value) {
421 for (i = 0; i < 16; ++i)
422 buf [i] = acfg->align_pad_value;
424 memset (buf, 0, sizeof (buf));
427 for (i = 0; i < size; i += 16) {
429 emit_bytes (acfg, buf, size - i);
431 emit_bytes (acfg, buf, 16);
436 emit_pointer (MonoAotCompile *acfg, const char *target)
438 mono_img_writer_emit_pointer (acfg->w, target);
442 emit_pointer_2 (MonoAotCompile *acfg, const char *prefix, const char *target)
444 if (prefix [0] != '\0') {
445 char *s = g_strdup_printf ("%s%s", prefix, target);
446 mono_img_writer_emit_pointer (acfg->w, s);
449 mono_img_writer_emit_pointer (acfg->w, target);
454 emit_int16 (MonoAotCompile *acfg, int value)
456 mono_img_writer_emit_int16 (acfg->w, value);
460 emit_int32 (MonoAotCompile *acfg, int value)
462 mono_img_writer_emit_int32 (acfg->w, value);
466 emit_symbol_diff (MonoAotCompile *acfg, const char *end, const char* start, int offset)
468 mono_img_writer_emit_symbol_diff (acfg->w, end, start, offset);
472 emit_zero_bytes (MonoAotCompile *acfg, int num)
474 mono_img_writer_emit_zero_bytes (acfg->w, num);
478 emit_byte (MonoAotCompile *acfg, guint8 val)
480 mono_img_writer_emit_byte (acfg->w, val);
483 #ifdef __native_client_codegen__
485 emit_nacl_call_alignment (MonoAotCompile *acfg)
487 mono_img_writer_emit_nacl_call_alignment (acfg->w);
491 static G_GNUC_UNUSED void
492 emit_global_inner (MonoAotCompile *acfg, const char *name, gboolean func)
494 mono_img_writer_emit_global (acfg->w, name, func);
498 emit_global (MonoAotCompile *acfg, const char *name, gboolean func)
500 if (acfg->aot_opts.no_dlsym) {
501 g_ptr_array_add (acfg->globals, g_strdup (name));
502 mono_img_writer_emit_local_symbol (acfg->w, name, NULL, func);
504 mono_img_writer_emit_global (acfg->w, name, func);
509 emit_symbol_size (MonoAotCompile *acfg, const char *name, const char *end_label)
511 mono_img_writer_emit_symbol_size (acfg->w, name, end_label);
514 /* Emit a symbol which is referenced by the MonoAotFileInfo structure */
516 emit_info_symbol (MonoAotCompile *acfg, const char *name)
521 emit_label (acfg, name);
522 /* LLVM generated code references this */
523 sprintf (symbol, "%s%s%s", acfg->user_symbol_prefix, acfg->global_prefix, name);
524 emit_label (acfg, symbol);
525 emit_global_inner (acfg, symbol, FALSE);
527 emit_label (acfg, name);
532 emit_string_symbol (MonoAotCompile *acfg, const char *name, const char *value)
535 mono_llvm_emit_aot_data (name, (guint8*)value, strlen (value) + 1);
539 mono_img_writer_emit_section_change (acfg->w, RODATA_SECT, 1);
541 /* On apple, all symbols need to be aligned to avoid warnings from ld */
542 emit_alignment (acfg, 4);
544 mono_img_writer_emit_label (acfg->w, name);
545 mono_img_writer_emit_string (acfg->w, value);
548 static G_GNUC_UNUSED void
549 emit_uleb128 (MonoAotCompile *acfg, guint32 value)
552 guint8 b = value & 0x7f;
554 if (value != 0) /* more bytes to come */
560 static G_GNUC_UNUSED void
561 emit_sleb128 (MonoAotCompile *acfg, gint64 value)
564 gboolean negative = (value < 0);
571 /* the following is unnecessary if the
572 * implementation of >>= uses an arithmetic rather
573 * than logical shift for a signed left operand
577 value |= - ((gint64)1 <<(size - 7));
578 /* sign bit of byte is second high order bit (0x40) */
579 if ((value == 0 && !(byte & 0x40)) ||
580 (value == -1 && (byte & 0x40)))
584 emit_byte (acfg, byte);
588 static G_GNUC_UNUSED void
589 encode_uleb128 (guint32 value, guint8 *buf, guint8 **endbuf)
594 guint8 b = value & 0x7f;
596 if (value != 0) /* more bytes to come */
604 static G_GNUC_UNUSED void
605 encode_sleb128 (gint32 value, guint8 *buf, guint8 **endbuf)
608 gboolean negative = (value < 0);
616 /* the following is unnecessary if the
617 * implementation of >>= uses an arithmetic rather
618 * than logical shift for a signed left operand
622 value |= - (1 <<(size - 7));
623 /* sign bit of byte is second high order bit (0x40) */
624 if ((value == 0 && !(byte & 0x40)) ||
625 (value == -1 && (byte & 0x40)))
636 encode_int (gint32 val, guint8 *buf, guint8 **endbuf)
639 buf [0] = (val >> 0) & 0xff;
640 buf [1] = (val >> 8) & 0xff;
641 buf [2] = (val >> 16) & 0xff;
642 buf [3] = (val >> 24) & 0xff;
648 encode_int16 (guint16 val, guint8 *buf, guint8 **endbuf)
650 buf [0] = (val >> 0) & 0xff;
651 buf [1] = (val >> 8) & 0xff;
657 encode_string (const char *s, guint8 *buf, guint8 **endbuf)
659 int len = strlen (s);
661 memcpy (buf, s, len + 1);
662 *endbuf = buf + len + 1;
666 emit_unset_mode (MonoAotCompile *acfg)
668 mono_img_writer_emit_unset_mode (acfg->w);
671 static G_GNUC_UNUSED void
672 emit_set_thumb_mode (MonoAotCompile *acfg)
674 emit_unset_mode (acfg);
675 fprintf (acfg->fp, ".code 16\n");
678 static G_GNUC_UNUSED void
679 emit_set_arm_mode (MonoAotCompile *acfg)
681 emit_unset_mode (acfg);
682 fprintf (acfg->fp, ".code 32\n");
686 emit_code_bytes (MonoAotCompile *acfg, const guint8* buf, int size)
691 g_assert (size % 4 == 0);
692 emit_unset_mode (acfg);
693 for (i = 0; i < size; i += 4)
694 fprintf (acfg->fp, "%s 0x%x\n", acfg->inst_directive, *(guint32*)(buf + i));
696 emit_bytes (acfg, buf, size);
700 /* ARCHITECTURE SPECIFIC CODE */
702 #if defined(TARGET_X86) || defined(TARGET_AMD64) || defined(TARGET_ARM) || defined(TARGET_POWERPC) || defined(TARGET_ARM64)
703 #define EMIT_DWARF_INFO 1
706 #if defined(TARGET_ARM)
707 #define AOT_FUNC_ALIGNMENT 4
709 #define AOT_FUNC_ALIGNMENT 16
711 #if (defined(TARGET_X86) || defined(TARGET_AMD64)) && defined(__native_client_codegen__)
712 #undef AOT_FUNC_ALIGNMENT
713 #define AOT_FUNC_ALIGNMENT 32
716 #if defined(TARGET_POWERPC64) && !defined(__mono_ilp32__)
717 #define PPC_LD_OP "ld"
718 #define PPC_LDX_OP "ldx"
720 #define PPC_LD_OP "lwz"
721 #define PPC_LDX_OP "lwzx"
725 #define AOT_TARGET_STR "AMD64"
730 #define AOT_TARGET_STR "ARM (MACH)"
732 #define AOT_TARGET_STR "ARM (!MACH)"
738 #define AOT_TARGET_STR "ARM64 (MACH)"
740 #define AOT_TARGET_STR "ARM64 (!MACH)"
744 #ifdef TARGET_POWERPC64
745 #ifdef __mono_ilp32__
746 #define AOT_TARGET_STR "POWERPC64 (mono ilp32)"
748 #define AOT_TARGET_STR "POWERPC64 (!mono ilp32)"
751 #ifdef TARGET_POWERPC
752 #ifdef __mono_ilp32__
753 #define AOT_TARGET_STR "POWERPC (mono ilp32)"
755 #define AOT_TARGET_STR "POWERPC (!mono ilp32)"
762 #define AOT_TARGET_STR "X86 (WIN32)"
763 #elif defined(__native_client_codegen__)
764 #define AOT_TARGET_STR "X86 (native client codegen)"
766 #define AOT_TARGET_STR "X86 (!native client codegen)"
770 #ifndef AOT_TARGET_STR
771 #define AOT_TARGET_STR ""
775 arch_init (MonoAotCompile *acfg)
777 acfg->llc_args = g_string_new ("");
778 acfg->as_args = g_string_new ("");
781 * The prefix LLVM likes to put in front of symbol names on darwin.
782 * The mach-os specs require this for globals, but LLVM puts them in front of all
783 * symbols. We need to handle this, since we need to refer to LLVM generated
786 acfg->llvm_label_prefix = "";
787 acfg->user_symbol_prefix = "";
789 #if defined(TARGET_X86)
790 g_string_append (acfg->llc_args, " -march=x86 -mattr=sse4.1");
793 #if defined(TARGET_AMD64)
794 g_string_append (acfg->llc_args, " -march=x86-64 -mattr=sse4.1");
796 acfg->align_pad_value = 0x90;
800 if (acfg->aot_opts.mtriple && strstr (acfg->aot_opts.mtriple, "darwin")) {
801 g_string_append (acfg->llc_args, "-mattr=+v6");
804 g_string_append (acfg->llc_args, " -mattr=+vfp2,-neon,+d16");
805 g_string_append (acfg->as_args, " -mfpu=vfp3");
807 g_string_append (acfg->llc_args, " -soft-float");
810 if (acfg->aot_opts.mtriple && strstr (acfg->aot_opts.mtriple, "thumb"))
811 acfg->thumb_mixed = TRUE;
813 if (acfg->aot_opts.mtriple)
814 mono_arch_set_target (acfg->aot_opts.mtriple);
818 acfg->inst_directive = ".inst";
819 if (acfg->aot_opts.mtriple)
820 mono_arch_set_target (acfg->aot_opts.mtriple);
824 acfg->user_symbol_prefix = "_";
825 acfg->llvm_label_prefix = "_";
826 acfg->inst_directive = ".word";
827 acfg->need_no_dead_strip = TRUE;
828 acfg->aot_opts.gnu_asm = TRUE;
831 #if defined(__linux__) && !defined(TARGET_ARM)
832 acfg->need_pt_gnu_stack = TRUE;
836 acfg->global_symbols = TRUE;
842 #include "../../../mono-extensions/mono/mini/aot-compiler-arm64.c"
846 #ifdef MONO_ARCH_AOT_SUPPORTED
848 * arch_emit_direct_call:
850 * Emit a direct call to the symbol TARGET. CALL_SIZE is set to the size of the
854 arch_emit_direct_call (MonoAotCompile *acfg, const char *target, gboolean external, gboolean thumb, MonoJumpInfo *ji, int *call_size)
856 #if defined(TARGET_X86) || defined(TARGET_AMD64)
857 /* Need to make sure this is exactly 5 bytes long */
858 emit_unset_mode (acfg);
859 fprintf (acfg->fp, "call %s\n", target);
861 #elif defined(TARGET_ARM)
862 emit_unset_mode (acfg);
864 fprintf (acfg->fp, "blx %s\n", target);
866 fprintf (acfg->fp, "bl %s\n", target);
868 #elif defined(TARGET_ARM64)
869 arm64_emit_direct_call (acfg, target, external, thumb, ji, call_size);
870 #elif defined(TARGET_POWERPC)
871 emit_unset_mode (acfg);
872 fprintf (acfg->fp, "bl %s\n", target);
875 g_assert_not_reached ();
882 * - we use an approach similar to the x86 abi: reserve a register (r30) to hold
884 * - The full-aot trampolines need access to the GOT of mscorlib, so we store
885 * in in the 2. slot of every GOT, and require every method to place the GOT
886 * address in r30, even when it doesn't access the GOT otherwise. This way,
887 * the trampolines can compute the mscorlib GOT address by loading 4(r30).
892 * PPC64 uses function descriptors which greatly complicate all code, since
893 * these are used very inconsistently in the runtime. Some functions like
894 * mono_compile_method () return ftn descriptors, while others like the
895 * trampoline creation functions do not.
896 * We assume that all GOT slots contain function descriptors, and create
897 * descriptors in aot-runtime.c when needed.
898 * The ppc64 abi uses r2 to hold the address of the TOC/GOT, which is loaded
899 * from function descriptors, we could do the same, but it would require
900 * rewriting all the ppc/aot code to handle function descriptors properly.
901 * So instead, we use the same approach as on PPC32.
902 * This is a horrible mess, but fixing it would probably lead to an even bigger
908 * - similar to the PPC32 design, we reserve EBX to hold the GOT pointer.
911 #ifdef MONO_ARCH_AOT_SUPPORTED
913 * arch_emit_got_offset:
915 * The memory pointed to by CODE should hold native code for computing the GOT
916 * address (OP_LOAD_GOTADDR). Emit this code while patching it with the offset
917 * between code and the GOT. CODE_SIZE is set to the number of bytes emitted.
920 arch_emit_got_offset (MonoAotCompile *acfg, guint8 *code, int *code_size)
922 #if defined(TARGET_POWERPC64)
923 emit_unset_mode (acfg);
925 * The ppc32 code doesn't seem to work on ppc64, the assembler complains about
926 * unsupported relocations. So we store the got address into the .Lgot_addr
927 * symbol which is in the text segment, compute its address, and load it.
929 fprintf (acfg->fp, ".L%d:\n", acfg->label_generator);
930 fprintf (acfg->fp, "lis 0, (.Lgot_addr + 4 - .L%d)@h\n", acfg->label_generator);
931 fprintf (acfg->fp, "ori 0, 0, (.Lgot_addr + 4 - .L%d)@l\n", acfg->label_generator);
932 fprintf (acfg->fp, "add 30, 30, 0\n");
933 fprintf (acfg->fp, "%s 30, 0(30)\n", PPC_LD_OP);
934 acfg->label_generator ++;
936 #elif defined(TARGET_POWERPC)
937 emit_unset_mode (acfg);
938 fprintf (acfg->fp, ".L%d:\n", acfg->label_generator);
939 fprintf (acfg->fp, "lis 0, (%s + 4 - .L%d)@h\n", acfg->got_symbol, acfg->label_generator);
940 fprintf (acfg->fp, "ori 0, 0, (%s + 4 - .L%d)@l\n", acfg->got_symbol, acfg->label_generator);
941 acfg->label_generator ++;
944 guint32 offset = mono_arch_get_patch_offset (code);
945 emit_bytes (acfg, code, offset);
946 emit_symbol_diff (acfg, acfg->got_symbol, ".", offset);
948 *code_size = offset + 4;
953 * arch_emit_got_access:
955 * The memory pointed to by CODE should hold native code for loading a GOT
956 * slot (OP_AOTCONST/OP_GOT_ENTRY). Emit this code while patching it so it accesses the
957 * GOT slot GOT_SLOT. CODE_SIZE is set to the number of bytes emitted.
960 arch_emit_got_access (MonoAotCompile *acfg, const char *got_symbol, guint8 *code, int got_slot, int *code_size)
963 /* mov reg, got+offset(%rip) */
965 /* The GOT symbol is in the LLVM module, the clang assembler has problems emitting symbol diffs for it */
969 /* Decode reg, see amd64_mov_reg_membase () */
970 rex_r = code [0] & AMD64_REX_R;
971 g_assert (code [0] == 0x49 + rex_r);
972 g_assert (code [1] == 0x8b);
973 dreg = ((code [2] >> 3) & 0x7) + (rex_r ? 8 : 0);
975 emit_unset_mode (acfg);
976 fprintf (acfg->fp, "mov %s+%d(%%rip), %s\n", got_symbol, (unsigned int) ((got_slot * sizeof (gpointer))), mono_arch_regname (dreg));
979 emit_bytes (acfg, code, mono_arch_get_patch_offset (code));
980 emit_symbol_diff (acfg, got_symbol, ".", (unsigned int) ((got_slot * sizeof (gpointer)) - 4));
981 *code_size = mono_arch_get_patch_offset (code) + 4;
983 #elif defined(TARGET_X86)
984 emit_bytes (acfg, code, mono_arch_get_patch_offset (code));
985 emit_int32 (acfg, (unsigned int) ((got_slot * sizeof (gpointer))));
986 *code_size = mono_arch_get_patch_offset (code) + 4;
987 #elif defined(TARGET_ARM)
988 emit_bytes (acfg, code, mono_arch_get_patch_offset (code));
989 emit_symbol_diff (acfg, got_symbol, ".", (unsigned int) ((got_slot * sizeof (gpointer))) - 12);
990 *code_size = mono_arch_get_patch_offset (code) + 4;
991 #elif defined(TARGET_ARM64)
992 emit_bytes (acfg, code, mono_arch_get_patch_offset (code));
993 arm64_emit_got_access (acfg, code, got_slot, code_size);
994 #elif defined(TARGET_POWERPC)
999 emit_bytes (acfg, code, mono_arch_get_patch_offset (code));
1001 ppc_load32 (code, ppc_r0, got_slot * sizeof (gpointer));
1002 g_assert (code - buf == 8);
1003 emit_bytes (acfg, buf, code - buf);
1004 *code_size = code - buf;
1007 g_assert_not_reached ();
1013 #ifdef MONO_ARCH_AOT_SUPPORTED
1015 * arch_emit_objc_selector_ref:
1017 * Emit the implementation of OP_OBJC_GET_SELECTOR, which itself implements @selector(foo:) in objective-c.
1020 arch_emit_objc_selector_ref (MonoAotCompile *acfg, guint8 *code, int index, int *code_size)
1022 #if defined(TARGET_ARM)
1025 int lindex = acfg->objc_selector_index_2 ++;
1027 /* Emit ldr.imm/b */
1028 emit_bytes (acfg, code, 8);
1030 sprintf (symbol1, "L_OBJC_SELECTOR_%d", lindex);
1031 sprintf (symbol2, "L_OBJC_SELECTOR_REFERENCES_%d", index);
1033 emit_label (acfg, symbol1);
1034 mono_img_writer_emit_unset_mode (acfg->w);
1035 fprintf (acfg->fp, ".long %s-(%s+12)", symbol2, symbol1);
1038 #elif defined(TARGET_ARM64)
1039 arm64_emit_objc_selector_ref (acfg, code, index, code_size);
1041 g_assert_not_reached ();
1047 * arch_emit_plt_entry:
1049 * Emit code for the PLT entry.
1050 * The plt entry should look like this:
1051 * <indirect jump to GOT_SYMBOL + OFFSET>
1052 * <INFO_OFFSET embedded into the instruction stream>
1055 arch_emit_plt_entry (MonoAotCompile *acfg, const char *got_symbol, int offset, int info_offset)
1057 #if defined(TARGET_X86)
1058 #if defined(__default_codegen__)
1059 /* jmp *<offset>(%ebx) */
1060 emit_byte (acfg, 0xff);
1061 emit_byte (acfg, 0xa3);
1062 emit_int32 (acfg, offset);
1063 /* Used by mono_aot_get_plt_info_offset */
1064 emit_int32 (acfg, info_offset);
1065 #elif defined(__native_client_codegen__)
1066 const guint8 kSizeOfNaClJmp = 11;
1067 guint8 bytes[kSizeOfNaClJmp];
1068 guint8 *pbytes = &bytes[0];
1070 x86_jump_membase32 (pbytes, X86_EBX, offset);
1071 emit_bytes (acfg, bytes, kSizeOfNaClJmp);
1072 /* four bytes of data, used by mono_arch_patch_plt_entry */
1073 /* For Native Client, make this work with data embedded in push. */
1074 emit_byte (acfg, 0x68); /* hide data in a push */
1075 emit_int32 (acfg, info_offset);
1076 emit_alignment (acfg, AOT_FUNC_ALIGNMENT);
1077 #endif /*__native_client_codegen__*/
1078 #elif defined(TARGET_AMD64)
1079 #if defined(__default_codegen__)
1080 emit_unset_mode (acfg);
1081 fprintf (acfg->fp, "jmp *%s+%d(%%rip)\n", got_symbol, offset);
1082 /* Used by mono_aot_get_plt_info_offset */
1083 emit_int32 (acfg, info_offset);
1084 acfg->stats.plt_size += 10;
1085 #elif defined(__native_client_codegen__)
1087 guint8 *buf_aligned = ALIGN_TO(buf, kNaClAlignment);
1088 guint8 *code = buf_aligned;
1090 /* mov <OFFSET>(%rip), %r11d */
1091 emit_byte (acfg, '\x45');
1092 emit_byte (acfg, '\x8b');
1093 emit_byte (acfg, '\x1d');
1094 emit_symbol_diff (acfg, got_symbol, ".", offset - 4);
1096 amd64_jump_reg (code, AMD64_R11);
1097 /* This should be constant for the plt patch */
1098 g_assert ((size_t)(code-buf_aligned) == 10);
1099 emit_bytes (acfg, buf_aligned, code - buf_aligned);
1101 /* Hide data in a push imm32 so it passes validation */
1102 emit_byte (acfg, 0x68); /* push */
1103 emit_int32 (acfg, info_offset);
1104 emit_alignment (acfg, AOT_FUNC_ALIGNMENT);
1105 #endif /*__native_client_codegen__*/
1106 #elif defined(TARGET_ARM)
1111 ARM_LDR_IMM (code, ARMREG_IP, ARMREG_PC, 0);
1112 ARM_LDR_REG_REG (code, ARMREG_PC, ARMREG_PC, ARMREG_IP);
1113 emit_bytes (acfg, buf, code - buf);
1114 emit_symbol_diff (acfg, got_symbol, ".", offset - 4);
1115 /* Used by mono_aot_get_plt_info_offset */
1116 emit_int32 (acfg, info_offset);
1117 #elif defined(TARGET_ARM64)
1118 arm64_emit_plt_entry (acfg, got_symbol, offset, info_offset);
1119 #elif defined(TARGET_POWERPC)
1120 /* The GOT address is guaranteed to be in r30 by OP_LOAD_GOTADDR */
1121 emit_unset_mode (acfg);
1122 fprintf (acfg->fp, "lis 11, %d@h\n", offset);
1123 fprintf (acfg->fp, "ori 11, 11, %d@l\n", offset);
1124 fprintf (acfg->fp, "add 11, 11, 30\n");
1125 fprintf (acfg->fp, "%s 11, 0(11)\n", PPC_LD_OP);
1126 #ifdef PPC_USES_FUNCTION_DESCRIPTOR
1127 fprintf (acfg->fp, "%s 2, %d(11)\n", PPC_LD_OP, (int)sizeof (gpointer));
1128 fprintf (acfg->fp, "%s 11, 0(11)\n", PPC_LD_OP);
1130 fprintf (acfg->fp, "mtctr 11\n");
1131 fprintf (acfg->fp, "bctr\n");
1132 emit_int32 (acfg, info_offset);
1134 g_assert_not_reached ();
1139 * arch_emit_llvm_plt_entry:
1141 * Same as arch_emit_plt_entry, but handles calls from LLVM generated code.
1142 * This is only needed on arm to handle thumb interop.
1145 arch_emit_llvm_plt_entry (MonoAotCompile *acfg, const char *got_symbol, int offset, int info_offset)
1147 #if defined(TARGET_ARM)
1148 /* LLVM calls the PLT entries using bl, so these have to be thumb2 */
1149 /* The caller already transitioned to thumb */
1150 /* The code below should be 12 bytes long */
1151 /* clang has trouble encoding these instructions, so emit the binary */
1153 fprintf (acfg->fp, "ldr ip, [pc, #8]\n");
1154 /* thumb can't encode ld pc, [pc, ip] */
1155 fprintf (acfg->fp, "add ip, pc, ip\n");
1156 fprintf (acfg->fp, "ldr ip, [ip, #0]\n");
1157 fprintf (acfg->fp, "bx ip\n");
1159 emit_set_thumb_mode (acfg);
1160 fprintf (acfg->fp, ".4byte 0xc008f8df\n");
1161 fprintf (acfg->fp, ".2byte 0x44fc\n");
1162 fprintf (acfg->fp, ".4byte 0xc000f8dc\n");
1163 fprintf (acfg->fp, ".2byte 0x4760\n");
1164 emit_symbol_diff (acfg, got_symbol, ".", offset + 4);
1165 emit_int32 (acfg, info_offset);
1166 emit_unset_mode (acfg);
1167 emit_set_arm_mode (acfg);
1169 g_assert_not_reached ();
1173 /* Save unwind_info in the module and emit the offset to the information at symbol */
1174 static void save_unwind_info (MonoAotCompile *acfg, char *symbol, GSList *unwind_ops)
1176 guint32 uw_offset, encoded_len;
1179 emit_section_change (acfg, RODATA_SECT, 0);
1180 emit_global (acfg, symbol, FALSE);
1181 emit_label (acfg, symbol);
1183 encoded = mono_unwind_ops_encode (unwind_ops, &encoded_len);
1184 uw_offset = get_unwind_info_offset (acfg, encoded, encoded_len);
1186 emit_int32 (acfg, uw_offset);
1190 * arch_emit_specific_trampoline_pages:
1192 * Emits a page full of trampolines: each trampoline uses its own address to
1193 * lookup both the generic trampoline code and the data argument.
1194 * This page can be remapped in process multiple times so we can get an
1195 * unlimited number of trampolines.
1196 * Specifically this implementation uses the following trick: two memory pages
1197 * are allocated, with the first containing the data and the second containing the trampolines.
1198 * To reduce trampoline size, each trampoline jumps at the start of the page where a common
1199 * implementation does all the lifting.
1200 * Note that the ARM single trampoline size is 8 bytes, exactly like the data that needs to be stored
1201 * on the arm 32 bit system.
1204 arch_emit_specific_trampoline_pages (MonoAotCompile *acfg)
1206 #if defined(TARGET_ARM)
1209 guint8 *loop_start, *loop_branch_back, *loop_end_check, *imt_found_check;
1211 int pagesize = MONO_AOT_TRAMP_PAGE_SIZE;
1212 GSList *unwind_ops = NULL;
1213 #define COMMON_TRAMP_SIZE 16
1214 int count = (pagesize - COMMON_TRAMP_SIZE) / 8;
1215 int imm8, rot_amount;
1218 if (!acfg->aot_opts.use_trampolines_page)
1221 acfg->tramp_page_size = pagesize;
1223 sprintf (symbol, "%sspecific_trampolines_page", acfg->user_symbol_prefix);
1224 emit_alignment (acfg, pagesize);
1225 emit_global (acfg, symbol, TRUE);
1226 emit_label (acfg, symbol);
1228 /* emit the generic code first, the trampoline address + 8 is in the lr register */
1230 imm8 = mono_arm_is_rotated_imm8 (pagesize, &rot_amount);
1231 ARM_SUB_REG_IMM (code, ARMREG_LR, ARMREG_LR, imm8, rot_amount);
1232 ARM_LDR_IMM (code, ARMREG_R1, ARMREG_LR, -8);
1233 ARM_LDR_IMM (code, ARMREG_PC, ARMREG_LR, -4);
1235 g_assert (code - buf == COMMON_TRAMP_SIZE);
1238 emit_bytes (acfg, buf, code - buf);
1240 for (i = 0; i < count; ++i) {
1242 ARM_PUSH (code, 0x5fff);
1244 arm_patch (code - 4, code - COMMON_TRAMP_SIZE - 8 * (i + 1));
1245 g_assert (code - buf == 8);
1246 emit_bytes (acfg, buf, code - buf);
1249 /* now the rgctx trampolines: each specific trampolines puts in the ip register
1250 * the instruction pointer address, so the generic trampoline at the start of the page
1251 * subtracts 4096 to get to the data page and loads the values
1252 * We again fit the generic trampiline in 16 bytes.
1254 sprintf (symbol, "%srgctx_trampolines_page", acfg->user_symbol_prefix);
1255 emit_global (acfg, symbol, TRUE);
1256 emit_label (acfg, symbol);
1258 imm8 = mono_arm_is_rotated_imm8 (pagesize, &rot_amount);
1259 ARM_SUB_REG_IMM (code, ARMREG_IP, ARMREG_IP, imm8, rot_amount);
1260 ARM_LDR_IMM (code, MONO_ARCH_RGCTX_REG, ARMREG_IP, -8);
1261 ARM_LDR_IMM (code, ARMREG_PC, ARMREG_IP, -4);
1263 g_assert (code - buf == COMMON_TRAMP_SIZE);
1266 emit_bytes (acfg, buf, code - buf);
1268 for (i = 0; i < count; ++i) {
1270 ARM_MOV_REG_REG (code, ARMREG_IP, ARMREG_PC);
1272 arm_patch (code - 4, code - COMMON_TRAMP_SIZE - 8 * (i + 1));
1273 g_assert (code - buf == 8);
1274 emit_bytes (acfg, buf, code - buf);
1278 * gsharedvt arg trampolines: see arch_emit_gsharedvt_arg_trampoline ()
1280 sprintf (symbol, "%sgsharedvt_arg_trampolines_page", acfg->user_symbol_prefix);
1281 emit_global (acfg, symbol, TRUE);
1282 emit_label (acfg, symbol);
1284 ARM_PUSH (code, (1 << ARMREG_R0) | (1 << ARMREG_R1) | (1 << ARMREG_R2) | (1 << ARMREG_R3));
1285 imm8 = mono_arm_is_rotated_imm8 (pagesize, &rot_amount);
1286 ARM_SUB_REG_IMM (code, ARMREG_IP, ARMREG_IP, imm8, rot_amount);
1287 ARM_LDR_IMM (code, ARMREG_R0, ARMREG_IP, -8);
1288 ARM_LDR_IMM (code, ARMREG_PC, ARMREG_IP, -4);
1289 g_assert (code - buf == COMMON_TRAMP_SIZE);
1291 emit_bytes (acfg, buf, code - buf);
1293 for (i = 0; i < count; ++i) {
1295 ARM_MOV_REG_REG (code, ARMREG_IP, ARMREG_PC);
1297 arm_patch (code - 4, code - COMMON_TRAMP_SIZE - 8 * (i + 1));
1298 g_assert (code - buf == 8);
1299 emit_bytes (acfg, buf, code - buf);
1302 /* now the imt trampolines: each specific trampolines puts in the ip register
1303 * the instruction pointer address, so the generic trampoline at the start of the page
1304 * subtracts 4096 to get to the data page and loads the values
1306 #define IMT_TRAMP_SIZE 72
1307 sprintf (symbol, "%simt_trampolines_page", acfg->user_symbol_prefix);
1308 emit_global (acfg, symbol, TRUE);
1309 emit_label (acfg, symbol);
1311 /* Need at least two free registers, plus a slot for storing the pc */
1312 ARM_PUSH (code, (1 << ARMREG_R0)|(1 << ARMREG_R1)|(1 << ARMREG_R2));
1314 imm8 = mono_arm_is_rotated_imm8 (pagesize, &rot_amount);
1315 ARM_SUB_REG_IMM (code, ARMREG_IP, ARMREG_IP, imm8, rot_amount);
1316 ARM_LDR_IMM (code, ARMREG_R0, ARMREG_IP, -8);
1318 /* The IMT method is in v5, r0 has the imt array address */
1321 ARM_LDR_IMM (code, ARMREG_R1, ARMREG_R0, 0);
1322 ARM_CMP_REG_REG (code, ARMREG_R1, ARMREG_V5);
1323 imt_found_check = code;
1324 ARM_B_COND (code, ARMCOND_EQ, 0);
1326 /* End-of-loop check */
1327 ARM_CMP_REG_IMM (code, ARMREG_R1, 0, 0);
1328 loop_end_check = code;
1329 ARM_B_COND (code, ARMCOND_EQ, 0);
1332 ARM_ADD_REG_IMM8 (code, ARMREG_R0, ARMREG_R0, sizeof (gpointer) * 2);
1333 loop_branch_back = code;
1335 arm_patch (loop_branch_back, loop_start);
1338 arm_patch (imt_found_check, code);
1339 ARM_LDR_IMM (code, ARMREG_R0, ARMREG_R0, 4);
1340 ARM_LDR_IMM (code, ARMREG_R0, ARMREG_R0, 0);
1341 /* Save it to the third stack slot */
1342 ARM_STR_IMM (code, ARMREG_R0, ARMREG_SP, 8);
1343 /* Restore the registers and branch */
1344 ARM_POP (code, (1 << ARMREG_R0)|(1 << ARMREG_R1)|(1 << ARMREG_PC));
1347 arm_patch (loop_end_check, code);
1348 ARM_LDR_IMM (code, ARMREG_R0, ARMREG_R0, 4);
1349 ARM_STR_IMM (code, ARMREG_R0, ARMREG_SP, 8);
1350 ARM_POP (code, (1 << ARMREG_R0)|(1 << ARMREG_R1)|(1 << ARMREG_PC));
1354 g_assert (code - buf == IMT_TRAMP_SIZE);
1355 emit_bytes (acfg, buf, code - buf);
1357 for (i = 0; i < count; ++i) {
1359 ARM_MOV_REG_REG (code, ARMREG_IP, ARMREG_PC);
1361 arm_patch (code - 4, code - IMT_TRAMP_SIZE - 8 * (i + 1));
1362 g_assert (code - buf == 8);
1363 emit_bytes (acfg, buf, code - buf);
1366 acfg->tramp_page_code_offsets [MONO_AOT_TRAMP_SPECIFIC] = 16;
1367 acfg->tramp_page_code_offsets [MONO_AOT_TRAMP_STATIC_RGCTX] = 16;
1368 acfg->tramp_page_code_offsets [MONO_AOT_TRAMP_IMT_THUNK] = 72;
1369 acfg->tramp_page_code_offsets [MONO_AOT_TRAMP_GSHAREDVT_ARG] = 16;
1371 /* Unwind info for specifc trampolines */
1372 sprintf (symbol, "%sspecific_trampolines_page_gen_p", acfg->user_symbol_prefix);
1373 /* We unwind to the original caller, from the stack, since lr is clobbered */
1374 mono_add_unwind_op_def_cfa (unwind_ops, 0, 0, ARMREG_SP, 14 * sizeof (mgreg_t));
1375 mono_add_unwind_op_offset (unwind_ops, 0, 0, ARMREG_LR, -4);
1376 save_unwind_info (acfg, symbol, unwind_ops);
1377 mono_free_unwind_info (unwind_ops);
1379 sprintf (symbol, "%sspecific_trampolines_page_sp_p", acfg->user_symbol_prefix);
1380 mono_add_unwind_op_def_cfa (unwind_ops, 0, 0, ARMREG_SP, 0);
1381 mono_add_unwind_op_def_cfa_offset (unwind_ops, 4, 0, 14 * sizeof (mgreg_t));
1382 save_unwind_info (acfg, symbol, unwind_ops);
1383 mono_free_unwind_info (unwind_ops);
1385 /* Unwind info for rgctx trampolines */
1386 sprintf (symbol, "%srgctx_trampolines_page_gen_p", acfg->user_symbol_prefix);
1387 mono_add_unwind_op_def_cfa (unwind_ops, 0, 0, ARMREG_SP, 0);
1388 save_unwind_info (acfg, symbol, unwind_ops);
1390 sprintf (symbol, "%srgctx_trampolines_page_sp_p", acfg->user_symbol_prefix);
1391 save_unwind_info (acfg, symbol, unwind_ops);
1392 mono_free_unwind_info (unwind_ops);
1394 /* Unwind info for gsharedvt trampolines */
1395 sprintf (symbol, "%sgsharedvt_trampolines_page_gen_p", acfg->user_symbol_prefix);
1396 mono_add_unwind_op_def_cfa (unwind_ops, 0, 0, ARMREG_SP, 0);
1397 mono_add_unwind_op_def_cfa_offset (unwind_ops, 4, 0, 4 * sizeof (mgreg_t));
1398 save_unwind_info (acfg, symbol, unwind_ops);
1399 mono_free_unwind_info (unwind_ops);
1401 sprintf (symbol, "%sgsharedvt_trampolines_page_sp_p", acfg->user_symbol_prefix);
1402 mono_add_unwind_op_def_cfa (unwind_ops, 0, 0, ARMREG_SP, 0);
1403 save_unwind_info (acfg, symbol, unwind_ops);
1404 mono_free_unwind_info (unwind_ops);
1406 /* Unwind info for imt trampolines */
1407 sprintf (symbol, "%simt_trampolines_page_gen_p", acfg->user_symbol_prefix);
1408 mono_add_unwind_op_def_cfa (unwind_ops, 0, 0, ARMREG_SP, 0);
1409 mono_add_unwind_op_def_cfa_offset (unwind_ops, 4, 0, 3 * sizeof (mgreg_t));
1410 save_unwind_info (acfg, symbol, unwind_ops);
1411 mono_free_unwind_info (unwind_ops);
1413 sprintf (symbol, "%simt_trampolines_page_sp_p", acfg->user_symbol_prefix);
1414 mono_add_unwind_op_def_cfa (unwind_ops, 0, 0, ARMREG_SP, 0);
1415 save_unwind_info (acfg, symbol, unwind_ops);
1416 mono_free_unwind_info (unwind_ops);
1417 #elif defined(TARGET_ARM64)
1418 arm64_emit_specific_trampoline_pages (acfg);
1423 * arch_emit_specific_trampoline:
1425 * Emit code for a specific trampoline. OFFSET is the offset of the first of
1426 * two GOT slots which contain the generic trampoline address and the trampoline
1427 * argument. TRAMP_SIZE is set to the size of the emitted trampoline.
1430 arch_emit_specific_trampoline (MonoAotCompile *acfg, int offset, int *tramp_size)
1433 * The trampolines created here are variations of the specific
1434 * trampolines created in mono_arch_create_specific_trampoline (). The
1436 * - the generic trampoline address is taken from a got slot.
1437 * - the offset of the got slot where the trampoline argument is stored
1438 * is embedded in the instruction stream, and the generic trampoline
1439 * can load the argument by loading the offset, adding it to the
1440 * address of the trampoline to get the address of the got slot, and
1441 * loading the argument from there.
1442 * - all the trampolines should be of the same length.
1444 #if defined(TARGET_AMD64)
1445 #if defined(__default_codegen__)
1446 /* This should be exactly 8 bytes long */
1448 /* call *<offset>(%rip) */
1450 emit_unset_mode (acfg);
1451 fprintf (acfg->fp, "call *%s+%d(%%rip)\n", acfg->got_symbol, (int)(offset * sizeof (gpointer)));
1452 emit_zero_bytes (acfg, 2);
1454 emit_byte (acfg, '\x41');
1455 emit_byte (acfg, '\xff');
1456 emit_byte (acfg, '\x15');
1457 emit_symbol_diff (acfg, acfg->got_symbol, ".", (offset * sizeof (gpointer)) - 4);
1458 emit_zero_bytes (acfg, 1);
1460 #elif defined(__native_client_codegen__)
1462 guint8 *buf_aligned = ALIGN_TO(buf, kNaClAlignment);
1463 guint8 *code = buf_aligned;
1468 /* Emit this call in 'code' so we can find out how long it is. */
1469 amd64_call_reg (code, AMD64_R11);
1470 call_start = mono_arch_nacl_skip_nops (buf_aligned);
1471 call_len = code - call_start;
1473 /* The tramp_size is twice the NaCl alignment because it starts with */
1474 /* a call which needs to be aligned to the end of the boundary. */
1475 *tramp_size = kNaClAlignment*2;
1477 /* Emit nops to align call site below which is 7 bytes plus */
1478 /* the length of the call sequence emitted above. */
1479 /* Note: this requires the specific trampoline starts on a */
1480 /* kNaclAlignedment aligned address, which it does because */
1481 /* it's its own function that is aligned. */
1482 guint8 nop_buf[256];
1483 guint8 *nopbuf_aligned = ALIGN_TO (nop_buf, kNaClAlignment);
1484 guint8 *nopbuf_end = mono_arch_nacl_pad (nopbuf_aligned, kNaClAlignment - 7 - (call_len));
1485 emit_bytes (acfg, nopbuf_aligned, nopbuf_end - nopbuf_aligned);
1487 /* The trampoline is stored at the offset'th pointer, the -4 is */
1488 /* present because RIP relative addressing starts at the end of */
1489 /* the current instruction, while the label "." is relative to */
1490 /* the beginning of the current asm location, which in this case */
1491 /* is not the mov instruction, but the offset itself, due to the */
1492 /* way the bytes and ints are emitted here. */
1493 got_offset = (offset * sizeof(gpointer)) - 4;
1495 /* mov <OFFSET>(%rip), %r11d */
1496 emit_byte (acfg, '\x45');
1497 emit_byte (acfg, '\x8b');
1498 emit_byte (acfg, '\x1d');
1499 emit_symbol_diff (acfg, acfg->got_symbol, ".", got_offset);
1502 emit_bytes (acfg, call_start, call_len);
1504 /* The arg is stored at the offset+1 pointer, relative to beginning */
1505 /* of trampoline: 7 for mov, plus the call length, and 1 for push. */
1506 got_offset = ((offset + 1) * sizeof(gpointer)) + 7 + call_len + 1;
1508 /* We can't emit this data directly, hide in a "push imm32" */
1509 emit_byte (acfg, '\x68'); /* push */
1510 emit_symbol_diff (acfg, acfg->got_symbol, ".", got_offset);
1511 emit_alignment (acfg, kNaClAlignment);
1512 #endif /*__native_client_codegen__*/
1513 #elif defined(TARGET_ARM)
1517 /* This should be exactly 20 bytes long */
1520 ARM_PUSH (code, 0x5fff);
1521 ARM_LDR_IMM (code, ARMREG_R1, ARMREG_PC, 4);
1522 /* Load the value from the GOT */
1523 ARM_LDR_REG_REG (code, ARMREG_R1, ARMREG_PC, ARMREG_R1);
1525 ARM_BLX_REG (code, ARMREG_R1);
1527 g_assert (code - buf == 16);
1530 emit_bytes (acfg, buf, code - buf);
1532 * Only one offset is needed, since the second one would be equal to the
1535 emit_symbol_diff (acfg, acfg->got_symbol, ".", (offset * sizeof (gpointer)) - 4 + 4);
1536 //emit_symbol_diff (acfg, acfg->got_symbol, ".", ((offset + 1) * sizeof (gpointer)) - 4 + 8);
1537 #elif defined(TARGET_ARM64)
1538 arm64_emit_specific_trampoline (acfg, offset, tramp_size);
1539 #elif defined(TARGET_POWERPC)
1547 * PPC has no ip relative addressing, so we need to compute the address
1548 * of the mscorlib got. That is slow and complex, so instead, we store it
1549 * in the second got slot of every aot image. The caller already computed
1550 * the address of its got and placed it into r30.
1552 emit_unset_mode (acfg);
1553 /* Load mscorlib got address */
1554 fprintf (acfg->fp, "%s 0, %d(30)\n", PPC_LD_OP, (int)sizeof (gpointer));
1555 /* Load generic trampoline address */
1556 fprintf (acfg->fp, "lis 11, %d@h\n", (int)(offset * sizeof (gpointer)));
1557 fprintf (acfg->fp, "ori 11, 11, %d@l\n", (int)(offset * sizeof (gpointer)));
1558 fprintf (acfg->fp, "%s 11, 11, 0\n", PPC_LDX_OP);
1559 #ifdef PPC_USES_FUNCTION_DESCRIPTOR
1560 fprintf (acfg->fp, "%s 11, 0(11)\n", PPC_LD_OP);
1562 fprintf (acfg->fp, "mtctr 11\n");
1563 /* Load trampoline argument */
1564 /* On ppc, we pass it normally to the generic trampoline */
1565 fprintf (acfg->fp, "lis 11, %d@h\n", (int)((offset + 1) * sizeof (gpointer)));
1566 fprintf (acfg->fp, "ori 11, 11, %d@l\n", (int)((offset + 1) * sizeof (gpointer)));
1567 fprintf (acfg->fp, "%s 0, 11, 0\n", PPC_LDX_OP);
1568 /* Branch to generic trampoline */
1569 fprintf (acfg->fp, "bctr\n");
1571 #ifdef PPC_USES_FUNCTION_DESCRIPTOR
1572 *tramp_size = 10 * 4;
1574 *tramp_size = 9 * 4;
1576 #elif defined(TARGET_X86)
1580 /* Similar to the PPC code above */
1582 /* FIXME: Could this clobber the register needed by get_vcall_slot () ? */
1585 /* Load mscorlib got address */
1586 x86_mov_reg_membase (code, X86_ECX, MONO_ARCH_GOT_REG, sizeof (gpointer), 4);
1587 /* Push trampoline argument */
1588 x86_push_membase (code, X86_ECX, (offset + 1) * sizeof (gpointer));
1589 /* Load generic trampoline address */
1590 x86_mov_reg_membase (code, X86_ECX, X86_ECX, offset * sizeof (gpointer), 4);
1591 /* Branch to generic trampoline */
1592 x86_jump_reg (code, X86_ECX);
1594 #ifdef __native_client_codegen__
1596 /* emit nops to next 32 byte alignment */
1597 int a = (~kNaClAlignmentMask) & ((code - buf) + kNaClAlignment - 1);
1598 while (code < (buf + a)) x86_nop(code);
1601 emit_bytes (acfg, buf, code - buf);
1603 *tramp_size = NACL_SIZE(17, kNaClAlignment);
1604 g_assert (code - buf == *tramp_size);
1606 g_assert_not_reached ();
1611 * arch_emit_unbox_trampoline:
1613 * Emit code for the unbox trampoline for METHOD used in the full-aot case.
1614 * CALL_TARGET is the symbol pointing to the native code of METHOD.
1617 arch_emit_unbox_trampoline (MonoAotCompile *acfg, MonoCompile *cfg, MonoMethod *method, const char *call_target)
1619 #if defined(TARGET_AMD64)
1624 this_reg = mono_arch_get_this_arg_reg (NULL);
1626 amd64_alu_reg_imm (code, X86_ADD, this_reg, sizeof (MonoObject));
1628 emit_bytes (acfg, buf, code - buf);
1631 emit_unset_mode (acfg);
1632 fprintf (acfg->fp, "jmp %s\n", call_target);
1634 emit_byte (acfg, '\xe9');
1635 emit_symbol_diff (acfg, call_target, ".", -4);
1637 #elif defined(TARGET_X86)
1644 x86_alu_membase_imm (code, X86_ADD, X86_ESP, this_pos, sizeof (MonoObject));
1646 emit_bytes (acfg, buf, code - buf);
1649 emit_byte (acfg, '\xe9');
1650 emit_symbol_diff (acfg, call_target, ".", -4);
1651 #elif defined(TARGET_ARM)
1655 if (acfg->thumb_mixed && cfg->compile_llvm) {
1656 fprintf (acfg->fp, "add r0, r0, #%d\n", (int)sizeof (MonoObject));
1657 fprintf (acfg->fp, "b %s\n", call_target);
1658 fprintf (acfg->fp, ".arm\n");
1659 fprintf (acfg->fp, ".align 2\n");
1665 ARM_ADD_REG_IMM8 (code, ARMREG_R0, ARMREG_R0, sizeof (MonoObject));
1667 emit_bytes (acfg, buf, code - buf);
1668 /* jump to method */
1669 if (acfg->thumb_mixed && cfg->compile_llvm)
1670 fprintf (acfg->fp, "\n\tbx %s\n", call_target);
1672 fprintf (acfg->fp, "\n\tb %s\n", call_target);
1673 #elif defined(TARGET_ARM64)
1674 arm64_emit_unbox_trampoline (acfg, cfg, method, call_target);
1675 #elif defined(TARGET_POWERPC)
1678 fprintf (acfg->fp, "\n\taddi %d, %d, %d\n", this_pos, this_pos, (int)sizeof (MonoObject));
1679 fprintf (acfg->fp, "\n\tb %s\n", call_target);
1681 g_assert_not_reached ();
1686 * arch_emit_static_rgctx_trampoline:
1688 * Emit code for a static rgctx trampoline. OFFSET is the offset of the first of
1689 * two GOT slots which contain the rgctx argument, and the method to jump to.
1690 * TRAMP_SIZE is set to the size of the emitted trampoline.
1691 * These kinds of trampolines cannot be enumerated statically, since there could
1692 * be one trampoline per method instantiation, so we emit the same code for all
1693 * trampolines, and parameterize them using two GOT slots.
1696 arch_emit_static_rgctx_trampoline (MonoAotCompile *acfg, int offset, int *tramp_size)
1698 #if defined(TARGET_AMD64)
1699 #if defined(__default_codegen__)
1700 /* This should be exactly 13 bytes long */
1704 emit_unset_mode (acfg);
1705 fprintf (acfg->fp, "mov %s+%d(%%rip), %%r10\n", acfg->got_symbol, (int)(offset * sizeof (gpointer)));
1706 fprintf (acfg->fp, "jmp *%s+%d(%%rip)\n", acfg->got_symbol, (int)((offset + 1) * sizeof (gpointer)));
1708 /* mov <OFFSET>(%rip), %r10 */
1709 emit_byte (acfg, '\x4d');
1710 emit_byte (acfg, '\x8b');
1711 emit_byte (acfg, '\x15');
1712 emit_symbol_diff (acfg, acfg->got_symbol, ".", (offset * sizeof (gpointer)) - 4);
1714 /* jmp *<offset>(%rip) */
1715 emit_byte (acfg, '\xff');
1716 emit_byte (acfg, '\x25');
1717 emit_symbol_diff (acfg, acfg->got_symbol, ".", ((offset + 1) * sizeof (gpointer)) - 4);
1719 #elif defined(__native_client_codegen__)
1721 guint8 *buf_aligned = ALIGN_TO(buf, kNaClAlignment);
1722 guint8 *code = buf_aligned;
1724 /* mov <OFFSET>(%rip), %r10d */
1725 emit_byte (acfg, '\x45');
1726 emit_byte (acfg, '\x8b');
1727 emit_byte (acfg, '\x15');
1728 emit_symbol_diff (acfg, acfg->got_symbol, ".", (offset * sizeof (gpointer)) - 4);
1730 /* mov <OFFSET>(%rip), %r11d */
1731 emit_byte (acfg, '\x45');
1732 emit_byte (acfg, '\x8b');
1733 emit_byte (acfg, '\x1d');
1734 emit_symbol_diff (acfg, acfg->got_symbol, ".", ((offset + 1) * sizeof (gpointer)) - 4);
1737 amd64_jump_reg (code, AMD64_R11);
1738 emit_bytes (acfg, buf_aligned, code - buf_aligned);
1740 emit_alignment (acfg, kNaClAlignment);
1741 *tramp_size = kNaClAlignment;
1742 #endif /*__native_client_codegen__*/
1744 #elif defined(TARGET_ARM)
1748 /* This should be exactly 24 bytes long */
1751 /* Load rgctx value */
1752 ARM_LDR_IMM (code, ARMREG_IP, ARMREG_PC, 8);
1753 ARM_LDR_REG_REG (code, MONO_ARCH_RGCTX_REG, ARMREG_PC, ARMREG_IP);
1754 /* Load branch addr + branch */
1755 ARM_LDR_IMM (code, ARMREG_IP, ARMREG_PC, 4);
1756 ARM_LDR_REG_REG (code, ARMREG_PC, ARMREG_PC, ARMREG_IP);
1758 g_assert (code - buf == 16);
1761 emit_bytes (acfg, buf, code - buf);
1762 emit_symbol_diff (acfg, acfg->got_symbol, ".", (offset * sizeof (gpointer)) - 4 + 8);
1763 emit_symbol_diff (acfg, acfg->got_symbol, ".", ((offset + 1) * sizeof (gpointer)) - 4 + 4);
1764 #elif defined(TARGET_ARM64)
1765 arm64_emit_static_rgctx_trampoline (acfg, offset, tramp_size);
1766 #elif defined(TARGET_POWERPC)
1774 * PPC has no ip relative addressing, so we need to compute the address
1775 * of the mscorlib got. That is slow and complex, so instead, we store it
1776 * in the second got slot of every aot image. The caller already computed
1777 * the address of its got and placed it into r30.
1779 emit_unset_mode (acfg);
1780 /* Load mscorlib got address */
1781 fprintf (acfg->fp, "%s 0, %d(30)\n", PPC_LD_OP, (int)sizeof (gpointer));
1783 fprintf (acfg->fp, "lis 11, %d@h\n", (int)(offset * sizeof (gpointer)));
1784 fprintf (acfg->fp, "ori 11, 11, %d@l\n", (int)(offset * sizeof (gpointer)));
1785 fprintf (acfg->fp, "%s %d, 11, 0\n", PPC_LDX_OP, MONO_ARCH_RGCTX_REG);
1786 /* Load target address */
1787 fprintf (acfg->fp, "lis 11, %d@h\n", (int)((offset + 1) * sizeof (gpointer)));
1788 fprintf (acfg->fp, "ori 11, 11, %d@l\n", (int)((offset + 1) * sizeof (gpointer)));
1789 fprintf (acfg->fp, "%s 11, 11, 0\n", PPC_LDX_OP);
1790 #ifdef PPC_USES_FUNCTION_DESCRIPTOR
1791 fprintf (acfg->fp, "%s 2, %d(11)\n", PPC_LD_OP, (int)sizeof (gpointer));
1792 fprintf (acfg->fp, "%s 11, 0(11)\n", PPC_LD_OP);
1794 fprintf (acfg->fp, "mtctr 11\n");
1795 /* Branch to the target address */
1796 fprintf (acfg->fp, "bctr\n");
1798 #ifdef PPC_USES_FUNCTION_DESCRIPTOR
1799 *tramp_size = 11 * 4;
1801 *tramp_size = 9 * 4;
1804 #elif defined(TARGET_X86)
1808 /* Similar to the PPC code above */
1810 g_assert (MONO_ARCH_RGCTX_REG != X86_ECX);
1813 /* Load mscorlib got address */
1814 x86_mov_reg_membase (code, X86_ECX, MONO_ARCH_GOT_REG, sizeof (gpointer), 4);
1816 x86_mov_reg_membase (code, MONO_ARCH_RGCTX_REG, X86_ECX, offset * sizeof (gpointer), 4);
1817 /* Branch to the target address */
1818 x86_jump_membase (code, X86_ECX, (offset + 1) * sizeof (gpointer));
1820 #ifdef __native_client_codegen__
1822 /* emit nops to next 32 byte alignment */
1823 int a = (~kNaClAlignmentMask) & ((code - buf) + kNaClAlignment - 1);
1824 while (code < (buf + a)) x86_nop(code);
1828 emit_bytes (acfg, buf, code - buf);
1830 *tramp_size = NACL_SIZE (15, kNaClAlignment);
1831 g_assert (code - buf == *tramp_size);
1833 g_assert_not_reached ();
1838 * arch_emit_imt_thunk:
1840 * Emit an IMT thunk usable in full-aot mode. The thunk uses 1 got slot which
1841 * points to an array of pointer pairs. The pairs of the form [key, ptr], where
1842 * key is the IMT key, and ptr holds the address of a memory location holding
1843 * the address to branch to if the IMT arg matches the key. The array is
1844 * terminated by a pair whose key is NULL, and whose ptr is the address of the
1846 * TRAMP_SIZE is set to the size of the emitted trampoline.
1849 arch_emit_imt_thunk (MonoAotCompile *acfg, int offset, int *tramp_size)
1851 #if defined(TARGET_AMD64)
1853 #if defined(__native_client_codegen__)
1856 guint8 *labels [16];
1858 guint8 *mov_buf_ptr = mov_buf;
1860 const int kSizeOfMove = 7;
1861 #if defined(__default_codegen__)
1862 code = buf = (guint8 *)g_malloc (256);
1863 #elif defined(__native_client_codegen__)
1864 buf_alloc = g_malloc (256 + kNaClAlignment + kSizeOfMove);
1865 buf = ((guint)buf_alloc + kNaClAlignment) & ~kNaClAlignmentMask;
1866 /* The RIP relative move below is emitted first */
1871 /* FIXME: Optimize this, i.e. use binary search etc. */
1872 /* Maybe move the body into a separate function (slower, but much smaller) */
1874 /* MONO_ARCH_IMT_SCRATCH_REG is a free register */
1877 emit_unset_mode (acfg);
1878 fprintf (acfg->fp, "mov %s+%d(%%rip), %s\n", acfg->got_symbol, (int)(offset * sizeof (gpointer)), mono_arch_regname (MONO_ARCH_IMT_SCRATCH_REG));
1882 amd64_alu_membase_imm (code, X86_CMP, MONO_ARCH_IMT_SCRATCH_REG, 0, 0);
1884 amd64_branch8 (code, X86_CC_Z, 0, FALSE);
1887 amd64_alu_membase_reg_size (code, X86_CMP, MONO_ARCH_IMT_SCRATCH_REG, 0, MONO_ARCH_IMT_REG, sizeof (gpointer));
1889 amd64_branch8 (code, X86_CC_Z, 0, FALSE);
1892 amd64_alu_reg_imm (code, X86_ADD, MONO_ARCH_IMT_SCRATCH_REG, 2 * sizeof (gpointer));
1893 amd64_jump_code (code, labels [0]);
1896 mono_amd64_patch (labels [2], code);
1897 amd64_mov_reg_membase (code, MONO_ARCH_IMT_SCRATCH_REG, MONO_ARCH_IMT_SCRATCH_REG, sizeof (gpointer), sizeof (gpointer));
1898 amd64_jump_membase (code, MONO_ARCH_IMT_SCRATCH_REG, 0);
1901 mono_amd64_patch (labels [1], code);
1902 /* Load fail tramp */
1903 amd64_alu_reg_imm (code, X86_ADD, MONO_ARCH_IMT_SCRATCH_REG, sizeof (gpointer));
1904 /* Check if there is a fail tramp */
1905 amd64_alu_membase_imm (code, X86_CMP, MONO_ARCH_IMT_SCRATCH_REG, 0, 0);
1907 amd64_branch8 (code, X86_CC_Z, 0, FALSE);
1908 /* Jump to fail tramp */
1909 amd64_jump_membase (code, MONO_ARCH_IMT_SCRATCH_REG, 0);
1912 mono_amd64_patch (labels [3], code);
1913 x86_breakpoint (code);
1916 /* mov <OFFSET>(%rip), MONO_ARCH_IMT_SCRATCH_REG */
1917 amd64_emit_rex (mov_buf_ptr, sizeof(gpointer), MONO_ARCH_IMT_SCRATCH_REG, 0, AMD64_RIP);
1918 *(mov_buf_ptr)++ = (unsigned char)0x8b; /* mov opcode */
1919 x86_address_byte (mov_buf_ptr, 0, MONO_ARCH_IMT_SCRATCH_REG & 0x7, 5);
1920 emit_bytes (acfg, mov_buf, mov_buf_ptr - mov_buf);
1921 emit_symbol_diff (acfg, acfg->got_symbol, ".", (offset * sizeof (gpointer)) - 4);
1923 emit_bytes (acfg, buf, code - buf);
1925 *tramp_size = code - buf + kSizeOfMove;
1926 #if defined(__native_client_codegen__)
1927 /* The tramp will be padded to the next kNaClAlignment bundle. */
1928 *tramp_size = ALIGN_TO ((*tramp_size), kNaClAlignment);
1931 #if defined(__default_codegen__)
1933 #elif defined(__native_client_codegen__)
1937 #elif defined(TARGET_X86)
1939 #ifdef __native_client_codegen__
1942 guint8 *labels [16];
1944 #if defined(__default_codegen__)
1945 code = buf = g_malloc (256);
1946 #elif defined(__native_client_codegen__)
1947 buf_alloc = g_malloc (256 + kNaClAlignment);
1948 code = buf = ((guint)buf_alloc + kNaClAlignment) & ~kNaClAlignmentMask;
1951 /* Allocate a temporary stack slot */
1952 x86_push_reg (code, X86_EAX);
1954 x86_push_reg (code, X86_EAX);
1956 /* Load mscorlib got address */
1957 x86_mov_reg_membase (code, X86_EAX, MONO_ARCH_GOT_REG, sizeof (gpointer), 4);
1959 x86_mov_reg_membase (code, X86_EAX, X86_EAX, offset * sizeof (gpointer), 4);
1962 x86_alu_membase_imm (code, X86_CMP, X86_EAX, 0, 0);
1964 x86_branch8 (code, X86_CC_Z, FALSE, 0);
1967 x86_alu_membase_reg (code, X86_CMP, X86_EAX, 0, MONO_ARCH_IMT_REG);
1969 x86_branch8 (code, X86_CC_Z, FALSE, 0);
1972 x86_alu_reg_imm (code, X86_ADD, X86_EAX, 2 * sizeof (gpointer));
1973 x86_jump_code (code, labels [0]);
1976 mono_x86_patch (labels [2], code);
1977 x86_mov_reg_membase (code, X86_EAX, X86_EAX, sizeof (gpointer), 4);
1978 x86_mov_reg_membase (code, X86_EAX, X86_EAX, 0, 4);
1979 /* Save the target address to the temporary stack location */
1980 x86_mov_membase_reg (code, X86_ESP, 4, X86_EAX, 4);
1982 x86_pop_reg (code, X86_EAX);
1983 /* Jump to the target address */
1987 mono_x86_patch (labels [1], code);
1988 /* Load fail tramp */
1989 x86_mov_reg_membase (code, X86_EAX, X86_EAX, sizeof (gpointer), 4);
1990 x86_alu_membase_imm (code, X86_CMP, X86_EAX, 0, 0);
1992 x86_branch8 (code, X86_CC_Z, FALSE, 0);
1993 /* Jump to fail tramp */
1994 x86_mov_membase_reg (code, X86_ESP, 4, X86_EAX, 4);
1995 x86_pop_reg (code, X86_EAX);
1999 mono_x86_patch (labels [3], code);
2000 x86_breakpoint (code);
2002 #ifdef __native_client_codegen__
2004 /* emit nops to next 32 byte alignment */
2005 int a = (~kNaClAlignmentMask) & ((code - buf) + kNaClAlignment - 1);
2006 while (code < (buf + a)) x86_nop(code);
2009 emit_bytes (acfg, buf, code - buf);
2011 *tramp_size = code - buf;
2013 #if defined(__default_codegen__)
2015 #elif defined(__native_client_codegen__)
2019 #elif defined(TARGET_ARM)
2021 guint8 *code, *code2, *labels [16];
2025 /* The IMT method is in v5 */
2027 /* Need at least two free registers, plus a slot for storing the pc */
2028 ARM_PUSH (code, (1 << ARMREG_R0)|(1 << ARMREG_R1)|(1 << ARMREG_R2));
2030 /* Load the parameter from the GOT */
2031 ARM_LDR_IMM (code, ARMREG_R0, ARMREG_PC, 0);
2032 ARM_LDR_REG_REG (code, ARMREG_R0, ARMREG_PC, ARMREG_R0);
2035 ARM_LDR_IMM (code, ARMREG_R1, ARMREG_R0, 0);
2036 ARM_CMP_REG_REG (code, ARMREG_R1, ARMREG_V5);
2038 ARM_B_COND (code, ARMCOND_EQ, 0);
2040 /* End-of-loop check */
2041 ARM_CMP_REG_IMM (code, ARMREG_R1, 0, 0);
2043 ARM_B_COND (code, ARMCOND_EQ, 0);
2046 ARM_ADD_REG_IMM8 (code, ARMREG_R0, ARMREG_R0, sizeof (gpointer) * 2);
2049 arm_patch (labels [4], labels [1]);
2052 arm_patch (labels [2], code);
2053 ARM_LDR_IMM (code, ARMREG_R0, ARMREG_R0, 4);
2054 ARM_LDR_IMM (code, ARMREG_R0, ARMREG_R0, 0);
2055 /* Save it to the third stack slot */
2056 ARM_STR_IMM (code, ARMREG_R0, ARMREG_SP, 8);
2057 /* Restore the registers and branch */
2058 ARM_POP (code, (1 << ARMREG_R0)|(1 << ARMREG_R1)|(1 << ARMREG_PC));
2061 arm_patch (labels [3], code);
2062 ARM_LDR_IMM (code, ARMREG_R0, ARMREG_R0, 4);
2063 ARM_STR_IMM (code, ARMREG_R0, ARMREG_SP, 8);
2064 ARM_POP (code, (1 << ARMREG_R0)|(1 << ARMREG_R1)|(1 << ARMREG_PC));
2068 ARM_LDR_IMM (code2, ARMREG_R0, ARMREG_PC, (code - (labels [0] + 8)));
2070 emit_bytes (acfg, buf, code - buf);
2071 emit_symbol_diff (acfg, acfg->got_symbol, ".", (offset * sizeof (gpointer)) + (code - (labels [0] + 8)) - 4);
2073 *tramp_size = code - buf + 4;
2074 #elif defined(TARGET_ARM64)
2075 arm64_emit_imt_thunk (acfg, offset, tramp_size);
2076 #elif defined(TARGET_POWERPC)
2078 guint8 *code, *labels [16];
2082 /* Load the mscorlib got address */
2083 ppc_ldptr (code, ppc_r12, sizeof (gpointer), ppc_r30);
2084 /* Load the parameter from the GOT */
2085 ppc_load (code, ppc_r0, offset * sizeof (gpointer));
2086 ppc_ldptr_indexed (code, ppc_r12, ppc_r12, ppc_r0);
2088 /* Load and check key */
2090 ppc_ldptr (code, ppc_r0, 0, ppc_r12);
2091 ppc_cmp (code, 0, sizeof (gpointer) == 8 ? 1 : 0, ppc_r0, MONO_ARCH_IMT_REG);
2093 ppc_bc (code, PPC_BR_TRUE, PPC_BR_EQ, 0);
2095 /* End-of-loop check */
2096 ppc_cmpi (code, 0, sizeof (gpointer) == 8 ? 1 : 0, ppc_r0, 0);
2098 ppc_bc (code, PPC_BR_TRUE, PPC_BR_EQ, 0);
2101 ppc_addi (code, ppc_r12, ppc_r12, 2 * sizeof (gpointer));
2104 mono_ppc_patch (labels [4], labels [1]);
2107 mono_ppc_patch (labels [2], code);
2108 ppc_ldptr (code, ppc_r12, sizeof (gpointer), ppc_r12);
2109 /* r12 now contains the value of the vtable slot */
2110 /* this is not a function descriptor on ppc64 */
2111 ppc_ldptr (code, ppc_r12, 0, ppc_r12);
2112 ppc_mtctr (code, ppc_r12);
2113 ppc_bcctr (code, PPC_BR_ALWAYS, 0);
2116 mono_ppc_patch (labels [3], code);
2120 *tramp_size = code - buf;
2122 emit_bytes (acfg, buf, code - buf);
2124 g_assert_not_reached ();
2129 * arch_emit_gsharedvt_arg_trampoline:
2131 * Emit code for a gsharedvt arg trampoline. OFFSET is the offset of the first of
2132 * two GOT slots which contain the argument, and the code to jump to.
2133 * TRAMP_SIZE is set to the size of the emitted trampoline.
2134 * These kinds of trampolines cannot be enumerated statically, since there could
2135 * be one trampoline per method instantiation, so we emit the same code for all
2136 * trampolines, and parameterize them using two GOT slots.
2139 arch_emit_gsharedvt_arg_trampoline (MonoAotCompile *acfg, int offset, int *tramp_size)
2141 #if defined(TARGET_X86)
2145 /* Similar to the PPC code above */
2147 g_assert (MONO_ARCH_RGCTX_REG != X86_ECX);
2150 /* Load mscorlib got address */
2151 x86_mov_reg_membase (code, X86_ECX, MONO_ARCH_GOT_REG, sizeof (gpointer), 4);
2153 x86_mov_reg_membase (code, X86_EAX, X86_ECX, offset * sizeof (gpointer), 4);
2154 /* Branch to the target address */
2155 x86_jump_membase (code, X86_ECX, (offset + 1) * sizeof (gpointer));
2157 #ifdef __native_client_codegen__
2159 /* emit nops to next 32 byte alignment */
2160 int a = (~kNaClAlignmentMask) & ((code - buf) + kNaClAlignment - 1);
2161 while (code < (buf + a)) x86_nop(code);
2165 emit_bytes (acfg, buf, code - buf);
2167 *tramp_size = NACL_SIZE (15, kNaClAlignment);
2168 g_assert (code - buf == *tramp_size);
2169 #elif defined(TARGET_ARM)
2173 /* The same as mono_arch_get_gsharedvt_arg_trampoline (), but for AOT */
2174 /* Similar to arch_emit_specific_trampoline () */
2177 ARM_PUSH (code, (1 << ARMREG_R0) | (1 << ARMREG_R1) | (1 << ARMREG_R2) | (1 << ARMREG_R3));
2178 ARM_LDR_IMM (code, ARMREG_R1, ARMREG_PC, 8);
2179 /* Load the arg value from the GOT */
2180 ARM_LDR_REG_REG (code, ARMREG_R0, ARMREG_PC, ARMREG_R1);
2181 /* Load the addr from the GOT */
2182 ARM_LDR_REG_REG (code, ARMREG_R1, ARMREG_PC, ARMREG_R1);
2184 ARM_BX (code, ARMREG_R1);
2186 g_assert (code - buf == 20);
2189 emit_bytes (acfg, buf, code - buf);
2190 emit_symbol_diff (acfg, acfg->got_symbol, ".", (offset * sizeof (gpointer)) + 4);
2191 #elif defined(TARGET_ARM64)
2192 arm64_emit_gsharedvt_arg_trampoline (acfg, offset, tramp_size);
2194 g_assert_not_reached ();
2198 /* END OF ARCH SPECIFIC CODE */
2201 mono_get_field_token (MonoClassField *field)
2203 MonoClass *klass = field->parent;
2206 for (i = 0; i < klass->field.count; ++i) {
2207 if (field == &klass->fields [i])
2208 return MONO_TOKEN_FIELD_DEF | (klass->field.first + 1 + i);
2211 g_assert_not_reached ();
2216 encode_value (gint32 value, guint8 *buf, guint8 **endbuf)
2220 //printf ("ENCODE: %d 0x%x.\n", value, value);
2223 * Same encoding as the one used in the metadata, extended to handle values
2224 * greater than 0x1fffffff.
2226 if ((value >= 0) && (value <= 127))
2228 else if ((value >= 0) && (value <= 16383)) {
2229 p [0] = 0x80 | (value >> 8);
2230 p [1] = value & 0xff;
2232 } else if ((value >= 0) && (value <= 0x1fffffff)) {
2233 p [0] = (value >> 24) | 0xc0;
2234 p [1] = (value >> 16) & 0xff;
2235 p [2] = (value >> 8) & 0xff;
2236 p [3] = value & 0xff;
2241 p [1] = (value >> 24) & 0xff;
2242 p [2] = (value >> 16) & 0xff;
2243 p [3] = (value >> 8) & 0xff;
2244 p [4] = value & 0xff;
2252 stream_init (MonoDynamicStream *sh)
2255 sh->alloc_size = 4096;
2256 sh->data = (char *)g_malloc (4096);
2258 /* So offsets are > 0 */
2264 make_room_in_stream (MonoDynamicStream *stream, int size)
2266 if (size <= stream->alloc_size)
2269 while (stream->alloc_size <= size) {
2270 if (stream->alloc_size < 4096)
2271 stream->alloc_size = 4096;
2273 stream->alloc_size *= 2;
2276 stream->data = (char *)g_realloc (stream->data, stream->alloc_size);
2280 add_stream_data (MonoDynamicStream *stream, const char *data, guint32 len)
2284 make_room_in_stream (stream, stream->index + len);
2285 memcpy (stream->data + stream->index, data, len);
2286 idx = stream->index;
2287 stream->index += len;
2294 * Add data to the binary blob inside the aot image. Returns the offset inside the
2295 * blob where the data was stored.
2298 add_to_blob (MonoAotCompile *acfg, const guint8 *data, guint32 data_len)
2300 if (acfg->blob.alloc_size == 0)
2301 stream_init (&acfg->blob);
2303 return add_stream_data (&acfg->blob, (char*)data, data_len);
2307 add_to_blob_aligned (MonoAotCompile *acfg, const guint8 *data, guint32 data_len, guint32 align)
2312 if (acfg->blob.alloc_size == 0)
2313 stream_init (&acfg->blob);
2315 count = acfg->blob.index % align;
2317 /* we assume the stream data will be aligned */
2319 add_stream_data (&acfg->blob, buf, 4 - count);
2321 return add_stream_data (&acfg->blob, (char*)data, data_len);
2325 * emit_offset_table:
2327 * Emit a table of increasing offsets in a compact form using differential encoding.
2328 * There is an index entry for each GROUP_SIZE number of entries. The greater the
2329 * group size, the more compact the table becomes, but the slower it becomes to compute
2330 * a given entry. Returns the size of the table.
2333 emit_offset_table (MonoAotCompile *acfg, const char *symbol, int noffsets, int group_size, gint32 *offsets)
2335 gint32 current_offset;
2336 int i, buf_size, ngroups, index_entry_size;
2338 guint8 *data_p, *data_buf;
2339 guint32 *index_offsets;
2341 ngroups = (noffsets + (group_size - 1)) / group_size;
2343 index_offsets = g_new0 (guint32, ngroups);
2345 buf_size = noffsets * 4;
2346 p = buf = (guint8 *)g_malloc0 (buf_size);
2349 for (i = 0; i < noffsets; ++i) {
2350 //printf ("D: %d -> %d\n", i, offsets [i]);
2351 if ((i % group_size) == 0) {
2352 index_offsets [i / group_size] = p - buf;
2353 /* Emit the full value for these entries */
2354 encode_value (offsets [i], p, &p);
2356 /* The offsets are allowed to be non-increasing */
2357 //g_assert (offsets [i] >= current_offset);
2358 encode_value (offsets [i] - current_offset, p, &p);
2360 current_offset = offsets [i];
2365 if (ngroups && index_offsets [ngroups - 1] < 65000)
2366 index_entry_size = 2;
2368 index_entry_size = 4;
2370 buf_size = (data_p - data_buf) + (ngroups * 4) + 16;
2371 p = buf = (guint8 *)g_malloc0 (buf_size);
2373 /* Emit the header */
2374 encode_int (noffsets, p, &p);
2375 encode_int (group_size, p, &p);
2376 encode_int (ngroups, p, &p);
2377 encode_int (index_entry_size, p, &p);
2379 /* Emit the index */
2380 for (i = 0; i < ngroups; ++i) {
2381 if (index_entry_size == 2)
2382 encode_int16 (index_offsets [i], p, &p);
2384 encode_int (index_offsets [i], p, &p);
2387 memcpy (p, data_buf, data_p - data_buf);
2388 p += data_p - data_buf;
2390 g_assert (p - buf <= buf_size);
2393 mono_llvm_emit_aot_data (symbol, buf, p - buf);
2395 emit_section_change (acfg, RODATA_SECT, 1);
2396 emit_alignment (acfg, 8);
2397 emit_label (acfg, symbol);
2398 emit_bytes (acfg, buf, p - buf);
2404 return (int)(p - buf);
2408 get_image_index (MonoAotCompile *cfg, MonoImage *image)
2412 index = GPOINTER_TO_UINT (g_hash_table_lookup (cfg->image_hash, image));
2416 index = g_hash_table_size (cfg->image_hash);
2417 g_hash_table_insert (cfg->image_hash, image, GUINT_TO_POINTER (index + 1));
2418 g_ptr_array_add (cfg->image_table, image);
2424 find_typespec_for_class (MonoAotCompile *acfg, MonoClass *klass)
2427 int len = acfg->image->tables [MONO_TABLE_TYPESPEC].rows;
2429 /* FIXME: Search referenced images as well */
2430 if (!acfg->typespec_classes) {
2431 acfg->typespec_classes = (MonoClass **)mono_mempool_alloc0 (acfg->mempool, sizeof (MonoClass*) * len);
2432 for (i = 0; i < len; ++i) {
2434 acfg->typespec_classes [i] = mono_class_get_and_inflate_typespec_checked (acfg->image, MONO_TOKEN_TYPE_SPEC | (i + 1), NULL, &error);
2435 g_assert (mono_error_ok (&error)); /* FIXME error handling */
2438 for (i = 0; i < len; ++i) {
2439 if (acfg->typespec_classes [i] == klass)
2444 return MONO_TOKEN_TYPE_SPEC | (i + 1);
2450 encode_method_ref (MonoAotCompile *acfg, MonoMethod *method, guint8 *buf, guint8 **endbuf);
2453 encode_klass_ref (MonoAotCompile *acfg, MonoClass *klass, guint8 *buf, guint8 **endbuf);
2456 encode_ginst (MonoAotCompile *acfg, MonoGenericInst *inst, guint8 *buf, guint8 **endbuf);
2459 encode_type (MonoAotCompile *acfg, MonoType *t, guint8 *buf, guint8 **endbuf);
2462 encode_klass_ref_inner (MonoAotCompile *acfg, MonoClass *klass, guint8 *buf, guint8 **endbuf)
2467 * The encoding begins with one of the MONO_AOT_TYPEREF values, followed by additional
2471 if (klass->generic_class) {
2473 g_assert (klass->type_token);
2475 /* Find a typespec for a class if possible */
2476 token = find_typespec_for_class (acfg, klass);
2478 encode_value (MONO_AOT_TYPEREF_TYPESPEC_TOKEN, p, &p);
2479 encode_value (token, p, &p);
2481 MonoClass *gclass = klass->generic_class->container_class;
2482 MonoGenericInst *inst = klass->generic_class->context.class_inst;
2483 static int count = 0;
2486 encode_value (MONO_AOT_TYPEREF_GINST, p, &p);
2487 encode_klass_ref (acfg, gclass, p, &p);
2488 encode_ginst (acfg, inst, p, &p);
2492 } else if (klass->type_token) {
2493 int iindex = get_image_index (acfg, klass->image);
2495 g_assert (mono_metadata_token_code (klass->type_token) == MONO_TOKEN_TYPE_DEF);
2497 encode_value (MONO_AOT_TYPEREF_TYPEDEF_INDEX, p, &p);
2498 encode_value (klass->type_token - MONO_TOKEN_TYPE_DEF, p, &p);
2500 encode_value (MONO_AOT_TYPEREF_TYPEDEF_INDEX_IMAGE, p, &p);
2501 encode_value (klass->type_token - MONO_TOKEN_TYPE_DEF, p, &p);
2502 encode_value (get_image_index (acfg, klass->image), p, &p);
2504 } else if ((klass->byval_arg.type == MONO_TYPE_VAR) || (klass->byval_arg.type == MONO_TYPE_MVAR)) {
2505 MonoGenericContainer *container = mono_type_get_generic_param_owner (&klass->byval_arg);
2506 MonoGenericParam *par = klass->byval_arg.data.generic_param;
2508 encode_value (MONO_AOT_TYPEREF_VAR, p, &p);
2510 encode_value (par->gshared_constraint ? 1 : 0, p, &p);
2511 if (par->gshared_constraint) {
2512 MonoGSharedGenericParam *gpar = (MonoGSharedGenericParam*)par;
2513 encode_type (acfg, par->gshared_constraint, p, &p);
2514 encode_klass_ref (acfg, mono_class_from_generic_parameter (gpar->parent, NULL, klass->byval_arg.type == MONO_TYPE_MVAR), p, &p);
2516 encode_value (klass->byval_arg.type, p, &p);
2517 encode_value (mono_type_get_generic_param_num (&klass->byval_arg), p, &p);
2519 encode_value (container->is_anonymous ? 0 : 1, p, &p);
2521 if (!container->is_anonymous) {
2522 encode_value (container->is_method, p, &p);
2523 if (container->is_method)
2524 encode_method_ref (acfg, container->owner.method, p, &p);
2526 encode_klass_ref (acfg, container->owner.klass, p, &p);
2529 } else if (klass->byval_arg.type == MONO_TYPE_PTR) {
2530 encode_value (MONO_AOT_TYPEREF_PTR, p, &p);
2531 encode_type (acfg, &klass->byval_arg, p, &p);
2534 g_assert (klass->rank > 0);
2535 encode_value (MONO_AOT_TYPEREF_ARRAY, p, &p);
2536 encode_value (klass->rank, p, &p);
2537 encode_klass_ref (acfg, klass->element_class, p, &p);
2545 * Encode a reference to KLASS. We use our home-grown encoding instead of the
2546 * standard metadata encoding.
2549 encode_klass_ref (MonoAotCompile *acfg, MonoClass *klass, guint8 *buf, guint8 **endbuf)
2551 gboolean shared = FALSE;
2554 * The encoding of generic instances is large so emit them only once.
2556 if (klass->generic_class) {
2558 g_assert (klass->type_token);
2560 /* Find a typespec for a class if possible */
2561 token = find_typespec_for_class (acfg, klass);
2564 } else if ((klass->byval_arg.type == MONO_TYPE_VAR) || (klass->byval_arg.type == MONO_TYPE_MVAR)) {
2569 guint offset = GPOINTER_TO_UINT (g_hash_table_lookup (acfg->klass_blob_hash, klass));
2573 buf2 = (guint8 *)g_malloc (1024);
2576 encode_klass_ref_inner (acfg, klass, p, &p);
2577 g_assert (p - buf2 < 1024);
2579 offset = add_to_blob (acfg, buf2, p - buf2);
2582 g_hash_table_insert (acfg->klass_blob_hash, klass, GUINT_TO_POINTER (offset + 1));
2588 encode_value (MONO_AOT_TYPEREF_BLOB_INDEX, p, &p);
2589 encode_value (offset, p, &p);
2594 encode_klass_ref_inner (acfg, klass, buf, endbuf);
2598 encode_field_info (MonoAotCompile *cfg, MonoClassField *field, guint8 *buf, guint8 **endbuf)
2600 guint32 token = mono_get_field_token (field);
2603 encode_klass_ref (cfg, field->parent, p, &p);
2604 g_assert (mono_metadata_token_code (token) == MONO_TOKEN_FIELD_DEF);
2605 encode_value (token - MONO_TOKEN_FIELD_DEF, p, &p);
2610 encode_ginst (MonoAotCompile *acfg, MonoGenericInst *inst, guint8 *buf, guint8 **endbuf)
2615 encode_value (inst->type_argc, p, &p);
2616 for (i = 0; i < inst->type_argc; ++i)
2617 encode_klass_ref (acfg, mono_class_from_mono_type (inst->type_argv [i]), p, &p);
2622 encode_generic_context (MonoAotCompile *acfg, MonoGenericContext *context, guint8 *buf, guint8 **endbuf)
2625 MonoGenericInst *inst;
2627 inst = context->class_inst;
2629 g_assert (inst->type_argc);
2630 encode_ginst (acfg, inst, p, &p);
2632 encode_value (0, p, &p);
2634 inst = context->method_inst;
2636 g_assert (inst->type_argc);
2637 encode_ginst (acfg, inst, p, &p);
2639 encode_value (0, p, &p);
2645 encode_type (MonoAotCompile *acfg, MonoType *t, guint8 *buf, guint8 **endbuf)
2649 g_assert (t->num_mods == 0);
2650 /* t->attrs can be ignored */
2651 //g_assert (t->attrs == 0);
2654 *p = MONO_TYPE_PINNED;
2658 *p = MONO_TYPE_BYREF;
2666 case MONO_TYPE_VOID:
2667 case MONO_TYPE_BOOLEAN:
2668 case MONO_TYPE_CHAR:
2681 case MONO_TYPE_STRING:
2682 case MONO_TYPE_OBJECT:
2683 case MONO_TYPE_TYPEDBYREF:
2685 case MONO_TYPE_VALUETYPE:
2686 case MONO_TYPE_CLASS:
2687 encode_klass_ref (acfg, mono_class_from_mono_type (t), p, &p);
2689 case MONO_TYPE_SZARRAY:
2690 encode_klass_ref (acfg, t->data.klass, p, &p);
2693 encode_type (acfg, t->data.type, p, &p);
2695 case MONO_TYPE_GENERICINST: {
2696 MonoClass *gclass = t->data.generic_class->container_class;
2697 MonoGenericInst *inst = t->data.generic_class->context.class_inst;
2699 encode_klass_ref (acfg, gclass, p, &p);
2700 encode_ginst (acfg, inst, p, &p);
2703 case MONO_TYPE_ARRAY: {
2704 MonoArrayType *array = t->data.array;
2707 encode_klass_ref (acfg, array->eklass, p, &p);
2708 encode_value (array->rank, p, &p);
2709 encode_value (array->numsizes, p, &p);
2710 for (i = 0; i < array->numsizes; ++i)
2711 encode_value (array->sizes [i], p, &p);
2712 encode_value (array->numlobounds, p, &p);
2713 for (i = 0; i < array->numlobounds; ++i)
2714 encode_value (array->lobounds [i], p, &p);
2718 case MONO_TYPE_MVAR:
2719 encode_klass_ref (acfg, mono_class_from_mono_type (t), p, &p);
2722 g_assert_not_reached ();
2729 encode_signature (MonoAotCompile *acfg, MonoMethodSignature *sig, guint8 *buf, guint8 **endbuf)
2735 /* Similar to the metadata encoding */
2736 if (sig->generic_param_count)
2740 if (sig->explicit_this)
2742 flags |= (sig->call_convention & 0x0F);
2746 if (sig->generic_param_count)
2747 encode_value (sig->generic_param_count, p, &p);
2748 encode_value (sig->param_count, p, &p);
2750 encode_type (acfg, sig->ret, p, &p);
2751 for (i = 0; i < sig->param_count; ++i) {
2752 if (sig->sentinelpos == i) {
2753 *p = MONO_TYPE_SENTINEL;
2756 encode_type (acfg, sig->params [i], p, &p);
2762 #define MAX_IMAGE_INDEX 250
2765 encode_method_ref (MonoAotCompile *acfg, MonoMethod *method, guint8 *buf, guint8 **endbuf)
2767 guint32 image_index = get_image_index (acfg, method->klass->image);
2768 guint32 token = method->token;
2769 MonoJumpInfoToken *ji;
2773 * The encoding for most methods is as follows:
2774 * - image index encoded as a leb128
2775 * - token index encoded as a leb128
2776 * Values of image index >= MONO_AOT_METHODREF_MIN are used to mark additional
2777 * types of method encodings.
2780 /* Mark methods which can't use aot trampolines because they need the further
2781 * processing in mono_magic_trampoline () which requires a MonoMethod*.
2783 if ((method->is_generic && (method->flags & METHOD_ATTRIBUTE_VIRTUAL)) ||
2784 (method->iflags & METHOD_IMPL_ATTRIBUTE_SYNCHRONIZED))
2785 encode_value ((MONO_AOT_METHODREF_NO_AOT_TRAMPOLINE << 24), p, &p);
2787 if (method->wrapper_type) {
2788 WrapperInfo *info = mono_marshal_get_wrapper_info (method);
2790 encode_value ((MONO_AOT_METHODREF_WRAPPER << 24), p, &p);
2792 encode_value (method->wrapper_type, p, &p);
2794 switch (method->wrapper_type) {
2795 case MONO_WRAPPER_REMOTING_INVOKE:
2796 case MONO_WRAPPER_REMOTING_INVOKE_WITH_CHECK:
2797 case MONO_WRAPPER_XDOMAIN_INVOKE: {
2800 m = mono_marshal_method_from_wrapper (method);
2802 encode_method_ref (acfg, m, p, &p);
2805 case MONO_WRAPPER_PROXY_ISINST:
2806 case MONO_WRAPPER_LDFLD:
2807 case MONO_WRAPPER_LDFLDA:
2808 case MONO_WRAPPER_STFLD:
2809 case MONO_WRAPPER_ISINST: {
2811 encode_klass_ref (acfg, info->d.proxy.klass, p, &p);
2814 case MONO_WRAPPER_LDFLD_REMOTE:
2815 case MONO_WRAPPER_STFLD_REMOTE:
2817 case MONO_WRAPPER_ALLOC: {
2818 /* The GC name is saved once in MonoAotFileInfo */
2819 g_assert (info->d.alloc.alloc_type != -1);
2820 encode_value (info->d.alloc.alloc_type, p, &p);
2823 case MONO_WRAPPER_WRITE_BARRIER: {
2827 case MONO_WRAPPER_STELEMREF: {
2829 encode_value (info->subtype, p, &p);
2830 if (info->subtype == WRAPPER_SUBTYPE_VIRTUAL_STELEMREF)
2831 encode_value (info->d.virtual_stelemref.kind, p, &p);
2834 case MONO_WRAPPER_UNKNOWN: {
2836 encode_value (info->subtype, p, &p);
2837 if (info->subtype == WRAPPER_SUBTYPE_PTR_TO_STRUCTURE ||
2838 info->subtype == WRAPPER_SUBTYPE_STRUCTURE_TO_PTR)
2839 encode_klass_ref (acfg, method->klass, p, &p);
2840 else if (info->subtype == WRAPPER_SUBTYPE_SYNCHRONIZED_INNER)
2841 encode_method_ref (acfg, info->d.synchronized_inner.method, p, &p);
2842 else if (info->subtype == WRAPPER_SUBTYPE_ARRAY_ACCESSOR)
2843 encode_method_ref (acfg, info->d.array_accessor.method, p, &p);
2844 else if (info->subtype == WRAPPER_SUBTYPE_GSHAREDVT_IN_SIG)
2845 encode_signature (acfg, info->d.gsharedvt.sig, p, &p);
2846 else if (info->subtype == WRAPPER_SUBTYPE_GSHAREDVT_OUT_SIG)
2847 encode_signature (acfg, info->d.gsharedvt.sig, p, &p);
2850 case MONO_WRAPPER_MANAGED_TO_NATIVE: {
2852 encode_value (info->subtype, p, &p);
2853 if (info->subtype == WRAPPER_SUBTYPE_ICALL_WRAPPER) {
2854 strcpy ((char*)p, method->name);
2855 p += strlen (method->name) + 1;
2856 } else if (info->subtype == WRAPPER_SUBTYPE_NATIVE_FUNC_AOT) {
2857 encode_method_ref (acfg, info->d.managed_to_native.method, p, &p);
2859 g_assert (info->subtype == WRAPPER_SUBTYPE_NONE || info->subtype == WRAPPER_SUBTYPE_PINVOKE);
2860 encode_method_ref (acfg, info->d.managed_to_native.method, p, &p);
2864 case MONO_WRAPPER_SYNCHRONIZED: {
2867 m = mono_marshal_method_from_wrapper (method);
2869 g_assert (m != method);
2870 encode_method_ref (acfg, m, p, &p);
2873 case MONO_WRAPPER_MANAGED_TO_MANAGED: {
2875 encode_value (info->subtype, p, &p);
2877 if (info->subtype == WRAPPER_SUBTYPE_ELEMENT_ADDR) {
2878 encode_value (info->d.element_addr.rank, p, &p);
2879 encode_value (info->d.element_addr.elem_size, p, &p);
2880 } else if (info->subtype == WRAPPER_SUBTYPE_STRING_CTOR) {
2881 encode_method_ref (acfg, info->d.string_ctor.method, p, &p);
2883 g_assert_not_reached ();
2887 case MONO_WRAPPER_CASTCLASS: {
2889 encode_value (info->subtype, p, &p);
2892 case MONO_WRAPPER_RUNTIME_INVOKE: {
2894 encode_value (info->subtype, p, &p);
2895 encode_value (info->d.runtime_invoke.pass_rgctx, p, &p);
2896 if (info->subtype == WRAPPER_SUBTYPE_RUNTIME_INVOKE_DIRECT || info->subtype == WRAPPER_SUBTYPE_RUNTIME_INVOKE_VIRTUAL)
2897 encode_method_ref (acfg, info->d.runtime_invoke.method, p, &p);
2898 else if (info->subtype == WRAPPER_SUBTYPE_RUNTIME_INVOKE_NORMAL)
2899 encode_signature (acfg, info->d.runtime_invoke.sig, p, &p);
2902 case MONO_WRAPPER_DELEGATE_INVOKE:
2903 case MONO_WRAPPER_DELEGATE_BEGIN_INVOKE:
2904 case MONO_WRAPPER_DELEGATE_END_INVOKE: {
2905 if (method->is_inflated) {
2906 /* These wrappers are identified by their class */
2907 encode_value (1, p, &p);
2908 encode_klass_ref (acfg, method->klass, p, &p);
2910 MonoMethodSignature *sig = mono_method_signature (method);
2911 WrapperInfo *info = mono_marshal_get_wrapper_info (method);
2913 encode_value (0, p, &p);
2914 if (method->wrapper_type == MONO_WRAPPER_DELEGATE_INVOKE)
2915 encode_value (info ? info->subtype : 0, p, &p);
2916 encode_signature (acfg, sig, p, &p);
2920 case MONO_WRAPPER_NATIVE_TO_MANAGED: {
2922 encode_method_ref (acfg, info->d.native_to_managed.method, p, &p);
2923 encode_klass_ref (acfg, info->d.native_to_managed.klass, p, &p);
2927 g_assert_not_reached ();
2929 } else if (mono_method_signature (method)->is_inflated) {
2931 * This is a generic method, find the original token which referenced it and
2933 * Obtain the token from information recorded by the JIT.
2935 ji = (MonoJumpInfoToken *)g_hash_table_lookup (acfg->token_info_hash, method);
2937 image_index = get_image_index (acfg, ji->image);
2938 g_assert (image_index < MAX_IMAGE_INDEX);
2941 encode_value ((MONO_AOT_METHODREF_METHODSPEC << 24), p, &p);
2942 encode_value (image_index, p, &p);
2943 encode_value (token, p, &p);
2945 MonoMethod *declaring;
2946 MonoGenericContext *context = mono_method_get_context (method);
2948 g_assert (method->is_inflated);
2949 declaring = ((MonoMethodInflated*)method)->declaring;
2952 * This might be a non-generic method of a generic instance, which
2953 * doesn't have a token since the reference is generated by the JIT
2954 * like Nullable:Box/Unbox, or by generic sharing.
2956 encode_value ((MONO_AOT_METHODREF_GINST << 24), p, &p);
2957 /* Encode the klass */
2958 encode_klass_ref (acfg, method->klass, p, &p);
2959 /* Encode the method */
2960 image_index = get_image_index (acfg, method->klass->image);
2961 g_assert (image_index < MAX_IMAGE_INDEX);
2962 g_assert (declaring->token);
2963 token = declaring->token;
2964 g_assert (mono_metadata_token_table (token) == MONO_TABLE_METHOD);
2965 encode_value (image_index, p, &p);
2966 encode_value (token, p, &p);
2967 encode_generic_context (acfg, context, p, &p);
2969 } else if (token == 0) {
2970 /* This might be a method of a constructed type like int[,].Set */
2971 /* Obtain the token from information recorded by the JIT */
2972 ji = (MonoJumpInfoToken *)g_hash_table_lookup (acfg->token_info_hash, method);
2974 image_index = get_image_index (acfg, ji->image);
2975 g_assert (image_index < MAX_IMAGE_INDEX);
2978 encode_value ((MONO_AOT_METHODREF_METHODSPEC << 24), p, &p);
2979 encode_value (image_index, p, &p);
2980 encode_value (token, p, &p);
2983 g_assert (method->klass->rank);
2985 /* Encode directly */
2986 encode_value ((MONO_AOT_METHODREF_ARRAY << 24), p, &p);
2987 encode_klass_ref (acfg, method->klass, p, &p);
2988 if (!strcmp (method->name, ".ctor") && mono_method_signature (method)->param_count == method->klass->rank)
2989 encode_value (0, p, &p);
2990 else if (!strcmp (method->name, ".ctor") && mono_method_signature (method)->param_count == method->klass->rank * 2)
2991 encode_value (1, p, &p);
2992 else if (!strcmp (method->name, "Get"))
2993 encode_value (2, p, &p);
2994 else if (!strcmp (method->name, "Address"))
2995 encode_value (3, p, &p);
2996 else if (!strcmp (method->name, "Set"))
2997 encode_value (4, p, &p);
2999 g_assert_not_reached ();
3002 g_assert (mono_metadata_token_table (token) == MONO_TABLE_METHOD);
3004 if (image_index >= MONO_AOT_METHODREF_MIN) {
3005 encode_value ((MONO_AOT_METHODREF_LARGE_IMAGE_INDEX << 24), p, &p);
3006 encode_value (image_index, p, &p);
3007 encode_value (mono_metadata_token_index (token), p, &p);
3009 encode_value ((image_index << 24) | mono_metadata_token_index (token), p, &p);
3016 compare_patches (gconstpointer a, gconstpointer b)
3020 i = (*(MonoJumpInfo**)a)->ip.i;
3021 j = (*(MonoJumpInfo**)b)->ip.i;
3032 static G_GNUC_UNUSED char*
3033 patch_to_string (MonoJumpInfo *patch_info)
3037 str = g_string_new ("");
3039 g_string_append_printf (str, "%s(", get_patch_name (patch_info->type));
3041 switch (patch_info->type) {
3042 case MONO_PATCH_INFO_VTABLE:
3043 mono_type_get_desc (str, &patch_info->data.klass->byval_arg, TRUE);
3048 g_string_append_printf (str, ")");
3049 return g_string_free (str, FALSE);
3055 * Return whenever PATCH_INFO refers to a direct call, and thus requires a
3058 static inline gboolean
3059 is_plt_patch (MonoJumpInfo *patch_info)
3061 switch (patch_info->type) {
3062 case MONO_PATCH_INFO_METHOD:
3063 case MONO_PATCH_INFO_INTERNAL_METHOD:
3064 case MONO_PATCH_INFO_JIT_ICALL_ADDR:
3065 case MONO_PATCH_INFO_ICALL_ADDR:
3066 case MONO_PATCH_INFO_RGCTX_FETCH:
3076 * Return the symbol identifying the plt entry PLT_OFFSET.
3079 get_plt_symbol (MonoAotCompile *acfg, int plt_offset, MonoJumpInfo *patch_info)
3083 * The Apple linker reorganizes object files, so it doesn't like branches to local
3084 * labels, since those have no relocations.
3086 return g_strdup_printf ("%sp_%d", acfg->llvm_label_prefix, plt_offset);
3088 return g_strdup_printf ("%sp_%d", acfg->temp_prefix, plt_offset);
3095 * Return a PLT entry which belongs to the method identified by PATCH_INFO.
3097 static MonoPltEntry*
3098 get_plt_entry (MonoAotCompile *acfg, MonoJumpInfo *patch_info)
3101 gboolean synchronized = FALSE;
3102 static int synchronized_symbol_idx;
3104 if (!is_plt_patch (patch_info))
3107 if (!acfg->patch_to_plt_entry [patch_info->type])
3108 acfg->patch_to_plt_entry [patch_info->type] = g_hash_table_new (mono_patch_info_hash, mono_patch_info_equal);
3109 res = (MonoPltEntry *)g_hash_table_lookup (acfg->patch_to_plt_entry [patch_info->type], patch_info);
3111 if (!acfg->llvm && patch_info->type == MONO_PATCH_INFO_METHOD && (patch_info->data.method->iflags & METHOD_IMPL_ATTRIBUTE_SYNCHRONIZED)) {
3113 * Allocate a separate PLT slot for each such patch, since some plt
3114 * entries will refer to the method itself, and some will refer to the
3118 synchronized = TRUE;
3122 MonoJumpInfo *new_ji;
3124 new_ji = mono_patch_info_dup_mp (acfg->mempool, patch_info);
3126 res = (MonoPltEntry *)mono_mempool_alloc0 (acfg->mempool, sizeof (MonoPltEntry));
3127 res->plt_offset = acfg->plt_offset;
3129 res->symbol = get_plt_symbol (acfg, res->plt_offset, patch_info);
3130 if (acfg->aot_opts.write_symbols)
3131 res->debug_sym = get_plt_entry_debug_sym (acfg, res->ji, acfg->plt_entry_debug_sym_cache);
3133 /* Avoid duplicate symbols because we don't cache */
3134 res->symbol = g_strdup_printf ("%s_%d", res->symbol, synchronized_symbol_idx);
3136 res->debug_sym = g_strdup_printf ("%s_%d", res->debug_sym, synchronized_symbol_idx);
3137 synchronized_symbol_idx ++;
3140 res->llvm_symbol = g_strdup_printf ("%s_%s_llvm", res->symbol, res->debug_sym);
3142 res->llvm_symbol = g_strdup_printf ("%s_llvm", res->symbol);
3144 g_hash_table_insert (acfg->patch_to_plt_entry [new_ji->type], new_ji, res);
3146 g_hash_table_insert (acfg->plt_offset_to_entry, GUINT_TO_POINTER (res->plt_offset), res);
3148 //g_assert (mono_patch_info_equal (patch_info, new_ji));
3149 //mono_print_ji (patch_info); printf ("\n");
3150 //g_hash_table_print_stats (acfg->patch_to_plt_entry);
3152 acfg->plt_offset ++;
3161 * Returns the offset of the GOT slot where the runtime object resulting from resolving
3162 * JI could be found if it exists, otherwise allocates a new one.
3165 get_got_offset (MonoAotCompile *acfg, gboolean llvm, MonoJumpInfo *ji)
3168 GotInfo *info = llvm ? &acfg->llvm_got_info : &acfg->got_info;
3170 got_offset = GPOINTER_TO_UINT (g_hash_table_lookup (info->patch_to_got_offset_by_type [ji->type], ji));
3172 return got_offset - 1;
3175 got_offset = acfg->llvm_got_offset;
3176 acfg->llvm_got_offset ++;
3178 got_offset = acfg->got_offset;
3179 acfg->got_offset ++;
3182 acfg->stats.got_slots ++;
3183 acfg->stats.got_slot_types [ji->type] ++;
3185 g_hash_table_insert (info->patch_to_got_offset, ji, GUINT_TO_POINTER (got_offset + 1));
3186 g_hash_table_insert (info->patch_to_got_offset_by_type [ji->type], ji, GUINT_TO_POINTER (got_offset + 1));
3187 g_ptr_array_add (info->got_patches, ji);
3192 /* Add a method to the list of methods which need to be emitted */
3194 add_method_with_index (MonoAotCompile *acfg, MonoMethod *method, int index, gboolean extra)
3197 if (!g_hash_table_lookup (acfg->method_indexes, method)) {
3198 g_ptr_array_add (acfg->methods, method);
3199 g_hash_table_insert (acfg->method_indexes, method, GUINT_TO_POINTER (index + 1));
3200 acfg->nmethods = acfg->methods->len + 1;
3203 if (method->wrapper_type || extra)
3204 g_ptr_array_add (acfg->extra_methods, method);
3208 prefer_gsharedvt_method (MonoAotCompile *acfg, MonoMethod *method)
3210 /* One instantiation with valuetypes is generated for each async method */
3211 if (method->klass->image == mono_defaults.corlib && (!strcmp (method->klass->name, "AsyncMethodBuilderCore") || !strcmp (method->klass->name, "AsyncVoidMethodBuilder")))
3218 get_method_index (MonoAotCompile *acfg, MonoMethod *method)
3220 int index = GPOINTER_TO_UINT (g_hash_table_lookup (acfg->method_indexes, method));
3228 add_method_full (MonoAotCompile *acfg, MonoMethod *method, gboolean extra, int depth)
3232 index = GPOINTER_TO_UINT (g_hash_table_lookup (acfg->method_indexes, method));
3236 index = acfg->method_index;
3237 add_method_with_index (acfg, method, index, extra);
3239 g_ptr_array_add (acfg->method_order, GUINT_TO_POINTER (index));
3241 g_hash_table_insert (acfg->method_depth, method, GUINT_TO_POINTER (depth));
3243 acfg->method_index ++;
3249 add_method (MonoAotCompile *acfg, MonoMethod *method)
3251 return add_method_full (acfg, method, FALSE, 0);
3255 add_extra_method_with_depth (MonoAotCompile *acfg, MonoMethod *method, int depth)
3257 if (mono_method_is_generic_sharable_full (method, TRUE, TRUE, FALSE))
3258 method = mini_get_shared_method (method);
3259 else if ((acfg->opts & MONO_OPT_GSHAREDVT) && prefer_gsharedvt_method (acfg, method) && mono_method_is_generic_sharable_full (method, FALSE, FALSE, TRUE))
3260 /* Use the gsharedvt version */
3261 method = mini_get_shared_method_full (method, TRUE, TRUE);
3263 if (acfg->aot_opts.log_generics)
3264 aot_printf (acfg, "%*sAdding method %s.\n", depth, "", mono_method_full_name (method, TRUE));
3266 add_method_full (acfg, method, TRUE, depth);
3270 add_extra_method (MonoAotCompile *acfg, MonoMethod *method)
3272 add_extra_method_with_depth (acfg, method, 0);
3276 add_jit_icall_wrapper (gpointer key, gpointer value, gpointer user_data)
3278 MonoAotCompile *acfg = (MonoAotCompile *)user_data;
3279 MonoJitICallInfo *callinfo = (MonoJitICallInfo *)value;
3280 MonoMethod *wrapper;
3286 name = g_strdup_printf ("__icall_wrapper_%s", callinfo->name);
3287 wrapper = mono_marshal_get_icall_wrapper (callinfo->sig, name, callinfo->func, TRUE);
3290 add_method (acfg, wrapper);
3294 get_runtime_invoke_sig (MonoMethodSignature *sig)
3296 MonoMethodBuilder *mb;
3299 mb = mono_mb_new (mono_defaults.object_class, "FOO", MONO_WRAPPER_NONE);
3300 m = mono_mb_create_method (mb, sig, 16);
3301 return mono_marshal_get_runtime_invoke (m, FALSE, FALSE);
3305 get_runtime_invoke (MonoAotCompile *acfg, MonoMethod *method, gboolean virtual_)
3307 return mono_marshal_get_runtime_invoke (method, virtual_, acfg->aot_opts.llvm_only && mono_method_needs_static_rgctx_invoke (method, TRUE));
3311 can_marshal_struct (MonoClass *klass)
3313 MonoClassField *field;
3314 gboolean can_marshal = TRUE;
3315 gpointer iter = NULL;
3316 MonoMarshalType *info;
3319 if ((klass->flags & TYPE_ATTRIBUTE_LAYOUT_MASK) == TYPE_ATTRIBUTE_AUTO_LAYOUT)
3322 info = mono_marshal_load_type_info (klass);
3324 /* Only allow a few field types to avoid asserts in the marshalling code */
3325 while ((field = mono_class_get_fields (klass, &iter))) {
3326 if ((field->type->attrs & FIELD_ATTRIBUTE_STATIC))
3329 switch (field->type->type) {
3334 case MONO_TYPE_BOOLEAN:
3337 case MONO_TYPE_CHAR:
3345 case MONO_TYPE_STRING:
3347 case MONO_TYPE_VALUETYPE:
3348 if (!mono_class_from_mono_type (field->type)->enumtype && !can_marshal_struct (mono_class_from_mono_type (field->type)))
3349 can_marshal = FALSE;
3351 case MONO_TYPE_SZARRAY: {
3352 gboolean has_mspec = FALSE;
3355 for (i = 0; i < info->num_fields; ++i) {
3356 if (info->fields [i].field == field && info->fields [i].mspec)
3361 can_marshal = FALSE;
3365 can_marshal = FALSE;
3371 /* Its hard to compute whenever these can be marshalled or not */
3372 if (!strcmp (klass->name_space, "System.Net.NetworkInformation.MacOsStructs") && strcmp (klass->name, "sockaddr_dl"))
3379 create_gsharedvt_inst (MonoAotCompile *acfg, MonoMethod *method, MonoGenericContext *ctx)
3381 /* Create a vtype instantiation */
3382 MonoGenericContext shared_context;
3384 MonoGenericInst *inst;
3385 MonoGenericContainer *container;
3386 MonoClass **constraints;
3389 memset (ctx, 0, sizeof (MonoGenericContext));
3391 if (method->klass->generic_container) {
3392 shared_context = method->klass->generic_container->context;
3393 inst = shared_context.class_inst;
3395 args = g_new0 (MonoType*, inst->type_argc);
3396 for (i = 0; i < inst->type_argc; ++i) {
3397 args [i] = &mono_defaults.int_class->byval_arg;
3399 ctx->class_inst = mono_metadata_get_generic_inst (inst->type_argc, args);
3401 if (method->is_generic) {
3402 container = mono_method_get_generic_container (method);
3403 shared_context = container->context;
3404 inst = shared_context.method_inst;
3406 args = g_new0 (MonoType*, inst->type_argc);
3407 for (i = 0; i < container->type_argc; ++i) {
3408 MonoGenericParamInfo *info = &container->type_params [i].info;
3409 gboolean ref_only = FALSE;
3411 if (info && info->constraints) {
3412 constraints = info->constraints;
3414 while (*constraints) {
3415 MonoClass *cklass = *constraints;
3416 if (!(cklass == mono_defaults.object_class || (cklass->image == mono_defaults.corlib && !strcmp (cklass->name, "ValueType"))))
3417 /* Inflaring the method with our vtype would not be valid */
3424 args [i] = &mono_defaults.object_class->byval_arg;
3426 args [i] = &mono_defaults.int_class->byval_arg;
3428 ctx->method_inst = mono_metadata_get_generic_inst (inst->type_argc, args);
3433 add_wrappers (MonoAotCompile *acfg)
3435 MonoMethod *method, *m;
3437 MonoMethodSignature *sig, *csig;
3441 * FIXME: Instead of AOTing all the wrappers, it might be better to redesign them
3442 * so there is only one wrapper of a given type, or inlining their contents into their
3445 for (i = 0; i < acfg->image->tables [MONO_TABLE_METHOD].rows; ++i) {
3448 guint32 token = MONO_TOKEN_METHOD_DEF | (i + 1);
3449 gboolean skip = FALSE;
3451 method = mono_get_method_checked (acfg->image, token, NULL, NULL, &error);
3452 report_loader_error (acfg, &error, "Failed to load method token 0x%x due to %s\n", i, mono_error_get_message (&error));
3454 if ((method->flags & METHOD_ATTRIBUTE_PINVOKE_IMPL) ||
3455 (method->iflags & METHOD_IMPL_ATTRIBUTE_RUNTIME) ||
3456 (method->flags & METHOD_ATTRIBUTE_ABSTRACT))
3459 /* Skip methods which can not be handled by get_runtime_invoke () */
3460 sig = mono_method_signature (method);
3463 if ((sig->ret->type == MONO_TYPE_PTR) ||
3464 (sig->ret->type == MONO_TYPE_TYPEDBYREF))
3466 if (mono_class_is_open_constructed_type (sig->ret))
3469 for (j = 0; j < sig->param_count; j++) {
3470 if (sig->params [j]->type == MONO_TYPE_TYPEDBYREF)
3472 if (mono_class_is_open_constructed_type (sig->params [j]))
3476 #ifdef MONO_ARCH_DYN_CALL_SUPPORTED
3477 if (!mono_class_is_contextbound (method->klass)) {
3478 MonoDynCallInfo *info = mono_arch_dyn_call_prepare (sig);
3479 gboolean has_nullable = FALSE;
3481 for (j = 0; j < sig->param_count; j++) {
3482 if (sig->params [j]->type == MONO_TYPE_GENERICINST && mono_class_is_nullable (mono_class_from_mono_type (sig->params [j])))
3483 has_nullable = TRUE;
3486 if (info && !has_nullable && !acfg->aot_opts.llvm_only) {
3487 /* Supported by the dynamic runtime-invoke wrapper */
3491 mono_arch_dyn_call_free (info);
3496 //printf ("%s\n", mono_method_full_name (method, TRUE));
3497 add_method (acfg, get_runtime_invoke (acfg, method, FALSE));
3501 if (strcmp (acfg->image->assembly->aname.name, "mscorlib") == 0) {
3504 /* Runtime invoke wrappers */
3506 /* void runtime-invoke () [.cctor] */
3507 csig = mono_metadata_signature_alloc (mono_defaults.corlib, 0);
3508 csig->ret = &mono_defaults.void_class->byval_arg;
3509 add_method (acfg, get_runtime_invoke_sig (csig));
3511 /* void runtime-invoke () [Finalize] */
3512 csig = mono_metadata_signature_alloc (mono_defaults.corlib, 0);
3514 csig->ret = &mono_defaults.void_class->byval_arg;
3515 add_method (acfg, get_runtime_invoke_sig (csig));
3517 /* void runtime-invoke (string) [exception ctor] */
3518 csig = mono_metadata_signature_alloc (mono_defaults.corlib, 1);
3520 csig->ret = &mono_defaults.void_class->byval_arg;
3521 csig->params [0] = &mono_defaults.string_class->byval_arg;
3522 add_method (acfg, get_runtime_invoke_sig (csig));
3524 /* void runtime-invoke (string, string) [exception ctor] */
3525 csig = mono_metadata_signature_alloc (mono_defaults.corlib, 2);
3527 csig->ret = &mono_defaults.void_class->byval_arg;
3528 csig->params [0] = &mono_defaults.string_class->byval_arg;
3529 csig->params [1] = &mono_defaults.string_class->byval_arg;
3530 add_method (acfg, get_runtime_invoke_sig (csig));
3532 /* string runtime-invoke () [Exception.ToString ()] */
3533 csig = mono_metadata_signature_alloc (mono_defaults.corlib, 0);
3535 csig->ret = &mono_defaults.string_class->byval_arg;
3536 add_method (acfg, get_runtime_invoke_sig (csig));
3538 /* void runtime-invoke (string, Exception) [exception ctor] */
3539 csig = mono_metadata_signature_alloc (mono_defaults.corlib, 2);
3541 csig->ret = &mono_defaults.void_class->byval_arg;
3542 csig->params [0] = &mono_defaults.string_class->byval_arg;
3543 csig->params [1] = &mono_defaults.exception_class->byval_arg;
3544 add_method (acfg, get_runtime_invoke_sig (csig));
3546 /* Assembly runtime-invoke (string, bool) [DoAssemblyResolve] */
3547 csig = mono_metadata_signature_alloc (mono_defaults.corlib, 2);
3549 csig->ret = &(mono_class_from_name (
3550 mono_defaults.corlib, "System.Reflection", "Assembly"))->byval_arg;
3551 csig->params [0] = &mono_defaults.string_class->byval_arg;
3552 csig->params [1] = &mono_defaults.boolean_class->byval_arg;
3553 add_method (acfg, get_runtime_invoke_sig (csig));
3555 /* runtime-invoke used by finalizers */
3556 add_method (acfg, get_runtime_invoke (acfg, mono_class_get_method_from_name_flags (mono_defaults.object_class, "Finalize", 0, 0), TRUE));
3558 /* This is used by mono_runtime_capture_context () */
3559 method = mono_get_context_capture_method ();
3561 add_method (acfg, get_runtime_invoke (acfg, method, FALSE));
3563 #ifdef MONO_ARCH_DYN_CALL_SUPPORTED
3564 if (!acfg->aot_opts.llvm_only)
3565 add_method (acfg, mono_marshal_get_runtime_invoke_dynamic ());
3568 /* These are used by mono_jit_runtime_invoke () to calls gsharedvt out wrappers */
3569 if (acfg->aot_opts.llvm_only) {
3572 /* Create simplified signatures which match the signature used by the gsharedvt out wrappers */
3573 for (variants = 0; variants < 4; ++variants) {
3574 for (i = 0; i < 16; ++i) {
3575 sig = mini_get_gsharedvt_out_sig_wrapper_signature ((variants & 1) > 0, (variants & 2) > 0, i);
3576 add_extra_method (acfg, mono_marshal_get_runtime_invoke_for_sig (sig));
3584 add_method (acfg, mono_marshal_get_stelemref ());
3586 if (MONO_ARCH_HAVE_TLS_GET) {
3587 /* Managed Allocators */
3588 nallocators = mono_gc_get_managed_allocator_types ();
3589 for (i = 0; i < nallocators; ++i) {
3590 m = mono_gc_get_managed_allocator_by_type (i, TRUE);
3592 add_method (acfg, m);
3594 for (i = 0; i < nallocators; ++i) {
3595 m = mono_gc_get_managed_allocator_by_type (i, FALSE);
3597 add_method (acfg, m);
3601 /* write barriers */
3602 if (mono_gc_is_moving ()) {
3603 add_method (acfg, mono_gc_get_specific_write_barrier (FALSE));
3604 add_method (acfg, mono_gc_get_specific_write_barrier (TRUE));
3607 /* Stelemref wrappers */
3609 MonoMethod **wrappers;
3612 wrappers = mono_marshal_get_virtual_stelemref_wrappers (&nwrappers);
3613 for (i = 0; i < nwrappers; ++i)
3614 add_method (acfg, wrappers [i]);
3618 /* castclass_with_check wrapper */
3619 add_method (acfg, mono_marshal_get_castclass_with_cache ());
3620 /* isinst_with_check wrapper */
3621 add_method (acfg, mono_marshal_get_isinst_with_cache ());
3623 /* JIT icall wrappers */
3624 /* FIXME: locking - this is "safe" as full-AOT threads don't mutate the icall hash*/
3625 g_hash_table_foreach (mono_get_jit_icall_info (), add_jit_icall_wrapper, acfg);
3629 * remoting-invoke-with-check wrappers are very frequent, so avoid emitting them,
3630 * we use the original method instead at runtime.
3631 * Since full-aot doesn't support remoting, this is not a problem.
3634 /* remoting-invoke wrappers */
3635 for (i = 0; i < acfg->image->tables [MONO_TABLE_METHOD].rows; ++i) {
3636 MonoMethodSignature *sig;
3638 token = MONO_TOKEN_METHOD_DEF | (i + 1);
3639 method = mono_get_method (acfg->image, token, NULL);
3641 sig = mono_method_signature (method);
3643 if (sig->hasthis && (method->klass->marshalbyref || method->klass == mono_defaults.object_class)) {
3644 m = mono_marshal_get_remoting_invoke_with_check (method);
3646 add_method (acfg, m);
3651 /* delegate-invoke wrappers */
3652 for (i = 0; i < acfg->image->tables [MONO_TABLE_TYPEDEF].rows; ++i) {
3655 MonoCustomAttrInfo *cattr;
3657 token = MONO_TOKEN_TYPE_DEF | (i + 1);
3658 klass = mono_class_get_checked (acfg->image, token, &error);
3661 mono_error_cleanup (&error);
3665 if (!klass->delegate || klass == mono_defaults.delegate_class || klass == mono_defaults.multicastdelegate_class)
3668 if (!klass->generic_container) {
3669 method = mono_get_delegate_invoke (klass);
3671 m = mono_marshal_get_delegate_invoke (method, NULL);
3673 add_method (acfg, m);
3675 method = mono_class_get_method_from_name_flags (klass, "BeginInvoke", -1, 0);
3677 add_method (acfg, mono_marshal_get_delegate_begin_invoke (method));
3679 method = mono_class_get_method_from_name_flags (klass, "EndInvoke", -1, 0);
3681 add_method (acfg, mono_marshal_get_delegate_end_invoke (method));
3683 cattr = mono_custom_attrs_from_class (klass);
3688 for (j = 0; j < cattr->num_attrs; ++j)
3689 if (cattr->attrs [j].ctor && (!strcmp (cattr->attrs [j].ctor->klass->name, "MonoNativeFunctionWrapperAttribute") || !strcmp (cattr->attrs [j].ctor->klass->name, "UnmanagedFunctionPointerAttribute")))
3691 if (j < cattr->num_attrs) {
3693 MonoMethod *wrapper;
3694 MonoMethod *del_invoke;
3696 /* Add wrappers needed by mono_ftnptr_to_delegate () */
3697 invoke = mono_get_delegate_invoke (klass);
3698 wrapper = mono_marshal_get_native_func_wrapper_aot (klass);
3699 del_invoke = mono_marshal_get_delegate_invoke_internal (invoke, FALSE, TRUE, wrapper);
3700 add_method (acfg, wrapper);
3701 add_method (acfg, del_invoke);
3704 } else if ((acfg->opts & MONO_OPT_GSHAREDVT) && klass->generic_container) {
3706 MonoGenericContext ctx;
3707 MonoMethod *inst, *gshared;
3710 * Emit gsharedvt versions of the generic delegate-invoke wrappers
3713 method = mono_get_delegate_invoke (klass);
3714 create_gsharedvt_inst (acfg, method, &ctx);
3716 inst = mono_class_inflate_generic_method_checked (method, &ctx, &error);
3717 g_assert (mono_error_ok (&error)); /* FIXME don't swallow the error */
3719 m = mono_marshal_get_delegate_invoke (inst, NULL);
3720 g_assert (m->is_inflated);
3722 gshared = mini_get_shared_method_full (m, FALSE, TRUE);
3723 add_extra_method (acfg, gshared);
3726 method = mono_get_delegate_begin_invoke (klass);
3727 create_gsharedvt_inst (acfg, method, &ctx);
3729 inst = mono_class_inflate_generic_method_checked (method, &ctx, &error);
3730 g_assert (mono_error_ok (&error)); /* FIXME don't swallow the error */
3732 m = mono_marshal_get_delegate_begin_invoke (inst);
3733 g_assert (m->is_inflated);
3735 gshared = mini_get_shared_method_full (m, FALSE, TRUE);
3736 add_extra_method (acfg, gshared);
3739 method = mono_get_delegate_end_invoke (klass);
3740 create_gsharedvt_inst (acfg, method, &ctx);
3742 inst = mono_class_inflate_generic_method_checked (method, &ctx, &error);
3743 g_assert (mono_error_ok (&error)); /* FIXME don't swallow the error */
3745 m = mono_marshal_get_delegate_end_invoke (inst);
3746 g_assert (m->is_inflated);
3748 gshared = mini_get_shared_method_full (m, FALSE, TRUE);
3749 add_extra_method (acfg, gshared);
3754 /* array access wrappers */
3755 for (i = 0; i < acfg->image->tables [MONO_TABLE_TYPESPEC].rows; ++i) {
3759 token = MONO_TOKEN_TYPE_SPEC | (i + 1);
3760 klass = mono_class_get_checked (acfg->image, token, &error);
3763 mono_error_cleanup (&error);
3767 if (klass->rank && MONO_TYPE_IS_PRIMITIVE (&klass->element_class->byval_arg)) {
3768 MonoMethod *m, *wrapper;
3770 /* Add runtime-invoke wrappers too */
3772 m = mono_class_get_method_from_name (klass, "Get", -1);
3774 wrapper = mono_marshal_get_array_accessor_wrapper (m);
3775 add_extra_method (acfg, wrapper);
3776 add_extra_method (acfg, get_runtime_invoke (acfg, wrapper, FALSE));
3778 m = mono_class_get_method_from_name (klass, "Set", -1);
3780 wrapper = mono_marshal_get_array_accessor_wrapper (m);
3781 add_extra_method (acfg, wrapper);
3782 add_extra_method (acfg, get_runtime_invoke (acfg, wrapper, FALSE));
3786 /* Synchronized wrappers */
3787 for (i = 0; i < acfg->image->tables [MONO_TABLE_METHOD].rows; ++i) {
3789 token = MONO_TOKEN_METHOD_DEF | (i + 1);
3790 method = mono_get_method_checked (acfg->image, token, NULL, NULL, &error);
3791 report_loader_error (acfg, &error, "Failed to load method token 0x%x due to %s\n", i, mono_error_get_message (&error));
3793 if (method->iflags & METHOD_IMPL_ATTRIBUTE_SYNCHRONIZED) {
3794 if (method->is_generic) {
3796 } else if ((acfg->opts & MONO_OPT_GSHAREDVT) && method->klass->generic_container) {
3798 MonoGenericContext ctx;
3799 MonoMethod *inst, *gshared, *m;
3802 * Create a generic wrapper for a generic instance, and AOT that.
3804 create_gsharedvt_inst (acfg, method, &ctx);
3805 inst = mono_class_inflate_generic_method_checked (method, &ctx, &error);
3806 g_assert (mono_error_ok (&error)); /* FIXME don't swallow the error */
3807 m = mono_marshal_get_synchronized_wrapper (inst);
3808 g_assert (m->is_inflated);
3809 gshared = mini_get_shared_method_full (m, FALSE, TRUE);
3810 add_method (acfg, gshared);
3812 add_method (acfg, mono_marshal_get_synchronized_wrapper (method));
3817 /* pinvoke wrappers */
3818 for (i = 0; i < acfg->image->tables [MONO_TABLE_METHOD].rows; ++i) {
3821 guint32 token = MONO_TOKEN_METHOD_DEF | (i + 1);
3823 method = mono_get_method_checked (acfg->image, token, NULL, NULL, &error);
3824 report_loader_error (acfg, &error, "Failed to load method token 0x%x due to %s\n", i, mono_error_get_message (&error));
3826 if ((method->flags & METHOD_ATTRIBUTE_PINVOKE_IMPL) ||
3827 (method->iflags & METHOD_IMPL_ATTRIBUTE_INTERNAL_CALL)) {
3828 add_method (acfg, mono_marshal_get_native_wrapper (method, TRUE, TRUE));
3832 /* native-to-managed wrappers */
3833 for (i = 0; i < acfg->image->tables [MONO_TABLE_METHOD].rows; ++i) {
3836 guint32 token = MONO_TOKEN_METHOD_DEF | (i + 1);
3837 MonoCustomAttrInfo *cattr;
3840 method = mono_get_method_checked (acfg->image, token, NULL, NULL, &error);
3841 report_loader_error (acfg, &error, "Failed to load method token 0x%x due to %s\n", i, mono_error_get_message (&error));
3844 * Only generate native-to-managed wrappers for methods which have an
3845 * attribute named MonoPInvokeCallbackAttribute. We search for the attribute by
3846 * name to avoid defining a new assembly to contain it.
3848 cattr = mono_custom_attrs_from_method (method);
3851 for (j = 0; j < cattr->num_attrs; ++j)
3852 if (cattr->attrs [j].ctor && !strcmp (cattr->attrs [j].ctor->klass->name, "MonoPInvokeCallbackAttribute"))
3854 if (j < cattr->num_attrs) {
3855 MonoCustomAttrEntry *e = &cattr->attrs [j];
3856 MonoMethodSignature *sig = mono_method_signature (e->ctor);
3857 const char *p = (const char*)e->data;
3859 int slen, num_named, named_type;
3863 char *export_name = NULL;
3864 MonoMethod *wrapper;
3866 /* this cannot be enforced by the C# compiler so we must give the user some warning before aborting */
3867 if (!(method->flags & METHOD_ATTRIBUTE_STATIC)) {
3868 g_warning ("AOT restriction: Method '%s' must be static since it is decorated with [MonoPInvokeCallback]. See http://ios.xamarin.com/Documentation/Limitations#Reverse_Callbacks",
3869 mono_method_full_name (method, TRUE));
3873 g_assert (sig->param_count == 1);
3874 g_assert (sig->params [0]->type == MONO_TYPE_CLASS && !strcmp (mono_class_from_mono_type (sig->params [0])->name, "Type"));
3877 * Decode the cattr manually since we can't create objects
3878 * during aot compilation.
3884 /* From load_cattr_value () in reflection.c */
3885 slen = mono_metadata_decode_value (p, &p);
3886 n = (char *)g_memdup (p, slen + 1);
3888 t = mono_reflection_type_from_name (n, acfg->image);
3892 klass = mono_class_from_mono_type (t);
3893 g_assert (klass->parent == mono_defaults.multicastdelegate_class);
3897 num_named = read16 (p);
3900 g_assert (num_named < 2);
3901 if (num_named == 1) {
3905 /* parse ExportSymbol attribute */
3907 named_type = *named;
3909 /* data_type = *named; */
3912 name_len = mono_metadata_decode_blob_size (named, &named);
3913 name = (char *)g_malloc (name_len + 1);
3914 memcpy (name, named, name_len);
3915 name [name_len] = 0;
3918 g_assert (named_type == 0x54);
3919 g_assert (!strcmp (name, "ExportSymbol"));
3921 /* load_cattr_value (), string case */
3922 g_assert (*named != (char)0xff);
3923 slen = mono_metadata_decode_value (named, &named);
3924 export_name = (char *)g_malloc (slen + 1);
3925 memcpy (export_name, named, slen);
3926 export_name [slen] = 0;
3930 wrapper = mono_marshal_get_managed_wrapper (method, klass, 0);
3931 add_method (acfg, wrapper);
3933 g_hash_table_insert (acfg->export_names, wrapper, export_name);
3937 if ((method->flags & METHOD_ATTRIBUTE_PINVOKE_IMPL) ||
3938 (method->iflags & METHOD_IMPL_ATTRIBUTE_INTERNAL_CALL)) {
3939 add_method (acfg, mono_marshal_get_native_wrapper (method, TRUE, TRUE));
3943 /* StructureToPtr/PtrToStructure wrappers */
3944 for (i = 0; i < acfg->image->tables [MONO_TABLE_TYPEDEF].rows; ++i) {
3948 token = MONO_TOKEN_TYPE_DEF | (i + 1);
3949 klass = mono_class_get_checked (acfg->image, token, &error);
3952 mono_error_cleanup (&error);
3956 if (klass->valuetype && !klass->generic_container && can_marshal_struct (klass) &&
3957 !(klass->nested_in && strstr (klass->nested_in->name, "<PrivateImplementationDetails>") == klass->nested_in->name)) {
3958 add_method (acfg, mono_marshal_get_struct_to_ptr (klass));
3959 add_method (acfg, mono_marshal_get_ptr_to_struct (klass));
3965 has_type_vars (MonoClass *klass)
3967 if ((klass->byval_arg.type == MONO_TYPE_VAR) || (klass->byval_arg.type == MONO_TYPE_MVAR))
3970 return has_type_vars (klass->element_class);
3971 if (klass->generic_class) {
3972 MonoGenericContext *context = &klass->generic_class->context;
3973 if (context->class_inst) {
3976 for (i = 0; i < context->class_inst->type_argc; ++i)
3977 if (has_type_vars (mono_class_from_mono_type (context->class_inst->type_argv [i])))
3981 if (klass->generic_container)
3987 is_vt_inst (MonoGenericInst *inst)
3991 for (i = 0; i < inst->type_argc; ++i) {
3992 MonoType *t = inst->type_argv [i];
3993 if (MONO_TYPE_ISSTRUCT (t) || t->type == MONO_TYPE_VALUETYPE)
4000 method_has_type_vars (MonoMethod *method)
4002 if (has_type_vars (method->klass))
4005 if (method->is_inflated) {
4006 MonoGenericContext *context = mono_method_get_context (method);
4007 if (context->method_inst) {
4010 for (i = 0; i < context->method_inst->type_argc; ++i)
4011 if (has_type_vars (mono_class_from_mono_type (context->method_inst->type_argv [i])))
4019 gboolean mono_aot_mode_is_full (MonoAotOptions *opts)
4021 return opts->mode == MONO_AOT_MODE_FULL;
4024 static void add_generic_class_with_depth (MonoAotCompile *acfg, MonoClass *klass, int depth, const char *ref);
4027 add_generic_class (MonoAotCompile *acfg, MonoClass *klass, gboolean force, const char *ref)
4029 /* This might lead to a huge code blowup so only do it if neccesary */
4030 if (!mono_aot_mode_is_full (&acfg->aot_opts) && !force)
4033 add_generic_class_with_depth (acfg, klass, 0, ref);
4037 check_type_depth (MonoType *t, int depth)
4045 case MONO_TYPE_GENERICINST: {
4046 MonoGenericClass *gklass = t->data.generic_class;
4047 MonoGenericInst *ginst = gklass->context.class_inst;
4050 for (i = 0; i < ginst->type_argc; ++i) {
4051 if (check_type_depth (ginst->type_argv [i], depth + 1))
4065 add_types_from_method_header (MonoAotCompile *acfg, MonoMethod *method);
4068 * add_generic_class:
4070 * Add all methods of a generic class.
4073 add_generic_class_with_depth (MonoAotCompile *acfg, MonoClass *klass, int depth, const char *ref)
4076 MonoClassField *field;
4078 gboolean use_gsharedvt = FALSE;
4080 if (!acfg->ginst_hash)
4081 acfg->ginst_hash = g_hash_table_new (NULL, NULL);
4083 mono_class_init (klass);
4085 if (klass->generic_class && klass->generic_class->context.class_inst->is_open)
4088 if (has_type_vars (klass))
4091 if (!klass->generic_class && !klass->rank)
4094 if (klass->exception_type)
4097 if (!acfg->ginst_hash)
4098 acfg->ginst_hash = g_hash_table_new (NULL, NULL);
4100 if (g_hash_table_lookup (acfg->ginst_hash, klass))
4103 if (check_type_depth (&klass->byval_arg, 0))
4106 if (acfg->aot_opts.log_generics)
4107 aot_printf (acfg, "%*sAdding generic instance %s [%s].\n", depth, "", mono_type_full_name (&klass->byval_arg), ref);
4109 g_hash_table_insert (acfg->ginst_hash, klass, klass);
4112 * Use gsharedvt for generic collections with vtype arguments to avoid code blowup.
4113 * Enable this only for some classes since gsharedvt might not support all methods.
4115 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) &&
4116 (!strcmp (klass->name, "Dictionary`2") || !strcmp (klass->name, "List`1") || !strcmp (klass->name, "ReadOnlyCollection`1")))
4117 use_gsharedvt = TRUE;
4120 while ((method = mono_class_get_methods (klass, &iter))) {
4121 if ((acfg->opts & MONO_OPT_GSHAREDVT) && method->is_inflated && mono_method_get_context (method)->method_inst) {
4123 * This is partial sharing, and we can't handle it yet
4128 if (mono_method_is_generic_sharable_full (method, FALSE, FALSE, use_gsharedvt)) {
4130 add_types_from_method_header (acfg, method);
4134 if (method->is_generic)
4139 * FIXME: Instances which are referenced by these methods are not added,
4140 * for example Array.Resize<int> for List<int>.Add ().
4142 add_extra_method_with_depth (acfg, method, depth + 1);
4146 while ((field = mono_class_get_fields (klass, &iter))) {
4147 if (field->type->type == MONO_TYPE_GENERICINST)
4148 add_generic_class_with_depth (acfg, mono_class_from_mono_type (field->type), depth + 1, "field");
4151 if (klass->delegate) {
4152 method = mono_get_delegate_invoke (klass);
4154 method = mono_marshal_get_delegate_invoke (method, NULL);
4156 if (acfg->aot_opts.log_generics)
4157 aot_printf (acfg, "%*sAdding method %s.\n", depth, "", mono_method_full_name (method, TRUE));
4159 add_method (acfg, method);
4162 /* Add superclasses */
4164 add_generic_class_with_depth (acfg, klass->parent, depth, "parent");
4167 * For ICollection<T>, add instances of the helper methods
4168 * in Array, since a T[] could be cast to ICollection<T>.
4170 if (klass->image == mono_defaults.corlib && !strcmp (klass->name_space, "System.Collections.Generic") &&
4171 (!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"))) {
4172 MonoClass *tclass = mono_class_from_mono_type (klass->generic_class->context.class_inst->type_argv [0]);
4173 MonoClass *array_class = mono_bounded_array_class_get (tclass, 1, FALSE);
4177 if (!strcmp (klass->name, "IEnumerator`1"))
4178 name_prefix = g_strdup_printf ("%s.%s", klass->name_space, "IEnumerable`1");
4180 name_prefix = g_strdup_printf ("%s.%s", klass->name_space, klass->name);
4182 /* Add the T[]/InternalEnumerator class */
4183 if (!strcmp (klass->name, "IEnumerable`1") || !strcmp (klass->name, "IEnumerator`1")) {
4187 while ((nclass = mono_class_get_nested_types (array_class->parent, &iter))) {
4188 if (!strcmp (nclass->name, "InternalEnumerator`1"))
4192 nclass = mono_class_inflate_generic_class (nclass, mono_generic_class_get_context (klass->generic_class));
4193 add_generic_class (acfg, nclass, FALSE, "ICollection<T>");
4197 while ((method = mono_class_get_methods (array_class, &iter))) {
4198 if (strstr (method->name, name_prefix)) {
4199 MonoMethod *m = mono_aot_get_array_helper_from_wrapper (method);
4201 add_extra_method_with_depth (acfg, m, depth);
4205 g_free (name_prefix);
4208 /* Add an instance of GenericComparer<T> which is created dynamically by Comparer<T> */
4209 if (klass->image == mono_defaults.corlib && !strcmp (klass->name_space, "System.Collections.Generic") && !strcmp (klass->name, "Comparer`1")) {
4210 MonoClass *tclass = mono_class_from_mono_type (klass->generic_class->context.class_inst->type_argv [0]);
4211 MonoClass *icomparable, *gcomparer;
4212 MonoGenericContext ctx;
4213 MonoType *args [16];
4215 memset (&ctx, 0, sizeof (ctx));
4217 icomparable = mono_class_from_name (mono_defaults.corlib, "System", "IComparable`1");
4218 g_assert (icomparable);
4219 args [0] = &tclass->byval_arg;
4220 ctx.class_inst = mono_metadata_get_generic_inst (1, args);
4222 if (mono_class_is_assignable_from (mono_class_inflate_generic_class (icomparable, &ctx), tclass)) {
4223 gcomparer = mono_class_from_name (mono_defaults.corlib, "System.Collections.Generic", "GenericComparer`1");
4224 g_assert (gcomparer);
4225 add_generic_class (acfg, mono_class_inflate_generic_class (gcomparer, &ctx), FALSE, "Comparer<T>");
4229 /* Add an instance of GenericEqualityComparer<T> which is created dynamically by EqualityComparer<T> */
4230 if (klass->image == mono_defaults.corlib && !strcmp (klass->name_space, "System.Collections.Generic") && !strcmp (klass->name, "EqualityComparer`1")) {
4231 MonoClass *tclass = mono_class_from_mono_type (klass->generic_class->context.class_inst->type_argv [0]);
4232 MonoClass *iface, *gcomparer;
4233 MonoGenericContext ctx;
4234 MonoType *args [16];
4236 memset (&ctx, 0, sizeof (ctx));
4238 iface = mono_class_from_name (mono_defaults.corlib, "System", "IEquatable`1");
4240 args [0] = &tclass->byval_arg;
4241 ctx.class_inst = mono_metadata_get_generic_inst (1, args);
4243 if (mono_class_is_assignable_from (mono_class_inflate_generic_class (iface, &ctx), tclass)) {
4244 gcomparer = mono_class_from_name (mono_defaults.corlib, "System.Collections.Generic", "GenericEqualityComparer`1");
4245 g_assert (gcomparer);
4246 add_generic_class (acfg, mono_class_inflate_generic_class (gcomparer, &ctx), FALSE, "EqualityComparer<T>");
4250 /* Add an instance of EnumComparer<T> which is created dynamically by EqualityComparer<T> for enums */
4251 if (klass->image == mono_defaults.corlib && !strcmp (klass->name_space, "System.Collections.Generic") && !strcmp (klass->name, "EqualityComparer`1")) {
4252 MonoClass *enum_comparer;
4253 MonoClass *tclass = mono_class_from_mono_type (klass->generic_class->context.class_inst->type_argv [0]);
4254 MonoGenericContext ctx;
4255 MonoType *args [16];
4257 if (mono_class_is_enum (tclass)) {
4258 memset (&ctx, 0, sizeof (ctx));
4259 args [0] = &tclass->byval_arg;
4260 ctx.class_inst = mono_metadata_get_generic_inst (1, args);
4262 enum_comparer = mono_class_from_name (mono_defaults.corlib, "System.Collections.Generic", "EnumEqualityComparer`1");
4263 g_assert (enum_comparer);
4264 add_generic_class (acfg, mono_class_inflate_generic_class (enum_comparer, &ctx), FALSE, "EqualityComparer<T>");
4268 /* Add an instance of ObjectComparer<T> which is created dynamically by Comparer<T> for enums */
4269 if (klass->image == mono_defaults.corlib && !strcmp (klass->name_space, "System.Collections.Generic") && !strcmp (klass->name, "Comparer`1")) {
4270 MonoClass *comparer;
4271 MonoClass *tclass = mono_class_from_mono_type (klass->generic_class->context.class_inst->type_argv [0]);
4272 MonoGenericContext ctx;
4273 MonoType *args [16];
4275 if (mono_class_is_enum (tclass)) {
4276 memset (&ctx, 0, sizeof (ctx));
4277 args [0] = &tclass->byval_arg;
4278 ctx.class_inst = mono_metadata_get_generic_inst (1, args);
4280 comparer = mono_class_from_name (mono_defaults.corlib, "System.Collections.Generic", "ObjectComparer`1");
4281 g_assert (comparer);
4282 add_generic_class (acfg, mono_class_inflate_generic_class (comparer, &ctx), FALSE, "Comparer<T>");
4288 add_instances_of (MonoAotCompile *acfg, MonoClass *klass, MonoType **insts, int ninsts, gboolean force)
4291 MonoGenericContext ctx;
4292 MonoType *args [16];
4294 if (acfg->aot_opts.no_instances)
4297 memset (&ctx, 0, sizeof (ctx));
4299 for (i = 0; i < ninsts; ++i) {
4300 args [0] = insts [i];
4301 ctx.class_inst = mono_metadata_get_generic_inst (1, args);
4302 add_generic_class (acfg, mono_class_inflate_generic_class (klass, &ctx), force, "");
4307 add_types_from_method_header (MonoAotCompile *acfg, MonoMethod *method)
4309 MonoMethodHeader *header;
4310 MonoMethodSignature *sig;
4313 depth = GPOINTER_TO_UINT (g_hash_table_lookup (acfg->method_depth, method));
4315 sig = mono_method_signature (method);
4318 for (j = 0; j < sig->param_count; ++j)
4319 if (sig->params [j]->type == MONO_TYPE_GENERICINST)
4320 add_generic_class_with_depth (acfg, mono_class_from_mono_type (sig->params [j]), depth + 1, "arg");
4323 header = mono_method_get_header (method);
4326 for (j = 0; j < header->num_locals; ++j)
4327 if (header->locals [j]->type == MONO_TYPE_GENERICINST)
4328 add_generic_class_with_depth (acfg, mono_class_from_mono_type (header->locals [j]), depth + 1, "local");
4330 mono_loader_clear_error ();
4335 * add_generic_instances:
4337 * Add instances referenced by the METHODSPEC/TYPESPEC table.
4340 add_generic_instances (MonoAotCompile *acfg)
4345 MonoGenericContext *context;
4347 if (acfg->aot_opts.no_instances)
4350 for (i = 0; i < acfg->image->tables [MONO_TABLE_METHODSPEC].rows; ++i) {
4352 token = MONO_TOKEN_METHOD_SPEC | (i + 1);
4353 method = mono_get_method_checked (acfg->image, token, NULL, NULL, &error);
4356 aot_printerrf (acfg, "Failed to load methodspec 0x%x due to %s.\n", token, mono_error_get_message (&error));
4357 aot_printerrf (acfg, "Run with MONO_LOG_LEVEL=debug for more information.\n");
4358 mono_error_cleanup (&error);
4362 if (method->klass->image != acfg->image)
4365 context = mono_method_get_context (method);
4367 if (context && ((context->class_inst && context->class_inst->is_open)))
4371 * For open methods, create an instantiation which can be passed to the JIT.
4372 * FIXME: Handle class_inst as well.
4374 if (context && context->method_inst && context->method_inst->is_open) {
4376 MonoGenericContext shared_context;
4377 MonoGenericInst *inst;
4378 MonoType **type_argv;
4380 MonoMethod *declaring_method;
4381 gboolean supported = TRUE;
4383 /* Check that the context doesn't contain open constructed types */
4384 if (context->class_inst) {
4385 inst = context->class_inst;
4386 for (i = 0; i < inst->type_argc; ++i) {
4387 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)
4389 if (mono_class_is_open_constructed_type (inst->type_argv [i]))
4393 if (context->method_inst) {
4394 inst = context->method_inst;
4395 for (i = 0; i < inst->type_argc; ++i) {
4396 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)
4398 if (mono_class_is_open_constructed_type (inst->type_argv [i]))
4406 memset (&shared_context, 0, sizeof (MonoGenericContext));
4408 inst = context->class_inst;
4410 type_argv = g_new0 (MonoType*, inst->type_argc);
4411 for (i = 0; i < inst->type_argc; ++i) {
4412 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)
4413 type_argv [i] = &mono_defaults.object_class->byval_arg;
4415 type_argv [i] = inst->type_argv [i];
4418 shared_context.class_inst = mono_metadata_get_generic_inst (inst->type_argc, type_argv);
4422 inst = context->method_inst;
4424 type_argv = g_new0 (MonoType*, inst->type_argc);
4425 for (i = 0; i < inst->type_argc; ++i) {
4426 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)
4427 type_argv [i] = &mono_defaults.object_class->byval_arg;
4429 type_argv [i] = inst->type_argv [i];
4432 shared_context.method_inst = mono_metadata_get_generic_inst (inst->type_argc, type_argv);
4436 if (method->is_generic || method->klass->generic_container)
4437 declaring_method = method;
4439 declaring_method = mono_method_get_declaring_generic_method (method);
4441 method = mono_class_inflate_generic_method_checked (declaring_method, &shared_context, &error);
4442 g_assert (mono_error_ok (&error)); /* FIXME don't swallow the error */
4446 * If the method is fully sharable, it was already added in place of its
4447 * generic definition.
4449 if (mono_method_is_generic_sharable_full (method, FALSE, FALSE, FALSE))
4453 * FIXME: Partially shared methods are not shared here, so we end up with
4454 * many identical methods.
4456 add_extra_method (acfg, method);
4459 for (i = 0; i < acfg->image->tables [MONO_TABLE_TYPESPEC].rows; ++i) {
4463 token = MONO_TOKEN_TYPE_SPEC | (i + 1);
4465 klass = mono_class_get_checked (acfg->image, token, &error);
4466 if (!klass || klass->rank) {
4467 mono_error_cleanup (&error);
4471 add_generic_class (acfg, klass, FALSE, "typespec");
4474 /* Add types of args/locals */
4475 for (i = 0; i < acfg->methods->len; ++i) {
4476 method = (MonoMethod *)g_ptr_array_index (acfg->methods, i);
4477 add_types_from_method_header (acfg, method);
4480 if (acfg->image == mono_defaults.corlib) {
4482 MonoType *insts [256];
4485 insts [ninsts ++] = &mono_defaults.byte_class->byval_arg;
4486 insts [ninsts ++] = &mono_defaults.sbyte_class->byval_arg;
4487 insts [ninsts ++] = &mono_defaults.int16_class->byval_arg;
4488 insts [ninsts ++] = &mono_defaults.uint16_class->byval_arg;
4489 insts [ninsts ++] = &mono_defaults.int32_class->byval_arg;
4490 insts [ninsts ++] = &mono_defaults.uint32_class->byval_arg;
4491 insts [ninsts ++] = &mono_defaults.int64_class->byval_arg;
4492 insts [ninsts ++] = &mono_defaults.uint64_class->byval_arg;
4493 insts [ninsts ++] = &mono_defaults.single_class->byval_arg;
4494 insts [ninsts ++] = &mono_defaults.double_class->byval_arg;
4495 insts [ninsts ++] = &mono_defaults.char_class->byval_arg;
4496 insts [ninsts ++] = &mono_defaults.boolean_class->byval_arg;
4498 /* Add GenericComparer<T> instances for primitive types for Enum.ToString () */
4499 klass = mono_class_from_name (acfg->image, "System.Collections.Generic", "GenericComparer`1");
4501 add_instances_of (acfg, klass, insts, ninsts, TRUE);
4502 klass = mono_class_from_name (acfg->image, "System.Collections.Generic", "GenericEqualityComparer`1");
4504 add_instances_of (acfg, klass, insts, ninsts, TRUE);
4506 /* Add instances of EnumEqualityComparer which are created by EqualityComparer<T> for enums */
4508 MonoClass *enum_comparer;
4509 MonoType *insts [16];
4513 insts [ninsts ++] = &mono_defaults.int32_class->byval_arg;
4514 insts [ninsts ++] = &mono_defaults.uint32_class->byval_arg;
4515 insts [ninsts ++] = &mono_defaults.uint16_class->byval_arg;
4516 insts [ninsts ++] = &mono_defaults.byte_class->byval_arg;
4517 enum_comparer = mono_class_from_name (mono_defaults.corlib, "System.Collections.Generic", "EnumEqualityComparer`1");
4518 g_assert (enum_comparer);
4519 add_instances_of (acfg, enum_comparer, insts, ninsts, FALSE);
4522 insts [ninsts ++] = &mono_defaults.int16_class->byval_arg;
4523 enum_comparer = mono_class_from_name (mono_defaults.corlib, "System.Collections.Generic", "ShortEnumEqualityComparer`1");
4524 g_assert (enum_comparer);
4525 add_instances_of (acfg, enum_comparer, insts, ninsts, FALSE);
4528 insts [ninsts ++] = &mono_defaults.sbyte_class->byval_arg;
4529 enum_comparer = mono_class_from_name (mono_defaults.corlib, "System.Collections.Generic", "SByteEnumEqualityComparer`1");
4530 g_assert (enum_comparer);
4531 add_instances_of (acfg, enum_comparer, insts, ninsts, FALSE);
4533 enum_comparer = mono_class_from_name (mono_defaults.corlib, "System.Collections.Generic", "LongEnumEqualityComparer`1");
4534 g_assert (enum_comparer);
4536 insts [ninsts ++] = &mono_defaults.int64_class->byval_arg;
4537 insts [ninsts ++] = &mono_defaults.uint64_class->byval_arg;
4538 add_instances_of (acfg, enum_comparer, insts, ninsts, FALSE);
4541 /* Add instances of the array generic interfaces for primitive types */
4542 /* This will add instances of the InternalArray_ helper methods in Array too */
4543 klass = mono_class_from_name (acfg->image, "System.Collections.Generic", "ICollection`1");
4545 add_instances_of (acfg, klass, insts, ninsts, TRUE);
4546 klass = mono_class_from_name (acfg->image, "System.Collections.Generic", "IList`1");
4548 add_instances_of (acfg, klass, insts, ninsts, TRUE);
4549 klass = mono_class_from_name (acfg->image, "System.Collections.Generic", "IEnumerable`1");
4551 add_instances_of (acfg, klass, insts, ninsts, TRUE);
4554 * Add a managed-to-native wrapper of Array.GetGenericValueImpl<object>, which is
4555 * used for all instances of GetGenericValueImpl by the AOT runtime.
4558 MonoGenericContext ctx;
4559 MonoType *args [16];
4560 MonoMethod *get_method;
4561 MonoClass *array_klass = mono_array_class_get (mono_defaults.object_class, 1)->parent;
4563 get_method = mono_class_get_method_from_name (array_klass, "GetGenericValueImpl", 2);
4567 memset (&ctx, 0, sizeof (ctx));
4568 args [0] = &mono_defaults.object_class->byval_arg;
4569 ctx.method_inst = mono_metadata_get_generic_inst (1, args);
4570 add_extra_method (acfg, mono_marshal_get_native_wrapper (mono_class_inflate_generic_method_checked (get_method, &ctx, &error), TRUE, TRUE));
4571 g_assert (mono_error_ok (&error)); /* FIXME don't swallow the error */
4575 /* Same for CompareExchange<T>/Exchange<T> */
4577 MonoGenericContext ctx;
4578 MonoType *args [16];
4580 MonoClass *interlocked_klass = mono_class_from_name (mono_defaults.corlib, "System.Threading", "Interlocked");
4581 gpointer iter = NULL;
4583 while ((m = mono_class_get_methods (interlocked_klass, &iter))) {
4584 if ((!strcmp (m->name, "CompareExchange") || !strcmp (m->name, "Exchange")) && m->is_generic) {
4586 memset (&ctx, 0, sizeof (ctx));
4587 args [0] = &mono_defaults.object_class->byval_arg;
4588 ctx.method_inst = mono_metadata_get_generic_inst (1, args);
4589 add_extra_method (acfg, mono_marshal_get_native_wrapper (mono_class_inflate_generic_method_checked (m, &ctx, &error), TRUE, TRUE));
4590 g_assert (mono_error_ok (&error)); /* FIXME don't swallow the error */
4595 /* Same for Volatile.Read/Write<T> */
4597 MonoGenericContext ctx;
4598 MonoType *args [16];
4600 MonoClass *volatile_klass = mono_class_from_name (mono_defaults.corlib, "System.Threading", "Volatile");
4601 gpointer iter = NULL;
4603 if (volatile_klass) {
4604 while ((m = mono_class_get_methods (volatile_klass, &iter))) {
4605 if ((!strcmp (m->name, "Read") || !strcmp (m->name, "Write")) && m->is_generic) {
4607 memset (&ctx, 0, sizeof (ctx));
4608 args [0] = &mono_defaults.object_class->byval_arg;
4609 ctx.method_inst = mono_metadata_get_generic_inst (1, args);
4610 add_extra_method (acfg, mono_marshal_get_native_wrapper (mono_class_inflate_generic_method_checked (m, &ctx, &error), TRUE, TRUE));
4611 g_assert (mono_error_ok (&error)); /* FIXME don't swallow the error */
4617 /* object[] accessor wrappers. */
4619 MonoClass *obj_array_class = mono_array_class_get (mono_defaults.object_class, 1);
4622 m = mono_class_get_method_from_name (obj_array_class, "Get", 1);
4625 m = mono_marshal_get_array_accessor_wrapper (m);
4626 add_extra_method (acfg, m);
4628 m = mono_class_get_method_from_name (obj_array_class, "Address", 1);
4631 m = mono_marshal_get_array_accessor_wrapper (m);
4632 add_extra_method (acfg, m);
4634 m = mono_class_get_method_from_name (obj_array_class, "Set", 2);
4637 m = mono_marshal_get_array_accessor_wrapper (m);
4638 add_extra_method (acfg, m);
4644 * is_direct_callable:
4646 * Return whenever the method identified by JI is directly callable without
4647 * going through the PLT.
4650 is_direct_callable (MonoAotCompile *acfg, MonoMethod *method, MonoJumpInfo *patch_info)
4652 if ((patch_info->type == MONO_PATCH_INFO_METHOD) && (patch_info->data.method->klass->image == acfg->image)) {
4653 MonoCompile *callee_cfg = (MonoCompile *)g_hash_table_lookup (acfg->method_to_cfg, patch_info->data.method);
4655 gboolean direct_callable = TRUE;
4657 if (direct_callable && !(!callee_cfg->has_got_slots && (callee_cfg->method->klass->flags & TYPE_ATTRIBUTE_BEFORE_FIELD_INIT)))
4658 direct_callable = FALSE;
4659 if ((callee_cfg->method->iflags & METHOD_IMPL_ATTRIBUTE_SYNCHRONIZED) && (!method || method->wrapper_type != MONO_WRAPPER_SYNCHRONIZED))
4660 // FIXME: Maybe call the wrapper directly ?
4661 direct_callable = FALSE;
4663 if (acfg->aot_opts.soft_debug || acfg->aot_opts.no_direct_calls) {
4664 /* Disable this so all calls go through load_method (), see the
4665 * mini_get_debug_options ()->load_aot_jit_info_eagerly = TRUE; line in
4666 * mono_debugger_agent_init ().
4668 direct_callable = FALSE;
4671 if (callee_cfg->method->wrapper_type == MONO_WRAPPER_ALLOC)
4672 /* sgen does some initialization when the allocator method is created */
4673 direct_callable = FALSE;
4674 if (callee_cfg->method->wrapper_type == MONO_WRAPPER_WRITE_BARRIER)
4675 /* we don't know at compile time whether sgen is concurrent or not */
4676 direct_callable = FALSE;
4678 if (direct_callable)
4681 } else if ((patch_info->type == MONO_PATCH_INFO_ICALL_ADDR && patch_info->data.method->flags & METHOD_ATTRIBUTE_PINVOKE_IMPL)) {
4682 if (acfg->aot_opts.direct_pinvoke)
4684 } else if (patch_info->type == MONO_PATCH_INFO_ICALL_ADDR) {
4685 if (acfg->aot_opts.direct_icalls)
4693 #ifdef MONO_ARCH_AOT_SUPPORTED
4695 get_pinvoke_import (MonoAotCompile *acfg, MonoMethod *method)
4697 MonoImage *image = method->klass->image;
4698 MonoMethodPInvoke *piinfo = (MonoMethodPInvoke *) method;
4699 MonoTableInfo *tables = image->tables;
4700 MonoTableInfo *im = &tables [MONO_TABLE_IMPLMAP];
4701 MonoTableInfo *mr = &tables [MONO_TABLE_MODULEREF];
4702 guint32 im_cols [MONO_IMPLMAP_SIZE];
4705 import = (char *)g_hash_table_lookup (acfg->method_to_pinvoke_import, method);
4709 if (!piinfo->implmap_idx || piinfo->implmap_idx > im->rows)
4712 mono_metadata_decode_row (im, piinfo->implmap_idx - 1, im_cols, MONO_IMPLMAP_SIZE);
4714 if (!im_cols [MONO_IMPLMAP_SCOPE] || im_cols [MONO_IMPLMAP_SCOPE] > mr->rows)
4717 import = g_strdup_printf ("%s", mono_metadata_string_heap (image, im_cols [MONO_IMPLMAP_NAME]));
4719 g_hash_table_insert (acfg->method_to_pinvoke_import, method, import);
4726 compare_lne (MonoDebugLineNumberEntry *a, MonoDebugLineNumberEntry *b)
4728 if (a->native_offset == b->native_offset)
4729 return a->il_offset - b->il_offset;
4731 return a->native_offset - b->native_offset;
4735 * compute_line_numbers:
4737 * Returns a sparse array of size CODE_SIZE containing MonoDebugSourceLocation* entries for the native offsets which have a corresponding line number
4740 static MonoDebugSourceLocation**
4741 compute_line_numbers (MonoMethod *method, int code_size, MonoDebugMethodJitInfo *debug_info)
4743 MonoDebugMethodInfo *minfo;
4744 MonoDebugLineNumberEntry *ln_array;
4745 MonoDebugSourceLocation *loc;
4746 int i, prev_line, prev_il_offset;
4747 int *native_to_il_offset = NULL;
4748 MonoDebugSourceLocation **res;
4751 minfo = mono_debug_lookup_method (method);
4754 // FIXME: This seems to happen when two methods have the same cfg->method_to_register
4755 if (debug_info->code_size != code_size)
4758 g_assert (code_size);
4760 /* Compute the native->IL offset mapping */
4762 ln_array = g_new0 (MonoDebugLineNumberEntry, debug_info->num_line_numbers);
4763 memcpy (ln_array, debug_info->line_numbers, debug_info->num_line_numbers * sizeof (MonoDebugLineNumberEntry));
4765 qsort (ln_array, debug_info->num_line_numbers, sizeof (MonoDebugLineNumberEntry), (int (*)(const void *, const void *))compare_lne);
4767 native_to_il_offset = g_new0 (int, code_size + 1);
4769 for (i = 0; i < debug_info->num_line_numbers; ++i) {
4771 MonoDebugLineNumberEntry *lne = &ln_array [i];
4774 for (j = 0; j < lne->native_offset; ++j)
4775 native_to_il_offset [j] = -1;
4778 if (i < debug_info->num_line_numbers - 1) {
4779 MonoDebugLineNumberEntry *lne_next = &ln_array [i + 1];
4781 for (j = lne->native_offset; j < lne_next->native_offset; ++j)
4782 native_to_il_offset [j] = lne->il_offset;
4784 for (j = lne->native_offset; j < code_size; ++j)
4785 native_to_il_offset [j] = lne->il_offset;
4790 /* Compute the native->line number mapping */
4791 res = g_new0 (MonoDebugSourceLocation*, code_size);
4792 prev_il_offset = -1;
4795 for (i = 0; i < code_size; ++i) {
4796 int il_offset = native_to_il_offset [i];
4798 if (il_offset == -1 || il_offset == prev_il_offset)
4800 prev_il_offset = il_offset;
4801 loc = mono_debug_symfile_lookup_location (minfo, il_offset);
4802 if (!(loc && loc->source_file))
4804 if (loc->row == prev_line) {
4805 mono_debug_symfile_free_location (loc);
4808 prev_line = loc->row;
4809 //printf ("D: %s:%d il=%x native=%x\n", loc->source_file, loc->row, il_offset, i);
4811 /* This will cover the prolog too */
4821 get_file_index (MonoAotCompile *acfg, const char *source_file)
4825 // FIXME: Free these
4826 if (!acfg->dwarf_ln_filenames)
4827 acfg->dwarf_ln_filenames = g_hash_table_new (g_str_hash, g_str_equal);
4828 findex = GPOINTER_TO_INT (g_hash_table_lookup (acfg->dwarf_ln_filenames, source_file));
4830 findex = g_hash_table_size (acfg->dwarf_ln_filenames) + 1;
4831 g_hash_table_insert (acfg->dwarf_ln_filenames, g_strdup (source_file), GINT_TO_POINTER (findex));
4832 emit_unset_mode (acfg);
4833 fprintf (acfg->fp, ".file %d \"%s\"\n", findex, mono_dwarf_escape_path (source_file));
4845 * emit_and_reloc_code:
4847 * Emit the native code in CODE, handling relocations along the way. If GOT_ONLY
4848 * is true, calls are made through the GOT too. This is used for emitting trampolines
4849 * in full-aot mode, since calls made from trampolines couldn't go through the PLT,
4850 * since trampolines are needed to make PTL work.
4853 emit_and_reloc_code (MonoAotCompile *acfg, MonoMethod *method, guint8 *code, guint32 code_len, MonoJumpInfo *relocs, gboolean got_only, MonoDebugMethodJitInfo *debug_info)
4855 int i, pindex, start_index;
4857 MonoJumpInfo *patch_info;
4858 MonoDebugSourceLocation **locs = NULL;
4860 #ifdef MONO_ARCH_AOT_SUPPORTED
4861 gboolean direct_call, external_call;
4863 const char *direct_call_target = 0;
4864 const char *direct_pinvoke;
4867 if (acfg->gas_line_numbers && method && debug_info) {
4868 locs = compute_line_numbers (method, code_len, debug_info);
4870 int findex = get_file_index (acfg, "<unknown>");
4871 emit_unset_mode (acfg);
4872 fprintf (acfg->fp, ".loc %d %d 0\n", findex, 1);
4876 /* Collect and sort relocations */
4877 patches = g_ptr_array_new ();
4878 for (patch_info = relocs; patch_info; patch_info = patch_info->next)
4879 g_ptr_array_add (patches, patch_info);
4880 g_ptr_array_sort (patches, compare_patches);
4883 for (i = 0; i < code_len; i += INST_LEN) {
4885 for (pindex = start_index; pindex < patches->len; ++pindex) {
4886 patch_info = (MonoJumpInfo *)g_ptr_array_index (patches, pindex);
4887 if (patch_info->ip.i >= i)
4891 if (locs && locs [i]) {
4892 MonoDebugSourceLocation *loc = locs [i];
4895 findex = get_file_index (acfg, loc->source_file);
4896 emit_unset_mode (acfg);
4897 fprintf (acfg->fp, ".loc %d %d 0\n", findex, loc->row);
4898 mono_debug_symfile_free_location (loc);
4902 #ifdef MONO_ARCH_AOT_SUPPORTED
4903 if (patch_info && (patch_info->ip.i == i) && (pindex < patches->len)) {
4904 start_index = pindex;
4906 switch (patch_info->type) {
4907 case MONO_PATCH_INFO_NONE:
4909 case MONO_PATCH_INFO_GOT_OFFSET: {
4912 arch_emit_got_offset (acfg, code + i, &code_size);
4913 i += code_size - INST_LEN;
4915 patch_info->type = MONO_PATCH_INFO_NONE;
4918 case MONO_PATCH_INFO_OBJC_SELECTOR_REF: {
4919 int code_size, index;
4920 char *selector = (char *)patch_info->data.target;
4922 if (!acfg->objc_selector_to_index)
4923 acfg->objc_selector_to_index = g_hash_table_new (g_str_hash, g_str_equal);
4924 if (!acfg->objc_selectors)
4925 acfg->objc_selectors = g_ptr_array_new ();
4926 index = GPOINTER_TO_UINT (g_hash_table_lookup (acfg->objc_selector_to_index, selector));
4930 index = acfg->objc_selector_index;
4931 g_ptr_array_add (acfg->objc_selectors, (void*)patch_info->data.target);
4932 g_hash_table_insert (acfg->objc_selector_to_index, selector, GUINT_TO_POINTER (index + 1));
4933 acfg->objc_selector_index ++;
4936 arch_emit_objc_selector_ref (acfg, code + i, index, &code_size);
4937 i += code_size - INST_LEN;
4939 patch_info->type = MONO_PATCH_INFO_NONE;
4944 * If this patch is a call, try emitting a direct call instead of
4945 * through a PLT entry. This is possible if the called method is in
4946 * the same assembly and requires no initialization.
4948 direct_call = FALSE;
4949 external_call = FALSE;
4950 if ((patch_info->type == MONO_PATCH_INFO_METHOD) && (patch_info->data.method->klass->image == acfg->image)) {
4951 if (!got_only && is_direct_callable (acfg, method, patch_info)) {
4952 MonoCompile *callee_cfg = (MonoCompile *)g_hash_table_lookup (acfg->method_to_cfg, patch_info->data.method);
4953 //printf ("DIRECT: %s %s\n", method ? mono_method_full_name (method, TRUE) : "", mono_method_full_name (callee_cfg->method, TRUE));
4955 direct_call_target = callee_cfg->asm_symbol;
4956 patch_info->type = MONO_PATCH_INFO_NONE;
4957 acfg->stats.direct_calls ++;
4960 acfg->stats.all_calls ++;
4961 } else if (patch_info->type == MONO_PATCH_INFO_ICALL_ADDR) {
4962 if (!got_only && is_direct_callable (acfg, method, patch_info)) {
4963 if (!(patch_info->data.method->flags & METHOD_ATTRIBUTE_PINVOKE_IMPL))
4964 direct_pinvoke = mono_lookup_icall_symbol (patch_info->data.method);
4966 direct_pinvoke = get_pinvoke_import (acfg, patch_info->data.method);
4967 if (direct_pinvoke) {
4969 g_assert (strlen (direct_pinvoke) < 1000);
4970 direct_call_target = g_strdup_printf ("%s%s", acfg->user_symbol_prefix, direct_pinvoke);
4973 } else if (patch_info->type == MONO_PATCH_INFO_JIT_ICALL_ADDR) {
4974 const char *sym = mono_lookup_jit_icall_symbol (patch_info->data.name);
4975 if (!got_only && sym && acfg->aot_opts.direct_icalls) {
4976 /* Call to a C function implementing a jit icall */
4978 external_call = TRUE;
4979 g_assert (strlen (sym) < 1000);
4980 direct_call_target = g_strdup_printf ("%s%s", acfg->user_symbol_prefix, sym);
4982 } else if (patch_info->type == MONO_PATCH_INFO_INTERNAL_METHOD) {
4983 MonoJitICallInfo *info = mono_find_jit_icall_by_name (patch_info->data.name);
4984 const char *sym = mono_lookup_jit_icall_symbol (patch_info->data.name);
4985 if (!got_only && sym && acfg->aot_opts.direct_icalls && info->func == info->wrapper) {
4986 /* Call to a jit icall without a wrapper */
4988 external_call = TRUE;
4989 g_assert (strlen (sym) < 1000);
4990 direct_call_target = g_strdup_printf ("%s%s", acfg->user_symbol_prefix, sym);
4995 patch_info->type = MONO_PATCH_INFO_NONE;
4996 acfg->stats.direct_calls ++;
4999 if (!got_only && !direct_call) {
5000 MonoPltEntry *plt_entry = get_plt_entry (acfg, patch_info);
5002 /* This patch has a PLT entry, so we must emit a call to the PLT entry */
5004 direct_call_target = plt_entry->symbol;
5006 /* Nullify the patch */
5007 patch_info->type = MONO_PATCH_INFO_NONE;
5008 plt_entry->jit_used = TRUE;
5015 arch_emit_direct_call (acfg, direct_call_target, external_call, FALSE, patch_info, &call_size);
5016 i += call_size - INST_LEN;
5020 got_slot = get_got_offset (acfg, FALSE, patch_info);
5022 arch_emit_got_access (acfg, acfg->got_symbol, code + i, got_slot, &code_size);
5023 i += code_size - INST_LEN;
5029 #endif /* MONO_ARCH_AOT_SUPPORTED */
5032 /* Find next patch */
5034 for (pindex = start_index; pindex < patches->len; ++pindex) {
5035 patch_info = (MonoJumpInfo *)g_ptr_array_index (patches, pindex);
5036 if (patch_info->ip.i >= i)
5040 /* Try to emit multiple bytes at once */
5041 if (pindex < patches->len && patch_info->ip.i > i) {
5044 for (limit = i + INST_LEN; limit < patch_info->ip.i; limit += INST_LEN) {
5045 if (locs && locs [limit])
5049 emit_code_bytes (acfg, code + i, limit - i);
5050 i = limit - INST_LEN;
5052 emit_code_bytes (acfg, code + i, INST_LEN);
5063 * Return a modified version of S which only includes characters permissible in symbols.
5066 sanitize_symbol (MonoAotCompile *acfg, char *s)
5068 gboolean process = FALSE;
5077 for (i = 0; i < len; ++i)
5078 if (!(s [i] <= 0x7f && (isalnum (s [i]) || s [i] == '_')))
5083 gs = g_string_sized_new (len);
5084 for (i = 0; i < len; ++i) {
5086 if (c <= 0x7f && (isalnum (c) || c == '_')) {
5087 g_string_append_c (gs, c);
5088 } else if (c > 0x7f) {
5089 /* multi-byte utf8 */
5090 g_string_append_printf (gs, "_0x%x", c);
5093 while (c >> 6 == 0x2) {
5094 g_string_append_printf (gs, "%x", c);
5098 g_string_append_printf (gs, "_");
5101 g_string_append_c (gs, '_');
5105 res = mono_mempool_strdup (acfg->mempool, gs->str);
5106 g_string_free (gs, TRUE);
5111 get_debug_sym (MonoMethod *method, const char *prefix, GHashTable *cache)
5113 char *name1, *name2, *cached;
5114 int i, j, len, count;
5115 MonoMethod *cached_method;
5117 name1 = mono_method_full_name (method, TRUE);
5120 // This is so that we don't accidentally create a local symbol (which starts with 'L')
5121 if ((!prefix || !*prefix) && name1 [0] == 'L')
5125 len = strlen (name1);
5126 name2 = (char *)malloc (strlen (prefix) + len + 16);
5127 memcpy (name2, prefix, strlen (prefix));
5128 j = strlen (prefix);
5129 for (i = 0; i < len; ++i) {
5130 if (i == 0 && name1 [0] >= '0' && name1 [0] <= '9') {
5132 } else if (isalnum (name1 [i])) {
5133 name2 [j ++] = name1 [i];
5134 } else if (name1 [i] == ' ' && name1 [i + 1] == '(' && name1 [i + 2] == ')') {
5136 } else if (name1 [i] == ',' && name1 [i + 1] == ' ') {
5139 } else if (name1 [i] == '(' || name1 [i] == ')' || name1 [i] == '>') {
5149 cached_method = (MonoMethod *)g_hash_table_lookup (cache, name2);
5150 if (!(cached_method && cached_method != method))
5152 sprintf (name2 + j, "_%d", count);
5156 cached = g_strdup (name2);
5157 g_hash_table_insert (cache, cached, method);
5163 emit_method_code (MonoAotCompile *acfg, MonoCompile *cfg)
5168 char *debug_sym = NULL;
5169 char *symbol = NULL;
5170 int func_alignment = AOT_FUNC_ALIGNMENT;
5173 method = cfg->orig_method;
5174 code = cfg->native_code;
5176 method_index = get_method_index (acfg, method);
5177 symbol = g_strdup_printf ("%sme_%x", acfg->temp_prefix, method_index);
5179 /* Make the labels local */
5180 emit_section_change (acfg, ".text", 0);
5181 emit_alignment_code (acfg, func_alignment);
5183 if (acfg->global_symbols && acfg->need_no_dead_strip)
5184 fprintf (acfg->fp, " .no_dead_strip %s\n", cfg->asm_symbol);
5186 emit_label (acfg, cfg->asm_symbol);
5188 if (acfg->aot_opts.write_symbols && !acfg->global_symbols && !acfg->llvm) {
5190 * Write a C style symbol for every method, this has two uses:
5191 * - it works on platforms where the dwarf debugging info is not
5193 * - it allows the setting of breakpoints of aot-ed methods.
5195 debug_sym = get_debug_sym (method, "", acfg->method_label_hash);
5196 cfg->asm_debug_symbol = g_strdup (debug_sym);
5198 if (acfg->need_no_dead_strip)
5199 fprintf (acfg->fp, " .no_dead_strip %s\n", debug_sym);
5200 emit_local_symbol (acfg, debug_sym, symbol, TRUE);
5201 emit_label (acfg, debug_sym);
5204 export_name = (char *)g_hash_table_lookup (acfg->export_names, method);
5206 /* Emit a global symbol for the method */
5207 emit_global_inner (acfg, export_name, TRUE);
5208 emit_label (acfg, export_name);
5211 if (cfg->verbose_level > 0)
5212 g_print ("Method %s emitted as %s\n", mono_method_full_name (method, TRUE), cfg->asm_symbol);
5214 acfg->stats.code_size += cfg->code_len;
5216 acfg->cfgs [method_index]->got_offset = acfg->got_offset;
5218 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 ()));
5222 if (acfg->aot_opts.write_symbols) {
5224 emit_symbol_size (acfg, debug_sym, ".");
5226 emit_symbol_size (acfg, cfg->asm_symbol, ".");
5230 emit_label (acfg, symbol);
5237 * Encode PATCH_INFO into its disk representation.
5240 encode_patch (MonoAotCompile *acfg, MonoJumpInfo *patch_info, guint8 *buf, guint8 **endbuf)
5244 switch (patch_info->type) {
5245 case MONO_PATCH_INFO_NONE:
5247 case MONO_PATCH_INFO_IMAGE:
5248 encode_value (get_image_index (acfg, patch_info->data.image), p, &p);
5250 case MONO_PATCH_INFO_MSCORLIB_GOT_ADDR:
5251 case MONO_PATCH_INFO_JIT_TLS_ID:
5252 case MONO_PATCH_INFO_GC_CARD_TABLE_ADDR:
5253 case MONO_PATCH_INFO_GC_NURSERY_START:
5254 case MONO_PATCH_INFO_GC_NURSERY_BITS:
5256 case MONO_PATCH_INFO_CASTCLASS_CACHE:
5257 encode_value (patch_info->data.index, p, &p);
5259 case MONO_PATCH_INFO_METHOD_REL:
5260 encode_value ((gint)patch_info->data.offset, p, &p);
5262 case MONO_PATCH_INFO_SWITCH: {
5263 gpointer *table = (gpointer *)patch_info->data.table->table;
5266 encode_value (patch_info->data.table->table_size, p, &p);
5267 for (k = 0; k < patch_info->data.table->table_size; k++)
5268 encode_value ((int)(gssize)table [k], p, &p);
5271 case MONO_PATCH_INFO_METHODCONST:
5272 case MONO_PATCH_INFO_METHOD:
5273 case MONO_PATCH_INFO_METHOD_JUMP:
5274 case MONO_PATCH_INFO_ICALL_ADDR:
5275 case MONO_PATCH_INFO_METHOD_RGCTX:
5276 case MONO_PATCH_INFO_METHOD_CODE_SLOT:
5277 encode_method_ref (acfg, patch_info->data.method, p, &p);
5279 case MONO_PATCH_INFO_AOT_JIT_INFO:
5280 encode_value (patch_info->data.index, p, &p);
5282 case MONO_PATCH_INFO_INTERNAL_METHOD:
5283 case MONO_PATCH_INFO_JIT_ICALL_ADDR: {
5284 guint32 len = strlen (patch_info->data.name);
5286 encode_value (len, p, &p);
5288 memcpy (p, patch_info->data.name, len);
5293 case MONO_PATCH_INFO_LDSTR: {
5294 guint32 image_index = get_image_index (acfg, patch_info->data.token->image);
5295 guint32 token = patch_info->data.token->token;
5296 g_assert (mono_metadata_token_code (token) == MONO_TOKEN_STRING);
5297 encode_value (image_index, p, &p);
5298 encode_value (patch_info->data.token->token - MONO_TOKEN_STRING, p, &p);
5301 case MONO_PATCH_INFO_RVA:
5302 case MONO_PATCH_INFO_DECLSEC:
5303 case MONO_PATCH_INFO_LDTOKEN:
5304 case MONO_PATCH_INFO_TYPE_FROM_HANDLE:
5305 encode_value (get_image_index (acfg, patch_info->data.token->image), p, &p);
5306 encode_value (patch_info->data.token->token, p, &p);
5307 encode_value (patch_info->data.token->has_context, p, &p);
5308 if (patch_info->data.token->has_context)
5309 encode_generic_context (acfg, &patch_info->data.token->context, p, &p);
5311 case MONO_PATCH_INFO_EXC_NAME: {
5312 MonoClass *ex_class;
5315 mono_class_from_name (mono_defaults.exception_class->image,
5316 "System", (const char *)patch_info->data.target);
5317 g_assert (ex_class);
5318 encode_klass_ref (acfg, ex_class, p, &p);
5321 case MONO_PATCH_INFO_R4:
5322 encode_value (*((guint32 *)patch_info->data.target), p, &p);
5324 case MONO_PATCH_INFO_R8:
5325 encode_value (((guint32 *)patch_info->data.target) [MINI_LS_WORD_IDX], p, &p);
5326 encode_value (((guint32 *)patch_info->data.target) [MINI_MS_WORD_IDX], p, &p);
5328 case MONO_PATCH_INFO_VTABLE:
5329 case MONO_PATCH_INFO_CLASS:
5330 case MONO_PATCH_INFO_IID:
5331 case MONO_PATCH_INFO_ADJUSTED_IID:
5332 encode_klass_ref (acfg, patch_info->data.klass, p, &p);
5334 case MONO_PATCH_INFO_DELEGATE_TRAMPOLINE:
5335 encode_klass_ref (acfg, patch_info->data.del_tramp->klass, p, &p);
5336 if (patch_info->data.del_tramp->method) {
5337 encode_value (1, p, &p);
5338 encode_method_ref (acfg, patch_info->data.del_tramp->method, p, &p);
5340 encode_value (0, p, &p);
5342 encode_value (patch_info->data.del_tramp->is_virtual, p, &p);
5344 case MONO_PATCH_INFO_FIELD:
5345 case MONO_PATCH_INFO_SFLDA:
5346 encode_field_info (acfg, patch_info->data.field, p, &p);
5348 case MONO_PATCH_INFO_INTERRUPTION_REQUEST_FLAG:
5350 case MONO_PATCH_INFO_RGCTX_FETCH:
5351 case MONO_PATCH_INFO_RGCTX_SLOT_INDEX: {
5352 MonoJumpInfoRgctxEntry *entry = patch_info->data.rgctx_entry;
5357 * entry->method has a lenghtly encoding and multiple rgctx_fetch entries
5358 * reference the same method, so encode the method only once.
5360 offset = GPOINTER_TO_UINT (g_hash_table_lookup (acfg->method_blob_hash, entry->method));
5362 buf2 = (guint8 *)g_malloc (1024);
5365 encode_method_ref (acfg, entry->method, p2, &p2);
5366 g_assert (p2 - buf2 < 1024);
5368 offset = add_to_blob (acfg, buf2, p2 - buf2);
5371 g_hash_table_insert (acfg->method_blob_hash, entry->method, GUINT_TO_POINTER (offset + 1));
5376 encode_value (offset, p, &p);
5377 g_assert ((int)entry->info_type < 256);
5378 g_assert (entry->data->type < 256);
5379 encode_value ((entry->in_mrgctx ? 1 : 0) | (entry->info_type << 1) | (entry->data->type << 9), p, &p);
5380 encode_patch (acfg, entry->data, p, &p);
5383 case MONO_PATCH_INFO_SEQ_POINT_INFO:
5384 case MONO_PATCH_INFO_AOT_MODULE:
5386 case MONO_PATCH_INFO_SIGNATURE:
5387 encode_signature (acfg, (MonoMethodSignature*)patch_info->data.target, p, &p);
5389 case MONO_PATCH_INFO_TLS_OFFSET:
5390 encode_value (GPOINTER_TO_INT (patch_info->data.target), p, &p);
5392 case MONO_PATCH_INFO_GSHAREDVT_CALL:
5393 encode_signature (acfg, (MonoMethodSignature*)patch_info->data.gsharedvt->sig, p, &p);
5394 encode_method_ref (acfg, patch_info->data.gsharedvt->method, p, &p);
5396 case MONO_PATCH_INFO_GSHAREDVT_METHOD: {
5397 MonoGSharedVtMethodInfo *info = patch_info->data.gsharedvt_method;
5400 encode_method_ref (acfg, info->method, p, &p);
5401 encode_value (info->num_entries, p, &p);
5402 for (i = 0; i < info->num_entries; ++i) {
5403 MonoRuntimeGenericContextInfoTemplate *template_ = &info->entries [i];
5405 encode_value (template_->info_type, p, &p);
5406 switch (mini_rgctx_info_type_to_patch_info_type (template_->info_type)) {
5407 case MONO_PATCH_INFO_CLASS:
5408 encode_klass_ref (acfg, mono_class_from_mono_type ((MonoType *)template_->data), p, &p);
5410 case MONO_PATCH_INFO_FIELD:
5411 encode_field_info (acfg, (MonoClassField *)template_->data, p, &p);
5414 g_assert_not_reached ();
5420 case MONO_PATCH_INFO_LDSTR_LIT: {
5421 const char *s = (const char *)patch_info->data.target;
5422 int len = strlen (s);
5424 encode_value (len, p, &p);
5425 memcpy (p, s, len + 1);
5429 case MONO_PATCH_INFO_VIRT_METHOD:
5430 encode_klass_ref (acfg, patch_info->data.virt_method->klass, p, &p);
5431 encode_method_ref (acfg, patch_info->data.virt_method->method, p, &p);
5433 case MONO_PATCH_INFO_GC_SAFE_POINT_FLAG:
5436 g_warning ("unable to handle jump info %d", patch_info->type);
5437 g_assert_not_reached ();
5444 encode_patch_list (MonoAotCompile *acfg, GPtrArray *patches, int n_patches, gboolean llvm, int first_got_offset, guint8 *buf, guint8 **endbuf)
5447 guint32 pindex, offset;
5448 MonoJumpInfo *patch_info;
5450 encode_value (n_patches, p, &p);
5452 for (pindex = 0; pindex < patches->len; ++pindex) {
5453 patch_info = (MonoJumpInfo *)g_ptr_array_index (patches, pindex);
5455 if (patch_info->type == MONO_PATCH_INFO_NONE || patch_info->type == MONO_PATCH_INFO_BB)
5459 offset = get_got_offset (acfg, llvm, patch_info);
5460 encode_value (offset, p, &p);
5467 emit_method_info (MonoAotCompile *acfg, MonoCompile *cfg)
5470 int pindex, buf_size, n_patches;
5472 MonoJumpInfo *patch_info;
5473 guint32 method_index;
5475 guint32 first_got_offset;
5477 method = cfg->orig_method;
5479 method_index = get_method_index (acfg, method);
5481 /* Sort relocations */
5482 patches = g_ptr_array_new ();
5483 for (patch_info = cfg->patch_info; patch_info; patch_info = patch_info->next)
5484 g_ptr_array_add (patches, patch_info);
5485 g_ptr_array_sort (patches, compare_patches);
5487 first_got_offset = acfg->cfgs [method_index]->got_offset;
5489 /**********************/
5490 /* Encode method info */
5491 /**********************/
5493 buf_size = (patches->len < 1000) ? 40960 : 40960 + (patches->len * 64);
5494 p = buf = (guint8 *)g_malloc (buf_size);
5496 if (mono_class_get_cctor (method->klass))
5497 encode_klass_ref (acfg, method->klass, p, &p);
5499 /* Not needed when loading the method */
5500 encode_value (0, p, &p);
5502 g_assert (!(cfg->opt & MONO_OPT_SHARED));
5505 for (pindex = 0; pindex < patches->len; ++pindex) {
5506 patch_info = (MonoJumpInfo *)g_ptr_array_index (patches, pindex);
5508 if ((patch_info->type == MONO_PATCH_INFO_GOT_OFFSET) ||
5509 (patch_info->type == MONO_PATCH_INFO_NONE)) {
5510 patch_info->type = MONO_PATCH_INFO_NONE;
5515 if ((patch_info->type == MONO_PATCH_INFO_IMAGE) && (patch_info->data.image == acfg->image)) {
5516 /* Stored in a GOT slot initialized at module load time */
5517 patch_info->type = MONO_PATCH_INFO_NONE;
5521 if (patch_info->type == MONO_PATCH_INFO_GC_CARD_TABLE_ADDR ||
5522 patch_info->type == MONO_PATCH_INFO_GC_NURSERY_START ||
5523 patch_info->type == MONO_PATCH_INFO_GC_NURSERY_BITS ||
5524 patch_info->type == MONO_PATCH_INFO_AOT_MODULE) {
5525 /* Stored in a GOT slot initialized at module load time */
5526 patch_info->type = MONO_PATCH_INFO_NONE;
5530 if (is_plt_patch (patch_info) && !(cfg->compile_llvm && acfg->aot_opts.llvm_only)) {
5531 /* Calls are made through the PLT */
5532 patch_info->type = MONO_PATCH_INFO_NONE;
5540 g_assert (cfg->has_got_slots);
5542 encode_patch_list (acfg, patches, n_patches, cfg->compile_llvm, first_got_offset, p, &p);
5544 acfg->stats.info_size += p - buf;
5546 g_assert (p - buf < buf_size);
5548 cfg->method_info_offset = add_to_blob (acfg, buf, p - buf);
5553 get_unwind_info_offset (MonoAotCompile *acfg, guint8 *encoded, guint32 encoded_len)
5555 guint32 cache_index;
5558 /* Reuse the unwind module to canonize and store unwind info entries */
5559 cache_index = mono_cache_unwind_info (encoded, encoded_len);
5561 /* Use +/- 1 to distinguish 0s from missing entries */
5562 offset = GPOINTER_TO_UINT (g_hash_table_lookup (acfg->unwind_info_offsets, GUINT_TO_POINTER (cache_index + 1)));
5570 * It would be easier to use assembler symbols, but the caller needs an
5573 offset = acfg->unwind_info_offset;
5574 g_hash_table_insert (acfg->unwind_info_offsets, GUINT_TO_POINTER (cache_index + 1), GUINT_TO_POINTER (offset + 1));
5575 g_ptr_array_add (acfg->unwind_ops, GUINT_TO_POINTER (cache_index));
5578 encode_value (encoded_len, p, &p);
5580 acfg->unwind_info_offset += encoded_len + (p - buf);
5586 emit_exception_debug_info (MonoAotCompile *acfg, MonoCompile *cfg, gboolean store_seq_points)
5589 guint32 debug_info_size, seq_points_size;
5591 MonoMethodHeader *header;
5592 guint8 *p, *buf, *debug_info;
5593 MonoJitInfo *jinfo = cfg->jit_info;
5595 gboolean use_unwind_ops = FALSE;
5596 MonoSeqPointInfo *seq_points;
5598 code = cfg->native_code;
5599 header = cfg->header;
5601 if (!acfg->aot_opts.nodebug) {
5602 mono_debug_serialize_debug_info (cfg, &debug_info, &debug_info_size);
5605 debug_info_size = 0;
5608 seq_points = cfg->seq_point_info;
5609 seq_points_size = (store_seq_points)? mono_seq_point_info_get_write_size (seq_points) : 0;
5611 buf_size = header->num_clauses * 256 + debug_info_size + 2048 + seq_points_size + cfg->gc_map_size;
5613 p = buf = (guint8 *)g_malloc (buf_size);
5615 use_unwind_ops = cfg->unwind_ops != NULL;
5617 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);
5619 encode_value (flags, p, &p);
5621 if (use_unwind_ops) {
5622 guint32 encoded_len;
5624 guint32 unwind_desc;
5626 encoded = mono_unwind_ops_encode (cfg->unwind_ops, &encoded_len);
5628 unwind_desc = get_unwind_info_offset (acfg, encoded, encoded_len);
5629 encode_value (unwind_desc, p, &p);
5631 encode_value (jinfo->unwind_info, p, &p);
5634 /*Encode the number of holes before the number of clauses to make decoding easier*/
5635 if (jinfo->has_try_block_holes) {
5636 MonoTryBlockHoleTableJitInfo *table = mono_jit_info_get_try_block_hole_table_info (jinfo);
5637 encode_value (table->num_holes, p, &p);
5640 if (jinfo->has_arch_eh_info) {
5642 * In AOT mode, the code length is calculated from the address of the previous method,
5643 * which could include alignment padding, so calculating the start of the epilog as
5644 * code_len - epilog_size is correct any more. Save the real code len as a workaround.
5646 encode_value (jinfo->code_size, p, &p);
5649 /* Exception table */
5650 if (cfg->compile_llvm) {
5652 * When using LLVM, we can't emit some data, like pc offsets, this reg/offset etc.,
5653 * since the information is only available to llc. Instead, we let llc save the data
5654 * into the LSDA, and read it from there at runtime.
5656 /* The assembly might be CIL stripped so emit the data ourselves */
5657 if (header->num_clauses)
5658 encode_value (header->num_clauses, p, &p);
5660 for (k = 0; k < header->num_clauses; ++k) {
5661 MonoExceptionClause *clause;
5663 clause = &header->clauses [k];
5665 encode_value (clause->flags, p, &p);
5666 if (clause->data.catch_class) {
5667 encode_value (1, p, &p);
5668 encode_klass_ref (acfg, clause->data.catch_class, p, &p);
5670 encode_value (0, p, &p);
5673 /* Emit the IL ranges too, since they might not be available at runtime */
5674 encode_value (clause->try_offset, p, &p);
5675 encode_value (clause->try_len, p, &p);
5676 encode_value (clause->handler_offset, p, &p);
5677 encode_value (clause->handler_len, p, &p);
5679 /* Emit a list of nesting clauses */
5680 for (i = 0; i < header->num_clauses; ++i) {
5682 MonoExceptionClause *clause1 = &header->clauses [cindex1];
5684 MonoExceptionClause *clause2 = &header->clauses [cindex2];
5686 if (cindex1 != cindex2 && clause1->try_offset >= clause2->try_offset && clause1->handler_offset <= clause2->handler_offset)
5687 encode_value (i, p, &p);
5689 encode_value (-1, p, &p);
5692 if (jinfo->num_clauses)
5693 encode_value (jinfo->num_clauses, p, &p);
5695 for (k = 0; k < jinfo->num_clauses; ++k) {
5696 MonoJitExceptionInfo *ei = &jinfo->clauses [k];
5698 encode_value (ei->flags, p, &p);
5699 #ifdef MONO_CONTEXT_SET_LLVM_EXC_REG
5700 /* Not used for catch clauses */
5701 if (ei->flags != MONO_EXCEPTION_CLAUSE_NONE)
5702 encode_value (ei->exvar_offset, p, &p);
5704 encode_value (ei->exvar_offset, p, &p);
5707 if (ei->flags == MONO_EXCEPTION_CLAUSE_FILTER || ei->flags == MONO_EXCEPTION_CLAUSE_FINALLY)
5708 encode_value ((gint)((guint8*)ei->data.filter - code), p, &p);
5710 if (ei->data.catch_class) {
5714 buf2 = (guint8 *)g_malloc (4096);
5716 encode_klass_ref (acfg, ei->data.catch_class, p2, &p2);
5718 g_assert (len < 4096);
5719 encode_value (len, p, &p);
5720 memcpy (p, buf2, len);
5724 encode_value (0, p, &p);
5728 encode_value ((gint)((guint8*)ei->try_start - code), p, &p);
5729 encode_value ((gint)((guint8*)ei->try_end - code), p, &p);
5730 encode_value ((gint)((guint8*)ei->handler_start - code), p, &p);
5734 if (jinfo->has_try_block_holes) {
5735 MonoTryBlockHoleTableJitInfo *table = mono_jit_info_get_try_block_hole_table_info (jinfo);
5736 for (i = 0; i < table->num_holes; ++i) {
5737 MonoTryBlockHoleJitInfo *hole = &table->holes [i];
5738 encode_value (hole->clause, p, &p);
5739 encode_value (hole->length, p, &p);
5740 encode_value (hole->offset, p, &p);
5744 if (jinfo->has_arch_eh_info) {
5745 MonoArchEHJitInfo *eh_info;
5747 eh_info = mono_jit_info_get_arch_eh_info (jinfo);
5748 encode_value (eh_info->stack_size, p, &p);
5749 encode_value (eh_info->epilog_size, p, &p);
5752 if (jinfo->has_generic_jit_info) {
5753 MonoGenericJitInfo *gi = mono_jit_info_get_generic_jit_info (jinfo);
5754 MonoGenericSharingContext* gsctx = gi->generic_sharing_context;
5758 encode_value (gi->nlocs, p, &p);
5760 for (i = 0; i < gi->nlocs; ++i) {
5761 MonoDwarfLocListEntry *entry = &gi->locations [i];
5763 encode_value (entry->is_reg ? 1 : 0, p, &p);
5764 encode_value (entry->reg, p, &p);
5766 encode_value (entry->offset, p, &p);
5768 g_assert (entry->from == 0);
5770 encode_value (entry->from, p, &p);
5771 encode_value (entry->to, p, &p);
5774 if (!cfg->compile_llvm) {
5775 encode_value (gi->has_this ? 1 : 0, p, &p);
5776 encode_value (gi->this_reg, p, &p);
5777 encode_value (gi->this_offset, p, &p);
5782 * Need to encode jinfo->method too, since it is not equal to 'method'
5783 * when using generic sharing.
5785 buf2 = (guint8 *)g_malloc (4096);
5787 encode_method_ref (acfg, jinfo->d.method, p2, &p2);
5789 g_assert (len < 4096);
5790 encode_value (len, p, &p);
5791 memcpy (p, buf2, len);
5795 if (gsctx && gsctx->is_gsharedvt) {
5796 encode_value (1, p, &p);
5798 encode_value (0, p, &p);
5802 if (seq_points_size)
5803 p += mono_seq_point_info_write (seq_points, p);
5805 g_assert (debug_info_size < buf_size);
5807 encode_value (debug_info_size, p, &p);
5808 if (debug_info_size) {
5809 memcpy (p, debug_info, debug_info_size);
5810 p += debug_info_size;
5811 g_free (debug_info);
5816 encode_value (cfg->gc_map_size, p, &p);
5817 /* The GC map requires 4 bytes of alignment */
5818 while ((gsize)p % 4)
5820 memcpy (p, cfg->gc_map, cfg->gc_map_size);
5821 p += cfg->gc_map_size;
5824 acfg->stats.ex_info_size += p - buf;
5826 g_assert (p - buf < buf_size);
5829 /* The GC Map requires 4 byte alignment */
5830 cfg->ex_info_offset = add_to_blob_aligned (acfg, buf, p - buf, cfg->gc_map ? 4 : 1);
5835 emit_klass_info (MonoAotCompile *acfg, guint32 token)
5838 MonoClass *klass = mono_class_get_checked (acfg->image, token, &error);
5840 int i, buf_size, res;
5841 gboolean no_special_static, cant_encode;
5842 gpointer iter = NULL;
5845 mono_error_cleanup (&error);
5849 p = buf = (guint8 *)g_malloc (buf_size);
5851 /* Mark as unusable */
5852 encode_value (-1, p, &p);
5854 res = add_to_blob (acfg, buf, p - buf);
5860 buf_size = 10240 + (klass->vtable_size * 16);
5861 p = buf = (guint8 *)g_malloc (buf_size);
5865 mono_class_init (klass);
5867 mono_class_get_nested_types (klass, &iter);
5868 g_assert (klass->nested_classes_inited);
5870 mono_class_setup_vtable (klass);
5873 * Emit all the information which is required for creating vtables so
5874 * the runtime does not need to create the MonoMethod structures which
5875 * take up a lot of space.
5878 no_special_static = !mono_class_has_special_static_fields (klass);
5880 /* Check whenever we have enough info to encode the vtable */
5881 cant_encode = FALSE;
5882 for (i = 0; i < klass->vtable_size; ++i) {
5883 MonoMethod *cm = klass->vtable [i];
5885 if (cm && mono_method_signature (cm)->is_inflated && !g_hash_table_lookup (acfg->token_info_hash, cm))
5889 mono_class_has_finalizer (klass);
5891 if (klass->generic_container || cant_encode) {
5892 encode_value (-1, p, &p);
5894 encode_value (klass->vtable_size, p, &p);
5895 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);
5896 if (klass->has_cctor)
5897 encode_method_ref (acfg, mono_class_get_cctor (klass), p, &p);
5898 if (klass->has_finalize)
5899 encode_method_ref (acfg, mono_class_get_finalizer (klass), p, &p);
5901 encode_value (klass->instance_size, p, &p);
5902 encode_value (mono_class_data_size (klass), p, &p);
5903 encode_value (klass->packing_size, p, &p);
5904 encode_value (klass->min_align, p, &p);
5906 for (i = 0; i < klass->vtable_size; ++i) {
5907 MonoMethod *cm = klass->vtable [i];
5910 encode_method_ref (acfg, cm, p, &p);
5912 encode_value (0, p, &p);
5916 acfg->stats.class_info_size += p - buf;
5918 g_assert (p - buf < buf_size);
5919 res = add_to_blob (acfg, buf, p - buf);
5926 get_plt_entry_debug_sym (MonoAotCompile *acfg, MonoJumpInfo *ji, GHashTable *cache)
5928 char *debug_sym = NULL;
5931 if (acfg->llvm && llvm_acfg->aot_opts.static_link) {
5932 /* Need to add a prefix to create unique symbols */
5933 prefix = g_strdup_printf ("plt_%s_", acfg->assembly_name_sym);
5935 prefix = g_strdup ("plt_");
5939 case MONO_PATCH_INFO_METHOD:
5940 debug_sym = get_debug_sym (ji->data.method, prefix, cache);
5942 case MONO_PATCH_INFO_INTERNAL_METHOD:
5943 debug_sym = g_strdup_printf ("%s_jit_icall_%s", prefix, ji->data.name);
5945 case MONO_PATCH_INFO_RGCTX_FETCH:
5946 debug_sym = g_strdup_printf ("%s_rgctx_fetch_%d", prefix, acfg->label_generator ++);
5948 case MONO_PATCH_INFO_ICALL_ADDR: {
5949 char *s = get_debug_sym (ji->data.method, "", cache);
5951 debug_sym = g_strdup_printf ("%s_icall_native_%s", prefix, s);
5955 case MONO_PATCH_INFO_JIT_ICALL_ADDR:
5956 debug_sym = g_strdup_printf ("%s_jit_icall_native_%s", prefix, ji->data.name);
5964 return sanitize_symbol (acfg, debug_sym);
5968 * Calls made from AOTed code are routed through a table of jumps similar to the
5969 * ELF PLT (Program Linkage Table). Initially the PLT entries jump to code which transfers
5970 * control to the AOT runtime through a trampoline.
5973 emit_plt (MonoAotCompile *acfg)
5977 if (acfg->aot_opts.llvm_only) {
5978 g_assert (acfg->plt_offset == 1);
5984 emit_section_change (acfg, ".text", 0);
5985 emit_alignment_code (acfg, NACL_SIZE(16, kNaClAlignment));
5986 emit_info_symbol (acfg, "plt");
5987 emit_label (acfg, acfg->plt_symbol);
5989 for (i = 0; i < acfg->plt_offset; ++i) {
5990 char *debug_sym = NULL;
5991 MonoPltEntry *plt_entry = NULL;
5995 * The first plt entry is unused.
5999 plt_entry = (MonoPltEntry *)g_hash_table_lookup (acfg->plt_offset_to_entry, GUINT_TO_POINTER (i));
6001 debug_sym = plt_entry->debug_sym;
6003 if (acfg->thumb_mixed && !plt_entry->jit_used)
6004 /* Emit only a thumb version */
6007 /* Skip plt entries not actually called */
6008 if (!plt_entry->jit_used && !plt_entry->llvm_used)
6011 if (acfg->llvm && !acfg->thumb_mixed) {
6012 emit_label (acfg, plt_entry->llvm_symbol);
6014 emit_global_inner (acfg, plt_entry->llvm_symbol, TRUE);
6015 #if defined(TARGET_MACH)
6016 fprintf (acfg->fp, ".private_extern %s\n", plt_entry->llvm_symbol);
6022 if (acfg->need_no_dead_strip) {
6023 emit_unset_mode (acfg);
6024 fprintf (acfg->fp, " .no_dead_strip %s\n", debug_sym);
6026 emit_local_symbol (acfg, debug_sym, NULL, TRUE);
6027 emit_label (acfg, debug_sym);
6030 emit_label (acfg, plt_entry->symbol);
6032 arch_emit_plt_entry (acfg, acfg->got_symbol, (acfg->plt_got_offset_base + i) * sizeof (gpointer), acfg->plt_got_info_offsets [i]);
6035 emit_symbol_size (acfg, debug_sym, ".");
6038 if (acfg->thumb_mixed) {
6039 /* Make sure the ARM symbols don't alias the thumb ones */
6040 emit_zero_bytes (acfg, 16);
6043 * Emit a separate set of PLT entries using thumb2 which is called by LLVM generated
6046 for (i = 0; i < acfg->plt_offset; ++i) {
6047 char *debug_sym = NULL;
6048 MonoPltEntry *plt_entry = NULL;
6053 plt_entry = (MonoPltEntry *)g_hash_table_lookup (acfg->plt_offset_to_entry, GUINT_TO_POINTER (i));
6055 /* Skip plt entries not actually called by LLVM code */
6056 if (!plt_entry->llvm_used)
6059 if (acfg->aot_opts.write_symbols) {
6060 if (plt_entry->debug_sym)
6061 debug_sym = g_strdup_printf ("%s_thumb", plt_entry->debug_sym);
6065 #if defined(TARGET_MACH)
6066 fprintf (acfg->fp, " .thumb_func %s\n", debug_sym);
6067 fprintf (acfg->fp, " .no_dead_strip %s\n", debug_sym);
6069 emit_local_symbol (acfg, debug_sym, NULL, TRUE);
6070 emit_label (acfg, debug_sym);
6072 fprintf (acfg->fp, "\n.thumb_func\n");
6074 emit_label (acfg, plt_entry->llvm_symbol);
6077 emit_global_inner (acfg, plt_entry->llvm_symbol, TRUE);
6079 arch_emit_llvm_plt_entry (acfg, acfg->got_symbol, (acfg->plt_got_offset_base + i) * sizeof (gpointer), acfg->plt_got_info_offsets [i]);
6082 emit_symbol_size (acfg, debug_sym, ".");
6088 emit_symbol_size (acfg, acfg->plt_symbol, ".");
6090 emit_info_symbol (acfg, "plt_end");
6094 * emit_trampoline_full:
6096 * If EMIT_TINFO is TRUE, emit additional information which can be used to create a MonoJitInfo for this trampoline by
6097 * create_jit_info_for_trampoline ().
6099 static G_GNUC_UNUSED void
6100 emit_trampoline_full (MonoAotCompile *acfg, int got_offset, MonoTrampInfo *info, gboolean emit_tinfo)
6102 char start_symbol [256];
6103 char end_symbol [256];
6105 guint32 buf_size, info_offset;
6106 MonoJumpInfo *patch_info;
6119 code_size = info->code_size;
6121 unwind_ops = info->unwind_ops;
6123 #ifdef __native_client_codegen__
6124 mono_nacl_fix_patches (code, ji);
6129 sprintf (start_symbol, "%s%s", acfg->user_symbol_prefix, name);
6131 emit_section_change (acfg, ".text", 0);
6132 emit_global (acfg, start_symbol, TRUE);
6133 emit_alignment_code (acfg, AOT_FUNC_ALIGNMENT);
6134 emit_label (acfg, start_symbol);
6136 sprintf (symbol, "%snamed_%s", acfg->temp_prefix, name);
6137 emit_label (acfg, symbol);
6140 * The code should access everything through the GOT, so we pass
6143 emit_and_reloc_code (acfg, NULL, code, code_size, ji, TRUE, NULL);
6145 emit_symbol_size (acfg, start_symbol, ".");
6148 sprintf (end_symbol, "%snamede_%s", acfg->temp_prefix, name);
6149 emit_label (acfg, end_symbol);
6154 /* Sort relocations */
6155 patches = g_ptr_array_new ();
6156 for (patch_info = ji; patch_info; patch_info = patch_info->next)
6157 if (patch_info->type != MONO_PATCH_INFO_NONE)
6158 g_ptr_array_add (patches, patch_info);
6159 g_ptr_array_sort (patches, compare_patches);
6161 buf_size = patches->len * 128 + 128;
6162 buf = (guint8 *)g_malloc (buf_size);
6165 encode_patch_list (acfg, patches, patches->len, FALSE, got_offset, p, &p);
6166 g_assert (p - buf < buf_size);
6168 sprintf (symbol, "%s%s_p", acfg->user_symbol_prefix, name);
6170 info_offset = add_to_blob (acfg, buf, p - buf);
6172 emit_section_change (acfg, RODATA_SECT, 0);
6173 emit_global (acfg, symbol, FALSE);
6174 emit_label (acfg, symbol);
6176 emit_int32 (acfg, info_offset);
6180 guint32 encoded_len;
6184 * Emit additional information which can be used to reconstruct a partial MonoTrampInfo.
6186 encoded = mono_unwind_ops_encode (info->unwind_ops, &encoded_len);
6187 uw_offset = get_unwind_info_offset (acfg, encoded, encoded_len);
6190 emit_symbol_diff (acfg, end_symbol, start_symbol, 0);
6191 emit_int32 (acfg, uw_offset);
6194 /* Emit debug info */
6198 sprintf (symbol, "%s", name);
6199 sprintf (symbol2, "%snamed_%s", acfg->temp_prefix, name);
6202 mono_dwarf_writer_emit_trampoline (acfg->dwarf, symbol, symbol2, NULL, NULL, code_size, unwind_ops);
6206 static G_GNUC_UNUSED void
6207 emit_trampoline (MonoAotCompile *acfg, int got_offset, MonoTrampInfo *info)
6209 emit_trampoline_full (acfg, got_offset, info, TRUE);
6213 emit_trampolines (MonoAotCompile *acfg)
6216 char end_symbol [256];
6217 int i, tramp_got_offset;
6219 #ifdef MONO_ARCH_HAVE_FULL_AOT_TRAMPOLINES
6223 if (!mono_aot_mode_is_full (&acfg->aot_opts) || acfg->aot_opts.llvm_only)
6226 g_assert (acfg->image->assembly);
6228 /* Currently, we emit most trampolines into the mscorlib AOT image. */
6229 if (strcmp (acfg->image->assembly->aname.name, "mscorlib") == 0) {
6230 #ifdef MONO_ARCH_HAVE_FULL_AOT_TRAMPOLINES
6231 MonoTrampInfo *info;
6234 * Emit the generic trampolines.
6236 * We could save some code by treating the generic trampolines as a wrapper
6237 * method, but that approach has its own complexities, so we choose the simpler
6240 for (tramp_type = 0; tramp_type < MONO_TRAMPOLINE_NUM; ++tramp_type) {
6241 /* we overload the boolean here to indicate the slightly different trampoline needed, see mono_arch_create_generic_trampoline() */
6242 #ifdef DISABLE_REMOTING
6243 if (tramp_type == MONO_TRAMPOLINE_GENERIC_VIRTUAL_REMOTING)
6246 #ifndef MONO_ARCH_HAVE_HANDLER_BLOCK_GUARD
6247 if (tramp_type == MONO_TRAMPOLINE_HANDLER_BLOCK_GUARD)
6250 mono_arch_create_generic_trampoline ((MonoTrampolineType)tramp_type, &info, acfg->aot_opts.use_trampolines_page? 2: TRUE);
6251 emit_trampoline (acfg, acfg->got_offset, info);
6254 /* Emit the exception related code pieces */
6255 mono_arch_get_restore_context (&info, TRUE);
6256 emit_trampoline (acfg, acfg->got_offset, info);
6257 mono_arch_get_call_filter (&info, TRUE);
6258 emit_trampoline (acfg, acfg->got_offset, info);
6259 mono_arch_get_throw_exception (&info, TRUE);
6260 emit_trampoline (acfg, acfg->got_offset, info);
6261 mono_arch_get_rethrow_exception (&info, TRUE);
6262 emit_trampoline (acfg, acfg->got_offset, info);
6263 mono_arch_get_throw_corlib_exception (&info, TRUE);
6264 emit_trampoline (acfg, acfg->got_offset, info);
6266 #ifdef MONO_ARCH_HAVE_SDB_TRAMPOLINES
6267 mono_arch_create_sdb_trampoline (TRUE, &info, TRUE);
6268 emit_trampoline (acfg, acfg->got_offset, info);
6269 mono_arch_create_sdb_trampoline (FALSE, &info, TRUE);
6270 emit_trampoline (acfg, acfg->got_offset, info);
6273 #ifdef MONO_ARCH_GSHAREDVT_SUPPORTED
6274 mono_arch_get_gsharedvt_trampoline (&info, TRUE);
6276 emit_trampoline_full (acfg, acfg->got_offset, info, TRUE);
6278 /* Create a separate out trampoline for more information in stack traces */
6279 info->name = g_strdup ("gsharedvt_out_trampoline");
6280 emit_trampoline_full (acfg, acfg->got_offset, info, TRUE);
6284 #if defined(MONO_ARCH_HAVE_GET_TRAMPOLINES)
6286 GSList *l = mono_arch_get_trampolines (TRUE);
6289 MonoTrampInfo *info = (MonoTrampInfo *)l->data;
6291 emit_trampoline (acfg, acfg->got_offset, info);
6297 for (i = 0; i < acfg->aot_opts.nrgctx_fetch_trampolines; ++i) {
6300 offset = MONO_RGCTX_SLOT_MAKE_RGCTX (i);
6301 mono_arch_create_rgctx_lazy_fetch_trampoline (offset, &info, TRUE);
6302 emit_trampoline (acfg, acfg->got_offset, info);
6304 offset = MONO_RGCTX_SLOT_MAKE_MRGCTX (i);
6305 mono_arch_create_rgctx_lazy_fetch_trampoline (offset, &info, TRUE);
6306 emit_trampoline (acfg, acfg->got_offset, info);
6309 #ifdef MONO_ARCH_HAVE_GENERAL_RGCTX_LAZY_FETCH_TRAMPOLINE
6310 mono_arch_create_general_rgctx_lazy_fetch_trampoline (&info, TRUE);
6311 emit_trampoline (acfg, acfg->got_offset, info);
6317 /* delegate_invoke_impl trampolines */
6318 l = mono_arch_get_delegate_invoke_impls ();
6320 MonoTrampInfo *info = (MonoTrampInfo *)l->data;
6322 emit_trampoline (acfg, acfg->got_offset, info);
6327 #endif /* #ifdef MONO_ARCH_HAVE_FULL_AOT_TRAMPOLINES */
6329 /* Emit trampolines which are numerous */
6332 * These include the following:
6333 * - specific trampolines
6334 * - static rgctx invoke trampolines
6336 * These trampolines have the same code, they are parameterized by GOT
6338 * They are defined in this file, in the arch_... routines instead of
6339 * in tramp-<ARCH>.c, since it is easier to do it this way.
6343 * When running in aot-only mode, we can't create specific trampolines at
6344 * runtime, so we create a few, and save them in the AOT file.
6345 * Normal trampolines embed their argument as a literal inside the
6346 * trampoline code, we can't do that here, so instead we embed an offset
6347 * which needs to be added to the trampoline address to get the address of
6348 * the GOT slot which contains the argument value.
6349 * The generated trampolines jump to the generic trampolines using another
6350 * GOT slot, which will be setup by the AOT loader to point to the
6351 * generic trampoline code of the given type.
6355 * FIXME: Maybe we should use more specific trampolines (i.e. one class init for
6359 emit_section_change (acfg, ".text", 0);
6361 tramp_got_offset = acfg->got_offset;
6363 for (ntype = 0; ntype < MONO_AOT_TRAMP_NUM; ++ntype) {
6365 case MONO_AOT_TRAMP_SPECIFIC:
6366 sprintf (symbol, "specific_trampolines");
6368 case MONO_AOT_TRAMP_STATIC_RGCTX:
6369 sprintf (symbol, "static_rgctx_trampolines");
6371 case MONO_AOT_TRAMP_IMT_THUNK:
6372 sprintf (symbol, "imt_thunks");
6374 case MONO_AOT_TRAMP_GSHAREDVT_ARG:
6375 sprintf (symbol, "gsharedvt_arg_trampolines");
6378 g_assert_not_reached ();
6381 sprintf (end_symbol, "%s_e", symbol);
6383 if (acfg->aot_opts.write_symbols)
6384 emit_local_symbol (acfg, symbol, end_symbol, TRUE);
6386 emit_alignment_code (acfg, AOT_FUNC_ALIGNMENT);
6387 emit_info_symbol (acfg, symbol);
6389 acfg->trampoline_got_offset_base [ntype] = tramp_got_offset;
6391 for (i = 0; i < acfg->num_trampolines [ntype]; ++i) {
6395 case MONO_AOT_TRAMP_SPECIFIC:
6396 arch_emit_specific_trampoline (acfg, tramp_got_offset, &tramp_size);
6397 tramp_got_offset += 2;
6399 case MONO_AOT_TRAMP_STATIC_RGCTX:
6400 arch_emit_static_rgctx_trampoline (acfg, tramp_got_offset, &tramp_size);
6401 tramp_got_offset += 2;
6403 case MONO_AOT_TRAMP_IMT_THUNK:
6404 arch_emit_imt_thunk (acfg, tramp_got_offset, &tramp_size);
6405 tramp_got_offset += 1;
6407 case MONO_AOT_TRAMP_GSHAREDVT_ARG:
6408 arch_emit_gsharedvt_arg_trampoline (acfg, tramp_got_offset, &tramp_size);
6409 tramp_got_offset += 2;
6412 g_assert_not_reached ();
6414 #ifdef __native_client_codegen__
6415 /* align to avoid 32-byte boundary crossings */
6416 emit_alignment (acfg, AOT_FUNC_ALIGNMENT);
6419 if (!acfg->trampoline_size [ntype]) {
6420 g_assert (tramp_size);
6421 acfg->trampoline_size [ntype] = tramp_size;
6425 emit_label (acfg, end_symbol);
6426 emit_int32 (acfg, 0);
6429 arch_emit_specific_trampoline_pages (acfg);
6431 /* Reserve some entries at the end of the GOT for our use */
6432 acfg->num_trampoline_got_entries = tramp_got_offset - acfg->got_offset;
6435 acfg->got_offset += acfg->num_trampoline_got_entries;
6439 str_begins_with (const char *str1, const char *str2)
6441 int len = strlen (str2);
6442 return strncmp (str1, str2, len) == 0;
6446 mono_aot_readonly_field_override (MonoClassField *field)
6449 for (rdv = readonly_values; rdv; rdv = rdv->next) {
6450 char *p = rdv->name;
6452 len = strlen (field->parent->name_space);
6453 if (strncmp (p, field->parent->name_space, len))
6458 len = strlen (field->parent->name);
6459 if (strncmp (p, field->parent->name, len))
6464 if (strcmp (p, field->name))
6466 switch (rdv->type) {
6468 return &rdv->value.i1;
6470 return &rdv->value.i2;
6472 return &rdv->value.i4;
6481 add_readonly_value (MonoAotOptions *opts, const char *val)
6486 /* the format of val is:
6487 * namespace.typename.fieldname=type/value
6488 * type can be i1 for uint8/int8/boolean, i2 for uint16/int16/char, i4 for uint32/int32
6490 fval = strrchr (val, '/');
6492 fprintf (stderr, "AOT : invalid format for readonly field '%s', missing /.\n", val);
6495 tval = strrchr (val, '=');
6497 fprintf (stderr, "AOT : invalid format for readonly field '%s', missing =.\n", val);
6500 rdv = g_new0 (ReadOnlyValue, 1);
6501 rdv->name = (char *)g_malloc0 (tval - val + 1);
6502 memcpy (rdv->name, val, tval - val);
6505 if (strncmp (tval, "i1", 2) == 0) {
6506 rdv->value.i1 = atoi (fval);
6507 rdv->type = MONO_TYPE_I1;
6508 } else if (strncmp (tval, "i2", 2) == 0) {
6509 rdv->value.i2 = atoi (fval);
6510 rdv->type = MONO_TYPE_I2;
6511 } else if (strncmp (tval, "i4", 2) == 0) {
6512 rdv->value.i4 = atoi (fval);
6513 rdv->type = MONO_TYPE_I4;
6515 fprintf (stderr, "AOT : unsupported type for readonly field '%s'.\n", tval);
6518 rdv->next = readonly_values;
6519 readonly_values = rdv;
6523 clean_path (gchar * path)
6528 if (g_str_has_suffix (path, G_DIR_SEPARATOR_S))
6531 gchar *clean = g_strconcat (path, G_DIR_SEPARATOR_S, NULL);
6538 mono_aot_split_options (const char *aot_options)
6540 enum MonoAotOptionState {
6541 MONO_AOT_OPTION_STATE_DEFAULT,
6542 MONO_AOT_OPTION_STATE_STRING,
6543 MONO_AOT_OPTION_STATE_ESCAPE,
6546 GPtrArray *args = g_ptr_array_new ();
6547 enum MonoAotOptionState state = MONO_AOT_OPTION_STATE_DEFAULT;
6548 gchar const *opt_start = aot_options;
6549 gboolean end_of_string = FALSE;
6552 g_return_val_if_fail (aot_options != NULL, NULL);
6554 while ((cur = *aot_options) != '\0') {
6555 if (state == MONO_AOT_OPTION_STATE_ESCAPE)
6560 // If we find a quote, then if we're in the default case then
6561 // it means we've found the start of a string, if not then it
6562 // means we've found the end of the string and should switch
6563 // back to the default case.
6565 case MONO_AOT_OPTION_STATE_DEFAULT:
6566 state = MONO_AOT_OPTION_STATE_STRING;
6568 case MONO_AOT_OPTION_STATE_STRING:
6569 state = MONO_AOT_OPTION_STATE_DEFAULT;
6571 case MONO_AOT_OPTION_STATE_ESCAPE:
6572 g_assert_not_reached ();
6577 // If we've found an escaping operator, then this means we
6578 // should not process the next character if inside a string.
6579 if (state == MONO_AOT_OPTION_STATE_STRING)
6580 state = MONO_AOT_OPTION_STATE_ESCAPE;
6583 // If we're in the default state then this means we've found
6584 // an option, store it for later processing.
6585 if (state == MONO_AOT_OPTION_STATE_DEFAULT)
6592 // If the next character is end of string, then process the last option.
6593 if (*(aot_options) == '\0') {
6594 end_of_string = TRUE;
6600 g_ptr_array_add (args, g_strndup (opt_start, aot_options - opt_start));
6601 opt_start = ++aot_options;
6611 mono_aot_parse_options (const char *aot_options, MonoAotOptions *opts)
6615 args = mono_aot_split_options (aot_options ? aot_options : "");
6616 for (int i = 0; i < args->len; ++i) {
6617 const char *arg = (const char *)g_ptr_array_index (args, i);
6619 if (str_begins_with (arg, "outfile=")) {
6620 opts->outfile = g_strdup (arg + strlen ("outfile="));
6621 } else if (str_begins_with (arg, "llvm-outfile=")) {
6622 opts->llvm_outfile = g_strdup (arg + strlen ("llvm-outfile="));
6623 } else if (str_begins_with (arg, "temp-path=")) {
6624 opts->temp_path = clean_path (g_strdup (arg + strlen ("temp-path=")));
6625 } else if (str_begins_with (arg, "save-temps")) {
6626 opts->save_temps = TRUE;
6627 } else if (str_begins_with (arg, "keep-temps")) {
6628 opts->save_temps = TRUE;
6629 } else if (str_begins_with (arg, "write-symbols")) {
6630 opts->write_symbols = TRUE;
6631 } else if (str_begins_with (arg, "no-write-symbols")) {
6632 opts->write_symbols = FALSE;
6633 } else if (str_begins_with (arg, "metadata-only")) {
6634 opts->metadata_only = TRUE;
6635 } else if (str_begins_with (arg, "bind-to-runtime-version")) {
6636 opts->bind_to_runtime_version = TRUE;
6637 } else if (str_begins_with (arg, "full")) {
6638 opts->mode = MONO_AOT_MODE_FULL;
6639 } else if (str_begins_with (arg, "hybrid")) {
6640 opts->mode = MONO_AOT_MODE_HYBRID;
6641 } else if (str_begins_with (arg, "threads=")) {
6642 opts->nthreads = atoi (arg + strlen ("threads="));
6643 } else if (str_begins_with (arg, "static")) {
6644 opts->static_link = TRUE;
6645 opts->no_dlsym = TRUE;
6646 } else if (str_begins_with (arg, "asmonly")) {
6647 opts->asm_only = TRUE;
6648 } else if (str_begins_with (arg, "asmwriter")) {
6649 opts->asm_writer = TRUE;
6650 } else if (str_begins_with (arg, "nodebug")) {
6651 opts->nodebug = TRUE;
6652 } else if (str_begins_with (arg, "dwarfdebug")) {
6653 opts->dwarf_debug = TRUE;
6654 } else if (str_begins_with (arg, "nopagetrampolines")) {
6655 opts->use_trampolines_page = FALSE;
6656 } else if (str_begins_with (arg, "ntrampolines=")) {
6657 opts->ntrampolines = atoi (arg + strlen ("ntrampolines="));
6658 } else if (str_begins_with (arg, "nrgctx-trampolines=")) {
6659 opts->nrgctx_trampolines = atoi (arg + strlen ("nrgctx-trampolines="));
6660 } else if (str_begins_with (arg, "nimt-trampolines=")) {
6661 opts->nimt_trampolines = atoi (arg + strlen ("nimt-trampolines="));
6662 } else if (str_begins_with (arg, "ngsharedvt-trampolines=")) {
6663 opts->ngsharedvt_arg_trampolines = atoi (arg + strlen ("ngsharedvt-trampolines="));
6664 } else if (str_begins_with (arg, "tool-prefix=")) {
6665 opts->tool_prefix = g_strdup (arg + strlen ("tool-prefix="));
6666 } else if (str_begins_with (arg, "ld-flags=")) {
6667 opts->ld_flags = g_strdup (arg + strlen ("ld-flags="));
6668 } else if (str_begins_with (arg, "soft-debug")) {
6669 opts->soft_debug = TRUE;
6670 } else if (str_begins_with (arg, "gen-seq-points-file")) {
6671 opts->gen_seq_points_file = TRUE;
6672 } else if (str_begins_with (arg, "direct-pinvoke")) {
6673 opts->direct_pinvoke = TRUE;
6674 } else if (str_begins_with (arg, "direct-icalls")) {
6675 opts->direct_icalls = TRUE;
6676 } else if (str_begins_with (arg, "no-direct-calls")) {
6677 opts->no_direct_calls = TRUE;
6678 } else if (str_begins_with (arg, "print-skipped")) {
6679 opts->print_skipped_methods = TRUE;
6680 } else if (str_begins_with (arg, "stats")) {
6682 } else if (str_begins_with (arg, "no-instances")) {
6683 opts->no_instances = TRUE;
6684 } else if (str_begins_with (arg, "log-generics")) {
6685 opts->log_generics = TRUE;
6686 } else if (str_begins_with (arg, "log-instances=")) {
6687 opts->log_instances = TRUE;
6688 opts->instances_logfile_path = g_strdup (arg + strlen ("log-instances="));
6689 } else if (str_begins_with (arg, "log-instances")) {
6690 opts->log_instances = TRUE;
6691 } else if (str_begins_with (arg, "internal-logfile=")) {
6692 opts->logfile = g_strdup (arg + strlen ("internal-logfile="));
6693 } else if (str_begins_with (arg, "mtriple=")) {
6694 opts->mtriple = g_strdup (arg + strlen ("mtriple="));
6695 } else if (str_begins_with (arg, "llvm-path=")) {
6696 opts->llvm_path = clean_path (g_strdup (arg + strlen ("llvm-path=")));
6697 } else if (!strcmp (arg, "llvm")) {
6699 } else if (str_begins_with (arg, "readonly-value=")) {
6700 add_readonly_value (opts, arg + strlen ("readonly-value="));
6701 } else if (str_begins_with (arg, "info")) {
6702 printf ("AOT target setup: %s.\n", AOT_TARGET_STR);
6704 } else if (str_begins_with (arg, "gc-maps")) {
6705 mini_gc_enable_gc_maps_for_aot ();
6706 } else if (str_begins_with (arg, "dump")) {
6707 opts->dump_json = TRUE;
6708 } else if (str_begins_with (arg, "llvmonly")) {
6709 opts->mode = MONO_AOT_MODE_FULL;
6711 opts->llvm_only = TRUE;
6712 } else if (str_begins_with (arg, "help") || str_begins_with (arg, "?")) {
6713 printf ("Supported options for --aot:\n");
6714 printf (" outfile=\n");
6715 printf (" llvm-outfile=\n");
6716 printf (" llvm-path=\n");
6717 printf (" temp-path=\n");
6718 printf (" save-temps\n");
6719 printf (" keep-temps\n");
6720 printf (" write-symbols\n");
6721 printf (" metadata-only\n");
6722 printf (" bind-to-runtime-version\n");
6724 printf (" threads=\n");
6725 printf (" static\n");
6726 printf (" asmonly\n");
6727 printf (" asmwriter\n");
6728 printf (" nodebug\n");
6729 printf (" dwarfdebug\n");
6730 printf (" ntrampolines=\n");
6731 printf (" nrgctx-trampolines=\n");
6732 printf (" nimt-trampolines=\n");
6733 printf (" ngsharedvt-trampolines=\n");
6734 printf (" tool-prefix=\n");
6735 printf (" readonly-value=\n");
6736 printf (" soft-debug\n");
6737 printf (" gen-seq-points-file\n");
6738 printf (" gc-maps\n");
6739 printf (" print-skipped\n");
6740 printf (" no-instances\n");
6741 printf (" stats\n");
6744 printf (" help/?\n");
6747 fprintf (stderr, "AOT : Unknown argument '%s'.\n", arg);
6751 g_free ((gpointer) arg);
6754 if (opts->use_trampolines_page) {
6755 opts->ntrampolines = 0;
6756 opts->nrgctx_trampolines = 0;
6757 opts->nimt_trampolines = 0;
6758 opts->ngsharedvt_arg_trampolines = 0;
6761 g_ptr_array_free (args, /*free_seg=*/TRUE);
6765 add_token_info_hash (gpointer key, gpointer value, gpointer user_data)
6767 MonoMethod *method = (MonoMethod*)key;
6768 MonoJumpInfoToken *ji = (MonoJumpInfoToken*)value;
6769 MonoAotCompile *acfg = (MonoAotCompile *)user_data;
6770 MonoJumpInfoToken *new_ji;
6772 new_ji = (MonoJumpInfoToken *)mono_mempool_alloc0 (acfg->mempool, sizeof (MonoJumpInfoToken));
6773 new_ji->image = ji->image;
6774 new_ji->token = ji->token;
6775 g_hash_table_insert (acfg->token_info_hash, method, new_ji);
6779 can_encode_class (MonoAotCompile *acfg, MonoClass *klass)
6781 if (klass->type_token)
6783 if ((klass->byval_arg.type == MONO_TYPE_VAR) || (klass->byval_arg.type == MONO_TYPE_MVAR) || (klass->byval_arg.type == MONO_TYPE_PTR))
6786 return can_encode_class (acfg, klass->element_class);
6791 can_encode_method (MonoAotCompile *acfg, MonoMethod *method)
6793 if (method->wrapper_type) {
6794 switch (method->wrapper_type) {
6795 case MONO_WRAPPER_NONE:
6796 case MONO_WRAPPER_REMOTING_INVOKE_WITH_CHECK:
6797 case MONO_WRAPPER_XDOMAIN_INVOKE:
6798 case MONO_WRAPPER_STFLD:
6799 case MONO_WRAPPER_LDFLD:
6800 case MONO_WRAPPER_LDFLDA:
6801 case MONO_WRAPPER_LDFLD_REMOTE:
6802 case MONO_WRAPPER_STFLD_REMOTE:
6803 case MONO_WRAPPER_STELEMREF:
6804 case MONO_WRAPPER_ISINST:
6805 case MONO_WRAPPER_PROXY_ISINST:
6806 case MONO_WRAPPER_ALLOC:
6807 case MONO_WRAPPER_REMOTING_INVOKE:
6808 case MONO_WRAPPER_UNKNOWN:
6809 case MONO_WRAPPER_WRITE_BARRIER:
6810 case MONO_WRAPPER_DELEGATE_INVOKE:
6811 case MONO_WRAPPER_DELEGATE_BEGIN_INVOKE:
6812 case MONO_WRAPPER_DELEGATE_END_INVOKE:
6813 case MONO_WRAPPER_SYNCHRONIZED:
6815 case MONO_WRAPPER_MANAGED_TO_MANAGED:
6816 case MONO_WRAPPER_CASTCLASS: {
6817 WrapperInfo *info = mono_marshal_get_wrapper_info (method);
6826 //printf ("Skip (wrapper call): %d -> %s\n", patch_info->type, mono_method_full_name (patch_info->data.method, TRUE));
6830 if (!method->token) {
6831 /* The method is part of a constructed type like Int[,].Set (). */
6832 if (!g_hash_table_lookup (acfg->token_info_hash, method)) {
6833 if (method->klass->rank)
6843 can_encode_patch (MonoAotCompile *acfg, MonoJumpInfo *patch_info)
6845 switch (patch_info->type) {
6846 case MONO_PATCH_INFO_METHOD:
6847 case MONO_PATCH_INFO_METHODCONST:
6848 case MONO_PATCH_INFO_METHOD_CODE_SLOT: {
6849 MonoMethod *method = patch_info->data.method;
6851 return can_encode_method (acfg, method);
6853 case MONO_PATCH_INFO_VTABLE:
6854 case MONO_PATCH_INFO_CLASS:
6855 case MONO_PATCH_INFO_IID:
6856 case MONO_PATCH_INFO_ADJUSTED_IID:
6857 if (!can_encode_class (acfg, patch_info->data.klass)) {
6858 //printf ("Skip: %s\n", mono_type_full_name (&patch_info->data.klass->byval_arg));
6862 case MONO_PATCH_INFO_DELEGATE_TRAMPOLINE: {
6863 if (!can_encode_class (acfg, patch_info->data.del_tramp->klass)) {
6864 //printf ("Skip: %s\n", mono_type_full_name (&patch_info->data.klass->byval_arg));
6869 case MONO_PATCH_INFO_RGCTX_FETCH:
6870 case MONO_PATCH_INFO_RGCTX_SLOT_INDEX: {
6871 MonoJumpInfoRgctxEntry *entry = patch_info->data.rgctx_entry;
6873 if (!can_encode_method (acfg, entry->method))
6875 if (!can_encode_patch (acfg, entry->data))
6889 * AOT compile a given method.
6890 * This function might be called by multiple threads, so it must be thread-safe.
6893 compile_method (MonoAotCompile *acfg, MonoMethod *method)
6896 MonoJumpInfo *patch_info;
6899 MonoMethod *wrapped;
6902 if (acfg->aot_opts.metadata_only)
6905 mono_acfg_lock (acfg);
6906 index = get_method_index (acfg, method);
6907 mono_acfg_unlock (acfg);
6909 /* fixme: maybe we can also precompile wrapper methods */
6910 if ((method->flags & METHOD_ATTRIBUTE_PINVOKE_IMPL) ||
6911 (method->iflags & METHOD_IMPL_ATTRIBUTE_RUNTIME) ||
6912 (method->flags & METHOD_ATTRIBUTE_ABSTRACT)) {
6913 //printf ("Skip (impossible): %s\n", mono_method_full_name (method, TRUE));
6917 if (method->iflags & METHOD_IMPL_ATTRIBUTE_INTERNAL_CALL)
6920 wrapped = mono_marshal_method_from_wrapper (method);
6921 if (wrapped && (wrapped->iflags & METHOD_IMPL_ATTRIBUTE_INTERNAL_CALL) && wrapped->is_generic)
6922 // FIXME: The wrapper should be generic too, but it is not
6925 if (method->wrapper_type == MONO_WRAPPER_COMINTEROP)
6928 InterlockedIncrement (&acfg->stats.mcount);
6931 if (method->is_generic || method->klass->generic_container) {
6932 InterlockedIncrement (&acfg->stats.genericcount);
6937 //acfg->aot_opts.print_skipped_methods = TRUE;
6940 * Since these methods are the only ones which are compiled with
6941 * AOT support, and they are not used by runtime startup/shutdown code,
6942 * the runtime will not see AOT methods during AOT compilation,so it
6943 * does not need to support them by creating a fake GOT etc.
6945 flags = JIT_FLAG_AOT;
6946 if (mono_aot_mode_is_full (&acfg->aot_opts))
6947 flags = (JitFlags)(flags | JIT_FLAG_FULL_AOT);
6949 flags = (JitFlags)(flags | JIT_FLAG_LLVM);
6950 if (acfg->aot_opts.llvm_only)
6951 flags = (JitFlags)(flags | JIT_FLAG_LLVM_ONLY | JIT_FLAG_EXPLICIT_NULL_CHECKS);
6952 if (acfg->aot_opts.no_direct_calls)
6953 flags = (JitFlags)(flags | JIT_FLAG_NO_DIRECT_ICALLS);
6954 cfg = mini_method_compile (method, acfg->opts, mono_get_root_domain (), flags, 0, index);
6955 mono_loader_clear_error ();
6957 if (cfg->exception_type == MONO_EXCEPTION_GENERIC_SHARING_FAILED) {
6958 if (acfg->aot_opts.print_skipped_methods)
6959 printf ("Skip (gshared failure): %s (%s)\n", mono_method_full_name (method, TRUE), cfg->exception_message);
6960 InterlockedIncrement (&acfg->stats.genericcount);
6963 if (cfg->exception_type != MONO_EXCEPTION_NONE) {
6964 if (acfg->aot_opts.print_skipped_methods)
6965 printf ("Skip (JIT failure): %s\n", mono_method_full_name (method, TRUE));
6966 /* Let the exception happen at runtime */
6970 if (cfg->disable_aot) {
6971 if (acfg->aot_opts.print_skipped_methods)
6972 printf ("Skip (disabled): %s\n", mono_method_full_name (method, TRUE));
6973 InterlockedIncrement (&acfg->stats.ocount);
6974 mono_destroy_compile (cfg);
6977 cfg->method_index = index;
6979 /* Nullify patches which need no aot processing */
6980 for (patch_info = cfg->patch_info; patch_info; patch_info = patch_info->next) {
6981 switch (patch_info->type) {
6982 case MONO_PATCH_INFO_LABEL:
6983 case MONO_PATCH_INFO_BB:
6984 patch_info->type = MONO_PATCH_INFO_NONE;
6991 /* Collect method->token associations from the cfg */
6992 mono_acfg_lock (acfg);
6993 g_hash_table_foreach (cfg->token_info_hash, add_token_info_hash, acfg);
6994 mono_acfg_unlock (acfg);
6995 g_hash_table_destroy (cfg->token_info_hash);
6996 cfg->token_info_hash = NULL;
6999 * Check for absolute addresses.
7002 for (patch_info = cfg->patch_info; patch_info; patch_info = patch_info->next) {
7003 switch (patch_info->type) {
7004 case MONO_PATCH_INFO_ABS:
7005 /* unable to handle this */
7014 if (acfg->aot_opts.print_skipped_methods)
7015 printf ("Skip (abs call): %s\n", mono_method_full_name (method, TRUE));
7016 InterlockedIncrement (&acfg->stats.abscount);
7017 mono_destroy_compile (cfg);
7021 /* Lock for the rest of the code */
7022 mono_acfg_lock (acfg);
7025 * Check for methods/klasses we can't encode.
7028 for (patch_info = cfg->patch_info; patch_info; patch_info = patch_info->next) {
7029 if (!can_encode_patch (acfg, patch_info))
7034 if (acfg->aot_opts.print_skipped_methods)
7035 printf ("Skip (patches): %s\n", mono_method_full_name (method, TRUE));
7036 acfg->stats.ocount++;
7037 mono_destroy_compile (cfg);
7038 mono_acfg_unlock (acfg);
7042 if (!cfg->compile_llvm)
7043 acfg->has_jitted_code = TRUE;
7045 if (method->is_inflated && acfg->aot_opts.log_instances) {
7046 if (acfg->instances_logfile)
7047 fprintf (acfg->instances_logfile, "%s ### %d\n", mono_method_full_name (method, TRUE), cfg->code_size);
7049 printf ("%s ### %d\n", mono_method_full_name (method, TRUE), cfg->code_size);
7052 /* Adds generic instances referenced by this method */
7054 * The depth is used to avoid infinite loops when generic virtual recursion is
7057 depth = GPOINTER_TO_UINT (g_hash_table_lookup (acfg->method_depth, method));
7058 if (!acfg->aot_opts.no_instances && depth < 32) {
7059 for (patch_info = cfg->patch_info; patch_info; patch_info = patch_info->next) {
7060 switch (patch_info->type) {
7061 case MONO_PATCH_INFO_RGCTX_FETCH:
7062 case MONO_PATCH_INFO_RGCTX_SLOT_INDEX:
7063 case MONO_PATCH_INFO_METHOD: {
7064 MonoMethod *m = NULL;
7066 if (patch_info->type == MONO_PATCH_INFO_RGCTX_FETCH || patch_info->type == MONO_PATCH_INFO_RGCTX_SLOT_INDEX) {
7067 MonoJumpInfoRgctxEntry *e = patch_info->data.rgctx_entry;
7069 if (e->info_type == MONO_RGCTX_INFO_GENERIC_METHOD_CODE)
7070 m = e->data->data.method;
7072 m = patch_info->data.method;
7077 if (m->is_inflated) {
7078 if (!(mono_class_generic_sharing_enabled (m->klass) &&
7079 mono_method_is_generic_sharable_full (m, FALSE, FALSE, FALSE)) &&
7080 (!method_has_type_vars (m) || mono_method_is_generic_sharable_full (m, TRUE, TRUE, FALSE))) {
7081 if (m->iflags & METHOD_IMPL_ATTRIBUTE_INTERNAL_CALL) {
7082 if (mono_aot_mode_is_full (&acfg->aot_opts) && !method_has_type_vars (m))
7083 add_extra_method_with_depth (acfg, mono_marshal_get_native_wrapper (m, TRUE, TRUE), depth + 1);
7085 add_extra_method_with_depth (acfg, m, depth + 1);
7086 add_types_from_method_header (acfg, m);
7089 add_generic_class_with_depth (acfg, m->klass, depth + 5, "method");
7091 if (m->wrapper_type == MONO_WRAPPER_MANAGED_TO_MANAGED) {
7092 WrapperInfo *info = mono_marshal_get_wrapper_info (m);
7094 if (info && info->subtype == WRAPPER_SUBTYPE_ELEMENT_ADDR)
7095 add_extra_method_with_depth (acfg, m, depth + 1);
7099 case MONO_PATCH_INFO_VTABLE: {
7100 MonoClass *klass = patch_info->data.klass;
7102 if (klass->generic_class && !mini_class_is_generic_sharable (klass))
7103 add_generic_class_with_depth (acfg, klass, depth + 5, "vtable");
7106 case MONO_PATCH_INFO_SFLDA: {
7107 MonoClass *klass = patch_info->data.field->parent;
7109 /* The .cctor needs to run at runtime. */
7110 if (klass->generic_class && !mono_generic_context_is_sharable (&klass->generic_class->context, FALSE) && mono_class_get_cctor (klass))
7111 add_extra_method_with_depth (acfg, mono_class_get_cctor (klass), depth + 1);
7120 /* Determine whenever the method has GOT slots */
7121 for (patch_info = cfg->patch_info; patch_info; patch_info = patch_info->next) {
7122 switch (patch_info->type) {
7123 case MONO_PATCH_INFO_GOT_OFFSET:
7124 case MONO_PATCH_INFO_NONE:
7125 case MONO_PATCH_INFO_GC_CARD_TABLE_ADDR:
7126 case MONO_PATCH_INFO_GC_NURSERY_START:
7127 case MONO_PATCH_INFO_GC_NURSERY_BITS:
7129 case MONO_PATCH_INFO_IMAGE:
7130 /* The assembly is stored in GOT slot 0 */
7131 if (patch_info->data.image != acfg->image)
7132 cfg->has_got_slots = TRUE;
7135 if (!is_plt_patch (patch_info) || (cfg->compile_llvm && acfg->aot_opts.llvm_only))
7136 cfg->has_got_slots = TRUE;
7141 if (!cfg->has_got_slots)
7142 InterlockedIncrement (&acfg->stats.methods_without_got_slots);
7144 if (!cfg->method->wrapper_type)
7145 cfg->signatures = g_slist_prepend_mempool (cfg->mempool, cfg->signatures, mono_method_signature (cfg->method));
7147 /* Add gsharedvt wrappers for signatures used by the method */
7148 if (acfg->aot_opts.llvm_only && (acfg->opts & MONO_OPT_GSHAREDVT)) {
7151 for (l = cfg->signatures; l; l = l->next) {
7152 MonoMethodSignature *sig = mono_metadata_signature_dup ((MonoMethodSignature*)l->data);
7154 if (!g_hash_table_lookup (acfg->signatures, sig) && !mini_is_gsharedvt_variable_signature (sig)) {
7155 g_hash_table_insert (acfg->signatures, sig, sig);
7156 if (!sig->has_type_parameters) {
7157 MonoMethod *wrapper;
7159 //printf ("%s\n", mono_signature_full_name (sig));
7161 wrapper = mini_get_gsharedvt_in_sig_wrapper (sig);
7162 add_extra_method (acfg, wrapper);
7163 wrapper = mini_get_gsharedvt_out_sig_wrapper (sig);
7164 add_extra_method (acfg, wrapper);
7166 /* For signatures creared during generic sharing, convert them to a concrete signature if possible */
7167 MonoMethodSignature *copy = mono_metadata_signature_dup (sig);
7169 gboolean concrete = TRUE;
7171 //printf ("%s\n", mono_signature_full_name (sig));
7173 copy->ret = mini_get_underlying_type (sig->ret);
7174 // FIXME: Add more cases
7175 if (copy->ret->type == MONO_TYPE_VAR || copy->ret->type == MONO_TYPE_MVAR || copy->ret->type == MONO_TYPE_GENERICINST)
7177 for (i = 0; i < sig->param_count; ++i) {
7178 copy->params [i] = mini_get_underlying_type (sig->params [i]);
7179 if (copy->params [i]->type == MONO_TYPE_VAR || copy->params [i]->type == MONO_TYPE_MVAR || copy->params [i]->type == MONO_TYPE_GENERICINST)
7183 copy->has_type_parameters = 0;
7185 if (!g_hash_table_lookup (acfg->signatures, sig)) {
7186 g_hash_table_insert (acfg->signatures, sig, sig);
7187 MonoMethod *wrapper = mini_get_gsharedvt_in_sig_wrapper (sig);
7188 add_extra_method (acfg, wrapper);
7190 //printf ("%s\n", mono_method_full_name (wrapper, 1));
7199 * FIXME: Instead of this mess, allocate the patches from the aot mempool.
7201 /* Make a copy of the patch info which is in the mempool */
7203 MonoJumpInfo *patches = NULL, *patches_end = NULL;
7205 for (patch_info = cfg->patch_info; patch_info; patch_info = patch_info->next) {
7206 MonoJumpInfo *new_patch_info = mono_patch_info_dup_mp (acfg->mempool, patch_info);
7209 patches = new_patch_info;
7211 patches_end->next = new_patch_info;
7212 patches_end = new_patch_info;
7214 cfg->patch_info = patches;
7216 /* Make a copy of the unwind info */
7218 GSList *l, *unwind_ops;
7222 for (l = cfg->unwind_ops; l; l = l->next) {
7223 op = (MonoUnwindOp *)mono_mempool_alloc (acfg->mempool, sizeof (MonoUnwindOp));
7224 memcpy (op, l->data, sizeof (MonoUnwindOp));
7225 unwind_ops = g_slist_prepend_mempool (acfg->mempool, unwind_ops, op);
7227 cfg->unwind_ops = g_slist_reverse (unwind_ops);
7229 /* Make a copy of the argument/local info */
7231 MonoInst **args, **locals;
7232 MonoMethodSignature *sig;
7233 MonoMethodHeader *header;
7236 sig = mono_method_signature (method);
7237 args = (MonoInst **)mono_mempool_alloc (acfg->mempool, sizeof (MonoInst*) * (sig->param_count + sig->hasthis));
7238 for (i = 0; i < sig->param_count + sig->hasthis; ++i) {
7239 args [i] = (MonoInst *)mono_mempool_alloc (acfg->mempool, sizeof (MonoInst));
7240 memcpy (args [i], cfg->args [i], sizeof (MonoInst));
7244 header = mono_method_get_header (method);
7245 locals = (MonoInst **)mono_mempool_alloc (acfg->mempool, sizeof (MonoInst*) * header->num_locals);
7246 for (i = 0; i < header->num_locals; ++i) {
7247 locals [i] = (MonoInst *)mono_mempool_alloc (acfg->mempool, sizeof (MonoInst));
7248 memcpy (locals [i], cfg->locals [i], sizeof (MonoInst));
7250 cfg->locals = locals;
7253 /* Free some fields used by cfg to conserve memory */
7254 mono_mempool_destroy (cfg->mempool);
7255 cfg->mempool = NULL;
7256 g_free (cfg->varinfo);
7257 cfg->varinfo = NULL;
7261 mono_regstate_free (cfg->rs);
7265 //printf ("Compile: %s\n", mono_method_full_name (method, TRUE));
7267 while (index >= acfg->cfgs_size) {
7268 MonoCompile **new_cfgs;
7271 new_size = acfg->cfgs_size * 2;
7272 new_cfgs = g_new0 (MonoCompile*, new_size);
7273 memcpy (new_cfgs, acfg->cfgs, sizeof (MonoCompile*) * acfg->cfgs_size);
7274 g_free (acfg->cfgs);
7275 acfg->cfgs = new_cfgs;
7276 acfg->cfgs_size = new_size;
7278 acfg->cfgs [index] = cfg;
7280 g_hash_table_insert (acfg->method_to_cfg, cfg->orig_method, cfg);
7283 if (cfg->orig_method->wrapper_type)
7284 g_ptr_array_add (acfg->extra_methods, cfg->orig_method);
7287 mono_acfg_unlock (acfg);
7289 InterlockedIncrement (&acfg->stats.ccount);
7293 compile_thread_main (gpointer *user_data)
7295 MonoDomain *domain = (MonoDomain *)user_data [0];
7296 MonoAotCompile *acfg = (MonoAotCompile *)user_data [1];
7297 GPtrArray *methods = (GPtrArray *)user_data [2];
7300 mono_thread_attach (domain);
7302 for (i = 0; i < methods->len; ++i)
7303 compile_method (acfg, (MonoMethod *)g_ptr_array_index (methods, i));
7307 load_profile_files (MonoAotCompile *acfg)
7311 int file_index, res, method_index, i;
7314 GList *unordered, *l;
7319 tmp = g_strdup_printf ("%s/.mono/aot-profile-data/%s-%d", g_get_home_dir (), acfg->image->assembly_name, file_index);
7321 if (!g_file_test (tmp, G_FILE_TEST_IS_REGULAR)) {
7326 infile = fopen (tmp, "r");
7329 printf ("Using profile data file '%s'\n", tmp);
7334 res = fscanf (infile, "%32s\n", ver);
7335 if ((res != 1) || strcmp (ver, "#VER:2") != 0) {
7336 printf ("Profile file has wrong version or invalid.\n");
7343 MonoMethodDesc *desc;
7346 if (fgets (name, 1023, infile) == NULL)
7349 /* Kill the newline */
7350 if (strlen (name) > 0)
7351 name [strlen (name) - 1] = '\0';
7353 desc = mono_method_desc_new (name, TRUE);
7355 method = mono_method_desc_search_in_image (desc, acfg->image);
7357 if (method && mono_method_get_token (method)) {
7358 token = mono_method_get_token (method);
7359 method_index = mono_metadata_token_index (token) - 1;
7362 for (i = 0; i < acfg->method_order->len; ++i) {
7363 if (g_ptr_array_index (acfg->method_order, i) == GUINT_TO_POINTER (method_index)) {
7369 g_ptr_array_add (acfg->method_order, GUINT_TO_POINTER (method_index));
7371 //printf ("No method found matching '%s'.\n", name);
7377 /* Add missing methods */
7379 for (method_index = 0; method_index < acfg->image->tables [MONO_TABLE_METHOD].rows; ++method_index) {
7381 for (i = 0; i < acfg->method_order->len; ++i) {
7382 if (g_ptr_array_index (acfg->method_order, i) == GUINT_TO_POINTER (method_index)) {
7388 unordered = g_list_prepend (unordered, GUINT_TO_POINTER (method_index));
7390 unordered = g_list_reverse (unordered);
7391 for (l = unordered; l; l = l->next)
7392 g_ptr_array_add (acfg->method_order, l->data);
7395 /* Used by the LLVM backend */
7397 mono_aot_get_got_offset (MonoJumpInfo *ji)
7399 return get_got_offset (llvm_acfg, TRUE, ji);
7403 * mono_aot_is_shared_got_offset:
7405 * Return whenever OFFSET refers to a GOT slot which is preinitialized
7406 * when the AOT image is loaded.
7409 mono_aot_is_shared_got_offset (int offset)
7411 return offset < llvm_acfg->nshared_got_entries;
7415 mono_aot_get_method_name (MonoCompile *cfg)
7417 if (llvm_acfg->aot_opts.static_link)
7418 /* Include the assembly name too to avoid duplicate symbol errors */
7419 return g_strdup_printf ("%s_%s", llvm_acfg->assembly_name_sym, get_debug_sym (cfg->orig_method, "", llvm_acfg->method_label_hash));
7421 return get_debug_sym (cfg->orig_method, "", llvm_acfg->method_label_hash);
7425 mono_aot_is_direct_callable (MonoJumpInfo *patch_info)
7427 return is_direct_callable (llvm_acfg, NULL, patch_info);
7431 mono_aot_mark_unused_llvm_plt_entry (MonoJumpInfo *patch_info)
7433 MonoPltEntry *plt_entry;
7435 plt_entry = get_plt_entry (llvm_acfg, patch_info);
7436 plt_entry->llvm_used = FALSE;
7440 mono_aot_get_direct_call_symbol (MonoJumpInfoType type, gconstpointer data)
7442 const char *sym = NULL;
7444 if (llvm_acfg->aot_opts.direct_icalls) {
7445 if (type == MONO_PATCH_INFO_JIT_ICALL_ADDR) {
7446 /* Call to a C function implementing a jit icall */
7447 sym = mono_lookup_jit_icall_symbol ((const char *)data);
7448 } else if (type == MONO_PATCH_INFO_ICALL_ADDR) {
7449 MonoMethod *method = (MonoMethod *)data;
7450 if (!(method->flags & METHOD_ATTRIBUTE_PINVOKE_IMPL))
7451 sym = mono_lookup_icall_symbol (method);
7454 return g_strdup (sym);
7460 mono_aot_get_plt_symbol (MonoJumpInfoType type, gconstpointer data)
7462 MonoJumpInfo *ji = (MonoJumpInfo *)mono_mempool_alloc (llvm_acfg->mempool, sizeof (MonoJumpInfo));
7463 MonoPltEntry *plt_entry;
7464 const char *sym = NULL;
7467 ji->data.target = data;
7469 if (!can_encode_patch (llvm_acfg, ji))
7472 if (llvm_acfg->aot_opts.direct_icalls) {
7473 if (type == MONO_PATCH_INFO_JIT_ICALL_ADDR) {
7474 /* Call to a C function implementing a jit icall */
7475 sym = mono_lookup_jit_icall_symbol ((const char *)data);
7476 } else if (type == MONO_PATCH_INFO_ICALL_ADDR) {
7477 MonoMethod *method = (MonoMethod *)data;
7478 if (!(method->flags & METHOD_ATTRIBUTE_PINVOKE_IMPL))
7479 sym = mono_lookup_icall_symbol (method);
7482 return g_strdup (sym);
7485 plt_entry = get_plt_entry (llvm_acfg, ji);
7486 plt_entry->llvm_used = TRUE;
7488 #if defined(TARGET_MACH)
7489 return g_strdup_printf (plt_entry->llvm_symbol + strlen (llvm_acfg->llvm_label_prefix));
7491 return g_strdup_printf (plt_entry->llvm_symbol);
7496 mono_aot_get_method_index (MonoMethod *method)
7498 g_assert (llvm_acfg);
7499 return get_method_index (llvm_acfg, method);
7503 mono_aot_patch_info_dup (MonoJumpInfo* ji)
7507 mono_acfg_lock (llvm_acfg);
7508 res = mono_patch_info_dup_mp (llvm_acfg->mempool, ji);
7509 mono_acfg_unlock (llvm_acfg);
7515 execute_system (const char * command)
7520 // We need an extra set of quotes around the whole command to properly handle commands
7521 // with spaces since internally the command is called through "cmd /c.
7522 command = g_strdup_printf ("\"%s\"", command);
7524 int size = MultiByteToWideChar (CP_UTF8, 0 , command , -1, NULL , 0);
7525 wchar_t* wstr = g_malloc (sizeof (wchar_t) * size);
7526 MultiByteToWideChar (CP_UTF8, 0, command, -1, wstr , size);
7527 status = _wsystem (wstr);
7531 #elif defined (HAVE_SYSTEM)
7532 status = system (command);
7534 g_assert_not_reached ();
7545 * Emit the LLVM code into an LLVM bytecode file, and compile it using the LLVM
7549 emit_llvm_file (MonoAotCompile *acfg)
7551 char *command, *opts, *tempbc, *output_fname;
7553 /* Emit the LLVM code into a .bc file */
7554 if (acfg->aot_opts.llvm_only && acfg->aot_opts.asm_only) {
7555 mono_llvm_emit_aot_module (acfg->aot_opts.llvm_outfile, g_path_get_basename (acfg->image->name));
7559 tempbc = g_strdup_printf ("%s.bc", acfg->tmpbasename);
7560 mono_llvm_emit_aot_module (tempbc, g_path_get_basename (acfg->image->name));
7563 if (acfg->aot_opts.llvm_only) {
7564 /* Use the stock clang from xcode */
7567 // FIXME: llc/opt flags
7568 command = g_strdup_printf ("clang -march=x86-64 -fpic -msse -msse2 -msse3 -msse4 -O0 -c -o \"%s\" \"%s.bc\"", acfg->llvm_ofile, acfg->tmpbasename);
7569 //command = g_strdup_printf ("/Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/bin/clang -isysroot /Applications/Xcode.app/Contents/Developer/Platforms/iPhoneOS.platform/Developer/SDKs/iPhoneOS8.3.sdk -Qunused-arguments -miphoneos-version-min=8.2 -arch arm64 -fpic -O0 -c -o \"%s\" \"%s.bc\"", acfg->llvm_ofile, acfg->tmpbasename);
7571 aot_printf (acfg, "Executing clang: %s\n", command);
7572 if (execute_system (command) != 0)
7578 * FIXME: Experiment with adding optimizations, the -std-compile-opts set takes
7579 * a lot of time, and doesn't seem to save much space.
7580 * The following optimizations cannot be enabled:
7582 * - 'jump-threading' changes our blockaddress references to int constants.
7583 * - 'basiccg' fails because it contains:
7584 * if (CS && !isa<IntrinsicInst>(II)) {
7585 * and isa<IntrinsicInst> is false for invokes to intrinsics (iltests.exe).
7586 * - 'prune-eh' and 'functionattrs' depend on 'basiccg'.
7587 * The opt list below was produced by taking the output of:
7588 * llvm-as < /dev/null | opt -O2 -disable-output -debug-pass=Arguments
7589 * then removing tailcallelim + the global opts.
7590 * strip-dead-prototypes deletes unused intrinsics definitions.
7592 //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");
7593 /* The dse pass is disabled because of #13734 and #17616 */
7595 * The dse bug is in DeadStoreElimination.cpp:isOverwrite ():
7596 * // If we have no DataLayout information around, then the size of the store
7597 * // is inferrable from the pointee type. If they are the same type, then
7598 * // we know that the store is safe.
7599 * if (AA.getDataLayout() == 0 &&
7600 * Later.Ptr->getType() == Earlier.Ptr->getType()) {
7601 * return OverwriteComplete;
7602 * Here, if 'Earlier' refers to a memset, and Later has no size info, it mistakenly thinks the memset is redundant.
7604 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");
7605 opts = g_strdup ("");
7607 command = g_strdup_printf ("\"%sopt\" -f %s -o \"%s.opt.bc\" \"%s.bc\"", acfg->aot_opts.llvm_path, opts, acfg->tmpbasename, acfg->tmpbasename);
7608 aot_printf (acfg, "Executing opt: %s\n", command);
7609 if (execute_system (command) != 0)
7614 if (!acfg->llc_args)
7615 acfg->llc_args = g_string_new ("");
7617 /* Verbose asm slows down llc greatly */
7618 g_string_append (acfg->llc_args, " -asm-verbose=false");
7620 if (acfg->aot_opts.mtriple)
7621 g_string_append_printf (acfg->llc_args, " -mtriple=%s", acfg->aot_opts.mtriple);
7623 g_string_append (acfg->llc_args, " -disable-gnu-eh-frame -enable-mono-eh-frame");
7625 g_string_append_printf (acfg->llc_args, " -mono-eh-frame-symbol=%s%s", acfg->user_symbol_prefix, acfg->llvm_eh_frame_symbol);
7627 #if defined(TARGET_MACH) && defined(TARGET_ARM)
7628 /* ios requires PIC code now */
7629 g_string_append_printf (acfg->llc_args, " -relocation-model=pic");
7631 if (llvm_acfg->aot_opts.static_link)
7632 g_string_append_printf (acfg->llc_args, " -relocation-model=static");
7634 g_string_append_printf (acfg->llc_args, " -relocation-model=pic");
7637 if (acfg->llvm_owriter) {
7638 /* Emit an object file directly */
7639 output_fname = g_strdup_printf ("%s", acfg->llvm_ofile);
7640 g_string_append_printf (acfg->llc_args, " -filetype=obj");
7642 output_fname = g_strdup_printf ("%s", acfg->llvm_sfile);
7644 command = g_strdup_printf ("\"%sllc\" %s -o \"%s\" \"%s.opt.bc\"", acfg->aot_opts.llvm_path, acfg->llc_args->str, output_fname, acfg->tmpbasename);
7645 g_free (output_fname);
7647 aot_printf (acfg, "Executing llc: %s\n", command);
7649 if (execute_system (command) != 0)
7656 emit_code (MonoAotCompile *acfg)
7658 int oindex, i, prev_index;
7659 gboolean saved_unbox_info = FALSE;
7662 if (acfg->aot_opts.llvm_only)
7665 #if defined(TARGET_POWERPC64)
7666 sprintf (symbol, ".Lgot_addr");
7667 emit_section_change (acfg, ".text", 0);
7668 emit_alignment (acfg, 8);
7669 emit_label (acfg, symbol);
7670 emit_pointer (acfg, acfg->got_symbol);
7674 * This global symbol is used to compute the address of each method using the
7675 * code_offsets array. It is also used to compute the memory ranges occupied by
7676 * AOT code, so it must be equal to the address of the first emitted method.
7678 emit_section_change (acfg, ".text", 0);
7679 emit_alignment_code (acfg, 8);
7680 emit_info_symbol (acfg, "jit_code_start");
7683 * Emit some padding so the local symbol for the first method doesn't have the
7684 * same address as 'methods'.
7686 #if defined(__default_codegen__)
7687 emit_padding (acfg, 16);
7688 #elif defined(__native_client_codegen__)
7690 const int kPaddingSize = 16;
7691 guint8 pad_buffer[kPaddingSize];
7692 mono_arch_nacl_pad (pad_buffer, kPaddingSize);
7693 emit_bytes (acfg, pad_buffer, kPaddingSize);
7697 for (oindex = 0; oindex < acfg->method_order->len; ++oindex) {
7701 i = GPOINTER_TO_UINT (g_ptr_array_index (acfg->method_order, oindex));
7703 cfg = acfg->cfgs [i];
7708 method = cfg->orig_method;
7710 /* Emit unbox trampoline */
7711 if (mono_aot_mode_is_full (&acfg->aot_opts) && cfg->orig_method->klass->valuetype && !(acfg->aot_opts.llvm_only && cfg->compile_llvm)) {
7712 sprintf (symbol, "ut_%d", get_method_index (acfg, method));
7714 emit_section_change (acfg, ".text", 0);
7715 #ifdef __native_client_codegen__
7716 emit_alignment (acfg, AOT_FUNC_ALIGNMENT);
7719 if (acfg->thumb_mixed && cfg->compile_llvm) {
7720 emit_set_thumb_mode (acfg);
7721 fprintf (acfg->fp, "\n.thumb_func\n");
7724 emit_label (acfg, symbol);
7726 arch_emit_unbox_trampoline (acfg, cfg, cfg->orig_method, cfg->asm_symbol);
7728 if (acfg->thumb_mixed && cfg->compile_llvm)
7729 emit_set_arm_mode (acfg);
7731 if (!saved_unbox_info) {
7732 char user_symbol [128];
7734 sprintf (user_symbol, "%sunbox_trampoline_p", acfg->user_symbol_prefix);
7736 emit_label (acfg, "ut_end");
7738 unwind_ops = mono_unwind_get_cie_program ();
7739 save_unwind_info (acfg, user_symbol, unwind_ops);
7740 mono_free_unwind_info (unwind_ops);
7742 /* Save the unbox trampoline size */
7743 emit_symbol_diff (acfg, "ut_end", symbol, 0);
7745 saved_unbox_info = TRUE;
7749 if (cfg->compile_llvm)
7750 acfg->stats.llvm_count ++;
7752 emit_method_code (acfg, cfg);
7755 emit_section_change (acfg, ".text", 0);
7756 emit_alignment_code (acfg, 8);
7757 emit_info_symbol (acfg, "jit_code_end");
7759 /* To distinguish it from the next symbol */
7760 emit_padding (acfg, 4);
7763 * Add .no_dead_strip directives for all LLVM methods to prevent the OSX linker
7764 * from optimizing them away, since it doesn't see that code_offsets references them.
7765 * JITted methods don't need this since they are referenced using assembler local
7767 * FIXME: This is why write-symbols doesn't work on OSX ?
7769 if (acfg->llvm && acfg->need_no_dead_strip) {
7770 fprintf (acfg->fp, "\n");
7771 for (i = 0; i < acfg->nmethods; ++i) {
7772 if (acfg->cfgs [i] && acfg->cfgs [i]->compile_llvm)
7773 fprintf (acfg->fp, ".no_dead_strip %s\n", acfg->cfgs [i]->asm_symbol);
7778 * To work around linker issues, we emit a table of branches, and disassemble them at runtime.
7779 * This is PIE code, and the linker can update it if needed.
7781 sprintf (symbol, "method_addresses");
7782 emit_section_change (acfg, ".text", 1);
7783 emit_alignment_code (acfg, 8);
7784 emit_info_symbol (acfg, symbol);
7785 emit_local_symbol (acfg, symbol, "method_addresses_end", TRUE);
7786 emit_unset_mode (acfg);
7787 if (acfg->need_no_dead_strip)
7788 fprintf (acfg->fp, " .no_dead_strip %s\n", symbol);
7790 for (i = 0; i < acfg->nmethods; ++i) {
7791 #ifdef MONO_ARCH_AOT_SUPPORTED
7794 if (acfg->cfgs [i]) {
7795 if (acfg->aot_opts.llvm_only && acfg->cfgs [i]->compile_llvm)
7796 /* Obtained by calling a generated function in the LLVM image */
7797 arch_emit_direct_call (acfg, "method_addresses", FALSE, FALSE, NULL, &call_size);
7799 arch_emit_direct_call (acfg, acfg->cfgs [i]->asm_symbol, FALSE, acfg->thumb_mixed && acfg->cfgs [i]->compile_llvm, NULL, &call_size);
7801 arch_emit_direct_call (acfg, "method_addresses", FALSE, FALSE, NULL, &call_size);
7806 sprintf (symbol, "method_addresses_end");
7807 emit_label (acfg, symbol);
7810 /* Emit a sorted table mapping methods to the index of their unbox trampolines */
7811 sprintf (symbol, "unbox_trampolines");
7812 emit_section_change (acfg, RODATA_SECT, 0);
7813 emit_alignment (acfg, 8);
7814 emit_info_symbol (acfg, symbol);
7817 for (i = 0; i < acfg->nmethods; ++i) {
7822 cfg = acfg->cfgs [i];
7826 method = cfg->orig_method;
7828 if (mono_aot_mode_is_full (&acfg->aot_opts) && cfg->orig_method->klass->valuetype && !(acfg->aot_opts.llvm_only && cfg->compile_llvm)) {
7829 index = get_method_index (acfg, method);
7831 emit_int32 (acfg, index);
7832 /* Make sure the table is sorted by index */
7833 g_assert (index > prev_index);
7837 sprintf (symbol, "unbox_trampolines_end");
7838 emit_info_symbol (acfg, symbol);
7839 emit_int32 (acfg, 0);
7841 /* Emit a separate table with the trampoline addresses/offsets */
7842 sprintf (symbol, "unbox_trampoline_addresses");
7843 emit_section_change (acfg, ".text", 0);
7844 emit_alignment_code (acfg, 8);
7845 emit_info_symbol (acfg, symbol);
7847 for (i = 0; i < acfg->nmethods; ++i) {
7852 cfg = acfg->cfgs [i];
7856 method = cfg->orig_method;
7858 if (mono_aot_mode_is_full (&acfg->aot_opts) && cfg->orig_method->klass->valuetype && !(acfg->aot_opts.llvm_only && cfg->compile_llvm)) {
7859 #ifdef MONO_ARCH_AOT_SUPPORTED
7862 index = get_method_index (acfg, method);
7863 sprintf (symbol, "ut_%d", index);
7865 arch_emit_direct_call (acfg, symbol, FALSE, acfg->thumb_mixed && cfg->compile_llvm, NULL, &call_size);
7869 emit_int32 (acfg, 0);
7873 emit_info (MonoAotCompile *acfg)
7878 offsets = g_new0 (gint32, acfg->nmethods);
7880 for (oindex = 0; oindex < acfg->method_order->len; ++oindex) {
7881 i = GPOINTER_TO_UINT (g_ptr_array_index (acfg->method_order, oindex));
7883 if (acfg->cfgs [i]) {
7884 emit_method_info (acfg, acfg->cfgs [i]);
7885 offsets [i] = acfg->cfgs [i]->method_info_offset;
7891 acfg->stats.offsets_size += emit_offset_table (acfg, "method_info_offsets", acfg->nmethods, 10, offsets);
7896 #endif /* #if !defined(DISABLE_AOT) && !defined(DISABLE_JIT) */
7898 #define rot(x,k) (((x)<<(k)) | ((x)>>(32-(k))))
7899 #define mix(a,b,c) { \
7900 a -= c; a ^= rot(c, 4); c += b; \
7901 b -= a; b ^= rot(a, 6); a += c; \
7902 c -= b; c ^= rot(b, 8); b += a; \
7903 a -= c; a ^= rot(c,16); c += b; \
7904 b -= a; b ^= rot(a,19); a += c; \
7905 c -= b; c ^= rot(b, 4); b += a; \
7907 #define final(a,b,c) { \
7908 c ^= b; c -= rot(b,14); \
7909 a ^= c; a -= rot(c,11); \
7910 b ^= a; b -= rot(a,25); \
7911 c ^= b; c -= rot(b,16); \
7912 a ^= c; a -= rot(c,4); \
7913 b ^= a; b -= rot(a,14); \
7914 c ^= b; c -= rot(b,24); \
7918 mono_aot_type_hash (MonoType *t1)
7920 guint hash = t1->type;
7922 hash |= t1->byref << 6; /* do not collide with t1->type values */
7924 case MONO_TYPE_VALUETYPE:
7925 case MONO_TYPE_CLASS:
7926 case MONO_TYPE_SZARRAY:
7927 /* check if the distribution is good enough */
7928 return ((hash << 5) - hash) ^ mono_metadata_str_hash (t1->data.klass->name);
7930 return ((hash << 5) - hash) ^ mono_metadata_type_hash (t1->data.type);
7931 case MONO_TYPE_ARRAY:
7932 return ((hash << 5) - hash) ^ mono_metadata_type_hash (&t1->data.array->eklass->byval_arg);
7933 case MONO_TYPE_GENERICINST:
7934 return ((hash << 5) - hash) ^ 0;
7941 * mono_aot_method_hash:
7943 * Return a hash code for methods which only depends on metadata.
7946 mono_aot_method_hash (MonoMethod *method)
7948 MonoMethodSignature *sig;
7952 guint32 *hashes_start, *hashes;
7954 MonoGenericInst *class_ginst = NULL;
7955 MonoGenericInst *ginst = NULL;
7957 /* Similar to the hash in mono_method_get_imt_slot () */
7959 sig = mono_method_signature (method);
7961 if (method->klass->generic_class)
7962 class_ginst = method->klass->generic_class->context.class_inst;
7963 if (method->is_inflated)
7964 ginst = ((MonoMethodInflated*)method)->context.method_inst;
7966 hashes_count = sig->param_count + 5 + (class_ginst ? class_ginst->type_argc : 0) + (ginst ? ginst->type_argc : 0);
7967 hashes_start = (guint32 *)g_malloc0 (hashes_count * sizeof (guint32));
7968 hashes = hashes_start;
7970 /* Some wrappers are assigned to random classes */
7971 if (!method->wrapper_type || method->wrapper_type == MONO_WRAPPER_REMOTING_INVOKE_WITH_CHECK)
7972 klass = method->klass;
7974 klass = mono_defaults.object_class;
7976 if (!method->wrapper_type) {
7979 if (klass->generic_class)
7980 full_name = mono_type_full_name (&klass->generic_class->container_class->byval_arg);
7982 full_name = mono_type_full_name (&klass->byval_arg);
7984 hashes [0] = mono_metadata_str_hash (full_name);
7988 hashes [0] = mono_metadata_str_hash (klass->name);
7989 hashes [1] = mono_metadata_str_hash (klass->name_space);
7991 if (method->wrapper_type == MONO_WRAPPER_STFLD || method->wrapper_type == MONO_WRAPPER_LDFLD || method->wrapper_type == MONO_WRAPPER_LDFLDA)
7992 /* The method name includes a stringified pointer */
7995 hashes [2] = mono_metadata_str_hash (method->name);
7996 hashes [3] = method->wrapper_type;
7997 hashes [4] = mono_aot_type_hash (sig->ret);
7999 for (i = 0; i < sig->param_count; i++) {
8000 hashes [hindex ++] = mono_aot_type_hash (sig->params [i]);
8003 for (i = 0; i < class_ginst->type_argc; ++i)
8004 hashes [hindex ++] = mono_aot_type_hash (class_ginst->type_argv [i]);
8007 for (i = 0; i < ginst->type_argc; ++i)
8008 hashes [hindex ++] = mono_aot_type_hash (ginst->type_argv [i]);
8010 g_assert (hindex == hashes_count);
8012 /* Setup internal state */
8013 a = b = c = 0xdeadbeef + (((guint32)hashes_count)<<2);
8015 /* Handle most of the hashes */
8016 while (hashes_count > 3) {
8025 /* Handle the last 3 hashes (all the case statements fall through) */
8026 switch (hashes_count) {
8027 case 3 : c += hashes [2];
8028 case 2 : b += hashes [1];
8029 case 1 : a += hashes [0];
8031 case 0: /* nothing left to add */
8035 free (hashes_start);
8044 * mono_aot_get_array_helper_from_wrapper;
8046 * Get the helper method in Array called by an array wrapper method.
8049 mono_aot_get_array_helper_from_wrapper (MonoMethod *method)
8053 MonoGenericContext ctx;
8054 MonoType *args [16];
8055 char *mname, *iname, *s, *s2, *helper_name = NULL;
8057 prefix = "System.Collections.Generic";
8058 s = g_strdup_printf ("%s", method->name + strlen (prefix) + 1);
8059 s2 = strstr (s, "`1.");
8065 //printf ("X: %s %s\n", iname, mname);
8067 if (!strcmp (iname, "IList"))
8068 helper_name = g_strdup_printf ("InternalArray__%s", mname);
8070 helper_name = g_strdup_printf ("InternalArray__%s_%s", iname, mname);
8071 m = mono_class_get_method_from_name (mono_defaults.array_class, helper_name, mono_method_signature (method)->param_count);
8073 g_free (helper_name);
8076 if (m->is_generic) {
8078 memset (&ctx, 0, sizeof (ctx));
8079 args [0] = &method->klass->element_class->byval_arg;
8080 ctx.method_inst = mono_metadata_get_generic_inst (1, args);
8081 m = mono_class_inflate_generic_method_checked (m, &ctx, &error);
8082 g_assert (mono_error_ok (&error)); /* FIXME don't swallow the error */
8088 #if !defined(DISABLE_AOT) && !defined(DISABLE_JIT)
8090 typedef struct HashEntry {
8091 guint32 key, value, index;
8092 struct HashEntry *next;
8096 * emit_extra_methods:
8098 * Emit methods which are not in the METHOD table, like wrappers.
8101 emit_extra_methods (MonoAotCompile *acfg)
8103 int i, table_size, buf_size;
8106 guint32 *info_offsets;
8109 HashEntry *entry, *new_entry;
8110 int nmethods, max_chain_length;
8113 info_offsets = g_new0 (guint32, acfg->extra_methods->len);
8115 /* Emit method info */
8117 for (i = 0; i < acfg->extra_methods->len; ++i) {
8118 MonoMethod *method = (MonoMethod *)g_ptr_array_index (acfg->extra_methods, i);
8119 MonoCompile *cfg = (MonoCompile *)g_hash_table_lookup (acfg->method_to_cfg, method);
8125 p = buf = (guint8 *)g_malloc (buf_size);
8129 method = cfg->method_to_register;
8131 encode_method_ref (acfg, method, p, &p);
8133 g_assert ((p - buf) < buf_size);
8135 info_offsets [i] = add_to_blob (acfg, buf, p - buf);
8140 * Construct a chained hash table for mapping indexes in extra_method_info to
8143 table_size = g_spaced_primes_closest ((int)(nmethods * 1.5));
8144 table = g_ptr_array_sized_new (table_size);
8145 for (i = 0; i < table_size; ++i)
8146 g_ptr_array_add (table, NULL);
8147 chain_lengths = g_new0 (int, table_size);
8148 max_chain_length = 0;
8149 for (i = 0; i < acfg->extra_methods->len; ++i) {
8150 MonoMethod *method = (MonoMethod *)g_ptr_array_index (acfg->extra_methods, i);
8151 MonoCompile *cfg = (MonoCompile *)g_hash_table_lookup (acfg->method_to_cfg, method);
8157 key = info_offsets [i];
8158 value = get_method_index (acfg, method);
8160 hash = mono_aot_method_hash (method) % table_size;
8161 //printf ("X: %s %x\n", mono_method_full_name (method, 1), mono_aot_method_hash (method));
8163 chain_lengths [hash] ++;
8164 max_chain_length = MAX (max_chain_length, chain_lengths [hash]);
8166 new_entry = (HashEntry *)mono_mempool_alloc0 (acfg->mempool, sizeof (HashEntry));
8167 new_entry->key = key;
8168 new_entry->value = value;
8170 entry = (HashEntry *)g_ptr_array_index (table, hash);
8171 if (entry == NULL) {
8172 new_entry->index = hash;
8173 g_ptr_array_index (table, hash) = new_entry;
8176 entry = entry->next;
8178 entry->next = new_entry;
8179 new_entry->index = table->len;
8180 g_ptr_array_add (table, new_entry);
8184 //printf ("MAX: %d\n", max_chain_length);
8186 buf_size = table->len * 12 + 4;
8187 p = buf = (guint8 *)g_malloc (buf_size);
8188 encode_int (table_size, p, &p);
8190 for (i = 0; i < table->len; ++i) {
8191 HashEntry *entry = (HashEntry *)g_ptr_array_index (table, i);
8193 if (entry == NULL) {
8194 encode_int (0, p, &p);
8195 encode_int (0, p, &p);
8196 encode_int (0, p, &p);
8198 //g_assert (entry->key > 0);
8199 encode_int (entry->key, p, &p);
8200 encode_int (entry->value, p, &p);
8202 encode_int (entry->next->index, p, &p);
8204 encode_int (0, p, &p);
8207 g_assert (p - buf <= buf_size);
8209 /* Emit the table */
8211 mono_llvm_emit_aot_data ("extra_method_table", buf, p - buf);
8213 sprintf (symbol, "extra_method_table");
8214 emit_section_change (acfg, RODATA_SECT, 0);
8215 emit_alignment (acfg, 8);
8216 emit_label (acfg, symbol);
8217 emit_bytes (acfg, buf, p - buf);
8221 * Emit a table reverse mapping method indexes to their index in extra_method_info.
8222 * This is used by mono_aot_find_jit_info ().
8224 buf_size = acfg->extra_methods->len * 8 + 4;
8225 p = buf = (guint8 *)g_malloc (buf_size);
8226 encode_int (acfg->extra_methods->len, p, &p);
8227 for (i = 0; i < acfg->extra_methods->len; ++i) {
8228 MonoMethod *method = (MonoMethod *)g_ptr_array_index (acfg->extra_methods, i);
8230 encode_int (get_method_index (acfg, method), p, &p);
8231 encode_int (info_offsets [i], p, &p);
8234 mono_llvm_emit_aot_data ("extra_method_info_offsets", buf, p - buf);
8236 sprintf (symbol, "extra_method_info_offsets");
8237 emit_section_change (acfg, RODATA_SECT, 0);
8238 emit_alignment (acfg, 8);
8239 emit_label (acfg, symbol);
8240 emit_bytes (acfg, buf, p - buf);
8245 emit_exception_info (MonoAotCompile *acfg)
8249 SeqPointData sp_data;
8250 gboolean seq_points_to_file = FALSE;
8252 offsets = g_new0 (gint32, acfg->nmethods);
8253 for (i = 0; i < acfg->nmethods; ++i) {
8254 if (acfg->cfgs [i]) {
8255 MonoCompile *cfg = acfg->cfgs [i];
8257 // By design aot-runtime decode_exception_debug_info is not able to load sequence point debug data from a file.
8258 // As it is not possible to load debug data from a file its is also not possible to store it in a file.
8259 gboolean method_seq_points_to_file = acfg->aot_opts.gen_seq_points_file &&
8260 cfg->gen_seq_points && !cfg->gen_sdb_seq_points;
8261 gboolean method_seq_points_to_binary = cfg->gen_seq_points && !method_seq_points_to_file;
8263 emit_exception_debug_info (acfg, cfg, method_seq_points_to_binary);
8264 offsets [i] = cfg->ex_info_offset;
8266 if (method_seq_points_to_file) {
8267 if (!seq_points_to_file) {
8268 mono_seq_point_data_init (&sp_data, acfg->nmethods);
8269 seq_points_to_file = TRUE;
8271 mono_seq_point_data_add (&sp_data, cfg->method->token, cfg->method_index, cfg->seq_point_info);
8278 if (seq_points_to_file) {
8279 char *seq_points_aot_file;
8280 mono_image_get_aot_seq_point_path (acfg->image, &seq_points_aot_file);
8281 mono_seq_point_data_write (&sp_data, seq_points_aot_file);
8282 mono_seq_point_data_free (&sp_data);
8283 g_free (seq_points_aot_file);
8286 acfg->stats.offsets_size += emit_offset_table (acfg, "ex_info_offsets", acfg->nmethods, 10, offsets);
8291 emit_unwind_info (MonoAotCompile *acfg)
8296 if (acfg->aot_opts.llvm_only) {
8297 g_assert (acfg->unwind_ops->len == 0);
8302 * The unwind info contains a lot of duplicates so we emit each unique
8303 * entry once, and only store the offset from the start of the table in the
8307 sprintf (symbol, "unwind_info");
8308 emit_section_change (acfg, RODATA_SECT, 1);
8309 emit_alignment (acfg, 8);
8310 emit_info_symbol (acfg, symbol);
8312 for (i = 0; i < acfg->unwind_ops->len; ++i) {
8313 guint32 index = GPOINTER_TO_UINT (g_ptr_array_index (acfg->unwind_ops, i));
8314 guint8 *unwind_info;
8315 guint32 unwind_info_len;
8319 unwind_info = mono_get_cached_unwind_info (index, &unwind_info_len);
8322 encode_value (unwind_info_len, p, &p);
8323 emit_bytes (acfg, buf, p - buf);
8324 emit_bytes (acfg, unwind_info, unwind_info_len);
8326 acfg->stats.unwind_info_size += (p - buf) + unwind_info_len;
8331 emit_class_info (MonoAotCompile *acfg)
8336 offsets = g_new0 (gint32, acfg->image->tables [MONO_TABLE_TYPEDEF].rows);
8337 for (i = 0; i < acfg->image->tables [MONO_TABLE_TYPEDEF].rows; ++i)
8338 offsets [i] = emit_klass_info (acfg, MONO_TOKEN_TYPE_DEF | (i + 1));
8340 acfg->stats.offsets_size += emit_offset_table (acfg, "class_info_offsets", acfg->image->tables [MONO_TABLE_TYPEDEF].rows, 10, offsets);
8344 typedef struct ClassNameTableEntry {
8345 guint32 token, index;
8346 struct ClassNameTableEntry *next;
8347 } ClassNameTableEntry;
8350 emit_class_name_table (MonoAotCompile *acfg)
8352 int i, table_size, buf_size;
8353 guint32 token, hash;
8359 ClassNameTableEntry *entry, *new_entry;
8362 * Construct a chained hash table for mapping class names to typedef tokens.
8364 table_size = g_spaced_primes_closest ((int)(acfg->image->tables [MONO_TABLE_TYPEDEF].rows * 1.5));
8365 table = g_ptr_array_sized_new (table_size);
8366 for (i = 0; i < table_size; ++i)
8367 g_ptr_array_add (table, NULL);
8368 for (i = 0; i < acfg->image->tables [MONO_TABLE_TYPEDEF].rows; ++i) {
8370 token = MONO_TOKEN_TYPE_DEF | (i + 1);
8371 klass = mono_class_get_checked (acfg->image, token, &error);
8373 mono_error_cleanup (&error);
8376 full_name = mono_type_get_name_full (mono_class_get_type (klass), MONO_TYPE_NAME_FORMAT_FULL_NAME);
8377 hash = mono_metadata_str_hash (full_name) % table_size;
8380 /* FIXME: Allocate from the mempool */
8381 new_entry = g_new0 (ClassNameTableEntry, 1);
8382 new_entry->token = token;
8384 entry = (ClassNameTableEntry *)g_ptr_array_index (table, hash);
8385 if (entry == NULL) {
8386 new_entry->index = hash;
8387 g_ptr_array_index (table, hash) = new_entry;
8390 entry = entry->next;
8392 entry->next = new_entry;
8393 new_entry->index = table->len;
8394 g_ptr_array_add (table, new_entry);
8398 /* Emit the table */
8399 buf_size = table->len * 4 + 4;
8400 p = buf = (guint8 *)g_malloc0 (buf_size);
8402 /* FIXME: Optimize memory usage */
8403 g_assert (table_size < 65000);
8404 encode_int16 (table_size, p, &p);
8405 g_assert (table->len < 65000);
8406 for (i = 0; i < table->len; ++i) {
8407 ClassNameTableEntry *entry = (ClassNameTableEntry *)g_ptr_array_index (table, i);
8409 if (entry == NULL) {
8410 encode_int16 (0, p, &p);
8411 encode_int16 (0, p, &p);
8413 encode_int16 (mono_metadata_token_index (entry->token), p, &p);
8415 encode_int16 (entry->next->index, p, &p);
8417 encode_int16 (0, p, &p);
8420 g_assert (p - buf <= buf_size);
8423 mono_llvm_emit_aot_data ("class_name_table", buf, p - buf);
8425 sprintf (symbol, "class_name_table");
8426 emit_section_change (acfg, RODATA_SECT, 0);
8427 emit_alignment (acfg, 8);
8428 emit_label (acfg, symbol);
8429 emit_bytes (acfg, buf, p - buf);
8434 emit_image_table (MonoAotCompile *acfg)
8441 * The image table is small but referenced in a lot of places.
8442 * So we emit it at once, and reference its elements by an index.
8444 buf_size = acfg->image_table->len * 28 + 4;
8445 for (i = 0; i < acfg->image_table->len; i++) {
8446 MonoImage *image = (MonoImage*)g_ptr_array_index (acfg->image_table, i);
8447 MonoAssemblyName *aname = &image->assembly->aname;
8449 buf_size += strlen (image->assembly_name) + strlen (image->guid) + (aname->culture ? strlen (aname->culture) : 1) + strlen ((char*)aname->public_key_token) + 4;
8452 buf = p = (guint8 *)g_malloc0 (buf_size);
8453 encode_int (acfg->image_table->len, p, &p);
8454 for (i = 0; i < acfg->image_table->len; i++) {
8455 MonoImage *image = (MonoImage*)g_ptr_array_index (acfg->image_table, i);
8456 MonoAssemblyName *aname = &image->assembly->aname;
8458 /* FIXME: Support multi-module assemblies */
8459 g_assert (image->assembly->image == image);
8461 encode_string (image->assembly_name, p, &p);
8462 encode_string (image->guid, p, &p);
8463 encode_string (aname->culture ? aname->culture : "", p, &p);
8464 encode_string ((const char*)aname->public_key_token, p, &p);
8466 while (GPOINTER_TO_UINT (p) % 8 != 0)
8469 encode_int (aname->flags, p, &p);
8470 encode_int (aname->major, p, &p);
8471 encode_int (aname->minor, p, &p);
8472 encode_int (aname->build, p, &p);
8473 encode_int (aname->revision, p, &p);
8475 g_assert (p - buf <= buf_size);
8478 mono_llvm_emit_aot_data ("image_table", buf, p - buf);
8480 sprintf (symbol, "image_table");
8481 emit_section_change (acfg, RODATA_SECT, 1);
8482 emit_alignment (acfg, 8);
8483 emit_label (acfg, symbol);
8484 emit_bytes (acfg, buf, p - buf);
8491 emit_got_info (MonoAotCompile *acfg, gboolean llvm)
8493 int i, first_plt_got_patch = 0, buf_size;
8495 guint32 *got_info_offsets;
8496 GotInfo *info = llvm ? &acfg->llvm_got_info : &acfg->got_info;
8498 /* Add the patches needed by the PLT to the GOT */
8500 acfg->plt_got_offset_base = acfg->got_offset;
8501 first_plt_got_patch = info->got_patches->len;
8502 for (i = 1; i < acfg->plt_offset; ++i) {
8503 MonoPltEntry *plt_entry = (MonoPltEntry *)g_hash_table_lookup (acfg->plt_offset_to_entry, GUINT_TO_POINTER (i));
8505 g_ptr_array_add (info->got_patches, plt_entry->ji);
8507 acfg->stats.got_slot_types [plt_entry->ji->type] ++;
8510 acfg->got_offset += acfg->plt_offset;
8515 * - optimize offsets table.
8516 * - reduce number of exported symbols.
8517 * - emit info for a klass only once.
8518 * - determine when a method uses a GOT slot which is guaranteed to be already
8520 * - clean up and document the code.
8521 * - use String.Empty in class libs.
8524 /* Encode info required to decode shared GOT entries */
8525 buf_size = info->got_patches->len * 128;
8526 p = buf = (guint8 *)mono_mempool_alloc (acfg->mempool, buf_size);
8527 got_info_offsets = (guint32 *)mono_mempool_alloc (acfg->mempool, info->got_patches->len * sizeof (guint32));
8529 acfg->plt_got_info_offsets = (guint32 *)mono_mempool_alloc (acfg->mempool, acfg->plt_offset * sizeof (guint32));
8531 if (acfg->plt_offset)
8532 acfg->plt_got_info_offsets [0] = 0;
8534 for (i = 0; i < info->got_patches->len; ++i) {
8535 MonoJumpInfo *ji = (MonoJumpInfo *)g_ptr_array_index (info->got_patches, i);
8540 encode_value (ji->type, p, &p);
8542 encode_patch (acfg, ji, p, &p);
8543 acfg->stats.got_slot_info_sizes [ji->type] += p - p2;
8544 g_assert (p - buf <= buf_size);
8545 got_info_offsets [i] = add_to_blob (acfg, buf, p - buf);
8547 if (!llvm && i >= first_plt_got_patch)
8548 acfg->plt_got_info_offsets [i - first_plt_got_patch + 1] = got_info_offsets [i];
8549 acfg->stats.got_info_size += p - buf;
8552 /* Emit got_info_offsets table */
8554 /* No need to emit offsets for the got plt entries, the plt embeds them directly */
8555 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);
8559 emit_got (MonoAotCompile *acfg)
8563 if (acfg->aot_opts.llvm_only)
8566 /* Don't make GOT global so accesses to it don't need relocations */
8567 sprintf (symbol, "%s", acfg->got_symbol);
8570 emit_unset_mode (acfg);
8571 fprintf (acfg->fp, ".section __DATA, __bss\n");
8572 emit_alignment (acfg, 8);
8574 emit_info_symbol (acfg, "jit_got");
8575 fprintf (acfg->fp, ".lcomm %s, %d\n", acfg->got_symbol, (int)(acfg->got_offset * sizeof (gpointer)));
8577 emit_section_change (acfg, ".bss", 0);
8578 emit_alignment (acfg, 8);
8579 emit_local_symbol (acfg, symbol, "got_end", FALSE);
8580 emit_label (acfg, symbol);
8582 emit_info_symbol (acfg, "jit_got");
8583 if (acfg->got_offset > 0)
8584 emit_zero_bytes (acfg, (int)(acfg->got_offset * sizeof (gpointer)));
8587 sprintf (symbol, "got_end");
8588 emit_label (acfg, symbol);
8591 typedef struct GlobalsTableEntry {
8592 guint32 value, index;
8593 struct GlobalsTableEntry *next;
8594 } GlobalsTableEntry;
8597 emit_globals (MonoAotCompile *acfg)
8603 GlobalsTableEntry *entry, *new_entry;
8605 if (!acfg->aot_opts.static_link)
8609 * When static linking, we emit a table containing our globals.
8613 * Construct a chained hash table for mapping global names to their index in
8614 * the globals table.
8616 table_size = g_spaced_primes_closest ((int)(acfg->globals->len * 1.5));
8617 table = g_ptr_array_sized_new (table_size);
8618 for (i = 0; i < table_size; ++i)
8619 g_ptr_array_add (table, NULL);
8620 for (i = 0; i < acfg->globals->len; ++i) {
8621 char *name = (char *)g_ptr_array_index (acfg->globals, i);
8623 hash = mono_metadata_str_hash (name) % table_size;
8625 /* FIXME: Allocate from the mempool */
8626 new_entry = g_new0 (GlobalsTableEntry, 1);
8627 new_entry->value = i;
8629 entry = (GlobalsTableEntry *)g_ptr_array_index (table, hash);
8630 if (entry == NULL) {
8631 new_entry->index = hash;
8632 g_ptr_array_index (table, hash) = new_entry;
8635 entry = entry->next;
8637 entry->next = new_entry;
8638 new_entry->index = table->len;
8639 g_ptr_array_add (table, new_entry);
8643 /* Emit the table */
8644 sprintf (symbol, ".Lglobals_hash");
8645 emit_section_change (acfg, RODATA_SECT, 0);
8646 emit_alignment (acfg, 8);
8647 emit_label (acfg, symbol);
8649 /* FIXME: Optimize memory usage */
8650 g_assert (table_size < 65000);
8651 emit_int16 (acfg, table_size);
8652 for (i = 0; i < table->len; ++i) {
8653 GlobalsTableEntry *entry = (GlobalsTableEntry *)g_ptr_array_index (table, i);
8655 if (entry == NULL) {
8656 emit_int16 (acfg, 0);
8657 emit_int16 (acfg, 0);
8659 emit_int16 (acfg, entry->value + 1);
8661 emit_int16 (acfg, entry->next->index);
8663 emit_int16 (acfg, 0);
8667 /* Emit the names */
8668 for (i = 0; i < acfg->globals->len; ++i) {
8669 char *name = (char *)g_ptr_array_index (acfg->globals, i);
8671 sprintf (symbol, "name_%d", i);
8672 emit_section_change (acfg, RODATA_SECT, 1);
8674 emit_alignment (acfg, 4);
8676 emit_label (acfg, symbol);
8677 emit_string (acfg, name);
8680 /* Emit the globals table */
8681 sprintf (symbol, "globals");
8682 emit_section_change (acfg, ".data", 0);
8683 /* This is not a global, since it is accessed by the init function */
8684 emit_alignment (acfg, 8);
8685 emit_info_symbol (acfg, symbol);
8687 sprintf (symbol, "%sglobals_hash", acfg->temp_prefix);
8688 emit_pointer (acfg, symbol);
8690 for (i = 0; i < acfg->globals->len; ++i) {
8691 char *name = (char *)g_ptr_array_index (acfg->globals, i);
8693 sprintf (symbol, "name_%d", i);
8694 emit_pointer (acfg, symbol);
8696 g_assert (strlen (name) < sizeof (symbol));
8697 sprintf (symbol, "%s", name);
8698 emit_pointer (acfg, symbol);
8700 /* Null terminate the table */
8701 emit_int32 (acfg, 0);
8702 emit_int32 (acfg, 0);
8706 emit_mem_end (MonoAotCompile *acfg)
8710 if (acfg->aot_opts.llvm_only)
8713 sprintf (symbol, "mem_end");
8714 emit_section_change (acfg, ".text", 1);
8715 emit_alignment_code (acfg, 8);
8716 emit_label (acfg, symbol);
8720 init_aot_file_info (MonoAotCompile *acfg, MonoAotFileInfo *info, int gc_name_offset)
8724 info->version = MONO_AOT_FILE_VERSION;
8725 info->plt_got_offset_base = acfg->plt_got_offset_base;
8726 info->got_size = acfg->got_offset * sizeof (gpointer);
8727 info->plt_size = acfg->plt_offset;
8728 info->nmethods = acfg->nmethods;
8729 info->flags = acfg->flags;
8730 info->opts = acfg->opts;
8731 info->simd_opts = acfg->simd_opts;
8732 info->gc_name_index = gc_name_offset;
8733 for (i = 0; i < MONO_AOT_TRAMP_NUM; ++i)
8734 info->num_trampolines [i] = acfg->num_trampolines [i];
8735 for (i = 0; i < MONO_AOT_TRAMP_NUM; ++i)
8736 info->trampoline_got_offset_base [i] = acfg->trampoline_got_offset_base [i];
8737 for (i = 0; i < MONO_AOT_TRAMP_NUM; ++i)
8738 info->trampoline_size [i] = acfg->trampoline_size [i];
8739 info->num_rgctx_fetch_trampolines = acfg->aot_opts.nrgctx_fetch_trampolines;
8741 info->double_align = MONO_ABI_ALIGNOF (double);
8742 info->long_align = MONO_ABI_ALIGNOF (gint64);
8743 info->generic_tramp_num = MONO_TRAMPOLINE_NUM;
8744 info->tramp_page_size = acfg->tramp_page_size;
8745 info->nshared_got_entries = acfg->nshared_got_entries;
8746 for (i = 0; i < MONO_AOT_TRAMP_NUM; ++i)
8747 info->tramp_page_code_offsets [i] = acfg->tramp_page_code_offsets [i];
8751 emit_aot_file_info (MonoAotCompile *acfg, MonoAotFileInfo *info)
8755 const char **symbols;
8757 symbols = g_new0 (const char *, MONO_AOT_FILE_INFO_NUM_SYMBOLS);
8759 symbols [sindex ++] = acfg->got_symbol;
8761 symbols [sindex ++] = g_strdup_printf ("%s%s", acfg->user_symbol_prefix, acfg->llvm_got_symbol);
8762 symbols [sindex ++] = acfg->llvm_eh_frame_symbol;
8764 symbols [sindex ++] = NULL;
8765 symbols [sindex ++] = NULL;
8767 /* llvm_get_method */
8768 symbols [sindex ++] = NULL;
8769 /* llvm_get_unbox_tramp */
8770 symbols [sindex ++] = NULL;
8771 if (!acfg->aot_opts.llvm_only) {
8772 symbols [sindex ++] = "jit_code_start";
8773 symbols [sindex ++] = "jit_code_end";
8774 symbols [sindex ++] = "method_addresses";
8776 symbols [sindex ++] = NULL;
8777 symbols [sindex ++] = NULL;
8778 symbols [sindex ++] = NULL;
8780 symbols [sindex ++] = "blob";
8781 symbols [sindex ++] = "class_name_table";
8782 symbols [sindex ++] = "class_info_offsets";
8783 symbols [sindex ++] = "method_info_offsets";
8784 symbols [sindex ++] = "ex_info_offsets";
8785 symbols [sindex ++] = "extra_method_info_offsets";
8786 symbols [sindex ++] = "extra_method_table";
8787 symbols [sindex ++] = "got_info_offsets";
8789 symbols [sindex ++] = "llvm_got_info_offsets";
8791 symbols [sindex ++] = NULL;
8792 symbols [sindex ++] = "mem_end";
8793 symbols [sindex ++] = "image_table";
8794 symbols [sindex ++] = "assembly_guid";
8795 symbols [sindex ++] = "runtime_version";
8796 if (acfg->num_trampoline_got_entries) {
8797 symbols [sindex ++] = "specific_trampolines";
8798 symbols [sindex ++] = "static_rgctx_trampolines";
8799 symbols [sindex ++] = "imt_thunks";
8800 symbols [sindex ++] = "gsharedvt_arg_trampolines";
8802 symbols [sindex ++] = NULL;
8803 symbols [sindex ++] = NULL;
8804 symbols [sindex ++] = NULL;
8805 symbols [sindex ++] = NULL;
8807 if (acfg->aot_opts.static_link) {
8808 symbols [sindex ++] = "globals";
8810 symbols [sindex ++] = NULL;
8812 symbols [sindex ++] = "assembly_name";
8813 symbols [sindex ++] = "plt";
8814 symbols [sindex ++] = "plt_end";
8815 symbols [sindex ++] = "unwind_info";
8816 if (!acfg->aot_opts.llvm_only) {
8817 symbols [sindex ++] = "unbox_trampolines";
8818 symbols [sindex ++] = "unbox_trampolines_end";
8819 symbols [sindex ++] = "unbox_trampoline_addresses";
8821 symbols [sindex ++] = NULL;
8822 symbols [sindex ++] = NULL;
8823 symbols [sindex ++] = NULL;
8826 g_assert (sindex == MONO_AOT_FILE_INFO_NUM_SYMBOLS);
8828 sprintf (symbol, "%smono_aot_file_info", acfg->user_symbol_prefix);
8829 emit_section_change (acfg, ".data", 0);
8830 emit_alignment (acfg, 8);
8831 emit_label (acfg, symbol);
8832 if (!acfg->aot_opts.static_link)
8833 emit_global (acfg, symbol, FALSE);
8835 /* The data emitted here must match MonoAotFileInfo. */
8837 emit_int32 (acfg, info->version);
8838 emit_int32 (acfg, info->dummy);
8841 * We emit pointers to our data structures instead of emitting global symbols which
8842 * point to them, to reduce the number of globals, and because using globals leads to
8843 * various problems (i.e. arm/thumb).
8845 for (i = 0; i < MONO_AOT_FILE_INFO_NUM_SYMBOLS; ++i)
8846 emit_pointer (acfg, symbols [i]);
8848 emit_int32 (acfg, info->plt_got_offset_base);
8849 emit_int32 (acfg, info->got_size);
8850 emit_int32 (acfg, info->plt_size);
8851 emit_int32 (acfg, info->nmethods);
8852 emit_int32 (acfg, info->flags);
8853 emit_int32 (acfg, info->opts);
8854 emit_int32 (acfg, info->simd_opts);
8855 emit_int32 (acfg, info->gc_name_index);
8856 emit_int32 (acfg, info->num_rgctx_fetch_trampolines);
8857 emit_int32 (acfg, info->double_align);
8858 emit_int32 (acfg, info->long_align);
8859 emit_int32 (acfg, info->generic_tramp_num);
8860 emit_int32 (acfg, info->tramp_page_size);
8861 emit_int32 (acfg, info->nshared_got_entries);
8863 for (i = 0; i < MONO_AOT_TRAMP_NUM; ++i)
8864 emit_int32 (acfg, info->num_trampolines [i]);
8865 for (i = 0; i < MONO_AOT_TRAMP_NUM; ++i)
8866 emit_int32 (acfg, info->trampoline_got_offset_base [i]);
8867 for (i = 0; i < MONO_AOT_TRAMP_NUM; ++i)
8868 emit_int32 (acfg, info->trampoline_size [i]);
8869 for (i = 0; i < MONO_AOT_TRAMP_NUM; ++i)
8870 emit_int32 (acfg, info->tramp_page_code_offsets [i]);
8872 if (acfg->aot_opts.static_link) {
8876 * Emit a global symbol which can be passed by an embedding app to
8877 * mono_aot_register_module (). The symbol points to a pointer to the the file info
8880 sprintf (symbol, "%smono_aot_module_%s_info", acfg->user_symbol_prefix, acfg->image->assembly->aname.name);
8882 /* Get rid of characters which cannot occur in symbols */
8884 for (p = symbol; *p; ++p) {
8885 if (!(isalnum (*p) || *p == '_'))
8888 acfg->static_linking_symbol = g_strdup (symbol);
8889 emit_global_inner (acfg, symbol, FALSE);
8890 emit_alignment (acfg, sizeof (gpointer));
8891 emit_label (acfg, symbol);
8892 emit_pointer_2 (acfg, acfg->user_symbol_prefix, "mono_aot_file_info");
8897 * Emit a structure containing all the information not stored elsewhere.
8900 emit_file_info (MonoAotCompile *acfg)
8903 const char *gc_name;
8905 MonoAotFileInfo *info;
8907 if (acfg->aot_opts.bind_to_runtime_version) {
8908 build_info = mono_get_runtime_build_info ();
8909 emit_string_symbol (acfg, "runtime_version", build_info);
8910 g_free (build_info);
8912 emit_string_symbol (acfg, "runtime_version", "");
8915 emit_string_symbol (acfg, "assembly_guid" , acfg->image->guid);
8917 /* Emit a string holding the assembly name */
8918 emit_string_symbol (acfg, "assembly_name", acfg->image->assembly->aname.name);
8921 * The managed allocators are GC specific, so can't use an AOT image created by one GC
8924 gc_name = mono_gc_get_gc_name ();
8925 gc_name_offset = add_to_blob (acfg, (guint8*)gc_name, strlen (gc_name) + 1);
8927 info = g_new0 (MonoAotFileInfo, 1);
8928 init_aot_file_info (acfg, info, gc_name_offset);
8931 mono_llvm_emit_aot_file_info (info, acfg->has_jitted_code);
8933 emit_aot_file_info (acfg, info);
8937 emit_blob (MonoAotCompile *acfg)
8942 mono_llvm_emit_aot_data ("blob", (guint8*)acfg->blob.data, acfg->blob.index);
8946 sprintf (symbol, "blob");
8947 emit_section_change (acfg, RODATA_SECT, 1);
8948 emit_alignment (acfg, 8);
8949 emit_label (acfg, symbol);
8951 emit_bytes (acfg, (guint8*)acfg->blob.data, acfg->blob.index);
8955 emit_objc_selectors (MonoAotCompile *acfg)
8960 if (!acfg->objc_selectors || acfg->objc_selectors->len == 0)
8965 * cat > foo.m << EOF
8968 * return @selector(print:);
8973 mono_img_writer_emit_unset_mode (acfg->w);
8974 g_assert (acfg->fp);
8975 fprintf (acfg->fp, ".section __DATA,__objc_selrefs,literal_pointers,no_dead_strip\n");
8976 fprintf (acfg->fp, ".align 3\n");
8977 for (i = 0; i < acfg->objc_selectors->len; ++i) {
8978 sprintf (symbol, "L_OBJC_SELECTOR_REFERENCES_%d", i);
8979 emit_label (acfg, symbol);
8980 sprintf (symbol, "L_OBJC_METH_VAR_NAME_%d", i);
8981 emit_pointer (acfg, symbol);
8984 fprintf (acfg->fp, ".section __TEXT,__cstring,cstring_literals\n");
8985 for (i = 0; i < acfg->objc_selectors->len; ++i) {
8986 fprintf (acfg->fp, "L_OBJC_METH_VAR_NAME_%d:\n", i);
8987 fprintf (acfg->fp, ".asciz \"%s\"\n", (char*)g_ptr_array_index (acfg->objc_selectors, i));
8990 fprintf (acfg->fp, ".section __DATA,__objc_imageinfo,regular,no_dead_strip\n");
8991 fprintf (acfg->fp, ".align 3\n");
8992 fprintf (acfg->fp, "L_OBJC_IMAGE_INFO:\n");
8993 fprintf (acfg->fp, ".long 0\n");
8994 fprintf (acfg->fp, ".long 16\n");
8998 emit_dwarf_info (MonoAotCompile *acfg)
9000 #ifdef EMIT_DWARF_INFO
9004 /* DIEs for methods */
9005 for (i = 0; i < acfg->nmethods; ++i) {
9006 MonoCompile *cfg = acfg->cfgs [i];
9011 // FIXME: LLVM doesn't define .Lme_...
9012 if (cfg->compile_llvm)
9015 sprintf (symbol2, "%sme_%x", acfg->temp_prefix, i);
9017 mono_dwarf_writer_emit_method (acfg->dwarf, cfg, cfg->method, cfg->asm_symbol, symbol2, cfg->asm_debug_symbol, (guint8 *)cfg->jit_info->code_start, cfg->jit_info->code_size, cfg->args, cfg->locals, cfg->unwind_ops, mono_debug_find_method (cfg->jit_info->d.method, mono_domain_get ()));
9023 collect_methods (MonoAotCompile *acfg)
9026 MonoImage *image = acfg->image;
9028 /* Collect methods */
9029 for (i = 0; i < image->tables [MONO_TABLE_METHOD].rows; ++i) {
9032 guint32 token = MONO_TOKEN_METHOD_DEF | (i + 1);
9034 method = mono_get_method_checked (acfg->image, token, NULL, NULL, &error);
9037 aot_printerrf (acfg, "Failed to load method 0x%x from '%s' due to %s.\n", token, image->name, mono_error_get_message (&error));
9038 aot_printerrf (acfg, "Run with MONO_LOG_LEVEL=debug for more information.\n");
9039 mono_error_cleanup (&error);
9043 /* Load all methods eagerly to skip the slower lazy loading code */
9044 mono_class_setup_methods (method->klass);
9046 if (mono_aot_mode_is_full (&acfg->aot_opts) && method->iflags & METHOD_IMPL_ATTRIBUTE_INTERNAL_CALL) {
9047 /* Compile the wrapper instead */
9048 /* We do this here instead of add_wrappers () because it is easy to do it here */
9049 MonoMethod *wrapper = mono_marshal_get_native_wrapper (method, TRUE, TRUE);
9053 /* FIXME: Some mscorlib methods don't have debug info */
9055 if (acfg->aot_opts.soft_debug && !method->wrapper_type) {
9056 if (!((method->flags & METHOD_ATTRIBUTE_PINVOKE_IMPL) ||
9057 (method->iflags & METHOD_IMPL_ATTRIBUTE_RUNTIME) ||
9058 (method->flags & METHOD_ATTRIBUTE_ABSTRACT) ||
9059 (method->iflags & METHOD_IMPL_ATTRIBUTE_INTERNAL_CALL))) {
9060 if (!mono_debug_lookup_method (method)) {
9061 fprintf (stderr, "Method %s has no debug info, probably the .mdb file for the assembly is missing.\n", mono_method_full_name (method, TRUE));
9068 if (method->is_generic || method->klass->generic_container)
9069 /* Compile the ref shared version instead */
9070 method = mini_get_shared_method (method);
9072 /* Since we add the normal methods first, their index will be equal to their zero based token index */
9073 add_method_with_index (acfg, method, i, FALSE);
9074 acfg->method_index ++;
9077 /* gsharedvt methods */
9078 for (mindex = 0; mindex < image->tables [MONO_TABLE_METHOD].rows; ++mindex) {
9081 guint32 token = MONO_TOKEN_METHOD_DEF | (mindex + 1);
9083 if (!(acfg->opts & MONO_OPT_GSHAREDVT))
9086 method = mono_get_method_checked (acfg->image, token, NULL, NULL, &error);
9087 report_loader_error (acfg, &error, "Failed to load method token 0x%x due to %s\n", i, mono_error_get_message (&error));
9089 if (method->is_generic || method->klass->generic_container) {
9090 MonoMethod *gshared;
9092 gshared = mini_get_shared_method_full (method, TRUE, TRUE);
9093 add_extra_method (acfg, gshared);
9097 add_generic_instances (acfg);
9099 if (mono_aot_mode_is_full (&acfg->aot_opts))
9100 add_wrappers (acfg);
9105 compile_methods (MonoAotCompile *acfg)
9109 if (acfg->aot_opts.nthreads > 0) {
9114 gpointer *user_data;
9115 MonoMethod **methods;
9117 methods_len = acfg->methods->len;
9119 len = acfg->methods->len / acfg->aot_opts.nthreads;
9122 * Partition the list of methods into fragments, and hand it to threads to
9125 threads = g_ptr_array_new ();
9126 /* Make a copy since acfg->methods is modified by compile_method () */
9127 methods = g_new0 (MonoMethod*, methods_len);
9128 //memcpy (methods, g_ptr_array_index (acfg->methods, 0), sizeof (MonoMethod*) * methods_len);
9129 for (i = 0; i < methods_len; ++i)
9130 methods [i] = (MonoMethod *)g_ptr_array_index (acfg->methods, i);
9132 while (i < methods_len) {
9133 frag = g_ptr_array_new ();
9134 for (j = 0; j < len; ++j) {
9135 if (i < methods_len) {
9136 g_ptr_array_add (frag, methods [i]);
9141 user_data = g_new0 (gpointer, 3);
9142 user_data [0] = mono_domain_get ();
9143 user_data [1] = acfg;
9144 user_data [2] = frag;
9146 handle = mono_threads_create_thread ((LPTHREAD_START_ROUTINE)compile_thread_main, user_data, 0, 0, NULL);
9147 g_ptr_array_add (threads, handle);
9151 for (i = 0; i < threads->len; ++i) {
9152 WaitForSingleObjectEx (g_ptr_array_index (threads, i), INFINITE, FALSE);
9158 /* Compile methods added by compile_method () or all methods if nthreads == 0 */
9159 for (i = methods_len; i < acfg->methods->len; ++i) {
9160 /* This can new methods to acfg->methods */
9161 compile_method (acfg, (MonoMethod *)g_ptr_array_index (acfg->methods, i));
9166 compile_asm (MonoAotCompile *acfg)
9168 char *command, *objfile;
9169 char *outfile_name, *tmp_outfile_name, *llvm_ofile;
9170 const char *tool_prefix = acfg->aot_opts.tool_prefix ? acfg->aot_opts.tool_prefix : "";
9171 char *ld_flags = acfg->aot_opts.ld_flags ? acfg->aot_opts.ld_flags : g_strdup("");
9173 #if defined(TARGET_AMD64) && !defined(TARGET_MACH)
9174 #define AS_OPTIONS "--64"
9175 #elif defined(TARGET_POWERPC64)
9176 #define AS_OPTIONS "-a64 -mppc64"
9177 #define LD_OPTIONS "-m elf64ppc"
9178 #elif defined(sparc) && SIZEOF_VOID_P == 8
9179 #define AS_OPTIONS "-xarch=v9"
9180 #elif defined(TARGET_X86) && defined(TARGET_MACH) && !defined(__native_client_codegen__)
9181 #define AS_OPTIONS "-arch i386"
9183 #define AS_OPTIONS ""
9186 #ifdef __native_client_codegen__
9187 #if defined(TARGET_AMD64)
9188 #define AS_NAME "nacl64-as"
9190 #define AS_NAME "nacl-as"
9192 #elif defined(TARGET_OSX)
9193 #define AS_NAME "clang"
9195 #define AS_NAME "as"
9199 #define LD_OPTIONS ""
9203 #define LD_NAME "ld -shared -G"
9204 #elif defined(__ppc__) && defined(TARGET_MACH)
9205 #define LD_NAME "gcc -dynamiclib"
9206 #elif defined(TARGET_AMD64) && defined(TARGET_MACH)
9207 #define LD_NAME "clang --shared"
9208 #elif defined(TARGET_WIN32) && !defined(TARGET_ANDROID)
9209 #define LD_NAME "gcc -shared --dll"
9210 #elif defined(TARGET_X86) && defined(TARGET_MACH) && !defined(__native_client_codegen__)
9211 #define LD_NAME "clang -m32 -dynamiclib"
9212 #elif defined(TARGET_ARM) && !defined(TARGET_ANDROID)
9213 #define LD_NAME "gcc --shared"
9216 if (acfg->aot_opts.asm_only) {
9217 aot_printf (acfg, "Output file: '%s'.\n", acfg->tmpfname);
9218 if (acfg->aot_opts.static_link)
9219 aot_printf (acfg, "Linking symbol: '%s'.\n", acfg->static_linking_symbol);
9221 aot_printf (acfg, "LLVM output file: '%s'.\n", acfg->llvm_sfile);
9225 if (acfg->aot_opts.static_link) {
9226 if (acfg->aot_opts.outfile)
9227 objfile = g_strdup_printf ("%s", acfg->aot_opts.outfile);
9229 objfile = g_strdup_printf ("%s.o", acfg->image->name);
9231 objfile = g_strdup_printf ("%s.o", acfg->tmpfname);
9235 g_string_append (acfg->as_args, "-c -x assembler");
9238 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);
9239 aot_printf (acfg, "Executing the native assembler: %s\n", command);
9240 if (execute_system (command) != 0) {
9246 if (acfg->llvm && !acfg->llvm_owriter) {
9247 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);
9248 aot_printf (acfg, "Executing the native assembler: %s\n", command);
9249 if (execute_system (command) != 0) {
9258 if (acfg->aot_opts.static_link) {
9259 aot_printf (acfg, "Output file: '%s'.\n", objfile);
9260 aot_printf (acfg, "Linking symbol: '%s'.\n", acfg->static_linking_symbol);
9265 if (acfg->aot_opts.outfile)
9266 outfile_name = g_strdup_printf ("%s", acfg->aot_opts.outfile);
9268 outfile_name = g_strdup_printf ("%s%s", acfg->image->name, MONO_SOLIB_EXT);
9270 tmp_outfile_name = g_strdup_printf ("%s.tmp", outfile_name);
9273 llvm_ofile = g_strdup_printf ("\"%s\"", acfg->llvm_ofile);
9275 llvm_ofile = g_strdup ("");
9278 /* replace the ; flags separators with spaces */
9279 g_strdelimit (ld_flags, ";", ' ');
9281 if (acfg->aot_opts.llvm_only)
9282 ld_flags = g_strdup_printf ("%s %s", ld_flags, "-lstdc++");
9285 command = g_strdup_printf ("%s -o \"%s\" %s \"%s.o\" %s", LD_NAME, tmp_outfile_name, llvm_ofile, acfg->tmpfname, ld_flags);
9287 command = g_strdup_printf ("\"%sld\" %s -shared -o %s %s %s.o %s", tool_prefix, LD_OPTIONS, tmp_outfile_name, llvm_ofile,
9288 acfg->tmpfname, ld_flags);
9290 aot_printf (acfg, "Executing the native linker: %s\n", command);
9291 if (execute_system (command) != 0) {
9292 g_free (tmp_outfile_name);
9293 g_free (outfile_name);
9302 /*com = g_strdup_printf ("strip --strip-unneeded %s%s", acfg->image->name, MONO_SOLIB_EXT);
9303 printf ("Stripping the binary: %s\n", com);
9304 execute_system (com);
9307 #if defined(TARGET_ARM) && !defined(TARGET_MACH)
9309 * gas generates 'mapping symbols' each time code and data is mixed, which
9310 * happens a lot in emit_and_reloc_code (), so we need to get rid of them.
9312 command = g_strdup_printf ("\"%sstrip\" --strip-symbol=\\$a --strip-symbol=\\$d %s", tool_prefix, tmp_outfile_name);
9313 aot_printf (acfg, "Stripping the binary: %s\n", command);
9314 if (execute_system (command) != 0) {
9315 g_free (tmp_outfile_name);
9316 g_free (outfile_name);
9323 rename (tmp_outfile_name, outfile_name);
9325 #if defined(TARGET_MACH)
9326 command = g_strdup_printf ("dsymutil \"%s\"", outfile_name);
9327 aot_printf (acfg, "Executing dsymutil: %s\n", command);
9328 if (execute_system (command) != 0) {
9333 if (!acfg->aot_opts.save_temps)
9336 g_free (tmp_outfile_name);
9337 g_free (outfile_name);
9340 if (acfg->aot_opts.save_temps)
9341 aot_printf (acfg, "Retained input file.\n");
9343 unlink (acfg->tmpfname);
9348 static void init_got_info (GotInfo *info)
9352 info->patch_to_got_offset = g_hash_table_new (mono_patch_info_hash, mono_patch_info_equal);
9353 info->patch_to_got_offset_by_type = g_new0 (GHashTable*, MONO_PATCH_INFO_NUM);
9354 for (i = 0; i < MONO_PATCH_INFO_NUM; ++i)
9355 info->patch_to_got_offset_by_type [i] = g_hash_table_new (mono_patch_info_hash, mono_patch_info_equal);
9356 info->got_patches = g_ptr_array_new ();
9359 static MonoAotCompile*
9360 acfg_create (MonoAssembly *ass, guint32 opts)
9362 MonoImage *image = ass->image;
9363 MonoAotCompile *acfg;
9365 acfg = g_new0 (MonoAotCompile, 1);
9366 acfg->methods = g_ptr_array_new ();
9367 acfg->method_indexes = g_hash_table_new (NULL, NULL);
9368 acfg->method_depth = g_hash_table_new (NULL, NULL);
9369 acfg->plt_offset_to_entry = g_hash_table_new (NULL, NULL);
9370 acfg->patch_to_plt_entry = g_new0 (GHashTable*, MONO_PATCH_INFO_NUM);
9371 acfg->method_to_cfg = g_hash_table_new (NULL, NULL);
9372 acfg->token_info_hash = g_hash_table_new_full (NULL, NULL, NULL, NULL);
9373 acfg->method_to_pinvoke_import = g_hash_table_new_full (NULL, NULL, NULL, g_free);
9374 acfg->image_hash = g_hash_table_new (NULL, NULL);
9375 acfg->image_table = g_ptr_array_new ();
9376 acfg->globals = g_ptr_array_new ();
9377 acfg->image = image;
9379 /* TODO: Write out set of SIMD instructions used, rather than just those available */
9380 acfg->simd_opts = mono_arch_cpu_enumerate_simd_versions ();
9381 acfg->mempool = mono_mempool_new ();
9382 acfg->extra_methods = g_ptr_array_new ();
9383 acfg->unwind_info_offsets = g_hash_table_new (NULL, NULL);
9384 acfg->unwind_ops = g_ptr_array_new ();
9385 acfg->method_label_hash = g_hash_table_new_full (g_str_hash, g_str_equal, g_free, NULL);
9386 acfg->method_order = g_ptr_array_new ();
9387 acfg->export_names = g_hash_table_new (NULL, NULL);
9388 acfg->klass_blob_hash = g_hash_table_new (NULL, NULL);
9389 acfg->method_blob_hash = g_hash_table_new (NULL, NULL);
9390 acfg->plt_entry_debug_sym_cache = g_hash_table_new (g_str_hash, g_str_equal);
9391 acfg->signatures = g_hash_table_new ((GHashFunc)mono_signature_hash, (GEqualFunc)mono_metadata_signature_equal);
9392 mono_os_mutex_init_recursive (&acfg->mutex);
9394 init_got_info (&acfg->got_info);
9395 init_got_info (&acfg->llvm_got_info);
9401 got_info_free (GotInfo *info)
9405 for (i = 0; i < MONO_PATCH_INFO_NUM; ++i)
9406 g_hash_table_destroy (info->patch_to_got_offset_by_type [i]);
9407 g_free (info->patch_to_got_offset_by_type);
9408 g_hash_table_destroy (info->patch_to_got_offset);
9409 g_ptr_array_free (info->got_patches, TRUE);
9413 acfg_free (MonoAotCompile *acfg)
9417 mono_img_writer_destroy (acfg->w);
9418 for (i = 0; i < acfg->nmethods; ++i)
9420 g_free (acfg->cfgs [i]);
9421 g_free (acfg->cfgs);
9422 g_free (acfg->static_linking_symbol);
9423 g_free (acfg->got_symbol);
9424 g_free (acfg->plt_symbol);
9425 g_ptr_array_free (acfg->methods, TRUE);
9426 g_ptr_array_free (acfg->image_table, TRUE);
9427 g_ptr_array_free (acfg->globals, TRUE);
9428 g_ptr_array_free (acfg->unwind_ops, TRUE);
9429 g_hash_table_destroy (acfg->method_indexes);
9430 g_hash_table_destroy (acfg->method_depth);
9431 g_hash_table_destroy (acfg->plt_offset_to_entry);
9432 for (i = 0; i < MONO_PATCH_INFO_NUM; ++i) {
9433 if (acfg->patch_to_plt_entry [i])
9434 g_hash_table_destroy (acfg->patch_to_plt_entry [i]);
9436 g_free (acfg->patch_to_plt_entry);
9437 g_hash_table_destroy (acfg->method_to_cfg);
9438 g_hash_table_destroy (acfg->token_info_hash);
9439 g_hash_table_destroy (acfg->method_to_pinvoke_import);
9440 g_hash_table_destroy (acfg->image_hash);
9441 g_hash_table_destroy (acfg->unwind_info_offsets);
9442 g_hash_table_destroy (acfg->method_label_hash);
9443 g_hash_table_destroy (acfg->export_names);
9444 g_hash_table_destroy (acfg->plt_entry_debug_sym_cache);
9445 g_hash_table_destroy (acfg->klass_blob_hash);
9446 g_hash_table_destroy (acfg->method_blob_hash);
9447 got_info_free (&acfg->got_info);
9448 got_info_free (&acfg->llvm_got_info);
9449 mono_mempool_destroy (acfg->mempool);
9453 #define WRAPPER(e,n) n,
9454 static const char* const
9455 wrapper_type_names [MONO_WRAPPER_NUM + 1] = {
9456 #include "mono/metadata/wrapper-types.h"
9460 static G_GNUC_UNUSED const char*
9461 get_wrapper_type_name (int type)
9463 return wrapper_type_names [type];
9469 static void aot_dump (MonoAotCompile *acfg)
9475 mono_json_writer_init (&writer);
9477 mono_json_writer_object_begin(&writer);
9480 mono_json_writer_indent (&writer);
9481 mono_json_writer_object_key(&writer, "methods");
9482 mono_json_writer_array_begin (&writer);
9485 for (i = 0; i < acfg->nmethods; ++i) {
9490 cfg = acfg->cfgs [i];
9494 method = cfg->orig_method;
9496 mono_json_writer_indent (&writer);
9497 mono_json_writer_object_begin(&writer);
9499 mono_json_writer_indent (&writer);
9500 mono_json_writer_object_key(&writer, "name");
9501 mono_json_writer_printf (&writer, "\"%s\",\n", method->name);
9503 mono_json_writer_indent (&writer);
9504 mono_json_writer_object_key(&writer, "signature");
9505 mono_json_writer_printf (&writer, "\"%s\",\n", mono_method_full_name (method,
9506 /*signature=*/TRUE));
9508 mono_json_writer_indent (&writer);
9509 mono_json_writer_object_key(&writer, "code_size");
9510 mono_json_writer_printf (&writer, "\"%d\",\n", cfg->code_size);
9512 klass = method->klass;
9514 mono_json_writer_indent (&writer);
9515 mono_json_writer_object_key(&writer, "class");
9516 mono_json_writer_printf (&writer, "\"%s\",\n", klass->name);
9518 mono_json_writer_indent (&writer);
9519 mono_json_writer_object_key(&writer, "namespace");
9520 mono_json_writer_printf (&writer, "\"%s\",\n", klass->name_space);
9522 mono_json_writer_indent (&writer);
9523 mono_json_writer_object_key(&writer, "wrapper_type");
9524 mono_json_writer_printf (&writer, "\"%s\",\n", get_wrapper_type_name(method->wrapper_type));
9526 mono_json_writer_indent_pop (&writer);
9527 mono_json_writer_indent (&writer);
9528 mono_json_writer_object_end (&writer);
9529 mono_json_writer_printf (&writer, ",\n");
9532 mono_json_writer_indent_pop (&writer);
9533 mono_json_writer_indent (&writer);
9534 mono_json_writer_array_end (&writer);
9535 mono_json_writer_printf (&writer, ",\n");
9539 mono_json_writer_indent_push (&writer);
9540 mono_json_writer_indent (&writer);
9541 mono_json_writer_object_key(&writer, "plt");
9542 mono_json_writer_array_begin (&writer);
9544 for (i = 0; i < acfg->plt_offset; ++i) {
9545 MonoPltEntry *plt_entry = NULL;
9550 * The first plt entry is unused.
9554 plt_entry = g_hash_table_lookup (acfg->plt_offset_to_entry, GUINT_TO_POINTER (i));
9557 mono_json_writer_indent (&writer);
9558 mono_json_writer_printf (&writer, "{ ");
9559 mono_json_writer_object_key(&writer, "symbol");
9560 mono_json_writer_printf (&writer, "\"%s\" },\n", plt_entry->symbol);
9563 mono_json_writer_indent_pop (&writer);
9564 mono_json_writer_indent (&writer);
9565 mono_json_writer_array_end (&writer);
9566 mono_json_writer_printf (&writer, ",\n");
9571 mono_json_writer_indent_push (&writer);
9572 mono_json_writer_indent (&writer);
9573 mono_json_writer_object_key(&writer, "got");
9574 mono_json_writer_array_begin (&writer);
9576 mono_json_writer_indent_push (&writer);
9577 for (i = 0; i < acfg->got_info.got_patches->len; ++i) {
9578 MonoJumpInfo *ji = g_ptr_array_index (acfg->got_info.got_patches, i);
9580 mono_json_writer_indent (&writer);
9581 mono_json_writer_printf (&writer, "{ ");
9582 mono_json_writer_object_key(&writer, "patch_name");
9583 mono_json_writer_printf (&writer, "\"%s\" },\n", get_patch_name (ji->type));
9586 mono_json_writer_indent_pop (&writer);
9587 mono_json_writer_indent (&writer);
9588 mono_json_writer_array_end (&writer);
9589 mono_json_writer_printf (&writer, ",\n");
9592 mono_json_writer_indent_pop (&writer);
9593 mono_json_writer_indent (&writer);
9594 mono_json_writer_object_end (&writer);
9596 dumpname = g_strdup_printf ("%s.json", g_path_get_basename (acfg->image->name));
9597 dumpfile = fopen (dumpname, "w+");
9600 fprintf (dumpfile, "%s", writer.text->str);
9603 mono_json_writer_destroy (&writer);
9606 static const char *preinited_jit_icalls[] = {
9607 "mono_aot_init_llvm_method",
9608 "mono_aot_init_gshared_method_this",
9609 "mono_aot_init_gshared_method_rgctx",
9610 "mono_llvm_throw_corlib_exception",
9611 "mono_resolve_vcall",
9612 "mono_helper_ldstr_mscorlib"
9616 add_preinit_got_slots (MonoAotCompile *acfg)
9622 * Allocate the first few GOT entries to information which is needed frequently, or it is needed
9623 * during method initialization etc.
9626 ji = (MonoJumpInfo *)mono_mempool_alloc0 (acfg->mempool, sizeof (MonoJumpInfo));
9627 ji->type = MONO_PATCH_INFO_IMAGE;
9628 ji->data.image = acfg->image;
9629 get_got_offset (acfg, FALSE, ji);
9630 get_got_offset (acfg, TRUE, ji);
9632 ji = (MonoJumpInfo *)mono_mempool_alloc0 (acfg->mempool, sizeof (MonoJumpInfo));
9633 ji->type = MONO_PATCH_INFO_MSCORLIB_GOT_ADDR;
9634 get_got_offset (acfg, FALSE, ji);
9635 get_got_offset (acfg, TRUE, ji);
9637 ji = (MonoJumpInfo *)mono_mempool_alloc0 (acfg->mempool, sizeof (MonoJumpInfo));
9638 ji->type = MONO_PATCH_INFO_GC_CARD_TABLE_ADDR;
9639 get_got_offset (acfg, FALSE, ji);
9640 get_got_offset (acfg, TRUE, ji);
9642 ji = (MonoJumpInfo *)mono_mempool_alloc0 (acfg->mempool, sizeof (MonoJumpInfo));
9643 ji->type = MONO_PATCH_INFO_GC_NURSERY_START;
9644 get_got_offset (acfg, FALSE, ji);
9645 get_got_offset (acfg, TRUE, ji);
9647 ji = (MonoJumpInfo *)mono_mempool_alloc0 (acfg->mempool, sizeof (MonoJumpInfo));
9648 ji->type = MONO_PATCH_INFO_JIT_TLS_ID;
9649 get_got_offset (acfg, FALSE, ji);
9650 get_got_offset (acfg, TRUE, ji);
9652 ji = (MonoJumpInfo *)mono_mempool_alloc0 (acfg->mempool, sizeof (MonoJumpInfo));
9653 ji->type = MONO_PATCH_INFO_AOT_MODULE;
9654 get_got_offset (acfg, FALSE, ji);
9655 get_got_offset (acfg, TRUE, ji);
9657 ji = (MonoJumpInfo *)mono_mempool_alloc0 (acfg->mempool, sizeof (MonoJumpInfo));
9658 ji->type = MONO_PATCH_INFO_GC_NURSERY_BITS;
9659 get_got_offset (acfg, FALSE, ji);
9660 get_got_offset (acfg, TRUE, ji);
9662 for (i = 0; i < sizeof (preinited_jit_icalls) / sizeof (char*); ++i) {
9663 ji = (MonoJumpInfo *)mono_mempool_alloc0 (acfg->mempool, sizeof (MonoAotCompile));
9664 ji->type = MONO_PATCH_INFO_INTERNAL_METHOD;
9665 ji->data.name = preinited_jit_icalls [i];
9666 get_got_offset (acfg, FALSE, ji);
9667 get_got_offset (acfg, TRUE, ji);
9670 acfg->nshared_got_entries = acfg->got_offset;
9674 mono_compile_assembly (MonoAssembly *ass, guint32 opts, const char *aot_options)
9676 MonoImage *image = ass->image;
9679 MonoAotCompile *acfg;
9680 char *outfile_name, *tmp_outfile_name, *p;
9681 char llvm_stats_msg [256];
9685 acfg = acfg_create (ass, opts);
9687 memset (&acfg->aot_opts, 0, sizeof (acfg->aot_opts));
9688 acfg->aot_opts.write_symbols = TRUE;
9689 acfg->aot_opts.ntrampolines = 1024;
9690 acfg->aot_opts.nrgctx_trampolines = 1024;
9691 acfg->aot_opts.nimt_trampolines = 128;
9692 acfg->aot_opts.nrgctx_fetch_trampolines = 128;
9693 acfg->aot_opts.ngsharedvt_arg_trampolines = 128;
9694 acfg->aot_opts.llvm_path = g_strdup ("");
9695 acfg->aot_opts.temp_path = g_strdup ("");
9697 acfg->aot_opts.use_trampolines_page = TRUE;
9700 mono_aot_parse_options (aot_options, &acfg->aot_opts);
9702 if (acfg->aot_opts.logfile) {
9703 acfg->logfile = fopen (acfg->aot_opts.logfile, "a+");
9706 //acfg->aot_opts.print_skipped_methods = TRUE;
9708 #if !defined(ENABLE_GSHAREDVT)
9709 if (opts & MONO_OPT_GSHAREDVT) {
9710 aot_printerrf (acfg, "-O=gsharedvt not supported on this platform.\n");
9715 #if !defined(MONO_ARCH_GSHAREDVT_SUPPORTED)
9716 if (!acfg->aot_opts.llvm_only && (opts & MONO_OPT_GSHAREDVT)) {
9717 aot_printerrf (acfg, "-O=gsharedvt not supported on this platform.\n");
9722 #if defined(ENABLE_GSHAREDVT)
9723 if (acfg->aot_opts.llvm_only) {
9724 acfg->opts |= MONO_OPT_GSHAREDVT;
9725 opts |= MONO_OPT_GSHAREDVT;
9729 if (opts & MONO_OPT_GSHAREDVT)
9730 mono_set_generic_sharing_vt_supported (TRUE);
9732 aot_printf (acfg, "Mono Ahead of Time compiler - compiling assembly %s\n", image->name);
9734 #ifndef MONO_ARCH_HAVE_FULL_AOT_TRAMPOLINES
9735 if (mono_aot_mode_is_full (&acfg->aot_opts)) {
9736 aot_printerrf (acfg, "--aot=full is not supported on this platform.\n");
9741 if (acfg->aot_opts.direct_pinvoke && !acfg->aot_opts.static_link) {
9742 aot_printerrf (acfg, "The 'direct-pinvoke' AOT option also requires the 'static' AOT option.\n");
9746 if (acfg->aot_opts.static_link)
9747 acfg->aot_opts.asm_writer = TRUE;
9749 if (acfg->aot_opts.soft_debug) {
9750 MonoDebugOptions *opt = mini_get_debug_options ();
9752 opt->mdb_optimizations = TRUE;
9753 opt->gen_sdb_seq_points = TRUE;
9755 if (!mono_debug_enabled ()) {
9756 aot_printerrf (acfg, "The soft-debug AOT option requires the --debug option.\n");
9759 acfg->flags = (MonoAotFileFlags)(acfg->flags | MONO_AOT_FILE_FLAG_DEBUG);
9762 if (mono_use_llvm || acfg->aot_opts.llvm) {
9764 acfg->aot_opts.asm_writer = TRUE;
9765 acfg->flags = (MonoAotFileFlags)(acfg->flags | MONO_AOT_FILE_FLAG_WITH_LLVM);
9767 if (acfg->aot_opts.soft_debug) {
9768 aot_printerrf (acfg, "The 'soft-debug' option is not supported when compiling with LLVM.\n");
9774 if (acfg->aot_opts.asm_only && !acfg->aot_opts.llvm_outfile) {
9775 aot_printerrf (acfg, "Compiling with LLVM and the asm-only option requires the llvm-outputfile= option.");
9780 * Emit all LLVM code into a separate assembly/object file and link with it
9783 if (!acfg->aot_opts.asm_only) {
9784 acfg->llvm_owriter = TRUE;
9785 } else if (acfg->aot_opts.llvm_outfile) {
9786 int len = strlen (acfg->aot_opts.llvm_outfile);
9788 if (len >= 2 && acfg->aot_opts.llvm_outfile [len - 2] == '.' && acfg->aot_opts.llvm_outfile [len - 1] == 'o')
9789 acfg->llvm_owriter = TRUE;
9793 if (mono_aot_mode_is_full (&acfg->aot_opts))
9794 acfg->flags = (MonoAotFileFlags)(acfg->flags | MONO_AOT_FILE_FLAG_FULL_AOT);
9796 if (mono_threads_is_coop_enabled ())
9797 acfg->flags = (MonoAotFileFlags)(acfg->flags | MONO_AOT_FILE_FLAG_SAFEPOINTS);
9799 if (acfg->aot_opts.instances_logfile_path) {
9800 acfg->instances_logfile = fopen (acfg->aot_opts.instances_logfile_path, "w");
9801 if (!acfg->instances_logfile) {
9802 aot_printerrf (acfg, "Unable to create logfile: '%s'.\n", acfg->aot_opts.instances_logfile_path);
9807 load_profile_files (acfg);
9809 acfg->num_trampolines [MONO_AOT_TRAMP_SPECIFIC] = mono_aot_mode_is_full (&acfg->aot_opts) ? acfg->aot_opts.ntrampolines : 0;
9810 #ifdef MONO_ARCH_GSHARED_SUPPORTED
9811 acfg->num_trampolines [MONO_AOT_TRAMP_STATIC_RGCTX] = mono_aot_mode_is_full (&acfg->aot_opts) ? acfg->aot_opts.nrgctx_trampolines : 0;
9813 acfg->num_trampolines [MONO_AOT_TRAMP_IMT_THUNK] = mono_aot_mode_is_full (&acfg->aot_opts) ? acfg->aot_opts.nimt_trampolines : 0;
9814 #ifdef MONO_ARCH_GSHAREDVT_SUPPORTED
9815 if (acfg->opts & MONO_OPT_GSHAREDVT)
9816 acfg->num_trampolines [MONO_AOT_TRAMP_GSHAREDVT_ARG] = mono_aot_mode_is_full (&acfg->aot_opts) ? acfg->aot_opts.ngsharedvt_arg_trampolines : 0;
9819 acfg->temp_prefix = mono_img_writer_get_temp_label_prefix (NULL);
9823 if (acfg->llvm && acfg->thumb_mixed)
9824 acfg->flags = (MonoAotFileFlags)(acfg->flags | MONO_AOT_FILE_FLAG_LLVM_THUMB);
9825 if (acfg->aot_opts.llvm_only)
9826 acfg->flags = (MonoAotFileFlags)(acfg->flags | MONO_AOT_FILE_FLAG_LLVM_ONLY);
9828 acfg->assembly_name_sym = g_strdup (acfg->image->assembly->aname.name);
9829 /* Get rid of characters which cannot occur in symbols */
9830 for (p = acfg->assembly_name_sym; *p; ++p) {
9831 if (!(isalnum (*p) || *p == '_'))
9835 acfg->global_prefix = g_strdup_printf ("mono_aot_%s", acfg->assembly_name_sym);
9836 acfg->plt_symbol = g_strdup_printf ("%s_plt", acfg->global_prefix);
9837 acfg->got_symbol = g_strdup_printf ("%s_got", acfg->global_prefix);
9839 acfg->llvm_got_symbol = g_strdup_printf ("%s_llvm_got", acfg->global_prefix);
9840 acfg->llvm_eh_frame_symbol = g_strdup_printf ("%s_eh_frame", acfg->global_prefix);
9843 acfg->method_index = 1;
9845 if (mono_aot_mode_is_full (&acfg->aot_opts))
9846 mono_set_partial_sharing_supported (TRUE);
9848 res = collect_methods (acfg);
9852 acfg->cfgs_size = acfg->methods->len + 32;
9853 acfg->cfgs = g_new0 (MonoCompile*, acfg->cfgs_size);
9855 /* PLT offset 0 is reserved for the PLT trampoline */
9856 acfg->plt_offset = 1;
9857 add_preinit_got_slots (acfg);
9862 mono_llvm_create_aot_module (acfg->image->assembly, acfg->global_prefix, TRUE, acfg->aot_opts.static_link, acfg->aot_opts.llvm_only);
9868 compile_methods (acfg);
9872 acfg->stats.jit_time = TV_ELAPSED (atv, btv);
9878 if (acfg->aot_opts.asm_only) {
9879 if (acfg->aot_opts.outfile) {
9880 acfg->tmpfname = g_strdup_printf ("%s", acfg->aot_opts.outfile);
9881 acfg->tmpbasename = g_strdup (acfg->tmpfname);
9883 acfg->tmpbasename = g_strdup_printf ("%s", acfg->image->name);
9884 acfg->tmpfname = g_strdup_printf ("%s.s", acfg->tmpbasename);
9886 g_assert (acfg->aot_opts.llvm_outfile);
9887 acfg->llvm_sfile = g_strdup (acfg->aot_opts.llvm_outfile);
9888 if (acfg->llvm_owriter)
9889 acfg->llvm_ofile = g_strdup (acfg->aot_opts.llvm_outfile);
9891 acfg->llvm_sfile = g_strdup (acfg->aot_opts.llvm_outfile);
9893 acfg->tmpbasename = (strcmp (acfg->aot_opts.temp_path, "") == 0) ?
9894 g_strdup_printf ("%s", "temp") :
9895 g_build_filename (acfg->aot_opts.temp_path, "temp", NULL);
9897 acfg->tmpfname = g_strdup_printf ("%s.s", acfg->tmpbasename);
9898 acfg->llvm_sfile = g_strdup_printf ("%s-llvm.s", acfg->tmpbasename);
9899 acfg->llvm_ofile = g_strdup_printf ("%s-llvm.o", acfg->tmpbasename);
9904 if (acfg->aot_opts.asm_only) {
9905 if (acfg->aot_opts.outfile)
9906 acfg->tmpfname = g_strdup_printf ("%s", acfg->aot_opts.outfile);
9908 acfg->tmpfname = g_strdup_printf ("%s.s", acfg->image->name);
9909 acfg->fp = fopen (acfg->tmpfname, "w+");
9911 int i = g_file_open_tmp ("mono_aot_XXXXXX", &acfg->tmpfname, NULL);
9912 acfg->fp = fdopen (i, "w+");
9914 if (acfg->fp == 0) {
9915 aot_printerrf (acfg, "Unable to open file '%s': %s\n", acfg->tmpfname, strerror (errno));
9918 acfg->w = mono_img_writer_create (acfg->fp, FALSE);
9920 tmp_outfile_name = NULL;
9921 outfile_name = NULL;
9923 /* Compute symbols for methods */
9924 for (i = 0; i < acfg->nmethods; ++i) {
9925 if (acfg->cfgs [i]) {
9926 MonoCompile *cfg = acfg->cfgs [i];
9927 int method_index = get_method_index (acfg, cfg->orig_method);
9929 if (COMPILE_LLVM (cfg))
9930 cfg->asm_symbol = g_strdup_printf ("%s%s", acfg->llvm_label_prefix, cfg->llvm_method_name);
9931 else if (acfg->global_symbols || acfg->llvm)
9932 cfg->asm_symbol = get_debug_sym (cfg->orig_method, "", acfg->method_label_hash);
9934 cfg->asm_symbol = g_strdup_printf ("%s%sm_%x", acfg->temp_prefix, acfg->llvm_label_prefix, method_index);
9935 cfg->asm_debug_symbol = cfg->asm_symbol;
9939 if (acfg->aot_opts.dwarf_debug && acfg->aot_opts.asm_only && acfg->aot_opts.gnu_asm) {
9941 * CLANG supports GAS .file/.loc directives, so emit line number information this way
9942 * FIXME: CLANG only emits line number info for .loc directives followed by assembly, not
9945 //acfg->gas_line_numbers = TRUE;
9948 if ((!acfg->aot_opts.nodebug || acfg->aot_opts.dwarf_debug) && acfg->has_jitted_code) {
9949 if (acfg->aot_opts.dwarf_debug && !mono_debug_enabled ()) {
9950 aot_printerrf (acfg, "The dwarf AOT option requires the --debug option.\n");
9953 acfg->dwarf = mono_dwarf_writer_create (acfg->w, NULL, 0, FALSE, !acfg->gas_line_numbers);
9956 mono_img_writer_emit_start (acfg->w);
9959 mono_dwarf_writer_emit_base_info (acfg->dwarf, g_path_get_basename (acfg->image->name), mono_unwind_get_cie_program ());
9965 emit_extra_methods (acfg);
9967 emit_trampolines (acfg);
9969 emit_class_name_table (acfg);
9971 emit_got_info (acfg, FALSE);
9973 emit_got_info (acfg, TRUE);
9975 emit_exception_info (acfg);
9977 emit_unwind_info (acfg);
9979 emit_class_info (acfg);
9983 emit_image_table (acfg);
9987 emit_file_info (acfg);
9991 emit_objc_selectors (acfg);
9993 emit_globals (acfg);
9996 emit_dwarf_info (acfg);
9997 mono_dwarf_writer_close (acfg->dwarf);
10000 emit_mem_end (acfg);
10002 if (acfg->need_pt_gnu_stack) {
10003 /* This is required so the .so doesn't have an executable stack */
10004 /* The bin writer already emits this */
10005 fprintf (acfg->fp, "\n.section .note.GNU-stack,\"\",@progbits\n");
10012 res = emit_llvm_file (acfg);
10020 acfg->stats.gen_time = TV_ELAPSED (atv, btv);
10023 sprintf (llvm_stats_msg, ", LLVM: %d (%d%%)", acfg->stats.llvm_count, acfg->stats.mcount ? (acfg->stats.llvm_count * 100) / acfg->stats.mcount : 100);
10025 strcpy (llvm_stats_msg, "");
10027 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;
10029 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",
10030 (int)acfg->stats.code_size, (int)(acfg->stats.code_size * 100 / all_sizes),
10031 (int)acfg->stats.info_size, (int)(acfg->stats.info_size * 100 / all_sizes),
10032 (int)acfg->stats.ex_info_size, (int)(acfg->stats.ex_info_size * 100 / all_sizes),
10033 (int)acfg->stats.unwind_info_size, (int)(acfg->stats.unwind_info_size * 100 / all_sizes),
10034 (int)acfg->stats.class_info_size, (int)(acfg->stats.class_info_size * 100 / all_sizes),
10035 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,
10036 (int)acfg->stats.got_info_size, (int)(acfg->stats.got_info_size * 100 / all_sizes),
10037 (int)acfg->stats.offsets_size, (int)(acfg->stats.offsets_size * 100 / all_sizes),
10038 (int)(acfg->got_offset * sizeof (gpointer)));
10039 aot_printf (acfg, "Compiled: %d/%d (%d%%)%s, No GOT slots: %d (%d%%), Direct calls: %d (%d%%)\n",
10040 acfg->stats.ccount, acfg->stats.mcount, acfg->stats.mcount ? (acfg->stats.ccount * 100) / acfg->stats.mcount : 100,
10042 acfg->stats.methods_without_got_slots, acfg->stats.mcount ? (acfg->stats.methods_without_got_slots * 100) / acfg->stats.mcount : 100,
10043 acfg->stats.direct_calls, acfg->stats.all_calls ? (acfg->stats.direct_calls * 100) / acfg->stats.all_calls : 100);
10044 if (acfg->stats.genericcount)
10045 aot_printf (acfg, "%d methods are generic (%d%%)\n", acfg->stats.genericcount, acfg->stats.mcount ? (acfg->stats.genericcount * 100) / acfg->stats.mcount : 100);
10046 if (acfg->stats.abscount)
10047 aot_printf (acfg, "%d methods contain absolute addresses (%d%%)\n", acfg->stats.abscount, acfg->stats.mcount ? (acfg->stats.abscount * 100) / acfg->stats.mcount : 100);
10048 if (acfg->stats.lmfcount)
10049 aot_printf (acfg, "%d methods contain lmf pointers (%d%%)\n", acfg->stats.lmfcount, acfg->stats.mcount ? (acfg->stats.lmfcount * 100) / acfg->stats.mcount : 100);
10050 if (acfg->stats.ocount)
10051 aot_printf (acfg, "%d methods have other problems (%d%%)\n", acfg->stats.ocount, acfg->stats.mcount ? (acfg->stats.ocount * 100) / acfg->stats.mcount : 100);
10054 res = mono_img_writer_emit_writeout (acfg->w);
10059 res = compile_asm (acfg);
10065 acfg->stats.link_time = TV_ELAPSED (atv, btv);
10067 if (acfg->aot_opts.stats) {
10070 aot_printf (acfg, "GOT slot distribution:\n");
10071 for (i = 0; i < MONO_PATCH_INFO_NONE; ++i)
10072 if (acfg->stats.got_slot_types [i])
10073 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]);
10076 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);
10078 if (acfg->aot_opts.dump_json)
10091 mono_aot_readonly_field_override (MonoClassField *field)
10097 mono_compile_assembly (MonoAssembly *ass, guint32 opts, const char *aot_options)
10103 mono_aot_is_shared_got_offset (int offset)