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;
121 int nrgctx_trampolines;
122 int nimt_trampolines;
123 int ngsharedvt_arg_trampolines;
124 int nrgctx_fetch_trampolines;
125 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 use_bin_writer;
201 gboolean gas_line_numbers;
202 /* Whenever to emit an object file directly from llc */
203 gboolean llvm_owriter;
205 MonoDwarfWriter *dwarf;
212 GHashTable *unwind_info_offsets;
213 GPtrArray *unwind_ops;
214 guint32 unwind_info_offset;
217 char *llvm_got_symbol;
219 char *llvm_eh_frame_symbol;
220 GHashTable *method_label_hash;
221 const char *temp_prefix;
222 const char *user_symbol_prefix;
223 const char *llvm_label_prefix;
224 const char *inst_directive;
226 guint32 label_generator;
228 gboolean has_jitted_code;
229 MonoAotFileFlags flags;
230 MonoDynamicStream blob;
231 MonoClass **typespec_classes;
234 char *assembly_name_sym;
235 GHashTable *plt_entry_debug_sym_cache;
236 gboolean thumb_mixed, need_no_dead_strip, need_pt_gnu_stack;
237 GHashTable *ginst_hash;
238 GHashTable *dwarf_ln_filenames;
239 gboolean global_symbols;
240 int objc_selector_index, objc_selector_index_2;
241 GPtrArray *objc_selectors;
242 GHashTable *objc_selector_to_index;
244 FILE *instances_logfile;
249 char *symbol, *llvm_symbol, *debug_sym;
251 gboolean jit_used, llvm_used;
254 #define mono_acfg_lock(acfg) mono_mutex_lock (&((acfg)->mutex))
255 #define mono_acfg_unlock(acfg) mono_mutex_unlock (&((acfg)->mutex))
257 /* This points to the current acfg in LLVM mode */
258 static MonoAotCompile *llvm_acfg;
260 #ifdef HAVE_ARRAY_ELEM_INIT
261 #define MSGSTRFIELD(line) MSGSTRFIELD1(line)
262 #define MSGSTRFIELD1(line) str##line
263 static const struct msgstr_t {
264 #define PATCH_INFO(a,b) char MSGSTRFIELD(__LINE__) [sizeof (b)];
265 #include "patch-info.h"
268 #define PATCH_INFO(a,b) b,
269 #include "patch-info.h"
272 static const gint16 opidx [] = {
273 #define PATCH_INFO(a,b) [MONO_PATCH_INFO_ ## a] = offsetof (struct msgstr_t, MSGSTRFIELD(__LINE__)),
274 #include "patch-info.h"
278 static G_GNUC_UNUSED const char*
279 get_patch_name (int info)
281 return (const char*)&opstr + opidx [info];
285 #define PATCH_INFO(a,b) b,
286 static const char* const
287 patch_types [MONO_PATCH_INFO_NUM + 1] = {
288 #include "patch-info.h"
292 static G_GNUC_UNUSED const char*
293 get_patch_name (int info)
295 return patch_types [info];
301 get_unwind_info_offset (MonoAotCompile *acfg, guint8 *encoded, guint32 encoded_len);
304 get_plt_entry_debug_sym (MonoAotCompile *acfg, MonoJumpInfo *ji, GHashTable *cache);
307 aot_printf (MonoAotCompile *acfg, const gchar *format, ...)
313 output = acfg->logfile;
317 va_start (args, format);
318 vfprintf (output, format, args);
323 aot_printerrf (MonoAotCompile *acfg, const gchar *format, ...)
329 output = acfg->logfile;
333 va_start (args, format);
334 vfprintf (output, format, args);
339 report_loader_error (MonoAotCompile *acfg, MonoError *error, const char *format, ...)
344 if (mono_error_ok (error))
348 output = acfg->logfile;
352 va_start (args, format);
353 vfprintf (output, format, args);
355 mono_error_cleanup (error);
357 g_error ("FullAOT cannot continue if there are loader errors");
360 /* Wrappers around the image writer functions */
363 emit_section_change (MonoAotCompile *acfg, const char *section_name, int subsection_index)
365 mono_img_writer_emit_section_change (acfg->w, section_name, subsection_index);
369 emit_local_symbol (MonoAotCompile *acfg, const char *name, const char *end_label, gboolean func)
371 mono_img_writer_emit_local_symbol (acfg->w, name, end_label, func);
375 emit_label (MonoAotCompile *acfg, const char *name)
377 mono_img_writer_emit_label (acfg->w, name);
381 emit_bytes (MonoAotCompile *acfg, const guint8* buf, int size)
383 mono_img_writer_emit_bytes (acfg->w, buf, size);
387 emit_string (MonoAotCompile *acfg, const char *value)
389 mono_img_writer_emit_string (acfg->w, value);
393 emit_line (MonoAotCompile *acfg)
395 mono_img_writer_emit_line (acfg->w);
399 emit_alignment (MonoAotCompile *acfg, int size)
401 mono_img_writer_emit_alignment (acfg->w, size);
405 emit_alignment_code (MonoAotCompile *acfg, int size)
407 if (acfg->align_pad_value)
408 mono_img_writer_emit_alignment_fill (acfg->w, size, acfg->align_pad_value);
410 mono_img_writer_emit_alignment (acfg->w, size);
414 emit_padding (MonoAotCompile *acfg, int size)
419 if (acfg->align_pad_value) {
420 for (i = 0; i < 16; ++i)
421 buf [i] = acfg->align_pad_value;
423 memset (buf, 0, sizeof (buf));
426 for (i = 0; i < size; i += 16) {
428 emit_bytes (acfg, buf, size - i);
430 emit_bytes (acfg, buf, 16);
435 emit_pointer (MonoAotCompile *acfg, const char *target)
437 mono_img_writer_emit_pointer (acfg->w, target);
441 emit_pointer_2 (MonoAotCompile *acfg, const char *prefix, const char *target)
443 if (prefix [0] != '\0') {
444 char *s = g_strdup_printf ("%s%s", prefix, target);
445 mono_img_writer_emit_pointer (acfg->w, s);
448 mono_img_writer_emit_pointer (acfg->w, target);
453 emit_int16 (MonoAotCompile *acfg, int value)
455 mono_img_writer_emit_int16 (acfg->w, value);
459 emit_int32 (MonoAotCompile *acfg, int value)
461 mono_img_writer_emit_int32 (acfg->w, value);
465 emit_symbol_diff (MonoAotCompile *acfg, const char *end, const char* start, int offset)
467 mono_img_writer_emit_symbol_diff (acfg->w, end, start, offset);
471 emit_zero_bytes (MonoAotCompile *acfg, int num)
473 mono_img_writer_emit_zero_bytes (acfg->w, num);
477 emit_byte (MonoAotCompile *acfg, guint8 val)
479 mono_img_writer_emit_byte (acfg->w, val);
482 #ifdef __native_client_codegen__
484 emit_nacl_call_alignment (MonoAotCompile *acfg)
486 mono_img_writer_emit_nacl_call_alignment (acfg->w);
490 static G_GNUC_UNUSED void
491 emit_global_inner (MonoAotCompile *acfg, const char *name, gboolean func)
493 mono_img_writer_emit_global (acfg->w, name, func);
497 emit_global (MonoAotCompile *acfg, const char *name, gboolean func)
499 if (acfg->aot_opts.no_dlsym) {
500 g_ptr_array_add (acfg->globals, g_strdup (name));
501 mono_img_writer_emit_local_symbol (acfg->w, name, NULL, func);
503 mono_img_writer_emit_global (acfg->w, name, func);
508 emit_symbol_size (MonoAotCompile *acfg, const char *name, const char *end_label)
510 mono_img_writer_emit_symbol_size (acfg->w, name, end_label);
513 /* Emit a symbol which is referenced by the MonoAotFileInfo structure */
515 emit_info_symbol (MonoAotCompile *acfg, const char *name)
520 emit_label (acfg, name);
521 /* LLVM generated code references this */
522 sprintf (symbol, "%s%s%s", acfg->user_symbol_prefix, acfg->global_prefix, name);
523 emit_label (acfg, symbol);
524 emit_global_inner (acfg, symbol, FALSE);
526 emit_label (acfg, name);
531 emit_string_symbol (MonoAotCompile *acfg, const char *name, const char *value)
534 mono_llvm_emit_aot_data (name, (guint8*)value, strlen (value) + 1);
538 mono_img_writer_emit_section_change (acfg->w, RODATA_SECT, 1);
540 /* On apple, all symbols need to be aligned to avoid warnings from ld */
541 emit_alignment (acfg, 4);
543 mono_img_writer_emit_label (acfg->w, name);
544 mono_img_writer_emit_string (acfg->w, value);
547 static G_GNUC_UNUSED void
548 emit_uleb128 (MonoAotCompile *acfg, guint32 value)
551 guint8 b = value & 0x7f;
553 if (value != 0) /* more bytes to come */
559 static G_GNUC_UNUSED void
560 emit_sleb128 (MonoAotCompile *acfg, gint64 value)
563 gboolean negative = (value < 0);
570 /* the following is unnecessary if the
571 * implementation of >>= uses an arithmetic rather
572 * than logical shift for a signed left operand
576 value |= - ((gint64)1 <<(size - 7));
577 /* sign bit of byte is second high order bit (0x40) */
578 if ((value == 0 && !(byte & 0x40)) ||
579 (value == -1 && (byte & 0x40)))
583 emit_byte (acfg, byte);
587 static G_GNUC_UNUSED void
588 encode_uleb128 (guint32 value, guint8 *buf, guint8 **endbuf)
593 guint8 b = value & 0x7f;
595 if (value != 0) /* more bytes to come */
603 static G_GNUC_UNUSED void
604 encode_sleb128 (gint32 value, guint8 *buf, guint8 **endbuf)
607 gboolean negative = (value < 0);
615 /* the following is unnecessary if the
616 * implementation of >>= uses an arithmetic rather
617 * than logical shift for a signed left operand
621 value |= - (1 <<(size - 7));
622 /* sign bit of byte is second high order bit (0x40) */
623 if ((value == 0 && !(byte & 0x40)) ||
624 (value == -1 && (byte & 0x40)))
635 encode_int (gint32 val, guint8 *buf, guint8 **endbuf)
638 buf [0] = (val >> 0) & 0xff;
639 buf [1] = (val >> 8) & 0xff;
640 buf [2] = (val >> 16) & 0xff;
641 buf [3] = (val >> 24) & 0xff;
647 encode_int16 (guint16 val, guint8 *buf, guint8 **endbuf)
649 buf [0] = (val >> 0) & 0xff;
650 buf [1] = (val >> 8) & 0xff;
656 encode_string (const char *s, guint8 *buf, guint8 **endbuf)
658 int len = strlen (s);
660 memcpy (buf, s, len + 1);
661 *endbuf = buf + len + 1;
665 emit_unset_mode (MonoAotCompile *acfg)
667 mono_img_writer_emit_unset_mode (acfg->w);
670 static G_GNUC_UNUSED void
671 emit_set_thumb_mode (MonoAotCompile *acfg)
673 emit_unset_mode (acfg);
674 fprintf (acfg->fp, ".code 16\n");
677 static G_GNUC_UNUSED void
678 emit_set_arm_mode (MonoAotCompile *acfg)
680 emit_unset_mode (acfg);
681 fprintf (acfg->fp, ".code 32\n");
685 emit_code_bytes (MonoAotCompile *acfg, const guint8* buf, int size)
690 g_assert (size % 4 == 0);
691 emit_unset_mode (acfg);
692 for (i = 0; i < size; i += 4)
693 fprintf (acfg->fp, "%s 0x%x\n", acfg->inst_directive, *(guint32*)(buf + i));
695 emit_bytes (acfg, buf, size);
699 /* ARCHITECTURE SPECIFIC CODE */
701 #if defined(TARGET_X86) || defined(TARGET_AMD64) || defined(TARGET_ARM) || defined(TARGET_POWERPC) || defined(TARGET_ARM64)
702 #define EMIT_DWARF_INFO 1
705 #if defined(TARGET_ARM)
706 #define AOT_FUNC_ALIGNMENT 4
708 #define AOT_FUNC_ALIGNMENT 16
710 #if (defined(TARGET_X86) || defined(TARGET_AMD64)) && defined(__native_client_codegen__)
711 #undef AOT_FUNC_ALIGNMENT
712 #define AOT_FUNC_ALIGNMENT 32
715 #if defined(TARGET_POWERPC64) && !defined(__mono_ilp32__)
716 #define PPC_LD_OP "ld"
717 #define PPC_LDX_OP "ldx"
719 #define PPC_LD_OP "lwz"
720 #define PPC_LDX_OP "lwzx"
724 #define AOT_TARGET_STR "AMD64"
729 #define AOT_TARGET_STR "ARM (MACH)"
731 #define AOT_TARGET_STR "ARM (!MACH)"
737 #define AOT_TARGET_STR "ARM64 (MACH)"
739 #define AOT_TARGET_STR "ARM64 (!MACH)"
743 #ifdef TARGET_POWERPC64
744 #ifdef __mono_ilp32__
745 #define AOT_TARGET_STR "POWERPC64 (mono ilp32)"
747 #define AOT_TARGET_STR "POWERPC64 (!mono ilp32)"
750 #ifdef TARGET_POWERPC
751 #ifdef __mono_ilp32__
752 #define AOT_TARGET_STR "POWERPC (mono ilp32)"
754 #define AOT_TARGET_STR "POWERPC (!mono ilp32)"
761 #define AOT_TARGET_STR "X86 (WIN32)"
762 #elif defined(__native_client_codegen__)
763 #define AOT_TARGET_STR "X86 (native client codegen)"
765 #define AOT_TARGET_STR "X86 (!native client codegen)"
769 #ifndef AOT_TARGET_STR
770 #define AOT_TARGET_STR ""
774 arch_init (MonoAotCompile *acfg)
776 acfg->llc_args = g_string_new ("");
777 acfg->as_args = g_string_new ("");
780 * The prefix LLVM likes to put in front of symbol names on darwin.
781 * The mach-os specs require this for globals, but LLVM puts them in front of all
782 * symbols. We need to handle this, since we need to refer to LLVM generated
785 acfg->llvm_label_prefix = "";
786 acfg->user_symbol_prefix = "";
788 #if defined(TARGET_X86)
789 g_string_append (acfg->llc_args, " -march=x86 -mattr=sse4.1");
792 #if defined(TARGET_AMD64)
793 g_string_append (acfg->llc_args, " -march=x86-64 -mattr=sse4.1");
795 acfg->align_pad_value = 0x90;
799 if (acfg->aot_opts.mtriple && strstr (acfg->aot_opts.mtriple, "darwin")) {
800 g_string_append (acfg->llc_args, "-mattr=+v6");
803 g_string_append (acfg->llc_args, " -mattr=+vfp2,-neon,+d16");
804 g_string_append (acfg->as_args, " -mfpu=vfp3");
806 g_string_append (acfg->llc_args, " -soft-float");
809 if (acfg->aot_opts.mtriple && strstr (acfg->aot_opts.mtriple, "thumb"))
810 acfg->thumb_mixed = TRUE;
812 if (acfg->aot_opts.mtriple)
813 mono_arch_set_target (acfg->aot_opts.mtriple);
817 acfg->inst_directive = ".inst";
818 if (acfg->aot_opts.mtriple)
819 mono_arch_set_target (acfg->aot_opts.mtriple);
823 acfg->user_symbol_prefix = "_";
824 acfg->llvm_label_prefix = "_";
825 acfg->inst_directive = ".word";
826 acfg->need_no_dead_strip = TRUE;
827 acfg->aot_opts.gnu_asm = TRUE;
830 #if defined(__linux__) && !defined(TARGET_ARM)
831 acfg->need_pt_gnu_stack = TRUE;
835 acfg->global_symbols = TRUE;
841 #include "../../../mono-extensions/mono/mini/aot-compiler-arm64.c"
845 #ifdef MONO_ARCH_AOT_SUPPORTED
847 * arch_emit_direct_call:
849 * Emit a direct call to the symbol TARGET. CALL_SIZE is set to the size of the
853 arch_emit_direct_call (MonoAotCompile *acfg, const char *target, gboolean external, gboolean thumb, MonoJumpInfo *ji, int *call_size)
855 #if defined(TARGET_X86) || defined(TARGET_AMD64)
856 /* Need to make sure this is exactly 5 bytes long */
857 if (!acfg->use_bin_writer) {
858 emit_unset_mode (acfg);
859 fprintf (acfg->fp, "call %s\n", target);
861 emit_byte (acfg, '\xe8');
862 emit_symbol_diff (acfg, target, ".", -4);
865 #elif defined(TARGET_ARM)
866 if (acfg->use_bin_writer) {
873 mono_img_writer_emit_reloc (acfg->w, R_ARM_CALL, target, -8);
874 emit_bytes (acfg, buf, 4);
876 emit_unset_mode (acfg);
878 fprintf (acfg->fp, "blx %s\n", target);
880 fprintf (acfg->fp, "bl %s\n", target);
883 #elif defined(TARGET_ARM64)
884 arm64_emit_direct_call (acfg, target, external, thumb, ji, call_size);
885 #elif defined(TARGET_POWERPC)
886 if (acfg->use_bin_writer) {
887 g_assert_not_reached ();
889 emit_unset_mode (acfg);
890 fprintf (acfg->fp, "bl %s\n", target);
894 g_assert_not_reached ();
901 * - we use an approach similar to the x86 abi: reserve a register (r30) to hold
903 * - The full-aot trampolines need access to the GOT of mscorlib, so we store
904 * in in the 2. slot of every GOT, and require every method to place the GOT
905 * address in r30, even when it doesn't access the GOT otherwise. This way,
906 * the trampolines can compute the mscorlib GOT address by loading 4(r30).
911 * PPC64 uses function descriptors which greatly complicate all code, since
912 * these are used very inconsistently in the runtime. Some functions like
913 * mono_compile_method () return ftn descriptors, while others like the
914 * trampoline creation functions do not.
915 * We assume that all GOT slots contain function descriptors, and create
916 * descriptors in aot-runtime.c when needed.
917 * The ppc64 abi uses r2 to hold the address of the TOC/GOT, which is loaded
918 * from function descriptors, we could do the same, but it would require
919 * rewriting all the ppc/aot code to handle function descriptors properly.
920 * So instead, we use the same approach as on PPC32.
921 * This is a horrible mess, but fixing it would probably lead to an even bigger
927 * - similar to the PPC32 design, we reserve EBX to hold the GOT pointer.
930 #ifdef MONO_ARCH_AOT_SUPPORTED
932 * arch_emit_got_offset:
934 * The memory pointed to by CODE should hold native code for computing the GOT
935 * address (OP_LOAD_GOTADDR). Emit this code while patching it with the offset
936 * between code and the GOT. CODE_SIZE is set to the number of bytes emitted.
939 arch_emit_got_offset (MonoAotCompile *acfg, guint8 *code, int *code_size)
941 #if defined(TARGET_POWERPC64)
942 g_assert (!acfg->use_bin_writer);
943 emit_unset_mode (acfg);
945 * The ppc32 code doesn't seem to work on ppc64, the assembler complains about
946 * unsupported relocations. So we store the got address into the .Lgot_addr
947 * symbol which is in the text segment, compute its address, and load it.
949 fprintf (acfg->fp, ".L%d:\n", acfg->label_generator);
950 fprintf (acfg->fp, "lis 0, (.Lgot_addr + 4 - .L%d)@h\n", acfg->label_generator);
951 fprintf (acfg->fp, "ori 0, 0, (.Lgot_addr + 4 - .L%d)@l\n", acfg->label_generator);
952 fprintf (acfg->fp, "add 30, 30, 0\n");
953 fprintf (acfg->fp, "%s 30, 0(30)\n", PPC_LD_OP);
954 acfg->label_generator ++;
956 #elif defined(TARGET_POWERPC)
957 g_assert (!acfg->use_bin_writer);
958 emit_unset_mode (acfg);
959 fprintf (acfg->fp, ".L%d:\n", acfg->label_generator);
960 fprintf (acfg->fp, "lis 0, (%s + 4 - .L%d)@h\n", acfg->got_symbol, acfg->label_generator);
961 fprintf (acfg->fp, "ori 0, 0, (%s + 4 - .L%d)@l\n", acfg->got_symbol, acfg->label_generator);
962 acfg->label_generator ++;
965 guint32 offset = mono_arch_get_patch_offset (code);
966 emit_bytes (acfg, code, offset);
967 emit_symbol_diff (acfg, acfg->got_symbol, ".", offset);
969 *code_size = offset + 4;
974 * arch_emit_got_access:
976 * The memory pointed to by CODE should hold native code for loading a GOT
977 * slot (OP_AOTCONST/OP_GOT_ENTRY). Emit this code while patching it so it accesses the
978 * GOT slot GOT_SLOT. CODE_SIZE is set to the number of bytes emitted.
981 arch_emit_got_access (MonoAotCompile *acfg, const char *got_symbol, guint8 *code, int got_slot, int *code_size)
984 /* mov reg, got+offset(%rip) */
986 /* The GOT symbol is in the LLVM module, the clang assembler has problems emitting symbol diffs for it */
990 /* Decode reg, see amd64_mov_reg_membase () */
991 rex_r = code [0] & AMD64_REX_R;
992 g_assert (code [0] == 0x49 + rex_r);
993 g_assert (code [1] == 0x8b);
994 dreg = ((code [2] >> 3) & 0x7) + (rex_r ? 8 : 0);
996 emit_unset_mode (acfg);
997 fprintf (acfg->fp, "mov %s+%d(%%rip), %s\n", got_symbol, (unsigned int) ((got_slot * sizeof (gpointer))), mono_arch_regname (dreg));
1000 emit_bytes (acfg, code, mono_arch_get_patch_offset (code));
1001 emit_symbol_diff (acfg, got_symbol, ".", (unsigned int) ((got_slot * sizeof (gpointer)) - 4));
1002 *code_size = mono_arch_get_patch_offset (code) + 4;
1004 #elif defined(TARGET_X86)
1005 emit_bytes (acfg, code, mono_arch_get_patch_offset (code));
1006 emit_int32 (acfg, (unsigned int) ((got_slot * sizeof (gpointer))));
1007 *code_size = mono_arch_get_patch_offset (code) + 4;
1008 #elif defined(TARGET_ARM)
1009 emit_bytes (acfg, code, mono_arch_get_patch_offset (code));
1010 emit_symbol_diff (acfg, got_symbol, ".", (unsigned int) ((got_slot * sizeof (gpointer))) - 12);
1011 *code_size = mono_arch_get_patch_offset (code) + 4;
1012 #elif defined(TARGET_ARM64)
1013 emit_bytes (acfg, code, mono_arch_get_patch_offset (code));
1014 arm64_emit_got_access (acfg, code, got_slot, code_size);
1015 #elif defined(TARGET_POWERPC)
1020 emit_bytes (acfg, code, mono_arch_get_patch_offset (code));
1022 ppc_load32 (code, ppc_r0, got_slot * sizeof (gpointer));
1023 g_assert (code - buf == 8);
1024 emit_bytes (acfg, buf, code - buf);
1025 *code_size = code - buf;
1028 g_assert_not_reached ();
1034 #ifdef MONO_ARCH_AOT_SUPPORTED
1036 * arch_emit_objc_selector_ref:
1038 * Emit the implementation of OP_OBJC_GET_SELECTOR, which itself implements @selector(foo:) in objective-c.
1041 arch_emit_objc_selector_ref (MonoAotCompile *acfg, guint8 *code, int index, int *code_size)
1043 #if defined(TARGET_ARM)
1046 int lindex = acfg->objc_selector_index_2 ++;
1048 /* Emit ldr.imm/b */
1049 emit_bytes (acfg, code, 8);
1051 sprintf (symbol1, "L_OBJC_SELECTOR_%d", lindex);
1052 sprintf (symbol2, "L_OBJC_SELECTOR_REFERENCES_%d", index);
1054 emit_label (acfg, symbol1);
1055 mono_img_writer_emit_unset_mode (acfg->w);
1056 fprintf (acfg->fp, ".long %s-(%s+12)", symbol2, symbol1);
1059 #elif defined(TARGET_ARM64)
1060 arm64_emit_objc_selector_ref (acfg, code, index, code_size);
1062 g_assert_not_reached ();
1068 * arch_emit_plt_entry:
1070 * Emit code for the PLT entry.
1071 * The plt entry should look like this:
1072 * <indirect jump to GOT_SYMBOL + OFFSET>
1073 * <INFO_OFFSET embedded into the instruction stream>
1076 arch_emit_plt_entry (MonoAotCompile *acfg, const char *got_symbol, int offset, int info_offset)
1078 #if defined(TARGET_X86)
1079 #if defined(__default_codegen__)
1080 /* jmp *<offset>(%ebx) */
1081 emit_byte (acfg, 0xff);
1082 emit_byte (acfg, 0xa3);
1083 emit_int32 (acfg, offset);
1084 /* Used by mono_aot_get_plt_info_offset */
1085 emit_int32 (acfg, info_offset);
1086 #elif defined(__native_client_codegen__)
1087 const guint8 kSizeOfNaClJmp = 11;
1088 guint8 bytes[kSizeOfNaClJmp];
1089 guint8 *pbytes = &bytes[0];
1091 x86_jump_membase32 (pbytes, X86_EBX, offset);
1092 emit_bytes (acfg, bytes, kSizeOfNaClJmp);
1093 /* four bytes of data, used by mono_arch_patch_plt_entry */
1094 /* For Native Client, make this work with data embedded in push. */
1095 emit_byte (acfg, 0x68); /* hide data in a push */
1096 emit_int32 (acfg, info_offset);
1097 emit_alignment (acfg, AOT_FUNC_ALIGNMENT);
1098 #endif /*__native_client_codegen__*/
1099 #elif defined(TARGET_AMD64)
1100 #if defined(__default_codegen__)
1101 if (acfg->use_bin_writer) {
1102 emit_byte (acfg, '\xff');
1103 emit_byte (acfg, '\x25');
1104 emit_symbol_diff (acfg, got_symbol, ".", offset - 4);
1106 emit_unset_mode (acfg);
1107 fprintf (acfg->fp, "jmp *%s+%d(%%rip)\n", got_symbol, offset);
1109 /* Used by mono_aot_get_plt_info_offset */
1110 emit_int32 (acfg, info_offset);
1111 acfg->stats.plt_size += 10;
1112 #elif defined(__native_client_codegen__)
1114 guint8 *buf_aligned = ALIGN_TO(buf, kNaClAlignment);
1115 guint8 *code = buf_aligned;
1117 /* mov <OFFSET>(%rip), %r11d */
1118 emit_byte (acfg, '\x45');
1119 emit_byte (acfg, '\x8b');
1120 emit_byte (acfg, '\x1d');
1121 emit_symbol_diff (acfg, got_symbol, ".", offset - 4);
1123 amd64_jump_reg (code, AMD64_R11);
1124 /* This should be constant for the plt patch */
1125 g_assert ((size_t)(code-buf_aligned) == 10);
1126 emit_bytes (acfg, buf_aligned, code - buf_aligned);
1128 /* Hide data in a push imm32 so it passes validation */
1129 emit_byte (acfg, 0x68); /* push */
1130 emit_int32 (acfg, info_offset);
1131 emit_alignment (acfg, AOT_FUNC_ALIGNMENT);
1132 #endif /*__native_client_codegen__*/
1133 #elif defined(TARGET_ARM)
1138 ARM_LDR_IMM (code, ARMREG_IP, ARMREG_PC, 0);
1139 ARM_LDR_REG_REG (code, ARMREG_PC, ARMREG_PC, ARMREG_IP);
1140 emit_bytes (acfg, buf, code - buf);
1141 emit_symbol_diff (acfg, got_symbol, ".", offset - 4);
1142 /* Used by mono_aot_get_plt_info_offset */
1143 emit_int32 (acfg, info_offset);
1144 #elif defined(TARGET_ARM64)
1145 arm64_emit_plt_entry (acfg, got_symbol, offset, info_offset);
1146 #elif defined(TARGET_POWERPC)
1147 /* The GOT address is guaranteed to be in r30 by OP_LOAD_GOTADDR */
1148 g_assert (!acfg->use_bin_writer);
1149 emit_unset_mode (acfg);
1150 fprintf (acfg->fp, "lis 11, %d@h\n", offset);
1151 fprintf (acfg->fp, "ori 11, 11, %d@l\n", offset);
1152 fprintf (acfg->fp, "add 11, 11, 30\n");
1153 fprintf (acfg->fp, "%s 11, 0(11)\n", PPC_LD_OP);
1154 #ifdef PPC_USES_FUNCTION_DESCRIPTOR
1155 fprintf (acfg->fp, "%s 2, %d(11)\n", PPC_LD_OP, (int)sizeof (gpointer));
1156 fprintf (acfg->fp, "%s 11, 0(11)\n", PPC_LD_OP);
1158 fprintf (acfg->fp, "mtctr 11\n");
1159 fprintf (acfg->fp, "bctr\n");
1160 emit_int32 (acfg, info_offset);
1162 g_assert_not_reached ();
1167 * arch_emit_llvm_plt_entry:
1169 * Same as arch_emit_plt_entry, but handles calls from LLVM generated code.
1170 * This is only needed on arm to handle thumb interop.
1173 arch_emit_llvm_plt_entry (MonoAotCompile *acfg, const char *got_symbol, int offset, int info_offset)
1175 #if defined(TARGET_ARM)
1176 /* LLVM calls the PLT entries using bl, so these have to be thumb2 */
1177 /* The caller already transitioned to thumb */
1178 /* The code below should be 12 bytes long */
1179 /* clang has trouble encoding these instructions, so emit the binary */
1181 fprintf (acfg->fp, "ldr ip, [pc, #8]\n");
1182 /* thumb can't encode ld pc, [pc, ip] */
1183 fprintf (acfg->fp, "add ip, pc, ip\n");
1184 fprintf (acfg->fp, "ldr ip, [ip, #0]\n");
1185 fprintf (acfg->fp, "bx ip\n");
1187 emit_set_thumb_mode (acfg);
1188 fprintf (acfg->fp, ".4byte 0xc008f8df\n");
1189 fprintf (acfg->fp, ".2byte 0x44fc\n");
1190 fprintf (acfg->fp, ".4byte 0xc000f8dc\n");
1191 fprintf (acfg->fp, ".2byte 0x4760\n");
1192 emit_symbol_diff (acfg, got_symbol, ".", offset + 4);
1193 emit_int32 (acfg, info_offset);
1194 emit_unset_mode (acfg);
1195 emit_set_arm_mode (acfg);
1197 g_assert_not_reached ();
1201 /* Save unwind_info in the module and emit the offset to the information at symbol */
1202 static void save_unwind_info (MonoAotCompile *acfg, char *symbol, GSList *unwind_ops)
1204 guint32 uw_offset, encoded_len;
1207 emit_section_change (acfg, RODATA_SECT, 0);
1208 emit_global (acfg, symbol, FALSE);
1209 emit_label (acfg, symbol);
1211 encoded = mono_unwind_ops_encode (unwind_ops, &encoded_len);
1212 uw_offset = get_unwind_info_offset (acfg, encoded, encoded_len);
1214 emit_int32 (acfg, uw_offset);
1218 * arch_emit_specific_trampoline_pages:
1220 * Emits a page full of trampolines: each trampoline uses its own address to
1221 * lookup both the generic trampoline code and the data argument.
1222 * This page can be remapped in process multiple times so we can get an
1223 * unlimited number of trampolines.
1224 * Specifically this implementation uses the following trick: two memory pages
1225 * are allocated, with the first containing the data and the second containing the trampolines.
1226 * To reduce trampoline size, each trampoline jumps at the start of the page where a common
1227 * implementation does all the lifting.
1228 * Note that the ARM single trampoline size is 8 bytes, exactly like the data that needs to be stored
1229 * on the arm 32 bit system.
1232 arch_emit_specific_trampoline_pages (MonoAotCompile *acfg)
1234 #if defined(TARGET_ARM)
1237 guint8 *loop_start, *loop_branch_back, *loop_end_check, *imt_found_check;
1239 int pagesize = MONO_AOT_TRAMP_PAGE_SIZE;
1240 GSList *unwind_ops = NULL;
1241 #define COMMON_TRAMP_SIZE 16
1242 int count = (pagesize - COMMON_TRAMP_SIZE) / 8;
1243 int imm8, rot_amount;
1246 if (!acfg->aot_opts.use_trampolines_page)
1249 acfg->tramp_page_size = pagesize;
1251 sprintf (symbol, "%sspecific_trampolines_page", acfg->user_symbol_prefix);
1252 emit_alignment (acfg, pagesize);
1253 emit_global (acfg, symbol, TRUE);
1254 emit_label (acfg, symbol);
1256 /* emit the generic code first, the trampoline address + 8 is in the lr register */
1258 imm8 = mono_arm_is_rotated_imm8 (pagesize, &rot_amount);
1259 ARM_SUB_REG_IMM (code, ARMREG_LR, ARMREG_LR, imm8, rot_amount);
1260 ARM_LDR_IMM (code, ARMREG_R1, ARMREG_LR, -8);
1261 ARM_LDR_IMM (code, ARMREG_PC, ARMREG_LR, -4);
1263 g_assert (code - buf == COMMON_TRAMP_SIZE);
1266 emit_bytes (acfg, buf, code - buf);
1268 for (i = 0; i < count; ++i) {
1270 ARM_PUSH (code, 0x5fff);
1272 arm_patch (code - 4, code - COMMON_TRAMP_SIZE - 8 * (i + 1));
1273 g_assert (code - buf == 8);
1274 emit_bytes (acfg, buf, code - buf);
1277 /* now the rgctx trampolines: each specific trampolines puts in the ip register
1278 * the instruction pointer address, so the generic trampoline at the start of the page
1279 * subtracts 4096 to get to the data page and loads the values
1280 * We again fit the generic trampiline in 16 bytes.
1282 sprintf (symbol, "%srgctx_trampolines_page", acfg->user_symbol_prefix);
1283 emit_global (acfg, symbol, TRUE);
1284 emit_label (acfg, symbol);
1286 imm8 = mono_arm_is_rotated_imm8 (pagesize, &rot_amount);
1287 ARM_SUB_REG_IMM (code, ARMREG_IP, ARMREG_IP, imm8, rot_amount);
1288 ARM_LDR_IMM (code, MONO_ARCH_RGCTX_REG, ARMREG_IP, -8);
1289 ARM_LDR_IMM (code, ARMREG_PC, ARMREG_IP, -4);
1291 g_assert (code - buf == COMMON_TRAMP_SIZE);
1294 emit_bytes (acfg, buf, code - buf);
1296 for (i = 0; i < count; ++i) {
1298 ARM_MOV_REG_REG (code, ARMREG_IP, ARMREG_PC);
1300 arm_patch (code - 4, code - COMMON_TRAMP_SIZE - 8 * (i + 1));
1301 g_assert (code - buf == 8);
1302 emit_bytes (acfg, buf, code - buf);
1306 * gsharedvt arg trampolines: see arch_emit_gsharedvt_arg_trampoline ()
1308 sprintf (symbol, "%sgsharedvt_arg_trampolines_page", acfg->user_symbol_prefix);
1309 emit_global (acfg, symbol, TRUE);
1310 emit_label (acfg, symbol);
1312 ARM_PUSH (code, (1 << ARMREG_R0) | (1 << ARMREG_R1) | (1 << ARMREG_R2) | (1 << ARMREG_R3));
1313 imm8 = mono_arm_is_rotated_imm8 (pagesize, &rot_amount);
1314 ARM_SUB_REG_IMM (code, ARMREG_IP, ARMREG_IP, imm8, rot_amount);
1315 ARM_LDR_IMM (code, ARMREG_R0, ARMREG_IP, -8);
1316 ARM_LDR_IMM (code, ARMREG_PC, ARMREG_IP, -4);
1317 g_assert (code - buf == COMMON_TRAMP_SIZE);
1319 emit_bytes (acfg, buf, code - buf);
1321 for (i = 0; i < count; ++i) {
1323 ARM_MOV_REG_REG (code, ARMREG_IP, ARMREG_PC);
1325 arm_patch (code - 4, code - COMMON_TRAMP_SIZE - 8 * (i + 1));
1326 g_assert (code - buf == 8);
1327 emit_bytes (acfg, buf, code - buf);
1330 /* now the imt trampolines: each specific trampolines puts in the ip register
1331 * the instruction pointer address, so the generic trampoline at the start of the page
1332 * subtracts 4096 to get to the data page and loads the values
1334 #define IMT_TRAMP_SIZE 72
1335 sprintf (symbol, "%simt_trampolines_page", acfg->user_symbol_prefix);
1336 emit_global (acfg, symbol, TRUE);
1337 emit_label (acfg, symbol);
1339 /* Need at least two free registers, plus a slot for storing the pc */
1340 ARM_PUSH (code, (1 << ARMREG_R0)|(1 << ARMREG_R1)|(1 << ARMREG_R2));
1342 imm8 = mono_arm_is_rotated_imm8 (pagesize, &rot_amount);
1343 ARM_SUB_REG_IMM (code, ARMREG_IP, ARMREG_IP, imm8, rot_amount);
1344 ARM_LDR_IMM (code, ARMREG_R0, ARMREG_IP, -8);
1346 /* The IMT method is in v5, r0 has the imt array address */
1349 ARM_LDR_IMM (code, ARMREG_R1, ARMREG_R0, 0);
1350 ARM_CMP_REG_REG (code, ARMREG_R1, ARMREG_V5);
1351 imt_found_check = code;
1352 ARM_B_COND (code, ARMCOND_EQ, 0);
1354 /* End-of-loop check */
1355 ARM_CMP_REG_IMM (code, ARMREG_R1, 0, 0);
1356 loop_end_check = code;
1357 ARM_B_COND (code, ARMCOND_EQ, 0);
1360 ARM_ADD_REG_IMM8 (code, ARMREG_R0, ARMREG_R0, sizeof (gpointer) * 2);
1361 loop_branch_back = code;
1363 arm_patch (loop_branch_back, loop_start);
1366 arm_patch (imt_found_check, code);
1367 ARM_LDR_IMM (code, ARMREG_R0, ARMREG_R0, 4);
1368 ARM_LDR_IMM (code, ARMREG_R0, ARMREG_R0, 0);
1369 /* Save it to the third stack slot */
1370 ARM_STR_IMM (code, ARMREG_R0, ARMREG_SP, 8);
1371 /* Restore the registers and branch */
1372 ARM_POP (code, (1 << ARMREG_R0)|(1 << ARMREG_R1)|(1 << ARMREG_PC));
1375 arm_patch (loop_end_check, code);
1376 ARM_LDR_IMM (code, ARMREG_R0, ARMREG_R0, 4);
1377 ARM_STR_IMM (code, ARMREG_R0, ARMREG_SP, 8);
1378 ARM_POP (code, (1 << ARMREG_R0)|(1 << ARMREG_R1)|(1 << ARMREG_PC));
1382 g_assert (code - buf == IMT_TRAMP_SIZE);
1383 emit_bytes (acfg, buf, code - buf);
1385 for (i = 0; i < count; ++i) {
1387 ARM_MOV_REG_REG (code, ARMREG_IP, ARMREG_PC);
1389 arm_patch (code - 4, code - IMT_TRAMP_SIZE - 8 * (i + 1));
1390 g_assert (code - buf == 8);
1391 emit_bytes (acfg, buf, code - buf);
1394 acfg->tramp_page_code_offsets [MONO_AOT_TRAMP_SPECIFIC] = 16;
1395 acfg->tramp_page_code_offsets [MONO_AOT_TRAMP_STATIC_RGCTX] = 16;
1396 acfg->tramp_page_code_offsets [MONO_AOT_TRAMP_IMT_THUNK] = 72;
1397 acfg->tramp_page_code_offsets [MONO_AOT_TRAMP_GSHAREDVT_ARG] = 16;
1399 /* Unwind info for specifc trampolines */
1400 sprintf (symbol, "%sspecific_trampolines_page_gen_p", acfg->user_symbol_prefix);
1401 /* We unwind to the original caller, from the stack, since lr is clobbered */
1402 mono_add_unwind_op_def_cfa (unwind_ops, 0, 0, ARMREG_SP, 14 * sizeof (mgreg_t));
1403 mono_add_unwind_op_offset (unwind_ops, 0, 0, ARMREG_LR, -4);
1404 save_unwind_info (acfg, symbol, unwind_ops);
1405 mono_free_unwind_info (unwind_ops);
1407 sprintf (symbol, "%sspecific_trampolines_page_sp_p", acfg->user_symbol_prefix);
1408 mono_add_unwind_op_def_cfa (unwind_ops, 0, 0, ARMREG_SP, 0);
1409 mono_add_unwind_op_def_cfa_offset (unwind_ops, 4, 0, 14 * sizeof (mgreg_t));
1410 save_unwind_info (acfg, symbol, unwind_ops);
1411 mono_free_unwind_info (unwind_ops);
1413 /* Unwind info for rgctx trampolines */
1414 sprintf (symbol, "%srgctx_trampolines_page_gen_p", acfg->user_symbol_prefix);
1415 mono_add_unwind_op_def_cfa (unwind_ops, 0, 0, ARMREG_SP, 0);
1416 save_unwind_info (acfg, symbol, unwind_ops);
1418 sprintf (symbol, "%srgctx_trampolines_page_sp_p", acfg->user_symbol_prefix);
1419 save_unwind_info (acfg, symbol, unwind_ops);
1420 mono_free_unwind_info (unwind_ops);
1422 /* Unwind info for gsharedvt trampolines */
1423 sprintf (symbol, "%sgsharedvt_trampolines_page_gen_p", acfg->user_symbol_prefix);
1424 mono_add_unwind_op_def_cfa (unwind_ops, 0, 0, ARMREG_SP, 0);
1425 mono_add_unwind_op_def_cfa_offset (unwind_ops, 4, 0, 4 * sizeof (mgreg_t));
1426 save_unwind_info (acfg, symbol, unwind_ops);
1427 mono_free_unwind_info (unwind_ops);
1429 sprintf (symbol, "%sgsharedvt_trampolines_page_sp_p", acfg->user_symbol_prefix);
1430 mono_add_unwind_op_def_cfa (unwind_ops, 0, 0, ARMREG_SP, 0);
1431 save_unwind_info (acfg, symbol, unwind_ops);
1432 mono_free_unwind_info (unwind_ops);
1434 /* Unwind info for imt trampolines */
1435 sprintf (symbol, "%simt_trampolines_page_gen_p", acfg->user_symbol_prefix);
1436 mono_add_unwind_op_def_cfa (unwind_ops, 0, 0, ARMREG_SP, 0);
1437 mono_add_unwind_op_def_cfa_offset (unwind_ops, 4, 0, 3 * sizeof (mgreg_t));
1438 save_unwind_info (acfg, symbol, unwind_ops);
1439 mono_free_unwind_info (unwind_ops);
1441 sprintf (symbol, "%simt_trampolines_page_sp_p", acfg->user_symbol_prefix);
1442 mono_add_unwind_op_def_cfa (unwind_ops, 0, 0, ARMREG_SP, 0);
1443 save_unwind_info (acfg, symbol, unwind_ops);
1444 mono_free_unwind_info (unwind_ops);
1445 #elif defined(TARGET_ARM64)
1446 arm64_emit_specific_trampoline_pages (acfg);
1451 * arch_emit_specific_trampoline:
1453 * Emit code for a specific trampoline. OFFSET is the offset of the first of
1454 * two GOT slots which contain the generic trampoline address and the trampoline
1455 * argument. TRAMP_SIZE is set to the size of the emitted trampoline.
1458 arch_emit_specific_trampoline (MonoAotCompile *acfg, int offset, int *tramp_size)
1461 * The trampolines created here are variations of the specific
1462 * trampolines created in mono_arch_create_specific_trampoline (). The
1464 * - the generic trampoline address is taken from a got slot.
1465 * - the offset of the got slot where the trampoline argument is stored
1466 * is embedded in the instruction stream, and the generic trampoline
1467 * can load the argument by loading the offset, adding it to the
1468 * address of the trampoline to get the address of the got slot, and
1469 * loading the argument from there.
1470 * - all the trampolines should be of the same length.
1472 #if defined(TARGET_AMD64)
1473 #if defined(__default_codegen__)
1474 /* This should be exactly 8 bytes long */
1476 /* call *<offset>(%rip) */
1478 emit_unset_mode (acfg);
1479 fprintf (acfg->fp, "call *%s+%d(%%rip)\n", acfg->got_symbol, (int)(offset * sizeof (gpointer)));
1480 emit_zero_bytes (acfg, 2);
1482 emit_byte (acfg, '\x41');
1483 emit_byte (acfg, '\xff');
1484 emit_byte (acfg, '\x15');
1485 emit_symbol_diff (acfg, acfg->got_symbol, ".", (offset * sizeof (gpointer)) - 4);
1486 emit_zero_bytes (acfg, 1);
1488 #elif defined(__native_client_codegen__)
1490 guint8 *buf_aligned = ALIGN_TO(buf, kNaClAlignment);
1491 guint8 *code = buf_aligned;
1496 /* Emit this call in 'code' so we can find out how long it is. */
1497 amd64_call_reg (code, AMD64_R11);
1498 call_start = mono_arch_nacl_skip_nops (buf_aligned);
1499 call_len = code - call_start;
1501 /* The tramp_size is twice the NaCl alignment because it starts with */
1502 /* a call which needs to be aligned to the end of the boundary. */
1503 *tramp_size = kNaClAlignment*2;
1505 /* Emit nops to align call site below which is 7 bytes plus */
1506 /* the length of the call sequence emitted above. */
1507 /* Note: this requires the specific trampoline starts on a */
1508 /* kNaclAlignedment aligned address, which it does because */
1509 /* it's its own function that is aligned. */
1510 guint8 nop_buf[256];
1511 guint8 *nopbuf_aligned = ALIGN_TO (nop_buf, kNaClAlignment);
1512 guint8 *nopbuf_end = mono_arch_nacl_pad (nopbuf_aligned, kNaClAlignment - 7 - (call_len));
1513 emit_bytes (acfg, nopbuf_aligned, nopbuf_end - nopbuf_aligned);
1515 /* The trampoline is stored at the offset'th pointer, the -4 is */
1516 /* present because RIP relative addressing starts at the end of */
1517 /* the current instruction, while the label "." is relative to */
1518 /* the beginning of the current asm location, which in this case */
1519 /* is not the mov instruction, but the offset itself, due to the */
1520 /* way the bytes and ints are emitted here. */
1521 got_offset = (offset * sizeof(gpointer)) - 4;
1523 /* mov <OFFSET>(%rip), %r11d */
1524 emit_byte (acfg, '\x45');
1525 emit_byte (acfg, '\x8b');
1526 emit_byte (acfg, '\x1d');
1527 emit_symbol_diff (acfg, acfg->got_symbol, ".", got_offset);
1530 emit_bytes (acfg, call_start, call_len);
1532 /* The arg is stored at the offset+1 pointer, relative to beginning */
1533 /* of trampoline: 7 for mov, plus the call length, and 1 for push. */
1534 got_offset = ((offset + 1) * sizeof(gpointer)) + 7 + call_len + 1;
1536 /* We can't emit this data directly, hide in a "push imm32" */
1537 emit_byte (acfg, '\x68'); /* push */
1538 emit_symbol_diff (acfg, acfg->got_symbol, ".", got_offset);
1539 emit_alignment (acfg, kNaClAlignment);
1540 #endif /*__native_client_codegen__*/
1541 #elif defined(TARGET_ARM)
1545 /* This should be exactly 20 bytes long */
1548 ARM_PUSH (code, 0x5fff);
1549 ARM_LDR_IMM (code, ARMREG_R1, ARMREG_PC, 4);
1550 /* Load the value from the GOT */
1551 ARM_LDR_REG_REG (code, ARMREG_R1, ARMREG_PC, ARMREG_R1);
1553 ARM_BLX_REG (code, ARMREG_R1);
1555 g_assert (code - buf == 16);
1558 emit_bytes (acfg, buf, code - buf);
1560 * Only one offset is needed, since the second one would be equal to the
1563 emit_symbol_diff (acfg, acfg->got_symbol, ".", (offset * sizeof (gpointer)) - 4 + 4);
1564 //emit_symbol_diff (acfg, acfg->got_symbol, ".", ((offset + 1) * sizeof (gpointer)) - 4 + 8);
1565 #elif defined(TARGET_ARM64)
1566 arm64_emit_specific_trampoline (acfg, offset, tramp_size);
1567 #elif defined(TARGET_POWERPC)
1574 g_assert (!acfg->use_bin_writer);
1577 * PPC has no ip relative addressing, so we need to compute the address
1578 * of the mscorlib got. That is slow and complex, so instead, we store it
1579 * in the second got slot of every aot image. The caller already computed
1580 * the address of its got and placed it into r30.
1582 emit_unset_mode (acfg);
1583 /* Load mscorlib got address */
1584 fprintf (acfg->fp, "%s 0, %d(30)\n", PPC_LD_OP, (int)sizeof (gpointer));
1585 /* Load generic trampoline address */
1586 fprintf (acfg->fp, "lis 11, %d@h\n", (int)(offset * sizeof (gpointer)));
1587 fprintf (acfg->fp, "ori 11, 11, %d@l\n", (int)(offset * sizeof (gpointer)));
1588 fprintf (acfg->fp, "%s 11, 11, 0\n", PPC_LDX_OP);
1589 #ifdef PPC_USES_FUNCTION_DESCRIPTOR
1590 fprintf (acfg->fp, "%s 11, 0(11)\n", PPC_LD_OP);
1592 fprintf (acfg->fp, "mtctr 11\n");
1593 /* Load trampoline argument */
1594 /* On ppc, we pass it normally to the generic trampoline */
1595 fprintf (acfg->fp, "lis 11, %d@h\n", (int)((offset + 1) * sizeof (gpointer)));
1596 fprintf (acfg->fp, "ori 11, 11, %d@l\n", (int)((offset + 1) * sizeof (gpointer)));
1597 fprintf (acfg->fp, "%s 0, 11, 0\n", PPC_LDX_OP);
1598 /* Branch to generic trampoline */
1599 fprintf (acfg->fp, "bctr\n");
1601 #ifdef PPC_USES_FUNCTION_DESCRIPTOR
1602 *tramp_size = 10 * 4;
1604 *tramp_size = 9 * 4;
1606 #elif defined(TARGET_X86)
1610 /* Similar to the PPC code above */
1612 /* FIXME: Could this clobber the register needed by get_vcall_slot () ? */
1615 /* Load mscorlib got address */
1616 x86_mov_reg_membase (code, X86_ECX, MONO_ARCH_GOT_REG, sizeof (gpointer), 4);
1617 /* Push trampoline argument */
1618 x86_push_membase (code, X86_ECX, (offset + 1) * sizeof (gpointer));
1619 /* Load generic trampoline address */
1620 x86_mov_reg_membase (code, X86_ECX, X86_ECX, offset * sizeof (gpointer), 4);
1621 /* Branch to generic trampoline */
1622 x86_jump_reg (code, X86_ECX);
1624 #ifdef __native_client_codegen__
1626 /* emit nops to next 32 byte alignment */
1627 int a = (~kNaClAlignmentMask) & ((code - buf) + kNaClAlignment - 1);
1628 while (code < (buf + a)) x86_nop(code);
1631 emit_bytes (acfg, buf, code - buf);
1633 *tramp_size = NACL_SIZE(17, kNaClAlignment);
1634 g_assert (code - buf == *tramp_size);
1636 g_assert_not_reached ();
1641 * arch_emit_unbox_trampoline:
1643 * Emit code for the unbox trampoline for METHOD used in the full-aot case.
1644 * CALL_TARGET is the symbol pointing to the native code of METHOD.
1647 arch_emit_unbox_trampoline (MonoAotCompile *acfg, MonoCompile *cfg, MonoMethod *method, const char *call_target)
1649 #if defined(TARGET_AMD64)
1654 this_reg = mono_arch_get_this_arg_reg (NULL);
1656 amd64_alu_reg_imm (code, X86_ADD, this_reg, sizeof (MonoObject));
1658 emit_bytes (acfg, buf, code - buf);
1661 emit_unset_mode (acfg);
1662 fprintf (acfg->fp, "jmp %s\n", call_target);
1664 emit_byte (acfg, '\xe9');
1665 emit_symbol_diff (acfg, call_target, ".", -4);
1667 #elif defined(TARGET_X86)
1674 x86_alu_membase_imm (code, X86_ADD, X86_ESP, this_pos, sizeof (MonoObject));
1676 emit_bytes (acfg, buf, code - buf);
1679 emit_byte (acfg, '\xe9');
1680 emit_symbol_diff (acfg, call_target, ".", -4);
1681 #elif defined(TARGET_ARM)
1685 if (acfg->thumb_mixed && cfg->compile_llvm) {
1686 fprintf (acfg->fp, "add r0, r0, #%d\n", (int)sizeof (MonoObject));
1687 fprintf (acfg->fp, "b %s\n", call_target);
1688 fprintf (acfg->fp, ".arm\n");
1689 fprintf (acfg->fp, ".align 2\n");
1695 ARM_ADD_REG_IMM8 (code, ARMREG_R0, ARMREG_R0, sizeof (MonoObject));
1697 emit_bytes (acfg, buf, code - buf);
1698 /* jump to method */
1699 if (acfg->use_bin_writer) {
1706 mono_img_writer_emit_reloc (acfg->w, R_ARM_JUMP24, call_target, -8);
1707 emit_bytes (acfg, buf, 4);
1709 if (acfg->thumb_mixed && cfg->compile_llvm)
1710 fprintf (acfg->fp, "\n\tbx %s\n", call_target);
1712 fprintf (acfg->fp, "\n\tb %s\n", call_target);
1714 #elif defined(TARGET_ARM64)
1715 arm64_emit_unbox_trampoline (acfg, cfg, method, call_target);
1716 #elif defined(TARGET_POWERPC)
1719 g_assert (!acfg->use_bin_writer);
1721 fprintf (acfg->fp, "\n\taddi %d, %d, %d\n", this_pos, this_pos, (int)sizeof (MonoObject));
1722 fprintf (acfg->fp, "\n\tb %s\n", call_target);
1724 g_assert_not_reached ();
1729 * arch_emit_static_rgctx_trampoline:
1731 * Emit code for a static rgctx trampoline. OFFSET is the offset of the first of
1732 * two GOT slots which contain the rgctx argument, and the method to jump to.
1733 * TRAMP_SIZE is set to the size of the emitted trampoline.
1734 * These kinds of trampolines cannot be enumerated statically, since there could
1735 * be one trampoline per method instantiation, so we emit the same code for all
1736 * trampolines, and parameterize them using two GOT slots.
1739 arch_emit_static_rgctx_trampoline (MonoAotCompile *acfg, int offset, int *tramp_size)
1741 #if defined(TARGET_AMD64)
1742 #if defined(__default_codegen__)
1743 /* This should be exactly 13 bytes long */
1747 emit_unset_mode (acfg);
1748 fprintf (acfg->fp, "mov %s+%d(%%rip), %%r10\n", acfg->got_symbol, (int)(offset * sizeof (gpointer)));
1749 fprintf (acfg->fp, "jmp *%s+%d(%%rip)\n", acfg->got_symbol, (int)((offset + 1) * sizeof (gpointer)));
1751 /* mov <OFFSET>(%rip), %r10 */
1752 emit_byte (acfg, '\x4d');
1753 emit_byte (acfg, '\x8b');
1754 emit_byte (acfg, '\x15');
1755 emit_symbol_diff (acfg, acfg->got_symbol, ".", (offset * sizeof (gpointer)) - 4);
1757 /* jmp *<offset>(%rip) */
1758 emit_byte (acfg, '\xff');
1759 emit_byte (acfg, '\x25');
1760 emit_symbol_diff (acfg, acfg->got_symbol, ".", ((offset + 1) * sizeof (gpointer)) - 4);
1762 #elif defined(__native_client_codegen__)
1764 guint8 *buf_aligned = ALIGN_TO(buf, kNaClAlignment);
1765 guint8 *code = buf_aligned;
1767 /* mov <OFFSET>(%rip), %r10d */
1768 emit_byte (acfg, '\x45');
1769 emit_byte (acfg, '\x8b');
1770 emit_byte (acfg, '\x15');
1771 emit_symbol_diff (acfg, acfg->got_symbol, ".", (offset * sizeof (gpointer)) - 4);
1773 /* mov <OFFSET>(%rip), %r11d */
1774 emit_byte (acfg, '\x45');
1775 emit_byte (acfg, '\x8b');
1776 emit_byte (acfg, '\x1d');
1777 emit_symbol_diff (acfg, acfg->got_symbol, ".", ((offset + 1) * sizeof (gpointer)) - 4);
1780 amd64_jump_reg (code, AMD64_R11);
1781 emit_bytes (acfg, buf_aligned, code - buf_aligned);
1783 emit_alignment (acfg, kNaClAlignment);
1784 *tramp_size = kNaClAlignment;
1785 #endif /*__native_client_codegen__*/
1787 #elif defined(TARGET_ARM)
1791 /* This should be exactly 24 bytes long */
1794 /* Load rgctx value */
1795 ARM_LDR_IMM (code, ARMREG_IP, ARMREG_PC, 8);
1796 ARM_LDR_REG_REG (code, MONO_ARCH_RGCTX_REG, ARMREG_PC, ARMREG_IP);
1797 /* Load branch addr + branch */
1798 ARM_LDR_IMM (code, ARMREG_IP, ARMREG_PC, 4);
1799 ARM_LDR_REG_REG (code, ARMREG_PC, ARMREG_PC, ARMREG_IP);
1801 g_assert (code - buf == 16);
1804 emit_bytes (acfg, buf, code - buf);
1805 emit_symbol_diff (acfg, acfg->got_symbol, ".", (offset * sizeof (gpointer)) - 4 + 8);
1806 emit_symbol_diff (acfg, acfg->got_symbol, ".", ((offset + 1) * sizeof (gpointer)) - 4 + 4);
1807 #elif defined(TARGET_ARM64)
1808 arm64_emit_static_rgctx_trampoline (acfg, offset, tramp_size);
1809 #elif defined(TARGET_POWERPC)
1816 g_assert (!acfg->use_bin_writer);
1819 * PPC has no ip relative addressing, so we need to compute the address
1820 * of the mscorlib got. That is slow and complex, so instead, we store it
1821 * in the second got slot of every aot image. The caller already computed
1822 * the address of its got and placed it into r30.
1824 emit_unset_mode (acfg);
1825 /* Load mscorlib got address */
1826 fprintf (acfg->fp, "%s 0, %d(30)\n", PPC_LD_OP, (int)sizeof (gpointer));
1828 fprintf (acfg->fp, "lis 11, %d@h\n", (int)(offset * sizeof (gpointer)));
1829 fprintf (acfg->fp, "ori 11, 11, %d@l\n", (int)(offset * sizeof (gpointer)));
1830 fprintf (acfg->fp, "%s %d, 11, 0\n", PPC_LDX_OP, MONO_ARCH_RGCTX_REG);
1831 /* Load target address */
1832 fprintf (acfg->fp, "lis 11, %d@h\n", (int)((offset + 1) * sizeof (gpointer)));
1833 fprintf (acfg->fp, "ori 11, 11, %d@l\n", (int)((offset + 1) * sizeof (gpointer)));
1834 fprintf (acfg->fp, "%s 11, 11, 0\n", PPC_LDX_OP);
1835 #ifdef PPC_USES_FUNCTION_DESCRIPTOR
1836 fprintf (acfg->fp, "%s 2, %d(11)\n", PPC_LD_OP, (int)sizeof (gpointer));
1837 fprintf (acfg->fp, "%s 11, 0(11)\n", PPC_LD_OP);
1839 fprintf (acfg->fp, "mtctr 11\n");
1840 /* Branch to the target address */
1841 fprintf (acfg->fp, "bctr\n");
1843 #ifdef PPC_USES_FUNCTION_DESCRIPTOR
1844 *tramp_size = 11 * 4;
1846 *tramp_size = 9 * 4;
1849 #elif defined(TARGET_X86)
1853 /* Similar to the PPC code above */
1855 g_assert (MONO_ARCH_RGCTX_REG != X86_ECX);
1858 /* Load mscorlib got address */
1859 x86_mov_reg_membase (code, X86_ECX, MONO_ARCH_GOT_REG, sizeof (gpointer), 4);
1861 x86_mov_reg_membase (code, MONO_ARCH_RGCTX_REG, X86_ECX, offset * sizeof (gpointer), 4);
1862 /* Branch to the target address */
1863 x86_jump_membase (code, X86_ECX, (offset + 1) * sizeof (gpointer));
1865 #ifdef __native_client_codegen__
1867 /* emit nops to next 32 byte alignment */
1868 int a = (~kNaClAlignmentMask) & ((code - buf) + kNaClAlignment - 1);
1869 while (code < (buf + a)) x86_nop(code);
1873 emit_bytes (acfg, buf, code - buf);
1875 *tramp_size = NACL_SIZE (15, kNaClAlignment);
1876 g_assert (code - buf == *tramp_size);
1878 g_assert_not_reached ();
1883 * arch_emit_imt_thunk:
1885 * Emit an IMT thunk usable in full-aot mode. The thunk uses 1 got slot which
1886 * points to an array of pointer pairs. The pairs of the form [key, ptr], where
1887 * key is the IMT key, and ptr holds the address of a memory location holding
1888 * the address to branch to if the IMT arg matches the key. The array is
1889 * terminated by a pair whose key is NULL, and whose ptr is the address of the
1891 * TRAMP_SIZE is set to the size of the emitted trampoline.
1894 arch_emit_imt_thunk (MonoAotCompile *acfg, int offset, int *tramp_size)
1896 #if defined(TARGET_AMD64)
1898 #if defined(__native_client_codegen__)
1901 guint8 *labels [16];
1903 guint8 *mov_buf_ptr = mov_buf;
1905 const int kSizeOfMove = 7;
1906 #if defined(__default_codegen__)
1907 code = buf = g_malloc (256);
1908 #elif defined(__native_client_codegen__)
1909 buf_alloc = g_malloc (256 + kNaClAlignment + kSizeOfMove);
1910 buf = ((guint)buf_alloc + kNaClAlignment) & ~kNaClAlignmentMask;
1911 /* The RIP relative move below is emitted first */
1916 /* FIXME: Optimize this, i.e. use binary search etc. */
1917 /* Maybe move the body into a separate function (slower, but much smaller) */
1919 /* MONO_ARCH_IMT_SCRATCH_REG is a free register */
1922 emit_unset_mode (acfg);
1923 fprintf (acfg->fp, "mov %s+%d(%%rip), %s\n", acfg->got_symbol, (int)(offset * sizeof (gpointer)), mono_arch_regname (MONO_ARCH_IMT_SCRATCH_REG));
1927 amd64_alu_membase_imm (code, X86_CMP, MONO_ARCH_IMT_SCRATCH_REG, 0, 0);
1929 amd64_branch8 (code, X86_CC_Z, 0, FALSE);
1932 amd64_alu_membase_reg_size (code, X86_CMP, MONO_ARCH_IMT_SCRATCH_REG, 0, MONO_ARCH_IMT_REG, sizeof (gpointer));
1934 amd64_branch8 (code, X86_CC_Z, 0, FALSE);
1937 amd64_alu_reg_imm (code, X86_ADD, MONO_ARCH_IMT_SCRATCH_REG, 2 * sizeof (gpointer));
1938 amd64_jump_code (code, labels [0]);
1941 mono_amd64_patch (labels [2], code);
1942 amd64_mov_reg_membase (code, MONO_ARCH_IMT_SCRATCH_REG, MONO_ARCH_IMT_SCRATCH_REG, sizeof (gpointer), sizeof (gpointer));
1943 amd64_jump_membase (code, MONO_ARCH_IMT_SCRATCH_REG, 0);
1946 mono_amd64_patch (labels [1], code);
1947 /* Load fail tramp */
1948 amd64_alu_reg_imm (code, X86_ADD, MONO_ARCH_IMT_SCRATCH_REG, sizeof (gpointer));
1949 /* Check if there is a fail tramp */
1950 amd64_alu_membase_imm (code, X86_CMP, MONO_ARCH_IMT_SCRATCH_REG, 0, 0);
1952 amd64_branch8 (code, X86_CC_Z, 0, FALSE);
1953 /* Jump to fail tramp */
1954 amd64_jump_membase (code, MONO_ARCH_IMT_SCRATCH_REG, 0);
1957 mono_amd64_patch (labels [3], code);
1958 x86_breakpoint (code);
1961 /* mov <OFFSET>(%rip), MONO_ARCH_IMT_SCRATCH_REG */
1962 amd64_emit_rex (mov_buf_ptr, sizeof(gpointer), MONO_ARCH_IMT_SCRATCH_REG, 0, AMD64_RIP);
1963 *(mov_buf_ptr)++ = (unsigned char)0x8b; /* mov opcode */
1964 x86_address_byte (mov_buf_ptr, 0, MONO_ARCH_IMT_SCRATCH_REG & 0x7, 5);
1965 emit_bytes (acfg, mov_buf, mov_buf_ptr - mov_buf);
1966 emit_symbol_diff (acfg, acfg->got_symbol, ".", (offset * sizeof (gpointer)) - 4);
1968 emit_bytes (acfg, buf, code - buf);
1970 *tramp_size = code - buf + kSizeOfMove;
1971 #if defined(__native_client_codegen__)
1972 /* The tramp will be padded to the next kNaClAlignment bundle. */
1973 *tramp_size = ALIGN_TO ((*tramp_size), kNaClAlignment);
1976 #if defined(__default_codegen__)
1978 #elif defined(__native_client_codegen__)
1982 #elif defined(TARGET_X86)
1984 #ifdef __native_client_codegen__
1987 guint8 *labels [16];
1989 #if defined(__default_codegen__)
1990 code = buf = g_malloc (256);
1991 #elif defined(__native_client_codegen__)
1992 buf_alloc = g_malloc (256 + kNaClAlignment);
1993 code = buf = ((guint)buf_alloc + kNaClAlignment) & ~kNaClAlignmentMask;
1996 /* Allocate a temporary stack slot */
1997 x86_push_reg (code, X86_EAX);
1999 x86_push_reg (code, X86_EAX);
2001 /* Load mscorlib got address */
2002 x86_mov_reg_membase (code, X86_EAX, MONO_ARCH_GOT_REG, sizeof (gpointer), 4);
2004 x86_mov_reg_membase (code, X86_EAX, X86_EAX, offset * sizeof (gpointer), 4);
2007 x86_alu_membase_imm (code, X86_CMP, X86_EAX, 0, 0);
2009 x86_branch8 (code, X86_CC_Z, FALSE, 0);
2012 x86_alu_membase_reg (code, X86_CMP, X86_EAX, 0, MONO_ARCH_IMT_REG);
2014 x86_branch8 (code, X86_CC_Z, FALSE, 0);
2017 x86_alu_reg_imm (code, X86_ADD, X86_EAX, 2 * sizeof (gpointer));
2018 x86_jump_code (code, labels [0]);
2021 mono_x86_patch (labels [2], code);
2022 x86_mov_reg_membase (code, X86_EAX, X86_EAX, sizeof (gpointer), 4);
2023 x86_mov_reg_membase (code, X86_EAX, X86_EAX, 0, 4);
2024 /* Save the target address to the temporary stack location */
2025 x86_mov_membase_reg (code, X86_ESP, 4, X86_EAX, 4);
2027 x86_pop_reg (code, X86_EAX);
2028 /* Jump to the target address */
2032 mono_x86_patch (labels [1], code);
2033 /* Load fail tramp */
2034 x86_mov_reg_membase (code, X86_EAX, X86_EAX, sizeof (gpointer), 4);
2035 x86_alu_membase_imm (code, X86_CMP, X86_EAX, 0, 0);
2037 x86_branch8 (code, X86_CC_Z, FALSE, 0);
2038 /* Jump to fail tramp */
2039 x86_mov_membase_reg (code, X86_ESP, 4, X86_EAX, 4);
2040 x86_pop_reg (code, X86_EAX);
2044 mono_x86_patch (labels [3], code);
2045 x86_breakpoint (code);
2047 #ifdef __native_client_codegen__
2049 /* emit nops to next 32 byte alignment */
2050 int a = (~kNaClAlignmentMask) & ((code - buf) + kNaClAlignment - 1);
2051 while (code < (buf + a)) x86_nop(code);
2054 emit_bytes (acfg, buf, code - buf);
2056 *tramp_size = code - buf;
2058 #if defined(__default_codegen__)
2060 #elif defined(__native_client_codegen__)
2064 #elif defined(TARGET_ARM)
2066 guint8 *code, *code2, *labels [16];
2070 /* The IMT method is in v5 */
2072 /* Need at least two free registers, plus a slot for storing the pc */
2073 ARM_PUSH (code, (1 << ARMREG_R0)|(1 << ARMREG_R1)|(1 << ARMREG_R2));
2075 /* Load the parameter from the GOT */
2076 ARM_LDR_IMM (code, ARMREG_R0, ARMREG_PC, 0);
2077 ARM_LDR_REG_REG (code, ARMREG_R0, ARMREG_PC, ARMREG_R0);
2080 ARM_LDR_IMM (code, ARMREG_R1, ARMREG_R0, 0);
2081 ARM_CMP_REG_REG (code, ARMREG_R1, ARMREG_V5);
2083 ARM_B_COND (code, ARMCOND_EQ, 0);
2085 /* End-of-loop check */
2086 ARM_CMP_REG_IMM (code, ARMREG_R1, 0, 0);
2088 ARM_B_COND (code, ARMCOND_EQ, 0);
2091 ARM_ADD_REG_IMM8 (code, ARMREG_R0, ARMREG_R0, sizeof (gpointer) * 2);
2094 arm_patch (labels [4], labels [1]);
2097 arm_patch (labels [2], code);
2098 ARM_LDR_IMM (code, ARMREG_R0, ARMREG_R0, 4);
2099 ARM_LDR_IMM (code, ARMREG_R0, ARMREG_R0, 0);
2100 /* Save it to the third stack slot */
2101 ARM_STR_IMM (code, ARMREG_R0, ARMREG_SP, 8);
2102 /* Restore the registers and branch */
2103 ARM_POP (code, (1 << ARMREG_R0)|(1 << ARMREG_R1)|(1 << ARMREG_PC));
2106 arm_patch (labels [3], code);
2107 ARM_LDR_IMM (code, ARMREG_R0, ARMREG_R0, 4);
2108 ARM_STR_IMM (code, ARMREG_R0, ARMREG_SP, 8);
2109 ARM_POP (code, (1 << ARMREG_R0)|(1 << ARMREG_R1)|(1 << ARMREG_PC));
2113 ARM_LDR_IMM (code2, ARMREG_R0, ARMREG_PC, (code - (labels [0] + 8)));
2115 emit_bytes (acfg, buf, code - buf);
2116 emit_symbol_diff (acfg, acfg->got_symbol, ".", (offset * sizeof (gpointer)) + (code - (labels [0] + 8)) - 4);
2118 *tramp_size = code - buf + 4;
2119 #elif defined(TARGET_ARM64)
2120 arm64_emit_imt_thunk (acfg, offset, tramp_size);
2121 #elif defined(TARGET_POWERPC)
2123 guint8 *code, *labels [16];
2127 /* Load the mscorlib got address */
2128 ppc_ldptr (code, ppc_r12, sizeof (gpointer), ppc_r30);
2129 /* Load the parameter from the GOT */
2130 ppc_load (code, ppc_r0, offset * sizeof (gpointer));
2131 ppc_ldptr_indexed (code, ppc_r12, ppc_r12, ppc_r0);
2133 /* Load and check key */
2135 ppc_ldptr (code, ppc_r0, 0, ppc_r12);
2136 ppc_cmp (code, 0, sizeof (gpointer) == 8 ? 1 : 0, ppc_r0, MONO_ARCH_IMT_REG);
2138 ppc_bc (code, PPC_BR_TRUE, PPC_BR_EQ, 0);
2140 /* End-of-loop check */
2141 ppc_cmpi (code, 0, sizeof (gpointer) == 8 ? 1 : 0, ppc_r0, 0);
2143 ppc_bc (code, PPC_BR_TRUE, PPC_BR_EQ, 0);
2146 ppc_addi (code, ppc_r12, ppc_r12, 2 * sizeof (gpointer));
2149 mono_ppc_patch (labels [4], labels [1]);
2152 mono_ppc_patch (labels [2], code);
2153 ppc_ldptr (code, ppc_r12, sizeof (gpointer), ppc_r12);
2154 /* r12 now contains the value of the vtable slot */
2155 /* this is not a function descriptor on ppc64 */
2156 ppc_ldptr (code, ppc_r12, 0, ppc_r12);
2157 ppc_mtctr (code, ppc_r12);
2158 ppc_bcctr (code, PPC_BR_ALWAYS, 0);
2161 mono_ppc_patch (labels [3], code);
2165 *tramp_size = code - buf;
2167 emit_bytes (acfg, buf, code - buf);
2169 g_assert_not_reached ();
2174 * arch_emit_gsharedvt_arg_trampoline:
2176 * Emit code for a gsharedvt arg trampoline. OFFSET is the offset of the first of
2177 * two GOT slots which contain the argument, and the code to jump to.
2178 * TRAMP_SIZE is set to the size of the emitted trampoline.
2179 * These kinds of trampolines cannot be enumerated statically, since there could
2180 * be one trampoline per method instantiation, so we emit the same code for all
2181 * trampolines, and parameterize them using two GOT slots.
2184 arch_emit_gsharedvt_arg_trampoline (MonoAotCompile *acfg, int offset, int *tramp_size)
2186 #if defined(TARGET_X86)
2190 /* Similar to the PPC code above */
2192 g_assert (MONO_ARCH_RGCTX_REG != X86_ECX);
2195 /* Load mscorlib got address */
2196 x86_mov_reg_membase (code, X86_ECX, MONO_ARCH_GOT_REG, sizeof (gpointer), 4);
2198 x86_mov_reg_membase (code, X86_EAX, X86_ECX, offset * sizeof (gpointer), 4);
2199 /* Branch to the target address */
2200 x86_jump_membase (code, X86_ECX, (offset + 1) * sizeof (gpointer));
2202 #ifdef __native_client_codegen__
2204 /* emit nops to next 32 byte alignment */
2205 int a = (~kNaClAlignmentMask) & ((code - buf) + kNaClAlignment - 1);
2206 while (code < (buf + a)) x86_nop(code);
2210 emit_bytes (acfg, buf, code - buf);
2212 *tramp_size = NACL_SIZE (15, kNaClAlignment);
2213 g_assert (code - buf == *tramp_size);
2214 #elif defined(TARGET_ARM)
2218 /* The same as mono_arch_get_gsharedvt_arg_trampoline (), but for AOT */
2219 /* Similar to arch_emit_specific_trampoline () */
2222 ARM_PUSH (code, (1 << ARMREG_R0) | (1 << ARMREG_R1) | (1 << ARMREG_R2) | (1 << ARMREG_R3));
2223 ARM_LDR_IMM (code, ARMREG_R1, ARMREG_PC, 8);
2224 /* Load the arg value from the GOT */
2225 ARM_LDR_REG_REG (code, ARMREG_R0, ARMREG_PC, ARMREG_R1);
2226 /* Load the addr from the GOT */
2227 ARM_LDR_REG_REG (code, ARMREG_R1, ARMREG_PC, ARMREG_R1);
2229 ARM_BX (code, ARMREG_R1);
2231 g_assert (code - buf == 20);
2234 emit_bytes (acfg, buf, code - buf);
2235 emit_symbol_diff (acfg, acfg->got_symbol, ".", (offset * sizeof (gpointer)) + 4);
2236 #elif defined(TARGET_ARM64)
2237 arm64_emit_gsharedvt_arg_trampoline (acfg, offset, tramp_size);
2239 g_assert_not_reached ();
2244 arch_emit_autoreg (MonoAotCompile *acfg, char *symbol)
2246 #if defined(TARGET_POWERPC) && defined(__mono_ilp32__)
2247 /* Based on code generated by gcc */
2248 emit_unset_mode (acfg);
2251 #if defined(_MSC_VER) || defined(MONO_CROSS_COMPILE)
2252 ".section .ctors,\"aw\",@progbits\n"
2256 ".section .opd,\"aw\"\n"
2259 ".long .%s,.TOC.@tocbase32\n"
2262 ".type .%s,@function\n"
2264 ".%s:\n", symbol, symbol, symbol, symbol, symbol, symbol, symbol, symbol);
2266 ".section .ctors,\"aw\",@progbits\n"
2270 ".section .opd,\"aw\"\n"
2273 ".long .%1$s,.TOC.@tocbase32\n"
2274 ".size %1$s,.-%1$s\n"
2276 ".type .%1$s,@function\n"
2278 ".%1$s:\n", symbol);
2289 "lis 3, .Lglobals@h\n"
2290 "ori 3, 3, .Lglobals@l\n"
2291 "bl .mono_aot_register_module\n"
2299 #if defined(_MSC_VER) || defined(MONO_CROSS_COMPILE)
2301 ".size .%s,.-.%s\n", symbol, symbol);
2304 ".size .%1$s,.-.%1$s\n", symbol);
2310 /* END OF ARCH SPECIFIC CODE */
2313 mono_get_field_token (MonoClassField *field)
2315 MonoClass *klass = field->parent;
2318 for (i = 0; i < klass->field.count; ++i) {
2319 if (field == &klass->fields [i])
2320 return MONO_TOKEN_FIELD_DEF | (klass->field.first + 1 + i);
2323 g_assert_not_reached ();
2328 encode_value (gint32 value, guint8 *buf, guint8 **endbuf)
2332 //printf ("ENCODE: %d 0x%x.\n", value, value);
2335 * Same encoding as the one used in the metadata, extended to handle values
2336 * greater than 0x1fffffff.
2338 if ((value >= 0) && (value <= 127))
2340 else if ((value >= 0) && (value <= 16383)) {
2341 p [0] = 0x80 | (value >> 8);
2342 p [1] = value & 0xff;
2344 } else if ((value >= 0) && (value <= 0x1fffffff)) {
2345 p [0] = (value >> 24) | 0xc0;
2346 p [1] = (value >> 16) & 0xff;
2347 p [2] = (value >> 8) & 0xff;
2348 p [3] = value & 0xff;
2353 p [1] = (value >> 24) & 0xff;
2354 p [2] = (value >> 16) & 0xff;
2355 p [3] = (value >> 8) & 0xff;
2356 p [4] = value & 0xff;
2364 stream_init (MonoDynamicStream *sh)
2367 sh->alloc_size = 4096;
2368 sh->data = g_malloc (4096);
2370 /* So offsets are > 0 */
2376 make_room_in_stream (MonoDynamicStream *stream, int size)
2378 if (size <= stream->alloc_size)
2381 while (stream->alloc_size <= size) {
2382 if (stream->alloc_size < 4096)
2383 stream->alloc_size = 4096;
2385 stream->alloc_size *= 2;
2388 stream->data = g_realloc (stream->data, stream->alloc_size);
2392 add_stream_data (MonoDynamicStream *stream, const char *data, guint32 len)
2396 make_room_in_stream (stream, stream->index + len);
2397 memcpy (stream->data + stream->index, data, len);
2398 idx = stream->index;
2399 stream->index += len;
2406 * Add data to the binary blob inside the aot image. Returns the offset inside the
2407 * blob where the data was stored.
2410 add_to_blob (MonoAotCompile *acfg, const guint8 *data, guint32 data_len)
2412 if (acfg->blob.alloc_size == 0)
2413 stream_init (&acfg->blob);
2415 return add_stream_data (&acfg->blob, (char*)data, data_len);
2419 add_to_blob_aligned (MonoAotCompile *acfg, const guint8 *data, guint32 data_len, guint32 align)
2424 if (acfg->blob.alloc_size == 0)
2425 stream_init (&acfg->blob);
2427 count = acfg->blob.index % align;
2429 /* we assume the stream data will be aligned */
2431 add_stream_data (&acfg->blob, buf, 4 - count);
2433 return add_stream_data (&acfg->blob, (char*)data, data_len);
2437 * emit_offset_table:
2439 * Emit a table of increasing offsets in a compact form using differential encoding.
2440 * There is an index entry for each GROUP_SIZE number of entries. The greater the
2441 * group size, the more compact the table becomes, but the slower it becomes to compute
2442 * a given entry. Returns the size of the table.
2445 emit_offset_table (MonoAotCompile *acfg, const char *symbol, int noffsets, int group_size, gint32 *offsets)
2447 gint32 current_offset;
2448 int i, buf_size, ngroups, index_entry_size;
2450 guint8 *data_p, *data_buf;
2451 guint32 *index_offsets;
2453 ngroups = (noffsets + (group_size - 1)) / group_size;
2455 index_offsets = g_new0 (guint32, ngroups);
2457 buf_size = noffsets * 4;
2458 p = buf = g_malloc0 (buf_size);
2461 for (i = 0; i < noffsets; ++i) {
2462 //printf ("D: %d -> %d\n", i, offsets [i]);
2463 if ((i % group_size) == 0) {
2464 index_offsets [i / group_size] = p - buf;
2465 /* Emit the full value for these entries */
2466 encode_value (offsets [i], p, &p);
2468 /* The offsets are allowed to be non-increasing */
2469 //g_assert (offsets [i] >= current_offset);
2470 encode_value (offsets [i] - current_offset, p, &p);
2472 current_offset = offsets [i];
2477 if (ngroups && index_offsets [ngroups - 1] < 65000)
2478 index_entry_size = 2;
2480 index_entry_size = 4;
2482 buf_size = (data_p - data_buf) + (ngroups * 4) + 16;
2483 p = buf = g_malloc0 (buf_size);
2485 /* Emit the header */
2486 encode_int (noffsets, p, &p);
2487 encode_int (group_size, p, &p);
2488 encode_int (ngroups, p, &p);
2489 encode_int (index_entry_size, p, &p);
2491 /* Emit the index */
2492 for (i = 0; i < ngroups; ++i) {
2493 if (index_entry_size == 2)
2494 encode_int16 (index_offsets [i], p, &p);
2496 encode_int (index_offsets [i], p, &p);
2499 memcpy (p, data_buf, data_p - data_buf);
2500 p += data_p - data_buf;
2502 g_assert (p - buf <= buf_size);
2505 mono_llvm_emit_aot_data (symbol, buf, p - buf);
2507 emit_section_change (acfg, RODATA_SECT, 1);
2508 emit_alignment (acfg, 8);
2509 emit_label (acfg, symbol);
2510 emit_bytes (acfg, buf, p - buf);
2516 return (int)(p - buf);
2520 get_image_index (MonoAotCompile *cfg, MonoImage *image)
2524 index = GPOINTER_TO_UINT (g_hash_table_lookup (cfg->image_hash, image));
2528 index = g_hash_table_size (cfg->image_hash);
2529 g_hash_table_insert (cfg->image_hash, image, GUINT_TO_POINTER (index + 1));
2530 g_ptr_array_add (cfg->image_table, image);
2536 find_typespec_for_class (MonoAotCompile *acfg, MonoClass *klass)
2539 int len = acfg->image->tables [MONO_TABLE_TYPESPEC].rows;
2541 /* FIXME: Search referenced images as well */
2542 if (!acfg->typespec_classes) {
2543 acfg->typespec_classes = mono_mempool_alloc0 (acfg->mempool, sizeof (MonoClass*) * len);
2544 for (i = 0; i < len; ++i) {
2546 acfg->typespec_classes [i] = mono_class_get_and_inflate_typespec_checked (acfg->image, MONO_TOKEN_TYPE_SPEC | (i + 1), NULL, &error);
2547 g_assert (mono_error_ok (&error)); /* FIXME error handling */
2550 for (i = 0; i < len; ++i) {
2551 if (acfg->typespec_classes [i] == klass)
2556 return MONO_TOKEN_TYPE_SPEC | (i + 1);
2562 encode_method_ref (MonoAotCompile *acfg, MonoMethod *method, guint8 *buf, guint8 **endbuf);
2565 encode_klass_ref (MonoAotCompile *acfg, MonoClass *klass, guint8 *buf, guint8 **endbuf);
2568 encode_ginst (MonoAotCompile *acfg, MonoGenericInst *inst, guint8 *buf, guint8 **endbuf);
2571 encode_type (MonoAotCompile *acfg, MonoType *t, guint8 *buf, guint8 **endbuf);
2574 encode_klass_ref_inner (MonoAotCompile *acfg, MonoClass *klass, guint8 *buf, guint8 **endbuf)
2579 * The encoding begins with one of the MONO_AOT_TYPEREF values, followed by additional
2583 if (klass->generic_class) {
2585 g_assert (klass->type_token);
2587 /* Find a typespec for a class if possible */
2588 token = find_typespec_for_class (acfg, klass);
2590 encode_value (MONO_AOT_TYPEREF_TYPESPEC_TOKEN, p, &p);
2591 encode_value (token, p, &p);
2593 MonoClass *gclass = klass->generic_class->container_class;
2594 MonoGenericInst *inst = klass->generic_class->context.class_inst;
2595 static int count = 0;
2598 encode_value (MONO_AOT_TYPEREF_GINST, p, &p);
2599 encode_klass_ref (acfg, gclass, p, &p);
2600 encode_ginst (acfg, inst, p, &p);
2604 } else if (klass->type_token) {
2605 int iindex = get_image_index (acfg, klass->image);
2607 g_assert (mono_metadata_token_code (klass->type_token) == MONO_TOKEN_TYPE_DEF);
2609 encode_value (MONO_AOT_TYPEREF_TYPEDEF_INDEX, p, &p);
2610 encode_value (klass->type_token - MONO_TOKEN_TYPE_DEF, p, &p);
2612 encode_value (MONO_AOT_TYPEREF_TYPEDEF_INDEX_IMAGE, p, &p);
2613 encode_value (klass->type_token - MONO_TOKEN_TYPE_DEF, p, &p);
2614 encode_value (get_image_index (acfg, klass->image), p, &p);
2616 } else if ((klass->byval_arg.type == MONO_TYPE_VAR) || (klass->byval_arg.type == MONO_TYPE_MVAR)) {
2617 MonoGenericContainer *container = mono_type_get_generic_param_owner (&klass->byval_arg);
2618 MonoGenericParam *par = klass->byval_arg.data.generic_param;
2620 encode_value (MONO_AOT_TYPEREF_VAR, p, &p);
2621 encode_value (klass->byval_arg.type, p, &p);
2622 encode_value (mono_type_get_generic_param_num (&klass->byval_arg), p, &p);
2624 encode_value (container ? 1 : 0, p, &p);
2626 encode_value (container->is_method, p, &p);
2627 g_assert (!par->gshared_constraint);
2628 if (container->is_method)
2629 encode_method_ref (acfg, container->owner.method, p, &p);
2631 encode_klass_ref (acfg, container->owner.klass, p, &p);
2633 encode_value (par->gshared_constraint ? 1 : 0, p, &p);
2634 if (par->gshared_constraint) {
2637 encode_type (acfg, par->gshared_constraint, p, &p);
2639 name = mono_generic_param_name (par);
2641 int len = strlen (name);
2643 encode_value (len, p, &p);
2644 memcpy (p, name, len);
2647 encode_value (0, p, &p);
2651 } else if (klass->byval_arg.type == MONO_TYPE_PTR) {
2652 encode_value (MONO_AOT_TYPEREF_PTR, p, &p);
2653 encode_type (acfg, &klass->byval_arg, p, &p);
2656 g_assert (klass->rank > 0);
2657 encode_value (MONO_AOT_TYPEREF_ARRAY, p, &p);
2658 encode_value (klass->rank, p, &p);
2659 encode_klass_ref (acfg, klass->element_class, p, &p);
2667 * Encode a reference to KLASS. We use our home-grown encoding instead of the
2668 * standard metadata encoding.
2671 encode_klass_ref (MonoAotCompile *acfg, MonoClass *klass, guint8 *buf, guint8 **endbuf)
2673 gboolean shared = FALSE;
2676 * The encoding of generic instances is large so emit them only once.
2678 if (klass->generic_class) {
2680 g_assert (klass->type_token);
2682 /* Find a typespec for a class if possible */
2683 token = find_typespec_for_class (acfg, klass);
2686 } else if ((klass->byval_arg.type == MONO_TYPE_VAR) || (klass->byval_arg.type == MONO_TYPE_MVAR)) {
2691 guint offset = GPOINTER_TO_UINT (g_hash_table_lookup (acfg->klass_blob_hash, klass));
2695 buf2 = g_malloc (1024);
2698 encode_klass_ref_inner (acfg, klass, p, &p);
2699 g_assert (p - buf2 < 1024);
2701 offset = add_to_blob (acfg, buf2, p - buf2);
2704 g_hash_table_insert (acfg->klass_blob_hash, klass, GUINT_TO_POINTER (offset + 1));
2710 encode_value (MONO_AOT_TYPEREF_BLOB_INDEX, p, &p);
2711 encode_value (offset, p, &p);
2716 encode_klass_ref_inner (acfg, klass, buf, endbuf);
2720 encode_field_info (MonoAotCompile *cfg, MonoClassField *field, guint8 *buf, guint8 **endbuf)
2722 guint32 token = mono_get_field_token (field);
2725 encode_klass_ref (cfg, field->parent, p, &p);
2726 g_assert (mono_metadata_token_code (token) == MONO_TOKEN_FIELD_DEF);
2727 encode_value (token - MONO_TOKEN_FIELD_DEF, p, &p);
2732 encode_ginst (MonoAotCompile *acfg, MonoGenericInst *inst, guint8 *buf, guint8 **endbuf)
2737 encode_value (inst->type_argc, p, &p);
2738 for (i = 0; i < inst->type_argc; ++i)
2739 encode_klass_ref (acfg, mono_class_from_mono_type (inst->type_argv [i]), p, &p);
2744 encode_generic_context (MonoAotCompile *acfg, MonoGenericContext *context, guint8 *buf, guint8 **endbuf)
2747 MonoGenericInst *inst;
2749 inst = context->class_inst;
2751 g_assert (inst->type_argc);
2752 encode_ginst (acfg, inst, p, &p);
2754 encode_value (0, p, &p);
2756 inst = context->method_inst;
2758 g_assert (inst->type_argc);
2759 encode_ginst (acfg, inst, p, &p);
2761 encode_value (0, p, &p);
2767 encode_type (MonoAotCompile *acfg, MonoType *t, guint8 *buf, guint8 **endbuf)
2771 g_assert (t->num_mods == 0);
2772 /* t->attrs can be ignored */
2773 //g_assert (t->attrs == 0);
2776 *p = MONO_TYPE_PINNED;
2780 *p = MONO_TYPE_BYREF;
2788 case MONO_TYPE_VOID:
2789 case MONO_TYPE_BOOLEAN:
2790 case MONO_TYPE_CHAR:
2803 case MONO_TYPE_STRING:
2804 case MONO_TYPE_OBJECT:
2805 case MONO_TYPE_TYPEDBYREF:
2807 case MONO_TYPE_VALUETYPE:
2808 case MONO_TYPE_CLASS:
2809 encode_klass_ref (acfg, mono_class_from_mono_type (t), p, &p);
2811 case MONO_TYPE_SZARRAY:
2812 encode_klass_ref (acfg, t->data.klass, p, &p);
2815 encode_type (acfg, t->data.type, p, &p);
2817 case MONO_TYPE_GENERICINST: {
2818 MonoClass *gclass = t->data.generic_class->container_class;
2819 MonoGenericInst *inst = t->data.generic_class->context.class_inst;
2821 encode_klass_ref (acfg, gclass, p, &p);
2822 encode_ginst (acfg, inst, p, &p);
2825 case MONO_TYPE_ARRAY: {
2826 MonoArrayType *array = t->data.array;
2829 encode_klass_ref (acfg, array->eklass, p, &p);
2830 encode_value (array->rank, p, &p);
2831 encode_value (array->numsizes, p, &p);
2832 for (i = 0; i < array->numsizes; ++i)
2833 encode_value (array->sizes [i], p, &p);
2834 encode_value (array->numlobounds, p, &p);
2835 for (i = 0; i < array->numlobounds; ++i)
2836 encode_value (array->lobounds [i], p, &p);
2840 case MONO_TYPE_MVAR:
2841 encode_klass_ref (acfg, mono_class_from_mono_type (t), p, &p);
2844 g_assert_not_reached ();
2851 encode_signature (MonoAotCompile *acfg, MonoMethodSignature *sig, guint8 *buf, guint8 **endbuf)
2857 /* Similar to the metadata encoding */
2858 if (sig->generic_param_count)
2862 if (sig->explicit_this)
2864 flags |= (sig->call_convention & 0x0F);
2868 if (sig->generic_param_count)
2869 encode_value (sig->generic_param_count, p, &p);
2870 encode_value (sig->param_count, p, &p);
2872 encode_type (acfg, sig->ret, p, &p);
2873 for (i = 0; i < sig->param_count; ++i) {
2874 if (sig->sentinelpos == i) {
2875 *p = MONO_TYPE_SENTINEL;
2878 encode_type (acfg, sig->params [i], p, &p);
2884 #define MAX_IMAGE_INDEX 250
2887 encode_method_ref (MonoAotCompile *acfg, MonoMethod *method, guint8 *buf, guint8 **endbuf)
2889 guint32 image_index = get_image_index (acfg, method->klass->image);
2890 guint32 token = method->token;
2891 MonoJumpInfoToken *ji;
2895 * The encoding for most methods is as follows:
2896 * - image index encoded as a leb128
2897 * - token index encoded as a leb128
2898 * Values of image index >= MONO_AOT_METHODREF_MIN are used to mark additional
2899 * types of method encodings.
2902 /* Mark methods which can't use aot trampolines because they need the further
2903 * processing in mono_magic_trampoline () which requires a MonoMethod*.
2905 if ((method->is_generic && (method->flags & METHOD_ATTRIBUTE_VIRTUAL)) ||
2906 (method->iflags & METHOD_IMPL_ATTRIBUTE_SYNCHRONIZED))
2907 encode_value ((MONO_AOT_METHODREF_NO_AOT_TRAMPOLINE << 24), p, &p);
2909 if (method->wrapper_type) {
2910 encode_value ((MONO_AOT_METHODREF_WRAPPER << 24), p, &p);
2912 encode_value (method->wrapper_type, p, &p);
2914 switch (method->wrapper_type) {
2915 case MONO_WRAPPER_REMOTING_INVOKE:
2916 case MONO_WRAPPER_REMOTING_INVOKE_WITH_CHECK:
2917 case MONO_WRAPPER_XDOMAIN_INVOKE: {
2920 m = mono_marshal_method_from_wrapper (method);
2922 encode_method_ref (acfg, m, p, &p);
2925 case MONO_WRAPPER_PROXY_ISINST:
2926 case MONO_WRAPPER_LDFLD:
2927 case MONO_WRAPPER_LDFLDA:
2928 case MONO_WRAPPER_STFLD:
2929 case MONO_WRAPPER_ISINST: {
2930 WrapperInfo *info = mono_marshal_get_wrapper_info (method);
2933 encode_klass_ref (acfg, info->d.proxy.klass, p, &p);
2936 case MONO_WRAPPER_LDFLD_REMOTE:
2937 case MONO_WRAPPER_STFLD_REMOTE:
2939 case MONO_WRAPPER_ALLOC: {
2940 AllocatorWrapperInfo *info = mono_marshal_get_wrapper_info (method);
2942 /* The GC name is saved once in MonoAotFileInfo */
2943 g_assert (info->alloc_type != -1);
2944 encode_value (info->alloc_type, p, &p);
2947 case MONO_WRAPPER_WRITE_BARRIER:
2949 case MONO_WRAPPER_STELEMREF: {
2950 WrapperInfo *info = mono_marshal_get_wrapper_info (method);
2953 encode_value (info->subtype, p, &p);
2954 if (info->subtype == WRAPPER_SUBTYPE_VIRTUAL_STELEMREF)
2955 encode_value (info->d.virtual_stelemref.kind, p, &p);
2958 case MONO_WRAPPER_UNKNOWN: {
2959 WrapperInfo *info = mono_marshal_get_wrapper_info (method);
2962 encode_value (info->subtype, p, &p);
2963 if (info->subtype == WRAPPER_SUBTYPE_PTR_TO_STRUCTURE ||
2964 info->subtype == WRAPPER_SUBTYPE_STRUCTURE_TO_PTR)
2965 encode_klass_ref (acfg, method->klass, p, &p);
2966 else if (info->subtype == WRAPPER_SUBTYPE_SYNCHRONIZED_INNER)
2967 encode_method_ref (acfg, info->d.synchronized_inner.method, p, &p);
2968 else if (info->subtype == WRAPPER_SUBTYPE_ARRAY_ACCESSOR)
2969 encode_method_ref (acfg, info->d.array_accessor.method, p, &p);
2972 case MONO_WRAPPER_MANAGED_TO_NATIVE: {
2973 WrapperInfo *info = mono_marshal_get_wrapper_info (method);
2976 encode_value (info->subtype, p, &p);
2977 if (info->subtype == WRAPPER_SUBTYPE_ICALL_WRAPPER) {
2978 strcpy ((char*)p, method->name);
2979 p += strlen (method->name) + 1;
2980 } else if (info->subtype == WRAPPER_SUBTYPE_NATIVE_FUNC_AOT) {
2981 encode_method_ref (acfg, info->d.managed_to_native.method, p, &p);
2983 g_assert (info->subtype == WRAPPER_SUBTYPE_NONE || info->subtype == WRAPPER_SUBTYPE_PINVOKE);
2984 encode_method_ref (acfg, info->d.managed_to_native.method, p, &p);
2988 case MONO_WRAPPER_SYNCHRONIZED: {
2991 m = mono_marshal_method_from_wrapper (method);
2993 g_assert (m != method);
2994 encode_method_ref (acfg, m, p, &p);
2997 case MONO_WRAPPER_MANAGED_TO_MANAGED: {
2998 WrapperInfo *info = mono_marshal_get_wrapper_info (method);
3001 encode_value (info->subtype, p, &p);
3003 if (info->subtype == WRAPPER_SUBTYPE_ELEMENT_ADDR) {
3004 encode_value (info->d.element_addr.rank, p, &p);
3005 encode_value (info->d.element_addr.elem_size, p, &p);
3006 } else if (info->subtype == WRAPPER_SUBTYPE_STRING_CTOR) {
3007 encode_method_ref (acfg, info->d.string_ctor.method, p, &p);
3009 g_assert_not_reached ();
3013 case MONO_WRAPPER_CASTCLASS: {
3014 WrapperInfo *info = mono_marshal_get_wrapper_info (method);
3017 encode_value (info->subtype, p, &p);
3020 case MONO_WRAPPER_RUNTIME_INVOKE: {
3021 WrapperInfo *info = mono_marshal_get_wrapper_info (method);
3024 encode_value (info->subtype, p, &p);
3025 if (info->subtype == WRAPPER_SUBTYPE_RUNTIME_INVOKE_DIRECT || info->subtype == WRAPPER_SUBTYPE_RUNTIME_INVOKE_VIRTUAL)
3026 encode_method_ref (acfg, info->d.runtime_invoke.method, p, &p);
3027 else if (info->subtype == WRAPPER_SUBTYPE_RUNTIME_INVOKE_NORMAL)
3028 encode_signature (acfg, info->d.runtime_invoke.sig, p, &p);
3031 case MONO_WRAPPER_DELEGATE_INVOKE:
3032 case MONO_WRAPPER_DELEGATE_BEGIN_INVOKE:
3033 case MONO_WRAPPER_DELEGATE_END_INVOKE: {
3034 if (method->is_inflated) {
3035 /* These wrappers are identified by their class */
3036 encode_value (1, p, &p);
3037 encode_klass_ref (acfg, method->klass, p, &p);
3039 MonoMethodSignature *sig = mono_method_signature (method);
3040 WrapperInfo *info = mono_marshal_get_wrapper_info (method);
3042 encode_value (0, p, &p);
3043 if (method->wrapper_type == MONO_WRAPPER_DELEGATE_INVOKE)
3044 encode_value (info ? info->subtype : 0, p, &p);
3045 encode_signature (acfg, sig, p, &p);
3049 case MONO_WRAPPER_NATIVE_TO_MANAGED: {
3050 WrapperInfo *info = mono_marshal_get_wrapper_info (method);
3053 encode_method_ref (acfg, info->d.native_to_managed.method, p, &p);
3054 encode_klass_ref (acfg, info->d.native_to_managed.klass, p, &p);
3058 g_assert_not_reached ();
3060 } else if (mono_method_signature (method)->is_inflated) {
3062 * This is a generic method, find the original token which referenced it and
3064 * Obtain the token from information recorded by the JIT.
3066 ji = g_hash_table_lookup (acfg->token_info_hash, method);
3068 image_index = get_image_index (acfg, ji->image);
3069 g_assert (image_index < MAX_IMAGE_INDEX);
3072 encode_value ((MONO_AOT_METHODREF_METHODSPEC << 24), p, &p);
3073 encode_value (image_index, p, &p);
3074 encode_value (token, p, &p);
3076 MonoMethod *declaring;
3077 MonoGenericContext *context = mono_method_get_context (method);
3079 g_assert (method->is_inflated);
3080 declaring = ((MonoMethodInflated*)method)->declaring;
3083 * This might be a non-generic method of a generic instance, which
3084 * doesn't have a token since the reference is generated by the JIT
3085 * like Nullable:Box/Unbox, or by generic sharing.
3087 encode_value ((MONO_AOT_METHODREF_GINST << 24), p, &p);
3088 /* Encode the klass */
3089 encode_klass_ref (acfg, method->klass, p, &p);
3090 /* Encode the method */
3091 image_index = get_image_index (acfg, method->klass->image);
3092 g_assert (image_index < MAX_IMAGE_INDEX);
3093 g_assert (declaring->token);
3094 token = declaring->token;
3095 g_assert (mono_metadata_token_table (token) == MONO_TABLE_METHOD);
3096 encode_value (image_index, p, &p);
3097 encode_value (token, p, &p);
3098 encode_generic_context (acfg, context, p, &p);
3100 } else if (token == 0) {
3101 /* This might be a method of a constructed type like int[,].Set */
3102 /* Obtain the token from information recorded by the JIT */
3103 ji = g_hash_table_lookup (acfg->token_info_hash, method);
3105 image_index = get_image_index (acfg, ji->image);
3106 g_assert (image_index < MAX_IMAGE_INDEX);
3109 encode_value ((MONO_AOT_METHODREF_METHODSPEC << 24), p, &p);
3110 encode_value (image_index, p, &p);
3111 encode_value (token, p, &p);
3114 g_assert (method->klass->rank);
3116 /* Encode directly */
3117 encode_value ((MONO_AOT_METHODREF_ARRAY << 24), p, &p);
3118 encode_klass_ref (acfg, method->klass, p, &p);
3119 if (!strcmp (method->name, ".ctor") && mono_method_signature (method)->param_count == method->klass->rank)
3120 encode_value (0, p, &p);
3121 else if (!strcmp (method->name, ".ctor") && mono_method_signature (method)->param_count == method->klass->rank * 2)
3122 encode_value (1, p, &p);
3123 else if (!strcmp (method->name, "Get"))
3124 encode_value (2, p, &p);
3125 else if (!strcmp (method->name, "Address"))
3126 encode_value (3, p, &p);
3127 else if (!strcmp (method->name, "Set"))
3128 encode_value (4, p, &p);
3130 g_assert_not_reached ();
3133 g_assert (mono_metadata_token_table (token) == MONO_TABLE_METHOD);
3135 if (image_index >= MONO_AOT_METHODREF_MIN) {
3136 encode_value ((MONO_AOT_METHODREF_LARGE_IMAGE_INDEX << 24), p, &p);
3137 encode_value (image_index, p, &p);
3138 encode_value (mono_metadata_token_index (token), p, &p);
3140 encode_value ((image_index << 24) | mono_metadata_token_index (token), p, &p);
3147 compare_patches (gconstpointer a, gconstpointer b)
3151 i = (*(MonoJumpInfo**)a)->ip.i;
3152 j = (*(MonoJumpInfo**)b)->ip.i;
3163 static G_GNUC_UNUSED char*
3164 patch_to_string (MonoJumpInfo *patch_info)
3168 str = g_string_new ("");
3170 g_string_append_printf (str, "%s(", get_patch_name (patch_info->type));
3172 switch (patch_info->type) {
3173 case MONO_PATCH_INFO_VTABLE:
3174 mono_type_get_desc (str, &patch_info->data.klass->byval_arg, TRUE);
3179 g_string_append_printf (str, ")");
3180 return g_string_free (str, FALSE);
3186 * Return whenever PATCH_INFO refers to a direct call, and thus requires a
3189 static inline gboolean
3190 is_plt_patch (MonoJumpInfo *patch_info)
3192 switch (patch_info->type) {
3193 case MONO_PATCH_INFO_METHOD:
3194 case MONO_PATCH_INFO_INTERNAL_METHOD:
3195 case MONO_PATCH_INFO_JIT_ICALL_ADDR:
3196 case MONO_PATCH_INFO_ICALL_ADDR:
3197 case MONO_PATCH_INFO_RGCTX_FETCH:
3198 case MONO_PATCH_INFO_LLVM_IMT_TRAMPOLINE:
3208 * Return the symbol identifying the plt entry PLT_OFFSET.
3211 get_plt_symbol (MonoAotCompile *acfg, int plt_offset, MonoJumpInfo *patch_info)
3215 * The Apple linker reorganizes object files, so it doesn't like branches to local
3216 * labels, since those have no relocations.
3218 return g_strdup_printf ("%sp_%d", acfg->llvm_label_prefix, plt_offset);
3220 return g_strdup_printf ("%sp_%d", acfg->temp_prefix, plt_offset);
3227 * Return a PLT entry which belongs to the method identified by PATCH_INFO.
3229 static MonoPltEntry*
3230 get_plt_entry (MonoAotCompile *acfg, MonoJumpInfo *patch_info)
3233 gboolean synchronized = FALSE;
3234 static int synchronized_symbol_idx;
3236 if (!is_plt_patch (patch_info))
3239 if (!acfg->patch_to_plt_entry [patch_info->type])
3240 acfg->patch_to_plt_entry [patch_info->type] = g_hash_table_new (mono_patch_info_hash, mono_patch_info_equal);
3241 res = g_hash_table_lookup (acfg->patch_to_plt_entry [patch_info->type], patch_info);
3243 if (!acfg->llvm && patch_info->type == MONO_PATCH_INFO_METHOD && (patch_info->data.method->iflags & METHOD_IMPL_ATTRIBUTE_SYNCHRONIZED)) {
3245 * Allocate a separate PLT slot for each such patch, since some plt
3246 * entries will refer to the method itself, and some will refer to the
3250 synchronized = TRUE;
3254 MonoJumpInfo *new_ji;
3256 new_ji = mono_patch_info_dup_mp (acfg->mempool, patch_info);
3258 res = mono_mempool_alloc0 (acfg->mempool, sizeof (MonoPltEntry));
3259 res->plt_offset = acfg->plt_offset;
3261 res->symbol = get_plt_symbol (acfg, res->plt_offset, patch_info);
3262 if (acfg->aot_opts.write_symbols)
3263 res->debug_sym = get_plt_entry_debug_sym (acfg, res->ji, acfg->plt_entry_debug_sym_cache);
3265 /* Avoid duplicate symbols because we don't cache */
3266 res->symbol = g_strdup_printf ("%s_%d", res->symbol, synchronized_symbol_idx);
3268 res->debug_sym = g_strdup_printf ("%s_%d", res->debug_sym, synchronized_symbol_idx);
3269 synchronized_symbol_idx ++;
3272 res->llvm_symbol = g_strdup_printf ("%s_%s_llvm", res->symbol, res->debug_sym);
3274 res->llvm_symbol = g_strdup_printf ("%s_llvm", res->symbol);
3276 g_hash_table_insert (acfg->patch_to_plt_entry [new_ji->type], new_ji, res);
3278 g_hash_table_insert (acfg->plt_offset_to_entry, GUINT_TO_POINTER (res->plt_offset), res);
3280 //g_assert (mono_patch_info_equal (patch_info, new_ji));
3281 //mono_print_ji (patch_info); printf ("\n");
3282 //g_hash_table_print_stats (acfg->patch_to_plt_entry);
3284 acfg->plt_offset ++;
3293 * Returns the offset of the GOT slot where the runtime object resulting from resolving
3294 * JI could be found if it exists, otherwise allocates a new one.
3297 get_got_offset (MonoAotCompile *acfg, gboolean llvm, MonoJumpInfo *ji)
3300 GotInfo *info = llvm ? &acfg->llvm_got_info : &acfg->got_info;
3302 got_offset = GPOINTER_TO_UINT (g_hash_table_lookup (info->patch_to_got_offset_by_type [ji->type], ji));
3304 return got_offset - 1;
3307 got_offset = acfg->llvm_got_offset;
3308 acfg->llvm_got_offset ++;
3310 got_offset = acfg->got_offset;
3311 acfg->got_offset ++;
3314 acfg->stats.got_slots ++;
3315 acfg->stats.got_slot_types [ji->type] ++;
3317 g_hash_table_insert (info->patch_to_got_offset, ji, GUINT_TO_POINTER (got_offset + 1));
3318 g_hash_table_insert (info->patch_to_got_offset_by_type [ji->type], ji, GUINT_TO_POINTER (got_offset + 1));
3319 g_ptr_array_add (info->got_patches, ji);
3324 /* Add a method to the list of methods which need to be emitted */
3326 add_method_with_index (MonoAotCompile *acfg, MonoMethod *method, int index, gboolean extra)
3329 if (!g_hash_table_lookup (acfg->method_indexes, method)) {
3330 g_ptr_array_add (acfg->methods, method);
3331 g_hash_table_insert (acfg->method_indexes, method, GUINT_TO_POINTER (index + 1));
3332 acfg->nmethods = acfg->methods->len + 1;
3335 if (method->wrapper_type || extra)
3336 g_ptr_array_add (acfg->extra_methods, method);
3340 prefer_gsharedvt_method (MonoAotCompile *acfg, MonoMethod *method)
3342 /* One instantiation with valuetypes is generated for each async method */
3343 if (method->klass->image == mono_defaults.corlib && (!strcmp (method->klass->name, "AsyncMethodBuilderCore") || !strcmp (method->klass->name, "AsyncVoidMethodBuilder")))
3350 get_method_index (MonoAotCompile *acfg, MonoMethod *method)
3352 int index = GPOINTER_TO_UINT (g_hash_table_lookup (acfg->method_indexes, method));
3360 add_method_full (MonoAotCompile *acfg, MonoMethod *method, gboolean extra, int depth)
3364 index = GPOINTER_TO_UINT (g_hash_table_lookup (acfg->method_indexes, method));
3368 index = acfg->method_index;
3369 add_method_with_index (acfg, method, index, extra);
3371 g_ptr_array_add (acfg->method_order, GUINT_TO_POINTER (index));
3373 g_hash_table_insert (acfg->method_depth, method, GUINT_TO_POINTER (depth));
3375 acfg->method_index ++;
3381 add_method (MonoAotCompile *acfg, MonoMethod *method)
3383 return add_method_full (acfg, method, FALSE, 0);
3387 add_extra_method_with_depth (MonoAotCompile *acfg, MonoMethod *method, int depth)
3389 if (mono_method_is_generic_sharable_full (method, TRUE, TRUE, FALSE))
3390 method = mini_get_shared_method (method);
3391 else if ((acfg->opts & MONO_OPT_GSHAREDVT) && prefer_gsharedvt_method (acfg, method) && mono_method_is_generic_sharable_full (method, FALSE, FALSE, TRUE))
3392 /* Use the gsharedvt version */
3393 method = mini_get_shared_method_full (method, TRUE, TRUE);
3395 if (acfg->aot_opts.log_generics)
3396 aot_printf (acfg, "%*sAdding method %s.\n", depth, "", mono_method_full_name (method, TRUE));
3398 add_method_full (acfg, method, TRUE, depth);
3402 add_extra_method (MonoAotCompile *acfg, MonoMethod *method)
3404 add_extra_method_with_depth (acfg, method, 0);
3408 add_jit_icall_wrapper (gpointer key, gpointer value, gpointer user_data)
3410 MonoAotCompile *acfg = user_data;
3411 MonoJitICallInfo *callinfo = value;
3412 MonoMethod *wrapper;
3418 name = g_strdup_printf ("__icall_wrapper_%s", callinfo->name);
3419 wrapper = mono_marshal_get_icall_wrapper (callinfo->sig, name, callinfo->func, TRUE);
3422 add_method (acfg, wrapper);
3426 get_runtime_invoke_sig (MonoMethodSignature *sig)
3428 MonoMethodBuilder *mb;
3431 mb = mono_mb_new (mono_defaults.object_class, "FOO", MONO_WRAPPER_NONE);
3432 m = mono_mb_create_method (mb, sig, 16);
3433 return mono_marshal_get_runtime_invoke (m, FALSE);
3437 can_marshal_struct (MonoClass *klass)
3439 MonoClassField *field;
3440 gboolean can_marshal = TRUE;
3441 gpointer iter = NULL;
3442 MonoMarshalType *info;
3445 if ((klass->flags & TYPE_ATTRIBUTE_LAYOUT_MASK) == TYPE_ATTRIBUTE_AUTO_LAYOUT)
3448 info = mono_marshal_load_type_info (klass);
3450 /* Only allow a few field types to avoid asserts in the marshalling code */
3451 while ((field = mono_class_get_fields (klass, &iter))) {
3452 if ((field->type->attrs & FIELD_ATTRIBUTE_STATIC))
3455 switch (field->type->type) {
3460 case MONO_TYPE_BOOLEAN:
3463 case MONO_TYPE_CHAR:
3471 case MONO_TYPE_STRING:
3473 case MONO_TYPE_VALUETYPE:
3474 if (!mono_class_from_mono_type (field->type)->enumtype && !can_marshal_struct (mono_class_from_mono_type (field->type)))
3475 can_marshal = FALSE;
3477 case MONO_TYPE_SZARRAY: {
3478 gboolean has_mspec = FALSE;
3481 for (i = 0; i < info->num_fields; ++i) {
3482 if (info->fields [i].field == field && info->fields [i].mspec)
3487 can_marshal = FALSE;
3491 can_marshal = FALSE;
3497 /* Its hard to compute whenever these can be marshalled or not */
3498 if (!strcmp (klass->name_space, "System.Net.NetworkInformation.MacOsStructs") && strcmp (klass->name, "sockaddr_dl"))
3505 create_gsharedvt_inst (MonoAotCompile *acfg, MonoMethod *method, MonoGenericContext *ctx)
3507 /* Create a vtype instantiation */
3508 MonoGenericContext shared_context;
3510 MonoGenericInst *inst;
3511 MonoGenericContainer *container;
3512 MonoClass **constraints;
3515 memset (ctx, 0, sizeof (MonoGenericContext));
3517 if (method->klass->generic_container) {
3518 shared_context = method->klass->generic_container->context;
3519 inst = shared_context.class_inst;
3521 args = g_new0 (MonoType*, inst->type_argc);
3522 for (i = 0; i < inst->type_argc; ++i) {
3523 args [i] = &mono_defaults.int_class->byval_arg;
3525 ctx->class_inst = mono_metadata_get_generic_inst (inst->type_argc, args);
3527 if (method->is_generic) {
3528 container = mono_method_get_generic_container (method);
3529 shared_context = container->context;
3530 inst = shared_context.method_inst;
3532 args = g_new0 (MonoType*, inst->type_argc);
3533 for (i = 0; i < container->type_argc; ++i) {
3534 MonoGenericParamInfo *info = &container->type_params [i].info;
3535 gboolean ref_only = FALSE;
3537 if (info && info->constraints) {
3538 constraints = info->constraints;
3540 while (*constraints) {
3541 MonoClass *cklass = *constraints;
3542 if (!(cklass == mono_defaults.object_class || (cklass->image == mono_defaults.corlib && !strcmp (cklass->name, "ValueType"))))
3543 /* Inflaring the method with our vtype would not be valid */
3550 args [i] = &mono_defaults.object_class->byval_arg;
3552 args [i] = &mono_defaults.int_class->byval_arg;
3554 ctx->method_inst = mono_metadata_get_generic_inst (inst->type_argc, args);
3559 add_wrappers (MonoAotCompile *acfg)
3561 MonoMethod *method, *m;
3563 MonoMethodSignature *sig, *csig;
3567 * FIXME: Instead of AOTing all the wrappers, it might be better to redesign them
3568 * so there is only one wrapper of a given type, or inlining their contents into their
3571 for (i = 0; i < acfg->image->tables [MONO_TABLE_METHOD].rows; ++i) {
3574 guint32 token = MONO_TOKEN_METHOD_DEF | (i + 1);
3575 gboolean skip = FALSE;
3577 method = mono_get_method_checked (acfg->image, token, NULL, NULL, &error);
3578 report_loader_error (acfg, &error, "Failed to load method token 0x%x due to %s\n", i, mono_error_get_message (&error));
3580 if ((method->flags & METHOD_ATTRIBUTE_PINVOKE_IMPL) ||
3581 (method->iflags & METHOD_IMPL_ATTRIBUTE_RUNTIME) ||
3582 (method->flags & METHOD_ATTRIBUTE_ABSTRACT))
3585 /* Skip methods which can not be handled by get_runtime_invoke () */
3586 sig = mono_method_signature (method);
3589 if ((sig->ret->type == MONO_TYPE_PTR) ||
3590 (sig->ret->type == MONO_TYPE_TYPEDBYREF))
3592 if (mono_class_is_open_constructed_type (sig->ret))
3595 for (j = 0; j < sig->param_count; j++) {
3596 if (sig->params [j]->type == MONO_TYPE_TYPEDBYREF)
3598 if (mono_class_is_open_constructed_type (sig->params [j]))
3602 #ifdef MONO_ARCH_DYN_CALL_SUPPORTED
3603 if (!mono_class_is_contextbound (method->klass)) {
3604 MonoDynCallInfo *info = mono_arch_dyn_call_prepare (sig);
3605 gboolean has_nullable = FALSE;
3607 for (j = 0; j < sig->param_count; j++) {
3608 if (sig->params [j]->type == MONO_TYPE_GENERICINST && mono_class_is_nullable (mono_class_from_mono_type (sig->params [j])))
3609 has_nullable = TRUE;
3612 if (info && !has_nullable) {
3613 /* Supported by the dynamic runtime-invoke wrapper */
3617 mono_arch_dyn_call_free (info);
3622 //printf ("%s\n", mono_method_full_name (method, TRUE));
3623 add_method (acfg, mono_marshal_get_runtime_invoke (method, FALSE));
3627 if (strcmp (acfg->image->assembly->aname.name, "mscorlib") == 0) {
3630 /* Runtime invoke wrappers */
3632 /* void runtime-invoke () [.cctor] */
3633 csig = mono_metadata_signature_alloc (mono_defaults.corlib, 0);
3634 csig->ret = &mono_defaults.void_class->byval_arg;
3635 add_method (acfg, get_runtime_invoke_sig (csig));
3637 /* void runtime-invoke () [Finalize] */
3638 csig = mono_metadata_signature_alloc (mono_defaults.corlib, 0);
3640 csig->ret = &mono_defaults.void_class->byval_arg;
3641 add_method (acfg, get_runtime_invoke_sig (csig));
3643 /* void runtime-invoke (string) [exception ctor] */
3644 csig = mono_metadata_signature_alloc (mono_defaults.corlib, 1);
3646 csig->ret = &mono_defaults.void_class->byval_arg;
3647 csig->params [0] = &mono_defaults.string_class->byval_arg;
3648 add_method (acfg, get_runtime_invoke_sig (csig));
3650 /* void runtime-invoke (string, string) [exception ctor] */
3651 csig = mono_metadata_signature_alloc (mono_defaults.corlib, 2);
3653 csig->ret = &mono_defaults.void_class->byval_arg;
3654 csig->params [0] = &mono_defaults.string_class->byval_arg;
3655 csig->params [1] = &mono_defaults.string_class->byval_arg;
3656 add_method (acfg, get_runtime_invoke_sig (csig));
3658 /* string runtime-invoke () [Exception.ToString ()] */
3659 csig = mono_metadata_signature_alloc (mono_defaults.corlib, 0);
3661 csig->ret = &mono_defaults.string_class->byval_arg;
3662 add_method (acfg, get_runtime_invoke_sig (csig));
3664 /* void runtime-invoke (string, Exception) [exception ctor] */
3665 csig = mono_metadata_signature_alloc (mono_defaults.corlib, 2);
3667 csig->ret = &mono_defaults.void_class->byval_arg;
3668 csig->params [0] = &mono_defaults.string_class->byval_arg;
3669 csig->params [1] = &mono_defaults.exception_class->byval_arg;
3670 add_method (acfg, get_runtime_invoke_sig (csig));
3672 /* Assembly runtime-invoke (string, bool) [DoAssemblyResolve] */
3673 csig = mono_metadata_signature_alloc (mono_defaults.corlib, 2);
3675 csig->ret = &(mono_class_from_name (
3676 mono_defaults.corlib, "System.Reflection", "Assembly"))->byval_arg;
3677 csig->params [0] = &mono_defaults.string_class->byval_arg;
3678 csig->params [1] = &mono_defaults.boolean_class->byval_arg;
3679 add_method (acfg, get_runtime_invoke_sig (csig));
3681 /* runtime-invoke used by finalizers */
3682 add_method (acfg, mono_marshal_get_runtime_invoke (mono_class_get_method_from_name_flags (mono_defaults.object_class, "Finalize", 0, 0), TRUE));
3684 /* This is used by mono_runtime_capture_context () */
3685 method = mono_get_context_capture_method ();
3687 add_method (acfg, mono_marshal_get_runtime_invoke (method, FALSE));
3689 #ifdef MONO_ARCH_DYN_CALL_SUPPORTED
3690 add_method (acfg, mono_marshal_get_runtime_invoke_dynamic ());
3694 add_method (acfg, mono_marshal_get_stelemref ());
3696 if (MONO_ARCH_HAVE_TLS_GET) {
3697 /* Managed Allocators */
3698 nallocators = mono_gc_get_managed_allocator_types ();
3699 for (i = 0; i < nallocators; ++i) {
3700 m = mono_gc_get_managed_allocator_by_type (i, TRUE);
3702 add_method (acfg, m);
3704 for (i = 0; i < nallocators; ++i) {
3705 m = mono_gc_get_managed_allocator_by_type (i, FALSE);
3707 add_method (acfg, m);
3711 /* write barriers */
3712 if (mono_gc_is_moving ()) {
3713 add_method (acfg, mono_gc_get_specific_write_barrier (FALSE));
3714 add_method (acfg, mono_gc_get_specific_write_barrier (TRUE));
3717 /* Stelemref wrappers */
3719 MonoMethod **wrappers;
3722 wrappers = mono_marshal_get_virtual_stelemref_wrappers (&nwrappers);
3723 for (i = 0; i < nwrappers; ++i)
3724 add_method (acfg, wrappers [i]);
3728 /* castclass_with_check wrapper */
3729 add_method (acfg, mono_marshal_get_castclass_with_cache ());
3730 /* isinst_with_check wrapper */
3731 add_method (acfg, mono_marshal_get_isinst_with_cache ());
3733 /* JIT icall wrappers */
3734 /* FIXME: locking - this is "safe" as full-AOT threads don't mutate the icall hash*/
3735 g_hash_table_foreach (mono_get_jit_icall_info (), add_jit_icall_wrapper, acfg);
3739 * remoting-invoke-with-check wrappers are very frequent, so avoid emitting them,
3740 * we use the original method instead at runtime.
3741 * Since full-aot doesn't support remoting, this is not a problem.
3744 /* remoting-invoke wrappers */
3745 for (i = 0; i < acfg->image->tables [MONO_TABLE_METHOD].rows; ++i) {
3746 MonoMethodSignature *sig;
3748 token = MONO_TOKEN_METHOD_DEF | (i + 1);
3749 method = mono_get_method (acfg->image, token, NULL);
3751 sig = mono_method_signature (method);
3753 if (sig->hasthis && (method->klass->marshalbyref || method->klass == mono_defaults.object_class)) {
3754 m = mono_marshal_get_remoting_invoke_with_check (method);
3756 add_method (acfg, m);
3761 /* delegate-invoke wrappers */
3762 for (i = 0; i < acfg->image->tables [MONO_TABLE_TYPEDEF].rows; ++i) {
3765 MonoCustomAttrInfo *cattr;
3767 token = MONO_TOKEN_TYPE_DEF | (i + 1);
3768 klass = mono_class_get_checked (acfg->image, token, &error);
3771 mono_error_cleanup (&error);
3775 if (!klass->delegate || klass == mono_defaults.delegate_class || klass == mono_defaults.multicastdelegate_class)
3778 if (!klass->generic_container) {
3779 method = mono_get_delegate_invoke (klass);
3781 m = mono_marshal_get_delegate_invoke (method, NULL);
3783 add_method (acfg, m);
3785 method = mono_class_get_method_from_name_flags (klass, "BeginInvoke", -1, 0);
3787 add_method (acfg, mono_marshal_get_delegate_begin_invoke (method));
3789 method = mono_class_get_method_from_name_flags (klass, "EndInvoke", -1, 0);
3791 add_method (acfg, mono_marshal_get_delegate_end_invoke (method));
3793 cattr = mono_custom_attrs_from_class (klass);
3798 for (j = 0; j < cattr->num_attrs; ++j)
3799 if (cattr->attrs [j].ctor && (!strcmp (cattr->attrs [j].ctor->klass->name, "MonoNativeFunctionWrapperAttribute") || !strcmp (cattr->attrs [j].ctor->klass->name, "UnmanagedFunctionPointerAttribute")))
3801 if (j < cattr->num_attrs) {
3803 MonoMethod *wrapper;
3804 MonoMethod *del_invoke;
3806 /* Add wrappers needed by mono_ftnptr_to_delegate () */
3807 invoke = mono_get_delegate_invoke (klass);
3808 wrapper = mono_marshal_get_native_func_wrapper_aot (klass);
3809 del_invoke = mono_marshal_get_delegate_invoke_internal (invoke, FALSE, TRUE, wrapper);
3810 add_method (acfg, wrapper);
3811 add_method (acfg, del_invoke);
3814 } else if ((acfg->opts & MONO_OPT_GSHAREDVT) && klass->generic_container) {
3816 MonoGenericContext ctx;
3817 MonoMethod *inst, *gshared;
3820 * Emit gsharedvt versions of the generic delegate-invoke wrappers
3823 method = mono_get_delegate_invoke (klass);
3824 create_gsharedvt_inst (acfg, method, &ctx);
3826 inst = mono_class_inflate_generic_method_checked (method, &ctx, &error);
3827 g_assert (mono_error_ok (&error)); /* FIXME don't swallow the error */
3829 m = mono_marshal_get_delegate_invoke (inst, NULL);
3830 g_assert (m->is_inflated);
3832 gshared = mini_get_shared_method_full (m, FALSE, TRUE);
3833 add_extra_method (acfg, gshared);
3836 method = mono_get_delegate_begin_invoke (klass);
3837 create_gsharedvt_inst (acfg, method, &ctx);
3839 inst = mono_class_inflate_generic_method_checked (method, &ctx, &error);
3840 g_assert (mono_error_ok (&error)); /* FIXME don't swallow the error */
3842 m = mono_marshal_get_delegate_begin_invoke (inst);
3843 g_assert (m->is_inflated);
3845 gshared = mini_get_shared_method_full (m, FALSE, TRUE);
3846 add_extra_method (acfg, gshared);
3849 method = mono_get_delegate_end_invoke (klass);
3850 create_gsharedvt_inst (acfg, method, &ctx);
3852 inst = mono_class_inflate_generic_method_checked (method, &ctx, &error);
3853 g_assert (mono_error_ok (&error)); /* FIXME don't swallow the error */
3855 m = mono_marshal_get_delegate_end_invoke (inst);
3856 g_assert (m->is_inflated);
3858 gshared = mini_get_shared_method_full (m, FALSE, TRUE);
3859 add_extra_method (acfg, gshared);
3864 /* array access wrappers */
3865 for (i = 0; i < acfg->image->tables [MONO_TABLE_TYPESPEC].rows; ++i) {
3869 token = MONO_TOKEN_TYPE_SPEC | (i + 1);
3870 klass = mono_class_get_checked (acfg->image, token, &error);
3873 mono_error_cleanup (&error);
3877 if (klass->rank && MONO_TYPE_IS_PRIMITIVE (&klass->element_class->byval_arg)) {
3878 MonoMethod *m, *wrapper;
3880 /* Add runtime-invoke wrappers too */
3882 m = mono_class_get_method_from_name (klass, "Get", -1);
3884 wrapper = mono_marshal_get_array_accessor_wrapper (m);
3885 add_extra_method (acfg, wrapper);
3886 add_extra_method (acfg, mono_marshal_get_runtime_invoke (wrapper, FALSE));
3888 m = mono_class_get_method_from_name (klass, "Set", -1);
3890 wrapper = mono_marshal_get_array_accessor_wrapper (m);
3891 add_extra_method (acfg, wrapper);
3892 add_extra_method (acfg, mono_marshal_get_runtime_invoke (wrapper, FALSE));
3896 /* Synchronized wrappers */
3897 for (i = 0; i < acfg->image->tables [MONO_TABLE_METHOD].rows; ++i) {
3899 token = MONO_TOKEN_METHOD_DEF | (i + 1);
3900 method = mono_get_method_checked (acfg->image, token, NULL, NULL, &error);
3901 report_loader_error (acfg, &error, "Failed to load method token 0x%x due to %s\n", i, mono_error_get_message (&error));
3903 if (method->iflags & METHOD_IMPL_ATTRIBUTE_SYNCHRONIZED) {
3904 if (method->is_generic) {
3906 } else if ((acfg->opts & MONO_OPT_GSHAREDVT) && method->klass->generic_container) {
3908 MonoGenericContext ctx;
3909 MonoMethod *inst, *gshared, *m;
3912 * Create a generic wrapper for a generic instance, and AOT that.
3914 create_gsharedvt_inst (acfg, method, &ctx);
3915 inst = mono_class_inflate_generic_method_checked (method, &ctx, &error);
3916 g_assert (mono_error_ok (&error)); /* FIXME don't swallow the error */
3917 m = mono_marshal_get_synchronized_wrapper (inst);
3918 g_assert (m->is_inflated);
3919 gshared = mini_get_shared_method_full (m, FALSE, TRUE);
3920 add_method (acfg, gshared);
3922 add_method (acfg, mono_marshal_get_synchronized_wrapper (method));
3927 /* pinvoke wrappers */
3928 for (i = 0; i < acfg->image->tables [MONO_TABLE_METHOD].rows; ++i) {
3931 guint32 token = MONO_TOKEN_METHOD_DEF | (i + 1);
3933 method = mono_get_method_checked (acfg->image, token, NULL, NULL, &error);
3934 report_loader_error (acfg, &error, "Failed to load method token 0x%x due to %s\n", i, mono_error_get_message (&error));
3936 if ((method->flags & METHOD_ATTRIBUTE_PINVOKE_IMPL) ||
3937 (method->iflags & METHOD_IMPL_ATTRIBUTE_INTERNAL_CALL)) {
3938 add_method (acfg, mono_marshal_get_native_wrapper (method, TRUE, TRUE));
3942 /* native-to-managed wrappers */
3943 for (i = 0; i < acfg->image->tables [MONO_TABLE_METHOD].rows; ++i) {
3946 guint32 token = MONO_TOKEN_METHOD_DEF | (i + 1);
3947 MonoCustomAttrInfo *cattr;
3950 method = mono_get_method_checked (acfg->image, token, NULL, NULL, &error);
3951 report_loader_error (acfg, &error, "Failed to load method token 0x%x due to %s\n", i, mono_error_get_message (&error));
3954 * Only generate native-to-managed wrappers for methods which have an
3955 * attribute named MonoPInvokeCallbackAttribute. We search for the attribute by
3956 * name to avoid defining a new assembly to contain it.
3958 cattr = mono_custom_attrs_from_method (method);
3961 for (j = 0; j < cattr->num_attrs; ++j)
3962 if (cattr->attrs [j].ctor && !strcmp (cattr->attrs [j].ctor->klass->name, "MonoPInvokeCallbackAttribute"))
3964 if (j < cattr->num_attrs) {
3965 MonoCustomAttrEntry *e = &cattr->attrs [j];
3966 MonoMethodSignature *sig = mono_method_signature (e->ctor);
3967 const char *p = (const char*)e->data;
3969 int slen, num_named, named_type;
3973 char *export_name = NULL;
3974 MonoMethod *wrapper;
3976 /* this cannot be enforced by the C# compiler so we must give the user some warning before aborting */
3977 if (!(method->flags & METHOD_ATTRIBUTE_STATIC)) {
3978 g_warning ("AOT restriction: Method '%s' must be static since it is decorated with [MonoPInvokeCallback]. See http://ios.xamarin.com/Documentation/Limitations#Reverse_Callbacks",
3979 mono_method_full_name (method, TRUE));
3983 g_assert (sig->param_count == 1);
3984 g_assert (sig->params [0]->type == MONO_TYPE_CLASS && !strcmp (mono_class_from_mono_type (sig->params [0])->name, "Type"));
3987 * Decode the cattr manually since we can't create objects
3988 * during aot compilation.
3994 /* From load_cattr_value () in reflection.c */
3995 slen = mono_metadata_decode_value (p, &p);
3996 n = g_memdup (p, slen + 1);
3998 t = mono_reflection_type_from_name (n, acfg->image);
4002 klass = mono_class_from_mono_type (t);
4003 g_assert (klass->parent == mono_defaults.multicastdelegate_class);
4007 num_named = read16 (p);
4010 g_assert (num_named < 2);
4011 if (num_named == 1) {
4015 /* parse ExportSymbol attribute */
4017 named_type = *named;
4019 /* data_type = *named; */
4022 name_len = mono_metadata_decode_blob_size (named, &named);
4023 name = g_malloc (name_len + 1);
4024 memcpy (name, named, name_len);
4025 name [name_len] = 0;
4028 g_assert (named_type == 0x54);
4029 g_assert (!strcmp (name, "ExportSymbol"));
4031 /* load_cattr_value (), string case */
4032 g_assert (*named != (char)0xff);
4033 slen = mono_metadata_decode_value (named, &named);
4034 export_name = g_malloc (slen + 1);
4035 memcpy (export_name, named, slen);
4036 export_name [slen] = 0;
4040 wrapper = mono_marshal_get_managed_wrapper (method, klass, 0);
4041 add_method (acfg, wrapper);
4043 g_hash_table_insert (acfg->export_names, wrapper, export_name);
4047 if ((method->flags & METHOD_ATTRIBUTE_PINVOKE_IMPL) ||
4048 (method->iflags & METHOD_IMPL_ATTRIBUTE_INTERNAL_CALL)) {
4049 add_method (acfg, mono_marshal_get_native_wrapper (method, TRUE, TRUE));
4053 /* StructureToPtr/PtrToStructure wrappers */
4054 for (i = 0; i < acfg->image->tables [MONO_TABLE_TYPEDEF].rows; ++i) {
4058 token = MONO_TOKEN_TYPE_DEF | (i + 1);
4059 klass = mono_class_get_checked (acfg->image, token, &error);
4062 mono_error_cleanup (&error);
4066 if (klass->valuetype && !klass->generic_container && can_marshal_struct (klass) &&
4067 !(klass->nested_in && strstr (klass->nested_in->name, "<PrivateImplementationDetails>") == klass->nested_in->name)) {
4068 add_method (acfg, mono_marshal_get_struct_to_ptr (klass));
4069 add_method (acfg, mono_marshal_get_ptr_to_struct (klass));
4075 has_type_vars (MonoClass *klass)
4077 if ((klass->byval_arg.type == MONO_TYPE_VAR) || (klass->byval_arg.type == MONO_TYPE_MVAR))
4080 return has_type_vars (klass->element_class);
4081 if (klass->generic_class) {
4082 MonoGenericContext *context = &klass->generic_class->context;
4083 if (context->class_inst) {
4086 for (i = 0; i < context->class_inst->type_argc; ++i)
4087 if (has_type_vars (mono_class_from_mono_type (context->class_inst->type_argv [i])))
4091 if (klass->generic_container)
4097 is_vt_inst (MonoGenericInst *inst)
4101 for (i = 0; i < inst->type_argc; ++i) {
4102 MonoType *t = inst->type_argv [i];
4103 if (MONO_TYPE_ISSTRUCT (t) || t->type == MONO_TYPE_VALUETYPE)
4110 method_has_type_vars (MonoMethod *method)
4112 if (has_type_vars (method->klass))
4115 if (method->is_inflated) {
4116 MonoGenericContext *context = mono_method_get_context (method);
4117 if (context->method_inst) {
4120 for (i = 0; i < context->method_inst->type_argc; ++i)
4121 if (has_type_vars (mono_class_from_mono_type (context->method_inst->type_argv [i])))
4129 gboolean mono_aot_mode_is_full (MonoAotOptions *opts)
4131 return opts->mode == MONO_AOT_MODE_FULL;
4134 static void add_generic_class_with_depth (MonoAotCompile *acfg, MonoClass *klass, int depth, const char *ref);
4137 add_generic_class (MonoAotCompile *acfg, MonoClass *klass, gboolean force, const char *ref)
4139 /* This might lead to a huge code blowup so only do it if neccesary */
4140 if (!mono_aot_mode_is_full (&acfg->aot_opts) && !force)
4143 add_generic_class_with_depth (acfg, klass, 0, ref);
4147 check_type_depth (MonoType *t, int depth)
4155 case MONO_TYPE_GENERICINST: {
4156 MonoGenericClass *gklass = t->data.generic_class;
4157 MonoGenericInst *ginst = gklass->context.class_inst;
4160 for (i = 0; i < ginst->type_argc; ++i) {
4161 if (check_type_depth (ginst->type_argv [i], depth + 1))
4175 add_types_from_method_header (MonoAotCompile *acfg, MonoMethod *method);
4178 * add_generic_class:
4180 * Add all methods of a generic class.
4183 add_generic_class_with_depth (MonoAotCompile *acfg, MonoClass *klass, int depth, const char *ref)
4186 MonoClassField *field;
4188 gboolean use_gsharedvt = FALSE;
4190 if (!acfg->ginst_hash)
4191 acfg->ginst_hash = g_hash_table_new (NULL, NULL);
4193 mono_class_init (klass);
4195 if (klass->generic_class && klass->generic_class->context.class_inst->is_open)
4198 if (has_type_vars (klass))
4201 if (!klass->generic_class && !klass->rank)
4204 if (klass->exception_type)
4207 if (!acfg->ginst_hash)
4208 acfg->ginst_hash = g_hash_table_new (NULL, NULL);
4210 if (g_hash_table_lookup (acfg->ginst_hash, klass))
4213 if (check_type_depth (&klass->byval_arg, 0))
4216 if (acfg->aot_opts.log_generics)
4217 aot_printf (acfg, "%*sAdding generic instance %s [%s].\n", depth, "", mono_type_full_name (&klass->byval_arg), ref);
4219 g_hash_table_insert (acfg->ginst_hash, klass, klass);
4222 * Use gsharedvt for generic collections with vtype arguments to avoid code blowup.
4223 * Enable this only for some classes since gsharedvt might not support all methods.
4225 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) &&
4226 (!strcmp (klass->name, "Dictionary`2") || !strcmp (klass->name, "List`1") || !strcmp (klass->name, "ReadOnlyCollection`1")))
4227 use_gsharedvt = TRUE;
4230 while ((method = mono_class_get_methods (klass, &iter))) {
4231 if ((acfg->opts & MONO_OPT_GSHAREDVT) && method->is_inflated && mono_method_get_context (method)->method_inst) {
4233 * This is partial sharing, and we can't handle it yet
4238 if (mono_method_is_generic_sharable_full (method, FALSE, FALSE, use_gsharedvt)) {
4240 add_types_from_method_header (acfg, method);
4244 if (method->is_generic)
4249 * FIXME: Instances which are referenced by these methods are not added,
4250 * for example Array.Resize<int> for List<int>.Add ().
4252 add_extra_method_with_depth (acfg, method, depth + 1);
4256 while ((field = mono_class_get_fields (klass, &iter))) {
4257 if (field->type->type == MONO_TYPE_GENERICINST)
4258 add_generic_class_with_depth (acfg, mono_class_from_mono_type (field->type), depth + 1, "field");
4261 if (klass->delegate) {
4262 method = mono_get_delegate_invoke (klass);
4264 method = mono_marshal_get_delegate_invoke (method, NULL);
4266 if (acfg->aot_opts.log_generics)
4267 aot_printf (acfg, "%*sAdding method %s.\n", depth, "", mono_method_full_name (method, TRUE));
4269 add_method (acfg, method);
4272 /* Add superclasses */
4274 add_generic_class_with_depth (acfg, klass->parent, depth, "parent");
4277 * For ICollection<T>, add instances of the helper methods
4278 * in Array, since a T[] could be cast to ICollection<T>.
4280 if (klass->image == mono_defaults.corlib && !strcmp (klass->name_space, "System.Collections.Generic") &&
4281 (!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"))) {
4282 MonoClass *tclass = mono_class_from_mono_type (klass->generic_class->context.class_inst->type_argv [0]);
4283 MonoClass *array_class = mono_bounded_array_class_get (tclass, 1, FALSE);
4287 if (!strcmp (klass->name, "IEnumerator`1"))
4288 name_prefix = g_strdup_printf ("%s.%s", klass->name_space, "IEnumerable`1");
4290 name_prefix = g_strdup_printf ("%s.%s", klass->name_space, klass->name);
4292 /* Add the T[]/InternalEnumerator class */
4293 if (!strcmp (klass->name, "IEnumerable`1") || !strcmp (klass->name, "IEnumerator`1")) {
4297 while ((nclass = mono_class_get_nested_types (array_class->parent, &iter))) {
4298 if (!strcmp (nclass->name, "InternalEnumerator`1"))
4302 nclass = mono_class_inflate_generic_class (nclass, mono_generic_class_get_context (klass->generic_class));
4303 add_generic_class (acfg, nclass, FALSE, "ICollection<T>");
4307 while ((method = mono_class_get_methods (array_class, &iter))) {
4308 if (strstr (method->name, name_prefix)) {
4309 MonoMethod *m = mono_aot_get_array_helper_from_wrapper (method);
4311 add_extra_method_with_depth (acfg, m, depth);
4315 g_free (name_prefix);
4318 /* Add an instance of GenericComparer<T> which is created dynamically by Comparer<T> */
4319 if (klass->image == mono_defaults.corlib && !strcmp (klass->name_space, "System.Collections.Generic") && !strcmp (klass->name, "Comparer`1")) {
4320 MonoClass *tclass = mono_class_from_mono_type (klass->generic_class->context.class_inst->type_argv [0]);
4321 MonoClass *icomparable, *gcomparer;
4322 MonoGenericContext ctx;
4323 MonoType *args [16];
4325 memset (&ctx, 0, sizeof (ctx));
4327 icomparable = mono_class_from_name (mono_defaults.corlib, "System", "IComparable`1");
4328 g_assert (icomparable);
4329 args [0] = &tclass->byval_arg;
4330 ctx.class_inst = mono_metadata_get_generic_inst (1, args);
4332 if (mono_class_is_assignable_from (mono_class_inflate_generic_class (icomparable, &ctx), tclass)) {
4333 gcomparer = mono_class_from_name (mono_defaults.corlib, "System.Collections.Generic", "GenericComparer`1");
4334 g_assert (gcomparer);
4335 add_generic_class (acfg, mono_class_inflate_generic_class (gcomparer, &ctx), FALSE, "Comparer<T>");
4339 /* Add an instance of GenericEqualityComparer<T> which is created dynamically by EqualityComparer<T> */
4340 if (klass->image == mono_defaults.corlib && !strcmp (klass->name_space, "System.Collections.Generic") && !strcmp (klass->name, "EqualityComparer`1")) {
4341 MonoClass *tclass = mono_class_from_mono_type (klass->generic_class->context.class_inst->type_argv [0]);
4342 MonoClass *iface, *gcomparer;
4343 MonoGenericContext ctx;
4344 MonoType *args [16];
4346 memset (&ctx, 0, sizeof (ctx));
4348 iface = mono_class_from_name (mono_defaults.corlib, "System", "IEquatable`1");
4350 args [0] = &tclass->byval_arg;
4351 ctx.class_inst = mono_metadata_get_generic_inst (1, args);
4353 if (mono_class_is_assignable_from (mono_class_inflate_generic_class (iface, &ctx), tclass)) {
4354 gcomparer = mono_class_from_name (mono_defaults.corlib, "System.Collections.Generic", "GenericEqualityComparer`1");
4355 g_assert (gcomparer);
4356 add_generic_class (acfg, mono_class_inflate_generic_class (gcomparer, &ctx), FALSE, "EqualityComparer<T>");
4360 /* Add an instance of EnumComparer<T> which is created dynamically by EqualityComparer<T> for enums */
4361 if (klass->image == mono_defaults.corlib && !strcmp (klass->name_space, "System.Collections.Generic") && !strcmp (klass->name, "EqualityComparer`1")) {
4362 MonoClass *enum_comparer;
4363 MonoClass *tclass = mono_class_from_mono_type (klass->generic_class->context.class_inst->type_argv [0]);
4364 MonoGenericContext ctx;
4365 MonoType *args [16];
4367 if (mono_class_is_enum (tclass)) {
4368 memset (&ctx, 0, sizeof (ctx));
4369 args [0] = &tclass->byval_arg;
4370 ctx.class_inst = mono_metadata_get_generic_inst (1, args);
4372 enum_comparer = mono_class_from_name (mono_defaults.corlib, "System.Collections.Generic", "EnumEqualityComparer`1");
4373 g_assert (enum_comparer);
4374 add_generic_class (acfg, mono_class_inflate_generic_class (enum_comparer, &ctx), FALSE, "EqualityComparer<T>");
4378 /* Add an instance of ObjectComparer<T> which is created dynamically by Comparer<T> for enums */
4379 if (klass->image == mono_defaults.corlib && !strcmp (klass->name_space, "System.Collections.Generic") && !strcmp (klass->name, "Comparer`1")) {
4380 MonoClass *comparer;
4381 MonoClass *tclass = mono_class_from_mono_type (klass->generic_class->context.class_inst->type_argv [0]);
4382 MonoGenericContext ctx;
4383 MonoType *args [16];
4385 if (mono_class_is_enum (tclass)) {
4386 memset (&ctx, 0, sizeof (ctx));
4387 args [0] = &tclass->byval_arg;
4388 ctx.class_inst = mono_metadata_get_generic_inst (1, args);
4390 comparer = mono_class_from_name (mono_defaults.corlib, "System.Collections.Generic", "ObjectComparer`1");
4391 g_assert (comparer);
4392 add_generic_class (acfg, mono_class_inflate_generic_class (comparer, &ctx), FALSE, "Comparer<T>");
4398 add_instances_of (MonoAotCompile *acfg, MonoClass *klass, MonoType **insts, int ninsts, gboolean force)
4401 MonoGenericContext ctx;
4402 MonoType *args [16];
4404 if (acfg->aot_opts.no_instances)
4407 memset (&ctx, 0, sizeof (ctx));
4409 for (i = 0; i < ninsts; ++i) {
4410 args [0] = insts [i];
4411 ctx.class_inst = mono_metadata_get_generic_inst (1, args);
4412 add_generic_class (acfg, mono_class_inflate_generic_class (klass, &ctx), force, "");
4417 add_types_from_method_header (MonoAotCompile *acfg, MonoMethod *method)
4419 MonoMethodHeader *header;
4420 MonoMethodSignature *sig;
4423 depth = GPOINTER_TO_UINT (g_hash_table_lookup (acfg->method_depth, method));
4425 sig = mono_method_signature (method);
4428 for (j = 0; j < sig->param_count; ++j)
4429 if (sig->params [j]->type == MONO_TYPE_GENERICINST)
4430 add_generic_class_with_depth (acfg, mono_class_from_mono_type (sig->params [j]), depth + 1, "arg");
4433 header = mono_method_get_header (method);
4436 for (j = 0; j < header->num_locals; ++j)
4437 if (header->locals [j]->type == MONO_TYPE_GENERICINST)
4438 add_generic_class_with_depth (acfg, mono_class_from_mono_type (header->locals [j]), depth + 1, "local");
4440 mono_loader_clear_error ();
4445 * add_generic_instances:
4447 * Add instances referenced by the METHODSPEC/TYPESPEC table.
4450 add_generic_instances (MonoAotCompile *acfg)
4455 MonoGenericContext *context;
4457 if (acfg->aot_opts.no_instances)
4460 for (i = 0; i < acfg->image->tables [MONO_TABLE_METHODSPEC].rows; ++i) {
4462 token = MONO_TOKEN_METHOD_SPEC | (i + 1);
4463 method = mono_get_method_checked (acfg->image, token, NULL, NULL, &error);
4466 aot_printerrf (acfg, "Failed to load methodspec 0x%x due to %s.\n", token, mono_error_get_message (&error));
4467 aot_printerrf (acfg, "Run with MONO_LOG_LEVEL=debug for more information.\n");
4468 mono_error_cleanup (&error);
4472 if (method->klass->image != acfg->image)
4475 context = mono_method_get_context (method);
4477 if (context && ((context->class_inst && context->class_inst->is_open)))
4481 * For open methods, create an instantiation which can be passed to the JIT.
4482 * FIXME: Handle class_inst as well.
4484 if (context && context->method_inst && context->method_inst->is_open) {
4486 MonoGenericContext shared_context;
4487 MonoGenericInst *inst;
4488 MonoType **type_argv;
4490 MonoMethod *declaring_method;
4491 gboolean supported = TRUE;
4493 /* Check that the context doesn't contain open constructed types */
4494 if (context->class_inst) {
4495 inst = context->class_inst;
4496 for (i = 0; i < inst->type_argc; ++i) {
4497 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)
4499 if (mono_class_is_open_constructed_type (inst->type_argv [i]))
4503 if (context->method_inst) {
4504 inst = context->method_inst;
4505 for (i = 0; i < inst->type_argc; ++i) {
4506 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)
4508 if (mono_class_is_open_constructed_type (inst->type_argv [i]))
4516 memset (&shared_context, 0, sizeof (MonoGenericContext));
4518 inst = context->class_inst;
4520 type_argv = g_new0 (MonoType*, inst->type_argc);
4521 for (i = 0; i < inst->type_argc; ++i) {
4522 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)
4523 type_argv [i] = &mono_defaults.object_class->byval_arg;
4525 type_argv [i] = inst->type_argv [i];
4528 shared_context.class_inst = mono_metadata_get_generic_inst (inst->type_argc, type_argv);
4532 inst = context->method_inst;
4534 type_argv = g_new0 (MonoType*, inst->type_argc);
4535 for (i = 0; i < inst->type_argc; ++i) {
4536 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)
4537 type_argv [i] = &mono_defaults.object_class->byval_arg;
4539 type_argv [i] = inst->type_argv [i];
4542 shared_context.method_inst = mono_metadata_get_generic_inst (inst->type_argc, type_argv);
4546 if (method->is_generic || method->klass->generic_container)
4547 declaring_method = method;
4549 declaring_method = mono_method_get_declaring_generic_method (method);
4551 method = mono_class_inflate_generic_method_checked (declaring_method, &shared_context, &error);
4552 g_assert (mono_error_ok (&error)); /* FIXME don't swallow the error */
4556 * If the method is fully sharable, it was already added in place of its
4557 * generic definition.
4559 if (mono_method_is_generic_sharable_full (method, FALSE, FALSE, FALSE))
4563 * FIXME: Partially shared methods are not shared here, so we end up with
4564 * many identical methods.
4566 add_extra_method (acfg, method);
4569 for (i = 0; i < acfg->image->tables [MONO_TABLE_TYPESPEC].rows; ++i) {
4573 token = MONO_TOKEN_TYPE_SPEC | (i + 1);
4575 klass = mono_class_get_checked (acfg->image, token, &error);
4576 if (!klass || klass->rank) {
4577 mono_error_cleanup (&error);
4581 add_generic_class (acfg, klass, FALSE, "typespec");
4584 /* Add types of args/locals */
4585 for (i = 0; i < acfg->methods->len; ++i) {
4586 method = g_ptr_array_index (acfg->methods, i);
4587 add_types_from_method_header (acfg, method);
4590 if (acfg->image == mono_defaults.corlib) {
4592 MonoType *insts [256];
4595 insts [ninsts ++] = &mono_defaults.byte_class->byval_arg;
4596 insts [ninsts ++] = &mono_defaults.sbyte_class->byval_arg;
4597 insts [ninsts ++] = &mono_defaults.int16_class->byval_arg;
4598 insts [ninsts ++] = &mono_defaults.uint16_class->byval_arg;
4599 insts [ninsts ++] = &mono_defaults.int32_class->byval_arg;
4600 insts [ninsts ++] = &mono_defaults.uint32_class->byval_arg;
4601 insts [ninsts ++] = &mono_defaults.int64_class->byval_arg;
4602 insts [ninsts ++] = &mono_defaults.uint64_class->byval_arg;
4603 insts [ninsts ++] = &mono_defaults.single_class->byval_arg;
4604 insts [ninsts ++] = &mono_defaults.double_class->byval_arg;
4605 insts [ninsts ++] = &mono_defaults.char_class->byval_arg;
4606 insts [ninsts ++] = &mono_defaults.boolean_class->byval_arg;
4608 /* Add GenericComparer<T> instances for primitive types for Enum.ToString () */
4609 klass = mono_class_from_name (acfg->image, "System.Collections.Generic", "GenericComparer`1");
4611 add_instances_of (acfg, klass, insts, ninsts, TRUE);
4612 klass = mono_class_from_name (acfg->image, "System.Collections.Generic", "GenericEqualityComparer`1");
4614 add_instances_of (acfg, klass, insts, ninsts, TRUE);
4616 /* Add instances of the array generic interfaces for primitive types */
4617 /* This will add instances of the InternalArray_ helper methods in Array too */
4618 klass = mono_class_from_name (acfg->image, "System.Collections.Generic", "ICollection`1");
4620 add_instances_of (acfg, klass, insts, ninsts, TRUE);
4621 klass = mono_class_from_name (acfg->image, "System.Collections.Generic", "IList`1");
4623 add_instances_of (acfg, klass, insts, ninsts, TRUE);
4624 klass = mono_class_from_name (acfg->image, "System.Collections.Generic", "IEnumerable`1");
4626 add_instances_of (acfg, klass, insts, ninsts, TRUE);
4629 * Add a managed-to-native wrapper of Array.GetGenericValueImpl<object>, which is
4630 * used for all instances of GetGenericValueImpl by the AOT runtime.
4633 MonoGenericContext ctx;
4634 MonoType *args [16];
4635 MonoMethod *get_method;
4636 MonoClass *array_klass = mono_array_class_get (mono_defaults.object_class, 1)->parent;
4638 get_method = mono_class_get_method_from_name (array_klass, "GetGenericValueImpl", 2);
4642 memset (&ctx, 0, sizeof (ctx));
4643 args [0] = &mono_defaults.object_class->byval_arg;
4644 ctx.method_inst = mono_metadata_get_generic_inst (1, args);
4645 add_extra_method (acfg, mono_marshal_get_native_wrapper (mono_class_inflate_generic_method_checked (get_method, &ctx, &error), TRUE, TRUE));
4646 g_assert (mono_error_ok (&error)); /* FIXME don't swallow the error */
4650 /* Same for CompareExchange<T>/Exchange<T> */
4652 MonoGenericContext ctx;
4653 MonoType *args [16];
4655 MonoClass *interlocked_klass = mono_class_from_name (mono_defaults.corlib, "System.Threading", "Interlocked");
4656 gpointer iter = NULL;
4658 while ((m = mono_class_get_methods (interlocked_klass, &iter))) {
4659 if ((!strcmp (m->name, "CompareExchange") || !strcmp (m->name, "Exchange")) && m->is_generic) {
4661 memset (&ctx, 0, sizeof (ctx));
4662 args [0] = &mono_defaults.object_class->byval_arg;
4663 ctx.method_inst = mono_metadata_get_generic_inst (1, args);
4664 add_extra_method (acfg, mono_marshal_get_native_wrapper (mono_class_inflate_generic_method_checked (m, &ctx, &error), TRUE, TRUE));
4665 g_assert (mono_error_ok (&error)); /* FIXME don't swallow the error */
4670 /* Same for Volatile.Read/Write<T> */
4672 MonoGenericContext ctx;
4673 MonoType *args [16];
4675 MonoClass *volatile_klass = mono_class_from_name (mono_defaults.corlib, "System.Threading", "Volatile");
4676 gpointer iter = NULL;
4678 if (volatile_klass) {
4679 while ((m = mono_class_get_methods (volatile_klass, &iter))) {
4680 if ((!strcmp (m->name, "Read") || !strcmp (m->name, "Write")) && m->is_generic) {
4682 memset (&ctx, 0, sizeof (ctx));
4683 args [0] = &mono_defaults.object_class->byval_arg;
4684 ctx.method_inst = mono_metadata_get_generic_inst (1, args);
4685 add_extra_method (acfg, mono_marshal_get_native_wrapper (mono_class_inflate_generic_method_checked (m, &ctx, &error), TRUE, TRUE));
4686 g_assert (mono_error_ok (&error)); /* FIXME don't swallow the error */
4695 * is_direct_callable:
4697 * Return whenever the method identified by JI is directly callable without
4698 * going through the PLT.
4701 is_direct_callable (MonoAotCompile *acfg, MonoMethod *method, MonoJumpInfo *patch_info)
4703 if ((patch_info->type == MONO_PATCH_INFO_METHOD) && (patch_info->data.method->klass->image == acfg->image)) {
4704 MonoCompile *callee_cfg = g_hash_table_lookup (acfg->method_to_cfg, patch_info->data.method);
4706 gboolean direct_callable = TRUE;
4708 if (direct_callable && !(!callee_cfg->has_got_slots && (callee_cfg->method->klass->flags & TYPE_ATTRIBUTE_BEFORE_FIELD_INIT)))
4709 direct_callable = FALSE;
4710 if ((callee_cfg->method->iflags & METHOD_IMPL_ATTRIBUTE_SYNCHRONIZED) && (!method || method->wrapper_type != MONO_WRAPPER_SYNCHRONIZED))
4711 // FIXME: Maybe call the wrapper directly ?
4712 direct_callable = FALSE;
4714 if (acfg->aot_opts.soft_debug || acfg->aot_opts.no_direct_calls) {
4715 /* Disable this so all calls go through load_method (), see the
4716 * mini_get_debug_options ()->load_aot_jit_info_eagerly = TRUE; line in
4717 * mono_debugger_agent_init ().
4719 direct_callable = FALSE;
4722 if (callee_cfg->method->wrapper_type == MONO_WRAPPER_ALLOC)
4723 /* sgen does some initialization when the allocator method is created */
4724 direct_callable = FALSE;
4725 if (callee_cfg->method->wrapper_type == MONO_WRAPPER_WRITE_BARRIER)
4726 /* we don't know at compile time whether sgen is concurrent or not */
4727 direct_callable = FALSE;
4729 if (direct_callable)
4732 } else if ((patch_info->type == MONO_PATCH_INFO_ICALL_ADDR && patch_info->data.method->flags & METHOD_ATTRIBUTE_PINVOKE_IMPL)) {
4733 if (acfg->aot_opts.direct_pinvoke)
4735 } else if (patch_info->type == MONO_PATCH_INFO_ICALL_ADDR) {
4736 if (acfg->aot_opts.direct_icalls)
4744 #ifdef MONO_ARCH_AOT_SUPPORTED
4746 get_pinvoke_import (MonoAotCompile *acfg, MonoMethod *method)
4748 MonoImage *image = method->klass->image;
4749 MonoMethodPInvoke *piinfo = (MonoMethodPInvoke *) method;
4750 MonoTableInfo *tables = image->tables;
4751 MonoTableInfo *im = &tables [MONO_TABLE_IMPLMAP];
4752 MonoTableInfo *mr = &tables [MONO_TABLE_MODULEREF];
4753 guint32 im_cols [MONO_IMPLMAP_SIZE];
4756 import = g_hash_table_lookup (acfg->method_to_pinvoke_import, method);
4760 if (!piinfo->implmap_idx || piinfo->implmap_idx > im->rows)
4763 mono_metadata_decode_row (im, piinfo->implmap_idx - 1, im_cols, MONO_IMPLMAP_SIZE);
4765 if (!im_cols [MONO_IMPLMAP_SCOPE] || im_cols [MONO_IMPLMAP_SCOPE] > mr->rows)
4768 import = g_strdup_printf ("%s", mono_metadata_string_heap (image, im_cols [MONO_IMPLMAP_NAME]));
4770 g_hash_table_insert (acfg->method_to_pinvoke_import, method, import);
4777 compare_lne (MonoDebugLineNumberEntry *a, MonoDebugLineNumberEntry *b)
4779 if (a->native_offset == b->native_offset)
4780 return a->il_offset - b->il_offset;
4782 return a->native_offset - b->native_offset;
4786 * compute_line_numbers:
4788 * Returns a sparse array of size CODE_SIZE containing MonoDebugSourceLocation* entries for the native offsets which have a corresponding line number
4791 static MonoDebugSourceLocation**
4792 compute_line_numbers (MonoMethod *method, int code_size, MonoDebugMethodJitInfo *debug_info)
4794 MonoDebugMethodInfo *minfo;
4795 MonoDebugLineNumberEntry *ln_array;
4796 MonoDebugSourceLocation *loc;
4797 int i, prev_line, prev_il_offset;
4798 int *native_to_il_offset = NULL;
4799 MonoDebugSourceLocation **res;
4802 minfo = mono_debug_lookup_method (method);
4805 // FIXME: This seems to happen when two methods have the same cfg->method_to_register
4806 if (debug_info->code_size != code_size)
4809 g_assert (code_size);
4811 /* Compute the native->IL offset mapping */
4813 ln_array = g_new0 (MonoDebugLineNumberEntry, debug_info->num_line_numbers);
4814 memcpy (ln_array, debug_info->line_numbers, debug_info->num_line_numbers * sizeof (MonoDebugLineNumberEntry));
4816 qsort (ln_array, debug_info->num_line_numbers, sizeof (MonoDebugLineNumberEntry), (gpointer)compare_lne);
4818 native_to_il_offset = g_new0 (int, code_size + 1);
4820 for (i = 0; i < debug_info->num_line_numbers; ++i) {
4822 MonoDebugLineNumberEntry *lne = &ln_array [i];
4825 for (j = 0; j < lne->native_offset; ++j)
4826 native_to_il_offset [j] = -1;
4829 if (i < debug_info->num_line_numbers - 1) {
4830 MonoDebugLineNumberEntry *lne_next = &ln_array [i + 1];
4832 for (j = lne->native_offset; j < lne_next->native_offset; ++j)
4833 native_to_il_offset [j] = lne->il_offset;
4835 for (j = lne->native_offset; j < code_size; ++j)
4836 native_to_il_offset [j] = lne->il_offset;
4841 /* Compute the native->line number mapping */
4842 res = g_new0 (MonoDebugSourceLocation*, code_size);
4843 prev_il_offset = -1;
4846 for (i = 0; i < code_size; ++i) {
4847 int il_offset = native_to_il_offset [i];
4849 if (il_offset == -1 || il_offset == prev_il_offset)
4851 prev_il_offset = il_offset;
4852 loc = mono_debug_symfile_lookup_location (minfo, il_offset);
4853 if (!(loc && loc->source_file))
4855 if (loc->row == prev_line) {
4856 mono_debug_symfile_free_location (loc);
4859 prev_line = loc->row;
4860 //printf ("D: %s:%d il=%x native=%x\n", loc->source_file, loc->row, il_offset, i);
4862 /* This will cover the prolog too */
4872 get_file_index (MonoAotCompile *acfg, const char *source_file)
4876 // FIXME: Free these
4877 if (!acfg->dwarf_ln_filenames)
4878 acfg->dwarf_ln_filenames = g_hash_table_new (g_str_hash, g_str_equal);
4879 findex = GPOINTER_TO_INT (g_hash_table_lookup (acfg->dwarf_ln_filenames, source_file));
4881 findex = g_hash_table_size (acfg->dwarf_ln_filenames) + 1;
4882 g_hash_table_insert (acfg->dwarf_ln_filenames, g_strdup (source_file), GINT_TO_POINTER (findex));
4883 emit_unset_mode (acfg);
4884 fprintf (acfg->fp, ".file %d \"%s\"\n", findex, mono_dwarf_escape_path (source_file));
4896 * emit_and_reloc_code:
4898 * Emit the native code in CODE, handling relocations along the way. If GOT_ONLY
4899 * is true, calls are made through the GOT too. This is used for emitting trampolines
4900 * in full-aot mode, since calls made from trampolines couldn't go through the PLT,
4901 * since trampolines are needed to make PTL work.
4904 emit_and_reloc_code (MonoAotCompile *acfg, MonoMethod *method, guint8 *code, guint32 code_len, MonoJumpInfo *relocs, gboolean got_only, MonoDebugMethodJitInfo *debug_info)
4906 int i, pindex, start_index;
4908 MonoJumpInfo *patch_info;
4909 MonoDebugSourceLocation **locs = NULL;
4911 #ifdef MONO_ARCH_AOT_SUPPORTED
4912 gboolean direct_call, external_call;
4914 const char *direct_call_target = 0;
4915 const char *direct_pinvoke;
4918 if (acfg->gas_line_numbers && method && debug_info) {
4919 locs = compute_line_numbers (method, code_len, debug_info);
4921 int findex = get_file_index (acfg, "<unknown>");
4922 emit_unset_mode (acfg);
4923 fprintf (acfg->fp, ".loc %d %d 0\n", findex, 1);
4927 /* Collect and sort relocations */
4928 patches = g_ptr_array_new ();
4929 for (patch_info = relocs; patch_info; patch_info = patch_info->next)
4930 g_ptr_array_add (patches, patch_info);
4931 g_ptr_array_sort (patches, compare_patches);
4934 for (i = 0; i < code_len; i += INST_LEN) {
4936 for (pindex = start_index; pindex < patches->len; ++pindex) {
4937 patch_info = g_ptr_array_index (patches, pindex);
4938 if (patch_info->ip.i >= i)
4942 if (locs && locs [i]) {
4943 MonoDebugSourceLocation *loc = locs [i];
4946 findex = get_file_index (acfg, loc->source_file);
4947 emit_unset_mode (acfg);
4948 fprintf (acfg->fp, ".loc %d %d 0\n", findex, loc->row);
4949 mono_debug_symfile_free_location (loc);
4953 #ifdef MONO_ARCH_AOT_SUPPORTED
4954 if (patch_info && (patch_info->ip.i == i) && (pindex < patches->len)) {
4955 start_index = pindex;
4957 switch (patch_info->type) {
4958 case MONO_PATCH_INFO_NONE:
4960 case MONO_PATCH_INFO_GOT_OFFSET: {
4963 arch_emit_got_offset (acfg, code + i, &code_size);
4964 i += code_size - INST_LEN;
4966 patch_info->type = MONO_PATCH_INFO_NONE;
4969 case MONO_PATCH_INFO_OBJC_SELECTOR_REF: {
4970 int code_size, index;
4971 char *selector = (void*)patch_info->data.target;
4973 if (!acfg->objc_selector_to_index)
4974 acfg->objc_selector_to_index = g_hash_table_new (g_str_hash, g_str_equal);
4975 if (!acfg->objc_selectors)
4976 acfg->objc_selectors = g_ptr_array_new ();
4977 index = GPOINTER_TO_UINT (g_hash_table_lookup (acfg->objc_selector_to_index, selector));
4981 index = acfg->objc_selector_index;
4982 g_ptr_array_add (acfg->objc_selectors, (void*)patch_info->data.target);
4983 g_hash_table_insert (acfg->objc_selector_to_index, selector, GUINT_TO_POINTER (index + 1));
4984 acfg->objc_selector_index ++;
4987 arch_emit_objc_selector_ref (acfg, code + i, index, &code_size);
4988 i += code_size - INST_LEN;
4990 patch_info->type = MONO_PATCH_INFO_NONE;
4995 * If this patch is a call, try emitting a direct call instead of
4996 * through a PLT entry. This is possible if the called method is in
4997 * the same assembly and requires no initialization.
4999 direct_call = FALSE;
5000 external_call = FALSE;
5001 if ((patch_info->type == MONO_PATCH_INFO_METHOD) && (patch_info->data.method->klass->image == acfg->image)) {
5002 if (!got_only && is_direct_callable (acfg, method, patch_info)) {
5003 MonoCompile *callee_cfg = g_hash_table_lookup (acfg->method_to_cfg, patch_info->data.method);
5004 //printf ("DIRECT: %s %s\n", method ? mono_method_full_name (method, TRUE) : "", mono_method_full_name (callee_cfg->method, TRUE));
5006 direct_call_target = callee_cfg->asm_symbol;
5007 patch_info->type = MONO_PATCH_INFO_NONE;
5008 acfg->stats.direct_calls ++;
5011 acfg->stats.all_calls ++;
5012 } else if (patch_info->type == MONO_PATCH_INFO_ICALL_ADDR) {
5013 if (!got_only && is_direct_callable (acfg, method, patch_info)) {
5014 if (!(patch_info->data.method->flags & METHOD_ATTRIBUTE_PINVOKE_IMPL))
5015 direct_pinvoke = mono_lookup_icall_symbol (patch_info->data.method);
5017 direct_pinvoke = get_pinvoke_import (acfg, patch_info->data.method);
5018 if (direct_pinvoke) {
5020 g_assert (strlen (direct_pinvoke) < 1000);
5021 direct_call_target = g_strdup_printf ("%s%s", acfg->user_symbol_prefix, direct_pinvoke);
5024 } else if (patch_info->type == MONO_PATCH_INFO_JIT_ICALL_ADDR) {
5025 const char *sym = mono_lookup_jit_icall_symbol (patch_info->data.name);
5026 if (!got_only && sym && acfg->aot_opts.direct_icalls) {
5027 /* Call to a C function implementing a jit icall */
5029 external_call = TRUE;
5030 g_assert (strlen (sym) < 1000);
5031 direct_call_target = g_strdup_printf ("%s%s", acfg->user_symbol_prefix, sym);
5033 } else if (patch_info->type == MONO_PATCH_INFO_INTERNAL_METHOD) {
5034 MonoJitICallInfo *info = mono_find_jit_icall_by_name (patch_info->data.name);
5035 const char *sym = mono_lookup_jit_icall_symbol (patch_info->data.name);
5036 if (!got_only && sym && acfg->aot_opts.direct_icalls && info->func == info->wrapper) {
5037 /* Call to a jit icall without a wrapper */
5039 external_call = TRUE;
5040 g_assert (strlen (sym) < 1000);
5041 direct_call_target = g_strdup_printf ("%s%s", acfg->user_symbol_prefix, sym);
5046 patch_info->type = MONO_PATCH_INFO_NONE;
5047 acfg->stats.direct_calls ++;
5050 if (!got_only && !direct_call) {
5051 MonoPltEntry *plt_entry = get_plt_entry (acfg, patch_info);
5053 /* This patch has a PLT entry, so we must emit a call to the PLT entry */
5055 direct_call_target = plt_entry->symbol;
5057 /* Nullify the patch */
5058 patch_info->type = MONO_PATCH_INFO_NONE;
5059 plt_entry->jit_used = TRUE;
5066 arch_emit_direct_call (acfg, direct_call_target, external_call, FALSE, patch_info, &call_size);
5067 i += call_size - INST_LEN;
5071 got_slot = get_got_offset (acfg, FALSE, patch_info);
5073 arch_emit_got_access (acfg, acfg->got_symbol, code + i, got_slot, &code_size);
5074 i += code_size - INST_LEN;
5080 #endif /* MONO_ARCH_AOT_SUPPORTED */
5083 /* Find next patch */
5085 for (pindex = start_index; pindex < patches->len; ++pindex) {
5086 patch_info = g_ptr_array_index (patches, pindex);
5087 if (patch_info->ip.i >= i)
5091 /* Try to emit multiple bytes at once */
5092 if (pindex < patches->len && patch_info->ip.i > i) {
5095 for (limit = i + INST_LEN; limit < patch_info->ip.i; limit += INST_LEN) {
5096 if (locs && locs [limit])
5100 emit_code_bytes (acfg, code + i, limit - i);
5101 i = limit - INST_LEN;
5103 emit_code_bytes (acfg, code + i, INST_LEN);
5114 * Return a modified version of S which only includes characters permissible in symbols.
5117 sanitize_symbol (MonoAotCompile *acfg, char *s)
5119 gboolean process = FALSE;
5128 for (i = 0; i < len; ++i)
5129 if (!(s [i] <= 0x7f && (isalnum (s [i]) || s [i] == '_')))
5134 gs = g_string_sized_new (len);
5135 for (i = 0; i < len; ++i) {
5137 if (c <= 0x7f && (isalnum (c) || c == '_')) {
5138 g_string_append_c (gs, c);
5139 } else if (c > 0x7f) {
5140 /* multi-byte utf8 */
5141 g_string_append_printf (gs, "_0x%x", c);
5144 while (c >> 6 == 0x2) {
5145 g_string_append_printf (gs, "%x", c);
5149 g_string_append_printf (gs, "_");
5152 g_string_append_c (gs, '_');
5156 res = mono_mempool_strdup (acfg->mempool, gs->str);
5157 g_string_free (gs, TRUE);
5162 get_debug_sym (MonoMethod *method, const char *prefix, GHashTable *cache)
5164 char *name1, *name2, *cached;
5165 int i, j, len, count;
5166 MonoMethod *cached_method;
5168 name1 = mono_method_full_name (method, TRUE);
5171 // This is so that we don't accidentally create a local symbol (which starts with 'L')
5172 if ((!prefix || !*prefix) && name1 [0] == 'L')
5176 len = strlen (name1);
5177 name2 = malloc (strlen (prefix) + len + 16);
5178 memcpy (name2, prefix, strlen (prefix));
5179 j = strlen (prefix);
5180 for (i = 0; i < len; ++i) {
5181 if (i == 0 && name1 [0] >= '0' && name1 [0] <= '9') {
5183 } else if (isalnum (name1 [i])) {
5184 name2 [j ++] = name1 [i];
5185 } else if (name1 [i] == ' ' && name1 [i + 1] == '(' && name1 [i + 2] == ')') {
5187 } else if (name1 [i] == ',' && name1 [i + 1] == ' ') {
5190 } else if (name1 [i] == '(' || name1 [i] == ')' || name1 [i] == '>') {
5200 cached_method = g_hash_table_lookup (cache, name2);
5201 if (!(cached_method && cached_method != method))
5203 sprintf (name2 + j, "_%d", count);
5207 cached = g_strdup (name2);
5208 g_hash_table_insert (cache, cached, method);
5214 emit_method_code (MonoAotCompile *acfg, MonoCompile *cfg)
5219 char *debug_sym = NULL;
5220 char *symbol = NULL;
5221 int func_alignment = AOT_FUNC_ALIGNMENT;
5224 method = cfg->orig_method;
5225 code = cfg->native_code;
5227 method_index = get_method_index (acfg, method);
5228 symbol = g_strdup_printf ("%sme_%x", acfg->temp_prefix, method_index);
5230 /* Make the labels local */
5231 emit_section_change (acfg, ".text", 0);
5232 emit_alignment_code (acfg, func_alignment);
5234 if (acfg->global_symbols && acfg->need_no_dead_strip)
5235 fprintf (acfg->fp, " .no_dead_strip %s\n", cfg->asm_symbol);
5237 emit_label (acfg, cfg->asm_symbol);
5239 if (acfg->aot_opts.write_symbols && !acfg->global_symbols && !acfg->llvm) {
5241 * Write a C style symbol for every method, this has two uses:
5242 * - it works on platforms where the dwarf debugging info is not
5244 * - it allows the setting of breakpoints of aot-ed methods.
5246 debug_sym = get_debug_sym (method, "", acfg->method_label_hash);
5247 cfg->asm_debug_symbol = g_strdup (debug_sym);
5249 if (acfg->need_no_dead_strip)
5250 fprintf (acfg->fp, " .no_dead_strip %s\n", debug_sym);
5251 emit_local_symbol (acfg, debug_sym, symbol, TRUE);
5252 emit_label (acfg, debug_sym);
5255 export_name = g_hash_table_lookup (acfg->export_names, method);
5257 /* Emit a global symbol for the method */
5258 emit_global_inner (acfg, export_name, TRUE);
5259 emit_label (acfg, export_name);
5262 if (cfg->verbose_level > 0)
5263 g_print ("Method %s emitted as %s\n", mono_method_full_name (method, TRUE), cfg->asm_symbol);
5265 acfg->stats.code_size += cfg->code_len;
5267 acfg->cfgs [method_index]->got_offset = acfg->got_offset;
5269 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 ()));
5273 if (acfg->aot_opts.write_symbols) {
5275 emit_symbol_size (acfg, debug_sym, ".");
5277 emit_symbol_size (acfg, cfg->asm_symbol, ".");
5281 emit_label (acfg, symbol);
5288 * Encode PATCH_INFO into its disk representation.
5291 encode_patch (MonoAotCompile *acfg, MonoJumpInfo *patch_info, guint8 *buf, guint8 **endbuf)
5295 switch (patch_info->type) {
5296 case MONO_PATCH_INFO_NONE:
5298 case MONO_PATCH_INFO_IMAGE:
5299 encode_value (get_image_index (acfg, patch_info->data.image), p, &p);
5301 case MONO_PATCH_INFO_MSCORLIB_GOT_ADDR:
5302 case MONO_PATCH_INFO_JIT_TLS_ID:
5303 case MONO_PATCH_INFO_GC_CARD_TABLE_ADDR:
5304 case MONO_PATCH_INFO_GC_NURSERY_START:
5306 case MONO_PATCH_INFO_CASTCLASS_CACHE:
5307 encode_value (patch_info->data.index, p, &p);
5309 case MONO_PATCH_INFO_METHOD_REL:
5310 encode_value ((gint)patch_info->data.offset, p, &p);
5312 case MONO_PATCH_INFO_SWITCH: {
5313 gpointer *table = (gpointer *)patch_info->data.table->table;
5316 encode_value (patch_info->data.table->table_size, p, &p);
5317 for (k = 0; k < patch_info->data.table->table_size; k++)
5318 encode_value ((int)(gssize)table [k], p, &p);
5321 case MONO_PATCH_INFO_METHODCONST:
5322 case MONO_PATCH_INFO_METHOD:
5323 case MONO_PATCH_INFO_METHOD_JUMP:
5324 case MONO_PATCH_INFO_ICALL_ADDR:
5325 case MONO_PATCH_INFO_METHOD_RGCTX:
5326 case MONO_PATCH_INFO_METHOD_CODE_SLOT:
5327 encode_method_ref (acfg, patch_info->data.method, p, &p);
5329 case MONO_PATCH_INFO_INTERNAL_METHOD:
5330 case MONO_PATCH_INFO_JIT_ICALL_ADDR: {
5331 guint32 len = strlen (patch_info->data.name);
5333 encode_value (len, p, &p);
5335 memcpy (p, patch_info->data.name, len);
5340 case MONO_PATCH_INFO_LDSTR: {
5341 guint32 image_index = get_image_index (acfg, patch_info->data.token->image);
5342 guint32 token = patch_info->data.token->token;
5343 g_assert (mono_metadata_token_code (token) == MONO_TOKEN_STRING);
5344 encode_value (image_index, p, &p);
5345 encode_value (patch_info->data.token->token - MONO_TOKEN_STRING, p, &p);
5348 case MONO_PATCH_INFO_RVA:
5349 case MONO_PATCH_INFO_DECLSEC:
5350 case MONO_PATCH_INFO_LDTOKEN:
5351 case MONO_PATCH_INFO_TYPE_FROM_HANDLE:
5352 encode_value (get_image_index (acfg, patch_info->data.token->image), p, &p);
5353 encode_value (patch_info->data.token->token, p, &p);
5354 encode_value (patch_info->data.token->has_context, p, &p);
5355 if (patch_info->data.token->has_context)
5356 encode_generic_context (acfg, &patch_info->data.token->context, p, &p);
5358 case MONO_PATCH_INFO_EXC_NAME: {
5359 MonoClass *ex_class;
5362 mono_class_from_name (mono_defaults.exception_class->image,
5363 "System", patch_info->data.target);
5364 g_assert (ex_class);
5365 encode_klass_ref (acfg, ex_class, p, &p);
5368 case MONO_PATCH_INFO_R4:
5369 encode_value (*((guint32 *)patch_info->data.target), p, &p);
5371 case MONO_PATCH_INFO_R8:
5372 encode_value (((guint32 *)patch_info->data.target) [MINI_LS_WORD_IDX], p, &p);
5373 encode_value (((guint32 *)patch_info->data.target) [MINI_MS_WORD_IDX], p, &p);
5375 case MONO_PATCH_INFO_VTABLE:
5376 case MONO_PATCH_INFO_CLASS:
5377 case MONO_PATCH_INFO_IID:
5378 case MONO_PATCH_INFO_ADJUSTED_IID:
5379 encode_klass_ref (acfg, patch_info->data.klass, p, &p);
5381 case MONO_PATCH_INFO_DELEGATE_TRAMPOLINE:
5382 encode_klass_ref (acfg, patch_info->data.del_tramp->klass, p, &p);
5383 if (patch_info->data.del_tramp->method) {
5384 encode_value (1, p, &p);
5385 encode_method_ref (acfg, patch_info->data.del_tramp->method, p, &p);
5387 encode_value (0, p, &p);
5389 encode_value (patch_info->data.del_tramp->virtual, p, &p);
5391 case MONO_PATCH_INFO_FIELD:
5392 case MONO_PATCH_INFO_SFLDA:
5393 encode_field_info (acfg, patch_info->data.field, p, &p);
5395 case MONO_PATCH_INFO_INTERRUPTION_REQUEST_FLAG:
5397 case MONO_PATCH_INFO_RGCTX_FETCH: {
5398 MonoJumpInfoRgctxEntry *entry = patch_info->data.rgctx_entry;
5403 * entry->method has a lenghtly encoding and multiple rgctx_fetch entries
5404 * reference the same method, so encode the method only once.
5406 offset = GPOINTER_TO_UINT (g_hash_table_lookup (acfg->method_blob_hash, entry->method));
5408 buf2 = g_malloc (1024);
5411 encode_method_ref (acfg, entry->method, p2, &p2);
5412 g_assert (p2 - buf2 < 1024);
5414 offset = add_to_blob (acfg, buf2, p2 - buf2);
5417 g_hash_table_insert (acfg->method_blob_hash, entry->method, GUINT_TO_POINTER (offset + 1));
5422 encode_value (offset, p, &p);
5423 g_assert ((int)entry->info_type < 256);
5424 g_assert (entry->data->type < 256);
5425 encode_value ((entry->in_mrgctx ? 1 : 0) | (entry->info_type << 1) | (entry->data->type << 9), p, &p);
5426 encode_patch (acfg, entry->data, p, &p);
5429 case MONO_PATCH_INFO_SEQ_POINT_INFO:
5431 case MONO_PATCH_INFO_LLVM_IMT_TRAMPOLINE:
5432 encode_method_ref (acfg, patch_info->data.imt_tramp->method, p, &p);
5433 encode_value (patch_info->data.imt_tramp->vt_offset, p, &p);
5435 case MONO_PATCH_INFO_SIGNATURE:
5436 encode_signature (acfg, (MonoMethodSignature*)patch_info->data.target, p, &p);
5438 case MONO_PATCH_INFO_TLS_OFFSET:
5439 encode_value (GPOINTER_TO_INT (patch_info->data.target), p, &p);
5441 case MONO_PATCH_INFO_GSHAREDVT_CALL:
5442 encode_signature (acfg, (MonoMethodSignature*)patch_info->data.gsharedvt->sig, p, &p);
5443 encode_method_ref (acfg, patch_info->data.gsharedvt->method, p, &p);
5445 case MONO_PATCH_INFO_GSHAREDVT_METHOD: {
5446 MonoGSharedVtMethodInfo *info = patch_info->data.gsharedvt_method;
5449 encode_method_ref (acfg, info->method, p, &p);
5450 encode_value (info->num_entries, p, &p);
5451 for (i = 0; i < info->num_entries; ++i) {
5452 MonoRuntimeGenericContextInfoTemplate *template = &info->entries [i];
5454 encode_value (template->info_type, p, &p);
5455 switch (mini_rgctx_info_type_to_patch_info_type (template->info_type)) {
5456 case MONO_PATCH_INFO_CLASS:
5457 encode_klass_ref (acfg, mono_class_from_mono_type (template->data), p, &p);
5459 case MONO_PATCH_INFO_FIELD:
5460 encode_field_info (acfg, template->data, p, &p);
5463 g_assert_not_reached ();
5469 case MONO_PATCH_INFO_LDSTR_LIT: {
5470 const char *s = patch_info->data.target;
5471 int len = strlen (s);
5473 encode_value (len, p, &p);
5474 memcpy (p, s, len + 1);
5478 case MONO_PATCH_INFO_VIRT_METHOD:
5479 encode_klass_ref (acfg, patch_info->data.virt_method->klass, p, &p);
5480 encode_method_ref (acfg, patch_info->data.virt_method->method, p, &p);
5482 case MONO_PATCH_INFO_GC_SAFE_POINT_FLAG:
5485 g_warning ("unable to handle jump info %d", patch_info->type);
5486 g_assert_not_reached ();
5493 encode_patch_list (MonoAotCompile *acfg, GPtrArray *patches, int n_patches, gboolean llvm, int first_got_offset, guint8 *buf, guint8 **endbuf)
5496 guint32 pindex, offset;
5497 MonoJumpInfo *patch_info;
5499 encode_value (n_patches, p, &p);
5501 for (pindex = 0; pindex < patches->len; ++pindex) {
5502 patch_info = g_ptr_array_index (patches, pindex);
5504 if (patch_info->type == MONO_PATCH_INFO_NONE || patch_info->type == MONO_PATCH_INFO_BB)
5508 offset = get_got_offset (acfg, llvm, patch_info);
5509 encode_value (offset, p, &p);
5516 emit_method_info (MonoAotCompile *acfg, MonoCompile *cfg)
5519 int pindex, buf_size, n_patches;
5521 MonoJumpInfo *patch_info;
5522 guint32 method_index;
5524 guint32 first_got_offset;
5526 method = cfg->orig_method;
5528 method_index = get_method_index (acfg, method);
5530 /* Sort relocations */
5531 patches = g_ptr_array_new ();
5532 for (patch_info = cfg->patch_info; patch_info; patch_info = patch_info->next)
5533 g_ptr_array_add (patches, patch_info);
5534 g_ptr_array_sort (patches, compare_patches);
5536 first_got_offset = acfg->cfgs [method_index]->got_offset;
5538 /**********************/
5539 /* Encode method info */
5540 /**********************/
5542 buf_size = (patches->len < 1000) ? 40960 : 40960 + (patches->len * 64);
5543 p = buf = g_malloc (buf_size);
5545 if (mono_class_get_cctor (method->klass))
5546 encode_klass_ref (acfg, method->klass, p, &p);
5548 /* Not needed when loading the method */
5549 encode_value (0, p, &p);
5551 g_assert (!(cfg->opt & MONO_OPT_SHARED));
5554 for (pindex = 0; pindex < patches->len; ++pindex) {
5555 patch_info = g_ptr_array_index (patches, pindex);
5557 if ((patch_info->type == MONO_PATCH_INFO_GOT_OFFSET) ||
5558 (patch_info->type == MONO_PATCH_INFO_NONE)) {
5559 patch_info->type = MONO_PATCH_INFO_NONE;
5564 if ((patch_info->type == MONO_PATCH_INFO_IMAGE) && (patch_info->data.image == acfg->image)) {
5565 /* Stored in a GOT slot initialized at module load time */
5566 patch_info->type = MONO_PATCH_INFO_NONE;
5570 if (patch_info->type == MONO_PATCH_INFO_GC_CARD_TABLE_ADDR ||
5571 patch_info->type == MONO_PATCH_INFO_GC_NURSERY_START) {
5572 /* Stored in a GOT slot initialized at module load time */
5573 patch_info->type = MONO_PATCH_INFO_NONE;
5577 if (is_plt_patch (patch_info)) {
5578 /* Calls are made through the PLT */
5579 patch_info->type = MONO_PATCH_INFO_NONE;
5587 g_assert (cfg->has_got_slots);
5589 encode_patch_list (acfg, patches, n_patches, cfg->compile_llvm, first_got_offset, p, &p);
5591 acfg->stats.info_size += p - buf;
5593 g_assert (p - buf < buf_size);
5595 cfg->method_info_offset = add_to_blob (acfg, buf, p - buf);
5600 get_unwind_info_offset (MonoAotCompile *acfg, guint8 *encoded, guint32 encoded_len)
5602 guint32 cache_index;
5605 /* Reuse the unwind module to canonize and store unwind info entries */
5606 cache_index = mono_cache_unwind_info (encoded, encoded_len);
5608 /* Use +/- 1 to distinguish 0s from missing entries */
5609 offset = GPOINTER_TO_UINT (g_hash_table_lookup (acfg->unwind_info_offsets, GUINT_TO_POINTER (cache_index + 1)));
5617 * It would be easier to use assembler symbols, but the caller needs an
5620 offset = acfg->unwind_info_offset;
5621 g_hash_table_insert (acfg->unwind_info_offsets, GUINT_TO_POINTER (cache_index + 1), GUINT_TO_POINTER (offset + 1));
5622 g_ptr_array_add (acfg->unwind_ops, GUINT_TO_POINTER (cache_index));
5625 encode_value (encoded_len, p, &p);
5627 acfg->unwind_info_offset += encoded_len + (p - buf);
5633 emit_exception_debug_info (MonoAotCompile *acfg, MonoCompile *cfg, gboolean store_seq_points)
5636 guint32 debug_info_size, seq_points_size;
5638 MonoMethodHeader *header;
5639 guint8 *p, *buf, *debug_info;
5640 MonoJitInfo *jinfo = cfg->jit_info;
5642 gboolean use_unwind_ops = FALSE;
5643 MonoSeqPointInfo *seq_points;
5645 code = cfg->native_code;
5646 header = cfg->header;
5648 if (!acfg->aot_opts.nodebug) {
5649 mono_debug_serialize_debug_info (cfg, &debug_info, &debug_info_size);
5652 debug_info_size = 0;
5655 seq_points = cfg->seq_point_info;
5656 seq_points_size = (store_seq_points)? mono_seq_point_info_get_write_size (seq_points) : 0;
5658 buf_size = header->num_clauses * 256 + debug_info_size + 2048 + seq_points_size + cfg->gc_map_size;
5660 p = buf = g_malloc (buf_size);
5662 use_unwind_ops = cfg->unwind_ops != NULL;
5664 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);
5666 encode_value (flags, p, &p);
5668 if (use_unwind_ops) {
5669 guint32 encoded_len;
5671 guint32 unwind_desc;
5673 encoded = mono_unwind_ops_encode (cfg->unwind_ops, &encoded_len);
5675 unwind_desc = get_unwind_info_offset (acfg, encoded, encoded_len);
5676 encode_value (unwind_desc, p, &p);
5678 encode_value (jinfo->unwind_info, p, &p);
5681 /*Encode the number of holes before the number of clauses to make decoding easier*/
5682 if (jinfo->has_try_block_holes) {
5683 MonoTryBlockHoleTableJitInfo *table = mono_jit_info_get_try_block_hole_table_info (jinfo);
5684 encode_value (table->num_holes, p, &p);
5687 if (jinfo->has_arch_eh_info) {
5689 * In AOT mode, the code length is calculated from the address of the previous method,
5690 * which could include alignment padding, so calculating the start of the epilog as
5691 * code_len - epilog_size is correct any more. Save the real code len as a workaround.
5693 encode_value (jinfo->code_size, p, &p);
5696 /* Exception table */
5697 if (cfg->compile_llvm) {
5699 * When using LLVM, we can't emit some data, like pc offsets, this reg/offset etc.,
5700 * since the information is only available to llc. Instead, we let llc save the data
5701 * into the LSDA, and read it from there at runtime.
5703 /* The assembly might be CIL stripped so emit the data ourselves */
5704 if (header->num_clauses)
5705 encode_value (header->num_clauses, p, &p);
5707 for (k = 0; k < header->num_clauses; ++k) {
5708 MonoExceptionClause *clause;
5710 clause = &header->clauses [k];
5712 encode_value (clause->flags, p, &p);
5713 if (clause->data.catch_class) {
5714 encode_value (1, p, &p);
5715 encode_klass_ref (acfg, clause->data.catch_class, p, &p);
5717 encode_value (0, p, &p);
5720 /* Emit a list of nesting clauses */
5721 for (i = 0; i < header->num_clauses; ++i) {
5723 MonoExceptionClause *clause1 = &header->clauses [cindex1];
5725 MonoExceptionClause *clause2 = &header->clauses [cindex2];
5727 if (cindex1 != cindex2 && clause1->try_offset >= clause2->try_offset && clause1->handler_offset <= clause2->handler_offset)
5728 encode_value (i, p, &p);
5730 encode_value (-1, p, &p);
5733 if (jinfo->num_clauses)
5734 encode_value (jinfo->num_clauses, p, &p);
5736 for (k = 0; k < jinfo->num_clauses; ++k) {
5737 MonoJitExceptionInfo *ei = &jinfo->clauses [k];
5739 encode_value (ei->flags, p, &p);
5740 #ifdef MONO_CONTEXT_SET_LLVM_EXC_REG
5741 /* Not used for catch clauses */
5742 if (ei->flags != MONO_EXCEPTION_CLAUSE_NONE)
5743 encode_value (ei->exvar_offset, p, &p);
5745 encode_value (ei->exvar_offset, p, &p);
5748 if (ei->flags == MONO_EXCEPTION_CLAUSE_FILTER || ei->flags == MONO_EXCEPTION_CLAUSE_FINALLY)
5749 encode_value ((gint)((guint8*)ei->data.filter - code), p, &p);
5751 if (ei->data.catch_class) {
5755 buf2 = g_malloc (4096);
5757 encode_klass_ref (acfg, ei->data.catch_class, p2, &p2);
5759 g_assert (len < 4096);
5760 encode_value (len, p, &p);
5761 memcpy (p, buf2, len);
5765 encode_value (0, p, &p);
5769 encode_value ((gint)((guint8*)ei->try_start - code), p, &p);
5770 encode_value ((gint)((guint8*)ei->try_end - code), p, &p);
5771 encode_value ((gint)((guint8*)ei->handler_start - code), p, &p);
5775 if (jinfo->has_try_block_holes) {
5776 MonoTryBlockHoleTableJitInfo *table = mono_jit_info_get_try_block_hole_table_info (jinfo);
5777 for (i = 0; i < table->num_holes; ++i) {
5778 MonoTryBlockHoleJitInfo *hole = &table->holes [i];
5779 encode_value (hole->clause, p, &p);
5780 encode_value (hole->length, p, &p);
5781 encode_value (hole->offset, p, &p);
5785 if (jinfo->has_arch_eh_info) {
5786 MonoArchEHJitInfo *eh_info;
5788 eh_info = mono_jit_info_get_arch_eh_info (jinfo);
5789 encode_value (eh_info->stack_size, p, &p);
5790 encode_value (eh_info->epilog_size, p, &p);
5793 if (jinfo->has_generic_jit_info) {
5794 MonoGenericJitInfo *gi = mono_jit_info_get_generic_jit_info (jinfo);
5795 MonoGenericSharingContext* gsctx = gi->generic_sharing_context;
5799 encode_value (gi->nlocs, p, &p);
5801 for (i = 0; i < gi->nlocs; ++i) {
5802 MonoDwarfLocListEntry *entry = &gi->locations [i];
5804 encode_value (entry->is_reg ? 1 : 0, p, &p);
5805 encode_value (entry->reg, p, &p);
5807 encode_value (entry->offset, p, &p);
5809 g_assert (entry->from == 0);
5811 encode_value (entry->from, p, &p);
5812 encode_value (entry->to, p, &p);
5815 if (!cfg->compile_llvm) {
5816 encode_value (gi->has_this ? 1 : 0, p, &p);
5817 encode_value (gi->this_reg, p, &p);
5818 encode_value (gi->this_offset, p, &p);
5823 * Need to encode jinfo->method too, since it is not equal to 'method'
5824 * when using generic sharing.
5826 buf2 = g_malloc (4096);
5828 encode_method_ref (acfg, jinfo->d.method, p2, &p2);
5830 g_assert (len < 4096);
5831 encode_value (len, p, &p);
5832 memcpy (p, buf2, len);
5836 if (gsctx && gsctx->is_gsharedvt) {
5837 encode_value (1, p, &p);
5839 encode_value (0, p, &p);
5843 if (seq_points_size)
5844 p += mono_seq_point_info_write (seq_points, p);
5846 g_assert (debug_info_size < buf_size);
5848 encode_value (debug_info_size, p, &p);
5849 if (debug_info_size) {
5850 memcpy (p, debug_info, debug_info_size);
5851 p += debug_info_size;
5852 g_free (debug_info);
5857 encode_value (cfg->gc_map_size, p, &p);
5858 /* The GC map requires 4 bytes of alignment */
5859 while ((gsize)p % 4)
5861 memcpy (p, cfg->gc_map, cfg->gc_map_size);
5862 p += cfg->gc_map_size;
5865 acfg->stats.ex_info_size += p - buf;
5867 g_assert (p - buf < buf_size);
5870 /* The GC Map requires 4 byte alignment */
5871 cfg->ex_info_offset = add_to_blob_aligned (acfg, buf, p - buf, cfg->gc_map ? 4 : 1);
5876 emit_klass_info (MonoAotCompile *acfg, guint32 token)
5879 MonoClass *klass = mono_class_get_checked (acfg->image, token, &error);
5881 int i, buf_size, res;
5882 gboolean no_special_static, cant_encode;
5883 gpointer iter = NULL;
5886 mono_error_cleanup (&error);
5890 p = buf = g_malloc (buf_size);
5892 /* Mark as unusable */
5893 encode_value (-1, p, &p);
5895 res = add_to_blob (acfg, buf, p - buf);
5901 buf_size = 10240 + (klass->vtable_size * 16);
5902 p = buf = g_malloc (buf_size);
5906 mono_class_init (klass);
5908 mono_class_get_nested_types (klass, &iter);
5909 g_assert (klass->nested_classes_inited);
5911 mono_class_setup_vtable (klass);
5914 * Emit all the information which is required for creating vtables so
5915 * the runtime does not need to create the MonoMethod structures which
5916 * take up a lot of space.
5919 no_special_static = !mono_class_has_special_static_fields (klass);
5921 /* Check whenever we have enough info to encode the vtable */
5922 cant_encode = FALSE;
5923 for (i = 0; i < klass->vtable_size; ++i) {
5924 MonoMethod *cm = klass->vtable [i];
5926 if (cm && mono_method_signature (cm)->is_inflated && !g_hash_table_lookup (acfg->token_info_hash, cm))
5930 mono_class_has_finalizer (klass);
5932 if (klass->generic_container || cant_encode) {
5933 encode_value (-1, p, &p);
5935 encode_value (klass->vtable_size, p, &p);
5936 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);
5937 if (klass->has_cctor)
5938 encode_method_ref (acfg, mono_class_get_cctor (klass), p, &p);
5939 if (klass->has_finalize)
5940 encode_method_ref (acfg, mono_class_get_finalizer (klass), p, &p);
5942 encode_value (klass->instance_size, p, &p);
5943 encode_value (mono_class_data_size (klass), p, &p);
5944 encode_value (klass->packing_size, p, &p);
5945 encode_value (klass->min_align, p, &p);
5947 for (i = 0; i < klass->vtable_size; ++i) {
5948 MonoMethod *cm = klass->vtable [i];
5951 encode_method_ref (acfg, cm, p, &p);
5953 encode_value (0, p, &p);
5957 acfg->stats.class_info_size += p - buf;
5959 g_assert (p - buf < buf_size);
5960 res = add_to_blob (acfg, buf, p - buf);
5967 get_plt_entry_debug_sym (MonoAotCompile *acfg, MonoJumpInfo *ji, GHashTable *cache)
5969 char *debug_sym = NULL;
5972 if (acfg->llvm && llvm_acfg->aot_opts.static_link) {
5973 /* Need to add a prefix to create unique symbols */
5974 prefix = g_strdup_printf ("plt_%s_", acfg->assembly_name_sym);
5976 prefix = g_strdup ("plt_");
5980 case MONO_PATCH_INFO_METHOD:
5981 debug_sym = get_debug_sym (ji->data.method, prefix, cache);
5983 case MONO_PATCH_INFO_INTERNAL_METHOD:
5984 debug_sym = g_strdup_printf ("%s_jit_icall_%s", prefix, ji->data.name);
5986 case MONO_PATCH_INFO_RGCTX_FETCH:
5987 debug_sym = g_strdup_printf ("%s_rgctx_fetch_%d", prefix, acfg->label_generator ++);
5989 case MONO_PATCH_INFO_ICALL_ADDR: {
5990 char *s = get_debug_sym (ji->data.method, "", cache);
5992 debug_sym = g_strdup_printf ("%s_icall_native_%s", prefix, s);
5996 case MONO_PATCH_INFO_JIT_ICALL_ADDR:
5997 debug_sym = g_strdup_printf ("%s_jit_icall_native_%s", prefix, ji->data.name);
6005 return sanitize_symbol (acfg, debug_sym);
6009 * Calls made from AOTed code are routed through a table of jumps similar to the
6010 * ELF PLT (Program Linkage Table). Initially the PLT entries jump to code which transfers
6011 * control to the AOT runtime through a trampoline.
6014 emit_plt (MonoAotCompile *acfg)
6020 sprintf (symbol, "plt");
6022 emit_section_change (acfg, ".text", 0);
6023 emit_alignment_code (acfg, NACL_SIZE(16, kNaClAlignment));
6024 emit_info_symbol (acfg, symbol);
6025 emit_label (acfg, acfg->plt_symbol);
6027 for (i = 0; i < acfg->plt_offset; ++i) {
6028 char *debug_sym = NULL;
6029 MonoPltEntry *plt_entry = NULL;
6033 * The first plt entry is unused.
6037 plt_entry = g_hash_table_lookup (acfg->plt_offset_to_entry, GUINT_TO_POINTER (i));
6039 debug_sym = plt_entry->debug_sym;
6041 if (acfg->thumb_mixed && !plt_entry->jit_used)
6042 /* Emit only a thumb version */
6045 /* Skip plt entries not actually called */
6046 if (!plt_entry->jit_used && !plt_entry->llvm_used)
6049 if (acfg->llvm && !acfg->thumb_mixed) {
6050 emit_label (acfg, plt_entry->llvm_symbol);
6052 emit_global_inner (acfg, plt_entry->llvm_symbol, TRUE);
6053 #if defined(TARGET_MACH)
6054 fprintf (acfg->fp, ".private_extern %s\n", plt_entry->llvm_symbol);
6060 if (acfg->need_no_dead_strip) {
6061 emit_unset_mode (acfg);
6062 fprintf (acfg->fp, " .no_dead_strip %s\n", debug_sym);
6064 emit_local_symbol (acfg, debug_sym, NULL, TRUE);
6065 emit_label (acfg, debug_sym);
6068 emit_label (acfg, plt_entry->symbol);
6070 arch_emit_plt_entry (acfg, acfg->got_symbol, (acfg->plt_got_offset_base + i) * sizeof (gpointer), acfg->plt_got_info_offsets [i]);
6073 emit_symbol_size (acfg, debug_sym, ".");
6076 if (acfg->thumb_mixed) {
6077 /* Make sure the ARM symbols don't alias the thumb ones */
6078 emit_zero_bytes (acfg, 16);
6081 * Emit a separate set of PLT entries using thumb2 which is called by LLVM generated
6084 for (i = 0; i < acfg->plt_offset; ++i) {
6085 char *debug_sym = NULL;
6086 MonoPltEntry *plt_entry = NULL;
6091 plt_entry = g_hash_table_lookup (acfg->plt_offset_to_entry, GUINT_TO_POINTER (i));
6093 /* Skip plt entries not actually called by LLVM code */
6094 if (!plt_entry->llvm_used)
6097 if (acfg->aot_opts.write_symbols) {
6098 if (plt_entry->debug_sym)
6099 debug_sym = g_strdup_printf ("%s_thumb", plt_entry->debug_sym);
6103 #if defined(TARGET_MACH)
6104 fprintf (acfg->fp, " .thumb_func %s\n", debug_sym);
6105 fprintf (acfg->fp, " .no_dead_strip %s\n", debug_sym);
6107 emit_local_symbol (acfg, debug_sym, NULL, TRUE);
6108 emit_label (acfg, debug_sym);
6110 fprintf (acfg->fp, "\n.thumb_func\n");
6112 emit_label (acfg, plt_entry->llvm_symbol);
6115 emit_global_inner (acfg, plt_entry->llvm_symbol, TRUE);
6117 arch_emit_llvm_plt_entry (acfg, acfg->got_symbol, (acfg->plt_got_offset_base + i) * sizeof (gpointer), acfg->plt_got_info_offsets [i]);
6120 emit_symbol_size (acfg, debug_sym, ".");
6126 emit_symbol_size (acfg, acfg->plt_symbol, ".");
6128 sprintf (symbol, "plt_end");
6129 emit_info_symbol (acfg, symbol);
6133 * emit_trampoline_full:
6135 * If EMIT_TINFO is TRUE, emit additional information which can be used to create a MonoJitInfo for this trampoline by
6136 * create_jit_info_for_trampoline ().
6138 static G_GNUC_UNUSED void
6139 emit_trampoline_full (MonoAotCompile *acfg, int got_offset, MonoTrampInfo *info, gboolean emit_tinfo)
6141 char start_symbol [256];
6142 char end_symbol [256];
6144 guint32 buf_size, info_offset;
6145 MonoJumpInfo *patch_info;
6158 code_size = info->code_size;
6160 unwind_ops = info->unwind_ops;
6162 #ifdef __native_client_codegen__
6163 mono_nacl_fix_patches (code, ji);
6168 sprintf (start_symbol, "%s%s", acfg->user_symbol_prefix, name);
6170 emit_section_change (acfg, ".text", 0);
6171 emit_global (acfg, start_symbol, TRUE);
6172 emit_alignment_code (acfg, AOT_FUNC_ALIGNMENT);
6173 emit_label (acfg, start_symbol);
6175 sprintf (symbol, "%snamed_%s", acfg->temp_prefix, name);
6176 emit_label (acfg, symbol);
6179 * The code should access everything through the GOT, so we pass
6182 emit_and_reloc_code (acfg, NULL, code, code_size, ji, TRUE, NULL);
6184 emit_symbol_size (acfg, start_symbol, ".");
6187 sprintf (end_symbol, "%snamede_%s", acfg->temp_prefix, name);
6188 emit_label (acfg, end_symbol);
6193 /* Sort relocations */
6194 patches = g_ptr_array_new ();
6195 for (patch_info = ji; patch_info; patch_info = patch_info->next)
6196 if (patch_info->type != MONO_PATCH_INFO_NONE)
6197 g_ptr_array_add (patches, patch_info);
6198 g_ptr_array_sort (patches, compare_patches);
6200 buf_size = patches->len * 128 + 128;
6201 buf = g_malloc (buf_size);
6204 encode_patch_list (acfg, patches, patches->len, FALSE, got_offset, p, &p);
6205 g_assert (p - buf < buf_size);
6207 sprintf (symbol, "%s%s_p", acfg->user_symbol_prefix, name);
6209 info_offset = add_to_blob (acfg, buf, p - buf);
6211 emit_section_change (acfg, RODATA_SECT, 0);
6212 emit_global (acfg, symbol, FALSE);
6213 emit_label (acfg, symbol);
6215 emit_int32 (acfg, info_offset);
6219 guint32 encoded_len;
6223 * Emit additional information which can be used to reconstruct a partial MonoTrampInfo.
6225 encoded = mono_unwind_ops_encode (info->unwind_ops, &encoded_len);
6226 uw_offset = get_unwind_info_offset (acfg, encoded, encoded_len);
6229 emit_symbol_diff (acfg, end_symbol, start_symbol, 0);
6230 emit_int32 (acfg, uw_offset);
6233 /* Emit debug info */
6237 sprintf (symbol, "%s", name);
6238 sprintf (symbol2, "%snamed_%s", acfg->temp_prefix, name);
6241 mono_dwarf_writer_emit_trampoline (acfg->dwarf, symbol, symbol2, NULL, NULL, code_size, unwind_ops);
6245 static G_GNUC_UNUSED void
6246 emit_trampoline (MonoAotCompile *acfg, int got_offset, MonoTrampInfo *info)
6248 emit_trampoline_full (acfg, got_offset, info, TRUE);
6252 emit_trampolines (MonoAotCompile *acfg)
6255 char end_symbol [256];
6256 int i, tramp_got_offset;
6257 MonoAotTrampoline ntype;
6258 #ifdef MONO_ARCH_HAVE_FULL_AOT_TRAMPOLINES
6262 if (!mono_aot_mode_is_full (&acfg->aot_opts))
6265 g_assert (acfg->image->assembly);
6267 /* Currently, we emit most trampolines into the mscorlib AOT image. */
6268 if (strcmp (acfg->image->assembly->aname.name, "mscorlib") == 0) {
6269 #ifdef MONO_ARCH_HAVE_FULL_AOT_TRAMPOLINES
6270 MonoTrampInfo *info;
6273 * Emit the generic trampolines.
6275 * We could save some code by treating the generic trampolines as a wrapper
6276 * method, but that approach has its own complexities, so we choose the simpler
6279 for (tramp_type = 0; tramp_type < MONO_TRAMPOLINE_NUM; ++tramp_type) {
6280 /* we overload the boolean here to indicate the slightly different trampoline needed, see mono_arch_create_generic_trampoline() */
6281 #ifdef DISABLE_REMOTING
6282 if (tramp_type == MONO_TRAMPOLINE_GENERIC_VIRTUAL_REMOTING)
6285 #ifndef MONO_ARCH_HAVE_HANDLER_BLOCK_GUARD
6286 if (tramp_type == MONO_TRAMPOLINE_HANDLER_BLOCK_GUARD)
6289 mono_arch_create_generic_trampoline (tramp_type, &info, acfg->aot_opts.use_trampolines_page? 2: TRUE);
6290 emit_trampoline (acfg, acfg->got_offset, info);
6293 /* Emit the exception related code pieces */
6294 mono_arch_get_restore_context (&info, TRUE);
6295 emit_trampoline (acfg, acfg->got_offset, info);
6296 mono_arch_get_call_filter (&info, TRUE);
6297 emit_trampoline (acfg, acfg->got_offset, info);
6298 mono_arch_get_throw_exception (&info, TRUE);
6299 emit_trampoline (acfg, acfg->got_offset, info);
6300 mono_arch_get_rethrow_exception (&info, TRUE);
6301 emit_trampoline (acfg, acfg->got_offset, info);
6302 mono_arch_get_throw_corlib_exception (&info, TRUE);
6303 emit_trampoline (acfg, acfg->got_offset, info);
6305 #ifdef MONO_ARCH_HAVE_SDB_TRAMPOLINES
6306 mono_arch_create_sdb_trampoline (TRUE, &info, TRUE);
6307 emit_trampoline (acfg, acfg->got_offset, info);
6308 mono_arch_create_sdb_trampoline (FALSE, &info, TRUE);
6309 emit_trampoline (acfg, acfg->got_offset, info);
6312 #ifdef MONO_ARCH_GSHAREDVT_SUPPORTED
6313 mono_arch_get_gsharedvt_trampoline (&info, TRUE);
6315 emit_trampoline_full (acfg, acfg->got_offset, info, TRUE);
6317 /* Create a separate out trampoline for more information in stack traces */
6318 info->name = g_strdup ("gsharedvt_out_trampoline");
6319 emit_trampoline_full (acfg, acfg->got_offset, info, TRUE);
6323 #if defined(MONO_ARCH_HAVE_GET_TRAMPOLINES)
6325 GSList *l = mono_arch_get_trampolines (TRUE);
6328 MonoTrampInfo *info = l->data;
6330 emit_trampoline (acfg, acfg->got_offset, info);
6336 for (i = 0; i < acfg->aot_opts.nrgctx_fetch_trampolines; ++i) {
6339 offset = MONO_RGCTX_SLOT_MAKE_RGCTX (i);
6340 mono_arch_create_rgctx_lazy_fetch_trampoline (offset, &info, TRUE);
6341 emit_trampoline (acfg, acfg->got_offset, info);
6343 offset = MONO_RGCTX_SLOT_MAKE_MRGCTX (i);
6344 mono_arch_create_rgctx_lazy_fetch_trampoline (offset, &info, TRUE);
6345 emit_trampoline (acfg, acfg->got_offset, info);
6348 #ifdef MONO_ARCH_HAVE_GENERAL_RGCTX_LAZY_FETCH_TRAMPOLINE
6349 mono_arch_create_general_rgctx_lazy_fetch_trampoline (&info, TRUE);
6350 emit_trampoline (acfg, acfg->got_offset, info);
6356 /* delegate_invoke_impl trampolines */
6357 l = mono_arch_get_delegate_invoke_impls ();
6359 MonoTrampInfo *info = l->data;
6361 emit_trampoline (acfg, acfg->got_offset, info);
6366 #endif /* #ifdef MONO_ARCH_HAVE_FULL_AOT_TRAMPOLINES */
6368 /* Emit trampolines which are numerous */
6371 * These include the following:
6372 * - specific trampolines
6373 * - static rgctx invoke trampolines
6375 * These trampolines have the same code, they are parameterized by GOT
6377 * They are defined in this file, in the arch_... routines instead of
6378 * in tramp-<ARCH>.c, since it is easier to do it this way.
6382 * When running in aot-only mode, we can't create specific trampolines at
6383 * runtime, so we create a few, and save them in the AOT file.
6384 * Normal trampolines embed their argument as a literal inside the
6385 * trampoline code, we can't do that here, so instead we embed an offset
6386 * which needs to be added to the trampoline address to get the address of
6387 * the GOT slot which contains the argument value.
6388 * The generated trampolines jump to the generic trampolines using another
6389 * GOT slot, which will be setup by the AOT loader to point to the
6390 * generic trampoline code of the given type.
6394 * FIXME: Maybe we should use more specific trampolines (i.e. one class init for
6398 emit_section_change (acfg, ".text", 0);
6400 tramp_got_offset = acfg->got_offset;
6402 for (ntype = 0; ntype < MONO_AOT_TRAMP_NUM; ++ntype) {
6404 case MONO_AOT_TRAMP_SPECIFIC:
6405 sprintf (symbol, "specific_trampolines");
6407 case MONO_AOT_TRAMP_STATIC_RGCTX:
6408 sprintf (symbol, "static_rgctx_trampolines");
6410 case MONO_AOT_TRAMP_IMT_THUNK:
6411 sprintf (symbol, "imt_thunks");
6413 case MONO_AOT_TRAMP_GSHAREDVT_ARG:
6414 sprintf (symbol, "gsharedvt_arg_trampolines");
6417 g_assert_not_reached ();
6420 sprintf (end_symbol, "%s_e", symbol);
6422 if (acfg->aot_opts.write_symbols)
6423 emit_local_symbol (acfg, symbol, end_symbol, TRUE);
6425 emit_alignment_code (acfg, AOT_FUNC_ALIGNMENT);
6426 emit_info_symbol (acfg, symbol);
6428 acfg->trampoline_got_offset_base [ntype] = tramp_got_offset;
6430 for (i = 0; i < acfg->num_trampolines [ntype]; ++i) {
6434 case MONO_AOT_TRAMP_SPECIFIC:
6435 arch_emit_specific_trampoline (acfg, tramp_got_offset, &tramp_size);
6436 tramp_got_offset += 2;
6438 case MONO_AOT_TRAMP_STATIC_RGCTX:
6439 arch_emit_static_rgctx_trampoline (acfg, tramp_got_offset, &tramp_size);
6440 tramp_got_offset += 2;
6442 case MONO_AOT_TRAMP_IMT_THUNK:
6443 arch_emit_imt_thunk (acfg, tramp_got_offset, &tramp_size);
6444 tramp_got_offset += 1;
6446 case MONO_AOT_TRAMP_GSHAREDVT_ARG:
6447 arch_emit_gsharedvt_arg_trampoline (acfg, tramp_got_offset, &tramp_size);
6448 tramp_got_offset += 2;
6451 g_assert_not_reached ();
6453 #ifdef __native_client_codegen__
6454 /* align to avoid 32-byte boundary crossings */
6455 emit_alignment (acfg, AOT_FUNC_ALIGNMENT);
6458 if (!acfg->trampoline_size [ntype]) {
6459 g_assert (tramp_size);
6460 acfg->trampoline_size [ntype] = tramp_size;
6464 emit_label (acfg, end_symbol);
6465 emit_int32 (acfg, 0);
6468 arch_emit_specific_trampoline_pages (acfg);
6470 /* Reserve some entries at the end of the GOT for our use */
6471 acfg->num_trampoline_got_entries = tramp_got_offset - acfg->got_offset;
6474 acfg->got_offset += acfg->num_trampoline_got_entries;
6478 str_begins_with (const char *str1, const char *str2)
6480 int len = strlen (str2);
6481 return strncmp (str1, str2, len) == 0;
6485 mono_aot_readonly_field_override (MonoClassField *field)
6488 for (rdv = readonly_values; rdv; rdv = rdv->next) {
6489 char *p = rdv->name;
6491 len = strlen (field->parent->name_space);
6492 if (strncmp (p, field->parent->name_space, len))
6497 len = strlen (field->parent->name);
6498 if (strncmp (p, field->parent->name, len))
6503 if (strcmp (p, field->name))
6505 switch (rdv->type) {
6507 return &rdv->value.i1;
6509 return &rdv->value.i2;
6511 return &rdv->value.i4;
6520 add_readonly_value (MonoAotOptions *opts, const char *val)
6525 /* the format of val is:
6526 * namespace.typename.fieldname=type/value
6527 * type can be i1 for uint8/int8/boolean, i2 for uint16/int16/char, i4 for uint32/int32
6529 fval = strrchr (val, '/');
6531 fprintf (stderr, "AOT : invalid format for readonly field '%s', missing /.\n", val);
6534 tval = strrchr (val, '=');
6536 fprintf (stderr, "AOT : invalid format for readonly field '%s', missing =.\n", val);
6539 rdv = g_new0 (ReadOnlyValue, 1);
6540 rdv->name = g_malloc0 (tval - val + 1);
6541 memcpy (rdv->name, val, tval - val);
6544 if (strncmp (tval, "i1", 2) == 0) {
6545 rdv->value.i1 = atoi (fval);
6546 rdv->type = MONO_TYPE_I1;
6547 } else if (strncmp (tval, "i2", 2) == 0) {
6548 rdv->value.i2 = atoi (fval);
6549 rdv->type = MONO_TYPE_I2;
6550 } else if (strncmp (tval, "i4", 2) == 0) {
6551 rdv->value.i4 = atoi (fval);
6552 rdv->type = MONO_TYPE_I4;
6554 fprintf (stderr, "AOT : unsupported type for readonly field '%s'.\n", tval);
6557 rdv->next = readonly_values;
6558 readonly_values = rdv;
6562 clean_path (gchar * path)
6567 if (g_str_has_suffix (path, G_DIR_SEPARATOR_S))
6570 gchar *clean = g_strconcat (path, G_DIR_SEPARATOR_S, NULL);
6577 mono_aot_split_options (const char *aot_options)
6579 enum MonoAotOptionState {
6580 MONO_AOT_OPTION_STATE_DEFAULT,
6581 MONO_AOT_OPTION_STATE_STRING,
6582 MONO_AOT_OPTION_STATE_ESCAPE,
6585 GPtrArray *args = g_ptr_array_new ();
6586 enum MonoAotOptionState state = MONO_AOT_OPTION_STATE_DEFAULT;
6587 gchar const *opt_start = aot_options;
6588 gboolean end_of_string = FALSE;
6591 g_return_val_if_fail (aot_options != NULL, NULL);
6593 while ((cur = *aot_options) != '\0') {
6594 if (state == MONO_AOT_OPTION_STATE_ESCAPE)
6599 // If we find a quote, then if we're in the default case then
6600 // it means we've found the start of a string, if not then it
6601 // means we've found the end of the string and should switch
6602 // back to the default case.
6604 case MONO_AOT_OPTION_STATE_DEFAULT:
6605 state = MONO_AOT_OPTION_STATE_STRING;
6607 case MONO_AOT_OPTION_STATE_STRING:
6608 state = MONO_AOT_OPTION_STATE_DEFAULT;
6610 case MONO_AOT_OPTION_STATE_ESCAPE:
6611 g_assert_not_reached ();
6616 // If we've found an escaping operator, then this means we
6617 // should not process the next character if inside a string.
6618 if (state == MONO_AOT_OPTION_STATE_STRING)
6619 state = MONO_AOT_OPTION_STATE_ESCAPE;
6622 // If we're in the default state then this means we've found
6623 // an option, store it for later processing.
6624 if (state == MONO_AOT_OPTION_STATE_DEFAULT)
6631 // If the next character is end of string, then process the last option.
6632 if (*(aot_options) == '\0') {
6633 end_of_string = TRUE;
6639 g_ptr_array_add (args, g_strndup (opt_start, aot_options - opt_start));
6640 opt_start = ++aot_options;
6650 mono_aot_parse_options (const char *aot_options, MonoAotOptions *opts)
6654 args = mono_aot_split_options (aot_options ? aot_options : "");
6655 for (int i = 0; i < args->len; ++i) {
6656 const char *arg = g_ptr_array_index (args, i);
6658 if (str_begins_with (arg, "outfile=")) {
6659 opts->outfile = g_strdup (arg + strlen ("outfile="));
6660 } else if (str_begins_with (arg, "llvm-outfile=")) {
6661 opts->llvm_outfile = g_strdup (arg + strlen ("llvm-outfile="));
6662 } else if (str_begins_with (arg, "temp-path=")) {
6663 opts->temp_path = clean_path (g_strdup (arg + strlen ("temp-path=")));
6664 } else if (str_begins_with (arg, "save-temps")) {
6665 opts->save_temps = TRUE;
6666 } else if (str_begins_with (arg, "keep-temps")) {
6667 opts->save_temps = TRUE;
6668 } else if (str_begins_with (arg, "write-symbols")) {
6669 opts->write_symbols = TRUE;
6670 } else if (str_begins_with (arg, "no-write-symbols")) {
6671 opts->write_symbols = FALSE;
6672 } else if (str_begins_with (arg, "metadata-only")) {
6673 opts->metadata_only = TRUE;
6674 } else if (str_begins_with (arg, "bind-to-runtime-version")) {
6675 opts->bind_to_runtime_version = TRUE;
6676 } else if (str_begins_with (arg, "full")) {
6677 opts->mode = MONO_AOT_MODE_FULL;
6678 } else if (str_begins_with (arg, "hybrid")) {
6679 opts->mode = MONO_AOT_MODE_HYBRID;
6680 } else if (str_begins_with (arg, "threads=")) {
6681 opts->nthreads = atoi (arg + strlen ("threads="));
6682 } else if (str_begins_with (arg, "static")) {
6683 opts->static_link = TRUE;
6684 opts->no_dlsym = TRUE;
6685 } else if (str_begins_with (arg, "asmonly")) {
6686 opts->asm_only = TRUE;
6687 } else if (str_begins_with (arg, "asmwriter")) {
6688 opts->asm_writer = TRUE;
6689 } else if (str_begins_with (arg, "nodebug")) {
6690 opts->nodebug = TRUE;
6691 } else if (str_begins_with (arg, "dwarfdebug")) {
6692 opts->dwarf_debug = TRUE;
6693 } else if (str_begins_with (arg, "nopagetrampolines")) {
6694 opts->use_trampolines_page = FALSE;
6695 } else if (str_begins_with (arg, "ntrampolines=")) {
6696 opts->ntrampolines = atoi (arg + strlen ("ntrampolines="));
6697 } else if (str_begins_with (arg, "nrgctx-trampolines=")) {
6698 opts->nrgctx_trampolines = atoi (arg + strlen ("nrgctx-trampolines="));
6699 } else if (str_begins_with (arg, "nimt-trampolines=")) {
6700 opts->nimt_trampolines = atoi (arg + strlen ("nimt-trampolines="));
6701 } else if (str_begins_with (arg, "ngsharedvt-trampolines=")) {
6702 opts->ngsharedvt_arg_trampolines = atoi (arg + strlen ("ngsharedvt-trampolines="));
6703 } else if (str_begins_with (arg, "autoreg")) {
6704 opts->autoreg = TRUE;
6705 } else if (str_begins_with (arg, "tool-prefix=")) {
6706 opts->tool_prefix = g_strdup (arg + strlen ("tool-prefix="));
6707 } else if (str_begins_with (arg, "ld-flags=")) {
6708 opts->ld_flags = g_strdup (arg + strlen ("ld-flags="));
6709 } else if (str_begins_with (arg, "soft-debug")) {
6710 opts->soft_debug = TRUE;
6711 } else if (str_begins_with (arg, "gen-seq-points-file")) {
6712 opts->gen_seq_points_file = TRUE;
6713 } else if (str_begins_with (arg, "direct-pinvoke")) {
6714 opts->direct_pinvoke = TRUE;
6715 } else if (str_begins_with (arg, "direct-icalls")) {
6716 opts->direct_icalls = TRUE;
6717 } else if (str_begins_with (arg, "no-direct-calls")) {
6718 opts->no_direct_calls = TRUE;
6719 } else if (str_begins_with (arg, "print-skipped")) {
6720 opts->print_skipped_methods = TRUE;
6721 } else if (str_begins_with (arg, "stats")) {
6723 } else if (str_begins_with (arg, "no-instances")) {
6724 opts->no_instances = TRUE;
6725 } else if (str_begins_with (arg, "log-generics")) {
6726 opts->log_generics = TRUE;
6727 } else if (str_begins_with (arg, "log-instances=")) {
6728 opts->log_instances = TRUE;
6729 opts->instances_logfile_path = g_strdup (arg + strlen ("log-instances="));
6730 } else if (str_begins_with (arg, "log-instances")) {
6731 opts->log_instances = TRUE;
6732 } else if (str_begins_with (arg, "internal-logfile=")) {
6733 opts->logfile = g_strdup (arg + strlen ("internal-logfile="));
6734 } else if (str_begins_with (arg, "mtriple=")) {
6735 opts->mtriple = g_strdup (arg + strlen ("mtriple="));
6736 } else if (str_begins_with (arg, "llvm-path=")) {
6737 opts->llvm_path = clean_path (g_strdup (arg + strlen ("llvm-path=")));
6738 } else if (!strcmp (arg, "llvm")) {
6740 } else if (str_begins_with (arg, "readonly-value=")) {
6741 add_readonly_value (opts, arg + strlen ("readonly-value="));
6742 } else if (str_begins_with (arg, "info")) {
6743 printf ("AOT target setup: %s.\n", AOT_TARGET_STR);
6745 } else if (str_begins_with (arg, "gc-maps")) {
6746 mini_gc_enable_gc_maps_for_aot ();
6747 } else if (str_begins_with (arg, "dump")) {
6748 opts->dump_json = TRUE;
6749 } else if (str_begins_with (arg, "help") || str_begins_with (arg, "?")) {
6750 printf ("Supported options for --aot:\n");
6751 printf (" outfile=\n");
6752 printf (" llvm-outfile=\n");
6753 printf (" llvm-path=\n");
6754 printf (" temp-path=\n");
6755 printf (" save-temps\n");
6756 printf (" keep-temps\n");
6757 printf (" write-symbols\n");
6758 printf (" metadata-only\n");
6759 printf (" bind-to-runtime-version\n");
6761 printf (" threads=\n");
6762 printf (" static\n");
6763 printf (" asmonly\n");
6764 printf (" asmwriter\n");
6765 printf (" nodebug\n");
6766 printf (" dwarfdebug\n");
6767 printf (" ntrampolines=\n");
6768 printf (" nrgctx-trampolines=\n");
6769 printf (" nimt-trampolines=\n");
6770 printf (" ngsharedvt-trampolines=\n");
6771 printf (" autoreg\n");
6772 printf (" tool-prefix=\n");
6773 printf (" readonly-value=\n");
6774 printf (" soft-debug\n");
6775 printf (" gen-seq-points-file\n");
6776 printf (" gc-maps\n");
6777 printf (" print-skipped\n");
6778 printf (" no-instances\n");
6779 printf (" stats\n");
6782 printf (" help/?\n");
6785 fprintf (stderr, "AOT : Unknown argument '%s'.\n", arg);
6789 g_free ((gpointer) arg);
6792 if (opts->use_trampolines_page) {
6793 opts->ntrampolines = 0;
6794 opts->nrgctx_trampolines = 0;
6795 opts->nimt_trampolines = 0;
6796 opts->ngsharedvt_arg_trampolines = 0;
6799 g_ptr_array_free (args, /*free_seg=*/TRUE);
6803 add_token_info_hash (gpointer key, gpointer value, gpointer user_data)
6805 MonoMethod *method = (MonoMethod*)key;
6806 MonoJumpInfoToken *ji = (MonoJumpInfoToken*)value;
6807 MonoAotCompile *acfg = user_data;
6808 MonoJumpInfoToken *new_ji;
6810 new_ji = mono_mempool_alloc0 (acfg->mempool, sizeof (MonoJumpInfoToken));
6811 new_ji->image = ji->image;
6812 new_ji->token = ji->token;
6813 g_hash_table_insert (acfg->token_info_hash, method, new_ji);
6817 can_encode_class (MonoAotCompile *acfg, MonoClass *klass)
6819 if (klass->type_token)
6821 if ((klass->byval_arg.type == MONO_TYPE_VAR) || (klass->byval_arg.type == MONO_TYPE_MVAR) || (klass->byval_arg.type == MONO_TYPE_PTR))
6824 return can_encode_class (acfg, klass->element_class);
6829 can_encode_method (MonoAotCompile *acfg, MonoMethod *method)
6831 if (method->wrapper_type) {
6832 switch (method->wrapper_type) {
6833 case MONO_WRAPPER_NONE:
6834 case MONO_WRAPPER_REMOTING_INVOKE_WITH_CHECK:
6835 case MONO_WRAPPER_XDOMAIN_INVOKE:
6836 case MONO_WRAPPER_STFLD:
6837 case MONO_WRAPPER_LDFLD:
6838 case MONO_WRAPPER_LDFLDA:
6839 case MONO_WRAPPER_LDFLD_REMOTE:
6840 case MONO_WRAPPER_STFLD_REMOTE:
6841 case MONO_WRAPPER_STELEMREF:
6842 case MONO_WRAPPER_ISINST:
6843 case MONO_WRAPPER_PROXY_ISINST:
6844 case MONO_WRAPPER_ALLOC:
6845 case MONO_WRAPPER_REMOTING_INVOKE:
6846 case MONO_WRAPPER_UNKNOWN:
6847 case MONO_WRAPPER_WRITE_BARRIER:
6848 case MONO_WRAPPER_DELEGATE_INVOKE:
6849 case MONO_WRAPPER_DELEGATE_BEGIN_INVOKE:
6850 case MONO_WRAPPER_DELEGATE_END_INVOKE:
6851 case MONO_WRAPPER_SYNCHRONIZED:
6853 case MONO_WRAPPER_MANAGED_TO_MANAGED:
6854 case MONO_WRAPPER_CASTCLASS: {
6855 WrapperInfo *info = mono_marshal_get_wrapper_info (method);
6864 //printf ("Skip (wrapper call): %d -> %s\n", patch_info->type, mono_method_full_name (patch_info->data.method, TRUE));
6868 if (!method->token) {
6869 /* The method is part of a constructed type like Int[,].Set (). */
6870 if (!g_hash_table_lookup (acfg->token_info_hash, method)) {
6871 if (method->klass->rank)
6881 can_encode_patch (MonoAotCompile *acfg, MonoJumpInfo *patch_info)
6883 switch (patch_info->type) {
6884 case MONO_PATCH_INFO_METHOD:
6885 case MONO_PATCH_INFO_METHODCONST:
6886 case MONO_PATCH_INFO_METHOD_CODE_SLOT: {
6887 MonoMethod *method = patch_info->data.method;
6889 return can_encode_method (acfg, method);
6891 case MONO_PATCH_INFO_VTABLE:
6892 case MONO_PATCH_INFO_CLASS:
6893 case MONO_PATCH_INFO_IID:
6894 case MONO_PATCH_INFO_ADJUSTED_IID:
6895 if (!can_encode_class (acfg, patch_info->data.klass)) {
6896 //printf ("Skip: %s\n", mono_type_full_name (&patch_info->data.klass->byval_arg));
6900 case MONO_PATCH_INFO_DELEGATE_TRAMPOLINE: {
6901 if (!can_encode_class (acfg, patch_info->data.del_tramp->klass)) {
6902 //printf ("Skip: %s\n", mono_type_full_name (&patch_info->data.klass->byval_arg));
6907 case MONO_PATCH_INFO_RGCTX_FETCH: {
6908 MonoJumpInfoRgctxEntry *entry = patch_info->data.rgctx_entry;
6910 if (!can_encode_method (acfg, entry->method))
6912 if (!can_encode_patch (acfg, entry->data))
6926 * AOT compile a given method.
6927 * This function might be called by multiple threads, so it must be thread-safe.
6930 compile_method (MonoAotCompile *acfg, MonoMethod *method)
6933 MonoJumpInfo *patch_info;
6936 MonoMethod *wrapped;
6939 if (acfg->aot_opts.metadata_only)
6942 mono_acfg_lock (acfg);
6943 index = get_method_index (acfg, method);
6944 mono_acfg_unlock (acfg);
6946 /* fixme: maybe we can also precompile wrapper methods */
6947 if ((method->flags & METHOD_ATTRIBUTE_PINVOKE_IMPL) ||
6948 (method->iflags & METHOD_IMPL_ATTRIBUTE_RUNTIME) ||
6949 (method->flags & METHOD_ATTRIBUTE_ABSTRACT)) {
6950 //printf ("Skip (impossible): %s\n", mono_method_full_name (method, TRUE));
6954 if (method->iflags & METHOD_IMPL_ATTRIBUTE_INTERNAL_CALL)
6957 wrapped = mono_marshal_method_from_wrapper (method);
6958 if (wrapped && (wrapped->iflags & METHOD_IMPL_ATTRIBUTE_INTERNAL_CALL) && wrapped->is_generic)
6959 // FIXME: The wrapper should be generic too, but it is not
6962 if (method->wrapper_type == MONO_WRAPPER_COMINTEROP)
6965 InterlockedIncrement (&acfg->stats.mcount);
6968 if (method->is_generic || method->klass->generic_container) {
6969 InterlockedIncrement (&acfg->stats.genericcount);
6974 //acfg->aot_opts.print_skipped_methods = TRUE;
6977 * Since these methods are the only ones which are compiled with
6978 * AOT support, and they are not used by runtime startup/shutdown code,
6979 * the runtime will not see AOT methods during AOT compilation,so it
6980 * does not need to support them by creating a fake GOT etc.
6982 flags = JIT_FLAG_AOT;
6983 if (mono_aot_mode_is_full (&acfg->aot_opts))
6984 flags |= JIT_FLAG_FULL_AOT;
6986 flags |= JIT_FLAG_LLVM;
6987 if (acfg->aot_opts.no_direct_calls)
6988 flags |= JIT_FLAG_NO_DIRECT_ICALLS;
6989 cfg = mini_method_compile (method, acfg->opts, mono_get_root_domain (), flags, 0, index);
6990 mono_loader_clear_error ();
6992 if (cfg->exception_type == MONO_EXCEPTION_GENERIC_SHARING_FAILED) {
6993 if (acfg->aot_opts.print_skipped_methods)
6994 printf ("Skip (gshared failure): %s (%s)\n", mono_method_full_name (method, TRUE), cfg->exception_message);
6995 InterlockedIncrement (&acfg->stats.genericcount);
6998 if (cfg->exception_type != MONO_EXCEPTION_NONE) {
6999 if (acfg->aot_opts.print_skipped_methods)
7000 printf ("Skip (JIT failure): %s\n", mono_method_full_name (method, TRUE));
7001 /* Let the exception happen at runtime */
7005 if (cfg->disable_aot) {
7006 if (acfg->aot_opts.print_skipped_methods)
7007 printf ("Skip (disabled): %s\n", mono_method_full_name (method, TRUE));
7008 InterlockedIncrement (&acfg->stats.ocount);
7009 mono_destroy_compile (cfg);
7012 cfg->method_index = index;
7014 /* Nullify patches which need no aot processing */
7015 for (patch_info = cfg->patch_info; patch_info; patch_info = patch_info->next) {
7016 switch (patch_info->type) {
7017 case MONO_PATCH_INFO_LABEL:
7018 case MONO_PATCH_INFO_BB:
7019 patch_info->type = MONO_PATCH_INFO_NONE;
7026 /* Collect method->token associations from the cfg */
7027 mono_acfg_lock (acfg);
7028 g_hash_table_foreach (cfg->token_info_hash, add_token_info_hash, acfg);
7029 mono_acfg_unlock (acfg);
7030 g_hash_table_destroy (cfg->token_info_hash);
7031 cfg->token_info_hash = NULL;
7034 * Check for absolute addresses.
7037 for (patch_info = cfg->patch_info; patch_info; patch_info = patch_info->next) {
7038 switch (patch_info->type) {
7039 case MONO_PATCH_INFO_ABS:
7040 /* unable to handle this */
7049 if (acfg->aot_opts.print_skipped_methods)
7050 printf ("Skip (abs call): %s\n", mono_method_full_name (method, TRUE));
7051 InterlockedIncrement (&acfg->stats.abscount);
7052 mono_destroy_compile (cfg);
7056 /* Lock for the rest of the code */
7057 mono_acfg_lock (acfg);
7060 * Check for methods/klasses we can't encode.
7063 for (patch_info = cfg->patch_info; patch_info; patch_info = patch_info->next) {
7064 if (!can_encode_patch (acfg, patch_info))
7069 if (acfg->aot_opts.print_skipped_methods)
7070 printf ("Skip (patches): %s\n", mono_method_full_name (method, TRUE));
7071 acfg->stats.ocount++;
7072 mono_destroy_compile (cfg);
7073 mono_acfg_unlock (acfg);
7077 if (!cfg->compile_llvm)
7078 acfg->has_jitted_code = TRUE;
7080 if (method->is_inflated && acfg->aot_opts.log_instances) {
7081 if (acfg->instances_logfile)
7082 fprintf (acfg->instances_logfile, "%s ### %d\n", mono_method_full_name (method, TRUE), cfg->code_size);
7084 printf ("%s ### %d\n", mono_method_full_name (method, TRUE), cfg->code_size);
7087 /* Adds generic instances referenced by this method */
7089 * The depth is used to avoid infinite loops when generic virtual recursion is
7092 depth = GPOINTER_TO_UINT (g_hash_table_lookup (acfg->method_depth, method));
7093 if (!acfg->aot_opts.no_instances && depth < 32) {
7094 for (patch_info = cfg->patch_info; patch_info; patch_info = patch_info->next) {
7095 switch (patch_info->type) {
7096 case MONO_PATCH_INFO_RGCTX_FETCH:
7097 case MONO_PATCH_INFO_METHOD: {
7098 MonoMethod *m = NULL;
7100 if (patch_info->type == MONO_PATCH_INFO_RGCTX_FETCH) {
7101 MonoJumpInfoRgctxEntry *e = patch_info->data.rgctx_entry;
7103 if (e->info_type == MONO_RGCTX_INFO_GENERIC_METHOD_CODE)
7104 m = e->data->data.method;
7106 m = patch_info->data.method;
7111 if (m->is_inflated) {
7112 if (!(mono_class_generic_sharing_enabled (m->klass) &&
7113 mono_method_is_generic_sharable_full (m, FALSE, FALSE, FALSE)) &&
7114 (!method_has_type_vars (m) || mono_method_is_generic_sharable_full (m, TRUE, TRUE, FALSE))) {
7115 if (m->iflags & METHOD_IMPL_ATTRIBUTE_INTERNAL_CALL) {
7116 if (mono_aot_mode_is_full (&acfg->aot_opts) && !method_has_type_vars (m))
7117 add_extra_method_with_depth (acfg, mono_marshal_get_native_wrapper (m, TRUE, TRUE), depth + 1);
7119 add_extra_method_with_depth (acfg, m, depth + 1);
7120 add_types_from_method_header (acfg, m);
7123 add_generic_class_with_depth (acfg, m->klass, depth + 5, "method");
7125 if (m->wrapper_type == MONO_WRAPPER_MANAGED_TO_MANAGED) {
7126 WrapperInfo *info = mono_marshal_get_wrapper_info (m);
7128 if (info && info->subtype == WRAPPER_SUBTYPE_ELEMENT_ADDR)
7129 add_extra_method_with_depth (acfg, m, depth + 1);
7133 case MONO_PATCH_INFO_VTABLE: {
7134 MonoClass *klass = patch_info->data.klass;
7136 if (klass->generic_class && !mini_class_is_generic_sharable (klass))
7137 add_generic_class_with_depth (acfg, klass, depth + 5, "vtable");
7140 case MONO_PATCH_INFO_SFLDA: {
7141 MonoClass *klass = patch_info->data.field->parent;
7143 /* The .cctor needs to run at runtime. */
7144 if (klass->generic_class && !mono_generic_context_is_sharable (&klass->generic_class->context, FALSE) && mono_class_get_cctor (klass))
7145 add_extra_method_with_depth (acfg, mono_class_get_cctor (klass), depth + 1);
7154 /* Determine whenever the method has GOT slots */
7155 for (patch_info = cfg->patch_info; patch_info; patch_info = patch_info->next) {
7156 switch (patch_info->type) {
7157 case MONO_PATCH_INFO_GOT_OFFSET:
7158 case MONO_PATCH_INFO_NONE:
7159 case MONO_PATCH_INFO_GC_CARD_TABLE_ADDR:
7160 case MONO_PATCH_INFO_GC_NURSERY_START:
7162 case MONO_PATCH_INFO_IMAGE:
7163 /* The assembly is stored in GOT slot 0 */
7164 if (patch_info->data.image != acfg->image)
7165 cfg->has_got_slots = TRUE;
7168 if (!is_plt_patch (patch_info))
7169 cfg->has_got_slots = TRUE;
7174 if (!cfg->has_got_slots)
7175 InterlockedIncrement (&acfg->stats.methods_without_got_slots);
7178 * FIXME: Instead of this mess, allocate the patches from the aot mempool.
7180 /* Make a copy of the patch info which is in the mempool */
7182 MonoJumpInfo *patches = NULL, *patches_end = NULL;
7184 for (patch_info = cfg->patch_info; patch_info; patch_info = patch_info->next) {
7185 MonoJumpInfo *new_patch_info = mono_patch_info_dup_mp (acfg->mempool, patch_info);
7188 patches = new_patch_info;
7190 patches_end->next = new_patch_info;
7191 patches_end = new_patch_info;
7193 cfg->patch_info = patches;
7195 /* Make a copy of the unwind info */
7197 GSList *l, *unwind_ops;
7201 for (l = cfg->unwind_ops; l; l = l->next) {
7202 op = mono_mempool_alloc (acfg->mempool, sizeof (MonoUnwindOp));
7203 memcpy (op, l->data, sizeof (MonoUnwindOp));
7204 unwind_ops = g_slist_prepend_mempool (acfg->mempool, unwind_ops, op);
7206 cfg->unwind_ops = g_slist_reverse (unwind_ops);
7208 /* Make a copy of the argument/local info */
7210 MonoInst **args, **locals;
7211 MonoMethodSignature *sig;
7212 MonoMethodHeader *header;
7215 sig = mono_method_signature (method);
7216 args = mono_mempool_alloc (acfg->mempool, sizeof (MonoInst*) * (sig->param_count + sig->hasthis));
7217 for (i = 0; i < sig->param_count + sig->hasthis; ++i) {
7218 args [i] = mono_mempool_alloc (acfg->mempool, sizeof (MonoInst));
7219 memcpy (args [i], cfg->args [i], sizeof (MonoInst));
7223 header = mono_method_get_header (method);
7224 locals = mono_mempool_alloc (acfg->mempool, sizeof (MonoInst*) * header->num_locals);
7225 for (i = 0; i < header->num_locals; ++i) {
7226 locals [i] = mono_mempool_alloc (acfg->mempool, sizeof (MonoInst));
7227 memcpy (locals [i], cfg->locals [i], sizeof (MonoInst));
7229 cfg->locals = locals;
7232 /* Free some fields used by cfg to conserve memory */
7233 mono_mempool_destroy (cfg->mempool);
7234 cfg->mempool = NULL;
7235 g_free (cfg->varinfo);
7236 cfg->varinfo = NULL;
7240 mono_regstate_free (cfg->rs);
7244 //printf ("Compile: %s\n", mono_method_full_name (method, TRUE));
7246 while (index >= acfg->cfgs_size) {
7247 MonoCompile **new_cfgs;
7250 new_size = acfg->cfgs_size * 2;
7251 new_cfgs = g_new0 (MonoCompile*, new_size);
7252 memcpy (new_cfgs, acfg->cfgs, sizeof (MonoCompile*) * acfg->cfgs_size);
7253 g_free (acfg->cfgs);
7254 acfg->cfgs = new_cfgs;
7255 acfg->cfgs_size = new_size;
7257 acfg->cfgs [index] = cfg;
7259 g_hash_table_insert (acfg->method_to_cfg, cfg->orig_method, cfg);
7262 if (cfg->orig_method->wrapper_type)
7263 g_ptr_array_add (acfg->extra_methods, cfg->orig_method);
7266 mono_acfg_unlock (acfg);
7268 InterlockedIncrement (&acfg->stats.ccount);
7272 compile_thread_main (gpointer *user_data)
7274 MonoDomain *domain = user_data [0];
7275 MonoAotCompile *acfg = user_data [1];
7276 GPtrArray *methods = user_data [2];
7279 mono_thread_attach (domain);
7281 for (i = 0; i < methods->len; ++i)
7282 compile_method (acfg, g_ptr_array_index (methods, i));
7286 load_profile_files (MonoAotCompile *acfg)
7290 int file_index, res, method_index, i;
7293 GList *unordered, *l;
7298 tmp = g_strdup_printf ("%s/.mono/aot-profile-data/%s-%d", g_get_home_dir (), acfg->image->assembly_name, file_index);
7300 if (!g_file_test (tmp, G_FILE_TEST_IS_REGULAR)) {
7305 infile = fopen (tmp, "r");
7308 printf ("Using profile data file '%s'\n", tmp);
7313 res = fscanf (infile, "%32s\n", ver);
7314 if ((res != 1) || strcmp (ver, "#VER:2") != 0) {
7315 printf ("Profile file has wrong version or invalid.\n");
7322 MonoMethodDesc *desc;
7325 if (fgets (name, 1023, infile) == NULL)
7328 /* Kill the newline */
7329 if (strlen (name) > 0)
7330 name [strlen (name) - 1] = '\0';
7332 desc = mono_method_desc_new (name, TRUE);
7334 method = mono_method_desc_search_in_image (desc, acfg->image);
7336 if (method && mono_method_get_token (method)) {
7337 token = mono_method_get_token (method);
7338 method_index = mono_metadata_token_index (token) - 1;
7341 for (i = 0; i < acfg->method_order->len; ++i) {
7342 if (g_ptr_array_index (acfg->method_order, i) == GUINT_TO_POINTER (method_index)) {
7348 g_ptr_array_add (acfg->method_order, GUINT_TO_POINTER (method_index));
7350 //printf ("No method found matching '%s'.\n", name);
7356 /* Add missing methods */
7358 for (method_index = 0; method_index < acfg->image->tables [MONO_TABLE_METHOD].rows; ++method_index) {
7360 for (i = 0; i < acfg->method_order->len; ++i) {
7361 if (g_ptr_array_index (acfg->method_order, i) == GUINT_TO_POINTER (method_index)) {
7367 unordered = g_list_prepend (unordered, GUINT_TO_POINTER (method_index));
7369 unordered = g_list_reverse (unordered);
7370 for (l = unordered; l; l = l->next)
7371 g_ptr_array_add (acfg->method_order, l->data);
7374 /* Used by the LLVM backend */
7376 mono_aot_get_got_offset (MonoJumpInfo *ji)
7378 return get_got_offset (llvm_acfg, TRUE, ji);
7382 mono_aot_get_method_name (MonoCompile *cfg)
7384 if (llvm_acfg->aot_opts.static_link)
7385 /* Include the assembly name too to avoid duplicate symbol errors */
7386 return g_strdup_printf ("%s_%s", llvm_acfg->assembly_name_sym, get_debug_sym (cfg->orig_method, "", llvm_acfg->method_label_hash));
7388 return get_debug_sym (cfg->orig_method, "", llvm_acfg->method_label_hash);
7392 mono_aot_is_direct_callable (MonoJumpInfo *patch_info)
7394 return is_direct_callable (llvm_acfg, NULL, patch_info);
7398 mono_aot_mark_unused_llvm_plt_entry (MonoJumpInfo *patch_info)
7400 MonoPltEntry *plt_entry;
7402 plt_entry = get_plt_entry (llvm_acfg, patch_info);
7403 plt_entry->llvm_used = FALSE;
7407 mono_aot_get_plt_symbol (MonoJumpInfoType type, gconstpointer data)
7409 MonoJumpInfo *ji = mono_mempool_alloc (llvm_acfg->mempool, sizeof (MonoJumpInfo));
7410 MonoPltEntry *plt_entry;
7411 const char *sym = NULL;
7414 ji->data.target = data;
7416 if (!can_encode_patch (llvm_acfg, ji))
7419 if (llvm_acfg->aot_opts.direct_icalls) {
7420 if (type == MONO_PATCH_INFO_JIT_ICALL_ADDR) {
7421 /* Call to a C function implementing a jit icall */
7422 sym = mono_lookup_jit_icall_symbol (data);
7423 } else if (type == MONO_PATCH_INFO_ICALL_ADDR) {
7424 MonoMethod *method = (gpointer)data;
7425 if (!(method->flags & METHOD_ATTRIBUTE_PINVOKE_IMPL))
7426 sym = mono_lookup_icall_symbol (method);
7429 return g_strdup (sym);
7432 plt_entry = get_plt_entry (llvm_acfg, ji);
7433 plt_entry->llvm_used = TRUE;
7435 #if defined(TARGET_MACH)
7436 return g_strdup_printf (plt_entry->llvm_symbol + strlen (llvm_acfg->llvm_label_prefix));
7438 return g_strdup_printf (plt_entry->llvm_symbol);
7443 mono_aot_get_method_index (MonoMethod *method)
7445 g_assert (llvm_acfg);
7446 return get_method_index (llvm_acfg, method);
7450 mono_aot_patch_info_dup (MonoJumpInfo* ji)
7454 mono_acfg_lock (llvm_acfg);
7455 res = mono_patch_info_dup_mp (llvm_acfg->mempool, ji);
7456 mono_acfg_unlock (llvm_acfg);
7462 execute_system (const char * command)
7467 // We need an extra set of quotes around the whole command to properly handle commands
7468 // with spaces since internally the command is called through "cmd /c.
7469 command = g_strdup_printf ("\"%s\"", command);
7471 int size = MultiByteToWideChar (CP_UTF8, 0 , command , -1, NULL , 0);
7472 wchar_t* wstr = g_malloc (sizeof (wchar_t) * size);
7473 MultiByteToWideChar (CP_UTF8, 0, command, -1, wstr , size);
7474 status = _wsystem (wstr);
7478 #elif defined (HAVE_SYSTEM)
7479 status = system (command);
7481 g_assert_not_reached ();
7492 * Emit the LLVM code into an LLVM bytecode file, and compile it using the LLVM
7496 emit_llvm_file (MonoAotCompile *acfg)
7498 char *command, *opts, *tempbc, *output_fname;
7500 tempbc = g_strdup_printf ("%s.bc", acfg->tmpbasename);
7501 mono_llvm_emit_aot_module (tempbc, g_path_get_basename (acfg->image->name));
7505 * FIXME: Experiment with adding optimizations, the -std-compile-opts set takes
7506 * a lot of time, and doesn't seem to save much space.
7507 * The following optimizations cannot be enabled:
7509 * - 'jump-threading' changes our blockaddress references to int constants.
7510 * - 'basiccg' fails because it contains:
7511 * if (CS && !isa<IntrinsicInst>(II)) {
7512 * and isa<IntrinsicInst> is false for invokes to intrinsics (iltests.exe).
7513 * - 'prune-eh' and 'functionattrs' depend on 'basiccg'.
7514 * The opt list below was produced by taking the output of:
7515 * llvm-as < /dev/null | opt -O2 -disable-output -debug-pass=Arguments
7516 * then removing tailcallelim + the global opts.
7517 * strip-dead-prototypes deletes unused intrinsics definitions.
7519 opts = g_strdup ("-instcombine -simplifycfg");
7520 //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");
7521 /* The dse pass is disabled because of #13734 and #17616 */
7523 * The dse bug is in DeadStoreElimination.cpp:isOverwrite ():
7524 * // If we have no DataLayout information around, then the size of the store
7525 * // is inferrable from the pointee type. If they are the same type, then
7526 * // we know that the store is safe.
7527 * if (AA.getDataLayout() == 0 &&
7528 * Later.Ptr->getType() == Earlier.Ptr->getType()) {
7529 * return OverwriteComplete;
7530 * Here, if 'Earlier' refers to a memset, and Later has no size info, it mistakenly thinks the memset is redundant.
7532 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");
7534 command = g_strdup_printf ("\"%sopt\" -f %s -o \"%s.opt.bc\" \"%s.bc\"", acfg->aot_opts.llvm_path, opts, acfg->tmpbasename, acfg->tmpbasename);
7535 aot_printf (acfg, "Executing opt: %s\n", command);
7536 if (execute_system (command) != 0)
7541 if (!acfg->llc_args)
7542 acfg->llc_args = g_string_new ("");
7544 /* Verbose asm slows down llc greatly */
7545 g_string_append (acfg->llc_args, " -asm-verbose=false");
7547 g_string_append (acfg->llc_args, " -disable-gnu-eh-frame -enable-mono-eh-frame");
7549 if (acfg->aot_opts.mtriple)
7550 g_string_append_printf (acfg->llc_args, " -mtriple=%s", acfg->aot_opts.mtriple);
7552 g_string_append_printf (acfg->llc_args, " -mono-eh-frame-symbol=%s%s", acfg->user_symbol_prefix, acfg->llvm_eh_frame_symbol);
7554 #if defined(TARGET_MACH) && defined(TARGET_ARM)
7555 /* ios requires PIC code now */
7556 g_string_append_printf (acfg->llc_args, " -relocation-model=pic");
7558 if (llvm_acfg->aot_opts.static_link)
7559 g_string_append_printf (acfg->llc_args, " -relocation-model=static");
7561 g_string_append_printf (acfg->llc_args, " -relocation-model=pic");
7564 if (acfg->llvm_owriter) {
7565 /* Emit an object file directly */
7566 output_fname = g_strdup_printf ("%s", acfg->llvm_ofile);
7567 g_string_append_printf (acfg->llc_args, " -filetype=obj");
7569 output_fname = g_strdup_printf ("%s", acfg->llvm_sfile);
7571 command = g_strdup_printf ("\"%sllc\" %s -o \"%s\" \"%s.opt.bc\"", acfg->aot_opts.llvm_path, acfg->llc_args->str, output_fname, acfg->tmpbasename);
7572 g_free (output_fname);
7574 aot_printf (acfg, "Executing llc: %s\n", command);
7576 if (execute_system (command) != 0)
7583 emit_code (MonoAotCompile *acfg)
7585 int oindex, i, prev_index;
7586 gboolean saved_unbox_info = FALSE;
7589 #if defined(TARGET_POWERPC64)
7590 sprintf (symbol, ".Lgot_addr");
7591 emit_section_change (acfg, ".text", 0);
7592 emit_alignment (acfg, 8);
7593 emit_label (acfg, symbol);
7594 emit_pointer (acfg, acfg->got_symbol);
7598 * This global symbol is used to compute the address of each method using the
7599 * code_offsets array. It is also used to compute the memory ranges occupied by
7600 * AOT code, so it must be equal to the address of the first emitted method.
7602 emit_section_change (acfg, ".text", 0);
7603 emit_alignment_code (acfg, 8);
7604 emit_info_symbol (acfg, "jit_code_start");
7607 * Emit some padding so the local symbol for the first method doesn't have the
7608 * same address as 'methods'.
7610 #if defined(__default_codegen__)
7611 emit_padding (acfg, 16);
7612 #elif defined(__native_client_codegen__)
7614 const int kPaddingSize = 16;
7615 guint8 pad_buffer[kPaddingSize];
7616 mono_arch_nacl_pad (pad_buffer, kPaddingSize);
7617 emit_bytes (acfg, pad_buffer, kPaddingSize);
7621 for (oindex = 0; oindex < acfg->method_order->len; ++oindex) {
7625 i = GPOINTER_TO_UINT (g_ptr_array_index (acfg->method_order, oindex));
7627 cfg = acfg->cfgs [i];
7632 method = cfg->orig_method;
7634 /* Emit unbox trampoline */
7635 if (mono_aot_mode_is_full (&acfg->aot_opts) && cfg->orig_method->klass->valuetype) {
7636 sprintf (symbol, "ut_%d", get_method_index (acfg, method));
7638 emit_section_change (acfg, ".text", 0);
7639 #ifdef __native_client_codegen__
7640 emit_alignment (acfg, AOT_FUNC_ALIGNMENT);
7643 if (acfg->thumb_mixed && cfg->compile_llvm) {
7644 emit_set_thumb_mode (acfg);
7645 fprintf (acfg->fp, "\n.thumb_func\n");
7648 emit_label (acfg, symbol);
7650 arch_emit_unbox_trampoline (acfg, cfg, cfg->orig_method, cfg->asm_symbol);
7652 if (acfg->thumb_mixed && cfg->compile_llvm)
7653 emit_set_arm_mode (acfg);
7655 if (!saved_unbox_info) {
7656 char user_symbol [128];
7658 sprintf (user_symbol, "%sunbox_trampoline_p", acfg->user_symbol_prefix);
7660 emit_label (acfg, "ut_end");
7662 unwind_ops = mono_unwind_get_cie_program ();
7663 save_unwind_info (acfg, user_symbol, unwind_ops);
7664 mono_free_unwind_info (unwind_ops);
7666 /* Save the unbox trampoline size */
7667 emit_symbol_diff (acfg, "ut_end", symbol, 0);
7669 saved_unbox_info = TRUE;
7673 if (cfg->compile_llvm)
7674 acfg->stats.llvm_count ++;
7676 emit_method_code (acfg, cfg);
7679 emit_section_change (acfg, ".text", 0);
7680 emit_alignment_code (acfg, 8);
7681 emit_info_symbol (acfg, "jit_code_end");
7683 /* To distinguish it from the next symbol */
7684 emit_padding (acfg, 4);
7687 * Add .no_dead_strip directives for all LLVM methods to prevent the OSX linker
7688 * from optimizing them away, since it doesn't see that code_offsets references them.
7689 * JITted methods don't need this since they are referenced using assembler local
7691 * FIXME: This is why write-symbols doesn't work on OSX ?
7693 if (acfg->llvm && acfg->need_no_dead_strip) {
7694 fprintf (acfg->fp, "\n");
7695 for (i = 0; i < acfg->nmethods; ++i) {
7696 if (acfg->cfgs [i] && acfg->cfgs [i]->compile_llvm)
7697 fprintf (acfg->fp, ".no_dead_strip %s\n", acfg->cfgs [i]->asm_symbol);
7702 * To work around linker issues, we emit a table of branches, and disassemble them at runtime.
7703 * This is PIE code, and the linker can update it if needed.
7705 sprintf (symbol, "method_addresses");
7706 emit_section_change (acfg, ".text", 1);
7707 emit_alignment_code (acfg, 8);
7708 emit_info_symbol (acfg, symbol);
7709 emit_local_symbol (acfg, symbol, "method_addresses_end", TRUE);
7710 emit_unset_mode (acfg);
7711 if (acfg->need_no_dead_strip)
7712 fprintf (acfg->fp, " .no_dead_strip %s\n", symbol);
7714 for (i = 0; i < acfg->nmethods; ++i) {
7715 #ifdef MONO_ARCH_AOT_SUPPORTED
7719 arch_emit_direct_call (acfg, acfg->cfgs [i]->asm_symbol, FALSE, acfg->thumb_mixed && acfg->cfgs [i]->compile_llvm, NULL, &call_size);
7721 arch_emit_direct_call (acfg, "method_addresses", FALSE, FALSE, NULL, &call_size);
7725 sprintf (symbol, "method_addresses_end");
7726 emit_label (acfg, symbol);
7729 /* Emit a sorted table mapping methods to the index of their unbox trampolines */
7730 sprintf (symbol, "unbox_trampolines");
7731 emit_section_change (acfg, RODATA_SECT, 0);
7732 emit_alignment (acfg, 8);
7733 emit_info_symbol (acfg, symbol);
7736 for (i = 0; i < acfg->nmethods; ++i) {
7741 cfg = acfg->cfgs [i];
7745 method = cfg->orig_method;
7747 if (mono_aot_mode_is_full (&acfg->aot_opts) && cfg->orig_method->klass->valuetype) {
7748 index = get_method_index (acfg, method);
7750 emit_int32 (acfg, index);
7751 /* Make sure the table is sorted by index */
7752 g_assert (index > prev_index);
7756 sprintf (symbol, "unbox_trampolines_end");
7757 emit_info_symbol (acfg, symbol);
7758 emit_int32 (acfg, 0);
7760 /* Emit a separate table with the trampoline addresses/offsets */
7761 sprintf (symbol, "unbox_trampoline_addresses");
7762 emit_section_change (acfg, ".text", 0);
7763 emit_alignment_code (acfg, 8);
7764 emit_info_symbol (acfg, symbol);
7766 for (i = 0; i < acfg->nmethods; ++i) {
7771 cfg = acfg->cfgs [i];
7775 method = cfg->orig_method;
7777 if (mono_aot_mode_is_full (&acfg->aot_opts) && cfg->orig_method->klass->valuetype) {
7778 #ifdef MONO_ARCH_AOT_SUPPORTED
7781 index = get_method_index (acfg, method);
7782 sprintf (symbol, "ut_%d", index);
7784 arch_emit_direct_call (acfg, symbol, FALSE, acfg->thumb_mixed && cfg->compile_llvm, NULL, &call_size);
7788 emit_int32 (acfg, 0);
7792 emit_info (MonoAotCompile *acfg)
7797 offsets = g_new0 (gint32, acfg->nmethods);
7799 for (oindex = 0; oindex < acfg->method_order->len; ++oindex) {
7800 i = GPOINTER_TO_UINT (g_ptr_array_index (acfg->method_order, oindex));
7802 if (acfg->cfgs [i]) {
7803 emit_method_info (acfg, acfg->cfgs [i]);
7804 offsets [i] = acfg->cfgs [i]->method_info_offset;
7810 acfg->stats.offsets_size += emit_offset_table (acfg, "method_info_offsets", acfg->nmethods, 10, offsets);
7815 #endif /* #if !defined(DISABLE_AOT) && !defined(DISABLE_JIT) */
7817 #define rot(x,k) (((x)<<(k)) | ((x)>>(32-(k))))
7818 #define mix(a,b,c) { \
7819 a -= c; a ^= rot(c, 4); c += b; \
7820 b -= a; b ^= rot(a, 6); a += c; \
7821 c -= b; c ^= rot(b, 8); b += a; \
7822 a -= c; a ^= rot(c,16); c += b; \
7823 b -= a; b ^= rot(a,19); a += c; \
7824 c -= b; c ^= rot(b, 4); b += a; \
7826 #define final(a,b,c) { \
7827 c ^= b; c -= rot(b,14); \
7828 a ^= c; a -= rot(c,11); \
7829 b ^= a; b -= rot(a,25); \
7830 c ^= b; c -= rot(b,16); \
7831 a ^= c; a -= rot(c,4); \
7832 b ^= a; b -= rot(a,14); \
7833 c ^= b; c -= rot(b,24); \
7837 mono_aot_type_hash (MonoType *t1)
7839 guint hash = t1->type;
7841 hash |= t1->byref << 6; /* do not collide with t1->type values */
7843 case MONO_TYPE_VALUETYPE:
7844 case MONO_TYPE_CLASS:
7845 case MONO_TYPE_SZARRAY:
7846 /* check if the distribution is good enough */
7847 return ((hash << 5) - hash) ^ mono_metadata_str_hash (t1->data.klass->name);
7849 return ((hash << 5) - hash) ^ mono_metadata_type_hash (t1->data.type);
7850 case MONO_TYPE_ARRAY:
7851 return ((hash << 5) - hash) ^ mono_metadata_type_hash (&t1->data.array->eklass->byval_arg);
7852 case MONO_TYPE_GENERICINST:
7853 return ((hash << 5) - hash) ^ 0;
7860 * mono_aot_method_hash:
7862 * Return a hash code for methods which only depends on metadata.
7865 mono_aot_method_hash (MonoMethod *method)
7867 MonoMethodSignature *sig;
7871 guint32 *hashes_start, *hashes;
7873 MonoGenericInst *class_ginst = NULL;
7874 MonoGenericInst *ginst = NULL;
7876 /* Similar to the hash in mono_method_get_imt_slot () */
7878 sig = mono_method_signature (method);
7880 if (method->klass->generic_class)
7881 class_ginst = method->klass->generic_class->context.class_inst;
7882 if (method->is_inflated)
7883 ginst = ((MonoMethodInflated*)method)->context.method_inst;
7885 hashes_count = sig->param_count + 5 + (class_ginst ? class_ginst->type_argc : 0) + (ginst ? ginst->type_argc : 0);
7886 hashes_start = g_malloc0 (hashes_count * sizeof (guint32));
7887 hashes = hashes_start;
7889 /* Some wrappers are assigned to random classes */
7890 if (!method->wrapper_type || method->wrapper_type == MONO_WRAPPER_REMOTING_INVOKE_WITH_CHECK)
7891 klass = method->klass;
7893 klass = mono_defaults.object_class;
7895 if (!method->wrapper_type) {
7898 if (klass->generic_class)
7899 full_name = mono_type_full_name (&klass->generic_class->container_class->byval_arg);
7901 full_name = mono_type_full_name (&klass->byval_arg);
7903 hashes [0] = mono_metadata_str_hash (full_name);
7907 hashes [0] = mono_metadata_str_hash (klass->name);
7908 hashes [1] = mono_metadata_str_hash (klass->name_space);
7910 if (method->wrapper_type == MONO_WRAPPER_STFLD || method->wrapper_type == MONO_WRAPPER_LDFLD || method->wrapper_type == MONO_WRAPPER_LDFLDA)
7911 /* The method name includes a stringified pointer */
7914 hashes [2] = mono_metadata_str_hash (method->name);
7915 hashes [3] = method->wrapper_type;
7916 hashes [4] = mono_aot_type_hash (sig->ret);
7918 for (i = 0; i < sig->param_count; i++) {
7919 hashes [hindex ++] = mono_aot_type_hash (sig->params [i]);
7922 for (i = 0; i < class_ginst->type_argc; ++i)
7923 hashes [hindex ++] = mono_aot_type_hash (class_ginst->type_argv [i]);
7926 for (i = 0; i < ginst->type_argc; ++i)
7927 hashes [hindex ++] = mono_aot_type_hash (ginst->type_argv [i]);
7929 g_assert (hindex == hashes_count);
7931 /* Setup internal state */
7932 a = b = c = 0xdeadbeef + (((guint32)hashes_count)<<2);
7934 /* Handle most of the hashes */
7935 while (hashes_count > 3) {
7944 /* Handle the last 3 hashes (all the case statements fall through) */
7945 switch (hashes_count) {
7946 case 3 : c += hashes [2];
7947 case 2 : b += hashes [1];
7948 case 1 : a += hashes [0];
7950 case 0: /* nothing left to add */
7954 free (hashes_start);
7963 * mono_aot_get_array_helper_from_wrapper;
7965 * Get the helper method in Array called by an array wrapper method.
7968 mono_aot_get_array_helper_from_wrapper (MonoMethod *method)
7972 MonoGenericContext ctx;
7973 MonoType *args [16];
7974 char *mname, *iname, *s, *s2, *helper_name = NULL;
7976 prefix = "System.Collections.Generic";
7977 s = g_strdup_printf ("%s", method->name + strlen (prefix) + 1);
7978 s2 = strstr (s, "`1.");
7984 //printf ("X: %s %s\n", iname, mname);
7986 if (!strcmp (iname, "IList"))
7987 helper_name = g_strdup_printf ("InternalArray__%s", mname);
7989 helper_name = g_strdup_printf ("InternalArray__%s_%s", iname, mname);
7990 m = mono_class_get_method_from_name (mono_defaults.array_class, helper_name, mono_method_signature (method)->param_count);
7992 g_free (helper_name);
7995 if (m->is_generic) {
7997 memset (&ctx, 0, sizeof (ctx));
7998 args [0] = &method->klass->element_class->byval_arg;
7999 ctx.method_inst = mono_metadata_get_generic_inst (1, args);
8000 m = mono_class_inflate_generic_method_checked (m, &ctx, &error);
8001 g_assert (mono_error_ok (&error)); /* FIXME don't swallow the error */
8007 #if !defined(DISABLE_AOT) && !defined(DISABLE_JIT)
8009 typedef struct HashEntry {
8010 guint32 key, value, index;
8011 struct HashEntry *next;
8015 * emit_extra_methods:
8017 * Emit methods which are not in the METHOD table, like wrappers.
8020 emit_extra_methods (MonoAotCompile *acfg)
8022 int i, table_size, buf_size;
8025 guint32 *info_offsets;
8028 HashEntry *entry, *new_entry;
8029 int nmethods, max_chain_length;
8032 info_offsets = g_new0 (guint32, acfg->extra_methods->len);
8034 /* Emit method info */
8036 for (i = 0; i < acfg->extra_methods->len; ++i) {
8037 MonoMethod *method = g_ptr_array_index (acfg->extra_methods, i);
8038 MonoCompile *cfg = g_hash_table_lookup (acfg->method_to_cfg, method);
8044 p = buf = g_malloc (buf_size);
8048 method = cfg->method_to_register;
8050 encode_method_ref (acfg, method, p, &p);
8052 g_assert ((p - buf) < buf_size);
8054 info_offsets [i] = add_to_blob (acfg, buf, p - buf);
8059 * Construct a chained hash table for mapping indexes in extra_method_info to
8062 table_size = g_spaced_primes_closest ((int)(nmethods * 1.5));
8063 table = g_ptr_array_sized_new (table_size);
8064 for (i = 0; i < table_size; ++i)
8065 g_ptr_array_add (table, NULL);
8066 chain_lengths = g_new0 (int, table_size);
8067 max_chain_length = 0;
8068 for (i = 0; i < acfg->extra_methods->len; ++i) {
8069 MonoMethod *method = g_ptr_array_index (acfg->extra_methods, i);
8070 MonoCompile *cfg = g_hash_table_lookup (acfg->method_to_cfg, method);
8076 key = info_offsets [i];
8077 value = get_method_index (acfg, method);
8079 hash = mono_aot_method_hash (method) % table_size;
8080 //printf ("X: %s %x\n", mono_method_full_name (method, 1), mono_aot_method_hash (method));
8082 chain_lengths [hash] ++;
8083 max_chain_length = MAX (max_chain_length, chain_lengths [hash]);
8085 new_entry = mono_mempool_alloc0 (acfg->mempool, sizeof (HashEntry));
8086 new_entry->key = key;
8087 new_entry->value = value;
8089 entry = g_ptr_array_index (table, hash);
8090 if (entry == NULL) {
8091 new_entry->index = hash;
8092 g_ptr_array_index (table, hash) = new_entry;
8095 entry = entry->next;
8097 entry->next = new_entry;
8098 new_entry->index = table->len;
8099 g_ptr_array_add (table, new_entry);
8103 //printf ("MAX: %d\n", max_chain_length);
8105 buf_size = table->len * 12 + 4;
8106 p = buf = g_malloc (buf_size);
8107 encode_int (table_size, p, &p);
8109 for (i = 0; i < table->len; ++i) {
8110 HashEntry *entry = g_ptr_array_index (table, i);
8112 if (entry == NULL) {
8113 encode_int (0, p, &p);
8114 encode_int (0, p, &p);
8115 encode_int (0, p, &p);
8117 //g_assert (entry->key > 0);
8118 encode_int (entry->key, p, &p);
8119 encode_int (entry->value, p, &p);
8121 encode_int (entry->next->index, p, &p);
8123 encode_int (0, p, &p);
8126 g_assert (p - buf <= buf_size);
8128 /* Emit the table */
8130 mono_llvm_emit_aot_data ("extra_method_table", buf, p - buf);
8132 sprintf (symbol, "extra_method_table");
8133 emit_section_change (acfg, RODATA_SECT, 0);
8134 emit_alignment (acfg, 8);
8135 emit_label (acfg, symbol);
8136 emit_bytes (acfg, buf, p - buf);
8140 * Emit a table reverse mapping method indexes to their index in extra_method_info.
8141 * This is used by mono_aot_find_jit_info ().
8143 buf_size = acfg->extra_methods->len * 8 + 4;
8144 p = buf = g_malloc (buf_size);
8145 encode_int (acfg->extra_methods->len, p, &p);
8146 for (i = 0; i < acfg->extra_methods->len; ++i) {
8147 MonoMethod *method = g_ptr_array_index (acfg->extra_methods, i);
8149 encode_int (get_method_index (acfg, method), p, &p);
8150 encode_int (info_offsets [i], p, &p);
8153 mono_llvm_emit_aot_data ("extra_method_info_offsets", buf, p - buf);
8155 sprintf (symbol, "extra_method_info_offsets");
8156 emit_section_change (acfg, RODATA_SECT, 0);
8157 emit_alignment (acfg, 8);
8158 emit_label (acfg, symbol);
8159 emit_bytes (acfg, buf, p - buf);
8164 emit_exception_info (MonoAotCompile *acfg)
8168 SeqPointData sp_data;
8169 gboolean seq_points_to_file = FALSE;
8171 offsets = g_new0 (gint32, acfg->nmethods);
8172 for (i = 0; i < acfg->nmethods; ++i) {
8173 if (acfg->cfgs [i]) {
8174 MonoCompile *cfg = acfg->cfgs [i];
8176 // By design aot-runtime decode_exception_debug_info is not able to load sequence point debug data from a file.
8177 // As it is not possible to load debug data from a file its is also not possible to store it in a file.
8178 gboolean method_seq_points_to_file = acfg->aot_opts.gen_seq_points_file &&
8179 cfg->gen_seq_points && !cfg->gen_sdb_seq_points;
8180 gboolean method_seq_points_to_binary = cfg->gen_seq_points && !method_seq_points_to_file;
8182 emit_exception_debug_info (acfg, cfg, method_seq_points_to_binary);
8183 offsets [i] = cfg->ex_info_offset;
8185 if (method_seq_points_to_file) {
8186 if (!seq_points_to_file) {
8187 mono_seq_point_data_init (&sp_data, acfg->nmethods);
8188 seq_points_to_file = TRUE;
8190 mono_seq_point_data_add (&sp_data, cfg->method->token, cfg->method_index, cfg->seq_point_info);
8197 if (seq_points_to_file) {
8198 char *seq_points_aot_file;
8199 mono_image_get_aot_seq_point_path (acfg->image, &seq_points_aot_file);
8200 mono_seq_point_data_write (&sp_data, seq_points_aot_file);
8201 mono_seq_point_data_free (&sp_data);
8202 g_free (seq_points_aot_file);
8205 acfg->stats.offsets_size += emit_offset_table (acfg, "ex_info_offsets", acfg->nmethods, 10, offsets);
8210 emit_unwind_info (MonoAotCompile *acfg)
8216 * The unwind info contains a lot of duplicates so we emit each unique
8217 * entry once, and only store the offset from the start of the table in the
8221 sprintf (symbol, "unwind_info");
8222 emit_section_change (acfg, RODATA_SECT, 1);
8223 emit_alignment (acfg, 8);
8224 emit_info_symbol (acfg, symbol);
8226 for (i = 0; i < acfg->unwind_ops->len; ++i) {
8227 guint32 index = GPOINTER_TO_UINT (g_ptr_array_index (acfg->unwind_ops, i));
8228 guint8 *unwind_info;
8229 guint32 unwind_info_len;
8233 unwind_info = mono_get_cached_unwind_info (index, &unwind_info_len);
8236 encode_value (unwind_info_len, p, &p);
8237 emit_bytes (acfg, buf, p - buf);
8238 emit_bytes (acfg, unwind_info, unwind_info_len);
8240 acfg->stats.unwind_info_size += (p - buf) + unwind_info_len;
8245 emit_class_info (MonoAotCompile *acfg)
8250 offsets = g_new0 (gint32, acfg->image->tables [MONO_TABLE_TYPEDEF].rows);
8251 for (i = 0; i < acfg->image->tables [MONO_TABLE_TYPEDEF].rows; ++i)
8252 offsets [i] = emit_klass_info (acfg, MONO_TOKEN_TYPE_DEF | (i + 1));
8254 acfg->stats.offsets_size += emit_offset_table (acfg, "class_info_offsets", acfg->image->tables [MONO_TABLE_TYPEDEF].rows, 10, offsets);
8258 typedef struct ClassNameTableEntry {
8259 guint32 token, index;
8260 struct ClassNameTableEntry *next;
8261 } ClassNameTableEntry;
8264 emit_class_name_table (MonoAotCompile *acfg)
8266 int i, table_size, buf_size;
8267 guint32 token, hash;
8273 ClassNameTableEntry *entry, *new_entry;
8276 * Construct a chained hash table for mapping class names to typedef tokens.
8278 table_size = g_spaced_primes_closest ((int)(acfg->image->tables [MONO_TABLE_TYPEDEF].rows * 1.5));
8279 table = g_ptr_array_sized_new (table_size);
8280 for (i = 0; i < table_size; ++i)
8281 g_ptr_array_add (table, NULL);
8282 for (i = 0; i < acfg->image->tables [MONO_TABLE_TYPEDEF].rows; ++i) {
8284 token = MONO_TOKEN_TYPE_DEF | (i + 1);
8285 klass = mono_class_get_checked (acfg->image, token, &error);
8287 mono_error_cleanup (&error);
8290 full_name = mono_type_get_name_full (mono_class_get_type (klass), MONO_TYPE_NAME_FORMAT_FULL_NAME);
8291 hash = mono_metadata_str_hash (full_name) % table_size;
8294 /* FIXME: Allocate from the mempool */
8295 new_entry = g_new0 (ClassNameTableEntry, 1);
8296 new_entry->token = token;
8298 entry = g_ptr_array_index (table, hash);
8299 if (entry == NULL) {
8300 new_entry->index = hash;
8301 g_ptr_array_index (table, hash) = new_entry;
8304 entry = entry->next;
8306 entry->next = new_entry;
8307 new_entry->index = table->len;
8308 g_ptr_array_add (table, new_entry);
8312 /* Emit the table */
8313 buf_size = table->len * 4 + 4;
8314 p = buf = g_malloc0 (buf_size);
8316 /* FIXME: Optimize memory usage */
8317 g_assert (table_size < 65000);
8318 encode_int16 (table_size, p, &p);
8319 g_assert (table->len < 65000);
8320 for (i = 0; i < table->len; ++i) {
8321 ClassNameTableEntry *entry = g_ptr_array_index (table, i);
8323 if (entry == NULL) {
8324 encode_int16 (0, p, &p);
8325 encode_int16 (0, p, &p);
8327 encode_int16 (mono_metadata_token_index (entry->token), p, &p);
8329 encode_int16 (entry->next->index, p, &p);
8331 encode_int16 (0, p, &p);
8334 g_assert (p - buf <= buf_size);
8337 mono_llvm_emit_aot_data ("class_name_table", buf, p - buf);
8339 sprintf (symbol, "class_name_table");
8340 emit_section_change (acfg, RODATA_SECT, 0);
8341 emit_alignment (acfg, 8);
8342 emit_label (acfg, symbol);
8343 emit_bytes (acfg, buf, p - buf);
8348 emit_image_table (MonoAotCompile *acfg)
8355 * The image table is small but referenced in a lot of places.
8356 * So we emit it at once, and reference its elements by an index.
8358 buf_size = acfg->image_table->len * 28 + 4;
8359 for (i = 0; i < acfg->image_table->len; i++) {
8360 MonoImage *image = (MonoImage*)g_ptr_array_index (acfg->image_table, i);
8361 MonoAssemblyName *aname = &image->assembly->aname;
8363 buf_size += strlen (image->assembly_name) + strlen (image->guid) + (aname->culture ? strlen (aname->culture) : 1) + strlen ((char*)aname->public_key_token) + 4;
8366 buf = p = g_malloc0 (buf_size);
8367 encode_int (acfg->image_table->len, p, &p);
8368 for (i = 0; i < acfg->image_table->len; i++) {
8369 MonoImage *image = (MonoImage*)g_ptr_array_index (acfg->image_table, i);
8370 MonoAssemblyName *aname = &image->assembly->aname;
8372 /* FIXME: Support multi-module assemblies */
8373 g_assert (image->assembly->image == image);
8375 encode_string (image->assembly_name, p, &p);
8376 encode_string (image->guid, p, &p);
8377 encode_string (aname->culture ? aname->culture : "", p, &p);
8378 encode_string ((const char*)aname->public_key_token, p, &p);
8380 while (GPOINTER_TO_UINT (p) % 8 != 0)
8383 encode_int (aname->flags, p, &p);
8384 encode_int (aname->major, p, &p);
8385 encode_int (aname->minor, p, &p);
8386 encode_int (aname->build, p, &p);
8387 encode_int (aname->revision, p, &p);
8389 g_assert (p - buf <= buf_size);
8392 mono_llvm_emit_aot_data ("image_table", buf, p - buf);
8394 sprintf (symbol, "image_table");
8395 emit_section_change (acfg, RODATA_SECT, 1);
8396 emit_alignment (acfg, 8);
8397 emit_label (acfg, symbol);
8398 emit_bytes (acfg, buf, p - buf);
8405 emit_got_info (MonoAotCompile *acfg, gboolean llvm)
8407 int i, first_plt_got_patch = 0, buf_size;
8409 guint32 *got_info_offsets;
8410 GotInfo *info = llvm ? &acfg->llvm_got_info : &acfg->got_info;
8412 /* Add the patches needed by the PLT to the GOT */
8414 acfg->plt_got_offset_base = acfg->got_offset;
8415 first_plt_got_patch = info->got_patches->len;
8416 for (i = 1; i < acfg->plt_offset; ++i) {
8417 MonoPltEntry *plt_entry = g_hash_table_lookup (acfg->plt_offset_to_entry, GUINT_TO_POINTER (i));
8419 g_ptr_array_add (info->got_patches, plt_entry->ji);
8421 acfg->stats.got_slot_types [plt_entry->ji->type] ++;
8424 acfg->got_offset += acfg->plt_offset;
8429 * - optimize offsets table.
8430 * - reduce number of exported symbols.
8431 * - emit info for a klass only once.
8432 * - determine when a method uses a GOT slot which is guaranteed to be already
8434 * - clean up and document the code.
8435 * - use String.Empty in class libs.
8438 /* Encode info required to decode shared GOT entries */
8439 buf_size = info->got_patches->len * 128;
8440 p = buf = mono_mempool_alloc (acfg->mempool, buf_size);
8441 got_info_offsets = mono_mempool_alloc (acfg->mempool, info->got_patches->len * sizeof (guint32));
8443 acfg->plt_got_info_offsets = mono_mempool_alloc (acfg->mempool, acfg->plt_offset * sizeof (guint32));
8445 if (acfg->plt_offset)
8446 acfg->plt_got_info_offsets [0] = 0;
8448 for (i = 0; i < info->got_patches->len; ++i) {
8449 MonoJumpInfo *ji = g_ptr_array_index (info->got_patches, i);
8454 encode_value (ji->type, p, &p);
8456 encode_patch (acfg, ji, p, &p);
8457 acfg->stats.got_slot_info_sizes [ji->type] += p - p2;
8458 g_assert (p - buf <= buf_size);
8459 got_info_offsets [i] = add_to_blob (acfg, buf, p - buf);
8461 if (!llvm && i >= first_plt_got_patch)
8462 acfg->plt_got_info_offsets [i - first_plt_got_patch + 1] = got_info_offsets [i];
8463 acfg->stats.got_info_size += p - buf;
8466 /* Emit got_info_offsets table */
8468 /* No need to emit offsets for the got plt entries, the plt embeds them directly */
8469 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);
8473 emit_got (MonoAotCompile *acfg)
8477 /* Don't make GOT global so accesses to it don't need relocations */
8478 sprintf (symbol, "%s", acfg->got_symbol);
8481 emit_unset_mode (acfg);
8482 fprintf (acfg->fp, ".section __DATA, __bss\n");
8483 emit_alignment (acfg, 8);
8485 emit_info_symbol (acfg, "jit_got");
8486 fprintf (acfg->fp, ".lcomm %s, %d\n", acfg->got_symbol, (int)(acfg->got_offset * sizeof (gpointer)));
8488 emit_section_change (acfg, ".bss", 0);
8489 emit_alignment (acfg, 8);
8490 emit_local_symbol (acfg, symbol, "got_end", FALSE);
8491 emit_label (acfg, symbol);
8493 emit_info_symbol (acfg, "jit_got");
8494 if (acfg->got_offset > 0)
8495 emit_zero_bytes (acfg, (int)(acfg->got_offset * sizeof (gpointer)));
8498 sprintf (symbol, "got_end");
8499 emit_label (acfg, symbol);
8502 typedef struct GlobalsTableEntry {
8503 guint32 value, index;
8504 struct GlobalsTableEntry *next;
8505 } GlobalsTableEntry;
8508 emit_globals (MonoAotCompile *acfg)
8514 GlobalsTableEntry *entry, *new_entry;
8516 if (!acfg->aot_opts.static_link)
8520 * When static linking, we emit a table containing our globals.
8524 * Construct a chained hash table for mapping global names to their index in
8525 * the globals table.
8527 table_size = g_spaced_primes_closest ((int)(acfg->globals->len * 1.5));
8528 table = g_ptr_array_sized_new (table_size);
8529 for (i = 0; i < table_size; ++i)
8530 g_ptr_array_add (table, NULL);
8531 for (i = 0; i < acfg->globals->len; ++i) {
8532 char *name = g_ptr_array_index (acfg->globals, i);
8534 hash = mono_metadata_str_hash (name) % table_size;
8536 /* FIXME: Allocate from the mempool */
8537 new_entry = g_new0 (GlobalsTableEntry, 1);
8538 new_entry->value = i;
8540 entry = g_ptr_array_index (table, hash);
8541 if (entry == NULL) {
8542 new_entry->index = hash;
8543 g_ptr_array_index (table, hash) = new_entry;
8546 entry = entry->next;
8548 entry->next = new_entry;
8549 new_entry->index = table->len;
8550 g_ptr_array_add (table, new_entry);
8554 /* Emit the table */
8555 sprintf (symbol, ".Lglobals_hash");
8556 emit_section_change (acfg, RODATA_SECT, 0);
8557 emit_alignment (acfg, 8);
8558 emit_label (acfg, symbol);
8560 /* FIXME: Optimize memory usage */
8561 g_assert (table_size < 65000);
8562 emit_int16 (acfg, table_size);
8563 for (i = 0; i < table->len; ++i) {
8564 GlobalsTableEntry *entry = g_ptr_array_index (table, i);
8566 if (entry == NULL) {
8567 emit_int16 (acfg, 0);
8568 emit_int16 (acfg, 0);
8570 emit_int16 (acfg, entry->value + 1);
8572 emit_int16 (acfg, entry->next->index);
8574 emit_int16 (acfg, 0);
8578 /* Emit the names */
8579 for (i = 0; i < acfg->globals->len; ++i) {
8580 char *name = g_ptr_array_index (acfg->globals, i);
8582 sprintf (symbol, "name_%d", i);
8583 emit_section_change (acfg, RODATA_SECT, 1);
8585 emit_alignment (acfg, 4);
8587 emit_label (acfg, symbol);
8588 emit_string (acfg, name);
8591 /* Emit the globals table */
8592 sprintf (symbol, "globals");
8593 emit_section_change (acfg, ".data", 0);
8594 /* This is not a global, since it is accessed by the init function */
8595 emit_alignment (acfg, 8);
8596 emit_info_symbol (acfg, symbol);
8598 sprintf (symbol, "%sglobals_hash", acfg->temp_prefix);
8599 emit_pointer (acfg, symbol);
8601 for (i = 0; i < acfg->globals->len; ++i) {
8602 char *name = g_ptr_array_index (acfg->globals, i);
8604 sprintf (symbol, "name_%d", i);
8605 emit_pointer (acfg, symbol);
8607 g_assert (strlen (name) < sizeof (symbol));
8608 sprintf (symbol, "%s", name);
8609 emit_pointer (acfg, symbol);
8611 /* Null terminate the table */
8612 emit_int32 (acfg, 0);
8613 emit_int32 (acfg, 0);
8617 emit_autoreg (MonoAotCompile *acfg)
8622 * Emit a function into the .ctor section which will be called by the ELF
8623 * loader to register this module with the runtime.
8625 if (! (!acfg->use_bin_writer && acfg->aot_opts.static_link && acfg->aot_opts.autoreg))
8628 symbol = g_strdup_printf ("_%s_autoreg", acfg->static_linking_symbol);
8630 arch_emit_autoreg (acfg, symbol);
8636 emit_mem_end (MonoAotCompile *acfg)
8640 sprintf (symbol, "mem_end");
8641 emit_section_change (acfg, ".text", 1);
8642 emit_alignment_code (acfg, 8);
8643 emit_label (acfg, symbol);
8647 init_aot_file_info (MonoAotCompile *acfg, MonoAotFileInfo *info, int gc_name_offset)
8651 info->version = MONO_AOT_FILE_VERSION;
8652 info->plt_got_offset_base = acfg->plt_got_offset_base;
8653 info->got_size = acfg->got_offset * sizeof (gpointer);
8654 info->plt_size = acfg->plt_offset;
8655 info->nmethods = acfg->nmethods;
8656 info->flags = acfg->flags;
8657 info->opts = acfg->opts;
8658 info->simd_opts = acfg->simd_opts;
8659 info->gc_name_index = gc_name_offset;
8660 for (i = 0; i < MONO_AOT_TRAMP_NUM; ++i)
8661 info->num_trampolines [i] = acfg->num_trampolines [i];
8662 for (i = 0; i < MONO_AOT_TRAMP_NUM; ++i)
8663 info->trampoline_got_offset_base [i] = acfg->trampoline_got_offset_base [i];
8664 for (i = 0; i < MONO_AOT_TRAMP_NUM; ++i)
8665 info->trampoline_size [i] = acfg->trampoline_size [i];
8666 info->num_rgctx_fetch_trampolines = acfg->aot_opts.nrgctx_fetch_trampolines;
8668 info->double_align = MONO_ABI_ALIGNOF (double);
8669 info->long_align = MONO_ABI_ALIGNOF (gint64);
8670 info->generic_tramp_num = MONO_TRAMPOLINE_NUM;
8671 info->tramp_page_size = acfg->tramp_page_size;
8672 for (i = 0; i < MONO_AOT_TRAMP_NUM; ++i)
8673 info->tramp_page_code_offsets [i] = acfg->tramp_page_code_offsets [i];
8677 emit_aot_file_info (MonoAotCompile *acfg, MonoAotFileInfo *info)
8681 const char **symbols;
8683 symbols = g_new0 (const char *, MONO_AOT_FILE_INFO_NUM_SYMBOLS);
8685 symbols [sindex ++] = acfg->got_symbol;
8687 symbols [sindex ++] = g_strdup_printf ("%s%s", acfg->user_symbol_prefix, acfg->llvm_got_symbol);
8688 symbols [sindex ++] = acfg->llvm_eh_frame_symbol;
8690 symbols [sindex ++] = NULL;
8691 symbols [sindex ++] = NULL;
8693 symbols [sindex ++] = "jit_code_start";
8694 symbols [sindex ++] = "jit_code_end";
8695 symbols [sindex ++] = "method_addresses";
8696 symbols [sindex ++] = "blob";
8697 symbols [sindex ++] = "class_name_table";
8698 symbols [sindex ++] = "class_info_offsets";
8699 symbols [sindex ++] = "method_info_offsets";
8700 symbols [sindex ++] = "ex_info_offsets";
8701 symbols [sindex ++] = "extra_method_info_offsets";
8702 symbols [sindex ++] = "extra_method_table";
8703 symbols [sindex ++] = "got_info_offsets";
8705 symbols [sindex ++] = "llvm_got_info_offsets";
8707 symbols [sindex ++] = NULL;
8708 symbols [sindex ++] = "mem_end";
8709 symbols [sindex ++] = "image_table";
8710 symbols [sindex ++] = "assembly_guid";
8711 symbols [sindex ++] = "runtime_version";
8712 if (acfg->num_trampoline_got_entries) {
8713 symbols [sindex ++] = "specific_trampolines";
8714 symbols [sindex ++] = "static_rgctx_trampolines";
8715 symbols [sindex ++] = "imt_thunks";
8716 symbols [sindex ++] = "gsharedvt_arg_trampolines";
8718 symbols [sindex ++] = NULL;
8719 symbols [sindex ++] = NULL;
8720 symbols [sindex ++] = NULL;
8721 symbols [sindex ++] = NULL;
8723 if (acfg->aot_opts.static_link) {
8724 symbols [sindex ++] = "globals";
8726 symbols [sindex ++] = NULL;
8728 symbols [sindex ++] = "assembly_name";
8729 symbols [sindex ++] = "plt";
8730 symbols [sindex ++] = "plt_end";
8731 symbols [sindex ++] = "unwind_info";
8732 symbols [sindex ++] = "unbox_trampolines";
8733 symbols [sindex ++] = "unbox_trampolines_end";
8734 symbols [sindex ++] = "unbox_trampoline_addresses";
8735 g_assert (sindex == MONO_AOT_FILE_INFO_NUM_SYMBOLS);
8737 sprintf (symbol, "%smono_aot_file_info", acfg->user_symbol_prefix);
8738 emit_section_change (acfg, ".data", 0);
8739 emit_alignment (acfg, 8);
8740 emit_label (acfg, symbol);
8741 if (!acfg->aot_opts.static_link)
8742 emit_global (acfg, symbol, FALSE);
8744 /* The data emitted here must match MonoAotFileInfo. */
8746 emit_int32 (acfg, info->version);
8747 emit_int32 (acfg, info->dummy);
8750 * We emit pointers to our data structures instead of emitting global symbols which
8751 * point to them, to reduce the number of globals, and because using globals leads to
8752 * various problems (i.e. arm/thumb).
8754 for (i = 0; i < MONO_AOT_FILE_INFO_NUM_SYMBOLS; ++i)
8755 emit_pointer (acfg, symbols [i]);
8757 emit_int32 (acfg, info->plt_got_offset_base);
8758 emit_int32 (acfg, info->got_size);
8759 emit_int32 (acfg, info->plt_size);
8760 emit_int32 (acfg, info->nmethods);
8761 emit_int32 (acfg, info->flags);
8762 emit_int32 (acfg, info->opts);
8763 emit_int32 (acfg, info->simd_opts);
8764 emit_int32 (acfg, info->gc_name_index);
8765 emit_int32 (acfg, info->num_rgctx_fetch_trampolines);
8766 emit_int32 (acfg, info->double_align);
8767 emit_int32 (acfg, info->long_align);
8768 emit_int32 (acfg, info->generic_tramp_num);
8769 emit_int32 (acfg, info->tramp_page_size);
8771 for (i = 0; i < MONO_AOT_TRAMP_NUM; ++i)
8772 emit_int32 (acfg, info->num_trampolines [i]);
8773 for (i = 0; i < MONO_AOT_TRAMP_NUM; ++i)
8774 emit_int32 (acfg, info->trampoline_got_offset_base [i]);
8775 for (i = 0; i < MONO_AOT_TRAMP_NUM; ++i)
8776 emit_int32 (acfg, info->trampoline_size [i]);
8777 for (i = 0; i < MONO_AOT_TRAMP_NUM; ++i)
8778 emit_int32 (acfg, info->tramp_page_code_offsets [i]);
8780 if (acfg->aot_opts.static_link) {
8784 * Emit a global symbol which can be passed by an embedding app to
8785 * mono_aot_register_module (). The symbol points to a pointer to the the file info
8788 sprintf (symbol, "%smono_aot_module_%s_info", acfg->user_symbol_prefix, acfg->image->assembly->aname.name);
8790 /* Get rid of characters which cannot occur in symbols */
8792 for (p = symbol; *p; ++p) {
8793 if (!(isalnum (*p) || *p == '_'))
8796 acfg->static_linking_symbol = g_strdup (symbol);
8797 emit_global_inner (acfg, symbol, FALSE);
8798 emit_alignment (acfg, sizeof (gpointer));
8799 emit_label (acfg, symbol);
8800 emit_pointer_2 (acfg, acfg->user_symbol_prefix, "mono_aot_file_info");
8805 * Emit a structure containing all the information not stored elsewhere.
8808 emit_file_info (MonoAotCompile *acfg)
8811 const char *gc_name;
8813 MonoAotFileInfo *info;
8815 if (acfg->aot_opts.bind_to_runtime_version) {
8816 build_info = mono_get_runtime_build_info ();
8817 emit_string_symbol (acfg, "runtime_version", build_info);
8818 g_free (build_info);
8820 emit_string_symbol (acfg, "runtime_version", "");
8823 emit_string_symbol (acfg, "assembly_guid" , acfg->image->guid);
8825 /* Emit a string holding the assembly name */
8826 emit_string_symbol (acfg, "assembly_name", acfg->image->assembly->aname.name);
8829 * The managed allocators are GC specific, so can't use an AOT image created by one GC
8832 gc_name = mono_gc_get_gc_name ();
8833 gc_name_offset = add_to_blob (acfg, (guint8*)gc_name, strlen (gc_name) + 1);
8835 info = g_new0 (MonoAotFileInfo, 1);
8836 init_aot_file_info (acfg, info, gc_name_offset);
8839 mono_llvm_emit_aot_file_info (info, acfg->has_jitted_code);
8841 emit_aot_file_info (acfg, info);
8845 emit_blob (MonoAotCompile *acfg)
8850 mono_llvm_emit_aot_data ("blob", (guint8*)acfg->blob.data, acfg->blob.index);
8854 sprintf (symbol, "blob");
8855 emit_section_change (acfg, RODATA_SECT, 1);
8856 emit_alignment (acfg, 8);
8857 emit_label (acfg, symbol);
8859 emit_bytes (acfg, (guint8*)acfg->blob.data, acfg->blob.index);
8863 emit_objc_selectors (MonoAotCompile *acfg)
8868 if (!acfg->objc_selectors || acfg->objc_selectors->len == 0)
8873 * cat > foo.m << EOF
8876 * return @selector(print:);
8881 mono_img_writer_emit_unset_mode (acfg->w);
8882 g_assert (acfg->fp);
8883 fprintf (acfg->fp, ".section __DATA,__objc_selrefs,literal_pointers,no_dead_strip\n");
8884 fprintf (acfg->fp, ".align 3\n");
8885 for (i = 0; i < acfg->objc_selectors->len; ++i) {
8886 sprintf (symbol, "L_OBJC_SELECTOR_REFERENCES_%d", i);
8887 emit_label (acfg, symbol);
8888 sprintf (symbol, "L_OBJC_METH_VAR_NAME_%d", i);
8889 emit_pointer (acfg, symbol);
8892 fprintf (acfg->fp, ".section __TEXT,__cstring,cstring_literals\n");
8893 for (i = 0; i < acfg->objc_selectors->len; ++i) {
8894 fprintf (acfg->fp, "L_OBJC_METH_VAR_NAME_%d:\n", i);
8895 fprintf (acfg->fp, ".asciz \"%s\"\n", (char*)g_ptr_array_index (acfg->objc_selectors, i));
8898 fprintf (acfg->fp, ".section __DATA,__objc_imageinfo,regular,no_dead_strip\n");
8899 fprintf (acfg->fp, ".align 3\n");
8900 fprintf (acfg->fp, "L_OBJC_IMAGE_INFO:\n");
8901 fprintf (acfg->fp, ".long 0\n");
8902 fprintf (acfg->fp, ".long 16\n");
8906 emit_dwarf_info (MonoAotCompile *acfg)
8908 #ifdef EMIT_DWARF_INFO
8912 /* DIEs for methods */
8913 for (i = 0; i < acfg->nmethods; ++i) {
8914 MonoCompile *cfg = acfg->cfgs [i];
8919 // FIXME: LLVM doesn't define .Lme_...
8920 if (cfg->compile_llvm)
8923 sprintf (symbol2, "%sme_%x", acfg->temp_prefix, i);
8925 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 ()));
8931 collect_methods (MonoAotCompile *acfg)
8934 MonoImage *image = acfg->image;
8936 /* Collect methods */
8937 for (i = 0; i < image->tables [MONO_TABLE_METHOD].rows; ++i) {
8940 guint32 token = MONO_TOKEN_METHOD_DEF | (i + 1);
8942 method = mono_get_method_checked (acfg->image, token, NULL, NULL, &error);
8945 aot_printerrf (acfg, "Failed to load method 0x%x from '%s' due to %s.\n", token, image->name, mono_error_get_message (&error));
8946 aot_printerrf (acfg, "Run with MONO_LOG_LEVEL=debug for more information.\n");
8947 mono_error_cleanup (&error);
8951 /* Load all methods eagerly to skip the slower lazy loading code */
8952 mono_class_setup_methods (method->klass);
8954 if (mono_aot_mode_is_full (&acfg->aot_opts) && method->iflags & METHOD_IMPL_ATTRIBUTE_INTERNAL_CALL) {
8955 /* Compile the wrapper instead */
8956 /* We do this here instead of add_wrappers () because it is easy to do it here */
8957 MonoMethod *wrapper = mono_marshal_get_native_wrapper (method, TRUE, TRUE);
8961 /* FIXME: Some mscorlib methods don't have debug info */
8963 if (acfg->aot_opts.soft_debug && !method->wrapper_type) {
8964 if (!((method->flags & METHOD_ATTRIBUTE_PINVOKE_IMPL) ||
8965 (method->iflags & METHOD_IMPL_ATTRIBUTE_RUNTIME) ||
8966 (method->flags & METHOD_ATTRIBUTE_ABSTRACT) ||
8967 (method->iflags & METHOD_IMPL_ATTRIBUTE_INTERNAL_CALL))) {
8968 if (!mono_debug_lookup_method (method)) {
8969 fprintf (stderr, "Method %s has no debug info, probably the .mdb file for the assembly is missing.\n", mono_method_full_name (method, TRUE));
8976 if (method->is_generic || method->klass->generic_container)
8977 /* Compile the ref shared version instead */
8978 method = mini_get_shared_method (method);
8980 /* Since we add the normal methods first, their index will be equal to their zero based token index */
8981 add_method_with_index (acfg, method, i, FALSE);
8982 acfg->method_index ++;
8985 /* gsharedvt methods */
8986 for (mindex = 0; mindex < image->tables [MONO_TABLE_METHOD].rows; ++mindex) {
8989 guint32 token = MONO_TOKEN_METHOD_DEF | (mindex + 1);
8991 if (!(acfg->opts & MONO_OPT_GSHAREDVT))
8994 method = mono_get_method_checked (acfg->image, token, NULL, NULL, &error);
8995 report_loader_error (acfg, &error, "Failed to load method token 0x%x due to %s\n", i, mono_error_get_message (&error));
8997 if (method->is_generic || method->klass->generic_container) {
8998 MonoMethod *gshared;
9000 gshared = mini_get_shared_method_full (method, TRUE, TRUE);
9001 add_extra_method (acfg, gshared);
9005 add_generic_instances (acfg);
9007 if (mono_aot_mode_is_full (&acfg->aot_opts))
9008 add_wrappers (acfg);
9013 compile_methods (MonoAotCompile *acfg)
9017 if (acfg->aot_opts.nthreads > 0) {
9022 gpointer *user_data;
9023 MonoMethod **methods;
9025 methods_len = acfg->methods->len;
9027 len = acfg->methods->len / acfg->aot_opts.nthreads;
9030 * Partition the list of methods into fragments, and hand it to threads to
9033 threads = g_ptr_array_new ();
9034 /* Make a copy since acfg->methods is modified by compile_method () */
9035 methods = g_new0 (MonoMethod*, methods_len);
9036 //memcpy (methods, g_ptr_array_index (acfg->methods, 0), sizeof (MonoMethod*) * methods_len);
9037 for (i = 0; i < methods_len; ++i)
9038 methods [i] = g_ptr_array_index (acfg->methods, i);
9040 while (i < methods_len) {
9041 frag = g_ptr_array_new ();
9042 for (j = 0; j < len; ++j) {
9043 if (i < methods_len) {
9044 g_ptr_array_add (frag, methods [i]);
9049 user_data = g_new0 (gpointer, 3);
9050 user_data [0] = mono_domain_get ();
9051 user_data [1] = acfg;
9052 user_data [2] = frag;
9054 handle = mono_threads_create_thread ((gpointer)compile_thread_main, user_data, 0, 0, NULL);
9055 g_ptr_array_add (threads, handle);
9059 for (i = 0; i < threads->len; ++i) {
9060 WaitForSingleObjectEx (g_ptr_array_index (threads, i), INFINITE, FALSE);
9066 /* Compile methods added by compile_method () or all methods if nthreads == 0 */
9067 for (i = methods_len; i < acfg->methods->len; ++i) {
9068 /* This can new methods to acfg->methods */
9069 compile_method (acfg, g_ptr_array_index (acfg->methods, i));
9074 compile_asm (MonoAotCompile *acfg)
9076 char *command, *objfile;
9077 char *outfile_name, *tmp_outfile_name, *llvm_ofile;
9078 const char *tool_prefix = acfg->aot_opts.tool_prefix ? acfg->aot_opts.tool_prefix : "";
9079 char *ld_flags = acfg->aot_opts.ld_flags ? acfg->aot_opts.ld_flags : g_strdup("");
9081 #if defined(TARGET_AMD64) && !defined(TARGET_MACH)
9082 #define AS_OPTIONS "--64"
9083 #elif defined(TARGET_POWERPC64)
9084 #define AS_OPTIONS "-a64 -mppc64"
9085 #define LD_OPTIONS "-m elf64ppc"
9086 #elif defined(sparc) && SIZEOF_VOID_P == 8
9087 #define AS_OPTIONS "-xarch=v9"
9088 #elif defined(TARGET_X86) && defined(TARGET_MACH) && !defined(__native_client_codegen__)
9089 #define AS_OPTIONS "-arch i386"
9091 #define AS_OPTIONS ""
9094 #ifdef __native_client_codegen__
9095 #if defined(TARGET_AMD64)
9096 #define AS_NAME "nacl64-as"
9098 #define AS_NAME "nacl-as"
9100 #elif defined(TARGET_OSX)
9101 #define AS_NAME "clang"
9103 #define AS_NAME "as"
9107 #define LD_OPTIONS ""
9111 #define LD_NAME "ld -shared -G"
9112 #elif defined(__ppc__) && defined(TARGET_MACH)
9113 #define LD_NAME "gcc -dynamiclib"
9114 #elif defined(TARGET_AMD64) && defined(TARGET_MACH)
9115 #define LD_NAME "clang --shared"
9116 #elif defined(TARGET_WIN32) && !defined(TARGET_ANDROID)
9117 #define LD_NAME "gcc -shared --dll"
9118 #elif defined(TARGET_X86) && defined(TARGET_MACH) && !defined(__native_client_codegen__)
9119 #define LD_NAME "clang -m32 -dynamiclib"
9120 #elif defined(TARGET_ARM) && !defined(TARGET_ANDROID)
9121 #define LD_NAME "gcc --shared"
9124 if (acfg->aot_opts.asm_only) {
9125 aot_printf (acfg, "Output file: '%s'.\n", acfg->tmpfname);
9126 if (acfg->aot_opts.static_link)
9127 aot_printf (acfg, "Linking symbol: '%s'.\n", acfg->static_linking_symbol);
9129 aot_printf (acfg, "LLVM output file: '%s'.\n", acfg->llvm_sfile);
9133 if (acfg->aot_opts.static_link) {
9134 if (acfg->aot_opts.outfile)
9135 objfile = g_strdup_printf ("%s", acfg->aot_opts.outfile);
9137 objfile = g_strdup_printf ("%s.o", acfg->image->name);
9139 objfile = g_strdup_printf ("%s.o", acfg->tmpfname);
9143 g_string_append (acfg->as_args, "-c -x assembler");
9146 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);
9147 aot_printf (acfg, "Executing the native assembler: %s\n", command);
9148 if (execute_system (command) != 0) {
9154 if (acfg->llvm && !acfg->llvm_owriter) {
9155 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);
9156 aot_printf (acfg, "Executing the native assembler: %s\n", command);
9157 if (execute_system (command) != 0) {
9166 if (acfg->aot_opts.static_link) {
9167 aot_printf (acfg, "Output file: '%s'.\n", objfile);
9168 aot_printf (acfg, "Linking symbol: '%s'.\n", acfg->static_linking_symbol);
9173 if (acfg->aot_opts.outfile)
9174 outfile_name = g_strdup_printf ("%s", acfg->aot_opts.outfile);
9176 outfile_name = g_strdup_printf ("%s%s", acfg->image->name, MONO_SOLIB_EXT);
9178 tmp_outfile_name = g_strdup_printf ("%s.tmp", outfile_name);
9181 llvm_ofile = g_strdup_printf ("\"%s\"", acfg->llvm_ofile);
9183 llvm_ofile = g_strdup ("");
9186 /* replace the ; flags separators with spaces */
9187 g_strdelimit (ld_flags, ";", ' ');
9190 command = g_strdup_printf ("%s -o \"%s\" %s \"%s.o\" %s", LD_NAME, tmp_outfile_name, llvm_ofile, acfg->tmpfname, ld_flags);
9192 command = g_strdup_printf ("\"%sld\" %s -shared -o %s %s %s.o %s", tool_prefix, LD_OPTIONS, tmp_outfile_name, llvm_ofile,
9193 acfg->tmpfname, ld_flags);
9195 aot_printf (acfg, "Executing the native linker: %s\n", command);
9196 if (execute_system (command) != 0) {
9197 g_free (tmp_outfile_name);
9198 g_free (outfile_name);
9207 /*com = g_strdup_printf ("strip --strip-unneeded %s%s", acfg->image->name, MONO_SOLIB_EXT);
9208 printf ("Stripping the binary: %s\n", com);
9209 execute_system (com);
9212 #if defined(TARGET_ARM) && !defined(TARGET_MACH)
9214 * gas generates 'mapping symbols' each time code and data is mixed, which
9215 * happens a lot in emit_and_reloc_code (), so we need to get rid of them.
9217 command = g_strdup_printf ("\"%sstrip\" --strip-symbol=\\$a --strip-symbol=\\$d %s", tool_prefix, tmp_outfile_name);
9218 aot_printf (acfg, "Stripping the binary: %s\n", command);
9219 if (execute_system (command) != 0) {
9220 g_free (tmp_outfile_name);
9221 g_free (outfile_name);
9228 rename (tmp_outfile_name, outfile_name);
9230 #if defined(TARGET_MACH)
9231 command = g_strdup_printf ("dsymutil \"%s\"", outfile_name);
9232 aot_printf (acfg, "Executing dsymutil: %s\n", command);
9233 if (execute_system (command) != 0) {
9238 if (!acfg->aot_opts.save_temps)
9241 g_free (tmp_outfile_name);
9242 g_free (outfile_name);
9245 if (acfg->aot_opts.save_temps)
9246 aot_printf (acfg, "Retained input file.\n");
9248 unlink (acfg->tmpfname);
9253 static void init_got_info (GotInfo *info)
9257 info->patch_to_got_offset = g_hash_table_new (mono_patch_info_hash, mono_patch_info_equal);
9258 info->patch_to_got_offset_by_type = g_new0 (GHashTable*, MONO_PATCH_INFO_NUM);
9259 for (i = 0; i < MONO_PATCH_INFO_NUM; ++i)
9260 info->patch_to_got_offset_by_type [i] = g_hash_table_new (mono_patch_info_hash, mono_patch_info_equal);
9261 info->got_patches = g_ptr_array_new ();
9264 static MonoAotCompile*
9265 acfg_create (MonoAssembly *ass, guint32 opts)
9267 MonoImage *image = ass->image;
9268 MonoAotCompile *acfg;
9270 acfg = g_new0 (MonoAotCompile, 1);
9271 acfg->methods = g_ptr_array_new ();
9272 acfg->method_indexes = g_hash_table_new (NULL, NULL);
9273 acfg->method_depth = g_hash_table_new (NULL, NULL);
9274 acfg->plt_offset_to_entry = g_hash_table_new (NULL, NULL);
9275 acfg->patch_to_plt_entry = g_new0 (GHashTable*, MONO_PATCH_INFO_NUM);
9276 acfg->method_to_cfg = g_hash_table_new (NULL, NULL);
9277 acfg->token_info_hash = g_hash_table_new_full (NULL, NULL, NULL, NULL);
9278 acfg->method_to_pinvoke_import = g_hash_table_new_full (NULL, NULL, NULL, g_free);
9279 acfg->image_hash = g_hash_table_new (NULL, NULL);
9280 acfg->image_table = g_ptr_array_new ();
9281 acfg->globals = g_ptr_array_new ();
9282 acfg->image = image;
9284 /* TODO: Write out set of SIMD instructions used, rather than just those available */
9285 acfg->simd_opts = mono_arch_cpu_enumerate_simd_versions ();
9286 acfg->mempool = mono_mempool_new ();
9287 acfg->extra_methods = g_ptr_array_new ();
9288 acfg->unwind_info_offsets = g_hash_table_new (NULL, NULL);
9289 acfg->unwind_ops = g_ptr_array_new ();
9290 acfg->method_label_hash = g_hash_table_new_full (g_str_hash, g_str_equal, g_free, NULL);
9291 acfg->method_order = g_ptr_array_new ();
9292 acfg->export_names = g_hash_table_new (NULL, NULL);
9293 acfg->klass_blob_hash = g_hash_table_new (NULL, NULL);
9294 acfg->method_blob_hash = g_hash_table_new (NULL, NULL);
9295 acfg->plt_entry_debug_sym_cache = g_hash_table_new (g_str_hash, g_str_equal);
9296 mono_mutex_init_recursive (&acfg->mutex);
9298 init_got_info (&acfg->got_info);
9299 init_got_info (&acfg->llvm_got_info);
9305 got_info_free (GotInfo *info)
9309 for (i = 0; i < MONO_PATCH_INFO_NUM; ++i)
9310 g_hash_table_destroy (info->patch_to_got_offset_by_type [i]);
9311 g_free (info->patch_to_got_offset_by_type);
9312 g_hash_table_destroy (info->patch_to_got_offset);
9313 g_ptr_array_free (info->got_patches, TRUE);
9317 acfg_free (MonoAotCompile *acfg)
9321 mono_img_writer_destroy (acfg->w);
9322 for (i = 0; i < acfg->nmethods; ++i)
9324 g_free (acfg->cfgs [i]);
9325 g_free (acfg->cfgs);
9326 g_free (acfg->static_linking_symbol);
9327 g_free (acfg->got_symbol);
9328 g_free (acfg->plt_symbol);
9329 g_ptr_array_free (acfg->methods, TRUE);
9330 g_ptr_array_free (acfg->image_table, TRUE);
9331 g_ptr_array_free (acfg->globals, TRUE);
9332 g_ptr_array_free (acfg->unwind_ops, TRUE);
9333 g_hash_table_destroy (acfg->method_indexes);
9334 g_hash_table_destroy (acfg->method_depth);
9335 g_hash_table_destroy (acfg->plt_offset_to_entry);
9336 for (i = 0; i < MONO_PATCH_INFO_NUM; ++i) {
9337 if (acfg->patch_to_plt_entry [i])
9338 g_hash_table_destroy (acfg->patch_to_plt_entry [i]);
9340 g_free (acfg->patch_to_plt_entry);
9341 g_hash_table_destroy (acfg->method_to_cfg);
9342 g_hash_table_destroy (acfg->token_info_hash);
9343 g_hash_table_destroy (acfg->method_to_pinvoke_import);
9344 g_hash_table_destroy (acfg->image_hash);
9345 g_hash_table_destroy (acfg->unwind_info_offsets);
9346 g_hash_table_destroy (acfg->method_label_hash);
9347 g_hash_table_destroy (acfg->export_names);
9348 g_hash_table_destroy (acfg->plt_entry_debug_sym_cache);
9349 g_hash_table_destroy (acfg->klass_blob_hash);
9350 g_hash_table_destroy (acfg->method_blob_hash);
9351 got_info_free (&acfg->got_info);
9352 got_info_free (&acfg->llvm_got_info);
9353 mono_mempool_destroy (acfg->mempool);
9357 #define WRAPPER(e,n) n,
9358 static const char* const
9359 wrapper_type_names [MONO_WRAPPER_NUM + 1] = {
9360 #include "mono/metadata/wrapper-types.h"
9364 static G_GNUC_UNUSED const char*
9365 get_wrapper_type_name (int type)
9367 return wrapper_type_names [type];
9373 static void aot_dump (MonoAotCompile *acfg)
9379 mono_json_writer_init (&writer);
9381 mono_json_writer_object_begin(&writer);
9384 mono_json_writer_indent (&writer);
9385 mono_json_writer_object_key(&writer, "methods");
9386 mono_json_writer_array_begin (&writer);
9389 for (i = 0; i < acfg->nmethods; ++i) {
9394 cfg = acfg->cfgs [i];
9398 method = cfg->orig_method;
9400 mono_json_writer_indent (&writer);
9401 mono_json_writer_object_begin(&writer);
9403 mono_json_writer_indent (&writer);
9404 mono_json_writer_object_key(&writer, "name");
9405 mono_json_writer_printf (&writer, "\"%s\",\n", method->name);
9407 mono_json_writer_indent (&writer);
9408 mono_json_writer_object_key(&writer, "signature");
9409 mono_json_writer_printf (&writer, "\"%s\",\n", mono_method_full_name (method,
9410 /*signature=*/TRUE));
9412 mono_json_writer_indent (&writer);
9413 mono_json_writer_object_key(&writer, "code_size");
9414 mono_json_writer_printf (&writer, "\"%d\",\n", cfg->code_size);
9416 klass = method->klass;
9418 mono_json_writer_indent (&writer);
9419 mono_json_writer_object_key(&writer, "class");
9420 mono_json_writer_printf (&writer, "\"%s\",\n", klass->name);
9422 mono_json_writer_indent (&writer);
9423 mono_json_writer_object_key(&writer, "namespace");
9424 mono_json_writer_printf (&writer, "\"%s\",\n", klass->name_space);
9426 mono_json_writer_indent (&writer);
9427 mono_json_writer_object_key(&writer, "wrapper_type");
9428 mono_json_writer_printf (&writer, "\"%s\",\n", get_wrapper_type_name(method->wrapper_type));
9430 mono_json_writer_indent_pop (&writer);
9431 mono_json_writer_indent (&writer);
9432 mono_json_writer_object_end (&writer);
9433 mono_json_writer_printf (&writer, ",\n");
9436 mono_json_writer_indent_pop (&writer);
9437 mono_json_writer_indent (&writer);
9438 mono_json_writer_array_end (&writer);
9439 mono_json_writer_printf (&writer, ",\n");
9443 mono_json_writer_indent_push (&writer);
9444 mono_json_writer_indent (&writer);
9445 mono_json_writer_object_key(&writer, "plt");
9446 mono_json_writer_array_begin (&writer);
9448 for (i = 0; i < acfg->plt_offset; ++i) {
9449 MonoPltEntry *plt_entry = NULL;
9454 * The first plt entry is unused.
9458 plt_entry = g_hash_table_lookup (acfg->plt_offset_to_entry, GUINT_TO_POINTER (i));
9461 mono_json_writer_indent (&writer);
9462 mono_json_writer_printf (&writer, "{ ");
9463 mono_json_writer_object_key(&writer, "symbol");
9464 mono_json_writer_printf (&writer, "\"%s\" },\n", plt_entry->symbol);
9467 mono_json_writer_indent_pop (&writer);
9468 mono_json_writer_indent (&writer);
9469 mono_json_writer_array_end (&writer);
9470 mono_json_writer_printf (&writer, ",\n");
9475 mono_json_writer_indent_push (&writer);
9476 mono_json_writer_indent (&writer);
9477 mono_json_writer_object_key(&writer, "got");
9478 mono_json_writer_array_begin (&writer);
9480 mono_json_writer_indent_push (&writer);
9481 for (i = 0; i < acfg->got_info.got_patches->len; ++i) {
9482 MonoJumpInfo *ji = g_ptr_array_index (acfg->got_info.got_patches, i);
9484 mono_json_writer_indent (&writer);
9485 mono_json_writer_printf (&writer, "{ ");
9486 mono_json_writer_object_key(&writer, "patch_name");
9487 mono_json_writer_printf (&writer, "\"%s\" },\n", get_patch_name (ji->type));
9490 mono_json_writer_indent_pop (&writer);
9491 mono_json_writer_indent (&writer);
9492 mono_json_writer_array_end (&writer);
9493 mono_json_writer_printf (&writer, ",\n");
9496 mono_json_writer_indent_pop (&writer);
9497 mono_json_writer_indent (&writer);
9498 mono_json_writer_object_end (&writer);
9500 dumpname = g_strdup_printf ("%s.json", g_path_get_basename (acfg->image->name));
9501 dumpfile = fopen (dumpname, "w+");
9504 fprintf (dumpfile, "%s", writer.text->str);
9507 mono_json_writer_destroy (&writer);
9511 mono_compile_assembly (MonoAssembly *ass, guint32 opts, const char *aot_options)
9513 MonoImage *image = ass->image;
9516 MonoAotCompile *acfg;
9517 char *outfile_name, *tmp_outfile_name, *p;
9518 char llvm_stats_msg [256];
9522 acfg = acfg_create (ass, opts);
9524 memset (&acfg->aot_opts, 0, sizeof (acfg->aot_opts));
9525 acfg->aot_opts.write_symbols = TRUE;
9526 acfg->aot_opts.ntrampolines = 1024;
9527 acfg->aot_opts.nrgctx_trampolines = 1024;
9528 acfg->aot_opts.nimt_trampolines = 128;
9529 acfg->aot_opts.nrgctx_fetch_trampolines = 128;
9530 acfg->aot_opts.ngsharedvt_arg_trampolines = 128;
9531 acfg->aot_opts.llvm_path = g_strdup ("");
9532 acfg->aot_opts.temp_path = g_strdup ("");
9534 acfg->aot_opts.use_trampolines_page = TRUE;
9537 mono_aot_parse_options (aot_options, &acfg->aot_opts);
9539 if (acfg->aot_opts.logfile) {
9540 acfg->logfile = fopen (acfg->aot_opts.logfile, "a+");
9543 if (acfg->aot_opts.static_link)
9544 acfg->aot_opts.autoreg = TRUE;
9546 //acfg->aot_opts.print_skipped_methods = TRUE;
9548 #if !defined(MONO_ARCH_GSHAREDVT_SUPPORTED) || !defined(ENABLE_GSHAREDVT)
9549 if (opts & MONO_OPT_GSHAREDVT) {
9550 aot_printerrf (acfg, "-O=gsharedvt not supported on this platform.\n");
9555 aot_printf (acfg, "Mono Ahead of Time compiler - compiling assembly %s\n", image->name);
9557 #ifndef MONO_ARCH_HAVE_FULL_AOT_TRAMPOLINES
9558 if (mono_aot_mode_is_full (&acfg->aot_opts)) {
9559 aot_printerrf (acfg, "--aot=full is not supported on this platform.\n");
9564 if (acfg->aot_opts.direct_pinvoke && !acfg->aot_opts.static_link) {
9565 aot_printerrf (acfg, "The 'direct-pinvoke' AOT option also requires the 'static' AOT option.\n");
9569 if (acfg->aot_opts.static_link)
9570 acfg->aot_opts.asm_writer = TRUE;
9572 if (acfg->aot_opts.soft_debug) {
9573 MonoDebugOptions *opt = mini_get_debug_options ();
9575 opt->mdb_optimizations = TRUE;
9576 opt->gen_sdb_seq_points = TRUE;
9578 if (!mono_debug_enabled ()) {
9579 aot_printerrf (acfg, "The soft-debug AOT option requires the --debug option.\n");
9582 acfg->flags |= MONO_AOT_FILE_FLAG_DEBUG;
9585 if (mono_use_llvm || acfg->aot_opts.llvm) {
9587 acfg->aot_opts.asm_writer = TRUE;
9588 acfg->flags |= MONO_AOT_FILE_FLAG_WITH_LLVM;
9590 if (acfg->aot_opts.soft_debug) {
9591 aot_printerrf (acfg, "The 'soft-debug' option is not supported when compiling with LLVM.\n");
9597 if (acfg->aot_opts.asm_only && !acfg->aot_opts.llvm_outfile) {
9598 aot_printerrf (acfg, "Compiling with LLVM and the asm-only option requires the llvm-outputfile= option.");
9603 * Emit all LLVM code into a separate assembly/object file and link with it
9606 if (!acfg->aot_opts.asm_only) {
9607 acfg->llvm_owriter = TRUE;
9608 } else if (acfg->aot_opts.llvm_outfile) {
9609 int len = strlen (acfg->aot_opts.llvm_outfile);
9611 if (len >= 2 && acfg->aot_opts.llvm_outfile [len - 2] == '.' && acfg->aot_opts.llvm_outfile [len - 1] == 'o')
9612 acfg->llvm_owriter = TRUE;
9616 if (mono_aot_mode_is_full (&acfg->aot_opts))
9617 acfg->flags |= MONO_AOT_FILE_FLAG_FULL_AOT;
9619 if (acfg->aot_opts.instances_logfile_path) {
9620 acfg->instances_logfile = fopen (acfg->aot_opts.instances_logfile_path, "w");
9621 if (!acfg->instances_logfile) {
9622 aot_printerrf (acfg, "Unable to create logfile: '%s'.\n", acfg->aot_opts.instances_logfile_path);
9627 load_profile_files (acfg);
9629 acfg->num_trampolines [MONO_AOT_TRAMP_SPECIFIC] = mono_aot_mode_is_full (&acfg->aot_opts) ? acfg->aot_opts.ntrampolines : 0;
9630 #ifdef MONO_ARCH_GSHARED_SUPPORTED
9631 acfg->num_trampolines [MONO_AOT_TRAMP_STATIC_RGCTX] = mono_aot_mode_is_full (&acfg->aot_opts) ? acfg->aot_opts.nrgctx_trampolines : 0;
9633 acfg->num_trampolines [MONO_AOT_TRAMP_IMT_THUNK] = mono_aot_mode_is_full (&acfg->aot_opts) ? acfg->aot_opts.nimt_trampolines : 0;
9634 #ifdef MONO_ARCH_GSHAREDVT_SUPPORTED
9635 if (acfg->opts & MONO_OPT_GSHAREDVT)
9636 acfg->num_trampolines [MONO_AOT_TRAMP_GSHAREDVT_ARG] = mono_aot_mode_is_full (&acfg->aot_opts) ? acfg->aot_opts.ngsharedvt_arg_trampolines : 0;
9639 acfg->temp_prefix = mono_img_writer_get_temp_label_prefix (NULL);
9643 if (acfg->llvm && acfg->thumb_mixed)
9644 acfg->flags |= MONO_AOT_FILE_FLAG_LLVM_THUMB;
9646 acfg->assembly_name_sym = g_strdup (acfg->image->assembly->aname.name);
9647 /* Get rid of characters which cannot occur in symbols */
9648 for (p = acfg->assembly_name_sym; *p; ++p) {
9649 if (!(isalnum (*p) || *p == '_'))
9653 acfg->global_prefix = g_strdup_printf ("mono_aot_%s", acfg->assembly_name_sym);
9654 acfg->plt_symbol = g_strdup_printf ("%s_plt", acfg->global_prefix);
9655 acfg->got_symbol = g_strdup_printf ("%s_got", acfg->global_prefix);
9657 acfg->llvm_got_symbol = g_strdup_printf ("%s_llvm_got", acfg->global_prefix);
9658 acfg->llvm_eh_frame_symbol = g_strdup_printf ("%s_eh_frame", acfg->global_prefix);
9661 acfg->method_index = 1;
9663 if (mono_aot_mode_is_full (&acfg->aot_opts))
9664 mono_set_partial_sharing_supported (TRUE);
9666 res = collect_methods (acfg);
9670 acfg->cfgs_size = acfg->methods->len + 32;
9671 acfg->cfgs = g_new0 (MonoCompile*, acfg->cfgs_size);
9673 /* PLT offset 0 is reserved for the PLT trampoline */
9674 acfg->plt_offset = 1;
9679 mono_llvm_create_aot_module (acfg->image->assembly, acfg->global_prefix, TRUE, acfg->aot_opts.static_link);
9683 /* GOT offset 0 is reserved for the address of the current assembly */
9687 ji = mono_mempool_alloc0 (acfg->mempool, sizeof (MonoJumpInfo));
9688 ji->type = MONO_PATCH_INFO_IMAGE;
9689 ji->data.image = acfg->image;
9691 get_got_offset (acfg, FALSE, ji);
9692 get_got_offset (acfg, TRUE, ji);
9694 /* Slot 1 is reserved for the mscorlib got addr */
9695 ji = mono_mempool_alloc0 (acfg->mempool, sizeof (MonoJumpInfo));
9696 ji->type = MONO_PATCH_INFO_MSCORLIB_GOT_ADDR;
9697 get_got_offset (acfg, FALSE, ji);
9698 get_got_offset (acfg, TRUE, ji);
9700 /* This is very common */
9701 ji = mono_mempool_alloc0 (acfg->mempool, sizeof (MonoJumpInfo));
9702 ji->type = MONO_PATCH_INFO_GC_CARD_TABLE_ADDR;
9703 get_got_offset (acfg, FALSE, ji);
9704 get_got_offset (acfg, TRUE, ji);
9706 ji = mono_mempool_alloc0 (acfg->mempool, sizeof (MonoJumpInfo));
9707 ji->type = MONO_PATCH_INFO_GC_NURSERY_START;
9708 get_got_offset (acfg, FALSE, ji);
9709 get_got_offset (acfg, TRUE, ji);
9711 ji = mono_mempool_alloc0 (acfg->mempool, sizeof (MonoJumpInfo));
9712 ji->type = MONO_PATCH_INFO_JIT_TLS_ID;
9713 get_got_offset (acfg, FALSE, ji);
9714 get_got_offset (acfg, TRUE, ji);
9719 compile_methods (acfg);
9723 acfg->stats.jit_time = TV_ELAPSED (atv, btv);
9729 if (acfg->aot_opts.asm_only) {
9730 if (acfg->aot_opts.outfile) {
9731 acfg->tmpfname = g_strdup_printf ("%s", acfg->aot_opts.outfile);
9732 acfg->tmpbasename = g_strdup (acfg->tmpfname);
9734 acfg->tmpbasename = g_strdup_printf ("%s", acfg->image->name);
9735 acfg->tmpfname = g_strdup_printf ("%s.s", acfg->tmpbasename);
9737 g_assert (acfg->aot_opts.llvm_outfile);
9738 acfg->llvm_sfile = g_strdup (acfg->aot_opts.llvm_outfile);
9739 if (acfg->llvm_owriter)
9740 acfg->llvm_ofile = g_strdup (acfg->aot_opts.llvm_outfile);
9742 acfg->llvm_sfile = g_strdup (acfg->aot_opts.llvm_outfile);
9744 acfg->tmpbasename = (strcmp (acfg->aot_opts.temp_path, "") == 0) ?
9745 g_strdup_printf ("%s", "temp") :
9746 g_build_filename (acfg->aot_opts.temp_path, "temp", NULL);
9748 acfg->tmpfname = g_strdup_printf ("%s.s", acfg->tmpbasename);
9749 acfg->llvm_sfile = g_strdup_printf ("%s-llvm.s", acfg->tmpbasename);
9750 acfg->llvm_ofile = g_strdup_printf ("%s-llvm.o", acfg->tmpbasename);
9755 if (!acfg->aot_opts.asm_only && !acfg->aot_opts.asm_writer && mono_bin_writer_supported ()) {
9756 if (acfg->aot_opts.outfile)
9757 outfile_name = g_strdup_printf ("%s", acfg->aot_opts.outfile);
9759 outfile_name = g_strdup_printf ("%s%s", acfg->image->name, MONO_SOLIB_EXT);
9762 * Can't use g_file_open_tmp () as it will be deleted at exit, and
9763 * it might be in another file system so the rename () won't work.
9765 tmp_outfile_name = g_strdup_printf ("%s.tmp", outfile_name);
9767 acfg->fp = fopen (tmp_outfile_name, "w");
9769 aot_printf (acfg, "Unable to create temporary file '%s': %s\n", tmp_outfile_name, strerror (errno));
9773 acfg->w = mono_img_writer_create (acfg->fp, TRUE);
9774 acfg->use_bin_writer = TRUE;
9776 if (acfg->aot_opts.asm_only) {
9777 if (acfg->aot_opts.outfile)
9778 acfg->tmpfname = g_strdup_printf ("%s", acfg->aot_opts.outfile);
9780 acfg->tmpfname = g_strdup_printf ("%s.s", acfg->image->name);
9781 acfg->fp = fopen (acfg->tmpfname, "w+");
9783 int i = g_file_open_tmp ("mono_aot_XXXXXX", &acfg->tmpfname, NULL);
9784 acfg->fp = fdopen (i, "w+");
9786 if (acfg->fp == 0) {
9787 aot_printerrf (acfg, "Unable to open file '%s': %s\n", acfg->tmpfname, strerror (errno));
9790 acfg->w = mono_img_writer_create (acfg->fp, FALSE);
9792 tmp_outfile_name = NULL;
9793 outfile_name = NULL;
9796 /* Compute symbols for methods */
9797 for (i = 0; i < acfg->nmethods; ++i) {
9798 if (acfg->cfgs [i]) {
9799 MonoCompile *cfg = acfg->cfgs [i];
9800 int method_index = get_method_index (acfg, cfg->orig_method);
9802 if (COMPILE_LLVM (cfg))
9803 cfg->asm_symbol = g_strdup_printf ("%s%s", acfg->llvm_label_prefix, cfg->llvm_method_name);
9804 else if (acfg->global_symbols || acfg->llvm)
9805 cfg->asm_symbol = get_debug_sym (cfg->orig_method, "", acfg->method_label_hash);
9807 cfg->asm_symbol = g_strdup_printf ("%s%sm_%x", acfg->temp_prefix, acfg->llvm_label_prefix, method_index);
9808 cfg->asm_debug_symbol = cfg->asm_symbol;
9812 if (acfg->aot_opts.dwarf_debug && acfg->aot_opts.asm_only && acfg->aot_opts.gnu_asm) {
9814 * CLANG supports GAS .file/.loc directives, so emit line number information this way
9815 * FIXME: CLANG only emits line number info for .loc directives followed by assembly, not
9818 //acfg->gas_line_numbers = TRUE;
9821 if ((!acfg->aot_opts.nodebug || acfg->aot_opts.dwarf_debug) && acfg->has_jitted_code) {
9822 if (acfg->aot_opts.dwarf_debug && !mono_debug_enabled ()) {
9823 aot_printerrf (acfg, "The dwarf AOT option requires the --debug option.\n");
9826 acfg->dwarf = mono_dwarf_writer_create (acfg->w, NULL, 0, FALSE, !acfg->gas_line_numbers);
9829 mono_img_writer_emit_start (acfg->w);
9832 mono_dwarf_writer_emit_base_info (acfg->dwarf, g_path_get_basename (acfg->image->name), mono_unwind_get_cie_program ());
9838 emit_extra_methods (acfg);
9840 emit_trampolines (acfg);
9842 emit_class_name_table (acfg);
9844 emit_got_info (acfg, FALSE);
9846 emit_got_info (acfg, TRUE);
9848 emit_exception_info (acfg);
9850 emit_unwind_info (acfg);
9852 emit_class_info (acfg);
9856 emit_image_table (acfg);
9860 emit_file_info (acfg);
9864 emit_objc_selectors (acfg);
9866 emit_globals (acfg);
9868 emit_autoreg (acfg);
9871 emit_dwarf_info (acfg);
9872 mono_dwarf_writer_close (acfg->dwarf);
9875 emit_mem_end (acfg);
9877 if (acfg->need_pt_gnu_stack) {
9878 /* This is required so the .so doesn't have an executable stack */
9879 /* The bin writer already emits this */
9880 if (!acfg->use_bin_writer)
9881 fprintf (acfg->fp, "\n.section .note.GNU-stack,\"\",@progbits\n");
9888 res = emit_llvm_file (acfg);
9896 acfg->stats.gen_time = TV_ELAPSED (atv, btv);
9899 sprintf (llvm_stats_msg, ", LLVM: %d (%d%%)", acfg->stats.llvm_count, acfg->stats.mcount ? (acfg->stats.llvm_count * 100) / acfg->stats.mcount : 100);
9901 strcpy (llvm_stats_msg, "");
9903 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;
9905 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",
9906 (int)acfg->stats.code_size, (int)(acfg->stats.code_size * 100 / all_sizes),
9907 (int)acfg->stats.info_size, (int)(acfg->stats.info_size * 100 / all_sizes),
9908 (int)acfg->stats.ex_info_size, (int)(acfg->stats.ex_info_size * 100 / all_sizes),
9909 (int)acfg->stats.unwind_info_size, (int)(acfg->stats.unwind_info_size * 100 / all_sizes),
9910 (int)acfg->stats.class_info_size, (int)(acfg->stats.class_info_size * 100 / all_sizes),
9911 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,
9912 (int)acfg->stats.got_info_size, (int)(acfg->stats.got_info_size * 100 / all_sizes),
9913 (int)acfg->stats.offsets_size, (int)(acfg->stats.offsets_size * 100 / all_sizes),
9914 (int)(acfg->got_offset * sizeof (gpointer)));
9915 aot_printf (acfg, "Compiled: %d/%d (%d%%)%s, No GOT slots: %d (%d%%), Direct calls: %d (%d%%)\n",
9916 acfg->stats.ccount, acfg->stats.mcount, acfg->stats.mcount ? (acfg->stats.ccount * 100) / acfg->stats.mcount : 100,
9918 acfg->stats.methods_without_got_slots, acfg->stats.mcount ? (acfg->stats.methods_without_got_slots * 100) / acfg->stats.mcount : 100,
9919 acfg->stats.direct_calls, acfg->stats.all_calls ? (acfg->stats.direct_calls * 100) / acfg->stats.all_calls : 100);
9920 if (acfg->stats.genericcount)
9921 aot_printf (acfg, "%d methods are generic (%d%%)\n", acfg->stats.genericcount, acfg->stats.mcount ? (acfg->stats.genericcount * 100) / acfg->stats.mcount : 100);
9922 if (acfg->stats.abscount)
9923 aot_printf (acfg, "%d methods contain absolute addresses (%d%%)\n", acfg->stats.abscount, acfg->stats.mcount ? (acfg->stats.abscount * 100) / acfg->stats.mcount : 100);
9924 if (acfg->stats.lmfcount)
9925 aot_printf (acfg, "%d methods contain lmf pointers (%d%%)\n", acfg->stats.lmfcount, acfg->stats.mcount ? (acfg->stats.lmfcount * 100) / acfg->stats.mcount : 100);
9926 if (acfg->stats.ocount)
9927 aot_printf (acfg, "%d methods have other problems (%d%%)\n", acfg->stats.ocount, acfg->stats.mcount ? (acfg->stats.ocount * 100) / acfg->stats.mcount : 100);
9930 res = mono_img_writer_emit_writeout (acfg->w);
9935 if (acfg->use_bin_writer) {
9936 int err = rename (tmp_outfile_name, outfile_name);
9939 aot_printf (acfg, "Unable to rename '%s' to '%s': %s\n", tmp_outfile_name, outfile_name, strerror (errno));
9943 res = compile_asm (acfg);
9950 acfg->stats.link_time = TV_ELAPSED (atv, btv);
9952 if (acfg->aot_opts.stats) {
9955 aot_printf (acfg, "GOT slot distribution:\n");
9956 for (i = 0; i < MONO_PATCH_INFO_NONE; ++i)
9957 if (acfg->stats.got_slot_types [i])
9958 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]);
9961 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);
9963 if (acfg->aot_opts.dump_json)
9976 mono_aot_readonly_field_override (MonoClassField *field)
9982 mono_compile_assembly (MonoAssembly *ass, guint32 opts, const char *aot_options)