2 * aot-compiler.c: mono Ahead of Time compiler
5 * Dietmar Maurer (dietmar@ximian.com)
6 * Zoltan Varga (vargaz@gmail.com)
8 * (C) 2002 Ximian, Inc.
9 * Copyright 2003-2011 Novell, Inc
10 * Copyright 2011 Xamarin Inc (http://www.xamarin.com)
14 #include <sys/types.h>
34 #include <mono/metadata/abi-details.h>
35 #include <mono/metadata/tabledefs.h>
36 #include <mono/metadata/class.h>
37 #include <mono/metadata/object.h>
38 #include <mono/metadata/tokentype.h>
39 #include <mono/metadata/appdomain.h>
40 #include <mono/metadata/debug-helpers.h>
41 #include <mono/metadata/assembly.h>
42 #include <mono/metadata/metadata-internals.h>
43 #include <mono/metadata/marshal.h>
44 #include <mono/metadata/gc-internals.h>
45 #include <mono/metadata/mempool-internals.h>
46 #include <mono/metadata/mono-endian.h>
47 #include <mono/metadata/threads-types.h>
48 #include <mono/utils/mono-logger-internals.h>
49 #include <mono/utils/mono-compiler.h>
50 #include <mono/utils/mono-time.h>
51 #include <mono/utils/mono-mmap.h>
52 #include <mono/utils/json.h>
54 #include "aot-compiler.h"
55 #include "seq-points.h"
56 #include "image-writer.h"
57 #include "dwarfwriter.h"
59 #include "mini-llvm.h"
61 #if !defined(DISABLE_AOT) && !defined(DISABLE_JIT)
63 #if defined(__linux__) || defined(__native_client_codegen__)
64 #define RODATA_SECT ".rodata"
65 #elif defined(TARGET_MACH)
66 #define RODATA_SECT ".section __TEXT, __const"
68 #define RODATA_SECT ".text"
71 #define TV_DECLARE(name) gint64 name
72 #define TV_GETTIME(tv) tv = mono_100ns_ticks ()
73 #define TV_ELAPSED(start,end) (((end) - (start)) / 10)
75 #define ALIGN_TO(val,align) ((((guint64)val) + ((align) - 1)) & ~((align) - 1))
76 #define ALIGN_PTR_TO(ptr,align) (gpointer)((((gssize)(ptr)) + (align - 1)) & (~(align - 1)))
77 #define ROUND_DOWN(VALUE,SIZE) ((VALUE) & ~((SIZE) - 1))
79 /* predefined values for static readonly fields without needed to run the .cctor */
80 typedef struct _ReadOnlyValue ReadOnlyValue;
81 struct _ReadOnlyValue {
84 int type; /* to be used later for typechecking to prevent user errors */
93 static ReadOnlyValue *readonly_values;
95 typedef struct MonoAotOptions {
99 gboolean write_symbols;
100 gboolean metadata_only;
101 gboolean bind_to_runtime_version;
104 gboolean static_link;
108 gboolean dwarf_debug;
110 gboolean log_generics;
111 gboolean log_instances;
112 gboolean gen_seq_points_file;
113 gboolean direct_pinvoke;
114 gboolean direct_icalls;
115 gboolean no_direct_calls;
116 gboolean use_trampolines_page;
117 gboolean no_instances;
123 int nrgctx_trampolines;
124 int nimt_trampolines;
125 int ngsharedvt_arg_trampolines;
126 int nrgctx_fetch_trampolines;
127 gboolean print_skipped_methods;
134 char *instances_logfile_path;
139 typedef struct MonoAotStats {
140 int ccount, mcount, lmfcount, abscount, gcount, ocount, genericcount;
141 gint64 code_size, info_size, ex_info_size, unwind_info_size, got_size, class_info_size, got_info_size, plt_size;
142 int methods_without_got_slots, direct_calls, all_calls, llvm_count;
143 int got_slots, offsets_size;
144 int got_slot_types [MONO_PATCH_INFO_NONE];
145 int got_slot_info_sizes [MONO_PATCH_INFO_NONE];
146 int jit_time, gen_time, link_time;
149 typedef struct GotInfo {
150 GHashTable *patch_to_got_offset;
151 GHashTable **patch_to_got_offset_by_type;
152 GPtrArray *got_patches;
155 typedef struct MonoAotCompile {
158 GHashTable *method_indexes;
159 GHashTable *method_depth;
162 GHashTable **patch_to_plt_entry;
163 GHashTable *plt_offset_to_entry;
164 //GHashTable *patch_to_got_offset;
165 //GHashTable **patch_to_got_offset_by_type;
166 //GPtrArray *got_patches;
167 GotInfo got_info, llvm_got_info;
168 GHashTable *image_hash;
169 GHashTable *method_to_cfg;
170 GHashTable *token_info_hash;
171 GHashTable *method_to_pinvoke_import;
172 GPtrArray *extra_methods;
173 GPtrArray *image_table;
175 GPtrArray *method_order;
176 GHashTable *export_names;
177 /* Maps MonoClass* -> blob offset */
178 GHashTable *klass_blob_hash;
179 /* Maps MonoMethod* -> blob offset */
180 GHashTable *method_blob_hash;
181 guint32 *plt_got_info_offsets;
182 guint32 got_offset, llvm_got_offset, plt_offset, plt_got_offset_base, nshared_got_entries;
183 /* Number of GOT entries reserved for trampolines */
184 guint32 num_trampoline_got_entries;
185 guint32 tramp_page_size;
187 guint32 num_trampolines [MONO_AOT_TRAMP_NUM];
188 guint32 trampoline_got_offset_base [MONO_AOT_TRAMP_NUM];
189 guint32 trampoline_size [MONO_AOT_TRAMP_NUM];
190 guint32 tramp_page_code_offsets [MONO_AOT_TRAMP_NUM];
192 MonoAotOptions aot_opts;
196 MonoMemPool *mempool;
199 char *static_linking_symbol;
201 gboolean gas_line_numbers;
202 /* Whenever to emit an object file directly from llc */
203 gboolean llvm_owriter;
205 MonoDwarfWriter *dwarf;
212 GHashTable *unwind_info_offsets;
213 GPtrArray *unwind_ops;
214 guint32 unwind_info_offset;
217 char *llvm_got_symbol;
219 char *llvm_eh_frame_symbol;
220 GHashTable *method_label_hash;
221 const char *temp_prefix;
222 const char *user_symbol_prefix;
223 const char *llvm_label_prefix;
224 const char *inst_directive;
226 guint32 label_generator;
228 gboolean has_jitted_code;
229 MonoAotFileFlags flags;
230 MonoDynamicStream blob;
231 MonoClass **typespec_classes;
234 char *assembly_name_sym;
235 GHashTable *plt_entry_debug_sym_cache;
236 gboolean thumb_mixed, need_no_dead_strip, need_pt_gnu_stack;
237 GHashTable *ginst_hash;
238 GHashTable *dwarf_ln_filenames;
239 gboolean global_symbols;
240 int objc_selector_index, objc_selector_index_2;
241 GPtrArray *objc_selectors;
242 GHashTable *objc_selector_to_index;
244 FILE *instances_logfile;
249 char *symbol, *llvm_symbol, *debug_sym;
251 gboolean jit_used, llvm_used;
254 #define mono_acfg_lock(acfg) mono_os_mutex_lock (&((acfg)->mutex))
255 #define mono_acfg_unlock(acfg) mono_os_mutex_unlock (&((acfg)->mutex))
257 /* This points to the current acfg in LLVM mode */
258 static MonoAotCompile *llvm_acfg;
260 #ifdef HAVE_ARRAY_ELEM_INIT
261 #define MSGSTRFIELD(line) MSGSTRFIELD1(line)
262 #define MSGSTRFIELD1(line) str##line
263 static const struct msgstr_t {
264 #define PATCH_INFO(a,b) char MSGSTRFIELD(__LINE__) [sizeof (b)];
265 #include "patch-info.h"
268 #define PATCH_INFO(a,b) b,
269 #include "patch-info.h"
272 static const gint16 opidx [] = {
273 #define PATCH_INFO(a,b) [MONO_PATCH_INFO_ ## a] = offsetof (struct msgstr_t, MSGSTRFIELD(__LINE__)),
274 #include "patch-info.h"
278 static G_GNUC_UNUSED const char*
279 get_patch_name (int info)
281 return (const char*)&opstr + opidx [info];
285 #define PATCH_INFO(a,b) b,
286 static const char* const
287 patch_types [MONO_PATCH_INFO_NUM + 1] = {
288 #include "patch-info.h"
292 static G_GNUC_UNUSED const char*
293 get_patch_name (int info)
295 return patch_types [info];
301 get_unwind_info_offset (MonoAotCompile *acfg, guint8 *encoded, guint32 encoded_len);
304 get_plt_entry_debug_sym (MonoAotCompile *acfg, MonoJumpInfo *ji, GHashTable *cache);
307 aot_printf (MonoAotCompile *acfg, const gchar *format, ...)
313 output = acfg->logfile;
317 va_start (args, format);
318 vfprintf (output, format, args);
323 aot_printerrf (MonoAotCompile *acfg, const gchar *format, ...)
329 output = acfg->logfile;
333 va_start (args, format);
334 vfprintf (output, format, args);
339 report_loader_error (MonoAotCompile *acfg, MonoError *error, const char *format, ...)
344 if (mono_error_ok (error))
348 output = acfg->logfile;
352 va_start (args, format);
353 vfprintf (output, format, args);
355 mono_error_cleanup (error);
357 g_error ("FullAOT cannot continue if there are loader errors");
360 /* Wrappers around the image writer functions */
363 emit_section_change (MonoAotCompile *acfg, const char *section_name, int subsection_index)
365 mono_img_writer_emit_section_change (acfg->w, section_name, subsection_index);
369 emit_local_symbol (MonoAotCompile *acfg, const char *name, const char *end_label, gboolean func)
371 mono_img_writer_emit_local_symbol (acfg->w, name, end_label, func);
375 emit_label (MonoAotCompile *acfg, const char *name)
377 mono_img_writer_emit_label (acfg->w, name);
381 emit_bytes (MonoAotCompile *acfg, const guint8* buf, int size)
383 mono_img_writer_emit_bytes (acfg->w, buf, size);
387 emit_string (MonoAotCompile *acfg, const char *value)
389 mono_img_writer_emit_string (acfg->w, value);
393 emit_line (MonoAotCompile *acfg)
395 mono_img_writer_emit_line (acfg->w);
399 emit_alignment (MonoAotCompile *acfg, int size)
401 mono_img_writer_emit_alignment (acfg->w, size);
405 emit_alignment_code (MonoAotCompile *acfg, int size)
407 if (acfg->align_pad_value)
408 mono_img_writer_emit_alignment_fill (acfg->w, size, acfg->align_pad_value);
410 mono_img_writer_emit_alignment (acfg->w, size);
414 emit_padding (MonoAotCompile *acfg, int size)
419 if (acfg->align_pad_value) {
420 for (i = 0; i < 16; ++i)
421 buf [i] = acfg->align_pad_value;
423 memset (buf, 0, sizeof (buf));
426 for (i = 0; i < size; i += 16) {
428 emit_bytes (acfg, buf, size - i);
430 emit_bytes (acfg, buf, 16);
435 emit_pointer (MonoAotCompile *acfg, const char *target)
437 mono_img_writer_emit_pointer (acfg->w, target);
441 emit_pointer_2 (MonoAotCompile *acfg, const char *prefix, const char *target)
443 if (prefix [0] != '\0') {
444 char *s = g_strdup_printf ("%s%s", prefix, target);
445 mono_img_writer_emit_pointer (acfg->w, s);
448 mono_img_writer_emit_pointer (acfg->w, target);
453 emit_int16 (MonoAotCompile *acfg, int value)
455 mono_img_writer_emit_int16 (acfg->w, value);
459 emit_int32 (MonoAotCompile *acfg, int value)
461 mono_img_writer_emit_int32 (acfg->w, value);
465 emit_symbol_diff (MonoAotCompile *acfg, const char *end, const char* start, int offset)
467 mono_img_writer_emit_symbol_diff (acfg->w, end, start, offset);
471 emit_zero_bytes (MonoAotCompile *acfg, int num)
473 mono_img_writer_emit_zero_bytes (acfg->w, num);
477 emit_byte (MonoAotCompile *acfg, guint8 val)
479 mono_img_writer_emit_byte (acfg->w, val);
482 #ifdef __native_client_codegen__
484 emit_nacl_call_alignment (MonoAotCompile *acfg)
486 mono_img_writer_emit_nacl_call_alignment (acfg->w);
490 static G_GNUC_UNUSED void
491 emit_global_inner (MonoAotCompile *acfg, const char *name, gboolean func)
493 mono_img_writer_emit_global (acfg->w, name, func);
497 emit_global (MonoAotCompile *acfg, const char *name, gboolean func)
499 if (acfg->aot_opts.no_dlsym) {
500 g_ptr_array_add (acfg->globals, g_strdup (name));
501 mono_img_writer_emit_local_symbol (acfg->w, name, NULL, func);
503 mono_img_writer_emit_global (acfg->w, name, func);
508 emit_symbol_size (MonoAotCompile *acfg, const char *name, const char *end_label)
510 mono_img_writer_emit_symbol_size (acfg->w, name, end_label);
513 /* Emit a symbol which is referenced by the MonoAotFileInfo structure */
515 emit_info_symbol (MonoAotCompile *acfg, const char *name)
520 emit_label (acfg, name);
521 /* LLVM generated code references this */
522 sprintf (symbol, "%s%s%s", acfg->user_symbol_prefix, acfg->global_prefix, name);
523 emit_label (acfg, symbol);
524 emit_global_inner (acfg, symbol, FALSE);
526 emit_label (acfg, name);
531 emit_string_symbol (MonoAotCompile *acfg, const char *name, const char *value)
534 mono_llvm_emit_aot_data (name, (guint8*)value, strlen (value) + 1);
538 mono_img_writer_emit_section_change (acfg->w, RODATA_SECT, 1);
540 /* On apple, all symbols need to be aligned to avoid warnings from ld */
541 emit_alignment (acfg, 4);
543 mono_img_writer_emit_label (acfg->w, name);
544 mono_img_writer_emit_string (acfg->w, value);
547 static G_GNUC_UNUSED void
548 emit_uleb128 (MonoAotCompile *acfg, guint32 value)
551 guint8 b = value & 0x7f;
553 if (value != 0) /* more bytes to come */
559 static G_GNUC_UNUSED void
560 emit_sleb128 (MonoAotCompile *acfg, gint64 value)
563 gboolean negative = (value < 0);
570 /* the following is unnecessary if the
571 * implementation of >>= uses an arithmetic rather
572 * than logical shift for a signed left operand
576 value |= - ((gint64)1 <<(size - 7));
577 /* sign bit of byte is second high order bit (0x40) */
578 if ((value == 0 && !(byte & 0x40)) ||
579 (value == -1 && (byte & 0x40)))
583 emit_byte (acfg, byte);
587 static G_GNUC_UNUSED void
588 encode_uleb128 (guint32 value, guint8 *buf, guint8 **endbuf)
593 guint8 b = value & 0x7f;
595 if (value != 0) /* more bytes to come */
603 static G_GNUC_UNUSED void
604 encode_sleb128 (gint32 value, guint8 *buf, guint8 **endbuf)
607 gboolean negative = (value < 0);
615 /* the following is unnecessary if the
616 * implementation of >>= uses an arithmetic rather
617 * than logical shift for a signed left operand
621 value |= - (1 <<(size - 7));
622 /* sign bit of byte is second high order bit (0x40) */
623 if ((value == 0 && !(byte & 0x40)) ||
624 (value == -1 && (byte & 0x40)))
635 encode_int (gint32 val, guint8 *buf, guint8 **endbuf)
638 buf [0] = (val >> 0) & 0xff;
639 buf [1] = (val >> 8) & 0xff;
640 buf [2] = (val >> 16) & 0xff;
641 buf [3] = (val >> 24) & 0xff;
647 encode_int16 (guint16 val, guint8 *buf, guint8 **endbuf)
649 buf [0] = (val >> 0) & 0xff;
650 buf [1] = (val >> 8) & 0xff;
656 encode_string (const char *s, guint8 *buf, guint8 **endbuf)
658 int len = strlen (s);
660 memcpy (buf, s, len + 1);
661 *endbuf = buf + len + 1;
665 emit_unset_mode (MonoAotCompile *acfg)
667 mono_img_writer_emit_unset_mode (acfg->w);
670 static G_GNUC_UNUSED void
671 emit_set_thumb_mode (MonoAotCompile *acfg)
673 emit_unset_mode (acfg);
674 fprintf (acfg->fp, ".code 16\n");
677 static G_GNUC_UNUSED void
678 emit_set_arm_mode (MonoAotCompile *acfg)
680 emit_unset_mode (acfg);
681 fprintf (acfg->fp, ".code 32\n");
685 emit_code_bytes (MonoAotCompile *acfg, const guint8* buf, int size)
690 g_assert (size % 4 == 0);
691 emit_unset_mode (acfg);
692 for (i = 0; i < size; i += 4)
693 fprintf (acfg->fp, "%s 0x%x\n", acfg->inst_directive, *(guint32*)(buf + i));
695 emit_bytes (acfg, buf, size);
699 /* ARCHITECTURE SPECIFIC CODE */
701 #if defined(TARGET_X86) || defined(TARGET_AMD64) || defined(TARGET_ARM) || defined(TARGET_POWERPC) || defined(TARGET_ARM64)
702 #define EMIT_DWARF_INFO 1
705 #if defined(TARGET_ARM)
706 #define AOT_FUNC_ALIGNMENT 4
708 #define AOT_FUNC_ALIGNMENT 16
710 #if (defined(TARGET_X86) || defined(TARGET_AMD64)) && defined(__native_client_codegen__)
711 #undef AOT_FUNC_ALIGNMENT
712 #define AOT_FUNC_ALIGNMENT 32
715 #if defined(TARGET_POWERPC64) && !defined(__mono_ilp32__)
716 #define PPC_LD_OP "ld"
717 #define PPC_LDX_OP "ldx"
719 #define PPC_LD_OP "lwz"
720 #define PPC_LDX_OP "lwzx"
724 #define AOT_TARGET_STR "AMD64"
729 #define AOT_TARGET_STR "ARM (MACH)"
731 #define AOT_TARGET_STR "ARM (!MACH)"
737 #define AOT_TARGET_STR "ARM64 (MACH)"
739 #define AOT_TARGET_STR "ARM64 (!MACH)"
743 #ifdef TARGET_POWERPC64
744 #ifdef __mono_ilp32__
745 #define AOT_TARGET_STR "POWERPC64 (mono ilp32)"
747 #define AOT_TARGET_STR "POWERPC64 (!mono ilp32)"
750 #ifdef TARGET_POWERPC
751 #ifdef __mono_ilp32__
752 #define AOT_TARGET_STR "POWERPC (mono ilp32)"
754 #define AOT_TARGET_STR "POWERPC (!mono ilp32)"
761 #define AOT_TARGET_STR "X86 (WIN32)"
762 #elif defined(__native_client_codegen__)
763 #define AOT_TARGET_STR "X86 (native client codegen)"
765 #define AOT_TARGET_STR "X86 (!native client codegen)"
769 #ifndef AOT_TARGET_STR
770 #define AOT_TARGET_STR ""
774 arch_init (MonoAotCompile *acfg)
776 acfg->llc_args = g_string_new ("");
777 acfg->as_args = g_string_new ("");
780 * The prefix LLVM likes to put in front of symbol names on darwin.
781 * The mach-os specs require this for globals, but LLVM puts them in front of all
782 * symbols. We need to handle this, since we need to refer to LLVM generated
785 acfg->llvm_label_prefix = "";
786 acfg->user_symbol_prefix = "";
788 #if defined(TARGET_X86)
789 g_string_append (acfg->llc_args, " -march=x86 -mattr=sse4.1");
792 #if defined(TARGET_AMD64)
793 g_string_append (acfg->llc_args, " -march=x86-64 -mattr=sse4.1");
795 acfg->align_pad_value = 0x90;
799 if (acfg->aot_opts.mtriple && strstr (acfg->aot_opts.mtriple, "darwin")) {
800 g_string_append (acfg->llc_args, "-mattr=+v6");
803 g_string_append (acfg->llc_args, " -mattr=+vfp2,-neon,+d16");
804 g_string_append (acfg->as_args, " -mfpu=vfp3");
806 g_string_append (acfg->llc_args, " -soft-float");
809 if (acfg->aot_opts.mtriple && strstr (acfg->aot_opts.mtriple, "thumb"))
810 acfg->thumb_mixed = TRUE;
812 if (acfg->aot_opts.mtriple)
813 mono_arch_set_target (acfg->aot_opts.mtriple);
817 acfg->inst_directive = ".inst";
818 if (acfg->aot_opts.mtriple)
819 mono_arch_set_target (acfg->aot_opts.mtriple);
823 acfg->user_symbol_prefix = "_";
824 acfg->llvm_label_prefix = "_";
825 acfg->inst_directive = ".word";
826 acfg->need_no_dead_strip = TRUE;
827 acfg->aot_opts.gnu_asm = TRUE;
830 #if defined(__linux__) && !defined(TARGET_ARM)
831 acfg->need_pt_gnu_stack = TRUE;
835 acfg->global_symbols = TRUE;
841 #include "../../../mono-extensions/mono/mini/aot-compiler-arm64.c"
845 #ifdef MONO_ARCH_AOT_SUPPORTED
847 * arch_emit_direct_call:
849 * Emit a direct call to the symbol TARGET. CALL_SIZE is set to the size of the
853 arch_emit_direct_call (MonoAotCompile *acfg, const char *target, gboolean external, gboolean thumb, MonoJumpInfo *ji, int *call_size)
855 #if defined(TARGET_X86) || defined(TARGET_AMD64)
856 /* Need to make sure this is exactly 5 bytes long */
857 emit_unset_mode (acfg);
858 fprintf (acfg->fp, "call %s\n", target);
860 #elif defined(TARGET_ARM)
861 emit_unset_mode (acfg);
863 fprintf (acfg->fp, "blx %s\n", target);
865 fprintf (acfg->fp, "bl %s\n", target);
867 #elif defined(TARGET_ARM64)
868 arm64_emit_direct_call (acfg, target, external, thumb, ji, call_size);
869 #elif defined(TARGET_POWERPC)
870 emit_unset_mode (acfg);
871 fprintf (acfg->fp, "bl %s\n", target);
874 g_assert_not_reached ();
881 * - we use an approach similar to the x86 abi: reserve a register (r30) to hold
883 * - The full-aot trampolines need access to the GOT of mscorlib, so we store
884 * in in the 2. slot of every GOT, and require every method to place the GOT
885 * address in r30, even when it doesn't access the GOT otherwise. This way,
886 * the trampolines can compute the mscorlib GOT address by loading 4(r30).
891 * PPC64 uses function descriptors which greatly complicate all code, since
892 * these are used very inconsistently in the runtime. Some functions like
893 * mono_compile_method () return ftn descriptors, while others like the
894 * trampoline creation functions do not.
895 * We assume that all GOT slots contain function descriptors, and create
896 * descriptors in aot-runtime.c when needed.
897 * The ppc64 abi uses r2 to hold the address of the TOC/GOT, which is loaded
898 * from function descriptors, we could do the same, but it would require
899 * rewriting all the ppc/aot code to handle function descriptors properly.
900 * So instead, we use the same approach as on PPC32.
901 * This is a horrible mess, but fixing it would probably lead to an even bigger
907 * - similar to the PPC32 design, we reserve EBX to hold the GOT pointer.
910 #ifdef MONO_ARCH_AOT_SUPPORTED
912 * arch_emit_got_offset:
914 * The memory pointed to by CODE should hold native code for computing the GOT
915 * address (OP_LOAD_GOTADDR). Emit this code while patching it with the offset
916 * between code and the GOT. CODE_SIZE is set to the number of bytes emitted.
919 arch_emit_got_offset (MonoAotCompile *acfg, guint8 *code, int *code_size)
921 #if defined(TARGET_POWERPC64)
922 emit_unset_mode (acfg);
924 * The ppc32 code doesn't seem to work on ppc64, the assembler complains about
925 * unsupported relocations. So we store the got address into the .Lgot_addr
926 * symbol which is in the text segment, compute its address, and load it.
928 fprintf (acfg->fp, ".L%d:\n", acfg->label_generator);
929 fprintf (acfg->fp, "lis 0, (.Lgot_addr + 4 - .L%d)@h\n", acfg->label_generator);
930 fprintf (acfg->fp, "ori 0, 0, (.Lgot_addr + 4 - .L%d)@l\n", acfg->label_generator);
931 fprintf (acfg->fp, "add 30, 30, 0\n");
932 fprintf (acfg->fp, "%s 30, 0(30)\n", PPC_LD_OP);
933 acfg->label_generator ++;
935 #elif defined(TARGET_POWERPC)
936 emit_unset_mode (acfg);
937 fprintf (acfg->fp, ".L%d:\n", acfg->label_generator);
938 fprintf (acfg->fp, "lis 0, (%s + 4 - .L%d)@h\n", acfg->got_symbol, acfg->label_generator);
939 fprintf (acfg->fp, "ori 0, 0, (%s + 4 - .L%d)@l\n", acfg->got_symbol, acfg->label_generator);
940 acfg->label_generator ++;
943 guint32 offset = mono_arch_get_patch_offset (code);
944 emit_bytes (acfg, code, offset);
945 emit_symbol_diff (acfg, acfg->got_symbol, ".", offset);
947 *code_size = offset + 4;
952 * arch_emit_got_access:
954 * The memory pointed to by CODE should hold native code for loading a GOT
955 * slot (OP_AOTCONST/OP_GOT_ENTRY). Emit this code while patching it so it accesses the
956 * GOT slot GOT_SLOT. CODE_SIZE is set to the number of bytes emitted.
959 arch_emit_got_access (MonoAotCompile *acfg, const char *got_symbol, guint8 *code, int got_slot, int *code_size)
962 /* mov reg, got+offset(%rip) */
964 /* The GOT symbol is in the LLVM module, the clang assembler has problems emitting symbol diffs for it */
968 /* Decode reg, see amd64_mov_reg_membase () */
969 rex_r = code [0] & AMD64_REX_R;
970 g_assert (code [0] == 0x49 + rex_r);
971 g_assert (code [1] == 0x8b);
972 dreg = ((code [2] >> 3) & 0x7) + (rex_r ? 8 : 0);
974 emit_unset_mode (acfg);
975 fprintf (acfg->fp, "mov %s+%d(%%rip), %s\n", got_symbol, (unsigned int) ((got_slot * sizeof (gpointer))), mono_arch_regname (dreg));
978 emit_bytes (acfg, code, mono_arch_get_patch_offset (code));
979 emit_symbol_diff (acfg, got_symbol, ".", (unsigned int) ((got_slot * sizeof (gpointer)) - 4));
980 *code_size = mono_arch_get_patch_offset (code) + 4;
982 #elif defined(TARGET_X86)
983 emit_bytes (acfg, code, mono_arch_get_patch_offset (code));
984 emit_int32 (acfg, (unsigned int) ((got_slot * sizeof (gpointer))));
985 *code_size = mono_arch_get_patch_offset (code) + 4;
986 #elif defined(TARGET_ARM)
987 emit_bytes (acfg, code, mono_arch_get_patch_offset (code));
988 emit_symbol_diff (acfg, got_symbol, ".", (unsigned int) ((got_slot * sizeof (gpointer))) - 12);
989 *code_size = mono_arch_get_patch_offset (code) + 4;
990 #elif defined(TARGET_ARM64)
991 emit_bytes (acfg, code, mono_arch_get_patch_offset (code));
992 arm64_emit_got_access (acfg, code, got_slot, code_size);
993 #elif defined(TARGET_POWERPC)
998 emit_bytes (acfg, code, mono_arch_get_patch_offset (code));
1000 ppc_load32 (code, ppc_r0, got_slot * sizeof (gpointer));
1001 g_assert (code - buf == 8);
1002 emit_bytes (acfg, buf, code - buf);
1003 *code_size = code - buf;
1006 g_assert_not_reached ();
1012 #ifdef MONO_ARCH_AOT_SUPPORTED
1014 * arch_emit_objc_selector_ref:
1016 * Emit the implementation of OP_OBJC_GET_SELECTOR, which itself implements @selector(foo:) in objective-c.
1019 arch_emit_objc_selector_ref (MonoAotCompile *acfg, guint8 *code, int index, int *code_size)
1021 #if defined(TARGET_ARM)
1024 int lindex = acfg->objc_selector_index_2 ++;
1026 /* Emit ldr.imm/b */
1027 emit_bytes (acfg, code, 8);
1029 sprintf (symbol1, "L_OBJC_SELECTOR_%d", lindex);
1030 sprintf (symbol2, "L_OBJC_SELECTOR_REFERENCES_%d", index);
1032 emit_label (acfg, symbol1);
1033 mono_img_writer_emit_unset_mode (acfg->w);
1034 fprintf (acfg->fp, ".long %s-(%s+12)", symbol2, symbol1);
1037 #elif defined(TARGET_ARM64)
1038 arm64_emit_objc_selector_ref (acfg, code, index, code_size);
1040 g_assert_not_reached ();
1046 * arch_emit_plt_entry:
1048 * Emit code for the PLT entry.
1049 * The plt entry should look like this:
1050 * <indirect jump to GOT_SYMBOL + OFFSET>
1051 * <INFO_OFFSET embedded into the instruction stream>
1054 arch_emit_plt_entry (MonoAotCompile *acfg, const char *got_symbol, int offset, int info_offset)
1056 #if defined(TARGET_X86)
1057 #if defined(__default_codegen__)
1058 /* jmp *<offset>(%ebx) */
1059 emit_byte (acfg, 0xff);
1060 emit_byte (acfg, 0xa3);
1061 emit_int32 (acfg, offset);
1062 /* Used by mono_aot_get_plt_info_offset */
1063 emit_int32 (acfg, info_offset);
1064 #elif defined(__native_client_codegen__)
1065 const guint8 kSizeOfNaClJmp = 11;
1066 guint8 bytes[kSizeOfNaClJmp];
1067 guint8 *pbytes = &bytes[0];
1069 x86_jump_membase32 (pbytes, X86_EBX, offset);
1070 emit_bytes (acfg, bytes, kSizeOfNaClJmp);
1071 /* four bytes of data, used by mono_arch_patch_plt_entry */
1072 /* For Native Client, make this work with data embedded in push. */
1073 emit_byte (acfg, 0x68); /* hide data in a push */
1074 emit_int32 (acfg, info_offset);
1075 emit_alignment (acfg, AOT_FUNC_ALIGNMENT);
1076 #endif /*__native_client_codegen__*/
1077 #elif defined(TARGET_AMD64)
1078 #if defined(__default_codegen__)
1079 emit_unset_mode (acfg);
1080 fprintf (acfg->fp, "jmp *%s+%d(%%rip)\n", got_symbol, offset);
1081 /* Used by mono_aot_get_plt_info_offset */
1082 emit_int32 (acfg, info_offset);
1083 acfg->stats.plt_size += 10;
1084 #elif defined(__native_client_codegen__)
1086 guint8 *buf_aligned = ALIGN_TO(buf, kNaClAlignment);
1087 guint8 *code = buf_aligned;
1089 /* mov <OFFSET>(%rip), %r11d */
1090 emit_byte (acfg, '\x45');
1091 emit_byte (acfg, '\x8b');
1092 emit_byte (acfg, '\x1d');
1093 emit_symbol_diff (acfg, got_symbol, ".", offset - 4);
1095 amd64_jump_reg (code, AMD64_R11);
1096 /* This should be constant for the plt patch */
1097 g_assert ((size_t)(code-buf_aligned) == 10);
1098 emit_bytes (acfg, buf_aligned, code - buf_aligned);
1100 /* Hide data in a push imm32 so it passes validation */
1101 emit_byte (acfg, 0x68); /* push */
1102 emit_int32 (acfg, info_offset);
1103 emit_alignment (acfg, AOT_FUNC_ALIGNMENT);
1104 #endif /*__native_client_codegen__*/
1105 #elif defined(TARGET_ARM)
1110 ARM_LDR_IMM (code, ARMREG_IP, ARMREG_PC, 0);
1111 ARM_LDR_REG_REG (code, ARMREG_PC, ARMREG_PC, ARMREG_IP);
1112 emit_bytes (acfg, buf, code - buf);
1113 emit_symbol_diff (acfg, got_symbol, ".", offset - 4);
1114 /* Used by mono_aot_get_plt_info_offset */
1115 emit_int32 (acfg, info_offset);
1116 #elif defined(TARGET_ARM64)
1117 arm64_emit_plt_entry (acfg, got_symbol, offset, info_offset);
1118 #elif defined(TARGET_POWERPC)
1119 /* The GOT address is guaranteed to be in r30 by OP_LOAD_GOTADDR */
1120 emit_unset_mode (acfg);
1121 fprintf (acfg->fp, "lis 11, %d@h\n", offset);
1122 fprintf (acfg->fp, "ori 11, 11, %d@l\n", offset);
1123 fprintf (acfg->fp, "add 11, 11, 30\n");
1124 fprintf (acfg->fp, "%s 11, 0(11)\n", PPC_LD_OP);
1125 #ifdef PPC_USES_FUNCTION_DESCRIPTOR
1126 fprintf (acfg->fp, "%s 2, %d(11)\n", PPC_LD_OP, (int)sizeof (gpointer));
1127 fprintf (acfg->fp, "%s 11, 0(11)\n", PPC_LD_OP);
1129 fprintf (acfg->fp, "mtctr 11\n");
1130 fprintf (acfg->fp, "bctr\n");
1131 emit_int32 (acfg, info_offset);
1133 g_assert_not_reached ();
1138 * arch_emit_llvm_plt_entry:
1140 * Same as arch_emit_plt_entry, but handles calls from LLVM generated code.
1141 * This is only needed on arm to handle thumb interop.
1144 arch_emit_llvm_plt_entry (MonoAotCompile *acfg, const char *got_symbol, int offset, int info_offset)
1146 #if defined(TARGET_ARM)
1147 /* LLVM calls the PLT entries using bl, so these have to be thumb2 */
1148 /* The caller already transitioned to thumb */
1149 /* The code below should be 12 bytes long */
1150 /* clang has trouble encoding these instructions, so emit the binary */
1152 fprintf (acfg->fp, "ldr ip, [pc, #8]\n");
1153 /* thumb can't encode ld pc, [pc, ip] */
1154 fprintf (acfg->fp, "add ip, pc, ip\n");
1155 fprintf (acfg->fp, "ldr ip, [ip, #0]\n");
1156 fprintf (acfg->fp, "bx ip\n");
1158 emit_set_thumb_mode (acfg);
1159 fprintf (acfg->fp, ".4byte 0xc008f8df\n");
1160 fprintf (acfg->fp, ".2byte 0x44fc\n");
1161 fprintf (acfg->fp, ".4byte 0xc000f8dc\n");
1162 fprintf (acfg->fp, ".2byte 0x4760\n");
1163 emit_symbol_diff (acfg, got_symbol, ".", offset + 4);
1164 emit_int32 (acfg, info_offset);
1165 emit_unset_mode (acfg);
1166 emit_set_arm_mode (acfg);
1168 g_assert_not_reached ();
1172 /* Save unwind_info in the module and emit the offset to the information at symbol */
1173 static void save_unwind_info (MonoAotCompile *acfg, char *symbol, GSList *unwind_ops)
1175 guint32 uw_offset, encoded_len;
1178 emit_section_change (acfg, RODATA_SECT, 0);
1179 emit_global (acfg, symbol, FALSE);
1180 emit_label (acfg, symbol);
1182 encoded = mono_unwind_ops_encode (unwind_ops, &encoded_len);
1183 uw_offset = get_unwind_info_offset (acfg, encoded, encoded_len);
1185 emit_int32 (acfg, uw_offset);
1189 * arch_emit_specific_trampoline_pages:
1191 * Emits a page full of trampolines: each trampoline uses its own address to
1192 * lookup both the generic trampoline code and the data argument.
1193 * This page can be remapped in process multiple times so we can get an
1194 * unlimited number of trampolines.
1195 * Specifically this implementation uses the following trick: two memory pages
1196 * are allocated, with the first containing the data and the second containing the trampolines.
1197 * To reduce trampoline size, each trampoline jumps at the start of the page where a common
1198 * implementation does all the lifting.
1199 * Note that the ARM single trampoline size is 8 bytes, exactly like the data that needs to be stored
1200 * on the arm 32 bit system.
1203 arch_emit_specific_trampoline_pages (MonoAotCompile *acfg)
1205 #if defined(TARGET_ARM)
1208 guint8 *loop_start, *loop_branch_back, *loop_end_check, *imt_found_check;
1210 int pagesize = MONO_AOT_TRAMP_PAGE_SIZE;
1211 GSList *unwind_ops = NULL;
1212 #define COMMON_TRAMP_SIZE 16
1213 int count = (pagesize - COMMON_TRAMP_SIZE) / 8;
1214 int imm8, rot_amount;
1217 if (!acfg->aot_opts.use_trampolines_page)
1220 acfg->tramp_page_size = pagesize;
1222 sprintf (symbol, "%sspecific_trampolines_page", acfg->user_symbol_prefix);
1223 emit_alignment (acfg, pagesize);
1224 emit_global (acfg, symbol, TRUE);
1225 emit_label (acfg, symbol);
1227 /* emit the generic code first, the trampoline address + 8 is in the lr register */
1229 imm8 = mono_arm_is_rotated_imm8 (pagesize, &rot_amount);
1230 ARM_SUB_REG_IMM (code, ARMREG_LR, ARMREG_LR, imm8, rot_amount);
1231 ARM_LDR_IMM (code, ARMREG_R1, ARMREG_LR, -8);
1232 ARM_LDR_IMM (code, ARMREG_PC, ARMREG_LR, -4);
1234 g_assert (code - buf == COMMON_TRAMP_SIZE);
1237 emit_bytes (acfg, buf, code - buf);
1239 for (i = 0; i < count; ++i) {
1241 ARM_PUSH (code, 0x5fff);
1243 arm_patch (code - 4, code - COMMON_TRAMP_SIZE - 8 * (i + 1));
1244 g_assert (code - buf == 8);
1245 emit_bytes (acfg, buf, code - buf);
1248 /* now the rgctx trampolines: each specific trampolines puts in the ip register
1249 * the instruction pointer address, so the generic trampoline at the start of the page
1250 * subtracts 4096 to get to the data page and loads the values
1251 * We again fit the generic trampiline in 16 bytes.
1253 sprintf (symbol, "%srgctx_trampolines_page", acfg->user_symbol_prefix);
1254 emit_global (acfg, symbol, TRUE);
1255 emit_label (acfg, symbol);
1257 imm8 = mono_arm_is_rotated_imm8 (pagesize, &rot_amount);
1258 ARM_SUB_REG_IMM (code, ARMREG_IP, ARMREG_IP, imm8, rot_amount);
1259 ARM_LDR_IMM (code, MONO_ARCH_RGCTX_REG, ARMREG_IP, -8);
1260 ARM_LDR_IMM (code, ARMREG_PC, ARMREG_IP, -4);
1262 g_assert (code - buf == COMMON_TRAMP_SIZE);
1265 emit_bytes (acfg, buf, code - buf);
1267 for (i = 0; i < count; ++i) {
1269 ARM_MOV_REG_REG (code, ARMREG_IP, ARMREG_PC);
1271 arm_patch (code - 4, code - COMMON_TRAMP_SIZE - 8 * (i + 1));
1272 g_assert (code - buf == 8);
1273 emit_bytes (acfg, buf, code - buf);
1277 * gsharedvt arg trampolines: see arch_emit_gsharedvt_arg_trampoline ()
1279 sprintf (symbol, "%sgsharedvt_arg_trampolines_page", acfg->user_symbol_prefix);
1280 emit_global (acfg, symbol, TRUE);
1281 emit_label (acfg, symbol);
1283 ARM_PUSH (code, (1 << ARMREG_R0) | (1 << ARMREG_R1) | (1 << ARMREG_R2) | (1 << ARMREG_R3));
1284 imm8 = mono_arm_is_rotated_imm8 (pagesize, &rot_amount);
1285 ARM_SUB_REG_IMM (code, ARMREG_IP, ARMREG_IP, imm8, rot_amount);
1286 ARM_LDR_IMM (code, ARMREG_R0, ARMREG_IP, -8);
1287 ARM_LDR_IMM (code, ARMREG_PC, ARMREG_IP, -4);
1288 g_assert (code - buf == COMMON_TRAMP_SIZE);
1290 emit_bytes (acfg, buf, code - buf);
1292 for (i = 0; i < count; ++i) {
1294 ARM_MOV_REG_REG (code, ARMREG_IP, ARMREG_PC);
1296 arm_patch (code - 4, code - COMMON_TRAMP_SIZE - 8 * (i + 1));
1297 g_assert (code - buf == 8);
1298 emit_bytes (acfg, buf, code - buf);
1301 /* now the imt trampolines: each specific trampolines puts in the ip register
1302 * the instruction pointer address, so the generic trampoline at the start of the page
1303 * subtracts 4096 to get to the data page and loads the values
1305 #define IMT_TRAMP_SIZE 72
1306 sprintf (symbol, "%simt_trampolines_page", acfg->user_symbol_prefix);
1307 emit_global (acfg, symbol, TRUE);
1308 emit_label (acfg, symbol);
1310 /* Need at least two free registers, plus a slot for storing the pc */
1311 ARM_PUSH (code, (1 << ARMREG_R0)|(1 << ARMREG_R1)|(1 << ARMREG_R2));
1313 imm8 = mono_arm_is_rotated_imm8 (pagesize, &rot_amount);
1314 ARM_SUB_REG_IMM (code, ARMREG_IP, ARMREG_IP, imm8, rot_amount);
1315 ARM_LDR_IMM (code, ARMREG_R0, ARMREG_IP, -8);
1317 /* The IMT method is in v5, r0 has the imt array address */
1320 ARM_LDR_IMM (code, ARMREG_R1, ARMREG_R0, 0);
1321 ARM_CMP_REG_REG (code, ARMREG_R1, ARMREG_V5);
1322 imt_found_check = code;
1323 ARM_B_COND (code, ARMCOND_EQ, 0);
1325 /* End-of-loop check */
1326 ARM_CMP_REG_IMM (code, ARMREG_R1, 0, 0);
1327 loop_end_check = code;
1328 ARM_B_COND (code, ARMCOND_EQ, 0);
1331 ARM_ADD_REG_IMM8 (code, ARMREG_R0, ARMREG_R0, sizeof (gpointer) * 2);
1332 loop_branch_back = code;
1334 arm_patch (loop_branch_back, loop_start);
1337 arm_patch (imt_found_check, code);
1338 ARM_LDR_IMM (code, ARMREG_R0, ARMREG_R0, 4);
1339 ARM_LDR_IMM (code, ARMREG_R0, ARMREG_R0, 0);
1340 /* Save it to the third stack slot */
1341 ARM_STR_IMM (code, ARMREG_R0, ARMREG_SP, 8);
1342 /* Restore the registers and branch */
1343 ARM_POP (code, (1 << ARMREG_R0)|(1 << ARMREG_R1)|(1 << ARMREG_PC));
1346 arm_patch (loop_end_check, code);
1347 ARM_LDR_IMM (code, ARMREG_R0, ARMREG_R0, 4);
1348 ARM_STR_IMM (code, ARMREG_R0, ARMREG_SP, 8);
1349 ARM_POP (code, (1 << ARMREG_R0)|(1 << ARMREG_R1)|(1 << ARMREG_PC));
1353 g_assert (code - buf == IMT_TRAMP_SIZE);
1354 emit_bytes (acfg, buf, code - buf);
1356 for (i = 0; i < count; ++i) {
1358 ARM_MOV_REG_REG (code, ARMREG_IP, ARMREG_PC);
1360 arm_patch (code - 4, code - IMT_TRAMP_SIZE - 8 * (i + 1));
1361 g_assert (code - buf == 8);
1362 emit_bytes (acfg, buf, code - buf);
1365 acfg->tramp_page_code_offsets [MONO_AOT_TRAMP_SPECIFIC] = 16;
1366 acfg->tramp_page_code_offsets [MONO_AOT_TRAMP_STATIC_RGCTX] = 16;
1367 acfg->tramp_page_code_offsets [MONO_AOT_TRAMP_IMT_THUNK] = 72;
1368 acfg->tramp_page_code_offsets [MONO_AOT_TRAMP_GSHAREDVT_ARG] = 16;
1370 /* Unwind info for specifc trampolines */
1371 sprintf (symbol, "%sspecific_trampolines_page_gen_p", acfg->user_symbol_prefix);
1372 /* We unwind to the original caller, from the stack, since lr is clobbered */
1373 mono_add_unwind_op_def_cfa (unwind_ops, 0, 0, ARMREG_SP, 14 * sizeof (mgreg_t));
1374 mono_add_unwind_op_offset (unwind_ops, 0, 0, ARMREG_LR, -4);
1375 save_unwind_info (acfg, symbol, unwind_ops);
1376 mono_free_unwind_info (unwind_ops);
1378 sprintf (symbol, "%sspecific_trampolines_page_sp_p", acfg->user_symbol_prefix);
1379 mono_add_unwind_op_def_cfa (unwind_ops, 0, 0, ARMREG_SP, 0);
1380 mono_add_unwind_op_def_cfa_offset (unwind_ops, 4, 0, 14 * sizeof (mgreg_t));
1381 save_unwind_info (acfg, symbol, unwind_ops);
1382 mono_free_unwind_info (unwind_ops);
1384 /* Unwind info for rgctx trampolines */
1385 sprintf (symbol, "%srgctx_trampolines_page_gen_p", acfg->user_symbol_prefix);
1386 mono_add_unwind_op_def_cfa (unwind_ops, 0, 0, ARMREG_SP, 0);
1387 save_unwind_info (acfg, symbol, unwind_ops);
1389 sprintf (symbol, "%srgctx_trampolines_page_sp_p", acfg->user_symbol_prefix);
1390 save_unwind_info (acfg, symbol, unwind_ops);
1391 mono_free_unwind_info (unwind_ops);
1393 /* Unwind info for gsharedvt trampolines */
1394 sprintf (symbol, "%sgsharedvt_trampolines_page_gen_p", acfg->user_symbol_prefix);
1395 mono_add_unwind_op_def_cfa (unwind_ops, 0, 0, ARMREG_SP, 0);
1396 mono_add_unwind_op_def_cfa_offset (unwind_ops, 4, 0, 4 * sizeof (mgreg_t));
1397 save_unwind_info (acfg, symbol, unwind_ops);
1398 mono_free_unwind_info (unwind_ops);
1400 sprintf (symbol, "%sgsharedvt_trampolines_page_sp_p", acfg->user_symbol_prefix);
1401 mono_add_unwind_op_def_cfa (unwind_ops, 0, 0, ARMREG_SP, 0);
1402 save_unwind_info (acfg, symbol, unwind_ops);
1403 mono_free_unwind_info (unwind_ops);
1405 /* Unwind info for imt trampolines */
1406 sprintf (symbol, "%simt_trampolines_page_gen_p", acfg->user_symbol_prefix);
1407 mono_add_unwind_op_def_cfa (unwind_ops, 0, 0, ARMREG_SP, 0);
1408 mono_add_unwind_op_def_cfa_offset (unwind_ops, 4, 0, 3 * sizeof (mgreg_t));
1409 save_unwind_info (acfg, symbol, unwind_ops);
1410 mono_free_unwind_info (unwind_ops);
1412 sprintf (symbol, "%simt_trampolines_page_sp_p", acfg->user_symbol_prefix);
1413 mono_add_unwind_op_def_cfa (unwind_ops, 0, 0, ARMREG_SP, 0);
1414 save_unwind_info (acfg, symbol, unwind_ops);
1415 mono_free_unwind_info (unwind_ops);
1416 #elif defined(TARGET_ARM64)
1417 arm64_emit_specific_trampoline_pages (acfg);
1422 * arch_emit_specific_trampoline:
1424 * Emit code for a specific trampoline. OFFSET is the offset of the first of
1425 * two GOT slots which contain the generic trampoline address and the trampoline
1426 * argument. TRAMP_SIZE is set to the size of the emitted trampoline.
1429 arch_emit_specific_trampoline (MonoAotCompile *acfg, int offset, int *tramp_size)
1432 * The trampolines created here are variations of the specific
1433 * trampolines created in mono_arch_create_specific_trampoline (). The
1435 * - the generic trampoline address is taken from a got slot.
1436 * - the offset of the got slot where the trampoline argument is stored
1437 * is embedded in the instruction stream, and the generic trampoline
1438 * can load the argument by loading the offset, adding it to the
1439 * address of the trampoline to get the address of the got slot, and
1440 * loading the argument from there.
1441 * - all the trampolines should be of the same length.
1443 #if defined(TARGET_AMD64)
1444 #if defined(__default_codegen__)
1445 /* This should be exactly 8 bytes long */
1447 /* call *<offset>(%rip) */
1449 emit_unset_mode (acfg);
1450 fprintf (acfg->fp, "call *%s+%d(%%rip)\n", acfg->got_symbol, (int)(offset * sizeof (gpointer)));
1451 emit_zero_bytes (acfg, 2);
1453 emit_byte (acfg, '\x41');
1454 emit_byte (acfg, '\xff');
1455 emit_byte (acfg, '\x15');
1456 emit_symbol_diff (acfg, acfg->got_symbol, ".", (offset * sizeof (gpointer)) - 4);
1457 emit_zero_bytes (acfg, 1);
1459 #elif defined(__native_client_codegen__)
1461 guint8 *buf_aligned = ALIGN_TO(buf, kNaClAlignment);
1462 guint8 *code = buf_aligned;
1467 /* Emit this call in 'code' so we can find out how long it is. */
1468 amd64_call_reg (code, AMD64_R11);
1469 call_start = mono_arch_nacl_skip_nops (buf_aligned);
1470 call_len = code - call_start;
1472 /* The tramp_size is twice the NaCl alignment because it starts with */
1473 /* a call which needs to be aligned to the end of the boundary. */
1474 *tramp_size = kNaClAlignment*2;
1476 /* Emit nops to align call site below which is 7 bytes plus */
1477 /* the length of the call sequence emitted above. */
1478 /* Note: this requires the specific trampoline starts on a */
1479 /* kNaclAlignedment aligned address, which it does because */
1480 /* it's its own function that is aligned. */
1481 guint8 nop_buf[256];
1482 guint8 *nopbuf_aligned = ALIGN_TO (nop_buf, kNaClAlignment);
1483 guint8 *nopbuf_end = mono_arch_nacl_pad (nopbuf_aligned, kNaClAlignment - 7 - (call_len));
1484 emit_bytes (acfg, nopbuf_aligned, nopbuf_end - nopbuf_aligned);
1486 /* The trampoline is stored at the offset'th pointer, the -4 is */
1487 /* present because RIP relative addressing starts at the end of */
1488 /* the current instruction, while the label "." is relative to */
1489 /* the beginning of the current asm location, which in this case */
1490 /* is not the mov instruction, but the offset itself, due to the */
1491 /* way the bytes and ints are emitted here. */
1492 got_offset = (offset * sizeof(gpointer)) - 4;
1494 /* mov <OFFSET>(%rip), %r11d */
1495 emit_byte (acfg, '\x45');
1496 emit_byte (acfg, '\x8b');
1497 emit_byte (acfg, '\x1d');
1498 emit_symbol_diff (acfg, acfg->got_symbol, ".", got_offset);
1501 emit_bytes (acfg, call_start, call_len);
1503 /* The arg is stored at the offset+1 pointer, relative to beginning */
1504 /* of trampoline: 7 for mov, plus the call length, and 1 for push. */
1505 got_offset = ((offset + 1) * sizeof(gpointer)) + 7 + call_len + 1;
1507 /* We can't emit this data directly, hide in a "push imm32" */
1508 emit_byte (acfg, '\x68'); /* push */
1509 emit_symbol_diff (acfg, acfg->got_symbol, ".", got_offset);
1510 emit_alignment (acfg, kNaClAlignment);
1511 #endif /*__native_client_codegen__*/
1512 #elif defined(TARGET_ARM)
1516 /* This should be exactly 20 bytes long */
1519 ARM_PUSH (code, 0x5fff);
1520 ARM_LDR_IMM (code, ARMREG_R1, ARMREG_PC, 4);
1521 /* Load the value from the GOT */
1522 ARM_LDR_REG_REG (code, ARMREG_R1, ARMREG_PC, ARMREG_R1);
1524 ARM_BLX_REG (code, ARMREG_R1);
1526 g_assert (code - buf == 16);
1529 emit_bytes (acfg, buf, code - buf);
1531 * Only one offset is needed, since the second one would be equal to the
1534 emit_symbol_diff (acfg, acfg->got_symbol, ".", (offset * sizeof (gpointer)) - 4 + 4);
1535 //emit_symbol_diff (acfg, acfg->got_symbol, ".", ((offset + 1) * sizeof (gpointer)) - 4 + 8);
1536 #elif defined(TARGET_ARM64)
1537 arm64_emit_specific_trampoline (acfg, offset, tramp_size);
1538 #elif defined(TARGET_POWERPC)
1546 * PPC has no ip relative addressing, so we need to compute the address
1547 * of the mscorlib got. That is slow and complex, so instead, we store it
1548 * in the second got slot of every aot image. The caller already computed
1549 * the address of its got and placed it into r30.
1551 emit_unset_mode (acfg);
1552 /* Load mscorlib got address */
1553 fprintf (acfg->fp, "%s 0, %d(30)\n", PPC_LD_OP, (int)sizeof (gpointer));
1554 /* Load generic trampoline address */
1555 fprintf (acfg->fp, "lis 11, %d@h\n", (int)(offset * sizeof (gpointer)));
1556 fprintf (acfg->fp, "ori 11, 11, %d@l\n", (int)(offset * sizeof (gpointer)));
1557 fprintf (acfg->fp, "%s 11, 11, 0\n", PPC_LDX_OP);
1558 #ifdef PPC_USES_FUNCTION_DESCRIPTOR
1559 fprintf (acfg->fp, "%s 11, 0(11)\n", PPC_LD_OP);
1561 fprintf (acfg->fp, "mtctr 11\n");
1562 /* Load trampoline argument */
1563 /* On ppc, we pass it normally to the generic trampoline */
1564 fprintf (acfg->fp, "lis 11, %d@h\n", (int)((offset + 1) * sizeof (gpointer)));
1565 fprintf (acfg->fp, "ori 11, 11, %d@l\n", (int)((offset + 1) * sizeof (gpointer)));
1566 fprintf (acfg->fp, "%s 0, 11, 0\n", PPC_LDX_OP);
1567 /* Branch to generic trampoline */
1568 fprintf (acfg->fp, "bctr\n");
1570 #ifdef PPC_USES_FUNCTION_DESCRIPTOR
1571 *tramp_size = 10 * 4;
1573 *tramp_size = 9 * 4;
1575 #elif defined(TARGET_X86)
1579 /* Similar to the PPC code above */
1581 /* FIXME: Could this clobber the register needed by get_vcall_slot () ? */
1584 /* Load mscorlib got address */
1585 x86_mov_reg_membase (code, X86_ECX, MONO_ARCH_GOT_REG, sizeof (gpointer), 4);
1586 /* Push trampoline argument */
1587 x86_push_membase (code, X86_ECX, (offset + 1) * sizeof (gpointer));
1588 /* Load generic trampoline address */
1589 x86_mov_reg_membase (code, X86_ECX, X86_ECX, offset * sizeof (gpointer), 4);
1590 /* Branch to generic trampoline */
1591 x86_jump_reg (code, X86_ECX);
1593 #ifdef __native_client_codegen__
1595 /* emit nops to next 32 byte alignment */
1596 int a = (~kNaClAlignmentMask) & ((code - buf) + kNaClAlignment - 1);
1597 while (code < (buf + a)) x86_nop(code);
1600 emit_bytes (acfg, buf, code - buf);
1602 *tramp_size = NACL_SIZE(17, kNaClAlignment);
1603 g_assert (code - buf == *tramp_size);
1605 g_assert_not_reached ();
1610 * arch_emit_unbox_trampoline:
1612 * Emit code for the unbox trampoline for METHOD used in the full-aot case.
1613 * CALL_TARGET is the symbol pointing to the native code of METHOD.
1616 arch_emit_unbox_trampoline (MonoAotCompile *acfg, MonoCompile *cfg, MonoMethod *method, const char *call_target)
1618 #if defined(TARGET_AMD64)
1623 this_reg = mono_arch_get_this_arg_reg (NULL);
1625 amd64_alu_reg_imm (code, X86_ADD, this_reg, sizeof (MonoObject));
1627 emit_bytes (acfg, buf, code - buf);
1630 emit_unset_mode (acfg);
1631 fprintf (acfg->fp, "jmp %s\n", call_target);
1633 emit_byte (acfg, '\xe9');
1634 emit_symbol_diff (acfg, call_target, ".", -4);
1636 #elif defined(TARGET_X86)
1643 x86_alu_membase_imm (code, X86_ADD, X86_ESP, this_pos, sizeof (MonoObject));
1645 emit_bytes (acfg, buf, code - buf);
1648 emit_byte (acfg, '\xe9');
1649 emit_symbol_diff (acfg, call_target, ".", -4);
1650 #elif defined(TARGET_ARM)
1654 if (acfg->thumb_mixed && cfg->compile_llvm) {
1655 fprintf (acfg->fp, "add r0, r0, #%d\n", (int)sizeof (MonoObject));
1656 fprintf (acfg->fp, "b %s\n", call_target);
1657 fprintf (acfg->fp, ".arm\n");
1658 fprintf (acfg->fp, ".align 2\n");
1664 ARM_ADD_REG_IMM8 (code, ARMREG_R0, ARMREG_R0, sizeof (MonoObject));
1666 emit_bytes (acfg, buf, code - buf);
1667 /* jump to method */
1668 if (acfg->thumb_mixed && cfg->compile_llvm)
1669 fprintf (acfg->fp, "\n\tbx %s\n", call_target);
1671 fprintf (acfg->fp, "\n\tb %s\n", call_target);
1672 #elif defined(TARGET_ARM64)
1673 arm64_emit_unbox_trampoline (acfg, cfg, method, call_target);
1674 #elif defined(TARGET_POWERPC)
1677 fprintf (acfg->fp, "\n\taddi %d, %d, %d\n", this_pos, this_pos, (int)sizeof (MonoObject));
1678 fprintf (acfg->fp, "\n\tb %s\n", call_target);
1680 g_assert_not_reached ();
1685 * arch_emit_static_rgctx_trampoline:
1687 * Emit code for a static rgctx trampoline. OFFSET is the offset of the first of
1688 * two GOT slots which contain the rgctx argument, and the method to jump to.
1689 * TRAMP_SIZE is set to the size of the emitted trampoline.
1690 * These kinds of trampolines cannot be enumerated statically, since there could
1691 * be one trampoline per method instantiation, so we emit the same code for all
1692 * trampolines, and parameterize them using two GOT slots.
1695 arch_emit_static_rgctx_trampoline (MonoAotCompile *acfg, int offset, int *tramp_size)
1697 #if defined(TARGET_AMD64)
1698 #if defined(__default_codegen__)
1699 /* This should be exactly 13 bytes long */
1703 emit_unset_mode (acfg);
1704 fprintf (acfg->fp, "mov %s+%d(%%rip), %%r10\n", acfg->got_symbol, (int)(offset * sizeof (gpointer)));
1705 fprintf (acfg->fp, "jmp *%s+%d(%%rip)\n", acfg->got_symbol, (int)((offset + 1) * sizeof (gpointer)));
1707 /* mov <OFFSET>(%rip), %r10 */
1708 emit_byte (acfg, '\x4d');
1709 emit_byte (acfg, '\x8b');
1710 emit_byte (acfg, '\x15');
1711 emit_symbol_diff (acfg, acfg->got_symbol, ".", (offset * sizeof (gpointer)) - 4);
1713 /* jmp *<offset>(%rip) */
1714 emit_byte (acfg, '\xff');
1715 emit_byte (acfg, '\x25');
1716 emit_symbol_diff (acfg, acfg->got_symbol, ".", ((offset + 1) * sizeof (gpointer)) - 4);
1718 #elif defined(__native_client_codegen__)
1720 guint8 *buf_aligned = ALIGN_TO(buf, kNaClAlignment);
1721 guint8 *code = buf_aligned;
1723 /* mov <OFFSET>(%rip), %r10d */
1724 emit_byte (acfg, '\x45');
1725 emit_byte (acfg, '\x8b');
1726 emit_byte (acfg, '\x15');
1727 emit_symbol_diff (acfg, acfg->got_symbol, ".", (offset * sizeof (gpointer)) - 4);
1729 /* mov <OFFSET>(%rip), %r11d */
1730 emit_byte (acfg, '\x45');
1731 emit_byte (acfg, '\x8b');
1732 emit_byte (acfg, '\x1d');
1733 emit_symbol_diff (acfg, acfg->got_symbol, ".", ((offset + 1) * sizeof (gpointer)) - 4);
1736 amd64_jump_reg (code, AMD64_R11);
1737 emit_bytes (acfg, buf_aligned, code - buf_aligned);
1739 emit_alignment (acfg, kNaClAlignment);
1740 *tramp_size = kNaClAlignment;
1741 #endif /*__native_client_codegen__*/
1743 #elif defined(TARGET_ARM)
1747 /* This should be exactly 24 bytes long */
1750 /* Load rgctx value */
1751 ARM_LDR_IMM (code, ARMREG_IP, ARMREG_PC, 8);
1752 ARM_LDR_REG_REG (code, MONO_ARCH_RGCTX_REG, ARMREG_PC, ARMREG_IP);
1753 /* Load branch addr + branch */
1754 ARM_LDR_IMM (code, ARMREG_IP, ARMREG_PC, 4);
1755 ARM_LDR_REG_REG (code, ARMREG_PC, ARMREG_PC, ARMREG_IP);
1757 g_assert (code - buf == 16);
1760 emit_bytes (acfg, buf, code - buf);
1761 emit_symbol_diff (acfg, acfg->got_symbol, ".", (offset * sizeof (gpointer)) - 4 + 8);
1762 emit_symbol_diff (acfg, acfg->got_symbol, ".", ((offset + 1) * sizeof (gpointer)) - 4 + 4);
1763 #elif defined(TARGET_ARM64)
1764 arm64_emit_static_rgctx_trampoline (acfg, offset, tramp_size);
1765 #elif defined(TARGET_POWERPC)
1773 * PPC has no ip relative addressing, so we need to compute the address
1774 * of the mscorlib got. That is slow and complex, so instead, we store it
1775 * in the second got slot of every aot image. The caller already computed
1776 * the address of its got and placed it into r30.
1778 emit_unset_mode (acfg);
1779 /* Load mscorlib got address */
1780 fprintf (acfg->fp, "%s 0, %d(30)\n", PPC_LD_OP, (int)sizeof (gpointer));
1782 fprintf (acfg->fp, "lis 11, %d@h\n", (int)(offset * sizeof (gpointer)));
1783 fprintf (acfg->fp, "ori 11, 11, %d@l\n", (int)(offset * sizeof (gpointer)));
1784 fprintf (acfg->fp, "%s %d, 11, 0\n", PPC_LDX_OP, MONO_ARCH_RGCTX_REG);
1785 /* Load target address */
1786 fprintf (acfg->fp, "lis 11, %d@h\n", (int)((offset + 1) * sizeof (gpointer)));
1787 fprintf (acfg->fp, "ori 11, 11, %d@l\n", (int)((offset + 1) * sizeof (gpointer)));
1788 fprintf (acfg->fp, "%s 11, 11, 0\n", PPC_LDX_OP);
1789 #ifdef PPC_USES_FUNCTION_DESCRIPTOR
1790 fprintf (acfg->fp, "%s 2, %d(11)\n", PPC_LD_OP, (int)sizeof (gpointer));
1791 fprintf (acfg->fp, "%s 11, 0(11)\n", PPC_LD_OP);
1793 fprintf (acfg->fp, "mtctr 11\n");
1794 /* Branch to the target address */
1795 fprintf (acfg->fp, "bctr\n");
1797 #ifdef PPC_USES_FUNCTION_DESCRIPTOR
1798 *tramp_size = 11 * 4;
1800 *tramp_size = 9 * 4;
1803 #elif defined(TARGET_X86)
1807 /* Similar to the PPC code above */
1809 g_assert (MONO_ARCH_RGCTX_REG != X86_ECX);
1812 /* Load mscorlib got address */
1813 x86_mov_reg_membase (code, X86_ECX, MONO_ARCH_GOT_REG, sizeof (gpointer), 4);
1815 x86_mov_reg_membase (code, MONO_ARCH_RGCTX_REG, X86_ECX, offset * sizeof (gpointer), 4);
1816 /* Branch to the target address */
1817 x86_jump_membase (code, X86_ECX, (offset + 1) * sizeof (gpointer));
1819 #ifdef __native_client_codegen__
1821 /* emit nops to next 32 byte alignment */
1822 int a = (~kNaClAlignmentMask) & ((code - buf) + kNaClAlignment - 1);
1823 while (code < (buf + a)) x86_nop(code);
1827 emit_bytes (acfg, buf, code - buf);
1829 *tramp_size = NACL_SIZE (15, kNaClAlignment);
1830 g_assert (code - buf == *tramp_size);
1832 g_assert_not_reached ();
1837 * arch_emit_imt_thunk:
1839 * Emit an IMT thunk usable in full-aot mode. The thunk uses 1 got slot which
1840 * points to an array of pointer pairs. The pairs of the form [key, ptr], where
1841 * key is the IMT key, and ptr holds the address of a memory location holding
1842 * the address to branch to if the IMT arg matches the key. The array is
1843 * terminated by a pair whose key is NULL, and whose ptr is the address of the
1845 * TRAMP_SIZE is set to the size of the emitted trampoline.
1848 arch_emit_imt_thunk (MonoAotCompile *acfg, int offset, int *tramp_size)
1850 #if defined(TARGET_AMD64)
1852 #if defined(__native_client_codegen__)
1855 guint8 *labels [16];
1857 guint8 *mov_buf_ptr = mov_buf;
1859 const int kSizeOfMove = 7;
1860 #if defined(__default_codegen__)
1861 code = buf = (guint8 *)g_malloc (256);
1862 #elif defined(__native_client_codegen__)
1863 buf_alloc = g_malloc (256 + kNaClAlignment + kSizeOfMove);
1864 buf = ((guint)buf_alloc + kNaClAlignment) & ~kNaClAlignmentMask;
1865 /* The RIP relative move below is emitted first */
1870 /* FIXME: Optimize this, i.e. use binary search etc. */
1871 /* Maybe move the body into a separate function (slower, but much smaller) */
1873 /* MONO_ARCH_IMT_SCRATCH_REG is a free register */
1876 emit_unset_mode (acfg);
1877 fprintf (acfg->fp, "mov %s+%d(%%rip), %s\n", acfg->got_symbol, (int)(offset * sizeof (gpointer)), mono_arch_regname (MONO_ARCH_IMT_SCRATCH_REG));
1881 amd64_alu_membase_imm (code, X86_CMP, MONO_ARCH_IMT_SCRATCH_REG, 0, 0);
1883 amd64_branch8 (code, X86_CC_Z, 0, FALSE);
1886 amd64_alu_membase_reg_size (code, X86_CMP, MONO_ARCH_IMT_SCRATCH_REG, 0, MONO_ARCH_IMT_REG, sizeof (gpointer));
1888 amd64_branch8 (code, X86_CC_Z, 0, FALSE);
1891 amd64_alu_reg_imm (code, X86_ADD, MONO_ARCH_IMT_SCRATCH_REG, 2 * sizeof (gpointer));
1892 amd64_jump_code (code, labels [0]);
1895 mono_amd64_patch (labels [2], code);
1896 amd64_mov_reg_membase (code, MONO_ARCH_IMT_SCRATCH_REG, MONO_ARCH_IMT_SCRATCH_REG, sizeof (gpointer), sizeof (gpointer));
1897 amd64_jump_membase (code, MONO_ARCH_IMT_SCRATCH_REG, 0);
1900 mono_amd64_patch (labels [1], code);
1901 /* Load fail tramp */
1902 amd64_alu_reg_imm (code, X86_ADD, MONO_ARCH_IMT_SCRATCH_REG, sizeof (gpointer));
1903 /* Check if there is a fail tramp */
1904 amd64_alu_membase_imm (code, X86_CMP, MONO_ARCH_IMT_SCRATCH_REG, 0, 0);
1906 amd64_branch8 (code, X86_CC_Z, 0, FALSE);
1907 /* Jump to fail tramp */
1908 amd64_jump_membase (code, MONO_ARCH_IMT_SCRATCH_REG, 0);
1911 mono_amd64_patch (labels [3], code);
1912 x86_breakpoint (code);
1915 /* mov <OFFSET>(%rip), MONO_ARCH_IMT_SCRATCH_REG */
1916 amd64_emit_rex (mov_buf_ptr, sizeof(gpointer), MONO_ARCH_IMT_SCRATCH_REG, 0, AMD64_RIP);
1917 *(mov_buf_ptr)++ = (unsigned char)0x8b; /* mov opcode */
1918 x86_address_byte (mov_buf_ptr, 0, MONO_ARCH_IMT_SCRATCH_REG & 0x7, 5);
1919 emit_bytes (acfg, mov_buf, mov_buf_ptr - mov_buf);
1920 emit_symbol_diff (acfg, acfg->got_symbol, ".", (offset * sizeof (gpointer)) - 4);
1922 emit_bytes (acfg, buf, code - buf);
1924 *tramp_size = code - buf + kSizeOfMove;
1925 #if defined(__native_client_codegen__)
1926 /* The tramp will be padded to the next kNaClAlignment bundle. */
1927 *tramp_size = ALIGN_TO ((*tramp_size), kNaClAlignment);
1930 #if defined(__default_codegen__)
1932 #elif defined(__native_client_codegen__)
1936 #elif defined(TARGET_X86)
1938 #ifdef __native_client_codegen__
1941 guint8 *labels [16];
1943 #if defined(__default_codegen__)
1944 code = buf = g_malloc (256);
1945 #elif defined(__native_client_codegen__)
1946 buf_alloc = g_malloc (256 + kNaClAlignment);
1947 code = buf = ((guint)buf_alloc + kNaClAlignment) & ~kNaClAlignmentMask;
1950 /* Allocate a temporary stack slot */
1951 x86_push_reg (code, X86_EAX);
1953 x86_push_reg (code, X86_EAX);
1955 /* Load mscorlib got address */
1956 x86_mov_reg_membase (code, X86_EAX, MONO_ARCH_GOT_REG, sizeof (gpointer), 4);
1958 x86_mov_reg_membase (code, X86_EAX, X86_EAX, offset * sizeof (gpointer), 4);
1961 x86_alu_membase_imm (code, X86_CMP, X86_EAX, 0, 0);
1963 x86_branch8 (code, X86_CC_Z, FALSE, 0);
1966 x86_alu_membase_reg (code, X86_CMP, X86_EAX, 0, MONO_ARCH_IMT_REG);
1968 x86_branch8 (code, X86_CC_Z, FALSE, 0);
1971 x86_alu_reg_imm (code, X86_ADD, X86_EAX, 2 * sizeof (gpointer));
1972 x86_jump_code (code, labels [0]);
1975 mono_x86_patch (labels [2], code);
1976 x86_mov_reg_membase (code, X86_EAX, X86_EAX, sizeof (gpointer), 4);
1977 x86_mov_reg_membase (code, X86_EAX, X86_EAX, 0, 4);
1978 /* Save the target address to the temporary stack location */
1979 x86_mov_membase_reg (code, X86_ESP, 4, X86_EAX, 4);
1981 x86_pop_reg (code, X86_EAX);
1982 /* Jump to the target address */
1986 mono_x86_patch (labels [1], code);
1987 /* Load fail tramp */
1988 x86_mov_reg_membase (code, X86_EAX, X86_EAX, sizeof (gpointer), 4);
1989 x86_alu_membase_imm (code, X86_CMP, X86_EAX, 0, 0);
1991 x86_branch8 (code, X86_CC_Z, FALSE, 0);
1992 /* Jump to fail tramp */
1993 x86_mov_membase_reg (code, X86_ESP, 4, X86_EAX, 4);
1994 x86_pop_reg (code, X86_EAX);
1998 mono_x86_patch (labels [3], code);
1999 x86_breakpoint (code);
2001 #ifdef __native_client_codegen__
2003 /* emit nops to next 32 byte alignment */
2004 int a = (~kNaClAlignmentMask) & ((code - buf) + kNaClAlignment - 1);
2005 while (code < (buf + a)) x86_nop(code);
2008 emit_bytes (acfg, buf, code - buf);
2010 *tramp_size = code - buf;
2012 #if defined(__default_codegen__)
2014 #elif defined(__native_client_codegen__)
2018 #elif defined(TARGET_ARM)
2020 guint8 *code, *code2, *labels [16];
2024 /* The IMT method is in v5 */
2026 /* Need at least two free registers, plus a slot for storing the pc */
2027 ARM_PUSH (code, (1 << ARMREG_R0)|(1 << ARMREG_R1)|(1 << ARMREG_R2));
2029 /* Load the parameter from the GOT */
2030 ARM_LDR_IMM (code, ARMREG_R0, ARMREG_PC, 0);
2031 ARM_LDR_REG_REG (code, ARMREG_R0, ARMREG_PC, ARMREG_R0);
2034 ARM_LDR_IMM (code, ARMREG_R1, ARMREG_R0, 0);
2035 ARM_CMP_REG_REG (code, ARMREG_R1, ARMREG_V5);
2037 ARM_B_COND (code, ARMCOND_EQ, 0);
2039 /* End-of-loop check */
2040 ARM_CMP_REG_IMM (code, ARMREG_R1, 0, 0);
2042 ARM_B_COND (code, ARMCOND_EQ, 0);
2045 ARM_ADD_REG_IMM8 (code, ARMREG_R0, ARMREG_R0, sizeof (gpointer) * 2);
2048 arm_patch (labels [4], labels [1]);
2051 arm_patch (labels [2], code);
2052 ARM_LDR_IMM (code, ARMREG_R0, ARMREG_R0, 4);
2053 ARM_LDR_IMM (code, ARMREG_R0, ARMREG_R0, 0);
2054 /* Save it to the third stack slot */
2055 ARM_STR_IMM (code, ARMREG_R0, ARMREG_SP, 8);
2056 /* Restore the registers and branch */
2057 ARM_POP (code, (1 << ARMREG_R0)|(1 << ARMREG_R1)|(1 << ARMREG_PC));
2060 arm_patch (labels [3], code);
2061 ARM_LDR_IMM (code, ARMREG_R0, ARMREG_R0, 4);
2062 ARM_STR_IMM (code, ARMREG_R0, ARMREG_SP, 8);
2063 ARM_POP (code, (1 << ARMREG_R0)|(1 << ARMREG_R1)|(1 << ARMREG_PC));
2067 ARM_LDR_IMM (code2, ARMREG_R0, ARMREG_PC, (code - (labels [0] + 8)));
2069 emit_bytes (acfg, buf, code - buf);
2070 emit_symbol_diff (acfg, acfg->got_symbol, ".", (offset * sizeof (gpointer)) + (code - (labels [0] + 8)) - 4);
2072 *tramp_size = code - buf + 4;
2073 #elif defined(TARGET_ARM64)
2074 arm64_emit_imt_thunk (acfg, offset, tramp_size);
2075 #elif defined(TARGET_POWERPC)
2077 guint8 *code, *labels [16];
2081 /* Load the mscorlib got address */
2082 ppc_ldptr (code, ppc_r12, sizeof (gpointer), ppc_r30);
2083 /* Load the parameter from the GOT */
2084 ppc_load (code, ppc_r0, offset * sizeof (gpointer));
2085 ppc_ldptr_indexed (code, ppc_r12, ppc_r12, ppc_r0);
2087 /* Load and check key */
2089 ppc_ldptr (code, ppc_r0, 0, ppc_r12);
2090 ppc_cmp (code, 0, sizeof (gpointer) == 8 ? 1 : 0, ppc_r0, MONO_ARCH_IMT_REG);
2092 ppc_bc (code, PPC_BR_TRUE, PPC_BR_EQ, 0);
2094 /* End-of-loop check */
2095 ppc_cmpi (code, 0, sizeof (gpointer) == 8 ? 1 : 0, ppc_r0, 0);
2097 ppc_bc (code, PPC_BR_TRUE, PPC_BR_EQ, 0);
2100 ppc_addi (code, ppc_r12, ppc_r12, 2 * sizeof (gpointer));
2103 mono_ppc_patch (labels [4], labels [1]);
2106 mono_ppc_patch (labels [2], code);
2107 ppc_ldptr (code, ppc_r12, sizeof (gpointer), ppc_r12);
2108 /* r12 now contains the value of the vtable slot */
2109 /* this is not a function descriptor on ppc64 */
2110 ppc_ldptr (code, ppc_r12, 0, ppc_r12);
2111 ppc_mtctr (code, ppc_r12);
2112 ppc_bcctr (code, PPC_BR_ALWAYS, 0);
2115 mono_ppc_patch (labels [3], code);
2119 *tramp_size = code - buf;
2121 emit_bytes (acfg, buf, code - buf);
2123 g_assert_not_reached ();
2128 * arch_emit_gsharedvt_arg_trampoline:
2130 * Emit code for a gsharedvt arg trampoline. OFFSET is the offset of the first of
2131 * two GOT slots which contain the argument, and the code to jump to.
2132 * TRAMP_SIZE is set to the size of the emitted trampoline.
2133 * These kinds of trampolines cannot be enumerated statically, since there could
2134 * be one trampoline per method instantiation, so we emit the same code for all
2135 * trampolines, and parameterize them using two GOT slots.
2138 arch_emit_gsharedvt_arg_trampoline (MonoAotCompile *acfg, int offset, int *tramp_size)
2140 #if defined(TARGET_X86)
2144 /* Similar to the PPC code above */
2146 g_assert (MONO_ARCH_RGCTX_REG != X86_ECX);
2149 /* Load mscorlib got address */
2150 x86_mov_reg_membase (code, X86_ECX, MONO_ARCH_GOT_REG, sizeof (gpointer), 4);
2152 x86_mov_reg_membase (code, X86_EAX, X86_ECX, offset * sizeof (gpointer), 4);
2153 /* Branch to the target address */
2154 x86_jump_membase (code, X86_ECX, (offset + 1) * sizeof (gpointer));
2156 #ifdef __native_client_codegen__
2158 /* emit nops to next 32 byte alignment */
2159 int a = (~kNaClAlignmentMask) & ((code - buf) + kNaClAlignment - 1);
2160 while (code < (buf + a)) x86_nop(code);
2164 emit_bytes (acfg, buf, code - buf);
2166 *tramp_size = NACL_SIZE (15, kNaClAlignment);
2167 g_assert (code - buf == *tramp_size);
2168 #elif defined(TARGET_ARM)
2172 /* The same as mono_arch_get_gsharedvt_arg_trampoline (), but for AOT */
2173 /* Similar to arch_emit_specific_trampoline () */
2176 ARM_PUSH (code, (1 << ARMREG_R0) | (1 << ARMREG_R1) | (1 << ARMREG_R2) | (1 << ARMREG_R3));
2177 ARM_LDR_IMM (code, ARMREG_R1, ARMREG_PC, 8);
2178 /* Load the arg value from the GOT */
2179 ARM_LDR_REG_REG (code, ARMREG_R0, ARMREG_PC, ARMREG_R1);
2180 /* Load the addr from the GOT */
2181 ARM_LDR_REG_REG (code, ARMREG_R1, ARMREG_PC, ARMREG_R1);
2183 ARM_BX (code, ARMREG_R1);
2185 g_assert (code - buf == 20);
2188 emit_bytes (acfg, buf, code - buf);
2189 emit_symbol_diff (acfg, acfg->got_symbol, ".", (offset * sizeof (gpointer)) + 4);
2190 #elif defined(TARGET_ARM64)
2191 arm64_emit_gsharedvt_arg_trampoline (acfg, offset, tramp_size);
2193 g_assert_not_reached ();
2197 /* END OF ARCH SPECIFIC CODE */
2200 mono_get_field_token (MonoClassField *field)
2202 MonoClass *klass = field->parent;
2205 for (i = 0; i < klass->field.count; ++i) {
2206 if (field == &klass->fields [i])
2207 return MONO_TOKEN_FIELD_DEF | (klass->field.first + 1 + i);
2210 g_assert_not_reached ();
2215 encode_value (gint32 value, guint8 *buf, guint8 **endbuf)
2219 //printf ("ENCODE: %d 0x%x.\n", value, value);
2222 * Same encoding as the one used in the metadata, extended to handle values
2223 * greater than 0x1fffffff.
2225 if ((value >= 0) && (value <= 127))
2227 else if ((value >= 0) && (value <= 16383)) {
2228 p [0] = 0x80 | (value >> 8);
2229 p [1] = value & 0xff;
2231 } else if ((value >= 0) && (value <= 0x1fffffff)) {
2232 p [0] = (value >> 24) | 0xc0;
2233 p [1] = (value >> 16) & 0xff;
2234 p [2] = (value >> 8) & 0xff;
2235 p [3] = value & 0xff;
2240 p [1] = (value >> 24) & 0xff;
2241 p [2] = (value >> 16) & 0xff;
2242 p [3] = (value >> 8) & 0xff;
2243 p [4] = value & 0xff;
2251 stream_init (MonoDynamicStream *sh)
2254 sh->alloc_size = 4096;
2255 sh->data = (char *)g_malloc (4096);
2257 /* So offsets are > 0 */
2263 make_room_in_stream (MonoDynamicStream *stream, int size)
2265 if (size <= stream->alloc_size)
2268 while (stream->alloc_size <= size) {
2269 if (stream->alloc_size < 4096)
2270 stream->alloc_size = 4096;
2272 stream->alloc_size *= 2;
2275 stream->data = (char *)g_realloc (stream->data, stream->alloc_size);
2279 add_stream_data (MonoDynamicStream *stream, const char *data, guint32 len)
2283 make_room_in_stream (stream, stream->index + len);
2284 memcpy (stream->data + stream->index, data, len);
2285 idx = stream->index;
2286 stream->index += len;
2293 * Add data to the binary blob inside the aot image. Returns the offset inside the
2294 * blob where the data was stored.
2297 add_to_blob (MonoAotCompile *acfg, const guint8 *data, guint32 data_len)
2299 if (acfg->blob.alloc_size == 0)
2300 stream_init (&acfg->blob);
2302 return add_stream_data (&acfg->blob, (char*)data, data_len);
2306 add_to_blob_aligned (MonoAotCompile *acfg, const guint8 *data, guint32 data_len, guint32 align)
2311 if (acfg->blob.alloc_size == 0)
2312 stream_init (&acfg->blob);
2314 count = acfg->blob.index % align;
2316 /* we assume the stream data will be aligned */
2318 add_stream_data (&acfg->blob, buf, 4 - count);
2320 return add_stream_data (&acfg->blob, (char*)data, data_len);
2324 * emit_offset_table:
2326 * Emit a table of increasing offsets in a compact form using differential encoding.
2327 * There is an index entry for each GROUP_SIZE number of entries. The greater the
2328 * group size, the more compact the table becomes, but the slower it becomes to compute
2329 * a given entry. Returns the size of the table.
2332 emit_offset_table (MonoAotCompile *acfg, const char *symbol, int noffsets, int group_size, gint32 *offsets)
2334 gint32 current_offset;
2335 int i, buf_size, ngroups, index_entry_size;
2337 guint8 *data_p, *data_buf;
2338 guint32 *index_offsets;
2340 ngroups = (noffsets + (group_size - 1)) / group_size;
2342 index_offsets = g_new0 (guint32, ngroups);
2344 buf_size = noffsets * 4;
2345 p = buf = (guint8 *)g_malloc0 (buf_size);
2348 for (i = 0; i < noffsets; ++i) {
2349 //printf ("D: %d -> %d\n", i, offsets [i]);
2350 if ((i % group_size) == 0) {
2351 index_offsets [i / group_size] = p - buf;
2352 /* Emit the full value for these entries */
2353 encode_value (offsets [i], p, &p);
2355 /* The offsets are allowed to be non-increasing */
2356 //g_assert (offsets [i] >= current_offset);
2357 encode_value (offsets [i] - current_offset, p, &p);
2359 current_offset = offsets [i];
2364 if (ngroups && index_offsets [ngroups - 1] < 65000)
2365 index_entry_size = 2;
2367 index_entry_size = 4;
2369 buf_size = (data_p - data_buf) + (ngroups * 4) + 16;
2370 p = buf = (guint8 *)g_malloc0 (buf_size);
2372 /* Emit the header */
2373 encode_int (noffsets, p, &p);
2374 encode_int (group_size, p, &p);
2375 encode_int (ngroups, p, &p);
2376 encode_int (index_entry_size, p, &p);
2378 /* Emit the index */
2379 for (i = 0; i < ngroups; ++i) {
2380 if (index_entry_size == 2)
2381 encode_int16 (index_offsets [i], p, &p);
2383 encode_int (index_offsets [i], p, &p);
2386 memcpy (p, data_buf, data_p - data_buf);
2387 p += data_p - data_buf;
2389 g_assert (p - buf <= buf_size);
2392 mono_llvm_emit_aot_data (symbol, buf, p - buf);
2394 emit_section_change (acfg, RODATA_SECT, 1);
2395 emit_alignment (acfg, 8);
2396 emit_label (acfg, symbol);
2397 emit_bytes (acfg, buf, p - buf);
2403 return (int)(p - buf);
2407 get_image_index (MonoAotCompile *cfg, MonoImage *image)
2411 index = GPOINTER_TO_UINT (g_hash_table_lookup (cfg->image_hash, image));
2415 index = g_hash_table_size (cfg->image_hash);
2416 g_hash_table_insert (cfg->image_hash, image, GUINT_TO_POINTER (index + 1));
2417 g_ptr_array_add (cfg->image_table, image);
2423 find_typespec_for_class (MonoAotCompile *acfg, MonoClass *klass)
2426 int len = acfg->image->tables [MONO_TABLE_TYPESPEC].rows;
2428 /* FIXME: Search referenced images as well */
2429 if (!acfg->typespec_classes) {
2430 acfg->typespec_classes = (MonoClass **)mono_mempool_alloc0 (acfg->mempool, sizeof (MonoClass*) * len);
2431 for (i = 0; i < len; ++i) {
2433 acfg->typespec_classes [i] = mono_class_get_and_inflate_typespec_checked (acfg->image, MONO_TOKEN_TYPE_SPEC | (i + 1), NULL, &error);
2434 g_assert (mono_error_ok (&error)); /* FIXME error handling */
2437 for (i = 0; i < len; ++i) {
2438 if (acfg->typespec_classes [i] == klass)
2443 return MONO_TOKEN_TYPE_SPEC | (i + 1);
2449 encode_method_ref (MonoAotCompile *acfg, MonoMethod *method, guint8 *buf, guint8 **endbuf);
2452 encode_klass_ref (MonoAotCompile *acfg, MonoClass *klass, guint8 *buf, guint8 **endbuf);
2455 encode_ginst (MonoAotCompile *acfg, MonoGenericInst *inst, guint8 *buf, guint8 **endbuf);
2458 encode_type (MonoAotCompile *acfg, MonoType *t, guint8 *buf, guint8 **endbuf);
2461 encode_klass_ref_inner (MonoAotCompile *acfg, MonoClass *klass, guint8 *buf, guint8 **endbuf)
2466 * The encoding begins with one of the MONO_AOT_TYPEREF values, followed by additional
2470 if (klass->generic_class) {
2472 g_assert (klass->type_token);
2474 /* Find a typespec for a class if possible */
2475 token = find_typespec_for_class (acfg, klass);
2477 encode_value (MONO_AOT_TYPEREF_TYPESPEC_TOKEN, p, &p);
2478 encode_value (token, p, &p);
2480 MonoClass *gclass = klass->generic_class->container_class;
2481 MonoGenericInst *inst = klass->generic_class->context.class_inst;
2482 static int count = 0;
2485 encode_value (MONO_AOT_TYPEREF_GINST, p, &p);
2486 encode_klass_ref (acfg, gclass, p, &p);
2487 encode_ginst (acfg, inst, p, &p);
2491 } else if (klass->type_token) {
2492 int iindex = get_image_index (acfg, klass->image);
2494 g_assert (mono_metadata_token_code (klass->type_token) == MONO_TOKEN_TYPE_DEF);
2496 encode_value (MONO_AOT_TYPEREF_TYPEDEF_INDEX, p, &p);
2497 encode_value (klass->type_token - MONO_TOKEN_TYPE_DEF, p, &p);
2499 encode_value (MONO_AOT_TYPEREF_TYPEDEF_INDEX_IMAGE, p, &p);
2500 encode_value (klass->type_token - MONO_TOKEN_TYPE_DEF, p, &p);
2501 encode_value (get_image_index (acfg, klass->image), p, &p);
2503 } else if ((klass->byval_arg.type == MONO_TYPE_VAR) || (klass->byval_arg.type == MONO_TYPE_MVAR)) {
2504 MonoGenericContainer *container = mono_type_get_generic_param_owner (&klass->byval_arg);
2505 MonoGenericParam *par = klass->byval_arg.data.generic_param;
2507 encode_value (MONO_AOT_TYPEREF_VAR, p, &p);
2509 encode_value (par->gshared_constraint ? 1 : 0, p, &p);
2510 if (par->gshared_constraint) {
2511 MonoGSharedGenericParam *gpar = (MonoGSharedGenericParam*)par;
2512 encode_type (acfg, par->gshared_constraint, p, &p);
2513 encode_klass_ref (acfg, mono_class_from_generic_parameter (gpar->parent, NULL, klass->byval_arg.type == MONO_TYPE_MVAR), p, &p);
2515 encode_value (klass->byval_arg.type, p, &p);
2516 encode_value (mono_type_get_generic_param_num (&klass->byval_arg), p, &p);
2518 encode_value (container->is_anonymous ? 0 : 1, p, &p);
2520 if (!container->is_anonymous) {
2521 encode_value (container->is_method, p, &p);
2522 if (container->is_method)
2523 encode_method_ref (acfg, container->owner.method, p, &p);
2525 encode_klass_ref (acfg, container->owner.klass, p, &p);
2528 } else if (klass->byval_arg.type == MONO_TYPE_PTR) {
2529 encode_value (MONO_AOT_TYPEREF_PTR, p, &p);
2530 encode_type (acfg, &klass->byval_arg, p, &p);
2533 g_assert (klass->rank > 0);
2534 encode_value (MONO_AOT_TYPEREF_ARRAY, p, &p);
2535 encode_value (klass->rank, p, &p);
2536 encode_klass_ref (acfg, klass->element_class, p, &p);
2544 * Encode a reference to KLASS. We use our home-grown encoding instead of the
2545 * standard metadata encoding.
2548 encode_klass_ref (MonoAotCompile *acfg, MonoClass *klass, guint8 *buf, guint8 **endbuf)
2550 gboolean shared = FALSE;
2553 * The encoding of generic instances is large so emit them only once.
2555 if (klass->generic_class) {
2557 g_assert (klass->type_token);
2559 /* Find a typespec for a class if possible */
2560 token = find_typespec_for_class (acfg, klass);
2563 } else if ((klass->byval_arg.type == MONO_TYPE_VAR) || (klass->byval_arg.type == MONO_TYPE_MVAR)) {
2568 guint offset = GPOINTER_TO_UINT (g_hash_table_lookup (acfg->klass_blob_hash, klass));
2572 buf2 = (guint8 *)g_malloc (1024);
2575 encode_klass_ref_inner (acfg, klass, p, &p);
2576 g_assert (p - buf2 < 1024);
2578 offset = add_to_blob (acfg, buf2, p - buf2);
2581 g_hash_table_insert (acfg->klass_blob_hash, klass, GUINT_TO_POINTER (offset + 1));
2587 encode_value (MONO_AOT_TYPEREF_BLOB_INDEX, p, &p);
2588 encode_value (offset, p, &p);
2593 encode_klass_ref_inner (acfg, klass, buf, endbuf);
2597 encode_field_info (MonoAotCompile *cfg, MonoClassField *field, guint8 *buf, guint8 **endbuf)
2599 guint32 token = mono_get_field_token (field);
2602 encode_klass_ref (cfg, field->parent, p, &p);
2603 g_assert (mono_metadata_token_code (token) == MONO_TOKEN_FIELD_DEF);
2604 encode_value (token - MONO_TOKEN_FIELD_DEF, p, &p);
2609 encode_ginst (MonoAotCompile *acfg, MonoGenericInst *inst, guint8 *buf, guint8 **endbuf)
2614 encode_value (inst->type_argc, p, &p);
2615 for (i = 0; i < inst->type_argc; ++i)
2616 encode_klass_ref (acfg, mono_class_from_mono_type (inst->type_argv [i]), p, &p);
2621 encode_generic_context (MonoAotCompile *acfg, MonoGenericContext *context, guint8 *buf, guint8 **endbuf)
2624 MonoGenericInst *inst;
2626 inst = context->class_inst;
2628 g_assert (inst->type_argc);
2629 encode_ginst (acfg, inst, p, &p);
2631 encode_value (0, p, &p);
2633 inst = context->method_inst;
2635 g_assert (inst->type_argc);
2636 encode_ginst (acfg, inst, p, &p);
2638 encode_value (0, p, &p);
2644 encode_type (MonoAotCompile *acfg, MonoType *t, guint8 *buf, guint8 **endbuf)
2648 g_assert (t->num_mods == 0);
2649 /* t->attrs can be ignored */
2650 //g_assert (t->attrs == 0);
2653 *p = MONO_TYPE_PINNED;
2657 *p = MONO_TYPE_BYREF;
2665 case MONO_TYPE_VOID:
2666 case MONO_TYPE_BOOLEAN:
2667 case MONO_TYPE_CHAR:
2680 case MONO_TYPE_STRING:
2681 case MONO_TYPE_OBJECT:
2682 case MONO_TYPE_TYPEDBYREF:
2684 case MONO_TYPE_VALUETYPE:
2685 case MONO_TYPE_CLASS:
2686 encode_klass_ref (acfg, mono_class_from_mono_type (t), p, &p);
2688 case MONO_TYPE_SZARRAY:
2689 encode_klass_ref (acfg, t->data.klass, p, &p);
2692 encode_type (acfg, t->data.type, p, &p);
2694 case MONO_TYPE_GENERICINST: {
2695 MonoClass *gclass = t->data.generic_class->container_class;
2696 MonoGenericInst *inst = t->data.generic_class->context.class_inst;
2698 encode_klass_ref (acfg, gclass, p, &p);
2699 encode_ginst (acfg, inst, p, &p);
2702 case MONO_TYPE_ARRAY: {
2703 MonoArrayType *array = t->data.array;
2706 encode_klass_ref (acfg, array->eklass, p, &p);
2707 encode_value (array->rank, p, &p);
2708 encode_value (array->numsizes, p, &p);
2709 for (i = 0; i < array->numsizes; ++i)
2710 encode_value (array->sizes [i], p, &p);
2711 encode_value (array->numlobounds, p, &p);
2712 for (i = 0; i < array->numlobounds; ++i)
2713 encode_value (array->lobounds [i], p, &p);
2717 case MONO_TYPE_MVAR:
2718 encode_klass_ref (acfg, mono_class_from_mono_type (t), p, &p);
2721 g_assert_not_reached ();
2728 encode_signature (MonoAotCompile *acfg, MonoMethodSignature *sig, guint8 *buf, guint8 **endbuf)
2734 /* Similar to the metadata encoding */
2735 if (sig->generic_param_count)
2739 if (sig->explicit_this)
2741 flags |= (sig->call_convention & 0x0F);
2745 if (sig->generic_param_count)
2746 encode_value (sig->generic_param_count, p, &p);
2747 encode_value (sig->param_count, p, &p);
2749 encode_type (acfg, sig->ret, p, &p);
2750 for (i = 0; i < sig->param_count; ++i) {
2751 if (sig->sentinelpos == i) {
2752 *p = MONO_TYPE_SENTINEL;
2755 encode_type (acfg, sig->params [i], p, &p);
2761 #define MAX_IMAGE_INDEX 250
2764 encode_method_ref (MonoAotCompile *acfg, MonoMethod *method, guint8 *buf, guint8 **endbuf)
2766 guint32 image_index = get_image_index (acfg, method->klass->image);
2767 guint32 token = method->token;
2768 MonoJumpInfoToken *ji;
2772 * The encoding for most methods is as follows:
2773 * - image index encoded as a leb128
2774 * - token index encoded as a leb128
2775 * Values of image index >= MONO_AOT_METHODREF_MIN are used to mark additional
2776 * types of method encodings.
2779 /* Mark methods which can't use aot trampolines because they need the further
2780 * processing in mono_magic_trampoline () which requires a MonoMethod*.
2782 if ((method->is_generic && (method->flags & METHOD_ATTRIBUTE_VIRTUAL)) ||
2783 (method->iflags & METHOD_IMPL_ATTRIBUTE_SYNCHRONIZED))
2784 encode_value ((MONO_AOT_METHODREF_NO_AOT_TRAMPOLINE << 24), p, &p);
2786 if (method->wrapper_type) {
2787 WrapperInfo *info = mono_marshal_get_wrapper_info (method);
2789 encode_value ((MONO_AOT_METHODREF_WRAPPER << 24), p, &p);
2791 encode_value (method->wrapper_type, p, &p);
2793 switch (method->wrapper_type) {
2794 case MONO_WRAPPER_REMOTING_INVOKE:
2795 case MONO_WRAPPER_REMOTING_INVOKE_WITH_CHECK:
2796 case MONO_WRAPPER_XDOMAIN_INVOKE: {
2799 m = mono_marshal_method_from_wrapper (method);
2801 encode_method_ref (acfg, m, p, &p);
2804 case MONO_WRAPPER_PROXY_ISINST:
2805 case MONO_WRAPPER_LDFLD:
2806 case MONO_WRAPPER_LDFLDA:
2807 case MONO_WRAPPER_STFLD:
2808 case MONO_WRAPPER_ISINST: {
2810 encode_klass_ref (acfg, info->d.proxy.klass, p, &p);
2813 case MONO_WRAPPER_LDFLD_REMOTE:
2814 case MONO_WRAPPER_STFLD_REMOTE:
2816 case MONO_WRAPPER_ALLOC: {
2817 /* The GC name is saved once in MonoAotFileInfo */
2818 g_assert (info->d.alloc.alloc_type != -1);
2819 encode_value (info->d.alloc.alloc_type, p, &p);
2822 case MONO_WRAPPER_WRITE_BARRIER: {
2826 case MONO_WRAPPER_STELEMREF: {
2828 encode_value (info->subtype, p, &p);
2829 if (info->subtype == WRAPPER_SUBTYPE_VIRTUAL_STELEMREF)
2830 encode_value (info->d.virtual_stelemref.kind, p, &p);
2833 case MONO_WRAPPER_UNKNOWN: {
2835 encode_value (info->subtype, p, &p);
2836 if (info->subtype == WRAPPER_SUBTYPE_PTR_TO_STRUCTURE ||
2837 info->subtype == WRAPPER_SUBTYPE_STRUCTURE_TO_PTR)
2838 encode_klass_ref (acfg, method->klass, p, &p);
2839 else if (info->subtype == WRAPPER_SUBTYPE_SYNCHRONIZED_INNER)
2840 encode_method_ref (acfg, info->d.synchronized_inner.method, p, &p);
2841 else if (info->subtype == WRAPPER_SUBTYPE_ARRAY_ACCESSOR)
2842 encode_method_ref (acfg, info->d.array_accessor.method, p, &p);
2845 case MONO_WRAPPER_MANAGED_TO_NATIVE: {
2847 encode_value (info->subtype, p, &p);
2848 if (info->subtype == WRAPPER_SUBTYPE_ICALL_WRAPPER) {
2849 strcpy ((char*)p, method->name);
2850 p += strlen (method->name) + 1;
2851 } else if (info->subtype == WRAPPER_SUBTYPE_NATIVE_FUNC_AOT) {
2852 encode_method_ref (acfg, info->d.managed_to_native.method, p, &p);
2854 g_assert (info->subtype == WRAPPER_SUBTYPE_NONE || info->subtype == WRAPPER_SUBTYPE_PINVOKE);
2855 encode_method_ref (acfg, info->d.managed_to_native.method, p, &p);
2859 case MONO_WRAPPER_SYNCHRONIZED: {
2862 m = mono_marshal_method_from_wrapper (method);
2864 g_assert (m != method);
2865 encode_method_ref (acfg, m, p, &p);
2868 case MONO_WRAPPER_MANAGED_TO_MANAGED: {
2870 encode_value (info->subtype, p, &p);
2872 if (info->subtype == WRAPPER_SUBTYPE_ELEMENT_ADDR) {
2873 encode_value (info->d.element_addr.rank, p, &p);
2874 encode_value (info->d.element_addr.elem_size, p, &p);
2875 } else if (info->subtype == WRAPPER_SUBTYPE_STRING_CTOR) {
2876 encode_method_ref (acfg, info->d.string_ctor.method, p, &p);
2878 g_assert_not_reached ();
2882 case MONO_WRAPPER_CASTCLASS: {
2884 encode_value (info->subtype, p, &p);
2887 case MONO_WRAPPER_RUNTIME_INVOKE: {
2889 encode_value (info->subtype, p, &p);
2890 encode_value (info->d.runtime_invoke.pass_rgctx, p, &p);
2891 if (info->subtype == WRAPPER_SUBTYPE_RUNTIME_INVOKE_DIRECT || info->subtype == WRAPPER_SUBTYPE_RUNTIME_INVOKE_VIRTUAL)
2892 encode_method_ref (acfg, info->d.runtime_invoke.method, p, &p);
2893 else if (info->subtype == WRAPPER_SUBTYPE_RUNTIME_INVOKE_NORMAL)
2894 encode_signature (acfg, info->d.runtime_invoke.sig, p, &p);
2897 case MONO_WRAPPER_DELEGATE_INVOKE:
2898 case MONO_WRAPPER_DELEGATE_BEGIN_INVOKE:
2899 case MONO_WRAPPER_DELEGATE_END_INVOKE: {
2900 if (method->is_inflated) {
2901 /* These wrappers are identified by their class */
2902 encode_value (1, p, &p);
2903 encode_klass_ref (acfg, method->klass, p, &p);
2905 MonoMethodSignature *sig = mono_method_signature (method);
2906 WrapperInfo *info = mono_marshal_get_wrapper_info (method);
2908 encode_value (0, p, &p);
2909 if (method->wrapper_type == MONO_WRAPPER_DELEGATE_INVOKE)
2910 encode_value (info ? info->subtype : 0, p, &p);
2911 encode_signature (acfg, sig, p, &p);
2915 case MONO_WRAPPER_NATIVE_TO_MANAGED: {
2917 encode_method_ref (acfg, info->d.native_to_managed.method, p, &p);
2918 encode_klass_ref (acfg, info->d.native_to_managed.klass, p, &p);
2922 g_assert_not_reached ();
2924 } else if (mono_method_signature (method)->is_inflated) {
2926 * This is a generic method, find the original token which referenced it and
2928 * Obtain the token from information recorded by the JIT.
2930 ji = (MonoJumpInfoToken *)g_hash_table_lookup (acfg->token_info_hash, method);
2932 image_index = get_image_index (acfg, ji->image);
2933 g_assert (image_index < MAX_IMAGE_INDEX);
2936 encode_value ((MONO_AOT_METHODREF_METHODSPEC << 24), p, &p);
2937 encode_value (image_index, p, &p);
2938 encode_value (token, p, &p);
2940 MonoMethod *declaring;
2941 MonoGenericContext *context = mono_method_get_context (method);
2943 g_assert (method->is_inflated);
2944 declaring = ((MonoMethodInflated*)method)->declaring;
2947 * This might be a non-generic method of a generic instance, which
2948 * doesn't have a token since the reference is generated by the JIT
2949 * like Nullable:Box/Unbox, or by generic sharing.
2951 encode_value ((MONO_AOT_METHODREF_GINST << 24), p, &p);
2952 /* Encode the klass */
2953 encode_klass_ref (acfg, method->klass, p, &p);
2954 /* Encode the method */
2955 image_index = get_image_index (acfg, method->klass->image);
2956 g_assert (image_index < MAX_IMAGE_INDEX);
2957 g_assert (declaring->token);
2958 token = declaring->token;
2959 g_assert (mono_metadata_token_table (token) == MONO_TABLE_METHOD);
2960 encode_value (image_index, p, &p);
2961 encode_value (token, p, &p);
2962 encode_generic_context (acfg, context, p, &p);
2964 } else if (token == 0) {
2965 /* This might be a method of a constructed type like int[,].Set */
2966 /* Obtain the token from information recorded by the JIT */
2967 ji = (MonoJumpInfoToken *)g_hash_table_lookup (acfg->token_info_hash, method);
2969 image_index = get_image_index (acfg, ji->image);
2970 g_assert (image_index < MAX_IMAGE_INDEX);
2973 encode_value ((MONO_AOT_METHODREF_METHODSPEC << 24), p, &p);
2974 encode_value (image_index, p, &p);
2975 encode_value (token, p, &p);
2978 g_assert (method->klass->rank);
2980 /* Encode directly */
2981 encode_value ((MONO_AOT_METHODREF_ARRAY << 24), p, &p);
2982 encode_klass_ref (acfg, method->klass, p, &p);
2983 if (!strcmp (method->name, ".ctor") && mono_method_signature (method)->param_count == method->klass->rank)
2984 encode_value (0, p, &p);
2985 else if (!strcmp (method->name, ".ctor") && mono_method_signature (method)->param_count == method->klass->rank * 2)
2986 encode_value (1, p, &p);
2987 else if (!strcmp (method->name, "Get"))
2988 encode_value (2, p, &p);
2989 else if (!strcmp (method->name, "Address"))
2990 encode_value (3, p, &p);
2991 else if (!strcmp (method->name, "Set"))
2992 encode_value (4, p, &p);
2994 g_assert_not_reached ();
2997 g_assert (mono_metadata_token_table (token) == MONO_TABLE_METHOD);
2999 if (image_index >= MONO_AOT_METHODREF_MIN) {
3000 encode_value ((MONO_AOT_METHODREF_LARGE_IMAGE_INDEX << 24), p, &p);
3001 encode_value (image_index, p, &p);
3002 encode_value (mono_metadata_token_index (token), p, &p);
3004 encode_value ((image_index << 24) | mono_metadata_token_index (token), p, &p);
3011 compare_patches (gconstpointer a, gconstpointer b)
3015 i = (*(MonoJumpInfo**)a)->ip.i;
3016 j = (*(MonoJumpInfo**)b)->ip.i;
3027 static G_GNUC_UNUSED char*
3028 patch_to_string (MonoJumpInfo *patch_info)
3032 str = g_string_new ("");
3034 g_string_append_printf (str, "%s(", get_patch_name (patch_info->type));
3036 switch (patch_info->type) {
3037 case MONO_PATCH_INFO_VTABLE:
3038 mono_type_get_desc (str, &patch_info->data.klass->byval_arg, TRUE);
3043 g_string_append_printf (str, ")");
3044 return g_string_free (str, FALSE);
3050 * Return whenever PATCH_INFO refers to a direct call, and thus requires a
3053 static inline gboolean
3054 is_plt_patch (MonoJumpInfo *patch_info)
3056 switch (patch_info->type) {
3057 case MONO_PATCH_INFO_METHOD:
3058 case MONO_PATCH_INFO_INTERNAL_METHOD:
3059 case MONO_PATCH_INFO_JIT_ICALL_ADDR:
3060 case MONO_PATCH_INFO_ICALL_ADDR:
3061 case MONO_PATCH_INFO_RGCTX_FETCH:
3071 * Return the symbol identifying the plt entry PLT_OFFSET.
3074 get_plt_symbol (MonoAotCompile *acfg, int plt_offset, MonoJumpInfo *patch_info)
3078 * The Apple linker reorganizes object files, so it doesn't like branches to local
3079 * labels, since those have no relocations.
3081 return g_strdup_printf ("%sp_%d", acfg->llvm_label_prefix, plt_offset);
3083 return g_strdup_printf ("%sp_%d", acfg->temp_prefix, plt_offset);
3090 * Return a PLT entry which belongs to the method identified by PATCH_INFO.
3092 static MonoPltEntry*
3093 get_plt_entry (MonoAotCompile *acfg, MonoJumpInfo *patch_info)
3096 gboolean synchronized = FALSE;
3097 static int synchronized_symbol_idx;
3099 if (!is_plt_patch (patch_info))
3102 if (!acfg->patch_to_plt_entry [patch_info->type])
3103 acfg->patch_to_plt_entry [patch_info->type] = g_hash_table_new (mono_patch_info_hash, mono_patch_info_equal);
3104 res = (MonoPltEntry *)g_hash_table_lookup (acfg->patch_to_plt_entry [patch_info->type], patch_info);
3106 if (!acfg->llvm && patch_info->type == MONO_PATCH_INFO_METHOD && (patch_info->data.method->iflags & METHOD_IMPL_ATTRIBUTE_SYNCHRONIZED)) {
3108 * Allocate a separate PLT slot for each such patch, since some plt
3109 * entries will refer to the method itself, and some will refer to the
3113 synchronized = TRUE;
3117 MonoJumpInfo *new_ji;
3119 new_ji = mono_patch_info_dup_mp (acfg->mempool, patch_info);
3121 res = (MonoPltEntry *)mono_mempool_alloc0 (acfg->mempool, sizeof (MonoPltEntry));
3122 res->plt_offset = acfg->plt_offset;
3124 res->symbol = get_plt_symbol (acfg, res->plt_offset, patch_info);
3125 if (acfg->aot_opts.write_symbols)
3126 res->debug_sym = get_plt_entry_debug_sym (acfg, res->ji, acfg->plt_entry_debug_sym_cache);
3128 /* Avoid duplicate symbols because we don't cache */
3129 res->symbol = g_strdup_printf ("%s_%d", res->symbol, synchronized_symbol_idx);
3131 res->debug_sym = g_strdup_printf ("%s_%d", res->debug_sym, synchronized_symbol_idx);
3132 synchronized_symbol_idx ++;
3135 res->llvm_symbol = g_strdup_printf ("%s_%s_llvm", res->symbol, res->debug_sym);
3137 res->llvm_symbol = g_strdup_printf ("%s_llvm", res->symbol);
3139 g_hash_table_insert (acfg->patch_to_plt_entry [new_ji->type], new_ji, res);
3141 g_hash_table_insert (acfg->plt_offset_to_entry, GUINT_TO_POINTER (res->plt_offset), res);
3143 //g_assert (mono_patch_info_equal (patch_info, new_ji));
3144 //mono_print_ji (patch_info); printf ("\n");
3145 //g_hash_table_print_stats (acfg->patch_to_plt_entry);
3147 acfg->plt_offset ++;
3156 * Returns the offset of the GOT slot where the runtime object resulting from resolving
3157 * JI could be found if it exists, otherwise allocates a new one.
3160 get_got_offset (MonoAotCompile *acfg, gboolean llvm, MonoJumpInfo *ji)
3163 GotInfo *info = llvm ? &acfg->llvm_got_info : &acfg->got_info;
3165 got_offset = GPOINTER_TO_UINT (g_hash_table_lookup (info->patch_to_got_offset_by_type [ji->type], ji));
3167 return got_offset - 1;
3170 got_offset = acfg->llvm_got_offset;
3171 acfg->llvm_got_offset ++;
3173 got_offset = acfg->got_offset;
3174 acfg->got_offset ++;
3177 acfg->stats.got_slots ++;
3178 acfg->stats.got_slot_types [ji->type] ++;
3180 g_hash_table_insert (info->patch_to_got_offset, ji, GUINT_TO_POINTER (got_offset + 1));
3181 g_hash_table_insert (info->patch_to_got_offset_by_type [ji->type], ji, GUINT_TO_POINTER (got_offset + 1));
3182 g_ptr_array_add (info->got_patches, ji);
3187 /* Add a method to the list of methods which need to be emitted */
3189 add_method_with_index (MonoAotCompile *acfg, MonoMethod *method, int index, gboolean extra)
3192 if (!g_hash_table_lookup (acfg->method_indexes, method)) {
3193 g_ptr_array_add (acfg->methods, method);
3194 g_hash_table_insert (acfg->method_indexes, method, GUINT_TO_POINTER (index + 1));
3195 acfg->nmethods = acfg->methods->len + 1;
3198 if (method->wrapper_type || extra)
3199 g_ptr_array_add (acfg->extra_methods, method);
3203 prefer_gsharedvt_method (MonoAotCompile *acfg, MonoMethod *method)
3205 /* One instantiation with valuetypes is generated for each async method */
3206 if (method->klass->image == mono_defaults.corlib && (!strcmp (method->klass->name, "AsyncMethodBuilderCore") || !strcmp (method->klass->name, "AsyncVoidMethodBuilder")))
3213 get_method_index (MonoAotCompile *acfg, MonoMethod *method)
3215 int index = GPOINTER_TO_UINT (g_hash_table_lookup (acfg->method_indexes, method));
3223 add_method_full (MonoAotCompile *acfg, MonoMethod *method, gboolean extra, int depth)
3227 index = GPOINTER_TO_UINT (g_hash_table_lookup (acfg->method_indexes, method));
3231 index = acfg->method_index;
3232 add_method_with_index (acfg, method, index, extra);
3234 g_ptr_array_add (acfg->method_order, GUINT_TO_POINTER (index));
3236 g_hash_table_insert (acfg->method_depth, method, GUINT_TO_POINTER (depth));
3238 acfg->method_index ++;
3244 add_method (MonoAotCompile *acfg, MonoMethod *method)
3246 return add_method_full (acfg, method, FALSE, 0);
3250 add_extra_method_with_depth (MonoAotCompile *acfg, MonoMethod *method, int depth)
3252 if (mono_method_is_generic_sharable_full (method, TRUE, TRUE, FALSE))
3253 method = mini_get_shared_method (method);
3254 else if ((acfg->opts & MONO_OPT_GSHAREDVT) && prefer_gsharedvt_method (acfg, method) && mono_method_is_generic_sharable_full (method, FALSE, FALSE, TRUE))
3255 /* Use the gsharedvt version */
3256 method = mini_get_shared_method_full (method, TRUE, TRUE);
3258 if (acfg->aot_opts.log_generics)
3259 aot_printf (acfg, "%*sAdding method %s.\n", depth, "", mono_method_full_name (method, TRUE));
3261 add_method_full (acfg, method, TRUE, depth);
3265 add_extra_method (MonoAotCompile *acfg, MonoMethod *method)
3267 add_extra_method_with_depth (acfg, method, 0);
3271 add_jit_icall_wrapper (gpointer key, gpointer value, gpointer user_data)
3273 MonoAotCompile *acfg = (MonoAotCompile *)user_data;
3274 MonoJitICallInfo *callinfo = (MonoJitICallInfo *)value;
3275 MonoMethod *wrapper;
3281 name = g_strdup_printf ("__icall_wrapper_%s", callinfo->name);
3282 wrapper = mono_marshal_get_icall_wrapper (callinfo->sig, name, callinfo->func, TRUE);
3285 add_method (acfg, wrapper);
3289 get_runtime_invoke_sig (MonoMethodSignature *sig)
3291 MonoMethodBuilder *mb;
3294 mb = mono_mb_new (mono_defaults.object_class, "FOO", MONO_WRAPPER_NONE);
3295 m = mono_mb_create_method (mb, sig, 16);
3296 return mono_marshal_get_runtime_invoke (m, FALSE, FALSE);
3300 get_runtime_invoke (MonoAotCompile *acfg, MonoMethod *method, gboolean virtual_)
3302 return mono_marshal_get_runtime_invoke (method, virtual_, acfg->aot_opts.llvm_only && mono_method_needs_static_rgctx_invoke (method, TRUE));
3306 can_marshal_struct (MonoClass *klass)
3308 MonoClassField *field;
3309 gboolean can_marshal = TRUE;
3310 gpointer iter = NULL;
3311 MonoMarshalType *info;
3314 if ((klass->flags & TYPE_ATTRIBUTE_LAYOUT_MASK) == TYPE_ATTRIBUTE_AUTO_LAYOUT)
3317 info = mono_marshal_load_type_info (klass);
3319 /* Only allow a few field types to avoid asserts in the marshalling code */
3320 while ((field = mono_class_get_fields (klass, &iter))) {
3321 if ((field->type->attrs & FIELD_ATTRIBUTE_STATIC))
3324 switch (field->type->type) {
3329 case MONO_TYPE_BOOLEAN:
3332 case MONO_TYPE_CHAR:
3340 case MONO_TYPE_STRING:
3342 case MONO_TYPE_VALUETYPE:
3343 if (!mono_class_from_mono_type (field->type)->enumtype && !can_marshal_struct (mono_class_from_mono_type (field->type)))
3344 can_marshal = FALSE;
3346 case MONO_TYPE_SZARRAY: {
3347 gboolean has_mspec = FALSE;
3350 for (i = 0; i < info->num_fields; ++i) {
3351 if (info->fields [i].field == field && info->fields [i].mspec)
3356 can_marshal = FALSE;
3360 can_marshal = FALSE;
3366 /* Its hard to compute whenever these can be marshalled or not */
3367 if (!strcmp (klass->name_space, "System.Net.NetworkInformation.MacOsStructs") && strcmp (klass->name, "sockaddr_dl"))
3374 create_gsharedvt_inst (MonoAotCompile *acfg, MonoMethod *method, MonoGenericContext *ctx)
3376 /* Create a vtype instantiation */
3377 MonoGenericContext shared_context;
3379 MonoGenericInst *inst;
3380 MonoGenericContainer *container;
3381 MonoClass **constraints;
3384 memset (ctx, 0, sizeof (MonoGenericContext));
3386 if (method->klass->generic_container) {
3387 shared_context = method->klass->generic_container->context;
3388 inst = shared_context.class_inst;
3390 args = g_new0 (MonoType*, inst->type_argc);
3391 for (i = 0; i < inst->type_argc; ++i) {
3392 args [i] = &mono_defaults.int_class->byval_arg;
3394 ctx->class_inst = mono_metadata_get_generic_inst (inst->type_argc, args);
3396 if (method->is_generic) {
3397 container = mono_method_get_generic_container (method);
3398 shared_context = container->context;
3399 inst = shared_context.method_inst;
3401 args = g_new0 (MonoType*, inst->type_argc);
3402 for (i = 0; i < container->type_argc; ++i) {
3403 MonoGenericParamInfo *info = &container->type_params [i].info;
3404 gboolean ref_only = FALSE;
3406 if (info && info->constraints) {
3407 constraints = info->constraints;
3409 while (*constraints) {
3410 MonoClass *cklass = *constraints;
3411 if (!(cklass == mono_defaults.object_class || (cklass->image == mono_defaults.corlib && !strcmp (cklass->name, "ValueType"))))
3412 /* Inflaring the method with our vtype would not be valid */
3419 args [i] = &mono_defaults.object_class->byval_arg;
3421 args [i] = &mono_defaults.int_class->byval_arg;
3423 ctx->method_inst = mono_metadata_get_generic_inst (inst->type_argc, args);
3428 add_wrappers (MonoAotCompile *acfg)
3430 MonoMethod *method, *m;
3432 MonoMethodSignature *sig, *csig;
3436 * FIXME: Instead of AOTing all the wrappers, it might be better to redesign them
3437 * so there is only one wrapper of a given type, or inlining their contents into their
3440 for (i = 0; i < acfg->image->tables [MONO_TABLE_METHOD].rows; ++i) {
3443 guint32 token = MONO_TOKEN_METHOD_DEF | (i + 1);
3444 gboolean skip = FALSE;
3446 method = mono_get_method_checked (acfg->image, token, NULL, NULL, &error);
3447 report_loader_error (acfg, &error, "Failed to load method token 0x%x due to %s\n", i, mono_error_get_message (&error));
3449 if ((method->flags & METHOD_ATTRIBUTE_PINVOKE_IMPL) ||
3450 (method->iflags & METHOD_IMPL_ATTRIBUTE_RUNTIME) ||
3451 (method->flags & METHOD_ATTRIBUTE_ABSTRACT))
3454 /* Skip methods which can not be handled by get_runtime_invoke () */
3455 sig = mono_method_signature (method);
3458 if ((sig->ret->type == MONO_TYPE_PTR) ||
3459 (sig->ret->type == MONO_TYPE_TYPEDBYREF))
3461 if (mono_class_is_open_constructed_type (sig->ret))
3464 for (j = 0; j < sig->param_count; j++) {
3465 if (sig->params [j]->type == MONO_TYPE_TYPEDBYREF)
3467 if (mono_class_is_open_constructed_type (sig->params [j]))
3471 #ifdef MONO_ARCH_DYN_CALL_SUPPORTED
3472 if (!mono_class_is_contextbound (method->klass)) {
3473 MonoDynCallInfo *info = mono_arch_dyn_call_prepare (sig);
3474 gboolean has_nullable = FALSE;
3476 for (j = 0; j < sig->param_count; j++) {
3477 if (sig->params [j]->type == MONO_TYPE_GENERICINST && mono_class_is_nullable (mono_class_from_mono_type (sig->params [j])))
3478 has_nullable = TRUE;
3481 if (info && !has_nullable && !acfg->aot_opts.llvm_only) {
3482 /* Supported by the dynamic runtime-invoke wrapper */
3486 mono_arch_dyn_call_free (info);
3491 //printf ("%s\n", mono_method_full_name (method, TRUE));
3492 add_method (acfg, get_runtime_invoke (acfg, method, FALSE));
3496 if (strcmp (acfg->image->assembly->aname.name, "mscorlib") == 0) {
3499 /* Runtime invoke wrappers */
3501 /* void runtime-invoke () [.cctor] */
3502 csig = mono_metadata_signature_alloc (mono_defaults.corlib, 0);
3503 csig->ret = &mono_defaults.void_class->byval_arg;
3504 add_method (acfg, get_runtime_invoke_sig (csig));
3506 /* void runtime-invoke () [Finalize] */
3507 csig = mono_metadata_signature_alloc (mono_defaults.corlib, 0);
3509 csig->ret = &mono_defaults.void_class->byval_arg;
3510 add_method (acfg, get_runtime_invoke_sig (csig));
3512 /* void runtime-invoke (string) [exception ctor] */
3513 csig = mono_metadata_signature_alloc (mono_defaults.corlib, 1);
3515 csig->ret = &mono_defaults.void_class->byval_arg;
3516 csig->params [0] = &mono_defaults.string_class->byval_arg;
3517 add_method (acfg, get_runtime_invoke_sig (csig));
3519 /* void runtime-invoke (string, string) [exception ctor] */
3520 csig = mono_metadata_signature_alloc (mono_defaults.corlib, 2);
3522 csig->ret = &mono_defaults.void_class->byval_arg;
3523 csig->params [0] = &mono_defaults.string_class->byval_arg;
3524 csig->params [1] = &mono_defaults.string_class->byval_arg;
3525 add_method (acfg, get_runtime_invoke_sig (csig));
3527 /* string runtime-invoke () [Exception.ToString ()] */
3528 csig = mono_metadata_signature_alloc (mono_defaults.corlib, 0);
3530 csig->ret = &mono_defaults.string_class->byval_arg;
3531 add_method (acfg, get_runtime_invoke_sig (csig));
3533 /* void runtime-invoke (string, Exception) [exception ctor] */
3534 csig = mono_metadata_signature_alloc (mono_defaults.corlib, 2);
3536 csig->ret = &mono_defaults.void_class->byval_arg;
3537 csig->params [0] = &mono_defaults.string_class->byval_arg;
3538 csig->params [1] = &mono_defaults.exception_class->byval_arg;
3539 add_method (acfg, get_runtime_invoke_sig (csig));
3541 /* Assembly runtime-invoke (string, bool) [DoAssemblyResolve] */
3542 csig = mono_metadata_signature_alloc (mono_defaults.corlib, 2);
3544 csig->ret = &(mono_class_from_name (
3545 mono_defaults.corlib, "System.Reflection", "Assembly"))->byval_arg;
3546 csig->params [0] = &mono_defaults.string_class->byval_arg;
3547 csig->params [1] = &mono_defaults.boolean_class->byval_arg;
3548 add_method (acfg, get_runtime_invoke_sig (csig));
3550 /* runtime-invoke used by finalizers */
3551 add_method (acfg, get_runtime_invoke (acfg, mono_class_get_method_from_name_flags (mono_defaults.object_class, "Finalize", 0, 0), TRUE));
3553 /* This is used by mono_runtime_capture_context () */
3554 method = mono_get_context_capture_method ();
3556 add_method (acfg, get_runtime_invoke (acfg, method, FALSE));
3558 #ifdef MONO_ARCH_DYN_CALL_SUPPORTED
3559 if (!acfg->aot_opts.llvm_only)
3560 add_method (acfg, mono_marshal_get_runtime_invoke_dynamic ());
3564 add_method (acfg, mono_marshal_get_stelemref ());
3566 if (MONO_ARCH_HAVE_TLS_GET) {
3567 /* Managed Allocators */
3568 nallocators = mono_gc_get_managed_allocator_types ();
3569 for (i = 0; i < nallocators; ++i) {
3570 m = mono_gc_get_managed_allocator_by_type (i, TRUE);
3572 add_method (acfg, m);
3574 for (i = 0; i < nallocators; ++i) {
3575 m = mono_gc_get_managed_allocator_by_type (i, FALSE);
3577 add_method (acfg, m);
3581 /* write barriers */
3582 if (mono_gc_is_moving ()) {
3583 add_method (acfg, mono_gc_get_specific_write_barrier (FALSE));
3584 add_method (acfg, mono_gc_get_specific_write_barrier (TRUE));
3587 /* Stelemref wrappers */
3589 MonoMethod **wrappers;
3592 wrappers = mono_marshal_get_virtual_stelemref_wrappers (&nwrappers);
3593 for (i = 0; i < nwrappers; ++i)
3594 add_method (acfg, wrappers [i]);
3598 /* castclass_with_check wrapper */
3599 add_method (acfg, mono_marshal_get_castclass_with_cache ());
3600 /* isinst_with_check wrapper */
3601 add_method (acfg, mono_marshal_get_isinst_with_cache ());
3603 /* JIT icall wrappers */
3604 /* FIXME: locking - this is "safe" as full-AOT threads don't mutate the icall hash*/
3605 g_hash_table_foreach (mono_get_jit_icall_info (), add_jit_icall_wrapper, acfg);
3609 * remoting-invoke-with-check wrappers are very frequent, so avoid emitting them,
3610 * we use the original method instead at runtime.
3611 * Since full-aot doesn't support remoting, this is not a problem.
3614 /* remoting-invoke wrappers */
3615 for (i = 0; i < acfg->image->tables [MONO_TABLE_METHOD].rows; ++i) {
3616 MonoMethodSignature *sig;
3618 token = MONO_TOKEN_METHOD_DEF | (i + 1);
3619 method = mono_get_method (acfg->image, token, NULL);
3621 sig = mono_method_signature (method);
3623 if (sig->hasthis && (method->klass->marshalbyref || method->klass == mono_defaults.object_class)) {
3624 m = mono_marshal_get_remoting_invoke_with_check (method);
3626 add_method (acfg, m);
3631 /* delegate-invoke wrappers */
3632 for (i = 0; i < acfg->image->tables [MONO_TABLE_TYPEDEF].rows; ++i) {
3635 MonoCustomAttrInfo *cattr;
3637 token = MONO_TOKEN_TYPE_DEF | (i + 1);
3638 klass = mono_class_get_checked (acfg->image, token, &error);
3641 mono_error_cleanup (&error);
3645 if (!klass->delegate || klass == mono_defaults.delegate_class || klass == mono_defaults.multicastdelegate_class)
3648 if (!klass->generic_container) {
3649 method = mono_get_delegate_invoke (klass);
3651 m = mono_marshal_get_delegate_invoke (method, NULL);
3653 add_method (acfg, m);
3655 method = mono_class_get_method_from_name_flags (klass, "BeginInvoke", -1, 0);
3657 add_method (acfg, mono_marshal_get_delegate_begin_invoke (method));
3659 method = mono_class_get_method_from_name_flags (klass, "EndInvoke", -1, 0);
3661 add_method (acfg, mono_marshal_get_delegate_end_invoke (method));
3663 cattr = mono_custom_attrs_from_class (klass);
3668 for (j = 0; j < cattr->num_attrs; ++j)
3669 if (cattr->attrs [j].ctor && (!strcmp (cattr->attrs [j].ctor->klass->name, "MonoNativeFunctionWrapperAttribute") || !strcmp (cattr->attrs [j].ctor->klass->name, "UnmanagedFunctionPointerAttribute")))
3671 if (j < cattr->num_attrs) {
3673 MonoMethod *wrapper;
3674 MonoMethod *del_invoke;
3676 /* Add wrappers needed by mono_ftnptr_to_delegate () */
3677 invoke = mono_get_delegate_invoke (klass);
3678 wrapper = mono_marshal_get_native_func_wrapper_aot (klass);
3679 del_invoke = mono_marshal_get_delegate_invoke_internal (invoke, FALSE, TRUE, wrapper);
3680 add_method (acfg, wrapper);
3681 add_method (acfg, del_invoke);
3684 } else if ((acfg->opts & MONO_OPT_GSHAREDVT) && klass->generic_container) {
3686 MonoGenericContext ctx;
3687 MonoMethod *inst, *gshared;
3690 * Emit gsharedvt versions of the generic delegate-invoke wrappers
3693 method = mono_get_delegate_invoke (klass);
3694 create_gsharedvt_inst (acfg, method, &ctx);
3696 inst = mono_class_inflate_generic_method_checked (method, &ctx, &error);
3697 g_assert (mono_error_ok (&error)); /* FIXME don't swallow the error */
3699 m = mono_marshal_get_delegate_invoke (inst, NULL);
3700 g_assert (m->is_inflated);
3702 gshared = mini_get_shared_method_full (m, FALSE, TRUE);
3703 add_extra_method (acfg, gshared);
3706 method = mono_get_delegate_begin_invoke (klass);
3707 create_gsharedvt_inst (acfg, method, &ctx);
3709 inst = mono_class_inflate_generic_method_checked (method, &ctx, &error);
3710 g_assert (mono_error_ok (&error)); /* FIXME don't swallow the error */
3712 m = mono_marshal_get_delegate_begin_invoke (inst);
3713 g_assert (m->is_inflated);
3715 gshared = mini_get_shared_method_full (m, FALSE, TRUE);
3716 add_extra_method (acfg, gshared);
3719 method = mono_get_delegate_end_invoke (klass);
3720 create_gsharedvt_inst (acfg, method, &ctx);
3722 inst = mono_class_inflate_generic_method_checked (method, &ctx, &error);
3723 g_assert (mono_error_ok (&error)); /* FIXME don't swallow the error */
3725 m = mono_marshal_get_delegate_end_invoke (inst);
3726 g_assert (m->is_inflated);
3728 gshared = mini_get_shared_method_full (m, FALSE, TRUE);
3729 add_extra_method (acfg, gshared);
3734 /* array access wrappers */
3735 for (i = 0; i < acfg->image->tables [MONO_TABLE_TYPESPEC].rows; ++i) {
3739 token = MONO_TOKEN_TYPE_SPEC | (i + 1);
3740 klass = mono_class_get_checked (acfg->image, token, &error);
3743 mono_error_cleanup (&error);
3747 if (klass->rank && MONO_TYPE_IS_PRIMITIVE (&klass->element_class->byval_arg)) {
3748 MonoMethod *m, *wrapper;
3750 /* Add runtime-invoke wrappers too */
3752 m = mono_class_get_method_from_name (klass, "Get", -1);
3754 wrapper = mono_marshal_get_array_accessor_wrapper (m);
3755 add_extra_method (acfg, wrapper);
3756 add_extra_method (acfg, get_runtime_invoke (acfg, wrapper, FALSE));
3758 m = mono_class_get_method_from_name (klass, "Set", -1);
3760 wrapper = mono_marshal_get_array_accessor_wrapper (m);
3761 add_extra_method (acfg, wrapper);
3762 add_extra_method (acfg, get_runtime_invoke (acfg, wrapper, FALSE));
3766 /* Synchronized wrappers */
3767 for (i = 0; i < acfg->image->tables [MONO_TABLE_METHOD].rows; ++i) {
3769 token = MONO_TOKEN_METHOD_DEF | (i + 1);
3770 method = mono_get_method_checked (acfg->image, token, NULL, NULL, &error);
3771 report_loader_error (acfg, &error, "Failed to load method token 0x%x due to %s\n", i, mono_error_get_message (&error));
3773 if (method->iflags & METHOD_IMPL_ATTRIBUTE_SYNCHRONIZED) {
3774 if (method->is_generic) {
3776 } else if ((acfg->opts & MONO_OPT_GSHAREDVT) && method->klass->generic_container) {
3778 MonoGenericContext ctx;
3779 MonoMethod *inst, *gshared, *m;
3782 * Create a generic wrapper for a generic instance, and AOT that.
3784 create_gsharedvt_inst (acfg, method, &ctx);
3785 inst = mono_class_inflate_generic_method_checked (method, &ctx, &error);
3786 g_assert (mono_error_ok (&error)); /* FIXME don't swallow the error */
3787 m = mono_marshal_get_synchronized_wrapper (inst);
3788 g_assert (m->is_inflated);
3789 gshared = mini_get_shared_method_full (m, FALSE, TRUE);
3790 add_method (acfg, gshared);
3792 add_method (acfg, mono_marshal_get_synchronized_wrapper (method));
3797 /* pinvoke wrappers */
3798 for (i = 0; i < acfg->image->tables [MONO_TABLE_METHOD].rows; ++i) {
3801 guint32 token = MONO_TOKEN_METHOD_DEF | (i + 1);
3803 method = mono_get_method_checked (acfg->image, token, NULL, NULL, &error);
3804 report_loader_error (acfg, &error, "Failed to load method token 0x%x due to %s\n", i, mono_error_get_message (&error));
3806 if ((method->flags & METHOD_ATTRIBUTE_PINVOKE_IMPL) ||
3807 (method->iflags & METHOD_IMPL_ATTRIBUTE_INTERNAL_CALL)) {
3808 add_method (acfg, mono_marshal_get_native_wrapper (method, TRUE, TRUE));
3812 /* native-to-managed wrappers */
3813 for (i = 0; i < acfg->image->tables [MONO_TABLE_METHOD].rows; ++i) {
3816 guint32 token = MONO_TOKEN_METHOD_DEF | (i + 1);
3817 MonoCustomAttrInfo *cattr;
3820 method = mono_get_method_checked (acfg->image, token, NULL, NULL, &error);
3821 report_loader_error (acfg, &error, "Failed to load method token 0x%x due to %s\n", i, mono_error_get_message (&error));
3824 * Only generate native-to-managed wrappers for methods which have an
3825 * attribute named MonoPInvokeCallbackAttribute. We search for the attribute by
3826 * name to avoid defining a new assembly to contain it.
3828 cattr = mono_custom_attrs_from_method (method);
3831 for (j = 0; j < cattr->num_attrs; ++j)
3832 if (cattr->attrs [j].ctor && !strcmp (cattr->attrs [j].ctor->klass->name, "MonoPInvokeCallbackAttribute"))
3834 if (j < cattr->num_attrs) {
3835 MonoCustomAttrEntry *e = &cattr->attrs [j];
3836 MonoMethodSignature *sig = mono_method_signature (e->ctor);
3837 const char *p = (const char*)e->data;
3839 int slen, num_named, named_type;
3843 char *export_name = NULL;
3844 MonoMethod *wrapper;
3846 /* this cannot be enforced by the C# compiler so we must give the user some warning before aborting */
3847 if (!(method->flags & METHOD_ATTRIBUTE_STATIC)) {
3848 g_warning ("AOT restriction: Method '%s' must be static since it is decorated with [MonoPInvokeCallback]. See http://ios.xamarin.com/Documentation/Limitations#Reverse_Callbacks",
3849 mono_method_full_name (method, TRUE));
3853 g_assert (sig->param_count == 1);
3854 g_assert (sig->params [0]->type == MONO_TYPE_CLASS && !strcmp (mono_class_from_mono_type (sig->params [0])->name, "Type"));
3857 * Decode the cattr manually since we can't create objects
3858 * during aot compilation.
3864 /* From load_cattr_value () in reflection.c */
3865 slen = mono_metadata_decode_value (p, &p);
3866 n = (char *)g_memdup (p, slen + 1);
3868 t = mono_reflection_type_from_name (n, acfg->image);
3872 klass = mono_class_from_mono_type (t);
3873 g_assert (klass->parent == mono_defaults.multicastdelegate_class);
3877 num_named = read16 (p);
3880 g_assert (num_named < 2);
3881 if (num_named == 1) {
3885 /* parse ExportSymbol attribute */
3887 named_type = *named;
3889 /* data_type = *named; */
3892 name_len = mono_metadata_decode_blob_size (named, &named);
3893 name = (char *)g_malloc (name_len + 1);
3894 memcpy (name, named, name_len);
3895 name [name_len] = 0;
3898 g_assert (named_type == 0x54);
3899 g_assert (!strcmp (name, "ExportSymbol"));
3901 /* load_cattr_value (), string case */
3902 g_assert (*named != (char)0xff);
3903 slen = mono_metadata_decode_value (named, &named);
3904 export_name = (char *)g_malloc (slen + 1);
3905 memcpy (export_name, named, slen);
3906 export_name [slen] = 0;
3910 wrapper = mono_marshal_get_managed_wrapper (method, klass, 0);
3911 add_method (acfg, wrapper);
3913 g_hash_table_insert (acfg->export_names, wrapper, export_name);
3917 if ((method->flags & METHOD_ATTRIBUTE_PINVOKE_IMPL) ||
3918 (method->iflags & METHOD_IMPL_ATTRIBUTE_INTERNAL_CALL)) {
3919 add_method (acfg, mono_marshal_get_native_wrapper (method, TRUE, TRUE));
3923 /* StructureToPtr/PtrToStructure wrappers */
3924 for (i = 0; i < acfg->image->tables [MONO_TABLE_TYPEDEF].rows; ++i) {
3928 token = MONO_TOKEN_TYPE_DEF | (i + 1);
3929 klass = mono_class_get_checked (acfg->image, token, &error);
3932 mono_error_cleanup (&error);
3936 if (klass->valuetype && !klass->generic_container && can_marshal_struct (klass) &&
3937 !(klass->nested_in && strstr (klass->nested_in->name, "<PrivateImplementationDetails>") == klass->nested_in->name)) {
3938 add_method (acfg, mono_marshal_get_struct_to_ptr (klass));
3939 add_method (acfg, mono_marshal_get_ptr_to_struct (klass));
3945 has_type_vars (MonoClass *klass)
3947 if ((klass->byval_arg.type == MONO_TYPE_VAR) || (klass->byval_arg.type == MONO_TYPE_MVAR))
3950 return has_type_vars (klass->element_class);
3951 if (klass->generic_class) {
3952 MonoGenericContext *context = &klass->generic_class->context;
3953 if (context->class_inst) {
3956 for (i = 0; i < context->class_inst->type_argc; ++i)
3957 if (has_type_vars (mono_class_from_mono_type (context->class_inst->type_argv [i])))
3961 if (klass->generic_container)
3967 is_vt_inst (MonoGenericInst *inst)
3971 for (i = 0; i < inst->type_argc; ++i) {
3972 MonoType *t = inst->type_argv [i];
3973 if (MONO_TYPE_ISSTRUCT (t) || t->type == MONO_TYPE_VALUETYPE)
3980 method_has_type_vars (MonoMethod *method)
3982 if (has_type_vars (method->klass))
3985 if (method->is_inflated) {
3986 MonoGenericContext *context = mono_method_get_context (method);
3987 if (context->method_inst) {
3990 for (i = 0; i < context->method_inst->type_argc; ++i)
3991 if (has_type_vars (mono_class_from_mono_type (context->method_inst->type_argv [i])))
3999 gboolean mono_aot_mode_is_full (MonoAotOptions *opts)
4001 return opts->mode == MONO_AOT_MODE_FULL;
4004 static void add_generic_class_with_depth (MonoAotCompile *acfg, MonoClass *klass, int depth, const char *ref);
4007 add_generic_class (MonoAotCompile *acfg, MonoClass *klass, gboolean force, const char *ref)
4009 /* This might lead to a huge code blowup so only do it if neccesary */
4010 if (!mono_aot_mode_is_full (&acfg->aot_opts) && !force)
4013 add_generic_class_with_depth (acfg, klass, 0, ref);
4017 check_type_depth (MonoType *t, int depth)
4025 case MONO_TYPE_GENERICINST: {
4026 MonoGenericClass *gklass = t->data.generic_class;
4027 MonoGenericInst *ginst = gklass->context.class_inst;
4030 for (i = 0; i < ginst->type_argc; ++i) {
4031 if (check_type_depth (ginst->type_argv [i], depth + 1))
4045 add_types_from_method_header (MonoAotCompile *acfg, MonoMethod *method);
4048 * add_generic_class:
4050 * Add all methods of a generic class.
4053 add_generic_class_with_depth (MonoAotCompile *acfg, MonoClass *klass, int depth, const char *ref)
4056 MonoClassField *field;
4058 gboolean use_gsharedvt = FALSE;
4060 if (!acfg->ginst_hash)
4061 acfg->ginst_hash = g_hash_table_new (NULL, NULL);
4063 mono_class_init (klass);
4065 if (klass->generic_class && klass->generic_class->context.class_inst->is_open)
4068 if (has_type_vars (klass))
4071 if (!klass->generic_class && !klass->rank)
4074 if (klass->exception_type)
4077 if (!acfg->ginst_hash)
4078 acfg->ginst_hash = g_hash_table_new (NULL, NULL);
4080 if (g_hash_table_lookup (acfg->ginst_hash, klass))
4083 if (check_type_depth (&klass->byval_arg, 0))
4086 if (acfg->aot_opts.log_generics)
4087 aot_printf (acfg, "%*sAdding generic instance %s [%s].\n", depth, "", mono_type_full_name (&klass->byval_arg), ref);
4089 g_hash_table_insert (acfg->ginst_hash, klass, klass);
4092 * Use gsharedvt for generic collections with vtype arguments to avoid code blowup.
4093 * Enable this only for some classes since gsharedvt might not support all methods.
4095 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) &&
4096 (!strcmp (klass->name, "Dictionary`2") || !strcmp (klass->name, "List`1") || !strcmp (klass->name, "ReadOnlyCollection`1")))
4097 use_gsharedvt = TRUE;
4100 while ((method = mono_class_get_methods (klass, &iter))) {
4101 if ((acfg->opts & MONO_OPT_GSHAREDVT) && method->is_inflated && mono_method_get_context (method)->method_inst) {
4103 * This is partial sharing, and we can't handle it yet
4108 if (mono_method_is_generic_sharable_full (method, FALSE, FALSE, use_gsharedvt)) {
4110 add_types_from_method_header (acfg, method);
4114 if (method->is_generic)
4119 * FIXME: Instances which are referenced by these methods are not added,
4120 * for example Array.Resize<int> for List<int>.Add ().
4122 add_extra_method_with_depth (acfg, method, depth + 1);
4126 while ((field = mono_class_get_fields (klass, &iter))) {
4127 if (field->type->type == MONO_TYPE_GENERICINST)
4128 add_generic_class_with_depth (acfg, mono_class_from_mono_type (field->type), depth + 1, "field");
4131 if (klass->delegate) {
4132 method = mono_get_delegate_invoke (klass);
4134 method = mono_marshal_get_delegate_invoke (method, NULL);
4136 if (acfg->aot_opts.log_generics)
4137 aot_printf (acfg, "%*sAdding method %s.\n", depth, "", mono_method_full_name (method, TRUE));
4139 add_method (acfg, method);
4142 /* Add superclasses */
4144 add_generic_class_with_depth (acfg, klass->parent, depth, "parent");
4147 * For ICollection<T>, add instances of the helper methods
4148 * in Array, since a T[] could be cast to ICollection<T>.
4150 if (klass->image == mono_defaults.corlib && !strcmp (klass->name_space, "System.Collections.Generic") &&
4151 (!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"))) {
4152 MonoClass *tclass = mono_class_from_mono_type (klass->generic_class->context.class_inst->type_argv [0]);
4153 MonoClass *array_class = mono_bounded_array_class_get (tclass, 1, FALSE);
4157 if (!strcmp (klass->name, "IEnumerator`1"))
4158 name_prefix = g_strdup_printf ("%s.%s", klass->name_space, "IEnumerable`1");
4160 name_prefix = g_strdup_printf ("%s.%s", klass->name_space, klass->name);
4162 /* Add the T[]/InternalEnumerator class */
4163 if (!strcmp (klass->name, "IEnumerable`1") || !strcmp (klass->name, "IEnumerator`1")) {
4167 while ((nclass = mono_class_get_nested_types (array_class->parent, &iter))) {
4168 if (!strcmp (nclass->name, "InternalEnumerator`1"))
4172 nclass = mono_class_inflate_generic_class (nclass, mono_generic_class_get_context (klass->generic_class));
4173 add_generic_class (acfg, nclass, FALSE, "ICollection<T>");
4177 while ((method = mono_class_get_methods (array_class, &iter))) {
4178 if (strstr (method->name, name_prefix)) {
4179 MonoMethod *m = mono_aot_get_array_helper_from_wrapper (method);
4181 add_extra_method_with_depth (acfg, m, depth);
4185 g_free (name_prefix);
4188 /* Add an instance of GenericComparer<T> which is created dynamically by Comparer<T> */
4189 if (klass->image == mono_defaults.corlib && !strcmp (klass->name_space, "System.Collections.Generic") && !strcmp (klass->name, "Comparer`1")) {
4190 MonoClass *tclass = mono_class_from_mono_type (klass->generic_class->context.class_inst->type_argv [0]);
4191 MonoClass *icomparable, *gcomparer;
4192 MonoGenericContext ctx;
4193 MonoType *args [16];
4195 memset (&ctx, 0, sizeof (ctx));
4197 icomparable = mono_class_from_name (mono_defaults.corlib, "System", "IComparable`1");
4198 g_assert (icomparable);
4199 args [0] = &tclass->byval_arg;
4200 ctx.class_inst = mono_metadata_get_generic_inst (1, args);
4202 if (mono_class_is_assignable_from (mono_class_inflate_generic_class (icomparable, &ctx), tclass)) {
4203 gcomparer = mono_class_from_name (mono_defaults.corlib, "System.Collections.Generic", "GenericComparer`1");
4204 g_assert (gcomparer);
4205 add_generic_class (acfg, mono_class_inflate_generic_class (gcomparer, &ctx), FALSE, "Comparer<T>");
4209 /* Add an instance of GenericEqualityComparer<T> which is created dynamically by EqualityComparer<T> */
4210 if (klass->image == mono_defaults.corlib && !strcmp (klass->name_space, "System.Collections.Generic") && !strcmp (klass->name, "EqualityComparer`1")) {
4211 MonoClass *tclass = mono_class_from_mono_type (klass->generic_class->context.class_inst->type_argv [0]);
4212 MonoClass *iface, *gcomparer;
4213 MonoGenericContext ctx;
4214 MonoType *args [16];
4216 memset (&ctx, 0, sizeof (ctx));
4218 iface = mono_class_from_name (mono_defaults.corlib, "System", "IEquatable`1");
4220 args [0] = &tclass->byval_arg;
4221 ctx.class_inst = mono_metadata_get_generic_inst (1, args);
4223 if (mono_class_is_assignable_from (mono_class_inflate_generic_class (iface, &ctx), tclass)) {
4224 gcomparer = mono_class_from_name (mono_defaults.corlib, "System.Collections.Generic", "GenericEqualityComparer`1");
4225 g_assert (gcomparer);
4226 add_generic_class (acfg, mono_class_inflate_generic_class (gcomparer, &ctx), FALSE, "EqualityComparer<T>");
4230 /* Add an instance of EnumComparer<T> which is created dynamically by EqualityComparer<T> for enums */
4231 if (klass->image == mono_defaults.corlib && !strcmp (klass->name_space, "System.Collections.Generic") && !strcmp (klass->name, "EqualityComparer`1")) {
4232 MonoClass *enum_comparer;
4233 MonoClass *tclass = mono_class_from_mono_type (klass->generic_class->context.class_inst->type_argv [0]);
4234 MonoGenericContext ctx;
4235 MonoType *args [16];
4237 if (mono_class_is_enum (tclass)) {
4238 memset (&ctx, 0, sizeof (ctx));
4239 args [0] = &tclass->byval_arg;
4240 ctx.class_inst = mono_metadata_get_generic_inst (1, args);
4242 enum_comparer = mono_class_from_name (mono_defaults.corlib, "System.Collections.Generic", "EnumEqualityComparer`1");
4243 g_assert (enum_comparer);
4244 add_generic_class (acfg, mono_class_inflate_generic_class (enum_comparer, &ctx), FALSE, "EqualityComparer<T>");
4248 /* Add an instance of ObjectComparer<T> which is created dynamically by Comparer<T> for enums */
4249 if (klass->image == mono_defaults.corlib && !strcmp (klass->name_space, "System.Collections.Generic") && !strcmp (klass->name, "Comparer`1")) {
4250 MonoClass *comparer;
4251 MonoClass *tclass = mono_class_from_mono_type (klass->generic_class->context.class_inst->type_argv [0]);
4252 MonoGenericContext ctx;
4253 MonoType *args [16];
4255 if (mono_class_is_enum (tclass)) {
4256 memset (&ctx, 0, sizeof (ctx));
4257 args [0] = &tclass->byval_arg;
4258 ctx.class_inst = mono_metadata_get_generic_inst (1, args);
4260 comparer = mono_class_from_name (mono_defaults.corlib, "System.Collections.Generic", "ObjectComparer`1");
4261 g_assert (comparer);
4262 add_generic_class (acfg, mono_class_inflate_generic_class (comparer, &ctx), FALSE, "Comparer<T>");
4268 add_instances_of (MonoAotCompile *acfg, MonoClass *klass, MonoType **insts, int ninsts, gboolean force)
4271 MonoGenericContext ctx;
4272 MonoType *args [16];
4274 if (acfg->aot_opts.no_instances)
4277 memset (&ctx, 0, sizeof (ctx));
4279 for (i = 0; i < ninsts; ++i) {
4280 args [0] = insts [i];
4281 ctx.class_inst = mono_metadata_get_generic_inst (1, args);
4282 add_generic_class (acfg, mono_class_inflate_generic_class (klass, &ctx), force, "");
4287 add_types_from_method_header (MonoAotCompile *acfg, MonoMethod *method)
4289 MonoMethodHeader *header;
4290 MonoMethodSignature *sig;
4293 depth = GPOINTER_TO_UINT (g_hash_table_lookup (acfg->method_depth, method));
4295 sig = mono_method_signature (method);
4298 for (j = 0; j < sig->param_count; ++j)
4299 if (sig->params [j]->type == MONO_TYPE_GENERICINST)
4300 add_generic_class_with_depth (acfg, mono_class_from_mono_type (sig->params [j]), depth + 1, "arg");
4303 header = mono_method_get_header (method);
4306 for (j = 0; j < header->num_locals; ++j)
4307 if (header->locals [j]->type == MONO_TYPE_GENERICINST)
4308 add_generic_class_with_depth (acfg, mono_class_from_mono_type (header->locals [j]), depth + 1, "local");
4310 mono_loader_clear_error ();
4315 * add_generic_instances:
4317 * Add instances referenced by the METHODSPEC/TYPESPEC table.
4320 add_generic_instances (MonoAotCompile *acfg)
4325 MonoGenericContext *context;
4327 if (acfg->aot_opts.no_instances)
4330 for (i = 0; i < acfg->image->tables [MONO_TABLE_METHODSPEC].rows; ++i) {
4332 token = MONO_TOKEN_METHOD_SPEC | (i + 1);
4333 method = mono_get_method_checked (acfg->image, token, NULL, NULL, &error);
4336 aot_printerrf (acfg, "Failed to load methodspec 0x%x due to %s.\n", token, mono_error_get_message (&error));
4337 aot_printerrf (acfg, "Run with MONO_LOG_LEVEL=debug for more information.\n");
4338 mono_error_cleanup (&error);
4342 if (method->klass->image != acfg->image)
4345 context = mono_method_get_context (method);
4347 if (context && ((context->class_inst && context->class_inst->is_open)))
4351 * For open methods, create an instantiation which can be passed to the JIT.
4352 * FIXME: Handle class_inst as well.
4354 if (context && context->method_inst && context->method_inst->is_open) {
4356 MonoGenericContext shared_context;
4357 MonoGenericInst *inst;
4358 MonoType **type_argv;
4360 MonoMethod *declaring_method;
4361 gboolean supported = TRUE;
4363 /* Check that the context doesn't contain open constructed types */
4364 if (context->class_inst) {
4365 inst = context->class_inst;
4366 for (i = 0; i < inst->type_argc; ++i) {
4367 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)
4369 if (mono_class_is_open_constructed_type (inst->type_argv [i]))
4373 if (context->method_inst) {
4374 inst = context->method_inst;
4375 for (i = 0; i < inst->type_argc; ++i) {
4376 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)
4378 if (mono_class_is_open_constructed_type (inst->type_argv [i]))
4386 memset (&shared_context, 0, sizeof (MonoGenericContext));
4388 inst = context->class_inst;
4390 type_argv = g_new0 (MonoType*, inst->type_argc);
4391 for (i = 0; i < inst->type_argc; ++i) {
4392 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)
4393 type_argv [i] = &mono_defaults.object_class->byval_arg;
4395 type_argv [i] = inst->type_argv [i];
4398 shared_context.class_inst = mono_metadata_get_generic_inst (inst->type_argc, type_argv);
4402 inst = context->method_inst;
4404 type_argv = g_new0 (MonoType*, inst->type_argc);
4405 for (i = 0; i < inst->type_argc; ++i) {
4406 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)
4407 type_argv [i] = &mono_defaults.object_class->byval_arg;
4409 type_argv [i] = inst->type_argv [i];
4412 shared_context.method_inst = mono_metadata_get_generic_inst (inst->type_argc, type_argv);
4416 if (method->is_generic || method->klass->generic_container)
4417 declaring_method = method;
4419 declaring_method = mono_method_get_declaring_generic_method (method);
4421 method = mono_class_inflate_generic_method_checked (declaring_method, &shared_context, &error);
4422 g_assert (mono_error_ok (&error)); /* FIXME don't swallow the error */
4426 * If the method is fully sharable, it was already added in place of its
4427 * generic definition.
4429 if (mono_method_is_generic_sharable_full (method, FALSE, FALSE, FALSE))
4433 * FIXME: Partially shared methods are not shared here, so we end up with
4434 * many identical methods.
4436 add_extra_method (acfg, method);
4439 for (i = 0; i < acfg->image->tables [MONO_TABLE_TYPESPEC].rows; ++i) {
4443 token = MONO_TOKEN_TYPE_SPEC | (i + 1);
4445 klass = mono_class_get_checked (acfg->image, token, &error);
4446 if (!klass || klass->rank) {
4447 mono_error_cleanup (&error);
4451 add_generic_class (acfg, klass, FALSE, "typespec");
4454 /* Add types of args/locals */
4455 for (i = 0; i < acfg->methods->len; ++i) {
4456 method = (MonoMethod *)g_ptr_array_index (acfg->methods, i);
4457 add_types_from_method_header (acfg, method);
4460 if (acfg->image == mono_defaults.corlib) {
4462 MonoType *insts [256];
4465 insts [ninsts ++] = &mono_defaults.byte_class->byval_arg;
4466 insts [ninsts ++] = &mono_defaults.sbyte_class->byval_arg;
4467 insts [ninsts ++] = &mono_defaults.int16_class->byval_arg;
4468 insts [ninsts ++] = &mono_defaults.uint16_class->byval_arg;
4469 insts [ninsts ++] = &mono_defaults.int32_class->byval_arg;
4470 insts [ninsts ++] = &mono_defaults.uint32_class->byval_arg;
4471 insts [ninsts ++] = &mono_defaults.int64_class->byval_arg;
4472 insts [ninsts ++] = &mono_defaults.uint64_class->byval_arg;
4473 insts [ninsts ++] = &mono_defaults.single_class->byval_arg;
4474 insts [ninsts ++] = &mono_defaults.double_class->byval_arg;
4475 insts [ninsts ++] = &mono_defaults.char_class->byval_arg;
4476 insts [ninsts ++] = &mono_defaults.boolean_class->byval_arg;
4478 /* Add GenericComparer<T> instances for primitive types for Enum.ToString () */
4479 klass = mono_class_from_name (acfg->image, "System.Collections.Generic", "GenericComparer`1");
4481 add_instances_of (acfg, klass, insts, ninsts, TRUE);
4482 klass = mono_class_from_name (acfg->image, "System.Collections.Generic", "GenericEqualityComparer`1");
4484 add_instances_of (acfg, klass, insts, ninsts, TRUE);
4486 /* Add instances of EnumEqualityComparer which are created by EqualityComparer<T> for enums */
4488 MonoClass *enum_comparer;
4489 MonoType *insts [16];
4493 insts [ninsts ++] = &mono_defaults.int32_class->byval_arg;
4494 insts [ninsts ++] = &mono_defaults.uint32_class->byval_arg;
4495 insts [ninsts ++] = &mono_defaults.uint16_class->byval_arg;
4496 insts [ninsts ++] = &mono_defaults.byte_class->byval_arg;
4497 enum_comparer = mono_class_from_name (mono_defaults.corlib, "System.Collections.Generic", "EnumEqualityComparer`1");
4498 g_assert (enum_comparer);
4499 add_instances_of (acfg, enum_comparer, insts, ninsts, FALSE);
4502 insts [ninsts ++] = &mono_defaults.int16_class->byval_arg;
4503 enum_comparer = mono_class_from_name (mono_defaults.corlib, "System.Collections.Generic", "ShortEnumEqualityComparer`1");
4504 g_assert (enum_comparer);
4505 add_instances_of (acfg, enum_comparer, insts, ninsts, FALSE);
4508 insts [ninsts ++] = &mono_defaults.sbyte_class->byval_arg;
4509 enum_comparer = mono_class_from_name (mono_defaults.corlib, "System.Collections.Generic", "SByteEnumEqualityComparer`1");
4510 g_assert (enum_comparer);
4511 add_instances_of (acfg, enum_comparer, insts, ninsts, FALSE);
4513 enum_comparer = mono_class_from_name (mono_defaults.corlib, "System.Collections.Generic", "LongEnumEqualityComparer`1");
4514 g_assert (enum_comparer);
4516 insts [ninsts ++] = &mono_defaults.int64_class->byval_arg;
4517 insts [ninsts ++] = &mono_defaults.uint64_class->byval_arg;
4518 add_instances_of (acfg, enum_comparer, insts, ninsts, FALSE);
4521 /* Add instances of the array generic interfaces for primitive types */
4522 /* This will add instances of the InternalArray_ helper methods in Array too */
4523 klass = mono_class_from_name (acfg->image, "System.Collections.Generic", "ICollection`1");
4525 add_instances_of (acfg, klass, insts, ninsts, TRUE);
4526 klass = mono_class_from_name (acfg->image, "System.Collections.Generic", "IList`1");
4528 add_instances_of (acfg, klass, insts, ninsts, TRUE);
4529 klass = mono_class_from_name (acfg->image, "System.Collections.Generic", "IEnumerable`1");
4531 add_instances_of (acfg, klass, insts, ninsts, TRUE);
4534 * Add a managed-to-native wrapper of Array.GetGenericValueImpl<object>, which is
4535 * used for all instances of GetGenericValueImpl by the AOT runtime.
4538 MonoGenericContext ctx;
4539 MonoType *args [16];
4540 MonoMethod *get_method;
4541 MonoClass *array_klass = mono_array_class_get (mono_defaults.object_class, 1)->parent;
4543 get_method = mono_class_get_method_from_name (array_klass, "GetGenericValueImpl", 2);
4547 memset (&ctx, 0, sizeof (ctx));
4548 args [0] = &mono_defaults.object_class->byval_arg;
4549 ctx.method_inst = mono_metadata_get_generic_inst (1, args);
4550 add_extra_method (acfg, mono_marshal_get_native_wrapper (mono_class_inflate_generic_method_checked (get_method, &ctx, &error), TRUE, TRUE));
4551 g_assert (mono_error_ok (&error)); /* FIXME don't swallow the error */
4555 /* Same for CompareExchange<T>/Exchange<T> */
4557 MonoGenericContext ctx;
4558 MonoType *args [16];
4560 MonoClass *interlocked_klass = mono_class_from_name (mono_defaults.corlib, "System.Threading", "Interlocked");
4561 gpointer iter = NULL;
4563 while ((m = mono_class_get_methods (interlocked_klass, &iter))) {
4564 if ((!strcmp (m->name, "CompareExchange") || !strcmp (m->name, "Exchange")) && m->is_generic) {
4566 memset (&ctx, 0, sizeof (ctx));
4567 args [0] = &mono_defaults.object_class->byval_arg;
4568 ctx.method_inst = mono_metadata_get_generic_inst (1, args);
4569 add_extra_method (acfg, mono_marshal_get_native_wrapper (mono_class_inflate_generic_method_checked (m, &ctx, &error), TRUE, TRUE));
4570 g_assert (mono_error_ok (&error)); /* FIXME don't swallow the error */
4575 /* Same for Volatile.Read/Write<T> */
4577 MonoGenericContext ctx;
4578 MonoType *args [16];
4580 MonoClass *volatile_klass = mono_class_from_name (mono_defaults.corlib, "System.Threading", "Volatile");
4581 gpointer iter = NULL;
4583 if (volatile_klass) {
4584 while ((m = mono_class_get_methods (volatile_klass, &iter))) {
4585 if ((!strcmp (m->name, "Read") || !strcmp (m->name, "Write")) && m->is_generic) {
4587 memset (&ctx, 0, sizeof (ctx));
4588 args [0] = &mono_defaults.object_class->byval_arg;
4589 ctx.method_inst = mono_metadata_get_generic_inst (1, args);
4590 add_extra_method (acfg, mono_marshal_get_native_wrapper (mono_class_inflate_generic_method_checked (m, &ctx, &error), TRUE, TRUE));
4591 g_assert (mono_error_ok (&error)); /* FIXME don't swallow the error */
4597 /* object[] accessor wrappers. */
4599 MonoClass *obj_array_class = mono_array_class_get (mono_defaults.object_class, 1);
4602 m = mono_class_get_method_from_name (obj_array_class, "Get", 1);
4605 m = mono_marshal_get_array_accessor_wrapper (m);
4606 add_extra_method (acfg, m);
4608 m = mono_class_get_method_from_name (obj_array_class, "Address", 1);
4611 m = mono_marshal_get_array_accessor_wrapper (m);
4612 add_extra_method (acfg, m);
4614 m = mono_class_get_method_from_name (obj_array_class, "Set", 2);
4617 m = mono_marshal_get_array_accessor_wrapper (m);
4618 add_extra_method (acfg, m);
4624 * is_direct_callable:
4626 * Return whenever the method identified by JI is directly callable without
4627 * going through the PLT.
4630 is_direct_callable (MonoAotCompile *acfg, MonoMethod *method, MonoJumpInfo *patch_info)
4632 if ((patch_info->type == MONO_PATCH_INFO_METHOD) && (patch_info->data.method->klass->image == acfg->image)) {
4633 MonoCompile *callee_cfg = (MonoCompile *)g_hash_table_lookup (acfg->method_to_cfg, patch_info->data.method);
4635 gboolean direct_callable = TRUE;
4637 if (direct_callable && !(!callee_cfg->has_got_slots && (callee_cfg->method->klass->flags & TYPE_ATTRIBUTE_BEFORE_FIELD_INIT)))
4638 direct_callable = FALSE;
4639 if ((callee_cfg->method->iflags & METHOD_IMPL_ATTRIBUTE_SYNCHRONIZED) && (!method || method->wrapper_type != MONO_WRAPPER_SYNCHRONIZED))
4640 // FIXME: Maybe call the wrapper directly ?
4641 direct_callable = FALSE;
4643 if (acfg->aot_opts.soft_debug || acfg->aot_opts.no_direct_calls) {
4644 /* Disable this so all calls go through load_method (), see the
4645 * mini_get_debug_options ()->load_aot_jit_info_eagerly = TRUE; line in
4646 * mono_debugger_agent_init ().
4648 direct_callable = FALSE;
4651 if (callee_cfg->method->wrapper_type == MONO_WRAPPER_ALLOC)
4652 /* sgen does some initialization when the allocator method is created */
4653 direct_callable = FALSE;
4654 if (callee_cfg->method->wrapper_type == MONO_WRAPPER_WRITE_BARRIER)
4655 /* we don't know at compile time whether sgen is concurrent or not */
4656 direct_callable = FALSE;
4658 if (direct_callable)
4661 } else if ((patch_info->type == MONO_PATCH_INFO_ICALL_ADDR && patch_info->data.method->flags & METHOD_ATTRIBUTE_PINVOKE_IMPL)) {
4662 if (acfg->aot_opts.direct_pinvoke)
4664 } else if (patch_info->type == MONO_PATCH_INFO_ICALL_ADDR) {
4665 if (acfg->aot_opts.direct_icalls)
4673 #ifdef MONO_ARCH_AOT_SUPPORTED
4675 get_pinvoke_import (MonoAotCompile *acfg, MonoMethod *method)
4677 MonoImage *image = method->klass->image;
4678 MonoMethodPInvoke *piinfo = (MonoMethodPInvoke *) method;
4679 MonoTableInfo *tables = image->tables;
4680 MonoTableInfo *im = &tables [MONO_TABLE_IMPLMAP];
4681 MonoTableInfo *mr = &tables [MONO_TABLE_MODULEREF];
4682 guint32 im_cols [MONO_IMPLMAP_SIZE];
4685 import = (char *)g_hash_table_lookup (acfg->method_to_pinvoke_import, method);
4689 if (!piinfo->implmap_idx || piinfo->implmap_idx > im->rows)
4692 mono_metadata_decode_row (im, piinfo->implmap_idx - 1, im_cols, MONO_IMPLMAP_SIZE);
4694 if (!im_cols [MONO_IMPLMAP_SCOPE] || im_cols [MONO_IMPLMAP_SCOPE] > mr->rows)
4697 import = g_strdup_printf ("%s", mono_metadata_string_heap (image, im_cols [MONO_IMPLMAP_NAME]));
4699 g_hash_table_insert (acfg->method_to_pinvoke_import, method, import);
4706 compare_lne (MonoDebugLineNumberEntry *a, MonoDebugLineNumberEntry *b)
4708 if (a->native_offset == b->native_offset)
4709 return a->il_offset - b->il_offset;
4711 return a->native_offset - b->native_offset;
4715 * compute_line_numbers:
4717 * Returns a sparse array of size CODE_SIZE containing MonoDebugSourceLocation* entries for the native offsets which have a corresponding line number
4720 static MonoDebugSourceLocation**
4721 compute_line_numbers (MonoMethod *method, int code_size, MonoDebugMethodJitInfo *debug_info)
4723 MonoDebugMethodInfo *minfo;
4724 MonoDebugLineNumberEntry *ln_array;
4725 MonoDebugSourceLocation *loc;
4726 int i, prev_line, prev_il_offset;
4727 int *native_to_il_offset = NULL;
4728 MonoDebugSourceLocation **res;
4731 minfo = mono_debug_lookup_method (method);
4734 // FIXME: This seems to happen when two methods have the same cfg->method_to_register
4735 if (debug_info->code_size != code_size)
4738 g_assert (code_size);
4740 /* Compute the native->IL offset mapping */
4742 ln_array = g_new0 (MonoDebugLineNumberEntry, debug_info->num_line_numbers);
4743 memcpy (ln_array, debug_info->line_numbers, debug_info->num_line_numbers * sizeof (MonoDebugLineNumberEntry));
4745 qsort (ln_array, debug_info->num_line_numbers, sizeof (MonoDebugLineNumberEntry), (int (*)(const void *, const void *))compare_lne);
4747 native_to_il_offset = g_new0 (int, code_size + 1);
4749 for (i = 0; i < debug_info->num_line_numbers; ++i) {
4751 MonoDebugLineNumberEntry *lne = &ln_array [i];
4754 for (j = 0; j < lne->native_offset; ++j)
4755 native_to_il_offset [j] = -1;
4758 if (i < debug_info->num_line_numbers - 1) {
4759 MonoDebugLineNumberEntry *lne_next = &ln_array [i + 1];
4761 for (j = lne->native_offset; j < lne_next->native_offset; ++j)
4762 native_to_il_offset [j] = lne->il_offset;
4764 for (j = lne->native_offset; j < code_size; ++j)
4765 native_to_il_offset [j] = lne->il_offset;
4770 /* Compute the native->line number mapping */
4771 res = g_new0 (MonoDebugSourceLocation*, code_size);
4772 prev_il_offset = -1;
4775 for (i = 0; i < code_size; ++i) {
4776 int il_offset = native_to_il_offset [i];
4778 if (il_offset == -1 || il_offset == prev_il_offset)
4780 prev_il_offset = il_offset;
4781 loc = mono_debug_symfile_lookup_location (minfo, il_offset);
4782 if (!(loc && loc->source_file))
4784 if (loc->row == prev_line) {
4785 mono_debug_symfile_free_location (loc);
4788 prev_line = loc->row;
4789 //printf ("D: %s:%d il=%x native=%x\n", loc->source_file, loc->row, il_offset, i);
4791 /* This will cover the prolog too */
4801 get_file_index (MonoAotCompile *acfg, const char *source_file)
4805 // FIXME: Free these
4806 if (!acfg->dwarf_ln_filenames)
4807 acfg->dwarf_ln_filenames = g_hash_table_new (g_str_hash, g_str_equal);
4808 findex = GPOINTER_TO_INT (g_hash_table_lookup (acfg->dwarf_ln_filenames, source_file));
4810 findex = g_hash_table_size (acfg->dwarf_ln_filenames) + 1;
4811 g_hash_table_insert (acfg->dwarf_ln_filenames, g_strdup (source_file), GINT_TO_POINTER (findex));
4812 emit_unset_mode (acfg);
4813 fprintf (acfg->fp, ".file %d \"%s\"\n", findex, mono_dwarf_escape_path (source_file));
4825 * emit_and_reloc_code:
4827 * Emit the native code in CODE, handling relocations along the way. If GOT_ONLY
4828 * is true, calls are made through the GOT too. This is used for emitting trampolines
4829 * in full-aot mode, since calls made from trampolines couldn't go through the PLT,
4830 * since trampolines are needed to make PTL work.
4833 emit_and_reloc_code (MonoAotCompile *acfg, MonoMethod *method, guint8 *code, guint32 code_len, MonoJumpInfo *relocs, gboolean got_only, MonoDebugMethodJitInfo *debug_info)
4835 int i, pindex, start_index;
4837 MonoJumpInfo *patch_info;
4838 MonoDebugSourceLocation **locs = NULL;
4840 #ifdef MONO_ARCH_AOT_SUPPORTED
4841 gboolean direct_call, external_call;
4843 const char *direct_call_target = 0;
4844 const char *direct_pinvoke;
4847 if (acfg->gas_line_numbers && method && debug_info) {
4848 locs = compute_line_numbers (method, code_len, debug_info);
4850 int findex = get_file_index (acfg, "<unknown>");
4851 emit_unset_mode (acfg);
4852 fprintf (acfg->fp, ".loc %d %d 0\n", findex, 1);
4856 /* Collect and sort relocations */
4857 patches = g_ptr_array_new ();
4858 for (patch_info = relocs; patch_info; patch_info = patch_info->next)
4859 g_ptr_array_add (patches, patch_info);
4860 g_ptr_array_sort (patches, compare_patches);
4863 for (i = 0; i < code_len; i += INST_LEN) {
4865 for (pindex = start_index; pindex < patches->len; ++pindex) {
4866 patch_info = (MonoJumpInfo *)g_ptr_array_index (patches, pindex);
4867 if (patch_info->ip.i >= i)
4871 if (locs && locs [i]) {
4872 MonoDebugSourceLocation *loc = locs [i];
4875 findex = get_file_index (acfg, loc->source_file);
4876 emit_unset_mode (acfg);
4877 fprintf (acfg->fp, ".loc %d %d 0\n", findex, loc->row);
4878 mono_debug_symfile_free_location (loc);
4882 #ifdef MONO_ARCH_AOT_SUPPORTED
4883 if (patch_info && (patch_info->ip.i == i) && (pindex < patches->len)) {
4884 start_index = pindex;
4886 switch (patch_info->type) {
4887 case MONO_PATCH_INFO_NONE:
4889 case MONO_PATCH_INFO_GOT_OFFSET: {
4892 arch_emit_got_offset (acfg, code + i, &code_size);
4893 i += code_size - INST_LEN;
4895 patch_info->type = MONO_PATCH_INFO_NONE;
4898 case MONO_PATCH_INFO_OBJC_SELECTOR_REF: {
4899 int code_size, index;
4900 char *selector = (char *)patch_info->data.target;
4902 if (!acfg->objc_selector_to_index)
4903 acfg->objc_selector_to_index = g_hash_table_new (g_str_hash, g_str_equal);
4904 if (!acfg->objc_selectors)
4905 acfg->objc_selectors = g_ptr_array_new ();
4906 index = GPOINTER_TO_UINT (g_hash_table_lookup (acfg->objc_selector_to_index, selector));
4910 index = acfg->objc_selector_index;
4911 g_ptr_array_add (acfg->objc_selectors, (void*)patch_info->data.target);
4912 g_hash_table_insert (acfg->objc_selector_to_index, selector, GUINT_TO_POINTER (index + 1));
4913 acfg->objc_selector_index ++;
4916 arch_emit_objc_selector_ref (acfg, code + i, index, &code_size);
4917 i += code_size - INST_LEN;
4919 patch_info->type = MONO_PATCH_INFO_NONE;
4924 * If this patch is a call, try emitting a direct call instead of
4925 * through a PLT entry. This is possible if the called method is in
4926 * the same assembly and requires no initialization.
4928 direct_call = FALSE;
4929 external_call = FALSE;
4930 if ((patch_info->type == MONO_PATCH_INFO_METHOD) && (patch_info->data.method->klass->image == acfg->image)) {
4931 if (!got_only && is_direct_callable (acfg, method, patch_info)) {
4932 MonoCompile *callee_cfg = (MonoCompile *)g_hash_table_lookup (acfg->method_to_cfg, patch_info->data.method);
4933 //printf ("DIRECT: %s %s\n", method ? mono_method_full_name (method, TRUE) : "", mono_method_full_name (callee_cfg->method, TRUE));
4935 direct_call_target = callee_cfg->asm_symbol;
4936 patch_info->type = MONO_PATCH_INFO_NONE;
4937 acfg->stats.direct_calls ++;
4940 acfg->stats.all_calls ++;
4941 } else if (patch_info->type == MONO_PATCH_INFO_ICALL_ADDR) {
4942 if (!got_only && is_direct_callable (acfg, method, patch_info)) {
4943 if (!(patch_info->data.method->flags & METHOD_ATTRIBUTE_PINVOKE_IMPL))
4944 direct_pinvoke = mono_lookup_icall_symbol (patch_info->data.method);
4946 direct_pinvoke = get_pinvoke_import (acfg, patch_info->data.method);
4947 if (direct_pinvoke) {
4949 g_assert (strlen (direct_pinvoke) < 1000);
4950 direct_call_target = g_strdup_printf ("%s%s", acfg->user_symbol_prefix, direct_pinvoke);
4953 } else if (patch_info->type == MONO_PATCH_INFO_JIT_ICALL_ADDR) {
4954 const char *sym = mono_lookup_jit_icall_symbol (patch_info->data.name);
4955 if (!got_only && sym && acfg->aot_opts.direct_icalls) {
4956 /* Call to a C function implementing a jit icall */
4958 external_call = TRUE;
4959 g_assert (strlen (sym) < 1000);
4960 direct_call_target = g_strdup_printf ("%s%s", acfg->user_symbol_prefix, sym);
4962 } else if (patch_info->type == MONO_PATCH_INFO_INTERNAL_METHOD) {
4963 MonoJitICallInfo *info = mono_find_jit_icall_by_name (patch_info->data.name);
4964 const char *sym = mono_lookup_jit_icall_symbol (patch_info->data.name);
4965 if (!got_only && sym && acfg->aot_opts.direct_icalls && info->func == info->wrapper) {
4966 /* Call to a jit icall without a wrapper */
4968 external_call = TRUE;
4969 g_assert (strlen (sym) < 1000);
4970 direct_call_target = g_strdup_printf ("%s%s", acfg->user_symbol_prefix, sym);
4975 patch_info->type = MONO_PATCH_INFO_NONE;
4976 acfg->stats.direct_calls ++;
4979 if (!got_only && !direct_call) {
4980 MonoPltEntry *plt_entry = get_plt_entry (acfg, patch_info);
4982 /* This patch has a PLT entry, so we must emit a call to the PLT entry */
4984 direct_call_target = plt_entry->symbol;
4986 /* Nullify the patch */
4987 patch_info->type = MONO_PATCH_INFO_NONE;
4988 plt_entry->jit_used = TRUE;
4995 arch_emit_direct_call (acfg, direct_call_target, external_call, FALSE, patch_info, &call_size);
4996 i += call_size - INST_LEN;
5000 got_slot = get_got_offset (acfg, FALSE, patch_info);
5002 arch_emit_got_access (acfg, acfg->got_symbol, code + i, got_slot, &code_size);
5003 i += code_size - INST_LEN;
5009 #endif /* MONO_ARCH_AOT_SUPPORTED */
5012 /* Find next patch */
5014 for (pindex = start_index; pindex < patches->len; ++pindex) {
5015 patch_info = (MonoJumpInfo *)g_ptr_array_index (patches, pindex);
5016 if (patch_info->ip.i >= i)
5020 /* Try to emit multiple bytes at once */
5021 if (pindex < patches->len && patch_info->ip.i > i) {
5024 for (limit = i + INST_LEN; limit < patch_info->ip.i; limit += INST_LEN) {
5025 if (locs && locs [limit])
5029 emit_code_bytes (acfg, code + i, limit - i);
5030 i = limit - INST_LEN;
5032 emit_code_bytes (acfg, code + i, INST_LEN);
5043 * Return a modified version of S which only includes characters permissible in symbols.
5046 sanitize_symbol (MonoAotCompile *acfg, char *s)
5048 gboolean process = FALSE;
5057 for (i = 0; i < len; ++i)
5058 if (!(s [i] <= 0x7f && (isalnum (s [i]) || s [i] == '_')))
5063 gs = g_string_sized_new (len);
5064 for (i = 0; i < len; ++i) {
5066 if (c <= 0x7f && (isalnum (c) || c == '_')) {
5067 g_string_append_c (gs, c);
5068 } else if (c > 0x7f) {
5069 /* multi-byte utf8 */
5070 g_string_append_printf (gs, "_0x%x", c);
5073 while (c >> 6 == 0x2) {
5074 g_string_append_printf (gs, "%x", c);
5078 g_string_append_printf (gs, "_");
5081 g_string_append_c (gs, '_');
5085 res = mono_mempool_strdup (acfg->mempool, gs->str);
5086 g_string_free (gs, TRUE);
5091 get_debug_sym (MonoMethod *method, const char *prefix, GHashTable *cache)
5093 char *name1, *name2, *cached;
5094 int i, j, len, count;
5095 MonoMethod *cached_method;
5097 name1 = mono_method_full_name (method, TRUE);
5100 // This is so that we don't accidentally create a local symbol (which starts with 'L')
5101 if ((!prefix || !*prefix) && name1 [0] == 'L')
5105 len = strlen (name1);
5106 name2 = (char *)malloc (strlen (prefix) + len + 16);
5107 memcpy (name2, prefix, strlen (prefix));
5108 j = strlen (prefix);
5109 for (i = 0; i < len; ++i) {
5110 if (i == 0 && name1 [0] >= '0' && name1 [0] <= '9') {
5112 } else if (isalnum (name1 [i])) {
5113 name2 [j ++] = name1 [i];
5114 } else if (name1 [i] == ' ' && name1 [i + 1] == '(' && name1 [i + 2] == ')') {
5116 } else if (name1 [i] == ',' && name1 [i + 1] == ' ') {
5119 } else if (name1 [i] == '(' || name1 [i] == ')' || name1 [i] == '>') {
5129 cached_method = (MonoMethod *)g_hash_table_lookup (cache, name2);
5130 if (!(cached_method && cached_method != method))
5132 sprintf (name2 + j, "_%d", count);
5136 cached = g_strdup (name2);
5137 g_hash_table_insert (cache, cached, method);
5143 emit_method_code (MonoAotCompile *acfg, MonoCompile *cfg)
5148 char *debug_sym = NULL;
5149 char *symbol = NULL;
5150 int func_alignment = AOT_FUNC_ALIGNMENT;
5153 method = cfg->orig_method;
5154 code = cfg->native_code;
5156 method_index = get_method_index (acfg, method);
5157 symbol = g_strdup_printf ("%sme_%x", acfg->temp_prefix, method_index);
5159 /* Make the labels local */
5160 emit_section_change (acfg, ".text", 0);
5161 emit_alignment_code (acfg, func_alignment);
5163 if (acfg->global_symbols && acfg->need_no_dead_strip)
5164 fprintf (acfg->fp, " .no_dead_strip %s\n", cfg->asm_symbol);
5166 emit_label (acfg, cfg->asm_symbol);
5168 if (acfg->aot_opts.write_symbols && !acfg->global_symbols && !acfg->llvm) {
5170 * Write a C style symbol for every method, this has two uses:
5171 * - it works on platforms where the dwarf debugging info is not
5173 * - it allows the setting of breakpoints of aot-ed methods.
5175 debug_sym = get_debug_sym (method, "", acfg->method_label_hash);
5176 cfg->asm_debug_symbol = g_strdup (debug_sym);
5178 if (acfg->need_no_dead_strip)
5179 fprintf (acfg->fp, " .no_dead_strip %s\n", debug_sym);
5180 emit_local_symbol (acfg, debug_sym, symbol, TRUE);
5181 emit_label (acfg, debug_sym);
5184 export_name = (char *)g_hash_table_lookup (acfg->export_names, method);
5186 /* Emit a global symbol for the method */
5187 emit_global_inner (acfg, export_name, TRUE);
5188 emit_label (acfg, export_name);
5191 if (cfg->verbose_level > 0)
5192 g_print ("Method %s emitted as %s\n", mono_method_full_name (method, TRUE), cfg->asm_symbol);
5194 acfg->stats.code_size += cfg->code_len;
5196 acfg->cfgs [method_index]->got_offset = acfg->got_offset;
5198 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 ()));
5202 if (acfg->aot_opts.write_symbols) {
5204 emit_symbol_size (acfg, debug_sym, ".");
5206 emit_symbol_size (acfg, cfg->asm_symbol, ".");
5210 emit_label (acfg, symbol);
5217 * Encode PATCH_INFO into its disk representation.
5220 encode_patch (MonoAotCompile *acfg, MonoJumpInfo *patch_info, guint8 *buf, guint8 **endbuf)
5224 switch (patch_info->type) {
5225 case MONO_PATCH_INFO_NONE:
5227 case MONO_PATCH_INFO_IMAGE:
5228 encode_value (get_image_index (acfg, patch_info->data.image), p, &p);
5230 case MONO_PATCH_INFO_MSCORLIB_GOT_ADDR:
5231 case MONO_PATCH_INFO_JIT_TLS_ID:
5232 case MONO_PATCH_INFO_GC_CARD_TABLE_ADDR:
5233 case MONO_PATCH_INFO_GC_NURSERY_START:
5234 case MONO_PATCH_INFO_GC_NURSERY_BITS:
5236 case MONO_PATCH_INFO_CASTCLASS_CACHE:
5237 encode_value (patch_info->data.index, p, &p);
5239 case MONO_PATCH_INFO_METHOD_REL:
5240 encode_value ((gint)patch_info->data.offset, p, &p);
5242 case MONO_PATCH_INFO_SWITCH: {
5243 gpointer *table = (gpointer *)patch_info->data.table->table;
5246 encode_value (patch_info->data.table->table_size, p, &p);
5247 for (k = 0; k < patch_info->data.table->table_size; k++)
5248 encode_value ((int)(gssize)table [k], p, &p);
5251 case MONO_PATCH_INFO_METHODCONST:
5252 case MONO_PATCH_INFO_METHOD:
5253 case MONO_PATCH_INFO_METHOD_JUMP:
5254 case MONO_PATCH_INFO_ICALL_ADDR:
5255 case MONO_PATCH_INFO_METHOD_RGCTX:
5256 case MONO_PATCH_INFO_METHOD_CODE_SLOT:
5257 encode_method_ref (acfg, patch_info->data.method, p, &p);
5259 case MONO_PATCH_INFO_AOT_JIT_INFO:
5260 encode_value (patch_info->data.index, p, &p);
5262 case MONO_PATCH_INFO_INTERNAL_METHOD:
5263 case MONO_PATCH_INFO_JIT_ICALL_ADDR: {
5264 guint32 len = strlen (patch_info->data.name);
5266 encode_value (len, p, &p);
5268 memcpy (p, patch_info->data.name, len);
5273 case MONO_PATCH_INFO_LDSTR: {
5274 guint32 image_index = get_image_index (acfg, patch_info->data.token->image);
5275 guint32 token = patch_info->data.token->token;
5276 g_assert (mono_metadata_token_code (token) == MONO_TOKEN_STRING);
5277 encode_value (image_index, p, &p);
5278 encode_value (patch_info->data.token->token - MONO_TOKEN_STRING, p, &p);
5281 case MONO_PATCH_INFO_RVA:
5282 case MONO_PATCH_INFO_DECLSEC:
5283 case MONO_PATCH_INFO_LDTOKEN:
5284 case MONO_PATCH_INFO_TYPE_FROM_HANDLE:
5285 encode_value (get_image_index (acfg, patch_info->data.token->image), p, &p);
5286 encode_value (patch_info->data.token->token, p, &p);
5287 encode_value (patch_info->data.token->has_context, p, &p);
5288 if (patch_info->data.token->has_context)
5289 encode_generic_context (acfg, &patch_info->data.token->context, p, &p);
5291 case MONO_PATCH_INFO_EXC_NAME: {
5292 MonoClass *ex_class;
5295 mono_class_from_name (mono_defaults.exception_class->image,
5296 "System", (const char *)patch_info->data.target);
5297 g_assert (ex_class);
5298 encode_klass_ref (acfg, ex_class, p, &p);
5301 case MONO_PATCH_INFO_R4:
5302 encode_value (*((guint32 *)patch_info->data.target), p, &p);
5304 case MONO_PATCH_INFO_R8:
5305 encode_value (((guint32 *)patch_info->data.target) [MINI_LS_WORD_IDX], p, &p);
5306 encode_value (((guint32 *)patch_info->data.target) [MINI_MS_WORD_IDX], p, &p);
5308 case MONO_PATCH_INFO_VTABLE:
5309 case MONO_PATCH_INFO_CLASS:
5310 case MONO_PATCH_INFO_IID:
5311 case MONO_PATCH_INFO_ADJUSTED_IID:
5312 encode_klass_ref (acfg, patch_info->data.klass, p, &p);
5314 case MONO_PATCH_INFO_DELEGATE_TRAMPOLINE:
5315 encode_klass_ref (acfg, patch_info->data.del_tramp->klass, p, &p);
5316 if (patch_info->data.del_tramp->method) {
5317 encode_value (1, p, &p);
5318 encode_method_ref (acfg, patch_info->data.del_tramp->method, p, &p);
5320 encode_value (0, p, &p);
5322 encode_value (patch_info->data.del_tramp->is_virtual, p, &p);
5324 case MONO_PATCH_INFO_FIELD:
5325 case MONO_PATCH_INFO_SFLDA:
5326 encode_field_info (acfg, patch_info->data.field, p, &p);
5328 case MONO_PATCH_INFO_INTERRUPTION_REQUEST_FLAG:
5330 case MONO_PATCH_INFO_RGCTX_FETCH:
5331 case MONO_PATCH_INFO_RGCTX_SLOT_INDEX: {
5332 MonoJumpInfoRgctxEntry *entry = patch_info->data.rgctx_entry;
5337 * entry->method has a lenghtly encoding and multiple rgctx_fetch entries
5338 * reference the same method, so encode the method only once.
5340 offset = GPOINTER_TO_UINT (g_hash_table_lookup (acfg->method_blob_hash, entry->method));
5342 buf2 = (guint8 *)g_malloc (1024);
5345 encode_method_ref (acfg, entry->method, p2, &p2);
5346 g_assert (p2 - buf2 < 1024);
5348 offset = add_to_blob (acfg, buf2, p2 - buf2);
5351 g_hash_table_insert (acfg->method_blob_hash, entry->method, GUINT_TO_POINTER (offset + 1));
5356 encode_value (offset, p, &p);
5357 g_assert ((int)entry->info_type < 256);
5358 g_assert (entry->data->type < 256);
5359 encode_value ((entry->in_mrgctx ? 1 : 0) | (entry->info_type << 1) | (entry->data->type << 9), p, &p);
5360 encode_patch (acfg, entry->data, p, &p);
5363 case MONO_PATCH_INFO_SEQ_POINT_INFO:
5364 case MONO_PATCH_INFO_AOT_MODULE:
5366 case MONO_PATCH_INFO_SIGNATURE:
5367 encode_signature (acfg, (MonoMethodSignature*)patch_info->data.target, p, &p);
5369 case MONO_PATCH_INFO_TLS_OFFSET:
5370 encode_value (GPOINTER_TO_INT (patch_info->data.target), p, &p);
5372 case MONO_PATCH_INFO_GSHAREDVT_CALL:
5373 encode_signature (acfg, (MonoMethodSignature*)patch_info->data.gsharedvt->sig, p, &p);
5374 encode_method_ref (acfg, patch_info->data.gsharedvt->method, p, &p);
5376 case MONO_PATCH_INFO_GSHAREDVT_METHOD: {
5377 MonoGSharedVtMethodInfo *info = patch_info->data.gsharedvt_method;
5380 encode_method_ref (acfg, info->method, p, &p);
5381 encode_value (info->num_entries, p, &p);
5382 for (i = 0; i < info->num_entries; ++i) {
5383 MonoRuntimeGenericContextInfoTemplate *template_ = &info->entries [i];
5385 encode_value (template_->info_type, p, &p);
5386 switch (mini_rgctx_info_type_to_patch_info_type (template_->info_type)) {
5387 case MONO_PATCH_INFO_CLASS:
5388 encode_klass_ref (acfg, mono_class_from_mono_type ((MonoType *)template_->data), p, &p);
5390 case MONO_PATCH_INFO_FIELD:
5391 encode_field_info (acfg, (MonoClassField *)template_->data, p, &p);
5394 g_assert_not_reached ();
5400 case MONO_PATCH_INFO_LDSTR_LIT: {
5401 const char *s = (const char *)patch_info->data.target;
5402 int len = strlen (s);
5404 encode_value (len, p, &p);
5405 memcpy (p, s, len + 1);
5409 case MONO_PATCH_INFO_VIRT_METHOD:
5410 encode_klass_ref (acfg, patch_info->data.virt_method->klass, p, &p);
5411 encode_method_ref (acfg, patch_info->data.virt_method->method, p, &p);
5413 case MONO_PATCH_INFO_GC_SAFE_POINT_FLAG:
5416 g_warning ("unable to handle jump info %d", patch_info->type);
5417 g_assert_not_reached ();
5424 encode_patch_list (MonoAotCompile *acfg, GPtrArray *patches, int n_patches, gboolean llvm, int first_got_offset, guint8 *buf, guint8 **endbuf)
5427 guint32 pindex, offset;
5428 MonoJumpInfo *patch_info;
5430 encode_value (n_patches, p, &p);
5432 for (pindex = 0; pindex < patches->len; ++pindex) {
5433 patch_info = (MonoJumpInfo *)g_ptr_array_index (patches, pindex);
5435 if (patch_info->type == MONO_PATCH_INFO_NONE || patch_info->type == MONO_PATCH_INFO_BB)
5439 offset = get_got_offset (acfg, llvm, patch_info);
5440 encode_value (offset, p, &p);
5447 emit_method_info (MonoAotCompile *acfg, MonoCompile *cfg)
5450 int pindex, buf_size, n_patches;
5452 MonoJumpInfo *patch_info;
5453 guint32 method_index;
5455 guint32 first_got_offset;
5457 method = cfg->orig_method;
5459 method_index = get_method_index (acfg, method);
5461 /* Sort relocations */
5462 patches = g_ptr_array_new ();
5463 for (patch_info = cfg->patch_info; patch_info; patch_info = patch_info->next)
5464 g_ptr_array_add (patches, patch_info);
5465 g_ptr_array_sort (patches, compare_patches);
5467 first_got_offset = acfg->cfgs [method_index]->got_offset;
5469 /**********************/
5470 /* Encode method info */
5471 /**********************/
5473 buf_size = (patches->len < 1000) ? 40960 : 40960 + (patches->len * 64);
5474 p = buf = (guint8 *)g_malloc (buf_size);
5476 if (mono_class_get_cctor (method->klass))
5477 encode_klass_ref (acfg, method->klass, p, &p);
5479 /* Not needed when loading the method */
5480 encode_value (0, p, &p);
5482 g_assert (!(cfg->opt & MONO_OPT_SHARED));
5485 for (pindex = 0; pindex < patches->len; ++pindex) {
5486 patch_info = (MonoJumpInfo *)g_ptr_array_index (patches, pindex);
5488 if ((patch_info->type == MONO_PATCH_INFO_GOT_OFFSET) ||
5489 (patch_info->type == MONO_PATCH_INFO_NONE)) {
5490 patch_info->type = MONO_PATCH_INFO_NONE;
5495 if ((patch_info->type == MONO_PATCH_INFO_IMAGE) && (patch_info->data.image == acfg->image)) {
5496 /* Stored in a GOT slot initialized at module load time */
5497 patch_info->type = MONO_PATCH_INFO_NONE;
5501 if (patch_info->type == MONO_PATCH_INFO_GC_CARD_TABLE_ADDR ||
5502 patch_info->type == MONO_PATCH_INFO_GC_NURSERY_START ||
5503 patch_info->type == MONO_PATCH_INFO_GC_NURSERY_BITS ||
5504 patch_info->type == MONO_PATCH_INFO_AOT_MODULE) {
5505 /* Stored in a GOT slot initialized at module load time */
5506 patch_info->type = MONO_PATCH_INFO_NONE;
5510 if (is_plt_patch (patch_info) && !(cfg->compile_llvm && acfg->aot_opts.llvm_only)) {
5511 /* Calls are made through the PLT */
5512 patch_info->type = MONO_PATCH_INFO_NONE;
5520 g_assert (cfg->has_got_slots);
5522 encode_patch_list (acfg, patches, n_patches, cfg->compile_llvm, first_got_offset, p, &p);
5524 acfg->stats.info_size += p - buf;
5526 g_assert (p - buf < buf_size);
5528 cfg->method_info_offset = add_to_blob (acfg, buf, p - buf);
5533 get_unwind_info_offset (MonoAotCompile *acfg, guint8 *encoded, guint32 encoded_len)
5535 guint32 cache_index;
5538 /* Reuse the unwind module to canonize and store unwind info entries */
5539 cache_index = mono_cache_unwind_info (encoded, encoded_len);
5541 /* Use +/- 1 to distinguish 0s from missing entries */
5542 offset = GPOINTER_TO_UINT (g_hash_table_lookup (acfg->unwind_info_offsets, GUINT_TO_POINTER (cache_index + 1)));
5550 * It would be easier to use assembler symbols, but the caller needs an
5553 offset = acfg->unwind_info_offset;
5554 g_hash_table_insert (acfg->unwind_info_offsets, GUINT_TO_POINTER (cache_index + 1), GUINT_TO_POINTER (offset + 1));
5555 g_ptr_array_add (acfg->unwind_ops, GUINT_TO_POINTER (cache_index));
5558 encode_value (encoded_len, p, &p);
5560 acfg->unwind_info_offset += encoded_len + (p - buf);
5566 emit_exception_debug_info (MonoAotCompile *acfg, MonoCompile *cfg, gboolean store_seq_points)
5569 guint32 debug_info_size, seq_points_size;
5571 MonoMethodHeader *header;
5572 guint8 *p, *buf, *debug_info;
5573 MonoJitInfo *jinfo = cfg->jit_info;
5575 gboolean use_unwind_ops = FALSE;
5576 MonoSeqPointInfo *seq_points;
5578 code = cfg->native_code;
5579 header = cfg->header;
5581 if (!acfg->aot_opts.nodebug) {
5582 mono_debug_serialize_debug_info (cfg, &debug_info, &debug_info_size);
5585 debug_info_size = 0;
5588 seq_points = cfg->seq_point_info;
5589 seq_points_size = (store_seq_points)? mono_seq_point_info_get_write_size (seq_points) : 0;
5591 buf_size = header->num_clauses * 256 + debug_info_size + 2048 + seq_points_size + cfg->gc_map_size;
5593 p = buf = (guint8 *)g_malloc (buf_size);
5595 use_unwind_ops = cfg->unwind_ops != NULL;
5597 flags = (jinfo->has_generic_jit_info ? 1 : 0) | (use_unwind_ops ? 2 : 0) | (header->num_clauses ? 4 : 0) | (seq_points_size ? 8 : 0) | (cfg->compile_llvm ? 16 : 0) | (jinfo->has_try_block_holes ? 32 : 0) | (cfg->gc_map ? 64 : 0) | (jinfo->has_arch_eh_info ? 128 : 0);
5599 encode_value (flags, p, &p);
5601 if (use_unwind_ops) {
5602 guint32 encoded_len;
5604 guint32 unwind_desc;
5606 encoded = mono_unwind_ops_encode (cfg->unwind_ops, &encoded_len);
5608 unwind_desc = get_unwind_info_offset (acfg, encoded, encoded_len);
5609 encode_value (unwind_desc, p, &p);
5611 encode_value (jinfo->unwind_info, p, &p);
5614 /*Encode the number of holes before the number of clauses to make decoding easier*/
5615 if (jinfo->has_try_block_holes) {
5616 MonoTryBlockHoleTableJitInfo *table = mono_jit_info_get_try_block_hole_table_info (jinfo);
5617 encode_value (table->num_holes, p, &p);
5620 if (jinfo->has_arch_eh_info) {
5622 * In AOT mode, the code length is calculated from the address of the previous method,
5623 * which could include alignment padding, so calculating the start of the epilog as
5624 * code_len - epilog_size is correct any more. Save the real code len as a workaround.
5626 encode_value (jinfo->code_size, p, &p);
5629 /* Exception table */
5630 if (cfg->compile_llvm) {
5632 * When using LLVM, we can't emit some data, like pc offsets, this reg/offset etc.,
5633 * since the information is only available to llc. Instead, we let llc save the data
5634 * into the LSDA, and read it from there at runtime.
5636 /* The assembly might be CIL stripped so emit the data ourselves */
5637 if (header->num_clauses)
5638 encode_value (header->num_clauses, p, &p);
5640 for (k = 0; k < header->num_clauses; ++k) {
5641 MonoExceptionClause *clause;
5643 clause = &header->clauses [k];
5645 encode_value (clause->flags, p, &p);
5646 if (clause->data.catch_class) {
5647 encode_value (1, p, &p);
5648 encode_klass_ref (acfg, clause->data.catch_class, p, &p);
5650 encode_value (0, p, &p);
5653 /* Emit the IL ranges too, since they might not be available at runtime */
5654 encode_value (clause->try_offset, p, &p);
5655 encode_value (clause->try_len, p, &p);
5656 encode_value (clause->handler_offset, p, &p);
5657 encode_value (clause->handler_len, p, &p);
5659 /* Emit a list of nesting clauses */
5660 for (i = 0; i < header->num_clauses; ++i) {
5662 MonoExceptionClause *clause1 = &header->clauses [cindex1];
5664 MonoExceptionClause *clause2 = &header->clauses [cindex2];
5666 if (cindex1 != cindex2 && clause1->try_offset >= clause2->try_offset && clause1->handler_offset <= clause2->handler_offset)
5667 encode_value (i, p, &p);
5669 encode_value (-1, p, &p);
5672 if (jinfo->num_clauses)
5673 encode_value (jinfo->num_clauses, p, &p);
5675 for (k = 0; k < jinfo->num_clauses; ++k) {
5676 MonoJitExceptionInfo *ei = &jinfo->clauses [k];
5678 encode_value (ei->flags, p, &p);
5679 #ifdef MONO_CONTEXT_SET_LLVM_EXC_REG
5680 /* Not used for catch clauses */
5681 if (ei->flags != MONO_EXCEPTION_CLAUSE_NONE)
5682 encode_value (ei->exvar_offset, p, &p);
5684 encode_value (ei->exvar_offset, p, &p);
5687 if (ei->flags == MONO_EXCEPTION_CLAUSE_FILTER || ei->flags == MONO_EXCEPTION_CLAUSE_FINALLY)
5688 encode_value ((gint)((guint8*)ei->data.filter - code), p, &p);
5690 if (ei->data.catch_class) {
5694 buf2 = (guint8 *)g_malloc (4096);
5696 encode_klass_ref (acfg, ei->data.catch_class, p2, &p2);
5698 g_assert (len < 4096);
5699 encode_value (len, p, &p);
5700 memcpy (p, buf2, len);
5704 encode_value (0, p, &p);
5708 encode_value ((gint)((guint8*)ei->try_start - code), p, &p);
5709 encode_value ((gint)((guint8*)ei->try_end - code), p, &p);
5710 encode_value ((gint)((guint8*)ei->handler_start - code), p, &p);
5714 if (jinfo->has_try_block_holes) {
5715 MonoTryBlockHoleTableJitInfo *table = mono_jit_info_get_try_block_hole_table_info (jinfo);
5716 for (i = 0; i < table->num_holes; ++i) {
5717 MonoTryBlockHoleJitInfo *hole = &table->holes [i];
5718 encode_value (hole->clause, p, &p);
5719 encode_value (hole->length, p, &p);
5720 encode_value (hole->offset, p, &p);
5724 if (jinfo->has_arch_eh_info) {
5725 MonoArchEHJitInfo *eh_info;
5727 eh_info = mono_jit_info_get_arch_eh_info (jinfo);
5728 encode_value (eh_info->stack_size, p, &p);
5729 encode_value (eh_info->epilog_size, p, &p);
5732 if (jinfo->has_generic_jit_info) {
5733 MonoGenericJitInfo *gi = mono_jit_info_get_generic_jit_info (jinfo);
5734 MonoGenericSharingContext* gsctx = gi->generic_sharing_context;
5738 encode_value (gi->nlocs, p, &p);
5740 for (i = 0; i < gi->nlocs; ++i) {
5741 MonoDwarfLocListEntry *entry = &gi->locations [i];
5743 encode_value (entry->is_reg ? 1 : 0, p, &p);
5744 encode_value (entry->reg, p, &p);
5746 encode_value (entry->offset, p, &p);
5748 g_assert (entry->from == 0);
5750 encode_value (entry->from, p, &p);
5751 encode_value (entry->to, p, &p);
5754 if (!cfg->compile_llvm) {
5755 encode_value (gi->has_this ? 1 : 0, p, &p);
5756 encode_value (gi->this_reg, p, &p);
5757 encode_value (gi->this_offset, p, &p);
5762 * Need to encode jinfo->method too, since it is not equal to 'method'
5763 * when using generic sharing.
5765 buf2 = (guint8 *)g_malloc (4096);
5767 encode_method_ref (acfg, jinfo->d.method, p2, &p2);
5769 g_assert (len < 4096);
5770 encode_value (len, p, &p);
5771 memcpy (p, buf2, len);
5775 if (gsctx && gsctx->is_gsharedvt) {
5776 encode_value (1, p, &p);
5778 encode_value (0, p, &p);
5782 if (seq_points_size)
5783 p += mono_seq_point_info_write (seq_points, p);
5785 g_assert (debug_info_size < buf_size);
5787 encode_value (debug_info_size, p, &p);
5788 if (debug_info_size) {
5789 memcpy (p, debug_info, debug_info_size);
5790 p += debug_info_size;
5791 g_free (debug_info);
5796 encode_value (cfg->gc_map_size, p, &p);
5797 /* The GC map requires 4 bytes of alignment */
5798 while ((gsize)p % 4)
5800 memcpy (p, cfg->gc_map, cfg->gc_map_size);
5801 p += cfg->gc_map_size;
5804 acfg->stats.ex_info_size += p - buf;
5806 g_assert (p - buf < buf_size);
5809 /* The GC Map requires 4 byte alignment */
5810 cfg->ex_info_offset = add_to_blob_aligned (acfg, buf, p - buf, cfg->gc_map ? 4 : 1);
5815 emit_klass_info (MonoAotCompile *acfg, guint32 token)
5818 MonoClass *klass = mono_class_get_checked (acfg->image, token, &error);
5820 int i, buf_size, res;
5821 gboolean no_special_static, cant_encode;
5822 gpointer iter = NULL;
5825 mono_error_cleanup (&error);
5829 p = buf = (guint8 *)g_malloc (buf_size);
5831 /* Mark as unusable */
5832 encode_value (-1, p, &p);
5834 res = add_to_blob (acfg, buf, p - buf);
5840 buf_size = 10240 + (klass->vtable_size * 16);
5841 p = buf = (guint8 *)g_malloc (buf_size);
5845 mono_class_init (klass);
5847 mono_class_get_nested_types (klass, &iter);
5848 g_assert (klass->nested_classes_inited);
5850 mono_class_setup_vtable (klass);
5853 * Emit all the information which is required for creating vtables so
5854 * the runtime does not need to create the MonoMethod structures which
5855 * take up a lot of space.
5858 no_special_static = !mono_class_has_special_static_fields (klass);
5860 /* Check whenever we have enough info to encode the vtable */
5861 cant_encode = FALSE;
5862 for (i = 0; i < klass->vtable_size; ++i) {
5863 MonoMethod *cm = klass->vtable [i];
5865 if (cm && mono_method_signature (cm)->is_inflated && !g_hash_table_lookup (acfg->token_info_hash, cm))
5869 mono_class_has_finalizer (klass);
5871 if (klass->generic_container || cant_encode) {
5872 encode_value (-1, p, &p);
5874 encode_value (klass->vtable_size, p, &p);
5875 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);
5876 if (klass->has_cctor)
5877 encode_method_ref (acfg, mono_class_get_cctor (klass), p, &p);
5878 if (klass->has_finalize)
5879 encode_method_ref (acfg, mono_class_get_finalizer (klass), p, &p);
5881 encode_value (klass->instance_size, p, &p);
5882 encode_value (mono_class_data_size (klass), p, &p);
5883 encode_value (klass->packing_size, p, &p);
5884 encode_value (klass->min_align, p, &p);
5886 for (i = 0; i < klass->vtable_size; ++i) {
5887 MonoMethod *cm = klass->vtable [i];
5890 encode_method_ref (acfg, cm, p, &p);
5892 encode_value (0, p, &p);
5896 acfg->stats.class_info_size += p - buf;
5898 g_assert (p - buf < buf_size);
5899 res = add_to_blob (acfg, buf, p - buf);
5906 get_plt_entry_debug_sym (MonoAotCompile *acfg, MonoJumpInfo *ji, GHashTable *cache)
5908 char *debug_sym = NULL;
5911 if (acfg->llvm && llvm_acfg->aot_opts.static_link) {
5912 /* Need to add a prefix to create unique symbols */
5913 prefix = g_strdup_printf ("plt_%s_", acfg->assembly_name_sym);
5915 prefix = g_strdup ("plt_");
5919 case MONO_PATCH_INFO_METHOD:
5920 debug_sym = get_debug_sym (ji->data.method, prefix, cache);
5922 case MONO_PATCH_INFO_INTERNAL_METHOD:
5923 debug_sym = g_strdup_printf ("%s_jit_icall_%s", prefix, ji->data.name);
5925 case MONO_PATCH_INFO_RGCTX_FETCH:
5926 debug_sym = g_strdup_printf ("%s_rgctx_fetch_%d", prefix, acfg->label_generator ++);
5928 case MONO_PATCH_INFO_ICALL_ADDR: {
5929 char *s = get_debug_sym (ji->data.method, "", cache);
5931 debug_sym = g_strdup_printf ("%s_icall_native_%s", prefix, s);
5935 case MONO_PATCH_INFO_JIT_ICALL_ADDR:
5936 debug_sym = g_strdup_printf ("%s_jit_icall_native_%s", prefix, ji->data.name);
5944 return sanitize_symbol (acfg, debug_sym);
5948 * Calls made from AOTed code are routed through a table of jumps similar to the
5949 * ELF PLT (Program Linkage Table). Initially the PLT entries jump to code which transfers
5950 * control to the AOT runtime through a trampoline.
5953 emit_plt (MonoAotCompile *acfg)
5957 if (acfg->aot_opts.llvm_only) {
5958 g_assert (acfg->plt_offset == 1);
5964 emit_section_change (acfg, ".text", 0);
5965 emit_alignment_code (acfg, NACL_SIZE(16, kNaClAlignment));
5966 emit_info_symbol (acfg, "plt");
5967 emit_label (acfg, acfg->plt_symbol);
5969 for (i = 0; i < acfg->plt_offset; ++i) {
5970 char *debug_sym = NULL;
5971 MonoPltEntry *plt_entry = NULL;
5975 * The first plt entry is unused.
5979 plt_entry = (MonoPltEntry *)g_hash_table_lookup (acfg->plt_offset_to_entry, GUINT_TO_POINTER (i));
5981 debug_sym = plt_entry->debug_sym;
5983 if (acfg->thumb_mixed && !plt_entry->jit_used)
5984 /* Emit only a thumb version */
5987 /* Skip plt entries not actually called */
5988 if (!plt_entry->jit_used && !plt_entry->llvm_used)
5991 if (acfg->llvm && !acfg->thumb_mixed) {
5992 emit_label (acfg, plt_entry->llvm_symbol);
5994 emit_global_inner (acfg, plt_entry->llvm_symbol, TRUE);
5995 #if defined(TARGET_MACH)
5996 fprintf (acfg->fp, ".private_extern %s\n", plt_entry->llvm_symbol);
6002 if (acfg->need_no_dead_strip) {
6003 emit_unset_mode (acfg);
6004 fprintf (acfg->fp, " .no_dead_strip %s\n", debug_sym);
6006 emit_local_symbol (acfg, debug_sym, NULL, TRUE);
6007 emit_label (acfg, debug_sym);
6010 emit_label (acfg, plt_entry->symbol);
6012 arch_emit_plt_entry (acfg, acfg->got_symbol, (acfg->plt_got_offset_base + i) * sizeof (gpointer), acfg->plt_got_info_offsets [i]);
6015 emit_symbol_size (acfg, debug_sym, ".");
6018 if (acfg->thumb_mixed) {
6019 /* Make sure the ARM symbols don't alias the thumb ones */
6020 emit_zero_bytes (acfg, 16);
6023 * Emit a separate set of PLT entries using thumb2 which is called by LLVM generated
6026 for (i = 0; i < acfg->plt_offset; ++i) {
6027 char *debug_sym = NULL;
6028 MonoPltEntry *plt_entry = NULL;
6033 plt_entry = (MonoPltEntry *)g_hash_table_lookup (acfg->plt_offset_to_entry, GUINT_TO_POINTER (i));
6035 /* Skip plt entries not actually called by LLVM code */
6036 if (!plt_entry->llvm_used)
6039 if (acfg->aot_opts.write_symbols) {
6040 if (plt_entry->debug_sym)
6041 debug_sym = g_strdup_printf ("%s_thumb", plt_entry->debug_sym);
6045 #if defined(TARGET_MACH)
6046 fprintf (acfg->fp, " .thumb_func %s\n", debug_sym);
6047 fprintf (acfg->fp, " .no_dead_strip %s\n", debug_sym);
6049 emit_local_symbol (acfg, debug_sym, NULL, TRUE);
6050 emit_label (acfg, debug_sym);
6052 fprintf (acfg->fp, "\n.thumb_func\n");
6054 emit_label (acfg, plt_entry->llvm_symbol);
6057 emit_global_inner (acfg, plt_entry->llvm_symbol, TRUE);
6059 arch_emit_llvm_plt_entry (acfg, acfg->got_symbol, (acfg->plt_got_offset_base + i) * sizeof (gpointer), acfg->plt_got_info_offsets [i]);
6062 emit_symbol_size (acfg, debug_sym, ".");
6068 emit_symbol_size (acfg, acfg->plt_symbol, ".");
6070 emit_info_symbol (acfg, "plt_end");
6074 * emit_trampoline_full:
6076 * If EMIT_TINFO is TRUE, emit additional information which can be used to create a MonoJitInfo for this trampoline by
6077 * create_jit_info_for_trampoline ().
6079 static G_GNUC_UNUSED void
6080 emit_trampoline_full (MonoAotCompile *acfg, int got_offset, MonoTrampInfo *info, gboolean emit_tinfo)
6082 char start_symbol [256];
6083 char end_symbol [256];
6085 guint32 buf_size, info_offset;
6086 MonoJumpInfo *patch_info;
6099 code_size = info->code_size;
6101 unwind_ops = info->unwind_ops;
6103 #ifdef __native_client_codegen__
6104 mono_nacl_fix_patches (code, ji);
6109 sprintf (start_symbol, "%s%s", acfg->user_symbol_prefix, name);
6111 emit_section_change (acfg, ".text", 0);
6112 emit_global (acfg, start_symbol, TRUE);
6113 emit_alignment_code (acfg, AOT_FUNC_ALIGNMENT);
6114 emit_label (acfg, start_symbol);
6116 sprintf (symbol, "%snamed_%s", acfg->temp_prefix, name);
6117 emit_label (acfg, symbol);
6120 * The code should access everything through the GOT, so we pass
6123 emit_and_reloc_code (acfg, NULL, code, code_size, ji, TRUE, NULL);
6125 emit_symbol_size (acfg, start_symbol, ".");
6128 sprintf (end_symbol, "%snamede_%s", acfg->temp_prefix, name);
6129 emit_label (acfg, end_symbol);
6134 /* Sort relocations */
6135 patches = g_ptr_array_new ();
6136 for (patch_info = ji; patch_info; patch_info = patch_info->next)
6137 if (patch_info->type != MONO_PATCH_INFO_NONE)
6138 g_ptr_array_add (patches, patch_info);
6139 g_ptr_array_sort (patches, compare_patches);
6141 buf_size = patches->len * 128 + 128;
6142 buf = (guint8 *)g_malloc (buf_size);
6145 encode_patch_list (acfg, patches, patches->len, FALSE, got_offset, p, &p);
6146 g_assert (p - buf < buf_size);
6148 sprintf (symbol, "%s%s_p", acfg->user_symbol_prefix, name);
6150 info_offset = add_to_blob (acfg, buf, p - buf);
6152 emit_section_change (acfg, RODATA_SECT, 0);
6153 emit_global (acfg, symbol, FALSE);
6154 emit_label (acfg, symbol);
6156 emit_int32 (acfg, info_offset);
6160 guint32 encoded_len;
6164 * Emit additional information which can be used to reconstruct a partial MonoTrampInfo.
6166 encoded = mono_unwind_ops_encode (info->unwind_ops, &encoded_len);
6167 uw_offset = get_unwind_info_offset (acfg, encoded, encoded_len);
6170 emit_symbol_diff (acfg, end_symbol, start_symbol, 0);
6171 emit_int32 (acfg, uw_offset);
6174 /* Emit debug info */
6178 sprintf (symbol, "%s", name);
6179 sprintf (symbol2, "%snamed_%s", acfg->temp_prefix, name);
6182 mono_dwarf_writer_emit_trampoline (acfg->dwarf, symbol, symbol2, NULL, NULL, code_size, unwind_ops);
6186 static G_GNUC_UNUSED void
6187 emit_trampoline (MonoAotCompile *acfg, int got_offset, MonoTrampInfo *info)
6189 emit_trampoline_full (acfg, got_offset, info, TRUE);
6193 emit_trampolines (MonoAotCompile *acfg)
6196 char end_symbol [256];
6197 int i, tramp_got_offset;
6199 #ifdef MONO_ARCH_HAVE_FULL_AOT_TRAMPOLINES
6203 if (!mono_aot_mode_is_full (&acfg->aot_opts) || acfg->aot_opts.llvm_only)
6206 g_assert (acfg->image->assembly);
6208 /* Currently, we emit most trampolines into the mscorlib AOT image. */
6209 if (strcmp (acfg->image->assembly->aname.name, "mscorlib") == 0) {
6210 #ifdef MONO_ARCH_HAVE_FULL_AOT_TRAMPOLINES
6211 MonoTrampInfo *info;
6214 * Emit the generic trampolines.
6216 * We could save some code by treating the generic trampolines as a wrapper
6217 * method, but that approach has its own complexities, so we choose the simpler
6220 for (tramp_type = 0; tramp_type < MONO_TRAMPOLINE_NUM; ++tramp_type) {
6221 /* we overload the boolean here to indicate the slightly different trampoline needed, see mono_arch_create_generic_trampoline() */
6222 #ifdef DISABLE_REMOTING
6223 if (tramp_type == MONO_TRAMPOLINE_GENERIC_VIRTUAL_REMOTING)
6226 #ifndef MONO_ARCH_HAVE_HANDLER_BLOCK_GUARD
6227 if (tramp_type == MONO_TRAMPOLINE_HANDLER_BLOCK_GUARD)
6230 mono_arch_create_generic_trampoline ((MonoTrampolineType)tramp_type, &info, acfg->aot_opts.use_trampolines_page? 2: TRUE);
6231 emit_trampoline (acfg, acfg->got_offset, info);
6234 /* Emit the exception related code pieces */
6235 mono_arch_get_restore_context (&info, TRUE);
6236 emit_trampoline (acfg, acfg->got_offset, info);
6237 mono_arch_get_call_filter (&info, TRUE);
6238 emit_trampoline (acfg, acfg->got_offset, info);
6239 mono_arch_get_throw_exception (&info, TRUE);
6240 emit_trampoline (acfg, acfg->got_offset, info);
6241 mono_arch_get_rethrow_exception (&info, TRUE);
6242 emit_trampoline (acfg, acfg->got_offset, info);
6243 mono_arch_get_throw_corlib_exception (&info, TRUE);
6244 emit_trampoline (acfg, acfg->got_offset, info);
6246 #ifdef MONO_ARCH_HAVE_SDB_TRAMPOLINES
6247 mono_arch_create_sdb_trampoline (TRUE, &info, TRUE);
6248 emit_trampoline (acfg, acfg->got_offset, info);
6249 mono_arch_create_sdb_trampoline (FALSE, &info, TRUE);
6250 emit_trampoline (acfg, acfg->got_offset, info);
6253 #ifdef MONO_ARCH_GSHAREDVT_SUPPORTED
6254 mono_arch_get_gsharedvt_trampoline (&info, TRUE);
6256 emit_trampoline_full (acfg, acfg->got_offset, info, TRUE);
6258 /* Create a separate out trampoline for more information in stack traces */
6259 info->name = g_strdup ("gsharedvt_out_trampoline");
6260 emit_trampoline_full (acfg, acfg->got_offset, info, TRUE);
6264 #if defined(MONO_ARCH_HAVE_GET_TRAMPOLINES)
6266 GSList *l = mono_arch_get_trampolines (TRUE);
6269 MonoTrampInfo *info = (MonoTrampInfo *)l->data;
6271 emit_trampoline (acfg, acfg->got_offset, info);
6277 for (i = 0; i < acfg->aot_opts.nrgctx_fetch_trampolines; ++i) {
6280 offset = MONO_RGCTX_SLOT_MAKE_RGCTX (i);
6281 mono_arch_create_rgctx_lazy_fetch_trampoline (offset, &info, TRUE);
6282 emit_trampoline (acfg, acfg->got_offset, info);
6284 offset = MONO_RGCTX_SLOT_MAKE_MRGCTX (i);
6285 mono_arch_create_rgctx_lazy_fetch_trampoline (offset, &info, TRUE);
6286 emit_trampoline (acfg, acfg->got_offset, info);
6289 #ifdef MONO_ARCH_HAVE_GENERAL_RGCTX_LAZY_FETCH_TRAMPOLINE
6290 mono_arch_create_general_rgctx_lazy_fetch_trampoline (&info, TRUE);
6291 emit_trampoline (acfg, acfg->got_offset, info);
6297 /* delegate_invoke_impl trampolines */
6298 l = mono_arch_get_delegate_invoke_impls ();
6300 MonoTrampInfo *info = (MonoTrampInfo *)l->data;
6302 emit_trampoline (acfg, acfg->got_offset, info);
6307 #endif /* #ifdef MONO_ARCH_HAVE_FULL_AOT_TRAMPOLINES */
6309 /* Emit trampolines which are numerous */
6312 * These include the following:
6313 * - specific trampolines
6314 * - static rgctx invoke trampolines
6316 * These trampolines have the same code, they are parameterized by GOT
6318 * They are defined in this file, in the arch_... routines instead of
6319 * in tramp-<ARCH>.c, since it is easier to do it this way.
6323 * When running in aot-only mode, we can't create specific trampolines at
6324 * runtime, so we create a few, and save them in the AOT file.
6325 * Normal trampolines embed their argument as a literal inside the
6326 * trampoline code, we can't do that here, so instead we embed an offset
6327 * which needs to be added to the trampoline address to get the address of
6328 * the GOT slot which contains the argument value.
6329 * The generated trampolines jump to the generic trampolines using another
6330 * GOT slot, which will be setup by the AOT loader to point to the
6331 * generic trampoline code of the given type.
6335 * FIXME: Maybe we should use more specific trampolines (i.e. one class init for
6339 emit_section_change (acfg, ".text", 0);
6341 tramp_got_offset = acfg->got_offset;
6343 for (ntype = 0; ntype < MONO_AOT_TRAMP_NUM; ++ntype) {
6345 case MONO_AOT_TRAMP_SPECIFIC:
6346 sprintf (symbol, "specific_trampolines");
6348 case MONO_AOT_TRAMP_STATIC_RGCTX:
6349 sprintf (symbol, "static_rgctx_trampolines");
6351 case MONO_AOT_TRAMP_IMT_THUNK:
6352 sprintf (symbol, "imt_thunks");
6354 case MONO_AOT_TRAMP_GSHAREDVT_ARG:
6355 sprintf (symbol, "gsharedvt_arg_trampolines");
6358 g_assert_not_reached ();
6361 sprintf (end_symbol, "%s_e", symbol);
6363 if (acfg->aot_opts.write_symbols)
6364 emit_local_symbol (acfg, symbol, end_symbol, TRUE);
6366 emit_alignment_code (acfg, AOT_FUNC_ALIGNMENT);
6367 emit_info_symbol (acfg, symbol);
6369 acfg->trampoline_got_offset_base [ntype] = tramp_got_offset;
6371 for (i = 0; i < acfg->num_trampolines [ntype]; ++i) {
6375 case MONO_AOT_TRAMP_SPECIFIC:
6376 arch_emit_specific_trampoline (acfg, tramp_got_offset, &tramp_size);
6377 tramp_got_offset += 2;
6379 case MONO_AOT_TRAMP_STATIC_RGCTX:
6380 arch_emit_static_rgctx_trampoline (acfg, tramp_got_offset, &tramp_size);
6381 tramp_got_offset += 2;
6383 case MONO_AOT_TRAMP_IMT_THUNK:
6384 arch_emit_imt_thunk (acfg, tramp_got_offset, &tramp_size);
6385 tramp_got_offset += 1;
6387 case MONO_AOT_TRAMP_GSHAREDVT_ARG:
6388 arch_emit_gsharedvt_arg_trampoline (acfg, tramp_got_offset, &tramp_size);
6389 tramp_got_offset += 2;
6392 g_assert_not_reached ();
6394 #ifdef __native_client_codegen__
6395 /* align to avoid 32-byte boundary crossings */
6396 emit_alignment (acfg, AOT_FUNC_ALIGNMENT);
6399 if (!acfg->trampoline_size [ntype]) {
6400 g_assert (tramp_size);
6401 acfg->trampoline_size [ntype] = tramp_size;
6405 emit_label (acfg, end_symbol);
6406 emit_int32 (acfg, 0);
6409 arch_emit_specific_trampoline_pages (acfg);
6411 /* Reserve some entries at the end of the GOT for our use */
6412 acfg->num_trampoline_got_entries = tramp_got_offset - acfg->got_offset;
6415 acfg->got_offset += acfg->num_trampoline_got_entries;
6419 str_begins_with (const char *str1, const char *str2)
6421 int len = strlen (str2);
6422 return strncmp (str1, str2, len) == 0;
6426 mono_aot_readonly_field_override (MonoClassField *field)
6429 for (rdv = readonly_values; rdv; rdv = rdv->next) {
6430 char *p = rdv->name;
6432 len = strlen (field->parent->name_space);
6433 if (strncmp (p, field->parent->name_space, len))
6438 len = strlen (field->parent->name);
6439 if (strncmp (p, field->parent->name, len))
6444 if (strcmp (p, field->name))
6446 switch (rdv->type) {
6448 return &rdv->value.i1;
6450 return &rdv->value.i2;
6452 return &rdv->value.i4;
6461 add_readonly_value (MonoAotOptions *opts, const char *val)
6466 /* the format of val is:
6467 * namespace.typename.fieldname=type/value
6468 * type can be i1 for uint8/int8/boolean, i2 for uint16/int16/char, i4 for uint32/int32
6470 fval = strrchr (val, '/');
6472 fprintf (stderr, "AOT : invalid format for readonly field '%s', missing /.\n", val);
6475 tval = strrchr (val, '=');
6477 fprintf (stderr, "AOT : invalid format for readonly field '%s', missing =.\n", val);
6480 rdv = g_new0 (ReadOnlyValue, 1);
6481 rdv->name = (char *)g_malloc0 (tval - val + 1);
6482 memcpy (rdv->name, val, tval - val);
6485 if (strncmp (tval, "i1", 2) == 0) {
6486 rdv->value.i1 = atoi (fval);
6487 rdv->type = MONO_TYPE_I1;
6488 } else if (strncmp (tval, "i2", 2) == 0) {
6489 rdv->value.i2 = atoi (fval);
6490 rdv->type = MONO_TYPE_I2;
6491 } else if (strncmp (tval, "i4", 2) == 0) {
6492 rdv->value.i4 = atoi (fval);
6493 rdv->type = MONO_TYPE_I4;
6495 fprintf (stderr, "AOT : unsupported type for readonly field '%s'.\n", tval);
6498 rdv->next = readonly_values;
6499 readonly_values = rdv;
6503 clean_path (gchar * path)
6508 if (g_str_has_suffix (path, G_DIR_SEPARATOR_S))
6511 gchar *clean = g_strconcat (path, G_DIR_SEPARATOR_S, NULL);
6518 mono_aot_split_options (const char *aot_options)
6520 enum MonoAotOptionState {
6521 MONO_AOT_OPTION_STATE_DEFAULT,
6522 MONO_AOT_OPTION_STATE_STRING,
6523 MONO_AOT_OPTION_STATE_ESCAPE,
6526 GPtrArray *args = g_ptr_array_new ();
6527 enum MonoAotOptionState state = MONO_AOT_OPTION_STATE_DEFAULT;
6528 gchar const *opt_start = aot_options;
6529 gboolean end_of_string = FALSE;
6532 g_return_val_if_fail (aot_options != NULL, NULL);
6534 while ((cur = *aot_options) != '\0') {
6535 if (state == MONO_AOT_OPTION_STATE_ESCAPE)
6540 // If we find a quote, then if we're in the default case then
6541 // it means we've found the start of a string, if not then it
6542 // means we've found the end of the string and should switch
6543 // back to the default case.
6545 case MONO_AOT_OPTION_STATE_DEFAULT:
6546 state = MONO_AOT_OPTION_STATE_STRING;
6548 case MONO_AOT_OPTION_STATE_STRING:
6549 state = MONO_AOT_OPTION_STATE_DEFAULT;
6551 case MONO_AOT_OPTION_STATE_ESCAPE:
6552 g_assert_not_reached ();
6557 // If we've found an escaping operator, then this means we
6558 // should not process the next character if inside a string.
6559 if (state == MONO_AOT_OPTION_STATE_STRING)
6560 state = MONO_AOT_OPTION_STATE_ESCAPE;
6563 // If we're in the default state then this means we've found
6564 // an option, store it for later processing.
6565 if (state == MONO_AOT_OPTION_STATE_DEFAULT)
6572 // If the next character is end of string, then process the last option.
6573 if (*(aot_options) == '\0') {
6574 end_of_string = TRUE;
6580 g_ptr_array_add (args, g_strndup (opt_start, aot_options - opt_start));
6581 opt_start = ++aot_options;
6591 mono_aot_parse_options (const char *aot_options, MonoAotOptions *opts)
6595 args = mono_aot_split_options (aot_options ? aot_options : "");
6596 for (int i = 0; i < args->len; ++i) {
6597 const char *arg = (const char *)g_ptr_array_index (args, i);
6599 if (str_begins_with (arg, "outfile=")) {
6600 opts->outfile = g_strdup (arg + strlen ("outfile="));
6601 } else if (str_begins_with (arg, "llvm-outfile=")) {
6602 opts->llvm_outfile = g_strdup (arg + strlen ("llvm-outfile="));
6603 } else if (str_begins_with (arg, "temp-path=")) {
6604 opts->temp_path = clean_path (g_strdup (arg + strlen ("temp-path=")));
6605 } else if (str_begins_with (arg, "save-temps")) {
6606 opts->save_temps = TRUE;
6607 } else if (str_begins_with (arg, "keep-temps")) {
6608 opts->save_temps = TRUE;
6609 } else if (str_begins_with (arg, "write-symbols")) {
6610 opts->write_symbols = TRUE;
6611 } else if (str_begins_with (arg, "no-write-symbols")) {
6612 opts->write_symbols = FALSE;
6613 } else if (str_begins_with (arg, "metadata-only")) {
6614 opts->metadata_only = TRUE;
6615 } else if (str_begins_with (arg, "bind-to-runtime-version")) {
6616 opts->bind_to_runtime_version = TRUE;
6617 } else if (str_begins_with (arg, "full")) {
6618 opts->mode = MONO_AOT_MODE_FULL;
6619 } else if (str_begins_with (arg, "hybrid")) {
6620 opts->mode = MONO_AOT_MODE_HYBRID;
6621 } else if (str_begins_with (arg, "threads=")) {
6622 opts->nthreads = atoi (arg + strlen ("threads="));
6623 } else if (str_begins_with (arg, "static")) {
6624 opts->static_link = TRUE;
6625 opts->no_dlsym = TRUE;
6626 } else if (str_begins_with (arg, "asmonly")) {
6627 opts->asm_only = TRUE;
6628 } else if (str_begins_with (arg, "asmwriter")) {
6629 opts->asm_writer = TRUE;
6630 } else if (str_begins_with (arg, "nodebug")) {
6631 opts->nodebug = TRUE;
6632 } else if (str_begins_with (arg, "dwarfdebug")) {
6633 opts->dwarf_debug = TRUE;
6634 } else if (str_begins_with (arg, "nopagetrampolines")) {
6635 opts->use_trampolines_page = FALSE;
6636 } else if (str_begins_with (arg, "ntrampolines=")) {
6637 opts->ntrampolines = atoi (arg + strlen ("ntrampolines="));
6638 } else if (str_begins_with (arg, "nrgctx-trampolines=")) {
6639 opts->nrgctx_trampolines = atoi (arg + strlen ("nrgctx-trampolines="));
6640 } else if (str_begins_with (arg, "nimt-trampolines=")) {
6641 opts->nimt_trampolines = atoi (arg + strlen ("nimt-trampolines="));
6642 } else if (str_begins_with (arg, "ngsharedvt-trampolines=")) {
6643 opts->ngsharedvt_arg_trampolines = atoi (arg + strlen ("ngsharedvt-trampolines="));
6644 } else if (str_begins_with (arg, "tool-prefix=")) {
6645 opts->tool_prefix = g_strdup (arg + strlen ("tool-prefix="));
6646 } else if (str_begins_with (arg, "ld-flags=")) {
6647 opts->ld_flags = g_strdup (arg + strlen ("ld-flags="));
6648 } else if (str_begins_with (arg, "soft-debug")) {
6649 opts->soft_debug = TRUE;
6650 } else if (str_begins_with (arg, "gen-seq-points-file")) {
6651 opts->gen_seq_points_file = TRUE;
6652 } else if (str_begins_with (arg, "direct-pinvoke")) {
6653 opts->direct_pinvoke = TRUE;
6654 } else if (str_begins_with (arg, "direct-icalls")) {
6655 opts->direct_icalls = TRUE;
6656 } else if (str_begins_with (arg, "no-direct-calls")) {
6657 opts->no_direct_calls = TRUE;
6658 } else if (str_begins_with (arg, "print-skipped")) {
6659 opts->print_skipped_methods = TRUE;
6660 } else if (str_begins_with (arg, "stats")) {
6662 } else if (str_begins_with (arg, "no-instances")) {
6663 opts->no_instances = TRUE;
6664 } else if (str_begins_with (arg, "log-generics")) {
6665 opts->log_generics = TRUE;
6666 } else if (str_begins_with (arg, "log-instances=")) {
6667 opts->log_instances = TRUE;
6668 opts->instances_logfile_path = g_strdup (arg + strlen ("log-instances="));
6669 } else if (str_begins_with (arg, "log-instances")) {
6670 opts->log_instances = TRUE;
6671 } else if (str_begins_with (arg, "internal-logfile=")) {
6672 opts->logfile = g_strdup (arg + strlen ("internal-logfile="));
6673 } else if (str_begins_with (arg, "mtriple=")) {
6674 opts->mtriple = g_strdup (arg + strlen ("mtriple="));
6675 } else if (str_begins_with (arg, "llvm-path=")) {
6676 opts->llvm_path = clean_path (g_strdup (arg + strlen ("llvm-path=")));
6677 } else if (!strcmp (arg, "llvm")) {
6679 } else if (str_begins_with (arg, "readonly-value=")) {
6680 add_readonly_value (opts, arg + strlen ("readonly-value="));
6681 } else if (str_begins_with (arg, "info")) {
6682 printf ("AOT target setup: %s.\n", AOT_TARGET_STR);
6684 } else if (str_begins_with (arg, "gc-maps")) {
6685 mini_gc_enable_gc_maps_for_aot ();
6686 } else if (str_begins_with (arg, "dump")) {
6687 opts->dump_json = TRUE;
6688 } else if (str_begins_with (arg, "llvmonly")) {
6689 opts->mode = MONO_AOT_MODE_FULL;
6691 opts->llvm_only = TRUE;
6692 } else if (str_begins_with (arg, "help") || str_begins_with (arg, "?")) {
6693 printf ("Supported options for --aot:\n");
6694 printf (" outfile=\n");
6695 printf (" llvm-outfile=\n");
6696 printf (" llvm-path=\n");
6697 printf (" temp-path=\n");
6698 printf (" save-temps\n");
6699 printf (" keep-temps\n");
6700 printf (" write-symbols\n");
6701 printf (" metadata-only\n");
6702 printf (" bind-to-runtime-version\n");
6704 printf (" threads=\n");
6705 printf (" static\n");
6706 printf (" asmonly\n");
6707 printf (" asmwriter\n");
6708 printf (" nodebug\n");
6709 printf (" dwarfdebug\n");
6710 printf (" ntrampolines=\n");
6711 printf (" nrgctx-trampolines=\n");
6712 printf (" nimt-trampolines=\n");
6713 printf (" ngsharedvt-trampolines=\n");
6714 printf (" tool-prefix=\n");
6715 printf (" readonly-value=\n");
6716 printf (" soft-debug\n");
6717 printf (" gen-seq-points-file\n");
6718 printf (" gc-maps\n");
6719 printf (" print-skipped\n");
6720 printf (" no-instances\n");
6721 printf (" stats\n");
6724 printf (" help/?\n");
6727 fprintf (stderr, "AOT : Unknown argument '%s'.\n", arg);
6731 g_free ((gpointer) arg);
6734 if (opts->use_trampolines_page) {
6735 opts->ntrampolines = 0;
6736 opts->nrgctx_trampolines = 0;
6737 opts->nimt_trampolines = 0;
6738 opts->ngsharedvt_arg_trampolines = 0;
6741 g_ptr_array_free (args, /*free_seg=*/TRUE);
6745 add_token_info_hash (gpointer key, gpointer value, gpointer user_data)
6747 MonoMethod *method = (MonoMethod*)key;
6748 MonoJumpInfoToken *ji = (MonoJumpInfoToken*)value;
6749 MonoAotCompile *acfg = (MonoAotCompile *)user_data;
6750 MonoJumpInfoToken *new_ji;
6752 new_ji = (MonoJumpInfoToken *)mono_mempool_alloc0 (acfg->mempool, sizeof (MonoJumpInfoToken));
6753 new_ji->image = ji->image;
6754 new_ji->token = ji->token;
6755 g_hash_table_insert (acfg->token_info_hash, method, new_ji);
6759 can_encode_class (MonoAotCompile *acfg, MonoClass *klass)
6761 if (klass->type_token)
6763 if ((klass->byval_arg.type == MONO_TYPE_VAR) || (klass->byval_arg.type == MONO_TYPE_MVAR) || (klass->byval_arg.type == MONO_TYPE_PTR))
6766 return can_encode_class (acfg, klass->element_class);
6771 can_encode_method (MonoAotCompile *acfg, MonoMethod *method)
6773 if (method->wrapper_type) {
6774 switch (method->wrapper_type) {
6775 case MONO_WRAPPER_NONE:
6776 case MONO_WRAPPER_REMOTING_INVOKE_WITH_CHECK:
6777 case MONO_WRAPPER_XDOMAIN_INVOKE:
6778 case MONO_WRAPPER_STFLD:
6779 case MONO_WRAPPER_LDFLD:
6780 case MONO_WRAPPER_LDFLDA:
6781 case MONO_WRAPPER_LDFLD_REMOTE:
6782 case MONO_WRAPPER_STFLD_REMOTE:
6783 case MONO_WRAPPER_STELEMREF:
6784 case MONO_WRAPPER_ISINST:
6785 case MONO_WRAPPER_PROXY_ISINST:
6786 case MONO_WRAPPER_ALLOC:
6787 case MONO_WRAPPER_REMOTING_INVOKE:
6788 case MONO_WRAPPER_UNKNOWN:
6789 case MONO_WRAPPER_WRITE_BARRIER:
6790 case MONO_WRAPPER_DELEGATE_INVOKE:
6791 case MONO_WRAPPER_DELEGATE_BEGIN_INVOKE:
6792 case MONO_WRAPPER_DELEGATE_END_INVOKE:
6793 case MONO_WRAPPER_SYNCHRONIZED:
6795 case MONO_WRAPPER_MANAGED_TO_MANAGED:
6796 case MONO_WRAPPER_CASTCLASS: {
6797 WrapperInfo *info = mono_marshal_get_wrapper_info (method);
6806 //printf ("Skip (wrapper call): %d -> %s\n", patch_info->type, mono_method_full_name (patch_info->data.method, TRUE));
6810 if (!method->token) {
6811 /* The method is part of a constructed type like Int[,].Set (). */
6812 if (!g_hash_table_lookup (acfg->token_info_hash, method)) {
6813 if (method->klass->rank)
6823 can_encode_patch (MonoAotCompile *acfg, MonoJumpInfo *patch_info)
6825 switch (patch_info->type) {
6826 case MONO_PATCH_INFO_METHOD:
6827 case MONO_PATCH_INFO_METHODCONST:
6828 case MONO_PATCH_INFO_METHOD_CODE_SLOT: {
6829 MonoMethod *method = patch_info->data.method;
6831 return can_encode_method (acfg, method);
6833 case MONO_PATCH_INFO_VTABLE:
6834 case MONO_PATCH_INFO_CLASS:
6835 case MONO_PATCH_INFO_IID:
6836 case MONO_PATCH_INFO_ADJUSTED_IID:
6837 if (!can_encode_class (acfg, patch_info->data.klass)) {
6838 //printf ("Skip: %s\n", mono_type_full_name (&patch_info->data.klass->byval_arg));
6842 case MONO_PATCH_INFO_DELEGATE_TRAMPOLINE: {
6843 if (!can_encode_class (acfg, patch_info->data.del_tramp->klass)) {
6844 //printf ("Skip: %s\n", mono_type_full_name (&patch_info->data.klass->byval_arg));
6849 case MONO_PATCH_INFO_RGCTX_FETCH:
6850 case MONO_PATCH_INFO_RGCTX_SLOT_INDEX: {
6851 MonoJumpInfoRgctxEntry *entry = patch_info->data.rgctx_entry;
6853 if (!can_encode_method (acfg, entry->method))
6855 if (!can_encode_patch (acfg, entry->data))
6869 * AOT compile a given method.
6870 * This function might be called by multiple threads, so it must be thread-safe.
6873 compile_method (MonoAotCompile *acfg, MonoMethod *method)
6876 MonoJumpInfo *patch_info;
6879 MonoMethod *wrapped;
6882 if (acfg->aot_opts.metadata_only)
6885 mono_acfg_lock (acfg);
6886 index = get_method_index (acfg, method);
6887 mono_acfg_unlock (acfg);
6889 /* fixme: maybe we can also precompile wrapper methods */
6890 if ((method->flags & METHOD_ATTRIBUTE_PINVOKE_IMPL) ||
6891 (method->iflags & METHOD_IMPL_ATTRIBUTE_RUNTIME) ||
6892 (method->flags & METHOD_ATTRIBUTE_ABSTRACT)) {
6893 //printf ("Skip (impossible): %s\n", mono_method_full_name (method, TRUE));
6897 if (method->iflags & METHOD_IMPL_ATTRIBUTE_INTERNAL_CALL)
6900 wrapped = mono_marshal_method_from_wrapper (method);
6901 if (wrapped && (wrapped->iflags & METHOD_IMPL_ATTRIBUTE_INTERNAL_CALL) && wrapped->is_generic)
6902 // FIXME: The wrapper should be generic too, but it is not
6905 if (method->wrapper_type == MONO_WRAPPER_COMINTEROP)
6908 InterlockedIncrement (&acfg->stats.mcount);
6911 if (method->is_generic || method->klass->generic_container) {
6912 InterlockedIncrement (&acfg->stats.genericcount);
6917 //acfg->aot_opts.print_skipped_methods = TRUE;
6920 * Since these methods are the only ones which are compiled with
6921 * AOT support, and they are not used by runtime startup/shutdown code,
6922 * the runtime will not see AOT methods during AOT compilation,so it
6923 * does not need to support them by creating a fake GOT etc.
6925 flags = JIT_FLAG_AOT;
6926 if (mono_aot_mode_is_full (&acfg->aot_opts))
6927 flags = (JitFlags)(flags | JIT_FLAG_FULL_AOT);
6929 flags = (JitFlags)(flags | JIT_FLAG_LLVM);
6930 if (acfg->aot_opts.llvm_only)
6931 flags = (JitFlags)(flags | JIT_FLAG_LLVM_ONLY | JIT_FLAG_EXPLICIT_NULL_CHECKS);
6932 if (acfg->aot_opts.no_direct_calls)
6933 flags = (JitFlags)(flags | JIT_FLAG_NO_DIRECT_ICALLS);
6934 cfg = mini_method_compile (method, acfg->opts, mono_get_root_domain (), flags, 0, index);
6935 mono_loader_clear_error ();
6937 if (cfg->exception_type == MONO_EXCEPTION_GENERIC_SHARING_FAILED) {
6938 if (acfg->aot_opts.print_skipped_methods)
6939 printf ("Skip (gshared failure): %s (%s)\n", mono_method_full_name (method, TRUE), cfg->exception_message);
6940 InterlockedIncrement (&acfg->stats.genericcount);
6943 if (cfg->exception_type != MONO_EXCEPTION_NONE) {
6944 if (acfg->aot_opts.print_skipped_methods)
6945 printf ("Skip (JIT failure): %s\n", mono_method_full_name (method, TRUE));
6946 /* Let the exception happen at runtime */
6950 if (cfg->disable_aot) {
6951 if (acfg->aot_opts.print_skipped_methods)
6952 printf ("Skip (disabled): %s\n", mono_method_full_name (method, TRUE));
6953 InterlockedIncrement (&acfg->stats.ocount);
6954 mono_destroy_compile (cfg);
6957 cfg->method_index = index;
6959 /* Nullify patches which need no aot processing */
6960 for (patch_info = cfg->patch_info; patch_info; patch_info = patch_info->next) {
6961 switch (patch_info->type) {
6962 case MONO_PATCH_INFO_LABEL:
6963 case MONO_PATCH_INFO_BB:
6964 patch_info->type = MONO_PATCH_INFO_NONE;
6971 /* Collect method->token associations from the cfg */
6972 mono_acfg_lock (acfg);
6973 g_hash_table_foreach (cfg->token_info_hash, add_token_info_hash, acfg);
6974 mono_acfg_unlock (acfg);
6975 g_hash_table_destroy (cfg->token_info_hash);
6976 cfg->token_info_hash = NULL;
6979 * Check for absolute addresses.
6982 for (patch_info = cfg->patch_info; patch_info; patch_info = patch_info->next) {
6983 switch (patch_info->type) {
6984 case MONO_PATCH_INFO_ABS:
6985 /* unable to handle this */
6994 if (acfg->aot_opts.print_skipped_methods)
6995 printf ("Skip (abs call): %s\n", mono_method_full_name (method, TRUE));
6996 InterlockedIncrement (&acfg->stats.abscount);
6997 mono_destroy_compile (cfg);
7001 /* Lock for the rest of the code */
7002 mono_acfg_lock (acfg);
7005 * Check for methods/klasses we can't encode.
7008 for (patch_info = cfg->patch_info; patch_info; patch_info = patch_info->next) {
7009 if (!can_encode_patch (acfg, patch_info))
7014 if (acfg->aot_opts.print_skipped_methods)
7015 printf ("Skip (patches): %s\n", mono_method_full_name (method, TRUE));
7016 acfg->stats.ocount++;
7017 mono_destroy_compile (cfg);
7018 mono_acfg_unlock (acfg);
7022 if (!cfg->compile_llvm)
7023 acfg->has_jitted_code = TRUE;
7025 if (method->is_inflated && acfg->aot_opts.log_instances) {
7026 if (acfg->instances_logfile)
7027 fprintf (acfg->instances_logfile, "%s ### %d\n", mono_method_full_name (method, TRUE), cfg->code_size);
7029 printf ("%s ### %d\n", mono_method_full_name (method, TRUE), cfg->code_size);
7032 /* Adds generic instances referenced by this method */
7034 * The depth is used to avoid infinite loops when generic virtual recursion is
7037 depth = GPOINTER_TO_UINT (g_hash_table_lookup (acfg->method_depth, method));
7038 if (!acfg->aot_opts.no_instances && depth < 32) {
7039 for (patch_info = cfg->patch_info; patch_info; patch_info = patch_info->next) {
7040 switch (patch_info->type) {
7041 case MONO_PATCH_INFO_RGCTX_FETCH:
7042 case MONO_PATCH_INFO_RGCTX_SLOT_INDEX:
7043 case MONO_PATCH_INFO_METHOD: {
7044 MonoMethod *m = NULL;
7046 if (patch_info->type == MONO_PATCH_INFO_RGCTX_FETCH || patch_info->type == MONO_PATCH_INFO_RGCTX_SLOT_INDEX) {
7047 MonoJumpInfoRgctxEntry *e = patch_info->data.rgctx_entry;
7049 if (e->info_type == MONO_RGCTX_INFO_GENERIC_METHOD_CODE)
7050 m = e->data->data.method;
7052 m = patch_info->data.method;
7057 if (m->is_inflated) {
7058 if (!(mono_class_generic_sharing_enabled (m->klass) &&
7059 mono_method_is_generic_sharable_full (m, FALSE, FALSE, FALSE)) &&
7060 (!method_has_type_vars (m) || mono_method_is_generic_sharable_full (m, TRUE, TRUE, FALSE))) {
7061 if (m->iflags & METHOD_IMPL_ATTRIBUTE_INTERNAL_CALL) {
7062 if (mono_aot_mode_is_full (&acfg->aot_opts) && !method_has_type_vars (m))
7063 add_extra_method_with_depth (acfg, mono_marshal_get_native_wrapper (m, TRUE, TRUE), depth + 1);
7065 add_extra_method_with_depth (acfg, m, depth + 1);
7066 add_types_from_method_header (acfg, m);
7069 add_generic_class_with_depth (acfg, m->klass, depth + 5, "method");
7071 if (m->wrapper_type == MONO_WRAPPER_MANAGED_TO_MANAGED) {
7072 WrapperInfo *info = mono_marshal_get_wrapper_info (m);
7074 if (info && info->subtype == WRAPPER_SUBTYPE_ELEMENT_ADDR)
7075 add_extra_method_with_depth (acfg, m, depth + 1);
7079 case MONO_PATCH_INFO_VTABLE: {
7080 MonoClass *klass = patch_info->data.klass;
7082 if (klass->generic_class && !mini_class_is_generic_sharable (klass))
7083 add_generic_class_with_depth (acfg, klass, depth + 5, "vtable");
7086 case MONO_PATCH_INFO_SFLDA: {
7087 MonoClass *klass = patch_info->data.field->parent;
7089 /* The .cctor needs to run at runtime. */
7090 if (klass->generic_class && !mono_generic_context_is_sharable (&klass->generic_class->context, FALSE) && mono_class_get_cctor (klass))
7091 add_extra_method_with_depth (acfg, mono_class_get_cctor (klass), depth + 1);
7100 /* Determine whenever the method has GOT slots */
7101 for (patch_info = cfg->patch_info; patch_info; patch_info = patch_info->next) {
7102 switch (patch_info->type) {
7103 case MONO_PATCH_INFO_GOT_OFFSET:
7104 case MONO_PATCH_INFO_NONE:
7105 case MONO_PATCH_INFO_GC_CARD_TABLE_ADDR:
7106 case MONO_PATCH_INFO_GC_NURSERY_START:
7107 case MONO_PATCH_INFO_GC_NURSERY_BITS:
7109 case MONO_PATCH_INFO_IMAGE:
7110 /* The assembly is stored in GOT slot 0 */
7111 if (patch_info->data.image != acfg->image)
7112 cfg->has_got_slots = TRUE;
7115 if (!is_plt_patch (patch_info) || (cfg->compile_llvm && acfg->aot_opts.llvm_only))
7116 cfg->has_got_slots = TRUE;
7121 if (!cfg->has_got_slots)
7122 InterlockedIncrement (&acfg->stats.methods_without_got_slots);
7125 * FIXME: Instead of this mess, allocate the patches from the aot mempool.
7127 /* Make a copy of the patch info which is in the mempool */
7129 MonoJumpInfo *patches = NULL, *patches_end = NULL;
7131 for (patch_info = cfg->patch_info; patch_info; patch_info = patch_info->next) {
7132 MonoJumpInfo *new_patch_info = mono_patch_info_dup_mp (acfg->mempool, patch_info);
7135 patches = new_patch_info;
7137 patches_end->next = new_patch_info;
7138 patches_end = new_patch_info;
7140 cfg->patch_info = patches;
7142 /* Make a copy of the unwind info */
7144 GSList *l, *unwind_ops;
7148 for (l = cfg->unwind_ops; l; l = l->next) {
7149 op = (MonoUnwindOp *)mono_mempool_alloc (acfg->mempool, sizeof (MonoUnwindOp));
7150 memcpy (op, l->data, sizeof (MonoUnwindOp));
7151 unwind_ops = g_slist_prepend_mempool (acfg->mempool, unwind_ops, op);
7153 cfg->unwind_ops = g_slist_reverse (unwind_ops);
7155 /* Make a copy of the argument/local info */
7157 MonoInst **args, **locals;
7158 MonoMethodSignature *sig;
7159 MonoMethodHeader *header;
7162 sig = mono_method_signature (method);
7163 args = (MonoInst **)mono_mempool_alloc (acfg->mempool, sizeof (MonoInst*) * (sig->param_count + sig->hasthis));
7164 for (i = 0; i < sig->param_count + sig->hasthis; ++i) {
7165 args [i] = (MonoInst *)mono_mempool_alloc (acfg->mempool, sizeof (MonoInst));
7166 memcpy (args [i], cfg->args [i], sizeof (MonoInst));
7170 header = mono_method_get_header (method);
7171 locals = (MonoInst **)mono_mempool_alloc (acfg->mempool, sizeof (MonoInst*) * header->num_locals);
7172 for (i = 0; i < header->num_locals; ++i) {
7173 locals [i] = (MonoInst *)mono_mempool_alloc (acfg->mempool, sizeof (MonoInst));
7174 memcpy (locals [i], cfg->locals [i], sizeof (MonoInst));
7176 cfg->locals = locals;
7179 /* Free some fields used by cfg to conserve memory */
7180 mono_mempool_destroy (cfg->mempool);
7181 cfg->mempool = NULL;
7182 g_free (cfg->varinfo);
7183 cfg->varinfo = NULL;
7187 mono_regstate_free (cfg->rs);
7191 //printf ("Compile: %s\n", mono_method_full_name (method, TRUE));
7193 while (index >= acfg->cfgs_size) {
7194 MonoCompile **new_cfgs;
7197 new_size = acfg->cfgs_size * 2;
7198 new_cfgs = g_new0 (MonoCompile*, new_size);
7199 memcpy (new_cfgs, acfg->cfgs, sizeof (MonoCompile*) * acfg->cfgs_size);
7200 g_free (acfg->cfgs);
7201 acfg->cfgs = new_cfgs;
7202 acfg->cfgs_size = new_size;
7204 acfg->cfgs [index] = cfg;
7206 g_hash_table_insert (acfg->method_to_cfg, cfg->orig_method, cfg);
7209 if (cfg->orig_method->wrapper_type)
7210 g_ptr_array_add (acfg->extra_methods, cfg->orig_method);
7213 mono_acfg_unlock (acfg);
7215 InterlockedIncrement (&acfg->stats.ccount);
7219 compile_thread_main (gpointer *user_data)
7221 MonoDomain *domain = (MonoDomain *)user_data [0];
7222 MonoAotCompile *acfg = (MonoAotCompile *)user_data [1];
7223 GPtrArray *methods = (GPtrArray *)user_data [2];
7226 mono_thread_attach (domain);
7228 for (i = 0; i < methods->len; ++i)
7229 compile_method (acfg, (MonoMethod *)g_ptr_array_index (methods, i));
7233 load_profile_files (MonoAotCompile *acfg)
7237 int file_index, res, method_index, i;
7240 GList *unordered, *l;
7245 tmp = g_strdup_printf ("%s/.mono/aot-profile-data/%s-%d", g_get_home_dir (), acfg->image->assembly_name, file_index);
7247 if (!g_file_test (tmp, G_FILE_TEST_IS_REGULAR)) {
7252 infile = fopen (tmp, "r");
7255 printf ("Using profile data file '%s'\n", tmp);
7260 res = fscanf (infile, "%32s\n", ver);
7261 if ((res != 1) || strcmp (ver, "#VER:2") != 0) {
7262 printf ("Profile file has wrong version or invalid.\n");
7269 MonoMethodDesc *desc;
7272 if (fgets (name, 1023, infile) == NULL)
7275 /* Kill the newline */
7276 if (strlen (name) > 0)
7277 name [strlen (name) - 1] = '\0';
7279 desc = mono_method_desc_new (name, TRUE);
7281 method = mono_method_desc_search_in_image (desc, acfg->image);
7283 if (method && mono_method_get_token (method)) {
7284 token = mono_method_get_token (method);
7285 method_index = mono_metadata_token_index (token) - 1;
7288 for (i = 0; i < acfg->method_order->len; ++i) {
7289 if (g_ptr_array_index (acfg->method_order, i) == GUINT_TO_POINTER (method_index)) {
7295 g_ptr_array_add (acfg->method_order, GUINT_TO_POINTER (method_index));
7297 //printf ("No method found matching '%s'.\n", name);
7303 /* Add missing methods */
7305 for (method_index = 0; method_index < acfg->image->tables [MONO_TABLE_METHOD].rows; ++method_index) {
7307 for (i = 0; i < acfg->method_order->len; ++i) {
7308 if (g_ptr_array_index (acfg->method_order, i) == GUINT_TO_POINTER (method_index)) {
7314 unordered = g_list_prepend (unordered, GUINT_TO_POINTER (method_index));
7316 unordered = g_list_reverse (unordered);
7317 for (l = unordered; l; l = l->next)
7318 g_ptr_array_add (acfg->method_order, l->data);
7321 /* Used by the LLVM backend */
7323 mono_aot_get_got_offset (MonoJumpInfo *ji)
7325 return get_got_offset (llvm_acfg, TRUE, ji);
7329 * mono_aot_is_shared_got_offset:
7331 * Return whenever OFFSET refers to a GOT slot which is preinitialized
7332 * when the AOT image is loaded.
7335 mono_aot_is_shared_got_offset (int offset)
7337 return offset < llvm_acfg->nshared_got_entries;
7341 mono_aot_get_method_name (MonoCompile *cfg)
7343 if (llvm_acfg->aot_opts.static_link)
7344 /* Include the assembly name too to avoid duplicate symbol errors */
7345 return g_strdup_printf ("%s_%s", llvm_acfg->assembly_name_sym, get_debug_sym (cfg->orig_method, "", llvm_acfg->method_label_hash));
7347 return get_debug_sym (cfg->orig_method, "", llvm_acfg->method_label_hash);
7351 mono_aot_is_direct_callable (MonoJumpInfo *patch_info)
7353 return is_direct_callable (llvm_acfg, NULL, patch_info);
7357 mono_aot_mark_unused_llvm_plt_entry (MonoJumpInfo *patch_info)
7359 MonoPltEntry *plt_entry;
7361 plt_entry = get_plt_entry (llvm_acfg, patch_info);
7362 plt_entry->llvm_used = FALSE;
7366 mono_aot_get_direct_call_symbol (MonoJumpInfoType type, gconstpointer data)
7368 const char *sym = NULL;
7370 if (llvm_acfg->aot_opts.direct_icalls) {
7371 if (type == MONO_PATCH_INFO_JIT_ICALL_ADDR) {
7372 /* Call to a C function implementing a jit icall */
7373 sym = mono_lookup_jit_icall_symbol ((const char *)data);
7374 } else if (type == MONO_PATCH_INFO_ICALL_ADDR) {
7375 MonoMethod *method = (MonoMethod *)data;
7376 if (!(method->flags & METHOD_ATTRIBUTE_PINVOKE_IMPL))
7377 sym = mono_lookup_icall_symbol (method);
7380 return g_strdup (sym);
7386 mono_aot_get_plt_symbol (MonoJumpInfoType type, gconstpointer data)
7388 MonoJumpInfo *ji = (MonoJumpInfo *)mono_mempool_alloc (llvm_acfg->mempool, sizeof (MonoJumpInfo));
7389 MonoPltEntry *plt_entry;
7390 const char *sym = NULL;
7393 ji->data.target = data;
7395 if (!can_encode_patch (llvm_acfg, ji))
7398 if (llvm_acfg->aot_opts.direct_icalls) {
7399 if (type == MONO_PATCH_INFO_JIT_ICALL_ADDR) {
7400 /* Call to a C function implementing a jit icall */
7401 sym = mono_lookup_jit_icall_symbol ((const char *)data);
7402 } else if (type == MONO_PATCH_INFO_ICALL_ADDR) {
7403 MonoMethod *method = (MonoMethod *)data;
7404 if (!(method->flags & METHOD_ATTRIBUTE_PINVOKE_IMPL))
7405 sym = mono_lookup_icall_symbol (method);
7408 return g_strdup (sym);
7411 plt_entry = get_plt_entry (llvm_acfg, ji);
7412 plt_entry->llvm_used = TRUE;
7414 #if defined(TARGET_MACH)
7415 return g_strdup_printf (plt_entry->llvm_symbol + strlen (llvm_acfg->llvm_label_prefix));
7417 return g_strdup_printf (plt_entry->llvm_symbol);
7422 mono_aot_get_method_index (MonoMethod *method)
7424 g_assert (llvm_acfg);
7425 return get_method_index (llvm_acfg, method);
7429 mono_aot_patch_info_dup (MonoJumpInfo* ji)
7433 mono_acfg_lock (llvm_acfg);
7434 res = mono_patch_info_dup_mp (llvm_acfg->mempool, ji);
7435 mono_acfg_unlock (llvm_acfg);
7441 execute_system (const char * command)
7446 // We need an extra set of quotes around the whole command to properly handle commands
7447 // with spaces since internally the command is called through "cmd /c.
7448 command = g_strdup_printf ("\"%s\"", command);
7450 int size = MultiByteToWideChar (CP_UTF8, 0 , command , -1, NULL , 0);
7451 wchar_t* wstr = g_malloc (sizeof (wchar_t) * size);
7452 MultiByteToWideChar (CP_UTF8, 0, command, -1, wstr , size);
7453 status = _wsystem (wstr);
7457 #elif defined (HAVE_SYSTEM)
7458 status = system (command);
7460 g_assert_not_reached ();
7471 * Emit the LLVM code into an LLVM bytecode file, and compile it using the LLVM
7475 emit_llvm_file (MonoAotCompile *acfg)
7477 char *command, *opts, *tempbc, *output_fname;
7479 /* Emit the LLVM code into a .bc file */
7480 if (acfg->aot_opts.llvm_only && acfg->aot_opts.asm_only) {
7481 mono_llvm_emit_aot_module (acfg->aot_opts.llvm_outfile, g_path_get_basename (acfg->image->name));
7485 tempbc = g_strdup_printf ("%s.bc", acfg->tmpbasename);
7486 mono_llvm_emit_aot_module (tempbc, g_path_get_basename (acfg->image->name));
7489 if (acfg->aot_opts.llvm_only) {
7490 /* Use the stock clang from xcode */
7493 // FIXME: llc/opt flags
7494 command = g_strdup_printf ("clang -march=x86-64 -fpic -msse -msse2 -msse3 -msse4 -O0 -c -o \"%s\" \"%s.bc\"", acfg->llvm_ofile, acfg->tmpbasename);
7495 //command = g_strdup_printf ("/Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/bin/clang -isysroot /Applications/Xcode.app/Contents/Developer/Platforms/iPhoneOS.platform/Developer/SDKs/iPhoneOS8.3.sdk -Qunused-arguments -miphoneos-version-min=8.2 -arch arm64 -fpic -O0 -c -o \"%s\" \"%s.bc\"", acfg->llvm_ofile, acfg->tmpbasename);
7497 aot_printf (acfg, "Executing clang: %s\n", command);
7498 if (execute_system (command) != 0)
7504 * FIXME: Experiment with adding optimizations, the -std-compile-opts set takes
7505 * a lot of time, and doesn't seem to save much space.
7506 * The following optimizations cannot be enabled:
7508 * - 'jump-threading' changes our blockaddress references to int constants.
7509 * - 'basiccg' fails because it contains:
7510 * if (CS && !isa<IntrinsicInst>(II)) {
7511 * and isa<IntrinsicInst> is false for invokes to intrinsics (iltests.exe).
7512 * - 'prune-eh' and 'functionattrs' depend on 'basiccg'.
7513 * The opt list below was produced by taking the output of:
7514 * llvm-as < /dev/null | opt -O2 -disable-output -debug-pass=Arguments
7515 * then removing tailcallelim + the global opts.
7516 * strip-dead-prototypes deletes unused intrinsics definitions.
7518 //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");
7519 /* The dse pass is disabled because of #13734 and #17616 */
7521 * The dse bug is in DeadStoreElimination.cpp:isOverwrite ():
7522 * // If we have no DataLayout information around, then the size of the store
7523 * // is inferrable from the pointee type. If they are the same type, then
7524 * // we know that the store is safe.
7525 * if (AA.getDataLayout() == 0 &&
7526 * Later.Ptr->getType() == Earlier.Ptr->getType()) {
7527 * return OverwriteComplete;
7528 * Here, if 'Earlier' refers to a memset, and Later has no size info, it mistakenly thinks the memset is redundant.
7530 opts = g_strdup ("-targetlibinfo -no-aa -basicaa -notti -instcombine -simplifycfg -inline-cost -inline -sroa -domtree -early-cse -lazy-value-info -correlated-propagation -simplifycfg -instcombine -simplifycfg -reassociate -domtree -loops -loop-simplify -lcssa -loop-rotate -licm -lcssa -loop-unswitch -instcombine -scalar-evolution -loop-simplify -lcssa -indvars -loop-idiom -loop-deletion -loop-unroll -memdep -gvn -memdep -memcpyopt -sccp -instcombine -lazy-value-info -correlated-propagation -domtree -memdep -adce -simplifycfg -instcombine -strip-dead-prototypes -domtree -verify");
7531 opts = g_strdup ("");
7533 command = g_strdup_printf ("\"%sopt\" -f %s -o \"%s.opt.bc\" \"%s.bc\"", acfg->aot_opts.llvm_path, opts, acfg->tmpbasename, acfg->tmpbasename);
7534 aot_printf (acfg, "Executing opt: %s\n", command);
7535 if (execute_system (command) != 0)
7540 if (!acfg->llc_args)
7541 acfg->llc_args = g_string_new ("");
7543 /* Verbose asm slows down llc greatly */
7544 g_string_append (acfg->llc_args, " -asm-verbose=false");
7546 if (acfg->aot_opts.mtriple)
7547 g_string_append_printf (acfg->llc_args, " -mtriple=%s", acfg->aot_opts.mtriple);
7549 g_string_append (acfg->llc_args, " -disable-gnu-eh-frame -enable-mono-eh-frame");
7551 g_string_append_printf (acfg->llc_args, " -mono-eh-frame-symbol=%s%s", acfg->user_symbol_prefix, acfg->llvm_eh_frame_symbol);
7553 #if defined(TARGET_MACH) && defined(TARGET_ARM)
7554 /* ios requires PIC code now */
7555 g_string_append_printf (acfg->llc_args, " -relocation-model=pic");
7557 if (llvm_acfg->aot_opts.static_link)
7558 g_string_append_printf (acfg->llc_args, " -relocation-model=static");
7560 g_string_append_printf (acfg->llc_args, " -relocation-model=pic");
7563 if (acfg->llvm_owriter) {
7564 /* Emit an object file directly */
7565 output_fname = g_strdup_printf ("%s", acfg->llvm_ofile);
7566 g_string_append_printf (acfg->llc_args, " -filetype=obj");
7568 output_fname = g_strdup_printf ("%s", acfg->llvm_sfile);
7570 command = g_strdup_printf ("\"%sllc\" %s -o \"%s\" \"%s.opt.bc\"", acfg->aot_opts.llvm_path, acfg->llc_args->str, output_fname, acfg->tmpbasename);
7571 g_free (output_fname);
7573 aot_printf (acfg, "Executing llc: %s\n", command);
7575 if (execute_system (command) != 0)
7582 emit_code (MonoAotCompile *acfg)
7584 int oindex, i, prev_index;
7585 gboolean saved_unbox_info = FALSE;
7588 if (acfg->aot_opts.llvm_only)
7591 #if defined(TARGET_POWERPC64)
7592 sprintf (symbol, ".Lgot_addr");
7593 emit_section_change (acfg, ".text", 0);
7594 emit_alignment (acfg, 8);
7595 emit_label (acfg, symbol);
7596 emit_pointer (acfg, acfg->got_symbol);
7600 * This global symbol is used to compute the address of each method using the
7601 * code_offsets array. It is also used to compute the memory ranges occupied by
7602 * AOT code, so it must be equal to the address of the first emitted method.
7604 emit_section_change (acfg, ".text", 0);
7605 emit_alignment_code (acfg, 8);
7606 emit_info_symbol (acfg, "jit_code_start");
7609 * Emit some padding so the local symbol for the first method doesn't have the
7610 * same address as 'methods'.
7612 #if defined(__default_codegen__)
7613 emit_padding (acfg, 16);
7614 #elif defined(__native_client_codegen__)
7616 const int kPaddingSize = 16;
7617 guint8 pad_buffer[kPaddingSize];
7618 mono_arch_nacl_pad (pad_buffer, kPaddingSize);
7619 emit_bytes (acfg, pad_buffer, kPaddingSize);
7623 for (oindex = 0; oindex < acfg->method_order->len; ++oindex) {
7627 i = GPOINTER_TO_UINT (g_ptr_array_index (acfg->method_order, oindex));
7629 cfg = acfg->cfgs [i];
7634 method = cfg->orig_method;
7636 /* Emit unbox trampoline */
7637 if (mono_aot_mode_is_full (&acfg->aot_opts) && cfg->orig_method->klass->valuetype && !(acfg->aot_opts.llvm_only && cfg->compile_llvm)) {
7638 sprintf (symbol, "ut_%d", get_method_index (acfg, method));
7640 emit_section_change (acfg, ".text", 0);
7641 #ifdef __native_client_codegen__
7642 emit_alignment (acfg, AOT_FUNC_ALIGNMENT);
7645 if (acfg->thumb_mixed && cfg->compile_llvm) {
7646 emit_set_thumb_mode (acfg);
7647 fprintf (acfg->fp, "\n.thumb_func\n");
7650 emit_label (acfg, symbol);
7652 arch_emit_unbox_trampoline (acfg, cfg, cfg->orig_method, cfg->asm_symbol);
7654 if (acfg->thumb_mixed && cfg->compile_llvm)
7655 emit_set_arm_mode (acfg);
7657 if (!saved_unbox_info) {
7658 char user_symbol [128];
7660 sprintf (user_symbol, "%sunbox_trampoline_p", acfg->user_symbol_prefix);
7662 emit_label (acfg, "ut_end");
7664 unwind_ops = mono_unwind_get_cie_program ();
7665 save_unwind_info (acfg, user_symbol, unwind_ops);
7666 mono_free_unwind_info (unwind_ops);
7668 /* Save the unbox trampoline size */
7669 emit_symbol_diff (acfg, "ut_end", symbol, 0);
7671 saved_unbox_info = TRUE;
7675 if (cfg->compile_llvm)
7676 acfg->stats.llvm_count ++;
7678 emit_method_code (acfg, cfg);
7681 emit_section_change (acfg, ".text", 0);
7682 emit_alignment_code (acfg, 8);
7683 emit_info_symbol (acfg, "jit_code_end");
7685 /* To distinguish it from the next symbol */
7686 emit_padding (acfg, 4);
7689 * Add .no_dead_strip directives for all LLVM methods to prevent the OSX linker
7690 * from optimizing them away, since it doesn't see that code_offsets references them.
7691 * JITted methods don't need this since they are referenced using assembler local
7693 * FIXME: This is why write-symbols doesn't work on OSX ?
7695 if (acfg->llvm && acfg->need_no_dead_strip) {
7696 fprintf (acfg->fp, "\n");
7697 for (i = 0; i < acfg->nmethods; ++i) {
7698 if (acfg->cfgs [i] && acfg->cfgs [i]->compile_llvm)
7699 fprintf (acfg->fp, ".no_dead_strip %s\n", acfg->cfgs [i]->asm_symbol);
7704 * To work around linker issues, we emit a table of branches, and disassemble them at runtime.
7705 * This is PIE code, and the linker can update it if needed.
7707 sprintf (symbol, "method_addresses");
7708 emit_section_change (acfg, ".text", 1);
7709 emit_alignment_code (acfg, 8);
7710 emit_info_symbol (acfg, symbol);
7711 emit_local_symbol (acfg, symbol, "method_addresses_end", TRUE);
7712 emit_unset_mode (acfg);
7713 if (acfg->need_no_dead_strip)
7714 fprintf (acfg->fp, " .no_dead_strip %s\n", symbol);
7716 for (i = 0; i < acfg->nmethods; ++i) {
7717 #ifdef MONO_ARCH_AOT_SUPPORTED
7720 if (acfg->cfgs [i]) {
7721 if (acfg->aot_opts.llvm_only && acfg->cfgs [i]->compile_llvm)
7722 /* Obtained by calling a generated function in the LLVM image */
7723 arch_emit_direct_call (acfg, "method_addresses", FALSE, FALSE, NULL, &call_size);
7725 arch_emit_direct_call (acfg, acfg->cfgs [i]->asm_symbol, FALSE, acfg->thumb_mixed && acfg->cfgs [i]->compile_llvm, NULL, &call_size);
7727 arch_emit_direct_call (acfg, "method_addresses", FALSE, FALSE, NULL, &call_size);
7732 sprintf (symbol, "method_addresses_end");
7733 emit_label (acfg, symbol);
7736 /* Emit a sorted table mapping methods to the index of their unbox trampolines */
7737 sprintf (symbol, "unbox_trampolines");
7738 emit_section_change (acfg, RODATA_SECT, 0);
7739 emit_alignment (acfg, 8);
7740 emit_info_symbol (acfg, symbol);
7743 for (i = 0; i < acfg->nmethods; ++i) {
7748 cfg = acfg->cfgs [i];
7752 method = cfg->orig_method;
7754 if (mono_aot_mode_is_full (&acfg->aot_opts) && cfg->orig_method->klass->valuetype && !(acfg->aot_opts.llvm_only && cfg->compile_llvm)) {
7755 index = get_method_index (acfg, method);
7757 emit_int32 (acfg, index);
7758 /* Make sure the table is sorted by index */
7759 g_assert (index > prev_index);
7763 sprintf (symbol, "unbox_trampolines_end");
7764 emit_info_symbol (acfg, symbol);
7765 emit_int32 (acfg, 0);
7767 /* Emit a separate table with the trampoline addresses/offsets */
7768 sprintf (symbol, "unbox_trampoline_addresses");
7769 emit_section_change (acfg, ".text", 0);
7770 emit_alignment_code (acfg, 8);
7771 emit_info_symbol (acfg, symbol);
7773 for (i = 0; i < acfg->nmethods; ++i) {
7778 cfg = acfg->cfgs [i];
7782 method = cfg->orig_method;
7784 if (mono_aot_mode_is_full (&acfg->aot_opts) && cfg->orig_method->klass->valuetype && !(acfg->aot_opts.llvm_only && cfg->compile_llvm)) {
7785 #ifdef MONO_ARCH_AOT_SUPPORTED
7788 index = get_method_index (acfg, method);
7789 sprintf (symbol, "ut_%d", index);
7791 arch_emit_direct_call (acfg, symbol, FALSE, acfg->thumb_mixed && cfg->compile_llvm, NULL, &call_size);
7795 emit_int32 (acfg, 0);
7799 emit_info (MonoAotCompile *acfg)
7804 offsets = g_new0 (gint32, acfg->nmethods);
7806 for (oindex = 0; oindex < acfg->method_order->len; ++oindex) {
7807 i = GPOINTER_TO_UINT (g_ptr_array_index (acfg->method_order, oindex));
7809 if (acfg->cfgs [i]) {
7810 emit_method_info (acfg, acfg->cfgs [i]);
7811 offsets [i] = acfg->cfgs [i]->method_info_offset;
7817 acfg->stats.offsets_size += emit_offset_table (acfg, "method_info_offsets", acfg->nmethods, 10, offsets);
7822 #endif /* #if !defined(DISABLE_AOT) && !defined(DISABLE_JIT) */
7824 #define rot(x,k) (((x)<<(k)) | ((x)>>(32-(k))))
7825 #define mix(a,b,c) { \
7826 a -= c; a ^= rot(c, 4); c += b; \
7827 b -= a; b ^= rot(a, 6); a += c; \
7828 c -= b; c ^= rot(b, 8); b += a; \
7829 a -= c; a ^= rot(c,16); c += b; \
7830 b -= a; b ^= rot(a,19); a += c; \
7831 c -= b; c ^= rot(b, 4); b += a; \
7833 #define final(a,b,c) { \
7834 c ^= b; c -= rot(b,14); \
7835 a ^= c; a -= rot(c,11); \
7836 b ^= a; b -= rot(a,25); \
7837 c ^= b; c -= rot(b,16); \
7838 a ^= c; a -= rot(c,4); \
7839 b ^= a; b -= rot(a,14); \
7840 c ^= b; c -= rot(b,24); \
7844 mono_aot_type_hash (MonoType *t1)
7846 guint hash = t1->type;
7848 hash |= t1->byref << 6; /* do not collide with t1->type values */
7850 case MONO_TYPE_VALUETYPE:
7851 case MONO_TYPE_CLASS:
7852 case MONO_TYPE_SZARRAY:
7853 /* check if the distribution is good enough */
7854 return ((hash << 5) - hash) ^ mono_metadata_str_hash (t1->data.klass->name);
7856 return ((hash << 5) - hash) ^ mono_metadata_type_hash (t1->data.type);
7857 case MONO_TYPE_ARRAY:
7858 return ((hash << 5) - hash) ^ mono_metadata_type_hash (&t1->data.array->eklass->byval_arg);
7859 case MONO_TYPE_GENERICINST:
7860 return ((hash << 5) - hash) ^ 0;
7867 * mono_aot_method_hash:
7869 * Return a hash code for methods which only depends on metadata.
7872 mono_aot_method_hash (MonoMethod *method)
7874 MonoMethodSignature *sig;
7878 guint32 *hashes_start, *hashes;
7880 MonoGenericInst *class_ginst = NULL;
7881 MonoGenericInst *ginst = NULL;
7883 /* Similar to the hash in mono_method_get_imt_slot () */
7885 sig = mono_method_signature (method);
7887 if (method->klass->generic_class)
7888 class_ginst = method->klass->generic_class->context.class_inst;
7889 if (method->is_inflated)
7890 ginst = ((MonoMethodInflated*)method)->context.method_inst;
7892 hashes_count = sig->param_count + 5 + (class_ginst ? class_ginst->type_argc : 0) + (ginst ? ginst->type_argc : 0);
7893 hashes_start = (guint32 *)g_malloc0 (hashes_count * sizeof (guint32));
7894 hashes = hashes_start;
7896 /* Some wrappers are assigned to random classes */
7897 if (!method->wrapper_type || method->wrapper_type == MONO_WRAPPER_REMOTING_INVOKE_WITH_CHECK)
7898 klass = method->klass;
7900 klass = mono_defaults.object_class;
7902 if (!method->wrapper_type) {
7905 if (klass->generic_class)
7906 full_name = mono_type_full_name (&klass->generic_class->container_class->byval_arg);
7908 full_name = mono_type_full_name (&klass->byval_arg);
7910 hashes [0] = mono_metadata_str_hash (full_name);
7914 hashes [0] = mono_metadata_str_hash (klass->name);
7915 hashes [1] = mono_metadata_str_hash (klass->name_space);
7917 if (method->wrapper_type == MONO_WRAPPER_STFLD || method->wrapper_type == MONO_WRAPPER_LDFLD || method->wrapper_type == MONO_WRAPPER_LDFLDA)
7918 /* The method name includes a stringified pointer */
7921 hashes [2] = mono_metadata_str_hash (method->name);
7922 hashes [3] = method->wrapper_type;
7923 hashes [4] = mono_aot_type_hash (sig->ret);
7925 for (i = 0; i < sig->param_count; i++) {
7926 hashes [hindex ++] = mono_aot_type_hash (sig->params [i]);
7929 for (i = 0; i < class_ginst->type_argc; ++i)
7930 hashes [hindex ++] = mono_aot_type_hash (class_ginst->type_argv [i]);
7933 for (i = 0; i < ginst->type_argc; ++i)
7934 hashes [hindex ++] = mono_aot_type_hash (ginst->type_argv [i]);
7936 g_assert (hindex == hashes_count);
7938 /* Setup internal state */
7939 a = b = c = 0xdeadbeef + (((guint32)hashes_count)<<2);
7941 /* Handle most of the hashes */
7942 while (hashes_count > 3) {
7951 /* Handle the last 3 hashes (all the case statements fall through) */
7952 switch (hashes_count) {
7953 case 3 : c += hashes [2];
7954 case 2 : b += hashes [1];
7955 case 1 : a += hashes [0];
7957 case 0: /* nothing left to add */
7961 free (hashes_start);
7970 * mono_aot_get_array_helper_from_wrapper;
7972 * Get the helper method in Array called by an array wrapper method.
7975 mono_aot_get_array_helper_from_wrapper (MonoMethod *method)
7979 MonoGenericContext ctx;
7980 MonoType *args [16];
7981 char *mname, *iname, *s, *s2, *helper_name = NULL;
7983 prefix = "System.Collections.Generic";
7984 s = g_strdup_printf ("%s", method->name + strlen (prefix) + 1);
7985 s2 = strstr (s, "`1.");
7991 //printf ("X: %s %s\n", iname, mname);
7993 if (!strcmp (iname, "IList"))
7994 helper_name = g_strdup_printf ("InternalArray__%s", mname);
7996 helper_name = g_strdup_printf ("InternalArray__%s_%s", iname, mname);
7997 m = mono_class_get_method_from_name (mono_defaults.array_class, helper_name, mono_method_signature (method)->param_count);
7999 g_free (helper_name);
8002 if (m->is_generic) {
8004 memset (&ctx, 0, sizeof (ctx));
8005 args [0] = &method->klass->element_class->byval_arg;
8006 ctx.method_inst = mono_metadata_get_generic_inst (1, args);
8007 m = mono_class_inflate_generic_method_checked (m, &ctx, &error);
8008 g_assert (mono_error_ok (&error)); /* FIXME don't swallow the error */
8014 #if !defined(DISABLE_AOT) && !defined(DISABLE_JIT)
8016 typedef struct HashEntry {
8017 guint32 key, value, index;
8018 struct HashEntry *next;
8022 * emit_extra_methods:
8024 * Emit methods which are not in the METHOD table, like wrappers.
8027 emit_extra_methods (MonoAotCompile *acfg)
8029 int i, table_size, buf_size;
8032 guint32 *info_offsets;
8035 HashEntry *entry, *new_entry;
8036 int nmethods, max_chain_length;
8039 info_offsets = g_new0 (guint32, acfg->extra_methods->len);
8041 /* Emit method info */
8043 for (i = 0; i < acfg->extra_methods->len; ++i) {
8044 MonoMethod *method = (MonoMethod *)g_ptr_array_index (acfg->extra_methods, i);
8045 MonoCompile *cfg = (MonoCompile *)g_hash_table_lookup (acfg->method_to_cfg, method);
8051 p = buf = (guint8 *)g_malloc (buf_size);
8055 method = cfg->method_to_register;
8057 encode_method_ref (acfg, method, p, &p);
8059 g_assert ((p - buf) < buf_size);
8061 info_offsets [i] = add_to_blob (acfg, buf, p - buf);
8066 * Construct a chained hash table for mapping indexes in extra_method_info to
8069 table_size = g_spaced_primes_closest ((int)(nmethods * 1.5));
8070 table = g_ptr_array_sized_new (table_size);
8071 for (i = 0; i < table_size; ++i)
8072 g_ptr_array_add (table, NULL);
8073 chain_lengths = g_new0 (int, table_size);
8074 max_chain_length = 0;
8075 for (i = 0; i < acfg->extra_methods->len; ++i) {
8076 MonoMethod *method = (MonoMethod *)g_ptr_array_index (acfg->extra_methods, i);
8077 MonoCompile *cfg = (MonoCompile *)g_hash_table_lookup (acfg->method_to_cfg, method);
8083 key = info_offsets [i];
8084 value = get_method_index (acfg, method);
8086 hash = mono_aot_method_hash (method) % table_size;
8087 //printf ("X: %s %x\n", mono_method_full_name (method, 1), mono_aot_method_hash (method));
8089 chain_lengths [hash] ++;
8090 max_chain_length = MAX (max_chain_length, chain_lengths [hash]);
8092 new_entry = (HashEntry *)mono_mempool_alloc0 (acfg->mempool, sizeof (HashEntry));
8093 new_entry->key = key;
8094 new_entry->value = value;
8096 entry = (HashEntry *)g_ptr_array_index (table, hash);
8097 if (entry == NULL) {
8098 new_entry->index = hash;
8099 g_ptr_array_index (table, hash) = new_entry;
8102 entry = entry->next;
8104 entry->next = new_entry;
8105 new_entry->index = table->len;
8106 g_ptr_array_add (table, new_entry);
8110 //printf ("MAX: %d\n", max_chain_length);
8112 buf_size = table->len * 12 + 4;
8113 p = buf = (guint8 *)g_malloc (buf_size);
8114 encode_int (table_size, p, &p);
8116 for (i = 0; i < table->len; ++i) {
8117 HashEntry *entry = (HashEntry *)g_ptr_array_index (table, i);
8119 if (entry == NULL) {
8120 encode_int (0, p, &p);
8121 encode_int (0, p, &p);
8122 encode_int (0, p, &p);
8124 //g_assert (entry->key > 0);
8125 encode_int (entry->key, p, &p);
8126 encode_int (entry->value, p, &p);
8128 encode_int (entry->next->index, p, &p);
8130 encode_int (0, p, &p);
8133 g_assert (p - buf <= buf_size);
8135 /* Emit the table */
8137 mono_llvm_emit_aot_data ("extra_method_table", buf, p - buf);
8139 sprintf (symbol, "extra_method_table");
8140 emit_section_change (acfg, RODATA_SECT, 0);
8141 emit_alignment (acfg, 8);
8142 emit_label (acfg, symbol);
8143 emit_bytes (acfg, buf, p - buf);
8147 * Emit a table reverse mapping method indexes to their index in extra_method_info.
8148 * This is used by mono_aot_find_jit_info ().
8150 buf_size = acfg->extra_methods->len * 8 + 4;
8151 p = buf = (guint8 *)g_malloc (buf_size);
8152 encode_int (acfg->extra_methods->len, p, &p);
8153 for (i = 0; i < acfg->extra_methods->len; ++i) {
8154 MonoMethod *method = (MonoMethod *)g_ptr_array_index (acfg->extra_methods, i);
8156 encode_int (get_method_index (acfg, method), p, &p);
8157 encode_int (info_offsets [i], p, &p);
8160 mono_llvm_emit_aot_data ("extra_method_info_offsets", buf, p - buf);
8162 sprintf (symbol, "extra_method_info_offsets");
8163 emit_section_change (acfg, RODATA_SECT, 0);
8164 emit_alignment (acfg, 8);
8165 emit_label (acfg, symbol);
8166 emit_bytes (acfg, buf, p - buf);
8171 emit_exception_info (MonoAotCompile *acfg)
8175 SeqPointData sp_data;
8176 gboolean seq_points_to_file = FALSE;
8178 offsets = g_new0 (gint32, acfg->nmethods);
8179 for (i = 0; i < acfg->nmethods; ++i) {
8180 if (acfg->cfgs [i]) {
8181 MonoCompile *cfg = acfg->cfgs [i];
8183 // By design aot-runtime decode_exception_debug_info is not able to load sequence point debug data from a file.
8184 // As it is not possible to load debug data from a file its is also not possible to store it in a file.
8185 gboolean method_seq_points_to_file = acfg->aot_opts.gen_seq_points_file &&
8186 cfg->gen_seq_points && !cfg->gen_sdb_seq_points;
8187 gboolean method_seq_points_to_binary = cfg->gen_seq_points && !method_seq_points_to_file;
8189 emit_exception_debug_info (acfg, cfg, method_seq_points_to_binary);
8190 offsets [i] = cfg->ex_info_offset;
8192 if (method_seq_points_to_file) {
8193 if (!seq_points_to_file) {
8194 mono_seq_point_data_init (&sp_data, acfg->nmethods);
8195 seq_points_to_file = TRUE;
8197 mono_seq_point_data_add (&sp_data, cfg->method->token, cfg->method_index, cfg->seq_point_info);
8204 if (seq_points_to_file) {
8205 char *seq_points_aot_file;
8206 mono_image_get_aot_seq_point_path (acfg->image, &seq_points_aot_file);
8207 mono_seq_point_data_write (&sp_data, seq_points_aot_file);
8208 mono_seq_point_data_free (&sp_data);
8209 g_free (seq_points_aot_file);
8212 acfg->stats.offsets_size += emit_offset_table (acfg, "ex_info_offsets", acfg->nmethods, 10, offsets);
8217 emit_unwind_info (MonoAotCompile *acfg)
8222 if (acfg->aot_opts.llvm_only) {
8223 g_assert (acfg->unwind_ops->len == 0);
8228 * The unwind info contains a lot of duplicates so we emit each unique
8229 * entry once, and only store the offset from the start of the table in the
8233 sprintf (symbol, "unwind_info");
8234 emit_section_change (acfg, RODATA_SECT, 1);
8235 emit_alignment (acfg, 8);
8236 emit_info_symbol (acfg, symbol);
8238 for (i = 0; i < acfg->unwind_ops->len; ++i) {
8239 guint32 index = GPOINTER_TO_UINT (g_ptr_array_index (acfg->unwind_ops, i));
8240 guint8 *unwind_info;
8241 guint32 unwind_info_len;
8245 unwind_info = mono_get_cached_unwind_info (index, &unwind_info_len);
8248 encode_value (unwind_info_len, p, &p);
8249 emit_bytes (acfg, buf, p - buf);
8250 emit_bytes (acfg, unwind_info, unwind_info_len);
8252 acfg->stats.unwind_info_size += (p - buf) + unwind_info_len;
8257 emit_class_info (MonoAotCompile *acfg)
8262 offsets = g_new0 (gint32, acfg->image->tables [MONO_TABLE_TYPEDEF].rows);
8263 for (i = 0; i < acfg->image->tables [MONO_TABLE_TYPEDEF].rows; ++i)
8264 offsets [i] = emit_klass_info (acfg, MONO_TOKEN_TYPE_DEF | (i + 1));
8266 acfg->stats.offsets_size += emit_offset_table (acfg, "class_info_offsets", acfg->image->tables [MONO_TABLE_TYPEDEF].rows, 10, offsets);
8270 typedef struct ClassNameTableEntry {
8271 guint32 token, index;
8272 struct ClassNameTableEntry *next;
8273 } ClassNameTableEntry;
8276 emit_class_name_table (MonoAotCompile *acfg)
8278 int i, table_size, buf_size;
8279 guint32 token, hash;
8285 ClassNameTableEntry *entry, *new_entry;
8288 * Construct a chained hash table for mapping class names to typedef tokens.
8290 table_size = g_spaced_primes_closest ((int)(acfg->image->tables [MONO_TABLE_TYPEDEF].rows * 1.5));
8291 table = g_ptr_array_sized_new (table_size);
8292 for (i = 0; i < table_size; ++i)
8293 g_ptr_array_add (table, NULL);
8294 for (i = 0; i < acfg->image->tables [MONO_TABLE_TYPEDEF].rows; ++i) {
8296 token = MONO_TOKEN_TYPE_DEF | (i + 1);
8297 klass = mono_class_get_checked (acfg->image, token, &error);
8299 mono_error_cleanup (&error);
8302 full_name = mono_type_get_name_full (mono_class_get_type (klass), MONO_TYPE_NAME_FORMAT_FULL_NAME);
8303 hash = mono_metadata_str_hash (full_name) % table_size;
8306 /* FIXME: Allocate from the mempool */
8307 new_entry = g_new0 (ClassNameTableEntry, 1);
8308 new_entry->token = token;
8310 entry = (ClassNameTableEntry *)g_ptr_array_index (table, hash);
8311 if (entry == NULL) {
8312 new_entry->index = hash;
8313 g_ptr_array_index (table, hash) = new_entry;
8316 entry = entry->next;
8318 entry->next = new_entry;
8319 new_entry->index = table->len;
8320 g_ptr_array_add (table, new_entry);
8324 /* Emit the table */
8325 buf_size = table->len * 4 + 4;
8326 p = buf = (guint8 *)g_malloc0 (buf_size);
8328 /* FIXME: Optimize memory usage */
8329 g_assert (table_size < 65000);
8330 encode_int16 (table_size, p, &p);
8331 g_assert (table->len < 65000);
8332 for (i = 0; i < table->len; ++i) {
8333 ClassNameTableEntry *entry = (ClassNameTableEntry *)g_ptr_array_index (table, i);
8335 if (entry == NULL) {
8336 encode_int16 (0, p, &p);
8337 encode_int16 (0, p, &p);
8339 encode_int16 (mono_metadata_token_index (entry->token), p, &p);
8341 encode_int16 (entry->next->index, p, &p);
8343 encode_int16 (0, p, &p);
8346 g_assert (p - buf <= buf_size);
8349 mono_llvm_emit_aot_data ("class_name_table", buf, p - buf);
8351 sprintf (symbol, "class_name_table");
8352 emit_section_change (acfg, RODATA_SECT, 0);
8353 emit_alignment (acfg, 8);
8354 emit_label (acfg, symbol);
8355 emit_bytes (acfg, buf, p - buf);
8360 emit_image_table (MonoAotCompile *acfg)
8367 * The image table is small but referenced in a lot of places.
8368 * So we emit it at once, and reference its elements by an index.
8370 buf_size = acfg->image_table->len * 28 + 4;
8371 for (i = 0; i < acfg->image_table->len; i++) {
8372 MonoImage *image = (MonoImage*)g_ptr_array_index (acfg->image_table, i);
8373 MonoAssemblyName *aname = &image->assembly->aname;
8375 buf_size += strlen (image->assembly_name) + strlen (image->guid) + (aname->culture ? strlen (aname->culture) : 1) + strlen ((char*)aname->public_key_token) + 4;
8378 buf = p = (guint8 *)g_malloc0 (buf_size);
8379 encode_int (acfg->image_table->len, p, &p);
8380 for (i = 0; i < acfg->image_table->len; i++) {
8381 MonoImage *image = (MonoImage*)g_ptr_array_index (acfg->image_table, i);
8382 MonoAssemblyName *aname = &image->assembly->aname;
8384 /* FIXME: Support multi-module assemblies */
8385 g_assert (image->assembly->image == image);
8387 encode_string (image->assembly_name, p, &p);
8388 encode_string (image->guid, p, &p);
8389 encode_string (aname->culture ? aname->culture : "", p, &p);
8390 encode_string ((const char*)aname->public_key_token, p, &p);
8392 while (GPOINTER_TO_UINT (p) % 8 != 0)
8395 encode_int (aname->flags, p, &p);
8396 encode_int (aname->major, p, &p);
8397 encode_int (aname->minor, p, &p);
8398 encode_int (aname->build, p, &p);
8399 encode_int (aname->revision, p, &p);
8401 g_assert (p - buf <= buf_size);
8404 mono_llvm_emit_aot_data ("image_table", buf, p - buf);
8406 sprintf (symbol, "image_table");
8407 emit_section_change (acfg, RODATA_SECT, 1);
8408 emit_alignment (acfg, 8);
8409 emit_label (acfg, symbol);
8410 emit_bytes (acfg, buf, p - buf);
8417 emit_got_info (MonoAotCompile *acfg, gboolean llvm)
8419 int i, first_plt_got_patch = 0, buf_size;
8421 guint32 *got_info_offsets;
8422 GotInfo *info = llvm ? &acfg->llvm_got_info : &acfg->got_info;
8424 /* Add the patches needed by the PLT to the GOT */
8426 acfg->plt_got_offset_base = acfg->got_offset;
8427 first_plt_got_patch = info->got_patches->len;
8428 for (i = 1; i < acfg->plt_offset; ++i) {
8429 MonoPltEntry *plt_entry = (MonoPltEntry *)g_hash_table_lookup (acfg->plt_offset_to_entry, GUINT_TO_POINTER (i));
8431 g_ptr_array_add (info->got_patches, plt_entry->ji);
8433 acfg->stats.got_slot_types [plt_entry->ji->type] ++;
8436 acfg->got_offset += acfg->plt_offset;
8441 * - optimize offsets table.
8442 * - reduce number of exported symbols.
8443 * - emit info for a klass only once.
8444 * - determine when a method uses a GOT slot which is guaranteed to be already
8446 * - clean up and document the code.
8447 * - use String.Empty in class libs.
8450 /* Encode info required to decode shared GOT entries */
8451 buf_size = info->got_patches->len * 128;
8452 p = buf = (guint8 *)mono_mempool_alloc (acfg->mempool, buf_size);
8453 got_info_offsets = (guint32 *)mono_mempool_alloc (acfg->mempool, info->got_patches->len * sizeof (guint32));
8455 acfg->plt_got_info_offsets = (guint32 *)mono_mempool_alloc (acfg->mempool, acfg->plt_offset * sizeof (guint32));
8457 if (acfg->plt_offset)
8458 acfg->plt_got_info_offsets [0] = 0;
8460 for (i = 0; i < info->got_patches->len; ++i) {
8461 MonoJumpInfo *ji = (MonoJumpInfo *)g_ptr_array_index (info->got_patches, i);
8466 encode_value (ji->type, p, &p);
8468 encode_patch (acfg, ji, p, &p);
8469 acfg->stats.got_slot_info_sizes [ji->type] += p - p2;
8470 g_assert (p - buf <= buf_size);
8471 got_info_offsets [i] = add_to_blob (acfg, buf, p - buf);
8473 if (!llvm && i >= first_plt_got_patch)
8474 acfg->plt_got_info_offsets [i - first_plt_got_patch + 1] = got_info_offsets [i];
8475 acfg->stats.got_info_size += p - buf;
8478 /* Emit got_info_offsets table */
8480 /* No need to emit offsets for the got plt entries, the plt embeds them directly */
8481 acfg->stats.offsets_size += emit_offset_table (acfg, llvm ? "llvm_got_info_offsets" : "got_info_offsets", llvm ? acfg->llvm_got_offset : first_plt_got_patch, 10, (gint32*)got_info_offsets);
8485 emit_got (MonoAotCompile *acfg)
8489 if (acfg->aot_opts.llvm_only)
8492 /* Don't make GOT global so accesses to it don't need relocations */
8493 sprintf (symbol, "%s", acfg->got_symbol);
8496 emit_unset_mode (acfg);
8497 fprintf (acfg->fp, ".section __DATA, __bss\n");
8498 emit_alignment (acfg, 8);
8500 emit_info_symbol (acfg, "jit_got");
8501 fprintf (acfg->fp, ".lcomm %s, %d\n", acfg->got_symbol, (int)(acfg->got_offset * sizeof (gpointer)));
8503 emit_section_change (acfg, ".bss", 0);
8504 emit_alignment (acfg, 8);
8505 emit_local_symbol (acfg, symbol, "got_end", FALSE);
8506 emit_label (acfg, symbol);
8508 emit_info_symbol (acfg, "jit_got");
8509 if (acfg->got_offset > 0)
8510 emit_zero_bytes (acfg, (int)(acfg->got_offset * sizeof (gpointer)));
8513 sprintf (symbol, "got_end");
8514 emit_label (acfg, symbol);
8517 typedef struct GlobalsTableEntry {
8518 guint32 value, index;
8519 struct GlobalsTableEntry *next;
8520 } GlobalsTableEntry;
8523 emit_globals (MonoAotCompile *acfg)
8529 GlobalsTableEntry *entry, *new_entry;
8531 if (!acfg->aot_opts.static_link)
8535 * When static linking, we emit a table containing our globals.
8539 * Construct a chained hash table for mapping global names to their index in
8540 * the globals table.
8542 table_size = g_spaced_primes_closest ((int)(acfg->globals->len * 1.5));
8543 table = g_ptr_array_sized_new (table_size);
8544 for (i = 0; i < table_size; ++i)
8545 g_ptr_array_add (table, NULL);
8546 for (i = 0; i < acfg->globals->len; ++i) {
8547 char *name = (char *)g_ptr_array_index (acfg->globals, i);
8549 hash = mono_metadata_str_hash (name) % table_size;
8551 /* FIXME: Allocate from the mempool */
8552 new_entry = g_new0 (GlobalsTableEntry, 1);
8553 new_entry->value = i;
8555 entry = (GlobalsTableEntry *)g_ptr_array_index (table, hash);
8556 if (entry == NULL) {
8557 new_entry->index = hash;
8558 g_ptr_array_index (table, hash) = new_entry;
8561 entry = entry->next;
8563 entry->next = new_entry;
8564 new_entry->index = table->len;
8565 g_ptr_array_add (table, new_entry);
8569 /* Emit the table */
8570 sprintf (symbol, ".Lglobals_hash");
8571 emit_section_change (acfg, RODATA_SECT, 0);
8572 emit_alignment (acfg, 8);
8573 emit_label (acfg, symbol);
8575 /* FIXME: Optimize memory usage */
8576 g_assert (table_size < 65000);
8577 emit_int16 (acfg, table_size);
8578 for (i = 0; i < table->len; ++i) {
8579 GlobalsTableEntry *entry = (GlobalsTableEntry *)g_ptr_array_index (table, i);
8581 if (entry == NULL) {
8582 emit_int16 (acfg, 0);
8583 emit_int16 (acfg, 0);
8585 emit_int16 (acfg, entry->value + 1);
8587 emit_int16 (acfg, entry->next->index);
8589 emit_int16 (acfg, 0);
8593 /* Emit the names */
8594 for (i = 0; i < acfg->globals->len; ++i) {
8595 char *name = (char *)g_ptr_array_index (acfg->globals, i);
8597 sprintf (symbol, "name_%d", i);
8598 emit_section_change (acfg, RODATA_SECT, 1);
8600 emit_alignment (acfg, 4);
8602 emit_label (acfg, symbol);
8603 emit_string (acfg, name);
8606 /* Emit the globals table */
8607 sprintf (symbol, "globals");
8608 emit_section_change (acfg, ".data", 0);
8609 /* This is not a global, since it is accessed by the init function */
8610 emit_alignment (acfg, 8);
8611 emit_info_symbol (acfg, symbol);
8613 sprintf (symbol, "%sglobals_hash", acfg->temp_prefix);
8614 emit_pointer (acfg, symbol);
8616 for (i = 0; i < acfg->globals->len; ++i) {
8617 char *name = (char *)g_ptr_array_index (acfg->globals, i);
8619 sprintf (symbol, "name_%d", i);
8620 emit_pointer (acfg, symbol);
8622 g_assert (strlen (name) < sizeof (symbol));
8623 sprintf (symbol, "%s", name);
8624 emit_pointer (acfg, symbol);
8626 /* Null terminate the table */
8627 emit_int32 (acfg, 0);
8628 emit_int32 (acfg, 0);
8632 emit_mem_end (MonoAotCompile *acfg)
8636 if (acfg->aot_opts.llvm_only)
8639 sprintf (symbol, "mem_end");
8640 emit_section_change (acfg, ".text", 1);
8641 emit_alignment_code (acfg, 8);
8642 emit_label (acfg, symbol);
8646 init_aot_file_info (MonoAotCompile *acfg, MonoAotFileInfo *info, int gc_name_offset)
8650 info->version = MONO_AOT_FILE_VERSION;
8651 info->plt_got_offset_base = acfg->plt_got_offset_base;
8652 info->got_size = acfg->got_offset * sizeof (gpointer);
8653 info->plt_size = acfg->plt_offset;
8654 info->nmethods = acfg->nmethods;
8655 info->flags = acfg->flags;
8656 info->opts = acfg->opts;
8657 info->simd_opts = acfg->simd_opts;
8658 info->gc_name_index = gc_name_offset;
8659 for (i = 0; i < MONO_AOT_TRAMP_NUM; ++i)
8660 info->num_trampolines [i] = acfg->num_trampolines [i];
8661 for (i = 0; i < MONO_AOT_TRAMP_NUM; ++i)
8662 info->trampoline_got_offset_base [i] = acfg->trampoline_got_offset_base [i];
8663 for (i = 0; i < MONO_AOT_TRAMP_NUM; ++i)
8664 info->trampoline_size [i] = acfg->trampoline_size [i];
8665 info->num_rgctx_fetch_trampolines = acfg->aot_opts.nrgctx_fetch_trampolines;
8667 info->double_align = MONO_ABI_ALIGNOF (double);
8668 info->long_align = MONO_ABI_ALIGNOF (gint64);
8669 info->generic_tramp_num = MONO_TRAMPOLINE_NUM;
8670 info->tramp_page_size = acfg->tramp_page_size;
8671 info->nshared_got_entries = acfg->nshared_got_entries;
8672 for (i = 0; i < MONO_AOT_TRAMP_NUM; ++i)
8673 info->tramp_page_code_offsets [i] = acfg->tramp_page_code_offsets [i];
8677 emit_aot_file_info (MonoAotCompile *acfg, MonoAotFileInfo *info)
8681 const char **symbols;
8683 symbols = g_new0 (const char *, MONO_AOT_FILE_INFO_NUM_SYMBOLS);
8685 symbols [sindex ++] = acfg->got_symbol;
8687 symbols [sindex ++] = g_strdup_printf ("%s%s", acfg->user_symbol_prefix, acfg->llvm_got_symbol);
8688 symbols [sindex ++] = acfg->llvm_eh_frame_symbol;
8690 symbols [sindex ++] = NULL;
8691 symbols [sindex ++] = NULL;
8693 /* llvm_get_method */
8694 symbols [sindex ++] = NULL;
8695 /* llvm_get_unbox_tramp */
8696 symbols [sindex ++] = NULL;
8697 if (!acfg->aot_opts.llvm_only) {
8698 symbols [sindex ++] = "jit_code_start";
8699 symbols [sindex ++] = "jit_code_end";
8700 symbols [sindex ++] = "method_addresses";
8702 symbols [sindex ++] = NULL;
8703 symbols [sindex ++] = NULL;
8704 symbols [sindex ++] = NULL;
8706 symbols [sindex ++] = "blob";
8707 symbols [sindex ++] = "class_name_table";
8708 symbols [sindex ++] = "class_info_offsets";
8709 symbols [sindex ++] = "method_info_offsets";
8710 symbols [sindex ++] = "ex_info_offsets";
8711 symbols [sindex ++] = "extra_method_info_offsets";
8712 symbols [sindex ++] = "extra_method_table";
8713 symbols [sindex ++] = "got_info_offsets";
8715 symbols [sindex ++] = "llvm_got_info_offsets";
8717 symbols [sindex ++] = NULL;
8718 symbols [sindex ++] = "mem_end";
8719 symbols [sindex ++] = "image_table";
8720 symbols [sindex ++] = "assembly_guid";
8721 symbols [sindex ++] = "runtime_version";
8722 if (acfg->num_trampoline_got_entries) {
8723 symbols [sindex ++] = "specific_trampolines";
8724 symbols [sindex ++] = "static_rgctx_trampolines";
8725 symbols [sindex ++] = "imt_thunks";
8726 symbols [sindex ++] = "gsharedvt_arg_trampolines";
8728 symbols [sindex ++] = NULL;
8729 symbols [sindex ++] = NULL;
8730 symbols [sindex ++] = NULL;
8731 symbols [sindex ++] = NULL;
8733 if (acfg->aot_opts.static_link) {
8734 symbols [sindex ++] = "globals";
8736 symbols [sindex ++] = NULL;
8738 symbols [sindex ++] = "assembly_name";
8739 symbols [sindex ++] = "plt";
8740 symbols [sindex ++] = "plt_end";
8741 symbols [sindex ++] = "unwind_info";
8742 if (!acfg->aot_opts.llvm_only) {
8743 symbols [sindex ++] = "unbox_trampolines";
8744 symbols [sindex ++] = "unbox_trampolines_end";
8745 symbols [sindex ++] = "unbox_trampoline_addresses";
8747 symbols [sindex ++] = NULL;
8748 symbols [sindex ++] = NULL;
8749 symbols [sindex ++] = NULL;
8752 g_assert (sindex == MONO_AOT_FILE_INFO_NUM_SYMBOLS);
8754 sprintf (symbol, "%smono_aot_file_info", acfg->user_symbol_prefix);
8755 emit_section_change (acfg, ".data", 0);
8756 emit_alignment (acfg, 8);
8757 emit_label (acfg, symbol);
8758 if (!acfg->aot_opts.static_link)
8759 emit_global (acfg, symbol, FALSE);
8761 /* The data emitted here must match MonoAotFileInfo. */
8763 emit_int32 (acfg, info->version);
8764 emit_int32 (acfg, info->dummy);
8767 * We emit pointers to our data structures instead of emitting global symbols which
8768 * point to them, to reduce the number of globals, and because using globals leads to
8769 * various problems (i.e. arm/thumb).
8771 for (i = 0; i < MONO_AOT_FILE_INFO_NUM_SYMBOLS; ++i)
8772 emit_pointer (acfg, symbols [i]);
8774 emit_int32 (acfg, info->plt_got_offset_base);
8775 emit_int32 (acfg, info->got_size);
8776 emit_int32 (acfg, info->plt_size);
8777 emit_int32 (acfg, info->nmethods);
8778 emit_int32 (acfg, info->flags);
8779 emit_int32 (acfg, info->opts);
8780 emit_int32 (acfg, info->simd_opts);
8781 emit_int32 (acfg, info->gc_name_index);
8782 emit_int32 (acfg, info->num_rgctx_fetch_trampolines);
8783 emit_int32 (acfg, info->double_align);
8784 emit_int32 (acfg, info->long_align);
8785 emit_int32 (acfg, info->generic_tramp_num);
8786 emit_int32 (acfg, info->tramp_page_size);
8787 emit_int32 (acfg, info->nshared_got_entries);
8789 for (i = 0; i < MONO_AOT_TRAMP_NUM; ++i)
8790 emit_int32 (acfg, info->num_trampolines [i]);
8791 for (i = 0; i < MONO_AOT_TRAMP_NUM; ++i)
8792 emit_int32 (acfg, info->trampoline_got_offset_base [i]);
8793 for (i = 0; i < MONO_AOT_TRAMP_NUM; ++i)
8794 emit_int32 (acfg, info->trampoline_size [i]);
8795 for (i = 0; i < MONO_AOT_TRAMP_NUM; ++i)
8796 emit_int32 (acfg, info->tramp_page_code_offsets [i]);
8798 if (acfg->aot_opts.static_link) {
8802 * Emit a global symbol which can be passed by an embedding app to
8803 * mono_aot_register_module (). The symbol points to a pointer to the the file info
8806 sprintf (symbol, "%smono_aot_module_%s_info", acfg->user_symbol_prefix, acfg->image->assembly->aname.name);
8808 /* Get rid of characters which cannot occur in symbols */
8810 for (p = symbol; *p; ++p) {
8811 if (!(isalnum (*p) || *p == '_'))
8814 acfg->static_linking_symbol = g_strdup (symbol);
8815 emit_global_inner (acfg, symbol, FALSE);
8816 emit_alignment (acfg, sizeof (gpointer));
8817 emit_label (acfg, symbol);
8818 emit_pointer_2 (acfg, acfg->user_symbol_prefix, "mono_aot_file_info");
8823 * Emit a structure containing all the information not stored elsewhere.
8826 emit_file_info (MonoAotCompile *acfg)
8829 const char *gc_name;
8831 MonoAotFileInfo *info;
8833 if (acfg->aot_opts.bind_to_runtime_version) {
8834 build_info = mono_get_runtime_build_info ();
8835 emit_string_symbol (acfg, "runtime_version", build_info);
8836 g_free (build_info);
8838 emit_string_symbol (acfg, "runtime_version", "");
8841 emit_string_symbol (acfg, "assembly_guid" , acfg->image->guid);
8843 /* Emit a string holding the assembly name */
8844 emit_string_symbol (acfg, "assembly_name", acfg->image->assembly->aname.name);
8847 * The managed allocators are GC specific, so can't use an AOT image created by one GC
8850 gc_name = mono_gc_get_gc_name ();
8851 gc_name_offset = add_to_blob (acfg, (guint8*)gc_name, strlen (gc_name) + 1);
8853 info = g_new0 (MonoAotFileInfo, 1);
8854 init_aot_file_info (acfg, info, gc_name_offset);
8857 mono_llvm_emit_aot_file_info (info, acfg->has_jitted_code);
8859 emit_aot_file_info (acfg, info);
8863 emit_blob (MonoAotCompile *acfg)
8868 mono_llvm_emit_aot_data ("blob", (guint8*)acfg->blob.data, acfg->blob.index);
8872 sprintf (symbol, "blob");
8873 emit_section_change (acfg, RODATA_SECT, 1);
8874 emit_alignment (acfg, 8);
8875 emit_label (acfg, symbol);
8877 emit_bytes (acfg, (guint8*)acfg->blob.data, acfg->blob.index);
8881 emit_objc_selectors (MonoAotCompile *acfg)
8886 if (!acfg->objc_selectors || acfg->objc_selectors->len == 0)
8891 * cat > foo.m << EOF
8894 * return @selector(print:);
8899 mono_img_writer_emit_unset_mode (acfg->w);
8900 g_assert (acfg->fp);
8901 fprintf (acfg->fp, ".section __DATA,__objc_selrefs,literal_pointers,no_dead_strip\n");
8902 fprintf (acfg->fp, ".align 3\n");
8903 for (i = 0; i < acfg->objc_selectors->len; ++i) {
8904 sprintf (symbol, "L_OBJC_SELECTOR_REFERENCES_%d", i);
8905 emit_label (acfg, symbol);
8906 sprintf (symbol, "L_OBJC_METH_VAR_NAME_%d", i);
8907 emit_pointer (acfg, symbol);
8910 fprintf (acfg->fp, ".section __TEXT,__cstring,cstring_literals\n");
8911 for (i = 0; i < acfg->objc_selectors->len; ++i) {
8912 fprintf (acfg->fp, "L_OBJC_METH_VAR_NAME_%d:\n", i);
8913 fprintf (acfg->fp, ".asciz \"%s\"\n", (char*)g_ptr_array_index (acfg->objc_selectors, i));
8916 fprintf (acfg->fp, ".section __DATA,__objc_imageinfo,regular,no_dead_strip\n");
8917 fprintf (acfg->fp, ".align 3\n");
8918 fprintf (acfg->fp, "L_OBJC_IMAGE_INFO:\n");
8919 fprintf (acfg->fp, ".long 0\n");
8920 fprintf (acfg->fp, ".long 16\n");
8924 emit_dwarf_info (MonoAotCompile *acfg)
8926 #ifdef EMIT_DWARF_INFO
8930 /* DIEs for methods */
8931 for (i = 0; i < acfg->nmethods; ++i) {
8932 MonoCompile *cfg = acfg->cfgs [i];
8937 // FIXME: LLVM doesn't define .Lme_...
8938 if (cfg->compile_llvm)
8941 sprintf (symbol2, "%sme_%x", acfg->temp_prefix, i);
8943 mono_dwarf_writer_emit_method (acfg->dwarf, cfg, cfg->method, cfg->asm_symbol, symbol2, cfg->asm_debug_symbol, (guint8 *)cfg->jit_info->code_start, cfg->jit_info->code_size, cfg->args, cfg->locals, cfg->unwind_ops, mono_debug_find_method (cfg->jit_info->d.method, mono_domain_get ()));
8949 collect_methods (MonoAotCompile *acfg)
8952 MonoImage *image = acfg->image;
8954 /* Collect methods */
8955 for (i = 0; i < image->tables [MONO_TABLE_METHOD].rows; ++i) {
8958 guint32 token = MONO_TOKEN_METHOD_DEF | (i + 1);
8960 method = mono_get_method_checked (acfg->image, token, NULL, NULL, &error);
8963 aot_printerrf (acfg, "Failed to load method 0x%x from '%s' due to %s.\n", token, image->name, mono_error_get_message (&error));
8964 aot_printerrf (acfg, "Run with MONO_LOG_LEVEL=debug for more information.\n");
8965 mono_error_cleanup (&error);
8969 /* Load all methods eagerly to skip the slower lazy loading code */
8970 mono_class_setup_methods (method->klass);
8972 if (mono_aot_mode_is_full (&acfg->aot_opts) && method->iflags & METHOD_IMPL_ATTRIBUTE_INTERNAL_CALL) {
8973 /* Compile the wrapper instead */
8974 /* We do this here instead of add_wrappers () because it is easy to do it here */
8975 MonoMethod *wrapper = mono_marshal_get_native_wrapper (method, TRUE, TRUE);
8979 /* FIXME: Some mscorlib methods don't have debug info */
8981 if (acfg->aot_opts.soft_debug && !method->wrapper_type) {
8982 if (!((method->flags & METHOD_ATTRIBUTE_PINVOKE_IMPL) ||
8983 (method->iflags & METHOD_IMPL_ATTRIBUTE_RUNTIME) ||
8984 (method->flags & METHOD_ATTRIBUTE_ABSTRACT) ||
8985 (method->iflags & METHOD_IMPL_ATTRIBUTE_INTERNAL_CALL))) {
8986 if (!mono_debug_lookup_method (method)) {
8987 fprintf (stderr, "Method %s has no debug info, probably the .mdb file for the assembly is missing.\n", mono_method_full_name (method, TRUE));
8994 if (method->is_generic || method->klass->generic_container)
8995 /* Compile the ref shared version instead */
8996 method = mini_get_shared_method (method);
8998 /* Since we add the normal methods first, their index will be equal to their zero based token index */
8999 add_method_with_index (acfg, method, i, FALSE);
9000 acfg->method_index ++;
9003 /* gsharedvt methods */
9004 for (mindex = 0; mindex < image->tables [MONO_TABLE_METHOD].rows; ++mindex) {
9007 guint32 token = MONO_TOKEN_METHOD_DEF | (mindex + 1);
9009 if (!(acfg->opts & MONO_OPT_GSHAREDVT))
9012 method = mono_get_method_checked (acfg->image, token, NULL, NULL, &error);
9013 report_loader_error (acfg, &error, "Failed to load method token 0x%x due to %s\n", i, mono_error_get_message (&error));
9015 if (method->is_generic || method->klass->generic_container) {
9016 MonoMethod *gshared;
9018 gshared = mini_get_shared_method_full (method, TRUE, TRUE);
9019 add_extra_method (acfg, gshared);
9023 add_generic_instances (acfg);
9025 if (mono_aot_mode_is_full (&acfg->aot_opts))
9026 add_wrappers (acfg);
9031 compile_methods (MonoAotCompile *acfg)
9035 if (acfg->aot_opts.nthreads > 0) {
9040 gpointer *user_data;
9041 MonoMethod **methods;
9043 methods_len = acfg->methods->len;
9045 len = acfg->methods->len / acfg->aot_opts.nthreads;
9048 * Partition the list of methods into fragments, and hand it to threads to
9051 threads = g_ptr_array_new ();
9052 /* Make a copy since acfg->methods is modified by compile_method () */
9053 methods = g_new0 (MonoMethod*, methods_len);
9054 //memcpy (methods, g_ptr_array_index (acfg->methods, 0), sizeof (MonoMethod*) * methods_len);
9055 for (i = 0; i < methods_len; ++i)
9056 methods [i] = (MonoMethod *)g_ptr_array_index (acfg->methods, i);
9058 while (i < methods_len) {
9059 frag = g_ptr_array_new ();
9060 for (j = 0; j < len; ++j) {
9061 if (i < methods_len) {
9062 g_ptr_array_add (frag, methods [i]);
9067 user_data = g_new0 (gpointer, 3);
9068 user_data [0] = mono_domain_get ();
9069 user_data [1] = acfg;
9070 user_data [2] = frag;
9072 handle = mono_threads_create_thread ((LPTHREAD_START_ROUTINE)compile_thread_main, user_data, 0, 0, NULL);
9073 g_ptr_array_add (threads, handle);
9077 for (i = 0; i < threads->len; ++i) {
9078 WaitForSingleObjectEx (g_ptr_array_index (threads, i), INFINITE, FALSE);
9084 /* Compile methods added by compile_method () or all methods if nthreads == 0 */
9085 for (i = methods_len; i < acfg->methods->len; ++i) {
9086 /* This can new methods to acfg->methods */
9087 compile_method (acfg, (MonoMethod *)g_ptr_array_index (acfg->methods, i));
9092 compile_asm (MonoAotCompile *acfg)
9094 char *command, *objfile;
9095 char *outfile_name, *tmp_outfile_name, *llvm_ofile;
9096 const char *tool_prefix = acfg->aot_opts.tool_prefix ? acfg->aot_opts.tool_prefix : "";
9097 char *ld_flags = acfg->aot_opts.ld_flags ? acfg->aot_opts.ld_flags : g_strdup("");
9099 #if defined(TARGET_AMD64) && !defined(TARGET_MACH)
9100 #define AS_OPTIONS "--64"
9101 #elif defined(TARGET_POWERPC64)
9102 #define AS_OPTIONS "-a64 -mppc64"
9103 #define LD_OPTIONS "-m elf64ppc"
9104 #elif defined(sparc) && SIZEOF_VOID_P == 8
9105 #define AS_OPTIONS "-xarch=v9"
9106 #elif defined(TARGET_X86) && defined(TARGET_MACH) && !defined(__native_client_codegen__)
9107 #define AS_OPTIONS "-arch i386"
9109 #define AS_OPTIONS ""
9112 #ifdef __native_client_codegen__
9113 #if defined(TARGET_AMD64)
9114 #define AS_NAME "nacl64-as"
9116 #define AS_NAME "nacl-as"
9118 #elif defined(TARGET_OSX)
9119 #define AS_NAME "clang"
9121 #define AS_NAME "as"
9125 #define LD_OPTIONS ""
9129 #define LD_NAME "ld -shared -G"
9130 #elif defined(__ppc__) && defined(TARGET_MACH)
9131 #define LD_NAME "gcc -dynamiclib"
9132 #elif defined(TARGET_AMD64) && defined(TARGET_MACH)
9133 #define LD_NAME "clang --shared"
9134 #elif defined(TARGET_WIN32) && !defined(TARGET_ANDROID)
9135 #define LD_NAME "gcc -shared --dll"
9136 #elif defined(TARGET_X86) && defined(TARGET_MACH) && !defined(__native_client_codegen__)
9137 #define LD_NAME "clang -m32 -dynamiclib"
9138 #elif defined(TARGET_ARM) && !defined(TARGET_ANDROID)
9139 #define LD_NAME "gcc --shared"
9142 if (acfg->aot_opts.asm_only) {
9143 aot_printf (acfg, "Output file: '%s'.\n", acfg->tmpfname);
9144 if (acfg->aot_opts.static_link)
9145 aot_printf (acfg, "Linking symbol: '%s'.\n", acfg->static_linking_symbol);
9147 aot_printf (acfg, "LLVM output file: '%s'.\n", acfg->llvm_sfile);
9151 if (acfg->aot_opts.static_link) {
9152 if (acfg->aot_opts.outfile)
9153 objfile = g_strdup_printf ("%s", acfg->aot_opts.outfile);
9155 objfile = g_strdup_printf ("%s.o", acfg->image->name);
9157 objfile = g_strdup_printf ("%s.o", acfg->tmpfname);
9161 g_string_append (acfg->as_args, "-c -x assembler");
9164 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);
9165 aot_printf (acfg, "Executing the native assembler: %s\n", command);
9166 if (execute_system (command) != 0) {
9172 if (acfg->llvm && !acfg->llvm_owriter) {
9173 command = g_strdup_printf ("\"%s%s\" %s %s -o %s %s", tool_prefix, AS_NAME, AS_OPTIONS, acfg->as_args ? acfg->as_args->str : "", acfg->llvm_ofile, acfg->llvm_sfile);
9174 aot_printf (acfg, "Executing the native assembler: %s\n", command);
9175 if (execute_system (command) != 0) {
9184 if (acfg->aot_opts.static_link) {
9185 aot_printf (acfg, "Output file: '%s'.\n", objfile);
9186 aot_printf (acfg, "Linking symbol: '%s'.\n", acfg->static_linking_symbol);
9191 if (acfg->aot_opts.outfile)
9192 outfile_name = g_strdup_printf ("%s", acfg->aot_opts.outfile);
9194 outfile_name = g_strdup_printf ("%s%s", acfg->image->name, MONO_SOLIB_EXT);
9196 tmp_outfile_name = g_strdup_printf ("%s.tmp", outfile_name);
9199 llvm_ofile = g_strdup_printf ("\"%s\"", acfg->llvm_ofile);
9201 llvm_ofile = g_strdup ("");
9204 /* replace the ; flags separators with spaces */
9205 g_strdelimit (ld_flags, ";", ' ');
9207 if (acfg->aot_opts.llvm_only)
9208 ld_flags = g_strdup_printf ("%s %s", ld_flags, "-lstdc++");
9211 command = g_strdup_printf ("%s -o \"%s\" %s \"%s.o\" %s", LD_NAME, tmp_outfile_name, llvm_ofile, acfg->tmpfname, ld_flags);
9213 command = g_strdup_printf ("\"%sld\" %s -shared -o %s %s %s.o %s", tool_prefix, LD_OPTIONS, tmp_outfile_name, llvm_ofile,
9214 acfg->tmpfname, ld_flags);
9216 aot_printf (acfg, "Executing the native linker: %s\n", command);
9217 if (execute_system (command) != 0) {
9218 g_free (tmp_outfile_name);
9219 g_free (outfile_name);
9228 /*com = g_strdup_printf ("strip --strip-unneeded %s%s", acfg->image->name, MONO_SOLIB_EXT);
9229 printf ("Stripping the binary: %s\n", com);
9230 execute_system (com);
9233 #if defined(TARGET_ARM) && !defined(TARGET_MACH)
9235 * gas generates 'mapping symbols' each time code and data is mixed, which
9236 * happens a lot in emit_and_reloc_code (), so we need to get rid of them.
9238 command = g_strdup_printf ("\"%sstrip\" --strip-symbol=\\$a --strip-symbol=\\$d %s", tool_prefix, tmp_outfile_name);
9239 aot_printf (acfg, "Stripping the binary: %s\n", command);
9240 if (execute_system (command) != 0) {
9241 g_free (tmp_outfile_name);
9242 g_free (outfile_name);
9249 rename (tmp_outfile_name, outfile_name);
9251 #if defined(TARGET_MACH)
9252 command = g_strdup_printf ("dsymutil \"%s\"", outfile_name);
9253 aot_printf (acfg, "Executing dsymutil: %s\n", command);
9254 if (execute_system (command) != 0) {
9259 if (!acfg->aot_opts.save_temps)
9262 g_free (tmp_outfile_name);
9263 g_free (outfile_name);
9266 if (acfg->aot_opts.save_temps)
9267 aot_printf (acfg, "Retained input file.\n");
9269 unlink (acfg->tmpfname);
9274 static void init_got_info (GotInfo *info)
9278 info->patch_to_got_offset = g_hash_table_new (mono_patch_info_hash, mono_patch_info_equal);
9279 info->patch_to_got_offset_by_type = g_new0 (GHashTable*, MONO_PATCH_INFO_NUM);
9280 for (i = 0; i < MONO_PATCH_INFO_NUM; ++i)
9281 info->patch_to_got_offset_by_type [i] = g_hash_table_new (mono_patch_info_hash, mono_patch_info_equal);
9282 info->got_patches = g_ptr_array_new ();
9285 static MonoAotCompile*
9286 acfg_create (MonoAssembly *ass, guint32 opts)
9288 MonoImage *image = ass->image;
9289 MonoAotCompile *acfg;
9291 acfg = g_new0 (MonoAotCompile, 1);
9292 acfg->methods = g_ptr_array_new ();
9293 acfg->method_indexes = g_hash_table_new (NULL, NULL);
9294 acfg->method_depth = g_hash_table_new (NULL, NULL);
9295 acfg->plt_offset_to_entry = g_hash_table_new (NULL, NULL);
9296 acfg->patch_to_plt_entry = g_new0 (GHashTable*, MONO_PATCH_INFO_NUM);
9297 acfg->method_to_cfg = g_hash_table_new (NULL, NULL);
9298 acfg->token_info_hash = g_hash_table_new_full (NULL, NULL, NULL, NULL);
9299 acfg->method_to_pinvoke_import = g_hash_table_new_full (NULL, NULL, NULL, g_free);
9300 acfg->image_hash = g_hash_table_new (NULL, NULL);
9301 acfg->image_table = g_ptr_array_new ();
9302 acfg->globals = g_ptr_array_new ();
9303 acfg->image = image;
9305 /* TODO: Write out set of SIMD instructions used, rather than just those available */
9306 acfg->simd_opts = mono_arch_cpu_enumerate_simd_versions ();
9307 acfg->mempool = mono_mempool_new ();
9308 acfg->extra_methods = g_ptr_array_new ();
9309 acfg->unwind_info_offsets = g_hash_table_new (NULL, NULL);
9310 acfg->unwind_ops = g_ptr_array_new ();
9311 acfg->method_label_hash = g_hash_table_new_full (g_str_hash, g_str_equal, g_free, NULL);
9312 acfg->method_order = g_ptr_array_new ();
9313 acfg->export_names = g_hash_table_new (NULL, NULL);
9314 acfg->klass_blob_hash = g_hash_table_new (NULL, NULL);
9315 acfg->method_blob_hash = g_hash_table_new (NULL, NULL);
9316 acfg->plt_entry_debug_sym_cache = g_hash_table_new (g_str_hash, g_str_equal);
9317 mono_os_mutex_init_recursive (&acfg->mutex);
9319 init_got_info (&acfg->got_info);
9320 init_got_info (&acfg->llvm_got_info);
9326 got_info_free (GotInfo *info)
9330 for (i = 0; i < MONO_PATCH_INFO_NUM; ++i)
9331 g_hash_table_destroy (info->patch_to_got_offset_by_type [i]);
9332 g_free (info->patch_to_got_offset_by_type);
9333 g_hash_table_destroy (info->patch_to_got_offset);
9334 g_ptr_array_free (info->got_patches, TRUE);
9338 acfg_free (MonoAotCompile *acfg)
9342 mono_img_writer_destroy (acfg->w);
9343 for (i = 0; i < acfg->nmethods; ++i)
9345 g_free (acfg->cfgs [i]);
9346 g_free (acfg->cfgs);
9347 g_free (acfg->static_linking_symbol);
9348 g_free (acfg->got_symbol);
9349 g_free (acfg->plt_symbol);
9350 g_ptr_array_free (acfg->methods, TRUE);
9351 g_ptr_array_free (acfg->image_table, TRUE);
9352 g_ptr_array_free (acfg->globals, TRUE);
9353 g_ptr_array_free (acfg->unwind_ops, TRUE);
9354 g_hash_table_destroy (acfg->method_indexes);
9355 g_hash_table_destroy (acfg->method_depth);
9356 g_hash_table_destroy (acfg->plt_offset_to_entry);
9357 for (i = 0; i < MONO_PATCH_INFO_NUM; ++i) {
9358 if (acfg->patch_to_plt_entry [i])
9359 g_hash_table_destroy (acfg->patch_to_plt_entry [i]);
9361 g_free (acfg->patch_to_plt_entry);
9362 g_hash_table_destroy (acfg->method_to_cfg);
9363 g_hash_table_destroy (acfg->token_info_hash);
9364 g_hash_table_destroy (acfg->method_to_pinvoke_import);
9365 g_hash_table_destroy (acfg->image_hash);
9366 g_hash_table_destroy (acfg->unwind_info_offsets);
9367 g_hash_table_destroy (acfg->method_label_hash);
9368 g_hash_table_destroy (acfg->export_names);
9369 g_hash_table_destroy (acfg->plt_entry_debug_sym_cache);
9370 g_hash_table_destroy (acfg->klass_blob_hash);
9371 g_hash_table_destroy (acfg->method_blob_hash);
9372 got_info_free (&acfg->got_info);
9373 got_info_free (&acfg->llvm_got_info);
9374 mono_mempool_destroy (acfg->mempool);
9378 #define WRAPPER(e,n) n,
9379 static const char* const
9380 wrapper_type_names [MONO_WRAPPER_NUM + 1] = {
9381 #include "mono/metadata/wrapper-types.h"
9385 static G_GNUC_UNUSED const char*
9386 get_wrapper_type_name (int type)
9388 return wrapper_type_names [type];
9394 static void aot_dump (MonoAotCompile *acfg)
9400 mono_json_writer_init (&writer);
9402 mono_json_writer_object_begin(&writer);
9405 mono_json_writer_indent (&writer);
9406 mono_json_writer_object_key(&writer, "methods");
9407 mono_json_writer_array_begin (&writer);
9410 for (i = 0; i < acfg->nmethods; ++i) {
9415 cfg = acfg->cfgs [i];
9419 method = cfg->orig_method;
9421 mono_json_writer_indent (&writer);
9422 mono_json_writer_object_begin(&writer);
9424 mono_json_writer_indent (&writer);
9425 mono_json_writer_object_key(&writer, "name");
9426 mono_json_writer_printf (&writer, "\"%s\",\n", method->name);
9428 mono_json_writer_indent (&writer);
9429 mono_json_writer_object_key(&writer, "signature");
9430 mono_json_writer_printf (&writer, "\"%s\",\n", mono_method_full_name (method,
9431 /*signature=*/TRUE));
9433 mono_json_writer_indent (&writer);
9434 mono_json_writer_object_key(&writer, "code_size");
9435 mono_json_writer_printf (&writer, "\"%d\",\n", cfg->code_size);
9437 klass = method->klass;
9439 mono_json_writer_indent (&writer);
9440 mono_json_writer_object_key(&writer, "class");
9441 mono_json_writer_printf (&writer, "\"%s\",\n", klass->name);
9443 mono_json_writer_indent (&writer);
9444 mono_json_writer_object_key(&writer, "namespace");
9445 mono_json_writer_printf (&writer, "\"%s\",\n", klass->name_space);
9447 mono_json_writer_indent (&writer);
9448 mono_json_writer_object_key(&writer, "wrapper_type");
9449 mono_json_writer_printf (&writer, "\"%s\",\n", get_wrapper_type_name(method->wrapper_type));
9451 mono_json_writer_indent_pop (&writer);
9452 mono_json_writer_indent (&writer);
9453 mono_json_writer_object_end (&writer);
9454 mono_json_writer_printf (&writer, ",\n");
9457 mono_json_writer_indent_pop (&writer);
9458 mono_json_writer_indent (&writer);
9459 mono_json_writer_array_end (&writer);
9460 mono_json_writer_printf (&writer, ",\n");
9464 mono_json_writer_indent_push (&writer);
9465 mono_json_writer_indent (&writer);
9466 mono_json_writer_object_key(&writer, "plt");
9467 mono_json_writer_array_begin (&writer);
9469 for (i = 0; i < acfg->plt_offset; ++i) {
9470 MonoPltEntry *plt_entry = NULL;
9475 * The first plt entry is unused.
9479 plt_entry = g_hash_table_lookup (acfg->plt_offset_to_entry, GUINT_TO_POINTER (i));
9482 mono_json_writer_indent (&writer);
9483 mono_json_writer_printf (&writer, "{ ");
9484 mono_json_writer_object_key(&writer, "symbol");
9485 mono_json_writer_printf (&writer, "\"%s\" },\n", plt_entry->symbol);
9488 mono_json_writer_indent_pop (&writer);
9489 mono_json_writer_indent (&writer);
9490 mono_json_writer_array_end (&writer);
9491 mono_json_writer_printf (&writer, ",\n");
9496 mono_json_writer_indent_push (&writer);
9497 mono_json_writer_indent (&writer);
9498 mono_json_writer_object_key(&writer, "got");
9499 mono_json_writer_array_begin (&writer);
9501 mono_json_writer_indent_push (&writer);
9502 for (i = 0; i < acfg->got_info.got_patches->len; ++i) {
9503 MonoJumpInfo *ji = g_ptr_array_index (acfg->got_info.got_patches, i);
9505 mono_json_writer_indent (&writer);
9506 mono_json_writer_printf (&writer, "{ ");
9507 mono_json_writer_object_key(&writer, "patch_name");
9508 mono_json_writer_printf (&writer, "\"%s\" },\n", get_patch_name (ji->type));
9511 mono_json_writer_indent_pop (&writer);
9512 mono_json_writer_indent (&writer);
9513 mono_json_writer_array_end (&writer);
9514 mono_json_writer_printf (&writer, ",\n");
9517 mono_json_writer_indent_pop (&writer);
9518 mono_json_writer_indent (&writer);
9519 mono_json_writer_object_end (&writer);
9521 dumpname = g_strdup_printf ("%s.json", g_path_get_basename (acfg->image->name));
9522 dumpfile = fopen (dumpname, "w+");
9525 fprintf (dumpfile, "%s", writer.text->str);
9528 mono_json_writer_destroy (&writer);
9531 static const char *preinited_jit_icalls[] = {
9532 "mono_aot_init_llvm_method",
9533 "mono_aot_init_gshared_method_this",
9534 "mono_aot_init_gshared_method_rgctx",
9535 "mono_llvm_throw_corlib_exception",
9536 "mono_resolve_vcall",
9537 "mono_helper_ldstr_mscorlib"
9541 add_preinit_got_slots (MonoAotCompile *acfg)
9547 * Allocate the first few GOT entries to information which is needed frequently, or it is needed
9548 * during method initialization etc.
9551 ji = (MonoJumpInfo *)mono_mempool_alloc0 (acfg->mempool, sizeof (MonoJumpInfo));
9552 ji->type = MONO_PATCH_INFO_IMAGE;
9553 ji->data.image = acfg->image;
9554 get_got_offset (acfg, FALSE, ji);
9555 get_got_offset (acfg, TRUE, ji);
9557 ji = (MonoJumpInfo *)mono_mempool_alloc0 (acfg->mempool, sizeof (MonoJumpInfo));
9558 ji->type = MONO_PATCH_INFO_MSCORLIB_GOT_ADDR;
9559 get_got_offset (acfg, FALSE, ji);
9560 get_got_offset (acfg, TRUE, ji);
9562 ji = (MonoJumpInfo *)mono_mempool_alloc0 (acfg->mempool, sizeof (MonoJumpInfo));
9563 ji->type = MONO_PATCH_INFO_GC_CARD_TABLE_ADDR;
9564 get_got_offset (acfg, FALSE, ji);
9565 get_got_offset (acfg, TRUE, ji);
9567 ji = (MonoJumpInfo *)mono_mempool_alloc0 (acfg->mempool, sizeof (MonoJumpInfo));
9568 ji->type = MONO_PATCH_INFO_GC_NURSERY_START;
9569 get_got_offset (acfg, FALSE, ji);
9570 get_got_offset (acfg, TRUE, ji);
9572 ji = (MonoJumpInfo *)mono_mempool_alloc0 (acfg->mempool, sizeof (MonoJumpInfo));
9573 ji->type = MONO_PATCH_INFO_JIT_TLS_ID;
9574 get_got_offset (acfg, FALSE, ji);
9575 get_got_offset (acfg, TRUE, ji);
9577 ji = (MonoJumpInfo *)mono_mempool_alloc0 (acfg->mempool, sizeof (MonoJumpInfo));
9578 ji->type = MONO_PATCH_INFO_AOT_MODULE;
9579 get_got_offset (acfg, FALSE, ji);
9580 get_got_offset (acfg, TRUE, ji);
9582 ji = (MonoJumpInfo *)mono_mempool_alloc0 (acfg->mempool, sizeof (MonoJumpInfo));
9583 ji->type = MONO_PATCH_INFO_GC_NURSERY_BITS;
9584 get_got_offset (acfg, FALSE, ji);
9585 get_got_offset (acfg, TRUE, ji);
9587 for (i = 0; i < sizeof (preinited_jit_icalls) / sizeof (char*); ++i) {
9588 ji = (MonoJumpInfo *)mono_mempool_alloc0 (acfg->mempool, sizeof (MonoAotCompile));
9589 ji->type = MONO_PATCH_INFO_INTERNAL_METHOD;
9590 ji->data.name = preinited_jit_icalls [i];
9591 get_got_offset (acfg, FALSE, ji);
9592 get_got_offset (acfg, TRUE, ji);
9595 acfg->nshared_got_entries = acfg->got_offset;
9599 mono_compile_assembly (MonoAssembly *ass, guint32 opts, const char *aot_options)
9601 MonoImage *image = ass->image;
9604 MonoAotCompile *acfg;
9605 char *outfile_name, *tmp_outfile_name, *p;
9606 char llvm_stats_msg [256];
9610 acfg = acfg_create (ass, opts);
9612 memset (&acfg->aot_opts, 0, sizeof (acfg->aot_opts));
9613 acfg->aot_opts.write_symbols = TRUE;
9614 acfg->aot_opts.ntrampolines = 1024;
9615 acfg->aot_opts.nrgctx_trampolines = 1024;
9616 acfg->aot_opts.nimt_trampolines = 128;
9617 acfg->aot_opts.nrgctx_fetch_trampolines = 128;
9618 acfg->aot_opts.ngsharedvt_arg_trampolines = 128;
9619 acfg->aot_opts.llvm_path = g_strdup ("");
9620 acfg->aot_opts.temp_path = g_strdup ("");
9622 acfg->aot_opts.use_trampolines_page = TRUE;
9625 mono_aot_parse_options (aot_options, &acfg->aot_opts);
9627 if (acfg->aot_opts.logfile) {
9628 acfg->logfile = fopen (acfg->aot_opts.logfile, "a+");
9631 //acfg->aot_opts.print_skipped_methods = TRUE;
9633 #if !defined(MONO_ARCH_GSHAREDVT_SUPPORTED) || !defined(ENABLE_GSHAREDVT)
9634 if (opts & MONO_OPT_GSHAREDVT) {
9635 aot_printerrf (acfg, "-O=gsharedvt not supported on this platform.\n");
9640 aot_printf (acfg, "Mono Ahead of Time compiler - compiling assembly %s\n", image->name);
9642 #ifndef MONO_ARCH_HAVE_FULL_AOT_TRAMPOLINES
9643 if (mono_aot_mode_is_full (&acfg->aot_opts)) {
9644 aot_printerrf (acfg, "--aot=full is not supported on this platform.\n");
9649 if (acfg->aot_opts.direct_pinvoke && !acfg->aot_opts.static_link) {
9650 aot_printerrf (acfg, "The 'direct-pinvoke' AOT option also requires the 'static' AOT option.\n");
9654 if (acfg->aot_opts.static_link)
9655 acfg->aot_opts.asm_writer = TRUE;
9657 if (acfg->aot_opts.soft_debug) {
9658 MonoDebugOptions *opt = mini_get_debug_options ();
9660 opt->mdb_optimizations = TRUE;
9661 opt->gen_sdb_seq_points = TRUE;
9663 if (!mono_debug_enabled ()) {
9664 aot_printerrf (acfg, "The soft-debug AOT option requires the --debug option.\n");
9667 acfg->flags = (MonoAotFileFlags)(acfg->flags | MONO_AOT_FILE_FLAG_DEBUG);
9670 if (mono_use_llvm || acfg->aot_opts.llvm) {
9672 acfg->aot_opts.asm_writer = TRUE;
9673 acfg->flags = (MonoAotFileFlags)(acfg->flags | MONO_AOT_FILE_FLAG_WITH_LLVM);
9675 if (acfg->aot_opts.soft_debug) {
9676 aot_printerrf (acfg, "The 'soft-debug' option is not supported when compiling with LLVM.\n");
9682 if (acfg->aot_opts.asm_only && !acfg->aot_opts.llvm_outfile) {
9683 aot_printerrf (acfg, "Compiling with LLVM and the asm-only option requires the llvm-outputfile= option.");
9688 * Emit all LLVM code into a separate assembly/object file and link with it
9691 if (!acfg->aot_opts.asm_only) {
9692 acfg->llvm_owriter = TRUE;
9693 } else if (acfg->aot_opts.llvm_outfile) {
9694 int len = strlen (acfg->aot_opts.llvm_outfile);
9696 if (len >= 2 && acfg->aot_opts.llvm_outfile [len - 2] == '.' && acfg->aot_opts.llvm_outfile [len - 1] == 'o')
9697 acfg->llvm_owriter = TRUE;
9701 if (mono_aot_mode_is_full (&acfg->aot_opts))
9702 acfg->flags = (MonoAotFileFlags)(acfg->flags | MONO_AOT_FILE_FLAG_FULL_AOT);
9704 if (mono_threads_is_coop_enabled ())
9705 acfg->flags = (MonoAotFileFlags)(acfg->flags | MONO_AOT_FILE_FLAG_SAFEPOINTS);
9707 if (acfg->aot_opts.instances_logfile_path) {
9708 acfg->instances_logfile = fopen (acfg->aot_opts.instances_logfile_path, "w");
9709 if (!acfg->instances_logfile) {
9710 aot_printerrf (acfg, "Unable to create logfile: '%s'.\n", acfg->aot_opts.instances_logfile_path);
9715 load_profile_files (acfg);
9717 acfg->num_trampolines [MONO_AOT_TRAMP_SPECIFIC] = mono_aot_mode_is_full (&acfg->aot_opts) ? acfg->aot_opts.ntrampolines : 0;
9718 #ifdef MONO_ARCH_GSHARED_SUPPORTED
9719 acfg->num_trampolines [MONO_AOT_TRAMP_STATIC_RGCTX] = mono_aot_mode_is_full (&acfg->aot_opts) ? acfg->aot_opts.nrgctx_trampolines : 0;
9721 acfg->num_trampolines [MONO_AOT_TRAMP_IMT_THUNK] = mono_aot_mode_is_full (&acfg->aot_opts) ? acfg->aot_opts.nimt_trampolines : 0;
9722 #ifdef MONO_ARCH_GSHAREDVT_SUPPORTED
9723 if (acfg->opts & MONO_OPT_GSHAREDVT)
9724 acfg->num_trampolines [MONO_AOT_TRAMP_GSHAREDVT_ARG] = mono_aot_mode_is_full (&acfg->aot_opts) ? acfg->aot_opts.ngsharedvt_arg_trampolines : 0;
9727 acfg->temp_prefix = mono_img_writer_get_temp_label_prefix (NULL);
9731 if (acfg->llvm && acfg->thumb_mixed)
9732 acfg->flags = (MonoAotFileFlags)(acfg->flags | MONO_AOT_FILE_FLAG_LLVM_THUMB);
9733 if (acfg->aot_opts.llvm_only)
9734 acfg->flags = (MonoAotFileFlags)(acfg->flags | MONO_AOT_FILE_FLAG_LLVM_ONLY);
9736 acfg->assembly_name_sym = g_strdup (acfg->image->assembly->aname.name);
9737 /* Get rid of characters which cannot occur in symbols */
9738 for (p = acfg->assembly_name_sym; *p; ++p) {
9739 if (!(isalnum (*p) || *p == '_'))
9743 acfg->global_prefix = g_strdup_printf ("mono_aot_%s", acfg->assembly_name_sym);
9744 acfg->plt_symbol = g_strdup_printf ("%s_plt", acfg->global_prefix);
9745 acfg->got_symbol = g_strdup_printf ("%s_got", acfg->global_prefix);
9747 acfg->llvm_got_symbol = g_strdup_printf ("%s_llvm_got", acfg->global_prefix);
9748 acfg->llvm_eh_frame_symbol = g_strdup_printf ("%s_eh_frame", acfg->global_prefix);
9751 acfg->method_index = 1;
9753 if (mono_aot_mode_is_full (&acfg->aot_opts))
9754 mono_set_partial_sharing_supported (TRUE);
9756 res = collect_methods (acfg);
9760 acfg->cfgs_size = acfg->methods->len + 32;
9761 acfg->cfgs = g_new0 (MonoCompile*, acfg->cfgs_size);
9763 /* PLT offset 0 is reserved for the PLT trampoline */
9764 acfg->plt_offset = 1;
9765 add_preinit_got_slots (acfg);
9770 mono_llvm_create_aot_module (acfg->image->assembly, acfg->global_prefix, TRUE, acfg->aot_opts.static_link, acfg->aot_opts.llvm_only);
9776 compile_methods (acfg);
9780 acfg->stats.jit_time = TV_ELAPSED (atv, btv);
9786 if (acfg->aot_opts.asm_only) {
9787 if (acfg->aot_opts.outfile) {
9788 acfg->tmpfname = g_strdup_printf ("%s", acfg->aot_opts.outfile);
9789 acfg->tmpbasename = g_strdup (acfg->tmpfname);
9791 acfg->tmpbasename = g_strdup_printf ("%s", acfg->image->name);
9792 acfg->tmpfname = g_strdup_printf ("%s.s", acfg->tmpbasename);
9794 g_assert (acfg->aot_opts.llvm_outfile);
9795 acfg->llvm_sfile = g_strdup (acfg->aot_opts.llvm_outfile);
9796 if (acfg->llvm_owriter)
9797 acfg->llvm_ofile = g_strdup (acfg->aot_opts.llvm_outfile);
9799 acfg->llvm_sfile = g_strdup (acfg->aot_opts.llvm_outfile);
9801 acfg->tmpbasename = (strcmp (acfg->aot_opts.temp_path, "") == 0) ?
9802 g_strdup_printf ("%s", "temp") :
9803 g_build_filename (acfg->aot_opts.temp_path, "temp", NULL);
9805 acfg->tmpfname = g_strdup_printf ("%s.s", acfg->tmpbasename);
9806 acfg->llvm_sfile = g_strdup_printf ("%s-llvm.s", acfg->tmpbasename);
9807 acfg->llvm_ofile = g_strdup_printf ("%s-llvm.o", acfg->tmpbasename);
9812 if (acfg->aot_opts.asm_only) {
9813 if (acfg->aot_opts.outfile)
9814 acfg->tmpfname = g_strdup_printf ("%s", acfg->aot_opts.outfile);
9816 acfg->tmpfname = g_strdup_printf ("%s.s", acfg->image->name);
9817 acfg->fp = fopen (acfg->tmpfname, "w+");
9819 int i = g_file_open_tmp ("mono_aot_XXXXXX", &acfg->tmpfname, NULL);
9820 acfg->fp = fdopen (i, "w+");
9822 if (acfg->fp == 0) {
9823 aot_printerrf (acfg, "Unable to open file '%s': %s\n", acfg->tmpfname, strerror (errno));
9826 acfg->w = mono_img_writer_create (acfg->fp, FALSE);
9828 tmp_outfile_name = NULL;
9829 outfile_name = NULL;
9831 /* Compute symbols for methods */
9832 for (i = 0; i < acfg->nmethods; ++i) {
9833 if (acfg->cfgs [i]) {
9834 MonoCompile *cfg = acfg->cfgs [i];
9835 int method_index = get_method_index (acfg, cfg->orig_method);
9837 if (COMPILE_LLVM (cfg))
9838 cfg->asm_symbol = g_strdup_printf ("%s%s", acfg->llvm_label_prefix, cfg->llvm_method_name);
9839 else if (acfg->global_symbols || acfg->llvm)
9840 cfg->asm_symbol = get_debug_sym (cfg->orig_method, "", acfg->method_label_hash);
9842 cfg->asm_symbol = g_strdup_printf ("%s%sm_%x", acfg->temp_prefix, acfg->llvm_label_prefix, method_index);
9843 cfg->asm_debug_symbol = cfg->asm_symbol;
9847 if (acfg->aot_opts.dwarf_debug && acfg->aot_opts.asm_only && acfg->aot_opts.gnu_asm) {
9849 * CLANG supports GAS .file/.loc directives, so emit line number information this way
9850 * FIXME: CLANG only emits line number info for .loc directives followed by assembly, not
9853 //acfg->gas_line_numbers = TRUE;
9856 if ((!acfg->aot_opts.nodebug || acfg->aot_opts.dwarf_debug) && acfg->has_jitted_code) {
9857 if (acfg->aot_opts.dwarf_debug && !mono_debug_enabled ()) {
9858 aot_printerrf (acfg, "The dwarf AOT option requires the --debug option.\n");
9861 acfg->dwarf = mono_dwarf_writer_create (acfg->w, NULL, 0, FALSE, !acfg->gas_line_numbers);
9864 mono_img_writer_emit_start (acfg->w);
9867 mono_dwarf_writer_emit_base_info (acfg->dwarf, g_path_get_basename (acfg->image->name), mono_unwind_get_cie_program ());
9873 emit_extra_methods (acfg);
9875 emit_trampolines (acfg);
9877 emit_class_name_table (acfg);
9879 emit_got_info (acfg, FALSE);
9881 emit_got_info (acfg, TRUE);
9883 emit_exception_info (acfg);
9885 emit_unwind_info (acfg);
9887 emit_class_info (acfg);
9891 emit_image_table (acfg);
9895 emit_file_info (acfg);
9899 emit_objc_selectors (acfg);
9901 emit_globals (acfg);
9904 emit_dwarf_info (acfg);
9905 mono_dwarf_writer_close (acfg->dwarf);
9908 emit_mem_end (acfg);
9910 if (acfg->need_pt_gnu_stack) {
9911 /* This is required so the .so doesn't have an executable stack */
9912 /* The bin writer already emits this */
9913 fprintf (acfg->fp, "\n.section .note.GNU-stack,\"\",@progbits\n");
9920 res = emit_llvm_file (acfg);
9928 acfg->stats.gen_time = TV_ELAPSED (atv, btv);
9931 sprintf (llvm_stats_msg, ", LLVM: %d (%d%%)", acfg->stats.llvm_count, acfg->stats.mcount ? (acfg->stats.llvm_count * 100) / acfg->stats.mcount : 100);
9933 strcpy (llvm_stats_msg, "");
9935 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;
9937 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",
9938 (int)acfg->stats.code_size, (int)(acfg->stats.code_size * 100 / all_sizes),
9939 (int)acfg->stats.info_size, (int)(acfg->stats.info_size * 100 / all_sizes),
9940 (int)acfg->stats.ex_info_size, (int)(acfg->stats.ex_info_size * 100 / all_sizes),
9941 (int)acfg->stats.unwind_info_size, (int)(acfg->stats.unwind_info_size * 100 / all_sizes),
9942 (int)acfg->stats.class_info_size, (int)(acfg->stats.class_info_size * 100 / all_sizes),
9943 acfg->stats.plt_size ? (int)acfg->stats.plt_size : (int)acfg->plt_offset, acfg->stats.plt_size ? (int)(acfg->stats.plt_size * 100 / all_sizes) : 0,
9944 (int)acfg->stats.got_info_size, (int)(acfg->stats.got_info_size * 100 / all_sizes),
9945 (int)acfg->stats.offsets_size, (int)(acfg->stats.offsets_size * 100 / all_sizes),
9946 (int)(acfg->got_offset * sizeof (gpointer)));
9947 aot_printf (acfg, "Compiled: %d/%d (%d%%)%s, No GOT slots: %d (%d%%), Direct calls: %d (%d%%)\n",
9948 acfg->stats.ccount, acfg->stats.mcount, acfg->stats.mcount ? (acfg->stats.ccount * 100) / acfg->stats.mcount : 100,
9950 acfg->stats.methods_without_got_slots, acfg->stats.mcount ? (acfg->stats.methods_without_got_slots * 100) / acfg->stats.mcount : 100,
9951 acfg->stats.direct_calls, acfg->stats.all_calls ? (acfg->stats.direct_calls * 100) / acfg->stats.all_calls : 100);
9952 if (acfg->stats.genericcount)
9953 aot_printf (acfg, "%d methods are generic (%d%%)\n", acfg->stats.genericcount, acfg->stats.mcount ? (acfg->stats.genericcount * 100) / acfg->stats.mcount : 100);
9954 if (acfg->stats.abscount)
9955 aot_printf (acfg, "%d methods contain absolute addresses (%d%%)\n", acfg->stats.abscount, acfg->stats.mcount ? (acfg->stats.abscount * 100) / acfg->stats.mcount : 100);
9956 if (acfg->stats.lmfcount)
9957 aot_printf (acfg, "%d methods contain lmf pointers (%d%%)\n", acfg->stats.lmfcount, acfg->stats.mcount ? (acfg->stats.lmfcount * 100) / acfg->stats.mcount : 100);
9958 if (acfg->stats.ocount)
9959 aot_printf (acfg, "%d methods have other problems (%d%%)\n", acfg->stats.ocount, acfg->stats.mcount ? (acfg->stats.ocount * 100) / acfg->stats.mcount : 100);
9962 res = mono_img_writer_emit_writeout (acfg->w);
9967 res = compile_asm (acfg);
9973 acfg->stats.link_time = TV_ELAPSED (atv, btv);
9975 if (acfg->aot_opts.stats) {
9978 aot_printf (acfg, "GOT slot distribution:\n");
9979 for (i = 0; i < MONO_PATCH_INFO_NONE; ++i)
9980 if (acfg->stats.got_slot_types [i])
9981 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]);
9984 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);
9986 if (acfg->aot_opts.dump_json)
9999 mono_aot_readonly_field_override (MonoClassField *field)
10005 mono_compile_assembly (MonoAssembly *ass, guint32 opts, const char *aot_options)
10011 mono_aot_is_shared_got_offset (int offset)