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 char *gen_seq_points_file_path;
115 gboolean direct_pinvoke;
116 gboolean direct_icalls;
117 gboolean no_direct_calls;
118 gboolean use_trampolines_page;
119 gboolean no_instances;
125 int nrgctx_trampolines;
126 int nimt_trampolines;
127 int ngsharedvt_arg_trampolines;
128 int nrgctx_fetch_trampolines;
129 gboolean print_skipped_methods;
136 char *instances_logfile_path;
143 METHOD_CAT_GSHAREDVT,
149 typedef struct MonoAotStats {
150 int ccount, mcount, lmfcount, abscount, gcount, ocount, genericcount;
151 gint64 code_size, info_size, ex_info_size, unwind_info_size, got_size, class_info_size, got_info_size, plt_size;
152 int methods_without_got_slots, direct_calls, all_calls, llvm_count;
153 int got_slots, offsets_size;
154 int method_categories [METHOD_CAT_NUM];
155 int got_slot_types [MONO_PATCH_INFO_NONE];
156 int got_slot_info_sizes [MONO_PATCH_INFO_NONE];
157 int jit_time, gen_time, link_time;
160 typedef struct GotInfo {
161 GHashTable *patch_to_got_offset;
162 GHashTable **patch_to_got_offset_by_type;
163 GPtrArray *got_patches;
166 typedef struct MonoAotCompile {
169 GHashTable *method_indexes;
170 GHashTable *method_depth;
173 GHashTable **patch_to_plt_entry;
174 GHashTable *plt_offset_to_entry;
175 //GHashTable *patch_to_got_offset;
176 //GHashTable **patch_to_got_offset_by_type;
177 //GPtrArray *got_patches;
178 GotInfo got_info, llvm_got_info;
179 GHashTable *image_hash;
180 GHashTable *method_to_cfg;
181 GHashTable *token_info_hash;
182 GHashTable *method_to_pinvoke_import;
183 GPtrArray *extra_methods;
184 GPtrArray *image_table;
186 GPtrArray *method_order;
187 GHashTable *export_names;
188 /* Maps MonoClass* -> blob offset */
189 GHashTable *klass_blob_hash;
190 /* Maps MonoMethod* -> blob offset */
191 GHashTable *method_blob_hash;
192 GHashTable *gsharedvt_in_signatures;
193 GHashTable *gsharedvt_out_signatures;
194 guint32 *plt_got_info_offsets;
195 guint32 got_offset, llvm_got_offset, plt_offset, plt_got_offset_base, nshared_got_entries;
196 /* Number of GOT entries reserved for trampolines */
197 guint32 num_trampoline_got_entries;
198 guint32 tramp_page_size;
200 guint32 table_offsets [MONO_AOT_TABLE_NUM];
201 guint32 num_trampolines [MONO_AOT_TRAMP_NUM];
202 guint32 trampoline_got_offset_base [MONO_AOT_TRAMP_NUM];
203 guint32 trampoline_size [MONO_AOT_TRAMP_NUM];
204 guint32 tramp_page_code_offsets [MONO_AOT_TRAMP_NUM];
206 MonoAotOptions aot_opts;
210 MonoMemPool *mempool;
213 char *static_linking_symbol;
215 gboolean gas_line_numbers;
216 /* Whenever to emit an object file directly from llc */
217 gboolean llvm_owriter;
219 MonoDwarfWriter *dwarf;
226 GHashTable *unwind_info_offsets;
227 GPtrArray *unwind_ops;
228 guint32 unwind_info_offset;
231 char *llvm_got_symbol;
233 char *llvm_eh_frame_symbol;
234 GHashTable *method_label_hash;
235 const char *temp_prefix;
236 const char *user_symbol_prefix;
237 const char *llvm_label_prefix;
238 const char *inst_directive;
240 guint32 label_generator;
242 gboolean has_jitted_code;
243 MonoAotFileFlags flags;
244 MonoDynamicStream blob;
245 gboolean blob_closed;
246 MonoClass **typespec_classes;
249 char *assembly_name_sym;
250 GHashTable *plt_entry_debug_sym_cache;
251 gboolean thumb_mixed, need_no_dead_strip, need_pt_gnu_stack;
252 GHashTable *ginst_hash;
253 GHashTable *dwarf_ln_filenames;
254 gboolean global_symbols;
255 int objc_selector_index, objc_selector_index_2;
256 GPtrArray *objc_selectors;
257 GHashTable *objc_selector_to_index;
259 FILE *instances_logfile;
267 char *symbol, *llvm_symbol, *debug_sym;
269 gboolean jit_used, llvm_used;
272 #define mono_acfg_lock(acfg) mono_os_mutex_lock (&((acfg)->mutex))
273 #define mono_acfg_unlock(acfg) mono_os_mutex_unlock (&((acfg)->mutex))
275 /* This points to the current acfg in LLVM mode */
276 static MonoAotCompile *llvm_acfg;
278 #ifdef HAVE_ARRAY_ELEM_INIT
279 #define MSGSTRFIELD(line) MSGSTRFIELD1(line)
280 #define MSGSTRFIELD1(line) str##line
281 static const struct msgstr_t {
282 #define PATCH_INFO(a,b) char MSGSTRFIELD(__LINE__) [sizeof (b)];
283 #include "patch-info.h"
286 #define PATCH_INFO(a,b) b,
287 #include "patch-info.h"
290 static const gint16 opidx [] = {
291 #define PATCH_INFO(a,b) [MONO_PATCH_INFO_ ## a] = offsetof (struct msgstr_t, MSGSTRFIELD(__LINE__)),
292 #include "patch-info.h"
296 static G_GNUC_UNUSED const char*
297 get_patch_name (int info)
299 return (const char*)&opstr + opidx [info];
303 #define PATCH_INFO(a,b) b,
304 static const char* const
305 patch_types [MONO_PATCH_INFO_NUM + 1] = {
306 #include "patch-info.h"
310 static G_GNUC_UNUSED const char*
311 get_patch_name (int info)
313 return patch_types [info];
319 get_unwind_info_offset (MonoAotCompile *acfg, guint8 *encoded, guint32 encoded_len);
322 get_plt_entry_debug_sym (MonoAotCompile *acfg, MonoJumpInfo *ji, GHashTable *cache);
325 aot_printf (MonoAotCompile *acfg, const gchar *format, ...)
331 output = acfg->logfile;
335 va_start (args, format);
336 vfprintf (output, format, args);
341 aot_printerrf (MonoAotCompile *acfg, const gchar *format, ...)
347 output = acfg->logfile;
351 va_start (args, format);
352 vfprintf (output, format, args);
357 report_loader_error (MonoAotCompile *acfg, MonoError *error, const char *format, ...)
362 if (mono_error_ok (error))
366 output = acfg->logfile;
370 va_start (args, format);
371 vfprintf (output, format, args);
373 mono_error_cleanup (error);
375 g_error ("FullAOT cannot continue if there are loader errors");
378 /* Wrappers around the image writer functions */
381 emit_section_change (MonoAotCompile *acfg, const char *section_name, int subsection_index)
383 mono_img_writer_emit_section_change (acfg->w, section_name, subsection_index);
387 emit_local_symbol (MonoAotCompile *acfg, const char *name, const char *end_label, gboolean func)
389 mono_img_writer_emit_local_symbol (acfg->w, name, end_label, func);
393 emit_label (MonoAotCompile *acfg, const char *name)
395 mono_img_writer_emit_label (acfg->w, name);
399 emit_bytes (MonoAotCompile *acfg, const guint8* buf, int size)
401 mono_img_writer_emit_bytes (acfg->w, buf, size);
405 emit_string (MonoAotCompile *acfg, const char *value)
407 mono_img_writer_emit_string (acfg->w, value);
411 emit_line (MonoAotCompile *acfg)
413 mono_img_writer_emit_line (acfg->w);
417 emit_alignment (MonoAotCompile *acfg, int size)
419 mono_img_writer_emit_alignment (acfg->w, size);
423 emit_alignment_code (MonoAotCompile *acfg, int size)
425 if (acfg->align_pad_value)
426 mono_img_writer_emit_alignment_fill (acfg->w, size, acfg->align_pad_value);
428 mono_img_writer_emit_alignment (acfg->w, size);
432 emit_padding (MonoAotCompile *acfg, int size)
437 if (acfg->align_pad_value) {
438 for (i = 0; i < 16; ++i)
439 buf [i] = acfg->align_pad_value;
441 memset (buf, 0, sizeof (buf));
444 for (i = 0; i < size; i += 16) {
446 emit_bytes (acfg, buf, size - i);
448 emit_bytes (acfg, buf, 16);
453 emit_pointer (MonoAotCompile *acfg, const char *target)
455 mono_img_writer_emit_pointer (acfg->w, target);
459 emit_pointer_2 (MonoAotCompile *acfg, const char *prefix, const char *target)
461 if (prefix [0] != '\0') {
462 char *s = g_strdup_printf ("%s%s", prefix, target);
463 mono_img_writer_emit_pointer (acfg->w, s);
466 mono_img_writer_emit_pointer (acfg->w, target);
471 emit_int16 (MonoAotCompile *acfg, int value)
473 mono_img_writer_emit_int16 (acfg->w, value);
477 emit_int32 (MonoAotCompile *acfg, int value)
479 mono_img_writer_emit_int32 (acfg->w, value);
483 emit_symbol_diff (MonoAotCompile *acfg, const char *end, const char* start, int offset)
485 mono_img_writer_emit_symbol_diff (acfg->w, end, start, offset);
489 emit_zero_bytes (MonoAotCompile *acfg, int num)
491 mono_img_writer_emit_zero_bytes (acfg->w, num);
495 emit_byte (MonoAotCompile *acfg, guint8 val)
497 mono_img_writer_emit_byte (acfg->w, val);
500 #ifdef __native_client_codegen__
502 emit_nacl_call_alignment (MonoAotCompile *acfg)
504 mono_img_writer_emit_nacl_call_alignment (acfg->w);
508 static G_GNUC_UNUSED void
509 emit_global_inner (MonoAotCompile *acfg, const char *name, gboolean func)
511 mono_img_writer_emit_global (acfg->w, name, func);
515 emit_global (MonoAotCompile *acfg, const char *name, gboolean func)
517 if (acfg->aot_opts.no_dlsym) {
518 g_ptr_array_add (acfg->globals, g_strdup (name));
519 mono_img_writer_emit_local_symbol (acfg->w, name, NULL, func);
521 mono_img_writer_emit_global (acfg->w, name, func);
526 emit_symbol_size (MonoAotCompile *acfg, const char *name, const char *end_label)
528 mono_img_writer_emit_symbol_size (acfg->w, name, end_label);
531 /* Emit a symbol which is referenced by the MonoAotFileInfo structure */
533 emit_info_symbol (MonoAotCompile *acfg, const char *name)
538 emit_label (acfg, name);
539 /* LLVM generated code references this */
540 sprintf (symbol, "%s%s%s", acfg->user_symbol_prefix, acfg->global_prefix, name);
541 emit_label (acfg, symbol);
542 emit_global_inner (acfg, symbol, FALSE);
544 emit_label (acfg, name);
549 emit_string_symbol (MonoAotCompile *acfg, const char *name, const char *value)
552 mono_llvm_emit_aot_data (name, (guint8*)value, strlen (value) + 1);
556 mono_img_writer_emit_section_change (acfg->w, RODATA_SECT, 1);
558 /* On apple, all symbols need to be aligned to avoid warnings from ld */
559 emit_alignment (acfg, 4);
561 mono_img_writer_emit_label (acfg->w, name);
562 mono_img_writer_emit_string (acfg->w, value);
565 static G_GNUC_UNUSED void
566 emit_uleb128 (MonoAotCompile *acfg, guint32 value)
569 guint8 b = value & 0x7f;
571 if (value != 0) /* more bytes to come */
577 static G_GNUC_UNUSED void
578 emit_sleb128 (MonoAotCompile *acfg, gint64 value)
581 gboolean negative = (value < 0);
588 /* the following is unnecessary if the
589 * implementation of >>= uses an arithmetic rather
590 * than logical shift for a signed left operand
594 value |= - ((gint64)1 <<(size - 7));
595 /* sign bit of byte is second high order bit (0x40) */
596 if ((value == 0 && !(byte & 0x40)) ||
597 (value == -1 && (byte & 0x40)))
601 emit_byte (acfg, byte);
605 static G_GNUC_UNUSED void
606 encode_uleb128 (guint32 value, guint8 *buf, guint8 **endbuf)
611 guint8 b = value & 0x7f;
613 if (value != 0) /* more bytes to come */
621 static G_GNUC_UNUSED void
622 encode_sleb128 (gint32 value, guint8 *buf, guint8 **endbuf)
625 gboolean negative = (value < 0);
633 /* the following is unnecessary if the
634 * implementation of >>= uses an arithmetic rather
635 * than logical shift for a signed left operand
639 value |= - (1 <<(size - 7));
640 /* sign bit of byte is second high order bit (0x40) */
641 if ((value == 0 && !(byte & 0x40)) ||
642 (value == -1 && (byte & 0x40)))
653 encode_int (gint32 val, guint8 *buf, guint8 **endbuf)
656 buf [0] = (val >> 0) & 0xff;
657 buf [1] = (val >> 8) & 0xff;
658 buf [2] = (val >> 16) & 0xff;
659 buf [3] = (val >> 24) & 0xff;
665 encode_int16 (guint16 val, guint8 *buf, guint8 **endbuf)
667 buf [0] = (val >> 0) & 0xff;
668 buf [1] = (val >> 8) & 0xff;
674 encode_string (const char *s, guint8 *buf, guint8 **endbuf)
676 int len = strlen (s);
678 memcpy (buf, s, len + 1);
679 *endbuf = buf + len + 1;
683 emit_unset_mode (MonoAotCompile *acfg)
685 mono_img_writer_emit_unset_mode (acfg->w);
688 static G_GNUC_UNUSED void
689 emit_set_thumb_mode (MonoAotCompile *acfg)
691 emit_unset_mode (acfg);
692 fprintf (acfg->fp, ".code 16\n");
695 static G_GNUC_UNUSED void
696 emit_set_arm_mode (MonoAotCompile *acfg)
698 emit_unset_mode (acfg);
699 fprintf (acfg->fp, ".code 32\n");
703 emit_code_bytes (MonoAotCompile *acfg, const guint8* buf, int size)
708 g_assert (size % 4 == 0);
709 emit_unset_mode (acfg);
710 for (i = 0; i < size; i += 4)
711 fprintf (acfg->fp, "%s 0x%x\n", acfg->inst_directive, *(guint32*)(buf + i));
713 emit_bytes (acfg, buf, size);
717 /* ARCHITECTURE SPECIFIC CODE */
719 #if defined(TARGET_X86) || defined(TARGET_AMD64) || defined(TARGET_ARM) || defined(TARGET_POWERPC) || defined(TARGET_ARM64)
720 #define EMIT_DWARF_INFO 1
723 #if defined(TARGET_ARM)
724 #define AOT_FUNC_ALIGNMENT 4
726 #define AOT_FUNC_ALIGNMENT 16
728 #if (defined(TARGET_X86) || defined(TARGET_AMD64)) && defined(__native_client_codegen__)
729 #undef AOT_FUNC_ALIGNMENT
730 #define AOT_FUNC_ALIGNMENT 32
733 #if defined(TARGET_POWERPC64) && !defined(__mono_ilp32__)
734 #define PPC_LD_OP "ld"
735 #define PPC_LDX_OP "ldx"
737 #define PPC_LD_OP "lwz"
738 #define PPC_LDX_OP "lwzx"
742 #define AOT_TARGET_STR "AMD64"
747 #define AOT_TARGET_STR "ARM (MACH)"
749 #define AOT_TARGET_STR "ARM (!MACH)"
755 #define AOT_TARGET_STR "ARM64 (MACH)"
757 #define AOT_TARGET_STR "ARM64 (!MACH)"
761 #ifdef TARGET_POWERPC64
762 #ifdef __mono_ilp32__
763 #define AOT_TARGET_STR "POWERPC64 (mono ilp32)"
765 #define AOT_TARGET_STR "POWERPC64 (!mono ilp32)"
768 #ifdef TARGET_POWERPC
769 #ifdef __mono_ilp32__
770 #define AOT_TARGET_STR "POWERPC (mono ilp32)"
772 #define AOT_TARGET_STR "POWERPC (!mono ilp32)"
779 #define AOT_TARGET_STR "X86 (WIN32)"
780 #elif defined(__native_client_codegen__)
781 #define AOT_TARGET_STR "X86 (native client codegen)"
783 #define AOT_TARGET_STR "X86 (!native client codegen)"
787 #ifndef AOT_TARGET_STR
788 #define AOT_TARGET_STR ""
792 arch_init (MonoAotCompile *acfg)
794 acfg->llc_args = g_string_new ("");
795 acfg->as_args = g_string_new ("");
798 * The prefix LLVM likes to put in front of symbol names on darwin.
799 * The mach-os specs require this for globals, but LLVM puts them in front of all
800 * symbols. We need to handle this, since we need to refer to LLVM generated
803 acfg->llvm_label_prefix = "";
804 acfg->user_symbol_prefix = "";
806 #if defined(TARGET_X86)
807 g_string_append (acfg->llc_args, " -march=x86 -mattr=sse4.1");
810 #if defined(TARGET_AMD64)
811 g_string_append (acfg->llc_args, " -march=x86-64 -mattr=sse4.1");
813 acfg->align_pad_value = 0x90;
817 if (acfg->aot_opts.mtriple && strstr (acfg->aot_opts.mtriple, "darwin")) {
818 g_string_append (acfg->llc_args, "-mattr=+v6");
821 g_string_append (acfg->llc_args, " -mattr=+vfp2,-neon,+d16");
822 g_string_append (acfg->as_args, " -mfpu=vfp3");
824 g_string_append (acfg->llc_args, " -soft-float");
827 if (acfg->aot_opts.mtriple && strstr (acfg->aot_opts.mtriple, "thumb"))
828 acfg->thumb_mixed = TRUE;
830 if (acfg->aot_opts.mtriple)
831 mono_arch_set_target (acfg->aot_opts.mtriple);
835 acfg->inst_directive = ".inst";
836 if (acfg->aot_opts.mtriple)
837 mono_arch_set_target (acfg->aot_opts.mtriple);
841 acfg->user_symbol_prefix = "_";
842 acfg->llvm_label_prefix = "_";
843 acfg->inst_directive = ".word";
844 acfg->need_no_dead_strip = TRUE;
845 acfg->aot_opts.gnu_asm = TRUE;
848 #if defined(__linux__) && !defined(TARGET_ARM)
849 acfg->need_pt_gnu_stack = TRUE;
853 acfg->global_symbols = TRUE;
859 #include "../../../mono-extensions/mono/mini/aot-compiler-arm64.c"
863 #ifdef MONO_ARCH_AOT_SUPPORTED
865 * arch_emit_direct_call:
867 * Emit a direct call to the symbol TARGET. CALL_SIZE is set to the size of the
871 arch_emit_direct_call (MonoAotCompile *acfg, const char *target, gboolean external, gboolean thumb, MonoJumpInfo *ji, int *call_size)
873 #if defined(TARGET_X86) || defined(TARGET_AMD64)
874 /* Need to make sure this is exactly 5 bytes long */
875 emit_unset_mode (acfg);
876 fprintf (acfg->fp, "call %s\n", target);
878 #elif defined(TARGET_ARM)
879 emit_unset_mode (acfg);
881 fprintf (acfg->fp, "blx %s\n", target);
883 fprintf (acfg->fp, "bl %s\n", target);
885 #elif defined(TARGET_ARM64)
886 arm64_emit_direct_call (acfg, target, external, thumb, ji, call_size);
887 #elif defined(TARGET_POWERPC)
888 emit_unset_mode (acfg);
889 fprintf (acfg->fp, "bl %s\n", target);
892 g_assert_not_reached ();
899 * - we use an approach similar to the x86 abi: reserve a register (r30) to hold
901 * - The full-aot trampolines need access to the GOT of mscorlib, so we store
902 * in in the 2. slot of every GOT, and require every method to place the GOT
903 * address in r30, even when it doesn't access the GOT otherwise. This way,
904 * the trampolines can compute the mscorlib GOT address by loading 4(r30).
909 * PPC64 uses function descriptors which greatly complicate all code, since
910 * these are used very inconsistently in the runtime. Some functions like
911 * mono_compile_method () return ftn descriptors, while others like the
912 * trampoline creation functions do not.
913 * We assume that all GOT slots contain function descriptors, and create
914 * descriptors in aot-runtime.c when needed.
915 * The ppc64 abi uses r2 to hold the address of the TOC/GOT, which is loaded
916 * from function descriptors, we could do the same, but it would require
917 * rewriting all the ppc/aot code to handle function descriptors properly.
918 * So instead, we use the same approach as on PPC32.
919 * This is a horrible mess, but fixing it would probably lead to an even bigger
925 * - similar to the PPC32 design, we reserve EBX to hold the GOT pointer.
928 #ifdef MONO_ARCH_AOT_SUPPORTED
930 * arch_emit_got_offset:
932 * The memory pointed to by CODE should hold native code for computing the GOT
933 * address (OP_LOAD_GOTADDR). Emit this code while patching it with the offset
934 * between code and the GOT. CODE_SIZE is set to the number of bytes emitted.
937 arch_emit_got_offset (MonoAotCompile *acfg, guint8 *code, int *code_size)
939 #if defined(TARGET_POWERPC64)
940 emit_unset_mode (acfg);
942 * The ppc32 code doesn't seem to work on ppc64, the assembler complains about
943 * unsupported relocations. So we store the got address into the .Lgot_addr
944 * symbol which is in the text segment, compute its address, and load it.
946 fprintf (acfg->fp, ".L%d:\n", acfg->label_generator);
947 fprintf (acfg->fp, "lis 0, (.Lgot_addr + 4 - .L%d)@h\n", acfg->label_generator);
948 fprintf (acfg->fp, "ori 0, 0, (.Lgot_addr + 4 - .L%d)@l\n", acfg->label_generator);
949 fprintf (acfg->fp, "add 30, 30, 0\n");
950 fprintf (acfg->fp, "%s 30, 0(30)\n", PPC_LD_OP);
951 acfg->label_generator ++;
953 #elif defined(TARGET_POWERPC)
954 emit_unset_mode (acfg);
955 fprintf (acfg->fp, ".L%d:\n", acfg->label_generator);
956 fprintf (acfg->fp, "lis 0, (%s + 4 - .L%d)@h\n", acfg->got_symbol, acfg->label_generator);
957 fprintf (acfg->fp, "ori 0, 0, (%s + 4 - .L%d)@l\n", acfg->got_symbol, acfg->label_generator);
958 acfg->label_generator ++;
961 guint32 offset = mono_arch_get_patch_offset (code);
962 emit_bytes (acfg, code, offset);
963 emit_symbol_diff (acfg, acfg->got_symbol, ".", offset);
965 *code_size = offset + 4;
970 * arch_emit_got_access:
972 * The memory pointed to by CODE should hold native code for loading a GOT
973 * slot (OP_AOTCONST/OP_GOT_ENTRY). Emit this code while patching it so it accesses the
974 * GOT slot GOT_SLOT. CODE_SIZE is set to the number of bytes emitted.
977 arch_emit_got_access (MonoAotCompile *acfg, const char *got_symbol, guint8 *code, int got_slot, int *code_size)
980 /* mov reg, got+offset(%rip) */
982 /* The GOT symbol is in the LLVM module, the clang assembler has problems emitting symbol diffs for it */
986 /* Decode reg, see amd64_mov_reg_membase () */
987 rex_r = code [0] & AMD64_REX_R;
988 g_assert (code [0] == 0x49 + rex_r);
989 g_assert (code [1] == 0x8b);
990 dreg = ((code [2] >> 3) & 0x7) + (rex_r ? 8 : 0);
992 emit_unset_mode (acfg);
993 fprintf (acfg->fp, "mov %s+%d(%%rip), %s\n", got_symbol, (unsigned int) ((got_slot * sizeof (gpointer))), mono_arch_regname (dreg));
996 emit_bytes (acfg, code, mono_arch_get_patch_offset (code));
997 emit_symbol_diff (acfg, got_symbol, ".", (unsigned int) ((got_slot * sizeof (gpointer)) - 4));
998 *code_size = mono_arch_get_patch_offset (code) + 4;
1000 #elif defined(TARGET_X86)
1001 emit_bytes (acfg, code, mono_arch_get_patch_offset (code));
1002 emit_int32 (acfg, (unsigned int) ((got_slot * sizeof (gpointer))));
1003 *code_size = mono_arch_get_patch_offset (code) + 4;
1004 #elif defined(TARGET_ARM)
1005 emit_bytes (acfg, code, mono_arch_get_patch_offset (code));
1006 emit_symbol_diff (acfg, got_symbol, ".", (unsigned int) ((got_slot * sizeof (gpointer))) - 12);
1007 *code_size = mono_arch_get_patch_offset (code) + 4;
1008 #elif defined(TARGET_ARM64)
1009 emit_bytes (acfg, code, mono_arch_get_patch_offset (code));
1010 arm64_emit_got_access (acfg, code, got_slot, code_size);
1011 #elif defined(TARGET_POWERPC)
1016 emit_bytes (acfg, code, mono_arch_get_patch_offset (code));
1018 ppc_load32 (code, ppc_r0, got_slot * sizeof (gpointer));
1019 g_assert (code - buf == 8);
1020 emit_bytes (acfg, buf, code - buf);
1021 *code_size = code - buf;
1024 g_assert_not_reached ();
1030 #ifdef MONO_ARCH_AOT_SUPPORTED
1032 * arch_emit_objc_selector_ref:
1034 * Emit the implementation of OP_OBJC_GET_SELECTOR, which itself implements @selector(foo:) in objective-c.
1037 arch_emit_objc_selector_ref (MonoAotCompile *acfg, guint8 *code, int index, int *code_size)
1039 #if defined(TARGET_ARM)
1042 int lindex = acfg->objc_selector_index_2 ++;
1044 /* Emit ldr.imm/b */
1045 emit_bytes (acfg, code, 8);
1047 sprintf (symbol1, "L_OBJC_SELECTOR_%d", lindex);
1048 sprintf (symbol2, "L_OBJC_SELECTOR_REFERENCES_%d", index);
1050 emit_label (acfg, symbol1);
1051 mono_img_writer_emit_unset_mode (acfg->w);
1052 fprintf (acfg->fp, ".long %s-(%s+12)", symbol2, symbol1);
1055 #elif defined(TARGET_ARM64)
1056 arm64_emit_objc_selector_ref (acfg, code, index, code_size);
1058 g_assert_not_reached ();
1064 * arch_emit_plt_entry:
1066 * Emit code for the PLT entry.
1067 * The plt entry should look like this:
1068 * <indirect jump to GOT_SYMBOL + OFFSET>
1069 * <INFO_OFFSET embedded into the instruction stream>
1072 arch_emit_plt_entry (MonoAotCompile *acfg, const char *got_symbol, int offset, int info_offset)
1074 #if defined(TARGET_X86)
1075 #if defined(__default_codegen__)
1076 /* jmp *<offset>(%ebx) */
1077 emit_byte (acfg, 0xff);
1078 emit_byte (acfg, 0xa3);
1079 emit_int32 (acfg, offset);
1080 /* Used by mono_aot_get_plt_info_offset */
1081 emit_int32 (acfg, info_offset);
1082 #elif defined(__native_client_codegen__)
1083 const guint8 kSizeOfNaClJmp = 11;
1084 guint8 bytes[kSizeOfNaClJmp];
1085 guint8 *pbytes = &bytes[0];
1087 x86_jump_membase32 (pbytes, X86_EBX, offset);
1088 emit_bytes (acfg, bytes, kSizeOfNaClJmp);
1089 /* four bytes of data, used by mono_arch_patch_plt_entry */
1090 /* For Native Client, make this work with data embedded in push. */
1091 emit_byte (acfg, 0x68); /* hide data in a push */
1092 emit_int32 (acfg, info_offset);
1093 emit_alignment (acfg, AOT_FUNC_ALIGNMENT);
1094 #endif /*__native_client_codegen__*/
1095 #elif defined(TARGET_AMD64)
1096 #if defined(__default_codegen__)
1097 emit_unset_mode (acfg);
1098 fprintf (acfg->fp, "jmp *%s+%d(%%rip)\n", got_symbol, offset);
1099 /* Used by mono_aot_get_plt_info_offset */
1100 emit_int32 (acfg, info_offset);
1101 acfg->stats.plt_size += 10;
1102 #elif defined(__native_client_codegen__)
1104 guint8 *buf_aligned = ALIGN_TO(buf, kNaClAlignment);
1105 guint8 *code = buf_aligned;
1107 /* mov <OFFSET>(%rip), %r11d */
1108 emit_byte (acfg, '\x45');
1109 emit_byte (acfg, '\x8b');
1110 emit_byte (acfg, '\x1d');
1111 emit_symbol_diff (acfg, got_symbol, ".", offset - 4);
1113 amd64_jump_reg (code, AMD64_R11);
1114 /* This should be constant for the plt patch */
1115 g_assert ((size_t)(code-buf_aligned) == 10);
1116 emit_bytes (acfg, buf_aligned, code - buf_aligned);
1118 /* Hide data in a push imm32 so it passes validation */
1119 emit_byte (acfg, 0x68); /* push */
1120 emit_int32 (acfg, info_offset);
1121 emit_alignment (acfg, AOT_FUNC_ALIGNMENT);
1122 #endif /*__native_client_codegen__*/
1123 #elif defined(TARGET_ARM)
1128 ARM_LDR_IMM (code, ARMREG_IP, ARMREG_PC, 0);
1129 ARM_LDR_REG_REG (code, ARMREG_PC, ARMREG_PC, ARMREG_IP);
1130 emit_bytes (acfg, buf, code - buf);
1131 emit_symbol_diff (acfg, got_symbol, ".", offset - 4);
1132 /* Used by mono_aot_get_plt_info_offset */
1133 emit_int32 (acfg, info_offset);
1134 #elif defined(TARGET_ARM64)
1135 arm64_emit_plt_entry (acfg, got_symbol, offset, info_offset);
1136 #elif defined(TARGET_POWERPC)
1137 /* The GOT address is guaranteed to be in r30 by OP_LOAD_GOTADDR */
1138 emit_unset_mode (acfg);
1139 fprintf (acfg->fp, "lis 11, %d@h\n", offset);
1140 fprintf (acfg->fp, "ori 11, 11, %d@l\n", offset);
1141 fprintf (acfg->fp, "add 11, 11, 30\n");
1142 fprintf (acfg->fp, "%s 11, 0(11)\n", PPC_LD_OP);
1143 #ifdef PPC_USES_FUNCTION_DESCRIPTOR
1144 fprintf (acfg->fp, "%s 2, %d(11)\n", PPC_LD_OP, (int)sizeof (gpointer));
1145 fprintf (acfg->fp, "%s 11, 0(11)\n", PPC_LD_OP);
1147 fprintf (acfg->fp, "mtctr 11\n");
1148 fprintf (acfg->fp, "bctr\n");
1149 emit_int32 (acfg, info_offset);
1151 g_assert_not_reached ();
1156 * arch_emit_llvm_plt_entry:
1158 * Same as arch_emit_plt_entry, but handles calls from LLVM generated code.
1159 * This is only needed on arm to handle thumb interop.
1162 arch_emit_llvm_plt_entry (MonoAotCompile *acfg, const char *got_symbol, int offset, int info_offset)
1164 #if defined(TARGET_ARM)
1165 /* LLVM calls the PLT entries using bl, so these have to be thumb2 */
1166 /* The caller already transitioned to thumb */
1167 /* The code below should be 12 bytes long */
1168 /* clang has trouble encoding these instructions, so emit the binary */
1170 fprintf (acfg->fp, "ldr ip, [pc, #8]\n");
1171 /* thumb can't encode ld pc, [pc, ip] */
1172 fprintf (acfg->fp, "add ip, pc, ip\n");
1173 fprintf (acfg->fp, "ldr ip, [ip, #0]\n");
1174 fprintf (acfg->fp, "bx ip\n");
1176 emit_set_thumb_mode (acfg);
1177 fprintf (acfg->fp, ".4byte 0xc008f8df\n");
1178 fprintf (acfg->fp, ".2byte 0x44fc\n");
1179 fprintf (acfg->fp, ".4byte 0xc000f8dc\n");
1180 fprintf (acfg->fp, ".2byte 0x4760\n");
1181 emit_symbol_diff (acfg, got_symbol, ".", offset + 4);
1182 emit_int32 (acfg, info_offset);
1183 emit_unset_mode (acfg);
1184 emit_set_arm_mode (acfg);
1186 g_assert_not_reached ();
1190 /* Save unwind_info in the module and emit the offset to the information at symbol */
1191 static void save_unwind_info (MonoAotCompile *acfg, char *symbol, GSList *unwind_ops)
1193 guint32 uw_offset, encoded_len;
1196 emit_section_change (acfg, RODATA_SECT, 0);
1197 emit_global (acfg, symbol, FALSE);
1198 emit_label (acfg, symbol);
1200 encoded = mono_unwind_ops_encode (unwind_ops, &encoded_len);
1201 uw_offset = get_unwind_info_offset (acfg, encoded, encoded_len);
1203 emit_int32 (acfg, uw_offset);
1207 * arch_emit_specific_trampoline_pages:
1209 * Emits a page full of trampolines: each trampoline uses its own address to
1210 * lookup both the generic trampoline code and the data argument.
1211 * This page can be remapped in process multiple times so we can get an
1212 * unlimited number of trampolines.
1213 * Specifically this implementation uses the following trick: two memory pages
1214 * are allocated, with the first containing the data and the second containing the trampolines.
1215 * To reduce trampoline size, each trampoline jumps at the start of the page where a common
1216 * implementation does all the lifting.
1217 * Note that the ARM single trampoline size is 8 bytes, exactly like the data that needs to be stored
1218 * on the arm 32 bit system.
1221 arch_emit_specific_trampoline_pages (MonoAotCompile *acfg)
1223 #if defined(TARGET_ARM)
1226 guint8 *loop_start, *loop_branch_back, *loop_end_check, *imt_found_check;
1228 int pagesize = MONO_AOT_TRAMP_PAGE_SIZE;
1229 GSList *unwind_ops = NULL;
1230 #define COMMON_TRAMP_SIZE 16
1231 int count = (pagesize - COMMON_TRAMP_SIZE) / 8;
1232 int imm8, rot_amount;
1235 if (!acfg->aot_opts.use_trampolines_page)
1238 acfg->tramp_page_size = pagesize;
1240 sprintf (symbol, "%sspecific_trampolines_page", acfg->user_symbol_prefix);
1241 emit_alignment (acfg, pagesize);
1242 emit_global (acfg, symbol, TRUE);
1243 emit_label (acfg, symbol);
1245 /* emit the generic code first, the trampoline address + 8 is in the lr register */
1247 imm8 = mono_arm_is_rotated_imm8 (pagesize, &rot_amount);
1248 ARM_SUB_REG_IMM (code, ARMREG_LR, ARMREG_LR, imm8, rot_amount);
1249 ARM_LDR_IMM (code, ARMREG_R1, ARMREG_LR, -8);
1250 ARM_LDR_IMM (code, ARMREG_PC, ARMREG_LR, -4);
1252 g_assert (code - buf == COMMON_TRAMP_SIZE);
1255 emit_bytes (acfg, buf, code - buf);
1257 for (i = 0; i < count; ++i) {
1259 ARM_PUSH (code, 0x5fff);
1261 arm_patch (code - 4, code - COMMON_TRAMP_SIZE - 8 * (i + 1));
1262 g_assert (code - buf == 8);
1263 emit_bytes (acfg, buf, code - buf);
1266 /* now the rgctx trampolines: each specific trampolines puts in the ip register
1267 * the instruction pointer address, so the generic trampoline at the start of the page
1268 * subtracts 4096 to get to the data page and loads the values
1269 * We again fit the generic trampiline in 16 bytes.
1271 sprintf (symbol, "%srgctx_trampolines_page", acfg->user_symbol_prefix);
1272 emit_global (acfg, symbol, TRUE);
1273 emit_label (acfg, symbol);
1275 imm8 = mono_arm_is_rotated_imm8 (pagesize, &rot_amount);
1276 ARM_SUB_REG_IMM (code, ARMREG_IP, ARMREG_IP, imm8, rot_amount);
1277 ARM_LDR_IMM (code, MONO_ARCH_RGCTX_REG, ARMREG_IP, -8);
1278 ARM_LDR_IMM (code, ARMREG_PC, ARMREG_IP, -4);
1280 g_assert (code - buf == COMMON_TRAMP_SIZE);
1283 emit_bytes (acfg, buf, code - buf);
1285 for (i = 0; i < count; ++i) {
1287 ARM_MOV_REG_REG (code, ARMREG_IP, ARMREG_PC);
1289 arm_patch (code - 4, code - COMMON_TRAMP_SIZE - 8 * (i + 1));
1290 g_assert (code - buf == 8);
1291 emit_bytes (acfg, buf, code - buf);
1295 * gsharedvt arg trampolines: see arch_emit_gsharedvt_arg_trampoline ()
1297 sprintf (symbol, "%sgsharedvt_arg_trampolines_page", acfg->user_symbol_prefix);
1298 emit_global (acfg, symbol, TRUE);
1299 emit_label (acfg, symbol);
1301 ARM_PUSH (code, (1 << ARMREG_R0) | (1 << ARMREG_R1) | (1 << ARMREG_R2) | (1 << ARMREG_R3));
1302 imm8 = mono_arm_is_rotated_imm8 (pagesize, &rot_amount);
1303 ARM_SUB_REG_IMM (code, ARMREG_IP, ARMREG_IP, imm8, rot_amount);
1304 ARM_LDR_IMM (code, ARMREG_R0, ARMREG_IP, -8);
1305 ARM_LDR_IMM (code, ARMREG_PC, ARMREG_IP, -4);
1306 g_assert (code - buf == COMMON_TRAMP_SIZE);
1308 emit_bytes (acfg, buf, code - buf);
1310 for (i = 0; i < count; ++i) {
1312 ARM_MOV_REG_REG (code, ARMREG_IP, ARMREG_PC);
1314 arm_patch (code - 4, code - COMMON_TRAMP_SIZE - 8 * (i + 1));
1315 g_assert (code - buf == 8);
1316 emit_bytes (acfg, buf, code - buf);
1319 /* now the imt trampolines: each specific trampolines puts in the ip register
1320 * the instruction pointer address, so the generic trampoline at the start of the page
1321 * subtracts 4096 to get to the data page and loads the values
1323 #define IMT_TRAMP_SIZE 72
1324 sprintf (symbol, "%simt_trampolines_page", acfg->user_symbol_prefix);
1325 emit_global (acfg, symbol, TRUE);
1326 emit_label (acfg, symbol);
1328 /* Need at least two free registers, plus a slot for storing the pc */
1329 ARM_PUSH (code, (1 << ARMREG_R0)|(1 << ARMREG_R1)|(1 << ARMREG_R2));
1331 imm8 = mono_arm_is_rotated_imm8 (pagesize, &rot_amount);
1332 ARM_SUB_REG_IMM (code, ARMREG_IP, ARMREG_IP, imm8, rot_amount);
1333 ARM_LDR_IMM (code, ARMREG_R0, ARMREG_IP, -8);
1335 /* The IMT method is in v5, r0 has the imt array address */
1338 ARM_LDR_IMM (code, ARMREG_R1, ARMREG_R0, 0);
1339 ARM_CMP_REG_REG (code, ARMREG_R1, ARMREG_V5);
1340 imt_found_check = code;
1341 ARM_B_COND (code, ARMCOND_EQ, 0);
1343 /* End-of-loop check */
1344 ARM_CMP_REG_IMM (code, ARMREG_R1, 0, 0);
1345 loop_end_check = code;
1346 ARM_B_COND (code, ARMCOND_EQ, 0);
1349 ARM_ADD_REG_IMM8 (code, ARMREG_R0, ARMREG_R0, sizeof (gpointer) * 2);
1350 loop_branch_back = code;
1352 arm_patch (loop_branch_back, loop_start);
1355 arm_patch (imt_found_check, code);
1356 ARM_LDR_IMM (code, ARMREG_R0, ARMREG_R0, 4);
1357 ARM_LDR_IMM (code, ARMREG_R0, ARMREG_R0, 0);
1358 /* Save it to the third stack slot */
1359 ARM_STR_IMM (code, ARMREG_R0, ARMREG_SP, 8);
1360 /* Restore the registers and branch */
1361 ARM_POP (code, (1 << ARMREG_R0)|(1 << ARMREG_R1)|(1 << ARMREG_PC));
1364 arm_patch (loop_end_check, code);
1365 ARM_LDR_IMM (code, ARMREG_R0, ARMREG_R0, 4);
1366 ARM_STR_IMM (code, ARMREG_R0, ARMREG_SP, 8);
1367 ARM_POP (code, (1 << ARMREG_R0)|(1 << ARMREG_R1)|(1 << ARMREG_PC));
1371 g_assert (code - buf == IMT_TRAMP_SIZE);
1372 emit_bytes (acfg, buf, code - buf);
1374 for (i = 0; i < count; ++i) {
1376 ARM_MOV_REG_REG (code, ARMREG_IP, ARMREG_PC);
1378 arm_patch (code - 4, code - IMT_TRAMP_SIZE - 8 * (i + 1));
1379 g_assert (code - buf == 8);
1380 emit_bytes (acfg, buf, code - buf);
1383 acfg->tramp_page_code_offsets [MONO_AOT_TRAMP_SPECIFIC] = 16;
1384 acfg->tramp_page_code_offsets [MONO_AOT_TRAMP_STATIC_RGCTX] = 16;
1385 acfg->tramp_page_code_offsets [MONO_AOT_TRAMP_IMT_THUNK] = 72;
1386 acfg->tramp_page_code_offsets [MONO_AOT_TRAMP_GSHAREDVT_ARG] = 16;
1388 /* Unwind info for specifc trampolines */
1389 sprintf (symbol, "%sspecific_trampolines_page_gen_p", acfg->user_symbol_prefix);
1390 /* We unwind to the original caller, from the stack, since lr is clobbered */
1391 mono_add_unwind_op_def_cfa (unwind_ops, 0, 0, ARMREG_SP, 14 * sizeof (mgreg_t));
1392 mono_add_unwind_op_offset (unwind_ops, 0, 0, ARMREG_LR, -4);
1393 save_unwind_info (acfg, symbol, unwind_ops);
1394 mono_free_unwind_info (unwind_ops);
1396 sprintf (symbol, "%sspecific_trampolines_page_sp_p", acfg->user_symbol_prefix);
1397 mono_add_unwind_op_def_cfa (unwind_ops, 0, 0, ARMREG_SP, 0);
1398 mono_add_unwind_op_def_cfa_offset (unwind_ops, 4, 0, 14 * sizeof (mgreg_t));
1399 save_unwind_info (acfg, symbol, unwind_ops);
1400 mono_free_unwind_info (unwind_ops);
1402 /* Unwind info for rgctx trampolines */
1403 sprintf (symbol, "%srgctx_trampolines_page_gen_p", acfg->user_symbol_prefix);
1404 mono_add_unwind_op_def_cfa (unwind_ops, 0, 0, ARMREG_SP, 0);
1405 save_unwind_info (acfg, symbol, unwind_ops);
1407 sprintf (symbol, "%srgctx_trampolines_page_sp_p", acfg->user_symbol_prefix);
1408 save_unwind_info (acfg, symbol, unwind_ops);
1409 mono_free_unwind_info (unwind_ops);
1411 /* Unwind info for gsharedvt trampolines */
1412 sprintf (symbol, "%sgsharedvt_trampolines_page_gen_p", acfg->user_symbol_prefix);
1413 mono_add_unwind_op_def_cfa (unwind_ops, 0, 0, ARMREG_SP, 0);
1414 mono_add_unwind_op_def_cfa_offset (unwind_ops, 4, 0, 4 * sizeof (mgreg_t));
1415 save_unwind_info (acfg, symbol, unwind_ops);
1416 mono_free_unwind_info (unwind_ops);
1418 sprintf (symbol, "%sgsharedvt_trampolines_page_sp_p", acfg->user_symbol_prefix);
1419 mono_add_unwind_op_def_cfa (unwind_ops, 0, 0, ARMREG_SP, 0);
1420 save_unwind_info (acfg, symbol, unwind_ops);
1421 mono_free_unwind_info (unwind_ops);
1423 /* Unwind info for imt trampolines */
1424 sprintf (symbol, "%simt_trampolines_page_gen_p", acfg->user_symbol_prefix);
1425 mono_add_unwind_op_def_cfa (unwind_ops, 0, 0, ARMREG_SP, 0);
1426 mono_add_unwind_op_def_cfa_offset (unwind_ops, 4, 0, 3 * sizeof (mgreg_t));
1427 save_unwind_info (acfg, symbol, unwind_ops);
1428 mono_free_unwind_info (unwind_ops);
1430 sprintf (symbol, "%simt_trampolines_page_sp_p", acfg->user_symbol_prefix);
1431 mono_add_unwind_op_def_cfa (unwind_ops, 0, 0, ARMREG_SP, 0);
1432 save_unwind_info (acfg, symbol, unwind_ops);
1433 mono_free_unwind_info (unwind_ops);
1434 #elif defined(TARGET_ARM64)
1435 arm64_emit_specific_trampoline_pages (acfg);
1440 * arch_emit_specific_trampoline:
1442 * Emit code for a specific trampoline. OFFSET is the offset of the first of
1443 * two GOT slots which contain the generic trampoline address and the trampoline
1444 * argument. TRAMP_SIZE is set to the size of the emitted trampoline.
1447 arch_emit_specific_trampoline (MonoAotCompile *acfg, int offset, int *tramp_size)
1450 * The trampolines created here are variations of the specific
1451 * trampolines created in mono_arch_create_specific_trampoline (). The
1453 * - the generic trampoline address is taken from a got slot.
1454 * - the offset of the got slot where the trampoline argument is stored
1455 * is embedded in the instruction stream, and the generic trampoline
1456 * can load the argument by loading the offset, adding it to the
1457 * address of the trampoline to get the address of the got slot, and
1458 * loading the argument from there.
1459 * - all the trampolines should be of the same length.
1461 #if defined(TARGET_AMD64)
1462 #if defined(__default_codegen__)
1463 /* This should be exactly 8 bytes long */
1465 /* call *<offset>(%rip) */
1467 emit_unset_mode (acfg);
1468 fprintf (acfg->fp, "call *%s+%d(%%rip)\n", acfg->got_symbol, (int)(offset * sizeof (gpointer)));
1469 emit_zero_bytes (acfg, 2);
1471 emit_byte (acfg, '\x41');
1472 emit_byte (acfg, '\xff');
1473 emit_byte (acfg, '\x15');
1474 emit_symbol_diff (acfg, acfg->got_symbol, ".", (offset * sizeof (gpointer)) - 4);
1475 emit_zero_bytes (acfg, 1);
1477 #elif defined(__native_client_codegen__)
1479 guint8 *buf_aligned = ALIGN_TO(buf, kNaClAlignment);
1480 guint8 *code = buf_aligned;
1485 /* Emit this call in 'code' so we can find out how long it is. */
1486 amd64_call_reg (code, AMD64_R11);
1487 call_start = mono_arch_nacl_skip_nops (buf_aligned);
1488 call_len = code - call_start;
1490 /* The tramp_size is twice the NaCl alignment because it starts with */
1491 /* a call which needs to be aligned to the end of the boundary. */
1492 *tramp_size = kNaClAlignment*2;
1494 /* Emit nops to align call site below which is 7 bytes plus */
1495 /* the length of the call sequence emitted above. */
1496 /* Note: this requires the specific trampoline starts on a */
1497 /* kNaclAlignedment aligned address, which it does because */
1498 /* it's its own function that is aligned. */
1499 guint8 nop_buf[256];
1500 guint8 *nopbuf_aligned = ALIGN_TO (nop_buf, kNaClAlignment);
1501 guint8 *nopbuf_end = mono_arch_nacl_pad (nopbuf_aligned, kNaClAlignment - 7 - (call_len));
1502 emit_bytes (acfg, nopbuf_aligned, nopbuf_end - nopbuf_aligned);
1504 /* The trampoline is stored at the offset'th pointer, the -4 is */
1505 /* present because RIP relative addressing starts at the end of */
1506 /* the current instruction, while the label "." is relative to */
1507 /* the beginning of the current asm location, which in this case */
1508 /* is not the mov instruction, but the offset itself, due to the */
1509 /* way the bytes and ints are emitted here. */
1510 got_offset = (offset * sizeof(gpointer)) - 4;
1512 /* mov <OFFSET>(%rip), %r11d */
1513 emit_byte (acfg, '\x45');
1514 emit_byte (acfg, '\x8b');
1515 emit_byte (acfg, '\x1d');
1516 emit_symbol_diff (acfg, acfg->got_symbol, ".", got_offset);
1519 emit_bytes (acfg, call_start, call_len);
1521 /* The arg is stored at the offset+1 pointer, relative to beginning */
1522 /* of trampoline: 7 for mov, plus the call length, and 1 for push. */
1523 got_offset = ((offset + 1) * sizeof(gpointer)) + 7 + call_len + 1;
1525 /* We can't emit this data directly, hide in a "push imm32" */
1526 emit_byte (acfg, '\x68'); /* push */
1527 emit_symbol_diff (acfg, acfg->got_symbol, ".", got_offset);
1528 emit_alignment (acfg, kNaClAlignment);
1529 #endif /*__native_client_codegen__*/
1530 #elif defined(TARGET_ARM)
1534 /* This should be exactly 20 bytes long */
1537 ARM_PUSH (code, 0x5fff);
1538 ARM_LDR_IMM (code, ARMREG_R1, ARMREG_PC, 4);
1539 /* Load the value from the GOT */
1540 ARM_LDR_REG_REG (code, ARMREG_R1, ARMREG_PC, ARMREG_R1);
1542 ARM_BLX_REG (code, ARMREG_R1);
1544 g_assert (code - buf == 16);
1547 emit_bytes (acfg, buf, code - buf);
1549 * Only one offset is needed, since the second one would be equal to the
1552 emit_symbol_diff (acfg, acfg->got_symbol, ".", (offset * sizeof (gpointer)) - 4 + 4);
1553 //emit_symbol_diff (acfg, acfg->got_symbol, ".", ((offset + 1) * sizeof (gpointer)) - 4 + 8);
1554 #elif defined(TARGET_ARM64)
1555 arm64_emit_specific_trampoline (acfg, offset, tramp_size);
1556 #elif defined(TARGET_POWERPC)
1564 * PPC has no ip relative addressing, so we need to compute the address
1565 * of the mscorlib got. That is slow and complex, so instead, we store it
1566 * in the second got slot of every aot image. The caller already computed
1567 * the address of its got and placed it into r30.
1569 emit_unset_mode (acfg);
1570 /* Load mscorlib got address */
1571 fprintf (acfg->fp, "%s 0, %d(30)\n", PPC_LD_OP, (int)sizeof (gpointer));
1572 /* Load generic trampoline address */
1573 fprintf (acfg->fp, "lis 11, %d@h\n", (int)(offset * sizeof (gpointer)));
1574 fprintf (acfg->fp, "ori 11, 11, %d@l\n", (int)(offset * sizeof (gpointer)));
1575 fprintf (acfg->fp, "%s 11, 11, 0\n", PPC_LDX_OP);
1576 #ifdef PPC_USES_FUNCTION_DESCRIPTOR
1577 fprintf (acfg->fp, "%s 11, 0(11)\n", PPC_LD_OP);
1579 fprintf (acfg->fp, "mtctr 11\n");
1580 /* Load trampoline argument */
1581 /* On ppc, we pass it normally to the generic trampoline */
1582 fprintf (acfg->fp, "lis 11, %d@h\n", (int)((offset + 1) * sizeof (gpointer)));
1583 fprintf (acfg->fp, "ori 11, 11, %d@l\n", (int)((offset + 1) * sizeof (gpointer)));
1584 fprintf (acfg->fp, "%s 0, 11, 0\n", PPC_LDX_OP);
1585 /* Branch to generic trampoline */
1586 fprintf (acfg->fp, "bctr\n");
1588 #ifdef PPC_USES_FUNCTION_DESCRIPTOR
1589 *tramp_size = 10 * 4;
1591 *tramp_size = 9 * 4;
1593 #elif defined(TARGET_X86)
1597 /* Similar to the PPC code above */
1599 /* FIXME: Could this clobber the register needed by get_vcall_slot () ? */
1602 /* Load mscorlib got address */
1603 x86_mov_reg_membase (code, X86_ECX, MONO_ARCH_GOT_REG, sizeof (gpointer), 4);
1604 /* Push trampoline argument */
1605 x86_push_membase (code, X86_ECX, (offset + 1) * sizeof (gpointer));
1606 /* Load generic trampoline address */
1607 x86_mov_reg_membase (code, X86_ECX, X86_ECX, offset * sizeof (gpointer), 4);
1608 /* Branch to generic trampoline */
1609 x86_jump_reg (code, X86_ECX);
1611 #ifdef __native_client_codegen__
1613 /* emit nops to next 32 byte alignment */
1614 int a = (~kNaClAlignmentMask) & ((code - buf) + kNaClAlignment - 1);
1615 while (code < (buf + a)) x86_nop(code);
1618 emit_bytes (acfg, buf, code - buf);
1620 *tramp_size = NACL_SIZE(17, kNaClAlignment);
1621 g_assert (code - buf == *tramp_size);
1623 g_assert_not_reached ();
1628 * arch_emit_unbox_trampoline:
1630 * Emit code for the unbox trampoline for METHOD used in the full-aot case.
1631 * CALL_TARGET is the symbol pointing to the native code of METHOD.
1634 arch_emit_unbox_trampoline (MonoAotCompile *acfg, MonoCompile *cfg, MonoMethod *method, const char *call_target)
1636 #if defined(TARGET_AMD64)
1641 this_reg = mono_arch_get_this_arg_reg (NULL);
1643 amd64_alu_reg_imm (code, X86_ADD, this_reg, sizeof (MonoObject));
1645 emit_bytes (acfg, buf, code - buf);
1648 emit_unset_mode (acfg);
1649 fprintf (acfg->fp, "jmp %s\n", call_target);
1651 emit_byte (acfg, '\xe9');
1652 emit_symbol_diff (acfg, call_target, ".", -4);
1654 #elif defined(TARGET_X86)
1661 x86_alu_membase_imm (code, X86_ADD, X86_ESP, this_pos, sizeof (MonoObject));
1663 emit_bytes (acfg, buf, code - buf);
1666 emit_byte (acfg, '\xe9');
1667 emit_symbol_diff (acfg, call_target, ".", -4);
1668 #elif defined(TARGET_ARM)
1672 if (acfg->thumb_mixed && cfg->compile_llvm) {
1673 fprintf (acfg->fp, "add r0, r0, #%d\n", (int)sizeof (MonoObject));
1674 fprintf (acfg->fp, "b %s\n", call_target);
1675 fprintf (acfg->fp, ".arm\n");
1676 fprintf (acfg->fp, ".align 2\n");
1682 ARM_ADD_REG_IMM8 (code, ARMREG_R0, ARMREG_R0, sizeof (MonoObject));
1684 emit_bytes (acfg, buf, code - buf);
1685 /* jump to method */
1686 if (acfg->thumb_mixed && cfg->compile_llvm)
1687 fprintf (acfg->fp, "\n\tbx %s\n", call_target);
1689 fprintf (acfg->fp, "\n\tb %s\n", call_target);
1690 #elif defined(TARGET_ARM64)
1691 arm64_emit_unbox_trampoline (acfg, cfg, method, call_target);
1692 #elif defined(TARGET_POWERPC)
1695 fprintf (acfg->fp, "\n\taddi %d, %d, %d\n", this_pos, this_pos, (int)sizeof (MonoObject));
1696 fprintf (acfg->fp, "\n\tb %s\n", call_target);
1698 g_assert_not_reached ();
1703 * arch_emit_static_rgctx_trampoline:
1705 * Emit code for a static rgctx trampoline. OFFSET is the offset of the first of
1706 * two GOT slots which contain the rgctx argument, and the method to jump to.
1707 * TRAMP_SIZE is set to the size of the emitted trampoline.
1708 * These kinds of trampolines cannot be enumerated statically, since there could
1709 * be one trampoline per method instantiation, so we emit the same code for all
1710 * trampolines, and parameterize them using two GOT slots.
1713 arch_emit_static_rgctx_trampoline (MonoAotCompile *acfg, int offset, int *tramp_size)
1715 #if defined(TARGET_AMD64)
1716 #if defined(__default_codegen__)
1717 /* This should be exactly 13 bytes long */
1721 emit_unset_mode (acfg);
1722 fprintf (acfg->fp, "mov %s+%d(%%rip), %%r10\n", acfg->got_symbol, (int)(offset * sizeof (gpointer)));
1723 fprintf (acfg->fp, "jmp *%s+%d(%%rip)\n", acfg->got_symbol, (int)((offset + 1) * sizeof (gpointer)));
1725 /* mov <OFFSET>(%rip), %r10 */
1726 emit_byte (acfg, '\x4d');
1727 emit_byte (acfg, '\x8b');
1728 emit_byte (acfg, '\x15');
1729 emit_symbol_diff (acfg, acfg->got_symbol, ".", (offset * sizeof (gpointer)) - 4);
1731 /* jmp *<offset>(%rip) */
1732 emit_byte (acfg, '\xff');
1733 emit_byte (acfg, '\x25');
1734 emit_symbol_diff (acfg, acfg->got_symbol, ".", ((offset + 1) * sizeof (gpointer)) - 4);
1736 #elif defined(__native_client_codegen__)
1738 guint8 *buf_aligned = ALIGN_TO(buf, kNaClAlignment);
1739 guint8 *code = buf_aligned;
1741 /* mov <OFFSET>(%rip), %r10d */
1742 emit_byte (acfg, '\x45');
1743 emit_byte (acfg, '\x8b');
1744 emit_byte (acfg, '\x15');
1745 emit_symbol_diff (acfg, acfg->got_symbol, ".", (offset * sizeof (gpointer)) - 4);
1747 /* mov <OFFSET>(%rip), %r11d */
1748 emit_byte (acfg, '\x45');
1749 emit_byte (acfg, '\x8b');
1750 emit_byte (acfg, '\x1d');
1751 emit_symbol_diff (acfg, acfg->got_symbol, ".", ((offset + 1) * sizeof (gpointer)) - 4);
1754 amd64_jump_reg (code, AMD64_R11);
1755 emit_bytes (acfg, buf_aligned, code - buf_aligned);
1757 emit_alignment (acfg, kNaClAlignment);
1758 *tramp_size = kNaClAlignment;
1759 #endif /*__native_client_codegen__*/
1761 #elif defined(TARGET_ARM)
1765 /* This should be exactly 24 bytes long */
1768 /* Load rgctx value */
1769 ARM_LDR_IMM (code, ARMREG_IP, ARMREG_PC, 8);
1770 ARM_LDR_REG_REG (code, MONO_ARCH_RGCTX_REG, ARMREG_PC, ARMREG_IP);
1771 /* Load branch addr + branch */
1772 ARM_LDR_IMM (code, ARMREG_IP, ARMREG_PC, 4);
1773 ARM_LDR_REG_REG (code, ARMREG_PC, ARMREG_PC, ARMREG_IP);
1775 g_assert (code - buf == 16);
1778 emit_bytes (acfg, buf, code - buf);
1779 emit_symbol_diff (acfg, acfg->got_symbol, ".", (offset * sizeof (gpointer)) - 4 + 8);
1780 emit_symbol_diff (acfg, acfg->got_symbol, ".", ((offset + 1) * sizeof (gpointer)) - 4 + 4);
1781 #elif defined(TARGET_ARM64)
1782 arm64_emit_static_rgctx_trampoline (acfg, offset, tramp_size);
1783 #elif defined(TARGET_POWERPC)
1791 * PPC has no ip relative addressing, so we need to compute the address
1792 * of the mscorlib got. That is slow and complex, so instead, we store it
1793 * in the second got slot of every aot image. The caller already computed
1794 * the address of its got and placed it into r30.
1796 emit_unset_mode (acfg);
1797 /* Load mscorlib got address */
1798 fprintf (acfg->fp, "%s 0, %d(30)\n", PPC_LD_OP, (int)sizeof (gpointer));
1800 fprintf (acfg->fp, "lis 11, %d@h\n", (int)(offset * sizeof (gpointer)));
1801 fprintf (acfg->fp, "ori 11, 11, %d@l\n", (int)(offset * sizeof (gpointer)));
1802 fprintf (acfg->fp, "%s %d, 11, 0\n", PPC_LDX_OP, MONO_ARCH_RGCTX_REG);
1803 /* Load target address */
1804 fprintf (acfg->fp, "lis 11, %d@h\n", (int)((offset + 1) * sizeof (gpointer)));
1805 fprintf (acfg->fp, "ori 11, 11, %d@l\n", (int)((offset + 1) * sizeof (gpointer)));
1806 fprintf (acfg->fp, "%s 11, 11, 0\n", PPC_LDX_OP);
1807 #ifdef PPC_USES_FUNCTION_DESCRIPTOR
1808 fprintf (acfg->fp, "%s 2, %d(11)\n", PPC_LD_OP, (int)sizeof (gpointer));
1809 fprintf (acfg->fp, "%s 11, 0(11)\n", PPC_LD_OP);
1811 fprintf (acfg->fp, "mtctr 11\n");
1812 /* Branch to the target address */
1813 fprintf (acfg->fp, "bctr\n");
1815 #ifdef PPC_USES_FUNCTION_DESCRIPTOR
1816 *tramp_size = 11 * 4;
1818 *tramp_size = 9 * 4;
1821 #elif defined(TARGET_X86)
1825 /* Similar to the PPC code above */
1827 g_assert (MONO_ARCH_RGCTX_REG != X86_ECX);
1830 /* Load mscorlib got address */
1831 x86_mov_reg_membase (code, X86_ECX, MONO_ARCH_GOT_REG, sizeof (gpointer), 4);
1833 x86_mov_reg_membase (code, MONO_ARCH_RGCTX_REG, X86_ECX, offset * sizeof (gpointer), 4);
1834 /* Branch to the target address */
1835 x86_jump_membase (code, X86_ECX, (offset + 1) * sizeof (gpointer));
1837 #ifdef __native_client_codegen__
1839 /* emit nops to next 32 byte alignment */
1840 int a = (~kNaClAlignmentMask) & ((code - buf) + kNaClAlignment - 1);
1841 while (code < (buf + a)) x86_nop(code);
1845 emit_bytes (acfg, buf, code - buf);
1847 *tramp_size = NACL_SIZE (15, kNaClAlignment);
1848 g_assert (code - buf == *tramp_size);
1850 g_assert_not_reached ();
1855 * arch_emit_imt_thunk:
1857 * Emit an IMT thunk usable in full-aot mode. The thunk uses 1 got slot which
1858 * points to an array of pointer pairs. The pairs of the form [key, ptr], where
1859 * key is the IMT key, and ptr holds the address of a memory location holding
1860 * the address to branch to if the IMT arg matches the key. The array is
1861 * terminated by a pair whose key is NULL, and whose ptr is the address of the
1863 * TRAMP_SIZE is set to the size of the emitted trampoline.
1866 arch_emit_imt_thunk (MonoAotCompile *acfg, int offset, int *tramp_size)
1868 #if defined(TARGET_AMD64)
1870 #if defined(__native_client_codegen__)
1873 guint8 *labels [16];
1875 guint8 *mov_buf_ptr = mov_buf;
1877 const int kSizeOfMove = 7;
1878 #if defined(__default_codegen__)
1879 code = buf = (guint8 *)g_malloc (256);
1880 #elif defined(__native_client_codegen__)
1881 buf_alloc = g_malloc (256 + kNaClAlignment + kSizeOfMove);
1882 buf = ((guint)buf_alloc + kNaClAlignment) & ~kNaClAlignmentMask;
1883 /* The RIP relative move below is emitted first */
1888 /* FIXME: Optimize this, i.e. use binary search etc. */
1889 /* Maybe move the body into a separate function (slower, but much smaller) */
1891 /* MONO_ARCH_IMT_SCRATCH_REG is a free register */
1894 emit_unset_mode (acfg);
1895 fprintf (acfg->fp, "mov %s+%d(%%rip), %s\n", acfg->got_symbol, (int)(offset * sizeof (gpointer)), mono_arch_regname (MONO_ARCH_IMT_SCRATCH_REG));
1899 amd64_alu_membase_imm (code, X86_CMP, MONO_ARCH_IMT_SCRATCH_REG, 0, 0);
1901 amd64_branch8 (code, X86_CC_Z, 0, FALSE);
1904 amd64_alu_membase_reg_size (code, X86_CMP, MONO_ARCH_IMT_SCRATCH_REG, 0, MONO_ARCH_IMT_REG, sizeof (gpointer));
1906 amd64_branch8 (code, X86_CC_Z, 0, FALSE);
1909 amd64_alu_reg_imm (code, X86_ADD, MONO_ARCH_IMT_SCRATCH_REG, 2 * sizeof (gpointer));
1910 amd64_jump_code (code, labels [0]);
1913 mono_amd64_patch (labels [2], code);
1914 amd64_mov_reg_membase (code, MONO_ARCH_IMT_SCRATCH_REG, MONO_ARCH_IMT_SCRATCH_REG, sizeof (gpointer), sizeof (gpointer));
1915 amd64_jump_membase (code, MONO_ARCH_IMT_SCRATCH_REG, 0);
1918 mono_amd64_patch (labels [1], code);
1919 /* Load fail tramp */
1920 amd64_alu_reg_imm (code, X86_ADD, MONO_ARCH_IMT_SCRATCH_REG, sizeof (gpointer));
1921 /* Check if there is a fail tramp */
1922 amd64_alu_membase_imm (code, X86_CMP, MONO_ARCH_IMT_SCRATCH_REG, 0, 0);
1924 amd64_branch8 (code, X86_CC_Z, 0, FALSE);
1925 /* Jump to fail tramp */
1926 amd64_jump_membase (code, MONO_ARCH_IMT_SCRATCH_REG, 0);
1929 mono_amd64_patch (labels [3], code);
1930 x86_breakpoint (code);
1933 /* mov <OFFSET>(%rip), MONO_ARCH_IMT_SCRATCH_REG */
1934 amd64_emit_rex (mov_buf_ptr, sizeof(gpointer), MONO_ARCH_IMT_SCRATCH_REG, 0, AMD64_RIP);
1935 *(mov_buf_ptr)++ = (unsigned char)0x8b; /* mov opcode */
1936 x86_address_byte (mov_buf_ptr, 0, MONO_ARCH_IMT_SCRATCH_REG & 0x7, 5);
1937 emit_bytes (acfg, mov_buf, mov_buf_ptr - mov_buf);
1938 emit_symbol_diff (acfg, acfg->got_symbol, ".", (offset * sizeof (gpointer)) - 4);
1940 emit_bytes (acfg, buf, code - buf);
1942 *tramp_size = code - buf + kSizeOfMove;
1943 #if defined(__native_client_codegen__)
1944 /* The tramp will be padded to the next kNaClAlignment bundle. */
1945 *tramp_size = ALIGN_TO ((*tramp_size), kNaClAlignment);
1948 #if defined(__default_codegen__)
1950 #elif defined(__native_client_codegen__)
1954 #elif defined(TARGET_X86)
1956 #ifdef __native_client_codegen__
1959 guint8 *labels [16];
1961 #if defined(__default_codegen__)
1962 code = buf = g_malloc (256);
1963 #elif defined(__native_client_codegen__)
1964 buf_alloc = g_malloc (256 + kNaClAlignment);
1965 code = buf = ((guint)buf_alloc + kNaClAlignment) & ~kNaClAlignmentMask;
1968 /* Allocate a temporary stack slot */
1969 x86_push_reg (code, X86_EAX);
1971 x86_push_reg (code, X86_EAX);
1973 /* Load mscorlib got address */
1974 x86_mov_reg_membase (code, X86_EAX, MONO_ARCH_GOT_REG, sizeof (gpointer), 4);
1976 x86_mov_reg_membase (code, X86_EAX, X86_EAX, offset * sizeof (gpointer), 4);
1979 x86_alu_membase_imm (code, X86_CMP, X86_EAX, 0, 0);
1981 x86_branch8 (code, X86_CC_Z, FALSE, 0);
1984 x86_alu_membase_reg (code, X86_CMP, X86_EAX, 0, MONO_ARCH_IMT_REG);
1986 x86_branch8 (code, X86_CC_Z, FALSE, 0);
1989 x86_alu_reg_imm (code, X86_ADD, X86_EAX, 2 * sizeof (gpointer));
1990 x86_jump_code (code, labels [0]);
1993 mono_x86_patch (labels [2], code);
1994 x86_mov_reg_membase (code, X86_EAX, X86_EAX, sizeof (gpointer), 4);
1995 x86_mov_reg_membase (code, X86_EAX, X86_EAX, 0, 4);
1996 /* Save the target address to the temporary stack location */
1997 x86_mov_membase_reg (code, X86_ESP, 4, X86_EAX, 4);
1999 x86_pop_reg (code, X86_EAX);
2000 /* Jump to the target address */
2004 mono_x86_patch (labels [1], code);
2005 /* Load fail tramp */
2006 x86_mov_reg_membase (code, X86_EAX, X86_EAX, sizeof (gpointer), 4);
2007 x86_alu_membase_imm (code, X86_CMP, X86_EAX, 0, 0);
2009 x86_branch8 (code, X86_CC_Z, FALSE, 0);
2010 /* Jump to fail tramp */
2011 x86_mov_membase_reg (code, X86_ESP, 4, X86_EAX, 4);
2012 x86_pop_reg (code, X86_EAX);
2016 mono_x86_patch (labels [3], code);
2017 x86_breakpoint (code);
2019 #ifdef __native_client_codegen__
2021 /* emit nops to next 32 byte alignment */
2022 int a = (~kNaClAlignmentMask) & ((code - buf) + kNaClAlignment - 1);
2023 while (code < (buf + a)) x86_nop(code);
2026 emit_bytes (acfg, buf, code - buf);
2028 *tramp_size = code - buf;
2030 #if defined(__default_codegen__)
2032 #elif defined(__native_client_codegen__)
2036 #elif defined(TARGET_ARM)
2038 guint8 *code, *code2, *labels [16];
2042 /* The IMT method is in v5 */
2044 /* Need at least two free registers, plus a slot for storing the pc */
2045 ARM_PUSH (code, (1 << ARMREG_R0)|(1 << ARMREG_R1)|(1 << ARMREG_R2));
2047 /* Load the parameter from the GOT */
2048 ARM_LDR_IMM (code, ARMREG_R0, ARMREG_PC, 0);
2049 ARM_LDR_REG_REG (code, ARMREG_R0, ARMREG_PC, ARMREG_R0);
2052 ARM_LDR_IMM (code, ARMREG_R1, ARMREG_R0, 0);
2053 ARM_CMP_REG_REG (code, ARMREG_R1, ARMREG_V5);
2055 ARM_B_COND (code, ARMCOND_EQ, 0);
2057 /* End-of-loop check */
2058 ARM_CMP_REG_IMM (code, ARMREG_R1, 0, 0);
2060 ARM_B_COND (code, ARMCOND_EQ, 0);
2063 ARM_ADD_REG_IMM8 (code, ARMREG_R0, ARMREG_R0, sizeof (gpointer) * 2);
2066 arm_patch (labels [4], labels [1]);
2069 arm_patch (labels [2], code);
2070 ARM_LDR_IMM (code, ARMREG_R0, ARMREG_R0, 4);
2071 ARM_LDR_IMM (code, ARMREG_R0, ARMREG_R0, 0);
2072 /* Save it to the third stack slot */
2073 ARM_STR_IMM (code, ARMREG_R0, ARMREG_SP, 8);
2074 /* Restore the registers and branch */
2075 ARM_POP (code, (1 << ARMREG_R0)|(1 << ARMREG_R1)|(1 << ARMREG_PC));
2078 arm_patch (labels [3], code);
2079 ARM_LDR_IMM (code, ARMREG_R0, ARMREG_R0, 4);
2080 ARM_STR_IMM (code, ARMREG_R0, ARMREG_SP, 8);
2081 ARM_POP (code, (1 << ARMREG_R0)|(1 << ARMREG_R1)|(1 << ARMREG_PC));
2085 ARM_LDR_IMM (code2, ARMREG_R0, ARMREG_PC, (code - (labels [0] + 8)));
2087 emit_bytes (acfg, buf, code - buf);
2088 emit_symbol_diff (acfg, acfg->got_symbol, ".", (offset * sizeof (gpointer)) + (code - (labels [0] + 8)) - 4);
2090 *tramp_size = code - buf + 4;
2091 #elif defined(TARGET_ARM64)
2092 arm64_emit_imt_thunk (acfg, offset, tramp_size);
2093 #elif defined(TARGET_POWERPC)
2095 guint8 *code, *labels [16];
2099 /* Load the mscorlib got address */
2100 ppc_ldptr (code, ppc_r12, sizeof (gpointer), ppc_r30);
2101 /* Load the parameter from the GOT */
2102 ppc_load (code, ppc_r0, offset * sizeof (gpointer));
2103 ppc_ldptr_indexed (code, ppc_r12, ppc_r12, ppc_r0);
2105 /* Load and check key */
2107 ppc_ldptr (code, ppc_r0, 0, ppc_r12);
2108 ppc_cmp (code, 0, sizeof (gpointer) == 8 ? 1 : 0, ppc_r0, MONO_ARCH_IMT_REG);
2110 ppc_bc (code, PPC_BR_TRUE, PPC_BR_EQ, 0);
2112 /* End-of-loop check */
2113 ppc_cmpi (code, 0, sizeof (gpointer) == 8 ? 1 : 0, ppc_r0, 0);
2115 ppc_bc (code, PPC_BR_TRUE, PPC_BR_EQ, 0);
2118 ppc_addi (code, ppc_r12, ppc_r12, 2 * sizeof (gpointer));
2121 mono_ppc_patch (labels [4], labels [1]);
2124 mono_ppc_patch (labels [2], code);
2125 ppc_ldptr (code, ppc_r12, sizeof (gpointer), ppc_r12);
2126 /* r12 now contains the value of the vtable slot */
2127 /* this is not a function descriptor on ppc64 */
2128 ppc_ldptr (code, ppc_r12, 0, ppc_r12);
2129 ppc_mtctr (code, ppc_r12);
2130 ppc_bcctr (code, PPC_BR_ALWAYS, 0);
2133 mono_ppc_patch (labels [3], code);
2137 *tramp_size = code - buf;
2139 emit_bytes (acfg, buf, code - buf);
2141 g_assert_not_reached ();
2146 #if defined (TARGET_AMD64)
2149 amd64_emit_load_got_slot (MonoAotCompile *acfg, int dreg, int got_slot)
2152 g_assert (acfg->fp);
2153 emit_unset_mode (acfg);
2155 fprintf (acfg->fp, "mov %s+%d(%%rip), %s\n", acfg->got_symbol, (unsigned int) ((got_slot * sizeof (gpointer))), mono_arch_regname (dreg));
2162 * arch_emit_gsharedvt_arg_trampoline:
2164 * Emit code for a gsharedvt arg trampoline. OFFSET is the offset of the first of
2165 * two GOT slots which contain the argument, and the code to jump to.
2166 * TRAMP_SIZE is set to the size of the emitted trampoline.
2167 * These kinds of trampolines cannot be enumerated statically, since there could
2168 * be one trampoline per method instantiation, so we emit the same code for all
2169 * trampolines, and parameterize them using two GOT slots.
2172 arch_emit_gsharedvt_arg_trampoline (MonoAotCompile *acfg, int offset, int *tramp_size)
2174 #if defined(TARGET_X86)
2178 /* Similar to the PPC code above */
2180 g_assert (MONO_ARCH_RGCTX_REG != X86_ECX);
2183 /* Load mscorlib got address */
2184 x86_mov_reg_membase (code, X86_ECX, MONO_ARCH_GOT_REG, sizeof (gpointer), 4);
2186 x86_mov_reg_membase (code, X86_EAX, X86_ECX, offset * sizeof (gpointer), 4);
2187 /* Branch to the target address */
2188 x86_jump_membase (code, X86_ECX, (offset + 1) * sizeof (gpointer));
2190 #ifdef __native_client_codegen__
2192 /* emit nops to next 32 byte alignment */
2193 int a = (~kNaClAlignmentMask) & ((code - buf) + kNaClAlignment - 1);
2194 while (code < (buf + a)) x86_nop(code);
2198 emit_bytes (acfg, buf, code - buf);
2200 *tramp_size = NACL_SIZE (15, kNaClAlignment);
2201 g_assert (code - buf == *tramp_size);
2202 #elif defined(TARGET_ARM)
2206 /* The same as mono_arch_get_gsharedvt_arg_trampoline (), but for AOT */
2207 /* Similar to arch_emit_specific_trampoline () */
2210 ARM_PUSH (code, (1 << ARMREG_R0) | (1 << ARMREG_R1) | (1 << ARMREG_R2) | (1 << ARMREG_R3));
2211 ARM_LDR_IMM (code, ARMREG_R1, ARMREG_PC, 8);
2212 /* Load the arg value from the GOT */
2213 ARM_LDR_REG_REG (code, ARMREG_R0, ARMREG_PC, ARMREG_R1);
2214 /* Load the addr from the GOT */
2215 ARM_LDR_REG_REG (code, ARMREG_R1, ARMREG_PC, ARMREG_R1);
2217 ARM_BX (code, ARMREG_R1);
2219 g_assert (code - buf == 20);
2222 emit_bytes (acfg, buf, code - buf);
2223 emit_symbol_diff (acfg, acfg->got_symbol, ".", (offset * sizeof (gpointer)) + 4);
2224 #elif defined(TARGET_ARM64)
2225 arm64_emit_gsharedvt_arg_trampoline (acfg, offset, tramp_size);
2226 #elif defined (TARGET_AMD64)
2228 amd64_emit_load_got_slot (acfg, AMD64_RAX, offset);
2229 amd64_emit_load_got_slot (acfg, MONO_ARCH_IMT_SCRATCH_REG, offset + 1);
2230 g_assert (AMD64_R11 == MONO_ARCH_IMT_SCRATCH_REG);
2231 fprintf (acfg->fp, "jmp *%%r11\n");
2235 g_assert_not_reached ();
2239 /* END OF ARCH SPECIFIC CODE */
2242 mono_get_field_token (MonoClassField *field)
2244 MonoClass *klass = field->parent;
2247 for (i = 0; i < klass->field.count; ++i) {
2248 if (field == &klass->fields [i])
2249 return MONO_TOKEN_FIELD_DEF | (klass->field.first + 1 + i);
2252 g_assert_not_reached ();
2257 encode_value (gint32 value, guint8 *buf, guint8 **endbuf)
2261 //printf ("ENCODE: %d 0x%x.\n", value, value);
2264 * Same encoding as the one used in the metadata, extended to handle values
2265 * greater than 0x1fffffff.
2267 if ((value >= 0) && (value <= 127))
2269 else if ((value >= 0) && (value <= 16383)) {
2270 p [0] = 0x80 | (value >> 8);
2271 p [1] = value & 0xff;
2273 } else if ((value >= 0) && (value <= 0x1fffffff)) {
2274 p [0] = (value >> 24) | 0xc0;
2275 p [1] = (value >> 16) & 0xff;
2276 p [2] = (value >> 8) & 0xff;
2277 p [3] = value & 0xff;
2282 p [1] = (value >> 24) & 0xff;
2283 p [2] = (value >> 16) & 0xff;
2284 p [3] = (value >> 8) & 0xff;
2285 p [4] = value & 0xff;
2293 stream_init (MonoDynamicStream *sh)
2296 sh->alloc_size = 4096;
2297 sh->data = (char *)g_malloc (4096);
2299 /* So offsets are > 0 */
2305 make_room_in_stream (MonoDynamicStream *stream, int size)
2307 if (size <= stream->alloc_size)
2310 while (stream->alloc_size <= size) {
2311 if (stream->alloc_size < 4096)
2312 stream->alloc_size = 4096;
2314 stream->alloc_size *= 2;
2317 stream->data = (char *)g_realloc (stream->data, stream->alloc_size);
2321 add_stream_data (MonoDynamicStream *stream, const char *data, guint32 len)
2325 make_room_in_stream (stream, stream->index + len);
2326 memcpy (stream->data + stream->index, data, len);
2327 idx = stream->index;
2328 stream->index += len;
2335 * Add data to the binary blob inside the aot image. Returns the offset inside the
2336 * blob where the data was stored.
2339 add_to_blob (MonoAotCompile *acfg, const guint8 *data, guint32 data_len)
2341 g_assert (!acfg->blob_closed);
2343 if (acfg->blob.alloc_size == 0)
2344 stream_init (&acfg->blob);
2346 return add_stream_data (&acfg->blob, (char*)data, data_len);
2350 add_to_blob_aligned (MonoAotCompile *acfg, const guint8 *data, guint32 data_len, guint32 align)
2355 if (acfg->blob.alloc_size == 0)
2356 stream_init (&acfg->blob);
2358 count = acfg->blob.index % align;
2360 /* we assume the stream data will be aligned */
2362 add_stream_data (&acfg->blob, buf, 4 - count);
2364 return add_stream_data (&acfg->blob, (char*)data, data_len);
2367 /* Emit a table of data into the aot image */
2369 emit_aot_data (MonoAotCompile *acfg, MonoAotFileTable table, const char *symbol, guint8 *data, int size)
2371 if (acfg->data_outfile) {
2372 acfg->table_offsets [(int)table] = acfg->datafile_offset;
2373 fwrite (data,1, size, acfg->data_outfile);
2374 acfg->datafile_offset += size;
2375 // align the data to 8 bytes. Put zeros in the file (so that every build results in consistent output).
2376 int align = 8 - size % 8;
2377 acfg->datafile_offset += align;
2378 guint8 align_buf [16];
2379 memset (&align_buf, 0, sizeof (align_buf));
2380 fwrite (align_buf, align, 1, acfg->data_outfile);
2381 } else if (acfg->llvm) {
2382 mono_llvm_emit_aot_data (symbol, data, size);
2384 emit_section_change (acfg, RODATA_SECT, 0);
2385 emit_alignment (acfg, 8);
2386 emit_label (acfg, symbol);
2387 emit_bytes (acfg, data, size);
2392 * emit_offset_table:
2394 * Emit a table of increasing offsets in a compact form using differential encoding.
2395 * There is an index entry for each GROUP_SIZE number of entries. The greater the
2396 * group size, the more compact the table becomes, but the slower it becomes to compute
2397 * a given entry. Returns the size of the table.
2400 emit_offset_table (MonoAotCompile *acfg, const char *symbol, MonoAotFileTable table, int noffsets, int group_size, gint32 *offsets)
2402 gint32 current_offset;
2403 int i, buf_size, ngroups, index_entry_size;
2405 guint8 *data_p, *data_buf;
2406 guint32 *index_offsets;
2408 ngroups = (noffsets + (group_size - 1)) / group_size;
2410 index_offsets = g_new0 (guint32, ngroups);
2412 buf_size = noffsets * 4;
2413 p = buf = (guint8 *)g_malloc0 (buf_size);
2416 for (i = 0; i < noffsets; ++i) {
2417 //printf ("D: %d -> %d\n", i, offsets [i]);
2418 if ((i % group_size) == 0) {
2419 index_offsets [i / group_size] = p - buf;
2420 /* Emit the full value for these entries */
2421 encode_value (offsets [i], p, &p);
2423 /* The offsets are allowed to be non-increasing */
2424 //g_assert (offsets [i] >= current_offset);
2425 encode_value (offsets [i] - current_offset, p, &p);
2427 current_offset = offsets [i];
2432 if (ngroups && index_offsets [ngroups - 1] < 65000)
2433 index_entry_size = 2;
2435 index_entry_size = 4;
2437 buf_size = (data_p - data_buf) + (ngroups * 4) + 16;
2438 p = buf = (guint8 *)g_malloc0 (buf_size);
2440 /* Emit the header */
2441 encode_int (noffsets, p, &p);
2442 encode_int (group_size, p, &p);
2443 encode_int (ngroups, p, &p);
2444 encode_int (index_entry_size, p, &p);
2446 /* Emit the index */
2447 for (i = 0; i < ngroups; ++i) {
2448 if (index_entry_size == 2)
2449 encode_int16 (index_offsets [i], p, &p);
2451 encode_int (index_offsets [i], p, &p);
2454 memcpy (p, data_buf, data_p - data_buf);
2455 p += data_p - data_buf;
2457 g_assert (p - buf <= buf_size);
2459 emit_aot_data (acfg, table, symbol, buf, p - buf);
2464 return (int)(p - buf);
2468 get_image_index (MonoAotCompile *cfg, MonoImage *image)
2472 index = GPOINTER_TO_UINT (g_hash_table_lookup (cfg->image_hash, image));
2476 index = g_hash_table_size (cfg->image_hash);
2477 g_hash_table_insert (cfg->image_hash, image, GUINT_TO_POINTER (index + 1));
2478 g_ptr_array_add (cfg->image_table, image);
2484 find_typespec_for_class (MonoAotCompile *acfg, MonoClass *klass)
2487 int len = acfg->image->tables [MONO_TABLE_TYPESPEC].rows;
2489 /* FIXME: Search referenced images as well */
2490 if (!acfg->typespec_classes) {
2491 acfg->typespec_classes = (MonoClass **)mono_mempool_alloc0 (acfg->mempool, sizeof (MonoClass*) * len);
2492 for (i = 0; i < len; ++i) {
2494 acfg->typespec_classes [i] = mono_class_get_and_inflate_typespec_checked (acfg->image, MONO_TOKEN_TYPE_SPEC | (i + 1), NULL, &error);
2495 g_assert (mono_error_ok (&error)); /* FIXME error handling */
2498 for (i = 0; i < len; ++i) {
2499 if (acfg->typespec_classes [i] == klass)
2504 return MONO_TOKEN_TYPE_SPEC | (i + 1);
2510 encode_method_ref (MonoAotCompile *acfg, MonoMethod *method, guint8 *buf, guint8 **endbuf);
2513 encode_klass_ref (MonoAotCompile *acfg, MonoClass *klass, guint8 *buf, guint8 **endbuf);
2516 encode_ginst (MonoAotCompile *acfg, MonoGenericInst *inst, guint8 *buf, guint8 **endbuf);
2519 encode_type (MonoAotCompile *acfg, MonoType *t, guint8 *buf, guint8 **endbuf);
2522 encode_klass_ref_inner (MonoAotCompile *acfg, MonoClass *klass, guint8 *buf, guint8 **endbuf)
2527 * The encoding begins with one of the MONO_AOT_TYPEREF values, followed by additional
2531 if (klass->generic_class) {
2533 g_assert (klass->type_token);
2535 /* Find a typespec for a class if possible */
2536 token = find_typespec_for_class (acfg, klass);
2538 encode_value (MONO_AOT_TYPEREF_TYPESPEC_TOKEN, p, &p);
2539 encode_value (token, p, &p);
2541 MonoClass *gclass = klass->generic_class->container_class;
2542 MonoGenericInst *inst = klass->generic_class->context.class_inst;
2543 static int count = 0;
2546 encode_value (MONO_AOT_TYPEREF_GINST, p, &p);
2547 encode_klass_ref (acfg, gclass, p, &p);
2548 encode_ginst (acfg, inst, p, &p);
2552 } else if (klass->type_token) {
2553 int iindex = get_image_index (acfg, klass->image);
2555 g_assert (mono_metadata_token_code (klass->type_token) == MONO_TOKEN_TYPE_DEF);
2557 encode_value (MONO_AOT_TYPEREF_TYPEDEF_INDEX, p, &p);
2558 encode_value (klass->type_token - MONO_TOKEN_TYPE_DEF, p, &p);
2560 encode_value (MONO_AOT_TYPEREF_TYPEDEF_INDEX_IMAGE, p, &p);
2561 encode_value (klass->type_token - MONO_TOKEN_TYPE_DEF, p, &p);
2562 encode_value (get_image_index (acfg, klass->image), p, &p);
2564 } else if ((klass->byval_arg.type == MONO_TYPE_VAR) || (klass->byval_arg.type == MONO_TYPE_MVAR)) {
2565 MonoGenericContainer *container = mono_type_get_generic_param_owner (&klass->byval_arg);
2566 MonoGenericParam *par = klass->byval_arg.data.generic_param;
2568 encode_value (MONO_AOT_TYPEREF_VAR, p, &p);
2570 encode_value (par->gshared_constraint ? 1 : 0, p, &p);
2571 if (par->gshared_constraint) {
2572 MonoGSharedGenericParam *gpar = (MonoGSharedGenericParam*)par;
2573 encode_type (acfg, par->gshared_constraint, p, &p);
2574 encode_klass_ref (acfg, mono_class_from_generic_parameter (gpar->parent, NULL, klass->byval_arg.type == MONO_TYPE_MVAR), p, &p);
2576 encode_value (klass->byval_arg.type, p, &p);
2577 encode_value (mono_type_get_generic_param_num (&klass->byval_arg), p, &p);
2579 encode_value (container->is_anonymous ? 0 : 1, p, &p);
2581 if (!container->is_anonymous) {
2582 encode_value (container->is_method, p, &p);
2583 if (container->is_method)
2584 encode_method_ref (acfg, container->owner.method, p, &p);
2586 encode_klass_ref (acfg, container->owner.klass, p, &p);
2589 } else if (klass->byval_arg.type == MONO_TYPE_PTR) {
2590 encode_value (MONO_AOT_TYPEREF_PTR, p, &p);
2591 encode_type (acfg, &klass->byval_arg, p, &p);
2594 g_assert (klass->rank > 0);
2595 encode_value (MONO_AOT_TYPEREF_ARRAY, p, &p);
2596 encode_value (klass->rank, p, &p);
2597 encode_klass_ref (acfg, klass->element_class, p, &p);
2605 * Encode a reference to KLASS. We use our home-grown encoding instead of the
2606 * standard metadata encoding.
2609 encode_klass_ref (MonoAotCompile *acfg, MonoClass *klass, guint8 *buf, guint8 **endbuf)
2611 gboolean shared = FALSE;
2614 * The encoding of generic instances is large so emit them only once.
2616 if (klass->generic_class) {
2618 g_assert (klass->type_token);
2620 /* Find a typespec for a class if possible */
2621 token = find_typespec_for_class (acfg, klass);
2624 } else if ((klass->byval_arg.type == MONO_TYPE_VAR) || (klass->byval_arg.type == MONO_TYPE_MVAR)) {
2629 guint offset = GPOINTER_TO_UINT (g_hash_table_lookup (acfg->klass_blob_hash, klass));
2633 buf2 = (guint8 *)g_malloc (1024);
2636 encode_klass_ref_inner (acfg, klass, p, &p);
2637 g_assert (p - buf2 < 1024);
2639 offset = add_to_blob (acfg, buf2, p - buf2);
2642 g_hash_table_insert (acfg->klass_blob_hash, klass, GUINT_TO_POINTER (offset + 1));
2648 encode_value (MONO_AOT_TYPEREF_BLOB_INDEX, p, &p);
2649 encode_value (offset, p, &p);
2654 encode_klass_ref_inner (acfg, klass, buf, endbuf);
2658 encode_field_info (MonoAotCompile *cfg, MonoClassField *field, guint8 *buf, guint8 **endbuf)
2660 guint32 token = mono_get_field_token (field);
2663 encode_klass_ref (cfg, field->parent, p, &p);
2664 g_assert (mono_metadata_token_code (token) == MONO_TOKEN_FIELD_DEF);
2665 encode_value (token - MONO_TOKEN_FIELD_DEF, p, &p);
2670 encode_ginst (MonoAotCompile *acfg, MonoGenericInst *inst, guint8 *buf, guint8 **endbuf)
2675 encode_value (inst->type_argc, p, &p);
2676 for (i = 0; i < inst->type_argc; ++i)
2677 encode_klass_ref (acfg, mono_class_from_mono_type (inst->type_argv [i]), p, &p);
2682 encode_generic_context (MonoAotCompile *acfg, MonoGenericContext *context, guint8 *buf, guint8 **endbuf)
2685 MonoGenericInst *inst;
2687 inst = context->class_inst;
2689 g_assert (inst->type_argc);
2690 encode_ginst (acfg, inst, p, &p);
2692 encode_value (0, p, &p);
2694 inst = context->method_inst;
2696 g_assert (inst->type_argc);
2697 encode_ginst (acfg, inst, p, &p);
2699 encode_value (0, p, &p);
2705 encode_type (MonoAotCompile *acfg, MonoType *t, guint8 *buf, guint8 **endbuf)
2709 g_assert (t->num_mods == 0);
2710 /* t->attrs can be ignored */
2711 //g_assert (t->attrs == 0);
2714 *p = MONO_TYPE_PINNED;
2718 *p = MONO_TYPE_BYREF;
2726 case MONO_TYPE_VOID:
2727 case MONO_TYPE_BOOLEAN:
2728 case MONO_TYPE_CHAR:
2741 case MONO_TYPE_STRING:
2742 case MONO_TYPE_OBJECT:
2743 case MONO_TYPE_TYPEDBYREF:
2745 case MONO_TYPE_VALUETYPE:
2746 case MONO_TYPE_CLASS:
2747 encode_klass_ref (acfg, mono_class_from_mono_type (t), p, &p);
2749 case MONO_TYPE_SZARRAY:
2750 encode_klass_ref (acfg, t->data.klass, p, &p);
2753 encode_type (acfg, t->data.type, p, &p);
2755 case MONO_TYPE_GENERICINST: {
2756 MonoClass *gclass = t->data.generic_class->container_class;
2757 MonoGenericInst *inst = t->data.generic_class->context.class_inst;
2759 encode_klass_ref (acfg, gclass, p, &p);
2760 encode_ginst (acfg, inst, p, &p);
2763 case MONO_TYPE_ARRAY: {
2764 MonoArrayType *array = t->data.array;
2767 encode_klass_ref (acfg, array->eklass, p, &p);
2768 encode_value (array->rank, p, &p);
2769 encode_value (array->numsizes, p, &p);
2770 for (i = 0; i < array->numsizes; ++i)
2771 encode_value (array->sizes [i], p, &p);
2772 encode_value (array->numlobounds, p, &p);
2773 for (i = 0; i < array->numlobounds; ++i)
2774 encode_value (array->lobounds [i], p, &p);
2778 case MONO_TYPE_MVAR:
2779 encode_klass_ref (acfg, mono_class_from_mono_type (t), p, &p);
2782 g_assert_not_reached ();
2789 encode_signature (MonoAotCompile *acfg, MonoMethodSignature *sig, guint8 *buf, guint8 **endbuf)
2795 /* Similar to the metadata encoding */
2796 if (sig->generic_param_count)
2800 if (sig->explicit_this)
2802 flags |= (sig->call_convention & 0x0F);
2806 if (sig->generic_param_count)
2807 encode_value (sig->generic_param_count, p, &p);
2808 encode_value (sig->param_count, p, &p);
2810 encode_type (acfg, sig->ret, p, &p);
2811 for (i = 0; i < sig->param_count; ++i) {
2812 if (sig->sentinelpos == i) {
2813 *p = MONO_TYPE_SENTINEL;
2816 encode_type (acfg, sig->params [i], p, &p);
2822 #define MAX_IMAGE_INDEX 250
2825 encode_method_ref (MonoAotCompile *acfg, MonoMethod *method, guint8 *buf, guint8 **endbuf)
2827 guint32 image_index = get_image_index (acfg, method->klass->image);
2828 guint32 token = method->token;
2829 MonoJumpInfoToken *ji;
2833 * The encoding for most methods is as follows:
2834 * - image index encoded as a leb128
2835 * - token index encoded as a leb128
2836 * Values of image index >= MONO_AOT_METHODREF_MIN are used to mark additional
2837 * types of method encodings.
2840 /* Mark methods which can't use aot trampolines because they need the further
2841 * processing in mono_magic_trampoline () which requires a MonoMethod*.
2843 if ((method->is_generic && (method->flags & METHOD_ATTRIBUTE_VIRTUAL)) ||
2844 (method->iflags & METHOD_IMPL_ATTRIBUTE_SYNCHRONIZED))
2845 encode_value ((MONO_AOT_METHODREF_NO_AOT_TRAMPOLINE << 24), p, &p);
2847 if (method->wrapper_type) {
2848 WrapperInfo *info = mono_marshal_get_wrapper_info (method);
2850 encode_value ((MONO_AOT_METHODREF_WRAPPER << 24), p, &p);
2852 encode_value (method->wrapper_type, p, &p);
2854 switch (method->wrapper_type) {
2855 case MONO_WRAPPER_REMOTING_INVOKE:
2856 case MONO_WRAPPER_REMOTING_INVOKE_WITH_CHECK:
2857 case MONO_WRAPPER_XDOMAIN_INVOKE: {
2860 m = mono_marshal_method_from_wrapper (method);
2862 encode_method_ref (acfg, m, p, &p);
2865 case MONO_WRAPPER_PROXY_ISINST:
2866 case MONO_WRAPPER_LDFLD:
2867 case MONO_WRAPPER_LDFLDA:
2868 case MONO_WRAPPER_STFLD:
2869 case MONO_WRAPPER_ISINST: {
2871 encode_klass_ref (acfg, info->d.proxy.klass, p, &p);
2874 case MONO_WRAPPER_LDFLD_REMOTE:
2875 case MONO_WRAPPER_STFLD_REMOTE:
2877 case MONO_WRAPPER_ALLOC: {
2878 /* The GC name is saved once in MonoAotFileInfo */
2879 g_assert (info->d.alloc.alloc_type != -1);
2880 encode_value (info->d.alloc.alloc_type, p, &p);
2883 case MONO_WRAPPER_WRITE_BARRIER: {
2887 case MONO_WRAPPER_STELEMREF: {
2889 encode_value (info->subtype, p, &p);
2890 if (info->subtype == WRAPPER_SUBTYPE_VIRTUAL_STELEMREF)
2891 encode_value (info->d.virtual_stelemref.kind, p, &p);
2894 case MONO_WRAPPER_UNKNOWN: {
2896 encode_value (info->subtype, p, &p);
2897 if (info->subtype == WRAPPER_SUBTYPE_PTR_TO_STRUCTURE ||
2898 info->subtype == WRAPPER_SUBTYPE_STRUCTURE_TO_PTR)
2899 encode_klass_ref (acfg, method->klass, p, &p);
2900 else if (info->subtype == WRAPPER_SUBTYPE_SYNCHRONIZED_INNER)
2901 encode_method_ref (acfg, info->d.synchronized_inner.method, p, &p);
2902 else if (info->subtype == WRAPPER_SUBTYPE_ARRAY_ACCESSOR)
2903 encode_method_ref (acfg, info->d.array_accessor.method, p, &p);
2904 else if (info->subtype == WRAPPER_SUBTYPE_GSHAREDVT_IN_SIG)
2905 encode_signature (acfg, info->d.gsharedvt.sig, p, &p);
2906 else if (info->subtype == WRAPPER_SUBTYPE_GSHAREDVT_OUT_SIG)
2907 encode_signature (acfg, info->d.gsharedvt.sig, p, &p);
2910 case MONO_WRAPPER_MANAGED_TO_NATIVE: {
2912 encode_value (info->subtype, p, &p);
2913 if (info->subtype == WRAPPER_SUBTYPE_ICALL_WRAPPER) {
2914 strcpy ((char*)p, method->name);
2915 p += strlen (method->name) + 1;
2916 } else if (info->subtype == WRAPPER_SUBTYPE_NATIVE_FUNC_AOT) {
2917 encode_method_ref (acfg, info->d.managed_to_native.method, p, &p);
2919 g_assert (info->subtype == WRAPPER_SUBTYPE_NONE || info->subtype == WRAPPER_SUBTYPE_PINVOKE);
2920 encode_method_ref (acfg, info->d.managed_to_native.method, p, &p);
2924 case MONO_WRAPPER_SYNCHRONIZED: {
2927 m = mono_marshal_method_from_wrapper (method);
2929 g_assert (m != method);
2930 encode_method_ref (acfg, m, p, &p);
2933 case MONO_WRAPPER_MANAGED_TO_MANAGED: {
2935 encode_value (info->subtype, p, &p);
2937 if (info->subtype == WRAPPER_SUBTYPE_ELEMENT_ADDR) {
2938 encode_value (info->d.element_addr.rank, p, &p);
2939 encode_value (info->d.element_addr.elem_size, p, &p);
2940 } else if (info->subtype == WRAPPER_SUBTYPE_STRING_CTOR) {
2941 encode_method_ref (acfg, info->d.string_ctor.method, p, &p);
2943 g_assert_not_reached ();
2947 case MONO_WRAPPER_CASTCLASS: {
2949 encode_value (info->subtype, p, &p);
2952 case MONO_WRAPPER_RUNTIME_INVOKE: {
2954 encode_value (info->subtype, p, &p);
2955 if (info->subtype == WRAPPER_SUBTYPE_RUNTIME_INVOKE_DIRECT || info->subtype == WRAPPER_SUBTYPE_RUNTIME_INVOKE_VIRTUAL)
2956 encode_method_ref (acfg, info->d.runtime_invoke.method, p, &p);
2957 else if (info->subtype == WRAPPER_SUBTYPE_RUNTIME_INVOKE_NORMAL)
2958 encode_signature (acfg, info->d.runtime_invoke.sig, p, &p);
2961 case MONO_WRAPPER_DELEGATE_INVOKE:
2962 case MONO_WRAPPER_DELEGATE_BEGIN_INVOKE:
2963 case MONO_WRAPPER_DELEGATE_END_INVOKE: {
2964 if (method->is_inflated) {
2965 /* These wrappers are identified by their class */
2966 encode_value (1, p, &p);
2967 encode_klass_ref (acfg, method->klass, p, &p);
2969 MonoMethodSignature *sig = mono_method_signature (method);
2970 WrapperInfo *info = mono_marshal_get_wrapper_info (method);
2972 encode_value (0, p, &p);
2973 if (method->wrapper_type == MONO_WRAPPER_DELEGATE_INVOKE)
2974 encode_value (info ? info->subtype : 0, p, &p);
2975 encode_signature (acfg, sig, p, &p);
2979 case MONO_WRAPPER_NATIVE_TO_MANAGED: {
2981 encode_method_ref (acfg, info->d.native_to_managed.method, p, &p);
2982 encode_klass_ref (acfg, info->d.native_to_managed.klass, p, &p);
2986 g_assert_not_reached ();
2988 } else if (mono_method_signature (method)->is_inflated) {
2990 * This is a generic method, find the original token which referenced it and
2992 * Obtain the token from information recorded by the JIT.
2994 ji = (MonoJumpInfoToken *)g_hash_table_lookup (acfg->token_info_hash, method);
2996 image_index = get_image_index (acfg, ji->image);
2997 g_assert (image_index < MAX_IMAGE_INDEX);
3000 encode_value ((MONO_AOT_METHODREF_METHODSPEC << 24), p, &p);
3001 encode_value (image_index, p, &p);
3002 encode_value (token, p, &p);
3004 MonoMethod *declaring;
3005 MonoGenericContext *context = mono_method_get_context (method);
3007 g_assert (method->is_inflated);
3008 declaring = ((MonoMethodInflated*)method)->declaring;
3011 * This might be a non-generic method of a generic instance, which
3012 * doesn't have a token since the reference is generated by the JIT
3013 * like Nullable:Box/Unbox, or by generic sharing.
3015 encode_value ((MONO_AOT_METHODREF_GINST << 24), p, &p);
3016 /* Encode the klass */
3017 encode_klass_ref (acfg, method->klass, p, &p);
3018 /* Encode the method */
3019 image_index = get_image_index (acfg, method->klass->image);
3020 g_assert (image_index < MAX_IMAGE_INDEX);
3021 g_assert (declaring->token);
3022 token = declaring->token;
3023 g_assert (mono_metadata_token_table (token) == MONO_TABLE_METHOD);
3024 encode_value (image_index, p, &p);
3025 encode_value (token, p, &p);
3026 encode_generic_context (acfg, context, p, &p);
3028 } else if (token == 0) {
3029 /* This might be a method of a constructed type like int[,].Set */
3030 /* Obtain the token from information recorded by the JIT */
3031 ji = (MonoJumpInfoToken *)g_hash_table_lookup (acfg->token_info_hash, method);
3033 image_index = get_image_index (acfg, ji->image);
3034 g_assert (image_index < MAX_IMAGE_INDEX);
3037 encode_value ((MONO_AOT_METHODREF_METHODSPEC << 24), p, &p);
3038 encode_value (image_index, p, &p);
3039 encode_value (token, p, &p);
3042 g_assert (method->klass->rank);
3044 /* Encode directly */
3045 encode_value ((MONO_AOT_METHODREF_ARRAY << 24), p, &p);
3046 encode_klass_ref (acfg, method->klass, p, &p);
3047 if (!strcmp (method->name, ".ctor") && mono_method_signature (method)->param_count == method->klass->rank)
3048 encode_value (0, p, &p);
3049 else if (!strcmp (method->name, ".ctor") && mono_method_signature (method)->param_count == method->klass->rank * 2)
3050 encode_value (1, p, &p);
3051 else if (!strcmp (method->name, "Get"))
3052 encode_value (2, p, &p);
3053 else if (!strcmp (method->name, "Address"))
3054 encode_value (3, p, &p);
3055 else if (!strcmp (method->name, "Set"))
3056 encode_value (4, p, &p);
3058 g_assert_not_reached ();
3061 g_assert (mono_metadata_token_table (token) == MONO_TABLE_METHOD);
3063 if (image_index >= MONO_AOT_METHODREF_MIN) {
3064 encode_value ((MONO_AOT_METHODREF_LARGE_IMAGE_INDEX << 24), p, &p);
3065 encode_value (image_index, p, &p);
3066 encode_value (mono_metadata_token_index (token), p, &p);
3068 encode_value ((image_index << 24) | mono_metadata_token_index (token), p, &p);
3075 compare_patches (gconstpointer a, gconstpointer b)
3079 i = (*(MonoJumpInfo**)a)->ip.i;
3080 j = (*(MonoJumpInfo**)b)->ip.i;
3091 static G_GNUC_UNUSED char*
3092 patch_to_string (MonoJumpInfo *patch_info)
3096 str = g_string_new ("");
3098 g_string_append_printf (str, "%s(", get_patch_name (patch_info->type));
3100 switch (patch_info->type) {
3101 case MONO_PATCH_INFO_VTABLE:
3102 mono_type_get_desc (str, &patch_info->data.klass->byval_arg, TRUE);
3107 g_string_append_printf (str, ")");
3108 return g_string_free (str, FALSE);
3114 * Return whenever PATCH_INFO refers to a direct call, and thus requires a
3117 static inline gboolean
3118 is_plt_patch (MonoJumpInfo *patch_info)
3120 switch (patch_info->type) {
3121 case MONO_PATCH_INFO_METHOD:
3122 case MONO_PATCH_INFO_INTERNAL_METHOD:
3123 case MONO_PATCH_INFO_JIT_ICALL_ADDR:
3124 case MONO_PATCH_INFO_ICALL_ADDR:
3125 case MONO_PATCH_INFO_RGCTX_FETCH:
3135 * Return the symbol identifying the plt entry PLT_OFFSET.
3138 get_plt_symbol (MonoAotCompile *acfg, int plt_offset, MonoJumpInfo *patch_info)
3142 * The Apple linker reorganizes object files, so it doesn't like branches to local
3143 * labels, since those have no relocations.
3145 return g_strdup_printf ("%sp_%d", acfg->llvm_label_prefix, plt_offset);
3147 return g_strdup_printf ("%sp_%d", acfg->temp_prefix, plt_offset);
3154 * Return a PLT entry which belongs to the method identified by PATCH_INFO.
3156 static MonoPltEntry*
3157 get_plt_entry (MonoAotCompile *acfg, MonoJumpInfo *patch_info)
3160 gboolean synchronized = FALSE;
3161 static int synchronized_symbol_idx;
3163 if (!is_plt_patch (patch_info))
3166 if (!acfg->patch_to_plt_entry [patch_info->type])
3167 acfg->patch_to_plt_entry [patch_info->type] = g_hash_table_new (mono_patch_info_hash, mono_patch_info_equal);
3168 res = (MonoPltEntry *)g_hash_table_lookup (acfg->patch_to_plt_entry [patch_info->type], patch_info);
3170 if (!acfg->llvm && patch_info->type == MONO_PATCH_INFO_METHOD && (patch_info->data.method->iflags & METHOD_IMPL_ATTRIBUTE_SYNCHRONIZED)) {
3172 * Allocate a separate PLT slot for each such patch, since some plt
3173 * entries will refer to the method itself, and some will refer to the
3177 synchronized = TRUE;
3181 MonoJumpInfo *new_ji;
3183 new_ji = mono_patch_info_dup_mp (acfg->mempool, patch_info);
3185 res = (MonoPltEntry *)mono_mempool_alloc0 (acfg->mempool, sizeof (MonoPltEntry));
3186 res->plt_offset = acfg->plt_offset;
3188 res->symbol = get_plt_symbol (acfg, res->plt_offset, patch_info);
3189 if (acfg->aot_opts.write_symbols)
3190 res->debug_sym = get_plt_entry_debug_sym (acfg, res->ji, acfg->plt_entry_debug_sym_cache);
3192 /* Avoid duplicate symbols because we don't cache */
3193 res->symbol = g_strdup_printf ("%s_%d", res->symbol, synchronized_symbol_idx);
3195 res->debug_sym = g_strdup_printf ("%s_%d", res->debug_sym, synchronized_symbol_idx);
3196 synchronized_symbol_idx ++;
3199 res->llvm_symbol = g_strdup_printf ("%s_%s_llvm", res->symbol, res->debug_sym);
3201 res->llvm_symbol = g_strdup_printf ("%s_llvm", res->symbol);
3203 g_hash_table_insert (acfg->patch_to_plt_entry [new_ji->type], new_ji, res);
3205 g_hash_table_insert (acfg->plt_offset_to_entry, GUINT_TO_POINTER (res->plt_offset), res);
3207 //g_assert (mono_patch_info_equal (patch_info, new_ji));
3208 //mono_print_ji (patch_info); printf ("\n");
3209 //g_hash_table_print_stats (acfg->patch_to_plt_entry);
3211 acfg->plt_offset ++;
3220 * Returns the offset of the GOT slot where the runtime object resulting from resolving
3221 * JI could be found if it exists, otherwise allocates a new one.
3224 get_got_offset (MonoAotCompile *acfg, gboolean llvm, MonoJumpInfo *ji)
3227 GotInfo *info = llvm ? &acfg->llvm_got_info : &acfg->got_info;
3229 got_offset = GPOINTER_TO_UINT (g_hash_table_lookup (info->patch_to_got_offset_by_type [ji->type], ji));
3231 return got_offset - 1;
3234 got_offset = acfg->llvm_got_offset;
3235 acfg->llvm_got_offset ++;
3237 got_offset = acfg->got_offset;
3238 acfg->got_offset ++;
3241 acfg->stats.got_slots ++;
3242 acfg->stats.got_slot_types [ji->type] ++;
3244 g_hash_table_insert (info->patch_to_got_offset, ji, GUINT_TO_POINTER (got_offset + 1));
3245 g_hash_table_insert (info->patch_to_got_offset_by_type [ji->type], ji, GUINT_TO_POINTER (got_offset + 1));
3246 g_ptr_array_add (info->got_patches, ji);
3251 /* Add a method to the list of methods which need to be emitted */
3253 add_method_with_index (MonoAotCompile *acfg, MonoMethod *method, int index, gboolean extra)
3256 if (!g_hash_table_lookup (acfg->method_indexes, method)) {
3257 g_ptr_array_add (acfg->methods, method);
3258 g_hash_table_insert (acfg->method_indexes, method, GUINT_TO_POINTER (index + 1));
3259 acfg->nmethods = acfg->methods->len + 1;
3262 if (method->wrapper_type || extra)
3263 g_ptr_array_add (acfg->extra_methods, method);
3267 prefer_gsharedvt_method (MonoAotCompile *acfg, MonoMethod *method)
3269 /* One instantiation with valuetypes is generated for each async method */
3270 if (method->klass->image == mono_defaults.corlib && (!strcmp (method->klass->name, "AsyncMethodBuilderCore") || !strcmp (method->klass->name, "AsyncVoidMethodBuilder")))
3277 get_method_index (MonoAotCompile *acfg, MonoMethod *method)
3279 int index = GPOINTER_TO_UINT (g_hash_table_lookup (acfg->method_indexes, method));
3287 add_method_full (MonoAotCompile *acfg, MonoMethod *method, gboolean extra, int depth)
3291 index = GPOINTER_TO_UINT (g_hash_table_lookup (acfg->method_indexes, method));
3295 index = acfg->method_index;
3296 add_method_with_index (acfg, method, index, extra);
3298 g_ptr_array_add (acfg->method_order, GUINT_TO_POINTER (index));
3300 g_hash_table_insert (acfg->method_depth, method, GUINT_TO_POINTER (depth));
3302 acfg->method_index ++;
3308 add_method (MonoAotCompile *acfg, MonoMethod *method)
3310 return add_method_full (acfg, method, FALSE, 0);
3314 add_extra_method_with_depth (MonoAotCompile *acfg, MonoMethod *method, int depth)
3316 if (mono_method_is_generic_sharable_full (method, TRUE, TRUE, FALSE))
3317 method = mini_get_shared_method (method);
3318 else if ((acfg->opts & MONO_OPT_GSHAREDVT) && prefer_gsharedvt_method (acfg, method) && mono_method_is_generic_sharable_full (method, FALSE, FALSE, TRUE))
3319 /* Use the gsharedvt version */
3320 method = mini_get_shared_method_full (method, TRUE, TRUE);
3322 if (acfg->aot_opts.log_generics)
3323 aot_printf (acfg, "%*sAdding method %s.\n", depth, "", mono_method_get_full_name (method));
3325 add_method_full (acfg, method, TRUE, depth);
3329 add_extra_method (MonoAotCompile *acfg, MonoMethod *method)
3331 add_extra_method_with_depth (acfg, method, 0);
3335 add_jit_icall_wrapper (gpointer key, gpointer value, gpointer user_data)
3337 MonoAotCompile *acfg = (MonoAotCompile *)user_data;
3338 MonoJitICallInfo *callinfo = (MonoJitICallInfo *)value;
3339 MonoMethod *wrapper;
3345 name = g_strdup_printf ("__icall_wrapper_%s", callinfo->name);
3346 wrapper = mono_marshal_get_icall_wrapper (callinfo->sig, name, callinfo->func, TRUE);
3349 add_method (acfg, wrapper);
3353 get_runtime_invoke_sig (MonoMethodSignature *sig)
3355 MonoMethodBuilder *mb;
3358 mb = mono_mb_new (mono_defaults.object_class, "FOO", MONO_WRAPPER_NONE);
3359 m = mono_mb_create_method (mb, sig, 16);
3360 return mono_marshal_get_runtime_invoke (m, FALSE);
3364 get_runtime_invoke (MonoAotCompile *acfg, MonoMethod *method, gboolean virtual_)
3366 return mono_marshal_get_runtime_invoke (method, virtual_);
3370 can_marshal_struct (MonoClass *klass)
3372 MonoClassField *field;
3373 gboolean can_marshal = TRUE;
3374 gpointer iter = NULL;
3375 MonoMarshalType *info;
3378 if ((klass->flags & TYPE_ATTRIBUTE_LAYOUT_MASK) == TYPE_ATTRIBUTE_AUTO_LAYOUT)
3381 info = mono_marshal_load_type_info (klass);
3383 /* Only allow a few field types to avoid asserts in the marshalling code */
3384 while ((field = mono_class_get_fields (klass, &iter))) {
3385 if ((field->type->attrs & FIELD_ATTRIBUTE_STATIC))
3388 switch (field->type->type) {
3393 case MONO_TYPE_BOOLEAN:
3396 case MONO_TYPE_CHAR:
3404 case MONO_TYPE_STRING:
3406 case MONO_TYPE_VALUETYPE:
3407 if (!mono_class_from_mono_type (field->type)->enumtype && !can_marshal_struct (mono_class_from_mono_type (field->type)))
3408 can_marshal = FALSE;
3410 case MONO_TYPE_SZARRAY: {
3411 gboolean has_mspec = FALSE;
3414 for (i = 0; i < info->num_fields; ++i) {
3415 if (info->fields [i].field == field && info->fields [i].mspec)
3420 can_marshal = FALSE;
3424 can_marshal = FALSE;
3430 /* Its hard to compute whenever these can be marshalled or not */
3431 if (!strcmp (klass->name_space, "System.Net.NetworkInformation.MacOsStructs") && strcmp (klass->name, "sockaddr_dl"))
3438 create_gsharedvt_inst (MonoAotCompile *acfg, MonoMethod *method, MonoGenericContext *ctx)
3440 /* Create a vtype instantiation */
3441 MonoGenericContext shared_context;
3443 MonoGenericInst *inst;
3444 MonoGenericContainer *container;
3445 MonoClass **constraints;
3448 memset (ctx, 0, sizeof (MonoGenericContext));
3450 if (method->klass->generic_container) {
3451 shared_context = method->klass->generic_container->context;
3452 inst = shared_context.class_inst;
3454 args = g_new0 (MonoType*, inst->type_argc);
3455 for (i = 0; i < inst->type_argc; ++i) {
3456 args [i] = &mono_defaults.int_class->byval_arg;
3458 ctx->class_inst = mono_metadata_get_generic_inst (inst->type_argc, args);
3460 if (method->is_generic) {
3461 container = mono_method_get_generic_container (method);
3462 shared_context = container->context;
3463 inst = shared_context.method_inst;
3465 args = g_new0 (MonoType*, inst->type_argc);
3466 for (i = 0; i < container->type_argc; ++i) {
3467 MonoGenericParamInfo *info = &container->type_params [i].info;
3468 gboolean ref_only = FALSE;
3470 if (info && info->constraints) {
3471 constraints = info->constraints;
3473 while (*constraints) {
3474 MonoClass *cklass = *constraints;
3475 if (!(cklass == mono_defaults.object_class || (cklass->image == mono_defaults.corlib && !strcmp (cklass->name, "ValueType"))))
3476 /* Inflaring the method with our vtype would not be valid */
3483 args [i] = &mono_defaults.object_class->byval_arg;
3485 args [i] = &mono_defaults.int_class->byval_arg;
3487 ctx->method_inst = mono_metadata_get_generic_inst (inst->type_argc, args);
3492 add_wrappers (MonoAotCompile *acfg)
3494 MonoMethod *method, *m;
3496 MonoMethodSignature *sig, *csig;
3500 * FIXME: Instead of AOTing all the wrappers, it might be better to redesign them
3501 * so there is only one wrapper of a given type, or inlining their contents into their
3504 for (i = 0; i < acfg->image->tables [MONO_TABLE_METHOD].rows; ++i) {
3507 guint32 token = MONO_TOKEN_METHOD_DEF | (i + 1);
3508 gboolean skip = FALSE;
3510 method = mono_get_method_checked (acfg->image, token, NULL, NULL, &error);
3511 report_loader_error (acfg, &error, "Failed to load method token 0x%x due to %s\n", i, mono_error_get_message (&error));
3513 if ((method->flags & METHOD_ATTRIBUTE_PINVOKE_IMPL) ||
3514 (method->iflags & METHOD_IMPL_ATTRIBUTE_RUNTIME) ||
3515 (method->flags & METHOD_ATTRIBUTE_ABSTRACT))
3518 /* Skip methods which can not be handled by get_runtime_invoke () */
3519 sig = mono_method_signature (method);
3522 if ((sig->ret->type == MONO_TYPE_PTR) ||
3523 (sig->ret->type == MONO_TYPE_TYPEDBYREF))
3525 if (mono_class_is_open_constructed_type (sig->ret))
3528 for (j = 0; j < sig->param_count; j++) {
3529 if (sig->params [j]->type == MONO_TYPE_TYPEDBYREF)
3531 if (mono_class_is_open_constructed_type (sig->params [j]))
3535 #ifdef MONO_ARCH_DYN_CALL_SUPPORTED
3536 if (!mono_class_is_contextbound (method->klass)) {
3537 MonoDynCallInfo *info = mono_arch_dyn_call_prepare (sig);
3538 gboolean has_nullable = FALSE;
3540 for (j = 0; j < sig->param_count; j++) {
3541 if (sig->params [j]->type == MONO_TYPE_GENERICINST && mono_class_is_nullable (mono_class_from_mono_type (sig->params [j])))
3542 has_nullable = TRUE;
3545 if (info && !has_nullable && !acfg->aot_opts.llvm_only) {
3546 /* Supported by the dynamic runtime-invoke wrapper */
3550 mono_arch_dyn_call_free (info);
3554 if (acfg->aot_opts.llvm_only)
3555 /* Supported by the gsharedvt based runtime-invoke wrapper */
3559 //printf ("%s\n", mono_method_full_name (method, TRUE));
3560 add_method (acfg, get_runtime_invoke (acfg, method, FALSE));
3564 if (strcmp (acfg->image->assembly->aname.name, "mscorlib") == 0) {
3567 /* Runtime invoke wrappers */
3569 /* void runtime-invoke () [.cctor] */
3570 csig = mono_metadata_signature_alloc (mono_defaults.corlib, 0);
3571 csig->ret = &mono_defaults.void_class->byval_arg;
3572 add_method (acfg, get_runtime_invoke_sig (csig));
3574 /* void runtime-invoke () [Finalize] */
3575 csig = mono_metadata_signature_alloc (mono_defaults.corlib, 0);
3577 csig->ret = &mono_defaults.void_class->byval_arg;
3578 add_method (acfg, get_runtime_invoke_sig (csig));
3580 /* void runtime-invoke (string) [exception ctor] */
3581 csig = mono_metadata_signature_alloc (mono_defaults.corlib, 1);
3583 csig->ret = &mono_defaults.void_class->byval_arg;
3584 csig->params [0] = &mono_defaults.string_class->byval_arg;
3585 add_method (acfg, get_runtime_invoke_sig (csig));
3587 /* void runtime-invoke (string, string) [exception ctor] */
3588 csig = mono_metadata_signature_alloc (mono_defaults.corlib, 2);
3590 csig->ret = &mono_defaults.void_class->byval_arg;
3591 csig->params [0] = &mono_defaults.string_class->byval_arg;
3592 csig->params [1] = &mono_defaults.string_class->byval_arg;
3593 add_method (acfg, get_runtime_invoke_sig (csig));
3595 /* string runtime-invoke () [Exception.ToString ()] */
3596 csig = mono_metadata_signature_alloc (mono_defaults.corlib, 0);
3598 csig->ret = &mono_defaults.string_class->byval_arg;
3599 add_method (acfg, get_runtime_invoke_sig (csig));
3601 /* void runtime-invoke (string, Exception) [exception ctor] */
3602 csig = mono_metadata_signature_alloc (mono_defaults.corlib, 2);
3604 csig->ret = &mono_defaults.void_class->byval_arg;
3605 csig->params [0] = &mono_defaults.string_class->byval_arg;
3606 csig->params [1] = &mono_defaults.exception_class->byval_arg;
3607 add_method (acfg, get_runtime_invoke_sig (csig));
3609 /* Assembly runtime-invoke (string, bool) [DoAssemblyResolve] */
3610 csig = mono_metadata_signature_alloc (mono_defaults.corlib, 2);
3612 csig->ret = &(mono_class_from_name (
3613 mono_defaults.corlib, "System.Reflection", "Assembly"))->byval_arg;
3614 csig->params [0] = &mono_defaults.string_class->byval_arg;
3615 csig->params [1] = &mono_defaults.boolean_class->byval_arg;
3616 add_method (acfg, get_runtime_invoke_sig (csig));
3618 /* runtime-invoke used by finalizers */
3619 add_method (acfg, get_runtime_invoke (acfg, mono_class_get_method_from_name_flags (mono_defaults.object_class, "Finalize", 0, 0), TRUE));
3621 /* This is used by mono_runtime_capture_context () */
3622 method = mono_get_context_capture_method ();
3624 add_method (acfg, get_runtime_invoke (acfg, method, FALSE));
3626 #ifdef MONO_ARCH_DYN_CALL_SUPPORTED
3627 if (!acfg->aot_opts.llvm_only)
3628 add_method (acfg, mono_marshal_get_runtime_invoke_dynamic ());
3631 /* These are used by mono_jit_runtime_invoke () to calls gsharedvt out wrappers */
3632 if (acfg->aot_opts.llvm_only) {
3635 /* Create simplified signatures which match the signature used by the gsharedvt out wrappers */
3636 for (variants = 0; variants < 4; ++variants) {
3637 for (i = 0; i < 16; ++i) {
3638 sig = mini_get_gsharedvt_out_sig_wrapper_signature ((variants & 1) > 0, (variants & 2) > 0, i);
3639 add_extra_method (acfg, mono_marshal_get_runtime_invoke_for_sig (sig));
3647 add_method (acfg, mono_marshal_get_stelemref ());
3649 if (MONO_ARCH_HAVE_TLS_GET) {
3650 /* Managed Allocators */
3651 nallocators = mono_gc_get_managed_allocator_types ();
3652 for (i = 0; i < nallocators; ++i) {
3653 m = mono_gc_get_managed_allocator_by_type (i, TRUE);
3655 add_method (acfg, m);
3657 for (i = 0; i < nallocators; ++i) {
3658 m = mono_gc_get_managed_allocator_by_type (i, FALSE);
3660 add_method (acfg, m);
3664 /* write barriers */
3665 if (mono_gc_is_moving ()) {
3666 add_method (acfg, mono_gc_get_specific_write_barrier (FALSE));
3667 add_method (acfg, mono_gc_get_specific_write_barrier (TRUE));
3670 /* Stelemref wrappers */
3672 MonoMethod **wrappers;
3675 wrappers = mono_marshal_get_virtual_stelemref_wrappers (&nwrappers);
3676 for (i = 0; i < nwrappers; ++i)
3677 add_method (acfg, wrappers [i]);
3681 /* castclass_with_check wrapper */
3682 add_method (acfg, mono_marshal_get_castclass_with_cache ());
3683 /* isinst_with_check wrapper */
3684 add_method (acfg, mono_marshal_get_isinst_with_cache ());
3686 /* JIT icall wrappers */
3687 /* FIXME: locking - this is "safe" as full-AOT threads don't mutate the icall hash*/
3688 g_hash_table_foreach (mono_get_jit_icall_info (), add_jit_icall_wrapper, acfg);
3692 * remoting-invoke-with-check wrappers are very frequent, so avoid emitting them,
3693 * we use the original method instead at runtime.
3694 * Since full-aot doesn't support remoting, this is not a problem.
3697 /* remoting-invoke wrappers */
3698 for (i = 0; i < acfg->image->tables [MONO_TABLE_METHOD].rows; ++i) {
3700 MonoMethodSignature *sig;
3702 token = MONO_TOKEN_METHOD_DEF | (i + 1);
3703 method = mono_get_method_checked (acfg->image, token, NULL, NULL, &error);
3704 g_assert (mono_error_ok (&error)); /* FIXME don't swallow the error */
3706 sig = mono_method_signature (method);
3708 if (sig->hasthis && (method->klass->marshalbyref || method->klass == mono_defaults.object_class)) {
3709 m = mono_marshal_get_remoting_invoke_with_check (method);
3711 add_method (acfg, m);
3716 /* delegate-invoke wrappers */
3717 for (i = 0; i < acfg->image->tables [MONO_TABLE_TYPEDEF].rows; ++i) {
3720 MonoCustomAttrInfo *cattr;
3722 token = MONO_TOKEN_TYPE_DEF | (i + 1);
3723 klass = mono_class_get_checked (acfg->image, token, &error);
3726 mono_error_cleanup (&error);
3730 if (!klass->delegate || klass == mono_defaults.delegate_class || klass == mono_defaults.multicastdelegate_class)
3733 if (!klass->generic_container) {
3734 method = mono_get_delegate_invoke (klass);
3736 m = mono_marshal_get_delegate_invoke (method, NULL);
3738 add_method (acfg, m);
3740 method = mono_class_get_method_from_name_flags (klass, "BeginInvoke", -1, 0);
3742 add_method (acfg, mono_marshal_get_delegate_begin_invoke (method));
3744 method = mono_class_get_method_from_name_flags (klass, "EndInvoke", -1, 0);
3746 add_method (acfg, mono_marshal_get_delegate_end_invoke (method));
3748 cattr = mono_custom_attrs_from_class (klass);
3753 for (j = 0; j < cattr->num_attrs; ++j)
3754 if (cattr->attrs [j].ctor && (!strcmp (cattr->attrs [j].ctor->klass->name, "MonoNativeFunctionWrapperAttribute") || !strcmp (cattr->attrs [j].ctor->klass->name, "UnmanagedFunctionPointerAttribute")))
3756 if (j < cattr->num_attrs) {
3758 MonoMethod *wrapper;
3759 MonoMethod *del_invoke;
3761 /* Add wrappers needed by mono_ftnptr_to_delegate () */
3762 invoke = mono_get_delegate_invoke (klass);
3763 wrapper = mono_marshal_get_native_func_wrapper_aot (klass);
3764 del_invoke = mono_marshal_get_delegate_invoke_internal (invoke, FALSE, TRUE, wrapper);
3765 add_method (acfg, wrapper);
3766 add_method (acfg, del_invoke);
3769 } else if ((acfg->opts & MONO_OPT_GSHAREDVT) && klass->generic_container) {
3771 MonoGenericContext ctx;
3772 MonoMethod *inst, *gshared;
3775 * Emit gsharedvt versions of the generic delegate-invoke wrappers
3778 method = mono_get_delegate_invoke (klass);
3779 create_gsharedvt_inst (acfg, method, &ctx);
3781 inst = mono_class_inflate_generic_method_checked (method, &ctx, &error);
3782 g_assert (mono_error_ok (&error)); /* FIXME don't swallow the error */
3784 m = mono_marshal_get_delegate_invoke (inst, NULL);
3785 g_assert (m->is_inflated);
3787 gshared = mini_get_shared_method_full (m, FALSE, TRUE);
3788 add_extra_method (acfg, gshared);
3791 method = mono_get_delegate_begin_invoke (klass);
3792 create_gsharedvt_inst (acfg, method, &ctx);
3794 inst = mono_class_inflate_generic_method_checked (method, &ctx, &error);
3795 g_assert (mono_error_ok (&error)); /* FIXME don't swallow the error */
3797 m = mono_marshal_get_delegate_begin_invoke (inst);
3798 g_assert (m->is_inflated);
3800 gshared = mini_get_shared_method_full (m, FALSE, TRUE);
3801 add_extra_method (acfg, gshared);
3804 method = mono_get_delegate_end_invoke (klass);
3805 create_gsharedvt_inst (acfg, method, &ctx);
3807 inst = mono_class_inflate_generic_method_checked (method, &ctx, &error);
3808 g_assert (mono_error_ok (&error)); /* FIXME don't swallow the error */
3810 m = mono_marshal_get_delegate_end_invoke (inst);
3811 g_assert (m->is_inflated);
3813 gshared = mini_get_shared_method_full (m, FALSE, TRUE);
3814 add_extra_method (acfg, gshared);
3819 /* array access wrappers */
3820 for (i = 0; i < acfg->image->tables [MONO_TABLE_TYPESPEC].rows; ++i) {
3824 token = MONO_TOKEN_TYPE_SPEC | (i + 1);
3825 klass = mono_class_get_checked (acfg->image, token, &error);
3828 mono_error_cleanup (&error);
3832 if (!acfg->aot_opts.llvm_only && klass->rank && MONO_TYPE_IS_PRIMITIVE (&klass->element_class->byval_arg)) {
3833 MonoMethod *m, *wrapper;
3835 /* Add runtime-invoke wrappers too */
3837 m = mono_class_get_method_from_name (klass, "Get", -1);
3839 wrapper = mono_marshal_get_array_accessor_wrapper (m);
3840 add_extra_method (acfg, wrapper);
3841 add_extra_method (acfg, get_runtime_invoke (acfg, wrapper, FALSE));
3843 m = mono_class_get_method_from_name (klass, "Set", -1);
3845 wrapper = mono_marshal_get_array_accessor_wrapper (m);
3846 add_extra_method (acfg, wrapper);
3847 add_extra_method (acfg, get_runtime_invoke (acfg, wrapper, FALSE));
3851 /* Synchronized wrappers */
3852 for (i = 0; i < acfg->image->tables [MONO_TABLE_METHOD].rows; ++i) {
3854 token = MONO_TOKEN_METHOD_DEF | (i + 1);
3855 method = mono_get_method_checked (acfg->image, token, NULL, NULL, &error);
3856 report_loader_error (acfg, &error, "Failed to load method token 0x%x due to %s\n", i, mono_error_get_message (&error));
3858 if (method->iflags & METHOD_IMPL_ATTRIBUTE_SYNCHRONIZED) {
3859 if (method->is_generic) {
3861 } else if ((acfg->opts & MONO_OPT_GSHAREDVT) && method->klass->generic_container) {
3863 MonoGenericContext ctx;
3864 MonoMethod *inst, *gshared, *m;
3867 * Create a generic wrapper for a generic instance, and AOT that.
3869 create_gsharedvt_inst (acfg, method, &ctx);
3870 inst = mono_class_inflate_generic_method_checked (method, &ctx, &error);
3871 g_assert (mono_error_ok (&error)); /* FIXME don't swallow the error */
3872 m = mono_marshal_get_synchronized_wrapper (inst);
3873 g_assert (m->is_inflated);
3874 gshared = mini_get_shared_method_full (m, FALSE, TRUE);
3875 add_method (acfg, gshared);
3877 add_method (acfg, mono_marshal_get_synchronized_wrapper (method));
3882 /* pinvoke wrappers */
3883 for (i = 0; i < acfg->image->tables [MONO_TABLE_METHOD].rows; ++i) {
3886 guint32 token = MONO_TOKEN_METHOD_DEF | (i + 1);
3888 method = mono_get_method_checked (acfg->image, token, NULL, NULL, &error);
3889 report_loader_error (acfg, &error, "Failed to load method token 0x%x due to %s\n", i, mono_error_get_message (&error));
3891 if ((method->flags & METHOD_ATTRIBUTE_PINVOKE_IMPL) ||
3892 (method->iflags & METHOD_IMPL_ATTRIBUTE_INTERNAL_CALL)) {
3893 add_method (acfg, mono_marshal_get_native_wrapper (method, TRUE, TRUE));
3897 /* native-to-managed wrappers */
3898 for (i = 0; i < acfg->image->tables [MONO_TABLE_METHOD].rows; ++i) {
3901 guint32 token = MONO_TOKEN_METHOD_DEF | (i + 1);
3902 MonoCustomAttrInfo *cattr;
3905 method = mono_get_method_checked (acfg->image, token, NULL, NULL, &error);
3906 report_loader_error (acfg, &error, "Failed to load method token 0x%x due to %s\n", i, mono_error_get_message (&error));
3909 * Only generate native-to-managed wrappers for methods which have an
3910 * attribute named MonoPInvokeCallbackAttribute. We search for the attribute by
3911 * name to avoid defining a new assembly to contain it.
3913 cattr = mono_custom_attrs_from_method (method);
3916 for (j = 0; j < cattr->num_attrs; ++j)
3917 if (cattr->attrs [j].ctor && !strcmp (cattr->attrs [j].ctor->klass->name, "MonoPInvokeCallbackAttribute"))
3919 if (j < cattr->num_attrs) {
3920 MonoCustomAttrEntry *e = &cattr->attrs [j];
3921 MonoMethodSignature *sig = mono_method_signature (e->ctor);
3922 const char *p = (const char*)e->data;
3924 int slen, num_named, named_type;
3928 char *export_name = NULL;
3929 MonoMethod *wrapper;
3931 /* this cannot be enforced by the C# compiler so we must give the user some warning before aborting */
3932 if (!(method->flags & METHOD_ATTRIBUTE_STATIC)) {
3933 g_warning ("AOT restriction: Method '%s' must be static since it is decorated with [MonoPInvokeCallback]. See http://ios.xamarin.com/Documentation/Limitations#Reverse_Callbacks",
3934 mono_method_full_name (method, TRUE));
3938 g_assert (sig->param_count == 1);
3939 g_assert (sig->params [0]->type == MONO_TYPE_CLASS && !strcmp (mono_class_from_mono_type (sig->params [0])->name, "Type"));
3942 * Decode the cattr manually since we can't create objects
3943 * during aot compilation.
3949 /* From load_cattr_value () in reflection.c */
3950 slen = mono_metadata_decode_value (p, &p);
3951 n = (char *)g_memdup (p, slen + 1);
3953 t = mono_reflection_type_from_name (n, acfg->image);
3957 klass = mono_class_from_mono_type (t);
3958 g_assert (klass->parent == mono_defaults.multicastdelegate_class);
3962 num_named = read16 (p);
3965 g_assert (num_named < 2);
3966 if (num_named == 1) {
3970 /* parse ExportSymbol attribute */
3972 named_type = *named;
3974 /* data_type = *named; */
3977 name_len = mono_metadata_decode_blob_size (named, &named);
3978 name = (char *)g_malloc (name_len + 1);
3979 memcpy (name, named, name_len);
3980 name [name_len] = 0;
3983 g_assert (named_type == 0x54);
3984 g_assert (!strcmp (name, "ExportSymbol"));
3986 /* load_cattr_value (), string case */
3987 g_assert (*named != (char)0xff);
3988 slen = mono_metadata_decode_value (named, &named);
3989 export_name = (char *)g_malloc (slen + 1);
3990 memcpy (export_name, named, slen);
3991 export_name [slen] = 0;
3995 wrapper = mono_marshal_get_managed_wrapper (method, klass, 0);
3996 add_method (acfg, wrapper);
3998 g_hash_table_insert (acfg->export_names, wrapper, export_name);
4002 if ((method->flags & METHOD_ATTRIBUTE_PINVOKE_IMPL) ||
4003 (method->iflags & METHOD_IMPL_ATTRIBUTE_INTERNAL_CALL)) {
4004 add_method (acfg, mono_marshal_get_native_wrapper (method, TRUE, TRUE));
4008 /* StructureToPtr/PtrToStructure wrappers */
4009 for (i = 0; i < acfg->image->tables [MONO_TABLE_TYPEDEF].rows; ++i) {
4013 token = MONO_TOKEN_TYPE_DEF | (i + 1);
4014 klass = mono_class_get_checked (acfg->image, token, &error);
4017 mono_error_cleanup (&error);
4021 if (klass->valuetype && !klass->generic_container && can_marshal_struct (klass) &&
4022 !(klass->nested_in && strstr (klass->nested_in->name, "<PrivateImplementationDetails>") == klass->nested_in->name)) {
4023 add_method (acfg, mono_marshal_get_struct_to_ptr (klass));
4024 add_method (acfg, mono_marshal_get_ptr_to_struct (klass));
4030 has_type_vars (MonoClass *klass)
4032 if ((klass->byval_arg.type == MONO_TYPE_VAR) || (klass->byval_arg.type == MONO_TYPE_MVAR))
4035 return has_type_vars (klass->element_class);
4036 if (klass->generic_class) {
4037 MonoGenericContext *context = &klass->generic_class->context;
4038 if (context->class_inst) {
4041 for (i = 0; i < context->class_inst->type_argc; ++i)
4042 if (has_type_vars (mono_class_from_mono_type (context->class_inst->type_argv [i])))
4046 if (klass->generic_container)
4052 is_vt_inst (MonoGenericInst *inst)
4056 for (i = 0; i < inst->type_argc; ++i) {
4057 MonoType *t = inst->type_argv [i];
4058 if (MONO_TYPE_ISSTRUCT (t) || t->type == MONO_TYPE_VALUETYPE)
4065 method_has_type_vars (MonoMethod *method)
4067 if (has_type_vars (method->klass))
4070 if (method->is_inflated) {
4071 MonoGenericContext *context = mono_method_get_context (method);
4072 if (context->method_inst) {
4075 for (i = 0; i < context->method_inst->type_argc; ++i)
4076 if (has_type_vars (mono_class_from_mono_type (context->method_inst->type_argv [i])))
4084 gboolean mono_aot_mode_is_full (MonoAotOptions *opts)
4086 return opts->mode == MONO_AOT_MODE_FULL;
4089 static void add_generic_class_with_depth (MonoAotCompile *acfg, MonoClass *klass, int depth, const char *ref);
4092 add_generic_class (MonoAotCompile *acfg, MonoClass *klass, gboolean force, const char *ref)
4094 /* This might lead to a huge code blowup so only do it if neccesary */
4095 if (!mono_aot_mode_is_full (&acfg->aot_opts) && !force)
4098 add_generic_class_with_depth (acfg, klass, 0, ref);
4102 check_type_depth (MonoType *t, int depth)
4110 case MONO_TYPE_GENERICINST: {
4111 MonoGenericClass *gklass = t->data.generic_class;
4112 MonoGenericInst *ginst = gklass->context.class_inst;
4115 for (i = 0; i < ginst->type_argc; ++i) {
4116 if (check_type_depth (ginst->type_argv [i], depth + 1))
4130 add_types_from_method_header (MonoAotCompile *acfg, MonoMethod *method);
4133 * add_generic_class:
4135 * Add all methods of a generic class.
4138 add_generic_class_with_depth (MonoAotCompile *acfg, MonoClass *klass, int depth, const char *ref)
4141 MonoClassField *field;
4143 gboolean use_gsharedvt = FALSE;
4145 if (!acfg->ginst_hash)
4146 acfg->ginst_hash = g_hash_table_new (NULL, NULL);
4148 mono_class_init (klass);
4150 if (klass->generic_class && klass->generic_class->context.class_inst->is_open)
4153 if (has_type_vars (klass))
4156 if (!klass->generic_class && !klass->rank)
4159 if (klass->exception_type)
4162 if (!acfg->ginst_hash)
4163 acfg->ginst_hash = g_hash_table_new (NULL, NULL);
4165 if (g_hash_table_lookup (acfg->ginst_hash, klass))
4168 if (check_type_depth (&klass->byval_arg, 0))
4171 if (acfg->aot_opts.log_generics)
4172 aot_printf (acfg, "%*sAdding generic instance %s [%s].\n", depth, "", mono_type_full_name (&klass->byval_arg), ref);
4174 g_hash_table_insert (acfg->ginst_hash, klass, klass);
4177 * Use gsharedvt for generic collections with vtype arguments to avoid code blowup.
4178 * Enable this only for some classes since gsharedvt might not support all methods.
4180 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) &&
4181 (!strcmp (klass->name, "Dictionary`2") || !strcmp (klass->name, "List`1") || !strcmp (klass->name, "ReadOnlyCollection`1")))
4182 use_gsharedvt = TRUE;
4185 while ((method = mono_class_get_methods (klass, &iter))) {
4186 if ((acfg->opts & MONO_OPT_GSHAREDVT) && method->is_inflated && mono_method_get_context (method)->method_inst) {
4188 * This is partial sharing, and we can't handle it yet
4193 if (mono_method_is_generic_sharable_full (method, FALSE, FALSE, use_gsharedvt)) {
4195 add_types_from_method_header (acfg, method);
4199 if (method->is_generic)
4204 * FIXME: Instances which are referenced by these methods are not added,
4205 * for example Array.Resize<int> for List<int>.Add ().
4207 add_extra_method_with_depth (acfg, method, depth + 1);
4211 while ((field = mono_class_get_fields (klass, &iter))) {
4212 if (field->type->type == MONO_TYPE_GENERICINST)
4213 add_generic_class_with_depth (acfg, mono_class_from_mono_type (field->type), depth + 1, "field");
4216 if (klass->delegate) {
4217 method = mono_get_delegate_invoke (klass);
4219 method = mono_marshal_get_delegate_invoke (method, NULL);
4221 if (acfg->aot_opts.log_generics)
4222 aot_printf (acfg, "%*sAdding method %s.\n", depth, "", mono_method_get_full_name (method));
4224 add_method (acfg, method);
4227 /* Add superclasses */
4229 add_generic_class_with_depth (acfg, klass->parent, depth, "parent");
4232 * For ICollection<T>, add instances of the helper methods
4233 * in Array, since a T[] could be cast to ICollection<T>.
4235 if (klass->image == mono_defaults.corlib && !strcmp (klass->name_space, "System.Collections.Generic") &&
4236 (!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"))) {
4237 MonoClass *tclass = mono_class_from_mono_type (klass->generic_class->context.class_inst->type_argv [0]);
4238 MonoClass *array_class = mono_bounded_array_class_get (tclass, 1, FALSE);
4242 if (!strcmp (klass->name, "IEnumerator`1"))
4243 name_prefix = g_strdup_printf ("%s.%s", klass->name_space, "IEnumerable`1");
4245 name_prefix = g_strdup_printf ("%s.%s", klass->name_space, klass->name);
4247 /* Add the T[]/InternalEnumerator class */
4248 if (!strcmp (klass->name, "IEnumerable`1") || !strcmp (klass->name, "IEnumerator`1")) {
4252 while ((nclass = mono_class_get_nested_types (array_class->parent, &iter))) {
4253 if (!strcmp (nclass->name, "InternalEnumerator`1"))
4257 nclass = mono_class_inflate_generic_class (nclass, mono_generic_class_get_context (klass->generic_class));
4258 add_generic_class (acfg, nclass, FALSE, "ICollection<T>");
4262 while ((method = mono_class_get_methods (array_class, &iter))) {
4263 if (strstr (method->name, name_prefix)) {
4264 MonoMethod *m = mono_aot_get_array_helper_from_wrapper (method);
4266 add_extra_method_with_depth (acfg, m, depth);
4270 g_free (name_prefix);
4273 /* Add an instance of GenericComparer<T> which is created dynamically by Comparer<T> */
4274 if (klass->image == mono_defaults.corlib && !strcmp (klass->name_space, "System.Collections.Generic") && !strcmp (klass->name, "Comparer`1")) {
4275 MonoClass *tclass = mono_class_from_mono_type (klass->generic_class->context.class_inst->type_argv [0]);
4276 MonoClass *icomparable, *gcomparer;
4277 MonoGenericContext ctx;
4278 MonoType *args [16];
4280 memset (&ctx, 0, sizeof (ctx));
4282 icomparable = mono_class_from_name (mono_defaults.corlib, "System", "IComparable`1");
4283 g_assert (icomparable);
4284 args [0] = &tclass->byval_arg;
4285 ctx.class_inst = mono_metadata_get_generic_inst (1, args);
4287 if (mono_class_is_assignable_from (mono_class_inflate_generic_class (icomparable, &ctx), tclass)) {
4288 gcomparer = mono_class_from_name (mono_defaults.corlib, "System.Collections.Generic", "GenericComparer`1");
4289 g_assert (gcomparer);
4290 add_generic_class (acfg, mono_class_inflate_generic_class (gcomparer, &ctx), FALSE, "Comparer<T>");
4294 /* Add an instance of GenericEqualityComparer<T> which is created dynamically by EqualityComparer<T> */
4295 if (klass->image == mono_defaults.corlib && !strcmp (klass->name_space, "System.Collections.Generic") && !strcmp (klass->name, "EqualityComparer`1")) {
4296 MonoClass *tclass = mono_class_from_mono_type (klass->generic_class->context.class_inst->type_argv [0]);
4297 MonoClass *iface, *gcomparer;
4298 MonoGenericContext ctx;
4299 MonoType *args [16];
4301 memset (&ctx, 0, sizeof (ctx));
4303 iface = mono_class_from_name (mono_defaults.corlib, "System", "IEquatable`1");
4305 args [0] = &tclass->byval_arg;
4306 ctx.class_inst = mono_metadata_get_generic_inst (1, args);
4308 if (mono_class_is_assignable_from (mono_class_inflate_generic_class (iface, &ctx), tclass)) {
4309 gcomparer = mono_class_from_name (mono_defaults.corlib, "System.Collections.Generic", "GenericEqualityComparer`1");
4310 g_assert (gcomparer);
4311 add_generic_class (acfg, mono_class_inflate_generic_class (gcomparer, &ctx), FALSE, "EqualityComparer<T>");
4315 /* Add an instance of EnumComparer<T> which is created dynamically by EqualityComparer<T> for enums */
4316 if (klass->image == mono_defaults.corlib && !strcmp (klass->name_space, "System.Collections.Generic") && !strcmp (klass->name, "EqualityComparer`1")) {
4317 MonoClass *enum_comparer;
4318 MonoClass *tclass = mono_class_from_mono_type (klass->generic_class->context.class_inst->type_argv [0]);
4319 MonoGenericContext ctx;
4320 MonoType *args [16];
4322 if (mono_class_is_enum (tclass)) {
4323 memset (&ctx, 0, sizeof (ctx));
4324 args [0] = &tclass->byval_arg;
4325 ctx.class_inst = mono_metadata_get_generic_inst (1, args);
4327 enum_comparer = mono_class_from_name (mono_defaults.corlib, "System.Collections.Generic", "EnumEqualityComparer`1");
4328 g_assert (enum_comparer);
4329 add_generic_class (acfg, mono_class_inflate_generic_class (enum_comparer, &ctx), FALSE, "EqualityComparer<T>");
4333 /* Add an instance of ObjectComparer<T> which is created dynamically by Comparer<T> for enums */
4334 if (klass->image == mono_defaults.corlib && !strcmp (klass->name_space, "System.Collections.Generic") && !strcmp (klass->name, "Comparer`1")) {
4335 MonoClass *comparer;
4336 MonoClass *tclass = mono_class_from_mono_type (klass->generic_class->context.class_inst->type_argv [0]);
4337 MonoGenericContext ctx;
4338 MonoType *args [16];
4340 if (mono_class_is_enum (tclass)) {
4341 memset (&ctx, 0, sizeof (ctx));
4342 args [0] = &tclass->byval_arg;
4343 ctx.class_inst = mono_metadata_get_generic_inst (1, args);
4345 comparer = mono_class_from_name (mono_defaults.corlib, "System.Collections.Generic", "ObjectComparer`1");
4346 g_assert (comparer);
4347 add_generic_class (acfg, mono_class_inflate_generic_class (comparer, &ctx), FALSE, "Comparer<T>");
4353 add_instances_of (MonoAotCompile *acfg, MonoClass *klass, MonoType **insts, int ninsts, gboolean force)
4356 MonoGenericContext ctx;
4357 MonoType *args [16];
4359 if (acfg->aot_opts.no_instances)
4362 memset (&ctx, 0, sizeof (ctx));
4364 for (i = 0; i < ninsts; ++i) {
4365 args [0] = insts [i];
4366 ctx.class_inst = mono_metadata_get_generic_inst (1, args);
4367 add_generic_class (acfg, mono_class_inflate_generic_class (klass, &ctx), force, "");
4372 add_types_from_method_header (MonoAotCompile *acfg, MonoMethod *method)
4374 MonoMethodHeader *header;
4375 MonoMethodSignature *sig;
4378 depth = GPOINTER_TO_UINT (g_hash_table_lookup (acfg->method_depth, method));
4380 sig = mono_method_signature (method);
4383 for (j = 0; j < sig->param_count; ++j)
4384 if (sig->params [j]->type == MONO_TYPE_GENERICINST)
4385 add_generic_class_with_depth (acfg, mono_class_from_mono_type (sig->params [j]), depth + 1, "arg");
4388 header = mono_method_get_header (method);
4391 for (j = 0; j < header->num_locals; ++j)
4392 if (header->locals [j]->type == MONO_TYPE_GENERICINST)
4393 add_generic_class_with_depth (acfg, mono_class_from_mono_type (header->locals [j]), depth + 1, "local");
4395 mono_loader_clear_error ();
4400 * add_generic_instances:
4402 * Add instances referenced by the METHODSPEC/TYPESPEC table.
4405 add_generic_instances (MonoAotCompile *acfg)
4410 MonoGenericContext *context;
4412 if (acfg->aot_opts.no_instances)
4415 for (i = 0; i < acfg->image->tables [MONO_TABLE_METHODSPEC].rows; ++i) {
4417 token = MONO_TOKEN_METHOD_SPEC | (i + 1);
4418 method = mono_get_method_checked (acfg->image, token, NULL, NULL, &error);
4421 aot_printerrf (acfg, "Failed to load methodspec 0x%x due to %s.\n", token, mono_error_get_message (&error));
4422 aot_printerrf (acfg, "Run with MONO_LOG_LEVEL=debug for more information.\n");
4423 mono_error_cleanup (&error);
4427 if (method->klass->image != acfg->image)
4430 context = mono_method_get_context (method);
4432 if (context && ((context->class_inst && context->class_inst->is_open)))
4436 * For open methods, create an instantiation which can be passed to the JIT.
4437 * FIXME: Handle class_inst as well.
4439 if (context && context->method_inst && context->method_inst->is_open) {
4441 MonoGenericContext shared_context;
4442 MonoGenericInst *inst;
4443 MonoType **type_argv;
4445 MonoMethod *declaring_method;
4446 gboolean supported = TRUE;
4448 /* Check that the context doesn't contain open constructed types */
4449 if (context->class_inst) {
4450 inst = context->class_inst;
4451 for (i = 0; i < inst->type_argc; ++i) {
4452 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)
4454 if (mono_class_is_open_constructed_type (inst->type_argv [i]))
4458 if (context->method_inst) {
4459 inst = context->method_inst;
4460 for (i = 0; i < inst->type_argc; ++i) {
4461 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)
4463 if (mono_class_is_open_constructed_type (inst->type_argv [i]))
4471 memset (&shared_context, 0, sizeof (MonoGenericContext));
4473 inst = context->class_inst;
4475 type_argv = g_new0 (MonoType*, inst->type_argc);
4476 for (i = 0; i < inst->type_argc; ++i) {
4477 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)
4478 type_argv [i] = &mono_defaults.object_class->byval_arg;
4480 type_argv [i] = inst->type_argv [i];
4483 shared_context.class_inst = mono_metadata_get_generic_inst (inst->type_argc, type_argv);
4487 inst = context->method_inst;
4489 type_argv = g_new0 (MonoType*, inst->type_argc);
4490 for (i = 0; i < inst->type_argc; ++i) {
4491 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)
4492 type_argv [i] = &mono_defaults.object_class->byval_arg;
4494 type_argv [i] = inst->type_argv [i];
4497 shared_context.method_inst = mono_metadata_get_generic_inst (inst->type_argc, type_argv);
4501 if (method->is_generic || method->klass->generic_container)
4502 declaring_method = method;
4504 declaring_method = mono_method_get_declaring_generic_method (method);
4506 method = mono_class_inflate_generic_method_checked (declaring_method, &shared_context, &error);
4507 g_assert (mono_error_ok (&error)); /* FIXME don't swallow the error */
4511 * If the method is fully sharable, it was already added in place of its
4512 * generic definition.
4514 if (mono_method_is_generic_sharable_full (method, FALSE, FALSE, FALSE))
4518 * FIXME: Partially shared methods are not shared here, so we end up with
4519 * many identical methods.
4521 add_extra_method (acfg, method);
4524 for (i = 0; i < acfg->image->tables [MONO_TABLE_TYPESPEC].rows; ++i) {
4528 token = MONO_TOKEN_TYPE_SPEC | (i + 1);
4530 klass = mono_class_get_checked (acfg->image, token, &error);
4531 if (!klass || klass->rank) {
4532 mono_error_cleanup (&error);
4536 add_generic_class (acfg, klass, FALSE, "typespec");
4539 /* Add types of args/locals */
4540 for (i = 0; i < acfg->methods->len; ++i) {
4541 method = (MonoMethod *)g_ptr_array_index (acfg->methods, i);
4542 add_types_from_method_header (acfg, method);
4545 if (acfg->image == mono_defaults.corlib) {
4547 MonoType *insts [256];
4550 insts [ninsts ++] = &mono_defaults.byte_class->byval_arg;
4551 insts [ninsts ++] = &mono_defaults.sbyte_class->byval_arg;
4552 insts [ninsts ++] = &mono_defaults.int16_class->byval_arg;
4553 insts [ninsts ++] = &mono_defaults.uint16_class->byval_arg;
4554 insts [ninsts ++] = &mono_defaults.int32_class->byval_arg;
4555 insts [ninsts ++] = &mono_defaults.uint32_class->byval_arg;
4556 insts [ninsts ++] = &mono_defaults.int64_class->byval_arg;
4557 insts [ninsts ++] = &mono_defaults.uint64_class->byval_arg;
4558 insts [ninsts ++] = &mono_defaults.single_class->byval_arg;
4559 insts [ninsts ++] = &mono_defaults.double_class->byval_arg;
4560 insts [ninsts ++] = &mono_defaults.char_class->byval_arg;
4561 insts [ninsts ++] = &mono_defaults.boolean_class->byval_arg;
4563 /* Add GenericComparer<T> instances for primitive types for Enum.ToString () */
4564 klass = mono_class_from_name (acfg->image, "System.Collections.Generic", "GenericComparer`1");
4566 add_instances_of (acfg, klass, insts, ninsts, TRUE);
4567 klass = mono_class_from_name (acfg->image, "System.Collections.Generic", "GenericEqualityComparer`1");
4569 add_instances_of (acfg, klass, insts, ninsts, TRUE);
4571 /* Add instances of EnumEqualityComparer which are created by EqualityComparer<T> for enums */
4573 MonoClass *enum_comparer;
4574 MonoType *insts [16];
4578 insts [ninsts ++] = &mono_defaults.int32_class->byval_arg;
4579 insts [ninsts ++] = &mono_defaults.uint32_class->byval_arg;
4580 insts [ninsts ++] = &mono_defaults.uint16_class->byval_arg;
4581 insts [ninsts ++] = &mono_defaults.byte_class->byval_arg;
4582 enum_comparer = mono_class_from_name (mono_defaults.corlib, "System.Collections.Generic", "EnumEqualityComparer`1");
4583 g_assert (enum_comparer);
4584 add_instances_of (acfg, enum_comparer, insts, ninsts, FALSE);
4587 insts [ninsts ++] = &mono_defaults.int16_class->byval_arg;
4588 enum_comparer = mono_class_from_name (mono_defaults.corlib, "System.Collections.Generic", "ShortEnumEqualityComparer`1");
4589 g_assert (enum_comparer);
4590 add_instances_of (acfg, enum_comparer, insts, ninsts, FALSE);
4593 insts [ninsts ++] = &mono_defaults.sbyte_class->byval_arg;
4594 enum_comparer = mono_class_from_name (mono_defaults.corlib, "System.Collections.Generic", "SByteEnumEqualityComparer`1");
4595 g_assert (enum_comparer);
4596 add_instances_of (acfg, enum_comparer, insts, ninsts, FALSE);
4598 enum_comparer = mono_class_from_name (mono_defaults.corlib, "System.Collections.Generic", "LongEnumEqualityComparer`1");
4599 g_assert (enum_comparer);
4601 insts [ninsts ++] = &mono_defaults.int64_class->byval_arg;
4602 insts [ninsts ++] = &mono_defaults.uint64_class->byval_arg;
4603 add_instances_of (acfg, enum_comparer, insts, ninsts, FALSE);
4606 /* Add instances of the array generic interfaces for primitive types */
4607 /* This will add instances of the InternalArray_ helper methods in Array too */
4608 klass = mono_class_from_name (acfg->image, "System.Collections.Generic", "ICollection`1");
4610 add_instances_of (acfg, klass, insts, ninsts, TRUE);
4611 klass = mono_class_from_name (acfg->image, "System.Collections.Generic", "IList`1");
4613 add_instances_of (acfg, klass, insts, ninsts, TRUE);
4614 klass = mono_class_from_name (acfg->image, "System.Collections.Generic", "IEnumerable`1");
4616 add_instances_of (acfg, klass, insts, ninsts, TRUE);
4619 * Add a managed-to-native wrapper of Array.GetGenericValueImpl<object>, which is
4620 * used for all instances of GetGenericValueImpl by the AOT runtime.
4623 MonoGenericContext ctx;
4624 MonoType *args [16];
4625 MonoMethod *get_method;
4626 MonoClass *array_klass = mono_array_class_get (mono_defaults.object_class, 1)->parent;
4628 get_method = mono_class_get_method_from_name (array_klass, "GetGenericValueImpl", 2);
4632 memset (&ctx, 0, sizeof (ctx));
4633 args [0] = &mono_defaults.object_class->byval_arg;
4634 ctx.method_inst = mono_metadata_get_generic_inst (1, args);
4635 add_extra_method (acfg, mono_marshal_get_native_wrapper (mono_class_inflate_generic_method_checked (get_method, &ctx, &error), TRUE, TRUE));
4636 g_assert (mono_error_ok (&error)); /* FIXME don't swallow the error */
4640 /* Same for CompareExchange<T>/Exchange<T> */
4642 MonoGenericContext ctx;
4643 MonoType *args [16];
4645 MonoClass *interlocked_klass = mono_class_from_name (mono_defaults.corlib, "System.Threading", "Interlocked");
4646 gpointer iter = NULL;
4648 while ((m = mono_class_get_methods (interlocked_klass, &iter))) {
4649 if ((!strcmp (m->name, "CompareExchange") || !strcmp (m->name, "Exchange")) && m->is_generic) {
4651 memset (&ctx, 0, sizeof (ctx));
4652 args [0] = &mono_defaults.object_class->byval_arg;
4653 ctx.method_inst = mono_metadata_get_generic_inst (1, args);
4654 add_extra_method (acfg, mono_marshal_get_native_wrapper (mono_class_inflate_generic_method_checked (m, &ctx, &error), TRUE, TRUE));
4655 g_assert (mono_error_ok (&error)); /* FIXME don't swallow the error */
4660 /* Same for Volatile.Read/Write<T> */
4662 MonoGenericContext ctx;
4663 MonoType *args [16];
4665 MonoClass *volatile_klass = mono_class_from_name (mono_defaults.corlib, "System.Threading", "Volatile");
4666 gpointer iter = NULL;
4668 if (volatile_klass) {
4669 while ((m = mono_class_get_methods (volatile_klass, &iter))) {
4670 if ((!strcmp (m->name, "Read") || !strcmp (m->name, "Write")) && m->is_generic) {
4672 memset (&ctx, 0, sizeof (ctx));
4673 args [0] = &mono_defaults.object_class->byval_arg;
4674 ctx.method_inst = mono_metadata_get_generic_inst (1, args);
4675 add_extra_method (acfg, mono_marshal_get_native_wrapper (mono_class_inflate_generic_method_checked (m, &ctx, &error), TRUE, TRUE));
4676 g_assert (mono_error_ok (&error)); /* FIXME don't swallow the error */
4682 /* object[] accessor wrappers. */
4684 MonoClass *obj_array_class = mono_array_class_get (mono_defaults.object_class, 1);
4687 m = mono_class_get_method_from_name (obj_array_class, "Get", 1);
4690 m = mono_marshal_get_array_accessor_wrapper (m);
4691 add_extra_method (acfg, m);
4693 m = mono_class_get_method_from_name (obj_array_class, "Address", 1);
4696 m = mono_marshal_get_array_accessor_wrapper (m);
4697 add_extra_method (acfg, m);
4699 m = mono_class_get_method_from_name (obj_array_class, "Set", 2);
4702 m = mono_marshal_get_array_accessor_wrapper (m);
4703 add_extra_method (acfg, m);
4709 * is_direct_callable:
4711 * Return whenever the method identified by JI is directly callable without
4712 * going through the PLT.
4715 is_direct_callable (MonoAotCompile *acfg, MonoMethod *method, MonoJumpInfo *patch_info)
4717 if ((patch_info->type == MONO_PATCH_INFO_METHOD) && (patch_info->data.method->klass->image == acfg->image)) {
4718 MonoCompile *callee_cfg = (MonoCompile *)g_hash_table_lookup (acfg->method_to_cfg, patch_info->data.method);
4720 gboolean direct_callable = TRUE;
4722 if (direct_callable && !(!callee_cfg->has_got_slots && (callee_cfg->method->klass->flags & TYPE_ATTRIBUTE_BEFORE_FIELD_INIT)))
4723 direct_callable = FALSE;
4724 if ((callee_cfg->method->iflags & METHOD_IMPL_ATTRIBUTE_SYNCHRONIZED) && (!method || method->wrapper_type != MONO_WRAPPER_SYNCHRONIZED))
4725 // FIXME: Maybe call the wrapper directly ?
4726 direct_callable = FALSE;
4728 if (acfg->aot_opts.soft_debug || acfg->aot_opts.no_direct_calls) {
4729 /* Disable this so all calls go through load_method (), see the
4730 * mini_get_debug_options ()->load_aot_jit_info_eagerly = TRUE; line in
4731 * mono_debugger_agent_init ().
4733 direct_callable = FALSE;
4736 if (callee_cfg->method->wrapper_type == MONO_WRAPPER_ALLOC)
4737 /* sgen does some initialization when the allocator method is created */
4738 direct_callable = FALSE;
4739 if (callee_cfg->method->wrapper_type == MONO_WRAPPER_WRITE_BARRIER)
4740 /* we don't know at compile time whether sgen is concurrent or not */
4741 direct_callable = FALSE;
4743 if (direct_callable)
4746 } else if ((patch_info->type == MONO_PATCH_INFO_ICALL_ADDR && patch_info->data.method->flags & METHOD_ATTRIBUTE_PINVOKE_IMPL)) {
4747 if (acfg->aot_opts.direct_pinvoke)
4749 } else if (patch_info->type == MONO_PATCH_INFO_ICALL_ADDR) {
4750 if (acfg->aot_opts.direct_icalls)
4758 #ifdef MONO_ARCH_AOT_SUPPORTED
4760 get_pinvoke_import (MonoAotCompile *acfg, MonoMethod *method)
4762 MonoImage *image = method->klass->image;
4763 MonoMethodPInvoke *piinfo = (MonoMethodPInvoke *) method;
4764 MonoTableInfo *tables = image->tables;
4765 MonoTableInfo *im = &tables [MONO_TABLE_IMPLMAP];
4766 MonoTableInfo *mr = &tables [MONO_TABLE_MODULEREF];
4767 guint32 im_cols [MONO_IMPLMAP_SIZE];
4770 import = (char *)g_hash_table_lookup (acfg->method_to_pinvoke_import, method);
4774 if (!piinfo->implmap_idx || piinfo->implmap_idx > im->rows)
4777 mono_metadata_decode_row (im, piinfo->implmap_idx - 1, im_cols, MONO_IMPLMAP_SIZE);
4779 if (!im_cols [MONO_IMPLMAP_SCOPE] || im_cols [MONO_IMPLMAP_SCOPE] > mr->rows)
4782 import = g_strdup_printf ("%s", mono_metadata_string_heap (image, im_cols [MONO_IMPLMAP_NAME]));
4784 g_hash_table_insert (acfg->method_to_pinvoke_import, method, import);
4790 get_pinvoke_import (MonoAotCompile *acfg, MonoMethod *method)
4797 compare_lne (MonoDebugLineNumberEntry *a, MonoDebugLineNumberEntry *b)
4799 if (a->native_offset == b->native_offset)
4800 return a->il_offset - b->il_offset;
4802 return a->native_offset - b->native_offset;
4806 * compute_line_numbers:
4808 * Returns a sparse array of size CODE_SIZE containing MonoDebugSourceLocation* entries for the native offsets which have a corresponding line number
4811 static MonoDebugSourceLocation**
4812 compute_line_numbers (MonoMethod *method, int code_size, MonoDebugMethodJitInfo *debug_info)
4814 MonoDebugMethodInfo *minfo;
4815 MonoDebugLineNumberEntry *ln_array;
4816 MonoDebugSourceLocation *loc;
4817 int i, prev_line, prev_il_offset;
4818 int *native_to_il_offset = NULL;
4819 MonoDebugSourceLocation **res;
4822 minfo = mono_debug_lookup_method (method);
4825 // FIXME: This seems to happen when two methods have the same cfg->method_to_register
4826 if (debug_info->code_size != code_size)
4829 g_assert (code_size);
4831 /* Compute the native->IL offset mapping */
4833 ln_array = g_new0 (MonoDebugLineNumberEntry, debug_info->num_line_numbers);
4834 memcpy (ln_array, debug_info->line_numbers, debug_info->num_line_numbers * sizeof (MonoDebugLineNumberEntry));
4836 qsort (ln_array, debug_info->num_line_numbers, sizeof (MonoDebugLineNumberEntry), (int (*)(const void *, const void *))compare_lne);
4838 native_to_il_offset = g_new0 (int, code_size + 1);
4840 for (i = 0; i < debug_info->num_line_numbers; ++i) {
4842 MonoDebugLineNumberEntry *lne = &ln_array [i];
4845 for (j = 0; j < lne->native_offset; ++j)
4846 native_to_il_offset [j] = -1;
4849 if (i < debug_info->num_line_numbers - 1) {
4850 MonoDebugLineNumberEntry *lne_next = &ln_array [i + 1];
4852 for (j = lne->native_offset; j < lne_next->native_offset; ++j)
4853 native_to_il_offset [j] = lne->il_offset;
4855 for (j = lne->native_offset; j < code_size; ++j)
4856 native_to_il_offset [j] = lne->il_offset;
4861 /* Compute the native->line number mapping */
4862 res = g_new0 (MonoDebugSourceLocation*, code_size);
4863 prev_il_offset = -1;
4866 for (i = 0; i < code_size; ++i) {
4867 int il_offset = native_to_il_offset [i];
4869 if (il_offset == -1 || il_offset == prev_il_offset)
4871 prev_il_offset = il_offset;
4872 loc = mono_debug_symfile_lookup_location (minfo, il_offset);
4873 if (!(loc && loc->source_file))
4875 if (loc->row == prev_line) {
4876 mono_debug_symfile_free_location (loc);
4879 prev_line = loc->row;
4880 //printf ("D: %s:%d il=%x native=%x\n", loc->source_file, loc->row, il_offset, i);
4882 /* This will cover the prolog too */
4892 get_file_index (MonoAotCompile *acfg, const char *source_file)
4896 // FIXME: Free these
4897 if (!acfg->dwarf_ln_filenames)
4898 acfg->dwarf_ln_filenames = g_hash_table_new (g_str_hash, g_str_equal);
4899 findex = GPOINTER_TO_INT (g_hash_table_lookup (acfg->dwarf_ln_filenames, source_file));
4901 findex = g_hash_table_size (acfg->dwarf_ln_filenames) + 1;
4902 g_hash_table_insert (acfg->dwarf_ln_filenames, g_strdup (source_file), GINT_TO_POINTER (findex));
4903 emit_unset_mode (acfg);
4904 fprintf (acfg->fp, ".file %d \"%s\"\n", findex, mono_dwarf_escape_path (source_file));
4916 * emit_and_reloc_code:
4918 * Emit the native code in CODE, handling relocations along the way. If GOT_ONLY
4919 * is true, calls are made through the GOT too. This is used for emitting trampolines
4920 * in full-aot mode, since calls made from trampolines couldn't go through the PLT,
4921 * since trampolines are needed to make PTL work.
4924 emit_and_reloc_code (MonoAotCompile *acfg, MonoMethod *method, guint8 *code, guint32 code_len, MonoJumpInfo *relocs, gboolean got_only, MonoDebugMethodJitInfo *debug_info)
4926 int i, pindex, start_index;
4928 MonoJumpInfo *patch_info;
4929 MonoDebugSourceLocation **locs = NULL;
4931 #ifdef MONO_ARCH_AOT_SUPPORTED
4932 gboolean direct_call, external_call;
4934 const char *direct_call_target = 0;
4935 const char *direct_pinvoke;
4938 if (acfg->gas_line_numbers && method && debug_info) {
4939 locs = compute_line_numbers (method, code_len, debug_info);
4941 int findex = get_file_index (acfg, "<unknown>");
4942 emit_unset_mode (acfg);
4943 fprintf (acfg->fp, ".loc %d %d 0\n", findex, 1);
4947 /* Collect and sort relocations */
4948 patches = g_ptr_array_new ();
4949 for (patch_info = relocs; patch_info; patch_info = patch_info->next)
4950 g_ptr_array_add (patches, patch_info);
4951 g_ptr_array_sort (patches, compare_patches);
4954 for (i = 0; i < code_len; i += INST_LEN) {
4956 for (pindex = start_index; pindex < patches->len; ++pindex) {
4957 patch_info = (MonoJumpInfo *)g_ptr_array_index (patches, pindex);
4958 if (patch_info->ip.i >= i)
4962 if (locs && locs [i]) {
4963 MonoDebugSourceLocation *loc = locs [i];
4966 findex = get_file_index (acfg, loc->source_file);
4967 emit_unset_mode (acfg);
4968 fprintf (acfg->fp, ".loc %d %d 0\n", findex, loc->row);
4969 mono_debug_symfile_free_location (loc);
4973 #ifdef MONO_ARCH_AOT_SUPPORTED
4974 if (patch_info && (patch_info->ip.i == i) && (pindex < patches->len)) {
4975 start_index = pindex;
4977 switch (patch_info->type) {
4978 case MONO_PATCH_INFO_NONE:
4980 case MONO_PATCH_INFO_GOT_OFFSET: {
4983 arch_emit_got_offset (acfg, code + i, &code_size);
4984 i += code_size - INST_LEN;
4986 patch_info->type = MONO_PATCH_INFO_NONE;
4989 case MONO_PATCH_INFO_OBJC_SELECTOR_REF: {
4990 int code_size, index;
4991 char *selector = (char *)patch_info->data.target;
4993 if (!acfg->objc_selector_to_index)
4994 acfg->objc_selector_to_index = g_hash_table_new (g_str_hash, g_str_equal);
4995 if (!acfg->objc_selectors)
4996 acfg->objc_selectors = g_ptr_array_new ();
4997 index = GPOINTER_TO_UINT (g_hash_table_lookup (acfg->objc_selector_to_index, selector));
5001 index = acfg->objc_selector_index;
5002 g_ptr_array_add (acfg->objc_selectors, (void*)patch_info->data.target);
5003 g_hash_table_insert (acfg->objc_selector_to_index, selector, GUINT_TO_POINTER (index + 1));
5004 acfg->objc_selector_index ++;
5007 arch_emit_objc_selector_ref (acfg, code + i, index, &code_size);
5008 i += code_size - INST_LEN;
5010 patch_info->type = MONO_PATCH_INFO_NONE;
5015 * If this patch is a call, try emitting a direct call instead of
5016 * through a PLT entry. This is possible if the called method is in
5017 * the same assembly and requires no initialization.
5019 direct_call = FALSE;
5020 external_call = FALSE;
5021 if ((patch_info->type == MONO_PATCH_INFO_METHOD) && (patch_info->data.method->klass->image == acfg->image)) {
5022 if (!got_only && is_direct_callable (acfg, method, patch_info)) {
5023 MonoCompile *callee_cfg = (MonoCompile *)g_hash_table_lookup (acfg->method_to_cfg, patch_info->data.method);
5024 //printf ("DIRECT: %s %s\n", method ? mono_method_full_name (method, TRUE) : "", mono_method_full_name (callee_cfg->method, TRUE));
5026 direct_call_target = callee_cfg->asm_symbol;
5027 patch_info->type = MONO_PATCH_INFO_NONE;
5028 acfg->stats.direct_calls ++;
5031 acfg->stats.all_calls ++;
5032 } else if (patch_info->type == MONO_PATCH_INFO_ICALL_ADDR) {
5033 if (!got_only && is_direct_callable (acfg, method, patch_info)) {
5034 if (!(patch_info->data.method->flags & METHOD_ATTRIBUTE_PINVOKE_IMPL))
5035 direct_pinvoke = mono_lookup_icall_symbol (patch_info->data.method);
5037 direct_pinvoke = get_pinvoke_import (acfg, patch_info->data.method);
5038 if (direct_pinvoke) {
5040 g_assert (strlen (direct_pinvoke) < 1000);
5041 direct_call_target = g_strdup_printf ("%s%s", acfg->user_symbol_prefix, direct_pinvoke);
5044 } else if (patch_info->type == MONO_PATCH_INFO_JIT_ICALL_ADDR) {
5045 const char *sym = mono_lookup_jit_icall_symbol (patch_info->data.name);
5046 if (!got_only && sym && acfg->aot_opts.direct_icalls) {
5047 /* Call to a C function implementing a jit icall */
5049 external_call = TRUE;
5050 g_assert (strlen (sym) < 1000);
5051 direct_call_target = g_strdup_printf ("%s%s", acfg->user_symbol_prefix, sym);
5053 } else if (patch_info->type == MONO_PATCH_INFO_INTERNAL_METHOD) {
5054 MonoJitICallInfo *info = mono_find_jit_icall_by_name (patch_info->data.name);
5055 const char *sym = mono_lookup_jit_icall_symbol (patch_info->data.name);
5056 if (!got_only && sym && acfg->aot_opts.direct_icalls && info->func == info->wrapper) {
5057 /* Call to a jit icall without a wrapper */
5059 external_call = TRUE;
5060 g_assert (strlen (sym) < 1000);
5061 direct_call_target = g_strdup_printf ("%s%s", acfg->user_symbol_prefix, sym);
5066 patch_info->type = MONO_PATCH_INFO_NONE;
5067 acfg->stats.direct_calls ++;
5070 if (!got_only && !direct_call) {
5071 MonoPltEntry *plt_entry = get_plt_entry (acfg, patch_info);
5073 /* This patch has a PLT entry, so we must emit a call to the PLT entry */
5075 direct_call_target = plt_entry->symbol;
5077 /* Nullify the patch */
5078 patch_info->type = MONO_PATCH_INFO_NONE;
5079 plt_entry->jit_used = TRUE;
5086 arch_emit_direct_call (acfg, direct_call_target, external_call, FALSE, patch_info, &call_size);
5087 i += call_size - INST_LEN;
5091 got_slot = get_got_offset (acfg, FALSE, patch_info);
5093 arch_emit_got_access (acfg, acfg->got_symbol, code + i, got_slot, &code_size);
5094 i += code_size - INST_LEN;
5100 #endif /* MONO_ARCH_AOT_SUPPORTED */
5103 /* Find next patch */
5105 for (pindex = start_index; pindex < patches->len; ++pindex) {
5106 patch_info = (MonoJumpInfo *)g_ptr_array_index (patches, pindex);
5107 if (patch_info->ip.i >= i)
5111 /* Try to emit multiple bytes at once */
5112 if (pindex < patches->len && patch_info->ip.i > i) {
5115 for (limit = i + INST_LEN; limit < patch_info->ip.i; limit += INST_LEN) {
5116 if (locs && locs [limit])
5120 emit_code_bytes (acfg, code + i, limit - i);
5121 i = limit - INST_LEN;
5123 emit_code_bytes (acfg, code + i, INST_LEN);
5134 * Return a modified version of S which only includes characters permissible in symbols.
5137 sanitize_symbol (MonoAotCompile *acfg, char *s)
5139 gboolean process = FALSE;
5148 for (i = 0; i < len; ++i)
5149 if (!(s [i] <= 0x7f && (isalnum (s [i]) || s [i] == '_')))
5154 gs = g_string_sized_new (len);
5155 for (i = 0; i < len; ++i) {
5157 if (c <= 0x7f && (isalnum (c) || c == '_')) {
5158 g_string_append_c (gs, c);
5159 } else if (c > 0x7f) {
5160 /* multi-byte utf8 */
5161 g_string_append_printf (gs, "_0x%x", c);
5164 while (c >> 6 == 0x2) {
5165 g_string_append_printf (gs, "%x", c);
5169 g_string_append_printf (gs, "_");
5172 g_string_append_c (gs, '_');
5176 res = mono_mempool_strdup (acfg->mempool, gs->str);
5177 g_string_free (gs, TRUE);
5182 get_debug_sym (MonoMethod *method, const char *prefix, GHashTable *cache)
5184 char *name1, *name2, *cached;
5185 int i, j, len, count;
5186 MonoMethod *cached_method;
5188 name1 = mono_method_full_name (method, TRUE);
5191 // This is so that we don't accidentally create a local symbol (which starts with 'L')
5192 if ((!prefix || !*prefix) && name1 [0] == 'L')
5196 len = strlen (name1);
5197 name2 = (char *)malloc (strlen (prefix) + len + 16);
5198 memcpy (name2, prefix, strlen (prefix));
5199 j = strlen (prefix);
5200 for (i = 0; i < len; ++i) {
5201 if (i == 0 && name1 [0] >= '0' && name1 [0] <= '9') {
5203 } else if (isalnum (name1 [i])) {
5204 name2 [j ++] = name1 [i];
5205 } else if (name1 [i] == ' ' && name1 [i + 1] == '(' && name1 [i + 2] == ')') {
5207 } else if (name1 [i] == ',' && name1 [i + 1] == ' ') {
5210 } else if (name1 [i] == '(' || name1 [i] == ')' || name1 [i] == '>') {
5220 cached_method = (MonoMethod *)g_hash_table_lookup (cache, name2);
5221 if (!(cached_method && cached_method != method))
5223 sprintf (name2 + j, "_%d", count);
5227 cached = g_strdup (name2);
5228 g_hash_table_insert (cache, cached, method);
5234 emit_method_code (MonoAotCompile *acfg, MonoCompile *cfg)
5239 char *debug_sym = NULL;
5240 char *symbol = NULL;
5241 int func_alignment = AOT_FUNC_ALIGNMENT;
5244 method = cfg->orig_method;
5245 code = cfg->native_code;
5247 method_index = get_method_index (acfg, method);
5248 symbol = g_strdup_printf ("%sme_%x", acfg->temp_prefix, method_index);
5250 /* Make the labels local */
5251 emit_section_change (acfg, ".text", 0);
5252 emit_alignment_code (acfg, func_alignment);
5254 if (acfg->global_symbols && acfg->need_no_dead_strip)
5255 fprintf (acfg->fp, " .no_dead_strip %s\n", cfg->asm_symbol);
5257 emit_label (acfg, cfg->asm_symbol);
5259 if (acfg->aot_opts.write_symbols && !acfg->global_symbols && !acfg->llvm) {
5261 * Write a C style symbol for every method, this has two uses:
5262 * - it works on platforms where the dwarf debugging info is not
5264 * - it allows the setting of breakpoints of aot-ed methods.
5266 debug_sym = get_debug_sym (method, "", acfg->method_label_hash);
5267 cfg->asm_debug_symbol = g_strdup (debug_sym);
5269 if (acfg->need_no_dead_strip)
5270 fprintf (acfg->fp, " .no_dead_strip %s\n", debug_sym);
5271 emit_local_symbol (acfg, debug_sym, symbol, TRUE);
5272 emit_label (acfg, debug_sym);
5275 export_name = (char *)g_hash_table_lookup (acfg->export_names, method);
5277 /* Emit a global symbol for the method */
5278 emit_global_inner (acfg, export_name, TRUE);
5279 emit_label (acfg, export_name);
5282 if (cfg->verbose_level > 0)
5283 g_print ("Method %s emitted as %s\n", mono_method_get_full_name (method), cfg->asm_symbol);
5285 acfg->stats.code_size += cfg->code_len;
5287 acfg->cfgs [method_index]->got_offset = acfg->got_offset;
5289 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 ()));
5293 if (acfg->aot_opts.write_symbols) {
5295 emit_symbol_size (acfg, debug_sym, ".");
5297 emit_symbol_size (acfg, cfg->asm_symbol, ".");
5301 emit_label (acfg, symbol);
5308 * Encode PATCH_INFO into its disk representation.
5311 encode_patch (MonoAotCompile *acfg, MonoJumpInfo *patch_info, guint8 *buf, guint8 **endbuf)
5315 switch (patch_info->type) {
5316 case MONO_PATCH_INFO_NONE:
5318 case MONO_PATCH_INFO_IMAGE:
5319 encode_value (get_image_index (acfg, patch_info->data.image), p, &p);
5321 case MONO_PATCH_INFO_MSCORLIB_GOT_ADDR:
5322 case MONO_PATCH_INFO_JIT_TLS_ID:
5323 case MONO_PATCH_INFO_GC_CARD_TABLE_ADDR:
5324 case MONO_PATCH_INFO_GC_NURSERY_START:
5325 case MONO_PATCH_INFO_GC_NURSERY_BITS:
5327 case MONO_PATCH_INFO_CASTCLASS_CACHE:
5328 encode_value (patch_info->data.index, p, &p);
5330 case MONO_PATCH_INFO_METHOD_REL:
5331 encode_value ((gint)patch_info->data.offset, p, &p);
5333 case MONO_PATCH_INFO_SWITCH: {
5334 gpointer *table = (gpointer *)patch_info->data.table->table;
5337 encode_value (patch_info->data.table->table_size, p, &p);
5338 for (k = 0; k < patch_info->data.table->table_size; k++)
5339 encode_value ((int)(gssize)table [k], p, &p);
5342 case MONO_PATCH_INFO_METHODCONST:
5343 case MONO_PATCH_INFO_METHOD:
5344 case MONO_PATCH_INFO_METHOD_JUMP:
5345 case MONO_PATCH_INFO_ICALL_ADDR:
5346 case MONO_PATCH_INFO_METHOD_RGCTX:
5347 case MONO_PATCH_INFO_METHOD_CODE_SLOT:
5348 encode_method_ref (acfg, patch_info->data.method, p, &p);
5350 case MONO_PATCH_INFO_AOT_JIT_INFO:
5351 encode_value (patch_info->data.index, p, &p);
5353 case MONO_PATCH_INFO_INTERNAL_METHOD:
5354 case MONO_PATCH_INFO_JIT_ICALL_ADDR: {
5355 guint32 len = strlen (patch_info->data.name);
5357 encode_value (len, p, &p);
5359 memcpy (p, patch_info->data.name, len);
5364 case MONO_PATCH_INFO_LDSTR: {
5365 guint32 image_index = get_image_index (acfg, patch_info->data.token->image);
5366 guint32 token = patch_info->data.token->token;
5367 g_assert (mono_metadata_token_code (token) == MONO_TOKEN_STRING);
5368 encode_value (image_index, p, &p);
5369 encode_value (patch_info->data.token->token - MONO_TOKEN_STRING, p, &p);
5372 case MONO_PATCH_INFO_RVA:
5373 case MONO_PATCH_INFO_DECLSEC:
5374 case MONO_PATCH_INFO_LDTOKEN:
5375 case MONO_PATCH_INFO_TYPE_FROM_HANDLE:
5376 encode_value (get_image_index (acfg, patch_info->data.token->image), p, &p);
5377 encode_value (patch_info->data.token->token, p, &p);
5378 encode_value (patch_info->data.token->has_context, p, &p);
5379 if (patch_info->data.token->has_context)
5380 encode_generic_context (acfg, &patch_info->data.token->context, p, &p);
5382 case MONO_PATCH_INFO_EXC_NAME: {
5383 MonoClass *ex_class;
5386 mono_class_from_name (mono_defaults.exception_class->image,
5387 "System", (const char *)patch_info->data.target);
5388 g_assert (ex_class);
5389 encode_klass_ref (acfg, ex_class, p, &p);
5392 case MONO_PATCH_INFO_R4:
5393 encode_value (*((guint32 *)patch_info->data.target), p, &p);
5395 case MONO_PATCH_INFO_R8:
5396 encode_value (((guint32 *)patch_info->data.target) [MINI_LS_WORD_IDX], p, &p);
5397 encode_value (((guint32 *)patch_info->data.target) [MINI_MS_WORD_IDX], p, &p);
5399 case MONO_PATCH_INFO_VTABLE:
5400 case MONO_PATCH_INFO_CLASS:
5401 case MONO_PATCH_INFO_IID:
5402 case MONO_PATCH_INFO_ADJUSTED_IID:
5403 encode_klass_ref (acfg, patch_info->data.klass, p, &p);
5405 case MONO_PATCH_INFO_DELEGATE_TRAMPOLINE:
5406 encode_klass_ref (acfg, patch_info->data.del_tramp->klass, p, &p);
5407 if (patch_info->data.del_tramp->method) {
5408 encode_value (1, p, &p);
5409 encode_method_ref (acfg, patch_info->data.del_tramp->method, p, &p);
5411 encode_value (0, p, &p);
5413 encode_value (patch_info->data.del_tramp->is_virtual, p, &p);
5415 case MONO_PATCH_INFO_FIELD:
5416 case MONO_PATCH_INFO_SFLDA:
5417 encode_field_info (acfg, patch_info->data.field, p, &p);
5419 case MONO_PATCH_INFO_INTERRUPTION_REQUEST_FLAG:
5421 case MONO_PATCH_INFO_RGCTX_FETCH:
5422 case MONO_PATCH_INFO_RGCTX_SLOT_INDEX: {
5423 MonoJumpInfoRgctxEntry *entry = patch_info->data.rgctx_entry;
5428 * entry->method has a lenghtly encoding and multiple rgctx_fetch entries
5429 * reference the same method, so encode the method only once.
5431 offset = GPOINTER_TO_UINT (g_hash_table_lookup (acfg->method_blob_hash, entry->method));
5433 buf2 = (guint8 *)g_malloc (1024);
5436 encode_method_ref (acfg, entry->method, p2, &p2);
5437 g_assert (p2 - buf2 < 1024);
5439 offset = add_to_blob (acfg, buf2, p2 - buf2);
5442 g_hash_table_insert (acfg->method_blob_hash, entry->method, GUINT_TO_POINTER (offset + 1));
5447 encode_value (offset, p, &p);
5448 g_assert ((int)entry->info_type < 256);
5449 g_assert (entry->data->type < 256);
5450 encode_value ((entry->in_mrgctx ? 1 : 0) | (entry->info_type << 1) | (entry->data->type << 9), p, &p);
5451 encode_patch (acfg, entry->data, p, &p);
5454 case MONO_PATCH_INFO_SEQ_POINT_INFO:
5455 case MONO_PATCH_INFO_AOT_MODULE:
5457 case MONO_PATCH_INFO_SIGNATURE:
5458 case MONO_PATCH_INFO_GSHAREDVT_IN_WRAPPER:
5459 encode_signature (acfg, (MonoMethodSignature*)patch_info->data.target, p, &p);
5461 case MONO_PATCH_INFO_TLS_OFFSET:
5462 encode_value (GPOINTER_TO_INT (patch_info->data.target), p, &p);
5464 case MONO_PATCH_INFO_GSHAREDVT_CALL:
5465 encode_signature (acfg, (MonoMethodSignature*)patch_info->data.gsharedvt->sig, p, &p);
5466 encode_method_ref (acfg, patch_info->data.gsharedvt->method, p, &p);
5468 case MONO_PATCH_INFO_GSHAREDVT_METHOD: {
5469 MonoGSharedVtMethodInfo *info = patch_info->data.gsharedvt_method;
5472 encode_method_ref (acfg, info->method, p, &p);
5473 encode_value (info->num_entries, p, &p);
5474 for (i = 0; i < info->num_entries; ++i) {
5475 MonoRuntimeGenericContextInfoTemplate *template_ = &info->entries [i];
5477 encode_value (template_->info_type, p, &p);
5478 switch (mini_rgctx_info_type_to_patch_info_type (template_->info_type)) {
5479 case MONO_PATCH_INFO_CLASS:
5480 encode_klass_ref (acfg, mono_class_from_mono_type ((MonoType *)template_->data), p, &p);
5482 case MONO_PATCH_INFO_FIELD:
5483 encode_field_info (acfg, (MonoClassField *)template_->data, p, &p);
5486 g_assert_not_reached ();
5492 case MONO_PATCH_INFO_LDSTR_LIT: {
5493 const char *s = (const char *)patch_info->data.target;
5494 int len = strlen (s);
5496 encode_value (len, p, &p);
5497 memcpy (p, s, len + 1);
5501 case MONO_PATCH_INFO_VIRT_METHOD:
5502 encode_klass_ref (acfg, patch_info->data.virt_method->klass, p, &p);
5503 encode_method_ref (acfg, patch_info->data.virt_method->method, p, &p);
5505 case MONO_PATCH_INFO_GC_SAFE_POINT_FLAG:
5508 g_warning ("unable to handle jump info %d", patch_info->type);
5509 g_assert_not_reached ();
5516 encode_patch_list (MonoAotCompile *acfg, GPtrArray *patches, int n_patches, gboolean llvm, int first_got_offset, guint8 *buf, guint8 **endbuf)
5519 guint32 pindex, offset;
5520 MonoJumpInfo *patch_info;
5522 encode_value (n_patches, p, &p);
5524 for (pindex = 0; pindex < patches->len; ++pindex) {
5525 patch_info = (MonoJumpInfo *)g_ptr_array_index (patches, pindex);
5527 if (patch_info->type == MONO_PATCH_INFO_NONE || patch_info->type == MONO_PATCH_INFO_BB)
5531 offset = get_got_offset (acfg, llvm, patch_info);
5532 encode_value (offset, p, &p);
5539 emit_method_info (MonoAotCompile *acfg, MonoCompile *cfg)
5542 int pindex, buf_size, n_patches;
5544 MonoJumpInfo *patch_info;
5545 guint32 method_index;
5547 guint32 first_got_offset;
5549 method = cfg->orig_method;
5551 method_index = get_method_index (acfg, method);
5553 /* Sort relocations */
5554 patches = g_ptr_array_new ();
5555 for (patch_info = cfg->patch_info; patch_info; patch_info = patch_info->next)
5556 g_ptr_array_add (patches, patch_info);
5557 g_ptr_array_sort (patches, compare_patches);
5559 first_got_offset = acfg->cfgs [method_index]->got_offset;
5561 /**********************/
5562 /* Encode method info */
5563 /**********************/
5565 buf_size = (patches->len < 1000) ? 40960 : 40960 + (patches->len * 64);
5566 p = buf = (guint8 *)g_malloc (buf_size);
5568 if (mono_class_get_cctor (method->klass))
5569 encode_klass_ref (acfg, method->klass, p, &p);
5571 /* Not needed when loading the method */
5572 encode_value (0, p, &p);
5574 g_assert (!(cfg->opt & MONO_OPT_SHARED));
5577 for (pindex = 0; pindex < patches->len; ++pindex) {
5578 patch_info = (MonoJumpInfo *)g_ptr_array_index (patches, pindex);
5580 if ((patch_info->type == MONO_PATCH_INFO_GOT_OFFSET) ||
5581 (patch_info->type == MONO_PATCH_INFO_NONE)) {
5582 patch_info->type = MONO_PATCH_INFO_NONE;
5587 if ((patch_info->type == MONO_PATCH_INFO_IMAGE) && (patch_info->data.image == acfg->image)) {
5588 /* Stored in a GOT slot initialized at module load time */
5589 patch_info->type = MONO_PATCH_INFO_NONE;
5593 if (patch_info->type == MONO_PATCH_INFO_GC_CARD_TABLE_ADDR ||
5594 patch_info->type == MONO_PATCH_INFO_GC_NURSERY_START ||
5595 patch_info->type == MONO_PATCH_INFO_GC_NURSERY_BITS ||
5596 patch_info->type == MONO_PATCH_INFO_AOT_MODULE) {
5597 /* Stored in a GOT slot initialized at module load time */
5598 patch_info->type = MONO_PATCH_INFO_NONE;
5602 if (is_plt_patch (patch_info) && !(cfg->compile_llvm && acfg->aot_opts.llvm_only)) {
5603 /* Calls are made through the PLT */
5604 patch_info->type = MONO_PATCH_INFO_NONE;
5612 g_assert (cfg->has_got_slots);
5614 encode_patch_list (acfg, patches, n_patches, cfg->compile_llvm, first_got_offset, p, &p);
5616 acfg->stats.info_size += p - buf;
5618 g_assert (p - buf < buf_size);
5620 cfg->method_info_offset = add_to_blob (acfg, buf, p - buf);
5625 get_unwind_info_offset (MonoAotCompile *acfg, guint8 *encoded, guint32 encoded_len)
5627 guint32 cache_index;
5630 /* Reuse the unwind module to canonize and store unwind info entries */
5631 cache_index = mono_cache_unwind_info (encoded, encoded_len);
5633 /* Use +/- 1 to distinguish 0s from missing entries */
5634 offset = GPOINTER_TO_UINT (g_hash_table_lookup (acfg->unwind_info_offsets, GUINT_TO_POINTER (cache_index + 1)));
5642 * It would be easier to use assembler symbols, but the caller needs an
5645 offset = acfg->unwind_info_offset;
5646 g_hash_table_insert (acfg->unwind_info_offsets, GUINT_TO_POINTER (cache_index + 1), GUINT_TO_POINTER (offset + 1));
5647 g_ptr_array_add (acfg->unwind_ops, GUINT_TO_POINTER (cache_index));
5650 encode_value (encoded_len, p, &p);
5652 acfg->unwind_info_offset += encoded_len + (p - buf);
5658 emit_exception_debug_info (MonoAotCompile *acfg, MonoCompile *cfg, gboolean store_seq_points)
5661 guint32 debug_info_size, seq_points_size;
5663 MonoMethodHeader *header;
5664 guint8 *p, *buf, *debug_info;
5665 MonoJitInfo *jinfo = cfg->jit_info;
5667 gboolean use_unwind_ops = FALSE;
5668 MonoSeqPointInfo *seq_points;
5670 code = cfg->native_code;
5671 header = cfg->header;
5673 if (!acfg->aot_opts.nodebug) {
5674 mono_debug_serialize_debug_info (cfg, &debug_info, &debug_info_size);
5677 debug_info_size = 0;
5680 seq_points = cfg->seq_point_info;
5681 seq_points_size = (store_seq_points)? mono_seq_point_info_get_write_size (seq_points) : 0;
5683 buf_size = header->num_clauses * 256 + debug_info_size + 2048 + seq_points_size + cfg->gc_map_size;
5685 p = buf = (guint8 *)g_malloc (buf_size);
5687 use_unwind_ops = cfg->unwind_ops != NULL;
5689 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);
5691 encode_value (flags, p, &p);
5693 if (use_unwind_ops) {
5694 guint32 encoded_len;
5696 guint32 unwind_desc;
5698 encoded = mono_unwind_ops_encode (cfg->unwind_ops, &encoded_len);
5700 unwind_desc = get_unwind_info_offset (acfg, encoded, encoded_len);
5701 encode_value (unwind_desc, p, &p);
5703 encode_value (jinfo->unwind_info, p, &p);
5706 /*Encode the number of holes before the number of clauses to make decoding easier*/
5707 if (jinfo->has_try_block_holes) {
5708 MonoTryBlockHoleTableJitInfo *table = mono_jit_info_get_try_block_hole_table_info (jinfo);
5709 encode_value (table->num_holes, p, &p);
5712 if (jinfo->has_arch_eh_info) {
5714 * In AOT mode, the code length is calculated from the address of the previous method,
5715 * which could include alignment padding, so calculating the start of the epilog as
5716 * code_len - epilog_size is correct any more. Save the real code len as a workaround.
5718 encode_value (jinfo->code_size, p, &p);
5721 /* Exception table */
5722 if (cfg->compile_llvm) {
5724 * When using LLVM, we can't emit some data, like pc offsets, this reg/offset etc.,
5725 * since the information is only available to llc. Instead, we let llc save the data
5726 * into the LSDA, and read it from there at runtime.
5728 /* The assembly might be CIL stripped so emit the data ourselves */
5729 if (header->num_clauses)
5730 encode_value (header->num_clauses, p, &p);
5732 for (k = 0; k < header->num_clauses; ++k) {
5733 MonoExceptionClause *clause;
5735 clause = &header->clauses [k];
5737 encode_value (clause->flags, p, &p);
5738 if (clause->data.catch_class) {
5739 encode_value (1, p, &p);
5740 encode_klass_ref (acfg, clause->data.catch_class, p, &p);
5742 encode_value (0, p, &p);
5745 /* Emit the IL ranges too, since they might not be available at runtime */
5746 encode_value (clause->try_offset, p, &p);
5747 encode_value (clause->try_len, p, &p);
5748 encode_value (clause->handler_offset, p, &p);
5749 encode_value (clause->handler_len, p, &p);
5751 /* Emit a list of nesting clauses */
5752 for (i = 0; i < header->num_clauses; ++i) {
5754 MonoExceptionClause *clause1 = &header->clauses [cindex1];
5756 MonoExceptionClause *clause2 = &header->clauses [cindex2];
5758 if (cindex1 != cindex2 && clause1->try_offset >= clause2->try_offset && clause1->handler_offset <= clause2->handler_offset)
5759 encode_value (i, p, &p);
5761 encode_value (-1, p, &p);
5764 if (jinfo->num_clauses)
5765 encode_value (jinfo->num_clauses, p, &p);
5767 for (k = 0; k < jinfo->num_clauses; ++k) {
5768 MonoJitExceptionInfo *ei = &jinfo->clauses [k];
5770 encode_value (ei->flags, p, &p);
5771 #ifdef MONO_CONTEXT_SET_LLVM_EXC_REG
5772 /* Not used for catch clauses */
5773 if (ei->flags != MONO_EXCEPTION_CLAUSE_NONE)
5774 encode_value (ei->exvar_offset, p, &p);
5776 encode_value (ei->exvar_offset, p, &p);
5779 if (ei->flags == MONO_EXCEPTION_CLAUSE_FILTER || ei->flags == MONO_EXCEPTION_CLAUSE_FINALLY)
5780 encode_value ((gint)((guint8*)ei->data.filter - code), p, &p);
5782 if (ei->data.catch_class) {
5786 buf2 = (guint8 *)g_malloc (4096);
5788 encode_klass_ref (acfg, ei->data.catch_class, p2, &p2);
5790 g_assert (len < 4096);
5791 encode_value (len, p, &p);
5792 memcpy (p, buf2, len);
5796 encode_value (0, p, &p);
5800 encode_value ((gint)((guint8*)ei->try_start - code), p, &p);
5801 encode_value ((gint)((guint8*)ei->try_end - code), p, &p);
5802 encode_value ((gint)((guint8*)ei->handler_start - code), p, &p);
5806 if (jinfo->has_try_block_holes) {
5807 MonoTryBlockHoleTableJitInfo *table = mono_jit_info_get_try_block_hole_table_info (jinfo);
5808 for (i = 0; i < table->num_holes; ++i) {
5809 MonoTryBlockHoleJitInfo *hole = &table->holes [i];
5810 encode_value (hole->clause, p, &p);
5811 encode_value (hole->length, p, &p);
5812 encode_value (hole->offset, p, &p);
5816 if (jinfo->has_arch_eh_info) {
5817 MonoArchEHJitInfo *eh_info;
5819 eh_info = mono_jit_info_get_arch_eh_info (jinfo);
5820 encode_value (eh_info->stack_size, p, &p);
5821 encode_value (eh_info->epilog_size, p, &p);
5824 if (jinfo->has_generic_jit_info) {
5825 MonoGenericJitInfo *gi = mono_jit_info_get_generic_jit_info (jinfo);
5826 MonoGenericSharingContext* gsctx = gi->generic_sharing_context;
5830 encode_value (gi->nlocs, p, &p);
5832 for (i = 0; i < gi->nlocs; ++i) {
5833 MonoDwarfLocListEntry *entry = &gi->locations [i];
5835 encode_value (entry->is_reg ? 1 : 0, p, &p);
5836 encode_value (entry->reg, p, &p);
5838 encode_value (entry->offset, p, &p);
5840 g_assert (entry->from == 0);
5842 encode_value (entry->from, p, &p);
5843 encode_value (entry->to, p, &p);
5846 if (!cfg->compile_llvm) {
5847 encode_value (gi->has_this ? 1 : 0, p, &p);
5848 encode_value (gi->this_reg, p, &p);
5849 encode_value (gi->this_offset, p, &p);
5854 * Need to encode jinfo->method too, since it is not equal to 'method'
5855 * when using generic sharing.
5857 buf2 = (guint8 *)g_malloc (4096);
5859 encode_method_ref (acfg, jinfo->d.method, p2, &p2);
5861 g_assert (len < 4096);
5862 encode_value (len, p, &p);
5863 memcpy (p, buf2, len);
5867 if (gsctx && gsctx->is_gsharedvt) {
5868 encode_value (1, p, &p);
5870 encode_value (0, p, &p);
5874 if (seq_points_size)
5875 p += mono_seq_point_info_write (seq_points, p);
5877 g_assert (debug_info_size < buf_size);
5879 encode_value (debug_info_size, p, &p);
5880 if (debug_info_size) {
5881 memcpy (p, debug_info, debug_info_size);
5882 p += debug_info_size;
5883 g_free (debug_info);
5888 encode_value (cfg->gc_map_size, p, &p);
5889 /* The GC map requires 4 bytes of alignment */
5890 while ((gsize)p % 4)
5892 memcpy (p, cfg->gc_map, cfg->gc_map_size);
5893 p += cfg->gc_map_size;
5896 acfg->stats.ex_info_size += p - buf;
5898 g_assert (p - buf < buf_size);
5901 /* The GC Map requires 4 byte alignment */
5902 cfg->ex_info_offset = add_to_blob_aligned (acfg, buf, p - buf, cfg->gc_map ? 4 : 1);
5907 emit_klass_info (MonoAotCompile *acfg, guint32 token)
5910 MonoClass *klass = mono_class_get_checked (acfg->image, token, &error);
5912 int i, buf_size, res;
5913 gboolean no_special_static, cant_encode;
5914 gpointer iter = NULL;
5917 mono_error_cleanup (&error);
5921 p = buf = (guint8 *)g_malloc (buf_size);
5923 /* Mark as unusable */
5924 encode_value (-1, p, &p);
5926 res = add_to_blob (acfg, buf, p - buf);
5932 buf_size = 10240 + (klass->vtable_size * 16);
5933 p = buf = (guint8 *)g_malloc (buf_size);
5937 mono_class_init (klass);
5939 mono_class_get_nested_types (klass, &iter);
5940 g_assert (klass->nested_classes_inited);
5942 mono_class_setup_vtable (klass);
5945 * Emit all the information which is required for creating vtables so
5946 * the runtime does not need to create the MonoMethod structures which
5947 * take up a lot of space.
5950 no_special_static = !mono_class_has_special_static_fields (klass);
5952 /* Check whenever we have enough info to encode the vtable */
5953 cant_encode = FALSE;
5954 for (i = 0; i < klass->vtable_size; ++i) {
5955 MonoMethod *cm = klass->vtable [i];
5957 if (cm && mono_method_signature (cm)->is_inflated && !g_hash_table_lookup (acfg->token_info_hash, cm))
5961 mono_class_has_finalizer (klass);
5963 if (klass->generic_container || cant_encode) {
5964 encode_value (-1, p, &p);
5966 encode_value (klass->vtable_size, p, &p);
5967 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);
5968 if (klass->has_cctor)
5969 encode_method_ref (acfg, mono_class_get_cctor (klass), p, &p);
5970 if (klass->has_finalize)
5971 encode_method_ref (acfg, mono_class_get_finalizer (klass), p, &p);
5973 encode_value (klass->instance_size, p, &p);
5974 encode_value (mono_class_data_size (klass), p, &p);
5975 encode_value (klass->packing_size, p, &p);
5976 encode_value (klass->min_align, p, &p);
5978 for (i = 0; i < klass->vtable_size; ++i) {
5979 MonoMethod *cm = klass->vtable [i];
5982 encode_method_ref (acfg, cm, p, &p);
5984 encode_value (0, p, &p);
5988 acfg->stats.class_info_size += p - buf;
5990 g_assert (p - buf < buf_size);
5991 res = add_to_blob (acfg, buf, p - buf);
5998 get_plt_entry_debug_sym (MonoAotCompile *acfg, MonoJumpInfo *ji, GHashTable *cache)
6000 char *debug_sym = NULL;
6003 if (acfg->llvm && llvm_acfg->aot_opts.static_link) {
6004 /* Need to add a prefix to create unique symbols */
6005 prefix = g_strdup_printf ("plt_%s_", acfg->assembly_name_sym);
6007 prefix = g_strdup ("plt_");
6011 case MONO_PATCH_INFO_METHOD:
6012 debug_sym = get_debug_sym (ji->data.method, prefix, cache);
6014 case MONO_PATCH_INFO_INTERNAL_METHOD:
6015 debug_sym = g_strdup_printf ("%s_jit_icall_%s", prefix, ji->data.name);
6017 case MONO_PATCH_INFO_RGCTX_FETCH:
6018 debug_sym = g_strdup_printf ("%s_rgctx_fetch_%d", prefix, acfg->label_generator ++);
6020 case MONO_PATCH_INFO_ICALL_ADDR: {
6021 char *s = get_debug_sym (ji->data.method, "", cache);
6023 debug_sym = g_strdup_printf ("%s_icall_native_%s", prefix, s);
6027 case MONO_PATCH_INFO_JIT_ICALL_ADDR:
6028 debug_sym = g_strdup_printf ("%s_jit_icall_native_%s", prefix, ji->data.name);
6036 return sanitize_symbol (acfg, debug_sym);
6040 * Calls made from AOTed code are routed through a table of jumps similar to the
6041 * ELF PLT (Program Linkage Table). Initially the PLT entries jump to code which transfers
6042 * control to the AOT runtime through a trampoline.
6045 emit_plt (MonoAotCompile *acfg)
6049 if (acfg->aot_opts.llvm_only) {
6050 g_assert (acfg->plt_offset == 1);
6056 emit_section_change (acfg, ".text", 0);
6057 emit_alignment_code (acfg, NACL_SIZE(16, kNaClAlignment));
6058 emit_info_symbol (acfg, "plt");
6059 emit_label (acfg, acfg->plt_symbol);
6061 for (i = 0; i < acfg->plt_offset; ++i) {
6062 char *debug_sym = NULL;
6063 MonoPltEntry *plt_entry = NULL;
6067 * The first plt entry is unused.
6071 plt_entry = (MonoPltEntry *)g_hash_table_lookup (acfg->plt_offset_to_entry, GUINT_TO_POINTER (i));
6073 debug_sym = plt_entry->debug_sym;
6075 if (acfg->thumb_mixed && !plt_entry->jit_used)
6076 /* Emit only a thumb version */
6079 /* Skip plt entries not actually called */
6080 if (!plt_entry->jit_used && !plt_entry->llvm_used)
6083 if (acfg->llvm && !acfg->thumb_mixed) {
6084 emit_label (acfg, plt_entry->llvm_symbol);
6086 emit_global_inner (acfg, plt_entry->llvm_symbol, TRUE);
6087 #if defined(TARGET_MACH)
6088 fprintf (acfg->fp, ".private_extern %s\n", plt_entry->llvm_symbol);
6094 if (acfg->need_no_dead_strip) {
6095 emit_unset_mode (acfg);
6096 fprintf (acfg->fp, " .no_dead_strip %s\n", debug_sym);
6098 emit_local_symbol (acfg, debug_sym, NULL, TRUE);
6099 emit_label (acfg, debug_sym);
6102 emit_label (acfg, plt_entry->symbol);
6104 arch_emit_plt_entry (acfg, acfg->got_symbol, (acfg->plt_got_offset_base + i) * sizeof (gpointer), acfg->plt_got_info_offsets [i]);
6107 emit_symbol_size (acfg, debug_sym, ".");
6110 if (acfg->thumb_mixed) {
6111 /* Make sure the ARM symbols don't alias the thumb ones */
6112 emit_zero_bytes (acfg, 16);
6115 * Emit a separate set of PLT entries using thumb2 which is called by LLVM generated
6118 for (i = 0; i < acfg->plt_offset; ++i) {
6119 char *debug_sym = NULL;
6120 MonoPltEntry *plt_entry = NULL;
6125 plt_entry = (MonoPltEntry *)g_hash_table_lookup (acfg->plt_offset_to_entry, GUINT_TO_POINTER (i));
6127 /* Skip plt entries not actually called by LLVM code */
6128 if (!plt_entry->llvm_used)
6131 if (acfg->aot_opts.write_symbols) {
6132 if (plt_entry->debug_sym)
6133 debug_sym = g_strdup_printf ("%s_thumb", plt_entry->debug_sym);
6137 #if defined(TARGET_MACH)
6138 fprintf (acfg->fp, " .thumb_func %s\n", debug_sym);
6139 fprintf (acfg->fp, " .no_dead_strip %s\n", debug_sym);
6141 emit_local_symbol (acfg, debug_sym, NULL, TRUE);
6142 emit_label (acfg, debug_sym);
6144 fprintf (acfg->fp, "\n.thumb_func\n");
6146 emit_label (acfg, plt_entry->llvm_symbol);
6149 emit_global_inner (acfg, plt_entry->llvm_symbol, TRUE);
6151 arch_emit_llvm_plt_entry (acfg, acfg->got_symbol, (acfg->plt_got_offset_base + i) * sizeof (gpointer), acfg->plt_got_info_offsets [i]);
6154 emit_symbol_size (acfg, debug_sym, ".");
6160 emit_symbol_size (acfg, acfg->plt_symbol, ".");
6162 emit_info_symbol (acfg, "plt_end");
6166 * emit_trampoline_full:
6168 * If EMIT_TINFO is TRUE, emit additional information which can be used to create a MonoJitInfo for this trampoline by
6169 * create_jit_info_for_trampoline ().
6171 static G_GNUC_UNUSED void
6172 emit_trampoline_full (MonoAotCompile *acfg, int got_offset, MonoTrampInfo *info, gboolean emit_tinfo)
6174 char start_symbol [256];
6175 char end_symbol [256];
6177 guint32 buf_size, info_offset;
6178 MonoJumpInfo *patch_info;
6191 code_size = info->code_size;
6193 unwind_ops = info->unwind_ops;
6195 #ifdef __native_client_codegen__
6196 mono_nacl_fix_patches (code, ji);
6201 sprintf (start_symbol, "%s%s", acfg->user_symbol_prefix, name);
6203 emit_section_change (acfg, ".text", 0);
6204 emit_global (acfg, start_symbol, TRUE);
6205 emit_alignment_code (acfg, AOT_FUNC_ALIGNMENT);
6206 emit_label (acfg, start_symbol);
6208 sprintf (symbol, "%snamed_%s", acfg->temp_prefix, name);
6209 emit_label (acfg, symbol);
6212 * The code should access everything through the GOT, so we pass
6215 emit_and_reloc_code (acfg, NULL, code, code_size, ji, TRUE, NULL);
6217 emit_symbol_size (acfg, start_symbol, ".");
6220 sprintf (end_symbol, "%snamede_%s", acfg->temp_prefix, name);
6221 emit_label (acfg, end_symbol);
6226 /* Sort relocations */
6227 patches = g_ptr_array_new ();
6228 for (patch_info = ji; patch_info; patch_info = patch_info->next)
6229 if (patch_info->type != MONO_PATCH_INFO_NONE)
6230 g_ptr_array_add (patches, patch_info);
6231 g_ptr_array_sort (patches, compare_patches);
6233 buf_size = patches->len * 128 + 128;
6234 buf = (guint8 *)g_malloc (buf_size);
6237 encode_patch_list (acfg, patches, patches->len, FALSE, got_offset, p, &p);
6238 g_assert (p - buf < buf_size);
6240 sprintf (symbol, "%s%s_p", acfg->user_symbol_prefix, name);
6242 info_offset = add_to_blob (acfg, buf, p - buf);
6244 emit_section_change (acfg, RODATA_SECT, 0);
6245 emit_global (acfg, symbol, FALSE);
6246 emit_label (acfg, symbol);
6248 emit_int32 (acfg, info_offset);
6252 guint32 encoded_len;
6256 * Emit additional information which can be used to reconstruct a partial MonoTrampInfo.
6258 encoded = mono_unwind_ops_encode (info->unwind_ops, &encoded_len);
6259 uw_offset = get_unwind_info_offset (acfg, encoded, encoded_len);
6262 emit_symbol_diff (acfg, end_symbol, start_symbol, 0);
6263 emit_int32 (acfg, uw_offset);
6266 /* Emit debug info */
6270 sprintf (symbol, "%s", name);
6271 sprintf (symbol2, "%snamed_%s", acfg->temp_prefix, name);
6274 mono_dwarf_writer_emit_trampoline (acfg->dwarf, symbol, symbol2, NULL, NULL, code_size, unwind_ops);
6278 static G_GNUC_UNUSED void
6279 emit_trampoline (MonoAotCompile *acfg, int got_offset, MonoTrampInfo *info)
6281 emit_trampoline_full (acfg, got_offset, info, TRUE);
6285 emit_trampolines (MonoAotCompile *acfg)
6288 char end_symbol [256];
6289 int i, tramp_got_offset;
6291 #ifdef MONO_ARCH_HAVE_FULL_AOT_TRAMPOLINES
6295 if (!mono_aot_mode_is_full (&acfg->aot_opts) || acfg->aot_opts.llvm_only)
6298 g_assert (acfg->image->assembly);
6300 /* Currently, we emit most trampolines into the mscorlib AOT image. */
6301 if (strcmp (acfg->image->assembly->aname.name, "mscorlib") == 0) {
6302 #ifdef MONO_ARCH_HAVE_FULL_AOT_TRAMPOLINES
6303 MonoTrampInfo *info;
6306 * Emit the generic trampolines.
6308 * We could save some code by treating the generic trampolines as a wrapper
6309 * method, but that approach has its own complexities, so we choose the simpler
6312 for (tramp_type = 0; tramp_type < MONO_TRAMPOLINE_NUM; ++tramp_type) {
6313 /* we overload the boolean here to indicate the slightly different trampoline needed, see mono_arch_create_generic_trampoline() */
6314 #ifdef DISABLE_REMOTING
6315 if (tramp_type == MONO_TRAMPOLINE_GENERIC_VIRTUAL_REMOTING)
6318 #ifndef MONO_ARCH_HAVE_HANDLER_BLOCK_GUARD
6319 if (tramp_type == MONO_TRAMPOLINE_HANDLER_BLOCK_GUARD)
6322 mono_arch_create_generic_trampoline ((MonoTrampolineType)tramp_type, &info, acfg->aot_opts.use_trampolines_page? 2: TRUE);
6323 emit_trampoline (acfg, acfg->got_offset, info);
6326 /* Emit the exception related code pieces */
6327 mono_arch_get_restore_context (&info, TRUE);
6328 emit_trampoline (acfg, acfg->got_offset, info);
6329 mono_arch_get_call_filter (&info, TRUE);
6330 emit_trampoline (acfg, acfg->got_offset, info);
6331 mono_arch_get_throw_exception (&info, TRUE);
6332 emit_trampoline (acfg, acfg->got_offset, info);
6333 mono_arch_get_rethrow_exception (&info, TRUE);
6334 emit_trampoline (acfg, acfg->got_offset, info);
6335 mono_arch_get_throw_corlib_exception (&info, TRUE);
6336 emit_trampoline (acfg, acfg->got_offset, info);
6338 #ifdef MONO_ARCH_HAVE_SDB_TRAMPOLINES
6339 mono_arch_create_sdb_trampoline (TRUE, &info, TRUE);
6340 emit_trampoline (acfg, acfg->got_offset, info);
6341 mono_arch_create_sdb_trampoline (FALSE, &info, TRUE);
6342 emit_trampoline (acfg, acfg->got_offset, info);
6345 #ifdef MONO_ARCH_GSHAREDVT_SUPPORTED
6346 mono_arch_get_gsharedvt_trampoline (&info, TRUE);
6348 emit_trampoline_full (acfg, acfg->got_offset, info, TRUE);
6350 /* Create a separate out trampoline for more information in stack traces */
6351 info->name = g_strdup ("gsharedvt_out_trampoline");
6352 emit_trampoline_full (acfg, acfg->got_offset, info, TRUE);
6356 #if defined(MONO_ARCH_HAVE_GET_TRAMPOLINES)
6358 GSList *l = mono_arch_get_trampolines (TRUE);
6361 MonoTrampInfo *info = (MonoTrampInfo *)l->data;
6363 emit_trampoline (acfg, acfg->got_offset, info);
6369 for (i = 0; i < acfg->aot_opts.nrgctx_fetch_trampolines; ++i) {
6372 offset = MONO_RGCTX_SLOT_MAKE_RGCTX (i);
6373 mono_arch_create_rgctx_lazy_fetch_trampoline (offset, &info, TRUE);
6374 emit_trampoline (acfg, acfg->got_offset, info);
6376 offset = MONO_RGCTX_SLOT_MAKE_MRGCTX (i);
6377 mono_arch_create_rgctx_lazy_fetch_trampoline (offset, &info, TRUE);
6378 emit_trampoline (acfg, acfg->got_offset, info);
6381 #ifdef MONO_ARCH_HAVE_GENERAL_RGCTX_LAZY_FETCH_TRAMPOLINE
6382 mono_arch_create_general_rgctx_lazy_fetch_trampoline (&info, TRUE);
6383 emit_trampoline (acfg, acfg->got_offset, info);
6389 /* delegate_invoke_impl trampolines */
6390 l = mono_arch_get_delegate_invoke_impls ();
6392 MonoTrampInfo *info = (MonoTrampInfo *)l->data;
6394 emit_trampoline (acfg, acfg->got_offset, info);
6399 #endif /* #ifdef MONO_ARCH_HAVE_FULL_AOT_TRAMPOLINES */
6401 /* Emit trampolines which are numerous */
6404 * These include the following:
6405 * - specific trampolines
6406 * - static rgctx invoke trampolines
6408 * These trampolines have the same code, they are parameterized by GOT
6410 * They are defined in this file, in the arch_... routines instead of
6411 * in tramp-<ARCH>.c, since it is easier to do it this way.
6415 * When running in aot-only mode, we can't create specific trampolines at
6416 * runtime, so we create a few, and save them in the AOT file.
6417 * Normal trampolines embed their argument as a literal inside the
6418 * trampoline code, we can't do that here, so instead we embed an offset
6419 * which needs to be added to the trampoline address to get the address of
6420 * the GOT slot which contains the argument value.
6421 * The generated trampolines jump to the generic trampolines using another
6422 * GOT slot, which will be setup by the AOT loader to point to the
6423 * generic trampoline code of the given type.
6427 * FIXME: Maybe we should use more specific trampolines (i.e. one class init for
6431 emit_section_change (acfg, ".text", 0);
6433 tramp_got_offset = acfg->got_offset;
6435 for (ntype = 0; ntype < MONO_AOT_TRAMP_NUM; ++ntype) {
6437 case MONO_AOT_TRAMP_SPECIFIC:
6438 sprintf (symbol, "specific_trampolines");
6440 case MONO_AOT_TRAMP_STATIC_RGCTX:
6441 sprintf (symbol, "static_rgctx_trampolines");
6443 case MONO_AOT_TRAMP_IMT_THUNK:
6444 sprintf (symbol, "imt_thunks");
6446 case MONO_AOT_TRAMP_GSHAREDVT_ARG:
6447 sprintf (symbol, "gsharedvt_arg_trampolines");
6450 g_assert_not_reached ();
6453 sprintf (end_symbol, "%s_e", symbol);
6455 if (acfg->aot_opts.write_symbols)
6456 emit_local_symbol (acfg, symbol, end_symbol, TRUE);
6458 emit_alignment_code (acfg, AOT_FUNC_ALIGNMENT);
6459 emit_info_symbol (acfg, symbol);
6461 acfg->trampoline_got_offset_base [ntype] = tramp_got_offset;
6463 for (i = 0; i < acfg->num_trampolines [ntype]; ++i) {
6467 case MONO_AOT_TRAMP_SPECIFIC:
6468 arch_emit_specific_trampoline (acfg, tramp_got_offset, &tramp_size);
6469 tramp_got_offset += 2;
6471 case MONO_AOT_TRAMP_STATIC_RGCTX:
6472 arch_emit_static_rgctx_trampoline (acfg, tramp_got_offset, &tramp_size);
6473 tramp_got_offset += 2;
6475 case MONO_AOT_TRAMP_IMT_THUNK:
6476 arch_emit_imt_thunk (acfg, tramp_got_offset, &tramp_size);
6477 tramp_got_offset += 1;
6479 case MONO_AOT_TRAMP_GSHAREDVT_ARG:
6480 arch_emit_gsharedvt_arg_trampoline (acfg, tramp_got_offset, &tramp_size);
6481 tramp_got_offset += 2;
6484 g_assert_not_reached ();
6486 #ifdef __native_client_codegen__
6487 /* align to avoid 32-byte boundary crossings */
6488 emit_alignment (acfg, AOT_FUNC_ALIGNMENT);
6491 if (!acfg->trampoline_size [ntype]) {
6492 g_assert (tramp_size);
6493 acfg->trampoline_size [ntype] = tramp_size;
6497 emit_label (acfg, end_symbol);
6498 emit_int32 (acfg, 0);
6501 arch_emit_specific_trampoline_pages (acfg);
6503 /* Reserve some entries at the end of the GOT for our use */
6504 acfg->num_trampoline_got_entries = tramp_got_offset - acfg->got_offset;
6507 acfg->got_offset += acfg->num_trampoline_got_entries;
6511 str_begins_with (const char *str1, const char *str2)
6513 int len = strlen (str2);
6514 return strncmp (str1, str2, len) == 0;
6518 mono_aot_readonly_field_override (MonoClassField *field)
6521 for (rdv = readonly_values; rdv; rdv = rdv->next) {
6522 char *p = rdv->name;
6524 len = strlen (field->parent->name_space);
6525 if (strncmp (p, field->parent->name_space, len))
6530 len = strlen (field->parent->name);
6531 if (strncmp (p, field->parent->name, len))
6536 if (strcmp (p, field->name))
6538 switch (rdv->type) {
6540 return &rdv->value.i1;
6542 return &rdv->value.i2;
6544 return &rdv->value.i4;
6553 add_readonly_value (MonoAotOptions *opts, const char *val)
6558 /* the format of val is:
6559 * namespace.typename.fieldname=type/value
6560 * type can be i1 for uint8/int8/boolean, i2 for uint16/int16/char, i4 for uint32/int32
6562 fval = strrchr (val, '/');
6564 fprintf (stderr, "AOT : invalid format for readonly field '%s', missing /.\n", val);
6567 tval = strrchr (val, '=');
6569 fprintf (stderr, "AOT : invalid format for readonly field '%s', missing =.\n", val);
6572 rdv = g_new0 (ReadOnlyValue, 1);
6573 rdv->name = (char *)g_malloc0 (tval - val + 1);
6574 memcpy (rdv->name, val, tval - val);
6577 if (strncmp (tval, "i1", 2) == 0) {
6578 rdv->value.i1 = atoi (fval);
6579 rdv->type = MONO_TYPE_I1;
6580 } else if (strncmp (tval, "i2", 2) == 0) {
6581 rdv->value.i2 = atoi (fval);
6582 rdv->type = MONO_TYPE_I2;
6583 } else if (strncmp (tval, "i4", 2) == 0) {
6584 rdv->value.i4 = atoi (fval);
6585 rdv->type = MONO_TYPE_I4;
6587 fprintf (stderr, "AOT : unsupported type for readonly field '%s'.\n", tval);
6590 rdv->next = readonly_values;
6591 readonly_values = rdv;
6595 clean_path (gchar * path)
6600 if (g_str_has_suffix (path, G_DIR_SEPARATOR_S))
6603 gchar *clean = g_strconcat (path, G_DIR_SEPARATOR_S, NULL);
6610 wrap_path (gchar * path)
6616 // If the string contains no spaces, just return the original string.
6617 if (strstr (path, " ") == NULL)
6620 // If the string is already wrapped in quotes, return it.
6621 len = strlen (path);
6622 if (len >= 2 && path[0] == '\"' && path[len-1] == '\"')
6625 // If the string contains spaces, then wrap it in quotes.
6626 gchar *clean = g_strdup_printf ("\"%s\"", path);
6632 mono_aot_split_options (const char *aot_options)
6634 enum MonoAotOptionState {
6635 MONO_AOT_OPTION_STATE_DEFAULT,
6636 MONO_AOT_OPTION_STATE_STRING,
6637 MONO_AOT_OPTION_STATE_ESCAPE,
6640 GPtrArray *args = g_ptr_array_new ();
6641 enum MonoAotOptionState state = MONO_AOT_OPTION_STATE_DEFAULT;
6642 gchar const *opt_start = aot_options;
6643 gboolean end_of_string = FALSE;
6646 g_return_val_if_fail (aot_options != NULL, NULL);
6648 while ((cur = *aot_options) != '\0') {
6649 if (state == MONO_AOT_OPTION_STATE_ESCAPE)
6654 // If we find a quote, then if we're in the default case then
6655 // it means we've found the start of a string, if not then it
6656 // means we've found the end of the string and should switch
6657 // back to the default case.
6659 case MONO_AOT_OPTION_STATE_DEFAULT:
6660 state = MONO_AOT_OPTION_STATE_STRING;
6662 case MONO_AOT_OPTION_STATE_STRING:
6663 state = MONO_AOT_OPTION_STATE_DEFAULT;
6665 case MONO_AOT_OPTION_STATE_ESCAPE:
6666 g_assert_not_reached ();
6671 // If we've found an escaping operator, then this means we
6672 // should not process the next character if inside a string.
6673 if (state == MONO_AOT_OPTION_STATE_STRING)
6674 state = MONO_AOT_OPTION_STATE_ESCAPE;
6677 // If we're in the default state then this means we've found
6678 // an option, store it for later processing.
6679 if (state == MONO_AOT_OPTION_STATE_DEFAULT)
6686 // If the next character is end of string, then process the last option.
6687 if (*(aot_options) == '\0') {
6688 end_of_string = TRUE;
6694 g_ptr_array_add (args, g_strndup (opt_start, aot_options - opt_start));
6695 opt_start = ++aot_options;
6705 mono_aot_parse_options (const char *aot_options, MonoAotOptions *opts)
6709 args = mono_aot_split_options (aot_options ? aot_options : "");
6710 for (int i = 0; i < args->len; ++i) {
6711 const char *arg = (const char *)g_ptr_array_index (args, i);
6713 if (str_begins_with (arg, "outfile=")) {
6714 opts->outfile = g_strdup (arg + strlen ("outfile="));
6715 } else if (str_begins_with (arg, "llvm-outfile=")) {
6716 opts->llvm_outfile = g_strdup (arg + strlen ("llvm-outfile="));
6717 } else if (str_begins_with (arg, "temp-path=")) {
6718 opts->temp_path = clean_path (g_strdup (arg + strlen ("temp-path=")));
6719 } else if (str_begins_with (arg, "save-temps")) {
6720 opts->save_temps = TRUE;
6721 } else if (str_begins_with (arg, "keep-temps")) {
6722 opts->save_temps = TRUE;
6723 } else if (str_begins_with (arg, "write-symbols")) {
6724 opts->write_symbols = TRUE;
6725 } else if (str_begins_with (arg, "no-write-symbols")) {
6726 opts->write_symbols = FALSE;
6727 } else if (str_begins_with (arg, "metadata-only")) {
6728 opts->metadata_only = TRUE;
6729 } else if (str_begins_with (arg, "bind-to-runtime-version")) {
6730 opts->bind_to_runtime_version = TRUE;
6731 } else if (str_begins_with (arg, "full")) {
6732 opts->mode = MONO_AOT_MODE_FULL;
6733 } else if (str_begins_with (arg, "hybrid")) {
6734 opts->mode = MONO_AOT_MODE_HYBRID;
6735 } else if (str_begins_with (arg, "threads=")) {
6736 opts->nthreads = atoi (arg + strlen ("threads="));
6737 } else if (str_begins_with (arg, "static")) {
6738 opts->static_link = TRUE;
6739 opts->no_dlsym = TRUE;
6740 } else if (str_begins_with (arg, "asmonly")) {
6741 opts->asm_only = TRUE;
6742 } else if (str_begins_with (arg, "asmwriter")) {
6743 opts->asm_writer = TRUE;
6744 } else if (str_begins_with (arg, "nodebug")) {
6745 opts->nodebug = TRUE;
6746 } else if (str_begins_with (arg, "dwarfdebug")) {
6747 opts->dwarf_debug = TRUE;
6748 } else if (str_begins_with (arg, "nopagetrampolines")) {
6749 opts->use_trampolines_page = FALSE;
6750 } else if (str_begins_with (arg, "ntrampolines=")) {
6751 opts->ntrampolines = atoi (arg + strlen ("ntrampolines="));
6752 } else if (str_begins_with (arg, "nrgctx-trampolines=")) {
6753 opts->nrgctx_trampolines = atoi (arg + strlen ("nrgctx-trampolines="));
6754 } else if (str_begins_with (arg, "nimt-trampolines=")) {
6755 opts->nimt_trampolines = atoi (arg + strlen ("nimt-trampolines="));
6756 } else if (str_begins_with (arg, "ngsharedvt-trampolines=")) {
6757 opts->ngsharedvt_arg_trampolines = atoi (arg + strlen ("ngsharedvt-trampolines="));
6758 } else if (str_begins_with (arg, "tool-prefix=")) {
6759 opts->tool_prefix = g_strdup (arg + strlen ("tool-prefix="));
6760 } else if (str_begins_with (arg, "ld-flags=")) {
6761 opts->ld_flags = g_strdup (arg + strlen ("ld-flags="));
6762 } else if (str_begins_with (arg, "soft-debug")) {
6763 opts->soft_debug = TRUE;
6764 } else if (str_begins_with (arg, "gen-seq-points-file=")) {
6765 debug_options.gen_seq_points_compact_data = TRUE;
6766 opts->gen_seq_points_file = TRUE;
6767 opts->gen_seq_points_file_path = g_strdup (arg + strlen ("gen-seq-points-file="));;
6768 } else if (str_begins_with (arg, "gen-seq-points-file")) {
6769 debug_options.gen_seq_points_compact_data = TRUE;
6770 opts->gen_seq_points_file = TRUE;
6771 } else if (str_begins_with (arg, "direct-pinvoke")) {
6772 opts->direct_pinvoke = TRUE;
6773 } else if (str_begins_with (arg, "direct-icalls")) {
6774 opts->direct_icalls = TRUE;
6775 } else if (str_begins_with (arg, "no-direct-calls")) {
6776 opts->no_direct_calls = TRUE;
6777 } else if (str_begins_with (arg, "print-skipped")) {
6778 opts->print_skipped_methods = TRUE;
6779 } else if (str_begins_with (arg, "stats")) {
6781 } else if (str_begins_with (arg, "no-instances")) {
6782 opts->no_instances = TRUE;
6783 } else if (str_begins_with (arg, "log-generics")) {
6784 opts->log_generics = TRUE;
6785 } else if (str_begins_with (arg, "log-instances=")) {
6786 opts->log_instances = TRUE;
6787 opts->instances_logfile_path = g_strdup (arg + strlen ("log-instances="));
6788 } else if (str_begins_with (arg, "log-instances")) {
6789 opts->log_instances = TRUE;
6790 } else if (str_begins_with (arg, "internal-logfile=")) {
6791 opts->logfile = g_strdup (arg + strlen ("internal-logfile="));
6792 } else if (str_begins_with (arg, "mtriple=")) {
6793 opts->mtriple = g_strdup (arg + strlen ("mtriple="));
6794 } else if (str_begins_with (arg, "llvm-path=")) {
6795 opts->llvm_path = clean_path (g_strdup (arg + strlen ("llvm-path=")));
6796 } else if (!strcmp (arg, "llvm")) {
6798 } else if (str_begins_with (arg, "readonly-value=")) {
6799 add_readonly_value (opts, arg + strlen ("readonly-value="));
6800 } else if (str_begins_with (arg, "info")) {
6801 printf ("AOT target setup: %s.\n", AOT_TARGET_STR);
6803 } else if (str_begins_with (arg, "gc-maps")) {
6804 mini_gc_enable_gc_maps_for_aot ();
6805 } else if (str_begins_with (arg, "dump")) {
6806 opts->dump_json = TRUE;
6807 } else if (str_begins_with (arg, "llvmonly")) {
6808 opts->mode = MONO_AOT_MODE_FULL;
6810 opts->llvm_only = TRUE;
6811 } else if (str_begins_with (arg, "data-outfile=")) {
6812 opts->data_outfile = g_strdup (arg + strlen ("data-outfile="));
6813 } else if (str_begins_with (arg, "help") || str_begins_with (arg, "?")) {
6814 printf ("Supported options for --aot:\n");
6815 printf (" outfile=\n");
6816 printf (" llvm-outfile=\n");
6817 printf (" llvm-path=\n");
6818 printf (" temp-path=\n");
6819 printf (" save-temps\n");
6820 printf (" keep-temps\n");
6821 printf (" write-symbols\n");
6822 printf (" metadata-only\n");
6823 printf (" bind-to-runtime-version\n");
6825 printf (" threads=\n");
6826 printf (" static\n");
6827 printf (" asmonly\n");
6828 printf (" asmwriter\n");
6829 printf (" nodebug\n");
6830 printf (" dwarfdebug\n");
6831 printf (" ntrampolines=\n");
6832 printf (" nrgctx-trampolines=\n");
6833 printf (" nimt-trampolines=\n");
6834 printf (" ngsharedvt-trampolines=\n");
6835 printf (" tool-prefix=\n");
6836 printf (" readonly-value=\n");
6837 printf (" soft-debug\n");
6838 printf (" gen-seq-points-file\n");
6839 printf (" gc-maps\n");
6840 printf (" print-skipped\n");
6841 printf (" no-instances\n");
6842 printf (" stats\n");
6845 printf (" help/?\n");
6848 fprintf (stderr, "AOT : Unknown argument '%s'.\n", arg);
6852 g_free ((gpointer) arg);
6855 if (opts->use_trampolines_page) {
6856 opts->ntrampolines = 0;
6857 opts->nrgctx_trampolines = 0;
6858 opts->nimt_trampolines = 0;
6859 opts->ngsharedvt_arg_trampolines = 0;
6862 g_ptr_array_free (args, /*free_seg=*/TRUE);
6866 add_token_info_hash (gpointer key, gpointer value, gpointer user_data)
6868 MonoMethod *method = (MonoMethod*)key;
6869 MonoJumpInfoToken *ji = (MonoJumpInfoToken*)value;
6870 MonoAotCompile *acfg = (MonoAotCompile *)user_data;
6871 MonoJumpInfoToken *new_ji;
6873 new_ji = (MonoJumpInfoToken *)mono_mempool_alloc0 (acfg->mempool, sizeof (MonoJumpInfoToken));
6874 new_ji->image = ji->image;
6875 new_ji->token = ji->token;
6876 g_hash_table_insert (acfg->token_info_hash, method, new_ji);
6880 can_encode_class (MonoAotCompile *acfg, MonoClass *klass)
6882 if (klass->type_token)
6884 if ((klass->byval_arg.type == MONO_TYPE_VAR) || (klass->byval_arg.type == MONO_TYPE_MVAR) || (klass->byval_arg.type == MONO_TYPE_PTR))
6887 return can_encode_class (acfg, klass->element_class);
6892 can_encode_method (MonoAotCompile *acfg, MonoMethod *method)
6894 if (method->wrapper_type) {
6895 switch (method->wrapper_type) {
6896 case MONO_WRAPPER_NONE:
6897 case MONO_WRAPPER_REMOTING_INVOKE_WITH_CHECK:
6898 case MONO_WRAPPER_XDOMAIN_INVOKE:
6899 case MONO_WRAPPER_STFLD:
6900 case MONO_WRAPPER_LDFLD:
6901 case MONO_WRAPPER_LDFLDA:
6902 case MONO_WRAPPER_LDFLD_REMOTE:
6903 case MONO_WRAPPER_STFLD_REMOTE:
6904 case MONO_WRAPPER_STELEMREF:
6905 case MONO_WRAPPER_ISINST:
6906 case MONO_WRAPPER_PROXY_ISINST:
6907 case MONO_WRAPPER_ALLOC:
6908 case MONO_WRAPPER_REMOTING_INVOKE:
6909 case MONO_WRAPPER_UNKNOWN:
6910 case MONO_WRAPPER_WRITE_BARRIER:
6911 case MONO_WRAPPER_DELEGATE_INVOKE:
6912 case MONO_WRAPPER_DELEGATE_BEGIN_INVOKE:
6913 case MONO_WRAPPER_DELEGATE_END_INVOKE:
6914 case MONO_WRAPPER_SYNCHRONIZED:
6916 case MONO_WRAPPER_MANAGED_TO_MANAGED:
6917 case MONO_WRAPPER_CASTCLASS: {
6918 WrapperInfo *info = mono_marshal_get_wrapper_info (method);
6927 //printf ("Skip (wrapper call): %d -> %s\n", patch_info->type, mono_method_full_name (patch_info->data.method, TRUE));
6931 if (!method->token) {
6932 /* The method is part of a constructed type like Int[,].Set (). */
6933 if (!g_hash_table_lookup (acfg->token_info_hash, method)) {
6934 if (method->klass->rank)
6944 can_encode_patch (MonoAotCompile *acfg, MonoJumpInfo *patch_info)
6946 switch (patch_info->type) {
6947 case MONO_PATCH_INFO_METHOD:
6948 case MONO_PATCH_INFO_METHODCONST:
6949 case MONO_PATCH_INFO_METHOD_CODE_SLOT: {
6950 MonoMethod *method = patch_info->data.method;
6952 return can_encode_method (acfg, method);
6954 case MONO_PATCH_INFO_VTABLE:
6955 case MONO_PATCH_INFO_CLASS:
6956 case MONO_PATCH_INFO_IID:
6957 case MONO_PATCH_INFO_ADJUSTED_IID:
6958 if (!can_encode_class (acfg, patch_info->data.klass)) {
6959 //printf ("Skip: %s\n", mono_type_full_name (&patch_info->data.klass->byval_arg));
6963 case MONO_PATCH_INFO_DELEGATE_TRAMPOLINE: {
6964 if (!can_encode_class (acfg, patch_info->data.del_tramp->klass)) {
6965 //printf ("Skip: %s\n", mono_type_full_name (&patch_info->data.klass->byval_arg));
6970 case MONO_PATCH_INFO_RGCTX_FETCH:
6971 case MONO_PATCH_INFO_RGCTX_SLOT_INDEX: {
6972 MonoJumpInfoRgctxEntry *entry = patch_info->data.rgctx_entry;
6974 if (!can_encode_method (acfg, entry->method))
6976 if (!can_encode_patch (acfg, entry->data))
6988 is_concrete_type (MonoType *t)
6993 if (t->type == MONO_TYPE_VAR || t->type == MONO_TYPE_MVAR)
6995 if (t->type == MONO_TYPE_GENERICINST) {
6996 MonoGenericContext *orig_ctx;
6997 MonoGenericInst *inst;
7000 if (!MONO_TYPE_ISSTRUCT (t))
7002 klass = mono_class_from_mono_type (t);
7003 orig_ctx = &klass->generic_class->context;
7005 inst = orig_ctx->class_inst;
7007 for (i = 0; i < inst->type_argc; ++i) {
7008 arg = mini_get_underlying_type (inst->type_argv [i]);
7009 if (!is_concrete_type (arg))
7013 inst = orig_ctx->method_inst;
7015 for (i = 0; i < inst->type_argc; ++i) {
7016 arg = mini_get_underlying_type (inst->type_argv [i]);
7017 if (!is_concrete_type (arg))
7025 /* LOCKING: Assumes the loader lock is held */
7027 add_gsharedvt_wrappers (MonoAotCompile *acfg, MonoMethodSignature *sig, gboolean gsharedvt_in, gboolean gsharedvt_out)
7029 MonoMethod *wrapper;
7030 gboolean concrete = TRUE;
7031 gboolean add_in = gsharedvt_in;
7032 gboolean add_out = gsharedvt_out;
7034 if (gsharedvt_in && g_hash_table_lookup (acfg->gsharedvt_in_signatures, sig))
7036 if (gsharedvt_out && g_hash_table_lookup (acfg->gsharedvt_out_signatures, sig))
7039 if (!add_in && !add_out)
7042 if (mini_is_gsharedvt_variable_signature (sig))
7046 g_hash_table_insert (acfg->gsharedvt_in_signatures, sig, sig);
7048 g_hash_table_insert (acfg->gsharedvt_out_signatures, sig, sig);
7050 if (!sig->has_type_parameters) {
7051 //printf ("%s\n", mono_signature_full_name (sig));
7054 wrapper = mini_get_gsharedvt_in_sig_wrapper (sig);
7055 add_extra_method (acfg, wrapper);
7057 if (gsharedvt_out) {
7058 wrapper = mini_get_gsharedvt_out_sig_wrapper (sig);
7059 add_extra_method (acfg, wrapper);
7062 /* For signatures creared during generic sharing, convert them to a concrete signature if possible */
7063 MonoMethodSignature *copy = mono_metadata_signature_dup (sig);
7066 //printf ("%s\n", mono_signature_full_name (sig));
7068 copy->ret = mini_get_underlying_type (sig->ret);
7069 if (!is_concrete_type (copy->ret))
7071 for (i = 0; i < sig->param_count; ++i) {
7072 copy->params [i] = mini_get_underlying_type (sig->params [i]);
7073 if (!is_concrete_type (copy->params [i]))
7077 copy->has_type_parameters = 0;
7080 wrapper = mini_get_gsharedvt_in_sig_wrapper (copy);
7081 add_extra_method (acfg, wrapper);
7084 if (gsharedvt_out) {
7085 wrapper = mini_get_gsharedvt_out_sig_wrapper (copy);
7086 add_extra_method (acfg, wrapper);
7089 //printf ("%s\n", mono_method_full_name (wrapper, 1));
7097 * AOT compile a given method.
7098 * This function might be called by multiple threads, so it must be thread-safe.
7101 compile_method (MonoAotCompile *acfg, MonoMethod *method)
7104 MonoJumpInfo *patch_info;
7107 MonoMethod *wrapped;
7111 if (acfg->aot_opts.metadata_only)
7114 mono_acfg_lock (acfg);
7115 index = get_method_index (acfg, method);
7116 mono_acfg_unlock (acfg);
7118 /* fixme: maybe we can also precompile wrapper methods */
7119 if ((method->flags & METHOD_ATTRIBUTE_PINVOKE_IMPL) ||
7120 (method->iflags & METHOD_IMPL_ATTRIBUTE_RUNTIME) ||
7121 (method->flags & METHOD_ATTRIBUTE_ABSTRACT)) {
7122 //printf ("Skip (impossible): %s\n", mono_method_full_name (method, TRUE));
7126 if (method->iflags & METHOD_IMPL_ATTRIBUTE_INTERNAL_CALL)
7129 wrapped = mono_marshal_method_from_wrapper (method);
7130 if (wrapped && (wrapped->iflags & METHOD_IMPL_ATTRIBUTE_INTERNAL_CALL) && wrapped->is_generic)
7131 // FIXME: The wrapper should be generic too, but it is not
7134 if (method->wrapper_type == MONO_WRAPPER_COMINTEROP)
7137 InterlockedIncrement (&acfg->stats.mcount);
7140 if (method->is_generic || method->klass->generic_container) {
7141 InterlockedIncrement (&acfg->stats.genericcount);
7146 //acfg->aot_opts.print_skipped_methods = TRUE;
7149 * Since these methods are the only ones which are compiled with
7150 * AOT support, and they are not used by runtime startup/shutdown code,
7151 * the runtime will not see AOT methods during AOT compilation,so it
7152 * does not need to support them by creating a fake GOT etc.
7154 flags = JIT_FLAG_AOT;
7155 if (mono_aot_mode_is_full (&acfg->aot_opts))
7156 flags = (JitFlags)(flags | JIT_FLAG_FULL_AOT);
7158 flags = (JitFlags)(flags | JIT_FLAG_LLVM);
7159 if (acfg->aot_opts.llvm_only)
7160 flags = (JitFlags)(flags | JIT_FLAG_LLVM_ONLY | JIT_FLAG_EXPLICIT_NULL_CHECKS);
7161 if (acfg->aot_opts.no_direct_calls)
7162 flags = (JitFlags)(flags | JIT_FLAG_NO_DIRECT_ICALLS);
7164 jit_timer = mono_time_track_start ();
7165 cfg = mini_method_compile (method, acfg->opts, mono_get_root_domain (), flags, 0, index);
7166 mono_time_track_end (&mono_jit_stats.jit_time, jit_timer);
7168 mono_loader_clear_error ();
7170 if (cfg->exception_type == MONO_EXCEPTION_GENERIC_SHARING_FAILED) {
7171 if (acfg->aot_opts.print_skipped_methods)
7172 printf ("Skip (gshared failure): %s (%s)\n", mono_method_get_full_name (method), cfg->exception_message);
7173 InterlockedIncrement (&acfg->stats.genericcount);
7176 if (cfg->exception_type != MONO_EXCEPTION_NONE) {
7177 if (acfg->aot_opts.print_skipped_methods)
7178 printf ("Skip (JIT failure): %s\n", mono_method_get_full_name (method));
7179 /* Let the exception happen at runtime */
7183 if (cfg->disable_aot) {
7184 if (acfg->aot_opts.print_skipped_methods)
7185 printf ("Skip (disabled): %s\n", mono_method_get_full_name (method));
7186 InterlockedIncrement (&acfg->stats.ocount);
7187 mono_destroy_compile (cfg);
7190 cfg->method_index = index;
7192 /* Nullify patches which need no aot processing */
7193 for (patch_info = cfg->patch_info; patch_info; patch_info = patch_info->next) {
7194 switch (patch_info->type) {
7195 case MONO_PATCH_INFO_LABEL:
7196 case MONO_PATCH_INFO_BB:
7197 patch_info->type = MONO_PATCH_INFO_NONE;
7204 /* Collect method->token associations from the cfg */
7205 mono_acfg_lock (acfg);
7206 g_hash_table_foreach (cfg->token_info_hash, add_token_info_hash, acfg);
7207 mono_acfg_unlock (acfg);
7208 g_hash_table_destroy (cfg->token_info_hash);
7209 cfg->token_info_hash = NULL;
7212 * Check for absolute addresses.
7215 for (patch_info = cfg->patch_info; patch_info; patch_info = patch_info->next) {
7216 switch (patch_info->type) {
7217 case MONO_PATCH_INFO_ABS:
7218 /* unable to handle this */
7227 if (acfg->aot_opts.print_skipped_methods)
7228 printf ("Skip (abs call): %s\n", mono_method_get_full_name (method));
7229 InterlockedIncrement (&acfg->stats.abscount);
7230 mono_destroy_compile (cfg);
7234 /* Lock for the rest of the code */
7235 mono_acfg_lock (acfg);
7238 acfg->stats.method_categories [METHOD_CAT_GSHAREDVT] ++;
7239 else if (cfg->gshared)
7240 acfg->stats.method_categories [METHOD_CAT_INST] ++;
7241 else if (cfg->method->wrapper_type)
7242 acfg->stats.method_categories [METHOD_CAT_WRAPPER] ++;
7244 acfg->stats.method_categories [METHOD_CAT_NORMAL] ++;
7247 * Check for methods/klasses we can't encode.
7250 for (patch_info = cfg->patch_info; patch_info; patch_info = patch_info->next) {
7251 if (!can_encode_patch (acfg, patch_info))
7256 if (acfg->aot_opts.print_skipped_methods)
7257 printf ("Skip (patches): %s\n", mono_method_get_full_name (method));
7258 acfg->stats.ocount++;
7259 mono_destroy_compile (cfg);
7260 mono_acfg_unlock (acfg);
7264 if (!cfg->compile_llvm)
7265 acfg->has_jitted_code = TRUE;
7267 if (method->is_inflated && acfg->aot_opts.log_instances) {
7268 if (acfg->instances_logfile)
7269 fprintf (acfg->instances_logfile, "%s ### %d\n", mono_method_get_full_name (method), cfg->code_size);
7271 printf ("%s ### %d\n", mono_method_get_full_name (method), cfg->code_size);
7274 /* Adds generic instances referenced by this method */
7276 * The depth is used to avoid infinite loops when generic virtual recursion is
7279 depth = GPOINTER_TO_UINT (g_hash_table_lookup (acfg->method_depth, method));
7280 if (!acfg->aot_opts.no_instances && depth < 32) {
7281 for (patch_info = cfg->patch_info; patch_info; patch_info = patch_info->next) {
7282 switch (patch_info->type) {
7283 case MONO_PATCH_INFO_RGCTX_FETCH:
7284 case MONO_PATCH_INFO_RGCTX_SLOT_INDEX:
7285 case MONO_PATCH_INFO_METHOD: {
7286 MonoMethod *m = NULL;
7288 if (patch_info->type == MONO_PATCH_INFO_RGCTX_FETCH || patch_info->type == MONO_PATCH_INFO_RGCTX_SLOT_INDEX) {
7289 MonoJumpInfoRgctxEntry *e = patch_info->data.rgctx_entry;
7291 if (e->info_type == MONO_RGCTX_INFO_GENERIC_METHOD_CODE)
7292 m = e->data->data.method;
7294 m = patch_info->data.method;
7299 if (m->is_inflated) {
7300 if (!(mono_class_generic_sharing_enabled (m->klass) &&
7301 mono_method_is_generic_sharable_full (m, FALSE, FALSE, FALSE)) &&
7302 (!method_has_type_vars (m) || mono_method_is_generic_sharable_full (m, TRUE, TRUE, FALSE))) {
7303 if (m->iflags & METHOD_IMPL_ATTRIBUTE_INTERNAL_CALL) {
7304 if (mono_aot_mode_is_full (&acfg->aot_opts) && !method_has_type_vars (m))
7305 add_extra_method_with_depth (acfg, mono_marshal_get_native_wrapper (m, TRUE, TRUE), depth + 1);
7307 add_extra_method_with_depth (acfg, m, depth + 1);
7308 add_types_from_method_header (acfg, m);
7311 add_generic_class_with_depth (acfg, m->klass, depth + 5, "method");
7313 if (m->wrapper_type == MONO_WRAPPER_MANAGED_TO_MANAGED) {
7314 WrapperInfo *info = mono_marshal_get_wrapper_info (m);
7316 if (info && info->subtype == WRAPPER_SUBTYPE_ELEMENT_ADDR)
7317 add_extra_method_with_depth (acfg, m, depth + 1);
7321 case MONO_PATCH_INFO_VTABLE: {
7322 MonoClass *klass = patch_info->data.klass;
7324 if (klass->generic_class && !mini_class_is_generic_sharable (klass))
7325 add_generic_class_with_depth (acfg, klass, depth + 5, "vtable");
7328 case MONO_PATCH_INFO_SFLDA: {
7329 MonoClass *klass = patch_info->data.field->parent;
7331 /* The .cctor needs to run at runtime. */
7332 if (klass->generic_class && !mono_generic_context_is_sharable (&klass->generic_class->context, FALSE) && mono_class_get_cctor (klass))
7333 add_extra_method_with_depth (acfg, mono_class_get_cctor (klass), depth + 1);
7342 /* Determine whenever the method has GOT slots */
7343 for (patch_info = cfg->patch_info; patch_info; patch_info = patch_info->next) {
7344 switch (patch_info->type) {
7345 case MONO_PATCH_INFO_GOT_OFFSET:
7346 case MONO_PATCH_INFO_NONE:
7347 case MONO_PATCH_INFO_GC_CARD_TABLE_ADDR:
7348 case MONO_PATCH_INFO_GC_NURSERY_START:
7349 case MONO_PATCH_INFO_GC_NURSERY_BITS:
7351 case MONO_PATCH_INFO_IMAGE:
7352 /* The assembly is stored in GOT slot 0 */
7353 if (patch_info->data.image != acfg->image)
7354 cfg->has_got_slots = TRUE;
7357 if (!is_plt_patch (patch_info) || (cfg->compile_llvm && acfg->aot_opts.llvm_only))
7358 cfg->has_got_slots = TRUE;
7363 if (!cfg->has_got_slots)
7364 InterlockedIncrement (&acfg->stats.methods_without_got_slots);
7366 /* Add gsharedvt wrappers for signatures used by the method */
7367 if (acfg->aot_opts.llvm_only) {
7370 if (!cfg->method->wrapper_type || cfg->method->wrapper_type == MONO_WRAPPER_DELEGATE_INVOKE)
7371 /* These only need out wrappers */
7372 add_gsharedvt_wrappers (acfg, mono_method_signature (cfg->method), FALSE, TRUE);
7374 for (l = cfg->signatures; l; l = l->next) {
7375 MonoMethodSignature *sig = mono_metadata_signature_dup ((MonoMethodSignature*)l->data);
7377 /* These only need in wrappers */
7378 add_gsharedvt_wrappers (acfg, sig, TRUE, FALSE);
7383 * FIXME: Instead of this mess, allocate the patches from the aot mempool.
7385 /* Make a copy of the patch info which is in the mempool */
7387 MonoJumpInfo *patches = NULL, *patches_end = NULL;
7389 for (patch_info = cfg->patch_info; patch_info; patch_info = patch_info->next) {
7390 MonoJumpInfo *new_patch_info = mono_patch_info_dup_mp (acfg->mempool, patch_info);
7393 patches = new_patch_info;
7395 patches_end->next = new_patch_info;
7396 patches_end = new_patch_info;
7398 cfg->patch_info = patches;
7400 /* Make a copy of the unwind info */
7402 GSList *l, *unwind_ops;
7406 for (l = cfg->unwind_ops; l; l = l->next) {
7407 op = (MonoUnwindOp *)mono_mempool_alloc (acfg->mempool, sizeof (MonoUnwindOp));
7408 memcpy (op, l->data, sizeof (MonoUnwindOp));
7409 unwind_ops = g_slist_prepend_mempool (acfg->mempool, unwind_ops, op);
7411 cfg->unwind_ops = g_slist_reverse (unwind_ops);
7413 /* Make a copy of the argument/local info */
7415 MonoInst **args, **locals;
7416 MonoMethodSignature *sig;
7417 MonoMethodHeader *header;
7420 sig = mono_method_signature (method);
7421 args = (MonoInst **)mono_mempool_alloc (acfg->mempool, sizeof (MonoInst*) * (sig->param_count + sig->hasthis));
7422 for (i = 0; i < sig->param_count + sig->hasthis; ++i) {
7423 args [i] = (MonoInst *)mono_mempool_alloc (acfg->mempool, sizeof (MonoInst));
7424 memcpy (args [i], cfg->args [i], sizeof (MonoInst));
7428 header = mono_method_get_header (method);
7429 locals = (MonoInst **)mono_mempool_alloc (acfg->mempool, sizeof (MonoInst*) * header->num_locals);
7430 for (i = 0; i < header->num_locals; ++i) {
7431 locals [i] = (MonoInst *)mono_mempool_alloc (acfg->mempool, sizeof (MonoInst));
7432 memcpy (locals [i], cfg->locals [i], sizeof (MonoInst));
7434 cfg->locals = locals;
7437 /* Free some fields used by cfg to conserve memory */
7438 mono_mempool_destroy (cfg->mempool);
7439 cfg->mempool = NULL;
7440 g_free (cfg->varinfo);
7441 cfg->varinfo = NULL;
7445 mono_regstate_free (cfg->rs);
7449 //printf ("Compile: %s\n", mono_method_full_name (method, TRUE));
7451 while (index >= acfg->cfgs_size) {
7452 MonoCompile **new_cfgs;
7455 new_size = acfg->cfgs_size * 2;
7456 new_cfgs = g_new0 (MonoCompile*, new_size);
7457 memcpy (new_cfgs, acfg->cfgs, sizeof (MonoCompile*) * acfg->cfgs_size);
7458 g_free (acfg->cfgs);
7459 acfg->cfgs = new_cfgs;
7460 acfg->cfgs_size = new_size;
7462 acfg->cfgs [index] = cfg;
7464 g_hash_table_insert (acfg->method_to_cfg, cfg->orig_method, cfg);
7466 mono_update_jit_stats (cfg);
7469 if (cfg->orig_method->wrapper_type)
7470 g_ptr_array_add (acfg->extra_methods, cfg->orig_method);
7473 mono_acfg_unlock (acfg);
7475 InterlockedIncrement (&acfg->stats.ccount);
7479 compile_thread_main (gpointer *user_data)
7481 MonoDomain *domain = (MonoDomain *)user_data [0];
7482 MonoAotCompile *acfg = (MonoAotCompile *)user_data [1];
7483 GPtrArray *methods = (GPtrArray *)user_data [2];
7486 mono_thread_attach (domain);
7488 for (i = 0; i < methods->len; ++i)
7489 compile_method (acfg, (MonoMethod *)g_ptr_array_index (methods, i));
7493 load_profile_files (MonoAotCompile *acfg)
7497 int file_index, res, method_index, i;
7500 GList *unordered, *l;
7505 tmp = g_strdup_printf ("%s/.mono/aot-profile-data/%s-%d", g_get_home_dir (), acfg->image->assembly_name, file_index);
7507 if (!g_file_test (tmp, G_FILE_TEST_IS_REGULAR)) {
7512 infile = fopen (tmp, "r");
7515 printf ("Using profile data file '%s'\n", tmp);
7520 res = fscanf (infile, "%32s\n", ver);
7521 if ((res != 1) || strcmp (ver, "#VER:2") != 0) {
7522 printf ("Profile file has wrong version or invalid.\n");
7529 MonoMethodDesc *desc;
7532 if (fgets (name, 1023, infile) == NULL)
7535 /* Kill the newline */
7536 if (strlen (name) > 0)
7537 name [strlen (name) - 1] = '\0';
7539 desc = mono_method_desc_new (name, TRUE);
7541 method = mono_method_desc_search_in_image (desc, acfg->image);
7543 if (method && mono_method_get_token (method)) {
7544 token = mono_method_get_token (method);
7545 method_index = mono_metadata_token_index (token) - 1;
7548 for (i = 0; i < acfg->method_order->len; ++i) {
7549 if (g_ptr_array_index (acfg->method_order, i) == GUINT_TO_POINTER (method_index)) {
7555 g_ptr_array_add (acfg->method_order, GUINT_TO_POINTER (method_index));
7557 //printf ("No method found matching '%s'.\n", name);
7563 /* Add missing methods */
7565 for (method_index = 0; method_index < acfg->image->tables [MONO_TABLE_METHOD].rows; ++method_index) {
7567 for (i = 0; i < acfg->method_order->len; ++i) {
7568 if (g_ptr_array_index (acfg->method_order, i) == GUINT_TO_POINTER (method_index)) {
7574 unordered = g_list_prepend (unordered, GUINT_TO_POINTER (method_index));
7576 unordered = g_list_reverse (unordered);
7577 for (l = unordered; l; l = l->next)
7578 g_ptr_array_add (acfg->method_order, l->data);
7581 /* Used by the LLVM backend */
7583 mono_aot_get_got_offset (MonoJumpInfo *ji)
7585 return get_got_offset (llvm_acfg, TRUE, ji);
7589 * mono_aot_is_shared_got_offset:
7591 * Return whenever OFFSET refers to a GOT slot which is preinitialized
7592 * when the AOT image is loaded.
7595 mono_aot_is_shared_got_offset (int offset)
7597 return offset < llvm_acfg->nshared_got_entries;
7601 mono_aot_get_method_name (MonoCompile *cfg)
7603 if (llvm_acfg->aot_opts.static_link)
7604 /* Include the assembly name too to avoid duplicate symbol errors */
7605 return g_strdup_printf ("%s_%s", llvm_acfg->assembly_name_sym, get_debug_sym (cfg->orig_method, "", llvm_acfg->method_label_hash));
7607 return get_debug_sym (cfg->orig_method, "", llvm_acfg->method_label_hash);
7611 * mono_aot_is_linkonce_method:
7613 * Return whenever METHOD should be emitted with linkonce linkage,
7614 * eliminating duplicate copies when compiling in static mode.
7617 mono_aot_is_linkonce_method (MonoMethod *method)
7621 // FIXME: Add more cases
7622 if (method->wrapper_type != MONO_WRAPPER_UNKNOWN)
7624 info = mono_marshal_get_wrapper_info (method);
7625 if ((info && (info->subtype == WRAPPER_SUBTYPE_GSHAREDVT_IN_SIG || info->subtype == WRAPPER_SUBTYPE_GSHAREDVT_OUT_SIG)))
7631 append_mangled_type (GString *s, MonoType *t)
7634 g_string_append_printf (s, "b");
7636 case MONO_TYPE_VOID:
7637 g_string_append_printf (s, "void_");
7640 g_string_append_printf (s, "i1");
7643 g_string_append_printf (s, "u1");
7646 g_string_append_printf (s, "i2");
7649 g_string_append_printf (s, "u2");
7652 g_string_append_printf (s, "i4");
7655 g_string_append_printf (s, "u4");
7658 g_string_append_printf (s, "i8");
7661 g_string_append_printf (s, "u8");
7664 g_string_append_printf (s, "ii");
7667 g_string_append_printf (s, "ui");
7670 g_string_append_printf (s, "fl");
7673 g_string_append_printf (s, "do");
7676 char *fullname = mono_type_full_name (t);
7682 * Have to create a mangled name which is:
7686 temp = g_string_new ("");
7687 len = strlen (fullname);
7688 for (i = 0; i < len; ++i) {
7689 char c = fullname [i];
7691 g_string_append_c (temp, c);
7692 } else if (c == '_') {
7693 g_string_append_c (temp, '_');
7694 g_string_append_c (temp, '_');
7696 g_string_append_c (temp, '_');
7697 g_string_append_printf (temp, "%x", (int)c);
7700 temps = g_string_free (temp, FALSE);
7701 /* Include the length to avoid different length type names aliasing each other */
7702 g_string_append_printf (s, "cl%x_%s_", strlen (temps), temps);
7711 append_mangled_signature (GString *s, MonoMethodSignature *sig)
7716 supported = append_mangled_type (s, sig->ret);
7720 g_string_append_printf (s, "this_");
7721 for (i = 0; i < sig->param_count; ++i) {
7722 supported = append_mangled_type (s, sig->params [i]);
7731 * mono_aot_get_mangled_method_name:
7733 * Return a unique mangled name for METHOD, or NULL.
7736 mono_aot_get_mangled_method_name (MonoMethod *method)
7742 // FIXME: Add more cases
7743 if (method->wrapper_type != MONO_WRAPPER_UNKNOWN)
7745 info = mono_marshal_get_wrapper_info (method);
7746 if (!(info && (info->subtype == WRAPPER_SUBTYPE_GSHAREDVT_IN_SIG || info->subtype == WRAPPER_SUBTYPE_GSHAREDVT_OUT_SIG)))
7749 s = g_string_new ("");
7751 g_string_append_printf (s, "aot_method_w_");
7753 switch (info->subtype) {
7754 case WRAPPER_SUBTYPE_GSHAREDVT_IN_SIG:
7755 g_string_append_printf (s, "gsharedvt_in_");
7757 case WRAPPER_SUBTYPE_GSHAREDVT_OUT_SIG:
7758 g_string_append_printf (s, "gsharedvt_out_");
7761 g_assert_not_reached ();
7765 supported = append_mangled_signature (s, info->d.gsharedvt.sig);
7767 g_string_free (s, TRUE);
7771 return g_string_free (s, FALSE);
7775 mono_aot_is_direct_callable (MonoJumpInfo *patch_info)
7777 return is_direct_callable (llvm_acfg, NULL, patch_info);
7781 mono_aot_mark_unused_llvm_plt_entry (MonoJumpInfo *patch_info)
7783 MonoPltEntry *plt_entry;
7785 plt_entry = get_plt_entry (llvm_acfg, patch_info);
7786 plt_entry->llvm_used = FALSE;
7790 mono_aot_get_direct_call_symbol (MonoJumpInfoType type, gconstpointer data)
7792 const char *sym = NULL;
7794 if (llvm_acfg->aot_opts.direct_icalls) {
7795 if (type == MONO_PATCH_INFO_JIT_ICALL_ADDR) {
7796 /* Call to a C function implementing a jit icall */
7797 sym = mono_lookup_jit_icall_symbol ((const char *)data);
7798 } else if (type == MONO_PATCH_INFO_ICALL_ADDR) {
7799 MonoMethod *method = (MonoMethod *)data;
7800 if (!(method->flags & METHOD_ATTRIBUTE_PINVOKE_IMPL))
7801 sym = mono_lookup_icall_symbol (method);
7802 else if (llvm_acfg->aot_opts.direct_pinvoke)
7803 sym = get_pinvoke_import (llvm_acfg, method);
7806 return g_strdup (sym);
7812 mono_aot_get_plt_symbol (MonoJumpInfoType type, gconstpointer data)
7814 MonoJumpInfo *ji = (MonoJumpInfo *)mono_mempool_alloc (llvm_acfg->mempool, sizeof (MonoJumpInfo));
7815 MonoPltEntry *plt_entry;
7816 const char *sym = NULL;
7819 ji->data.target = data;
7821 if (!can_encode_patch (llvm_acfg, ji))
7824 if (llvm_acfg->aot_opts.direct_icalls) {
7825 if (type == MONO_PATCH_INFO_JIT_ICALL_ADDR) {
7826 /* Call to a C function implementing a jit icall */
7827 sym = mono_lookup_jit_icall_symbol ((const char *)data);
7828 } else if (type == MONO_PATCH_INFO_ICALL_ADDR) {
7829 MonoMethod *method = (MonoMethod *)data;
7830 if (!(method->flags & METHOD_ATTRIBUTE_PINVOKE_IMPL))
7831 sym = mono_lookup_icall_symbol (method);
7834 return g_strdup (sym);
7837 plt_entry = get_plt_entry (llvm_acfg, ji);
7838 plt_entry->llvm_used = TRUE;
7840 #if defined(TARGET_MACH)
7841 return g_strdup_printf (plt_entry->llvm_symbol + strlen (llvm_acfg->llvm_label_prefix));
7843 return g_strdup_printf (plt_entry->llvm_symbol);
7848 mono_aot_get_method_index (MonoMethod *method)
7850 g_assert (llvm_acfg);
7851 return get_method_index (llvm_acfg, method);
7855 mono_aot_patch_info_dup (MonoJumpInfo* ji)
7859 mono_acfg_lock (llvm_acfg);
7860 res = mono_patch_info_dup_mp (llvm_acfg->mempool, ji);
7861 mono_acfg_unlock (llvm_acfg);
7867 execute_system (const char * command)
7872 // We need an extra set of quotes around the whole command to properly handle commands
7873 // with spaces since internally the command is called through "cmd /c.
7874 command = g_strdup_printf ("\"%s\"", command);
7876 int size = MultiByteToWideChar (CP_UTF8, 0 , command , -1, NULL , 0);
7877 wchar_t* wstr = g_malloc (sizeof (wchar_t) * size);
7878 MultiByteToWideChar (CP_UTF8, 0, command, -1, wstr , size);
7879 status = _wsystem (wstr);
7883 #elif defined (HAVE_SYSTEM)
7884 status = system (command);
7886 g_assert_not_reached ();
7897 * Emit the LLVM code into an LLVM bytecode file, and compile it using the LLVM
7901 emit_llvm_file (MonoAotCompile *acfg)
7903 char *command, *opts, *tempbc, *optbc, *output_fname;
7905 if (acfg->aot_opts.llvm_only && acfg->aot_opts.asm_only) {
7906 tempbc = g_strdup_printf ("%s.bc", acfg->tmpbasename);
7907 optbc = g_strdup (acfg->aot_opts.llvm_outfile);
7909 tempbc = g_strdup_printf ("%s.bc", acfg->tmpbasename);
7910 optbc = g_strdup_printf ("%s.opt.bc", acfg->tmpbasename);
7913 mono_llvm_emit_aot_module (tempbc, g_path_get_basename (acfg->image->name));
7916 * FIXME: Experiment with adding optimizations, the -std-compile-opts set takes
7917 * a lot of time, and doesn't seem to save much space.
7918 * The following optimizations cannot be enabled:
7920 * - 'jump-threading' changes our blockaddress references to int constants.
7921 * - 'basiccg' fails because it contains:
7922 * if (CS && !isa<IntrinsicInst>(II)) {
7923 * and isa<IntrinsicInst> is false for invokes to intrinsics (iltests.exe).
7924 * - 'prune-eh' and 'functionattrs' depend on 'basiccg'.
7925 * The opt list below was produced by taking the output of:
7926 * llvm-as < /dev/null | opt -O2 -disable-output -debug-pass=Arguments
7927 * then removing tailcallelim + the global opts.
7928 * strip-dead-prototypes deletes unused intrinsics definitions.
7930 /* The dse pass is disabled because of #13734 and #17616 */
7932 * The dse bug is in DeadStoreElimination.cpp:isOverwrite ():
7933 * // If we have no DataLayout information around, then the size of the store
7934 * // is inferrable from the pointee type. If they are the same type, then
7935 * // we know that the store is safe.
7936 * if (AA.getDataLayout() == 0 &&
7937 * Later.Ptr->getType() == Earlier.Ptr->getType()) {
7938 * return OverwriteComplete;
7939 * Here, if 'Earlier' refers to a memset, and Later has no size info, it mistakenly thinks the memset is redundant.
7941 if (acfg->aot_opts.llvm_only)
7942 // FIXME: This doesn't work yet
7943 opts = g_strdup ("");
7945 #if LLVM_API_VERSION > 100
7946 opts = g_strdup ("-O2");
7948 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");
7950 command = g_strdup_printf ("\"%sopt\" -f %s -o \"%s\" \"%s\"", acfg->aot_opts.llvm_path, opts, optbc, tempbc);
7951 aot_printf (acfg, "Executing opt: %s\n", command);
7952 if (execute_system (command) != 0)
7956 if (acfg->aot_opts.llvm_only && acfg->aot_opts.asm_only)
7957 /* Nothing else to do */
7960 if (acfg->aot_opts.llvm_only) {
7961 /* Use the stock clang from xcode */
7963 command = g_strdup_printf ("clang -march=x86-64 -fpic -msse -msse2 -msse3 -msse4 -O2 -fno-optimize-sibling-calls -Wno-override-module -c -o \"%s\" \"%s.opt.bc\"", acfg->llvm_ofile, acfg->tmpbasename);
7965 aot_printf (acfg, "Executing clang: %s\n", command);
7966 if (execute_system (command) != 0)
7971 if (!acfg->llc_args)
7972 acfg->llc_args = g_string_new ("");
7974 /* Verbose asm slows down llc greatly */
7975 g_string_append (acfg->llc_args, " -asm-verbose=false");
7977 if (acfg->aot_opts.mtriple)
7978 g_string_append_printf (acfg->llc_args, " -mtriple=%s", acfg->aot_opts.mtriple);
7980 g_string_append (acfg->llc_args, " -disable-gnu-eh-frame -enable-mono-eh-frame");
7982 g_string_append_printf (acfg->llc_args, " -mono-eh-frame-symbol=%s%s", acfg->user_symbol_prefix, acfg->llvm_eh_frame_symbol);
7984 #if LLVM_API_VERSION > 100
7985 g_string_append_printf (acfg->llc_args, " -disable-tail-calls");
7988 #if defined(TARGET_MACH) && defined(TARGET_ARM)
7989 /* ios requires PIC code now */
7990 g_string_append_printf (acfg->llc_args, " -relocation-model=pic");
7992 if (llvm_acfg->aot_opts.static_link)
7993 g_string_append_printf (acfg->llc_args, " -relocation-model=static");
7995 g_string_append_printf (acfg->llc_args, " -relocation-model=pic");
7998 if (acfg->llvm_owriter) {
7999 /* Emit an object file directly */
8000 output_fname = g_strdup_printf ("%s", acfg->llvm_ofile);
8001 g_string_append_printf (acfg->llc_args, " -filetype=obj");
8003 output_fname = g_strdup_printf ("%s", acfg->llvm_sfile);
8005 command = g_strdup_printf ("\"%sllc\" %s -o \"%s\" \"%s.opt.bc\"", acfg->aot_opts.llvm_path, acfg->llc_args->str, output_fname, acfg->tmpbasename);
8006 g_free (output_fname);
8008 aot_printf (acfg, "Executing llc: %s\n", command);
8010 if (execute_system (command) != 0)
8017 emit_code (MonoAotCompile *acfg)
8019 int oindex, i, prev_index;
8020 gboolean saved_unbox_info = FALSE;
8023 if (acfg->aot_opts.llvm_only)
8026 #if defined(TARGET_POWERPC64)
8027 sprintf (symbol, ".Lgot_addr");
8028 emit_section_change (acfg, ".text", 0);
8029 emit_alignment (acfg, 8);
8030 emit_label (acfg, symbol);
8031 emit_pointer (acfg, acfg->got_symbol);
8035 * This global symbol is used to compute the address of each method using the
8036 * code_offsets array. It is also used to compute the memory ranges occupied by
8037 * AOT code, so it must be equal to the address of the first emitted method.
8039 emit_section_change (acfg, ".text", 0);
8040 emit_alignment_code (acfg, 8);
8041 emit_info_symbol (acfg, "jit_code_start");
8044 * Emit some padding so the local symbol for the first method doesn't have the
8045 * same address as 'methods'.
8047 #if defined(__default_codegen__)
8048 emit_padding (acfg, 16);
8049 #elif defined(__native_client_codegen__)
8051 const int kPaddingSize = 16;
8052 guint8 pad_buffer[kPaddingSize];
8053 mono_arch_nacl_pad (pad_buffer, kPaddingSize);
8054 emit_bytes (acfg, pad_buffer, kPaddingSize);
8058 for (oindex = 0; oindex < acfg->method_order->len; ++oindex) {
8062 i = GPOINTER_TO_UINT (g_ptr_array_index (acfg->method_order, oindex));
8064 cfg = acfg->cfgs [i];
8069 method = cfg->orig_method;
8071 /* Emit unbox trampoline */
8072 if (mono_aot_mode_is_full (&acfg->aot_opts) && cfg->orig_method->klass->valuetype && !(acfg->aot_opts.llvm_only && cfg->compile_llvm)) {
8073 sprintf (symbol, "ut_%d", get_method_index (acfg, method));
8075 emit_section_change (acfg, ".text", 0);
8076 #ifdef __native_client_codegen__
8077 emit_alignment (acfg, AOT_FUNC_ALIGNMENT);
8080 if (acfg->thumb_mixed && cfg->compile_llvm) {
8081 emit_set_thumb_mode (acfg);
8082 fprintf (acfg->fp, "\n.thumb_func\n");
8085 emit_label (acfg, symbol);
8087 arch_emit_unbox_trampoline (acfg, cfg, cfg->orig_method, cfg->asm_symbol);
8089 if (acfg->thumb_mixed && cfg->compile_llvm)
8090 emit_set_arm_mode (acfg);
8092 if (!saved_unbox_info) {
8093 char user_symbol [128];
8095 sprintf (user_symbol, "%sunbox_trampoline_p", acfg->user_symbol_prefix);
8097 emit_label (acfg, "ut_end");
8099 unwind_ops = mono_unwind_get_cie_program ();
8100 save_unwind_info (acfg, user_symbol, unwind_ops);
8101 mono_free_unwind_info (unwind_ops);
8103 /* Save the unbox trampoline size */
8104 emit_symbol_diff (acfg, "ut_end", symbol, 0);
8106 saved_unbox_info = TRUE;
8110 if (cfg->compile_llvm)
8111 acfg->stats.llvm_count ++;
8113 emit_method_code (acfg, cfg);
8116 emit_section_change (acfg, ".text", 0);
8117 emit_alignment_code (acfg, 8);
8118 emit_info_symbol (acfg, "jit_code_end");
8120 /* To distinguish it from the next symbol */
8121 emit_padding (acfg, 4);
8124 * Add .no_dead_strip directives for all LLVM methods to prevent the OSX linker
8125 * from optimizing them away, since it doesn't see that code_offsets references them.
8126 * JITted methods don't need this since they are referenced using assembler local
8128 * FIXME: This is why write-symbols doesn't work on OSX ?
8130 if (acfg->llvm && acfg->need_no_dead_strip) {
8131 fprintf (acfg->fp, "\n");
8132 for (i = 0; i < acfg->nmethods; ++i) {
8133 if (acfg->cfgs [i] && acfg->cfgs [i]->compile_llvm)
8134 fprintf (acfg->fp, ".no_dead_strip %s\n", acfg->cfgs [i]->asm_symbol);
8139 * To work around linker issues, we emit a table of branches, and disassemble them at runtime.
8140 * This is PIE code, and the linker can update it if needed.
8142 sprintf (symbol, "method_addresses");
8143 emit_section_change (acfg, ".text", 1);
8144 emit_alignment_code (acfg, 8);
8145 emit_info_symbol (acfg, symbol);
8146 emit_local_symbol (acfg, symbol, "method_addresses_end", TRUE);
8147 emit_unset_mode (acfg);
8148 if (acfg->need_no_dead_strip)
8149 fprintf (acfg->fp, " .no_dead_strip %s\n", symbol);
8151 for (i = 0; i < acfg->nmethods; ++i) {
8152 #ifdef MONO_ARCH_AOT_SUPPORTED
8155 if (acfg->cfgs [i]) {
8156 if (acfg->aot_opts.llvm_only && acfg->cfgs [i]->compile_llvm)
8157 /* Obtained by calling a generated function in the LLVM image */
8158 arch_emit_direct_call (acfg, "method_addresses", FALSE, FALSE, NULL, &call_size);
8160 arch_emit_direct_call (acfg, acfg->cfgs [i]->asm_symbol, FALSE, acfg->thumb_mixed && acfg->cfgs [i]->compile_llvm, NULL, &call_size);
8162 arch_emit_direct_call (acfg, "method_addresses", FALSE, FALSE, NULL, &call_size);
8167 sprintf (symbol, "method_addresses_end");
8168 emit_label (acfg, symbol);
8171 /* Emit a sorted table mapping methods to the index of their unbox trampolines */
8172 sprintf (symbol, "unbox_trampolines");
8173 emit_section_change (acfg, RODATA_SECT, 0);
8174 emit_alignment (acfg, 8);
8175 emit_info_symbol (acfg, symbol);
8178 for (i = 0; i < acfg->nmethods; ++i) {
8183 cfg = acfg->cfgs [i];
8187 method = cfg->orig_method;
8189 if (mono_aot_mode_is_full (&acfg->aot_opts) && cfg->orig_method->klass->valuetype && !(acfg->aot_opts.llvm_only && cfg->compile_llvm)) {
8190 index = get_method_index (acfg, method);
8192 emit_int32 (acfg, index);
8193 /* Make sure the table is sorted by index */
8194 g_assert (index > prev_index);
8198 sprintf (symbol, "unbox_trampolines_end");
8199 emit_info_symbol (acfg, symbol);
8200 emit_int32 (acfg, 0);
8202 /* Emit a separate table with the trampoline addresses/offsets */
8203 sprintf (symbol, "unbox_trampoline_addresses");
8204 emit_section_change (acfg, ".text", 0);
8205 emit_alignment_code (acfg, 8);
8206 emit_info_symbol (acfg, symbol);
8208 for (i = 0; i < acfg->nmethods; ++i) {
8213 cfg = acfg->cfgs [i];
8217 method = cfg->orig_method;
8219 if (mono_aot_mode_is_full (&acfg->aot_opts) && cfg->orig_method->klass->valuetype && !(acfg->aot_opts.llvm_only && cfg->compile_llvm)) {
8220 #ifdef MONO_ARCH_AOT_SUPPORTED
8223 index = get_method_index (acfg, method);
8224 sprintf (symbol, "ut_%d", index);
8226 arch_emit_direct_call (acfg, symbol, FALSE, acfg->thumb_mixed && cfg->compile_llvm, NULL, &call_size);
8230 emit_int32 (acfg, 0);
8234 emit_info (MonoAotCompile *acfg)
8239 offsets = g_new0 (gint32, acfg->nmethods);
8241 for (oindex = 0; oindex < acfg->method_order->len; ++oindex) {
8242 i = GPOINTER_TO_UINT (g_ptr_array_index (acfg->method_order, oindex));
8244 if (acfg->cfgs [i]) {
8245 emit_method_info (acfg, acfg->cfgs [i]);
8246 offsets [i] = acfg->cfgs [i]->method_info_offset;
8252 acfg->stats.offsets_size += emit_offset_table (acfg, "method_info_offsets", MONO_AOT_TABLE_METHOD_INFO_OFFSETS, acfg->nmethods, 10, offsets);
8257 #endif /* #if !defined(DISABLE_AOT) && !defined(DISABLE_JIT) */
8259 #define rot(x,k) (((x)<<(k)) | ((x)>>(32-(k))))
8260 #define mix(a,b,c) { \
8261 a -= c; a ^= rot(c, 4); c += b; \
8262 b -= a; b ^= rot(a, 6); a += c; \
8263 c -= b; c ^= rot(b, 8); b += a; \
8264 a -= c; a ^= rot(c,16); c += b; \
8265 b -= a; b ^= rot(a,19); a += c; \
8266 c -= b; c ^= rot(b, 4); b += a; \
8268 #define final(a,b,c) { \
8269 c ^= b; c -= rot(b,14); \
8270 a ^= c; a -= rot(c,11); \
8271 b ^= a; b -= rot(a,25); \
8272 c ^= b; c -= rot(b,16); \
8273 a ^= c; a -= rot(c,4); \
8274 b ^= a; b -= rot(a,14); \
8275 c ^= b; c -= rot(b,24); \
8279 mono_aot_type_hash (MonoType *t1)
8281 guint hash = t1->type;
8283 hash |= t1->byref << 6; /* do not collide with t1->type values */
8285 case MONO_TYPE_VALUETYPE:
8286 case MONO_TYPE_CLASS:
8287 case MONO_TYPE_SZARRAY:
8288 /* check if the distribution is good enough */
8289 return ((hash << 5) - hash) ^ mono_metadata_str_hash (t1->data.klass->name);
8291 return ((hash << 5) - hash) ^ mono_metadata_type_hash (t1->data.type);
8292 case MONO_TYPE_ARRAY:
8293 return ((hash << 5) - hash) ^ mono_metadata_type_hash (&t1->data.array->eklass->byval_arg);
8294 case MONO_TYPE_GENERICINST:
8295 return ((hash << 5) - hash) ^ 0;
8302 * mono_aot_method_hash:
8304 * Return a hash code for methods which only depends on metadata.
8307 mono_aot_method_hash (MonoMethod *method)
8309 MonoMethodSignature *sig;
8313 guint32 *hashes_start, *hashes;
8315 MonoGenericInst *class_ginst = NULL;
8316 MonoGenericInst *ginst = NULL;
8318 /* Similar to the hash in mono_method_get_imt_slot () */
8320 sig = mono_method_signature (method);
8322 if (method->klass->generic_class)
8323 class_ginst = method->klass->generic_class->context.class_inst;
8324 if (method->is_inflated)
8325 ginst = ((MonoMethodInflated*)method)->context.method_inst;
8327 hashes_count = sig->param_count + 5 + (class_ginst ? class_ginst->type_argc : 0) + (ginst ? ginst->type_argc : 0);
8328 hashes_start = (guint32 *)g_malloc0 (hashes_count * sizeof (guint32));
8329 hashes = hashes_start;
8331 /* Some wrappers are assigned to random classes */
8332 if (!method->wrapper_type || method->wrapper_type == MONO_WRAPPER_REMOTING_INVOKE_WITH_CHECK)
8333 klass = method->klass;
8335 klass = mono_defaults.object_class;
8337 if (!method->wrapper_type) {
8340 if (klass->generic_class)
8341 full_name = mono_type_full_name (&klass->generic_class->container_class->byval_arg);
8343 full_name = mono_type_full_name (&klass->byval_arg);
8345 hashes [0] = mono_metadata_str_hash (full_name);
8349 hashes [0] = mono_metadata_str_hash (klass->name);
8350 hashes [1] = mono_metadata_str_hash (klass->name_space);
8352 if (method->wrapper_type == MONO_WRAPPER_STFLD || method->wrapper_type == MONO_WRAPPER_LDFLD || method->wrapper_type == MONO_WRAPPER_LDFLDA)
8353 /* The method name includes a stringified pointer */
8356 hashes [2] = mono_metadata_str_hash (method->name);
8357 hashes [3] = method->wrapper_type;
8358 hashes [4] = mono_aot_type_hash (sig->ret);
8360 for (i = 0; i < sig->param_count; i++) {
8361 hashes [hindex ++] = mono_aot_type_hash (sig->params [i]);
8364 for (i = 0; i < class_ginst->type_argc; ++i)
8365 hashes [hindex ++] = mono_aot_type_hash (class_ginst->type_argv [i]);
8368 for (i = 0; i < ginst->type_argc; ++i)
8369 hashes [hindex ++] = mono_aot_type_hash (ginst->type_argv [i]);
8371 g_assert (hindex == hashes_count);
8373 /* Setup internal state */
8374 a = b = c = 0xdeadbeef + (((guint32)hashes_count)<<2);
8376 /* Handle most of the hashes */
8377 while (hashes_count > 3) {
8386 /* Handle the last 3 hashes (all the case statements fall through) */
8387 switch (hashes_count) {
8388 case 3 : c += hashes [2];
8389 case 2 : b += hashes [1];
8390 case 1 : a += hashes [0];
8392 case 0: /* nothing left to add */
8396 free (hashes_start);
8405 * mono_aot_get_array_helper_from_wrapper;
8407 * Get the helper method in Array called by an array wrapper method.
8410 mono_aot_get_array_helper_from_wrapper (MonoMethod *method)
8414 MonoGenericContext ctx;
8415 MonoType *args [16];
8416 char *mname, *iname, *s, *s2, *helper_name = NULL;
8418 prefix = "System.Collections.Generic";
8419 s = g_strdup_printf ("%s", method->name + strlen (prefix) + 1);
8420 s2 = strstr (s, "`1.");
8426 //printf ("X: %s %s\n", iname, mname);
8428 if (!strcmp (iname, "IList"))
8429 helper_name = g_strdup_printf ("InternalArray__%s", mname);
8431 helper_name = g_strdup_printf ("InternalArray__%s_%s", iname, mname);
8432 m = mono_class_get_method_from_name (mono_defaults.array_class, helper_name, mono_method_signature (method)->param_count);
8434 g_free (helper_name);
8437 if (m->is_generic) {
8439 memset (&ctx, 0, sizeof (ctx));
8440 args [0] = &method->klass->element_class->byval_arg;
8441 ctx.method_inst = mono_metadata_get_generic_inst (1, args);
8442 m = mono_class_inflate_generic_method_checked (m, &ctx, &error);
8443 g_assert (mono_error_ok (&error)); /* FIXME don't swallow the error */
8449 #if !defined(DISABLE_AOT) && !defined(DISABLE_JIT)
8451 typedef struct HashEntry {
8452 guint32 key, value, index;
8453 struct HashEntry *next;
8457 * emit_extra_methods:
8459 * Emit methods which are not in the METHOD table, like wrappers.
8462 emit_extra_methods (MonoAotCompile *acfg)
8464 int i, table_size, buf_size;
8466 guint32 *info_offsets;
8469 HashEntry *entry, *new_entry;
8470 int nmethods, max_chain_length;
8473 info_offsets = g_new0 (guint32, acfg->extra_methods->len);
8475 /* Emit method info */
8477 for (i = 0; i < acfg->extra_methods->len; ++i) {
8478 MonoMethod *method = (MonoMethod *)g_ptr_array_index (acfg->extra_methods, i);
8479 MonoCompile *cfg = (MonoCompile *)g_hash_table_lookup (acfg->method_to_cfg, method);
8485 p = buf = (guint8 *)g_malloc (buf_size);
8489 method = cfg->method_to_register;
8491 encode_method_ref (acfg, method, p, &p);
8493 g_assert ((p - buf) < buf_size);
8495 info_offsets [i] = add_to_blob (acfg, buf, p - buf);
8500 * Construct a chained hash table for mapping indexes in extra_method_info to
8503 table_size = g_spaced_primes_closest ((int)(nmethods * 1.5));
8504 table = g_ptr_array_sized_new (table_size);
8505 for (i = 0; i < table_size; ++i)
8506 g_ptr_array_add (table, NULL);
8507 chain_lengths = g_new0 (int, table_size);
8508 max_chain_length = 0;
8509 for (i = 0; i < acfg->extra_methods->len; ++i) {
8510 MonoMethod *method = (MonoMethod *)g_ptr_array_index (acfg->extra_methods, i);
8511 MonoCompile *cfg = (MonoCompile *)g_hash_table_lookup (acfg->method_to_cfg, method);
8517 key = info_offsets [i];
8518 value = get_method_index (acfg, method);
8520 hash = mono_aot_method_hash (method) % table_size;
8521 //printf ("X: %s %x\n", mono_method_get_full_name (method), mono_aot_method_hash (method));
8523 chain_lengths [hash] ++;
8524 max_chain_length = MAX (max_chain_length, chain_lengths [hash]);
8526 new_entry = (HashEntry *)mono_mempool_alloc0 (acfg->mempool, sizeof (HashEntry));
8527 new_entry->key = key;
8528 new_entry->value = value;
8530 entry = (HashEntry *)g_ptr_array_index (table, hash);
8531 if (entry == NULL) {
8532 new_entry->index = hash;
8533 g_ptr_array_index (table, hash) = new_entry;
8536 entry = entry->next;
8538 entry->next = new_entry;
8539 new_entry->index = table->len;
8540 g_ptr_array_add (table, new_entry);
8544 //printf ("MAX: %d\n", max_chain_length);
8546 buf_size = table->len * 12 + 4;
8547 p = buf = (guint8 *)g_malloc (buf_size);
8548 encode_int (table_size, p, &p);
8550 for (i = 0; i < table->len; ++i) {
8551 HashEntry *entry = (HashEntry *)g_ptr_array_index (table, i);
8553 if (entry == NULL) {
8554 encode_int (0, p, &p);
8555 encode_int (0, p, &p);
8556 encode_int (0, p, &p);
8558 //g_assert (entry->key > 0);
8559 encode_int (entry->key, p, &p);
8560 encode_int (entry->value, p, &p);
8562 encode_int (entry->next->index, p, &p);
8564 encode_int (0, p, &p);
8567 g_assert (p - buf <= buf_size);
8569 /* Emit the table */
8570 emit_aot_data (acfg, MONO_AOT_TABLE_EXTRA_METHOD_TABLE, "extra_method_table", buf, p - buf);
8573 * Emit a table reverse mapping method indexes to their index in extra_method_info.
8574 * This is used by mono_aot_find_jit_info ().
8576 buf_size = acfg->extra_methods->len * 8 + 4;
8577 p = buf = (guint8 *)g_malloc (buf_size);
8578 encode_int (acfg->extra_methods->len, p, &p);
8579 for (i = 0; i < acfg->extra_methods->len; ++i) {
8580 MonoMethod *method = (MonoMethod *)g_ptr_array_index (acfg->extra_methods, i);
8582 encode_int (get_method_index (acfg, method), p, &p);
8583 encode_int (info_offsets [i], p, &p);
8585 emit_aot_data (acfg, MONO_AOT_TABLE_EXTRA_METHOD_INFO_OFFSETS, "extra_method_info_offsets", buf, p - buf);
8589 emit_exception_info (MonoAotCompile *acfg)
8593 SeqPointData sp_data;
8594 gboolean seq_points_to_file = FALSE;
8596 offsets = g_new0 (gint32, acfg->nmethods);
8597 for (i = 0; i < acfg->nmethods; ++i) {
8598 if (acfg->cfgs [i]) {
8599 MonoCompile *cfg = acfg->cfgs [i];
8601 // By design aot-runtime decode_exception_debug_info is not able to load sequence point debug data from a file.
8602 // As it is not possible to load debug data from a file its is also not possible to store it in a file.
8603 gboolean method_seq_points_to_file = acfg->aot_opts.gen_seq_points_file &&
8604 cfg->gen_seq_points && !cfg->gen_sdb_seq_points;
8605 gboolean method_seq_points_to_binary = cfg->gen_seq_points && !method_seq_points_to_file;
8607 emit_exception_debug_info (acfg, cfg, method_seq_points_to_binary);
8608 offsets [i] = cfg->ex_info_offset;
8610 if (method_seq_points_to_file) {
8611 if (!seq_points_to_file) {
8612 mono_seq_point_data_init (&sp_data, acfg->nmethods);
8613 seq_points_to_file = TRUE;
8615 mono_seq_point_data_add (&sp_data, cfg->method->token, cfg->method_index, cfg->seq_point_info);
8622 if (seq_points_to_file) {
8623 char *seq_points_aot_file = acfg->aot_opts.gen_seq_points_file_path ? acfg->aot_opts.gen_seq_points_file_path
8624 : g_strdup_printf("%s%s", acfg->image->name, SEQ_POINT_AOT_EXT);
8625 mono_seq_point_data_write (&sp_data, seq_points_aot_file);
8626 mono_seq_point_data_free (&sp_data);
8627 g_free (seq_points_aot_file);
8630 acfg->stats.offsets_size += emit_offset_table (acfg, "ex_info_offsets", MONO_AOT_TABLE_EX_INFO_OFFSETS, acfg->nmethods, 10, offsets);
8635 emit_unwind_info (MonoAotCompile *acfg)
8640 if (acfg->aot_opts.llvm_only) {
8641 g_assert (acfg->unwind_ops->len == 0);
8646 * The unwind info contains a lot of duplicates so we emit each unique
8647 * entry once, and only store the offset from the start of the table in the
8651 sprintf (symbol, "unwind_info");
8652 emit_section_change (acfg, RODATA_SECT, 1);
8653 emit_alignment (acfg, 8);
8654 emit_info_symbol (acfg, symbol);
8656 for (i = 0; i < acfg->unwind_ops->len; ++i) {
8657 guint32 index = GPOINTER_TO_UINT (g_ptr_array_index (acfg->unwind_ops, i));
8658 guint8 *unwind_info;
8659 guint32 unwind_info_len;
8663 unwind_info = mono_get_cached_unwind_info (index, &unwind_info_len);
8666 encode_value (unwind_info_len, p, &p);
8667 emit_bytes (acfg, buf, p - buf);
8668 emit_bytes (acfg, unwind_info, unwind_info_len);
8670 acfg->stats.unwind_info_size += (p - buf) + unwind_info_len;
8675 emit_class_info (MonoAotCompile *acfg)
8680 offsets = g_new0 (gint32, acfg->image->tables [MONO_TABLE_TYPEDEF].rows);
8681 for (i = 0; i < acfg->image->tables [MONO_TABLE_TYPEDEF].rows; ++i)
8682 offsets [i] = emit_klass_info (acfg, MONO_TOKEN_TYPE_DEF | (i + 1));
8684 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);
8688 typedef struct ClassNameTableEntry {
8689 guint32 token, index;
8690 struct ClassNameTableEntry *next;
8691 } ClassNameTableEntry;
8694 emit_class_name_table (MonoAotCompile *acfg)
8696 int i, table_size, buf_size;
8697 guint32 token, hash;
8702 ClassNameTableEntry *entry, *new_entry;
8705 * Construct a chained hash table for mapping class names to typedef tokens.
8707 table_size = g_spaced_primes_closest ((int)(acfg->image->tables [MONO_TABLE_TYPEDEF].rows * 1.5));
8708 table = g_ptr_array_sized_new (table_size);
8709 for (i = 0; i < table_size; ++i)
8710 g_ptr_array_add (table, NULL);
8711 for (i = 0; i < acfg->image->tables [MONO_TABLE_TYPEDEF].rows; ++i) {
8713 token = MONO_TOKEN_TYPE_DEF | (i + 1);
8714 klass = mono_class_get_checked (acfg->image, token, &error);
8716 mono_error_cleanup (&error);
8719 full_name = mono_type_get_name_full (mono_class_get_type (klass), MONO_TYPE_NAME_FORMAT_FULL_NAME);
8720 hash = mono_metadata_str_hash (full_name) % table_size;
8723 /* FIXME: Allocate from the mempool */
8724 new_entry = g_new0 (ClassNameTableEntry, 1);
8725 new_entry->token = token;
8727 entry = (ClassNameTableEntry *)g_ptr_array_index (table, hash);
8728 if (entry == NULL) {
8729 new_entry->index = hash;
8730 g_ptr_array_index (table, hash) = new_entry;
8733 entry = entry->next;
8735 entry->next = new_entry;
8736 new_entry->index = table->len;
8737 g_ptr_array_add (table, new_entry);
8741 /* Emit the table */
8742 buf_size = table->len * 4 + 4;
8743 p = buf = (guint8 *)g_malloc0 (buf_size);
8745 /* FIXME: Optimize memory usage */
8746 g_assert (table_size < 65000);
8747 encode_int16 (table_size, p, &p);
8748 g_assert (table->len < 65000);
8749 for (i = 0; i < table->len; ++i) {
8750 ClassNameTableEntry *entry = (ClassNameTableEntry *)g_ptr_array_index (table, i);
8752 if (entry == NULL) {
8753 encode_int16 (0, p, &p);
8754 encode_int16 (0, p, &p);
8756 encode_int16 (mono_metadata_token_index (entry->token), p, &p);
8758 encode_int16 (entry->next->index, p, &p);
8760 encode_int16 (0, p, &p);
8763 g_assert (p - buf <= buf_size);
8765 emit_aot_data (acfg, MONO_AOT_TABLE_CLASS_NAME, "class_name_table", buf, p - buf);
8769 emit_image_table (MonoAotCompile *acfg)
8775 * The image table is small but referenced in a lot of places.
8776 * So we emit it at once, and reference its elements by an index.
8778 buf_size = acfg->image_table->len * 28 + 4;
8779 for (i = 0; i < acfg->image_table->len; i++) {
8780 MonoImage *image = (MonoImage*)g_ptr_array_index (acfg->image_table, i);
8781 MonoAssemblyName *aname = &image->assembly->aname;
8783 buf_size += strlen (image->assembly_name) + strlen (image->guid) + (aname->culture ? strlen (aname->culture) : 1) + strlen ((char*)aname->public_key_token) + 4;
8786 buf = p = (guint8 *)g_malloc0 (buf_size);
8787 encode_int (acfg->image_table->len, p, &p);
8788 for (i = 0; i < acfg->image_table->len; i++) {
8789 MonoImage *image = (MonoImage*)g_ptr_array_index (acfg->image_table, i);
8790 MonoAssemblyName *aname = &image->assembly->aname;
8792 /* FIXME: Support multi-module assemblies */
8793 g_assert (image->assembly->image == image);
8795 encode_string (image->assembly_name, p, &p);
8796 encode_string (image->guid, p, &p);
8797 encode_string (aname->culture ? aname->culture : "", p, &p);
8798 encode_string ((const char*)aname->public_key_token, p, &p);
8800 while (GPOINTER_TO_UINT (p) % 8 != 0)
8803 encode_int (aname->flags, p, &p);
8804 encode_int (aname->major, p, &p);
8805 encode_int (aname->minor, p, &p);
8806 encode_int (aname->build, p, &p);
8807 encode_int (aname->revision, p, &p);
8809 g_assert (p - buf <= buf_size);
8811 emit_aot_data (acfg, MONO_AOT_TABLE_IMAGE_TABLE, "image_table", buf, p - buf);
8817 emit_got_info (MonoAotCompile *acfg, gboolean llvm)
8819 int i, first_plt_got_patch = 0, buf_size;
8821 guint32 *got_info_offsets;
8822 GotInfo *info = llvm ? &acfg->llvm_got_info : &acfg->got_info;
8824 /* Add the patches needed by the PLT to the GOT */
8826 acfg->plt_got_offset_base = acfg->got_offset;
8827 first_plt_got_patch = info->got_patches->len;
8828 for (i = 1; i < acfg->plt_offset; ++i) {
8829 MonoPltEntry *plt_entry = (MonoPltEntry *)g_hash_table_lookup (acfg->plt_offset_to_entry, GUINT_TO_POINTER (i));
8831 g_ptr_array_add (info->got_patches, plt_entry->ji);
8833 acfg->stats.got_slot_types [plt_entry->ji->type] ++;
8836 acfg->got_offset += acfg->plt_offset;
8841 * - optimize offsets table.
8842 * - reduce number of exported symbols.
8843 * - emit info for a klass only once.
8844 * - determine when a method uses a GOT slot which is guaranteed to be already
8846 * - clean up and document the code.
8847 * - use String.Empty in class libs.
8850 /* Encode info required to decode shared GOT entries */
8851 buf_size = info->got_patches->len * 128;
8852 p = buf = (guint8 *)mono_mempool_alloc (acfg->mempool, buf_size);
8853 got_info_offsets = (guint32 *)mono_mempool_alloc (acfg->mempool, info->got_patches->len * sizeof (guint32));
8855 acfg->plt_got_info_offsets = (guint32 *)mono_mempool_alloc (acfg->mempool, acfg->plt_offset * sizeof (guint32));
8857 if (acfg->plt_offset)
8858 acfg->plt_got_info_offsets [0] = 0;
8860 for (i = 0; i < info->got_patches->len; ++i) {
8861 MonoJumpInfo *ji = (MonoJumpInfo *)g_ptr_array_index (info->got_patches, i);
8866 encode_value (ji->type, p, &p);
8868 encode_patch (acfg, ji, p, &p);
8869 acfg->stats.got_slot_info_sizes [ji->type] += p - p2;
8870 g_assert (p - buf <= buf_size);
8871 got_info_offsets [i] = add_to_blob (acfg, buf, p - buf);
8873 if (!llvm && i >= first_plt_got_patch)
8874 acfg->plt_got_info_offsets [i - first_plt_got_patch + 1] = got_info_offsets [i];
8875 acfg->stats.got_info_size += p - buf;
8878 /* Emit got_info_offsets table */
8880 /* No need to emit offsets for the got plt entries, the plt embeds them directly */
8881 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);
8885 emit_got (MonoAotCompile *acfg)
8889 if (acfg->aot_opts.llvm_only)
8892 /* Don't make GOT global so accesses to it don't need relocations */
8893 sprintf (symbol, "%s", acfg->got_symbol);
8896 emit_unset_mode (acfg);
8897 fprintf (acfg->fp, ".section __DATA, __bss\n");
8898 emit_alignment (acfg, 8);
8900 emit_info_symbol (acfg, "jit_got");
8901 fprintf (acfg->fp, ".lcomm %s, %d\n", acfg->got_symbol, (int)(acfg->got_offset * sizeof (gpointer)));
8903 emit_section_change (acfg, ".bss", 0);
8904 emit_alignment (acfg, 8);
8905 emit_local_symbol (acfg, symbol, "got_end", FALSE);
8906 emit_label (acfg, symbol);
8908 emit_info_symbol (acfg, "jit_got");
8909 if (acfg->got_offset > 0)
8910 emit_zero_bytes (acfg, (int)(acfg->got_offset * sizeof (gpointer)));
8913 sprintf (symbol, "got_end");
8914 emit_label (acfg, symbol);
8917 typedef struct GlobalsTableEntry {
8918 guint32 value, index;
8919 struct GlobalsTableEntry *next;
8920 } GlobalsTableEntry;
8923 emit_globals (MonoAotCompile *acfg)
8929 GlobalsTableEntry *entry, *new_entry;
8931 if (!acfg->aot_opts.static_link)
8933 if (acfg->aot_opts.llvm_only) {
8934 g_assert (acfg->globals->len == 0);
8939 * When static linking, we emit a table containing our globals.
8943 * Construct a chained hash table for mapping global names to their index in
8944 * the globals table.
8946 table_size = g_spaced_primes_closest ((int)(acfg->globals->len * 1.5));
8947 table = g_ptr_array_sized_new (table_size);
8948 for (i = 0; i < table_size; ++i)
8949 g_ptr_array_add (table, NULL);
8950 for (i = 0; i < acfg->globals->len; ++i) {
8951 char *name = (char *)g_ptr_array_index (acfg->globals, i);
8953 hash = mono_metadata_str_hash (name) % table_size;
8955 /* FIXME: Allocate from the mempool */
8956 new_entry = g_new0 (GlobalsTableEntry, 1);
8957 new_entry->value = i;
8959 entry = (GlobalsTableEntry *)g_ptr_array_index (table, hash);
8960 if (entry == NULL) {
8961 new_entry->index = hash;
8962 g_ptr_array_index (table, hash) = new_entry;
8965 entry = entry->next;
8967 entry->next = new_entry;
8968 new_entry->index = table->len;
8969 g_ptr_array_add (table, new_entry);
8973 /* Emit the table */
8974 sprintf (symbol, ".Lglobals_hash");
8975 emit_section_change (acfg, RODATA_SECT, 0);
8976 emit_alignment (acfg, 8);
8977 emit_label (acfg, symbol);
8979 /* FIXME: Optimize memory usage */
8980 g_assert (table_size < 65000);
8981 emit_int16 (acfg, table_size);
8982 for (i = 0; i < table->len; ++i) {
8983 GlobalsTableEntry *entry = (GlobalsTableEntry *)g_ptr_array_index (table, i);
8985 if (entry == NULL) {
8986 emit_int16 (acfg, 0);
8987 emit_int16 (acfg, 0);
8989 emit_int16 (acfg, entry->value + 1);
8991 emit_int16 (acfg, entry->next->index);
8993 emit_int16 (acfg, 0);
8997 /* Emit the names */
8998 for (i = 0; i < acfg->globals->len; ++i) {
8999 char *name = (char *)g_ptr_array_index (acfg->globals, i);
9001 sprintf (symbol, "name_%d", i);
9002 emit_section_change (acfg, RODATA_SECT, 1);
9004 emit_alignment (acfg, 4);
9006 emit_label (acfg, symbol);
9007 emit_string (acfg, name);
9010 /* Emit the globals table */
9011 sprintf (symbol, "globals");
9012 emit_section_change (acfg, ".data", 0);
9013 /* This is not a global, since it is accessed by the init function */
9014 emit_alignment (acfg, 8);
9015 emit_info_symbol (acfg, symbol);
9017 sprintf (symbol, "%sglobals_hash", acfg->temp_prefix);
9018 emit_pointer (acfg, symbol);
9020 for (i = 0; i < acfg->globals->len; ++i) {
9021 char *name = (char *)g_ptr_array_index (acfg->globals, i);
9023 sprintf (symbol, "name_%d", i);
9024 emit_pointer (acfg, symbol);
9026 g_assert (strlen (name) < sizeof (symbol));
9027 sprintf (symbol, "%s", name);
9028 emit_pointer (acfg, symbol);
9030 /* Null terminate the table */
9031 emit_int32 (acfg, 0);
9032 emit_int32 (acfg, 0);
9036 emit_mem_end (MonoAotCompile *acfg)
9040 if (acfg->aot_opts.llvm_only)
9043 sprintf (symbol, "mem_end");
9044 emit_section_change (acfg, ".text", 1);
9045 emit_alignment_code (acfg, 8);
9046 emit_label (acfg, symbol);
9050 init_aot_file_info (MonoAotCompile *acfg, MonoAotFileInfo *info)
9054 info->version = MONO_AOT_FILE_VERSION;
9055 info->plt_got_offset_base = acfg->plt_got_offset_base;
9056 info->got_size = acfg->got_offset * sizeof (gpointer);
9057 info->plt_size = acfg->plt_offset;
9058 info->nmethods = acfg->nmethods;
9059 info->flags = acfg->flags;
9060 info->opts = acfg->opts;
9061 info->simd_opts = acfg->simd_opts;
9062 info->gc_name_index = acfg->gc_name_offset;
9063 info->datafile_size = acfg->datafile_offset;
9064 for (i = 0; i < MONO_AOT_TABLE_NUM; ++i)
9065 info->table_offsets [i] = acfg->table_offsets [i];
9066 for (i = 0; i < MONO_AOT_TRAMP_NUM; ++i)
9067 info->num_trampolines [i] = acfg->num_trampolines [i];
9068 for (i = 0; i < MONO_AOT_TRAMP_NUM; ++i)
9069 info->trampoline_got_offset_base [i] = acfg->trampoline_got_offset_base [i];
9070 for (i = 0; i < MONO_AOT_TRAMP_NUM; ++i)
9071 info->trampoline_size [i] = acfg->trampoline_size [i];
9072 info->num_rgctx_fetch_trampolines = acfg->aot_opts.nrgctx_fetch_trampolines;
9074 info->double_align = MONO_ABI_ALIGNOF (double);
9075 info->long_align = MONO_ABI_ALIGNOF (gint64);
9076 info->generic_tramp_num = MONO_TRAMPOLINE_NUM;
9077 info->tramp_page_size = acfg->tramp_page_size;
9078 info->nshared_got_entries = acfg->nshared_got_entries;
9079 for (i = 0; i < MONO_AOT_TRAMP_NUM; ++i)
9080 info->tramp_page_code_offsets [i] = acfg->tramp_page_code_offsets [i];
9084 emit_aot_file_info (MonoAotCompile *acfg, MonoAotFileInfo *info)
9088 const char **symbols;
9090 symbols = g_new0 (const char *, MONO_AOT_FILE_INFO_NUM_SYMBOLS);
9092 symbols [sindex ++] = acfg->got_symbol;
9094 symbols [sindex ++] = g_strdup_printf ("%s%s", acfg->user_symbol_prefix, acfg->llvm_got_symbol);
9095 symbols [sindex ++] = acfg->llvm_eh_frame_symbol;
9097 symbols [sindex ++] = NULL;
9098 symbols [sindex ++] = NULL;
9100 /* llvm_get_method */
9101 symbols [sindex ++] = NULL;
9102 /* llvm_get_unbox_tramp */
9103 symbols [sindex ++] = NULL;
9104 if (!acfg->aot_opts.llvm_only) {
9105 symbols [sindex ++] = "jit_code_start";
9106 symbols [sindex ++] = "jit_code_end";
9107 symbols [sindex ++] = "method_addresses";
9109 symbols [sindex ++] = NULL;
9110 symbols [sindex ++] = NULL;
9111 symbols [sindex ++] = NULL;
9113 if (acfg->data_outfile) {
9114 for (i = 0; i < MONO_AOT_TABLE_NUM; ++i)
9115 symbols [sindex ++] = NULL;
9117 symbols [sindex ++] = "blob";
9118 symbols [sindex ++] = "class_name_table";
9119 symbols [sindex ++] = "class_info_offsets";
9120 symbols [sindex ++] = "method_info_offsets";
9121 symbols [sindex ++] = "ex_info_offsets";
9122 symbols [sindex ++] = "extra_method_info_offsets";
9123 symbols [sindex ++] = "extra_method_table";
9124 symbols [sindex ++] = "got_info_offsets";
9126 symbols [sindex ++] = "llvm_got_info_offsets";
9128 symbols [sindex ++] = NULL;
9129 symbols [sindex ++] = "image_table";
9131 symbols [sindex ++] = "mem_end";
9132 symbols [sindex ++] = "assembly_guid";
9133 symbols [sindex ++] = "runtime_version";
9134 if (acfg->num_trampoline_got_entries) {
9135 symbols [sindex ++] = "specific_trampolines";
9136 symbols [sindex ++] = "static_rgctx_trampolines";
9137 symbols [sindex ++] = "imt_thunks";
9138 symbols [sindex ++] = "gsharedvt_arg_trampolines";
9140 symbols [sindex ++] = NULL;
9141 symbols [sindex ++] = NULL;
9142 symbols [sindex ++] = NULL;
9143 symbols [sindex ++] = NULL;
9145 if (acfg->aot_opts.static_link) {
9146 symbols [sindex ++] = "globals";
9148 symbols [sindex ++] = NULL;
9150 symbols [sindex ++] = "assembly_name";
9151 symbols [sindex ++] = "plt";
9152 symbols [sindex ++] = "plt_end";
9153 symbols [sindex ++] = "unwind_info";
9154 if (!acfg->aot_opts.llvm_only) {
9155 symbols [sindex ++] = "unbox_trampolines";
9156 symbols [sindex ++] = "unbox_trampolines_end";
9157 symbols [sindex ++] = "unbox_trampoline_addresses";
9159 symbols [sindex ++] = NULL;
9160 symbols [sindex ++] = NULL;
9161 symbols [sindex ++] = NULL;
9164 g_assert (sindex == MONO_AOT_FILE_INFO_NUM_SYMBOLS);
9166 sprintf (symbol, "%smono_aot_file_info", acfg->user_symbol_prefix);
9167 emit_section_change (acfg, ".data", 0);
9168 emit_alignment (acfg, 8);
9169 emit_label (acfg, symbol);
9170 if (!acfg->aot_opts.static_link)
9171 emit_global (acfg, symbol, FALSE);
9173 /* The data emitted here must match MonoAotFileInfo. */
9175 emit_int32 (acfg, info->version);
9176 emit_int32 (acfg, info->dummy);
9179 * We emit pointers to our data structures instead of emitting global symbols which
9180 * point to them, to reduce the number of globals, and because using globals leads to
9181 * various problems (i.e. arm/thumb).
9183 for (i = 0; i < MONO_AOT_FILE_INFO_NUM_SYMBOLS; ++i)
9184 emit_pointer (acfg, symbols [i]);
9186 emit_int32 (acfg, info->plt_got_offset_base);
9187 emit_int32 (acfg, info->got_size);
9188 emit_int32 (acfg, info->plt_size);
9189 emit_int32 (acfg, info->nmethods);
9190 emit_int32 (acfg, info->flags);
9191 emit_int32 (acfg, info->opts);
9192 emit_int32 (acfg, info->simd_opts);
9193 emit_int32 (acfg, info->gc_name_index);
9194 emit_int32 (acfg, info->num_rgctx_fetch_trampolines);
9195 emit_int32 (acfg, info->double_align);
9196 emit_int32 (acfg, info->long_align);
9197 emit_int32 (acfg, info->generic_tramp_num);
9198 emit_int32 (acfg, info->tramp_page_size);
9199 emit_int32 (acfg, info->nshared_got_entries);
9200 emit_int32 (acfg, info->datafile_size);
9202 for (i = 0; i < MONO_AOT_TABLE_NUM; ++i)
9203 emit_int32 (acfg, info->table_offsets [i]);
9204 for (i = 0; i < MONO_AOT_TRAMP_NUM; ++i)
9205 emit_int32 (acfg, info->num_trampolines [i]);
9206 for (i = 0; i < MONO_AOT_TRAMP_NUM; ++i)
9207 emit_int32 (acfg, info->trampoline_got_offset_base [i]);
9208 for (i = 0; i < MONO_AOT_TRAMP_NUM; ++i)
9209 emit_int32 (acfg, info->trampoline_size [i]);
9210 for (i = 0; i < MONO_AOT_TRAMP_NUM; ++i)
9211 emit_int32 (acfg, info->tramp_page_code_offsets [i]);
9213 if (acfg->aot_opts.static_link) {
9214 emit_global_inner (acfg, acfg->static_linking_symbol, FALSE);
9215 emit_alignment (acfg, sizeof (gpointer));
9216 emit_label (acfg, acfg->static_linking_symbol);
9217 emit_pointer_2 (acfg, acfg->user_symbol_prefix, "mono_aot_file_info");
9222 * Emit a structure containing all the information not stored elsewhere.
9225 emit_file_info (MonoAotCompile *acfg)
9228 MonoAotFileInfo *info;
9230 if (acfg->aot_opts.bind_to_runtime_version) {
9231 build_info = mono_get_runtime_build_info ();
9232 emit_string_symbol (acfg, "runtime_version", build_info);
9233 g_free (build_info);
9235 emit_string_symbol (acfg, "runtime_version", "");
9238 emit_string_symbol (acfg, "assembly_guid" , acfg->image->guid);
9240 /* Emit a string holding the assembly name */
9241 emit_string_symbol (acfg, "assembly_name", acfg->image->assembly->aname.name);
9243 info = g_new0 (MonoAotFileInfo, 1);
9244 init_aot_file_info (acfg, info);
9246 if (acfg->aot_opts.static_link) {
9251 * Emit a global symbol which can be passed by an embedding app to
9252 * mono_aot_register_module (). The symbol points to a pointer to the the file info
9255 sprintf (symbol, "%smono_aot_module_%s_info", acfg->user_symbol_prefix, acfg->image->assembly->aname.name);
9257 /* Get rid of characters which cannot occur in symbols */
9259 for (p = symbol; *p; ++p) {
9260 if (!(isalnum (*p) || *p == '_'))
9263 acfg->static_linking_symbol = g_strdup (symbol);
9267 mono_llvm_emit_aot_file_info (info, acfg->has_jitted_code);
9269 emit_aot_file_info (acfg, info);
9273 emit_blob (MonoAotCompile *acfg)
9275 acfg->blob_closed = TRUE;
9277 emit_aot_data (acfg, MONO_AOT_TABLE_BLOB, "blob", (guint8*)acfg->blob.data, acfg->blob.index);
9281 emit_objc_selectors (MonoAotCompile *acfg)
9286 if (!acfg->objc_selectors || acfg->objc_selectors->len == 0)
9291 * cat > foo.m << EOF
9294 * return @selector(print:);
9299 mono_img_writer_emit_unset_mode (acfg->w);
9300 g_assert (acfg->fp);
9301 fprintf (acfg->fp, ".section __DATA,__objc_selrefs,literal_pointers,no_dead_strip\n");
9302 fprintf (acfg->fp, ".align 3\n");
9303 for (i = 0; i < acfg->objc_selectors->len; ++i) {
9304 sprintf (symbol, "L_OBJC_SELECTOR_REFERENCES_%d", i);
9305 emit_label (acfg, symbol);
9306 sprintf (symbol, "L_OBJC_METH_VAR_NAME_%d", i);
9307 emit_pointer (acfg, symbol);
9310 fprintf (acfg->fp, ".section __TEXT,__cstring,cstring_literals\n");
9311 for (i = 0; i < acfg->objc_selectors->len; ++i) {
9312 fprintf (acfg->fp, "L_OBJC_METH_VAR_NAME_%d:\n", i);
9313 fprintf (acfg->fp, ".asciz \"%s\"\n", (char*)g_ptr_array_index (acfg->objc_selectors, i));
9316 fprintf (acfg->fp, ".section __DATA,__objc_imageinfo,regular,no_dead_strip\n");
9317 fprintf (acfg->fp, ".align 3\n");
9318 fprintf (acfg->fp, "L_OBJC_IMAGE_INFO:\n");
9319 fprintf (acfg->fp, ".long 0\n");
9320 fprintf (acfg->fp, ".long 16\n");
9324 emit_dwarf_info (MonoAotCompile *acfg)
9326 #ifdef EMIT_DWARF_INFO
9330 /* DIEs for methods */
9331 for (i = 0; i < acfg->nmethods; ++i) {
9332 MonoCompile *cfg = acfg->cfgs [i];
9337 // FIXME: LLVM doesn't define .Lme_...
9338 if (cfg->compile_llvm)
9341 sprintf (symbol2, "%sme_%x", acfg->temp_prefix, i);
9343 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 ()));
9349 collect_methods (MonoAotCompile *acfg)
9352 MonoImage *image = acfg->image;
9354 /* Collect methods */
9355 for (i = 0; i < image->tables [MONO_TABLE_METHOD].rows; ++i) {
9358 guint32 token = MONO_TOKEN_METHOD_DEF | (i + 1);
9360 method = mono_get_method_checked (acfg->image, token, NULL, NULL, &error);
9363 aot_printerrf (acfg, "Failed to load method 0x%x from '%s' due to %s.\n", token, image->name, mono_error_get_message (&error));
9364 aot_printerrf (acfg, "Run with MONO_LOG_LEVEL=debug for more information.\n");
9365 mono_error_cleanup (&error);
9369 /* Load all methods eagerly to skip the slower lazy loading code */
9370 mono_class_setup_methods (method->klass);
9372 if (mono_aot_mode_is_full (&acfg->aot_opts) && method->iflags & METHOD_IMPL_ATTRIBUTE_INTERNAL_CALL) {
9373 /* Compile the wrapper instead */
9374 /* We do this here instead of add_wrappers () because it is easy to do it here */
9375 MonoMethod *wrapper = mono_marshal_get_native_wrapper (method, TRUE, TRUE);
9379 /* FIXME: Some mscorlib methods don't have debug info */
9381 if (acfg->aot_opts.soft_debug && !method->wrapper_type) {
9382 if (!((method->flags & METHOD_ATTRIBUTE_PINVOKE_IMPL) ||
9383 (method->iflags & METHOD_IMPL_ATTRIBUTE_RUNTIME) ||
9384 (method->flags & METHOD_ATTRIBUTE_ABSTRACT) ||
9385 (method->iflags & METHOD_IMPL_ATTRIBUTE_INTERNAL_CALL))) {
9386 if (!mono_debug_lookup_method (method)) {
9387 fprintf (stderr, "Method %s has no debug info, probably the .mdb file for the assembly is missing.\n", mono_method_get_full_name (method));
9394 if (method->is_generic || method->klass->generic_container)
9395 /* Compile the ref shared version instead */
9396 method = mini_get_shared_method (method);
9398 /* Since we add the normal methods first, their index will be equal to their zero based token index */
9399 add_method_with_index (acfg, method, i, FALSE);
9400 acfg->method_index ++;
9403 /* gsharedvt methods */
9404 for (mindex = 0; mindex < image->tables [MONO_TABLE_METHOD].rows; ++mindex) {
9407 guint32 token = MONO_TOKEN_METHOD_DEF | (mindex + 1);
9409 if (!(acfg->opts & MONO_OPT_GSHAREDVT))
9412 method = mono_get_method_checked (acfg->image, token, NULL, NULL, &error);
9413 report_loader_error (acfg, &error, "Failed to load method token 0x%x due to %s\n", i, mono_error_get_message (&error));
9415 if (method->is_generic || method->klass->generic_container) {
9416 MonoMethod *gshared;
9418 gshared = mini_get_shared_method_full (method, TRUE, TRUE);
9419 add_extra_method (acfg, gshared);
9423 add_generic_instances (acfg);
9425 if (mono_aot_mode_is_full (&acfg->aot_opts))
9426 add_wrappers (acfg);
9431 compile_methods (MonoAotCompile *acfg)
9435 if (acfg->aot_opts.nthreads > 0) {
9440 gpointer *user_data;
9441 MonoMethod **methods;
9443 methods_len = acfg->methods->len;
9445 len = acfg->methods->len / acfg->aot_opts.nthreads;
9448 * Partition the list of methods into fragments, and hand it to threads to
9451 threads = g_ptr_array_new ();
9452 /* Make a copy since acfg->methods is modified by compile_method () */
9453 methods = g_new0 (MonoMethod*, methods_len);
9454 //memcpy (methods, g_ptr_array_index (acfg->methods, 0), sizeof (MonoMethod*) * methods_len);
9455 for (i = 0; i < methods_len; ++i)
9456 methods [i] = (MonoMethod *)g_ptr_array_index (acfg->methods, i);
9458 while (i < methods_len) {
9459 frag = g_ptr_array_new ();
9460 for (j = 0; j < len; ++j) {
9461 if (i < methods_len) {
9462 g_ptr_array_add (frag, methods [i]);
9467 user_data = g_new0 (gpointer, 3);
9468 user_data [0] = mono_domain_get ();
9469 user_data [1] = acfg;
9470 user_data [2] = frag;
9472 handle = mono_threads_create_thread ((LPTHREAD_START_ROUTINE)compile_thread_main, user_data, 0, 0, NULL);
9473 g_ptr_array_add (threads, handle);
9477 for (i = 0; i < threads->len; ++i) {
9478 WaitForSingleObjectEx (g_ptr_array_index (threads, i), INFINITE, FALSE);
9484 /* Compile methods added by compile_method () or all methods if nthreads == 0 */
9485 for (i = methods_len; i < acfg->methods->len; ++i) {
9486 /* This can new methods to acfg->methods */
9487 compile_method (acfg, (MonoMethod *)g_ptr_array_index (acfg->methods, i));
9492 compile_asm (MonoAotCompile *acfg)
9494 char *command, *objfile;
9495 char *outfile_name, *tmp_outfile_name, *llvm_ofile;
9496 const char *tool_prefix = acfg->aot_opts.tool_prefix ? acfg->aot_opts.tool_prefix : "";
9497 char *ld_flags = acfg->aot_opts.ld_flags ? acfg->aot_opts.ld_flags : g_strdup("");
9499 #if defined(TARGET_AMD64) && !defined(TARGET_MACH)
9500 #define AS_OPTIONS "--64"
9501 #elif defined(TARGET_POWERPC64)
9502 #define AS_OPTIONS "-a64 -mppc64"
9503 #define LD_OPTIONS "-m elf64ppc"
9504 #elif defined(sparc) && SIZEOF_VOID_P == 8
9505 #define AS_OPTIONS "-xarch=v9"
9506 #elif defined(TARGET_X86) && defined(TARGET_MACH) && !defined(__native_client_codegen__)
9507 #define AS_OPTIONS "-arch i386"
9509 #define AS_OPTIONS ""
9512 #ifdef __native_client_codegen__
9513 #if defined(TARGET_AMD64)
9514 #define AS_NAME "nacl64-as"
9516 #define AS_NAME "nacl-as"
9518 #elif defined(TARGET_OSX)
9519 #define AS_NAME "clang"
9521 #define AS_NAME "as"
9525 #define LD_OPTIONS ""
9529 #define LD_NAME "ld -shared -G"
9530 #elif defined(__ppc__) && defined(TARGET_MACH)
9531 #define LD_NAME "gcc -dynamiclib"
9532 #elif defined(TARGET_AMD64) && defined(TARGET_MACH)
9533 #define LD_NAME "clang --shared"
9534 #elif defined(TARGET_WIN32) && !defined(TARGET_ANDROID)
9535 #define LD_NAME "gcc -shared --dll"
9536 #elif defined(TARGET_X86) && defined(TARGET_MACH) && !defined(__native_client_codegen__)
9537 #define LD_NAME "clang -m32 -dynamiclib"
9538 #elif defined(TARGET_ARM) && !defined(TARGET_ANDROID)
9539 #define LD_NAME "gcc --shared"
9542 if (acfg->aot_opts.asm_only) {
9543 aot_printf (acfg, "Output file: '%s'.\n", acfg->tmpfname);
9544 if (acfg->aot_opts.static_link)
9545 aot_printf (acfg, "Linking symbol: '%s'.\n", acfg->static_linking_symbol);
9547 aot_printf (acfg, "LLVM output file: '%s'.\n", acfg->llvm_sfile);
9551 if (acfg->aot_opts.static_link) {
9552 if (acfg->aot_opts.outfile)
9553 objfile = g_strdup_printf ("%s", acfg->aot_opts.outfile);
9555 objfile = g_strdup_printf ("%s.o", acfg->image->name);
9557 objfile = g_strdup_printf ("%s.o", acfg->tmpfname);
9561 g_string_append (acfg->as_args, "-c -x assembler");
9564 command = g_strdup_printf ("\"%s%s\" %s %s -o %s %s", tool_prefix, AS_NAME, AS_OPTIONS,
9565 acfg->as_args ? acfg->as_args->str : "",
9566 wrap_path (objfile), wrap_path (acfg->tmpfname));
9567 aot_printf (acfg, "Executing the native assembler: %s\n", command);
9568 if (execute_system (command) != 0) {
9574 if (acfg->llvm && !acfg->llvm_owriter) {
9575 command = g_strdup_printf ("\"%s%s\" %s %s -o %s %s", tool_prefix, AS_NAME, AS_OPTIONS,
9576 acfg->as_args ? acfg->as_args->str : "",
9577 wrap_path (acfg->llvm_ofile), wrap_path (acfg->llvm_sfile));
9578 aot_printf (acfg, "Executing the native assembler: %s\n", command);
9579 if (execute_system (command) != 0) {
9588 if (acfg->aot_opts.static_link) {
9589 aot_printf (acfg, "Output file: '%s'.\n", objfile);
9590 aot_printf (acfg, "Linking symbol: '%s'.\n", acfg->static_linking_symbol);
9595 if (acfg->aot_opts.outfile)
9596 outfile_name = g_strdup_printf ("%s", acfg->aot_opts.outfile);
9598 outfile_name = g_strdup_printf ("%s%s", acfg->image->name, MONO_SOLIB_EXT);
9600 tmp_outfile_name = g_strdup_printf ("%s.tmp", outfile_name);
9603 llvm_ofile = g_strdup_printf ("\"%s\"", acfg->llvm_ofile);
9605 llvm_ofile = g_strdup ("");
9608 /* replace the ; flags separators with spaces */
9609 g_strdelimit (ld_flags, ";", ' ');
9611 if (acfg->aot_opts.llvm_only)
9612 ld_flags = g_strdup_printf ("%s %s", ld_flags, "-lstdc++");
9615 command = g_strdup_printf ("%s -o %s %s %s %s", LD_NAME,
9616 wrap_path (tmp_outfile_name), wrap_path (llvm_ofile),
9617 wrap_path (g_strdup_printf ("%s.o", acfg->tmpfname)), ld_flags);
9619 command = g_strdup_printf ("\"%sld\" %s -shared -o %s %s %s %s", tool_prefix, LD_OPTIONS,
9620 wrap_path (tmp_outfile_name), wrap_path (llvm_ofile),
9621 wrap_path (g_strdup_printf ("%s.o", acfg->tmpfname)), ld_flags);
9623 aot_printf (acfg, "Executing the native linker: %s\n", command);
9624 if (execute_system (command) != 0) {
9625 g_free (tmp_outfile_name);
9626 g_free (outfile_name);
9635 /*com = g_strdup_printf ("strip --strip-unneeded %s%s", acfg->image->name, MONO_SOLIB_EXT);
9636 printf ("Stripping the binary: %s\n", com);
9637 execute_system (com);
9640 #if defined(TARGET_ARM) && !defined(TARGET_MACH)
9642 * gas generates 'mapping symbols' each time code and data is mixed, which
9643 * happens a lot in emit_and_reloc_code (), so we need to get rid of them.
9645 command = g_strdup_printf ("\"%sstrip\" --strip-symbol=\\$a --strip-symbol=\\$d %s", tool_prefix, tmp_outfile_name);
9646 aot_printf (acfg, "Stripping the binary: %s\n", command);
9647 if (execute_system (command) != 0) {
9648 g_free (tmp_outfile_name);
9649 g_free (outfile_name);
9656 rename (tmp_outfile_name, outfile_name);
9658 #if defined(TARGET_MACH)
9659 command = g_strdup_printf ("dsymutil \"%s\"", outfile_name);
9660 aot_printf (acfg, "Executing dsymutil: %s\n", command);
9661 if (execute_system (command) != 0) {
9666 if (!acfg->aot_opts.save_temps)
9669 g_free (tmp_outfile_name);
9670 g_free (outfile_name);
9673 if (acfg->aot_opts.save_temps)
9674 aot_printf (acfg, "Retained input file.\n");
9676 unlink (acfg->tmpfname);
9681 static void init_got_info (GotInfo *info)
9685 info->patch_to_got_offset = g_hash_table_new (mono_patch_info_hash, mono_patch_info_equal);
9686 info->patch_to_got_offset_by_type = g_new0 (GHashTable*, MONO_PATCH_INFO_NUM);
9687 for (i = 0; i < MONO_PATCH_INFO_NUM; ++i)
9688 info->patch_to_got_offset_by_type [i] = g_hash_table_new (mono_patch_info_hash, mono_patch_info_equal);
9689 info->got_patches = g_ptr_array_new ();
9692 static MonoAotCompile*
9693 acfg_create (MonoAssembly *ass, guint32 opts)
9695 MonoImage *image = ass->image;
9696 MonoAotCompile *acfg;
9698 acfg = g_new0 (MonoAotCompile, 1);
9699 acfg->methods = g_ptr_array_new ();
9700 acfg->method_indexes = g_hash_table_new (NULL, NULL);
9701 acfg->method_depth = g_hash_table_new (NULL, NULL);
9702 acfg->plt_offset_to_entry = g_hash_table_new (NULL, NULL);
9703 acfg->patch_to_plt_entry = g_new0 (GHashTable*, MONO_PATCH_INFO_NUM);
9704 acfg->method_to_cfg = g_hash_table_new (NULL, NULL);
9705 acfg->token_info_hash = g_hash_table_new_full (NULL, NULL, NULL, NULL);
9706 acfg->method_to_pinvoke_import = g_hash_table_new_full (NULL, NULL, NULL, g_free);
9707 acfg->image_hash = g_hash_table_new (NULL, NULL);
9708 acfg->image_table = g_ptr_array_new ();
9709 acfg->globals = g_ptr_array_new ();
9710 acfg->image = image;
9712 /* TODO: Write out set of SIMD instructions used, rather than just those available */
9713 acfg->simd_opts = mono_arch_cpu_enumerate_simd_versions ();
9714 acfg->mempool = mono_mempool_new ();
9715 acfg->extra_methods = g_ptr_array_new ();
9716 acfg->unwind_info_offsets = g_hash_table_new (NULL, NULL);
9717 acfg->unwind_ops = g_ptr_array_new ();
9718 acfg->method_label_hash = g_hash_table_new_full (g_str_hash, g_str_equal, g_free, NULL);
9719 acfg->method_order = g_ptr_array_new ();
9720 acfg->export_names = g_hash_table_new (NULL, NULL);
9721 acfg->klass_blob_hash = g_hash_table_new (NULL, NULL);
9722 acfg->method_blob_hash = g_hash_table_new (NULL, NULL);
9723 acfg->plt_entry_debug_sym_cache = g_hash_table_new (g_str_hash, g_str_equal);
9724 acfg->gsharedvt_in_signatures = g_hash_table_new ((GHashFunc)mono_signature_hash, (GEqualFunc)mono_metadata_signature_equal);
9725 acfg->gsharedvt_out_signatures = g_hash_table_new ((GHashFunc)mono_signature_hash, (GEqualFunc)mono_metadata_signature_equal);
9726 mono_os_mutex_init_recursive (&acfg->mutex);
9728 init_got_info (&acfg->got_info);
9729 init_got_info (&acfg->llvm_got_info);
9735 got_info_free (GotInfo *info)
9739 for (i = 0; i < MONO_PATCH_INFO_NUM; ++i)
9740 g_hash_table_destroy (info->patch_to_got_offset_by_type [i]);
9741 g_free (info->patch_to_got_offset_by_type);
9742 g_hash_table_destroy (info->patch_to_got_offset);
9743 g_ptr_array_free (info->got_patches, TRUE);
9747 acfg_free (MonoAotCompile *acfg)
9751 mono_img_writer_destroy (acfg->w);
9752 for (i = 0; i < acfg->nmethods; ++i)
9754 g_free (acfg->cfgs [i]);
9755 g_free (acfg->cfgs);
9756 g_free (acfg->static_linking_symbol);
9757 g_free (acfg->got_symbol);
9758 g_free (acfg->plt_symbol);
9759 g_ptr_array_free (acfg->methods, TRUE);
9760 g_ptr_array_free (acfg->image_table, TRUE);
9761 g_ptr_array_free (acfg->globals, TRUE);
9762 g_ptr_array_free (acfg->unwind_ops, TRUE);
9763 g_hash_table_destroy (acfg->method_indexes);
9764 g_hash_table_destroy (acfg->method_depth);
9765 g_hash_table_destroy (acfg->plt_offset_to_entry);
9766 for (i = 0; i < MONO_PATCH_INFO_NUM; ++i) {
9767 if (acfg->patch_to_plt_entry [i])
9768 g_hash_table_destroy (acfg->patch_to_plt_entry [i]);
9770 g_free (acfg->patch_to_plt_entry);
9771 g_hash_table_destroy (acfg->method_to_cfg);
9772 g_hash_table_destroy (acfg->token_info_hash);
9773 g_hash_table_destroy (acfg->method_to_pinvoke_import);
9774 g_hash_table_destroy (acfg->image_hash);
9775 g_hash_table_destroy (acfg->unwind_info_offsets);
9776 g_hash_table_destroy (acfg->method_label_hash);
9777 g_hash_table_destroy (acfg->export_names);
9778 g_hash_table_destroy (acfg->plt_entry_debug_sym_cache);
9779 g_hash_table_destroy (acfg->klass_blob_hash);
9780 g_hash_table_destroy (acfg->method_blob_hash);
9781 got_info_free (&acfg->got_info);
9782 got_info_free (&acfg->llvm_got_info);
9783 mono_mempool_destroy (acfg->mempool);
9787 #define WRAPPER(e,n) n,
9788 static const char* const
9789 wrapper_type_names [MONO_WRAPPER_NUM + 1] = {
9790 #include "mono/metadata/wrapper-types.h"
9794 static G_GNUC_UNUSED const char*
9795 get_wrapper_type_name (int type)
9797 return wrapper_type_names [type];
9803 static void aot_dump (MonoAotCompile *acfg)
9809 mono_json_writer_init (&writer);
9811 mono_json_writer_object_begin(&writer);
9814 mono_json_writer_indent (&writer);
9815 mono_json_writer_object_key(&writer, "methods");
9816 mono_json_writer_array_begin (&writer);
9819 for (i = 0; i < acfg->nmethods; ++i) {
9824 cfg = acfg->cfgs [i];
9828 method = cfg->orig_method;
9830 mono_json_writer_indent (&writer);
9831 mono_json_writer_object_begin(&writer);
9833 mono_json_writer_indent (&writer);
9834 mono_json_writer_object_key(&writer, "name");
9835 mono_json_writer_printf (&writer, "\"%s\",\n", method->name);
9837 mono_json_writer_indent (&writer);
9838 mono_json_writer_object_key(&writer, "signature");
9839 mono_json_writer_printf (&writer, "\"%s\",\n", mono_method_get_full_name (method));
9841 mono_json_writer_indent (&writer);
9842 mono_json_writer_object_key(&writer, "code_size");
9843 mono_json_writer_printf (&writer, "\"%d\",\n", cfg->code_size);
9845 klass = method->klass;
9847 mono_json_writer_indent (&writer);
9848 mono_json_writer_object_key(&writer, "class");
9849 mono_json_writer_printf (&writer, "\"%s\",\n", klass->name);
9851 mono_json_writer_indent (&writer);
9852 mono_json_writer_object_key(&writer, "namespace");
9853 mono_json_writer_printf (&writer, "\"%s\",\n", klass->name_space);
9855 mono_json_writer_indent (&writer);
9856 mono_json_writer_object_key(&writer, "wrapper_type");
9857 mono_json_writer_printf (&writer, "\"%s\",\n", get_wrapper_type_name(method->wrapper_type));
9859 mono_json_writer_indent_pop (&writer);
9860 mono_json_writer_indent (&writer);
9861 mono_json_writer_object_end (&writer);
9862 mono_json_writer_printf (&writer, ",\n");
9865 mono_json_writer_indent_pop (&writer);
9866 mono_json_writer_indent (&writer);
9867 mono_json_writer_array_end (&writer);
9868 mono_json_writer_printf (&writer, ",\n");
9872 mono_json_writer_indent_push (&writer);
9873 mono_json_writer_indent (&writer);
9874 mono_json_writer_object_key(&writer, "plt");
9875 mono_json_writer_array_begin (&writer);
9877 for (i = 0; i < acfg->plt_offset; ++i) {
9878 MonoPltEntry *plt_entry = NULL;
9883 * The first plt entry is unused.
9887 plt_entry = g_hash_table_lookup (acfg->plt_offset_to_entry, GUINT_TO_POINTER (i));
9890 mono_json_writer_indent (&writer);
9891 mono_json_writer_printf (&writer, "{ ");
9892 mono_json_writer_object_key(&writer, "symbol");
9893 mono_json_writer_printf (&writer, "\"%s\" },\n", plt_entry->symbol);
9896 mono_json_writer_indent_pop (&writer);
9897 mono_json_writer_indent (&writer);
9898 mono_json_writer_array_end (&writer);
9899 mono_json_writer_printf (&writer, ",\n");
9904 mono_json_writer_indent_push (&writer);
9905 mono_json_writer_indent (&writer);
9906 mono_json_writer_object_key(&writer, "got");
9907 mono_json_writer_array_begin (&writer);
9909 mono_json_writer_indent_push (&writer);
9910 for (i = 0; i < acfg->got_info.got_patches->len; ++i) {
9911 MonoJumpInfo *ji = g_ptr_array_index (acfg->got_info.got_patches, i);
9913 mono_json_writer_indent (&writer);
9914 mono_json_writer_printf (&writer, "{ ");
9915 mono_json_writer_object_key(&writer, "patch_name");
9916 mono_json_writer_printf (&writer, "\"%s\" },\n", get_patch_name (ji->type));
9919 mono_json_writer_indent_pop (&writer);
9920 mono_json_writer_indent (&writer);
9921 mono_json_writer_array_end (&writer);
9922 mono_json_writer_printf (&writer, ",\n");
9925 mono_json_writer_indent_pop (&writer);
9926 mono_json_writer_indent (&writer);
9927 mono_json_writer_object_end (&writer);
9929 dumpname = g_strdup_printf ("%s.json", g_path_get_basename (acfg->image->name));
9930 dumpfile = fopen (dumpname, "w+");
9933 fprintf (dumpfile, "%s", writer.text->str);
9936 mono_json_writer_destroy (&writer);
9939 static const char *preinited_jit_icalls[] = {
9940 "mono_aot_init_llvm_method",
9941 "mono_aot_init_gshared_method_this",
9942 "mono_aot_init_gshared_method_mrgctx",
9943 "mono_aot_init_gshared_method_vtable",
9944 "mono_llvm_throw_corlib_exception",
9945 "mono_init_vtable_slot",
9946 "mono_helper_ldstr_mscorlib"
9950 add_preinit_got_slots (MonoAotCompile *acfg)
9956 * Allocate the first few GOT entries to information which is needed frequently, or it is needed
9957 * during method initialization etc.
9960 ji = (MonoJumpInfo *)mono_mempool_alloc0 (acfg->mempool, sizeof (MonoJumpInfo));
9961 ji->type = MONO_PATCH_INFO_IMAGE;
9962 ji->data.image = acfg->image;
9963 get_got_offset (acfg, FALSE, ji);
9964 get_got_offset (acfg, TRUE, ji);
9966 ji = (MonoJumpInfo *)mono_mempool_alloc0 (acfg->mempool, sizeof (MonoJumpInfo));
9967 ji->type = MONO_PATCH_INFO_MSCORLIB_GOT_ADDR;
9968 get_got_offset (acfg, FALSE, ji);
9969 get_got_offset (acfg, TRUE, ji);
9971 ji = (MonoJumpInfo *)mono_mempool_alloc0 (acfg->mempool, sizeof (MonoJumpInfo));
9972 ji->type = MONO_PATCH_INFO_GC_CARD_TABLE_ADDR;
9973 get_got_offset (acfg, FALSE, ji);
9974 get_got_offset (acfg, TRUE, ji);
9976 ji = (MonoJumpInfo *)mono_mempool_alloc0 (acfg->mempool, sizeof (MonoJumpInfo));
9977 ji->type = MONO_PATCH_INFO_GC_NURSERY_START;
9978 get_got_offset (acfg, FALSE, ji);
9979 get_got_offset (acfg, TRUE, ji);
9981 ji = (MonoJumpInfo *)mono_mempool_alloc0 (acfg->mempool, sizeof (MonoJumpInfo));
9982 ji->type = MONO_PATCH_INFO_JIT_TLS_ID;
9983 get_got_offset (acfg, FALSE, ji);
9984 get_got_offset (acfg, TRUE, ji);
9986 ji = (MonoJumpInfo *)mono_mempool_alloc0 (acfg->mempool, sizeof (MonoJumpInfo));
9987 ji->type = MONO_PATCH_INFO_AOT_MODULE;
9988 get_got_offset (acfg, FALSE, ji);
9989 get_got_offset (acfg, TRUE, ji);
9991 ji = (MonoJumpInfo *)mono_mempool_alloc0 (acfg->mempool, sizeof (MonoJumpInfo));
9992 ji->type = MONO_PATCH_INFO_GC_NURSERY_BITS;
9993 get_got_offset (acfg, FALSE, ji);
9994 get_got_offset (acfg, TRUE, ji);
9996 for (i = 0; i < sizeof (preinited_jit_icalls) / sizeof (char*); ++i) {
9997 ji = (MonoJumpInfo *)mono_mempool_alloc0 (acfg->mempool, sizeof (MonoAotCompile));
9998 ji->type = MONO_PATCH_INFO_INTERNAL_METHOD;
9999 ji->data.name = preinited_jit_icalls [i];
10000 get_got_offset (acfg, FALSE, ji);
10001 get_got_offset (acfg, TRUE, ji);
10004 acfg->nshared_got_entries = acfg->got_offset;
10008 mono_compile_assembly (MonoAssembly *ass, guint32 opts, const char *aot_options)
10010 MonoImage *image = ass->image;
10013 MonoAotCompile *acfg;
10014 char *outfile_name, *tmp_outfile_name, *p;
10015 char llvm_stats_msg [256];
10019 acfg = acfg_create (ass, opts);
10021 memset (&acfg->aot_opts, 0, sizeof (acfg->aot_opts));
10022 acfg->aot_opts.write_symbols = TRUE;
10023 acfg->aot_opts.ntrampolines = 1024;
10024 acfg->aot_opts.nrgctx_trampolines = 1024;
10025 acfg->aot_opts.nimt_trampolines = 128;
10026 acfg->aot_opts.nrgctx_fetch_trampolines = 128;
10027 acfg->aot_opts.ngsharedvt_arg_trampolines = 128;
10028 acfg->aot_opts.llvm_path = g_strdup ("");
10029 acfg->aot_opts.temp_path = g_strdup ("");
10031 acfg->aot_opts.use_trampolines_page = TRUE;
10034 mono_aot_parse_options (aot_options, &acfg->aot_opts);
10036 if (acfg->aot_opts.logfile) {
10037 acfg->logfile = fopen (acfg->aot_opts.logfile, "a+");
10040 if (acfg->aot_opts.data_outfile) {
10041 acfg->data_outfile = fopen (acfg->aot_opts.data_outfile, "w+");
10042 if (!acfg->data_outfile) {
10043 aot_printerrf (acfg, "Unable to create file '%s': %s\n", acfg->aot_opts.data_outfile, strerror (errno));
10046 acfg->flags = (MonoAotFileFlags)(acfg->flags | MONO_AOT_FILE_FLAG_SEPARATE_DATA);
10049 //acfg->aot_opts.print_skipped_methods = TRUE;
10051 #if !defined(ENABLE_GSHAREDVT)
10052 if (opts & MONO_OPT_GSHAREDVT) {
10053 aot_printerrf (acfg, "-O=gsharedvt not supported on this platform.\n");
10058 #if !defined(MONO_ARCH_GSHAREDVT_SUPPORTED)
10059 if (!acfg->aot_opts.llvm_only && (opts & MONO_OPT_GSHAREDVT)) {
10060 aot_printerrf (acfg, "-O=gsharedvt not supported on this platform.\n");
10065 if (acfg->aot_opts.llvm_only) {
10066 #ifndef ENABLE_GSHAREDVT
10067 aot_printerrf (acfg, "--aot=llvmonly requires a runtime compiled with --enable-gsharedvt.\n");
10072 #if defined(ENABLE_GSHAREDVT) && defined(MONO_ARCH_GSHAREDVT_SUPPORTED)
10073 acfg->opts |= MONO_OPT_GSHAREDVT;
10074 opts |= MONO_OPT_GSHAREDVT;
10077 if (opts & MONO_OPT_GSHAREDVT)
10078 mono_set_generic_sharing_vt_supported (TRUE);
10080 aot_printf (acfg, "Mono Ahead of Time compiler - compiling assembly %s\n", image->name);
10082 #ifndef MONO_ARCH_HAVE_FULL_AOT_TRAMPOLINES
10083 if (mono_aot_mode_is_full (&acfg->aot_opts)) {
10084 aot_printerrf (acfg, "--aot=full is not supported on this platform.\n");
10089 if (acfg->aot_opts.direct_pinvoke && !acfg->aot_opts.static_link) {
10090 aot_printerrf (acfg, "The 'direct-pinvoke' AOT option also requires the 'static' AOT option.\n");
10094 if (acfg->aot_opts.static_link)
10095 acfg->aot_opts.asm_writer = TRUE;
10097 if (acfg->aot_opts.soft_debug) {
10098 MonoDebugOptions *opt = mini_get_debug_options ();
10100 opt->mdb_optimizations = TRUE;
10101 opt->gen_sdb_seq_points = TRUE;
10103 if (!mono_debug_enabled ()) {
10104 aot_printerrf (acfg, "The soft-debug AOT option requires the --debug option.\n");
10107 acfg->flags = (MonoAotFileFlags)(acfg->flags | MONO_AOT_FILE_FLAG_DEBUG);
10110 if (mono_use_llvm || acfg->aot_opts.llvm) {
10112 acfg->aot_opts.asm_writer = TRUE;
10113 acfg->flags = (MonoAotFileFlags)(acfg->flags | MONO_AOT_FILE_FLAG_WITH_LLVM);
10115 if (acfg->aot_opts.soft_debug) {
10116 aot_printerrf (acfg, "The 'soft-debug' option is not supported when compiling with LLVM.\n");
10122 if (acfg->aot_opts.asm_only && !acfg->aot_opts.llvm_outfile) {
10123 aot_printerrf (acfg, "Compiling with LLVM and the asm-only option requires the llvm-outputfile= option.");
10128 * Emit all LLVM code into a separate assembly/object file and link with it
10131 if (!acfg->aot_opts.asm_only) {
10132 acfg->llvm_owriter = TRUE;
10133 } else if (acfg->aot_opts.llvm_outfile) {
10134 int len = strlen (acfg->aot_opts.llvm_outfile);
10136 if (len >= 2 && acfg->aot_opts.llvm_outfile [len - 2] == '.' && acfg->aot_opts.llvm_outfile [len - 1] == 'o')
10137 acfg->llvm_owriter = TRUE;
10141 if (mono_aot_mode_is_full (&acfg->aot_opts))
10142 acfg->flags = (MonoAotFileFlags)(acfg->flags | MONO_AOT_FILE_FLAG_FULL_AOT);
10144 if (mono_threads_is_coop_enabled ())
10145 acfg->flags = (MonoAotFileFlags)(acfg->flags | MONO_AOT_FILE_FLAG_SAFEPOINTS);
10147 if (acfg->aot_opts.instances_logfile_path) {
10148 acfg->instances_logfile = fopen (acfg->aot_opts.instances_logfile_path, "w");
10149 if (!acfg->instances_logfile) {
10150 aot_printerrf (acfg, "Unable to create logfile: '%s'.\n", acfg->aot_opts.instances_logfile_path);
10155 load_profile_files (acfg);
10157 acfg->num_trampolines [MONO_AOT_TRAMP_SPECIFIC] = mono_aot_mode_is_full (&acfg->aot_opts) ? acfg->aot_opts.ntrampolines : 0;
10158 #ifdef MONO_ARCH_GSHARED_SUPPORTED
10159 acfg->num_trampolines [MONO_AOT_TRAMP_STATIC_RGCTX] = mono_aot_mode_is_full (&acfg->aot_opts) ? acfg->aot_opts.nrgctx_trampolines : 0;
10161 acfg->num_trampolines [MONO_AOT_TRAMP_IMT_THUNK] = mono_aot_mode_is_full (&acfg->aot_opts) ? acfg->aot_opts.nimt_trampolines : 0;
10162 #ifdef MONO_ARCH_GSHAREDVT_SUPPORTED
10163 if (acfg->opts & MONO_OPT_GSHAREDVT)
10164 acfg->num_trampolines [MONO_AOT_TRAMP_GSHAREDVT_ARG] = mono_aot_mode_is_full (&acfg->aot_opts) ? acfg->aot_opts.ngsharedvt_arg_trampolines : 0;
10167 acfg->temp_prefix = mono_img_writer_get_temp_label_prefix (NULL);
10171 if (acfg->llvm && acfg->thumb_mixed)
10172 acfg->flags = (MonoAotFileFlags)(acfg->flags | MONO_AOT_FILE_FLAG_LLVM_THUMB);
10173 if (acfg->aot_opts.llvm_only)
10174 acfg->flags = (MonoAotFileFlags)(acfg->flags | MONO_AOT_FILE_FLAG_LLVM_ONLY);
10176 acfg->assembly_name_sym = g_strdup (acfg->image->assembly->aname.name);
10177 /* Get rid of characters which cannot occur in symbols */
10178 for (p = acfg->assembly_name_sym; *p; ++p) {
10179 if (!(isalnum (*p) || *p == '_'))
10183 acfg->global_prefix = g_strdup_printf ("mono_aot_%s", acfg->assembly_name_sym);
10184 acfg->plt_symbol = g_strdup_printf ("%s_plt", acfg->global_prefix);
10185 acfg->got_symbol = g_strdup_printf ("%s_got", acfg->global_prefix);
10187 acfg->llvm_got_symbol = g_strdup_printf ("%s_llvm_got", acfg->global_prefix);
10188 acfg->llvm_eh_frame_symbol = g_strdup_printf ("%s_eh_frame", acfg->global_prefix);
10191 acfg->method_index = 1;
10193 if (mono_aot_mode_is_full (&acfg->aot_opts))
10194 mono_set_partial_sharing_supported (TRUE);
10196 res = collect_methods (acfg);
10200 acfg->cfgs_size = acfg->methods->len + 32;
10201 acfg->cfgs = g_new0 (MonoCompile*, acfg->cfgs_size);
10203 /* PLT offset 0 is reserved for the PLT trampoline */
10204 acfg->plt_offset = 1;
10205 add_preinit_got_slots (acfg);
10210 mono_llvm_create_aot_module (acfg->image->assembly, acfg->global_prefix, TRUE, acfg->aot_opts.static_link, acfg->aot_opts.llvm_only);
10216 compile_methods (acfg);
10220 acfg->stats.jit_time = TV_ELAPSED (atv, btv);
10226 if (acfg->aot_opts.asm_only) {
10227 if (acfg->aot_opts.outfile) {
10228 acfg->tmpfname = g_strdup_printf ("%s", acfg->aot_opts.outfile);
10229 acfg->tmpbasename = g_strdup (acfg->tmpfname);
10231 acfg->tmpbasename = g_strdup_printf ("%s", acfg->image->name);
10232 acfg->tmpfname = g_strdup_printf ("%s.s", acfg->tmpbasename);
10234 g_assert (acfg->aot_opts.llvm_outfile);
10235 acfg->llvm_sfile = g_strdup (acfg->aot_opts.llvm_outfile);
10236 if (acfg->llvm_owriter)
10237 acfg->llvm_ofile = g_strdup (acfg->aot_opts.llvm_outfile);
10239 acfg->llvm_sfile = g_strdup (acfg->aot_opts.llvm_outfile);
10241 acfg->tmpbasename = (strcmp (acfg->aot_opts.temp_path, "") == 0) ?
10242 g_strdup_printf ("%s", "temp") :
10243 g_build_filename (acfg->aot_opts.temp_path, "temp", NULL);
10245 acfg->tmpfname = g_strdup_printf ("%s.s", acfg->tmpbasename);
10246 acfg->llvm_sfile = g_strdup_printf ("%s-llvm.s", acfg->tmpbasename);
10247 acfg->llvm_ofile = g_strdup_printf ("%s-llvm.o", acfg->tmpbasename);
10252 if (acfg->aot_opts.asm_only && !acfg->aot_opts.llvm_only) {
10253 if (acfg->aot_opts.outfile)
10254 acfg->tmpfname = g_strdup_printf ("%s", acfg->aot_opts.outfile);
10256 acfg->tmpfname = g_strdup_printf ("%s.s", acfg->image->name);
10257 acfg->fp = fopen (acfg->tmpfname, "w+");
10259 int i = g_file_open_tmp ("mono_aot_XXXXXX", &acfg->tmpfname, NULL);
10260 acfg->fp = fdopen (i, "w+");
10262 if (acfg->fp == 0 && !acfg->aot_opts.llvm_only) {
10263 aot_printerrf (acfg, "Unable to open file '%s': %s\n", acfg->tmpfname, strerror (errno));
10267 acfg->w = mono_img_writer_create (acfg->fp, FALSE);
10269 tmp_outfile_name = NULL;
10270 outfile_name = NULL;
10272 /* Compute symbols for methods */
10273 for (i = 0; i < acfg->nmethods; ++i) {
10274 if (acfg->cfgs [i]) {
10275 MonoCompile *cfg = acfg->cfgs [i];
10276 int method_index = get_method_index (acfg, cfg->orig_method);
10278 if (COMPILE_LLVM (cfg))
10279 cfg->asm_symbol = g_strdup_printf ("%s%s", acfg->llvm_label_prefix, cfg->llvm_method_name);
10280 else if (acfg->global_symbols || acfg->llvm)
10281 cfg->asm_symbol = get_debug_sym (cfg->orig_method, "", acfg->method_label_hash);
10283 cfg->asm_symbol = g_strdup_printf ("%s%sm_%x", acfg->temp_prefix, acfg->llvm_label_prefix, method_index);
10284 cfg->asm_debug_symbol = cfg->asm_symbol;
10288 if (acfg->aot_opts.dwarf_debug && acfg->aot_opts.asm_only && acfg->aot_opts.gnu_asm) {
10290 * CLANG supports GAS .file/.loc directives, so emit line number information this way
10291 * FIXME: CLANG only emits line number info for .loc directives followed by assembly, not
10292 * .byte directives.
10294 //acfg->gas_line_numbers = TRUE;
10297 if ((!acfg->aot_opts.nodebug || acfg->aot_opts.dwarf_debug) && acfg->has_jitted_code) {
10298 if (acfg->aot_opts.dwarf_debug && !mono_debug_enabled ()) {
10299 aot_printerrf (acfg, "The dwarf AOT option requires the --debug option.\n");
10302 acfg->dwarf = mono_dwarf_writer_create (acfg->w, NULL, 0, FALSE, !acfg->gas_line_numbers);
10306 mono_img_writer_emit_start (acfg->w);
10309 mono_dwarf_writer_emit_base_info (acfg->dwarf, g_path_get_basename (acfg->image->name), mono_unwind_get_cie_program ());
10315 emit_extra_methods (acfg);
10317 emit_trampolines (acfg);
10319 emit_class_name_table (acfg);
10321 emit_got_info (acfg, FALSE);
10323 emit_got_info (acfg, TRUE);
10325 emit_exception_info (acfg);
10327 emit_unwind_info (acfg);
10329 emit_class_info (acfg);
10333 emit_image_table (acfg);
10339 * The managed allocators are GC specific, so can't use an AOT image created by one GC
10342 const char *gc_name = mono_gc_get_gc_name ();
10343 acfg->gc_name_offset = add_to_blob (acfg, (guint8*)gc_name, strlen (gc_name) + 1);
10348 emit_objc_selectors (acfg);
10350 emit_globals (acfg);
10352 emit_file_info (acfg);
10355 emit_dwarf_info (acfg);
10356 mono_dwarf_writer_close (acfg->dwarf);
10359 emit_mem_end (acfg);
10361 if (acfg->need_pt_gnu_stack) {
10362 /* This is required so the .so doesn't have an executable stack */
10363 /* The bin writer already emits this */
10364 fprintf (acfg->fp, "\n.section .note.GNU-stack,\"\",@progbits\n");
10367 if (acfg->aot_opts.data_outfile)
10368 fclose (acfg->data_outfile);
10374 res = emit_llvm_file (acfg);
10382 acfg->stats.gen_time = TV_ELAPSED (atv, btv);
10385 sprintf (llvm_stats_msg, ", LLVM: %d (%d%%)", acfg->stats.llvm_count, acfg->stats.mcount ? (acfg->stats.llvm_count * 100) / acfg->stats.mcount : 100);
10387 strcpy (llvm_stats_msg, "");
10389 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;
10391 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",
10392 (int)acfg->stats.code_size, (int)(acfg->stats.code_size * 100 / all_sizes),
10393 (int)acfg->stats.info_size, (int)(acfg->stats.info_size * 100 / all_sizes),
10394 (int)acfg->stats.ex_info_size, (int)(acfg->stats.ex_info_size * 100 / all_sizes),
10395 (int)acfg->stats.unwind_info_size, (int)(acfg->stats.unwind_info_size * 100 / all_sizes),
10396 (int)acfg->stats.class_info_size, (int)(acfg->stats.class_info_size * 100 / all_sizes),
10397 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,
10398 (int)acfg->stats.got_info_size, (int)(acfg->stats.got_info_size * 100 / all_sizes),
10399 (int)acfg->stats.offsets_size, (int)(acfg->stats.offsets_size * 100 / all_sizes),
10400 (int)(acfg->got_offset * sizeof (gpointer)));
10401 aot_printf (acfg, "Compiled: %d/%d (%d%%)%s, No GOT slots: %d (%d%%), Direct calls: %d (%d%%)\n",
10402 acfg->stats.ccount, acfg->stats.mcount, acfg->stats.mcount ? (acfg->stats.ccount * 100) / acfg->stats.mcount : 100,
10404 acfg->stats.methods_without_got_slots, acfg->stats.mcount ? (acfg->stats.methods_without_got_slots * 100) / acfg->stats.mcount : 100,
10405 acfg->stats.direct_calls, acfg->stats.all_calls ? (acfg->stats.direct_calls * 100) / acfg->stats.all_calls : 100);
10406 if (acfg->stats.genericcount)
10407 aot_printf (acfg, "%d methods are generic (%d%%)\n", acfg->stats.genericcount, acfg->stats.mcount ? (acfg->stats.genericcount * 100) / acfg->stats.mcount : 100);
10408 if (acfg->stats.abscount)
10409 aot_printf (acfg, "%d methods contain absolute addresses (%d%%)\n", acfg->stats.abscount, acfg->stats.mcount ? (acfg->stats.abscount * 100) / acfg->stats.mcount : 100);
10410 if (acfg->stats.lmfcount)
10411 aot_printf (acfg, "%d methods contain lmf pointers (%d%%)\n", acfg->stats.lmfcount, acfg->stats.mcount ? (acfg->stats.lmfcount * 100) / acfg->stats.mcount : 100);
10412 if (acfg->stats.ocount)
10413 aot_printf (acfg, "%d methods have other problems (%d%%)\n", acfg->stats.ocount, acfg->stats.mcount ? (acfg->stats.ocount * 100) / acfg->stats.mcount : 100);
10417 res = mono_img_writer_emit_writeout (acfg->w);
10422 res = compile_asm (acfg);
10429 acfg->stats.link_time = TV_ELAPSED (atv, btv);
10431 if (acfg->aot_opts.stats) {
10434 aot_printf (acfg, "GOT slot distribution:\n");
10435 for (i = 0; i < MONO_PATCH_INFO_NONE; ++i)
10436 if (acfg->stats.got_slot_types [i])
10437 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]);
10438 aot_printf (acfg, "\nMethod stats:\n");
10439 aot_printf (acfg, "\tNormal: %d\n", acfg->stats.method_categories [METHOD_CAT_NORMAL]);
10440 aot_printf (acfg, "\tInstance: %d\n", acfg->stats.method_categories [METHOD_CAT_INST]);
10441 aot_printf (acfg, "\tGSharedvt: %d\n", acfg->stats.method_categories [METHOD_CAT_GSHAREDVT]);
10442 aot_printf (acfg, "\tWrapper: %d\n", acfg->stats.method_categories [METHOD_CAT_WRAPPER]);
10445 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);
10447 if (acfg->aot_opts.dump_json)
10460 mono_aot_readonly_field_override (MonoClassField *field)
10466 mono_compile_assembly (MonoAssembly *ass, guint32 opts, const char *aot_options)
10472 mono_aot_is_shared_got_offset (int offset)