2 * aot-compiler.c: mono Ahead of Time compiler
5 * Dietmar Maurer (dietmar@ximian.com)
6 * Zoltan Varga (vargaz@gmail.com)
8 * (C) 2002 Ximian, Inc.
9 * Copyright 2003-2011 Novell, Inc
10 * Copyright 2011 Xamarin Inc (http://www.xamarin.com)
14 #include <sys/types.h>
34 #include <mono/metadata/abi-details.h>
35 #include <mono/metadata/tabledefs.h>
36 #include <mono/metadata/class.h>
37 #include <mono/metadata/object.h>
38 #include <mono/metadata/tokentype.h>
39 #include <mono/metadata/appdomain.h>
40 #include <mono/metadata/debug-helpers.h>
41 #include <mono/metadata/assembly.h>
42 #include <mono/metadata/metadata-internals.h>
43 #include <mono/metadata/marshal.h>
44 #include <mono/metadata/gc-internal.h>
45 #include <mono/metadata/mempool-internals.h>
46 #include <mono/metadata/mono-endian.h>
47 #include <mono/metadata/threads-types.h>
48 #include <mono/utils/mono-logger-internal.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>
55 #include "seq-points.h"
56 #include "image-writer.h"
57 #include "dwarfwriter.h"
60 #if !defined(DISABLE_AOT) && !defined(DISABLE_JIT)
62 #if defined(__linux__) || defined(__native_client_codegen__)
63 #define RODATA_SECT ".rodata"
64 #elif defined(TARGET_MACH)
65 #define RODATA_SECT ".section __TEXT, __const"
67 #define RODATA_SECT ".text"
70 #define TV_DECLARE(name) gint64 name
71 #define TV_GETTIME(tv) tv = mono_100ns_ticks ()
72 #define TV_ELAPSED(start,end) (((end) - (start)) / 10)
74 #define ALIGN_TO(val,align) ((((guint64)val) + ((align) - 1)) & ~((align) - 1))
75 #define ALIGN_PTR_TO(ptr,align) (gpointer)((((gssize)(ptr)) + (align - 1)) & (~(align - 1)))
76 #define ROUND_DOWN(VALUE,SIZE) ((VALUE) & ~((SIZE) - 1))
78 /* predefined values for static readonly fields without needed to run the .cctor */
79 typedef struct _ReadOnlyValue ReadOnlyValue;
80 struct _ReadOnlyValue {
83 int type; /* to be used later for typechecking to prevent user errors */
92 static ReadOnlyValue *readonly_values;
94 typedef struct MonoAotOptions {
98 gboolean write_symbols;
99 gboolean metadata_only;
100 gboolean bind_to_runtime_version;
103 gboolean static_link;
107 gboolean dwarf_debug;
109 gboolean log_generics;
110 gboolean log_instances;
111 gboolean gen_seq_points_file;
112 gboolean direct_pinvoke;
113 gboolean direct_icalls;
114 gboolean no_direct_calls;
115 gboolean use_trampolines_page;
116 gboolean no_instances;
122 int nrgctx_trampolines;
123 int nimt_trampolines;
124 int ngsharedvt_arg_trampolines;
125 int nrgctx_fetch_trampolines;
126 gboolean print_skipped_methods;
133 char *instances_logfile_path;
138 typedef struct MonoAotStats {
139 int ccount, mcount, lmfcount, abscount, gcount, ocount, genericcount;
140 gint64 code_size, info_size, ex_info_size, unwind_info_size, got_size, class_info_size, got_info_size, plt_size;
141 int methods_without_got_slots, direct_calls, all_calls, llvm_count;
142 int got_slots, offsets_size;
143 int got_slot_types [MONO_PATCH_INFO_NONE];
144 int got_slot_info_sizes [MONO_PATCH_INFO_NONE];
145 int jit_time, gen_time, link_time;
148 typedef struct GotInfo {
149 GHashTable *patch_to_got_offset;
150 GHashTable **patch_to_got_offset_by_type;
151 GPtrArray *got_patches;
154 typedef struct MonoAotCompile {
157 GHashTable *method_indexes;
158 GHashTable *method_depth;
161 GHashTable **patch_to_plt_entry;
162 GHashTable *plt_offset_to_entry;
163 //GHashTable *patch_to_got_offset;
164 //GHashTable **patch_to_got_offset_by_type;
165 //GPtrArray *got_patches;
166 GotInfo got_info, llvm_got_info;
167 GHashTable *image_hash;
168 GHashTable *method_to_cfg;
169 GHashTable *token_info_hash;
170 GHashTable *method_to_pinvoke_import;
171 GPtrArray *extra_methods;
172 GPtrArray *image_table;
174 GPtrArray *method_order;
175 GHashTable *export_names;
176 /* Maps MonoClass* -> blob offset */
177 GHashTable *klass_blob_hash;
178 /* Maps MonoMethod* -> blob offset */
179 GHashTable *method_blob_hash;
180 guint32 *plt_got_info_offsets;
181 guint32 got_offset, llvm_got_offset, plt_offset, plt_got_offset_base;
182 /* Number of GOT entries reserved for trampolines */
183 guint32 num_trampoline_got_entries;
184 guint32 tramp_page_size;
186 guint32 num_trampolines [MONO_AOT_TRAMP_NUM];
187 guint32 trampoline_got_offset_base [MONO_AOT_TRAMP_NUM];
188 guint32 trampoline_size [MONO_AOT_TRAMP_NUM];
189 guint32 tramp_page_code_offsets [MONO_AOT_TRAMP_NUM];
191 MonoAotOptions aot_opts;
195 MonoMemPool *mempool;
198 char *static_linking_symbol;
200 gboolean gas_line_numbers;
201 /* Whenever to emit an object file directly from llc */
202 gboolean llvm_owriter;
204 MonoDwarfWriter *dwarf;
211 GHashTable *unwind_info_offsets;
212 GPtrArray *unwind_ops;
213 guint32 unwind_info_offset;
216 char *llvm_got_symbol;
218 char *llvm_eh_frame_symbol;
219 GHashTable *method_label_hash;
220 const char *temp_prefix;
221 const char *user_symbol_prefix;
222 const char *llvm_label_prefix;
223 const char *inst_directive;
225 guint32 label_generator;
227 gboolean has_jitted_code;
228 MonoAotFileFlags flags;
229 MonoDynamicStream blob;
230 MonoClass **typespec_classes;
233 char *assembly_name_sym;
234 GHashTable *plt_entry_debug_sym_cache;
235 gboolean thumb_mixed, need_no_dead_strip, need_pt_gnu_stack;
236 GHashTable *ginst_hash;
237 GHashTable *dwarf_ln_filenames;
238 gboolean global_symbols;
239 int objc_selector_index, objc_selector_index_2;
240 GPtrArray *objc_selectors;
241 GHashTable *objc_selector_to_index;
243 FILE *instances_logfile;
248 char *symbol, *llvm_symbol, *debug_sym;
250 gboolean jit_used, llvm_used;
253 #define mono_acfg_lock(acfg) mono_mutex_lock (&((acfg)->mutex))
254 #define mono_acfg_unlock(acfg) mono_mutex_unlock (&((acfg)->mutex))
256 /* This points to the current acfg in LLVM mode */
257 static MonoAotCompile *llvm_acfg;
259 #ifdef HAVE_ARRAY_ELEM_INIT
260 #define MSGSTRFIELD(line) MSGSTRFIELD1(line)
261 #define MSGSTRFIELD1(line) str##line
262 static const struct msgstr_t {
263 #define PATCH_INFO(a,b) char MSGSTRFIELD(__LINE__) [sizeof (b)];
264 #include "patch-info.h"
267 #define PATCH_INFO(a,b) b,
268 #include "patch-info.h"
271 static const gint16 opidx [] = {
272 #define PATCH_INFO(a,b) [MONO_PATCH_INFO_ ## a] = offsetof (struct msgstr_t, MSGSTRFIELD(__LINE__)),
273 #include "patch-info.h"
277 static G_GNUC_UNUSED const char*
278 get_patch_name (int info)
280 return (const char*)&opstr + opidx [info];
284 #define PATCH_INFO(a,b) b,
285 static const char* const
286 patch_types [MONO_PATCH_INFO_NUM + 1] = {
287 #include "patch-info.h"
291 static G_GNUC_UNUSED const char*
292 get_patch_name (int info)
294 return patch_types [info];
300 get_unwind_info_offset (MonoAotCompile *acfg, guint8 *encoded, guint32 encoded_len);
303 get_plt_entry_debug_sym (MonoAotCompile *acfg, MonoJumpInfo *ji, GHashTable *cache);
306 aot_printf (MonoAotCompile *acfg, const gchar *format, ...)
312 output = acfg->logfile;
316 va_start (args, format);
317 vfprintf (output, format, args);
322 aot_printerrf (MonoAotCompile *acfg, const gchar *format, ...)
328 output = acfg->logfile;
332 va_start (args, format);
333 vfprintf (output, format, args);
338 report_loader_error (MonoAotCompile *acfg, MonoError *error, const char *format, ...)
343 if (mono_error_ok (error))
347 output = acfg->logfile;
351 va_start (args, format);
352 vfprintf (output, format, args);
354 mono_error_cleanup (error);
356 g_error ("FullAOT cannot continue if there are loader errors");
359 /* Wrappers around the image writer functions */
362 emit_section_change (MonoAotCompile *acfg, const char *section_name, int subsection_index)
364 mono_img_writer_emit_section_change (acfg->w, section_name, subsection_index);
368 emit_local_symbol (MonoAotCompile *acfg, const char *name, const char *end_label, gboolean func)
370 mono_img_writer_emit_local_symbol (acfg->w, name, end_label, func);
374 emit_label (MonoAotCompile *acfg, const char *name)
376 mono_img_writer_emit_label (acfg->w, name);
380 emit_bytes (MonoAotCompile *acfg, const guint8* buf, int size)
382 mono_img_writer_emit_bytes (acfg->w, buf, size);
386 emit_string (MonoAotCompile *acfg, const char *value)
388 mono_img_writer_emit_string (acfg->w, value);
392 emit_line (MonoAotCompile *acfg)
394 mono_img_writer_emit_line (acfg->w);
398 emit_alignment (MonoAotCompile *acfg, int size)
400 mono_img_writer_emit_alignment (acfg->w, size);
404 emit_alignment_code (MonoAotCompile *acfg, int size)
406 if (acfg->align_pad_value)
407 mono_img_writer_emit_alignment_fill (acfg->w, size, acfg->align_pad_value);
409 mono_img_writer_emit_alignment (acfg->w, size);
413 emit_padding (MonoAotCompile *acfg, int size)
418 if (acfg->align_pad_value) {
419 for (i = 0; i < 16; ++i)
420 buf [i] = acfg->align_pad_value;
422 memset (buf, 0, sizeof (buf));
425 for (i = 0; i < size; i += 16) {
427 emit_bytes (acfg, buf, size - i);
429 emit_bytes (acfg, buf, 16);
434 emit_pointer (MonoAotCompile *acfg, const char *target)
436 mono_img_writer_emit_pointer (acfg->w, target);
440 emit_pointer_2 (MonoAotCompile *acfg, const char *prefix, const char *target)
442 if (prefix [0] != '\0') {
443 char *s = g_strdup_printf ("%s%s", prefix, target);
444 mono_img_writer_emit_pointer (acfg->w, s);
447 mono_img_writer_emit_pointer (acfg->w, target);
452 emit_int16 (MonoAotCompile *acfg, int value)
454 mono_img_writer_emit_int16 (acfg->w, value);
458 emit_int32 (MonoAotCompile *acfg, int value)
460 mono_img_writer_emit_int32 (acfg->w, value);
464 emit_symbol_diff (MonoAotCompile *acfg, const char *end, const char* start, int offset)
466 mono_img_writer_emit_symbol_diff (acfg->w, end, start, offset);
470 emit_zero_bytes (MonoAotCompile *acfg, int num)
472 mono_img_writer_emit_zero_bytes (acfg->w, num);
476 emit_byte (MonoAotCompile *acfg, guint8 val)
478 mono_img_writer_emit_byte (acfg->w, val);
481 #ifdef __native_client_codegen__
483 emit_nacl_call_alignment (MonoAotCompile *acfg)
485 mono_img_writer_emit_nacl_call_alignment (acfg->w);
489 static G_GNUC_UNUSED void
490 emit_global_inner (MonoAotCompile *acfg, const char *name, gboolean func)
492 mono_img_writer_emit_global (acfg->w, name, func);
496 emit_global (MonoAotCompile *acfg, const char *name, gboolean func)
498 if (acfg->aot_opts.no_dlsym) {
499 g_ptr_array_add (acfg->globals, g_strdup (name));
500 mono_img_writer_emit_local_symbol (acfg->w, name, NULL, func);
502 mono_img_writer_emit_global (acfg->w, name, func);
507 emit_symbol_size (MonoAotCompile *acfg, const char *name, const char *end_label)
509 mono_img_writer_emit_symbol_size (acfg->w, name, end_label);
512 /* Emit a symbol which is referenced by the MonoAotFileInfo structure */
514 emit_info_symbol (MonoAotCompile *acfg, const char *name)
519 emit_label (acfg, name);
520 /* LLVM generated code references this */
521 sprintf (symbol, "%s%s%s", acfg->user_symbol_prefix, acfg->global_prefix, name);
522 emit_label (acfg, symbol);
523 emit_global_inner (acfg, symbol, FALSE);
525 emit_label (acfg, name);
530 emit_string_symbol (MonoAotCompile *acfg, const char *name, const char *value)
533 mono_llvm_emit_aot_data (name, (guint8*)value, strlen (value) + 1);
537 mono_img_writer_emit_section_change (acfg->w, RODATA_SECT, 1);
539 /* On apple, all symbols need to be aligned to avoid warnings from ld */
540 emit_alignment (acfg, 4);
542 mono_img_writer_emit_label (acfg->w, name);
543 mono_img_writer_emit_string (acfg->w, value);
546 static G_GNUC_UNUSED void
547 emit_uleb128 (MonoAotCompile *acfg, guint32 value)
550 guint8 b = value & 0x7f;
552 if (value != 0) /* more bytes to come */
558 static G_GNUC_UNUSED void
559 emit_sleb128 (MonoAotCompile *acfg, gint64 value)
562 gboolean negative = (value < 0);
569 /* the following is unnecessary if the
570 * implementation of >>= uses an arithmetic rather
571 * than logical shift for a signed left operand
575 value |= - ((gint64)1 <<(size - 7));
576 /* sign bit of byte is second high order bit (0x40) */
577 if ((value == 0 && !(byte & 0x40)) ||
578 (value == -1 && (byte & 0x40)))
582 emit_byte (acfg, byte);
586 static G_GNUC_UNUSED void
587 encode_uleb128 (guint32 value, guint8 *buf, guint8 **endbuf)
592 guint8 b = value & 0x7f;
594 if (value != 0) /* more bytes to come */
602 static G_GNUC_UNUSED void
603 encode_sleb128 (gint32 value, guint8 *buf, guint8 **endbuf)
606 gboolean negative = (value < 0);
614 /* the following is unnecessary if the
615 * implementation of >>= uses an arithmetic rather
616 * than logical shift for a signed left operand
620 value |= - (1 <<(size - 7));
621 /* sign bit of byte is second high order bit (0x40) */
622 if ((value == 0 && !(byte & 0x40)) ||
623 (value == -1 && (byte & 0x40)))
634 encode_int (gint32 val, guint8 *buf, guint8 **endbuf)
637 buf [0] = (val >> 0) & 0xff;
638 buf [1] = (val >> 8) & 0xff;
639 buf [2] = (val >> 16) & 0xff;
640 buf [3] = (val >> 24) & 0xff;
646 encode_int16 (guint16 val, guint8 *buf, guint8 **endbuf)
648 buf [0] = (val >> 0) & 0xff;
649 buf [1] = (val >> 8) & 0xff;
655 encode_string (const char *s, guint8 *buf, guint8 **endbuf)
657 int len = strlen (s);
659 memcpy (buf, s, len + 1);
660 *endbuf = buf + len + 1;
664 emit_unset_mode (MonoAotCompile *acfg)
666 mono_img_writer_emit_unset_mode (acfg->w);
669 static G_GNUC_UNUSED void
670 emit_set_thumb_mode (MonoAotCompile *acfg)
672 emit_unset_mode (acfg);
673 fprintf (acfg->fp, ".code 16\n");
676 static G_GNUC_UNUSED void
677 emit_set_arm_mode (MonoAotCompile *acfg)
679 emit_unset_mode (acfg);
680 fprintf (acfg->fp, ".code 32\n");
684 emit_code_bytes (MonoAotCompile *acfg, const guint8* buf, int size)
689 g_assert (size % 4 == 0);
690 emit_unset_mode (acfg);
691 for (i = 0; i < size; i += 4)
692 fprintf (acfg->fp, "%s 0x%x\n", acfg->inst_directive, *(guint32*)(buf + i));
694 emit_bytes (acfg, buf, size);
698 /* ARCHITECTURE SPECIFIC CODE */
700 #if defined(TARGET_X86) || defined(TARGET_AMD64) || defined(TARGET_ARM) || defined(TARGET_POWERPC) || defined(TARGET_ARM64)
701 #define EMIT_DWARF_INFO 1
704 #if defined(TARGET_ARM)
705 #define AOT_FUNC_ALIGNMENT 4
707 #define AOT_FUNC_ALIGNMENT 16
709 #if (defined(TARGET_X86) || defined(TARGET_AMD64)) && defined(__native_client_codegen__)
710 #undef AOT_FUNC_ALIGNMENT
711 #define AOT_FUNC_ALIGNMENT 32
714 #if defined(TARGET_POWERPC64) && !defined(__mono_ilp32__)
715 #define PPC_LD_OP "ld"
716 #define PPC_LDX_OP "ldx"
718 #define PPC_LD_OP "lwz"
719 #define PPC_LDX_OP "lwzx"
723 #define AOT_TARGET_STR "AMD64"
728 #define AOT_TARGET_STR "ARM (MACH)"
730 #define AOT_TARGET_STR "ARM (!MACH)"
736 #define AOT_TARGET_STR "ARM64 (MACH)"
738 #define AOT_TARGET_STR "ARM64 (!MACH)"
742 #ifdef TARGET_POWERPC64
743 #ifdef __mono_ilp32__
744 #define AOT_TARGET_STR "POWERPC64 (mono ilp32)"
746 #define AOT_TARGET_STR "POWERPC64 (!mono ilp32)"
749 #ifdef TARGET_POWERPC
750 #ifdef __mono_ilp32__
751 #define AOT_TARGET_STR "POWERPC (mono ilp32)"
753 #define AOT_TARGET_STR "POWERPC (!mono ilp32)"
760 #define AOT_TARGET_STR "X86 (WIN32)"
761 #elif defined(__native_client_codegen__)
762 #define AOT_TARGET_STR "X86 (native client codegen)"
764 #define AOT_TARGET_STR "X86 (!native client codegen)"
768 #ifndef AOT_TARGET_STR
769 #define AOT_TARGET_STR ""
773 arch_init (MonoAotCompile *acfg)
775 acfg->llc_args = g_string_new ("");
776 acfg->as_args = g_string_new ("");
779 * The prefix LLVM likes to put in front of symbol names on darwin.
780 * The mach-os specs require this for globals, but LLVM puts them in front of all
781 * symbols. We need to handle this, since we need to refer to LLVM generated
784 acfg->llvm_label_prefix = "";
785 acfg->user_symbol_prefix = "";
787 #if defined(TARGET_X86)
788 g_string_append (acfg->llc_args, " -march=x86 -mattr=sse4.1");
791 #if defined(TARGET_AMD64)
792 g_string_append (acfg->llc_args, " -march=x86-64 -mattr=sse4.1");
794 acfg->align_pad_value = 0x90;
798 if (acfg->aot_opts.mtriple && strstr (acfg->aot_opts.mtriple, "darwin")) {
799 g_string_append (acfg->llc_args, "-mattr=+v6");
802 g_string_append (acfg->llc_args, " -mattr=+vfp2,-neon,+d16");
803 g_string_append (acfg->as_args, " -mfpu=vfp3");
805 g_string_append (acfg->llc_args, " -soft-float");
808 if (acfg->aot_opts.mtriple && strstr (acfg->aot_opts.mtriple, "thumb"))
809 acfg->thumb_mixed = TRUE;
811 if (acfg->aot_opts.mtriple)
812 mono_arch_set_target (acfg->aot_opts.mtriple);
816 acfg->inst_directive = ".inst";
817 if (acfg->aot_opts.mtriple)
818 mono_arch_set_target (acfg->aot_opts.mtriple);
822 acfg->user_symbol_prefix = "_";
823 acfg->llvm_label_prefix = "_";
824 acfg->inst_directive = ".word";
825 acfg->need_no_dead_strip = TRUE;
826 acfg->aot_opts.gnu_asm = TRUE;
829 #if defined(__linux__) && !defined(TARGET_ARM)
830 acfg->need_pt_gnu_stack = TRUE;
834 acfg->global_symbols = TRUE;
840 #include "../../../mono-extensions/mono/mini/aot-compiler-arm64.c"
844 #ifdef MONO_ARCH_AOT_SUPPORTED
846 * arch_emit_direct_call:
848 * Emit a direct call to the symbol TARGET. CALL_SIZE is set to the size of the
852 arch_emit_direct_call (MonoAotCompile *acfg, const char *target, gboolean external, gboolean thumb, MonoJumpInfo *ji, int *call_size)
854 #if defined(TARGET_X86) || defined(TARGET_AMD64)
855 /* Need to make sure this is exactly 5 bytes long */
856 emit_unset_mode (acfg);
857 fprintf (acfg->fp, "call %s\n", target);
859 #elif defined(TARGET_ARM)
860 emit_unset_mode (acfg);
862 fprintf (acfg->fp, "blx %s\n", target);
864 fprintf (acfg->fp, "bl %s\n", target);
866 #elif defined(TARGET_ARM64)
867 arm64_emit_direct_call (acfg, target, external, thumb, ji, call_size);
868 #elif defined(TARGET_POWERPC)
869 emit_unset_mode (acfg);
870 fprintf (acfg->fp, "bl %s\n", target);
873 g_assert_not_reached ();
880 * - we use an approach similar to the x86 abi: reserve a register (r30) to hold
882 * - The full-aot trampolines need access to the GOT of mscorlib, so we store
883 * in in the 2. slot of every GOT, and require every method to place the GOT
884 * address in r30, even when it doesn't access the GOT otherwise. This way,
885 * the trampolines can compute the mscorlib GOT address by loading 4(r30).
890 * PPC64 uses function descriptors which greatly complicate all code, since
891 * these are used very inconsistently in the runtime. Some functions like
892 * mono_compile_method () return ftn descriptors, while others like the
893 * trampoline creation functions do not.
894 * We assume that all GOT slots contain function descriptors, and create
895 * descriptors in aot-runtime.c when needed.
896 * The ppc64 abi uses r2 to hold the address of the TOC/GOT, which is loaded
897 * from function descriptors, we could do the same, but it would require
898 * rewriting all the ppc/aot code to handle function descriptors properly.
899 * So instead, we use the same approach as on PPC32.
900 * This is a horrible mess, but fixing it would probably lead to an even bigger
906 * - similar to the PPC32 design, we reserve EBX to hold the GOT pointer.
909 #ifdef MONO_ARCH_AOT_SUPPORTED
911 * arch_emit_got_offset:
913 * The memory pointed to by CODE should hold native code for computing the GOT
914 * address (OP_LOAD_GOTADDR). Emit this code while patching it with the offset
915 * between code and the GOT. CODE_SIZE is set to the number of bytes emitted.
918 arch_emit_got_offset (MonoAotCompile *acfg, guint8 *code, int *code_size)
920 #if defined(TARGET_POWERPC64)
921 emit_unset_mode (acfg);
923 * The ppc32 code doesn't seem to work on ppc64, the assembler complains about
924 * unsupported relocations. So we store the got address into the .Lgot_addr
925 * symbol which is in the text segment, compute its address, and load it.
927 fprintf (acfg->fp, ".L%d:\n", acfg->label_generator);
928 fprintf (acfg->fp, "lis 0, (.Lgot_addr + 4 - .L%d)@h\n", acfg->label_generator);
929 fprintf (acfg->fp, "ori 0, 0, (.Lgot_addr + 4 - .L%d)@l\n", acfg->label_generator);
930 fprintf (acfg->fp, "add 30, 30, 0\n");
931 fprintf (acfg->fp, "%s 30, 0(30)\n", PPC_LD_OP);
932 acfg->label_generator ++;
934 #elif defined(TARGET_POWERPC)
935 emit_unset_mode (acfg);
936 fprintf (acfg->fp, ".L%d:\n", acfg->label_generator);
937 fprintf (acfg->fp, "lis 0, (%s + 4 - .L%d)@h\n", acfg->got_symbol, acfg->label_generator);
938 fprintf (acfg->fp, "ori 0, 0, (%s + 4 - .L%d)@l\n", acfg->got_symbol, acfg->label_generator);
939 acfg->label_generator ++;
942 guint32 offset = mono_arch_get_patch_offset (code);
943 emit_bytes (acfg, code, offset);
944 emit_symbol_diff (acfg, acfg->got_symbol, ".", offset);
946 *code_size = offset + 4;
951 * arch_emit_got_access:
953 * The memory pointed to by CODE should hold native code for loading a GOT
954 * slot (OP_AOTCONST/OP_GOT_ENTRY). Emit this code while patching it so it accesses the
955 * GOT slot GOT_SLOT. CODE_SIZE is set to the number of bytes emitted.
958 arch_emit_got_access (MonoAotCompile *acfg, const char *got_symbol, guint8 *code, int got_slot, int *code_size)
961 /* mov reg, got+offset(%rip) */
963 /* The GOT symbol is in the LLVM module, the clang assembler has problems emitting symbol diffs for it */
967 /* Decode reg, see amd64_mov_reg_membase () */
968 rex_r = code [0] & AMD64_REX_R;
969 g_assert (code [0] == 0x49 + rex_r);
970 g_assert (code [1] == 0x8b);
971 dreg = ((code [2] >> 3) & 0x7) + (rex_r ? 8 : 0);
973 emit_unset_mode (acfg);
974 fprintf (acfg->fp, "mov %s+%d(%%rip), %s\n", got_symbol, (unsigned int) ((got_slot * sizeof (gpointer))), mono_arch_regname (dreg));
977 emit_bytes (acfg, code, mono_arch_get_patch_offset (code));
978 emit_symbol_diff (acfg, got_symbol, ".", (unsigned int) ((got_slot * sizeof (gpointer)) - 4));
979 *code_size = mono_arch_get_patch_offset (code) + 4;
981 #elif defined(TARGET_X86)
982 emit_bytes (acfg, code, mono_arch_get_patch_offset (code));
983 emit_int32 (acfg, (unsigned int) ((got_slot * sizeof (gpointer))));
984 *code_size = mono_arch_get_patch_offset (code) + 4;
985 #elif defined(TARGET_ARM)
986 emit_bytes (acfg, code, mono_arch_get_patch_offset (code));
987 emit_symbol_diff (acfg, got_symbol, ".", (unsigned int) ((got_slot * sizeof (gpointer))) - 12);
988 *code_size = mono_arch_get_patch_offset (code) + 4;
989 #elif defined(TARGET_ARM64)
990 emit_bytes (acfg, code, mono_arch_get_patch_offset (code));
991 arm64_emit_got_access (acfg, code, got_slot, code_size);
992 #elif defined(TARGET_POWERPC)
997 emit_bytes (acfg, code, mono_arch_get_patch_offset (code));
999 ppc_load32 (code, ppc_r0, got_slot * sizeof (gpointer));
1000 g_assert (code - buf == 8);
1001 emit_bytes (acfg, buf, code - buf);
1002 *code_size = code - buf;
1005 g_assert_not_reached ();
1011 #ifdef MONO_ARCH_AOT_SUPPORTED
1013 * arch_emit_objc_selector_ref:
1015 * Emit the implementation of OP_OBJC_GET_SELECTOR, which itself implements @selector(foo:) in objective-c.
1018 arch_emit_objc_selector_ref (MonoAotCompile *acfg, guint8 *code, int index, int *code_size)
1020 #if defined(TARGET_ARM)
1023 int lindex = acfg->objc_selector_index_2 ++;
1025 /* Emit ldr.imm/b */
1026 emit_bytes (acfg, code, 8);
1028 sprintf (symbol1, "L_OBJC_SELECTOR_%d", lindex);
1029 sprintf (symbol2, "L_OBJC_SELECTOR_REFERENCES_%d", index);
1031 emit_label (acfg, symbol1);
1032 mono_img_writer_emit_unset_mode (acfg->w);
1033 fprintf (acfg->fp, ".long %s-(%s+12)", symbol2, symbol1);
1036 #elif defined(TARGET_ARM64)
1037 arm64_emit_objc_selector_ref (acfg, code, index, code_size);
1039 g_assert_not_reached ();
1045 * arch_emit_plt_entry:
1047 * Emit code for the PLT entry.
1048 * The plt entry should look like this:
1049 * <indirect jump to GOT_SYMBOL + OFFSET>
1050 * <INFO_OFFSET embedded into the instruction stream>
1053 arch_emit_plt_entry (MonoAotCompile *acfg, const char *got_symbol, int offset, int info_offset)
1055 #if defined(TARGET_X86)
1056 #if defined(__default_codegen__)
1057 /* jmp *<offset>(%ebx) */
1058 emit_byte (acfg, 0xff);
1059 emit_byte (acfg, 0xa3);
1060 emit_int32 (acfg, offset);
1061 /* Used by mono_aot_get_plt_info_offset */
1062 emit_int32 (acfg, info_offset);
1063 #elif defined(__native_client_codegen__)
1064 const guint8 kSizeOfNaClJmp = 11;
1065 guint8 bytes[kSizeOfNaClJmp];
1066 guint8 *pbytes = &bytes[0];
1068 x86_jump_membase32 (pbytes, X86_EBX, offset);
1069 emit_bytes (acfg, bytes, kSizeOfNaClJmp);
1070 /* four bytes of data, used by mono_arch_patch_plt_entry */
1071 /* For Native Client, make this work with data embedded in push. */
1072 emit_byte (acfg, 0x68); /* hide data in a push */
1073 emit_int32 (acfg, info_offset);
1074 emit_alignment (acfg, AOT_FUNC_ALIGNMENT);
1075 #endif /*__native_client_codegen__*/
1076 #elif defined(TARGET_AMD64)
1077 #if defined(__default_codegen__)
1078 emit_unset_mode (acfg);
1079 fprintf (acfg->fp, "jmp *%s+%d(%%rip)\n", got_symbol, offset);
1080 /* Used by mono_aot_get_plt_info_offset */
1081 emit_int32 (acfg, info_offset);
1082 acfg->stats.plt_size += 10;
1083 #elif defined(__native_client_codegen__)
1085 guint8 *buf_aligned = ALIGN_TO(buf, kNaClAlignment);
1086 guint8 *code = buf_aligned;
1088 /* mov <OFFSET>(%rip), %r11d */
1089 emit_byte (acfg, '\x45');
1090 emit_byte (acfg, '\x8b');
1091 emit_byte (acfg, '\x1d');
1092 emit_symbol_diff (acfg, got_symbol, ".", offset - 4);
1094 amd64_jump_reg (code, AMD64_R11);
1095 /* This should be constant for the plt patch */
1096 g_assert ((size_t)(code-buf_aligned) == 10);
1097 emit_bytes (acfg, buf_aligned, code - buf_aligned);
1099 /* Hide data in a push imm32 so it passes validation */
1100 emit_byte (acfg, 0x68); /* push */
1101 emit_int32 (acfg, info_offset);
1102 emit_alignment (acfg, AOT_FUNC_ALIGNMENT);
1103 #endif /*__native_client_codegen__*/
1104 #elif defined(TARGET_ARM)
1109 ARM_LDR_IMM (code, ARMREG_IP, ARMREG_PC, 0);
1110 ARM_LDR_REG_REG (code, ARMREG_PC, ARMREG_PC, ARMREG_IP);
1111 emit_bytes (acfg, buf, code - buf);
1112 emit_symbol_diff (acfg, got_symbol, ".", offset - 4);
1113 /* Used by mono_aot_get_plt_info_offset */
1114 emit_int32 (acfg, info_offset);
1115 #elif defined(TARGET_ARM64)
1116 arm64_emit_plt_entry (acfg, got_symbol, offset, info_offset);
1117 #elif defined(TARGET_POWERPC)
1118 /* The GOT address is guaranteed to be in r30 by OP_LOAD_GOTADDR */
1119 emit_unset_mode (acfg);
1120 fprintf (acfg->fp, "lis 11, %d@h\n", offset);
1121 fprintf (acfg->fp, "ori 11, 11, %d@l\n", offset);
1122 fprintf (acfg->fp, "add 11, 11, 30\n");
1123 fprintf (acfg->fp, "%s 11, 0(11)\n", PPC_LD_OP);
1124 #ifdef PPC_USES_FUNCTION_DESCRIPTOR
1125 fprintf (acfg->fp, "%s 2, %d(11)\n", PPC_LD_OP, (int)sizeof (gpointer));
1126 fprintf (acfg->fp, "%s 11, 0(11)\n", PPC_LD_OP);
1128 fprintf (acfg->fp, "mtctr 11\n");
1129 fprintf (acfg->fp, "bctr\n");
1130 emit_int32 (acfg, info_offset);
1132 g_assert_not_reached ();
1137 * arch_emit_llvm_plt_entry:
1139 * Same as arch_emit_plt_entry, but handles calls from LLVM generated code.
1140 * This is only needed on arm to handle thumb interop.
1143 arch_emit_llvm_plt_entry (MonoAotCompile *acfg, const char *got_symbol, int offset, int info_offset)
1145 #if defined(TARGET_ARM)
1146 /* LLVM calls the PLT entries using bl, so these have to be thumb2 */
1147 /* The caller already transitioned to thumb */
1148 /* The code below should be 12 bytes long */
1149 /* clang has trouble encoding these instructions, so emit the binary */
1151 fprintf (acfg->fp, "ldr ip, [pc, #8]\n");
1152 /* thumb can't encode ld pc, [pc, ip] */
1153 fprintf (acfg->fp, "add ip, pc, ip\n");
1154 fprintf (acfg->fp, "ldr ip, [ip, #0]\n");
1155 fprintf (acfg->fp, "bx ip\n");
1157 emit_set_thumb_mode (acfg);
1158 fprintf (acfg->fp, ".4byte 0xc008f8df\n");
1159 fprintf (acfg->fp, ".2byte 0x44fc\n");
1160 fprintf (acfg->fp, ".4byte 0xc000f8dc\n");
1161 fprintf (acfg->fp, ".2byte 0x4760\n");
1162 emit_symbol_diff (acfg, got_symbol, ".", offset + 4);
1163 emit_int32 (acfg, info_offset);
1164 emit_unset_mode (acfg);
1165 emit_set_arm_mode (acfg);
1167 g_assert_not_reached ();
1171 /* Save unwind_info in the module and emit the offset to the information at symbol */
1172 static void save_unwind_info (MonoAotCompile *acfg, char *symbol, GSList *unwind_ops)
1174 guint32 uw_offset, encoded_len;
1177 emit_section_change (acfg, RODATA_SECT, 0);
1178 emit_global (acfg, symbol, FALSE);
1179 emit_label (acfg, symbol);
1181 encoded = mono_unwind_ops_encode (unwind_ops, &encoded_len);
1182 uw_offset = get_unwind_info_offset (acfg, encoded, encoded_len);
1184 emit_int32 (acfg, uw_offset);
1188 * arch_emit_specific_trampoline_pages:
1190 * Emits a page full of trampolines: each trampoline uses its own address to
1191 * lookup both the generic trampoline code and the data argument.
1192 * This page can be remapped in process multiple times so we can get an
1193 * unlimited number of trampolines.
1194 * Specifically this implementation uses the following trick: two memory pages
1195 * are allocated, with the first containing the data and the second containing the trampolines.
1196 * To reduce trampoline size, each trampoline jumps at the start of the page where a common
1197 * implementation does all the lifting.
1198 * Note that the ARM single trampoline size is 8 bytes, exactly like the data that needs to be stored
1199 * on the arm 32 bit system.
1202 arch_emit_specific_trampoline_pages (MonoAotCompile *acfg)
1204 #if defined(TARGET_ARM)
1207 guint8 *loop_start, *loop_branch_back, *loop_end_check, *imt_found_check;
1209 int pagesize = MONO_AOT_TRAMP_PAGE_SIZE;
1210 GSList *unwind_ops = NULL;
1211 #define COMMON_TRAMP_SIZE 16
1212 int count = (pagesize - COMMON_TRAMP_SIZE) / 8;
1213 int imm8, rot_amount;
1216 if (!acfg->aot_opts.use_trampolines_page)
1219 acfg->tramp_page_size = pagesize;
1221 sprintf (symbol, "%sspecific_trampolines_page", acfg->user_symbol_prefix);
1222 emit_alignment (acfg, pagesize);
1223 emit_global (acfg, symbol, TRUE);
1224 emit_label (acfg, symbol);
1226 /* emit the generic code first, the trampoline address + 8 is in the lr register */
1228 imm8 = mono_arm_is_rotated_imm8 (pagesize, &rot_amount);
1229 ARM_SUB_REG_IMM (code, ARMREG_LR, ARMREG_LR, imm8, rot_amount);
1230 ARM_LDR_IMM (code, ARMREG_R1, ARMREG_LR, -8);
1231 ARM_LDR_IMM (code, ARMREG_PC, ARMREG_LR, -4);
1233 g_assert (code - buf == COMMON_TRAMP_SIZE);
1236 emit_bytes (acfg, buf, code - buf);
1238 for (i = 0; i < count; ++i) {
1240 ARM_PUSH (code, 0x5fff);
1242 arm_patch (code - 4, code - COMMON_TRAMP_SIZE - 8 * (i + 1));
1243 g_assert (code - buf == 8);
1244 emit_bytes (acfg, buf, code - buf);
1247 /* now the rgctx trampolines: each specific trampolines puts in the ip register
1248 * the instruction pointer address, so the generic trampoline at the start of the page
1249 * subtracts 4096 to get to the data page and loads the values
1250 * We again fit the generic trampiline in 16 bytes.
1252 sprintf (symbol, "%srgctx_trampolines_page", acfg->user_symbol_prefix);
1253 emit_global (acfg, symbol, TRUE);
1254 emit_label (acfg, symbol);
1256 imm8 = mono_arm_is_rotated_imm8 (pagesize, &rot_amount);
1257 ARM_SUB_REG_IMM (code, ARMREG_IP, ARMREG_IP, imm8, rot_amount);
1258 ARM_LDR_IMM (code, MONO_ARCH_RGCTX_REG, ARMREG_IP, -8);
1259 ARM_LDR_IMM (code, ARMREG_PC, ARMREG_IP, -4);
1261 g_assert (code - buf == COMMON_TRAMP_SIZE);
1264 emit_bytes (acfg, buf, code - buf);
1266 for (i = 0; i < count; ++i) {
1268 ARM_MOV_REG_REG (code, ARMREG_IP, ARMREG_PC);
1270 arm_patch (code - 4, code - COMMON_TRAMP_SIZE - 8 * (i + 1));
1271 g_assert (code - buf == 8);
1272 emit_bytes (acfg, buf, code - buf);
1276 * gsharedvt arg trampolines: see arch_emit_gsharedvt_arg_trampoline ()
1278 sprintf (symbol, "%sgsharedvt_arg_trampolines_page", acfg->user_symbol_prefix);
1279 emit_global (acfg, symbol, TRUE);
1280 emit_label (acfg, symbol);
1282 ARM_PUSH (code, (1 << ARMREG_R0) | (1 << ARMREG_R1) | (1 << ARMREG_R2) | (1 << ARMREG_R3));
1283 imm8 = mono_arm_is_rotated_imm8 (pagesize, &rot_amount);
1284 ARM_SUB_REG_IMM (code, ARMREG_IP, ARMREG_IP, imm8, rot_amount);
1285 ARM_LDR_IMM (code, ARMREG_R0, ARMREG_IP, -8);
1286 ARM_LDR_IMM (code, ARMREG_PC, ARMREG_IP, -4);
1287 g_assert (code - buf == COMMON_TRAMP_SIZE);
1289 emit_bytes (acfg, buf, code - buf);
1291 for (i = 0; i < count; ++i) {
1293 ARM_MOV_REG_REG (code, ARMREG_IP, ARMREG_PC);
1295 arm_patch (code - 4, code - COMMON_TRAMP_SIZE - 8 * (i + 1));
1296 g_assert (code - buf == 8);
1297 emit_bytes (acfg, buf, code - buf);
1300 /* now the imt trampolines: each specific trampolines puts in the ip register
1301 * the instruction pointer address, so the generic trampoline at the start of the page
1302 * subtracts 4096 to get to the data page and loads the values
1304 #define IMT_TRAMP_SIZE 72
1305 sprintf (symbol, "%simt_trampolines_page", acfg->user_symbol_prefix);
1306 emit_global (acfg, symbol, TRUE);
1307 emit_label (acfg, symbol);
1309 /* Need at least two free registers, plus a slot for storing the pc */
1310 ARM_PUSH (code, (1 << ARMREG_R0)|(1 << ARMREG_R1)|(1 << ARMREG_R2));
1312 imm8 = mono_arm_is_rotated_imm8 (pagesize, &rot_amount);
1313 ARM_SUB_REG_IMM (code, ARMREG_IP, ARMREG_IP, imm8, rot_amount);
1314 ARM_LDR_IMM (code, ARMREG_R0, ARMREG_IP, -8);
1316 /* The IMT method is in v5, r0 has the imt array address */
1319 ARM_LDR_IMM (code, ARMREG_R1, ARMREG_R0, 0);
1320 ARM_CMP_REG_REG (code, ARMREG_R1, ARMREG_V5);
1321 imt_found_check = code;
1322 ARM_B_COND (code, ARMCOND_EQ, 0);
1324 /* End-of-loop check */
1325 ARM_CMP_REG_IMM (code, ARMREG_R1, 0, 0);
1326 loop_end_check = code;
1327 ARM_B_COND (code, ARMCOND_EQ, 0);
1330 ARM_ADD_REG_IMM8 (code, ARMREG_R0, ARMREG_R0, sizeof (gpointer) * 2);
1331 loop_branch_back = code;
1333 arm_patch (loop_branch_back, loop_start);
1336 arm_patch (imt_found_check, code);
1337 ARM_LDR_IMM (code, ARMREG_R0, ARMREG_R0, 4);
1338 ARM_LDR_IMM (code, ARMREG_R0, ARMREG_R0, 0);
1339 /* Save it to the third stack slot */
1340 ARM_STR_IMM (code, ARMREG_R0, ARMREG_SP, 8);
1341 /* Restore the registers and branch */
1342 ARM_POP (code, (1 << ARMREG_R0)|(1 << ARMREG_R1)|(1 << ARMREG_PC));
1345 arm_patch (loop_end_check, code);
1346 ARM_LDR_IMM (code, ARMREG_R0, ARMREG_R0, 4);
1347 ARM_STR_IMM (code, ARMREG_R0, ARMREG_SP, 8);
1348 ARM_POP (code, (1 << ARMREG_R0)|(1 << ARMREG_R1)|(1 << ARMREG_PC));
1352 g_assert (code - buf == IMT_TRAMP_SIZE);
1353 emit_bytes (acfg, buf, code - buf);
1355 for (i = 0; i < count; ++i) {
1357 ARM_MOV_REG_REG (code, ARMREG_IP, ARMREG_PC);
1359 arm_patch (code - 4, code - IMT_TRAMP_SIZE - 8 * (i + 1));
1360 g_assert (code - buf == 8);
1361 emit_bytes (acfg, buf, code - buf);
1364 acfg->tramp_page_code_offsets [MONO_AOT_TRAMP_SPECIFIC] = 16;
1365 acfg->tramp_page_code_offsets [MONO_AOT_TRAMP_STATIC_RGCTX] = 16;
1366 acfg->tramp_page_code_offsets [MONO_AOT_TRAMP_IMT_THUNK] = 72;
1367 acfg->tramp_page_code_offsets [MONO_AOT_TRAMP_GSHAREDVT_ARG] = 16;
1369 /* Unwind info for specifc trampolines */
1370 sprintf (symbol, "%sspecific_trampolines_page_gen_p", acfg->user_symbol_prefix);
1371 /* We unwind to the original caller, from the stack, since lr is clobbered */
1372 mono_add_unwind_op_def_cfa (unwind_ops, 0, 0, ARMREG_SP, 14 * sizeof (mgreg_t));
1373 mono_add_unwind_op_offset (unwind_ops, 0, 0, ARMREG_LR, -4);
1374 save_unwind_info (acfg, symbol, unwind_ops);
1375 mono_free_unwind_info (unwind_ops);
1377 sprintf (symbol, "%sspecific_trampolines_page_sp_p", acfg->user_symbol_prefix);
1378 mono_add_unwind_op_def_cfa (unwind_ops, 0, 0, ARMREG_SP, 0);
1379 mono_add_unwind_op_def_cfa_offset (unwind_ops, 4, 0, 14 * sizeof (mgreg_t));
1380 save_unwind_info (acfg, symbol, unwind_ops);
1381 mono_free_unwind_info (unwind_ops);
1383 /* Unwind info for rgctx trampolines */
1384 sprintf (symbol, "%srgctx_trampolines_page_gen_p", acfg->user_symbol_prefix);
1385 mono_add_unwind_op_def_cfa (unwind_ops, 0, 0, ARMREG_SP, 0);
1386 save_unwind_info (acfg, symbol, unwind_ops);
1388 sprintf (symbol, "%srgctx_trampolines_page_sp_p", acfg->user_symbol_prefix);
1389 save_unwind_info (acfg, symbol, unwind_ops);
1390 mono_free_unwind_info (unwind_ops);
1392 /* Unwind info for gsharedvt trampolines */
1393 sprintf (symbol, "%sgsharedvt_trampolines_page_gen_p", acfg->user_symbol_prefix);
1394 mono_add_unwind_op_def_cfa (unwind_ops, 0, 0, ARMREG_SP, 0);
1395 mono_add_unwind_op_def_cfa_offset (unwind_ops, 4, 0, 4 * sizeof (mgreg_t));
1396 save_unwind_info (acfg, symbol, unwind_ops);
1397 mono_free_unwind_info (unwind_ops);
1399 sprintf (symbol, "%sgsharedvt_trampolines_page_sp_p", acfg->user_symbol_prefix);
1400 mono_add_unwind_op_def_cfa (unwind_ops, 0, 0, ARMREG_SP, 0);
1401 save_unwind_info (acfg, symbol, unwind_ops);
1402 mono_free_unwind_info (unwind_ops);
1404 /* Unwind info for imt trampolines */
1405 sprintf (symbol, "%simt_trampolines_page_gen_p", acfg->user_symbol_prefix);
1406 mono_add_unwind_op_def_cfa (unwind_ops, 0, 0, ARMREG_SP, 0);
1407 mono_add_unwind_op_def_cfa_offset (unwind_ops, 4, 0, 3 * sizeof (mgreg_t));
1408 save_unwind_info (acfg, symbol, unwind_ops);
1409 mono_free_unwind_info (unwind_ops);
1411 sprintf (symbol, "%simt_trampolines_page_sp_p", acfg->user_symbol_prefix);
1412 mono_add_unwind_op_def_cfa (unwind_ops, 0, 0, ARMREG_SP, 0);
1413 save_unwind_info (acfg, symbol, unwind_ops);
1414 mono_free_unwind_info (unwind_ops);
1415 #elif defined(TARGET_ARM64)
1416 arm64_emit_specific_trampoline_pages (acfg);
1421 * arch_emit_specific_trampoline:
1423 * Emit code for a specific trampoline. OFFSET is the offset of the first of
1424 * two GOT slots which contain the generic trampoline address and the trampoline
1425 * argument. TRAMP_SIZE is set to the size of the emitted trampoline.
1428 arch_emit_specific_trampoline (MonoAotCompile *acfg, int offset, int *tramp_size)
1431 * The trampolines created here are variations of the specific
1432 * trampolines created in mono_arch_create_specific_trampoline (). The
1434 * - the generic trampoline address is taken from a got slot.
1435 * - the offset of the got slot where the trampoline argument is stored
1436 * is embedded in the instruction stream, and the generic trampoline
1437 * can load the argument by loading the offset, adding it to the
1438 * address of the trampoline to get the address of the got slot, and
1439 * loading the argument from there.
1440 * - all the trampolines should be of the same length.
1442 #if defined(TARGET_AMD64)
1443 #if defined(__default_codegen__)
1444 /* This should be exactly 8 bytes long */
1446 /* call *<offset>(%rip) */
1448 emit_unset_mode (acfg);
1449 fprintf (acfg->fp, "call *%s+%d(%%rip)\n", acfg->got_symbol, (int)(offset * sizeof (gpointer)));
1450 emit_zero_bytes (acfg, 2);
1452 emit_byte (acfg, '\x41');
1453 emit_byte (acfg, '\xff');
1454 emit_byte (acfg, '\x15');
1455 emit_symbol_diff (acfg, acfg->got_symbol, ".", (offset * sizeof (gpointer)) - 4);
1456 emit_zero_bytes (acfg, 1);
1458 #elif defined(__native_client_codegen__)
1460 guint8 *buf_aligned = ALIGN_TO(buf, kNaClAlignment);
1461 guint8 *code = buf_aligned;
1466 /* Emit this call in 'code' so we can find out how long it is. */
1467 amd64_call_reg (code, AMD64_R11);
1468 call_start = mono_arch_nacl_skip_nops (buf_aligned);
1469 call_len = code - call_start;
1471 /* The tramp_size is twice the NaCl alignment because it starts with */
1472 /* a call which needs to be aligned to the end of the boundary. */
1473 *tramp_size = kNaClAlignment*2;
1475 /* Emit nops to align call site below which is 7 bytes plus */
1476 /* the length of the call sequence emitted above. */
1477 /* Note: this requires the specific trampoline starts on a */
1478 /* kNaclAlignedment aligned address, which it does because */
1479 /* it's its own function that is aligned. */
1480 guint8 nop_buf[256];
1481 guint8 *nopbuf_aligned = ALIGN_TO (nop_buf, kNaClAlignment);
1482 guint8 *nopbuf_end = mono_arch_nacl_pad (nopbuf_aligned, kNaClAlignment - 7 - (call_len));
1483 emit_bytes (acfg, nopbuf_aligned, nopbuf_end - nopbuf_aligned);
1485 /* The trampoline is stored at the offset'th pointer, the -4 is */
1486 /* present because RIP relative addressing starts at the end of */
1487 /* the current instruction, while the label "." is relative to */
1488 /* the beginning of the current asm location, which in this case */
1489 /* is not the mov instruction, but the offset itself, due to the */
1490 /* way the bytes and ints are emitted here. */
1491 got_offset = (offset * sizeof(gpointer)) - 4;
1493 /* mov <OFFSET>(%rip), %r11d */
1494 emit_byte (acfg, '\x45');
1495 emit_byte (acfg, '\x8b');
1496 emit_byte (acfg, '\x1d');
1497 emit_symbol_diff (acfg, acfg->got_symbol, ".", got_offset);
1500 emit_bytes (acfg, call_start, call_len);
1502 /* The arg is stored at the offset+1 pointer, relative to beginning */
1503 /* of trampoline: 7 for mov, plus the call length, and 1 for push. */
1504 got_offset = ((offset + 1) * sizeof(gpointer)) + 7 + call_len + 1;
1506 /* We can't emit this data directly, hide in a "push imm32" */
1507 emit_byte (acfg, '\x68'); /* push */
1508 emit_symbol_diff (acfg, acfg->got_symbol, ".", got_offset);
1509 emit_alignment (acfg, kNaClAlignment);
1510 #endif /*__native_client_codegen__*/
1511 #elif defined(TARGET_ARM)
1515 /* This should be exactly 20 bytes long */
1518 ARM_PUSH (code, 0x5fff);
1519 ARM_LDR_IMM (code, ARMREG_R1, ARMREG_PC, 4);
1520 /* Load the value from the GOT */
1521 ARM_LDR_REG_REG (code, ARMREG_R1, ARMREG_PC, ARMREG_R1);
1523 ARM_BLX_REG (code, ARMREG_R1);
1525 g_assert (code - buf == 16);
1528 emit_bytes (acfg, buf, code - buf);
1530 * Only one offset is needed, since the second one would be equal to the
1533 emit_symbol_diff (acfg, acfg->got_symbol, ".", (offset * sizeof (gpointer)) - 4 + 4);
1534 //emit_symbol_diff (acfg, acfg->got_symbol, ".", ((offset + 1) * sizeof (gpointer)) - 4 + 8);
1535 #elif defined(TARGET_ARM64)
1536 arm64_emit_specific_trampoline (acfg, offset, tramp_size);
1537 #elif defined(TARGET_POWERPC)
1545 * PPC has no ip relative addressing, so we need to compute the address
1546 * of the mscorlib got. That is slow and complex, so instead, we store it
1547 * in the second got slot of every aot image. The caller already computed
1548 * the address of its got and placed it into r30.
1550 emit_unset_mode (acfg);
1551 /* Load mscorlib got address */
1552 fprintf (acfg->fp, "%s 0, %d(30)\n", PPC_LD_OP, (int)sizeof (gpointer));
1553 /* Load generic trampoline address */
1554 fprintf (acfg->fp, "lis 11, %d@h\n", (int)(offset * sizeof (gpointer)));
1555 fprintf (acfg->fp, "ori 11, 11, %d@l\n", (int)(offset * sizeof (gpointer)));
1556 fprintf (acfg->fp, "%s 11, 11, 0\n", PPC_LDX_OP);
1557 #ifdef PPC_USES_FUNCTION_DESCRIPTOR
1558 fprintf (acfg->fp, "%s 11, 0(11)\n", PPC_LD_OP);
1560 fprintf (acfg->fp, "mtctr 11\n");
1561 /* Load trampoline argument */
1562 /* On ppc, we pass it normally to the generic trampoline */
1563 fprintf (acfg->fp, "lis 11, %d@h\n", (int)((offset + 1) * sizeof (gpointer)));
1564 fprintf (acfg->fp, "ori 11, 11, %d@l\n", (int)((offset + 1) * sizeof (gpointer)));
1565 fprintf (acfg->fp, "%s 0, 11, 0\n", PPC_LDX_OP);
1566 /* Branch to generic trampoline */
1567 fprintf (acfg->fp, "bctr\n");
1569 #ifdef PPC_USES_FUNCTION_DESCRIPTOR
1570 *tramp_size = 10 * 4;
1572 *tramp_size = 9 * 4;
1574 #elif defined(TARGET_X86)
1578 /* Similar to the PPC code above */
1580 /* FIXME: Could this clobber the register needed by get_vcall_slot () ? */
1583 /* Load mscorlib got address */
1584 x86_mov_reg_membase (code, X86_ECX, MONO_ARCH_GOT_REG, sizeof (gpointer), 4);
1585 /* Push trampoline argument */
1586 x86_push_membase (code, X86_ECX, (offset + 1) * sizeof (gpointer));
1587 /* Load generic trampoline address */
1588 x86_mov_reg_membase (code, X86_ECX, X86_ECX, offset * sizeof (gpointer), 4);
1589 /* Branch to generic trampoline */
1590 x86_jump_reg (code, X86_ECX);
1592 #ifdef __native_client_codegen__
1594 /* emit nops to next 32 byte alignment */
1595 int a = (~kNaClAlignmentMask) & ((code - buf) + kNaClAlignment - 1);
1596 while (code < (buf + a)) x86_nop(code);
1599 emit_bytes (acfg, buf, code - buf);
1601 *tramp_size = NACL_SIZE(17, kNaClAlignment);
1602 g_assert (code - buf == *tramp_size);
1604 g_assert_not_reached ();
1609 * arch_emit_unbox_trampoline:
1611 * Emit code for the unbox trampoline for METHOD used in the full-aot case.
1612 * CALL_TARGET is the symbol pointing to the native code of METHOD.
1615 arch_emit_unbox_trampoline (MonoAotCompile *acfg, MonoCompile *cfg, MonoMethod *method, const char *call_target)
1617 #if defined(TARGET_AMD64)
1622 this_reg = mono_arch_get_this_arg_reg (NULL);
1624 amd64_alu_reg_imm (code, X86_ADD, this_reg, sizeof (MonoObject));
1626 emit_bytes (acfg, buf, code - buf);
1629 emit_unset_mode (acfg);
1630 fprintf (acfg->fp, "jmp %s\n", call_target);
1632 emit_byte (acfg, '\xe9');
1633 emit_symbol_diff (acfg, call_target, ".", -4);
1635 #elif defined(TARGET_X86)
1642 x86_alu_membase_imm (code, X86_ADD, X86_ESP, this_pos, sizeof (MonoObject));
1644 emit_bytes (acfg, buf, code - buf);
1647 emit_byte (acfg, '\xe9');
1648 emit_symbol_diff (acfg, call_target, ".", -4);
1649 #elif defined(TARGET_ARM)
1653 if (acfg->thumb_mixed && cfg->compile_llvm) {
1654 fprintf (acfg->fp, "add r0, r0, #%d\n", (int)sizeof (MonoObject));
1655 fprintf (acfg->fp, "b %s\n", call_target);
1656 fprintf (acfg->fp, ".arm\n");
1657 fprintf (acfg->fp, ".align 2\n");
1663 ARM_ADD_REG_IMM8 (code, ARMREG_R0, ARMREG_R0, sizeof (MonoObject));
1665 emit_bytes (acfg, buf, code - buf);
1666 /* jump to method */
1667 if (acfg->thumb_mixed && cfg->compile_llvm)
1668 fprintf (acfg->fp, "\n\tbx %s\n", call_target);
1670 fprintf (acfg->fp, "\n\tb %s\n", call_target);
1671 #elif defined(TARGET_ARM64)
1672 arm64_emit_unbox_trampoline (acfg, cfg, method, call_target);
1673 #elif defined(TARGET_POWERPC)
1676 fprintf (acfg->fp, "\n\taddi %d, %d, %d\n", this_pos, this_pos, (int)sizeof (MonoObject));
1677 fprintf (acfg->fp, "\n\tb %s\n", call_target);
1679 g_assert_not_reached ();
1684 * arch_emit_static_rgctx_trampoline:
1686 * Emit code for a static rgctx trampoline. OFFSET is the offset of the first of
1687 * two GOT slots which contain the rgctx argument, and the method to jump to.
1688 * TRAMP_SIZE is set to the size of the emitted trampoline.
1689 * These kinds of trampolines cannot be enumerated statically, since there could
1690 * be one trampoline per method instantiation, so we emit the same code for all
1691 * trampolines, and parameterize them using two GOT slots.
1694 arch_emit_static_rgctx_trampoline (MonoAotCompile *acfg, int offset, int *tramp_size)
1696 #if defined(TARGET_AMD64)
1697 #if defined(__default_codegen__)
1698 /* This should be exactly 13 bytes long */
1702 emit_unset_mode (acfg);
1703 fprintf (acfg->fp, "mov %s+%d(%%rip), %%r10\n", acfg->got_symbol, (int)(offset * sizeof (gpointer)));
1704 fprintf (acfg->fp, "jmp *%s+%d(%%rip)\n", acfg->got_symbol, (int)((offset + 1) * sizeof (gpointer)));
1706 /* mov <OFFSET>(%rip), %r10 */
1707 emit_byte (acfg, '\x4d');
1708 emit_byte (acfg, '\x8b');
1709 emit_byte (acfg, '\x15');
1710 emit_symbol_diff (acfg, acfg->got_symbol, ".", (offset * sizeof (gpointer)) - 4);
1712 /* jmp *<offset>(%rip) */
1713 emit_byte (acfg, '\xff');
1714 emit_byte (acfg, '\x25');
1715 emit_symbol_diff (acfg, acfg->got_symbol, ".", ((offset + 1) * sizeof (gpointer)) - 4);
1717 #elif defined(__native_client_codegen__)
1719 guint8 *buf_aligned = ALIGN_TO(buf, kNaClAlignment);
1720 guint8 *code = buf_aligned;
1722 /* mov <OFFSET>(%rip), %r10d */
1723 emit_byte (acfg, '\x45');
1724 emit_byte (acfg, '\x8b');
1725 emit_byte (acfg, '\x15');
1726 emit_symbol_diff (acfg, acfg->got_symbol, ".", (offset * sizeof (gpointer)) - 4);
1728 /* mov <OFFSET>(%rip), %r11d */
1729 emit_byte (acfg, '\x45');
1730 emit_byte (acfg, '\x8b');
1731 emit_byte (acfg, '\x1d');
1732 emit_symbol_diff (acfg, acfg->got_symbol, ".", ((offset + 1) * sizeof (gpointer)) - 4);
1735 amd64_jump_reg (code, AMD64_R11);
1736 emit_bytes (acfg, buf_aligned, code - buf_aligned);
1738 emit_alignment (acfg, kNaClAlignment);
1739 *tramp_size = kNaClAlignment;
1740 #endif /*__native_client_codegen__*/
1742 #elif defined(TARGET_ARM)
1746 /* This should be exactly 24 bytes long */
1749 /* Load rgctx value */
1750 ARM_LDR_IMM (code, ARMREG_IP, ARMREG_PC, 8);
1751 ARM_LDR_REG_REG (code, MONO_ARCH_RGCTX_REG, ARMREG_PC, ARMREG_IP);
1752 /* Load branch addr + branch */
1753 ARM_LDR_IMM (code, ARMREG_IP, ARMREG_PC, 4);
1754 ARM_LDR_REG_REG (code, ARMREG_PC, ARMREG_PC, ARMREG_IP);
1756 g_assert (code - buf == 16);
1759 emit_bytes (acfg, buf, code - buf);
1760 emit_symbol_diff (acfg, acfg->got_symbol, ".", (offset * sizeof (gpointer)) - 4 + 8);
1761 emit_symbol_diff (acfg, acfg->got_symbol, ".", ((offset + 1) * sizeof (gpointer)) - 4 + 4);
1762 #elif defined(TARGET_ARM64)
1763 arm64_emit_static_rgctx_trampoline (acfg, offset, tramp_size);
1764 #elif defined(TARGET_POWERPC)
1772 * PPC has no ip relative addressing, so we need to compute the address
1773 * of the mscorlib got. That is slow and complex, so instead, we store it
1774 * in the second got slot of every aot image. The caller already computed
1775 * the address of its got and placed it into r30.
1777 emit_unset_mode (acfg);
1778 /* Load mscorlib got address */
1779 fprintf (acfg->fp, "%s 0, %d(30)\n", PPC_LD_OP, (int)sizeof (gpointer));
1781 fprintf (acfg->fp, "lis 11, %d@h\n", (int)(offset * sizeof (gpointer)));
1782 fprintf (acfg->fp, "ori 11, 11, %d@l\n", (int)(offset * sizeof (gpointer)));
1783 fprintf (acfg->fp, "%s %d, 11, 0\n", PPC_LDX_OP, MONO_ARCH_RGCTX_REG);
1784 /* Load target address */
1785 fprintf (acfg->fp, "lis 11, %d@h\n", (int)((offset + 1) * sizeof (gpointer)));
1786 fprintf (acfg->fp, "ori 11, 11, %d@l\n", (int)((offset + 1) * sizeof (gpointer)));
1787 fprintf (acfg->fp, "%s 11, 11, 0\n", PPC_LDX_OP);
1788 #ifdef PPC_USES_FUNCTION_DESCRIPTOR
1789 fprintf (acfg->fp, "%s 2, %d(11)\n", PPC_LD_OP, (int)sizeof (gpointer));
1790 fprintf (acfg->fp, "%s 11, 0(11)\n", PPC_LD_OP);
1792 fprintf (acfg->fp, "mtctr 11\n");
1793 /* Branch to the target address */
1794 fprintf (acfg->fp, "bctr\n");
1796 #ifdef PPC_USES_FUNCTION_DESCRIPTOR
1797 *tramp_size = 11 * 4;
1799 *tramp_size = 9 * 4;
1802 #elif defined(TARGET_X86)
1806 /* Similar to the PPC code above */
1808 g_assert (MONO_ARCH_RGCTX_REG != X86_ECX);
1811 /* Load mscorlib got address */
1812 x86_mov_reg_membase (code, X86_ECX, MONO_ARCH_GOT_REG, sizeof (gpointer), 4);
1814 x86_mov_reg_membase (code, MONO_ARCH_RGCTX_REG, X86_ECX, offset * sizeof (gpointer), 4);
1815 /* Branch to the target address */
1816 x86_jump_membase (code, X86_ECX, (offset + 1) * sizeof (gpointer));
1818 #ifdef __native_client_codegen__
1820 /* emit nops to next 32 byte alignment */
1821 int a = (~kNaClAlignmentMask) & ((code - buf) + kNaClAlignment - 1);
1822 while (code < (buf + a)) x86_nop(code);
1826 emit_bytes (acfg, buf, code - buf);
1828 *tramp_size = NACL_SIZE (15, kNaClAlignment);
1829 g_assert (code - buf == *tramp_size);
1831 g_assert_not_reached ();
1836 * arch_emit_imt_thunk:
1838 * Emit an IMT thunk usable in full-aot mode. The thunk uses 1 got slot which
1839 * points to an array of pointer pairs. The pairs of the form [key, ptr], where
1840 * key is the IMT key, and ptr holds the address of a memory location holding
1841 * the address to branch to if the IMT arg matches the key. The array is
1842 * terminated by a pair whose key is NULL, and whose ptr is the address of the
1844 * TRAMP_SIZE is set to the size of the emitted trampoline.
1847 arch_emit_imt_thunk (MonoAotCompile *acfg, int offset, int *tramp_size)
1849 #if defined(TARGET_AMD64)
1851 #if defined(__native_client_codegen__)
1854 guint8 *labels [16];
1856 guint8 *mov_buf_ptr = mov_buf;
1858 const int kSizeOfMove = 7;
1859 #if defined(__default_codegen__)
1860 code = buf = g_malloc (256);
1861 #elif defined(__native_client_codegen__)
1862 buf_alloc = g_malloc (256 + kNaClAlignment + kSizeOfMove);
1863 buf = ((guint)buf_alloc + kNaClAlignment) & ~kNaClAlignmentMask;
1864 /* The RIP relative move below is emitted first */
1869 /* FIXME: Optimize this, i.e. use binary search etc. */
1870 /* Maybe move the body into a separate function (slower, but much smaller) */
1872 /* MONO_ARCH_IMT_SCRATCH_REG is a free register */
1875 emit_unset_mode (acfg);
1876 fprintf (acfg->fp, "mov %s+%d(%%rip), %s\n", acfg->got_symbol, (int)(offset * sizeof (gpointer)), mono_arch_regname (MONO_ARCH_IMT_SCRATCH_REG));
1880 amd64_alu_membase_imm (code, X86_CMP, MONO_ARCH_IMT_SCRATCH_REG, 0, 0);
1882 amd64_branch8 (code, X86_CC_Z, 0, FALSE);
1885 amd64_alu_membase_reg_size (code, X86_CMP, MONO_ARCH_IMT_SCRATCH_REG, 0, MONO_ARCH_IMT_REG, sizeof (gpointer));
1887 amd64_branch8 (code, X86_CC_Z, 0, FALSE);
1890 amd64_alu_reg_imm (code, X86_ADD, MONO_ARCH_IMT_SCRATCH_REG, 2 * sizeof (gpointer));
1891 amd64_jump_code (code, labels [0]);
1894 mono_amd64_patch (labels [2], code);
1895 amd64_mov_reg_membase (code, MONO_ARCH_IMT_SCRATCH_REG, MONO_ARCH_IMT_SCRATCH_REG, sizeof (gpointer), sizeof (gpointer));
1896 amd64_jump_membase (code, MONO_ARCH_IMT_SCRATCH_REG, 0);
1899 mono_amd64_patch (labels [1], code);
1900 /* Load fail tramp */
1901 amd64_alu_reg_imm (code, X86_ADD, MONO_ARCH_IMT_SCRATCH_REG, sizeof (gpointer));
1902 /* Check if there is a fail tramp */
1903 amd64_alu_membase_imm (code, X86_CMP, MONO_ARCH_IMT_SCRATCH_REG, 0, 0);
1905 amd64_branch8 (code, X86_CC_Z, 0, FALSE);
1906 /* Jump to fail tramp */
1907 amd64_jump_membase (code, MONO_ARCH_IMT_SCRATCH_REG, 0);
1910 mono_amd64_patch (labels [3], code);
1911 x86_breakpoint (code);
1914 /* mov <OFFSET>(%rip), MONO_ARCH_IMT_SCRATCH_REG */
1915 amd64_emit_rex (mov_buf_ptr, sizeof(gpointer), MONO_ARCH_IMT_SCRATCH_REG, 0, AMD64_RIP);
1916 *(mov_buf_ptr)++ = (unsigned char)0x8b; /* mov opcode */
1917 x86_address_byte (mov_buf_ptr, 0, MONO_ARCH_IMT_SCRATCH_REG & 0x7, 5);
1918 emit_bytes (acfg, mov_buf, mov_buf_ptr - mov_buf);
1919 emit_symbol_diff (acfg, acfg->got_symbol, ".", (offset * sizeof (gpointer)) - 4);
1921 emit_bytes (acfg, buf, code - buf);
1923 *tramp_size = code - buf + kSizeOfMove;
1924 #if defined(__native_client_codegen__)
1925 /* The tramp will be padded to the next kNaClAlignment bundle. */
1926 *tramp_size = ALIGN_TO ((*tramp_size), kNaClAlignment);
1929 #if defined(__default_codegen__)
1931 #elif defined(__native_client_codegen__)
1935 #elif defined(TARGET_X86)
1937 #ifdef __native_client_codegen__
1940 guint8 *labels [16];
1942 #if defined(__default_codegen__)
1943 code = buf = g_malloc (256);
1944 #elif defined(__native_client_codegen__)
1945 buf_alloc = g_malloc (256 + kNaClAlignment);
1946 code = buf = ((guint)buf_alloc + kNaClAlignment) & ~kNaClAlignmentMask;
1949 /* Allocate a temporary stack slot */
1950 x86_push_reg (code, X86_EAX);
1952 x86_push_reg (code, X86_EAX);
1954 /* Load mscorlib got address */
1955 x86_mov_reg_membase (code, X86_EAX, MONO_ARCH_GOT_REG, sizeof (gpointer), 4);
1957 x86_mov_reg_membase (code, X86_EAX, X86_EAX, offset * sizeof (gpointer), 4);
1960 x86_alu_membase_imm (code, X86_CMP, X86_EAX, 0, 0);
1962 x86_branch8 (code, X86_CC_Z, FALSE, 0);
1965 x86_alu_membase_reg (code, X86_CMP, X86_EAX, 0, MONO_ARCH_IMT_REG);
1967 x86_branch8 (code, X86_CC_Z, FALSE, 0);
1970 x86_alu_reg_imm (code, X86_ADD, X86_EAX, 2 * sizeof (gpointer));
1971 x86_jump_code (code, labels [0]);
1974 mono_x86_patch (labels [2], code);
1975 x86_mov_reg_membase (code, X86_EAX, X86_EAX, sizeof (gpointer), 4);
1976 x86_mov_reg_membase (code, X86_EAX, X86_EAX, 0, 4);
1977 /* Save the target address to the temporary stack location */
1978 x86_mov_membase_reg (code, X86_ESP, 4, X86_EAX, 4);
1980 x86_pop_reg (code, X86_EAX);
1981 /* Jump to the target address */
1985 mono_x86_patch (labels [1], code);
1986 /* Load fail tramp */
1987 x86_mov_reg_membase (code, X86_EAX, X86_EAX, sizeof (gpointer), 4);
1988 x86_alu_membase_imm (code, X86_CMP, X86_EAX, 0, 0);
1990 x86_branch8 (code, X86_CC_Z, FALSE, 0);
1991 /* Jump to fail tramp */
1992 x86_mov_membase_reg (code, X86_ESP, 4, X86_EAX, 4);
1993 x86_pop_reg (code, X86_EAX);
1997 mono_x86_patch (labels [3], code);
1998 x86_breakpoint (code);
2000 #ifdef __native_client_codegen__
2002 /* emit nops to next 32 byte alignment */
2003 int a = (~kNaClAlignmentMask) & ((code - buf) + kNaClAlignment - 1);
2004 while (code < (buf + a)) x86_nop(code);
2007 emit_bytes (acfg, buf, code - buf);
2009 *tramp_size = code - buf;
2011 #if defined(__default_codegen__)
2013 #elif defined(__native_client_codegen__)
2017 #elif defined(TARGET_ARM)
2019 guint8 *code, *code2, *labels [16];
2023 /* The IMT method is in v5 */
2025 /* Need at least two free registers, plus a slot for storing the pc */
2026 ARM_PUSH (code, (1 << ARMREG_R0)|(1 << ARMREG_R1)|(1 << ARMREG_R2));
2028 /* Load the parameter from the GOT */
2029 ARM_LDR_IMM (code, ARMREG_R0, ARMREG_PC, 0);
2030 ARM_LDR_REG_REG (code, ARMREG_R0, ARMREG_PC, ARMREG_R0);
2033 ARM_LDR_IMM (code, ARMREG_R1, ARMREG_R0, 0);
2034 ARM_CMP_REG_REG (code, ARMREG_R1, ARMREG_V5);
2036 ARM_B_COND (code, ARMCOND_EQ, 0);
2038 /* End-of-loop check */
2039 ARM_CMP_REG_IMM (code, ARMREG_R1, 0, 0);
2041 ARM_B_COND (code, ARMCOND_EQ, 0);
2044 ARM_ADD_REG_IMM8 (code, ARMREG_R0, ARMREG_R0, sizeof (gpointer) * 2);
2047 arm_patch (labels [4], labels [1]);
2050 arm_patch (labels [2], code);
2051 ARM_LDR_IMM (code, ARMREG_R0, ARMREG_R0, 4);
2052 ARM_LDR_IMM (code, ARMREG_R0, ARMREG_R0, 0);
2053 /* Save it to the third stack slot */
2054 ARM_STR_IMM (code, ARMREG_R0, ARMREG_SP, 8);
2055 /* Restore the registers and branch */
2056 ARM_POP (code, (1 << ARMREG_R0)|(1 << ARMREG_R1)|(1 << ARMREG_PC));
2059 arm_patch (labels [3], code);
2060 ARM_LDR_IMM (code, ARMREG_R0, ARMREG_R0, 4);
2061 ARM_STR_IMM (code, ARMREG_R0, ARMREG_SP, 8);
2062 ARM_POP (code, (1 << ARMREG_R0)|(1 << ARMREG_R1)|(1 << ARMREG_PC));
2066 ARM_LDR_IMM (code2, ARMREG_R0, ARMREG_PC, (code - (labels [0] + 8)));
2068 emit_bytes (acfg, buf, code - buf);
2069 emit_symbol_diff (acfg, acfg->got_symbol, ".", (offset * sizeof (gpointer)) + (code - (labels [0] + 8)) - 4);
2071 *tramp_size = code - buf + 4;
2072 #elif defined(TARGET_ARM64)
2073 arm64_emit_imt_thunk (acfg, offset, tramp_size);
2074 #elif defined(TARGET_POWERPC)
2076 guint8 *code, *labels [16];
2080 /* Load the mscorlib got address */
2081 ppc_ldptr (code, ppc_r12, sizeof (gpointer), ppc_r30);
2082 /* Load the parameter from the GOT */
2083 ppc_load (code, ppc_r0, offset * sizeof (gpointer));
2084 ppc_ldptr_indexed (code, ppc_r12, ppc_r12, ppc_r0);
2086 /* Load and check key */
2088 ppc_ldptr (code, ppc_r0, 0, ppc_r12);
2089 ppc_cmp (code, 0, sizeof (gpointer) == 8 ? 1 : 0, ppc_r0, MONO_ARCH_IMT_REG);
2091 ppc_bc (code, PPC_BR_TRUE, PPC_BR_EQ, 0);
2093 /* End-of-loop check */
2094 ppc_cmpi (code, 0, sizeof (gpointer) == 8 ? 1 : 0, ppc_r0, 0);
2096 ppc_bc (code, PPC_BR_TRUE, PPC_BR_EQ, 0);
2099 ppc_addi (code, ppc_r12, ppc_r12, 2 * sizeof (gpointer));
2102 mono_ppc_patch (labels [4], labels [1]);
2105 mono_ppc_patch (labels [2], code);
2106 ppc_ldptr (code, ppc_r12, sizeof (gpointer), ppc_r12);
2107 /* r12 now contains the value of the vtable slot */
2108 /* this is not a function descriptor on ppc64 */
2109 ppc_ldptr (code, ppc_r12, 0, ppc_r12);
2110 ppc_mtctr (code, ppc_r12);
2111 ppc_bcctr (code, PPC_BR_ALWAYS, 0);
2114 mono_ppc_patch (labels [3], code);
2118 *tramp_size = code - buf;
2120 emit_bytes (acfg, buf, code - buf);
2122 g_assert_not_reached ();
2127 * arch_emit_gsharedvt_arg_trampoline:
2129 * Emit code for a gsharedvt arg trampoline. OFFSET is the offset of the first of
2130 * two GOT slots which contain the argument, and the code to jump to.
2131 * TRAMP_SIZE is set to the size of the emitted trampoline.
2132 * These kinds of trampolines cannot be enumerated statically, since there could
2133 * be one trampoline per method instantiation, so we emit the same code for all
2134 * trampolines, and parameterize them using two GOT slots.
2137 arch_emit_gsharedvt_arg_trampoline (MonoAotCompile *acfg, int offset, int *tramp_size)
2139 #if defined(TARGET_X86)
2143 /* Similar to the PPC code above */
2145 g_assert (MONO_ARCH_RGCTX_REG != X86_ECX);
2148 /* Load mscorlib got address */
2149 x86_mov_reg_membase (code, X86_ECX, MONO_ARCH_GOT_REG, sizeof (gpointer), 4);
2151 x86_mov_reg_membase (code, X86_EAX, X86_ECX, offset * sizeof (gpointer), 4);
2152 /* Branch to the target address */
2153 x86_jump_membase (code, X86_ECX, (offset + 1) * sizeof (gpointer));
2155 #ifdef __native_client_codegen__
2157 /* emit nops to next 32 byte alignment */
2158 int a = (~kNaClAlignmentMask) & ((code - buf) + kNaClAlignment - 1);
2159 while (code < (buf + a)) x86_nop(code);
2163 emit_bytes (acfg, buf, code - buf);
2165 *tramp_size = NACL_SIZE (15, kNaClAlignment);
2166 g_assert (code - buf == *tramp_size);
2167 #elif defined(TARGET_ARM)
2171 /* The same as mono_arch_get_gsharedvt_arg_trampoline (), but for AOT */
2172 /* Similar to arch_emit_specific_trampoline () */
2175 ARM_PUSH (code, (1 << ARMREG_R0) | (1 << ARMREG_R1) | (1 << ARMREG_R2) | (1 << ARMREG_R3));
2176 ARM_LDR_IMM (code, ARMREG_R1, ARMREG_PC, 8);
2177 /* Load the arg value from the GOT */
2178 ARM_LDR_REG_REG (code, ARMREG_R0, ARMREG_PC, ARMREG_R1);
2179 /* Load the addr from the GOT */
2180 ARM_LDR_REG_REG (code, ARMREG_R1, ARMREG_PC, ARMREG_R1);
2182 ARM_BX (code, ARMREG_R1);
2184 g_assert (code - buf == 20);
2187 emit_bytes (acfg, buf, code - buf);
2188 emit_symbol_diff (acfg, acfg->got_symbol, ".", (offset * sizeof (gpointer)) + 4);
2189 #elif defined(TARGET_ARM64)
2190 arm64_emit_gsharedvt_arg_trampoline (acfg, offset, tramp_size);
2192 g_assert_not_reached ();
2196 /* END OF ARCH SPECIFIC CODE */
2199 mono_get_field_token (MonoClassField *field)
2201 MonoClass *klass = field->parent;
2204 for (i = 0; i < klass->field.count; ++i) {
2205 if (field == &klass->fields [i])
2206 return MONO_TOKEN_FIELD_DEF | (klass->field.first + 1 + i);
2209 g_assert_not_reached ();
2214 encode_value (gint32 value, guint8 *buf, guint8 **endbuf)
2218 //printf ("ENCODE: %d 0x%x.\n", value, value);
2221 * Same encoding as the one used in the metadata, extended to handle values
2222 * greater than 0x1fffffff.
2224 if ((value >= 0) && (value <= 127))
2226 else if ((value >= 0) && (value <= 16383)) {
2227 p [0] = 0x80 | (value >> 8);
2228 p [1] = value & 0xff;
2230 } else if ((value >= 0) && (value <= 0x1fffffff)) {
2231 p [0] = (value >> 24) | 0xc0;
2232 p [1] = (value >> 16) & 0xff;
2233 p [2] = (value >> 8) & 0xff;
2234 p [3] = value & 0xff;
2239 p [1] = (value >> 24) & 0xff;
2240 p [2] = (value >> 16) & 0xff;
2241 p [3] = (value >> 8) & 0xff;
2242 p [4] = value & 0xff;
2250 stream_init (MonoDynamicStream *sh)
2253 sh->alloc_size = 4096;
2254 sh->data = g_malloc (4096);
2256 /* So offsets are > 0 */
2262 make_room_in_stream (MonoDynamicStream *stream, int size)
2264 if (size <= stream->alloc_size)
2267 while (stream->alloc_size <= size) {
2268 if (stream->alloc_size < 4096)
2269 stream->alloc_size = 4096;
2271 stream->alloc_size *= 2;
2274 stream->data = g_realloc (stream->data, stream->alloc_size);
2278 add_stream_data (MonoDynamicStream *stream, const char *data, guint32 len)
2282 make_room_in_stream (stream, stream->index + len);
2283 memcpy (stream->data + stream->index, data, len);
2284 idx = stream->index;
2285 stream->index += len;
2292 * Add data to the binary blob inside the aot image. Returns the offset inside the
2293 * blob where the data was stored.
2296 add_to_blob (MonoAotCompile *acfg, const guint8 *data, guint32 data_len)
2298 if (acfg->blob.alloc_size == 0)
2299 stream_init (&acfg->blob);
2301 return add_stream_data (&acfg->blob, (char*)data, data_len);
2305 add_to_blob_aligned (MonoAotCompile *acfg, const guint8 *data, guint32 data_len, guint32 align)
2310 if (acfg->blob.alloc_size == 0)
2311 stream_init (&acfg->blob);
2313 count = acfg->blob.index % align;
2315 /* we assume the stream data will be aligned */
2317 add_stream_data (&acfg->blob, buf, 4 - count);
2319 return add_stream_data (&acfg->blob, (char*)data, data_len);
2323 * emit_offset_table:
2325 * Emit a table of increasing offsets in a compact form using differential encoding.
2326 * There is an index entry for each GROUP_SIZE number of entries. The greater the
2327 * group size, the more compact the table becomes, but the slower it becomes to compute
2328 * a given entry. Returns the size of the table.
2331 emit_offset_table (MonoAotCompile *acfg, const char *symbol, int noffsets, int group_size, gint32 *offsets)
2333 gint32 current_offset;
2334 int i, buf_size, ngroups, index_entry_size;
2336 guint8 *data_p, *data_buf;
2337 guint32 *index_offsets;
2339 ngroups = (noffsets + (group_size - 1)) / group_size;
2341 index_offsets = g_new0 (guint32, ngroups);
2343 buf_size = noffsets * 4;
2344 p = buf = g_malloc0 (buf_size);
2347 for (i = 0; i < noffsets; ++i) {
2348 //printf ("D: %d -> %d\n", i, offsets [i]);
2349 if ((i % group_size) == 0) {
2350 index_offsets [i / group_size] = p - buf;
2351 /* Emit the full value for these entries */
2352 encode_value (offsets [i], p, &p);
2354 /* The offsets are allowed to be non-increasing */
2355 //g_assert (offsets [i] >= current_offset);
2356 encode_value (offsets [i] - current_offset, p, &p);
2358 current_offset = offsets [i];
2363 if (ngroups && index_offsets [ngroups - 1] < 65000)
2364 index_entry_size = 2;
2366 index_entry_size = 4;
2368 buf_size = (data_p - data_buf) + (ngroups * 4) + 16;
2369 p = buf = g_malloc0 (buf_size);
2371 /* Emit the header */
2372 encode_int (noffsets, p, &p);
2373 encode_int (group_size, p, &p);
2374 encode_int (ngroups, p, &p);
2375 encode_int (index_entry_size, p, &p);
2377 /* Emit the index */
2378 for (i = 0; i < ngroups; ++i) {
2379 if (index_entry_size == 2)
2380 encode_int16 (index_offsets [i], p, &p);
2382 encode_int (index_offsets [i], p, &p);
2385 memcpy (p, data_buf, data_p - data_buf);
2386 p += data_p - data_buf;
2388 g_assert (p - buf <= buf_size);
2391 mono_llvm_emit_aot_data (symbol, buf, p - buf);
2393 emit_section_change (acfg, RODATA_SECT, 1);
2394 emit_alignment (acfg, 8);
2395 emit_label (acfg, symbol);
2396 emit_bytes (acfg, buf, p - buf);
2402 return (int)(p - buf);
2406 get_image_index (MonoAotCompile *cfg, MonoImage *image)
2410 index = GPOINTER_TO_UINT (g_hash_table_lookup (cfg->image_hash, image));
2414 index = g_hash_table_size (cfg->image_hash);
2415 g_hash_table_insert (cfg->image_hash, image, GUINT_TO_POINTER (index + 1));
2416 g_ptr_array_add (cfg->image_table, image);
2422 find_typespec_for_class (MonoAotCompile *acfg, MonoClass *klass)
2425 int len = acfg->image->tables [MONO_TABLE_TYPESPEC].rows;
2427 /* FIXME: Search referenced images as well */
2428 if (!acfg->typespec_classes) {
2429 acfg->typespec_classes = mono_mempool_alloc0 (acfg->mempool, sizeof (MonoClass*) * len);
2430 for (i = 0; i < len; ++i) {
2432 acfg->typespec_classes [i] = mono_class_get_and_inflate_typespec_checked (acfg->image, MONO_TOKEN_TYPE_SPEC | (i + 1), NULL, &error);
2433 g_assert (mono_error_ok (&error)); /* FIXME error handling */
2436 for (i = 0; i < len; ++i) {
2437 if (acfg->typespec_classes [i] == klass)
2442 return MONO_TOKEN_TYPE_SPEC | (i + 1);
2448 encode_method_ref (MonoAotCompile *acfg, MonoMethod *method, guint8 *buf, guint8 **endbuf);
2451 encode_klass_ref (MonoAotCompile *acfg, MonoClass *klass, guint8 *buf, guint8 **endbuf);
2454 encode_ginst (MonoAotCompile *acfg, MonoGenericInst *inst, guint8 *buf, guint8 **endbuf);
2457 encode_type (MonoAotCompile *acfg, MonoType *t, guint8 *buf, guint8 **endbuf);
2460 encode_klass_ref_inner (MonoAotCompile *acfg, MonoClass *klass, guint8 *buf, guint8 **endbuf)
2465 * The encoding begins with one of the MONO_AOT_TYPEREF values, followed by additional
2469 if (klass->generic_class) {
2471 g_assert (klass->type_token);
2473 /* Find a typespec for a class if possible */
2474 token = find_typespec_for_class (acfg, klass);
2476 encode_value (MONO_AOT_TYPEREF_TYPESPEC_TOKEN, p, &p);
2477 encode_value (token, p, &p);
2479 MonoClass *gclass = klass->generic_class->container_class;
2480 MonoGenericInst *inst = klass->generic_class->context.class_inst;
2481 static int count = 0;
2484 encode_value (MONO_AOT_TYPEREF_GINST, p, &p);
2485 encode_klass_ref (acfg, gclass, p, &p);
2486 encode_ginst (acfg, inst, p, &p);
2490 } else if (klass->type_token) {
2491 int iindex = get_image_index (acfg, klass->image);
2493 g_assert (mono_metadata_token_code (klass->type_token) == MONO_TOKEN_TYPE_DEF);
2495 encode_value (MONO_AOT_TYPEREF_TYPEDEF_INDEX, p, &p);
2496 encode_value (klass->type_token - MONO_TOKEN_TYPE_DEF, p, &p);
2498 encode_value (MONO_AOT_TYPEREF_TYPEDEF_INDEX_IMAGE, p, &p);
2499 encode_value (klass->type_token - MONO_TOKEN_TYPE_DEF, p, &p);
2500 encode_value (get_image_index (acfg, klass->image), p, &p);
2502 } else if ((klass->byval_arg.type == MONO_TYPE_VAR) || (klass->byval_arg.type == MONO_TYPE_MVAR)) {
2503 MonoGenericContainer *container = mono_type_get_generic_param_owner (&klass->byval_arg);
2504 MonoGenericParam *par = klass->byval_arg.data.generic_param;
2506 encode_value (MONO_AOT_TYPEREF_VAR, p, &p);
2507 encode_value (klass->byval_arg.type, p, &p);
2508 encode_value (mono_type_get_generic_param_num (&klass->byval_arg), p, &p);
2510 encode_value (container ? 1 : 0, p, &p);
2512 encode_value (container->is_method, p, &p);
2513 g_assert (!par->gshared_constraint);
2514 if (container->is_method)
2515 encode_method_ref (acfg, container->owner.method, p, &p);
2517 encode_klass_ref (acfg, container->owner.klass, p, &p);
2519 encode_value (par->gshared_constraint ? 1 : 0, p, &p);
2520 if (par->gshared_constraint) {
2523 encode_type (acfg, par->gshared_constraint, p, &p);
2525 name = mono_generic_param_name (par);
2527 int len = strlen (name);
2529 encode_value (len, p, &p);
2530 memcpy (p, name, len);
2533 encode_value (0, p, &p);
2537 } else if (klass->byval_arg.type == MONO_TYPE_PTR) {
2538 encode_value (MONO_AOT_TYPEREF_PTR, p, &p);
2539 encode_type (acfg, &klass->byval_arg, p, &p);
2542 g_assert (klass->rank > 0);
2543 encode_value (MONO_AOT_TYPEREF_ARRAY, p, &p);
2544 encode_value (klass->rank, p, &p);
2545 encode_klass_ref (acfg, klass->element_class, p, &p);
2553 * Encode a reference to KLASS. We use our home-grown encoding instead of the
2554 * standard metadata encoding.
2557 encode_klass_ref (MonoAotCompile *acfg, MonoClass *klass, guint8 *buf, guint8 **endbuf)
2559 gboolean shared = FALSE;
2562 * The encoding of generic instances is large so emit them only once.
2564 if (klass->generic_class) {
2566 g_assert (klass->type_token);
2568 /* Find a typespec for a class if possible */
2569 token = find_typespec_for_class (acfg, klass);
2572 } else if ((klass->byval_arg.type == MONO_TYPE_VAR) || (klass->byval_arg.type == MONO_TYPE_MVAR)) {
2577 guint offset = GPOINTER_TO_UINT (g_hash_table_lookup (acfg->klass_blob_hash, klass));
2581 buf2 = g_malloc (1024);
2584 encode_klass_ref_inner (acfg, klass, p, &p);
2585 g_assert (p - buf2 < 1024);
2587 offset = add_to_blob (acfg, buf2, p - buf2);
2590 g_hash_table_insert (acfg->klass_blob_hash, klass, GUINT_TO_POINTER (offset + 1));
2596 encode_value (MONO_AOT_TYPEREF_BLOB_INDEX, p, &p);
2597 encode_value (offset, p, &p);
2602 encode_klass_ref_inner (acfg, klass, buf, endbuf);
2606 encode_field_info (MonoAotCompile *cfg, MonoClassField *field, guint8 *buf, guint8 **endbuf)
2608 guint32 token = mono_get_field_token (field);
2611 encode_klass_ref (cfg, field->parent, p, &p);
2612 g_assert (mono_metadata_token_code (token) == MONO_TOKEN_FIELD_DEF);
2613 encode_value (token - MONO_TOKEN_FIELD_DEF, p, &p);
2618 encode_ginst (MonoAotCompile *acfg, MonoGenericInst *inst, guint8 *buf, guint8 **endbuf)
2623 encode_value (inst->type_argc, p, &p);
2624 for (i = 0; i < inst->type_argc; ++i)
2625 encode_klass_ref (acfg, mono_class_from_mono_type (inst->type_argv [i]), p, &p);
2630 encode_generic_context (MonoAotCompile *acfg, MonoGenericContext *context, guint8 *buf, guint8 **endbuf)
2633 MonoGenericInst *inst;
2635 inst = context->class_inst;
2637 g_assert (inst->type_argc);
2638 encode_ginst (acfg, inst, p, &p);
2640 encode_value (0, p, &p);
2642 inst = context->method_inst;
2644 g_assert (inst->type_argc);
2645 encode_ginst (acfg, inst, p, &p);
2647 encode_value (0, p, &p);
2653 encode_type (MonoAotCompile *acfg, MonoType *t, guint8 *buf, guint8 **endbuf)
2657 g_assert (t->num_mods == 0);
2658 /* t->attrs can be ignored */
2659 //g_assert (t->attrs == 0);
2662 *p = MONO_TYPE_PINNED;
2666 *p = MONO_TYPE_BYREF;
2674 case MONO_TYPE_VOID:
2675 case MONO_TYPE_BOOLEAN:
2676 case MONO_TYPE_CHAR:
2689 case MONO_TYPE_STRING:
2690 case MONO_TYPE_OBJECT:
2691 case MONO_TYPE_TYPEDBYREF:
2693 case MONO_TYPE_VALUETYPE:
2694 case MONO_TYPE_CLASS:
2695 encode_klass_ref (acfg, mono_class_from_mono_type (t), p, &p);
2697 case MONO_TYPE_SZARRAY:
2698 encode_klass_ref (acfg, t->data.klass, p, &p);
2701 encode_type (acfg, t->data.type, p, &p);
2703 case MONO_TYPE_GENERICINST: {
2704 MonoClass *gclass = t->data.generic_class->container_class;
2705 MonoGenericInst *inst = t->data.generic_class->context.class_inst;
2707 encode_klass_ref (acfg, gclass, p, &p);
2708 encode_ginst (acfg, inst, p, &p);
2711 case MONO_TYPE_ARRAY: {
2712 MonoArrayType *array = t->data.array;
2715 encode_klass_ref (acfg, array->eklass, p, &p);
2716 encode_value (array->rank, p, &p);
2717 encode_value (array->numsizes, p, &p);
2718 for (i = 0; i < array->numsizes; ++i)
2719 encode_value (array->sizes [i], p, &p);
2720 encode_value (array->numlobounds, p, &p);
2721 for (i = 0; i < array->numlobounds; ++i)
2722 encode_value (array->lobounds [i], p, &p);
2726 case MONO_TYPE_MVAR:
2727 encode_klass_ref (acfg, mono_class_from_mono_type (t), p, &p);
2730 g_assert_not_reached ();
2737 encode_signature (MonoAotCompile *acfg, MonoMethodSignature *sig, guint8 *buf, guint8 **endbuf)
2743 /* Similar to the metadata encoding */
2744 if (sig->generic_param_count)
2748 if (sig->explicit_this)
2750 flags |= (sig->call_convention & 0x0F);
2754 if (sig->generic_param_count)
2755 encode_value (sig->generic_param_count, p, &p);
2756 encode_value (sig->param_count, p, &p);
2758 encode_type (acfg, sig->ret, p, &p);
2759 for (i = 0; i < sig->param_count; ++i) {
2760 if (sig->sentinelpos == i) {
2761 *p = MONO_TYPE_SENTINEL;
2764 encode_type (acfg, sig->params [i], p, &p);
2770 #define MAX_IMAGE_INDEX 250
2773 encode_method_ref (MonoAotCompile *acfg, MonoMethod *method, guint8 *buf, guint8 **endbuf)
2775 guint32 image_index = get_image_index (acfg, method->klass->image);
2776 guint32 token = method->token;
2777 MonoJumpInfoToken *ji;
2781 * The encoding for most methods is as follows:
2782 * - image index encoded as a leb128
2783 * - token index encoded as a leb128
2784 * Values of image index >= MONO_AOT_METHODREF_MIN are used to mark additional
2785 * types of method encodings.
2788 /* Mark methods which can't use aot trampolines because they need the further
2789 * processing in mono_magic_trampoline () which requires a MonoMethod*.
2791 if ((method->is_generic && (method->flags & METHOD_ATTRIBUTE_VIRTUAL)) ||
2792 (method->iflags & METHOD_IMPL_ATTRIBUTE_SYNCHRONIZED))
2793 encode_value ((MONO_AOT_METHODREF_NO_AOT_TRAMPOLINE << 24), p, &p);
2795 if (method->wrapper_type) {
2796 encode_value ((MONO_AOT_METHODREF_WRAPPER << 24), p, &p);
2798 encode_value (method->wrapper_type, p, &p);
2800 switch (method->wrapper_type) {
2801 case MONO_WRAPPER_REMOTING_INVOKE:
2802 case MONO_WRAPPER_REMOTING_INVOKE_WITH_CHECK:
2803 case MONO_WRAPPER_XDOMAIN_INVOKE: {
2806 m = mono_marshal_method_from_wrapper (method);
2808 encode_method_ref (acfg, m, p, &p);
2811 case MONO_WRAPPER_PROXY_ISINST:
2812 case MONO_WRAPPER_LDFLD:
2813 case MONO_WRAPPER_LDFLDA:
2814 case MONO_WRAPPER_STFLD:
2815 case MONO_WRAPPER_ISINST: {
2816 WrapperInfo *info = mono_marshal_get_wrapper_info (method);
2819 encode_klass_ref (acfg, info->d.proxy.klass, p, &p);
2822 case MONO_WRAPPER_LDFLD_REMOTE:
2823 case MONO_WRAPPER_STFLD_REMOTE:
2825 case MONO_WRAPPER_ALLOC: {
2826 AllocatorWrapperInfo *info = mono_marshal_get_wrapper_info (method);
2828 /* The GC name is saved once in MonoAotFileInfo */
2829 g_assert (info->alloc_type != -1);
2830 encode_value (info->alloc_type, p, &p);
2833 case MONO_WRAPPER_WRITE_BARRIER:
2835 case MONO_WRAPPER_STELEMREF: {
2836 WrapperInfo *info = mono_marshal_get_wrapper_info (method);
2839 encode_value (info->subtype, p, &p);
2840 if (info->subtype == WRAPPER_SUBTYPE_VIRTUAL_STELEMREF)
2841 encode_value (info->d.virtual_stelemref.kind, p, &p);
2844 case MONO_WRAPPER_UNKNOWN: {
2845 WrapperInfo *info = mono_marshal_get_wrapper_info (method);
2848 encode_value (info->subtype, p, &p);
2849 if (info->subtype == WRAPPER_SUBTYPE_PTR_TO_STRUCTURE ||
2850 info->subtype == WRAPPER_SUBTYPE_STRUCTURE_TO_PTR)
2851 encode_klass_ref (acfg, method->klass, p, &p);
2852 else if (info->subtype == WRAPPER_SUBTYPE_SYNCHRONIZED_INNER)
2853 encode_method_ref (acfg, info->d.synchronized_inner.method, p, &p);
2854 else if (info->subtype == WRAPPER_SUBTYPE_ARRAY_ACCESSOR)
2855 encode_method_ref (acfg, info->d.array_accessor.method, p, &p);
2858 case MONO_WRAPPER_MANAGED_TO_NATIVE: {
2859 WrapperInfo *info = mono_marshal_get_wrapper_info (method);
2862 encode_value (info->subtype, p, &p);
2863 if (info->subtype == WRAPPER_SUBTYPE_ICALL_WRAPPER) {
2864 strcpy ((char*)p, method->name);
2865 p += strlen (method->name) + 1;
2866 } else if (info->subtype == WRAPPER_SUBTYPE_NATIVE_FUNC_AOT) {
2867 encode_method_ref (acfg, info->d.managed_to_native.method, p, &p);
2869 g_assert (info->subtype == WRAPPER_SUBTYPE_NONE || info->subtype == WRAPPER_SUBTYPE_PINVOKE);
2870 encode_method_ref (acfg, info->d.managed_to_native.method, p, &p);
2874 case MONO_WRAPPER_SYNCHRONIZED: {
2877 m = mono_marshal_method_from_wrapper (method);
2879 g_assert (m != method);
2880 encode_method_ref (acfg, m, p, &p);
2883 case MONO_WRAPPER_MANAGED_TO_MANAGED: {
2884 WrapperInfo *info = mono_marshal_get_wrapper_info (method);
2887 encode_value (info->subtype, p, &p);
2889 if (info->subtype == WRAPPER_SUBTYPE_ELEMENT_ADDR) {
2890 encode_value (info->d.element_addr.rank, p, &p);
2891 encode_value (info->d.element_addr.elem_size, p, &p);
2892 } else if (info->subtype == WRAPPER_SUBTYPE_STRING_CTOR) {
2893 encode_method_ref (acfg, info->d.string_ctor.method, p, &p);
2895 g_assert_not_reached ();
2899 case MONO_WRAPPER_CASTCLASS: {
2900 WrapperInfo *info = mono_marshal_get_wrapper_info (method);
2903 encode_value (info->subtype, p, &p);
2906 case MONO_WRAPPER_RUNTIME_INVOKE: {
2907 WrapperInfo *info = mono_marshal_get_wrapper_info (method);
2910 encode_value (info->subtype, p, &p);
2911 if (info->subtype == WRAPPER_SUBTYPE_RUNTIME_INVOKE_DIRECT || info->subtype == WRAPPER_SUBTYPE_RUNTIME_INVOKE_VIRTUAL)
2912 encode_method_ref (acfg, info->d.runtime_invoke.method, p, &p);
2913 else if (info->subtype == WRAPPER_SUBTYPE_RUNTIME_INVOKE_NORMAL)
2914 encode_signature (acfg, info->d.runtime_invoke.sig, p, &p);
2917 case MONO_WRAPPER_DELEGATE_INVOKE:
2918 case MONO_WRAPPER_DELEGATE_BEGIN_INVOKE:
2919 case MONO_WRAPPER_DELEGATE_END_INVOKE: {
2920 if (method->is_inflated) {
2921 /* These wrappers are identified by their class */
2922 encode_value (1, p, &p);
2923 encode_klass_ref (acfg, method->klass, p, &p);
2925 MonoMethodSignature *sig = mono_method_signature (method);
2926 WrapperInfo *info = mono_marshal_get_wrapper_info (method);
2928 encode_value (0, p, &p);
2929 if (method->wrapper_type == MONO_WRAPPER_DELEGATE_INVOKE)
2930 encode_value (info ? info->subtype : 0, p, &p);
2931 encode_signature (acfg, sig, p, &p);
2935 case MONO_WRAPPER_NATIVE_TO_MANAGED: {
2936 WrapperInfo *info = mono_marshal_get_wrapper_info (method);
2939 encode_method_ref (acfg, info->d.native_to_managed.method, p, &p);
2940 encode_klass_ref (acfg, info->d.native_to_managed.klass, p, &p);
2944 g_assert_not_reached ();
2946 } else if (mono_method_signature (method)->is_inflated) {
2948 * This is a generic method, find the original token which referenced it and
2950 * Obtain the token from information recorded by the JIT.
2952 ji = g_hash_table_lookup (acfg->token_info_hash, method);
2954 image_index = get_image_index (acfg, ji->image);
2955 g_assert (image_index < MAX_IMAGE_INDEX);
2958 encode_value ((MONO_AOT_METHODREF_METHODSPEC << 24), p, &p);
2959 encode_value (image_index, p, &p);
2960 encode_value (token, p, &p);
2962 MonoMethod *declaring;
2963 MonoGenericContext *context = mono_method_get_context (method);
2965 g_assert (method->is_inflated);
2966 declaring = ((MonoMethodInflated*)method)->declaring;
2969 * This might be a non-generic method of a generic instance, which
2970 * doesn't have a token since the reference is generated by the JIT
2971 * like Nullable:Box/Unbox, or by generic sharing.
2973 encode_value ((MONO_AOT_METHODREF_GINST << 24), p, &p);
2974 /* Encode the klass */
2975 encode_klass_ref (acfg, method->klass, p, &p);
2976 /* Encode the method */
2977 image_index = get_image_index (acfg, method->klass->image);
2978 g_assert (image_index < MAX_IMAGE_INDEX);
2979 g_assert (declaring->token);
2980 token = declaring->token;
2981 g_assert (mono_metadata_token_table (token) == MONO_TABLE_METHOD);
2982 encode_value (image_index, p, &p);
2983 encode_value (token, p, &p);
2984 encode_generic_context (acfg, context, p, &p);
2986 } else if (token == 0) {
2987 /* This might be a method of a constructed type like int[,].Set */
2988 /* Obtain the token from information recorded by the JIT */
2989 ji = g_hash_table_lookup (acfg->token_info_hash, method);
2991 image_index = get_image_index (acfg, ji->image);
2992 g_assert (image_index < MAX_IMAGE_INDEX);
2995 encode_value ((MONO_AOT_METHODREF_METHODSPEC << 24), p, &p);
2996 encode_value (image_index, p, &p);
2997 encode_value (token, p, &p);
3000 g_assert (method->klass->rank);
3002 /* Encode directly */
3003 encode_value ((MONO_AOT_METHODREF_ARRAY << 24), p, &p);
3004 encode_klass_ref (acfg, method->klass, p, &p);
3005 if (!strcmp (method->name, ".ctor") && mono_method_signature (method)->param_count == method->klass->rank)
3006 encode_value (0, p, &p);
3007 else if (!strcmp (method->name, ".ctor") && mono_method_signature (method)->param_count == method->klass->rank * 2)
3008 encode_value (1, p, &p);
3009 else if (!strcmp (method->name, "Get"))
3010 encode_value (2, p, &p);
3011 else if (!strcmp (method->name, "Address"))
3012 encode_value (3, p, &p);
3013 else if (!strcmp (method->name, "Set"))
3014 encode_value (4, p, &p);
3016 g_assert_not_reached ();
3019 g_assert (mono_metadata_token_table (token) == MONO_TABLE_METHOD);
3021 if (image_index >= MONO_AOT_METHODREF_MIN) {
3022 encode_value ((MONO_AOT_METHODREF_LARGE_IMAGE_INDEX << 24), p, &p);
3023 encode_value (image_index, p, &p);
3024 encode_value (mono_metadata_token_index (token), p, &p);
3026 encode_value ((image_index << 24) | mono_metadata_token_index (token), p, &p);
3033 compare_patches (gconstpointer a, gconstpointer b)
3037 i = (*(MonoJumpInfo**)a)->ip.i;
3038 j = (*(MonoJumpInfo**)b)->ip.i;
3049 static G_GNUC_UNUSED char*
3050 patch_to_string (MonoJumpInfo *patch_info)
3054 str = g_string_new ("");
3056 g_string_append_printf (str, "%s(", get_patch_name (patch_info->type));
3058 switch (patch_info->type) {
3059 case MONO_PATCH_INFO_VTABLE:
3060 mono_type_get_desc (str, &patch_info->data.klass->byval_arg, TRUE);
3065 g_string_append_printf (str, ")");
3066 return g_string_free (str, FALSE);
3072 * Return whenever PATCH_INFO refers to a direct call, and thus requires a
3075 static inline gboolean
3076 is_plt_patch (MonoJumpInfo *patch_info)
3078 switch (patch_info->type) {
3079 case MONO_PATCH_INFO_METHOD:
3080 case MONO_PATCH_INFO_INTERNAL_METHOD:
3081 case MONO_PATCH_INFO_JIT_ICALL_ADDR:
3082 case MONO_PATCH_INFO_ICALL_ADDR:
3083 case MONO_PATCH_INFO_RGCTX_FETCH:
3084 case MONO_PATCH_INFO_LLVM_IMT_TRAMPOLINE:
3094 * Return the symbol identifying the plt entry PLT_OFFSET.
3097 get_plt_symbol (MonoAotCompile *acfg, int plt_offset, MonoJumpInfo *patch_info)
3101 * The Apple linker reorganizes object files, so it doesn't like branches to local
3102 * labels, since those have no relocations.
3104 return g_strdup_printf ("%sp_%d", acfg->llvm_label_prefix, plt_offset);
3106 return g_strdup_printf ("%sp_%d", acfg->temp_prefix, plt_offset);
3113 * Return a PLT entry which belongs to the method identified by PATCH_INFO.
3115 static MonoPltEntry*
3116 get_plt_entry (MonoAotCompile *acfg, MonoJumpInfo *patch_info)
3119 gboolean synchronized = FALSE;
3120 static int synchronized_symbol_idx;
3122 if (!is_plt_patch (patch_info))
3125 if (!acfg->patch_to_plt_entry [patch_info->type])
3126 acfg->patch_to_plt_entry [patch_info->type] = g_hash_table_new (mono_patch_info_hash, mono_patch_info_equal);
3127 res = g_hash_table_lookup (acfg->patch_to_plt_entry [patch_info->type], patch_info);
3129 if (!acfg->llvm && patch_info->type == MONO_PATCH_INFO_METHOD && (patch_info->data.method->iflags & METHOD_IMPL_ATTRIBUTE_SYNCHRONIZED)) {
3131 * Allocate a separate PLT slot for each such patch, since some plt
3132 * entries will refer to the method itself, and some will refer to the
3136 synchronized = TRUE;
3140 MonoJumpInfo *new_ji;
3142 new_ji = mono_patch_info_dup_mp (acfg->mempool, patch_info);
3144 res = mono_mempool_alloc0 (acfg->mempool, sizeof (MonoPltEntry));
3145 res->plt_offset = acfg->plt_offset;
3147 res->symbol = get_plt_symbol (acfg, res->plt_offset, patch_info);
3148 if (acfg->aot_opts.write_symbols)
3149 res->debug_sym = get_plt_entry_debug_sym (acfg, res->ji, acfg->plt_entry_debug_sym_cache);
3151 /* Avoid duplicate symbols because we don't cache */
3152 res->symbol = g_strdup_printf ("%s_%d", res->symbol, synchronized_symbol_idx);
3154 res->debug_sym = g_strdup_printf ("%s_%d", res->debug_sym, synchronized_symbol_idx);
3155 synchronized_symbol_idx ++;
3158 res->llvm_symbol = g_strdup_printf ("%s_%s_llvm", res->symbol, res->debug_sym);
3160 res->llvm_symbol = g_strdup_printf ("%s_llvm", res->symbol);
3162 g_hash_table_insert (acfg->patch_to_plt_entry [new_ji->type], new_ji, res);
3164 g_hash_table_insert (acfg->plt_offset_to_entry, GUINT_TO_POINTER (res->plt_offset), res);
3166 //g_assert (mono_patch_info_equal (patch_info, new_ji));
3167 //mono_print_ji (patch_info); printf ("\n");
3168 //g_hash_table_print_stats (acfg->patch_to_plt_entry);
3170 acfg->plt_offset ++;
3179 * Returns the offset of the GOT slot where the runtime object resulting from resolving
3180 * JI could be found if it exists, otherwise allocates a new one.
3183 get_got_offset (MonoAotCompile *acfg, gboolean llvm, MonoJumpInfo *ji)
3186 GotInfo *info = llvm ? &acfg->llvm_got_info : &acfg->got_info;
3188 got_offset = GPOINTER_TO_UINT (g_hash_table_lookup (info->patch_to_got_offset_by_type [ji->type], ji));
3190 return got_offset - 1;
3193 got_offset = acfg->llvm_got_offset;
3194 acfg->llvm_got_offset ++;
3196 got_offset = acfg->got_offset;
3197 acfg->got_offset ++;
3200 acfg->stats.got_slots ++;
3201 acfg->stats.got_slot_types [ji->type] ++;
3203 g_hash_table_insert (info->patch_to_got_offset, ji, GUINT_TO_POINTER (got_offset + 1));
3204 g_hash_table_insert (info->patch_to_got_offset_by_type [ji->type], ji, GUINT_TO_POINTER (got_offset + 1));
3205 g_ptr_array_add (info->got_patches, ji);
3210 /* Add a method to the list of methods which need to be emitted */
3212 add_method_with_index (MonoAotCompile *acfg, MonoMethod *method, int index, gboolean extra)
3215 if (!g_hash_table_lookup (acfg->method_indexes, method)) {
3216 g_ptr_array_add (acfg->methods, method);
3217 g_hash_table_insert (acfg->method_indexes, method, GUINT_TO_POINTER (index + 1));
3218 acfg->nmethods = acfg->methods->len + 1;
3221 if (method->wrapper_type || extra)
3222 g_ptr_array_add (acfg->extra_methods, method);
3226 prefer_gsharedvt_method (MonoAotCompile *acfg, MonoMethod *method)
3228 /* One instantiation with valuetypes is generated for each async method */
3229 if (method->klass->image == mono_defaults.corlib && (!strcmp (method->klass->name, "AsyncMethodBuilderCore") || !strcmp (method->klass->name, "AsyncVoidMethodBuilder")))
3236 get_method_index (MonoAotCompile *acfg, MonoMethod *method)
3238 int index = GPOINTER_TO_UINT (g_hash_table_lookup (acfg->method_indexes, method));
3246 add_method_full (MonoAotCompile *acfg, MonoMethod *method, gboolean extra, int depth)
3250 index = GPOINTER_TO_UINT (g_hash_table_lookup (acfg->method_indexes, method));
3254 index = acfg->method_index;
3255 add_method_with_index (acfg, method, index, extra);
3257 g_ptr_array_add (acfg->method_order, GUINT_TO_POINTER (index));
3259 g_hash_table_insert (acfg->method_depth, method, GUINT_TO_POINTER (depth));
3261 acfg->method_index ++;
3267 add_method (MonoAotCompile *acfg, MonoMethod *method)
3269 return add_method_full (acfg, method, FALSE, 0);
3273 add_extra_method_with_depth (MonoAotCompile *acfg, MonoMethod *method, int depth)
3275 if (mono_method_is_generic_sharable_full (method, TRUE, TRUE, FALSE))
3276 method = mini_get_shared_method (method);
3277 else if ((acfg->opts & MONO_OPT_GSHAREDVT) && prefer_gsharedvt_method (acfg, method) && mono_method_is_generic_sharable_full (method, FALSE, FALSE, TRUE))
3278 /* Use the gsharedvt version */
3279 method = mini_get_shared_method_full (method, TRUE, TRUE);
3281 if (acfg->aot_opts.log_generics)
3282 aot_printf (acfg, "%*sAdding method %s.\n", depth, "", mono_method_full_name (method, TRUE));
3284 add_method_full (acfg, method, TRUE, depth);
3288 add_extra_method (MonoAotCompile *acfg, MonoMethod *method)
3290 add_extra_method_with_depth (acfg, method, 0);
3294 add_jit_icall_wrapper (gpointer key, gpointer value, gpointer user_data)
3296 MonoAotCompile *acfg = user_data;
3297 MonoJitICallInfo *callinfo = value;
3298 MonoMethod *wrapper;
3304 name = g_strdup_printf ("__icall_wrapper_%s", callinfo->name);
3305 wrapper = mono_marshal_get_icall_wrapper (callinfo->sig, name, callinfo->func, TRUE);
3308 add_method (acfg, wrapper);
3312 get_runtime_invoke_sig (MonoMethodSignature *sig)
3314 MonoMethodBuilder *mb;
3317 mb = mono_mb_new (mono_defaults.object_class, "FOO", MONO_WRAPPER_NONE);
3318 m = mono_mb_create_method (mb, sig, 16);
3319 return mono_marshal_get_runtime_invoke (m, FALSE);
3323 can_marshal_struct (MonoClass *klass)
3325 MonoClassField *field;
3326 gboolean can_marshal = TRUE;
3327 gpointer iter = NULL;
3328 MonoMarshalType *info;
3331 if ((klass->flags & TYPE_ATTRIBUTE_LAYOUT_MASK) == TYPE_ATTRIBUTE_AUTO_LAYOUT)
3334 info = mono_marshal_load_type_info (klass);
3336 /* Only allow a few field types to avoid asserts in the marshalling code */
3337 while ((field = mono_class_get_fields (klass, &iter))) {
3338 if ((field->type->attrs & FIELD_ATTRIBUTE_STATIC))
3341 switch (field->type->type) {
3346 case MONO_TYPE_BOOLEAN:
3349 case MONO_TYPE_CHAR:
3357 case MONO_TYPE_STRING:
3359 case MONO_TYPE_VALUETYPE:
3360 if (!mono_class_from_mono_type (field->type)->enumtype && !can_marshal_struct (mono_class_from_mono_type (field->type)))
3361 can_marshal = FALSE;
3363 case MONO_TYPE_SZARRAY: {
3364 gboolean has_mspec = FALSE;
3367 for (i = 0; i < info->num_fields; ++i) {
3368 if (info->fields [i].field == field && info->fields [i].mspec)
3373 can_marshal = FALSE;
3377 can_marshal = FALSE;
3383 /* Its hard to compute whenever these can be marshalled or not */
3384 if (!strcmp (klass->name_space, "System.Net.NetworkInformation.MacOsStructs") && strcmp (klass->name, "sockaddr_dl"))
3391 create_gsharedvt_inst (MonoAotCompile *acfg, MonoMethod *method, MonoGenericContext *ctx)
3393 /* Create a vtype instantiation */
3394 MonoGenericContext shared_context;
3396 MonoGenericInst *inst;
3397 MonoGenericContainer *container;
3398 MonoClass **constraints;
3401 memset (ctx, 0, sizeof (MonoGenericContext));
3403 if (method->klass->generic_container) {
3404 shared_context = method->klass->generic_container->context;
3405 inst = shared_context.class_inst;
3407 args = g_new0 (MonoType*, inst->type_argc);
3408 for (i = 0; i < inst->type_argc; ++i) {
3409 args [i] = &mono_defaults.int_class->byval_arg;
3411 ctx->class_inst = mono_metadata_get_generic_inst (inst->type_argc, args);
3413 if (method->is_generic) {
3414 container = mono_method_get_generic_container (method);
3415 shared_context = container->context;
3416 inst = shared_context.method_inst;
3418 args = g_new0 (MonoType*, inst->type_argc);
3419 for (i = 0; i < container->type_argc; ++i) {
3420 MonoGenericParamInfo *info = &container->type_params [i].info;
3421 gboolean ref_only = FALSE;
3423 if (info && info->constraints) {
3424 constraints = info->constraints;
3426 while (*constraints) {
3427 MonoClass *cklass = *constraints;
3428 if (!(cklass == mono_defaults.object_class || (cklass->image == mono_defaults.corlib && !strcmp (cklass->name, "ValueType"))))
3429 /* Inflaring the method with our vtype would not be valid */
3436 args [i] = &mono_defaults.object_class->byval_arg;
3438 args [i] = &mono_defaults.int_class->byval_arg;
3440 ctx->method_inst = mono_metadata_get_generic_inst (inst->type_argc, args);
3445 add_wrappers (MonoAotCompile *acfg)
3447 MonoMethod *method, *m;
3449 MonoMethodSignature *sig, *csig;
3453 * FIXME: Instead of AOTing all the wrappers, it might be better to redesign them
3454 * so there is only one wrapper of a given type, or inlining their contents into their
3457 for (i = 0; i < acfg->image->tables [MONO_TABLE_METHOD].rows; ++i) {
3460 guint32 token = MONO_TOKEN_METHOD_DEF | (i + 1);
3461 gboolean skip = FALSE;
3463 method = mono_get_method_checked (acfg->image, token, NULL, NULL, &error);
3464 report_loader_error (acfg, &error, "Failed to load method token 0x%x due to %s\n", i, mono_error_get_message (&error));
3466 if ((method->flags & METHOD_ATTRIBUTE_PINVOKE_IMPL) ||
3467 (method->iflags & METHOD_IMPL_ATTRIBUTE_RUNTIME) ||
3468 (method->flags & METHOD_ATTRIBUTE_ABSTRACT))
3471 /* Skip methods which can not be handled by get_runtime_invoke () */
3472 sig = mono_method_signature (method);
3475 if ((sig->ret->type == MONO_TYPE_PTR) ||
3476 (sig->ret->type == MONO_TYPE_TYPEDBYREF))
3478 if (mono_class_is_open_constructed_type (sig->ret))
3481 for (j = 0; j < sig->param_count; j++) {
3482 if (sig->params [j]->type == MONO_TYPE_TYPEDBYREF)
3484 if (mono_class_is_open_constructed_type (sig->params [j]))
3488 #ifdef MONO_ARCH_DYN_CALL_SUPPORTED
3489 if (!mono_class_is_contextbound (method->klass)) {
3490 MonoDynCallInfo *info = mono_arch_dyn_call_prepare (sig);
3491 gboolean has_nullable = FALSE;
3493 for (j = 0; j < sig->param_count; j++) {
3494 if (sig->params [j]->type == MONO_TYPE_GENERICINST && mono_class_is_nullable (mono_class_from_mono_type (sig->params [j])))
3495 has_nullable = TRUE;
3498 if (info && !has_nullable) {
3499 /* Supported by the dynamic runtime-invoke wrapper */
3503 mono_arch_dyn_call_free (info);
3508 //printf ("%s\n", mono_method_full_name (method, TRUE));
3509 add_method (acfg, mono_marshal_get_runtime_invoke (method, FALSE));
3513 if (strcmp (acfg->image->assembly->aname.name, "mscorlib") == 0) {
3516 /* Runtime invoke wrappers */
3518 /* void runtime-invoke () [.cctor] */
3519 csig = mono_metadata_signature_alloc (mono_defaults.corlib, 0);
3520 csig->ret = &mono_defaults.void_class->byval_arg;
3521 add_method (acfg, get_runtime_invoke_sig (csig));
3523 /* void runtime-invoke () [Finalize] */
3524 csig = mono_metadata_signature_alloc (mono_defaults.corlib, 0);
3526 csig->ret = &mono_defaults.void_class->byval_arg;
3527 add_method (acfg, get_runtime_invoke_sig (csig));
3529 /* void runtime-invoke (string) [exception ctor] */
3530 csig = mono_metadata_signature_alloc (mono_defaults.corlib, 1);
3532 csig->ret = &mono_defaults.void_class->byval_arg;
3533 csig->params [0] = &mono_defaults.string_class->byval_arg;
3534 add_method (acfg, get_runtime_invoke_sig (csig));
3536 /* void runtime-invoke (string, string) [exception ctor] */
3537 csig = mono_metadata_signature_alloc (mono_defaults.corlib, 2);
3539 csig->ret = &mono_defaults.void_class->byval_arg;
3540 csig->params [0] = &mono_defaults.string_class->byval_arg;
3541 csig->params [1] = &mono_defaults.string_class->byval_arg;
3542 add_method (acfg, get_runtime_invoke_sig (csig));
3544 /* string runtime-invoke () [Exception.ToString ()] */
3545 csig = mono_metadata_signature_alloc (mono_defaults.corlib, 0);
3547 csig->ret = &mono_defaults.string_class->byval_arg;
3548 add_method (acfg, get_runtime_invoke_sig (csig));
3550 /* void runtime-invoke (string, Exception) [exception ctor] */
3551 csig = mono_metadata_signature_alloc (mono_defaults.corlib, 2);
3553 csig->ret = &mono_defaults.void_class->byval_arg;
3554 csig->params [0] = &mono_defaults.string_class->byval_arg;
3555 csig->params [1] = &mono_defaults.exception_class->byval_arg;
3556 add_method (acfg, get_runtime_invoke_sig (csig));
3558 /* Assembly runtime-invoke (string, bool) [DoAssemblyResolve] */
3559 csig = mono_metadata_signature_alloc (mono_defaults.corlib, 2);
3561 csig->ret = &(mono_class_from_name (
3562 mono_defaults.corlib, "System.Reflection", "Assembly"))->byval_arg;
3563 csig->params [0] = &mono_defaults.string_class->byval_arg;
3564 csig->params [1] = &mono_defaults.boolean_class->byval_arg;
3565 add_method (acfg, get_runtime_invoke_sig (csig));
3567 /* runtime-invoke used by finalizers */
3568 add_method (acfg, mono_marshal_get_runtime_invoke (mono_class_get_method_from_name_flags (mono_defaults.object_class, "Finalize", 0, 0), TRUE));
3570 /* This is used by mono_runtime_capture_context () */
3571 method = mono_get_context_capture_method ();
3573 add_method (acfg, mono_marshal_get_runtime_invoke (method, FALSE));
3575 #ifdef MONO_ARCH_DYN_CALL_SUPPORTED
3576 add_method (acfg, mono_marshal_get_runtime_invoke_dynamic ());
3580 add_method (acfg, mono_marshal_get_stelemref ());
3582 if (MONO_ARCH_HAVE_TLS_GET) {
3583 /* Managed Allocators */
3584 nallocators = mono_gc_get_managed_allocator_types ();
3585 for (i = 0; i < nallocators; ++i) {
3586 m = mono_gc_get_managed_allocator_by_type (i, TRUE);
3588 add_method (acfg, m);
3590 for (i = 0; i < nallocators; ++i) {
3591 m = mono_gc_get_managed_allocator_by_type (i, FALSE);
3593 add_method (acfg, m);
3597 /* write barriers */
3598 if (mono_gc_is_moving ()) {
3599 add_method (acfg, mono_gc_get_specific_write_barrier (FALSE));
3600 add_method (acfg, mono_gc_get_specific_write_barrier (TRUE));
3603 /* Stelemref wrappers */
3605 MonoMethod **wrappers;
3608 wrappers = mono_marshal_get_virtual_stelemref_wrappers (&nwrappers);
3609 for (i = 0; i < nwrappers; ++i)
3610 add_method (acfg, wrappers [i]);
3614 /* castclass_with_check wrapper */
3615 add_method (acfg, mono_marshal_get_castclass_with_cache ());
3616 /* isinst_with_check wrapper */
3617 add_method (acfg, mono_marshal_get_isinst_with_cache ());
3619 /* JIT icall wrappers */
3620 /* FIXME: locking - this is "safe" as full-AOT threads don't mutate the icall hash*/
3621 g_hash_table_foreach (mono_get_jit_icall_info (), add_jit_icall_wrapper, acfg);
3625 * remoting-invoke-with-check wrappers are very frequent, so avoid emitting them,
3626 * we use the original method instead at runtime.
3627 * Since full-aot doesn't support remoting, this is not a problem.
3630 /* remoting-invoke wrappers */
3631 for (i = 0; i < acfg->image->tables [MONO_TABLE_METHOD].rows; ++i) {
3632 MonoMethodSignature *sig;
3634 token = MONO_TOKEN_METHOD_DEF | (i + 1);
3635 method = mono_get_method (acfg->image, token, NULL);
3637 sig = mono_method_signature (method);
3639 if (sig->hasthis && (method->klass->marshalbyref || method->klass == mono_defaults.object_class)) {
3640 m = mono_marshal_get_remoting_invoke_with_check (method);
3642 add_method (acfg, m);
3647 /* delegate-invoke wrappers */
3648 for (i = 0; i < acfg->image->tables [MONO_TABLE_TYPEDEF].rows; ++i) {
3651 MonoCustomAttrInfo *cattr;
3653 token = MONO_TOKEN_TYPE_DEF | (i + 1);
3654 klass = mono_class_get_checked (acfg->image, token, &error);
3657 mono_error_cleanup (&error);
3661 if (!klass->delegate || klass == mono_defaults.delegate_class || klass == mono_defaults.multicastdelegate_class)
3664 if (!klass->generic_container) {
3665 method = mono_get_delegate_invoke (klass);
3667 m = mono_marshal_get_delegate_invoke (method, NULL);
3669 add_method (acfg, m);
3671 method = mono_class_get_method_from_name_flags (klass, "BeginInvoke", -1, 0);
3673 add_method (acfg, mono_marshal_get_delegate_begin_invoke (method));
3675 method = mono_class_get_method_from_name_flags (klass, "EndInvoke", -1, 0);
3677 add_method (acfg, mono_marshal_get_delegate_end_invoke (method));
3679 cattr = mono_custom_attrs_from_class (klass);
3684 for (j = 0; j < cattr->num_attrs; ++j)
3685 if (cattr->attrs [j].ctor && (!strcmp (cattr->attrs [j].ctor->klass->name, "MonoNativeFunctionWrapperAttribute") || !strcmp (cattr->attrs [j].ctor->klass->name, "UnmanagedFunctionPointerAttribute")))
3687 if (j < cattr->num_attrs) {
3689 MonoMethod *wrapper;
3690 MonoMethod *del_invoke;
3692 /* Add wrappers needed by mono_ftnptr_to_delegate () */
3693 invoke = mono_get_delegate_invoke (klass);
3694 wrapper = mono_marshal_get_native_func_wrapper_aot (klass);
3695 del_invoke = mono_marshal_get_delegate_invoke_internal (invoke, FALSE, TRUE, wrapper);
3696 add_method (acfg, wrapper);
3697 add_method (acfg, del_invoke);
3700 } else if ((acfg->opts & MONO_OPT_GSHAREDVT) && klass->generic_container) {
3702 MonoGenericContext ctx;
3703 MonoMethod *inst, *gshared;
3706 * Emit gsharedvt versions of the generic delegate-invoke wrappers
3709 method = mono_get_delegate_invoke (klass);
3710 create_gsharedvt_inst (acfg, method, &ctx);
3712 inst = mono_class_inflate_generic_method_checked (method, &ctx, &error);
3713 g_assert (mono_error_ok (&error)); /* FIXME don't swallow the error */
3715 m = mono_marshal_get_delegate_invoke (inst, NULL);
3716 g_assert (m->is_inflated);
3718 gshared = mini_get_shared_method_full (m, FALSE, TRUE);
3719 add_extra_method (acfg, gshared);
3722 method = mono_get_delegate_begin_invoke (klass);
3723 create_gsharedvt_inst (acfg, method, &ctx);
3725 inst = mono_class_inflate_generic_method_checked (method, &ctx, &error);
3726 g_assert (mono_error_ok (&error)); /* FIXME don't swallow the error */
3728 m = mono_marshal_get_delegate_begin_invoke (inst);
3729 g_assert (m->is_inflated);
3731 gshared = mini_get_shared_method_full (m, FALSE, TRUE);
3732 add_extra_method (acfg, gshared);
3735 method = mono_get_delegate_end_invoke (klass);
3736 create_gsharedvt_inst (acfg, method, &ctx);
3738 inst = mono_class_inflate_generic_method_checked (method, &ctx, &error);
3739 g_assert (mono_error_ok (&error)); /* FIXME don't swallow the error */
3741 m = mono_marshal_get_delegate_end_invoke (inst);
3742 g_assert (m->is_inflated);
3744 gshared = mini_get_shared_method_full (m, FALSE, TRUE);
3745 add_extra_method (acfg, gshared);
3750 /* array access wrappers */
3751 for (i = 0; i < acfg->image->tables [MONO_TABLE_TYPESPEC].rows; ++i) {
3755 token = MONO_TOKEN_TYPE_SPEC | (i + 1);
3756 klass = mono_class_get_checked (acfg->image, token, &error);
3759 mono_error_cleanup (&error);
3763 if (klass->rank && MONO_TYPE_IS_PRIMITIVE (&klass->element_class->byval_arg)) {
3764 MonoMethod *m, *wrapper;
3766 /* Add runtime-invoke wrappers too */
3768 m = mono_class_get_method_from_name (klass, "Get", -1);
3770 wrapper = mono_marshal_get_array_accessor_wrapper (m);
3771 add_extra_method (acfg, wrapper);
3772 add_extra_method (acfg, mono_marshal_get_runtime_invoke (wrapper, FALSE));
3774 m = mono_class_get_method_from_name (klass, "Set", -1);
3776 wrapper = mono_marshal_get_array_accessor_wrapper (m);
3777 add_extra_method (acfg, wrapper);
3778 add_extra_method (acfg, mono_marshal_get_runtime_invoke (wrapper, FALSE));
3782 /* Synchronized wrappers */
3783 for (i = 0; i < acfg->image->tables [MONO_TABLE_METHOD].rows; ++i) {
3785 token = MONO_TOKEN_METHOD_DEF | (i + 1);
3786 method = mono_get_method_checked (acfg->image, token, NULL, NULL, &error);
3787 report_loader_error (acfg, &error, "Failed to load method token 0x%x due to %s\n", i, mono_error_get_message (&error));
3789 if (method->iflags & METHOD_IMPL_ATTRIBUTE_SYNCHRONIZED) {
3790 if (method->is_generic) {
3792 } else if ((acfg->opts & MONO_OPT_GSHAREDVT) && method->klass->generic_container) {
3794 MonoGenericContext ctx;
3795 MonoMethod *inst, *gshared, *m;
3798 * Create a generic wrapper for a generic instance, and AOT that.
3800 create_gsharedvt_inst (acfg, method, &ctx);
3801 inst = mono_class_inflate_generic_method_checked (method, &ctx, &error);
3802 g_assert (mono_error_ok (&error)); /* FIXME don't swallow the error */
3803 m = mono_marshal_get_synchronized_wrapper (inst);
3804 g_assert (m->is_inflated);
3805 gshared = mini_get_shared_method_full (m, FALSE, TRUE);
3806 add_method (acfg, gshared);
3808 add_method (acfg, mono_marshal_get_synchronized_wrapper (method));
3813 /* pinvoke wrappers */
3814 for (i = 0; i < acfg->image->tables [MONO_TABLE_METHOD].rows; ++i) {
3817 guint32 token = MONO_TOKEN_METHOD_DEF | (i + 1);
3819 method = mono_get_method_checked (acfg->image, token, NULL, NULL, &error);
3820 report_loader_error (acfg, &error, "Failed to load method token 0x%x due to %s\n", i, mono_error_get_message (&error));
3822 if ((method->flags & METHOD_ATTRIBUTE_PINVOKE_IMPL) ||
3823 (method->iflags & METHOD_IMPL_ATTRIBUTE_INTERNAL_CALL)) {
3824 add_method (acfg, mono_marshal_get_native_wrapper (method, TRUE, TRUE));
3828 /* native-to-managed wrappers */
3829 for (i = 0; i < acfg->image->tables [MONO_TABLE_METHOD].rows; ++i) {
3832 guint32 token = MONO_TOKEN_METHOD_DEF | (i + 1);
3833 MonoCustomAttrInfo *cattr;
3836 method = mono_get_method_checked (acfg->image, token, NULL, NULL, &error);
3837 report_loader_error (acfg, &error, "Failed to load method token 0x%x due to %s\n", i, mono_error_get_message (&error));
3840 * Only generate native-to-managed wrappers for methods which have an
3841 * attribute named MonoPInvokeCallbackAttribute. We search for the attribute by
3842 * name to avoid defining a new assembly to contain it.
3844 cattr = mono_custom_attrs_from_method (method);
3847 for (j = 0; j < cattr->num_attrs; ++j)
3848 if (cattr->attrs [j].ctor && !strcmp (cattr->attrs [j].ctor->klass->name, "MonoPInvokeCallbackAttribute"))
3850 if (j < cattr->num_attrs) {
3851 MonoCustomAttrEntry *e = &cattr->attrs [j];
3852 MonoMethodSignature *sig = mono_method_signature (e->ctor);
3853 const char *p = (const char*)e->data;
3855 int slen, num_named, named_type;
3859 char *export_name = NULL;
3860 MonoMethod *wrapper;
3862 /* this cannot be enforced by the C# compiler so we must give the user some warning before aborting */
3863 if (!(method->flags & METHOD_ATTRIBUTE_STATIC)) {
3864 g_warning ("AOT restriction: Method '%s' must be static since it is decorated with [MonoPInvokeCallback]. See http://ios.xamarin.com/Documentation/Limitations#Reverse_Callbacks",
3865 mono_method_full_name (method, TRUE));
3869 g_assert (sig->param_count == 1);
3870 g_assert (sig->params [0]->type == MONO_TYPE_CLASS && !strcmp (mono_class_from_mono_type (sig->params [0])->name, "Type"));
3873 * Decode the cattr manually since we can't create objects
3874 * during aot compilation.
3880 /* From load_cattr_value () in reflection.c */
3881 slen = mono_metadata_decode_value (p, &p);
3882 n = g_memdup (p, slen + 1);
3884 t = mono_reflection_type_from_name (n, acfg->image);
3888 klass = mono_class_from_mono_type (t);
3889 g_assert (klass->parent == mono_defaults.multicastdelegate_class);
3893 num_named = read16 (p);
3896 g_assert (num_named < 2);
3897 if (num_named == 1) {
3901 /* parse ExportSymbol attribute */
3903 named_type = *named;
3905 /* data_type = *named; */
3908 name_len = mono_metadata_decode_blob_size (named, &named);
3909 name = g_malloc (name_len + 1);
3910 memcpy (name, named, name_len);
3911 name [name_len] = 0;
3914 g_assert (named_type == 0x54);
3915 g_assert (!strcmp (name, "ExportSymbol"));
3917 /* load_cattr_value (), string case */
3918 g_assert (*named != (char)0xff);
3919 slen = mono_metadata_decode_value (named, &named);
3920 export_name = g_malloc (slen + 1);
3921 memcpy (export_name, named, slen);
3922 export_name [slen] = 0;
3926 wrapper = mono_marshal_get_managed_wrapper (method, klass, 0);
3927 add_method (acfg, wrapper);
3929 g_hash_table_insert (acfg->export_names, wrapper, export_name);
3933 if ((method->flags & METHOD_ATTRIBUTE_PINVOKE_IMPL) ||
3934 (method->iflags & METHOD_IMPL_ATTRIBUTE_INTERNAL_CALL)) {
3935 add_method (acfg, mono_marshal_get_native_wrapper (method, TRUE, TRUE));
3939 /* StructureToPtr/PtrToStructure wrappers */
3940 for (i = 0; i < acfg->image->tables [MONO_TABLE_TYPEDEF].rows; ++i) {
3944 token = MONO_TOKEN_TYPE_DEF | (i + 1);
3945 klass = mono_class_get_checked (acfg->image, token, &error);
3948 mono_error_cleanup (&error);
3952 if (klass->valuetype && !klass->generic_container && can_marshal_struct (klass) &&
3953 !(klass->nested_in && strstr (klass->nested_in->name, "<PrivateImplementationDetails>") == klass->nested_in->name)) {
3954 add_method (acfg, mono_marshal_get_struct_to_ptr (klass));
3955 add_method (acfg, mono_marshal_get_ptr_to_struct (klass));
3961 has_type_vars (MonoClass *klass)
3963 if ((klass->byval_arg.type == MONO_TYPE_VAR) || (klass->byval_arg.type == MONO_TYPE_MVAR))
3966 return has_type_vars (klass->element_class);
3967 if (klass->generic_class) {
3968 MonoGenericContext *context = &klass->generic_class->context;
3969 if (context->class_inst) {
3972 for (i = 0; i < context->class_inst->type_argc; ++i)
3973 if (has_type_vars (mono_class_from_mono_type (context->class_inst->type_argv [i])))
3977 if (klass->generic_container)
3983 is_vt_inst (MonoGenericInst *inst)
3987 for (i = 0; i < inst->type_argc; ++i) {
3988 MonoType *t = inst->type_argv [i];
3989 if (MONO_TYPE_ISSTRUCT (t) || t->type == MONO_TYPE_VALUETYPE)
3996 method_has_type_vars (MonoMethod *method)
3998 if (has_type_vars (method->klass))
4001 if (method->is_inflated) {
4002 MonoGenericContext *context = mono_method_get_context (method);
4003 if (context->method_inst) {
4006 for (i = 0; i < context->method_inst->type_argc; ++i)
4007 if (has_type_vars (mono_class_from_mono_type (context->method_inst->type_argv [i])))
4015 gboolean mono_aot_mode_is_full (MonoAotOptions *opts)
4017 return opts->mode == MONO_AOT_MODE_FULL;
4020 static void add_generic_class_with_depth (MonoAotCompile *acfg, MonoClass *klass, int depth, const char *ref);
4023 add_generic_class (MonoAotCompile *acfg, MonoClass *klass, gboolean force, const char *ref)
4025 /* This might lead to a huge code blowup so only do it if neccesary */
4026 if (!mono_aot_mode_is_full (&acfg->aot_opts) && !force)
4029 add_generic_class_with_depth (acfg, klass, 0, ref);
4033 check_type_depth (MonoType *t, int depth)
4041 case MONO_TYPE_GENERICINST: {
4042 MonoGenericClass *gklass = t->data.generic_class;
4043 MonoGenericInst *ginst = gklass->context.class_inst;
4046 for (i = 0; i < ginst->type_argc; ++i) {
4047 if (check_type_depth (ginst->type_argv [i], depth + 1))
4061 add_types_from_method_header (MonoAotCompile *acfg, MonoMethod *method);
4064 * add_generic_class:
4066 * Add all methods of a generic class.
4069 add_generic_class_with_depth (MonoAotCompile *acfg, MonoClass *klass, int depth, const char *ref)
4072 MonoClassField *field;
4074 gboolean use_gsharedvt = FALSE;
4076 if (!acfg->ginst_hash)
4077 acfg->ginst_hash = g_hash_table_new (NULL, NULL);
4079 mono_class_init (klass);
4081 if (klass->generic_class && klass->generic_class->context.class_inst->is_open)
4084 if (has_type_vars (klass))
4087 if (!klass->generic_class && !klass->rank)
4090 if (klass->exception_type)
4093 if (!acfg->ginst_hash)
4094 acfg->ginst_hash = g_hash_table_new (NULL, NULL);
4096 if (g_hash_table_lookup (acfg->ginst_hash, klass))
4099 if (check_type_depth (&klass->byval_arg, 0))
4102 if (acfg->aot_opts.log_generics)
4103 aot_printf (acfg, "%*sAdding generic instance %s [%s].\n", depth, "", mono_type_full_name (&klass->byval_arg), ref);
4105 g_hash_table_insert (acfg->ginst_hash, klass, klass);
4108 * Use gsharedvt for generic collections with vtype arguments to avoid code blowup.
4109 * Enable this only for some classes since gsharedvt might not support all methods.
4111 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) &&
4112 (!strcmp (klass->name, "Dictionary`2") || !strcmp (klass->name, "List`1") || !strcmp (klass->name, "ReadOnlyCollection`1")))
4113 use_gsharedvt = TRUE;
4116 while ((method = mono_class_get_methods (klass, &iter))) {
4117 if ((acfg->opts & MONO_OPT_GSHAREDVT) && method->is_inflated && mono_method_get_context (method)->method_inst) {
4119 * This is partial sharing, and we can't handle it yet
4124 if (mono_method_is_generic_sharable_full (method, FALSE, FALSE, use_gsharedvt)) {
4126 add_types_from_method_header (acfg, method);
4130 if (method->is_generic)
4135 * FIXME: Instances which are referenced by these methods are not added,
4136 * for example Array.Resize<int> for List<int>.Add ().
4138 add_extra_method_with_depth (acfg, method, depth + 1);
4142 while ((field = mono_class_get_fields (klass, &iter))) {
4143 if (field->type->type == MONO_TYPE_GENERICINST)
4144 add_generic_class_with_depth (acfg, mono_class_from_mono_type (field->type), depth + 1, "field");
4147 if (klass->delegate) {
4148 method = mono_get_delegate_invoke (klass);
4150 method = mono_marshal_get_delegate_invoke (method, NULL);
4152 if (acfg->aot_opts.log_generics)
4153 aot_printf (acfg, "%*sAdding method %s.\n", depth, "", mono_method_full_name (method, TRUE));
4155 add_method (acfg, method);
4158 /* Add superclasses */
4160 add_generic_class_with_depth (acfg, klass->parent, depth, "parent");
4163 * For ICollection<T>, add instances of the helper methods
4164 * in Array, since a T[] could be cast to ICollection<T>.
4166 if (klass->image == mono_defaults.corlib && !strcmp (klass->name_space, "System.Collections.Generic") &&
4167 (!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"))) {
4168 MonoClass *tclass = mono_class_from_mono_type (klass->generic_class->context.class_inst->type_argv [0]);
4169 MonoClass *array_class = mono_bounded_array_class_get (tclass, 1, FALSE);
4173 if (!strcmp (klass->name, "IEnumerator`1"))
4174 name_prefix = g_strdup_printf ("%s.%s", klass->name_space, "IEnumerable`1");
4176 name_prefix = g_strdup_printf ("%s.%s", klass->name_space, klass->name);
4178 /* Add the T[]/InternalEnumerator class */
4179 if (!strcmp (klass->name, "IEnumerable`1") || !strcmp (klass->name, "IEnumerator`1")) {
4183 while ((nclass = mono_class_get_nested_types (array_class->parent, &iter))) {
4184 if (!strcmp (nclass->name, "InternalEnumerator`1"))
4188 nclass = mono_class_inflate_generic_class (nclass, mono_generic_class_get_context (klass->generic_class));
4189 add_generic_class (acfg, nclass, FALSE, "ICollection<T>");
4193 while ((method = mono_class_get_methods (array_class, &iter))) {
4194 if (strstr (method->name, name_prefix)) {
4195 MonoMethod *m = mono_aot_get_array_helper_from_wrapper (method);
4197 add_extra_method_with_depth (acfg, m, depth);
4201 g_free (name_prefix);
4204 /* Add an instance of GenericComparer<T> which is created dynamically by Comparer<T> */
4205 if (klass->image == mono_defaults.corlib && !strcmp (klass->name_space, "System.Collections.Generic") && !strcmp (klass->name, "Comparer`1")) {
4206 MonoClass *tclass = mono_class_from_mono_type (klass->generic_class->context.class_inst->type_argv [0]);
4207 MonoClass *icomparable, *gcomparer;
4208 MonoGenericContext ctx;
4209 MonoType *args [16];
4211 memset (&ctx, 0, sizeof (ctx));
4213 icomparable = mono_class_from_name (mono_defaults.corlib, "System", "IComparable`1");
4214 g_assert (icomparable);
4215 args [0] = &tclass->byval_arg;
4216 ctx.class_inst = mono_metadata_get_generic_inst (1, args);
4218 if (mono_class_is_assignable_from (mono_class_inflate_generic_class (icomparable, &ctx), tclass)) {
4219 gcomparer = mono_class_from_name (mono_defaults.corlib, "System.Collections.Generic", "GenericComparer`1");
4220 g_assert (gcomparer);
4221 add_generic_class (acfg, mono_class_inflate_generic_class (gcomparer, &ctx), FALSE, "Comparer<T>");
4225 /* Add an instance of GenericEqualityComparer<T> which is created dynamically by EqualityComparer<T> */
4226 if (klass->image == mono_defaults.corlib && !strcmp (klass->name_space, "System.Collections.Generic") && !strcmp (klass->name, "EqualityComparer`1")) {
4227 MonoClass *tclass = mono_class_from_mono_type (klass->generic_class->context.class_inst->type_argv [0]);
4228 MonoClass *iface, *gcomparer;
4229 MonoGenericContext ctx;
4230 MonoType *args [16];
4232 memset (&ctx, 0, sizeof (ctx));
4234 iface = mono_class_from_name (mono_defaults.corlib, "System", "IEquatable`1");
4236 args [0] = &tclass->byval_arg;
4237 ctx.class_inst = mono_metadata_get_generic_inst (1, args);
4239 if (mono_class_is_assignable_from (mono_class_inflate_generic_class (iface, &ctx), tclass)) {
4240 gcomparer = mono_class_from_name (mono_defaults.corlib, "System.Collections.Generic", "GenericEqualityComparer`1");
4241 g_assert (gcomparer);
4242 add_generic_class (acfg, mono_class_inflate_generic_class (gcomparer, &ctx), FALSE, "EqualityComparer<T>");
4246 /* Add an instance of EnumComparer<T> which is created dynamically by EqualityComparer<T> for enums */
4247 if (klass->image == mono_defaults.corlib && !strcmp (klass->name_space, "System.Collections.Generic") && !strcmp (klass->name, "EqualityComparer`1")) {
4248 MonoClass *enum_comparer;
4249 MonoClass *tclass = mono_class_from_mono_type (klass->generic_class->context.class_inst->type_argv [0]);
4250 MonoGenericContext ctx;
4251 MonoType *args [16];
4253 if (mono_class_is_enum (tclass)) {
4254 memset (&ctx, 0, sizeof (ctx));
4255 args [0] = &tclass->byval_arg;
4256 ctx.class_inst = mono_metadata_get_generic_inst (1, args);
4258 enum_comparer = mono_class_from_name (mono_defaults.corlib, "System.Collections.Generic", "EnumEqualityComparer`1");
4259 g_assert (enum_comparer);
4260 add_generic_class (acfg, mono_class_inflate_generic_class (enum_comparer, &ctx), FALSE, "EqualityComparer<T>");
4264 /* Add an instance of ObjectComparer<T> which is created dynamically by Comparer<T> for enums */
4265 if (klass->image == mono_defaults.corlib && !strcmp (klass->name_space, "System.Collections.Generic") && !strcmp (klass->name, "Comparer`1")) {
4266 MonoClass *comparer;
4267 MonoClass *tclass = mono_class_from_mono_type (klass->generic_class->context.class_inst->type_argv [0]);
4268 MonoGenericContext ctx;
4269 MonoType *args [16];
4271 if (mono_class_is_enum (tclass)) {
4272 memset (&ctx, 0, sizeof (ctx));
4273 args [0] = &tclass->byval_arg;
4274 ctx.class_inst = mono_metadata_get_generic_inst (1, args);
4276 comparer = mono_class_from_name (mono_defaults.corlib, "System.Collections.Generic", "ObjectComparer`1");
4277 g_assert (comparer);
4278 add_generic_class (acfg, mono_class_inflate_generic_class (comparer, &ctx), FALSE, "Comparer<T>");
4284 add_instances_of (MonoAotCompile *acfg, MonoClass *klass, MonoType **insts, int ninsts, gboolean force)
4287 MonoGenericContext ctx;
4288 MonoType *args [16];
4290 if (acfg->aot_opts.no_instances)
4293 memset (&ctx, 0, sizeof (ctx));
4295 for (i = 0; i < ninsts; ++i) {
4296 args [0] = insts [i];
4297 ctx.class_inst = mono_metadata_get_generic_inst (1, args);
4298 add_generic_class (acfg, mono_class_inflate_generic_class (klass, &ctx), force, "");
4303 add_types_from_method_header (MonoAotCompile *acfg, MonoMethod *method)
4305 MonoMethodHeader *header;
4306 MonoMethodSignature *sig;
4309 depth = GPOINTER_TO_UINT (g_hash_table_lookup (acfg->method_depth, method));
4311 sig = mono_method_signature (method);
4314 for (j = 0; j < sig->param_count; ++j)
4315 if (sig->params [j]->type == MONO_TYPE_GENERICINST)
4316 add_generic_class_with_depth (acfg, mono_class_from_mono_type (sig->params [j]), depth + 1, "arg");
4319 header = mono_method_get_header (method);
4322 for (j = 0; j < header->num_locals; ++j)
4323 if (header->locals [j]->type == MONO_TYPE_GENERICINST)
4324 add_generic_class_with_depth (acfg, mono_class_from_mono_type (header->locals [j]), depth + 1, "local");
4326 mono_loader_clear_error ();
4331 * add_generic_instances:
4333 * Add instances referenced by the METHODSPEC/TYPESPEC table.
4336 add_generic_instances (MonoAotCompile *acfg)
4341 MonoGenericContext *context;
4343 if (acfg->aot_opts.no_instances)
4346 for (i = 0; i < acfg->image->tables [MONO_TABLE_METHODSPEC].rows; ++i) {
4348 token = MONO_TOKEN_METHOD_SPEC | (i + 1);
4349 method = mono_get_method_checked (acfg->image, token, NULL, NULL, &error);
4352 aot_printerrf (acfg, "Failed to load methodspec 0x%x due to %s.\n", token, mono_error_get_message (&error));
4353 aot_printerrf (acfg, "Run with MONO_LOG_LEVEL=debug for more information.\n");
4354 mono_error_cleanup (&error);
4358 if (method->klass->image != acfg->image)
4361 context = mono_method_get_context (method);
4363 if (context && ((context->class_inst && context->class_inst->is_open)))
4367 * For open methods, create an instantiation which can be passed to the JIT.
4368 * FIXME: Handle class_inst as well.
4370 if (context && context->method_inst && context->method_inst->is_open) {
4372 MonoGenericContext shared_context;
4373 MonoGenericInst *inst;
4374 MonoType **type_argv;
4376 MonoMethod *declaring_method;
4377 gboolean supported = TRUE;
4379 /* Check that the context doesn't contain open constructed types */
4380 if (context->class_inst) {
4381 inst = context->class_inst;
4382 for (i = 0; i < inst->type_argc; ++i) {
4383 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)
4385 if (mono_class_is_open_constructed_type (inst->type_argv [i]))
4389 if (context->method_inst) {
4390 inst = context->method_inst;
4391 for (i = 0; i < inst->type_argc; ++i) {
4392 if (MONO_TYPE_IS_REFERENCE (inst->type_argv [i]) || inst->type_argv [i]->type == MONO_TYPE_VAR || inst->type_argv [i]->type == MONO_TYPE_MVAR)
4394 if (mono_class_is_open_constructed_type (inst->type_argv [i]))
4402 memset (&shared_context, 0, sizeof (MonoGenericContext));
4404 inst = context->class_inst;
4406 type_argv = g_new0 (MonoType*, inst->type_argc);
4407 for (i = 0; i < inst->type_argc; ++i) {
4408 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)
4409 type_argv [i] = &mono_defaults.object_class->byval_arg;
4411 type_argv [i] = inst->type_argv [i];
4414 shared_context.class_inst = mono_metadata_get_generic_inst (inst->type_argc, type_argv);
4418 inst = context->method_inst;
4420 type_argv = g_new0 (MonoType*, inst->type_argc);
4421 for (i = 0; i < inst->type_argc; ++i) {
4422 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)
4423 type_argv [i] = &mono_defaults.object_class->byval_arg;
4425 type_argv [i] = inst->type_argv [i];
4428 shared_context.method_inst = mono_metadata_get_generic_inst (inst->type_argc, type_argv);
4432 if (method->is_generic || method->klass->generic_container)
4433 declaring_method = method;
4435 declaring_method = mono_method_get_declaring_generic_method (method);
4437 method = mono_class_inflate_generic_method_checked (declaring_method, &shared_context, &error);
4438 g_assert (mono_error_ok (&error)); /* FIXME don't swallow the error */
4442 * If the method is fully sharable, it was already added in place of its
4443 * generic definition.
4445 if (mono_method_is_generic_sharable_full (method, FALSE, FALSE, FALSE))
4449 * FIXME: Partially shared methods are not shared here, so we end up with
4450 * many identical methods.
4452 add_extra_method (acfg, method);
4455 for (i = 0; i < acfg->image->tables [MONO_TABLE_TYPESPEC].rows; ++i) {
4459 token = MONO_TOKEN_TYPE_SPEC | (i + 1);
4461 klass = mono_class_get_checked (acfg->image, token, &error);
4462 if (!klass || klass->rank) {
4463 mono_error_cleanup (&error);
4467 add_generic_class (acfg, klass, FALSE, "typespec");
4470 /* Add types of args/locals */
4471 for (i = 0; i < acfg->methods->len; ++i) {
4472 method = g_ptr_array_index (acfg->methods, i);
4473 add_types_from_method_header (acfg, method);
4476 if (acfg->image == mono_defaults.corlib) {
4478 MonoType *insts [256];
4481 insts [ninsts ++] = &mono_defaults.byte_class->byval_arg;
4482 insts [ninsts ++] = &mono_defaults.sbyte_class->byval_arg;
4483 insts [ninsts ++] = &mono_defaults.int16_class->byval_arg;
4484 insts [ninsts ++] = &mono_defaults.uint16_class->byval_arg;
4485 insts [ninsts ++] = &mono_defaults.int32_class->byval_arg;
4486 insts [ninsts ++] = &mono_defaults.uint32_class->byval_arg;
4487 insts [ninsts ++] = &mono_defaults.int64_class->byval_arg;
4488 insts [ninsts ++] = &mono_defaults.uint64_class->byval_arg;
4489 insts [ninsts ++] = &mono_defaults.single_class->byval_arg;
4490 insts [ninsts ++] = &mono_defaults.double_class->byval_arg;
4491 insts [ninsts ++] = &mono_defaults.char_class->byval_arg;
4492 insts [ninsts ++] = &mono_defaults.boolean_class->byval_arg;
4494 /* Add GenericComparer<T> instances for primitive types for Enum.ToString () */
4495 klass = mono_class_from_name (acfg->image, "System.Collections.Generic", "GenericComparer`1");
4497 add_instances_of (acfg, klass, insts, ninsts, TRUE);
4498 klass = mono_class_from_name (acfg->image, "System.Collections.Generic", "GenericEqualityComparer`1");
4500 add_instances_of (acfg, klass, insts, ninsts, TRUE);
4502 /* Add instances of the array generic interfaces for primitive types */
4503 /* This will add instances of the InternalArray_ helper methods in Array too */
4504 klass = mono_class_from_name (acfg->image, "System.Collections.Generic", "ICollection`1");
4506 add_instances_of (acfg, klass, insts, ninsts, TRUE);
4507 klass = mono_class_from_name (acfg->image, "System.Collections.Generic", "IList`1");
4509 add_instances_of (acfg, klass, insts, ninsts, TRUE);
4510 klass = mono_class_from_name (acfg->image, "System.Collections.Generic", "IEnumerable`1");
4512 add_instances_of (acfg, klass, insts, ninsts, TRUE);
4515 * Add a managed-to-native wrapper of Array.GetGenericValueImpl<object>, which is
4516 * used for all instances of GetGenericValueImpl by the AOT runtime.
4519 MonoGenericContext ctx;
4520 MonoType *args [16];
4521 MonoMethod *get_method;
4522 MonoClass *array_klass = mono_array_class_get (mono_defaults.object_class, 1)->parent;
4524 get_method = mono_class_get_method_from_name (array_klass, "GetGenericValueImpl", 2);
4528 memset (&ctx, 0, sizeof (ctx));
4529 args [0] = &mono_defaults.object_class->byval_arg;
4530 ctx.method_inst = mono_metadata_get_generic_inst (1, args);
4531 add_extra_method (acfg, mono_marshal_get_native_wrapper (mono_class_inflate_generic_method_checked (get_method, &ctx, &error), TRUE, TRUE));
4532 g_assert (mono_error_ok (&error)); /* FIXME don't swallow the error */
4536 /* Same for CompareExchange<T>/Exchange<T> */
4538 MonoGenericContext ctx;
4539 MonoType *args [16];
4541 MonoClass *interlocked_klass = mono_class_from_name (mono_defaults.corlib, "System.Threading", "Interlocked");
4542 gpointer iter = NULL;
4544 while ((m = mono_class_get_methods (interlocked_klass, &iter))) {
4545 if ((!strcmp (m->name, "CompareExchange") || !strcmp (m->name, "Exchange")) && m->is_generic) {
4547 memset (&ctx, 0, sizeof (ctx));
4548 args [0] = &mono_defaults.object_class->byval_arg;
4549 ctx.method_inst = mono_metadata_get_generic_inst (1, args);
4550 add_extra_method (acfg, mono_marshal_get_native_wrapper (mono_class_inflate_generic_method_checked (m, &ctx, &error), TRUE, TRUE));
4551 g_assert (mono_error_ok (&error)); /* FIXME don't swallow the error */
4556 /* Same for Volatile.Read/Write<T> */
4558 MonoGenericContext ctx;
4559 MonoType *args [16];
4561 MonoClass *volatile_klass = mono_class_from_name (mono_defaults.corlib, "System.Threading", "Volatile");
4562 gpointer iter = NULL;
4564 if (volatile_klass) {
4565 while ((m = mono_class_get_methods (volatile_klass, &iter))) {
4566 if ((!strcmp (m->name, "Read") || !strcmp (m->name, "Write")) && m->is_generic) {
4568 memset (&ctx, 0, sizeof (ctx));
4569 args [0] = &mono_defaults.object_class->byval_arg;
4570 ctx.method_inst = mono_metadata_get_generic_inst (1, args);
4571 add_extra_method (acfg, mono_marshal_get_native_wrapper (mono_class_inflate_generic_method_checked (m, &ctx, &error), TRUE, TRUE));
4572 g_assert (mono_error_ok (&error)); /* FIXME don't swallow the error */
4581 * is_direct_callable:
4583 * Return whenever the method identified by JI is directly callable without
4584 * going through the PLT.
4587 is_direct_callable (MonoAotCompile *acfg, MonoMethod *method, MonoJumpInfo *patch_info)
4589 if ((patch_info->type == MONO_PATCH_INFO_METHOD) && (patch_info->data.method->klass->image == acfg->image)) {
4590 MonoCompile *callee_cfg = g_hash_table_lookup (acfg->method_to_cfg, patch_info->data.method);
4592 gboolean direct_callable = TRUE;
4594 if (direct_callable && !(!callee_cfg->has_got_slots && (callee_cfg->method->klass->flags & TYPE_ATTRIBUTE_BEFORE_FIELD_INIT)))
4595 direct_callable = FALSE;
4596 if ((callee_cfg->method->iflags & METHOD_IMPL_ATTRIBUTE_SYNCHRONIZED) && (!method || method->wrapper_type != MONO_WRAPPER_SYNCHRONIZED))
4597 // FIXME: Maybe call the wrapper directly ?
4598 direct_callable = FALSE;
4600 if (acfg->aot_opts.soft_debug || acfg->aot_opts.no_direct_calls) {
4601 /* Disable this so all calls go through load_method (), see the
4602 * mini_get_debug_options ()->load_aot_jit_info_eagerly = TRUE; line in
4603 * mono_debugger_agent_init ().
4605 direct_callable = FALSE;
4608 if (callee_cfg->method->wrapper_type == MONO_WRAPPER_ALLOC)
4609 /* sgen does some initialization when the allocator method is created */
4610 direct_callable = FALSE;
4611 if (callee_cfg->method->wrapper_type == MONO_WRAPPER_WRITE_BARRIER)
4612 /* we don't know at compile time whether sgen is concurrent or not */
4613 direct_callable = FALSE;
4615 if (direct_callable)
4618 } else if ((patch_info->type == MONO_PATCH_INFO_ICALL_ADDR && patch_info->data.method->flags & METHOD_ATTRIBUTE_PINVOKE_IMPL)) {
4619 if (acfg->aot_opts.direct_pinvoke)
4621 } else if (patch_info->type == MONO_PATCH_INFO_ICALL_ADDR) {
4622 if (acfg->aot_opts.direct_icalls)
4630 #ifdef MONO_ARCH_AOT_SUPPORTED
4632 get_pinvoke_import (MonoAotCompile *acfg, MonoMethod *method)
4634 MonoImage *image = method->klass->image;
4635 MonoMethodPInvoke *piinfo = (MonoMethodPInvoke *) method;
4636 MonoTableInfo *tables = image->tables;
4637 MonoTableInfo *im = &tables [MONO_TABLE_IMPLMAP];
4638 MonoTableInfo *mr = &tables [MONO_TABLE_MODULEREF];
4639 guint32 im_cols [MONO_IMPLMAP_SIZE];
4642 import = g_hash_table_lookup (acfg->method_to_pinvoke_import, method);
4646 if (!piinfo->implmap_idx || piinfo->implmap_idx > im->rows)
4649 mono_metadata_decode_row (im, piinfo->implmap_idx - 1, im_cols, MONO_IMPLMAP_SIZE);
4651 if (!im_cols [MONO_IMPLMAP_SCOPE] || im_cols [MONO_IMPLMAP_SCOPE] > mr->rows)
4654 import = g_strdup_printf ("%s", mono_metadata_string_heap (image, im_cols [MONO_IMPLMAP_NAME]));
4656 g_hash_table_insert (acfg->method_to_pinvoke_import, method, import);
4663 compare_lne (MonoDebugLineNumberEntry *a, MonoDebugLineNumberEntry *b)
4665 if (a->native_offset == b->native_offset)
4666 return a->il_offset - b->il_offset;
4668 return a->native_offset - b->native_offset;
4672 * compute_line_numbers:
4674 * Returns a sparse array of size CODE_SIZE containing MonoDebugSourceLocation* entries for the native offsets which have a corresponding line number
4677 static MonoDebugSourceLocation**
4678 compute_line_numbers (MonoMethod *method, int code_size, MonoDebugMethodJitInfo *debug_info)
4680 MonoDebugMethodInfo *minfo;
4681 MonoDebugLineNumberEntry *ln_array;
4682 MonoDebugSourceLocation *loc;
4683 int i, prev_line, prev_il_offset;
4684 int *native_to_il_offset = NULL;
4685 MonoDebugSourceLocation **res;
4688 minfo = mono_debug_lookup_method (method);
4691 // FIXME: This seems to happen when two methods have the same cfg->method_to_register
4692 if (debug_info->code_size != code_size)
4695 g_assert (code_size);
4697 /* Compute the native->IL offset mapping */
4699 ln_array = g_new0 (MonoDebugLineNumberEntry, debug_info->num_line_numbers);
4700 memcpy (ln_array, debug_info->line_numbers, debug_info->num_line_numbers * sizeof (MonoDebugLineNumberEntry));
4702 qsort (ln_array, debug_info->num_line_numbers, sizeof (MonoDebugLineNumberEntry), (gpointer)compare_lne);
4704 native_to_il_offset = g_new0 (int, code_size + 1);
4706 for (i = 0; i < debug_info->num_line_numbers; ++i) {
4708 MonoDebugLineNumberEntry *lne = &ln_array [i];
4711 for (j = 0; j < lne->native_offset; ++j)
4712 native_to_il_offset [j] = -1;
4715 if (i < debug_info->num_line_numbers - 1) {
4716 MonoDebugLineNumberEntry *lne_next = &ln_array [i + 1];
4718 for (j = lne->native_offset; j < lne_next->native_offset; ++j)
4719 native_to_il_offset [j] = lne->il_offset;
4721 for (j = lne->native_offset; j < code_size; ++j)
4722 native_to_il_offset [j] = lne->il_offset;
4727 /* Compute the native->line number mapping */
4728 res = g_new0 (MonoDebugSourceLocation*, code_size);
4729 prev_il_offset = -1;
4732 for (i = 0; i < code_size; ++i) {
4733 int il_offset = native_to_il_offset [i];
4735 if (il_offset == -1 || il_offset == prev_il_offset)
4737 prev_il_offset = il_offset;
4738 loc = mono_debug_symfile_lookup_location (minfo, il_offset);
4739 if (!(loc && loc->source_file))
4741 if (loc->row == prev_line) {
4742 mono_debug_symfile_free_location (loc);
4745 prev_line = loc->row;
4746 //printf ("D: %s:%d il=%x native=%x\n", loc->source_file, loc->row, il_offset, i);
4748 /* This will cover the prolog too */
4758 get_file_index (MonoAotCompile *acfg, const char *source_file)
4762 // FIXME: Free these
4763 if (!acfg->dwarf_ln_filenames)
4764 acfg->dwarf_ln_filenames = g_hash_table_new (g_str_hash, g_str_equal);
4765 findex = GPOINTER_TO_INT (g_hash_table_lookup (acfg->dwarf_ln_filenames, source_file));
4767 findex = g_hash_table_size (acfg->dwarf_ln_filenames) + 1;
4768 g_hash_table_insert (acfg->dwarf_ln_filenames, g_strdup (source_file), GINT_TO_POINTER (findex));
4769 emit_unset_mode (acfg);
4770 fprintf (acfg->fp, ".file %d \"%s\"\n", findex, mono_dwarf_escape_path (source_file));
4782 * emit_and_reloc_code:
4784 * Emit the native code in CODE, handling relocations along the way. If GOT_ONLY
4785 * is true, calls are made through the GOT too. This is used for emitting trampolines
4786 * in full-aot mode, since calls made from trampolines couldn't go through the PLT,
4787 * since trampolines are needed to make PTL work.
4790 emit_and_reloc_code (MonoAotCompile *acfg, MonoMethod *method, guint8 *code, guint32 code_len, MonoJumpInfo *relocs, gboolean got_only, MonoDebugMethodJitInfo *debug_info)
4792 int i, pindex, start_index;
4794 MonoJumpInfo *patch_info;
4795 MonoDebugSourceLocation **locs = NULL;
4797 #ifdef MONO_ARCH_AOT_SUPPORTED
4798 gboolean direct_call, external_call;
4800 const char *direct_call_target = 0;
4801 const char *direct_pinvoke;
4804 if (acfg->gas_line_numbers && method && debug_info) {
4805 locs = compute_line_numbers (method, code_len, debug_info);
4807 int findex = get_file_index (acfg, "<unknown>");
4808 emit_unset_mode (acfg);
4809 fprintf (acfg->fp, ".loc %d %d 0\n", findex, 1);
4813 /* Collect and sort relocations */
4814 patches = g_ptr_array_new ();
4815 for (patch_info = relocs; patch_info; patch_info = patch_info->next)
4816 g_ptr_array_add (patches, patch_info);
4817 g_ptr_array_sort (patches, compare_patches);
4820 for (i = 0; i < code_len; i += INST_LEN) {
4822 for (pindex = start_index; pindex < patches->len; ++pindex) {
4823 patch_info = g_ptr_array_index (patches, pindex);
4824 if (patch_info->ip.i >= i)
4828 if (locs && locs [i]) {
4829 MonoDebugSourceLocation *loc = locs [i];
4832 findex = get_file_index (acfg, loc->source_file);
4833 emit_unset_mode (acfg);
4834 fprintf (acfg->fp, ".loc %d %d 0\n", findex, loc->row);
4835 mono_debug_symfile_free_location (loc);
4839 #ifdef MONO_ARCH_AOT_SUPPORTED
4840 if (patch_info && (patch_info->ip.i == i) && (pindex < patches->len)) {
4841 start_index = pindex;
4843 switch (patch_info->type) {
4844 case MONO_PATCH_INFO_NONE:
4846 case MONO_PATCH_INFO_GOT_OFFSET: {
4849 arch_emit_got_offset (acfg, code + i, &code_size);
4850 i += code_size - INST_LEN;
4852 patch_info->type = MONO_PATCH_INFO_NONE;
4855 case MONO_PATCH_INFO_OBJC_SELECTOR_REF: {
4856 int code_size, index;
4857 char *selector = (void*)patch_info->data.target;
4859 if (!acfg->objc_selector_to_index)
4860 acfg->objc_selector_to_index = g_hash_table_new (g_str_hash, g_str_equal);
4861 if (!acfg->objc_selectors)
4862 acfg->objc_selectors = g_ptr_array_new ();
4863 index = GPOINTER_TO_UINT (g_hash_table_lookup (acfg->objc_selector_to_index, selector));
4867 index = acfg->objc_selector_index;
4868 g_ptr_array_add (acfg->objc_selectors, (void*)patch_info->data.target);
4869 g_hash_table_insert (acfg->objc_selector_to_index, selector, GUINT_TO_POINTER (index + 1));
4870 acfg->objc_selector_index ++;
4873 arch_emit_objc_selector_ref (acfg, code + i, index, &code_size);
4874 i += code_size - INST_LEN;
4876 patch_info->type = MONO_PATCH_INFO_NONE;
4881 * If this patch is a call, try emitting a direct call instead of
4882 * through a PLT entry. This is possible if the called method is in
4883 * the same assembly and requires no initialization.
4885 direct_call = FALSE;
4886 external_call = FALSE;
4887 if ((patch_info->type == MONO_PATCH_INFO_METHOD) && (patch_info->data.method->klass->image == acfg->image)) {
4888 if (!got_only && is_direct_callable (acfg, method, patch_info)) {
4889 MonoCompile *callee_cfg = g_hash_table_lookup (acfg->method_to_cfg, patch_info->data.method);
4890 //printf ("DIRECT: %s %s\n", method ? mono_method_full_name (method, TRUE) : "", mono_method_full_name (callee_cfg->method, TRUE));
4892 direct_call_target = callee_cfg->asm_symbol;
4893 patch_info->type = MONO_PATCH_INFO_NONE;
4894 acfg->stats.direct_calls ++;
4897 acfg->stats.all_calls ++;
4898 } else if (patch_info->type == MONO_PATCH_INFO_ICALL_ADDR) {
4899 if (!got_only && is_direct_callable (acfg, method, patch_info)) {
4900 if (!(patch_info->data.method->flags & METHOD_ATTRIBUTE_PINVOKE_IMPL))
4901 direct_pinvoke = mono_lookup_icall_symbol (patch_info->data.method);
4903 direct_pinvoke = get_pinvoke_import (acfg, patch_info->data.method);
4904 if (direct_pinvoke) {
4906 g_assert (strlen (direct_pinvoke) < 1000);
4907 direct_call_target = g_strdup_printf ("%s%s", acfg->user_symbol_prefix, direct_pinvoke);
4910 } else if (patch_info->type == MONO_PATCH_INFO_JIT_ICALL_ADDR) {
4911 const char *sym = mono_lookup_jit_icall_symbol (patch_info->data.name);
4912 if (!got_only && sym && acfg->aot_opts.direct_icalls) {
4913 /* Call to a C function implementing a jit icall */
4915 external_call = TRUE;
4916 g_assert (strlen (sym) < 1000);
4917 direct_call_target = g_strdup_printf ("%s%s", acfg->user_symbol_prefix, sym);
4919 } else if (patch_info->type == MONO_PATCH_INFO_INTERNAL_METHOD) {
4920 MonoJitICallInfo *info = mono_find_jit_icall_by_name (patch_info->data.name);
4921 const char *sym = mono_lookup_jit_icall_symbol (patch_info->data.name);
4922 if (!got_only && sym && acfg->aot_opts.direct_icalls && info->func == info->wrapper) {
4923 /* Call to a jit icall without a wrapper */
4925 external_call = TRUE;
4926 g_assert (strlen (sym) < 1000);
4927 direct_call_target = g_strdup_printf ("%s%s", acfg->user_symbol_prefix, sym);
4932 patch_info->type = MONO_PATCH_INFO_NONE;
4933 acfg->stats.direct_calls ++;
4936 if (!got_only && !direct_call) {
4937 MonoPltEntry *plt_entry = get_plt_entry (acfg, patch_info);
4939 /* This patch has a PLT entry, so we must emit a call to the PLT entry */
4941 direct_call_target = plt_entry->symbol;
4943 /* Nullify the patch */
4944 patch_info->type = MONO_PATCH_INFO_NONE;
4945 plt_entry->jit_used = TRUE;
4952 arch_emit_direct_call (acfg, direct_call_target, external_call, FALSE, patch_info, &call_size);
4953 i += call_size - INST_LEN;
4957 got_slot = get_got_offset (acfg, FALSE, patch_info);
4959 arch_emit_got_access (acfg, acfg->got_symbol, code + i, got_slot, &code_size);
4960 i += code_size - INST_LEN;
4966 #endif /* MONO_ARCH_AOT_SUPPORTED */
4969 /* Find next patch */
4971 for (pindex = start_index; pindex < patches->len; ++pindex) {
4972 patch_info = g_ptr_array_index (patches, pindex);
4973 if (patch_info->ip.i >= i)
4977 /* Try to emit multiple bytes at once */
4978 if (pindex < patches->len && patch_info->ip.i > i) {
4981 for (limit = i + INST_LEN; limit < patch_info->ip.i; limit += INST_LEN) {
4982 if (locs && locs [limit])
4986 emit_code_bytes (acfg, code + i, limit - i);
4987 i = limit - INST_LEN;
4989 emit_code_bytes (acfg, code + i, INST_LEN);
5000 * Return a modified version of S which only includes characters permissible in symbols.
5003 sanitize_symbol (MonoAotCompile *acfg, char *s)
5005 gboolean process = FALSE;
5014 for (i = 0; i < len; ++i)
5015 if (!(s [i] <= 0x7f && (isalnum (s [i]) || s [i] == '_')))
5020 gs = g_string_sized_new (len);
5021 for (i = 0; i < len; ++i) {
5023 if (c <= 0x7f && (isalnum (c) || c == '_')) {
5024 g_string_append_c (gs, c);
5025 } else if (c > 0x7f) {
5026 /* multi-byte utf8 */
5027 g_string_append_printf (gs, "_0x%x", c);
5030 while (c >> 6 == 0x2) {
5031 g_string_append_printf (gs, "%x", c);
5035 g_string_append_printf (gs, "_");
5038 g_string_append_c (gs, '_');
5042 res = mono_mempool_strdup (acfg->mempool, gs->str);
5043 g_string_free (gs, TRUE);
5048 get_debug_sym (MonoMethod *method, const char *prefix, GHashTable *cache)
5050 char *name1, *name2, *cached;
5051 int i, j, len, count;
5052 MonoMethod *cached_method;
5054 name1 = mono_method_full_name (method, TRUE);
5057 // This is so that we don't accidentally create a local symbol (which starts with 'L')
5058 if ((!prefix || !*prefix) && name1 [0] == 'L')
5062 len = strlen (name1);
5063 name2 = malloc (strlen (prefix) + len + 16);
5064 memcpy (name2, prefix, strlen (prefix));
5065 j = strlen (prefix);
5066 for (i = 0; i < len; ++i) {
5067 if (i == 0 && name1 [0] >= '0' && name1 [0] <= '9') {
5069 } else if (isalnum (name1 [i])) {
5070 name2 [j ++] = name1 [i];
5071 } else if (name1 [i] == ' ' && name1 [i + 1] == '(' && name1 [i + 2] == ')') {
5073 } else if (name1 [i] == ',' && name1 [i + 1] == ' ') {
5076 } else if (name1 [i] == '(' || name1 [i] == ')' || name1 [i] == '>') {
5086 cached_method = g_hash_table_lookup (cache, name2);
5087 if (!(cached_method && cached_method != method))
5089 sprintf (name2 + j, "_%d", count);
5093 cached = g_strdup (name2);
5094 g_hash_table_insert (cache, cached, method);
5100 emit_method_code (MonoAotCompile *acfg, MonoCompile *cfg)
5105 char *debug_sym = NULL;
5106 char *symbol = NULL;
5107 int func_alignment = AOT_FUNC_ALIGNMENT;
5110 method = cfg->orig_method;
5111 code = cfg->native_code;
5113 method_index = get_method_index (acfg, method);
5114 symbol = g_strdup_printf ("%sme_%x", acfg->temp_prefix, method_index);
5116 /* Make the labels local */
5117 emit_section_change (acfg, ".text", 0);
5118 emit_alignment_code (acfg, func_alignment);
5120 if (acfg->global_symbols && acfg->need_no_dead_strip)
5121 fprintf (acfg->fp, " .no_dead_strip %s\n", cfg->asm_symbol);
5123 emit_label (acfg, cfg->asm_symbol);
5125 if (acfg->aot_opts.write_symbols && !acfg->global_symbols && !acfg->llvm) {
5127 * Write a C style symbol for every method, this has two uses:
5128 * - it works on platforms where the dwarf debugging info is not
5130 * - it allows the setting of breakpoints of aot-ed methods.
5132 debug_sym = get_debug_sym (method, "", acfg->method_label_hash);
5133 cfg->asm_debug_symbol = g_strdup (debug_sym);
5135 if (acfg->need_no_dead_strip)
5136 fprintf (acfg->fp, " .no_dead_strip %s\n", debug_sym);
5137 emit_local_symbol (acfg, debug_sym, symbol, TRUE);
5138 emit_label (acfg, debug_sym);
5141 export_name = g_hash_table_lookup (acfg->export_names, method);
5143 /* Emit a global symbol for the method */
5144 emit_global_inner (acfg, export_name, TRUE);
5145 emit_label (acfg, export_name);
5148 if (cfg->verbose_level > 0)
5149 g_print ("Method %s emitted as %s\n", mono_method_full_name (method, TRUE), cfg->asm_symbol);
5151 acfg->stats.code_size += cfg->code_len;
5153 acfg->cfgs [method_index]->got_offset = acfg->got_offset;
5155 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 ()));
5159 if (acfg->aot_opts.write_symbols) {
5161 emit_symbol_size (acfg, debug_sym, ".");
5163 emit_symbol_size (acfg, cfg->asm_symbol, ".");
5167 emit_label (acfg, symbol);
5174 * Encode PATCH_INFO into its disk representation.
5177 encode_patch (MonoAotCompile *acfg, MonoJumpInfo *patch_info, guint8 *buf, guint8 **endbuf)
5181 switch (patch_info->type) {
5182 case MONO_PATCH_INFO_NONE:
5184 case MONO_PATCH_INFO_IMAGE:
5185 encode_value (get_image_index (acfg, patch_info->data.image), p, &p);
5187 case MONO_PATCH_INFO_MSCORLIB_GOT_ADDR:
5188 case MONO_PATCH_INFO_JIT_TLS_ID:
5189 case MONO_PATCH_INFO_GC_CARD_TABLE_ADDR:
5190 case MONO_PATCH_INFO_GC_NURSERY_START:
5192 case MONO_PATCH_INFO_CASTCLASS_CACHE:
5193 encode_value (patch_info->data.index, p, &p);
5195 case MONO_PATCH_INFO_METHOD_REL:
5196 encode_value ((gint)patch_info->data.offset, p, &p);
5198 case MONO_PATCH_INFO_SWITCH: {
5199 gpointer *table = (gpointer *)patch_info->data.table->table;
5202 encode_value (patch_info->data.table->table_size, p, &p);
5203 for (k = 0; k < patch_info->data.table->table_size; k++)
5204 encode_value ((int)(gssize)table [k], p, &p);
5207 case MONO_PATCH_INFO_METHODCONST:
5208 case MONO_PATCH_INFO_METHOD:
5209 case MONO_PATCH_INFO_METHOD_JUMP:
5210 case MONO_PATCH_INFO_ICALL_ADDR:
5211 case MONO_PATCH_INFO_METHOD_RGCTX:
5212 case MONO_PATCH_INFO_METHOD_CODE_SLOT:
5213 encode_method_ref (acfg, patch_info->data.method, p, &p);
5215 case MONO_PATCH_INFO_INTERNAL_METHOD:
5216 case MONO_PATCH_INFO_JIT_ICALL_ADDR: {
5217 guint32 len = strlen (patch_info->data.name);
5219 encode_value (len, p, &p);
5221 memcpy (p, patch_info->data.name, len);
5226 case MONO_PATCH_INFO_LDSTR: {
5227 guint32 image_index = get_image_index (acfg, patch_info->data.token->image);
5228 guint32 token = patch_info->data.token->token;
5229 g_assert (mono_metadata_token_code (token) == MONO_TOKEN_STRING);
5230 encode_value (image_index, p, &p);
5231 encode_value (patch_info->data.token->token - MONO_TOKEN_STRING, p, &p);
5234 case MONO_PATCH_INFO_RVA:
5235 case MONO_PATCH_INFO_DECLSEC:
5236 case MONO_PATCH_INFO_LDTOKEN:
5237 case MONO_PATCH_INFO_TYPE_FROM_HANDLE:
5238 encode_value (get_image_index (acfg, patch_info->data.token->image), p, &p);
5239 encode_value (patch_info->data.token->token, p, &p);
5240 encode_value (patch_info->data.token->has_context, p, &p);
5241 if (patch_info->data.token->has_context)
5242 encode_generic_context (acfg, &patch_info->data.token->context, p, &p);
5244 case MONO_PATCH_INFO_EXC_NAME: {
5245 MonoClass *ex_class;
5248 mono_class_from_name (mono_defaults.exception_class->image,
5249 "System", patch_info->data.target);
5250 g_assert (ex_class);
5251 encode_klass_ref (acfg, ex_class, p, &p);
5254 case MONO_PATCH_INFO_R4:
5255 encode_value (*((guint32 *)patch_info->data.target), p, &p);
5257 case MONO_PATCH_INFO_R8:
5258 encode_value (((guint32 *)patch_info->data.target) [MINI_LS_WORD_IDX], p, &p);
5259 encode_value (((guint32 *)patch_info->data.target) [MINI_MS_WORD_IDX], p, &p);
5261 case MONO_PATCH_INFO_VTABLE:
5262 case MONO_PATCH_INFO_CLASS:
5263 case MONO_PATCH_INFO_IID:
5264 case MONO_PATCH_INFO_ADJUSTED_IID:
5265 encode_klass_ref (acfg, patch_info->data.klass, p, &p);
5267 case MONO_PATCH_INFO_DELEGATE_TRAMPOLINE:
5268 encode_klass_ref (acfg, patch_info->data.del_tramp->klass, p, &p);
5269 if (patch_info->data.del_tramp->method) {
5270 encode_value (1, p, &p);
5271 encode_method_ref (acfg, patch_info->data.del_tramp->method, p, &p);
5273 encode_value (0, p, &p);
5275 encode_value (patch_info->data.del_tramp->virtual, p, &p);
5277 case MONO_PATCH_INFO_FIELD:
5278 case MONO_PATCH_INFO_SFLDA:
5279 encode_field_info (acfg, patch_info->data.field, p, &p);
5281 case MONO_PATCH_INFO_INTERRUPTION_REQUEST_FLAG:
5283 case MONO_PATCH_INFO_RGCTX_FETCH:
5284 case MONO_PATCH_INFO_RGCTX_SLOT_INDEX: {
5285 MonoJumpInfoRgctxEntry *entry = patch_info->data.rgctx_entry;
5290 * entry->method has a lenghtly encoding and multiple rgctx_fetch entries
5291 * reference the same method, so encode the method only once.
5293 offset = GPOINTER_TO_UINT (g_hash_table_lookup (acfg->method_blob_hash, entry->method));
5295 buf2 = g_malloc (1024);
5298 encode_method_ref (acfg, entry->method, p2, &p2);
5299 g_assert (p2 - buf2 < 1024);
5301 offset = add_to_blob (acfg, buf2, p2 - buf2);
5304 g_hash_table_insert (acfg->method_blob_hash, entry->method, GUINT_TO_POINTER (offset + 1));
5309 encode_value (offset, p, &p);
5310 g_assert ((int)entry->info_type < 256);
5311 g_assert (entry->data->type < 256);
5312 encode_value ((entry->in_mrgctx ? 1 : 0) | (entry->info_type << 1) | (entry->data->type << 9), p, &p);
5313 encode_patch (acfg, entry->data, p, &p);
5316 case MONO_PATCH_INFO_SEQ_POINT_INFO:
5317 case MONO_PATCH_INFO_AOT_MODULE:
5319 case MONO_PATCH_INFO_LLVM_IMT_TRAMPOLINE:
5320 encode_method_ref (acfg, patch_info->data.imt_tramp->method, p, &p);
5321 encode_value (patch_info->data.imt_tramp->vt_offset, p, &p);
5323 case MONO_PATCH_INFO_SIGNATURE:
5324 encode_signature (acfg, (MonoMethodSignature*)patch_info->data.target, p, &p);
5326 case MONO_PATCH_INFO_TLS_OFFSET:
5327 encode_value (GPOINTER_TO_INT (patch_info->data.target), p, &p);
5329 case MONO_PATCH_INFO_GSHAREDVT_CALL:
5330 encode_signature (acfg, (MonoMethodSignature*)patch_info->data.gsharedvt->sig, p, &p);
5331 encode_method_ref (acfg, patch_info->data.gsharedvt->method, p, &p);
5333 case MONO_PATCH_INFO_GSHAREDVT_METHOD: {
5334 MonoGSharedVtMethodInfo *info = patch_info->data.gsharedvt_method;
5337 encode_method_ref (acfg, info->method, p, &p);
5338 encode_value (info->num_entries, p, &p);
5339 for (i = 0; i < info->num_entries; ++i) {
5340 MonoRuntimeGenericContextInfoTemplate *template = &info->entries [i];
5342 encode_value (template->info_type, p, &p);
5343 switch (mini_rgctx_info_type_to_patch_info_type (template->info_type)) {
5344 case MONO_PATCH_INFO_CLASS:
5345 encode_klass_ref (acfg, mono_class_from_mono_type (template->data), p, &p);
5347 case MONO_PATCH_INFO_FIELD:
5348 encode_field_info (acfg, template->data, p, &p);
5351 g_assert_not_reached ();
5357 case MONO_PATCH_INFO_LDSTR_LIT: {
5358 const char *s = patch_info->data.target;
5359 int len = strlen (s);
5361 encode_value (len, p, &p);
5362 memcpy (p, s, len + 1);
5366 case MONO_PATCH_INFO_VIRT_METHOD:
5367 encode_klass_ref (acfg, patch_info->data.virt_method->klass, p, &p);
5368 encode_method_ref (acfg, patch_info->data.virt_method->method, p, &p);
5370 case MONO_PATCH_INFO_GC_SAFE_POINT_FLAG:
5373 g_warning ("unable to handle jump info %d", patch_info->type);
5374 g_assert_not_reached ();
5381 encode_patch_list (MonoAotCompile *acfg, GPtrArray *patches, int n_patches, gboolean llvm, int first_got_offset, guint8 *buf, guint8 **endbuf)
5384 guint32 pindex, offset;
5385 MonoJumpInfo *patch_info;
5387 encode_value (n_patches, p, &p);
5389 for (pindex = 0; pindex < patches->len; ++pindex) {
5390 patch_info = g_ptr_array_index (patches, pindex);
5392 if (patch_info->type == MONO_PATCH_INFO_NONE || patch_info->type == MONO_PATCH_INFO_BB)
5396 offset = get_got_offset (acfg, llvm, patch_info);
5397 encode_value (offset, p, &p);
5404 emit_method_info (MonoAotCompile *acfg, MonoCompile *cfg)
5407 int pindex, buf_size, n_patches;
5409 MonoJumpInfo *patch_info;
5410 guint32 method_index;
5412 guint32 first_got_offset;
5414 method = cfg->orig_method;
5416 method_index = get_method_index (acfg, method);
5418 /* Sort relocations */
5419 patches = g_ptr_array_new ();
5420 for (patch_info = cfg->patch_info; patch_info; patch_info = patch_info->next)
5421 g_ptr_array_add (patches, patch_info);
5422 g_ptr_array_sort (patches, compare_patches);
5424 first_got_offset = acfg->cfgs [method_index]->got_offset;
5426 /**********************/
5427 /* Encode method info */
5428 /**********************/
5430 buf_size = (patches->len < 1000) ? 40960 : 40960 + (patches->len * 64);
5431 p = buf = g_malloc (buf_size);
5433 if (mono_class_get_cctor (method->klass))
5434 encode_klass_ref (acfg, method->klass, p, &p);
5436 /* Not needed when loading the method */
5437 encode_value (0, p, &p);
5439 g_assert (!(cfg->opt & MONO_OPT_SHARED));
5442 for (pindex = 0; pindex < patches->len; ++pindex) {
5443 patch_info = g_ptr_array_index (patches, pindex);
5445 if ((patch_info->type == MONO_PATCH_INFO_GOT_OFFSET) ||
5446 (patch_info->type == MONO_PATCH_INFO_NONE)) {
5447 patch_info->type = MONO_PATCH_INFO_NONE;
5452 if ((patch_info->type == MONO_PATCH_INFO_IMAGE) && (patch_info->data.image == acfg->image)) {
5453 /* Stored in a GOT slot initialized at module load time */
5454 patch_info->type = MONO_PATCH_INFO_NONE;
5458 if (patch_info->type == MONO_PATCH_INFO_GC_CARD_TABLE_ADDR ||
5459 patch_info->type == MONO_PATCH_INFO_GC_NURSERY_START ||
5460 patch_info->type == MONO_PATCH_INFO_AOT_MODULE) {
5461 /* Stored in a GOT slot initialized at module load time */
5462 patch_info->type = MONO_PATCH_INFO_NONE;
5466 if (is_plt_patch (patch_info) && !(cfg->compile_llvm && acfg->aot_opts.llvm_only)) {
5467 /* Calls are made through the PLT */
5468 patch_info->type = MONO_PATCH_INFO_NONE;
5476 g_assert (cfg->has_got_slots);
5478 encode_patch_list (acfg, patches, n_patches, cfg->compile_llvm, first_got_offset, p, &p);
5480 acfg->stats.info_size += p - buf;
5482 g_assert (p - buf < buf_size);
5484 cfg->method_info_offset = add_to_blob (acfg, buf, p - buf);
5489 get_unwind_info_offset (MonoAotCompile *acfg, guint8 *encoded, guint32 encoded_len)
5491 guint32 cache_index;
5494 /* Reuse the unwind module to canonize and store unwind info entries */
5495 cache_index = mono_cache_unwind_info (encoded, encoded_len);
5497 /* Use +/- 1 to distinguish 0s from missing entries */
5498 offset = GPOINTER_TO_UINT (g_hash_table_lookup (acfg->unwind_info_offsets, GUINT_TO_POINTER (cache_index + 1)));
5506 * It would be easier to use assembler symbols, but the caller needs an
5509 offset = acfg->unwind_info_offset;
5510 g_hash_table_insert (acfg->unwind_info_offsets, GUINT_TO_POINTER (cache_index + 1), GUINT_TO_POINTER (offset + 1));
5511 g_ptr_array_add (acfg->unwind_ops, GUINT_TO_POINTER (cache_index));
5514 encode_value (encoded_len, p, &p);
5516 acfg->unwind_info_offset += encoded_len + (p - buf);
5522 emit_exception_debug_info (MonoAotCompile *acfg, MonoCompile *cfg, gboolean store_seq_points)
5525 guint32 debug_info_size, seq_points_size;
5527 MonoMethodHeader *header;
5528 guint8 *p, *buf, *debug_info;
5529 MonoJitInfo *jinfo = cfg->jit_info;
5531 gboolean use_unwind_ops = FALSE;
5532 MonoSeqPointInfo *seq_points;
5534 code = cfg->native_code;
5535 header = cfg->header;
5537 if (!acfg->aot_opts.nodebug) {
5538 mono_debug_serialize_debug_info (cfg, &debug_info, &debug_info_size);
5541 debug_info_size = 0;
5544 seq_points = cfg->seq_point_info;
5545 seq_points_size = (store_seq_points)? mono_seq_point_info_get_write_size (seq_points) : 0;
5547 buf_size = header->num_clauses * 256 + debug_info_size + 2048 + seq_points_size + cfg->gc_map_size;
5549 p = buf = g_malloc (buf_size);
5551 use_unwind_ops = cfg->unwind_ops != NULL;
5553 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);
5555 encode_value (flags, p, &p);
5557 if (use_unwind_ops) {
5558 guint32 encoded_len;
5560 guint32 unwind_desc;
5562 encoded = mono_unwind_ops_encode (cfg->unwind_ops, &encoded_len);
5564 unwind_desc = get_unwind_info_offset (acfg, encoded, encoded_len);
5565 encode_value (unwind_desc, p, &p);
5567 encode_value (jinfo->unwind_info, p, &p);
5570 /*Encode the number of holes before the number of clauses to make decoding easier*/
5571 if (jinfo->has_try_block_holes) {
5572 MonoTryBlockHoleTableJitInfo *table = mono_jit_info_get_try_block_hole_table_info (jinfo);
5573 encode_value (table->num_holes, p, &p);
5576 if (jinfo->has_arch_eh_info) {
5578 * In AOT mode, the code length is calculated from the address of the previous method,
5579 * which could include alignment padding, so calculating the start of the epilog as
5580 * code_len - epilog_size is correct any more. Save the real code len as a workaround.
5582 encode_value (jinfo->code_size, p, &p);
5585 /* Exception table */
5586 if (cfg->compile_llvm) {
5588 * When using LLVM, we can't emit some data, like pc offsets, this reg/offset etc.,
5589 * since the information is only available to llc. Instead, we let llc save the data
5590 * into the LSDA, and read it from there at runtime.
5592 /* The assembly might be CIL stripped so emit the data ourselves */
5593 if (header->num_clauses)
5594 encode_value (header->num_clauses, p, &p);
5596 for (k = 0; k < header->num_clauses; ++k) {
5597 MonoExceptionClause *clause;
5599 clause = &header->clauses [k];
5601 encode_value (clause->flags, p, &p);
5602 if (clause->data.catch_class) {
5603 encode_value (1, p, &p);
5604 encode_klass_ref (acfg, clause->data.catch_class, p, &p);
5606 encode_value (0, p, &p);
5609 /* Emit a list of nesting clauses */
5610 for (i = 0; i < header->num_clauses; ++i) {
5612 MonoExceptionClause *clause1 = &header->clauses [cindex1];
5614 MonoExceptionClause *clause2 = &header->clauses [cindex2];
5616 if (cindex1 != cindex2 && clause1->try_offset >= clause2->try_offset && clause1->handler_offset <= clause2->handler_offset)
5617 encode_value (i, p, &p);
5619 encode_value (-1, p, &p);
5622 if (jinfo->num_clauses)
5623 encode_value (jinfo->num_clauses, p, &p);
5625 for (k = 0; k < jinfo->num_clauses; ++k) {
5626 MonoJitExceptionInfo *ei = &jinfo->clauses [k];
5628 encode_value (ei->flags, p, &p);
5629 #ifdef MONO_CONTEXT_SET_LLVM_EXC_REG
5630 /* Not used for catch clauses */
5631 if (ei->flags != MONO_EXCEPTION_CLAUSE_NONE)
5632 encode_value (ei->exvar_offset, p, &p);
5634 encode_value (ei->exvar_offset, p, &p);
5637 if (ei->flags == MONO_EXCEPTION_CLAUSE_FILTER || ei->flags == MONO_EXCEPTION_CLAUSE_FINALLY)
5638 encode_value ((gint)((guint8*)ei->data.filter - code), p, &p);
5640 if (ei->data.catch_class) {
5644 buf2 = g_malloc (4096);
5646 encode_klass_ref (acfg, ei->data.catch_class, p2, &p2);
5648 g_assert (len < 4096);
5649 encode_value (len, p, &p);
5650 memcpy (p, buf2, len);
5654 encode_value (0, p, &p);
5658 encode_value ((gint)((guint8*)ei->try_start - code), p, &p);
5659 encode_value ((gint)((guint8*)ei->try_end - code), p, &p);
5660 encode_value ((gint)((guint8*)ei->handler_start - code), p, &p);
5664 if (jinfo->has_try_block_holes) {
5665 MonoTryBlockHoleTableJitInfo *table = mono_jit_info_get_try_block_hole_table_info (jinfo);
5666 for (i = 0; i < table->num_holes; ++i) {
5667 MonoTryBlockHoleJitInfo *hole = &table->holes [i];
5668 encode_value (hole->clause, p, &p);
5669 encode_value (hole->length, p, &p);
5670 encode_value (hole->offset, p, &p);
5674 if (jinfo->has_arch_eh_info) {
5675 MonoArchEHJitInfo *eh_info;
5677 eh_info = mono_jit_info_get_arch_eh_info (jinfo);
5678 encode_value (eh_info->stack_size, p, &p);
5679 encode_value (eh_info->epilog_size, p, &p);
5682 if (jinfo->has_generic_jit_info) {
5683 MonoGenericJitInfo *gi = mono_jit_info_get_generic_jit_info (jinfo);
5684 MonoGenericSharingContext* gsctx = gi->generic_sharing_context;
5688 encode_value (gi->nlocs, p, &p);
5690 for (i = 0; i < gi->nlocs; ++i) {
5691 MonoDwarfLocListEntry *entry = &gi->locations [i];
5693 encode_value (entry->is_reg ? 1 : 0, p, &p);
5694 encode_value (entry->reg, p, &p);
5696 encode_value (entry->offset, p, &p);
5698 g_assert (entry->from == 0);
5700 encode_value (entry->from, p, &p);
5701 encode_value (entry->to, p, &p);
5704 if (!cfg->compile_llvm) {
5705 encode_value (gi->has_this ? 1 : 0, p, &p);
5706 encode_value (gi->this_reg, p, &p);
5707 encode_value (gi->this_offset, p, &p);
5712 * Need to encode jinfo->method too, since it is not equal to 'method'
5713 * when using generic sharing.
5715 buf2 = g_malloc (4096);
5717 encode_method_ref (acfg, jinfo->d.method, p2, &p2);
5719 g_assert (len < 4096);
5720 encode_value (len, p, &p);
5721 memcpy (p, buf2, len);
5725 if (gsctx && gsctx->is_gsharedvt) {
5726 encode_value (1, p, &p);
5728 encode_value (0, p, &p);
5732 if (seq_points_size)
5733 p += mono_seq_point_info_write (seq_points, p);
5735 g_assert (debug_info_size < buf_size);
5737 encode_value (debug_info_size, p, &p);
5738 if (debug_info_size) {
5739 memcpy (p, debug_info, debug_info_size);
5740 p += debug_info_size;
5741 g_free (debug_info);
5746 encode_value (cfg->gc_map_size, p, &p);
5747 /* The GC map requires 4 bytes of alignment */
5748 while ((gsize)p % 4)
5750 memcpy (p, cfg->gc_map, cfg->gc_map_size);
5751 p += cfg->gc_map_size;
5754 acfg->stats.ex_info_size += p - buf;
5756 g_assert (p - buf < buf_size);
5759 /* The GC Map requires 4 byte alignment */
5760 cfg->ex_info_offset = add_to_blob_aligned (acfg, buf, p - buf, cfg->gc_map ? 4 : 1);
5765 emit_klass_info (MonoAotCompile *acfg, guint32 token)
5768 MonoClass *klass = mono_class_get_checked (acfg->image, token, &error);
5770 int i, buf_size, res;
5771 gboolean no_special_static, cant_encode;
5772 gpointer iter = NULL;
5775 mono_error_cleanup (&error);
5779 p = buf = g_malloc (buf_size);
5781 /* Mark as unusable */
5782 encode_value (-1, p, &p);
5784 res = add_to_blob (acfg, buf, p - buf);
5790 buf_size = 10240 + (klass->vtable_size * 16);
5791 p = buf = g_malloc (buf_size);
5795 mono_class_init (klass);
5797 mono_class_get_nested_types (klass, &iter);
5798 g_assert (klass->nested_classes_inited);
5800 mono_class_setup_vtable (klass);
5803 * Emit all the information which is required for creating vtables so
5804 * the runtime does not need to create the MonoMethod structures which
5805 * take up a lot of space.
5808 no_special_static = !mono_class_has_special_static_fields (klass);
5810 /* Check whenever we have enough info to encode the vtable */
5811 cant_encode = FALSE;
5812 for (i = 0; i < klass->vtable_size; ++i) {
5813 MonoMethod *cm = klass->vtable [i];
5815 if (cm && mono_method_signature (cm)->is_inflated && !g_hash_table_lookup (acfg->token_info_hash, cm))
5819 mono_class_has_finalizer (klass);
5821 if (klass->generic_container || cant_encode) {
5822 encode_value (-1, p, &p);
5824 encode_value (klass->vtable_size, p, &p);
5825 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);
5826 if (klass->has_cctor)
5827 encode_method_ref (acfg, mono_class_get_cctor (klass), p, &p);
5828 if (klass->has_finalize)
5829 encode_method_ref (acfg, mono_class_get_finalizer (klass), p, &p);
5831 encode_value (klass->instance_size, p, &p);
5832 encode_value (mono_class_data_size (klass), p, &p);
5833 encode_value (klass->packing_size, p, &p);
5834 encode_value (klass->min_align, p, &p);
5836 for (i = 0; i < klass->vtable_size; ++i) {
5837 MonoMethod *cm = klass->vtable [i];
5840 encode_method_ref (acfg, cm, p, &p);
5842 encode_value (0, p, &p);
5846 acfg->stats.class_info_size += p - buf;
5848 g_assert (p - buf < buf_size);
5849 res = add_to_blob (acfg, buf, p - buf);
5856 get_plt_entry_debug_sym (MonoAotCompile *acfg, MonoJumpInfo *ji, GHashTable *cache)
5858 char *debug_sym = NULL;
5861 if (acfg->llvm && llvm_acfg->aot_opts.static_link) {
5862 /* Need to add a prefix to create unique symbols */
5863 prefix = g_strdup_printf ("plt_%s_", acfg->assembly_name_sym);
5865 prefix = g_strdup ("plt_");
5869 case MONO_PATCH_INFO_METHOD:
5870 debug_sym = get_debug_sym (ji->data.method, prefix, cache);
5872 case MONO_PATCH_INFO_INTERNAL_METHOD:
5873 debug_sym = g_strdup_printf ("%s_jit_icall_%s", prefix, ji->data.name);
5875 case MONO_PATCH_INFO_RGCTX_FETCH:
5876 debug_sym = g_strdup_printf ("%s_rgctx_fetch_%d", prefix, acfg->label_generator ++);
5878 case MONO_PATCH_INFO_ICALL_ADDR: {
5879 char *s = get_debug_sym (ji->data.method, "", cache);
5881 debug_sym = g_strdup_printf ("%s_icall_native_%s", prefix, s);
5885 case MONO_PATCH_INFO_JIT_ICALL_ADDR:
5886 debug_sym = g_strdup_printf ("%s_jit_icall_native_%s", prefix, ji->data.name);
5894 return sanitize_symbol (acfg, debug_sym);
5898 * Calls made from AOTed code are routed through a table of jumps similar to the
5899 * ELF PLT (Program Linkage Table). Initially the PLT entries jump to code which transfers
5900 * control to the AOT runtime through a trampoline.
5903 emit_plt (MonoAotCompile *acfg)
5907 if (!acfg->has_jitted_code) {
5908 g_assert (acfg->plt_offset == 1);
5914 emit_section_change (acfg, ".text", 0);
5915 emit_alignment_code (acfg, NACL_SIZE(16, kNaClAlignment));
5916 emit_info_symbol (acfg, "plt");
5917 emit_label (acfg, acfg->plt_symbol);
5919 for (i = 0; i < acfg->plt_offset; ++i) {
5920 char *debug_sym = NULL;
5921 MonoPltEntry *plt_entry = NULL;
5925 * The first plt entry is unused.
5929 plt_entry = g_hash_table_lookup (acfg->plt_offset_to_entry, GUINT_TO_POINTER (i));
5931 debug_sym = plt_entry->debug_sym;
5933 if (acfg->thumb_mixed && !plt_entry->jit_used)
5934 /* Emit only a thumb version */
5937 /* Skip plt entries not actually called */
5938 if (!plt_entry->jit_used && !plt_entry->llvm_used)
5941 if (acfg->llvm && !acfg->thumb_mixed) {
5942 emit_label (acfg, plt_entry->llvm_symbol);
5944 emit_global_inner (acfg, plt_entry->llvm_symbol, TRUE);
5945 #if defined(TARGET_MACH)
5946 fprintf (acfg->fp, ".private_extern %s\n", plt_entry->llvm_symbol);
5952 if (acfg->need_no_dead_strip) {
5953 emit_unset_mode (acfg);
5954 fprintf (acfg->fp, " .no_dead_strip %s\n", debug_sym);
5956 emit_local_symbol (acfg, debug_sym, NULL, TRUE);
5957 emit_label (acfg, debug_sym);
5960 emit_label (acfg, plt_entry->symbol);
5962 arch_emit_plt_entry (acfg, acfg->got_symbol, (acfg->plt_got_offset_base + i) * sizeof (gpointer), acfg->plt_got_info_offsets [i]);
5965 emit_symbol_size (acfg, debug_sym, ".");
5968 if (acfg->thumb_mixed) {
5969 /* Make sure the ARM symbols don't alias the thumb ones */
5970 emit_zero_bytes (acfg, 16);
5973 * Emit a separate set of PLT entries using thumb2 which is called by LLVM generated
5976 for (i = 0; i < acfg->plt_offset; ++i) {
5977 char *debug_sym = NULL;
5978 MonoPltEntry *plt_entry = NULL;
5983 plt_entry = g_hash_table_lookup (acfg->plt_offset_to_entry, GUINT_TO_POINTER (i));
5985 /* Skip plt entries not actually called by LLVM code */
5986 if (!plt_entry->llvm_used)
5989 if (acfg->aot_opts.write_symbols) {
5990 if (plt_entry->debug_sym)
5991 debug_sym = g_strdup_printf ("%s_thumb", plt_entry->debug_sym);
5995 #if defined(TARGET_MACH)
5996 fprintf (acfg->fp, " .thumb_func %s\n", debug_sym);
5997 fprintf (acfg->fp, " .no_dead_strip %s\n", debug_sym);
5999 emit_local_symbol (acfg, debug_sym, NULL, TRUE);
6000 emit_label (acfg, debug_sym);
6002 fprintf (acfg->fp, "\n.thumb_func\n");
6004 emit_label (acfg, plt_entry->llvm_symbol);
6007 emit_global_inner (acfg, plt_entry->llvm_symbol, TRUE);
6009 arch_emit_llvm_plt_entry (acfg, acfg->got_symbol, (acfg->plt_got_offset_base + i) * sizeof (gpointer), acfg->plt_got_info_offsets [i]);
6012 emit_symbol_size (acfg, debug_sym, ".");
6018 emit_symbol_size (acfg, acfg->plt_symbol, ".");
6020 emit_info_symbol (acfg, "plt_end");
6024 * emit_trampoline_full:
6026 * If EMIT_TINFO is TRUE, emit additional information which can be used to create a MonoJitInfo for this trampoline by
6027 * create_jit_info_for_trampoline ().
6029 static G_GNUC_UNUSED void
6030 emit_trampoline_full (MonoAotCompile *acfg, int got_offset, MonoTrampInfo *info, gboolean emit_tinfo)
6032 char start_symbol [256];
6033 char end_symbol [256];
6035 guint32 buf_size, info_offset;
6036 MonoJumpInfo *patch_info;
6049 code_size = info->code_size;
6051 unwind_ops = info->unwind_ops;
6053 #ifdef __native_client_codegen__
6054 mono_nacl_fix_patches (code, ji);
6059 sprintf (start_symbol, "%s%s", acfg->user_symbol_prefix, name);
6061 emit_section_change (acfg, ".text", 0);
6062 emit_global (acfg, start_symbol, TRUE);
6063 emit_alignment_code (acfg, AOT_FUNC_ALIGNMENT);
6064 emit_label (acfg, start_symbol);
6066 sprintf (symbol, "%snamed_%s", acfg->temp_prefix, name);
6067 emit_label (acfg, symbol);
6070 * The code should access everything through the GOT, so we pass
6073 emit_and_reloc_code (acfg, NULL, code, code_size, ji, TRUE, NULL);
6075 emit_symbol_size (acfg, start_symbol, ".");
6078 sprintf (end_symbol, "%snamede_%s", acfg->temp_prefix, name);
6079 emit_label (acfg, end_symbol);
6084 /* Sort relocations */
6085 patches = g_ptr_array_new ();
6086 for (patch_info = ji; patch_info; patch_info = patch_info->next)
6087 if (patch_info->type != MONO_PATCH_INFO_NONE)
6088 g_ptr_array_add (patches, patch_info);
6089 g_ptr_array_sort (patches, compare_patches);
6091 buf_size = patches->len * 128 + 128;
6092 buf = g_malloc (buf_size);
6095 encode_patch_list (acfg, patches, patches->len, FALSE, got_offset, p, &p);
6096 g_assert (p - buf < buf_size);
6098 sprintf (symbol, "%s%s_p", acfg->user_symbol_prefix, name);
6100 info_offset = add_to_blob (acfg, buf, p - buf);
6102 emit_section_change (acfg, RODATA_SECT, 0);
6103 emit_global (acfg, symbol, FALSE);
6104 emit_label (acfg, symbol);
6106 emit_int32 (acfg, info_offset);
6110 guint32 encoded_len;
6114 * Emit additional information which can be used to reconstruct a partial MonoTrampInfo.
6116 encoded = mono_unwind_ops_encode (info->unwind_ops, &encoded_len);
6117 uw_offset = get_unwind_info_offset (acfg, encoded, encoded_len);
6120 emit_symbol_diff (acfg, end_symbol, start_symbol, 0);
6121 emit_int32 (acfg, uw_offset);
6124 /* Emit debug info */
6128 sprintf (symbol, "%s", name);
6129 sprintf (symbol2, "%snamed_%s", acfg->temp_prefix, name);
6132 mono_dwarf_writer_emit_trampoline (acfg->dwarf, symbol, symbol2, NULL, NULL, code_size, unwind_ops);
6136 static G_GNUC_UNUSED void
6137 emit_trampoline (MonoAotCompile *acfg, int got_offset, MonoTrampInfo *info)
6139 emit_trampoline_full (acfg, got_offset, info, TRUE);
6143 emit_trampolines (MonoAotCompile *acfg)
6146 char end_symbol [256];
6147 int i, tramp_got_offset;
6148 MonoAotTrampoline ntype;
6149 #ifdef MONO_ARCH_HAVE_FULL_AOT_TRAMPOLINES
6153 if (!mono_aot_mode_is_full (&acfg->aot_opts))
6156 g_assert (acfg->image->assembly);
6158 /* Currently, we emit most trampolines into the mscorlib AOT image. */
6159 if (strcmp (acfg->image->assembly->aname.name, "mscorlib") == 0) {
6160 #ifdef MONO_ARCH_HAVE_FULL_AOT_TRAMPOLINES
6161 MonoTrampInfo *info;
6164 * Emit the generic trampolines.
6166 * We could save some code by treating the generic trampolines as a wrapper
6167 * method, but that approach has its own complexities, so we choose the simpler
6170 for (tramp_type = 0; tramp_type < MONO_TRAMPOLINE_NUM; ++tramp_type) {
6171 /* we overload the boolean here to indicate the slightly different trampoline needed, see mono_arch_create_generic_trampoline() */
6172 #ifdef DISABLE_REMOTING
6173 if (tramp_type == MONO_TRAMPOLINE_GENERIC_VIRTUAL_REMOTING)
6176 #ifndef MONO_ARCH_HAVE_HANDLER_BLOCK_GUARD
6177 if (tramp_type == MONO_TRAMPOLINE_HANDLER_BLOCK_GUARD)
6180 mono_arch_create_generic_trampoline (tramp_type, &info, acfg->aot_opts.use_trampolines_page? 2: TRUE);
6181 emit_trampoline (acfg, acfg->got_offset, info);
6184 /* Emit the exception related code pieces */
6185 mono_arch_get_restore_context (&info, TRUE);
6186 emit_trampoline (acfg, acfg->got_offset, info);
6187 mono_arch_get_call_filter (&info, TRUE);
6188 emit_trampoline (acfg, acfg->got_offset, info);
6189 mono_arch_get_throw_exception (&info, TRUE);
6190 emit_trampoline (acfg, acfg->got_offset, info);
6191 mono_arch_get_rethrow_exception (&info, TRUE);
6192 emit_trampoline (acfg, acfg->got_offset, info);
6193 mono_arch_get_throw_corlib_exception (&info, TRUE);
6194 emit_trampoline (acfg, acfg->got_offset, info);
6196 #ifdef MONO_ARCH_HAVE_SDB_TRAMPOLINES
6197 mono_arch_create_sdb_trampoline (TRUE, &info, TRUE);
6198 emit_trampoline (acfg, acfg->got_offset, info);
6199 mono_arch_create_sdb_trampoline (FALSE, &info, TRUE);
6200 emit_trampoline (acfg, acfg->got_offset, info);
6203 #ifdef MONO_ARCH_GSHAREDVT_SUPPORTED
6204 mono_arch_get_gsharedvt_trampoline (&info, TRUE);
6206 emit_trampoline_full (acfg, acfg->got_offset, info, TRUE);
6208 /* Create a separate out trampoline for more information in stack traces */
6209 info->name = g_strdup ("gsharedvt_out_trampoline");
6210 emit_trampoline_full (acfg, acfg->got_offset, info, TRUE);
6214 #if defined(MONO_ARCH_HAVE_GET_TRAMPOLINES)
6216 GSList *l = mono_arch_get_trampolines (TRUE);
6219 MonoTrampInfo *info = l->data;
6221 emit_trampoline (acfg, acfg->got_offset, info);
6227 for (i = 0; i < acfg->aot_opts.nrgctx_fetch_trampolines; ++i) {
6230 offset = MONO_RGCTX_SLOT_MAKE_RGCTX (i);
6231 mono_arch_create_rgctx_lazy_fetch_trampoline (offset, &info, TRUE);
6232 emit_trampoline (acfg, acfg->got_offset, info);
6234 offset = MONO_RGCTX_SLOT_MAKE_MRGCTX (i);
6235 mono_arch_create_rgctx_lazy_fetch_trampoline (offset, &info, TRUE);
6236 emit_trampoline (acfg, acfg->got_offset, info);
6239 #ifdef MONO_ARCH_HAVE_GENERAL_RGCTX_LAZY_FETCH_TRAMPOLINE
6240 mono_arch_create_general_rgctx_lazy_fetch_trampoline (&info, TRUE);
6241 emit_trampoline (acfg, acfg->got_offset, info);
6247 /* delegate_invoke_impl trampolines */
6248 l = mono_arch_get_delegate_invoke_impls ();
6250 MonoTrampInfo *info = l->data;
6252 emit_trampoline (acfg, acfg->got_offset, info);
6257 #endif /* #ifdef MONO_ARCH_HAVE_FULL_AOT_TRAMPOLINES */
6259 /* Emit trampolines which are numerous */
6262 * These include the following:
6263 * - specific trampolines
6264 * - static rgctx invoke trampolines
6266 * These trampolines have the same code, they are parameterized by GOT
6268 * They are defined in this file, in the arch_... routines instead of
6269 * in tramp-<ARCH>.c, since it is easier to do it this way.
6273 * When running in aot-only mode, we can't create specific trampolines at
6274 * runtime, so we create a few, and save them in the AOT file.
6275 * Normal trampolines embed their argument as a literal inside the
6276 * trampoline code, we can't do that here, so instead we embed an offset
6277 * which needs to be added to the trampoline address to get the address of
6278 * the GOT slot which contains the argument value.
6279 * The generated trampolines jump to the generic trampolines using another
6280 * GOT slot, which will be setup by the AOT loader to point to the
6281 * generic trampoline code of the given type.
6285 * FIXME: Maybe we should use more specific trampolines (i.e. one class init for
6289 emit_section_change (acfg, ".text", 0);
6291 tramp_got_offset = acfg->got_offset;
6293 for (ntype = 0; ntype < MONO_AOT_TRAMP_NUM; ++ntype) {
6295 case MONO_AOT_TRAMP_SPECIFIC:
6296 sprintf (symbol, "specific_trampolines");
6298 case MONO_AOT_TRAMP_STATIC_RGCTX:
6299 sprintf (symbol, "static_rgctx_trampolines");
6301 case MONO_AOT_TRAMP_IMT_THUNK:
6302 sprintf (symbol, "imt_thunks");
6304 case MONO_AOT_TRAMP_GSHAREDVT_ARG:
6305 sprintf (symbol, "gsharedvt_arg_trampolines");
6308 g_assert_not_reached ();
6311 sprintf (end_symbol, "%s_e", symbol);
6313 if (acfg->aot_opts.write_symbols)
6314 emit_local_symbol (acfg, symbol, end_symbol, TRUE);
6316 emit_alignment_code (acfg, AOT_FUNC_ALIGNMENT);
6317 emit_info_symbol (acfg, symbol);
6319 acfg->trampoline_got_offset_base [ntype] = tramp_got_offset;
6321 for (i = 0; i < acfg->num_trampolines [ntype]; ++i) {
6325 case MONO_AOT_TRAMP_SPECIFIC:
6326 arch_emit_specific_trampoline (acfg, tramp_got_offset, &tramp_size);
6327 tramp_got_offset += 2;
6329 case MONO_AOT_TRAMP_STATIC_RGCTX:
6330 arch_emit_static_rgctx_trampoline (acfg, tramp_got_offset, &tramp_size);
6331 tramp_got_offset += 2;
6333 case MONO_AOT_TRAMP_IMT_THUNK:
6334 arch_emit_imt_thunk (acfg, tramp_got_offset, &tramp_size);
6335 tramp_got_offset += 1;
6337 case MONO_AOT_TRAMP_GSHAREDVT_ARG:
6338 arch_emit_gsharedvt_arg_trampoline (acfg, tramp_got_offset, &tramp_size);
6339 tramp_got_offset += 2;
6342 g_assert_not_reached ();
6344 #ifdef __native_client_codegen__
6345 /* align to avoid 32-byte boundary crossings */
6346 emit_alignment (acfg, AOT_FUNC_ALIGNMENT);
6349 if (!acfg->trampoline_size [ntype]) {
6350 g_assert (tramp_size);
6351 acfg->trampoline_size [ntype] = tramp_size;
6355 emit_label (acfg, end_symbol);
6356 emit_int32 (acfg, 0);
6359 arch_emit_specific_trampoline_pages (acfg);
6361 /* Reserve some entries at the end of the GOT for our use */
6362 acfg->num_trampoline_got_entries = tramp_got_offset - acfg->got_offset;
6365 acfg->got_offset += acfg->num_trampoline_got_entries;
6369 str_begins_with (const char *str1, const char *str2)
6371 int len = strlen (str2);
6372 return strncmp (str1, str2, len) == 0;
6376 mono_aot_readonly_field_override (MonoClassField *field)
6379 for (rdv = readonly_values; rdv; rdv = rdv->next) {
6380 char *p = rdv->name;
6382 len = strlen (field->parent->name_space);
6383 if (strncmp (p, field->parent->name_space, len))
6388 len = strlen (field->parent->name);
6389 if (strncmp (p, field->parent->name, len))
6394 if (strcmp (p, field->name))
6396 switch (rdv->type) {
6398 return &rdv->value.i1;
6400 return &rdv->value.i2;
6402 return &rdv->value.i4;
6411 add_readonly_value (MonoAotOptions *opts, const char *val)
6416 /* the format of val is:
6417 * namespace.typename.fieldname=type/value
6418 * type can be i1 for uint8/int8/boolean, i2 for uint16/int16/char, i4 for uint32/int32
6420 fval = strrchr (val, '/');
6422 fprintf (stderr, "AOT : invalid format for readonly field '%s', missing /.\n", val);
6425 tval = strrchr (val, '=');
6427 fprintf (stderr, "AOT : invalid format for readonly field '%s', missing =.\n", val);
6430 rdv = g_new0 (ReadOnlyValue, 1);
6431 rdv->name = g_malloc0 (tval - val + 1);
6432 memcpy (rdv->name, val, tval - val);
6435 if (strncmp (tval, "i1", 2) == 0) {
6436 rdv->value.i1 = atoi (fval);
6437 rdv->type = MONO_TYPE_I1;
6438 } else if (strncmp (tval, "i2", 2) == 0) {
6439 rdv->value.i2 = atoi (fval);
6440 rdv->type = MONO_TYPE_I2;
6441 } else if (strncmp (tval, "i4", 2) == 0) {
6442 rdv->value.i4 = atoi (fval);
6443 rdv->type = MONO_TYPE_I4;
6445 fprintf (stderr, "AOT : unsupported type for readonly field '%s'.\n", tval);
6448 rdv->next = readonly_values;
6449 readonly_values = rdv;
6453 clean_path (gchar * path)
6458 if (g_str_has_suffix (path, G_DIR_SEPARATOR_S))
6461 gchar *clean = g_strconcat (path, G_DIR_SEPARATOR_S, NULL);
6468 mono_aot_split_options (const char *aot_options)
6470 enum MonoAotOptionState {
6471 MONO_AOT_OPTION_STATE_DEFAULT,
6472 MONO_AOT_OPTION_STATE_STRING,
6473 MONO_AOT_OPTION_STATE_ESCAPE,
6476 GPtrArray *args = g_ptr_array_new ();
6477 enum MonoAotOptionState state = MONO_AOT_OPTION_STATE_DEFAULT;
6478 gchar const *opt_start = aot_options;
6479 gboolean end_of_string = FALSE;
6482 g_return_val_if_fail (aot_options != NULL, NULL);
6484 while ((cur = *aot_options) != '\0') {
6485 if (state == MONO_AOT_OPTION_STATE_ESCAPE)
6490 // If we find a quote, then if we're in the default case then
6491 // it means we've found the start of a string, if not then it
6492 // means we've found the end of the string and should switch
6493 // back to the default case.
6495 case MONO_AOT_OPTION_STATE_DEFAULT:
6496 state = MONO_AOT_OPTION_STATE_STRING;
6498 case MONO_AOT_OPTION_STATE_STRING:
6499 state = MONO_AOT_OPTION_STATE_DEFAULT;
6501 case MONO_AOT_OPTION_STATE_ESCAPE:
6502 g_assert_not_reached ();
6507 // If we've found an escaping operator, then this means we
6508 // should not process the next character if inside a string.
6509 if (state == MONO_AOT_OPTION_STATE_STRING)
6510 state = MONO_AOT_OPTION_STATE_ESCAPE;
6513 // If we're in the default state then this means we've found
6514 // an option, store it for later processing.
6515 if (state == MONO_AOT_OPTION_STATE_DEFAULT)
6522 // If the next character is end of string, then process the last option.
6523 if (*(aot_options) == '\0') {
6524 end_of_string = TRUE;
6530 g_ptr_array_add (args, g_strndup (opt_start, aot_options - opt_start));
6531 opt_start = ++aot_options;
6541 mono_aot_parse_options (const char *aot_options, MonoAotOptions *opts)
6545 args = mono_aot_split_options (aot_options ? aot_options : "");
6546 for (int i = 0; i < args->len; ++i) {
6547 const char *arg = g_ptr_array_index (args, i);
6549 if (str_begins_with (arg, "outfile=")) {
6550 opts->outfile = g_strdup (arg + strlen ("outfile="));
6551 } else if (str_begins_with (arg, "llvm-outfile=")) {
6552 opts->llvm_outfile = g_strdup (arg + strlen ("llvm-outfile="));
6553 } else if (str_begins_with (arg, "temp-path=")) {
6554 opts->temp_path = clean_path (g_strdup (arg + strlen ("temp-path=")));
6555 } else if (str_begins_with (arg, "save-temps")) {
6556 opts->save_temps = TRUE;
6557 } else if (str_begins_with (arg, "keep-temps")) {
6558 opts->save_temps = TRUE;
6559 } else if (str_begins_with (arg, "write-symbols")) {
6560 opts->write_symbols = TRUE;
6561 } else if (str_begins_with (arg, "no-write-symbols")) {
6562 opts->write_symbols = FALSE;
6563 } else if (str_begins_with (arg, "metadata-only")) {
6564 opts->metadata_only = TRUE;
6565 } else if (str_begins_with (arg, "bind-to-runtime-version")) {
6566 opts->bind_to_runtime_version = TRUE;
6567 } else if (str_begins_with (arg, "full")) {
6568 opts->mode = MONO_AOT_MODE_FULL;
6569 } else if (str_begins_with (arg, "hybrid")) {
6570 opts->mode = MONO_AOT_MODE_HYBRID;
6571 } else if (str_begins_with (arg, "threads=")) {
6572 opts->nthreads = atoi (arg + strlen ("threads="));
6573 } else if (str_begins_with (arg, "static")) {
6574 opts->static_link = TRUE;
6575 opts->no_dlsym = TRUE;
6576 } else if (str_begins_with (arg, "asmonly")) {
6577 opts->asm_only = TRUE;
6578 } else if (str_begins_with (arg, "asmwriter")) {
6579 opts->asm_writer = TRUE;
6580 } else if (str_begins_with (arg, "nodebug")) {
6581 opts->nodebug = TRUE;
6582 } else if (str_begins_with (arg, "dwarfdebug")) {
6583 opts->dwarf_debug = TRUE;
6584 } else if (str_begins_with (arg, "nopagetrampolines")) {
6585 opts->use_trampolines_page = FALSE;
6586 } else if (str_begins_with (arg, "ntrampolines=")) {
6587 opts->ntrampolines = atoi (arg + strlen ("ntrampolines="));
6588 } else if (str_begins_with (arg, "nrgctx-trampolines=")) {
6589 opts->nrgctx_trampolines = atoi (arg + strlen ("nrgctx-trampolines="));
6590 } else if (str_begins_with (arg, "nimt-trampolines=")) {
6591 opts->nimt_trampolines = atoi (arg + strlen ("nimt-trampolines="));
6592 } else if (str_begins_with (arg, "ngsharedvt-trampolines=")) {
6593 opts->ngsharedvt_arg_trampolines = atoi (arg + strlen ("ngsharedvt-trampolines="));
6594 } else if (str_begins_with (arg, "tool-prefix=")) {
6595 opts->tool_prefix = g_strdup (arg + strlen ("tool-prefix="));
6596 } else if (str_begins_with (arg, "ld-flags=")) {
6597 opts->ld_flags = g_strdup (arg + strlen ("ld-flags="));
6598 } else if (str_begins_with (arg, "soft-debug")) {
6599 opts->soft_debug = TRUE;
6600 } else if (str_begins_with (arg, "gen-seq-points-file")) {
6601 opts->gen_seq_points_file = TRUE;
6602 } else if (str_begins_with (arg, "direct-pinvoke")) {
6603 opts->direct_pinvoke = TRUE;
6604 } else if (str_begins_with (arg, "direct-icalls")) {
6605 opts->direct_icalls = TRUE;
6606 } else if (str_begins_with (arg, "no-direct-calls")) {
6607 opts->no_direct_calls = TRUE;
6608 } else if (str_begins_with (arg, "print-skipped")) {
6609 opts->print_skipped_methods = TRUE;
6610 } else if (str_begins_with (arg, "stats")) {
6612 } else if (str_begins_with (arg, "no-instances")) {
6613 opts->no_instances = TRUE;
6614 } else if (str_begins_with (arg, "log-generics")) {
6615 opts->log_generics = TRUE;
6616 } else if (str_begins_with (arg, "log-instances=")) {
6617 opts->log_instances = TRUE;
6618 opts->instances_logfile_path = g_strdup (arg + strlen ("log-instances="));
6619 } else if (str_begins_with (arg, "log-instances")) {
6620 opts->log_instances = TRUE;
6621 } else if (str_begins_with (arg, "internal-logfile=")) {
6622 opts->logfile = g_strdup (arg + strlen ("internal-logfile="));
6623 } else if (str_begins_with (arg, "mtriple=")) {
6624 opts->mtriple = g_strdup (arg + strlen ("mtriple="));
6625 } else if (str_begins_with (arg, "llvm-path=")) {
6626 opts->llvm_path = clean_path (g_strdup (arg + strlen ("llvm-path=")));
6627 } else if (!strcmp (arg, "llvm")) {
6629 } else if (str_begins_with (arg, "readonly-value=")) {
6630 add_readonly_value (opts, arg + strlen ("readonly-value="));
6631 } else if (str_begins_with (arg, "info")) {
6632 printf ("AOT target setup: %s.\n", AOT_TARGET_STR);
6634 } else if (str_begins_with (arg, "gc-maps")) {
6635 mini_gc_enable_gc_maps_for_aot ();
6636 } else if (str_begins_with (arg, "dump")) {
6637 opts->dump_json = TRUE;
6638 } else if (str_begins_with (arg, "llvmonly")) {
6639 opts->mode = MONO_AOT_MODE_FULL;
6641 opts->llvm_only = TRUE;
6642 } else if (str_begins_with (arg, "help") || str_begins_with (arg, "?")) {
6643 printf ("Supported options for --aot:\n");
6644 printf (" outfile=\n");
6645 printf (" llvm-outfile=\n");
6646 printf (" llvm-path=\n");
6647 printf (" temp-path=\n");
6648 printf (" save-temps\n");
6649 printf (" keep-temps\n");
6650 printf (" write-symbols\n");
6651 printf (" metadata-only\n");
6652 printf (" bind-to-runtime-version\n");
6654 printf (" threads=\n");
6655 printf (" static\n");
6656 printf (" asmonly\n");
6657 printf (" asmwriter\n");
6658 printf (" nodebug\n");
6659 printf (" dwarfdebug\n");
6660 printf (" ntrampolines=\n");
6661 printf (" nrgctx-trampolines=\n");
6662 printf (" nimt-trampolines=\n");
6663 printf (" ngsharedvt-trampolines=\n");
6664 printf (" tool-prefix=\n");
6665 printf (" readonly-value=\n");
6666 printf (" soft-debug\n");
6667 printf (" gen-seq-points-file\n");
6668 printf (" gc-maps\n");
6669 printf (" print-skipped\n");
6670 printf (" no-instances\n");
6671 printf (" stats\n");
6674 printf (" help/?\n");
6677 fprintf (stderr, "AOT : Unknown argument '%s'.\n", arg);
6681 g_free ((gpointer) arg);
6684 if (opts->use_trampolines_page) {
6685 opts->ntrampolines = 0;
6686 opts->nrgctx_trampolines = 0;
6687 opts->nimt_trampolines = 0;
6688 opts->ngsharedvt_arg_trampolines = 0;
6691 g_ptr_array_free (args, /*free_seg=*/TRUE);
6695 add_token_info_hash (gpointer key, gpointer value, gpointer user_data)
6697 MonoMethod *method = (MonoMethod*)key;
6698 MonoJumpInfoToken *ji = (MonoJumpInfoToken*)value;
6699 MonoAotCompile *acfg = user_data;
6700 MonoJumpInfoToken *new_ji;
6702 new_ji = mono_mempool_alloc0 (acfg->mempool, sizeof (MonoJumpInfoToken));
6703 new_ji->image = ji->image;
6704 new_ji->token = ji->token;
6705 g_hash_table_insert (acfg->token_info_hash, method, new_ji);
6709 can_encode_class (MonoAotCompile *acfg, MonoClass *klass)
6711 if (klass->type_token)
6713 if ((klass->byval_arg.type == MONO_TYPE_VAR) || (klass->byval_arg.type == MONO_TYPE_MVAR) || (klass->byval_arg.type == MONO_TYPE_PTR))
6716 return can_encode_class (acfg, klass->element_class);
6721 can_encode_method (MonoAotCompile *acfg, MonoMethod *method)
6723 if (method->wrapper_type) {
6724 switch (method->wrapper_type) {
6725 case MONO_WRAPPER_NONE:
6726 case MONO_WRAPPER_REMOTING_INVOKE_WITH_CHECK:
6727 case MONO_WRAPPER_XDOMAIN_INVOKE:
6728 case MONO_WRAPPER_STFLD:
6729 case MONO_WRAPPER_LDFLD:
6730 case MONO_WRAPPER_LDFLDA:
6731 case MONO_WRAPPER_LDFLD_REMOTE:
6732 case MONO_WRAPPER_STFLD_REMOTE:
6733 case MONO_WRAPPER_STELEMREF:
6734 case MONO_WRAPPER_ISINST:
6735 case MONO_WRAPPER_PROXY_ISINST:
6736 case MONO_WRAPPER_ALLOC:
6737 case MONO_WRAPPER_REMOTING_INVOKE:
6738 case MONO_WRAPPER_UNKNOWN:
6739 case MONO_WRAPPER_WRITE_BARRIER:
6740 case MONO_WRAPPER_DELEGATE_INVOKE:
6741 case MONO_WRAPPER_DELEGATE_BEGIN_INVOKE:
6742 case MONO_WRAPPER_DELEGATE_END_INVOKE:
6743 case MONO_WRAPPER_SYNCHRONIZED:
6745 case MONO_WRAPPER_MANAGED_TO_MANAGED:
6746 case MONO_WRAPPER_CASTCLASS: {
6747 WrapperInfo *info = mono_marshal_get_wrapper_info (method);
6756 //printf ("Skip (wrapper call): %d -> %s\n", patch_info->type, mono_method_full_name (patch_info->data.method, TRUE));
6760 if (!method->token) {
6761 /* The method is part of a constructed type like Int[,].Set (). */
6762 if (!g_hash_table_lookup (acfg->token_info_hash, method)) {
6763 if (method->klass->rank)
6773 can_encode_patch (MonoAotCompile *acfg, MonoJumpInfo *patch_info)
6775 switch (patch_info->type) {
6776 case MONO_PATCH_INFO_METHOD:
6777 case MONO_PATCH_INFO_METHODCONST:
6778 case MONO_PATCH_INFO_METHOD_CODE_SLOT: {
6779 MonoMethod *method = patch_info->data.method;
6781 return can_encode_method (acfg, method);
6783 case MONO_PATCH_INFO_VTABLE:
6784 case MONO_PATCH_INFO_CLASS:
6785 case MONO_PATCH_INFO_IID:
6786 case MONO_PATCH_INFO_ADJUSTED_IID:
6787 if (!can_encode_class (acfg, patch_info->data.klass)) {
6788 //printf ("Skip: %s\n", mono_type_full_name (&patch_info->data.klass->byval_arg));
6792 case MONO_PATCH_INFO_DELEGATE_TRAMPOLINE: {
6793 if (!can_encode_class (acfg, patch_info->data.del_tramp->klass)) {
6794 //printf ("Skip: %s\n", mono_type_full_name (&patch_info->data.klass->byval_arg));
6799 case MONO_PATCH_INFO_RGCTX_FETCH:
6800 case MONO_PATCH_INFO_RGCTX_SLOT_INDEX: {
6801 MonoJumpInfoRgctxEntry *entry = patch_info->data.rgctx_entry;
6803 if (!can_encode_method (acfg, entry->method))
6805 if (!can_encode_patch (acfg, entry->data))
6819 * AOT compile a given method.
6820 * This function might be called by multiple threads, so it must be thread-safe.
6823 compile_method (MonoAotCompile *acfg, MonoMethod *method)
6826 MonoJumpInfo *patch_info;
6829 MonoMethod *wrapped;
6832 if (acfg->aot_opts.metadata_only)
6835 mono_acfg_lock (acfg);
6836 index = get_method_index (acfg, method);
6837 mono_acfg_unlock (acfg);
6839 /* fixme: maybe we can also precompile wrapper methods */
6840 if ((method->flags & METHOD_ATTRIBUTE_PINVOKE_IMPL) ||
6841 (method->iflags & METHOD_IMPL_ATTRIBUTE_RUNTIME) ||
6842 (method->flags & METHOD_ATTRIBUTE_ABSTRACT)) {
6843 //printf ("Skip (impossible): %s\n", mono_method_full_name (method, TRUE));
6847 if (method->iflags & METHOD_IMPL_ATTRIBUTE_INTERNAL_CALL)
6850 wrapped = mono_marshal_method_from_wrapper (method);
6851 if (wrapped && (wrapped->iflags & METHOD_IMPL_ATTRIBUTE_INTERNAL_CALL) && wrapped->is_generic)
6852 // FIXME: The wrapper should be generic too, but it is not
6855 if (method->wrapper_type == MONO_WRAPPER_COMINTEROP)
6858 InterlockedIncrement (&acfg->stats.mcount);
6861 if (method->is_generic || method->klass->generic_container) {
6862 InterlockedIncrement (&acfg->stats.genericcount);
6867 //acfg->aot_opts.print_skipped_methods = TRUE;
6870 * Since these methods are the only ones which are compiled with
6871 * AOT support, and they are not used by runtime startup/shutdown code,
6872 * the runtime will not see AOT methods during AOT compilation,so it
6873 * does not need to support them by creating a fake GOT etc.
6875 flags = JIT_FLAG_AOT;
6876 if (mono_aot_mode_is_full (&acfg->aot_opts))
6877 flags |= JIT_FLAG_FULL_AOT;
6879 flags |= JIT_FLAG_LLVM;
6880 if (acfg->aot_opts.llvm_only)
6881 flags |= JIT_FLAG_LLVM_ONLY;
6882 if (acfg->aot_opts.no_direct_calls)
6883 flags |= JIT_FLAG_NO_DIRECT_ICALLS;
6884 cfg = mini_method_compile (method, acfg->opts, mono_get_root_domain (), flags, 0, index);
6885 mono_loader_clear_error ();
6887 if (cfg->exception_type == MONO_EXCEPTION_GENERIC_SHARING_FAILED) {
6888 if (acfg->aot_opts.print_skipped_methods)
6889 printf ("Skip (gshared failure): %s (%s)\n", mono_method_full_name (method, TRUE), cfg->exception_message);
6890 InterlockedIncrement (&acfg->stats.genericcount);
6893 if (cfg->exception_type != MONO_EXCEPTION_NONE) {
6894 if (acfg->aot_opts.print_skipped_methods)
6895 printf ("Skip (JIT failure): %s\n", mono_method_full_name (method, TRUE));
6896 /* Let the exception happen at runtime */
6900 if (cfg->disable_aot) {
6901 if (acfg->aot_opts.print_skipped_methods)
6902 printf ("Skip (disabled): %s\n", mono_method_full_name (method, TRUE));
6903 InterlockedIncrement (&acfg->stats.ocount);
6904 mono_destroy_compile (cfg);
6907 cfg->method_index = index;
6909 /* Nullify patches which need no aot processing */
6910 for (patch_info = cfg->patch_info; patch_info; patch_info = patch_info->next) {
6911 switch (patch_info->type) {
6912 case MONO_PATCH_INFO_LABEL:
6913 case MONO_PATCH_INFO_BB:
6914 patch_info->type = MONO_PATCH_INFO_NONE;
6921 /* Collect method->token associations from the cfg */
6922 mono_acfg_lock (acfg);
6923 g_hash_table_foreach (cfg->token_info_hash, add_token_info_hash, acfg);
6924 mono_acfg_unlock (acfg);
6925 g_hash_table_destroy (cfg->token_info_hash);
6926 cfg->token_info_hash = NULL;
6929 * Check for absolute addresses.
6932 for (patch_info = cfg->patch_info; patch_info; patch_info = patch_info->next) {
6933 switch (patch_info->type) {
6934 case MONO_PATCH_INFO_ABS:
6935 /* unable to handle this */
6944 if (acfg->aot_opts.print_skipped_methods)
6945 printf ("Skip (abs call): %s\n", mono_method_full_name (method, TRUE));
6946 InterlockedIncrement (&acfg->stats.abscount);
6947 mono_destroy_compile (cfg);
6951 /* Lock for the rest of the code */
6952 mono_acfg_lock (acfg);
6955 * Check for methods/klasses we can't encode.
6958 for (patch_info = cfg->patch_info; patch_info; patch_info = patch_info->next) {
6959 if (!can_encode_patch (acfg, patch_info))
6964 if (acfg->aot_opts.print_skipped_methods)
6965 printf ("Skip (patches): %s\n", mono_method_full_name (method, TRUE));
6966 acfg->stats.ocount++;
6967 mono_destroy_compile (cfg);
6968 mono_acfg_unlock (acfg);
6972 if (!cfg->compile_llvm)
6973 acfg->has_jitted_code = TRUE;
6975 if (method->is_inflated && acfg->aot_opts.log_instances) {
6976 if (acfg->instances_logfile)
6977 fprintf (acfg->instances_logfile, "%s ### %d\n", mono_method_full_name (method, TRUE), cfg->code_size);
6979 printf ("%s ### %d\n", mono_method_full_name (method, TRUE), cfg->code_size);
6982 /* Adds generic instances referenced by this method */
6984 * The depth is used to avoid infinite loops when generic virtual recursion is
6987 depth = GPOINTER_TO_UINT (g_hash_table_lookup (acfg->method_depth, method));
6988 if (!acfg->aot_opts.no_instances && depth < 32) {
6989 for (patch_info = cfg->patch_info; patch_info; patch_info = patch_info->next) {
6990 switch (patch_info->type) {
6991 case MONO_PATCH_INFO_RGCTX_FETCH:
6992 case MONO_PATCH_INFO_RGCTX_SLOT_INDEX:
6993 case MONO_PATCH_INFO_METHOD: {
6994 MonoMethod *m = NULL;
6996 if (patch_info->type == MONO_PATCH_INFO_RGCTX_FETCH || patch_info->type == MONO_PATCH_INFO_RGCTX_SLOT_INDEX) {
6997 MonoJumpInfoRgctxEntry *e = patch_info->data.rgctx_entry;
6999 if (e->info_type == MONO_RGCTX_INFO_GENERIC_METHOD_CODE)
7000 m = e->data->data.method;
7002 m = patch_info->data.method;
7007 if (m->is_inflated) {
7008 if (!(mono_class_generic_sharing_enabled (m->klass) &&
7009 mono_method_is_generic_sharable_full (m, FALSE, FALSE, FALSE)) &&
7010 (!method_has_type_vars (m) || mono_method_is_generic_sharable_full (m, TRUE, TRUE, FALSE))) {
7011 if (m->iflags & METHOD_IMPL_ATTRIBUTE_INTERNAL_CALL) {
7012 if (mono_aot_mode_is_full (&acfg->aot_opts) && !method_has_type_vars (m))
7013 add_extra_method_with_depth (acfg, mono_marshal_get_native_wrapper (m, TRUE, TRUE), depth + 1);
7015 add_extra_method_with_depth (acfg, m, depth + 1);
7016 add_types_from_method_header (acfg, m);
7019 add_generic_class_with_depth (acfg, m->klass, depth + 5, "method");
7021 if (m->wrapper_type == MONO_WRAPPER_MANAGED_TO_MANAGED) {
7022 WrapperInfo *info = mono_marshal_get_wrapper_info (m);
7024 if (info && info->subtype == WRAPPER_SUBTYPE_ELEMENT_ADDR)
7025 add_extra_method_with_depth (acfg, m, depth + 1);
7029 case MONO_PATCH_INFO_VTABLE: {
7030 MonoClass *klass = patch_info->data.klass;
7032 if (klass->generic_class && !mini_class_is_generic_sharable (klass))
7033 add_generic_class_with_depth (acfg, klass, depth + 5, "vtable");
7036 case MONO_PATCH_INFO_SFLDA: {
7037 MonoClass *klass = patch_info->data.field->parent;
7039 /* The .cctor needs to run at runtime. */
7040 if (klass->generic_class && !mono_generic_context_is_sharable (&klass->generic_class->context, FALSE) && mono_class_get_cctor (klass))
7041 add_extra_method_with_depth (acfg, mono_class_get_cctor (klass), depth + 1);
7050 /* Determine whenever the method has GOT slots */
7051 for (patch_info = cfg->patch_info; patch_info; patch_info = patch_info->next) {
7052 switch (patch_info->type) {
7053 case MONO_PATCH_INFO_GOT_OFFSET:
7054 case MONO_PATCH_INFO_NONE:
7055 case MONO_PATCH_INFO_GC_CARD_TABLE_ADDR:
7056 case MONO_PATCH_INFO_GC_NURSERY_START:
7058 case MONO_PATCH_INFO_IMAGE:
7059 /* The assembly is stored in GOT slot 0 */
7060 if (patch_info->data.image != acfg->image)
7061 cfg->has_got_slots = TRUE;
7064 if (!is_plt_patch (patch_info) || (cfg->compile_llvm && acfg->aot_opts.llvm_only))
7065 cfg->has_got_slots = TRUE;
7070 if (!cfg->has_got_slots)
7071 InterlockedIncrement (&acfg->stats.methods_without_got_slots);
7074 * FIXME: Instead of this mess, allocate the patches from the aot mempool.
7076 /* Make a copy of the patch info which is in the mempool */
7078 MonoJumpInfo *patches = NULL, *patches_end = NULL;
7080 for (patch_info = cfg->patch_info; patch_info; patch_info = patch_info->next) {
7081 MonoJumpInfo *new_patch_info = mono_patch_info_dup_mp (acfg->mempool, patch_info);
7084 patches = new_patch_info;
7086 patches_end->next = new_patch_info;
7087 patches_end = new_patch_info;
7089 cfg->patch_info = patches;
7091 /* Make a copy of the unwind info */
7093 GSList *l, *unwind_ops;
7097 for (l = cfg->unwind_ops; l; l = l->next) {
7098 op = mono_mempool_alloc (acfg->mempool, sizeof (MonoUnwindOp));
7099 memcpy (op, l->data, sizeof (MonoUnwindOp));
7100 unwind_ops = g_slist_prepend_mempool (acfg->mempool, unwind_ops, op);
7102 cfg->unwind_ops = g_slist_reverse (unwind_ops);
7104 /* Make a copy of the argument/local info */
7106 MonoInst **args, **locals;
7107 MonoMethodSignature *sig;
7108 MonoMethodHeader *header;
7111 sig = mono_method_signature (method);
7112 args = mono_mempool_alloc (acfg->mempool, sizeof (MonoInst*) * (sig->param_count + sig->hasthis));
7113 for (i = 0; i < sig->param_count + sig->hasthis; ++i) {
7114 args [i] = mono_mempool_alloc (acfg->mempool, sizeof (MonoInst));
7115 memcpy (args [i], cfg->args [i], sizeof (MonoInst));
7119 header = mono_method_get_header (method);
7120 locals = mono_mempool_alloc (acfg->mempool, sizeof (MonoInst*) * header->num_locals);
7121 for (i = 0; i < header->num_locals; ++i) {
7122 locals [i] = mono_mempool_alloc (acfg->mempool, sizeof (MonoInst));
7123 memcpy (locals [i], cfg->locals [i], sizeof (MonoInst));
7125 cfg->locals = locals;
7128 /* Free some fields used by cfg to conserve memory */
7129 mono_mempool_destroy (cfg->mempool);
7130 cfg->mempool = NULL;
7131 g_free (cfg->varinfo);
7132 cfg->varinfo = NULL;
7136 mono_regstate_free (cfg->rs);
7140 //printf ("Compile: %s\n", mono_method_full_name (method, TRUE));
7142 while (index >= acfg->cfgs_size) {
7143 MonoCompile **new_cfgs;
7146 new_size = acfg->cfgs_size * 2;
7147 new_cfgs = g_new0 (MonoCompile*, new_size);
7148 memcpy (new_cfgs, acfg->cfgs, sizeof (MonoCompile*) * acfg->cfgs_size);
7149 g_free (acfg->cfgs);
7150 acfg->cfgs = new_cfgs;
7151 acfg->cfgs_size = new_size;
7153 acfg->cfgs [index] = cfg;
7155 g_hash_table_insert (acfg->method_to_cfg, cfg->orig_method, cfg);
7158 if (cfg->orig_method->wrapper_type)
7159 g_ptr_array_add (acfg->extra_methods, cfg->orig_method);
7162 mono_acfg_unlock (acfg);
7164 InterlockedIncrement (&acfg->stats.ccount);
7168 compile_thread_main (gpointer *user_data)
7170 MonoDomain *domain = user_data [0];
7171 MonoAotCompile *acfg = user_data [1];
7172 GPtrArray *methods = user_data [2];
7175 mono_thread_attach (domain);
7177 for (i = 0; i < methods->len; ++i)
7178 compile_method (acfg, g_ptr_array_index (methods, i));
7182 load_profile_files (MonoAotCompile *acfg)
7186 int file_index, res, method_index, i;
7189 GList *unordered, *l;
7194 tmp = g_strdup_printf ("%s/.mono/aot-profile-data/%s-%d", g_get_home_dir (), acfg->image->assembly_name, file_index);
7196 if (!g_file_test (tmp, G_FILE_TEST_IS_REGULAR)) {
7201 infile = fopen (tmp, "r");
7204 printf ("Using profile data file '%s'\n", tmp);
7209 res = fscanf (infile, "%32s\n", ver);
7210 if ((res != 1) || strcmp (ver, "#VER:2") != 0) {
7211 printf ("Profile file has wrong version or invalid.\n");
7218 MonoMethodDesc *desc;
7221 if (fgets (name, 1023, infile) == NULL)
7224 /* Kill the newline */
7225 if (strlen (name) > 0)
7226 name [strlen (name) - 1] = '\0';
7228 desc = mono_method_desc_new (name, TRUE);
7230 method = mono_method_desc_search_in_image (desc, acfg->image);
7232 if (method && mono_method_get_token (method)) {
7233 token = mono_method_get_token (method);
7234 method_index = mono_metadata_token_index (token) - 1;
7237 for (i = 0; i < acfg->method_order->len; ++i) {
7238 if (g_ptr_array_index (acfg->method_order, i) == GUINT_TO_POINTER (method_index)) {
7244 g_ptr_array_add (acfg->method_order, GUINT_TO_POINTER (method_index));
7246 //printf ("No method found matching '%s'.\n", name);
7252 /* Add missing methods */
7254 for (method_index = 0; method_index < acfg->image->tables [MONO_TABLE_METHOD].rows; ++method_index) {
7256 for (i = 0; i < acfg->method_order->len; ++i) {
7257 if (g_ptr_array_index (acfg->method_order, i) == GUINT_TO_POINTER (method_index)) {
7263 unordered = g_list_prepend (unordered, GUINT_TO_POINTER (method_index));
7265 unordered = g_list_reverse (unordered);
7266 for (l = unordered; l; l = l->next)
7267 g_ptr_array_add (acfg->method_order, l->data);
7270 /* Used by the LLVM backend */
7272 mono_aot_get_got_offset (MonoJumpInfo *ji)
7274 return get_got_offset (llvm_acfg, TRUE, ji);
7278 mono_aot_get_method_name (MonoCompile *cfg)
7280 if (llvm_acfg->aot_opts.static_link)
7281 /* Include the assembly name too to avoid duplicate symbol errors */
7282 return g_strdup_printf ("%s_%s", llvm_acfg->assembly_name_sym, get_debug_sym (cfg->orig_method, "", llvm_acfg->method_label_hash));
7284 return get_debug_sym (cfg->orig_method, "", llvm_acfg->method_label_hash);
7288 mono_aot_is_direct_callable (MonoJumpInfo *patch_info)
7290 return is_direct_callable (llvm_acfg, NULL, patch_info);
7294 mono_aot_mark_unused_llvm_plt_entry (MonoJumpInfo *patch_info)
7296 MonoPltEntry *plt_entry;
7298 plt_entry = get_plt_entry (llvm_acfg, patch_info);
7299 plt_entry->llvm_used = FALSE;
7303 mono_aot_get_plt_symbol (MonoJumpInfoType type, gconstpointer data)
7305 MonoJumpInfo *ji = mono_mempool_alloc (llvm_acfg->mempool, sizeof (MonoJumpInfo));
7306 MonoPltEntry *plt_entry;
7307 const char *sym = NULL;
7310 ji->data.target = data;
7312 if (!can_encode_patch (llvm_acfg, ji))
7315 if (llvm_acfg->aot_opts.direct_icalls) {
7316 if (type == MONO_PATCH_INFO_JIT_ICALL_ADDR) {
7317 /* Call to a C function implementing a jit icall */
7318 sym = mono_lookup_jit_icall_symbol (data);
7319 } else if (type == MONO_PATCH_INFO_ICALL_ADDR) {
7320 MonoMethod *method = (gpointer)data;
7321 if (!(method->flags & METHOD_ATTRIBUTE_PINVOKE_IMPL))
7322 sym = mono_lookup_icall_symbol (method);
7325 return g_strdup (sym);
7328 plt_entry = get_plt_entry (llvm_acfg, ji);
7329 plt_entry->llvm_used = TRUE;
7331 #if defined(TARGET_MACH)
7332 return g_strdup_printf (plt_entry->llvm_symbol + strlen (llvm_acfg->llvm_label_prefix));
7334 return g_strdup_printf (plt_entry->llvm_symbol);
7339 mono_aot_get_method_index (MonoMethod *method)
7341 g_assert (llvm_acfg);
7342 return get_method_index (llvm_acfg, method);
7346 mono_aot_patch_info_dup (MonoJumpInfo* ji)
7350 mono_acfg_lock (llvm_acfg);
7351 res = mono_patch_info_dup_mp (llvm_acfg->mempool, ji);
7352 mono_acfg_unlock (llvm_acfg);
7358 execute_system (const char * command)
7363 // We need an extra set of quotes around the whole command to properly handle commands
7364 // with spaces since internally the command is called through "cmd /c.
7365 command = g_strdup_printf ("\"%s\"", command);
7367 int size = MultiByteToWideChar (CP_UTF8, 0 , command , -1, NULL , 0);
7368 wchar_t* wstr = g_malloc (sizeof (wchar_t) * size);
7369 MultiByteToWideChar (CP_UTF8, 0, command, -1, wstr , size);
7370 status = _wsystem (wstr);
7374 #elif defined (HAVE_SYSTEM)
7375 status = system (command);
7377 g_assert_not_reached ();
7388 * Emit the LLVM code into an LLVM bytecode file, and compile it using the LLVM
7392 emit_llvm_file (MonoAotCompile *acfg)
7394 char *command, *opts, *tempbc, *output_fname;
7396 tempbc = g_strdup_printf ("%s.bc", acfg->tmpbasename);
7397 mono_llvm_emit_aot_module (tempbc, g_path_get_basename (acfg->image->name));
7401 * FIXME: Experiment with adding optimizations, the -std-compile-opts set takes
7402 * a lot of time, and doesn't seem to save much space.
7403 * The following optimizations cannot be enabled:
7405 * - 'jump-threading' changes our blockaddress references to int constants.
7406 * - 'basiccg' fails because it contains:
7407 * if (CS && !isa<IntrinsicInst>(II)) {
7408 * and isa<IntrinsicInst> is false for invokes to intrinsics (iltests.exe).
7409 * - 'prune-eh' and 'functionattrs' depend on 'basiccg'.
7410 * The opt list below was produced by taking the output of:
7411 * llvm-as < /dev/null | opt -O2 -disable-output -debug-pass=Arguments
7412 * then removing tailcallelim + the global opts.
7413 * strip-dead-prototypes deletes unused intrinsics definitions.
7415 //opts = g_strdup ("-instcombine -simplifycfg");
7416 //opts = g_strdup ("-simplifycfg -domtree -domfrontier -scalarrepl -instcombine -simplifycfg -domtree -domfrontier -scalarrepl -simplify-libcalls -instcombine -simplifycfg -instcombine -simplifycfg -reassociate -domtree -loops -loop-simplify -domfrontier -loop-simplify -lcssa -loop-rotate -licm -lcssa -loop-unswitch -instcombine -scalar-evolution -loop-simplify -lcssa -iv-users -indvars -loop-deletion -loop-simplify -lcssa -loop-unroll -instcombine -memdep -gvn -memdep -memcpyopt -sccp -instcombine -domtree -memdep -dse -adce -simplifycfg -domtree -verify");
7417 /* The dse pass is disabled because of #13734 and #17616 */
7419 * The dse bug is in DeadStoreElimination.cpp:isOverwrite ():
7420 * // If we have no DataLayout information around, then the size of the store
7421 * // is inferrable from the pointee type. If they are the same type, then
7422 * // we know that the store is safe.
7423 * if (AA.getDataLayout() == 0 &&
7424 * Later.Ptr->getType() == Earlier.Ptr->getType()) {
7425 * return OverwriteComplete;
7426 * Here, if 'Earlier' refers to a memset, and Later has no size info, it mistakenly thinks the memset is redundant.
7428 //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");
7429 opts = g_strdup ("");
7431 command = g_strdup_printf ("\"%sopt\" -f %s -o \"%s.opt.bc\" \"%s.bc\"", acfg->aot_opts.llvm_path, opts, acfg->tmpbasename, acfg->tmpbasename);
7432 aot_printf (acfg, "Executing opt: %s\n", command);
7433 if (execute_system (command) != 0)
7438 if (!acfg->llc_args)
7439 acfg->llc_args = g_string_new ("");
7441 /* Verbose asm slows down llc greatly */
7442 g_string_append (acfg->llc_args, " -asm-verbose=false");
7444 g_string_append (acfg->llc_args, " -disable-gnu-eh-frame -enable-mono-eh-frame");
7446 if (acfg->aot_opts.mtriple)
7447 g_string_append_printf (acfg->llc_args, " -mtriple=%s", acfg->aot_opts.mtriple);
7449 g_string_append_printf (acfg->llc_args, " -mono-eh-frame-symbol=%s%s", acfg->user_symbol_prefix, acfg->llvm_eh_frame_symbol);
7451 #if defined(TARGET_MACH) && defined(TARGET_ARM)
7452 /* ios requires PIC code now */
7453 g_string_append_printf (acfg->llc_args, " -relocation-model=pic");
7455 if (llvm_acfg->aot_opts.static_link)
7456 g_string_append_printf (acfg->llc_args, " -relocation-model=static");
7458 g_string_append_printf (acfg->llc_args, " -relocation-model=pic");
7461 if (acfg->llvm_owriter) {
7462 /* Emit an object file directly */
7463 output_fname = g_strdup_printf ("%s", acfg->llvm_ofile);
7464 g_string_append_printf (acfg->llc_args, " -filetype=obj");
7466 output_fname = g_strdup_printf ("%s", acfg->llvm_sfile);
7468 command = g_strdup_printf ("\"%sllc\" %s -o \"%s\" \"%s.opt.bc\"", acfg->aot_opts.llvm_path, acfg->llc_args->str, output_fname, acfg->tmpbasename);
7469 g_free (output_fname);
7471 aot_printf (acfg, "Executing llc: %s\n", command);
7473 if (execute_system (command) != 0)
7480 emit_code (MonoAotCompile *acfg)
7482 int oindex, i, prev_index;
7483 gboolean saved_unbox_info = FALSE;
7486 if (!acfg->has_jitted_code)
7489 #if defined(TARGET_POWERPC64)
7490 sprintf (symbol, ".Lgot_addr");
7491 emit_section_change (acfg, ".text", 0);
7492 emit_alignment (acfg, 8);
7493 emit_label (acfg, symbol);
7494 emit_pointer (acfg, acfg->got_symbol);
7498 * This global symbol is used to compute the address of each method using the
7499 * code_offsets array. It is also used to compute the memory ranges occupied by
7500 * AOT code, so it must be equal to the address of the first emitted method.
7502 emit_section_change (acfg, ".text", 0);
7503 emit_alignment_code (acfg, 8);
7504 emit_info_symbol (acfg, "jit_code_start");
7507 * Emit some padding so the local symbol for the first method doesn't have the
7508 * same address as 'methods'.
7510 #if defined(__default_codegen__)
7511 emit_padding (acfg, 16);
7512 #elif defined(__native_client_codegen__)
7514 const int kPaddingSize = 16;
7515 guint8 pad_buffer[kPaddingSize];
7516 mono_arch_nacl_pad (pad_buffer, kPaddingSize);
7517 emit_bytes (acfg, pad_buffer, kPaddingSize);
7521 for (oindex = 0; oindex < acfg->method_order->len; ++oindex) {
7525 i = GPOINTER_TO_UINT (g_ptr_array_index (acfg->method_order, oindex));
7527 cfg = acfg->cfgs [i];
7532 method = cfg->orig_method;
7534 /* Emit unbox trampoline */
7535 if (mono_aot_mode_is_full (&acfg->aot_opts) && cfg->orig_method->klass->valuetype && !(acfg->aot_opts.llvm_only && cfg->compile_llvm)) {
7536 sprintf (symbol, "ut_%d", get_method_index (acfg, method));
7538 emit_section_change (acfg, ".text", 0);
7539 #ifdef __native_client_codegen__
7540 emit_alignment (acfg, AOT_FUNC_ALIGNMENT);
7543 if (acfg->thumb_mixed && cfg->compile_llvm) {
7544 emit_set_thumb_mode (acfg);
7545 fprintf (acfg->fp, "\n.thumb_func\n");
7548 emit_label (acfg, symbol);
7550 arch_emit_unbox_trampoline (acfg, cfg, cfg->orig_method, cfg->asm_symbol);
7552 if (acfg->thumb_mixed && cfg->compile_llvm)
7553 emit_set_arm_mode (acfg);
7555 if (!saved_unbox_info) {
7556 char user_symbol [128];
7558 sprintf (user_symbol, "%sunbox_trampoline_p", acfg->user_symbol_prefix);
7560 emit_label (acfg, "ut_end");
7562 unwind_ops = mono_unwind_get_cie_program ();
7563 save_unwind_info (acfg, user_symbol, unwind_ops);
7564 mono_free_unwind_info (unwind_ops);
7566 /* Save the unbox trampoline size */
7567 emit_symbol_diff (acfg, "ut_end", symbol, 0);
7569 saved_unbox_info = TRUE;
7573 if (cfg->compile_llvm)
7574 acfg->stats.llvm_count ++;
7576 emit_method_code (acfg, cfg);
7579 emit_section_change (acfg, ".text", 0);
7580 emit_alignment_code (acfg, 8);
7581 emit_info_symbol (acfg, "jit_code_end");
7583 /* To distinguish it from the next symbol */
7584 emit_padding (acfg, 4);
7587 * Add .no_dead_strip directives for all LLVM methods to prevent the OSX linker
7588 * from optimizing them away, since it doesn't see that code_offsets references them.
7589 * JITted methods don't need this since they are referenced using assembler local
7591 * FIXME: This is why write-symbols doesn't work on OSX ?
7593 if (acfg->llvm && acfg->need_no_dead_strip) {
7594 fprintf (acfg->fp, "\n");
7595 for (i = 0; i < acfg->nmethods; ++i) {
7596 if (acfg->cfgs [i] && acfg->cfgs [i]->compile_llvm)
7597 fprintf (acfg->fp, ".no_dead_strip %s\n", acfg->cfgs [i]->asm_symbol);
7602 * To work around linker issues, we emit a table of branches, and disassemble them at runtime.
7603 * This is PIE code, and the linker can update it if needed.
7605 sprintf (symbol, "method_addresses");
7606 emit_section_change (acfg, ".text", 1);
7607 emit_alignment_code (acfg, 8);
7608 emit_info_symbol (acfg, symbol);
7609 emit_local_symbol (acfg, symbol, "method_addresses_end", TRUE);
7610 emit_unset_mode (acfg);
7611 if (acfg->need_no_dead_strip)
7612 fprintf (acfg->fp, " .no_dead_strip %s\n", symbol);
7614 for (i = 0; i < acfg->nmethods; ++i) {
7615 #ifdef MONO_ARCH_AOT_SUPPORTED
7618 if (acfg->cfgs [i]) {
7619 if (acfg->aot_opts.llvm_only && acfg->cfgs [i]->compile_llvm)
7620 /* Obtained by calling a generated function in the LLVM image */
7621 arch_emit_direct_call (acfg, "method_addresses", FALSE, FALSE, NULL, &call_size);
7623 arch_emit_direct_call (acfg, acfg->cfgs [i]->asm_symbol, FALSE, acfg->thumb_mixed && acfg->cfgs [i]->compile_llvm, NULL, &call_size);
7625 arch_emit_direct_call (acfg, "method_addresses", FALSE, FALSE, NULL, &call_size);
7630 sprintf (symbol, "method_addresses_end");
7631 emit_label (acfg, symbol);
7634 /* Emit a sorted table mapping methods to the index of their unbox trampolines */
7635 sprintf (symbol, "unbox_trampolines");
7636 emit_section_change (acfg, RODATA_SECT, 0);
7637 emit_alignment (acfg, 8);
7638 emit_info_symbol (acfg, symbol);
7641 for (i = 0; i < acfg->nmethods; ++i) {
7646 cfg = acfg->cfgs [i];
7650 method = cfg->orig_method;
7652 if (mono_aot_mode_is_full (&acfg->aot_opts) && cfg->orig_method->klass->valuetype && !(acfg->aot_opts.llvm_only && cfg->compile_llvm)) {
7653 index = get_method_index (acfg, method);
7655 emit_int32 (acfg, index);
7656 /* Make sure the table is sorted by index */
7657 g_assert (index > prev_index);
7661 sprintf (symbol, "unbox_trampolines_end");
7662 emit_info_symbol (acfg, symbol);
7663 emit_int32 (acfg, 0);
7665 /* Emit a separate table with the trampoline addresses/offsets */
7666 sprintf (symbol, "unbox_trampoline_addresses");
7667 emit_section_change (acfg, ".text", 0);
7668 emit_alignment_code (acfg, 8);
7669 emit_info_symbol (acfg, symbol);
7671 for (i = 0; i < acfg->nmethods; ++i) {
7676 cfg = acfg->cfgs [i];
7680 method = cfg->orig_method;
7682 if (mono_aot_mode_is_full (&acfg->aot_opts) && cfg->orig_method->klass->valuetype && !(acfg->aot_opts.llvm_only && cfg->compile_llvm)) {
7683 #ifdef MONO_ARCH_AOT_SUPPORTED
7686 index = get_method_index (acfg, method);
7687 sprintf (symbol, "ut_%d", index);
7689 arch_emit_direct_call (acfg, symbol, FALSE, acfg->thumb_mixed && cfg->compile_llvm, NULL, &call_size);
7693 emit_int32 (acfg, 0);
7697 emit_info (MonoAotCompile *acfg)
7702 offsets = g_new0 (gint32, acfg->nmethods);
7704 for (oindex = 0; oindex < acfg->method_order->len; ++oindex) {
7705 i = GPOINTER_TO_UINT (g_ptr_array_index (acfg->method_order, oindex));
7707 if (acfg->cfgs [i]) {
7708 emit_method_info (acfg, acfg->cfgs [i]);
7709 offsets [i] = acfg->cfgs [i]->method_info_offset;
7715 acfg->stats.offsets_size += emit_offset_table (acfg, "method_info_offsets", acfg->nmethods, 10, offsets);
7720 #endif /* #if !defined(DISABLE_AOT) && !defined(DISABLE_JIT) */
7722 #define rot(x,k) (((x)<<(k)) | ((x)>>(32-(k))))
7723 #define mix(a,b,c) { \
7724 a -= c; a ^= rot(c, 4); c += b; \
7725 b -= a; b ^= rot(a, 6); a += c; \
7726 c -= b; c ^= rot(b, 8); b += a; \
7727 a -= c; a ^= rot(c,16); c += b; \
7728 b -= a; b ^= rot(a,19); a += c; \
7729 c -= b; c ^= rot(b, 4); b += a; \
7731 #define final(a,b,c) { \
7732 c ^= b; c -= rot(b,14); \
7733 a ^= c; a -= rot(c,11); \
7734 b ^= a; b -= rot(a,25); \
7735 c ^= b; c -= rot(b,16); \
7736 a ^= c; a -= rot(c,4); \
7737 b ^= a; b -= rot(a,14); \
7738 c ^= b; c -= rot(b,24); \
7742 mono_aot_type_hash (MonoType *t1)
7744 guint hash = t1->type;
7746 hash |= t1->byref << 6; /* do not collide with t1->type values */
7748 case MONO_TYPE_VALUETYPE:
7749 case MONO_TYPE_CLASS:
7750 case MONO_TYPE_SZARRAY:
7751 /* check if the distribution is good enough */
7752 return ((hash << 5) - hash) ^ mono_metadata_str_hash (t1->data.klass->name);
7754 return ((hash << 5) - hash) ^ mono_metadata_type_hash (t1->data.type);
7755 case MONO_TYPE_ARRAY:
7756 return ((hash << 5) - hash) ^ mono_metadata_type_hash (&t1->data.array->eklass->byval_arg);
7757 case MONO_TYPE_GENERICINST:
7758 return ((hash << 5) - hash) ^ 0;
7765 * mono_aot_method_hash:
7767 * Return a hash code for methods which only depends on metadata.
7770 mono_aot_method_hash (MonoMethod *method)
7772 MonoMethodSignature *sig;
7776 guint32 *hashes_start, *hashes;
7778 MonoGenericInst *class_ginst = NULL;
7779 MonoGenericInst *ginst = NULL;
7781 /* Similar to the hash in mono_method_get_imt_slot () */
7783 sig = mono_method_signature (method);
7785 if (method->klass->generic_class)
7786 class_ginst = method->klass->generic_class->context.class_inst;
7787 if (method->is_inflated)
7788 ginst = ((MonoMethodInflated*)method)->context.method_inst;
7790 hashes_count = sig->param_count + 5 + (class_ginst ? class_ginst->type_argc : 0) + (ginst ? ginst->type_argc : 0);
7791 hashes_start = g_malloc0 (hashes_count * sizeof (guint32));
7792 hashes = hashes_start;
7794 /* Some wrappers are assigned to random classes */
7795 if (!method->wrapper_type || method->wrapper_type == MONO_WRAPPER_REMOTING_INVOKE_WITH_CHECK)
7796 klass = method->klass;
7798 klass = mono_defaults.object_class;
7800 if (!method->wrapper_type) {
7803 if (klass->generic_class)
7804 full_name = mono_type_full_name (&klass->generic_class->container_class->byval_arg);
7806 full_name = mono_type_full_name (&klass->byval_arg);
7808 hashes [0] = mono_metadata_str_hash (full_name);
7812 hashes [0] = mono_metadata_str_hash (klass->name);
7813 hashes [1] = mono_metadata_str_hash (klass->name_space);
7815 if (method->wrapper_type == MONO_WRAPPER_STFLD || method->wrapper_type == MONO_WRAPPER_LDFLD || method->wrapper_type == MONO_WRAPPER_LDFLDA)
7816 /* The method name includes a stringified pointer */
7819 hashes [2] = mono_metadata_str_hash (method->name);
7820 hashes [3] = method->wrapper_type;
7821 hashes [4] = mono_aot_type_hash (sig->ret);
7823 for (i = 0; i < sig->param_count; i++) {
7824 hashes [hindex ++] = mono_aot_type_hash (sig->params [i]);
7827 for (i = 0; i < class_ginst->type_argc; ++i)
7828 hashes [hindex ++] = mono_aot_type_hash (class_ginst->type_argv [i]);
7831 for (i = 0; i < ginst->type_argc; ++i)
7832 hashes [hindex ++] = mono_aot_type_hash (ginst->type_argv [i]);
7834 g_assert (hindex == hashes_count);
7836 /* Setup internal state */
7837 a = b = c = 0xdeadbeef + (((guint32)hashes_count)<<2);
7839 /* Handle most of the hashes */
7840 while (hashes_count > 3) {
7849 /* Handle the last 3 hashes (all the case statements fall through) */
7850 switch (hashes_count) {
7851 case 3 : c += hashes [2];
7852 case 2 : b += hashes [1];
7853 case 1 : a += hashes [0];
7855 case 0: /* nothing left to add */
7859 free (hashes_start);
7868 * mono_aot_get_array_helper_from_wrapper;
7870 * Get the helper method in Array called by an array wrapper method.
7873 mono_aot_get_array_helper_from_wrapper (MonoMethod *method)
7877 MonoGenericContext ctx;
7878 MonoType *args [16];
7879 char *mname, *iname, *s, *s2, *helper_name = NULL;
7881 prefix = "System.Collections.Generic";
7882 s = g_strdup_printf ("%s", method->name + strlen (prefix) + 1);
7883 s2 = strstr (s, "`1.");
7889 //printf ("X: %s %s\n", iname, mname);
7891 if (!strcmp (iname, "IList"))
7892 helper_name = g_strdup_printf ("InternalArray__%s", mname);
7894 helper_name = g_strdup_printf ("InternalArray__%s_%s", iname, mname);
7895 m = mono_class_get_method_from_name (mono_defaults.array_class, helper_name, mono_method_signature (method)->param_count);
7897 g_free (helper_name);
7900 if (m->is_generic) {
7902 memset (&ctx, 0, sizeof (ctx));
7903 args [0] = &method->klass->element_class->byval_arg;
7904 ctx.method_inst = mono_metadata_get_generic_inst (1, args);
7905 m = mono_class_inflate_generic_method_checked (m, &ctx, &error);
7906 g_assert (mono_error_ok (&error)); /* FIXME don't swallow the error */
7912 #if !defined(DISABLE_AOT) && !defined(DISABLE_JIT)
7914 typedef struct HashEntry {
7915 guint32 key, value, index;
7916 struct HashEntry *next;
7920 * emit_extra_methods:
7922 * Emit methods which are not in the METHOD table, like wrappers.
7925 emit_extra_methods (MonoAotCompile *acfg)
7927 int i, table_size, buf_size;
7930 guint32 *info_offsets;
7933 HashEntry *entry, *new_entry;
7934 int nmethods, max_chain_length;
7937 info_offsets = g_new0 (guint32, acfg->extra_methods->len);
7939 /* Emit method info */
7941 for (i = 0; i < acfg->extra_methods->len; ++i) {
7942 MonoMethod *method = g_ptr_array_index (acfg->extra_methods, i);
7943 MonoCompile *cfg = g_hash_table_lookup (acfg->method_to_cfg, method);
7949 p = buf = g_malloc (buf_size);
7953 method = cfg->method_to_register;
7955 encode_method_ref (acfg, method, p, &p);
7957 g_assert ((p - buf) < buf_size);
7959 info_offsets [i] = add_to_blob (acfg, buf, p - buf);
7964 * Construct a chained hash table for mapping indexes in extra_method_info to
7967 table_size = g_spaced_primes_closest ((int)(nmethods * 1.5));
7968 table = g_ptr_array_sized_new (table_size);
7969 for (i = 0; i < table_size; ++i)
7970 g_ptr_array_add (table, NULL);
7971 chain_lengths = g_new0 (int, table_size);
7972 max_chain_length = 0;
7973 for (i = 0; i < acfg->extra_methods->len; ++i) {
7974 MonoMethod *method = g_ptr_array_index (acfg->extra_methods, i);
7975 MonoCompile *cfg = g_hash_table_lookup (acfg->method_to_cfg, method);
7981 key = info_offsets [i];
7982 value = get_method_index (acfg, method);
7984 hash = mono_aot_method_hash (method) % table_size;
7985 //printf ("X: %s %x\n", mono_method_full_name (method, 1), mono_aot_method_hash (method));
7987 chain_lengths [hash] ++;
7988 max_chain_length = MAX (max_chain_length, chain_lengths [hash]);
7990 new_entry = mono_mempool_alloc0 (acfg->mempool, sizeof (HashEntry));
7991 new_entry->key = key;
7992 new_entry->value = value;
7994 entry = g_ptr_array_index (table, hash);
7995 if (entry == NULL) {
7996 new_entry->index = hash;
7997 g_ptr_array_index (table, hash) = new_entry;
8000 entry = entry->next;
8002 entry->next = new_entry;
8003 new_entry->index = table->len;
8004 g_ptr_array_add (table, new_entry);
8008 //printf ("MAX: %d\n", max_chain_length);
8010 buf_size = table->len * 12 + 4;
8011 p = buf = g_malloc (buf_size);
8012 encode_int (table_size, p, &p);
8014 for (i = 0; i < table->len; ++i) {
8015 HashEntry *entry = g_ptr_array_index (table, i);
8017 if (entry == NULL) {
8018 encode_int (0, p, &p);
8019 encode_int (0, p, &p);
8020 encode_int (0, p, &p);
8022 //g_assert (entry->key > 0);
8023 encode_int (entry->key, p, &p);
8024 encode_int (entry->value, p, &p);
8026 encode_int (entry->next->index, p, &p);
8028 encode_int (0, p, &p);
8031 g_assert (p - buf <= buf_size);
8033 /* Emit the table */
8035 mono_llvm_emit_aot_data ("extra_method_table", buf, p - buf);
8037 sprintf (symbol, "extra_method_table");
8038 emit_section_change (acfg, RODATA_SECT, 0);
8039 emit_alignment (acfg, 8);
8040 emit_label (acfg, symbol);
8041 emit_bytes (acfg, buf, p - buf);
8045 * Emit a table reverse mapping method indexes to their index in extra_method_info.
8046 * This is used by mono_aot_find_jit_info ().
8048 buf_size = acfg->extra_methods->len * 8 + 4;
8049 p = buf = g_malloc (buf_size);
8050 encode_int (acfg->extra_methods->len, p, &p);
8051 for (i = 0; i < acfg->extra_methods->len; ++i) {
8052 MonoMethod *method = g_ptr_array_index (acfg->extra_methods, i);
8054 encode_int (get_method_index (acfg, method), p, &p);
8055 encode_int (info_offsets [i], p, &p);
8058 mono_llvm_emit_aot_data ("extra_method_info_offsets", buf, p - buf);
8060 sprintf (symbol, "extra_method_info_offsets");
8061 emit_section_change (acfg, RODATA_SECT, 0);
8062 emit_alignment (acfg, 8);
8063 emit_label (acfg, symbol);
8064 emit_bytes (acfg, buf, p - buf);
8069 emit_exception_info (MonoAotCompile *acfg)
8073 SeqPointData sp_data;
8074 gboolean seq_points_to_file = FALSE;
8076 offsets = g_new0 (gint32, acfg->nmethods);
8077 for (i = 0; i < acfg->nmethods; ++i) {
8078 if (acfg->cfgs [i]) {
8079 MonoCompile *cfg = acfg->cfgs [i];
8081 // By design aot-runtime decode_exception_debug_info is not able to load sequence point debug data from a file.
8082 // As it is not possible to load debug data from a file its is also not possible to store it in a file.
8083 gboolean method_seq_points_to_file = acfg->aot_opts.gen_seq_points_file &&
8084 cfg->gen_seq_points && !cfg->gen_sdb_seq_points;
8085 gboolean method_seq_points_to_binary = cfg->gen_seq_points && !method_seq_points_to_file;
8087 emit_exception_debug_info (acfg, cfg, method_seq_points_to_binary);
8088 offsets [i] = cfg->ex_info_offset;
8090 if (method_seq_points_to_file) {
8091 if (!seq_points_to_file) {
8092 mono_seq_point_data_init (&sp_data, acfg->nmethods);
8093 seq_points_to_file = TRUE;
8095 mono_seq_point_data_add (&sp_data, cfg->method->token, cfg->method_index, cfg->seq_point_info);
8102 if (seq_points_to_file) {
8103 char *seq_points_aot_file;
8104 mono_image_get_aot_seq_point_path (acfg->image, &seq_points_aot_file);
8105 mono_seq_point_data_write (&sp_data, seq_points_aot_file);
8106 mono_seq_point_data_free (&sp_data);
8107 g_free (seq_points_aot_file);
8110 acfg->stats.offsets_size += emit_offset_table (acfg, "ex_info_offsets", acfg->nmethods, 10, offsets);
8115 emit_unwind_info (MonoAotCompile *acfg)
8120 if (!acfg->has_jitted_code) {
8121 g_assert (acfg->unwind_ops->len == 0);
8126 * The unwind info contains a lot of duplicates so we emit each unique
8127 * entry once, and only store the offset from the start of the table in the
8131 sprintf (symbol, "unwind_info");
8132 emit_section_change (acfg, RODATA_SECT, 1);
8133 emit_alignment (acfg, 8);
8134 emit_info_symbol (acfg, symbol);
8136 for (i = 0; i < acfg->unwind_ops->len; ++i) {
8137 guint32 index = GPOINTER_TO_UINT (g_ptr_array_index (acfg->unwind_ops, i));
8138 guint8 *unwind_info;
8139 guint32 unwind_info_len;
8143 unwind_info = mono_get_cached_unwind_info (index, &unwind_info_len);
8146 encode_value (unwind_info_len, p, &p);
8147 emit_bytes (acfg, buf, p - buf);
8148 emit_bytes (acfg, unwind_info, unwind_info_len);
8150 acfg->stats.unwind_info_size += (p - buf) + unwind_info_len;
8155 emit_class_info (MonoAotCompile *acfg)
8160 offsets = g_new0 (gint32, acfg->image->tables [MONO_TABLE_TYPEDEF].rows);
8161 for (i = 0; i < acfg->image->tables [MONO_TABLE_TYPEDEF].rows; ++i)
8162 offsets [i] = emit_klass_info (acfg, MONO_TOKEN_TYPE_DEF | (i + 1));
8164 acfg->stats.offsets_size += emit_offset_table (acfg, "class_info_offsets", acfg->image->tables [MONO_TABLE_TYPEDEF].rows, 10, offsets);
8168 typedef struct ClassNameTableEntry {
8169 guint32 token, index;
8170 struct ClassNameTableEntry *next;
8171 } ClassNameTableEntry;
8174 emit_class_name_table (MonoAotCompile *acfg)
8176 int i, table_size, buf_size;
8177 guint32 token, hash;
8183 ClassNameTableEntry *entry, *new_entry;
8186 * Construct a chained hash table for mapping class names to typedef tokens.
8188 table_size = g_spaced_primes_closest ((int)(acfg->image->tables [MONO_TABLE_TYPEDEF].rows * 1.5));
8189 table = g_ptr_array_sized_new (table_size);
8190 for (i = 0; i < table_size; ++i)
8191 g_ptr_array_add (table, NULL);
8192 for (i = 0; i < acfg->image->tables [MONO_TABLE_TYPEDEF].rows; ++i) {
8194 token = MONO_TOKEN_TYPE_DEF | (i + 1);
8195 klass = mono_class_get_checked (acfg->image, token, &error);
8197 mono_error_cleanup (&error);
8200 full_name = mono_type_get_name_full (mono_class_get_type (klass), MONO_TYPE_NAME_FORMAT_FULL_NAME);
8201 hash = mono_metadata_str_hash (full_name) % table_size;
8204 /* FIXME: Allocate from the mempool */
8205 new_entry = g_new0 (ClassNameTableEntry, 1);
8206 new_entry->token = token;
8208 entry = g_ptr_array_index (table, hash);
8209 if (entry == NULL) {
8210 new_entry->index = hash;
8211 g_ptr_array_index (table, hash) = new_entry;
8214 entry = entry->next;
8216 entry->next = new_entry;
8217 new_entry->index = table->len;
8218 g_ptr_array_add (table, new_entry);
8222 /* Emit the table */
8223 buf_size = table->len * 4 + 4;
8224 p = buf = g_malloc0 (buf_size);
8226 /* FIXME: Optimize memory usage */
8227 g_assert (table_size < 65000);
8228 encode_int16 (table_size, p, &p);
8229 g_assert (table->len < 65000);
8230 for (i = 0; i < table->len; ++i) {
8231 ClassNameTableEntry *entry = g_ptr_array_index (table, i);
8233 if (entry == NULL) {
8234 encode_int16 (0, p, &p);
8235 encode_int16 (0, p, &p);
8237 encode_int16 (mono_metadata_token_index (entry->token), p, &p);
8239 encode_int16 (entry->next->index, p, &p);
8241 encode_int16 (0, p, &p);
8244 g_assert (p - buf <= buf_size);
8247 mono_llvm_emit_aot_data ("class_name_table", buf, p - buf);
8249 sprintf (symbol, "class_name_table");
8250 emit_section_change (acfg, RODATA_SECT, 0);
8251 emit_alignment (acfg, 8);
8252 emit_label (acfg, symbol);
8253 emit_bytes (acfg, buf, p - buf);
8258 emit_image_table (MonoAotCompile *acfg)
8265 * The image table is small but referenced in a lot of places.
8266 * So we emit it at once, and reference its elements by an index.
8268 buf_size = acfg->image_table->len * 28 + 4;
8269 for (i = 0; i < acfg->image_table->len; i++) {
8270 MonoImage *image = (MonoImage*)g_ptr_array_index (acfg->image_table, i);
8271 MonoAssemblyName *aname = &image->assembly->aname;
8273 buf_size += strlen (image->assembly_name) + strlen (image->guid) + (aname->culture ? strlen (aname->culture) : 1) + strlen ((char*)aname->public_key_token) + 4;
8276 buf = p = g_malloc0 (buf_size);
8277 encode_int (acfg->image_table->len, p, &p);
8278 for (i = 0; i < acfg->image_table->len; i++) {
8279 MonoImage *image = (MonoImage*)g_ptr_array_index (acfg->image_table, i);
8280 MonoAssemblyName *aname = &image->assembly->aname;
8282 /* FIXME: Support multi-module assemblies */
8283 g_assert (image->assembly->image == image);
8285 encode_string (image->assembly_name, p, &p);
8286 encode_string (image->guid, p, &p);
8287 encode_string (aname->culture ? aname->culture : "", p, &p);
8288 encode_string ((const char*)aname->public_key_token, p, &p);
8290 while (GPOINTER_TO_UINT (p) % 8 != 0)
8293 encode_int (aname->flags, p, &p);
8294 encode_int (aname->major, p, &p);
8295 encode_int (aname->minor, p, &p);
8296 encode_int (aname->build, p, &p);
8297 encode_int (aname->revision, p, &p);
8299 g_assert (p - buf <= buf_size);
8302 mono_llvm_emit_aot_data ("image_table", buf, p - buf);
8304 sprintf (symbol, "image_table");
8305 emit_section_change (acfg, RODATA_SECT, 1);
8306 emit_alignment (acfg, 8);
8307 emit_label (acfg, symbol);
8308 emit_bytes (acfg, buf, p - buf);
8315 emit_got_info (MonoAotCompile *acfg, gboolean llvm)
8317 int i, first_plt_got_patch = 0, buf_size;
8319 guint32 *got_info_offsets;
8320 GotInfo *info = llvm ? &acfg->llvm_got_info : &acfg->got_info;
8322 /* Add the patches needed by the PLT to the GOT */
8324 acfg->plt_got_offset_base = acfg->got_offset;
8325 first_plt_got_patch = info->got_patches->len;
8326 for (i = 1; i < acfg->plt_offset; ++i) {
8327 MonoPltEntry *plt_entry = g_hash_table_lookup (acfg->plt_offset_to_entry, GUINT_TO_POINTER (i));
8329 g_ptr_array_add (info->got_patches, plt_entry->ji);
8331 acfg->stats.got_slot_types [plt_entry->ji->type] ++;
8334 acfg->got_offset += acfg->plt_offset;
8339 * - optimize offsets table.
8340 * - reduce number of exported symbols.
8341 * - emit info for a klass only once.
8342 * - determine when a method uses a GOT slot which is guaranteed to be already
8344 * - clean up and document the code.
8345 * - use String.Empty in class libs.
8348 /* Encode info required to decode shared GOT entries */
8349 buf_size = info->got_patches->len * 128;
8350 p = buf = mono_mempool_alloc (acfg->mempool, buf_size);
8351 got_info_offsets = mono_mempool_alloc (acfg->mempool, info->got_patches->len * sizeof (guint32));
8353 acfg->plt_got_info_offsets = mono_mempool_alloc (acfg->mempool, acfg->plt_offset * sizeof (guint32));
8355 if (acfg->plt_offset)
8356 acfg->plt_got_info_offsets [0] = 0;
8358 for (i = 0; i < info->got_patches->len; ++i) {
8359 MonoJumpInfo *ji = g_ptr_array_index (info->got_patches, i);
8364 encode_value (ji->type, p, &p);
8366 encode_patch (acfg, ji, p, &p);
8367 acfg->stats.got_slot_info_sizes [ji->type] += p - p2;
8368 g_assert (p - buf <= buf_size);
8369 got_info_offsets [i] = add_to_blob (acfg, buf, p - buf);
8371 if (!llvm && i >= first_plt_got_patch)
8372 acfg->plt_got_info_offsets [i - first_plt_got_patch + 1] = got_info_offsets [i];
8373 acfg->stats.got_info_size += p - buf;
8376 /* Emit got_info_offsets table */
8378 /* No need to emit offsets for the got plt entries, the plt embeds them directly */
8379 acfg->stats.offsets_size += emit_offset_table (acfg, llvm ? "llvm_got_info_offsets" : "got_info_offsets", llvm ? acfg->llvm_got_offset : first_plt_got_patch, 10, (gint32*)got_info_offsets);
8383 emit_got (MonoAotCompile *acfg)
8387 /* Don't make GOT global so accesses to it don't need relocations */
8388 sprintf (symbol, "%s", acfg->got_symbol);
8391 emit_unset_mode (acfg);
8392 fprintf (acfg->fp, ".section __DATA, __bss\n");
8393 emit_alignment (acfg, 8);
8395 emit_info_symbol (acfg, "jit_got");
8396 fprintf (acfg->fp, ".lcomm %s, %d\n", acfg->got_symbol, (int)(acfg->got_offset * sizeof (gpointer)));
8398 emit_section_change (acfg, ".bss", 0);
8399 emit_alignment (acfg, 8);
8400 emit_local_symbol (acfg, symbol, "got_end", FALSE);
8401 emit_label (acfg, symbol);
8403 emit_info_symbol (acfg, "jit_got");
8404 if (acfg->got_offset > 0)
8405 emit_zero_bytes (acfg, (int)(acfg->got_offset * sizeof (gpointer)));
8408 sprintf (symbol, "got_end");
8409 emit_label (acfg, symbol);
8412 typedef struct GlobalsTableEntry {
8413 guint32 value, index;
8414 struct GlobalsTableEntry *next;
8415 } GlobalsTableEntry;
8418 emit_globals (MonoAotCompile *acfg)
8424 GlobalsTableEntry *entry, *new_entry;
8426 if (!acfg->aot_opts.static_link)
8430 * When static linking, we emit a table containing our globals.
8434 * Construct a chained hash table for mapping global names to their index in
8435 * the globals table.
8437 table_size = g_spaced_primes_closest ((int)(acfg->globals->len * 1.5));
8438 table = g_ptr_array_sized_new (table_size);
8439 for (i = 0; i < table_size; ++i)
8440 g_ptr_array_add (table, NULL);
8441 for (i = 0; i < acfg->globals->len; ++i) {
8442 char *name = g_ptr_array_index (acfg->globals, i);
8444 hash = mono_metadata_str_hash (name) % table_size;
8446 /* FIXME: Allocate from the mempool */
8447 new_entry = g_new0 (GlobalsTableEntry, 1);
8448 new_entry->value = i;
8450 entry = g_ptr_array_index (table, hash);
8451 if (entry == NULL) {
8452 new_entry->index = hash;
8453 g_ptr_array_index (table, hash) = new_entry;
8456 entry = entry->next;
8458 entry->next = new_entry;
8459 new_entry->index = table->len;
8460 g_ptr_array_add (table, new_entry);
8464 /* Emit the table */
8465 sprintf (symbol, ".Lglobals_hash");
8466 emit_section_change (acfg, RODATA_SECT, 0);
8467 emit_alignment (acfg, 8);
8468 emit_label (acfg, symbol);
8470 /* FIXME: Optimize memory usage */
8471 g_assert (table_size < 65000);
8472 emit_int16 (acfg, table_size);
8473 for (i = 0; i < table->len; ++i) {
8474 GlobalsTableEntry *entry = g_ptr_array_index (table, i);
8476 if (entry == NULL) {
8477 emit_int16 (acfg, 0);
8478 emit_int16 (acfg, 0);
8480 emit_int16 (acfg, entry->value + 1);
8482 emit_int16 (acfg, entry->next->index);
8484 emit_int16 (acfg, 0);
8488 /* Emit the names */
8489 for (i = 0; i < acfg->globals->len; ++i) {
8490 char *name = g_ptr_array_index (acfg->globals, i);
8492 sprintf (symbol, "name_%d", i);
8493 emit_section_change (acfg, RODATA_SECT, 1);
8495 emit_alignment (acfg, 4);
8497 emit_label (acfg, symbol);
8498 emit_string (acfg, name);
8501 /* Emit the globals table */
8502 sprintf (symbol, "globals");
8503 emit_section_change (acfg, ".data", 0);
8504 /* This is not a global, since it is accessed by the init function */
8505 emit_alignment (acfg, 8);
8506 emit_info_symbol (acfg, symbol);
8508 sprintf (symbol, "%sglobals_hash", acfg->temp_prefix);
8509 emit_pointer (acfg, symbol);
8511 for (i = 0; i < acfg->globals->len; ++i) {
8512 char *name = g_ptr_array_index (acfg->globals, i);
8514 sprintf (symbol, "name_%d", i);
8515 emit_pointer (acfg, symbol);
8517 g_assert (strlen (name) < sizeof (symbol));
8518 sprintf (symbol, "%s", name);
8519 emit_pointer (acfg, symbol);
8521 /* Null terminate the table */
8522 emit_int32 (acfg, 0);
8523 emit_int32 (acfg, 0);
8527 emit_mem_end (MonoAotCompile *acfg)
8531 sprintf (symbol, "mem_end");
8532 emit_section_change (acfg, ".text", 1);
8533 emit_alignment_code (acfg, 8);
8534 emit_label (acfg, symbol);
8538 init_aot_file_info (MonoAotCompile *acfg, MonoAotFileInfo *info, int gc_name_offset)
8542 info->version = MONO_AOT_FILE_VERSION;
8543 info->plt_got_offset_base = acfg->plt_got_offset_base;
8544 info->got_size = acfg->got_offset * sizeof (gpointer);
8545 info->plt_size = acfg->plt_offset;
8546 info->nmethods = acfg->nmethods;
8547 info->flags = acfg->flags;
8548 info->opts = acfg->opts;
8549 info->simd_opts = acfg->simd_opts;
8550 info->gc_name_index = gc_name_offset;
8551 for (i = 0; i < MONO_AOT_TRAMP_NUM; ++i)
8552 info->num_trampolines [i] = acfg->num_trampolines [i];
8553 for (i = 0; i < MONO_AOT_TRAMP_NUM; ++i)
8554 info->trampoline_got_offset_base [i] = acfg->trampoline_got_offset_base [i];
8555 for (i = 0; i < MONO_AOT_TRAMP_NUM; ++i)
8556 info->trampoline_size [i] = acfg->trampoline_size [i];
8557 info->num_rgctx_fetch_trampolines = acfg->aot_opts.nrgctx_fetch_trampolines;
8559 info->double_align = MONO_ABI_ALIGNOF (double);
8560 info->long_align = MONO_ABI_ALIGNOF (gint64);
8561 info->generic_tramp_num = MONO_TRAMPOLINE_NUM;
8562 info->tramp_page_size = acfg->tramp_page_size;
8563 for (i = 0; i < MONO_AOT_TRAMP_NUM; ++i)
8564 info->tramp_page_code_offsets [i] = acfg->tramp_page_code_offsets [i];
8568 emit_aot_file_info (MonoAotCompile *acfg, MonoAotFileInfo *info)
8572 const char **symbols;
8574 symbols = g_new0 (const char *, MONO_AOT_FILE_INFO_NUM_SYMBOLS);
8576 symbols [sindex ++] = acfg->got_symbol;
8578 symbols [sindex ++] = g_strdup_printf ("%s%s", acfg->user_symbol_prefix, acfg->llvm_got_symbol);
8579 symbols [sindex ++] = acfg->llvm_eh_frame_symbol;
8581 symbols [sindex ++] = NULL;
8582 symbols [sindex ++] = NULL;
8584 /* llvm_get_method */
8585 symbols [sindex ++] = NULL;
8586 /* llvm_get_unbox_tramp */
8587 symbols [sindex ++] = NULL;
8588 symbols [sindex ++] = "jit_code_start";
8589 symbols [sindex ++] = "jit_code_end";
8590 symbols [sindex ++] = "method_addresses";
8591 symbols [sindex ++] = "blob";
8592 symbols [sindex ++] = "class_name_table";
8593 symbols [sindex ++] = "class_info_offsets";
8594 symbols [sindex ++] = "method_info_offsets";
8595 symbols [sindex ++] = "ex_info_offsets";
8596 symbols [sindex ++] = "extra_method_info_offsets";
8597 symbols [sindex ++] = "extra_method_table";
8598 symbols [sindex ++] = "got_info_offsets";
8600 symbols [sindex ++] = "llvm_got_info_offsets";
8602 symbols [sindex ++] = NULL;
8603 symbols [sindex ++] = "mem_end";
8604 symbols [sindex ++] = "image_table";
8605 symbols [sindex ++] = "assembly_guid";
8606 symbols [sindex ++] = "runtime_version";
8607 if (acfg->num_trampoline_got_entries) {
8608 symbols [sindex ++] = "specific_trampolines";
8609 symbols [sindex ++] = "static_rgctx_trampolines";
8610 symbols [sindex ++] = "imt_thunks";
8611 symbols [sindex ++] = "gsharedvt_arg_trampolines";
8613 symbols [sindex ++] = NULL;
8614 symbols [sindex ++] = NULL;
8615 symbols [sindex ++] = NULL;
8616 symbols [sindex ++] = NULL;
8618 if (acfg->aot_opts.static_link) {
8619 symbols [sindex ++] = "globals";
8621 symbols [sindex ++] = NULL;
8623 symbols [sindex ++] = "assembly_name";
8624 symbols [sindex ++] = "plt";
8625 symbols [sindex ++] = "plt_end";
8626 symbols [sindex ++] = "unwind_info";
8627 symbols [sindex ++] = "unbox_trampolines";
8628 symbols [sindex ++] = "unbox_trampolines_end";
8629 symbols [sindex ++] = "unbox_trampoline_addresses";
8630 g_assert (sindex == MONO_AOT_FILE_INFO_NUM_SYMBOLS);
8632 sprintf (symbol, "%smono_aot_file_info", acfg->user_symbol_prefix);
8633 emit_section_change (acfg, ".data", 0);
8634 emit_alignment (acfg, 8);
8635 emit_label (acfg, symbol);
8636 if (!acfg->aot_opts.static_link)
8637 emit_global (acfg, symbol, FALSE);
8639 /* The data emitted here must match MonoAotFileInfo. */
8641 emit_int32 (acfg, info->version);
8642 emit_int32 (acfg, info->dummy);
8645 * We emit pointers to our data structures instead of emitting global symbols which
8646 * point to them, to reduce the number of globals, and because using globals leads to
8647 * various problems (i.e. arm/thumb).
8649 for (i = 0; i < MONO_AOT_FILE_INFO_NUM_SYMBOLS; ++i)
8650 emit_pointer (acfg, symbols [i]);
8652 emit_int32 (acfg, info->plt_got_offset_base);
8653 emit_int32 (acfg, info->got_size);
8654 emit_int32 (acfg, info->plt_size);
8655 emit_int32 (acfg, info->nmethods);
8656 emit_int32 (acfg, info->flags);
8657 emit_int32 (acfg, info->opts);
8658 emit_int32 (acfg, info->simd_opts);
8659 emit_int32 (acfg, info->gc_name_index);
8660 emit_int32 (acfg, info->num_rgctx_fetch_trampolines);
8661 emit_int32 (acfg, info->double_align);
8662 emit_int32 (acfg, info->long_align);
8663 emit_int32 (acfg, info->generic_tramp_num);
8664 emit_int32 (acfg, info->tramp_page_size);
8666 for (i = 0; i < MONO_AOT_TRAMP_NUM; ++i)
8667 emit_int32 (acfg, info->num_trampolines [i]);
8668 for (i = 0; i < MONO_AOT_TRAMP_NUM; ++i)
8669 emit_int32 (acfg, info->trampoline_got_offset_base [i]);
8670 for (i = 0; i < MONO_AOT_TRAMP_NUM; ++i)
8671 emit_int32 (acfg, info->trampoline_size [i]);
8672 for (i = 0; i < MONO_AOT_TRAMP_NUM; ++i)
8673 emit_int32 (acfg, info->tramp_page_code_offsets [i]);
8675 if (acfg->aot_opts.static_link) {
8679 * Emit a global symbol which can be passed by an embedding app to
8680 * mono_aot_register_module (). The symbol points to a pointer to the the file info
8683 sprintf (symbol, "%smono_aot_module_%s_info", acfg->user_symbol_prefix, acfg->image->assembly->aname.name);
8685 /* Get rid of characters which cannot occur in symbols */
8687 for (p = symbol; *p; ++p) {
8688 if (!(isalnum (*p) || *p == '_'))
8691 acfg->static_linking_symbol = g_strdup (symbol);
8692 emit_global_inner (acfg, symbol, FALSE);
8693 emit_alignment (acfg, sizeof (gpointer));
8694 emit_label (acfg, symbol);
8695 emit_pointer_2 (acfg, acfg->user_symbol_prefix, "mono_aot_file_info");
8700 * Emit a structure containing all the information not stored elsewhere.
8703 emit_file_info (MonoAotCompile *acfg)
8706 const char *gc_name;
8708 MonoAotFileInfo *info;
8710 if (acfg->aot_opts.bind_to_runtime_version) {
8711 build_info = mono_get_runtime_build_info ();
8712 emit_string_symbol (acfg, "runtime_version", build_info);
8713 g_free (build_info);
8715 emit_string_symbol (acfg, "runtime_version", "");
8718 emit_string_symbol (acfg, "assembly_guid" , acfg->image->guid);
8720 /* Emit a string holding the assembly name */
8721 emit_string_symbol (acfg, "assembly_name", acfg->image->assembly->aname.name);
8724 * The managed allocators are GC specific, so can't use an AOT image created by one GC
8727 gc_name = mono_gc_get_gc_name ();
8728 gc_name_offset = add_to_blob (acfg, (guint8*)gc_name, strlen (gc_name) + 1);
8730 info = g_new0 (MonoAotFileInfo, 1);
8731 init_aot_file_info (acfg, info, gc_name_offset);
8734 mono_llvm_emit_aot_file_info (info, acfg->has_jitted_code);
8736 emit_aot_file_info (acfg, info);
8740 emit_blob (MonoAotCompile *acfg)
8745 mono_llvm_emit_aot_data ("blob", (guint8*)acfg->blob.data, acfg->blob.index);
8749 sprintf (symbol, "blob");
8750 emit_section_change (acfg, RODATA_SECT, 1);
8751 emit_alignment (acfg, 8);
8752 emit_label (acfg, symbol);
8754 emit_bytes (acfg, (guint8*)acfg->blob.data, acfg->blob.index);
8758 emit_objc_selectors (MonoAotCompile *acfg)
8763 if (!acfg->objc_selectors || acfg->objc_selectors->len == 0)
8768 * cat > foo.m << EOF
8771 * return @selector(print:);
8776 mono_img_writer_emit_unset_mode (acfg->w);
8777 g_assert (acfg->fp);
8778 fprintf (acfg->fp, ".section __DATA,__objc_selrefs,literal_pointers,no_dead_strip\n");
8779 fprintf (acfg->fp, ".align 3\n");
8780 for (i = 0; i < acfg->objc_selectors->len; ++i) {
8781 sprintf (symbol, "L_OBJC_SELECTOR_REFERENCES_%d", i);
8782 emit_label (acfg, symbol);
8783 sprintf (symbol, "L_OBJC_METH_VAR_NAME_%d", i);
8784 emit_pointer (acfg, symbol);
8787 fprintf (acfg->fp, ".section __TEXT,__cstring,cstring_literals\n");
8788 for (i = 0; i < acfg->objc_selectors->len; ++i) {
8789 fprintf (acfg->fp, "L_OBJC_METH_VAR_NAME_%d:\n", i);
8790 fprintf (acfg->fp, ".asciz \"%s\"\n", (char*)g_ptr_array_index (acfg->objc_selectors, i));
8793 fprintf (acfg->fp, ".section __DATA,__objc_imageinfo,regular,no_dead_strip\n");
8794 fprintf (acfg->fp, ".align 3\n");
8795 fprintf (acfg->fp, "L_OBJC_IMAGE_INFO:\n");
8796 fprintf (acfg->fp, ".long 0\n");
8797 fprintf (acfg->fp, ".long 16\n");
8801 emit_dwarf_info (MonoAotCompile *acfg)
8803 #ifdef EMIT_DWARF_INFO
8807 /* DIEs for methods */
8808 for (i = 0; i < acfg->nmethods; ++i) {
8809 MonoCompile *cfg = acfg->cfgs [i];
8814 // FIXME: LLVM doesn't define .Lme_...
8815 if (cfg->compile_llvm)
8818 sprintf (symbol2, "%sme_%x", acfg->temp_prefix, i);
8820 mono_dwarf_writer_emit_method (acfg->dwarf, cfg, cfg->method, cfg->asm_symbol, symbol2, cfg->asm_debug_symbol, cfg->jit_info->code_start, cfg->jit_info->code_size, cfg->args, cfg->locals, cfg->unwind_ops, mono_debug_find_method (cfg->jit_info->d.method, mono_domain_get ()));
8826 collect_methods (MonoAotCompile *acfg)
8829 MonoImage *image = acfg->image;
8831 /* Collect methods */
8832 for (i = 0; i < image->tables [MONO_TABLE_METHOD].rows; ++i) {
8835 guint32 token = MONO_TOKEN_METHOD_DEF | (i + 1);
8837 method = mono_get_method_checked (acfg->image, token, NULL, NULL, &error);
8840 aot_printerrf (acfg, "Failed to load method 0x%x from '%s' due to %s.\n", token, image->name, mono_error_get_message (&error));
8841 aot_printerrf (acfg, "Run with MONO_LOG_LEVEL=debug for more information.\n");
8842 mono_error_cleanup (&error);
8846 /* Load all methods eagerly to skip the slower lazy loading code */
8847 mono_class_setup_methods (method->klass);
8849 if (mono_aot_mode_is_full (&acfg->aot_opts) && method->iflags & METHOD_IMPL_ATTRIBUTE_INTERNAL_CALL) {
8850 /* Compile the wrapper instead */
8851 /* We do this here instead of add_wrappers () because it is easy to do it here */
8852 MonoMethod *wrapper = mono_marshal_get_native_wrapper (method, TRUE, TRUE);
8856 /* FIXME: Some mscorlib methods don't have debug info */
8858 if (acfg->aot_opts.soft_debug && !method->wrapper_type) {
8859 if (!((method->flags & METHOD_ATTRIBUTE_PINVOKE_IMPL) ||
8860 (method->iflags & METHOD_IMPL_ATTRIBUTE_RUNTIME) ||
8861 (method->flags & METHOD_ATTRIBUTE_ABSTRACT) ||
8862 (method->iflags & METHOD_IMPL_ATTRIBUTE_INTERNAL_CALL))) {
8863 if (!mono_debug_lookup_method (method)) {
8864 fprintf (stderr, "Method %s has no debug info, probably the .mdb file for the assembly is missing.\n", mono_method_full_name (method, TRUE));
8871 if (method->is_generic || method->klass->generic_container)
8872 /* Compile the ref shared version instead */
8873 method = mini_get_shared_method (method);
8875 /* Since we add the normal methods first, their index will be equal to their zero based token index */
8876 add_method_with_index (acfg, method, i, FALSE);
8877 acfg->method_index ++;
8880 /* gsharedvt methods */
8881 for (mindex = 0; mindex < image->tables [MONO_TABLE_METHOD].rows; ++mindex) {
8884 guint32 token = MONO_TOKEN_METHOD_DEF | (mindex + 1);
8886 if (!(acfg->opts & MONO_OPT_GSHAREDVT))
8889 method = mono_get_method_checked (acfg->image, token, NULL, NULL, &error);
8890 report_loader_error (acfg, &error, "Failed to load method token 0x%x due to %s\n", i, mono_error_get_message (&error));
8892 if (method->is_generic || method->klass->generic_container) {
8893 MonoMethod *gshared;
8895 gshared = mini_get_shared_method_full (method, TRUE, TRUE);
8896 add_extra_method (acfg, gshared);
8900 add_generic_instances (acfg);
8902 if (mono_aot_mode_is_full (&acfg->aot_opts))
8903 add_wrappers (acfg);
8908 compile_methods (MonoAotCompile *acfg)
8912 if (acfg->aot_opts.nthreads > 0) {
8917 gpointer *user_data;
8918 MonoMethod **methods;
8920 methods_len = acfg->methods->len;
8922 len = acfg->methods->len / acfg->aot_opts.nthreads;
8925 * Partition the list of methods into fragments, and hand it to threads to
8928 threads = g_ptr_array_new ();
8929 /* Make a copy since acfg->methods is modified by compile_method () */
8930 methods = g_new0 (MonoMethod*, methods_len);
8931 //memcpy (methods, g_ptr_array_index (acfg->methods, 0), sizeof (MonoMethod*) * methods_len);
8932 for (i = 0; i < methods_len; ++i)
8933 methods [i] = g_ptr_array_index (acfg->methods, i);
8935 while (i < methods_len) {
8936 frag = g_ptr_array_new ();
8937 for (j = 0; j < len; ++j) {
8938 if (i < methods_len) {
8939 g_ptr_array_add (frag, methods [i]);
8944 user_data = g_new0 (gpointer, 3);
8945 user_data [0] = mono_domain_get ();
8946 user_data [1] = acfg;
8947 user_data [2] = frag;
8949 handle = mono_threads_create_thread ((gpointer)compile_thread_main, user_data, 0, 0, NULL);
8950 g_ptr_array_add (threads, handle);
8954 for (i = 0; i < threads->len; ++i) {
8955 WaitForSingleObjectEx (g_ptr_array_index (threads, i), INFINITE, FALSE);
8961 /* Compile methods added by compile_method () or all methods if nthreads == 0 */
8962 for (i = methods_len; i < acfg->methods->len; ++i) {
8963 /* This can new methods to acfg->methods */
8964 compile_method (acfg, g_ptr_array_index (acfg->methods, i));
8969 compile_asm (MonoAotCompile *acfg)
8971 char *command, *objfile;
8972 char *outfile_name, *tmp_outfile_name, *llvm_ofile;
8973 const char *tool_prefix = acfg->aot_opts.tool_prefix ? acfg->aot_opts.tool_prefix : "";
8974 char *ld_flags = acfg->aot_opts.ld_flags ? acfg->aot_opts.ld_flags : g_strdup("");
8976 #if defined(TARGET_AMD64) && !defined(TARGET_MACH)
8977 #define AS_OPTIONS "--64"
8978 #elif defined(TARGET_POWERPC64)
8979 #define AS_OPTIONS "-a64 -mppc64"
8980 #define LD_OPTIONS "-m elf64ppc"
8981 #elif defined(sparc) && SIZEOF_VOID_P == 8
8982 #define AS_OPTIONS "-xarch=v9"
8983 #elif defined(TARGET_X86) && defined(TARGET_MACH) && !defined(__native_client_codegen__)
8984 #define AS_OPTIONS "-arch i386"
8986 #define AS_OPTIONS ""
8989 #ifdef __native_client_codegen__
8990 #if defined(TARGET_AMD64)
8991 #define AS_NAME "nacl64-as"
8993 #define AS_NAME "nacl-as"
8995 #elif defined(TARGET_OSX)
8996 #define AS_NAME "clang"
8998 #define AS_NAME "as"
9002 #define LD_OPTIONS ""
9006 #define LD_NAME "ld -shared -G"
9007 #elif defined(__ppc__) && defined(TARGET_MACH)
9008 #define LD_NAME "gcc -dynamiclib"
9009 #elif defined(TARGET_AMD64) && defined(TARGET_MACH)
9010 #define LD_NAME "clang --shared"
9011 #elif defined(TARGET_WIN32) && !defined(TARGET_ANDROID)
9012 #define LD_NAME "gcc -shared --dll"
9013 #elif defined(TARGET_X86) && defined(TARGET_MACH) && !defined(__native_client_codegen__)
9014 #define LD_NAME "clang -m32 -dynamiclib"
9015 #elif defined(TARGET_ARM) && !defined(TARGET_ANDROID)
9016 #define LD_NAME "gcc --shared"
9019 if (acfg->aot_opts.asm_only) {
9020 aot_printf (acfg, "Output file: '%s'.\n", acfg->tmpfname);
9021 if (acfg->aot_opts.static_link)
9022 aot_printf (acfg, "Linking symbol: '%s'.\n", acfg->static_linking_symbol);
9024 aot_printf (acfg, "LLVM output file: '%s'.\n", acfg->llvm_sfile);
9028 if (acfg->aot_opts.static_link) {
9029 if (acfg->aot_opts.outfile)
9030 objfile = g_strdup_printf ("%s", acfg->aot_opts.outfile);
9032 objfile = g_strdup_printf ("%s.o", acfg->image->name);
9034 objfile = g_strdup_printf ("%s.o", acfg->tmpfname);
9038 g_string_append (acfg->as_args, "-c -x assembler");
9041 command = g_strdup_printf ("\"%s%s\" %s %s -o %s %s", tool_prefix, AS_NAME, AS_OPTIONS, acfg->as_args ? acfg->as_args->str : "", objfile, acfg->tmpfname);
9042 aot_printf (acfg, "Executing the native assembler: %s\n", command);
9043 if (execute_system (command) != 0) {
9049 if (acfg->llvm && !acfg->llvm_owriter) {
9050 command = g_strdup_printf ("\"%s%s\" %s %s -o %s %s", tool_prefix, AS_NAME, AS_OPTIONS, acfg->as_args ? acfg->as_args->str : "", acfg->llvm_ofile, acfg->llvm_sfile);
9051 aot_printf (acfg, "Executing the native assembler: %s\n", command);
9052 if (execute_system (command) != 0) {
9061 if (acfg->aot_opts.static_link) {
9062 aot_printf (acfg, "Output file: '%s'.\n", objfile);
9063 aot_printf (acfg, "Linking symbol: '%s'.\n", acfg->static_linking_symbol);
9068 if (acfg->aot_opts.outfile)
9069 outfile_name = g_strdup_printf ("%s", acfg->aot_opts.outfile);
9071 outfile_name = g_strdup_printf ("%s%s", acfg->image->name, MONO_SOLIB_EXT);
9073 tmp_outfile_name = g_strdup_printf ("%s.tmp", outfile_name);
9076 llvm_ofile = g_strdup_printf ("\"%s\"", acfg->llvm_ofile);
9078 llvm_ofile = g_strdup ("");
9081 /* replace the ; flags separators with spaces */
9082 g_strdelimit (ld_flags, ";", ' ');
9085 command = g_strdup_printf ("%s -o \"%s\" %s \"%s.o\" %s", LD_NAME, tmp_outfile_name, llvm_ofile, acfg->tmpfname, ld_flags);
9087 command = g_strdup_printf ("\"%sld\" %s -shared -o %s %s %s.o %s", tool_prefix, LD_OPTIONS, tmp_outfile_name, llvm_ofile,
9088 acfg->tmpfname, ld_flags);
9090 aot_printf (acfg, "Executing the native linker: %s\n", command);
9091 if (execute_system (command) != 0) {
9092 g_free (tmp_outfile_name);
9093 g_free (outfile_name);
9102 /*com = g_strdup_printf ("strip --strip-unneeded %s%s", acfg->image->name, MONO_SOLIB_EXT);
9103 printf ("Stripping the binary: %s\n", com);
9104 execute_system (com);
9107 #if defined(TARGET_ARM) && !defined(TARGET_MACH)
9109 * gas generates 'mapping symbols' each time code and data is mixed, which
9110 * happens a lot in emit_and_reloc_code (), so we need to get rid of them.
9112 command = g_strdup_printf ("\"%sstrip\" --strip-symbol=\\$a --strip-symbol=\\$d %s", tool_prefix, tmp_outfile_name);
9113 aot_printf (acfg, "Stripping the binary: %s\n", command);
9114 if (execute_system (command) != 0) {
9115 g_free (tmp_outfile_name);
9116 g_free (outfile_name);
9123 rename (tmp_outfile_name, outfile_name);
9125 #if defined(TARGET_MACH)
9126 command = g_strdup_printf ("dsymutil \"%s\"", outfile_name);
9127 aot_printf (acfg, "Executing dsymutil: %s\n", command);
9128 if (execute_system (command) != 0) {
9133 if (!acfg->aot_opts.save_temps)
9136 g_free (tmp_outfile_name);
9137 g_free (outfile_name);
9140 if (acfg->aot_opts.save_temps)
9141 aot_printf (acfg, "Retained input file.\n");
9143 unlink (acfg->tmpfname);
9148 static void init_got_info (GotInfo *info)
9152 info->patch_to_got_offset = g_hash_table_new (mono_patch_info_hash, mono_patch_info_equal);
9153 info->patch_to_got_offset_by_type = g_new0 (GHashTable*, MONO_PATCH_INFO_NUM);
9154 for (i = 0; i < MONO_PATCH_INFO_NUM; ++i)
9155 info->patch_to_got_offset_by_type [i] = g_hash_table_new (mono_patch_info_hash, mono_patch_info_equal);
9156 info->got_patches = g_ptr_array_new ();
9159 static MonoAotCompile*
9160 acfg_create (MonoAssembly *ass, guint32 opts)
9162 MonoImage *image = ass->image;
9163 MonoAotCompile *acfg;
9165 acfg = g_new0 (MonoAotCompile, 1);
9166 acfg->methods = g_ptr_array_new ();
9167 acfg->method_indexes = g_hash_table_new (NULL, NULL);
9168 acfg->method_depth = g_hash_table_new (NULL, NULL);
9169 acfg->plt_offset_to_entry = g_hash_table_new (NULL, NULL);
9170 acfg->patch_to_plt_entry = g_new0 (GHashTable*, MONO_PATCH_INFO_NUM);
9171 acfg->method_to_cfg = g_hash_table_new (NULL, NULL);
9172 acfg->token_info_hash = g_hash_table_new_full (NULL, NULL, NULL, NULL);
9173 acfg->method_to_pinvoke_import = g_hash_table_new_full (NULL, NULL, NULL, g_free);
9174 acfg->image_hash = g_hash_table_new (NULL, NULL);
9175 acfg->image_table = g_ptr_array_new ();
9176 acfg->globals = g_ptr_array_new ();
9177 acfg->image = image;
9179 /* TODO: Write out set of SIMD instructions used, rather than just those available */
9180 acfg->simd_opts = mono_arch_cpu_enumerate_simd_versions ();
9181 acfg->mempool = mono_mempool_new ();
9182 acfg->extra_methods = g_ptr_array_new ();
9183 acfg->unwind_info_offsets = g_hash_table_new (NULL, NULL);
9184 acfg->unwind_ops = g_ptr_array_new ();
9185 acfg->method_label_hash = g_hash_table_new_full (g_str_hash, g_str_equal, g_free, NULL);
9186 acfg->method_order = g_ptr_array_new ();
9187 acfg->export_names = g_hash_table_new (NULL, NULL);
9188 acfg->klass_blob_hash = g_hash_table_new (NULL, NULL);
9189 acfg->method_blob_hash = g_hash_table_new (NULL, NULL);
9190 acfg->plt_entry_debug_sym_cache = g_hash_table_new (g_str_hash, g_str_equal);
9191 mono_mutex_init_recursive (&acfg->mutex);
9193 init_got_info (&acfg->got_info);
9194 init_got_info (&acfg->llvm_got_info);
9200 got_info_free (GotInfo *info)
9204 for (i = 0; i < MONO_PATCH_INFO_NUM; ++i)
9205 g_hash_table_destroy (info->patch_to_got_offset_by_type [i]);
9206 g_free (info->patch_to_got_offset_by_type);
9207 g_hash_table_destroy (info->patch_to_got_offset);
9208 g_ptr_array_free (info->got_patches, TRUE);
9212 acfg_free (MonoAotCompile *acfg)
9216 mono_img_writer_destroy (acfg->w);
9217 for (i = 0; i < acfg->nmethods; ++i)
9219 g_free (acfg->cfgs [i]);
9220 g_free (acfg->cfgs);
9221 g_free (acfg->static_linking_symbol);
9222 g_free (acfg->got_symbol);
9223 g_free (acfg->plt_symbol);
9224 g_ptr_array_free (acfg->methods, TRUE);
9225 g_ptr_array_free (acfg->image_table, TRUE);
9226 g_ptr_array_free (acfg->globals, TRUE);
9227 g_ptr_array_free (acfg->unwind_ops, TRUE);
9228 g_hash_table_destroy (acfg->method_indexes);
9229 g_hash_table_destroy (acfg->method_depth);
9230 g_hash_table_destroy (acfg->plt_offset_to_entry);
9231 for (i = 0; i < MONO_PATCH_INFO_NUM; ++i) {
9232 if (acfg->patch_to_plt_entry [i])
9233 g_hash_table_destroy (acfg->patch_to_plt_entry [i]);
9235 g_free (acfg->patch_to_plt_entry);
9236 g_hash_table_destroy (acfg->method_to_cfg);
9237 g_hash_table_destroy (acfg->token_info_hash);
9238 g_hash_table_destroy (acfg->method_to_pinvoke_import);
9239 g_hash_table_destroy (acfg->image_hash);
9240 g_hash_table_destroy (acfg->unwind_info_offsets);
9241 g_hash_table_destroy (acfg->method_label_hash);
9242 g_hash_table_destroy (acfg->export_names);
9243 g_hash_table_destroy (acfg->plt_entry_debug_sym_cache);
9244 g_hash_table_destroy (acfg->klass_blob_hash);
9245 g_hash_table_destroy (acfg->method_blob_hash);
9246 got_info_free (&acfg->got_info);
9247 got_info_free (&acfg->llvm_got_info);
9248 mono_mempool_destroy (acfg->mempool);
9252 #define WRAPPER(e,n) n,
9253 static const char* const
9254 wrapper_type_names [MONO_WRAPPER_NUM + 1] = {
9255 #include "mono/metadata/wrapper-types.h"
9259 static G_GNUC_UNUSED const char*
9260 get_wrapper_type_name (int type)
9262 return wrapper_type_names [type];
9268 static void aot_dump (MonoAotCompile *acfg)
9274 mono_json_writer_init (&writer);
9276 mono_json_writer_object_begin(&writer);
9279 mono_json_writer_indent (&writer);
9280 mono_json_writer_object_key(&writer, "methods");
9281 mono_json_writer_array_begin (&writer);
9284 for (i = 0; i < acfg->nmethods; ++i) {
9289 cfg = acfg->cfgs [i];
9293 method = cfg->orig_method;
9295 mono_json_writer_indent (&writer);
9296 mono_json_writer_object_begin(&writer);
9298 mono_json_writer_indent (&writer);
9299 mono_json_writer_object_key(&writer, "name");
9300 mono_json_writer_printf (&writer, "\"%s\",\n", method->name);
9302 mono_json_writer_indent (&writer);
9303 mono_json_writer_object_key(&writer, "signature");
9304 mono_json_writer_printf (&writer, "\"%s\",\n", mono_method_full_name (method,
9305 /*signature=*/TRUE));
9307 mono_json_writer_indent (&writer);
9308 mono_json_writer_object_key(&writer, "code_size");
9309 mono_json_writer_printf (&writer, "\"%d\",\n", cfg->code_size);
9311 klass = method->klass;
9313 mono_json_writer_indent (&writer);
9314 mono_json_writer_object_key(&writer, "class");
9315 mono_json_writer_printf (&writer, "\"%s\",\n", klass->name);
9317 mono_json_writer_indent (&writer);
9318 mono_json_writer_object_key(&writer, "namespace");
9319 mono_json_writer_printf (&writer, "\"%s\",\n", klass->name_space);
9321 mono_json_writer_indent (&writer);
9322 mono_json_writer_object_key(&writer, "wrapper_type");
9323 mono_json_writer_printf (&writer, "\"%s\",\n", get_wrapper_type_name(method->wrapper_type));
9325 mono_json_writer_indent_pop (&writer);
9326 mono_json_writer_indent (&writer);
9327 mono_json_writer_object_end (&writer);
9328 mono_json_writer_printf (&writer, ",\n");
9331 mono_json_writer_indent_pop (&writer);
9332 mono_json_writer_indent (&writer);
9333 mono_json_writer_array_end (&writer);
9334 mono_json_writer_printf (&writer, ",\n");
9338 mono_json_writer_indent_push (&writer);
9339 mono_json_writer_indent (&writer);
9340 mono_json_writer_object_key(&writer, "plt");
9341 mono_json_writer_array_begin (&writer);
9343 for (i = 0; i < acfg->plt_offset; ++i) {
9344 MonoPltEntry *plt_entry = NULL;
9349 * The first plt entry is unused.
9353 plt_entry = g_hash_table_lookup (acfg->plt_offset_to_entry, GUINT_TO_POINTER (i));
9356 mono_json_writer_indent (&writer);
9357 mono_json_writer_printf (&writer, "{ ");
9358 mono_json_writer_object_key(&writer, "symbol");
9359 mono_json_writer_printf (&writer, "\"%s\" },\n", plt_entry->symbol);
9362 mono_json_writer_indent_pop (&writer);
9363 mono_json_writer_indent (&writer);
9364 mono_json_writer_array_end (&writer);
9365 mono_json_writer_printf (&writer, ",\n");
9370 mono_json_writer_indent_push (&writer);
9371 mono_json_writer_indent (&writer);
9372 mono_json_writer_object_key(&writer, "got");
9373 mono_json_writer_array_begin (&writer);
9375 mono_json_writer_indent_push (&writer);
9376 for (i = 0; i < acfg->got_info.got_patches->len; ++i) {
9377 MonoJumpInfo *ji = g_ptr_array_index (acfg->got_info.got_patches, i);
9379 mono_json_writer_indent (&writer);
9380 mono_json_writer_printf (&writer, "{ ");
9381 mono_json_writer_object_key(&writer, "patch_name");
9382 mono_json_writer_printf (&writer, "\"%s\" },\n", get_patch_name (ji->type));
9385 mono_json_writer_indent_pop (&writer);
9386 mono_json_writer_indent (&writer);
9387 mono_json_writer_array_end (&writer);
9388 mono_json_writer_printf (&writer, ",\n");
9391 mono_json_writer_indent_pop (&writer);
9392 mono_json_writer_indent (&writer);
9393 mono_json_writer_object_end (&writer);
9395 dumpname = g_strdup_printf ("%s.json", g_path_get_basename (acfg->image->name));
9396 dumpfile = fopen (dumpname, "w+");
9399 fprintf (dumpfile, "%s", writer.text->str);
9402 mono_json_writer_destroy (&writer);
9406 mono_compile_assembly (MonoAssembly *ass, guint32 opts, const char *aot_options)
9408 MonoImage *image = ass->image;
9411 MonoAotCompile *acfg;
9412 char *outfile_name, *tmp_outfile_name, *p;
9413 char llvm_stats_msg [256];
9417 acfg = acfg_create (ass, opts);
9419 memset (&acfg->aot_opts, 0, sizeof (acfg->aot_opts));
9420 acfg->aot_opts.write_symbols = TRUE;
9421 acfg->aot_opts.ntrampolines = 1024;
9422 acfg->aot_opts.nrgctx_trampolines = 1024;
9423 acfg->aot_opts.nimt_trampolines = 128;
9424 acfg->aot_opts.nrgctx_fetch_trampolines = 128;
9425 acfg->aot_opts.ngsharedvt_arg_trampolines = 128;
9426 acfg->aot_opts.llvm_path = g_strdup ("");
9427 acfg->aot_opts.temp_path = g_strdup ("");
9429 acfg->aot_opts.use_trampolines_page = TRUE;
9432 mono_aot_parse_options (aot_options, &acfg->aot_opts);
9434 if (acfg->aot_opts.logfile) {
9435 acfg->logfile = fopen (acfg->aot_opts.logfile, "a+");
9438 //acfg->aot_opts.print_skipped_methods = TRUE;
9440 #if !defined(MONO_ARCH_GSHAREDVT_SUPPORTED) || !defined(ENABLE_GSHAREDVT)
9441 if (opts & MONO_OPT_GSHAREDVT) {
9442 aot_printerrf (acfg, "-O=gsharedvt not supported on this platform.\n");
9447 aot_printf (acfg, "Mono Ahead of Time compiler - compiling assembly %s\n", image->name);
9449 #ifndef MONO_ARCH_HAVE_FULL_AOT_TRAMPOLINES
9450 if (mono_aot_mode_is_full (&acfg->aot_opts)) {
9451 aot_printerrf (acfg, "--aot=full is not supported on this platform.\n");
9456 if (acfg->aot_opts.direct_pinvoke && !acfg->aot_opts.static_link) {
9457 aot_printerrf (acfg, "The 'direct-pinvoke' AOT option also requires the 'static' AOT option.\n");
9461 if (acfg->aot_opts.static_link)
9462 acfg->aot_opts.asm_writer = TRUE;
9464 if (acfg->aot_opts.soft_debug) {
9465 MonoDebugOptions *opt = mini_get_debug_options ();
9467 opt->mdb_optimizations = TRUE;
9468 opt->gen_sdb_seq_points = TRUE;
9470 if (!mono_debug_enabled ()) {
9471 aot_printerrf (acfg, "The soft-debug AOT option requires the --debug option.\n");
9474 acfg->flags |= MONO_AOT_FILE_FLAG_DEBUG;
9477 if (mono_use_llvm || acfg->aot_opts.llvm) {
9479 acfg->aot_opts.asm_writer = TRUE;
9480 acfg->flags |= MONO_AOT_FILE_FLAG_WITH_LLVM;
9482 if (acfg->aot_opts.soft_debug) {
9483 aot_printerrf (acfg, "The 'soft-debug' option is not supported when compiling with LLVM.\n");
9489 if (acfg->aot_opts.asm_only && !acfg->aot_opts.llvm_outfile) {
9490 aot_printerrf (acfg, "Compiling with LLVM and the asm-only option requires the llvm-outputfile= option.");
9495 * Emit all LLVM code into a separate assembly/object file and link with it
9498 if (!acfg->aot_opts.asm_only) {
9499 acfg->llvm_owriter = TRUE;
9500 } else if (acfg->aot_opts.llvm_outfile) {
9501 int len = strlen (acfg->aot_opts.llvm_outfile);
9503 if (len >= 2 && acfg->aot_opts.llvm_outfile [len - 2] == '.' && acfg->aot_opts.llvm_outfile [len - 1] == 'o')
9504 acfg->llvm_owriter = TRUE;
9508 if (mono_aot_mode_is_full (&acfg->aot_opts))
9509 acfg->flags |= MONO_AOT_FILE_FLAG_FULL_AOT;
9511 if (acfg->aot_opts.instances_logfile_path) {
9512 acfg->instances_logfile = fopen (acfg->aot_opts.instances_logfile_path, "w");
9513 if (!acfg->instances_logfile) {
9514 aot_printerrf (acfg, "Unable to create logfile: '%s'.\n", acfg->aot_opts.instances_logfile_path);
9519 load_profile_files (acfg);
9521 acfg->num_trampolines [MONO_AOT_TRAMP_SPECIFIC] = mono_aot_mode_is_full (&acfg->aot_opts) ? acfg->aot_opts.ntrampolines : 0;
9522 #ifdef MONO_ARCH_GSHARED_SUPPORTED
9523 acfg->num_trampolines [MONO_AOT_TRAMP_STATIC_RGCTX] = mono_aot_mode_is_full (&acfg->aot_opts) ? acfg->aot_opts.nrgctx_trampolines : 0;
9525 acfg->num_trampolines [MONO_AOT_TRAMP_IMT_THUNK] = mono_aot_mode_is_full (&acfg->aot_opts) ? acfg->aot_opts.nimt_trampolines : 0;
9526 #ifdef MONO_ARCH_GSHAREDVT_SUPPORTED
9527 if (acfg->opts & MONO_OPT_GSHAREDVT)
9528 acfg->num_trampolines [MONO_AOT_TRAMP_GSHAREDVT_ARG] = mono_aot_mode_is_full (&acfg->aot_opts) ? acfg->aot_opts.ngsharedvt_arg_trampolines : 0;
9531 acfg->temp_prefix = mono_img_writer_get_temp_label_prefix (NULL);
9535 if (acfg->llvm && acfg->thumb_mixed)
9536 acfg->flags |= MONO_AOT_FILE_FLAG_LLVM_THUMB;
9537 if (acfg->aot_opts.llvm_only)
9538 acfg->flags |= MONO_AOT_FILE_FLAG_LLVM_ONLY;
9540 acfg->assembly_name_sym = g_strdup (acfg->image->assembly->aname.name);
9541 /* Get rid of characters which cannot occur in symbols */
9542 for (p = acfg->assembly_name_sym; *p; ++p) {
9543 if (!(isalnum (*p) || *p == '_'))
9547 acfg->global_prefix = g_strdup_printf ("mono_aot_%s", acfg->assembly_name_sym);
9548 acfg->plt_symbol = g_strdup_printf ("%s_plt", acfg->global_prefix);
9549 acfg->got_symbol = g_strdup_printf ("%s_got", acfg->global_prefix);
9551 acfg->llvm_got_symbol = g_strdup_printf ("%s_llvm_got", acfg->global_prefix);
9552 acfg->llvm_eh_frame_symbol = g_strdup_printf ("%s_eh_frame", acfg->global_prefix);
9555 acfg->method_index = 1;
9557 if (mono_aot_mode_is_full (&acfg->aot_opts))
9558 mono_set_partial_sharing_supported (TRUE);
9560 res = collect_methods (acfg);
9564 acfg->cfgs_size = acfg->methods->len + 32;
9565 acfg->cfgs = g_new0 (MonoCompile*, acfg->cfgs_size);
9567 /* PLT offset 0 is reserved for the PLT trampoline */
9568 acfg->plt_offset = 1;
9573 mono_llvm_create_aot_module (acfg->image->assembly, acfg->global_prefix, TRUE, acfg->aot_opts.static_link, acfg->aot_opts.llvm_only);
9581 ji = mono_mempool_alloc0 (acfg->mempool, sizeof (MonoJumpInfo));
9582 ji->type = MONO_PATCH_INFO_IMAGE;
9583 ji->data.image = acfg->image;
9584 get_got_offset (acfg, FALSE, ji);
9585 get_got_offset (acfg, TRUE, ji);
9588 ji = mono_mempool_alloc0 (acfg->mempool, sizeof (MonoJumpInfo));
9589 ji->type = MONO_PATCH_INFO_MSCORLIB_GOT_ADDR;
9590 get_got_offset (acfg, FALSE, ji);
9591 get_got_offset (acfg, TRUE, ji);
9594 ji = mono_mempool_alloc0 (acfg->mempool, sizeof (MonoJumpInfo));
9595 ji->type = MONO_PATCH_INFO_GC_CARD_TABLE_ADDR;
9596 get_got_offset (acfg, FALSE, ji);
9597 get_got_offset (acfg, TRUE, ji);
9600 ji = mono_mempool_alloc0 (acfg->mempool, sizeof (MonoJumpInfo));
9601 ji->type = MONO_PATCH_INFO_GC_NURSERY_START;
9602 get_got_offset (acfg, FALSE, ji);
9603 get_got_offset (acfg, TRUE, ji);
9606 ji = mono_mempool_alloc0 (acfg->mempool, sizeof (MonoJumpInfo));
9607 ji->type = MONO_PATCH_INFO_JIT_TLS_ID;
9608 get_got_offset (acfg, FALSE, ji);
9609 get_got_offset (acfg, TRUE, ji);
9612 ji = mono_mempool_alloc0 (acfg->mempool, sizeof (MonoJumpInfo));
9613 ji->type = MONO_PATCH_INFO_AOT_MODULE;
9614 get_got_offset (acfg, FALSE, ji);
9615 get_got_offset (acfg, TRUE, ji);
9618 ji = mono_mempool_alloc0 (acfg->mempool, sizeof (MonoAotCompile));
9619 ji->type = MONO_PATCH_INFO_INTERNAL_METHOD;
9620 ji->data.name = "mono_aot_init_llvm_method";
9621 get_got_offset (acfg, FALSE, ji);
9622 get_got_offset (acfg, TRUE, ji);
9625 ji = mono_mempool_alloc0 (acfg->mempool, sizeof (MonoAotCompile));
9626 ji->type = MONO_PATCH_INFO_INTERNAL_METHOD;
9627 ji->data.name = "mono_aot_init_gshared_method_this";
9628 get_got_offset (acfg, FALSE, ji);
9629 get_got_offset (acfg, TRUE, ji);
9632 ji = mono_mempool_alloc0 (acfg->mempool, sizeof (MonoAotCompile));
9633 ji->type = MONO_PATCH_INFO_INTERNAL_METHOD;
9634 ji->data.name = "mono_aot_init_gshared_method_rgctx";
9635 get_got_offset (acfg, FALSE, ji);
9636 get_got_offset (acfg, TRUE, ji);
9641 compile_methods (acfg);
9645 acfg->stats.jit_time = TV_ELAPSED (atv, btv);
9651 if (acfg->aot_opts.asm_only) {
9652 if (acfg->aot_opts.outfile) {
9653 acfg->tmpfname = g_strdup_printf ("%s", acfg->aot_opts.outfile);
9654 acfg->tmpbasename = g_strdup (acfg->tmpfname);
9656 acfg->tmpbasename = g_strdup_printf ("%s", acfg->image->name);
9657 acfg->tmpfname = g_strdup_printf ("%s.s", acfg->tmpbasename);
9659 g_assert (acfg->aot_opts.llvm_outfile);
9660 acfg->llvm_sfile = g_strdup (acfg->aot_opts.llvm_outfile);
9661 if (acfg->llvm_owriter)
9662 acfg->llvm_ofile = g_strdup (acfg->aot_opts.llvm_outfile);
9664 acfg->llvm_sfile = g_strdup (acfg->aot_opts.llvm_outfile);
9666 acfg->tmpbasename = (strcmp (acfg->aot_opts.temp_path, "") == 0) ?
9667 g_strdup_printf ("%s", "temp") :
9668 g_build_filename (acfg->aot_opts.temp_path, "temp", NULL);
9670 acfg->tmpfname = g_strdup_printf ("%s.s", acfg->tmpbasename);
9671 acfg->llvm_sfile = g_strdup_printf ("%s-llvm.s", acfg->tmpbasename);
9672 acfg->llvm_ofile = g_strdup_printf ("%s-llvm.o", acfg->tmpbasename);
9677 if (acfg->aot_opts.asm_only) {
9678 if (acfg->aot_opts.outfile)
9679 acfg->tmpfname = g_strdup_printf ("%s", acfg->aot_opts.outfile);
9681 acfg->tmpfname = g_strdup_printf ("%s.s", acfg->image->name);
9682 acfg->fp = fopen (acfg->tmpfname, "w+");
9684 int i = g_file_open_tmp ("mono_aot_XXXXXX", &acfg->tmpfname, NULL);
9685 acfg->fp = fdopen (i, "w+");
9687 if (acfg->fp == 0) {
9688 aot_printerrf (acfg, "Unable to open file '%s': %s\n", acfg->tmpfname, strerror (errno));
9691 acfg->w = mono_img_writer_create (acfg->fp, FALSE);
9693 tmp_outfile_name = NULL;
9694 outfile_name = NULL;
9696 /* Compute symbols for methods */
9697 for (i = 0; i < acfg->nmethods; ++i) {
9698 if (acfg->cfgs [i]) {
9699 MonoCompile *cfg = acfg->cfgs [i];
9700 int method_index = get_method_index (acfg, cfg->orig_method);
9702 if (COMPILE_LLVM (cfg))
9703 cfg->asm_symbol = g_strdup_printf ("%s%s", acfg->llvm_label_prefix, cfg->llvm_method_name);
9704 else if (acfg->global_symbols || acfg->llvm)
9705 cfg->asm_symbol = get_debug_sym (cfg->orig_method, "", acfg->method_label_hash);
9707 cfg->asm_symbol = g_strdup_printf ("%s%sm_%x", acfg->temp_prefix, acfg->llvm_label_prefix, method_index);
9708 cfg->asm_debug_symbol = cfg->asm_symbol;
9712 if (acfg->aot_opts.dwarf_debug && acfg->aot_opts.asm_only && acfg->aot_opts.gnu_asm) {
9714 * CLANG supports GAS .file/.loc directives, so emit line number information this way
9715 * FIXME: CLANG only emits line number info for .loc directives followed by assembly, not
9718 //acfg->gas_line_numbers = TRUE;
9721 if ((!acfg->aot_opts.nodebug || acfg->aot_opts.dwarf_debug) && acfg->has_jitted_code) {
9722 if (acfg->aot_opts.dwarf_debug && !mono_debug_enabled ()) {
9723 aot_printerrf (acfg, "The dwarf AOT option requires the --debug option.\n");
9726 acfg->dwarf = mono_dwarf_writer_create (acfg->w, NULL, 0, FALSE, !acfg->gas_line_numbers);
9729 mono_img_writer_emit_start (acfg->w);
9732 mono_dwarf_writer_emit_base_info (acfg->dwarf, g_path_get_basename (acfg->image->name), mono_unwind_get_cie_program ());
9738 emit_extra_methods (acfg);
9740 emit_trampolines (acfg);
9742 emit_class_name_table (acfg);
9744 emit_got_info (acfg, FALSE);
9746 emit_got_info (acfg, TRUE);
9748 emit_exception_info (acfg);
9750 emit_unwind_info (acfg);
9752 emit_class_info (acfg);
9756 emit_image_table (acfg);
9760 emit_file_info (acfg);
9764 emit_objc_selectors (acfg);
9766 emit_globals (acfg);
9769 emit_dwarf_info (acfg);
9770 mono_dwarf_writer_close (acfg->dwarf);
9773 emit_mem_end (acfg);
9775 if (acfg->need_pt_gnu_stack) {
9776 /* This is required so the .so doesn't have an executable stack */
9777 /* The bin writer already emits this */
9778 fprintf (acfg->fp, "\n.section .note.GNU-stack,\"\",@progbits\n");
9785 res = emit_llvm_file (acfg);
9793 acfg->stats.gen_time = TV_ELAPSED (atv, btv);
9796 sprintf (llvm_stats_msg, ", LLVM: %d (%d%%)", acfg->stats.llvm_count, acfg->stats.mcount ? (acfg->stats.llvm_count * 100) / acfg->stats.mcount : 100);
9798 strcpy (llvm_stats_msg, "");
9800 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;
9802 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",
9803 (int)acfg->stats.code_size, (int)(acfg->stats.code_size * 100 / all_sizes),
9804 (int)acfg->stats.info_size, (int)(acfg->stats.info_size * 100 / all_sizes),
9805 (int)acfg->stats.ex_info_size, (int)(acfg->stats.ex_info_size * 100 / all_sizes),
9806 (int)acfg->stats.unwind_info_size, (int)(acfg->stats.unwind_info_size * 100 / all_sizes),
9807 (int)acfg->stats.class_info_size, (int)(acfg->stats.class_info_size * 100 / all_sizes),
9808 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,
9809 (int)acfg->stats.got_info_size, (int)(acfg->stats.got_info_size * 100 / all_sizes),
9810 (int)acfg->stats.offsets_size, (int)(acfg->stats.offsets_size * 100 / all_sizes),
9811 (int)(acfg->got_offset * sizeof (gpointer)));
9812 aot_printf (acfg, "Compiled: %d/%d (%d%%)%s, No GOT slots: %d (%d%%), Direct calls: %d (%d%%)\n",
9813 acfg->stats.ccount, acfg->stats.mcount, acfg->stats.mcount ? (acfg->stats.ccount * 100) / acfg->stats.mcount : 100,
9815 acfg->stats.methods_without_got_slots, acfg->stats.mcount ? (acfg->stats.methods_without_got_slots * 100) / acfg->stats.mcount : 100,
9816 acfg->stats.direct_calls, acfg->stats.all_calls ? (acfg->stats.direct_calls * 100) / acfg->stats.all_calls : 100);
9817 if (acfg->stats.genericcount)
9818 aot_printf (acfg, "%d methods are generic (%d%%)\n", acfg->stats.genericcount, acfg->stats.mcount ? (acfg->stats.genericcount * 100) / acfg->stats.mcount : 100);
9819 if (acfg->stats.abscount)
9820 aot_printf (acfg, "%d methods contain absolute addresses (%d%%)\n", acfg->stats.abscount, acfg->stats.mcount ? (acfg->stats.abscount * 100) / acfg->stats.mcount : 100);
9821 if (acfg->stats.lmfcount)
9822 aot_printf (acfg, "%d methods contain lmf pointers (%d%%)\n", acfg->stats.lmfcount, acfg->stats.mcount ? (acfg->stats.lmfcount * 100) / acfg->stats.mcount : 100);
9823 if (acfg->stats.ocount)
9824 aot_printf (acfg, "%d methods have other problems (%d%%)\n", acfg->stats.ocount, acfg->stats.mcount ? (acfg->stats.ocount * 100) / acfg->stats.mcount : 100);
9827 res = mono_img_writer_emit_writeout (acfg->w);
9832 res = compile_asm (acfg);
9838 acfg->stats.link_time = TV_ELAPSED (atv, btv);
9840 if (acfg->aot_opts.stats) {
9843 aot_printf (acfg, "GOT slot distribution:\n");
9844 for (i = 0; i < MONO_PATCH_INFO_NONE; ++i)
9845 if (acfg->stats.got_slot_types [i])
9846 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]);
9849 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);
9851 if (acfg->aot_opts.dump_json)
9864 mono_aot_readonly_field_override (MonoClassField *field)
9870 mono_compile_assembly (MonoAssembly *ass, guint32 opts, const char *aot_options)