2 * aot-compiler.c: mono Ahead of Time compiler
5 * Dietmar Maurer (dietmar@ximian.com)
6 * Zoltan Varga (vargaz@gmail.com)
8 * (C) 2002 Ximian, Inc.
9 * Copyright 2003-2011 Novell, Inc
10 * Copyright 2011 Xamarin Inc (http://www.xamarin.com)
14 #include <sys/types.h>
34 #include <mono/metadata/abi-details.h>
35 #include <mono/metadata/tabledefs.h>
36 #include <mono/metadata/class.h>
37 #include <mono/metadata/object.h>
38 #include <mono/metadata/tokentype.h>
39 #include <mono/metadata/appdomain.h>
40 #include <mono/metadata/debug-helpers.h>
41 #include <mono/metadata/assembly.h>
42 #include <mono/metadata/metadata-internals.h>
43 #include <mono/metadata/marshal.h>
44 #include <mono/metadata/gc-internal.h>
45 #include <mono/metadata/monitor.h>
46 #include <mono/metadata/mempool-internals.h>
47 #include <mono/metadata/mono-endian.h>
48 #include <mono/metadata/threads-types.h>
49 #include <mono/utils/mono-logger-internal.h>
50 #include <mono/utils/mono-compiler.h>
51 #include <mono/utils/mono-time.h>
52 #include <mono/utils/mono-mmap.h>
53 #include <mono/utils/json.h>
56 #include "seq-points.h"
57 #include "image-writer.h"
58 #include "dwarfwriter.h"
61 #if !defined(DISABLE_AOT) && !defined(DISABLE_JIT)
63 #if defined(__linux__) || defined(__native_client_codegen__)
64 #define RODATA_SECT ".rodata"
65 #elif defined(TARGET_MACH)
66 #define RODATA_SECT ".section __TEXT, __const"
68 #define RODATA_SECT ".text"
71 #define TV_DECLARE(name) gint64 name
72 #define TV_GETTIME(tv) tv = mono_100ns_ticks ()
73 #define TV_ELAPSED(start,end) (((end) - (start)) / 10)
75 #define ALIGN_TO(val,align) ((((guint64)val) + ((align) - 1)) & ~((align) - 1))
76 #define ALIGN_PTR_TO(ptr,align) (gpointer)((((gssize)(ptr)) + (align - 1)) & (~(align - 1)))
77 #define ROUND_DOWN(VALUE,SIZE) ((VALUE) & ~((SIZE) - 1))
79 /* predefined values for static readonly fields without needed to run the .cctor */
80 typedef struct _ReadOnlyValue ReadOnlyValue;
81 struct _ReadOnlyValue {
84 int type; /* to be used later for typechecking to prevent user errors */
93 static ReadOnlyValue *readonly_values;
95 typedef struct MonoAotOptions {
99 gboolean write_symbols;
100 gboolean metadata_only;
101 gboolean bind_to_runtime_version;
104 gboolean static_link;
108 gboolean dwarf_debug;
110 gboolean log_generics;
111 gboolean log_instances;
112 gboolean gen_seq_points_file;
113 gboolean direct_pinvoke;
114 gboolean direct_icalls;
115 gboolean no_direct_calls;
116 gboolean use_trampolines_page;
117 gboolean no_instances;
122 int nrgctx_trampolines;
123 int nimt_trampolines;
124 int ngsharedvt_arg_trampolines;
125 int nrgctx_fetch_trampolines;
126 gboolean print_skipped_methods;
133 char *instances_logfile_path;
138 typedef struct MonoAotStats {
139 int ccount, mcount, lmfcount, abscount, gcount, ocount, genericcount;
140 int code_size, info_size, ex_info_size, unwind_info_size, got_size, class_info_size, got_info_size, plt_size;
141 int methods_without_got_slots, direct_calls, all_calls, llvm_count;
142 int got_slots, offsets_size;
143 int got_slot_types [MONO_PATCH_INFO_NONE];
144 int got_slot_info_sizes [MONO_PATCH_INFO_NONE];
145 int jit_time, gen_time, link_time;
148 typedef struct GotInfo {
149 GHashTable *patch_to_got_offset;
150 GHashTable **patch_to_got_offset_by_type;
151 GPtrArray *got_patches;
154 typedef struct MonoAotCompile {
157 GHashTable *method_indexes;
158 GHashTable *method_depth;
161 GHashTable **patch_to_plt_entry;
162 GHashTable *plt_offset_to_entry;
163 //GHashTable *patch_to_got_offset;
164 //GHashTable **patch_to_got_offset_by_type;
165 //GPtrArray *got_patches;
166 GotInfo got_info, llvm_got_info;
167 GHashTable *image_hash;
168 GHashTable *method_to_cfg;
169 GHashTable *token_info_hash;
170 GHashTable *method_to_pinvoke_import;
171 GPtrArray *extra_methods;
172 GPtrArray *image_table;
174 GPtrArray *method_order;
175 GHashTable *export_names;
176 /* Maps MonoClass* -> blob offset */
177 GHashTable *klass_blob_hash;
178 /* Maps MonoMethod* -> blob offset */
179 GHashTable *method_blob_hash;
180 guint32 *plt_got_info_offsets;
181 guint32 got_offset, llvm_got_offset, plt_offset, plt_got_offset_base;
182 /* Number of GOT entries reserved for trampolines */
183 guint32 num_trampoline_got_entries;
184 guint32 tramp_page_size;
186 guint32 num_trampolines [MONO_AOT_TRAMP_NUM];
187 guint32 trampoline_got_offset_base [MONO_AOT_TRAMP_NUM];
188 guint32 trampoline_size [MONO_AOT_TRAMP_NUM];
189 guint32 tramp_page_code_offsets [MONO_AOT_TRAMP_NUM];
191 MonoAotOptions aot_opts;
195 MonoMemPool *mempool;
198 char *static_linking_symbol;
200 gboolean use_bin_writer;
201 gboolean gas_line_numbers;
202 /* Whenever to emit LLVM code into a separate object file */
203 gboolean llvm_separate;
204 /* Whenever to emit an object file directly from llc */
205 gboolean llvm_owriter;
207 MonoDwarfWriter *dwarf;
214 GHashTable *unwind_info_offsets;
215 GPtrArray *unwind_ops;
216 guint32 unwind_info_offset;
217 char *got_symbol_base;
218 char *llvm_got_symbol_base;
220 char *llvm_got_symbol;
222 char *methods_symbol;
223 char *llvm_eh_frame_symbol;
224 GHashTable *method_label_hash;
225 const char *temp_prefix;
226 const char *user_symbol_prefix;
227 const char *llvm_label_prefix;
228 const char *inst_directive;
230 guint32 label_generator;
232 MonoAotFileFlags flags;
233 MonoDynamicStream blob;
234 MonoClass **typespec_classes;
237 char *assembly_name_sym;
238 GHashTable *plt_entry_debug_sym_cache;
239 gboolean thumb_mixed, need_no_dead_strip, need_pt_gnu_stack;
240 GHashTable *ginst_hash;
241 GHashTable *dwarf_ln_filenames;
242 gboolean global_symbols;
243 int objc_selector_index, objc_selector_index_2;
244 GPtrArray *objc_selectors;
245 GHashTable *objc_selector_to_index;
247 FILE *instances_logfile;
252 char *symbol, *llvm_symbol, *debug_sym;
254 gboolean jit_used, llvm_used;
257 #define mono_acfg_lock(acfg) mono_mutex_lock (&((acfg)->mutex))
258 #define mono_acfg_unlock(acfg) mono_mutex_unlock (&((acfg)->mutex))
260 /* This points to the current acfg in LLVM mode */
261 static MonoAotCompile *llvm_acfg;
263 #ifdef HAVE_ARRAY_ELEM_INIT
264 #define MSGSTRFIELD(line) MSGSTRFIELD1(line)
265 #define MSGSTRFIELD1(line) str##line
266 static const struct msgstr_t {
267 #define PATCH_INFO(a,b) char MSGSTRFIELD(__LINE__) [sizeof (b)];
268 #include "patch-info.h"
271 #define PATCH_INFO(a,b) b,
272 #include "patch-info.h"
275 static const gint16 opidx [] = {
276 #define PATCH_INFO(a,b) [MONO_PATCH_INFO_ ## a] = offsetof (struct msgstr_t, MSGSTRFIELD(__LINE__)),
277 #include "patch-info.h"
281 static G_GNUC_UNUSED const char*
282 get_patch_name (int info)
284 return (const char*)&opstr + opidx [info];
288 #define PATCH_INFO(a,b) b,
289 static const char* const
290 patch_types [MONO_PATCH_INFO_NUM + 1] = {
291 #include "patch-info.h"
295 static G_GNUC_UNUSED const char*
296 get_patch_name (int info)
298 return patch_types [info];
304 get_plt_entry_debug_sym (MonoAotCompile *acfg, MonoJumpInfo *ji, GHashTable *cache);
307 aot_printf (MonoAotCompile *acfg, const gchar *format, ...)
313 output = acfg->logfile;
317 va_start (args, format);
318 vfprintf (output, format, args);
323 aot_printerrf (MonoAotCompile *acfg, const gchar *format, ...)
329 output = acfg->logfile;
333 va_start (args, format);
334 vfprintf (output, format, args);
339 report_loader_error (MonoAotCompile *acfg, MonoError *error, const char *format, ...)
344 if (mono_error_ok (error))
348 output = acfg->logfile;
352 va_start (args, format);
353 vfprintf (output, format, args);
355 mono_error_cleanup (error);
357 g_error ("FullAOT cannot continue if there are loader errors");
360 /* Wrappers around the image writer functions */
363 emit_section_change (MonoAotCompile *acfg, const char *section_name, int subsection_index)
365 img_writer_emit_section_change (acfg->w, section_name, subsection_index);
369 emit_local_symbol (MonoAotCompile *acfg, const char *name, const char *end_label, gboolean func)
371 img_writer_emit_local_symbol (acfg->w, name, end_label, func);
375 emit_label (MonoAotCompile *acfg, const char *name)
377 img_writer_emit_label (acfg->w, name);
381 emit_bytes (MonoAotCompile *acfg, const guint8* buf, int size)
383 img_writer_emit_bytes (acfg->w, buf, size);
387 emit_string (MonoAotCompile *acfg, const char *value)
389 img_writer_emit_string (acfg->w, value);
393 emit_line (MonoAotCompile *acfg)
395 img_writer_emit_line (acfg->w);
399 emit_alignment (MonoAotCompile *acfg, int size)
401 img_writer_emit_alignment (acfg->w, size);
405 emit_alignment_code (MonoAotCompile *acfg, int size)
407 if (acfg->align_pad_value)
408 img_writer_emit_alignment_fill (acfg->w, size, acfg->align_pad_value);
410 img_writer_emit_alignment (acfg->w, size);
414 emit_padding (MonoAotCompile *acfg, int size)
419 if (acfg->align_pad_value) {
420 for (i = 0; i < 16; ++i)
421 buf [i] = acfg->align_pad_value;
423 memset (buf, 0, sizeof (buf));
426 for (i = 0; i < size; i += 16) {
428 emit_bytes (acfg, buf, size - i);
430 emit_bytes (acfg, buf, 16);
435 emit_pointer (MonoAotCompile *acfg, const char *target)
437 img_writer_emit_pointer (acfg->w, target);
441 emit_pointer_2 (MonoAotCompile *acfg, const char *prefix, const char *target)
443 if (prefix [0] != '\0') {
444 char *s = g_strdup_printf ("%s%s", prefix, target);
445 img_writer_emit_pointer (acfg->w, s);
448 img_writer_emit_pointer (acfg->w, target);
453 emit_int16 (MonoAotCompile *acfg, int value)
455 img_writer_emit_int16 (acfg->w, value);
459 emit_int32 (MonoAotCompile *acfg, int value)
461 img_writer_emit_int32 (acfg->w, value);
465 emit_symbol_diff (MonoAotCompile *acfg, const char *end, const char* start, int offset)
467 img_writer_emit_symbol_diff (acfg->w, end, start, offset);
471 emit_zero_bytes (MonoAotCompile *acfg, int num)
473 img_writer_emit_zero_bytes (acfg->w, num);
477 emit_byte (MonoAotCompile *acfg, guint8 val)
479 img_writer_emit_byte (acfg->w, val);
482 #ifdef __native_client_codegen__
484 emit_nacl_call_alignment (MonoAotCompile *acfg)
486 img_writer_emit_nacl_call_alignment (acfg->w);
490 static G_GNUC_UNUSED void
491 emit_global_inner (MonoAotCompile *acfg, const char *name, gboolean func)
493 img_writer_emit_global (acfg->w, name, func);
497 emit_global (MonoAotCompile *acfg, const char *name, gboolean func)
499 if (acfg->aot_opts.no_dlsym) {
500 g_ptr_array_add (acfg->globals, g_strdup (name));
501 img_writer_emit_local_symbol (acfg->w, name, NULL, func);
503 img_writer_emit_global (acfg->w, name, func);
508 emit_symbol_size (MonoAotCompile *acfg, const char *name, const char *end_label)
510 img_writer_emit_symbol_size (acfg->w, name, end_label);
514 emit_string_symbol (MonoAotCompile *acfg, const char *name, const char *value)
516 img_writer_emit_section_change (acfg->w, RODATA_SECT, 1);
518 /* On apple, all symbols need to be aligned to avoid warnings from ld */
519 emit_alignment (acfg, 4);
521 img_writer_emit_label (acfg->w, name);
522 img_writer_emit_string (acfg->w, value);
525 static G_GNUC_UNUSED void
526 emit_uleb128 (MonoAotCompile *acfg, guint32 value)
529 guint8 b = value & 0x7f;
531 if (value != 0) /* more bytes to come */
537 static G_GNUC_UNUSED void
538 emit_sleb128 (MonoAotCompile *acfg, gint64 value)
541 gboolean negative = (value < 0);
548 /* the following is unnecessary if the
549 * implementation of >>= uses an arithmetic rather
550 * than logical shift for a signed left operand
554 value |= - ((gint64)1 <<(size - 7));
555 /* sign bit of byte is second high order bit (0x40) */
556 if ((value == 0 && !(byte & 0x40)) ||
557 (value == -1 && (byte & 0x40)))
561 emit_byte (acfg, byte);
565 static G_GNUC_UNUSED void
566 encode_uleb128 (guint32 value, guint8 *buf, guint8 **endbuf)
571 guint8 b = value & 0x7f;
573 if (value != 0) /* more bytes to come */
581 static G_GNUC_UNUSED void
582 encode_sleb128 (gint32 value, guint8 *buf, guint8 **endbuf)
585 gboolean negative = (value < 0);
593 /* the following is unnecessary if the
594 * implementation of >>= uses an arithmetic rather
595 * than logical shift for a signed left operand
599 value |= - (1 <<(size - 7));
600 /* sign bit of byte is second high order bit (0x40) */
601 if ((value == 0 && !(byte & 0x40)) ||
602 (value == -1 && (byte & 0x40)))
613 emit_unset_mode (MonoAotCompile *acfg)
615 img_writer_emit_unset_mode (acfg->w);
618 static G_GNUC_UNUSED void
619 emit_set_thumb_mode (MonoAotCompile *acfg)
621 emit_unset_mode (acfg);
622 fprintf (acfg->fp, ".code 16\n");
625 static G_GNUC_UNUSED void
626 emit_set_arm_mode (MonoAotCompile *acfg)
628 emit_unset_mode (acfg);
629 fprintf (acfg->fp, ".code 32\n");
633 emit_code_bytes (MonoAotCompile *acfg, const guint8* buf, int size)
638 g_assert (size % 4 == 0);
639 emit_unset_mode (acfg);
640 for (i = 0; i < size; i += 4)
641 fprintf (acfg->fp, "%s 0x%x\n", acfg->inst_directive, *(guint32*)(buf + i));
643 emit_bytes (acfg, buf, size);
647 /* ARCHITECTURE SPECIFIC CODE */
649 #if defined(TARGET_X86) || defined(TARGET_AMD64) || defined(TARGET_ARM) || defined(TARGET_POWERPC) || defined(TARGET_ARM64)
650 #define EMIT_DWARF_INFO 1
653 #if defined(TARGET_ARM)
654 #define AOT_FUNC_ALIGNMENT 4
656 #define AOT_FUNC_ALIGNMENT 16
658 #if (defined(TARGET_X86) || defined(TARGET_AMD64)) && defined(__native_client_codegen__)
659 #undef AOT_FUNC_ALIGNMENT
660 #define AOT_FUNC_ALIGNMENT 32
663 #if defined(TARGET_POWERPC64) && !defined(__mono_ilp32__)
664 #define PPC_LD_OP "ld"
665 #define PPC_LDX_OP "ldx"
667 #define PPC_LD_OP "lwz"
668 #define PPC_LDX_OP "lwzx"
672 #define AOT_TARGET_STR "AMD64"
677 #define AOT_TARGET_STR "ARM (MACH)"
679 #define AOT_TARGET_STR "ARM (!MACH)"
685 #define AOT_TARGET_STR "ARM64 (MACH)"
687 #define AOT_TARGET_STR "ARM64 (!MACH)"
691 #ifdef TARGET_POWERPC64
692 #ifdef __mono_ilp32__
693 #define AOT_TARGET_STR "POWERPC64 (mono ilp32)"
695 #define AOT_TARGET_STR "POWERPC64 (!mono ilp32)"
698 #ifdef TARGET_POWERPC
699 #ifdef __mono_ilp32__
700 #define AOT_TARGET_STR "POWERPC (mono ilp32)"
702 #define AOT_TARGET_STR "POWERPC (!mono ilp32)"
709 #define AOT_TARGET_STR "X86 (WIN32)"
710 #elif defined(__native_client_codegen__)
711 #define AOT_TARGET_STR "X86 (native client codegen)"
713 #define AOT_TARGET_STR "X86 (!native client codegen)"
717 #ifndef AOT_TARGET_STR
718 #define AOT_TARGET_STR ""
722 arch_init (MonoAotCompile *acfg)
724 acfg->llc_args = g_string_new ("");
725 acfg->as_args = g_string_new ("");
728 * The prefix LLVM likes to put in front of symbol names on darwin.
729 * The mach-os specs require this for globals, but LLVM puts them in front of all
730 * symbols. We need to handle this, since we need to refer to LLVM generated
733 acfg->llvm_label_prefix = "";
734 acfg->user_symbol_prefix = "";
736 #if defined(TARGET_X86)
737 g_string_append (acfg->llc_args, " -march=x86 -mattr=sse4.1");
740 #if defined(TARGET_AMD64)
741 g_string_append (acfg->llc_args, " -march=x86-64 -mattr=sse4.1");
743 acfg->align_pad_value = 0x90;
747 if (acfg->aot_opts.mtriple && strstr (acfg->aot_opts.mtriple, "darwin")) {
748 g_string_append (acfg->llc_args, "-mattr=+v6");
751 g_string_append (acfg->llc_args, " -mattr=+vfp2,-neon,+d16");
752 g_string_append (acfg->as_args, " -mfpu=vfp3");
754 g_string_append (acfg->llc_args, " -soft-float");
757 if (acfg->aot_opts.mtriple && strstr (acfg->aot_opts.mtriple, "thumb"))
758 acfg->thumb_mixed = TRUE;
760 if (acfg->aot_opts.mtriple)
761 mono_arch_set_target (acfg->aot_opts.mtriple);
765 acfg->inst_directive = ".inst";
766 if (acfg->aot_opts.mtriple)
767 mono_arch_set_target (acfg->aot_opts.mtriple);
771 acfg->user_symbol_prefix = "_";
772 acfg->llvm_label_prefix = "_";
773 acfg->inst_directive = ".word";
774 acfg->need_no_dead_strip = TRUE;
775 acfg->aot_opts.gnu_asm = TRUE;
778 #if defined(__linux__) && !defined(TARGET_ARM)
779 acfg->need_pt_gnu_stack = TRUE;
783 acfg->global_symbols = TRUE;
789 #include "../../../mono-extensions/mono/mini/aot-compiler-arm64.c"
793 #ifdef MONO_ARCH_AOT_SUPPORTED
795 * arch_emit_direct_call:
797 * Emit a direct call to the symbol TARGET. CALL_SIZE is set to the size of the
801 arch_emit_direct_call (MonoAotCompile *acfg, const char *target, gboolean external, gboolean thumb, MonoJumpInfo *ji, int *call_size)
803 #if defined(TARGET_X86) || defined(TARGET_AMD64)
804 /* Need to make sure this is exactly 5 bytes long */
805 if (!acfg->use_bin_writer) {
806 emit_unset_mode (acfg);
807 fprintf (acfg->fp, "call %s\n", target);
809 emit_byte (acfg, '\xe8');
810 emit_symbol_diff (acfg, target, ".", -4);
813 #elif defined(TARGET_ARM)
814 if (acfg->use_bin_writer) {
821 img_writer_emit_reloc (acfg->w, R_ARM_CALL, target, -8);
822 emit_bytes (acfg, buf, 4);
824 emit_unset_mode (acfg);
826 fprintf (acfg->fp, "blx %s\n", target);
828 fprintf (acfg->fp, "bl %s\n", target);
831 #elif defined(TARGET_ARM64)
832 arm64_emit_direct_call (acfg, target, external, thumb, ji, call_size);
833 #elif defined(TARGET_POWERPC)
834 if (acfg->use_bin_writer) {
835 g_assert_not_reached ();
837 emit_unset_mode (acfg);
838 fprintf (acfg->fp, "bl %s\n", target);
842 g_assert_not_reached ();
849 * - we use an approach similar to the x86 abi: reserve a register (r30) to hold
851 * - The full-aot trampolines need access to the GOT of mscorlib, so we store
852 * in in the 2. slot of every GOT, and require every method to place the GOT
853 * address in r30, even when it doesn't access the GOT otherwise. This way,
854 * the trampolines can compute the mscorlib GOT address by loading 4(r30).
859 * PPC64 uses function descriptors which greatly complicate all code, since
860 * these are used very inconsistently in the runtime. Some functions like
861 * mono_compile_method () return ftn descriptors, while others like the
862 * trampoline creation functions do not.
863 * We assume that all GOT slots contain function descriptors, and create
864 * descriptors in aot-runtime.c when needed.
865 * The ppc64 abi uses r2 to hold the address of the TOC/GOT, which is loaded
866 * from function descriptors, we could do the same, but it would require
867 * rewriting all the ppc/aot code to handle function descriptors properly.
868 * So instead, we use the same approach as on PPC32.
869 * This is a horrible mess, but fixing it would probably lead to an even bigger
875 * - similar to the PPC32 design, we reserve EBX to hold the GOT pointer.
878 #ifdef MONO_ARCH_AOT_SUPPORTED
880 * arch_emit_got_offset:
882 * The memory pointed to by CODE should hold native code for computing the GOT
883 * address. Emit this code while patching it with the offset between code and
884 * the GOT. CODE_SIZE is set to the number of bytes emitted.
887 arch_emit_got_offset (MonoAotCompile *acfg, guint8 *code, int *code_size)
889 #if defined(TARGET_POWERPC64)
890 g_assert (!acfg->use_bin_writer);
891 emit_unset_mode (acfg);
893 * The ppc32 code doesn't seem to work on ppc64, the assembler complains about
894 * unsupported relocations. So we store the got address into the .Lgot_addr
895 * symbol which is in the text segment, compute its address, and load it.
897 fprintf (acfg->fp, ".L%d:\n", acfg->label_generator);
898 fprintf (acfg->fp, "lis 0, (.Lgot_addr + 4 - .L%d)@h\n", acfg->label_generator);
899 fprintf (acfg->fp, "ori 0, 0, (.Lgot_addr + 4 - .L%d)@l\n", acfg->label_generator);
900 fprintf (acfg->fp, "add 30, 30, 0\n");
901 fprintf (acfg->fp, "%s 30, 0(30)\n", PPC_LD_OP);
902 acfg->label_generator ++;
904 #elif defined(TARGET_POWERPC)
905 g_assert (!acfg->use_bin_writer);
906 emit_unset_mode (acfg);
907 fprintf (acfg->fp, ".L%d:\n", acfg->label_generator);
908 fprintf (acfg->fp, "lis 0, (%s + 4 - .L%d)@h\n", acfg->got_symbol, acfg->label_generator);
909 fprintf (acfg->fp, "ori 0, 0, (%s + 4 - .L%d)@l\n", acfg->got_symbol, acfg->label_generator);
910 acfg->label_generator ++;
913 guint32 offset = mono_arch_get_patch_offset (code);
914 emit_bytes (acfg, code, offset);
915 emit_symbol_diff (acfg, acfg->got_symbol, ".", offset);
917 *code_size = offset + 4;
922 * arch_emit_got_access:
924 * The memory pointed to by CODE should hold native code for loading a GOT
925 * slot. Emit this code while patching it so it accesses the GOT slot GOT_SLOT.
926 * CODE_SIZE is set to the number of bytes emitted.
929 arch_emit_got_access (MonoAotCompile *acfg, guint8 *code, int got_slot, int *code_size)
931 /* This needs to emit the same code as OP_AOTCONST */
934 /* mov reg, got+offset(%rip) */
935 if (acfg->llvm_separate) {
936 /* The GOT symbol is in the LLVM module, the clang assembler has problems emitting symbol diffs for it */
940 /* Decode reg, see amd64_mov_reg_membase () */
941 rex_r = code [0] & AMD64_REX_R;
942 g_assert (code [0] == 0x49 + rex_r);
943 g_assert (code [1] == 0x8b);
944 dreg = ((code [2] >> 3) & 0x7) + (rex_r ? 8 : 0);
946 emit_unset_mode (acfg);
947 fprintf (acfg->fp, "mov %s+%d(%%rip), %s\n", acfg->got_symbol, (unsigned int) ((got_slot * sizeof (gpointer))), mono_arch_regname (dreg));
950 emit_bytes (acfg, code, mono_arch_get_patch_offset (code));
951 emit_symbol_diff (acfg, acfg->got_symbol, ".", (unsigned int) ((got_slot * sizeof (gpointer)) - 4));
952 *code_size = mono_arch_get_patch_offset (code) + 4;
954 #elif defined(TARGET_X86)
955 emit_bytes (acfg, code, mono_arch_get_patch_offset (code));
956 emit_int32 (acfg, (unsigned int) ((got_slot * sizeof (gpointer))));
957 *code_size = mono_arch_get_patch_offset (code) + 4;
958 #elif defined(TARGET_ARM)
959 emit_bytes (acfg, code, mono_arch_get_patch_offset (code));
960 emit_symbol_diff (acfg, acfg->got_symbol, ".", (unsigned int) ((got_slot * sizeof (gpointer))) - 12);
961 *code_size = mono_arch_get_patch_offset (code) + 4;
962 #elif defined(TARGET_ARM64)
963 emit_bytes (acfg, code, mono_arch_get_patch_offset (code));
964 arm64_emit_got_access (acfg, code, got_slot, code_size);
965 #elif defined(TARGET_POWERPC)
970 emit_bytes (acfg, code, mono_arch_get_patch_offset (code));
972 ppc_load32 (code, ppc_r0, got_slot * sizeof (gpointer));
973 g_assert (code - buf == 8);
974 emit_bytes (acfg, buf, code - buf);
975 *code_size = code - buf;
978 g_assert_not_reached ();
984 #ifdef MONO_ARCH_AOT_SUPPORTED
986 * arch_emit_objc_selector_ref:
988 * Emit the implementation of OP_OBJC_GET_SELECTOR, which itself implements @selector(foo:) in objective-c.
991 arch_emit_objc_selector_ref (MonoAotCompile *acfg, guint8 *code, int index, int *code_size)
993 #if defined(TARGET_ARM)
996 int lindex = acfg->objc_selector_index_2 ++;
999 emit_bytes (acfg, code, 8);
1001 sprintf (symbol1, "L_OBJC_SELECTOR_%d", lindex);
1002 sprintf (symbol2, "L_OBJC_SELECTOR_REFERENCES_%d", index);
1004 emit_label (acfg, symbol1);
1005 img_writer_emit_unset_mode (acfg->w);
1006 fprintf (acfg->fp, ".long %s-(%s+12)", symbol2, symbol1);
1009 #elif defined(TARGET_ARM64)
1010 arm64_emit_objc_selector_ref (acfg, code, index, code_size);
1012 g_assert_not_reached ();
1018 * arch_emit_plt_entry:
1020 * Emit code for the PLT entry with index INDEX.
1023 arch_emit_plt_entry (MonoAotCompile *acfg, int index)
1025 #if defined(TARGET_X86)
1026 guint32 offset = (acfg->plt_got_offset_base + index) * sizeof (gpointer);
1027 #if defined(__default_codegen__)
1028 /* jmp *<offset>(%ebx) */
1029 emit_byte (acfg, 0xff);
1030 emit_byte (acfg, 0xa3);
1031 emit_int32 (acfg, offset);
1032 /* Used by mono_aot_get_plt_info_offset */
1033 emit_int32 (acfg, acfg->plt_got_info_offsets [index]);
1034 #elif defined(__native_client_codegen__)
1035 const guint8 kSizeOfNaClJmp = 11;
1036 guint8 bytes[kSizeOfNaClJmp];
1037 guint8 *pbytes = &bytes[0];
1039 x86_jump_membase32 (pbytes, X86_EBX, offset);
1040 emit_bytes (acfg, bytes, kSizeOfNaClJmp);
1041 /* four bytes of data, used by mono_arch_patch_plt_entry */
1042 /* For Native Client, make this work with data embedded in push. */
1043 emit_byte (acfg, 0x68); /* hide data in a push */
1044 emit_int32 (acfg, acfg->plt_got_info_offsets [index]);
1045 emit_alignment (acfg, AOT_FUNC_ALIGNMENT);
1046 #endif /*__native_client_codegen__*/
1047 #elif defined(TARGET_AMD64)
1048 #if defined(__default_codegen__)
1049 if (acfg->use_bin_writer) {
1050 emit_byte (acfg, '\xff');
1051 emit_byte (acfg, '\x25');
1052 emit_symbol_diff (acfg, acfg->got_symbol, ".", ((acfg->plt_got_offset_base + index) * sizeof (gpointer)) -4);
1054 emit_unset_mode (acfg);
1055 fprintf (acfg->fp, "jmp *%s+%d(%%rip)\n", acfg->got_symbol, (int)((acfg->plt_got_offset_base + index) * sizeof (gpointer)));
1057 /* Used by mono_aot_get_plt_info_offset */
1058 emit_int32 (acfg, acfg->plt_got_info_offsets [index]);
1059 acfg->stats.plt_size += 10;
1060 #elif defined(__native_client_codegen__)
1062 guint8 *buf_aligned = ALIGN_TO(buf, kNaClAlignment);
1063 guint8 *code = buf_aligned;
1065 /* mov <OFFSET>(%rip), %r11d */
1066 emit_byte (acfg, '\x45');
1067 emit_byte (acfg, '\x8b');
1068 emit_byte (acfg, '\x1d');
1069 emit_symbol_diff (acfg, acfg->got_symbol, ".", ((acfg->plt_got_offset_base + index) * sizeof (gpointer)) -4);
1071 amd64_jump_reg (code, AMD64_R11);
1072 /* This should be constant for the plt patch */
1073 g_assert ((size_t)(code-buf_aligned) == 10);
1074 emit_bytes (acfg, buf_aligned, code - buf_aligned);
1076 /* Hide data in a push imm32 so it passes validation */
1077 emit_byte (acfg, 0x68); /* push */
1078 emit_int32 (acfg, acfg->plt_got_info_offsets [index]);
1079 emit_alignment (acfg, AOT_FUNC_ALIGNMENT);
1080 #endif /*__native_client_codegen__*/
1081 #elif defined(TARGET_ARM)
1086 ARM_LDR_IMM (code, ARMREG_IP, ARMREG_PC, 0);
1087 ARM_LDR_REG_REG (code, ARMREG_PC, ARMREG_PC, ARMREG_IP);
1088 emit_bytes (acfg, buf, code - buf);
1089 emit_symbol_diff (acfg, acfg->got_symbol, ".", ((acfg->plt_got_offset_base + index) * sizeof (gpointer)) - 4);
1090 /* Used by mono_aot_get_plt_info_offset */
1091 emit_int32 (acfg, acfg->plt_got_info_offsets [index]);
1092 #elif defined(TARGET_ARM64)
1093 arm64_emit_plt_entry (acfg, index);
1094 #elif defined(TARGET_POWERPC)
1095 guint32 offset = (acfg->plt_got_offset_base + index) * sizeof (gpointer);
1097 /* The GOT address is guaranteed to be in r30 by OP_LOAD_GOTADDR */
1098 g_assert (!acfg->use_bin_writer);
1099 emit_unset_mode (acfg);
1100 fprintf (acfg->fp, "lis 11, %d@h\n", offset);
1101 fprintf (acfg->fp, "ori 11, 11, %d@l\n", offset);
1102 fprintf (acfg->fp, "add 11, 11, 30\n");
1103 fprintf (acfg->fp, "%s 11, 0(11)\n", PPC_LD_OP);
1104 #ifdef PPC_USES_FUNCTION_DESCRIPTOR
1105 fprintf (acfg->fp, "%s 2, %d(11)\n", PPC_LD_OP, (int)sizeof (gpointer));
1106 fprintf (acfg->fp, "%s 11, 0(11)\n", PPC_LD_OP);
1108 fprintf (acfg->fp, "mtctr 11\n");
1109 fprintf (acfg->fp, "bctr\n");
1110 emit_int32 (acfg, acfg->plt_got_info_offsets [index]);
1112 g_assert_not_reached ();
1117 arch_emit_llvm_plt_entry (MonoAotCompile *acfg, int index)
1119 #if defined(TARGET_ARM)
1121 /* LLVM calls the PLT entries using bl, so emit a stub */
1122 /* FIXME: Too much overhead on every call */
1123 fprintf (acfg->fp, ".thumb_func\n");
1124 fprintf (acfg->fp, "bx pc\n");
1125 fprintf (acfg->fp, "nop\n");
1126 fprintf (acfg->fp, ".arm\n");
1128 /* LLVM calls the PLT entries using bl, so these have to be thumb2 */
1129 /* The caller already transitioned to thumb */
1130 /* The code below should be 12 bytes long */
1131 /* clang has trouble encoding these instructions, so emit the binary */
1133 fprintf (acfg->fp, "ldr ip, [pc, #8]\n");
1134 /* thumb can't encode ld pc, [pc, ip] */
1135 fprintf (acfg->fp, "add ip, pc, ip\n");
1136 fprintf (acfg->fp, "ldr ip, [ip, #0]\n");
1137 fprintf (acfg->fp, "bx ip\n");
1139 emit_set_thumb_mode (acfg);
1140 fprintf (acfg->fp, ".4byte 0xc008f8df\n");
1141 fprintf (acfg->fp, ".2byte 0x44fc\n");
1142 fprintf (acfg->fp, ".4byte 0xc000f8dc\n");
1143 fprintf (acfg->fp, ".2byte 0x4760\n");
1144 emit_symbol_diff (acfg, acfg->got_symbol, ".", ((acfg->plt_got_offset_base + index) * sizeof (gpointer)) + 4);
1145 emit_int32 (acfg, acfg->plt_got_info_offsets [index]);
1146 emit_unset_mode (acfg);
1147 emit_set_arm_mode (acfg);
1149 g_assert_not_reached ();
1154 * arch_emit_specific_trampoline_pages:
1156 * Emits a page full of trampolines: each trampoline uses its own address to
1157 * lookup both the generic trampoline code and the data argument.
1158 * This page can be remapped in process multiple times so we can get an
1159 * unlimited number of trampolines.
1160 * Specifically this implementation uses the following trick: two memory pages
1161 * are allocated, with the first containing the data and the second containing the trampolines.
1162 * To reduce trampoline size, each trampoline jumps at the start of the page where a common
1163 * implementation does all the lifting.
1164 * Note that the ARM single trampoline size is 8 bytes, exactly like the data that needs to be stored
1165 * on the arm 32 bit system.
1168 arch_emit_specific_trampoline_pages (MonoAotCompile *acfg)
1170 #if defined(TARGET_ARM)
1173 guint8 *loop_start, *loop_branch_back, *loop_end_check, *imt_found_check;
1175 #define COMMON_TRAMP_SIZE 16
1176 int count = (mono_pagesize () - COMMON_TRAMP_SIZE) / 8;
1177 int imm8, rot_amount;
1180 if (!acfg->aot_opts.use_trampolines_page)
1183 acfg->tramp_page_size = mono_pagesize ();
1185 sprintf (symbol, "%sspecific_trampolines_page", acfg->user_symbol_prefix);
1186 emit_alignment (acfg, mono_pagesize ());
1187 emit_global (acfg, symbol, TRUE);
1188 emit_label (acfg, symbol);
1190 /* emit the generic code first, the trampoline address + 8 is in the lr register */
1192 imm8 = mono_arm_is_rotated_imm8 (mono_pagesize (), &rot_amount);
1193 ARM_SUB_REG_IMM (code, ARMREG_LR, ARMREG_LR, imm8, rot_amount);
1194 ARM_LDR_IMM (code, ARMREG_R1, ARMREG_LR, -8);
1195 ARM_LDR_IMM (code, ARMREG_PC, ARMREG_LR, -4);
1197 g_assert (code - buf == COMMON_TRAMP_SIZE);
1200 emit_bytes (acfg, buf, code - buf);
1202 for (i = 0; i < count; ++i) {
1204 ARM_PUSH (code, 0x5fff);
1206 arm_patch (code - 4, code - COMMON_TRAMP_SIZE - 8 * (i + 1));
1207 g_assert (code - buf == 8);
1208 emit_bytes (acfg, buf, code - buf);
1211 /* now the rgctx trampolines: each specific trampolines puts in the ip register
1212 * the instruction pointer address, so the generic trampoline at the start of the page
1213 * subtracts 4096 to get to the data page and loads the values
1214 * We again fit the generic trampiline in 16 bytes.
1216 sprintf (symbol, "%srgctx_trampolines_page", acfg->user_symbol_prefix);
1217 emit_global (acfg, symbol, TRUE);
1218 emit_label (acfg, symbol);
1220 imm8 = mono_arm_is_rotated_imm8 (mono_pagesize (), &rot_amount);
1221 ARM_SUB_REG_IMM (code, ARMREG_IP, ARMREG_IP, imm8, rot_amount);
1222 ARM_LDR_IMM (code, MONO_ARCH_RGCTX_REG, ARMREG_IP, -8);
1223 ARM_LDR_IMM (code, ARMREG_PC, ARMREG_IP, -4);
1225 g_assert (code - buf == COMMON_TRAMP_SIZE);
1228 emit_bytes (acfg, buf, code - buf);
1230 for (i = 0; i < count; ++i) {
1232 ARM_MOV_REG_REG (code, ARMREG_IP, ARMREG_PC);
1234 arm_patch (code - 4, code - COMMON_TRAMP_SIZE - 8 * (i + 1));
1235 g_assert (code - buf == 8);
1236 emit_bytes (acfg, buf, code - buf);
1240 * gsharedvt arg trampolines: see arch_emit_gsharedvt_arg_trampoline ()
1242 sprintf (symbol, "%sgsharedvt_arg_trampolines_page", acfg->user_symbol_prefix);
1243 emit_global (acfg, symbol, TRUE);
1244 emit_label (acfg, symbol);
1246 ARM_PUSH (code, (1 << ARMREG_R0) | (1 << ARMREG_R1) | (1 << ARMREG_R2) | (1 << ARMREG_R3));
1247 imm8 = mono_arm_is_rotated_imm8 (mono_pagesize (), &rot_amount);
1248 ARM_SUB_REG_IMM (code, ARMREG_IP, ARMREG_IP, imm8, rot_amount);
1249 ARM_LDR_IMM (code, ARMREG_R0, ARMREG_IP, -8);
1250 ARM_LDR_IMM (code, ARMREG_PC, ARMREG_IP, -4);
1251 g_assert (code - buf == COMMON_TRAMP_SIZE);
1253 emit_bytes (acfg, buf, code - buf);
1255 for (i = 0; i < count; ++i) {
1257 ARM_MOV_REG_REG (code, ARMREG_IP, ARMREG_PC);
1259 arm_patch (code - 4, code - COMMON_TRAMP_SIZE - 8 * (i + 1));
1260 g_assert (code - buf == 8);
1261 emit_bytes (acfg, buf, code - buf);
1264 /* now the imt trampolines: each specific trampolines puts in the ip register
1265 * the instruction pointer address, so the generic trampoline at the start of the page
1266 * subtracts 4096 to get to the data page and loads the values
1267 * We again fit the generic trampiline in 16 bytes.
1269 #define IMT_TRAMP_SIZE 72
1270 sprintf (symbol, "%simt_trampolines_page", acfg->user_symbol_prefix);
1271 emit_global (acfg, symbol, TRUE);
1272 emit_label (acfg, symbol);
1274 /* Need at least two free registers, plus a slot for storing the pc */
1275 ARM_PUSH (code, (1 << ARMREG_R0)|(1 << ARMREG_R1)|(1 << ARMREG_R2));
1277 imm8 = mono_arm_is_rotated_imm8 (mono_pagesize (), &rot_amount);
1278 ARM_SUB_REG_IMM (code, ARMREG_IP, ARMREG_IP, imm8, rot_amount);
1279 ARM_LDR_IMM (code, ARMREG_R0, ARMREG_IP, -8);
1281 /* The IMT method is in v5, r0 has the imt array address */
1284 ARM_LDR_IMM (code, ARMREG_R1, ARMREG_R0, 0);
1285 ARM_CMP_REG_REG (code, ARMREG_R1, ARMREG_V5);
1286 imt_found_check = code;
1287 ARM_B_COND (code, ARMCOND_EQ, 0);
1289 /* End-of-loop check */
1290 ARM_CMP_REG_IMM (code, ARMREG_R1, 0, 0);
1291 loop_end_check = code;
1292 ARM_B_COND (code, ARMCOND_EQ, 0);
1295 ARM_ADD_REG_IMM8 (code, ARMREG_R0, ARMREG_R0, sizeof (gpointer) * 2);
1296 loop_branch_back = code;
1298 arm_patch (loop_branch_back, loop_start);
1301 arm_patch (imt_found_check, code);
1302 ARM_LDR_IMM (code, ARMREG_R0, ARMREG_R0, 4);
1303 ARM_LDR_IMM (code, ARMREG_R0, ARMREG_R0, 0);
1304 /* Save it to the third stack slot */
1305 ARM_STR_IMM (code, ARMREG_R0, ARMREG_SP, 8);
1306 /* Restore the registers and branch */
1307 ARM_POP (code, (1 << ARMREG_R0)|(1 << ARMREG_R1)|(1 << ARMREG_PC));
1310 arm_patch (loop_end_check, code);
1311 ARM_LDR_IMM (code, ARMREG_R0, ARMREG_R0, 4);
1312 ARM_STR_IMM (code, ARMREG_R0, ARMREG_SP, 8);
1313 ARM_POP (code, (1 << ARMREG_R0)|(1 << ARMREG_R1)|(1 << ARMREG_PC));
1317 g_assert (code - buf == IMT_TRAMP_SIZE);
1318 emit_bytes (acfg, buf, code - buf);
1320 for (i = 0; i < count; ++i) {
1322 ARM_MOV_REG_REG (code, ARMREG_IP, ARMREG_PC);
1324 arm_patch (code - 4, code - IMT_TRAMP_SIZE - 8 * (i + 1));
1325 g_assert (code - buf == 8);
1326 emit_bytes (acfg, buf, code - buf);
1329 acfg->tramp_page_code_offsets [MONO_AOT_TRAMP_SPECIFIC] = 16;
1330 acfg->tramp_page_code_offsets [MONO_AOT_TRAMP_STATIC_RGCTX] = 16;
1331 acfg->tramp_page_code_offsets [MONO_AOT_TRAMP_IMT_THUNK] = 72;
1332 acfg->tramp_page_code_offsets [MONO_AOT_TRAMP_GSHAREDVT_ARG] = 16;
1333 #elif defined(TARGET_ARM64)
1334 arm64_emit_specific_trampoline_pages (acfg);
1339 * arch_emit_specific_trampoline:
1341 * Emit code for a specific trampoline. OFFSET is the offset of the first of
1342 * two GOT slots which contain the generic trampoline address and the trampoline
1343 * argument. TRAMP_SIZE is set to the size of the emitted trampoline.
1346 arch_emit_specific_trampoline (MonoAotCompile *acfg, int offset, int *tramp_size)
1349 * The trampolines created here are variations of the specific
1350 * trampolines created in mono_arch_create_specific_trampoline (). The
1352 * - the generic trampoline address is taken from a got slot.
1353 * - the offset of the got slot where the trampoline argument is stored
1354 * is embedded in the instruction stream, and the generic trampoline
1355 * can load the argument by loading the offset, adding it to the
1356 * address of the trampoline to get the address of the got slot, and
1357 * loading the argument from there.
1358 * - all the trampolines should be of the same length.
1360 #if defined(TARGET_AMD64)
1361 #if defined(__default_codegen__)
1362 /* This should be exactly 8 bytes long */
1364 /* call *<offset>(%rip) */
1365 if (acfg->llvm_separate) {
1366 emit_unset_mode (acfg);
1367 fprintf (acfg->fp, "call *%s+%d(%%rip)\n", acfg->got_symbol, (int)(offset * sizeof (gpointer)));
1368 emit_zero_bytes (acfg, 2);
1370 emit_byte (acfg, '\x41');
1371 emit_byte (acfg, '\xff');
1372 emit_byte (acfg, '\x15');
1373 emit_symbol_diff (acfg, acfg->got_symbol, ".", (offset * sizeof (gpointer)) - 4);
1374 emit_zero_bytes (acfg, 1);
1376 #elif defined(__native_client_codegen__)
1378 guint8 *buf_aligned = ALIGN_TO(buf, kNaClAlignment);
1379 guint8 *code = buf_aligned;
1384 /* Emit this call in 'code' so we can find out how long it is. */
1385 amd64_call_reg (code, AMD64_R11);
1386 call_start = mono_arch_nacl_skip_nops (buf_aligned);
1387 call_len = code - call_start;
1389 /* The tramp_size is twice the NaCl alignment because it starts with */
1390 /* a call which needs to be aligned to the end of the boundary. */
1391 *tramp_size = kNaClAlignment*2;
1393 /* Emit nops to align call site below which is 7 bytes plus */
1394 /* the length of the call sequence emitted above. */
1395 /* Note: this requires the specific trampoline starts on a */
1396 /* kNaclAlignedment aligned address, which it does because */
1397 /* it's its own function that is aligned. */
1398 guint8 nop_buf[256];
1399 guint8 *nopbuf_aligned = ALIGN_TO (nop_buf, kNaClAlignment);
1400 guint8 *nopbuf_end = mono_arch_nacl_pad (nopbuf_aligned, kNaClAlignment - 7 - (call_len));
1401 emit_bytes (acfg, nopbuf_aligned, nopbuf_end - nopbuf_aligned);
1403 /* The trampoline is stored at the offset'th pointer, the -4 is */
1404 /* present because RIP relative addressing starts at the end of */
1405 /* the current instruction, while the label "." is relative to */
1406 /* the beginning of the current asm location, which in this case */
1407 /* is not the mov instruction, but the offset itself, due to the */
1408 /* way the bytes and ints are emitted here. */
1409 got_offset = (offset * sizeof(gpointer)) - 4;
1411 /* mov <OFFSET>(%rip), %r11d */
1412 emit_byte (acfg, '\x45');
1413 emit_byte (acfg, '\x8b');
1414 emit_byte (acfg, '\x1d');
1415 emit_symbol_diff (acfg, acfg->got_symbol, ".", got_offset);
1418 emit_bytes (acfg, call_start, call_len);
1420 /* The arg is stored at the offset+1 pointer, relative to beginning */
1421 /* of trampoline: 7 for mov, plus the call length, and 1 for push. */
1422 got_offset = ((offset + 1) * sizeof(gpointer)) + 7 + call_len + 1;
1424 /* We can't emit this data directly, hide in a "push imm32" */
1425 emit_byte (acfg, '\x68'); /* push */
1426 emit_symbol_diff (acfg, acfg->got_symbol, ".", got_offset);
1427 emit_alignment (acfg, kNaClAlignment);
1428 #endif /*__native_client_codegen__*/
1429 #elif defined(TARGET_ARM)
1433 /* This should be exactly 20 bytes long */
1436 ARM_PUSH (code, 0x5fff);
1437 ARM_LDR_IMM (code, ARMREG_R1, ARMREG_PC, 4);
1438 /* Load the value from the GOT */
1439 ARM_LDR_REG_REG (code, ARMREG_R1, ARMREG_PC, ARMREG_R1);
1441 ARM_BLX_REG (code, ARMREG_R1);
1443 g_assert (code - buf == 16);
1446 emit_bytes (acfg, buf, code - buf);
1448 * Only one offset is needed, since the second one would be equal to the
1451 emit_symbol_diff (acfg, acfg->got_symbol, ".", (offset * sizeof (gpointer)) - 4 + 4);
1452 //emit_symbol_diff (acfg, acfg->got_symbol, ".", ((offset + 1) * sizeof (gpointer)) - 4 + 8);
1453 #elif defined(TARGET_ARM64)
1454 arm64_emit_specific_trampoline (acfg, offset, tramp_size);
1455 #elif defined(TARGET_POWERPC)
1462 g_assert (!acfg->use_bin_writer);
1465 * PPC has no ip relative addressing, so we need to compute the address
1466 * of the mscorlib got. That is slow and complex, so instead, we store it
1467 * in the second got slot of every aot image. The caller already computed
1468 * the address of its got and placed it into r30.
1470 emit_unset_mode (acfg);
1471 /* Load mscorlib got address */
1472 fprintf (acfg->fp, "%s 0, %d(30)\n", PPC_LD_OP, (int)sizeof (gpointer));
1473 /* Load generic trampoline address */
1474 fprintf (acfg->fp, "lis 11, %d@h\n", (int)(offset * sizeof (gpointer)));
1475 fprintf (acfg->fp, "ori 11, 11, %d@l\n", (int)(offset * sizeof (gpointer)));
1476 fprintf (acfg->fp, "%s 11, 11, 0\n", PPC_LDX_OP);
1477 #ifdef PPC_USES_FUNCTION_DESCRIPTOR
1478 fprintf (acfg->fp, "%s 11, 0(11)\n", PPC_LD_OP);
1480 fprintf (acfg->fp, "mtctr 11\n");
1481 /* Load trampoline argument */
1482 /* On ppc, we pass it normally to the generic trampoline */
1483 fprintf (acfg->fp, "lis 11, %d@h\n", (int)((offset + 1) * sizeof (gpointer)));
1484 fprintf (acfg->fp, "ori 11, 11, %d@l\n", (int)((offset + 1) * sizeof (gpointer)));
1485 fprintf (acfg->fp, "%s 0, 11, 0\n", PPC_LDX_OP);
1486 /* Branch to generic trampoline */
1487 fprintf (acfg->fp, "bctr\n");
1489 #ifdef PPC_USES_FUNCTION_DESCRIPTOR
1490 *tramp_size = 10 * 4;
1492 *tramp_size = 9 * 4;
1494 #elif defined(TARGET_X86)
1498 /* Similar to the PPC code above */
1500 /* FIXME: Could this clobber the register needed by get_vcall_slot () ? */
1502 /* We clobber ECX, since EAX is used as MONO_ARCH_MONITOR_OBJECT_REG */
1503 #ifdef MONO_ARCH_MONITOR_OBJECT_REG
1504 g_assert (MONO_ARCH_MONITOR_OBJECT_REG != X86_ECX);
1505 #ifdef MONO_ARCH_MONITOR_LOCK_TAKEN_REG
1506 g_assert (MONO_ARCH_MONITOR_LOCK_TAKEN_REG != X86_ECX);
1511 /* Load mscorlib got address */
1512 x86_mov_reg_membase (code, X86_ECX, MONO_ARCH_GOT_REG, sizeof (gpointer), 4);
1513 /* Push trampoline argument */
1514 x86_push_membase (code, X86_ECX, (offset + 1) * sizeof (gpointer));
1515 /* Load generic trampoline address */
1516 x86_mov_reg_membase (code, X86_ECX, X86_ECX, offset * sizeof (gpointer), 4);
1517 /* Branch to generic trampoline */
1518 x86_jump_reg (code, X86_ECX);
1520 #ifdef __native_client_codegen__
1522 /* emit nops to next 32 byte alignment */
1523 int a = (~kNaClAlignmentMask) & ((code - buf) + kNaClAlignment - 1);
1524 while (code < (buf + a)) x86_nop(code);
1527 emit_bytes (acfg, buf, code - buf);
1529 *tramp_size = NACL_SIZE(17, kNaClAlignment);
1530 g_assert (code - buf == *tramp_size);
1532 g_assert_not_reached ();
1537 * arch_emit_unbox_trampoline:
1539 * Emit code for the unbox trampoline for METHOD used in the full-aot case.
1540 * CALL_TARGET is the symbol pointing to the native code of METHOD.
1543 arch_emit_unbox_trampoline (MonoAotCompile *acfg, MonoCompile *cfg, MonoMethod *method, const char *call_target)
1545 #if defined(TARGET_AMD64)
1550 this_reg = mono_arch_get_this_arg_reg (NULL);
1552 amd64_alu_reg_imm (code, X86_ADD, this_reg, sizeof (MonoObject));
1554 emit_bytes (acfg, buf, code - buf);
1556 if (acfg->llvm_separate) {
1557 emit_unset_mode (acfg);
1558 fprintf (acfg->fp, "jmp %s\n", call_target);
1560 emit_byte (acfg, '\xe9');
1561 emit_symbol_diff (acfg, call_target, ".", -4);
1563 #elif defined(TARGET_X86)
1570 x86_alu_membase_imm (code, X86_ADD, X86_ESP, this_pos, sizeof (MonoObject));
1572 emit_bytes (acfg, buf, code - buf);
1575 emit_byte (acfg, '\xe9');
1576 emit_symbol_diff (acfg, call_target, ".", -4);
1577 #elif defined(TARGET_ARM)
1581 if (acfg->thumb_mixed && cfg->compile_llvm) {
1582 fprintf (acfg->fp, "add r0, r0, #%d\n", (int)sizeof (MonoObject));
1583 fprintf (acfg->fp, "b %s\n", call_target);
1584 fprintf (acfg->fp, ".arm\n");
1585 fprintf (acfg->fp, ".align 2\n");
1591 ARM_ADD_REG_IMM8 (code, ARMREG_R0, ARMREG_R0, sizeof (MonoObject));
1593 emit_bytes (acfg, buf, code - buf);
1594 /* jump to method */
1595 if (acfg->use_bin_writer) {
1602 img_writer_emit_reloc (acfg->w, R_ARM_JUMP24, call_target, -8);
1603 emit_bytes (acfg, buf, 4);
1605 if (acfg->thumb_mixed && cfg->compile_llvm)
1606 fprintf (acfg->fp, "\n\tbx %s\n", call_target);
1608 fprintf (acfg->fp, "\n\tb %s\n", call_target);
1610 #elif defined(TARGET_ARM64)
1611 arm64_emit_unbox_trampoline (acfg, cfg, method, call_target);
1612 #elif defined(TARGET_POWERPC)
1615 g_assert (!acfg->use_bin_writer);
1617 fprintf (acfg->fp, "\n\taddi %d, %d, %d\n", this_pos, this_pos, (int)sizeof (MonoObject));
1618 fprintf (acfg->fp, "\n\tb %s\n", call_target);
1620 g_assert_not_reached ();
1625 * arch_emit_static_rgctx_trampoline:
1627 * Emit code for a static rgctx trampoline. OFFSET is the offset of the first of
1628 * two GOT slots which contain the rgctx argument, and the method to jump to.
1629 * TRAMP_SIZE is set to the size of the emitted trampoline.
1630 * These kinds of trampolines cannot be enumerated statically, since there could
1631 * be one trampoline per method instantiation, so we emit the same code for all
1632 * trampolines, and parameterize them using two GOT slots.
1635 arch_emit_static_rgctx_trampoline (MonoAotCompile *acfg, int offset, int *tramp_size)
1637 #if defined(TARGET_AMD64)
1638 #if defined(__default_codegen__)
1639 /* This should be exactly 13 bytes long */
1642 if (acfg->llvm_separate) {
1643 emit_unset_mode (acfg);
1644 fprintf (acfg->fp, "mov %s+%d(%%rip), %%r10\n", acfg->got_symbol, (int)(offset * sizeof (gpointer)));
1645 fprintf (acfg->fp, "jmp *%s+%d(%%rip)\n", acfg->got_symbol, (int)((offset + 1) * sizeof (gpointer)));
1647 /* mov <OFFSET>(%rip), %r10 */
1648 emit_byte (acfg, '\x4d');
1649 emit_byte (acfg, '\x8b');
1650 emit_byte (acfg, '\x15');
1651 emit_symbol_diff (acfg, acfg->got_symbol, ".", (offset * sizeof (gpointer)) - 4);
1653 /* jmp *<offset>(%rip) */
1654 emit_byte (acfg, '\xff');
1655 emit_byte (acfg, '\x25');
1656 emit_symbol_diff (acfg, acfg->got_symbol, ".", ((offset + 1) * sizeof (gpointer)) - 4);
1658 #elif defined(__native_client_codegen__)
1660 guint8 *buf_aligned = ALIGN_TO(buf, kNaClAlignment);
1661 guint8 *code = buf_aligned;
1663 /* mov <OFFSET>(%rip), %r10d */
1664 emit_byte (acfg, '\x45');
1665 emit_byte (acfg, '\x8b');
1666 emit_byte (acfg, '\x15');
1667 emit_symbol_diff (acfg, acfg->got_symbol, ".", (offset * sizeof (gpointer)) - 4);
1669 /* mov <OFFSET>(%rip), %r11d */
1670 emit_byte (acfg, '\x45');
1671 emit_byte (acfg, '\x8b');
1672 emit_byte (acfg, '\x1d');
1673 emit_symbol_diff (acfg, acfg->got_symbol, ".", ((offset + 1) * sizeof (gpointer)) - 4);
1676 amd64_jump_reg (code, AMD64_R11);
1677 emit_bytes (acfg, buf_aligned, code - buf_aligned);
1679 emit_alignment (acfg, kNaClAlignment);
1680 *tramp_size = kNaClAlignment;
1681 #endif /*__native_client_codegen__*/
1683 #elif defined(TARGET_ARM)
1687 /* This should be exactly 24 bytes long */
1690 /* Load rgctx value */
1691 ARM_LDR_IMM (code, ARMREG_IP, ARMREG_PC, 8);
1692 ARM_LDR_REG_REG (code, MONO_ARCH_RGCTX_REG, ARMREG_PC, ARMREG_IP);
1693 /* Load branch addr + branch */
1694 ARM_LDR_IMM (code, ARMREG_IP, ARMREG_PC, 4);
1695 ARM_LDR_REG_REG (code, ARMREG_PC, ARMREG_PC, ARMREG_IP);
1697 g_assert (code - buf == 16);
1700 emit_bytes (acfg, buf, code - buf);
1701 emit_symbol_diff (acfg, acfg->got_symbol, ".", (offset * sizeof (gpointer)) - 4 + 8);
1702 emit_symbol_diff (acfg, acfg->got_symbol, ".", ((offset + 1) * sizeof (gpointer)) - 4 + 4);
1703 #elif defined(TARGET_ARM64)
1704 arm64_emit_static_rgctx_trampoline (acfg, offset, tramp_size);
1705 #elif defined(TARGET_POWERPC)
1712 g_assert (!acfg->use_bin_writer);
1715 * PPC has no ip relative addressing, so we need to compute the address
1716 * of the mscorlib got. That is slow and complex, so instead, we store it
1717 * in the second got slot of every aot image. The caller already computed
1718 * the address of its got and placed it into r30.
1720 emit_unset_mode (acfg);
1721 /* Load mscorlib got address */
1722 fprintf (acfg->fp, "%s 0, %d(30)\n", PPC_LD_OP, (int)sizeof (gpointer));
1724 fprintf (acfg->fp, "lis 11, %d@h\n", (int)(offset * sizeof (gpointer)));
1725 fprintf (acfg->fp, "ori 11, 11, %d@l\n", (int)(offset * sizeof (gpointer)));
1726 fprintf (acfg->fp, "%s %d, 11, 0\n", PPC_LDX_OP, MONO_ARCH_RGCTX_REG);
1727 /* Load target address */
1728 fprintf (acfg->fp, "lis 11, %d@h\n", (int)((offset + 1) * sizeof (gpointer)));
1729 fprintf (acfg->fp, "ori 11, 11, %d@l\n", (int)((offset + 1) * sizeof (gpointer)));
1730 fprintf (acfg->fp, "%s 11, 11, 0\n", PPC_LDX_OP);
1731 #ifdef PPC_USES_FUNCTION_DESCRIPTOR
1732 fprintf (acfg->fp, "%s 2, %d(11)\n", PPC_LD_OP, (int)sizeof (gpointer));
1733 fprintf (acfg->fp, "%s 11, 0(11)\n", PPC_LD_OP);
1735 fprintf (acfg->fp, "mtctr 11\n");
1736 /* Branch to the target address */
1737 fprintf (acfg->fp, "bctr\n");
1739 #ifdef PPC_USES_FUNCTION_DESCRIPTOR
1740 *tramp_size = 11 * 4;
1742 *tramp_size = 9 * 4;
1745 #elif defined(TARGET_X86)
1749 /* Similar to the PPC code above */
1751 g_assert (MONO_ARCH_RGCTX_REG != X86_ECX);
1754 /* Load mscorlib got address */
1755 x86_mov_reg_membase (code, X86_ECX, MONO_ARCH_GOT_REG, sizeof (gpointer), 4);
1757 x86_mov_reg_membase (code, MONO_ARCH_RGCTX_REG, X86_ECX, offset * sizeof (gpointer), 4);
1758 /* Branch to the target address */
1759 x86_jump_membase (code, X86_ECX, (offset + 1) * sizeof (gpointer));
1761 #ifdef __native_client_codegen__
1763 /* emit nops to next 32 byte alignment */
1764 int a = (~kNaClAlignmentMask) & ((code - buf) + kNaClAlignment - 1);
1765 while (code < (buf + a)) x86_nop(code);
1769 emit_bytes (acfg, buf, code - buf);
1771 *tramp_size = NACL_SIZE (15, kNaClAlignment);
1772 g_assert (code - buf == *tramp_size);
1774 g_assert_not_reached ();
1779 * arch_emit_imt_thunk:
1781 * Emit an IMT thunk usable in full-aot mode. The thunk uses 1 got slot which
1782 * points to an array of pointer pairs. The pairs of the form [key, ptr], where
1783 * key is the IMT key, and ptr holds the address of a memory location holding
1784 * the address to branch to if the IMT arg matches the key. The array is
1785 * terminated by a pair whose key is NULL, and whose ptr is the address of the
1787 * TRAMP_SIZE is set to the size of the emitted trampoline.
1790 arch_emit_imt_thunk (MonoAotCompile *acfg, int offset, int *tramp_size)
1792 #if defined(TARGET_AMD64)
1794 #if defined(__native_client_codegen__)
1797 guint8 *labels [16];
1799 guint8 *mov_buf_ptr = mov_buf;
1801 const int kSizeOfMove = 7;
1802 #if defined(__default_codegen__)
1803 code = buf = g_malloc (256);
1804 #elif defined(__native_client_codegen__)
1805 buf_alloc = g_malloc (256 + kNaClAlignment + kSizeOfMove);
1806 buf = ((guint)buf_alloc + kNaClAlignment) & ~kNaClAlignmentMask;
1807 /* The RIP relative move below is emitted first */
1812 /* FIXME: Optimize this, i.e. use binary search etc. */
1813 /* Maybe move the body into a separate function (slower, but much smaller) */
1815 /* MONO_ARCH_IMT_SCRATCH_REG is a free register */
1817 if (acfg->llvm_separate) {
1818 emit_unset_mode (acfg);
1819 fprintf (acfg->fp, "mov %s+%d(%%rip), %s\n", acfg->got_symbol, (int)(offset * sizeof (gpointer)), mono_arch_regname (MONO_ARCH_IMT_SCRATCH_REG));
1823 amd64_alu_membase_imm (code, X86_CMP, MONO_ARCH_IMT_SCRATCH_REG, 0, 0);
1825 amd64_branch8 (code, X86_CC_Z, 0, FALSE);
1828 amd64_alu_membase_reg_size (code, X86_CMP, MONO_ARCH_IMT_SCRATCH_REG, 0, MONO_ARCH_IMT_REG, sizeof (gpointer));
1830 amd64_branch8 (code, X86_CC_Z, 0, FALSE);
1833 amd64_alu_reg_imm (code, X86_ADD, MONO_ARCH_IMT_SCRATCH_REG, 2 * sizeof (gpointer));
1834 amd64_jump_code (code, labels [0]);
1837 mono_amd64_patch (labels [2], code);
1838 amd64_mov_reg_membase (code, MONO_ARCH_IMT_SCRATCH_REG, MONO_ARCH_IMT_SCRATCH_REG, sizeof (gpointer), sizeof (gpointer));
1839 amd64_jump_membase (code, MONO_ARCH_IMT_SCRATCH_REG, 0);
1842 mono_amd64_patch (labels [1], code);
1843 /* Load fail tramp */
1844 amd64_alu_reg_imm (code, X86_ADD, MONO_ARCH_IMT_SCRATCH_REG, sizeof (gpointer));
1845 /* Check if there is a fail tramp */
1846 amd64_alu_membase_imm (code, X86_CMP, MONO_ARCH_IMT_SCRATCH_REG, 0, 0);
1848 amd64_branch8 (code, X86_CC_Z, 0, FALSE);
1849 /* Jump to fail tramp */
1850 amd64_jump_membase (code, MONO_ARCH_IMT_SCRATCH_REG, 0);
1853 mono_amd64_patch (labels [3], code);
1854 x86_breakpoint (code);
1856 if (!acfg->llvm_separate) {
1857 /* mov <OFFSET>(%rip), MONO_ARCH_IMT_SCRATCH_REG */
1858 amd64_emit_rex (mov_buf_ptr, sizeof(gpointer), MONO_ARCH_IMT_SCRATCH_REG, 0, AMD64_RIP);
1859 *(mov_buf_ptr)++ = (unsigned char)0x8b; /* mov opcode */
1860 x86_address_byte (mov_buf_ptr, 0, MONO_ARCH_IMT_SCRATCH_REG & 0x7, 5);
1861 emit_bytes (acfg, mov_buf, mov_buf_ptr - mov_buf);
1862 emit_symbol_diff (acfg, acfg->got_symbol, ".", (offset * sizeof (gpointer)) - 4);
1864 emit_bytes (acfg, buf, code - buf);
1866 *tramp_size = code - buf + kSizeOfMove;
1867 #if defined(__native_client_codegen__)
1868 /* The tramp will be padded to the next kNaClAlignment bundle. */
1869 *tramp_size = ALIGN_TO ((*tramp_size), kNaClAlignment);
1872 #if defined(__default_codegen__)
1874 #elif defined(__native_client_codegen__)
1878 #elif defined(TARGET_X86)
1880 #ifdef __native_client_codegen__
1883 guint8 *labels [16];
1885 #if defined(__default_codegen__)
1886 code = buf = g_malloc (256);
1887 #elif defined(__native_client_codegen__)
1888 buf_alloc = g_malloc (256 + kNaClAlignment);
1889 code = buf = ((guint)buf_alloc + kNaClAlignment) & ~kNaClAlignmentMask;
1892 /* Allocate a temporary stack slot */
1893 x86_push_reg (code, X86_EAX);
1895 x86_push_reg (code, X86_EAX);
1897 /* Load mscorlib got address */
1898 x86_mov_reg_membase (code, X86_EAX, MONO_ARCH_GOT_REG, sizeof (gpointer), 4);
1900 x86_mov_reg_membase (code, X86_EAX, X86_EAX, offset * sizeof (gpointer), 4);
1903 x86_alu_membase_imm (code, X86_CMP, X86_EAX, 0, 0);
1905 x86_branch8 (code, X86_CC_Z, FALSE, 0);
1908 x86_alu_membase_reg (code, X86_CMP, X86_EAX, 0, MONO_ARCH_IMT_REG);
1910 x86_branch8 (code, X86_CC_Z, FALSE, 0);
1913 x86_alu_reg_imm (code, X86_ADD, X86_EAX, 2 * sizeof (gpointer));
1914 x86_jump_code (code, labels [0]);
1917 mono_x86_patch (labels [2], code);
1918 x86_mov_reg_membase (code, X86_EAX, X86_EAX, sizeof (gpointer), 4);
1919 x86_mov_reg_membase (code, X86_EAX, X86_EAX, 0, 4);
1920 /* Save the target address to the temporary stack location */
1921 x86_mov_membase_reg (code, X86_ESP, 4, X86_EAX, 4);
1923 x86_pop_reg (code, X86_EAX);
1924 /* Jump to the target address */
1928 mono_x86_patch (labels [1], code);
1929 /* Load fail tramp */
1930 x86_mov_reg_membase (code, X86_EAX, X86_EAX, sizeof (gpointer), 4);
1931 x86_alu_membase_imm (code, X86_CMP, X86_EAX, 0, 0);
1933 x86_branch8 (code, X86_CC_Z, FALSE, 0);
1934 /* Jump to fail tramp */
1935 x86_mov_membase_reg (code, X86_ESP, 4, X86_EAX, 4);
1936 x86_pop_reg (code, X86_EAX);
1940 mono_x86_patch (labels [3], code);
1941 x86_breakpoint (code);
1943 #ifdef __native_client_codegen__
1945 /* emit nops to next 32 byte alignment */
1946 int a = (~kNaClAlignmentMask) & ((code - buf) + kNaClAlignment - 1);
1947 while (code < (buf + a)) x86_nop(code);
1950 emit_bytes (acfg, buf, code - buf);
1952 *tramp_size = code - buf;
1954 #if defined(__default_codegen__)
1956 #elif defined(__native_client_codegen__)
1960 #elif defined(TARGET_ARM)
1962 guint8 *code, *code2, *labels [16];
1966 /* The IMT method is in v5 */
1968 /* Need at least two free registers, plus a slot for storing the pc */
1969 ARM_PUSH (code, (1 << ARMREG_R0)|(1 << ARMREG_R1)|(1 << ARMREG_R2));
1971 /* Load the parameter from the GOT */
1972 ARM_LDR_IMM (code, ARMREG_R0, ARMREG_PC, 0);
1973 ARM_LDR_REG_REG (code, ARMREG_R0, ARMREG_PC, ARMREG_R0);
1976 ARM_LDR_IMM (code, ARMREG_R1, ARMREG_R0, 0);
1977 ARM_CMP_REG_REG (code, ARMREG_R1, ARMREG_V5);
1979 ARM_B_COND (code, ARMCOND_EQ, 0);
1981 /* End-of-loop check */
1982 ARM_CMP_REG_IMM (code, ARMREG_R1, 0, 0);
1984 ARM_B_COND (code, ARMCOND_EQ, 0);
1987 ARM_ADD_REG_IMM8 (code, ARMREG_R0, ARMREG_R0, sizeof (gpointer) * 2);
1990 arm_patch (labels [4], labels [1]);
1993 arm_patch (labels [2], code);
1994 ARM_LDR_IMM (code, ARMREG_R0, ARMREG_R0, 4);
1995 ARM_LDR_IMM (code, ARMREG_R0, ARMREG_R0, 0);
1996 /* Save it to the third stack slot */
1997 ARM_STR_IMM (code, ARMREG_R0, ARMREG_SP, 8);
1998 /* Restore the registers and branch */
1999 ARM_POP (code, (1 << ARMREG_R0)|(1 << ARMREG_R1)|(1 << ARMREG_PC));
2002 arm_patch (labels [3], code);
2003 ARM_LDR_IMM (code, ARMREG_R0, ARMREG_R0, 4);
2004 ARM_STR_IMM (code, ARMREG_R0, ARMREG_SP, 8);
2005 ARM_POP (code, (1 << ARMREG_R0)|(1 << ARMREG_R1)|(1 << ARMREG_PC));
2009 ARM_LDR_IMM (code2, ARMREG_R0, ARMREG_PC, (code - (labels [0] + 8)));
2011 emit_bytes (acfg, buf, code - buf);
2012 emit_symbol_diff (acfg, acfg->got_symbol, ".", (offset * sizeof (gpointer)) + (code - (labels [0] + 8)) - 4);
2014 *tramp_size = code - buf + 4;
2015 #elif defined(TARGET_ARM64)
2016 arm64_emit_imt_thunk (acfg, offset, tramp_size);
2017 #elif defined(TARGET_POWERPC)
2019 guint8 *code, *labels [16];
2023 /* Load the mscorlib got address */
2024 ppc_ldptr (code, ppc_r12, sizeof (gpointer), ppc_r30);
2025 /* Load the parameter from the GOT */
2026 ppc_load (code, ppc_r0, offset * sizeof (gpointer));
2027 ppc_ldptr_indexed (code, ppc_r12, ppc_r12, ppc_r0);
2029 /* Load and check key */
2031 ppc_ldptr (code, ppc_r0, 0, ppc_r12);
2032 ppc_cmp (code, 0, sizeof (gpointer) == 8 ? 1 : 0, ppc_r0, MONO_ARCH_IMT_REG);
2034 ppc_bc (code, PPC_BR_TRUE, PPC_BR_EQ, 0);
2036 /* End-of-loop check */
2037 ppc_cmpi (code, 0, sizeof (gpointer) == 8 ? 1 : 0, ppc_r0, 0);
2039 ppc_bc (code, PPC_BR_TRUE, PPC_BR_EQ, 0);
2042 ppc_addi (code, ppc_r12, ppc_r12, 2 * sizeof (gpointer));
2045 mono_ppc_patch (labels [4], labels [1]);
2048 mono_ppc_patch (labels [2], code);
2049 ppc_ldptr (code, ppc_r12, sizeof (gpointer), ppc_r12);
2050 /* r12 now contains the value of the vtable slot */
2051 /* this is not a function descriptor on ppc64 */
2052 ppc_ldptr (code, ppc_r12, 0, ppc_r12);
2053 ppc_mtctr (code, ppc_r12);
2054 ppc_bcctr (code, PPC_BR_ALWAYS, 0);
2057 mono_ppc_patch (labels [3], code);
2061 *tramp_size = code - buf;
2063 emit_bytes (acfg, buf, code - buf);
2065 g_assert_not_reached ();
2070 * arch_emit_gsharedvt_arg_trampoline:
2072 * Emit code for a gsharedvt arg trampoline. OFFSET is the offset of the first of
2073 * two GOT slots which contain the argument, and the code to jump to.
2074 * TRAMP_SIZE is set to the size of the emitted trampoline.
2075 * These kinds of trampolines cannot be enumerated statically, since there could
2076 * be one trampoline per method instantiation, so we emit the same code for all
2077 * trampolines, and parameterize them using two GOT slots.
2080 arch_emit_gsharedvt_arg_trampoline (MonoAotCompile *acfg, int offset, int *tramp_size)
2082 #if defined(TARGET_X86)
2086 /* Similar to the PPC code above */
2088 g_assert (MONO_ARCH_RGCTX_REG != X86_ECX);
2091 /* Load mscorlib got address */
2092 x86_mov_reg_membase (code, X86_ECX, MONO_ARCH_GOT_REG, sizeof (gpointer), 4);
2094 x86_mov_reg_membase (code, X86_EAX, X86_ECX, offset * sizeof (gpointer), 4);
2095 /* Branch to the target address */
2096 x86_jump_membase (code, X86_ECX, (offset + 1) * sizeof (gpointer));
2098 #ifdef __native_client_codegen__
2100 /* emit nops to next 32 byte alignment */
2101 int a = (~kNaClAlignmentMask) & ((code - buf) + kNaClAlignment - 1);
2102 while (code < (buf + a)) x86_nop(code);
2106 emit_bytes (acfg, buf, code - buf);
2108 *tramp_size = NACL_SIZE (15, kNaClAlignment);
2109 g_assert (code - buf == *tramp_size);
2110 #elif defined(TARGET_ARM)
2114 /* The same as mono_arch_get_gsharedvt_arg_trampoline (), but for AOT */
2115 /* Similar to arch_emit_specific_trampoline () */
2118 ARM_PUSH (code, (1 << ARMREG_R0) | (1 << ARMREG_R1) | (1 << ARMREG_R2) | (1 << ARMREG_R3));
2119 ARM_LDR_IMM (code, ARMREG_R1, ARMREG_PC, 8);
2120 /* Load the arg value from the GOT */
2121 ARM_LDR_REG_REG (code, ARMREG_R0, ARMREG_PC, ARMREG_R1);
2122 /* Load the addr from the GOT */
2123 ARM_LDR_REG_REG (code, ARMREG_R1, ARMREG_PC, ARMREG_R1);
2125 ARM_BX (code, ARMREG_R1);
2127 g_assert (code - buf == 20);
2130 emit_bytes (acfg, buf, code - buf);
2131 emit_symbol_diff (acfg, acfg->got_symbol, ".", (offset * sizeof (gpointer)) + 4);
2132 #elif defined(TARGET_ARM64)
2133 arm64_emit_gsharedvt_arg_trampoline (acfg, offset, tramp_size);
2135 g_assert_not_reached ();
2140 arch_emit_autoreg (MonoAotCompile *acfg, char *symbol)
2142 #if defined(TARGET_POWERPC) && defined(__mono_ilp32__)
2143 /* Based on code generated by gcc */
2144 emit_unset_mode (acfg);
2147 #if defined(_MSC_VER) || defined(MONO_CROSS_COMPILE)
2148 ".section .ctors,\"aw\",@progbits\n"
2152 ".section .opd,\"aw\"\n"
2155 ".long .%s,.TOC.@tocbase32\n"
2158 ".type .%s,@function\n"
2160 ".%s:\n", symbol, symbol, symbol, symbol, symbol, symbol, symbol, symbol);
2162 ".section .ctors,\"aw\",@progbits\n"
2166 ".section .opd,\"aw\"\n"
2169 ".long .%1$s,.TOC.@tocbase32\n"
2170 ".size %1$s,.-%1$s\n"
2172 ".type .%1$s,@function\n"
2174 ".%1$s:\n", symbol);
2185 "lis 3, .Lglobals@h\n"
2186 "ori 3, 3, .Lglobals@l\n"
2187 "bl .mono_aot_register_module\n"
2195 #if defined(_MSC_VER) || defined(MONO_CROSS_COMPILE)
2197 ".size .%s,.-.%s\n", symbol, symbol);
2200 ".size .%1$s,.-.%1$s\n", symbol);
2206 /* END OF ARCH SPECIFIC CODE */
2209 mono_get_field_token (MonoClassField *field)
2211 MonoClass *klass = field->parent;
2214 for (i = 0; i < klass->field.count; ++i) {
2215 if (field == &klass->fields [i])
2216 return MONO_TOKEN_FIELD_DEF | (klass->field.first + 1 + i);
2219 g_assert_not_reached ();
2224 encode_value (gint32 value, guint8 *buf, guint8 **endbuf)
2228 //printf ("ENCODE: %d 0x%x.\n", value, value);
2231 * Same encoding as the one used in the metadata, extended to handle values
2232 * greater than 0x1fffffff.
2234 if ((value >= 0) && (value <= 127))
2236 else if ((value >= 0) && (value <= 16383)) {
2237 p [0] = 0x80 | (value >> 8);
2238 p [1] = value & 0xff;
2240 } else if ((value >= 0) && (value <= 0x1fffffff)) {
2241 p [0] = (value >> 24) | 0xc0;
2242 p [1] = (value >> 16) & 0xff;
2243 p [2] = (value >> 8) & 0xff;
2244 p [3] = value & 0xff;
2249 p [1] = (value >> 24) & 0xff;
2250 p [2] = (value >> 16) & 0xff;
2251 p [3] = (value >> 8) & 0xff;
2252 p [4] = value & 0xff;
2260 stream_init (MonoDynamicStream *sh)
2263 sh->alloc_size = 4096;
2264 sh->data = g_malloc (4096);
2266 /* So offsets are > 0 */
2272 make_room_in_stream (MonoDynamicStream *stream, int size)
2274 if (size <= stream->alloc_size)
2277 while (stream->alloc_size <= size) {
2278 if (stream->alloc_size < 4096)
2279 stream->alloc_size = 4096;
2281 stream->alloc_size *= 2;
2284 stream->data = g_realloc (stream->data, stream->alloc_size);
2288 add_stream_data (MonoDynamicStream *stream, const char *data, guint32 len)
2292 make_room_in_stream (stream, stream->index + len);
2293 memcpy (stream->data + stream->index, data, len);
2294 idx = stream->index;
2295 stream->index += len;
2302 * Add data to the binary blob inside the aot image. Returns the offset inside the
2303 * blob where the data was stored.
2306 add_to_blob (MonoAotCompile *acfg, const guint8 *data, guint32 data_len)
2308 if (acfg->blob.alloc_size == 0)
2309 stream_init (&acfg->blob);
2311 return add_stream_data (&acfg->blob, (char*)data, data_len);
2315 add_to_blob_aligned (MonoAotCompile *acfg, const guint8 *data, guint32 data_len, guint32 align)
2320 if (acfg->blob.alloc_size == 0)
2321 stream_init (&acfg->blob);
2323 count = acfg->blob.index % align;
2325 /* we assume the stream data will be aligned */
2327 add_stream_data (&acfg->blob, buf, 4 - count);
2329 return add_stream_data (&acfg->blob, (char*)data, data_len);
2333 * emit_offset_table:
2335 * Emit a table of increasing offsets in a compact form using differential encoding.
2336 * There is an index entry for each GROUP_SIZE number of entries. The greater the
2337 * group size, the more compact the table becomes, but the slower it becomes to compute
2338 * a given entry. Returns the size of the table.
2341 emit_offset_table (MonoAotCompile *acfg, int noffsets, int group_size, gint32 *offsets)
2343 gint32 current_offset;
2344 int i, buf_size, ngroups, index_entry_size;
2346 guint32 *index_offsets;
2348 ngroups = (noffsets + (group_size - 1)) / group_size;
2350 index_offsets = g_new0 (guint32, ngroups);
2352 buf_size = noffsets * 4;
2353 p = buf = g_malloc0 (buf_size);
2356 for (i = 0; i < noffsets; ++i) {
2357 //printf ("D: %d -> %d\n", i, offsets [i]);
2358 if ((i % group_size) == 0) {
2359 index_offsets [i / group_size] = p - buf;
2360 /* Emit the full value for these entries */
2361 encode_value (offsets [i], p, &p);
2363 /* The offsets are allowed to be non-increasing */
2364 //g_assert (offsets [i] >= current_offset);
2365 encode_value (offsets [i] - current_offset, p, &p);
2367 current_offset = offsets [i];
2370 if (ngroups && index_offsets [ngroups - 1] < 65000)
2371 index_entry_size = 2;
2373 index_entry_size = 4;
2375 /* Emit the header */
2376 emit_int32 (acfg, noffsets);
2377 emit_int32 (acfg, group_size);
2378 emit_int32 (acfg, ngroups);
2379 emit_int32 (acfg, index_entry_size);
2381 /* Emit the index */
2382 for (i = 0; i < ngroups; ++i) {
2383 if (index_entry_size == 2)
2384 emit_int16 (acfg, index_offsets [i]);
2386 emit_int32 (acfg, index_offsets [i]);
2390 emit_bytes (acfg, buf, p - buf);
2392 return (int)(p - buf) + (ngroups * 4);
2396 get_image_index (MonoAotCompile *cfg, MonoImage *image)
2400 index = GPOINTER_TO_UINT (g_hash_table_lookup (cfg->image_hash, image));
2404 index = g_hash_table_size (cfg->image_hash);
2405 g_hash_table_insert (cfg->image_hash, image, GUINT_TO_POINTER (index + 1));
2406 g_ptr_array_add (cfg->image_table, image);
2412 find_typespec_for_class (MonoAotCompile *acfg, MonoClass *klass)
2415 int len = acfg->image->tables [MONO_TABLE_TYPESPEC].rows;
2417 /* FIXME: Search referenced images as well */
2418 if (!acfg->typespec_classes) {
2419 acfg->typespec_classes = mono_mempool_alloc0 (acfg->mempool, sizeof (MonoClass*) * len);
2420 for (i = 0; i < len; ++i) {
2422 acfg->typespec_classes [i] = mono_class_get_and_inflate_typespec_checked (acfg->image, MONO_TOKEN_TYPE_SPEC | (i + 1), NULL, &error);
2423 g_assert (mono_error_ok (&error)); /* FIXME error handling */
2426 for (i = 0; i < len; ++i) {
2427 if (acfg->typespec_classes [i] == klass)
2432 return MONO_TOKEN_TYPE_SPEC | (i + 1);
2438 encode_method_ref (MonoAotCompile *acfg, MonoMethod *method, guint8 *buf, guint8 **endbuf);
2441 encode_klass_ref (MonoAotCompile *acfg, MonoClass *klass, guint8 *buf, guint8 **endbuf);
2444 encode_ginst (MonoAotCompile *acfg, MonoGenericInst *inst, guint8 *buf, guint8 **endbuf);
2447 encode_type (MonoAotCompile *acfg, MonoType *t, guint8 *buf, guint8 **endbuf);
2450 encode_klass_ref_inner (MonoAotCompile *acfg, MonoClass *klass, guint8 *buf, guint8 **endbuf)
2455 * The encoding begins with one of the MONO_AOT_TYPEREF values, followed by additional
2459 if (klass->generic_class) {
2461 g_assert (klass->type_token);
2463 /* Find a typespec for a class if possible */
2464 token = find_typespec_for_class (acfg, klass);
2466 encode_value (MONO_AOT_TYPEREF_TYPESPEC_TOKEN, p, &p);
2467 encode_value (token, p, &p);
2469 MonoClass *gclass = klass->generic_class->container_class;
2470 MonoGenericInst *inst = klass->generic_class->context.class_inst;
2471 static int count = 0;
2474 encode_value (MONO_AOT_TYPEREF_GINST, p, &p);
2475 encode_klass_ref (acfg, gclass, p, &p);
2476 encode_ginst (acfg, inst, p, &p);
2480 } else if (klass->type_token) {
2481 int iindex = get_image_index (acfg, klass->image);
2483 g_assert (mono_metadata_token_code (klass->type_token) == MONO_TOKEN_TYPE_DEF);
2485 encode_value (MONO_AOT_TYPEREF_TYPEDEF_INDEX, p, &p);
2486 encode_value (klass->type_token - MONO_TOKEN_TYPE_DEF, p, &p);
2488 encode_value (MONO_AOT_TYPEREF_TYPEDEF_INDEX_IMAGE, p, &p);
2489 encode_value (klass->type_token - MONO_TOKEN_TYPE_DEF, p, &p);
2490 encode_value (get_image_index (acfg, klass->image), p, &p);
2492 } else if ((klass->byval_arg.type == MONO_TYPE_VAR) || (klass->byval_arg.type == MONO_TYPE_MVAR)) {
2493 MonoGenericContainer *container = mono_type_get_generic_param_owner (&klass->byval_arg);
2494 MonoGenericParam *par = klass->byval_arg.data.generic_param;
2496 encode_value (MONO_AOT_TYPEREF_VAR, p, &p);
2497 encode_value (klass->byval_arg.type, p, &p);
2498 encode_value (mono_type_get_generic_param_num (&klass->byval_arg), p, &p);
2500 encode_value (container ? 1 : 0, p, &p);
2502 encode_value (container->is_method, p, &p);
2503 g_assert (par->gshared_constraint == 0);
2504 if (container->is_method)
2505 encode_method_ref (acfg, container->owner.method, p, &p);
2507 encode_klass_ref (acfg, container->owner.klass, p, &p);
2509 encode_value (par->gshared_constraint, p, &p);
2511 } else if (klass->byval_arg.type == MONO_TYPE_PTR) {
2512 encode_value (MONO_AOT_TYPEREF_PTR, p, &p);
2513 encode_type (acfg, &klass->byval_arg, p, &p);
2516 g_assert (klass->rank > 0);
2517 encode_value (MONO_AOT_TYPEREF_ARRAY, p, &p);
2518 encode_value (klass->rank, p, &p);
2519 encode_klass_ref (acfg, klass->element_class, p, &p);
2527 * Encode a reference to KLASS. We use our home-grown encoding instead of the
2528 * standard metadata encoding.
2531 encode_klass_ref (MonoAotCompile *acfg, MonoClass *klass, guint8 *buf, guint8 **endbuf)
2533 gboolean shared = FALSE;
2536 * The encoding of generic instances is large so emit them only once.
2538 if (klass->generic_class) {
2540 g_assert (klass->type_token);
2542 /* Find a typespec for a class if possible */
2543 token = find_typespec_for_class (acfg, klass);
2546 } else if ((klass->byval_arg.type == MONO_TYPE_VAR) || (klass->byval_arg.type == MONO_TYPE_MVAR)) {
2551 guint offset = GPOINTER_TO_UINT (g_hash_table_lookup (acfg->klass_blob_hash, klass));
2555 buf2 = g_malloc (1024);
2558 encode_klass_ref_inner (acfg, klass, p, &p);
2559 g_assert (p - buf2 < 1024);
2561 offset = add_to_blob (acfg, buf2, p - buf2);
2564 g_hash_table_insert (acfg->klass_blob_hash, klass, GUINT_TO_POINTER (offset + 1));
2570 encode_value (MONO_AOT_TYPEREF_BLOB_INDEX, p, &p);
2571 encode_value (offset, p, &p);
2576 encode_klass_ref_inner (acfg, klass, buf, endbuf);
2580 encode_field_info (MonoAotCompile *cfg, MonoClassField *field, guint8 *buf, guint8 **endbuf)
2582 guint32 token = mono_get_field_token (field);
2585 encode_klass_ref (cfg, field->parent, p, &p);
2586 g_assert (mono_metadata_token_code (token) == MONO_TOKEN_FIELD_DEF);
2587 encode_value (token - MONO_TOKEN_FIELD_DEF, p, &p);
2592 encode_ginst (MonoAotCompile *acfg, MonoGenericInst *inst, guint8 *buf, guint8 **endbuf)
2597 encode_value (inst->type_argc, p, &p);
2598 for (i = 0; i < inst->type_argc; ++i)
2599 encode_klass_ref (acfg, mono_class_from_mono_type (inst->type_argv [i]), p, &p);
2604 encode_generic_context (MonoAotCompile *acfg, MonoGenericContext *context, guint8 *buf, guint8 **endbuf)
2607 MonoGenericInst *inst;
2609 inst = context->class_inst;
2611 g_assert (inst->type_argc);
2612 encode_ginst (acfg, inst, p, &p);
2614 encode_value (0, p, &p);
2616 inst = context->method_inst;
2618 g_assert (inst->type_argc);
2619 encode_ginst (acfg, inst, p, &p);
2621 encode_value (0, p, &p);
2627 encode_type (MonoAotCompile *acfg, MonoType *t, guint8 *buf, guint8 **endbuf)
2631 g_assert (t->num_mods == 0);
2632 /* t->attrs can be ignored */
2633 //g_assert (t->attrs == 0);
2636 *p = MONO_TYPE_PINNED;
2640 *p = MONO_TYPE_BYREF;
2648 case MONO_TYPE_VOID:
2649 case MONO_TYPE_BOOLEAN:
2650 case MONO_TYPE_CHAR:
2663 case MONO_TYPE_STRING:
2664 case MONO_TYPE_OBJECT:
2665 case MONO_TYPE_TYPEDBYREF:
2667 case MONO_TYPE_VALUETYPE:
2668 case MONO_TYPE_CLASS:
2669 encode_klass_ref (acfg, mono_class_from_mono_type (t), p, &p);
2671 case MONO_TYPE_SZARRAY:
2672 encode_klass_ref (acfg, t->data.klass, p, &p);
2675 encode_type (acfg, t->data.type, p, &p);
2677 case MONO_TYPE_GENERICINST: {
2678 MonoClass *gclass = t->data.generic_class->container_class;
2679 MonoGenericInst *inst = t->data.generic_class->context.class_inst;
2681 encode_klass_ref (acfg, gclass, p, &p);
2682 encode_ginst (acfg, inst, p, &p);
2685 case MONO_TYPE_ARRAY: {
2686 MonoArrayType *array = t->data.array;
2689 encode_klass_ref (acfg, array->eklass, p, &p);
2690 encode_value (array->rank, p, &p);
2691 encode_value (array->numsizes, p, &p);
2692 for (i = 0; i < array->numsizes; ++i)
2693 encode_value (array->sizes [i], p, &p);
2694 encode_value (array->numlobounds, p, &p);
2695 for (i = 0; i < array->numlobounds; ++i)
2696 encode_value (array->lobounds [i], p, &p);
2700 case MONO_TYPE_MVAR:
2701 encode_klass_ref (acfg, mono_class_from_mono_type (t), p, &p);
2704 g_assert_not_reached ();
2711 encode_signature (MonoAotCompile *acfg, MonoMethodSignature *sig, guint8 *buf, guint8 **endbuf)
2717 /* Similar to the metadata encoding */
2718 if (sig->generic_param_count)
2722 if (sig->explicit_this)
2724 flags |= (sig->call_convention & 0x0F);
2728 if (sig->generic_param_count)
2729 encode_value (sig->generic_param_count, p, &p);
2730 encode_value (sig->param_count, p, &p);
2732 encode_type (acfg, sig->ret, p, &p);
2733 for (i = 0; i < sig->param_count; ++i) {
2734 if (sig->sentinelpos == i) {
2735 *p = MONO_TYPE_SENTINEL;
2738 encode_type (acfg, sig->params [i], p, &p);
2744 #define MAX_IMAGE_INDEX 250
2747 encode_method_ref (MonoAotCompile *acfg, MonoMethod *method, guint8 *buf, guint8 **endbuf)
2749 guint32 image_index = get_image_index (acfg, method->klass->image);
2750 guint32 token = method->token;
2751 MonoJumpInfoToken *ji;
2755 * The encoding for most methods is as follows:
2756 * - image index encoded as a leb128
2757 * - token index encoded as a leb128
2758 * Values of image index >= MONO_AOT_METHODREF_MIN are used to mark additional
2759 * types of method encodings.
2762 /* Mark methods which can't use aot trampolines because they need the further
2763 * processing in mono_magic_trampoline () which requires a MonoMethod*.
2765 if ((method->is_generic && (method->flags & METHOD_ATTRIBUTE_VIRTUAL)) ||
2766 (method->iflags & METHOD_IMPL_ATTRIBUTE_SYNCHRONIZED))
2767 encode_value ((MONO_AOT_METHODREF_NO_AOT_TRAMPOLINE << 24), p, &p);
2769 if (method->wrapper_type) {
2770 encode_value ((MONO_AOT_METHODREF_WRAPPER << 24), p, &p);
2772 encode_value (method->wrapper_type, p, &p);
2774 switch (method->wrapper_type) {
2775 case MONO_WRAPPER_REMOTING_INVOKE:
2776 case MONO_WRAPPER_REMOTING_INVOKE_WITH_CHECK:
2777 case MONO_WRAPPER_XDOMAIN_INVOKE: {
2780 m = mono_marshal_method_from_wrapper (method);
2782 encode_method_ref (acfg, m, p, &p);
2785 case MONO_WRAPPER_PROXY_ISINST:
2786 case MONO_WRAPPER_LDFLD:
2787 case MONO_WRAPPER_LDFLDA:
2788 case MONO_WRAPPER_STFLD:
2789 case MONO_WRAPPER_ISINST: {
2790 WrapperInfo *info = mono_marshal_get_wrapper_info (method);
2793 encode_klass_ref (acfg, info->d.proxy.klass, p, &p);
2796 case MONO_WRAPPER_LDFLD_REMOTE:
2797 case MONO_WRAPPER_STFLD_REMOTE:
2799 case MONO_WRAPPER_ALLOC: {
2800 AllocatorWrapperInfo *info = mono_marshal_get_wrapper_info (method);
2802 /* The GC name is saved once in MonoAotFileInfo */
2803 g_assert (info->alloc_type != -1);
2804 encode_value (info->alloc_type, p, &p);
2807 case MONO_WRAPPER_WRITE_BARRIER:
2809 case MONO_WRAPPER_STELEMREF: {
2810 WrapperInfo *info = mono_marshal_get_wrapper_info (method);
2813 encode_value (info->subtype, p, &p);
2814 if (info->subtype == WRAPPER_SUBTYPE_VIRTUAL_STELEMREF)
2815 encode_value (info->d.virtual_stelemref.kind, p, &p);
2818 case MONO_WRAPPER_UNKNOWN: {
2819 WrapperInfo *info = mono_marshal_get_wrapper_info (method);
2822 encode_value (info->subtype, p, &p);
2823 if (info->subtype == WRAPPER_SUBTYPE_PTR_TO_STRUCTURE ||
2824 info->subtype == WRAPPER_SUBTYPE_STRUCTURE_TO_PTR)
2825 encode_klass_ref (acfg, method->klass, p, &p);
2826 else if (info->subtype == WRAPPER_SUBTYPE_SYNCHRONIZED_INNER)
2827 encode_method_ref (acfg, info->d.synchronized_inner.method, p, &p);
2828 else if (info->subtype == WRAPPER_SUBTYPE_ARRAY_ACCESSOR)
2829 encode_method_ref (acfg, info->d.array_accessor.method, p, &p);
2832 case MONO_WRAPPER_MANAGED_TO_NATIVE: {
2833 WrapperInfo *info = mono_marshal_get_wrapper_info (method);
2836 encode_value (info->subtype, p, &p);
2837 if (info->subtype == WRAPPER_SUBTYPE_ICALL_WRAPPER) {
2838 strcpy ((char*)p, method->name);
2839 p += strlen (method->name) + 1;
2840 } else if (info->subtype == WRAPPER_SUBTYPE_NATIVE_FUNC_AOT) {
2841 encode_method_ref (acfg, info->d.managed_to_native.method, p, &p);
2843 g_assert (info->subtype == WRAPPER_SUBTYPE_NONE || info->subtype == WRAPPER_SUBTYPE_PINVOKE);
2844 encode_method_ref (acfg, info->d.managed_to_native.method, p, &p);
2848 case MONO_WRAPPER_SYNCHRONIZED: {
2851 m = mono_marshal_method_from_wrapper (method);
2853 g_assert (m != method);
2854 encode_method_ref (acfg, m, p, &p);
2857 case MONO_WRAPPER_MANAGED_TO_MANAGED: {
2858 WrapperInfo *info = mono_marshal_get_wrapper_info (method);
2861 encode_value (info->subtype, p, &p);
2863 if (info->subtype == WRAPPER_SUBTYPE_ELEMENT_ADDR) {
2864 encode_value (info->d.element_addr.rank, p, &p);
2865 encode_value (info->d.element_addr.elem_size, p, &p);
2866 } else if (info->subtype == WRAPPER_SUBTYPE_STRING_CTOR) {
2867 encode_method_ref (acfg, info->d.string_ctor.method, p, &p);
2869 g_assert_not_reached ();
2873 case MONO_WRAPPER_CASTCLASS: {
2874 WrapperInfo *info = mono_marshal_get_wrapper_info (method);
2877 encode_value (info->subtype, p, &p);
2880 case MONO_WRAPPER_RUNTIME_INVOKE: {
2881 WrapperInfo *info = mono_marshal_get_wrapper_info (method);
2884 encode_value (info->subtype, p, &p);
2885 if (info->subtype == WRAPPER_SUBTYPE_RUNTIME_INVOKE_DIRECT || info->subtype == WRAPPER_SUBTYPE_RUNTIME_INVOKE_VIRTUAL)
2886 encode_method_ref (acfg, info->d.runtime_invoke.method, p, &p);
2887 else if (info->subtype == WRAPPER_SUBTYPE_RUNTIME_INVOKE_NORMAL)
2888 encode_signature (acfg, info->d.runtime_invoke.sig, p, &p);
2891 case MONO_WRAPPER_DELEGATE_INVOKE:
2892 case MONO_WRAPPER_DELEGATE_BEGIN_INVOKE:
2893 case MONO_WRAPPER_DELEGATE_END_INVOKE: {
2894 if (method->is_inflated) {
2895 /* These wrappers are identified by their class */
2896 encode_value (1, p, &p);
2897 encode_klass_ref (acfg, method->klass, p, &p);
2899 MonoMethodSignature *sig = mono_method_signature (method);
2900 WrapperInfo *info = mono_marshal_get_wrapper_info (method);
2902 encode_value (0, p, &p);
2903 if (method->wrapper_type == MONO_WRAPPER_DELEGATE_INVOKE)
2904 encode_value (info ? info->subtype : 0, p, &p);
2905 encode_signature (acfg, sig, p, &p);
2909 case MONO_WRAPPER_NATIVE_TO_MANAGED: {
2910 WrapperInfo *info = mono_marshal_get_wrapper_info (method);
2913 encode_method_ref (acfg, info->d.native_to_managed.method, p, &p);
2914 encode_klass_ref (acfg, info->d.native_to_managed.klass, p, &p);
2918 g_assert_not_reached ();
2920 } else if (mono_method_signature (method)->is_inflated) {
2922 * This is a generic method, find the original token which referenced it and
2924 * Obtain the token from information recorded by the JIT.
2926 ji = g_hash_table_lookup (acfg->token_info_hash, method);
2928 image_index = get_image_index (acfg, ji->image);
2929 g_assert (image_index < MAX_IMAGE_INDEX);
2932 encode_value ((MONO_AOT_METHODREF_METHODSPEC << 24), p, &p);
2933 encode_value (image_index, p, &p);
2934 encode_value (token, p, &p);
2936 MonoMethod *declaring;
2937 MonoGenericContext *context = mono_method_get_context (method);
2939 g_assert (method->is_inflated);
2940 declaring = ((MonoMethodInflated*)method)->declaring;
2943 * This might be a non-generic method of a generic instance, which
2944 * doesn't have a token since the reference is generated by the JIT
2945 * like Nullable:Box/Unbox, or by generic sharing.
2947 encode_value ((MONO_AOT_METHODREF_GINST << 24), p, &p);
2948 /* Encode the klass */
2949 encode_klass_ref (acfg, method->klass, p, &p);
2950 /* Encode the method */
2951 image_index = get_image_index (acfg, method->klass->image);
2952 g_assert (image_index < MAX_IMAGE_INDEX);
2953 g_assert (declaring->token);
2954 token = declaring->token;
2955 g_assert (mono_metadata_token_table (token) == MONO_TABLE_METHOD);
2956 encode_value (image_index, p, &p);
2957 encode_value (token, p, &p);
2958 encode_generic_context (acfg, context, p, &p);
2960 } else if (token == 0) {
2961 /* This might be a method of a constructed type like int[,].Set */
2962 /* Obtain the token from information recorded by the JIT */
2963 ji = g_hash_table_lookup (acfg->token_info_hash, method);
2965 image_index = get_image_index (acfg, ji->image);
2966 g_assert (image_index < MAX_IMAGE_INDEX);
2969 encode_value ((MONO_AOT_METHODREF_METHODSPEC << 24), p, &p);
2970 encode_value (image_index, p, &p);
2971 encode_value (token, p, &p);
2974 g_assert (method->klass->rank);
2976 /* Encode directly */
2977 encode_value ((MONO_AOT_METHODREF_ARRAY << 24), p, &p);
2978 encode_klass_ref (acfg, method->klass, p, &p);
2979 if (!strcmp (method->name, ".ctor") && mono_method_signature (method)->param_count == method->klass->rank)
2980 encode_value (0, p, &p);
2981 else if (!strcmp (method->name, ".ctor") && mono_method_signature (method)->param_count == method->klass->rank * 2)
2982 encode_value (1, p, &p);
2983 else if (!strcmp (method->name, "Get"))
2984 encode_value (2, p, &p);
2985 else if (!strcmp (method->name, "Address"))
2986 encode_value (3, p, &p);
2987 else if (!strcmp (method->name, "Set"))
2988 encode_value (4, p, &p);
2990 g_assert_not_reached ();
2993 g_assert (mono_metadata_token_table (token) == MONO_TABLE_METHOD);
2995 if (image_index >= MONO_AOT_METHODREF_MIN) {
2996 encode_value ((MONO_AOT_METHODREF_LARGE_IMAGE_INDEX << 24), p, &p);
2997 encode_value (image_index, p, &p);
2998 encode_value (mono_metadata_token_index (token), p, &p);
3000 encode_value ((image_index << 24) | mono_metadata_token_index (token), p, &p);
3007 compare_patches (gconstpointer a, gconstpointer b)
3011 i = (*(MonoJumpInfo**)a)->ip.i;
3012 j = (*(MonoJumpInfo**)b)->ip.i;
3023 static G_GNUC_UNUSED char*
3024 patch_to_string (MonoJumpInfo *patch_info)
3028 str = g_string_new ("");
3030 g_string_append_printf (str, "%s(", get_patch_name (patch_info->type));
3032 switch (patch_info->type) {
3033 case MONO_PATCH_INFO_VTABLE:
3034 mono_type_get_desc (str, &patch_info->data.klass->byval_arg, TRUE);
3039 g_string_append_printf (str, ")");
3040 return g_string_free (str, FALSE);
3046 * Return whenever PATCH_INFO refers to a direct call, and thus requires a
3049 static inline gboolean
3050 is_plt_patch (MonoJumpInfo *patch_info)
3052 switch (patch_info->type) {
3053 case MONO_PATCH_INFO_METHOD:
3054 case MONO_PATCH_INFO_INTERNAL_METHOD:
3055 case MONO_PATCH_INFO_JIT_ICALL_ADDR:
3056 case MONO_PATCH_INFO_ICALL_ADDR:
3057 case MONO_PATCH_INFO_CLASS_INIT:
3058 case MONO_PATCH_INFO_RGCTX_FETCH:
3059 case MONO_PATCH_INFO_GENERIC_CLASS_INIT:
3060 case MONO_PATCH_INFO_MONITOR_ENTER:
3061 case MONO_PATCH_INFO_MONITOR_ENTER_V4:
3062 case MONO_PATCH_INFO_MONITOR_EXIT:
3063 case MONO_PATCH_INFO_LLVM_IMT_TRAMPOLINE:
3073 * Return the symbol identifying the plt entry PLT_OFFSET.
3076 get_plt_symbol (MonoAotCompile *acfg, int plt_offset, MonoJumpInfo *patch_info)
3080 * The Apple linker reorganizes object files, so it doesn't like branches to local
3081 * labels, since those have no relocations.
3083 return g_strdup_printf ("%sp_%d", acfg->llvm_label_prefix, plt_offset);
3085 return g_strdup_printf ("%sp_%d", acfg->temp_prefix, plt_offset);
3092 * Return a PLT entry which belongs to the method identified by PATCH_INFO.
3094 static MonoPltEntry*
3095 get_plt_entry (MonoAotCompile *acfg, MonoJumpInfo *patch_info)
3099 if (!is_plt_patch (patch_info))
3102 if (!acfg->patch_to_plt_entry [patch_info->type])
3103 acfg->patch_to_plt_entry [patch_info->type] = g_hash_table_new (mono_patch_info_hash, mono_patch_info_equal);
3104 res = g_hash_table_lookup (acfg->patch_to_plt_entry [patch_info->type], patch_info);
3106 if (!acfg->llvm && patch_info->type == MONO_PATCH_INFO_METHOD && (patch_info->data.method->iflags & METHOD_IMPL_ATTRIBUTE_SYNCHRONIZED)) {
3108 * Allocate a separate PLT slot for each such patch, since some plt
3109 * entries will refer to the method itself, and some will refer to the
3116 MonoJumpInfo *new_ji;
3118 new_ji = mono_patch_info_dup_mp (acfg->mempool, patch_info);
3120 res = mono_mempool_alloc0 (acfg->mempool, sizeof (MonoPltEntry));
3121 res->plt_offset = acfg->plt_offset;
3123 res->symbol = get_plt_symbol (acfg, res->plt_offset, patch_info);
3124 if (acfg->aot_opts.write_symbols)
3125 res->debug_sym = get_plt_entry_debug_sym (acfg, res->ji, acfg->plt_entry_debug_sym_cache);
3127 res->llvm_symbol = g_strdup_printf ("%s_%s_llvm", res->symbol, res->debug_sym);
3129 res->llvm_symbol = g_strdup_printf ("%s_llvm", res->symbol);
3131 g_hash_table_insert (acfg->patch_to_plt_entry [new_ji->type], new_ji, res);
3133 g_hash_table_insert (acfg->plt_offset_to_entry, GUINT_TO_POINTER (res->plt_offset), res);
3135 //g_assert (mono_patch_info_equal (patch_info, new_ji));
3136 //mono_print_ji (patch_info); printf ("\n");
3137 //g_hash_table_print_stats (acfg->patch_to_plt_entry);
3139 acfg->plt_offset ++;
3148 * Returns the offset of the GOT slot where the runtime object resulting from resolving
3149 * JI could be found if it exists, otherwise allocates a new one.
3152 get_got_offset (MonoAotCompile *acfg, gboolean llvm, MonoJumpInfo *ji)
3155 GotInfo *info = llvm ? &acfg->llvm_got_info : &acfg->got_info;
3157 got_offset = GPOINTER_TO_UINT (g_hash_table_lookup (info->patch_to_got_offset_by_type [ji->type], ji));
3159 return got_offset - 1;
3162 got_offset = acfg->llvm_got_offset;
3163 acfg->llvm_got_offset ++;
3165 got_offset = acfg->got_offset;
3166 acfg->got_offset ++;
3169 acfg->stats.got_slots ++;
3170 acfg->stats.got_slot_types [ji->type] ++;
3172 g_hash_table_insert (info->patch_to_got_offset, ji, GUINT_TO_POINTER (got_offset + 1));
3173 g_hash_table_insert (info->patch_to_got_offset_by_type [ji->type], ji, GUINT_TO_POINTER (got_offset + 1));
3174 g_ptr_array_add (info->got_patches, ji);
3179 /* Add a method to the list of methods which need to be emitted */
3181 add_method_with_index (MonoAotCompile *acfg, MonoMethod *method, int index, gboolean extra)
3184 if (!g_hash_table_lookup (acfg->method_indexes, method)) {
3185 g_ptr_array_add (acfg->methods, method);
3186 g_hash_table_insert (acfg->method_indexes, method, GUINT_TO_POINTER (index + 1));
3187 acfg->nmethods = acfg->methods->len + 1;
3190 if (method->wrapper_type || extra)
3191 g_ptr_array_add (acfg->extra_methods, method);
3195 get_method_index (MonoAotCompile *acfg, MonoMethod *method)
3197 int index = GPOINTER_TO_UINT (g_hash_table_lookup (acfg->method_indexes, method));
3205 add_method_full (MonoAotCompile *acfg, MonoMethod *method, gboolean extra, int depth)
3209 index = GPOINTER_TO_UINT (g_hash_table_lookup (acfg->method_indexes, method));
3213 index = acfg->method_index;
3214 add_method_with_index (acfg, method, index, extra);
3216 g_ptr_array_add (acfg->method_order, GUINT_TO_POINTER (index));
3218 g_hash_table_insert (acfg->method_depth, method, GUINT_TO_POINTER (depth));
3220 acfg->method_index ++;
3226 add_method (MonoAotCompile *acfg, MonoMethod *method)
3228 return add_method_full (acfg, method, FALSE, 0);
3232 add_extra_method_with_depth (MonoAotCompile *acfg, MonoMethod *method, int depth)
3234 if (mono_method_is_generic_sharable_full (method, FALSE, TRUE, FALSE))
3235 method = mini_get_shared_method (method);
3237 if (acfg->aot_opts.log_generics)
3238 aot_printf (acfg, "%*sAdding method %s.\n", depth, "", mono_method_full_name (method, TRUE));
3240 add_method_full (acfg, method, TRUE, depth);
3244 add_extra_method (MonoAotCompile *acfg, MonoMethod *method)
3246 add_extra_method_with_depth (acfg, method, 0);
3250 add_jit_icall_wrapper (gpointer key, gpointer value, gpointer user_data)
3252 MonoAotCompile *acfg = user_data;
3253 MonoJitICallInfo *callinfo = value;
3254 MonoMethod *wrapper;
3260 name = g_strdup_printf ("__icall_wrapper_%s", callinfo->name);
3261 wrapper = mono_marshal_get_icall_wrapper (callinfo->sig, name, callinfo->func, check_for_pending_exc);
3264 add_method (acfg, wrapper);
3268 get_runtime_invoke_sig (MonoMethodSignature *sig)
3270 MonoMethodBuilder *mb;
3273 mb = mono_mb_new (mono_defaults.object_class, "FOO", MONO_WRAPPER_NONE);
3274 m = mono_mb_create_method (mb, sig, 16);
3275 return mono_marshal_get_runtime_invoke (m, FALSE);
3279 can_marshal_struct (MonoClass *klass)
3281 MonoClassField *field;
3282 gboolean can_marshal = TRUE;
3283 gpointer iter = NULL;
3284 MonoMarshalType *info;
3287 if ((klass->flags & TYPE_ATTRIBUTE_LAYOUT_MASK) == TYPE_ATTRIBUTE_AUTO_LAYOUT)
3290 info = mono_marshal_load_type_info (klass);
3292 /* Only allow a few field types to avoid asserts in the marshalling code */
3293 while ((field = mono_class_get_fields (klass, &iter))) {
3294 if ((field->type->attrs & FIELD_ATTRIBUTE_STATIC))
3297 switch (field->type->type) {
3302 case MONO_TYPE_BOOLEAN:
3305 case MONO_TYPE_CHAR:
3313 case MONO_TYPE_STRING:
3315 case MONO_TYPE_VALUETYPE:
3316 if (!mono_class_from_mono_type (field->type)->enumtype && !can_marshal_struct (mono_class_from_mono_type (field->type)))
3317 can_marshal = FALSE;
3319 case MONO_TYPE_SZARRAY: {
3320 gboolean has_mspec = FALSE;
3323 for (i = 0; i < info->num_fields; ++i) {
3324 if (info->fields [i].field == field && info->fields [i].mspec)
3329 can_marshal = FALSE;
3333 can_marshal = FALSE;
3339 /* Its hard to compute whenever these can be marshalled or not */
3340 if (!strcmp (klass->name_space, "System.Net.NetworkInformation.MacOsStructs") && strcmp (klass->name, "sockaddr_dl"))
3347 create_gsharedvt_inst (MonoAotCompile *acfg, MonoMethod *method, MonoGenericContext *ctx)
3349 /* Create a vtype instantiation */
3350 MonoGenericContext shared_context;
3352 MonoGenericInst *inst;
3353 MonoGenericContainer *container;
3354 MonoClass **constraints;
3357 memset (ctx, 0, sizeof (MonoGenericContext));
3359 if (method->klass->generic_container) {
3360 shared_context = method->klass->generic_container->context;
3361 inst = shared_context.class_inst;
3363 args = g_new0 (MonoType*, inst->type_argc);
3364 for (i = 0; i < inst->type_argc; ++i) {
3365 args [i] = &mono_defaults.int_class->byval_arg;
3367 ctx->class_inst = mono_metadata_get_generic_inst (inst->type_argc, args);
3369 if (method->is_generic) {
3370 container = mono_method_get_generic_container (method);
3371 shared_context = container->context;
3372 inst = shared_context.method_inst;
3374 args = g_new0 (MonoType*, inst->type_argc);
3375 for (i = 0; i < container->type_argc; ++i) {
3376 MonoGenericParamInfo *info = &container->type_params [i].info;
3377 gboolean ref_only = FALSE;
3379 if (info && info->constraints) {
3380 constraints = info->constraints;
3382 while (*constraints) {
3383 MonoClass *cklass = *constraints;
3384 if (!(cklass == mono_defaults.object_class || (cklass->image == mono_defaults.corlib && !strcmp (cklass->name, "ValueType"))))
3385 /* Inflaring the method with our vtype would not be valid */
3392 args [i] = &mono_defaults.object_class->byval_arg;
3394 args [i] = &mono_defaults.int_class->byval_arg;
3396 ctx->method_inst = mono_metadata_get_generic_inst (inst->type_argc, args);
3401 add_wrappers (MonoAotCompile *acfg)
3403 MonoMethod *method, *m;
3405 MonoMethodSignature *sig, *csig;
3409 * FIXME: Instead of AOTing all the wrappers, it might be better to redesign them
3410 * so there is only one wrapper of a given type, or inlining their contents into their
3413 for (i = 0; i < acfg->image->tables [MONO_TABLE_METHOD].rows; ++i) {
3416 guint32 token = MONO_TOKEN_METHOD_DEF | (i + 1);
3417 gboolean skip = FALSE;
3419 method = mono_get_method_checked (acfg->image, token, NULL, NULL, &error);
3420 report_loader_error (acfg, &error, "Failed to load method token 0x%x due to %s\n", i, mono_error_get_message (&error));
3422 if ((method->flags & METHOD_ATTRIBUTE_PINVOKE_IMPL) ||
3423 (method->iflags & METHOD_IMPL_ATTRIBUTE_RUNTIME) ||
3424 (method->flags & METHOD_ATTRIBUTE_ABSTRACT))
3427 /* Skip methods which can not be handled by get_runtime_invoke () */
3428 sig = mono_method_signature (method);
3431 if ((sig->ret->type == MONO_TYPE_PTR) ||
3432 (sig->ret->type == MONO_TYPE_TYPEDBYREF))
3434 if (mono_class_is_open_constructed_type (sig->ret))
3437 for (j = 0; j < sig->param_count; j++) {
3438 if (sig->params [j]->type == MONO_TYPE_TYPEDBYREF)
3440 if (mono_class_is_open_constructed_type (sig->params [j]))
3444 #ifdef MONO_ARCH_DYN_CALL_SUPPORTED
3445 if (!mono_class_is_contextbound (method->klass)) {
3446 MonoDynCallInfo *info = mono_arch_dyn_call_prepare (sig);
3447 gboolean has_nullable = FALSE;
3449 for (j = 0; j < sig->param_count; j++) {
3450 if (sig->params [j]->type == MONO_TYPE_GENERICINST && mono_class_is_nullable (mono_class_from_mono_type (sig->params [j])))
3451 has_nullable = TRUE;
3454 if (info && !has_nullable) {
3455 /* Supported by the dynamic runtime-invoke wrapper */
3459 mono_arch_dyn_call_free (info);
3464 //printf ("%s\n", mono_method_full_name (method, TRUE));
3465 add_method (acfg, mono_marshal_get_runtime_invoke (method, FALSE));
3469 if (strcmp (acfg->image->assembly->aname.name, "mscorlib") == 0) {
3472 /* Runtime invoke wrappers */
3474 /* void runtime-invoke () [.cctor] */
3475 csig = mono_metadata_signature_alloc (mono_defaults.corlib, 0);
3476 csig->ret = &mono_defaults.void_class->byval_arg;
3477 add_method (acfg, get_runtime_invoke_sig (csig));
3479 /* void runtime-invoke () [Finalize] */
3480 csig = mono_metadata_signature_alloc (mono_defaults.corlib, 0);
3482 csig->ret = &mono_defaults.void_class->byval_arg;
3483 add_method (acfg, get_runtime_invoke_sig (csig));
3485 /* void runtime-invoke (string) [exception ctor] */
3486 csig = mono_metadata_signature_alloc (mono_defaults.corlib, 1);
3488 csig->ret = &mono_defaults.void_class->byval_arg;
3489 csig->params [0] = &mono_defaults.string_class->byval_arg;
3490 add_method (acfg, get_runtime_invoke_sig (csig));
3492 /* void runtime-invoke (string, string) [exception ctor] */
3493 csig = mono_metadata_signature_alloc (mono_defaults.corlib, 2);
3495 csig->ret = &mono_defaults.void_class->byval_arg;
3496 csig->params [0] = &mono_defaults.string_class->byval_arg;
3497 csig->params [1] = &mono_defaults.string_class->byval_arg;
3498 add_method (acfg, get_runtime_invoke_sig (csig));
3500 /* string runtime-invoke () [Exception.ToString ()] */
3501 csig = mono_metadata_signature_alloc (mono_defaults.corlib, 0);
3503 csig->ret = &mono_defaults.string_class->byval_arg;
3504 add_method (acfg, get_runtime_invoke_sig (csig));
3506 /* void runtime-invoke (string, Exception) [exception ctor] */
3507 csig = mono_metadata_signature_alloc (mono_defaults.corlib, 2);
3509 csig->ret = &mono_defaults.void_class->byval_arg;
3510 csig->params [0] = &mono_defaults.string_class->byval_arg;
3511 csig->params [1] = &mono_defaults.exception_class->byval_arg;
3512 add_method (acfg, get_runtime_invoke_sig (csig));
3514 /* Assembly runtime-invoke (string, bool) [DoAssemblyResolve] */
3515 csig = mono_metadata_signature_alloc (mono_defaults.corlib, 2);
3517 csig->ret = &(mono_class_from_name (
3518 mono_defaults.corlib, "System.Reflection", "Assembly"))->byval_arg;
3519 csig->params [0] = &mono_defaults.string_class->byval_arg;
3520 csig->params [1] = &mono_defaults.boolean_class->byval_arg;
3521 add_method (acfg, get_runtime_invoke_sig (csig));
3523 /* runtime-invoke used by finalizers */
3524 add_method (acfg, mono_marshal_get_runtime_invoke (mono_class_get_method_from_name_flags (mono_defaults.object_class, "Finalize", 0, 0), TRUE));
3526 /* This is used by mono_runtime_capture_context () */
3527 method = mono_get_context_capture_method ();
3529 add_method (acfg, mono_marshal_get_runtime_invoke (method, FALSE));
3531 #ifdef MONO_ARCH_DYN_CALL_SUPPORTED
3532 add_method (acfg, mono_marshal_get_runtime_invoke_dynamic ());
3536 add_method (acfg, mono_marshal_get_stelemref ());
3538 if (MONO_ARCH_HAVE_TLS_GET) {
3539 /* Managed Allocators */
3540 nallocators = mono_gc_get_managed_allocator_types ();
3541 for (i = 0; i < nallocators; ++i) {
3542 m = mono_gc_get_managed_allocator_by_type (i);
3544 add_method (acfg, m);
3548 /* Stelemref wrappers */
3550 MonoMethod **wrappers;
3553 wrappers = mono_marshal_get_virtual_stelemref_wrappers (&nwrappers);
3554 for (i = 0; i < nwrappers; ++i)
3555 add_method (acfg, wrappers [i]);
3559 /* castclass_with_check wrapper */
3560 add_method (acfg, mono_marshal_get_castclass_with_cache ());
3561 /* isinst_with_check wrapper */
3562 add_method (acfg, mono_marshal_get_isinst_with_cache ());
3564 /* JIT icall wrappers */
3565 /* FIXME: locking - this is "safe" as full-AOT threads don't mutate the icall hash*/
3566 g_hash_table_foreach (mono_get_jit_icall_info (), add_jit_icall_wrapper, acfg);
3570 * remoting-invoke-with-check wrappers are very frequent, so avoid emitting them,
3571 * we use the original method instead at runtime.
3572 * Since full-aot doesn't support remoting, this is not a problem.
3575 /* remoting-invoke wrappers */
3576 for (i = 0; i < acfg->image->tables [MONO_TABLE_METHOD].rows; ++i) {
3577 MonoMethodSignature *sig;
3579 token = MONO_TOKEN_METHOD_DEF | (i + 1);
3580 method = mono_get_method (acfg->image, token, NULL);
3582 sig = mono_method_signature (method);
3584 if (sig->hasthis && (method->klass->marshalbyref || method->klass == mono_defaults.object_class)) {
3585 m = mono_marshal_get_remoting_invoke_with_check (method);
3587 add_method (acfg, m);
3592 /* delegate-invoke wrappers */
3593 for (i = 0; i < acfg->image->tables [MONO_TABLE_TYPEDEF].rows; ++i) {
3596 MonoCustomAttrInfo *cattr;
3598 token = MONO_TOKEN_TYPE_DEF | (i + 1);
3599 klass = mono_class_get_checked (acfg->image, token, &error);
3602 mono_error_cleanup (&error);
3606 if (!klass->delegate || klass == mono_defaults.delegate_class || klass == mono_defaults.multicastdelegate_class)
3609 if (!klass->generic_container) {
3610 method = mono_get_delegate_invoke (klass);
3612 m = mono_marshal_get_delegate_invoke (method, NULL);
3614 add_method (acfg, m);
3616 method = mono_class_get_method_from_name_flags (klass, "BeginInvoke", -1, 0);
3618 add_method (acfg, mono_marshal_get_delegate_begin_invoke (method));
3620 method = mono_class_get_method_from_name_flags (klass, "EndInvoke", -1, 0);
3622 add_method (acfg, mono_marshal_get_delegate_end_invoke (method));
3624 cattr = mono_custom_attrs_from_class (klass);
3629 for (j = 0; j < cattr->num_attrs; ++j)
3630 if (cattr->attrs [j].ctor && (!strcmp (cattr->attrs [j].ctor->klass->name, "MonoNativeFunctionWrapperAttribute") || !strcmp (cattr->attrs [j].ctor->klass->name, "UnmanagedFunctionPointerAttribute")))
3632 if (j < cattr->num_attrs)
3633 add_method (acfg, mono_marshal_get_native_func_wrapper_aot (klass));
3635 } else if ((acfg->opts & MONO_OPT_GSHAREDVT) && klass->generic_container) {
3637 MonoGenericContext ctx;
3638 MonoMethod *inst, *gshared;
3641 * Emit gsharedvt versions of the generic delegate-invoke wrappers
3644 method = mono_get_delegate_invoke (klass);
3645 create_gsharedvt_inst (acfg, method, &ctx);
3647 inst = mono_class_inflate_generic_method_checked (method, &ctx, &error);
3648 g_assert (mono_error_ok (&error)); /* FIXME don't swallow the error */
3650 m = mono_marshal_get_delegate_invoke (inst, NULL);
3651 g_assert (m->is_inflated);
3653 gshared = mini_get_shared_method_full (m, FALSE, TRUE);
3654 add_extra_method (acfg, gshared);
3657 method = mono_get_delegate_begin_invoke (klass);
3658 create_gsharedvt_inst (acfg, method, &ctx);
3660 inst = mono_class_inflate_generic_method_checked (method, &ctx, &error);
3661 g_assert (mono_error_ok (&error)); /* FIXME don't swallow the error */
3663 m = mono_marshal_get_delegate_begin_invoke (inst);
3664 g_assert (m->is_inflated);
3666 gshared = mini_get_shared_method_full (m, FALSE, TRUE);
3667 add_extra_method (acfg, gshared);
3670 method = mono_get_delegate_end_invoke (klass);
3671 create_gsharedvt_inst (acfg, method, &ctx);
3673 inst = mono_class_inflate_generic_method_checked (method, &ctx, &error);
3674 g_assert (mono_error_ok (&error)); /* FIXME don't swallow the error */
3676 m = mono_marshal_get_delegate_end_invoke (inst);
3677 g_assert (m->is_inflated);
3679 gshared = mini_get_shared_method_full (m, FALSE, TRUE);
3680 add_extra_method (acfg, gshared);
3685 /* array access wrappers */
3686 for (i = 0; i < acfg->image->tables [MONO_TABLE_TYPESPEC].rows; ++i) {
3690 token = MONO_TOKEN_TYPE_SPEC | (i + 1);
3691 klass = mono_class_get_checked (acfg->image, token, &error);
3694 mono_error_cleanup (&error);
3698 if (klass->rank && MONO_TYPE_IS_PRIMITIVE (&klass->element_class->byval_arg)) {
3699 MonoMethod *m, *wrapper;
3701 /* Add runtime-invoke wrappers too */
3703 m = mono_class_get_method_from_name (klass, "Get", -1);
3705 wrapper = mono_marshal_get_array_accessor_wrapper (m);
3706 add_extra_method (acfg, wrapper);
3707 add_extra_method (acfg, mono_marshal_get_runtime_invoke (wrapper, FALSE));
3709 m = mono_class_get_method_from_name (klass, "Set", -1);
3711 wrapper = mono_marshal_get_array_accessor_wrapper (m);
3712 add_extra_method (acfg, wrapper);
3713 add_extra_method (acfg, mono_marshal_get_runtime_invoke (wrapper, FALSE));
3717 /* Synchronized wrappers */
3718 for (i = 0; i < acfg->image->tables [MONO_TABLE_METHOD].rows; ++i) {
3720 token = MONO_TOKEN_METHOD_DEF | (i + 1);
3721 method = mono_get_method_checked (acfg->image, token, NULL, NULL, &error);
3722 report_loader_error (acfg, &error, "Failed to load method token 0x%x due to %s\n", i, mono_error_get_message (&error));
3724 if (method->iflags & METHOD_IMPL_ATTRIBUTE_SYNCHRONIZED) {
3725 if (method->is_generic) {
3727 } else if ((acfg->opts & MONO_OPT_GSHAREDVT) && method->klass->generic_container) {
3729 MonoGenericContext ctx;
3730 MonoMethod *inst, *gshared, *m;
3733 * Create a generic wrapper for a generic instance, and AOT that.
3735 create_gsharedvt_inst (acfg, method, &ctx);
3736 inst = mono_class_inflate_generic_method_checked (method, &ctx, &error);
3737 g_assert (mono_error_ok (&error)); /* FIXME don't swallow the error */
3738 m = mono_marshal_get_synchronized_wrapper (inst);
3739 g_assert (m->is_inflated);
3740 gshared = mini_get_shared_method_full (m, FALSE, TRUE);
3741 add_method (acfg, gshared);
3743 add_method (acfg, mono_marshal_get_synchronized_wrapper (method));
3748 /* pinvoke wrappers */
3749 for (i = 0; i < acfg->image->tables [MONO_TABLE_METHOD].rows; ++i) {
3752 guint32 token = MONO_TOKEN_METHOD_DEF | (i + 1);
3754 method = mono_get_method_checked (acfg->image, token, NULL, NULL, &error);
3755 report_loader_error (acfg, &error, "Failed to load method token 0x%x due to %s\n", i, mono_error_get_message (&error));
3757 if ((method->flags & METHOD_ATTRIBUTE_PINVOKE_IMPL) ||
3758 (method->iflags & METHOD_IMPL_ATTRIBUTE_INTERNAL_CALL)) {
3759 add_method (acfg, mono_marshal_get_native_wrapper (method, TRUE, TRUE));
3763 /* native-to-managed wrappers */
3764 for (i = 0; i < acfg->image->tables [MONO_TABLE_METHOD].rows; ++i) {
3767 guint32 token = MONO_TOKEN_METHOD_DEF | (i + 1);
3768 MonoCustomAttrInfo *cattr;
3771 method = mono_get_method_checked (acfg->image, token, NULL, NULL, &error);
3772 report_loader_error (acfg, &error, "Failed to load method token 0x%x due to %s\n", i, mono_error_get_message (&error));
3775 * Only generate native-to-managed wrappers for methods which have an
3776 * attribute named MonoPInvokeCallbackAttribute. We search for the attribute by
3777 * name to avoid defining a new assembly to contain it.
3779 cattr = mono_custom_attrs_from_method (method);
3782 for (j = 0; j < cattr->num_attrs; ++j)
3783 if (cattr->attrs [j].ctor && !strcmp (cattr->attrs [j].ctor->klass->name, "MonoPInvokeCallbackAttribute"))
3785 if (j < cattr->num_attrs) {
3786 MonoCustomAttrEntry *e = &cattr->attrs [j];
3787 MonoMethodSignature *sig = mono_method_signature (e->ctor);
3788 const char *p = (const char*)e->data;
3790 int slen, num_named, named_type;
3794 char *export_name = NULL;
3795 MonoMethod *wrapper;
3797 /* this cannot be enforced by the C# compiler so we must give the user some warning before aborting */
3798 if (!(method->flags & METHOD_ATTRIBUTE_STATIC)) {
3799 g_warning ("AOT restriction: Method '%s' must be static since it is decorated with [MonoPInvokeCallback]. See http://ios.xamarin.com/Documentation/Limitations#Reverse_Callbacks",
3800 mono_method_full_name (method, TRUE));
3804 g_assert (sig->param_count == 1);
3805 g_assert (sig->params [0]->type == MONO_TYPE_CLASS && !strcmp (mono_class_from_mono_type (sig->params [0])->name, "Type"));
3808 * Decode the cattr manually since we can't create objects
3809 * during aot compilation.
3815 /* From load_cattr_value () in reflection.c */
3816 slen = mono_metadata_decode_value (p, &p);
3817 n = g_memdup (p, slen + 1);
3819 t = mono_reflection_type_from_name (n, acfg->image);
3823 klass = mono_class_from_mono_type (t);
3824 g_assert (klass->parent == mono_defaults.multicastdelegate_class);
3828 num_named = read16 (p);
3831 g_assert (num_named < 2);
3832 if (num_named == 1) {
3836 /* parse ExportSymbol attribute */
3838 named_type = *named;
3840 /* data_type = *named; */
3843 name_len = mono_metadata_decode_blob_size (named, &named);
3844 name = g_malloc (name_len + 1);
3845 memcpy (name, named, name_len);
3846 name [name_len] = 0;
3849 g_assert (named_type == 0x54);
3850 g_assert (!strcmp (name, "ExportSymbol"));
3852 /* load_cattr_value (), string case */
3853 g_assert (*named != (char)0xff);
3854 slen = mono_metadata_decode_value (named, &named);
3855 export_name = g_malloc (slen + 1);
3856 memcpy (export_name, named, slen);
3857 export_name [slen] = 0;
3861 wrapper = mono_marshal_get_managed_wrapper (method, klass, 0);
3862 add_method (acfg, wrapper);
3864 g_hash_table_insert (acfg->export_names, wrapper, export_name);
3868 if ((method->flags & METHOD_ATTRIBUTE_PINVOKE_IMPL) ||
3869 (method->iflags & METHOD_IMPL_ATTRIBUTE_INTERNAL_CALL)) {
3870 add_method (acfg, mono_marshal_get_native_wrapper (method, TRUE, TRUE));
3874 /* StructureToPtr/PtrToStructure wrappers */
3875 for (i = 0; i < acfg->image->tables [MONO_TABLE_TYPEDEF].rows; ++i) {
3879 token = MONO_TOKEN_TYPE_DEF | (i + 1);
3880 klass = mono_class_get_checked (acfg->image, token, &error);
3883 mono_error_cleanup (&error);
3887 if (klass->valuetype && !klass->generic_container && can_marshal_struct (klass) &&
3888 !(klass->nested_in && strstr (klass->nested_in->name, "<PrivateImplementationDetails>") == klass->nested_in->name)) {
3889 add_method (acfg, mono_marshal_get_struct_to_ptr (klass));
3890 add_method (acfg, mono_marshal_get_ptr_to_struct (klass));
3896 has_type_vars (MonoClass *klass)
3898 if ((klass->byval_arg.type == MONO_TYPE_VAR) || (klass->byval_arg.type == MONO_TYPE_MVAR))
3901 return has_type_vars (klass->element_class);
3902 if (klass->generic_class) {
3903 MonoGenericContext *context = &klass->generic_class->context;
3904 if (context->class_inst) {
3907 for (i = 0; i < context->class_inst->type_argc; ++i)
3908 if (has_type_vars (mono_class_from_mono_type (context->class_inst->type_argv [i])))
3912 if (klass->generic_container)
3918 is_vt_inst (MonoGenericInst *inst)
3922 for (i = 0; i < inst->type_argc; ++i) {
3923 MonoType *t = inst->type_argv [i];
3924 if (MONO_TYPE_ISSTRUCT (t) || t->type == MONO_TYPE_VALUETYPE)
3931 method_has_type_vars (MonoMethod *method)
3933 if (has_type_vars (method->klass))
3936 if (method->is_inflated) {
3937 MonoGenericContext *context = mono_method_get_context (method);
3938 if (context->method_inst) {
3941 for (i = 0; i < context->method_inst->type_argc; ++i)
3942 if (has_type_vars (mono_class_from_mono_type (context->method_inst->type_argv [i])))
3949 static void add_generic_class_with_depth (MonoAotCompile *acfg, MonoClass *klass, int depth, const char *ref);
3952 add_generic_class (MonoAotCompile *acfg, MonoClass *klass, gboolean force, const char *ref)
3954 /* This might lead to a huge code blowup so only do it if neccesary */
3955 if (!acfg->aot_opts.full_aot && !force)
3958 add_generic_class_with_depth (acfg, klass, 0, ref);
3962 check_type_depth (MonoType *t, int depth)
3970 case MONO_TYPE_GENERICINST: {
3971 MonoGenericClass *gklass = t->data.generic_class;
3972 MonoGenericInst *ginst = gklass->context.class_inst;
3975 for (i = 0; i < ginst->type_argc; ++i) {
3976 if (check_type_depth (ginst->type_argv [i], depth + 1))
3990 add_types_from_method_header (MonoAotCompile *acfg, MonoMethod *method);
3993 * add_generic_class:
3995 * Add all methods of a generic class.
3998 add_generic_class_with_depth (MonoAotCompile *acfg, MonoClass *klass, int depth, const char *ref)
4001 MonoClassField *field;
4003 gboolean use_gsharedvt = FALSE;
4005 if (!acfg->ginst_hash)
4006 acfg->ginst_hash = g_hash_table_new (NULL, NULL);
4008 mono_class_init (klass);
4010 if (klass->generic_class && klass->generic_class->context.class_inst->is_open)
4013 if (has_type_vars (klass))
4016 if (!klass->generic_class && !klass->rank)
4019 if (klass->exception_type)
4022 if (!acfg->ginst_hash)
4023 acfg->ginst_hash = g_hash_table_new (NULL, NULL);
4025 if (g_hash_table_lookup (acfg->ginst_hash, klass))
4028 if (check_type_depth (&klass->byval_arg, 0))
4031 if (acfg->aot_opts.log_generics)
4032 aot_printf (acfg, "%*sAdding generic instance %s [%s].\n", depth, "", mono_type_full_name (&klass->byval_arg), ref);
4034 g_hash_table_insert (acfg->ginst_hash, klass, klass);
4037 * Use gsharedvt for generic collections with vtype arguments to avoid code blowup.
4038 * Enable this only for some classes since gsharedvt might not support all methods.
4040 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) &&
4041 (!strcmp (klass->name, "Dictionary`2") || !strcmp (klass->name, "List`1") || !strcmp (klass->name, "ReadOnlyCollection`1")))
4042 use_gsharedvt = TRUE;
4045 while ((method = mono_class_get_methods (klass, &iter))) {
4046 if ((acfg->opts & MONO_OPT_GSHAREDVT) && method->is_inflated && mono_method_get_context (method)->method_inst) {
4048 * This is partial sharing, and we can't handle it yet
4053 if (mono_method_is_generic_sharable_full (method, FALSE, FALSE, use_gsharedvt)) {
4055 add_types_from_method_header (acfg, method);
4059 if (method->is_generic)
4064 * FIXME: Instances which are referenced by these methods are not added,
4065 * for example Array.Resize<int> for List<int>.Add ().
4067 add_extra_method_with_depth (acfg, method, depth + 1);
4071 while ((field = mono_class_get_fields (klass, &iter))) {
4072 if (field->type->type == MONO_TYPE_GENERICINST)
4073 add_generic_class_with_depth (acfg, mono_class_from_mono_type (field->type), depth + 1, "field");
4076 if (klass->delegate) {
4077 method = mono_get_delegate_invoke (klass);
4079 method = mono_marshal_get_delegate_invoke (method, NULL);
4081 if (acfg->aot_opts.log_generics)
4082 aot_printf (acfg, "%*sAdding method %s.\n", depth, "", mono_method_full_name (method, TRUE));
4084 add_method (acfg, method);
4087 /* Add superclasses */
4089 add_generic_class_with_depth (acfg, klass->parent, depth, "parent");
4092 * For ICollection<T>, add instances of the helper methods
4093 * in Array, since a T[] could be cast to ICollection<T>.
4095 if (klass->image == mono_defaults.corlib && !strcmp (klass->name_space, "System.Collections.Generic") &&
4096 (!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"))) {
4097 MonoClass *tclass = mono_class_from_mono_type (klass->generic_class->context.class_inst->type_argv [0]);
4098 MonoClass *array_class = mono_bounded_array_class_get (tclass, 1, FALSE);
4102 if (!strcmp (klass->name, "IEnumerator`1"))
4103 name_prefix = g_strdup_printf ("%s.%s", klass->name_space, "IEnumerable`1");
4105 name_prefix = g_strdup_printf ("%s.%s", klass->name_space, klass->name);
4107 /* Add the T[]/InternalEnumerator class */
4108 if (!strcmp (klass->name, "IEnumerable`1") || !strcmp (klass->name, "IEnumerator`1")) {
4112 while ((nclass = mono_class_get_nested_types (array_class->parent, &iter))) {
4113 if (!strcmp (nclass->name, "InternalEnumerator`1"))
4117 nclass = mono_class_inflate_generic_class (nclass, mono_generic_class_get_context (klass->generic_class));
4118 add_generic_class (acfg, nclass, FALSE, "ICollection<T>");
4122 while ((method = mono_class_get_methods (array_class, &iter))) {
4123 if (strstr (method->name, name_prefix)) {
4124 MonoMethod *m = mono_aot_get_array_helper_from_wrapper (method);
4126 add_extra_method_with_depth (acfg, m, depth);
4130 g_free (name_prefix);
4133 /* Add an instance of GenericComparer<T> which is created dynamically by Comparer<T> */
4134 if (klass->image == mono_defaults.corlib && !strcmp (klass->name_space, "System.Collections.Generic") && !strcmp (klass->name, "Comparer`1")) {
4135 MonoClass *tclass = mono_class_from_mono_type (klass->generic_class->context.class_inst->type_argv [0]);
4136 MonoClass *icomparable, *gcomparer;
4137 MonoGenericContext ctx;
4138 MonoType *args [16];
4140 memset (&ctx, 0, sizeof (ctx));
4142 icomparable = mono_class_from_name (mono_defaults.corlib, "System", "IComparable`1");
4143 g_assert (icomparable);
4144 args [0] = &tclass->byval_arg;
4145 ctx.class_inst = mono_metadata_get_generic_inst (1, args);
4147 if (mono_class_is_assignable_from (mono_class_inflate_generic_class (icomparable, &ctx), tclass)) {
4148 gcomparer = mono_class_from_name (mono_defaults.corlib, "System.Collections.Generic", "GenericComparer`1");
4149 g_assert (gcomparer);
4150 add_generic_class (acfg, mono_class_inflate_generic_class (gcomparer, &ctx), FALSE, "Comparer<T>");
4154 /* Add an instance of GenericEqualityComparer<T> which is created dynamically by EqualityComparer<T> */
4155 if (klass->image == mono_defaults.corlib && !strcmp (klass->name_space, "System.Collections.Generic") && !strcmp (klass->name, "EqualityComparer`1")) {
4156 MonoClass *tclass = mono_class_from_mono_type (klass->generic_class->context.class_inst->type_argv [0]);
4157 MonoClass *iface, *gcomparer;
4158 MonoGenericContext ctx;
4159 MonoType *args [16];
4161 memset (&ctx, 0, sizeof (ctx));
4163 iface = mono_class_from_name (mono_defaults.corlib, "System", "IEquatable`1");
4165 args [0] = &tclass->byval_arg;
4166 ctx.class_inst = mono_metadata_get_generic_inst (1, args);
4168 if (mono_class_is_assignable_from (mono_class_inflate_generic_class (iface, &ctx), tclass)) {
4169 gcomparer = mono_class_from_name (mono_defaults.corlib, "System.Collections.Generic", "GenericEqualityComparer`1");
4170 g_assert (gcomparer);
4171 add_generic_class (acfg, mono_class_inflate_generic_class (gcomparer, &ctx), FALSE, "EqualityComparer<T>");
4177 add_instances_of (MonoAotCompile *acfg, MonoClass *klass, MonoType **insts, int ninsts, gboolean force)
4180 MonoGenericContext ctx;
4181 MonoType *args [16];
4183 if (acfg->aot_opts.no_instances)
4186 memset (&ctx, 0, sizeof (ctx));
4188 for (i = 0; i < ninsts; ++i) {
4189 args [0] = insts [i];
4190 ctx.class_inst = mono_metadata_get_generic_inst (1, args);
4191 add_generic_class (acfg, mono_class_inflate_generic_class (klass, &ctx), force, "");
4196 add_types_from_method_header (MonoAotCompile *acfg, MonoMethod *method)
4198 MonoMethodHeader *header;
4199 MonoMethodSignature *sig;
4202 depth = GPOINTER_TO_UINT (g_hash_table_lookup (acfg->method_depth, method));
4204 sig = mono_method_signature (method);
4207 for (j = 0; j < sig->param_count; ++j)
4208 if (sig->params [j]->type == MONO_TYPE_GENERICINST)
4209 add_generic_class_with_depth (acfg, mono_class_from_mono_type (sig->params [j]), depth + 1, "arg");
4212 header = mono_method_get_header (method);
4215 for (j = 0; j < header->num_locals; ++j)
4216 if (header->locals [j]->type == MONO_TYPE_GENERICINST)
4217 add_generic_class_with_depth (acfg, mono_class_from_mono_type (header->locals [j]), depth + 1, "local");
4219 mono_loader_clear_error ();
4224 * add_generic_instances:
4226 * Add instances referenced by the METHODSPEC/TYPESPEC table.
4229 add_generic_instances (MonoAotCompile *acfg)
4234 MonoGenericContext *context;
4236 if (acfg->aot_opts.no_instances)
4239 for (i = 0; i < acfg->image->tables [MONO_TABLE_METHODSPEC].rows; ++i) {
4241 token = MONO_TOKEN_METHOD_SPEC | (i + 1);
4242 method = mono_get_method_checked (acfg->image, token, NULL, NULL, &error);
4245 aot_printerrf (acfg, "Failed to load methodspec 0x%x due to %s.\n", token, mono_error_get_message (&error));
4246 aot_printerrf (acfg, "Run with MONO_LOG_LEVEL=debug for more information.\n");
4247 mono_error_cleanup (&error);
4251 if (method->klass->image != acfg->image)
4254 context = mono_method_get_context (method);
4256 if (context && ((context->class_inst && context->class_inst->is_open)))
4260 * For open methods, create an instantiation which can be passed to the JIT.
4261 * FIXME: Handle class_inst as well.
4263 if (context && context->method_inst && context->method_inst->is_open) {
4265 MonoGenericContext shared_context;
4266 MonoGenericInst *inst;
4267 MonoType **type_argv;
4269 MonoMethod *declaring_method;
4270 gboolean supported = TRUE;
4272 /* Check that the context doesn't contain open constructed types */
4273 if (context->class_inst) {
4274 inst = context->class_inst;
4275 for (i = 0; i < inst->type_argc; ++i) {
4276 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)
4278 if (mono_class_is_open_constructed_type (inst->type_argv [i]))
4282 if (context->method_inst) {
4283 inst = context->method_inst;
4284 for (i = 0; i < inst->type_argc; ++i) {
4285 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)
4287 if (mono_class_is_open_constructed_type (inst->type_argv [i]))
4295 memset (&shared_context, 0, sizeof (MonoGenericContext));
4297 inst = context->class_inst;
4299 type_argv = g_new0 (MonoType*, inst->type_argc);
4300 for (i = 0; i < inst->type_argc; ++i) {
4301 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)
4302 type_argv [i] = &mono_defaults.object_class->byval_arg;
4304 type_argv [i] = inst->type_argv [i];
4307 shared_context.class_inst = mono_metadata_get_generic_inst (inst->type_argc, type_argv);
4311 inst = context->method_inst;
4313 type_argv = g_new0 (MonoType*, inst->type_argc);
4314 for (i = 0; i < inst->type_argc; ++i) {
4315 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)
4316 type_argv [i] = &mono_defaults.object_class->byval_arg;
4318 type_argv [i] = inst->type_argv [i];
4321 shared_context.method_inst = mono_metadata_get_generic_inst (inst->type_argc, type_argv);
4325 if (method->is_generic || method->klass->generic_container)
4326 declaring_method = method;
4328 declaring_method = mono_method_get_declaring_generic_method (method);
4330 method = mono_class_inflate_generic_method_checked (declaring_method, &shared_context, &error);
4331 g_assert (mono_error_ok (&error)); /* FIXME don't swallow the error */
4335 * If the method is fully sharable, it was already added in place of its
4336 * generic definition.
4338 if (mono_method_is_generic_sharable_full (method, FALSE, FALSE, FALSE))
4342 * FIXME: Partially shared methods are not shared here, so we end up with
4343 * many identical methods.
4345 add_extra_method (acfg, method);
4348 for (i = 0; i < acfg->image->tables [MONO_TABLE_TYPESPEC].rows; ++i) {
4352 token = MONO_TOKEN_TYPE_SPEC | (i + 1);
4354 klass = mono_class_get_checked (acfg->image, token, &error);
4355 if (!klass || klass->rank) {
4356 mono_error_cleanup (&error);
4360 add_generic_class (acfg, klass, FALSE, "typespec");
4363 /* Add types of args/locals */
4364 for (i = 0; i < acfg->methods->len; ++i) {
4365 method = g_ptr_array_index (acfg->methods, i);
4366 add_types_from_method_header (acfg, method);
4369 if (acfg->image == mono_defaults.corlib) {
4371 MonoType *insts [256];
4374 insts [ninsts ++] = &mono_defaults.byte_class->byval_arg;
4375 insts [ninsts ++] = &mono_defaults.sbyte_class->byval_arg;
4376 insts [ninsts ++] = &mono_defaults.int16_class->byval_arg;
4377 insts [ninsts ++] = &mono_defaults.uint16_class->byval_arg;
4378 insts [ninsts ++] = &mono_defaults.int32_class->byval_arg;
4379 insts [ninsts ++] = &mono_defaults.uint32_class->byval_arg;
4380 insts [ninsts ++] = &mono_defaults.int64_class->byval_arg;
4381 insts [ninsts ++] = &mono_defaults.uint64_class->byval_arg;
4382 insts [ninsts ++] = &mono_defaults.single_class->byval_arg;
4383 insts [ninsts ++] = &mono_defaults.double_class->byval_arg;
4384 insts [ninsts ++] = &mono_defaults.char_class->byval_arg;
4385 insts [ninsts ++] = &mono_defaults.boolean_class->byval_arg;
4387 /* Add GenericComparer<T> instances for primitive types for Enum.ToString () */
4388 klass = mono_class_from_name (acfg->image, "System.Collections.Generic", "GenericComparer`1");
4390 add_instances_of (acfg, klass, insts, ninsts, TRUE);
4391 klass = mono_class_from_name (acfg->image, "System.Collections.Generic", "GenericEqualityComparer`1");
4393 add_instances_of (acfg, klass, insts, ninsts, TRUE);
4395 /* Add instances of the array generic interfaces for primitive types */
4396 /* This will add instances of the InternalArray_ helper methods in Array too */
4397 klass = mono_class_from_name (acfg->image, "System.Collections.Generic", "ICollection`1");
4399 add_instances_of (acfg, klass, insts, ninsts, TRUE);
4400 klass = mono_class_from_name (acfg->image, "System.Collections.Generic", "IList`1");
4402 add_instances_of (acfg, klass, insts, ninsts, TRUE);
4403 klass = mono_class_from_name (acfg->image, "System.Collections.Generic", "IEnumerable`1");
4405 add_instances_of (acfg, klass, insts, ninsts, TRUE);
4408 * Add a managed-to-native wrapper of Array.GetGenericValueImpl<object>, which is
4409 * used for all instances of GetGenericValueImpl by the AOT runtime.
4412 MonoGenericContext ctx;
4413 MonoType *args [16];
4414 MonoMethod *get_method;
4415 MonoClass *array_klass = mono_array_class_get (mono_defaults.object_class, 1)->parent;
4417 get_method = mono_class_get_method_from_name (array_klass, "GetGenericValueImpl", 2);
4421 memset (&ctx, 0, sizeof (ctx));
4422 args [0] = &mono_defaults.object_class->byval_arg;
4423 ctx.method_inst = mono_metadata_get_generic_inst (1, args);
4424 add_extra_method (acfg, mono_marshal_get_native_wrapper (mono_class_inflate_generic_method_checked (get_method, &ctx, &error), TRUE, TRUE));
4425 g_assert (mono_error_ok (&error)); /* FIXME don't swallow the error */
4429 /* Same for CompareExchange<T>/Exchange<T> */
4431 MonoGenericContext ctx;
4432 MonoType *args [16];
4434 MonoClass *interlocked_klass = mono_class_from_name (mono_defaults.corlib, "System.Threading", "Interlocked");
4435 gpointer iter = NULL;
4437 while ((m = mono_class_get_methods (interlocked_klass, &iter))) {
4438 if ((!strcmp (m->name, "CompareExchange") || !strcmp (m->name, "Exchange")) && m->is_generic) {
4440 memset (&ctx, 0, sizeof (ctx));
4441 args [0] = &mono_defaults.object_class->byval_arg;
4442 ctx.method_inst = mono_metadata_get_generic_inst (1, args);
4443 add_extra_method (acfg, mono_marshal_get_native_wrapper (mono_class_inflate_generic_method_checked (m, &ctx, &error), TRUE, TRUE));
4444 g_assert (mono_error_ok (&error)); /* FIXME don't swallow the error */
4449 /* Same for Volatile.Read/Write<T> */
4451 MonoGenericContext ctx;
4452 MonoType *args [16];
4454 MonoClass *volatile_klass = mono_class_from_name (mono_defaults.corlib, "System.Threading", "Volatile");
4455 gpointer iter = NULL;
4457 if (volatile_klass) {
4458 while ((m = mono_class_get_methods (volatile_klass, &iter))) {
4459 if ((!strcmp (m->name, "Read") || !strcmp (m->name, "Write")) && m->is_generic) {
4461 memset (&ctx, 0, sizeof (ctx));
4462 args [0] = &mono_defaults.object_class->byval_arg;
4463 ctx.method_inst = mono_metadata_get_generic_inst (1, args);
4464 add_extra_method (acfg, mono_marshal_get_native_wrapper (mono_class_inflate_generic_method_checked (m, &ctx, &error), TRUE, TRUE));
4465 g_assert (mono_error_ok (&error)); /* FIXME don't swallow the error */
4474 * is_direct_callable:
4476 * Return whenever the method identified by JI is directly callable without
4477 * going through the PLT.
4480 is_direct_callable (MonoAotCompile *acfg, MonoMethod *method, MonoJumpInfo *patch_info)
4482 if ((patch_info->type == MONO_PATCH_INFO_METHOD) && (patch_info->data.method->klass->image == acfg->image)) {
4483 MonoCompile *callee_cfg = g_hash_table_lookup (acfg->method_to_cfg, patch_info->data.method);
4485 gboolean direct_callable = TRUE;
4487 if (direct_callable && !(!callee_cfg->has_got_slots && (callee_cfg->method->klass->flags & TYPE_ATTRIBUTE_BEFORE_FIELD_INIT)))
4488 direct_callable = FALSE;
4489 if ((callee_cfg->method->iflags & METHOD_IMPL_ATTRIBUTE_SYNCHRONIZED) && (!method || method->wrapper_type != MONO_WRAPPER_SYNCHRONIZED))
4490 // FIXME: Maybe call the wrapper directly ?
4491 direct_callable = FALSE;
4493 if (acfg->aot_opts.soft_debug || acfg->aot_opts.no_direct_calls) {
4494 /* Disable this so all calls go through load_method (), see the
4495 * mini_get_debug_options ()->load_aot_jit_info_eagerly = TRUE; line in
4496 * mono_debugger_agent_init ().
4498 direct_callable = FALSE;
4501 if (callee_cfg->method->wrapper_type == MONO_WRAPPER_ALLOC)
4502 /* sgen does some initialization when the allocator method is created */
4503 direct_callable = FALSE;
4505 if (direct_callable)
4508 } else if ((patch_info->type == MONO_PATCH_INFO_ICALL_ADDR && patch_info->data.method->flags & METHOD_ATTRIBUTE_PINVOKE_IMPL)) {
4509 if (acfg->aot_opts.direct_pinvoke)
4511 } else if (patch_info->type == MONO_PATCH_INFO_ICALL_ADDR) {
4512 if (acfg->aot_opts.direct_icalls)
4520 #ifdef MONO_ARCH_AOT_SUPPORTED
4522 get_pinvoke_import (MonoAotCompile *acfg, MonoMethod *method)
4524 MonoImage *image = method->klass->image;
4525 MonoMethodPInvoke *piinfo = (MonoMethodPInvoke *) method;
4526 MonoTableInfo *tables = image->tables;
4527 MonoTableInfo *im = &tables [MONO_TABLE_IMPLMAP];
4528 MonoTableInfo *mr = &tables [MONO_TABLE_MODULEREF];
4529 guint32 im_cols [MONO_IMPLMAP_SIZE];
4532 import = g_hash_table_lookup (acfg->method_to_pinvoke_import, method);
4536 if (!piinfo->implmap_idx || piinfo->implmap_idx > im->rows)
4539 mono_metadata_decode_row (im, piinfo->implmap_idx - 1, im_cols, MONO_IMPLMAP_SIZE);
4541 if (!im_cols [MONO_IMPLMAP_SCOPE] || im_cols [MONO_IMPLMAP_SCOPE] > mr->rows)
4544 import = g_strdup_printf ("%s", mono_metadata_string_heap (image, im_cols [MONO_IMPLMAP_NAME]));
4546 g_hash_table_insert (acfg->method_to_pinvoke_import, method, import);
4553 compare_lne (MonoDebugLineNumberEntry *a, MonoDebugLineNumberEntry *b)
4555 if (a->native_offset == b->native_offset)
4556 return a->il_offset - b->il_offset;
4558 return a->native_offset - b->native_offset;
4562 * compute_line_numbers:
4564 * Returns a sparse array of size CODE_SIZE containing MonoDebugSourceLocation* entries for the native offsets which have a corresponding line number
4567 static MonoDebugSourceLocation**
4568 compute_line_numbers (MonoMethod *method, int code_size, MonoDebugMethodJitInfo *debug_info)
4570 MonoDebugMethodInfo *minfo;
4571 MonoDebugLineNumberEntry *ln_array;
4572 MonoDebugSourceLocation *loc;
4573 int i, prev_line, prev_il_offset;
4574 int *native_to_il_offset = NULL;
4575 MonoDebugSourceLocation **res;
4578 minfo = mono_debug_lookup_method (method);
4581 // FIXME: This seems to happen when two methods have the same cfg->method_to_register
4582 if (debug_info->code_size != code_size)
4585 g_assert (code_size);
4587 /* Compute the native->IL offset mapping */
4589 ln_array = g_new0 (MonoDebugLineNumberEntry, debug_info->num_line_numbers);
4590 memcpy (ln_array, debug_info->line_numbers, debug_info->num_line_numbers * sizeof (MonoDebugLineNumberEntry));
4592 qsort (ln_array, debug_info->num_line_numbers, sizeof (MonoDebugLineNumberEntry), (gpointer)compare_lne);
4594 native_to_il_offset = g_new0 (int, code_size + 1);
4596 for (i = 0; i < debug_info->num_line_numbers; ++i) {
4598 MonoDebugLineNumberEntry *lne = &ln_array [i];
4601 for (j = 0; j < lne->native_offset; ++j)
4602 native_to_il_offset [j] = -1;
4605 if (i < debug_info->num_line_numbers - 1) {
4606 MonoDebugLineNumberEntry *lne_next = &ln_array [i + 1];
4608 for (j = lne->native_offset; j < lne_next->native_offset; ++j)
4609 native_to_il_offset [j] = lne->il_offset;
4611 for (j = lne->native_offset; j < code_size; ++j)
4612 native_to_il_offset [j] = lne->il_offset;
4617 /* Compute the native->line number mapping */
4618 res = g_new0 (MonoDebugSourceLocation*, code_size);
4619 prev_il_offset = -1;
4622 for (i = 0; i < code_size; ++i) {
4623 int il_offset = native_to_il_offset [i];
4625 if (il_offset == -1 || il_offset == prev_il_offset)
4627 prev_il_offset = il_offset;
4628 loc = mono_debug_symfile_lookup_location (minfo, il_offset);
4629 if (!(loc && loc->source_file))
4631 if (loc->row == prev_line) {
4632 mono_debug_symfile_free_location (loc);
4635 prev_line = loc->row;
4636 //printf ("D: %s:%d il=%x native=%x\n", loc->source_file, loc->row, il_offset, i);
4638 /* This will cover the prolog too */
4648 get_file_index (MonoAotCompile *acfg, const char *source_file)
4652 // FIXME: Free these
4653 if (!acfg->dwarf_ln_filenames)
4654 acfg->dwarf_ln_filenames = g_hash_table_new (g_str_hash, g_str_equal);
4655 findex = GPOINTER_TO_INT (g_hash_table_lookup (acfg->dwarf_ln_filenames, source_file));
4657 findex = g_hash_table_size (acfg->dwarf_ln_filenames) + 1;
4658 g_hash_table_insert (acfg->dwarf_ln_filenames, g_strdup (source_file), GINT_TO_POINTER (findex));
4659 emit_unset_mode (acfg);
4660 fprintf (acfg->fp, ".file %d \"%s\"\n", findex, mono_dwarf_escape_path (source_file));
4672 * emit_and_reloc_code:
4674 * Emit the native code in CODE, handling relocations along the way. If GOT_ONLY
4675 * is true, calls are made through the GOT too. This is used for emitting trampolines
4676 * in full-aot mode, since calls made from trampolines couldn't go through the PLT,
4677 * since trampolines are needed to make PTL work.
4680 emit_and_reloc_code (MonoAotCompile *acfg, MonoMethod *method, guint8 *code, guint32 code_len, MonoJumpInfo *relocs, gboolean got_only, MonoDebugMethodJitInfo *debug_info)
4682 int i, pindex, start_index;
4684 MonoJumpInfo *patch_info;
4685 MonoDebugSourceLocation **locs = NULL;
4687 #ifdef MONO_ARCH_AOT_SUPPORTED
4688 gboolean direct_call, external_call;
4690 const char *direct_call_target = 0;
4691 const char *direct_pinvoke;
4694 if (acfg->gas_line_numbers && method && debug_info) {
4695 locs = compute_line_numbers (method, code_len, debug_info);
4697 int findex = get_file_index (acfg, "<unknown>");
4698 emit_unset_mode (acfg);
4699 fprintf (acfg->fp, ".loc %d %d 0\n", findex, 1);
4703 /* Collect and sort relocations */
4704 patches = g_ptr_array_new ();
4705 for (patch_info = relocs; patch_info; patch_info = patch_info->next)
4706 g_ptr_array_add (patches, patch_info);
4707 g_ptr_array_sort (patches, compare_patches);
4710 for (i = 0; i < code_len; i += INST_LEN) {
4712 for (pindex = start_index; pindex < patches->len; ++pindex) {
4713 patch_info = g_ptr_array_index (patches, pindex);
4714 if (patch_info->ip.i >= i)
4718 if (locs && locs [i]) {
4719 MonoDebugSourceLocation *loc = locs [i];
4722 findex = get_file_index (acfg, loc->source_file);
4723 emit_unset_mode (acfg);
4724 fprintf (acfg->fp, ".loc %d %d 0\n", findex, loc->row);
4725 mono_debug_symfile_free_location (loc);
4729 #ifdef MONO_ARCH_AOT_SUPPORTED
4730 if (patch_info && (patch_info->ip.i == i) && (pindex < patches->len)) {
4731 start_index = pindex;
4733 switch (patch_info->type) {
4734 case MONO_PATCH_INFO_NONE:
4736 case MONO_PATCH_INFO_GOT_OFFSET: {
4739 arch_emit_got_offset (acfg, code + i, &code_size);
4740 i += code_size - INST_LEN;
4742 patch_info->type = MONO_PATCH_INFO_NONE;
4745 case MONO_PATCH_INFO_OBJC_SELECTOR_REF: {
4746 int code_size, index;
4747 char *selector = (void*)patch_info->data.target;
4749 if (!acfg->objc_selector_to_index)
4750 acfg->objc_selector_to_index = g_hash_table_new (g_str_hash, g_str_equal);
4751 if (!acfg->objc_selectors)
4752 acfg->objc_selectors = g_ptr_array_new ();
4753 index = GPOINTER_TO_UINT (g_hash_table_lookup (acfg->objc_selector_to_index, selector));
4757 index = acfg->objc_selector_index;
4758 g_ptr_array_add (acfg->objc_selectors, (void*)patch_info->data.target);
4759 g_hash_table_insert (acfg->objc_selector_to_index, selector, GUINT_TO_POINTER (index + 1));
4760 acfg->objc_selector_index ++;
4763 arch_emit_objc_selector_ref (acfg, code + i, index, &code_size);
4764 i += code_size - INST_LEN;
4766 patch_info->type = MONO_PATCH_INFO_NONE;
4771 * If this patch is a call, try emitting a direct call instead of
4772 * through a PLT entry. This is possible if the called method is in
4773 * the same assembly and requires no initialization.
4775 direct_call = FALSE;
4776 external_call = FALSE;
4777 if ((patch_info->type == MONO_PATCH_INFO_METHOD) && (patch_info->data.method->klass->image == acfg->image)) {
4778 if (!got_only && is_direct_callable (acfg, method, patch_info)) {
4779 MonoCompile *callee_cfg = g_hash_table_lookup (acfg->method_to_cfg, patch_info->data.method);
4780 //printf ("DIRECT: %s %s\n", method ? mono_method_full_name (method, TRUE) : "", mono_method_full_name (callee_cfg->method, TRUE));
4782 direct_call_target = callee_cfg->asm_symbol;
4783 patch_info->type = MONO_PATCH_INFO_NONE;
4784 acfg->stats.direct_calls ++;
4787 acfg->stats.all_calls ++;
4788 } else if (patch_info->type == MONO_PATCH_INFO_ICALL_ADDR) {
4789 if (!got_only && is_direct_callable (acfg, method, patch_info)) {
4790 if (!(patch_info->data.method->flags & METHOD_ATTRIBUTE_PINVOKE_IMPL))
4791 direct_pinvoke = mono_lookup_icall_symbol (patch_info->data.method);
4793 direct_pinvoke = get_pinvoke_import (acfg, patch_info->data.method);
4794 if (direct_pinvoke) {
4796 g_assert (strlen (direct_pinvoke) < 1000);
4797 direct_call_target = g_strdup_printf ("%s%s", acfg->user_symbol_prefix, direct_pinvoke);
4800 } else if (patch_info->type == MONO_PATCH_INFO_JIT_ICALL_ADDR) {
4801 const char *sym = mono_lookup_jit_icall_symbol (patch_info->data.name);
4802 if (!got_only && sym && acfg->aot_opts.direct_icalls) {
4803 /* Call to a C function implementing a jit icall */
4805 external_call = TRUE;
4806 g_assert (strlen (sym) < 1000);
4807 direct_call_target = g_strdup_printf ("%s%s", acfg->user_symbol_prefix, sym);
4809 } else if (patch_info->type == MONO_PATCH_INFO_INTERNAL_METHOD) {
4810 MonoJitICallInfo *info = mono_find_jit_icall_by_name (patch_info->data.name);
4811 const char *sym = mono_lookup_jit_icall_symbol (patch_info->data.name);
4812 if (!got_only && sym && acfg->aot_opts.direct_icalls && info->func == info->wrapper) {
4813 /* Call to a jit icall without a wrapper */
4815 external_call = TRUE;
4816 g_assert (strlen (sym) < 1000);
4817 direct_call_target = g_strdup_printf ("%s%s", acfg->user_symbol_prefix, sym);
4822 patch_info->type = MONO_PATCH_INFO_NONE;
4823 acfg->stats.direct_calls ++;
4826 if (!got_only && !direct_call) {
4827 MonoPltEntry *plt_entry = get_plt_entry (acfg, patch_info);
4829 /* This patch has a PLT entry, so we must emit a call to the PLT entry */
4831 direct_call_target = plt_entry->symbol;
4833 /* Nullify the patch */
4834 patch_info->type = MONO_PATCH_INFO_NONE;
4835 plt_entry->jit_used = TRUE;
4842 arch_emit_direct_call (acfg, direct_call_target, external_call, FALSE, patch_info, &call_size);
4843 i += call_size - INST_LEN;
4847 got_slot = get_got_offset (acfg, FALSE, patch_info);
4849 arch_emit_got_access (acfg, code + i, got_slot, &code_size);
4850 i += code_size - INST_LEN;
4856 #endif /* MONO_ARCH_AOT_SUPPORTED */
4859 /* Find next patch */
4861 for (pindex = start_index; pindex < patches->len; ++pindex) {
4862 patch_info = g_ptr_array_index (patches, pindex);
4863 if (patch_info->ip.i >= i)
4867 /* Try to emit multiple bytes at once */
4868 if (pindex < patches->len && patch_info->ip.i > i) {
4871 for (limit = i + INST_LEN; limit < patch_info->ip.i; limit += INST_LEN) {
4872 if (locs && locs [limit])
4876 emit_code_bytes (acfg, code + i, limit - i);
4877 i = limit - INST_LEN;
4879 emit_code_bytes (acfg, code + i, INST_LEN);
4890 * Return a modified version of S which only includes characters permissible in symbols.
4893 sanitize_symbol (MonoAotCompile *acfg, char *s)
4895 gboolean process = FALSE;
4904 for (i = 0; i < len; ++i)
4905 if (!(s [i] <= 0x7f && (isalnum (s [i]) || s [i] == '_')))
4910 gs = g_string_sized_new (len);
4911 for (i = 0; i < len; ++i) {
4913 if (c <= 0x7f && (isalnum (c) || c == '_')) {
4914 g_string_append_c (gs, c);
4915 } else if (c > 0x7f) {
4916 /* multi-byte utf8 */
4917 g_string_append_printf (gs, "_0x%x", c);
4920 while (c >> 6 == 0x2) {
4921 g_string_append_printf (gs, "%x", c);
4925 g_string_append_printf (gs, "_");
4928 g_string_append_c (gs, '_');
4932 res = mono_mempool_strdup (acfg->mempool, gs->str);
4933 g_string_free (gs, TRUE);
4938 get_debug_sym (MonoMethod *method, const char *prefix, GHashTable *cache)
4940 char *name1, *name2, *cached;
4941 int i, j, len, count;
4942 MonoMethod *cached_method;
4944 name1 = mono_method_full_name (method, TRUE);
4947 // This is so that we don't accidentally create a local symbol (which starts with 'L')
4948 if ((!prefix || !*prefix) && name1 [0] == 'L')
4952 len = strlen (name1);
4953 name2 = malloc (strlen (prefix) + len + 16);
4954 memcpy (name2, prefix, strlen (prefix));
4955 j = strlen (prefix);
4956 for (i = 0; i < len; ++i) {
4957 if (isalnum (name1 [i])) {
4958 name2 [j ++] = name1 [i];
4959 } else if (name1 [i] == ' ' && name1 [i + 1] == '(' && name1 [i + 2] == ')') {
4961 } else if (name1 [i] == ',' && name1 [i + 1] == ' ') {
4964 } else if (name1 [i] == '(' || name1 [i] == ')' || name1 [i] == '>') {
4974 cached_method = g_hash_table_lookup (cache, name2);
4975 if (!(cached_method && cached_method != method))
4977 sprintf (name2 + j, "_%d", count);
4981 cached = g_strdup (name2);
4982 g_hash_table_insert (cache, cached, method);
4988 emit_method_code (MonoAotCompile *acfg, MonoCompile *cfg)
4993 char *debug_sym = NULL;
4994 char *symbol = NULL;
4995 int func_alignment = AOT_FUNC_ALIGNMENT;
4998 method = cfg->orig_method;
4999 code = cfg->native_code;
5001 method_index = get_method_index (acfg, method);
5002 symbol = g_strdup_printf ("%sme_%x", acfg->temp_prefix, method_index);
5004 /* Make the labels local */
5005 emit_section_change (acfg, ".text", 0);
5006 emit_alignment_code (acfg, func_alignment);
5008 if (acfg->global_symbols && acfg->need_no_dead_strip)
5009 fprintf (acfg->fp, " .no_dead_strip %s\n", cfg->asm_symbol);
5011 emit_label (acfg, cfg->asm_symbol);
5013 if (acfg->aot_opts.write_symbols && !acfg->global_symbols && !acfg->llvm_separate) {
5015 * Write a C style symbol for every method, this has two uses:
5016 * - it works on platforms where the dwarf debugging info is not
5018 * - it allows the setting of breakpoints of aot-ed methods.
5020 debug_sym = get_debug_sym (method, "", acfg->method_label_hash);
5021 cfg->asm_debug_symbol = g_strdup (debug_sym);
5023 if (acfg->need_no_dead_strip)
5024 fprintf (acfg->fp, " .no_dead_strip %s\n", debug_sym);
5025 emit_local_symbol (acfg, debug_sym, symbol, TRUE);
5026 emit_label (acfg, debug_sym);
5029 export_name = g_hash_table_lookup (acfg->export_names, method);
5031 /* Emit a global symbol for the method */
5032 emit_global_inner (acfg, export_name, TRUE);
5033 emit_label (acfg, export_name);
5036 if (cfg->verbose_level > 0)
5037 g_print ("Method %s emitted as %s\n", mono_method_full_name (method, TRUE), cfg->asm_symbol);
5039 acfg->stats.code_size += cfg->code_len;
5041 acfg->cfgs [method_index]->got_offset = acfg->got_offset;
5043 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 ()));
5047 if (acfg->aot_opts.write_symbols) {
5049 emit_symbol_size (acfg, debug_sym, ".");
5051 emit_symbol_size (acfg, cfg->asm_symbol, ".");
5055 emit_label (acfg, symbol);
5062 * Encode PATCH_INFO into its disk representation.
5065 encode_patch (MonoAotCompile *acfg, MonoJumpInfo *patch_info, guint8 *buf, guint8 **endbuf)
5069 switch (patch_info->type) {
5070 case MONO_PATCH_INFO_NONE:
5072 case MONO_PATCH_INFO_IMAGE:
5073 encode_value (get_image_index (acfg, patch_info->data.image), p, &p);
5075 case MONO_PATCH_INFO_MSCORLIB_GOT_ADDR:
5076 case MONO_PATCH_INFO_JIT_TLS_ID:
5077 case MONO_PATCH_INFO_GC_CARD_TABLE_ADDR:
5079 case MONO_PATCH_INFO_CASTCLASS_CACHE:
5080 encode_value (patch_info->data.index, p, &p);
5082 case MONO_PATCH_INFO_METHOD_REL:
5083 encode_value ((gint)patch_info->data.offset, p, &p);
5085 case MONO_PATCH_INFO_SWITCH: {
5086 gpointer *table = (gpointer *)patch_info->data.table->table;
5089 encode_value (patch_info->data.table->table_size, p, &p);
5090 for (k = 0; k < patch_info->data.table->table_size; k++)
5091 encode_value ((int)(gssize)table [k], p, &p);
5094 case MONO_PATCH_INFO_METHODCONST:
5095 case MONO_PATCH_INFO_METHOD:
5096 case MONO_PATCH_INFO_METHOD_JUMP:
5097 case MONO_PATCH_INFO_ICALL_ADDR:
5098 case MONO_PATCH_INFO_METHOD_RGCTX:
5099 case MONO_PATCH_INFO_METHOD_CODE_SLOT:
5100 encode_method_ref (acfg, patch_info->data.method, p, &p);
5102 case MONO_PATCH_INFO_INTERNAL_METHOD:
5103 case MONO_PATCH_INFO_JIT_ICALL_ADDR: {
5104 guint32 len = strlen (patch_info->data.name);
5106 encode_value (len, p, &p);
5108 memcpy (p, patch_info->data.name, len);
5113 case MONO_PATCH_INFO_LDSTR: {
5114 guint32 image_index = get_image_index (acfg, patch_info->data.token->image);
5115 guint32 token = patch_info->data.token->token;
5116 g_assert (mono_metadata_token_code (token) == MONO_TOKEN_STRING);
5117 encode_value (image_index, p, &p);
5118 encode_value (patch_info->data.token->token - MONO_TOKEN_STRING, p, &p);
5121 case MONO_PATCH_INFO_RVA:
5122 case MONO_PATCH_INFO_DECLSEC:
5123 case MONO_PATCH_INFO_LDTOKEN:
5124 case MONO_PATCH_INFO_TYPE_FROM_HANDLE:
5125 encode_value (get_image_index (acfg, patch_info->data.token->image), p, &p);
5126 encode_value (patch_info->data.token->token, p, &p);
5127 encode_value (patch_info->data.token->has_context, p, &p);
5128 if (patch_info->data.token->has_context)
5129 encode_generic_context (acfg, &patch_info->data.token->context, p, &p);
5131 case MONO_PATCH_INFO_EXC_NAME: {
5132 MonoClass *ex_class;
5135 mono_class_from_name (mono_defaults.exception_class->image,
5136 "System", patch_info->data.target);
5137 g_assert (ex_class);
5138 encode_klass_ref (acfg, ex_class, p, &p);
5141 case MONO_PATCH_INFO_R4:
5142 encode_value (*((guint32 *)patch_info->data.target), p, &p);
5144 case MONO_PATCH_INFO_R8:
5145 encode_value (((guint32 *)patch_info->data.target) [MINI_LS_WORD_IDX], p, &p);
5146 encode_value (((guint32 *)patch_info->data.target) [MINI_MS_WORD_IDX], p, &p);
5148 case MONO_PATCH_INFO_VTABLE:
5149 case MONO_PATCH_INFO_CLASS:
5150 case MONO_PATCH_INFO_IID:
5151 case MONO_PATCH_INFO_ADJUSTED_IID:
5152 case MONO_PATCH_INFO_CLASS_INIT:
5153 encode_klass_ref (acfg, patch_info->data.klass, p, &p);
5155 case MONO_PATCH_INFO_DELEGATE_TRAMPOLINE:
5156 encode_klass_ref (acfg, patch_info->data.del_tramp->klass, p, &p);
5157 if (patch_info->data.del_tramp->method) {
5158 encode_value (1, p, &p);
5159 encode_method_ref (acfg, patch_info->data.del_tramp->method, p, &p);
5161 encode_value (0, p, &p);
5163 encode_value (patch_info->data.del_tramp->virtual, p, &p);
5165 case MONO_PATCH_INFO_FIELD:
5166 case MONO_PATCH_INFO_SFLDA:
5167 encode_field_info (acfg, patch_info->data.field, p, &p);
5169 case MONO_PATCH_INFO_INTERRUPTION_REQUEST_FLAG:
5171 case MONO_PATCH_INFO_RGCTX_FETCH: {
5172 MonoJumpInfoRgctxEntry *entry = patch_info->data.rgctx_entry;
5177 * entry->method has a lenghtly encoding and multiple rgctx_fetch entries
5178 * reference the same method, so encode the method only once.
5180 offset = GPOINTER_TO_UINT (g_hash_table_lookup (acfg->method_blob_hash, entry->method));
5182 buf2 = g_malloc (1024);
5185 encode_method_ref (acfg, entry->method, p2, &p2);
5186 g_assert (p2 - buf2 < 1024);
5188 offset = add_to_blob (acfg, buf2, p2 - buf2);
5191 g_hash_table_insert (acfg->method_blob_hash, entry->method, GUINT_TO_POINTER (offset + 1));
5196 encode_value (offset, p, &p);
5197 g_assert ((int)entry->info_type < 256);
5198 g_assert (entry->data->type < 256);
5199 encode_value ((entry->in_mrgctx ? 1 : 0) | (entry->info_type << 1) | (entry->data->type << 9), p, &p);
5200 encode_patch (acfg, entry->data, p, &p);
5203 case MONO_PATCH_INFO_GENERIC_CLASS_INIT:
5204 case MONO_PATCH_INFO_MONITOR_ENTER:
5205 case MONO_PATCH_INFO_MONITOR_ENTER_V4:
5206 case MONO_PATCH_INFO_MONITOR_EXIT:
5207 case MONO_PATCH_INFO_SEQ_POINT_INFO:
5209 case MONO_PATCH_INFO_LLVM_IMT_TRAMPOLINE:
5210 encode_method_ref (acfg, patch_info->data.imt_tramp->method, p, &p);
5211 encode_value (patch_info->data.imt_tramp->vt_offset, p, &p);
5213 case MONO_PATCH_INFO_SIGNATURE:
5214 encode_signature (acfg, (MonoMethodSignature*)patch_info->data.target, p, &p);
5216 case MONO_PATCH_INFO_TLS_OFFSET:
5217 encode_value (GPOINTER_TO_INT (patch_info->data.target), p, &p);
5219 case MONO_PATCH_INFO_GSHAREDVT_CALL:
5220 encode_signature (acfg, (MonoMethodSignature*)patch_info->data.gsharedvt->sig, p, &p);
5221 encode_method_ref (acfg, patch_info->data.gsharedvt->method, p, &p);
5223 case MONO_PATCH_INFO_GSHAREDVT_METHOD: {
5224 MonoGSharedVtMethodInfo *info = patch_info->data.gsharedvt_method;
5227 encode_method_ref (acfg, info->method, p, &p);
5228 encode_value (info->num_entries, p, &p);
5229 for (i = 0; i < info->num_entries; ++i) {
5230 MonoRuntimeGenericContextInfoTemplate *template = &info->entries [i];
5232 encode_value (template->info_type, p, &p);
5233 switch (mini_rgctx_info_type_to_patch_info_type (template->info_type)) {
5234 case MONO_PATCH_INFO_CLASS:
5235 encode_klass_ref (acfg, mono_class_from_mono_type (template->data), p, &p);
5237 case MONO_PATCH_INFO_FIELD:
5238 encode_field_info (acfg, template->data, p, &p);
5241 g_assert_not_reached ();
5247 case MONO_PATCH_INFO_LDSTR_LIT: {
5248 const char *s = patch_info->data.target;
5249 int len = strlen (s);
5251 encode_value (len, p, &p);
5252 memcpy (p, s, len + 1);
5257 g_warning ("unable to handle jump info %d", patch_info->type);
5258 g_assert_not_reached ();
5265 encode_patch_list (MonoAotCompile *acfg, GPtrArray *patches, int n_patches, gboolean llvm, int first_got_offset, guint8 *buf, guint8 **endbuf)
5268 guint32 pindex, offset;
5269 MonoJumpInfo *patch_info;
5271 encode_value (n_patches, p, &p);
5273 for (pindex = 0; pindex < patches->len; ++pindex) {
5274 patch_info = g_ptr_array_index (patches, pindex);
5276 if (patch_info->type == MONO_PATCH_INFO_NONE || patch_info->type == MONO_PATCH_INFO_BB)
5280 offset = get_got_offset (acfg, llvm, patch_info);
5281 encode_value (offset, p, &p);
5288 emit_method_info (MonoAotCompile *acfg, MonoCompile *cfg)
5292 int pindex, buf_size, n_patches;
5294 MonoJumpInfo *patch_info;
5295 guint32 method_index;
5297 guint32 first_got_offset;
5299 method = cfg->orig_method;
5301 method_index = get_method_index (acfg, method);
5303 /* Sort relocations */
5304 patches = g_ptr_array_new ();
5305 for (patch_info = cfg->patch_info; patch_info; patch_info = patch_info->next)
5306 g_ptr_array_add (patches, patch_info);
5307 g_ptr_array_sort (patches, compare_patches);
5309 first_got_offset = acfg->cfgs [method_index]->got_offset;
5311 /**********************/
5312 /* Encode method info */
5313 /**********************/
5315 buf_size = (patches->len < 1000) ? 40960 : 40960 + (patches->len * 64);
5316 p = buf = g_malloc (buf_size);
5318 if (mono_class_get_cctor (method->klass))
5319 encode_klass_ref (acfg, method->klass, p, &p);
5321 /* Not needed when loading the method */
5322 encode_value (0, p, &p);
5325 if (cfg->opt & MONO_OPT_SHARED) {
5326 encode_value (g_list_length (cfg->ldstr_list), p, &p);
5327 for (l = cfg->ldstr_list; l; l = l->next) {
5328 encode_value ((long)l->data, p, &p);
5332 /* Used only in shared mode */
5333 g_assert (!cfg->ldstr_list);
5336 for (pindex = 0; pindex < patches->len; ++pindex) {
5337 patch_info = g_ptr_array_index (patches, pindex);
5339 if ((patch_info->type == MONO_PATCH_INFO_GOT_OFFSET) ||
5340 (patch_info->type == MONO_PATCH_INFO_NONE)) {
5341 patch_info->type = MONO_PATCH_INFO_NONE;
5346 if ((patch_info->type == MONO_PATCH_INFO_IMAGE) && (patch_info->data.image == acfg->image)) {
5347 /* Stored in a GOT slot initialized at module load time */
5348 patch_info->type = MONO_PATCH_INFO_NONE;
5352 if (patch_info->type == MONO_PATCH_INFO_GC_CARD_TABLE_ADDR) {
5353 /* Stored in a GOT slot initialized at module load time */
5354 patch_info->type = MONO_PATCH_INFO_NONE;
5358 if (is_plt_patch (patch_info)) {
5359 /* Calls are made through the PLT */
5360 patch_info->type = MONO_PATCH_INFO_NONE;
5368 g_assert (cfg->has_got_slots);
5370 encode_patch_list (acfg, patches, n_patches, cfg->compile_llvm, first_got_offset, p, &p);
5372 acfg->stats.info_size += p - buf;
5374 g_assert (p - buf < buf_size);
5376 cfg->method_info_offset = add_to_blob (acfg, buf, p - buf);
5381 get_unwind_info_offset (MonoAotCompile *acfg, guint8 *encoded, guint32 encoded_len)
5383 guint32 cache_index;
5386 /* Reuse the unwind module to canonize and store unwind info entries */
5387 cache_index = mono_cache_unwind_info (encoded, encoded_len);
5389 /* Use +/- 1 to distinguish 0s from missing entries */
5390 offset = GPOINTER_TO_UINT (g_hash_table_lookup (acfg->unwind_info_offsets, GUINT_TO_POINTER (cache_index + 1)));
5398 * It would be easier to use assembler symbols, but the caller needs an
5401 offset = acfg->unwind_info_offset;
5402 g_hash_table_insert (acfg->unwind_info_offsets, GUINT_TO_POINTER (cache_index + 1), GUINT_TO_POINTER (offset + 1));
5403 g_ptr_array_add (acfg->unwind_ops, GUINT_TO_POINTER (cache_index));
5406 encode_value (encoded_len, p, &p);
5408 acfg->unwind_info_offset += encoded_len + (p - buf);
5414 emit_exception_debug_info (MonoAotCompile *acfg, MonoCompile *cfg, gboolean store_seq_points)
5417 guint32 debug_info_size, seq_points_size;
5419 MonoMethodHeader *header;
5420 guint8 *p, *buf, *debug_info;
5421 MonoJitInfo *jinfo = cfg->jit_info;
5423 gboolean use_unwind_ops = FALSE;
5424 MonoSeqPointInfo *seq_points;
5426 code = cfg->native_code;
5427 header = cfg->header;
5429 if (!acfg->aot_opts.nodebug) {
5430 mono_debug_serialize_debug_info (cfg, &debug_info, &debug_info_size);
5433 debug_info_size = 0;
5436 seq_points = cfg->seq_point_info;
5437 seq_points_size = (store_seq_points)? seq_point_info_get_write_size (seq_points) : 0;
5439 buf_size = header->num_clauses * 256 + debug_info_size + 2048 + seq_points_size + cfg->gc_map_size;
5441 p = buf = g_malloc (buf_size);
5443 use_unwind_ops = cfg->unwind_ops != NULL;
5445 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);
5447 encode_value (flags, p, &p);
5449 if (use_unwind_ops) {
5450 guint32 encoded_len;
5452 guint32 unwind_desc;
5454 encoded = mono_unwind_ops_encode (cfg->unwind_ops, &encoded_len);
5456 unwind_desc = get_unwind_info_offset (acfg, encoded, encoded_len);
5457 encode_value (unwind_desc, p, &p);
5459 encode_value (jinfo->unwind_info, p, &p);
5462 /*Encode the number of holes before the number of clauses to make decoding easier*/
5463 if (jinfo->has_try_block_holes) {
5464 MonoTryBlockHoleTableJitInfo *table = mono_jit_info_get_try_block_hole_table_info (jinfo);
5465 encode_value (table->num_holes, p, &p);
5468 if (jinfo->has_arch_eh_info) {
5470 * In AOT mode, the code length is calculated from the address of the previous method,
5471 * which could include alignment padding, so calculating the start of the epilog as
5472 * code_len - epilog_size is correct any more. Save the real code len as a workaround.
5474 encode_value (jinfo->code_size, p, &p);
5477 /* Exception table */
5478 if (cfg->compile_llvm) {
5480 * When using LLVM, we can't emit some data, like pc offsets, this reg/offset etc.,
5481 * since the information is only available to llc. Instead, we let llc save the data
5482 * into the LSDA, and read it from there at runtime.
5484 /* The assembly might be CIL stripped so emit the data ourselves */
5485 if (header->num_clauses)
5486 encode_value (header->num_clauses, p, &p);
5488 for (k = 0; k < header->num_clauses; ++k) {
5489 MonoExceptionClause *clause;
5491 clause = &header->clauses [k];
5493 encode_value (clause->flags, p, &p);
5494 if (clause->data.catch_class) {
5495 encode_value (1, p, &p);
5496 encode_klass_ref (acfg, clause->data.catch_class, p, &p);
5498 encode_value (0, p, &p);
5501 /* Emit a list of nesting clauses */
5502 for (i = 0; i < header->num_clauses; ++i) {
5504 MonoExceptionClause *clause1 = &header->clauses [cindex1];
5506 MonoExceptionClause *clause2 = &header->clauses [cindex2];
5508 if (cindex1 != cindex2 && clause1->try_offset >= clause2->try_offset && clause1->handler_offset <= clause2->handler_offset)
5509 encode_value (i, p, &p);
5511 encode_value (-1, p, &p);
5514 if (jinfo->num_clauses)
5515 encode_value (jinfo->num_clauses, p, &p);
5517 for (k = 0; k < jinfo->num_clauses; ++k) {
5518 MonoJitExceptionInfo *ei = &jinfo->clauses [k];
5520 encode_value (ei->flags, p, &p);
5521 encode_value (ei->exvar_offset, p, &p);
5523 if (ei->flags == MONO_EXCEPTION_CLAUSE_FILTER || ei->flags == MONO_EXCEPTION_CLAUSE_FINALLY)
5524 encode_value ((gint)((guint8*)ei->data.filter - code), p, &p);
5526 if (ei->data.catch_class) {
5530 buf2 = g_malloc (4096);
5532 encode_klass_ref (acfg, ei->data.catch_class, p2, &p2);
5534 g_assert (len < 4096);
5535 encode_value (len, p, &p);
5536 memcpy (p, buf2, len);
5540 encode_value (0, p, &p);
5544 encode_value ((gint)((guint8*)ei->try_start - code), p, &p);
5545 encode_value ((gint)((guint8*)ei->try_end - code), p, &p);
5546 encode_value ((gint)((guint8*)ei->handler_start - code), p, &p);
5550 if (jinfo->has_try_block_holes) {
5551 MonoTryBlockHoleTableJitInfo *table = mono_jit_info_get_try_block_hole_table_info (jinfo);
5552 for (i = 0; i < table->num_holes; ++i) {
5553 MonoTryBlockHoleJitInfo *hole = &table->holes [i];
5554 encode_value (hole->clause, p, &p);
5555 encode_value (hole->length, p, &p);
5556 encode_value (hole->offset, p, &p);
5560 if (jinfo->has_arch_eh_info) {
5561 MonoArchEHJitInfo *eh_info;
5563 eh_info = mono_jit_info_get_arch_eh_info (jinfo);
5564 encode_value (eh_info->stack_size, p, &p);
5565 encode_value (eh_info->epilog_size, p, &p);
5568 if (jinfo->has_generic_jit_info) {
5569 MonoGenericJitInfo *gi = mono_jit_info_get_generic_jit_info (jinfo);
5570 MonoGenericSharingContext* gsctx = gi->generic_sharing_context;
5574 encode_value (gi->nlocs, p, &p);
5576 for (i = 0; i < gi->nlocs; ++i) {
5577 MonoDwarfLocListEntry *entry = &gi->locations [i];
5579 encode_value (entry->is_reg ? 1 : 0, p, &p);
5580 encode_value (entry->reg, p, &p);
5582 encode_value (entry->offset, p, &p);
5584 g_assert (entry->from == 0);
5586 encode_value (entry->from, p, &p);
5587 encode_value (entry->to, p, &p);
5590 if (!cfg->compile_llvm) {
5591 encode_value (gi->has_this ? 1 : 0, p, &p);
5592 encode_value (gi->this_reg, p, &p);
5593 encode_value (gi->this_offset, p, &p);
5598 * Need to encode jinfo->method too, since it is not equal to 'method'
5599 * when using generic sharing.
5601 buf2 = g_malloc (4096);
5603 encode_method_ref (acfg, jinfo->d.method, p2, &p2);
5605 g_assert (len < 4096);
5606 encode_value (len, p, &p);
5607 memcpy (p, buf2, len);
5611 if (gsctx && (gsctx->var_is_vt || gsctx->mvar_is_vt)) {
5612 MonoMethodInflated *inflated;
5613 MonoGenericContext *context;
5614 MonoGenericInst *inst;
5616 g_assert (jinfo->d.method->is_inflated);
5617 inflated = (MonoMethodInflated*)jinfo->d.method;
5618 context = &inflated->context;
5620 encode_value (1, p, &p);
5621 if (context->class_inst) {
5622 inst = context->class_inst;
5624 encode_value (inst->type_argc, p, &p);
5625 for (i = 0; i < inst->type_argc; ++i)
5626 encode_value (gsctx->var_is_vt [i], p, &p);
5628 encode_value (0, p, &p);
5630 if (context->method_inst) {
5631 inst = context->method_inst;
5633 encode_value (inst->type_argc, p, &p);
5634 for (i = 0; i < inst->type_argc; ++i)
5635 encode_value (gsctx->mvar_is_vt [i], p, &p);
5637 encode_value (0, p, &p);
5640 encode_value (0, p, &p);
5644 if (seq_points_size)
5645 p += seq_point_info_write (seq_points, p);
5647 g_assert (debug_info_size < buf_size);
5649 encode_value (debug_info_size, p, &p);
5650 if (debug_info_size) {
5651 memcpy (p, debug_info, debug_info_size);
5652 p += debug_info_size;
5653 g_free (debug_info);
5658 encode_value (cfg->gc_map_size, p, &p);
5659 /* The GC map requires 4 bytes of alignment */
5660 while ((gsize)p % 4)
5662 memcpy (p, cfg->gc_map, cfg->gc_map_size);
5663 p += cfg->gc_map_size;
5666 acfg->stats.ex_info_size += p - buf;
5668 g_assert (p - buf < buf_size);
5671 /* The GC Map requires 4 byte alignment */
5672 cfg->ex_info_offset = add_to_blob_aligned (acfg, buf, p - buf, cfg->gc_map ? 4 : 1);
5677 emit_klass_info (MonoAotCompile *acfg, guint32 token)
5680 MonoClass *klass = mono_class_get_checked (acfg->image, token, &error);
5682 int i, buf_size, res;
5683 gboolean no_special_static, cant_encode;
5684 gpointer iter = NULL;
5687 mono_error_cleanup (&error);
5691 p = buf = g_malloc (buf_size);
5693 /* Mark as unusable */
5694 encode_value (-1, p, &p);
5696 res = add_to_blob (acfg, buf, p - buf);
5702 buf_size = 10240 + (klass->vtable_size * 16);
5703 p = buf = g_malloc (buf_size);
5707 mono_class_init (klass);
5709 mono_class_get_nested_types (klass, &iter);
5710 g_assert (klass->nested_classes_inited);
5712 mono_class_setup_vtable (klass);
5715 * Emit all the information which is required for creating vtables so
5716 * the runtime does not need to create the MonoMethod structures which
5717 * take up a lot of space.
5720 no_special_static = !mono_class_has_special_static_fields (klass);
5722 /* Check whenever we have enough info to encode the vtable */
5723 cant_encode = FALSE;
5724 for (i = 0; i < klass->vtable_size; ++i) {
5725 MonoMethod *cm = klass->vtable [i];
5727 if (cm && mono_method_signature (cm)->is_inflated && !g_hash_table_lookup (acfg->token_info_hash, cm))
5731 mono_class_has_finalizer (klass);
5733 if (klass->generic_container || cant_encode) {
5734 encode_value (-1, p, &p);
5736 encode_value (klass->vtable_size, p, &p);
5737 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);
5738 if (klass->has_cctor)
5739 encode_method_ref (acfg, mono_class_get_cctor (klass), p, &p);
5740 if (klass->has_finalize)
5741 encode_method_ref (acfg, mono_class_get_finalizer (klass), p, &p);
5743 encode_value (klass->instance_size, p, &p);
5744 encode_value (mono_class_data_size (klass), p, &p);
5745 encode_value (klass->packing_size, p, &p);
5746 encode_value (klass->min_align, p, &p);
5748 for (i = 0; i < klass->vtable_size; ++i) {
5749 MonoMethod *cm = klass->vtable [i];
5752 encode_method_ref (acfg, cm, p, &p);
5754 encode_value (0, p, &p);
5758 acfg->stats.class_info_size += p - buf;
5760 g_assert (p - buf < buf_size);
5761 res = add_to_blob (acfg, buf, p - buf);
5768 get_plt_entry_debug_sym (MonoAotCompile *acfg, MonoJumpInfo *ji, GHashTable *cache)
5770 char *debug_sym = NULL;
5774 if (acfg->llvm_separate && llvm_acfg->aot_opts.static_link) {
5775 /* Need to add a prefix to create unique symbols */
5776 prefix = g_strdup_printf ("plt_%s_", acfg->assembly_name_sym);
5778 prefix = g_strdup ("plt_");
5782 case MONO_PATCH_INFO_METHOD:
5783 debug_sym = get_debug_sym (ji->data.method, prefix, cache);
5785 case MONO_PATCH_INFO_INTERNAL_METHOD:
5786 debug_sym = g_strdup_printf ("%s_jit_icall_%s", prefix, ji->data.name);
5788 case MONO_PATCH_INFO_CLASS_INIT:
5789 s = mono_type_get_name (&ji->data.klass->byval_arg);
5790 debug_sym = g_strdup_printf ("%s__class_init_%s", prefix, s);
5793 case MONO_PATCH_INFO_RGCTX_FETCH:
5794 debug_sym = g_strdup_printf ("%s_rgctx_fetch_%d", prefix, acfg->label_generator ++);
5796 case MONO_PATCH_INFO_ICALL_ADDR: {
5797 char *s = get_debug_sym (ji->data.method, "", cache);
5799 debug_sym = g_strdup_printf ("%s_icall_native_%s", prefix, s);
5803 case MONO_PATCH_INFO_JIT_ICALL_ADDR:
5804 debug_sym = g_strdup_printf ("%s_jit_icall_native_%s", prefix, ji->data.name);
5806 case MONO_PATCH_INFO_GENERIC_CLASS_INIT:
5807 debug_sym = g_strdup_printf ("%s_generic_class_init", prefix);
5815 return sanitize_symbol (acfg, debug_sym);
5819 * Calls made from AOTed code are routed through a table of jumps similar to the
5820 * ELF PLT (Program Linkage Table). Initially the PLT entries jump to code which transfers
5821 * control to the AOT runtime through a trampoline.
5824 emit_plt (MonoAotCompile *acfg)
5830 sprintf (symbol, "plt");
5832 emit_section_change (acfg, ".text", 0);
5833 emit_alignment_code (acfg, NACL_SIZE(16, kNaClAlignment));
5834 emit_label (acfg, symbol);
5835 emit_label (acfg, acfg->plt_symbol);
5837 for (i = 0; i < acfg->plt_offset; ++i) {
5838 char *debug_sym = NULL;
5839 MonoPltEntry *plt_entry = NULL;
5843 * The first plt entry is unused.
5847 plt_entry = g_hash_table_lookup (acfg->plt_offset_to_entry, GUINT_TO_POINTER (i));
5849 debug_sym = plt_entry->debug_sym;
5851 if (acfg->thumb_mixed && !plt_entry->jit_used)
5852 /* Emit only a thumb version */
5855 /* Skip plt entries not actually called */
5856 if (!plt_entry->jit_used && !plt_entry->llvm_used)
5859 if (acfg->llvm && !acfg->thumb_mixed) {
5860 emit_label (acfg, plt_entry->llvm_symbol);
5861 if (acfg->llvm_separate) {
5862 emit_global_inner (acfg, plt_entry->llvm_symbol, TRUE);
5863 #if defined(TARGET_MACH)
5864 fprintf (acfg->fp, ".private_extern %s\n", plt_entry->llvm_symbol);
5870 if (acfg->need_no_dead_strip) {
5871 emit_unset_mode (acfg);
5872 fprintf (acfg->fp, " .no_dead_strip %s\n", debug_sym);
5874 emit_local_symbol (acfg, debug_sym, NULL, TRUE);
5875 emit_label (acfg, debug_sym);
5878 emit_label (acfg, plt_entry->symbol);
5880 arch_emit_plt_entry (acfg, i);
5883 emit_symbol_size (acfg, debug_sym, ".");
5886 if (acfg->thumb_mixed) {
5887 /* Make sure the ARM symbols don't alias the thumb ones */
5888 emit_zero_bytes (acfg, 16);
5891 * Emit a separate set of PLT entries using thumb2 which is called by LLVM generated
5894 for (i = 0; i < acfg->plt_offset; ++i) {
5895 char *debug_sym = NULL;
5896 MonoPltEntry *plt_entry = NULL;
5901 plt_entry = g_hash_table_lookup (acfg->plt_offset_to_entry, GUINT_TO_POINTER (i));
5903 /* Skip plt entries not actually called by LLVM code */
5904 if (!plt_entry->llvm_used)
5907 if (acfg->aot_opts.write_symbols) {
5908 if (plt_entry->debug_sym)
5909 debug_sym = g_strdup_printf ("%s_thumb", plt_entry->debug_sym);
5913 #if defined(TARGET_MACH)
5914 fprintf (acfg->fp, " .thumb_func %s\n", debug_sym);
5915 fprintf (acfg->fp, " .no_dead_strip %s\n", debug_sym);
5917 emit_local_symbol (acfg, debug_sym, NULL, TRUE);
5918 emit_label (acfg, debug_sym);
5920 fprintf (acfg->fp, "\n.thumb_func\n");
5922 emit_label (acfg, plt_entry->llvm_symbol);
5924 if (acfg->llvm_separate)
5925 emit_global_inner (acfg, plt_entry->llvm_symbol, TRUE);
5927 arch_emit_llvm_plt_entry (acfg, i);
5930 emit_symbol_size (acfg, debug_sym, ".");
5936 emit_symbol_size (acfg, acfg->plt_symbol, ".");
5938 sprintf (symbol, "plt_end");
5939 emit_label (acfg, symbol);
5943 * emit_trampoline_full:
5945 * If EMIT_TINFO is TRUE, emit additional information which can be used to create a MonoJitInfo for this trampoline by
5946 * create_jit_info_for_trampoline ().
5948 static G_GNUC_UNUSED void
5949 emit_trampoline_full (MonoAotCompile *acfg, int got_offset, MonoTrampInfo *info, gboolean emit_tinfo)
5951 char start_symbol [256];
5952 char end_symbol [256];
5954 guint32 buf_size, info_offset;
5955 MonoJumpInfo *patch_info;
5968 code_size = info->code_size;
5970 unwind_ops = info->unwind_ops;
5972 #ifdef __native_client_codegen__
5973 mono_nacl_fix_patches (code, ji);
5978 sprintf (start_symbol, "%s%s", acfg->user_symbol_prefix, name);
5980 emit_section_change (acfg, ".text", 0);
5981 emit_global (acfg, start_symbol, TRUE);
5982 emit_alignment_code (acfg, AOT_FUNC_ALIGNMENT);
5983 emit_label (acfg, start_symbol);
5985 sprintf (symbol, "%snamed_%s", acfg->temp_prefix, name);
5986 emit_label (acfg, symbol);
5989 * The code should access everything through the GOT, so we pass
5992 emit_and_reloc_code (acfg, NULL, code, code_size, ji, TRUE, NULL);
5994 emit_symbol_size (acfg, start_symbol, ".");
5997 sprintf (end_symbol, "%snamede_%s", acfg->temp_prefix, name);
5998 emit_label (acfg, end_symbol);
6003 /* Sort relocations */
6004 patches = g_ptr_array_new ();
6005 for (patch_info = ji; patch_info; patch_info = patch_info->next)
6006 if (patch_info->type != MONO_PATCH_INFO_NONE)
6007 g_ptr_array_add (patches, patch_info);
6008 g_ptr_array_sort (patches, compare_patches);
6010 buf_size = patches->len * 128 + 128;
6011 buf = g_malloc (buf_size);
6014 encode_patch_list (acfg, patches, patches->len, FALSE, got_offset, p, &p);
6015 g_assert (p - buf < buf_size);
6017 sprintf (symbol, "%s%s_p", acfg->user_symbol_prefix, name);
6019 info_offset = add_to_blob (acfg, buf, p - buf);
6021 emit_section_change (acfg, RODATA_SECT, 0);
6022 emit_global (acfg, symbol, FALSE);
6023 emit_label (acfg, symbol);
6025 emit_int32 (acfg, info_offset);
6029 guint32 encoded_len;
6033 * Emit additional information which can be used to reconstruct a partial MonoTrampInfo.
6035 encoded = mono_unwind_ops_encode (info->unwind_ops, &encoded_len);
6036 uw_offset = get_unwind_info_offset (acfg, encoded, encoded_len);
6039 emit_symbol_diff (acfg, end_symbol, start_symbol, 0);
6040 emit_int32 (acfg, uw_offset);
6043 /* Emit debug info */
6047 sprintf (symbol, "%s", name);
6048 sprintf (symbol2, "%snamed_%s", acfg->temp_prefix, name);
6051 mono_dwarf_writer_emit_trampoline (acfg->dwarf, symbol, symbol2, NULL, NULL, code_size, unwind_ops);
6055 static G_GNUC_UNUSED void
6056 emit_trampoline (MonoAotCompile *acfg, int got_offset, MonoTrampInfo *info)
6058 emit_trampoline_full (acfg, got_offset, info, FALSE);
6062 emit_trampolines (MonoAotCompile *acfg)
6065 char end_symbol [256];
6066 int i, tramp_got_offset;
6067 MonoAotTrampoline ntype;
6068 #ifdef MONO_ARCH_HAVE_FULL_AOT_TRAMPOLINES
6072 if (!acfg->aot_opts.full_aot)
6075 g_assert (acfg->image->assembly);
6077 /* Currently, we emit most trampolines into the mscorlib AOT image. */
6078 if (strcmp (acfg->image->assembly->aname.name, "mscorlib") == 0) {
6079 #ifdef MONO_ARCH_HAVE_FULL_AOT_TRAMPOLINES
6080 MonoTrampInfo *info;
6083 * Emit the generic trampolines.
6085 * We could save some code by treating the generic trampolines as a wrapper
6086 * method, but that approach has its own complexities, so we choose the simpler
6089 for (tramp_type = 0; tramp_type < MONO_TRAMPOLINE_NUM; ++tramp_type) {
6090 /* we overload the boolean here to indicate the slightly different trampoline needed, see mono_arch_create_generic_trampoline() */
6091 #ifdef DISABLE_REMOTING
6092 if (tramp_type == MONO_TRAMPOLINE_GENERIC_VIRTUAL_REMOTING)
6095 #ifndef MONO_ARCH_HAVE_HANDLER_BLOCK_GUARD
6096 if (tramp_type == MONO_TRAMPOLINE_HANDLER_BLOCK_GUARD)
6099 mono_arch_create_generic_trampoline (tramp_type, &info, acfg->aot_opts.use_trampolines_page? 2: TRUE);
6100 emit_trampoline (acfg, acfg->got_offset, info);
6103 mono_arch_get_nullified_class_init_trampoline (&info);
6104 emit_trampoline (acfg, acfg->got_offset, info);
6105 #if defined(MONO_ARCH_MONITOR_OBJECT_REG)
6106 mono_arch_create_monitor_enter_trampoline (&info, FALSE, TRUE);
6107 emit_trampoline (acfg, acfg->got_offset, info);
6108 #if defined(MONO_ARCH_MONITOR_LOCK_TAKEN_REG)
6109 mono_arch_create_monitor_enter_trampoline (&info, TRUE, TRUE);
6110 emit_trampoline (acfg, acfg->got_offset, info);
6112 mono_arch_create_monitor_exit_trampoline (&info, TRUE);
6113 emit_trampoline (acfg, acfg->got_offset, info);
6116 mono_arch_create_generic_class_init_trampoline (&info, TRUE);
6117 emit_trampoline (acfg, acfg->got_offset, info);
6119 /* Emit the exception related code pieces */
6120 mono_arch_get_restore_context (&info, TRUE);
6121 emit_trampoline (acfg, acfg->got_offset, info);
6122 mono_arch_get_call_filter (&info, TRUE);
6123 emit_trampoline (acfg, acfg->got_offset, info);
6124 mono_arch_get_throw_exception (&info, TRUE);
6125 emit_trampoline (acfg, acfg->got_offset, info);
6126 mono_arch_get_rethrow_exception (&info, TRUE);
6127 emit_trampoline (acfg, acfg->got_offset, info);
6128 mono_arch_get_throw_corlib_exception (&info, TRUE);
6129 emit_trampoline (acfg, acfg->got_offset, info);
6131 #ifdef MONO_ARCH_GSHAREDVT_SUPPORTED
6132 mono_arch_get_gsharedvt_trampoline (&info, TRUE);
6134 emit_trampoline_full (acfg, acfg->got_offset, info, TRUE);
6136 /* Create a separate out trampoline for more information in stack traces */
6137 info->name = g_strdup ("gsharedvt_out_trampoline");
6138 emit_trampoline_full (acfg, acfg->got_offset, info, TRUE);
6142 #if defined(MONO_ARCH_HAVE_GET_TRAMPOLINES)
6144 GSList *l = mono_arch_get_trampolines (TRUE);
6147 MonoTrampInfo *info = l->data;
6149 emit_trampoline (acfg, acfg->got_offset, info);
6155 for (i = 0; i < acfg->aot_opts.nrgctx_fetch_trampolines; ++i) {
6158 offset = MONO_RGCTX_SLOT_MAKE_RGCTX (i);
6159 mono_arch_create_rgctx_lazy_fetch_trampoline (offset, &info, TRUE);
6160 emit_trampoline (acfg, acfg->got_offset, info);
6162 offset = MONO_RGCTX_SLOT_MAKE_MRGCTX (i);
6163 mono_arch_create_rgctx_lazy_fetch_trampoline (offset, &info, TRUE);
6164 emit_trampoline (acfg, acfg->got_offset, info);
6167 #ifdef MONO_ARCH_HAVE_GENERAL_RGCTX_LAZY_FETCH_TRAMPOLINE
6168 mono_arch_create_general_rgctx_lazy_fetch_trampoline (&info, TRUE);
6169 emit_trampoline (acfg, acfg->got_offset, info);
6175 /* delegate_invoke_impl trampolines */
6176 l = mono_arch_get_delegate_invoke_impls ();
6178 MonoTrampInfo *info = l->data;
6180 emit_trampoline (acfg, acfg->got_offset, info);
6185 #endif /* #ifdef MONO_ARCH_HAVE_FULL_AOT_TRAMPOLINES */
6187 /* Emit trampolines which are numerous */
6190 * These include the following:
6191 * - specific trampolines
6192 * - static rgctx invoke trampolines
6194 * These trampolines have the same code, they are parameterized by GOT
6196 * They are defined in this file, in the arch_... routines instead of
6197 * in tramp-<ARCH>.c, since it is easier to do it this way.
6201 * When running in aot-only mode, we can't create specific trampolines at
6202 * runtime, so we create a few, and save them in the AOT file.
6203 * Normal trampolines embed their argument as a literal inside the
6204 * trampoline code, we can't do that here, so instead we embed an offset
6205 * which needs to be added to the trampoline address to get the address of
6206 * the GOT slot which contains the argument value.
6207 * The generated trampolines jump to the generic trampolines using another
6208 * GOT slot, which will be setup by the AOT loader to point to the
6209 * generic trampoline code of the given type.
6213 * FIXME: Maybe we should use more specific trampolines (i.e. one class init for
6217 emit_section_change (acfg, ".text", 0);
6219 tramp_got_offset = acfg->got_offset;
6221 for (ntype = 0; ntype < MONO_AOT_TRAMP_NUM; ++ntype) {
6223 case MONO_AOT_TRAMP_SPECIFIC:
6224 sprintf (symbol, "specific_trampolines");
6226 case MONO_AOT_TRAMP_STATIC_RGCTX:
6227 sprintf (symbol, "static_rgctx_trampolines");
6229 case MONO_AOT_TRAMP_IMT_THUNK:
6230 sprintf (symbol, "imt_thunks");
6232 case MONO_AOT_TRAMP_GSHAREDVT_ARG:
6233 sprintf (symbol, "gsharedvt_arg_trampolines");
6236 g_assert_not_reached ();
6239 sprintf (end_symbol, "%s_e", symbol);
6241 if (acfg->aot_opts.write_symbols)
6242 emit_local_symbol (acfg, symbol, end_symbol, TRUE);
6244 emit_alignment_code (acfg, AOT_FUNC_ALIGNMENT);
6245 emit_label (acfg, symbol);
6247 acfg->trampoline_got_offset_base [ntype] = tramp_got_offset;
6249 for (i = 0; i < acfg->num_trampolines [ntype]; ++i) {
6253 case MONO_AOT_TRAMP_SPECIFIC:
6254 arch_emit_specific_trampoline (acfg, tramp_got_offset, &tramp_size);
6255 tramp_got_offset += 2;
6257 case MONO_AOT_TRAMP_STATIC_RGCTX:
6258 arch_emit_static_rgctx_trampoline (acfg, tramp_got_offset, &tramp_size);
6259 tramp_got_offset += 2;
6261 case MONO_AOT_TRAMP_IMT_THUNK:
6262 arch_emit_imt_thunk (acfg, tramp_got_offset, &tramp_size);
6263 tramp_got_offset += 1;
6265 case MONO_AOT_TRAMP_GSHAREDVT_ARG:
6266 arch_emit_gsharedvt_arg_trampoline (acfg, tramp_got_offset, &tramp_size);
6267 tramp_got_offset += 2;
6270 g_assert_not_reached ();
6272 #ifdef __native_client_codegen__
6273 /* align to avoid 32-byte boundary crossings */
6274 emit_alignment (acfg, AOT_FUNC_ALIGNMENT);
6277 if (!acfg->trampoline_size [ntype]) {
6278 g_assert (tramp_size);
6279 acfg->trampoline_size [ntype] = tramp_size;
6283 emit_label (acfg, end_symbol);
6284 emit_int32 (acfg, 0);
6287 arch_emit_specific_trampoline_pages (acfg);
6289 /* Reserve some entries at the end of the GOT for our use */
6290 acfg->num_trampoline_got_entries = tramp_got_offset - acfg->got_offset;
6293 acfg->got_offset += acfg->num_trampoline_got_entries;
6297 str_begins_with (const char *str1, const char *str2)
6299 int len = strlen (str2);
6300 return strncmp (str1, str2, len) == 0;
6304 mono_aot_readonly_field_override (MonoClassField *field)
6307 for (rdv = readonly_values; rdv; rdv = rdv->next) {
6308 char *p = rdv->name;
6310 len = strlen (field->parent->name_space);
6311 if (strncmp (p, field->parent->name_space, len))
6316 len = strlen (field->parent->name);
6317 if (strncmp (p, field->parent->name, len))
6322 if (strcmp (p, field->name))
6324 switch (rdv->type) {
6326 return &rdv->value.i1;
6328 return &rdv->value.i2;
6330 return &rdv->value.i4;
6339 add_readonly_value (MonoAotOptions *opts, const char *val)
6344 /* the format of val is:
6345 * namespace.typename.fieldname=type/value
6346 * type can be i1 for uint8/int8/boolean, i2 for uint16/int16/char, i4 for uint32/int32
6348 fval = strrchr (val, '/');
6350 fprintf (stderr, "AOT : invalid format for readonly field '%s', missing /.\n", val);
6353 tval = strrchr (val, '=');
6355 fprintf (stderr, "AOT : invalid format for readonly field '%s', missing =.\n", val);
6358 rdv = g_new0 (ReadOnlyValue, 1);
6359 rdv->name = g_malloc0 (tval - val + 1);
6360 memcpy (rdv->name, val, tval - val);
6363 if (strncmp (tval, "i1", 2) == 0) {
6364 rdv->value.i1 = atoi (fval);
6365 rdv->type = MONO_TYPE_I1;
6366 } else if (strncmp (tval, "i2", 2) == 0) {
6367 rdv->value.i2 = atoi (fval);
6368 rdv->type = MONO_TYPE_I2;
6369 } else if (strncmp (tval, "i4", 2) == 0) {
6370 rdv->value.i4 = atoi (fval);
6371 rdv->type = MONO_TYPE_I4;
6373 fprintf (stderr, "AOT : unsupported type for readonly field '%s'.\n", tval);
6376 rdv->next = readonly_values;
6377 readonly_values = rdv;
6381 mono_aot_parse_options (const char *aot_options, MonoAotOptions *opts)
6383 gchar **args, **ptr;
6385 args = g_strsplit (aot_options ? aot_options : "", ",", -1);
6386 for (ptr = args; ptr && *ptr; ptr ++) {
6387 const char *arg = *ptr;
6389 if (str_begins_with (arg, "outfile=")) {
6390 opts->outfile = g_strdup (arg + strlen ("outfile="));
6391 } else if (str_begins_with (arg, "llvm-outfile=")) {
6392 opts->llvm_outfile = g_strdup (arg + strlen ("llvm-outfile="));
6393 } else if (str_begins_with (arg, "save-temps")) {
6394 opts->save_temps = TRUE;
6395 } else if (str_begins_with (arg, "keep-temps")) {
6396 opts->save_temps = TRUE;
6397 } else if (str_begins_with (arg, "write-symbols")) {
6398 opts->write_symbols = TRUE;
6399 } else if (str_begins_with (arg, "no-write-symbols")) {
6400 opts->write_symbols = FALSE;
6401 } else if (str_begins_with (arg, "metadata-only")) {
6402 opts->metadata_only = TRUE;
6403 } else if (str_begins_with (arg, "bind-to-runtime-version")) {
6404 opts->bind_to_runtime_version = TRUE;
6405 } else if (str_begins_with (arg, "full")) {
6406 opts->full_aot = TRUE;
6407 } else if (str_begins_with (arg, "threads=")) {
6408 opts->nthreads = atoi (arg + strlen ("threads="));
6409 } else if (str_begins_with (arg, "static")) {
6410 opts->static_link = TRUE;
6411 opts->no_dlsym = TRUE;
6412 } else if (str_begins_with (arg, "asmonly")) {
6413 opts->asm_only = TRUE;
6414 } else if (str_begins_with (arg, "asmwriter")) {
6415 opts->asm_writer = TRUE;
6416 } else if (str_begins_with (arg, "nodebug")) {
6417 opts->nodebug = TRUE;
6418 } else if (str_begins_with (arg, "dwarfdebug")) {
6419 opts->dwarf_debug = TRUE;
6420 } else if (str_begins_with (arg, "nopagetrampolines")) {
6421 opts->use_trampolines_page = FALSE;
6422 } else if (str_begins_with (arg, "ntrampolines=")) {
6423 opts->ntrampolines = atoi (arg + strlen ("ntrampolines="));
6424 } else if (str_begins_with (arg, "nrgctx-trampolines=")) {
6425 opts->nrgctx_trampolines = atoi (arg + strlen ("nrgctx-trampolines="));
6426 } else if (str_begins_with (arg, "nimt-trampolines=")) {
6427 opts->nimt_trampolines = atoi (arg + strlen ("nimt-trampolines="));
6428 } else if (str_begins_with (arg, "ngsharedvt-trampolines=")) {
6429 opts->ngsharedvt_arg_trampolines = atoi (arg + strlen ("ngsharedvt-trampolines="));
6430 } else if (str_begins_with (arg, "autoreg")) {
6431 opts->autoreg = TRUE;
6432 } else if (str_begins_with (arg, "tool-prefix=")) {
6433 opts->tool_prefix = g_strdup (arg + strlen ("tool-prefix="));
6434 } else if (str_begins_with (arg, "ld-flags=")) {
6435 opts->ld_flags = g_strdup (arg + strlen ("ld-flags="));
6436 } else if (str_begins_with (arg, "soft-debug")) {
6437 opts->soft_debug = TRUE;
6438 } else if (str_begins_with (arg, "gen-seq-points-file")) {
6439 opts->gen_seq_points_file = TRUE;
6440 } else if (str_begins_with (arg, "direct-pinvoke")) {
6441 opts->direct_pinvoke = TRUE;
6442 } else if (str_begins_with (arg, "direct-icalls")) {
6443 opts->direct_icalls = TRUE;
6444 #if defined(TARGET_ARM) || defined(TARGET_ARM64)
6445 } else if (str_begins_with (arg, "iphone-abi")) {
6446 // older full-aot users did depend on this.
6448 } else if (str_begins_with (arg, "no-direct-calls")) {
6449 opts->no_direct_calls = TRUE;
6450 } else if (str_begins_with (arg, "print-skipped")) {
6451 opts->print_skipped_methods = TRUE;
6452 } else if (str_begins_with (arg, "stats")) {
6454 } else if (str_begins_with (arg, "no-instances")) {
6455 opts->no_instances = TRUE;
6456 } else if (str_begins_with (arg, "log-generics")) {
6457 opts->log_generics = TRUE;
6458 } else if (str_begins_with (arg, "log-instances=")) {
6459 opts->log_instances = TRUE;
6460 opts->instances_logfile_path = g_strdup (arg + strlen ("log-instances="));
6461 } else if (str_begins_with (arg, "log-instances")) {
6462 opts->log_instances = TRUE;
6463 } else if (str_begins_with (arg, "internal-logfile=")) {
6464 opts->logfile = g_strdup (arg + strlen ("internal-logfile="));
6465 } else if (str_begins_with (arg, "mtriple=")) {
6466 opts->mtriple = g_strdup (arg + strlen ("mtriple="));
6467 } else if (str_begins_with (arg, "llvm-path=")) {
6468 opts->llvm_path = g_strdup (arg + strlen ("llvm-path="));
6469 if (!g_str_has_suffix (opts->llvm_path, G_DIR_SEPARATOR_S)) {
6470 gchar *old = opts->llvm_path;
6471 opts->llvm_path = g_strconcat (opts->llvm_path, G_DIR_SEPARATOR_S, NULL);
6474 } else if (!strcmp (arg, "llvm")) {
6476 } else if (str_begins_with (arg, "readonly-value=")) {
6477 add_readonly_value (opts, arg + strlen ("readonly-value="));
6478 } else if (str_begins_with (arg, "info")) {
6479 printf ("AOT target setup: %s.\n", AOT_TARGET_STR);
6481 } else if (str_begins_with (arg, "gc-maps")) {
6482 mini_gc_enable_gc_maps_for_aot ();
6483 } else if (str_begins_with (arg, "dump")) {
6484 opts->dump_json = TRUE;
6485 } else if (str_begins_with (arg, "help") || str_begins_with (arg, "?")) {
6486 printf ("Supported options for --aot:\n");
6487 printf (" outfile=\n");
6488 printf (" llvm-outfile=\n");
6489 printf (" save-temps\n");
6490 printf (" keep-temps\n");
6491 printf (" write-symbols\n");
6492 printf (" metadata-only\n");
6493 printf (" bind-to-runtime-version\n");
6495 printf (" threads=\n");
6496 printf (" static\n");
6497 printf (" asmonly\n");
6498 printf (" asmwriter\n");
6499 printf (" nodebug\n");
6500 printf (" dwarfdebug\n");
6501 printf (" ntrampolines=\n");
6502 printf (" nrgctx-trampolines=\n");
6503 printf (" nimt-trampolines=\n");
6504 printf (" ngsharedvt-trampolines=\n");
6505 printf (" autoreg\n");
6506 printf (" tool-prefix=\n");
6507 printf (" readonly-value=\n");
6508 printf (" soft-debug\n");
6509 printf (" gen-seq-points-file\n");
6510 printf (" gc-maps\n");
6511 printf (" print-skipped\n");
6512 printf (" no-instances\n");
6513 printf (" stats\n");
6516 printf (" help/?\n");
6519 fprintf (stderr, "AOT : Unknown argument '%s'.\n", arg);
6524 if (opts->use_trampolines_page) {
6525 opts->ntrampolines = 0;
6526 opts->nrgctx_trampolines = 0;
6527 opts->nimt_trampolines = 0;
6528 opts->ngsharedvt_arg_trampolines = 0;
6534 add_token_info_hash (gpointer key, gpointer value, gpointer user_data)
6536 MonoMethod *method = (MonoMethod*)key;
6537 MonoJumpInfoToken *ji = (MonoJumpInfoToken*)value;
6538 MonoAotCompile *acfg = user_data;
6539 MonoJumpInfoToken *new_ji;
6541 new_ji = mono_mempool_alloc0 (acfg->mempool, sizeof (MonoJumpInfoToken));
6542 new_ji->image = ji->image;
6543 new_ji->token = ji->token;
6544 g_hash_table_insert (acfg->token_info_hash, method, new_ji);
6548 can_encode_class (MonoAotCompile *acfg, MonoClass *klass)
6550 if (klass->type_token)
6552 if ((klass->byval_arg.type == MONO_TYPE_VAR) || (klass->byval_arg.type == MONO_TYPE_MVAR) || (klass->byval_arg.type == MONO_TYPE_PTR))
6555 return can_encode_class (acfg, klass->element_class);
6560 can_encode_method (MonoAotCompile *acfg, MonoMethod *method)
6562 if (method->wrapper_type) {
6563 switch (method->wrapper_type) {
6564 case MONO_WRAPPER_NONE:
6565 case MONO_WRAPPER_REMOTING_INVOKE_WITH_CHECK:
6566 case MONO_WRAPPER_XDOMAIN_INVOKE:
6567 case MONO_WRAPPER_STFLD:
6568 case MONO_WRAPPER_LDFLD:
6569 case MONO_WRAPPER_LDFLDA:
6570 case MONO_WRAPPER_LDFLD_REMOTE:
6571 case MONO_WRAPPER_STFLD_REMOTE:
6572 case MONO_WRAPPER_STELEMREF:
6573 case MONO_WRAPPER_ISINST:
6574 case MONO_WRAPPER_PROXY_ISINST:
6575 case MONO_WRAPPER_ALLOC:
6576 case MONO_WRAPPER_REMOTING_INVOKE:
6577 case MONO_WRAPPER_UNKNOWN:
6578 case MONO_WRAPPER_WRITE_BARRIER:
6579 case MONO_WRAPPER_DELEGATE_INVOKE:
6580 case MONO_WRAPPER_DELEGATE_BEGIN_INVOKE:
6581 case MONO_WRAPPER_DELEGATE_END_INVOKE:
6582 case MONO_WRAPPER_SYNCHRONIZED:
6584 case MONO_WRAPPER_MANAGED_TO_MANAGED:
6585 case MONO_WRAPPER_CASTCLASS: {
6586 WrapperInfo *info = mono_marshal_get_wrapper_info (method);
6595 //printf ("Skip (wrapper call): %d -> %s\n", patch_info->type, mono_method_full_name (patch_info->data.method, TRUE));
6599 if (!method->token) {
6600 /* The method is part of a constructed type like Int[,].Set (). */
6601 if (!g_hash_table_lookup (acfg->token_info_hash, method)) {
6602 if (method->klass->rank)
6612 can_encode_patch (MonoAotCompile *acfg, MonoJumpInfo *patch_info)
6614 switch (patch_info->type) {
6615 case MONO_PATCH_INFO_METHOD:
6616 case MONO_PATCH_INFO_METHODCONST:
6617 case MONO_PATCH_INFO_METHOD_CODE_SLOT: {
6618 MonoMethod *method = patch_info->data.method;
6620 return can_encode_method (acfg, method);
6622 case MONO_PATCH_INFO_VTABLE:
6623 case MONO_PATCH_INFO_CLASS_INIT:
6624 case MONO_PATCH_INFO_CLASS:
6625 case MONO_PATCH_INFO_IID:
6626 case MONO_PATCH_INFO_ADJUSTED_IID:
6627 if (!can_encode_class (acfg, patch_info->data.klass)) {
6628 //printf ("Skip: %s\n", mono_type_full_name (&patch_info->data.klass->byval_arg));
6632 case MONO_PATCH_INFO_DELEGATE_TRAMPOLINE: {
6633 if (!can_encode_class (acfg, patch_info->data.del_tramp->klass)) {
6634 //printf ("Skip: %s\n", mono_type_full_name (&patch_info->data.klass->byval_arg));
6639 case MONO_PATCH_INFO_RGCTX_FETCH: {
6640 MonoJumpInfoRgctxEntry *entry = patch_info->data.rgctx_entry;
6642 if (!can_encode_method (acfg, entry->method))
6644 if (!can_encode_patch (acfg, entry->data))
6658 * AOT compile a given method.
6659 * This function might be called by multiple threads, so it must be thread-safe.
6662 compile_method (MonoAotCompile *acfg, MonoMethod *method)
6665 MonoJumpInfo *patch_info;
6668 MonoMethod *wrapped;
6671 if (acfg->aot_opts.metadata_only)
6674 mono_acfg_lock (acfg);
6675 index = get_method_index (acfg, method);
6676 mono_acfg_unlock (acfg);
6678 /* fixme: maybe we can also precompile wrapper methods */
6679 if ((method->flags & METHOD_ATTRIBUTE_PINVOKE_IMPL) ||
6680 (method->iflags & METHOD_IMPL_ATTRIBUTE_RUNTIME) ||
6681 (method->flags & METHOD_ATTRIBUTE_ABSTRACT)) {
6682 //printf ("Skip (impossible): %s\n", mono_method_full_name (method, TRUE));
6686 if (method->iflags & METHOD_IMPL_ATTRIBUTE_INTERNAL_CALL)
6689 wrapped = mono_marshal_method_from_wrapper (method);
6690 if (wrapped && (wrapped->iflags & METHOD_IMPL_ATTRIBUTE_INTERNAL_CALL) && wrapped->is_generic)
6691 // FIXME: The wrapper should be generic too, but it is not
6694 if (method->wrapper_type == MONO_WRAPPER_COMINTEROP)
6697 InterlockedIncrement (&acfg->stats.mcount);
6700 if (method->is_generic || method->klass->generic_container) {
6701 InterlockedIncrement (&acfg->stats.genericcount);
6706 //acfg->aot_opts.print_skipped_methods = TRUE;
6709 * Since these methods are the only ones which are compiled with
6710 * AOT support, and they are not used by runtime startup/shutdown code,
6711 * the runtime will not see AOT methods during AOT compilation,so it
6712 * does not need to support them by creating a fake GOT etc.
6714 flags = JIT_FLAG_AOT;
6715 if (acfg->aot_opts.full_aot)
6716 flags |= JIT_FLAG_FULL_AOT;
6718 flags |= JIT_FLAG_LLVM;
6719 cfg = mini_method_compile (method, acfg->opts, mono_get_root_domain (), flags, 0);
6720 mono_loader_clear_error ();
6722 if (cfg->exception_type == MONO_EXCEPTION_GENERIC_SHARING_FAILED) {
6723 if (acfg->aot_opts.print_skipped_methods)
6724 printf ("Skip (gshared failure): %s (%s)\n", mono_method_full_name (method, TRUE), cfg->exception_message);
6725 InterlockedIncrement (&acfg->stats.genericcount);
6728 if (cfg->exception_type != MONO_EXCEPTION_NONE) {
6729 if (acfg->aot_opts.print_skipped_methods)
6730 printf ("Skip (JIT failure): %s\n", mono_method_full_name (method, TRUE));
6731 /* Let the exception happen at runtime */
6735 if (cfg->disable_aot) {
6736 if (acfg->aot_opts.print_skipped_methods)
6737 printf ("Skip (disabled): %s\n", mono_method_full_name (method, TRUE));
6738 InterlockedIncrement (&acfg->stats.ocount);
6739 mono_destroy_compile (cfg);
6742 cfg->method_index = index;
6744 /* Nullify patches which need no aot processing */
6745 for (patch_info = cfg->patch_info; patch_info; patch_info = patch_info->next) {
6746 switch (patch_info->type) {
6747 case MONO_PATCH_INFO_LABEL:
6748 case MONO_PATCH_INFO_BB:
6749 patch_info->type = MONO_PATCH_INFO_NONE;
6756 /* Collect method->token associations from the cfg */
6757 mono_acfg_lock (acfg);
6758 g_hash_table_foreach (cfg->token_info_hash, add_token_info_hash, acfg);
6759 mono_acfg_unlock (acfg);
6760 g_hash_table_destroy (cfg->token_info_hash);
6761 cfg->token_info_hash = NULL;
6764 * Check for absolute addresses.
6767 for (patch_info = cfg->patch_info; patch_info; patch_info = patch_info->next) {
6768 switch (patch_info->type) {
6769 case MONO_PATCH_INFO_ABS:
6770 /* unable to handle this */
6779 if (acfg->aot_opts.print_skipped_methods)
6780 printf ("Skip (abs call): %s\n", mono_method_full_name (method, TRUE));
6781 InterlockedIncrement (&acfg->stats.abscount);
6782 mono_destroy_compile (cfg);
6786 /* Lock for the rest of the code */
6787 mono_acfg_lock (acfg);
6790 * Check for methods/klasses we can't encode.
6793 for (patch_info = cfg->patch_info; patch_info; patch_info = patch_info->next) {
6794 if (!can_encode_patch (acfg, patch_info))
6799 if (acfg->aot_opts.print_skipped_methods)
6800 printf ("Skip (patches): %s\n", mono_method_full_name (method, TRUE));
6801 acfg->stats.ocount++;
6802 mono_destroy_compile (cfg);
6803 mono_acfg_unlock (acfg);
6807 if (method->is_inflated && acfg->aot_opts.log_instances) {
6808 if (acfg->instances_logfile)
6809 fprintf (acfg->instances_logfile, "%s ### %d\n", mono_method_full_name (method, TRUE), cfg->code_size);
6811 printf ("%s ### %d\n", mono_method_full_name (method, TRUE), cfg->code_size);
6814 /* Adds generic instances referenced by this method */
6816 * The depth is used to avoid infinite loops when generic virtual recursion is
6819 depth = GPOINTER_TO_UINT (g_hash_table_lookup (acfg->method_depth, method));
6820 if (!acfg->aot_opts.no_instances && depth < 32) {
6821 for (patch_info = cfg->patch_info; patch_info; patch_info = patch_info->next) {
6822 switch (patch_info->type) {
6823 case MONO_PATCH_INFO_METHOD: {
6824 MonoMethod *m = patch_info->data.method;
6825 if (m->is_inflated) {
6826 if (!(mono_class_generic_sharing_enabled (m->klass) &&
6827 mono_method_is_generic_sharable_full (m, FALSE, FALSE, FALSE)) &&
6828 !method_has_type_vars (m)) {
6829 if (m->iflags & METHOD_IMPL_ATTRIBUTE_INTERNAL_CALL) {
6830 if (acfg->aot_opts.full_aot)
6831 add_extra_method_with_depth (acfg, mono_marshal_get_native_wrapper (m, TRUE, TRUE), depth + 1);
6833 add_extra_method_with_depth (acfg, m, depth + 1);
6834 add_types_from_method_header (acfg, m);
6837 add_generic_class_with_depth (acfg, m->klass, depth + 5, "method");
6839 if (m->wrapper_type == MONO_WRAPPER_MANAGED_TO_MANAGED) {
6840 WrapperInfo *info = mono_marshal_get_wrapper_info (m);
6842 if (info && info->subtype == WRAPPER_SUBTYPE_ELEMENT_ADDR)
6843 add_extra_method_with_depth (acfg, m, depth + 1);
6847 case MONO_PATCH_INFO_VTABLE: {
6848 MonoClass *klass = patch_info->data.klass;
6850 if (klass->generic_class && !mini_class_is_generic_sharable (klass))
6851 add_generic_class_with_depth (acfg, klass, depth + 5, "vtable");
6854 case MONO_PATCH_INFO_SFLDA: {
6855 MonoClass *klass = patch_info->data.field->parent;
6857 /* The .cctor needs to run at runtime. */
6858 if (klass->generic_class && !mono_generic_context_is_sharable (&klass->generic_class->context, FALSE) && mono_class_get_cctor (klass))
6859 add_extra_method_with_depth (acfg, mono_class_get_cctor (klass), depth + 1);
6868 /* Determine whenever the method has GOT slots */
6869 for (patch_info = cfg->patch_info; patch_info; patch_info = patch_info->next) {
6870 switch (patch_info->type) {
6871 case MONO_PATCH_INFO_GOT_OFFSET:
6872 case MONO_PATCH_INFO_NONE:
6873 case MONO_PATCH_INFO_GC_CARD_TABLE_ADDR:
6875 case MONO_PATCH_INFO_IMAGE:
6876 /* The assembly is stored in GOT slot 0 */
6877 if (patch_info->data.image != acfg->image)
6878 cfg->has_got_slots = TRUE;
6881 if (!is_plt_patch (patch_info))
6882 cfg->has_got_slots = TRUE;
6887 if (!cfg->has_got_slots)
6888 InterlockedIncrement (&acfg->stats.methods_without_got_slots);
6891 * FIXME: Instead of this mess, allocate the patches from the aot mempool.
6893 /* Make a copy of the patch info which is in the mempool */
6895 MonoJumpInfo *patches = NULL, *patches_end = NULL;
6897 for (patch_info = cfg->patch_info; patch_info; patch_info = patch_info->next) {
6898 MonoJumpInfo *new_patch_info = mono_patch_info_dup_mp (acfg->mempool, patch_info);
6901 patches = new_patch_info;
6903 patches_end->next = new_patch_info;
6904 patches_end = new_patch_info;
6906 cfg->patch_info = patches;
6908 /* Make a copy of the unwind info */
6910 GSList *l, *unwind_ops;
6914 for (l = cfg->unwind_ops; l; l = l->next) {
6915 op = mono_mempool_alloc (acfg->mempool, sizeof (MonoUnwindOp));
6916 memcpy (op, l->data, sizeof (MonoUnwindOp));
6917 unwind_ops = g_slist_prepend_mempool (acfg->mempool, unwind_ops, op);
6919 cfg->unwind_ops = g_slist_reverse (unwind_ops);
6921 /* Make a copy of the argument/local info */
6923 MonoInst **args, **locals;
6924 MonoMethodSignature *sig;
6925 MonoMethodHeader *header;
6928 sig = mono_method_signature (method);
6929 args = mono_mempool_alloc (acfg->mempool, sizeof (MonoInst*) * (sig->param_count + sig->hasthis));
6930 for (i = 0; i < sig->param_count + sig->hasthis; ++i) {
6931 args [i] = mono_mempool_alloc (acfg->mempool, sizeof (MonoInst));
6932 memcpy (args [i], cfg->args [i], sizeof (MonoInst));
6936 header = mono_method_get_header (method);
6937 locals = mono_mempool_alloc (acfg->mempool, sizeof (MonoInst*) * header->num_locals);
6938 for (i = 0; i < header->num_locals; ++i) {
6939 locals [i] = mono_mempool_alloc (acfg->mempool, sizeof (MonoInst));
6940 memcpy (locals [i], cfg->locals [i], sizeof (MonoInst));
6942 cfg->locals = locals;
6945 /* Free some fields used by cfg to conserve memory */
6946 mono_mempool_destroy (cfg->mempool);
6947 cfg->mempool = NULL;
6948 g_free (cfg->varinfo);
6949 cfg->varinfo = NULL;
6953 mono_regstate_free (cfg->rs);
6957 //printf ("Compile: %s\n", mono_method_full_name (method, TRUE));
6959 while (index >= acfg->cfgs_size) {
6960 MonoCompile **new_cfgs;
6963 new_size = acfg->cfgs_size * 2;
6964 new_cfgs = g_new0 (MonoCompile*, new_size);
6965 memcpy (new_cfgs, acfg->cfgs, sizeof (MonoCompile*) * acfg->cfgs_size);
6966 g_free (acfg->cfgs);
6967 acfg->cfgs = new_cfgs;
6968 acfg->cfgs_size = new_size;
6970 acfg->cfgs [index] = cfg;
6972 g_hash_table_insert (acfg->method_to_cfg, cfg->orig_method, cfg);
6975 if (cfg->orig_method->wrapper_type)
6976 g_ptr_array_add (acfg->extra_methods, cfg->orig_method);
6979 mono_acfg_unlock (acfg);
6981 InterlockedIncrement (&acfg->stats.ccount);
6985 compile_thread_main (gpointer *user_data)
6987 MonoDomain *domain = user_data [0];
6988 MonoAotCompile *acfg = user_data [1];
6989 GPtrArray *methods = user_data [2];
6992 mono_thread_attach (domain);
6994 for (i = 0; i < methods->len; ++i)
6995 compile_method (acfg, g_ptr_array_index (methods, i));
6999 load_profile_files (MonoAotCompile *acfg)
7003 int file_index, res, method_index, i;
7006 GList *unordered, *l;
7011 tmp = g_strdup_printf ("%s/.mono/aot-profile-data/%s-%d", g_get_home_dir (), acfg->image->assembly_name, file_index);
7013 if (!g_file_test (tmp, G_FILE_TEST_IS_REGULAR)) {
7018 infile = fopen (tmp, "r");
7021 printf ("Using profile data file '%s'\n", tmp);
7026 res = fscanf (infile, "%32s\n", ver);
7027 if ((res != 1) || strcmp (ver, "#VER:2") != 0) {
7028 printf ("Profile file has wrong version or invalid.\n");
7035 MonoMethodDesc *desc;
7038 if (fgets (name, 1023, infile) == NULL)
7041 /* Kill the newline */
7042 if (strlen (name) > 0)
7043 name [strlen (name) - 1] = '\0';
7045 desc = mono_method_desc_new (name, TRUE);
7047 method = mono_method_desc_search_in_image (desc, acfg->image);
7049 if (method && mono_method_get_token (method)) {
7050 token = mono_method_get_token (method);
7051 method_index = mono_metadata_token_index (token) - 1;
7054 for (i = 0; i < acfg->method_order->len; ++i) {
7055 if (g_ptr_array_index (acfg->method_order, i) == GUINT_TO_POINTER (method_index)) {
7061 g_ptr_array_add (acfg->method_order, GUINT_TO_POINTER (method_index));
7063 //printf ("No method found matching '%s'.\n", name);
7069 /* Add missing methods */
7071 for (method_index = 0; method_index < acfg->image->tables [MONO_TABLE_METHOD].rows; ++method_index) {
7073 for (i = 0; i < acfg->method_order->len; ++i) {
7074 if (g_ptr_array_index (acfg->method_order, i) == GUINT_TO_POINTER (method_index)) {
7080 unordered = g_list_prepend (unordered, GUINT_TO_POINTER (method_index));
7082 unordered = g_list_reverse (unordered);
7083 for (l = unordered; l; l = l->next)
7084 g_ptr_array_add (acfg->method_order, l->data);
7087 /* Used by the LLVM backend */
7089 mono_aot_get_got_offset (MonoJumpInfo *ji)
7091 return get_got_offset (llvm_acfg, TRUE, ji);
7095 mono_aot_get_method_name (MonoCompile *cfg)
7097 if (llvm_acfg->aot_opts.static_link)
7098 /* Include the assembly name too to avoid duplicate symbol errors */
7099 return g_strdup_printf ("%s_%s", llvm_acfg->assembly_name_sym, get_debug_sym (cfg->orig_method, "", llvm_acfg->method_label_hash));
7101 return get_debug_sym (cfg->orig_method, "", llvm_acfg->method_label_hash);
7105 mono_aot_is_direct_callable (MonoJumpInfo *patch_info)
7107 return is_direct_callable (llvm_acfg, NULL, patch_info);
7111 mono_aot_mark_unused_llvm_plt_entry (MonoJumpInfo *patch_info)
7113 MonoPltEntry *plt_entry;
7115 plt_entry = get_plt_entry (llvm_acfg, patch_info);
7116 plt_entry->llvm_used = FALSE;
7120 mono_aot_get_plt_symbol (MonoJumpInfoType type, gconstpointer data)
7122 MonoJumpInfo *ji = mono_mempool_alloc (llvm_acfg->mempool, sizeof (MonoJumpInfo));
7123 MonoPltEntry *plt_entry;
7126 ji->data.target = data;
7128 if (!can_encode_patch (llvm_acfg, ji))
7131 plt_entry = get_plt_entry (llvm_acfg, ji);
7132 plt_entry->llvm_used = TRUE;
7134 #if defined(TARGET_MACH)
7135 return g_strdup_printf (plt_entry->llvm_symbol + strlen (llvm_acfg->llvm_label_prefix));
7137 return g_strdup_printf (plt_entry->llvm_symbol);
7142 mono_aot_get_method_index (MonoMethod *method)
7144 g_assert (llvm_acfg);
7145 return get_method_index (llvm_acfg, method);
7149 mono_aot_patch_info_dup (MonoJumpInfo* ji)
7153 mono_acfg_lock (llvm_acfg);
7154 res = mono_patch_info_dup_mp (llvm_acfg->mempool, ji);
7155 mono_acfg_unlock (llvm_acfg);
7161 execute_system (const char * command)
7166 // We need an extra set of quotes around the whole command to properly handle commands
7167 // with spaces since internally the command is called through "cmd /c.
7168 command = g_strdup_printf ("\"%s\"", command);
7170 int size = MultiByteToWideChar (CP_UTF8, 0 , command , -1, NULL , 0);
7171 wchar_t* wstr = g_malloc (sizeof (wchar_t) * size);
7172 MultiByteToWideChar (CP_UTF8, 0, command, -1, wstr , size);
7173 status = _wsystem (wstr);
7178 status = system (command);
7189 * Emit the LLVM code into an LLVM bytecode file, and compile it using the LLVM
7193 emit_llvm_file (MonoAotCompile *acfg)
7195 char *command, *opts, *tempbc, *output_fname;
7197 tempbc = g_strdup_printf ("%s.bc", acfg->tmpbasename);
7198 mono_llvm_emit_aot_module (tempbc, g_path_get_basename (acfg->image->name));
7202 * FIXME: Experiment with adding optimizations, the -std-compile-opts set takes
7203 * a lot of time, and doesn't seem to save much space.
7204 * The following optimizations cannot be enabled:
7206 * - 'jump-threading' changes our blockaddress references to int constants.
7207 * - 'basiccg' fails because it contains:
7208 * if (CS && !isa<IntrinsicInst>(II)) {
7209 * and isa<IntrinsicInst> is false for invokes to intrinsics (iltests.exe).
7210 * - 'prune-eh' and 'functionattrs' depend on 'basiccg'.
7211 * The opt list below was produced by taking the output of:
7212 * llvm-as < /dev/null | opt -O2 -disable-output -debug-pass=Arguments
7213 * then removing tailcallelim + the global opts.
7214 * strip-dead-prototypes deletes unused intrinsics definitions.
7216 opts = g_strdup ("-instcombine -simplifycfg");
7217 //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");
7218 /* The dse pass is disabled because of #13734 and #17616 */
7220 * The dse bug is in DeadStoreElimination.cpp:isOverwrite ():
7221 * // If we have no DataLayout information around, then the size of the store
7222 * // is inferrable from the pointee type. If they are the same type, then
7223 * // we know that the store is safe.
7224 * if (AA.getDataLayout() == 0 &&
7225 * Later.Ptr->getType() == Earlier.Ptr->getType()) {
7226 * return OverwriteComplete;
7227 * Here, if 'Earlier' refers to a memset, and Later has no size info, it mistakenly thinks the memset is redundant.
7229 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");
7231 command = g_strdup_printf ("\"%sopt\" -f %s -o \"%s.opt.bc\" \"%s.bc\"", acfg->aot_opts.llvm_path, opts, acfg->tmpbasename, acfg->tmpbasename);
7232 aot_printf (acfg, "Executing opt: %s\n", command);
7233 if (execute_system (command) != 0)
7238 if (!acfg->llc_args)
7239 acfg->llc_args = g_string_new ("");
7241 /* Verbose asm slows down llc greatly */
7242 g_string_append (acfg->llc_args, " -asm-verbose=false");
7244 g_string_append (acfg->llc_args, " -disable-gnu-eh-frame -enable-mono-eh-frame");
7246 if (acfg->aot_opts.mtriple)
7247 g_string_append_printf (acfg->llc_args, " -mtriple=%s", acfg->aot_opts.mtriple);
7249 if (acfg->llvm_separate)
7250 g_string_append_printf (acfg->llc_args, " -mono-eh-frame-symbol=%s", acfg->llvm_eh_frame_symbol);
7252 #if defined(TARGET_MACH) && defined(TARGET_ARM)
7253 /* ios requires PIC code now */
7254 g_string_append_printf (acfg->llc_args, " -relocation-model=pic");
7256 if (llvm_acfg->aot_opts.static_link)
7257 g_string_append_printf (acfg->llc_args, " -relocation-model=static");
7259 g_string_append_printf (acfg->llc_args, " -relocation-model=pic");
7261 unlink (acfg->tmpfname);
7263 if (acfg->llvm_separate) {
7264 if (acfg->llvm_owriter) {
7265 /* Emit an object file directly */
7266 output_fname = g_strdup_printf ("%s", acfg->llvm_ofile);
7267 g_string_append_printf (acfg->llc_args, " -filetype=obj");
7269 output_fname = g_strdup_printf ("%s", acfg->llvm_sfile);
7272 output_fname = g_strdup (acfg->tmpfname);
7274 command = g_strdup_printf ("\"%sllc\" %s -o \"%s\" \"%s.opt.bc\"", acfg->aot_opts.llvm_path, acfg->llc_args->str, output_fname, acfg->tmpbasename);
7276 aot_printf (acfg, "Executing llc: %s\n", command);
7278 if (execute_system (command) != 0)
7285 emit_code (MonoAotCompile *acfg)
7287 int oindex, i, prev_index;
7290 #if defined(TARGET_POWERPC64)
7291 sprintf (symbol, ".Lgot_addr");
7292 emit_section_change (acfg, ".text", 0);
7293 emit_alignment (acfg, 8);
7294 emit_label (acfg, symbol);
7295 emit_pointer (acfg, acfg->got_symbol);
7299 * This global symbol is used to compute the address of each method using the
7300 * code_offsets array. It is also used to compute the memory ranges occupied by
7301 * AOT code, so it must be equal to the address of the first emitted method.
7303 emit_section_change (acfg, ".text", 0);
7304 emit_alignment_code (acfg, 8);
7306 for (i = 0; i < acfg->nmethods; ++i) {
7307 if (acfg->cfgs [i] && acfg->cfgs [i]->compile_llvm) {
7308 acfg->methods_symbol = g_strdup (acfg->cfgs [i]->asm_symbol);
7313 if (!acfg->methods_symbol) {
7314 sprintf (symbol, "methods");
7315 emit_label (acfg, symbol);
7316 acfg->methods_symbol = g_strdup (symbol);
7318 emit_label (acfg, "jit_code_start");
7321 * Emit some padding so the local symbol for the first method doesn't have the
7322 * same address as 'methods'.
7324 #if defined(__default_codegen__)
7325 emit_padding (acfg, 16);
7326 #elif defined(__native_client_codegen__)
7328 const int kPaddingSize = 16;
7329 guint8 pad_buffer[kPaddingSize];
7330 mono_arch_nacl_pad (pad_buffer, kPaddingSize);
7331 emit_bytes (acfg, pad_buffer, kPaddingSize);
7335 for (oindex = 0; oindex < acfg->method_order->len; ++oindex) {
7339 i = GPOINTER_TO_UINT (g_ptr_array_index (acfg->method_order, oindex));
7341 cfg = acfg->cfgs [i];
7346 method = cfg->orig_method;
7348 /* Emit unbox trampoline */
7349 if (acfg->aot_opts.full_aot && cfg->orig_method->klass->valuetype) {
7350 sprintf (symbol, "ut_%d", get_method_index (acfg, method));
7352 emit_section_change (acfg, ".text", 0);
7353 #ifdef __native_client_codegen__
7354 emit_alignment (acfg, AOT_FUNC_ALIGNMENT);
7357 if (acfg->thumb_mixed && cfg->compile_llvm) {
7358 emit_set_thumb_mode (acfg);
7359 fprintf (acfg->fp, "\n.thumb_func\n");
7362 emit_label (acfg, symbol);
7364 arch_emit_unbox_trampoline (acfg, cfg, cfg->orig_method, cfg->asm_symbol);
7366 if (acfg->thumb_mixed && cfg->compile_llvm)
7367 emit_set_arm_mode (acfg);
7370 if (cfg->compile_llvm)
7371 acfg->stats.llvm_count ++;
7373 emit_method_code (acfg, cfg);
7376 emit_section_change (acfg, ".text", 0);
7377 emit_alignment_code (acfg, 8);
7378 emit_label (acfg, "jit_code_end");
7380 /* To distinguish it from the next symbol */
7381 emit_padding (acfg, 4);
7384 * Add .no_dead_strip directives for all LLVM methods to prevent the OSX linker
7385 * from optimizing them away, since it doesn't see that code_offsets references them.
7386 * JITted methods don't need this since they are referenced using assembler local
7388 * FIXME: This is why write-symbols doesn't work on OSX ?
7390 if (acfg->llvm && acfg->need_no_dead_strip) {
7391 fprintf (acfg->fp, "\n");
7392 for (i = 0; i < acfg->nmethods; ++i) {
7393 if (acfg->cfgs [i] && acfg->cfgs [i]->compile_llvm)
7394 fprintf (acfg->fp, ".no_dead_strip %s\n", acfg->cfgs [i]->asm_symbol);
7399 * To work around linker issues, we emit a table of branches, and disassemble them at runtime.
7400 * This is PIE code, and the linker can update it if needed.
7402 sprintf (symbol, "method_addresses");
7403 emit_section_change (acfg, ".text", 1);
7404 emit_alignment_code (acfg, 8);
7405 emit_label (acfg, symbol);
7406 emit_local_symbol (acfg, symbol, "method_addresses_end", TRUE);
7407 emit_unset_mode (acfg);
7408 if (acfg->need_no_dead_strip)
7409 fprintf (acfg->fp, " .no_dead_strip %s\n", symbol);
7411 for (i = 0; i < acfg->nmethods; ++i) {
7412 #ifdef MONO_ARCH_AOT_SUPPORTED
7416 arch_emit_direct_call (acfg, acfg->cfgs [i]->asm_symbol, FALSE, acfg->thumb_mixed && acfg->cfgs [i]->compile_llvm, NULL, &call_size);
7418 arch_emit_direct_call (acfg, "method_addresses", FALSE, FALSE, NULL, &call_size);
7422 sprintf (symbol, "method_addresses_end");
7423 emit_label (acfg, symbol);
7426 /* Emit a sorted table mapping methods to the index of their unbox trampolines */
7427 sprintf (symbol, "unbox_trampolines");
7428 emit_section_change (acfg, RODATA_SECT, 0);
7429 emit_alignment (acfg, 8);
7430 emit_label (acfg, symbol);
7433 for (i = 0; i < acfg->nmethods; ++i) {
7438 cfg = acfg->cfgs [i];
7442 method = cfg->orig_method;
7444 if (acfg->aot_opts.full_aot && cfg->orig_method->klass->valuetype) {
7445 index = get_method_index (acfg, method);
7447 emit_int32 (acfg, index);
7448 /* Make sure the table is sorted by index */
7449 g_assert (index > prev_index);
7453 sprintf (symbol, "unbox_trampolines_end");
7454 emit_label (acfg, symbol);
7455 emit_int32 (acfg, 0);
7457 /* Emit a separate table with the trampoline addresses/offsets */
7458 sprintf (symbol, "unbox_trampoline_addresses");
7459 emit_section_change (acfg, ".text", 0);
7460 emit_alignment_code (acfg, 8);
7461 emit_label (acfg, symbol);
7463 for (i = 0; i < acfg->nmethods; ++i) {
7468 cfg = acfg->cfgs [i];
7472 method = cfg->orig_method;
7474 if (acfg->aot_opts.full_aot && cfg->orig_method->klass->valuetype) {
7475 #ifdef MONO_ARCH_AOT_SUPPORTED
7478 index = get_method_index (acfg, method);
7479 sprintf (symbol, "ut_%d", index);
7481 arch_emit_direct_call (acfg, symbol, FALSE, acfg->thumb_mixed && cfg->compile_llvm, NULL, &call_size);
7485 emit_int32 (acfg, 0);
7489 emit_info (MonoAotCompile *acfg)
7495 offsets = g_new0 (gint32, acfg->nmethods);
7497 for (oindex = 0; oindex < acfg->method_order->len; ++oindex) {
7498 i = GPOINTER_TO_UINT (g_ptr_array_index (acfg->method_order, oindex));
7500 if (acfg->cfgs [i]) {
7501 emit_method_info (acfg, acfg->cfgs [i]);
7502 offsets [i] = acfg->cfgs [i]->method_info_offset;
7508 sprintf (symbol, "method_info_offsets");
7509 emit_section_change (acfg, RODATA_SECT, 1);
7510 emit_alignment (acfg, 8);
7511 emit_label (acfg, symbol);
7513 acfg->stats.offsets_size += emit_offset_table (acfg, acfg->nmethods, 10, offsets);
7518 #endif /* #if !defined(DISABLE_AOT) && !defined(DISABLE_JIT) */
7520 #define rot(x,k) (((x)<<(k)) | ((x)>>(32-(k))))
7521 #define mix(a,b,c) { \
7522 a -= c; a ^= rot(c, 4); c += b; \
7523 b -= a; b ^= rot(a, 6); a += c; \
7524 c -= b; c ^= rot(b, 8); b += a; \
7525 a -= c; a ^= rot(c,16); c += b; \
7526 b -= a; b ^= rot(a,19); a += c; \
7527 c -= b; c ^= rot(b, 4); b += a; \
7529 #define final(a,b,c) { \
7530 c ^= b; c -= rot(b,14); \
7531 a ^= c; a -= rot(c,11); \
7532 b ^= a; b -= rot(a,25); \
7533 c ^= b; c -= rot(b,16); \
7534 a ^= c; a -= rot(c,4); \
7535 b ^= a; b -= rot(a,14); \
7536 c ^= b; c -= rot(b,24); \
7540 mono_aot_type_hash (MonoType *t1)
7542 guint hash = t1->type;
7544 hash |= t1->byref << 6; /* do not collide with t1->type values */
7546 case MONO_TYPE_VALUETYPE:
7547 case MONO_TYPE_CLASS:
7548 case MONO_TYPE_SZARRAY:
7549 /* check if the distribution is good enough */
7550 return ((hash << 5) - hash) ^ mono_metadata_str_hash (t1->data.klass->name);
7552 return ((hash << 5) - hash) ^ mono_metadata_type_hash (t1->data.type);
7553 case MONO_TYPE_ARRAY:
7554 return ((hash << 5) - hash) ^ mono_metadata_type_hash (&t1->data.array->eklass->byval_arg);
7555 case MONO_TYPE_GENERICINST:
7556 return ((hash << 5) - hash) ^ 0;
7563 * mono_aot_method_hash:
7565 * Return a hash code for methods which only depends on metadata.
7568 mono_aot_method_hash (MonoMethod *method)
7570 MonoMethodSignature *sig;
7574 guint32 *hashes_start, *hashes;
7576 MonoGenericInst *class_ginst = NULL;
7577 MonoGenericInst *ginst = NULL;
7579 /* Similar to the hash in mono_method_get_imt_slot () */
7581 sig = mono_method_signature (method);
7583 if (method->klass->generic_class)
7584 class_ginst = method->klass->generic_class->context.class_inst;
7585 if (method->is_inflated)
7586 ginst = ((MonoMethodInflated*)method)->context.method_inst;
7588 hashes_count = sig->param_count + 5 + (class_ginst ? class_ginst->type_argc : 0) + (ginst ? ginst->type_argc : 0);
7589 hashes_start = g_malloc0 (hashes_count * sizeof (guint32));
7590 hashes = hashes_start;
7592 /* Some wrappers are assigned to random classes */
7593 if (!method->wrapper_type || method->wrapper_type == MONO_WRAPPER_REMOTING_INVOKE_WITH_CHECK)
7594 klass = method->klass;
7596 klass = mono_defaults.object_class;
7598 if (!method->wrapper_type) {
7601 if (klass->generic_class)
7602 full_name = mono_type_full_name (&klass->generic_class->container_class->byval_arg);
7604 full_name = mono_type_full_name (&klass->byval_arg);
7606 hashes [0] = mono_metadata_str_hash (full_name);
7610 hashes [0] = mono_metadata_str_hash (klass->name);
7611 hashes [1] = mono_metadata_str_hash (klass->name_space);
7613 if (method->wrapper_type == MONO_WRAPPER_STFLD || method->wrapper_type == MONO_WRAPPER_LDFLD || method->wrapper_type == MONO_WRAPPER_LDFLDA)
7614 /* The method name includes a stringified pointer */
7617 hashes [2] = mono_metadata_str_hash (method->name);
7618 hashes [3] = method->wrapper_type;
7619 hashes [4] = mono_aot_type_hash (sig->ret);
7621 for (i = 0; i < sig->param_count; i++) {
7622 hashes [hindex ++] = mono_aot_type_hash (sig->params [i]);
7625 for (i = 0; i < class_ginst->type_argc; ++i)
7626 hashes [hindex ++] = mono_aot_type_hash (class_ginst->type_argv [i]);
7629 for (i = 0; i < ginst->type_argc; ++i)
7630 hashes [hindex ++] = mono_aot_type_hash (ginst->type_argv [i]);
7632 g_assert (hindex == hashes_count);
7634 /* Setup internal state */
7635 a = b = c = 0xdeadbeef + (((guint32)hashes_count)<<2);
7637 /* Handle most of the hashes */
7638 while (hashes_count > 3) {
7647 /* Handle the last 3 hashes (all the case statements fall through) */
7648 switch (hashes_count) {
7649 case 3 : c += hashes [2];
7650 case 2 : b += hashes [1];
7651 case 1 : a += hashes [0];
7653 case 0: /* nothing left to add */
7657 free (hashes_start);
7666 * mono_aot_get_array_helper_from_wrapper;
7668 * Get the helper method in Array called by an array wrapper method.
7671 mono_aot_get_array_helper_from_wrapper (MonoMethod *method)
7675 MonoGenericContext ctx;
7676 MonoType *args [16];
7677 char *mname, *iname, *s, *s2, *helper_name = NULL;
7679 prefix = "System.Collections.Generic";
7680 s = g_strdup_printf ("%s", method->name + strlen (prefix) + 1);
7681 s2 = strstr (s, "`1.");
7687 //printf ("X: %s %s\n", iname, mname);
7689 if (!strcmp (iname, "IList"))
7690 helper_name = g_strdup_printf ("InternalArray__%s", mname);
7692 helper_name = g_strdup_printf ("InternalArray__%s_%s", iname, mname);
7693 m = mono_class_get_method_from_name (mono_defaults.array_class, helper_name, mono_method_signature (method)->param_count);
7695 g_free (helper_name);
7698 if (m->is_generic) {
7700 memset (&ctx, 0, sizeof (ctx));
7701 args [0] = &method->klass->element_class->byval_arg;
7702 ctx.method_inst = mono_metadata_get_generic_inst (1, args);
7703 m = mono_class_inflate_generic_method_checked (m, &ctx, &error);
7704 g_assert (mono_error_ok (&error)); /* FIXME don't swallow the error */
7710 #if !defined(DISABLE_AOT) && !defined(DISABLE_JIT)
7712 typedef struct HashEntry {
7713 guint32 key, value, index;
7714 struct HashEntry *next;
7718 * emit_extra_methods:
7720 * Emit methods which are not in the METHOD table, like wrappers.
7723 emit_extra_methods (MonoAotCompile *acfg)
7725 int i, table_size, buf_size;
7728 guint32 *info_offsets;
7731 HashEntry *entry, *new_entry;
7732 int nmethods, max_chain_length;
7735 info_offsets = g_new0 (guint32, acfg->extra_methods->len);
7737 /* Emit method info */
7739 for (i = 0; i < acfg->extra_methods->len; ++i) {
7740 MonoMethod *method = g_ptr_array_index (acfg->extra_methods, i);
7741 MonoCompile *cfg = g_hash_table_lookup (acfg->method_to_cfg, method);
7747 p = buf = g_malloc (buf_size);
7751 method = cfg->method_to_register;
7753 encode_method_ref (acfg, method, p, &p);
7755 g_assert ((p - buf) < buf_size);
7757 info_offsets [i] = add_to_blob (acfg, buf, p - buf);
7762 * Construct a chained hash table for mapping indexes in extra_method_info to
7765 table_size = g_spaced_primes_closest ((int)(nmethods * 1.5));
7766 table = g_ptr_array_sized_new (table_size);
7767 for (i = 0; i < table_size; ++i)
7768 g_ptr_array_add (table, NULL);
7769 chain_lengths = g_new0 (int, table_size);
7770 max_chain_length = 0;
7771 for (i = 0; i < acfg->extra_methods->len; ++i) {
7772 MonoMethod *method = g_ptr_array_index (acfg->extra_methods, i);
7773 MonoCompile *cfg = g_hash_table_lookup (acfg->method_to_cfg, method);
7779 key = info_offsets [i];
7780 value = get_method_index (acfg, method);
7782 hash = mono_aot_method_hash (method) % table_size;
7783 //printf ("X: %s %x\n", mono_method_full_name (method, 1), mono_aot_method_hash (method));
7785 chain_lengths [hash] ++;
7786 max_chain_length = MAX (max_chain_length, chain_lengths [hash]);
7788 new_entry = mono_mempool_alloc0 (acfg->mempool, sizeof (HashEntry));
7789 new_entry->key = key;
7790 new_entry->value = value;
7792 entry = g_ptr_array_index (table, hash);
7793 if (entry == NULL) {
7794 new_entry->index = hash;
7795 g_ptr_array_index (table, hash) = new_entry;
7798 entry = entry->next;
7800 entry->next = new_entry;
7801 new_entry->index = table->len;
7802 g_ptr_array_add (table, new_entry);
7806 //printf ("MAX: %d\n", max_chain_length);
7808 /* Emit the table */
7809 sprintf (symbol, "extra_method_table");
7810 emit_section_change (acfg, RODATA_SECT, 0);
7811 emit_alignment (acfg, 8);
7812 emit_label (acfg, symbol);
7814 emit_int32 (acfg, table_size);
7815 for (i = 0; i < table->len; ++i) {
7816 HashEntry *entry = g_ptr_array_index (table, i);
7818 if (entry == NULL) {
7819 emit_int32 (acfg, 0);
7820 emit_int32 (acfg, 0);
7821 emit_int32 (acfg, 0);
7823 //g_assert (entry->key > 0);
7824 emit_int32 (acfg, entry->key);
7825 emit_int32 (acfg, entry->value);
7827 emit_int32 (acfg, entry->next->index);
7829 emit_int32 (acfg, 0);
7834 * Emit a table reverse mapping method indexes to their index in extra_method_info.
7835 * This is used by mono_aot_find_jit_info ().
7837 sprintf (symbol, "extra_method_info_offsets");
7838 emit_section_change (acfg, RODATA_SECT, 0);
7839 emit_alignment (acfg, 8);
7840 emit_label (acfg, symbol);
7842 emit_int32 (acfg, acfg->extra_methods->len);
7843 for (i = 0; i < acfg->extra_methods->len; ++i) {
7844 MonoMethod *method = g_ptr_array_index (acfg->extra_methods, i);
7846 emit_int32 (acfg, get_method_index (acfg, method));
7847 emit_int32 (acfg, info_offsets [i]);
7852 emit_exception_info (MonoAotCompile *acfg)
7857 SeqPointData sp_data;
7858 gboolean seq_points_to_file = FALSE;
7860 offsets = g_new0 (gint32, acfg->nmethods);
7861 for (i = 0; i < acfg->nmethods; ++i) {
7862 if (acfg->cfgs [i]) {
7863 MonoCompile *cfg = acfg->cfgs [i];
7865 // By design aot-runtime decode_exception_debug_info is not able to load sequence point debug data from a file.
7866 // As it is not possible to load debug data from a file its is also not possible to store it in a file.
7867 gboolean method_seq_points_to_file = acfg->aot_opts.gen_seq_points_file &&
7868 cfg->gen_seq_points && !cfg->gen_seq_points_debug_data;
7869 gboolean method_seq_points_to_binary = cfg->gen_seq_points && !method_seq_points_to_file;
7871 emit_exception_debug_info (acfg, cfg, method_seq_points_to_binary);
7872 offsets [i] = cfg->ex_info_offset;
7874 if (method_seq_points_to_file) {
7875 if (!seq_points_to_file) {
7876 seq_point_data_init (&sp_data, acfg->nmethods);
7877 seq_points_to_file = TRUE;
7879 seq_point_data_add (&sp_data, cfg->method->token, cfg->seq_point_info);
7886 if (seq_points_to_file) {
7887 char *seq_points_aot_file;
7888 mono_image_get_aot_seq_point_path (acfg->image, &seq_points_aot_file);
7889 seq_point_data_write (&sp_data, seq_points_aot_file);
7890 seq_point_data_free (&sp_data);
7891 g_free (seq_points_aot_file);
7894 sprintf (symbol, "ex_info_offsets");
7895 emit_section_change (acfg, RODATA_SECT, 1);
7896 emit_alignment (acfg, 8);
7897 emit_label (acfg, symbol);
7899 acfg->stats.offsets_size += emit_offset_table (acfg, acfg->nmethods, 10, offsets);
7904 emit_unwind_info (MonoAotCompile *acfg)
7910 * The unwind info contains a lot of duplicates so we emit each unique
7911 * entry once, and only store the offset from the start of the table in the
7915 sprintf (symbol, "unwind_info");
7916 emit_section_change (acfg, RODATA_SECT, 1);
7917 emit_alignment (acfg, 8);
7918 emit_label (acfg, symbol);
7920 for (i = 0; i < acfg->unwind_ops->len; ++i) {
7921 guint32 index = GPOINTER_TO_UINT (g_ptr_array_index (acfg->unwind_ops, i));
7922 guint8 *unwind_info;
7923 guint32 unwind_info_len;
7927 unwind_info = mono_get_cached_unwind_info (index, &unwind_info_len);
7930 encode_value (unwind_info_len, p, &p);
7931 emit_bytes (acfg, buf, p - buf);
7932 emit_bytes (acfg, unwind_info, unwind_info_len);
7934 acfg->stats.unwind_info_size += (p - buf) + unwind_info_len;
7939 emit_class_info (MonoAotCompile *acfg)
7945 offsets = g_new0 (gint32, acfg->image->tables [MONO_TABLE_TYPEDEF].rows);
7946 for (i = 0; i < acfg->image->tables [MONO_TABLE_TYPEDEF].rows; ++i)
7947 offsets [i] = emit_klass_info (acfg, MONO_TOKEN_TYPE_DEF | (i + 1));
7949 sprintf (symbol, "class_info_offsets");
7950 emit_section_change (acfg, RODATA_SECT, 1);
7951 emit_alignment (acfg, 8);
7952 emit_label (acfg, symbol);
7954 acfg->stats.offsets_size += emit_offset_table (acfg, acfg->image->tables [MONO_TABLE_TYPEDEF].rows, 10, offsets);
7958 typedef struct ClassNameTableEntry {
7959 guint32 token, index;
7960 struct ClassNameTableEntry *next;
7961 } ClassNameTableEntry;
7964 emit_class_name_table (MonoAotCompile *acfg)
7967 guint32 token, hash;
7972 ClassNameTableEntry *entry, *new_entry;
7975 * Construct a chained hash table for mapping class names to typedef tokens.
7977 table_size = g_spaced_primes_closest ((int)(acfg->image->tables [MONO_TABLE_TYPEDEF].rows * 1.5));
7978 table = g_ptr_array_sized_new (table_size);
7979 for (i = 0; i < table_size; ++i)
7980 g_ptr_array_add (table, NULL);
7981 for (i = 0; i < acfg->image->tables [MONO_TABLE_TYPEDEF].rows; ++i) {
7983 token = MONO_TOKEN_TYPE_DEF | (i + 1);
7984 klass = mono_class_get_checked (acfg->image, token, &error);
7986 mono_error_cleanup (&error);
7989 full_name = mono_type_get_name_full (mono_class_get_type (klass), MONO_TYPE_NAME_FORMAT_FULL_NAME);
7990 hash = mono_metadata_str_hash (full_name) % table_size;
7993 /* FIXME: Allocate from the mempool */
7994 new_entry = g_new0 (ClassNameTableEntry, 1);
7995 new_entry->token = token;
7997 entry = g_ptr_array_index (table, hash);
7998 if (entry == NULL) {
7999 new_entry->index = hash;
8000 g_ptr_array_index (table, hash) = new_entry;
8003 entry = entry->next;
8005 entry->next = new_entry;
8006 new_entry->index = table->len;
8007 g_ptr_array_add (table, new_entry);
8011 /* Emit the table */
8012 sprintf (symbol, "class_name_table");
8013 emit_section_change (acfg, RODATA_SECT, 0);
8014 emit_alignment (acfg, 8);
8015 emit_label (acfg, symbol);
8017 /* FIXME: Optimize memory usage */
8018 g_assert (table_size < 65000);
8019 emit_int16 (acfg, table_size);
8020 g_assert (table->len < 65000);
8021 for (i = 0; i < table->len; ++i) {
8022 ClassNameTableEntry *entry = g_ptr_array_index (table, i);
8024 if (entry == NULL) {
8025 emit_int16 (acfg, 0);
8026 emit_int16 (acfg, 0);
8028 emit_int16 (acfg, mono_metadata_token_index (entry->token));
8030 emit_int16 (acfg, entry->next->index);
8032 emit_int16 (acfg, 0);
8038 emit_image_table (MonoAotCompile *acfg)
8044 * The image table is small but referenced in a lot of places.
8045 * So we emit it at once, and reference its elements by an index.
8048 sprintf (symbol, "image_table");
8049 emit_section_change (acfg, RODATA_SECT, 1);
8050 emit_alignment (acfg, 8);
8051 emit_label (acfg, symbol);
8053 emit_int32 (acfg, acfg->image_table->len);
8054 for (i = 0; i < acfg->image_table->len; i++) {
8055 MonoImage *image = (MonoImage*)g_ptr_array_index (acfg->image_table, i);
8056 MonoAssemblyName *aname = &image->assembly->aname;
8058 /* FIXME: Support multi-module assemblies */
8059 g_assert (image->assembly->image == image);
8061 emit_string (acfg, image->assembly_name);
8062 emit_string (acfg, image->guid);
8063 emit_string (acfg, aname->culture ? aname->culture : "");
8064 emit_string (acfg, (const char*)aname->public_key_token);
8066 emit_alignment (acfg, 8);
8067 emit_int32 (acfg, aname->flags);
8068 emit_int32 (acfg, aname->major);
8069 emit_int32 (acfg, aname->minor);
8070 emit_int32 (acfg, aname->build);
8071 emit_int32 (acfg, aname->revision);
8076 emit_got_info (MonoAotCompile *acfg, gboolean llvm)
8079 int i, first_plt_got_patch = 0, buf_size;
8081 guint32 *got_info_offsets;
8082 GotInfo *info = llvm ? &acfg->llvm_got_info : &acfg->got_info;
8084 /* Add the patches needed by the PLT to the GOT */
8086 acfg->plt_got_offset_base = acfg->got_offset;
8087 first_plt_got_patch = info->got_patches->len;
8088 for (i = 1; i < acfg->plt_offset; ++i) {
8089 MonoPltEntry *plt_entry = g_hash_table_lookup (acfg->plt_offset_to_entry, GUINT_TO_POINTER (i));
8091 g_ptr_array_add (info->got_patches, plt_entry->ji);
8093 acfg->stats.got_slot_types [plt_entry->ji->type] ++;
8096 acfg->got_offset += acfg->plt_offset;
8101 * - optimize offsets table.
8102 * - reduce number of exported symbols.
8103 * - emit info for a klass only once.
8104 * - determine when a method uses a GOT slot which is guaranteed to be already
8106 * - clean up and document the code.
8107 * - use String.Empty in class libs.
8110 /* Encode info required to decode shared GOT entries */
8111 buf_size = info->got_patches->len * 128;
8112 p = buf = mono_mempool_alloc (acfg->mempool, buf_size);
8113 got_info_offsets = mono_mempool_alloc (acfg->mempool, info->got_patches->len * sizeof (guint32));
8115 acfg->plt_got_info_offsets = mono_mempool_alloc (acfg->mempool, acfg->plt_offset * sizeof (guint32));
8117 if (acfg->plt_offset)
8118 acfg->plt_got_info_offsets [0] = 0;
8120 for (i = 0; i < info->got_patches->len; ++i) {
8121 MonoJumpInfo *ji = g_ptr_array_index (info->got_patches, i);
8126 encode_value (ji->type, p, &p);
8128 encode_patch (acfg, ji, p, &p);
8129 acfg->stats.got_slot_info_sizes [ji->type] += p - p2;
8130 g_assert (p - buf <= buf_size);
8131 got_info_offsets [i] = add_to_blob (acfg, buf, p - buf);
8133 if (!llvm && i >= first_plt_got_patch)
8134 acfg->plt_got_info_offsets [i - first_plt_got_patch + 1] = got_info_offsets [i];
8135 acfg->stats.got_info_size += p - buf;
8138 /* Emit got_info_offsets table */
8140 sprintf (symbol, "llvm_got_info_offsets");
8142 sprintf (symbol, "got_info_offsets");
8143 emit_section_change (acfg, RODATA_SECT, 1);
8144 emit_alignment (acfg, 8);
8145 emit_label (acfg, symbol);
8147 /* No need to emit offsets for the got plt entries, the plt embeds them directly */
8148 acfg->stats.offsets_size += emit_offset_table (acfg, llvm ? acfg->llvm_got_offset : first_plt_got_patch, 10, (gint32*)got_info_offsets);
8152 emit_got (MonoAotCompile *acfg)
8156 /* Don't make GOT global so accesses to it don't need relocations */
8157 sprintf (symbol, "%s", acfg->got_symbol);
8158 emit_section_change (acfg, ".bss", 0);
8159 emit_alignment (acfg, 8);
8160 emit_local_symbol (acfg, symbol, "got_end", FALSE);
8161 emit_label (acfg, symbol);
8162 if (acfg->got_offset > 0)
8163 emit_zero_bytes (acfg, (int)(acfg->got_offset * sizeof (gpointer)));
8165 sprintf (symbol, "got_end");
8166 emit_label (acfg, symbol);
8169 typedef struct GlobalsTableEntry {
8170 guint32 value, index;
8171 struct GlobalsTableEntry *next;
8172 } GlobalsTableEntry;
8175 emit_globals (MonoAotCompile *acfg)
8181 GlobalsTableEntry *entry, *new_entry;
8183 if (!acfg->aot_opts.static_link)
8187 * When static linking, we emit a table containing our globals.
8191 * Construct a chained hash table for mapping global names to their index in
8192 * the globals table.
8194 table_size = g_spaced_primes_closest ((int)(acfg->globals->len * 1.5));
8195 table = g_ptr_array_sized_new (table_size);
8196 for (i = 0; i < table_size; ++i)
8197 g_ptr_array_add (table, NULL);
8198 for (i = 0; i < acfg->globals->len; ++i) {
8199 char *name = g_ptr_array_index (acfg->globals, i);
8201 hash = mono_metadata_str_hash (name) % table_size;
8203 /* FIXME: Allocate from the mempool */
8204 new_entry = g_new0 (GlobalsTableEntry, 1);
8205 new_entry->value = i;
8207 entry = g_ptr_array_index (table, hash);
8208 if (entry == NULL) {
8209 new_entry->index = hash;
8210 g_ptr_array_index (table, hash) = new_entry;
8213 entry = entry->next;
8215 entry->next = new_entry;
8216 new_entry->index = table->len;
8217 g_ptr_array_add (table, new_entry);
8221 /* Emit the table */
8222 sprintf (symbol, ".Lglobals_hash");
8223 emit_section_change (acfg, RODATA_SECT, 0);
8224 emit_alignment (acfg, 8);
8225 emit_label (acfg, symbol);
8227 /* FIXME: Optimize memory usage */
8228 g_assert (table_size < 65000);
8229 emit_int16 (acfg, table_size);
8230 for (i = 0; i < table->len; ++i) {
8231 GlobalsTableEntry *entry = g_ptr_array_index (table, i);
8233 if (entry == NULL) {
8234 emit_int16 (acfg, 0);
8235 emit_int16 (acfg, 0);
8237 emit_int16 (acfg, entry->value + 1);
8239 emit_int16 (acfg, entry->next->index);
8241 emit_int16 (acfg, 0);
8245 /* Emit the names */
8246 for (i = 0; i < acfg->globals->len; ++i) {
8247 char *name = g_ptr_array_index (acfg->globals, i);
8249 sprintf (symbol, "name_%d", i);
8250 emit_section_change (acfg, RODATA_SECT, 1);
8252 emit_alignment (acfg, 4);
8254 emit_label (acfg, symbol);
8255 emit_string (acfg, name);
8258 /* Emit the globals table */
8259 sprintf (symbol, "globals");
8260 emit_section_change (acfg, ".data", 0);
8261 /* This is not a global, since it is accessed by the init function */
8262 emit_alignment (acfg, 8);
8263 emit_label (acfg, symbol);
8265 sprintf (symbol, "%sglobals_hash", acfg->temp_prefix);
8266 emit_pointer (acfg, symbol);
8268 for (i = 0; i < acfg->globals->len; ++i) {
8269 char *name = g_ptr_array_index (acfg->globals, i);
8271 sprintf (symbol, "name_%d", i);
8272 emit_pointer (acfg, symbol);
8274 g_assert (strlen (name) < sizeof (symbol));
8275 sprintf (symbol, "%s", name);
8276 emit_pointer (acfg, symbol);
8278 /* Null terminate the table */
8279 emit_int32 (acfg, 0);
8280 emit_int32 (acfg, 0);
8284 emit_autoreg (MonoAotCompile *acfg)
8289 * Emit a function into the .ctor section which will be called by the ELF
8290 * loader to register this module with the runtime.
8292 if (! (!acfg->use_bin_writer && acfg->aot_opts.static_link && acfg->aot_opts.autoreg))
8295 symbol = g_strdup_printf ("_%s_autoreg", acfg->static_linking_symbol);
8297 arch_emit_autoreg (acfg, symbol);
8303 emit_mem_end (MonoAotCompile *acfg)
8307 sprintf (symbol, "mem_end");
8308 emit_section_change (acfg, ".text", 1);
8309 emit_alignment_code (acfg, 8);
8310 emit_label (acfg, symbol);
8314 * Emit a structure containing all the information not stored elsewhere.
8317 emit_file_info (MonoAotCompile *acfg)
8322 const char *gc_name;
8325 emit_string_symbol (acfg, "assembly_guid" , acfg->image->guid);
8327 if (acfg->aot_opts.bind_to_runtime_version) {
8328 build_info = mono_get_runtime_build_info ();
8329 emit_string_symbol (acfg, "runtime_version", build_info);
8330 g_free (build_info);
8332 emit_string_symbol (acfg, "runtime_version", "");
8335 /* Emit a string holding the assembly name */
8336 emit_string_symbol (acfg, "assembly_name", acfg->image->assembly->aname.name);
8339 * The managed allocators are GC specific, so can't use an AOT image created by one GC
8342 gc_name = mono_gc_get_gc_name ();
8343 gc_name_offset = add_to_blob (acfg, (guint8*)gc_name, strlen (gc_name) + 1);
8345 sprintf (symbol, "%smono_aot_file_info", acfg->user_symbol_prefix);
8346 emit_section_change (acfg, ".data", 0);
8347 emit_alignment (acfg, 8);
8348 emit_label (acfg, symbol);
8349 if (!acfg->aot_opts.static_link)
8350 emit_global (acfg, symbol, FALSE);
8352 /* The data emitted here must match MonoAotFileInfo. */
8354 emit_int32 (acfg, MONO_AOT_FILE_VERSION);
8355 emit_int32 (acfg, 0);
8358 * We emit pointers to our data structures instead of emitting global symbols which
8359 * point to them, to reduce the number of globals, and because using globals leads to
8360 * various problems (i.e. arm/thumb).
8362 emit_pointer (acfg, acfg->got_symbol);
8364 emit_pointer (acfg, acfg->llvm_got_symbol);
8366 emit_pointer (acfg, NULL);
8367 emit_pointer (acfg, acfg->methods_symbol);
8368 emit_pointer (acfg, "jit_code_start");
8369 emit_pointer (acfg, "jit_code_end");
8372 * Emit a reference to the mono_eh_frame table created by our modified LLVM compiler.
8374 emit_pointer (acfg, acfg->llvm_eh_frame_symbol);
8376 emit_pointer (acfg, NULL);
8378 emit_pointer (acfg, "blob");
8379 emit_pointer (acfg, "class_name_table");
8380 emit_pointer (acfg, "class_info_offsets");
8381 emit_pointer (acfg, "method_info_offsets");
8382 emit_pointer (acfg, "ex_info_offsets");
8383 emit_pointer (acfg, "method_addresses");
8384 emit_pointer (acfg, "extra_method_info_offsets");
8385 emit_pointer (acfg, "extra_method_table");
8386 emit_pointer (acfg, "got_info_offsets");
8388 emit_pointer (acfg, "llvm_got_info_offsets");
8390 emit_pointer (acfg, NULL);
8391 emit_pointer (acfg, "unwind_info");
8392 emit_pointer (acfg, "mem_end");
8393 emit_pointer (acfg, "image_table");
8394 emit_pointer (acfg, "plt");
8395 emit_pointer (acfg, "plt_end");
8396 emit_pointer (acfg, "assembly_guid");
8397 emit_pointer (acfg, "runtime_version");
8398 if (acfg->num_trampoline_got_entries) {
8399 emit_pointer (acfg, "specific_trampolines");
8400 emit_pointer (acfg, "static_rgctx_trampolines");
8401 emit_pointer (acfg, "imt_thunks");
8402 emit_pointer (acfg, "gsharedvt_arg_trampolines");
8404 emit_pointer (acfg, NULL);
8405 emit_pointer (acfg, NULL);
8406 emit_pointer (acfg, NULL);
8407 emit_pointer (acfg, NULL);
8409 if (acfg->thumb_mixed) {
8410 emit_pointer (acfg, "thumb_end");
8412 emit_pointer (acfg, NULL);
8414 if (acfg->aot_opts.static_link) {
8415 emit_pointer (acfg, "globals");
8417 emit_pointer (acfg, NULL);
8419 emit_pointer (acfg, "assembly_name");
8420 emit_pointer (acfg, "unbox_trampolines");
8421 emit_pointer (acfg, "unbox_trampolines_end");
8422 emit_pointer (acfg, "unbox_trampoline_addresses");
8424 emit_int32 (acfg, acfg->plt_got_offset_base);
8425 emit_int32 (acfg, (int)(acfg->got_offset * sizeof (gpointer)));
8426 emit_int32 (acfg, acfg->plt_offset);
8427 emit_int32 (acfg, acfg->nmethods);
8428 emit_int32 (acfg, acfg->flags);
8429 emit_int32 (acfg, acfg->opts);
8430 emit_int32 (acfg, acfg->simd_opts);
8431 emit_int32 (acfg, gc_name_offset);
8433 for (i = 0; i < MONO_AOT_TRAMP_NUM; ++i)
8434 emit_int32 (acfg, acfg->num_trampolines [i]);
8435 for (i = 0; i < MONO_AOT_TRAMP_NUM; ++i)
8436 emit_int32 (acfg, acfg->trampoline_got_offset_base [i]);
8437 for (i = 0; i < MONO_AOT_TRAMP_NUM; ++i)
8438 emit_int32 (acfg, acfg->trampoline_size [i]);
8439 emit_int32 (acfg, acfg->aot_opts.nrgctx_fetch_trampolines);
8441 #if defined (TARGET_ARM) && defined (TARGET_MACH)
8446 memset (&t, 0, sizeof (MonoType));
8447 t.type = MONO_TYPE_R8;
8448 mono_type_size (&t, &align);
8449 emit_int32 (acfg, align);
8451 memset (&t, 0, sizeof (MonoType));
8452 t.type = MONO_TYPE_I8;
8453 mono_type_size (&t, &align);
8455 emit_int32 (acfg, align);
8458 emit_int32 (acfg, MONO_ABI_ALIGNOF (double));
8459 emit_int32 (acfg, MONO_ABI_ALIGNOF (gint64));
8461 emit_int32 (acfg, MONO_TRAMPOLINE_NUM);
8462 emit_int32 (acfg, acfg->tramp_page_size);
8463 for (i = 0; i < MONO_AOT_TRAMP_NUM; ++i)
8464 emit_int32 (acfg, acfg->tramp_page_code_offsets [i]);
8466 if (acfg->aot_opts.static_link) {
8470 * Emit a global symbol which can be passed by an embedding app to
8471 * mono_aot_register_module (). The symbol points to a pointer to the the file info
8474 sprintf (symbol, "%smono_aot_module_%s_info", acfg->user_symbol_prefix, acfg->image->assembly->aname.name);
8476 /* Get rid of characters which cannot occur in symbols */
8478 for (p = symbol; *p; ++p) {
8479 if (!(isalnum (*p) || *p == '_'))
8482 acfg->static_linking_symbol = g_strdup (symbol);
8483 emit_global_inner (acfg, symbol, FALSE);
8484 emit_alignment (acfg, sizeof (gpointer));
8485 emit_label (acfg, symbol);
8486 emit_pointer_2 (acfg, acfg->user_symbol_prefix, "mono_aot_file_info");
8491 emit_blob (MonoAotCompile *acfg)
8495 sprintf (symbol, "blob");
8496 emit_section_change (acfg, RODATA_SECT, 1);
8497 emit_alignment (acfg, 8);
8498 emit_label (acfg, symbol);
8500 emit_bytes (acfg, (guint8*)acfg->blob.data, acfg->blob.index);
8504 emit_objc_selectors (MonoAotCompile *acfg)
8508 if (!acfg->objc_selectors || acfg->objc_selectors->len == 0)
8513 * cat > foo.m << EOF
8516 * return @selector(print:);
8521 img_writer_emit_unset_mode (acfg->w);
8522 g_assert (acfg->fp);
8523 fprintf (acfg->fp, ".section __DATA,__objc_selrefs,literal_pointers,no_dead_strip\n");
8524 fprintf (acfg->fp, ".align 3\n");
8525 for (i = 0; i < acfg->objc_selectors->len; ++i) {
8526 fprintf (acfg->fp, "L_OBJC_SELECTOR_REFERENCES_%d:\n", i);
8527 fprintf (acfg->fp, ".long L_OBJC_METH_VAR_NAME_%d\n", i);
8529 fprintf (acfg->fp, ".section __TEXT,__cstring,cstring_literals\n");
8530 for (i = 0; i < acfg->objc_selectors->len; ++i) {
8531 fprintf (acfg->fp, "L_OBJC_METH_VAR_NAME_%d:\n", i);
8532 fprintf (acfg->fp, ".asciz \"%s\"\n", (char*)g_ptr_array_index (acfg->objc_selectors, i));
8535 fprintf (acfg->fp, ".section __DATA,__objc_imageinfo,regular,no_dead_strip\n");
8536 fprintf (acfg->fp, ".align 3\n");
8537 fprintf (acfg->fp, "L_OBJC_IMAGE_INFO:\n");
8538 fprintf (acfg->fp, ".long 0\n");
8539 fprintf (acfg->fp, ".long 16\n");
8543 emit_dwarf_info (MonoAotCompile *acfg)
8545 #ifdef EMIT_DWARF_INFO
8549 /* DIEs for methods */
8550 for (i = 0; i < acfg->nmethods; ++i) {
8551 MonoCompile *cfg = acfg->cfgs [i];
8556 // FIXME: LLVM doesn't define .Lme_...
8557 if (cfg->compile_llvm)
8560 sprintf (symbol2, "%sme_%x", acfg->temp_prefix, i);
8562 mono_dwarf_writer_emit_method (acfg->dwarf, cfg, cfg->method, cfg->asm_symbol, symbol2, cfg->asm_debug_symbol, cfg->jit_info->code_start, cfg->jit_info->code_size, cfg->args, cfg->locals, cfg->unwind_ops, mono_debug_find_method (cfg->jit_info->d.method, mono_domain_get ()));
8568 collect_methods (MonoAotCompile *acfg)
8571 MonoImage *image = acfg->image;
8573 /* Collect methods */
8574 for (i = 0; i < image->tables [MONO_TABLE_METHOD].rows; ++i) {
8577 guint32 token = MONO_TOKEN_METHOD_DEF | (i + 1);
8579 method = mono_get_method_checked (acfg->image, token, NULL, NULL, &error);
8582 aot_printerrf (acfg, "Failed to load method 0x%x from '%s' due to %s.\n", token, image->name, mono_error_get_message (&error));
8583 aot_printerrf (acfg, "Run with MONO_LOG_LEVEL=debug for more information.\n");
8584 mono_error_cleanup (&error);
8588 /* Load all methods eagerly to skip the slower lazy loading code */
8589 mono_class_setup_methods (method->klass);
8591 if (acfg->aot_opts.full_aot && method->iflags & METHOD_IMPL_ATTRIBUTE_INTERNAL_CALL) {
8592 /* Compile the wrapper instead */
8593 /* We do this here instead of add_wrappers () because it is easy to do it here */
8594 MonoMethod *wrapper = mono_marshal_get_native_wrapper (method, check_for_pending_exc, TRUE);
8598 /* FIXME: Some mscorlib methods don't have debug info */
8600 if (acfg->aot_opts.soft_debug && !method->wrapper_type) {
8601 if (!((method->flags & METHOD_ATTRIBUTE_PINVOKE_IMPL) ||
8602 (method->iflags & METHOD_IMPL_ATTRIBUTE_RUNTIME) ||
8603 (method->flags & METHOD_ATTRIBUTE_ABSTRACT) ||
8604 (method->iflags & METHOD_IMPL_ATTRIBUTE_INTERNAL_CALL))) {
8605 if (!mono_debug_lookup_method (method)) {
8606 fprintf (stderr, "Method %s has no debug info, probably the .mdb file for the assembly is missing.\n", mono_method_full_name (method, TRUE));
8613 /* Since we add the normal methods first, their index will be equal to their zero based token index */
8614 add_method_with_index (acfg, method, i, FALSE);
8615 acfg->method_index ++;
8618 /* gsharedvt methods */
8619 for (mindex = 0; mindex < image->tables [MONO_TABLE_METHOD].rows; ++mindex) {
8622 guint32 token = MONO_TOKEN_METHOD_DEF | (mindex + 1);
8624 if (!(acfg->opts & MONO_OPT_GSHAREDVT))
8627 method = mono_get_method_checked (acfg->image, token, NULL, NULL, &error);
8628 report_loader_error (acfg, &error, "Failed to load method token 0x%x due to %s\n", i, mono_error_get_message (&error));
8631 if (strcmp (method->name, "gshared2"))
8635 if (!strstr (method->klass->image->name, "mini"))
8638 if (method->is_generic || method->klass->generic_container) {
8639 MonoMethod *gshared;
8641 gshared = mini_get_shared_method_full (method, TRUE, TRUE);
8642 add_extra_method (acfg, gshared);
8646 add_generic_instances (acfg);
8648 if (acfg->aot_opts.full_aot)
8649 add_wrappers (acfg);
8654 compile_methods (MonoAotCompile *acfg)
8658 if (acfg->aot_opts.nthreads > 0) {
8663 gpointer *user_data;
8664 MonoMethod **methods;
8666 methods_len = acfg->methods->len;
8668 len = acfg->methods->len / acfg->aot_opts.nthreads;
8671 * Partition the list of methods into fragments, and hand it to threads to
8674 threads = g_ptr_array_new ();
8675 /* Make a copy since acfg->methods is modified by compile_method () */
8676 methods = g_new0 (MonoMethod*, methods_len);
8677 //memcpy (methods, g_ptr_array_index (acfg->methods, 0), sizeof (MonoMethod*) * methods_len);
8678 for (i = 0; i < methods_len; ++i)
8679 methods [i] = g_ptr_array_index (acfg->methods, i);
8681 while (i < methods_len) {
8682 frag = g_ptr_array_new ();
8683 for (j = 0; j < len; ++j) {
8684 if (i < methods_len) {
8685 g_ptr_array_add (frag, methods [i]);
8690 user_data = g_new0 (gpointer, 3);
8691 user_data [0] = mono_domain_get ();
8692 user_data [1] = acfg;
8693 user_data [2] = frag;
8695 handle = mono_threads_create_thread ((gpointer)compile_thread_main, user_data, 0, 0, NULL);
8696 g_ptr_array_add (threads, handle);
8700 for (i = 0; i < threads->len; ++i) {
8701 WaitForSingleObjectEx (g_ptr_array_index (threads, i), INFINITE, FALSE);
8707 /* Compile methods added by compile_method () or all methods if nthreads == 0 */
8708 for (i = methods_len; i < acfg->methods->len; ++i) {
8709 /* This can new methods to acfg->methods */
8710 compile_method (acfg, g_ptr_array_index (acfg->methods, i));
8715 compile_asm (MonoAotCompile *acfg)
8717 char *command, *objfile;
8718 char *outfile_name, *tmp_outfile_name, *llvm_ofile;
8719 const char *tool_prefix = acfg->aot_opts.tool_prefix ? acfg->aot_opts.tool_prefix : "";
8720 char *ld_flags = acfg->aot_opts.ld_flags ? acfg->aot_opts.ld_flags : g_strdup("");
8722 #if defined(TARGET_AMD64) && !defined(TARGET_MACH)
8723 #define AS_OPTIONS "--64"
8724 #elif defined(TARGET_POWERPC64)
8725 #define AS_OPTIONS "-a64 -mppc64"
8726 #define LD_OPTIONS "-m elf64ppc"
8727 #elif defined(sparc) && SIZEOF_VOID_P == 8
8728 #define AS_OPTIONS "-xarch=v9"
8729 #elif defined(TARGET_X86) && defined(TARGET_MACH) && !defined(__native_client_codegen__)
8730 #define AS_OPTIONS "-arch i386"
8732 #define AS_OPTIONS ""
8735 #ifdef __native_client_codegen__
8736 #if defined(TARGET_AMD64)
8737 #define AS_NAME "nacl64-as"
8739 #define AS_NAME "nacl-as"
8741 #elif defined(TARGET_OSX)
8742 #define AS_NAME "clang"
8744 #define AS_NAME "as"
8748 #define LD_OPTIONS ""
8752 #define LD_NAME "ld -shared -G"
8753 #elif defined(__ppc__) && defined(TARGET_MACH)
8754 #define LD_NAME "gcc -dynamiclib"
8755 #elif defined(TARGET_AMD64) && defined(TARGET_MACH)
8756 #define LD_NAME "clang --shared"
8757 #elif defined(TARGET_WIN32) && !defined(TARGET_ANDROID)
8758 #define LD_NAME "gcc -shared --dll"
8759 #elif defined(TARGET_X86) && defined(TARGET_MACH) && !defined(__native_client_codegen__)
8760 #define LD_NAME "clang -m32 -dynamiclib"
8763 if (acfg->aot_opts.asm_only) {
8764 aot_printf (acfg, "Output file: '%s'.\n", acfg->tmpfname);
8765 if (acfg->aot_opts.static_link)
8766 aot_printf (acfg, "Linking symbol: '%s'.\n", acfg->static_linking_symbol);
8767 if (acfg->llvm_separate)
8768 aot_printf (acfg, "LLVM output file: '%s'.\n", acfg->llvm_sfile);
8772 if (acfg->aot_opts.static_link) {
8773 if (acfg->aot_opts.outfile)
8774 objfile = g_strdup_printf ("%s", acfg->aot_opts.outfile);
8776 objfile = g_strdup_printf ("%s.o", acfg->image->name);
8778 objfile = g_strdup_printf ("%s.o", acfg->tmpfname);
8782 g_string_append (acfg->as_args, "-c -x assembler");
8785 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);
8786 aot_printf (acfg, "Executing the native assembler: %s\n", command);
8787 if (execute_system (command) != 0) {
8793 if (acfg->llvm_separate && !acfg->llvm_owriter) {
8794 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);
8795 aot_printf (acfg, "Executing the native assembler: %s\n", command);
8796 if (execute_system (command) != 0) {
8805 if (acfg->aot_opts.static_link) {
8806 aot_printf (acfg, "Output file: '%s'.\n", objfile);
8807 aot_printf (acfg, "Linking symbol: '%s'.\n", acfg->static_linking_symbol);
8812 if (acfg->aot_opts.outfile)
8813 outfile_name = g_strdup_printf ("%s", acfg->aot_opts.outfile);
8815 outfile_name = g_strdup_printf ("%s%s", acfg->image->name, MONO_SOLIB_EXT);
8817 tmp_outfile_name = g_strdup_printf ("%s.tmp", outfile_name);
8819 if (acfg->llvm_separate) {
8820 llvm_ofile = g_strdup (acfg->llvm_ofile);
8822 llvm_ofile = g_strdup ("");
8825 /* replace the ; flags separators with spaces */
8826 g_strdelimit (ld_flags, ";", ' ');
8829 command = g_strdup_printf ("%s -o %s %s %s.o %s", LD_NAME, tmp_outfile_name, llvm_ofile, acfg->tmpfname, ld_flags);
8831 command = g_strdup_printf ("\"%sld\" %s -shared -o %s %s %s.o %s", tool_prefix, LD_OPTIONS, tmp_outfile_name, llvm_ofile,
8832 acfg->tmpfname, ld_flags);
8834 aot_printf (acfg, "Executing the native linker: %s\n", command);
8835 if (execute_system (command) != 0) {
8836 g_free (tmp_outfile_name);
8837 g_free (outfile_name);
8846 /*com = g_strdup_printf ("strip --strip-unneeded %s%s", acfg->image->name, MONO_SOLIB_EXT);
8847 printf ("Stripping the binary: %s\n", com);
8848 execute_system (com);
8851 #if defined(TARGET_ARM) && !defined(TARGET_MACH)
8853 * gas generates 'mapping symbols' each time code and data is mixed, which
8854 * happens a lot in emit_and_reloc_code (), so we need to get rid of them.
8856 command = g_strdup_printf ("%sstrip --strip-symbol=\\$a --strip-symbol=\\$d %s", tool_prefix, tmp_outfile_name);
8857 aot_printf (acfg, "Stripping the binary: %s\n", command);
8858 if (execute_system (command) != 0) {
8859 g_free (tmp_outfile_name);
8860 g_free (outfile_name);
8867 rename (tmp_outfile_name, outfile_name);
8869 #if defined(TARGET_MACH)
8870 command = g_strdup_printf ("dsymutil %s", outfile_name);
8871 aot_printf (acfg, "Executing dsymutil: %s\n", command);
8872 if (execute_system (command) != 0) {
8877 if (!acfg->aot_opts.save_temps)
8880 g_free (tmp_outfile_name);
8881 g_free (outfile_name);
8884 if (acfg->aot_opts.save_temps)
8885 aot_printf (acfg, "Retained input file.\n");
8887 unlink (acfg->tmpfname);
8892 static void init_got_info (GotInfo *info)
8896 info->patch_to_got_offset = g_hash_table_new (mono_patch_info_hash, mono_patch_info_equal);
8897 info->patch_to_got_offset_by_type = g_new0 (GHashTable*, MONO_PATCH_INFO_NUM);
8898 for (i = 0; i < MONO_PATCH_INFO_NUM; ++i)
8899 info->patch_to_got_offset_by_type [i] = g_hash_table_new (mono_patch_info_hash, mono_patch_info_equal);
8900 info->got_patches = g_ptr_array_new ();
8903 static MonoAotCompile*
8904 acfg_create (MonoAssembly *ass, guint32 opts)
8906 MonoImage *image = ass->image;
8907 MonoAotCompile *acfg;
8909 acfg = g_new0 (MonoAotCompile, 1);
8910 acfg->methods = g_ptr_array_new ();
8911 acfg->method_indexes = g_hash_table_new (NULL, NULL);
8912 acfg->method_depth = g_hash_table_new (NULL, NULL);
8913 acfg->plt_offset_to_entry = g_hash_table_new (NULL, NULL);
8914 acfg->patch_to_plt_entry = g_new0 (GHashTable*, MONO_PATCH_INFO_NUM);
8915 acfg->method_to_cfg = g_hash_table_new (NULL, NULL);
8916 acfg->token_info_hash = g_hash_table_new_full (NULL, NULL, NULL, NULL);
8917 acfg->method_to_pinvoke_import = g_hash_table_new_full (NULL, NULL, NULL, g_free);
8918 acfg->image_hash = g_hash_table_new (NULL, NULL);
8919 acfg->image_table = g_ptr_array_new ();
8920 acfg->globals = g_ptr_array_new ();
8921 acfg->image = image;
8923 /* TODO: Write out set of SIMD instructions used, rather than just those available */
8924 acfg->simd_opts = mono_arch_cpu_enumerate_simd_versions ();
8925 acfg->mempool = mono_mempool_new ();
8926 acfg->extra_methods = g_ptr_array_new ();
8927 acfg->unwind_info_offsets = g_hash_table_new (NULL, NULL);
8928 acfg->unwind_ops = g_ptr_array_new ();
8929 acfg->method_label_hash = g_hash_table_new_full (g_str_hash, g_str_equal, g_free, NULL);
8930 acfg->method_order = g_ptr_array_new ();
8931 acfg->export_names = g_hash_table_new (NULL, NULL);
8932 acfg->klass_blob_hash = g_hash_table_new (NULL, NULL);
8933 acfg->method_blob_hash = g_hash_table_new (NULL, NULL);
8934 acfg->plt_entry_debug_sym_cache = g_hash_table_new (g_str_hash, g_str_equal);
8935 mono_mutex_init_recursive (&acfg->mutex);
8937 init_got_info (&acfg->got_info);
8938 init_got_info (&acfg->llvm_got_info);
8944 got_info_free (GotInfo *info)
8948 for (i = 0; i < MONO_PATCH_INFO_NUM; ++i)
8949 g_hash_table_destroy (info->patch_to_got_offset_by_type [i]);
8950 g_free (info->patch_to_got_offset_by_type);
8951 g_hash_table_destroy (info->patch_to_got_offset);
8952 g_ptr_array_free (info->got_patches, TRUE);
8956 acfg_free (MonoAotCompile *acfg)
8960 img_writer_destroy (acfg->w);
8961 for (i = 0; i < acfg->nmethods; ++i)
8963 g_free (acfg->cfgs [i]);
8964 g_free (acfg->cfgs);
8965 g_free (acfg->static_linking_symbol);
8966 g_free (acfg->got_symbol);
8967 g_free (acfg->plt_symbol);
8968 g_ptr_array_free (acfg->methods, TRUE);
8969 g_ptr_array_free (acfg->image_table, TRUE);
8970 g_ptr_array_free (acfg->globals, TRUE);
8971 g_ptr_array_free (acfg->unwind_ops, TRUE);
8972 g_hash_table_destroy (acfg->method_indexes);
8973 g_hash_table_destroy (acfg->method_depth);
8974 g_hash_table_destroy (acfg->plt_offset_to_entry);
8975 for (i = 0; i < MONO_PATCH_INFO_NUM; ++i) {
8976 if (acfg->patch_to_plt_entry [i])
8977 g_hash_table_destroy (acfg->patch_to_plt_entry [i]);
8979 g_free (acfg->patch_to_plt_entry);
8980 g_hash_table_destroy (acfg->method_to_cfg);
8981 g_hash_table_destroy (acfg->token_info_hash);
8982 g_hash_table_destroy (acfg->method_to_pinvoke_import);
8983 g_hash_table_destroy (acfg->image_hash);
8984 g_hash_table_destroy (acfg->unwind_info_offsets);
8985 g_hash_table_destroy (acfg->method_label_hash);
8986 g_hash_table_destroy (acfg->export_names);
8987 g_hash_table_destroy (acfg->plt_entry_debug_sym_cache);
8988 g_hash_table_destroy (acfg->klass_blob_hash);
8989 g_hash_table_destroy (acfg->method_blob_hash);
8990 got_info_free (&acfg->got_info);
8991 got_info_free (&acfg->llvm_got_info);
8992 mono_mempool_destroy (acfg->mempool);
8996 #define WRAPPER(e,n) n,
8997 static const char* const
8998 wrapper_type_names [MONO_WRAPPER_NUM + 1] = {
8999 #include "mono/metadata/wrapper-types.h"
9003 static G_GNUC_UNUSED const char*
9004 get_wrapper_type_name (int type)
9006 return wrapper_type_names [type];
9012 static void aot_dump (MonoAotCompile *acfg)
9018 json_writer_init (&writer);
9020 json_writer_object_begin(&writer);
9023 json_writer_indent (&writer);
9024 json_writer_object_key(&writer, "methods");
9025 json_writer_array_begin (&writer);
9028 for (i = 0; i < acfg->nmethods; ++i) {
9033 cfg = acfg->cfgs [i];
9037 method = cfg->orig_method;
9039 json_writer_indent (&writer);
9040 json_writer_object_begin(&writer);
9042 json_writer_indent (&writer);
9043 json_writer_object_key(&writer, "name");
9044 json_writer_printf (&writer, "\"%s\",\n", method->name);
9046 json_writer_indent (&writer);
9047 json_writer_object_key(&writer, "signature");
9048 json_writer_printf (&writer, "\"%s\",\n", mono_method_full_name (method,
9049 /*signature=*/TRUE));
9051 json_writer_indent (&writer);
9052 json_writer_object_key(&writer, "code_size");
9053 json_writer_printf (&writer, "\"%d\",\n", cfg->code_size);
9055 klass = method->klass;
9057 json_writer_indent (&writer);
9058 json_writer_object_key(&writer, "class");
9059 json_writer_printf (&writer, "\"%s\",\n", klass->name);
9061 json_writer_indent (&writer);
9062 json_writer_object_key(&writer, "namespace");
9063 json_writer_printf (&writer, "\"%s\",\n", klass->name_space);
9065 json_writer_indent (&writer);
9066 json_writer_object_key(&writer, "wrapper_type");
9067 json_writer_printf (&writer, "\"%s\",\n", get_wrapper_type_name(method->wrapper_type));
9069 json_writer_indent_pop (&writer);
9070 json_writer_indent (&writer);
9071 json_writer_object_end (&writer);
9072 json_writer_printf (&writer, ",\n");
9075 json_writer_indent_pop (&writer);
9076 json_writer_indent (&writer);
9077 json_writer_array_end (&writer);
9078 json_writer_printf (&writer, ",\n");
9082 json_writer_indent_push (&writer);
9083 json_writer_indent (&writer);
9084 json_writer_object_key(&writer, "plt");
9085 json_writer_array_begin (&writer);
9087 for (i = 0; i < acfg->plt_offset; ++i) {
9088 MonoPltEntry *plt_entry = NULL;
9093 * The first plt entry is unused.
9097 plt_entry = g_hash_table_lookup (acfg->plt_offset_to_entry, GUINT_TO_POINTER (i));
9100 json_writer_indent (&writer);
9101 json_writer_printf (&writer, "{ ");
9102 json_writer_object_key(&writer, "symbol");
9103 json_writer_printf (&writer, "\"%s\" },\n", plt_entry->symbol);
9106 json_writer_indent_pop (&writer);
9107 json_writer_indent (&writer);
9108 json_writer_array_end (&writer);
9109 json_writer_printf (&writer, ",\n");
9114 json_writer_indent_push (&writer);
9115 json_writer_indent (&writer);
9116 json_writer_object_key(&writer, "got");
9117 json_writer_array_begin (&writer);
9119 json_writer_indent_push (&writer);
9120 for (i = 0; i < acfg->got_info.got_patches->len; ++i) {
9121 MonoJumpInfo *ji = g_ptr_array_index (acfg->got_info.got_patches, i);
9123 json_writer_indent (&writer);
9124 json_writer_printf (&writer, "{ ");
9125 json_writer_object_key(&writer, "patch_name");
9126 json_writer_printf (&writer, "\"%s\" },\n", get_patch_name (ji->type));
9129 json_writer_indent_pop (&writer);
9130 json_writer_indent (&writer);
9131 json_writer_array_end (&writer);
9132 json_writer_printf (&writer, ",\n");
9135 json_writer_indent_pop (&writer);
9136 json_writer_indent (&writer);
9137 json_writer_object_end (&writer);
9139 dumpname = g_strdup_printf ("%s.json", g_path_get_basename (acfg->image->name));
9140 dumpfile = fopen (dumpname, "w+");
9143 fprintf (dumpfile, "%s", writer.text->str);
9146 json_writer_destroy (&writer);
9150 mono_compile_assembly (MonoAssembly *ass, guint32 opts, const char *aot_options)
9152 MonoImage *image = ass->image;
9153 int i, res, all_sizes;
9154 MonoAotCompile *acfg;
9155 char *outfile_name, *tmp_outfile_name, *p;
9156 char llvm_stats_msg [256];
9160 acfg = acfg_create (ass, opts);
9162 memset (&acfg->aot_opts, 0, sizeof (acfg->aot_opts));
9163 acfg->aot_opts.write_symbols = TRUE;
9164 acfg->aot_opts.ntrampolines = 1024;
9165 acfg->aot_opts.nrgctx_trampolines = 1024;
9166 acfg->aot_opts.nimt_trampolines = 128;
9167 acfg->aot_opts.nrgctx_fetch_trampolines = 128;
9168 acfg->aot_opts.ngsharedvt_arg_trampolines = 128;
9169 acfg->aot_opts.llvm_path = g_strdup ("");
9171 acfg->aot_opts.use_trampolines_page = TRUE;
9174 mono_aot_parse_options (aot_options, &acfg->aot_opts);
9176 if (acfg->aot_opts.logfile) {
9177 acfg->logfile = fopen (acfg->aot_opts.logfile, "a+");
9180 if (acfg->aot_opts.static_link)
9181 acfg->aot_opts.autoreg = TRUE;
9183 //acfg->aot_opts.print_skipped_methods = TRUE;
9185 #if !defined(MONO_ARCH_GSHAREDVT_SUPPORTED) || !defined(ENABLE_GSHAREDVT)
9186 if (opts & MONO_OPT_GSHAREDVT) {
9187 aot_printerrf (acfg, "-O=gsharedvt not supported on this platform.\n");
9192 aot_printf (acfg, "Mono Ahead of Time compiler - compiling assembly %s\n", image->name);
9194 #ifndef MONO_ARCH_HAVE_FULL_AOT_TRAMPOLINES
9195 if (acfg->aot_opts.full_aot) {
9196 aot_printerrf (acfg, "--aot=full is not supported on this platform.\n");
9201 if (acfg->aot_opts.direct_pinvoke && !acfg->aot_opts.static_link) {
9202 aot_printerrf (acfg, "The 'direct-pinvoke' AOT option also requires the 'static' AOT option.\n");
9206 if (acfg->aot_opts.static_link)
9207 acfg->aot_opts.asm_writer = TRUE;
9209 if (acfg->aot_opts.soft_debug) {
9210 MonoDebugOptions *opt = mini_get_debug_options ();
9212 opt->mdb_optimizations = TRUE;
9213 opt->gen_seq_points_debug_data = TRUE;
9215 if (!mono_debug_enabled ()) {
9216 aot_printerrf (acfg, "The soft-debug AOT option requires the --debug option.\n");
9219 acfg->flags |= MONO_AOT_FILE_FLAG_DEBUG;
9222 if (mono_use_llvm || acfg->aot_opts.llvm) {
9224 acfg->aot_opts.asm_writer = TRUE;
9225 acfg->flags |= MONO_AOT_FILE_FLAG_WITH_LLVM;
9227 if (acfg->aot_opts.soft_debug) {
9228 aot_printerrf (acfg, "The 'soft-debug' option is not supported when compiling with LLVM.\n");
9234 if (!acfg->aot_opts.asm_only || acfg->aot_opts.llvm_outfile) {
9236 * Emit all LLVM code into a separate assembly/object file and link with it
9239 #if LLVM_API_VERSION >= 3
9240 acfg->llvm_separate = TRUE;
9241 if (!acfg->aot_opts.asm_only)
9242 acfg->llvm_owriter = TRUE;
9245 if (acfg->aot_opts.llvm_outfile && !acfg->llvm_separate) {
9246 aot_printerrf (acfg, "The llvm-outputfile= option is not supported on this platform.\n");
9251 if (acfg->aot_opts.full_aot)
9252 acfg->flags |= MONO_AOT_FILE_FLAG_FULL_AOT;
9254 if (acfg->aot_opts.instances_logfile_path) {
9255 acfg->instances_logfile = fopen (acfg->aot_opts.instances_logfile_path, "w");
9256 if (!acfg->instances_logfile) {
9257 aot_printerrf (acfg, "Unable to create logfile: '%s'.\n", acfg->aot_opts.instances_logfile_path);
9262 load_profile_files (acfg);
9264 acfg->num_trampolines [MONO_AOT_TRAMP_SPECIFIC] = acfg->aot_opts.full_aot ? acfg->aot_opts.ntrampolines : 0;
9265 #ifdef MONO_ARCH_GSHARED_SUPPORTED
9266 acfg->num_trampolines [MONO_AOT_TRAMP_STATIC_RGCTX] = acfg->aot_opts.full_aot ? acfg->aot_opts.nrgctx_trampolines : 0;
9268 acfg->num_trampolines [MONO_AOT_TRAMP_IMT_THUNK] = acfg->aot_opts.full_aot ? acfg->aot_opts.nimt_trampolines : 0;
9269 #ifdef MONO_ARCH_GSHAREDVT_SUPPORTED
9270 if (acfg->opts & MONO_OPT_GSHAREDVT)
9271 acfg->num_trampolines [MONO_AOT_TRAMP_GSHAREDVT_ARG] = acfg->aot_opts.full_aot ? acfg->aot_opts.ngsharedvt_arg_trampolines : 0;
9274 acfg->temp_prefix = img_writer_get_temp_label_prefix (NULL);
9278 acfg->assembly_name_sym = g_strdup (acfg->image->assembly->aname.name);
9279 /* Get rid of characters which cannot occur in symbols */
9280 for (p = acfg->assembly_name_sym; *p; ++p) {
9281 if (!(isalnum (*p) || *p == '_'))
9285 acfg->got_symbol_base = g_strdup_printf ("mono_aot_%s_got", acfg->assembly_name_sym);
9286 acfg->llvm_got_symbol_base = g_strdup_printf ("mono_aot_%s_llvm_got", acfg->assembly_name_sym);
9287 acfg->plt_symbol = g_strdup_printf ("%smono_aot_%s_plt", acfg->llvm_label_prefix, acfg->assembly_name_sym);
9289 acfg->got_symbol = g_strdup_printf ("%s%s", acfg->llvm_label_prefix, acfg->got_symbol_base);
9291 acfg->llvm_got_symbol = g_strdup_printf ("%s%s", acfg->llvm_label_prefix, acfg->llvm_got_symbol_base);
9292 if (acfg->llvm_separate)
9293 acfg->llvm_eh_frame_symbol = g_strdup_printf ("mono_aot_%s_eh_frame", acfg->assembly_name_sym);
9295 acfg->llvm_eh_frame_symbol = g_strdup ("mono_eh_frame");
9298 acfg->method_index = 1;
9302 if (acfg->aot_opts.full_aot)
9303 mono_set_partial_sharing_supported (TRUE);
9306 mono_set_partial_sharing_supported (FALSE);
9308 res = collect_methods (acfg);
9312 acfg->cfgs_size = acfg->methods->len + 32;
9313 acfg->cfgs = g_new0 (MonoCompile*, acfg->cfgs_size);
9315 /* PLT offset 0 is reserved for the PLT trampoline */
9316 acfg->plt_offset = 1;
9321 mono_llvm_create_aot_module (acfg->llvm_got_symbol_base, acfg->llvm_separate, acfg->llvm_separate);
9325 /* GOT offset 0 is reserved for the address of the current assembly */
9329 ji = mono_mempool_alloc0 (acfg->mempool, sizeof (MonoJumpInfo));
9330 ji->type = MONO_PATCH_INFO_IMAGE;
9331 ji->data.image = acfg->image;
9333 get_got_offset (acfg, FALSE, ji);
9334 get_got_offset (acfg, TRUE, ji);
9336 /* Slot 1 is reserved for the mscorlib got addr */
9337 ji = mono_mempool_alloc0 (acfg->mempool, sizeof (MonoJumpInfo));
9338 ji->type = MONO_PATCH_INFO_MSCORLIB_GOT_ADDR;
9339 get_got_offset (acfg, FALSE, ji);
9340 get_got_offset (acfg, TRUE, ji);
9342 /* This is very common */
9343 ji = mono_mempool_alloc0 (acfg->mempool, sizeof (MonoJumpInfo));
9344 ji->type = MONO_PATCH_INFO_GC_CARD_TABLE_ADDR;
9345 get_got_offset (acfg, FALSE, ji);
9346 get_got_offset (acfg, TRUE, ji);
9348 ji = mono_mempool_alloc0 (acfg->mempool, sizeof (MonoJumpInfo));
9349 ji->type = MONO_PATCH_INFO_JIT_TLS_ID;
9350 get_got_offset (acfg, FALSE, ji);
9351 get_got_offset (acfg, TRUE, ji);
9356 compile_methods (acfg);
9360 acfg->stats.jit_time = TV_ELAPSED (atv, btv);
9368 if (acfg->aot_opts.asm_only) {
9369 if (acfg->aot_opts.outfile) {
9370 acfg->tmpfname = g_strdup_printf ("%s", acfg->aot_opts.outfile);
9371 acfg->tmpbasename = g_strdup (acfg->tmpfname);
9373 acfg->tmpbasename = g_strdup_printf ("%s", acfg->image->name);
9374 acfg->tmpfname = g_strdup_printf ("%s.s", acfg->tmpbasename);
9376 if (acfg->llvm_separate) {
9377 g_assert (acfg->aot_opts.llvm_outfile);
9378 acfg->llvm_sfile = g_strdup (acfg->aot_opts.llvm_outfile);
9381 acfg->tmpbasename = g_strdup_printf ("%s", "temp");
9382 acfg->tmpfname = g_strdup_printf ("%s.s", acfg->tmpbasename);
9383 acfg->llvm_sfile = g_strdup ("temp-llvm.s");
9384 acfg->llvm_ofile = g_strdup ("temp-llvm.o");
9387 res = emit_llvm_file (acfg);
9393 if (!acfg->aot_opts.asm_only && !acfg->aot_opts.asm_writer && bin_writer_supported ()) {
9394 if (acfg->aot_opts.outfile)
9395 outfile_name = g_strdup_printf ("%s", acfg->aot_opts.outfile);
9397 outfile_name = g_strdup_printf ("%s%s", acfg->image->name, MONO_SOLIB_EXT);
9400 * Can't use g_file_open_tmp () as it will be deleted at exit, and
9401 * it might be in another file system so the rename () won't work.
9403 tmp_outfile_name = g_strdup_printf ("%s.tmp", outfile_name);
9405 acfg->fp = fopen (tmp_outfile_name, "w");
9407 aot_printf (acfg, "Unable to create temporary file '%s': %s\n", tmp_outfile_name, strerror (errno));
9411 acfg->w = img_writer_create (acfg->fp, TRUE);
9412 acfg->use_bin_writer = TRUE;
9414 if (acfg->llvm && !acfg->llvm_separate) {
9415 /* Append to the .s file created by llvm */
9416 /* FIXME: Use multiple files instead */
9417 acfg->fp = fopen (acfg->tmpfname, "a+");
9419 if (acfg->aot_opts.asm_only) {
9420 if (acfg->aot_opts.outfile)
9421 acfg->tmpfname = g_strdup_printf ("%s", acfg->aot_opts.outfile);
9423 acfg->tmpfname = g_strdup_printf ("%s.s", acfg->image->name);
9424 acfg->fp = fopen (acfg->tmpfname, "w+");
9426 int i = g_file_open_tmp ("mono_aot_XXXXXX", &acfg->tmpfname, NULL);
9427 acfg->fp = fdopen (i, "w+");
9430 if (acfg->fp == 0) {
9431 aot_printerrf (acfg, "Unable to open file '%s': %s\n", acfg->tmpfname, strerror (errno));
9434 acfg->w = img_writer_create (acfg->fp, FALSE);
9436 tmp_outfile_name = NULL;
9437 outfile_name = NULL;
9440 /* Compute symbols for methods */
9441 for (i = 0; i < acfg->nmethods; ++i) {
9442 if (acfg->cfgs [i]) {
9443 MonoCompile *cfg = acfg->cfgs [i];
9444 int method_index = get_method_index (acfg, cfg->orig_method);
9446 if (COMPILE_LLVM (cfg))
9447 cfg->asm_symbol = g_strdup_printf ("%s%s", acfg->llvm_label_prefix, cfg->llvm_method_name);
9448 else if (acfg->global_symbols || acfg->llvm_separate)
9449 cfg->asm_symbol = get_debug_sym (cfg->orig_method, "", acfg->method_label_hash);
9451 cfg->asm_symbol = g_strdup_printf ("%s%sm_%x", acfg->temp_prefix, acfg->llvm_label_prefix, method_index);
9452 cfg->asm_debug_symbol = cfg->asm_symbol;
9456 if (acfg->aot_opts.dwarf_debug && acfg->aot_opts.asm_only && acfg->aot_opts.gnu_asm) {
9458 * CLANG supports GAS .file/.loc directives, so emit line number information this way
9459 * FIXME: CLANG only emits line number info for .loc directives followed by assembly, not
9462 //acfg->gas_line_numbers = TRUE;
9465 if (!acfg->aot_opts.nodebug || acfg->aot_opts.dwarf_debug) {
9466 if (acfg->aot_opts.dwarf_debug && !mono_debug_enabled ()) {
9467 aot_printerrf (acfg, "The dwarf AOT option requires the --debug option.\n");
9470 acfg->dwarf = mono_dwarf_writer_create (acfg->w, NULL, 0, FALSE, !acfg->gas_line_numbers);
9473 img_writer_emit_start (acfg->w);
9476 mono_dwarf_writer_emit_base_info (acfg->dwarf, g_path_get_basename (acfg->image->name), mono_unwind_get_cie_program ());
9478 if (acfg->thumb_mixed) {
9481 * This global symbol marks the end of THUMB code, and the beginning of ARM
9482 * code generated by our JIT.
9484 sprintf (symbol, "thumb_end");
9485 emit_section_change (acfg, ".text", 0);
9486 emit_alignment_code (acfg, 8);
9487 emit_label (acfg, symbol);
9488 emit_zero_bytes (acfg, 16);
9490 fprintf (acfg->fp, ".arm\n");
9497 emit_extra_methods (acfg);
9499 emit_trampolines (acfg);
9501 emit_class_name_table (acfg);
9503 emit_got_info (acfg, FALSE);
9505 emit_got_info (acfg, TRUE);
9507 emit_exception_info (acfg);
9509 emit_unwind_info (acfg);
9511 emit_class_info (acfg);
9515 emit_image_table (acfg);
9519 emit_file_info (acfg);
9523 emit_objc_selectors (acfg);
9525 emit_globals (acfg);
9527 emit_autoreg (acfg);
9530 emit_dwarf_info (acfg);
9531 mono_dwarf_writer_close (acfg->dwarf);
9534 emit_mem_end (acfg);
9536 if (acfg->need_pt_gnu_stack) {
9537 /* This is required so the .so doesn't have an executable stack */
9538 /* The bin writer already emits this */
9539 if (!acfg->use_bin_writer)
9540 fprintf (acfg->fp, "\n.section .note.GNU-stack,\"\",@progbits\n");
9545 acfg->stats.gen_time = TV_ELAPSED (atv, btv);
9548 sprintf (llvm_stats_msg, ", LLVM: %d (%d%%)", acfg->stats.llvm_count, acfg->stats.mcount ? (acfg->stats.llvm_count * 100) / acfg->stats.mcount : 100);
9550 strcpy (llvm_stats_msg, "");
9552 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;
9554 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",
9555 acfg->stats.code_size, acfg->stats.code_size * 100 / all_sizes,
9556 acfg->stats.info_size, acfg->stats.info_size * 100 / all_sizes,
9557 acfg->stats.ex_info_size, acfg->stats.ex_info_size * 100 / all_sizes,
9558 acfg->stats.unwind_info_size, acfg->stats.unwind_info_size * 100 / all_sizes,
9559 acfg->stats.class_info_size, acfg->stats.class_info_size * 100 / all_sizes,
9560 acfg->stats.plt_size ? acfg->stats.plt_size : acfg->plt_offset, acfg->stats.plt_size ? acfg->stats.plt_size * 100 / all_sizes : 0,
9561 acfg->stats.got_info_size, acfg->stats.got_info_size * 100 / all_sizes,
9562 acfg->stats.offsets_size, acfg->stats.offsets_size * 100 / all_sizes,
9563 (int)(acfg->got_offset * sizeof (gpointer)));
9564 aot_printf (acfg, "Compiled: %d/%d (%d%%)%s, No GOT slots: %d (%d%%), Direct calls: %d (%d%%)\n",
9565 acfg->stats.ccount, acfg->stats.mcount, acfg->stats.mcount ? (acfg->stats.ccount * 100) / acfg->stats.mcount : 100,
9567 acfg->stats.methods_without_got_slots, acfg->stats.mcount ? (acfg->stats.methods_without_got_slots * 100) / acfg->stats.mcount : 100,
9568 acfg->stats.direct_calls, acfg->stats.all_calls ? (acfg->stats.direct_calls * 100) / acfg->stats.all_calls : 100);
9569 if (acfg->stats.genericcount)
9570 aot_printf (acfg, "%d methods are generic (%d%%)\n", acfg->stats.genericcount, acfg->stats.mcount ? (acfg->stats.genericcount * 100) / acfg->stats.mcount : 100);
9571 if (acfg->stats.abscount)
9572 aot_printf (acfg, "%d methods contain absolute addresses (%d%%)\n", acfg->stats.abscount, acfg->stats.mcount ? (acfg->stats.abscount * 100) / acfg->stats.mcount : 100);
9573 if (acfg->stats.lmfcount)
9574 aot_printf (acfg, "%d methods contain lmf pointers (%d%%)\n", acfg->stats.lmfcount, acfg->stats.mcount ? (acfg->stats.lmfcount * 100) / acfg->stats.mcount : 100);
9575 if (acfg->stats.ocount)
9576 aot_printf (acfg, "%d methods have other problems (%d%%)\n", acfg->stats.ocount, acfg->stats.mcount ? (acfg->stats.ocount * 100) / acfg->stats.mcount : 100);
9579 res = img_writer_emit_writeout (acfg->w);
9584 if (acfg->use_bin_writer) {
9585 int err = rename (tmp_outfile_name, outfile_name);
9588 aot_printf (acfg, "Unable to rename '%s' to '%s': %s\n", tmp_outfile_name, outfile_name, strerror (errno));
9592 res = compile_asm (acfg);
9599 acfg->stats.link_time = TV_ELAPSED (atv, btv);
9601 if (acfg->aot_opts.stats) {
9604 aot_printf (acfg, "GOT slot distribution:\n");
9605 for (i = 0; i < MONO_PATCH_INFO_NONE; ++i)
9606 if (acfg->stats.got_slot_types [i])
9607 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]);
9610 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);
9612 if (acfg->aot_opts.dump_json)
9625 mono_aot_readonly_field_override (MonoClassField *field)
9631 mono_compile_assembly (MonoAssembly *ass, guint32 opts, const char *aot_options)