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>
55 #include "seq-points.h"
56 #include "image-writer.h"
57 #include "dwarfwriter.h"
60 #if !defined(DISABLE_AOT) && !defined(DISABLE_JIT)
62 #if defined(__linux__) || defined(__native_client_codegen__)
63 #define RODATA_SECT ".rodata"
64 #elif defined(TARGET_MACH)
65 #define RODATA_SECT ".section __TEXT, __const"
67 #define RODATA_SECT ".text"
70 #define TV_DECLARE(name) gint64 name
71 #define TV_GETTIME(tv) tv = mono_100ns_ticks ()
72 #define TV_ELAPSED(start,end) (((end) - (start)) / 10)
74 #define ALIGN_TO(val,align) ((((guint64)val) + ((align) - 1)) & ~((align) - 1))
75 #define ALIGN_PTR_TO(ptr,align) (gpointer)((((gssize)(ptr)) + (align - 1)) & (~(align - 1)))
76 #define ROUND_DOWN(VALUE,SIZE) ((VALUE) & ~((SIZE) - 1))
78 /* predefined values for static readonly fields without needed to run the .cctor */
79 typedef struct _ReadOnlyValue ReadOnlyValue;
80 struct _ReadOnlyValue {
83 int type; /* to be used later for typechecking to prevent user errors */
92 static ReadOnlyValue *readonly_values;
94 typedef struct MonoAotOptions {
97 gboolean write_symbols;
98 gboolean metadata_only;
99 gboolean bind_to_runtime_version;
102 gboolean static_link;
106 gboolean dwarf_debug;
108 gboolean log_generics;
109 gboolean log_instances;
110 gboolean direct_pinvoke;
111 gboolean direct_icalls;
112 gboolean no_direct_calls;
113 gboolean use_trampolines_page;
114 gboolean no_instances;
119 int nrgctx_trampolines;
120 int nimt_trampolines;
121 int ngsharedvt_arg_trampolines;
122 int nrgctx_fetch_trampolines;
123 gboolean print_skipped_methods;
129 char *instances_logfile_path;
133 typedef struct MonoAotStats {
134 int ccount, mcount, lmfcount, abscount, gcount, ocount, genericcount;
135 int code_size, info_size, ex_info_size, unwind_info_size, got_size, class_info_size, got_info_size, plt_size;
136 int methods_without_got_slots, direct_calls, all_calls, llvm_count;
137 int got_slots, offsets_size;
138 int got_slot_types [MONO_PATCH_INFO_NONE];
139 int got_slot_info_sizes [MONO_PATCH_INFO_NONE];
140 int jit_time, gen_time, link_time;
143 typedef struct MonoAotCompile {
146 GHashTable *method_indexes;
147 GHashTable *method_depth;
150 GHashTable **patch_to_plt_entry;
151 GHashTable *plt_offset_to_entry;
152 GHashTable *patch_to_got_offset;
153 GHashTable **patch_to_got_offset_by_type;
154 GPtrArray *got_patches;
155 GHashTable *image_hash;
156 GHashTable *method_to_cfg;
157 GHashTable *token_info_hash;
158 GHashTable *method_to_pinvoke_import;
159 GPtrArray *extra_methods;
160 GPtrArray *image_table;
162 GPtrArray *method_order;
163 GHashTable *export_names;
164 /* Maps MonoClass* -> blob offset */
165 GHashTable *klass_blob_hash;
166 /* Maps MonoMethod* -> blob offset */
167 GHashTable *method_blob_hash;
168 guint32 *plt_got_info_offsets;
169 guint32 got_offset, plt_offset, plt_got_offset_base;
170 guint32 final_got_size;
171 /* Number of GOT entries reserved for trampolines */
172 guint32 num_trampoline_got_entries;
173 guint32 tramp_page_size;
175 guint32 num_trampolines [MONO_AOT_TRAMP_NUM];
176 guint32 trampoline_got_offset_base [MONO_AOT_TRAMP_NUM];
177 guint32 trampoline_size [MONO_AOT_TRAMP_NUM];
178 guint32 tramp_page_code_offsets [MONO_AOT_TRAMP_NUM];
180 MonoAotOptions aot_opts;
184 MonoMemPool *mempool;
187 char *static_linking_symbol;
189 gboolean use_bin_writer;
190 gboolean gas_line_numbers;
192 MonoDwarfWriter *dwarf;
197 GHashTable *unwind_info_offsets;
198 GPtrArray *unwind_ops;
199 guint32 unwind_info_offset;
200 char *got_symbol_base;
203 char *methods_symbol;
204 GHashTable *method_label_hash;
205 const char *temp_prefix;
206 const char *user_symbol_prefix;
207 const char *llvm_label_prefix;
208 const char *inst_directive;
209 guint32 label_generator;
211 MonoAotFileFlags flags;
212 MonoDynamicStream blob;
213 MonoClass **typespec_classes;
216 char *assembly_name_sym;
217 GHashTable *plt_entry_debug_sym_cache;
218 gboolean thumb_mixed, need_no_dead_strip, need_pt_gnu_stack;
219 GHashTable *ginst_hash;
220 GHashTable *dwarf_ln_filenames;
221 gboolean global_symbols;
222 gboolean direct_method_addresses;
223 int objc_selector_index, objc_selector_index_2;
224 GPtrArray *objc_selectors;
225 GHashTable *objc_selector_to_index;
227 FILE *instances_logfile;
232 char *symbol, *llvm_symbol, *debug_sym;
234 gboolean jit_used, llvm_used;
237 #define mono_acfg_lock(acfg) mono_mutex_lock (&((acfg)->mutex))
238 #define mono_acfg_unlock(acfg) mono_mutex_unlock (&((acfg)->mutex))
240 /* This points to the current acfg in LLVM mode */
241 static MonoAotCompile *llvm_acfg;
243 #ifdef HAVE_ARRAY_ELEM_INIT
244 #define MSGSTRFIELD(line) MSGSTRFIELD1(line)
245 #define MSGSTRFIELD1(line) str##line
246 static const struct msgstr_t {
247 #define PATCH_INFO(a,b) char MSGSTRFIELD(__LINE__) [sizeof (b)];
248 #include "patch-info.h"
251 #define PATCH_INFO(a,b) b,
252 #include "patch-info.h"
255 static const gint16 opidx [] = {
256 #define PATCH_INFO(a,b) [MONO_PATCH_INFO_ ## a] = offsetof (struct msgstr_t, MSGSTRFIELD(__LINE__)),
257 #include "patch-info.h"
261 static G_GNUC_UNUSED const char*
262 get_patch_name (int info)
264 return (const char*)&opstr + opidx [info];
268 #define PATCH_INFO(a,b) b,
269 static const char* const
270 patch_types [MONO_PATCH_INFO_NUM + 1] = {
271 #include "patch-info.h"
275 static G_GNUC_UNUSED const char*
276 get_patch_name (int info)
278 return patch_types [info];
284 get_plt_entry_debug_sym (MonoAotCompile *acfg, MonoJumpInfo *ji, GHashTable *cache);
287 aot_printf (MonoAotCompile *acfg, const gchar *format, ...)
293 output = acfg->logfile;
297 va_start (args, format);
298 vfprintf (output, format, args);
303 aot_printerrf (MonoAotCompile *acfg, const gchar *format, ...)
309 output = acfg->logfile;
313 va_start (args, format);
314 vfprintf (output, format, args);
318 /* Wrappers around the image writer functions */
321 emit_section_change (MonoAotCompile *acfg, const char *section_name, int subsection_index)
323 img_writer_emit_section_change (acfg->w, section_name, subsection_index);
327 emit_push_section (MonoAotCompile *acfg, const char *section_name, int subsection)
329 img_writer_emit_push_section (acfg->w, section_name, subsection);
333 emit_pop_section (MonoAotCompile *acfg)
335 img_writer_emit_pop_section (acfg->w);
339 emit_local_symbol (MonoAotCompile *acfg, const char *name, const char *end_label, gboolean func)
341 img_writer_emit_local_symbol (acfg->w, name, end_label, func);
345 emit_label (MonoAotCompile *acfg, const char *name)
347 img_writer_emit_label (acfg->w, name);
351 emit_bytes (MonoAotCompile *acfg, const guint8* buf, int size)
353 img_writer_emit_bytes (acfg->w, buf, size);
357 emit_string (MonoAotCompile *acfg, const char *value)
359 img_writer_emit_string (acfg->w, value);
363 emit_line (MonoAotCompile *acfg)
365 img_writer_emit_line (acfg->w);
369 emit_alignment (MonoAotCompile *acfg, int size)
371 img_writer_emit_alignment (acfg->w, size);
375 emit_pointer_unaligned (MonoAotCompile *acfg, const char *target)
377 img_writer_emit_pointer_unaligned (acfg->w, target);
381 emit_pointer (MonoAotCompile *acfg, const char *target)
383 img_writer_emit_pointer (acfg->w, target);
387 emit_pointer_2 (MonoAotCompile *acfg, const char *prefix, const char *target)
389 if (prefix [0] != '\0') {
390 char *s = g_strdup_printf ("%s%s", prefix, target);
391 img_writer_emit_pointer (acfg->w, s);
394 img_writer_emit_pointer (acfg->w, target);
399 emit_int16 (MonoAotCompile *acfg, int value)
401 img_writer_emit_int16 (acfg->w, value);
405 emit_int32 (MonoAotCompile *acfg, int value)
407 img_writer_emit_int32 (acfg->w, value);
411 emit_symbol_diff (MonoAotCompile *acfg, const char *end, const char* start, int offset)
413 img_writer_emit_symbol_diff (acfg->w, end, start, offset);
417 emit_zero_bytes (MonoAotCompile *acfg, int num)
419 img_writer_emit_zero_bytes (acfg->w, num);
423 emit_byte (MonoAotCompile *acfg, guint8 val)
425 img_writer_emit_byte (acfg->w, val);
428 #ifdef __native_client_codegen__
430 emit_nacl_call_alignment (MonoAotCompile *acfg)
432 img_writer_emit_nacl_call_alignment (acfg->w);
436 static G_GNUC_UNUSED void
437 emit_global_inner (MonoAotCompile *acfg, const char *name, gboolean func)
439 img_writer_emit_global (acfg->w, name, func);
443 emit_global (MonoAotCompile *acfg, const char *name, gboolean func)
445 if (acfg->aot_opts.no_dlsym) {
446 g_ptr_array_add (acfg->globals, g_strdup (name));
447 img_writer_emit_local_symbol (acfg->w, name, NULL, func);
449 img_writer_emit_global (acfg->w, name, func);
454 emit_symbol_size (MonoAotCompile *acfg, const char *name, const char *end_label)
456 img_writer_emit_symbol_size (acfg->w, name, end_label);
460 emit_string_symbol (MonoAotCompile *acfg, const char *name, const char *value)
462 img_writer_emit_section_change (acfg->w, RODATA_SECT, 1);
464 /* On apple, all symbols need to be aligned to avoid warnings from ld */
465 emit_alignment (acfg, 4);
467 img_writer_emit_label (acfg->w, name);
468 img_writer_emit_string (acfg->w, value);
471 static G_GNUC_UNUSED void
472 emit_uleb128 (MonoAotCompile *acfg, guint32 value)
475 guint8 b = value & 0x7f;
477 if (value != 0) /* more bytes to come */
483 static G_GNUC_UNUSED void
484 emit_sleb128 (MonoAotCompile *acfg, gint64 value)
487 gboolean negative = (value < 0);
494 /* the following is unnecessary if the
495 * implementation of >>= uses an arithmetic rather
496 * than logical shift for a signed left operand
500 value |= - ((gint64)1 <<(size - 7));
501 /* sign bit of byte is second high order bit (0x40) */
502 if ((value == 0 && !(byte & 0x40)) ||
503 (value == -1 && (byte & 0x40)))
507 emit_byte (acfg, byte);
511 static G_GNUC_UNUSED void
512 encode_uleb128 (guint32 value, guint8 *buf, guint8 **endbuf)
517 guint8 b = value & 0x7f;
519 if (value != 0) /* more bytes to come */
527 static G_GNUC_UNUSED void
528 encode_sleb128 (gint32 value, guint8 *buf, guint8 **endbuf)
531 gboolean negative = (value < 0);
539 /* the following is unnecessary if the
540 * implementation of >>= uses an arithmetic rather
541 * than logical shift for a signed left operand
545 value |= - (1 <<(size - 7));
546 /* sign bit of byte is second high order bit (0x40) */
547 if ((value == 0 && !(byte & 0x40)) ||
548 (value == -1 && (byte & 0x40)))
559 emit_unset_mode (MonoAotCompile *acfg)
561 img_writer_emit_unset_mode (acfg->w);
564 static G_GNUC_UNUSED void
565 emit_set_thumb_mode (MonoAotCompile *acfg)
567 emit_unset_mode (acfg);
568 fprintf (acfg->fp, ".code 16\n");
571 static G_GNUC_UNUSED void
572 emit_set_arm_mode (MonoAotCompile *acfg)
574 emit_unset_mode (acfg);
575 fprintf (acfg->fp, ".code 32\n");
579 emit_code_bytes (MonoAotCompile *acfg, const guint8* buf, int size)
584 g_assert (size % 4 == 0);
585 emit_unset_mode (acfg);
586 for (i = 0; i < size; i += 4)
587 fprintf (acfg->fp, "%s 0x%x\n", acfg->inst_directive, *(guint32*)(buf + i));
589 emit_bytes (acfg, buf, size);
593 /* ARCHITECTURE SPECIFIC CODE */
595 #if defined(TARGET_X86) || defined(TARGET_AMD64) || defined(TARGET_ARM) || defined(TARGET_POWERPC)
596 #define EMIT_DWARF_INFO 1
599 #if defined(TARGET_ARM)
600 #define AOT_FUNC_ALIGNMENT 4
602 #define AOT_FUNC_ALIGNMENT 16
604 #if (defined(TARGET_X86) || defined(TARGET_AMD64)) && defined(__native_client_codegen__)
605 #undef AOT_FUNC_ALIGNMENT
606 #define AOT_FUNC_ALIGNMENT 32
609 #if defined(TARGET_POWERPC64) && !defined(__mono_ilp32__)
610 #define PPC_LD_OP "ld"
611 #define PPC_LDX_OP "ldx"
613 #define PPC_LD_OP "lwz"
614 #define PPC_LDX_OP "lwzx"
618 #define AOT_TARGET_STR "AMD64"
623 #define AOT_TARGET_STR "ARM (MACH)"
625 #define AOT_TARGET_STR "ARM (!MACH)"
631 #define AOT_TARGET_STR "ARM64 (MACH)"
633 #define AOT_TARGET_STR "ARM64 (!MACH)"
637 #ifdef TARGET_POWERPC64
638 #ifdef __mono_ilp32__
639 #define AOT_TARGET_STR "POWERPC64 (mono ilp32)"
641 #define AOT_TARGET_STR "POWERPC64 (!mono ilp32)"
644 #ifdef TARGET_POWERPC
645 #ifdef __mono_ilp32__
646 #define AOT_TARGET_STR "POWERPC (mono ilp32)"
648 #define AOT_TARGET_STR "POWERPC (!mono ilp32)"
655 #define AOT_TARGET_STR "X86 (WIN32)"
656 #elif defined(__native_client_codegen__)
657 #define AOT_TARGET_STR "X86 (native client codegen)"
659 #define AOT_TARGET_STR "X86 (!native client codegen)"
663 #ifndef AOT_TARGET_STR
664 #define AOT_TARGET_STR ""
668 arch_init (MonoAotCompile *acfg)
670 acfg->llc_args = g_string_new ("");
671 acfg->as_args = g_string_new ("");
674 * The prefix LLVM likes to put in front of symbol names on darwin.
675 * The mach-os specs require this for globals, but LLVM puts them in front of all
676 * symbols. We need to handle this, since we need to refer to LLVM generated
679 acfg->llvm_label_prefix = "";
680 acfg->user_symbol_prefix = "";
682 #if defined(TARGET_X86)
683 g_string_append (acfg->llc_args, " -march=x86 -mattr=sse4.1");
686 #if defined(TARGET_AMD64)
687 g_string_append (acfg->llc_args, " -march=x86-64 -mattr=sse4.1");
691 if (acfg->aot_opts.mtriple && strstr (acfg->aot_opts.mtriple, "darwin")) {
692 g_string_append (acfg->llc_args, "-mattr=+v6");
695 g_string_append (acfg->llc_args, " -mattr=+vfp2,-neon,+d16");
696 g_string_append (acfg->as_args, " -mfpu=vfp3");
698 g_string_append (acfg->llc_args, " -soft-float");
701 if (acfg->aot_opts.mtriple && strstr (acfg->aot_opts.mtriple, "thumb"))
702 acfg->thumb_mixed = TRUE;
704 if (acfg->aot_opts.mtriple)
705 mono_arch_set_target (acfg->aot_opts.mtriple);
709 acfg->inst_directive = ".inst";
710 if (acfg->aot_opts.mtriple)
711 mono_arch_set_target (acfg->aot_opts.mtriple);
715 acfg->user_symbol_prefix = "_";
716 acfg->llvm_label_prefix = "_";
717 acfg->inst_directive = ".word";
718 acfg->need_no_dead_strip = TRUE;
719 acfg->aot_opts.gnu_asm = TRUE;
722 #if defined(__linux__) && !defined(TARGET_ARM)
723 acfg->need_pt_gnu_stack = TRUE;
727 acfg->direct_method_addresses = TRUE;
728 acfg->global_symbols = TRUE;
734 #include "../../../mono-extensions/mono/mini/aot-compiler-arm64.c"
738 #ifdef MONO_ARCH_AOT_SUPPORTED
740 * arch_emit_direct_call:
742 * Emit a direct call to the symbol TARGET. CALL_SIZE is set to the size of the
746 arch_emit_direct_call (MonoAotCompile *acfg, const char *target, gboolean external, gboolean thumb, MonoJumpInfo *ji, int *call_size)
748 #if defined(TARGET_X86) || defined(TARGET_AMD64)
749 /* Need to make sure this is exactly 5 bytes long */
750 if (external && !acfg->use_bin_writer) {
751 emit_unset_mode (acfg);
752 fprintf (acfg->fp, "call %s\n", target);
754 emit_byte (acfg, '\xe8');
755 emit_symbol_diff (acfg, target, ".", -4);
758 #elif defined(TARGET_ARM)
759 if (acfg->use_bin_writer) {
766 img_writer_emit_reloc (acfg->w, R_ARM_CALL, target, -8);
767 emit_bytes (acfg, buf, 4);
769 emit_unset_mode (acfg);
771 fprintf (acfg->fp, "blx %s\n", target);
773 fprintf (acfg->fp, "bl %s\n", target);
776 #elif defined(TARGET_ARM64)
777 arm64_emit_direct_call (acfg, target, external, thumb, ji, call_size);
778 #elif defined(TARGET_POWERPC)
779 if (acfg->use_bin_writer) {
780 g_assert_not_reached ();
782 emit_unset_mode (acfg);
783 fprintf (acfg->fp, "bl %s\n", target);
787 g_assert_not_reached ();
794 * - we use an approach similar to the x86 abi: reserve a register (r30) to hold
796 * - The full-aot trampolines need access to the GOT of mscorlib, so we store
797 * in in the 2. slot of every GOT, and require every method to place the GOT
798 * address in r30, even when it doesn't access the GOT otherwise. This way,
799 * the trampolines can compute the mscorlib GOT address by loading 4(r30).
804 * PPC64 uses function descriptors which greatly complicate all code, since
805 * these are used very inconsistently in the runtime. Some functions like
806 * mono_compile_method () return ftn descriptors, while others like the
807 * trampoline creation functions do not.
808 * We assume that all GOT slots contain function descriptors, and create
809 * descriptors in aot-runtime.c when needed.
810 * The ppc64 abi uses r2 to hold the address of the TOC/GOT, which is loaded
811 * from function descriptors, we could do the same, but it would require
812 * rewriting all the ppc/aot code to handle function descriptors properly.
813 * So instead, we use the same approach as on PPC32.
814 * This is a horrible mess, but fixing it would probably lead to an even bigger
820 * - similar to the PPC32 design, we reserve EBX to hold the GOT pointer.
823 #ifdef MONO_ARCH_AOT_SUPPORTED
825 * arch_emit_got_offset:
827 * The memory pointed to by CODE should hold native code for computing the GOT
828 * address. Emit this code while patching it with the offset between code and
829 * the GOT. CODE_SIZE is set to the number of bytes emitted.
832 arch_emit_got_offset (MonoAotCompile *acfg, guint8 *code, int *code_size)
834 #if defined(TARGET_POWERPC64)
835 g_assert (!acfg->use_bin_writer);
836 emit_unset_mode (acfg);
838 * The ppc32 code doesn't seem to work on ppc64, the assembler complains about
839 * unsupported relocations. So we store the got address into the .Lgot_addr
840 * symbol which is in the text segment, compute its address, and load it.
842 fprintf (acfg->fp, ".L%d:\n", acfg->label_generator);
843 fprintf (acfg->fp, "lis 0, (.Lgot_addr + 4 - .L%d)@h\n", acfg->label_generator);
844 fprintf (acfg->fp, "ori 0, 0, (.Lgot_addr + 4 - .L%d)@l\n", acfg->label_generator);
845 fprintf (acfg->fp, "add 30, 30, 0\n");
846 fprintf (acfg->fp, "%s 30, 0(30)\n", PPC_LD_OP);
847 acfg->label_generator ++;
849 #elif defined(TARGET_POWERPC)
850 g_assert (!acfg->use_bin_writer);
851 emit_unset_mode (acfg);
852 fprintf (acfg->fp, ".L%d:\n", acfg->label_generator);
853 fprintf (acfg->fp, "lis 0, (%s + 4 - .L%d)@h\n", acfg->got_symbol, acfg->label_generator);
854 fprintf (acfg->fp, "ori 0, 0, (%s + 4 - .L%d)@l\n", acfg->got_symbol, acfg->label_generator);
855 acfg->label_generator ++;
858 guint32 offset = mono_arch_get_patch_offset (code);
859 emit_bytes (acfg, code, offset);
860 emit_symbol_diff (acfg, acfg->got_symbol, ".", offset);
862 *code_size = offset + 4;
867 * arch_emit_got_access:
869 * The memory pointed to by CODE should hold native code for loading a GOT
870 * slot. Emit this code while patching it so it accesses the GOT slot GOT_SLOT.
871 * CODE_SIZE is set to the number of bytes emitted.
874 arch_emit_got_access (MonoAotCompile *acfg, guint8 *code, int got_slot, int *code_size)
876 /* Emit beginning of instruction */
877 emit_bytes (acfg, code, mono_arch_get_patch_offset (code));
879 /* Emit the offset */
881 emit_symbol_diff (acfg, acfg->got_symbol, ".", (unsigned int) ((got_slot * sizeof (gpointer)) - 4));
882 *code_size = mono_arch_get_patch_offset (code) + 4;
883 #elif defined(TARGET_X86)
884 emit_int32 (acfg, (unsigned int) ((got_slot * sizeof (gpointer))));
885 *code_size = mono_arch_get_patch_offset (code) + 4;
886 #elif defined(TARGET_ARM)
887 emit_symbol_diff (acfg, acfg->got_symbol, ".", (unsigned int) ((got_slot * sizeof (gpointer))) - 12);
888 *code_size = mono_arch_get_patch_offset (code) + 4;
889 #elif defined(TARGET_ARM64)
890 arm64_emit_got_access (acfg, code, got_slot, code_size);
891 #elif defined(TARGET_POWERPC)
897 ppc_load32 (code, ppc_r0, got_slot * sizeof (gpointer));
898 g_assert (code - buf == 8);
899 emit_bytes (acfg, buf, code - buf);
900 *code_size = code - buf;
903 g_assert_not_reached ();
909 #ifdef MONO_ARCH_AOT_SUPPORTED
911 * arch_emit_objc_selector_ref:
913 * Emit the implementation of OP_OBJC_GET_SELECTOR, which itself implements @selector(foo:) in objective-c.
916 arch_emit_objc_selector_ref (MonoAotCompile *acfg, guint8 *code, int index, int *code_size)
918 #if defined(TARGET_ARM)
921 int lindex = acfg->objc_selector_index_2 ++;
924 emit_bytes (acfg, code, 8);
926 sprintf (symbol1, "L_OBJC_SELECTOR_%d", lindex);
927 sprintf (symbol2, "L_OBJC_SELECTOR_REFERENCES_%d", index);
929 emit_label (acfg, symbol1);
930 img_writer_emit_unset_mode (acfg->w);
931 fprintf (acfg->fp, ".long %s-(%s+12)", symbol2, symbol1);
934 #elif defined(TARGET_ARM64)
935 arm64_emit_objc_selector_ref (acfg, code, index, code_size);
937 g_assert_not_reached ();
943 * arch_emit_plt_entry:
945 * Emit code for the PLT entry with index INDEX.
948 arch_emit_plt_entry (MonoAotCompile *acfg, int index)
950 #if defined(TARGET_X86)
951 guint32 offset = (acfg->plt_got_offset_base + index) * sizeof (gpointer);
952 #if defined(__default_codegen__)
953 /* jmp *<offset>(%ebx) */
954 emit_byte (acfg, 0xff);
955 emit_byte (acfg, 0xa3);
956 emit_int32 (acfg, offset);
957 /* Used by mono_aot_get_plt_info_offset */
958 emit_int32 (acfg, acfg->plt_got_info_offsets [index]);
959 #elif defined(__native_client_codegen__)
960 const guint8 kSizeOfNaClJmp = 11;
961 guint8 bytes[kSizeOfNaClJmp];
962 guint8 *pbytes = &bytes[0];
964 x86_jump_membase32 (pbytes, X86_EBX, offset);
965 emit_bytes (acfg, bytes, kSizeOfNaClJmp);
966 /* four bytes of data, used by mono_arch_patch_plt_entry */
967 /* For Native Client, make this work with data embedded in push. */
968 emit_byte (acfg, 0x68); /* hide data in a push */
969 emit_int32 (acfg, acfg->plt_got_info_offsets [index]);
970 emit_alignment (acfg, AOT_FUNC_ALIGNMENT);
971 #endif /*__native_client_codegen__*/
972 #elif defined(TARGET_AMD64)
973 #if defined(__default_codegen__)
975 * We can't emit jumps because they are 32 bits only so they can't be patched.
976 * So we make indirect calls through GOT entries which are patched by the AOT
977 * loader to point to .Lpd entries.
979 /* jmpq *<offset>(%rip) */
980 emit_byte (acfg, '\xff');
981 emit_byte (acfg, '\x25');
982 emit_symbol_diff (acfg, acfg->got_symbol, ".", ((acfg->plt_got_offset_base + index) * sizeof (gpointer)) -4);
983 /* Used by mono_aot_get_plt_info_offset */
984 emit_int32 (acfg, acfg->plt_got_info_offsets [index]);
985 acfg->stats.plt_size += 10;
986 #elif defined(__native_client_codegen__)
988 guint8 *buf_aligned = ALIGN_TO(buf, kNaClAlignment);
989 guint8 *code = buf_aligned;
991 /* mov <OFFSET>(%rip), %r11d */
992 emit_byte (acfg, '\x45');
993 emit_byte (acfg, '\x8b');
994 emit_byte (acfg, '\x1d');
995 emit_symbol_diff (acfg, acfg->got_symbol, ".", ((acfg->plt_got_offset_base + index) * sizeof (gpointer)) -4);
997 amd64_jump_reg (code, AMD64_R11);
998 /* This should be constant for the plt patch */
999 g_assert ((size_t)(code-buf_aligned) == 10);
1000 emit_bytes (acfg, buf_aligned, code - buf_aligned);
1002 /* Hide data in a push imm32 so it passes validation */
1003 emit_byte (acfg, 0x68); /* push */
1004 emit_int32 (acfg, acfg->plt_got_info_offsets [index]);
1005 emit_alignment (acfg, AOT_FUNC_ALIGNMENT);
1006 #endif /*__native_client_codegen__*/
1007 #elif defined(TARGET_ARM)
1012 ARM_LDR_IMM (code, ARMREG_IP, ARMREG_PC, 0);
1013 ARM_LDR_REG_REG (code, ARMREG_PC, ARMREG_PC, ARMREG_IP);
1014 emit_bytes (acfg, buf, code - buf);
1015 emit_symbol_diff (acfg, acfg->got_symbol, ".", ((acfg->plt_got_offset_base + index) * sizeof (gpointer)) - 4);
1016 /* Used by mono_aot_get_plt_info_offset */
1017 emit_int32 (acfg, acfg->plt_got_info_offsets [index]);
1018 #elif defined(TARGET_ARM64)
1019 arm64_emit_plt_entry (acfg, index);
1020 #elif defined(TARGET_POWERPC)
1021 guint32 offset = (acfg->plt_got_offset_base + index) * sizeof (gpointer);
1023 /* The GOT address is guaranteed to be in r30 by OP_LOAD_GOTADDR */
1024 g_assert (!acfg->use_bin_writer);
1025 emit_unset_mode (acfg);
1026 fprintf (acfg->fp, "lis 11, %d@h\n", offset);
1027 fprintf (acfg->fp, "ori 11, 11, %d@l\n", offset);
1028 fprintf (acfg->fp, "add 11, 11, 30\n");
1029 fprintf (acfg->fp, "%s 11, 0(11)\n", PPC_LD_OP);
1030 #ifdef PPC_USES_FUNCTION_DESCRIPTOR
1031 fprintf (acfg->fp, "%s 2, %d(11)\n", PPC_LD_OP, (int)sizeof (gpointer));
1032 fprintf (acfg->fp, "%s 11, 0(11)\n", PPC_LD_OP);
1034 fprintf (acfg->fp, "mtctr 11\n");
1035 fprintf (acfg->fp, "bctr\n");
1036 emit_int32 (acfg, acfg->plt_got_info_offsets [index]);
1038 g_assert_not_reached ();
1043 arch_emit_llvm_plt_entry (MonoAotCompile *acfg, int index)
1045 #if defined(TARGET_ARM)
1047 /* LLVM calls the PLT entries using bl, so emit a stub */
1048 /* FIXME: Too much overhead on every call */
1049 fprintf (acfg->fp, ".thumb_func\n");
1050 fprintf (acfg->fp, "bx pc\n");
1051 fprintf (acfg->fp, "nop\n");
1052 fprintf (acfg->fp, ".arm\n");
1054 /* LLVM calls the PLT entries using bl, so these have to be thumb2 */
1055 /* The caller already transitioned to thumb */
1056 /* The code below should be 12 bytes long */
1057 /* clang has trouble encoding these instructions, so emit the binary */
1059 fprintf (acfg->fp, "ldr ip, [pc, #8]\n");
1060 /* thumb can't encode ld pc, [pc, ip] */
1061 fprintf (acfg->fp, "add ip, pc, ip\n");
1062 fprintf (acfg->fp, "ldr ip, [ip, #0]\n");
1063 fprintf (acfg->fp, "bx ip\n");
1065 emit_set_thumb_mode (acfg);
1066 fprintf (acfg->fp, ".4byte 0xc008f8df\n");
1067 fprintf (acfg->fp, ".2byte 0x44fc\n");
1068 fprintf (acfg->fp, ".4byte 0xc000f8dc\n");
1069 fprintf (acfg->fp, ".2byte 0x4760\n");
1070 emit_symbol_diff (acfg, acfg->got_symbol, ".", ((acfg->plt_got_offset_base + index) * sizeof (gpointer)) + 4);
1071 emit_int32 (acfg, acfg->plt_got_info_offsets [index]);
1072 emit_unset_mode (acfg);
1073 emit_set_arm_mode (acfg);
1075 g_assert_not_reached ();
1080 * arch_emit_specific_trampoline_pages:
1082 * Emits a page full of trampolines: each trampoline uses its own address to
1083 * lookup both the generic trampoline code and the data argument.
1084 * This page can be remapped in process multiple times so we can get an
1085 * unlimited number of trampolines.
1086 * Specifically this implementation uses the following trick: two memory pages
1087 * are allocated, with the first containing the data and the second containing the trampolines.
1088 * To reduce trampoline size, each trampoline jumps at the start of the page where a common
1089 * implementation does all the lifting.
1090 * Note that the ARM single trampoline size is 8 bytes, exactly like the data that needs to be stored
1091 * on the arm 32 bit system.
1094 arch_emit_specific_trampoline_pages (MonoAotCompile *acfg)
1096 #if defined(TARGET_ARM)
1099 guint8 *loop_start, *loop_branch_back, *loop_end_check, *imt_found_check;
1101 #define COMMON_TRAMP_SIZE 16
1102 int count = (mono_pagesize () - COMMON_TRAMP_SIZE) / 8;
1103 int imm8, rot_amount;
1106 if (!acfg->aot_opts.use_trampolines_page)
1109 acfg->tramp_page_size = mono_pagesize ();
1111 sprintf (symbol, "%sspecific_trampolines_page", acfg->user_symbol_prefix);
1112 emit_alignment (acfg, mono_pagesize ());
1113 emit_global (acfg, symbol, TRUE);
1114 emit_label (acfg, symbol);
1116 /* emit the generic code first, the trampoline address + 8 is in the lr register */
1118 imm8 = mono_arm_is_rotated_imm8 (mono_pagesize (), &rot_amount);
1119 ARM_SUB_REG_IMM (code, ARMREG_LR, ARMREG_LR, imm8, rot_amount);
1120 ARM_LDR_IMM (code, ARMREG_R1, ARMREG_LR, -8);
1121 ARM_LDR_IMM (code, ARMREG_PC, ARMREG_LR, -4);
1123 g_assert (code - buf == COMMON_TRAMP_SIZE);
1126 emit_bytes (acfg, buf, code - buf);
1128 for (i = 0; i < count; ++i) {
1130 ARM_PUSH (code, 0x5fff);
1132 arm_patch (code - 4, code - COMMON_TRAMP_SIZE - 8 * (i + 1));
1133 g_assert (code - buf == 8);
1134 emit_bytes (acfg, buf, code - buf);
1137 /* now the rgctx trampolines: each specific trampolines puts in the ip register
1138 * the instruction pointer address, so the generic trampoline at the start of the page
1139 * subtracts 4096 to get to the data page and loads the values
1140 * We again fit the generic trampiline in 16 bytes.
1142 sprintf (symbol, "%srgctx_trampolines_page", acfg->user_symbol_prefix);
1143 emit_global (acfg, symbol, TRUE);
1144 emit_label (acfg, symbol);
1146 imm8 = mono_arm_is_rotated_imm8 (mono_pagesize (), &rot_amount);
1147 ARM_SUB_REG_IMM (code, ARMREG_IP, ARMREG_IP, imm8, rot_amount);
1148 ARM_LDR_IMM (code, MONO_ARCH_RGCTX_REG, ARMREG_IP, -8);
1149 ARM_LDR_IMM (code, ARMREG_PC, ARMREG_IP, -4);
1151 g_assert (code - buf == COMMON_TRAMP_SIZE);
1154 emit_bytes (acfg, buf, code - buf);
1156 for (i = 0; i < count; ++i) {
1158 ARM_MOV_REG_REG (code, ARMREG_IP, ARMREG_PC);
1160 arm_patch (code - 4, code - COMMON_TRAMP_SIZE - 8 * (i + 1));
1161 g_assert (code - buf == 8);
1162 emit_bytes (acfg, buf, code - buf);
1166 * gsharedvt arg trampolines: see arch_emit_gsharedvt_arg_trampoline ()
1168 sprintf (symbol, "%sgsharedvt_arg_trampolines_page", acfg->user_symbol_prefix);
1169 emit_global (acfg, symbol, TRUE);
1170 emit_label (acfg, symbol);
1172 ARM_PUSH (code, (1 << ARMREG_R0) | (1 << ARMREG_R1) | (1 << ARMREG_R2) | (1 << ARMREG_R3));
1173 imm8 = mono_arm_is_rotated_imm8 (mono_pagesize (), &rot_amount);
1174 ARM_SUB_REG_IMM (code, ARMREG_IP, ARMREG_IP, imm8, rot_amount);
1175 ARM_LDR_IMM (code, ARMREG_R0, ARMREG_IP, -8);
1176 ARM_LDR_IMM (code, ARMREG_PC, ARMREG_IP, -4);
1177 g_assert (code - buf == COMMON_TRAMP_SIZE);
1179 emit_bytes (acfg, buf, code - buf);
1181 for (i = 0; i < count; ++i) {
1183 ARM_MOV_REG_REG (code, ARMREG_IP, ARMREG_PC);
1185 arm_patch (code - 4, code - COMMON_TRAMP_SIZE - 8 * (i + 1));
1186 g_assert (code - buf == 8);
1187 emit_bytes (acfg, buf, code - buf);
1190 /* now the imt trampolines: each specific trampolines puts in the ip register
1191 * the instruction pointer address, so the generic trampoline at the start of the page
1192 * subtracts 4096 to get to the data page and loads the values
1193 * We again fit the generic trampiline in 16 bytes.
1195 #define IMT_TRAMP_SIZE 72
1196 sprintf (symbol, "%simt_trampolines_page", acfg->user_symbol_prefix);
1197 emit_global (acfg, symbol, TRUE);
1198 emit_label (acfg, symbol);
1200 /* Need at least two free registers, plus a slot for storing the pc */
1201 ARM_PUSH (code, (1 << ARMREG_R0)|(1 << ARMREG_R1)|(1 << ARMREG_R2));
1203 imm8 = mono_arm_is_rotated_imm8 (mono_pagesize (), &rot_amount);
1204 ARM_SUB_REG_IMM (code, ARMREG_IP, ARMREG_IP, imm8, rot_amount);
1205 ARM_LDR_IMM (code, ARMREG_R0, ARMREG_IP, -8);
1207 /* The IMT method is in v5, r0 has the imt array address */
1210 ARM_LDR_IMM (code, ARMREG_R1, ARMREG_R0, 0);
1211 ARM_CMP_REG_REG (code, ARMREG_R1, ARMREG_V5);
1212 imt_found_check = code;
1213 ARM_B_COND (code, ARMCOND_EQ, 0);
1215 /* End-of-loop check */
1216 ARM_CMP_REG_IMM (code, ARMREG_R1, 0, 0);
1217 loop_end_check = code;
1218 ARM_B_COND (code, ARMCOND_EQ, 0);
1221 ARM_ADD_REG_IMM8 (code, ARMREG_R0, ARMREG_R0, sizeof (gpointer) * 2);
1222 loop_branch_back = code;
1224 arm_patch (loop_branch_back, loop_start);
1227 arm_patch (imt_found_check, code);
1228 ARM_LDR_IMM (code, ARMREG_R0, ARMREG_R0, 4);
1229 ARM_LDR_IMM (code, ARMREG_R0, ARMREG_R0, 0);
1230 /* Save it to the third stack slot */
1231 ARM_STR_IMM (code, ARMREG_R0, ARMREG_SP, 8);
1232 /* Restore the registers and branch */
1233 ARM_POP (code, (1 << ARMREG_R0)|(1 << ARMREG_R1)|(1 << ARMREG_PC));
1236 arm_patch (loop_end_check, code);
1237 ARM_LDR_IMM (code, ARMREG_R0, ARMREG_R0, 4);
1238 ARM_STR_IMM (code, ARMREG_R0, ARMREG_SP, 8);
1239 ARM_POP (code, (1 << ARMREG_R0)|(1 << ARMREG_R1)|(1 << ARMREG_PC));
1243 g_assert (code - buf == IMT_TRAMP_SIZE);
1244 emit_bytes (acfg, buf, code - buf);
1246 for (i = 0; i < count; ++i) {
1248 ARM_MOV_REG_REG (code, ARMREG_IP, ARMREG_PC);
1250 arm_patch (code - 4, code - IMT_TRAMP_SIZE - 8 * (i + 1));
1251 g_assert (code - buf == 8);
1252 emit_bytes (acfg, buf, code - buf);
1255 acfg->tramp_page_code_offsets [MONO_AOT_TRAMP_SPECIFIC] = 16;
1256 acfg->tramp_page_code_offsets [MONO_AOT_TRAMP_STATIC_RGCTX] = 16;
1257 acfg->tramp_page_code_offsets [MONO_AOT_TRAMP_IMT_THUNK] = 72;
1258 acfg->tramp_page_code_offsets [MONO_AOT_TRAMP_GSHAREDVT_ARG] = 16;
1259 #elif defined(TARGET_ARM64)
1260 arm64_emit_specific_trampoline_pages (acfg);
1265 * arch_emit_specific_trampoline:
1267 * Emit code for a specific trampoline. OFFSET is the offset of the first of
1268 * two GOT slots which contain the generic trampoline address and the trampoline
1269 * argument. TRAMP_SIZE is set to the size of the emitted trampoline.
1272 arch_emit_specific_trampoline (MonoAotCompile *acfg, int offset, int *tramp_size)
1275 * The trampolines created here are variations of the specific
1276 * trampolines created in mono_arch_create_specific_trampoline (). The
1278 * - the generic trampoline address is taken from a got slot.
1279 * - the offset of the got slot where the trampoline argument is stored
1280 * is embedded in the instruction stream, and the generic trampoline
1281 * can load the argument by loading the offset, adding it to the
1282 * address of the trampoline to get the address of the got slot, and
1283 * loading the argument from there.
1284 * - all the trampolines should be of the same length.
1286 #if defined(TARGET_AMD64)
1287 #if defined(__default_codegen__)
1288 /* This should be exactly 16 bytes long */
1290 /* call *<offset>(%rip) */
1291 emit_byte (acfg, '\x41');
1292 emit_byte (acfg, '\xff');
1293 emit_byte (acfg, '\x15');
1294 emit_symbol_diff (acfg, acfg->got_symbol, ".", (offset * sizeof (gpointer)) - 4);
1295 /* This should be relative to the start of the trampoline */
1296 emit_symbol_diff (acfg, acfg->got_symbol, ".", ((offset+1) * sizeof (gpointer)) + 7);
1297 emit_zero_bytes (acfg, 5);
1298 #elif defined(__native_client_codegen__)
1300 guint8 *buf_aligned = ALIGN_TO(buf, kNaClAlignment);
1301 guint8 *code = buf_aligned;
1306 /* Emit this call in 'code' so we can find out how long it is. */
1307 amd64_call_reg (code, AMD64_R11);
1308 call_start = mono_arch_nacl_skip_nops (buf_aligned);
1309 call_len = code - call_start;
1311 /* The tramp_size is twice the NaCl alignment because it starts with */
1312 /* a call which needs to be aligned to the end of the boundary. */
1313 *tramp_size = kNaClAlignment*2;
1315 /* Emit nops to align call site below which is 7 bytes plus */
1316 /* the length of the call sequence emitted above. */
1317 /* Note: this requires the specific trampoline starts on a */
1318 /* kNaclAlignedment aligned address, which it does because */
1319 /* it's its own function that is aligned. */
1320 guint8 nop_buf[256];
1321 guint8 *nopbuf_aligned = ALIGN_TO (nop_buf, kNaClAlignment);
1322 guint8 *nopbuf_end = mono_arch_nacl_pad (nopbuf_aligned, kNaClAlignment - 7 - (call_len));
1323 emit_bytes (acfg, nopbuf_aligned, nopbuf_end - nopbuf_aligned);
1325 /* The trampoline is stored at the offset'th pointer, the -4 is */
1326 /* present because RIP relative addressing starts at the end of */
1327 /* the current instruction, while the label "." is relative to */
1328 /* the beginning of the current asm location, which in this case */
1329 /* is not the mov instruction, but the offset itself, due to the */
1330 /* way the bytes and ints are emitted here. */
1331 got_offset = (offset * sizeof(gpointer)) - 4;
1333 /* mov <OFFSET>(%rip), %r11d */
1334 emit_byte (acfg, '\x45');
1335 emit_byte (acfg, '\x8b');
1336 emit_byte (acfg, '\x1d');
1337 emit_symbol_diff (acfg, acfg->got_symbol, ".", got_offset);
1340 emit_bytes (acfg, call_start, call_len);
1342 /* The arg is stored at the offset+1 pointer, relative to beginning */
1343 /* of trampoline: 7 for mov, plus the call length, and 1 for push. */
1344 got_offset = ((offset + 1) * sizeof(gpointer)) + 7 + call_len + 1;
1346 /* We can't emit this data directly, hide in a "push imm32" */
1347 emit_byte (acfg, '\x68'); /* push */
1348 emit_symbol_diff (acfg, acfg->got_symbol, ".", got_offset);
1349 emit_alignment (acfg, kNaClAlignment);
1350 #endif /*__native_client_codegen__*/
1351 #elif defined(TARGET_ARM)
1355 /* This should be exactly 20 bytes long */
1358 ARM_PUSH (code, 0x5fff);
1359 ARM_LDR_IMM (code, ARMREG_R1, ARMREG_PC, 4);
1360 /* Load the value from the GOT */
1361 ARM_LDR_REG_REG (code, ARMREG_R1, ARMREG_PC, ARMREG_R1);
1363 ARM_BLX_REG (code, ARMREG_R1);
1365 g_assert (code - buf == 16);
1368 emit_bytes (acfg, buf, code - buf);
1370 * Only one offset is needed, since the second one would be equal to the
1373 emit_symbol_diff (acfg, acfg->got_symbol, ".", (offset * sizeof (gpointer)) - 4 + 4);
1374 //emit_symbol_diff (acfg, acfg->got_symbol, ".", ((offset + 1) * sizeof (gpointer)) - 4 + 8);
1375 #elif defined(TARGET_ARM64)
1376 arm64_emit_specific_trampoline (acfg, offset, tramp_size);
1377 #elif defined(TARGET_POWERPC)
1384 g_assert (!acfg->use_bin_writer);
1387 * PPC has no ip relative addressing, so we need to compute the address
1388 * of the mscorlib got. That is slow and complex, so instead, we store it
1389 * in the second got slot of every aot image. The caller already computed
1390 * the address of its got and placed it into r30.
1392 emit_unset_mode (acfg);
1393 /* Load mscorlib got address */
1394 fprintf (acfg->fp, "%s 0, %d(30)\n", PPC_LD_OP, (int)sizeof (gpointer));
1395 /* Load generic trampoline address */
1396 fprintf (acfg->fp, "lis 11, %d@h\n", (int)(offset * sizeof (gpointer)));
1397 fprintf (acfg->fp, "ori 11, 11, %d@l\n", (int)(offset * sizeof (gpointer)));
1398 fprintf (acfg->fp, "%s 11, 11, 0\n", PPC_LDX_OP);
1399 #ifdef PPC_USES_FUNCTION_DESCRIPTOR
1400 fprintf (acfg->fp, "%s 11, 0(11)\n", PPC_LD_OP);
1402 fprintf (acfg->fp, "mtctr 11\n");
1403 /* Load trampoline argument */
1404 /* On ppc, we pass it normally to the generic trampoline */
1405 fprintf (acfg->fp, "lis 11, %d@h\n", (int)((offset + 1) * sizeof (gpointer)));
1406 fprintf (acfg->fp, "ori 11, 11, %d@l\n", (int)((offset + 1) * sizeof (gpointer)));
1407 fprintf (acfg->fp, "%s 0, 11, 0\n", PPC_LDX_OP);
1408 /* Branch to generic trampoline */
1409 fprintf (acfg->fp, "bctr\n");
1411 #ifdef PPC_USES_FUNCTION_DESCRIPTOR
1412 *tramp_size = 10 * 4;
1414 *tramp_size = 9 * 4;
1416 #elif defined(TARGET_X86)
1420 /* Similar to the PPC code above */
1422 /* FIXME: Could this clobber the register needed by get_vcall_slot () ? */
1424 /* We clobber ECX, since EAX is used as MONO_ARCH_MONITOR_OBJECT_REG */
1425 #ifdef MONO_ARCH_MONITOR_OBJECT_REG
1426 g_assert (MONO_ARCH_MONITOR_OBJECT_REG != X86_ECX);
1430 /* Load mscorlib got address */
1431 x86_mov_reg_membase (code, X86_ECX, MONO_ARCH_GOT_REG, sizeof (gpointer), 4);
1432 /* Push trampoline argument */
1433 x86_push_membase (code, X86_ECX, (offset + 1) * sizeof (gpointer));
1434 /* Load generic trampoline address */
1435 x86_mov_reg_membase (code, X86_ECX, X86_ECX, offset * sizeof (gpointer), 4);
1436 /* Branch to generic trampoline */
1437 x86_jump_reg (code, X86_ECX);
1439 #ifdef __native_client_codegen__
1441 /* emit nops to next 32 byte alignment */
1442 int a = (~kNaClAlignmentMask) & ((code - buf) + kNaClAlignment - 1);
1443 while (code < (buf + a)) x86_nop(code);
1446 emit_bytes (acfg, buf, code - buf);
1448 *tramp_size = NACL_SIZE(17, kNaClAlignment);
1449 g_assert (code - buf == *tramp_size);
1451 g_assert_not_reached ();
1456 * arch_emit_unbox_trampoline:
1458 * Emit code for the unbox trampoline for METHOD used in the full-aot case.
1459 * CALL_TARGET is the symbol pointing to the native code of METHOD.
1462 arch_emit_unbox_trampoline (MonoAotCompile *acfg, MonoCompile *cfg, MonoMethod *method, const char *call_target)
1464 #if defined(TARGET_AMD64)
1469 this_reg = mono_arch_get_this_arg_reg (NULL);
1471 amd64_alu_reg_imm (code, X86_ADD, this_reg, sizeof (MonoObject));
1473 emit_bytes (acfg, buf, code - buf);
1475 emit_byte (acfg, '\xe9');
1476 emit_symbol_diff (acfg, call_target, ".", -4);
1477 #elif defined(TARGET_X86)
1484 x86_alu_membase_imm (code, X86_ADD, X86_ESP, this_pos, sizeof (MonoObject));
1486 emit_bytes (acfg, buf, code - buf);
1489 emit_byte (acfg, '\xe9');
1490 emit_symbol_diff (acfg, call_target, ".", -4);
1491 #elif defined(TARGET_ARM)
1495 if (acfg->thumb_mixed && cfg->compile_llvm) {
1496 fprintf (acfg->fp, "add r0, r0, #%d\n", (int)sizeof (MonoObject));
1497 fprintf (acfg->fp, "b %s\n", call_target);
1498 fprintf (acfg->fp, ".arm\n");
1499 fprintf (acfg->fp, ".align 2\n");
1505 ARM_ADD_REG_IMM8 (code, ARMREG_R0, ARMREG_R0, sizeof (MonoObject));
1507 emit_bytes (acfg, buf, code - buf);
1508 /* jump to method */
1509 if (acfg->use_bin_writer) {
1516 img_writer_emit_reloc (acfg->w, R_ARM_JUMP24, call_target, -8);
1517 emit_bytes (acfg, buf, 4);
1519 if (acfg->thumb_mixed && cfg->compile_llvm)
1520 fprintf (acfg->fp, "\n\tbx %s\n", call_target);
1522 fprintf (acfg->fp, "\n\tb %s\n", call_target);
1524 #elif defined(TARGET_ARM64)
1525 arm64_emit_unbox_trampoline (acfg, cfg, method, call_target);
1526 #elif defined(TARGET_POWERPC)
1529 g_assert (!acfg->use_bin_writer);
1531 fprintf (acfg->fp, "\n\taddi %d, %d, %d\n", this_pos, this_pos, (int)sizeof (MonoObject));
1532 fprintf (acfg->fp, "\n\tb %s\n", call_target);
1534 g_assert_not_reached ();
1539 * arch_emit_static_rgctx_trampoline:
1541 * Emit code for a static rgctx trampoline. OFFSET is the offset of the first of
1542 * two GOT slots which contain the rgctx argument, and the method to jump to.
1543 * TRAMP_SIZE is set to the size of the emitted trampoline.
1544 * These kinds of trampolines cannot be enumerated statically, since there could
1545 * be one trampoline per method instantiation, so we emit the same code for all
1546 * trampolines, and parameterize them using two GOT slots.
1549 arch_emit_static_rgctx_trampoline (MonoAotCompile *acfg, int offset, int *tramp_size)
1551 #if defined(TARGET_AMD64)
1552 #if defined(__default_codegen__)
1553 /* This should be exactly 13 bytes long */
1556 /* mov <OFFSET>(%rip), %r10 */
1557 emit_byte (acfg, '\x4d');
1558 emit_byte (acfg, '\x8b');
1559 emit_byte (acfg, '\x15');
1560 emit_symbol_diff (acfg, acfg->got_symbol, ".", (offset * sizeof (gpointer)) - 4);
1562 /* jmp *<offset>(%rip) */
1563 emit_byte (acfg, '\xff');
1564 emit_byte (acfg, '\x25');
1565 emit_symbol_diff (acfg, acfg->got_symbol, ".", ((offset + 1) * sizeof (gpointer)) - 4);
1566 #elif defined(__native_client_codegen__)
1568 guint8 *buf_aligned = ALIGN_TO(buf, kNaClAlignment);
1569 guint8 *code = buf_aligned;
1571 /* mov <OFFSET>(%rip), %r10d */
1572 emit_byte (acfg, '\x45');
1573 emit_byte (acfg, '\x8b');
1574 emit_byte (acfg, '\x15');
1575 emit_symbol_diff (acfg, acfg->got_symbol, ".", (offset * sizeof (gpointer)) - 4);
1577 /* mov <OFFSET>(%rip), %r11d */
1578 emit_byte (acfg, '\x45');
1579 emit_byte (acfg, '\x8b');
1580 emit_byte (acfg, '\x1d');
1581 emit_symbol_diff (acfg, acfg->got_symbol, ".", ((offset + 1) * sizeof (gpointer)) - 4);
1584 amd64_jump_reg (code, AMD64_R11);
1585 emit_bytes (acfg, buf_aligned, code - buf_aligned);
1587 emit_alignment (acfg, kNaClAlignment);
1588 *tramp_size = kNaClAlignment;
1589 #endif /*__native_client_codegen__*/
1591 #elif defined(TARGET_ARM)
1595 /* This should be exactly 24 bytes long */
1598 /* Load rgctx value */
1599 ARM_LDR_IMM (code, ARMREG_IP, ARMREG_PC, 8);
1600 ARM_LDR_REG_REG (code, MONO_ARCH_RGCTX_REG, ARMREG_PC, ARMREG_IP);
1601 /* Load branch addr + branch */
1602 ARM_LDR_IMM (code, ARMREG_IP, ARMREG_PC, 4);
1603 ARM_LDR_REG_REG (code, ARMREG_PC, ARMREG_PC, ARMREG_IP);
1605 g_assert (code - buf == 16);
1608 emit_bytes (acfg, buf, code - buf);
1609 emit_symbol_diff (acfg, acfg->got_symbol, ".", (offset * sizeof (gpointer)) - 4 + 8);
1610 emit_symbol_diff (acfg, acfg->got_symbol, ".", ((offset + 1) * sizeof (gpointer)) - 4 + 4);
1611 #elif defined(TARGET_ARM64)
1612 arm64_emit_static_rgctx_trampoline (acfg, offset, tramp_size);
1613 #elif defined(TARGET_POWERPC)
1620 g_assert (!acfg->use_bin_writer);
1623 * PPC has no ip relative addressing, so we need to compute the address
1624 * of the mscorlib got. That is slow and complex, so instead, we store it
1625 * in the second got slot of every aot image. The caller already computed
1626 * the address of its got and placed it into r30.
1628 emit_unset_mode (acfg);
1629 /* Load mscorlib got address */
1630 fprintf (acfg->fp, "%s 0, %d(30)\n", PPC_LD_OP, (int)sizeof (gpointer));
1632 fprintf (acfg->fp, "lis 11, %d@h\n", (int)(offset * sizeof (gpointer)));
1633 fprintf (acfg->fp, "ori 11, 11, %d@l\n", (int)(offset * sizeof (gpointer)));
1634 fprintf (acfg->fp, "%s %d, 11, 0\n", PPC_LDX_OP, MONO_ARCH_RGCTX_REG);
1635 /* Load target address */
1636 fprintf (acfg->fp, "lis 11, %d@h\n", (int)((offset + 1) * sizeof (gpointer)));
1637 fprintf (acfg->fp, "ori 11, 11, %d@l\n", (int)((offset + 1) * sizeof (gpointer)));
1638 fprintf (acfg->fp, "%s 11, 11, 0\n", PPC_LDX_OP);
1639 #ifdef PPC_USES_FUNCTION_DESCRIPTOR
1640 fprintf (acfg->fp, "%s 2, %d(11)\n", PPC_LD_OP, (int)sizeof (gpointer));
1641 fprintf (acfg->fp, "%s 11, 0(11)\n", PPC_LD_OP);
1643 fprintf (acfg->fp, "mtctr 11\n");
1644 /* Branch to the target address */
1645 fprintf (acfg->fp, "bctr\n");
1647 #ifdef PPC_USES_FUNCTION_DESCRIPTOR
1648 *tramp_size = 11 * 4;
1650 *tramp_size = 9 * 4;
1653 #elif defined(TARGET_X86)
1657 /* Similar to the PPC code above */
1659 g_assert (MONO_ARCH_RGCTX_REG != X86_ECX);
1662 /* Load mscorlib got address */
1663 x86_mov_reg_membase (code, X86_ECX, MONO_ARCH_GOT_REG, sizeof (gpointer), 4);
1665 x86_mov_reg_membase (code, MONO_ARCH_RGCTX_REG, X86_ECX, offset * sizeof (gpointer), 4);
1666 /* Branch to the target address */
1667 x86_jump_membase (code, X86_ECX, (offset + 1) * sizeof (gpointer));
1669 #ifdef __native_client_codegen__
1671 /* emit nops to next 32 byte alignment */
1672 int a = (~kNaClAlignmentMask) & ((code - buf) + kNaClAlignment - 1);
1673 while (code < (buf + a)) x86_nop(code);
1677 emit_bytes (acfg, buf, code - buf);
1679 *tramp_size = NACL_SIZE (15, kNaClAlignment);
1680 g_assert (code - buf == *tramp_size);
1682 g_assert_not_reached ();
1687 * arch_emit_imt_thunk:
1689 * Emit an IMT thunk usable in full-aot mode. The thunk uses 1 got slot which
1690 * points to an array of pointer pairs. The pairs of the form [key, ptr], where
1691 * key is the IMT key, and ptr holds the address of a memory location holding
1692 * the address to branch to if the IMT arg matches the key. The array is
1693 * terminated by a pair whose key is NULL, and whose ptr is the address of the
1695 * TRAMP_SIZE is set to the size of the emitted trampoline.
1698 arch_emit_imt_thunk (MonoAotCompile *acfg, int offset, int *tramp_size)
1700 #if defined(TARGET_AMD64)
1702 #if defined(__native_client_codegen__)
1705 guint8 *labels [16];
1707 guint8 *mov_buf_ptr = mov_buf;
1709 const int kSizeOfMove = 7;
1710 #if defined(__default_codegen__)
1711 code = buf = g_malloc (256);
1712 #elif defined(__native_client_codegen__)
1713 buf_alloc = g_malloc (256 + kNaClAlignment + kSizeOfMove);
1714 buf = ((guint)buf_alloc + kNaClAlignment) & ~kNaClAlignmentMask;
1715 /* The RIP relative move below is emitted first */
1720 /* FIXME: Optimize this, i.e. use binary search etc. */
1721 /* Maybe move the body into a separate function (slower, but much smaller) */
1723 /* MONO_ARCH_IMT_SCRATCH_REG is a free register */
1726 amd64_alu_membase_imm (code, X86_CMP, MONO_ARCH_IMT_SCRATCH_REG, 0, 0);
1728 amd64_branch8 (code, X86_CC_Z, 0, FALSE);
1731 amd64_alu_membase_reg_size (code, X86_CMP, MONO_ARCH_IMT_SCRATCH_REG, 0, MONO_ARCH_IMT_REG, sizeof (gpointer));
1733 amd64_branch8 (code, X86_CC_Z, 0, FALSE);
1736 amd64_alu_reg_imm (code, X86_ADD, MONO_ARCH_IMT_SCRATCH_REG, 2 * sizeof (gpointer));
1737 amd64_jump_code (code, labels [0]);
1740 mono_amd64_patch (labels [2], code);
1741 amd64_mov_reg_membase (code, MONO_ARCH_IMT_SCRATCH_REG, MONO_ARCH_IMT_SCRATCH_REG, sizeof (gpointer), sizeof (gpointer));
1742 amd64_jump_membase (code, MONO_ARCH_IMT_SCRATCH_REG, 0);
1745 mono_amd64_patch (labels [1], code);
1746 /* Load fail tramp */
1747 amd64_alu_reg_imm (code, X86_ADD, MONO_ARCH_IMT_SCRATCH_REG, sizeof (gpointer));
1748 /* Check if there is a fail tramp */
1749 amd64_alu_membase_imm (code, X86_CMP, MONO_ARCH_IMT_SCRATCH_REG, 0, 0);
1751 amd64_branch8 (code, X86_CC_Z, 0, FALSE);
1752 /* Jump to fail tramp */
1753 amd64_jump_membase (code, MONO_ARCH_IMT_SCRATCH_REG, 0);
1756 mono_amd64_patch (labels [3], code);
1757 x86_breakpoint (code);
1759 /* mov <OFFSET>(%rip), MONO_ARCH_IMT_SCRATCH_REG */
1760 amd64_emit_rex (mov_buf_ptr, sizeof(gpointer), MONO_ARCH_IMT_SCRATCH_REG, 0, AMD64_RIP);
1761 *(mov_buf_ptr)++ = (unsigned char)0x8b; /* mov opcode */
1762 x86_address_byte (mov_buf_ptr, 0, MONO_ARCH_IMT_SCRATCH_REG & 0x7, 5);
1763 emit_bytes (acfg, mov_buf, mov_buf_ptr - mov_buf);
1764 emit_symbol_diff (acfg, acfg->got_symbol, ".", (offset * sizeof (gpointer)) - 4);
1766 emit_bytes (acfg, buf, code - buf);
1768 *tramp_size = code - buf + kSizeOfMove;
1769 #if defined(__native_client_codegen__)
1770 /* The tramp will be padded to the next kNaClAlignment bundle. */
1771 *tramp_size = ALIGN_TO ((*tramp_size), kNaClAlignment);
1774 #if defined(__default_codegen__)
1776 #elif defined(__native_client_codegen__)
1780 #elif defined(TARGET_X86)
1782 #ifdef __native_client_codegen__
1785 guint8 *labels [16];
1787 #if defined(__default_codegen__)
1788 code = buf = g_malloc (256);
1789 #elif defined(__native_client_codegen__)
1790 buf_alloc = g_malloc (256 + kNaClAlignment);
1791 code = buf = ((guint)buf_alloc + kNaClAlignment) & ~kNaClAlignmentMask;
1794 /* Allocate a temporary stack slot */
1795 x86_push_reg (code, X86_EAX);
1797 x86_push_reg (code, X86_EAX);
1799 /* Load mscorlib got address */
1800 x86_mov_reg_membase (code, X86_EAX, MONO_ARCH_GOT_REG, sizeof (gpointer), 4);
1802 x86_mov_reg_membase (code, X86_EAX, X86_EAX, offset * sizeof (gpointer), 4);
1805 x86_alu_membase_imm (code, X86_CMP, X86_EAX, 0, 0);
1807 x86_branch8 (code, X86_CC_Z, FALSE, 0);
1810 x86_alu_membase_reg (code, X86_CMP, X86_EAX, 0, MONO_ARCH_IMT_REG);
1812 x86_branch8 (code, X86_CC_Z, FALSE, 0);
1815 x86_alu_reg_imm (code, X86_ADD, X86_EAX, 2 * sizeof (gpointer));
1816 x86_jump_code (code, labels [0]);
1819 mono_x86_patch (labels [2], code);
1820 x86_mov_reg_membase (code, X86_EAX, X86_EAX, sizeof (gpointer), 4);
1821 x86_mov_reg_membase (code, X86_EAX, X86_EAX, 0, 4);
1822 /* Save the target address to the temporary stack location */
1823 x86_mov_membase_reg (code, X86_ESP, 4, X86_EAX, 4);
1825 x86_pop_reg (code, X86_EAX);
1826 /* Jump to the target address */
1830 mono_x86_patch (labels [1], code);
1831 /* Load fail tramp */
1832 x86_mov_reg_membase (code, X86_EAX, X86_EAX, sizeof (gpointer), 4);
1833 x86_alu_membase_imm (code, X86_CMP, X86_EAX, 0, 0);
1835 x86_branch8 (code, X86_CC_Z, FALSE, 0);
1836 /* Jump to fail tramp */
1837 x86_mov_membase_reg (code, X86_ESP, 4, X86_EAX, 4);
1838 x86_pop_reg (code, X86_EAX);
1842 mono_x86_patch (labels [3], code);
1843 x86_breakpoint (code);
1845 #ifdef __native_client_codegen__
1847 /* emit nops to next 32 byte alignment */
1848 int a = (~kNaClAlignmentMask) & ((code - buf) + kNaClAlignment - 1);
1849 while (code < (buf + a)) x86_nop(code);
1852 emit_bytes (acfg, buf, code - buf);
1854 *tramp_size = code - buf;
1856 #if defined(__default_codegen__)
1858 #elif defined(__native_client_codegen__)
1862 #elif defined(TARGET_ARM)
1864 guint8 *code, *code2, *labels [16];
1868 /* The IMT method is in v5 */
1870 /* Need at least two free registers, plus a slot for storing the pc */
1871 ARM_PUSH (code, (1 << ARMREG_R0)|(1 << ARMREG_R1)|(1 << ARMREG_R2));
1873 /* Load the parameter from the GOT */
1874 ARM_LDR_IMM (code, ARMREG_R0, ARMREG_PC, 0);
1875 ARM_LDR_REG_REG (code, ARMREG_R0, ARMREG_PC, ARMREG_R0);
1878 ARM_LDR_IMM (code, ARMREG_R1, ARMREG_R0, 0);
1879 ARM_CMP_REG_REG (code, ARMREG_R1, ARMREG_V5);
1881 ARM_B_COND (code, ARMCOND_EQ, 0);
1883 /* End-of-loop check */
1884 ARM_CMP_REG_IMM (code, ARMREG_R1, 0, 0);
1886 ARM_B_COND (code, ARMCOND_EQ, 0);
1889 ARM_ADD_REG_IMM8 (code, ARMREG_R0, ARMREG_R0, sizeof (gpointer) * 2);
1892 arm_patch (labels [4], labels [1]);
1895 arm_patch (labels [2], code);
1896 ARM_LDR_IMM (code, ARMREG_R0, ARMREG_R0, 4);
1897 ARM_LDR_IMM (code, ARMREG_R0, ARMREG_R0, 0);
1898 /* Save it to the third stack slot */
1899 ARM_STR_IMM (code, ARMREG_R0, ARMREG_SP, 8);
1900 /* Restore the registers and branch */
1901 ARM_POP (code, (1 << ARMREG_R0)|(1 << ARMREG_R1)|(1 << ARMREG_PC));
1904 arm_patch (labels [3], code);
1905 ARM_LDR_IMM (code, ARMREG_R0, ARMREG_R0, 4);
1906 ARM_STR_IMM (code, ARMREG_R0, ARMREG_SP, 8);
1907 ARM_POP (code, (1 << ARMREG_R0)|(1 << ARMREG_R1)|(1 << ARMREG_PC));
1911 ARM_LDR_IMM (code2, ARMREG_R0, ARMREG_PC, (code - (labels [0] + 8)));
1913 emit_bytes (acfg, buf, code - buf);
1914 emit_symbol_diff (acfg, acfg->got_symbol, ".", (offset * sizeof (gpointer)) + (code - (labels [0] + 8)) - 4);
1916 *tramp_size = code - buf + 4;
1917 #elif defined(TARGET_ARM64)
1918 arm64_emit_imt_thunk (acfg, offset, tramp_size);
1919 #elif defined(TARGET_POWERPC)
1921 guint8 *code, *labels [16];
1925 /* Load the mscorlib got address */
1926 ppc_ldptr (code, ppc_r12, sizeof (gpointer), ppc_r30);
1927 /* Load the parameter from the GOT */
1928 ppc_load (code, ppc_r0, offset * sizeof (gpointer));
1929 ppc_ldptr_indexed (code, ppc_r12, ppc_r12, ppc_r0);
1931 /* Load and check key */
1933 ppc_ldptr (code, ppc_r0, 0, ppc_r12);
1934 ppc_cmp (code, 0, sizeof (gpointer) == 8 ? 1 : 0, ppc_r0, MONO_ARCH_IMT_REG);
1936 ppc_bc (code, PPC_BR_TRUE, PPC_BR_EQ, 0);
1938 /* End-of-loop check */
1939 ppc_cmpi (code, 0, sizeof (gpointer) == 8 ? 1 : 0, ppc_r0, 0);
1941 ppc_bc (code, PPC_BR_TRUE, PPC_BR_EQ, 0);
1944 ppc_addi (code, ppc_r12, ppc_r12, 2 * sizeof (gpointer));
1947 mono_ppc_patch (labels [4], labels [1]);
1950 mono_ppc_patch (labels [2], code);
1951 ppc_ldptr (code, ppc_r12, sizeof (gpointer), ppc_r12);
1952 /* r12 now contains the value of the vtable slot */
1953 /* this is not a function descriptor on ppc64 */
1954 ppc_ldptr (code, ppc_r12, 0, ppc_r12);
1955 ppc_mtctr (code, ppc_r12);
1956 ppc_bcctr (code, PPC_BR_ALWAYS, 0);
1959 mono_ppc_patch (labels [3], code);
1963 *tramp_size = code - buf;
1965 emit_bytes (acfg, buf, code - buf);
1967 g_assert_not_reached ();
1972 * arch_emit_gsharedvt_arg_trampoline:
1974 * Emit code for a gsharedvt arg trampoline. OFFSET is the offset of the first of
1975 * two GOT slots which contain the argument, and the code to jump to.
1976 * TRAMP_SIZE is set to the size of the emitted trampoline.
1977 * These kinds of trampolines cannot be enumerated statically, since there could
1978 * be one trampoline per method instantiation, so we emit the same code for all
1979 * trampolines, and parameterize them using two GOT slots.
1982 arch_emit_gsharedvt_arg_trampoline (MonoAotCompile *acfg, int offset, int *tramp_size)
1984 #if defined(TARGET_X86)
1988 /* Similar to the PPC code above */
1990 g_assert (MONO_ARCH_RGCTX_REG != X86_ECX);
1993 /* Load mscorlib got address */
1994 x86_mov_reg_membase (code, X86_ECX, MONO_ARCH_GOT_REG, sizeof (gpointer), 4);
1996 x86_mov_reg_membase (code, X86_EAX, X86_ECX, offset * sizeof (gpointer), 4);
1997 /* Branch to the target address */
1998 x86_jump_membase (code, X86_ECX, (offset + 1) * sizeof (gpointer));
2000 #ifdef __native_client_codegen__
2002 /* emit nops to next 32 byte alignment */
2003 int a = (~kNaClAlignmentMask) & ((code - buf) + kNaClAlignment - 1);
2004 while (code < (buf + a)) x86_nop(code);
2008 emit_bytes (acfg, buf, code - buf);
2010 *tramp_size = NACL_SIZE (15, kNaClAlignment);
2011 g_assert (code - buf == *tramp_size);
2012 #elif defined(TARGET_ARM)
2016 /* The same as mono_arch_get_gsharedvt_arg_trampoline (), but for AOT */
2017 /* Similar to arch_emit_specific_trampoline () */
2020 ARM_PUSH (code, (1 << ARMREG_R0) | (1 << ARMREG_R1) | (1 << ARMREG_R2) | (1 << ARMREG_R3));
2021 ARM_LDR_IMM (code, ARMREG_R1, ARMREG_PC, 8);
2022 /* Load the arg value from the GOT */
2023 ARM_LDR_REG_REG (code, ARMREG_R0, ARMREG_PC, ARMREG_R1);
2024 /* Load the addr from the GOT */
2025 ARM_LDR_REG_REG (code, ARMREG_R1, ARMREG_PC, ARMREG_R1);
2027 ARM_BX (code, ARMREG_R1);
2029 g_assert (code - buf == 20);
2032 emit_bytes (acfg, buf, code - buf);
2033 emit_symbol_diff (acfg, acfg->got_symbol, ".", (offset * sizeof (gpointer)) + 4);
2034 #elif defined(TARGET_ARM64)
2035 arm64_emit_gsharedvt_arg_trampoline (acfg, offset, tramp_size);
2037 g_assert_not_reached ();
2042 arch_emit_autoreg (MonoAotCompile *acfg, char *symbol)
2044 #if defined(TARGET_POWERPC) && defined(__mono_ilp32__)
2045 /* Based on code generated by gcc */
2046 emit_unset_mode (acfg);
2049 #if defined(_MSC_VER) || defined(MONO_CROSS_COMPILE)
2050 ".section .ctors,\"aw\",@progbits\n"
2054 ".section .opd,\"aw\"\n"
2057 ".long .%s,.TOC.@tocbase32\n"
2060 ".type .%s,@function\n"
2062 ".%s:\n", symbol, symbol, symbol, symbol, symbol, symbol, symbol, symbol);
2064 ".section .ctors,\"aw\",@progbits\n"
2068 ".section .opd,\"aw\"\n"
2071 ".long .%1$s,.TOC.@tocbase32\n"
2072 ".size %1$s,.-%1$s\n"
2074 ".type .%1$s,@function\n"
2076 ".%1$s:\n", symbol);
2087 "lis 3, .Lglobals@h\n"
2088 "ori 3, 3, .Lglobals@l\n"
2089 "bl .mono_aot_register_module\n"
2097 #if defined(_MSC_VER) || defined(MONO_CROSS_COMPILE)
2099 ".size .%s,.-.%s\n", symbol, symbol);
2102 ".size .%1$s,.-.%1$s\n", symbol);
2108 /* END OF ARCH SPECIFIC CODE */
2111 mono_get_field_token (MonoClassField *field)
2113 MonoClass *klass = field->parent;
2116 for (i = 0; i < klass->field.count; ++i) {
2117 if (field == &klass->fields [i])
2118 return MONO_TOKEN_FIELD_DEF | (klass->field.first + 1 + i);
2121 g_assert_not_reached ();
2126 encode_value (gint32 value, guint8 *buf, guint8 **endbuf)
2130 //printf ("ENCODE: %d 0x%x.\n", value, value);
2133 * Same encoding as the one used in the metadata, extended to handle values
2134 * greater than 0x1fffffff.
2136 if ((value >= 0) && (value <= 127))
2138 else if ((value >= 0) && (value <= 16383)) {
2139 p [0] = 0x80 | (value >> 8);
2140 p [1] = value & 0xff;
2142 } else if ((value >= 0) && (value <= 0x1fffffff)) {
2143 p [0] = (value >> 24) | 0xc0;
2144 p [1] = (value >> 16) & 0xff;
2145 p [2] = (value >> 8) & 0xff;
2146 p [3] = value & 0xff;
2151 p [1] = (value >> 24) & 0xff;
2152 p [2] = (value >> 16) & 0xff;
2153 p [3] = (value >> 8) & 0xff;
2154 p [4] = value & 0xff;
2162 stream_init (MonoDynamicStream *sh)
2165 sh->alloc_size = 4096;
2166 sh->data = g_malloc (4096);
2168 /* So offsets are > 0 */
2174 make_room_in_stream (MonoDynamicStream *stream, int size)
2176 if (size <= stream->alloc_size)
2179 while (stream->alloc_size <= size) {
2180 if (stream->alloc_size < 4096)
2181 stream->alloc_size = 4096;
2183 stream->alloc_size *= 2;
2186 stream->data = g_realloc (stream->data, stream->alloc_size);
2190 add_stream_data (MonoDynamicStream *stream, const char *data, guint32 len)
2194 make_room_in_stream (stream, stream->index + len);
2195 memcpy (stream->data + stream->index, data, len);
2196 idx = stream->index;
2197 stream->index += len;
2204 * Add data to the binary blob inside the aot image. Returns the offset inside the
2205 * blob where the data was stored.
2208 add_to_blob (MonoAotCompile *acfg, const guint8 *data, guint32 data_len)
2210 if (acfg->blob.alloc_size == 0)
2211 stream_init (&acfg->blob);
2213 return add_stream_data (&acfg->blob, (char*)data, data_len);
2217 add_to_blob_aligned (MonoAotCompile *acfg, const guint8 *data, guint32 data_len, guint32 align)
2222 if (acfg->blob.alloc_size == 0)
2223 stream_init (&acfg->blob);
2225 count = acfg->blob.index % align;
2227 /* we assume the stream data will be aligned */
2229 add_stream_data (&acfg->blob, buf, 4 - count);
2231 return add_stream_data (&acfg->blob, (char*)data, data_len);
2235 * emit_offset_table:
2237 * Emit a table of increasing offsets in a compact form using differential encoding.
2238 * There is an index entry for each GROUP_SIZE number of entries. The greater the
2239 * group size, the more compact the table becomes, but the slower it becomes to compute
2240 * a given entry. Returns the size of the table.
2243 emit_offset_table (MonoAotCompile *acfg, int noffsets, int group_size, gint32 *offsets)
2245 gint32 current_offset;
2246 int i, buf_size, ngroups, index_entry_size;
2248 guint32 *index_offsets;
2250 ngroups = (noffsets + (group_size - 1)) / group_size;
2252 index_offsets = g_new0 (guint32, ngroups);
2254 buf_size = noffsets * 4;
2255 p = buf = g_malloc0 (buf_size);
2258 for (i = 0; i < noffsets; ++i) {
2259 //printf ("D: %d -> %d\n", i, offsets [i]);
2260 if ((i % group_size) == 0) {
2261 index_offsets [i / group_size] = p - buf;
2262 /* Emit the full value for these entries */
2263 encode_value (offsets [i], p, &p);
2265 /* The offsets are allowed to be non-increasing */
2266 //g_assert (offsets [i] >= current_offset);
2267 encode_value (offsets [i] - current_offset, p, &p);
2269 current_offset = offsets [i];
2272 if (ngroups && index_offsets [ngroups - 1] < 65000)
2273 index_entry_size = 2;
2275 index_entry_size = 4;
2277 /* Emit the header */
2278 emit_int32 (acfg, noffsets);
2279 emit_int32 (acfg, group_size);
2280 emit_int32 (acfg, ngroups);
2281 emit_int32 (acfg, index_entry_size);
2283 /* Emit the index */
2284 for (i = 0; i < ngroups; ++i) {
2285 if (index_entry_size == 2)
2286 emit_int16 (acfg, index_offsets [i]);
2288 emit_int32 (acfg, index_offsets [i]);
2292 emit_bytes (acfg, buf, p - buf);
2294 return (int)(p - buf) + (ngroups * 4);
2298 get_image_index (MonoAotCompile *cfg, MonoImage *image)
2302 index = GPOINTER_TO_UINT (g_hash_table_lookup (cfg->image_hash, image));
2306 index = g_hash_table_size (cfg->image_hash);
2307 g_hash_table_insert (cfg->image_hash, image, GUINT_TO_POINTER (index + 1));
2308 g_ptr_array_add (cfg->image_table, image);
2314 find_typespec_for_class (MonoAotCompile *acfg, MonoClass *klass)
2317 int len = acfg->image->tables [MONO_TABLE_TYPESPEC].rows;
2319 /* FIXME: Search referenced images as well */
2320 if (!acfg->typespec_classes) {
2321 acfg->typespec_classes = mono_mempool_alloc0 (acfg->mempool, sizeof (MonoClass*) * len);
2322 for (i = 0; i < len; ++i) {
2324 acfg->typespec_classes [i] = mono_class_get_and_inflate_typespec_checked (acfg->image, MONO_TOKEN_TYPE_SPEC | (i + 1), NULL, &error);
2325 g_assert (mono_error_ok (&error)); /* FIXME error handling */
2328 for (i = 0; i < len; ++i) {
2329 if (acfg->typespec_classes [i] == klass)
2334 return MONO_TOKEN_TYPE_SPEC | (i + 1);
2340 encode_method_ref (MonoAotCompile *acfg, MonoMethod *method, guint8 *buf, guint8 **endbuf);
2343 encode_klass_ref (MonoAotCompile *acfg, MonoClass *klass, guint8 *buf, guint8 **endbuf);
2346 encode_ginst (MonoAotCompile *acfg, MonoGenericInst *inst, guint8 *buf, guint8 **endbuf);
2349 encode_type (MonoAotCompile *acfg, MonoType *t, guint8 *buf, guint8 **endbuf);
2352 encode_klass_ref_inner (MonoAotCompile *acfg, MonoClass *klass, guint8 *buf, guint8 **endbuf)
2357 * The encoding begins with one of the MONO_AOT_TYPEREF values, followed by additional
2361 if (klass->generic_class) {
2363 g_assert (klass->type_token);
2365 /* Find a typespec for a class if possible */
2366 token = find_typespec_for_class (acfg, klass);
2368 encode_value (MONO_AOT_TYPEREF_TYPESPEC_TOKEN, p, &p);
2369 encode_value (token, p, &p);
2371 MonoClass *gclass = klass->generic_class->container_class;
2372 MonoGenericInst *inst = klass->generic_class->context.class_inst;
2373 static int count = 0;
2376 encode_value (MONO_AOT_TYPEREF_GINST, p, &p);
2377 encode_klass_ref (acfg, gclass, p, &p);
2378 encode_ginst (acfg, inst, p, &p);
2382 } else if (klass->type_token) {
2383 int iindex = get_image_index (acfg, klass->image);
2385 g_assert (mono_metadata_token_code (klass->type_token) == MONO_TOKEN_TYPE_DEF);
2387 encode_value (MONO_AOT_TYPEREF_TYPEDEF_INDEX, p, &p);
2388 encode_value (klass->type_token - MONO_TOKEN_TYPE_DEF, p, &p);
2390 encode_value (MONO_AOT_TYPEREF_TYPEDEF_INDEX_IMAGE, p, &p);
2391 encode_value (klass->type_token - MONO_TOKEN_TYPE_DEF, p, &p);
2392 encode_value (get_image_index (acfg, klass->image), p, &p);
2394 } else if ((klass->byval_arg.type == MONO_TYPE_VAR) || (klass->byval_arg.type == MONO_TYPE_MVAR)) {
2395 MonoGenericContainer *container = mono_type_get_generic_param_owner (&klass->byval_arg);
2396 MonoGenericParam *par = klass->byval_arg.data.generic_param;
2398 encode_value (MONO_AOT_TYPEREF_VAR, p, &p);
2399 encode_value (klass->byval_arg.type, p, &p);
2400 encode_value (mono_type_get_generic_param_num (&klass->byval_arg), p, &p);
2402 encode_value (container ? 1 : 0, p, &p);
2404 encode_value (container->is_method, p, &p);
2405 g_assert (par->serial == 0);
2406 if (container->is_method)
2407 encode_method_ref (acfg, container->owner.method, p, &p);
2409 encode_klass_ref (acfg, container->owner.klass, p, &p);
2411 encode_value (par->serial, p, &p);
2413 } else if (klass->byval_arg.type == MONO_TYPE_PTR) {
2414 encode_value (MONO_AOT_TYPEREF_PTR, p, &p);
2415 encode_type (acfg, &klass->byval_arg, p, &p);
2418 g_assert (klass->rank > 0);
2419 encode_value (MONO_AOT_TYPEREF_ARRAY, p, &p);
2420 encode_value (klass->rank, p, &p);
2421 encode_klass_ref (acfg, klass->element_class, p, &p);
2429 * Encode a reference to KLASS. We use our home-grown encoding instead of the
2430 * standard metadata encoding.
2433 encode_klass_ref (MonoAotCompile *acfg, MonoClass *klass, guint8 *buf, guint8 **endbuf)
2435 gboolean shared = FALSE;
2438 * The encoding of generic instances is large so emit them only once.
2440 if (klass->generic_class) {
2442 g_assert (klass->type_token);
2444 /* Find a typespec for a class if possible */
2445 token = find_typespec_for_class (acfg, klass);
2448 } else if ((klass->byval_arg.type == MONO_TYPE_VAR) || (klass->byval_arg.type == MONO_TYPE_MVAR)) {
2453 guint offset = GPOINTER_TO_UINT (g_hash_table_lookup (acfg->klass_blob_hash, klass));
2457 buf2 = g_malloc (1024);
2460 encode_klass_ref_inner (acfg, klass, p, &p);
2461 g_assert (p - buf2 < 1024);
2463 offset = add_to_blob (acfg, buf2, p - buf2);
2466 g_hash_table_insert (acfg->klass_blob_hash, klass, GUINT_TO_POINTER (offset + 1));
2472 encode_value (MONO_AOT_TYPEREF_BLOB_INDEX, p, &p);
2473 encode_value (offset, p, &p);
2478 encode_klass_ref_inner (acfg, klass, buf, endbuf);
2482 encode_field_info (MonoAotCompile *cfg, MonoClassField *field, guint8 *buf, guint8 **endbuf)
2484 guint32 token = mono_get_field_token (field);
2487 encode_klass_ref (cfg, field->parent, p, &p);
2488 g_assert (mono_metadata_token_code (token) == MONO_TOKEN_FIELD_DEF);
2489 encode_value (token - MONO_TOKEN_FIELD_DEF, p, &p);
2494 encode_ginst (MonoAotCompile *acfg, MonoGenericInst *inst, guint8 *buf, guint8 **endbuf)
2499 encode_value (inst->type_argc, p, &p);
2500 for (i = 0; i < inst->type_argc; ++i)
2501 encode_klass_ref (acfg, mono_class_from_mono_type (inst->type_argv [i]), p, &p);
2506 encode_generic_context (MonoAotCompile *acfg, MonoGenericContext *context, guint8 *buf, guint8 **endbuf)
2509 MonoGenericInst *inst;
2511 inst = context->class_inst;
2513 g_assert (inst->type_argc);
2514 encode_ginst (acfg, inst, p, &p);
2516 encode_value (0, p, &p);
2518 inst = context->method_inst;
2520 g_assert (inst->type_argc);
2521 encode_ginst (acfg, inst, p, &p);
2523 encode_value (0, p, &p);
2529 encode_type (MonoAotCompile *acfg, MonoType *t, guint8 *buf, guint8 **endbuf)
2533 g_assert (t->num_mods == 0);
2534 /* t->attrs can be ignored */
2535 //g_assert (t->attrs == 0);
2538 *p = MONO_TYPE_PINNED;
2542 *p = MONO_TYPE_BYREF;
2550 case MONO_TYPE_VOID:
2551 case MONO_TYPE_BOOLEAN:
2552 case MONO_TYPE_CHAR:
2565 case MONO_TYPE_STRING:
2566 case MONO_TYPE_OBJECT:
2567 case MONO_TYPE_TYPEDBYREF:
2569 case MONO_TYPE_VALUETYPE:
2570 case MONO_TYPE_CLASS:
2571 encode_klass_ref (acfg, mono_class_from_mono_type (t), p, &p);
2573 case MONO_TYPE_SZARRAY:
2574 encode_klass_ref (acfg, t->data.klass, p, &p);
2577 encode_type (acfg, t->data.type, p, &p);
2579 case MONO_TYPE_GENERICINST: {
2580 MonoClass *gclass = t->data.generic_class->container_class;
2581 MonoGenericInst *inst = t->data.generic_class->context.class_inst;
2583 encode_klass_ref (acfg, gclass, p, &p);
2584 encode_ginst (acfg, inst, p, &p);
2587 case MONO_TYPE_ARRAY: {
2588 MonoArrayType *array = t->data.array;
2591 encode_klass_ref (acfg, array->eklass, p, &p);
2592 encode_value (array->rank, p, &p);
2593 encode_value (array->numsizes, p, &p);
2594 for (i = 0; i < array->numsizes; ++i)
2595 encode_value (array->sizes [i], p, &p);
2596 encode_value (array->numlobounds, p, &p);
2597 for (i = 0; i < array->numlobounds; ++i)
2598 encode_value (array->lobounds [i], p, &p);
2602 case MONO_TYPE_MVAR:
2603 encode_klass_ref (acfg, mono_class_from_mono_type (t), p, &p);
2606 g_assert_not_reached ();
2613 encode_signature (MonoAotCompile *acfg, MonoMethodSignature *sig, guint8 *buf, guint8 **endbuf)
2619 /* Similar to the metadata encoding */
2620 if (sig->generic_param_count)
2624 if (sig->explicit_this)
2626 flags |= (sig->call_convention & 0x0F);
2630 if (sig->generic_param_count)
2631 encode_value (sig->generic_param_count, p, &p);
2632 encode_value (sig->param_count, p, &p);
2634 encode_type (acfg, sig->ret, p, &p);
2635 for (i = 0; i < sig->param_count; ++i) {
2636 if (sig->sentinelpos == i) {
2637 *p = MONO_TYPE_SENTINEL;
2640 encode_type (acfg, sig->params [i], p, &p);
2646 #define MAX_IMAGE_INDEX 250
2649 encode_method_ref (MonoAotCompile *acfg, MonoMethod *method, guint8 *buf, guint8 **endbuf)
2651 guint32 image_index = get_image_index (acfg, method->klass->image);
2652 guint32 token = method->token;
2653 MonoJumpInfoToken *ji;
2657 * The encoding for most methods is as follows:
2658 * - image index encoded as a leb128
2659 * - token index encoded as a leb128
2660 * Values of image index >= MONO_AOT_METHODREF_MIN are used to mark additional
2661 * types of method encodings.
2664 /* Mark methods which can't use aot trampolines because they need the further
2665 * processing in mono_magic_trampoline () which requires a MonoMethod*.
2667 if ((method->is_generic && (method->flags & METHOD_ATTRIBUTE_VIRTUAL)) ||
2668 (method->iflags & METHOD_IMPL_ATTRIBUTE_SYNCHRONIZED))
2669 encode_value ((MONO_AOT_METHODREF_NO_AOT_TRAMPOLINE << 24), p, &p);
2671 if (method->wrapper_type) {
2672 encode_value ((MONO_AOT_METHODREF_WRAPPER << 24), p, &p);
2674 encode_value (method->wrapper_type, p, &p);
2676 switch (method->wrapper_type) {
2677 case MONO_WRAPPER_REMOTING_INVOKE:
2678 case MONO_WRAPPER_REMOTING_INVOKE_WITH_CHECK:
2679 case MONO_WRAPPER_XDOMAIN_INVOKE: {
2682 m = mono_marshal_method_from_wrapper (method);
2684 encode_method_ref (acfg, m, p, &p);
2687 case MONO_WRAPPER_PROXY_ISINST:
2688 case MONO_WRAPPER_LDFLD:
2689 case MONO_WRAPPER_LDFLDA:
2690 case MONO_WRAPPER_STFLD:
2691 case MONO_WRAPPER_ISINST: {
2692 WrapperInfo *info = mono_marshal_get_wrapper_info (method);
2695 encode_klass_ref (acfg, info->d.proxy.klass, p, &p);
2698 case MONO_WRAPPER_LDFLD_REMOTE:
2699 case MONO_WRAPPER_STFLD_REMOTE:
2701 case MONO_WRAPPER_ALLOC: {
2702 AllocatorWrapperInfo *info = mono_marshal_get_wrapper_info (method);
2704 /* The GC name is saved once in MonoAotFileInfo */
2705 g_assert (info->alloc_type != -1);
2706 encode_value (info->alloc_type, p, &p);
2709 case MONO_WRAPPER_WRITE_BARRIER:
2711 case MONO_WRAPPER_STELEMREF: {
2712 WrapperInfo *info = mono_marshal_get_wrapper_info (method);
2715 encode_value (info->subtype, p, &p);
2716 if (info->subtype == WRAPPER_SUBTYPE_VIRTUAL_STELEMREF)
2717 encode_value (info->d.virtual_stelemref.kind, p, &p);
2720 case MONO_WRAPPER_UNKNOWN: {
2721 WrapperInfo *info = mono_marshal_get_wrapper_info (method);
2724 encode_value (info->subtype, p, &p);
2725 if (info->subtype == WRAPPER_SUBTYPE_PTR_TO_STRUCTURE ||
2726 info->subtype == WRAPPER_SUBTYPE_STRUCTURE_TO_PTR)
2727 encode_klass_ref (acfg, method->klass, p, &p);
2728 else if (info->subtype == WRAPPER_SUBTYPE_SYNCHRONIZED_INNER)
2729 encode_method_ref (acfg, info->d.synchronized_inner.method, p, &p);
2730 else if (info->subtype == WRAPPER_SUBTYPE_ARRAY_ACCESSOR)
2731 encode_method_ref (acfg, info->d.array_accessor.method, p, &p);
2734 case MONO_WRAPPER_MANAGED_TO_NATIVE: {
2735 WrapperInfo *info = mono_marshal_get_wrapper_info (method);
2738 encode_value (info->subtype, p, &p);
2739 if (info->subtype == WRAPPER_SUBTYPE_ICALL_WRAPPER) {
2740 strcpy ((char*)p, method->name);
2741 p += strlen (method->name) + 1;
2742 } else if (info->subtype == WRAPPER_SUBTYPE_NATIVE_FUNC_AOT) {
2743 encode_method_ref (acfg, info->d.managed_to_native.method, p, &p);
2745 g_assert (info->subtype == WRAPPER_SUBTYPE_NONE || info->subtype == WRAPPER_SUBTYPE_PINVOKE);
2746 encode_method_ref (acfg, info->d.managed_to_native.method, p, &p);
2750 case MONO_WRAPPER_SYNCHRONIZED: {
2753 m = mono_marshal_method_from_wrapper (method);
2755 g_assert (m != method);
2756 encode_method_ref (acfg, m, p, &p);
2759 case MONO_WRAPPER_MANAGED_TO_MANAGED: {
2760 WrapperInfo *info = mono_marshal_get_wrapper_info (method);
2763 encode_value (info->subtype, p, &p);
2765 if (info->subtype == WRAPPER_SUBTYPE_ELEMENT_ADDR) {
2766 encode_value (info->d.element_addr.rank, p, &p);
2767 encode_value (info->d.element_addr.elem_size, p, &p);
2768 } else if (info->subtype == WRAPPER_SUBTYPE_STRING_CTOR) {
2769 encode_method_ref (acfg, info->d.string_ctor.method, p, &p);
2771 g_assert_not_reached ();
2775 case MONO_WRAPPER_CASTCLASS: {
2776 WrapperInfo *info = mono_marshal_get_wrapper_info (method);
2779 encode_value (info->subtype, p, &p);
2782 case MONO_WRAPPER_RUNTIME_INVOKE: {
2783 WrapperInfo *info = mono_marshal_get_wrapper_info (method);
2786 encode_value (info->subtype, p, &p);
2787 if (info->subtype == WRAPPER_SUBTYPE_RUNTIME_INVOKE_DIRECT || info->subtype == WRAPPER_SUBTYPE_RUNTIME_INVOKE_VIRTUAL)
2788 encode_method_ref (acfg, info->d.runtime_invoke.method, p, &p);
2789 else if (info->subtype == WRAPPER_SUBTYPE_RUNTIME_INVOKE_NORMAL)
2790 encode_signature (acfg, info->d.runtime_invoke.sig, p, &p);
2793 case MONO_WRAPPER_DELEGATE_INVOKE:
2794 case MONO_WRAPPER_DELEGATE_BEGIN_INVOKE:
2795 case MONO_WRAPPER_DELEGATE_END_INVOKE: {
2796 if (method->is_inflated) {
2797 /* These wrappers are identified by their class */
2798 encode_value (1, p, &p);
2799 encode_klass_ref (acfg, method->klass, p, &p);
2801 MonoMethodSignature *sig = mono_method_signature (method);
2802 WrapperInfo *info = mono_marshal_get_wrapper_info (method);
2804 encode_value (0, p, &p);
2805 if (method->wrapper_type == MONO_WRAPPER_DELEGATE_INVOKE)
2806 encode_value (info ? info->subtype : 0, p, &p);
2807 encode_signature (acfg, sig, p, &p);
2811 case MONO_WRAPPER_NATIVE_TO_MANAGED: {
2812 WrapperInfo *info = mono_marshal_get_wrapper_info (method);
2815 encode_method_ref (acfg, info->d.native_to_managed.method, p, &p);
2816 encode_klass_ref (acfg, info->d.native_to_managed.klass, p, &p);
2820 g_assert_not_reached ();
2822 } else if (mono_method_signature (method)->is_inflated) {
2824 * This is a generic method, find the original token which referenced it and
2826 * Obtain the token from information recorded by the JIT.
2828 ji = g_hash_table_lookup (acfg->token_info_hash, method);
2830 image_index = get_image_index (acfg, ji->image);
2831 g_assert (image_index < MAX_IMAGE_INDEX);
2834 encode_value ((MONO_AOT_METHODREF_METHODSPEC << 24), p, &p);
2835 encode_value (image_index, p, &p);
2836 encode_value (token, p, &p);
2838 MonoMethod *declaring;
2839 MonoGenericContext *context = mono_method_get_context (method);
2841 g_assert (method->is_inflated);
2842 declaring = ((MonoMethodInflated*)method)->declaring;
2845 * This might be a non-generic method of a generic instance, which
2846 * doesn't have a token since the reference is generated by the JIT
2847 * like Nullable:Box/Unbox, or by generic sharing.
2849 encode_value ((MONO_AOT_METHODREF_GINST << 24), p, &p);
2850 /* Encode the klass */
2851 encode_klass_ref (acfg, method->klass, p, &p);
2852 /* Encode the method */
2853 image_index = get_image_index (acfg, method->klass->image);
2854 g_assert (image_index < MAX_IMAGE_INDEX);
2855 g_assert (declaring->token);
2856 token = declaring->token;
2857 g_assert (mono_metadata_token_table (token) == MONO_TABLE_METHOD);
2858 encode_value (image_index, p, &p);
2859 encode_value (token, p, &p);
2860 encode_generic_context (acfg, context, p, &p);
2862 } else if (token == 0) {
2863 /* This might be a method of a constructed type like int[,].Set */
2864 /* Obtain the token from information recorded by the JIT */
2865 ji = g_hash_table_lookup (acfg->token_info_hash, method);
2867 image_index = get_image_index (acfg, ji->image);
2868 g_assert (image_index < MAX_IMAGE_INDEX);
2871 encode_value ((MONO_AOT_METHODREF_METHODSPEC << 24), p, &p);
2872 encode_value (image_index, p, &p);
2873 encode_value (token, p, &p);
2876 g_assert (method->klass->rank);
2878 /* Encode directly */
2879 encode_value ((MONO_AOT_METHODREF_ARRAY << 24), p, &p);
2880 encode_klass_ref (acfg, method->klass, p, &p);
2881 if (!strcmp (method->name, ".ctor") && mono_method_signature (method)->param_count == method->klass->rank)
2882 encode_value (0, p, &p);
2883 else if (!strcmp (method->name, ".ctor") && mono_method_signature (method)->param_count == method->klass->rank * 2)
2884 encode_value (1, p, &p);
2885 else if (!strcmp (method->name, "Get"))
2886 encode_value (2, p, &p);
2887 else if (!strcmp (method->name, "Address"))
2888 encode_value (3, p, &p);
2889 else if (!strcmp (method->name, "Set"))
2890 encode_value (4, p, &p);
2892 g_assert_not_reached ();
2895 g_assert (mono_metadata_token_table (token) == MONO_TABLE_METHOD);
2897 if (image_index >= MONO_AOT_METHODREF_MIN) {
2898 encode_value ((MONO_AOT_METHODREF_LARGE_IMAGE_INDEX << 24), p, &p);
2899 encode_value (image_index, p, &p);
2900 encode_value (mono_metadata_token_index (token), p, &p);
2902 encode_value ((image_index << 24) | mono_metadata_token_index (token), p, &p);
2909 compare_patches (gconstpointer a, gconstpointer b)
2913 i = (*(MonoJumpInfo**)a)->ip.i;
2914 j = (*(MonoJumpInfo**)b)->ip.i;
2925 static G_GNUC_UNUSED char*
2926 patch_to_string (MonoJumpInfo *patch_info)
2930 str = g_string_new ("");
2932 g_string_append_printf (str, "%s(", get_patch_name (patch_info->type));
2934 switch (patch_info->type) {
2935 case MONO_PATCH_INFO_VTABLE:
2936 mono_type_get_desc (str, &patch_info->data.klass->byval_arg, TRUE);
2941 g_string_append_printf (str, ")");
2942 return g_string_free (str, FALSE);
2948 * Return whenever PATCH_INFO refers to a direct call, and thus requires a
2951 static inline gboolean
2952 is_plt_patch (MonoJumpInfo *patch_info)
2954 switch (patch_info->type) {
2955 case MONO_PATCH_INFO_METHOD:
2956 case MONO_PATCH_INFO_INTERNAL_METHOD:
2957 case MONO_PATCH_INFO_JIT_ICALL_ADDR:
2958 case MONO_PATCH_INFO_ICALL_ADDR:
2959 case MONO_PATCH_INFO_CLASS_INIT:
2960 case MONO_PATCH_INFO_RGCTX_FETCH:
2961 case MONO_PATCH_INFO_GENERIC_CLASS_INIT:
2962 case MONO_PATCH_INFO_MONITOR_ENTER:
2963 case MONO_PATCH_INFO_MONITOR_EXIT:
2964 case MONO_PATCH_INFO_LLVM_IMT_TRAMPOLINE:
2974 * Return the symbol identifying the plt entry PLT_OFFSET.
2977 get_plt_symbol (MonoAotCompile *acfg, int plt_offset, MonoJumpInfo *patch_info)
2981 * The Apple linker reorganizes object files, so it doesn't like branches to local
2982 * labels, since those have no relocations.
2984 return g_strdup_printf ("%sp_%d", acfg->llvm_label_prefix, plt_offset);
2986 return g_strdup_printf ("%sp_%d", acfg->temp_prefix, plt_offset);
2993 * Return a PLT entry which belongs to the method identified by PATCH_INFO.
2995 static MonoPltEntry*
2996 get_plt_entry (MonoAotCompile *acfg, MonoJumpInfo *patch_info)
3000 if (!is_plt_patch (patch_info))
3003 if (!acfg->patch_to_plt_entry [patch_info->type])
3004 acfg->patch_to_plt_entry [patch_info->type] = g_hash_table_new (mono_patch_info_hash, mono_patch_info_equal);
3005 res = g_hash_table_lookup (acfg->patch_to_plt_entry [patch_info->type], patch_info);
3007 // FIXME: This breaks the calculation of final_got_size
3008 if (!acfg->llvm && patch_info->type == MONO_PATCH_INFO_METHOD && (patch_info->data.method->iflags & METHOD_IMPL_ATTRIBUTE_SYNCHRONIZED)) {
3010 * Allocate a separate PLT slot for each such patch, since some plt
3011 * entries will refer to the method itself, and some will refer to the
3018 MonoJumpInfo *new_ji;
3020 g_assert (!acfg->final_got_size);
3022 new_ji = mono_patch_info_dup_mp (acfg->mempool, patch_info);
3024 res = mono_mempool_alloc0 (acfg->mempool, sizeof (MonoPltEntry));
3025 res->plt_offset = acfg->plt_offset;
3027 res->symbol = get_plt_symbol (acfg, res->plt_offset, patch_info);
3028 if (acfg->aot_opts.write_symbols)
3029 res->debug_sym = get_plt_entry_debug_sym (acfg, res->ji, acfg->plt_entry_debug_sym_cache);
3031 res->llvm_symbol = g_strdup_printf ("%s_%s_llvm", res->symbol, res->debug_sym);
3033 res->llvm_symbol = g_strdup_printf ("%s_llvm", res->symbol);
3035 g_hash_table_insert (acfg->patch_to_plt_entry [new_ji->type], new_ji, res);
3037 g_hash_table_insert (acfg->plt_offset_to_entry, GUINT_TO_POINTER (res->plt_offset), res);
3039 //g_assert (mono_patch_info_equal (patch_info, new_ji));
3040 //mono_print_ji (patch_info); printf ("\n");
3041 //g_hash_table_print_stats (acfg->patch_to_plt_entry);
3043 acfg->plt_offset ++;
3052 * Returns the offset of the GOT slot where the runtime object resulting from resolving
3053 * JI could be found if it exists, otherwise allocates a new one.
3056 get_got_offset (MonoAotCompile *acfg, MonoJumpInfo *ji)
3060 got_offset = GPOINTER_TO_UINT (g_hash_table_lookup (acfg->patch_to_got_offset_by_type [ji->type], ji));
3062 return got_offset - 1;
3064 got_offset = acfg->got_offset;
3065 acfg->got_offset ++;
3067 if (acfg->final_got_size)
3068 g_assert (got_offset < acfg->final_got_size);
3070 acfg->stats.got_slots ++;
3071 acfg->stats.got_slot_types [ji->type] ++;
3073 g_hash_table_insert (acfg->patch_to_got_offset, ji, GUINT_TO_POINTER (got_offset + 1));
3074 g_hash_table_insert (acfg->patch_to_got_offset_by_type [ji->type], ji, GUINT_TO_POINTER (got_offset + 1));
3075 g_ptr_array_add (acfg->got_patches, ji);
3080 /* Add a method to the list of methods which need to be emitted */
3082 add_method_with_index (MonoAotCompile *acfg, MonoMethod *method, int index, gboolean extra)
3085 if (!g_hash_table_lookup (acfg->method_indexes, method)) {
3086 g_ptr_array_add (acfg->methods, method);
3087 g_hash_table_insert (acfg->method_indexes, method, GUINT_TO_POINTER (index + 1));
3088 acfg->nmethods = acfg->methods->len + 1;
3091 if (method->wrapper_type || extra)
3092 g_ptr_array_add (acfg->extra_methods, method);
3096 get_method_index (MonoAotCompile *acfg, MonoMethod *method)
3098 int index = GPOINTER_TO_UINT (g_hash_table_lookup (acfg->method_indexes, method));
3106 add_method_full (MonoAotCompile *acfg, MonoMethod *method, gboolean extra, int depth)
3110 index = GPOINTER_TO_UINT (g_hash_table_lookup (acfg->method_indexes, method));
3114 index = acfg->method_index;
3115 add_method_with_index (acfg, method, index, extra);
3117 g_ptr_array_add (acfg->method_order, GUINT_TO_POINTER (index));
3119 g_hash_table_insert (acfg->method_depth, method, GUINT_TO_POINTER (depth));
3121 acfg->method_index ++;
3127 add_method (MonoAotCompile *acfg, MonoMethod *method)
3129 return add_method_full (acfg, method, FALSE, 0);
3133 add_extra_method_with_depth (MonoAotCompile *acfg, MonoMethod *method, int depth)
3135 if (mono_method_is_generic_sharable_full (method, FALSE, TRUE, FALSE))
3136 method = mini_get_shared_method (method);
3138 if (acfg->aot_opts.log_generics)
3139 aot_printf (acfg, "%*sAdding method %s.\n", depth, "", mono_method_full_name (method, TRUE));
3141 add_method_full (acfg, method, TRUE, depth);
3145 add_extra_method (MonoAotCompile *acfg, MonoMethod *method)
3147 add_extra_method_with_depth (acfg, method, 0);
3151 add_jit_icall_wrapper (gpointer key, gpointer value, gpointer user_data)
3153 MonoAotCompile *acfg = user_data;
3154 MonoJitICallInfo *callinfo = value;
3155 MonoMethod *wrapper;
3161 name = g_strdup_printf ("__icall_wrapper_%s", callinfo->name);
3162 wrapper = mono_marshal_get_icall_wrapper (callinfo->sig, name, callinfo->func, check_for_pending_exc);
3165 add_method (acfg, wrapper);
3169 get_runtime_invoke_sig (MonoMethodSignature *sig)
3171 MonoMethodBuilder *mb;
3174 mb = mono_mb_new (mono_defaults.object_class, "FOO", MONO_WRAPPER_NONE);
3175 m = mono_mb_create_method (mb, sig, 16);
3176 return mono_marshal_get_runtime_invoke (m, FALSE);
3180 can_marshal_struct (MonoClass *klass)
3182 MonoClassField *field;
3183 gboolean can_marshal = TRUE;
3184 gpointer iter = NULL;
3185 MonoMarshalType *info;
3188 if ((klass->flags & TYPE_ATTRIBUTE_LAYOUT_MASK) == TYPE_ATTRIBUTE_AUTO_LAYOUT)
3191 info = mono_marshal_load_type_info (klass);
3193 /* Only allow a few field types to avoid asserts in the marshalling code */
3194 while ((field = mono_class_get_fields (klass, &iter))) {
3195 if ((field->type->attrs & FIELD_ATTRIBUTE_STATIC))
3198 switch (field->type->type) {
3203 case MONO_TYPE_BOOLEAN:
3206 case MONO_TYPE_CHAR:
3214 case MONO_TYPE_STRING:
3216 case MONO_TYPE_VALUETYPE:
3217 if (!mono_class_from_mono_type (field->type)->enumtype && !can_marshal_struct (mono_class_from_mono_type (field->type)))
3218 can_marshal = FALSE;
3220 case MONO_TYPE_SZARRAY: {
3221 gboolean has_mspec = FALSE;
3224 for (i = 0; i < info->num_fields; ++i) {
3225 if (info->fields [i].field == field && info->fields [i].mspec)
3230 can_marshal = FALSE;
3234 can_marshal = FALSE;
3240 /* Its hard to compute whenever these can be marshalled or not */
3241 if (!strcmp (klass->name_space, "System.Net.NetworkInformation.MacOsStructs") && strcmp (klass->name, "sockaddr_dl"))
3248 create_gsharedvt_inst (MonoAotCompile *acfg, MonoMethod *method, MonoGenericContext *ctx)
3250 /* Create a vtype instantiation */
3251 MonoGenericContext shared_context;
3253 MonoGenericInst *inst;
3254 MonoGenericContainer *container;
3255 MonoClass **constraints;
3258 memset (ctx, 0, sizeof (MonoGenericContext));
3260 if (method->klass->generic_container) {
3261 shared_context = method->klass->generic_container->context;
3262 inst = shared_context.class_inst;
3264 args = g_new0 (MonoType*, inst->type_argc);
3265 for (i = 0; i < inst->type_argc; ++i) {
3266 args [i] = &mono_defaults.int_class->byval_arg;
3268 ctx->class_inst = mono_metadata_get_generic_inst (inst->type_argc, args);
3270 if (method->is_generic) {
3271 container = mono_method_get_generic_container (method);
3272 shared_context = container->context;
3273 inst = shared_context.method_inst;
3275 args = g_new0 (MonoType*, inst->type_argc);
3276 for (i = 0; i < container->type_argc; ++i) {
3277 MonoGenericParamInfo *info = &container->type_params [i].info;
3278 gboolean ref_only = FALSE;
3280 if (info && info->constraints) {
3281 constraints = info->constraints;
3283 while (*constraints) {
3284 MonoClass *cklass = *constraints;
3285 if (!(cklass == mono_defaults.object_class || (cklass->image == mono_defaults.corlib && !strcmp (cklass->name, "ValueType"))))
3286 /* Inflaring the method with our vtype would not be valid */
3293 args [i] = &mono_defaults.object_class->byval_arg;
3295 args [i] = &mono_defaults.int_class->byval_arg;
3297 ctx->method_inst = mono_metadata_get_generic_inst (inst->type_argc, args);
3302 add_wrappers (MonoAotCompile *acfg)
3304 MonoMethod *method, *m;
3306 MonoMethodSignature *sig, *csig;
3310 * FIXME: Instead of AOTing all the wrappers, it might be better to redesign them
3311 * so there is only one wrapper of a given type, or inlining their contents into their
3314 for (i = 0; i < acfg->image->tables [MONO_TABLE_METHOD].rows; ++i) {
3316 guint32 token = MONO_TOKEN_METHOD_DEF | (i + 1);
3317 gboolean skip = FALSE;
3319 method = mono_get_method (acfg->image, token, NULL);
3321 if ((method->flags & METHOD_ATTRIBUTE_PINVOKE_IMPL) ||
3322 (method->iflags & METHOD_IMPL_ATTRIBUTE_RUNTIME) ||
3323 (method->flags & METHOD_ATTRIBUTE_ABSTRACT))
3326 /* Skip methods which can not be handled by get_runtime_invoke () */
3327 sig = mono_method_signature (method);
3330 if ((sig->ret->type == MONO_TYPE_PTR) ||
3331 (sig->ret->type == MONO_TYPE_TYPEDBYREF))
3333 if (mono_class_is_open_constructed_type (sig->ret))
3336 for (j = 0; j < sig->param_count; j++) {
3337 if (sig->params [j]->type == MONO_TYPE_TYPEDBYREF)
3339 if (mono_class_is_open_constructed_type (sig->params [j]))
3343 #ifdef MONO_ARCH_DYN_CALL_SUPPORTED
3344 if (!mono_class_is_contextbound (method->klass)) {
3345 MonoDynCallInfo *info = mono_arch_dyn_call_prepare (sig);
3346 gboolean has_nullable = FALSE;
3348 for (j = 0; j < sig->param_count; j++) {
3349 if (sig->params [j]->type == MONO_TYPE_GENERICINST && mono_class_is_nullable (mono_class_from_mono_type (sig->params [j])))
3350 has_nullable = TRUE;
3353 if (info && !has_nullable) {
3354 /* Supported by the dynamic runtime-invoke wrapper */
3358 mono_arch_dyn_call_free (info);
3363 //printf ("%s\n", mono_method_full_name (method, TRUE));
3364 add_method (acfg, mono_marshal_get_runtime_invoke (method, FALSE));
3368 if (strcmp (acfg->image->assembly->aname.name, "mscorlib") == 0) {
3369 MonoMethodDesc *desc;
3370 MonoMethod *orig_method;
3373 /* Runtime invoke wrappers */
3375 /* void runtime-invoke () [.cctor] */
3376 csig = mono_metadata_signature_alloc (mono_defaults.corlib, 0);
3377 csig->ret = &mono_defaults.void_class->byval_arg;
3378 add_method (acfg, get_runtime_invoke_sig (csig));
3380 /* void runtime-invoke () [Finalize] */
3381 csig = mono_metadata_signature_alloc (mono_defaults.corlib, 0);
3383 csig->ret = &mono_defaults.void_class->byval_arg;
3384 add_method (acfg, get_runtime_invoke_sig (csig));
3386 /* void runtime-invoke (string) [exception ctor] */
3387 csig = mono_metadata_signature_alloc (mono_defaults.corlib, 1);
3389 csig->ret = &mono_defaults.void_class->byval_arg;
3390 csig->params [0] = &mono_defaults.string_class->byval_arg;
3391 add_method (acfg, get_runtime_invoke_sig (csig));
3393 /* void runtime-invoke (string, string) [exception ctor] */
3394 csig = mono_metadata_signature_alloc (mono_defaults.corlib, 2);
3396 csig->ret = &mono_defaults.void_class->byval_arg;
3397 csig->params [0] = &mono_defaults.string_class->byval_arg;
3398 csig->params [1] = &mono_defaults.string_class->byval_arg;
3399 add_method (acfg, get_runtime_invoke_sig (csig));
3401 /* string runtime-invoke () [Exception.ToString ()] */
3402 csig = mono_metadata_signature_alloc (mono_defaults.corlib, 0);
3404 csig->ret = &mono_defaults.string_class->byval_arg;
3405 add_method (acfg, get_runtime_invoke_sig (csig));
3407 /* void runtime-invoke (string, Exception) [exception ctor] */
3408 csig = mono_metadata_signature_alloc (mono_defaults.corlib, 2);
3410 csig->ret = &mono_defaults.void_class->byval_arg;
3411 csig->params [0] = &mono_defaults.string_class->byval_arg;
3412 csig->params [1] = &mono_defaults.exception_class->byval_arg;
3413 add_method (acfg, get_runtime_invoke_sig (csig));
3415 /* Assembly runtime-invoke (string, bool) [DoAssemblyResolve] */
3416 csig = mono_metadata_signature_alloc (mono_defaults.corlib, 2);
3418 csig->ret = &(mono_class_from_name (
3419 mono_defaults.corlib, "System.Reflection", "Assembly"))->byval_arg;
3420 csig->params [0] = &mono_defaults.string_class->byval_arg;
3421 csig->params [1] = &mono_defaults.boolean_class->byval_arg;
3422 add_method (acfg, get_runtime_invoke_sig (csig));
3424 /* runtime-invoke used by finalizers */
3425 add_method (acfg, mono_marshal_get_runtime_invoke (mono_class_get_method_from_name_flags (mono_defaults.object_class, "Finalize", 0, 0), TRUE));
3427 /* This is used by mono_runtime_capture_context () */
3428 method = mono_get_context_capture_method ();
3430 add_method (acfg, mono_marshal_get_runtime_invoke (method, FALSE));
3432 #ifdef MONO_ARCH_DYN_CALL_SUPPORTED
3433 add_method (acfg, mono_marshal_get_runtime_invoke_dynamic ());
3437 add_method (acfg, mono_marshal_get_stelemref ());
3439 if (MONO_ARCH_HAVE_TLS_GET) {
3440 /* Managed Allocators */
3441 nallocators = mono_gc_get_managed_allocator_types ();
3442 for (i = 0; i < nallocators; ++i) {
3443 m = mono_gc_get_managed_allocator_by_type (i);
3445 add_method (acfg, m);
3448 /* Monitor Enter/Exit */
3449 desc = mono_method_desc_new ("Monitor:Enter(object,bool&)", FALSE);
3450 orig_method = mono_method_desc_search_in_class (desc, mono_defaults.monitor_class);
3451 /* This is a v4 method */
3453 method = mono_monitor_get_fast_path (orig_method);
3455 add_method (acfg, method);
3457 mono_method_desc_free (desc);
3459 desc = mono_method_desc_new ("Monitor:Exit(object)", FALSE);
3460 orig_method = mono_method_desc_search_in_class (desc, mono_defaults.monitor_class);
3461 g_assert (orig_method);
3462 mono_method_desc_free (desc);
3463 method = mono_monitor_get_fast_path (orig_method);
3465 add_method (acfg, method);
3468 /* Stelemref wrappers */
3470 MonoMethod **wrappers;
3473 wrappers = mono_marshal_get_virtual_stelemref_wrappers (&nwrappers);
3474 for (i = 0; i < nwrappers; ++i)
3475 add_method (acfg, wrappers [i]);
3479 /* castclass_with_check wrapper */
3480 add_method (acfg, mono_marshal_get_castclass_with_cache ());
3481 /* isinst_with_check wrapper */
3482 add_method (acfg, mono_marshal_get_isinst_with_cache ());
3484 #if defined(MONO_ARCH_ENABLE_MONITOR_IL_FASTPATH)
3486 MonoMethodDesc *desc;
3489 desc = mono_method_desc_new ("Monitor:Enter(object,bool&)", FALSE);
3490 m = mono_method_desc_search_in_class (desc, mono_defaults.monitor_class);
3491 mono_method_desc_free (desc);
3493 m = mono_monitor_get_fast_path (m);
3495 add_method (acfg, m);
3500 /* JIT icall wrappers */
3501 /* FIXME: locking - this is "safe" as full-AOT threads don't mutate the icall hash*/
3502 g_hash_table_foreach (mono_get_jit_icall_info (), add_jit_icall_wrapper, acfg);
3506 * remoting-invoke-with-check wrappers are very frequent, so avoid emitting them,
3507 * we use the original method instead at runtime.
3508 * Since full-aot doesn't support remoting, this is not a problem.
3511 /* remoting-invoke wrappers */
3512 for (i = 0; i < acfg->image->tables [MONO_TABLE_METHOD].rows; ++i) {
3513 MonoMethodSignature *sig;
3515 token = MONO_TOKEN_METHOD_DEF | (i + 1);
3516 method = mono_get_method (acfg->image, token, NULL);
3518 sig = mono_method_signature (method);
3520 if (sig->hasthis && (method->klass->marshalbyref || method->klass == mono_defaults.object_class)) {
3521 m = mono_marshal_get_remoting_invoke_with_check (method);
3523 add_method (acfg, m);
3528 /* delegate-invoke wrappers */
3529 for (i = 0; i < acfg->image->tables [MONO_TABLE_TYPEDEF].rows; ++i) {
3532 MonoCustomAttrInfo *cattr;
3534 token = MONO_TOKEN_TYPE_DEF | (i + 1);
3535 klass = mono_class_get_checked (acfg->image, token, &error);
3538 mono_error_cleanup (&error);
3542 if (!klass->delegate || klass == mono_defaults.delegate_class || klass == mono_defaults.multicastdelegate_class)
3545 if (!klass->generic_container) {
3546 method = mono_get_delegate_invoke (klass);
3548 m = mono_marshal_get_delegate_invoke (method, NULL);
3550 add_method (acfg, m);
3552 method = mono_class_get_method_from_name_flags (klass, "BeginInvoke", -1, 0);
3554 add_method (acfg, mono_marshal_get_delegate_begin_invoke (method));
3556 method = mono_class_get_method_from_name_flags (klass, "EndInvoke", -1, 0);
3558 add_method (acfg, mono_marshal_get_delegate_end_invoke (method));
3560 cattr = mono_custom_attrs_from_class (klass);
3565 for (j = 0; j < cattr->num_attrs; ++j)
3566 if (cattr->attrs [j].ctor && (!strcmp (cattr->attrs [j].ctor->klass->name, "MonoNativeFunctionWrapperAttribute") || !strcmp (cattr->attrs [j].ctor->klass->name, "UnmanagedFunctionPointerAttribute")))
3568 if (j < cattr->num_attrs)
3569 add_method (acfg, mono_marshal_get_native_func_wrapper_aot (klass));
3571 } else if ((acfg->opts & MONO_OPT_GSHAREDVT) && klass->generic_container) {
3572 MonoGenericContext ctx;
3573 MonoMethod *inst, *gshared;
3576 * Emit gsharedvt versions of the generic delegate-invoke wrappers
3579 method = mono_get_delegate_invoke (klass);
3580 create_gsharedvt_inst (acfg, method, &ctx);
3582 inst = mono_class_inflate_generic_method (method, &ctx);
3584 m = mono_marshal_get_delegate_invoke (inst, NULL);
3585 g_assert (m->is_inflated);
3587 gshared = mini_get_shared_method_full (m, FALSE, TRUE);
3588 add_extra_method (acfg, gshared);
3591 method = mono_get_delegate_begin_invoke (klass);
3592 create_gsharedvt_inst (acfg, method, &ctx);
3594 inst = mono_class_inflate_generic_method (method, &ctx);
3596 m = mono_marshal_get_delegate_begin_invoke (inst);
3597 g_assert (m->is_inflated);
3599 gshared = mini_get_shared_method_full (m, FALSE, TRUE);
3600 add_extra_method (acfg, gshared);
3603 method = mono_get_delegate_end_invoke (klass);
3604 create_gsharedvt_inst (acfg, method, &ctx);
3606 inst = mono_class_inflate_generic_method (method, &ctx);
3608 m = mono_marshal_get_delegate_end_invoke (inst);
3609 g_assert (m->is_inflated);
3611 gshared = mini_get_shared_method_full (m, FALSE, TRUE);
3612 add_extra_method (acfg, gshared);
3617 /* array access wrappers */
3618 for (i = 0; i < acfg->image->tables [MONO_TABLE_TYPESPEC].rows; ++i) {
3622 token = MONO_TOKEN_TYPE_SPEC | (i + 1);
3623 klass = mono_class_get_checked (acfg->image, token, &error);
3626 mono_error_cleanup (&error);
3630 if (klass->rank && MONO_TYPE_IS_PRIMITIVE (&klass->element_class->byval_arg)) {
3631 MonoMethod *m, *wrapper;
3633 /* Add runtime-invoke wrappers too */
3635 m = mono_class_get_method_from_name (klass, "Get", -1);
3637 wrapper = mono_marshal_get_array_accessor_wrapper (m);
3638 add_extra_method (acfg, wrapper);
3639 add_extra_method (acfg, mono_marshal_get_runtime_invoke (wrapper, FALSE));
3641 m = mono_class_get_method_from_name (klass, "Set", -1);
3643 wrapper = mono_marshal_get_array_accessor_wrapper (m);
3644 add_extra_method (acfg, wrapper);
3645 add_extra_method (acfg, mono_marshal_get_runtime_invoke (wrapper, FALSE));
3649 /* Synchronized wrappers */
3650 for (i = 0; i < acfg->image->tables [MONO_TABLE_METHOD].rows; ++i) {
3651 token = MONO_TOKEN_METHOD_DEF | (i + 1);
3652 method = mono_get_method (acfg->image, token, NULL);
3654 if (method->iflags & METHOD_IMPL_ATTRIBUTE_SYNCHRONIZED) {
3655 if (method->is_generic) {
3657 } else if (method->klass->generic_container) {
3658 MonoGenericContext ctx;
3659 MonoMethod *inst, *gshared, *m;
3662 * Create a generic wrapper for a generic instance, and AOT that.
3664 create_gsharedvt_inst (acfg, method, &ctx);
3665 inst = mono_class_inflate_generic_method (method, &ctx);
3666 m = mono_marshal_get_synchronized_wrapper (inst);
3667 g_assert (m->is_inflated);
3668 gshared = mini_get_shared_method_full (m, FALSE, TRUE);
3669 add_method (acfg, gshared);
3671 add_method (acfg, mono_marshal_get_synchronized_wrapper (method));
3676 /* pinvoke wrappers */
3677 for (i = 0; i < acfg->image->tables [MONO_TABLE_METHOD].rows; ++i) {
3679 guint32 token = MONO_TOKEN_METHOD_DEF | (i + 1);
3681 method = mono_get_method (acfg->image, token, NULL);
3683 if ((method->flags & METHOD_ATTRIBUTE_PINVOKE_IMPL) ||
3684 (method->iflags & METHOD_IMPL_ATTRIBUTE_INTERNAL_CALL)) {
3685 add_method (acfg, mono_marshal_get_native_wrapper (method, TRUE, TRUE));
3689 /* native-to-managed wrappers */
3690 for (i = 0; i < acfg->image->tables [MONO_TABLE_METHOD].rows; ++i) {
3692 guint32 token = MONO_TOKEN_METHOD_DEF | (i + 1);
3693 MonoCustomAttrInfo *cattr;
3696 method = mono_get_method (acfg->image, token, NULL);
3699 * Only generate native-to-managed wrappers for methods which have an
3700 * attribute named MonoPInvokeCallbackAttribute. We search for the attribute by
3701 * name to avoid defining a new assembly to contain it.
3703 cattr = mono_custom_attrs_from_method (method);
3706 for (j = 0; j < cattr->num_attrs; ++j)
3707 if (cattr->attrs [j].ctor && !strcmp (cattr->attrs [j].ctor->klass->name, "MonoPInvokeCallbackAttribute"))
3709 if (j < cattr->num_attrs) {
3710 MonoCustomAttrEntry *e = &cattr->attrs [j];
3711 MonoMethodSignature *sig = mono_method_signature (e->ctor);
3712 const char *p = (const char*)e->data;
3714 int slen, num_named, named_type, data_type;
3718 char *export_name = NULL;
3719 MonoMethod *wrapper;
3721 /* this cannot be enforced by the C# compiler so we must give the user some warning before aborting */
3722 if (!(method->flags & METHOD_ATTRIBUTE_STATIC)) {
3723 g_warning ("AOT restriction: Method '%s' must be static since it is decorated with [MonoPInvokeCallback]. See http://ios.xamarin.com/Documentation/Limitations#Reverse_Callbacks",
3724 mono_method_full_name (method, TRUE));
3728 g_assert (sig->param_count == 1);
3729 g_assert (sig->params [0]->type == MONO_TYPE_CLASS && !strcmp (mono_class_from_mono_type (sig->params [0])->name, "Type"));
3732 * Decode the cattr manually since we can't create objects
3733 * during aot compilation.
3739 /* From load_cattr_value () in reflection.c */
3740 slen = mono_metadata_decode_value (p, &p);
3741 n = g_memdup (p, slen + 1);
3743 t = mono_reflection_type_from_name (n, acfg->image);
3747 klass = mono_class_from_mono_type (t);
3748 g_assert (klass->parent == mono_defaults.multicastdelegate_class);
3752 num_named = read16 (p);
3755 g_assert (num_named < 2);
3756 if (num_named == 1) {
3759 MonoType *prop_type;
3761 /* parse ExportSymbol attribute */
3763 named_type = *named;
3768 name_len = mono_metadata_decode_blob_size (named, &named);
3769 name = g_malloc (name_len + 1);
3770 memcpy (name, named, name_len);
3771 name [name_len] = 0;
3774 g_assert (named_type == 0x54);
3775 g_assert (!strcmp (name, "ExportSymbol"));
3777 prop_type = &mono_defaults.string_class->byval_arg;
3779 /* load_cattr_value (), string case */
3780 g_assert (*named != (char)0xff);
3781 slen = mono_metadata_decode_value (named, &named);
3782 export_name = g_malloc (slen + 1);
3783 memcpy (export_name, named, slen);
3784 export_name [slen] = 0;
3788 wrapper = mono_marshal_get_managed_wrapper (method, klass, 0);
3789 add_method (acfg, wrapper);
3791 g_hash_table_insert (acfg->export_names, wrapper, export_name);
3795 if ((method->flags & METHOD_ATTRIBUTE_PINVOKE_IMPL) ||
3796 (method->iflags & METHOD_IMPL_ATTRIBUTE_INTERNAL_CALL)) {
3797 add_method (acfg, mono_marshal_get_native_wrapper (method, TRUE, TRUE));
3801 /* StructureToPtr/PtrToStructure wrappers */
3802 for (i = 0; i < acfg->image->tables [MONO_TABLE_TYPEDEF].rows; ++i) {
3806 token = MONO_TOKEN_TYPE_DEF | (i + 1);
3807 klass = mono_class_get_checked (acfg->image, token, &error);
3810 mono_error_cleanup (&error);
3814 if (klass->valuetype && !klass->generic_container && can_marshal_struct (klass) &&
3815 !(klass->nested_in && strstr (klass->nested_in->name, "<PrivateImplementationDetails>") == klass->nested_in->name)) {
3816 add_method (acfg, mono_marshal_get_struct_to_ptr (klass));
3817 add_method (acfg, mono_marshal_get_ptr_to_struct (klass));
3823 has_type_vars (MonoClass *klass)
3825 if ((klass->byval_arg.type == MONO_TYPE_VAR) || (klass->byval_arg.type == MONO_TYPE_MVAR))
3828 return has_type_vars (klass->element_class);
3829 if (klass->generic_class) {
3830 MonoGenericContext *context = &klass->generic_class->context;
3831 if (context->class_inst) {
3834 for (i = 0; i < context->class_inst->type_argc; ++i)
3835 if (has_type_vars (mono_class_from_mono_type (context->class_inst->type_argv [i])))
3839 if (klass->generic_container)
3845 is_vt_inst (MonoGenericInst *inst)
3849 for (i = 0; i < inst->type_argc; ++i) {
3850 MonoType *t = inst->type_argv [i];
3851 if (MONO_TYPE_ISSTRUCT (t) || t->type == MONO_TYPE_VALUETYPE)
3858 method_has_type_vars (MonoMethod *method)
3860 if (has_type_vars (method->klass))
3863 if (method->is_inflated) {
3864 MonoGenericContext *context = mono_method_get_context (method);
3865 if (context->method_inst) {
3868 for (i = 0; i < context->method_inst->type_argc; ++i)
3869 if (has_type_vars (mono_class_from_mono_type (context->method_inst->type_argv [i])))
3876 static void add_generic_class_with_depth (MonoAotCompile *acfg, MonoClass *klass, int depth, const char *ref);
3879 add_generic_class (MonoAotCompile *acfg, MonoClass *klass, gboolean force, const char *ref)
3881 /* This might lead to a huge code blowup so only do it if neccesary */
3882 if (!acfg->aot_opts.full_aot && !force)
3885 add_generic_class_with_depth (acfg, klass, 0, ref);
3889 check_type_depth (MonoType *t, int depth)
3897 case MONO_TYPE_GENERICINST: {
3898 MonoGenericClass *gklass = t->data.generic_class;
3899 MonoGenericInst *ginst = gklass->context.class_inst;
3902 for (i = 0; i < ginst->type_argc; ++i) {
3903 if (check_type_depth (ginst->type_argv [i], depth + 1))
3917 add_types_from_method_header (MonoAotCompile *acfg, MonoMethod *method);
3920 * add_generic_class:
3922 * Add all methods of a generic class.
3925 add_generic_class_with_depth (MonoAotCompile *acfg, MonoClass *klass, int depth, const char *ref)
3928 MonoClassField *field;
3930 gboolean use_gsharedvt = FALSE;
3932 if (!acfg->ginst_hash)
3933 acfg->ginst_hash = g_hash_table_new (NULL, NULL);
3935 mono_class_init (klass);
3937 if (klass->generic_class && klass->generic_class->context.class_inst->is_open)
3940 if (has_type_vars (klass))
3943 if (!klass->generic_class && !klass->rank)
3946 if (klass->exception_type)
3949 if (!acfg->ginst_hash)
3950 acfg->ginst_hash = g_hash_table_new (NULL, NULL);
3952 if (g_hash_table_lookup (acfg->ginst_hash, klass))
3955 if (check_type_depth (&klass->byval_arg, 0))
3958 if (acfg->aot_opts.log_generics)
3959 aot_printf (acfg, "%*sAdding generic instance %s [%s].\n", depth, "", mono_type_full_name (&klass->byval_arg), ref);
3961 g_hash_table_insert (acfg->ginst_hash, klass, klass);
3964 * Use gsharedvt for generic collections with vtype arguments to avoid code blowup.
3965 * Enable this only for some classes since gsharedvt might not support all methods.
3967 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) &&
3968 (!strcmp (klass->name, "Dictionary`2") || !strcmp (klass->name, "List`1") || !strcmp (klass->name, "ReadOnlyCollection`1")))
3969 use_gsharedvt = TRUE;
3972 while ((method = mono_class_get_methods (klass, &iter))) {
3973 if ((acfg->opts & MONO_OPT_GSHAREDVT) && method->is_inflated && mono_method_get_context (method)->method_inst) {
3975 * This is partial sharing, and we can't handle it yet
3980 if (mono_method_is_generic_sharable_full (method, FALSE, FALSE, use_gsharedvt)) {
3982 add_types_from_method_header (acfg, method);
3986 if (method->is_generic)
3991 * FIXME: Instances which are referenced by these methods are not added,
3992 * for example Array.Resize<int> for List<int>.Add ().
3994 add_extra_method_with_depth (acfg, method, depth + 1);
3998 while ((field = mono_class_get_fields (klass, &iter))) {
3999 if (field->type->type == MONO_TYPE_GENERICINST)
4000 add_generic_class_with_depth (acfg, mono_class_from_mono_type (field->type), depth + 1, "field");
4003 if (klass->delegate) {
4004 method = mono_get_delegate_invoke (klass);
4006 method = mono_marshal_get_delegate_invoke (method, NULL);
4008 if (acfg->aot_opts.log_generics)
4009 aot_printf (acfg, "%*sAdding method %s.\n", depth, "", mono_method_full_name (method, TRUE));
4011 add_method (acfg, method);
4014 /* Add superclasses */
4016 add_generic_class_with_depth (acfg, klass->parent, depth, "parent");
4019 * For ICollection<T>, add instances of the helper methods
4020 * in Array, since a T[] could be cast to ICollection<T>.
4022 if (klass->image == mono_defaults.corlib && !strcmp (klass->name_space, "System.Collections.Generic") &&
4023 (!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"))) {
4024 MonoClass *tclass = mono_class_from_mono_type (klass->generic_class->context.class_inst->type_argv [0]);
4025 MonoClass *array_class = mono_bounded_array_class_get (tclass, 1, FALSE);
4029 if (!strcmp (klass->name, "IEnumerator`1"))
4030 name_prefix = g_strdup_printf ("%s.%s", klass->name_space, "IEnumerable`1");
4032 name_prefix = g_strdup_printf ("%s.%s", klass->name_space, klass->name);
4034 /* Add the T[]/InternalEnumerator class */
4035 if (!strcmp (klass->name, "IEnumerable`1") || !strcmp (klass->name, "IEnumerator`1")) {
4039 while ((nclass = mono_class_get_nested_types (array_class->parent, &iter))) {
4040 if (!strcmp (nclass->name, "InternalEnumerator`1"))
4044 nclass = mono_class_inflate_generic_class (nclass, mono_generic_class_get_context (klass->generic_class));
4045 add_generic_class (acfg, nclass, FALSE, "ICollection<T>");
4049 while ((method = mono_class_get_methods (array_class, &iter))) {
4050 if (strstr (method->name, name_prefix)) {
4051 MonoMethod *m = mono_aot_get_array_helper_from_wrapper (method);
4053 add_extra_method_with_depth (acfg, m, depth);
4057 g_free (name_prefix);
4060 /* Add an instance of GenericComparer<T> which is created dynamically by Comparer<T> */
4061 if (klass->image == mono_defaults.corlib && !strcmp (klass->name_space, "System.Collections.Generic") && !strcmp (klass->name, "Comparer`1")) {
4062 MonoClass *tclass = mono_class_from_mono_type (klass->generic_class->context.class_inst->type_argv [0]);
4063 MonoClass *icomparable, *gcomparer;
4064 MonoGenericContext ctx;
4065 MonoType *args [16];
4067 memset (&ctx, 0, sizeof (ctx));
4069 icomparable = mono_class_from_name (mono_defaults.corlib, "System", "IComparable`1");
4070 g_assert (icomparable);
4071 args [0] = &tclass->byval_arg;
4072 ctx.class_inst = mono_metadata_get_generic_inst (1, args);
4074 if (mono_class_is_assignable_from (mono_class_inflate_generic_class (icomparable, &ctx), tclass)) {
4075 gcomparer = mono_class_from_name (mono_defaults.corlib, "System.Collections.Generic", "GenericComparer`1");
4076 g_assert (gcomparer);
4077 add_generic_class (acfg, mono_class_inflate_generic_class (gcomparer, &ctx), FALSE, "Comparer<T>");
4081 /* Add an instance of GenericEqualityComparer<T> which is created dynamically by EqualityComparer<T> */
4082 if (klass->image == mono_defaults.corlib && !strcmp (klass->name_space, "System.Collections.Generic") && !strcmp (klass->name, "EqualityComparer`1")) {
4083 MonoClass *tclass = mono_class_from_mono_type (klass->generic_class->context.class_inst->type_argv [0]);
4084 MonoClass *iface, *gcomparer;
4085 MonoGenericContext ctx;
4086 MonoType *args [16];
4088 memset (&ctx, 0, sizeof (ctx));
4090 iface = mono_class_from_name (mono_defaults.corlib, "System", "IEquatable`1");
4092 args [0] = &tclass->byval_arg;
4093 ctx.class_inst = mono_metadata_get_generic_inst (1, args);
4095 if (mono_class_is_assignable_from (mono_class_inflate_generic_class (iface, &ctx), tclass)) {
4096 gcomparer = mono_class_from_name (mono_defaults.corlib, "System.Collections.Generic", "GenericEqualityComparer`1");
4097 g_assert (gcomparer);
4098 add_generic_class (acfg, mono_class_inflate_generic_class (gcomparer, &ctx), FALSE, "EqualityComparer<T>");
4104 add_instances_of (MonoAotCompile *acfg, MonoClass *klass, MonoType **insts, int ninsts, gboolean force)
4107 MonoGenericContext ctx;
4108 MonoType *args [16];
4110 if (acfg->aot_opts.no_instances)
4113 memset (&ctx, 0, sizeof (ctx));
4115 for (i = 0; i < ninsts; ++i) {
4116 args [0] = insts [i];
4117 ctx.class_inst = mono_metadata_get_generic_inst (1, args);
4118 add_generic_class (acfg, mono_class_inflate_generic_class (klass, &ctx), force, "");
4123 add_types_from_method_header (MonoAotCompile *acfg, MonoMethod *method)
4125 MonoMethodHeader *header;
4126 MonoMethodSignature *sig;
4129 depth = GPOINTER_TO_UINT (g_hash_table_lookup (acfg->method_depth, method));
4131 sig = mono_method_signature (method);
4134 for (j = 0; j < sig->param_count; ++j)
4135 if (sig->params [j]->type == MONO_TYPE_GENERICINST)
4136 add_generic_class_with_depth (acfg, mono_class_from_mono_type (sig->params [j]), depth + 1, "arg");
4139 header = mono_method_get_header (method);
4142 for (j = 0; j < header->num_locals; ++j)
4143 if (header->locals [j]->type == MONO_TYPE_GENERICINST)
4144 add_generic_class_with_depth (acfg, mono_class_from_mono_type (header->locals [j]), depth + 1, "local");
4146 mono_loader_clear_error ();
4151 * add_generic_instances:
4153 * Add instances referenced by the METHODSPEC/TYPESPEC table.
4156 add_generic_instances (MonoAotCompile *acfg)
4161 MonoGenericContext *context;
4163 if (acfg->aot_opts.no_instances)
4166 for (i = 0; i < acfg->image->tables [MONO_TABLE_METHODSPEC].rows; ++i) {
4167 token = MONO_TOKEN_METHOD_SPEC | (i + 1);
4168 method = mono_get_method (acfg->image, token, NULL);
4173 if (method->klass->image != acfg->image)
4176 context = mono_method_get_context (method);
4178 if (context && ((context->class_inst && context->class_inst->is_open)))
4182 * For open methods, create an instantiation which can be passed to the JIT.
4183 * FIXME: Handle class_inst as well.
4185 if (context && context->method_inst && context->method_inst->is_open) {
4186 MonoGenericContext shared_context;
4187 MonoGenericInst *inst;
4188 MonoType **type_argv;
4190 MonoMethod *declaring_method;
4191 gboolean supported = TRUE;
4193 /* Check that the context doesn't contain open constructed types */
4194 if (context->class_inst) {
4195 inst = context->class_inst;
4196 for (i = 0; i < inst->type_argc; ++i) {
4197 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)
4199 if (mono_class_is_open_constructed_type (inst->type_argv [i]))
4203 if (context->method_inst) {
4204 inst = context->method_inst;
4205 for (i = 0; i < inst->type_argc; ++i) {
4206 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)
4208 if (mono_class_is_open_constructed_type (inst->type_argv [i]))
4216 memset (&shared_context, 0, sizeof (MonoGenericContext));
4218 inst = context->class_inst;
4220 type_argv = g_new0 (MonoType*, inst->type_argc);
4221 for (i = 0; i < inst->type_argc; ++i) {
4222 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)
4223 type_argv [i] = &mono_defaults.object_class->byval_arg;
4225 type_argv [i] = inst->type_argv [i];
4228 shared_context.class_inst = mono_metadata_get_generic_inst (inst->type_argc, type_argv);
4232 inst = context->method_inst;
4234 type_argv = g_new0 (MonoType*, inst->type_argc);
4235 for (i = 0; i < inst->type_argc; ++i) {
4236 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)
4237 type_argv [i] = &mono_defaults.object_class->byval_arg;
4239 type_argv [i] = inst->type_argv [i];
4242 shared_context.method_inst = mono_metadata_get_generic_inst (inst->type_argc, type_argv);
4246 if (method->is_generic || method->klass->generic_container)
4247 declaring_method = method;
4249 declaring_method = mono_method_get_declaring_generic_method (method);
4251 method = mono_class_inflate_generic_method (declaring_method, &shared_context);
4255 * If the method is fully sharable, it was already added in place of its
4256 * generic definition.
4258 if (mono_method_is_generic_sharable_full (method, FALSE, FALSE, FALSE))
4262 * FIXME: Partially shared methods are not shared here, so we end up with
4263 * many identical methods.
4265 add_extra_method (acfg, method);
4268 for (i = 0; i < acfg->image->tables [MONO_TABLE_TYPESPEC].rows; ++i) {
4272 token = MONO_TOKEN_TYPE_SPEC | (i + 1);
4274 klass = mono_class_get_checked (acfg->image, token, &error);
4275 if (!klass || klass->rank) {
4276 mono_error_cleanup (&error);
4280 add_generic_class (acfg, klass, FALSE, "typespec");
4283 /* Add types of args/locals */
4284 for (i = 0; i < acfg->methods->len; ++i) {
4285 method = g_ptr_array_index (acfg->methods, i);
4286 add_types_from_method_header (acfg, method);
4289 if (acfg->image == mono_defaults.corlib) {
4291 MonoType *insts [256];
4294 insts [ninsts ++] = &mono_defaults.byte_class->byval_arg;
4295 insts [ninsts ++] = &mono_defaults.sbyte_class->byval_arg;
4296 insts [ninsts ++] = &mono_defaults.int16_class->byval_arg;
4297 insts [ninsts ++] = &mono_defaults.uint16_class->byval_arg;
4298 insts [ninsts ++] = &mono_defaults.int32_class->byval_arg;
4299 insts [ninsts ++] = &mono_defaults.uint32_class->byval_arg;
4300 insts [ninsts ++] = &mono_defaults.int64_class->byval_arg;
4301 insts [ninsts ++] = &mono_defaults.uint64_class->byval_arg;
4302 insts [ninsts ++] = &mono_defaults.single_class->byval_arg;
4303 insts [ninsts ++] = &mono_defaults.double_class->byval_arg;
4304 insts [ninsts ++] = &mono_defaults.char_class->byval_arg;
4305 insts [ninsts ++] = &mono_defaults.boolean_class->byval_arg;
4307 /* Add GenericComparer<T> instances for primitive types for Enum.ToString () */
4308 klass = mono_class_from_name (acfg->image, "System.Collections.Generic", "GenericComparer`1");
4310 add_instances_of (acfg, klass, insts, ninsts, TRUE);
4311 klass = mono_class_from_name (acfg->image, "System.Collections.Generic", "GenericEqualityComparer`1");
4313 add_instances_of (acfg, klass, insts, ninsts, TRUE);
4315 /* Add instances of the array generic interfaces for primitive types */
4316 /* This will add instances of the InternalArray_ helper methods in Array too */
4317 klass = mono_class_from_name (acfg->image, "System.Collections.Generic", "ICollection`1");
4319 add_instances_of (acfg, klass, insts, ninsts, TRUE);
4320 klass = mono_class_from_name (acfg->image, "System.Collections.Generic", "IList`1");
4322 add_instances_of (acfg, klass, insts, ninsts, TRUE);
4323 klass = mono_class_from_name (acfg->image, "System.Collections.Generic", "IEnumerable`1");
4325 add_instances_of (acfg, klass, insts, ninsts, TRUE);
4328 * Add a managed-to-native wrapper of Array.GetGenericValueImpl<object>, which is
4329 * used for all instances of GetGenericValueImpl by the AOT runtime.
4332 MonoGenericContext ctx;
4333 MonoType *args [16];
4334 MonoMethod *get_method;
4335 MonoClass *array_klass = mono_array_class_get (mono_defaults.object_class, 1)->parent;
4337 get_method = mono_class_get_method_from_name (array_klass, "GetGenericValueImpl", 2);
4340 memset (&ctx, 0, sizeof (ctx));
4341 args [0] = &mono_defaults.object_class->byval_arg;
4342 ctx.method_inst = mono_metadata_get_generic_inst (1, args);
4343 add_extra_method (acfg, mono_marshal_get_native_wrapper (mono_class_inflate_generic_method (get_method, &ctx), TRUE, TRUE));
4347 /* Same for CompareExchange<T>/Exchange<T> */
4349 MonoGenericContext ctx;
4350 MonoType *args [16];
4352 MonoClass *interlocked_klass = mono_class_from_name (mono_defaults.corlib, "System.Threading", "Interlocked");
4353 gpointer iter = NULL;
4355 while ((m = mono_class_get_methods (interlocked_klass, &iter))) {
4356 if ((!strcmp (m->name, "CompareExchange") || !strcmp (m->name, "Exchange")) && m->is_generic) {
4357 memset (&ctx, 0, sizeof (ctx));
4358 args [0] = &mono_defaults.object_class->byval_arg;
4359 ctx.method_inst = mono_metadata_get_generic_inst (1, args);
4360 add_extra_method (acfg, mono_marshal_get_native_wrapper (mono_class_inflate_generic_method (m, &ctx), TRUE, TRUE));
4365 /* Same for Volatile.Read/Write<T> */
4367 MonoGenericContext ctx;
4368 MonoType *args [16];
4370 MonoClass *volatile_klass = mono_class_from_name (mono_defaults.corlib, "System.Threading", "Volatile");
4371 gpointer iter = NULL;
4373 if (volatile_klass) {
4374 while ((m = mono_class_get_methods (volatile_klass, &iter))) {
4375 if ((!strcmp (m->name, "Read") || !strcmp (m->name, "Write")) && m->is_generic) {
4376 memset (&ctx, 0, sizeof (ctx));
4377 args [0] = &mono_defaults.object_class->byval_arg;
4378 ctx.method_inst = mono_metadata_get_generic_inst (1, args);
4379 add_extra_method (acfg, mono_marshal_get_native_wrapper (mono_class_inflate_generic_method (m, &ctx), TRUE, TRUE));
4388 * is_direct_callable:
4390 * Return whenever the method identified by JI is directly callable without
4391 * going through the PLT.
4394 is_direct_callable (MonoAotCompile *acfg, MonoMethod *method, MonoJumpInfo *patch_info)
4396 if ((patch_info->type == MONO_PATCH_INFO_METHOD) && (patch_info->data.method->klass->image == acfg->image)) {
4397 MonoCompile *callee_cfg = g_hash_table_lookup (acfg->method_to_cfg, patch_info->data.method);
4399 gboolean direct_callable = TRUE;
4401 if (direct_callable && !(!callee_cfg->has_got_slots && (callee_cfg->method->klass->flags & TYPE_ATTRIBUTE_BEFORE_FIELD_INIT)))
4402 direct_callable = FALSE;
4403 if ((callee_cfg->method->iflags & METHOD_IMPL_ATTRIBUTE_SYNCHRONIZED) && (!method || method->wrapper_type != MONO_WRAPPER_SYNCHRONIZED))
4404 // FIXME: Maybe call the wrapper directly ?
4405 direct_callable = FALSE;
4407 if (acfg->aot_opts.soft_debug || acfg->aot_opts.no_direct_calls) {
4408 /* Disable this so all calls go through load_method (), see the
4409 * mini_get_debug_options ()->load_aot_jit_info_eagerly = TRUE; line in
4410 * mono_debugger_agent_init ().
4412 direct_callable = FALSE;
4415 if (callee_cfg->method->wrapper_type == MONO_WRAPPER_ALLOC)
4416 /* sgen does some initialization when the allocator method is created */
4417 direct_callable = FALSE;
4419 if (direct_callable)
4422 } else if ((patch_info->type == MONO_PATCH_INFO_ICALL_ADDR && patch_info->data.method->flags & METHOD_ATTRIBUTE_PINVOKE_IMPL)) {
4423 if (acfg->aot_opts.direct_pinvoke)
4425 } else if (patch_info->type == MONO_PATCH_INFO_ICALL_ADDR) {
4426 if (acfg->aot_opts.direct_icalls)
4434 #ifdef MONO_ARCH_AOT_SUPPORTED
4436 get_pinvoke_import (MonoAotCompile *acfg, MonoMethod *method)
4438 MonoImage *image = method->klass->image;
4439 MonoMethodPInvoke *piinfo = (MonoMethodPInvoke *) method;
4440 MonoTableInfo *tables = image->tables;
4441 MonoTableInfo *im = &tables [MONO_TABLE_IMPLMAP];
4442 MonoTableInfo *mr = &tables [MONO_TABLE_MODULEREF];
4443 guint32 im_cols [MONO_IMPLMAP_SIZE];
4446 import = g_hash_table_lookup (acfg->method_to_pinvoke_import, method);
4450 if (!piinfo->implmap_idx || piinfo->implmap_idx > im->rows)
4453 mono_metadata_decode_row (im, piinfo->implmap_idx - 1, im_cols, MONO_IMPLMAP_SIZE);
4455 if (!im_cols [MONO_IMPLMAP_SCOPE] || im_cols [MONO_IMPLMAP_SCOPE] > mr->rows)
4458 import = g_strdup_printf ("%s", mono_metadata_string_heap (image, im_cols [MONO_IMPLMAP_NAME]));
4460 g_hash_table_insert (acfg->method_to_pinvoke_import, method, import);
4467 compare_lne (MonoDebugLineNumberEntry *a, MonoDebugLineNumberEntry *b)
4469 if (a->native_offset == b->native_offset)
4470 return a->il_offset - b->il_offset;
4472 return a->native_offset - b->native_offset;
4476 * compute_line_numbers:
4478 * Returns a sparse array of size CODE_SIZE containing MonoDebugSourceLocation* entries for the native offsets which have a corresponding line number
4481 static MonoDebugSourceLocation**
4482 compute_line_numbers (MonoMethod *method, int code_size, MonoDebugMethodJitInfo *debug_info)
4484 MonoDebugMethodInfo *minfo;
4485 MonoDebugLineNumberEntry *ln_array;
4486 MonoDebugSourceLocation *loc;
4487 int i, prev_line, prev_il_offset;
4488 int *native_to_il_offset = NULL;
4489 MonoDebugSourceLocation **res;
4492 minfo = mono_debug_lookup_method (method);
4495 // FIXME: This seems to happen when two methods have the same cfg->method_to_register
4496 if (debug_info->code_size != code_size)
4499 g_assert (code_size);
4501 /* Compute the native->IL offset mapping */
4503 ln_array = g_new0 (MonoDebugLineNumberEntry, debug_info->num_line_numbers);
4504 memcpy (ln_array, debug_info->line_numbers, debug_info->num_line_numbers * sizeof (MonoDebugLineNumberEntry));
4506 qsort (ln_array, debug_info->num_line_numbers, sizeof (MonoDebugLineNumberEntry), (gpointer)compare_lne);
4508 native_to_il_offset = g_new0 (int, code_size + 1);
4510 for (i = 0; i < debug_info->num_line_numbers; ++i) {
4512 MonoDebugLineNumberEntry *lne = &ln_array [i];
4515 for (j = 0; j < lne->native_offset; ++j)
4516 native_to_il_offset [j] = -1;
4519 if (i < debug_info->num_line_numbers - 1) {
4520 MonoDebugLineNumberEntry *lne_next = &ln_array [i + 1];
4522 for (j = lne->native_offset; j < lne_next->native_offset; ++j)
4523 native_to_il_offset [j] = lne->il_offset;
4525 for (j = lne->native_offset; j < code_size; ++j)
4526 native_to_il_offset [j] = lne->il_offset;
4531 /* Compute the native->line number mapping */
4532 res = g_new0 (MonoDebugSourceLocation*, code_size);
4533 prev_il_offset = -1;
4536 for (i = 0; i < code_size; ++i) {
4537 int il_offset = native_to_il_offset [i];
4539 if (il_offset == -1 || il_offset == prev_il_offset)
4541 prev_il_offset = il_offset;
4542 loc = mono_debug_symfile_lookup_location (minfo, il_offset);
4543 if (!(loc && loc->source_file))
4545 if (loc->row == prev_line) {
4546 mono_debug_symfile_free_location (loc);
4549 prev_line = loc->row;
4550 //printf ("D: %s:%d il=%x native=%x\n", loc->source_file, loc->row, il_offset, i);
4552 /* This will cover the prolog too */
4562 get_file_index (MonoAotCompile *acfg, const char *source_file)
4566 // FIXME: Free these
4567 if (!acfg->dwarf_ln_filenames)
4568 acfg->dwarf_ln_filenames = g_hash_table_new (g_str_hash, g_str_equal);
4569 findex = GPOINTER_TO_INT (g_hash_table_lookup (acfg->dwarf_ln_filenames, source_file));
4571 findex = g_hash_table_size (acfg->dwarf_ln_filenames) + 1;
4572 g_hash_table_insert (acfg->dwarf_ln_filenames, g_strdup (source_file), GINT_TO_POINTER (findex));
4573 emit_unset_mode (acfg);
4574 fprintf (acfg->fp, ".file %d \"%s\"\n", findex, mono_dwarf_escape_path (source_file));
4586 * emit_and_reloc_code:
4588 * Emit the native code in CODE, handling relocations along the way. If GOT_ONLY
4589 * is true, calls are made through the GOT too. This is used for emitting trampolines
4590 * in full-aot mode, since calls made from trampolines couldn't go through the PLT,
4591 * since trampolines are needed to make PTL work.
4594 emit_and_reloc_code (MonoAotCompile *acfg, MonoMethod *method, guint8 *code, guint32 code_len, MonoJumpInfo *relocs, gboolean got_only, MonoDebugMethodJitInfo *debug_info)
4596 int i, pindex, start_index, method_index;
4598 MonoJumpInfo *patch_info;
4599 MonoMethodHeader *header;
4600 MonoDebugSourceLocation **locs = NULL;
4602 #ifdef MONO_ARCH_AOT_SUPPORTED
4603 gboolean direct_call, external_call;
4605 const char *direct_call_target = 0;
4606 const char *direct_pinvoke;
4610 header = mono_method_get_header (method);
4612 method_index = get_method_index (acfg, method);
4615 if (acfg->gas_line_numbers && method && debug_info) {
4616 locs = compute_line_numbers (method, code_len, debug_info);
4618 int findex = get_file_index (acfg, "<unknown>");
4619 emit_unset_mode (acfg);
4620 fprintf (acfg->fp, ".loc %d %d 0\n", findex, 1);
4624 /* Collect and sort relocations */
4625 patches = g_ptr_array_new ();
4626 for (patch_info = relocs; patch_info; patch_info = patch_info->next)
4627 g_ptr_array_add (patches, patch_info);
4628 g_ptr_array_sort (patches, compare_patches);
4631 for (i = 0; i < code_len; i += INST_LEN) {
4633 for (pindex = start_index; pindex < patches->len; ++pindex) {
4634 patch_info = g_ptr_array_index (patches, pindex);
4635 if (patch_info->ip.i >= i)
4639 if (locs && locs [i]) {
4640 MonoDebugSourceLocation *loc = locs [i];
4643 findex = get_file_index (acfg, loc->source_file);
4644 emit_unset_mode (acfg);
4645 fprintf (acfg->fp, ".loc %d %d 0\n", findex, loc->row);
4646 mono_debug_symfile_free_location (loc);
4650 #ifdef MONO_ARCH_AOT_SUPPORTED
4651 if (patch_info && (patch_info->ip.i == i) && (pindex < patches->len)) {
4652 start_index = pindex;
4654 switch (patch_info->type) {
4655 case MONO_PATCH_INFO_NONE:
4657 case MONO_PATCH_INFO_GOT_OFFSET: {
4660 arch_emit_got_offset (acfg, code + i, &code_size);
4661 i += code_size - INST_LEN;
4663 patch_info->type = MONO_PATCH_INFO_NONE;
4666 case MONO_PATCH_INFO_OBJC_SELECTOR_REF: {
4667 int code_size, index;
4668 char *selector = (void*)patch_info->data.target;
4670 if (!acfg->objc_selector_to_index)
4671 acfg->objc_selector_to_index = g_hash_table_new (g_str_hash, g_str_equal);
4672 if (!acfg->objc_selectors)
4673 acfg->objc_selectors = g_ptr_array_new ();
4674 index = GPOINTER_TO_UINT (g_hash_table_lookup (acfg->objc_selector_to_index, selector));
4678 index = acfg->objc_selector_index;
4679 g_ptr_array_add (acfg->objc_selectors, (void*)patch_info->data.target);
4680 g_hash_table_insert (acfg->objc_selector_to_index, selector, GUINT_TO_POINTER (index + 1));
4681 acfg->objc_selector_index ++;
4684 arch_emit_objc_selector_ref (acfg, code + i, index, &code_size);
4685 i += code_size - INST_LEN;
4687 patch_info->type = MONO_PATCH_INFO_NONE;
4692 * If this patch is a call, try emitting a direct call instead of
4693 * through a PLT entry. This is possible if the called method is in
4694 * the same assembly and requires no initialization.
4696 direct_call = FALSE;
4697 external_call = FALSE;
4698 if ((patch_info->type == MONO_PATCH_INFO_METHOD) && (patch_info->data.method->klass->image == acfg->image)) {
4699 if (!got_only && is_direct_callable (acfg, method, patch_info)) {
4700 MonoCompile *callee_cfg = g_hash_table_lookup (acfg->method_to_cfg, patch_info->data.method);
4701 //printf ("DIRECT: %s %s\n", method ? mono_method_full_name (method, TRUE) : "", mono_method_full_name (callee_cfg->method, TRUE));
4703 direct_call_target = callee_cfg->asm_symbol;
4704 patch_info->type = MONO_PATCH_INFO_NONE;
4705 acfg->stats.direct_calls ++;
4708 acfg->stats.all_calls ++;
4709 } else if (patch_info->type == MONO_PATCH_INFO_ICALL_ADDR) {
4710 if (!got_only && is_direct_callable (acfg, method, patch_info)) {
4711 if (!(patch_info->data.method->flags & METHOD_ATTRIBUTE_PINVOKE_IMPL))
4712 direct_pinvoke = mono_lookup_icall_symbol (patch_info->data.method);
4714 direct_pinvoke = get_pinvoke_import (acfg, patch_info->data.method);
4715 if (direct_pinvoke) {
4717 g_assert (strlen (direct_pinvoke) < 1000);
4718 direct_call_target = g_strdup_printf ("%s%s", acfg->user_symbol_prefix, direct_pinvoke);
4721 } else if (patch_info->type == MONO_PATCH_INFO_JIT_ICALL_ADDR) {
4722 const char *sym = mono_lookup_jit_icall_symbol (patch_info->data.name);
4723 if (!got_only && sym && acfg->aot_opts.direct_icalls) {
4724 /* Call to a C function implementing a jit icall */
4726 external_call = TRUE;
4727 g_assert (strlen (sym) < 1000);
4728 direct_call_target = g_strdup_printf ("%s%s", acfg->user_symbol_prefix, sym);
4730 } else if (patch_info->type == MONO_PATCH_INFO_INTERNAL_METHOD) {
4731 MonoJitICallInfo *info = mono_find_jit_icall_by_name (patch_info->data.name);
4732 const char *sym = mono_lookup_jit_icall_symbol (patch_info->data.name);
4733 if (!got_only && sym && acfg->aot_opts.direct_icalls && info->func == info->wrapper) {
4734 /* Call to a jit icall without a wrapper */
4736 external_call = TRUE;
4737 g_assert (strlen (sym) < 1000);
4738 direct_call_target = g_strdup_printf ("%s%s", acfg->user_symbol_prefix, sym);
4743 patch_info->type = MONO_PATCH_INFO_NONE;
4744 acfg->stats.direct_calls ++;
4747 if (!got_only && !direct_call) {
4748 MonoPltEntry *plt_entry = get_plt_entry (acfg, patch_info);
4750 /* This patch has a PLT entry, so we must emit a call to the PLT entry */
4752 direct_call_target = plt_entry->symbol;
4754 /* Nullify the patch */
4755 patch_info->type = MONO_PATCH_INFO_NONE;
4756 plt_entry->jit_used = TRUE;
4763 arch_emit_direct_call (acfg, direct_call_target, external_call, FALSE, patch_info, &call_size);
4764 i += call_size - INST_LEN;
4768 got_slot = get_got_offset (acfg, patch_info);
4770 arch_emit_got_access (acfg, code + i, got_slot, &code_size);
4771 i += code_size - INST_LEN;
4777 #endif /* MONO_ARCH_AOT_SUPPORTED */
4780 /* Find next patch */
4782 for (pindex = start_index; pindex < patches->len; ++pindex) {
4783 patch_info = g_ptr_array_index (patches, pindex);
4784 if (patch_info->ip.i >= i)
4788 /* Try to emit multiple bytes at once */
4789 if (pindex < patches->len && patch_info->ip.i > i) {
4792 for (limit = i + INST_LEN; limit < patch_info->ip.i; limit += INST_LEN) {
4793 if (locs && locs [limit])
4797 emit_code_bytes (acfg, code + i, limit - i);
4798 i = limit - INST_LEN;
4800 emit_code_bytes (acfg, code + i, INST_LEN);
4811 * Return a modified version of S which only includes characters permissible in symbols.
4814 sanitize_symbol (MonoAotCompile *acfg, char *s)
4816 gboolean process = FALSE;
4825 for (i = 0; i < len; ++i)
4826 if (!(s [i] <= 0x7f && (isalnum (s [i]) || s [i] == '_')))
4831 gs = g_string_sized_new (len);
4832 for (i = 0; i < len; ++i) {
4834 if (c <= 0x7f && (isalnum (c) || c == '_')) {
4835 g_string_append_c (gs, c);
4836 } else if (c > 0x7f) {
4837 /* multi-byte utf8 */
4838 g_string_append_printf (gs, "_0x%x", c);
4841 while (c >> 6 == 0x2) {
4842 g_string_append_printf (gs, "%x", c);
4846 g_string_append_printf (gs, "_");
4849 g_string_append_c (gs, '_');
4853 res = mono_mempool_strdup (acfg->mempool, gs->str);
4854 g_string_free (gs, TRUE);
4859 get_debug_sym (MonoMethod *method, const char *prefix, GHashTable *cache)
4861 char *name1, *name2, *cached;
4862 int i, j, len, count;
4864 name1 = mono_method_full_name (method, TRUE);
4867 // This is so that we don't accidentally create a local symbol (which starts with 'L')
4868 if ((!prefix || !*prefix) && name1 [0] == 'L')
4872 len = strlen (name1);
4873 name2 = malloc (strlen (prefix) + len + 16);
4874 memcpy (name2, prefix, strlen (prefix));
4875 j = strlen (prefix);
4876 for (i = 0; i < len; ++i) {
4877 if (isalnum (name1 [i])) {
4878 name2 [j ++] = name1 [i];
4879 } else if (name1 [i] == ' ' && name1 [i + 1] == '(' && name1 [i + 2] == ')') {
4881 } else if (name1 [i] == ',' && name1 [i + 1] == ' ') {
4884 } else if (name1 [i] == '(' || name1 [i] == ')' || name1 [i] == '>') {
4893 while (g_hash_table_lookup (cache, name2)) {
4894 sprintf (name2 + j, "_%d", count);
4898 cached = g_strdup (name2);
4899 g_hash_table_insert (cache, cached, cached);
4905 emit_method_code (MonoAotCompile *acfg, MonoCompile *cfg)
4910 char *debug_sym = NULL;
4911 char *symbol = NULL;
4912 int func_alignment = AOT_FUNC_ALIGNMENT;
4913 MonoMethodHeader *header;
4916 method = cfg->orig_method;
4917 code = cfg->native_code;
4918 header = cfg->header;
4920 method_index = get_method_index (acfg, method);
4921 symbol = g_strdup_printf ("%sme_%x", acfg->temp_prefix, method_index);
4924 /* Make the labels local */
4925 emit_section_change (acfg, ".text", 0);
4926 emit_alignment (acfg, func_alignment);
4928 if (acfg->global_symbols && acfg->need_no_dead_strip)
4929 fprintf (acfg->fp, " .no_dead_strip %s\n", cfg->asm_symbol);
4931 emit_label (acfg, cfg->asm_symbol);
4933 if (acfg->aot_opts.write_symbols && !acfg->global_symbols) {
4935 * Write a C style symbol for every method, this has two uses:
4936 * - it works on platforms where the dwarf debugging info is not
4938 * - it allows the setting of breakpoints of aot-ed methods.
4940 debug_sym = get_debug_sym (method, "", acfg->method_label_hash);
4942 if (acfg->need_no_dead_strip)
4943 fprintf (acfg->fp, " .no_dead_strip %s\n", debug_sym);
4944 emit_local_symbol (acfg, debug_sym, symbol, TRUE);
4945 emit_label (acfg, debug_sym);
4948 export_name = g_hash_table_lookup (acfg->export_names, method);
4950 /* Emit a global symbol for the method */
4951 emit_global_inner (acfg, export_name, TRUE);
4952 emit_label (acfg, export_name);
4955 if (cfg->verbose_level > 0)
4956 g_print ("Method %s emitted as %s\n", mono_method_full_name (method, TRUE), cfg->asm_symbol);
4958 acfg->stats.code_size += cfg->code_len;
4960 acfg->cfgs [method_index]->got_offset = acfg->got_offset;
4962 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 ()));
4966 if (acfg->aot_opts.write_symbols) {
4967 emit_symbol_size (acfg, debug_sym, ".");
4971 emit_label (acfg, symbol);
4978 * Encode PATCH_INFO into its disk representation.
4981 encode_patch (MonoAotCompile *acfg, MonoJumpInfo *patch_info, guint8 *buf, guint8 **endbuf)
4985 switch (patch_info->type) {
4986 case MONO_PATCH_INFO_NONE:
4988 case MONO_PATCH_INFO_IMAGE:
4989 encode_value (get_image_index (acfg, patch_info->data.image), p, &p);
4991 case MONO_PATCH_INFO_MSCORLIB_GOT_ADDR:
4992 case MONO_PATCH_INFO_JIT_TLS_ID:
4993 case MONO_PATCH_INFO_GC_CARD_TABLE_ADDR:
4995 case MONO_PATCH_INFO_CASTCLASS_CACHE:
4996 encode_value (patch_info->data.index, p, &p);
4998 case MONO_PATCH_INFO_METHOD_REL:
4999 encode_value ((gint)patch_info->data.offset, p, &p);
5001 case MONO_PATCH_INFO_SWITCH: {
5002 gpointer *table = (gpointer *)patch_info->data.table->table;
5005 encode_value (patch_info->data.table->table_size, p, &p);
5006 for (k = 0; k < patch_info->data.table->table_size; k++)
5007 encode_value ((int)(gssize)table [k], p, &p);
5010 case MONO_PATCH_INFO_METHODCONST:
5011 case MONO_PATCH_INFO_METHOD:
5012 case MONO_PATCH_INFO_METHOD_JUMP:
5013 case MONO_PATCH_INFO_ICALL_ADDR:
5014 case MONO_PATCH_INFO_METHOD_RGCTX:
5015 case MONO_PATCH_INFO_METHOD_CODE_SLOT:
5016 encode_method_ref (acfg, patch_info->data.method, p, &p);
5018 case MONO_PATCH_INFO_INTERNAL_METHOD:
5019 case MONO_PATCH_INFO_JIT_ICALL_ADDR: {
5020 guint32 len = strlen (patch_info->data.name);
5022 encode_value (len, p, &p);
5024 memcpy (p, patch_info->data.name, len);
5029 case MONO_PATCH_INFO_LDSTR: {
5030 guint32 image_index = get_image_index (acfg, patch_info->data.token->image);
5031 guint32 token = patch_info->data.token->token;
5032 g_assert (mono_metadata_token_code (token) == MONO_TOKEN_STRING);
5033 encode_value (image_index, p, &p);
5034 encode_value (patch_info->data.token->token - MONO_TOKEN_STRING, p, &p);
5037 case MONO_PATCH_INFO_RVA:
5038 case MONO_PATCH_INFO_DECLSEC:
5039 case MONO_PATCH_INFO_LDTOKEN:
5040 case MONO_PATCH_INFO_TYPE_FROM_HANDLE:
5041 encode_value (get_image_index (acfg, patch_info->data.token->image), p, &p);
5042 encode_value (patch_info->data.token->token, p, &p);
5043 encode_value (patch_info->data.token->has_context, p, &p);
5044 if (patch_info->data.token->has_context)
5045 encode_generic_context (acfg, &patch_info->data.token->context, p, &p);
5047 case MONO_PATCH_INFO_EXC_NAME: {
5048 MonoClass *ex_class;
5051 mono_class_from_name (mono_defaults.exception_class->image,
5052 "System", patch_info->data.target);
5053 g_assert (ex_class);
5054 encode_klass_ref (acfg, ex_class, p, &p);
5057 case MONO_PATCH_INFO_R4:
5058 encode_value (*((guint32 *)patch_info->data.target), p, &p);
5060 case MONO_PATCH_INFO_R8:
5061 encode_value (((guint32 *)patch_info->data.target) [MINI_LS_WORD_IDX], p, &p);
5062 encode_value (((guint32 *)patch_info->data.target) [MINI_MS_WORD_IDX], p, &p);
5064 case MONO_PATCH_INFO_VTABLE:
5065 case MONO_PATCH_INFO_CLASS:
5066 case MONO_PATCH_INFO_IID:
5067 case MONO_PATCH_INFO_ADJUSTED_IID:
5068 case MONO_PATCH_INFO_CLASS_INIT:
5069 encode_klass_ref (acfg, patch_info->data.klass, p, &p);
5071 case MONO_PATCH_INFO_DELEGATE_TRAMPOLINE:
5072 encode_klass_ref (acfg, patch_info->data.del_tramp->klass, p, &p);
5073 if (patch_info->data.del_tramp->method) {
5074 encode_value (1, p, &p);
5075 encode_method_ref (acfg, patch_info->data.del_tramp->method, p, &p);
5077 encode_value (0, p, &p);
5079 encode_value (patch_info->data.del_tramp->virtual, p, &p);
5081 case MONO_PATCH_INFO_FIELD:
5082 case MONO_PATCH_INFO_SFLDA:
5083 encode_field_info (acfg, patch_info->data.field, p, &p);
5085 case MONO_PATCH_INFO_INTERRUPTION_REQUEST_FLAG:
5087 case MONO_PATCH_INFO_RGCTX_FETCH: {
5088 MonoJumpInfoRgctxEntry *entry = patch_info->data.rgctx_entry;
5093 * entry->method has a lenghtly encoding and multiple rgctx_fetch entries
5094 * reference the same method, so encode the method only once.
5096 offset = GPOINTER_TO_UINT (g_hash_table_lookup (acfg->method_blob_hash, entry->method));
5098 buf2 = g_malloc (1024);
5101 encode_method_ref (acfg, entry->method, p2, &p2);
5102 g_assert (p2 - buf2 < 1024);
5104 offset = add_to_blob (acfg, buf2, p2 - buf2);
5107 g_hash_table_insert (acfg->method_blob_hash, entry->method, GUINT_TO_POINTER (offset + 1));
5112 encode_value (offset, p, &p);
5113 g_assert ((int)entry->info_type < 256);
5114 g_assert (entry->data->type < 256);
5115 encode_value ((entry->in_mrgctx ? 1 : 0) | (entry->info_type << 1) | (entry->data->type << 9), p, &p);
5116 encode_patch (acfg, entry->data, p, &p);
5119 case MONO_PATCH_INFO_GENERIC_CLASS_INIT:
5120 case MONO_PATCH_INFO_MONITOR_ENTER:
5121 case MONO_PATCH_INFO_MONITOR_EXIT:
5122 case MONO_PATCH_INFO_SEQ_POINT_INFO:
5124 case MONO_PATCH_INFO_LLVM_IMT_TRAMPOLINE:
5125 encode_method_ref (acfg, patch_info->data.imt_tramp->method, p, &p);
5126 encode_value (patch_info->data.imt_tramp->vt_offset, p, &p);
5128 case MONO_PATCH_INFO_SIGNATURE:
5129 encode_signature (acfg, (MonoMethodSignature*)patch_info->data.target, p, &p);
5131 case MONO_PATCH_INFO_TLS_OFFSET:
5132 encode_value (GPOINTER_TO_INT (patch_info->data.target), p, &p);
5134 case MONO_PATCH_INFO_GSHAREDVT_CALL:
5135 encode_signature (acfg, (MonoMethodSignature*)patch_info->data.gsharedvt->sig, p, &p);
5136 encode_method_ref (acfg, patch_info->data.gsharedvt->method, p, &p);
5138 case MONO_PATCH_INFO_GSHAREDVT_METHOD: {
5139 MonoGSharedVtMethodInfo *info = patch_info->data.gsharedvt_method;
5142 encode_method_ref (acfg, info->method, p, &p);
5143 encode_value (info->num_entries, p, &p);
5144 for (i = 0; i < info->num_entries; ++i) {
5145 MonoRuntimeGenericContextInfoTemplate *template = &info->entries [i];
5147 encode_value (template->info_type, p, &p);
5148 switch (mini_rgctx_info_type_to_patch_info_type (template->info_type)) {
5149 case MONO_PATCH_INFO_CLASS:
5150 encode_klass_ref (acfg, mono_class_from_mono_type (template->data), p, &p);
5152 case MONO_PATCH_INFO_FIELD:
5153 encode_field_info (acfg, template->data, p, &p);
5156 g_assert_not_reached ();
5163 g_warning ("unable to handle jump info %d", patch_info->type);
5164 g_assert_not_reached ();
5171 encode_patch_list (MonoAotCompile *acfg, GPtrArray *patches, int n_patches, int first_got_offset, guint8 *buf, guint8 **endbuf)
5174 guint32 pindex, offset;
5175 MonoJumpInfo *patch_info;
5177 encode_value (n_patches, p, &p);
5179 for (pindex = 0; pindex < patches->len; ++pindex) {
5180 patch_info = g_ptr_array_index (patches, pindex);
5182 if (patch_info->type == MONO_PATCH_INFO_NONE || patch_info->type == MONO_PATCH_INFO_BB)
5186 offset = get_got_offset (acfg, patch_info);
5187 encode_value (offset, p, &p);
5194 emit_method_info (MonoAotCompile *acfg, MonoCompile *cfg)
5198 int pindex, buf_size, n_patches;
5200 MonoJumpInfo *patch_info;
5201 MonoMethodHeader *header;
5202 guint32 method_index;
5204 guint32 first_got_offset;
5206 method = cfg->orig_method;
5207 header = mono_method_get_header (method);
5209 method_index = get_method_index (acfg, method);
5211 /* Sort relocations */
5212 patches = g_ptr_array_new ();
5213 for (patch_info = cfg->patch_info; patch_info; patch_info = patch_info->next)
5214 g_ptr_array_add (patches, patch_info);
5215 g_ptr_array_sort (patches, compare_patches);
5217 first_got_offset = acfg->cfgs [method_index]->got_offset;
5219 /**********************/
5220 /* Encode method info */
5221 /**********************/
5223 buf_size = (patches->len < 1000) ? 40960 : 40960 + (patches->len * 64);
5224 p = buf = g_malloc (buf_size);
5226 if (mono_class_get_cctor (method->klass))
5227 encode_klass_ref (acfg, method->klass, p, &p);
5229 /* Not needed when loading the method */
5230 encode_value (0, p, &p);
5233 if (cfg->opt & MONO_OPT_SHARED) {
5234 encode_value (g_list_length (cfg->ldstr_list), p, &p);
5235 for (l = cfg->ldstr_list; l; l = l->next) {
5236 encode_value ((long)l->data, p, &p);
5240 /* Used only in shared mode */
5241 g_assert (!cfg->ldstr_list);
5244 for (pindex = 0; pindex < patches->len; ++pindex) {
5245 patch_info = g_ptr_array_index (patches, pindex);
5247 if ((patch_info->type == MONO_PATCH_INFO_GOT_OFFSET) ||
5248 (patch_info->type == MONO_PATCH_INFO_NONE)) {
5249 patch_info->type = MONO_PATCH_INFO_NONE;
5254 if ((patch_info->type == MONO_PATCH_INFO_IMAGE) && (patch_info->data.image == acfg->image)) {
5255 /* Stored in a GOT slot initialized at module load time */
5256 patch_info->type = MONO_PATCH_INFO_NONE;
5260 if (patch_info->type == MONO_PATCH_INFO_GC_CARD_TABLE_ADDR) {
5261 /* Stored in a GOT slot initialized at module load time */
5262 patch_info->type = MONO_PATCH_INFO_NONE;
5266 if (is_plt_patch (patch_info)) {
5267 /* Calls are made through the PLT */
5268 patch_info->type = MONO_PATCH_INFO_NONE;
5276 g_assert (cfg->has_got_slots);
5278 encode_patch_list (acfg, patches, n_patches, first_got_offset, p, &p);
5280 acfg->stats.info_size += p - buf;
5282 g_assert (p - buf < buf_size);
5284 cfg->method_info_offset = add_to_blob (acfg, buf, p - buf);
5289 get_unwind_info_offset (MonoAotCompile *acfg, guint8 *encoded, guint32 encoded_len)
5291 guint32 cache_index;
5294 /* Reuse the unwind module to canonize and store unwind info entries */
5295 cache_index = mono_cache_unwind_info (encoded, encoded_len);
5297 /* Use +/- 1 to distinguish 0s from missing entries */
5298 offset = GPOINTER_TO_UINT (g_hash_table_lookup (acfg->unwind_info_offsets, GUINT_TO_POINTER (cache_index + 1)));
5306 * It would be easier to use assembler symbols, but the caller needs an
5309 offset = acfg->unwind_info_offset;
5310 g_hash_table_insert (acfg->unwind_info_offsets, GUINT_TO_POINTER (cache_index + 1), GUINT_TO_POINTER (offset + 1));
5311 g_ptr_array_add (acfg->unwind_ops, GUINT_TO_POINTER (cache_index));
5314 encode_value (encoded_len, p, &p);
5316 acfg->unwind_info_offset += encoded_len + (p - buf);
5322 emit_exception_debug_info (MonoAotCompile *acfg, MonoCompile *cfg)
5325 int i, k, buf_size, method_index;
5326 guint32 debug_info_size, seq_points_size;
5328 MonoMethodHeader *header;
5329 guint8 *p, *buf, *debug_info;
5330 MonoJitInfo *jinfo = cfg->jit_info;
5332 gboolean use_unwind_ops = FALSE;
5333 MonoSeqPointInfo *seq_points;
5335 method = cfg->orig_method;
5336 code = cfg->native_code;
5337 header = cfg->header;
5339 method_index = get_method_index (acfg, method);
5341 if (!acfg->aot_opts.nodebug) {
5342 mono_debug_serialize_debug_info (cfg, &debug_info, &debug_info_size);
5345 debug_info_size = 0;
5348 seq_points = cfg->seq_point_info;
5350 seq_points_size = seq_point_info_get_write_size (seq_points);
5352 buf_size = header->num_clauses * 256 + debug_info_size + 2048 + seq_points_size + cfg->gc_map_size;
5353 p = buf = g_malloc (buf_size);
5355 use_unwind_ops = cfg->unwind_ops != NULL;
5357 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);
5359 encode_value (flags, p, &p);
5361 if (use_unwind_ops) {
5362 guint32 encoded_len;
5364 guint32 unwind_desc;
5366 encoded = mono_unwind_ops_encode (cfg->unwind_ops, &encoded_len);
5368 unwind_desc = get_unwind_info_offset (acfg, encoded, encoded_len);
5369 encode_value (unwind_desc, p, &p);
5371 encode_value (jinfo->unwind_info, p, &p);
5374 /*Encode the number of holes before the number of clauses to make decoding easier*/
5375 if (jinfo->has_try_block_holes) {
5376 MonoTryBlockHoleTableJitInfo *table = mono_jit_info_get_try_block_hole_table_info (jinfo);
5377 encode_value (table->num_holes, p, &p);
5380 if (jinfo->has_arch_eh_info) {
5382 * In AOT mode, the code length is calculated from the address of the previous method,
5383 * which could include alignment padding, so calculating the start of the epilog as
5384 * code_len - epilog_size is correct any more. Save the real code len as a workaround.
5386 encode_value (jinfo->code_size, p, &p);
5389 /* Exception table */
5390 if (cfg->compile_llvm) {
5392 * When using LLVM, we can't emit some data, like pc offsets, this reg/offset etc.,
5393 * since the information is only available to llc. Instead, we let llc save the data
5394 * into the LSDA, and read it from there at runtime.
5396 /* The assembly might be CIL stripped so emit the data ourselves */
5397 if (header->num_clauses)
5398 encode_value (header->num_clauses, p, &p);
5400 for (k = 0; k < header->num_clauses; ++k) {
5401 MonoExceptionClause *clause;
5403 clause = &header->clauses [k];
5405 encode_value (clause->flags, p, &p);
5406 if (clause->data.catch_class) {
5407 encode_value (1, p, &p);
5408 encode_klass_ref (acfg, clause->data.catch_class, p, &p);
5410 encode_value (0, p, &p);
5413 /* Emit a list of nesting clauses */
5414 for (i = 0; i < header->num_clauses; ++i) {
5416 MonoExceptionClause *clause1 = &header->clauses [cindex1];
5418 MonoExceptionClause *clause2 = &header->clauses [cindex2];
5420 if (cindex1 != cindex2 && clause1->try_offset >= clause2->try_offset && clause1->handler_offset <= clause2->handler_offset)
5421 encode_value (i, p, &p);
5423 encode_value (-1, p, &p);
5426 if (jinfo->num_clauses)
5427 encode_value (jinfo->num_clauses, p, &p);
5429 for (k = 0; k < jinfo->num_clauses; ++k) {
5430 MonoJitExceptionInfo *ei = &jinfo->clauses [k];
5432 encode_value (ei->flags, p, &p);
5433 encode_value (ei->exvar_offset, p, &p);
5435 if (ei->flags == MONO_EXCEPTION_CLAUSE_FILTER || ei->flags == MONO_EXCEPTION_CLAUSE_FINALLY)
5436 encode_value ((gint)((guint8*)ei->data.filter - code), p, &p);
5438 if (ei->data.catch_class) {
5442 buf2 = g_malloc (4096);
5444 encode_klass_ref (acfg, ei->data.catch_class, p2, &p2);
5446 g_assert (len < 4096);
5447 encode_value (len, p, &p);
5448 memcpy (p, buf2, len);
5452 encode_value (0, p, &p);
5456 encode_value ((gint)((guint8*)ei->try_start - code), p, &p);
5457 encode_value ((gint)((guint8*)ei->try_end - code), p, &p);
5458 encode_value ((gint)((guint8*)ei->handler_start - code), p, &p);
5462 if (jinfo->has_try_block_holes) {
5463 MonoTryBlockHoleTableJitInfo *table = mono_jit_info_get_try_block_hole_table_info (jinfo);
5464 for (i = 0; i < table->num_holes; ++i) {
5465 MonoTryBlockHoleJitInfo *hole = &table->holes [i];
5466 encode_value (hole->clause, p, &p);
5467 encode_value (hole->length, p, &p);
5468 encode_value (hole->offset, p, &p);
5472 if (jinfo->has_arch_eh_info) {
5473 MonoArchEHJitInfo *eh_info;
5475 eh_info = mono_jit_info_get_arch_eh_info (jinfo);
5476 encode_value (eh_info->stack_size, p, &p);
5477 encode_value (eh_info->epilog_size, p, &p);
5480 if (jinfo->has_generic_jit_info) {
5481 MonoGenericJitInfo *gi = mono_jit_info_get_generic_jit_info (jinfo);
5482 MonoGenericSharingContext* gsctx = gi->generic_sharing_context;
5488 encode_value (gi->nlocs, p, &p);
5490 for (i = 0; i < gi->nlocs; ++i) {
5491 MonoDwarfLocListEntry *entry = &gi->locations [i];
5493 encode_value (entry->is_reg ? 1 : 0, p, &p);
5494 encode_value (entry->reg, p, &p);
5496 encode_value (entry->offset, p, &p);
5498 g_assert (entry->from == 0);
5500 encode_value (entry->from, p, &p);
5501 encode_value (entry->to, p, &p);
5504 if (!cfg->compile_llvm) {
5505 encode_value (gi->has_this ? 1 : 0, p, &p);
5506 encode_value (gi->this_reg, p, &p);
5507 encode_value (gi->this_offset, p, &p);
5512 * Need to encode jinfo->method too, since it is not equal to 'method'
5513 * when using generic sharing.
5515 buf2 = g_malloc (4096);
5517 encode_method_ref (acfg, jinfo->d.method, p2, &p2);
5519 g_assert (len < 4096);
5520 encode_value (len, p, &p);
5521 memcpy (p, buf2, len);
5525 if (gsctx && (gsctx->var_is_vt || gsctx->mvar_is_vt)) {
5526 MonoMethodInflated *inflated;
5527 MonoGenericContext *context;
5528 MonoGenericInst *inst;
5530 g_assert (jinfo->d.method->is_inflated);
5531 inflated = (MonoMethodInflated*)jinfo->d.method;
5532 context = &inflated->context;
5534 encode_value (1, p, &p);
5535 if (context->class_inst) {
5536 inst = context->class_inst;
5538 encode_value (inst->type_argc, p, &p);
5539 for (i = 0; i < inst->type_argc; ++i)
5540 encode_value (gsctx->var_is_vt [i], p, &p);
5542 encode_value (0, p, &p);
5544 if (context->method_inst) {
5545 inst = context->method_inst;
5547 encode_value (inst->type_argc, p, &p);
5548 for (i = 0; i < inst->type_argc; ++i)
5549 encode_value (gsctx->mvar_is_vt [i], p, &p);
5551 encode_value (0, p, &p);
5554 encode_value (0, p, &p);
5559 p += seq_point_info_write (seq_points, p);
5561 g_assert (debug_info_size < buf_size);
5563 encode_value (debug_info_size, p, &p);
5564 if (debug_info_size) {
5565 memcpy (p, debug_info, debug_info_size);
5566 p += debug_info_size;
5567 g_free (debug_info);
5572 encode_value (cfg->gc_map_size, p, &p);
5573 /* The GC map requires 4 bytes of alignment */
5574 while ((gsize)p % 4)
5576 memcpy (p, cfg->gc_map, cfg->gc_map_size);
5577 p += cfg->gc_map_size;
5580 acfg->stats.ex_info_size += p - buf;
5582 g_assert (p - buf < buf_size);
5585 /* The GC Map requires 4 byte alignment */
5586 cfg->ex_info_offset = add_to_blob_aligned (acfg, buf, p - buf, cfg->gc_map ? 4 : 1);
5591 emit_klass_info (MonoAotCompile *acfg, guint32 token)
5594 MonoClass *klass = mono_class_get_checked (acfg->image, token, &error);
5596 int i, buf_size, res;
5597 gboolean no_special_static, cant_encode;
5598 gpointer iter = NULL;
5601 mono_error_cleanup (&error);
5605 p = buf = g_malloc (buf_size);
5607 /* Mark as unusable */
5608 encode_value (-1, p, &p);
5610 res = add_to_blob (acfg, buf, p - buf);
5616 buf_size = 10240 + (klass->vtable_size * 16);
5617 p = buf = g_malloc (buf_size);
5621 mono_class_init (klass);
5623 mono_class_get_nested_types (klass, &iter);
5624 g_assert (klass->nested_classes_inited);
5626 mono_class_setup_vtable (klass);
5629 * Emit all the information which is required for creating vtables so
5630 * the runtime does not need to create the MonoMethod structures which
5631 * take up a lot of space.
5634 no_special_static = !mono_class_has_special_static_fields (klass);
5636 /* Check whenever we have enough info to encode the vtable */
5637 cant_encode = FALSE;
5638 for (i = 0; i < klass->vtable_size; ++i) {
5639 MonoMethod *cm = klass->vtable [i];
5641 if (cm && mono_method_signature (cm)->is_inflated && !g_hash_table_lookup (acfg->token_info_hash, cm))
5645 mono_class_has_finalizer (klass);
5647 if (klass->generic_container || cant_encode) {
5648 encode_value (-1, p, &p);
5650 encode_value (klass->vtable_size, p, &p);
5651 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);
5652 if (klass->has_cctor)
5653 encode_method_ref (acfg, mono_class_get_cctor (klass), p, &p);
5654 if (klass->has_finalize)
5655 encode_method_ref (acfg, mono_class_get_finalizer (klass), p, &p);
5657 encode_value (klass->instance_size, p, &p);
5658 encode_value (mono_class_data_size (klass), p, &p);
5659 encode_value (klass->packing_size, p, &p);
5660 encode_value (klass->min_align, p, &p);
5662 for (i = 0; i < klass->vtable_size; ++i) {
5663 MonoMethod *cm = klass->vtable [i];
5666 encode_method_ref (acfg, cm, p, &p);
5668 encode_value (0, p, &p);
5672 acfg->stats.class_info_size += p - buf;
5674 g_assert (p - buf < buf_size);
5675 res = add_to_blob (acfg, buf, p - buf);
5682 get_plt_entry_debug_sym (MonoAotCompile *acfg, MonoJumpInfo *ji, GHashTable *cache)
5684 char *debug_sym = NULL;
5688 case MONO_PATCH_INFO_METHOD:
5689 debug_sym = get_debug_sym (ji->data.method, "plt_", cache);
5691 case MONO_PATCH_INFO_INTERNAL_METHOD:
5692 debug_sym = g_strdup_printf ("plt__jit_icall_%s", ji->data.name);
5694 case MONO_PATCH_INFO_CLASS_INIT:
5695 s = mono_type_get_name (&ji->data.klass->byval_arg);
5696 debug_sym = g_strdup_printf ("plt__class_init_%s", s);
5699 case MONO_PATCH_INFO_RGCTX_FETCH:
5700 debug_sym = g_strdup_printf ("plt__rgctx_fetch_%d", acfg->label_generator ++);
5702 case MONO_PATCH_INFO_ICALL_ADDR: {
5703 char *s = get_debug_sym (ji->data.method, "", cache);
5705 debug_sym = g_strdup_printf ("plt__icall_native_%s", s);
5709 case MONO_PATCH_INFO_JIT_ICALL_ADDR:
5710 debug_sym = g_strdup_printf ("plt__jit_icall_native_%s", ji->data.name);
5712 case MONO_PATCH_INFO_GENERIC_CLASS_INIT:
5713 debug_sym = g_strdup_printf ("plt__generic_class_init");
5719 return sanitize_symbol (acfg, debug_sym);
5723 * Calls made from AOTed code are routed through a table of jumps similar to the
5724 * ELF PLT (Program Linkage Table). Initially the PLT entries jump to code which transfers
5725 * control to the AOT runtime through a trampoline.
5728 emit_plt (MonoAotCompile *acfg)
5734 sprintf (symbol, "plt");
5736 emit_section_change (acfg, ".text", 0);
5737 emit_alignment (acfg, NACL_SIZE(16, kNaClAlignment));
5738 emit_label (acfg, symbol);
5739 emit_label (acfg, acfg->plt_symbol);
5741 for (i = 0; i < acfg->plt_offset; ++i) {
5742 char *debug_sym = NULL;
5743 MonoPltEntry *plt_entry = NULL;
5748 * The first plt entry is unused.
5752 plt_entry = g_hash_table_lookup (acfg->plt_offset_to_entry, GUINT_TO_POINTER (i));
5755 debug_sym = plt_entry->debug_sym;
5757 if (acfg->thumb_mixed && !plt_entry->jit_used)
5758 /* Emit only a thumb version */
5761 /* Skip plt entries not actually called */
5762 if (!plt_entry->jit_used && !plt_entry->llvm_used)
5765 if (acfg->llvm && !acfg->thumb_mixed)
5766 emit_label (acfg, plt_entry->llvm_symbol);
5769 if (acfg->need_no_dead_strip) {
5770 emit_unset_mode (acfg);
5771 fprintf (acfg->fp, " .no_dead_strip %s\n", debug_sym);
5773 emit_local_symbol (acfg, debug_sym, NULL, TRUE);
5774 emit_label (acfg, debug_sym);
5777 emit_label (acfg, plt_entry->symbol);
5779 arch_emit_plt_entry (acfg, i);
5782 emit_symbol_size (acfg, debug_sym, ".");
5785 if (acfg->thumb_mixed) {
5786 /* Make sure the ARM symbols don't alias the thumb ones */
5787 emit_zero_bytes (acfg, 16);
5790 * Emit a separate set of PLT entries using thumb2 which is called by LLVM generated
5793 for (i = 0; i < acfg->plt_offset; ++i) {
5794 char *debug_sym = NULL;
5795 MonoPltEntry *plt_entry = NULL;
5801 plt_entry = g_hash_table_lookup (acfg->plt_offset_to_entry, GUINT_TO_POINTER (i));
5804 /* Skip plt entries not actually called by LLVM code */
5805 if (!plt_entry->llvm_used)
5808 if (acfg->aot_opts.write_symbols) {
5809 if (plt_entry->debug_sym)
5810 debug_sym = g_strdup_printf ("%s_thumb", plt_entry->debug_sym);
5814 #if defined(TARGET_MACH)
5815 fprintf (acfg->fp, " .thumb_func %s\n", debug_sym);
5816 fprintf (acfg->fp, " .no_dead_strip %s\n", debug_sym);
5818 emit_local_symbol (acfg, debug_sym, NULL, TRUE);
5819 emit_label (acfg, debug_sym);
5821 fprintf (acfg->fp, "\n.thumb_func\n");
5823 emit_label (acfg, plt_entry->llvm_symbol);
5825 arch_emit_llvm_plt_entry (acfg, i);
5828 emit_symbol_size (acfg, debug_sym, ".");
5834 emit_symbol_size (acfg, acfg->plt_symbol, ".");
5836 sprintf (symbol, "plt_end");
5837 emit_label (acfg, symbol);
5841 * emit_trampoline_full:
5843 * If EMIT_TINFO is TRUE, emit additional information which can be used to create a MonoJitInfo for this trampoline by
5844 * create_jit_info_for_trampoline ().
5846 static G_GNUC_UNUSED void
5847 emit_trampoline_full (MonoAotCompile *acfg, int got_offset, MonoTrampInfo *info, gboolean emit_tinfo)
5849 char start_symbol [256];
5850 char end_symbol [256];
5852 guint32 buf_size, info_offset;
5853 MonoJumpInfo *patch_info;
5866 code_size = info->code_size;
5868 unwind_ops = info->unwind_ops;
5870 #ifdef __native_client_codegen__
5871 mono_nacl_fix_patches (code, ji);
5876 sprintf (start_symbol, "%s%s", acfg->user_symbol_prefix, name);
5878 emit_section_change (acfg, ".text", 0);
5879 emit_global (acfg, start_symbol, TRUE);
5880 emit_alignment (acfg, AOT_FUNC_ALIGNMENT);
5881 emit_label (acfg, start_symbol);
5883 sprintf (symbol, "%snamed_%s", acfg->temp_prefix, name);
5884 emit_label (acfg, symbol);
5887 * The code should access everything through the GOT, so we pass
5890 emit_and_reloc_code (acfg, NULL, code, code_size, ji, TRUE, NULL);
5892 emit_symbol_size (acfg, start_symbol, ".");
5895 sprintf (end_symbol, "%snamede_%s", acfg->temp_prefix, name);
5896 emit_label (acfg, end_symbol);
5901 /* Sort relocations */
5902 patches = g_ptr_array_new ();
5903 for (patch_info = ji; patch_info; patch_info = patch_info->next)
5904 if (patch_info->type != MONO_PATCH_INFO_NONE)
5905 g_ptr_array_add (patches, patch_info);
5906 g_ptr_array_sort (patches, compare_patches);
5908 buf_size = patches->len * 128 + 128;
5909 buf = g_malloc (buf_size);
5912 encode_patch_list (acfg, patches, patches->len, got_offset, p, &p);
5913 g_assert (p - buf < buf_size);
5915 sprintf (symbol, "%s%s_p", acfg->user_symbol_prefix, name);
5917 info_offset = add_to_blob (acfg, buf, p - buf);
5919 emit_section_change (acfg, RODATA_SECT, 0);
5920 emit_global (acfg, symbol, FALSE);
5921 emit_label (acfg, symbol);
5923 emit_int32 (acfg, info_offset);
5927 guint32 encoded_len;
5931 * Emit additional information which can be used to reconstruct a partial MonoTrampInfo.
5933 encoded = mono_unwind_ops_encode (info->unwind_ops, &encoded_len);
5934 uw_offset = get_unwind_info_offset (acfg, encoded, encoded_len);
5937 emit_symbol_diff (acfg, end_symbol, start_symbol, 0);
5938 emit_int32 (acfg, uw_offset);
5941 /* Emit debug info */
5945 sprintf (symbol, "%s", name);
5946 sprintf (symbol2, "%snamed_%s", acfg->temp_prefix, name);
5949 mono_dwarf_writer_emit_trampoline (acfg->dwarf, symbol, symbol2, NULL, NULL, code_size, unwind_ops);
5953 static G_GNUC_UNUSED void
5954 emit_trampoline (MonoAotCompile *acfg, int got_offset, MonoTrampInfo *info)
5956 emit_trampoline_full (acfg, got_offset, info, FALSE);
5960 emit_trampolines (MonoAotCompile *acfg)
5963 char end_symbol [256];
5964 int i, tramp_got_offset;
5965 MonoAotTrampoline ntype;
5966 #ifdef MONO_ARCH_HAVE_FULL_AOT_TRAMPOLINES
5970 if (!acfg->aot_opts.full_aot)
5973 g_assert (acfg->image->assembly);
5975 /* Currently, we emit most trampolines into the mscorlib AOT image. */
5976 if (strcmp (acfg->image->assembly->aname.name, "mscorlib") == 0) {
5977 #ifdef MONO_ARCH_HAVE_FULL_AOT_TRAMPOLINES
5978 MonoTrampInfo *info;
5981 * Emit the generic trampolines.
5983 * We could save some code by treating the generic trampolines as a wrapper
5984 * method, but that approach has its own complexities, so we choose the simpler
5987 for (tramp_type = 0; tramp_type < MONO_TRAMPOLINE_NUM; ++tramp_type) {
5988 /* we overload the boolean here to indicate the slightly different trampoline needed, see mono_arch_create_generic_trampoline() */
5989 #ifdef DISABLE_REMOTING
5990 if (tramp_type == MONO_TRAMPOLINE_GENERIC_VIRTUAL_REMOTING)
5993 #ifndef MONO_ARCH_HAVE_HANDLER_BLOCK_GUARD
5994 if (tramp_type == MONO_TRAMPOLINE_HANDLER_BLOCK_GUARD)
5997 mono_arch_create_generic_trampoline (tramp_type, &info, acfg->aot_opts.use_trampolines_page? 2: TRUE);
5998 emit_trampoline (acfg, acfg->got_offset, info);
6001 mono_arch_get_nullified_class_init_trampoline (&info);
6002 emit_trampoline (acfg, acfg->got_offset, info);
6003 #if defined(MONO_ARCH_MONITOR_OBJECT_REG)
6004 mono_arch_create_monitor_enter_trampoline (&info, TRUE);
6005 emit_trampoline (acfg, acfg->got_offset, info);
6006 mono_arch_create_monitor_exit_trampoline (&info, TRUE);
6007 emit_trampoline (acfg, acfg->got_offset, info);
6010 mono_arch_create_generic_class_init_trampoline (&info, TRUE);
6011 emit_trampoline (acfg, acfg->got_offset, info);
6013 /* Emit the exception related code pieces */
6014 mono_arch_get_restore_context (&info, TRUE);
6015 emit_trampoline (acfg, acfg->got_offset, info);
6016 mono_arch_get_call_filter (&info, TRUE);
6017 emit_trampoline (acfg, acfg->got_offset, info);
6018 mono_arch_get_throw_exception (&info, TRUE);
6019 emit_trampoline (acfg, acfg->got_offset, info);
6020 mono_arch_get_rethrow_exception (&info, TRUE);
6021 emit_trampoline (acfg, acfg->got_offset, info);
6022 mono_arch_get_throw_corlib_exception (&info, TRUE);
6023 emit_trampoline (acfg, acfg->got_offset, info);
6025 #ifdef MONO_ARCH_GSHAREDVT_SUPPORTED
6026 mono_arch_get_gsharedvt_trampoline (&info, TRUE);
6028 emit_trampoline_full (acfg, acfg->got_offset, info, TRUE);
6030 /* Create a separate out trampoline for more information in stack traces */
6031 info->name = g_strdup ("gsharedvt_out_trampoline");
6032 emit_trampoline_full (acfg, acfg->got_offset, info, TRUE);
6036 #if defined(MONO_ARCH_HAVE_GET_TRAMPOLINES)
6038 GSList *l = mono_arch_get_trampolines (TRUE);
6041 MonoTrampInfo *info = l->data;
6043 emit_trampoline (acfg, acfg->got_offset, info);
6049 for (i = 0; i < acfg->aot_opts.nrgctx_fetch_trampolines; ++i) {
6052 offset = MONO_RGCTX_SLOT_MAKE_RGCTX (i);
6053 mono_arch_create_rgctx_lazy_fetch_trampoline (offset, &info, TRUE);
6054 emit_trampoline (acfg, acfg->got_offset, info);
6056 offset = MONO_RGCTX_SLOT_MAKE_MRGCTX (i);
6057 mono_arch_create_rgctx_lazy_fetch_trampoline (offset, &info, TRUE);
6058 emit_trampoline (acfg, acfg->got_offset, info);
6061 #ifdef MONO_ARCH_HAVE_GENERAL_RGCTX_LAZY_FETCH_TRAMPOLINE
6062 mono_arch_create_general_rgctx_lazy_fetch_trampoline (&info, TRUE);
6063 emit_trampoline (acfg, acfg->got_offset, info);
6069 /* delegate_invoke_impl trampolines */
6070 l = mono_arch_get_delegate_invoke_impls ();
6072 MonoTrampInfo *info = l->data;
6074 emit_trampoline (acfg, acfg->got_offset, info);
6079 #endif /* #ifdef MONO_ARCH_HAVE_FULL_AOT_TRAMPOLINES */
6081 /* Emit trampolines which are numerous */
6084 * These include the following:
6085 * - specific trampolines
6086 * - static rgctx invoke trampolines
6088 * These trampolines have the same code, they are parameterized by GOT
6090 * They are defined in this file, in the arch_... routines instead of
6091 * in tramp-<ARCH>.c, since it is easier to do it this way.
6095 * When running in aot-only mode, we can't create specific trampolines at
6096 * runtime, so we create a few, and save them in the AOT file.
6097 * Normal trampolines embed their argument as a literal inside the
6098 * trampoline code, we can't do that here, so instead we embed an offset
6099 * which needs to be added to the trampoline address to get the address of
6100 * the GOT slot which contains the argument value.
6101 * The generated trampolines jump to the generic trampolines using another
6102 * GOT slot, which will be setup by the AOT loader to point to the
6103 * generic trampoline code of the given type.
6107 * FIXME: Maybe we should use more specific trampolines (i.e. one class init for
6111 emit_section_change (acfg, ".text", 0);
6113 tramp_got_offset = acfg->got_offset;
6115 for (ntype = 0; ntype < MONO_AOT_TRAMP_NUM; ++ntype) {
6117 case MONO_AOT_TRAMP_SPECIFIC:
6118 sprintf (symbol, "specific_trampolines");
6120 case MONO_AOT_TRAMP_STATIC_RGCTX:
6121 sprintf (symbol, "static_rgctx_trampolines");
6123 case MONO_AOT_TRAMP_IMT_THUNK:
6124 sprintf (symbol, "imt_thunks");
6126 case MONO_AOT_TRAMP_GSHAREDVT_ARG:
6127 sprintf (symbol, "gsharedvt_arg_trampolines");
6130 g_assert_not_reached ();
6133 sprintf (end_symbol, "%s_e", symbol);
6135 if (acfg->aot_opts.write_symbols)
6136 emit_local_symbol (acfg, symbol, end_symbol, TRUE);
6138 emit_alignment (acfg, AOT_FUNC_ALIGNMENT);
6139 emit_label (acfg, symbol);
6141 acfg->trampoline_got_offset_base [ntype] = tramp_got_offset;
6143 for (i = 0; i < acfg->num_trampolines [ntype]; ++i) {
6147 case MONO_AOT_TRAMP_SPECIFIC:
6148 arch_emit_specific_trampoline (acfg, tramp_got_offset, &tramp_size);
6149 tramp_got_offset += 2;
6151 case MONO_AOT_TRAMP_STATIC_RGCTX:
6152 arch_emit_static_rgctx_trampoline (acfg, tramp_got_offset, &tramp_size);
6153 tramp_got_offset += 2;
6155 case MONO_AOT_TRAMP_IMT_THUNK:
6156 arch_emit_imt_thunk (acfg, tramp_got_offset, &tramp_size);
6157 tramp_got_offset += 1;
6159 case MONO_AOT_TRAMP_GSHAREDVT_ARG:
6160 arch_emit_gsharedvt_arg_trampoline (acfg, tramp_got_offset, &tramp_size);
6161 tramp_got_offset += 2;
6164 g_assert_not_reached ();
6166 #ifdef __native_client_codegen__
6167 /* align to avoid 32-byte boundary crossings */
6168 emit_alignment (acfg, AOT_FUNC_ALIGNMENT);
6171 if (!acfg->trampoline_size [ntype]) {
6172 g_assert (tramp_size);
6173 acfg->trampoline_size [ntype] = tramp_size;
6177 emit_label (acfg, end_symbol);
6178 emit_int32 (acfg, 0);
6181 arch_emit_specific_trampoline_pages (acfg);
6183 /* Reserve some entries at the end of the GOT for our use */
6184 acfg->num_trampoline_got_entries = tramp_got_offset - acfg->got_offset;
6187 acfg->got_offset += acfg->num_trampoline_got_entries;
6191 str_begins_with (const char *str1, const char *str2)
6193 int len = strlen (str2);
6194 return strncmp (str1, str2, len) == 0;
6198 mono_aot_readonly_field_override (MonoClassField *field)
6201 for (rdv = readonly_values; rdv; rdv = rdv->next) {
6202 char *p = rdv->name;
6204 len = strlen (field->parent->name_space);
6205 if (strncmp (p, field->parent->name_space, len))
6210 len = strlen (field->parent->name);
6211 if (strncmp (p, field->parent->name, len))
6216 if (strcmp (p, field->name))
6218 switch (rdv->type) {
6220 return &rdv->value.i1;
6222 return &rdv->value.i2;
6224 return &rdv->value.i4;
6233 add_readonly_value (MonoAotOptions *opts, const char *val)
6238 /* the format of val is:
6239 * namespace.typename.fieldname=type/value
6240 * type can be i1 for uint8/int8/boolean, i2 for uint16/int16/char, i4 for uint32/int32
6242 fval = strrchr (val, '/');
6244 fprintf (stderr, "AOT : invalid format for readonly field '%s', missing /.\n", val);
6247 tval = strrchr (val, '=');
6249 fprintf (stderr, "AOT : invalid format for readonly field '%s', missing =.\n", val);
6252 rdv = g_new0 (ReadOnlyValue, 1);
6253 rdv->name = g_malloc0 (tval - val + 1);
6254 memcpy (rdv->name, val, tval - val);
6257 if (strncmp (tval, "i1", 2) == 0) {
6258 rdv->value.i1 = atoi (fval);
6259 rdv->type = MONO_TYPE_I1;
6260 } else if (strncmp (tval, "i2", 2) == 0) {
6261 rdv->value.i2 = atoi (fval);
6262 rdv->type = MONO_TYPE_I2;
6263 } else if (strncmp (tval, "i4", 2) == 0) {
6264 rdv->value.i4 = atoi (fval);
6265 rdv->type = MONO_TYPE_I4;
6267 fprintf (stderr, "AOT : unsupported type for readonly field '%s'.\n", tval);
6270 rdv->next = readonly_values;
6271 readonly_values = rdv;
6275 mono_aot_parse_options (const char *aot_options, MonoAotOptions *opts)
6277 gchar **args, **ptr;
6279 args = g_strsplit (aot_options ? aot_options : "", ",", -1);
6280 for (ptr = args; ptr && *ptr; ptr ++) {
6281 const char *arg = *ptr;
6283 if (str_begins_with (arg, "outfile=")) {
6284 opts->outfile = g_strdup (arg + strlen ("outfile="));
6285 } else if (str_begins_with (arg, "save-temps")) {
6286 opts->save_temps = TRUE;
6287 } else if (str_begins_with (arg, "keep-temps")) {
6288 opts->save_temps = TRUE;
6289 } else if (str_begins_with (arg, "write-symbols")) {
6290 opts->write_symbols = TRUE;
6291 } else if (str_begins_with (arg, "no-write-symbols")) {
6292 opts->write_symbols = FALSE;
6293 } else if (str_begins_with (arg, "metadata-only")) {
6294 opts->metadata_only = TRUE;
6295 } else if (str_begins_with (arg, "bind-to-runtime-version")) {
6296 opts->bind_to_runtime_version = TRUE;
6297 } else if (str_begins_with (arg, "full")) {
6298 opts->full_aot = TRUE;
6299 } else if (str_begins_with (arg, "threads=")) {
6300 opts->nthreads = atoi (arg + strlen ("threads="));
6301 } else if (str_begins_with (arg, "static")) {
6302 opts->static_link = TRUE;
6303 opts->no_dlsym = TRUE;
6304 } else if (str_begins_with (arg, "asmonly")) {
6305 opts->asm_only = TRUE;
6306 } else if (str_begins_with (arg, "asmwriter")) {
6307 opts->asm_writer = TRUE;
6308 } else if (str_begins_with (arg, "nodebug")) {
6309 opts->nodebug = TRUE;
6310 } else if (str_begins_with (arg, "dwarfdebug")) {
6311 opts->dwarf_debug = TRUE;
6312 } else if (str_begins_with (arg, "nopagetrampolines")) {
6313 opts->use_trampolines_page = FALSE;
6314 } else if (str_begins_with (arg, "ntrampolines=")) {
6315 opts->ntrampolines = atoi (arg + strlen ("ntrampolines="));
6316 } else if (str_begins_with (arg, "nrgctx-trampolines=")) {
6317 opts->nrgctx_trampolines = atoi (arg + strlen ("nrgctx-trampolines="));
6318 } else if (str_begins_with (arg, "nimt-trampolines=")) {
6319 opts->nimt_trampolines = atoi (arg + strlen ("nimt-trampolines="));
6320 } else if (str_begins_with (arg, "ngsharedvt-trampolines=")) {
6321 opts->ngsharedvt_arg_trampolines = atoi (arg + strlen ("ngsharedvt-trampolines="));
6322 } else if (str_begins_with (arg, "autoreg")) {
6323 opts->autoreg = TRUE;
6324 } else if (str_begins_with (arg, "tool-prefix=")) {
6325 opts->tool_prefix = g_strdup (arg + strlen ("tool-prefix="));
6326 } else if (str_begins_with (arg, "soft-debug")) {
6327 opts->soft_debug = TRUE;
6328 } else if (str_begins_with (arg, "direct-pinvoke")) {
6329 opts->direct_pinvoke = TRUE;
6330 } else if (str_begins_with (arg, "direct-icalls")) {
6331 opts->direct_icalls = TRUE;
6332 #if defined(TARGET_ARM) || defined(TARGET_ARM64)
6333 } else if (str_begins_with (arg, "iphone-abi")) {
6334 // older full-aot users did depend on this.
6336 } else if (str_begins_with (arg, "no-direct-calls")) {
6337 opts->no_direct_calls = TRUE;
6338 } else if (str_begins_with (arg, "print-skipped")) {
6339 opts->print_skipped_methods = TRUE;
6340 } else if (str_begins_with (arg, "stats")) {
6342 } else if (str_begins_with (arg, "no-instances")) {
6343 opts->no_instances = TRUE;
6344 } else if (str_begins_with (arg, "log-generics")) {
6345 opts->log_generics = TRUE;
6346 } else if (str_begins_with (arg, "log-instances=")) {
6347 opts->log_instances = TRUE;
6348 opts->instances_logfile_path = g_strdup (arg + strlen ("log-instances="));
6349 } else if (str_begins_with (arg, "log-instances")) {
6350 opts->log_instances = TRUE;
6351 } else if (str_begins_with (arg, "internal-logfile=")) {
6352 opts->logfile = g_strdup (arg + strlen ("internal-logfile="));
6353 } else if (str_begins_with (arg, "mtriple=")) {
6354 opts->mtriple = g_strdup (arg + strlen ("mtriple="));
6355 } else if (str_begins_with (arg, "llvm-path=")) {
6356 opts->llvm_path = g_strdup (arg + strlen ("llvm-path="));
6357 } else if (!strcmp (arg, "llvm")) {
6359 } else if (str_begins_with (arg, "readonly-value=")) {
6360 add_readonly_value (opts, arg + strlen ("readonly-value="));
6361 } else if (str_begins_with (arg, "info")) {
6362 printf ("AOT target setup: %s.\n", AOT_TARGET_STR);
6364 } else if (str_begins_with (arg, "gc-maps")) {
6365 mini_gc_enable_gc_maps_for_aot ();
6366 } else if (str_begins_with (arg, "help") || str_begins_with (arg, "?")) {
6367 printf ("Supported options for --aot:\n");
6368 printf (" outfile=\n");
6369 printf (" save-temps\n");
6370 printf (" keep-temps\n");
6371 printf (" write-symbols\n");
6372 printf (" metadata-only\n");
6373 printf (" bind-to-runtime-version\n");
6375 printf (" threads=\n");
6376 printf (" static\n");
6377 printf (" asmonly\n");
6378 printf (" asmwriter\n");
6379 printf (" nodebug\n");
6380 printf (" dwarfdebug\n");
6381 printf (" ntrampolines=\n");
6382 printf (" nrgctx-trampolines=\n");
6383 printf (" nimt-trampolines=\n");
6384 printf (" ngsharedvt-trampolines=\n");
6385 printf (" autoreg\n");
6386 printf (" tool-prefix=\n");
6387 printf (" readonly-value=\n");
6388 printf (" soft-debug\n");
6389 printf (" gc-maps\n");
6390 printf (" print-skipped\n");
6391 printf (" no-instances\n");
6392 printf (" stats\n");
6394 printf (" help/?\n");
6397 fprintf (stderr, "AOT : Unknown argument '%s'.\n", arg);
6402 if (opts->use_trampolines_page) {
6403 opts->ntrampolines = 0;
6404 opts->nrgctx_trampolines = 0;
6405 opts->nimt_trampolines = 0;
6406 opts->ngsharedvt_arg_trampolines = 0;
6412 add_token_info_hash (gpointer key, gpointer value, gpointer user_data)
6414 MonoMethod *method = (MonoMethod*)key;
6415 MonoJumpInfoToken *ji = (MonoJumpInfoToken*)value;
6416 MonoAotCompile *acfg = user_data;
6417 MonoJumpInfoToken *new_ji;
6419 new_ji = mono_mempool_alloc0 (acfg->mempool, sizeof (MonoJumpInfoToken));
6420 new_ji->image = ji->image;
6421 new_ji->token = ji->token;
6422 g_hash_table_insert (acfg->token_info_hash, method, new_ji);
6426 can_encode_class (MonoAotCompile *acfg, MonoClass *klass)
6428 if (klass->type_token)
6430 if ((klass->byval_arg.type == MONO_TYPE_VAR) || (klass->byval_arg.type == MONO_TYPE_MVAR) || (klass->byval_arg.type == MONO_TYPE_PTR))
6433 return can_encode_class (acfg, klass->element_class);
6438 can_encode_method (MonoAotCompile *acfg, MonoMethod *method)
6440 if (method->wrapper_type) {
6441 switch (method->wrapper_type) {
6442 case MONO_WRAPPER_NONE:
6443 case MONO_WRAPPER_REMOTING_INVOKE_WITH_CHECK:
6444 case MONO_WRAPPER_XDOMAIN_INVOKE:
6445 case MONO_WRAPPER_STFLD:
6446 case MONO_WRAPPER_LDFLD:
6447 case MONO_WRAPPER_LDFLDA:
6448 case MONO_WRAPPER_LDFLD_REMOTE:
6449 case MONO_WRAPPER_STFLD_REMOTE:
6450 case MONO_WRAPPER_STELEMREF:
6451 case MONO_WRAPPER_ISINST:
6452 case MONO_WRAPPER_PROXY_ISINST:
6453 case MONO_WRAPPER_ALLOC:
6454 case MONO_WRAPPER_REMOTING_INVOKE:
6455 case MONO_WRAPPER_UNKNOWN:
6456 case MONO_WRAPPER_WRITE_BARRIER:
6457 case MONO_WRAPPER_DELEGATE_INVOKE:
6458 case MONO_WRAPPER_DELEGATE_BEGIN_INVOKE:
6459 case MONO_WRAPPER_DELEGATE_END_INVOKE:
6460 case MONO_WRAPPER_SYNCHRONIZED:
6462 case MONO_WRAPPER_MANAGED_TO_MANAGED:
6463 case MONO_WRAPPER_CASTCLASS: {
6464 WrapperInfo *info = mono_marshal_get_wrapper_info (method);
6473 //printf ("Skip (wrapper call): %d -> %s\n", patch_info->type, mono_method_full_name (patch_info->data.method, TRUE));
6477 if (!method->token) {
6478 /* The method is part of a constructed type like Int[,].Set (). */
6479 if (!g_hash_table_lookup (acfg->token_info_hash, method)) {
6480 if (method->klass->rank)
6490 can_encode_patch (MonoAotCompile *acfg, MonoJumpInfo *patch_info)
6492 switch (patch_info->type) {
6493 case MONO_PATCH_INFO_METHOD:
6494 case MONO_PATCH_INFO_METHODCONST:
6495 case MONO_PATCH_INFO_METHOD_CODE_SLOT: {
6496 MonoMethod *method = patch_info->data.method;
6498 return can_encode_method (acfg, method);
6500 case MONO_PATCH_INFO_VTABLE:
6501 case MONO_PATCH_INFO_CLASS_INIT:
6502 case MONO_PATCH_INFO_CLASS:
6503 case MONO_PATCH_INFO_IID:
6504 case MONO_PATCH_INFO_ADJUSTED_IID:
6505 if (!can_encode_class (acfg, patch_info->data.klass)) {
6506 //printf ("Skip: %s\n", mono_type_full_name (&patch_info->data.klass->byval_arg));
6510 case MONO_PATCH_INFO_DELEGATE_TRAMPOLINE: {
6511 if (!can_encode_class (acfg, patch_info->data.del_tramp->klass)) {
6512 //printf ("Skip: %s\n", mono_type_full_name (&patch_info->data.klass->byval_arg));
6517 case MONO_PATCH_INFO_RGCTX_FETCH: {
6518 MonoJumpInfoRgctxEntry *entry = patch_info->data.rgctx_entry;
6520 if (!can_encode_method (acfg, entry->method))
6522 if (!can_encode_patch (acfg, entry->data))
6536 * AOT compile a given method.
6537 * This function might be called by multiple threads, so it must be thread-safe.
6540 compile_method (MonoAotCompile *acfg, MonoMethod *method)
6543 MonoJumpInfo *patch_info;
6546 MonoMethod *wrapped;
6549 if (acfg->aot_opts.metadata_only)
6552 mono_acfg_lock (acfg);
6553 index = get_method_index (acfg, method);
6554 mono_acfg_unlock (acfg);
6556 /* fixme: maybe we can also precompile wrapper methods */
6557 if ((method->flags & METHOD_ATTRIBUTE_PINVOKE_IMPL) ||
6558 (method->iflags & METHOD_IMPL_ATTRIBUTE_RUNTIME) ||
6559 (method->flags & METHOD_ATTRIBUTE_ABSTRACT)) {
6560 //printf ("Skip (impossible): %s\n", mono_method_full_name (method, TRUE));
6564 if (method->iflags & METHOD_IMPL_ATTRIBUTE_INTERNAL_CALL)
6567 wrapped = mono_marshal_method_from_wrapper (method);
6568 if (wrapped && (wrapped->iflags & METHOD_IMPL_ATTRIBUTE_INTERNAL_CALL) && wrapped->is_generic)
6569 // FIXME: The wrapper should be generic too, but it is not
6572 if (method->wrapper_type == MONO_WRAPPER_COMINTEROP)
6575 InterlockedIncrement (&acfg->stats.mcount);
6578 if (method->is_generic || method->klass->generic_container) {
6579 InterlockedIncrement (&acfg->stats.genericcount);
6584 //acfg->aot_opts.print_skipped_methods = TRUE;
6587 * Since these methods are the only ones which are compiled with
6588 * AOT support, and they are not used by runtime startup/shutdown code,
6589 * the runtime will not see AOT methods during AOT compilation,so it
6590 * does not need to support them by creating a fake GOT etc.
6592 flags = JIT_FLAG_AOT;
6593 if (acfg->aot_opts.full_aot)
6594 flags |= JIT_FLAG_FULL_AOT;
6596 flags |= JIT_FLAG_LLVM;
6597 cfg = mini_method_compile (method, acfg->opts, mono_get_root_domain (), flags, 0);
6598 mono_loader_clear_error ();
6600 if (cfg->exception_type == MONO_EXCEPTION_GENERIC_SHARING_FAILED) {
6601 if (acfg->aot_opts.print_skipped_methods)
6602 printf ("Skip (gshared failure): %s (%s)\n", mono_method_full_name (method, TRUE), cfg->exception_message);
6603 InterlockedIncrement (&acfg->stats.genericcount);
6606 if (cfg->exception_type != MONO_EXCEPTION_NONE) {
6607 if (acfg->aot_opts.print_skipped_methods)
6608 printf ("Skip (JIT failure): %s\n", mono_method_full_name (method, TRUE));
6609 /* Let the exception happen at runtime */
6613 if (cfg->disable_aot) {
6614 if (acfg->aot_opts.print_skipped_methods)
6615 printf ("Skip (disabled): %s\n", mono_method_full_name (method, TRUE));
6616 InterlockedIncrement (&acfg->stats.ocount);
6617 mono_destroy_compile (cfg);
6620 cfg->method_index = index;
6622 /* Nullify patches which need no aot processing */
6623 for (patch_info = cfg->patch_info; patch_info; patch_info = patch_info->next) {
6624 switch (patch_info->type) {
6625 case MONO_PATCH_INFO_LABEL:
6626 case MONO_PATCH_INFO_BB:
6627 patch_info->type = MONO_PATCH_INFO_NONE;
6634 /* Collect method->token associations from the cfg */
6635 mono_acfg_lock (acfg);
6636 g_hash_table_foreach (cfg->token_info_hash, add_token_info_hash, acfg);
6637 mono_acfg_unlock (acfg);
6638 g_hash_table_destroy (cfg->token_info_hash);
6639 cfg->token_info_hash = NULL;
6642 * Check for absolute addresses.
6645 for (patch_info = cfg->patch_info; patch_info; patch_info = patch_info->next) {
6646 switch (patch_info->type) {
6647 case MONO_PATCH_INFO_ABS:
6648 /* unable to handle this */
6657 if (acfg->aot_opts.print_skipped_methods)
6658 printf ("Skip (abs call): %s\n", mono_method_full_name (method, TRUE));
6659 InterlockedIncrement (&acfg->stats.abscount);
6660 mono_destroy_compile (cfg);
6664 /* Lock for the rest of the code */
6665 mono_acfg_lock (acfg);
6668 * Check for methods/klasses we can't encode.
6671 for (patch_info = cfg->patch_info; patch_info; patch_info = patch_info->next) {
6672 if (!can_encode_patch (acfg, patch_info))
6677 if (acfg->aot_opts.print_skipped_methods)
6678 printf ("Skip (patches): %s\n", mono_method_full_name (method, TRUE));
6679 acfg->stats.ocount++;
6680 mono_destroy_compile (cfg);
6681 mono_acfg_unlock (acfg);
6685 if (method->is_inflated && acfg->aot_opts.log_instances) {
6686 if (acfg->instances_logfile)
6687 fprintf (acfg->instances_logfile, "%s ### %d\n", mono_method_full_name (method, TRUE), cfg->code_size);
6689 printf ("%s ### %d\n", mono_method_full_name (method, TRUE), cfg->code_size);
6692 /* Adds generic instances referenced by this method */
6694 * The depth is used to avoid infinite loops when generic virtual recursion is
6697 depth = GPOINTER_TO_UINT (g_hash_table_lookup (acfg->method_depth, method));
6698 if (!acfg->aot_opts.no_instances && depth < 32) {
6699 for (patch_info = cfg->patch_info; patch_info; patch_info = patch_info->next) {
6700 switch (patch_info->type) {
6701 case MONO_PATCH_INFO_METHOD: {
6702 MonoMethod *m = patch_info->data.method;
6703 if (m->is_inflated) {
6704 if (!(mono_class_generic_sharing_enabled (m->klass) &&
6705 mono_method_is_generic_sharable_full (m, FALSE, FALSE, FALSE)) &&
6706 !method_has_type_vars (m)) {
6707 if (m->iflags & METHOD_IMPL_ATTRIBUTE_INTERNAL_CALL) {
6708 if (acfg->aot_opts.full_aot)
6709 add_extra_method_with_depth (acfg, mono_marshal_get_native_wrapper (m, TRUE, TRUE), depth + 1);
6711 add_extra_method_with_depth (acfg, m, depth + 1);
6712 add_types_from_method_header (acfg, m);
6715 add_generic_class_with_depth (acfg, m->klass, depth + 5, "method");
6717 if (m->wrapper_type == MONO_WRAPPER_MANAGED_TO_MANAGED && !strcmp (m->name, "ElementAddr"))
6718 add_extra_method_with_depth (acfg, m, depth + 1);
6721 case MONO_PATCH_INFO_VTABLE: {
6722 MonoClass *klass = patch_info->data.klass;
6724 if (klass->generic_class && !mini_class_is_generic_sharable (klass))
6725 add_generic_class_with_depth (acfg, klass, depth + 5, "vtable");
6728 case MONO_PATCH_INFO_SFLDA: {
6729 MonoClass *klass = patch_info->data.field->parent;
6731 /* The .cctor needs to run at runtime. */
6732 if (klass->generic_class && !mono_generic_context_is_sharable (&klass->generic_class->context, FALSE) && mono_class_get_cctor (klass))
6733 add_extra_method_with_depth (acfg, mono_class_get_cctor (klass), depth + 1);
6742 /* Determine whenever the method has GOT slots */
6743 for (patch_info = cfg->patch_info; patch_info; patch_info = patch_info->next) {
6744 switch (patch_info->type) {
6745 case MONO_PATCH_INFO_GOT_OFFSET:
6746 case MONO_PATCH_INFO_NONE:
6747 case MONO_PATCH_INFO_GC_CARD_TABLE_ADDR:
6749 case MONO_PATCH_INFO_IMAGE:
6750 /* The assembly is stored in GOT slot 0 */
6751 if (patch_info->data.image != acfg->image)
6752 cfg->has_got_slots = TRUE;
6755 if (!is_plt_patch (patch_info))
6756 cfg->has_got_slots = TRUE;
6761 if (!cfg->has_got_slots)
6762 InterlockedIncrement (&acfg->stats.methods_without_got_slots);
6765 * FIXME: Instead of this mess, allocate the patches from the aot mempool.
6767 /* Make a copy of the patch info which is in the mempool */
6769 MonoJumpInfo *patches = NULL, *patches_end = NULL;
6771 for (patch_info = cfg->patch_info; patch_info; patch_info = patch_info->next) {
6772 MonoJumpInfo *new_patch_info = mono_patch_info_dup_mp (acfg->mempool, patch_info);
6775 patches = new_patch_info;
6777 patches_end->next = new_patch_info;
6778 patches_end = new_patch_info;
6780 cfg->patch_info = patches;
6782 /* Make a copy of the unwind info */
6784 GSList *l, *unwind_ops;
6788 for (l = cfg->unwind_ops; l; l = l->next) {
6789 op = mono_mempool_alloc (acfg->mempool, sizeof (MonoUnwindOp));
6790 memcpy (op, l->data, sizeof (MonoUnwindOp));
6791 unwind_ops = g_slist_prepend_mempool (acfg->mempool, unwind_ops, op);
6793 cfg->unwind_ops = g_slist_reverse (unwind_ops);
6795 /* Make a copy of the argument/local info */
6797 MonoInst **args, **locals;
6798 MonoMethodSignature *sig;
6799 MonoMethodHeader *header;
6802 sig = mono_method_signature (method);
6803 args = mono_mempool_alloc (acfg->mempool, sizeof (MonoInst*) * (sig->param_count + sig->hasthis));
6804 for (i = 0; i < sig->param_count + sig->hasthis; ++i) {
6805 args [i] = mono_mempool_alloc (acfg->mempool, sizeof (MonoInst));
6806 memcpy (args [i], cfg->args [i], sizeof (MonoInst));
6810 header = mono_method_get_header (method);
6811 locals = mono_mempool_alloc (acfg->mempool, sizeof (MonoInst*) * header->num_locals);
6812 for (i = 0; i < header->num_locals; ++i) {
6813 locals [i] = mono_mempool_alloc (acfg->mempool, sizeof (MonoInst));
6814 memcpy (locals [i], cfg->locals [i], sizeof (MonoInst));
6816 cfg->locals = locals;
6819 /* Free some fields used by cfg to conserve memory */
6820 mono_mempool_destroy (cfg->mempool);
6821 cfg->mempool = NULL;
6822 g_free (cfg->varinfo);
6823 cfg->varinfo = NULL;
6827 mono_regstate_free (cfg->rs);
6831 //printf ("Compile: %s\n", mono_method_full_name (method, TRUE));
6833 while (index >= acfg->cfgs_size) {
6834 MonoCompile **new_cfgs;
6837 new_size = acfg->cfgs_size * 2;
6838 new_cfgs = g_new0 (MonoCompile*, new_size);
6839 memcpy (new_cfgs, acfg->cfgs, sizeof (MonoCompile*) * acfg->cfgs_size);
6840 g_free (acfg->cfgs);
6841 acfg->cfgs = new_cfgs;
6842 acfg->cfgs_size = new_size;
6844 acfg->cfgs [index] = cfg;
6846 g_hash_table_insert (acfg->method_to_cfg, cfg->orig_method, cfg);
6849 if (cfg->orig_method->wrapper_type)
6850 g_ptr_array_add (acfg->extra_methods, cfg->orig_method);
6853 mono_acfg_unlock (acfg);
6855 InterlockedIncrement (&acfg->stats.ccount);
6859 compile_thread_main (gpointer *user_data)
6861 MonoDomain *domain = user_data [0];
6862 MonoAotCompile *acfg = user_data [1];
6863 GPtrArray *methods = user_data [2];
6866 mono_thread_attach (domain);
6868 for (i = 0; i < methods->len; ++i)
6869 compile_method (acfg, g_ptr_array_index (methods, i));
6873 load_profile_files (MonoAotCompile *acfg)
6877 int file_index, res, method_index, i;
6880 GList *unordered, *l;
6885 tmp = g_strdup_printf ("%s/.mono/aot-profile-data/%s-%d", g_get_home_dir (), acfg->image->assembly_name, file_index);
6887 if (!g_file_test (tmp, G_FILE_TEST_IS_REGULAR)) {
6892 infile = fopen (tmp, "r");
6895 printf ("Using profile data file '%s'\n", tmp);
6900 res = fscanf (infile, "%32s\n", ver);
6901 if ((res != 1) || strcmp (ver, "#VER:2") != 0) {
6902 printf ("Profile file has wrong version or invalid.\n");
6909 MonoMethodDesc *desc;
6912 if (fgets (name, 1023, infile) == NULL)
6915 /* Kill the newline */
6916 if (strlen (name) > 0)
6917 name [strlen (name) - 1] = '\0';
6919 desc = mono_method_desc_new (name, TRUE);
6921 method = mono_method_desc_search_in_image (desc, acfg->image);
6923 if (method && mono_method_get_token (method)) {
6924 token = mono_method_get_token (method);
6925 method_index = mono_metadata_token_index (token) - 1;
6928 for (i = 0; i < acfg->method_order->len; ++i) {
6929 if (g_ptr_array_index (acfg->method_order, i) == GUINT_TO_POINTER (method_index)) {
6935 g_ptr_array_add (acfg->method_order, GUINT_TO_POINTER (method_index));
6937 //printf ("No method found matching '%s'.\n", name);
6943 /* Add missing methods */
6945 for (method_index = 0; method_index < acfg->image->tables [MONO_TABLE_METHOD].rows; ++method_index) {
6947 for (i = 0; i < acfg->method_order->len; ++i) {
6948 if (g_ptr_array_index (acfg->method_order, i) == GUINT_TO_POINTER (method_index)) {
6954 unordered = g_list_prepend (unordered, GUINT_TO_POINTER (method_index));
6956 unordered = g_list_reverse (unordered);
6957 for (l = unordered; l; l = l->next)
6958 g_ptr_array_add (acfg->method_order, l->data);
6961 /* Used by the LLVM backend */
6963 mono_aot_get_got_offset (MonoJumpInfo *ji)
6965 return get_got_offset (llvm_acfg, ji);
6969 mono_aot_get_method_name (MonoCompile *cfg)
6971 if (llvm_acfg->aot_opts.static_link)
6972 /* Include the assembly name too to avoid duplicate symbol errors */
6973 return g_strdup_printf ("%s_%s", llvm_acfg->assembly_name_sym, get_debug_sym (cfg->orig_method, "", llvm_acfg->method_label_hash));
6975 return get_debug_sym (cfg->orig_method, "", llvm_acfg->method_label_hash);
6979 mono_aot_is_direct_callable (MonoJumpInfo *patch_info)
6981 return is_direct_callable (llvm_acfg, NULL, patch_info);
6985 mono_aot_mark_unused_llvm_plt_entry (MonoJumpInfo *patch_info)
6987 MonoPltEntry *plt_entry;
6989 plt_entry = get_plt_entry (llvm_acfg, patch_info);
6990 plt_entry->llvm_used = FALSE;
6994 mono_aot_get_plt_symbol (MonoJumpInfoType type, gconstpointer data)
6996 MonoJumpInfo *ji = mono_mempool_alloc (llvm_acfg->mempool, sizeof (MonoJumpInfo));
6997 MonoPltEntry *plt_entry;
7000 ji->data.target = data;
7002 if (!can_encode_patch (llvm_acfg, ji))
7005 plt_entry = get_plt_entry (llvm_acfg, ji);
7006 plt_entry->llvm_used = TRUE;
7008 #if defined(TARGET_MACH)
7009 return g_strdup_printf (plt_entry->llvm_symbol + strlen (llvm_acfg->llvm_label_prefix));
7011 return g_strdup_printf (plt_entry->llvm_symbol);
7016 mono_aot_get_method_index (MonoMethod *method)
7018 g_assert (llvm_acfg);
7019 return get_method_index (llvm_acfg, method);
7023 mono_aot_patch_info_dup (MonoJumpInfo* ji)
7027 mono_acfg_lock (llvm_acfg);
7028 res = mono_patch_info_dup_mp (llvm_acfg->mempool, ji);
7029 mono_acfg_unlock (llvm_acfg);
7039 * Emit the LLVM code into an LLVM bytecode file, and compile it using the LLVM
7043 emit_llvm_file (MonoAotCompile *acfg)
7045 char *command, *opts, *tempbc;
7047 MonoJumpInfo *patch_info;
7050 * When using LLVM, we let llvm emit the got since the LLVM IL needs to refer
7054 /* Compute the final size of the got */
7055 for (i = 0; i < acfg->nmethods; ++i) {
7056 if (acfg->cfgs [i]) {
7057 for (patch_info = acfg->cfgs [i]->patch_info; patch_info; patch_info = patch_info->next) {
7058 if (patch_info->type != MONO_PATCH_INFO_NONE) {
7059 if (!is_plt_patch (patch_info))
7060 get_got_offset (acfg, patch_info);
7062 get_plt_entry (acfg, patch_info);
7068 acfg->final_got_size = acfg->got_offset + acfg->plt_offset;
7070 if (acfg->aot_opts.full_aot) {
7074 * Need to add the got entries used by the trampolines.
7075 * This is only a conservative approximation.
7077 if (strcmp (acfg->image->assembly->aname.name, "mscorlib") == 0) {
7078 /* For the generic + rgctx trampolines */
7079 acfg->final_got_size += 400;
7080 /* For the specific trampolines */
7081 for (ntype = 0; ntype < MONO_AOT_TRAMP_NUM; ++ntype)
7082 acfg->final_got_size += acfg->num_trampolines [ntype] * 2;
7087 tempbc = g_strdup_printf ("%s.bc", acfg->tmpbasename);
7088 mono_llvm_emit_aot_module (tempbc, g_path_get_basename (acfg->image->name), acfg->final_got_size);
7092 * FIXME: Experiment with adding optimizations, the -std-compile-opts set takes
7093 * a lot of time, and doesn't seem to save much space.
7094 * The following optimizations cannot be enabled:
7096 * - 'jump-threading' changes our blockaddress references to int constants.
7097 * - 'basiccg' fails because it contains:
7098 * if (CS && !isa<IntrinsicInst>(II)) {
7099 * and isa<IntrinsicInst> is false for invokes to intrinsics (iltests.exe).
7100 * - 'prune-eh' and 'functionattrs' depend on 'basiccg'.
7101 * The opt list below was produced by taking the output of:
7102 * llvm-as < /dev/null | opt -O2 -disable-output -debug-pass=Arguments
7103 * then removing tailcallelim + the global opts.
7104 * strip-dead-prototypes deletes unused intrinsics definitions.
7106 opts = g_strdup ("-instcombine -simplifycfg");
7107 //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");
7108 /* The dse pass is disabled because of #13734 and #17616 */
7110 * The dse bug is in DeadStoreElimination.cpp:isOverwrite ():
7111 * // If we have no DataLayout information around, then the size of the store
7112 * // is inferrable from the pointee type. If they are the same type, then
7113 * // we know that the store is safe.
7114 * if (AA.getDataLayout() == 0 &&
7115 * Later.Ptr->getType() == Earlier.Ptr->getType()) {
7116 * return OverwriteComplete;
7117 * Here, if 'Earlier' refers to a memset, and Later has no size info, it mistakenly thinks the memset is redundant.
7119 opts = g_strdup ("-targetlibinfo -no-aa -basicaa -notti -instcombine -simplifycfg -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");
7121 command = g_strdup_printf ("%sopt -f %s -o \"%s.opt.bc\" \"%s.bc\"", acfg->aot_opts.llvm_path, opts, acfg->tmpbasename, acfg->tmpbasename);
7122 aot_printf (acfg, "Executing opt: %s\n", command);
7123 if (system (command) != 0)
7128 if (!acfg->llc_args)
7129 acfg->llc_args = g_string_new ("");
7131 /* Verbose asm slows down llc greatly */
7132 g_string_append (acfg->llc_args, " -asm-verbose=false");
7134 if (acfg->aot_opts.mtriple)
7135 g_string_append_printf (acfg->llc_args, " -mtriple=%s", acfg->aot_opts.mtriple);
7137 #if defined(TARGET_MACH) && defined(TARGET_ARM)
7138 /* ios requires PIC code now */
7139 g_string_append_printf (acfg->llc_args, " -relocation-model=pic");
7141 if (llvm_acfg->aot_opts.static_link)
7142 g_string_append_printf (acfg->llc_args, " -relocation-model=static");
7144 g_string_append_printf (acfg->llc_args, " -relocation-model=pic");
7146 unlink (acfg->tmpfname);
7148 command = g_strdup_printf ("%sllc %s -disable-gnu-eh-frame -enable-mono-eh-frame -o \"%s\" \"%s.opt.bc\"", acfg->aot_opts.llvm_path, acfg->llc_args->str, acfg->tmpfname, acfg->tmpbasename);
7150 aot_printf (acfg, "Executing llc: %s\n", command);
7152 if (system (command) != 0)
7159 emit_code (MonoAotCompile *acfg)
7161 int oindex, i, prev_index;
7164 #if defined(TARGET_POWERPC64)
7165 sprintf (symbol, ".Lgot_addr");
7166 emit_section_change (acfg, ".text", 0);
7167 emit_alignment (acfg, 8);
7168 emit_label (acfg, symbol);
7169 emit_pointer (acfg, acfg->got_symbol);
7173 * This global symbol is used to compute the address of each method using the
7174 * code_offsets array. It is also used to compute the memory ranges occupied by
7175 * AOT code, so it must be equal to the address of the first emitted method.
7177 emit_section_change (acfg, ".text", 0);
7178 emit_alignment (acfg, 8);
7180 for (i = 0; i < acfg->nmethods; ++i) {
7181 if (acfg->cfgs [i] && acfg->cfgs [i]->compile_llvm) {
7182 acfg->methods_symbol = g_strdup (acfg->cfgs [i]->asm_symbol);
7187 if (!acfg->methods_symbol) {
7188 sprintf (symbol, "methods");
7189 emit_label (acfg, symbol);
7190 acfg->methods_symbol = g_strdup (symbol);
7194 * Emit some padding so the local symbol for the first method doesn't have the
7195 * same address as 'methods'.
7197 #if defined(__default_codegen__)
7198 emit_zero_bytes (acfg, 16);
7199 #elif defined(__native_client_codegen__)
7201 const int kPaddingSize = 16;
7202 guint8 pad_buffer[kPaddingSize];
7203 mono_arch_nacl_pad (pad_buffer, kPaddingSize);
7204 emit_bytes (acfg, pad_buffer, kPaddingSize);
7208 for (oindex = 0; oindex < acfg->method_order->len; ++oindex) {
7212 i = GPOINTER_TO_UINT (g_ptr_array_index (acfg->method_order, oindex));
7214 cfg = acfg->cfgs [i];
7219 method = cfg->orig_method;
7221 /* Emit unbox trampoline */
7222 if (acfg->aot_opts.full_aot && cfg->orig_method->klass->valuetype) {
7223 sprintf (symbol, "ut_%d", get_method_index (acfg, method));
7225 emit_section_change (acfg, ".text", 0);
7226 #ifdef __native_client_codegen__
7227 emit_alignment (acfg, AOT_FUNC_ALIGNMENT);
7230 if (acfg->thumb_mixed && cfg->compile_llvm) {
7231 emit_set_thumb_mode (acfg);
7232 fprintf (acfg->fp, "\n.thumb_func\n");
7235 emit_label (acfg, symbol);
7237 arch_emit_unbox_trampoline (acfg, cfg, cfg->orig_method, cfg->asm_symbol);
7239 if (acfg->thumb_mixed && cfg->compile_llvm) {
7240 emit_set_arm_mode (acfg);
7244 if (cfg->compile_llvm)
7245 acfg->stats.llvm_count ++;
7247 emit_method_code (acfg, cfg);
7250 sprintf (symbol, "methods_end");
7251 emit_section_change (acfg, ".text", 0);
7252 emit_alignment (acfg, 8);
7253 emit_label (acfg, symbol);
7254 /* To distinguish it from the next symbol */
7255 emit_int32 (acfg, 0);
7258 * Add .no_dead_strip directives for all LLVM methods to prevent the OSX linker
7259 * from optimizing them away, since it doesn't see that code_offsets references them.
7260 * JITted methods don't need this since they are referenced using assembler local
7262 * FIXME: This is why write-symbols doesn't work on OSX ?
7264 if (acfg->llvm && acfg->need_no_dead_strip) {
7265 fprintf (acfg->fp, "\n");
7266 for (i = 0; i < acfg->nmethods; ++i) {
7267 if (acfg->cfgs [i] && acfg->cfgs [i]->compile_llvm)
7268 fprintf (acfg->fp, ".no_dead_strip %s\n", acfg->cfgs [i]->asm_symbol);
7272 if (acfg->direct_method_addresses) {
7273 acfg->flags |= MONO_AOT_FILE_FLAG_DIRECT_METHOD_ADDRESSES;
7276 * To work around linker issues, we emit a table of branches, and disassemble them at runtime.
7277 * This is PIE code, and the linker can update it if needed.
7279 sprintf (symbol, "method_addresses");
7280 emit_section_change (acfg, ".text", 1);
7281 emit_alignment (acfg, 8);
7282 emit_label (acfg, symbol);
7283 emit_local_symbol (acfg, symbol, "method_addresses_end", TRUE);
7284 emit_unset_mode (acfg);
7285 if (acfg->need_no_dead_strip)
7286 fprintf (acfg->fp, " .no_dead_strip %s\n", symbol);
7288 for (i = 0; i < acfg->nmethods; ++i) {
7289 #ifdef MONO_ARCH_AOT_SUPPORTED
7293 arch_emit_direct_call (acfg, acfg->cfgs [i]->asm_symbol, FALSE, acfg->thumb_mixed && acfg->cfgs [i]->compile_llvm, NULL, &call_size);
7295 arch_emit_direct_call (acfg, "method_addresses", FALSE, FALSE, NULL, &call_size);
7299 sprintf (symbol, "method_addresses_end");
7300 emit_label (acfg, symbol);
7303 sprintf (symbol, "code_offsets");
7304 emit_section_change (acfg, RODATA_SECT, 1);
7305 emit_alignment (acfg, 8);
7306 emit_label (acfg, symbol);
7307 emit_int32 (acfg, 0);
7309 sprintf (symbol, "code_offsets");
7310 emit_section_change (acfg, RODATA_SECT, 1);
7311 emit_alignment (acfg, 8);
7312 emit_label (acfg, symbol);
7314 acfg->stats.offsets_size += acfg->nmethods * 4;
7316 for (i = 0; i < acfg->nmethods; ++i) {
7317 if (acfg->cfgs [i]) {
7318 emit_symbol_diff (acfg, acfg->cfgs [i]->asm_symbol, acfg->methods_symbol, 0);
7320 emit_int32 (acfg, 0xffffffff);
7326 /* Emit a sorted table mapping methods to their unbox trampolines */
7327 sprintf (symbol, "unbox_trampolines");
7328 if (acfg->direct_method_addresses)
7329 emit_section_change (acfg, ".text", 0);
7331 emit_section_change (acfg, RODATA_SECT, 0);
7332 emit_alignment (acfg, 8);
7333 emit_label (acfg, symbol);
7336 for (i = 0; i < acfg->nmethods; ++i) {
7341 cfg = acfg->cfgs [i];
7345 method = cfg->orig_method;
7347 if (acfg->aot_opts.full_aot && cfg->orig_method->klass->valuetype) {
7348 #ifdef MONO_ARCH_AOT_SUPPORTED
7352 index = get_method_index (acfg, method);
7353 sprintf (symbol, "ut_%d", index);
7355 emit_int32 (acfg, index);
7356 if (acfg->direct_method_addresses) {
7357 #ifdef MONO_ARCH_AOT_SUPPORTED
7358 arch_emit_direct_call (acfg, symbol, FALSE, acfg->thumb_mixed && cfg->compile_llvm, NULL, &call_size);
7361 emit_symbol_diff (acfg, symbol, acfg->methods_symbol, 0);
7363 /* Make sure the table is sorted by index */
7364 g_assert (index > prev_index);
7368 sprintf (symbol, "unbox_trampolines_end");
7369 emit_label (acfg, symbol);
7370 emit_int32 (acfg, 0);
7374 emit_info (MonoAotCompile *acfg)
7380 offsets = g_new0 (gint32, acfg->nmethods);
7382 for (oindex = 0; oindex < acfg->method_order->len; ++oindex) {
7383 i = GPOINTER_TO_UINT (g_ptr_array_index (acfg->method_order, oindex));
7385 if (acfg->cfgs [i]) {
7386 emit_method_info (acfg, acfg->cfgs [i]);
7387 offsets [i] = acfg->cfgs [i]->method_info_offset;
7393 sprintf (symbol, "method_info_offsets");
7394 emit_section_change (acfg, RODATA_SECT, 1);
7395 emit_alignment (acfg, 8);
7396 emit_label (acfg, symbol);
7398 acfg->stats.offsets_size += emit_offset_table (acfg, acfg->nmethods, 10, offsets);
7403 #endif /* #if !defined(DISABLE_AOT) && !defined(DISABLE_JIT) */
7405 #define rot(x,k) (((x)<<(k)) | ((x)>>(32-(k))))
7406 #define mix(a,b,c) { \
7407 a -= c; a ^= rot(c, 4); c += b; \
7408 b -= a; b ^= rot(a, 6); a += c; \
7409 c -= b; c ^= rot(b, 8); b += a; \
7410 a -= c; a ^= rot(c,16); c += b; \
7411 b -= a; b ^= rot(a,19); a += c; \
7412 c -= b; c ^= rot(b, 4); b += a; \
7414 #define final(a,b,c) { \
7415 c ^= b; c -= rot(b,14); \
7416 a ^= c; a -= rot(c,11); \
7417 b ^= a; b -= rot(a,25); \
7418 c ^= b; c -= rot(b,16); \
7419 a ^= c; a -= rot(c,4); \
7420 b ^= a; b -= rot(a,14); \
7421 c ^= b; c -= rot(b,24); \
7425 mono_aot_type_hash (MonoType *t1)
7427 guint hash = t1->type;
7429 hash |= t1->byref << 6; /* do not collide with t1->type values */
7431 case MONO_TYPE_VALUETYPE:
7432 case MONO_TYPE_CLASS:
7433 case MONO_TYPE_SZARRAY:
7434 /* check if the distribution is good enough */
7435 return ((hash << 5) - hash) ^ mono_metadata_str_hash (t1->data.klass->name);
7437 return ((hash << 5) - hash) ^ mono_metadata_type_hash (t1->data.type);
7438 case MONO_TYPE_ARRAY:
7439 return ((hash << 5) - hash) ^ mono_metadata_type_hash (&t1->data.array->eklass->byval_arg);
7440 case MONO_TYPE_GENERICINST:
7441 return ((hash << 5) - hash) ^ 0;
7448 * mono_aot_method_hash:
7450 * Return a hash code for methods which only depends on metadata.
7453 mono_aot_method_hash (MonoMethod *method)
7455 MonoMethodSignature *sig;
7459 guint32 *hashes_start, *hashes;
7461 MonoGenericInst *ginst = NULL;
7463 /* Similar to the hash in mono_method_get_imt_slot () */
7465 sig = mono_method_signature (method);
7467 if (method->is_inflated)
7468 ginst = ((MonoMethodInflated*)method)->context.method_inst;
7470 hashes_count = sig->param_count + 5 + (ginst ? ginst->type_argc : 0);
7471 hashes_start = g_malloc0 (hashes_count * sizeof (guint32));
7472 hashes = hashes_start;
7474 /* Some wrappers are assigned to random classes */
7475 if (!method->wrapper_type || method->wrapper_type == MONO_WRAPPER_REMOTING_INVOKE_WITH_CHECK)
7476 klass = method->klass;
7478 klass = mono_defaults.object_class;
7480 if (!method->wrapper_type) {
7481 char *full_name = mono_type_full_name (&klass->byval_arg);
7483 hashes [0] = mono_metadata_str_hash (full_name);
7487 hashes [0] = mono_metadata_str_hash (klass->name);
7488 hashes [1] = mono_metadata_str_hash (klass->name_space);
7490 if (method->wrapper_type == MONO_WRAPPER_STFLD || method->wrapper_type == MONO_WRAPPER_LDFLD || method->wrapper_type == MONO_WRAPPER_LDFLDA)
7491 /* The method name includes a stringified pointer */
7494 hashes [2] = mono_metadata_str_hash (method->name);
7495 hashes [3] = method->wrapper_type;
7496 hashes [4] = mono_aot_type_hash (sig->ret);
7498 for (i = 0; i < sig->param_count; i++) {
7499 hashes [hindex ++] = mono_aot_type_hash (sig->params [i]);
7502 for (i = 0; i < ginst->type_argc; ++i)
7503 hashes [hindex ++] = mono_aot_type_hash (ginst->type_argv [i]);
7505 g_assert (hindex == hashes_count);
7507 /* Setup internal state */
7508 a = b = c = 0xdeadbeef + (((guint32)hashes_count)<<2);
7510 /* Handle most of the hashes */
7511 while (hashes_count > 3) {
7520 /* Handle the last 3 hashes (all the case statements fall through) */
7521 switch (hashes_count) {
7522 case 3 : c += hashes [2];
7523 case 2 : b += hashes [1];
7524 case 1 : a += hashes [0];
7526 case 0: /* nothing left to add */
7530 free (hashes_start);
7539 * mono_aot_get_array_helper_from_wrapper;
7541 * Get the helper method in Array called by an array wrapper method.
7544 mono_aot_get_array_helper_from_wrapper (MonoMethod *method)
7548 MonoGenericContext ctx;
7549 MonoType *args [16];
7550 char *mname, *iname, *s, *s2, *helper_name = NULL;
7552 prefix = "System.Collections.Generic";
7553 s = g_strdup_printf ("%s", method->name + strlen (prefix) + 1);
7554 s2 = strstr (s, "`1.");
7560 //printf ("X: %s %s\n", iname, mname);
7562 if (!strcmp (iname, "IList"))
7563 helper_name = g_strdup_printf ("InternalArray__%s", mname);
7565 helper_name = g_strdup_printf ("InternalArray__%s_%s", iname, mname);
7566 m = mono_class_get_method_from_name (mono_defaults.array_class, helper_name, mono_method_signature (method)->param_count);
7568 g_free (helper_name);
7571 if (m->is_generic) {
7572 memset (&ctx, 0, sizeof (ctx));
7573 args [0] = &method->klass->element_class->byval_arg;
7574 ctx.method_inst = mono_metadata_get_generic_inst (1, args);
7575 m = mono_class_inflate_generic_method (m, &ctx);
7581 #if !defined(DISABLE_AOT) && !defined(DISABLE_JIT)
7583 typedef struct HashEntry {
7584 guint32 key, value, index;
7585 struct HashEntry *next;
7589 * emit_extra_methods:
7591 * Emit methods which are not in the METHOD table, like wrappers.
7594 emit_extra_methods (MonoAotCompile *acfg)
7596 int i, table_size, buf_size;
7599 guint32 *info_offsets;
7602 HashEntry *entry, *new_entry;
7603 int nmethods, max_chain_length;
7606 info_offsets = g_new0 (guint32, acfg->extra_methods->len);
7608 /* Emit method info */
7610 for (i = 0; i < acfg->extra_methods->len; ++i) {
7611 MonoMethod *method = g_ptr_array_index (acfg->extra_methods, i);
7612 MonoCompile *cfg = g_hash_table_lookup (acfg->method_to_cfg, method);
7618 p = buf = g_malloc (buf_size);
7622 method = cfg->method_to_register;
7624 encode_method_ref (acfg, method, p, &p);
7626 g_assert ((p - buf) < buf_size);
7628 info_offsets [i] = add_to_blob (acfg, buf, p - buf);
7633 * Construct a chained hash table for mapping indexes in extra_method_info to
7636 table_size = g_spaced_primes_closest ((int)(nmethods * 1.5));
7637 table = g_ptr_array_sized_new (table_size);
7638 for (i = 0; i < table_size; ++i)
7639 g_ptr_array_add (table, NULL);
7640 chain_lengths = g_new0 (int, table_size);
7641 max_chain_length = 0;
7642 for (i = 0; i < acfg->extra_methods->len; ++i) {
7643 MonoMethod *method = g_ptr_array_index (acfg->extra_methods, i);
7644 MonoCompile *cfg = g_hash_table_lookup (acfg->method_to_cfg, method);
7650 key = info_offsets [i];
7651 value = get_method_index (acfg, method);
7653 hash = mono_aot_method_hash (method) % table_size;
7654 //printf ("X: %s %d\n", mono_method_full_name (method, 1), hash);
7656 chain_lengths [hash] ++;
7657 max_chain_length = MAX (max_chain_length, chain_lengths [hash]);
7659 new_entry = mono_mempool_alloc0 (acfg->mempool, sizeof (HashEntry));
7660 new_entry->key = key;
7661 new_entry->value = value;
7663 entry = g_ptr_array_index (table, hash);
7664 if (entry == NULL) {
7665 new_entry->index = hash;
7666 g_ptr_array_index (table, hash) = new_entry;
7669 entry = entry->next;
7671 entry->next = new_entry;
7672 new_entry->index = table->len;
7673 g_ptr_array_add (table, new_entry);
7677 //printf ("MAX: %d\n", max_chain_length);
7679 /* Emit the table */
7680 sprintf (symbol, "extra_method_table");
7681 emit_section_change (acfg, RODATA_SECT, 0);
7682 emit_alignment (acfg, 8);
7683 emit_label (acfg, symbol);
7685 emit_int32 (acfg, table_size);
7686 for (i = 0; i < table->len; ++i) {
7687 HashEntry *entry = g_ptr_array_index (table, i);
7689 if (entry == NULL) {
7690 emit_int32 (acfg, 0);
7691 emit_int32 (acfg, 0);
7692 emit_int32 (acfg, 0);
7694 //g_assert (entry->key > 0);
7695 emit_int32 (acfg, entry->key);
7696 emit_int32 (acfg, entry->value);
7698 emit_int32 (acfg, entry->next->index);
7700 emit_int32 (acfg, 0);
7705 * Emit a table reverse mapping method indexes to their index in extra_method_info.
7706 * This is used by mono_aot_find_jit_info ().
7708 sprintf (symbol, "extra_method_info_offsets");
7709 emit_section_change (acfg, RODATA_SECT, 0);
7710 emit_alignment (acfg, 8);
7711 emit_label (acfg, symbol);
7713 emit_int32 (acfg, acfg->extra_methods->len);
7714 for (i = 0; i < acfg->extra_methods->len; ++i) {
7715 MonoMethod *method = g_ptr_array_index (acfg->extra_methods, i);
7717 emit_int32 (acfg, get_method_index (acfg, method));
7718 emit_int32 (acfg, info_offsets [i]);
7723 emit_exception_info (MonoAotCompile *acfg)
7729 offsets = g_new0 (gint32, acfg->nmethods);
7730 for (i = 0; i < acfg->nmethods; ++i) {
7731 if (acfg->cfgs [i]) {
7732 emit_exception_debug_info (acfg, acfg->cfgs [i]);
7733 offsets [i] = acfg->cfgs [i]->ex_info_offset;
7739 sprintf (symbol, "ex_info_offsets");
7740 emit_section_change (acfg, RODATA_SECT, 1);
7741 emit_alignment (acfg, 8);
7742 emit_label (acfg, symbol);
7744 acfg->stats.offsets_size += emit_offset_table (acfg, acfg->nmethods, 10, offsets);
7749 emit_unwind_info (MonoAotCompile *acfg)
7755 * The unwind info contains a lot of duplicates so we emit each unique
7756 * entry once, and only store the offset from the start of the table in the
7760 sprintf (symbol, "unwind_info");
7761 emit_section_change (acfg, RODATA_SECT, 1);
7762 emit_alignment (acfg, 8);
7763 emit_label (acfg, symbol);
7765 for (i = 0; i < acfg->unwind_ops->len; ++i) {
7766 guint32 index = GPOINTER_TO_UINT (g_ptr_array_index (acfg->unwind_ops, i));
7767 guint8 *unwind_info;
7768 guint32 unwind_info_len;
7772 unwind_info = mono_get_cached_unwind_info (index, &unwind_info_len);
7775 encode_value (unwind_info_len, p, &p);
7776 emit_bytes (acfg, buf, p - buf);
7777 emit_bytes (acfg, unwind_info, unwind_info_len);
7779 acfg->stats.unwind_info_size += (p - buf) + unwind_info_len;
7784 emit_class_info (MonoAotCompile *acfg)
7790 offsets = g_new0 (gint32, acfg->image->tables [MONO_TABLE_TYPEDEF].rows);
7791 for (i = 0; i < acfg->image->tables [MONO_TABLE_TYPEDEF].rows; ++i)
7792 offsets [i] = emit_klass_info (acfg, MONO_TOKEN_TYPE_DEF | (i + 1));
7794 sprintf (symbol, "class_info_offsets");
7795 emit_section_change (acfg, RODATA_SECT, 1);
7796 emit_alignment (acfg, 8);
7797 emit_label (acfg, symbol);
7799 acfg->stats.offsets_size += emit_offset_table (acfg, acfg->image->tables [MONO_TABLE_TYPEDEF].rows, 10, offsets);
7803 typedef struct ClassNameTableEntry {
7804 guint32 token, index;
7805 struct ClassNameTableEntry *next;
7806 } ClassNameTableEntry;
7809 emit_class_name_table (MonoAotCompile *acfg)
7812 guint32 token, hash;
7817 ClassNameTableEntry *entry, *new_entry;
7820 * Construct a chained hash table for mapping class names to typedef tokens.
7822 table_size = g_spaced_primes_closest ((int)(acfg->image->tables [MONO_TABLE_TYPEDEF].rows * 1.5));
7823 table = g_ptr_array_sized_new (table_size);
7824 for (i = 0; i < table_size; ++i)
7825 g_ptr_array_add (table, NULL);
7826 for (i = 0; i < acfg->image->tables [MONO_TABLE_TYPEDEF].rows; ++i) {
7828 token = MONO_TOKEN_TYPE_DEF | (i + 1);
7829 klass = mono_class_get_checked (acfg->image, token, &error);
7831 mono_error_cleanup (&error);
7834 full_name = mono_type_get_name_full (mono_class_get_type (klass), MONO_TYPE_NAME_FORMAT_FULL_NAME);
7835 hash = mono_metadata_str_hash (full_name) % table_size;
7838 /* FIXME: Allocate from the mempool */
7839 new_entry = g_new0 (ClassNameTableEntry, 1);
7840 new_entry->token = token;
7842 entry = g_ptr_array_index (table, hash);
7843 if (entry == NULL) {
7844 new_entry->index = hash;
7845 g_ptr_array_index (table, hash) = new_entry;
7848 entry = entry->next;
7850 entry->next = new_entry;
7851 new_entry->index = table->len;
7852 g_ptr_array_add (table, new_entry);
7856 /* Emit the table */
7857 sprintf (symbol, "class_name_table");
7858 emit_section_change (acfg, RODATA_SECT, 0);
7859 emit_alignment (acfg, 8);
7860 emit_label (acfg, symbol);
7862 /* FIXME: Optimize memory usage */
7863 g_assert (table_size < 65000);
7864 emit_int16 (acfg, table_size);
7865 g_assert (table->len < 65000);
7866 for (i = 0; i < table->len; ++i) {
7867 ClassNameTableEntry *entry = g_ptr_array_index (table, i);
7869 if (entry == NULL) {
7870 emit_int16 (acfg, 0);
7871 emit_int16 (acfg, 0);
7873 emit_int16 (acfg, mono_metadata_token_index (entry->token));
7875 emit_int16 (acfg, entry->next->index);
7877 emit_int16 (acfg, 0);
7883 emit_image_table (MonoAotCompile *acfg)
7889 * The image table is small but referenced in a lot of places.
7890 * So we emit it at once, and reference its elements by an index.
7893 sprintf (symbol, "image_table");
7894 emit_section_change (acfg, RODATA_SECT, 1);
7895 emit_alignment (acfg, 8);
7896 emit_label (acfg, symbol);
7898 emit_int32 (acfg, acfg->image_table->len);
7899 for (i = 0; i < acfg->image_table->len; i++) {
7900 MonoImage *image = (MonoImage*)g_ptr_array_index (acfg->image_table, i);
7901 MonoAssemblyName *aname = &image->assembly->aname;
7903 /* FIXME: Support multi-module assemblies */
7904 g_assert (image->assembly->image == image);
7906 emit_string (acfg, image->assembly_name);
7907 emit_string (acfg, image->guid);
7908 emit_string (acfg, aname->culture ? aname->culture : "");
7909 emit_string (acfg, (const char*)aname->public_key_token);
7911 emit_alignment (acfg, 8);
7912 emit_int32 (acfg, aname->flags);
7913 emit_int32 (acfg, aname->major);
7914 emit_int32 (acfg, aname->minor);
7915 emit_int32 (acfg, aname->build);
7916 emit_int32 (acfg, aname->revision);
7921 emit_got_info (MonoAotCompile *acfg)
7924 int i, first_plt_got_patch, buf_size;
7926 guint32 *got_info_offsets;
7928 /* Add the patches needed by the PLT to the GOT */
7929 acfg->plt_got_offset_base = acfg->got_offset;
7930 first_plt_got_patch = acfg->got_patches->len;
7931 for (i = 1; i < acfg->plt_offset; ++i) {
7932 MonoPltEntry *plt_entry = g_hash_table_lookup (acfg->plt_offset_to_entry, GUINT_TO_POINTER (i));
7934 g_ptr_array_add (acfg->got_patches, plt_entry->ji);
7936 acfg->stats.got_slot_types [plt_entry->ji->type] ++;
7939 acfg->got_offset += acfg->plt_offset;
7943 * - optimize offsets table.
7944 * - reduce number of exported symbols.
7945 * - emit info for a klass only once.
7946 * - determine when a method uses a GOT slot which is guaranteed to be already
7948 * - clean up and document the code.
7949 * - use String.Empty in class libs.
7952 /* Encode info required to decode shared GOT entries */
7953 buf_size = acfg->got_patches->len * 128;
7954 p = buf = mono_mempool_alloc (acfg->mempool, buf_size);
7955 got_info_offsets = mono_mempool_alloc (acfg->mempool, acfg->got_patches->len * sizeof (guint32));
7956 acfg->plt_got_info_offsets = mono_mempool_alloc (acfg->mempool, acfg->plt_offset * sizeof (guint32));
7958 if (acfg->plt_offset)
7959 acfg->plt_got_info_offsets [0] = 0;
7960 for (i = 0; i < acfg->got_patches->len; ++i) {
7961 MonoJumpInfo *ji = g_ptr_array_index (acfg->got_patches, i);
7966 encode_value (ji->type, p, &p);
7968 encode_patch (acfg, ji, p, &p);
7969 acfg->stats.got_slot_info_sizes [ji->type] += p - p2;
7970 g_assert (p - buf <= buf_size);
7971 got_info_offsets [i] = add_to_blob (acfg, buf, p - buf);
7973 if (i >= first_plt_got_patch)
7974 acfg->plt_got_info_offsets [i - first_plt_got_patch + 1] = got_info_offsets [i];
7975 acfg->stats.got_info_size += p - buf;
7978 /* Emit got_info_offsets table */
7979 sprintf (symbol, "got_info_offsets");
7980 emit_section_change (acfg, RODATA_SECT, 1);
7981 emit_alignment (acfg, 8);
7982 emit_label (acfg, symbol);
7984 /* No need to emit offsets for the got plt entries, the plt embeds them directly */
7985 acfg->stats.offsets_size += emit_offset_table (acfg, first_plt_got_patch, 10, (gint32*)got_info_offsets);
7989 emit_got (MonoAotCompile *acfg)
7994 /* Don't make GOT global so accesses to it don't need relocations */
7995 sprintf (symbol, "%s", acfg->got_symbol);
7996 emit_section_change (acfg, ".bss", 0);
7997 emit_alignment (acfg, 8);
7998 emit_local_symbol (acfg, symbol, "got_end", FALSE);
7999 emit_label (acfg, symbol);
8000 if (acfg->got_offset > 0)
8001 emit_zero_bytes (acfg, (int)(acfg->got_offset * sizeof (gpointer)));
8003 sprintf (symbol, "got_end");
8004 emit_label (acfg, symbol);
8008 typedef struct GlobalsTableEntry {
8009 guint32 value, index;
8010 struct GlobalsTableEntry *next;
8011 } GlobalsTableEntry;
8014 emit_globals (MonoAotCompile *acfg)
8020 GlobalsTableEntry *entry, *new_entry;
8022 if (!acfg->aot_opts.static_link)
8026 * When static linking, we emit a table containing our globals.
8030 * Construct a chained hash table for mapping global names to their index in
8031 * the globals table.
8033 table_size = g_spaced_primes_closest ((int)(acfg->globals->len * 1.5));
8034 table = g_ptr_array_sized_new (table_size);
8035 for (i = 0; i < table_size; ++i)
8036 g_ptr_array_add (table, NULL);
8037 for (i = 0; i < acfg->globals->len; ++i) {
8038 char *name = g_ptr_array_index (acfg->globals, i);
8040 hash = mono_metadata_str_hash (name) % table_size;
8042 /* FIXME: Allocate from the mempool */
8043 new_entry = g_new0 (GlobalsTableEntry, 1);
8044 new_entry->value = i;
8046 entry = g_ptr_array_index (table, hash);
8047 if (entry == NULL) {
8048 new_entry->index = hash;
8049 g_ptr_array_index (table, hash) = new_entry;
8052 entry = entry->next;
8054 entry->next = new_entry;
8055 new_entry->index = table->len;
8056 g_ptr_array_add (table, new_entry);
8060 /* Emit the table */
8061 sprintf (symbol, ".Lglobals_hash");
8062 emit_section_change (acfg, RODATA_SECT, 0);
8063 emit_alignment (acfg, 8);
8064 emit_label (acfg, symbol);
8066 /* FIXME: Optimize memory usage */
8067 g_assert (table_size < 65000);
8068 emit_int16 (acfg, table_size);
8069 for (i = 0; i < table->len; ++i) {
8070 GlobalsTableEntry *entry = g_ptr_array_index (table, i);
8072 if (entry == NULL) {
8073 emit_int16 (acfg, 0);
8074 emit_int16 (acfg, 0);
8076 emit_int16 (acfg, entry->value + 1);
8078 emit_int16 (acfg, entry->next->index);
8080 emit_int16 (acfg, 0);
8084 /* Emit the names */
8085 for (i = 0; i < acfg->globals->len; ++i) {
8086 char *name = g_ptr_array_index (acfg->globals, i);
8088 sprintf (symbol, "name_%d", i);
8089 emit_section_change (acfg, RODATA_SECT, 1);
8091 emit_alignment (acfg, 4);
8093 emit_label (acfg, symbol);
8094 emit_string (acfg, name);
8097 /* Emit the globals table */
8098 sprintf (symbol, "globals");
8099 emit_section_change (acfg, ".data", 0);
8100 /* This is not a global, since it is accessed by the init function */
8101 emit_alignment (acfg, 8);
8102 emit_label (acfg, symbol);
8104 sprintf (symbol, "%sglobals_hash", acfg->temp_prefix);
8105 emit_pointer (acfg, symbol);
8107 for (i = 0; i < acfg->globals->len; ++i) {
8108 char *name = g_ptr_array_index (acfg->globals, i);
8110 sprintf (symbol, "name_%d", i);
8111 emit_pointer (acfg, symbol);
8113 sprintf (symbol, "%s", name);
8114 emit_pointer (acfg, symbol);
8116 /* Null terminate the table */
8117 emit_int32 (acfg, 0);
8118 emit_int32 (acfg, 0);
8122 emit_autoreg (MonoAotCompile *acfg)
8127 * Emit a function into the .ctor section which will be called by the ELF
8128 * loader to register this module with the runtime.
8130 if (! (!acfg->use_bin_writer && acfg->aot_opts.static_link && acfg->aot_opts.autoreg))
8133 symbol = g_strdup_printf ("_%s_autoreg", acfg->static_linking_symbol);
8135 arch_emit_autoreg (acfg, symbol);
8141 emit_mem_end (MonoAotCompile *acfg)
8145 sprintf (symbol, "mem_end");
8146 emit_section_change (acfg, ".text", 1);
8147 emit_alignment (acfg, 8);
8148 emit_label (acfg, symbol);
8152 * Emit a structure containing all the information not stored elsewhere.
8155 emit_file_info (MonoAotCompile *acfg)
8160 const char *gc_name;
8163 emit_string_symbol (acfg, "assembly_guid" , acfg->image->guid);
8165 if (acfg->aot_opts.bind_to_runtime_version) {
8166 build_info = mono_get_runtime_build_info ();
8167 emit_string_symbol (acfg, "runtime_version", build_info);
8168 g_free (build_info);
8170 emit_string_symbol (acfg, "runtime_version", "");
8173 /* Emit a string holding the assembly name */
8174 emit_string_symbol (acfg, "assembly_name", acfg->image->assembly->aname.name);
8177 * The managed allocators are GC specific, so can't use an AOT image created by one GC
8180 gc_name = mono_gc_get_gc_name ();
8181 gc_name_offset = add_to_blob (acfg, (guint8*)gc_name, strlen (gc_name) + 1);
8183 sprintf (symbol, "%smono_aot_file_info", acfg->user_symbol_prefix);
8184 emit_section_change (acfg, ".data", 0);
8185 emit_alignment (acfg, 8);
8186 emit_label (acfg, symbol);
8187 if (!acfg->aot_opts.static_link)
8188 emit_global (acfg, symbol, FALSE);
8190 /* The data emitted here must match MonoAotFileInfo. */
8192 emit_int32 (acfg, MONO_AOT_FILE_VERSION);
8193 emit_int32 (acfg, 0);
8196 * We emit pointers to our data structures instead of emitting global symbols which
8197 * point to them, to reduce the number of globals, and because using globals leads to
8198 * various problems (i.e. arm/thumb).
8200 emit_pointer (acfg, acfg->got_symbol);
8201 emit_pointer (acfg, acfg->methods_symbol);
8204 * Emit a reference to the mono_eh_frame table created by our modified LLVM compiler.
8206 emit_pointer (acfg, "mono_eh_frame");
8208 emit_pointer (acfg, NULL);
8210 emit_pointer (acfg, "blob");
8211 emit_pointer (acfg, "class_name_table");
8212 emit_pointer (acfg, "class_info_offsets");
8213 emit_pointer (acfg, "method_info_offsets");
8214 emit_pointer (acfg, "ex_info_offsets");
8215 emit_pointer (acfg, "code_offsets");
8216 if (acfg->direct_method_addresses)
8217 emit_pointer (acfg, "method_addresses");
8219 emit_pointer (acfg, NULL);
8220 emit_pointer (acfg, "extra_method_info_offsets");
8221 emit_pointer (acfg, "extra_method_table");
8222 emit_pointer (acfg, "got_info_offsets");
8223 emit_pointer (acfg, "methods_end");
8224 emit_pointer (acfg, "unwind_info");
8225 emit_pointer (acfg, "mem_end");
8226 emit_pointer (acfg, "image_table");
8227 emit_pointer (acfg, "plt");
8228 emit_pointer (acfg, "plt_end");
8229 emit_pointer (acfg, "assembly_guid");
8230 emit_pointer (acfg, "runtime_version");
8231 if (acfg->num_trampoline_got_entries) {
8232 emit_pointer (acfg, "specific_trampolines");
8233 emit_pointer (acfg, "static_rgctx_trampolines");
8234 emit_pointer (acfg, "imt_thunks");
8235 emit_pointer (acfg, "gsharedvt_arg_trampolines");
8237 emit_pointer (acfg, NULL);
8238 emit_pointer (acfg, NULL);
8239 emit_pointer (acfg, NULL);
8240 emit_pointer (acfg, NULL);
8242 if (acfg->thumb_mixed) {
8243 emit_pointer (acfg, "thumb_end");
8245 emit_pointer (acfg, NULL);
8247 if (acfg->aot_opts.static_link) {
8248 emit_pointer (acfg, "globals");
8250 emit_pointer (acfg, NULL);
8252 emit_pointer (acfg, "assembly_name");
8253 emit_pointer (acfg, "unbox_trampolines");
8254 emit_pointer (acfg, "unbox_trampolines_end");
8256 emit_int32 (acfg, acfg->plt_got_offset_base);
8257 emit_int32 (acfg, (int)(acfg->got_offset * sizeof (gpointer)));
8258 emit_int32 (acfg, acfg->plt_offset);
8259 emit_int32 (acfg, acfg->nmethods);
8260 emit_int32 (acfg, acfg->flags);
8261 emit_int32 (acfg, acfg->opts);
8262 emit_int32 (acfg, acfg->simd_opts);
8263 emit_int32 (acfg, gc_name_offset);
8265 for (i = 0; i < MONO_AOT_TRAMP_NUM; ++i)
8266 emit_int32 (acfg, acfg->num_trampolines [i]);
8267 for (i = 0; i < MONO_AOT_TRAMP_NUM; ++i)
8268 emit_int32 (acfg, acfg->trampoline_got_offset_base [i]);
8269 for (i = 0; i < MONO_AOT_TRAMP_NUM; ++i)
8270 emit_int32 (acfg, acfg->trampoline_size [i]);
8271 emit_int32 (acfg, acfg->aot_opts.nrgctx_fetch_trampolines);
8273 #if defined (TARGET_ARM) && defined (TARGET_MACH)
8278 memset (&t, 0, sizeof (MonoType));
8279 t.type = MONO_TYPE_R8;
8280 mono_type_size (&t, &align);
8281 emit_int32 (acfg, align);
8283 memset (&t, 0, sizeof (MonoType));
8284 t.type = MONO_TYPE_I8;
8285 mono_type_size (&t, &align);
8287 emit_int32 (acfg, align);
8290 emit_int32 (acfg, MONO_ABI_ALIGNOF (double));
8291 emit_int32 (acfg, MONO_ABI_ALIGNOF (gint64));
8293 emit_int32 (acfg, MONO_TRAMPOLINE_NUM);
8294 emit_int32 (acfg, acfg->tramp_page_size);
8295 for (i = 0; i < MONO_AOT_TRAMP_NUM; ++i)
8296 emit_int32 (acfg, acfg->tramp_page_code_offsets [i]);
8298 if (acfg->aot_opts.static_link) {
8302 * Emit a global symbol which can be passed by an embedding app to
8303 * mono_aot_register_module (). The symbol points to a pointer to the the file info
8306 sprintf (symbol, "%smono_aot_module_%s_info", acfg->user_symbol_prefix, acfg->image->assembly->aname.name);
8308 /* Get rid of characters which cannot occur in symbols */
8310 for (p = symbol; *p; ++p) {
8311 if (!(isalnum (*p) || *p == '_'))
8314 acfg->static_linking_symbol = g_strdup (symbol);
8315 emit_global_inner (acfg, symbol, FALSE);
8316 emit_alignment (acfg, sizeof (gpointer));
8317 emit_label (acfg, symbol);
8318 emit_pointer_2 (acfg, acfg->user_symbol_prefix, "mono_aot_file_info");
8323 emit_blob (MonoAotCompile *acfg)
8327 sprintf (symbol, "blob");
8328 emit_section_change (acfg, RODATA_SECT, 1);
8329 emit_alignment (acfg, 8);
8330 emit_label (acfg, symbol);
8332 emit_bytes (acfg, (guint8*)acfg->blob.data, acfg->blob.index);
8336 emit_objc_selectors (MonoAotCompile *acfg)
8340 if (!acfg->objc_selectors || acfg->objc_selectors->len == 0)
8345 * cat > foo.m << EOF
8348 * return @selector(print:);
8353 img_writer_emit_unset_mode (acfg->w);
8354 g_assert (acfg->fp);
8355 fprintf (acfg->fp, ".section __DATA,__objc_selrefs,literal_pointers,no_dead_strip\n");
8356 fprintf (acfg->fp, ".align 3\n");
8357 for (i = 0; i < acfg->objc_selectors->len; ++i) {
8358 fprintf (acfg->fp, "L_OBJC_SELECTOR_REFERENCES_%d:\n", i);
8359 fprintf (acfg->fp, ".long L_OBJC_METH_VAR_NAME_%d\n", i);
8361 fprintf (acfg->fp, ".section __TEXT,__cstring,cstring_literals\n");
8362 for (i = 0; i < acfg->objc_selectors->len; ++i) {
8363 fprintf (acfg->fp, "L_OBJC_METH_VAR_NAME_%d:\n", i);
8364 fprintf (acfg->fp, ".asciz \"%s\"\n", (char*)g_ptr_array_index (acfg->objc_selectors, i));
8367 fprintf (acfg->fp, ".section __DATA,__objc_imageinfo,regular,no_dead_strip\n");
8368 fprintf (acfg->fp, ".align 3\n");
8369 fprintf (acfg->fp, "L_OBJC_IMAGE_INFO:\n");
8370 fprintf (acfg->fp, ".long 0\n");
8371 fprintf (acfg->fp, ".long 16\n");
8375 emit_dwarf_info (MonoAotCompile *acfg)
8377 #ifdef EMIT_DWARF_INFO
8381 /* DIEs for methods */
8382 for (i = 0; i < acfg->nmethods; ++i) {
8383 MonoCompile *cfg = acfg->cfgs [i];
8388 // FIXME: LLVM doesn't define .Lme_...
8389 if (cfg->compile_llvm)
8392 sprintf (symbol2, "%sme_%x", acfg->temp_prefix, i);
8394 mono_dwarf_writer_emit_method (acfg->dwarf, cfg, cfg->method, cfg->asm_symbol, symbol2, 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 ()));
8400 collect_methods (MonoAotCompile *acfg)
8403 MonoImage *image = acfg->image;
8405 /* Collect methods */
8406 for (i = 0; i < image->tables [MONO_TABLE_METHOD].rows; ++i) {
8408 guint32 token = MONO_TOKEN_METHOD_DEF | (i + 1);
8410 method = mono_get_method (acfg->image, token, NULL);
8413 aot_printerrf (acfg, "Failed to load method 0x%x from '%s'.\n", token, image->name);
8414 aot_printerrf (acfg, "Run with MONO_LOG_LEVEL=debug for more information.\n");
8418 /* Load all methods eagerly to skip the slower lazy loading code */
8419 mono_class_setup_methods (method->klass);
8421 if (acfg->aot_opts.full_aot && method->iflags & METHOD_IMPL_ATTRIBUTE_INTERNAL_CALL) {
8422 /* Compile the wrapper instead */
8423 /* We do this here instead of add_wrappers () because it is easy to do it here */
8424 MonoMethod *wrapper = mono_marshal_get_native_wrapper (method, check_for_pending_exc, TRUE);
8428 /* FIXME: Some mscorlib methods don't have debug info */
8430 if (acfg->aot_opts.soft_debug && !method->wrapper_type) {
8431 if (!((method->flags & METHOD_ATTRIBUTE_PINVOKE_IMPL) ||
8432 (method->iflags & METHOD_IMPL_ATTRIBUTE_RUNTIME) ||
8433 (method->flags & METHOD_ATTRIBUTE_ABSTRACT) ||
8434 (method->iflags & METHOD_IMPL_ATTRIBUTE_INTERNAL_CALL))) {
8435 if (!mono_debug_lookup_method (method)) {
8436 fprintf (stderr, "Method %s has no debug info, probably the .mdb file for the assembly is missing.\n", mono_method_full_name (method, TRUE));
8443 /* Since we add the normal methods first, their index will be equal to their zero based token index */
8444 add_method_with_index (acfg, method, i, FALSE);
8445 acfg->method_index ++;
8448 /* gsharedvt methods */
8449 for (mindex = 0; mindex < image->tables [MONO_TABLE_METHOD].rows; ++mindex) {
8451 guint32 token = MONO_TOKEN_METHOD_DEF | (mindex + 1);
8453 if (!(acfg->opts & MONO_OPT_GSHAREDVT))
8456 method = mono_get_method (acfg->image, token, NULL);
8460 if (strcmp (method->name, "gshared2"))
8464 if (!strstr (method->klass->image->name, "mini"))
8467 if (method->is_generic || method->klass->generic_container) {
8468 MonoMethod *gshared;
8470 gshared = mini_get_shared_method_full (method, TRUE, TRUE);
8471 add_extra_method (acfg, gshared);
8475 add_generic_instances (acfg);
8477 if (acfg->aot_opts.full_aot)
8478 add_wrappers (acfg);
8483 compile_methods (MonoAotCompile *acfg)
8487 if (acfg->aot_opts.nthreads > 0) {
8492 gpointer *user_data;
8493 MonoMethod **methods;
8495 methods_len = acfg->methods->len;
8497 len = acfg->methods->len / acfg->aot_opts.nthreads;
8500 * Partition the list of methods into fragments, and hand it to threads to
8503 threads = g_ptr_array_new ();
8504 /* Make a copy since acfg->methods is modified by compile_method () */
8505 methods = g_new0 (MonoMethod*, methods_len);
8506 //memcpy (methods, g_ptr_array_index (acfg->methods, 0), sizeof (MonoMethod*) * methods_len);
8507 for (i = 0; i < methods_len; ++i)
8508 methods [i] = g_ptr_array_index (acfg->methods, i);
8510 while (i < methods_len) {
8511 frag = g_ptr_array_new ();
8512 for (j = 0; j < len; ++j) {
8513 if (i < methods_len) {
8514 g_ptr_array_add (frag, methods [i]);
8519 user_data = g_new0 (gpointer, 3);
8520 user_data [0] = mono_domain_get ();
8521 user_data [1] = acfg;
8522 user_data [2] = frag;
8524 handle = mono_threads_create_thread ((gpointer)compile_thread_main, user_data, 0, 0, NULL);
8525 g_ptr_array_add (threads, handle);
8529 for (i = 0; i < threads->len; ++i) {
8530 WaitForSingleObjectEx (g_ptr_array_index (threads, i), INFINITE, FALSE);
8536 /* Compile methods added by compile_method () or all methods if nthreads == 0 */
8537 for (i = methods_len; i < acfg->methods->len; ++i) {
8538 /* This can new methods to acfg->methods */
8539 compile_method (acfg, g_ptr_array_index (acfg->methods, i));
8544 compile_asm (MonoAotCompile *acfg)
8546 char *command, *objfile;
8547 char *outfile_name, *tmp_outfile_name;
8548 const char *tool_prefix = acfg->aot_opts.tool_prefix ? acfg->aot_opts.tool_prefix : "";
8550 #if defined(TARGET_AMD64) && !defined(TARGET_MACH)
8551 #define AS_OPTIONS "--64"
8552 #elif defined(TARGET_POWERPC64)
8553 #define AS_OPTIONS "-a64 -mppc64"
8554 #define LD_OPTIONS "-m elf64ppc"
8555 #elif defined(sparc) && SIZEOF_VOID_P == 8
8556 #define AS_OPTIONS "-xarch=v9"
8557 #elif defined(TARGET_X86) && defined(TARGET_MACH) && !defined(__native_client_codegen__)
8558 #define AS_OPTIONS "-arch i386"
8560 #define AS_OPTIONS ""
8563 #ifdef __native_client_codegen__
8564 #if defined(TARGET_AMD64)
8565 #define AS_NAME "nacl64-as"
8567 #define AS_NAME "nacl-as"
8569 #elif defined(TARGET_OSX)
8570 #define AS_NAME "clang -c -x assembler"
8572 #define AS_NAME "as"
8576 #define LD_OPTIONS ""
8580 #define LD_NAME "ld -shared -G"
8581 #elif defined(__ppc__) && defined(TARGET_MACH)
8582 #define LD_NAME "gcc -dynamiclib"
8583 #elif defined(TARGET_AMD64) && defined(TARGET_MACH)
8584 #define LD_NAME "clang --shared"
8585 #elif defined(HOST_WIN32)
8586 #define LD_NAME "gcc -shared --dll"
8587 #elif defined(TARGET_X86) && defined(TARGET_MACH) && !defined(__native_client_codegen__)
8588 #define LD_NAME "clang -m32 -dynamiclib"
8591 if (acfg->aot_opts.asm_only) {
8592 aot_printf (acfg, "Output file: '%s'.\n", acfg->tmpfname);
8593 if (acfg->aot_opts.static_link)
8594 aot_printf (acfg, "Linking symbol: '%s'.\n", acfg->static_linking_symbol);
8598 if (acfg->aot_opts.static_link) {
8599 if (acfg->aot_opts.outfile)
8600 objfile = g_strdup_printf ("%s", acfg->aot_opts.outfile);
8602 objfile = g_strdup_printf ("%s.o", acfg->image->name);
8604 objfile = g_strdup_printf ("%s.o", acfg->tmpfname);
8606 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);
8607 aot_printf (acfg, "Executing the native assembler: %s\n", command);
8608 if (system (command) != 0) {
8616 if (acfg->aot_opts.static_link) {
8617 aot_printf (acfg, "Output file: '%s'.\n", objfile);
8618 aot_printf (acfg, "Linking symbol: '%s'.\n", acfg->static_linking_symbol);
8623 if (acfg->aot_opts.outfile)
8624 outfile_name = g_strdup_printf ("%s", acfg->aot_opts.outfile);
8626 outfile_name = g_strdup_printf ("%s%s", acfg->image->name, MONO_SOLIB_EXT);
8628 tmp_outfile_name = g_strdup_printf ("%s.tmp", outfile_name);
8631 command = g_strdup_printf ("%s -o %s %s.o", LD_NAME, tmp_outfile_name, acfg->tmpfname);
8633 command = g_strdup_printf ("%sld %s -shared -o %s %s.o", tool_prefix, LD_OPTIONS, tmp_outfile_name, acfg->tmpfname);
8635 aot_printf (acfg, "Executing the native linker: %s\n", command);
8636 if (system (command) != 0) {
8637 g_free (tmp_outfile_name);
8638 g_free (outfile_name);
8646 /*com = g_strdup_printf ("strip --strip-unneeded %s%s", acfg->image->name, MONO_SOLIB_EXT);
8647 printf ("Stripping the binary: %s\n", com);
8651 #if defined(TARGET_ARM) && !defined(TARGET_MACH)
8653 * gas generates 'mapping symbols' each time code and data is mixed, which
8654 * happens a lot in emit_and_reloc_code (), so we need to get rid of them.
8656 command = g_strdup_printf ("%sstrip --strip-symbol=\\$a --strip-symbol=\\$d %s", tool_prefix, tmp_outfile_name);
8657 aot_printf (acfg, "Stripping the binary: %s\n", command);
8658 if (system (command) != 0) {
8659 g_free (tmp_outfile_name);
8660 g_free (outfile_name);
8667 rename (tmp_outfile_name, outfile_name);
8669 #if defined(TARGET_MACH)
8670 command = g_strdup_printf ("dsymutil %s", outfile_name);
8671 aot_printf (acfg, "Executing dsymutil: %s\n", command);
8672 if (system (command) != 0) {
8677 if (!acfg->aot_opts.save_temps)
8680 g_free (tmp_outfile_name);
8681 g_free (outfile_name);
8684 if (acfg->aot_opts.save_temps)
8685 aot_printf (acfg, "Retained input file.\n");
8687 unlink (acfg->tmpfname);
8692 static MonoAotCompile*
8693 acfg_create (MonoAssembly *ass, guint32 opts)
8695 MonoImage *image = ass->image;
8696 MonoAotCompile *acfg;
8699 acfg = g_new0 (MonoAotCompile, 1);
8700 acfg->methods = g_ptr_array_new ();
8701 acfg->method_indexes = g_hash_table_new (NULL, NULL);
8702 acfg->method_depth = g_hash_table_new (NULL, NULL);
8703 acfg->plt_offset_to_entry = g_hash_table_new (NULL, NULL);
8704 acfg->patch_to_plt_entry = g_new0 (GHashTable*, MONO_PATCH_INFO_NUM);
8705 acfg->patch_to_got_offset = g_hash_table_new (mono_patch_info_hash, mono_patch_info_equal);
8706 acfg->patch_to_got_offset_by_type = g_new0 (GHashTable*, MONO_PATCH_INFO_NUM);
8707 for (i = 0; i < MONO_PATCH_INFO_NUM; ++i)
8708 acfg->patch_to_got_offset_by_type [i] = g_hash_table_new (mono_patch_info_hash, mono_patch_info_equal);
8709 acfg->got_patches = g_ptr_array_new ();
8710 acfg->method_to_cfg = g_hash_table_new (NULL, NULL);
8711 acfg->token_info_hash = g_hash_table_new_full (NULL, NULL, NULL, NULL);
8712 acfg->method_to_pinvoke_import = g_hash_table_new_full (NULL, NULL, NULL, g_free);
8713 acfg->image_hash = g_hash_table_new (NULL, NULL);
8714 acfg->image_table = g_ptr_array_new ();
8715 acfg->globals = g_ptr_array_new ();
8716 acfg->image = image;
8718 /* TODO: Write out set of SIMD instructions used, rather than just those available */
8719 acfg->simd_opts = mono_arch_cpu_enumerate_simd_versions ();
8720 acfg->mempool = mono_mempool_new ();
8721 acfg->extra_methods = g_ptr_array_new ();
8722 acfg->unwind_info_offsets = g_hash_table_new (NULL, NULL);
8723 acfg->unwind_ops = g_ptr_array_new ();
8724 acfg->method_label_hash = g_hash_table_new_full (g_str_hash, g_str_equal, g_free, NULL);
8725 acfg->method_order = g_ptr_array_new ();
8726 acfg->export_names = g_hash_table_new (NULL, NULL);
8727 acfg->klass_blob_hash = g_hash_table_new (NULL, NULL);
8728 acfg->method_blob_hash = g_hash_table_new (NULL, NULL);
8729 acfg->plt_entry_debug_sym_cache = g_hash_table_new (g_str_hash, g_str_equal);
8730 mono_mutex_init_recursive (&acfg->mutex);
8736 acfg_free (MonoAotCompile *acfg)
8740 img_writer_destroy (acfg->w);
8741 for (i = 0; i < acfg->nmethods; ++i)
8743 g_free (acfg->cfgs [i]);
8744 g_free (acfg->cfgs);
8745 g_free (acfg->static_linking_symbol);
8746 g_free (acfg->got_symbol);
8747 g_free (acfg->plt_symbol);
8748 g_ptr_array_free (acfg->methods, TRUE);
8749 g_ptr_array_free (acfg->got_patches, TRUE);
8750 g_ptr_array_free (acfg->image_table, TRUE);
8751 g_ptr_array_free (acfg->globals, TRUE);
8752 g_ptr_array_free (acfg->unwind_ops, TRUE);
8753 g_hash_table_destroy (acfg->method_indexes);
8754 g_hash_table_destroy (acfg->method_depth);
8755 g_hash_table_destroy (acfg->plt_offset_to_entry);
8756 for (i = 0; i < MONO_PATCH_INFO_NUM; ++i) {
8757 if (acfg->patch_to_plt_entry [i])
8758 g_hash_table_destroy (acfg->patch_to_plt_entry [i]);
8760 g_free (acfg->patch_to_plt_entry);
8761 g_hash_table_destroy (acfg->patch_to_got_offset);
8762 g_hash_table_destroy (acfg->method_to_cfg);
8763 g_hash_table_destroy (acfg->token_info_hash);
8764 g_hash_table_destroy (acfg->method_to_pinvoke_import);
8765 g_hash_table_destroy (acfg->image_hash);
8766 g_hash_table_destroy (acfg->unwind_info_offsets);
8767 g_hash_table_destroy (acfg->method_label_hash);
8768 g_hash_table_destroy (acfg->export_names);
8769 g_hash_table_destroy (acfg->plt_entry_debug_sym_cache);
8770 g_hash_table_destroy (acfg->klass_blob_hash);
8771 g_hash_table_destroy (acfg->method_blob_hash);
8772 for (i = 0; i < MONO_PATCH_INFO_NUM; ++i)
8773 g_hash_table_destroy (acfg->patch_to_got_offset_by_type [i]);
8774 g_free (acfg->patch_to_got_offset_by_type);
8775 mono_mempool_destroy (acfg->mempool);
8780 mono_compile_assembly (MonoAssembly *ass, guint32 opts, const char *aot_options)
8782 MonoImage *image = ass->image;
8783 int i, res, all_sizes;
8784 MonoAotCompile *acfg;
8785 char *outfile_name, *tmp_outfile_name, *p;
8786 char llvm_stats_msg [256];
8790 acfg = acfg_create (ass, opts);
8792 memset (&acfg->aot_opts, 0, sizeof (acfg->aot_opts));
8793 acfg->aot_opts.write_symbols = TRUE;
8794 acfg->aot_opts.ntrampolines = 1024;
8795 acfg->aot_opts.nrgctx_trampolines = 1024;
8796 acfg->aot_opts.nimt_trampolines = 128;
8797 acfg->aot_opts.nrgctx_fetch_trampolines = 128;
8798 acfg->aot_opts.ngsharedvt_arg_trampolines = 128;
8799 acfg->aot_opts.llvm_path = g_strdup ("");
8801 acfg->aot_opts.use_trampolines_page = TRUE;
8804 mono_aot_parse_options (aot_options, &acfg->aot_opts);
8806 if (acfg->aot_opts.logfile) {
8807 acfg->logfile = fopen (acfg->aot_opts.logfile, "a+");
8810 if (acfg->aot_opts.static_link)
8811 acfg->aot_opts.autoreg = TRUE;
8813 //acfg->aot_opts.print_skipped_methods = TRUE;
8815 #if !defined(MONO_ARCH_GSHAREDVT_SUPPORTED) || !defined(ENABLE_GSHAREDVT)
8816 if (opts & MONO_OPT_GSHAREDVT) {
8817 aot_printerrf (acfg, "-O=gsharedvt not supported on this platform.\n");
8822 aot_printf (acfg, "Mono Ahead of Time compiler - compiling assembly %s\n", image->name);
8824 #ifndef MONO_ARCH_HAVE_FULL_AOT_TRAMPOLINES
8825 if (acfg->aot_opts.full_aot) {
8826 aot_printerrf (acfg, "--aot=full is not supported on this platform.\n");
8831 if (acfg->aot_opts.direct_pinvoke && !acfg->aot_opts.static_link) {
8832 aot_printerrf (acfg, "The 'direct-pinvoke' AOT option also requires the 'static' AOT option.\n");
8836 if (acfg->aot_opts.static_link)
8837 acfg->aot_opts.asm_writer = TRUE;
8839 if (acfg->aot_opts.soft_debug) {
8840 MonoDebugOptions *opt = mini_get_debug_options ();
8842 opt->mdb_optimizations = TRUE;
8843 opt->gen_seq_points_debug_data = TRUE;
8845 if (!mono_debug_enabled ()) {
8846 aot_printerrf (acfg, "The soft-debug AOT option requires the --debug option.\n");
8849 acfg->flags |= MONO_AOT_FILE_FLAG_DEBUG;
8852 if (mono_use_llvm || acfg->aot_opts.llvm) {
8854 acfg->aot_opts.asm_writer = TRUE;
8855 acfg->flags |= MONO_AOT_FILE_FLAG_WITH_LLVM;
8857 if (acfg->aot_opts.soft_debug) {
8858 aot_printerrf (acfg, "The 'soft-debug' option is not supported when compiling with LLVM.\n");
8865 if (acfg->aot_opts.full_aot)
8866 acfg->flags |= MONO_AOT_FILE_FLAG_FULL_AOT;
8868 if (acfg->aot_opts.instances_logfile_path) {
8869 acfg->instances_logfile = fopen (acfg->aot_opts.instances_logfile_path, "w");
8870 if (!acfg->instances_logfile) {
8871 aot_printerrf (acfg, "Unable to create logfile: '%s'.\n", acfg->aot_opts.instances_logfile_path);
8876 load_profile_files (acfg);
8878 acfg->num_trampolines [MONO_AOT_TRAMP_SPECIFIC] = acfg->aot_opts.full_aot ? acfg->aot_opts.ntrampolines : 0;
8879 #ifdef MONO_ARCH_GSHARED_SUPPORTED
8880 acfg->num_trampolines [MONO_AOT_TRAMP_STATIC_RGCTX] = acfg->aot_opts.full_aot ? acfg->aot_opts.nrgctx_trampolines : 0;
8882 acfg->num_trampolines [MONO_AOT_TRAMP_IMT_THUNK] = acfg->aot_opts.full_aot ? acfg->aot_opts.nimt_trampolines : 0;
8883 #ifdef MONO_ARCH_GSHAREDVT_SUPPORTED
8884 if (acfg->opts & MONO_OPT_GSHAREDVT)
8885 acfg->num_trampolines [MONO_AOT_TRAMP_GSHAREDVT_ARG] = acfg->aot_opts.full_aot ? acfg->aot_opts.ngsharedvt_arg_trampolines : 0;
8888 acfg->temp_prefix = img_writer_get_temp_label_prefix (NULL);
8892 acfg->got_symbol_base = g_strdup_printf ("mono_aot_%s_got", acfg->image->assembly->aname.name);
8893 acfg->plt_symbol = g_strdup_printf ("%smono_aot_%s_plt", acfg->llvm_label_prefix, acfg->image->assembly->aname.name);
8894 acfg->assembly_name_sym = g_strdup (acfg->image->assembly->aname.name);
8896 /* Get rid of characters which cannot occur in symbols */
8897 for (p = acfg->got_symbol_base; *p; ++p) {
8898 if (!(isalnum (*p) || *p == '_'))
8901 for (p = acfg->plt_symbol; *p; ++p) {
8902 if (!(isalnum (*p) || *p == '_'))
8905 for (p = acfg->assembly_name_sym; *p; ++p) {
8906 if (!(isalnum (*p) || *p == '_'))
8910 acfg->method_index = 1;
8914 if (acfg->aot_opts.full_aot)
8915 mono_set_partial_sharing_supported (TRUE);
8918 res = collect_methods (acfg);
8922 acfg->cfgs_size = acfg->methods->len + 32;
8923 acfg->cfgs = g_new0 (MonoCompile*, acfg->cfgs_size);
8925 /* PLT offset 0 is reserved for the PLT trampoline */
8926 acfg->plt_offset = 1;
8931 mono_llvm_create_aot_module (acfg->got_symbol_base);
8935 /* GOT offset 0 is reserved for the address of the current assembly */
8939 ji = mono_mempool_alloc0 (acfg->mempool, sizeof (MonoAotCompile));
8940 ji->type = MONO_PATCH_INFO_IMAGE;
8941 ji->data.image = acfg->image;
8943 get_got_offset (acfg, ji);
8945 /* Slot 1 is reserved for the mscorlib got addr */
8946 ji = mono_mempool_alloc0 (acfg->mempool, sizeof (MonoAotCompile));
8947 ji->type = MONO_PATCH_INFO_MSCORLIB_GOT_ADDR;
8948 get_got_offset (acfg, ji);
8950 /* This is very common */
8951 ji = mono_mempool_alloc0 (acfg->mempool, sizeof (MonoAotCompile));
8952 ji->type = MONO_PATCH_INFO_GC_CARD_TABLE_ADDR;
8953 get_got_offset (acfg, ji);
8955 ji = mono_mempool_alloc0 (acfg->mempool, sizeof (MonoAotCompile));
8956 ji->type = MONO_PATCH_INFO_JIT_TLS_ID;
8957 get_got_offset (acfg, ji);
8962 compile_methods (acfg);
8966 acfg->stats.jit_time = TV_ELAPSED (atv, btv);
8974 if (acfg->aot_opts.asm_only) {
8975 if (acfg->aot_opts.outfile) {
8976 acfg->tmpfname = g_strdup_printf ("%s", acfg->aot_opts.outfile);
8977 acfg->tmpbasename = g_strdup (acfg->tmpfname);
8979 acfg->tmpbasename = g_strdup_printf ("%s", acfg->image->name);
8980 acfg->tmpfname = g_strdup_printf ("%s.s", acfg->tmpbasename);
8983 acfg->tmpbasename = g_strdup_printf ("%s", "temp");
8984 acfg->tmpfname = g_strdup_printf ("%s.s", acfg->tmpbasename);
8987 res = emit_llvm_file (acfg);
8993 if (!acfg->aot_opts.asm_only && !acfg->aot_opts.asm_writer && bin_writer_supported ()) {
8994 if (acfg->aot_opts.outfile)
8995 outfile_name = g_strdup_printf ("%s", acfg->aot_opts.outfile);
8997 outfile_name = g_strdup_printf ("%s%s", acfg->image->name, MONO_SOLIB_EXT);
9000 * Can't use g_file_open_tmp () as it will be deleted at exit, and
9001 * it might be in another file system so the rename () won't work.
9003 tmp_outfile_name = g_strdup_printf ("%s.tmp", outfile_name);
9005 acfg->fp = fopen (tmp_outfile_name, "w");
9007 aot_printf (acfg, "Unable to create temporary file '%s': %s\n", tmp_outfile_name, strerror (errno));
9011 acfg->w = img_writer_create (acfg->fp, TRUE);
9012 acfg->use_bin_writer = TRUE;
9015 /* Append to the .s file created by llvm */
9016 /* FIXME: Use multiple files instead */
9017 acfg->fp = fopen (acfg->tmpfname, "a+");
9019 if (acfg->aot_opts.asm_only) {
9020 if (acfg->aot_opts.outfile)
9021 acfg->tmpfname = g_strdup_printf ("%s", acfg->aot_opts.outfile);
9023 acfg->tmpfname = g_strdup_printf ("%s.s", acfg->image->name);
9024 acfg->fp = fopen (acfg->tmpfname, "w+");
9026 int i = g_file_open_tmp ("mono_aot_XXXXXX", &acfg->tmpfname, NULL);
9027 acfg->fp = fdopen (i, "w+");
9030 if (acfg->fp == 0) {
9031 aot_printerrf (acfg, "Unable to open file '%s': %s\n", acfg->tmpfname, strerror (errno));
9034 acfg->w = img_writer_create (acfg->fp, FALSE);
9036 tmp_outfile_name = NULL;
9037 outfile_name = NULL;
9040 acfg->got_symbol = g_strdup_printf ("%s%s", acfg->llvm_label_prefix, acfg->got_symbol_base);
9042 /* Compute symbols for methods */
9043 for (i = 0; i < acfg->nmethods; ++i) {
9044 if (acfg->cfgs [i]) {
9045 MonoCompile *cfg = acfg->cfgs [i];
9046 int method_index = get_method_index (acfg, cfg->orig_method);
9048 if (COMPILE_LLVM (cfg))
9049 cfg->asm_symbol = g_strdup_printf ("%s%s", acfg->llvm_label_prefix, cfg->llvm_method_name);
9050 else if (acfg->global_symbols)
9051 cfg->asm_symbol = get_debug_sym (cfg->method, "", acfg->method_label_hash);
9053 cfg->asm_symbol = g_strdup_printf ("%s%sm_%x", acfg->temp_prefix, acfg->llvm_label_prefix, method_index);
9057 if (acfg->aot_opts.dwarf_debug && acfg->aot_opts.asm_only && acfg->aot_opts.gnu_asm) {
9059 * CLANG supports GAS .file/.loc directives, so emit line number information this way
9060 * FIXME: CLANG only emits line number info for .loc directives followed by assembly, not
9063 //acfg->gas_line_numbers = TRUE;
9066 if (!acfg->aot_opts.nodebug || acfg->aot_opts.dwarf_debug) {
9067 if (acfg->aot_opts.dwarf_debug && !mono_debug_enabled ()) {
9068 aot_printerrf (acfg, "The dwarf AOT option requires the --debug option.\n");
9071 acfg->dwarf = mono_dwarf_writer_create (acfg->w, NULL, 0, FALSE, !acfg->gas_line_numbers);
9074 img_writer_emit_start (acfg->w);
9077 mono_dwarf_writer_emit_base_info (acfg->dwarf, g_path_get_basename (acfg->image->name), mono_unwind_get_cie_program ());
9079 if (acfg->thumb_mixed) {
9082 * This global symbol marks the end of THUMB code, and the beginning of ARM
9083 * code generated by our JIT.
9085 sprintf (symbol, "thumb_end");
9086 emit_section_change (acfg, ".text", 0);
9087 emit_alignment (acfg, 8);
9088 emit_label (acfg, symbol);
9089 emit_zero_bytes (acfg, 16);
9091 fprintf (acfg->fp, ".arm\n");
9098 emit_extra_methods (acfg);
9100 emit_trampolines (acfg);
9102 emit_class_name_table (acfg);
9104 emit_got_info (acfg);
9106 emit_exception_info (acfg);
9108 emit_unwind_info (acfg);
9110 emit_class_info (acfg);
9114 emit_image_table (acfg);
9118 emit_file_info (acfg);
9122 emit_objc_selectors (acfg);
9124 emit_globals (acfg);
9126 emit_autoreg (acfg);
9129 emit_dwarf_info (acfg);
9130 mono_dwarf_writer_close (acfg->dwarf);
9133 emit_mem_end (acfg);
9135 if (acfg->need_pt_gnu_stack) {
9136 /* This is required so the .so doesn't have an executable stack */
9137 /* The bin writer already emits this */
9138 if (!acfg->use_bin_writer)
9139 fprintf (acfg->fp, "\n.section .note.GNU-stack,\"\",@progbits\n");
9144 acfg->stats.gen_time = TV_ELAPSED (atv, btv);
9147 g_assert (acfg->got_offset <= acfg->final_got_size);
9150 sprintf (llvm_stats_msg, ", LLVM: %d (%d%%)", acfg->stats.llvm_count, acfg->stats.mcount ? (acfg->stats.llvm_count * 100) / acfg->stats.mcount : 100);
9152 strcpy (llvm_stats_msg, "");
9154 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;
9156 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",
9157 acfg->stats.code_size, acfg->stats.code_size * 100 / all_sizes,
9158 acfg->stats.info_size, acfg->stats.info_size * 100 / all_sizes,
9159 acfg->stats.ex_info_size, acfg->stats.ex_info_size * 100 / all_sizes,
9160 acfg->stats.unwind_info_size, acfg->stats.unwind_info_size * 100 / all_sizes,
9161 acfg->stats.class_info_size, acfg->stats.class_info_size * 100 / all_sizes,
9162 acfg->stats.plt_size ? acfg->stats.plt_size : acfg->plt_offset, acfg->stats.plt_size ? acfg->stats.plt_size * 100 / all_sizes : 0,
9163 acfg->stats.got_info_size, acfg->stats.got_info_size * 100 / all_sizes,
9164 acfg->stats.offsets_size, acfg->stats.offsets_size * 100 / all_sizes,
9165 (int)(acfg->got_offset * sizeof (gpointer)));
9166 aot_printf (acfg, "Compiled: %d/%d (%d%%)%s, No GOT slots: %d (%d%%), Direct calls: %d (%d%%)\n",
9167 acfg->stats.ccount, acfg->stats.mcount, acfg->stats.mcount ? (acfg->stats.ccount * 100) / acfg->stats.mcount : 100,
9169 acfg->stats.methods_without_got_slots, acfg->stats.mcount ? (acfg->stats.methods_without_got_slots * 100) / acfg->stats.mcount : 100,
9170 acfg->stats.direct_calls, acfg->stats.all_calls ? (acfg->stats.direct_calls * 100) / acfg->stats.all_calls : 100);
9171 if (acfg->stats.genericcount)
9172 aot_printf (acfg, "%d methods are generic (%d%%)\n", acfg->stats.genericcount, acfg->stats.mcount ? (acfg->stats.genericcount * 100) / acfg->stats.mcount : 100);
9173 if (acfg->stats.abscount)
9174 aot_printf (acfg, "%d methods contain absolute addresses (%d%%)\n", acfg->stats.abscount, acfg->stats.mcount ? (acfg->stats.abscount * 100) / acfg->stats.mcount : 100);
9175 if (acfg->stats.lmfcount)
9176 aot_printf (acfg, "%d methods contain lmf pointers (%d%%)\n", acfg->stats.lmfcount, acfg->stats.mcount ? (acfg->stats.lmfcount * 100) / acfg->stats.mcount : 100);
9177 if (acfg->stats.ocount)
9178 aot_printf (acfg, "%d methods have other problems (%d%%)\n", acfg->stats.ocount, acfg->stats.mcount ? (acfg->stats.ocount * 100) / acfg->stats.mcount : 100);
9181 res = img_writer_emit_writeout (acfg->w);
9186 if (acfg->use_bin_writer) {
9187 int err = rename (tmp_outfile_name, outfile_name);
9190 aot_printf (acfg, "Unable to rename '%s' to '%s': %s\n", tmp_outfile_name, outfile_name, strerror (errno));
9194 res = compile_asm (acfg);
9201 acfg->stats.link_time = TV_ELAPSED (atv, btv);
9203 if (acfg->aot_opts.stats) {
9206 aot_printf (acfg, "GOT slot distribution:\n");
9207 for (i = 0; i < MONO_PATCH_INFO_NONE; ++i)
9208 if (acfg->stats.got_slot_types [i])
9209 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]);
9212 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);
9224 mono_aot_readonly_field_override (MonoClassField *field)
9230 mono_compile_assembly (MonoAssembly *ass, guint32 opts, const char *aot_options)