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 direct_pinvoke;
113 gboolean direct_icalls;
114 gboolean no_direct_calls;
115 gboolean use_trampolines_page;
116 gboolean no_instances;
121 int nrgctx_trampolines;
122 int nimt_trampolines;
123 int ngsharedvt_arg_trampolines;
124 int nrgctx_fetch_trampolines;
125 gboolean print_skipped_methods;
132 char *instances_logfile_path;
137 typedef struct MonoAotStats {
138 int ccount, mcount, lmfcount, abscount, gcount, ocount, genericcount;
139 int code_size, info_size, ex_info_size, unwind_info_size, got_size, class_info_size, got_info_size, plt_size;
140 int methods_without_got_slots, direct_calls, all_calls, llvm_count;
141 int got_slots, offsets_size;
142 int got_slot_types [MONO_PATCH_INFO_NONE];
143 int got_slot_info_sizes [MONO_PATCH_INFO_NONE];
144 int jit_time, gen_time, link_time;
147 typedef struct GotInfo {
148 GHashTable *patch_to_got_offset;
149 GHashTable **patch_to_got_offset_by_type;
150 GPtrArray *got_patches;
153 typedef struct MonoAotCompile {
156 GHashTable *method_indexes;
157 GHashTable *method_depth;
160 GHashTable **patch_to_plt_entry;
161 GHashTable *plt_offset_to_entry;
162 //GHashTable *patch_to_got_offset;
163 //GHashTable **patch_to_got_offset_by_type;
164 //GPtrArray *got_patches;
165 GotInfo got_info, llvm_got_info;
166 GHashTable *image_hash;
167 GHashTable *method_to_cfg;
168 GHashTable *token_info_hash;
169 GHashTable *method_to_pinvoke_import;
170 GPtrArray *extra_methods;
171 GPtrArray *image_table;
173 GPtrArray *method_order;
174 GHashTable *export_names;
175 /* Maps MonoClass* -> blob offset */
176 GHashTable *klass_blob_hash;
177 /* Maps MonoMethod* -> blob offset */
178 GHashTable *method_blob_hash;
179 guint32 *plt_got_info_offsets;
180 guint32 got_offset, llvm_got_offset, plt_offset, plt_got_offset_base;
181 /* Number of GOT entries reserved for trampolines */
182 guint32 num_trampoline_got_entries;
183 guint32 tramp_page_size;
185 guint32 num_trampolines [MONO_AOT_TRAMP_NUM];
186 guint32 trampoline_got_offset_base [MONO_AOT_TRAMP_NUM];
187 guint32 trampoline_size [MONO_AOT_TRAMP_NUM];
188 guint32 tramp_page_code_offsets [MONO_AOT_TRAMP_NUM];
190 MonoAotOptions aot_opts;
194 MonoMemPool *mempool;
197 char *static_linking_symbol;
199 gboolean use_bin_writer;
200 gboolean gas_line_numbers;
201 /* Whenever to emit LLVM code into a separate object file */
202 gboolean llvm_separate;
203 /* Whenever to emit an object file directly from llc */
204 gboolean llvm_owriter;
206 MonoDwarfWriter *dwarf;
213 GHashTable *unwind_info_offsets;
214 GPtrArray *unwind_ops;
215 guint32 unwind_info_offset;
216 char *got_symbol_base;
217 char *llvm_got_symbol_base;
219 char *llvm_got_symbol;
221 char *methods_symbol;
222 char *llvm_eh_frame_symbol;
223 GHashTable *method_label_hash;
224 const char *temp_prefix;
225 const char *user_symbol_prefix;
226 const char *llvm_label_prefix;
227 const char *inst_directive;
229 guint32 label_generator;
231 MonoAotFileFlags flags;
232 MonoDynamicStream blob;
233 MonoClass **typespec_classes;
236 char *assembly_name_sym;
237 GHashTable *plt_entry_debug_sym_cache;
238 gboolean thumb_mixed, need_no_dead_strip, need_pt_gnu_stack;
239 GHashTable *ginst_hash;
240 GHashTable *dwarf_ln_filenames;
241 gboolean global_symbols;
242 int objc_selector_index, objc_selector_index_2;
243 GPtrArray *objc_selectors;
244 GHashTable *objc_selector_to_index;
246 FILE *instances_logfile;
251 char *symbol, *llvm_symbol, *debug_sym;
253 gboolean jit_used, llvm_used;
256 #define mono_acfg_lock(acfg) mono_mutex_lock (&((acfg)->mutex))
257 #define mono_acfg_unlock(acfg) mono_mutex_unlock (&((acfg)->mutex))
259 /* This points to the current acfg in LLVM mode */
260 static MonoAotCompile *llvm_acfg;
262 #ifdef HAVE_ARRAY_ELEM_INIT
263 #define MSGSTRFIELD(line) MSGSTRFIELD1(line)
264 #define MSGSTRFIELD1(line) str##line
265 static const struct msgstr_t {
266 #define PATCH_INFO(a,b) char MSGSTRFIELD(__LINE__) [sizeof (b)];
267 #include "patch-info.h"
270 #define PATCH_INFO(a,b) b,
271 #include "patch-info.h"
274 static const gint16 opidx [] = {
275 #define PATCH_INFO(a,b) [MONO_PATCH_INFO_ ## a] = offsetof (struct msgstr_t, MSGSTRFIELD(__LINE__)),
276 #include "patch-info.h"
280 static G_GNUC_UNUSED const char*
281 get_patch_name (int info)
283 return (const char*)&opstr + opidx [info];
287 #define PATCH_INFO(a,b) b,
288 static const char* const
289 patch_types [MONO_PATCH_INFO_NUM + 1] = {
290 #include "patch-info.h"
294 static G_GNUC_UNUSED const char*
295 get_patch_name (int info)
297 return patch_types [info];
303 get_plt_entry_debug_sym (MonoAotCompile *acfg, MonoJumpInfo *ji, GHashTable *cache);
306 aot_printf (MonoAotCompile *acfg, const gchar *format, ...)
312 output = acfg->logfile;
316 va_start (args, format);
317 vfprintf (output, format, args);
322 aot_printerrf (MonoAotCompile *acfg, const gchar *format, ...)
328 output = acfg->logfile;
332 va_start (args, format);
333 vfprintf (output, format, args);
337 /* Wrappers around the image writer functions */
340 emit_section_change (MonoAotCompile *acfg, const char *section_name, int subsection_index)
342 img_writer_emit_section_change (acfg->w, section_name, subsection_index);
346 emit_push_section (MonoAotCompile *acfg, const char *section_name, int subsection)
348 img_writer_emit_push_section (acfg->w, section_name, subsection);
352 emit_pop_section (MonoAotCompile *acfg)
354 img_writer_emit_pop_section (acfg->w);
358 emit_local_symbol (MonoAotCompile *acfg, const char *name, const char *end_label, gboolean func)
360 img_writer_emit_local_symbol (acfg->w, name, end_label, func);
364 emit_label (MonoAotCompile *acfg, const char *name)
366 img_writer_emit_label (acfg->w, name);
370 emit_bytes (MonoAotCompile *acfg, const guint8* buf, int size)
372 img_writer_emit_bytes (acfg->w, buf, size);
376 emit_string (MonoAotCompile *acfg, const char *value)
378 img_writer_emit_string (acfg->w, value);
382 emit_line (MonoAotCompile *acfg)
384 img_writer_emit_line (acfg->w);
388 emit_alignment (MonoAotCompile *acfg, int size)
390 img_writer_emit_alignment (acfg->w, size);
394 emit_alignment_code (MonoAotCompile *acfg, int size)
396 if (acfg->align_pad_value)
397 img_writer_emit_alignment_fill (acfg->w, size, acfg->align_pad_value);
399 img_writer_emit_alignment (acfg->w, size);
403 emit_padding (MonoAotCompile *acfg, int size)
408 if (acfg->align_pad_value) {
409 for (i = 0; i < 16; ++i)
410 buf [i] = acfg->align_pad_value;
412 memset (buf, 0, sizeof (buf));
415 for (i = 0; i < size; i += 16) {
417 emit_bytes (acfg, buf, size - i);
419 emit_bytes (acfg, buf, 16);
424 emit_pointer_unaligned (MonoAotCompile *acfg, const char *target)
426 img_writer_emit_pointer_unaligned (acfg->w, target);
430 emit_pointer (MonoAotCompile *acfg, const char *target)
432 img_writer_emit_pointer (acfg->w, target);
436 emit_pointer_2 (MonoAotCompile *acfg, const char *prefix, const char *target)
438 if (prefix [0] != '\0') {
439 char *s = g_strdup_printf ("%s%s", prefix, target);
440 img_writer_emit_pointer (acfg->w, s);
443 img_writer_emit_pointer (acfg->w, target);
448 emit_int16 (MonoAotCompile *acfg, int value)
450 img_writer_emit_int16 (acfg->w, value);
454 emit_int32 (MonoAotCompile *acfg, int value)
456 img_writer_emit_int32 (acfg->w, value);
460 emit_symbol_diff (MonoAotCompile *acfg, const char *end, const char* start, int offset)
462 img_writer_emit_symbol_diff (acfg->w, end, start, offset);
466 emit_zero_bytes (MonoAotCompile *acfg, int num)
468 img_writer_emit_zero_bytes (acfg->w, num);
472 emit_byte (MonoAotCompile *acfg, guint8 val)
474 img_writer_emit_byte (acfg->w, val);
477 #ifdef __native_client_codegen__
479 emit_nacl_call_alignment (MonoAotCompile *acfg)
481 img_writer_emit_nacl_call_alignment (acfg->w);
485 static G_GNUC_UNUSED void
486 emit_global_inner (MonoAotCompile *acfg, const char *name, gboolean func)
488 img_writer_emit_global (acfg->w, name, func);
492 emit_global (MonoAotCompile *acfg, const char *name, gboolean func)
494 if (acfg->aot_opts.no_dlsym) {
495 g_ptr_array_add (acfg->globals, g_strdup (name));
496 img_writer_emit_local_symbol (acfg->w, name, NULL, func);
498 img_writer_emit_global (acfg->w, name, func);
503 emit_symbol_size (MonoAotCompile *acfg, const char *name, const char *end_label)
505 img_writer_emit_symbol_size (acfg->w, name, end_label);
509 emit_string_symbol (MonoAotCompile *acfg, const char *name, const char *value)
511 img_writer_emit_section_change (acfg->w, RODATA_SECT, 1);
513 /* On apple, all symbols need to be aligned to avoid warnings from ld */
514 emit_alignment (acfg, 4);
516 img_writer_emit_label (acfg->w, name);
517 img_writer_emit_string (acfg->w, value);
520 static G_GNUC_UNUSED void
521 emit_uleb128 (MonoAotCompile *acfg, guint32 value)
524 guint8 b = value & 0x7f;
526 if (value != 0) /* more bytes to come */
532 static G_GNUC_UNUSED void
533 emit_sleb128 (MonoAotCompile *acfg, gint64 value)
536 gboolean negative = (value < 0);
543 /* the following is unnecessary if the
544 * implementation of >>= uses an arithmetic rather
545 * than logical shift for a signed left operand
549 value |= - ((gint64)1 <<(size - 7));
550 /* sign bit of byte is second high order bit (0x40) */
551 if ((value == 0 && !(byte & 0x40)) ||
552 (value == -1 && (byte & 0x40)))
556 emit_byte (acfg, byte);
560 static G_GNUC_UNUSED void
561 encode_uleb128 (guint32 value, guint8 *buf, guint8 **endbuf)
566 guint8 b = value & 0x7f;
568 if (value != 0) /* more bytes to come */
576 static G_GNUC_UNUSED void
577 encode_sleb128 (gint32 value, guint8 *buf, guint8 **endbuf)
580 gboolean negative = (value < 0);
588 /* the following is unnecessary if the
589 * implementation of >>= uses an arithmetic rather
590 * than logical shift for a signed left operand
594 value |= - (1 <<(size - 7));
595 /* sign bit of byte is second high order bit (0x40) */
596 if ((value == 0 && !(byte & 0x40)) ||
597 (value == -1 && (byte & 0x40)))
608 emit_unset_mode (MonoAotCompile *acfg)
610 img_writer_emit_unset_mode (acfg->w);
613 static G_GNUC_UNUSED void
614 emit_set_thumb_mode (MonoAotCompile *acfg)
616 emit_unset_mode (acfg);
617 fprintf (acfg->fp, ".code 16\n");
620 static G_GNUC_UNUSED void
621 emit_set_arm_mode (MonoAotCompile *acfg)
623 emit_unset_mode (acfg);
624 fprintf (acfg->fp, ".code 32\n");
628 emit_code_bytes (MonoAotCompile *acfg, const guint8* buf, int size)
633 g_assert (size % 4 == 0);
634 emit_unset_mode (acfg);
635 for (i = 0; i < size; i += 4)
636 fprintf (acfg->fp, "%s 0x%x\n", acfg->inst_directive, *(guint32*)(buf + i));
638 emit_bytes (acfg, buf, size);
642 /* ARCHITECTURE SPECIFIC CODE */
644 #if defined(TARGET_X86) || defined(TARGET_AMD64) || defined(TARGET_ARM) || defined(TARGET_POWERPC) || defined(TARGET_ARM64)
645 #define EMIT_DWARF_INFO 1
648 #if defined(TARGET_ARM)
649 #define AOT_FUNC_ALIGNMENT 4
651 #define AOT_FUNC_ALIGNMENT 16
653 #if (defined(TARGET_X86) || defined(TARGET_AMD64)) && defined(__native_client_codegen__)
654 #undef AOT_FUNC_ALIGNMENT
655 #define AOT_FUNC_ALIGNMENT 32
658 #if defined(TARGET_POWERPC64) && !defined(__mono_ilp32__)
659 #define PPC_LD_OP "ld"
660 #define PPC_LDX_OP "ldx"
662 #define PPC_LD_OP "lwz"
663 #define PPC_LDX_OP "lwzx"
667 #define AOT_TARGET_STR "AMD64"
672 #define AOT_TARGET_STR "ARM (MACH)"
674 #define AOT_TARGET_STR "ARM (!MACH)"
680 #define AOT_TARGET_STR "ARM64 (MACH)"
682 #define AOT_TARGET_STR "ARM64 (!MACH)"
686 #ifdef TARGET_POWERPC64
687 #ifdef __mono_ilp32__
688 #define AOT_TARGET_STR "POWERPC64 (mono ilp32)"
690 #define AOT_TARGET_STR "POWERPC64 (!mono ilp32)"
693 #ifdef TARGET_POWERPC
694 #ifdef __mono_ilp32__
695 #define AOT_TARGET_STR "POWERPC (mono ilp32)"
697 #define AOT_TARGET_STR "POWERPC (!mono ilp32)"
704 #define AOT_TARGET_STR "X86 (WIN32)"
705 #elif defined(__native_client_codegen__)
706 #define AOT_TARGET_STR "X86 (native client codegen)"
708 #define AOT_TARGET_STR "X86 (!native client codegen)"
712 #ifndef AOT_TARGET_STR
713 #define AOT_TARGET_STR ""
717 arch_init (MonoAotCompile *acfg)
719 acfg->llc_args = g_string_new ("");
720 acfg->as_args = g_string_new ("");
723 * The prefix LLVM likes to put in front of symbol names on darwin.
724 * The mach-os specs require this for globals, but LLVM puts them in front of all
725 * symbols. We need to handle this, since we need to refer to LLVM generated
728 acfg->llvm_label_prefix = "";
729 acfg->user_symbol_prefix = "";
731 #if defined(TARGET_X86)
732 g_string_append (acfg->llc_args, " -march=x86 -mattr=sse4.1");
735 #if defined(TARGET_AMD64)
736 g_string_append (acfg->llc_args, " -march=x86-64 -mattr=sse4.1");
738 acfg->align_pad_value = 0x90;
742 if (acfg->aot_opts.mtriple && strstr (acfg->aot_opts.mtriple, "darwin")) {
743 g_string_append (acfg->llc_args, "-mattr=+v6");
746 g_string_append (acfg->llc_args, " -mattr=+vfp2,-neon,+d16");
747 g_string_append (acfg->as_args, " -mfpu=vfp3");
749 g_string_append (acfg->llc_args, " -soft-float");
752 if (acfg->aot_opts.mtriple && strstr (acfg->aot_opts.mtriple, "thumb"))
753 acfg->thumb_mixed = TRUE;
755 if (acfg->aot_opts.mtriple)
756 mono_arch_set_target (acfg->aot_opts.mtriple);
760 acfg->inst_directive = ".inst";
761 if (acfg->aot_opts.mtriple)
762 mono_arch_set_target (acfg->aot_opts.mtriple);
766 acfg->user_symbol_prefix = "_";
767 acfg->llvm_label_prefix = "_";
768 acfg->inst_directive = ".word";
769 acfg->need_no_dead_strip = TRUE;
770 acfg->aot_opts.gnu_asm = TRUE;
773 #if defined(__linux__) && !defined(TARGET_ARM)
774 acfg->need_pt_gnu_stack = TRUE;
778 acfg->global_symbols = TRUE;
784 #include "../../../mono-extensions/mono/mini/aot-compiler-arm64.c"
788 #ifdef MONO_ARCH_AOT_SUPPORTED
790 * arch_emit_direct_call:
792 * Emit a direct call to the symbol TARGET. CALL_SIZE is set to the size of the
796 arch_emit_direct_call (MonoAotCompile *acfg, const char *target, gboolean external, gboolean thumb, MonoJumpInfo *ji, int *call_size)
798 #if defined(TARGET_X86) || defined(TARGET_AMD64)
799 /* Need to make sure this is exactly 5 bytes long */
800 if (!acfg->use_bin_writer) {
801 emit_unset_mode (acfg);
802 fprintf (acfg->fp, "call %s\n", target);
804 emit_byte (acfg, '\xe8');
805 emit_symbol_diff (acfg, target, ".", -4);
808 #elif defined(TARGET_ARM)
809 if (acfg->use_bin_writer) {
816 img_writer_emit_reloc (acfg->w, R_ARM_CALL, target, -8);
817 emit_bytes (acfg, buf, 4);
819 emit_unset_mode (acfg);
821 fprintf (acfg->fp, "blx %s\n", target);
823 fprintf (acfg->fp, "bl %s\n", target);
826 #elif defined(TARGET_ARM64)
827 arm64_emit_direct_call (acfg, target, external, thumb, ji, call_size);
828 #elif defined(TARGET_POWERPC)
829 if (acfg->use_bin_writer) {
830 g_assert_not_reached ();
832 emit_unset_mode (acfg);
833 fprintf (acfg->fp, "bl %s\n", target);
837 g_assert_not_reached ();
844 * - we use an approach similar to the x86 abi: reserve a register (r30) to hold
846 * - The full-aot trampolines need access to the GOT of mscorlib, so we store
847 * in in the 2. slot of every GOT, and require every method to place the GOT
848 * address in r30, even when it doesn't access the GOT otherwise. This way,
849 * the trampolines can compute the mscorlib GOT address by loading 4(r30).
854 * PPC64 uses function descriptors which greatly complicate all code, since
855 * these are used very inconsistently in the runtime. Some functions like
856 * mono_compile_method () return ftn descriptors, while others like the
857 * trampoline creation functions do not.
858 * We assume that all GOT slots contain function descriptors, and create
859 * descriptors in aot-runtime.c when needed.
860 * The ppc64 abi uses r2 to hold the address of the TOC/GOT, which is loaded
861 * from function descriptors, we could do the same, but it would require
862 * rewriting all the ppc/aot code to handle function descriptors properly.
863 * So instead, we use the same approach as on PPC32.
864 * This is a horrible mess, but fixing it would probably lead to an even bigger
870 * - similar to the PPC32 design, we reserve EBX to hold the GOT pointer.
873 #ifdef MONO_ARCH_AOT_SUPPORTED
875 * arch_emit_got_offset:
877 * The memory pointed to by CODE should hold native code for computing the GOT
878 * address. Emit this code while patching it with the offset between code and
879 * the GOT. CODE_SIZE is set to the number of bytes emitted.
882 arch_emit_got_offset (MonoAotCompile *acfg, guint8 *code, int *code_size)
884 #if defined(TARGET_POWERPC64)
885 g_assert (!acfg->use_bin_writer);
886 emit_unset_mode (acfg);
888 * The ppc32 code doesn't seem to work on ppc64, the assembler complains about
889 * unsupported relocations. So we store the got address into the .Lgot_addr
890 * symbol which is in the text segment, compute its address, and load it.
892 fprintf (acfg->fp, ".L%d:\n", acfg->label_generator);
893 fprintf (acfg->fp, "lis 0, (.Lgot_addr + 4 - .L%d)@h\n", acfg->label_generator);
894 fprintf (acfg->fp, "ori 0, 0, (.Lgot_addr + 4 - .L%d)@l\n", acfg->label_generator);
895 fprintf (acfg->fp, "add 30, 30, 0\n");
896 fprintf (acfg->fp, "%s 30, 0(30)\n", PPC_LD_OP);
897 acfg->label_generator ++;
899 #elif defined(TARGET_POWERPC)
900 g_assert (!acfg->use_bin_writer);
901 emit_unset_mode (acfg);
902 fprintf (acfg->fp, ".L%d:\n", acfg->label_generator);
903 fprintf (acfg->fp, "lis 0, (%s + 4 - .L%d)@h\n", acfg->got_symbol, acfg->label_generator);
904 fprintf (acfg->fp, "ori 0, 0, (%s + 4 - .L%d)@l\n", acfg->got_symbol, acfg->label_generator);
905 acfg->label_generator ++;
908 guint32 offset = mono_arch_get_patch_offset (code);
909 emit_bytes (acfg, code, offset);
910 emit_symbol_diff (acfg, acfg->got_symbol, ".", offset);
912 *code_size = offset + 4;
917 * arch_emit_got_access:
919 * The memory pointed to by CODE should hold native code for loading a GOT
920 * slot. Emit this code while patching it so it accesses the GOT slot GOT_SLOT.
921 * CODE_SIZE is set to the number of bytes emitted.
924 arch_emit_got_access (MonoAotCompile *acfg, guint8 *code, int got_slot, int *code_size)
926 /* This needs to emit the same code as OP_AOTCONST */
929 /* mov reg, got+offset(%rip) */
930 if (acfg->llvm_separate) {
931 /* The GOT symbol is in the LLVM module, the clang assembler has problems emitting symbol diffs for it */
935 /* Decode reg, see amd64_mov_reg_membase () */
936 rex_r = code [0] & AMD64_REX_R;
937 g_assert (code [0] == 0x49 + rex_r);
938 g_assert (code [1] == 0x8b);
939 dreg = ((code [2] >> 3) & 0x7) + (rex_r ? 8 : 0);
941 emit_unset_mode (acfg);
942 fprintf (acfg->fp, "mov %s+%d(%%rip), %s\n", acfg->got_symbol, (unsigned int) ((got_slot * sizeof (gpointer))), mono_arch_regname (dreg));
945 emit_bytes (acfg, code, mono_arch_get_patch_offset (code));
946 emit_symbol_diff (acfg, acfg->got_symbol, ".", (unsigned int) ((got_slot * sizeof (gpointer)) - 4));
947 *code_size = mono_arch_get_patch_offset (code) + 4;
949 #elif defined(TARGET_X86)
950 emit_bytes (acfg, code, mono_arch_get_patch_offset (code));
951 emit_int32 (acfg, (unsigned int) ((got_slot * sizeof (gpointer))));
952 *code_size = mono_arch_get_patch_offset (code) + 4;
953 #elif defined(TARGET_ARM)
954 emit_bytes (acfg, code, mono_arch_get_patch_offset (code));
955 emit_symbol_diff (acfg, acfg->got_symbol, ".", (unsigned int) ((got_slot * sizeof (gpointer))) - 12);
956 *code_size = mono_arch_get_patch_offset (code) + 4;
957 #elif defined(TARGET_ARM64)
958 emit_bytes (acfg, code, mono_arch_get_patch_offset (code));
959 arm64_emit_got_access (acfg, code, got_slot, code_size);
960 #elif defined(TARGET_POWERPC)
965 emit_bytes (acfg, code, mono_arch_get_patch_offset (code));
967 ppc_load32 (code, ppc_r0, got_slot * sizeof (gpointer));
968 g_assert (code - buf == 8);
969 emit_bytes (acfg, buf, code - buf);
970 *code_size = code - buf;
973 g_assert_not_reached ();
979 #ifdef MONO_ARCH_AOT_SUPPORTED
981 * arch_emit_objc_selector_ref:
983 * Emit the implementation of OP_OBJC_GET_SELECTOR, which itself implements @selector(foo:) in objective-c.
986 arch_emit_objc_selector_ref (MonoAotCompile *acfg, guint8 *code, int index, int *code_size)
988 #if defined(TARGET_ARM)
991 int lindex = acfg->objc_selector_index_2 ++;
994 emit_bytes (acfg, code, 8);
996 sprintf (symbol1, "L_OBJC_SELECTOR_%d", lindex);
997 sprintf (symbol2, "L_OBJC_SELECTOR_REFERENCES_%d", index);
999 emit_label (acfg, symbol1);
1000 img_writer_emit_unset_mode (acfg->w);
1001 fprintf (acfg->fp, ".long %s-(%s+12)", symbol2, symbol1);
1004 #elif defined(TARGET_ARM64)
1005 arm64_emit_objc_selector_ref (acfg, code, index, code_size);
1007 g_assert_not_reached ();
1013 * arch_emit_plt_entry:
1015 * Emit code for the PLT entry with index INDEX.
1018 arch_emit_plt_entry (MonoAotCompile *acfg, int index)
1020 #if defined(TARGET_X86)
1021 guint32 offset = (acfg->plt_got_offset_base + index) * sizeof (gpointer);
1022 #if defined(__default_codegen__)
1023 /* jmp *<offset>(%ebx) */
1024 emit_byte (acfg, 0xff);
1025 emit_byte (acfg, 0xa3);
1026 emit_int32 (acfg, offset);
1027 /* Used by mono_aot_get_plt_info_offset */
1028 emit_int32 (acfg, acfg->plt_got_info_offsets [index]);
1029 #elif defined(__native_client_codegen__)
1030 const guint8 kSizeOfNaClJmp = 11;
1031 guint8 bytes[kSizeOfNaClJmp];
1032 guint8 *pbytes = &bytes[0];
1034 x86_jump_membase32 (pbytes, X86_EBX, offset);
1035 emit_bytes (acfg, bytes, kSizeOfNaClJmp);
1036 /* four bytes of data, used by mono_arch_patch_plt_entry */
1037 /* For Native Client, make this work with data embedded in push. */
1038 emit_byte (acfg, 0x68); /* hide data in a push */
1039 emit_int32 (acfg, acfg->plt_got_info_offsets [index]);
1040 emit_alignment (acfg, AOT_FUNC_ALIGNMENT);
1041 #endif /*__native_client_codegen__*/
1042 #elif defined(TARGET_AMD64)
1043 #if defined(__default_codegen__)
1044 if (acfg->use_bin_writer) {
1045 emit_byte (acfg, '\xff');
1046 emit_byte (acfg, '\x25');
1047 emit_symbol_diff (acfg, acfg->got_symbol, ".", ((acfg->plt_got_offset_base + index) * sizeof (gpointer)) -4);
1049 emit_unset_mode (acfg);
1050 fprintf (acfg->fp, "jmp *%s+%d(%%rip)\n", acfg->got_symbol, (int)((acfg->plt_got_offset_base + index) * sizeof (gpointer)));
1052 /* Used by mono_aot_get_plt_info_offset */
1053 emit_int32 (acfg, acfg->plt_got_info_offsets [index]);
1054 acfg->stats.plt_size += 10;
1055 #elif defined(__native_client_codegen__)
1057 guint8 *buf_aligned = ALIGN_TO(buf, kNaClAlignment);
1058 guint8 *code = buf_aligned;
1060 /* mov <OFFSET>(%rip), %r11d */
1061 emit_byte (acfg, '\x45');
1062 emit_byte (acfg, '\x8b');
1063 emit_byte (acfg, '\x1d');
1064 emit_symbol_diff (acfg, acfg->got_symbol, ".", ((acfg->plt_got_offset_base + index) * sizeof (gpointer)) -4);
1066 amd64_jump_reg (code, AMD64_R11);
1067 /* This should be constant for the plt patch */
1068 g_assert ((size_t)(code-buf_aligned) == 10);
1069 emit_bytes (acfg, buf_aligned, code - buf_aligned);
1071 /* Hide data in a push imm32 so it passes validation */
1072 emit_byte (acfg, 0x68); /* push */
1073 emit_int32 (acfg, acfg->plt_got_info_offsets [index]);
1074 emit_alignment (acfg, AOT_FUNC_ALIGNMENT);
1075 #endif /*__native_client_codegen__*/
1076 #elif defined(TARGET_ARM)
1081 ARM_LDR_IMM (code, ARMREG_IP, ARMREG_PC, 0);
1082 ARM_LDR_REG_REG (code, ARMREG_PC, ARMREG_PC, ARMREG_IP);
1083 emit_bytes (acfg, buf, code - buf);
1084 emit_symbol_diff (acfg, acfg->got_symbol, ".", ((acfg->plt_got_offset_base + index) * sizeof (gpointer)) - 4);
1085 /* Used by mono_aot_get_plt_info_offset */
1086 emit_int32 (acfg, acfg->plt_got_info_offsets [index]);
1087 #elif defined(TARGET_ARM64)
1088 arm64_emit_plt_entry (acfg, index);
1089 #elif defined(TARGET_POWERPC)
1090 guint32 offset = (acfg->plt_got_offset_base + index) * sizeof (gpointer);
1092 /* The GOT address is guaranteed to be in r30 by OP_LOAD_GOTADDR */
1093 g_assert (!acfg->use_bin_writer);
1094 emit_unset_mode (acfg);
1095 fprintf (acfg->fp, "lis 11, %d@h\n", offset);
1096 fprintf (acfg->fp, "ori 11, 11, %d@l\n", offset);
1097 fprintf (acfg->fp, "add 11, 11, 30\n");
1098 fprintf (acfg->fp, "%s 11, 0(11)\n", PPC_LD_OP);
1099 #ifdef PPC_USES_FUNCTION_DESCRIPTOR
1100 fprintf (acfg->fp, "%s 2, %d(11)\n", PPC_LD_OP, (int)sizeof (gpointer));
1101 fprintf (acfg->fp, "%s 11, 0(11)\n", PPC_LD_OP);
1103 fprintf (acfg->fp, "mtctr 11\n");
1104 fprintf (acfg->fp, "bctr\n");
1105 emit_int32 (acfg, acfg->plt_got_info_offsets [index]);
1107 g_assert_not_reached ();
1112 arch_emit_llvm_plt_entry (MonoAotCompile *acfg, int index)
1114 #if defined(TARGET_ARM)
1116 /* LLVM calls the PLT entries using bl, so emit a stub */
1117 /* FIXME: Too much overhead on every call */
1118 fprintf (acfg->fp, ".thumb_func\n");
1119 fprintf (acfg->fp, "bx pc\n");
1120 fprintf (acfg->fp, "nop\n");
1121 fprintf (acfg->fp, ".arm\n");
1123 /* LLVM calls the PLT entries using bl, so these have to be thumb2 */
1124 /* The caller already transitioned to thumb */
1125 /* The code below should be 12 bytes long */
1126 /* clang has trouble encoding these instructions, so emit the binary */
1128 fprintf (acfg->fp, "ldr ip, [pc, #8]\n");
1129 /* thumb can't encode ld pc, [pc, ip] */
1130 fprintf (acfg->fp, "add ip, pc, ip\n");
1131 fprintf (acfg->fp, "ldr ip, [ip, #0]\n");
1132 fprintf (acfg->fp, "bx ip\n");
1134 emit_set_thumb_mode (acfg);
1135 fprintf (acfg->fp, ".4byte 0xc008f8df\n");
1136 fprintf (acfg->fp, ".2byte 0x44fc\n");
1137 fprintf (acfg->fp, ".4byte 0xc000f8dc\n");
1138 fprintf (acfg->fp, ".2byte 0x4760\n");
1139 emit_symbol_diff (acfg, acfg->got_symbol, ".", ((acfg->plt_got_offset_base + index) * sizeof (gpointer)) + 4);
1140 emit_int32 (acfg, acfg->plt_got_info_offsets [index]);
1141 emit_unset_mode (acfg);
1142 emit_set_arm_mode (acfg);
1144 g_assert_not_reached ();
1149 * arch_emit_specific_trampoline_pages:
1151 * Emits a page full of trampolines: each trampoline uses its own address to
1152 * lookup both the generic trampoline code and the data argument.
1153 * This page can be remapped in process multiple times so we can get an
1154 * unlimited number of trampolines.
1155 * Specifically this implementation uses the following trick: two memory pages
1156 * are allocated, with the first containing the data and the second containing the trampolines.
1157 * To reduce trampoline size, each trampoline jumps at the start of the page where a common
1158 * implementation does all the lifting.
1159 * Note that the ARM single trampoline size is 8 bytes, exactly like the data that needs to be stored
1160 * on the arm 32 bit system.
1163 arch_emit_specific_trampoline_pages (MonoAotCompile *acfg)
1165 #if defined(TARGET_ARM)
1168 guint8 *loop_start, *loop_branch_back, *loop_end_check, *imt_found_check;
1170 #define COMMON_TRAMP_SIZE 16
1171 int count = (mono_pagesize () - COMMON_TRAMP_SIZE) / 8;
1172 int imm8, rot_amount;
1175 if (!acfg->aot_opts.use_trampolines_page)
1178 acfg->tramp_page_size = mono_pagesize ();
1180 sprintf (symbol, "%sspecific_trampolines_page", acfg->user_symbol_prefix);
1181 emit_alignment (acfg, mono_pagesize ());
1182 emit_global (acfg, symbol, TRUE);
1183 emit_label (acfg, symbol);
1185 /* emit the generic code first, the trampoline address + 8 is in the lr register */
1187 imm8 = mono_arm_is_rotated_imm8 (mono_pagesize (), &rot_amount);
1188 ARM_SUB_REG_IMM (code, ARMREG_LR, ARMREG_LR, imm8, rot_amount);
1189 ARM_LDR_IMM (code, ARMREG_R1, ARMREG_LR, -8);
1190 ARM_LDR_IMM (code, ARMREG_PC, ARMREG_LR, -4);
1192 g_assert (code - buf == COMMON_TRAMP_SIZE);
1195 emit_bytes (acfg, buf, code - buf);
1197 for (i = 0; i < count; ++i) {
1199 ARM_PUSH (code, 0x5fff);
1201 arm_patch (code - 4, code - COMMON_TRAMP_SIZE - 8 * (i + 1));
1202 g_assert (code - buf == 8);
1203 emit_bytes (acfg, buf, code - buf);
1206 /* now the rgctx trampolines: each specific trampolines puts in the ip register
1207 * the instruction pointer address, so the generic trampoline at the start of the page
1208 * subtracts 4096 to get to the data page and loads the values
1209 * We again fit the generic trampiline in 16 bytes.
1211 sprintf (symbol, "%srgctx_trampolines_page", acfg->user_symbol_prefix);
1212 emit_global (acfg, symbol, TRUE);
1213 emit_label (acfg, symbol);
1215 imm8 = mono_arm_is_rotated_imm8 (mono_pagesize (), &rot_amount);
1216 ARM_SUB_REG_IMM (code, ARMREG_IP, ARMREG_IP, imm8, rot_amount);
1217 ARM_LDR_IMM (code, MONO_ARCH_RGCTX_REG, ARMREG_IP, -8);
1218 ARM_LDR_IMM (code, ARMREG_PC, ARMREG_IP, -4);
1220 g_assert (code - buf == COMMON_TRAMP_SIZE);
1223 emit_bytes (acfg, buf, code - buf);
1225 for (i = 0; i < count; ++i) {
1227 ARM_MOV_REG_REG (code, ARMREG_IP, ARMREG_PC);
1229 arm_patch (code - 4, code - COMMON_TRAMP_SIZE - 8 * (i + 1));
1230 g_assert (code - buf == 8);
1231 emit_bytes (acfg, buf, code - buf);
1235 * gsharedvt arg trampolines: see arch_emit_gsharedvt_arg_trampoline ()
1237 sprintf (symbol, "%sgsharedvt_arg_trampolines_page", acfg->user_symbol_prefix);
1238 emit_global (acfg, symbol, TRUE);
1239 emit_label (acfg, symbol);
1241 ARM_PUSH (code, (1 << ARMREG_R0) | (1 << ARMREG_R1) | (1 << ARMREG_R2) | (1 << ARMREG_R3));
1242 imm8 = mono_arm_is_rotated_imm8 (mono_pagesize (), &rot_amount);
1243 ARM_SUB_REG_IMM (code, ARMREG_IP, ARMREG_IP, imm8, rot_amount);
1244 ARM_LDR_IMM (code, ARMREG_R0, ARMREG_IP, -8);
1245 ARM_LDR_IMM (code, ARMREG_PC, ARMREG_IP, -4);
1246 g_assert (code - buf == COMMON_TRAMP_SIZE);
1248 emit_bytes (acfg, buf, code - buf);
1250 for (i = 0; i < count; ++i) {
1252 ARM_MOV_REG_REG (code, ARMREG_IP, ARMREG_PC);
1254 arm_patch (code - 4, code - COMMON_TRAMP_SIZE - 8 * (i + 1));
1255 g_assert (code - buf == 8);
1256 emit_bytes (acfg, buf, code - buf);
1259 /* now the imt trampolines: each specific trampolines puts in the ip register
1260 * the instruction pointer address, so the generic trampoline at the start of the page
1261 * subtracts 4096 to get to the data page and loads the values
1262 * We again fit the generic trampiline in 16 bytes.
1264 #define IMT_TRAMP_SIZE 72
1265 sprintf (symbol, "%simt_trampolines_page", acfg->user_symbol_prefix);
1266 emit_global (acfg, symbol, TRUE);
1267 emit_label (acfg, symbol);
1269 /* Need at least two free registers, plus a slot for storing the pc */
1270 ARM_PUSH (code, (1 << ARMREG_R0)|(1 << ARMREG_R1)|(1 << ARMREG_R2));
1272 imm8 = mono_arm_is_rotated_imm8 (mono_pagesize (), &rot_amount);
1273 ARM_SUB_REG_IMM (code, ARMREG_IP, ARMREG_IP, imm8, rot_amount);
1274 ARM_LDR_IMM (code, ARMREG_R0, ARMREG_IP, -8);
1276 /* The IMT method is in v5, r0 has the imt array address */
1279 ARM_LDR_IMM (code, ARMREG_R1, ARMREG_R0, 0);
1280 ARM_CMP_REG_REG (code, ARMREG_R1, ARMREG_V5);
1281 imt_found_check = code;
1282 ARM_B_COND (code, ARMCOND_EQ, 0);
1284 /* End-of-loop check */
1285 ARM_CMP_REG_IMM (code, ARMREG_R1, 0, 0);
1286 loop_end_check = code;
1287 ARM_B_COND (code, ARMCOND_EQ, 0);
1290 ARM_ADD_REG_IMM8 (code, ARMREG_R0, ARMREG_R0, sizeof (gpointer) * 2);
1291 loop_branch_back = code;
1293 arm_patch (loop_branch_back, loop_start);
1296 arm_patch (imt_found_check, code);
1297 ARM_LDR_IMM (code, ARMREG_R0, ARMREG_R0, 4);
1298 ARM_LDR_IMM (code, ARMREG_R0, ARMREG_R0, 0);
1299 /* Save it to the third stack slot */
1300 ARM_STR_IMM (code, ARMREG_R0, ARMREG_SP, 8);
1301 /* Restore the registers and branch */
1302 ARM_POP (code, (1 << ARMREG_R0)|(1 << ARMREG_R1)|(1 << ARMREG_PC));
1305 arm_patch (loop_end_check, code);
1306 ARM_LDR_IMM (code, ARMREG_R0, ARMREG_R0, 4);
1307 ARM_STR_IMM (code, ARMREG_R0, ARMREG_SP, 8);
1308 ARM_POP (code, (1 << ARMREG_R0)|(1 << ARMREG_R1)|(1 << ARMREG_PC));
1312 g_assert (code - buf == IMT_TRAMP_SIZE);
1313 emit_bytes (acfg, buf, code - buf);
1315 for (i = 0; i < count; ++i) {
1317 ARM_MOV_REG_REG (code, ARMREG_IP, ARMREG_PC);
1319 arm_patch (code - 4, code - IMT_TRAMP_SIZE - 8 * (i + 1));
1320 g_assert (code - buf == 8);
1321 emit_bytes (acfg, buf, code - buf);
1324 acfg->tramp_page_code_offsets [MONO_AOT_TRAMP_SPECIFIC] = 16;
1325 acfg->tramp_page_code_offsets [MONO_AOT_TRAMP_STATIC_RGCTX] = 16;
1326 acfg->tramp_page_code_offsets [MONO_AOT_TRAMP_IMT_THUNK] = 72;
1327 acfg->tramp_page_code_offsets [MONO_AOT_TRAMP_GSHAREDVT_ARG] = 16;
1328 #elif defined(TARGET_ARM64)
1329 arm64_emit_specific_trampoline_pages (acfg);
1334 * arch_emit_specific_trampoline:
1336 * Emit code for a specific trampoline. OFFSET is the offset of the first of
1337 * two GOT slots which contain the generic trampoline address and the trampoline
1338 * argument. TRAMP_SIZE is set to the size of the emitted trampoline.
1341 arch_emit_specific_trampoline (MonoAotCompile *acfg, int offset, int *tramp_size)
1344 * The trampolines created here are variations of the specific
1345 * trampolines created in mono_arch_create_specific_trampoline (). The
1347 * - the generic trampoline address is taken from a got slot.
1348 * - the offset of the got slot where the trampoline argument is stored
1349 * is embedded in the instruction stream, and the generic trampoline
1350 * can load the argument by loading the offset, adding it to the
1351 * address of the trampoline to get the address of the got slot, and
1352 * loading the argument from there.
1353 * - all the trampolines should be of the same length.
1355 #if defined(TARGET_AMD64)
1356 #if defined(__default_codegen__)
1357 /* This should be exactly 8 bytes long */
1359 /* call *<offset>(%rip) */
1360 if (acfg->llvm_separate) {
1361 emit_unset_mode (acfg);
1362 fprintf (acfg->fp, "call *%s+%d(%%rip)\n", acfg->got_symbol, (int)(offset * sizeof (gpointer)));
1363 emit_zero_bytes (acfg, 2);
1365 emit_byte (acfg, '\x41');
1366 emit_byte (acfg, '\xff');
1367 emit_byte (acfg, '\x15');
1368 emit_symbol_diff (acfg, acfg->got_symbol, ".", (offset * sizeof (gpointer)) - 4);
1369 emit_zero_bytes (acfg, 1);
1371 #elif defined(__native_client_codegen__)
1373 guint8 *buf_aligned = ALIGN_TO(buf, kNaClAlignment);
1374 guint8 *code = buf_aligned;
1379 /* Emit this call in 'code' so we can find out how long it is. */
1380 amd64_call_reg (code, AMD64_R11);
1381 call_start = mono_arch_nacl_skip_nops (buf_aligned);
1382 call_len = code - call_start;
1384 /* The tramp_size is twice the NaCl alignment because it starts with */
1385 /* a call which needs to be aligned to the end of the boundary. */
1386 *tramp_size = kNaClAlignment*2;
1388 /* Emit nops to align call site below which is 7 bytes plus */
1389 /* the length of the call sequence emitted above. */
1390 /* Note: this requires the specific trampoline starts on a */
1391 /* kNaclAlignedment aligned address, which it does because */
1392 /* it's its own function that is aligned. */
1393 guint8 nop_buf[256];
1394 guint8 *nopbuf_aligned = ALIGN_TO (nop_buf, kNaClAlignment);
1395 guint8 *nopbuf_end = mono_arch_nacl_pad (nopbuf_aligned, kNaClAlignment - 7 - (call_len));
1396 emit_bytes (acfg, nopbuf_aligned, nopbuf_end - nopbuf_aligned);
1398 /* The trampoline is stored at the offset'th pointer, the -4 is */
1399 /* present because RIP relative addressing starts at the end of */
1400 /* the current instruction, while the label "." is relative to */
1401 /* the beginning of the current asm location, which in this case */
1402 /* is not the mov instruction, but the offset itself, due to the */
1403 /* way the bytes and ints are emitted here. */
1404 got_offset = (offset * sizeof(gpointer)) - 4;
1406 /* mov <OFFSET>(%rip), %r11d */
1407 emit_byte (acfg, '\x45');
1408 emit_byte (acfg, '\x8b');
1409 emit_byte (acfg, '\x1d');
1410 emit_symbol_diff (acfg, acfg->got_symbol, ".", got_offset);
1413 emit_bytes (acfg, call_start, call_len);
1415 /* The arg is stored at the offset+1 pointer, relative to beginning */
1416 /* of trampoline: 7 for mov, plus the call length, and 1 for push. */
1417 got_offset = ((offset + 1) * sizeof(gpointer)) + 7 + call_len + 1;
1419 /* We can't emit this data directly, hide in a "push imm32" */
1420 emit_byte (acfg, '\x68'); /* push */
1421 emit_symbol_diff (acfg, acfg->got_symbol, ".", got_offset);
1422 emit_alignment (acfg, kNaClAlignment);
1423 #endif /*__native_client_codegen__*/
1424 #elif defined(TARGET_ARM)
1428 /* This should be exactly 20 bytes long */
1431 ARM_PUSH (code, 0x5fff);
1432 ARM_LDR_IMM (code, ARMREG_R1, ARMREG_PC, 4);
1433 /* Load the value from the GOT */
1434 ARM_LDR_REG_REG (code, ARMREG_R1, ARMREG_PC, ARMREG_R1);
1436 ARM_BLX_REG (code, ARMREG_R1);
1438 g_assert (code - buf == 16);
1441 emit_bytes (acfg, buf, code - buf);
1443 * Only one offset is needed, since the second one would be equal to the
1446 emit_symbol_diff (acfg, acfg->got_symbol, ".", (offset * sizeof (gpointer)) - 4 + 4);
1447 //emit_symbol_diff (acfg, acfg->got_symbol, ".", ((offset + 1) * sizeof (gpointer)) - 4 + 8);
1448 #elif defined(TARGET_ARM64)
1449 arm64_emit_specific_trampoline (acfg, offset, tramp_size);
1450 #elif defined(TARGET_POWERPC)
1457 g_assert (!acfg->use_bin_writer);
1460 * PPC has no ip relative addressing, so we need to compute the address
1461 * of the mscorlib got. That is slow and complex, so instead, we store it
1462 * in the second got slot of every aot image. The caller already computed
1463 * the address of its got and placed it into r30.
1465 emit_unset_mode (acfg);
1466 /* Load mscorlib got address */
1467 fprintf (acfg->fp, "%s 0, %d(30)\n", PPC_LD_OP, (int)sizeof (gpointer));
1468 /* Load generic trampoline address */
1469 fprintf (acfg->fp, "lis 11, %d@h\n", (int)(offset * sizeof (gpointer)));
1470 fprintf (acfg->fp, "ori 11, 11, %d@l\n", (int)(offset * sizeof (gpointer)));
1471 fprintf (acfg->fp, "%s 11, 11, 0\n", PPC_LDX_OP);
1472 #ifdef PPC_USES_FUNCTION_DESCRIPTOR
1473 fprintf (acfg->fp, "%s 11, 0(11)\n", PPC_LD_OP);
1475 fprintf (acfg->fp, "mtctr 11\n");
1476 /* Load trampoline argument */
1477 /* On ppc, we pass it normally to the generic trampoline */
1478 fprintf (acfg->fp, "lis 11, %d@h\n", (int)((offset + 1) * sizeof (gpointer)));
1479 fprintf (acfg->fp, "ori 11, 11, %d@l\n", (int)((offset + 1) * sizeof (gpointer)));
1480 fprintf (acfg->fp, "%s 0, 11, 0\n", PPC_LDX_OP);
1481 /* Branch to generic trampoline */
1482 fprintf (acfg->fp, "bctr\n");
1484 #ifdef PPC_USES_FUNCTION_DESCRIPTOR
1485 *tramp_size = 10 * 4;
1487 *tramp_size = 9 * 4;
1489 #elif defined(TARGET_X86)
1493 /* Similar to the PPC code above */
1495 /* FIXME: Could this clobber the register needed by get_vcall_slot () ? */
1497 /* We clobber ECX, since EAX is used as MONO_ARCH_MONITOR_OBJECT_REG */
1498 #ifdef MONO_ARCH_MONITOR_OBJECT_REG
1499 g_assert (MONO_ARCH_MONITOR_OBJECT_REG != X86_ECX);
1500 #ifdef MONO_ARCH_MONITOR_LOCK_TAKEN_REG
1501 g_assert (MONO_ARCH_MONITOR_LOCK_TAKEN_REG != X86_ECX);
1506 /* Load mscorlib got address */
1507 x86_mov_reg_membase (code, X86_ECX, MONO_ARCH_GOT_REG, sizeof (gpointer), 4);
1508 /* Push trampoline argument */
1509 x86_push_membase (code, X86_ECX, (offset + 1) * sizeof (gpointer));
1510 /* Load generic trampoline address */
1511 x86_mov_reg_membase (code, X86_ECX, X86_ECX, offset * sizeof (gpointer), 4);
1512 /* Branch to generic trampoline */
1513 x86_jump_reg (code, X86_ECX);
1515 #ifdef __native_client_codegen__
1517 /* emit nops to next 32 byte alignment */
1518 int a = (~kNaClAlignmentMask) & ((code - buf) + kNaClAlignment - 1);
1519 while (code < (buf + a)) x86_nop(code);
1522 emit_bytes (acfg, buf, code - buf);
1524 *tramp_size = NACL_SIZE(17, kNaClAlignment);
1525 g_assert (code - buf == *tramp_size);
1527 g_assert_not_reached ();
1532 * arch_emit_unbox_trampoline:
1534 * Emit code for the unbox trampoline for METHOD used in the full-aot case.
1535 * CALL_TARGET is the symbol pointing to the native code of METHOD.
1538 arch_emit_unbox_trampoline (MonoAotCompile *acfg, MonoCompile *cfg, MonoMethod *method, const char *call_target)
1540 #if defined(TARGET_AMD64)
1545 this_reg = mono_arch_get_this_arg_reg (NULL);
1547 amd64_alu_reg_imm (code, X86_ADD, this_reg, sizeof (MonoObject));
1549 emit_bytes (acfg, buf, code - buf);
1551 if (acfg->llvm_separate) {
1552 emit_unset_mode (acfg);
1553 fprintf (acfg->fp, "jmp %s\n", call_target);
1555 emit_byte (acfg, '\xe9');
1556 emit_symbol_diff (acfg, call_target, ".", -4);
1558 #elif defined(TARGET_X86)
1565 x86_alu_membase_imm (code, X86_ADD, X86_ESP, this_pos, sizeof (MonoObject));
1567 emit_bytes (acfg, buf, code - buf);
1570 emit_byte (acfg, '\xe9');
1571 emit_symbol_diff (acfg, call_target, ".", -4);
1572 #elif defined(TARGET_ARM)
1576 if (acfg->thumb_mixed && cfg->compile_llvm) {
1577 fprintf (acfg->fp, "add r0, r0, #%d\n", (int)sizeof (MonoObject));
1578 fprintf (acfg->fp, "b %s\n", call_target);
1579 fprintf (acfg->fp, ".arm\n");
1580 fprintf (acfg->fp, ".align 2\n");
1586 ARM_ADD_REG_IMM8 (code, ARMREG_R0, ARMREG_R0, sizeof (MonoObject));
1588 emit_bytes (acfg, buf, code - buf);
1589 /* jump to method */
1590 if (acfg->use_bin_writer) {
1597 img_writer_emit_reloc (acfg->w, R_ARM_JUMP24, call_target, -8);
1598 emit_bytes (acfg, buf, 4);
1600 if (acfg->thumb_mixed && cfg->compile_llvm)
1601 fprintf (acfg->fp, "\n\tbx %s\n", call_target);
1603 fprintf (acfg->fp, "\n\tb %s\n", call_target);
1605 #elif defined(TARGET_ARM64)
1606 arm64_emit_unbox_trampoline (acfg, cfg, method, call_target);
1607 #elif defined(TARGET_POWERPC)
1610 g_assert (!acfg->use_bin_writer);
1612 fprintf (acfg->fp, "\n\taddi %d, %d, %d\n", this_pos, this_pos, (int)sizeof (MonoObject));
1613 fprintf (acfg->fp, "\n\tb %s\n", call_target);
1615 g_assert_not_reached ();
1620 * arch_emit_static_rgctx_trampoline:
1622 * Emit code for a static rgctx trampoline. OFFSET is the offset of the first of
1623 * two GOT slots which contain the rgctx argument, and the method to jump to.
1624 * TRAMP_SIZE is set to the size of the emitted trampoline.
1625 * These kinds of trampolines cannot be enumerated statically, since there could
1626 * be one trampoline per method instantiation, so we emit the same code for all
1627 * trampolines, and parameterize them using two GOT slots.
1630 arch_emit_static_rgctx_trampoline (MonoAotCompile *acfg, int offset, int *tramp_size)
1632 #if defined(TARGET_AMD64)
1633 #if defined(__default_codegen__)
1634 /* This should be exactly 13 bytes long */
1637 if (acfg->llvm_separate) {
1638 emit_unset_mode (acfg);
1639 fprintf (acfg->fp, "mov %s+%d(%%rip), %%r10\n", acfg->got_symbol, (int)(offset * sizeof (gpointer)));
1640 fprintf (acfg->fp, "jmp *%s+%d(%%rip)\n", acfg->got_symbol, (int)((offset + 1) * sizeof (gpointer)));
1642 /* mov <OFFSET>(%rip), %r10 */
1643 emit_byte (acfg, '\x4d');
1644 emit_byte (acfg, '\x8b');
1645 emit_byte (acfg, '\x15');
1646 emit_symbol_diff (acfg, acfg->got_symbol, ".", (offset * sizeof (gpointer)) - 4);
1648 /* jmp *<offset>(%rip) */
1649 emit_byte (acfg, '\xff');
1650 emit_byte (acfg, '\x25');
1651 emit_symbol_diff (acfg, acfg->got_symbol, ".", ((offset + 1) * sizeof (gpointer)) - 4);
1653 #elif defined(__native_client_codegen__)
1655 guint8 *buf_aligned = ALIGN_TO(buf, kNaClAlignment);
1656 guint8 *code = buf_aligned;
1658 /* mov <OFFSET>(%rip), %r10d */
1659 emit_byte (acfg, '\x45');
1660 emit_byte (acfg, '\x8b');
1661 emit_byte (acfg, '\x15');
1662 emit_symbol_diff (acfg, acfg->got_symbol, ".", (offset * sizeof (gpointer)) - 4);
1664 /* mov <OFFSET>(%rip), %r11d */
1665 emit_byte (acfg, '\x45');
1666 emit_byte (acfg, '\x8b');
1667 emit_byte (acfg, '\x1d');
1668 emit_symbol_diff (acfg, acfg->got_symbol, ".", ((offset + 1) * sizeof (gpointer)) - 4);
1671 amd64_jump_reg (code, AMD64_R11);
1672 emit_bytes (acfg, buf_aligned, code - buf_aligned);
1674 emit_alignment (acfg, kNaClAlignment);
1675 *tramp_size = kNaClAlignment;
1676 #endif /*__native_client_codegen__*/
1678 #elif defined(TARGET_ARM)
1682 /* This should be exactly 24 bytes long */
1685 /* Load rgctx value */
1686 ARM_LDR_IMM (code, ARMREG_IP, ARMREG_PC, 8);
1687 ARM_LDR_REG_REG (code, MONO_ARCH_RGCTX_REG, ARMREG_PC, ARMREG_IP);
1688 /* Load branch addr + branch */
1689 ARM_LDR_IMM (code, ARMREG_IP, ARMREG_PC, 4);
1690 ARM_LDR_REG_REG (code, ARMREG_PC, ARMREG_PC, ARMREG_IP);
1692 g_assert (code - buf == 16);
1695 emit_bytes (acfg, buf, code - buf);
1696 emit_symbol_diff (acfg, acfg->got_symbol, ".", (offset * sizeof (gpointer)) - 4 + 8);
1697 emit_symbol_diff (acfg, acfg->got_symbol, ".", ((offset + 1) * sizeof (gpointer)) - 4 + 4);
1698 #elif defined(TARGET_ARM64)
1699 arm64_emit_static_rgctx_trampoline (acfg, offset, tramp_size);
1700 #elif defined(TARGET_POWERPC)
1707 g_assert (!acfg->use_bin_writer);
1710 * PPC has no ip relative addressing, so we need to compute the address
1711 * of the mscorlib got. That is slow and complex, so instead, we store it
1712 * in the second got slot of every aot image. The caller already computed
1713 * the address of its got and placed it into r30.
1715 emit_unset_mode (acfg);
1716 /* Load mscorlib got address */
1717 fprintf (acfg->fp, "%s 0, %d(30)\n", PPC_LD_OP, (int)sizeof (gpointer));
1719 fprintf (acfg->fp, "lis 11, %d@h\n", (int)(offset * sizeof (gpointer)));
1720 fprintf (acfg->fp, "ori 11, 11, %d@l\n", (int)(offset * sizeof (gpointer)));
1721 fprintf (acfg->fp, "%s %d, 11, 0\n", PPC_LDX_OP, MONO_ARCH_RGCTX_REG);
1722 /* Load target address */
1723 fprintf (acfg->fp, "lis 11, %d@h\n", (int)((offset + 1) * sizeof (gpointer)));
1724 fprintf (acfg->fp, "ori 11, 11, %d@l\n", (int)((offset + 1) * sizeof (gpointer)));
1725 fprintf (acfg->fp, "%s 11, 11, 0\n", PPC_LDX_OP);
1726 #ifdef PPC_USES_FUNCTION_DESCRIPTOR
1727 fprintf (acfg->fp, "%s 2, %d(11)\n", PPC_LD_OP, (int)sizeof (gpointer));
1728 fprintf (acfg->fp, "%s 11, 0(11)\n", PPC_LD_OP);
1730 fprintf (acfg->fp, "mtctr 11\n");
1731 /* Branch to the target address */
1732 fprintf (acfg->fp, "bctr\n");
1734 #ifdef PPC_USES_FUNCTION_DESCRIPTOR
1735 *tramp_size = 11 * 4;
1737 *tramp_size = 9 * 4;
1740 #elif defined(TARGET_X86)
1744 /* Similar to the PPC code above */
1746 g_assert (MONO_ARCH_RGCTX_REG != X86_ECX);
1749 /* Load mscorlib got address */
1750 x86_mov_reg_membase (code, X86_ECX, MONO_ARCH_GOT_REG, sizeof (gpointer), 4);
1752 x86_mov_reg_membase (code, MONO_ARCH_RGCTX_REG, X86_ECX, offset * sizeof (gpointer), 4);
1753 /* Branch to the target address */
1754 x86_jump_membase (code, X86_ECX, (offset + 1) * sizeof (gpointer));
1756 #ifdef __native_client_codegen__
1758 /* emit nops to next 32 byte alignment */
1759 int a = (~kNaClAlignmentMask) & ((code - buf) + kNaClAlignment - 1);
1760 while (code < (buf + a)) x86_nop(code);
1764 emit_bytes (acfg, buf, code - buf);
1766 *tramp_size = NACL_SIZE (15, kNaClAlignment);
1767 g_assert (code - buf == *tramp_size);
1769 g_assert_not_reached ();
1774 * arch_emit_imt_thunk:
1776 * Emit an IMT thunk usable in full-aot mode. The thunk uses 1 got slot which
1777 * points to an array of pointer pairs. The pairs of the form [key, ptr], where
1778 * key is the IMT key, and ptr holds the address of a memory location holding
1779 * the address to branch to if the IMT arg matches the key. The array is
1780 * terminated by a pair whose key is NULL, and whose ptr is the address of the
1782 * TRAMP_SIZE is set to the size of the emitted trampoline.
1785 arch_emit_imt_thunk (MonoAotCompile *acfg, int offset, int *tramp_size)
1787 #if defined(TARGET_AMD64)
1789 #if defined(__native_client_codegen__)
1792 guint8 *labels [16];
1794 guint8 *mov_buf_ptr = mov_buf;
1796 const int kSizeOfMove = 7;
1797 #if defined(__default_codegen__)
1798 code = buf = g_malloc (256);
1799 #elif defined(__native_client_codegen__)
1800 buf_alloc = g_malloc (256 + kNaClAlignment + kSizeOfMove);
1801 buf = ((guint)buf_alloc + kNaClAlignment) & ~kNaClAlignmentMask;
1802 /* The RIP relative move below is emitted first */
1807 /* FIXME: Optimize this, i.e. use binary search etc. */
1808 /* Maybe move the body into a separate function (slower, but much smaller) */
1810 /* MONO_ARCH_IMT_SCRATCH_REG is a free register */
1812 if (acfg->llvm_separate) {
1813 emit_unset_mode (acfg);
1814 fprintf (acfg->fp, "mov %s+%d(%%rip), %s\n", acfg->got_symbol, (int)(offset * sizeof (gpointer)), mono_arch_regname (MONO_ARCH_IMT_SCRATCH_REG));
1818 amd64_alu_membase_imm (code, X86_CMP, MONO_ARCH_IMT_SCRATCH_REG, 0, 0);
1820 amd64_branch8 (code, X86_CC_Z, 0, FALSE);
1823 amd64_alu_membase_reg_size (code, X86_CMP, MONO_ARCH_IMT_SCRATCH_REG, 0, MONO_ARCH_IMT_REG, sizeof (gpointer));
1825 amd64_branch8 (code, X86_CC_Z, 0, FALSE);
1828 amd64_alu_reg_imm (code, X86_ADD, MONO_ARCH_IMT_SCRATCH_REG, 2 * sizeof (gpointer));
1829 amd64_jump_code (code, labels [0]);
1832 mono_amd64_patch (labels [2], code);
1833 amd64_mov_reg_membase (code, MONO_ARCH_IMT_SCRATCH_REG, MONO_ARCH_IMT_SCRATCH_REG, sizeof (gpointer), sizeof (gpointer));
1834 amd64_jump_membase (code, MONO_ARCH_IMT_SCRATCH_REG, 0);
1837 mono_amd64_patch (labels [1], code);
1838 /* Load fail tramp */
1839 amd64_alu_reg_imm (code, X86_ADD, MONO_ARCH_IMT_SCRATCH_REG, sizeof (gpointer));
1840 /* Check if there is a fail tramp */
1841 amd64_alu_membase_imm (code, X86_CMP, MONO_ARCH_IMT_SCRATCH_REG, 0, 0);
1843 amd64_branch8 (code, X86_CC_Z, 0, FALSE);
1844 /* Jump to fail tramp */
1845 amd64_jump_membase (code, MONO_ARCH_IMT_SCRATCH_REG, 0);
1848 mono_amd64_patch (labels [3], code);
1849 x86_breakpoint (code);
1851 if (!acfg->llvm_separate) {
1852 /* mov <OFFSET>(%rip), MONO_ARCH_IMT_SCRATCH_REG */
1853 amd64_emit_rex (mov_buf_ptr, sizeof(gpointer), MONO_ARCH_IMT_SCRATCH_REG, 0, AMD64_RIP);
1854 *(mov_buf_ptr)++ = (unsigned char)0x8b; /* mov opcode */
1855 x86_address_byte (mov_buf_ptr, 0, MONO_ARCH_IMT_SCRATCH_REG & 0x7, 5);
1856 emit_bytes (acfg, mov_buf, mov_buf_ptr - mov_buf);
1857 emit_symbol_diff (acfg, acfg->got_symbol, ".", (offset * sizeof (gpointer)) - 4);
1859 emit_bytes (acfg, buf, code - buf);
1861 *tramp_size = code - buf + kSizeOfMove;
1862 #if defined(__native_client_codegen__)
1863 /* The tramp will be padded to the next kNaClAlignment bundle. */
1864 *tramp_size = ALIGN_TO ((*tramp_size), kNaClAlignment);
1867 #if defined(__default_codegen__)
1869 #elif defined(__native_client_codegen__)
1873 #elif defined(TARGET_X86)
1875 #ifdef __native_client_codegen__
1878 guint8 *labels [16];
1880 #if defined(__default_codegen__)
1881 code = buf = g_malloc (256);
1882 #elif defined(__native_client_codegen__)
1883 buf_alloc = g_malloc (256 + kNaClAlignment);
1884 code = buf = ((guint)buf_alloc + kNaClAlignment) & ~kNaClAlignmentMask;
1887 /* Allocate a temporary stack slot */
1888 x86_push_reg (code, X86_EAX);
1890 x86_push_reg (code, X86_EAX);
1892 /* Load mscorlib got address */
1893 x86_mov_reg_membase (code, X86_EAX, MONO_ARCH_GOT_REG, sizeof (gpointer), 4);
1895 x86_mov_reg_membase (code, X86_EAX, X86_EAX, offset * sizeof (gpointer), 4);
1898 x86_alu_membase_imm (code, X86_CMP, X86_EAX, 0, 0);
1900 x86_branch8 (code, X86_CC_Z, FALSE, 0);
1903 x86_alu_membase_reg (code, X86_CMP, X86_EAX, 0, MONO_ARCH_IMT_REG);
1905 x86_branch8 (code, X86_CC_Z, FALSE, 0);
1908 x86_alu_reg_imm (code, X86_ADD, X86_EAX, 2 * sizeof (gpointer));
1909 x86_jump_code (code, labels [0]);
1912 mono_x86_patch (labels [2], code);
1913 x86_mov_reg_membase (code, X86_EAX, X86_EAX, sizeof (gpointer), 4);
1914 x86_mov_reg_membase (code, X86_EAX, X86_EAX, 0, 4);
1915 /* Save the target address to the temporary stack location */
1916 x86_mov_membase_reg (code, X86_ESP, 4, X86_EAX, 4);
1918 x86_pop_reg (code, X86_EAX);
1919 /* Jump to the target address */
1923 mono_x86_patch (labels [1], code);
1924 /* Load fail tramp */
1925 x86_mov_reg_membase (code, X86_EAX, X86_EAX, sizeof (gpointer), 4);
1926 x86_alu_membase_imm (code, X86_CMP, X86_EAX, 0, 0);
1928 x86_branch8 (code, X86_CC_Z, FALSE, 0);
1929 /* Jump to fail tramp */
1930 x86_mov_membase_reg (code, X86_ESP, 4, X86_EAX, 4);
1931 x86_pop_reg (code, X86_EAX);
1935 mono_x86_patch (labels [3], code);
1936 x86_breakpoint (code);
1938 #ifdef __native_client_codegen__
1940 /* emit nops to next 32 byte alignment */
1941 int a = (~kNaClAlignmentMask) & ((code - buf) + kNaClAlignment - 1);
1942 while (code < (buf + a)) x86_nop(code);
1945 emit_bytes (acfg, buf, code - buf);
1947 *tramp_size = code - buf;
1949 #if defined(__default_codegen__)
1951 #elif defined(__native_client_codegen__)
1955 #elif defined(TARGET_ARM)
1957 guint8 *code, *code2, *labels [16];
1961 /* The IMT method is in v5 */
1963 /* Need at least two free registers, plus a slot for storing the pc */
1964 ARM_PUSH (code, (1 << ARMREG_R0)|(1 << ARMREG_R1)|(1 << ARMREG_R2));
1966 /* Load the parameter from the GOT */
1967 ARM_LDR_IMM (code, ARMREG_R0, ARMREG_PC, 0);
1968 ARM_LDR_REG_REG (code, ARMREG_R0, ARMREG_PC, ARMREG_R0);
1971 ARM_LDR_IMM (code, ARMREG_R1, ARMREG_R0, 0);
1972 ARM_CMP_REG_REG (code, ARMREG_R1, ARMREG_V5);
1974 ARM_B_COND (code, ARMCOND_EQ, 0);
1976 /* End-of-loop check */
1977 ARM_CMP_REG_IMM (code, ARMREG_R1, 0, 0);
1979 ARM_B_COND (code, ARMCOND_EQ, 0);
1982 ARM_ADD_REG_IMM8 (code, ARMREG_R0, ARMREG_R0, sizeof (gpointer) * 2);
1985 arm_patch (labels [4], labels [1]);
1988 arm_patch (labels [2], code);
1989 ARM_LDR_IMM (code, ARMREG_R0, ARMREG_R0, 4);
1990 ARM_LDR_IMM (code, ARMREG_R0, ARMREG_R0, 0);
1991 /* Save it to the third stack slot */
1992 ARM_STR_IMM (code, ARMREG_R0, ARMREG_SP, 8);
1993 /* Restore the registers and branch */
1994 ARM_POP (code, (1 << ARMREG_R0)|(1 << ARMREG_R1)|(1 << ARMREG_PC));
1997 arm_patch (labels [3], code);
1998 ARM_LDR_IMM (code, ARMREG_R0, ARMREG_R0, 4);
1999 ARM_STR_IMM (code, ARMREG_R0, ARMREG_SP, 8);
2000 ARM_POP (code, (1 << ARMREG_R0)|(1 << ARMREG_R1)|(1 << ARMREG_PC));
2004 ARM_LDR_IMM (code2, ARMREG_R0, ARMREG_PC, (code - (labels [0] + 8)));
2006 emit_bytes (acfg, buf, code - buf);
2007 emit_symbol_diff (acfg, acfg->got_symbol, ".", (offset * sizeof (gpointer)) + (code - (labels [0] + 8)) - 4);
2009 *tramp_size = code - buf + 4;
2010 #elif defined(TARGET_ARM64)
2011 arm64_emit_imt_thunk (acfg, offset, tramp_size);
2012 #elif defined(TARGET_POWERPC)
2014 guint8 *code, *labels [16];
2018 /* Load the mscorlib got address */
2019 ppc_ldptr (code, ppc_r12, sizeof (gpointer), ppc_r30);
2020 /* Load the parameter from the GOT */
2021 ppc_load (code, ppc_r0, offset * sizeof (gpointer));
2022 ppc_ldptr_indexed (code, ppc_r12, ppc_r12, ppc_r0);
2024 /* Load and check key */
2026 ppc_ldptr (code, ppc_r0, 0, ppc_r12);
2027 ppc_cmp (code, 0, sizeof (gpointer) == 8 ? 1 : 0, ppc_r0, MONO_ARCH_IMT_REG);
2029 ppc_bc (code, PPC_BR_TRUE, PPC_BR_EQ, 0);
2031 /* End-of-loop check */
2032 ppc_cmpi (code, 0, sizeof (gpointer) == 8 ? 1 : 0, ppc_r0, 0);
2034 ppc_bc (code, PPC_BR_TRUE, PPC_BR_EQ, 0);
2037 ppc_addi (code, ppc_r12, ppc_r12, 2 * sizeof (gpointer));
2040 mono_ppc_patch (labels [4], labels [1]);
2043 mono_ppc_patch (labels [2], code);
2044 ppc_ldptr (code, ppc_r12, sizeof (gpointer), ppc_r12);
2045 /* r12 now contains the value of the vtable slot */
2046 /* this is not a function descriptor on ppc64 */
2047 ppc_ldptr (code, ppc_r12, 0, ppc_r12);
2048 ppc_mtctr (code, ppc_r12);
2049 ppc_bcctr (code, PPC_BR_ALWAYS, 0);
2052 mono_ppc_patch (labels [3], code);
2056 *tramp_size = code - buf;
2058 emit_bytes (acfg, buf, code - buf);
2060 g_assert_not_reached ();
2065 * arch_emit_gsharedvt_arg_trampoline:
2067 * Emit code for a gsharedvt arg trampoline. OFFSET is the offset of the first of
2068 * two GOT slots which contain the argument, and the code to jump to.
2069 * TRAMP_SIZE is set to the size of the emitted trampoline.
2070 * These kinds of trampolines cannot be enumerated statically, since there could
2071 * be one trampoline per method instantiation, so we emit the same code for all
2072 * trampolines, and parameterize them using two GOT slots.
2075 arch_emit_gsharedvt_arg_trampoline (MonoAotCompile *acfg, int offset, int *tramp_size)
2077 #if defined(TARGET_X86)
2081 /* Similar to the PPC code above */
2083 g_assert (MONO_ARCH_RGCTX_REG != X86_ECX);
2086 /* Load mscorlib got address */
2087 x86_mov_reg_membase (code, X86_ECX, MONO_ARCH_GOT_REG, sizeof (gpointer), 4);
2089 x86_mov_reg_membase (code, X86_EAX, X86_ECX, offset * sizeof (gpointer), 4);
2090 /* Branch to the target address */
2091 x86_jump_membase (code, X86_ECX, (offset + 1) * sizeof (gpointer));
2093 #ifdef __native_client_codegen__
2095 /* emit nops to next 32 byte alignment */
2096 int a = (~kNaClAlignmentMask) & ((code - buf) + kNaClAlignment - 1);
2097 while (code < (buf + a)) x86_nop(code);
2101 emit_bytes (acfg, buf, code - buf);
2103 *tramp_size = NACL_SIZE (15, kNaClAlignment);
2104 g_assert (code - buf == *tramp_size);
2105 #elif defined(TARGET_ARM)
2109 /* The same as mono_arch_get_gsharedvt_arg_trampoline (), but for AOT */
2110 /* Similar to arch_emit_specific_trampoline () */
2113 ARM_PUSH (code, (1 << ARMREG_R0) | (1 << ARMREG_R1) | (1 << ARMREG_R2) | (1 << ARMREG_R3));
2114 ARM_LDR_IMM (code, ARMREG_R1, ARMREG_PC, 8);
2115 /* Load the arg value from the GOT */
2116 ARM_LDR_REG_REG (code, ARMREG_R0, ARMREG_PC, ARMREG_R1);
2117 /* Load the addr from the GOT */
2118 ARM_LDR_REG_REG (code, ARMREG_R1, ARMREG_PC, ARMREG_R1);
2120 ARM_BX (code, ARMREG_R1);
2122 g_assert (code - buf == 20);
2125 emit_bytes (acfg, buf, code - buf);
2126 emit_symbol_diff (acfg, acfg->got_symbol, ".", (offset * sizeof (gpointer)) + 4);
2127 #elif defined(TARGET_ARM64)
2128 arm64_emit_gsharedvt_arg_trampoline (acfg, offset, tramp_size);
2130 g_assert_not_reached ();
2135 arch_emit_autoreg (MonoAotCompile *acfg, char *symbol)
2137 #if defined(TARGET_POWERPC) && defined(__mono_ilp32__)
2138 /* Based on code generated by gcc */
2139 emit_unset_mode (acfg);
2142 #if defined(_MSC_VER) || defined(MONO_CROSS_COMPILE)
2143 ".section .ctors,\"aw\",@progbits\n"
2147 ".section .opd,\"aw\"\n"
2150 ".long .%s,.TOC.@tocbase32\n"
2153 ".type .%s,@function\n"
2155 ".%s:\n", symbol, symbol, symbol, symbol, symbol, symbol, symbol, symbol);
2157 ".section .ctors,\"aw\",@progbits\n"
2161 ".section .opd,\"aw\"\n"
2164 ".long .%1$s,.TOC.@tocbase32\n"
2165 ".size %1$s,.-%1$s\n"
2167 ".type .%1$s,@function\n"
2169 ".%1$s:\n", symbol);
2180 "lis 3, .Lglobals@h\n"
2181 "ori 3, 3, .Lglobals@l\n"
2182 "bl .mono_aot_register_module\n"
2190 #if defined(_MSC_VER) || defined(MONO_CROSS_COMPILE)
2192 ".size .%s,.-.%s\n", symbol, symbol);
2195 ".size .%1$s,.-.%1$s\n", symbol);
2201 /* END OF ARCH SPECIFIC CODE */
2204 mono_get_field_token (MonoClassField *field)
2206 MonoClass *klass = field->parent;
2209 for (i = 0; i < klass->field.count; ++i) {
2210 if (field == &klass->fields [i])
2211 return MONO_TOKEN_FIELD_DEF | (klass->field.first + 1 + i);
2214 g_assert_not_reached ();
2219 encode_value (gint32 value, guint8 *buf, guint8 **endbuf)
2223 //printf ("ENCODE: %d 0x%x.\n", value, value);
2226 * Same encoding as the one used in the metadata, extended to handle values
2227 * greater than 0x1fffffff.
2229 if ((value >= 0) && (value <= 127))
2231 else if ((value >= 0) && (value <= 16383)) {
2232 p [0] = 0x80 | (value >> 8);
2233 p [1] = value & 0xff;
2235 } else if ((value >= 0) && (value <= 0x1fffffff)) {
2236 p [0] = (value >> 24) | 0xc0;
2237 p [1] = (value >> 16) & 0xff;
2238 p [2] = (value >> 8) & 0xff;
2239 p [3] = value & 0xff;
2244 p [1] = (value >> 24) & 0xff;
2245 p [2] = (value >> 16) & 0xff;
2246 p [3] = (value >> 8) & 0xff;
2247 p [4] = value & 0xff;
2255 stream_init (MonoDynamicStream *sh)
2258 sh->alloc_size = 4096;
2259 sh->data = g_malloc (4096);
2261 /* So offsets are > 0 */
2267 make_room_in_stream (MonoDynamicStream *stream, int size)
2269 if (size <= stream->alloc_size)
2272 while (stream->alloc_size <= size) {
2273 if (stream->alloc_size < 4096)
2274 stream->alloc_size = 4096;
2276 stream->alloc_size *= 2;
2279 stream->data = g_realloc (stream->data, stream->alloc_size);
2283 add_stream_data (MonoDynamicStream *stream, const char *data, guint32 len)
2287 make_room_in_stream (stream, stream->index + len);
2288 memcpy (stream->data + stream->index, data, len);
2289 idx = stream->index;
2290 stream->index += len;
2297 * Add data to the binary blob inside the aot image. Returns the offset inside the
2298 * blob where the data was stored.
2301 add_to_blob (MonoAotCompile *acfg, const guint8 *data, guint32 data_len)
2303 if (acfg->blob.alloc_size == 0)
2304 stream_init (&acfg->blob);
2306 return add_stream_data (&acfg->blob, (char*)data, data_len);
2310 add_to_blob_aligned (MonoAotCompile *acfg, const guint8 *data, guint32 data_len, guint32 align)
2315 if (acfg->blob.alloc_size == 0)
2316 stream_init (&acfg->blob);
2318 count = acfg->blob.index % align;
2320 /* we assume the stream data will be aligned */
2322 add_stream_data (&acfg->blob, buf, 4 - count);
2324 return add_stream_data (&acfg->blob, (char*)data, data_len);
2328 * emit_offset_table:
2330 * Emit a table of increasing offsets in a compact form using differential encoding.
2331 * There is an index entry for each GROUP_SIZE number of entries. The greater the
2332 * group size, the more compact the table becomes, but the slower it becomes to compute
2333 * a given entry. Returns the size of the table.
2336 emit_offset_table (MonoAotCompile *acfg, int noffsets, int group_size, gint32 *offsets)
2338 gint32 current_offset;
2339 int i, buf_size, ngroups, index_entry_size;
2341 guint32 *index_offsets;
2343 ngroups = (noffsets + (group_size - 1)) / group_size;
2345 index_offsets = g_new0 (guint32, ngroups);
2347 buf_size = noffsets * 4;
2348 p = buf = g_malloc0 (buf_size);
2351 for (i = 0; i < noffsets; ++i) {
2352 //printf ("D: %d -> %d\n", i, offsets [i]);
2353 if ((i % group_size) == 0) {
2354 index_offsets [i / group_size] = p - buf;
2355 /* Emit the full value for these entries */
2356 encode_value (offsets [i], p, &p);
2358 /* The offsets are allowed to be non-increasing */
2359 //g_assert (offsets [i] >= current_offset);
2360 encode_value (offsets [i] - current_offset, p, &p);
2362 current_offset = offsets [i];
2365 if (ngroups && index_offsets [ngroups - 1] < 65000)
2366 index_entry_size = 2;
2368 index_entry_size = 4;
2370 /* Emit the header */
2371 emit_int32 (acfg, noffsets);
2372 emit_int32 (acfg, group_size);
2373 emit_int32 (acfg, ngroups);
2374 emit_int32 (acfg, index_entry_size);
2376 /* Emit the index */
2377 for (i = 0; i < ngroups; ++i) {
2378 if (index_entry_size == 2)
2379 emit_int16 (acfg, index_offsets [i]);
2381 emit_int32 (acfg, index_offsets [i]);
2385 emit_bytes (acfg, buf, p - buf);
2387 return (int)(p - buf) + (ngroups * 4);
2391 get_image_index (MonoAotCompile *cfg, MonoImage *image)
2395 index = GPOINTER_TO_UINT (g_hash_table_lookup (cfg->image_hash, image));
2399 index = g_hash_table_size (cfg->image_hash);
2400 g_hash_table_insert (cfg->image_hash, image, GUINT_TO_POINTER (index + 1));
2401 g_ptr_array_add (cfg->image_table, image);
2407 find_typespec_for_class (MonoAotCompile *acfg, MonoClass *klass)
2410 int len = acfg->image->tables [MONO_TABLE_TYPESPEC].rows;
2412 /* FIXME: Search referenced images as well */
2413 if (!acfg->typespec_classes) {
2414 acfg->typespec_classes = mono_mempool_alloc0 (acfg->mempool, sizeof (MonoClass*) * len);
2415 for (i = 0; i < len; ++i) {
2417 acfg->typespec_classes [i] = mono_class_get_and_inflate_typespec_checked (acfg->image, MONO_TOKEN_TYPE_SPEC | (i + 1), NULL, &error);
2418 g_assert (mono_error_ok (&error)); /* FIXME error handling */
2421 for (i = 0; i < len; ++i) {
2422 if (acfg->typespec_classes [i] == klass)
2427 return MONO_TOKEN_TYPE_SPEC | (i + 1);
2433 encode_method_ref (MonoAotCompile *acfg, MonoMethod *method, guint8 *buf, guint8 **endbuf);
2436 encode_klass_ref (MonoAotCompile *acfg, MonoClass *klass, guint8 *buf, guint8 **endbuf);
2439 encode_ginst (MonoAotCompile *acfg, MonoGenericInst *inst, guint8 *buf, guint8 **endbuf);
2442 encode_type (MonoAotCompile *acfg, MonoType *t, guint8 *buf, guint8 **endbuf);
2445 encode_klass_ref_inner (MonoAotCompile *acfg, MonoClass *klass, guint8 *buf, guint8 **endbuf)
2450 * The encoding begins with one of the MONO_AOT_TYPEREF values, followed by additional
2454 if (klass->generic_class) {
2456 g_assert (klass->type_token);
2458 /* Find a typespec for a class if possible */
2459 token = find_typespec_for_class (acfg, klass);
2461 encode_value (MONO_AOT_TYPEREF_TYPESPEC_TOKEN, p, &p);
2462 encode_value (token, p, &p);
2464 MonoClass *gclass = klass->generic_class->container_class;
2465 MonoGenericInst *inst = klass->generic_class->context.class_inst;
2466 static int count = 0;
2469 encode_value (MONO_AOT_TYPEREF_GINST, p, &p);
2470 encode_klass_ref (acfg, gclass, p, &p);
2471 encode_ginst (acfg, inst, p, &p);
2475 } else if (klass->type_token) {
2476 int iindex = get_image_index (acfg, klass->image);
2478 g_assert (mono_metadata_token_code (klass->type_token) == MONO_TOKEN_TYPE_DEF);
2480 encode_value (MONO_AOT_TYPEREF_TYPEDEF_INDEX, p, &p);
2481 encode_value (klass->type_token - MONO_TOKEN_TYPE_DEF, p, &p);
2483 encode_value (MONO_AOT_TYPEREF_TYPEDEF_INDEX_IMAGE, p, &p);
2484 encode_value (klass->type_token - MONO_TOKEN_TYPE_DEF, p, &p);
2485 encode_value (get_image_index (acfg, klass->image), p, &p);
2487 } else if ((klass->byval_arg.type == MONO_TYPE_VAR) || (klass->byval_arg.type == MONO_TYPE_MVAR)) {
2488 MonoGenericContainer *container = mono_type_get_generic_param_owner (&klass->byval_arg);
2489 MonoGenericParam *par = klass->byval_arg.data.generic_param;
2491 encode_value (MONO_AOT_TYPEREF_VAR, p, &p);
2492 encode_value (klass->byval_arg.type, p, &p);
2493 encode_value (mono_type_get_generic_param_num (&klass->byval_arg), p, &p);
2495 encode_value (container ? 1 : 0, p, &p);
2497 encode_value (container->is_method, p, &p);
2498 g_assert (par->serial == 0);
2499 if (container->is_method)
2500 encode_method_ref (acfg, container->owner.method, p, &p);
2502 encode_klass_ref (acfg, container->owner.klass, p, &p);
2504 encode_value (par->serial, p, &p);
2506 } else if (klass->byval_arg.type == MONO_TYPE_PTR) {
2507 encode_value (MONO_AOT_TYPEREF_PTR, p, &p);
2508 encode_type (acfg, &klass->byval_arg, p, &p);
2511 g_assert (klass->rank > 0);
2512 encode_value (MONO_AOT_TYPEREF_ARRAY, p, &p);
2513 encode_value (klass->rank, p, &p);
2514 encode_klass_ref (acfg, klass->element_class, p, &p);
2522 * Encode a reference to KLASS. We use our home-grown encoding instead of the
2523 * standard metadata encoding.
2526 encode_klass_ref (MonoAotCompile *acfg, MonoClass *klass, guint8 *buf, guint8 **endbuf)
2528 gboolean shared = FALSE;
2531 * The encoding of generic instances is large so emit them only once.
2533 if (klass->generic_class) {
2535 g_assert (klass->type_token);
2537 /* Find a typespec for a class if possible */
2538 token = find_typespec_for_class (acfg, klass);
2541 } else if ((klass->byval_arg.type == MONO_TYPE_VAR) || (klass->byval_arg.type == MONO_TYPE_MVAR)) {
2546 guint offset = GPOINTER_TO_UINT (g_hash_table_lookup (acfg->klass_blob_hash, klass));
2550 buf2 = g_malloc (1024);
2553 encode_klass_ref_inner (acfg, klass, p, &p);
2554 g_assert (p - buf2 < 1024);
2556 offset = add_to_blob (acfg, buf2, p - buf2);
2559 g_hash_table_insert (acfg->klass_blob_hash, klass, GUINT_TO_POINTER (offset + 1));
2565 encode_value (MONO_AOT_TYPEREF_BLOB_INDEX, p, &p);
2566 encode_value (offset, p, &p);
2571 encode_klass_ref_inner (acfg, klass, buf, endbuf);
2575 encode_field_info (MonoAotCompile *cfg, MonoClassField *field, guint8 *buf, guint8 **endbuf)
2577 guint32 token = mono_get_field_token (field);
2580 encode_klass_ref (cfg, field->parent, p, &p);
2581 g_assert (mono_metadata_token_code (token) == MONO_TOKEN_FIELD_DEF);
2582 encode_value (token - MONO_TOKEN_FIELD_DEF, p, &p);
2587 encode_ginst (MonoAotCompile *acfg, MonoGenericInst *inst, guint8 *buf, guint8 **endbuf)
2592 encode_value (inst->type_argc, p, &p);
2593 for (i = 0; i < inst->type_argc; ++i)
2594 encode_klass_ref (acfg, mono_class_from_mono_type (inst->type_argv [i]), p, &p);
2599 encode_generic_context (MonoAotCompile *acfg, MonoGenericContext *context, guint8 *buf, guint8 **endbuf)
2602 MonoGenericInst *inst;
2604 inst = context->class_inst;
2606 g_assert (inst->type_argc);
2607 encode_ginst (acfg, inst, p, &p);
2609 encode_value (0, p, &p);
2611 inst = context->method_inst;
2613 g_assert (inst->type_argc);
2614 encode_ginst (acfg, inst, p, &p);
2616 encode_value (0, p, &p);
2622 encode_type (MonoAotCompile *acfg, MonoType *t, guint8 *buf, guint8 **endbuf)
2626 g_assert (t->num_mods == 0);
2627 /* t->attrs can be ignored */
2628 //g_assert (t->attrs == 0);
2631 *p = MONO_TYPE_PINNED;
2635 *p = MONO_TYPE_BYREF;
2643 case MONO_TYPE_VOID:
2644 case MONO_TYPE_BOOLEAN:
2645 case MONO_TYPE_CHAR:
2658 case MONO_TYPE_STRING:
2659 case MONO_TYPE_OBJECT:
2660 case MONO_TYPE_TYPEDBYREF:
2662 case MONO_TYPE_VALUETYPE:
2663 case MONO_TYPE_CLASS:
2664 encode_klass_ref (acfg, mono_class_from_mono_type (t), p, &p);
2666 case MONO_TYPE_SZARRAY:
2667 encode_klass_ref (acfg, t->data.klass, p, &p);
2670 encode_type (acfg, t->data.type, p, &p);
2672 case MONO_TYPE_GENERICINST: {
2673 MonoClass *gclass = t->data.generic_class->container_class;
2674 MonoGenericInst *inst = t->data.generic_class->context.class_inst;
2676 encode_klass_ref (acfg, gclass, p, &p);
2677 encode_ginst (acfg, inst, p, &p);
2680 case MONO_TYPE_ARRAY: {
2681 MonoArrayType *array = t->data.array;
2684 encode_klass_ref (acfg, array->eklass, p, &p);
2685 encode_value (array->rank, p, &p);
2686 encode_value (array->numsizes, p, &p);
2687 for (i = 0; i < array->numsizes; ++i)
2688 encode_value (array->sizes [i], p, &p);
2689 encode_value (array->numlobounds, p, &p);
2690 for (i = 0; i < array->numlobounds; ++i)
2691 encode_value (array->lobounds [i], p, &p);
2695 case MONO_TYPE_MVAR:
2696 encode_klass_ref (acfg, mono_class_from_mono_type (t), p, &p);
2699 g_assert_not_reached ();
2706 encode_signature (MonoAotCompile *acfg, MonoMethodSignature *sig, guint8 *buf, guint8 **endbuf)
2712 /* Similar to the metadata encoding */
2713 if (sig->generic_param_count)
2717 if (sig->explicit_this)
2719 flags |= (sig->call_convention & 0x0F);
2723 if (sig->generic_param_count)
2724 encode_value (sig->generic_param_count, p, &p);
2725 encode_value (sig->param_count, p, &p);
2727 encode_type (acfg, sig->ret, p, &p);
2728 for (i = 0; i < sig->param_count; ++i) {
2729 if (sig->sentinelpos == i) {
2730 *p = MONO_TYPE_SENTINEL;
2733 encode_type (acfg, sig->params [i], p, &p);
2739 #define MAX_IMAGE_INDEX 250
2742 encode_method_ref (MonoAotCompile *acfg, MonoMethod *method, guint8 *buf, guint8 **endbuf)
2744 guint32 image_index = get_image_index (acfg, method->klass->image);
2745 guint32 token = method->token;
2746 MonoJumpInfoToken *ji;
2750 * The encoding for most methods is as follows:
2751 * - image index encoded as a leb128
2752 * - token index encoded as a leb128
2753 * Values of image index >= MONO_AOT_METHODREF_MIN are used to mark additional
2754 * types of method encodings.
2757 /* Mark methods which can't use aot trampolines because they need the further
2758 * processing in mono_magic_trampoline () which requires a MonoMethod*.
2760 if ((method->is_generic && (method->flags & METHOD_ATTRIBUTE_VIRTUAL)) ||
2761 (method->iflags & METHOD_IMPL_ATTRIBUTE_SYNCHRONIZED))
2762 encode_value ((MONO_AOT_METHODREF_NO_AOT_TRAMPOLINE << 24), p, &p);
2764 if (method->wrapper_type) {
2765 encode_value ((MONO_AOT_METHODREF_WRAPPER << 24), p, &p);
2767 encode_value (method->wrapper_type, p, &p);
2769 switch (method->wrapper_type) {
2770 case MONO_WRAPPER_REMOTING_INVOKE:
2771 case MONO_WRAPPER_REMOTING_INVOKE_WITH_CHECK:
2772 case MONO_WRAPPER_XDOMAIN_INVOKE: {
2775 m = mono_marshal_method_from_wrapper (method);
2777 encode_method_ref (acfg, m, p, &p);
2780 case MONO_WRAPPER_PROXY_ISINST:
2781 case MONO_WRAPPER_LDFLD:
2782 case MONO_WRAPPER_LDFLDA:
2783 case MONO_WRAPPER_STFLD:
2784 case MONO_WRAPPER_ISINST: {
2785 WrapperInfo *info = mono_marshal_get_wrapper_info (method);
2788 encode_klass_ref (acfg, info->d.proxy.klass, p, &p);
2791 case MONO_WRAPPER_LDFLD_REMOTE:
2792 case MONO_WRAPPER_STFLD_REMOTE:
2794 case MONO_WRAPPER_ALLOC: {
2795 AllocatorWrapperInfo *info = mono_marshal_get_wrapper_info (method);
2797 /* The GC name is saved once in MonoAotFileInfo */
2798 g_assert (info->alloc_type != -1);
2799 encode_value (info->alloc_type, p, &p);
2802 case MONO_WRAPPER_WRITE_BARRIER:
2804 case MONO_WRAPPER_STELEMREF: {
2805 WrapperInfo *info = mono_marshal_get_wrapper_info (method);
2808 encode_value (info->subtype, p, &p);
2809 if (info->subtype == WRAPPER_SUBTYPE_VIRTUAL_STELEMREF)
2810 encode_value (info->d.virtual_stelemref.kind, p, &p);
2813 case MONO_WRAPPER_UNKNOWN: {
2814 WrapperInfo *info = mono_marshal_get_wrapper_info (method);
2817 encode_value (info->subtype, p, &p);
2818 if (info->subtype == WRAPPER_SUBTYPE_PTR_TO_STRUCTURE ||
2819 info->subtype == WRAPPER_SUBTYPE_STRUCTURE_TO_PTR)
2820 encode_klass_ref (acfg, method->klass, p, &p);
2821 else if (info->subtype == WRAPPER_SUBTYPE_SYNCHRONIZED_INNER)
2822 encode_method_ref (acfg, info->d.synchronized_inner.method, p, &p);
2823 else if (info->subtype == WRAPPER_SUBTYPE_ARRAY_ACCESSOR)
2824 encode_method_ref (acfg, info->d.array_accessor.method, p, &p);
2827 case MONO_WRAPPER_MANAGED_TO_NATIVE: {
2828 WrapperInfo *info = mono_marshal_get_wrapper_info (method);
2831 encode_value (info->subtype, p, &p);
2832 if (info->subtype == WRAPPER_SUBTYPE_ICALL_WRAPPER) {
2833 strcpy ((char*)p, method->name);
2834 p += strlen (method->name) + 1;
2835 } else if (info->subtype == WRAPPER_SUBTYPE_NATIVE_FUNC_AOT) {
2836 encode_method_ref (acfg, info->d.managed_to_native.method, p, &p);
2838 g_assert (info->subtype == WRAPPER_SUBTYPE_NONE || info->subtype == WRAPPER_SUBTYPE_PINVOKE);
2839 encode_method_ref (acfg, info->d.managed_to_native.method, p, &p);
2843 case MONO_WRAPPER_SYNCHRONIZED: {
2846 m = mono_marshal_method_from_wrapper (method);
2848 g_assert (m != method);
2849 encode_method_ref (acfg, m, p, &p);
2852 case MONO_WRAPPER_MANAGED_TO_MANAGED: {
2853 WrapperInfo *info = mono_marshal_get_wrapper_info (method);
2856 encode_value (info->subtype, p, &p);
2858 if (info->subtype == WRAPPER_SUBTYPE_ELEMENT_ADDR) {
2859 encode_value (info->d.element_addr.rank, p, &p);
2860 encode_value (info->d.element_addr.elem_size, p, &p);
2861 } else if (info->subtype == WRAPPER_SUBTYPE_STRING_CTOR) {
2862 encode_method_ref (acfg, info->d.string_ctor.method, p, &p);
2864 g_assert_not_reached ();
2868 case MONO_WRAPPER_CASTCLASS: {
2869 WrapperInfo *info = mono_marshal_get_wrapper_info (method);
2872 encode_value (info->subtype, p, &p);
2875 case MONO_WRAPPER_RUNTIME_INVOKE: {
2876 WrapperInfo *info = mono_marshal_get_wrapper_info (method);
2879 encode_value (info->subtype, p, &p);
2880 if (info->subtype == WRAPPER_SUBTYPE_RUNTIME_INVOKE_DIRECT || info->subtype == WRAPPER_SUBTYPE_RUNTIME_INVOKE_VIRTUAL)
2881 encode_method_ref (acfg, info->d.runtime_invoke.method, p, &p);
2882 else if (info->subtype == WRAPPER_SUBTYPE_RUNTIME_INVOKE_NORMAL)
2883 encode_signature (acfg, info->d.runtime_invoke.sig, p, &p);
2886 case MONO_WRAPPER_DELEGATE_INVOKE:
2887 case MONO_WRAPPER_DELEGATE_BEGIN_INVOKE:
2888 case MONO_WRAPPER_DELEGATE_END_INVOKE: {
2889 if (method->is_inflated) {
2890 /* These wrappers are identified by their class */
2891 encode_value (1, p, &p);
2892 encode_klass_ref (acfg, method->klass, p, &p);
2894 MonoMethodSignature *sig = mono_method_signature (method);
2895 WrapperInfo *info = mono_marshal_get_wrapper_info (method);
2897 encode_value (0, p, &p);
2898 if (method->wrapper_type == MONO_WRAPPER_DELEGATE_INVOKE)
2899 encode_value (info ? info->subtype : 0, p, &p);
2900 encode_signature (acfg, sig, p, &p);
2904 case MONO_WRAPPER_NATIVE_TO_MANAGED: {
2905 WrapperInfo *info = mono_marshal_get_wrapper_info (method);
2908 encode_method_ref (acfg, info->d.native_to_managed.method, p, &p);
2909 encode_klass_ref (acfg, info->d.native_to_managed.klass, p, &p);
2913 g_assert_not_reached ();
2915 } else if (mono_method_signature (method)->is_inflated) {
2917 * This is a generic method, find the original token which referenced it and
2919 * Obtain the token from information recorded by the JIT.
2921 ji = g_hash_table_lookup (acfg->token_info_hash, method);
2923 image_index = get_image_index (acfg, ji->image);
2924 g_assert (image_index < MAX_IMAGE_INDEX);
2927 encode_value ((MONO_AOT_METHODREF_METHODSPEC << 24), p, &p);
2928 encode_value (image_index, p, &p);
2929 encode_value (token, p, &p);
2931 MonoMethod *declaring;
2932 MonoGenericContext *context = mono_method_get_context (method);
2934 g_assert (method->is_inflated);
2935 declaring = ((MonoMethodInflated*)method)->declaring;
2938 * This might be a non-generic method of a generic instance, which
2939 * doesn't have a token since the reference is generated by the JIT
2940 * like Nullable:Box/Unbox, or by generic sharing.
2942 encode_value ((MONO_AOT_METHODREF_GINST << 24), p, &p);
2943 /* Encode the klass */
2944 encode_klass_ref (acfg, method->klass, p, &p);
2945 /* Encode the method */
2946 image_index = get_image_index (acfg, method->klass->image);
2947 g_assert (image_index < MAX_IMAGE_INDEX);
2948 g_assert (declaring->token);
2949 token = declaring->token;
2950 g_assert (mono_metadata_token_table (token) == MONO_TABLE_METHOD);
2951 encode_value (image_index, p, &p);
2952 encode_value (token, p, &p);
2953 encode_generic_context (acfg, context, p, &p);
2955 } else if (token == 0) {
2956 /* This might be a method of a constructed type like int[,].Set */
2957 /* Obtain the token from information recorded by the JIT */
2958 ji = g_hash_table_lookup (acfg->token_info_hash, method);
2960 image_index = get_image_index (acfg, ji->image);
2961 g_assert (image_index < MAX_IMAGE_INDEX);
2964 encode_value ((MONO_AOT_METHODREF_METHODSPEC << 24), p, &p);
2965 encode_value (image_index, p, &p);
2966 encode_value (token, p, &p);
2969 g_assert (method->klass->rank);
2971 /* Encode directly */
2972 encode_value ((MONO_AOT_METHODREF_ARRAY << 24), p, &p);
2973 encode_klass_ref (acfg, method->klass, p, &p);
2974 if (!strcmp (method->name, ".ctor") && mono_method_signature (method)->param_count == method->klass->rank)
2975 encode_value (0, p, &p);
2976 else if (!strcmp (method->name, ".ctor") && mono_method_signature (method)->param_count == method->klass->rank * 2)
2977 encode_value (1, p, &p);
2978 else if (!strcmp (method->name, "Get"))
2979 encode_value (2, p, &p);
2980 else if (!strcmp (method->name, "Address"))
2981 encode_value (3, p, &p);
2982 else if (!strcmp (method->name, "Set"))
2983 encode_value (4, p, &p);
2985 g_assert_not_reached ();
2988 g_assert (mono_metadata_token_table (token) == MONO_TABLE_METHOD);
2990 if (image_index >= MONO_AOT_METHODREF_MIN) {
2991 encode_value ((MONO_AOT_METHODREF_LARGE_IMAGE_INDEX << 24), p, &p);
2992 encode_value (image_index, p, &p);
2993 encode_value (mono_metadata_token_index (token), p, &p);
2995 encode_value ((image_index << 24) | mono_metadata_token_index (token), p, &p);
3002 compare_patches (gconstpointer a, gconstpointer b)
3006 i = (*(MonoJumpInfo**)a)->ip.i;
3007 j = (*(MonoJumpInfo**)b)->ip.i;
3018 static G_GNUC_UNUSED char*
3019 patch_to_string (MonoJumpInfo *patch_info)
3023 str = g_string_new ("");
3025 g_string_append_printf (str, "%s(", get_patch_name (patch_info->type));
3027 switch (patch_info->type) {
3028 case MONO_PATCH_INFO_VTABLE:
3029 mono_type_get_desc (str, &patch_info->data.klass->byval_arg, TRUE);
3034 g_string_append_printf (str, ")");
3035 return g_string_free (str, FALSE);
3041 * Return whenever PATCH_INFO refers to a direct call, and thus requires a
3044 static inline gboolean
3045 is_plt_patch (MonoJumpInfo *patch_info)
3047 switch (patch_info->type) {
3048 case MONO_PATCH_INFO_METHOD:
3049 case MONO_PATCH_INFO_INTERNAL_METHOD:
3050 case MONO_PATCH_INFO_JIT_ICALL_ADDR:
3051 case MONO_PATCH_INFO_ICALL_ADDR:
3052 case MONO_PATCH_INFO_CLASS_INIT:
3053 case MONO_PATCH_INFO_RGCTX_FETCH:
3054 case MONO_PATCH_INFO_GENERIC_CLASS_INIT:
3055 case MONO_PATCH_INFO_MONITOR_ENTER:
3056 case MONO_PATCH_INFO_MONITOR_ENTER_V4:
3057 case MONO_PATCH_INFO_MONITOR_EXIT:
3058 case MONO_PATCH_INFO_LLVM_IMT_TRAMPOLINE:
3068 * Return the symbol identifying the plt entry PLT_OFFSET.
3071 get_plt_symbol (MonoAotCompile *acfg, int plt_offset, MonoJumpInfo *patch_info)
3075 * The Apple linker reorganizes object files, so it doesn't like branches to local
3076 * labels, since those have no relocations.
3078 return g_strdup_printf ("%sp_%d", acfg->llvm_label_prefix, plt_offset);
3080 return g_strdup_printf ("%sp_%d", acfg->temp_prefix, plt_offset);
3087 * Return a PLT entry which belongs to the method identified by PATCH_INFO.
3089 static MonoPltEntry*
3090 get_plt_entry (MonoAotCompile *acfg, MonoJumpInfo *patch_info)
3094 if (!is_plt_patch (patch_info))
3097 if (!acfg->patch_to_plt_entry [patch_info->type])
3098 acfg->patch_to_plt_entry [patch_info->type] = g_hash_table_new (mono_patch_info_hash, mono_patch_info_equal);
3099 res = g_hash_table_lookup (acfg->patch_to_plt_entry [patch_info->type], patch_info);
3101 if (!acfg->llvm && patch_info->type == MONO_PATCH_INFO_METHOD && (patch_info->data.method->iflags & METHOD_IMPL_ATTRIBUTE_SYNCHRONIZED)) {
3103 * Allocate a separate PLT slot for each such patch, since some plt
3104 * entries will refer to the method itself, and some will refer to the
3111 MonoJumpInfo *new_ji;
3113 new_ji = mono_patch_info_dup_mp (acfg->mempool, patch_info);
3115 res = mono_mempool_alloc0 (acfg->mempool, sizeof (MonoPltEntry));
3116 res->plt_offset = acfg->plt_offset;
3118 res->symbol = get_plt_symbol (acfg, res->plt_offset, patch_info);
3119 if (acfg->aot_opts.write_symbols)
3120 res->debug_sym = get_plt_entry_debug_sym (acfg, res->ji, acfg->plt_entry_debug_sym_cache);
3122 res->llvm_symbol = g_strdup_printf ("%s_%s_llvm", res->symbol, res->debug_sym);
3124 res->llvm_symbol = g_strdup_printf ("%s_llvm", res->symbol);
3126 g_hash_table_insert (acfg->patch_to_plt_entry [new_ji->type], new_ji, res);
3128 g_hash_table_insert (acfg->plt_offset_to_entry, GUINT_TO_POINTER (res->plt_offset), res);
3130 //g_assert (mono_patch_info_equal (patch_info, new_ji));
3131 //mono_print_ji (patch_info); printf ("\n");
3132 //g_hash_table_print_stats (acfg->patch_to_plt_entry);
3134 acfg->plt_offset ++;
3143 * Returns the offset of the GOT slot where the runtime object resulting from resolving
3144 * JI could be found if it exists, otherwise allocates a new one.
3147 get_got_offset (MonoAotCompile *acfg, gboolean llvm, MonoJumpInfo *ji)
3150 GotInfo *info = llvm ? &acfg->llvm_got_info : &acfg->got_info;
3152 got_offset = GPOINTER_TO_UINT (g_hash_table_lookup (info->patch_to_got_offset_by_type [ji->type], ji));
3154 return got_offset - 1;
3157 got_offset = acfg->llvm_got_offset;
3158 acfg->llvm_got_offset ++;
3160 got_offset = acfg->got_offset;
3161 acfg->got_offset ++;
3164 acfg->stats.got_slots ++;
3165 acfg->stats.got_slot_types [ji->type] ++;
3167 g_hash_table_insert (info->patch_to_got_offset, ji, GUINT_TO_POINTER (got_offset + 1));
3168 g_hash_table_insert (info->patch_to_got_offset_by_type [ji->type], ji, GUINT_TO_POINTER (got_offset + 1));
3169 g_ptr_array_add (info->got_patches, ji);
3174 /* Add a method to the list of methods which need to be emitted */
3176 add_method_with_index (MonoAotCompile *acfg, MonoMethod *method, int index, gboolean extra)
3179 if (!g_hash_table_lookup (acfg->method_indexes, method)) {
3180 g_ptr_array_add (acfg->methods, method);
3181 g_hash_table_insert (acfg->method_indexes, method, GUINT_TO_POINTER (index + 1));
3182 acfg->nmethods = acfg->methods->len + 1;
3185 if (method->wrapper_type || extra)
3186 g_ptr_array_add (acfg->extra_methods, method);
3190 get_method_index (MonoAotCompile *acfg, MonoMethod *method)
3192 int index = GPOINTER_TO_UINT (g_hash_table_lookup (acfg->method_indexes, method));
3200 add_method_full (MonoAotCompile *acfg, MonoMethod *method, gboolean extra, int depth)
3204 index = GPOINTER_TO_UINT (g_hash_table_lookup (acfg->method_indexes, method));
3208 index = acfg->method_index;
3209 add_method_with_index (acfg, method, index, extra);
3211 g_ptr_array_add (acfg->method_order, GUINT_TO_POINTER (index));
3213 g_hash_table_insert (acfg->method_depth, method, GUINT_TO_POINTER (depth));
3215 acfg->method_index ++;
3221 add_method (MonoAotCompile *acfg, MonoMethod *method)
3223 return add_method_full (acfg, method, FALSE, 0);
3227 add_extra_method_with_depth (MonoAotCompile *acfg, MonoMethod *method, int depth)
3229 if (mono_method_is_generic_sharable_full (method, FALSE, TRUE, FALSE))
3230 method = mini_get_shared_method (method);
3232 if (acfg->aot_opts.log_generics)
3233 aot_printf (acfg, "%*sAdding method %s.\n", depth, "", mono_method_full_name (method, TRUE));
3235 add_method_full (acfg, method, TRUE, depth);
3239 add_extra_method (MonoAotCompile *acfg, MonoMethod *method)
3241 add_extra_method_with_depth (acfg, method, 0);
3245 add_jit_icall_wrapper (gpointer key, gpointer value, gpointer user_data)
3247 MonoAotCompile *acfg = user_data;
3248 MonoJitICallInfo *callinfo = value;
3249 MonoMethod *wrapper;
3255 name = g_strdup_printf ("__icall_wrapper_%s", callinfo->name);
3256 wrapper = mono_marshal_get_icall_wrapper (callinfo->sig, name, callinfo->func, check_for_pending_exc);
3259 add_method (acfg, wrapper);
3263 get_runtime_invoke_sig (MonoMethodSignature *sig)
3265 MonoMethodBuilder *mb;
3268 mb = mono_mb_new (mono_defaults.object_class, "FOO", MONO_WRAPPER_NONE);
3269 m = mono_mb_create_method (mb, sig, 16);
3270 return mono_marshal_get_runtime_invoke (m, FALSE);
3274 can_marshal_struct (MonoClass *klass)
3276 MonoClassField *field;
3277 gboolean can_marshal = TRUE;
3278 gpointer iter = NULL;
3279 MonoMarshalType *info;
3282 if ((klass->flags & TYPE_ATTRIBUTE_LAYOUT_MASK) == TYPE_ATTRIBUTE_AUTO_LAYOUT)
3285 info = mono_marshal_load_type_info (klass);
3287 /* Only allow a few field types to avoid asserts in the marshalling code */
3288 while ((field = mono_class_get_fields (klass, &iter))) {
3289 if ((field->type->attrs & FIELD_ATTRIBUTE_STATIC))
3292 switch (field->type->type) {
3297 case MONO_TYPE_BOOLEAN:
3300 case MONO_TYPE_CHAR:
3308 case MONO_TYPE_STRING:
3310 case MONO_TYPE_VALUETYPE:
3311 if (!mono_class_from_mono_type (field->type)->enumtype && !can_marshal_struct (mono_class_from_mono_type (field->type)))
3312 can_marshal = FALSE;
3314 case MONO_TYPE_SZARRAY: {
3315 gboolean has_mspec = FALSE;
3318 for (i = 0; i < info->num_fields; ++i) {
3319 if (info->fields [i].field == field && info->fields [i].mspec)
3324 can_marshal = FALSE;
3328 can_marshal = FALSE;
3334 /* Its hard to compute whenever these can be marshalled or not */
3335 if (!strcmp (klass->name_space, "System.Net.NetworkInformation.MacOsStructs") && strcmp (klass->name, "sockaddr_dl"))
3342 create_gsharedvt_inst (MonoAotCompile *acfg, MonoMethod *method, MonoGenericContext *ctx)
3344 /* Create a vtype instantiation */
3345 MonoGenericContext shared_context;
3347 MonoGenericInst *inst;
3348 MonoGenericContainer *container;
3349 MonoClass **constraints;
3352 memset (ctx, 0, sizeof (MonoGenericContext));
3354 if (method->klass->generic_container) {
3355 shared_context = method->klass->generic_container->context;
3356 inst = shared_context.class_inst;
3358 args = g_new0 (MonoType*, inst->type_argc);
3359 for (i = 0; i < inst->type_argc; ++i) {
3360 args [i] = &mono_defaults.int_class->byval_arg;
3362 ctx->class_inst = mono_metadata_get_generic_inst (inst->type_argc, args);
3364 if (method->is_generic) {
3365 container = mono_method_get_generic_container (method);
3366 shared_context = container->context;
3367 inst = shared_context.method_inst;
3369 args = g_new0 (MonoType*, inst->type_argc);
3370 for (i = 0; i < container->type_argc; ++i) {
3371 MonoGenericParamInfo *info = &container->type_params [i].info;
3372 gboolean ref_only = FALSE;
3374 if (info && info->constraints) {
3375 constraints = info->constraints;
3377 while (*constraints) {
3378 MonoClass *cklass = *constraints;
3379 if (!(cklass == mono_defaults.object_class || (cklass->image == mono_defaults.corlib && !strcmp (cklass->name, "ValueType"))))
3380 /* Inflaring the method with our vtype would not be valid */
3387 args [i] = &mono_defaults.object_class->byval_arg;
3389 args [i] = &mono_defaults.int_class->byval_arg;
3391 ctx->method_inst = mono_metadata_get_generic_inst (inst->type_argc, args);
3396 add_wrappers (MonoAotCompile *acfg)
3398 MonoMethod *method, *m;
3400 MonoMethodSignature *sig, *csig;
3404 * FIXME: Instead of AOTing all the wrappers, it might be better to redesign them
3405 * so there is only one wrapper of a given type, or inlining their contents into their
3408 for (i = 0; i < acfg->image->tables [MONO_TABLE_METHOD].rows; ++i) {
3410 guint32 token = MONO_TOKEN_METHOD_DEF | (i + 1);
3411 gboolean skip = FALSE;
3413 method = mono_get_method (acfg->image, token, NULL);
3415 if ((method->flags & METHOD_ATTRIBUTE_PINVOKE_IMPL) ||
3416 (method->iflags & METHOD_IMPL_ATTRIBUTE_RUNTIME) ||
3417 (method->flags & METHOD_ATTRIBUTE_ABSTRACT))
3420 /* Skip methods which can not be handled by get_runtime_invoke () */
3421 sig = mono_method_signature (method);
3424 if ((sig->ret->type == MONO_TYPE_PTR) ||
3425 (sig->ret->type == MONO_TYPE_TYPEDBYREF))
3427 if (mono_class_is_open_constructed_type (sig->ret))
3430 for (j = 0; j < sig->param_count; j++) {
3431 if (sig->params [j]->type == MONO_TYPE_TYPEDBYREF)
3433 if (mono_class_is_open_constructed_type (sig->params [j]))
3437 #ifdef MONO_ARCH_DYN_CALL_SUPPORTED
3438 if (!mono_class_is_contextbound (method->klass)) {
3439 MonoDynCallInfo *info = mono_arch_dyn_call_prepare (sig);
3440 gboolean has_nullable = FALSE;
3442 for (j = 0; j < sig->param_count; j++) {
3443 if (sig->params [j]->type == MONO_TYPE_GENERICINST && mono_class_is_nullable (mono_class_from_mono_type (sig->params [j])))
3444 has_nullable = TRUE;
3447 if (info && !has_nullable) {
3448 /* Supported by the dynamic runtime-invoke wrapper */
3452 mono_arch_dyn_call_free (info);
3457 //printf ("%s\n", mono_method_full_name (method, TRUE));
3458 add_method (acfg, mono_marshal_get_runtime_invoke (method, FALSE));
3462 if (strcmp (acfg->image->assembly->aname.name, "mscorlib") == 0) {
3465 /* Runtime invoke wrappers */
3467 /* void runtime-invoke () [.cctor] */
3468 csig = mono_metadata_signature_alloc (mono_defaults.corlib, 0);
3469 csig->ret = &mono_defaults.void_class->byval_arg;
3470 add_method (acfg, get_runtime_invoke_sig (csig));
3472 /* void runtime-invoke () [Finalize] */
3473 csig = mono_metadata_signature_alloc (mono_defaults.corlib, 0);
3475 csig->ret = &mono_defaults.void_class->byval_arg;
3476 add_method (acfg, get_runtime_invoke_sig (csig));
3478 /* void runtime-invoke (string) [exception ctor] */
3479 csig = mono_metadata_signature_alloc (mono_defaults.corlib, 1);
3481 csig->ret = &mono_defaults.void_class->byval_arg;
3482 csig->params [0] = &mono_defaults.string_class->byval_arg;
3483 add_method (acfg, get_runtime_invoke_sig (csig));
3485 /* void runtime-invoke (string, string) [exception ctor] */
3486 csig = mono_metadata_signature_alloc (mono_defaults.corlib, 2);
3488 csig->ret = &mono_defaults.void_class->byval_arg;
3489 csig->params [0] = &mono_defaults.string_class->byval_arg;
3490 csig->params [1] = &mono_defaults.string_class->byval_arg;
3491 add_method (acfg, get_runtime_invoke_sig (csig));
3493 /* string runtime-invoke () [Exception.ToString ()] */
3494 csig = mono_metadata_signature_alloc (mono_defaults.corlib, 0);
3496 csig->ret = &mono_defaults.string_class->byval_arg;
3497 add_method (acfg, get_runtime_invoke_sig (csig));
3499 /* void runtime-invoke (string, Exception) [exception ctor] */
3500 csig = mono_metadata_signature_alloc (mono_defaults.corlib, 2);
3502 csig->ret = &mono_defaults.void_class->byval_arg;
3503 csig->params [0] = &mono_defaults.string_class->byval_arg;
3504 csig->params [1] = &mono_defaults.exception_class->byval_arg;
3505 add_method (acfg, get_runtime_invoke_sig (csig));
3507 /* Assembly runtime-invoke (string, bool) [DoAssemblyResolve] */
3508 csig = mono_metadata_signature_alloc (mono_defaults.corlib, 2);
3510 csig->ret = &(mono_class_from_name (
3511 mono_defaults.corlib, "System.Reflection", "Assembly"))->byval_arg;
3512 csig->params [0] = &mono_defaults.string_class->byval_arg;
3513 csig->params [1] = &mono_defaults.boolean_class->byval_arg;
3514 add_method (acfg, get_runtime_invoke_sig (csig));
3516 /* runtime-invoke used by finalizers */
3517 add_method (acfg, mono_marshal_get_runtime_invoke (mono_class_get_method_from_name_flags (mono_defaults.object_class, "Finalize", 0, 0), TRUE));
3519 /* This is used by mono_runtime_capture_context () */
3520 method = mono_get_context_capture_method ();
3522 add_method (acfg, mono_marshal_get_runtime_invoke (method, FALSE));
3524 #ifdef MONO_ARCH_DYN_CALL_SUPPORTED
3525 add_method (acfg, mono_marshal_get_runtime_invoke_dynamic ());
3529 add_method (acfg, mono_marshal_get_stelemref ());
3531 if (MONO_ARCH_HAVE_TLS_GET) {
3532 /* Managed Allocators */
3533 nallocators = mono_gc_get_managed_allocator_types ();
3534 for (i = 0; i < nallocators; ++i) {
3535 m = mono_gc_get_managed_allocator_by_type (i);
3537 add_method (acfg, m);
3541 /* Stelemref wrappers */
3543 MonoMethod **wrappers;
3546 wrappers = mono_marshal_get_virtual_stelemref_wrappers (&nwrappers);
3547 for (i = 0; i < nwrappers; ++i)
3548 add_method (acfg, wrappers [i]);
3552 /* castclass_with_check wrapper */
3553 add_method (acfg, mono_marshal_get_castclass_with_cache ());
3554 /* isinst_with_check wrapper */
3555 add_method (acfg, mono_marshal_get_isinst_with_cache ());
3557 /* JIT icall wrappers */
3558 /* FIXME: locking - this is "safe" as full-AOT threads don't mutate the icall hash*/
3559 g_hash_table_foreach (mono_get_jit_icall_info (), add_jit_icall_wrapper, acfg);
3563 * remoting-invoke-with-check wrappers are very frequent, so avoid emitting them,
3564 * we use the original method instead at runtime.
3565 * Since full-aot doesn't support remoting, this is not a problem.
3568 /* remoting-invoke wrappers */
3569 for (i = 0; i < acfg->image->tables [MONO_TABLE_METHOD].rows; ++i) {
3570 MonoMethodSignature *sig;
3572 token = MONO_TOKEN_METHOD_DEF | (i + 1);
3573 method = mono_get_method (acfg->image, token, NULL);
3575 sig = mono_method_signature (method);
3577 if (sig->hasthis && (method->klass->marshalbyref || method->klass == mono_defaults.object_class)) {
3578 m = mono_marshal_get_remoting_invoke_with_check (method);
3580 add_method (acfg, m);
3585 /* delegate-invoke wrappers */
3586 for (i = 0; i < acfg->image->tables [MONO_TABLE_TYPEDEF].rows; ++i) {
3589 MonoCustomAttrInfo *cattr;
3591 token = MONO_TOKEN_TYPE_DEF | (i + 1);
3592 klass = mono_class_get_checked (acfg->image, token, &error);
3595 mono_error_cleanup (&error);
3599 if (!klass->delegate || klass == mono_defaults.delegate_class || klass == mono_defaults.multicastdelegate_class)
3602 if (!klass->generic_container) {
3603 method = mono_get_delegate_invoke (klass);
3605 m = mono_marshal_get_delegate_invoke (method, NULL);
3607 add_method (acfg, m);
3609 method = mono_class_get_method_from_name_flags (klass, "BeginInvoke", -1, 0);
3611 add_method (acfg, mono_marshal_get_delegate_begin_invoke (method));
3613 method = mono_class_get_method_from_name_flags (klass, "EndInvoke", -1, 0);
3615 add_method (acfg, mono_marshal_get_delegate_end_invoke (method));
3617 cattr = mono_custom_attrs_from_class (klass);
3622 for (j = 0; j < cattr->num_attrs; ++j)
3623 if (cattr->attrs [j].ctor && (!strcmp (cattr->attrs [j].ctor->klass->name, "MonoNativeFunctionWrapperAttribute") || !strcmp (cattr->attrs [j].ctor->klass->name, "UnmanagedFunctionPointerAttribute")))
3625 if (j < cattr->num_attrs)
3626 add_method (acfg, mono_marshal_get_native_func_wrapper_aot (klass));
3628 } else if ((acfg->opts & MONO_OPT_GSHAREDVT) && klass->generic_container) {
3630 MonoGenericContext ctx;
3631 MonoMethod *inst, *gshared;
3634 * Emit gsharedvt versions of the generic delegate-invoke wrappers
3637 method = mono_get_delegate_invoke (klass);
3638 create_gsharedvt_inst (acfg, method, &ctx);
3640 inst = mono_class_inflate_generic_method_checked (method, &ctx, &error);
3641 g_assert (mono_error_ok (&error)); /* FIXME don't swallow the error */
3643 m = mono_marshal_get_delegate_invoke (inst, NULL);
3644 g_assert (m->is_inflated);
3646 gshared = mini_get_shared_method_full (m, FALSE, TRUE);
3647 add_extra_method (acfg, gshared);
3650 method = mono_get_delegate_begin_invoke (klass);
3651 create_gsharedvt_inst (acfg, method, &ctx);
3653 inst = mono_class_inflate_generic_method_checked (method, &ctx, &error);
3654 g_assert (mono_error_ok (&error)); /* FIXME don't swallow the error */
3656 m = mono_marshal_get_delegate_begin_invoke (inst);
3657 g_assert (m->is_inflated);
3659 gshared = mini_get_shared_method_full (m, FALSE, TRUE);
3660 add_extra_method (acfg, gshared);
3663 method = mono_get_delegate_end_invoke (klass);
3664 create_gsharedvt_inst (acfg, method, &ctx);
3666 inst = mono_class_inflate_generic_method_checked (method, &ctx, &error);
3667 g_assert (mono_error_ok (&error)); /* FIXME don't swallow the error */
3669 m = mono_marshal_get_delegate_end_invoke (inst);
3670 g_assert (m->is_inflated);
3672 gshared = mini_get_shared_method_full (m, FALSE, TRUE);
3673 add_extra_method (acfg, gshared);
3678 /* array access wrappers */
3679 for (i = 0; i < acfg->image->tables [MONO_TABLE_TYPESPEC].rows; ++i) {
3683 token = MONO_TOKEN_TYPE_SPEC | (i + 1);
3684 klass = mono_class_get_checked (acfg->image, token, &error);
3687 mono_error_cleanup (&error);
3691 if (klass->rank && MONO_TYPE_IS_PRIMITIVE (&klass->element_class->byval_arg)) {
3692 MonoMethod *m, *wrapper;
3694 /* Add runtime-invoke wrappers too */
3696 m = mono_class_get_method_from_name (klass, "Get", -1);
3698 wrapper = mono_marshal_get_array_accessor_wrapper (m);
3699 add_extra_method (acfg, wrapper);
3700 add_extra_method (acfg, mono_marshal_get_runtime_invoke (wrapper, FALSE));
3702 m = mono_class_get_method_from_name (klass, "Set", -1);
3704 wrapper = mono_marshal_get_array_accessor_wrapper (m);
3705 add_extra_method (acfg, wrapper);
3706 add_extra_method (acfg, mono_marshal_get_runtime_invoke (wrapper, FALSE));
3710 /* Synchronized wrappers */
3711 for (i = 0; i < acfg->image->tables [MONO_TABLE_METHOD].rows; ++i) {
3712 token = MONO_TOKEN_METHOD_DEF | (i + 1);
3713 method = mono_get_method (acfg->image, token, NULL);
3715 if (method->iflags & METHOD_IMPL_ATTRIBUTE_SYNCHRONIZED) {
3716 if (method->is_generic) {
3718 } else if ((acfg->opts & MONO_OPT_GSHAREDVT) && method->klass->generic_container) {
3720 MonoGenericContext ctx;
3721 MonoMethod *inst, *gshared, *m;
3724 * Create a generic wrapper for a generic instance, and AOT that.
3726 create_gsharedvt_inst (acfg, method, &ctx);
3727 inst = mono_class_inflate_generic_method_checked (method, &ctx, &error);
3728 g_assert (mono_error_ok (&error)); /* FIXME don't swallow the error */
3729 m = mono_marshal_get_synchronized_wrapper (inst);
3730 g_assert (m->is_inflated);
3731 gshared = mini_get_shared_method_full (m, FALSE, TRUE);
3732 add_method (acfg, gshared);
3734 add_method (acfg, mono_marshal_get_synchronized_wrapper (method));
3739 /* pinvoke wrappers */
3740 for (i = 0; i < acfg->image->tables [MONO_TABLE_METHOD].rows; ++i) {
3742 guint32 token = MONO_TOKEN_METHOD_DEF | (i + 1);
3744 method = mono_get_method (acfg->image, token, NULL);
3746 if ((method->flags & METHOD_ATTRIBUTE_PINVOKE_IMPL) ||
3747 (method->iflags & METHOD_IMPL_ATTRIBUTE_INTERNAL_CALL)) {
3748 add_method (acfg, mono_marshal_get_native_wrapper (method, TRUE, TRUE));
3752 /* native-to-managed wrappers */
3753 for (i = 0; i < acfg->image->tables [MONO_TABLE_METHOD].rows; ++i) {
3755 guint32 token = MONO_TOKEN_METHOD_DEF | (i + 1);
3756 MonoCustomAttrInfo *cattr;
3759 method = mono_get_method (acfg->image, token, NULL);
3762 * Only generate native-to-managed wrappers for methods which have an
3763 * attribute named MonoPInvokeCallbackAttribute. We search for the attribute by
3764 * name to avoid defining a new assembly to contain it.
3766 cattr = mono_custom_attrs_from_method (method);
3769 for (j = 0; j < cattr->num_attrs; ++j)
3770 if (cattr->attrs [j].ctor && !strcmp (cattr->attrs [j].ctor->klass->name, "MonoPInvokeCallbackAttribute"))
3772 if (j < cattr->num_attrs) {
3773 MonoCustomAttrEntry *e = &cattr->attrs [j];
3774 MonoMethodSignature *sig = mono_method_signature (e->ctor);
3775 const char *p = (const char*)e->data;
3777 int slen, num_named, named_type, data_type;
3781 char *export_name = NULL;
3782 MonoMethod *wrapper;
3784 /* this cannot be enforced by the C# compiler so we must give the user some warning before aborting */
3785 if (!(method->flags & METHOD_ATTRIBUTE_STATIC)) {
3786 g_warning ("AOT restriction: Method '%s' must be static since it is decorated with [MonoPInvokeCallback]. See http://ios.xamarin.com/Documentation/Limitations#Reverse_Callbacks",
3787 mono_method_full_name (method, TRUE));
3791 g_assert (sig->param_count == 1);
3792 g_assert (sig->params [0]->type == MONO_TYPE_CLASS && !strcmp (mono_class_from_mono_type (sig->params [0])->name, "Type"));
3795 * Decode the cattr manually since we can't create objects
3796 * during aot compilation.
3802 /* From load_cattr_value () in reflection.c */
3803 slen = mono_metadata_decode_value (p, &p);
3804 n = g_memdup (p, slen + 1);
3806 t = mono_reflection_type_from_name (n, acfg->image);
3810 klass = mono_class_from_mono_type (t);
3811 g_assert (klass->parent == mono_defaults.multicastdelegate_class);
3815 num_named = read16 (p);
3818 g_assert (num_named < 2);
3819 if (num_named == 1) {
3822 MonoType *prop_type;
3824 /* parse ExportSymbol attribute */
3826 named_type = *named;
3831 name_len = mono_metadata_decode_blob_size (named, &named);
3832 name = g_malloc (name_len + 1);
3833 memcpy (name, named, name_len);
3834 name [name_len] = 0;
3837 g_assert (named_type == 0x54);
3838 g_assert (!strcmp (name, "ExportSymbol"));
3840 prop_type = &mono_defaults.string_class->byval_arg;
3842 /* load_cattr_value (), string case */
3843 g_assert (*named != (char)0xff);
3844 slen = mono_metadata_decode_value (named, &named);
3845 export_name = g_malloc (slen + 1);
3846 memcpy (export_name, named, slen);
3847 export_name [slen] = 0;
3851 wrapper = mono_marshal_get_managed_wrapper (method, klass, 0);
3852 add_method (acfg, wrapper);
3854 g_hash_table_insert (acfg->export_names, wrapper, export_name);
3858 if ((method->flags & METHOD_ATTRIBUTE_PINVOKE_IMPL) ||
3859 (method->iflags & METHOD_IMPL_ATTRIBUTE_INTERNAL_CALL)) {
3860 add_method (acfg, mono_marshal_get_native_wrapper (method, TRUE, TRUE));
3864 /* StructureToPtr/PtrToStructure wrappers */
3865 for (i = 0; i < acfg->image->tables [MONO_TABLE_TYPEDEF].rows; ++i) {
3869 token = MONO_TOKEN_TYPE_DEF | (i + 1);
3870 klass = mono_class_get_checked (acfg->image, token, &error);
3873 mono_error_cleanup (&error);
3877 if (klass->valuetype && !klass->generic_container && can_marshal_struct (klass) &&
3878 !(klass->nested_in && strstr (klass->nested_in->name, "<PrivateImplementationDetails>") == klass->nested_in->name)) {
3879 add_method (acfg, mono_marshal_get_struct_to_ptr (klass));
3880 add_method (acfg, mono_marshal_get_ptr_to_struct (klass));
3886 has_type_vars (MonoClass *klass)
3888 if ((klass->byval_arg.type == MONO_TYPE_VAR) || (klass->byval_arg.type == MONO_TYPE_MVAR))
3891 return has_type_vars (klass->element_class);
3892 if (klass->generic_class) {
3893 MonoGenericContext *context = &klass->generic_class->context;
3894 if (context->class_inst) {
3897 for (i = 0; i < context->class_inst->type_argc; ++i)
3898 if (has_type_vars (mono_class_from_mono_type (context->class_inst->type_argv [i])))
3902 if (klass->generic_container)
3908 is_vt_inst (MonoGenericInst *inst)
3912 for (i = 0; i < inst->type_argc; ++i) {
3913 MonoType *t = inst->type_argv [i];
3914 if (MONO_TYPE_ISSTRUCT (t) || t->type == MONO_TYPE_VALUETYPE)
3921 method_has_type_vars (MonoMethod *method)
3923 if (has_type_vars (method->klass))
3926 if (method->is_inflated) {
3927 MonoGenericContext *context = mono_method_get_context (method);
3928 if (context->method_inst) {
3931 for (i = 0; i < context->method_inst->type_argc; ++i)
3932 if (has_type_vars (mono_class_from_mono_type (context->method_inst->type_argv [i])))
3939 static void add_generic_class_with_depth (MonoAotCompile *acfg, MonoClass *klass, int depth, const char *ref);
3942 add_generic_class (MonoAotCompile *acfg, MonoClass *klass, gboolean force, const char *ref)
3944 /* This might lead to a huge code blowup so only do it if neccesary */
3945 if (!acfg->aot_opts.full_aot && !force)
3948 add_generic_class_with_depth (acfg, klass, 0, ref);
3952 check_type_depth (MonoType *t, int depth)
3960 case MONO_TYPE_GENERICINST: {
3961 MonoGenericClass *gklass = t->data.generic_class;
3962 MonoGenericInst *ginst = gklass->context.class_inst;
3965 for (i = 0; i < ginst->type_argc; ++i) {
3966 if (check_type_depth (ginst->type_argv [i], depth + 1))
3980 add_types_from_method_header (MonoAotCompile *acfg, MonoMethod *method);
3983 * add_generic_class:
3985 * Add all methods of a generic class.
3988 add_generic_class_with_depth (MonoAotCompile *acfg, MonoClass *klass, int depth, const char *ref)
3991 MonoClassField *field;
3993 gboolean use_gsharedvt = FALSE;
3995 if (!acfg->ginst_hash)
3996 acfg->ginst_hash = g_hash_table_new (NULL, NULL);
3998 mono_class_init (klass);
4000 if (klass->generic_class && klass->generic_class->context.class_inst->is_open)
4003 if (has_type_vars (klass))
4006 if (!klass->generic_class && !klass->rank)
4009 if (klass->exception_type)
4012 if (!acfg->ginst_hash)
4013 acfg->ginst_hash = g_hash_table_new (NULL, NULL);
4015 if (g_hash_table_lookup (acfg->ginst_hash, klass))
4018 if (check_type_depth (&klass->byval_arg, 0))
4021 if (acfg->aot_opts.log_generics)
4022 aot_printf (acfg, "%*sAdding generic instance %s [%s].\n", depth, "", mono_type_full_name (&klass->byval_arg), ref);
4024 g_hash_table_insert (acfg->ginst_hash, klass, klass);
4027 * Use gsharedvt for generic collections with vtype arguments to avoid code blowup.
4028 * Enable this only for some classes since gsharedvt might not support all methods.
4030 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) &&
4031 (!strcmp (klass->name, "Dictionary`2") || !strcmp (klass->name, "List`1") || !strcmp (klass->name, "ReadOnlyCollection`1")))
4032 use_gsharedvt = TRUE;
4035 while ((method = mono_class_get_methods (klass, &iter))) {
4036 if ((acfg->opts & MONO_OPT_GSHAREDVT) && method->is_inflated && mono_method_get_context (method)->method_inst) {
4038 * This is partial sharing, and we can't handle it yet
4043 if (mono_method_is_generic_sharable_full (method, FALSE, FALSE, use_gsharedvt)) {
4045 add_types_from_method_header (acfg, method);
4049 if (method->is_generic)
4054 * FIXME: Instances which are referenced by these methods are not added,
4055 * for example Array.Resize<int> for List<int>.Add ().
4057 add_extra_method_with_depth (acfg, method, depth + 1);
4061 while ((field = mono_class_get_fields (klass, &iter))) {
4062 if (field->type->type == MONO_TYPE_GENERICINST)
4063 add_generic_class_with_depth (acfg, mono_class_from_mono_type (field->type), depth + 1, "field");
4066 if (klass->delegate) {
4067 method = mono_get_delegate_invoke (klass);
4069 method = mono_marshal_get_delegate_invoke (method, NULL);
4071 if (acfg->aot_opts.log_generics)
4072 aot_printf (acfg, "%*sAdding method %s.\n", depth, "", mono_method_full_name (method, TRUE));
4074 add_method (acfg, method);
4077 /* Add superclasses */
4079 add_generic_class_with_depth (acfg, klass->parent, depth, "parent");
4082 * For ICollection<T>, add instances of the helper methods
4083 * in Array, since a T[] could be cast to ICollection<T>.
4085 if (klass->image == mono_defaults.corlib && !strcmp (klass->name_space, "System.Collections.Generic") &&
4086 (!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"))) {
4087 MonoClass *tclass = mono_class_from_mono_type (klass->generic_class->context.class_inst->type_argv [0]);
4088 MonoClass *array_class = mono_bounded_array_class_get (tclass, 1, FALSE);
4092 if (!strcmp (klass->name, "IEnumerator`1"))
4093 name_prefix = g_strdup_printf ("%s.%s", klass->name_space, "IEnumerable`1");
4095 name_prefix = g_strdup_printf ("%s.%s", klass->name_space, klass->name);
4097 /* Add the T[]/InternalEnumerator class */
4098 if (!strcmp (klass->name, "IEnumerable`1") || !strcmp (klass->name, "IEnumerator`1")) {
4102 while ((nclass = mono_class_get_nested_types (array_class->parent, &iter))) {
4103 if (!strcmp (nclass->name, "InternalEnumerator`1"))
4107 nclass = mono_class_inflate_generic_class (nclass, mono_generic_class_get_context (klass->generic_class));
4108 add_generic_class (acfg, nclass, FALSE, "ICollection<T>");
4112 while ((method = mono_class_get_methods (array_class, &iter))) {
4113 if (strstr (method->name, name_prefix)) {
4114 MonoMethod *m = mono_aot_get_array_helper_from_wrapper (method);
4116 add_extra_method_with_depth (acfg, m, depth);
4120 g_free (name_prefix);
4123 /* Add an instance of GenericComparer<T> which is created dynamically by Comparer<T> */
4124 if (klass->image == mono_defaults.corlib && !strcmp (klass->name_space, "System.Collections.Generic") && !strcmp (klass->name, "Comparer`1")) {
4125 MonoClass *tclass = mono_class_from_mono_type (klass->generic_class->context.class_inst->type_argv [0]);
4126 MonoClass *icomparable, *gcomparer;
4127 MonoGenericContext ctx;
4128 MonoType *args [16];
4130 memset (&ctx, 0, sizeof (ctx));
4132 icomparable = mono_class_from_name (mono_defaults.corlib, "System", "IComparable`1");
4133 g_assert (icomparable);
4134 args [0] = &tclass->byval_arg;
4135 ctx.class_inst = mono_metadata_get_generic_inst (1, args);
4137 if (mono_class_is_assignable_from (mono_class_inflate_generic_class (icomparable, &ctx), tclass)) {
4138 gcomparer = mono_class_from_name (mono_defaults.corlib, "System.Collections.Generic", "GenericComparer`1");
4139 g_assert (gcomparer);
4140 add_generic_class (acfg, mono_class_inflate_generic_class (gcomparer, &ctx), FALSE, "Comparer<T>");
4144 /* Add an instance of GenericEqualityComparer<T> which is created dynamically by EqualityComparer<T> */
4145 if (klass->image == mono_defaults.corlib && !strcmp (klass->name_space, "System.Collections.Generic") && !strcmp (klass->name, "EqualityComparer`1")) {
4146 MonoClass *tclass = mono_class_from_mono_type (klass->generic_class->context.class_inst->type_argv [0]);
4147 MonoClass *iface, *gcomparer;
4148 MonoGenericContext ctx;
4149 MonoType *args [16];
4151 memset (&ctx, 0, sizeof (ctx));
4153 iface = mono_class_from_name (mono_defaults.corlib, "System", "IEquatable`1");
4155 args [0] = &tclass->byval_arg;
4156 ctx.class_inst = mono_metadata_get_generic_inst (1, args);
4158 if (mono_class_is_assignable_from (mono_class_inflate_generic_class (iface, &ctx), tclass)) {
4159 gcomparer = mono_class_from_name (mono_defaults.corlib, "System.Collections.Generic", "GenericEqualityComparer`1");
4160 g_assert (gcomparer);
4161 add_generic_class (acfg, mono_class_inflate_generic_class (gcomparer, &ctx), FALSE, "EqualityComparer<T>");
4167 add_instances_of (MonoAotCompile *acfg, MonoClass *klass, MonoType **insts, int ninsts, gboolean force)
4170 MonoGenericContext ctx;
4171 MonoType *args [16];
4173 if (acfg->aot_opts.no_instances)
4176 memset (&ctx, 0, sizeof (ctx));
4178 for (i = 0; i < ninsts; ++i) {
4179 args [0] = insts [i];
4180 ctx.class_inst = mono_metadata_get_generic_inst (1, args);
4181 add_generic_class (acfg, mono_class_inflate_generic_class (klass, &ctx), force, "");
4186 add_types_from_method_header (MonoAotCompile *acfg, MonoMethod *method)
4188 MonoMethodHeader *header;
4189 MonoMethodSignature *sig;
4192 depth = GPOINTER_TO_UINT (g_hash_table_lookup (acfg->method_depth, method));
4194 sig = mono_method_signature (method);
4197 for (j = 0; j < sig->param_count; ++j)
4198 if (sig->params [j]->type == MONO_TYPE_GENERICINST)
4199 add_generic_class_with_depth (acfg, mono_class_from_mono_type (sig->params [j]), depth + 1, "arg");
4202 header = mono_method_get_header (method);
4205 for (j = 0; j < header->num_locals; ++j)
4206 if (header->locals [j]->type == MONO_TYPE_GENERICINST)
4207 add_generic_class_with_depth (acfg, mono_class_from_mono_type (header->locals [j]), depth + 1, "local");
4209 mono_loader_clear_error ();
4214 * add_generic_instances:
4216 * Add instances referenced by the METHODSPEC/TYPESPEC table.
4219 add_generic_instances (MonoAotCompile *acfg)
4224 MonoGenericContext *context;
4226 if (acfg->aot_opts.no_instances)
4229 for (i = 0; i < acfg->image->tables [MONO_TABLE_METHODSPEC].rows; ++i) {
4230 token = MONO_TOKEN_METHOD_SPEC | (i + 1);
4231 method = mono_get_method (acfg->image, token, NULL);
4236 if (method->klass->image != acfg->image)
4239 context = mono_method_get_context (method);
4241 if (context && ((context->class_inst && context->class_inst->is_open)))
4245 * For open methods, create an instantiation which can be passed to the JIT.
4246 * FIXME: Handle class_inst as well.
4248 if (context && context->method_inst && context->method_inst->is_open) {
4250 MonoGenericContext shared_context;
4251 MonoGenericInst *inst;
4252 MonoType **type_argv;
4254 MonoMethod *declaring_method;
4255 gboolean supported = TRUE;
4257 /* Check that the context doesn't contain open constructed types */
4258 if (context->class_inst) {
4259 inst = context->class_inst;
4260 for (i = 0; i < inst->type_argc; ++i) {
4261 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)
4263 if (mono_class_is_open_constructed_type (inst->type_argv [i]))
4267 if (context->method_inst) {
4268 inst = context->method_inst;
4269 for (i = 0; i < inst->type_argc; ++i) {
4270 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)
4272 if (mono_class_is_open_constructed_type (inst->type_argv [i]))
4280 memset (&shared_context, 0, sizeof (MonoGenericContext));
4282 inst = context->class_inst;
4284 type_argv = g_new0 (MonoType*, inst->type_argc);
4285 for (i = 0; i < inst->type_argc; ++i) {
4286 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 type_argv [i] = &mono_defaults.object_class->byval_arg;
4289 type_argv [i] = inst->type_argv [i];
4292 shared_context.class_inst = mono_metadata_get_generic_inst (inst->type_argc, type_argv);
4296 inst = context->method_inst;
4298 type_argv = g_new0 (MonoType*, inst->type_argc);
4299 for (i = 0; i < inst->type_argc; ++i) {
4300 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)
4301 type_argv [i] = &mono_defaults.object_class->byval_arg;
4303 type_argv [i] = inst->type_argv [i];
4306 shared_context.method_inst = mono_metadata_get_generic_inst (inst->type_argc, type_argv);
4310 if (method->is_generic || method->klass->generic_container)
4311 declaring_method = method;
4313 declaring_method = mono_method_get_declaring_generic_method (method);
4315 method = mono_class_inflate_generic_method_checked (declaring_method, &shared_context, &error);
4316 g_assert (mono_error_ok (&error)); /* FIXME don't swallow the error */
4320 * If the method is fully sharable, it was already added in place of its
4321 * generic definition.
4323 if (mono_method_is_generic_sharable_full (method, FALSE, FALSE, FALSE))
4327 * FIXME: Partially shared methods are not shared here, so we end up with
4328 * many identical methods.
4330 add_extra_method (acfg, method);
4333 for (i = 0; i < acfg->image->tables [MONO_TABLE_TYPESPEC].rows; ++i) {
4337 token = MONO_TOKEN_TYPE_SPEC | (i + 1);
4339 klass = mono_class_get_checked (acfg->image, token, &error);
4340 if (!klass || klass->rank) {
4341 mono_error_cleanup (&error);
4345 add_generic_class (acfg, klass, FALSE, "typespec");
4348 /* Add types of args/locals */
4349 for (i = 0; i < acfg->methods->len; ++i) {
4350 method = g_ptr_array_index (acfg->methods, i);
4351 add_types_from_method_header (acfg, method);
4354 if (acfg->image == mono_defaults.corlib) {
4356 MonoType *insts [256];
4359 insts [ninsts ++] = &mono_defaults.byte_class->byval_arg;
4360 insts [ninsts ++] = &mono_defaults.sbyte_class->byval_arg;
4361 insts [ninsts ++] = &mono_defaults.int16_class->byval_arg;
4362 insts [ninsts ++] = &mono_defaults.uint16_class->byval_arg;
4363 insts [ninsts ++] = &mono_defaults.int32_class->byval_arg;
4364 insts [ninsts ++] = &mono_defaults.uint32_class->byval_arg;
4365 insts [ninsts ++] = &mono_defaults.int64_class->byval_arg;
4366 insts [ninsts ++] = &mono_defaults.uint64_class->byval_arg;
4367 insts [ninsts ++] = &mono_defaults.single_class->byval_arg;
4368 insts [ninsts ++] = &mono_defaults.double_class->byval_arg;
4369 insts [ninsts ++] = &mono_defaults.char_class->byval_arg;
4370 insts [ninsts ++] = &mono_defaults.boolean_class->byval_arg;
4372 /* Add GenericComparer<T> instances for primitive types for Enum.ToString () */
4373 klass = mono_class_from_name (acfg->image, "System.Collections.Generic", "GenericComparer`1");
4375 add_instances_of (acfg, klass, insts, ninsts, TRUE);
4376 klass = mono_class_from_name (acfg->image, "System.Collections.Generic", "GenericEqualityComparer`1");
4378 add_instances_of (acfg, klass, insts, ninsts, TRUE);
4380 /* Add instances of the array generic interfaces for primitive types */
4381 /* This will add instances of the InternalArray_ helper methods in Array too */
4382 klass = mono_class_from_name (acfg->image, "System.Collections.Generic", "ICollection`1");
4384 add_instances_of (acfg, klass, insts, ninsts, TRUE);
4385 klass = mono_class_from_name (acfg->image, "System.Collections.Generic", "IList`1");
4387 add_instances_of (acfg, klass, insts, ninsts, TRUE);
4388 klass = mono_class_from_name (acfg->image, "System.Collections.Generic", "IEnumerable`1");
4390 add_instances_of (acfg, klass, insts, ninsts, TRUE);
4393 * Add a managed-to-native wrapper of Array.GetGenericValueImpl<object>, which is
4394 * used for all instances of GetGenericValueImpl by the AOT runtime.
4397 MonoGenericContext ctx;
4398 MonoType *args [16];
4399 MonoMethod *get_method;
4400 MonoClass *array_klass = mono_array_class_get (mono_defaults.object_class, 1)->parent;
4402 get_method = mono_class_get_method_from_name (array_klass, "GetGenericValueImpl", 2);
4406 memset (&ctx, 0, sizeof (ctx));
4407 args [0] = &mono_defaults.object_class->byval_arg;
4408 ctx.method_inst = mono_metadata_get_generic_inst (1, args);
4409 add_extra_method (acfg, mono_marshal_get_native_wrapper (mono_class_inflate_generic_method_checked (get_method, &ctx, &error), TRUE, TRUE));
4410 g_assert (mono_error_ok (&error)); /* FIXME don't swallow the error */
4414 /* Same for CompareExchange<T>/Exchange<T> */
4416 MonoGenericContext ctx;
4417 MonoType *args [16];
4419 MonoClass *interlocked_klass = mono_class_from_name (mono_defaults.corlib, "System.Threading", "Interlocked");
4420 gpointer iter = NULL;
4422 while ((m = mono_class_get_methods (interlocked_klass, &iter))) {
4423 if ((!strcmp (m->name, "CompareExchange") || !strcmp (m->name, "Exchange")) && m->is_generic) {
4425 memset (&ctx, 0, sizeof (ctx));
4426 args [0] = &mono_defaults.object_class->byval_arg;
4427 ctx.method_inst = mono_metadata_get_generic_inst (1, args);
4428 add_extra_method (acfg, mono_marshal_get_native_wrapper (mono_class_inflate_generic_method_checked (m, &ctx, &error), TRUE, TRUE));
4429 g_assert (mono_error_ok (&error)); /* FIXME don't swallow the error */
4434 /* Same for Volatile.Read/Write<T> */
4436 MonoGenericContext ctx;
4437 MonoType *args [16];
4439 MonoClass *volatile_klass = mono_class_from_name (mono_defaults.corlib, "System.Threading", "Volatile");
4440 gpointer iter = NULL;
4442 if (volatile_klass) {
4443 while ((m = mono_class_get_methods (volatile_klass, &iter))) {
4444 if ((!strcmp (m->name, "Read") || !strcmp (m->name, "Write")) && m->is_generic) {
4446 memset (&ctx, 0, sizeof (ctx));
4447 args [0] = &mono_defaults.object_class->byval_arg;
4448 ctx.method_inst = mono_metadata_get_generic_inst (1, args);
4449 add_extra_method (acfg, mono_marshal_get_native_wrapper (mono_class_inflate_generic_method_checked (m, &ctx, &error), TRUE, TRUE));
4450 g_assert (mono_error_ok (&error)); /* FIXME don't swallow the error */
4459 * is_direct_callable:
4461 * Return whenever the method identified by JI is directly callable without
4462 * going through the PLT.
4465 is_direct_callable (MonoAotCompile *acfg, MonoMethod *method, MonoJumpInfo *patch_info)
4467 if ((patch_info->type == MONO_PATCH_INFO_METHOD) && (patch_info->data.method->klass->image == acfg->image)) {
4468 MonoCompile *callee_cfg = g_hash_table_lookup (acfg->method_to_cfg, patch_info->data.method);
4470 gboolean direct_callable = TRUE;
4472 if (direct_callable && !(!callee_cfg->has_got_slots && (callee_cfg->method->klass->flags & TYPE_ATTRIBUTE_BEFORE_FIELD_INIT)))
4473 direct_callable = FALSE;
4474 if ((callee_cfg->method->iflags & METHOD_IMPL_ATTRIBUTE_SYNCHRONIZED) && (!method || method->wrapper_type != MONO_WRAPPER_SYNCHRONIZED))
4475 // FIXME: Maybe call the wrapper directly ?
4476 direct_callable = FALSE;
4478 if (acfg->aot_opts.soft_debug || acfg->aot_opts.no_direct_calls) {
4479 /* Disable this so all calls go through load_method (), see the
4480 * mini_get_debug_options ()->load_aot_jit_info_eagerly = TRUE; line in
4481 * mono_debugger_agent_init ().
4483 direct_callable = FALSE;
4486 if (callee_cfg->method->wrapper_type == MONO_WRAPPER_ALLOC)
4487 /* sgen does some initialization when the allocator method is created */
4488 direct_callable = FALSE;
4490 if (direct_callable)
4493 } else if ((patch_info->type == MONO_PATCH_INFO_ICALL_ADDR && patch_info->data.method->flags & METHOD_ATTRIBUTE_PINVOKE_IMPL)) {
4494 if (acfg->aot_opts.direct_pinvoke)
4496 } else if (patch_info->type == MONO_PATCH_INFO_ICALL_ADDR) {
4497 if (acfg->aot_opts.direct_icalls)
4505 #ifdef MONO_ARCH_AOT_SUPPORTED
4507 get_pinvoke_import (MonoAotCompile *acfg, MonoMethod *method)
4509 MonoImage *image = method->klass->image;
4510 MonoMethodPInvoke *piinfo = (MonoMethodPInvoke *) method;
4511 MonoTableInfo *tables = image->tables;
4512 MonoTableInfo *im = &tables [MONO_TABLE_IMPLMAP];
4513 MonoTableInfo *mr = &tables [MONO_TABLE_MODULEREF];
4514 guint32 im_cols [MONO_IMPLMAP_SIZE];
4517 import = g_hash_table_lookup (acfg->method_to_pinvoke_import, method);
4521 if (!piinfo->implmap_idx || piinfo->implmap_idx > im->rows)
4524 mono_metadata_decode_row (im, piinfo->implmap_idx - 1, im_cols, MONO_IMPLMAP_SIZE);
4526 if (!im_cols [MONO_IMPLMAP_SCOPE] || im_cols [MONO_IMPLMAP_SCOPE] > mr->rows)
4529 import = g_strdup_printf ("%s", mono_metadata_string_heap (image, im_cols [MONO_IMPLMAP_NAME]));
4531 g_hash_table_insert (acfg->method_to_pinvoke_import, method, import);
4538 compare_lne (MonoDebugLineNumberEntry *a, MonoDebugLineNumberEntry *b)
4540 if (a->native_offset == b->native_offset)
4541 return a->il_offset - b->il_offset;
4543 return a->native_offset - b->native_offset;
4547 * compute_line_numbers:
4549 * Returns a sparse array of size CODE_SIZE containing MonoDebugSourceLocation* entries for the native offsets which have a corresponding line number
4552 static MonoDebugSourceLocation**
4553 compute_line_numbers (MonoMethod *method, int code_size, MonoDebugMethodJitInfo *debug_info)
4555 MonoDebugMethodInfo *minfo;
4556 MonoDebugLineNumberEntry *ln_array;
4557 MonoDebugSourceLocation *loc;
4558 int i, prev_line, prev_il_offset;
4559 int *native_to_il_offset = NULL;
4560 MonoDebugSourceLocation **res;
4563 minfo = mono_debug_lookup_method (method);
4566 // FIXME: This seems to happen when two methods have the same cfg->method_to_register
4567 if (debug_info->code_size != code_size)
4570 g_assert (code_size);
4572 /* Compute the native->IL offset mapping */
4574 ln_array = g_new0 (MonoDebugLineNumberEntry, debug_info->num_line_numbers);
4575 memcpy (ln_array, debug_info->line_numbers, debug_info->num_line_numbers * sizeof (MonoDebugLineNumberEntry));
4577 qsort (ln_array, debug_info->num_line_numbers, sizeof (MonoDebugLineNumberEntry), (gpointer)compare_lne);
4579 native_to_il_offset = g_new0 (int, code_size + 1);
4581 for (i = 0; i < debug_info->num_line_numbers; ++i) {
4583 MonoDebugLineNumberEntry *lne = &ln_array [i];
4586 for (j = 0; j < lne->native_offset; ++j)
4587 native_to_il_offset [j] = -1;
4590 if (i < debug_info->num_line_numbers - 1) {
4591 MonoDebugLineNumberEntry *lne_next = &ln_array [i + 1];
4593 for (j = lne->native_offset; j < lne_next->native_offset; ++j)
4594 native_to_il_offset [j] = lne->il_offset;
4596 for (j = lne->native_offset; j < code_size; ++j)
4597 native_to_il_offset [j] = lne->il_offset;
4602 /* Compute the native->line number mapping */
4603 res = g_new0 (MonoDebugSourceLocation*, code_size);
4604 prev_il_offset = -1;
4607 for (i = 0; i < code_size; ++i) {
4608 int il_offset = native_to_il_offset [i];
4610 if (il_offset == -1 || il_offset == prev_il_offset)
4612 prev_il_offset = il_offset;
4613 loc = mono_debug_symfile_lookup_location (minfo, il_offset);
4614 if (!(loc && loc->source_file))
4616 if (loc->row == prev_line) {
4617 mono_debug_symfile_free_location (loc);
4620 prev_line = loc->row;
4621 //printf ("D: %s:%d il=%x native=%x\n", loc->source_file, loc->row, il_offset, i);
4623 /* This will cover the prolog too */
4633 get_file_index (MonoAotCompile *acfg, const char *source_file)
4637 // FIXME: Free these
4638 if (!acfg->dwarf_ln_filenames)
4639 acfg->dwarf_ln_filenames = g_hash_table_new (g_str_hash, g_str_equal);
4640 findex = GPOINTER_TO_INT (g_hash_table_lookup (acfg->dwarf_ln_filenames, source_file));
4642 findex = g_hash_table_size (acfg->dwarf_ln_filenames) + 1;
4643 g_hash_table_insert (acfg->dwarf_ln_filenames, g_strdup (source_file), GINT_TO_POINTER (findex));
4644 emit_unset_mode (acfg);
4645 fprintf (acfg->fp, ".file %d \"%s\"\n", findex, mono_dwarf_escape_path (source_file));
4657 * emit_and_reloc_code:
4659 * Emit the native code in CODE, handling relocations along the way. If GOT_ONLY
4660 * is true, calls are made through the GOT too. This is used for emitting trampolines
4661 * in full-aot mode, since calls made from trampolines couldn't go through the PLT,
4662 * since trampolines are needed to make PTL work.
4665 emit_and_reloc_code (MonoAotCompile *acfg, MonoMethod *method, guint8 *code, guint32 code_len, MonoJumpInfo *relocs, gboolean got_only, MonoDebugMethodJitInfo *debug_info)
4667 int i, pindex, start_index, method_index;
4669 MonoJumpInfo *patch_info;
4670 MonoMethodHeader *header;
4671 MonoDebugSourceLocation **locs = NULL;
4673 #ifdef MONO_ARCH_AOT_SUPPORTED
4674 gboolean direct_call, external_call;
4676 const char *direct_call_target = 0;
4677 const char *direct_pinvoke;
4681 header = mono_method_get_header (method);
4683 method_index = get_method_index (acfg, method);
4686 if (acfg->gas_line_numbers && method && debug_info) {
4687 locs = compute_line_numbers (method, code_len, debug_info);
4689 int findex = get_file_index (acfg, "<unknown>");
4690 emit_unset_mode (acfg);
4691 fprintf (acfg->fp, ".loc %d %d 0\n", findex, 1);
4695 /* Collect and sort relocations */
4696 patches = g_ptr_array_new ();
4697 for (patch_info = relocs; patch_info; patch_info = patch_info->next)
4698 g_ptr_array_add (patches, patch_info);
4699 g_ptr_array_sort (patches, compare_patches);
4702 for (i = 0; i < code_len; i += INST_LEN) {
4704 for (pindex = start_index; pindex < patches->len; ++pindex) {
4705 patch_info = g_ptr_array_index (patches, pindex);
4706 if (patch_info->ip.i >= i)
4710 if (locs && locs [i]) {
4711 MonoDebugSourceLocation *loc = locs [i];
4714 findex = get_file_index (acfg, loc->source_file);
4715 emit_unset_mode (acfg);
4716 fprintf (acfg->fp, ".loc %d %d 0\n", findex, loc->row);
4717 mono_debug_symfile_free_location (loc);
4721 #ifdef MONO_ARCH_AOT_SUPPORTED
4722 if (patch_info && (patch_info->ip.i == i) && (pindex < patches->len)) {
4723 start_index = pindex;
4725 switch (patch_info->type) {
4726 case MONO_PATCH_INFO_NONE:
4728 case MONO_PATCH_INFO_GOT_OFFSET: {
4731 arch_emit_got_offset (acfg, code + i, &code_size);
4732 i += code_size - INST_LEN;
4734 patch_info->type = MONO_PATCH_INFO_NONE;
4737 case MONO_PATCH_INFO_OBJC_SELECTOR_REF: {
4738 int code_size, index;
4739 char *selector = (void*)patch_info->data.target;
4741 if (!acfg->objc_selector_to_index)
4742 acfg->objc_selector_to_index = g_hash_table_new (g_str_hash, g_str_equal);
4743 if (!acfg->objc_selectors)
4744 acfg->objc_selectors = g_ptr_array_new ();
4745 index = GPOINTER_TO_UINT (g_hash_table_lookup (acfg->objc_selector_to_index, selector));
4749 index = acfg->objc_selector_index;
4750 g_ptr_array_add (acfg->objc_selectors, (void*)patch_info->data.target);
4751 g_hash_table_insert (acfg->objc_selector_to_index, selector, GUINT_TO_POINTER (index + 1));
4752 acfg->objc_selector_index ++;
4755 arch_emit_objc_selector_ref (acfg, code + i, index, &code_size);
4756 i += code_size - INST_LEN;
4758 patch_info->type = MONO_PATCH_INFO_NONE;
4763 * If this patch is a call, try emitting a direct call instead of
4764 * through a PLT entry. This is possible if the called method is in
4765 * the same assembly and requires no initialization.
4767 direct_call = FALSE;
4768 external_call = FALSE;
4769 if ((patch_info->type == MONO_PATCH_INFO_METHOD) && (patch_info->data.method->klass->image == acfg->image)) {
4770 if (!got_only && is_direct_callable (acfg, method, patch_info)) {
4771 MonoCompile *callee_cfg = g_hash_table_lookup (acfg->method_to_cfg, patch_info->data.method);
4772 //printf ("DIRECT: %s %s\n", method ? mono_method_full_name (method, TRUE) : "", mono_method_full_name (callee_cfg->method, TRUE));
4774 direct_call_target = callee_cfg->asm_symbol;
4775 patch_info->type = MONO_PATCH_INFO_NONE;
4776 acfg->stats.direct_calls ++;
4779 acfg->stats.all_calls ++;
4780 } else if (patch_info->type == MONO_PATCH_INFO_ICALL_ADDR) {
4781 if (!got_only && is_direct_callable (acfg, method, patch_info)) {
4782 if (!(patch_info->data.method->flags & METHOD_ATTRIBUTE_PINVOKE_IMPL))
4783 direct_pinvoke = mono_lookup_icall_symbol (patch_info->data.method);
4785 direct_pinvoke = get_pinvoke_import (acfg, patch_info->data.method);
4786 if (direct_pinvoke) {
4788 g_assert (strlen (direct_pinvoke) < 1000);
4789 direct_call_target = g_strdup_printf ("%s%s", acfg->user_symbol_prefix, direct_pinvoke);
4792 } else if (patch_info->type == MONO_PATCH_INFO_JIT_ICALL_ADDR) {
4793 const char *sym = mono_lookup_jit_icall_symbol (patch_info->data.name);
4794 if (!got_only && sym && acfg->aot_opts.direct_icalls) {
4795 /* Call to a C function implementing a jit icall */
4797 external_call = TRUE;
4798 g_assert (strlen (sym) < 1000);
4799 direct_call_target = g_strdup_printf ("%s%s", acfg->user_symbol_prefix, sym);
4801 } else if (patch_info->type == MONO_PATCH_INFO_INTERNAL_METHOD) {
4802 MonoJitICallInfo *info = mono_find_jit_icall_by_name (patch_info->data.name);
4803 const char *sym = mono_lookup_jit_icall_symbol (patch_info->data.name);
4804 if (!got_only && sym && acfg->aot_opts.direct_icalls && info->func == info->wrapper) {
4805 /* Call to a jit icall without a wrapper */
4807 external_call = TRUE;
4808 g_assert (strlen (sym) < 1000);
4809 direct_call_target = g_strdup_printf ("%s%s", acfg->user_symbol_prefix, sym);
4814 patch_info->type = MONO_PATCH_INFO_NONE;
4815 acfg->stats.direct_calls ++;
4818 if (!got_only && !direct_call) {
4819 MonoPltEntry *plt_entry = get_plt_entry (acfg, patch_info);
4821 /* This patch has a PLT entry, so we must emit a call to the PLT entry */
4823 direct_call_target = plt_entry->symbol;
4825 /* Nullify the patch */
4826 patch_info->type = MONO_PATCH_INFO_NONE;
4827 plt_entry->jit_used = TRUE;
4834 arch_emit_direct_call (acfg, direct_call_target, external_call, FALSE, patch_info, &call_size);
4835 i += call_size - INST_LEN;
4839 got_slot = get_got_offset (acfg, FALSE, patch_info);
4841 arch_emit_got_access (acfg, code + i, got_slot, &code_size);
4842 i += code_size - INST_LEN;
4848 #endif /* MONO_ARCH_AOT_SUPPORTED */
4851 /* Find next patch */
4853 for (pindex = start_index; pindex < patches->len; ++pindex) {
4854 patch_info = g_ptr_array_index (patches, pindex);
4855 if (patch_info->ip.i >= i)
4859 /* Try to emit multiple bytes at once */
4860 if (pindex < patches->len && patch_info->ip.i > i) {
4863 for (limit = i + INST_LEN; limit < patch_info->ip.i; limit += INST_LEN) {
4864 if (locs && locs [limit])
4868 emit_code_bytes (acfg, code + i, limit - i);
4869 i = limit - INST_LEN;
4871 emit_code_bytes (acfg, code + i, INST_LEN);
4882 * Return a modified version of S which only includes characters permissible in symbols.
4885 sanitize_symbol (MonoAotCompile *acfg, char *s)
4887 gboolean process = FALSE;
4896 for (i = 0; i < len; ++i)
4897 if (!(s [i] <= 0x7f && (isalnum (s [i]) || s [i] == '_')))
4902 gs = g_string_sized_new (len);
4903 for (i = 0; i < len; ++i) {
4905 if (c <= 0x7f && (isalnum (c) || c == '_')) {
4906 g_string_append_c (gs, c);
4907 } else if (c > 0x7f) {
4908 /* multi-byte utf8 */
4909 g_string_append_printf (gs, "_0x%x", c);
4912 while (c >> 6 == 0x2) {
4913 g_string_append_printf (gs, "%x", c);
4917 g_string_append_printf (gs, "_");
4920 g_string_append_c (gs, '_');
4924 res = mono_mempool_strdup (acfg->mempool, gs->str);
4925 g_string_free (gs, TRUE);
4930 get_debug_sym (MonoMethod *method, const char *prefix, GHashTable *cache)
4932 char *name1, *name2, *cached;
4933 int i, j, len, count;
4934 MonoMethod *cached_method;
4936 name1 = mono_method_full_name (method, TRUE);
4939 // This is so that we don't accidentally create a local symbol (which starts with 'L')
4940 if ((!prefix || !*prefix) && name1 [0] == 'L')
4944 len = strlen (name1);
4945 name2 = malloc (strlen (prefix) + len + 16);
4946 memcpy (name2, prefix, strlen (prefix));
4947 j = strlen (prefix);
4948 for (i = 0; i < len; ++i) {
4949 if (isalnum (name1 [i])) {
4950 name2 [j ++] = name1 [i];
4951 } else if (name1 [i] == ' ' && name1 [i + 1] == '(' && name1 [i + 2] == ')') {
4953 } else if (name1 [i] == ',' && name1 [i + 1] == ' ') {
4956 } else if (name1 [i] == '(' || name1 [i] == ')' || name1 [i] == '>') {
4966 cached_method = g_hash_table_lookup (cache, name2);
4967 if (!(cached_method && cached_method != method))
4969 sprintf (name2 + j, "_%d", count);
4973 cached = g_strdup (name2);
4974 g_hash_table_insert (cache, cached, method);
4980 emit_method_code (MonoAotCompile *acfg, MonoCompile *cfg)
4985 char *debug_sym = NULL;
4986 char *symbol = NULL;
4987 int func_alignment = AOT_FUNC_ALIGNMENT;
4988 MonoMethodHeader *header;
4991 method = cfg->orig_method;
4992 code = cfg->native_code;
4993 header = cfg->header;
4995 method_index = get_method_index (acfg, method);
4996 symbol = g_strdup_printf ("%sme_%x", acfg->temp_prefix, method_index);
4998 /* Make the labels local */
4999 emit_section_change (acfg, ".text", 0);
5000 emit_alignment_code (acfg, func_alignment);
5002 if (acfg->global_symbols && acfg->need_no_dead_strip)
5003 fprintf (acfg->fp, " .no_dead_strip %s\n", cfg->asm_symbol);
5005 emit_label (acfg, cfg->asm_symbol);
5007 if (acfg->aot_opts.write_symbols && !acfg->global_symbols && !acfg->llvm_separate) {
5009 * Write a C style symbol for every method, this has two uses:
5010 * - it works on platforms where the dwarf debugging info is not
5012 * - it allows the setting of breakpoints of aot-ed methods.
5014 debug_sym = get_debug_sym (method, "", acfg->method_label_hash);
5015 cfg->asm_debug_symbol = g_strdup (debug_sym);
5017 if (acfg->need_no_dead_strip)
5018 fprintf (acfg->fp, " .no_dead_strip %s\n", debug_sym);
5019 emit_local_symbol (acfg, debug_sym, symbol, TRUE);
5020 emit_label (acfg, debug_sym);
5023 export_name = g_hash_table_lookup (acfg->export_names, method);
5025 /* Emit a global symbol for the method */
5026 emit_global_inner (acfg, export_name, TRUE);
5027 emit_label (acfg, export_name);
5030 if (cfg->verbose_level > 0)
5031 g_print ("Method %s emitted as %s\n", mono_method_full_name (method, TRUE), cfg->asm_symbol);
5033 acfg->stats.code_size += cfg->code_len;
5035 acfg->cfgs [method_index]->got_offset = acfg->got_offset;
5037 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 ()));
5041 if (acfg->aot_opts.write_symbols) {
5043 emit_symbol_size (acfg, debug_sym, ".");
5045 emit_symbol_size (acfg, cfg->asm_symbol, ".");
5049 emit_label (acfg, symbol);
5056 * Encode PATCH_INFO into its disk representation.
5059 encode_patch (MonoAotCompile *acfg, MonoJumpInfo *patch_info, guint8 *buf, guint8 **endbuf)
5063 switch (patch_info->type) {
5064 case MONO_PATCH_INFO_NONE:
5066 case MONO_PATCH_INFO_IMAGE:
5067 encode_value (get_image_index (acfg, patch_info->data.image), p, &p);
5069 case MONO_PATCH_INFO_MSCORLIB_GOT_ADDR:
5070 case MONO_PATCH_INFO_JIT_TLS_ID:
5071 case MONO_PATCH_INFO_GC_CARD_TABLE_ADDR:
5073 case MONO_PATCH_INFO_CASTCLASS_CACHE:
5074 encode_value (patch_info->data.index, p, &p);
5076 case MONO_PATCH_INFO_METHOD_REL:
5077 encode_value ((gint)patch_info->data.offset, p, &p);
5079 case MONO_PATCH_INFO_SWITCH: {
5080 gpointer *table = (gpointer *)patch_info->data.table->table;
5083 encode_value (patch_info->data.table->table_size, p, &p);
5084 for (k = 0; k < patch_info->data.table->table_size; k++)
5085 encode_value ((int)(gssize)table [k], p, &p);
5088 case MONO_PATCH_INFO_METHODCONST:
5089 case MONO_PATCH_INFO_METHOD:
5090 case MONO_PATCH_INFO_METHOD_JUMP:
5091 case MONO_PATCH_INFO_ICALL_ADDR:
5092 case MONO_PATCH_INFO_METHOD_RGCTX:
5093 case MONO_PATCH_INFO_METHOD_CODE_SLOT:
5094 encode_method_ref (acfg, patch_info->data.method, p, &p);
5096 case MONO_PATCH_INFO_INTERNAL_METHOD:
5097 case MONO_PATCH_INFO_JIT_ICALL_ADDR: {
5098 guint32 len = strlen (patch_info->data.name);
5100 encode_value (len, p, &p);
5102 memcpy (p, patch_info->data.name, len);
5107 case MONO_PATCH_INFO_LDSTR: {
5108 guint32 image_index = get_image_index (acfg, patch_info->data.token->image);
5109 guint32 token = patch_info->data.token->token;
5110 g_assert (mono_metadata_token_code (token) == MONO_TOKEN_STRING);
5111 encode_value (image_index, p, &p);
5112 encode_value (patch_info->data.token->token - MONO_TOKEN_STRING, p, &p);
5115 case MONO_PATCH_INFO_RVA:
5116 case MONO_PATCH_INFO_DECLSEC:
5117 case MONO_PATCH_INFO_LDTOKEN:
5118 case MONO_PATCH_INFO_TYPE_FROM_HANDLE:
5119 encode_value (get_image_index (acfg, patch_info->data.token->image), p, &p);
5120 encode_value (patch_info->data.token->token, p, &p);
5121 encode_value (patch_info->data.token->has_context, p, &p);
5122 if (patch_info->data.token->has_context)
5123 encode_generic_context (acfg, &patch_info->data.token->context, p, &p);
5125 case MONO_PATCH_INFO_EXC_NAME: {
5126 MonoClass *ex_class;
5129 mono_class_from_name (mono_defaults.exception_class->image,
5130 "System", patch_info->data.target);
5131 g_assert (ex_class);
5132 encode_klass_ref (acfg, ex_class, p, &p);
5135 case MONO_PATCH_INFO_R4:
5136 encode_value (*((guint32 *)patch_info->data.target), p, &p);
5138 case MONO_PATCH_INFO_R8:
5139 encode_value (((guint32 *)patch_info->data.target) [MINI_LS_WORD_IDX], p, &p);
5140 encode_value (((guint32 *)patch_info->data.target) [MINI_MS_WORD_IDX], p, &p);
5142 case MONO_PATCH_INFO_VTABLE:
5143 case MONO_PATCH_INFO_CLASS:
5144 case MONO_PATCH_INFO_IID:
5145 case MONO_PATCH_INFO_ADJUSTED_IID:
5146 case MONO_PATCH_INFO_CLASS_INIT:
5147 encode_klass_ref (acfg, patch_info->data.klass, p, &p);
5149 case MONO_PATCH_INFO_DELEGATE_TRAMPOLINE:
5150 encode_klass_ref (acfg, patch_info->data.del_tramp->klass, p, &p);
5151 if (patch_info->data.del_tramp->method) {
5152 encode_value (1, p, &p);
5153 encode_method_ref (acfg, patch_info->data.del_tramp->method, p, &p);
5155 encode_value (0, p, &p);
5157 encode_value (patch_info->data.del_tramp->virtual, p, &p);
5159 case MONO_PATCH_INFO_FIELD:
5160 case MONO_PATCH_INFO_SFLDA:
5161 encode_field_info (acfg, patch_info->data.field, p, &p);
5163 case MONO_PATCH_INFO_INTERRUPTION_REQUEST_FLAG:
5165 case MONO_PATCH_INFO_RGCTX_FETCH: {
5166 MonoJumpInfoRgctxEntry *entry = patch_info->data.rgctx_entry;
5171 * entry->method has a lenghtly encoding and multiple rgctx_fetch entries
5172 * reference the same method, so encode the method only once.
5174 offset = GPOINTER_TO_UINT (g_hash_table_lookup (acfg->method_blob_hash, entry->method));
5176 buf2 = g_malloc (1024);
5179 encode_method_ref (acfg, entry->method, p2, &p2);
5180 g_assert (p2 - buf2 < 1024);
5182 offset = add_to_blob (acfg, buf2, p2 - buf2);
5185 g_hash_table_insert (acfg->method_blob_hash, entry->method, GUINT_TO_POINTER (offset + 1));
5190 encode_value (offset, p, &p);
5191 g_assert ((int)entry->info_type < 256);
5192 g_assert (entry->data->type < 256);
5193 encode_value ((entry->in_mrgctx ? 1 : 0) | (entry->info_type << 1) | (entry->data->type << 9), p, &p);
5194 encode_patch (acfg, entry->data, p, &p);
5197 case MONO_PATCH_INFO_GENERIC_CLASS_INIT:
5198 case MONO_PATCH_INFO_MONITOR_ENTER:
5199 case MONO_PATCH_INFO_MONITOR_ENTER_V4:
5200 case MONO_PATCH_INFO_MONITOR_EXIT:
5201 case MONO_PATCH_INFO_SEQ_POINT_INFO:
5203 case MONO_PATCH_INFO_LLVM_IMT_TRAMPOLINE:
5204 encode_method_ref (acfg, patch_info->data.imt_tramp->method, p, &p);
5205 encode_value (patch_info->data.imt_tramp->vt_offset, p, &p);
5207 case MONO_PATCH_INFO_SIGNATURE:
5208 encode_signature (acfg, (MonoMethodSignature*)patch_info->data.target, p, &p);
5210 case MONO_PATCH_INFO_TLS_OFFSET:
5211 encode_value (GPOINTER_TO_INT (patch_info->data.target), p, &p);
5213 case MONO_PATCH_INFO_GSHAREDVT_CALL:
5214 encode_signature (acfg, (MonoMethodSignature*)patch_info->data.gsharedvt->sig, p, &p);
5215 encode_method_ref (acfg, patch_info->data.gsharedvt->method, p, &p);
5217 case MONO_PATCH_INFO_GSHAREDVT_METHOD: {
5218 MonoGSharedVtMethodInfo *info = patch_info->data.gsharedvt_method;
5221 encode_method_ref (acfg, info->method, p, &p);
5222 encode_value (info->num_entries, p, &p);
5223 for (i = 0; i < info->num_entries; ++i) {
5224 MonoRuntimeGenericContextInfoTemplate *template = &info->entries [i];
5226 encode_value (template->info_type, p, &p);
5227 switch (mini_rgctx_info_type_to_patch_info_type (template->info_type)) {
5228 case MONO_PATCH_INFO_CLASS:
5229 encode_klass_ref (acfg, mono_class_from_mono_type (template->data), p, &p);
5231 case MONO_PATCH_INFO_FIELD:
5232 encode_field_info (acfg, template->data, p, &p);
5235 g_assert_not_reached ();
5241 case MONO_PATCH_INFO_LDSTR_LIT: {
5242 const char *s = patch_info->data.target;
5244 encode_value (strlen (s), p, &p);
5245 memcpy (p, s, strlen (s) + 1);
5249 g_warning ("unable to handle jump info %d", patch_info->type);
5250 g_assert_not_reached ();
5257 encode_patch_list (MonoAotCompile *acfg, GPtrArray *patches, int n_patches, gboolean llvm, int first_got_offset, guint8 *buf, guint8 **endbuf)
5260 guint32 pindex, offset;
5261 MonoJumpInfo *patch_info;
5263 encode_value (n_patches, p, &p);
5265 for (pindex = 0; pindex < patches->len; ++pindex) {
5266 patch_info = g_ptr_array_index (patches, pindex);
5268 if (patch_info->type == MONO_PATCH_INFO_NONE || patch_info->type == MONO_PATCH_INFO_BB)
5272 offset = get_got_offset (acfg, llvm, patch_info);
5273 encode_value (offset, p, &p);
5280 emit_method_info (MonoAotCompile *acfg, MonoCompile *cfg)
5284 int pindex, buf_size, n_patches;
5286 MonoJumpInfo *patch_info;
5287 MonoMethodHeader *header;
5288 guint32 method_index;
5290 guint32 first_got_offset;
5292 method = cfg->orig_method;
5293 header = mono_method_get_header (method);
5295 method_index = get_method_index (acfg, method);
5297 /* Sort relocations */
5298 patches = g_ptr_array_new ();
5299 for (patch_info = cfg->patch_info; patch_info; patch_info = patch_info->next)
5300 g_ptr_array_add (patches, patch_info);
5301 g_ptr_array_sort (patches, compare_patches);
5303 first_got_offset = acfg->cfgs [method_index]->got_offset;
5305 /**********************/
5306 /* Encode method info */
5307 /**********************/
5309 buf_size = (patches->len < 1000) ? 40960 : 40960 + (patches->len * 64);
5310 p = buf = g_malloc (buf_size);
5312 if (mono_class_get_cctor (method->klass))
5313 encode_klass_ref (acfg, method->klass, p, &p);
5315 /* Not needed when loading the method */
5316 encode_value (0, p, &p);
5319 if (cfg->opt & MONO_OPT_SHARED) {
5320 encode_value (g_list_length (cfg->ldstr_list), p, &p);
5321 for (l = cfg->ldstr_list; l; l = l->next) {
5322 encode_value ((long)l->data, p, &p);
5326 /* Used only in shared mode */
5327 g_assert (!cfg->ldstr_list);
5330 for (pindex = 0; pindex < patches->len; ++pindex) {
5331 patch_info = g_ptr_array_index (patches, pindex);
5333 if ((patch_info->type == MONO_PATCH_INFO_GOT_OFFSET) ||
5334 (patch_info->type == MONO_PATCH_INFO_NONE)) {
5335 patch_info->type = MONO_PATCH_INFO_NONE;
5340 if ((patch_info->type == MONO_PATCH_INFO_IMAGE) && (patch_info->data.image == acfg->image)) {
5341 /* Stored in a GOT slot initialized at module load time */
5342 patch_info->type = MONO_PATCH_INFO_NONE;
5346 if (patch_info->type == MONO_PATCH_INFO_GC_CARD_TABLE_ADDR) {
5347 /* Stored in a GOT slot initialized at module load time */
5348 patch_info->type = MONO_PATCH_INFO_NONE;
5352 if (is_plt_patch (patch_info)) {
5353 /* Calls are made through the PLT */
5354 patch_info->type = MONO_PATCH_INFO_NONE;
5362 g_assert (cfg->has_got_slots);
5364 encode_patch_list (acfg, patches, n_patches, cfg->compile_llvm, first_got_offset, p, &p);
5366 acfg->stats.info_size += p - buf;
5368 g_assert (p - buf < buf_size);
5370 cfg->method_info_offset = add_to_blob (acfg, buf, p - buf);
5375 get_unwind_info_offset (MonoAotCompile *acfg, guint8 *encoded, guint32 encoded_len)
5377 guint32 cache_index;
5380 /* Reuse the unwind module to canonize and store unwind info entries */
5381 cache_index = mono_cache_unwind_info (encoded, encoded_len);
5383 /* Use +/- 1 to distinguish 0s from missing entries */
5384 offset = GPOINTER_TO_UINT (g_hash_table_lookup (acfg->unwind_info_offsets, GUINT_TO_POINTER (cache_index + 1)));
5392 * It would be easier to use assembler symbols, but the caller needs an
5395 offset = acfg->unwind_info_offset;
5396 g_hash_table_insert (acfg->unwind_info_offsets, GUINT_TO_POINTER (cache_index + 1), GUINT_TO_POINTER (offset + 1));
5397 g_ptr_array_add (acfg->unwind_ops, GUINT_TO_POINTER (cache_index));
5400 encode_value (encoded_len, p, &p);
5402 acfg->unwind_info_offset += encoded_len + (p - buf);
5408 emit_exception_debug_info (MonoAotCompile *acfg, MonoCompile *cfg)
5411 int i, k, buf_size, method_index;
5412 guint32 debug_info_size, seq_points_size;
5414 MonoMethodHeader *header;
5415 guint8 *p, *buf, *debug_info;
5416 MonoJitInfo *jinfo = cfg->jit_info;
5418 gboolean use_unwind_ops = FALSE;
5419 MonoSeqPointInfo *seq_points;
5421 method = cfg->orig_method;
5422 code = cfg->native_code;
5423 header = cfg->header;
5425 method_index = get_method_index (acfg, method);
5427 if (!acfg->aot_opts.nodebug) {
5428 mono_debug_serialize_debug_info (cfg, &debug_info, &debug_info_size);
5431 debug_info_size = 0;
5434 seq_points = cfg->seq_point_info;
5436 seq_points_size = (cfg->gen_seq_points)? seq_point_info_get_write_size (seq_points) : 0;
5438 buf_size = header->num_clauses * 256 + debug_info_size + 2048 + seq_points_size + cfg->gc_map_size;
5439 p = buf = g_malloc (buf_size);
5441 use_unwind_ops = cfg->unwind_ops != NULL;
5443 flags = (jinfo->has_generic_jit_info ? 1 : 0) | (use_unwind_ops ? 2 : 0) | (header->num_clauses ? 4 : 0) | (seq_points ? 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);
5445 encode_value (flags, p, &p);
5447 if (use_unwind_ops) {
5448 guint32 encoded_len;
5450 guint32 unwind_desc;
5452 encoded = mono_unwind_ops_encode (cfg->unwind_ops, &encoded_len);
5454 unwind_desc = get_unwind_info_offset (acfg, encoded, encoded_len);
5455 encode_value (unwind_desc, p, &p);
5457 encode_value (jinfo->unwind_info, p, &p);
5460 /*Encode the number of holes before the number of clauses to make decoding easier*/
5461 if (jinfo->has_try_block_holes) {
5462 MonoTryBlockHoleTableJitInfo *table = mono_jit_info_get_try_block_hole_table_info (jinfo);
5463 encode_value (table->num_holes, p, &p);
5466 if (jinfo->has_arch_eh_info) {
5468 * In AOT mode, the code length is calculated from the address of the previous method,
5469 * which could include alignment padding, so calculating the start of the epilog as
5470 * code_len - epilog_size is correct any more. Save the real code len as a workaround.
5472 encode_value (jinfo->code_size, p, &p);
5475 /* Exception table */
5476 if (cfg->compile_llvm) {
5478 * When using LLVM, we can't emit some data, like pc offsets, this reg/offset etc.,
5479 * since the information is only available to llc. Instead, we let llc save the data
5480 * into the LSDA, and read it from there at runtime.
5482 /* The assembly might be CIL stripped so emit the data ourselves */
5483 if (header->num_clauses)
5484 encode_value (header->num_clauses, p, &p);
5486 for (k = 0; k < header->num_clauses; ++k) {
5487 MonoExceptionClause *clause;
5489 clause = &header->clauses [k];
5491 encode_value (clause->flags, p, &p);
5492 if (clause->data.catch_class) {
5493 encode_value (1, p, &p);
5494 encode_klass_ref (acfg, clause->data.catch_class, p, &p);
5496 encode_value (0, p, &p);
5499 /* Emit a list of nesting clauses */
5500 for (i = 0; i < header->num_clauses; ++i) {
5502 MonoExceptionClause *clause1 = &header->clauses [cindex1];
5504 MonoExceptionClause *clause2 = &header->clauses [cindex2];
5506 if (cindex1 != cindex2 && clause1->try_offset >= clause2->try_offset && clause1->handler_offset <= clause2->handler_offset)
5507 encode_value (i, p, &p);
5509 encode_value (-1, p, &p);
5512 if (jinfo->num_clauses)
5513 encode_value (jinfo->num_clauses, p, &p);
5515 for (k = 0; k < jinfo->num_clauses; ++k) {
5516 MonoJitExceptionInfo *ei = &jinfo->clauses [k];
5518 encode_value (ei->flags, p, &p);
5519 encode_value (ei->exvar_offset, p, &p);
5521 if (ei->flags == MONO_EXCEPTION_CLAUSE_FILTER || ei->flags == MONO_EXCEPTION_CLAUSE_FINALLY)
5522 encode_value ((gint)((guint8*)ei->data.filter - code), p, &p);
5524 if (ei->data.catch_class) {
5528 buf2 = g_malloc (4096);
5530 encode_klass_ref (acfg, ei->data.catch_class, p2, &p2);
5532 g_assert (len < 4096);
5533 encode_value (len, p, &p);
5534 memcpy (p, buf2, len);
5538 encode_value (0, p, &p);
5542 encode_value ((gint)((guint8*)ei->try_start - code), p, &p);
5543 encode_value ((gint)((guint8*)ei->try_end - code), p, &p);
5544 encode_value ((gint)((guint8*)ei->handler_start - code), p, &p);
5548 if (jinfo->has_try_block_holes) {
5549 MonoTryBlockHoleTableJitInfo *table = mono_jit_info_get_try_block_hole_table_info (jinfo);
5550 for (i = 0; i < table->num_holes; ++i) {
5551 MonoTryBlockHoleJitInfo *hole = &table->holes [i];
5552 encode_value (hole->clause, p, &p);
5553 encode_value (hole->length, p, &p);
5554 encode_value (hole->offset, p, &p);
5558 if (jinfo->has_arch_eh_info) {
5559 MonoArchEHJitInfo *eh_info;
5561 eh_info = mono_jit_info_get_arch_eh_info (jinfo);
5562 encode_value (eh_info->stack_size, p, &p);
5563 encode_value (eh_info->epilog_size, p, &p);
5566 if (jinfo->has_generic_jit_info) {
5567 MonoGenericJitInfo *gi = mono_jit_info_get_generic_jit_info (jinfo);
5568 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);
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;
5844 * The first plt entry is unused.
5848 plt_entry = g_hash_table_lookup (acfg->plt_offset_to_entry, GUINT_TO_POINTER (i));
5851 debug_sym = plt_entry->debug_sym;
5853 if (acfg->thumb_mixed && !plt_entry->jit_used)
5854 /* Emit only a thumb version */
5857 /* Skip plt entries not actually called */
5858 if (!plt_entry->jit_used && !plt_entry->llvm_used)
5861 if (acfg->llvm && !acfg->thumb_mixed) {
5862 emit_label (acfg, plt_entry->llvm_symbol);
5863 if (acfg->llvm_separate) {
5864 emit_global_inner (acfg, plt_entry->llvm_symbol, TRUE);
5865 #if defined(TARGET_MACH)
5866 fprintf (acfg->fp, ".private_extern %s\n", plt_entry->llvm_symbol);
5872 if (acfg->need_no_dead_strip) {
5873 emit_unset_mode (acfg);
5874 fprintf (acfg->fp, " .no_dead_strip %s\n", debug_sym);
5876 emit_local_symbol (acfg, debug_sym, NULL, TRUE);
5877 emit_label (acfg, debug_sym);
5880 emit_label (acfg, plt_entry->symbol);
5882 arch_emit_plt_entry (acfg, i);
5885 emit_symbol_size (acfg, debug_sym, ".");
5888 if (acfg->thumb_mixed) {
5889 /* Make sure the ARM symbols don't alias the thumb ones */
5890 emit_zero_bytes (acfg, 16);
5893 * Emit a separate set of PLT entries using thumb2 which is called by LLVM generated
5896 for (i = 0; i < acfg->plt_offset; ++i) {
5897 char *debug_sym = NULL;
5898 MonoPltEntry *plt_entry = NULL;
5904 plt_entry = g_hash_table_lookup (acfg->plt_offset_to_entry, GUINT_TO_POINTER (i));
5907 /* Skip plt entries not actually called by LLVM code */
5908 if (!plt_entry->llvm_used)
5911 if (acfg->aot_opts.write_symbols) {
5912 if (plt_entry->debug_sym)
5913 debug_sym = g_strdup_printf ("%s_thumb", plt_entry->debug_sym);
5917 #if defined(TARGET_MACH)
5918 fprintf (acfg->fp, " .thumb_func %s\n", debug_sym);
5919 fprintf (acfg->fp, " .no_dead_strip %s\n", debug_sym);
5921 emit_local_symbol (acfg, debug_sym, NULL, TRUE);
5922 emit_label (acfg, debug_sym);
5924 fprintf (acfg->fp, "\n.thumb_func\n");
5926 emit_label (acfg, plt_entry->llvm_symbol);
5928 if (acfg->llvm_separate)
5929 emit_global_inner (acfg, plt_entry->llvm_symbol, TRUE);
5931 arch_emit_llvm_plt_entry (acfg, i);
5934 emit_symbol_size (acfg, debug_sym, ".");
5940 emit_symbol_size (acfg, acfg->plt_symbol, ".");
5942 sprintf (symbol, "plt_end");
5943 emit_label (acfg, symbol);
5947 * emit_trampoline_full:
5949 * If EMIT_TINFO is TRUE, emit additional information which can be used to create a MonoJitInfo for this trampoline by
5950 * create_jit_info_for_trampoline ().
5952 static G_GNUC_UNUSED void
5953 emit_trampoline_full (MonoAotCompile *acfg, int got_offset, MonoTrampInfo *info, gboolean emit_tinfo)
5955 char start_symbol [256];
5956 char end_symbol [256];
5958 guint32 buf_size, info_offset;
5959 MonoJumpInfo *patch_info;
5972 code_size = info->code_size;
5974 unwind_ops = info->unwind_ops;
5976 #ifdef __native_client_codegen__
5977 mono_nacl_fix_patches (code, ji);
5982 sprintf (start_symbol, "%s%s", acfg->user_symbol_prefix, name);
5984 emit_section_change (acfg, ".text", 0);
5985 emit_global (acfg, start_symbol, TRUE);
5986 emit_alignment_code (acfg, AOT_FUNC_ALIGNMENT);
5987 emit_label (acfg, start_symbol);
5989 sprintf (symbol, "%snamed_%s", acfg->temp_prefix, name);
5990 emit_label (acfg, symbol);
5993 * The code should access everything through the GOT, so we pass
5996 emit_and_reloc_code (acfg, NULL, code, code_size, ji, TRUE, NULL);
5998 emit_symbol_size (acfg, start_symbol, ".");
6001 sprintf (end_symbol, "%snamede_%s", acfg->temp_prefix, name);
6002 emit_label (acfg, end_symbol);
6007 /* Sort relocations */
6008 patches = g_ptr_array_new ();
6009 for (patch_info = ji; patch_info; patch_info = patch_info->next)
6010 if (patch_info->type != MONO_PATCH_INFO_NONE)
6011 g_ptr_array_add (patches, patch_info);
6012 g_ptr_array_sort (patches, compare_patches);
6014 buf_size = patches->len * 128 + 128;
6015 buf = g_malloc (buf_size);
6018 encode_patch_list (acfg, patches, patches->len, FALSE, got_offset, p, &p);
6019 g_assert (p - buf < buf_size);
6021 sprintf (symbol, "%s%s_p", acfg->user_symbol_prefix, name);
6023 info_offset = add_to_blob (acfg, buf, p - buf);
6025 emit_section_change (acfg, RODATA_SECT, 0);
6026 emit_global (acfg, symbol, FALSE);
6027 emit_label (acfg, symbol);
6029 emit_int32 (acfg, info_offset);
6033 guint32 encoded_len;
6037 * Emit additional information which can be used to reconstruct a partial MonoTrampInfo.
6039 encoded = mono_unwind_ops_encode (info->unwind_ops, &encoded_len);
6040 uw_offset = get_unwind_info_offset (acfg, encoded, encoded_len);
6043 emit_symbol_diff (acfg, end_symbol, start_symbol, 0);
6044 emit_int32 (acfg, uw_offset);
6047 /* Emit debug info */
6051 sprintf (symbol, "%s", name);
6052 sprintf (symbol2, "%snamed_%s", acfg->temp_prefix, name);
6055 mono_dwarf_writer_emit_trampoline (acfg->dwarf, symbol, symbol2, NULL, NULL, code_size, unwind_ops);
6059 static G_GNUC_UNUSED void
6060 emit_trampoline (MonoAotCompile *acfg, int got_offset, MonoTrampInfo *info)
6062 emit_trampoline_full (acfg, got_offset, info, FALSE);
6066 emit_trampolines (MonoAotCompile *acfg)
6069 char end_symbol [256];
6070 int i, tramp_got_offset;
6071 MonoAotTrampoline ntype;
6072 #ifdef MONO_ARCH_HAVE_FULL_AOT_TRAMPOLINES
6076 if (!acfg->aot_opts.full_aot)
6079 g_assert (acfg->image->assembly);
6081 /* Currently, we emit most trampolines into the mscorlib AOT image. */
6082 if (strcmp (acfg->image->assembly->aname.name, "mscorlib") == 0) {
6083 #ifdef MONO_ARCH_HAVE_FULL_AOT_TRAMPOLINES
6084 MonoTrampInfo *info;
6087 * Emit the generic trampolines.
6089 * We could save some code by treating the generic trampolines as a wrapper
6090 * method, but that approach has its own complexities, so we choose the simpler
6093 for (tramp_type = 0; tramp_type < MONO_TRAMPOLINE_NUM; ++tramp_type) {
6094 /* we overload the boolean here to indicate the slightly different trampoline needed, see mono_arch_create_generic_trampoline() */
6095 #ifdef DISABLE_REMOTING
6096 if (tramp_type == MONO_TRAMPOLINE_GENERIC_VIRTUAL_REMOTING)
6099 #ifndef MONO_ARCH_HAVE_HANDLER_BLOCK_GUARD
6100 if (tramp_type == MONO_TRAMPOLINE_HANDLER_BLOCK_GUARD)
6103 mono_arch_create_generic_trampoline (tramp_type, &info, acfg->aot_opts.use_trampolines_page? 2: TRUE);
6104 emit_trampoline (acfg, acfg->got_offset, info);
6107 mono_arch_get_nullified_class_init_trampoline (&info);
6108 emit_trampoline (acfg, acfg->got_offset, info);
6109 #if defined(MONO_ARCH_MONITOR_OBJECT_REG)
6110 mono_arch_create_monitor_enter_trampoline (&info, FALSE, TRUE);
6111 emit_trampoline (acfg, acfg->got_offset, info);
6112 #if defined(MONO_ARCH_MONITOR_LOCK_TAKEN_REG)
6113 mono_arch_create_monitor_enter_trampoline (&info, TRUE, TRUE);
6114 emit_trampoline (acfg, acfg->got_offset, info);
6116 mono_arch_create_monitor_exit_trampoline (&info, TRUE);
6117 emit_trampoline (acfg, acfg->got_offset, info);
6120 mono_arch_create_generic_class_init_trampoline (&info, TRUE);
6121 emit_trampoline (acfg, acfg->got_offset, info);
6123 /* Emit the exception related code pieces */
6124 mono_arch_get_restore_context (&info, TRUE);
6125 emit_trampoline (acfg, acfg->got_offset, info);
6126 mono_arch_get_call_filter (&info, TRUE);
6127 emit_trampoline (acfg, acfg->got_offset, info);
6128 mono_arch_get_throw_exception (&info, TRUE);
6129 emit_trampoline (acfg, acfg->got_offset, info);
6130 mono_arch_get_rethrow_exception (&info, TRUE);
6131 emit_trampoline (acfg, acfg->got_offset, info);
6132 mono_arch_get_throw_corlib_exception (&info, TRUE);
6133 emit_trampoline (acfg, acfg->got_offset, info);
6135 #ifdef MONO_ARCH_GSHAREDVT_SUPPORTED
6136 mono_arch_get_gsharedvt_trampoline (&info, TRUE);
6138 emit_trampoline_full (acfg, acfg->got_offset, info, TRUE);
6140 /* Create a separate out trampoline for more information in stack traces */
6141 info->name = g_strdup ("gsharedvt_out_trampoline");
6142 emit_trampoline_full (acfg, acfg->got_offset, info, TRUE);
6146 #if defined(MONO_ARCH_HAVE_GET_TRAMPOLINES)
6148 GSList *l = mono_arch_get_trampolines (TRUE);
6151 MonoTrampInfo *info = l->data;
6153 emit_trampoline (acfg, acfg->got_offset, info);
6159 for (i = 0; i < acfg->aot_opts.nrgctx_fetch_trampolines; ++i) {
6162 offset = MONO_RGCTX_SLOT_MAKE_RGCTX (i);
6163 mono_arch_create_rgctx_lazy_fetch_trampoline (offset, &info, TRUE);
6164 emit_trampoline (acfg, acfg->got_offset, info);
6166 offset = MONO_RGCTX_SLOT_MAKE_MRGCTX (i);
6167 mono_arch_create_rgctx_lazy_fetch_trampoline (offset, &info, TRUE);
6168 emit_trampoline (acfg, acfg->got_offset, info);
6171 #ifdef MONO_ARCH_HAVE_GENERAL_RGCTX_LAZY_FETCH_TRAMPOLINE
6172 mono_arch_create_general_rgctx_lazy_fetch_trampoline (&info, TRUE);
6173 emit_trampoline (acfg, acfg->got_offset, info);
6179 /* delegate_invoke_impl trampolines */
6180 l = mono_arch_get_delegate_invoke_impls ();
6182 MonoTrampInfo *info = l->data;
6184 emit_trampoline (acfg, acfg->got_offset, info);
6189 #endif /* #ifdef MONO_ARCH_HAVE_FULL_AOT_TRAMPOLINES */
6191 /* Emit trampolines which are numerous */
6194 * These include the following:
6195 * - specific trampolines
6196 * - static rgctx invoke trampolines
6198 * These trampolines have the same code, they are parameterized by GOT
6200 * They are defined in this file, in the arch_... routines instead of
6201 * in tramp-<ARCH>.c, since it is easier to do it this way.
6205 * When running in aot-only mode, we can't create specific trampolines at
6206 * runtime, so we create a few, and save them in the AOT file.
6207 * Normal trampolines embed their argument as a literal inside the
6208 * trampoline code, we can't do that here, so instead we embed an offset
6209 * which needs to be added to the trampoline address to get the address of
6210 * the GOT slot which contains the argument value.
6211 * The generated trampolines jump to the generic trampolines using another
6212 * GOT slot, which will be setup by the AOT loader to point to the
6213 * generic trampoline code of the given type.
6217 * FIXME: Maybe we should use more specific trampolines (i.e. one class init for
6221 emit_section_change (acfg, ".text", 0);
6223 tramp_got_offset = acfg->got_offset;
6225 for (ntype = 0; ntype < MONO_AOT_TRAMP_NUM; ++ntype) {
6227 case MONO_AOT_TRAMP_SPECIFIC:
6228 sprintf (symbol, "specific_trampolines");
6230 case MONO_AOT_TRAMP_STATIC_RGCTX:
6231 sprintf (symbol, "static_rgctx_trampolines");
6233 case MONO_AOT_TRAMP_IMT_THUNK:
6234 sprintf (symbol, "imt_thunks");
6236 case MONO_AOT_TRAMP_GSHAREDVT_ARG:
6237 sprintf (symbol, "gsharedvt_arg_trampolines");
6240 g_assert_not_reached ();
6243 sprintf (end_symbol, "%s_e", symbol);
6245 if (acfg->aot_opts.write_symbols)
6246 emit_local_symbol (acfg, symbol, end_symbol, TRUE);
6248 emit_alignment_code (acfg, AOT_FUNC_ALIGNMENT);
6249 emit_label (acfg, symbol);
6251 acfg->trampoline_got_offset_base [ntype] = tramp_got_offset;
6253 for (i = 0; i < acfg->num_trampolines [ntype]; ++i) {
6257 case MONO_AOT_TRAMP_SPECIFIC:
6258 arch_emit_specific_trampoline (acfg, tramp_got_offset, &tramp_size);
6259 tramp_got_offset += 2;
6261 case MONO_AOT_TRAMP_STATIC_RGCTX:
6262 arch_emit_static_rgctx_trampoline (acfg, tramp_got_offset, &tramp_size);
6263 tramp_got_offset += 2;
6265 case MONO_AOT_TRAMP_IMT_THUNK:
6266 arch_emit_imt_thunk (acfg, tramp_got_offset, &tramp_size);
6267 tramp_got_offset += 1;
6269 case MONO_AOT_TRAMP_GSHAREDVT_ARG:
6270 arch_emit_gsharedvt_arg_trampoline (acfg, tramp_got_offset, &tramp_size);
6271 tramp_got_offset += 2;
6274 g_assert_not_reached ();
6276 #ifdef __native_client_codegen__
6277 /* align to avoid 32-byte boundary crossings */
6278 emit_alignment (acfg, AOT_FUNC_ALIGNMENT);
6281 if (!acfg->trampoline_size [ntype]) {
6282 g_assert (tramp_size);
6283 acfg->trampoline_size [ntype] = tramp_size;
6287 emit_label (acfg, end_symbol);
6288 emit_int32 (acfg, 0);
6291 arch_emit_specific_trampoline_pages (acfg);
6293 /* Reserve some entries at the end of the GOT for our use */
6294 acfg->num_trampoline_got_entries = tramp_got_offset - acfg->got_offset;
6297 acfg->got_offset += acfg->num_trampoline_got_entries;
6301 str_begins_with (const char *str1, const char *str2)
6303 int len = strlen (str2);
6304 return strncmp (str1, str2, len) == 0;
6308 mono_aot_readonly_field_override (MonoClassField *field)
6311 for (rdv = readonly_values; rdv; rdv = rdv->next) {
6312 char *p = rdv->name;
6314 len = strlen (field->parent->name_space);
6315 if (strncmp (p, field->parent->name_space, len))
6320 len = strlen (field->parent->name);
6321 if (strncmp (p, field->parent->name, len))
6326 if (strcmp (p, field->name))
6328 switch (rdv->type) {
6330 return &rdv->value.i1;
6332 return &rdv->value.i2;
6334 return &rdv->value.i4;
6343 add_readonly_value (MonoAotOptions *opts, const char *val)
6348 /* the format of val is:
6349 * namespace.typename.fieldname=type/value
6350 * type can be i1 for uint8/int8/boolean, i2 for uint16/int16/char, i4 for uint32/int32
6352 fval = strrchr (val, '/');
6354 fprintf (stderr, "AOT : invalid format for readonly field '%s', missing /.\n", val);
6357 tval = strrchr (val, '=');
6359 fprintf (stderr, "AOT : invalid format for readonly field '%s', missing =.\n", val);
6362 rdv = g_new0 (ReadOnlyValue, 1);
6363 rdv->name = g_malloc0 (tval - val + 1);
6364 memcpy (rdv->name, val, tval - val);
6367 if (strncmp (tval, "i1", 2) == 0) {
6368 rdv->value.i1 = atoi (fval);
6369 rdv->type = MONO_TYPE_I1;
6370 } else if (strncmp (tval, "i2", 2) == 0) {
6371 rdv->value.i2 = atoi (fval);
6372 rdv->type = MONO_TYPE_I2;
6373 } else if (strncmp (tval, "i4", 2) == 0) {
6374 rdv->value.i4 = atoi (fval);
6375 rdv->type = MONO_TYPE_I4;
6377 fprintf (stderr, "AOT : unsupported type for readonly field '%s'.\n", tval);
6380 rdv->next = readonly_values;
6381 readonly_values = rdv;
6385 mono_aot_parse_options (const char *aot_options, MonoAotOptions *opts)
6387 gchar **args, **ptr;
6389 args = g_strsplit (aot_options ? aot_options : "", ",", -1);
6390 for (ptr = args; ptr && *ptr; ptr ++) {
6391 const char *arg = *ptr;
6393 if (str_begins_with (arg, "outfile=")) {
6394 opts->outfile = g_strdup (arg + strlen ("outfile="));
6395 } else if (str_begins_with (arg, "llvm-outfile=")) {
6396 opts->llvm_outfile = g_strdup (arg + strlen ("llvm-outfile="));
6397 } else if (str_begins_with (arg, "save-temps")) {
6398 opts->save_temps = TRUE;
6399 } else if (str_begins_with (arg, "keep-temps")) {
6400 opts->save_temps = TRUE;
6401 } else if (str_begins_with (arg, "write-symbols")) {
6402 opts->write_symbols = TRUE;
6403 } else if (str_begins_with (arg, "no-write-symbols")) {
6404 opts->write_symbols = FALSE;
6405 } else if (str_begins_with (arg, "metadata-only")) {
6406 opts->metadata_only = TRUE;
6407 } else if (str_begins_with (arg, "bind-to-runtime-version")) {
6408 opts->bind_to_runtime_version = TRUE;
6409 } else if (str_begins_with (arg, "full")) {
6410 opts->full_aot = TRUE;
6411 } else if (str_begins_with (arg, "threads=")) {
6412 opts->nthreads = atoi (arg + strlen ("threads="));
6413 } else if (str_begins_with (arg, "static")) {
6414 opts->static_link = TRUE;
6415 opts->no_dlsym = TRUE;
6416 } else if (str_begins_with (arg, "asmonly")) {
6417 opts->asm_only = TRUE;
6418 } else if (str_begins_with (arg, "asmwriter")) {
6419 opts->asm_writer = TRUE;
6420 } else if (str_begins_with (arg, "nodebug")) {
6421 opts->nodebug = TRUE;
6422 } else if (str_begins_with (arg, "dwarfdebug")) {
6423 opts->dwarf_debug = TRUE;
6424 } else if (str_begins_with (arg, "nopagetrampolines")) {
6425 opts->use_trampolines_page = FALSE;
6426 } else if (str_begins_with (arg, "ntrampolines=")) {
6427 opts->ntrampolines = atoi (arg + strlen ("ntrampolines="));
6428 } else if (str_begins_with (arg, "nrgctx-trampolines=")) {
6429 opts->nrgctx_trampolines = atoi (arg + strlen ("nrgctx-trampolines="));
6430 } else if (str_begins_with (arg, "nimt-trampolines=")) {
6431 opts->nimt_trampolines = atoi (arg + strlen ("nimt-trampolines="));
6432 } else if (str_begins_with (arg, "ngsharedvt-trampolines=")) {
6433 opts->ngsharedvt_arg_trampolines = atoi (arg + strlen ("ngsharedvt-trampolines="));
6434 } else if (str_begins_with (arg, "autoreg")) {
6435 opts->autoreg = TRUE;
6436 } else if (str_begins_with (arg, "tool-prefix=")) {
6437 opts->tool_prefix = g_strdup (arg + strlen ("tool-prefix="));
6438 } else if (str_begins_with (arg, "ld-flags=")) {
6439 opts->ld_flags = g_strdup (arg + strlen ("ld-flags="));
6440 } else if (str_begins_with (arg, "soft-debug")) {
6441 opts->soft_debug = TRUE;
6442 } else if (str_begins_with (arg, "direct-pinvoke")) {
6443 opts->direct_pinvoke = TRUE;
6444 } else if (str_begins_with (arg, "direct-icalls")) {
6445 opts->direct_icalls = TRUE;
6446 #if defined(TARGET_ARM) || defined(TARGET_ARM64)
6447 } else if (str_begins_with (arg, "iphone-abi")) {
6448 // older full-aot users did depend on this.
6450 } else if (str_begins_with (arg, "no-direct-calls")) {
6451 opts->no_direct_calls = TRUE;
6452 } else if (str_begins_with (arg, "print-skipped")) {
6453 opts->print_skipped_methods = TRUE;
6454 } else if (str_begins_with (arg, "stats")) {
6456 } else if (str_begins_with (arg, "no-instances")) {
6457 opts->no_instances = TRUE;
6458 } else if (str_begins_with (arg, "log-generics")) {
6459 opts->log_generics = TRUE;
6460 } else if (str_begins_with (arg, "log-instances=")) {
6461 opts->log_instances = TRUE;
6462 opts->instances_logfile_path = g_strdup (arg + strlen ("log-instances="));
6463 } else if (str_begins_with (arg, "log-instances")) {
6464 opts->log_instances = TRUE;
6465 } else if (str_begins_with (arg, "internal-logfile=")) {
6466 opts->logfile = g_strdup (arg + strlen ("internal-logfile="));
6467 } else if (str_begins_with (arg, "mtriple=")) {
6468 opts->mtriple = g_strdup (arg + strlen ("mtriple="));
6469 } else if (str_begins_with (arg, "llvm-path=")) {
6470 opts->llvm_path = g_strdup (arg + strlen ("llvm-path="));
6471 } else if (!strcmp (arg, "llvm")) {
6473 } else if (str_begins_with (arg, "readonly-value=")) {
6474 add_readonly_value (opts, arg + strlen ("readonly-value="));
6475 } else if (str_begins_with (arg, "info")) {
6476 printf ("AOT target setup: %s.\n", AOT_TARGET_STR);
6478 } else if (str_begins_with (arg, "gc-maps")) {
6479 mini_gc_enable_gc_maps_for_aot ();
6480 } else if (str_begins_with (arg, "dump")) {
6481 opts->dump_json = TRUE;
6482 } else if (str_begins_with (arg, "help") || str_begins_with (arg, "?")) {
6483 printf ("Supported options for --aot:\n");
6484 printf (" outfile=\n");
6485 printf (" llvm-outfile=\n");
6486 printf (" save-temps\n");
6487 printf (" keep-temps\n");
6488 printf (" write-symbols\n");
6489 printf (" metadata-only\n");
6490 printf (" bind-to-runtime-version\n");
6492 printf (" threads=\n");
6493 printf (" static\n");
6494 printf (" asmonly\n");
6495 printf (" asmwriter\n");
6496 printf (" nodebug\n");
6497 printf (" dwarfdebug\n");
6498 printf (" ntrampolines=\n");
6499 printf (" nrgctx-trampolines=\n");
6500 printf (" nimt-trampolines=\n");
6501 printf (" ngsharedvt-trampolines=\n");
6502 printf (" autoreg\n");
6503 printf (" tool-prefix=\n");
6504 printf (" readonly-value=\n");
6505 printf (" soft-debug\n");
6506 printf (" gc-maps\n");
6507 printf (" print-skipped\n");
6508 printf (" no-instances\n");
6509 printf (" stats\n");
6512 printf (" help/?\n");
6515 fprintf (stderr, "AOT : Unknown argument '%s'.\n", arg);
6520 if (opts->use_trampolines_page) {
6521 opts->ntrampolines = 0;
6522 opts->nrgctx_trampolines = 0;
6523 opts->nimt_trampolines = 0;
6524 opts->ngsharedvt_arg_trampolines = 0;
6530 add_token_info_hash (gpointer key, gpointer value, gpointer user_data)
6532 MonoMethod *method = (MonoMethod*)key;
6533 MonoJumpInfoToken *ji = (MonoJumpInfoToken*)value;
6534 MonoAotCompile *acfg = user_data;
6535 MonoJumpInfoToken *new_ji;
6537 new_ji = mono_mempool_alloc0 (acfg->mempool, sizeof (MonoJumpInfoToken));
6538 new_ji->image = ji->image;
6539 new_ji->token = ji->token;
6540 g_hash_table_insert (acfg->token_info_hash, method, new_ji);
6544 can_encode_class (MonoAotCompile *acfg, MonoClass *klass)
6546 if (klass->type_token)
6548 if ((klass->byval_arg.type == MONO_TYPE_VAR) || (klass->byval_arg.type == MONO_TYPE_MVAR) || (klass->byval_arg.type == MONO_TYPE_PTR))
6551 return can_encode_class (acfg, klass->element_class);
6556 can_encode_method (MonoAotCompile *acfg, MonoMethod *method)
6558 if (method->wrapper_type) {
6559 switch (method->wrapper_type) {
6560 case MONO_WRAPPER_NONE:
6561 case MONO_WRAPPER_REMOTING_INVOKE_WITH_CHECK:
6562 case MONO_WRAPPER_XDOMAIN_INVOKE:
6563 case MONO_WRAPPER_STFLD:
6564 case MONO_WRAPPER_LDFLD:
6565 case MONO_WRAPPER_LDFLDA:
6566 case MONO_WRAPPER_LDFLD_REMOTE:
6567 case MONO_WRAPPER_STFLD_REMOTE:
6568 case MONO_WRAPPER_STELEMREF:
6569 case MONO_WRAPPER_ISINST:
6570 case MONO_WRAPPER_PROXY_ISINST:
6571 case MONO_WRAPPER_ALLOC:
6572 case MONO_WRAPPER_REMOTING_INVOKE:
6573 case MONO_WRAPPER_UNKNOWN:
6574 case MONO_WRAPPER_WRITE_BARRIER:
6575 case MONO_WRAPPER_DELEGATE_INVOKE:
6576 case MONO_WRAPPER_DELEGATE_BEGIN_INVOKE:
6577 case MONO_WRAPPER_DELEGATE_END_INVOKE:
6578 case MONO_WRAPPER_SYNCHRONIZED:
6580 case MONO_WRAPPER_MANAGED_TO_MANAGED:
6581 case MONO_WRAPPER_CASTCLASS: {
6582 WrapperInfo *info = mono_marshal_get_wrapper_info (method);
6591 //printf ("Skip (wrapper call): %d -> %s\n", patch_info->type, mono_method_full_name (patch_info->data.method, TRUE));
6595 if (!method->token) {
6596 /* The method is part of a constructed type like Int[,].Set (). */
6597 if (!g_hash_table_lookup (acfg->token_info_hash, method)) {
6598 if (method->klass->rank)
6608 can_encode_patch (MonoAotCompile *acfg, MonoJumpInfo *patch_info)
6610 switch (patch_info->type) {
6611 case MONO_PATCH_INFO_METHOD:
6612 case MONO_PATCH_INFO_METHODCONST:
6613 case MONO_PATCH_INFO_METHOD_CODE_SLOT: {
6614 MonoMethod *method = patch_info->data.method;
6616 return can_encode_method (acfg, method);
6618 case MONO_PATCH_INFO_VTABLE:
6619 case MONO_PATCH_INFO_CLASS_INIT:
6620 case MONO_PATCH_INFO_CLASS:
6621 case MONO_PATCH_INFO_IID:
6622 case MONO_PATCH_INFO_ADJUSTED_IID:
6623 if (!can_encode_class (acfg, patch_info->data.klass)) {
6624 //printf ("Skip: %s\n", mono_type_full_name (&patch_info->data.klass->byval_arg));
6628 case MONO_PATCH_INFO_DELEGATE_TRAMPOLINE: {
6629 if (!can_encode_class (acfg, patch_info->data.del_tramp->klass)) {
6630 //printf ("Skip: %s\n", mono_type_full_name (&patch_info->data.klass->byval_arg));
6635 case MONO_PATCH_INFO_RGCTX_FETCH: {
6636 MonoJumpInfoRgctxEntry *entry = patch_info->data.rgctx_entry;
6638 if (!can_encode_method (acfg, entry->method))
6640 if (!can_encode_patch (acfg, entry->data))
6654 * AOT compile a given method.
6655 * This function might be called by multiple threads, so it must be thread-safe.
6658 compile_method (MonoAotCompile *acfg, MonoMethod *method)
6661 MonoJumpInfo *patch_info;
6664 MonoMethod *wrapped;
6667 if (acfg->aot_opts.metadata_only)
6670 mono_acfg_lock (acfg);
6671 index = get_method_index (acfg, method);
6672 mono_acfg_unlock (acfg);
6674 /* fixme: maybe we can also precompile wrapper methods */
6675 if ((method->flags & METHOD_ATTRIBUTE_PINVOKE_IMPL) ||
6676 (method->iflags & METHOD_IMPL_ATTRIBUTE_RUNTIME) ||
6677 (method->flags & METHOD_ATTRIBUTE_ABSTRACT)) {
6678 //printf ("Skip (impossible): %s\n", mono_method_full_name (method, TRUE));
6682 if (method->iflags & METHOD_IMPL_ATTRIBUTE_INTERNAL_CALL)
6685 wrapped = mono_marshal_method_from_wrapper (method);
6686 if (wrapped && (wrapped->iflags & METHOD_IMPL_ATTRIBUTE_INTERNAL_CALL) && wrapped->is_generic)
6687 // FIXME: The wrapper should be generic too, but it is not
6690 if (method->wrapper_type == MONO_WRAPPER_COMINTEROP)
6693 InterlockedIncrement (&acfg->stats.mcount);
6696 if (method->is_generic || method->klass->generic_container) {
6697 InterlockedIncrement (&acfg->stats.genericcount);
6702 //acfg->aot_opts.print_skipped_methods = TRUE;
6705 * Since these methods are the only ones which are compiled with
6706 * AOT support, and they are not used by runtime startup/shutdown code,
6707 * the runtime will not see AOT methods during AOT compilation,so it
6708 * does not need to support them by creating a fake GOT etc.
6710 flags = JIT_FLAG_AOT;
6711 if (acfg->aot_opts.full_aot)
6712 flags |= JIT_FLAG_FULL_AOT;
6714 flags |= JIT_FLAG_LLVM;
6715 cfg = mini_method_compile (method, acfg->opts, mono_get_root_domain (), flags, 0);
6716 mono_loader_clear_error ();
6718 if (cfg->exception_type == MONO_EXCEPTION_GENERIC_SHARING_FAILED) {
6719 if (acfg->aot_opts.print_skipped_methods)
6720 printf ("Skip (gshared failure): %s (%s)\n", mono_method_full_name (method, TRUE), cfg->exception_message);
6721 InterlockedIncrement (&acfg->stats.genericcount);
6724 if (cfg->exception_type != MONO_EXCEPTION_NONE) {
6725 if (acfg->aot_opts.print_skipped_methods)
6726 printf ("Skip (JIT failure): %s\n", mono_method_full_name (method, TRUE));
6727 /* Let the exception happen at runtime */
6731 if (cfg->disable_aot) {
6732 if (acfg->aot_opts.print_skipped_methods)
6733 printf ("Skip (disabled): %s\n", mono_method_full_name (method, TRUE));
6734 InterlockedIncrement (&acfg->stats.ocount);
6735 mono_destroy_compile (cfg);
6738 cfg->method_index = index;
6740 /* Nullify patches which need no aot processing */
6741 for (patch_info = cfg->patch_info; patch_info; patch_info = patch_info->next) {
6742 switch (patch_info->type) {
6743 case MONO_PATCH_INFO_LABEL:
6744 case MONO_PATCH_INFO_BB:
6745 patch_info->type = MONO_PATCH_INFO_NONE;
6752 /* Collect method->token associations from the cfg */
6753 mono_acfg_lock (acfg);
6754 g_hash_table_foreach (cfg->token_info_hash, add_token_info_hash, acfg);
6755 mono_acfg_unlock (acfg);
6756 g_hash_table_destroy (cfg->token_info_hash);
6757 cfg->token_info_hash = NULL;
6760 * Check for absolute addresses.
6763 for (patch_info = cfg->patch_info; patch_info; patch_info = patch_info->next) {
6764 switch (patch_info->type) {
6765 case MONO_PATCH_INFO_ABS:
6766 /* unable to handle this */
6775 if (acfg->aot_opts.print_skipped_methods)
6776 printf ("Skip (abs call): %s\n", mono_method_full_name (method, TRUE));
6777 InterlockedIncrement (&acfg->stats.abscount);
6778 mono_destroy_compile (cfg);
6782 /* Lock for the rest of the code */
6783 mono_acfg_lock (acfg);
6786 * Check for methods/klasses we can't encode.
6789 for (patch_info = cfg->patch_info; patch_info; patch_info = patch_info->next) {
6790 if (!can_encode_patch (acfg, patch_info))
6795 if (acfg->aot_opts.print_skipped_methods)
6796 printf ("Skip (patches): %s\n", mono_method_full_name (method, TRUE));
6797 acfg->stats.ocount++;
6798 mono_destroy_compile (cfg);
6799 mono_acfg_unlock (acfg);
6803 if (method->is_inflated && acfg->aot_opts.log_instances) {
6804 if (acfg->instances_logfile)
6805 fprintf (acfg->instances_logfile, "%s ### %d\n", mono_method_full_name (method, TRUE), cfg->code_size);
6807 printf ("%s ### %d\n", mono_method_full_name (method, TRUE), cfg->code_size);
6810 /* Adds generic instances referenced by this method */
6812 * The depth is used to avoid infinite loops when generic virtual recursion is
6815 depth = GPOINTER_TO_UINT (g_hash_table_lookup (acfg->method_depth, method));
6816 if (!acfg->aot_opts.no_instances && depth < 32) {
6817 for (patch_info = cfg->patch_info; patch_info; patch_info = patch_info->next) {
6818 switch (patch_info->type) {
6819 case MONO_PATCH_INFO_METHOD: {
6820 MonoMethod *m = patch_info->data.method;
6821 if (m->is_inflated) {
6822 if (!(mono_class_generic_sharing_enabled (m->klass) &&
6823 mono_method_is_generic_sharable_full (m, FALSE, FALSE, FALSE)) &&
6824 !method_has_type_vars (m)) {
6825 if (m->iflags & METHOD_IMPL_ATTRIBUTE_INTERNAL_CALL) {
6826 if (acfg->aot_opts.full_aot)
6827 add_extra_method_with_depth (acfg, mono_marshal_get_native_wrapper (m, TRUE, TRUE), depth + 1);
6829 add_extra_method_with_depth (acfg, m, depth + 1);
6830 add_types_from_method_header (acfg, m);
6833 add_generic_class_with_depth (acfg, m->klass, depth + 5, "method");
6835 if (m->wrapper_type == MONO_WRAPPER_MANAGED_TO_MANAGED) {
6836 WrapperInfo *info = mono_marshal_get_wrapper_info (m);
6838 if (info && info->subtype == WRAPPER_SUBTYPE_ELEMENT_ADDR)
6839 add_extra_method_with_depth (acfg, m, depth + 1);
6843 case MONO_PATCH_INFO_VTABLE: {
6844 MonoClass *klass = patch_info->data.klass;
6846 if (klass->generic_class && !mini_class_is_generic_sharable (klass))
6847 add_generic_class_with_depth (acfg, klass, depth + 5, "vtable");
6850 case MONO_PATCH_INFO_SFLDA: {
6851 MonoClass *klass = patch_info->data.field->parent;
6853 /* The .cctor needs to run at runtime. */
6854 if (klass->generic_class && !mono_generic_context_is_sharable (&klass->generic_class->context, FALSE) && mono_class_get_cctor (klass))
6855 add_extra_method_with_depth (acfg, mono_class_get_cctor (klass), depth + 1);
6864 /* Determine whenever the method has GOT slots */
6865 for (patch_info = cfg->patch_info; patch_info; patch_info = patch_info->next) {
6866 switch (patch_info->type) {
6867 case MONO_PATCH_INFO_GOT_OFFSET:
6868 case MONO_PATCH_INFO_NONE:
6869 case MONO_PATCH_INFO_GC_CARD_TABLE_ADDR:
6871 case MONO_PATCH_INFO_IMAGE:
6872 /* The assembly is stored in GOT slot 0 */
6873 if (patch_info->data.image != acfg->image)
6874 cfg->has_got_slots = TRUE;
6877 if (!is_plt_patch (patch_info))
6878 cfg->has_got_slots = TRUE;
6883 if (!cfg->has_got_slots)
6884 InterlockedIncrement (&acfg->stats.methods_without_got_slots);
6887 * FIXME: Instead of this mess, allocate the patches from the aot mempool.
6889 /* Make a copy of the patch info which is in the mempool */
6891 MonoJumpInfo *patches = NULL, *patches_end = NULL;
6893 for (patch_info = cfg->patch_info; patch_info; patch_info = patch_info->next) {
6894 MonoJumpInfo *new_patch_info = mono_patch_info_dup_mp (acfg->mempool, patch_info);
6897 patches = new_patch_info;
6899 patches_end->next = new_patch_info;
6900 patches_end = new_patch_info;
6902 cfg->patch_info = patches;
6904 /* Make a copy of the unwind info */
6906 GSList *l, *unwind_ops;
6910 for (l = cfg->unwind_ops; l; l = l->next) {
6911 op = mono_mempool_alloc (acfg->mempool, sizeof (MonoUnwindOp));
6912 memcpy (op, l->data, sizeof (MonoUnwindOp));
6913 unwind_ops = g_slist_prepend_mempool (acfg->mempool, unwind_ops, op);
6915 cfg->unwind_ops = g_slist_reverse (unwind_ops);
6917 /* Make a copy of the argument/local info */
6919 MonoInst **args, **locals;
6920 MonoMethodSignature *sig;
6921 MonoMethodHeader *header;
6924 sig = mono_method_signature (method);
6925 args = mono_mempool_alloc (acfg->mempool, sizeof (MonoInst*) * (sig->param_count + sig->hasthis));
6926 for (i = 0; i < sig->param_count + sig->hasthis; ++i) {
6927 args [i] = mono_mempool_alloc (acfg->mempool, sizeof (MonoInst));
6928 memcpy (args [i], cfg->args [i], sizeof (MonoInst));
6932 header = mono_method_get_header (method);
6933 locals = mono_mempool_alloc (acfg->mempool, sizeof (MonoInst*) * header->num_locals);
6934 for (i = 0; i < header->num_locals; ++i) {
6935 locals [i] = mono_mempool_alloc (acfg->mempool, sizeof (MonoInst));
6936 memcpy (locals [i], cfg->locals [i], sizeof (MonoInst));
6938 cfg->locals = locals;
6941 /* Free some fields used by cfg to conserve memory */
6942 mono_mempool_destroy (cfg->mempool);
6943 cfg->mempool = NULL;
6944 g_free (cfg->varinfo);
6945 cfg->varinfo = NULL;
6949 mono_regstate_free (cfg->rs);
6953 //printf ("Compile: %s\n", mono_method_full_name (method, TRUE));
6955 while (index >= acfg->cfgs_size) {
6956 MonoCompile **new_cfgs;
6959 new_size = acfg->cfgs_size * 2;
6960 new_cfgs = g_new0 (MonoCompile*, new_size);
6961 memcpy (new_cfgs, acfg->cfgs, sizeof (MonoCompile*) * acfg->cfgs_size);
6962 g_free (acfg->cfgs);
6963 acfg->cfgs = new_cfgs;
6964 acfg->cfgs_size = new_size;
6966 acfg->cfgs [index] = cfg;
6968 g_hash_table_insert (acfg->method_to_cfg, cfg->orig_method, cfg);
6971 if (cfg->orig_method->wrapper_type)
6972 g_ptr_array_add (acfg->extra_methods, cfg->orig_method);
6975 mono_acfg_unlock (acfg);
6977 InterlockedIncrement (&acfg->stats.ccount);
6981 compile_thread_main (gpointer *user_data)
6983 MonoDomain *domain = user_data [0];
6984 MonoAotCompile *acfg = user_data [1];
6985 GPtrArray *methods = user_data [2];
6988 mono_thread_attach (domain);
6990 for (i = 0; i < methods->len; ++i)
6991 compile_method (acfg, g_ptr_array_index (methods, i));
6995 load_profile_files (MonoAotCompile *acfg)
6999 int file_index, res, method_index, i;
7002 GList *unordered, *l;
7007 tmp = g_strdup_printf ("%s/.mono/aot-profile-data/%s-%d", g_get_home_dir (), acfg->image->assembly_name, file_index);
7009 if (!g_file_test (tmp, G_FILE_TEST_IS_REGULAR)) {
7014 infile = fopen (tmp, "r");
7017 printf ("Using profile data file '%s'\n", tmp);
7022 res = fscanf (infile, "%32s\n", ver);
7023 if ((res != 1) || strcmp (ver, "#VER:2") != 0) {
7024 printf ("Profile file has wrong version or invalid.\n");
7031 MonoMethodDesc *desc;
7034 if (fgets (name, 1023, infile) == NULL)
7037 /* Kill the newline */
7038 if (strlen (name) > 0)
7039 name [strlen (name) - 1] = '\0';
7041 desc = mono_method_desc_new (name, TRUE);
7043 method = mono_method_desc_search_in_image (desc, acfg->image);
7045 if (method && mono_method_get_token (method)) {
7046 token = mono_method_get_token (method);
7047 method_index = mono_metadata_token_index (token) - 1;
7050 for (i = 0; i < acfg->method_order->len; ++i) {
7051 if (g_ptr_array_index (acfg->method_order, i) == GUINT_TO_POINTER (method_index)) {
7057 g_ptr_array_add (acfg->method_order, GUINT_TO_POINTER (method_index));
7059 //printf ("No method found matching '%s'.\n", name);
7065 /* Add missing methods */
7067 for (method_index = 0; method_index < acfg->image->tables [MONO_TABLE_METHOD].rows; ++method_index) {
7069 for (i = 0; i < acfg->method_order->len; ++i) {
7070 if (g_ptr_array_index (acfg->method_order, i) == GUINT_TO_POINTER (method_index)) {
7076 unordered = g_list_prepend (unordered, GUINT_TO_POINTER (method_index));
7078 unordered = g_list_reverse (unordered);
7079 for (l = unordered; l; l = l->next)
7080 g_ptr_array_add (acfg->method_order, l->data);
7083 /* Used by the LLVM backend */
7085 mono_aot_get_got_offset (MonoJumpInfo *ji)
7087 return get_got_offset (llvm_acfg, TRUE, ji);
7091 mono_aot_get_method_name (MonoCompile *cfg)
7093 if (llvm_acfg->aot_opts.static_link)
7094 /* Include the assembly name too to avoid duplicate symbol errors */
7095 return g_strdup_printf ("%s_%s", llvm_acfg->assembly_name_sym, get_debug_sym (cfg->orig_method, "", llvm_acfg->method_label_hash));
7097 return get_debug_sym (cfg->orig_method, "", llvm_acfg->method_label_hash);
7101 mono_aot_is_direct_callable (MonoJumpInfo *patch_info)
7103 return is_direct_callable (llvm_acfg, NULL, patch_info);
7107 mono_aot_mark_unused_llvm_plt_entry (MonoJumpInfo *patch_info)
7109 MonoPltEntry *plt_entry;
7111 plt_entry = get_plt_entry (llvm_acfg, patch_info);
7112 plt_entry->llvm_used = FALSE;
7116 mono_aot_get_plt_symbol (MonoJumpInfoType type, gconstpointer data)
7118 MonoJumpInfo *ji = mono_mempool_alloc (llvm_acfg->mempool, sizeof (MonoJumpInfo));
7119 MonoPltEntry *plt_entry;
7122 ji->data.target = data;
7124 if (!can_encode_patch (llvm_acfg, ji))
7127 plt_entry = get_plt_entry (llvm_acfg, ji);
7128 plt_entry->llvm_used = TRUE;
7130 #if defined(TARGET_MACH)
7131 return g_strdup_printf (plt_entry->llvm_symbol + strlen (llvm_acfg->llvm_label_prefix));
7133 return g_strdup_printf (plt_entry->llvm_symbol);
7138 mono_aot_get_method_index (MonoMethod *method)
7140 g_assert (llvm_acfg);
7141 return get_method_index (llvm_acfg, method);
7145 mono_aot_patch_info_dup (MonoJumpInfo* ji)
7149 mono_acfg_lock (llvm_acfg);
7150 res = mono_patch_info_dup_mp (llvm_acfg->mempool, ji);
7151 mono_acfg_unlock (llvm_acfg);
7161 * Emit the LLVM code into an LLVM bytecode file, and compile it using the LLVM
7165 emit_llvm_file (MonoAotCompile *acfg)
7167 char *command, *opts, *tempbc, *output_fname;
7169 tempbc = g_strdup_printf ("%s.bc", acfg->tmpbasename);
7170 mono_llvm_emit_aot_module (tempbc, g_path_get_basename (acfg->image->name));
7174 * FIXME: Experiment with adding optimizations, the -std-compile-opts set takes
7175 * a lot of time, and doesn't seem to save much space.
7176 * The following optimizations cannot be enabled:
7178 * - 'jump-threading' changes our blockaddress references to int constants.
7179 * - 'basiccg' fails because it contains:
7180 * if (CS && !isa<IntrinsicInst>(II)) {
7181 * and isa<IntrinsicInst> is false for invokes to intrinsics (iltests.exe).
7182 * - 'prune-eh' and 'functionattrs' depend on 'basiccg'.
7183 * The opt list below was produced by taking the output of:
7184 * llvm-as < /dev/null | opt -O2 -disable-output -debug-pass=Arguments
7185 * then removing tailcallelim + the global opts.
7186 * strip-dead-prototypes deletes unused intrinsics definitions.
7188 opts = g_strdup ("-instcombine -simplifycfg");
7189 //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");
7190 /* The dse pass is disabled because of #13734 and #17616 */
7192 * The dse bug is in DeadStoreElimination.cpp:isOverwrite ():
7193 * // If we have no DataLayout information around, then the size of the store
7194 * // is inferrable from the pointee type. If they are the same type, then
7195 * // we know that the store is safe.
7196 * if (AA.getDataLayout() == 0 &&
7197 * Later.Ptr->getType() == Earlier.Ptr->getType()) {
7198 * return OverwriteComplete;
7199 * Here, if 'Earlier' refers to a memset, and Later has no size info, it mistakenly thinks the memset is redundant.
7201 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");
7203 command = g_strdup_printf ("%sopt -f %s -o \"%s.opt.bc\" \"%s.bc\"", acfg->aot_opts.llvm_path, opts, acfg->tmpbasename, acfg->tmpbasename);
7204 aot_printf (acfg, "Executing opt: %s\n", command);
7205 if (system (command) != 0)
7210 if (!acfg->llc_args)
7211 acfg->llc_args = g_string_new ("");
7213 /* Verbose asm slows down llc greatly */
7214 g_string_append (acfg->llc_args, " -asm-verbose=false");
7216 g_string_append (acfg->llc_args, " -disable-gnu-eh-frame -enable-mono-eh-frame");
7218 if (acfg->aot_opts.mtriple)
7219 g_string_append_printf (acfg->llc_args, " -mtriple=%s", acfg->aot_opts.mtriple);
7221 if (acfg->llvm_separate)
7222 g_string_append_printf (acfg->llc_args, " -mono-eh-frame-symbol=%s", acfg->llvm_eh_frame_symbol);
7224 #if defined(TARGET_MACH) && defined(TARGET_ARM)
7225 /* ios requires PIC code now */
7226 g_string_append_printf (acfg->llc_args, " -relocation-model=pic");
7228 if (llvm_acfg->aot_opts.static_link)
7229 g_string_append_printf (acfg->llc_args, " -relocation-model=static");
7231 g_string_append_printf (acfg->llc_args, " -relocation-model=pic");
7233 unlink (acfg->tmpfname);
7235 if (acfg->llvm_separate) {
7236 if (acfg->llvm_owriter) {
7237 /* Emit an object file directly */
7238 output_fname = g_strdup_printf ("%s", acfg->llvm_ofile);
7239 g_string_append_printf (acfg->llc_args, " -filetype=obj");
7241 output_fname = g_strdup_printf ("%s", acfg->llvm_sfile);
7244 output_fname = g_strdup (acfg->tmpfname);
7246 command = g_strdup_printf ("%sllc %s -o \"%s\" \"%s.opt.bc\"", acfg->aot_opts.llvm_path, acfg->llc_args->str, output_fname, acfg->tmpbasename);
7248 aot_printf (acfg, "Executing llc: %s\n", command);
7250 if (system (command) != 0)
7257 emit_code (MonoAotCompile *acfg)
7259 int oindex, i, prev_index;
7262 #if defined(TARGET_POWERPC64)
7263 sprintf (symbol, ".Lgot_addr");
7264 emit_section_change (acfg, ".text", 0);
7265 emit_alignment (acfg, 8);
7266 emit_label (acfg, symbol);
7267 emit_pointer (acfg, acfg->got_symbol);
7271 * This global symbol is used to compute the address of each method using the
7272 * code_offsets array. It is also used to compute the memory ranges occupied by
7273 * AOT code, so it must be equal to the address of the first emitted method.
7275 emit_section_change (acfg, ".text", 0);
7276 emit_alignment_code (acfg, 8);
7278 for (i = 0; i < acfg->nmethods; ++i) {
7279 if (acfg->cfgs [i] && acfg->cfgs [i]->compile_llvm) {
7280 acfg->methods_symbol = g_strdup (acfg->cfgs [i]->asm_symbol);
7285 if (!acfg->methods_symbol) {
7286 sprintf (symbol, "methods");
7287 emit_label (acfg, symbol);
7288 acfg->methods_symbol = g_strdup (symbol);
7290 emit_label (acfg, "jit_code_start");
7293 * Emit some padding so the local symbol for the first method doesn't have the
7294 * same address as 'methods'.
7296 #if defined(__default_codegen__)
7297 emit_padding (acfg, 16);
7298 #elif defined(__native_client_codegen__)
7300 const int kPaddingSize = 16;
7301 guint8 pad_buffer[kPaddingSize];
7302 mono_arch_nacl_pad (pad_buffer, kPaddingSize);
7303 emit_bytes (acfg, pad_buffer, kPaddingSize);
7307 for (oindex = 0; oindex < acfg->method_order->len; ++oindex) {
7311 i = GPOINTER_TO_UINT (g_ptr_array_index (acfg->method_order, oindex));
7313 cfg = acfg->cfgs [i];
7318 method = cfg->orig_method;
7320 /* Emit unbox trampoline */
7321 if (acfg->aot_opts.full_aot && cfg->orig_method->klass->valuetype) {
7322 sprintf (symbol, "ut_%d", get_method_index (acfg, method));
7324 emit_section_change (acfg, ".text", 0);
7325 #ifdef __native_client_codegen__
7326 emit_alignment (acfg, AOT_FUNC_ALIGNMENT);
7329 if (acfg->thumb_mixed && cfg->compile_llvm) {
7330 emit_set_thumb_mode (acfg);
7331 fprintf (acfg->fp, "\n.thumb_func\n");
7334 emit_label (acfg, symbol);
7336 arch_emit_unbox_trampoline (acfg, cfg, cfg->orig_method, cfg->asm_symbol);
7338 if (acfg->thumb_mixed && cfg->compile_llvm)
7339 emit_set_arm_mode (acfg);
7342 if (cfg->compile_llvm)
7343 acfg->stats.llvm_count ++;
7345 emit_method_code (acfg, cfg);
7348 emit_section_change (acfg, ".text", 0);
7349 emit_alignment_code (acfg, 8);
7350 emit_label (acfg, "jit_code_end");
7352 /* To distinguish it from the next symbol */
7353 emit_padding (acfg, 4);
7356 * Add .no_dead_strip directives for all LLVM methods to prevent the OSX linker
7357 * from optimizing them away, since it doesn't see that code_offsets references them.
7358 * JITted methods don't need this since they are referenced using assembler local
7360 * FIXME: This is why write-symbols doesn't work on OSX ?
7362 if (acfg->llvm && acfg->need_no_dead_strip) {
7363 fprintf (acfg->fp, "\n");
7364 for (i = 0; i < acfg->nmethods; ++i) {
7365 if (acfg->cfgs [i] && acfg->cfgs [i]->compile_llvm)
7366 fprintf (acfg->fp, ".no_dead_strip %s\n", acfg->cfgs [i]->asm_symbol);
7371 * To work around linker issues, we emit a table of branches, and disassemble them at runtime.
7372 * This is PIE code, and the linker can update it if needed.
7374 sprintf (symbol, "method_addresses");
7375 emit_section_change (acfg, ".text", 1);
7376 emit_alignment_code (acfg, 8);
7377 emit_label (acfg, symbol);
7378 emit_local_symbol (acfg, symbol, "method_addresses_end", TRUE);
7379 emit_unset_mode (acfg);
7380 if (acfg->need_no_dead_strip)
7381 fprintf (acfg->fp, " .no_dead_strip %s\n", symbol);
7383 for (i = 0; i < acfg->nmethods; ++i) {
7384 #ifdef MONO_ARCH_AOT_SUPPORTED
7388 arch_emit_direct_call (acfg, acfg->cfgs [i]->asm_symbol, FALSE, acfg->thumb_mixed && acfg->cfgs [i]->compile_llvm, NULL, &call_size);
7390 arch_emit_direct_call (acfg, "method_addresses", FALSE, FALSE, NULL, &call_size);
7394 sprintf (symbol, "method_addresses_end");
7395 emit_label (acfg, symbol);
7398 /* Emit a sorted table mapping methods to the index of their unbox trampolines */
7399 sprintf (symbol, "unbox_trampolines");
7400 emit_section_change (acfg, RODATA_SECT, 0);
7401 emit_alignment (acfg, 8);
7402 emit_label (acfg, symbol);
7405 for (i = 0; i < acfg->nmethods; ++i) {
7410 cfg = acfg->cfgs [i];
7414 method = cfg->orig_method;
7416 if (acfg->aot_opts.full_aot && cfg->orig_method->klass->valuetype) {
7417 index = get_method_index (acfg, method);
7419 emit_int32 (acfg, index);
7420 /* Make sure the table is sorted by index */
7421 g_assert (index > prev_index);
7425 sprintf (symbol, "unbox_trampolines_end");
7426 emit_label (acfg, symbol);
7427 emit_int32 (acfg, 0);
7429 /* Emit a separate table with the trampoline addresses/offsets */
7430 sprintf (symbol, "unbox_trampoline_addresses");
7431 emit_section_change (acfg, ".text", 0);
7432 emit_alignment_code (acfg, 8);
7433 emit_label (acfg, symbol);
7435 for (i = 0; i < acfg->nmethods; ++i) {
7440 cfg = acfg->cfgs [i];
7444 method = cfg->orig_method;
7446 if (acfg->aot_opts.full_aot && cfg->orig_method->klass->valuetype) {
7447 #ifdef MONO_ARCH_AOT_SUPPORTED
7450 index = get_method_index (acfg, method);
7451 sprintf (symbol, "ut_%d", index);
7453 arch_emit_direct_call (acfg, symbol, FALSE, acfg->thumb_mixed && cfg->compile_llvm, NULL, &call_size);
7457 emit_int32 (acfg, 0);
7461 emit_info (MonoAotCompile *acfg)
7467 offsets = g_new0 (gint32, acfg->nmethods);
7469 for (oindex = 0; oindex < acfg->method_order->len; ++oindex) {
7470 i = GPOINTER_TO_UINT (g_ptr_array_index (acfg->method_order, oindex));
7472 if (acfg->cfgs [i]) {
7473 emit_method_info (acfg, acfg->cfgs [i]);
7474 offsets [i] = acfg->cfgs [i]->method_info_offset;
7480 sprintf (symbol, "method_info_offsets");
7481 emit_section_change (acfg, RODATA_SECT, 1);
7482 emit_alignment (acfg, 8);
7483 emit_label (acfg, symbol);
7485 acfg->stats.offsets_size += emit_offset_table (acfg, acfg->nmethods, 10, offsets);
7490 #endif /* #if !defined(DISABLE_AOT) && !defined(DISABLE_JIT) */
7492 #define rot(x,k) (((x)<<(k)) | ((x)>>(32-(k))))
7493 #define mix(a,b,c) { \
7494 a -= c; a ^= rot(c, 4); c += b; \
7495 b -= a; b ^= rot(a, 6); a += c; \
7496 c -= b; c ^= rot(b, 8); b += a; \
7497 a -= c; a ^= rot(c,16); c += b; \
7498 b -= a; b ^= rot(a,19); a += c; \
7499 c -= b; c ^= rot(b, 4); b += a; \
7501 #define final(a,b,c) { \
7502 c ^= b; c -= rot(b,14); \
7503 a ^= c; a -= rot(c,11); \
7504 b ^= a; b -= rot(a,25); \
7505 c ^= b; c -= rot(b,16); \
7506 a ^= c; a -= rot(c,4); \
7507 b ^= a; b -= rot(a,14); \
7508 c ^= b; c -= rot(b,24); \
7512 mono_aot_type_hash (MonoType *t1)
7514 guint hash = t1->type;
7516 hash |= t1->byref << 6; /* do not collide with t1->type values */
7518 case MONO_TYPE_VALUETYPE:
7519 case MONO_TYPE_CLASS:
7520 case MONO_TYPE_SZARRAY:
7521 /* check if the distribution is good enough */
7522 return ((hash << 5) - hash) ^ mono_metadata_str_hash (t1->data.klass->name);
7524 return ((hash << 5) - hash) ^ mono_metadata_type_hash (t1->data.type);
7525 case MONO_TYPE_ARRAY:
7526 return ((hash << 5) - hash) ^ mono_metadata_type_hash (&t1->data.array->eklass->byval_arg);
7527 case MONO_TYPE_GENERICINST:
7528 return ((hash << 5) - hash) ^ 0;
7535 * mono_aot_method_hash:
7537 * Return a hash code for methods which only depends on metadata.
7540 mono_aot_method_hash (MonoMethod *method)
7542 MonoMethodSignature *sig;
7546 guint32 *hashes_start, *hashes;
7548 MonoGenericInst *ginst = NULL;
7550 /* Similar to the hash in mono_method_get_imt_slot () */
7552 sig = mono_method_signature (method);
7554 if (method->is_inflated)
7555 ginst = ((MonoMethodInflated*)method)->context.method_inst;
7557 hashes_count = sig->param_count + 5 + (ginst ? ginst->type_argc : 0);
7558 hashes_start = g_malloc0 (hashes_count * sizeof (guint32));
7559 hashes = hashes_start;
7561 /* Some wrappers are assigned to random classes */
7562 if (!method->wrapper_type || method->wrapper_type == MONO_WRAPPER_REMOTING_INVOKE_WITH_CHECK)
7563 klass = method->klass;
7565 klass = mono_defaults.object_class;
7567 if (!method->wrapper_type) {
7568 char *full_name = mono_type_full_name (&klass->byval_arg);
7570 hashes [0] = mono_metadata_str_hash (full_name);
7574 hashes [0] = mono_metadata_str_hash (klass->name);
7575 hashes [1] = mono_metadata_str_hash (klass->name_space);
7577 if (method->wrapper_type == MONO_WRAPPER_STFLD || method->wrapper_type == MONO_WRAPPER_LDFLD || method->wrapper_type == MONO_WRAPPER_LDFLDA)
7578 /* The method name includes a stringified pointer */
7581 hashes [2] = mono_metadata_str_hash (method->name);
7582 hashes [3] = method->wrapper_type;
7583 hashes [4] = mono_aot_type_hash (sig->ret);
7585 for (i = 0; i < sig->param_count; i++) {
7586 hashes [hindex ++] = mono_aot_type_hash (sig->params [i]);
7589 for (i = 0; i < ginst->type_argc; ++i)
7590 hashes [hindex ++] = mono_aot_type_hash (ginst->type_argv [i]);
7592 g_assert (hindex == hashes_count);
7594 /* Setup internal state */
7595 a = b = c = 0xdeadbeef + (((guint32)hashes_count)<<2);
7597 /* Handle most of the hashes */
7598 while (hashes_count > 3) {
7607 /* Handle the last 3 hashes (all the case statements fall through) */
7608 switch (hashes_count) {
7609 case 3 : c += hashes [2];
7610 case 2 : b += hashes [1];
7611 case 1 : a += hashes [0];
7613 case 0: /* nothing left to add */
7617 free (hashes_start);
7626 * mono_aot_get_array_helper_from_wrapper;
7628 * Get the helper method in Array called by an array wrapper method.
7631 mono_aot_get_array_helper_from_wrapper (MonoMethod *method)
7635 MonoGenericContext ctx;
7636 MonoType *args [16];
7637 char *mname, *iname, *s, *s2, *helper_name = NULL;
7639 prefix = "System.Collections.Generic";
7640 s = g_strdup_printf ("%s", method->name + strlen (prefix) + 1);
7641 s2 = strstr (s, "`1.");
7647 //printf ("X: %s %s\n", iname, mname);
7649 if (!strcmp (iname, "IList"))
7650 helper_name = g_strdup_printf ("InternalArray__%s", mname);
7652 helper_name = g_strdup_printf ("InternalArray__%s_%s", iname, mname);
7653 m = mono_class_get_method_from_name (mono_defaults.array_class, helper_name, mono_method_signature (method)->param_count);
7655 g_free (helper_name);
7658 if (m->is_generic) {
7660 memset (&ctx, 0, sizeof (ctx));
7661 args [0] = &method->klass->element_class->byval_arg;
7662 ctx.method_inst = mono_metadata_get_generic_inst (1, args);
7663 m = mono_class_inflate_generic_method_checked (m, &ctx, &error);
7664 g_assert (mono_error_ok (&error)); /* FIXME don't swallow the error */
7670 #if !defined(DISABLE_AOT) && !defined(DISABLE_JIT)
7672 typedef struct HashEntry {
7673 guint32 key, value, index;
7674 struct HashEntry *next;
7678 * emit_extra_methods:
7680 * Emit methods which are not in the METHOD table, like wrappers.
7683 emit_extra_methods (MonoAotCompile *acfg)
7685 int i, table_size, buf_size;
7688 guint32 *info_offsets;
7691 HashEntry *entry, *new_entry;
7692 int nmethods, max_chain_length;
7695 info_offsets = g_new0 (guint32, acfg->extra_methods->len);
7697 /* Emit method info */
7699 for (i = 0; i < acfg->extra_methods->len; ++i) {
7700 MonoMethod *method = g_ptr_array_index (acfg->extra_methods, i);
7701 MonoCompile *cfg = g_hash_table_lookup (acfg->method_to_cfg, method);
7707 p = buf = g_malloc (buf_size);
7711 method = cfg->method_to_register;
7713 encode_method_ref (acfg, method, p, &p);
7715 g_assert ((p - buf) < buf_size);
7717 info_offsets [i] = add_to_blob (acfg, buf, p - buf);
7722 * Construct a chained hash table for mapping indexes in extra_method_info to
7725 table_size = g_spaced_primes_closest ((int)(nmethods * 1.5));
7726 table = g_ptr_array_sized_new (table_size);
7727 for (i = 0; i < table_size; ++i)
7728 g_ptr_array_add (table, NULL);
7729 chain_lengths = g_new0 (int, table_size);
7730 max_chain_length = 0;
7731 for (i = 0; i < acfg->extra_methods->len; ++i) {
7732 MonoMethod *method = g_ptr_array_index (acfg->extra_methods, i);
7733 MonoCompile *cfg = g_hash_table_lookup (acfg->method_to_cfg, method);
7739 key = info_offsets [i];
7740 value = get_method_index (acfg, method);
7742 hash = mono_aot_method_hash (method) % table_size;
7743 //printf ("X: %s %d\n", mono_method_full_name (method, 1), hash);
7745 chain_lengths [hash] ++;
7746 max_chain_length = MAX (max_chain_length, chain_lengths [hash]);
7748 new_entry = mono_mempool_alloc0 (acfg->mempool, sizeof (HashEntry));
7749 new_entry->key = key;
7750 new_entry->value = value;
7752 entry = g_ptr_array_index (table, hash);
7753 if (entry == NULL) {
7754 new_entry->index = hash;
7755 g_ptr_array_index (table, hash) = new_entry;
7758 entry = entry->next;
7760 entry->next = new_entry;
7761 new_entry->index = table->len;
7762 g_ptr_array_add (table, new_entry);
7766 //printf ("MAX: %d\n", max_chain_length);
7768 /* Emit the table */
7769 sprintf (symbol, "extra_method_table");
7770 emit_section_change (acfg, RODATA_SECT, 0);
7771 emit_alignment (acfg, 8);
7772 emit_label (acfg, symbol);
7774 emit_int32 (acfg, table_size);
7775 for (i = 0; i < table->len; ++i) {
7776 HashEntry *entry = g_ptr_array_index (table, i);
7778 if (entry == NULL) {
7779 emit_int32 (acfg, 0);
7780 emit_int32 (acfg, 0);
7781 emit_int32 (acfg, 0);
7783 //g_assert (entry->key > 0);
7784 emit_int32 (acfg, entry->key);
7785 emit_int32 (acfg, entry->value);
7787 emit_int32 (acfg, entry->next->index);
7789 emit_int32 (acfg, 0);
7794 * Emit a table reverse mapping method indexes to their index in extra_method_info.
7795 * This is used by mono_aot_find_jit_info ().
7797 sprintf (symbol, "extra_method_info_offsets");
7798 emit_section_change (acfg, RODATA_SECT, 0);
7799 emit_alignment (acfg, 8);
7800 emit_label (acfg, symbol);
7802 emit_int32 (acfg, acfg->extra_methods->len);
7803 for (i = 0; i < acfg->extra_methods->len; ++i) {
7804 MonoMethod *method = g_ptr_array_index (acfg->extra_methods, i);
7806 emit_int32 (acfg, get_method_index (acfg, method));
7807 emit_int32 (acfg, info_offsets [i]);
7812 emit_exception_info (MonoAotCompile *acfg)
7818 offsets = g_new0 (gint32, acfg->nmethods);
7819 for (i = 0; i < acfg->nmethods; ++i) {
7820 if (acfg->cfgs [i]) {
7821 emit_exception_debug_info (acfg, acfg->cfgs [i]);
7822 offsets [i] = acfg->cfgs [i]->ex_info_offset;
7828 sprintf (symbol, "ex_info_offsets");
7829 emit_section_change (acfg, RODATA_SECT, 1);
7830 emit_alignment (acfg, 8);
7831 emit_label (acfg, symbol);
7833 acfg->stats.offsets_size += emit_offset_table (acfg, acfg->nmethods, 10, offsets);
7838 emit_unwind_info (MonoAotCompile *acfg)
7844 * The unwind info contains a lot of duplicates so we emit each unique
7845 * entry once, and only store the offset from the start of the table in the
7849 sprintf (symbol, "unwind_info");
7850 emit_section_change (acfg, RODATA_SECT, 1);
7851 emit_alignment (acfg, 8);
7852 emit_label (acfg, symbol);
7854 for (i = 0; i < acfg->unwind_ops->len; ++i) {
7855 guint32 index = GPOINTER_TO_UINT (g_ptr_array_index (acfg->unwind_ops, i));
7856 guint8 *unwind_info;
7857 guint32 unwind_info_len;
7861 unwind_info = mono_get_cached_unwind_info (index, &unwind_info_len);
7864 encode_value (unwind_info_len, p, &p);
7865 emit_bytes (acfg, buf, p - buf);
7866 emit_bytes (acfg, unwind_info, unwind_info_len);
7868 acfg->stats.unwind_info_size += (p - buf) + unwind_info_len;
7873 emit_class_info (MonoAotCompile *acfg)
7879 offsets = g_new0 (gint32, acfg->image->tables [MONO_TABLE_TYPEDEF].rows);
7880 for (i = 0; i < acfg->image->tables [MONO_TABLE_TYPEDEF].rows; ++i)
7881 offsets [i] = emit_klass_info (acfg, MONO_TOKEN_TYPE_DEF | (i + 1));
7883 sprintf (symbol, "class_info_offsets");
7884 emit_section_change (acfg, RODATA_SECT, 1);
7885 emit_alignment (acfg, 8);
7886 emit_label (acfg, symbol);
7888 acfg->stats.offsets_size += emit_offset_table (acfg, acfg->image->tables [MONO_TABLE_TYPEDEF].rows, 10, offsets);
7892 typedef struct ClassNameTableEntry {
7893 guint32 token, index;
7894 struct ClassNameTableEntry *next;
7895 } ClassNameTableEntry;
7898 emit_class_name_table (MonoAotCompile *acfg)
7901 guint32 token, hash;
7906 ClassNameTableEntry *entry, *new_entry;
7909 * Construct a chained hash table for mapping class names to typedef tokens.
7911 table_size = g_spaced_primes_closest ((int)(acfg->image->tables [MONO_TABLE_TYPEDEF].rows * 1.5));
7912 table = g_ptr_array_sized_new (table_size);
7913 for (i = 0; i < table_size; ++i)
7914 g_ptr_array_add (table, NULL);
7915 for (i = 0; i < acfg->image->tables [MONO_TABLE_TYPEDEF].rows; ++i) {
7917 token = MONO_TOKEN_TYPE_DEF | (i + 1);
7918 klass = mono_class_get_checked (acfg->image, token, &error);
7920 mono_error_cleanup (&error);
7923 full_name = mono_type_get_name_full (mono_class_get_type (klass), MONO_TYPE_NAME_FORMAT_FULL_NAME);
7924 hash = mono_metadata_str_hash (full_name) % table_size;
7927 /* FIXME: Allocate from the mempool */
7928 new_entry = g_new0 (ClassNameTableEntry, 1);
7929 new_entry->token = token;
7931 entry = g_ptr_array_index (table, hash);
7932 if (entry == NULL) {
7933 new_entry->index = hash;
7934 g_ptr_array_index (table, hash) = new_entry;
7937 entry = entry->next;
7939 entry->next = new_entry;
7940 new_entry->index = table->len;
7941 g_ptr_array_add (table, new_entry);
7945 /* Emit the table */
7946 sprintf (symbol, "class_name_table");
7947 emit_section_change (acfg, RODATA_SECT, 0);
7948 emit_alignment (acfg, 8);
7949 emit_label (acfg, symbol);
7951 /* FIXME: Optimize memory usage */
7952 g_assert (table_size < 65000);
7953 emit_int16 (acfg, table_size);
7954 g_assert (table->len < 65000);
7955 for (i = 0; i < table->len; ++i) {
7956 ClassNameTableEntry *entry = g_ptr_array_index (table, i);
7958 if (entry == NULL) {
7959 emit_int16 (acfg, 0);
7960 emit_int16 (acfg, 0);
7962 emit_int16 (acfg, mono_metadata_token_index (entry->token));
7964 emit_int16 (acfg, entry->next->index);
7966 emit_int16 (acfg, 0);
7972 emit_image_table (MonoAotCompile *acfg)
7978 * The image table is small but referenced in a lot of places.
7979 * So we emit it at once, and reference its elements by an index.
7982 sprintf (symbol, "image_table");
7983 emit_section_change (acfg, RODATA_SECT, 1);
7984 emit_alignment (acfg, 8);
7985 emit_label (acfg, symbol);
7987 emit_int32 (acfg, acfg->image_table->len);
7988 for (i = 0; i < acfg->image_table->len; i++) {
7989 MonoImage *image = (MonoImage*)g_ptr_array_index (acfg->image_table, i);
7990 MonoAssemblyName *aname = &image->assembly->aname;
7992 /* FIXME: Support multi-module assemblies */
7993 g_assert (image->assembly->image == image);
7995 emit_string (acfg, image->assembly_name);
7996 emit_string (acfg, image->guid);
7997 emit_string (acfg, aname->culture ? aname->culture : "");
7998 emit_string (acfg, (const char*)aname->public_key_token);
8000 emit_alignment (acfg, 8);
8001 emit_int32 (acfg, aname->flags);
8002 emit_int32 (acfg, aname->major);
8003 emit_int32 (acfg, aname->minor);
8004 emit_int32 (acfg, aname->build);
8005 emit_int32 (acfg, aname->revision);
8010 emit_got_info (MonoAotCompile *acfg, gboolean llvm)
8013 int i, first_plt_got_patch = 0, buf_size;
8015 guint32 *got_info_offsets;
8016 GotInfo *info = llvm ? &acfg->llvm_got_info : &acfg->got_info;
8018 /* Add the patches needed by the PLT to the GOT */
8020 acfg->plt_got_offset_base = acfg->got_offset;
8021 first_plt_got_patch = info->got_patches->len;
8022 for (i = 1; i < acfg->plt_offset; ++i) {
8023 MonoPltEntry *plt_entry = g_hash_table_lookup (acfg->plt_offset_to_entry, GUINT_TO_POINTER (i));
8025 g_ptr_array_add (info->got_patches, plt_entry->ji);
8027 acfg->stats.got_slot_types [plt_entry->ji->type] ++;
8030 acfg->got_offset += acfg->plt_offset;
8035 * - optimize offsets table.
8036 * - reduce number of exported symbols.
8037 * - emit info for a klass only once.
8038 * - determine when a method uses a GOT slot which is guaranteed to be already
8040 * - clean up and document the code.
8041 * - use String.Empty in class libs.
8044 /* Encode info required to decode shared GOT entries */
8045 buf_size = info->got_patches->len * 128;
8046 p = buf = mono_mempool_alloc (acfg->mempool, buf_size);
8047 got_info_offsets = mono_mempool_alloc (acfg->mempool, info->got_patches->len * sizeof (guint32));
8049 acfg->plt_got_info_offsets = mono_mempool_alloc (acfg->mempool, acfg->plt_offset * sizeof (guint32));
8051 if (acfg->plt_offset)
8052 acfg->plt_got_info_offsets [0] = 0;
8054 for (i = 0; i < info->got_patches->len; ++i) {
8055 MonoJumpInfo *ji = g_ptr_array_index (info->got_patches, i);
8060 encode_value (ji->type, p, &p);
8062 encode_patch (acfg, ji, p, &p);
8063 acfg->stats.got_slot_info_sizes [ji->type] += p - p2;
8064 g_assert (p - buf <= buf_size);
8065 got_info_offsets [i] = add_to_blob (acfg, buf, p - buf);
8067 if (!llvm && i >= first_plt_got_patch)
8068 acfg->plt_got_info_offsets [i - first_plt_got_patch + 1] = got_info_offsets [i];
8069 acfg->stats.got_info_size += p - buf;
8072 /* Emit got_info_offsets table */
8074 sprintf (symbol, "llvm_got_info_offsets");
8076 sprintf (symbol, "got_info_offsets");
8077 emit_section_change (acfg, RODATA_SECT, 1);
8078 emit_alignment (acfg, 8);
8079 emit_label (acfg, symbol);
8081 /* No need to emit offsets for the got plt entries, the plt embeds them directly */
8082 acfg->stats.offsets_size += emit_offset_table (acfg, llvm ? acfg->llvm_got_offset : first_plt_got_patch, 10, (gint32*)got_info_offsets);
8086 emit_got (MonoAotCompile *acfg)
8090 /* Don't make GOT global so accesses to it don't need relocations */
8091 sprintf (symbol, "%s", acfg->got_symbol);
8092 emit_section_change (acfg, ".bss", 0);
8093 emit_alignment (acfg, 8);
8094 emit_local_symbol (acfg, symbol, "got_end", FALSE);
8095 emit_label (acfg, symbol);
8096 if (acfg->got_offset > 0)
8097 emit_zero_bytes (acfg, (int)(acfg->got_offset * sizeof (gpointer)));
8099 sprintf (symbol, "got_end");
8100 emit_label (acfg, symbol);
8103 typedef struct GlobalsTableEntry {
8104 guint32 value, index;
8105 struct GlobalsTableEntry *next;
8106 } GlobalsTableEntry;
8109 emit_globals (MonoAotCompile *acfg)
8115 GlobalsTableEntry *entry, *new_entry;
8117 if (!acfg->aot_opts.static_link)
8121 * When static linking, we emit a table containing our globals.
8125 * Construct a chained hash table for mapping global names to their index in
8126 * the globals table.
8128 table_size = g_spaced_primes_closest ((int)(acfg->globals->len * 1.5));
8129 table = g_ptr_array_sized_new (table_size);
8130 for (i = 0; i < table_size; ++i)
8131 g_ptr_array_add (table, NULL);
8132 for (i = 0; i < acfg->globals->len; ++i) {
8133 char *name = g_ptr_array_index (acfg->globals, i);
8135 hash = mono_metadata_str_hash (name) % table_size;
8137 /* FIXME: Allocate from the mempool */
8138 new_entry = g_new0 (GlobalsTableEntry, 1);
8139 new_entry->value = i;
8141 entry = g_ptr_array_index (table, hash);
8142 if (entry == NULL) {
8143 new_entry->index = hash;
8144 g_ptr_array_index (table, hash) = new_entry;
8147 entry = entry->next;
8149 entry->next = new_entry;
8150 new_entry->index = table->len;
8151 g_ptr_array_add (table, new_entry);
8155 /* Emit the table */
8156 sprintf (symbol, ".Lglobals_hash");
8157 emit_section_change (acfg, RODATA_SECT, 0);
8158 emit_alignment (acfg, 8);
8159 emit_label (acfg, symbol);
8161 /* FIXME: Optimize memory usage */
8162 g_assert (table_size < 65000);
8163 emit_int16 (acfg, table_size);
8164 for (i = 0; i < table->len; ++i) {
8165 GlobalsTableEntry *entry = g_ptr_array_index (table, i);
8167 if (entry == NULL) {
8168 emit_int16 (acfg, 0);
8169 emit_int16 (acfg, 0);
8171 emit_int16 (acfg, entry->value + 1);
8173 emit_int16 (acfg, entry->next->index);
8175 emit_int16 (acfg, 0);
8179 /* Emit the names */
8180 for (i = 0; i < acfg->globals->len; ++i) {
8181 char *name = g_ptr_array_index (acfg->globals, i);
8183 sprintf (symbol, "name_%d", i);
8184 emit_section_change (acfg, RODATA_SECT, 1);
8186 emit_alignment (acfg, 4);
8188 emit_label (acfg, symbol);
8189 emit_string (acfg, name);
8192 /* Emit the globals table */
8193 sprintf (symbol, "globals");
8194 emit_section_change (acfg, ".data", 0);
8195 /* This is not a global, since it is accessed by the init function */
8196 emit_alignment (acfg, 8);
8197 emit_label (acfg, symbol);
8199 sprintf (symbol, "%sglobals_hash", acfg->temp_prefix);
8200 emit_pointer (acfg, symbol);
8202 for (i = 0; i < acfg->globals->len; ++i) {
8203 char *name = g_ptr_array_index (acfg->globals, i);
8205 sprintf (symbol, "name_%d", i);
8206 emit_pointer (acfg, symbol);
8208 g_assert (strlen (name) < sizeof (symbol));
8209 sprintf (symbol, "%s", name);
8210 emit_pointer (acfg, symbol);
8212 /* Null terminate the table */
8213 emit_int32 (acfg, 0);
8214 emit_int32 (acfg, 0);
8218 emit_autoreg (MonoAotCompile *acfg)
8223 * Emit a function into the .ctor section which will be called by the ELF
8224 * loader to register this module with the runtime.
8226 if (! (!acfg->use_bin_writer && acfg->aot_opts.static_link && acfg->aot_opts.autoreg))
8229 symbol = g_strdup_printf ("_%s_autoreg", acfg->static_linking_symbol);
8231 arch_emit_autoreg (acfg, symbol);
8237 emit_mem_end (MonoAotCompile *acfg)
8241 sprintf (symbol, "mem_end");
8242 emit_section_change (acfg, ".text", 1);
8243 emit_alignment_code (acfg, 8);
8244 emit_label (acfg, symbol);
8248 * Emit a structure containing all the information not stored elsewhere.
8251 emit_file_info (MonoAotCompile *acfg)
8256 const char *gc_name;
8259 emit_string_symbol (acfg, "assembly_guid" , acfg->image->guid);
8261 if (acfg->aot_opts.bind_to_runtime_version) {
8262 build_info = mono_get_runtime_build_info ();
8263 emit_string_symbol (acfg, "runtime_version", build_info);
8264 g_free (build_info);
8266 emit_string_symbol (acfg, "runtime_version", "");
8269 /* Emit a string holding the assembly name */
8270 emit_string_symbol (acfg, "assembly_name", acfg->image->assembly->aname.name);
8273 * The managed allocators are GC specific, so can't use an AOT image created by one GC
8276 gc_name = mono_gc_get_gc_name ();
8277 gc_name_offset = add_to_blob (acfg, (guint8*)gc_name, strlen (gc_name) + 1);
8279 sprintf (symbol, "%smono_aot_file_info", acfg->user_symbol_prefix);
8280 emit_section_change (acfg, ".data", 0);
8281 emit_alignment (acfg, 8);
8282 emit_label (acfg, symbol);
8283 if (!acfg->aot_opts.static_link)
8284 emit_global (acfg, symbol, FALSE);
8286 /* The data emitted here must match MonoAotFileInfo. */
8288 emit_int32 (acfg, MONO_AOT_FILE_VERSION);
8289 emit_int32 (acfg, 0);
8292 * We emit pointers to our data structures instead of emitting global symbols which
8293 * point to them, to reduce the number of globals, and because using globals leads to
8294 * various problems (i.e. arm/thumb).
8296 emit_pointer (acfg, acfg->got_symbol);
8298 emit_pointer (acfg, acfg->llvm_got_symbol);
8300 emit_pointer (acfg, NULL);
8301 emit_pointer (acfg, acfg->methods_symbol);
8302 emit_pointer (acfg, "jit_code_start");
8303 emit_pointer (acfg, "jit_code_end");
8306 * Emit a reference to the mono_eh_frame table created by our modified LLVM compiler.
8308 emit_pointer (acfg, acfg->llvm_eh_frame_symbol);
8310 emit_pointer (acfg, NULL);
8312 emit_pointer (acfg, "blob");
8313 emit_pointer (acfg, "class_name_table");
8314 emit_pointer (acfg, "class_info_offsets");
8315 emit_pointer (acfg, "method_info_offsets");
8316 emit_pointer (acfg, "ex_info_offsets");
8317 emit_pointer (acfg, "method_addresses");
8318 emit_pointer (acfg, "extra_method_info_offsets");
8319 emit_pointer (acfg, "extra_method_table");
8320 emit_pointer (acfg, "got_info_offsets");
8322 emit_pointer (acfg, "llvm_got_info_offsets");
8324 emit_pointer (acfg, NULL);
8325 emit_pointer (acfg, "unwind_info");
8326 emit_pointer (acfg, "mem_end");
8327 emit_pointer (acfg, "image_table");
8328 emit_pointer (acfg, "plt");
8329 emit_pointer (acfg, "plt_end");
8330 emit_pointer (acfg, "assembly_guid");
8331 emit_pointer (acfg, "runtime_version");
8332 if (acfg->num_trampoline_got_entries) {
8333 emit_pointer (acfg, "specific_trampolines");
8334 emit_pointer (acfg, "static_rgctx_trampolines");
8335 emit_pointer (acfg, "imt_thunks");
8336 emit_pointer (acfg, "gsharedvt_arg_trampolines");
8338 emit_pointer (acfg, NULL);
8339 emit_pointer (acfg, NULL);
8340 emit_pointer (acfg, NULL);
8341 emit_pointer (acfg, NULL);
8343 if (acfg->thumb_mixed) {
8344 emit_pointer (acfg, "thumb_end");
8346 emit_pointer (acfg, NULL);
8348 if (acfg->aot_opts.static_link) {
8349 emit_pointer (acfg, "globals");
8351 emit_pointer (acfg, NULL);
8353 emit_pointer (acfg, "assembly_name");
8354 emit_pointer (acfg, "unbox_trampolines");
8355 emit_pointer (acfg, "unbox_trampolines_end");
8356 emit_pointer (acfg, "unbox_trampoline_addresses");
8358 emit_int32 (acfg, acfg->plt_got_offset_base);
8359 emit_int32 (acfg, (int)(acfg->got_offset * sizeof (gpointer)));
8360 emit_int32 (acfg, acfg->plt_offset);
8361 emit_int32 (acfg, acfg->nmethods);
8362 emit_int32 (acfg, acfg->flags);
8363 emit_int32 (acfg, acfg->opts);
8364 emit_int32 (acfg, acfg->simd_opts);
8365 emit_int32 (acfg, gc_name_offset);
8367 for (i = 0; i < MONO_AOT_TRAMP_NUM; ++i)
8368 emit_int32 (acfg, acfg->num_trampolines [i]);
8369 for (i = 0; i < MONO_AOT_TRAMP_NUM; ++i)
8370 emit_int32 (acfg, acfg->trampoline_got_offset_base [i]);
8371 for (i = 0; i < MONO_AOT_TRAMP_NUM; ++i)
8372 emit_int32 (acfg, acfg->trampoline_size [i]);
8373 emit_int32 (acfg, acfg->aot_opts.nrgctx_fetch_trampolines);
8375 #if defined (TARGET_ARM) && defined (TARGET_MACH)
8380 memset (&t, 0, sizeof (MonoType));
8381 t.type = MONO_TYPE_R8;
8382 mono_type_size (&t, &align);
8383 emit_int32 (acfg, align);
8385 memset (&t, 0, sizeof (MonoType));
8386 t.type = MONO_TYPE_I8;
8387 mono_type_size (&t, &align);
8389 emit_int32 (acfg, align);
8392 emit_int32 (acfg, MONO_ABI_ALIGNOF (double));
8393 emit_int32 (acfg, MONO_ABI_ALIGNOF (gint64));
8395 emit_int32 (acfg, MONO_TRAMPOLINE_NUM);
8396 emit_int32 (acfg, acfg->tramp_page_size);
8397 for (i = 0; i < MONO_AOT_TRAMP_NUM; ++i)
8398 emit_int32 (acfg, acfg->tramp_page_code_offsets [i]);
8400 if (acfg->aot_opts.static_link) {
8404 * Emit a global symbol which can be passed by an embedding app to
8405 * mono_aot_register_module (). The symbol points to a pointer to the the file info
8408 sprintf (symbol, "%smono_aot_module_%s_info", acfg->user_symbol_prefix, acfg->image->assembly->aname.name);
8410 /* Get rid of characters which cannot occur in symbols */
8412 for (p = symbol; *p; ++p) {
8413 if (!(isalnum (*p) || *p == '_'))
8416 acfg->static_linking_symbol = g_strdup (symbol);
8417 emit_global_inner (acfg, symbol, FALSE);
8418 emit_alignment (acfg, sizeof (gpointer));
8419 emit_label (acfg, symbol);
8420 emit_pointer_2 (acfg, acfg->user_symbol_prefix, "mono_aot_file_info");
8425 emit_blob (MonoAotCompile *acfg)
8429 sprintf (symbol, "blob");
8430 emit_section_change (acfg, RODATA_SECT, 1);
8431 emit_alignment (acfg, 8);
8432 emit_label (acfg, symbol);
8434 emit_bytes (acfg, (guint8*)acfg->blob.data, acfg->blob.index);
8438 emit_objc_selectors (MonoAotCompile *acfg)
8442 if (!acfg->objc_selectors || acfg->objc_selectors->len == 0)
8447 * cat > foo.m << EOF
8450 * return @selector(print:);
8455 img_writer_emit_unset_mode (acfg->w);
8456 g_assert (acfg->fp);
8457 fprintf (acfg->fp, ".section __DATA,__objc_selrefs,literal_pointers,no_dead_strip\n");
8458 fprintf (acfg->fp, ".align 3\n");
8459 for (i = 0; i < acfg->objc_selectors->len; ++i) {
8460 fprintf (acfg->fp, "L_OBJC_SELECTOR_REFERENCES_%d:\n", i);
8461 fprintf (acfg->fp, ".long L_OBJC_METH_VAR_NAME_%d\n", i);
8463 fprintf (acfg->fp, ".section __TEXT,__cstring,cstring_literals\n");
8464 for (i = 0; i < acfg->objc_selectors->len; ++i) {
8465 fprintf (acfg->fp, "L_OBJC_METH_VAR_NAME_%d:\n", i);
8466 fprintf (acfg->fp, ".asciz \"%s\"\n", (char*)g_ptr_array_index (acfg->objc_selectors, i));
8469 fprintf (acfg->fp, ".section __DATA,__objc_imageinfo,regular,no_dead_strip\n");
8470 fprintf (acfg->fp, ".align 3\n");
8471 fprintf (acfg->fp, "L_OBJC_IMAGE_INFO:\n");
8472 fprintf (acfg->fp, ".long 0\n");
8473 fprintf (acfg->fp, ".long 16\n");
8477 emit_dwarf_info (MonoAotCompile *acfg)
8479 #ifdef EMIT_DWARF_INFO
8483 /* DIEs for methods */
8484 for (i = 0; i < acfg->nmethods; ++i) {
8485 MonoCompile *cfg = acfg->cfgs [i];
8490 // FIXME: LLVM doesn't define .Lme_...
8491 if (cfg->compile_llvm)
8494 sprintf (symbol2, "%sme_%x", acfg->temp_prefix, i);
8496 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 ()));
8502 collect_methods (MonoAotCompile *acfg)
8505 MonoImage *image = acfg->image;
8507 /* Collect methods */
8508 for (i = 0; i < image->tables [MONO_TABLE_METHOD].rows; ++i) {
8510 guint32 token = MONO_TOKEN_METHOD_DEF | (i + 1);
8512 method = mono_get_method (acfg->image, token, NULL);
8515 aot_printerrf (acfg, "Failed to load method 0x%x from '%s'.\n", token, image->name);
8516 aot_printerrf (acfg, "Run with MONO_LOG_LEVEL=debug for more information.\n");
8520 /* Load all methods eagerly to skip the slower lazy loading code */
8521 mono_class_setup_methods (method->klass);
8523 if (acfg->aot_opts.full_aot && method->iflags & METHOD_IMPL_ATTRIBUTE_INTERNAL_CALL) {
8524 /* Compile the wrapper instead */
8525 /* We do this here instead of add_wrappers () because it is easy to do it here */
8526 MonoMethod *wrapper = mono_marshal_get_native_wrapper (method, check_for_pending_exc, TRUE);
8530 /* FIXME: Some mscorlib methods don't have debug info */
8532 if (acfg->aot_opts.soft_debug && !method->wrapper_type) {
8533 if (!((method->flags & METHOD_ATTRIBUTE_PINVOKE_IMPL) ||
8534 (method->iflags & METHOD_IMPL_ATTRIBUTE_RUNTIME) ||
8535 (method->flags & METHOD_ATTRIBUTE_ABSTRACT) ||
8536 (method->iflags & METHOD_IMPL_ATTRIBUTE_INTERNAL_CALL))) {
8537 if (!mono_debug_lookup_method (method)) {
8538 fprintf (stderr, "Method %s has no debug info, probably the .mdb file for the assembly is missing.\n", mono_method_full_name (method, TRUE));
8545 /* Since we add the normal methods first, their index will be equal to their zero based token index */
8546 add_method_with_index (acfg, method, i, FALSE);
8547 acfg->method_index ++;
8550 /* gsharedvt methods */
8551 for (mindex = 0; mindex < image->tables [MONO_TABLE_METHOD].rows; ++mindex) {
8553 guint32 token = MONO_TOKEN_METHOD_DEF | (mindex + 1);
8555 if (!(acfg->opts & MONO_OPT_GSHAREDVT))
8558 method = mono_get_method (acfg->image, token, NULL);
8562 if (strcmp (method->name, "gshared2"))
8566 if (!strstr (method->klass->image->name, "mini"))
8569 if (method->is_generic || method->klass->generic_container) {
8570 MonoMethod *gshared;
8572 gshared = mini_get_shared_method_full (method, TRUE, TRUE);
8573 add_extra_method (acfg, gshared);
8577 add_generic_instances (acfg);
8579 if (acfg->aot_opts.full_aot)
8580 add_wrappers (acfg);
8585 compile_methods (MonoAotCompile *acfg)
8589 if (acfg->aot_opts.nthreads > 0) {
8594 gpointer *user_data;
8595 MonoMethod **methods;
8597 methods_len = acfg->methods->len;
8599 len = acfg->methods->len / acfg->aot_opts.nthreads;
8602 * Partition the list of methods into fragments, and hand it to threads to
8605 threads = g_ptr_array_new ();
8606 /* Make a copy since acfg->methods is modified by compile_method () */
8607 methods = g_new0 (MonoMethod*, methods_len);
8608 //memcpy (methods, g_ptr_array_index (acfg->methods, 0), sizeof (MonoMethod*) * methods_len);
8609 for (i = 0; i < methods_len; ++i)
8610 methods [i] = g_ptr_array_index (acfg->methods, i);
8612 while (i < methods_len) {
8613 frag = g_ptr_array_new ();
8614 for (j = 0; j < len; ++j) {
8615 if (i < methods_len) {
8616 g_ptr_array_add (frag, methods [i]);
8621 user_data = g_new0 (gpointer, 3);
8622 user_data [0] = mono_domain_get ();
8623 user_data [1] = acfg;
8624 user_data [2] = frag;
8626 handle = mono_threads_create_thread ((gpointer)compile_thread_main, user_data, 0, 0, NULL);
8627 g_ptr_array_add (threads, handle);
8631 for (i = 0; i < threads->len; ++i) {
8632 WaitForSingleObjectEx (g_ptr_array_index (threads, i), INFINITE, FALSE);
8638 /* Compile methods added by compile_method () or all methods if nthreads == 0 */
8639 for (i = methods_len; i < acfg->methods->len; ++i) {
8640 /* This can new methods to acfg->methods */
8641 compile_method (acfg, g_ptr_array_index (acfg->methods, i));
8646 compile_asm (MonoAotCompile *acfg)
8648 char *command, *objfile;
8649 char *outfile_name, *tmp_outfile_name, *llvm_ofile;
8650 const char *tool_prefix = acfg->aot_opts.tool_prefix ? acfg->aot_opts.tool_prefix : "";
8651 const char *ld_flags = acfg->aot_opts.ld_flags ? acfg->aot_opts.ld_flags : "";;
8653 #if defined(TARGET_AMD64) && !defined(TARGET_MACH)
8654 #define AS_OPTIONS "--64"
8655 #elif defined(TARGET_POWERPC64)
8656 #define AS_OPTIONS "-a64 -mppc64"
8657 #define LD_OPTIONS "-m elf64ppc"
8658 #elif defined(sparc) && SIZEOF_VOID_P == 8
8659 #define AS_OPTIONS "-xarch=v9"
8660 #elif defined(TARGET_X86) && defined(TARGET_MACH) && !defined(__native_client_codegen__)
8661 #define AS_OPTIONS "-arch i386"
8663 #define AS_OPTIONS ""
8666 #ifdef __native_client_codegen__
8667 #if defined(TARGET_AMD64)
8668 #define AS_NAME "nacl64-as"
8670 #define AS_NAME "nacl-as"
8672 #elif defined(TARGET_OSX)
8673 #define AS_NAME "clang -c -x assembler"
8675 #define AS_NAME "as"
8679 #define LD_OPTIONS ""
8683 #define LD_NAME "ld -shared -G"
8684 #elif defined(__ppc__) && defined(TARGET_MACH)
8685 #define LD_NAME "gcc -dynamiclib"
8686 #elif defined(TARGET_AMD64) && defined(TARGET_MACH)
8687 #define LD_NAME "clang --shared"
8688 #elif defined(HOST_WIN32)
8689 #define LD_NAME "gcc -shared --dll"
8690 #elif defined(TARGET_X86) && defined(TARGET_MACH) && !defined(__native_client_codegen__)
8691 #define LD_NAME "clang -m32 -dynamiclib"
8694 if (acfg->aot_opts.asm_only) {
8695 aot_printf (acfg, "Output file: '%s'.\n", acfg->tmpfname);
8696 if (acfg->aot_opts.static_link)
8697 aot_printf (acfg, "Linking symbol: '%s'.\n", acfg->static_linking_symbol);
8698 if (acfg->llvm_separate)
8699 aot_printf (acfg, "LLVM output file: '%s'.\n", acfg->llvm_sfile);
8703 if (acfg->aot_opts.static_link) {
8704 if (acfg->aot_opts.outfile)
8705 objfile = g_strdup_printf ("%s", acfg->aot_opts.outfile);
8707 objfile = g_strdup_printf ("%s.o", acfg->image->name);
8709 objfile = g_strdup_printf ("%s.o", acfg->tmpfname);
8711 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);
8712 aot_printf (acfg, "Executing the native assembler: %s\n", command);
8713 if (system (command) != 0) {
8719 if (acfg->llvm_separate && !acfg->llvm_owriter) {
8720 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);
8721 aot_printf (acfg, "Executing the native assembler: %s\n", command);
8722 if (system (command) != 0) {
8731 if (acfg->aot_opts.static_link) {
8732 aot_printf (acfg, "Output file: '%s'.\n", objfile);
8733 aot_printf (acfg, "Linking symbol: '%s'.\n", acfg->static_linking_symbol);
8738 if (acfg->aot_opts.outfile)
8739 outfile_name = g_strdup_printf ("%s", acfg->aot_opts.outfile);
8741 outfile_name = g_strdup_printf ("%s%s", acfg->image->name, MONO_SOLIB_EXT);
8743 tmp_outfile_name = g_strdup_printf ("%s.tmp", outfile_name);
8745 if (acfg->llvm_separate) {
8746 llvm_ofile = g_strdup (acfg->llvm_ofile);
8748 llvm_ofile = g_strdup ("");
8752 command = g_strdup_printf ("%s -o %s %s %s.o %s", LD_NAME, tmp_outfile_name, llvm_ofile, acfg->tmpfname, ld_flags);
8754 command = g_strdup_printf ("%sld %s -shared -o %s %s %s.o %s", tool_prefix, LD_OPTIONS, tmp_outfile_name, llvm_ofile,
8755 acfg->tmpfname, ld_flags);
8757 aot_printf (acfg, "Executing the native linker: %s\n", command);
8758 if (system (command) != 0) {
8759 g_free (tmp_outfile_name);
8760 g_free (outfile_name);
8768 /*com = g_strdup_printf ("strip --strip-unneeded %s%s", acfg->image->name, MONO_SOLIB_EXT);
8769 printf ("Stripping the binary: %s\n", com);
8773 #if defined(TARGET_ARM) && !defined(TARGET_MACH)
8775 * gas generates 'mapping symbols' each time code and data is mixed, which
8776 * happens a lot in emit_and_reloc_code (), so we need to get rid of them.
8778 command = g_strdup_printf ("%sstrip --strip-symbol=\\$a --strip-symbol=\\$d %s", tool_prefix, tmp_outfile_name);
8779 aot_printf (acfg, "Stripping the binary: %s\n", command);
8780 if (system (command) != 0) {
8781 g_free (tmp_outfile_name);
8782 g_free (outfile_name);
8789 rename (tmp_outfile_name, outfile_name);
8791 #if defined(TARGET_MACH)
8792 command = g_strdup_printf ("dsymutil %s", outfile_name);
8793 aot_printf (acfg, "Executing dsymutil: %s\n", command);
8794 if (system (command) != 0) {
8799 if (!acfg->aot_opts.save_temps)
8802 g_free (tmp_outfile_name);
8803 g_free (outfile_name);
8806 if (acfg->aot_opts.save_temps)
8807 aot_printf (acfg, "Retained input file.\n");
8809 unlink (acfg->tmpfname);
8814 static void init_got_info (GotInfo *info)
8818 info->patch_to_got_offset = g_hash_table_new (mono_patch_info_hash, mono_patch_info_equal);
8819 info->patch_to_got_offset_by_type = g_new0 (GHashTable*, MONO_PATCH_INFO_NUM);
8820 for (i = 0; i < MONO_PATCH_INFO_NUM; ++i)
8821 info->patch_to_got_offset_by_type [i] = g_hash_table_new (mono_patch_info_hash, mono_patch_info_equal);
8822 info->got_patches = g_ptr_array_new ();
8825 static MonoAotCompile*
8826 acfg_create (MonoAssembly *ass, guint32 opts)
8828 MonoImage *image = ass->image;
8829 MonoAotCompile *acfg;
8831 acfg = g_new0 (MonoAotCompile, 1);
8832 acfg->methods = g_ptr_array_new ();
8833 acfg->method_indexes = g_hash_table_new (NULL, NULL);
8834 acfg->method_depth = g_hash_table_new (NULL, NULL);
8835 acfg->plt_offset_to_entry = g_hash_table_new (NULL, NULL);
8836 acfg->patch_to_plt_entry = g_new0 (GHashTable*, MONO_PATCH_INFO_NUM);
8837 acfg->method_to_cfg = g_hash_table_new (NULL, NULL);
8838 acfg->token_info_hash = g_hash_table_new_full (NULL, NULL, NULL, NULL);
8839 acfg->method_to_pinvoke_import = g_hash_table_new_full (NULL, NULL, NULL, g_free);
8840 acfg->image_hash = g_hash_table_new (NULL, NULL);
8841 acfg->image_table = g_ptr_array_new ();
8842 acfg->globals = g_ptr_array_new ();
8843 acfg->image = image;
8845 /* TODO: Write out set of SIMD instructions used, rather than just those available */
8846 acfg->simd_opts = mono_arch_cpu_enumerate_simd_versions ();
8847 acfg->mempool = mono_mempool_new ();
8848 acfg->extra_methods = g_ptr_array_new ();
8849 acfg->unwind_info_offsets = g_hash_table_new (NULL, NULL);
8850 acfg->unwind_ops = g_ptr_array_new ();
8851 acfg->method_label_hash = g_hash_table_new_full (g_str_hash, g_str_equal, g_free, NULL);
8852 acfg->method_order = g_ptr_array_new ();
8853 acfg->export_names = g_hash_table_new (NULL, NULL);
8854 acfg->klass_blob_hash = g_hash_table_new (NULL, NULL);
8855 acfg->method_blob_hash = g_hash_table_new (NULL, NULL);
8856 acfg->plt_entry_debug_sym_cache = g_hash_table_new (g_str_hash, g_str_equal);
8857 mono_mutex_init_recursive (&acfg->mutex);
8859 init_got_info (&acfg->got_info);
8860 init_got_info (&acfg->llvm_got_info);
8866 got_info_free (GotInfo *info)
8870 for (i = 0; i < MONO_PATCH_INFO_NUM; ++i)
8871 g_hash_table_destroy (info->patch_to_got_offset_by_type [i]);
8872 g_free (info->patch_to_got_offset_by_type);
8873 g_hash_table_destroy (info->patch_to_got_offset);
8874 g_ptr_array_free (info->got_patches, TRUE);
8878 acfg_free (MonoAotCompile *acfg)
8882 img_writer_destroy (acfg->w);
8883 for (i = 0; i < acfg->nmethods; ++i)
8885 g_free (acfg->cfgs [i]);
8886 g_free (acfg->cfgs);
8887 g_free (acfg->static_linking_symbol);
8888 g_free (acfg->got_symbol);
8889 g_free (acfg->plt_symbol);
8890 g_ptr_array_free (acfg->methods, TRUE);
8891 g_ptr_array_free (acfg->image_table, TRUE);
8892 g_ptr_array_free (acfg->globals, TRUE);
8893 g_ptr_array_free (acfg->unwind_ops, TRUE);
8894 g_hash_table_destroy (acfg->method_indexes);
8895 g_hash_table_destroy (acfg->method_depth);
8896 g_hash_table_destroy (acfg->plt_offset_to_entry);
8897 for (i = 0; i < MONO_PATCH_INFO_NUM; ++i) {
8898 if (acfg->patch_to_plt_entry [i])
8899 g_hash_table_destroy (acfg->patch_to_plt_entry [i]);
8901 g_free (acfg->patch_to_plt_entry);
8902 g_hash_table_destroy (acfg->method_to_cfg);
8903 g_hash_table_destroy (acfg->token_info_hash);
8904 g_hash_table_destroy (acfg->method_to_pinvoke_import);
8905 g_hash_table_destroy (acfg->image_hash);
8906 g_hash_table_destroy (acfg->unwind_info_offsets);
8907 g_hash_table_destroy (acfg->method_label_hash);
8908 g_hash_table_destroy (acfg->export_names);
8909 g_hash_table_destroy (acfg->plt_entry_debug_sym_cache);
8910 g_hash_table_destroy (acfg->klass_blob_hash);
8911 g_hash_table_destroy (acfg->method_blob_hash);
8912 got_info_free (&acfg->got_info);
8913 got_info_free (&acfg->llvm_got_info);
8914 mono_mempool_destroy (acfg->mempool);
8918 #define WRAPPER(e,n) n,
8919 static const char* const
8920 wrapper_type_names [MONO_WRAPPER_NUM + 1] = {
8921 #include "mono/metadata/wrapper-types.h"
8925 static G_GNUC_UNUSED const char*
8926 get_wrapper_type_name (int type)
8928 return wrapper_type_names [type];
8934 static void aot_dump (MonoAotCompile *acfg)
8940 json_writer_init (&writer);
8942 json_writer_object_begin(&writer);
8945 json_writer_indent (&writer);
8946 json_writer_object_key(&writer, "methods");
8947 json_writer_array_begin (&writer);
8950 for (i = 0; i < acfg->nmethods; ++i) {
8955 cfg = acfg->cfgs [i];
8959 method = cfg->orig_method;
8961 json_writer_indent (&writer);
8962 json_writer_object_begin(&writer);
8964 json_writer_indent (&writer);
8965 json_writer_object_key(&writer, "name");
8966 json_writer_printf (&writer, "\"%s\",\n", method->name);
8968 json_writer_indent (&writer);
8969 json_writer_object_key(&writer, "signature");
8970 json_writer_printf (&writer, "\"%s\",\n", mono_method_full_name (method,
8971 /*signature=*/TRUE));
8973 json_writer_indent (&writer);
8974 json_writer_object_key(&writer, "code_size");
8975 json_writer_printf (&writer, "\"%d\",\n", cfg->code_size);
8977 klass = method->klass;
8979 json_writer_indent (&writer);
8980 json_writer_object_key(&writer, "class");
8981 json_writer_printf (&writer, "\"%s\",\n", klass->name);
8983 json_writer_indent (&writer);
8984 json_writer_object_key(&writer, "namespace");
8985 json_writer_printf (&writer, "\"%s\",\n", klass->name_space);
8987 json_writer_indent (&writer);
8988 json_writer_object_key(&writer, "wrapper_type");
8989 json_writer_printf (&writer, "\"%s\",\n", get_wrapper_type_name(method->wrapper_type));
8991 json_writer_indent_pop (&writer);
8992 json_writer_indent (&writer);
8993 json_writer_object_end (&writer);
8994 json_writer_printf (&writer, ",\n");
8997 json_writer_indent_pop (&writer);
8998 json_writer_indent (&writer);
8999 json_writer_array_end (&writer);
9000 json_writer_printf (&writer, ",\n");
9004 json_writer_indent_push (&writer);
9005 json_writer_indent (&writer);
9006 json_writer_object_key(&writer, "plt");
9007 json_writer_array_begin (&writer);
9009 for (i = 0; i < acfg->plt_offset; ++i) {
9010 MonoPltEntry *plt_entry = NULL;
9015 * The first plt entry is unused.
9019 plt_entry = g_hash_table_lookup (acfg->plt_offset_to_entry, GUINT_TO_POINTER (i));
9022 json_writer_indent (&writer);
9023 json_writer_printf (&writer, "{ ");
9024 json_writer_object_key(&writer, "symbol");
9025 json_writer_printf (&writer, "\"%s\" },\n", plt_entry->symbol);
9028 json_writer_indent_pop (&writer);
9029 json_writer_indent (&writer);
9030 json_writer_array_end (&writer);
9031 json_writer_printf (&writer, ",\n");
9036 json_writer_indent_push (&writer);
9037 json_writer_indent (&writer);
9038 json_writer_object_key(&writer, "got");
9039 json_writer_array_begin (&writer);
9041 json_writer_indent_push (&writer);
9042 for (i = 0; i < acfg->got_info.got_patches->len; ++i) {
9043 MonoJumpInfo *ji = g_ptr_array_index (acfg->got_info.got_patches, i);
9045 json_writer_indent (&writer);
9046 json_writer_printf (&writer, "{ ");
9047 json_writer_object_key(&writer, "patch_name");
9048 json_writer_printf (&writer, "\"%s\" },\n", get_patch_name (ji->type));
9051 json_writer_indent_pop (&writer);
9052 json_writer_indent (&writer);
9053 json_writer_array_end (&writer);
9054 json_writer_printf (&writer, ",\n");
9057 json_writer_indent_pop (&writer);
9058 json_writer_indent (&writer);
9059 json_writer_object_end (&writer);
9061 dumpname = g_strdup_printf ("%s.json", g_path_get_basename (acfg->image->name));
9062 dumpfile = fopen (dumpname, "w+");
9065 fprintf (dumpfile, "%s", writer.text->str);
9068 json_writer_destroy (&writer);
9072 mono_compile_assembly (MonoAssembly *ass, guint32 opts, const char *aot_options)
9074 MonoImage *image = ass->image;
9075 int i, res, all_sizes;
9076 MonoAotCompile *acfg;
9077 char *outfile_name, *tmp_outfile_name, *p;
9078 char llvm_stats_msg [256];
9082 acfg = acfg_create (ass, opts);
9084 memset (&acfg->aot_opts, 0, sizeof (acfg->aot_opts));
9085 acfg->aot_opts.write_symbols = TRUE;
9086 acfg->aot_opts.ntrampolines = 1024;
9087 acfg->aot_opts.nrgctx_trampolines = 1024;
9088 acfg->aot_opts.nimt_trampolines = 128;
9089 acfg->aot_opts.nrgctx_fetch_trampolines = 128;
9090 acfg->aot_opts.ngsharedvt_arg_trampolines = 128;
9091 acfg->aot_opts.llvm_path = g_strdup ("");
9093 acfg->aot_opts.use_trampolines_page = TRUE;
9096 mono_aot_parse_options (aot_options, &acfg->aot_opts);
9098 if (acfg->aot_opts.logfile) {
9099 acfg->logfile = fopen (acfg->aot_opts.logfile, "a+");
9102 if (acfg->aot_opts.static_link)
9103 acfg->aot_opts.autoreg = TRUE;
9105 //acfg->aot_opts.print_skipped_methods = TRUE;
9107 #if !defined(MONO_ARCH_GSHAREDVT_SUPPORTED) || !defined(ENABLE_GSHAREDVT)
9108 if (opts & MONO_OPT_GSHAREDVT) {
9109 aot_printerrf (acfg, "-O=gsharedvt not supported on this platform.\n");
9114 aot_printf (acfg, "Mono Ahead of Time compiler - compiling assembly %s\n", image->name);
9116 #ifndef MONO_ARCH_HAVE_FULL_AOT_TRAMPOLINES
9117 if (acfg->aot_opts.full_aot) {
9118 aot_printerrf (acfg, "--aot=full is not supported on this platform.\n");
9123 if (acfg->aot_opts.direct_pinvoke && !acfg->aot_opts.static_link) {
9124 aot_printerrf (acfg, "The 'direct-pinvoke' AOT option also requires the 'static' AOT option.\n");
9128 if (acfg->aot_opts.static_link)
9129 acfg->aot_opts.asm_writer = TRUE;
9131 if (acfg->aot_opts.soft_debug) {
9132 MonoDebugOptions *opt = mini_get_debug_options ();
9134 opt->mdb_optimizations = TRUE;
9135 opt->gen_seq_points_debug_data = TRUE;
9137 if (!mono_debug_enabled ()) {
9138 aot_printerrf (acfg, "The soft-debug AOT option requires the --debug option.\n");
9141 acfg->flags |= MONO_AOT_FILE_FLAG_DEBUG;
9144 if (mono_use_llvm || acfg->aot_opts.llvm) {
9146 acfg->aot_opts.asm_writer = TRUE;
9147 acfg->flags |= MONO_AOT_FILE_FLAG_WITH_LLVM;
9149 if (acfg->aot_opts.soft_debug) {
9150 aot_printerrf (acfg, "The 'soft-debug' option is not supported when compiling with LLVM.\n");
9156 if (!acfg->aot_opts.asm_only || acfg->aot_opts.llvm_outfile) {
9158 * Emit all LLVM code into a separate assembly/object file and link with it
9161 #if LLVM_API_VERSION >= 3
9162 acfg->llvm_separate = TRUE;
9163 if (!acfg->aot_opts.asm_only)
9164 acfg->llvm_owriter = TRUE;
9167 if (acfg->aot_opts.llvm_outfile && !acfg->llvm_separate) {
9168 aot_printerrf (acfg, "The llvm-outputfile= option is not supported on this platform.\n");
9173 if (acfg->aot_opts.full_aot)
9174 acfg->flags |= MONO_AOT_FILE_FLAG_FULL_AOT;
9176 if (acfg->aot_opts.instances_logfile_path) {
9177 acfg->instances_logfile = fopen (acfg->aot_opts.instances_logfile_path, "w");
9178 if (!acfg->instances_logfile) {
9179 aot_printerrf (acfg, "Unable to create logfile: '%s'.\n", acfg->aot_opts.instances_logfile_path);
9184 load_profile_files (acfg);
9186 acfg->num_trampolines [MONO_AOT_TRAMP_SPECIFIC] = acfg->aot_opts.full_aot ? acfg->aot_opts.ntrampolines : 0;
9187 #ifdef MONO_ARCH_GSHARED_SUPPORTED
9188 acfg->num_trampolines [MONO_AOT_TRAMP_STATIC_RGCTX] = acfg->aot_opts.full_aot ? acfg->aot_opts.nrgctx_trampolines : 0;
9190 acfg->num_trampolines [MONO_AOT_TRAMP_IMT_THUNK] = acfg->aot_opts.full_aot ? acfg->aot_opts.nimt_trampolines : 0;
9191 #ifdef MONO_ARCH_GSHAREDVT_SUPPORTED
9192 if (acfg->opts & MONO_OPT_GSHAREDVT)
9193 acfg->num_trampolines [MONO_AOT_TRAMP_GSHAREDVT_ARG] = acfg->aot_opts.full_aot ? acfg->aot_opts.ngsharedvt_arg_trampolines : 0;
9196 acfg->temp_prefix = img_writer_get_temp_label_prefix (NULL);
9200 acfg->assembly_name_sym = g_strdup (acfg->image->assembly->aname.name);
9201 /* Get rid of characters which cannot occur in symbols */
9202 for (p = acfg->assembly_name_sym; *p; ++p) {
9203 if (!(isalnum (*p) || *p == '_'))
9207 acfg->got_symbol_base = g_strdup_printf ("mono_aot_%s_got", acfg->assembly_name_sym);
9208 acfg->llvm_got_symbol_base = g_strdup_printf ("mono_aot_%s_llvm_got", acfg->assembly_name_sym);
9209 acfg->plt_symbol = g_strdup_printf ("%smono_aot_%s_plt", acfg->llvm_label_prefix, acfg->assembly_name_sym);
9211 acfg->got_symbol = g_strdup_printf ("%s%s", acfg->llvm_label_prefix, acfg->got_symbol_base);
9213 acfg->llvm_got_symbol = g_strdup_printf ("%s%s", acfg->llvm_label_prefix, acfg->llvm_got_symbol_base);
9214 if (acfg->llvm_separate)
9215 acfg->llvm_eh_frame_symbol = g_strdup_printf ("mono_aot_%s_eh_frame", acfg->assembly_name_sym);
9217 acfg->llvm_eh_frame_symbol = g_strdup ("mono_eh_frame");
9220 acfg->method_index = 1;
9224 if (acfg->aot_opts.full_aot)
9225 mono_set_partial_sharing_supported (TRUE);
9228 res = collect_methods (acfg);
9232 acfg->cfgs_size = acfg->methods->len + 32;
9233 acfg->cfgs = g_new0 (MonoCompile*, acfg->cfgs_size);
9235 /* PLT offset 0 is reserved for the PLT trampoline */
9236 acfg->plt_offset = 1;
9241 mono_llvm_create_aot_module (acfg->llvm_got_symbol_base, acfg->llvm_separate, acfg->llvm_separate);
9245 /* GOT offset 0 is reserved for the address of the current assembly */
9249 ji = mono_mempool_alloc0 (acfg->mempool, sizeof (MonoAotCompile));
9250 ji->type = MONO_PATCH_INFO_IMAGE;
9251 ji->data.image = acfg->image;
9253 get_got_offset (acfg, FALSE, ji);
9254 get_got_offset (acfg, TRUE, ji);
9256 /* Slot 1 is reserved for the mscorlib got addr */
9257 ji = mono_mempool_alloc0 (acfg->mempool, sizeof (MonoAotCompile));
9258 ji->type = MONO_PATCH_INFO_MSCORLIB_GOT_ADDR;
9259 get_got_offset (acfg, FALSE, ji);
9260 get_got_offset (acfg, TRUE, ji);
9262 /* This is very common */
9263 ji = mono_mempool_alloc0 (acfg->mempool, sizeof (MonoAotCompile));
9264 ji->type = MONO_PATCH_INFO_GC_CARD_TABLE_ADDR;
9265 get_got_offset (acfg, FALSE, ji);
9266 get_got_offset (acfg, TRUE, ji);
9268 ji = mono_mempool_alloc0 (acfg->mempool, sizeof (MonoAotCompile));
9269 ji->type = MONO_PATCH_INFO_JIT_TLS_ID;
9270 get_got_offset (acfg, FALSE, ji);
9271 get_got_offset (acfg, TRUE, ji);
9276 compile_methods (acfg);
9280 acfg->stats.jit_time = TV_ELAPSED (atv, btv);
9288 if (acfg->aot_opts.asm_only) {
9289 if (acfg->aot_opts.outfile) {
9290 acfg->tmpfname = g_strdup_printf ("%s", acfg->aot_opts.outfile);
9291 acfg->tmpbasename = g_strdup (acfg->tmpfname);
9293 acfg->tmpbasename = g_strdup_printf ("%s", acfg->image->name);
9294 acfg->tmpfname = g_strdup_printf ("%s.s", acfg->tmpbasename);
9296 if (acfg->llvm_separate) {
9297 g_assert (acfg->aot_opts.llvm_outfile);
9298 acfg->llvm_sfile = g_strdup (acfg->aot_opts.llvm_outfile);
9301 acfg->tmpbasename = g_strdup_printf ("%s", "temp");
9302 acfg->tmpfname = g_strdup_printf ("%s.s", acfg->tmpbasename);
9303 acfg->llvm_sfile = g_strdup ("temp-llvm.s");
9304 acfg->llvm_ofile = g_strdup ("temp-llvm.o");
9307 res = emit_llvm_file (acfg);
9313 if (!acfg->aot_opts.asm_only && !acfg->aot_opts.asm_writer && bin_writer_supported ()) {
9314 if (acfg->aot_opts.outfile)
9315 outfile_name = g_strdup_printf ("%s", acfg->aot_opts.outfile);
9317 outfile_name = g_strdup_printf ("%s%s", acfg->image->name, MONO_SOLIB_EXT);
9320 * Can't use g_file_open_tmp () as it will be deleted at exit, and
9321 * it might be in another file system so the rename () won't work.
9323 tmp_outfile_name = g_strdup_printf ("%s.tmp", outfile_name);
9325 acfg->fp = fopen (tmp_outfile_name, "w");
9327 aot_printf (acfg, "Unable to create temporary file '%s': %s\n", tmp_outfile_name, strerror (errno));
9331 acfg->w = img_writer_create (acfg->fp, TRUE);
9332 acfg->use_bin_writer = TRUE;
9334 if (acfg->llvm && !acfg->llvm_separate) {
9335 /* Append to the .s file created by llvm */
9336 /* FIXME: Use multiple files instead */
9337 acfg->fp = fopen (acfg->tmpfname, "a+");
9339 if (acfg->aot_opts.asm_only) {
9340 if (acfg->aot_opts.outfile)
9341 acfg->tmpfname = g_strdup_printf ("%s", acfg->aot_opts.outfile);
9343 acfg->tmpfname = g_strdup_printf ("%s.s", acfg->image->name);
9344 acfg->fp = fopen (acfg->tmpfname, "w+");
9346 int i = g_file_open_tmp ("mono_aot_XXXXXX", &acfg->tmpfname, NULL);
9347 acfg->fp = fdopen (i, "w+");
9350 if (acfg->fp == 0) {
9351 aot_printerrf (acfg, "Unable to open file '%s': %s\n", acfg->tmpfname, strerror (errno));
9354 acfg->w = img_writer_create (acfg->fp, FALSE);
9356 tmp_outfile_name = NULL;
9357 outfile_name = NULL;
9360 /* Compute symbols for methods */
9361 for (i = 0; i < acfg->nmethods; ++i) {
9362 if (acfg->cfgs [i]) {
9363 MonoCompile *cfg = acfg->cfgs [i];
9364 int method_index = get_method_index (acfg, cfg->orig_method);
9366 if (COMPILE_LLVM (cfg))
9367 cfg->asm_symbol = g_strdup_printf ("%s%s", acfg->llvm_label_prefix, cfg->llvm_method_name);
9368 else if (acfg->global_symbols || acfg->llvm_separate)
9369 cfg->asm_symbol = get_debug_sym (cfg->orig_method, "", acfg->method_label_hash);
9371 cfg->asm_symbol = g_strdup_printf ("%s%sm_%x", acfg->temp_prefix, acfg->llvm_label_prefix, method_index);
9372 cfg->asm_debug_symbol = cfg->asm_symbol;
9376 if (acfg->aot_opts.dwarf_debug && acfg->aot_opts.asm_only && acfg->aot_opts.gnu_asm) {
9378 * CLANG supports GAS .file/.loc directives, so emit line number information this way
9379 * FIXME: CLANG only emits line number info for .loc directives followed by assembly, not
9382 //acfg->gas_line_numbers = TRUE;
9385 if (!acfg->aot_opts.nodebug || acfg->aot_opts.dwarf_debug) {
9386 if (acfg->aot_opts.dwarf_debug && !mono_debug_enabled ()) {
9387 aot_printerrf (acfg, "The dwarf AOT option requires the --debug option.\n");
9390 acfg->dwarf = mono_dwarf_writer_create (acfg->w, NULL, 0, FALSE, !acfg->gas_line_numbers);
9393 img_writer_emit_start (acfg->w);
9396 mono_dwarf_writer_emit_base_info (acfg->dwarf, g_path_get_basename (acfg->image->name), mono_unwind_get_cie_program ());
9398 if (acfg->thumb_mixed) {
9401 * This global symbol marks the end of THUMB code, and the beginning of ARM
9402 * code generated by our JIT.
9404 sprintf (symbol, "thumb_end");
9405 emit_section_change (acfg, ".text", 0);
9406 emit_alignment_code (acfg, 8);
9407 emit_label (acfg, symbol);
9408 emit_zero_bytes (acfg, 16);
9410 fprintf (acfg->fp, ".arm\n");
9417 emit_extra_methods (acfg);
9419 emit_trampolines (acfg);
9421 emit_class_name_table (acfg);
9423 emit_got_info (acfg, FALSE);
9425 emit_got_info (acfg, TRUE);
9427 emit_exception_info (acfg);
9429 emit_unwind_info (acfg);
9431 emit_class_info (acfg);
9435 emit_image_table (acfg);
9439 emit_file_info (acfg);
9443 emit_objc_selectors (acfg);
9445 emit_globals (acfg);
9447 emit_autoreg (acfg);
9450 emit_dwarf_info (acfg);
9451 mono_dwarf_writer_close (acfg->dwarf);
9454 emit_mem_end (acfg);
9456 if (acfg->need_pt_gnu_stack) {
9457 /* This is required so the .so doesn't have an executable stack */
9458 /* The bin writer already emits this */
9459 if (!acfg->use_bin_writer)
9460 fprintf (acfg->fp, "\n.section .note.GNU-stack,\"\",@progbits\n");
9465 acfg->stats.gen_time = TV_ELAPSED (atv, btv);
9468 sprintf (llvm_stats_msg, ", LLVM: %d (%d%%)", acfg->stats.llvm_count, acfg->stats.mcount ? (acfg->stats.llvm_count * 100) / acfg->stats.mcount : 100);
9470 strcpy (llvm_stats_msg, "");
9472 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;
9474 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",
9475 acfg->stats.code_size, acfg->stats.code_size * 100 / all_sizes,
9476 acfg->stats.info_size, acfg->stats.info_size * 100 / all_sizes,
9477 acfg->stats.ex_info_size, acfg->stats.ex_info_size * 100 / all_sizes,
9478 acfg->stats.unwind_info_size, acfg->stats.unwind_info_size * 100 / all_sizes,
9479 acfg->stats.class_info_size, acfg->stats.class_info_size * 100 / all_sizes,
9480 acfg->stats.plt_size ? acfg->stats.plt_size : acfg->plt_offset, acfg->stats.plt_size ? acfg->stats.plt_size * 100 / all_sizes : 0,
9481 acfg->stats.got_info_size, acfg->stats.got_info_size * 100 / all_sizes,
9482 acfg->stats.offsets_size, acfg->stats.offsets_size * 100 / all_sizes,
9483 (int)(acfg->got_offset * sizeof (gpointer)));
9484 aot_printf (acfg, "Compiled: %d/%d (%d%%)%s, No GOT slots: %d (%d%%), Direct calls: %d (%d%%)\n",
9485 acfg->stats.ccount, acfg->stats.mcount, acfg->stats.mcount ? (acfg->stats.ccount * 100) / acfg->stats.mcount : 100,
9487 acfg->stats.methods_without_got_slots, acfg->stats.mcount ? (acfg->stats.methods_without_got_slots * 100) / acfg->stats.mcount : 100,
9488 acfg->stats.direct_calls, acfg->stats.all_calls ? (acfg->stats.direct_calls * 100) / acfg->stats.all_calls : 100);
9489 if (acfg->stats.genericcount)
9490 aot_printf (acfg, "%d methods are generic (%d%%)\n", acfg->stats.genericcount, acfg->stats.mcount ? (acfg->stats.genericcount * 100) / acfg->stats.mcount : 100);
9491 if (acfg->stats.abscount)
9492 aot_printf (acfg, "%d methods contain absolute addresses (%d%%)\n", acfg->stats.abscount, acfg->stats.mcount ? (acfg->stats.abscount * 100) / acfg->stats.mcount : 100);
9493 if (acfg->stats.lmfcount)
9494 aot_printf (acfg, "%d methods contain lmf pointers (%d%%)\n", acfg->stats.lmfcount, acfg->stats.mcount ? (acfg->stats.lmfcount * 100) / acfg->stats.mcount : 100);
9495 if (acfg->stats.ocount)
9496 aot_printf (acfg, "%d methods have other problems (%d%%)\n", acfg->stats.ocount, acfg->stats.mcount ? (acfg->stats.ocount * 100) / acfg->stats.mcount : 100);
9499 res = img_writer_emit_writeout (acfg->w);
9504 if (acfg->use_bin_writer) {
9505 int err = rename (tmp_outfile_name, outfile_name);
9508 aot_printf (acfg, "Unable to rename '%s' to '%s': %s\n", tmp_outfile_name, outfile_name, strerror (errno));
9512 res = compile_asm (acfg);
9519 acfg->stats.link_time = TV_ELAPSED (atv, btv);
9521 if (acfg->aot_opts.stats) {
9524 aot_printf (acfg, "GOT slot distribution:\n");
9525 for (i = 0; i < MONO_PATCH_INFO_NONE; ++i)
9526 if (acfg->stats.got_slot_types [i])
9527 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]);
9530 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);
9532 if (acfg->aot_opts.dump_json)
9545 mono_aot_readonly_field_override (MonoClassField *field)
9551 mono_compile_assembly (MonoAssembly *ass, guint32 opts, const char *aot_options)