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 {
100 gboolean write_symbols;
101 gboolean metadata_only;
102 gboolean bind_to_runtime_version;
105 gboolean static_link;
109 gboolean dwarf_debug;
111 gboolean log_generics;
112 gboolean log_instances;
113 gboolean gen_seq_points_file;
114 gboolean direct_pinvoke;
115 gboolean direct_icalls;
116 gboolean no_direct_calls;
117 gboolean use_trampolines_page;
118 gboolean no_instances;
124 int nrgctx_trampolines;
125 int nimt_trampolines;
126 int ngsharedvt_arg_trampolines;
127 int nrgctx_fetch_trampolines;
128 gboolean print_skipped_methods;
135 char *instances_logfile_path;
142 METHOD_CAT_GSHAREDVT,
148 typedef struct MonoAotStats {
149 int ccount, mcount, lmfcount, abscount, gcount, ocount, genericcount;
150 gint64 code_size, info_size, ex_info_size, unwind_info_size, got_size, class_info_size, got_info_size, plt_size;
151 int methods_without_got_slots, direct_calls, all_calls, llvm_count;
152 int got_slots, offsets_size;
153 int method_categories [METHOD_CAT_NUM];
154 int got_slot_types [MONO_PATCH_INFO_NONE];
155 int got_slot_info_sizes [MONO_PATCH_INFO_NONE];
156 int jit_time, gen_time, link_time;
159 typedef struct GotInfo {
160 GHashTable *patch_to_got_offset;
161 GHashTable **patch_to_got_offset_by_type;
162 GPtrArray *got_patches;
165 typedef struct MonoAotCompile {
168 GHashTable *method_indexes;
169 GHashTable *method_depth;
172 GHashTable **patch_to_plt_entry;
173 GHashTable *plt_offset_to_entry;
174 //GHashTable *patch_to_got_offset;
175 //GHashTable **patch_to_got_offset_by_type;
176 //GPtrArray *got_patches;
177 GotInfo got_info, llvm_got_info;
178 GHashTable *image_hash;
179 GHashTable *method_to_cfg;
180 GHashTable *token_info_hash;
181 GHashTable *method_to_pinvoke_import;
182 GPtrArray *extra_methods;
183 GPtrArray *image_table;
185 GPtrArray *method_order;
186 GHashTable *export_names;
187 /* Maps MonoClass* -> blob offset */
188 GHashTable *klass_blob_hash;
189 /* Maps MonoMethod* -> blob offset */
190 GHashTable *method_blob_hash;
191 GHashTable *gsharedvt_in_signatures;
192 GHashTable *gsharedvt_out_signatures;
193 guint32 *plt_got_info_offsets;
194 guint32 got_offset, llvm_got_offset, plt_offset, plt_got_offset_base, nshared_got_entries;
195 /* Number of GOT entries reserved for trampolines */
196 guint32 num_trampoline_got_entries;
197 guint32 tramp_page_size;
199 guint32 table_offsets [MONO_AOT_TABLE_NUM];
200 guint32 num_trampolines [MONO_AOT_TRAMP_NUM];
201 guint32 trampoline_got_offset_base [MONO_AOT_TRAMP_NUM];
202 guint32 trampoline_size [MONO_AOT_TRAMP_NUM];
203 guint32 tramp_page_code_offsets [MONO_AOT_TRAMP_NUM];
205 MonoAotOptions aot_opts;
209 MonoMemPool *mempool;
212 char *static_linking_symbol;
214 gboolean gas_line_numbers;
215 /* Whenever to emit an object file directly from llc */
216 gboolean llvm_owriter;
218 MonoDwarfWriter *dwarf;
225 GHashTable *unwind_info_offsets;
226 GPtrArray *unwind_ops;
227 guint32 unwind_info_offset;
230 char *llvm_got_symbol;
232 char *llvm_eh_frame_symbol;
233 GHashTable *method_label_hash;
234 const char *temp_prefix;
235 const char *user_symbol_prefix;
236 const char *llvm_label_prefix;
237 const char *inst_directive;
239 guint32 label_generator;
241 gboolean has_jitted_code;
242 MonoAotFileFlags flags;
243 MonoDynamicStream blob;
244 gboolean blob_closed;
245 MonoClass **typespec_classes;
248 char *assembly_name_sym;
249 GHashTable *plt_entry_debug_sym_cache;
250 gboolean thumb_mixed, need_no_dead_strip, need_pt_gnu_stack;
251 GHashTable *ginst_hash;
252 GHashTable *dwarf_ln_filenames;
253 gboolean global_symbols;
254 int objc_selector_index, objc_selector_index_2;
255 GPtrArray *objc_selectors;
256 GHashTable *objc_selector_to_index;
258 FILE *instances_logfile;
266 char *symbol, *llvm_symbol, *debug_sym;
268 gboolean jit_used, llvm_used;
271 #define mono_acfg_lock(acfg) mono_os_mutex_lock (&((acfg)->mutex))
272 #define mono_acfg_unlock(acfg) mono_os_mutex_unlock (&((acfg)->mutex))
274 /* This points to the current acfg in LLVM mode */
275 static MonoAotCompile *llvm_acfg;
277 #ifdef HAVE_ARRAY_ELEM_INIT
278 #define MSGSTRFIELD(line) MSGSTRFIELD1(line)
279 #define MSGSTRFIELD1(line) str##line
280 static const struct msgstr_t {
281 #define PATCH_INFO(a,b) char MSGSTRFIELD(__LINE__) [sizeof (b)];
282 #include "patch-info.h"
285 #define PATCH_INFO(a,b) b,
286 #include "patch-info.h"
289 static const gint16 opidx [] = {
290 #define PATCH_INFO(a,b) [MONO_PATCH_INFO_ ## a] = offsetof (struct msgstr_t, MSGSTRFIELD(__LINE__)),
291 #include "patch-info.h"
295 static G_GNUC_UNUSED const char*
296 get_patch_name (int info)
298 return (const char*)&opstr + opidx [info];
302 #define PATCH_INFO(a,b) b,
303 static const char* const
304 patch_types [MONO_PATCH_INFO_NUM + 1] = {
305 #include "patch-info.h"
309 static G_GNUC_UNUSED const char*
310 get_patch_name (int info)
312 return patch_types [info];
318 get_unwind_info_offset (MonoAotCompile *acfg, guint8 *encoded, guint32 encoded_len);
321 get_plt_entry_debug_sym (MonoAotCompile *acfg, MonoJumpInfo *ji, GHashTable *cache);
324 aot_printf (MonoAotCompile *acfg, const gchar *format, ...)
330 output = acfg->logfile;
334 va_start (args, format);
335 vfprintf (output, format, args);
340 aot_printerrf (MonoAotCompile *acfg, const gchar *format, ...)
346 output = acfg->logfile;
350 va_start (args, format);
351 vfprintf (output, format, args);
356 report_loader_error (MonoAotCompile *acfg, MonoError *error, const char *format, ...)
361 if (mono_error_ok (error))
365 output = acfg->logfile;
369 va_start (args, format);
370 vfprintf (output, format, args);
372 mono_error_cleanup (error);
374 g_error ("FullAOT cannot continue if there are loader errors");
377 /* Wrappers around the image writer functions */
380 emit_section_change (MonoAotCompile *acfg, const char *section_name, int subsection_index)
382 mono_img_writer_emit_section_change (acfg->w, section_name, subsection_index);
386 emit_local_symbol (MonoAotCompile *acfg, const char *name, const char *end_label, gboolean func)
388 mono_img_writer_emit_local_symbol (acfg->w, name, end_label, func);
392 emit_label (MonoAotCompile *acfg, const char *name)
394 mono_img_writer_emit_label (acfg->w, name);
398 emit_bytes (MonoAotCompile *acfg, const guint8* buf, int size)
400 mono_img_writer_emit_bytes (acfg->w, buf, size);
404 emit_string (MonoAotCompile *acfg, const char *value)
406 mono_img_writer_emit_string (acfg->w, value);
410 emit_line (MonoAotCompile *acfg)
412 mono_img_writer_emit_line (acfg->w);
416 emit_alignment (MonoAotCompile *acfg, int size)
418 mono_img_writer_emit_alignment (acfg->w, size);
422 emit_alignment_code (MonoAotCompile *acfg, int size)
424 if (acfg->align_pad_value)
425 mono_img_writer_emit_alignment_fill (acfg->w, size, acfg->align_pad_value);
427 mono_img_writer_emit_alignment (acfg->w, size);
431 emit_padding (MonoAotCompile *acfg, int size)
436 if (acfg->align_pad_value) {
437 for (i = 0; i < 16; ++i)
438 buf [i] = acfg->align_pad_value;
440 memset (buf, 0, sizeof (buf));
443 for (i = 0; i < size; i += 16) {
445 emit_bytes (acfg, buf, size - i);
447 emit_bytes (acfg, buf, 16);
452 emit_pointer (MonoAotCompile *acfg, const char *target)
454 mono_img_writer_emit_pointer (acfg->w, target);
458 emit_pointer_2 (MonoAotCompile *acfg, const char *prefix, const char *target)
460 if (prefix [0] != '\0') {
461 char *s = g_strdup_printf ("%s%s", prefix, target);
462 mono_img_writer_emit_pointer (acfg->w, s);
465 mono_img_writer_emit_pointer (acfg->w, target);
470 emit_int16 (MonoAotCompile *acfg, int value)
472 mono_img_writer_emit_int16 (acfg->w, value);
476 emit_int32 (MonoAotCompile *acfg, int value)
478 mono_img_writer_emit_int32 (acfg->w, value);
482 emit_symbol_diff (MonoAotCompile *acfg, const char *end, const char* start, int offset)
484 mono_img_writer_emit_symbol_diff (acfg->w, end, start, offset);
488 emit_zero_bytes (MonoAotCompile *acfg, int num)
490 mono_img_writer_emit_zero_bytes (acfg->w, num);
494 emit_byte (MonoAotCompile *acfg, guint8 val)
496 mono_img_writer_emit_byte (acfg->w, val);
499 #ifdef __native_client_codegen__
501 emit_nacl_call_alignment (MonoAotCompile *acfg)
503 mono_img_writer_emit_nacl_call_alignment (acfg->w);
507 static G_GNUC_UNUSED void
508 emit_global_inner (MonoAotCompile *acfg, const char *name, gboolean func)
510 mono_img_writer_emit_global (acfg->w, name, func);
514 emit_global (MonoAotCompile *acfg, const char *name, gboolean func)
516 if (acfg->aot_opts.no_dlsym) {
517 g_ptr_array_add (acfg->globals, g_strdup (name));
518 mono_img_writer_emit_local_symbol (acfg->w, name, NULL, func);
520 mono_img_writer_emit_global (acfg->w, name, func);
525 emit_symbol_size (MonoAotCompile *acfg, const char *name, const char *end_label)
527 mono_img_writer_emit_symbol_size (acfg->w, name, end_label);
530 /* Emit a symbol which is referenced by the MonoAotFileInfo structure */
532 emit_info_symbol (MonoAotCompile *acfg, const char *name)
537 emit_label (acfg, name);
538 /* LLVM generated code references this */
539 sprintf (symbol, "%s%s%s", acfg->user_symbol_prefix, acfg->global_prefix, name);
540 emit_label (acfg, symbol);
541 emit_global_inner (acfg, symbol, FALSE);
543 emit_label (acfg, name);
548 emit_string_symbol (MonoAotCompile *acfg, const char *name, const char *value)
551 mono_llvm_emit_aot_data (name, (guint8*)value, strlen (value) + 1);
555 mono_img_writer_emit_section_change (acfg->w, RODATA_SECT, 1);
557 /* On apple, all symbols need to be aligned to avoid warnings from ld */
558 emit_alignment (acfg, 4);
560 mono_img_writer_emit_label (acfg->w, name);
561 mono_img_writer_emit_string (acfg->w, value);
564 static G_GNUC_UNUSED void
565 emit_uleb128 (MonoAotCompile *acfg, guint32 value)
568 guint8 b = value & 0x7f;
570 if (value != 0) /* more bytes to come */
576 static G_GNUC_UNUSED void
577 emit_sleb128 (MonoAotCompile *acfg, gint64 value)
580 gboolean negative = (value < 0);
587 /* the following is unnecessary if the
588 * implementation of >>= uses an arithmetic rather
589 * than logical shift for a signed left operand
593 value |= - ((gint64)1 <<(size - 7));
594 /* sign bit of byte is second high order bit (0x40) */
595 if ((value == 0 && !(byte & 0x40)) ||
596 (value == -1 && (byte & 0x40)))
600 emit_byte (acfg, byte);
604 static G_GNUC_UNUSED void
605 encode_uleb128 (guint32 value, guint8 *buf, guint8 **endbuf)
610 guint8 b = value & 0x7f;
612 if (value != 0) /* more bytes to come */
620 static G_GNUC_UNUSED void
621 encode_sleb128 (gint32 value, guint8 *buf, guint8 **endbuf)
624 gboolean negative = (value < 0);
632 /* the following is unnecessary if the
633 * implementation of >>= uses an arithmetic rather
634 * than logical shift for a signed left operand
638 value |= - (1 <<(size - 7));
639 /* sign bit of byte is second high order bit (0x40) */
640 if ((value == 0 && !(byte & 0x40)) ||
641 (value == -1 && (byte & 0x40)))
652 encode_int (gint32 val, guint8 *buf, guint8 **endbuf)
655 buf [0] = (val >> 0) & 0xff;
656 buf [1] = (val >> 8) & 0xff;
657 buf [2] = (val >> 16) & 0xff;
658 buf [3] = (val >> 24) & 0xff;
664 encode_int16 (guint16 val, guint8 *buf, guint8 **endbuf)
666 buf [0] = (val >> 0) & 0xff;
667 buf [1] = (val >> 8) & 0xff;
673 encode_string (const char *s, guint8 *buf, guint8 **endbuf)
675 int len = strlen (s);
677 memcpy (buf, s, len + 1);
678 *endbuf = buf + len + 1;
682 emit_unset_mode (MonoAotCompile *acfg)
684 mono_img_writer_emit_unset_mode (acfg->w);
687 static G_GNUC_UNUSED void
688 emit_set_thumb_mode (MonoAotCompile *acfg)
690 emit_unset_mode (acfg);
691 fprintf (acfg->fp, ".code 16\n");
694 static G_GNUC_UNUSED void
695 emit_set_arm_mode (MonoAotCompile *acfg)
697 emit_unset_mode (acfg);
698 fprintf (acfg->fp, ".code 32\n");
702 emit_code_bytes (MonoAotCompile *acfg, const guint8* buf, int size)
707 g_assert (size % 4 == 0);
708 emit_unset_mode (acfg);
709 for (i = 0; i < size; i += 4)
710 fprintf (acfg->fp, "%s 0x%x\n", acfg->inst_directive, *(guint32*)(buf + i));
712 emit_bytes (acfg, buf, size);
716 /* ARCHITECTURE SPECIFIC CODE */
718 #if defined(TARGET_X86) || defined(TARGET_AMD64) || defined(TARGET_ARM) || defined(TARGET_POWERPC) || defined(TARGET_ARM64)
719 #define EMIT_DWARF_INFO 1
722 #if defined(TARGET_ARM)
723 #define AOT_FUNC_ALIGNMENT 4
725 #define AOT_FUNC_ALIGNMENT 16
727 #if (defined(TARGET_X86) || defined(TARGET_AMD64)) && defined(__native_client_codegen__)
728 #undef AOT_FUNC_ALIGNMENT
729 #define AOT_FUNC_ALIGNMENT 32
732 #if defined(TARGET_POWERPC64) && !defined(__mono_ilp32__)
733 #define PPC_LD_OP "ld"
734 #define PPC_LDX_OP "ldx"
736 #define PPC_LD_OP "lwz"
737 #define PPC_LDX_OP "lwzx"
741 #define AOT_TARGET_STR "AMD64"
746 #define AOT_TARGET_STR "ARM (MACH)"
748 #define AOT_TARGET_STR "ARM (!MACH)"
754 #define AOT_TARGET_STR "ARM64 (MACH)"
756 #define AOT_TARGET_STR "ARM64 (!MACH)"
760 #ifdef TARGET_POWERPC64
761 #ifdef __mono_ilp32__
762 #define AOT_TARGET_STR "POWERPC64 (mono ilp32)"
764 #define AOT_TARGET_STR "POWERPC64 (!mono ilp32)"
767 #ifdef TARGET_POWERPC
768 #ifdef __mono_ilp32__
769 #define AOT_TARGET_STR "POWERPC (mono ilp32)"
771 #define AOT_TARGET_STR "POWERPC (!mono ilp32)"
778 #define AOT_TARGET_STR "X86 (WIN32)"
779 #elif defined(__native_client_codegen__)
780 #define AOT_TARGET_STR "X86 (native client codegen)"
782 #define AOT_TARGET_STR "X86 (!native client codegen)"
786 #ifndef AOT_TARGET_STR
787 #define AOT_TARGET_STR ""
791 arch_init (MonoAotCompile *acfg)
793 acfg->llc_args = g_string_new ("");
794 acfg->as_args = g_string_new ("");
797 * The prefix LLVM likes to put in front of symbol names on darwin.
798 * The mach-os specs require this for globals, but LLVM puts them in front of all
799 * symbols. We need to handle this, since we need to refer to LLVM generated
802 acfg->llvm_label_prefix = "";
803 acfg->user_symbol_prefix = "";
805 #if defined(TARGET_X86)
806 g_string_append (acfg->llc_args, " -march=x86 -mattr=sse4.1");
809 #if defined(TARGET_AMD64)
810 g_string_append (acfg->llc_args, " -march=x86-64 -mattr=sse4.1");
812 acfg->align_pad_value = 0x90;
816 if (acfg->aot_opts.mtriple && strstr (acfg->aot_opts.mtriple, "darwin")) {
817 g_string_append (acfg->llc_args, "-mattr=+v6");
820 g_string_append (acfg->llc_args, " -mattr=+vfp2,-neon,+d16");
821 g_string_append (acfg->as_args, " -mfpu=vfp3");
823 g_string_append (acfg->llc_args, " -soft-float");
826 if (acfg->aot_opts.mtriple && strstr (acfg->aot_opts.mtriple, "thumb"))
827 acfg->thumb_mixed = TRUE;
829 if (acfg->aot_opts.mtriple)
830 mono_arch_set_target (acfg->aot_opts.mtriple);
834 acfg->inst_directive = ".inst";
835 if (acfg->aot_opts.mtriple)
836 mono_arch_set_target (acfg->aot_opts.mtriple);
840 acfg->user_symbol_prefix = "_";
841 acfg->llvm_label_prefix = "_";
842 acfg->inst_directive = ".word";
843 acfg->need_no_dead_strip = TRUE;
844 acfg->aot_opts.gnu_asm = TRUE;
847 #if defined(__linux__) && !defined(TARGET_ARM)
848 acfg->need_pt_gnu_stack = TRUE;
852 acfg->global_symbols = TRUE;
858 #include "../../../mono-extensions/mono/mini/aot-compiler-arm64.c"
862 #ifdef MONO_ARCH_AOT_SUPPORTED
864 * arch_emit_direct_call:
866 * Emit a direct call to the symbol TARGET. CALL_SIZE is set to the size of the
870 arch_emit_direct_call (MonoAotCompile *acfg, const char *target, gboolean external, gboolean thumb, MonoJumpInfo *ji, int *call_size)
872 #if defined(TARGET_X86) || defined(TARGET_AMD64)
873 /* Need to make sure this is exactly 5 bytes long */
874 emit_unset_mode (acfg);
875 fprintf (acfg->fp, "call %s\n", target);
877 #elif defined(TARGET_ARM)
878 emit_unset_mode (acfg);
880 fprintf (acfg->fp, "blx %s\n", target);
882 fprintf (acfg->fp, "bl %s\n", target);
884 #elif defined(TARGET_ARM64)
885 arm64_emit_direct_call (acfg, target, external, thumb, ji, call_size);
886 #elif defined(TARGET_POWERPC)
887 emit_unset_mode (acfg);
888 fprintf (acfg->fp, "bl %s\n", target);
891 g_assert_not_reached ();
898 * - we use an approach similar to the x86 abi: reserve a register (r30) to hold
900 * - The full-aot trampolines need access to the GOT of mscorlib, so we store
901 * in in the 2. slot of every GOT, and require every method to place the GOT
902 * address in r30, even when it doesn't access the GOT otherwise. This way,
903 * the trampolines can compute the mscorlib GOT address by loading 4(r30).
908 * PPC64 uses function descriptors which greatly complicate all code, since
909 * these are used very inconsistently in the runtime. Some functions like
910 * mono_compile_method () return ftn descriptors, while others like the
911 * trampoline creation functions do not.
912 * We assume that all GOT slots contain function descriptors, and create
913 * descriptors in aot-runtime.c when needed.
914 * The ppc64 abi uses r2 to hold the address of the TOC/GOT, which is loaded
915 * from function descriptors, we could do the same, but it would require
916 * rewriting all the ppc/aot code to handle function descriptors properly.
917 * So instead, we use the same approach as on PPC32.
918 * This is a horrible mess, but fixing it would probably lead to an even bigger
924 * - similar to the PPC32 design, we reserve EBX to hold the GOT pointer.
927 #ifdef MONO_ARCH_AOT_SUPPORTED
929 * arch_emit_got_offset:
931 * The memory pointed to by CODE should hold native code for computing the GOT
932 * address (OP_LOAD_GOTADDR). Emit this code while patching it with the offset
933 * between code and the GOT. CODE_SIZE is set to the number of bytes emitted.
936 arch_emit_got_offset (MonoAotCompile *acfg, guint8 *code, int *code_size)
938 #if defined(TARGET_POWERPC64)
939 emit_unset_mode (acfg);
941 * The ppc32 code doesn't seem to work on ppc64, the assembler complains about
942 * unsupported relocations. So we store the got address into the .Lgot_addr
943 * symbol which is in the text segment, compute its address, and load it.
945 fprintf (acfg->fp, ".L%d:\n", acfg->label_generator);
946 fprintf (acfg->fp, "lis 0, (.Lgot_addr + 4 - .L%d)@h\n", acfg->label_generator);
947 fprintf (acfg->fp, "ori 0, 0, (.Lgot_addr + 4 - .L%d)@l\n", acfg->label_generator);
948 fprintf (acfg->fp, "add 30, 30, 0\n");
949 fprintf (acfg->fp, "%s 30, 0(30)\n", PPC_LD_OP);
950 acfg->label_generator ++;
952 #elif defined(TARGET_POWERPC)
953 emit_unset_mode (acfg);
954 fprintf (acfg->fp, ".L%d:\n", acfg->label_generator);
955 fprintf (acfg->fp, "lis 0, (%s + 4 - .L%d)@h\n", acfg->got_symbol, acfg->label_generator);
956 fprintf (acfg->fp, "ori 0, 0, (%s + 4 - .L%d)@l\n", acfg->got_symbol, acfg->label_generator);
957 acfg->label_generator ++;
960 guint32 offset = mono_arch_get_patch_offset (code);
961 emit_bytes (acfg, code, offset);
962 emit_symbol_diff (acfg, acfg->got_symbol, ".", offset);
964 *code_size = offset + 4;
969 * arch_emit_got_access:
971 * The memory pointed to by CODE should hold native code for loading a GOT
972 * slot (OP_AOTCONST/OP_GOT_ENTRY). Emit this code while patching it so it accesses the
973 * GOT slot GOT_SLOT. CODE_SIZE is set to the number of bytes emitted.
976 arch_emit_got_access (MonoAotCompile *acfg, const char *got_symbol, guint8 *code, int got_slot, int *code_size)
979 /* mov reg, got+offset(%rip) */
981 /* The GOT symbol is in the LLVM module, the clang assembler has problems emitting symbol diffs for it */
985 /* Decode reg, see amd64_mov_reg_membase () */
986 rex_r = code [0] & AMD64_REX_R;
987 g_assert (code [0] == 0x49 + rex_r);
988 g_assert (code [1] == 0x8b);
989 dreg = ((code [2] >> 3) & 0x7) + (rex_r ? 8 : 0);
991 emit_unset_mode (acfg);
992 fprintf (acfg->fp, "mov %s+%d(%%rip), %s\n", got_symbol, (unsigned int) ((got_slot * sizeof (gpointer))), mono_arch_regname (dreg));
995 emit_bytes (acfg, code, mono_arch_get_patch_offset (code));
996 emit_symbol_diff (acfg, got_symbol, ".", (unsigned int) ((got_slot * sizeof (gpointer)) - 4));
997 *code_size = mono_arch_get_patch_offset (code) + 4;
999 #elif defined(TARGET_X86)
1000 emit_bytes (acfg, code, mono_arch_get_patch_offset (code));
1001 emit_int32 (acfg, (unsigned int) ((got_slot * sizeof (gpointer))));
1002 *code_size = mono_arch_get_patch_offset (code) + 4;
1003 #elif defined(TARGET_ARM)
1004 emit_bytes (acfg, code, mono_arch_get_patch_offset (code));
1005 emit_symbol_diff (acfg, got_symbol, ".", (unsigned int) ((got_slot * sizeof (gpointer))) - 12);
1006 *code_size = mono_arch_get_patch_offset (code) + 4;
1007 #elif defined(TARGET_ARM64)
1008 emit_bytes (acfg, code, mono_arch_get_patch_offset (code));
1009 arm64_emit_got_access (acfg, code, got_slot, code_size);
1010 #elif defined(TARGET_POWERPC)
1015 emit_bytes (acfg, code, mono_arch_get_patch_offset (code));
1017 ppc_load32 (code, ppc_r0, got_slot * sizeof (gpointer));
1018 g_assert (code - buf == 8);
1019 emit_bytes (acfg, buf, code - buf);
1020 *code_size = code - buf;
1023 g_assert_not_reached ();
1029 #ifdef MONO_ARCH_AOT_SUPPORTED
1031 * arch_emit_objc_selector_ref:
1033 * Emit the implementation of OP_OBJC_GET_SELECTOR, which itself implements @selector(foo:) in objective-c.
1036 arch_emit_objc_selector_ref (MonoAotCompile *acfg, guint8 *code, int index, int *code_size)
1038 #if defined(TARGET_ARM)
1041 int lindex = acfg->objc_selector_index_2 ++;
1043 /* Emit ldr.imm/b */
1044 emit_bytes (acfg, code, 8);
1046 sprintf (symbol1, "L_OBJC_SELECTOR_%d", lindex);
1047 sprintf (symbol2, "L_OBJC_SELECTOR_REFERENCES_%d", index);
1049 emit_label (acfg, symbol1);
1050 mono_img_writer_emit_unset_mode (acfg->w);
1051 fprintf (acfg->fp, ".long %s-(%s+12)", symbol2, symbol1);
1054 #elif defined(TARGET_ARM64)
1055 arm64_emit_objc_selector_ref (acfg, code, index, code_size);
1057 g_assert_not_reached ();
1063 * arch_emit_plt_entry:
1065 * Emit code for the PLT entry.
1066 * The plt entry should look like this:
1067 * <indirect jump to GOT_SYMBOL + OFFSET>
1068 * <INFO_OFFSET embedded into the instruction stream>
1071 arch_emit_plt_entry (MonoAotCompile *acfg, const char *got_symbol, int offset, int info_offset)
1073 #if defined(TARGET_X86)
1074 #if defined(__default_codegen__)
1075 /* jmp *<offset>(%ebx) */
1076 emit_byte (acfg, 0xff);
1077 emit_byte (acfg, 0xa3);
1078 emit_int32 (acfg, offset);
1079 /* Used by mono_aot_get_plt_info_offset */
1080 emit_int32 (acfg, info_offset);
1081 #elif defined(__native_client_codegen__)
1082 const guint8 kSizeOfNaClJmp = 11;
1083 guint8 bytes[kSizeOfNaClJmp];
1084 guint8 *pbytes = &bytes[0];
1086 x86_jump_membase32 (pbytes, X86_EBX, offset);
1087 emit_bytes (acfg, bytes, kSizeOfNaClJmp);
1088 /* four bytes of data, used by mono_arch_patch_plt_entry */
1089 /* For Native Client, make this work with data embedded in push. */
1090 emit_byte (acfg, 0x68); /* hide data in a push */
1091 emit_int32 (acfg, info_offset);
1092 emit_alignment (acfg, AOT_FUNC_ALIGNMENT);
1093 #endif /*__native_client_codegen__*/
1094 #elif defined(TARGET_AMD64)
1095 #if defined(__default_codegen__)
1096 emit_unset_mode (acfg);
1097 fprintf (acfg->fp, "jmp *%s+%d(%%rip)\n", got_symbol, offset);
1098 /* Used by mono_aot_get_plt_info_offset */
1099 emit_int32 (acfg, info_offset);
1100 acfg->stats.plt_size += 10;
1101 #elif defined(__native_client_codegen__)
1103 guint8 *buf_aligned = ALIGN_TO(buf, kNaClAlignment);
1104 guint8 *code = buf_aligned;
1106 /* mov <OFFSET>(%rip), %r11d */
1107 emit_byte (acfg, '\x45');
1108 emit_byte (acfg, '\x8b');
1109 emit_byte (acfg, '\x1d');
1110 emit_symbol_diff (acfg, got_symbol, ".", offset - 4);
1112 amd64_jump_reg (code, AMD64_R11);
1113 /* This should be constant for the plt patch */
1114 g_assert ((size_t)(code-buf_aligned) == 10);
1115 emit_bytes (acfg, buf_aligned, code - buf_aligned);
1117 /* Hide data in a push imm32 so it passes validation */
1118 emit_byte (acfg, 0x68); /* push */
1119 emit_int32 (acfg, info_offset);
1120 emit_alignment (acfg, AOT_FUNC_ALIGNMENT);
1121 #endif /*__native_client_codegen__*/
1122 #elif defined(TARGET_ARM)
1127 ARM_LDR_IMM (code, ARMREG_IP, ARMREG_PC, 0);
1128 ARM_LDR_REG_REG (code, ARMREG_PC, ARMREG_PC, ARMREG_IP);
1129 emit_bytes (acfg, buf, code - buf);
1130 emit_symbol_diff (acfg, got_symbol, ".", offset - 4);
1131 /* Used by mono_aot_get_plt_info_offset */
1132 emit_int32 (acfg, info_offset);
1133 #elif defined(TARGET_ARM64)
1134 arm64_emit_plt_entry (acfg, got_symbol, offset, info_offset);
1135 #elif defined(TARGET_POWERPC)
1136 /* The GOT address is guaranteed to be in r30 by OP_LOAD_GOTADDR */
1137 emit_unset_mode (acfg);
1138 fprintf (acfg->fp, "lis 11, %d@h\n", offset);
1139 fprintf (acfg->fp, "ori 11, 11, %d@l\n", offset);
1140 fprintf (acfg->fp, "add 11, 11, 30\n");
1141 fprintf (acfg->fp, "%s 11, 0(11)\n", PPC_LD_OP);
1142 #ifdef PPC_USES_FUNCTION_DESCRIPTOR
1143 fprintf (acfg->fp, "%s 2, %d(11)\n", PPC_LD_OP, (int)sizeof (gpointer));
1144 fprintf (acfg->fp, "%s 11, 0(11)\n", PPC_LD_OP);
1146 fprintf (acfg->fp, "mtctr 11\n");
1147 fprintf (acfg->fp, "bctr\n");
1148 emit_int32 (acfg, info_offset);
1150 g_assert_not_reached ();
1155 * arch_emit_llvm_plt_entry:
1157 * Same as arch_emit_plt_entry, but handles calls from LLVM generated code.
1158 * This is only needed on arm to handle thumb interop.
1161 arch_emit_llvm_plt_entry (MonoAotCompile *acfg, const char *got_symbol, int offset, int info_offset)
1163 #if defined(TARGET_ARM)
1164 /* LLVM calls the PLT entries using bl, so these have to be thumb2 */
1165 /* The caller already transitioned to thumb */
1166 /* The code below should be 12 bytes long */
1167 /* clang has trouble encoding these instructions, so emit the binary */
1169 fprintf (acfg->fp, "ldr ip, [pc, #8]\n");
1170 /* thumb can't encode ld pc, [pc, ip] */
1171 fprintf (acfg->fp, "add ip, pc, ip\n");
1172 fprintf (acfg->fp, "ldr ip, [ip, #0]\n");
1173 fprintf (acfg->fp, "bx ip\n");
1175 emit_set_thumb_mode (acfg);
1176 fprintf (acfg->fp, ".4byte 0xc008f8df\n");
1177 fprintf (acfg->fp, ".2byte 0x44fc\n");
1178 fprintf (acfg->fp, ".4byte 0xc000f8dc\n");
1179 fprintf (acfg->fp, ".2byte 0x4760\n");
1180 emit_symbol_diff (acfg, got_symbol, ".", offset + 4);
1181 emit_int32 (acfg, info_offset);
1182 emit_unset_mode (acfg);
1183 emit_set_arm_mode (acfg);
1185 g_assert_not_reached ();
1189 /* Save unwind_info in the module and emit the offset to the information at symbol */
1190 static void save_unwind_info (MonoAotCompile *acfg, char *symbol, GSList *unwind_ops)
1192 guint32 uw_offset, encoded_len;
1195 emit_section_change (acfg, RODATA_SECT, 0);
1196 emit_global (acfg, symbol, FALSE);
1197 emit_label (acfg, symbol);
1199 encoded = mono_unwind_ops_encode (unwind_ops, &encoded_len);
1200 uw_offset = get_unwind_info_offset (acfg, encoded, encoded_len);
1202 emit_int32 (acfg, uw_offset);
1206 * arch_emit_specific_trampoline_pages:
1208 * Emits a page full of trampolines: each trampoline uses its own address to
1209 * lookup both the generic trampoline code and the data argument.
1210 * This page can be remapped in process multiple times so we can get an
1211 * unlimited number of trampolines.
1212 * Specifically this implementation uses the following trick: two memory pages
1213 * are allocated, with the first containing the data and the second containing the trampolines.
1214 * To reduce trampoline size, each trampoline jumps at the start of the page where a common
1215 * implementation does all the lifting.
1216 * Note that the ARM single trampoline size is 8 bytes, exactly like the data that needs to be stored
1217 * on the arm 32 bit system.
1220 arch_emit_specific_trampoline_pages (MonoAotCompile *acfg)
1222 #if defined(TARGET_ARM)
1225 guint8 *loop_start, *loop_branch_back, *loop_end_check, *imt_found_check;
1227 int pagesize = MONO_AOT_TRAMP_PAGE_SIZE;
1228 GSList *unwind_ops = NULL;
1229 #define COMMON_TRAMP_SIZE 16
1230 int count = (pagesize - COMMON_TRAMP_SIZE) / 8;
1231 int imm8, rot_amount;
1234 if (!acfg->aot_opts.use_trampolines_page)
1237 acfg->tramp_page_size = pagesize;
1239 sprintf (symbol, "%sspecific_trampolines_page", acfg->user_symbol_prefix);
1240 emit_alignment (acfg, pagesize);
1241 emit_global (acfg, symbol, TRUE);
1242 emit_label (acfg, symbol);
1244 /* emit the generic code first, the trampoline address + 8 is in the lr register */
1246 imm8 = mono_arm_is_rotated_imm8 (pagesize, &rot_amount);
1247 ARM_SUB_REG_IMM (code, ARMREG_LR, ARMREG_LR, imm8, rot_amount);
1248 ARM_LDR_IMM (code, ARMREG_R1, ARMREG_LR, -8);
1249 ARM_LDR_IMM (code, ARMREG_PC, ARMREG_LR, -4);
1251 g_assert (code - buf == COMMON_TRAMP_SIZE);
1254 emit_bytes (acfg, buf, code - buf);
1256 for (i = 0; i < count; ++i) {
1258 ARM_PUSH (code, 0x5fff);
1260 arm_patch (code - 4, code - COMMON_TRAMP_SIZE - 8 * (i + 1));
1261 g_assert (code - buf == 8);
1262 emit_bytes (acfg, buf, code - buf);
1265 /* now the rgctx trampolines: each specific trampolines puts in the ip register
1266 * the instruction pointer address, so the generic trampoline at the start of the page
1267 * subtracts 4096 to get to the data page and loads the values
1268 * We again fit the generic trampiline in 16 bytes.
1270 sprintf (symbol, "%srgctx_trampolines_page", acfg->user_symbol_prefix);
1271 emit_global (acfg, symbol, TRUE);
1272 emit_label (acfg, symbol);
1274 imm8 = mono_arm_is_rotated_imm8 (pagesize, &rot_amount);
1275 ARM_SUB_REG_IMM (code, ARMREG_IP, ARMREG_IP, imm8, rot_amount);
1276 ARM_LDR_IMM (code, MONO_ARCH_RGCTX_REG, ARMREG_IP, -8);
1277 ARM_LDR_IMM (code, ARMREG_PC, ARMREG_IP, -4);
1279 g_assert (code - buf == COMMON_TRAMP_SIZE);
1282 emit_bytes (acfg, buf, code - buf);
1284 for (i = 0; i < count; ++i) {
1286 ARM_MOV_REG_REG (code, ARMREG_IP, ARMREG_PC);
1288 arm_patch (code - 4, code - COMMON_TRAMP_SIZE - 8 * (i + 1));
1289 g_assert (code - buf == 8);
1290 emit_bytes (acfg, buf, code - buf);
1294 * gsharedvt arg trampolines: see arch_emit_gsharedvt_arg_trampoline ()
1296 sprintf (symbol, "%sgsharedvt_arg_trampolines_page", acfg->user_symbol_prefix);
1297 emit_global (acfg, symbol, TRUE);
1298 emit_label (acfg, symbol);
1300 ARM_PUSH (code, (1 << ARMREG_R0) | (1 << ARMREG_R1) | (1 << ARMREG_R2) | (1 << ARMREG_R3));
1301 imm8 = mono_arm_is_rotated_imm8 (pagesize, &rot_amount);
1302 ARM_SUB_REG_IMM (code, ARMREG_IP, ARMREG_IP, imm8, rot_amount);
1303 ARM_LDR_IMM (code, ARMREG_R0, ARMREG_IP, -8);
1304 ARM_LDR_IMM (code, ARMREG_PC, ARMREG_IP, -4);
1305 g_assert (code - buf == COMMON_TRAMP_SIZE);
1307 emit_bytes (acfg, buf, code - buf);
1309 for (i = 0; i < count; ++i) {
1311 ARM_MOV_REG_REG (code, ARMREG_IP, ARMREG_PC);
1313 arm_patch (code - 4, code - COMMON_TRAMP_SIZE - 8 * (i + 1));
1314 g_assert (code - buf == 8);
1315 emit_bytes (acfg, buf, code - buf);
1318 /* now the imt trampolines: each specific trampolines puts in the ip register
1319 * the instruction pointer address, so the generic trampoline at the start of the page
1320 * subtracts 4096 to get to the data page and loads the values
1322 #define IMT_TRAMP_SIZE 72
1323 sprintf (symbol, "%simt_trampolines_page", acfg->user_symbol_prefix);
1324 emit_global (acfg, symbol, TRUE);
1325 emit_label (acfg, symbol);
1327 /* Need at least two free registers, plus a slot for storing the pc */
1328 ARM_PUSH (code, (1 << ARMREG_R0)|(1 << ARMREG_R1)|(1 << ARMREG_R2));
1330 imm8 = mono_arm_is_rotated_imm8 (pagesize, &rot_amount);
1331 ARM_SUB_REG_IMM (code, ARMREG_IP, ARMREG_IP, imm8, rot_amount);
1332 ARM_LDR_IMM (code, ARMREG_R0, ARMREG_IP, -8);
1334 /* The IMT method is in v5, r0 has the imt array address */
1337 ARM_LDR_IMM (code, ARMREG_R1, ARMREG_R0, 0);
1338 ARM_CMP_REG_REG (code, ARMREG_R1, ARMREG_V5);
1339 imt_found_check = code;
1340 ARM_B_COND (code, ARMCOND_EQ, 0);
1342 /* End-of-loop check */
1343 ARM_CMP_REG_IMM (code, ARMREG_R1, 0, 0);
1344 loop_end_check = code;
1345 ARM_B_COND (code, ARMCOND_EQ, 0);
1348 ARM_ADD_REG_IMM8 (code, ARMREG_R0, ARMREG_R0, sizeof (gpointer) * 2);
1349 loop_branch_back = code;
1351 arm_patch (loop_branch_back, loop_start);
1354 arm_patch (imt_found_check, code);
1355 ARM_LDR_IMM (code, ARMREG_R0, ARMREG_R0, 4);
1356 ARM_LDR_IMM (code, ARMREG_R0, ARMREG_R0, 0);
1357 /* Save it to the third stack slot */
1358 ARM_STR_IMM (code, ARMREG_R0, ARMREG_SP, 8);
1359 /* Restore the registers and branch */
1360 ARM_POP (code, (1 << ARMREG_R0)|(1 << ARMREG_R1)|(1 << ARMREG_PC));
1363 arm_patch (loop_end_check, code);
1364 ARM_LDR_IMM (code, ARMREG_R0, ARMREG_R0, 4);
1365 ARM_STR_IMM (code, ARMREG_R0, ARMREG_SP, 8);
1366 ARM_POP (code, (1 << ARMREG_R0)|(1 << ARMREG_R1)|(1 << ARMREG_PC));
1370 g_assert (code - buf == IMT_TRAMP_SIZE);
1371 emit_bytes (acfg, buf, code - buf);
1373 for (i = 0; i < count; ++i) {
1375 ARM_MOV_REG_REG (code, ARMREG_IP, ARMREG_PC);
1377 arm_patch (code - 4, code - IMT_TRAMP_SIZE - 8 * (i + 1));
1378 g_assert (code - buf == 8);
1379 emit_bytes (acfg, buf, code - buf);
1382 acfg->tramp_page_code_offsets [MONO_AOT_TRAMP_SPECIFIC] = 16;
1383 acfg->tramp_page_code_offsets [MONO_AOT_TRAMP_STATIC_RGCTX] = 16;
1384 acfg->tramp_page_code_offsets [MONO_AOT_TRAMP_IMT_THUNK] = 72;
1385 acfg->tramp_page_code_offsets [MONO_AOT_TRAMP_GSHAREDVT_ARG] = 16;
1387 /* Unwind info for specifc trampolines */
1388 sprintf (symbol, "%sspecific_trampolines_page_gen_p", acfg->user_symbol_prefix);
1389 /* We unwind to the original caller, from the stack, since lr is clobbered */
1390 mono_add_unwind_op_def_cfa (unwind_ops, 0, 0, ARMREG_SP, 14 * sizeof (mgreg_t));
1391 mono_add_unwind_op_offset (unwind_ops, 0, 0, ARMREG_LR, -4);
1392 save_unwind_info (acfg, symbol, unwind_ops);
1393 mono_free_unwind_info (unwind_ops);
1395 sprintf (symbol, "%sspecific_trampolines_page_sp_p", acfg->user_symbol_prefix);
1396 mono_add_unwind_op_def_cfa (unwind_ops, 0, 0, ARMREG_SP, 0);
1397 mono_add_unwind_op_def_cfa_offset (unwind_ops, 4, 0, 14 * sizeof (mgreg_t));
1398 save_unwind_info (acfg, symbol, unwind_ops);
1399 mono_free_unwind_info (unwind_ops);
1401 /* Unwind info for rgctx trampolines */
1402 sprintf (symbol, "%srgctx_trampolines_page_gen_p", acfg->user_symbol_prefix);
1403 mono_add_unwind_op_def_cfa (unwind_ops, 0, 0, ARMREG_SP, 0);
1404 save_unwind_info (acfg, symbol, unwind_ops);
1406 sprintf (symbol, "%srgctx_trampolines_page_sp_p", acfg->user_symbol_prefix);
1407 save_unwind_info (acfg, symbol, unwind_ops);
1408 mono_free_unwind_info (unwind_ops);
1410 /* Unwind info for gsharedvt trampolines */
1411 sprintf (symbol, "%sgsharedvt_trampolines_page_gen_p", acfg->user_symbol_prefix);
1412 mono_add_unwind_op_def_cfa (unwind_ops, 0, 0, ARMREG_SP, 0);
1413 mono_add_unwind_op_def_cfa_offset (unwind_ops, 4, 0, 4 * sizeof (mgreg_t));
1414 save_unwind_info (acfg, symbol, unwind_ops);
1415 mono_free_unwind_info (unwind_ops);
1417 sprintf (symbol, "%sgsharedvt_trampolines_page_sp_p", acfg->user_symbol_prefix);
1418 mono_add_unwind_op_def_cfa (unwind_ops, 0, 0, ARMREG_SP, 0);
1419 save_unwind_info (acfg, symbol, unwind_ops);
1420 mono_free_unwind_info (unwind_ops);
1422 /* Unwind info for imt trampolines */
1423 sprintf (symbol, "%simt_trampolines_page_gen_p", acfg->user_symbol_prefix);
1424 mono_add_unwind_op_def_cfa (unwind_ops, 0, 0, ARMREG_SP, 0);
1425 mono_add_unwind_op_def_cfa_offset (unwind_ops, 4, 0, 3 * sizeof (mgreg_t));
1426 save_unwind_info (acfg, symbol, unwind_ops);
1427 mono_free_unwind_info (unwind_ops);
1429 sprintf (symbol, "%simt_trampolines_page_sp_p", acfg->user_symbol_prefix);
1430 mono_add_unwind_op_def_cfa (unwind_ops, 0, 0, ARMREG_SP, 0);
1431 save_unwind_info (acfg, symbol, unwind_ops);
1432 mono_free_unwind_info (unwind_ops);
1433 #elif defined(TARGET_ARM64)
1434 arm64_emit_specific_trampoline_pages (acfg);
1439 * arch_emit_specific_trampoline:
1441 * Emit code for a specific trampoline. OFFSET is the offset of the first of
1442 * two GOT slots which contain the generic trampoline address and the trampoline
1443 * argument. TRAMP_SIZE is set to the size of the emitted trampoline.
1446 arch_emit_specific_trampoline (MonoAotCompile *acfg, int offset, int *tramp_size)
1449 * The trampolines created here are variations of the specific
1450 * trampolines created in mono_arch_create_specific_trampoline (). The
1452 * - the generic trampoline address is taken from a got slot.
1453 * - the offset of the got slot where the trampoline argument is stored
1454 * is embedded in the instruction stream, and the generic trampoline
1455 * can load the argument by loading the offset, adding it to the
1456 * address of the trampoline to get the address of the got slot, and
1457 * loading the argument from there.
1458 * - all the trampolines should be of the same length.
1460 #if defined(TARGET_AMD64)
1461 #if defined(__default_codegen__)
1462 /* This should be exactly 8 bytes long */
1464 /* call *<offset>(%rip) */
1466 emit_unset_mode (acfg);
1467 fprintf (acfg->fp, "call *%s+%d(%%rip)\n", acfg->got_symbol, (int)(offset * sizeof (gpointer)));
1468 emit_zero_bytes (acfg, 2);
1470 emit_byte (acfg, '\x41');
1471 emit_byte (acfg, '\xff');
1472 emit_byte (acfg, '\x15');
1473 emit_symbol_diff (acfg, acfg->got_symbol, ".", (offset * sizeof (gpointer)) - 4);
1474 emit_zero_bytes (acfg, 1);
1476 #elif defined(__native_client_codegen__)
1478 guint8 *buf_aligned = ALIGN_TO(buf, kNaClAlignment);
1479 guint8 *code = buf_aligned;
1484 /* Emit this call in 'code' so we can find out how long it is. */
1485 amd64_call_reg (code, AMD64_R11);
1486 call_start = mono_arch_nacl_skip_nops (buf_aligned);
1487 call_len = code - call_start;
1489 /* The tramp_size is twice the NaCl alignment because it starts with */
1490 /* a call which needs to be aligned to the end of the boundary. */
1491 *tramp_size = kNaClAlignment*2;
1493 /* Emit nops to align call site below which is 7 bytes plus */
1494 /* the length of the call sequence emitted above. */
1495 /* Note: this requires the specific trampoline starts on a */
1496 /* kNaclAlignedment aligned address, which it does because */
1497 /* it's its own function that is aligned. */
1498 guint8 nop_buf[256];
1499 guint8 *nopbuf_aligned = ALIGN_TO (nop_buf, kNaClAlignment);
1500 guint8 *nopbuf_end = mono_arch_nacl_pad (nopbuf_aligned, kNaClAlignment - 7 - (call_len));
1501 emit_bytes (acfg, nopbuf_aligned, nopbuf_end - nopbuf_aligned);
1503 /* The trampoline is stored at the offset'th pointer, the -4 is */
1504 /* present because RIP relative addressing starts at the end of */
1505 /* the current instruction, while the label "." is relative to */
1506 /* the beginning of the current asm location, which in this case */
1507 /* is not the mov instruction, but the offset itself, due to the */
1508 /* way the bytes and ints are emitted here. */
1509 got_offset = (offset * sizeof(gpointer)) - 4;
1511 /* mov <OFFSET>(%rip), %r11d */
1512 emit_byte (acfg, '\x45');
1513 emit_byte (acfg, '\x8b');
1514 emit_byte (acfg, '\x1d');
1515 emit_symbol_diff (acfg, acfg->got_symbol, ".", got_offset);
1518 emit_bytes (acfg, call_start, call_len);
1520 /* The arg is stored at the offset+1 pointer, relative to beginning */
1521 /* of trampoline: 7 for mov, plus the call length, and 1 for push. */
1522 got_offset = ((offset + 1) * sizeof(gpointer)) + 7 + call_len + 1;
1524 /* We can't emit this data directly, hide in a "push imm32" */
1525 emit_byte (acfg, '\x68'); /* push */
1526 emit_symbol_diff (acfg, acfg->got_symbol, ".", got_offset);
1527 emit_alignment (acfg, kNaClAlignment);
1528 #endif /*__native_client_codegen__*/
1529 #elif defined(TARGET_ARM)
1533 /* This should be exactly 20 bytes long */
1536 ARM_PUSH (code, 0x5fff);
1537 ARM_LDR_IMM (code, ARMREG_R1, ARMREG_PC, 4);
1538 /* Load the value from the GOT */
1539 ARM_LDR_REG_REG (code, ARMREG_R1, ARMREG_PC, ARMREG_R1);
1541 ARM_BLX_REG (code, ARMREG_R1);
1543 g_assert (code - buf == 16);
1546 emit_bytes (acfg, buf, code - buf);
1548 * Only one offset is needed, since the second one would be equal to the
1551 emit_symbol_diff (acfg, acfg->got_symbol, ".", (offset * sizeof (gpointer)) - 4 + 4);
1552 //emit_symbol_diff (acfg, acfg->got_symbol, ".", ((offset + 1) * sizeof (gpointer)) - 4 + 8);
1553 #elif defined(TARGET_ARM64)
1554 arm64_emit_specific_trampoline (acfg, offset, tramp_size);
1555 #elif defined(TARGET_POWERPC)
1563 * PPC has no ip relative addressing, so we need to compute the address
1564 * of the mscorlib got. That is slow and complex, so instead, we store it
1565 * in the second got slot of every aot image. The caller already computed
1566 * the address of its got and placed it into r30.
1568 emit_unset_mode (acfg);
1569 /* Load mscorlib got address */
1570 fprintf (acfg->fp, "%s 0, %d(30)\n", PPC_LD_OP, (int)sizeof (gpointer));
1571 /* Load generic trampoline address */
1572 fprintf (acfg->fp, "lis 11, %d@h\n", (int)(offset * sizeof (gpointer)));
1573 fprintf (acfg->fp, "ori 11, 11, %d@l\n", (int)(offset * sizeof (gpointer)));
1574 fprintf (acfg->fp, "%s 11, 11, 0\n", PPC_LDX_OP);
1575 #ifdef PPC_USES_FUNCTION_DESCRIPTOR
1576 fprintf (acfg->fp, "%s 11, 0(11)\n", PPC_LD_OP);
1578 fprintf (acfg->fp, "mtctr 11\n");
1579 /* Load trampoline argument */
1580 /* On ppc, we pass it normally to the generic trampoline */
1581 fprintf (acfg->fp, "lis 11, %d@h\n", (int)((offset + 1) * sizeof (gpointer)));
1582 fprintf (acfg->fp, "ori 11, 11, %d@l\n", (int)((offset + 1) * sizeof (gpointer)));
1583 fprintf (acfg->fp, "%s 0, 11, 0\n", PPC_LDX_OP);
1584 /* Branch to generic trampoline */
1585 fprintf (acfg->fp, "bctr\n");
1587 #ifdef PPC_USES_FUNCTION_DESCRIPTOR
1588 *tramp_size = 10 * 4;
1590 *tramp_size = 9 * 4;
1592 #elif defined(TARGET_X86)
1596 /* Similar to the PPC code above */
1598 /* FIXME: Could this clobber the register needed by get_vcall_slot () ? */
1601 /* Load mscorlib got address */
1602 x86_mov_reg_membase (code, X86_ECX, MONO_ARCH_GOT_REG, sizeof (gpointer), 4);
1603 /* Push trampoline argument */
1604 x86_push_membase (code, X86_ECX, (offset + 1) * sizeof (gpointer));
1605 /* Load generic trampoline address */
1606 x86_mov_reg_membase (code, X86_ECX, X86_ECX, offset * sizeof (gpointer), 4);
1607 /* Branch to generic trampoline */
1608 x86_jump_reg (code, X86_ECX);
1610 #ifdef __native_client_codegen__
1612 /* emit nops to next 32 byte alignment */
1613 int a = (~kNaClAlignmentMask) & ((code - buf) + kNaClAlignment - 1);
1614 while (code < (buf + a)) x86_nop(code);
1617 emit_bytes (acfg, buf, code - buf);
1619 *tramp_size = NACL_SIZE(17, kNaClAlignment);
1620 g_assert (code - buf == *tramp_size);
1622 g_assert_not_reached ();
1627 * arch_emit_unbox_trampoline:
1629 * Emit code for the unbox trampoline for METHOD used in the full-aot case.
1630 * CALL_TARGET is the symbol pointing to the native code of METHOD.
1633 arch_emit_unbox_trampoline (MonoAotCompile *acfg, MonoCompile *cfg, MonoMethod *method, const char *call_target)
1635 #if defined(TARGET_AMD64)
1640 this_reg = mono_arch_get_this_arg_reg (NULL);
1642 amd64_alu_reg_imm (code, X86_ADD, this_reg, sizeof (MonoObject));
1644 emit_bytes (acfg, buf, code - buf);
1647 emit_unset_mode (acfg);
1648 fprintf (acfg->fp, "jmp %s\n", call_target);
1650 emit_byte (acfg, '\xe9');
1651 emit_symbol_diff (acfg, call_target, ".", -4);
1653 #elif defined(TARGET_X86)
1660 x86_alu_membase_imm (code, X86_ADD, X86_ESP, this_pos, sizeof (MonoObject));
1662 emit_bytes (acfg, buf, code - buf);
1665 emit_byte (acfg, '\xe9');
1666 emit_symbol_diff (acfg, call_target, ".", -4);
1667 #elif defined(TARGET_ARM)
1671 if (acfg->thumb_mixed && cfg->compile_llvm) {
1672 fprintf (acfg->fp, "add r0, r0, #%d\n", (int)sizeof (MonoObject));
1673 fprintf (acfg->fp, "b %s\n", call_target);
1674 fprintf (acfg->fp, ".arm\n");
1675 fprintf (acfg->fp, ".align 2\n");
1681 ARM_ADD_REG_IMM8 (code, ARMREG_R0, ARMREG_R0, sizeof (MonoObject));
1683 emit_bytes (acfg, buf, code - buf);
1684 /* jump to method */
1685 if (acfg->thumb_mixed && cfg->compile_llvm)
1686 fprintf (acfg->fp, "\n\tbx %s\n", call_target);
1688 fprintf (acfg->fp, "\n\tb %s\n", call_target);
1689 #elif defined(TARGET_ARM64)
1690 arm64_emit_unbox_trampoline (acfg, cfg, method, call_target);
1691 #elif defined(TARGET_POWERPC)
1694 fprintf (acfg->fp, "\n\taddi %d, %d, %d\n", this_pos, this_pos, (int)sizeof (MonoObject));
1695 fprintf (acfg->fp, "\n\tb %s\n", call_target);
1697 g_assert_not_reached ();
1702 * arch_emit_static_rgctx_trampoline:
1704 * Emit code for a static rgctx trampoline. OFFSET is the offset of the first of
1705 * two GOT slots which contain the rgctx argument, and the method to jump to.
1706 * TRAMP_SIZE is set to the size of the emitted trampoline.
1707 * These kinds of trampolines cannot be enumerated statically, since there could
1708 * be one trampoline per method instantiation, so we emit the same code for all
1709 * trampolines, and parameterize them using two GOT slots.
1712 arch_emit_static_rgctx_trampoline (MonoAotCompile *acfg, int offset, int *tramp_size)
1714 #if defined(TARGET_AMD64)
1715 #if defined(__default_codegen__)
1716 /* This should be exactly 13 bytes long */
1720 emit_unset_mode (acfg);
1721 fprintf (acfg->fp, "mov %s+%d(%%rip), %%r10\n", acfg->got_symbol, (int)(offset * sizeof (gpointer)));
1722 fprintf (acfg->fp, "jmp *%s+%d(%%rip)\n", acfg->got_symbol, (int)((offset + 1) * sizeof (gpointer)));
1724 /* mov <OFFSET>(%rip), %r10 */
1725 emit_byte (acfg, '\x4d');
1726 emit_byte (acfg, '\x8b');
1727 emit_byte (acfg, '\x15');
1728 emit_symbol_diff (acfg, acfg->got_symbol, ".", (offset * sizeof (gpointer)) - 4);
1730 /* jmp *<offset>(%rip) */
1731 emit_byte (acfg, '\xff');
1732 emit_byte (acfg, '\x25');
1733 emit_symbol_diff (acfg, acfg->got_symbol, ".", ((offset + 1) * sizeof (gpointer)) - 4);
1735 #elif defined(__native_client_codegen__)
1737 guint8 *buf_aligned = ALIGN_TO(buf, kNaClAlignment);
1738 guint8 *code = buf_aligned;
1740 /* mov <OFFSET>(%rip), %r10d */
1741 emit_byte (acfg, '\x45');
1742 emit_byte (acfg, '\x8b');
1743 emit_byte (acfg, '\x15');
1744 emit_symbol_diff (acfg, acfg->got_symbol, ".", (offset * sizeof (gpointer)) - 4);
1746 /* mov <OFFSET>(%rip), %r11d */
1747 emit_byte (acfg, '\x45');
1748 emit_byte (acfg, '\x8b');
1749 emit_byte (acfg, '\x1d');
1750 emit_symbol_diff (acfg, acfg->got_symbol, ".", ((offset + 1) * sizeof (gpointer)) - 4);
1753 amd64_jump_reg (code, AMD64_R11);
1754 emit_bytes (acfg, buf_aligned, code - buf_aligned);
1756 emit_alignment (acfg, kNaClAlignment);
1757 *tramp_size = kNaClAlignment;
1758 #endif /*__native_client_codegen__*/
1760 #elif defined(TARGET_ARM)
1764 /* This should be exactly 24 bytes long */
1767 /* Load rgctx value */
1768 ARM_LDR_IMM (code, ARMREG_IP, ARMREG_PC, 8);
1769 ARM_LDR_REG_REG (code, MONO_ARCH_RGCTX_REG, ARMREG_PC, ARMREG_IP);
1770 /* Load branch addr + branch */
1771 ARM_LDR_IMM (code, ARMREG_IP, ARMREG_PC, 4);
1772 ARM_LDR_REG_REG (code, ARMREG_PC, ARMREG_PC, ARMREG_IP);
1774 g_assert (code - buf == 16);
1777 emit_bytes (acfg, buf, code - buf);
1778 emit_symbol_diff (acfg, acfg->got_symbol, ".", (offset * sizeof (gpointer)) - 4 + 8);
1779 emit_symbol_diff (acfg, acfg->got_symbol, ".", ((offset + 1) * sizeof (gpointer)) - 4 + 4);
1780 #elif defined(TARGET_ARM64)
1781 arm64_emit_static_rgctx_trampoline (acfg, offset, tramp_size);
1782 #elif defined(TARGET_POWERPC)
1790 * PPC has no ip relative addressing, so we need to compute the address
1791 * of the mscorlib got. That is slow and complex, so instead, we store it
1792 * in the second got slot of every aot image. The caller already computed
1793 * the address of its got and placed it into r30.
1795 emit_unset_mode (acfg);
1796 /* Load mscorlib got address */
1797 fprintf (acfg->fp, "%s 0, %d(30)\n", PPC_LD_OP, (int)sizeof (gpointer));
1799 fprintf (acfg->fp, "lis 11, %d@h\n", (int)(offset * sizeof (gpointer)));
1800 fprintf (acfg->fp, "ori 11, 11, %d@l\n", (int)(offset * sizeof (gpointer)));
1801 fprintf (acfg->fp, "%s %d, 11, 0\n", PPC_LDX_OP, MONO_ARCH_RGCTX_REG);
1802 /* Load target address */
1803 fprintf (acfg->fp, "lis 11, %d@h\n", (int)((offset + 1) * sizeof (gpointer)));
1804 fprintf (acfg->fp, "ori 11, 11, %d@l\n", (int)((offset + 1) * sizeof (gpointer)));
1805 fprintf (acfg->fp, "%s 11, 11, 0\n", PPC_LDX_OP);
1806 #ifdef PPC_USES_FUNCTION_DESCRIPTOR
1807 fprintf (acfg->fp, "%s 2, %d(11)\n", PPC_LD_OP, (int)sizeof (gpointer));
1808 fprintf (acfg->fp, "%s 11, 0(11)\n", PPC_LD_OP);
1810 fprintf (acfg->fp, "mtctr 11\n");
1811 /* Branch to the target address */
1812 fprintf (acfg->fp, "bctr\n");
1814 #ifdef PPC_USES_FUNCTION_DESCRIPTOR
1815 *tramp_size = 11 * 4;
1817 *tramp_size = 9 * 4;
1820 #elif defined(TARGET_X86)
1824 /* Similar to the PPC code above */
1826 g_assert (MONO_ARCH_RGCTX_REG != X86_ECX);
1829 /* Load mscorlib got address */
1830 x86_mov_reg_membase (code, X86_ECX, MONO_ARCH_GOT_REG, sizeof (gpointer), 4);
1832 x86_mov_reg_membase (code, MONO_ARCH_RGCTX_REG, X86_ECX, offset * sizeof (gpointer), 4);
1833 /* Branch to the target address */
1834 x86_jump_membase (code, X86_ECX, (offset + 1) * sizeof (gpointer));
1836 #ifdef __native_client_codegen__
1838 /* emit nops to next 32 byte alignment */
1839 int a = (~kNaClAlignmentMask) & ((code - buf) + kNaClAlignment - 1);
1840 while (code < (buf + a)) x86_nop(code);
1844 emit_bytes (acfg, buf, code - buf);
1846 *tramp_size = NACL_SIZE (15, kNaClAlignment);
1847 g_assert (code - buf == *tramp_size);
1849 g_assert_not_reached ();
1854 * arch_emit_imt_thunk:
1856 * Emit an IMT thunk usable in full-aot mode. The thunk uses 1 got slot which
1857 * points to an array of pointer pairs. The pairs of the form [key, ptr], where
1858 * key is the IMT key, and ptr holds the address of a memory location holding
1859 * the address to branch to if the IMT arg matches the key. The array is
1860 * terminated by a pair whose key is NULL, and whose ptr is the address of the
1862 * TRAMP_SIZE is set to the size of the emitted trampoline.
1865 arch_emit_imt_thunk (MonoAotCompile *acfg, int offset, int *tramp_size)
1867 #if defined(TARGET_AMD64)
1869 #if defined(__native_client_codegen__)
1872 guint8 *labels [16];
1874 guint8 *mov_buf_ptr = mov_buf;
1876 const int kSizeOfMove = 7;
1877 #if defined(__default_codegen__)
1878 code = buf = (guint8 *)g_malloc (256);
1879 #elif defined(__native_client_codegen__)
1880 buf_alloc = g_malloc (256 + kNaClAlignment + kSizeOfMove);
1881 buf = ((guint)buf_alloc + kNaClAlignment) & ~kNaClAlignmentMask;
1882 /* The RIP relative move below is emitted first */
1887 /* FIXME: Optimize this, i.e. use binary search etc. */
1888 /* Maybe move the body into a separate function (slower, but much smaller) */
1890 /* MONO_ARCH_IMT_SCRATCH_REG is a free register */
1893 emit_unset_mode (acfg);
1894 fprintf (acfg->fp, "mov %s+%d(%%rip), %s\n", acfg->got_symbol, (int)(offset * sizeof (gpointer)), mono_arch_regname (MONO_ARCH_IMT_SCRATCH_REG));
1898 amd64_alu_membase_imm (code, X86_CMP, MONO_ARCH_IMT_SCRATCH_REG, 0, 0);
1900 amd64_branch8 (code, X86_CC_Z, 0, FALSE);
1903 amd64_alu_membase_reg_size (code, X86_CMP, MONO_ARCH_IMT_SCRATCH_REG, 0, MONO_ARCH_IMT_REG, sizeof (gpointer));
1905 amd64_branch8 (code, X86_CC_Z, 0, FALSE);
1908 amd64_alu_reg_imm (code, X86_ADD, MONO_ARCH_IMT_SCRATCH_REG, 2 * sizeof (gpointer));
1909 amd64_jump_code (code, labels [0]);
1912 mono_amd64_patch (labels [2], code);
1913 amd64_mov_reg_membase (code, MONO_ARCH_IMT_SCRATCH_REG, MONO_ARCH_IMT_SCRATCH_REG, sizeof (gpointer), sizeof (gpointer));
1914 amd64_jump_membase (code, MONO_ARCH_IMT_SCRATCH_REG, 0);
1917 mono_amd64_patch (labels [1], code);
1918 /* Load fail tramp */
1919 amd64_alu_reg_imm (code, X86_ADD, MONO_ARCH_IMT_SCRATCH_REG, sizeof (gpointer));
1920 /* Check if there is a fail tramp */
1921 amd64_alu_membase_imm (code, X86_CMP, MONO_ARCH_IMT_SCRATCH_REG, 0, 0);
1923 amd64_branch8 (code, X86_CC_Z, 0, FALSE);
1924 /* Jump to fail tramp */
1925 amd64_jump_membase (code, MONO_ARCH_IMT_SCRATCH_REG, 0);
1928 mono_amd64_patch (labels [3], code);
1929 x86_breakpoint (code);
1932 /* mov <OFFSET>(%rip), MONO_ARCH_IMT_SCRATCH_REG */
1933 amd64_emit_rex (mov_buf_ptr, sizeof(gpointer), MONO_ARCH_IMT_SCRATCH_REG, 0, AMD64_RIP);
1934 *(mov_buf_ptr)++ = (unsigned char)0x8b; /* mov opcode */
1935 x86_address_byte (mov_buf_ptr, 0, MONO_ARCH_IMT_SCRATCH_REG & 0x7, 5);
1936 emit_bytes (acfg, mov_buf, mov_buf_ptr - mov_buf);
1937 emit_symbol_diff (acfg, acfg->got_symbol, ".", (offset * sizeof (gpointer)) - 4);
1939 emit_bytes (acfg, buf, code - buf);
1941 *tramp_size = code - buf + kSizeOfMove;
1942 #if defined(__native_client_codegen__)
1943 /* The tramp will be padded to the next kNaClAlignment bundle. */
1944 *tramp_size = ALIGN_TO ((*tramp_size), kNaClAlignment);
1947 #if defined(__default_codegen__)
1949 #elif defined(__native_client_codegen__)
1953 #elif defined(TARGET_X86)
1955 #ifdef __native_client_codegen__
1958 guint8 *labels [16];
1960 #if defined(__default_codegen__)
1961 code = buf = g_malloc (256);
1962 #elif defined(__native_client_codegen__)
1963 buf_alloc = g_malloc (256 + kNaClAlignment);
1964 code = buf = ((guint)buf_alloc + kNaClAlignment) & ~kNaClAlignmentMask;
1967 /* Allocate a temporary stack slot */
1968 x86_push_reg (code, X86_EAX);
1970 x86_push_reg (code, X86_EAX);
1972 /* Load mscorlib got address */
1973 x86_mov_reg_membase (code, X86_EAX, MONO_ARCH_GOT_REG, sizeof (gpointer), 4);
1975 x86_mov_reg_membase (code, X86_EAX, X86_EAX, offset * sizeof (gpointer), 4);
1978 x86_alu_membase_imm (code, X86_CMP, X86_EAX, 0, 0);
1980 x86_branch8 (code, X86_CC_Z, FALSE, 0);
1983 x86_alu_membase_reg (code, X86_CMP, X86_EAX, 0, MONO_ARCH_IMT_REG);
1985 x86_branch8 (code, X86_CC_Z, FALSE, 0);
1988 x86_alu_reg_imm (code, X86_ADD, X86_EAX, 2 * sizeof (gpointer));
1989 x86_jump_code (code, labels [0]);
1992 mono_x86_patch (labels [2], code);
1993 x86_mov_reg_membase (code, X86_EAX, X86_EAX, sizeof (gpointer), 4);
1994 x86_mov_reg_membase (code, X86_EAX, X86_EAX, 0, 4);
1995 /* Save the target address to the temporary stack location */
1996 x86_mov_membase_reg (code, X86_ESP, 4, X86_EAX, 4);
1998 x86_pop_reg (code, X86_EAX);
1999 /* Jump to the target address */
2003 mono_x86_patch (labels [1], code);
2004 /* Load fail tramp */
2005 x86_mov_reg_membase (code, X86_EAX, X86_EAX, sizeof (gpointer), 4);
2006 x86_alu_membase_imm (code, X86_CMP, X86_EAX, 0, 0);
2008 x86_branch8 (code, X86_CC_Z, FALSE, 0);
2009 /* Jump to fail tramp */
2010 x86_mov_membase_reg (code, X86_ESP, 4, X86_EAX, 4);
2011 x86_pop_reg (code, X86_EAX);
2015 mono_x86_patch (labels [3], code);
2016 x86_breakpoint (code);
2018 #ifdef __native_client_codegen__
2020 /* emit nops to next 32 byte alignment */
2021 int a = (~kNaClAlignmentMask) & ((code - buf) + kNaClAlignment - 1);
2022 while (code < (buf + a)) x86_nop(code);
2025 emit_bytes (acfg, buf, code - buf);
2027 *tramp_size = code - buf;
2029 #if defined(__default_codegen__)
2031 #elif defined(__native_client_codegen__)
2035 #elif defined(TARGET_ARM)
2037 guint8 *code, *code2, *labels [16];
2041 /* The IMT method is in v5 */
2043 /* Need at least two free registers, plus a slot for storing the pc */
2044 ARM_PUSH (code, (1 << ARMREG_R0)|(1 << ARMREG_R1)|(1 << ARMREG_R2));
2046 /* Load the parameter from the GOT */
2047 ARM_LDR_IMM (code, ARMREG_R0, ARMREG_PC, 0);
2048 ARM_LDR_REG_REG (code, ARMREG_R0, ARMREG_PC, ARMREG_R0);
2051 ARM_LDR_IMM (code, ARMREG_R1, ARMREG_R0, 0);
2052 ARM_CMP_REG_REG (code, ARMREG_R1, ARMREG_V5);
2054 ARM_B_COND (code, ARMCOND_EQ, 0);
2056 /* End-of-loop check */
2057 ARM_CMP_REG_IMM (code, ARMREG_R1, 0, 0);
2059 ARM_B_COND (code, ARMCOND_EQ, 0);
2062 ARM_ADD_REG_IMM8 (code, ARMREG_R0, ARMREG_R0, sizeof (gpointer) * 2);
2065 arm_patch (labels [4], labels [1]);
2068 arm_patch (labels [2], code);
2069 ARM_LDR_IMM (code, ARMREG_R0, ARMREG_R0, 4);
2070 ARM_LDR_IMM (code, ARMREG_R0, ARMREG_R0, 0);
2071 /* Save it to the third stack slot */
2072 ARM_STR_IMM (code, ARMREG_R0, ARMREG_SP, 8);
2073 /* Restore the registers and branch */
2074 ARM_POP (code, (1 << ARMREG_R0)|(1 << ARMREG_R1)|(1 << ARMREG_PC));
2077 arm_patch (labels [3], code);
2078 ARM_LDR_IMM (code, ARMREG_R0, ARMREG_R0, 4);
2079 ARM_STR_IMM (code, ARMREG_R0, ARMREG_SP, 8);
2080 ARM_POP (code, (1 << ARMREG_R0)|(1 << ARMREG_R1)|(1 << ARMREG_PC));
2084 ARM_LDR_IMM (code2, ARMREG_R0, ARMREG_PC, (code - (labels [0] + 8)));
2086 emit_bytes (acfg, buf, code - buf);
2087 emit_symbol_diff (acfg, acfg->got_symbol, ".", (offset * sizeof (gpointer)) + (code - (labels [0] + 8)) - 4);
2089 *tramp_size = code - buf + 4;
2090 #elif defined(TARGET_ARM64)
2091 arm64_emit_imt_thunk (acfg, offset, tramp_size);
2092 #elif defined(TARGET_POWERPC)
2094 guint8 *code, *labels [16];
2098 /* Load the mscorlib got address */
2099 ppc_ldptr (code, ppc_r12, sizeof (gpointer), ppc_r30);
2100 /* Load the parameter from the GOT */
2101 ppc_load (code, ppc_r0, offset * sizeof (gpointer));
2102 ppc_ldptr_indexed (code, ppc_r12, ppc_r12, ppc_r0);
2104 /* Load and check key */
2106 ppc_ldptr (code, ppc_r0, 0, ppc_r12);
2107 ppc_cmp (code, 0, sizeof (gpointer) == 8 ? 1 : 0, ppc_r0, MONO_ARCH_IMT_REG);
2109 ppc_bc (code, PPC_BR_TRUE, PPC_BR_EQ, 0);
2111 /* End-of-loop check */
2112 ppc_cmpi (code, 0, sizeof (gpointer) == 8 ? 1 : 0, ppc_r0, 0);
2114 ppc_bc (code, PPC_BR_TRUE, PPC_BR_EQ, 0);
2117 ppc_addi (code, ppc_r12, ppc_r12, 2 * sizeof (gpointer));
2120 mono_ppc_patch (labels [4], labels [1]);
2123 mono_ppc_patch (labels [2], code);
2124 ppc_ldptr (code, ppc_r12, sizeof (gpointer), ppc_r12);
2125 /* r12 now contains the value of the vtable slot */
2126 /* this is not a function descriptor on ppc64 */
2127 ppc_ldptr (code, ppc_r12, 0, ppc_r12);
2128 ppc_mtctr (code, ppc_r12);
2129 ppc_bcctr (code, PPC_BR_ALWAYS, 0);
2132 mono_ppc_patch (labels [3], code);
2136 *tramp_size = code - buf;
2138 emit_bytes (acfg, buf, code - buf);
2140 g_assert_not_reached ();
2145 #if defined (TARGET_AMD64)
2148 amd64_emit_load_got_slot (MonoAotCompile *acfg, int dreg, int got_slot)
2151 g_assert (acfg->fp);
2152 emit_unset_mode (acfg);
2154 fprintf (acfg->fp, "mov %s+%d(%%rip), %s\n", acfg->got_symbol, (unsigned int) ((got_slot * sizeof (gpointer))), mono_arch_regname (dreg));
2161 * arch_emit_gsharedvt_arg_trampoline:
2163 * Emit code for a gsharedvt arg trampoline. OFFSET is the offset of the first of
2164 * two GOT slots which contain the argument, and the code to jump to.
2165 * TRAMP_SIZE is set to the size of the emitted trampoline.
2166 * These kinds of trampolines cannot be enumerated statically, since there could
2167 * be one trampoline per method instantiation, so we emit the same code for all
2168 * trampolines, and parameterize them using two GOT slots.
2171 arch_emit_gsharedvt_arg_trampoline (MonoAotCompile *acfg, int offset, int *tramp_size)
2173 #if defined(TARGET_X86)
2177 /* Similar to the PPC code above */
2179 g_assert (MONO_ARCH_RGCTX_REG != X86_ECX);
2182 /* Load mscorlib got address */
2183 x86_mov_reg_membase (code, X86_ECX, MONO_ARCH_GOT_REG, sizeof (gpointer), 4);
2185 x86_mov_reg_membase (code, X86_EAX, X86_ECX, offset * sizeof (gpointer), 4);
2186 /* Branch to the target address */
2187 x86_jump_membase (code, X86_ECX, (offset + 1) * sizeof (gpointer));
2189 #ifdef __native_client_codegen__
2191 /* emit nops to next 32 byte alignment */
2192 int a = (~kNaClAlignmentMask) & ((code - buf) + kNaClAlignment - 1);
2193 while (code < (buf + a)) x86_nop(code);
2197 emit_bytes (acfg, buf, code - buf);
2199 *tramp_size = NACL_SIZE (15, kNaClAlignment);
2200 g_assert (code - buf == *tramp_size);
2201 #elif defined(TARGET_ARM)
2205 /* The same as mono_arch_get_gsharedvt_arg_trampoline (), but for AOT */
2206 /* Similar to arch_emit_specific_trampoline () */
2209 ARM_PUSH (code, (1 << ARMREG_R0) | (1 << ARMREG_R1) | (1 << ARMREG_R2) | (1 << ARMREG_R3));
2210 ARM_LDR_IMM (code, ARMREG_R1, ARMREG_PC, 8);
2211 /* Load the arg value from the GOT */
2212 ARM_LDR_REG_REG (code, ARMREG_R0, ARMREG_PC, ARMREG_R1);
2213 /* Load the addr from the GOT */
2214 ARM_LDR_REG_REG (code, ARMREG_R1, ARMREG_PC, ARMREG_R1);
2216 ARM_BX (code, ARMREG_R1);
2218 g_assert (code - buf == 20);
2221 emit_bytes (acfg, buf, code - buf);
2222 emit_symbol_diff (acfg, acfg->got_symbol, ".", (offset * sizeof (gpointer)) + 4);
2223 #elif defined(TARGET_ARM64)
2224 arm64_emit_gsharedvt_arg_trampoline (acfg, offset, tramp_size);
2225 #elif defined (TARGET_AMD64)
2227 amd64_emit_load_got_slot (acfg, AMD64_RAX, offset);
2228 amd64_emit_load_got_slot (acfg, MONO_ARCH_IMT_SCRATCH_REG, offset + 1);
2229 g_assert (AMD64_R11 == MONO_ARCH_IMT_SCRATCH_REG);
2230 fprintf (acfg->fp, "jmp *%%r11\n");
2234 g_assert_not_reached ();
2238 /* END OF ARCH SPECIFIC CODE */
2241 mono_get_field_token (MonoClassField *field)
2243 MonoClass *klass = field->parent;
2246 for (i = 0; i < klass->field.count; ++i) {
2247 if (field == &klass->fields [i])
2248 return MONO_TOKEN_FIELD_DEF | (klass->field.first + 1 + i);
2251 g_assert_not_reached ();
2256 encode_value (gint32 value, guint8 *buf, guint8 **endbuf)
2260 //printf ("ENCODE: %d 0x%x.\n", value, value);
2263 * Same encoding as the one used in the metadata, extended to handle values
2264 * greater than 0x1fffffff.
2266 if ((value >= 0) && (value <= 127))
2268 else if ((value >= 0) && (value <= 16383)) {
2269 p [0] = 0x80 | (value >> 8);
2270 p [1] = value & 0xff;
2272 } else if ((value >= 0) && (value <= 0x1fffffff)) {
2273 p [0] = (value >> 24) | 0xc0;
2274 p [1] = (value >> 16) & 0xff;
2275 p [2] = (value >> 8) & 0xff;
2276 p [3] = value & 0xff;
2281 p [1] = (value >> 24) & 0xff;
2282 p [2] = (value >> 16) & 0xff;
2283 p [3] = (value >> 8) & 0xff;
2284 p [4] = value & 0xff;
2292 stream_init (MonoDynamicStream *sh)
2295 sh->alloc_size = 4096;
2296 sh->data = (char *)g_malloc (4096);
2298 /* So offsets are > 0 */
2304 make_room_in_stream (MonoDynamicStream *stream, int size)
2306 if (size <= stream->alloc_size)
2309 while (stream->alloc_size <= size) {
2310 if (stream->alloc_size < 4096)
2311 stream->alloc_size = 4096;
2313 stream->alloc_size *= 2;
2316 stream->data = (char *)g_realloc (stream->data, stream->alloc_size);
2320 add_stream_data (MonoDynamicStream *stream, const char *data, guint32 len)
2324 make_room_in_stream (stream, stream->index + len);
2325 memcpy (stream->data + stream->index, data, len);
2326 idx = stream->index;
2327 stream->index += len;
2334 * Add data to the binary blob inside the aot image. Returns the offset inside the
2335 * blob where the data was stored.
2338 add_to_blob (MonoAotCompile *acfg, const guint8 *data, guint32 data_len)
2340 g_assert (!acfg->blob_closed);
2342 if (acfg->blob.alloc_size == 0)
2343 stream_init (&acfg->blob);
2345 return add_stream_data (&acfg->blob, (char*)data, data_len);
2349 add_to_blob_aligned (MonoAotCompile *acfg, const guint8 *data, guint32 data_len, guint32 align)
2354 if (acfg->blob.alloc_size == 0)
2355 stream_init (&acfg->blob);
2357 count = acfg->blob.index % align;
2359 /* we assume the stream data will be aligned */
2361 add_stream_data (&acfg->blob, buf, 4 - count);
2363 return add_stream_data (&acfg->blob, (char*)data, data_len);
2366 /* Emit a table of data into the aot image */
2368 emit_aot_data (MonoAotCompile *acfg, MonoAotFileTable table, const char *symbol, guint8 *data, int size)
2370 if (acfg->data_outfile) {
2371 acfg->table_offsets [(int)table] = acfg->datafile_offset;
2372 fwrite (data,1, size, acfg->data_outfile);
2373 acfg->datafile_offset += size;
2374 // align the data to 8 bytes. Put zeros in the file (so that every build results in consistent output).
2375 int align = 8 - size % 8;
2376 acfg->datafile_offset += align;
2377 guint8 align_buf [16];
2378 memset (&align_buf, 0, sizeof (align_buf));
2379 fwrite (align_buf, align, 1, acfg->data_outfile);
2380 } else if (acfg->llvm) {
2381 mono_llvm_emit_aot_data (symbol, data, size);
2383 emit_section_change (acfg, RODATA_SECT, 0);
2384 emit_alignment (acfg, 8);
2385 emit_label (acfg, symbol);
2386 emit_bytes (acfg, data, size);
2391 * emit_offset_table:
2393 * Emit a table of increasing offsets in a compact form using differential encoding.
2394 * There is an index entry for each GROUP_SIZE number of entries. The greater the
2395 * group size, the more compact the table becomes, but the slower it becomes to compute
2396 * a given entry. Returns the size of the table.
2399 emit_offset_table (MonoAotCompile *acfg, const char *symbol, MonoAotFileTable table, int noffsets, int group_size, gint32 *offsets)
2401 gint32 current_offset;
2402 int i, buf_size, ngroups, index_entry_size;
2404 guint8 *data_p, *data_buf;
2405 guint32 *index_offsets;
2407 ngroups = (noffsets + (group_size - 1)) / group_size;
2409 index_offsets = g_new0 (guint32, ngroups);
2411 buf_size = noffsets * 4;
2412 p = buf = (guint8 *)g_malloc0 (buf_size);
2415 for (i = 0; i < noffsets; ++i) {
2416 //printf ("D: %d -> %d\n", i, offsets [i]);
2417 if ((i % group_size) == 0) {
2418 index_offsets [i / group_size] = p - buf;
2419 /* Emit the full value for these entries */
2420 encode_value (offsets [i], p, &p);
2422 /* The offsets are allowed to be non-increasing */
2423 //g_assert (offsets [i] >= current_offset);
2424 encode_value (offsets [i] - current_offset, p, &p);
2426 current_offset = offsets [i];
2431 if (ngroups && index_offsets [ngroups - 1] < 65000)
2432 index_entry_size = 2;
2434 index_entry_size = 4;
2436 buf_size = (data_p - data_buf) + (ngroups * 4) + 16;
2437 p = buf = (guint8 *)g_malloc0 (buf_size);
2439 /* Emit the header */
2440 encode_int (noffsets, p, &p);
2441 encode_int (group_size, p, &p);
2442 encode_int (ngroups, p, &p);
2443 encode_int (index_entry_size, p, &p);
2445 /* Emit the index */
2446 for (i = 0; i < ngroups; ++i) {
2447 if (index_entry_size == 2)
2448 encode_int16 (index_offsets [i], p, &p);
2450 encode_int (index_offsets [i], p, &p);
2453 memcpy (p, data_buf, data_p - data_buf);
2454 p += data_p - data_buf;
2456 g_assert (p - buf <= buf_size);
2458 emit_aot_data (acfg, table, symbol, buf, p - buf);
2463 return (int)(p - buf);
2467 get_image_index (MonoAotCompile *cfg, MonoImage *image)
2471 index = GPOINTER_TO_UINT (g_hash_table_lookup (cfg->image_hash, image));
2475 index = g_hash_table_size (cfg->image_hash);
2476 g_hash_table_insert (cfg->image_hash, image, GUINT_TO_POINTER (index + 1));
2477 g_ptr_array_add (cfg->image_table, image);
2483 find_typespec_for_class (MonoAotCompile *acfg, MonoClass *klass)
2486 int len = acfg->image->tables [MONO_TABLE_TYPESPEC].rows;
2488 /* FIXME: Search referenced images as well */
2489 if (!acfg->typespec_classes) {
2490 acfg->typespec_classes = (MonoClass **)mono_mempool_alloc0 (acfg->mempool, sizeof (MonoClass*) * len);
2491 for (i = 0; i < len; ++i) {
2493 acfg->typespec_classes [i] = mono_class_get_and_inflate_typespec_checked (acfg->image, MONO_TOKEN_TYPE_SPEC | (i + 1), NULL, &error);
2494 g_assert (mono_error_ok (&error)); /* FIXME error handling */
2497 for (i = 0; i < len; ++i) {
2498 if (acfg->typespec_classes [i] == klass)
2503 return MONO_TOKEN_TYPE_SPEC | (i + 1);
2509 encode_method_ref (MonoAotCompile *acfg, MonoMethod *method, guint8 *buf, guint8 **endbuf);
2512 encode_klass_ref (MonoAotCompile *acfg, MonoClass *klass, guint8 *buf, guint8 **endbuf);
2515 encode_ginst (MonoAotCompile *acfg, MonoGenericInst *inst, guint8 *buf, guint8 **endbuf);
2518 encode_type (MonoAotCompile *acfg, MonoType *t, guint8 *buf, guint8 **endbuf);
2521 encode_klass_ref_inner (MonoAotCompile *acfg, MonoClass *klass, guint8 *buf, guint8 **endbuf)
2526 * The encoding begins with one of the MONO_AOT_TYPEREF values, followed by additional
2530 if (klass->generic_class) {
2532 g_assert (klass->type_token);
2534 /* Find a typespec for a class if possible */
2535 token = find_typespec_for_class (acfg, klass);
2537 encode_value (MONO_AOT_TYPEREF_TYPESPEC_TOKEN, p, &p);
2538 encode_value (token, p, &p);
2540 MonoClass *gclass = klass->generic_class->container_class;
2541 MonoGenericInst *inst = klass->generic_class->context.class_inst;
2542 static int count = 0;
2545 encode_value (MONO_AOT_TYPEREF_GINST, p, &p);
2546 encode_klass_ref (acfg, gclass, p, &p);
2547 encode_ginst (acfg, inst, p, &p);
2551 } else if (klass->type_token) {
2552 int iindex = get_image_index (acfg, klass->image);
2554 g_assert (mono_metadata_token_code (klass->type_token) == MONO_TOKEN_TYPE_DEF);
2556 encode_value (MONO_AOT_TYPEREF_TYPEDEF_INDEX, p, &p);
2557 encode_value (klass->type_token - MONO_TOKEN_TYPE_DEF, p, &p);
2559 encode_value (MONO_AOT_TYPEREF_TYPEDEF_INDEX_IMAGE, p, &p);
2560 encode_value (klass->type_token - MONO_TOKEN_TYPE_DEF, p, &p);
2561 encode_value (get_image_index (acfg, klass->image), p, &p);
2563 } else if ((klass->byval_arg.type == MONO_TYPE_VAR) || (klass->byval_arg.type == MONO_TYPE_MVAR)) {
2564 MonoGenericContainer *container = mono_type_get_generic_param_owner (&klass->byval_arg);
2565 MonoGenericParam *par = klass->byval_arg.data.generic_param;
2567 encode_value (MONO_AOT_TYPEREF_VAR, p, &p);
2569 encode_value (par->gshared_constraint ? 1 : 0, p, &p);
2570 if (par->gshared_constraint) {
2571 MonoGSharedGenericParam *gpar = (MonoGSharedGenericParam*)par;
2572 encode_type (acfg, par->gshared_constraint, p, &p);
2573 encode_klass_ref (acfg, mono_class_from_generic_parameter (gpar->parent, NULL, klass->byval_arg.type == MONO_TYPE_MVAR), p, &p);
2575 encode_value (klass->byval_arg.type, p, &p);
2576 encode_value (mono_type_get_generic_param_num (&klass->byval_arg), p, &p);
2578 encode_value (container->is_anonymous ? 0 : 1, p, &p);
2580 if (!container->is_anonymous) {
2581 encode_value (container->is_method, p, &p);
2582 if (container->is_method)
2583 encode_method_ref (acfg, container->owner.method, p, &p);
2585 encode_klass_ref (acfg, container->owner.klass, p, &p);
2588 } else if (klass->byval_arg.type == MONO_TYPE_PTR) {
2589 encode_value (MONO_AOT_TYPEREF_PTR, p, &p);
2590 encode_type (acfg, &klass->byval_arg, p, &p);
2593 g_assert (klass->rank > 0);
2594 encode_value (MONO_AOT_TYPEREF_ARRAY, p, &p);
2595 encode_value (klass->rank, p, &p);
2596 encode_klass_ref (acfg, klass->element_class, p, &p);
2604 * Encode a reference to KLASS. We use our home-grown encoding instead of the
2605 * standard metadata encoding.
2608 encode_klass_ref (MonoAotCompile *acfg, MonoClass *klass, guint8 *buf, guint8 **endbuf)
2610 gboolean shared = FALSE;
2613 * The encoding of generic instances is large so emit them only once.
2615 if (klass->generic_class) {
2617 g_assert (klass->type_token);
2619 /* Find a typespec for a class if possible */
2620 token = find_typespec_for_class (acfg, klass);
2623 } else if ((klass->byval_arg.type == MONO_TYPE_VAR) || (klass->byval_arg.type == MONO_TYPE_MVAR)) {
2628 guint offset = GPOINTER_TO_UINT (g_hash_table_lookup (acfg->klass_blob_hash, klass));
2632 buf2 = (guint8 *)g_malloc (1024);
2635 encode_klass_ref_inner (acfg, klass, p, &p);
2636 g_assert (p - buf2 < 1024);
2638 offset = add_to_blob (acfg, buf2, p - buf2);
2641 g_hash_table_insert (acfg->klass_blob_hash, klass, GUINT_TO_POINTER (offset + 1));
2647 encode_value (MONO_AOT_TYPEREF_BLOB_INDEX, p, &p);
2648 encode_value (offset, p, &p);
2653 encode_klass_ref_inner (acfg, klass, buf, endbuf);
2657 encode_field_info (MonoAotCompile *cfg, MonoClassField *field, guint8 *buf, guint8 **endbuf)
2659 guint32 token = mono_get_field_token (field);
2662 encode_klass_ref (cfg, field->parent, p, &p);
2663 g_assert (mono_metadata_token_code (token) == MONO_TOKEN_FIELD_DEF);
2664 encode_value (token - MONO_TOKEN_FIELD_DEF, p, &p);
2669 encode_ginst (MonoAotCompile *acfg, MonoGenericInst *inst, guint8 *buf, guint8 **endbuf)
2674 encode_value (inst->type_argc, p, &p);
2675 for (i = 0; i < inst->type_argc; ++i)
2676 encode_klass_ref (acfg, mono_class_from_mono_type (inst->type_argv [i]), p, &p);
2681 encode_generic_context (MonoAotCompile *acfg, MonoGenericContext *context, guint8 *buf, guint8 **endbuf)
2684 MonoGenericInst *inst;
2686 inst = context->class_inst;
2688 g_assert (inst->type_argc);
2689 encode_ginst (acfg, inst, p, &p);
2691 encode_value (0, p, &p);
2693 inst = context->method_inst;
2695 g_assert (inst->type_argc);
2696 encode_ginst (acfg, inst, p, &p);
2698 encode_value (0, p, &p);
2704 encode_type (MonoAotCompile *acfg, MonoType *t, guint8 *buf, guint8 **endbuf)
2708 g_assert (t->num_mods == 0);
2709 /* t->attrs can be ignored */
2710 //g_assert (t->attrs == 0);
2713 *p = MONO_TYPE_PINNED;
2717 *p = MONO_TYPE_BYREF;
2725 case MONO_TYPE_VOID:
2726 case MONO_TYPE_BOOLEAN:
2727 case MONO_TYPE_CHAR:
2740 case MONO_TYPE_STRING:
2741 case MONO_TYPE_OBJECT:
2742 case MONO_TYPE_TYPEDBYREF:
2744 case MONO_TYPE_VALUETYPE:
2745 case MONO_TYPE_CLASS:
2746 encode_klass_ref (acfg, mono_class_from_mono_type (t), p, &p);
2748 case MONO_TYPE_SZARRAY:
2749 encode_klass_ref (acfg, t->data.klass, p, &p);
2752 encode_type (acfg, t->data.type, p, &p);
2754 case MONO_TYPE_GENERICINST: {
2755 MonoClass *gclass = t->data.generic_class->container_class;
2756 MonoGenericInst *inst = t->data.generic_class->context.class_inst;
2758 encode_klass_ref (acfg, gclass, p, &p);
2759 encode_ginst (acfg, inst, p, &p);
2762 case MONO_TYPE_ARRAY: {
2763 MonoArrayType *array = t->data.array;
2766 encode_klass_ref (acfg, array->eklass, p, &p);
2767 encode_value (array->rank, p, &p);
2768 encode_value (array->numsizes, p, &p);
2769 for (i = 0; i < array->numsizes; ++i)
2770 encode_value (array->sizes [i], p, &p);
2771 encode_value (array->numlobounds, p, &p);
2772 for (i = 0; i < array->numlobounds; ++i)
2773 encode_value (array->lobounds [i], p, &p);
2777 case MONO_TYPE_MVAR:
2778 encode_klass_ref (acfg, mono_class_from_mono_type (t), p, &p);
2781 g_assert_not_reached ();
2788 encode_signature (MonoAotCompile *acfg, MonoMethodSignature *sig, guint8 *buf, guint8 **endbuf)
2794 /* Similar to the metadata encoding */
2795 if (sig->generic_param_count)
2799 if (sig->explicit_this)
2801 flags |= (sig->call_convention & 0x0F);
2805 if (sig->generic_param_count)
2806 encode_value (sig->generic_param_count, p, &p);
2807 encode_value (sig->param_count, p, &p);
2809 encode_type (acfg, sig->ret, p, &p);
2810 for (i = 0; i < sig->param_count; ++i) {
2811 if (sig->sentinelpos == i) {
2812 *p = MONO_TYPE_SENTINEL;
2815 encode_type (acfg, sig->params [i], p, &p);
2821 #define MAX_IMAGE_INDEX 250
2824 encode_method_ref (MonoAotCompile *acfg, MonoMethod *method, guint8 *buf, guint8 **endbuf)
2826 guint32 image_index = get_image_index (acfg, method->klass->image);
2827 guint32 token = method->token;
2828 MonoJumpInfoToken *ji;
2832 * The encoding for most methods is as follows:
2833 * - image index encoded as a leb128
2834 * - token index encoded as a leb128
2835 * Values of image index >= MONO_AOT_METHODREF_MIN are used to mark additional
2836 * types of method encodings.
2839 /* Mark methods which can't use aot trampolines because they need the further
2840 * processing in mono_magic_trampoline () which requires a MonoMethod*.
2842 if ((method->is_generic && (method->flags & METHOD_ATTRIBUTE_VIRTUAL)) ||
2843 (method->iflags & METHOD_IMPL_ATTRIBUTE_SYNCHRONIZED))
2844 encode_value ((MONO_AOT_METHODREF_NO_AOT_TRAMPOLINE << 24), p, &p);
2846 if (method->wrapper_type) {
2847 WrapperInfo *info = mono_marshal_get_wrapper_info (method);
2849 encode_value ((MONO_AOT_METHODREF_WRAPPER << 24), p, &p);
2851 encode_value (method->wrapper_type, p, &p);
2853 switch (method->wrapper_type) {
2854 case MONO_WRAPPER_REMOTING_INVOKE:
2855 case MONO_WRAPPER_REMOTING_INVOKE_WITH_CHECK:
2856 case MONO_WRAPPER_XDOMAIN_INVOKE: {
2859 m = mono_marshal_method_from_wrapper (method);
2861 encode_method_ref (acfg, m, p, &p);
2864 case MONO_WRAPPER_PROXY_ISINST:
2865 case MONO_WRAPPER_LDFLD:
2866 case MONO_WRAPPER_LDFLDA:
2867 case MONO_WRAPPER_STFLD:
2868 case MONO_WRAPPER_ISINST: {
2870 encode_klass_ref (acfg, info->d.proxy.klass, p, &p);
2873 case MONO_WRAPPER_LDFLD_REMOTE:
2874 case MONO_WRAPPER_STFLD_REMOTE:
2876 case MONO_WRAPPER_ALLOC: {
2877 /* The GC name is saved once in MonoAotFileInfo */
2878 g_assert (info->d.alloc.alloc_type != -1);
2879 encode_value (info->d.alloc.alloc_type, p, &p);
2882 case MONO_WRAPPER_WRITE_BARRIER: {
2886 case MONO_WRAPPER_STELEMREF: {
2888 encode_value (info->subtype, p, &p);
2889 if (info->subtype == WRAPPER_SUBTYPE_VIRTUAL_STELEMREF)
2890 encode_value (info->d.virtual_stelemref.kind, p, &p);
2893 case MONO_WRAPPER_UNKNOWN: {
2895 encode_value (info->subtype, p, &p);
2896 if (info->subtype == WRAPPER_SUBTYPE_PTR_TO_STRUCTURE ||
2897 info->subtype == WRAPPER_SUBTYPE_STRUCTURE_TO_PTR)
2898 encode_klass_ref (acfg, method->klass, p, &p);
2899 else if (info->subtype == WRAPPER_SUBTYPE_SYNCHRONIZED_INNER)
2900 encode_method_ref (acfg, info->d.synchronized_inner.method, p, &p);
2901 else if (info->subtype == WRAPPER_SUBTYPE_ARRAY_ACCESSOR)
2902 encode_method_ref (acfg, info->d.array_accessor.method, p, &p);
2903 else if (info->subtype == WRAPPER_SUBTYPE_GSHAREDVT_IN_SIG)
2904 encode_signature (acfg, info->d.gsharedvt.sig, p, &p);
2905 else if (info->subtype == WRAPPER_SUBTYPE_GSHAREDVT_OUT_SIG)
2906 encode_signature (acfg, info->d.gsharedvt.sig, p, &p);
2909 case MONO_WRAPPER_MANAGED_TO_NATIVE: {
2911 encode_value (info->subtype, p, &p);
2912 if (info->subtype == WRAPPER_SUBTYPE_ICALL_WRAPPER) {
2913 strcpy ((char*)p, method->name);
2914 p += strlen (method->name) + 1;
2915 } else if (info->subtype == WRAPPER_SUBTYPE_NATIVE_FUNC_AOT) {
2916 encode_method_ref (acfg, info->d.managed_to_native.method, p, &p);
2918 g_assert (info->subtype == WRAPPER_SUBTYPE_NONE || info->subtype == WRAPPER_SUBTYPE_PINVOKE);
2919 encode_method_ref (acfg, info->d.managed_to_native.method, p, &p);
2923 case MONO_WRAPPER_SYNCHRONIZED: {
2926 m = mono_marshal_method_from_wrapper (method);
2928 g_assert (m != method);
2929 encode_method_ref (acfg, m, p, &p);
2932 case MONO_WRAPPER_MANAGED_TO_MANAGED: {
2934 encode_value (info->subtype, p, &p);
2936 if (info->subtype == WRAPPER_SUBTYPE_ELEMENT_ADDR) {
2937 encode_value (info->d.element_addr.rank, p, &p);
2938 encode_value (info->d.element_addr.elem_size, p, &p);
2939 } else if (info->subtype == WRAPPER_SUBTYPE_STRING_CTOR) {
2940 encode_method_ref (acfg, info->d.string_ctor.method, p, &p);
2942 g_assert_not_reached ();
2946 case MONO_WRAPPER_CASTCLASS: {
2948 encode_value (info->subtype, p, &p);
2951 case MONO_WRAPPER_RUNTIME_INVOKE: {
2953 encode_value (info->subtype, p, &p);
2954 if (info->subtype == WRAPPER_SUBTYPE_RUNTIME_INVOKE_DIRECT || info->subtype == WRAPPER_SUBTYPE_RUNTIME_INVOKE_VIRTUAL)
2955 encode_method_ref (acfg, info->d.runtime_invoke.method, p, &p);
2956 else if (info->subtype == WRAPPER_SUBTYPE_RUNTIME_INVOKE_NORMAL)
2957 encode_signature (acfg, info->d.runtime_invoke.sig, p, &p);
2960 case MONO_WRAPPER_DELEGATE_INVOKE:
2961 case MONO_WRAPPER_DELEGATE_BEGIN_INVOKE:
2962 case MONO_WRAPPER_DELEGATE_END_INVOKE: {
2963 if (method->is_inflated) {
2964 /* These wrappers are identified by their class */
2965 encode_value (1, p, &p);
2966 encode_klass_ref (acfg, method->klass, p, &p);
2968 MonoMethodSignature *sig = mono_method_signature (method);
2969 WrapperInfo *info = mono_marshal_get_wrapper_info (method);
2971 encode_value (0, p, &p);
2972 if (method->wrapper_type == MONO_WRAPPER_DELEGATE_INVOKE)
2973 encode_value (info ? info->subtype : 0, p, &p);
2974 encode_signature (acfg, sig, p, &p);
2978 case MONO_WRAPPER_NATIVE_TO_MANAGED: {
2980 encode_method_ref (acfg, info->d.native_to_managed.method, p, &p);
2981 encode_klass_ref (acfg, info->d.native_to_managed.klass, p, &p);
2985 g_assert_not_reached ();
2987 } else if (mono_method_signature (method)->is_inflated) {
2989 * This is a generic method, find the original token which referenced it and
2991 * Obtain the token from information recorded by the JIT.
2993 ji = (MonoJumpInfoToken *)g_hash_table_lookup (acfg->token_info_hash, method);
2995 image_index = get_image_index (acfg, ji->image);
2996 g_assert (image_index < MAX_IMAGE_INDEX);
2999 encode_value ((MONO_AOT_METHODREF_METHODSPEC << 24), p, &p);
3000 encode_value (image_index, p, &p);
3001 encode_value (token, p, &p);
3003 MonoMethod *declaring;
3004 MonoGenericContext *context = mono_method_get_context (method);
3006 g_assert (method->is_inflated);
3007 declaring = ((MonoMethodInflated*)method)->declaring;
3010 * This might be a non-generic method of a generic instance, which
3011 * doesn't have a token since the reference is generated by the JIT
3012 * like Nullable:Box/Unbox, or by generic sharing.
3014 encode_value ((MONO_AOT_METHODREF_GINST << 24), p, &p);
3015 /* Encode the klass */
3016 encode_klass_ref (acfg, method->klass, p, &p);
3017 /* Encode the method */
3018 image_index = get_image_index (acfg, method->klass->image);
3019 g_assert (image_index < MAX_IMAGE_INDEX);
3020 g_assert (declaring->token);
3021 token = declaring->token;
3022 g_assert (mono_metadata_token_table (token) == MONO_TABLE_METHOD);
3023 encode_value (image_index, p, &p);
3024 encode_value (token, p, &p);
3025 encode_generic_context (acfg, context, p, &p);
3027 } else if (token == 0) {
3028 /* This might be a method of a constructed type like int[,].Set */
3029 /* Obtain the token from information recorded by the JIT */
3030 ji = (MonoJumpInfoToken *)g_hash_table_lookup (acfg->token_info_hash, method);
3032 image_index = get_image_index (acfg, ji->image);
3033 g_assert (image_index < MAX_IMAGE_INDEX);
3036 encode_value ((MONO_AOT_METHODREF_METHODSPEC << 24), p, &p);
3037 encode_value (image_index, p, &p);
3038 encode_value (token, p, &p);
3041 g_assert (method->klass->rank);
3043 /* Encode directly */
3044 encode_value ((MONO_AOT_METHODREF_ARRAY << 24), p, &p);
3045 encode_klass_ref (acfg, method->klass, p, &p);
3046 if (!strcmp (method->name, ".ctor") && mono_method_signature (method)->param_count == method->klass->rank)
3047 encode_value (0, p, &p);
3048 else if (!strcmp (method->name, ".ctor") && mono_method_signature (method)->param_count == method->klass->rank * 2)
3049 encode_value (1, p, &p);
3050 else if (!strcmp (method->name, "Get"))
3051 encode_value (2, p, &p);
3052 else if (!strcmp (method->name, "Address"))
3053 encode_value (3, p, &p);
3054 else if (!strcmp (method->name, "Set"))
3055 encode_value (4, p, &p);
3057 g_assert_not_reached ();
3060 g_assert (mono_metadata_token_table (token) == MONO_TABLE_METHOD);
3062 if (image_index >= MONO_AOT_METHODREF_MIN) {
3063 encode_value ((MONO_AOT_METHODREF_LARGE_IMAGE_INDEX << 24), p, &p);
3064 encode_value (image_index, p, &p);
3065 encode_value (mono_metadata_token_index (token), p, &p);
3067 encode_value ((image_index << 24) | mono_metadata_token_index (token), p, &p);
3074 compare_patches (gconstpointer a, gconstpointer b)
3078 i = (*(MonoJumpInfo**)a)->ip.i;
3079 j = (*(MonoJumpInfo**)b)->ip.i;
3090 static G_GNUC_UNUSED char*
3091 patch_to_string (MonoJumpInfo *patch_info)
3095 str = g_string_new ("");
3097 g_string_append_printf (str, "%s(", get_patch_name (patch_info->type));
3099 switch (patch_info->type) {
3100 case MONO_PATCH_INFO_VTABLE:
3101 mono_type_get_desc (str, &patch_info->data.klass->byval_arg, TRUE);
3106 g_string_append_printf (str, ")");
3107 return g_string_free (str, FALSE);
3113 * Return whenever PATCH_INFO refers to a direct call, and thus requires a
3116 static inline gboolean
3117 is_plt_patch (MonoJumpInfo *patch_info)
3119 switch (patch_info->type) {
3120 case MONO_PATCH_INFO_METHOD:
3121 case MONO_PATCH_INFO_INTERNAL_METHOD:
3122 case MONO_PATCH_INFO_JIT_ICALL_ADDR:
3123 case MONO_PATCH_INFO_ICALL_ADDR:
3124 case MONO_PATCH_INFO_RGCTX_FETCH:
3134 * Return the symbol identifying the plt entry PLT_OFFSET.
3137 get_plt_symbol (MonoAotCompile *acfg, int plt_offset, MonoJumpInfo *patch_info)
3141 * The Apple linker reorganizes object files, so it doesn't like branches to local
3142 * labels, since those have no relocations.
3144 return g_strdup_printf ("%sp_%d", acfg->llvm_label_prefix, plt_offset);
3146 return g_strdup_printf ("%sp_%d", acfg->temp_prefix, plt_offset);
3153 * Return a PLT entry which belongs to the method identified by PATCH_INFO.
3155 static MonoPltEntry*
3156 get_plt_entry (MonoAotCompile *acfg, MonoJumpInfo *patch_info)
3159 gboolean synchronized = FALSE;
3160 static int synchronized_symbol_idx;
3162 if (!is_plt_patch (patch_info))
3165 if (!acfg->patch_to_plt_entry [patch_info->type])
3166 acfg->patch_to_plt_entry [patch_info->type] = g_hash_table_new (mono_patch_info_hash, mono_patch_info_equal);
3167 res = (MonoPltEntry *)g_hash_table_lookup (acfg->patch_to_plt_entry [patch_info->type], patch_info);
3169 if (!acfg->llvm && patch_info->type == MONO_PATCH_INFO_METHOD && (patch_info->data.method->iflags & METHOD_IMPL_ATTRIBUTE_SYNCHRONIZED)) {
3171 * Allocate a separate PLT slot for each such patch, since some plt
3172 * entries will refer to the method itself, and some will refer to the
3176 synchronized = TRUE;
3180 MonoJumpInfo *new_ji;
3182 new_ji = mono_patch_info_dup_mp (acfg->mempool, patch_info);
3184 res = (MonoPltEntry *)mono_mempool_alloc0 (acfg->mempool, sizeof (MonoPltEntry));
3185 res->plt_offset = acfg->plt_offset;
3187 res->symbol = get_plt_symbol (acfg, res->plt_offset, patch_info);
3188 if (acfg->aot_opts.write_symbols)
3189 res->debug_sym = get_plt_entry_debug_sym (acfg, res->ji, acfg->plt_entry_debug_sym_cache);
3191 /* Avoid duplicate symbols because we don't cache */
3192 res->symbol = g_strdup_printf ("%s_%d", res->symbol, synchronized_symbol_idx);
3194 res->debug_sym = g_strdup_printf ("%s_%d", res->debug_sym, synchronized_symbol_idx);
3195 synchronized_symbol_idx ++;
3198 res->llvm_symbol = g_strdup_printf ("%s_%s_llvm", res->symbol, res->debug_sym);
3200 res->llvm_symbol = g_strdup_printf ("%s_llvm", res->symbol);
3202 g_hash_table_insert (acfg->patch_to_plt_entry [new_ji->type], new_ji, res);
3204 g_hash_table_insert (acfg->plt_offset_to_entry, GUINT_TO_POINTER (res->plt_offset), res);
3206 //g_assert (mono_patch_info_equal (patch_info, new_ji));
3207 //mono_print_ji (patch_info); printf ("\n");
3208 //g_hash_table_print_stats (acfg->patch_to_plt_entry);
3210 acfg->plt_offset ++;
3219 * Returns the offset of the GOT slot where the runtime object resulting from resolving
3220 * JI could be found if it exists, otherwise allocates a new one.
3223 get_got_offset (MonoAotCompile *acfg, gboolean llvm, MonoJumpInfo *ji)
3226 GotInfo *info = llvm ? &acfg->llvm_got_info : &acfg->got_info;
3228 got_offset = GPOINTER_TO_UINT (g_hash_table_lookup (info->patch_to_got_offset_by_type [ji->type], ji));
3230 return got_offset - 1;
3233 got_offset = acfg->llvm_got_offset;
3234 acfg->llvm_got_offset ++;
3236 got_offset = acfg->got_offset;
3237 acfg->got_offset ++;
3240 acfg->stats.got_slots ++;
3241 acfg->stats.got_slot_types [ji->type] ++;
3243 g_hash_table_insert (info->patch_to_got_offset, ji, GUINT_TO_POINTER (got_offset + 1));
3244 g_hash_table_insert (info->patch_to_got_offset_by_type [ji->type], ji, GUINT_TO_POINTER (got_offset + 1));
3245 g_ptr_array_add (info->got_patches, ji);
3250 /* Add a method to the list of methods which need to be emitted */
3252 add_method_with_index (MonoAotCompile *acfg, MonoMethod *method, int index, gboolean extra)
3255 if (!g_hash_table_lookup (acfg->method_indexes, method)) {
3256 g_ptr_array_add (acfg->methods, method);
3257 g_hash_table_insert (acfg->method_indexes, method, GUINT_TO_POINTER (index + 1));
3258 acfg->nmethods = acfg->methods->len + 1;
3261 if (method->wrapper_type || extra)
3262 g_ptr_array_add (acfg->extra_methods, method);
3266 prefer_gsharedvt_method (MonoAotCompile *acfg, MonoMethod *method)
3268 /* One instantiation with valuetypes is generated for each async method */
3269 if (method->klass->image == mono_defaults.corlib && (!strcmp (method->klass->name, "AsyncMethodBuilderCore") || !strcmp (method->klass->name, "AsyncVoidMethodBuilder")))
3276 get_method_index (MonoAotCompile *acfg, MonoMethod *method)
3278 int index = GPOINTER_TO_UINT (g_hash_table_lookup (acfg->method_indexes, method));
3286 add_method_full (MonoAotCompile *acfg, MonoMethod *method, gboolean extra, int depth)
3290 index = GPOINTER_TO_UINT (g_hash_table_lookup (acfg->method_indexes, method));
3294 index = acfg->method_index;
3295 add_method_with_index (acfg, method, index, extra);
3297 g_ptr_array_add (acfg->method_order, GUINT_TO_POINTER (index));
3299 g_hash_table_insert (acfg->method_depth, method, GUINT_TO_POINTER (depth));
3301 acfg->method_index ++;
3307 add_method (MonoAotCompile *acfg, MonoMethod *method)
3309 return add_method_full (acfg, method, FALSE, 0);
3313 add_extra_method_with_depth (MonoAotCompile *acfg, MonoMethod *method, int depth)
3315 if (mono_method_is_generic_sharable_full (method, TRUE, TRUE, FALSE))
3316 method = mini_get_shared_method (method);
3317 else if ((acfg->opts & MONO_OPT_GSHAREDVT) && prefer_gsharedvt_method (acfg, method) && mono_method_is_generic_sharable_full (method, FALSE, FALSE, TRUE))
3318 /* Use the gsharedvt version */
3319 method = mini_get_shared_method_full (method, TRUE, TRUE);
3321 if (acfg->aot_opts.log_generics)
3322 aot_printf (acfg, "%*sAdding method %s.\n", depth, "", mono_method_get_full_name (method));
3324 add_method_full (acfg, method, TRUE, depth);
3328 add_extra_method (MonoAotCompile *acfg, MonoMethod *method)
3330 add_extra_method_with_depth (acfg, method, 0);
3334 add_jit_icall_wrapper (gpointer key, gpointer value, gpointer user_data)
3336 MonoAotCompile *acfg = (MonoAotCompile *)user_data;
3337 MonoJitICallInfo *callinfo = (MonoJitICallInfo *)value;
3338 MonoMethod *wrapper;
3344 name = g_strdup_printf ("__icall_wrapper_%s", callinfo->name);
3345 wrapper = mono_marshal_get_icall_wrapper (callinfo->sig, name, callinfo->func, TRUE);
3348 add_method (acfg, wrapper);
3352 get_runtime_invoke_sig (MonoMethodSignature *sig)
3354 MonoMethodBuilder *mb;
3357 mb = mono_mb_new (mono_defaults.object_class, "FOO", MONO_WRAPPER_NONE);
3358 m = mono_mb_create_method (mb, sig, 16);
3359 return mono_marshal_get_runtime_invoke (m, FALSE);
3363 get_runtime_invoke (MonoAotCompile *acfg, MonoMethod *method, gboolean virtual_)
3365 return mono_marshal_get_runtime_invoke (method, virtual_);
3369 can_marshal_struct (MonoClass *klass)
3371 MonoClassField *field;
3372 gboolean can_marshal = TRUE;
3373 gpointer iter = NULL;
3374 MonoMarshalType *info;
3377 if ((klass->flags & TYPE_ATTRIBUTE_LAYOUT_MASK) == TYPE_ATTRIBUTE_AUTO_LAYOUT)
3380 info = mono_marshal_load_type_info (klass);
3382 /* Only allow a few field types to avoid asserts in the marshalling code */
3383 while ((field = mono_class_get_fields (klass, &iter))) {
3384 if ((field->type->attrs & FIELD_ATTRIBUTE_STATIC))
3387 switch (field->type->type) {
3392 case MONO_TYPE_BOOLEAN:
3395 case MONO_TYPE_CHAR:
3403 case MONO_TYPE_STRING:
3405 case MONO_TYPE_VALUETYPE:
3406 if (!mono_class_from_mono_type (field->type)->enumtype && !can_marshal_struct (mono_class_from_mono_type (field->type)))
3407 can_marshal = FALSE;
3409 case MONO_TYPE_SZARRAY: {
3410 gboolean has_mspec = FALSE;
3413 for (i = 0; i < info->num_fields; ++i) {
3414 if (info->fields [i].field == field && info->fields [i].mspec)
3419 can_marshal = FALSE;
3423 can_marshal = FALSE;
3429 /* Its hard to compute whenever these can be marshalled or not */
3430 if (!strcmp (klass->name_space, "System.Net.NetworkInformation.MacOsStructs") && strcmp (klass->name, "sockaddr_dl"))
3437 create_gsharedvt_inst (MonoAotCompile *acfg, MonoMethod *method, MonoGenericContext *ctx)
3439 /* Create a vtype instantiation */
3440 MonoGenericContext shared_context;
3442 MonoGenericInst *inst;
3443 MonoGenericContainer *container;
3444 MonoClass **constraints;
3447 memset (ctx, 0, sizeof (MonoGenericContext));
3449 if (method->klass->generic_container) {
3450 shared_context = method->klass->generic_container->context;
3451 inst = shared_context.class_inst;
3453 args = g_new0 (MonoType*, inst->type_argc);
3454 for (i = 0; i < inst->type_argc; ++i) {
3455 args [i] = &mono_defaults.int_class->byval_arg;
3457 ctx->class_inst = mono_metadata_get_generic_inst (inst->type_argc, args);
3459 if (method->is_generic) {
3460 container = mono_method_get_generic_container (method);
3461 shared_context = container->context;
3462 inst = shared_context.method_inst;
3464 args = g_new0 (MonoType*, inst->type_argc);
3465 for (i = 0; i < container->type_argc; ++i) {
3466 MonoGenericParamInfo *info = &container->type_params [i].info;
3467 gboolean ref_only = FALSE;
3469 if (info && info->constraints) {
3470 constraints = info->constraints;
3472 while (*constraints) {
3473 MonoClass *cklass = *constraints;
3474 if (!(cklass == mono_defaults.object_class || (cklass->image == mono_defaults.corlib && !strcmp (cklass->name, "ValueType"))))
3475 /* Inflaring the method with our vtype would not be valid */
3482 args [i] = &mono_defaults.object_class->byval_arg;
3484 args [i] = &mono_defaults.int_class->byval_arg;
3486 ctx->method_inst = mono_metadata_get_generic_inst (inst->type_argc, args);
3491 add_wrappers (MonoAotCompile *acfg)
3493 MonoMethod *method, *m;
3495 MonoMethodSignature *sig, *csig;
3499 * FIXME: Instead of AOTing all the wrappers, it might be better to redesign them
3500 * so there is only one wrapper of a given type, or inlining their contents into their
3503 for (i = 0; i < acfg->image->tables [MONO_TABLE_METHOD].rows; ++i) {
3506 guint32 token = MONO_TOKEN_METHOD_DEF | (i + 1);
3507 gboolean skip = FALSE;
3509 method = mono_get_method_checked (acfg->image, token, NULL, NULL, &error);
3510 report_loader_error (acfg, &error, "Failed to load method token 0x%x due to %s\n", i, mono_error_get_message (&error));
3512 if ((method->flags & METHOD_ATTRIBUTE_PINVOKE_IMPL) ||
3513 (method->iflags & METHOD_IMPL_ATTRIBUTE_RUNTIME) ||
3514 (method->flags & METHOD_ATTRIBUTE_ABSTRACT))
3517 /* Skip methods which can not be handled by get_runtime_invoke () */
3518 sig = mono_method_signature (method);
3521 if ((sig->ret->type == MONO_TYPE_PTR) ||
3522 (sig->ret->type == MONO_TYPE_TYPEDBYREF))
3524 if (mono_class_is_open_constructed_type (sig->ret))
3527 for (j = 0; j < sig->param_count; j++) {
3528 if (sig->params [j]->type == MONO_TYPE_TYPEDBYREF)
3530 if (mono_class_is_open_constructed_type (sig->params [j]))
3534 #ifdef MONO_ARCH_DYN_CALL_SUPPORTED
3535 if (!mono_class_is_contextbound (method->klass)) {
3536 MonoDynCallInfo *info = mono_arch_dyn_call_prepare (sig);
3537 gboolean has_nullable = FALSE;
3539 for (j = 0; j < sig->param_count; j++) {
3540 if (sig->params [j]->type == MONO_TYPE_GENERICINST && mono_class_is_nullable (mono_class_from_mono_type (sig->params [j])))
3541 has_nullable = TRUE;
3544 if (info && !has_nullable && !acfg->aot_opts.llvm_only) {
3545 /* Supported by the dynamic runtime-invoke wrapper */
3549 mono_arch_dyn_call_free (info);
3553 if (acfg->aot_opts.llvm_only)
3554 /* Supported by the gsharedvt based runtime-invoke wrapper */
3558 //printf ("%s\n", mono_method_full_name (method, TRUE));
3559 add_method (acfg, get_runtime_invoke (acfg, method, FALSE));
3563 if (strcmp (acfg->image->assembly->aname.name, "mscorlib") == 0) {
3566 /* Runtime invoke wrappers */
3568 /* void runtime-invoke () [.cctor] */
3569 csig = mono_metadata_signature_alloc (mono_defaults.corlib, 0);
3570 csig->ret = &mono_defaults.void_class->byval_arg;
3571 add_method (acfg, get_runtime_invoke_sig (csig));
3573 /* void runtime-invoke () [Finalize] */
3574 csig = mono_metadata_signature_alloc (mono_defaults.corlib, 0);
3576 csig->ret = &mono_defaults.void_class->byval_arg;
3577 add_method (acfg, get_runtime_invoke_sig (csig));
3579 /* void runtime-invoke (string) [exception ctor] */
3580 csig = mono_metadata_signature_alloc (mono_defaults.corlib, 1);
3582 csig->ret = &mono_defaults.void_class->byval_arg;
3583 csig->params [0] = &mono_defaults.string_class->byval_arg;
3584 add_method (acfg, get_runtime_invoke_sig (csig));
3586 /* void runtime-invoke (string, string) [exception ctor] */
3587 csig = mono_metadata_signature_alloc (mono_defaults.corlib, 2);
3589 csig->ret = &mono_defaults.void_class->byval_arg;
3590 csig->params [0] = &mono_defaults.string_class->byval_arg;
3591 csig->params [1] = &mono_defaults.string_class->byval_arg;
3592 add_method (acfg, get_runtime_invoke_sig (csig));
3594 /* string runtime-invoke () [Exception.ToString ()] */
3595 csig = mono_metadata_signature_alloc (mono_defaults.corlib, 0);
3597 csig->ret = &mono_defaults.string_class->byval_arg;
3598 add_method (acfg, get_runtime_invoke_sig (csig));
3600 /* void runtime-invoke (string, Exception) [exception ctor] */
3601 csig = mono_metadata_signature_alloc (mono_defaults.corlib, 2);
3603 csig->ret = &mono_defaults.void_class->byval_arg;
3604 csig->params [0] = &mono_defaults.string_class->byval_arg;
3605 csig->params [1] = &mono_defaults.exception_class->byval_arg;
3606 add_method (acfg, get_runtime_invoke_sig (csig));
3608 /* Assembly runtime-invoke (string, bool) [DoAssemblyResolve] */
3609 csig = mono_metadata_signature_alloc (mono_defaults.corlib, 2);
3611 csig->ret = &(mono_class_from_name (
3612 mono_defaults.corlib, "System.Reflection", "Assembly"))->byval_arg;
3613 csig->params [0] = &mono_defaults.string_class->byval_arg;
3614 csig->params [1] = &mono_defaults.boolean_class->byval_arg;
3615 add_method (acfg, get_runtime_invoke_sig (csig));
3617 /* runtime-invoke used by finalizers */
3618 add_method (acfg, get_runtime_invoke (acfg, mono_class_get_method_from_name_flags (mono_defaults.object_class, "Finalize", 0, 0), TRUE));
3620 /* This is used by mono_runtime_capture_context () */
3621 method = mono_get_context_capture_method ();
3623 add_method (acfg, get_runtime_invoke (acfg, method, FALSE));
3625 #ifdef MONO_ARCH_DYN_CALL_SUPPORTED
3626 if (!acfg->aot_opts.llvm_only)
3627 add_method (acfg, mono_marshal_get_runtime_invoke_dynamic ());
3630 /* These are used by mono_jit_runtime_invoke () to calls gsharedvt out wrappers */
3631 if (acfg->aot_opts.llvm_only) {
3634 /* Create simplified signatures which match the signature used by the gsharedvt out wrappers */
3635 for (variants = 0; variants < 4; ++variants) {
3636 for (i = 0; i < 16; ++i) {
3637 sig = mini_get_gsharedvt_out_sig_wrapper_signature ((variants & 1) > 0, (variants & 2) > 0, i);
3638 add_extra_method (acfg, mono_marshal_get_runtime_invoke_for_sig (sig));
3646 add_method (acfg, mono_marshal_get_stelemref ());
3648 if (MONO_ARCH_HAVE_TLS_GET) {
3649 /* Managed Allocators */
3650 nallocators = mono_gc_get_managed_allocator_types ();
3651 for (i = 0; i < nallocators; ++i) {
3652 m = mono_gc_get_managed_allocator_by_type (i, TRUE);
3654 add_method (acfg, m);
3656 for (i = 0; i < nallocators; ++i) {
3657 m = mono_gc_get_managed_allocator_by_type (i, FALSE);
3659 add_method (acfg, m);
3663 /* write barriers */
3664 if (mono_gc_is_moving ()) {
3665 add_method (acfg, mono_gc_get_specific_write_barrier (FALSE));
3666 add_method (acfg, mono_gc_get_specific_write_barrier (TRUE));
3669 /* Stelemref wrappers */
3671 MonoMethod **wrappers;
3674 wrappers = mono_marshal_get_virtual_stelemref_wrappers (&nwrappers);
3675 for (i = 0; i < nwrappers; ++i)
3676 add_method (acfg, wrappers [i]);
3680 /* castclass_with_check wrapper */
3681 add_method (acfg, mono_marshal_get_castclass_with_cache ());
3682 /* isinst_with_check wrapper */
3683 add_method (acfg, mono_marshal_get_isinst_with_cache ());
3685 /* JIT icall wrappers */
3686 /* FIXME: locking - this is "safe" as full-AOT threads don't mutate the icall hash*/
3687 g_hash_table_foreach (mono_get_jit_icall_info (), add_jit_icall_wrapper, acfg);
3691 * remoting-invoke-with-check wrappers are very frequent, so avoid emitting them,
3692 * we use the original method instead at runtime.
3693 * Since full-aot doesn't support remoting, this is not a problem.
3696 /* remoting-invoke wrappers */
3697 for (i = 0; i < acfg->image->tables [MONO_TABLE_METHOD].rows; ++i) {
3699 MonoMethodSignature *sig;
3701 token = MONO_TOKEN_METHOD_DEF | (i + 1);
3702 method = mono_get_method_checked (acfg->image, token, NULL, NULL, &error);
3703 g_assert (mono_error_ok (&error)); /* FIXME don't swallow the error */
3705 sig = mono_method_signature (method);
3707 if (sig->hasthis && (method->klass->marshalbyref || method->klass == mono_defaults.object_class)) {
3708 m = mono_marshal_get_remoting_invoke_with_check (method);
3710 add_method (acfg, m);
3715 /* delegate-invoke wrappers */
3716 for (i = 0; i < acfg->image->tables [MONO_TABLE_TYPEDEF].rows; ++i) {
3719 MonoCustomAttrInfo *cattr;
3721 token = MONO_TOKEN_TYPE_DEF | (i + 1);
3722 klass = mono_class_get_checked (acfg->image, token, &error);
3725 mono_error_cleanup (&error);
3729 if (!klass->delegate || klass == mono_defaults.delegate_class || klass == mono_defaults.multicastdelegate_class)
3732 if (!klass->generic_container) {
3733 method = mono_get_delegate_invoke (klass);
3735 m = mono_marshal_get_delegate_invoke (method, NULL);
3737 add_method (acfg, m);
3739 method = mono_class_get_method_from_name_flags (klass, "BeginInvoke", -1, 0);
3741 add_method (acfg, mono_marshal_get_delegate_begin_invoke (method));
3743 method = mono_class_get_method_from_name_flags (klass, "EndInvoke", -1, 0);
3745 add_method (acfg, mono_marshal_get_delegate_end_invoke (method));
3747 cattr = mono_custom_attrs_from_class (klass);
3752 for (j = 0; j < cattr->num_attrs; ++j)
3753 if (cattr->attrs [j].ctor && (!strcmp (cattr->attrs [j].ctor->klass->name, "MonoNativeFunctionWrapperAttribute") || !strcmp (cattr->attrs [j].ctor->klass->name, "UnmanagedFunctionPointerAttribute")))
3755 if (j < cattr->num_attrs) {
3757 MonoMethod *wrapper;
3758 MonoMethod *del_invoke;
3760 /* Add wrappers needed by mono_ftnptr_to_delegate () */
3761 invoke = mono_get_delegate_invoke (klass);
3762 wrapper = mono_marshal_get_native_func_wrapper_aot (klass);
3763 del_invoke = mono_marshal_get_delegate_invoke_internal (invoke, FALSE, TRUE, wrapper);
3764 add_method (acfg, wrapper);
3765 add_method (acfg, del_invoke);
3768 } else if ((acfg->opts & MONO_OPT_GSHAREDVT) && klass->generic_container) {
3770 MonoGenericContext ctx;
3771 MonoMethod *inst, *gshared;
3774 * Emit gsharedvt versions of the generic delegate-invoke wrappers
3777 method = mono_get_delegate_invoke (klass);
3778 create_gsharedvt_inst (acfg, method, &ctx);
3780 inst = mono_class_inflate_generic_method_checked (method, &ctx, &error);
3781 g_assert (mono_error_ok (&error)); /* FIXME don't swallow the error */
3783 m = mono_marshal_get_delegate_invoke (inst, NULL);
3784 g_assert (m->is_inflated);
3786 gshared = mini_get_shared_method_full (m, FALSE, TRUE);
3787 add_extra_method (acfg, gshared);
3790 method = mono_get_delegate_begin_invoke (klass);
3791 create_gsharedvt_inst (acfg, method, &ctx);
3793 inst = mono_class_inflate_generic_method_checked (method, &ctx, &error);
3794 g_assert (mono_error_ok (&error)); /* FIXME don't swallow the error */
3796 m = mono_marshal_get_delegate_begin_invoke (inst);
3797 g_assert (m->is_inflated);
3799 gshared = mini_get_shared_method_full (m, FALSE, TRUE);
3800 add_extra_method (acfg, gshared);
3803 method = mono_get_delegate_end_invoke (klass);
3804 create_gsharedvt_inst (acfg, method, &ctx);
3806 inst = mono_class_inflate_generic_method_checked (method, &ctx, &error);
3807 g_assert (mono_error_ok (&error)); /* FIXME don't swallow the error */
3809 m = mono_marshal_get_delegate_end_invoke (inst);
3810 g_assert (m->is_inflated);
3812 gshared = mini_get_shared_method_full (m, FALSE, TRUE);
3813 add_extra_method (acfg, gshared);
3818 /* array access wrappers */
3819 for (i = 0; i < acfg->image->tables [MONO_TABLE_TYPESPEC].rows; ++i) {
3823 token = MONO_TOKEN_TYPE_SPEC | (i + 1);
3824 klass = mono_class_get_checked (acfg->image, token, &error);
3827 mono_error_cleanup (&error);
3831 if (!acfg->aot_opts.llvm_only && klass->rank && MONO_TYPE_IS_PRIMITIVE (&klass->element_class->byval_arg)) {
3832 MonoMethod *m, *wrapper;
3834 /* Add runtime-invoke wrappers too */
3836 m = mono_class_get_method_from_name (klass, "Get", -1);
3838 wrapper = mono_marshal_get_array_accessor_wrapper (m);
3839 add_extra_method (acfg, wrapper);
3840 add_extra_method (acfg, get_runtime_invoke (acfg, wrapper, FALSE));
3842 m = mono_class_get_method_from_name (klass, "Set", -1);
3844 wrapper = mono_marshal_get_array_accessor_wrapper (m);
3845 add_extra_method (acfg, wrapper);
3846 add_extra_method (acfg, get_runtime_invoke (acfg, wrapper, FALSE));
3850 /* Synchronized wrappers */
3851 for (i = 0; i < acfg->image->tables [MONO_TABLE_METHOD].rows; ++i) {
3853 token = MONO_TOKEN_METHOD_DEF | (i + 1);
3854 method = mono_get_method_checked (acfg->image, token, NULL, NULL, &error);
3855 report_loader_error (acfg, &error, "Failed to load method token 0x%x due to %s\n", i, mono_error_get_message (&error));
3857 if (method->iflags & METHOD_IMPL_ATTRIBUTE_SYNCHRONIZED) {
3858 if (method->is_generic) {
3860 } else if ((acfg->opts & MONO_OPT_GSHAREDVT) && method->klass->generic_container) {
3862 MonoGenericContext ctx;
3863 MonoMethod *inst, *gshared, *m;
3866 * Create a generic wrapper for a generic instance, and AOT that.
3868 create_gsharedvt_inst (acfg, method, &ctx);
3869 inst = mono_class_inflate_generic_method_checked (method, &ctx, &error);
3870 g_assert (mono_error_ok (&error)); /* FIXME don't swallow the error */
3871 m = mono_marshal_get_synchronized_wrapper (inst);
3872 g_assert (m->is_inflated);
3873 gshared = mini_get_shared_method_full (m, FALSE, TRUE);
3874 add_method (acfg, gshared);
3876 add_method (acfg, mono_marshal_get_synchronized_wrapper (method));
3881 /* pinvoke wrappers */
3882 for (i = 0; i < acfg->image->tables [MONO_TABLE_METHOD].rows; ++i) {
3885 guint32 token = MONO_TOKEN_METHOD_DEF | (i + 1);
3887 method = mono_get_method_checked (acfg->image, token, NULL, NULL, &error);
3888 report_loader_error (acfg, &error, "Failed to load method token 0x%x due to %s\n", i, mono_error_get_message (&error));
3890 if ((method->flags & METHOD_ATTRIBUTE_PINVOKE_IMPL) ||
3891 (method->iflags & METHOD_IMPL_ATTRIBUTE_INTERNAL_CALL)) {
3892 add_method (acfg, mono_marshal_get_native_wrapper (method, TRUE, TRUE));
3896 /* native-to-managed wrappers */
3897 for (i = 0; i < acfg->image->tables [MONO_TABLE_METHOD].rows; ++i) {
3900 guint32 token = MONO_TOKEN_METHOD_DEF | (i + 1);
3901 MonoCustomAttrInfo *cattr;
3904 method = mono_get_method_checked (acfg->image, token, NULL, NULL, &error);
3905 report_loader_error (acfg, &error, "Failed to load method token 0x%x due to %s\n", i, mono_error_get_message (&error));
3908 * Only generate native-to-managed wrappers for methods which have an
3909 * attribute named MonoPInvokeCallbackAttribute. We search for the attribute by
3910 * name to avoid defining a new assembly to contain it.
3912 cattr = mono_custom_attrs_from_method (method);
3915 for (j = 0; j < cattr->num_attrs; ++j)
3916 if (cattr->attrs [j].ctor && !strcmp (cattr->attrs [j].ctor->klass->name, "MonoPInvokeCallbackAttribute"))
3918 if (j < cattr->num_attrs) {
3919 MonoCustomAttrEntry *e = &cattr->attrs [j];
3920 MonoMethodSignature *sig = mono_method_signature (e->ctor);
3921 const char *p = (const char*)e->data;
3923 int slen, num_named, named_type;
3927 char *export_name = NULL;
3928 MonoMethod *wrapper;
3930 /* this cannot be enforced by the C# compiler so we must give the user some warning before aborting */
3931 if (!(method->flags & METHOD_ATTRIBUTE_STATIC)) {
3932 g_warning ("AOT restriction: Method '%s' must be static since it is decorated with [MonoPInvokeCallback]. See http://ios.xamarin.com/Documentation/Limitations#Reverse_Callbacks",
3933 mono_method_full_name (method, TRUE));
3937 g_assert (sig->param_count == 1);
3938 g_assert (sig->params [0]->type == MONO_TYPE_CLASS && !strcmp (mono_class_from_mono_type (sig->params [0])->name, "Type"));
3941 * Decode the cattr manually since we can't create objects
3942 * during aot compilation.
3948 /* From load_cattr_value () in reflection.c */
3949 slen = mono_metadata_decode_value (p, &p);
3950 n = (char *)g_memdup (p, slen + 1);
3952 t = mono_reflection_type_from_name (n, acfg->image);
3956 klass = mono_class_from_mono_type (t);
3957 g_assert (klass->parent == mono_defaults.multicastdelegate_class);
3961 num_named = read16 (p);
3964 g_assert (num_named < 2);
3965 if (num_named == 1) {
3969 /* parse ExportSymbol attribute */
3971 named_type = *named;
3973 /* data_type = *named; */
3976 name_len = mono_metadata_decode_blob_size (named, &named);
3977 name = (char *)g_malloc (name_len + 1);
3978 memcpy (name, named, name_len);
3979 name [name_len] = 0;
3982 g_assert (named_type == 0x54);
3983 g_assert (!strcmp (name, "ExportSymbol"));
3985 /* load_cattr_value (), string case */
3986 g_assert (*named != (char)0xff);
3987 slen = mono_metadata_decode_value (named, &named);
3988 export_name = (char *)g_malloc (slen + 1);
3989 memcpy (export_name, named, slen);
3990 export_name [slen] = 0;
3994 wrapper = mono_marshal_get_managed_wrapper (method, klass, 0);
3995 add_method (acfg, wrapper);
3997 g_hash_table_insert (acfg->export_names, wrapper, export_name);
4001 if ((method->flags & METHOD_ATTRIBUTE_PINVOKE_IMPL) ||
4002 (method->iflags & METHOD_IMPL_ATTRIBUTE_INTERNAL_CALL)) {
4003 add_method (acfg, mono_marshal_get_native_wrapper (method, TRUE, TRUE));
4007 /* StructureToPtr/PtrToStructure wrappers */
4008 for (i = 0; i < acfg->image->tables [MONO_TABLE_TYPEDEF].rows; ++i) {
4012 token = MONO_TOKEN_TYPE_DEF | (i + 1);
4013 klass = mono_class_get_checked (acfg->image, token, &error);
4016 mono_error_cleanup (&error);
4020 if (klass->valuetype && !klass->generic_container && can_marshal_struct (klass) &&
4021 !(klass->nested_in && strstr (klass->nested_in->name, "<PrivateImplementationDetails>") == klass->nested_in->name)) {
4022 add_method (acfg, mono_marshal_get_struct_to_ptr (klass));
4023 add_method (acfg, mono_marshal_get_ptr_to_struct (klass));
4029 has_type_vars (MonoClass *klass)
4031 if ((klass->byval_arg.type == MONO_TYPE_VAR) || (klass->byval_arg.type == MONO_TYPE_MVAR))
4034 return has_type_vars (klass->element_class);
4035 if (klass->generic_class) {
4036 MonoGenericContext *context = &klass->generic_class->context;
4037 if (context->class_inst) {
4040 for (i = 0; i < context->class_inst->type_argc; ++i)
4041 if (has_type_vars (mono_class_from_mono_type (context->class_inst->type_argv [i])))
4045 if (klass->generic_container)
4051 is_vt_inst (MonoGenericInst *inst)
4055 for (i = 0; i < inst->type_argc; ++i) {
4056 MonoType *t = inst->type_argv [i];
4057 if (MONO_TYPE_ISSTRUCT (t) || t->type == MONO_TYPE_VALUETYPE)
4064 method_has_type_vars (MonoMethod *method)
4066 if (has_type_vars (method->klass))
4069 if (method->is_inflated) {
4070 MonoGenericContext *context = mono_method_get_context (method);
4071 if (context->method_inst) {
4074 for (i = 0; i < context->method_inst->type_argc; ++i)
4075 if (has_type_vars (mono_class_from_mono_type (context->method_inst->type_argv [i])))
4083 gboolean mono_aot_mode_is_full (MonoAotOptions *opts)
4085 return opts->mode == MONO_AOT_MODE_FULL;
4088 static void add_generic_class_with_depth (MonoAotCompile *acfg, MonoClass *klass, int depth, const char *ref);
4091 add_generic_class (MonoAotCompile *acfg, MonoClass *klass, gboolean force, const char *ref)
4093 /* This might lead to a huge code blowup so only do it if neccesary */
4094 if (!mono_aot_mode_is_full (&acfg->aot_opts) && !force)
4097 add_generic_class_with_depth (acfg, klass, 0, ref);
4101 check_type_depth (MonoType *t, int depth)
4109 case MONO_TYPE_GENERICINST: {
4110 MonoGenericClass *gklass = t->data.generic_class;
4111 MonoGenericInst *ginst = gklass->context.class_inst;
4114 for (i = 0; i < ginst->type_argc; ++i) {
4115 if (check_type_depth (ginst->type_argv [i], depth + 1))
4129 add_types_from_method_header (MonoAotCompile *acfg, MonoMethod *method);
4132 * add_generic_class:
4134 * Add all methods of a generic class.
4137 add_generic_class_with_depth (MonoAotCompile *acfg, MonoClass *klass, int depth, const char *ref)
4140 MonoClassField *field;
4142 gboolean use_gsharedvt = FALSE;
4144 if (!acfg->ginst_hash)
4145 acfg->ginst_hash = g_hash_table_new (NULL, NULL);
4147 mono_class_init (klass);
4149 if (klass->generic_class && klass->generic_class->context.class_inst->is_open)
4152 if (has_type_vars (klass))
4155 if (!klass->generic_class && !klass->rank)
4158 if (klass->exception_type)
4161 if (!acfg->ginst_hash)
4162 acfg->ginst_hash = g_hash_table_new (NULL, NULL);
4164 if (g_hash_table_lookup (acfg->ginst_hash, klass))
4167 if (check_type_depth (&klass->byval_arg, 0))
4170 if (acfg->aot_opts.log_generics)
4171 aot_printf (acfg, "%*sAdding generic instance %s [%s].\n", depth, "", mono_type_full_name (&klass->byval_arg), ref);
4173 g_hash_table_insert (acfg->ginst_hash, klass, klass);
4176 * Use gsharedvt for generic collections with vtype arguments to avoid code blowup.
4177 * Enable this only for some classes since gsharedvt might not support all methods.
4179 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) &&
4180 (!strcmp (klass->name, "Dictionary`2") || !strcmp (klass->name, "List`1") || !strcmp (klass->name, "ReadOnlyCollection`1")))
4181 use_gsharedvt = TRUE;
4184 while ((method = mono_class_get_methods (klass, &iter))) {
4185 if ((acfg->opts & MONO_OPT_GSHAREDVT) && method->is_inflated && mono_method_get_context (method)->method_inst) {
4187 * This is partial sharing, and we can't handle it yet
4192 if (mono_method_is_generic_sharable_full (method, FALSE, FALSE, use_gsharedvt)) {
4194 add_types_from_method_header (acfg, method);
4198 if (method->is_generic)
4203 * FIXME: Instances which are referenced by these methods are not added,
4204 * for example Array.Resize<int> for List<int>.Add ().
4206 add_extra_method_with_depth (acfg, method, depth + 1);
4210 while ((field = mono_class_get_fields (klass, &iter))) {
4211 if (field->type->type == MONO_TYPE_GENERICINST)
4212 add_generic_class_with_depth (acfg, mono_class_from_mono_type (field->type), depth + 1, "field");
4215 if (klass->delegate) {
4216 method = mono_get_delegate_invoke (klass);
4218 method = mono_marshal_get_delegate_invoke (method, NULL);
4220 if (acfg->aot_opts.log_generics)
4221 aot_printf (acfg, "%*sAdding method %s.\n", depth, "", mono_method_get_full_name (method));
4223 add_method (acfg, method);
4226 /* Add superclasses */
4228 add_generic_class_with_depth (acfg, klass->parent, depth, "parent");
4231 * For ICollection<T>, add instances of the helper methods
4232 * in Array, since a T[] could be cast to ICollection<T>.
4234 if (klass->image == mono_defaults.corlib && !strcmp (klass->name_space, "System.Collections.Generic") &&
4235 (!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"))) {
4236 MonoClass *tclass = mono_class_from_mono_type (klass->generic_class->context.class_inst->type_argv [0]);
4237 MonoClass *array_class = mono_bounded_array_class_get (tclass, 1, FALSE);
4241 if (!strcmp (klass->name, "IEnumerator`1"))
4242 name_prefix = g_strdup_printf ("%s.%s", klass->name_space, "IEnumerable`1");
4244 name_prefix = g_strdup_printf ("%s.%s", klass->name_space, klass->name);
4246 /* Add the T[]/InternalEnumerator class */
4247 if (!strcmp (klass->name, "IEnumerable`1") || !strcmp (klass->name, "IEnumerator`1")) {
4251 while ((nclass = mono_class_get_nested_types (array_class->parent, &iter))) {
4252 if (!strcmp (nclass->name, "InternalEnumerator`1"))
4256 nclass = mono_class_inflate_generic_class (nclass, mono_generic_class_get_context (klass->generic_class));
4257 add_generic_class (acfg, nclass, FALSE, "ICollection<T>");
4261 while ((method = mono_class_get_methods (array_class, &iter))) {
4262 if (strstr (method->name, name_prefix)) {
4263 MonoMethod *m = mono_aot_get_array_helper_from_wrapper (method);
4265 add_extra_method_with_depth (acfg, m, depth);
4269 g_free (name_prefix);
4272 /* Add an instance of GenericComparer<T> which is created dynamically by Comparer<T> */
4273 if (klass->image == mono_defaults.corlib && !strcmp (klass->name_space, "System.Collections.Generic") && !strcmp (klass->name, "Comparer`1")) {
4274 MonoClass *tclass = mono_class_from_mono_type (klass->generic_class->context.class_inst->type_argv [0]);
4275 MonoClass *icomparable, *gcomparer;
4276 MonoGenericContext ctx;
4277 MonoType *args [16];
4279 memset (&ctx, 0, sizeof (ctx));
4281 icomparable = mono_class_from_name (mono_defaults.corlib, "System", "IComparable`1");
4282 g_assert (icomparable);
4283 args [0] = &tclass->byval_arg;
4284 ctx.class_inst = mono_metadata_get_generic_inst (1, args);
4286 if (mono_class_is_assignable_from (mono_class_inflate_generic_class (icomparable, &ctx), tclass)) {
4287 gcomparer = mono_class_from_name (mono_defaults.corlib, "System.Collections.Generic", "GenericComparer`1");
4288 g_assert (gcomparer);
4289 add_generic_class (acfg, mono_class_inflate_generic_class (gcomparer, &ctx), FALSE, "Comparer<T>");
4293 /* Add an instance of GenericEqualityComparer<T> which is created dynamically by EqualityComparer<T> */
4294 if (klass->image == mono_defaults.corlib && !strcmp (klass->name_space, "System.Collections.Generic") && !strcmp (klass->name, "EqualityComparer`1")) {
4295 MonoClass *tclass = mono_class_from_mono_type (klass->generic_class->context.class_inst->type_argv [0]);
4296 MonoClass *iface, *gcomparer;
4297 MonoGenericContext ctx;
4298 MonoType *args [16];
4300 memset (&ctx, 0, sizeof (ctx));
4302 iface = mono_class_from_name (mono_defaults.corlib, "System", "IEquatable`1");
4304 args [0] = &tclass->byval_arg;
4305 ctx.class_inst = mono_metadata_get_generic_inst (1, args);
4307 if (mono_class_is_assignable_from (mono_class_inflate_generic_class (iface, &ctx), tclass)) {
4308 gcomparer = mono_class_from_name (mono_defaults.corlib, "System.Collections.Generic", "GenericEqualityComparer`1");
4309 g_assert (gcomparer);
4310 add_generic_class (acfg, mono_class_inflate_generic_class (gcomparer, &ctx), FALSE, "EqualityComparer<T>");
4314 /* Add an instance of EnumComparer<T> which is created dynamically by EqualityComparer<T> for enums */
4315 if (klass->image == mono_defaults.corlib && !strcmp (klass->name_space, "System.Collections.Generic") && !strcmp (klass->name, "EqualityComparer`1")) {
4316 MonoClass *enum_comparer;
4317 MonoClass *tclass = mono_class_from_mono_type (klass->generic_class->context.class_inst->type_argv [0]);
4318 MonoGenericContext ctx;
4319 MonoType *args [16];
4321 if (mono_class_is_enum (tclass)) {
4322 memset (&ctx, 0, sizeof (ctx));
4323 args [0] = &tclass->byval_arg;
4324 ctx.class_inst = mono_metadata_get_generic_inst (1, args);
4326 enum_comparer = mono_class_from_name (mono_defaults.corlib, "System.Collections.Generic", "EnumEqualityComparer`1");
4327 g_assert (enum_comparer);
4328 add_generic_class (acfg, mono_class_inflate_generic_class (enum_comparer, &ctx), FALSE, "EqualityComparer<T>");
4332 /* Add an instance of ObjectComparer<T> which is created dynamically by Comparer<T> for enums */
4333 if (klass->image == mono_defaults.corlib && !strcmp (klass->name_space, "System.Collections.Generic") && !strcmp (klass->name, "Comparer`1")) {
4334 MonoClass *comparer;
4335 MonoClass *tclass = mono_class_from_mono_type (klass->generic_class->context.class_inst->type_argv [0]);
4336 MonoGenericContext ctx;
4337 MonoType *args [16];
4339 if (mono_class_is_enum (tclass)) {
4340 memset (&ctx, 0, sizeof (ctx));
4341 args [0] = &tclass->byval_arg;
4342 ctx.class_inst = mono_metadata_get_generic_inst (1, args);
4344 comparer = mono_class_from_name (mono_defaults.corlib, "System.Collections.Generic", "ObjectComparer`1");
4345 g_assert (comparer);
4346 add_generic_class (acfg, mono_class_inflate_generic_class (comparer, &ctx), FALSE, "Comparer<T>");
4352 add_instances_of (MonoAotCompile *acfg, MonoClass *klass, MonoType **insts, int ninsts, gboolean force)
4355 MonoGenericContext ctx;
4356 MonoType *args [16];
4358 if (acfg->aot_opts.no_instances)
4361 memset (&ctx, 0, sizeof (ctx));
4363 for (i = 0; i < ninsts; ++i) {
4364 args [0] = insts [i];
4365 ctx.class_inst = mono_metadata_get_generic_inst (1, args);
4366 add_generic_class (acfg, mono_class_inflate_generic_class (klass, &ctx), force, "");
4371 add_types_from_method_header (MonoAotCompile *acfg, MonoMethod *method)
4373 MonoMethodHeader *header;
4374 MonoMethodSignature *sig;
4377 depth = GPOINTER_TO_UINT (g_hash_table_lookup (acfg->method_depth, method));
4379 sig = mono_method_signature (method);
4382 for (j = 0; j < sig->param_count; ++j)
4383 if (sig->params [j]->type == MONO_TYPE_GENERICINST)
4384 add_generic_class_with_depth (acfg, mono_class_from_mono_type (sig->params [j]), depth + 1, "arg");
4387 header = mono_method_get_header (method);
4390 for (j = 0; j < header->num_locals; ++j)
4391 if (header->locals [j]->type == MONO_TYPE_GENERICINST)
4392 add_generic_class_with_depth (acfg, mono_class_from_mono_type (header->locals [j]), depth + 1, "local");
4394 mono_loader_clear_error ();
4399 * add_generic_instances:
4401 * Add instances referenced by the METHODSPEC/TYPESPEC table.
4404 add_generic_instances (MonoAotCompile *acfg)
4409 MonoGenericContext *context;
4411 if (acfg->aot_opts.no_instances)
4414 for (i = 0; i < acfg->image->tables [MONO_TABLE_METHODSPEC].rows; ++i) {
4416 token = MONO_TOKEN_METHOD_SPEC | (i + 1);
4417 method = mono_get_method_checked (acfg->image, token, NULL, NULL, &error);
4420 aot_printerrf (acfg, "Failed to load methodspec 0x%x due to %s.\n", token, mono_error_get_message (&error));
4421 aot_printerrf (acfg, "Run with MONO_LOG_LEVEL=debug for more information.\n");
4422 mono_error_cleanup (&error);
4426 if (method->klass->image != acfg->image)
4429 context = mono_method_get_context (method);
4431 if (context && ((context->class_inst && context->class_inst->is_open)))
4435 * For open methods, create an instantiation which can be passed to the JIT.
4436 * FIXME: Handle class_inst as well.
4438 if (context && context->method_inst && context->method_inst->is_open) {
4440 MonoGenericContext shared_context;
4441 MonoGenericInst *inst;
4442 MonoType **type_argv;
4444 MonoMethod *declaring_method;
4445 gboolean supported = TRUE;
4447 /* Check that the context doesn't contain open constructed types */
4448 if (context->class_inst) {
4449 inst = context->class_inst;
4450 for (i = 0; i < inst->type_argc; ++i) {
4451 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)
4453 if (mono_class_is_open_constructed_type (inst->type_argv [i]))
4457 if (context->method_inst) {
4458 inst = context->method_inst;
4459 for (i = 0; i < inst->type_argc; ++i) {
4460 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)
4462 if (mono_class_is_open_constructed_type (inst->type_argv [i]))
4470 memset (&shared_context, 0, sizeof (MonoGenericContext));
4472 inst = context->class_inst;
4474 type_argv = g_new0 (MonoType*, inst->type_argc);
4475 for (i = 0; i < inst->type_argc; ++i) {
4476 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)
4477 type_argv [i] = &mono_defaults.object_class->byval_arg;
4479 type_argv [i] = inst->type_argv [i];
4482 shared_context.class_inst = mono_metadata_get_generic_inst (inst->type_argc, type_argv);
4486 inst = context->method_inst;
4488 type_argv = g_new0 (MonoType*, inst->type_argc);
4489 for (i = 0; i < inst->type_argc; ++i) {
4490 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)
4491 type_argv [i] = &mono_defaults.object_class->byval_arg;
4493 type_argv [i] = inst->type_argv [i];
4496 shared_context.method_inst = mono_metadata_get_generic_inst (inst->type_argc, type_argv);
4500 if (method->is_generic || method->klass->generic_container)
4501 declaring_method = method;
4503 declaring_method = mono_method_get_declaring_generic_method (method);
4505 method = mono_class_inflate_generic_method_checked (declaring_method, &shared_context, &error);
4506 g_assert (mono_error_ok (&error)); /* FIXME don't swallow the error */
4510 * If the method is fully sharable, it was already added in place of its
4511 * generic definition.
4513 if (mono_method_is_generic_sharable_full (method, FALSE, FALSE, FALSE))
4517 * FIXME: Partially shared methods are not shared here, so we end up with
4518 * many identical methods.
4520 add_extra_method (acfg, method);
4523 for (i = 0; i < acfg->image->tables [MONO_TABLE_TYPESPEC].rows; ++i) {
4527 token = MONO_TOKEN_TYPE_SPEC | (i + 1);
4529 klass = mono_class_get_checked (acfg->image, token, &error);
4530 if (!klass || klass->rank) {
4531 mono_error_cleanup (&error);
4535 add_generic_class (acfg, klass, FALSE, "typespec");
4538 /* Add types of args/locals */
4539 for (i = 0; i < acfg->methods->len; ++i) {
4540 method = (MonoMethod *)g_ptr_array_index (acfg->methods, i);
4541 add_types_from_method_header (acfg, method);
4544 if (acfg->image == mono_defaults.corlib) {
4546 MonoType *insts [256];
4549 insts [ninsts ++] = &mono_defaults.byte_class->byval_arg;
4550 insts [ninsts ++] = &mono_defaults.sbyte_class->byval_arg;
4551 insts [ninsts ++] = &mono_defaults.int16_class->byval_arg;
4552 insts [ninsts ++] = &mono_defaults.uint16_class->byval_arg;
4553 insts [ninsts ++] = &mono_defaults.int32_class->byval_arg;
4554 insts [ninsts ++] = &mono_defaults.uint32_class->byval_arg;
4555 insts [ninsts ++] = &mono_defaults.int64_class->byval_arg;
4556 insts [ninsts ++] = &mono_defaults.uint64_class->byval_arg;
4557 insts [ninsts ++] = &mono_defaults.single_class->byval_arg;
4558 insts [ninsts ++] = &mono_defaults.double_class->byval_arg;
4559 insts [ninsts ++] = &mono_defaults.char_class->byval_arg;
4560 insts [ninsts ++] = &mono_defaults.boolean_class->byval_arg;
4562 /* Add GenericComparer<T> instances for primitive types for Enum.ToString () */
4563 klass = mono_class_from_name (acfg->image, "System.Collections.Generic", "GenericComparer`1");
4565 add_instances_of (acfg, klass, insts, ninsts, TRUE);
4566 klass = mono_class_from_name (acfg->image, "System.Collections.Generic", "GenericEqualityComparer`1");
4568 add_instances_of (acfg, klass, insts, ninsts, TRUE);
4570 /* Add instances of EnumEqualityComparer which are created by EqualityComparer<T> for enums */
4572 MonoClass *enum_comparer;
4573 MonoType *insts [16];
4577 insts [ninsts ++] = &mono_defaults.int32_class->byval_arg;
4578 insts [ninsts ++] = &mono_defaults.uint32_class->byval_arg;
4579 insts [ninsts ++] = &mono_defaults.uint16_class->byval_arg;
4580 insts [ninsts ++] = &mono_defaults.byte_class->byval_arg;
4581 enum_comparer = mono_class_from_name (mono_defaults.corlib, "System.Collections.Generic", "EnumEqualityComparer`1");
4582 g_assert (enum_comparer);
4583 add_instances_of (acfg, enum_comparer, insts, ninsts, FALSE);
4586 insts [ninsts ++] = &mono_defaults.int16_class->byval_arg;
4587 enum_comparer = mono_class_from_name (mono_defaults.corlib, "System.Collections.Generic", "ShortEnumEqualityComparer`1");
4588 g_assert (enum_comparer);
4589 add_instances_of (acfg, enum_comparer, insts, ninsts, FALSE);
4592 insts [ninsts ++] = &mono_defaults.sbyte_class->byval_arg;
4593 enum_comparer = mono_class_from_name (mono_defaults.corlib, "System.Collections.Generic", "SByteEnumEqualityComparer`1");
4594 g_assert (enum_comparer);
4595 add_instances_of (acfg, enum_comparer, insts, ninsts, FALSE);
4597 enum_comparer = mono_class_from_name (mono_defaults.corlib, "System.Collections.Generic", "LongEnumEqualityComparer`1");
4598 g_assert (enum_comparer);
4600 insts [ninsts ++] = &mono_defaults.int64_class->byval_arg;
4601 insts [ninsts ++] = &mono_defaults.uint64_class->byval_arg;
4602 add_instances_of (acfg, enum_comparer, insts, ninsts, FALSE);
4605 /* Add instances of the array generic interfaces for primitive types */
4606 /* This will add instances of the InternalArray_ helper methods in Array too */
4607 klass = mono_class_from_name (acfg->image, "System.Collections.Generic", "ICollection`1");
4609 add_instances_of (acfg, klass, insts, ninsts, TRUE);
4610 klass = mono_class_from_name (acfg->image, "System.Collections.Generic", "IList`1");
4612 add_instances_of (acfg, klass, insts, ninsts, TRUE);
4613 klass = mono_class_from_name (acfg->image, "System.Collections.Generic", "IEnumerable`1");
4615 add_instances_of (acfg, klass, insts, ninsts, TRUE);
4618 * Add a managed-to-native wrapper of Array.GetGenericValueImpl<object>, which is
4619 * used for all instances of GetGenericValueImpl by the AOT runtime.
4622 MonoGenericContext ctx;
4623 MonoType *args [16];
4624 MonoMethod *get_method;
4625 MonoClass *array_klass = mono_array_class_get (mono_defaults.object_class, 1)->parent;
4627 get_method = mono_class_get_method_from_name (array_klass, "GetGenericValueImpl", 2);
4631 memset (&ctx, 0, sizeof (ctx));
4632 args [0] = &mono_defaults.object_class->byval_arg;
4633 ctx.method_inst = mono_metadata_get_generic_inst (1, args);
4634 add_extra_method (acfg, mono_marshal_get_native_wrapper (mono_class_inflate_generic_method_checked (get_method, &ctx, &error), TRUE, TRUE));
4635 g_assert (mono_error_ok (&error)); /* FIXME don't swallow the error */
4639 /* Same for CompareExchange<T>/Exchange<T> */
4641 MonoGenericContext ctx;
4642 MonoType *args [16];
4644 MonoClass *interlocked_klass = mono_class_from_name (mono_defaults.corlib, "System.Threading", "Interlocked");
4645 gpointer iter = NULL;
4647 while ((m = mono_class_get_methods (interlocked_klass, &iter))) {
4648 if ((!strcmp (m->name, "CompareExchange") || !strcmp (m->name, "Exchange")) && m->is_generic) {
4650 memset (&ctx, 0, sizeof (ctx));
4651 args [0] = &mono_defaults.object_class->byval_arg;
4652 ctx.method_inst = mono_metadata_get_generic_inst (1, args);
4653 add_extra_method (acfg, mono_marshal_get_native_wrapper (mono_class_inflate_generic_method_checked (m, &ctx, &error), TRUE, TRUE));
4654 g_assert (mono_error_ok (&error)); /* FIXME don't swallow the error */
4659 /* Same for Volatile.Read/Write<T> */
4661 MonoGenericContext ctx;
4662 MonoType *args [16];
4664 MonoClass *volatile_klass = mono_class_from_name (mono_defaults.corlib, "System.Threading", "Volatile");
4665 gpointer iter = NULL;
4667 if (volatile_klass) {
4668 while ((m = mono_class_get_methods (volatile_klass, &iter))) {
4669 if ((!strcmp (m->name, "Read") || !strcmp (m->name, "Write")) && m->is_generic) {
4671 memset (&ctx, 0, sizeof (ctx));
4672 args [0] = &mono_defaults.object_class->byval_arg;
4673 ctx.method_inst = mono_metadata_get_generic_inst (1, args);
4674 add_extra_method (acfg, mono_marshal_get_native_wrapper (mono_class_inflate_generic_method_checked (m, &ctx, &error), TRUE, TRUE));
4675 g_assert (mono_error_ok (&error)); /* FIXME don't swallow the error */
4681 /* object[] accessor wrappers. */
4683 MonoClass *obj_array_class = mono_array_class_get (mono_defaults.object_class, 1);
4686 m = mono_class_get_method_from_name (obj_array_class, "Get", 1);
4689 m = mono_marshal_get_array_accessor_wrapper (m);
4690 add_extra_method (acfg, m);
4692 m = mono_class_get_method_from_name (obj_array_class, "Address", 1);
4695 m = mono_marshal_get_array_accessor_wrapper (m);
4696 add_extra_method (acfg, m);
4698 m = mono_class_get_method_from_name (obj_array_class, "Set", 2);
4701 m = mono_marshal_get_array_accessor_wrapper (m);
4702 add_extra_method (acfg, m);
4708 * is_direct_callable:
4710 * Return whenever the method identified by JI is directly callable without
4711 * going through the PLT.
4714 is_direct_callable (MonoAotCompile *acfg, MonoMethod *method, MonoJumpInfo *patch_info)
4716 if ((patch_info->type == MONO_PATCH_INFO_METHOD) && (patch_info->data.method->klass->image == acfg->image)) {
4717 MonoCompile *callee_cfg = (MonoCompile *)g_hash_table_lookup (acfg->method_to_cfg, patch_info->data.method);
4719 gboolean direct_callable = TRUE;
4721 if (direct_callable && !(!callee_cfg->has_got_slots && (callee_cfg->method->klass->flags & TYPE_ATTRIBUTE_BEFORE_FIELD_INIT)))
4722 direct_callable = FALSE;
4723 if ((callee_cfg->method->iflags & METHOD_IMPL_ATTRIBUTE_SYNCHRONIZED) && (!method || method->wrapper_type != MONO_WRAPPER_SYNCHRONIZED))
4724 // FIXME: Maybe call the wrapper directly ?
4725 direct_callable = FALSE;
4727 if (acfg->aot_opts.soft_debug || acfg->aot_opts.no_direct_calls) {
4728 /* Disable this so all calls go through load_method (), see the
4729 * mini_get_debug_options ()->load_aot_jit_info_eagerly = TRUE; line in
4730 * mono_debugger_agent_init ().
4732 direct_callable = FALSE;
4735 if (callee_cfg->method->wrapper_type == MONO_WRAPPER_ALLOC)
4736 /* sgen does some initialization when the allocator method is created */
4737 direct_callable = FALSE;
4738 if (callee_cfg->method->wrapper_type == MONO_WRAPPER_WRITE_BARRIER)
4739 /* we don't know at compile time whether sgen is concurrent or not */
4740 direct_callable = FALSE;
4742 if (direct_callable)
4745 } else if ((patch_info->type == MONO_PATCH_INFO_ICALL_ADDR && patch_info->data.method->flags & METHOD_ATTRIBUTE_PINVOKE_IMPL)) {
4746 if (acfg->aot_opts.direct_pinvoke)
4748 } else if (patch_info->type == MONO_PATCH_INFO_ICALL_ADDR) {
4749 if (acfg->aot_opts.direct_icalls)
4757 #ifdef MONO_ARCH_AOT_SUPPORTED
4759 get_pinvoke_import (MonoAotCompile *acfg, MonoMethod *method)
4761 MonoImage *image = method->klass->image;
4762 MonoMethodPInvoke *piinfo = (MonoMethodPInvoke *) method;
4763 MonoTableInfo *tables = image->tables;
4764 MonoTableInfo *im = &tables [MONO_TABLE_IMPLMAP];
4765 MonoTableInfo *mr = &tables [MONO_TABLE_MODULEREF];
4766 guint32 im_cols [MONO_IMPLMAP_SIZE];
4769 import = (char *)g_hash_table_lookup (acfg->method_to_pinvoke_import, method);
4773 if (!piinfo->implmap_idx || piinfo->implmap_idx > im->rows)
4776 mono_metadata_decode_row (im, piinfo->implmap_idx - 1, im_cols, MONO_IMPLMAP_SIZE);
4778 if (!im_cols [MONO_IMPLMAP_SCOPE] || im_cols [MONO_IMPLMAP_SCOPE] > mr->rows)
4781 import = g_strdup_printf ("%s", mono_metadata_string_heap (image, im_cols [MONO_IMPLMAP_NAME]));
4783 g_hash_table_insert (acfg->method_to_pinvoke_import, method, import);
4789 get_pinvoke_import (MonoAotCompile *acfg, MonoMethod *method)
4796 compare_lne (MonoDebugLineNumberEntry *a, MonoDebugLineNumberEntry *b)
4798 if (a->native_offset == b->native_offset)
4799 return a->il_offset - b->il_offset;
4801 return a->native_offset - b->native_offset;
4805 * compute_line_numbers:
4807 * Returns a sparse array of size CODE_SIZE containing MonoDebugSourceLocation* entries for the native offsets which have a corresponding line number
4810 static MonoDebugSourceLocation**
4811 compute_line_numbers (MonoMethod *method, int code_size, MonoDebugMethodJitInfo *debug_info)
4813 MonoDebugMethodInfo *minfo;
4814 MonoDebugLineNumberEntry *ln_array;
4815 MonoDebugSourceLocation *loc;
4816 int i, prev_line, prev_il_offset;
4817 int *native_to_il_offset = NULL;
4818 MonoDebugSourceLocation **res;
4821 minfo = mono_debug_lookup_method (method);
4824 // FIXME: This seems to happen when two methods have the same cfg->method_to_register
4825 if (debug_info->code_size != code_size)
4828 g_assert (code_size);
4830 /* Compute the native->IL offset mapping */
4832 ln_array = g_new0 (MonoDebugLineNumberEntry, debug_info->num_line_numbers);
4833 memcpy (ln_array, debug_info->line_numbers, debug_info->num_line_numbers * sizeof (MonoDebugLineNumberEntry));
4835 qsort (ln_array, debug_info->num_line_numbers, sizeof (MonoDebugLineNumberEntry), (int (*)(const void *, const void *))compare_lne);
4837 native_to_il_offset = g_new0 (int, code_size + 1);
4839 for (i = 0; i < debug_info->num_line_numbers; ++i) {
4841 MonoDebugLineNumberEntry *lne = &ln_array [i];
4844 for (j = 0; j < lne->native_offset; ++j)
4845 native_to_il_offset [j] = -1;
4848 if (i < debug_info->num_line_numbers - 1) {
4849 MonoDebugLineNumberEntry *lne_next = &ln_array [i + 1];
4851 for (j = lne->native_offset; j < lne_next->native_offset; ++j)
4852 native_to_il_offset [j] = lne->il_offset;
4854 for (j = lne->native_offset; j < code_size; ++j)
4855 native_to_il_offset [j] = lne->il_offset;
4860 /* Compute the native->line number mapping */
4861 res = g_new0 (MonoDebugSourceLocation*, code_size);
4862 prev_il_offset = -1;
4865 for (i = 0; i < code_size; ++i) {
4866 int il_offset = native_to_il_offset [i];
4868 if (il_offset == -1 || il_offset == prev_il_offset)
4870 prev_il_offset = il_offset;
4871 loc = mono_debug_symfile_lookup_location (minfo, il_offset);
4872 if (!(loc && loc->source_file))
4874 if (loc->row == prev_line) {
4875 mono_debug_symfile_free_location (loc);
4878 prev_line = loc->row;
4879 //printf ("D: %s:%d il=%x native=%x\n", loc->source_file, loc->row, il_offset, i);
4881 /* This will cover the prolog too */
4891 get_file_index (MonoAotCompile *acfg, const char *source_file)
4895 // FIXME: Free these
4896 if (!acfg->dwarf_ln_filenames)
4897 acfg->dwarf_ln_filenames = g_hash_table_new (g_str_hash, g_str_equal);
4898 findex = GPOINTER_TO_INT (g_hash_table_lookup (acfg->dwarf_ln_filenames, source_file));
4900 findex = g_hash_table_size (acfg->dwarf_ln_filenames) + 1;
4901 g_hash_table_insert (acfg->dwarf_ln_filenames, g_strdup (source_file), GINT_TO_POINTER (findex));
4902 emit_unset_mode (acfg);
4903 fprintf (acfg->fp, ".file %d \"%s\"\n", findex, mono_dwarf_escape_path (source_file));
4915 * emit_and_reloc_code:
4917 * Emit the native code in CODE, handling relocations along the way. If GOT_ONLY
4918 * is true, calls are made through the GOT too. This is used for emitting trampolines
4919 * in full-aot mode, since calls made from trampolines couldn't go through the PLT,
4920 * since trampolines are needed to make PTL work.
4923 emit_and_reloc_code (MonoAotCompile *acfg, MonoMethod *method, guint8 *code, guint32 code_len, MonoJumpInfo *relocs, gboolean got_only, MonoDebugMethodJitInfo *debug_info)
4925 int i, pindex, start_index;
4927 MonoJumpInfo *patch_info;
4928 MonoDebugSourceLocation **locs = NULL;
4930 #ifdef MONO_ARCH_AOT_SUPPORTED
4931 gboolean direct_call, external_call;
4933 const char *direct_call_target = 0;
4934 const char *direct_pinvoke;
4937 if (acfg->gas_line_numbers && method && debug_info) {
4938 locs = compute_line_numbers (method, code_len, debug_info);
4940 int findex = get_file_index (acfg, "<unknown>");
4941 emit_unset_mode (acfg);
4942 fprintf (acfg->fp, ".loc %d %d 0\n", findex, 1);
4946 /* Collect and sort relocations */
4947 patches = g_ptr_array_new ();
4948 for (patch_info = relocs; patch_info; patch_info = patch_info->next)
4949 g_ptr_array_add (patches, patch_info);
4950 g_ptr_array_sort (patches, compare_patches);
4953 for (i = 0; i < code_len; i += INST_LEN) {
4955 for (pindex = start_index; pindex < patches->len; ++pindex) {
4956 patch_info = (MonoJumpInfo *)g_ptr_array_index (patches, pindex);
4957 if (patch_info->ip.i >= i)
4961 if (locs && locs [i]) {
4962 MonoDebugSourceLocation *loc = locs [i];
4965 findex = get_file_index (acfg, loc->source_file);
4966 emit_unset_mode (acfg);
4967 fprintf (acfg->fp, ".loc %d %d 0\n", findex, loc->row);
4968 mono_debug_symfile_free_location (loc);
4972 #ifdef MONO_ARCH_AOT_SUPPORTED
4973 if (patch_info && (patch_info->ip.i == i) && (pindex < patches->len)) {
4974 start_index = pindex;
4976 switch (patch_info->type) {
4977 case MONO_PATCH_INFO_NONE:
4979 case MONO_PATCH_INFO_GOT_OFFSET: {
4982 arch_emit_got_offset (acfg, code + i, &code_size);
4983 i += code_size - INST_LEN;
4985 patch_info->type = MONO_PATCH_INFO_NONE;
4988 case MONO_PATCH_INFO_OBJC_SELECTOR_REF: {
4989 int code_size, index;
4990 char *selector = (char *)patch_info->data.target;
4992 if (!acfg->objc_selector_to_index)
4993 acfg->objc_selector_to_index = g_hash_table_new (g_str_hash, g_str_equal);
4994 if (!acfg->objc_selectors)
4995 acfg->objc_selectors = g_ptr_array_new ();
4996 index = GPOINTER_TO_UINT (g_hash_table_lookup (acfg->objc_selector_to_index, selector));
5000 index = acfg->objc_selector_index;
5001 g_ptr_array_add (acfg->objc_selectors, (void*)patch_info->data.target);
5002 g_hash_table_insert (acfg->objc_selector_to_index, selector, GUINT_TO_POINTER (index + 1));
5003 acfg->objc_selector_index ++;
5006 arch_emit_objc_selector_ref (acfg, code + i, index, &code_size);
5007 i += code_size - INST_LEN;
5009 patch_info->type = MONO_PATCH_INFO_NONE;
5014 * If this patch is a call, try emitting a direct call instead of
5015 * through a PLT entry. This is possible if the called method is in
5016 * the same assembly and requires no initialization.
5018 direct_call = FALSE;
5019 external_call = FALSE;
5020 if ((patch_info->type == MONO_PATCH_INFO_METHOD) && (patch_info->data.method->klass->image == acfg->image)) {
5021 if (!got_only && is_direct_callable (acfg, method, patch_info)) {
5022 MonoCompile *callee_cfg = (MonoCompile *)g_hash_table_lookup (acfg->method_to_cfg, patch_info->data.method);
5023 //printf ("DIRECT: %s %s\n", method ? mono_method_full_name (method, TRUE) : "", mono_method_full_name (callee_cfg->method, TRUE));
5025 direct_call_target = callee_cfg->asm_symbol;
5026 patch_info->type = MONO_PATCH_INFO_NONE;
5027 acfg->stats.direct_calls ++;
5030 acfg->stats.all_calls ++;
5031 } else if (patch_info->type == MONO_PATCH_INFO_ICALL_ADDR) {
5032 if (!got_only && is_direct_callable (acfg, method, patch_info)) {
5033 if (!(patch_info->data.method->flags & METHOD_ATTRIBUTE_PINVOKE_IMPL))
5034 direct_pinvoke = mono_lookup_icall_symbol (patch_info->data.method);
5036 direct_pinvoke = get_pinvoke_import (acfg, patch_info->data.method);
5037 if (direct_pinvoke) {
5039 g_assert (strlen (direct_pinvoke) < 1000);
5040 direct_call_target = g_strdup_printf ("%s%s", acfg->user_symbol_prefix, direct_pinvoke);
5043 } else if (patch_info->type == MONO_PATCH_INFO_JIT_ICALL_ADDR) {
5044 const char *sym = mono_lookup_jit_icall_symbol (patch_info->data.name);
5045 if (!got_only && sym && acfg->aot_opts.direct_icalls) {
5046 /* Call to a C function implementing a jit icall */
5048 external_call = TRUE;
5049 g_assert (strlen (sym) < 1000);
5050 direct_call_target = g_strdup_printf ("%s%s", acfg->user_symbol_prefix, sym);
5052 } else if (patch_info->type == MONO_PATCH_INFO_INTERNAL_METHOD) {
5053 MonoJitICallInfo *info = mono_find_jit_icall_by_name (patch_info->data.name);
5054 const char *sym = mono_lookup_jit_icall_symbol (patch_info->data.name);
5055 if (!got_only && sym && acfg->aot_opts.direct_icalls && info->func == info->wrapper) {
5056 /* Call to a jit icall without a wrapper */
5058 external_call = TRUE;
5059 g_assert (strlen (sym) < 1000);
5060 direct_call_target = g_strdup_printf ("%s%s", acfg->user_symbol_prefix, sym);
5065 patch_info->type = MONO_PATCH_INFO_NONE;
5066 acfg->stats.direct_calls ++;
5069 if (!got_only && !direct_call) {
5070 MonoPltEntry *plt_entry = get_plt_entry (acfg, patch_info);
5072 /* This patch has a PLT entry, so we must emit a call to the PLT entry */
5074 direct_call_target = plt_entry->symbol;
5076 /* Nullify the patch */
5077 patch_info->type = MONO_PATCH_INFO_NONE;
5078 plt_entry->jit_used = TRUE;
5085 arch_emit_direct_call (acfg, direct_call_target, external_call, FALSE, patch_info, &call_size);
5086 i += call_size - INST_LEN;
5090 got_slot = get_got_offset (acfg, FALSE, patch_info);
5092 arch_emit_got_access (acfg, acfg->got_symbol, code + i, got_slot, &code_size);
5093 i += code_size - INST_LEN;
5099 #endif /* MONO_ARCH_AOT_SUPPORTED */
5102 /* Find next patch */
5104 for (pindex = start_index; pindex < patches->len; ++pindex) {
5105 patch_info = (MonoJumpInfo *)g_ptr_array_index (patches, pindex);
5106 if (patch_info->ip.i >= i)
5110 /* Try to emit multiple bytes at once */
5111 if (pindex < patches->len && patch_info->ip.i > i) {
5114 for (limit = i + INST_LEN; limit < patch_info->ip.i; limit += INST_LEN) {
5115 if (locs && locs [limit])
5119 emit_code_bytes (acfg, code + i, limit - i);
5120 i = limit - INST_LEN;
5122 emit_code_bytes (acfg, code + i, INST_LEN);
5133 * Return a modified version of S which only includes characters permissible in symbols.
5136 sanitize_symbol (MonoAotCompile *acfg, char *s)
5138 gboolean process = FALSE;
5147 for (i = 0; i < len; ++i)
5148 if (!(s [i] <= 0x7f && (isalnum (s [i]) || s [i] == '_')))
5153 gs = g_string_sized_new (len);
5154 for (i = 0; i < len; ++i) {
5156 if (c <= 0x7f && (isalnum (c) || c == '_')) {
5157 g_string_append_c (gs, c);
5158 } else if (c > 0x7f) {
5159 /* multi-byte utf8 */
5160 g_string_append_printf (gs, "_0x%x", c);
5163 while (c >> 6 == 0x2) {
5164 g_string_append_printf (gs, "%x", c);
5168 g_string_append_printf (gs, "_");
5171 g_string_append_c (gs, '_');
5175 res = mono_mempool_strdup (acfg->mempool, gs->str);
5176 g_string_free (gs, TRUE);
5181 get_debug_sym (MonoMethod *method, const char *prefix, GHashTable *cache)
5183 char *name1, *name2, *cached;
5184 int i, j, len, count;
5185 MonoMethod *cached_method;
5187 name1 = mono_method_full_name (method, TRUE);
5190 // This is so that we don't accidentally create a local symbol (which starts with 'L')
5191 if ((!prefix || !*prefix) && name1 [0] == 'L')
5195 len = strlen (name1);
5196 name2 = (char *)malloc (strlen (prefix) + len + 16);
5197 memcpy (name2, prefix, strlen (prefix));
5198 j = strlen (prefix);
5199 for (i = 0; i < len; ++i) {
5200 if (i == 0 && name1 [0] >= '0' && name1 [0] <= '9') {
5202 } else if (isalnum (name1 [i])) {
5203 name2 [j ++] = name1 [i];
5204 } else if (name1 [i] == ' ' && name1 [i + 1] == '(' && name1 [i + 2] == ')') {
5206 } else if (name1 [i] == ',' && name1 [i + 1] == ' ') {
5209 } else if (name1 [i] == '(' || name1 [i] == ')' || name1 [i] == '>') {
5219 cached_method = (MonoMethod *)g_hash_table_lookup (cache, name2);
5220 if (!(cached_method && cached_method != method))
5222 sprintf (name2 + j, "_%d", count);
5226 cached = g_strdup (name2);
5227 g_hash_table_insert (cache, cached, method);
5233 emit_method_code (MonoAotCompile *acfg, MonoCompile *cfg)
5238 char *debug_sym = NULL;
5239 char *symbol = NULL;
5240 int func_alignment = AOT_FUNC_ALIGNMENT;
5243 method = cfg->orig_method;
5244 code = cfg->native_code;
5246 method_index = get_method_index (acfg, method);
5247 symbol = g_strdup_printf ("%sme_%x", acfg->temp_prefix, method_index);
5249 /* Make the labels local */
5250 emit_section_change (acfg, ".text", 0);
5251 emit_alignment_code (acfg, func_alignment);
5253 if (acfg->global_symbols && acfg->need_no_dead_strip)
5254 fprintf (acfg->fp, " .no_dead_strip %s\n", cfg->asm_symbol);
5256 emit_label (acfg, cfg->asm_symbol);
5258 if (acfg->aot_opts.write_symbols && !acfg->global_symbols && !acfg->llvm) {
5260 * Write a C style symbol for every method, this has two uses:
5261 * - it works on platforms where the dwarf debugging info is not
5263 * - it allows the setting of breakpoints of aot-ed methods.
5265 debug_sym = get_debug_sym (method, "", acfg->method_label_hash);
5266 cfg->asm_debug_symbol = g_strdup (debug_sym);
5268 if (acfg->need_no_dead_strip)
5269 fprintf (acfg->fp, " .no_dead_strip %s\n", debug_sym);
5270 emit_local_symbol (acfg, debug_sym, symbol, TRUE);
5271 emit_label (acfg, debug_sym);
5274 export_name = (char *)g_hash_table_lookup (acfg->export_names, method);
5276 /* Emit a global symbol for the method */
5277 emit_global_inner (acfg, export_name, TRUE);
5278 emit_label (acfg, export_name);
5281 if (cfg->verbose_level > 0)
5282 g_print ("Method %s emitted as %s\n", mono_method_get_full_name (method), cfg->asm_symbol);
5284 acfg->stats.code_size += cfg->code_len;
5286 acfg->cfgs [method_index]->got_offset = acfg->got_offset;
5288 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 ()));
5292 if (acfg->aot_opts.write_symbols) {
5294 emit_symbol_size (acfg, debug_sym, ".");
5296 emit_symbol_size (acfg, cfg->asm_symbol, ".");
5300 emit_label (acfg, symbol);
5307 * Encode PATCH_INFO into its disk representation.
5310 encode_patch (MonoAotCompile *acfg, MonoJumpInfo *patch_info, guint8 *buf, guint8 **endbuf)
5314 switch (patch_info->type) {
5315 case MONO_PATCH_INFO_NONE:
5317 case MONO_PATCH_INFO_IMAGE:
5318 encode_value (get_image_index (acfg, patch_info->data.image), p, &p);
5320 case MONO_PATCH_INFO_MSCORLIB_GOT_ADDR:
5321 case MONO_PATCH_INFO_JIT_TLS_ID:
5322 case MONO_PATCH_INFO_GC_CARD_TABLE_ADDR:
5323 case MONO_PATCH_INFO_GC_NURSERY_START:
5324 case MONO_PATCH_INFO_GC_NURSERY_BITS:
5326 case MONO_PATCH_INFO_CASTCLASS_CACHE:
5327 encode_value (patch_info->data.index, p, &p);
5329 case MONO_PATCH_INFO_METHOD_REL:
5330 encode_value ((gint)patch_info->data.offset, p, &p);
5332 case MONO_PATCH_INFO_SWITCH: {
5333 gpointer *table = (gpointer *)patch_info->data.table->table;
5336 encode_value (patch_info->data.table->table_size, p, &p);
5337 for (k = 0; k < patch_info->data.table->table_size; k++)
5338 encode_value ((int)(gssize)table [k], p, &p);
5341 case MONO_PATCH_INFO_METHODCONST:
5342 case MONO_PATCH_INFO_METHOD:
5343 case MONO_PATCH_INFO_METHOD_JUMP:
5344 case MONO_PATCH_INFO_ICALL_ADDR:
5345 case MONO_PATCH_INFO_METHOD_RGCTX:
5346 case MONO_PATCH_INFO_METHOD_CODE_SLOT:
5347 encode_method_ref (acfg, patch_info->data.method, p, &p);
5349 case MONO_PATCH_INFO_AOT_JIT_INFO:
5350 encode_value (patch_info->data.index, p, &p);
5352 case MONO_PATCH_INFO_INTERNAL_METHOD:
5353 case MONO_PATCH_INFO_JIT_ICALL_ADDR: {
5354 guint32 len = strlen (patch_info->data.name);
5356 encode_value (len, p, &p);
5358 memcpy (p, patch_info->data.name, len);
5363 case MONO_PATCH_INFO_LDSTR: {
5364 guint32 image_index = get_image_index (acfg, patch_info->data.token->image);
5365 guint32 token = patch_info->data.token->token;
5366 g_assert (mono_metadata_token_code (token) == MONO_TOKEN_STRING);
5367 encode_value (image_index, p, &p);
5368 encode_value (patch_info->data.token->token - MONO_TOKEN_STRING, p, &p);
5371 case MONO_PATCH_INFO_RVA:
5372 case MONO_PATCH_INFO_DECLSEC:
5373 case MONO_PATCH_INFO_LDTOKEN:
5374 case MONO_PATCH_INFO_TYPE_FROM_HANDLE:
5375 encode_value (get_image_index (acfg, patch_info->data.token->image), p, &p);
5376 encode_value (patch_info->data.token->token, p, &p);
5377 encode_value (patch_info->data.token->has_context, p, &p);
5378 if (patch_info->data.token->has_context)
5379 encode_generic_context (acfg, &patch_info->data.token->context, p, &p);
5381 case MONO_PATCH_INFO_EXC_NAME: {
5382 MonoClass *ex_class;
5385 mono_class_from_name (mono_defaults.exception_class->image,
5386 "System", (const char *)patch_info->data.target);
5387 g_assert (ex_class);
5388 encode_klass_ref (acfg, ex_class, p, &p);
5391 case MONO_PATCH_INFO_R4:
5392 encode_value (*((guint32 *)patch_info->data.target), p, &p);
5394 case MONO_PATCH_INFO_R8:
5395 encode_value (((guint32 *)patch_info->data.target) [MINI_LS_WORD_IDX], p, &p);
5396 encode_value (((guint32 *)patch_info->data.target) [MINI_MS_WORD_IDX], p, &p);
5398 case MONO_PATCH_INFO_VTABLE:
5399 case MONO_PATCH_INFO_CLASS:
5400 case MONO_PATCH_INFO_IID:
5401 case MONO_PATCH_INFO_ADJUSTED_IID:
5402 encode_klass_ref (acfg, patch_info->data.klass, p, &p);
5404 case MONO_PATCH_INFO_DELEGATE_TRAMPOLINE:
5405 encode_klass_ref (acfg, patch_info->data.del_tramp->klass, p, &p);
5406 if (patch_info->data.del_tramp->method) {
5407 encode_value (1, p, &p);
5408 encode_method_ref (acfg, patch_info->data.del_tramp->method, p, &p);
5410 encode_value (0, p, &p);
5412 encode_value (patch_info->data.del_tramp->is_virtual, p, &p);
5414 case MONO_PATCH_INFO_FIELD:
5415 case MONO_PATCH_INFO_SFLDA:
5416 encode_field_info (acfg, patch_info->data.field, p, &p);
5418 case MONO_PATCH_INFO_INTERRUPTION_REQUEST_FLAG:
5420 case MONO_PATCH_INFO_RGCTX_FETCH:
5421 case MONO_PATCH_INFO_RGCTX_SLOT_INDEX: {
5422 MonoJumpInfoRgctxEntry *entry = patch_info->data.rgctx_entry;
5427 * entry->method has a lenghtly encoding and multiple rgctx_fetch entries
5428 * reference the same method, so encode the method only once.
5430 offset = GPOINTER_TO_UINT (g_hash_table_lookup (acfg->method_blob_hash, entry->method));
5432 buf2 = (guint8 *)g_malloc (1024);
5435 encode_method_ref (acfg, entry->method, p2, &p2);
5436 g_assert (p2 - buf2 < 1024);
5438 offset = add_to_blob (acfg, buf2, p2 - buf2);
5441 g_hash_table_insert (acfg->method_blob_hash, entry->method, GUINT_TO_POINTER (offset + 1));
5446 encode_value (offset, p, &p);
5447 g_assert ((int)entry->info_type < 256);
5448 g_assert (entry->data->type < 256);
5449 encode_value ((entry->in_mrgctx ? 1 : 0) | (entry->info_type << 1) | (entry->data->type << 9), p, &p);
5450 encode_patch (acfg, entry->data, p, &p);
5453 case MONO_PATCH_INFO_SEQ_POINT_INFO:
5454 case MONO_PATCH_INFO_AOT_MODULE:
5456 case MONO_PATCH_INFO_SIGNATURE:
5457 case MONO_PATCH_INFO_GSHAREDVT_IN_WRAPPER:
5458 encode_signature (acfg, (MonoMethodSignature*)patch_info->data.target, p, &p);
5460 case MONO_PATCH_INFO_TLS_OFFSET:
5461 encode_value (GPOINTER_TO_INT (patch_info->data.target), p, &p);
5463 case MONO_PATCH_INFO_GSHAREDVT_CALL:
5464 encode_signature (acfg, (MonoMethodSignature*)patch_info->data.gsharedvt->sig, p, &p);
5465 encode_method_ref (acfg, patch_info->data.gsharedvt->method, p, &p);
5467 case MONO_PATCH_INFO_GSHAREDVT_METHOD: {
5468 MonoGSharedVtMethodInfo *info = patch_info->data.gsharedvt_method;
5471 encode_method_ref (acfg, info->method, p, &p);
5472 encode_value (info->num_entries, p, &p);
5473 for (i = 0; i < info->num_entries; ++i) {
5474 MonoRuntimeGenericContextInfoTemplate *template_ = &info->entries [i];
5476 encode_value (template_->info_type, p, &p);
5477 switch (mini_rgctx_info_type_to_patch_info_type (template_->info_type)) {
5478 case MONO_PATCH_INFO_CLASS:
5479 encode_klass_ref (acfg, mono_class_from_mono_type ((MonoType *)template_->data), p, &p);
5481 case MONO_PATCH_INFO_FIELD:
5482 encode_field_info (acfg, (MonoClassField *)template_->data, p, &p);
5485 g_assert_not_reached ();
5491 case MONO_PATCH_INFO_LDSTR_LIT: {
5492 const char *s = (const char *)patch_info->data.target;
5493 int len = strlen (s);
5495 encode_value (len, p, &p);
5496 memcpy (p, s, len + 1);
5500 case MONO_PATCH_INFO_VIRT_METHOD:
5501 encode_klass_ref (acfg, patch_info->data.virt_method->klass, p, &p);
5502 encode_method_ref (acfg, patch_info->data.virt_method->method, p, &p);
5504 case MONO_PATCH_INFO_GC_SAFE_POINT_FLAG:
5507 g_warning ("unable to handle jump info %d", patch_info->type);
5508 g_assert_not_reached ();
5515 encode_patch_list (MonoAotCompile *acfg, GPtrArray *patches, int n_patches, gboolean llvm, int first_got_offset, guint8 *buf, guint8 **endbuf)
5518 guint32 pindex, offset;
5519 MonoJumpInfo *patch_info;
5521 encode_value (n_patches, p, &p);
5523 for (pindex = 0; pindex < patches->len; ++pindex) {
5524 patch_info = (MonoJumpInfo *)g_ptr_array_index (patches, pindex);
5526 if (patch_info->type == MONO_PATCH_INFO_NONE || patch_info->type == MONO_PATCH_INFO_BB)
5530 offset = get_got_offset (acfg, llvm, patch_info);
5531 encode_value (offset, p, &p);
5538 emit_method_info (MonoAotCompile *acfg, MonoCompile *cfg)
5541 int pindex, buf_size, n_patches;
5543 MonoJumpInfo *patch_info;
5544 guint32 method_index;
5546 guint32 first_got_offset;
5548 method = cfg->orig_method;
5550 method_index = get_method_index (acfg, method);
5552 /* Sort relocations */
5553 patches = g_ptr_array_new ();
5554 for (patch_info = cfg->patch_info; patch_info; patch_info = patch_info->next)
5555 g_ptr_array_add (patches, patch_info);
5556 g_ptr_array_sort (patches, compare_patches);
5558 first_got_offset = acfg->cfgs [method_index]->got_offset;
5560 /**********************/
5561 /* Encode method info */
5562 /**********************/
5564 buf_size = (patches->len < 1000) ? 40960 : 40960 + (patches->len * 64);
5565 p = buf = (guint8 *)g_malloc (buf_size);
5567 if (mono_class_get_cctor (method->klass))
5568 encode_klass_ref (acfg, method->klass, p, &p);
5570 /* Not needed when loading the method */
5571 encode_value (0, p, &p);
5573 g_assert (!(cfg->opt & MONO_OPT_SHARED));
5576 for (pindex = 0; pindex < patches->len; ++pindex) {
5577 patch_info = (MonoJumpInfo *)g_ptr_array_index (patches, pindex);
5579 if ((patch_info->type == MONO_PATCH_INFO_GOT_OFFSET) ||
5580 (patch_info->type == MONO_PATCH_INFO_NONE)) {
5581 patch_info->type = MONO_PATCH_INFO_NONE;
5586 if ((patch_info->type == MONO_PATCH_INFO_IMAGE) && (patch_info->data.image == acfg->image)) {
5587 /* Stored in a GOT slot initialized at module load time */
5588 patch_info->type = MONO_PATCH_INFO_NONE;
5592 if (patch_info->type == MONO_PATCH_INFO_GC_CARD_TABLE_ADDR ||
5593 patch_info->type == MONO_PATCH_INFO_GC_NURSERY_START ||
5594 patch_info->type == MONO_PATCH_INFO_GC_NURSERY_BITS ||
5595 patch_info->type == MONO_PATCH_INFO_AOT_MODULE) {
5596 /* Stored in a GOT slot initialized at module load time */
5597 patch_info->type = MONO_PATCH_INFO_NONE;
5601 if (is_plt_patch (patch_info) && !(cfg->compile_llvm && acfg->aot_opts.llvm_only)) {
5602 /* Calls are made through the PLT */
5603 patch_info->type = MONO_PATCH_INFO_NONE;
5611 g_assert (cfg->has_got_slots);
5613 encode_patch_list (acfg, patches, n_patches, cfg->compile_llvm, first_got_offset, p, &p);
5615 acfg->stats.info_size += p - buf;
5617 g_assert (p - buf < buf_size);
5619 cfg->method_info_offset = add_to_blob (acfg, buf, p - buf);
5624 get_unwind_info_offset (MonoAotCompile *acfg, guint8 *encoded, guint32 encoded_len)
5626 guint32 cache_index;
5629 /* Reuse the unwind module to canonize and store unwind info entries */
5630 cache_index = mono_cache_unwind_info (encoded, encoded_len);
5632 /* Use +/- 1 to distinguish 0s from missing entries */
5633 offset = GPOINTER_TO_UINT (g_hash_table_lookup (acfg->unwind_info_offsets, GUINT_TO_POINTER (cache_index + 1)));
5641 * It would be easier to use assembler symbols, but the caller needs an
5644 offset = acfg->unwind_info_offset;
5645 g_hash_table_insert (acfg->unwind_info_offsets, GUINT_TO_POINTER (cache_index + 1), GUINT_TO_POINTER (offset + 1));
5646 g_ptr_array_add (acfg->unwind_ops, GUINT_TO_POINTER (cache_index));
5649 encode_value (encoded_len, p, &p);
5651 acfg->unwind_info_offset += encoded_len + (p - buf);
5657 emit_exception_debug_info (MonoAotCompile *acfg, MonoCompile *cfg, gboolean store_seq_points)
5660 guint32 debug_info_size, seq_points_size;
5662 MonoMethodHeader *header;
5663 guint8 *p, *buf, *debug_info;
5664 MonoJitInfo *jinfo = cfg->jit_info;
5666 gboolean use_unwind_ops = FALSE;
5667 MonoSeqPointInfo *seq_points;
5669 code = cfg->native_code;
5670 header = cfg->header;
5672 if (!acfg->aot_opts.nodebug) {
5673 mono_debug_serialize_debug_info (cfg, &debug_info, &debug_info_size);
5676 debug_info_size = 0;
5679 seq_points = cfg->seq_point_info;
5680 seq_points_size = (store_seq_points)? mono_seq_point_info_get_write_size (seq_points) : 0;
5682 buf_size = header->num_clauses * 256 + debug_info_size + 2048 + seq_points_size + cfg->gc_map_size;
5684 p = buf = (guint8 *)g_malloc (buf_size);
5686 use_unwind_ops = cfg->unwind_ops != NULL;
5688 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);
5690 encode_value (flags, p, &p);
5692 if (use_unwind_ops) {
5693 guint32 encoded_len;
5695 guint32 unwind_desc;
5697 encoded = mono_unwind_ops_encode (cfg->unwind_ops, &encoded_len);
5699 unwind_desc = get_unwind_info_offset (acfg, encoded, encoded_len);
5700 encode_value (unwind_desc, p, &p);
5702 encode_value (jinfo->unwind_info, p, &p);
5705 /*Encode the number of holes before the number of clauses to make decoding easier*/
5706 if (jinfo->has_try_block_holes) {
5707 MonoTryBlockHoleTableJitInfo *table = mono_jit_info_get_try_block_hole_table_info (jinfo);
5708 encode_value (table->num_holes, p, &p);
5711 if (jinfo->has_arch_eh_info) {
5713 * In AOT mode, the code length is calculated from the address of the previous method,
5714 * which could include alignment padding, so calculating the start of the epilog as
5715 * code_len - epilog_size is correct any more. Save the real code len as a workaround.
5717 encode_value (jinfo->code_size, p, &p);
5720 /* Exception table */
5721 if (cfg->compile_llvm) {
5723 * When using LLVM, we can't emit some data, like pc offsets, this reg/offset etc.,
5724 * since the information is only available to llc. Instead, we let llc save the data
5725 * into the LSDA, and read it from there at runtime.
5727 /* The assembly might be CIL stripped so emit the data ourselves */
5728 if (header->num_clauses)
5729 encode_value (header->num_clauses, p, &p);
5731 for (k = 0; k < header->num_clauses; ++k) {
5732 MonoExceptionClause *clause;
5734 clause = &header->clauses [k];
5736 encode_value (clause->flags, p, &p);
5737 if (clause->data.catch_class) {
5738 encode_value (1, p, &p);
5739 encode_klass_ref (acfg, clause->data.catch_class, p, &p);
5741 encode_value (0, p, &p);
5744 /* Emit the IL ranges too, since they might not be available at runtime */
5745 encode_value (clause->try_offset, p, &p);
5746 encode_value (clause->try_len, p, &p);
5747 encode_value (clause->handler_offset, p, &p);
5748 encode_value (clause->handler_len, p, &p);
5750 /* Emit a list of nesting clauses */
5751 for (i = 0; i < header->num_clauses; ++i) {
5753 MonoExceptionClause *clause1 = &header->clauses [cindex1];
5755 MonoExceptionClause *clause2 = &header->clauses [cindex2];
5757 if (cindex1 != cindex2 && clause1->try_offset >= clause2->try_offset && clause1->handler_offset <= clause2->handler_offset)
5758 encode_value (i, p, &p);
5760 encode_value (-1, p, &p);
5763 if (jinfo->num_clauses)
5764 encode_value (jinfo->num_clauses, p, &p);
5766 for (k = 0; k < jinfo->num_clauses; ++k) {
5767 MonoJitExceptionInfo *ei = &jinfo->clauses [k];
5769 encode_value (ei->flags, p, &p);
5770 #ifdef MONO_CONTEXT_SET_LLVM_EXC_REG
5771 /* Not used for catch clauses */
5772 if (ei->flags != MONO_EXCEPTION_CLAUSE_NONE)
5773 encode_value (ei->exvar_offset, p, &p);
5775 encode_value (ei->exvar_offset, p, &p);
5778 if (ei->flags == MONO_EXCEPTION_CLAUSE_FILTER || ei->flags == MONO_EXCEPTION_CLAUSE_FINALLY)
5779 encode_value ((gint)((guint8*)ei->data.filter - code), p, &p);
5781 if (ei->data.catch_class) {
5785 buf2 = (guint8 *)g_malloc (4096);
5787 encode_klass_ref (acfg, ei->data.catch_class, p2, &p2);
5789 g_assert (len < 4096);
5790 encode_value (len, p, &p);
5791 memcpy (p, buf2, len);
5795 encode_value (0, p, &p);
5799 encode_value ((gint)((guint8*)ei->try_start - code), p, &p);
5800 encode_value ((gint)((guint8*)ei->try_end - code), p, &p);
5801 encode_value ((gint)((guint8*)ei->handler_start - code), p, &p);
5805 if (jinfo->has_try_block_holes) {
5806 MonoTryBlockHoleTableJitInfo *table = mono_jit_info_get_try_block_hole_table_info (jinfo);
5807 for (i = 0; i < table->num_holes; ++i) {
5808 MonoTryBlockHoleJitInfo *hole = &table->holes [i];
5809 encode_value (hole->clause, p, &p);
5810 encode_value (hole->length, p, &p);
5811 encode_value (hole->offset, p, &p);
5815 if (jinfo->has_arch_eh_info) {
5816 MonoArchEHJitInfo *eh_info;
5818 eh_info = mono_jit_info_get_arch_eh_info (jinfo);
5819 encode_value (eh_info->stack_size, p, &p);
5820 encode_value (eh_info->epilog_size, p, &p);
5823 if (jinfo->has_generic_jit_info) {
5824 MonoGenericJitInfo *gi = mono_jit_info_get_generic_jit_info (jinfo);
5825 MonoGenericSharingContext* gsctx = gi->generic_sharing_context;
5829 encode_value (gi->nlocs, p, &p);
5831 for (i = 0; i < gi->nlocs; ++i) {
5832 MonoDwarfLocListEntry *entry = &gi->locations [i];
5834 encode_value (entry->is_reg ? 1 : 0, p, &p);
5835 encode_value (entry->reg, p, &p);
5837 encode_value (entry->offset, p, &p);
5839 g_assert (entry->from == 0);
5841 encode_value (entry->from, p, &p);
5842 encode_value (entry->to, p, &p);
5845 if (!cfg->compile_llvm) {
5846 encode_value (gi->has_this ? 1 : 0, p, &p);
5847 encode_value (gi->this_reg, p, &p);
5848 encode_value (gi->this_offset, p, &p);
5853 * Need to encode jinfo->method too, since it is not equal to 'method'
5854 * when using generic sharing.
5856 buf2 = (guint8 *)g_malloc (4096);
5858 encode_method_ref (acfg, jinfo->d.method, p2, &p2);
5860 g_assert (len < 4096);
5861 encode_value (len, p, &p);
5862 memcpy (p, buf2, len);
5866 if (gsctx && gsctx->is_gsharedvt) {
5867 encode_value (1, p, &p);
5869 encode_value (0, p, &p);
5873 if (seq_points_size)
5874 p += mono_seq_point_info_write (seq_points, p);
5876 g_assert (debug_info_size < buf_size);
5878 encode_value (debug_info_size, p, &p);
5879 if (debug_info_size) {
5880 memcpy (p, debug_info, debug_info_size);
5881 p += debug_info_size;
5882 g_free (debug_info);
5887 encode_value (cfg->gc_map_size, p, &p);
5888 /* The GC map requires 4 bytes of alignment */
5889 while ((gsize)p % 4)
5891 memcpy (p, cfg->gc_map, cfg->gc_map_size);
5892 p += cfg->gc_map_size;
5895 acfg->stats.ex_info_size += p - buf;
5897 g_assert (p - buf < buf_size);
5900 /* The GC Map requires 4 byte alignment */
5901 cfg->ex_info_offset = add_to_blob_aligned (acfg, buf, p - buf, cfg->gc_map ? 4 : 1);
5906 emit_klass_info (MonoAotCompile *acfg, guint32 token)
5909 MonoClass *klass = mono_class_get_checked (acfg->image, token, &error);
5911 int i, buf_size, res;
5912 gboolean no_special_static, cant_encode;
5913 gpointer iter = NULL;
5916 mono_error_cleanup (&error);
5920 p = buf = (guint8 *)g_malloc (buf_size);
5922 /* Mark as unusable */
5923 encode_value (-1, p, &p);
5925 res = add_to_blob (acfg, buf, p - buf);
5931 buf_size = 10240 + (klass->vtable_size * 16);
5932 p = buf = (guint8 *)g_malloc (buf_size);
5936 mono_class_init (klass);
5938 mono_class_get_nested_types (klass, &iter);
5939 g_assert (klass->nested_classes_inited);
5941 mono_class_setup_vtable (klass);
5944 * Emit all the information which is required for creating vtables so
5945 * the runtime does not need to create the MonoMethod structures which
5946 * take up a lot of space.
5949 no_special_static = !mono_class_has_special_static_fields (klass);
5951 /* Check whenever we have enough info to encode the vtable */
5952 cant_encode = FALSE;
5953 for (i = 0; i < klass->vtable_size; ++i) {
5954 MonoMethod *cm = klass->vtable [i];
5956 if (cm && mono_method_signature (cm)->is_inflated && !g_hash_table_lookup (acfg->token_info_hash, cm))
5960 mono_class_has_finalizer (klass);
5962 if (klass->generic_container || cant_encode) {
5963 encode_value (-1, p, &p);
5965 encode_value (klass->vtable_size, p, &p);
5966 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);
5967 if (klass->has_cctor)
5968 encode_method_ref (acfg, mono_class_get_cctor (klass), p, &p);
5969 if (klass->has_finalize)
5970 encode_method_ref (acfg, mono_class_get_finalizer (klass), p, &p);
5972 encode_value (klass->instance_size, p, &p);
5973 encode_value (mono_class_data_size (klass), p, &p);
5974 encode_value (klass->packing_size, p, &p);
5975 encode_value (klass->min_align, p, &p);
5977 for (i = 0; i < klass->vtable_size; ++i) {
5978 MonoMethod *cm = klass->vtable [i];
5981 encode_method_ref (acfg, cm, p, &p);
5983 encode_value (0, p, &p);
5987 acfg->stats.class_info_size += p - buf;
5989 g_assert (p - buf < buf_size);
5990 res = add_to_blob (acfg, buf, p - buf);
5997 get_plt_entry_debug_sym (MonoAotCompile *acfg, MonoJumpInfo *ji, GHashTable *cache)
5999 char *debug_sym = NULL;
6002 if (acfg->llvm && llvm_acfg->aot_opts.static_link) {
6003 /* Need to add a prefix to create unique symbols */
6004 prefix = g_strdup_printf ("plt_%s_", acfg->assembly_name_sym);
6006 prefix = g_strdup ("plt_");
6010 case MONO_PATCH_INFO_METHOD:
6011 debug_sym = get_debug_sym (ji->data.method, prefix, cache);
6013 case MONO_PATCH_INFO_INTERNAL_METHOD:
6014 debug_sym = g_strdup_printf ("%s_jit_icall_%s", prefix, ji->data.name);
6016 case MONO_PATCH_INFO_RGCTX_FETCH:
6017 debug_sym = g_strdup_printf ("%s_rgctx_fetch_%d", prefix, acfg->label_generator ++);
6019 case MONO_PATCH_INFO_ICALL_ADDR: {
6020 char *s = get_debug_sym (ji->data.method, "", cache);
6022 debug_sym = g_strdup_printf ("%s_icall_native_%s", prefix, s);
6026 case MONO_PATCH_INFO_JIT_ICALL_ADDR:
6027 debug_sym = g_strdup_printf ("%s_jit_icall_native_%s", prefix, ji->data.name);
6035 return sanitize_symbol (acfg, debug_sym);
6039 * Calls made from AOTed code are routed through a table of jumps similar to the
6040 * ELF PLT (Program Linkage Table). Initially the PLT entries jump to code which transfers
6041 * control to the AOT runtime through a trampoline.
6044 emit_plt (MonoAotCompile *acfg)
6048 if (acfg->aot_opts.llvm_only) {
6049 g_assert (acfg->plt_offset == 1);
6055 emit_section_change (acfg, ".text", 0);
6056 emit_alignment_code (acfg, NACL_SIZE(16, kNaClAlignment));
6057 emit_info_symbol (acfg, "plt");
6058 emit_label (acfg, acfg->plt_symbol);
6060 for (i = 0; i < acfg->plt_offset; ++i) {
6061 char *debug_sym = NULL;
6062 MonoPltEntry *plt_entry = NULL;
6066 * The first plt entry is unused.
6070 plt_entry = (MonoPltEntry *)g_hash_table_lookup (acfg->plt_offset_to_entry, GUINT_TO_POINTER (i));
6072 debug_sym = plt_entry->debug_sym;
6074 if (acfg->thumb_mixed && !plt_entry->jit_used)
6075 /* Emit only a thumb version */
6078 /* Skip plt entries not actually called */
6079 if (!plt_entry->jit_used && !plt_entry->llvm_used)
6082 if (acfg->llvm && !acfg->thumb_mixed) {
6083 emit_label (acfg, plt_entry->llvm_symbol);
6085 emit_global_inner (acfg, plt_entry->llvm_symbol, TRUE);
6086 #if defined(TARGET_MACH)
6087 fprintf (acfg->fp, ".private_extern %s\n", plt_entry->llvm_symbol);
6093 if (acfg->need_no_dead_strip) {
6094 emit_unset_mode (acfg);
6095 fprintf (acfg->fp, " .no_dead_strip %s\n", debug_sym);
6097 emit_local_symbol (acfg, debug_sym, NULL, TRUE);
6098 emit_label (acfg, debug_sym);
6101 emit_label (acfg, plt_entry->symbol);
6103 arch_emit_plt_entry (acfg, acfg->got_symbol, (acfg->plt_got_offset_base + i) * sizeof (gpointer), acfg->plt_got_info_offsets [i]);
6106 emit_symbol_size (acfg, debug_sym, ".");
6109 if (acfg->thumb_mixed) {
6110 /* Make sure the ARM symbols don't alias the thumb ones */
6111 emit_zero_bytes (acfg, 16);
6114 * Emit a separate set of PLT entries using thumb2 which is called by LLVM generated
6117 for (i = 0; i < acfg->plt_offset; ++i) {
6118 char *debug_sym = NULL;
6119 MonoPltEntry *plt_entry = NULL;
6124 plt_entry = (MonoPltEntry *)g_hash_table_lookup (acfg->plt_offset_to_entry, GUINT_TO_POINTER (i));
6126 /* Skip plt entries not actually called by LLVM code */
6127 if (!plt_entry->llvm_used)
6130 if (acfg->aot_opts.write_symbols) {
6131 if (plt_entry->debug_sym)
6132 debug_sym = g_strdup_printf ("%s_thumb", plt_entry->debug_sym);
6136 #if defined(TARGET_MACH)
6137 fprintf (acfg->fp, " .thumb_func %s\n", debug_sym);
6138 fprintf (acfg->fp, " .no_dead_strip %s\n", debug_sym);
6140 emit_local_symbol (acfg, debug_sym, NULL, TRUE);
6141 emit_label (acfg, debug_sym);
6143 fprintf (acfg->fp, "\n.thumb_func\n");
6145 emit_label (acfg, plt_entry->llvm_symbol);
6148 emit_global_inner (acfg, plt_entry->llvm_symbol, TRUE);
6150 arch_emit_llvm_plt_entry (acfg, acfg->got_symbol, (acfg->plt_got_offset_base + i) * sizeof (gpointer), acfg->plt_got_info_offsets [i]);
6153 emit_symbol_size (acfg, debug_sym, ".");
6159 emit_symbol_size (acfg, acfg->plt_symbol, ".");
6161 emit_info_symbol (acfg, "plt_end");
6165 * emit_trampoline_full:
6167 * If EMIT_TINFO is TRUE, emit additional information which can be used to create a MonoJitInfo for this trampoline by
6168 * create_jit_info_for_trampoline ().
6170 static G_GNUC_UNUSED void
6171 emit_trampoline_full (MonoAotCompile *acfg, int got_offset, MonoTrampInfo *info, gboolean emit_tinfo)
6173 char start_symbol [256];
6174 char end_symbol [256];
6176 guint32 buf_size, info_offset;
6177 MonoJumpInfo *patch_info;
6190 code_size = info->code_size;
6192 unwind_ops = info->unwind_ops;
6194 #ifdef __native_client_codegen__
6195 mono_nacl_fix_patches (code, ji);
6200 sprintf (start_symbol, "%s%s", acfg->user_symbol_prefix, name);
6202 emit_section_change (acfg, ".text", 0);
6203 emit_global (acfg, start_symbol, TRUE);
6204 emit_alignment_code (acfg, AOT_FUNC_ALIGNMENT);
6205 emit_label (acfg, start_symbol);
6207 sprintf (symbol, "%snamed_%s", acfg->temp_prefix, name);
6208 emit_label (acfg, symbol);
6211 * The code should access everything through the GOT, so we pass
6214 emit_and_reloc_code (acfg, NULL, code, code_size, ji, TRUE, NULL);
6216 emit_symbol_size (acfg, start_symbol, ".");
6219 sprintf (end_symbol, "%snamede_%s", acfg->temp_prefix, name);
6220 emit_label (acfg, end_symbol);
6225 /* Sort relocations */
6226 patches = g_ptr_array_new ();
6227 for (patch_info = ji; patch_info; patch_info = patch_info->next)
6228 if (patch_info->type != MONO_PATCH_INFO_NONE)
6229 g_ptr_array_add (patches, patch_info);
6230 g_ptr_array_sort (patches, compare_patches);
6232 buf_size = patches->len * 128 + 128;
6233 buf = (guint8 *)g_malloc (buf_size);
6236 encode_patch_list (acfg, patches, patches->len, FALSE, got_offset, p, &p);
6237 g_assert (p - buf < buf_size);
6239 sprintf (symbol, "%s%s_p", acfg->user_symbol_prefix, name);
6241 info_offset = add_to_blob (acfg, buf, p - buf);
6243 emit_section_change (acfg, RODATA_SECT, 0);
6244 emit_global (acfg, symbol, FALSE);
6245 emit_label (acfg, symbol);
6247 emit_int32 (acfg, info_offset);
6251 guint32 encoded_len;
6255 * Emit additional information which can be used to reconstruct a partial MonoTrampInfo.
6257 encoded = mono_unwind_ops_encode (info->unwind_ops, &encoded_len);
6258 uw_offset = get_unwind_info_offset (acfg, encoded, encoded_len);
6261 emit_symbol_diff (acfg, end_symbol, start_symbol, 0);
6262 emit_int32 (acfg, uw_offset);
6265 /* Emit debug info */
6269 sprintf (symbol, "%s", name);
6270 sprintf (symbol2, "%snamed_%s", acfg->temp_prefix, name);
6273 mono_dwarf_writer_emit_trampoline (acfg->dwarf, symbol, symbol2, NULL, NULL, code_size, unwind_ops);
6277 static G_GNUC_UNUSED void
6278 emit_trampoline (MonoAotCompile *acfg, int got_offset, MonoTrampInfo *info)
6280 emit_trampoline_full (acfg, got_offset, info, TRUE);
6284 emit_trampolines (MonoAotCompile *acfg)
6287 char end_symbol [256];
6288 int i, tramp_got_offset;
6290 #ifdef MONO_ARCH_HAVE_FULL_AOT_TRAMPOLINES
6294 if (!mono_aot_mode_is_full (&acfg->aot_opts) || acfg->aot_opts.llvm_only)
6297 g_assert (acfg->image->assembly);
6299 /* Currently, we emit most trampolines into the mscorlib AOT image. */
6300 if (strcmp (acfg->image->assembly->aname.name, "mscorlib") == 0) {
6301 #ifdef MONO_ARCH_HAVE_FULL_AOT_TRAMPOLINES
6302 MonoTrampInfo *info;
6305 * Emit the generic trampolines.
6307 * We could save some code by treating the generic trampolines as a wrapper
6308 * method, but that approach has its own complexities, so we choose the simpler
6311 for (tramp_type = 0; tramp_type < MONO_TRAMPOLINE_NUM; ++tramp_type) {
6312 /* we overload the boolean here to indicate the slightly different trampoline needed, see mono_arch_create_generic_trampoline() */
6313 #ifdef DISABLE_REMOTING
6314 if (tramp_type == MONO_TRAMPOLINE_GENERIC_VIRTUAL_REMOTING)
6317 #ifndef MONO_ARCH_HAVE_HANDLER_BLOCK_GUARD
6318 if (tramp_type == MONO_TRAMPOLINE_HANDLER_BLOCK_GUARD)
6321 mono_arch_create_generic_trampoline ((MonoTrampolineType)tramp_type, &info, acfg->aot_opts.use_trampolines_page? 2: TRUE);
6322 emit_trampoline (acfg, acfg->got_offset, info);
6325 /* Emit the exception related code pieces */
6326 mono_arch_get_restore_context (&info, TRUE);
6327 emit_trampoline (acfg, acfg->got_offset, info);
6328 mono_arch_get_call_filter (&info, TRUE);
6329 emit_trampoline (acfg, acfg->got_offset, info);
6330 mono_arch_get_throw_exception (&info, TRUE);
6331 emit_trampoline (acfg, acfg->got_offset, info);
6332 mono_arch_get_rethrow_exception (&info, TRUE);
6333 emit_trampoline (acfg, acfg->got_offset, info);
6334 mono_arch_get_throw_corlib_exception (&info, TRUE);
6335 emit_trampoline (acfg, acfg->got_offset, info);
6337 #ifdef MONO_ARCH_HAVE_SDB_TRAMPOLINES
6338 mono_arch_create_sdb_trampoline (TRUE, &info, TRUE);
6339 emit_trampoline (acfg, acfg->got_offset, info);
6340 mono_arch_create_sdb_trampoline (FALSE, &info, TRUE);
6341 emit_trampoline (acfg, acfg->got_offset, info);
6344 #ifdef MONO_ARCH_GSHAREDVT_SUPPORTED
6345 mono_arch_get_gsharedvt_trampoline (&info, TRUE);
6347 emit_trampoline_full (acfg, acfg->got_offset, info, TRUE);
6349 /* Create a separate out trampoline for more information in stack traces */
6350 info->name = g_strdup ("gsharedvt_out_trampoline");
6351 emit_trampoline_full (acfg, acfg->got_offset, info, TRUE);
6355 #if defined(MONO_ARCH_HAVE_GET_TRAMPOLINES)
6357 GSList *l = mono_arch_get_trampolines (TRUE);
6360 MonoTrampInfo *info = (MonoTrampInfo *)l->data;
6362 emit_trampoline (acfg, acfg->got_offset, info);
6368 for (i = 0; i < acfg->aot_opts.nrgctx_fetch_trampolines; ++i) {
6371 offset = MONO_RGCTX_SLOT_MAKE_RGCTX (i);
6372 mono_arch_create_rgctx_lazy_fetch_trampoline (offset, &info, TRUE);
6373 emit_trampoline (acfg, acfg->got_offset, info);
6375 offset = MONO_RGCTX_SLOT_MAKE_MRGCTX (i);
6376 mono_arch_create_rgctx_lazy_fetch_trampoline (offset, &info, TRUE);
6377 emit_trampoline (acfg, acfg->got_offset, info);
6380 #ifdef MONO_ARCH_HAVE_GENERAL_RGCTX_LAZY_FETCH_TRAMPOLINE
6381 mono_arch_create_general_rgctx_lazy_fetch_trampoline (&info, TRUE);
6382 emit_trampoline (acfg, acfg->got_offset, info);
6388 /* delegate_invoke_impl trampolines */
6389 l = mono_arch_get_delegate_invoke_impls ();
6391 MonoTrampInfo *info = (MonoTrampInfo *)l->data;
6393 emit_trampoline (acfg, acfg->got_offset, info);
6398 #endif /* #ifdef MONO_ARCH_HAVE_FULL_AOT_TRAMPOLINES */
6400 /* Emit trampolines which are numerous */
6403 * These include the following:
6404 * - specific trampolines
6405 * - static rgctx invoke trampolines
6407 * These trampolines have the same code, they are parameterized by GOT
6409 * They are defined in this file, in the arch_... routines instead of
6410 * in tramp-<ARCH>.c, since it is easier to do it this way.
6414 * When running in aot-only mode, we can't create specific trampolines at
6415 * runtime, so we create a few, and save them in the AOT file.
6416 * Normal trampolines embed their argument as a literal inside the
6417 * trampoline code, we can't do that here, so instead we embed an offset
6418 * which needs to be added to the trampoline address to get the address of
6419 * the GOT slot which contains the argument value.
6420 * The generated trampolines jump to the generic trampolines using another
6421 * GOT slot, which will be setup by the AOT loader to point to the
6422 * generic trampoline code of the given type.
6426 * FIXME: Maybe we should use more specific trampolines (i.e. one class init for
6430 emit_section_change (acfg, ".text", 0);
6432 tramp_got_offset = acfg->got_offset;
6434 for (ntype = 0; ntype < MONO_AOT_TRAMP_NUM; ++ntype) {
6436 case MONO_AOT_TRAMP_SPECIFIC:
6437 sprintf (symbol, "specific_trampolines");
6439 case MONO_AOT_TRAMP_STATIC_RGCTX:
6440 sprintf (symbol, "static_rgctx_trampolines");
6442 case MONO_AOT_TRAMP_IMT_THUNK:
6443 sprintf (symbol, "imt_thunks");
6445 case MONO_AOT_TRAMP_GSHAREDVT_ARG:
6446 sprintf (symbol, "gsharedvt_arg_trampolines");
6449 g_assert_not_reached ();
6452 sprintf (end_symbol, "%s_e", symbol);
6454 if (acfg->aot_opts.write_symbols)
6455 emit_local_symbol (acfg, symbol, end_symbol, TRUE);
6457 emit_alignment_code (acfg, AOT_FUNC_ALIGNMENT);
6458 emit_info_symbol (acfg, symbol);
6460 acfg->trampoline_got_offset_base [ntype] = tramp_got_offset;
6462 for (i = 0; i < acfg->num_trampolines [ntype]; ++i) {
6466 case MONO_AOT_TRAMP_SPECIFIC:
6467 arch_emit_specific_trampoline (acfg, tramp_got_offset, &tramp_size);
6468 tramp_got_offset += 2;
6470 case MONO_AOT_TRAMP_STATIC_RGCTX:
6471 arch_emit_static_rgctx_trampoline (acfg, tramp_got_offset, &tramp_size);
6472 tramp_got_offset += 2;
6474 case MONO_AOT_TRAMP_IMT_THUNK:
6475 arch_emit_imt_thunk (acfg, tramp_got_offset, &tramp_size);
6476 tramp_got_offset += 1;
6478 case MONO_AOT_TRAMP_GSHAREDVT_ARG:
6479 arch_emit_gsharedvt_arg_trampoline (acfg, tramp_got_offset, &tramp_size);
6480 tramp_got_offset += 2;
6483 g_assert_not_reached ();
6485 #ifdef __native_client_codegen__
6486 /* align to avoid 32-byte boundary crossings */
6487 emit_alignment (acfg, AOT_FUNC_ALIGNMENT);
6490 if (!acfg->trampoline_size [ntype]) {
6491 g_assert (tramp_size);
6492 acfg->trampoline_size [ntype] = tramp_size;
6496 emit_label (acfg, end_symbol);
6497 emit_int32 (acfg, 0);
6500 arch_emit_specific_trampoline_pages (acfg);
6502 /* Reserve some entries at the end of the GOT for our use */
6503 acfg->num_trampoline_got_entries = tramp_got_offset - acfg->got_offset;
6506 acfg->got_offset += acfg->num_trampoline_got_entries;
6510 str_begins_with (const char *str1, const char *str2)
6512 int len = strlen (str2);
6513 return strncmp (str1, str2, len) == 0;
6517 mono_aot_readonly_field_override (MonoClassField *field)
6520 for (rdv = readonly_values; rdv; rdv = rdv->next) {
6521 char *p = rdv->name;
6523 len = strlen (field->parent->name_space);
6524 if (strncmp (p, field->parent->name_space, len))
6529 len = strlen (field->parent->name);
6530 if (strncmp (p, field->parent->name, len))
6535 if (strcmp (p, field->name))
6537 switch (rdv->type) {
6539 return &rdv->value.i1;
6541 return &rdv->value.i2;
6543 return &rdv->value.i4;
6552 add_readonly_value (MonoAotOptions *opts, const char *val)
6557 /* the format of val is:
6558 * namespace.typename.fieldname=type/value
6559 * type can be i1 for uint8/int8/boolean, i2 for uint16/int16/char, i4 for uint32/int32
6561 fval = strrchr (val, '/');
6563 fprintf (stderr, "AOT : invalid format for readonly field '%s', missing /.\n", val);
6566 tval = strrchr (val, '=');
6568 fprintf (stderr, "AOT : invalid format for readonly field '%s', missing =.\n", val);
6571 rdv = g_new0 (ReadOnlyValue, 1);
6572 rdv->name = (char *)g_malloc0 (tval - val + 1);
6573 memcpy (rdv->name, val, tval - val);
6576 if (strncmp (tval, "i1", 2) == 0) {
6577 rdv->value.i1 = atoi (fval);
6578 rdv->type = MONO_TYPE_I1;
6579 } else if (strncmp (tval, "i2", 2) == 0) {
6580 rdv->value.i2 = atoi (fval);
6581 rdv->type = MONO_TYPE_I2;
6582 } else if (strncmp (tval, "i4", 2) == 0) {
6583 rdv->value.i4 = atoi (fval);
6584 rdv->type = MONO_TYPE_I4;
6586 fprintf (stderr, "AOT : unsupported type for readonly field '%s'.\n", tval);
6589 rdv->next = readonly_values;
6590 readonly_values = rdv;
6594 clean_path (gchar * path)
6599 if (g_str_has_suffix (path, G_DIR_SEPARATOR_S))
6602 gchar *clean = g_strconcat (path, G_DIR_SEPARATOR_S, NULL);
6609 wrap_path (gchar * path)
6615 // If the string contains no spaces, just return the original string.
6616 if (strstr (path, " ") == NULL)
6619 // If the string is already wrapped in quotes, return it.
6620 len = strlen (path);
6621 if (len >= 2 && path[0] == '\"' && path[len-1] == '\"')
6624 // If the string contains spaces, then wrap it in quotes.
6625 gchar *clean = g_strdup_printf ("\"%s\"", path);
6631 mono_aot_split_options (const char *aot_options)
6633 enum MonoAotOptionState {
6634 MONO_AOT_OPTION_STATE_DEFAULT,
6635 MONO_AOT_OPTION_STATE_STRING,
6636 MONO_AOT_OPTION_STATE_ESCAPE,
6639 GPtrArray *args = g_ptr_array_new ();
6640 enum MonoAotOptionState state = MONO_AOT_OPTION_STATE_DEFAULT;
6641 gchar const *opt_start = aot_options;
6642 gboolean end_of_string = FALSE;
6645 g_return_val_if_fail (aot_options != NULL, NULL);
6647 while ((cur = *aot_options) != '\0') {
6648 if (state == MONO_AOT_OPTION_STATE_ESCAPE)
6653 // If we find a quote, then if we're in the default case then
6654 // it means we've found the start of a string, if not then it
6655 // means we've found the end of the string and should switch
6656 // back to the default case.
6658 case MONO_AOT_OPTION_STATE_DEFAULT:
6659 state = MONO_AOT_OPTION_STATE_STRING;
6661 case MONO_AOT_OPTION_STATE_STRING:
6662 state = MONO_AOT_OPTION_STATE_DEFAULT;
6664 case MONO_AOT_OPTION_STATE_ESCAPE:
6665 g_assert_not_reached ();
6670 // If we've found an escaping operator, then this means we
6671 // should not process the next character if inside a string.
6672 if (state == MONO_AOT_OPTION_STATE_STRING)
6673 state = MONO_AOT_OPTION_STATE_ESCAPE;
6676 // If we're in the default state then this means we've found
6677 // an option, store it for later processing.
6678 if (state == MONO_AOT_OPTION_STATE_DEFAULT)
6685 // If the next character is end of string, then process the last option.
6686 if (*(aot_options) == '\0') {
6687 end_of_string = TRUE;
6693 g_ptr_array_add (args, g_strndup (opt_start, aot_options - opt_start));
6694 opt_start = ++aot_options;
6704 mono_aot_parse_options (const char *aot_options, MonoAotOptions *opts)
6708 args = mono_aot_split_options (aot_options ? aot_options : "");
6709 for (int i = 0; i < args->len; ++i) {
6710 const char *arg = (const char *)g_ptr_array_index (args, i);
6712 if (str_begins_with (arg, "outfile=")) {
6713 opts->outfile = g_strdup (arg + strlen ("outfile="));
6714 } else if (str_begins_with (arg, "llvm-outfile=")) {
6715 opts->llvm_outfile = g_strdup (arg + strlen ("llvm-outfile="));
6716 } else if (str_begins_with (arg, "temp-path=")) {
6717 opts->temp_path = clean_path (g_strdup (arg + strlen ("temp-path=")));
6718 } else if (str_begins_with (arg, "save-temps")) {
6719 opts->save_temps = TRUE;
6720 } else if (str_begins_with (arg, "keep-temps")) {
6721 opts->save_temps = TRUE;
6722 } else if (str_begins_with (arg, "write-symbols")) {
6723 opts->write_symbols = TRUE;
6724 } else if (str_begins_with (arg, "no-write-symbols")) {
6725 opts->write_symbols = FALSE;
6726 } else if (str_begins_with (arg, "metadata-only")) {
6727 opts->metadata_only = TRUE;
6728 } else if (str_begins_with (arg, "bind-to-runtime-version")) {
6729 opts->bind_to_runtime_version = TRUE;
6730 } else if (str_begins_with (arg, "full")) {
6731 opts->mode = MONO_AOT_MODE_FULL;
6732 } else if (str_begins_with (arg, "hybrid")) {
6733 opts->mode = MONO_AOT_MODE_HYBRID;
6734 } else if (str_begins_with (arg, "threads=")) {
6735 opts->nthreads = atoi (arg + strlen ("threads="));
6736 } else if (str_begins_with (arg, "static")) {
6737 opts->static_link = TRUE;
6738 opts->no_dlsym = TRUE;
6739 } else if (str_begins_with (arg, "asmonly")) {
6740 opts->asm_only = TRUE;
6741 } else if (str_begins_with (arg, "asmwriter")) {
6742 opts->asm_writer = TRUE;
6743 } else if (str_begins_with (arg, "nodebug")) {
6744 opts->nodebug = TRUE;
6745 } else if (str_begins_with (arg, "dwarfdebug")) {
6746 opts->dwarf_debug = TRUE;
6747 } else if (str_begins_with (arg, "nopagetrampolines")) {
6748 opts->use_trampolines_page = FALSE;
6749 } else if (str_begins_with (arg, "ntrampolines=")) {
6750 opts->ntrampolines = atoi (arg + strlen ("ntrampolines="));
6751 } else if (str_begins_with (arg, "nrgctx-trampolines=")) {
6752 opts->nrgctx_trampolines = atoi (arg + strlen ("nrgctx-trampolines="));
6753 } else if (str_begins_with (arg, "nimt-trampolines=")) {
6754 opts->nimt_trampolines = atoi (arg + strlen ("nimt-trampolines="));
6755 } else if (str_begins_with (arg, "ngsharedvt-trampolines=")) {
6756 opts->ngsharedvt_arg_trampolines = atoi (arg + strlen ("ngsharedvt-trampolines="));
6757 } else if (str_begins_with (arg, "tool-prefix=")) {
6758 opts->tool_prefix = g_strdup (arg + strlen ("tool-prefix="));
6759 } else if (str_begins_with (arg, "ld-flags=")) {
6760 opts->ld_flags = g_strdup (arg + strlen ("ld-flags="));
6761 } else if (str_begins_with (arg, "soft-debug")) {
6762 opts->soft_debug = TRUE;
6763 } else if (str_begins_with (arg, "gen-seq-points-file")) {
6764 opts->gen_seq_points_file = TRUE;
6765 } else if (str_begins_with (arg, "direct-pinvoke")) {
6766 opts->direct_pinvoke = TRUE;
6767 } else if (str_begins_with (arg, "direct-icalls")) {
6768 opts->direct_icalls = TRUE;
6769 } else if (str_begins_with (arg, "no-direct-calls")) {
6770 opts->no_direct_calls = TRUE;
6771 } else if (str_begins_with (arg, "print-skipped")) {
6772 opts->print_skipped_methods = TRUE;
6773 } else if (str_begins_with (arg, "stats")) {
6775 } else if (str_begins_with (arg, "no-instances")) {
6776 opts->no_instances = TRUE;
6777 } else if (str_begins_with (arg, "log-generics")) {
6778 opts->log_generics = TRUE;
6779 } else if (str_begins_with (arg, "log-instances=")) {
6780 opts->log_instances = TRUE;
6781 opts->instances_logfile_path = g_strdup (arg + strlen ("log-instances="));
6782 } else if (str_begins_with (arg, "log-instances")) {
6783 opts->log_instances = TRUE;
6784 } else if (str_begins_with (arg, "internal-logfile=")) {
6785 opts->logfile = g_strdup (arg + strlen ("internal-logfile="));
6786 } else if (str_begins_with (arg, "mtriple=")) {
6787 opts->mtriple = g_strdup (arg + strlen ("mtriple="));
6788 } else if (str_begins_with (arg, "llvm-path=")) {
6789 opts->llvm_path = clean_path (g_strdup (arg + strlen ("llvm-path=")));
6790 } else if (!strcmp (arg, "llvm")) {
6792 } else if (str_begins_with (arg, "readonly-value=")) {
6793 add_readonly_value (opts, arg + strlen ("readonly-value="));
6794 } else if (str_begins_with (arg, "info")) {
6795 printf ("AOT target setup: %s.\n", AOT_TARGET_STR);
6797 } else if (str_begins_with (arg, "gc-maps")) {
6798 mini_gc_enable_gc_maps_for_aot ();
6799 } else if (str_begins_with (arg, "dump")) {
6800 opts->dump_json = TRUE;
6801 } else if (str_begins_with (arg, "llvmonly")) {
6802 opts->mode = MONO_AOT_MODE_FULL;
6804 opts->llvm_only = TRUE;
6805 } else if (str_begins_with (arg, "data-outfile=")) {
6806 opts->data_outfile = g_strdup (arg + strlen ("data-outfile="));
6807 } else if (str_begins_with (arg, "help") || str_begins_with (arg, "?")) {
6808 printf ("Supported options for --aot:\n");
6809 printf (" outfile=\n");
6810 printf (" llvm-outfile=\n");
6811 printf (" llvm-path=\n");
6812 printf (" temp-path=\n");
6813 printf (" save-temps\n");
6814 printf (" keep-temps\n");
6815 printf (" write-symbols\n");
6816 printf (" metadata-only\n");
6817 printf (" bind-to-runtime-version\n");
6819 printf (" threads=\n");
6820 printf (" static\n");
6821 printf (" asmonly\n");
6822 printf (" asmwriter\n");
6823 printf (" nodebug\n");
6824 printf (" dwarfdebug\n");
6825 printf (" ntrampolines=\n");
6826 printf (" nrgctx-trampolines=\n");
6827 printf (" nimt-trampolines=\n");
6828 printf (" ngsharedvt-trampolines=\n");
6829 printf (" tool-prefix=\n");
6830 printf (" readonly-value=\n");
6831 printf (" soft-debug\n");
6832 printf (" gen-seq-points-file\n");
6833 printf (" gc-maps\n");
6834 printf (" print-skipped\n");
6835 printf (" no-instances\n");
6836 printf (" stats\n");
6839 printf (" help/?\n");
6842 fprintf (stderr, "AOT : Unknown argument '%s'.\n", arg);
6846 g_free ((gpointer) arg);
6849 if (opts->use_trampolines_page) {
6850 opts->ntrampolines = 0;
6851 opts->nrgctx_trampolines = 0;
6852 opts->nimt_trampolines = 0;
6853 opts->ngsharedvt_arg_trampolines = 0;
6856 g_ptr_array_free (args, /*free_seg=*/TRUE);
6860 add_token_info_hash (gpointer key, gpointer value, gpointer user_data)
6862 MonoMethod *method = (MonoMethod*)key;
6863 MonoJumpInfoToken *ji = (MonoJumpInfoToken*)value;
6864 MonoAotCompile *acfg = (MonoAotCompile *)user_data;
6865 MonoJumpInfoToken *new_ji;
6867 new_ji = (MonoJumpInfoToken *)mono_mempool_alloc0 (acfg->mempool, sizeof (MonoJumpInfoToken));
6868 new_ji->image = ji->image;
6869 new_ji->token = ji->token;
6870 g_hash_table_insert (acfg->token_info_hash, method, new_ji);
6874 can_encode_class (MonoAotCompile *acfg, MonoClass *klass)
6876 if (klass->type_token)
6878 if ((klass->byval_arg.type == MONO_TYPE_VAR) || (klass->byval_arg.type == MONO_TYPE_MVAR) || (klass->byval_arg.type == MONO_TYPE_PTR))
6881 return can_encode_class (acfg, klass->element_class);
6886 can_encode_method (MonoAotCompile *acfg, MonoMethod *method)
6888 if (method->wrapper_type) {
6889 switch (method->wrapper_type) {
6890 case MONO_WRAPPER_NONE:
6891 case MONO_WRAPPER_REMOTING_INVOKE_WITH_CHECK:
6892 case MONO_WRAPPER_XDOMAIN_INVOKE:
6893 case MONO_WRAPPER_STFLD:
6894 case MONO_WRAPPER_LDFLD:
6895 case MONO_WRAPPER_LDFLDA:
6896 case MONO_WRAPPER_LDFLD_REMOTE:
6897 case MONO_WRAPPER_STFLD_REMOTE:
6898 case MONO_WRAPPER_STELEMREF:
6899 case MONO_WRAPPER_ISINST:
6900 case MONO_WRAPPER_PROXY_ISINST:
6901 case MONO_WRAPPER_ALLOC:
6902 case MONO_WRAPPER_REMOTING_INVOKE:
6903 case MONO_WRAPPER_UNKNOWN:
6904 case MONO_WRAPPER_WRITE_BARRIER:
6905 case MONO_WRAPPER_DELEGATE_INVOKE:
6906 case MONO_WRAPPER_DELEGATE_BEGIN_INVOKE:
6907 case MONO_WRAPPER_DELEGATE_END_INVOKE:
6908 case MONO_WRAPPER_SYNCHRONIZED:
6910 case MONO_WRAPPER_MANAGED_TO_MANAGED:
6911 case MONO_WRAPPER_CASTCLASS: {
6912 WrapperInfo *info = mono_marshal_get_wrapper_info (method);
6921 //printf ("Skip (wrapper call): %d -> %s\n", patch_info->type, mono_method_full_name (patch_info->data.method, TRUE));
6925 if (!method->token) {
6926 /* The method is part of a constructed type like Int[,].Set (). */
6927 if (!g_hash_table_lookup (acfg->token_info_hash, method)) {
6928 if (method->klass->rank)
6938 can_encode_patch (MonoAotCompile *acfg, MonoJumpInfo *patch_info)
6940 switch (patch_info->type) {
6941 case MONO_PATCH_INFO_METHOD:
6942 case MONO_PATCH_INFO_METHODCONST:
6943 case MONO_PATCH_INFO_METHOD_CODE_SLOT: {
6944 MonoMethod *method = patch_info->data.method;
6946 return can_encode_method (acfg, method);
6948 case MONO_PATCH_INFO_VTABLE:
6949 case MONO_PATCH_INFO_CLASS:
6950 case MONO_PATCH_INFO_IID:
6951 case MONO_PATCH_INFO_ADJUSTED_IID:
6952 if (!can_encode_class (acfg, patch_info->data.klass)) {
6953 //printf ("Skip: %s\n", mono_type_full_name (&patch_info->data.klass->byval_arg));
6957 case MONO_PATCH_INFO_DELEGATE_TRAMPOLINE: {
6958 if (!can_encode_class (acfg, patch_info->data.del_tramp->klass)) {
6959 //printf ("Skip: %s\n", mono_type_full_name (&patch_info->data.klass->byval_arg));
6964 case MONO_PATCH_INFO_RGCTX_FETCH:
6965 case MONO_PATCH_INFO_RGCTX_SLOT_INDEX: {
6966 MonoJumpInfoRgctxEntry *entry = patch_info->data.rgctx_entry;
6968 if (!can_encode_method (acfg, entry->method))
6970 if (!can_encode_patch (acfg, entry->data))
6982 is_concrete_type (MonoType *t)
6987 if (t->type == MONO_TYPE_VAR || t->type == MONO_TYPE_MVAR)
6989 if (t->type == MONO_TYPE_GENERICINST) {
6990 MonoGenericContext *orig_ctx;
6991 MonoGenericInst *inst;
6994 if (!MONO_TYPE_ISSTRUCT (t))
6996 klass = mono_class_from_mono_type (t);
6997 orig_ctx = &klass->generic_class->context;
6999 inst = orig_ctx->class_inst;
7001 for (i = 0; i < inst->type_argc; ++i) {
7002 arg = mini_get_underlying_type (inst->type_argv [i]);
7003 if (!is_concrete_type (arg))
7007 inst = orig_ctx->method_inst;
7009 for (i = 0; i < inst->type_argc; ++i) {
7010 arg = mini_get_underlying_type (inst->type_argv [i]);
7011 if (!is_concrete_type (arg))
7019 /* LOCKING: Assumes the loader lock is held */
7021 add_gsharedvt_wrappers (MonoAotCompile *acfg, MonoMethodSignature *sig, gboolean gsharedvt_in, gboolean gsharedvt_out)
7023 MonoMethod *wrapper;
7024 gboolean concrete = TRUE;
7025 gboolean add_in = gsharedvt_in;
7026 gboolean add_out = gsharedvt_out;
7028 if (gsharedvt_in && g_hash_table_lookup (acfg->gsharedvt_in_signatures, sig))
7030 if (gsharedvt_out && g_hash_table_lookup (acfg->gsharedvt_out_signatures, sig))
7033 if (!add_in && !add_out)
7036 if (mini_is_gsharedvt_variable_signature (sig))
7040 g_hash_table_insert (acfg->gsharedvt_in_signatures, sig, sig);
7042 g_hash_table_insert (acfg->gsharedvt_out_signatures, sig, sig);
7044 if (!sig->has_type_parameters) {
7045 //printf ("%s\n", mono_signature_full_name (sig));
7048 wrapper = mini_get_gsharedvt_in_sig_wrapper (sig);
7049 add_extra_method (acfg, wrapper);
7051 if (gsharedvt_out) {
7052 wrapper = mini_get_gsharedvt_out_sig_wrapper (sig);
7053 add_extra_method (acfg, wrapper);
7056 /* For signatures creared during generic sharing, convert them to a concrete signature if possible */
7057 MonoMethodSignature *copy = mono_metadata_signature_dup (sig);
7060 //printf ("%s\n", mono_signature_full_name (sig));
7062 copy->ret = mini_get_underlying_type (sig->ret);
7063 if (!is_concrete_type (copy->ret))
7065 for (i = 0; i < sig->param_count; ++i) {
7066 copy->params [i] = mini_get_underlying_type (sig->params [i]);
7067 if (!is_concrete_type (copy->params [i]))
7071 copy->has_type_parameters = 0;
7074 wrapper = mini_get_gsharedvt_in_sig_wrapper (copy);
7075 add_extra_method (acfg, wrapper);
7078 if (gsharedvt_out) {
7079 wrapper = mini_get_gsharedvt_out_sig_wrapper (copy);
7080 add_extra_method (acfg, wrapper);
7083 //printf ("%s\n", mono_method_full_name (wrapper, 1));
7091 * AOT compile a given method.
7092 * This function might be called by multiple threads, so it must be thread-safe.
7095 compile_method (MonoAotCompile *acfg, MonoMethod *method)
7098 MonoJumpInfo *patch_info;
7101 MonoMethod *wrapped;
7104 if (acfg->aot_opts.metadata_only)
7107 mono_acfg_lock (acfg);
7108 index = get_method_index (acfg, method);
7109 mono_acfg_unlock (acfg);
7111 /* fixme: maybe we can also precompile wrapper methods */
7112 if ((method->flags & METHOD_ATTRIBUTE_PINVOKE_IMPL) ||
7113 (method->iflags & METHOD_IMPL_ATTRIBUTE_RUNTIME) ||
7114 (method->flags & METHOD_ATTRIBUTE_ABSTRACT)) {
7115 //printf ("Skip (impossible): %s\n", mono_method_full_name (method, TRUE));
7119 if (method->iflags & METHOD_IMPL_ATTRIBUTE_INTERNAL_CALL)
7122 wrapped = mono_marshal_method_from_wrapper (method);
7123 if (wrapped && (wrapped->iflags & METHOD_IMPL_ATTRIBUTE_INTERNAL_CALL) && wrapped->is_generic)
7124 // FIXME: The wrapper should be generic too, but it is not
7127 if (method->wrapper_type == MONO_WRAPPER_COMINTEROP)
7130 InterlockedIncrement (&acfg->stats.mcount);
7133 if (method->is_generic || method->klass->generic_container) {
7134 InterlockedIncrement (&acfg->stats.genericcount);
7139 //acfg->aot_opts.print_skipped_methods = TRUE;
7142 * Since these methods are the only ones which are compiled with
7143 * AOT support, and they are not used by runtime startup/shutdown code,
7144 * the runtime will not see AOT methods during AOT compilation,so it
7145 * does not need to support them by creating a fake GOT etc.
7147 flags = JIT_FLAG_AOT;
7148 if (mono_aot_mode_is_full (&acfg->aot_opts))
7149 flags = (JitFlags)(flags | JIT_FLAG_FULL_AOT);
7151 flags = (JitFlags)(flags | JIT_FLAG_LLVM);
7152 if (acfg->aot_opts.llvm_only)
7153 flags = (JitFlags)(flags | JIT_FLAG_LLVM_ONLY | JIT_FLAG_EXPLICIT_NULL_CHECKS);
7154 if (acfg->aot_opts.no_direct_calls)
7155 flags = (JitFlags)(flags | JIT_FLAG_NO_DIRECT_ICALLS);
7156 cfg = mini_method_compile (method, acfg->opts, mono_get_root_domain (), flags, 0, index);
7157 mono_loader_clear_error ();
7159 if (cfg->exception_type == MONO_EXCEPTION_GENERIC_SHARING_FAILED) {
7160 if (acfg->aot_opts.print_skipped_methods)
7161 printf ("Skip (gshared failure): %s (%s)\n", mono_method_get_full_name (method), cfg->exception_message);
7162 InterlockedIncrement (&acfg->stats.genericcount);
7165 if (cfg->exception_type != MONO_EXCEPTION_NONE) {
7166 if (acfg->aot_opts.print_skipped_methods)
7167 printf ("Skip (JIT failure): %s\n", mono_method_get_full_name (method));
7168 /* Let the exception happen at runtime */
7172 if (cfg->disable_aot) {
7173 if (acfg->aot_opts.print_skipped_methods)
7174 printf ("Skip (disabled): %s\n", mono_method_get_full_name (method));
7175 InterlockedIncrement (&acfg->stats.ocount);
7176 mono_destroy_compile (cfg);
7179 cfg->method_index = index;
7181 /* Nullify patches which need no aot processing */
7182 for (patch_info = cfg->patch_info; patch_info; patch_info = patch_info->next) {
7183 switch (patch_info->type) {
7184 case MONO_PATCH_INFO_LABEL:
7185 case MONO_PATCH_INFO_BB:
7186 patch_info->type = MONO_PATCH_INFO_NONE;
7193 /* Collect method->token associations from the cfg */
7194 mono_acfg_lock (acfg);
7195 g_hash_table_foreach (cfg->token_info_hash, add_token_info_hash, acfg);
7196 mono_acfg_unlock (acfg);
7197 g_hash_table_destroy (cfg->token_info_hash);
7198 cfg->token_info_hash = NULL;
7201 * Check for absolute addresses.
7204 for (patch_info = cfg->patch_info; patch_info; patch_info = patch_info->next) {
7205 switch (patch_info->type) {
7206 case MONO_PATCH_INFO_ABS:
7207 /* unable to handle this */
7216 if (acfg->aot_opts.print_skipped_methods)
7217 printf ("Skip (abs call): %s\n", mono_method_get_full_name (method));
7218 InterlockedIncrement (&acfg->stats.abscount);
7219 mono_destroy_compile (cfg);
7223 /* Lock for the rest of the code */
7224 mono_acfg_lock (acfg);
7227 acfg->stats.method_categories [METHOD_CAT_GSHAREDVT] ++;
7228 else if (cfg->gshared)
7229 acfg->stats.method_categories [METHOD_CAT_INST] ++;
7230 else if (cfg->method->wrapper_type)
7231 acfg->stats.method_categories [METHOD_CAT_WRAPPER] ++;
7233 acfg->stats.method_categories [METHOD_CAT_NORMAL] ++;
7236 * Check for methods/klasses we can't encode.
7239 for (patch_info = cfg->patch_info; patch_info; patch_info = patch_info->next) {
7240 if (!can_encode_patch (acfg, patch_info))
7245 if (acfg->aot_opts.print_skipped_methods)
7246 printf ("Skip (patches): %s\n", mono_method_get_full_name (method));
7247 acfg->stats.ocount++;
7248 mono_destroy_compile (cfg);
7249 mono_acfg_unlock (acfg);
7253 if (!cfg->compile_llvm)
7254 acfg->has_jitted_code = TRUE;
7256 if (method->is_inflated && acfg->aot_opts.log_instances) {
7257 if (acfg->instances_logfile)
7258 fprintf (acfg->instances_logfile, "%s ### %d\n", mono_method_get_full_name (method), cfg->code_size);
7260 printf ("%s ### %d\n", mono_method_get_full_name (method), cfg->code_size);
7263 /* Adds generic instances referenced by this method */
7265 * The depth is used to avoid infinite loops when generic virtual recursion is
7268 depth = GPOINTER_TO_UINT (g_hash_table_lookup (acfg->method_depth, method));
7269 if (!acfg->aot_opts.no_instances && depth < 32) {
7270 for (patch_info = cfg->patch_info; patch_info; patch_info = patch_info->next) {
7271 switch (patch_info->type) {
7272 case MONO_PATCH_INFO_RGCTX_FETCH:
7273 case MONO_PATCH_INFO_RGCTX_SLOT_INDEX:
7274 case MONO_PATCH_INFO_METHOD: {
7275 MonoMethod *m = NULL;
7277 if (patch_info->type == MONO_PATCH_INFO_RGCTX_FETCH || patch_info->type == MONO_PATCH_INFO_RGCTX_SLOT_INDEX) {
7278 MonoJumpInfoRgctxEntry *e = patch_info->data.rgctx_entry;
7280 if (e->info_type == MONO_RGCTX_INFO_GENERIC_METHOD_CODE)
7281 m = e->data->data.method;
7283 m = patch_info->data.method;
7288 if (m->is_inflated) {
7289 if (!(mono_class_generic_sharing_enabled (m->klass) &&
7290 mono_method_is_generic_sharable_full (m, FALSE, FALSE, FALSE)) &&
7291 (!method_has_type_vars (m) || mono_method_is_generic_sharable_full (m, TRUE, TRUE, FALSE))) {
7292 if (m->iflags & METHOD_IMPL_ATTRIBUTE_INTERNAL_CALL) {
7293 if (mono_aot_mode_is_full (&acfg->aot_opts) && !method_has_type_vars (m))
7294 add_extra_method_with_depth (acfg, mono_marshal_get_native_wrapper (m, TRUE, TRUE), depth + 1);
7296 add_extra_method_with_depth (acfg, m, depth + 1);
7297 add_types_from_method_header (acfg, m);
7300 add_generic_class_with_depth (acfg, m->klass, depth + 5, "method");
7302 if (m->wrapper_type == MONO_WRAPPER_MANAGED_TO_MANAGED) {
7303 WrapperInfo *info = mono_marshal_get_wrapper_info (m);
7305 if (info && info->subtype == WRAPPER_SUBTYPE_ELEMENT_ADDR)
7306 add_extra_method_with_depth (acfg, m, depth + 1);
7310 case MONO_PATCH_INFO_VTABLE: {
7311 MonoClass *klass = patch_info->data.klass;
7313 if (klass->generic_class && !mini_class_is_generic_sharable (klass))
7314 add_generic_class_with_depth (acfg, klass, depth + 5, "vtable");
7317 case MONO_PATCH_INFO_SFLDA: {
7318 MonoClass *klass = patch_info->data.field->parent;
7320 /* The .cctor needs to run at runtime. */
7321 if (klass->generic_class && !mono_generic_context_is_sharable (&klass->generic_class->context, FALSE) && mono_class_get_cctor (klass))
7322 add_extra_method_with_depth (acfg, mono_class_get_cctor (klass), depth + 1);
7331 /* Determine whenever the method has GOT slots */
7332 for (patch_info = cfg->patch_info; patch_info; patch_info = patch_info->next) {
7333 switch (patch_info->type) {
7334 case MONO_PATCH_INFO_GOT_OFFSET:
7335 case MONO_PATCH_INFO_NONE:
7336 case MONO_PATCH_INFO_GC_CARD_TABLE_ADDR:
7337 case MONO_PATCH_INFO_GC_NURSERY_START:
7338 case MONO_PATCH_INFO_GC_NURSERY_BITS:
7340 case MONO_PATCH_INFO_IMAGE:
7341 /* The assembly is stored in GOT slot 0 */
7342 if (patch_info->data.image != acfg->image)
7343 cfg->has_got_slots = TRUE;
7346 if (!is_plt_patch (patch_info) || (cfg->compile_llvm && acfg->aot_opts.llvm_only))
7347 cfg->has_got_slots = TRUE;
7352 if (!cfg->has_got_slots)
7353 InterlockedIncrement (&acfg->stats.methods_without_got_slots);
7355 /* Add gsharedvt wrappers for signatures used by the method */
7356 if (acfg->aot_opts.llvm_only) {
7359 if (!cfg->method->wrapper_type || cfg->method->wrapper_type == MONO_WRAPPER_DELEGATE_INVOKE)
7360 /* These only need out wrappers */
7361 add_gsharedvt_wrappers (acfg, mono_method_signature (cfg->method), FALSE, TRUE);
7363 for (l = cfg->signatures; l; l = l->next) {
7364 MonoMethodSignature *sig = mono_metadata_signature_dup ((MonoMethodSignature*)l->data);
7366 /* These only need in wrappers */
7367 add_gsharedvt_wrappers (acfg, sig, TRUE, FALSE);
7372 * FIXME: Instead of this mess, allocate the patches from the aot mempool.
7374 /* Make a copy of the patch info which is in the mempool */
7376 MonoJumpInfo *patches = NULL, *patches_end = NULL;
7378 for (patch_info = cfg->patch_info; patch_info; patch_info = patch_info->next) {
7379 MonoJumpInfo *new_patch_info = mono_patch_info_dup_mp (acfg->mempool, patch_info);
7382 patches = new_patch_info;
7384 patches_end->next = new_patch_info;
7385 patches_end = new_patch_info;
7387 cfg->patch_info = patches;
7389 /* Make a copy of the unwind info */
7391 GSList *l, *unwind_ops;
7395 for (l = cfg->unwind_ops; l; l = l->next) {
7396 op = (MonoUnwindOp *)mono_mempool_alloc (acfg->mempool, sizeof (MonoUnwindOp));
7397 memcpy (op, l->data, sizeof (MonoUnwindOp));
7398 unwind_ops = g_slist_prepend_mempool (acfg->mempool, unwind_ops, op);
7400 cfg->unwind_ops = g_slist_reverse (unwind_ops);
7402 /* Make a copy of the argument/local info */
7404 MonoInst **args, **locals;
7405 MonoMethodSignature *sig;
7406 MonoMethodHeader *header;
7409 sig = mono_method_signature (method);
7410 args = (MonoInst **)mono_mempool_alloc (acfg->mempool, sizeof (MonoInst*) * (sig->param_count + sig->hasthis));
7411 for (i = 0; i < sig->param_count + sig->hasthis; ++i) {
7412 args [i] = (MonoInst *)mono_mempool_alloc (acfg->mempool, sizeof (MonoInst));
7413 memcpy (args [i], cfg->args [i], sizeof (MonoInst));
7417 header = mono_method_get_header (method);
7418 locals = (MonoInst **)mono_mempool_alloc (acfg->mempool, sizeof (MonoInst*) * header->num_locals);
7419 for (i = 0; i < header->num_locals; ++i) {
7420 locals [i] = (MonoInst *)mono_mempool_alloc (acfg->mempool, sizeof (MonoInst));
7421 memcpy (locals [i], cfg->locals [i], sizeof (MonoInst));
7423 cfg->locals = locals;
7426 /* Free some fields used by cfg to conserve memory */
7427 mono_mempool_destroy (cfg->mempool);
7428 cfg->mempool = NULL;
7429 g_free (cfg->varinfo);
7430 cfg->varinfo = NULL;
7434 mono_regstate_free (cfg->rs);
7438 //printf ("Compile: %s\n", mono_method_full_name (method, TRUE));
7440 while (index >= acfg->cfgs_size) {
7441 MonoCompile **new_cfgs;
7444 new_size = acfg->cfgs_size * 2;
7445 new_cfgs = g_new0 (MonoCompile*, new_size);
7446 memcpy (new_cfgs, acfg->cfgs, sizeof (MonoCompile*) * acfg->cfgs_size);
7447 g_free (acfg->cfgs);
7448 acfg->cfgs = new_cfgs;
7449 acfg->cfgs_size = new_size;
7451 acfg->cfgs [index] = cfg;
7453 g_hash_table_insert (acfg->method_to_cfg, cfg->orig_method, cfg);
7456 if (cfg->orig_method->wrapper_type)
7457 g_ptr_array_add (acfg->extra_methods, cfg->orig_method);
7460 mono_acfg_unlock (acfg);
7462 InterlockedIncrement (&acfg->stats.ccount);
7466 compile_thread_main (gpointer *user_data)
7468 MonoDomain *domain = (MonoDomain *)user_data [0];
7469 MonoAotCompile *acfg = (MonoAotCompile *)user_data [1];
7470 GPtrArray *methods = (GPtrArray *)user_data [2];
7473 mono_thread_attach (domain);
7475 for (i = 0; i < methods->len; ++i)
7476 compile_method (acfg, (MonoMethod *)g_ptr_array_index (methods, i));
7480 load_profile_files (MonoAotCompile *acfg)
7484 int file_index, res, method_index, i;
7487 GList *unordered, *l;
7492 tmp = g_strdup_printf ("%s/.mono/aot-profile-data/%s-%d", g_get_home_dir (), acfg->image->assembly_name, file_index);
7494 if (!g_file_test (tmp, G_FILE_TEST_IS_REGULAR)) {
7499 infile = fopen (tmp, "r");
7502 printf ("Using profile data file '%s'\n", tmp);
7507 res = fscanf (infile, "%32s\n", ver);
7508 if ((res != 1) || strcmp (ver, "#VER:2") != 0) {
7509 printf ("Profile file has wrong version or invalid.\n");
7516 MonoMethodDesc *desc;
7519 if (fgets (name, 1023, infile) == NULL)
7522 /* Kill the newline */
7523 if (strlen (name) > 0)
7524 name [strlen (name) - 1] = '\0';
7526 desc = mono_method_desc_new (name, TRUE);
7528 method = mono_method_desc_search_in_image (desc, acfg->image);
7530 if (method && mono_method_get_token (method)) {
7531 token = mono_method_get_token (method);
7532 method_index = mono_metadata_token_index (token) - 1;
7535 for (i = 0; i < acfg->method_order->len; ++i) {
7536 if (g_ptr_array_index (acfg->method_order, i) == GUINT_TO_POINTER (method_index)) {
7542 g_ptr_array_add (acfg->method_order, GUINT_TO_POINTER (method_index));
7544 //printf ("No method found matching '%s'.\n", name);
7550 /* Add missing methods */
7552 for (method_index = 0; method_index < acfg->image->tables [MONO_TABLE_METHOD].rows; ++method_index) {
7554 for (i = 0; i < acfg->method_order->len; ++i) {
7555 if (g_ptr_array_index (acfg->method_order, i) == GUINT_TO_POINTER (method_index)) {
7561 unordered = g_list_prepend (unordered, GUINT_TO_POINTER (method_index));
7563 unordered = g_list_reverse (unordered);
7564 for (l = unordered; l; l = l->next)
7565 g_ptr_array_add (acfg->method_order, l->data);
7568 /* Used by the LLVM backend */
7570 mono_aot_get_got_offset (MonoJumpInfo *ji)
7572 return get_got_offset (llvm_acfg, TRUE, ji);
7576 * mono_aot_is_shared_got_offset:
7578 * Return whenever OFFSET refers to a GOT slot which is preinitialized
7579 * when the AOT image is loaded.
7582 mono_aot_is_shared_got_offset (int offset)
7584 return offset < llvm_acfg->nshared_got_entries;
7588 mono_aot_get_method_name (MonoCompile *cfg)
7590 if (llvm_acfg->aot_opts.static_link)
7591 /* Include the assembly name too to avoid duplicate symbol errors */
7592 return g_strdup_printf ("%s_%s", llvm_acfg->assembly_name_sym, get_debug_sym (cfg->orig_method, "", llvm_acfg->method_label_hash));
7594 return get_debug_sym (cfg->orig_method, "", llvm_acfg->method_label_hash);
7598 * mono_aot_is_linkonce_method:
7600 * Return whenever METHOD should be emitted with linkonce linkage,
7601 * eliminating duplicate copies when compiling in static mode.
7604 mono_aot_is_linkonce_method (MonoMethod *method)
7608 // FIXME: Add more cases
7609 if (method->wrapper_type != MONO_WRAPPER_UNKNOWN)
7611 info = mono_marshal_get_wrapper_info (method);
7612 if ((info && (info->subtype == WRAPPER_SUBTYPE_GSHAREDVT_IN_SIG || info->subtype == WRAPPER_SUBTYPE_GSHAREDVT_OUT_SIG)))
7618 append_mangled_type (GString *s, MonoType *t)
7621 g_string_append_printf (s, "b");
7623 case MONO_TYPE_VOID:
7624 g_string_append_printf (s, "void_");
7627 g_string_append_printf (s, "i1");
7630 g_string_append_printf (s, "u1");
7633 g_string_append_printf (s, "i2");
7636 g_string_append_printf (s, "u2");
7639 g_string_append_printf (s, "i4");
7642 g_string_append_printf (s, "u4");
7645 g_string_append_printf (s, "i8");
7648 g_string_append_printf (s, "u8");
7651 g_string_append_printf (s, "ii");
7654 g_string_append_printf (s, "ui");
7657 g_string_append_printf (s, "fl");
7660 g_string_append_printf (s, "do");
7663 char *fullname = mono_type_full_name (t);
7669 * Have to create a mangled name which is:
7673 temp = g_string_new ("");
7674 len = strlen (fullname);
7675 for (i = 0; i < len; ++i) {
7676 char c = fullname [i];
7678 g_string_append_c (temp, c);
7679 } else if (c == '_') {
7680 g_string_append_c (temp, '_');
7681 g_string_append_c (temp, '_');
7683 g_string_append_c (temp, '_');
7684 g_string_append_printf (temp, "%x", (int)c);
7687 temps = g_string_free (temp, FALSE);
7688 /* Include the length to avoid different length type names aliasing each other */
7689 g_string_append_printf (s, "cl%x_%s_", strlen (temps), temps);
7698 append_mangled_signature (GString *s, MonoMethodSignature *sig)
7703 supported = append_mangled_type (s, sig->ret);
7707 g_string_append_printf (s, "this_");
7708 for (i = 0; i < sig->param_count; ++i) {
7709 supported = append_mangled_type (s, sig->params [i]);
7718 * mono_aot_get_mangled_method_name:
7720 * Return a unique mangled name for METHOD, or NULL.
7723 mono_aot_get_mangled_method_name (MonoMethod *method)
7729 // FIXME: Add more cases
7730 if (method->wrapper_type != MONO_WRAPPER_UNKNOWN)
7732 info = mono_marshal_get_wrapper_info (method);
7733 if (!(info && (info->subtype == WRAPPER_SUBTYPE_GSHAREDVT_IN_SIG || info->subtype == WRAPPER_SUBTYPE_GSHAREDVT_OUT_SIG)))
7736 s = g_string_new ("");
7738 g_string_append_printf (s, "aot_method_w_");
7740 switch (info->subtype) {
7741 case WRAPPER_SUBTYPE_GSHAREDVT_IN_SIG:
7742 g_string_append_printf (s, "gsharedvt_in_");
7744 case WRAPPER_SUBTYPE_GSHAREDVT_OUT_SIG:
7745 g_string_append_printf (s, "gsharedvt_out_");
7748 g_assert_not_reached ();
7752 supported = append_mangled_signature (s, info->d.gsharedvt.sig);
7754 g_string_free (s, TRUE);
7758 return g_string_free (s, FALSE);
7762 mono_aot_is_direct_callable (MonoJumpInfo *patch_info)
7764 return is_direct_callable (llvm_acfg, NULL, patch_info);
7768 mono_aot_mark_unused_llvm_plt_entry (MonoJumpInfo *patch_info)
7770 MonoPltEntry *plt_entry;
7772 plt_entry = get_plt_entry (llvm_acfg, patch_info);
7773 plt_entry->llvm_used = FALSE;
7777 mono_aot_get_direct_call_symbol (MonoJumpInfoType type, gconstpointer data)
7779 const char *sym = NULL;
7781 if (llvm_acfg->aot_opts.direct_icalls) {
7782 if (type == MONO_PATCH_INFO_JIT_ICALL_ADDR) {
7783 /* Call to a C function implementing a jit icall */
7784 sym = mono_lookup_jit_icall_symbol ((const char *)data);
7785 } else if (type == MONO_PATCH_INFO_ICALL_ADDR) {
7786 MonoMethod *method = (MonoMethod *)data;
7787 if (!(method->flags & METHOD_ATTRIBUTE_PINVOKE_IMPL))
7788 sym = mono_lookup_icall_symbol (method);
7789 else if (llvm_acfg->aot_opts.direct_pinvoke)
7790 sym = get_pinvoke_import (llvm_acfg, method);
7793 return g_strdup (sym);
7799 mono_aot_get_plt_symbol (MonoJumpInfoType type, gconstpointer data)
7801 MonoJumpInfo *ji = (MonoJumpInfo *)mono_mempool_alloc (llvm_acfg->mempool, sizeof (MonoJumpInfo));
7802 MonoPltEntry *plt_entry;
7803 const char *sym = NULL;
7806 ji->data.target = data;
7808 if (!can_encode_patch (llvm_acfg, ji))
7811 if (llvm_acfg->aot_opts.direct_icalls) {
7812 if (type == MONO_PATCH_INFO_JIT_ICALL_ADDR) {
7813 /* Call to a C function implementing a jit icall */
7814 sym = mono_lookup_jit_icall_symbol ((const char *)data);
7815 } else if (type == MONO_PATCH_INFO_ICALL_ADDR) {
7816 MonoMethod *method = (MonoMethod *)data;
7817 if (!(method->flags & METHOD_ATTRIBUTE_PINVOKE_IMPL))
7818 sym = mono_lookup_icall_symbol (method);
7821 return g_strdup (sym);
7824 plt_entry = get_plt_entry (llvm_acfg, ji);
7825 plt_entry->llvm_used = TRUE;
7827 #if defined(TARGET_MACH)
7828 return g_strdup_printf (plt_entry->llvm_symbol + strlen (llvm_acfg->llvm_label_prefix));
7830 return g_strdup_printf (plt_entry->llvm_symbol);
7835 mono_aot_get_method_index (MonoMethod *method)
7837 g_assert (llvm_acfg);
7838 return get_method_index (llvm_acfg, method);
7842 mono_aot_patch_info_dup (MonoJumpInfo* ji)
7846 mono_acfg_lock (llvm_acfg);
7847 res = mono_patch_info_dup_mp (llvm_acfg->mempool, ji);
7848 mono_acfg_unlock (llvm_acfg);
7854 execute_system (const char * command)
7859 // We need an extra set of quotes around the whole command to properly handle commands
7860 // with spaces since internally the command is called through "cmd /c.
7861 command = g_strdup_printf ("\"%s\"", command);
7863 int size = MultiByteToWideChar (CP_UTF8, 0 , command , -1, NULL , 0);
7864 wchar_t* wstr = g_malloc (sizeof (wchar_t) * size);
7865 MultiByteToWideChar (CP_UTF8, 0, command, -1, wstr , size);
7866 status = _wsystem (wstr);
7870 #elif defined (HAVE_SYSTEM)
7871 status = system (command);
7873 g_assert_not_reached ();
7884 * Emit the LLVM code into an LLVM bytecode file, and compile it using the LLVM
7888 emit_llvm_file (MonoAotCompile *acfg)
7890 char *command, *opts, *tempbc, *optbc, *output_fname;
7892 if (acfg->aot_opts.llvm_only && acfg->aot_opts.asm_only) {
7893 tempbc = g_strdup_printf ("%s.bc", acfg->tmpbasename);
7894 optbc = g_strdup (acfg->aot_opts.llvm_outfile);
7896 tempbc = g_strdup_printf ("%s.bc", acfg->tmpbasename);
7897 optbc = g_strdup_printf ("%s.opt.bc", acfg->tmpbasename);
7900 mono_llvm_emit_aot_module (tempbc, g_path_get_basename (acfg->image->name));
7903 * FIXME: Experiment with adding optimizations, the -std-compile-opts set takes
7904 * a lot of time, and doesn't seem to save much space.
7905 * The following optimizations cannot be enabled:
7907 * - 'jump-threading' changes our blockaddress references to int constants.
7908 * - 'basiccg' fails because it contains:
7909 * if (CS && !isa<IntrinsicInst>(II)) {
7910 * and isa<IntrinsicInst> is false for invokes to intrinsics (iltests.exe).
7911 * - 'prune-eh' and 'functionattrs' depend on 'basiccg'.
7912 * The opt list below was produced by taking the output of:
7913 * llvm-as < /dev/null | opt -O2 -disable-output -debug-pass=Arguments
7914 * then removing tailcallelim + the global opts.
7915 * strip-dead-prototypes deletes unused intrinsics definitions.
7917 //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");
7918 /* The dse pass is disabled because of #13734 and #17616 */
7920 * The dse bug is in DeadStoreElimination.cpp:isOverwrite ():
7921 * // If we have no DataLayout information around, then the size of the store
7922 * // is inferrable from the pointee type. If they are the same type, then
7923 * // we know that the store is safe.
7924 * if (AA.getDataLayout() == 0 &&
7925 * Later.Ptr->getType() == Earlier.Ptr->getType()) {
7926 * return OverwriteComplete;
7927 * Here, if 'Earlier' refers to a memset, and Later has no size info, it mistakenly thinks the memset is redundant.
7929 if (acfg->aot_opts.llvm_only)
7930 // FIXME: This doesn't work yet
7931 opts = g_strdup ("");
7933 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");
7934 command = g_strdup_printf ("\"%sopt\" -f %s -o \"%s\" \"%s\"", acfg->aot_opts.llvm_path, opts, optbc, tempbc);
7935 aot_printf (acfg, "Executing opt: %s\n", command);
7936 if (execute_system (command) != 0)
7940 if (acfg->aot_opts.llvm_only && acfg->aot_opts.asm_only)
7941 /* Nothing else to do */
7944 if (acfg->aot_opts.llvm_only) {
7945 /* Use the stock clang from xcode */
7948 // FIXME: llc/opt flags
7949 command = g_strdup_printf ("clang -march=x86-64 -fpic -msse -msse2 -msse3 -msse4 -O2 -c -o \"%s\" \"%s.opt.bc\"", acfg->llvm_ofile, acfg->tmpbasename);
7950 //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);
7952 aot_printf (acfg, "Executing clang: %s\n", command);
7953 if (execute_system (command) != 0)
7958 if (!acfg->llc_args)
7959 acfg->llc_args = g_string_new ("");
7961 /* Verbose asm slows down llc greatly */
7962 g_string_append (acfg->llc_args, " -asm-verbose=false");
7964 if (acfg->aot_opts.mtriple)
7965 g_string_append_printf (acfg->llc_args, " -mtriple=%s", acfg->aot_opts.mtriple);
7967 g_string_append (acfg->llc_args, " -disable-gnu-eh-frame -enable-mono-eh-frame");
7969 g_string_append_printf (acfg->llc_args, " -mono-eh-frame-symbol=%s%s", acfg->user_symbol_prefix, acfg->llvm_eh_frame_symbol);
7971 #if defined(TARGET_MACH) && defined(TARGET_ARM)
7972 /* ios requires PIC code now */
7973 g_string_append_printf (acfg->llc_args, " -relocation-model=pic");
7975 if (llvm_acfg->aot_opts.static_link)
7976 g_string_append_printf (acfg->llc_args, " -relocation-model=static");
7978 g_string_append_printf (acfg->llc_args, " -relocation-model=pic");
7981 if (acfg->llvm_owriter) {
7982 /* Emit an object file directly */
7983 output_fname = g_strdup_printf ("%s", acfg->llvm_ofile);
7984 g_string_append_printf (acfg->llc_args, " -filetype=obj");
7986 output_fname = g_strdup_printf ("%s", acfg->llvm_sfile);
7988 command = g_strdup_printf ("\"%sllc\" %s -o \"%s\" \"%s.opt.bc\"", acfg->aot_opts.llvm_path, acfg->llc_args->str, output_fname, acfg->tmpbasename);
7989 g_free (output_fname);
7991 aot_printf (acfg, "Executing llc: %s\n", command);
7993 if (execute_system (command) != 0)
8000 emit_code (MonoAotCompile *acfg)
8002 int oindex, i, prev_index;
8003 gboolean saved_unbox_info = FALSE;
8006 if (acfg->aot_opts.llvm_only)
8009 #if defined(TARGET_POWERPC64)
8010 sprintf (symbol, ".Lgot_addr");
8011 emit_section_change (acfg, ".text", 0);
8012 emit_alignment (acfg, 8);
8013 emit_label (acfg, symbol);
8014 emit_pointer (acfg, acfg->got_symbol);
8018 * This global symbol is used to compute the address of each method using the
8019 * code_offsets array. It is also used to compute the memory ranges occupied by
8020 * AOT code, so it must be equal to the address of the first emitted method.
8022 emit_section_change (acfg, ".text", 0);
8023 emit_alignment_code (acfg, 8);
8024 emit_info_symbol (acfg, "jit_code_start");
8027 * Emit some padding so the local symbol for the first method doesn't have the
8028 * same address as 'methods'.
8030 #if defined(__default_codegen__)
8031 emit_padding (acfg, 16);
8032 #elif defined(__native_client_codegen__)
8034 const int kPaddingSize = 16;
8035 guint8 pad_buffer[kPaddingSize];
8036 mono_arch_nacl_pad (pad_buffer, kPaddingSize);
8037 emit_bytes (acfg, pad_buffer, kPaddingSize);
8041 for (oindex = 0; oindex < acfg->method_order->len; ++oindex) {
8045 i = GPOINTER_TO_UINT (g_ptr_array_index (acfg->method_order, oindex));
8047 cfg = acfg->cfgs [i];
8052 method = cfg->orig_method;
8054 /* Emit unbox trampoline */
8055 if (mono_aot_mode_is_full (&acfg->aot_opts) && cfg->orig_method->klass->valuetype && !(acfg->aot_opts.llvm_only && cfg->compile_llvm)) {
8056 sprintf (symbol, "ut_%d", get_method_index (acfg, method));
8058 emit_section_change (acfg, ".text", 0);
8059 #ifdef __native_client_codegen__
8060 emit_alignment (acfg, AOT_FUNC_ALIGNMENT);
8063 if (acfg->thumb_mixed && cfg->compile_llvm) {
8064 emit_set_thumb_mode (acfg);
8065 fprintf (acfg->fp, "\n.thumb_func\n");
8068 emit_label (acfg, symbol);
8070 arch_emit_unbox_trampoline (acfg, cfg, cfg->orig_method, cfg->asm_symbol);
8072 if (acfg->thumb_mixed && cfg->compile_llvm)
8073 emit_set_arm_mode (acfg);
8075 if (!saved_unbox_info) {
8076 char user_symbol [128];
8078 sprintf (user_symbol, "%sunbox_trampoline_p", acfg->user_symbol_prefix);
8080 emit_label (acfg, "ut_end");
8082 unwind_ops = mono_unwind_get_cie_program ();
8083 save_unwind_info (acfg, user_symbol, unwind_ops);
8084 mono_free_unwind_info (unwind_ops);
8086 /* Save the unbox trampoline size */
8087 emit_symbol_diff (acfg, "ut_end", symbol, 0);
8089 saved_unbox_info = TRUE;
8093 if (cfg->compile_llvm)
8094 acfg->stats.llvm_count ++;
8096 emit_method_code (acfg, cfg);
8099 emit_section_change (acfg, ".text", 0);
8100 emit_alignment_code (acfg, 8);
8101 emit_info_symbol (acfg, "jit_code_end");
8103 /* To distinguish it from the next symbol */
8104 emit_padding (acfg, 4);
8107 * Add .no_dead_strip directives for all LLVM methods to prevent the OSX linker
8108 * from optimizing them away, since it doesn't see that code_offsets references them.
8109 * JITted methods don't need this since they are referenced using assembler local
8111 * FIXME: This is why write-symbols doesn't work on OSX ?
8113 if (acfg->llvm && acfg->need_no_dead_strip) {
8114 fprintf (acfg->fp, "\n");
8115 for (i = 0; i < acfg->nmethods; ++i) {
8116 if (acfg->cfgs [i] && acfg->cfgs [i]->compile_llvm)
8117 fprintf (acfg->fp, ".no_dead_strip %s\n", acfg->cfgs [i]->asm_symbol);
8122 * To work around linker issues, we emit a table of branches, and disassemble them at runtime.
8123 * This is PIE code, and the linker can update it if needed.
8125 sprintf (symbol, "method_addresses");
8126 emit_section_change (acfg, ".text", 1);
8127 emit_alignment_code (acfg, 8);
8128 emit_info_symbol (acfg, symbol);
8129 emit_local_symbol (acfg, symbol, "method_addresses_end", TRUE);
8130 emit_unset_mode (acfg);
8131 if (acfg->need_no_dead_strip)
8132 fprintf (acfg->fp, " .no_dead_strip %s\n", symbol);
8134 for (i = 0; i < acfg->nmethods; ++i) {
8135 #ifdef MONO_ARCH_AOT_SUPPORTED
8138 if (acfg->cfgs [i]) {
8139 if (acfg->aot_opts.llvm_only && acfg->cfgs [i]->compile_llvm)
8140 /* Obtained by calling a generated function in the LLVM image */
8141 arch_emit_direct_call (acfg, "method_addresses", FALSE, FALSE, NULL, &call_size);
8143 arch_emit_direct_call (acfg, acfg->cfgs [i]->asm_symbol, FALSE, acfg->thumb_mixed && acfg->cfgs [i]->compile_llvm, NULL, &call_size);
8145 arch_emit_direct_call (acfg, "method_addresses", FALSE, FALSE, NULL, &call_size);
8150 sprintf (symbol, "method_addresses_end");
8151 emit_label (acfg, symbol);
8154 /* Emit a sorted table mapping methods to the index of their unbox trampolines */
8155 sprintf (symbol, "unbox_trampolines");
8156 emit_section_change (acfg, RODATA_SECT, 0);
8157 emit_alignment (acfg, 8);
8158 emit_info_symbol (acfg, symbol);
8161 for (i = 0; i < acfg->nmethods; ++i) {
8166 cfg = acfg->cfgs [i];
8170 method = cfg->orig_method;
8172 if (mono_aot_mode_is_full (&acfg->aot_opts) && cfg->orig_method->klass->valuetype && !(acfg->aot_opts.llvm_only && cfg->compile_llvm)) {
8173 index = get_method_index (acfg, method);
8175 emit_int32 (acfg, index);
8176 /* Make sure the table is sorted by index */
8177 g_assert (index > prev_index);
8181 sprintf (symbol, "unbox_trampolines_end");
8182 emit_info_symbol (acfg, symbol);
8183 emit_int32 (acfg, 0);
8185 /* Emit a separate table with the trampoline addresses/offsets */
8186 sprintf (symbol, "unbox_trampoline_addresses");
8187 emit_section_change (acfg, ".text", 0);
8188 emit_alignment_code (acfg, 8);
8189 emit_info_symbol (acfg, symbol);
8191 for (i = 0; i < acfg->nmethods; ++i) {
8196 cfg = acfg->cfgs [i];
8200 method = cfg->orig_method;
8202 if (mono_aot_mode_is_full (&acfg->aot_opts) && cfg->orig_method->klass->valuetype && !(acfg->aot_opts.llvm_only && cfg->compile_llvm)) {
8203 #ifdef MONO_ARCH_AOT_SUPPORTED
8206 index = get_method_index (acfg, method);
8207 sprintf (symbol, "ut_%d", index);
8209 arch_emit_direct_call (acfg, symbol, FALSE, acfg->thumb_mixed && cfg->compile_llvm, NULL, &call_size);
8213 emit_int32 (acfg, 0);
8217 emit_info (MonoAotCompile *acfg)
8222 offsets = g_new0 (gint32, acfg->nmethods);
8224 for (oindex = 0; oindex < acfg->method_order->len; ++oindex) {
8225 i = GPOINTER_TO_UINT (g_ptr_array_index (acfg->method_order, oindex));
8227 if (acfg->cfgs [i]) {
8228 emit_method_info (acfg, acfg->cfgs [i]);
8229 offsets [i] = acfg->cfgs [i]->method_info_offset;
8235 acfg->stats.offsets_size += emit_offset_table (acfg, "method_info_offsets", MONO_AOT_TABLE_METHOD_INFO_OFFSETS, acfg->nmethods, 10, offsets);
8240 #endif /* #if !defined(DISABLE_AOT) && !defined(DISABLE_JIT) */
8242 #define rot(x,k) (((x)<<(k)) | ((x)>>(32-(k))))
8243 #define mix(a,b,c) { \
8244 a -= c; a ^= rot(c, 4); c += b; \
8245 b -= a; b ^= rot(a, 6); a += c; \
8246 c -= b; c ^= rot(b, 8); b += a; \
8247 a -= c; a ^= rot(c,16); c += b; \
8248 b -= a; b ^= rot(a,19); a += c; \
8249 c -= b; c ^= rot(b, 4); b += a; \
8251 #define final(a,b,c) { \
8252 c ^= b; c -= rot(b,14); \
8253 a ^= c; a -= rot(c,11); \
8254 b ^= a; b -= rot(a,25); \
8255 c ^= b; c -= rot(b,16); \
8256 a ^= c; a -= rot(c,4); \
8257 b ^= a; b -= rot(a,14); \
8258 c ^= b; c -= rot(b,24); \
8262 mono_aot_type_hash (MonoType *t1)
8264 guint hash = t1->type;
8266 hash |= t1->byref << 6; /* do not collide with t1->type values */
8268 case MONO_TYPE_VALUETYPE:
8269 case MONO_TYPE_CLASS:
8270 case MONO_TYPE_SZARRAY:
8271 /* check if the distribution is good enough */
8272 return ((hash << 5) - hash) ^ mono_metadata_str_hash (t1->data.klass->name);
8274 return ((hash << 5) - hash) ^ mono_metadata_type_hash (t1->data.type);
8275 case MONO_TYPE_ARRAY:
8276 return ((hash << 5) - hash) ^ mono_metadata_type_hash (&t1->data.array->eklass->byval_arg);
8277 case MONO_TYPE_GENERICINST:
8278 return ((hash << 5) - hash) ^ 0;
8285 * mono_aot_method_hash:
8287 * Return a hash code for methods which only depends on metadata.
8290 mono_aot_method_hash (MonoMethod *method)
8292 MonoMethodSignature *sig;
8296 guint32 *hashes_start, *hashes;
8298 MonoGenericInst *class_ginst = NULL;
8299 MonoGenericInst *ginst = NULL;
8301 /* Similar to the hash in mono_method_get_imt_slot () */
8303 sig = mono_method_signature (method);
8305 if (method->klass->generic_class)
8306 class_ginst = method->klass->generic_class->context.class_inst;
8307 if (method->is_inflated)
8308 ginst = ((MonoMethodInflated*)method)->context.method_inst;
8310 hashes_count = sig->param_count + 5 + (class_ginst ? class_ginst->type_argc : 0) + (ginst ? ginst->type_argc : 0);
8311 hashes_start = (guint32 *)g_malloc0 (hashes_count * sizeof (guint32));
8312 hashes = hashes_start;
8314 /* Some wrappers are assigned to random classes */
8315 if (!method->wrapper_type || method->wrapper_type == MONO_WRAPPER_REMOTING_INVOKE_WITH_CHECK)
8316 klass = method->klass;
8318 klass = mono_defaults.object_class;
8320 if (!method->wrapper_type) {
8323 if (klass->generic_class)
8324 full_name = mono_type_full_name (&klass->generic_class->container_class->byval_arg);
8326 full_name = mono_type_full_name (&klass->byval_arg);
8328 hashes [0] = mono_metadata_str_hash (full_name);
8332 hashes [0] = mono_metadata_str_hash (klass->name);
8333 hashes [1] = mono_metadata_str_hash (klass->name_space);
8335 if (method->wrapper_type == MONO_WRAPPER_STFLD || method->wrapper_type == MONO_WRAPPER_LDFLD || method->wrapper_type == MONO_WRAPPER_LDFLDA)
8336 /* The method name includes a stringified pointer */
8339 hashes [2] = mono_metadata_str_hash (method->name);
8340 hashes [3] = method->wrapper_type;
8341 hashes [4] = mono_aot_type_hash (sig->ret);
8343 for (i = 0; i < sig->param_count; i++) {
8344 hashes [hindex ++] = mono_aot_type_hash (sig->params [i]);
8347 for (i = 0; i < class_ginst->type_argc; ++i)
8348 hashes [hindex ++] = mono_aot_type_hash (class_ginst->type_argv [i]);
8351 for (i = 0; i < ginst->type_argc; ++i)
8352 hashes [hindex ++] = mono_aot_type_hash (ginst->type_argv [i]);
8354 g_assert (hindex == hashes_count);
8356 /* Setup internal state */
8357 a = b = c = 0xdeadbeef + (((guint32)hashes_count)<<2);
8359 /* Handle most of the hashes */
8360 while (hashes_count > 3) {
8369 /* Handle the last 3 hashes (all the case statements fall through) */
8370 switch (hashes_count) {
8371 case 3 : c += hashes [2];
8372 case 2 : b += hashes [1];
8373 case 1 : a += hashes [0];
8375 case 0: /* nothing left to add */
8379 free (hashes_start);
8388 * mono_aot_get_array_helper_from_wrapper;
8390 * Get the helper method in Array called by an array wrapper method.
8393 mono_aot_get_array_helper_from_wrapper (MonoMethod *method)
8397 MonoGenericContext ctx;
8398 MonoType *args [16];
8399 char *mname, *iname, *s, *s2, *helper_name = NULL;
8401 prefix = "System.Collections.Generic";
8402 s = g_strdup_printf ("%s", method->name + strlen (prefix) + 1);
8403 s2 = strstr (s, "`1.");
8409 //printf ("X: %s %s\n", iname, mname);
8411 if (!strcmp (iname, "IList"))
8412 helper_name = g_strdup_printf ("InternalArray__%s", mname);
8414 helper_name = g_strdup_printf ("InternalArray__%s_%s", iname, mname);
8415 m = mono_class_get_method_from_name (mono_defaults.array_class, helper_name, mono_method_signature (method)->param_count);
8417 g_free (helper_name);
8420 if (m->is_generic) {
8422 memset (&ctx, 0, sizeof (ctx));
8423 args [0] = &method->klass->element_class->byval_arg;
8424 ctx.method_inst = mono_metadata_get_generic_inst (1, args);
8425 m = mono_class_inflate_generic_method_checked (m, &ctx, &error);
8426 g_assert (mono_error_ok (&error)); /* FIXME don't swallow the error */
8432 #if !defined(DISABLE_AOT) && !defined(DISABLE_JIT)
8434 typedef struct HashEntry {
8435 guint32 key, value, index;
8436 struct HashEntry *next;
8440 * emit_extra_methods:
8442 * Emit methods which are not in the METHOD table, like wrappers.
8445 emit_extra_methods (MonoAotCompile *acfg)
8447 int i, table_size, buf_size;
8449 guint32 *info_offsets;
8452 HashEntry *entry, *new_entry;
8453 int nmethods, max_chain_length;
8456 info_offsets = g_new0 (guint32, acfg->extra_methods->len);
8458 /* Emit method info */
8460 for (i = 0; i < acfg->extra_methods->len; ++i) {
8461 MonoMethod *method = (MonoMethod *)g_ptr_array_index (acfg->extra_methods, i);
8462 MonoCompile *cfg = (MonoCompile *)g_hash_table_lookup (acfg->method_to_cfg, method);
8468 p = buf = (guint8 *)g_malloc (buf_size);
8472 method = cfg->method_to_register;
8474 encode_method_ref (acfg, method, p, &p);
8476 g_assert ((p - buf) < buf_size);
8478 info_offsets [i] = add_to_blob (acfg, buf, p - buf);
8483 * Construct a chained hash table for mapping indexes in extra_method_info to
8486 table_size = g_spaced_primes_closest ((int)(nmethods * 1.5));
8487 table = g_ptr_array_sized_new (table_size);
8488 for (i = 0; i < table_size; ++i)
8489 g_ptr_array_add (table, NULL);
8490 chain_lengths = g_new0 (int, table_size);
8491 max_chain_length = 0;
8492 for (i = 0; i < acfg->extra_methods->len; ++i) {
8493 MonoMethod *method = (MonoMethod *)g_ptr_array_index (acfg->extra_methods, i);
8494 MonoCompile *cfg = (MonoCompile *)g_hash_table_lookup (acfg->method_to_cfg, method);
8500 key = info_offsets [i];
8501 value = get_method_index (acfg, method);
8503 hash = mono_aot_method_hash (method) % table_size;
8504 //printf ("X: %s %x\n", mono_method_get_full_name (method), mono_aot_method_hash (method));
8506 chain_lengths [hash] ++;
8507 max_chain_length = MAX (max_chain_length, chain_lengths [hash]);
8509 new_entry = (HashEntry *)mono_mempool_alloc0 (acfg->mempool, sizeof (HashEntry));
8510 new_entry->key = key;
8511 new_entry->value = value;
8513 entry = (HashEntry *)g_ptr_array_index (table, hash);
8514 if (entry == NULL) {
8515 new_entry->index = hash;
8516 g_ptr_array_index (table, hash) = new_entry;
8519 entry = entry->next;
8521 entry->next = new_entry;
8522 new_entry->index = table->len;
8523 g_ptr_array_add (table, new_entry);
8527 //printf ("MAX: %d\n", max_chain_length);
8529 buf_size = table->len * 12 + 4;
8530 p = buf = (guint8 *)g_malloc (buf_size);
8531 encode_int (table_size, p, &p);
8533 for (i = 0; i < table->len; ++i) {
8534 HashEntry *entry = (HashEntry *)g_ptr_array_index (table, i);
8536 if (entry == NULL) {
8537 encode_int (0, p, &p);
8538 encode_int (0, p, &p);
8539 encode_int (0, p, &p);
8541 //g_assert (entry->key > 0);
8542 encode_int (entry->key, p, &p);
8543 encode_int (entry->value, p, &p);
8545 encode_int (entry->next->index, p, &p);
8547 encode_int (0, p, &p);
8550 g_assert (p - buf <= buf_size);
8552 /* Emit the table */
8553 emit_aot_data (acfg, MONO_AOT_TABLE_EXTRA_METHOD_TABLE, "extra_method_table", buf, p - buf);
8556 * Emit a table reverse mapping method indexes to their index in extra_method_info.
8557 * This is used by mono_aot_find_jit_info ().
8559 buf_size = acfg->extra_methods->len * 8 + 4;
8560 p = buf = (guint8 *)g_malloc (buf_size);
8561 encode_int (acfg->extra_methods->len, p, &p);
8562 for (i = 0; i < acfg->extra_methods->len; ++i) {
8563 MonoMethod *method = (MonoMethod *)g_ptr_array_index (acfg->extra_methods, i);
8565 encode_int (get_method_index (acfg, method), p, &p);
8566 encode_int (info_offsets [i], p, &p);
8568 emit_aot_data (acfg, MONO_AOT_TABLE_EXTRA_METHOD_INFO_OFFSETS, "extra_method_info_offsets", buf, p - buf);
8572 emit_exception_info (MonoAotCompile *acfg)
8576 SeqPointData sp_data;
8577 gboolean seq_points_to_file = FALSE;
8579 offsets = g_new0 (gint32, acfg->nmethods);
8580 for (i = 0; i < acfg->nmethods; ++i) {
8581 if (acfg->cfgs [i]) {
8582 MonoCompile *cfg = acfg->cfgs [i];
8584 // By design aot-runtime decode_exception_debug_info is not able to load sequence point debug data from a file.
8585 // As it is not possible to load debug data from a file its is also not possible to store it in a file.
8586 gboolean method_seq_points_to_file = acfg->aot_opts.gen_seq_points_file &&
8587 cfg->gen_seq_points && !cfg->gen_sdb_seq_points;
8588 gboolean method_seq_points_to_binary = cfg->gen_seq_points && !method_seq_points_to_file;
8590 emit_exception_debug_info (acfg, cfg, method_seq_points_to_binary);
8591 offsets [i] = cfg->ex_info_offset;
8593 if (method_seq_points_to_file) {
8594 if (!seq_points_to_file) {
8595 mono_seq_point_data_init (&sp_data, acfg->nmethods);
8596 seq_points_to_file = TRUE;
8598 mono_seq_point_data_add (&sp_data, cfg->method->token, cfg->method_index, cfg->seq_point_info);
8605 if (seq_points_to_file) {
8606 char *seq_points_aot_file;
8607 mono_image_get_aot_seq_point_path (acfg->image, &seq_points_aot_file);
8608 mono_seq_point_data_write (&sp_data, seq_points_aot_file);
8609 mono_seq_point_data_free (&sp_data);
8610 g_free (seq_points_aot_file);
8613 acfg->stats.offsets_size += emit_offset_table (acfg, "ex_info_offsets", MONO_AOT_TABLE_EX_INFO_OFFSETS, acfg->nmethods, 10, offsets);
8618 emit_unwind_info (MonoAotCompile *acfg)
8623 if (acfg->aot_opts.llvm_only) {
8624 g_assert (acfg->unwind_ops->len == 0);
8629 * The unwind info contains a lot of duplicates so we emit each unique
8630 * entry once, and only store the offset from the start of the table in the
8634 sprintf (symbol, "unwind_info");
8635 emit_section_change (acfg, RODATA_SECT, 1);
8636 emit_alignment (acfg, 8);
8637 emit_info_symbol (acfg, symbol);
8639 for (i = 0; i < acfg->unwind_ops->len; ++i) {
8640 guint32 index = GPOINTER_TO_UINT (g_ptr_array_index (acfg->unwind_ops, i));
8641 guint8 *unwind_info;
8642 guint32 unwind_info_len;
8646 unwind_info = mono_get_cached_unwind_info (index, &unwind_info_len);
8649 encode_value (unwind_info_len, p, &p);
8650 emit_bytes (acfg, buf, p - buf);
8651 emit_bytes (acfg, unwind_info, unwind_info_len);
8653 acfg->stats.unwind_info_size += (p - buf) + unwind_info_len;
8658 emit_class_info (MonoAotCompile *acfg)
8663 offsets = g_new0 (gint32, acfg->image->tables [MONO_TABLE_TYPEDEF].rows);
8664 for (i = 0; i < acfg->image->tables [MONO_TABLE_TYPEDEF].rows; ++i)
8665 offsets [i] = emit_klass_info (acfg, MONO_TOKEN_TYPE_DEF | (i + 1));
8667 acfg->stats.offsets_size += emit_offset_table (acfg, "class_info_offsets", MONO_AOT_TABLE_CLASS_INFO_OFFSETS, acfg->image->tables [MONO_TABLE_TYPEDEF].rows, 10, offsets);
8671 typedef struct ClassNameTableEntry {
8672 guint32 token, index;
8673 struct ClassNameTableEntry *next;
8674 } ClassNameTableEntry;
8677 emit_class_name_table (MonoAotCompile *acfg)
8679 int i, table_size, buf_size;
8680 guint32 token, hash;
8685 ClassNameTableEntry *entry, *new_entry;
8688 * Construct a chained hash table for mapping class names to typedef tokens.
8690 table_size = g_spaced_primes_closest ((int)(acfg->image->tables [MONO_TABLE_TYPEDEF].rows * 1.5));
8691 table = g_ptr_array_sized_new (table_size);
8692 for (i = 0; i < table_size; ++i)
8693 g_ptr_array_add (table, NULL);
8694 for (i = 0; i < acfg->image->tables [MONO_TABLE_TYPEDEF].rows; ++i) {
8696 token = MONO_TOKEN_TYPE_DEF | (i + 1);
8697 klass = mono_class_get_checked (acfg->image, token, &error);
8699 mono_error_cleanup (&error);
8702 full_name = mono_type_get_name_full (mono_class_get_type (klass), MONO_TYPE_NAME_FORMAT_FULL_NAME);
8703 hash = mono_metadata_str_hash (full_name) % table_size;
8706 /* FIXME: Allocate from the mempool */
8707 new_entry = g_new0 (ClassNameTableEntry, 1);
8708 new_entry->token = token;
8710 entry = (ClassNameTableEntry *)g_ptr_array_index (table, hash);
8711 if (entry == NULL) {
8712 new_entry->index = hash;
8713 g_ptr_array_index (table, hash) = new_entry;
8716 entry = entry->next;
8718 entry->next = new_entry;
8719 new_entry->index = table->len;
8720 g_ptr_array_add (table, new_entry);
8724 /* Emit the table */
8725 buf_size = table->len * 4 + 4;
8726 p = buf = (guint8 *)g_malloc0 (buf_size);
8728 /* FIXME: Optimize memory usage */
8729 g_assert (table_size < 65000);
8730 encode_int16 (table_size, p, &p);
8731 g_assert (table->len < 65000);
8732 for (i = 0; i < table->len; ++i) {
8733 ClassNameTableEntry *entry = (ClassNameTableEntry *)g_ptr_array_index (table, i);
8735 if (entry == NULL) {
8736 encode_int16 (0, p, &p);
8737 encode_int16 (0, p, &p);
8739 encode_int16 (mono_metadata_token_index (entry->token), p, &p);
8741 encode_int16 (entry->next->index, p, &p);
8743 encode_int16 (0, p, &p);
8746 g_assert (p - buf <= buf_size);
8748 emit_aot_data (acfg, MONO_AOT_TABLE_CLASS_NAME, "class_name_table", buf, p - buf);
8752 emit_image_table (MonoAotCompile *acfg)
8758 * The image table is small but referenced in a lot of places.
8759 * So we emit it at once, and reference its elements by an index.
8761 buf_size = acfg->image_table->len * 28 + 4;
8762 for (i = 0; i < acfg->image_table->len; i++) {
8763 MonoImage *image = (MonoImage*)g_ptr_array_index (acfg->image_table, i);
8764 MonoAssemblyName *aname = &image->assembly->aname;
8766 buf_size += strlen (image->assembly_name) + strlen (image->guid) + (aname->culture ? strlen (aname->culture) : 1) + strlen ((char*)aname->public_key_token) + 4;
8769 buf = p = (guint8 *)g_malloc0 (buf_size);
8770 encode_int (acfg->image_table->len, p, &p);
8771 for (i = 0; i < acfg->image_table->len; i++) {
8772 MonoImage *image = (MonoImage*)g_ptr_array_index (acfg->image_table, i);
8773 MonoAssemblyName *aname = &image->assembly->aname;
8775 /* FIXME: Support multi-module assemblies */
8776 g_assert (image->assembly->image == image);
8778 encode_string (image->assembly_name, p, &p);
8779 encode_string (image->guid, p, &p);
8780 encode_string (aname->culture ? aname->culture : "", p, &p);
8781 encode_string ((const char*)aname->public_key_token, p, &p);
8783 while (GPOINTER_TO_UINT (p) % 8 != 0)
8786 encode_int (aname->flags, p, &p);
8787 encode_int (aname->major, p, &p);
8788 encode_int (aname->minor, p, &p);
8789 encode_int (aname->build, p, &p);
8790 encode_int (aname->revision, p, &p);
8792 g_assert (p - buf <= buf_size);
8794 emit_aot_data (acfg, MONO_AOT_TABLE_IMAGE_TABLE, "image_table", buf, p - buf);
8800 emit_got_info (MonoAotCompile *acfg, gboolean llvm)
8802 int i, first_plt_got_patch = 0, buf_size;
8804 guint32 *got_info_offsets;
8805 GotInfo *info = llvm ? &acfg->llvm_got_info : &acfg->got_info;
8807 /* Add the patches needed by the PLT to the GOT */
8809 acfg->plt_got_offset_base = acfg->got_offset;
8810 first_plt_got_patch = info->got_patches->len;
8811 for (i = 1; i < acfg->plt_offset; ++i) {
8812 MonoPltEntry *plt_entry = (MonoPltEntry *)g_hash_table_lookup (acfg->plt_offset_to_entry, GUINT_TO_POINTER (i));
8814 g_ptr_array_add (info->got_patches, plt_entry->ji);
8816 acfg->stats.got_slot_types [plt_entry->ji->type] ++;
8819 acfg->got_offset += acfg->plt_offset;
8824 * - optimize offsets table.
8825 * - reduce number of exported symbols.
8826 * - emit info for a klass only once.
8827 * - determine when a method uses a GOT slot which is guaranteed to be already
8829 * - clean up and document the code.
8830 * - use String.Empty in class libs.
8833 /* Encode info required to decode shared GOT entries */
8834 buf_size = info->got_patches->len * 128;
8835 p = buf = (guint8 *)mono_mempool_alloc (acfg->mempool, buf_size);
8836 got_info_offsets = (guint32 *)mono_mempool_alloc (acfg->mempool, info->got_patches->len * sizeof (guint32));
8838 acfg->plt_got_info_offsets = (guint32 *)mono_mempool_alloc (acfg->mempool, acfg->plt_offset * sizeof (guint32));
8840 if (acfg->plt_offset)
8841 acfg->plt_got_info_offsets [0] = 0;
8843 for (i = 0; i < info->got_patches->len; ++i) {
8844 MonoJumpInfo *ji = (MonoJumpInfo *)g_ptr_array_index (info->got_patches, i);
8849 encode_value (ji->type, p, &p);
8851 encode_patch (acfg, ji, p, &p);
8852 acfg->stats.got_slot_info_sizes [ji->type] += p - p2;
8853 g_assert (p - buf <= buf_size);
8854 got_info_offsets [i] = add_to_blob (acfg, buf, p - buf);
8856 if (!llvm && i >= first_plt_got_patch)
8857 acfg->plt_got_info_offsets [i - first_plt_got_patch + 1] = got_info_offsets [i];
8858 acfg->stats.got_info_size += p - buf;
8861 /* Emit got_info_offsets table */
8863 /* No need to emit offsets for the got plt entries, the plt embeds them directly */
8864 acfg->stats.offsets_size += emit_offset_table (acfg, llvm ? "llvm_got_info_offsets" : "got_info_offsets", llvm ? MONO_AOT_TABLE_LLVM_GOT_INFO_OFFSETS : MONO_AOT_TABLE_GOT_INFO_OFFSETS, llvm ? acfg->llvm_got_offset : first_plt_got_patch, 10, (gint32*)got_info_offsets);
8868 emit_got (MonoAotCompile *acfg)
8872 if (acfg->aot_opts.llvm_only)
8875 /* Don't make GOT global so accesses to it don't need relocations */
8876 sprintf (symbol, "%s", acfg->got_symbol);
8879 emit_unset_mode (acfg);
8880 fprintf (acfg->fp, ".section __DATA, __bss\n");
8881 emit_alignment (acfg, 8);
8883 emit_info_symbol (acfg, "jit_got");
8884 fprintf (acfg->fp, ".lcomm %s, %d\n", acfg->got_symbol, (int)(acfg->got_offset * sizeof (gpointer)));
8886 emit_section_change (acfg, ".bss", 0);
8887 emit_alignment (acfg, 8);
8888 emit_local_symbol (acfg, symbol, "got_end", FALSE);
8889 emit_label (acfg, symbol);
8891 emit_info_symbol (acfg, "jit_got");
8892 if (acfg->got_offset > 0)
8893 emit_zero_bytes (acfg, (int)(acfg->got_offset * sizeof (gpointer)));
8896 sprintf (symbol, "got_end");
8897 emit_label (acfg, symbol);
8900 typedef struct GlobalsTableEntry {
8901 guint32 value, index;
8902 struct GlobalsTableEntry *next;
8903 } GlobalsTableEntry;
8906 emit_globals (MonoAotCompile *acfg)
8912 GlobalsTableEntry *entry, *new_entry;
8914 if (!acfg->aot_opts.static_link)
8916 if (acfg->aot_opts.llvm_only) {
8917 g_assert (acfg->globals->len == 0);
8922 * When static linking, we emit a table containing our globals.
8926 * Construct a chained hash table for mapping global names to their index in
8927 * the globals table.
8929 table_size = g_spaced_primes_closest ((int)(acfg->globals->len * 1.5));
8930 table = g_ptr_array_sized_new (table_size);
8931 for (i = 0; i < table_size; ++i)
8932 g_ptr_array_add (table, NULL);
8933 for (i = 0; i < acfg->globals->len; ++i) {
8934 char *name = (char *)g_ptr_array_index (acfg->globals, i);
8936 hash = mono_metadata_str_hash (name) % table_size;
8938 /* FIXME: Allocate from the mempool */
8939 new_entry = g_new0 (GlobalsTableEntry, 1);
8940 new_entry->value = i;
8942 entry = (GlobalsTableEntry *)g_ptr_array_index (table, hash);
8943 if (entry == NULL) {
8944 new_entry->index = hash;
8945 g_ptr_array_index (table, hash) = new_entry;
8948 entry = entry->next;
8950 entry->next = new_entry;
8951 new_entry->index = table->len;
8952 g_ptr_array_add (table, new_entry);
8956 /* Emit the table */
8957 sprintf (symbol, ".Lglobals_hash");
8958 emit_section_change (acfg, RODATA_SECT, 0);
8959 emit_alignment (acfg, 8);
8960 emit_label (acfg, symbol);
8962 /* FIXME: Optimize memory usage */
8963 g_assert (table_size < 65000);
8964 emit_int16 (acfg, table_size);
8965 for (i = 0; i < table->len; ++i) {
8966 GlobalsTableEntry *entry = (GlobalsTableEntry *)g_ptr_array_index (table, i);
8968 if (entry == NULL) {
8969 emit_int16 (acfg, 0);
8970 emit_int16 (acfg, 0);
8972 emit_int16 (acfg, entry->value + 1);
8974 emit_int16 (acfg, entry->next->index);
8976 emit_int16 (acfg, 0);
8980 /* Emit the names */
8981 for (i = 0; i < acfg->globals->len; ++i) {
8982 char *name = (char *)g_ptr_array_index (acfg->globals, i);
8984 sprintf (symbol, "name_%d", i);
8985 emit_section_change (acfg, RODATA_SECT, 1);
8987 emit_alignment (acfg, 4);
8989 emit_label (acfg, symbol);
8990 emit_string (acfg, name);
8993 /* Emit the globals table */
8994 sprintf (symbol, "globals");
8995 emit_section_change (acfg, ".data", 0);
8996 /* This is not a global, since it is accessed by the init function */
8997 emit_alignment (acfg, 8);
8998 emit_info_symbol (acfg, symbol);
9000 sprintf (symbol, "%sglobals_hash", acfg->temp_prefix);
9001 emit_pointer (acfg, symbol);
9003 for (i = 0; i < acfg->globals->len; ++i) {
9004 char *name = (char *)g_ptr_array_index (acfg->globals, i);
9006 sprintf (symbol, "name_%d", i);
9007 emit_pointer (acfg, symbol);
9009 g_assert (strlen (name) < sizeof (symbol));
9010 sprintf (symbol, "%s", name);
9011 emit_pointer (acfg, symbol);
9013 /* Null terminate the table */
9014 emit_int32 (acfg, 0);
9015 emit_int32 (acfg, 0);
9019 emit_mem_end (MonoAotCompile *acfg)
9023 if (acfg->aot_opts.llvm_only)
9026 sprintf (symbol, "mem_end");
9027 emit_section_change (acfg, ".text", 1);
9028 emit_alignment_code (acfg, 8);
9029 emit_label (acfg, symbol);
9033 init_aot_file_info (MonoAotCompile *acfg, MonoAotFileInfo *info)
9037 info->version = MONO_AOT_FILE_VERSION;
9038 info->plt_got_offset_base = acfg->plt_got_offset_base;
9039 info->got_size = acfg->got_offset * sizeof (gpointer);
9040 info->plt_size = acfg->plt_offset;
9041 info->nmethods = acfg->nmethods;
9042 info->flags = acfg->flags;
9043 info->opts = acfg->opts;
9044 info->simd_opts = acfg->simd_opts;
9045 info->gc_name_index = acfg->gc_name_offset;
9046 info->datafile_size = acfg->datafile_offset;
9047 for (i = 0; i < MONO_AOT_TABLE_NUM; ++i)
9048 info->table_offsets [i] = acfg->table_offsets [i];
9049 for (i = 0; i < MONO_AOT_TRAMP_NUM; ++i)
9050 info->num_trampolines [i] = acfg->num_trampolines [i];
9051 for (i = 0; i < MONO_AOT_TRAMP_NUM; ++i)
9052 info->trampoline_got_offset_base [i] = acfg->trampoline_got_offset_base [i];
9053 for (i = 0; i < MONO_AOT_TRAMP_NUM; ++i)
9054 info->trampoline_size [i] = acfg->trampoline_size [i];
9055 info->num_rgctx_fetch_trampolines = acfg->aot_opts.nrgctx_fetch_trampolines;
9057 info->double_align = MONO_ABI_ALIGNOF (double);
9058 info->long_align = MONO_ABI_ALIGNOF (gint64);
9059 info->generic_tramp_num = MONO_TRAMPOLINE_NUM;
9060 info->tramp_page_size = acfg->tramp_page_size;
9061 info->nshared_got_entries = acfg->nshared_got_entries;
9062 for (i = 0; i < MONO_AOT_TRAMP_NUM; ++i)
9063 info->tramp_page_code_offsets [i] = acfg->tramp_page_code_offsets [i];
9067 emit_aot_file_info (MonoAotCompile *acfg, MonoAotFileInfo *info)
9071 const char **symbols;
9073 symbols = g_new0 (const char *, MONO_AOT_FILE_INFO_NUM_SYMBOLS);
9075 symbols [sindex ++] = acfg->got_symbol;
9077 symbols [sindex ++] = g_strdup_printf ("%s%s", acfg->user_symbol_prefix, acfg->llvm_got_symbol);
9078 symbols [sindex ++] = acfg->llvm_eh_frame_symbol;
9080 symbols [sindex ++] = NULL;
9081 symbols [sindex ++] = NULL;
9083 /* llvm_get_method */
9084 symbols [sindex ++] = NULL;
9085 /* llvm_get_unbox_tramp */
9086 symbols [sindex ++] = NULL;
9087 if (!acfg->aot_opts.llvm_only) {
9088 symbols [sindex ++] = "jit_code_start";
9089 symbols [sindex ++] = "jit_code_end";
9090 symbols [sindex ++] = "method_addresses";
9092 symbols [sindex ++] = NULL;
9093 symbols [sindex ++] = NULL;
9094 symbols [sindex ++] = NULL;
9096 if (acfg->data_outfile) {
9097 for (i = 0; i < MONO_AOT_TABLE_NUM; ++i)
9098 symbols [sindex ++] = NULL;
9100 symbols [sindex ++] = "blob";
9101 symbols [sindex ++] = "class_name_table";
9102 symbols [sindex ++] = "class_info_offsets";
9103 symbols [sindex ++] = "method_info_offsets";
9104 symbols [sindex ++] = "ex_info_offsets";
9105 symbols [sindex ++] = "extra_method_info_offsets";
9106 symbols [sindex ++] = "extra_method_table";
9107 symbols [sindex ++] = "got_info_offsets";
9109 symbols [sindex ++] = "llvm_got_info_offsets";
9111 symbols [sindex ++] = NULL;
9112 symbols [sindex ++] = "image_table";
9114 symbols [sindex ++] = "mem_end";
9115 symbols [sindex ++] = "assembly_guid";
9116 symbols [sindex ++] = "runtime_version";
9117 if (acfg->num_trampoline_got_entries) {
9118 symbols [sindex ++] = "specific_trampolines";
9119 symbols [sindex ++] = "static_rgctx_trampolines";
9120 symbols [sindex ++] = "imt_thunks";
9121 symbols [sindex ++] = "gsharedvt_arg_trampolines";
9123 symbols [sindex ++] = NULL;
9124 symbols [sindex ++] = NULL;
9125 symbols [sindex ++] = NULL;
9126 symbols [sindex ++] = NULL;
9128 if (acfg->aot_opts.static_link) {
9129 symbols [sindex ++] = "globals";
9131 symbols [sindex ++] = NULL;
9133 symbols [sindex ++] = "assembly_name";
9134 symbols [sindex ++] = "plt";
9135 symbols [sindex ++] = "plt_end";
9136 symbols [sindex ++] = "unwind_info";
9137 if (!acfg->aot_opts.llvm_only) {
9138 symbols [sindex ++] = "unbox_trampolines";
9139 symbols [sindex ++] = "unbox_trampolines_end";
9140 symbols [sindex ++] = "unbox_trampoline_addresses";
9142 symbols [sindex ++] = NULL;
9143 symbols [sindex ++] = NULL;
9144 symbols [sindex ++] = NULL;
9147 g_assert (sindex == MONO_AOT_FILE_INFO_NUM_SYMBOLS);
9149 sprintf (symbol, "%smono_aot_file_info", acfg->user_symbol_prefix);
9150 emit_section_change (acfg, ".data", 0);
9151 emit_alignment (acfg, 8);
9152 emit_label (acfg, symbol);
9153 if (!acfg->aot_opts.static_link)
9154 emit_global (acfg, symbol, FALSE);
9156 /* The data emitted here must match MonoAotFileInfo. */
9158 emit_int32 (acfg, info->version);
9159 emit_int32 (acfg, info->dummy);
9162 * We emit pointers to our data structures instead of emitting global symbols which
9163 * point to them, to reduce the number of globals, and because using globals leads to
9164 * various problems (i.e. arm/thumb).
9166 for (i = 0; i < MONO_AOT_FILE_INFO_NUM_SYMBOLS; ++i)
9167 emit_pointer (acfg, symbols [i]);
9169 emit_int32 (acfg, info->plt_got_offset_base);
9170 emit_int32 (acfg, info->got_size);
9171 emit_int32 (acfg, info->plt_size);
9172 emit_int32 (acfg, info->nmethods);
9173 emit_int32 (acfg, info->flags);
9174 emit_int32 (acfg, info->opts);
9175 emit_int32 (acfg, info->simd_opts);
9176 emit_int32 (acfg, info->gc_name_index);
9177 emit_int32 (acfg, info->num_rgctx_fetch_trampolines);
9178 emit_int32 (acfg, info->double_align);
9179 emit_int32 (acfg, info->long_align);
9180 emit_int32 (acfg, info->generic_tramp_num);
9181 emit_int32 (acfg, info->tramp_page_size);
9182 emit_int32 (acfg, info->nshared_got_entries);
9183 emit_int32 (acfg, info->datafile_size);
9185 for (i = 0; i < MONO_AOT_TABLE_NUM; ++i)
9186 emit_int32 (acfg, info->table_offsets [i]);
9187 for (i = 0; i < MONO_AOT_TRAMP_NUM; ++i)
9188 emit_int32 (acfg, info->num_trampolines [i]);
9189 for (i = 0; i < MONO_AOT_TRAMP_NUM; ++i)
9190 emit_int32 (acfg, info->trampoline_got_offset_base [i]);
9191 for (i = 0; i < MONO_AOT_TRAMP_NUM; ++i)
9192 emit_int32 (acfg, info->trampoline_size [i]);
9193 for (i = 0; i < MONO_AOT_TRAMP_NUM; ++i)
9194 emit_int32 (acfg, info->tramp_page_code_offsets [i]);
9196 if (acfg->aot_opts.static_link) {
9197 emit_global_inner (acfg, acfg->static_linking_symbol, FALSE);
9198 emit_alignment (acfg, sizeof (gpointer));
9199 emit_label (acfg, acfg->static_linking_symbol);
9200 emit_pointer_2 (acfg, acfg->user_symbol_prefix, "mono_aot_file_info");
9205 * Emit a structure containing all the information not stored elsewhere.
9208 emit_file_info (MonoAotCompile *acfg)
9211 MonoAotFileInfo *info;
9213 if (acfg->aot_opts.bind_to_runtime_version) {
9214 build_info = mono_get_runtime_build_info ();
9215 emit_string_symbol (acfg, "runtime_version", build_info);
9216 g_free (build_info);
9218 emit_string_symbol (acfg, "runtime_version", "");
9221 emit_string_symbol (acfg, "assembly_guid" , acfg->image->guid);
9223 /* Emit a string holding the assembly name */
9224 emit_string_symbol (acfg, "assembly_name", acfg->image->assembly->aname.name);
9226 info = g_new0 (MonoAotFileInfo, 1);
9227 init_aot_file_info (acfg, info);
9229 if (acfg->aot_opts.static_link) {
9234 * Emit a global symbol which can be passed by an embedding app to
9235 * mono_aot_register_module (). The symbol points to a pointer to the the file info
9238 sprintf (symbol, "%smono_aot_module_%s_info", acfg->user_symbol_prefix, acfg->image->assembly->aname.name);
9240 /* Get rid of characters which cannot occur in symbols */
9242 for (p = symbol; *p; ++p) {
9243 if (!(isalnum (*p) || *p == '_'))
9246 acfg->static_linking_symbol = g_strdup (symbol);
9250 mono_llvm_emit_aot_file_info (info, acfg->has_jitted_code);
9252 emit_aot_file_info (acfg, info);
9256 emit_blob (MonoAotCompile *acfg)
9258 acfg->blob_closed = TRUE;
9260 emit_aot_data (acfg, MONO_AOT_TABLE_BLOB, "blob", (guint8*)acfg->blob.data, acfg->blob.index);
9264 emit_objc_selectors (MonoAotCompile *acfg)
9269 if (!acfg->objc_selectors || acfg->objc_selectors->len == 0)
9274 * cat > foo.m << EOF
9277 * return @selector(print:);
9282 mono_img_writer_emit_unset_mode (acfg->w);
9283 g_assert (acfg->fp);
9284 fprintf (acfg->fp, ".section __DATA,__objc_selrefs,literal_pointers,no_dead_strip\n");
9285 fprintf (acfg->fp, ".align 3\n");
9286 for (i = 0; i < acfg->objc_selectors->len; ++i) {
9287 sprintf (symbol, "L_OBJC_SELECTOR_REFERENCES_%d", i);
9288 emit_label (acfg, symbol);
9289 sprintf (symbol, "L_OBJC_METH_VAR_NAME_%d", i);
9290 emit_pointer (acfg, symbol);
9293 fprintf (acfg->fp, ".section __TEXT,__cstring,cstring_literals\n");
9294 for (i = 0; i < acfg->objc_selectors->len; ++i) {
9295 fprintf (acfg->fp, "L_OBJC_METH_VAR_NAME_%d:\n", i);
9296 fprintf (acfg->fp, ".asciz \"%s\"\n", (char*)g_ptr_array_index (acfg->objc_selectors, i));
9299 fprintf (acfg->fp, ".section __DATA,__objc_imageinfo,regular,no_dead_strip\n");
9300 fprintf (acfg->fp, ".align 3\n");
9301 fprintf (acfg->fp, "L_OBJC_IMAGE_INFO:\n");
9302 fprintf (acfg->fp, ".long 0\n");
9303 fprintf (acfg->fp, ".long 16\n");
9307 emit_dwarf_info (MonoAotCompile *acfg)
9309 #ifdef EMIT_DWARF_INFO
9313 /* DIEs for methods */
9314 for (i = 0; i < acfg->nmethods; ++i) {
9315 MonoCompile *cfg = acfg->cfgs [i];
9320 // FIXME: LLVM doesn't define .Lme_...
9321 if (cfg->compile_llvm)
9324 sprintf (symbol2, "%sme_%x", acfg->temp_prefix, i);
9326 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 ()));
9332 collect_methods (MonoAotCompile *acfg)
9335 MonoImage *image = acfg->image;
9337 /* Collect methods */
9338 for (i = 0; i < image->tables [MONO_TABLE_METHOD].rows; ++i) {
9341 guint32 token = MONO_TOKEN_METHOD_DEF | (i + 1);
9343 method = mono_get_method_checked (acfg->image, token, NULL, NULL, &error);
9346 aot_printerrf (acfg, "Failed to load method 0x%x from '%s' due to %s.\n", token, image->name, mono_error_get_message (&error));
9347 aot_printerrf (acfg, "Run with MONO_LOG_LEVEL=debug for more information.\n");
9348 mono_error_cleanup (&error);
9352 /* Load all methods eagerly to skip the slower lazy loading code */
9353 mono_class_setup_methods (method->klass);
9355 if (mono_aot_mode_is_full (&acfg->aot_opts) && method->iflags & METHOD_IMPL_ATTRIBUTE_INTERNAL_CALL) {
9356 /* Compile the wrapper instead */
9357 /* We do this here instead of add_wrappers () because it is easy to do it here */
9358 MonoMethod *wrapper = mono_marshal_get_native_wrapper (method, TRUE, TRUE);
9362 /* FIXME: Some mscorlib methods don't have debug info */
9364 if (acfg->aot_opts.soft_debug && !method->wrapper_type) {
9365 if (!((method->flags & METHOD_ATTRIBUTE_PINVOKE_IMPL) ||
9366 (method->iflags & METHOD_IMPL_ATTRIBUTE_RUNTIME) ||
9367 (method->flags & METHOD_ATTRIBUTE_ABSTRACT) ||
9368 (method->iflags & METHOD_IMPL_ATTRIBUTE_INTERNAL_CALL))) {
9369 if (!mono_debug_lookup_method (method)) {
9370 fprintf (stderr, "Method %s has no debug info, probably the .mdb file for the assembly is missing.\n", mono_method_get_full_name (method));
9377 if (method->is_generic || method->klass->generic_container)
9378 /* Compile the ref shared version instead */
9379 method = mini_get_shared_method (method);
9381 /* Since we add the normal methods first, their index will be equal to their zero based token index */
9382 add_method_with_index (acfg, method, i, FALSE);
9383 acfg->method_index ++;
9386 /* gsharedvt methods */
9387 for (mindex = 0; mindex < image->tables [MONO_TABLE_METHOD].rows; ++mindex) {
9390 guint32 token = MONO_TOKEN_METHOD_DEF | (mindex + 1);
9392 if (!(acfg->opts & MONO_OPT_GSHAREDVT))
9395 method = mono_get_method_checked (acfg->image, token, NULL, NULL, &error);
9396 report_loader_error (acfg, &error, "Failed to load method token 0x%x due to %s\n", i, mono_error_get_message (&error));
9398 if (method->is_generic || method->klass->generic_container) {
9399 MonoMethod *gshared;
9401 gshared = mini_get_shared_method_full (method, TRUE, TRUE);
9402 add_extra_method (acfg, gshared);
9406 add_generic_instances (acfg);
9408 if (mono_aot_mode_is_full (&acfg->aot_opts))
9409 add_wrappers (acfg);
9414 compile_methods (MonoAotCompile *acfg)
9418 if (acfg->aot_opts.nthreads > 0) {
9423 gpointer *user_data;
9424 MonoMethod **methods;
9426 methods_len = acfg->methods->len;
9428 len = acfg->methods->len / acfg->aot_opts.nthreads;
9431 * Partition the list of methods into fragments, and hand it to threads to
9434 threads = g_ptr_array_new ();
9435 /* Make a copy since acfg->methods is modified by compile_method () */
9436 methods = g_new0 (MonoMethod*, methods_len);
9437 //memcpy (methods, g_ptr_array_index (acfg->methods, 0), sizeof (MonoMethod*) * methods_len);
9438 for (i = 0; i < methods_len; ++i)
9439 methods [i] = (MonoMethod *)g_ptr_array_index (acfg->methods, i);
9441 while (i < methods_len) {
9442 frag = g_ptr_array_new ();
9443 for (j = 0; j < len; ++j) {
9444 if (i < methods_len) {
9445 g_ptr_array_add (frag, methods [i]);
9450 user_data = g_new0 (gpointer, 3);
9451 user_data [0] = mono_domain_get ();
9452 user_data [1] = acfg;
9453 user_data [2] = frag;
9455 handle = mono_threads_create_thread ((LPTHREAD_START_ROUTINE)compile_thread_main, user_data, 0, 0, NULL);
9456 g_ptr_array_add (threads, handle);
9460 for (i = 0; i < threads->len; ++i) {
9461 WaitForSingleObjectEx (g_ptr_array_index (threads, i), INFINITE, FALSE);
9467 /* Compile methods added by compile_method () or all methods if nthreads == 0 */
9468 for (i = methods_len; i < acfg->methods->len; ++i) {
9469 /* This can new methods to acfg->methods */
9470 compile_method (acfg, (MonoMethod *)g_ptr_array_index (acfg->methods, i));
9475 compile_asm (MonoAotCompile *acfg)
9477 char *command, *objfile;
9478 char *outfile_name, *tmp_outfile_name, *llvm_ofile;
9479 const char *tool_prefix = acfg->aot_opts.tool_prefix ? acfg->aot_opts.tool_prefix : "";
9480 char *ld_flags = acfg->aot_opts.ld_flags ? acfg->aot_opts.ld_flags : g_strdup("");
9482 #if defined(TARGET_AMD64) && !defined(TARGET_MACH)
9483 #define AS_OPTIONS "--64"
9484 #elif defined(TARGET_POWERPC64)
9485 #define AS_OPTIONS "-a64 -mppc64"
9486 #define LD_OPTIONS "-m elf64ppc"
9487 #elif defined(sparc) && SIZEOF_VOID_P == 8
9488 #define AS_OPTIONS "-xarch=v9"
9489 #elif defined(TARGET_X86) && defined(TARGET_MACH) && !defined(__native_client_codegen__)
9490 #define AS_OPTIONS "-arch i386"
9492 #define AS_OPTIONS ""
9495 #ifdef __native_client_codegen__
9496 #if defined(TARGET_AMD64)
9497 #define AS_NAME "nacl64-as"
9499 #define AS_NAME "nacl-as"
9501 #elif defined(TARGET_OSX)
9502 #define AS_NAME "clang"
9504 #define AS_NAME "as"
9508 #define LD_OPTIONS ""
9512 #define LD_NAME "ld -shared -G"
9513 #elif defined(__ppc__) && defined(TARGET_MACH)
9514 #define LD_NAME "gcc -dynamiclib"
9515 #elif defined(TARGET_AMD64) && defined(TARGET_MACH)
9516 #define LD_NAME "clang --shared"
9517 #elif defined(TARGET_WIN32) && !defined(TARGET_ANDROID)
9518 #define LD_NAME "gcc -shared --dll"
9519 #elif defined(TARGET_X86) && defined(TARGET_MACH) && !defined(__native_client_codegen__)
9520 #define LD_NAME "clang -m32 -dynamiclib"
9521 #elif defined(TARGET_ARM) && !defined(TARGET_ANDROID)
9522 #define LD_NAME "gcc --shared"
9525 if (acfg->aot_opts.asm_only) {
9526 aot_printf (acfg, "Output file: '%s'.\n", acfg->tmpfname);
9527 if (acfg->aot_opts.static_link)
9528 aot_printf (acfg, "Linking symbol: '%s'.\n", acfg->static_linking_symbol);
9530 aot_printf (acfg, "LLVM output file: '%s'.\n", acfg->llvm_sfile);
9534 if (acfg->aot_opts.static_link) {
9535 if (acfg->aot_opts.outfile)
9536 objfile = g_strdup_printf ("%s", acfg->aot_opts.outfile);
9538 objfile = g_strdup_printf ("%s.o", acfg->image->name);
9540 objfile = g_strdup_printf ("%s.o", acfg->tmpfname);
9544 g_string_append (acfg->as_args, "-c -x assembler");
9547 command = g_strdup_printf ("\"%s%s\" %s %s -o %s %s", tool_prefix, AS_NAME, AS_OPTIONS,
9548 acfg->as_args ? acfg->as_args->str : "",
9549 wrap_path (objfile), wrap_path (acfg->tmpfname));
9550 aot_printf (acfg, "Executing the native assembler: %s\n", command);
9551 if (execute_system (command) != 0) {
9557 if (acfg->llvm && !acfg->llvm_owriter) {
9558 command = g_strdup_printf ("\"%s%s\" %s %s -o %s %s", tool_prefix, AS_NAME, AS_OPTIONS,
9559 acfg->as_args ? acfg->as_args->str : "",
9560 wrap_path (acfg->llvm_ofile), wrap_path (acfg->llvm_sfile));
9561 aot_printf (acfg, "Executing the native assembler: %s\n", command);
9562 if (execute_system (command) != 0) {
9571 if (acfg->aot_opts.static_link) {
9572 aot_printf (acfg, "Output file: '%s'.\n", objfile);
9573 aot_printf (acfg, "Linking symbol: '%s'.\n", acfg->static_linking_symbol);
9578 if (acfg->aot_opts.outfile)
9579 outfile_name = g_strdup_printf ("%s", acfg->aot_opts.outfile);
9581 outfile_name = g_strdup_printf ("%s%s", acfg->image->name, MONO_SOLIB_EXT);
9583 tmp_outfile_name = g_strdup_printf ("%s.tmp", outfile_name);
9586 llvm_ofile = g_strdup_printf ("\"%s\"", acfg->llvm_ofile);
9588 llvm_ofile = g_strdup ("");
9591 /* replace the ; flags separators with spaces */
9592 g_strdelimit (ld_flags, ";", ' ');
9594 if (acfg->aot_opts.llvm_only)
9595 ld_flags = g_strdup_printf ("%s %s", ld_flags, "-lstdc++");
9598 command = g_strdup_printf ("%s -o %s %s %s %s", LD_NAME,
9599 wrap_path (tmp_outfile_name), wrap_path (llvm_ofile),
9600 wrap_path (g_strdup_printf ("%s.o", acfg->tmpfname)), ld_flags);
9602 command = g_strdup_printf ("\"%sld\" %s -shared -o %s %s %s %s", tool_prefix, LD_OPTIONS,
9603 wrap_path (tmp_outfile_name), wrap_path (llvm_ofile),
9604 wrap_path (g_strdup_printf ("%s.o", acfg->tmpfname)), ld_flags);
9606 aot_printf (acfg, "Executing the native linker: %s\n", command);
9607 if (execute_system (command) != 0) {
9608 g_free (tmp_outfile_name);
9609 g_free (outfile_name);
9618 /*com = g_strdup_printf ("strip --strip-unneeded %s%s", acfg->image->name, MONO_SOLIB_EXT);
9619 printf ("Stripping the binary: %s\n", com);
9620 execute_system (com);
9623 #if defined(TARGET_ARM) && !defined(TARGET_MACH)
9625 * gas generates 'mapping symbols' each time code and data is mixed, which
9626 * happens a lot in emit_and_reloc_code (), so we need to get rid of them.
9628 command = g_strdup_printf ("\"%sstrip\" --strip-symbol=\\$a --strip-symbol=\\$d %s", tool_prefix, tmp_outfile_name);
9629 aot_printf (acfg, "Stripping the binary: %s\n", command);
9630 if (execute_system (command) != 0) {
9631 g_free (tmp_outfile_name);
9632 g_free (outfile_name);
9639 rename (tmp_outfile_name, outfile_name);
9641 #if defined(TARGET_MACH)
9642 command = g_strdup_printf ("dsymutil \"%s\"", outfile_name);
9643 aot_printf (acfg, "Executing dsymutil: %s\n", command);
9644 if (execute_system (command) != 0) {
9649 if (!acfg->aot_opts.save_temps)
9652 g_free (tmp_outfile_name);
9653 g_free (outfile_name);
9656 if (acfg->aot_opts.save_temps)
9657 aot_printf (acfg, "Retained input file.\n");
9659 unlink (acfg->tmpfname);
9664 static void init_got_info (GotInfo *info)
9668 info->patch_to_got_offset = g_hash_table_new (mono_patch_info_hash, mono_patch_info_equal);
9669 info->patch_to_got_offset_by_type = g_new0 (GHashTable*, MONO_PATCH_INFO_NUM);
9670 for (i = 0; i < MONO_PATCH_INFO_NUM; ++i)
9671 info->patch_to_got_offset_by_type [i] = g_hash_table_new (mono_patch_info_hash, mono_patch_info_equal);
9672 info->got_patches = g_ptr_array_new ();
9675 static MonoAotCompile*
9676 acfg_create (MonoAssembly *ass, guint32 opts)
9678 MonoImage *image = ass->image;
9679 MonoAotCompile *acfg;
9681 acfg = g_new0 (MonoAotCompile, 1);
9682 acfg->methods = g_ptr_array_new ();
9683 acfg->method_indexes = g_hash_table_new (NULL, NULL);
9684 acfg->method_depth = g_hash_table_new (NULL, NULL);
9685 acfg->plt_offset_to_entry = g_hash_table_new (NULL, NULL);
9686 acfg->patch_to_plt_entry = g_new0 (GHashTable*, MONO_PATCH_INFO_NUM);
9687 acfg->method_to_cfg = g_hash_table_new (NULL, NULL);
9688 acfg->token_info_hash = g_hash_table_new_full (NULL, NULL, NULL, NULL);
9689 acfg->method_to_pinvoke_import = g_hash_table_new_full (NULL, NULL, NULL, g_free);
9690 acfg->image_hash = g_hash_table_new (NULL, NULL);
9691 acfg->image_table = g_ptr_array_new ();
9692 acfg->globals = g_ptr_array_new ();
9693 acfg->image = image;
9695 /* TODO: Write out set of SIMD instructions used, rather than just those available */
9696 acfg->simd_opts = mono_arch_cpu_enumerate_simd_versions ();
9697 acfg->mempool = mono_mempool_new ();
9698 acfg->extra_methods = g_ptr_array_new ();
9699 acfg->unwind_info_offsets = g_hash_table_new (NULL, NULL);
9700 acfg->unwind_ops = g_ptr_array_new ();
9701 acfg->method_label_hash = g_hash_table_new_full (g_str_hash, g_str_equal, g_free, NULL);
9702 acfg->method_order = g_ptr_array_new ();
9703 acfg->export_names = g_hash_table_new (NULL, NULL);
9704 acfg->klass_blob_hash = g_hash_table_new (NULL, NULL);
9705 acfg->method_blob_hash = g_hash_table_new (NULL, NULL);
9706 acfg->plt_entry_debug_sym_cache = g_hash_table_new (g_str_hash, g_str_equal);
9707 acfg->gsharedvt_in_signatures = g_hash_table_new ((GHashFunc)mono_signature_hash, (GEqualFunc)mono_metadata_signature_equal);
9708 acfg->gsharedvt_out_signatures = g_hash_table_new ((GHashFunc)mono_signature_hash, (GEqualFunc)mono_metadata_signature_equal);
9709 mono_os_mutex_init_recursive (&acfg->mutex);
9711 init_got_info (&acfg->got_info);
9712 init_got_info (&acfg->llvm_got_info);
9718 got_info_free (GotInfo *info)
9722 for (i = 0; i < MONO_PATCH_INFO_NUM; ++i)
9723 g_hash_table_destroy (info->patch_to_got_offset_by_type [i]);
9724 g_free (info->patch_to_got_offset_by_type);
9725 g_hash_table_destroy (info->patch_to_got_offset);
9726 g_ptr_array_free (info->got_patches, TRUE);
9730 acfg_free (MonoAotCompile *acfg)
9734 mono_img_writer_destroy (acfg->w);
9735 for (i = 0; i < acfg->nmethods; ++i)
9737 g_free (acfg->cfgs [i]);
9738 g_free (acfg->cfgs);
9739 g_free (acfg->static_linking_symbol);
9740 g_free (acfg->got_symbol);
9741 g_free (acfg->plt_symbol);
9742 g_ptr_array_free (acfg->methods, TRUE);
9743 g_ptr_array_free (acfg->image_table, TRUE);
9744 g_ptr_array_free (acfg->globals, TRUE);
9745 g_ptr_array_free (acfg->unwind_ops, TRUE);
9746 g_hash_table_destroy (acfg->method_indexes);
9747 g_hash_table_destroy (acfg->method_depth);
9748 g_hash_table_destroy (acfg->plt_offset_to_entry);
9749 for (i = 0; i < MONO_PATCH_INFO_NUM; ++i) {
9750 if (acfg->patch_to_plt_entry [i])
9751 g_hash_table_destroy (acfg->patch_to_plt_entry [i]);
9753 g_free (acfg->patch_to_plt_entry);
9754 g_hash_table_destroy (acfg->method_to_cfg);
9755 g_hash_table_destroy (acfg->token_info_hash);
9756 g_hash_table_destroy (acfg->method_to_pinvoke_import);
9757 g_hash_table_destroy (acfg->image_hash);
9758 g_hash_table_destroy (acfg->unwind_info_offsets);
9759 g_hash_table_destroy (acfg->method_label_hash);
9760 g_hash_table_destroy (acfg->export_names);
9761 g_hash_table_destroy (acfg->plt_entry_debug_sym_cache);
9762 g_hash_table_destroy (acfg->klass_blob_hash);
9763 g_hash_table_destroy (acfg->method_blob_hash);
9764 got_info_free (&acfg->got_info);
9765 got_info_free (&acfg->llvm_got_info);
9766 mono_mempool_destroy (acfg->mempool);
9770 #define WRAPPER(e,n) n,
9771 static const char* const
9772 wrapper_type_names [MONO_WRAPPER_NUM + 1] = {
9773 #include "mono/metadata/wrapper-types.h"
9777 static G_GNUC_UNUSED const char*
9778 get_wrapper_type_name (int type)
9780 return wrapper_type_names [type];
9786 static void aot_dump (MonoAotCompile *acfg)
9792 mono_json_writer_init (&writer);
9794 mono_json_writer_object_begin(&writer);
9797 mono_json_writer_indent (&writer);
9798 mono_json_writer_object_key(&writer, "methods");
9799 mono_json_writer_array_begin (&writer);
9802 for (i = 0; i < acfg->nmethods; ++i) {
9807 cfg = acfg->cfgs [i];
9811 method = cfg->orig_method;
9813 mono_json_writer_indent (&writer);
9814 mono_json_writer_object_begin(&writer);
9816 mono_json_writer_indent (&writer);
9817 mono_json_writer_object_key(&writer, "name");
9818 mono_json_writer_printf (&writer, "\"%s\",\n", method->name);
9820 mono_json_writer_indent (&writer);
9821 mono_json_writer_object_key(&writer, "signature");
9822 mono_json_writer_printf (&writer, "\"%s\",\n", mono_method_get_full_name (method));
9824 mono_json_writer_indent (&writer);
9825 mono_json_writer_object_key(&writer, "code_size");
9826 mono_json_writer_printf (&writer, "\"%d\",\n", cfg->code_size);
9828 klass = method->klass;
9830 mono_json_writer_indent (&writer);
9831 mono_json_writer_object_key(&writer, "class");
9832 mono_json_writer_printf (&writer, "\"%s\",\n", klass->name);
9834 mono_json_writer_indent (&writer);
9835 mono_json_writer_object_key(&writer, "namespace");
9836 mono_json_writer_printf (&writer, "\"%s\",\n", klass->name_space);
9838 mono_json_writer_indent (&writer);
9839 mono_json_writer_object_key(&writer, "wrapper_type");
9840 mono_json_writer_printf (&writer, "\"%s\",\n", get_wrapper_type_name(method->wrapper_type));
9842 mono_json_writer_indent_pop (&writer);
9843 mono_json_writer_indent (&writer);
9844 mono_json_writer_object_end (&writer);
9845 mono_json_writer_printf (&writer, ",\n");
9848 mono_json_writer_indent_pop (&writer);
9849 mono_json_writer_indent (&writer);
9850 mono_json_writer_array_end (&writer);
9851 mono_json_writer_printf (&writer, ",\n");
9855 mono_json_writer_indent_push (&writer);
9856 mono_json_writer_indent (&writer);
9857 mono_json_writer_object_key(&writer, "plt");
9858 mono_json_writer_array_begin (&writer);
9860 for (i = 0; i < acfg->plt_offset; ++i) {
9861 MonoPltEntry *plt_entry = NULL;
9866 * The first plt entry is unused.
9870 plt_entry = g_hash_table_lookup (acfg->plt_offset_to_entry, GUINT_TO_POINTER (i));
9873 mono_json_writer_indent (&writer);
9874 mono_json_writer_printf (&writer, "{ ");
9875 mono_json_writer_object_key(&writer, "symbol");
9876 mono_json_writer_printf (&writer, "\"%s\" },\n", plt_entry->symbol);
9879 mono_json_writer_indent_pop (&writer);
9880 mono_json_writer_indent (&writer);
9881 mono_json_writer_array_end (&writer);
9882 mono_json_writer_printf (&writer, ",\n");
9887 mono_json_writer_indent_push (&writer);
9888 mono_json_writer_indent (&writer);
9889 mono_json_writer_object_key(&writer, "got");
9890 mono_json_writer_array_begin (&writer);
9892 mono_json_writer_indent_push (&writer);
9893 for (i = 0; i < acfg->got_info.got_patches->len; ++i) {
9894 MonoJumpInfo *ji = g_ptr_array_index (acfg->got_info.got_patches, i);
9896 mono_json_writer_indent (&writer);
9897 mono_json_writer_printf (&writer, "{ ");
9898 mono_json_writer_object_key(&writer, "patch_name");
9899 mono_json_writer_printf (&writer, "\"%s\" },\n", get_patch_name (ji->type));
9902 mono_json_writer_indent_pop (&writer);
9903 mono_json_writer_indent (&writer);
9904 mono_json_writer_array_end (&writer);
9905 mono_json_writer_printf (&writer, ",\n");
9908 mono_json_writer_indent_pop (&writer);
9909 mono_json_writer_indent (&writer);
9910 mono_json_writer_object_end (&writer);
9912 dumpname = g_strdup_printf ("%s.json", g_path_get_basename (acfg->image->name));
9913 dumpfile = fopen (dumpname, "w+");
9916 fprintf (dumpfile, "%s", writer.text->str);
9919 mono_json_writer_destroy (&writer);
9922 static const char *preinited_jit_icalls[] = {
9923 "mono_aot_init_llvm_method",
9924 "mono_aot_init_gshared_method_this",
9925 "mono_aot_init_gshared_method_mrgctx",
9926 "mono_aot_init_gshared_method_vtable",
9927 "mono_llvm_throw_corlib_exception",
9928 "mono_init_vtable_slot",
9929 "mono_helper_ldstr_mscorlib"
9933 add_preinit_got_slots (MonoAotCompile *acfg)
9939 * Allocate the first few GOT entries to information which is needed frequently, or it is needed
9940 * during method initialization etc.
9943 ji = (MonoJumpInfo *)mono_mempool_alloc0 (acfg->mempool, sizeof (MonoJumpInfo));
9944 ji->type = MONO_PATCH_INFO_IMAGE;
9945 ji->data.image = acfg->image;
9946 get_got_offset (acfg, FALSE, ji);
9947 get_got_offset (acfg, TRUE, ji);
9949 ji = (MonoJumpInfo *)mono_mempool_alloc0 (acfg->mempool, sizeof (MonoJumpInfo));
9950 ji->type = MONO_PATCH_INFO_MSCORLIB_GOT_ADDR;
9951 get_got_offset (acfg, FALSE, ji);
9952 get_got_offset (acfg, TRUE, ji);
9954 ji = (MonoJumpInfo *)mono_mempool_alloc0 (acfg->mempool, sizeof (MonoJumpInfo));
9955 ji->type = MONO_PATCH_INFO_GC_CARD_TABLE_ADDR;
9956 get_got_offset (acfg, FALSE, ji);
9957 get_got_offset (acfg, TRUE, ji);
9959 ji = (MonoJumpInfo *)mono_mempool_alloc0 (acfg->mempool, sizeof (MonoJumpInfo));
9960 ji->type = MONO_PATCH_INFO_GC_NURSERY_START;
9961 get_got_offset (acfg, FALSE, ji);
9962 get_got_offset (acfg, TRUE, ji);
9964 ji = (MonoJumpInfo *)mono_mempool_alloc0 (acfg->mempool, sizeof (MonoJumpInfo));
9965 ji->type = MONO_PATCH_INFO_JIT_TLS_ID;
9966 get_got_offset (acfg, FALSE, ji);
9967 get_got_offset (acfg, TRUE, ji);
9969 ji = (MonoJumpInfo *)mono_mempool_alloc0 (acfg->mempool, sizeof (MonoJumpInfo));
9970 ji->type = MONO_PATCH_INFO_AOT_MODULE;
9971 get_got_offset (acfg, FALSE, ji);
9972 get_got_offset (acfg, TRUE, ji);
9974 ji = (MonoJumpInfo *)mono_mempool_alloc0 (acfg->mempool, sizeof (MonoJumpInfo));
9975 ji->type = MONO_PATCH_INFO_GC_NURSERY_BITS;
9976 get_got_offset (acfg, FALSE, ji);
9977 get_got_offset (acfg, TRUE, ji);
9979 for (i = 0; i < sizeof (preinited_jit_icalls) / sizeof (char*); ++i) {
9980 ji = (MonoJumpInfo *)mono_mempool_alloc0 (acfg->mempool, sizeof (MonoAotCompile));
9981 ji->type = MONO_PATCH_INFO_INTERNAL_METHOD;
9982 ji->data.name = preinited_jit_icalls [i];
9983 get_got_offset (acfg, FALSE, ji);
9984 get_got_offset (acfg, TRUE, ji);
9987 acfg->nshared_got_entries = acfg->got_offset;
9991 mono_compile_assembly (MonoAssembly *ass, guint32 opts, const char *aot_options)
9993 MonoImage *image = ass->image;
9996 MonoAotCompile *acfg;
9997 char *outfile_name, *tmp_outfile_name, *p;
9998 char llvm_stats_msg [256];
10002 acfg = acfg_create (ass, opts);
10004 memset (&acfg->aot_opts, 0, sizeof (acfg->aot_opts));
10005 acfg->aot_opts.write_symbols = TRUE;
10006 acfg->aot_opts.ntrampolines = 1024;
10007 acfg->aot_opts.nrgctx_trampolines = 1024;
10008 acfg->aot_opts.nimt_trampolines = 128;
10009 acfg->aot_opts.nrgctx_fetch_trampolines = 128;
10010 acfg->aot_opts.ngsharedvt_arg_trampolines = 128;
10011 acfg->aot_opts.llvm_path = g_strdup ("");
10012 acfg->aot_opts.temp_path = g_strdup ("");
10014 acfg->aot_opts.use_trampolines_page = TRUE;
10017 mono_aot_parse_options (aot_options, &acfg->aot_opts);
10019 if (acfg->aot_opts.logfile) {
10020 acfg->logfile = fopen (acfg->aot_opts.logfile, "a+");
10023 if (acfg->aot_opts.data_outfile) {
10024 acfg->data_outfile = fopen (acfg->aot_opts.data_outfile, "w+");
10025 if (!acfg->data_outfile) {
10026 aot_printerrf (acfg, "Unable to create file '%s': %s\n", acfg->aot_opts.data_outfile, strerror (errno));
10029 acfg->flags = (MonoAotFileFlags)(acfg->flags | MONO_AOT_FILE_FLAG_SEPARATE_DATA);
10032 //acfg->aot_opts.print_skipped_methods = TRUE;
10034 #if !defined(ENABLE_GSHAREDVT)
10035 if (opts & MONO_OPT_GSHAREDVT) {
10036 aot_printerrf (acfg, "-O=gsharedvt not supported on this platform.\n");
10041 #if !defined(MONO_ARCH_GSHAREDVT_SUPPORTED)
10042 if (!acfg->aot_opts.llvm_only && (opts & MONO_OPT_GSHAREDVT)) {
10043 aot_printerrf (acfg, "-O=gsharedvt not supported on this platform.\n");
10048 if (acfg->aot_opts.llvm_only) {
10049 #ifndef ENABLE_GSHAREDVT
10050 aot_printerrf (acfg, "--aot=llvmonly requires a runtime compiled with --enable-gsharedvt.\n");
10055 #if defined(ENABLE_GSHAREDVT) && defined(MONO_ARCH_GSHAREDVT_SUPPORTED)
10056 acfg->opts |= MONO_OPT_GSHAREDVT;
10057 opts |= MONO_OPT_GSHAREDVT;
10060 if (opts & MONO_OPT_GSHAREDVT)
10061 mono_set_generic_sharing_vt_supported (TRUE);
10063 aot_printf (acfg, "Mono Ahead of Time compiler - compiling assembly %s\n", image->name);
10065 #ifndef MONO_ARCH_HAVE_FULL_AOT_TRAMPOLINES
10066 if (mono_aot_mode_is_full (&acfg->aot_opts)) {
10067 aot_printerrf (acfg, "--aot=full is not supported on this platform.\n");
10072 if (acfg->aot_opts.direct_pinvoke && !acfg->aot_opts.static_link) {
10073 aot_printerrf (acfg, "The 'direct-pinvoke' AOT option also requires the 'static' AOT option.\n");
10077 if (acfg->aot_opts.static_link)
10078 acfg->aot_opts.asm_writer = TRUE;
10080 if (acfg->aot_opts.soft_debug) {
10081 MonoDebugOptions *opt = mini_get_debug_options ();
10083 opt->mdb_optimizations = TRUE;
10084 opt->gen_sdb_seq_points = TRUE;
10086 if (!mono_debug_enabled ()) {
10087 aot_printerrf (acfg, "The soft-debug AOT option requires the --debug option.\n");
10090 acfg->flags = (MonoAotFileFlags)(acfg->flags | MONO_AOT_FILE_FLAG_DEBUG);
10093 if (mono_use_llvm || acfg->aot_opts.llvm) {
10095 acfg->aot_opts.asm_writer = TRUE;
10096 acfg->flags = (MonoAotFileFlags)(acfg->flags | MONO_AOT_FILE_FLAG_WITH_LLVM);
10098 if (acfg->aot_opts.soft_debug) {
10099 aot_printerrf (acfg, "The 'soft-debug' option is not supported when compiling with LLVM.\n");
10105 if (acfg->aot_opts.asm_only && !acfg->aot_opts.llvm_outfile) {
10106 aot_printerrf (acfg, "Compiling with LLVM and the asm-only option requires the llvm-outputfile= option.");
10111 * Emit all LLVM code into a separate assembly/object file and link with it
10114 if (!acfg->aot_opts.asm_only) {
10115 acfg->llvm_owriter = TRUE;
10116 } else if (acfg->aot_opts.llvm_outfile) {
10117 int len = strlen (acfg->aot_opts.llvm_outfile);
10119 if (len >= 2 && acfg->aot_opts.llvm_outfile [len - 2] == '.' && acfg->aot_opts.llvm_outfile [len - 1] == 'o')
10120 acfg->llvm_owriter = TRUE;
10124 if (mono_aot_mode_is_full (&acfg->aot_opts))
10125 acfg->flags = (MonoAotFileFlags)(acfg->flags | MONO_AOT_FILE_FLAG_FULL_AOT);
10127 if (mono_threads_is_coop_enabled ())
10128 acfg->flags = (MonoAotFileFlags)(acfg->flags | MONO_AOT_FILE_FLAG_SAFEPOINTS);
10130 if (acfg->aot_opts.instances_logfile_path) {
10131 acfg->instances_logfile = fopen (acfg->aot_opts.instances_logfile_path, "w");
10132 if (!acfg->instances_logfile) {
10133 aot_printerrf (acfg, "Unable to create logfile: '%s'.\n", acfg->aot_opts.instances_logfile_path);
10138 load_profile_files (acfg);
10140 acfg->num_trampolines [MONO_AOT_TRAMP_SPECIFIC] = mono_aot_mode_is_full (&acfg->aot_opts) ? acfg->aot_opts.ntrampolines : 0;
10141 #ifdef MONO_ARCH_GSHARED_SUPPORTED
10142 acfg->num_trampolines [MONO_AOT_TRAMP_STATIC_RGCTX] = mono_aot_mode_is_full (&acfg->aot_opts) ? acfg->aot_opts.nrgctx_trampolines : 0;
10144 acfg->num_trampolines [MONO_AOT_TRAMP_IMT_THUNK] = mono_aot_mode_is_full (&acfg->aot_opts) ? acfg->aot_opts.nimt_trampolines : 0;
10145 #ifdef MONO_ARCH_GSHAREDVT_SUPPORTED
10146 if (acfg->opts & MONO_OPT_GSHAREDVT)
10147 acfg->num_trampolines [MONO_AOT_TRAMP_GSHAREDVT_ARG] = mono_aot_mode_is_full (&acfg->aot_opts) ? acfg->aot_opts.ngsharedvt_arg_trampolines : 0;
10150 acfg->temp_prefix = mono_img_writer_get_temp_label_prefix (NULL);
10154 if (acfg->llvm && acfg->thumb_mixed)
10155 acfg->flags = (MonoAotFileFlags)(acfg->flags | MONO_AOT_FILE_FLAG_LLVM_THUMB);
10156 if (acfg->aot_opts.llvm_only)
10157 acfg->flags = (MonoAotFileFlags)(acfg->flags | MONO_AOT_FILE_FLAG_LLVM_ONLY);
10159 acfg->assembly_name_sym = g_strdup (acfg->image->assembly->aname.name);
10160 /* Get rid of characters which cannot occur in symbols */
10161 for (p = acfg->assembly_name_sym; *p; ++p) {
10162 if (!(isalnum (*p) || *p == '_'))
10166 acfg->global_prefix = g_strdup_printf ("mono_aot_%s", acfg->assembly_name_sym);
10167 acfg->plt_symbol = g_strdup_printf ("%s_plt", acfg->global_prefix);
10168 acfg->got_symbol = g_strdup_printf ("%s_got", acfg->global_prefix);
10170 acfg->llvm_got_symbol = g_strdup_printf ("%s_llvm_got", acfg->global_prefix);
10171 acfg->llvm_eh_frame_symbol = g_strdup_printf ("%s_eh_frame", acfg->global_prefix);
10174 acfg->method_index = 1;
10176 if (mono_aot_mode_is_full (&acfg->aot_opts))
10177 mono_set_partial_sharing_supported (TRUE);
10179 res = collect_methods (acfg);
10183 acfg->cfgs_size = acfg->methods->len + 32;
10184 acfg->cfgs = g_new0 (MonoCompile*, acfg->cfgs_size);
10186 /* PLT offset 0 is reserved for the PLT trampoline */
10187 acfg->plt_offset = 1;
10188 add_preinit_got_slots (acfg);
10193 mono_llvm_create_aot_module (acfg->image->assembly, acfg->global_prefix, TRUE, acfg->aot_opts.static_link, acfg->aot_opts.llvm_only);
10199 compile_methods (acfg);
10203 acfg->stats.jit_time = TV_ELAPSED (atv, btv);
10209 if (acfg->aot_opts.asm_only) {
10210 if (acfg->aot_opts.outfile) {
10211 acfg->tmpfname = g_strdup_printf ("%s", acfg->aot_opts.outfile);
10212 acfg->tmpbasename = g_strdup (acfg->tmpfname);
10214 acfg->tmpbasename = g_strdup_printf ("%s", acfg->image->name);
10215 acfg->tmpfname = g_strdup_printf ("%s.s", acfg->tmpbasename);
10217 g_assert (acfg->aot_opts.llvm_outfile);
10218 acfg->llvm_sfile = g_strdup (acfg->aot_opts.llvm_outfile);
10219 if (acfg->llvm_owriter)
10220 acfg->llvm_ofile = g_strdup (acfg->aot_opts.llvm_outfile);
10222 acfg->llvm_sfile = g_strdup (acfg->aot_opts.llvm_outfile);
10224 acfg->tmpbasename = (strcmp (acfg->aot_opts.temp_path, "") == 0) ?
10225 g_strdup_printf ("%s", "temp") :
10226 g_build_filename (acfg->aot_opts.temp_path, "temp", NULL);
10228 acfg->tmpfname = g_strdup_printf ("%s.s", acfg->tmpbasename);
10229 acfg->llvm_sfile = g_strdup_printf ("%s-llvm.s", acfg->tmpbasename);
10230 acfg->llvm_ofile = g_strdup_printf ("%s-llvm.o", acfg->tmpbasename);
10235 if (acfg->aot_opts.asm_only && !acfg->aot_opts.llvm_only) {
10236 if (acfg->aot_opts.outfile)
10237 acfg->tmpfname = g_strdup_printf ("%s", acfg->aot_opts.outfile);
10239 acfg->tmpfname = g_strdup_printf ("%s.s", acfg->image->name);
10240 acfg->fp = fopen (acfg->tmpfname, "w+");
10242 int i = g_file_open_tmp ("mono_aot_XXXXXX", &acfg->tmpfname, NULL);
10243 acfg->fp = fdopen (i, "w+");
10245 if (acfg->fp == 0 && !acfg->aot_opts.llvm_only) {
10246 aot_printerrf (acfg, "Unable to open file '%s': %s\n", acfg->tmpfname, strerror (errno));
10250 acfg->w = mono_img_writer_create (acfg->fp, FALSE);
10252 tmp_outfile_name = NULL;
10253 outfile_name = NULL;
10255 /* Compute symbols for methods */
10256 for (i = 0; i < acfg->nmethods; ++i) {
10257 if (acfg->cfgs [i]) {
10258 MonoCompile *cfg = acfg->cfgs [i];
10259 int method_index = get_method_index (acfg, cfg->orig_method);
10261 if (COMPILE_LLVM (cfg))
10262 cfg->asm_symbol = g_strdup_printf ("%s%s", acfg->llvm_label_prefix, cfg->llvm_method_name);
10263 else if (acfg->global_symbols || acfg->llvm)
10264 cfg->asm_symbol = get_debug_sym (cfg->orig_method, "", acfg->method_label_hash);
10266 cfg->asm_symbol = g_strdup_printf ("%s%sm_%x", acfg->temp_prefix, acfg->llvm_label_prefix, method_index);
10267 cfg->asm_debug_symbol = cfg->asm_symbol;
10271 if (acfg->aot_opts.dwarf_debug && acfg->aot_opts.asm_only && acfg->aot_opts.gnu_asm) {
10273 * CLANG supports GAS .file/.loc directives, so emit line number information this way
10274 * FIXME: CLANG only emits line number info for .loc directives followed by assembly, not
10275 * .byte directives.
10277 //acfg->gas_line_numbers = TRUE;
10280 if ((!acfg->aot_opts.nodebug || acfg->aot_opts.dwarf_debug) && acfg->has_jitted_code) {
10281 if (acfg->aot_opts.dwarf_debug && !mono_debug_enabled ()) {
10282 aot_printerrf (acfg, "The dwarf AOT option requires the --debug option.\n");
10285 acfg->dwarf = mono_dwarf_writer_create (acfg->w, NULL, 0, FALSE, !acfg->gas_line_numbers);
10289 mono_img_writer_emit_start (acfg->w);
10292 mono_dwarf_writer_emit_base_info (acfg->dwarf, g_path_get_basename (acfg->image->name), mono_unwind_get_cie_program ());
10298 emit_extra_methods (acfg);
10300 emit_trampolines (acfg);
10302 emit_class_name_table (acfg);
10304 emit_got_info (acfg, FALSE);
10306 emit_got_info (acfg, TRUE);
10308 emit_exception_info (acfg);
10310 emit_unwind_info (acfg);
10312 emit_class_info (acfg);
10316 emit_image_table (acfg);
10322 * The managed allocators are GC specific, so can't use an AOT image created by one GC
10325 const char *gc_name = mono_gc_get_gc_name ();
10326 acfg->gc_name_offset = add_to_blob (acfg, (guint8*)gc_name, strlen (gc_name) + 1);
10331 emit_objc_selectors (acfg);
10333 emit_globals (acfg);
10335 emit_file_info (acfg);
10338 emit_dwarf_info (acfg);
10339 mono_dwarf_writer_close (acfg->dwarf);
10342 emit_mem_end (acfg);
10344 if (acfg->need_pt_gnu_stack) {
10345 /* This is required so the .so doesn't have an executable stack */
10346 /* The bin writer already emits this */
10347 fprintf (acfg->fp, "\n.section .note.GNU-stack,\"\",@progbits\n");
10350 if (acfg->aot_opts.data_outfile)
10351 fclose (acfg->data_outfile);
10357 res = emit_llvm_file (acfg);
10365 acfg->stats.gen_time = TV_ELAPSED (atv, btv);
10368 sprintf (llvm_stats_msg, ", LLVM: %d (%d%%)", acfg->stats.llvm_count, acfg->stats.mcount ? (acfg->stats.llvm_count * 100) / acfg->stats.mcount : 100);
10370 strcpy (llvm_stats_msg, "");
10372 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;
10374 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",
10375 (int)acfg->stats.code_size, (int)(acfg->stats.code_size * 100 / all_sizes),
10376 (int)acfg->stats.info_size, (int)(acfg->stats.info_size * 100 / all_sizes),
10377 (int)acfg->stats.ex_info_size, (int)(acfg->stats.ex_info_size * 100 / all_sizes),
10378 (int)acfg->stats.unwind_info_size, (int)(acfg->stats.unwind_info_size * 100 / all_sizes),
10379 (int)acfg->stats.class_info_size, (int)(acfg->stats.class_info_size * 100 / all_sizes),
10380 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,
10381 (int)acfg->stats.got_info_size, (int)(acfg->stats.got_info_size * 100 / all_sizes),
10382 (int)acfg->stats.offsets_size, (int)(acfg->stats.offsets_size * 100 / all_sizes),
10383 (int)(acfg->got_offset * sizeof (gpointer)));
10384 aot_printf (acfg, "Compiled: %d/%d (%d%%)%s, No GOT slots: %d (%d%%), Direct calls: %d (%d%%)\n",
10385 acfg->stats.ccount, acfg->stats.mcount, acfg->stats.mcount ? (acfg->stats.ccount * 100) / acfg->stats.mcount : 100,
10387 acfg->stats.methods_without_got_slots, acfg->stats.mcount ? (acfg->stats.methods_without_got_slots * 100) / acfg->stats.mcount : 100,
10388 acfg->stats.direct_calls, acfg->stats.all_calls ? (acfg->stats.direct_calls * 100) / acfg->stats.all_calls : 100);
10389 if (acfg->stats.genericcount)
10390 aot_printf (acfg, "%d methods are generic (%d%%)\n", acfg->stats.genericcount, acfg->stats.mcount ? (acfg->stats.genericcount * 100) / acfg->stats.mcount : 100);
10391 if (acfg->stats.abscount)
10392 aot_printf (acfg, "%d methods contain absolute addresses (%d%%)\n", acfg->stats.abscount, acfg->stats.mcount ? (acfg->stats.abscount * 100) / acfg->stats.mcount : 100);
10393 if (acfg->stats.lmfcount)
10394 aot_printf (acfg, "%d methods contain lmf pointers (%d%%)\n", acfg->stats.lmfcount, acfg->stats.mcount ? (acfg->stats.lmfcount * 100) / acfg->stats.mcount : 100);
10395 if (acfg->stats.ocount)
10396 aot_printf (acfg, "%d methods have other problems (%d%%)\n", acfg->stats.ocount, acfg->stats.mcount ? (acfg->stats.ocount * 100) / acfg->stats.mcount : 100);
10400 res = mono_img_writer_emit_writeout (acfg->w);
10405 res = compile_asm (acfg);
10412 acfg->stats.link_time = TV_ELAPSED (atv, btv);
10414 if (acfg->aot_opts.stats) {
10417 aot_printf (acfg, "GOT slot distribution:\n");
10418 for (i = 0; i < MONO_PATCH_INFO_NONE; ++i)
10419 if (acfg->stats.got_slot_types [i])
10420 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]);
10421 aot_printf (acfg, "\nMethod stats:\n");
10422 aot_printf (acfg, "\tNormal: %d\n", acfg->stats.method_categories [METHOD_CAT_NORMAL]);
10423 aot_printf (acfg, "\tInstance: %d\n", acfg->stats.method_categories [METHOD_CAT_INST]);
10424 aot_printf (acfg, "\tGSharedvt: %d\n", acfg->stats.method_categories [METHOD_CAT_GSHAREDVT]);
10425 aot_printf (acfg, "\tWrapper: %d\n", acfg->stats.method_categories [METHOD_CAT_WRAPPER]);
10428 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);
10430 if (acfg->aot_opts.dump_json)
10443 mono_aot_readonly_field_override (MonoClassField *field)
10449 mono_compile_assembly (MonoAssembly *ass, guint32 opts, const char *aot_options)
10455 mono_aot_is_shared_got_offset (int offset)