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/reflection-internals.h>
44 #include <mono/metadata/marshal.h>
45 #include <mono/metadata/gc-internals.h>
46 #include <mono/metadata/mempool-internals.h>
47 #include <mono/metadata/mono-endian.h>
48 #include <mono/metadata/threads-types.h>
49 #include <mono/utils/mono-logger-internals.h>
50 #include <mono/utils/mono-compiler.h>
51 #include <mono/utils/mono-time.h>
52 #include <mono/utils/mono-mmap.h>
53 #include <mono/utils/json.h>
55 #include "aot-compiler.h"
56 #include "seq-points.h"
57 #include "image-writer.h"
58 #include "dwarfwriter.h"
60 #include "mini-llvm.h"
62 #if !defined(DISABLE_AOT) && !defined(DISABLE_JIT)
64 #if defined(__linux__) || defined(__native_client_codegen__)
65 #define RODATA_SECT ".rodata"
66 #elif defined(TARGET_MACH)
67 #define RODATA_SECT ".section __TEXT, __const"
69 #define RODATA_SECT ".text"
72 #define TV_DECLARE(name) gint64 name
73 #define TV_GETTIME(tv) tv = mono_100ns_ticks ()
74 #define TV_ELAPSED(start,end) (((end) - (start)) / 10)
76 #define ALIGN_TO(val,align) ((((guint64)val) + ((align) - 1)) & ~((align) - 1))
77 #define ALIGN_PTR_TO(ptr,align) (gpointer)((((gssize)(ptr)) + (align - 1)) & (~(align - 1)))
78 #define ROUND_DOWN(VALUE,SIZE) ((VALUE) & ~((SIZE) - 1))
80 /* predefined values for static readonly fields without needed to run the .cctor */
81 typedef struct _ReadOnlyValue ReadOnlyValue;
82 struct _ReadOnlyValue {
85 int type; /* to be used later for typechecking to prevent user errors */
94 static ReadOnlyValue *readonly_values;
96 typedef struct MonoAotOptions {
101 gboolean write_symbols;
102 gboolean metadata_only;
103 gboolean bind_to_runtime_version;
106 gboolean static_link;
110 gboolean dwarf_debug;
112 gboolean log_generics;
113 gboolean log_instances;
114 gboolean gen_seq_points_file;
115 char *gen_seq_points_file_path;
116 gboolean direct_pinvoke;
117 gboolean direct_icalls;
118 gboolean no_direct_calls;
119 gboolean use_trampolines_page;
120 gboolean no_instances;
126 int nrgctx_trampolines;
127 int nimt_trampolines;
128 int ngsharedvt_arg_trampolines;
129 int nrgctx_fetch_trampolines;
130 gboolean print_skipped_methods;
137 char *instances_logfile_path;
144 METHOD_CAT_GSHAREDVT,
150 typedef struct MonoAotStats {
151 int ccount, mcount, lmfcount, abscount, gcount, ocount, genericcount;
152 gint64 code_size, info_size, ex_info_size, unwind_info_size, got_size, class_info_size, got_info_size, plt_size;
153 int methods_without_got_slots, direct_calls, all_calls, llvm_count;
154 int got_slots, offsets_size;
155 int method_categories [METHOD_CAT_NUM];
156 int got_slot_types [MONO_PATCH_INFO_NUM];
157 int got_slot_info_sizes [MONO_PATCH_INFO_NUM];
158 int jit_time, gen_time, link_time;
161 typedef struct GotInfo {
162 GHashTable *patch_to_got_offset;
163 GHashTable **patch_to_got_offset_by_type;
164 GPtrArray *got_patches;
167 typedef struct MonoAotCompile {
170 GHashTable *method_indexes;
171 GHashTable *method_depth;
174 GHashTable **patch_to_plt_entry;
175 GHashTable *plt_offset_to_entry;
176 //GHashTable *patch_to_got_offset;
177 //GHashTable **patch_to_got_offset_by_type;
178 //GPtrArray *got_patches;
179 GotInfo got_info, llvm_got_info;
180 GHashTable *image_hash;
181 GHashTable *method_to_cfg;
182 GHashTable *token_info_hash;
183 GHashTable *method_to_pinvoke_import;
184 GPtrArray *extra_methods;
185 GPtrArray *image_table;
187 GPtrArray *method_order;
188 GHashTable *export_names;
189 /* Maps MonoClass* -> blob offset */
190 GHashTable *klass_blob_hash;
191 /* Maps MonoMethod* -> blob offset */
192 GHashTable *method_blob_hash;
193 GHashTable *gsharedvt_in_signatures;
194 GHashTable *gsharedvt_out_signatures;
195 guint32 *plt_got_info_offsets;
196 guint32 got_offset, llvm_got_offset, plt_offset, plt_got_offset_base, nshared_got_entries;
197 /* Number of GOT entries reserved for trampolines */
198 guint32 num_trampoline_got_entries;
199 guint32 tramp_page_size;
201 guint32 table_offsets [MONO_AOT_TABLE_NUM];
202 guint32 num_trampolines [MONO_AOT_TRAMP_NUM];
203 guint32 trampoline_got_offset_base [MONO_AOT_TRAMP_NUM];
204 guint32 trampoline_size [MONO_AOT_TRAMP_NUM];
205 guint32 tramp_page_code_offsets [MONO_AOT_TRAMP_NUM];
207 MonoAotOptions aot_opts;
211 MonoMemPool *mempool;
214 char *static_linking_symbol;
216 gboolean gas_line_numbers;
217 /* Whenever to emit an object file directly from llc */
218 gboolean llvm_owriter;
220 MonoDwarfWriter *dwarf;
227 GHashTable *unwind_info_offsets;
228 GPtrArray *unwind_ops;
229 guint32 unwind_info_offset;
232 char *llvm_got_symbol;
234 char *llvm_eh_frame_symbol;
235 GHashTable *method_label_hash;
236 const char *temp_prefix;
237 const char *user_symbol_prefix;
238 const char *llvm_label_prefix;
239 const char *inst_directive;
241 guint32 label_generator;
243 gboolean has_jitted_code;
244 MonoAotFileFlags flags;
245 MonoDynamicStream blob;
246 gboolean blob_closed;
247 MonoClass **typespec_classes;
250 char *assembly_name_sym;
251 GHashTable *plt_entry_debug_sym_cache;
252 gboolean thumb_mixed, need_no_dead_strip, need_pt_gnu_stack;
253 GHashTable *ginst_hash;
254 GHashTable *dwarf_ln_filenames;
255 gboolean global_symbols;
256 int objc_selector_index, objc_selector_index_2;
257 GPtrArray *objc_selectors;
258 GHashTable *objc_selector_to_index;
260 FILE *instances_logfile;
268 char *symbol, *llvm_symbol, *debug_sym;
270 gboolean jit_used, llvm_used;
273 #define mono_acfg_lock(acfg) mono_os_mutex_lock (&((acfg)->mutex))
274 #define mono_acfg_unlock(acfg) mono_os_mutex_unlock (&((acfg)->mutex))
276 /* This points to the current acfg in LLVM mode */
277 static MonoAotCompile *llvm_acfg;
279 #ifdef HAVE_ARRAY_ELEM_INIT
280 #define MSGSTRFIELD(line) MSGSTRFIELD1(line)
281 #define MSGSTRFIELD1(line) str##line
282 static const struct msgstr_t {
283 #define PATCH_INFO(a,b) char MSGSTRFIELD(__LINE__) [sizeof (b)];
284 #include "patch-info.h"
287 #define PATCH_INFO(a,b) b,
288 #include "patch-info.h"
291 static const gint16 opidx [] = {
292 #define PATCH_INFO(a,b) [MONO_PATCH_INFO_ ## a] = offsetof (struct msgstr_t, MSGSTRFIELD(__LINE__)),
293 #include "patch-info.h"
297 static G_GNUC_UNUSED const char*
298 get_patch_name (int info)
300 return (const char*)&opstr + opidx [info];
304 #define PATCH_INFO(a,b) b,
305 static const char* const
306 patch_types [MONO_PATCH_INFO_NUM + 1] = {
307 #include "patch-info.h"
311 static G_GNUC_UNUSED const char*
312 get_patch_name (int info)
314 return patch_types [info];
320 get_unwind_info_offset (MonoAotCompile *acfg, guint8 *encoded, guint32 encoded_len);
323 get_plt_entry_debug_sym (MonoAotCompile *acfg, MonoJumpInfo *ji, GHashTable *cache);
326 aot_printf (MonoAotCompile *acfg, const gchar *format, ...)
332 output = acfg->logfile;
336 va_start (args, format);
337 vfprintf (output, format, args);
342 aot_printerrf (MonoAotCompile *acfg, const gchar *format, ...)
348 output = acfg->logfile;
352 va_start (args, format);
353 vfprintf (output, format, args);
358 report_loader_error (MonoAotCompile *acfg, MonoError *error, const char *format, ...)
363 if (mono_error_ok (error))
367 output = acfg->logfile;
371 va_start (args, format);
372 vfprintf (output, format, args);
374 mono_error_cleanup (error);
376 g_error ("FullAOT cannot continue if there are loader errors");
379 /* Wrappers around the image writer functions */
382 emit_section_change (MonoAotCompile *acfg, const char *section_name, int subsection_index)
384 mono_img_writer_emit_section_change (acfg->w, section_name, subsection_index);
388 emit_local_symbol (MonoAotCompile *acfg, const char *name, const char *end_label, gboolean func)
390 mono_img_writer_emit_local_symbol (acfg->w, name, end_label, func);
394 emit_label (MonoAotCompile *acfg, const char *name)
396 mono_img_writer_emit_label (acfg->w, name);
400 emit_bytes (MonoAotCompile *acfg, const guint8* buf, int size)
402 mono_img_writer_emit_bytes (acfg->w, buf, size);
406 emit_string (MonoAotCompile *acfg, const char *value)
408 mono_img_writer_emit_string (acfg->w, value);
412 emit_line (MonoAotCompile *acfg)
414 mono_img_writer_emit_line (acfg->w);
418 emit_alignment (MonoAotCompile *acfg, int size)
420 mono_img_writer_emit_alignment (acfg->w, size);
424 emit_alignment_code (MonoAotCompile *acfg, int size)
426 if (acfg->align_pad_value)
427 mono_img_writer_emit_alignment_fill (acfg->w, size, acfg->align_pad_value);
429 mono_img_writer_emit_alignment (acfg->w, size);
433 emit_padding (MonoAotCompile *acfg, int size)
438 if (acfg->align_pad_value) {
439 for (i = 0; i < 16; ++i)
440 buf [i] = acfg->align_pad_value;
442 memset (buf, 0, sizeof (buf));
445 for (i = 0; i < size; i += 16) {
447 emit_bytes (acfg, buf, size - i);
449 emit_bytes (acfg, buf, 16);
454 emit_pointer (MonoAotCompile *acfg, const char *target)
456 mono_img_writer_emit_pointer (acfg->w, target);
460 emit_pointer_2 (MonoAotCompile *acfg, const char *prefix, const char *target)
462 if (prefix [0] != '\0') {
463 char *s = g_strdup_printf ("%s%s", prefix, target);
464 mono_img_writer_emit_pointer (acfg->w, s);
467 mono_img_writer_emit_pointer (acfg->w, target);
472 emit_int16 (MonoAotCompile *acfg, int value)
474 mono_img_writer_emit_int16 (acfg->w, value);
478 emit_int32 (MonoAotCompile *acfg, int value)
480 mono_img_writer_emit_int32 (acfg->w, value);
484 emit_symbol_diff (MonoAotCompile *acfg, const char *end, const char* start, int offset)
486 mono_img_writer_emit_symbol_diff (acfg->w, end, start, offset);
490 emit_zero_bytes (MonoAotCompile *acfg, int num)
492 mono_img_writer_emit_zero_bytes (acfg->w, num);
496 emit_byte (MonoAotCompile *acfg, guint8 val)
498 mono_img_writer_emit_byte (acfg->w, val);
501 #ifdef __native_client_codegen__
503 emit_nacl_call_alignment (MonoAotCompile *acfg)
505 mono_img_writer_emit_nacl_call_alignment (acfg->w);
509 static G_GNUC_UNUSED void
510 emit_global_inner (MonoAotCompile *acfg, const char *name, gboolean func)
512 mono_img_writer_emit_global (acfg->w, name, func);
516 emit_global (MonoAotCompile *acfg, const char *name, gboolean func)
518 if (acfg->aot_opts.no_dlsym) {
519 g_ptr_array_add (acfg->globals, g_strdup (name));
520 mono_img_writer_emit_local_symbol (acfg->w, name, NULL, func);
522 mono_img_writer_emit_global (acfg->w, name, func);
527 emit_symbol_size (MonoAotCompile *acfg, const char *name, const char *end_label)
529 mono_img_writer_emit_symbol_size (acfg->w, name, end_label);
532 /* Emit a symbol which is referenced by the MonoAotFileInfo structure */
534 emit_info_symbol (MonoAotCompile *acfg, const char *name)
539 emit_label (acfg, name);
540 /* LLVM generated code references this */
541 sprintf (symbol, "%s%s%s", acfg->user_symbol_prefix, acfg->global_prefix, name);
542 emit_label (acfg, symbol);
543 emit_global_inner (acfg, symbol, FALSE);
545 emit_label (acfg, name);
550 emit_string_symbol (MonoAotCompile *acfg, const char *name, const char *value)
553 mono_llvm_emit_aot_data (name, (guint8*)value, strlen (value) + 1);
557 mono_img_writer_emit_section_change (acfg->w, RODATA_SECT, 1);
559 /* On apple, all symbols need to be aligned to avoid warnings from ld */
560 emit_alignment (acfg, 4);
562 mono_img_writer_emit_label (acfg->w, name);
563 mono_img_writer_emit_string (acfg->w, value);
566 static G_GNUC_UNUSED void
567 emit_uleb128 (MonoAotCompile *acfg, guint32 value)
570 guint8 b = value & 0x7f;
572 if (value != 0) /* more bytes to come */
578 static G_GNUC_UNUSED void
579 emit_sleb128 (MonoAotCompile *acfg, gint64 value)
582 gboolean negative = (value < 0);
589 /* the following is unnecessary if the
590 * implementation of >>= uses an arithmetic rather
591 * than logical shift for a signed left operand
595 value |= - ((gint64)1 <<(size - 7));
596 /* sign bit of byte is second high order bit (0x40) */
597 if ((value == 0 && !(byte & 0x40)) ||
598 (value == -1 && (byte & 0x40)))
602 emit_byte (acfg, byte);
606 static G_GNUC_UNUSED void
607 encode_uleb128 (guint32 value, guint8 *buf, guint8 **endbuf)
612 guint8 b = value & 0x7f;
614 if (value != 0) /* more bytes to come */
622 static G_GNUC_UNUSED void
623 encode_sleb128 (gint32 value, guint8 *buf, guint8 **endbuf)
626 gboolean negative = (value < 0);
634 /* the following is unnecessary if the
635 * implementation of >>= uses an arithmetic rather
636 * than logical shift for a signed left operand
640 value |= - (1 <<(size - 7));
641 /* sign bit of byte is second high order bit (0x40) */
642 if ((value == 0 && !(byte & 0x40)) ||
643 (value == -1 && (byte & 0x40)))
654 encode_int (gint32 val, guint8 *buf, guint8 **endbuf)
657 buf [0] = (val >> 0) & 0xff;
658 buf [1] = (val >> 8) & 0xff;
659 buf [2] = (val >> 16) & 0xff;
660 buf [3] = (val >> 24) & 0xff;
666 encode_int16 (guint16 val, guint8 *buf, guint8 **endbuf)
668 buf [0] = (val >> 0) & 0xff;
669 buf [1] = (val >> 8) & 0xff;
675 encode_string (const char *s, guint8 *buf, guint8 **endbuf)
677 int len = strlen (s);
679 memcpy (buf, s, len + 1);
680 *endbuf = buf + len + 1;
684 emit_unset_mode (MonoAotCompile *acfg)
686 mono_img_writer_emit_unset_mode (acfg->w);
689 static G_GNUC_UNUSED void
690 emit_set_thumb_mode (MonoAotCompile *acfg)
692 emit_unset_mode (acfg);
693 fprintf (acfg->fp, ".code 16\n");
696 static G_GNUC_UNUSED void
697 emit_set_arm_mode (MonoAotCompile *acfg)
699 emit_unset_mode (acfg);
700 fprintf (acfg->fp, ".code 32\n");
704 emit_code_bytes (MonoAotCompile *acfg, const guint8* buf, int size)
709 g_assert (size % 4 == 0);
710 emit_unset_mode (acfg);
711 for (i = 0; i < size; i += 4)
712 fprintf (acfg->fp, "%s 0x%x\n", acfg->inst_directive, *(guint32*)(buf + i));
714 emit_bytes (acfg, buf, size);
718 /* ARCHITECTURE SPECIFIC CODE */
720 #if defined(TARGET_X86) || defined(TARGET_AMD64) || defined(TARGET_ARM) || defined(TARGET_POWERPC) || defined(TARGET_ARM64)
721 #define EMIT_DWARF_INFO 1
724 #if defined(TARGET_ARM)
725 #define AOT_FUNC_ALIGNMENT 4
727 #define AOT_FUNC_ALIGNMENT 16
729 #if (defined(TARGET_X86) || defined(TARGET_AMD64)) && defined(__native_client_codegen__)
730 #undef AOT_FUNC_ALIGNMENT
731 #define AOT_FUNC_ALIGNMENT 32
734 #if defined(TARGET_POWERPC64) && !defined(__mono_ilp32__)
735 #define PPC_LD_OP "ld"
736 #define PPC_LDX_OP "ldx"
738 #define PPC_LD_OP "lwz"
739 #define PPC_LDX_OP "lwzx"
743 #define AOT_TARGET_STR "AMD64"
748 #define AOT_TARGET_STR "ARM (MACH)"
750 #define AOT_TARGET_STR "ARM (!MACH)"
756 #define AOT_TARGET_STR "ARM64 (MACH)"
758 #define AOT_TARGET_STR "ARM64 (!MACH)"
762 #ifdef TARGET_POWERPC64
763 #ifdef __mono_ilp32__
764 #define AOT_TARGET_STR "POWERPC64 (mono ilp32)"
766 #define AOT_TARGET_STR "POWERPC64 (!mono ilp32)"
769 #ifdef TARGET_POWERPC
770 #ifdef __mono_ilp32__
771 #define AOT_TARGET_STR "POWERPC (mono ilp32)"
773 #define AOT_TARGET_STR "POWERPC (!mono ilp32)"
780 #define AOT_TARGET_STR "X86 (WIN32)"
781 #elif defined(__native_client_codegen__)
782 #define AOT_TARGET_STR "X86 (native client codegen)"
784 #define AOT_TARGET_STR "X86 (!native client codegen)"
788 #ifndef AOT_TARGET_STR
789 #define AOT_TARGET_STR ""
793 arch_init (MonoAotCompile *acfg)
795 acfg->llc_args = g_string_new ("");
796 acfg->as_args = g_string_new ("");
799 * The prefix LLVM likes to put in front of symbol names on darwin.
800 * The mach-os specs require this for globals, but LLVM puts them in front of all
801 * symbols. We need to handle this, since we need to refer to LLVM generated
804 acfg->llvm_label_prefix = "";
805 acfg->user_symbol_prefix = "";
807 #if defined(TARGET_X86)
808 g_string_append (acfg->llc_args, " -march=x86 -mattr=sse4.1");
811 #if defined(TARGET_AMD64)
812 g_string_append (acfg->llc_args, " -march=x86-64 -mattr=sse4.1");
814 acfg->align_pad_value = 0x90;
818 if (acfg->aot_opts.mtriple && strstr (acfg->aot_opts.mtriple, "darwin")) {
819 g_string_append (acfg->llc_args, "-mattr=+v6");
822 g_string_append (acfg->llc_args, " -mattr=+vfp2,-neon,+d16");
823 g_string_append (acfg->as_args, " -mfpu=vfp3");
825 g_string_append (acfg->llc_args, " -soft-float");
828 if (acfg->aot_opts.mtriple && strstr (acfg->aot_opts.mtriple, "thumb"))
829 acfg->thumb_mixed = TRUE;
831 if (acfg->aot_opts.mtriple)
832 mono_arch_set_target (acfg->aot_opts.mtriple);
836 acfg->inst_directive = ".inst";
837 if (acfg->aot_opts.mtriple)
838 mono_arch_set_target (acfg->aot_opts.mtriple);
842 acfg->user_symbol_prefix = "_";
843 acfg->llvm_label_prefix = "_";
844 acfg->inst_directive = ".word";
845 acfg->need_no_dead_strip = TRUE;
846 acfg->aot_opts.gnu_asm = TRUE;
849 #if defined(__linux__) && !defined(TARGET_ARM)
850 acfg->need_pt_gnu_stack = TRUE;
854 acfg->global_symbols = TRUE;
861 /* Load the contents of GOT_SLOT into dreg, clobbering ip0 */
863 arm64_emit_load_got_slot (MonoAotCompile *acfg, int dreg, int got_slot)
868 emit_unset_mode (acfg);
870 offset = (int)(got_slot * sizeof (gpointer));
872 /* clang's integrated assembler */
873 fprintf (acfg->fp, "adrp x16, %s@PAGE+%d\n", acfg->got_symbol, offset & 0xfffff000);
874 fprintf (acfg->fp, "add x16, x16, %s@PAGEOFF\n", acfg->got_symbol);
875 fprintf (acfg->fp, "ldr x%d, [x16, #%d]\n", dreg, offset & 0xfff);
878 fprintf (acfg->fp, "adrp x16, %s+%d\n", acfg->got_symbol, offset & 0xfffff000);
879 fprintf (acfg->fp, "add x16, x16, :lo12:%s\n", acfg->got_symbol);
880 fprintf (acfg->fp, "ldr x%d, [x16, %d]\n", dreg, offset & 0xfff);
885 arm64_emit_objc_selector_ref (MonoAotCompile *acfg, guint8 *code, int index, int *code_size)
890 emit_unset_mode (acfg);
893 reg = arm_get_ldr_lit_reg (code);
895 fprintf (acfg->fp, "adrp x%d, L_OBJC_SELECTOR_REFERENCES_%d@PAGE\n", reg, index);
896 fprintf (acfg->fp, "add x%d, x%d, L_OBJC_SELECTOR_REFERENCES_%d@PAGEOFF\n", reg, reg, index);
897 fprintf (acfg->fp, "ldr x%d, [x%d]\n", reg, reg);
903 arm64_emit_direct_call (MonoAotCompile *acfg, const char *target, gboolean external, gboolean thumb, MonoJumpInfo *ji, int *call_size)
906 emit_unset_mode (acfg);
907 if (ji && ji->relocation == MONO_R_ARM64_B) {
908 fprintf (acfg->fp, "b %s\n", target);
911 g_assert (ji->relocation == MONO_R_ARM64_BL);
912 fprintf (acfg->fp, "bl %s\n", target);
918 arm64_emit_got_access (MonoAotCompile *acfg, guint8 *code, int got_slot, int *code_size)
923 reg = arm_get_ldr_lit_reg (code);
924 arm64_emit_load_got_slot (acfg, reg, got_slot);
929 arm64_emit_plt_entry (MonoAotCompile *acfg, const char *got_symbol, int offset, int info_offset)
931 arm64_emit_load_got_slot (acfg, ARMREG_R16, offset / sizeof (gpointer));
932 fprintf (acfg->fp, "br x16\n");
933 /* Used by mono_aot_get_plt_info_offset () */
934 fprintf (acfg->fp, "%s %d\n", acfg->inst_directive, info_offset);
938 arm64_emit_tramp_page_common_code (MonoAotCompile *acfg, int pagesize, int arg_reg, int *size)
944 /* The common code */
947 /* The trampoline address is in IP0 */
948 arm_movzx (code, ARMREG_IP1, imm & 0xffff, 0);
949 arm_movkx (code, ARMREG_IP1, (imm >> 16) & 0xffff, 16);
950 /* Compute the data slot address */
951 arm_subx (code, ARMREG_IP0, ARMREG_IP0, ARMREG_IP1);
952 /* Trampoline argument */
953 arm_ldrx (code, arg_reg, ARMREG_IP0, 0);
955 arm_ldrx (code, ARMREG_IP0, ARMREG_IP0, 8);
956 arm_brx (code, ARMREG_IP0);
959 emit_code_bytes (acfg, buf, code - buf);
965 arm64_emit_tramp_page_specific_code (MonoAotCompile *acfg, int pagesize, int common_tramp_size, int specific_tramp_size)
971 count = (pagesize - common_tramp_size) / specific_tramp_size;
972 for (i = 0; i < count; ++i) {
974 arm_adrx (code, ARMREG_IP0, code);
975 /* Branch to the generic code */
976 arm_b (code, code - 4 - (i * specific_tramp_size) - common_tramp_size);
977 /* This has to be 2 pointers long */
980 g_assert (code - buf == specific_tramp_size);
981 emit_code_bytes (acfg, buf, code - buf);
986 arm64_emit_specific_trampoline_pages (MonoAotCompile *acfg)
991 int common_tramp_size;
992 int specific_tramp_size = 2 * 8;
996 if (!acfg->aot_opts.use_trampolines_page)
1000 /* Have to match the target pagesize */
1003 pagesize = mono_pagesize ();
1005 acfg->tramp_page_size = pagesize;
1007 /* The specific trampolines */
1008 sprintf (symbol, "%sspecific_trampolines_page", acfg->user_symbol_prefix);
1009 emit_alignment (acfg, pagesize);
1010 emit_global (acfg, symbol, TRUE);
1011 emit_label (acfg, symbol);
1013 /* The common code */
1014 arm64_emit_tramp_page_common_code (acfg, pagesize, ARMREG_IP1, &common_tramp_size);
1015 acfg->tramp_page_code_offsets [MONO_AOT_TRAMP_SPECIFIC] = common_tramp_size;
1017 arm64_emit_tramp_page_specific_code (acfg, pagesize, common_tramp_size, specific_tramp_size);
1019 /* The rgctx trampolines */
1020 /* These are the same as the specific trampolines, but they load the argument into MONO_ARCH_RGCTX_REG */
1021 sprintf (symbol, "%srgctx_trampolines_page", acfg->user_symbol_prefix);
1022 emit_alignment (acfg, pagesize);
1023 emit_global (acfg, symbol, TRUE);
1024 emit_label (acfg, symbol);
1026 /* The common code */
1027 arm64_emit_tramp_page_common_code (acfg, pagesize, MONO_ARCH_RGCTX_REG, &common_tramp_size);
1028 acfg->tramp_page_code_offsets [MONO_AOT_TRAMP_STATIC_RGCTX] = common_tramp_size;
1030 arm64_emit_tramp_page_specific_code (acfg, pagesize, common_tramp_size, specific_tramp_size);
1032 /* The gsharedvt arg trampolines */
1033 /* These are the same as the specific trampolines */
1034 sprintf (symbol, "%sgsharedvt_arg_trampolines_page", acfg->user_symbol_prefix);
1035 emit_alignment (acfg, pagesize);
1036 emit_global (acfg, symbol, TRUE);
1037 emit_label (acfg, symbol);
1039 arm64_emit_tramp_page_common_code (acfg, pagesize, ARMREG_IP1, &common_tramp_size);
1040 acfg->tramp_page_code_offsets [MONO_AOT_TRAMP_GSHAREDVT_ARG] = common_tramp_size;
1042 arm64_emit_tramp_page_specific_code (acfg, pagesize, common_tramp_size, specific_tramp_size);
1044 /* The IMT trampolines */
1045 sprintf (symbol, "%simt_trampolines_page", acfg->user_symbol_prefix);
1046 emit_alignment (acfg, pagesize);
1047 emit_global (acfg, symbol, TRUE);
1048 emit_label (acfg, symbol);
1052 /* The trampoline address is in IP0 */
1053 arm_movzx (code, ARMREG_IP1, imm & 0xffff, 0);
1054 arm_movkx (code, ARMREG_IP1, (imm >> 16) & 0xffff, 16);
1055 /* Compute the data slot address */
1056 arm_subx (code, ARMREG_IP0, ARMREG_IP0, ARMREG_IP1);
1057 /* Trampoline argument */
1058 arm_ldrx (code, ARMREG_IP1, ARMREG_IP0, 0);
1060 /* Same as arch_emit_imt_thunk () */
1062 arm_ldrx (code, ARMREG_IP0, ARMREG_IP1, 0);
1063 arm_cmpx (code, ARMREG_IP0, MONO_ARCH_RGCTX_REG);
1065 arm_bcc (code, ARMCOND_EQ, 0);
1067 /* End-of-loop check */
1069 arm_cbzx (code, ARMREG_IP0, 0);
1072 arm_addx_imm (code, ARMREG_IP1, ARMREG_IP1, 2 * 8);
1073 arm_b (code, labels [0]);
1076 mono_arm_patch (labels [1], code, MONO_R_ARM64_BCC);
1077 /* Load vtable slot addr */
1078 arm_ldrx (code, ARMREG_IP0, ARMREG_IP1, 8);
1079 /* Load vtable slot */
1080 arm_ldrx (code, ARMREG_IP0, ARMREG_IP0, 0);
1081 arm_brx (code, ARMREG_IP0);
1084 mono_arm_patch (labels [2], code, MONO_R_ARM64_CBZ);
1085 /* Load fail addr */
1086 arm_ldrx (code, ARMREG_IP0, ARMREG_IP1, 8);
1087 arm_brx (code, ARMREG_IP0);
1089 emit_code_bytes (acfg, buf, code - buf);
1091 common_tramp_size = code - buf;
1092 acfg->tramp_page_code_offsets [MONO_AOT_TRAMP_IMT_THUNK] = common_tramp_size;
1094 arm64_emit_tramp_page_specific_code (acfg, pagesize, common_tramp_size, specific_tramp_size);
1098 arm64_emit_specific_trampoline (MonoAotCompile *acfg, int offset, int *tramp_size)
1100 /* Load argument from second GOT slot */
1101 arm64_emit_load_got_slot (acfg, ARMREG_R17, offset + 1);
1102 /* Load generic trampoline address from first GOT slot */
1103 arm64_emit_load_got_slot (acfg, ARMREG_R16, offset);
1104 fprintf (acfg->fp, "br x16\n");
1105 *tramp_size = 7 * 4;
1109 arm64_emit_unbox_trampoline (MonoAotCompile *acfg, MonoCompile *cfg, MonoMethod *method, const char *call_target)
1111 emit_unset_mode (acfg);
1112 fprintf (acfg->fp, "add x0, x0, %d\n", (int)(sizeof (MonoObject)));
1113 fprintf (acfg->fp, "b %s\n", call_target);
1117 arm64_emit_static_rgctx_trampoline (MonoAotCompile *acfg, int offset, int *tramp_size)
1119 /* Similar to the specific trampolines, but use the rgctx reg instead of ip1 */
1121 /* Load argument from first GOT slot */
1122 g_assert (MONO_ARCH_RGCTX_REG == 27);
1123 arm64_emit_load_got_slot (acfg, ARMREG_R27, offset);
1124 /* Load generic trampoline address from second GOT slot */
1125 arm64_emit_load_got_slot (acfg, ARMREG_R16, offset + 1);
1126 fprintf (acfg->fp, "br x16\n");
1127 *tramp_size = 7 * 4;
1131 arm64_emit_imt_thunk (MonoAotCompile *acfg, int offset, int *tramp_size)
1134 guint8 *code, *labels [16];
1136 /* Load parameter from GOT slot into ip1 */
1137 arm64_emit_load_got_slot (acfg, ARMREG_R17, offset);
1141 arm_ldrx (code, ARMREG_IP0, ARMREG_IP1, 0);
1142 arm_cmpx (code, ARMREG_IP0, MONO_ARCH_RGCTX_REG);
1144 arm_bcc (code, ARMCOND_EQ, 0);
1146 /* End-of-loop check */
1148 arm_cbzx (code, ARMREG_IP0, 0);
1151 arm_addx_imm (code, ARMREG_IP1, ARMREG_IP1, 2 * 8);
1152 arm_b (code, labels [0]);
1155 mono_arm_patch (labels [1], code, MONO_R_ARM64_BCC);
1156 /* Load vtable slot addr */
1157 arm_ldrx (code, ARMREG_IP0, ARMREG_IP1, 8);
1158 /* Load vtable slot */
1159 arm_ldrx (code, ARMREG_IP0, ARMREG_IP0, 0);
1160 arm_brx (code, ARMREG_IP0);
1163 mono_arm_patch (labels [2], code, MONO_R_ARM64_CBZ);
1164 /* Load fail addr */
1165 arm_ldrx (code, ARMREG_IP0, ARMREG_IP1, 8);
1166 arm_brx (code, ARMREG_IP0);
1168 emit_code_bytes (acfg, buf, code - buf);
1170 *tramp_size = code - buf + (3 * 4);
1174 arm64_emit_gsharedvt_arg_trampoline (MonoAotCompile *acfg, int offset, int *tramp_size)
1176 /* Similar to the specific trampolines, but the address is in the second slot */
1177 /* Load argument from first GOT slot */
1178 arm64_emit_load_got_slot (acfg, ARMREG_R17, offset);
1179 /* Load generic trampoline address from second GOT slot */
1180 arm64_emit_load_got_slot (acfg, ARMREG_R16, offset + 1);
1181 fprintf (acfg->fp, "br x16\n");
1182 *tramp_size = 7 * 4;
1188 #ifdef MONO_ARCH_AOT_SUPPORTED
1190 * arch_emit_direct_call:
1192 * Emit a direct call to the symbol TARGET. CALL_SIZE is set to the size of the
1196 arch_emit_direct_call (MonoAotCompile *acfg, const char *target, gboolean external, gboolean thumb, MonoJumpInfo *ji, int *call_size)
1198 #if defined(TARGET_X86) || defined(TARGET_AMD64)
1199 /* Need to make sure this is exactly 5 bytes long */
1200 emit_unset_mode (acfg);
1201 fprintf (acfg->fp, "call %s\n", target);
1203 #elif defined(TARGET_ARM)
1204 emit_unset_mode (acfg);
1206 fprintf (acfg->fp, "blx %s\n", target);
1208 fprintf (acfg->fp, "bl %s\n", target);
1210 #elif defined(TARGET_ARM64)
1211 arm64_emit_direct_call (acfg, target, external, thumb, ji, call_size);
1212 #elif defined(TARGET_POWERPC)
1213 emit_unset_mode (acfg);
1214 fprintf (acfg->fp, "bl %s\n", target);
1217 g_assert_not_reached ();
1224 * - we use an approach similar to the x86 abi: reserve a register (r30) to hold
1226 * - The full-aot trampolines need access to the GOT of mscorlib, so we store
1227 * in in the 2. slot of every GOT, and require every method to place the GOT
1228 * address in r30, even when it doesn't access the GOT otherwise. This way,
1229 * the trampolines can compute the mscorlib GOT address by loading 4(r30).
1234 * PPC64 uses function descriptors which greatly complicate all code, since
1235 * these are used very inconsistently in the runtime. Some functions like
1236 * mono_compile_method () return ftn descriptors, while others like the
1237 * trampoline creation functions do not.
1238 * We assume that all GOT slots contain function descriptors, and create
1239 * descriptors in aot-runtime.c when needed.
1240 * The ppc64 abi uses r2 to hold the address of the TOC/GOT, which is loaded
1241 * from function descriptors, we could do the same, but it would require
1242 * rewriting all the ppc/aot code to handle function descriptors properly.
1243 * So instead, we use the same approach as on PPC32.
1244 * This is a horrible mess, but fixing it would probably lead to an even bigger
1250 * - similar to the PPC32 design, we reserve EBX to hold the GOT pointer.
1253 #ifdef MONO_ARCH_AOT_SUPPORTED
1255 * arch_emit_got_offset:
1257 * The memory pointed to by CODE should hold native code for computing the GOT
1258 * address (OP_LOAD_GOTADDR). Emit this code while patching it with the offset
1259 * between code and the GOT. CODE_SIZE is set to the number of bytes emitted.
1262 arch_emit_got_offset (MonoAotCompile *acfg, guint8 *code, int *code_size)
1264 #if defined(TARGET_POWERPC64)
1265 emit_unset_mode (acfg);
1267 * The ppc32 code doesn't seem to work on ppc64, the assembler complains about
1268 * unsupported relocations. So we store the got address into the .Lgot_addr
1269 * symbol which is in the text segment, compute its address, and load it.
1271 fprintf (acfg->fp, ".L%d:\n", acfg->label_generator);
1272 fprintf (acfg->fp, "lis 0, (.Lgot_addr + 4 - .L%d)@h\n", acfg->label_generator);
1273 fprintf (acfg->fp, "ori 0, 0, (.Lgot_addr + 4 - .L%d)@l\n", acfg->label_generator);
1274 fprintf (acfg->fp, "add 30, 30, 0\n");
1275 fprintf (acfg->fp, "%s 30, 0(30)\n", PPC_LD_OP);
1276 acfg->label_generator ++;
1278 #elif defined(TARGET_POWERPC)
1279 emit_unset_mode (acfg);
1280 fprintf (acfg->fp, ".L%d:\n", acfg->label_generator);
1281 fprintf (acfg->fp, "lis 0, (%s + 4 - .L%d)@h\n", acfg->got_symbol, acfg->label_generator);
1282 fprintf (acfg->fp, "ori 0, 0, (%s + 4 - .L%d)@l\n", acfg->got_symbol, acfg->label_generator);
1283 acfg->label_generator ++;
1286 guint32 offset = mono_arch_get_patch_offset (code);
1287 emit_bytes (acfg, code, offset);
1288 emit_symbol_diff (acfg, acfg->got_symbol, ".", offset);
1290 *code_size = offset + 4;
1295 * arch_emit_got_access:
1297 * The memory pointed to by CODE should hold native code for loading a GOT
1298 * slot (OP_AOTCONST/OP_GOT_ENTRY). Emit this code while patching it so it accesses the
1299 * GOT slot GOT_SLOT. CODE_SIZE is set to the number of bytes emitted.
1302 arch_emit_got_access (MonoAotCompile *acfg, const char *got_symbol, guint8 *code, int got_slot, int *code_size)
1305 /* mov reg, got+offset(%rip) */
1307 /* The GOT symbol is in the LLVM module, the clang assembler has problems emitting symbol diffs for it */
1311 /* Decode reg, see amd64_mov_reg_membase () */
1312 rex_r = code [0] & AMD64_REX_R;
1313 g_assert (code [0] == 0x49 + rex_r);
1314 g_assert (code [1] == 0x8b);
1315 dreg = ((code [2] >> 3) & 0x7) + (rex_r ? 8 : 0);
1317 emit_unset_mode (acfg);
1318 fprintf (acfg->fp, "mov %s+%d(%%rip), %s\n", got_symbol, (unsigned int) ((got_slot * sizeof (gpointer))), mono_arch_regname (dreg));
1321 emit_bytes (acfg, code, mono_arch_get_patch_offset (code));
1322 emit_symbol_diff (acfg, got_symbol, ".", (unsigned int) ((got_slot * sizeof (gpointer)) - 4));
1323 *code_size = mono_arch_get_patch_offset (code) + 4;
1325 #elif defined(TARGET_X86)
1326 emit_bytes (acfg, code, mono_arch_get_patch_offset (code));
1327 emit_int32 (acfg, (unsigned int) ((got_slot * sizeof (gpointer))));
1328 *code_size = mono_arch_get_patch_offset (code) + 4;
1329 #elif defined(TARGET_ARM)
1330 emit_bytes (acfg, code, mono_arch_get_patch_offset (code));
1331 emit_symbol_diff (acfg, got_symbol, ".", (unsigned int) ((got_slot * sizeof (gpointer))) - 12);
1332 *code_size = mono_arch_get_patch_offset (code) + 4;
1333 #elif defined(TARGET_ARM64)
1334 emit_bytes (acfg, code, mono_arch_get_patch_offset (code));
1335 arm64_emit_got_access (acfg, code, got_slot, code_size);
1336 #elif defined(TARGET_POWERPC)
1341 emit_bytes (acfg, code, mono_arch_get_patch_offset (code));
1343 ppc_load32 (code, ppc_r0, got_slot * sizeof (gpointer));
1344 g_assert (code - buf == 8);
1345 emit_bytes (acfg, buf, code - buf);
1346 *code_size = code - buf;
1349 g_assert_not_reached ();
1355 #ifdef MONO_ARCH_AOT_SUPPORTED
1357 * arch_emit_objc_selector_ref:
1359 * Emit the implementation of OP_OBJC_GET_SELECTOR, which itself implements @selector(foo:) in objective-c.
1362 arch_emit_objc_selector_ref (MonoAotCompile *acfg, guint8 *code, int index, int *code_size)
1364 #if defined(TARGET_ARM)
1367 int lindex = acfg->objc_selector_index_2 ++;
1369 /* Emit ldr.imm/b */
1370 emit_bytes (acfg, code, 8);
1372 sprintf (symbol1, "L_OBJC_SELECTOR_%d", lindex);
1373 sprintf (symbol2, "L_OBJC_SELECTOR_REFERENCES_%d", index);
1375 emit_label (acfg, symbol1);
1376 mono_img_writer_emit_unset_mode (acfg->w);
1377 fprintf (acfg->fp, ".long %s-(%s+12)", symbol2, symbol1);
1380 #elif defined(TARGET_ARM64)
1381 arm64_emit_objc_selector_ref (acfg, code, index, code_size);
1383 g_assert_not_reached ();
1389 * arch_emit_plt_entry:
1391 * Emit code for the PLT entry.
1392 * The plt entry should look like this:
1393 * <indirect jump to GOT_SYMBOL + OFFSET>
1394 * <INFO_OFFSET embedded into the instruction stream>
1397 arch_emit_plt_entry (MonoAotCompile *acfg, const char *got_symbol, int offset, int info_offset)
1399 #if defined(TARGET_X86)
1400 #if defined(__default_codegen__)
1401 /* jmp *<offset>(%ebx) */
1402 emit_byte (acfg, 0xff);
1403 emit_byte (acfg, 0xa3);
1404 emit_int32 (acfg, offset);
1405 /* Used by mono_aot_get_plt_info_offset */
1406 emit_int32 (acfg, info_offset);
1407 #elif defined(__native_client_codegen__)
1408 const guint8 kSizeOfNaClJmp = 11;
1409 guint8 bytes[kSizeOfNaClJmp];
1410 guint8 *pbytes = &bytes[0];
1412 x86_jump_membase32 (pbytes, X86_EBX, offset);
1413 emit_bytes (acfg, bytes, kSizeOfNaClJmp);
1414 /* four bytes of data, used by mono_arch_patch_plt_entry */
1415 /* For Native Client, make this work with data embedded in push. */
1416 emit_byte (acfg, 0x68); /* hide data in a push */
1417 emit_int32 (acfg, info_offset);
1418 emit_alignment (acfg, AOT_FUNC_ALIGNMENT);
1419 #endif /*__native_client_codegen__*/
1420 #elif defined(TARGET_AMD64)
1421 #if defined(__default_codegen__)
1422 emit_unset_mode (acfg);
1423 fprintf (acfg->fp, "jmp *%s+%d(%%rip)\n", got_symbol, offset);
1424 /* Used by mono_aot_get_plt_info_offset */
1425 emit_int32 (acfg, info_offset);
1426 acfg->stats.plt_size += 10;
1427 #elif defined(__native_client_codegen__)
1429 guint8 *buf_aligned = ALIGN_TO(buf, kNaClAlignment);
1430 guint8 *code = buf_aligned;
1432 /* mov <OFFSET>(%rip), %r11d */
1433 emit_byte (acfg, '\x45');
1434 emit_byte (acfg, '\x8b');
1435 emit_byte (acfg, '\x1d');
1436 emit_symbol_diff (acfg, got_symbol, ".", offset - 4);
1438 amd64_jump_reg (code, AMD64_R11);
1439 /* This should be constant for the plt patch */
1440 g_assert ((size_t)(code-buf_aligned) == 10);
1441 emit_bytes (acfg, buf_aligned, code - buf_aligned);
1443 /* Hide data in a push imm32 so it passes validation */
1444 emit_byte (acfg, 0x68); /* push */
1445 emit_int32 (acfg, info_offset);
1446 emit_alignment (acfg, AOT_FUNC_ALIGNMENT);
1447 #endif /*__native_client_codegen__*/
1448 #elif defined(TARGET_ARM)
1453 ARM_LDR_IMM (code, ARMREG_IP, ARMREG_PC, 0);
1454 ARM_LDR_REG_REG (code, ARMREG_PC, ARMREG_PC, ARMREG_IP);
1455 emit_bytes (acfg, buf, code - buf);
1456 emit_symbol_diff (acfg, got_symbol, ".", offset - 4);
1457 /* Used by mono_aot_get_plt_info_offset */
1458 emit_int32 (acfg, info_offset);
1459 #elif defined(TARGET_ARM64)
1460 arm64_emit_plt_entry (acfg, got_symbol, offset, info_offset);
1461 #elif defined(TARGET_POWERPC)
1462 /* The GOT address is guaranteed to be in r30 by OP_LOAD_GOTADDR */
1463 emit_unset_mode (acfg);
1464 fprintf (acfg->fp, "lis 11, %d@h\n", offset);
1465 fprintf (acfg->fp, "ori 11, 11, %d@l\n", offset);
1466 fprintf (acfg->fp, "add 11, 11, 30\n");
1467 fprintf (acfg->fp, "%s 11, 0(11)\n", PPC_LD_OP);
1468 #ifdef PPC_USES_FUNCTION_DESCRIPTOR
1469 fprintf (acfg->fp, "%s 2, %d(11)\n", PPC_LD_OP, (int)sizeof (gpointer));
1470 fprintf (acfg->fp, "%s 11, 0(11)\n", PPC_LD_OP);
1472 fprintf (acfg->fp, "mtctr 11\n");
1473 fprintf (acfg->fp, "bctr\n");
1474 emit_int32 (acfg, info_offset);
1476 g_assert_not_reached ();
1481 * arch_emit_llvm_plt_entry:
1483 * Same as arch_emit_plt_entry, but handles calls from LLVM generated code.
1484 * This is only needed on arm to handle thumb interop.
1487 arch_emit_llvm_plt_entry (MonoAotCompile *acfg, const char *got_symbol, int offset, int info_offset)
1489 #if defined(TARGET_ARM)
1490 /* LLVM calls the PLT entries using bl, so these have to be thumb2 */
1491 /* The caller already transitioned to thumb */
1492 /* The code below should be 12 bytes long */
1493 /* clang has trouble encoding these instructions, so emit the binary */
1495 fprintf (acfg->fp, "ldr ip, [pc, #8]\n");
1496 /* thumb can't encode ld pc, [pc, ip] */
1497 fprintf (acfg->fp, "add ip, pc, ip\n");
1498 fprintf (acfg->fp, "ldr ip, [ip, #0]\n");
1499 fprintf (acfg->fp, "bx ip\n");
1501 emit_set_thumb_mode (acfg);
1502 fprintf (acfg->fp, ".4byte 0xc008f8df\n");
1503 fprintf (acfg->fp, ".2byte 0x44fc\n");
1504 fprintf (acfg->fp, ".4byte 0xc000f8dc\n");
1505 fprintf (acfg->fp, ".2byte 0x4760\n");
1506 emit_symbol_diff (acfg, got_symbol, ".", offset + 4);
1507 emit_int32 (acfg, info_offset);
1508 emit_unset_mode (acfg);
1509 emit_set_arm_mode (acfg);
1511 g_assert_not_reached ();
1515 /* Save unwind_info in the module and emit the offset to the information at symbol */
1516 static void save_unwind_info (MonoAotCompile *acfg, char *symbol, GSList *unwind_ops)
1518 guint32 uw_offset, encoded_len;
1521 emit_section_change (acfg, RODATA_SECT, 0);
1522 emit_global (acfg, symbol, FALSE);
1523 emit_label (acfg, symbol);
1525 encoded = mono_unwind_ops_encode (unwind_ops, &encoded_len);
1526 uw_offset = get_unwind_info_offset (acfg, encoded, encoded_len);
1528 emit_int32 (acfg, uw_offset);
1532 * arch_emit_specific_trampoline_pages:
1534 * Emits a page full of trampolines: each trampoline uses its own address to
1535 * lookup both the generic trampoline code and the data argument.
1536 * This page can be remapped in process multiple times so we can get an
1537 * unlimited number of trampolines.
1538 * Specifically this implementation uses the following trick: two memory pages
1539 * are allocated, with the first containing the data and the second containing the trampolines.
1540 * To reduce trampoline size, each trampoline jumps at the start of the page where a common
1541 * implementation does all the lifting.
1542 * Note that the ARM single trampoline size is 8 bytes, exactly like the data that needs to be stored
1543 * on the arm 32 bit system.
1546 arch_emit_specific_trampoline_pages (MonoAotCompile *acfg)
1548 #if defined(TARGET_ARM)
1551 guint8 *loop_start, *loop_branch_back, *loop_end_check, *imt_found_check;
1553 int pagesize = MONO_AOT_TRAMP_PAGE_SIZE;
1554 GSList *unwind_ops = NULL;
1555 #define COMMON_TRAMP_SIZE 16
1556 int count = (pagesize - COMMON_TRAMP_SIZE) / 8;
1557 int imm8, rot_amount;
1560 if (!acfg->aot_opts.use_trampolines_page)
1563 acfg->tramp_page_size = pagesize;
1565 sprintf (symbol, "%sspecific_trampolines_page", acfg->user_symbol_prefix);
1566 emit_alignment (acfg, pagesize);
1567 emit_global (acfg, symbol, TRUE);
1568 emit_label (acfg, symbol);
1570 /* emit the generic code first, the trampoline address + 8 is in the lr register */
1572 imm8 = mono_arm_is_rotated_imm8 (pagesize, &rot_amount);
1573 ARM_SUB_REG_IMM (code, ARMREG_LR, ARMREG_LR, imm8, rot_amount);
1574 ARM_LDR_IMM (code, ARMREG_R1, ARMREG_LR, -8);
1575 ARM_LDR_IMM (code, ARMREG_PC, ARMREG_LR, -4);
1577 g_assert (code - buf == COMMON_TRAMP_SIZE);
1580 emit_bytes (acfg, buf, code - buf);
1582 for (i = 0; i < count; ++i) {
1584 ARM_PUSH (code, 0x5fff);
1586 arm_patch (code - 4, code - COMMON_TRAMP_SIZE - 8 * (i + 1));
1587 g_assert (code - buf == 8);
1588 emit_bytes (acfg, buf, code - buf);
1591 /* now the rgctx trampolines: each specific trampolines puts in the ip register
1592 * the instruction pointer address, so the generic trampoline at the start of the page
1593 * subtracts 4096 to get to the data page and loads the values
1594 * We again fit the generic trampiline in 16 bytes.
1596 sprintf (symbol, "%srgctx_trampolines_page", acfg->user_symbol_prefix);
1597 emit_global (acfg, symbol, TRUE);
1598 emit_label (acfg, symbol);
1600 imm8 = mono_arm_is_rotated_imm8 (pagesize, &rot_amount);
1601 ARM_SUB_REG_IMM (code, ARMREG_IP, ARMREG_IP, imm8, rot_amount);
1602 ARM_LDR_IMM (code, MONO_ARCH_RGCTX_REG, ARMREG_IP, -8);
1603 ARM_LDR_IMM (code, ARMREG_PC, ARMREG_IP, -4);
1605 g_assert (code - buf == COMMON_TRAMP_SIZE);
1608 emit_bytes (acfg, buf, code - buf);
1610 for (i = 0; i < count; ++i) {
1612 ARM_MOV_REG_REG (code, ARMREG_IP, ARMREG_PC);
1614 arm_patch (code - 4, code - COMMON_TRAMP_SIZE - 8 * (i + 1));
1615 g_assert (code - buf == 8);
1616 emit_bytes (acfg, buf, code - buf);
1620 * gsharedvt arg trampolines: see arch_emit_gsharedvt_arg_trampoline ()
1622 sprintf (symbol, "%sgsharedvt_arg_trampolines_page", acfg->user_symbol_prefix);
1623 emit_global (acfg, symbol, TRUE);
1624 emit_label (acfg, symbol);
1626 ARM_PUSH (code, (1 << ARMREG_R0) | (1 << ARMREG_R1) | (1 << ARMREG_R2) | (1 << ARMREG_R3));
1627 imm8 = mono_arm_is_rotated_imm8 (pagesize, &rot_amount);
1628 ARM_SUB_REG_IMM (code, ARMREG_IP, ARMREG_IP, imm8, rot_amount);
1629 ARM_LDR_IMM (code, ARMREG_R0, ARMREG_IP, -8);
1630 ARM_LDR_IMM (code, ARMREG_PC, ARMREG_IP, -4);
1631 g_assert (code - buf == COMMON_TRAMP_SIZE);
1633 emit_bytes (acfg, buf, code - buf);
1635 for (i = 0; i < count; ++i) {
1637 ARM_MOV_REG_REG (code, ARMREG_IP, ARMREG_PC);
1639 arm_patch (code - 4, code - COMMON_TRAMP_SIZE - 8 * (i + 1));
1640 g_assert (code - buf == 8);
1641 emit_bytes (acfg, buf, code - buf);
1644 /* now the imt trampolines: each specific trampolines puts in the ip register
1645 * the instruction pointer address, so the generic trampoline at the start of the page
1646 * subtracts 4096 to get to the data page and loads the values
1648 #define IMT_TRAMP_SIZE 72
1649 sprintf (symbol, "%simt_trampolines_page", acfg->user_symbol_prefix);
1650 emit_global (acfg, symbol, TRUE);
1651 emit_label (acfg, symbol);
1653 /* Need at least two free registers, plus a slot for storing the pc */
1654 ARM_PUSH (code, (1 << ARMREG_R0)|(1 << ARMREG_R1)|(1 << ARMREG_R2));
1656 imm8 = mono_arm_is_rotated_imm8 (pagesize, &rot_amount);
1657 ARM_SUB_REG_IMM (code, ARMREG_IP, ARMREG_IP, imm8, rot_amount);
1658 ARM_LDR_IMM (code, ARMREG_R0, ARMREG_IP, -8);
1660 /* The IMT method is in v5, r0 has the imt array address */
1663 ARM_LDR_IMM (code, ARMREG_R1, ARMREG_R0, 0);
1664 ARM_CMP_REG_REG (code, ARMREG_R1, ARMREG_V5);
1665 imt_found_check = code;
1666 ARM_B_COND (code, ARMCOND_EQ, 0);
1668 /* End-of-loop check */
1669 ARM_CMP_REG_IMM (code, ARMREG_R1, 0, 0);
1670 loop_end_check = code;
1671 ARM_B_COND (code, ARMCOND_EQ, 0);
1674 ARM_ADD_REG_IMM8 (code, ARMREG_R0, ARMREG_R0, sizeof (gpointer) * 2);
1675 loop_branch_back = code;
1677 arm_patch (loop_branch_back, loop_start);
1680 arm_patch (imt_found_check, code);
1681 ARM_LDR_IMM (code, ARMREG_R0, ARMREG_R0, 4);
1682 ARM_LDR_IMM (code, ARMREG_R0, ARMREG_R0, 0);
1683 /* Save it to the third stack slot */
1684 ARM_STR_IMM (code, ARMREG_R0, ARMREG_SP, 8);
1685 /* Restore the registers and branch */
1686 ARM_POP (code, (1 << ARMREG_R0)|(1 << ARMREG_R1)|(1 << ARMREG_PC));
1689 arm_patch (loop_end_check, code);
1690 ARM_LDR_IMM (code, ARMREG_R0, ARMREG_R0, 4);
1691 ARM_STR_IMM (code, ARMREG_R0, ARMREG_SP, 8);
1692 ARM_POP (code, (1 << ARMREG_R0)|(1 << ARMREG_R1)|(1 << ARMREG_PC));
1696 g_assert (code - buf == IMT_TRAMP_SIZE);
1697 emit_bytes (acfg, buf, code - buf);
1699 for (i = 0; i < count; ++i) {
1701 ARM_MOV_REG_REG (code, ARMREG_IP, ARMREG_PC);
1703 arm_patch (code - 4, code - IMT_TRAMP_SIZE - 8 * (i + 1));
1704 g_assert (code - buf == 8);
1705 emit_bytes (acfg, buf, code - buf);
1708 acfg->tramp_page_code_offsets [MONO_AOT_TRAMP_SPECIFIC] = 16;
1709 acfg->tramp_page_code_offsets [MONO_AOT_TRAMP_STATIC_RGCTX] = 16;
1710 acfg->tramp_page_code_offsets [MONO_AOT_TRAMP_IMT_THUNK] = 72;
1711 acfg->tramp_page_code_offsets [MONO_AOT_TRAMP_GSHAREDVT_ARG] = 16;
1713 /* Unwind info for specifc trampolines */
1714 sprintf (symbol, "%sspecific_trampolines_page_gen_p", acfg->user_symbol_prefix);
1715 /* We unwind to the original caller, from the stack, since lr is clobbered */
1716 mono_add_unwind_op_def_cfa (unwind_ops, 0, 0, ARMREG_SP, 14 * sizeof (mgreg_t));
1717 mono_add_unwind_op_offset (unwind_ops, 0, 0, ARMREG_LR, -4);
1718 save_unwind_info (acfg, symbol, unwind_ops);
1719 mono_free_unwind_info (unwind_ops);
1721 sprintf (symbol, "%sspecific_trampolines_page_sp_p", acfg->user_symbol_prefix);
1722 mono_add_unwind_op_def_cfa (unwind_ops, 0, 0, ARMREG_SP, 0);
1723 mono_add_unwind_op_def_cfa_offset (unwind_ops, 4, 0, 14 * sizeof (mgreg_t));
1724 save_unwind_info (acfg, symbol, unwind_ops);
1725 mono_free_unwind_info (unwind_ops);
1727 /* Unwind info for rgctx trampolines */
1728 sprintf (symbol, "%srgctx_trampolines_page_gen_p", acfg->user_symbol_prefix);
1729 mono_add_unwind_op_def_cfa (unwind_ops, 0, 0, ARMREG_SP, 0);
1730 save_unwind_info (acfg, symbol, unwind_ops);
1732 sprintf (symbol, "%srgctx_trampolines_page_sp_p", acfg->user_symbol_prefix);
1733 save_unwind_info (acfg, symbol, unwind_ops);
1734 mono_free_unwind_info (unwind_ops);
1736 /* Unwind info for gsharedvt trampolines */
1737 sprintf (symbol, "%sgsharedvt_trampolines_page_gen_p", acfg->user_symbol_prefix);
1738 mono_add_unwind_op_def_cfa (unwind_ops, 0, 0, ARMREG_SP, 0);
1739 mono_add_unwind_op_def_cfa_offset (unwind_ops, 4, 0, 4 * sizeof (mgreg_t));
1740 save_unwind_info (acfg, symbol, unwind_ops);
1741 mono_free_unwind_info (unwind_ops);
1743 sprintf (symbol, "%sgsharedvt_trampolines_page_sp_p", acfg->user_symbol_prefix);
1744 mono_add_unwind_op_def_cfa (unwind_ops, 0, 0, ARMREG_SP, 0);
1745 save_unwind_info (acfg, symbol, unwind_ops);
1746 mono_free_unwind_info (unwind_ops);
1748 /* Unwind info for imt trampolines */
1749 sprintf (symbol, "%simt_trampolines_page_gen_p", acfg->user_symbol_prefix);
1750 mono_add_unwind_op_def_cfa (unwind_ops, 0, 0, ARMREG_SP, 0);
1751 mono_add_unwind_op_def_cfa_offset (unwind_ops, 4, 0, 3 * sizeof (mgreg_t));
1752 save_unwind_info (acfg, symbol, unwind_ops);
1753 mono_free_unwind_info (unwind_ops);
1755 sprintf (symbol, "%simt_trampolines_page_sp_p", acfg->user_symbol_prefix);
1756 mono_add_unwind_op_def_cfa (unwind_ops, 0, 0, ARMREG_SP, 0);
1757 save_unwind_info (acfg, symbol, unwind_ops);
1758 mono_free_unwind_info (unwind_ops);
1759 #elif defined(TARGET_ARM64)
1760 arm64_emit_specific_trampoline_pages (acfg);
1765 * arch_emit_specific_trampoline:
1767 * Emit code for a specific trampoline. OFFSET is the offset of the first of
1768 * two GOT slots which contain the generic trampoline address and the trampoline
1769 * argument. TRAMP_SIZE is set to the size of the emitted trampoline.
1772 arch_emit_specific_trampoline (MonoAotCompile *acfg, int offset, int *tramp_size)
1775 * The trampolines created here are variations of the specific
1776 * trampolines created in mono_arch_create_specific_trampoline (). The
1778 * - the generic trampoline address is taken from a got slot.
1779 * - the offset of the got slot where the trampoline argument is stored
1780 * is embedded in the instruction stream, and the generic trampoline
1781 * can load the argument by loading the offset, adding it to the
1782 * address of the trampoline to get the address of the got slot, and
1783 * loading the argument from there.
1784 * - all the trampolines should be of the same length.
1786 #if defined(TARGET_AMD64)
1787 #if defined(__default_codegen__)
1788 /* This should be exactly 8 bytes long */
1790 /* call *<offset>(%rip) */
1792 emit_unset_mode (acfg);
1793 fprintf (acfg->fp, "call *%s+%d(%%rip)\n", acfg->got_symbol, (int)(offset * sizeof (gpointer)));
1794 emit_zero_bytes (acfg, 2);
1796 emit_byte (acfg, '\x41');
1797 emit_byte (acfg, '\xff');
1798 emit_byte (acfg, '\x15');
1799 emit_symbol_diff (acfg, acfg->got_symbol, ".", (offset * sizeof (gpointer)) - 4);
1800 emit_zero_bytes (acfg, 1);
1802 #elif defined(__native_client_codegen__)
1804 guint8 *buf_aligned = ALIGN_TO(buf, kNaClAlignment);
1805 guint8 *code = buf_aligned;
1810 /* Emit this call in 'code' so we can find out how long it is. */
1811 amd64_call_reg (code, AMD64_R11);
1812 call_start = mono_arch_nacl_skip_nops (buf_aligned);
1813 call_len = code - call_start;
1815 /* The tramp_size is twice the NaCl alignment because it starts with */
1816 /* a call which needs to be aligned to the end of the boundary. */
1817 *tramp_size = kNaClAlignment*2;
1819 /* Emit nops to align call site below which is 7 bytes plus */
1820 /* the length of the call sequence emitted above. */
1821 /* Note: this requires the specific trampoline starts on a */
1822 /* kNaclAlignedment aligned address, which it does because */
1823 /* it's its own function that is aligned. */
1824 guint8 nop_buf[256];
1825 guint8 *nopbuf_aligned = ALIGN_TO (nop_buf, kNaClAlignment);
1826 guint8 *nopbuf_end = mono_arch_nacl_pad (nopbuf_aligned, kNaClAlignment - 7 - (call_len));
1827 emit_bytes (acfg, nopbuf_aligned, nopbuf_end - nopbuf_aligned);
1829 /* The trampoline is stored at the offset'th pointer, the -4 is */
1830 /* present because RIP relative addressing starts at the end of */
1831 /* the current instruction, while the label "." is relative to */
1832 /* the beginning of the current asm location, which in this case */
1833 /* is not the mov instruction, but the offset itself, due to the */
1834 /* way the bytes and ints are emitted here. */
1835 got_offset = (offset * sizeof(gpointer)) - 4;
1837 /* mov <OFFSET>(%rip), %r11d */
1838 emit_byte (acfg, '\x45');
1839 emit_byte (acfg, '\x8b');
1840 emit_byte (acfg, '\x1d');
1841 emit_symbol_diff (acfg, acfg->got_symbol, ".", got_offset);
1844 emit_bytes (acfg, call_start, call_len);
1846 /* The arg is stored at the offset+1 pointer, relative to beginning */
1847 /* of trampoline: 7 for mov, plus the call length, and 1 for push. */
1848 got_offset = ((offset + 1) * sizeof(gpointer)) + 7 + call_len + 1;
1850 /* We can't emit this data directly, hide in a "push imm32" */
1851 emit_byte (acfg, '\x68'); /* push */
1852 emit_symbol_diff (acfg, acfg->got_symbol, ".", got_offset);
1853 emit_alignment (acfg, kNaClAlignment);
1854 #endif /*__native_client_codegen__*/
1855 #elif defined(TARGET_ARM)
1859 /* This should be exactly 20 bytes long */
1862 ARM_PUSH (code, 0x5fff);
1863 ARM_LDR_IMM (code, ARMREG_R1, ARMREG_PC, 4);
1864 /* Load the value from the GOT */
1865 ARM_LDR_REG_REG (code, ARMREG_R1, ARMREG_PC, ARMREG_R1);
1867 ARM_BLX_REG (code, ARMREG_R1);
1869 g_assert (code - buf == 16);
1872 emit_bytes (acfg, buf, code - buf);
1874 * Only one offset is needed, since the second one would be equal to the
1877 emit_symbol_diff (acfg, acfg->got_symbol, ".", (offset * sizeof (gpointer)) - 4 + 4);
1878 //emit_symbol_diff (acfg, acfg->got_symbol, ".", ((offset + 1) * sizeof (gpointer)) - 4 + 8);
1879 #elif defined(TARGET_ARM64)
1880 arm64_emit_specific_trampoline (acfg, offset, tramp_size);
1881 #elif defined(TARGET_POWERPC)
1889 * PPC has no ip relative addressing, so we need to compute the address
1890 * of the mscorlib got. That is slow and complex, so instead, we store it
1891 * in the second got slot of every aot image. The caller already computed
1892 * the address of its got and placed it into r30.
1894 emit_unset_mode (acfg);
1895 /* Load mscorlib got address */
1896 fprintf (acfg->fp, "%s 0, %d(30)\n", PPC_LD_OP, (int)sizeof (gpointer));
1897 /* Load generic trampoline address */
1898 fprintf (acfg->fp, "lis 11, %d@h\n", (int)(offset * sizeof (gpointer)));
1899 fprintf (acfg->fp, "ori 11, 11, %d@l\n", (int)(offset * sizeof (gpointer)));
1900 fprintf (acfg->fp, "%s 11, 11, 0\n", PPC_LDX_OP);
1901 #ifdef PPC_USES_FUNCTION_DESCRIPTOR
1902 fprintf (acfg->fp, "%s 11, 0(11)\n", PPC_LD_OP);
1904 fprintf (acfg->fp, "mtctr 11\n");
1905 /* Load trampoline argument */
1906 /* On ppc, we pass it normally to the generic trampoline */
1907 fprintf (acfg->fp, "lis 11, %d@h\n", (int)((offset + 1) * sizeof (gpointer)));
1908 fprintf (acfg->fp, "ori 11, 11, %d@l\n", (int)((offset + 1) * sizeof (gpointer)));
1909 fprintf (acfg->fp, "%s 0, 11, 0\n", PPC_LDX_OP);
1910 /* Branch to generic trampoline */
1911 fprintf (acfg->fp, "bctr\n");
1913 #ifdef PPC_USES_FUNCTION_DESCRIPTOR
1914 *tramp_size = 10 * 4;
1916 *tramp_size = 9 * 4;
1918 #elif defined(TARGET_X86)
1922 /* Similar to the PPC code above */
1924 /* FIXME: Could this clobber the register needed by get_vcall_slot () ? */
1927 /* Load mscorlib got address */
1928 x86_mov_reg_membase (code, X86_ECX, MONO_ARCH_GOT_REG, sizeof (gpointer), 4);
1929 /* Push trampoline argument */
1930 x86_push_membase (code, X86_ECX, (offset + 1) * sizeof (gpointer));
1931 /* Load generic trampoline address */
1932 x86_mov_reg_membase (code, X86_ECX, X86_ECX, offset * sizeof (gpointer), 4);
1933 /* Branch to generic trampoline */
1934 x86_jump_reg (code, X86_ECX);
1936 #ifdef __native_client_codegen__
1938 /* emit nops to next 32 byte alignment */
1939 int a = (~kNaClAlignmentMask) & ((code - buf) + kNaClAlignment - 1);
1940 while (code < (buf + a)) x86_nop(code);
1943 emit_bytes (acfg, buf, code - buf);
1945 *tramp_size = NACL_SIZE(17, kNaClAlignment);
1946 g_assert (code - buf == *tramp_size);
1948 g_assert_not_reached ();
1953 * arch_emit_unbox_trampoline:
1955 * Emit code for the unbox trampoline for METHOD used in the full-aot case.
1956 * CALL_TARGET is the symbol pointing to the native code of METHOD.
1959 arch_emit_unbox_trampoline (MonoAotCompile *acfg, MonoCompile *cfg, MonoMethod *method, const char *call_target)
1961 #if defined(TARGET_AMD64)
1966 this_reg = mono_arch_get_this_arg_reg (NULL);
1968 amd64_alu_reg_imm (code, X86_ADD, this_reg, sizeof (MonoObject));
1970 emit_bytes (acfg, buf, code - buf);
1973 emit_unset_mode (acfg);
1974 fprintf (acfg->fp, "jmp %s\n", call_target);
1976 emit_byte (acfg, '\xe9');
1977 emit_symbol_diff (acfg, call_target, ".", -4);
1979 #elif defined(TARGET_X86)
1986 x86_alu_membase_imm (code, X86_ADD, X86_ESP, this_pos, sizeof (MonoObject));
1988 emit_bytes (acfg, buf, code - buf);
1991 emit_byte (acfg, '\xe9');
1992 emit_symbol_diff (acfg, call_target, ".", -4);
1993 #elif defined(TARGET_ARM)
1997 if (acfg->thumb_mixed && cfg->compile_llvm) {
1998 fprintf (acfg->fp, "add r0, r0, #%d\n", (int)sizeof (MonoObject));
1999 fprintf (acfg->fp, "b %s\n", call_target);
2000 fprintf (acfg->fp, ".arm\n");
2001 fprintf (acfg->fp, ".align 2\n");
2007 ARM_ADD_REG_IMM8 (code, ARMREG_R0, ARMREG_R0, sizeof (MonoObject));
2009 emit_bytes (acfg, buf, code - buf);
2010 /* jump to method */
2011 if (acfg->thumb_mixed && cfg->compile_llvm)
2012 fprintf (acfg->fp, "\n\tbx %s\n", call_target);
2014 fprintf (acfg->fp, "\n\tb %s\n", call_target);
2015 #elif defined(TARGET_ARM64)
2016 arm64_emit_unbox_trampoline (acfg, cfg, method, call_target);
2017 #elif defined(TARGET_POWERPC)
2020 fprintf (acfg->fp, "\n\taddi %d, %d, %d\n", this_pos, this_pos, (int)sizeof (MonoObject));
2021 fprintf (acfg->fp, "\n\tb %s\n", call_target);
2023 g_assert_not_reached ();
2028 * arch_emit_static_rgctx_trampoline:
2030 * Emit code for a static rgctx trampoline. OFFSET is the offset of the first of
2031 * two GOT slots which contain the rgctx argument, and the method to jump to.
2032 * TRAMP_SIZE is set to the size of the emitted trampoline.
2033 * These kinds of trampolines cannot be enumerated statically, since there could
2034 * be one trampoline per method instantiation, so we emit the same code for all
2035 * trampolines, and parameterize them using two GOT slots.
2038 arch_emit_static_rgctx_trampoline (MonoAotCompile *acfg, int offset, int *tramp_size)
2040 #if defined(TARGET_AMD64)
2041 #if defined(__default_codegen__)
2042 /* This should be exactly 13 bytes long */
2046 emit_unset_mode (acfg);
2047 fprintf (acfg->fp, "mov %s+%d(%%rip), %%r10\n", acfg->got_symbol, (int)(offset * sizeof (gpointer)));
2048 fprintf (acfg->fp, "jmp *%s+%d(%%rip)\n", acfg->got_symbol, (int)((offset + 1) * sizeof (gpointer)));
2050 /* mov <OFFSET>(%rip), %r10 */
2051 emit_byte (acfg, '\x4d');
2052 emit_byte (acfg, '\x8b');
2053 emit_byte (acfg, '\x15');
2054 emit_symbol_diff (acfg, acfg->got_symbol, ".", (offset * sizeof (gpointer)) - 4);
2056 /* jmp *<offset>(%rip) */
2057 emit_byte (acfg, '\xff');
2058 emit_byte (acfg, '\x25');
2059 emit_symbol_diff (acfg, acfg->got_symbol, ".", ((offset + 1) * sizeof (gpointer)) - 4);
2061 #elif defined(__native_client_codegen__)
2063 guint8 *buf_aligned = ALIGN_TO(buf, kNaClAlignment);
2064 guint8 *code = buf_aligned;
2066 /* mov <OFFSET>(%rip), %r10d */
2067 emit_byte (acfg, '\x45');
2068 emit_byte (acfg, '\x8b');
2069 emit_byte (acfg, '\x15');
2070 emit_symbol_diff (acfg, acfg->got_symbol, ".", (offset * sizeof (gpointer)) - 4);
2072 /* mov <OFFSET>(%rip), %r11d */
2073 emit_byte (acfg, '\x45');
2074 emit_byte (acfg, '\x8b');
2075 emit_byte (acfg, '\x1d');
2076 emit_symbol_diff (acfg, acfg->got_symbol, ".", ((offset + 1) * sizeof (gpointer)) - 4);
2079 amd64_jump_reg (code, AMD64_R11);
2080 emit_bytes (acfg, buf_aligned, code - buf_aligned);
2082 emit_alignment (acfg, kNaClAlignment);
2083 *tramp_size = kNaClAlignment;
2084 #endif /*__native_client_codegen__*/
2086 #elif defined(TARGET_ARM)
2090 /* This should be exactly 24 bytes long */
2093 /* Load rgctx value */
2094 ARM_LDR_IMM (code, ARMREG_IP, ARMREG_PC, 8);
2095 ARM_LDR_REG_REG (code, MONO_ARCH_RGCTX_REG, ARMREG_PC, ARMREG_IP);
2096 /* Load branch addr + branch */
2097 ARM_LDR_IMM (code, ARMREG_IP, ARMREG_PC, 4);
2098 ARM_LDR_REG_REG (code, ARMREG_PC, ARMREG_PC, ARMREG_IP);
2100 g_assert (code - buf == 16);
2103 emit_bytes (acfg, buf, code - buf);
2104 emit_symbol_diff (acfg, acfg->got_symbol, ".", (offset * sizeof (gpointer)) - 4 + 8);
2105 emit_symbol_diff (acfg, acfg->got_symbol, ".", ((offset + 1) * sizeof (gpointer)) - 4 + 4);
2106 #elif defined(TARGET_ARM64)
2107 arm64_emit_static_rgctx_trampoline (acfg, offset, tramp_size);
2108 #elif defined(TARGET_POWERPC)
2116 * PPC has no ip relative addressing, so we need to compute the address
2117 * of the mscorlib got. That is slow and complex, so instead, we store it
2118 * in the second got slot of every aot image. The caller already computed
2119 * the address of its got and placed it into r30.
2121 emit_unset_mode (acfg);
2122 /* Load mscorlib got address */
2123 fprintf (acfg->fp, "%s 0, %d(30)\n", PPC_LD_OP, (int)sizeof (gpointer));
2125 fprintf (acfg->fp, "lis 11, %d@h\n", (int)(offset * sizeof (gpointer)));
2126 fprintf (acfg->fp, "ori 11, 11, %d@l\n", (int)(offset * sizeof (gpointer)));
2127 fprintf (acfg->fp, "%s %d, 11, 0\n", PPC_LDX_OP, MONO_ARCH_RGCTX_REG);
2128 /* Load target address */
2129 fprintf (acfg->fp, "lis 11, %d@h\n", (int)((offset + 1) * sizeof (gpointer)));
2130 fprintf (acfg->fp, "ori 11, 11, %d@l\n", (int)((offset + 1) * sizeof (gpointer)));
2131 fprintf (acfg->fp, "%s 11, 11, 0\n", PPC_LDX_OP);
2132 #ifdef PPC_USES_FUNCTION_DESCRIPTOR
2133 fprintf (acfg->fp, "%s 2, %d(11)\n", PPC_LD_OP, (int)sizeof (gpointer));
2134 fprintf (acfg->fp, "%s 11, 0(11)\n", PPC_LD_OP);
2136 fprintf (acfg->fp, "mtctr 11\n");
2137 /* Branch to the target address */
2138 fprintf (acfg->fp, "bctr\n");
2140 #ifdef PPC_USES_FUNCTION_DESCRIPTOR
2141 *tramp_size = 11 * 4;
2143 *tramp_size = 9 * 4;
2146 #elif defined(TARGET_X86)
2150 /* Similar to the PPC code above */
2152 g_assert (MONO_ARCH_RGCTX_REG != X86_ECX);
2155 /* Load mscorlib got address */
2156 x86_mov_reg_membase (code, X86_ECX, MONO_ARCH_GOT_REG, sizeof (gpointer), 4);
2158 x86_mov_reg_membase (code, MONO_ARCH_RGCTX_REG, X86_ECX, offset * sizeof (gpointer), 4);
2159 /* Branch to the target address */
2160 x86_jump_membase (code, X86_ECX, (offset + 1) * sizeof (gpointer));
2162 #ifdef __native_client_codegen__
2164 /* emit nops to next 32 byte alignment */
2165 int a = (~kNaClAlignmentMask) & ((code - buf) + kNaClAlignment - 1);
2166 while (code < (buf + a)) x86_nop(code);
2170 emit_bytes (acfg, buf, code - buf);
2172 *tramp_size = NACL_SIZE (15, kNaClAlignment);
2173 g_assert (code - buf == *tramp_size);
2175 g_assert_not_reached ();
2180 * arch_emit_imt_thunk:
2182 * Emit an IMT thunk usable in full-aot mode. The thunk uses 1 got slot which
2183 * points to an array of pointer pairs. The pairs of the form [key, ptr], where
2184 * key is the IMT key, and ptr holds the address of a memory location holding
2185 * the address to branch to if the IMT arg matches the key. The array is
2186 * terminated by a pair whose key is NULL, and whose ptr is the address of the
2188 * TRAMP_SIZE is set to the size of the emitted trampoline.
2191 arch_emit_imt_thunk (MonoAotCompile *acfg, int offset, int *tramp_size)
2193 #if defined(TARGET_AMD64)
2195 #if defined(__native_client_codegen__)
2198 guint8 *labels [16];
2200 guint8 *mov_buf_ptr = mov_buf;
2202 const int kSizeOfMove = 7;
2203 #if defined(__default_codegen__)
2204 code = buf = (guint8 *)g_malloc (256);
2205 #elif defined(__native_client_codegen__)
2206 buf_alloc = g_malloc (256 + kNaClAlignment + kSizeOfMove);
2207 buf = ((guint)buf_alloc + kNaClAlignment) & ~kNaClAlignmentMask;
2208 /* The RIP relative move below is emitted first */
2213 /* FIXME: Optimize this, i.e. use binary search etc. */
2214 /* Maybe move the body into a separate function (slower, but much smaller) */
2216 /* MONO_ARCH_IMT_SCRATCH_REG is a free register */
2219 emit_unset_mode (acfg);
2220 fprintf (acfg->fp, "mov %s+%d(%%rip), %s\n", acfg->got_symbol, (int)(offset * sizeof (gpointer)), mono_arch_regname (MONO_ARCH_IMT_SCRATCH_REG));
2224 amd64_alu_membase_imm (code, X86_CMP, MONO_ARCH_IMT_SCRATCH_REG, 0, 0);
2226 amd64_branch8 (code, X86_CC_Z, 0, FALSE);
2229 amd64_alu_membase_reg_size (code, X86_CMP, MONO_ARCH_IMT_SCRATCH_REG, 0, MONO_ARCH_IMT_REG, sizeof (gpointer));
2231 amd64_branch8 (code, X86_CC_Z, 0, FALSE);
2234 amd64_alu_reg_imm (code, X86_ADD, MONO_ARCH_IMT_SCRATCH_REG, 2 * sizeof (gpointer));
2235 amd64_jump_code (code, labels [0]);
2238 mono_amd64_patch (labels [2], code);
2239 amd64_mov_reg_membase (code, MONO_ARCH_IMT_SCRATCH_REG, MONO_ARCH_IMT_SCRATCH_REG, sizeof (gpointer), sizeof (gpointer));
2240 amd64_jump_membase (code, MONO_ARCH_IMT_SCRATCH_REG, 0);
2243 mono_amd64_patch (labels [1], code);
2244 /* Load fail tramp */
2245 amd64_alu_reg_imm (code, X86_ADD, MONO_ARCH_IMT_SCRATCH_REG, sizeof (gpointer));
2246 /* Check if there is a fail tramp */
2247 amd64_alu_membase_imm (code, X86_CMP, MONO_ARCH_IMT_SCRATCH_REG, 0, 0);
2249 amd64_branch8 (code, X86_CC_Z, 0, FALSE);
2250 /* Jump to fail tramp */
2251 amd64_jump_membase (code, MONO_ARCH_IMT_SCRATCH_REG, 0);
2254 mono_amd64_patch (labels [3], code);
2255 x86_breakpoint (code);
2258 /* mov <OFFSET>(%rip), MONO_ARCH_IMT_SCRATCH_REG */
2259 amd64_emit_rex (mov_buf_ptr, sizeof(gpointer), MONO_ARCH_IMT_SCRATCH_REG, 0, AMD64_RIP);
2260 *(mov_buf_ptr)++ = (unsigned char)0x8b; /* mov opcode */
2261 x86_address_byte (mov_buf_ptr, 0, MONO_ARCH_IMT_SCRATCH_REG & 0x7, 5);
2262 emit_bytes (acfg, mov_buf, mov_buf_ptr - mov_buf);
2263 emit_symbol_diff (acfg, acfg->got_symbol, ".", (offset * sizeof (gpointer)) - 4);
2265 emit_bytes (acfg, buf, code - buf);
2267 *tramp_size = code - buf + kSizeOfMove;
2268 #if defined(__native_client_codegen__)
2269 /* The tramp will be padded to the next kNaClAlignment bundle. */
2270 *tramp_size = ALIGN_TO ((*tramp_size), kNaClAlignment);
2273 #if defined(__default_codegen__)
2275 #elif defined(__native_client_codegen__)
2279 #elif defined(TARGET_X86)
2281 #ifdef __native_client_codegen__
2284 guint8 *labels [16];
2286 #if defined(__default_codegen__)
2287 code = buf = g_malloc (256);
2288 #elif defined(__native_client_codegen__)
2289 buf_alloc = g_malloc (256 + kNaClAlignment);
2290 code = buf = ((guint)buf_alloc + kNaClAlignment) & ~kNaClAlignmentMask;
2293 /* Allocate a temporary stack slot */
2294 x86_push_reg (code, X86_EAX);
2296 x86_push_reg (code, X86_EAX);
2298 /* Load mscorlib got address */
2299 x86_mov_reg_membase (code, X86_EAX, MONO_ARCH_GOT_REG, sizeof (gpointer), 4);
2301 x86_mov_reg_membase (code, X86_EAX, X86_EAX, offset * sizeof (gpointer), 4);
2304 x86_alu_membase_imm (code, X86_CMP, X86_EAX, 0, 0);
2306 x86_branch8 (code, X86_CC_Z, FALSE, 0);
2309 x86_alu_membase_reg (code, X86_CMP, X86_EAX, 0, MONO_ARCH_IMT_REG);
2311 x86_branch8 (code, X86_CC_Z, FALSE, 0);
2314 x86_alu_reg_imm (code, X86_ADD, X86_EAX, 2 * sizeof (gpointer));
2315 x86_jump_code (code, labels [0]);
2318 mono_x86_patch (labels [2], code);
2319 x86_mov_reg_membase (code, X86_EAX, X86_EAX, sizeof (gpointer), 4);
2320 x86_mov_reg_membase (code, X86_EAX, X86_EAX, 0, 4);
2321 /* Save the target address to the temporary stack location */
2322 x86_mov_membase_reg (code, X86_ESP, 4, X86_EAX, 4);
2324 x86_pop_reg (code, X86_EAX);
2325 /* Jump to the target address */
2329 mono_x86_patch (labels [1], code);
2330 /* Load fail tramp */
2331 x86_mov_reg_membase (code, X86_EAX, X86_EAX, sizeof (gpointer), 4);
2332 x86_alu_membase_imm (code, X86_CMP, X86_EAX, 0, 0);
2334 x86_branch8 (code, X86_CC_Z, FALSE, 0);
2335 /* Jump to fail tramp */
2336 x86_mov_membase_reg (code, X86_ESP, 4, X86_EAX, 4);
2337 x86_pop_reg (code, X86_EAX);
2341 mono_x86_patch (labels [3], code);
2342 x86_breakpoint (code);
2344 #ifdef __native_client_codegen__
2346 /* emit nops to next 32 byte alignment */
2347 int a = (~kNaClAlignmentMask) & ((code - buf) + kNaClAlignment - 1);
2348 while (code < (buf + a)) x86_nop(code);
2351 emit_bytes (acfg, buf, code - buf);
2353 *tramp_size = code - buf;
2355 #if defined(__default_codegen__)
2357 #elif defined(__native_client_codegen__)
2361 #elif defined(TARGET_ARM)
2363 guint8 *code, *code2, *labels [16];
2367 /* The IMT method is in v5 */
2369 /* Need at least two free registers, plus a slot for storing the pc */
2370 ARM_PUSH (code, (1 << ARMREG_R0)|(1 << ARMREG_R1)|(1 << ARMREG_R2));
2372 /* Load the parameter from the GOT */
2373 ARM_LDR_IMM (code, ARMREG_R0, ARMREG_PC, 0);
2374 ARM_LDR_REG_REG (code, ARMREG_R0, ARMREG_PC, ARMREG_R0);
2377 ARM_LDR_IMM (code, ARMREG_R1, ARMREG_R0, 0);
2378 ARM_CMP_REG_REG (code, ARMREG_R1, ARMREG_V5);
2380 ARM_B_COND (code, ARMCOND_EQ, 0);
2382 /* End-of-loop check */
2383 ARM_CMP_REG_IMM (code, ARMREG_R1, 0, 0);
2385 ARM_B_COND (code, ARMCOND_EQ, 0);
2388 ARM_ADD_REG_IMM8 (code, ARMREG_R0, ARMREG_R0, sizeof (gpointer) * 2);
2391 arm_patch (labels [4], labels [1]);
2394 arm_patch (labels [2], code);
2395 ARM_LDR_IMM (code, ARMREG_R0, ARMREG_R0, 4);
2396 ARM_LDR_IMM (code, ARMREG_R0, ARMREG_R0, 0);
2397 /* Save it to the third stack slot */
2398 ARM_STR_IMM (code, ARMREG_R0, ARMREG_SP, 8);
2399 /* Restore the registers and branch */
2400 ARM_POP (code, (1 << ARMREG_R0)|(1 << ARMREG_R1)|(1 << ARMREG_PC));
2403 arm_patch (labels [3], code);
2404 ARM_LDR_IMM (code, ARMREG_R0, ARMREG_R0, 4);
2405 ARM_STR_IMM (code, ARMREG_R0, ARMREG_SP, 8);
2406 ARM_POP (code, (1 << ARMREG_R0)|(1 << ARMREG_R1)|(1 << ARMREG_PC));
2410 ARM_LDR_IMM (code2, ARMREG_R0, ARMREG_PC, (code - (labels [0] + 8)));
2412 emit_bytes (acfg, buf, code - buf);
2413 emit_symbol_diff (acfg, acfg->got_symbol, ".", (offset * sizeof (gpointer)) + (code - (labels [0] + 8)) - 4);
2415 *tramp_size = code - buf + 4;
2416 #elif defined(TARGET_ARM64)
2417 arm64_emit_imt_thunk (acfg, offset, tramp_size);
2418 #elif defined(TARGET_POWERPC)
2420 guint8 *code, *labels [16];
2424 /* Load the mscorlib got address */
2425 ppc_ldptr (code, ppc_r12, sizeof (gpointer), ppc_r30);
2426 /* Load the parameter from the GOT */
2427 ppc_load (code, ppc_r0, offset * sizeof (gpointer));
2428 ppc_ldptr_indexed (code, ppc_r12, ppc_r12, ppc_r0);
2430 /* Load and check key */
2432 ppc_ldptr (code, ppc_r0, 0, ppc_r12);
2433 ppc_cmp (code, 0, sizeof (gpointer) == 8 ? 1 : 0, ppc_r0, MONO_ARCH_IMT_REG);
2435 ppc_bc (code, PPC_BR_TRUE, PPC_BR_EQ, 0);
2437 /* End-of-loop check */
2438 ppc_cmpi (code, 0, sizeof (gpointer) == 8 ? 1 : 0, ppc_r0, 0);
2440 ppc_bc (code, PPC_BR_TRUE, PPC_BR_EQ, 0);
2443 ppc_addi (code, ppc_r12, ppc_r12, 2 * sizeof (gpointer));
2446 mono_ppc_patch (labels [4], labels [1]);
2449 mono_ppc_patch (labels [2], code);
2450 ppc_ldptr (code, ppc_r12, sizeof (gpointer), ppc_r12);
2451 /* r12 now contains the value of the vtable slot */
2452 /* this is not a function descriptor on ppc64 */
2453 ppc_ldptr (code, ppc_r12, 0, ppc_r12);
2454 ppc_mtctr (code, ppc_r12);
2455 ppc_bcctr (code, PPC_BR_ALWAYS, 0);
2458 mono_ppc_patch (labels [3], code);
2462 *tramp_size = code - buf;
2464 emit_bytes (acfg, buf, code - buf);
2466 g_assert_not_reached ();
2471 #if defined (TARGET_AMD64)
2474 amd64_emit_load_got_slot (MonoAotCompile *acfg, int dreg, int got_slot)
2477 g_assert (acfg->fp);
2478 emit_unset_mode (acfg);
2480 fprintf (acfg->fp, "mov %s+%d(%%rip), %s\n", acfg->got_symbol, (unsigned int) ((got_slot * sizeof (gpointer))), mono_arch_regname (dreg));
2487 * arch_emit_gsharedvt_arg_trampoline:
2489 * Emit code for a gsharedvt arg trampoline. OFFSET is the offset of the first of
2490 * two GOT slots which contain the argument, and the code to jump to.
2491 * TRAMP_SIZE is set to the size of the emitted trampoline.
2492 * These kinds of trampolines cannot be enumerated statically, since there could
2493 * be one trampoline per method instantiation, so we emit the same code for all
2494 * trampolines, and parameterize them using two GOT slots.
2497 arch_emit_gsharedvt_arg_trampoline (MonoAotCompile *acfg, int offset, int *tramp_size)
2499 #if defined(TARGET_X86)
2503 /* Similar to the PPC code above */
2505 g_assert (MONO_ARCH_RGCTX_REG != X86_ECX);
2508 /* Load mscorlib got address */
2509 x86_mov_reg_membase (code, X86_ECX, MONO_ARCH_GOT_REG, sizeof (gpointer), 4);
2511 x86_mov_reg_membase (code, X86_EAX, X86_ECX, offset * sizeof (gpointer), 4);
2512 /* Branch to the target address */
2513 x86_jump_membase (code, X86_ECX, (offset + 1) * sizeof (gpointer));
2515 #ifdef __native_client_codegen__
2517 /* emit nops to next 32 byte alignment */
2518 int a = (~kNaClAlignmentMask) & ((code - buf) + kNaClAlignment - 1);
2519 while (code < (buf + a)) x86_nop(code);
2523 emit_bytes (acfg, buf, code - buf);
2525 *tramp_size = NACL_SIZE (15, kNaClAlignment);
2526 g_assert (code - buf == *tramp_size);
2527 #elif defined(TARGET_ARM)
2531 /* The same as mono_arch_get_gsharedvt_arg_trampoline (), but for AOT */
2532 /* Similar to arch_emit_specific_trampoline () */
2535 ARM_PUSH (code, (1 << ARMREG_R0) | (1 << ARMREG_R1) | (1 << ARMREG_R2) | (1 << ARMREG_R3));
2536 ARM_LDR_IMM (code, ARMREG_R1, ARMREG_PC, 8);
2537 /* Load the arg value from the GOT */
2538 ARM_LDR_REG_REG (code, ARMREG_R0, ARMREG_PC, ARMREG_R1);
2539 /* Load the addr from the GOT */
2540 ARM_LDR_REG_REG (code, ARMREG_R1, ARMREG_PC, ARMREG_R1);
2542 ARM_BX (code, ARMREG_R1);
2544 g_assert (code - buf == 20);
2547 emit_bytes (acfg, buf, code - buf);
2548 emit_symbol_diff (acfg, acfg->got_symbol, ".", (offset * sizeof (gpointer)) + 4);
2549 #elif defined(TARGET_ARM64)
2550 arm64_emit_gsharedvt_arg_trampoline (acfg, offset, tramp_size);
2551 #elif defined (TARGET_AMD64)
2553 amd64_emit_load_got_slot (acfg, AMD64_RAX, offset);
2554 amd64_emit_load_got_slot (acfg, MONO_ARCH_IMT_SCRATCH_REG, offset + 1);
2555 g_assert (AMD64_R11 == MONO_ARCH_IMT_SCRATCH_REG);
2556 fprintf (acfg->fp, "jmp *%%r11\n");
2560 g_assert_not_reached ();
2564 /* END OF ARCH SPECIFIC CODE */
2567 mono_get_field_token (MonoClassField *field)
2569 MonoClass *klass = field->parent;
2572 for (i = 0; i < klass->field.count; ++i) {
2573 if (field == &klass->fields [i])
2574 return MONO_TOKEN_FIELD_DEF | (klass->field.first + 1 + i);
2577 g_assert_not_reached ();
2582 encode_value (gint32 value, guint8 *buf, guint8 **endbuf)
2586 //printf ("ENCODE: %d 0x%x.\n", value, value);
2589 * Same encoding as the one used in the metadata, extended to handle values
2590 * greater than 0x1fffffff.
2592 if ((value >= 0) && (value <= 127))
2594 else if ((value >= 0) && (value <= 16383)) {
2595 p [0] = 0x80 | (value >> 8);
2596 p [1] = value & 0xff;
2598 } else if ((value >= 0) && (value <= 0x1fffffff)) {
2599 p [0] = (value >> 24) | 0xc0;
2600 p [1] = (value >> 16) & 0xff;
2601 p [2] = (value >> 8) & 0xff;
2602 p [3] = value & 0xff;
2607 p [1] = (value >> 24) & 0xff;
2608 p [2] = (value >> 16) & 0xff;
2609 p [3] = (value >> 8) & 0xff;
2610 p [4] = value & 0xff;
2618 stream_init (MonoDynamicStream *sh)
2621 sh->alloc_size = 4096;
2622 sh->data = (char *)g_malloc (4096);
2624 /* So offsets are > 0 */
2630 make_room_in_stream (MonoDynamicStream *stream, int size)
2632 if (size <= stream->alloc_size)
2635 while (stream->alloc_size <= size) {
2636 if (stream->alloc_size < 4096)
2637 stream->alloc_size = 4096;
2639 stream->alloc_size *= 2;
2642 stream->data = (char *)g_realloc (stream->data, stream->alloc_size);
2646 add_stream_data (MonoDynamicStream *stream, const char *data, guint32 len)
2650 make_room_in_stream (stream, stream->index + len);
2651 memcpy (stream->data + stream->index, data, len);
2652 idx = stream->index;
2653 stream->index += len;
2660 * Add data to the binary blob inside the aot image. Returns the offset inside the
2661 * blob where the data was stored.
2664 add_to_blob (MonoAotCompile *acfg, const guint8 *data, guint32 data_len)
2666 g_assert (!acfg->blob_closed);
2668 if (acfg->blob.alloc_size == 0)
2669 stream_init (&acfg->blob);
2671 return add_stream_data (&acfg->blob, (char*)data, data_len);
2675 add_to_blob_aligned (MonoAotCompile *acfg, const guint8 *data, guint32 data_len, guint32 align)
2680 if (acfg->blob.alloc_size == 0)
2681 stream_init (&acfg->blob);
2683 count = acfg->blob.index % align;
2685 /* we assume the stream data will be aligned */
2687 add_stream_data (&acfg->blob, buf, 4 - count);
2689 return add_stream_data (&acfg->blob, (char*)data, data_len);
2692 /* Emit a table of data into the aot image */
2694 emit_aot_data (MonoAotCompile *acfg, MonoAotFileTable table, const char *symbol, guint8 *data, int size)
2696 if (acfg->data_outfile) {
2697 acfg->table_offsets [(int)table] = acfg->datafile_offset;
2698 fwrite (data,1, size, acfg->data_outfile);
2699 acfg->datafile_offset += size;
2700 // align the data to 8 bytes. Put zeros in the file (so that every build results in consistent output).
2701 int align = 8 - size % 8;
2702 acfg->datafile_offset += align;
2703 guint8 align_buf [16];
2704 memset (&align_buf, 0, sizeof (align_buf));
2705 fwrite (align_buf, align, 1, acfg->data_outfile);
2706 } else if (acfg->llvm) {
2707 mono_llvm_emit_aot_data (symbol, data, size);
2709 emit_section_change (acfg, RODATA_SECT, 0);
2710 emit_alignment (acfg, 8);
2711 emit_label (acfg, symbol);
2712 emit_bytes (acfg, data, size);
2717 * emit_offset_table:
2719 * Emit a table of increasing offsets in a compact form using differential encoding.
2720 * There is an index entry for each GROUP_SIZE number of entries. The greater the
2721 * group size, the more compact the table becomes, but the slower it becomes to compute
2722 * a given entry. Returns the size of the table.
2725 emit_offset_table (MonoAotCompile *acfg, const char *symbol, MonoAotFileTable table, int noffsets, int group_size, gint32 *offsets)
2727 gint32 current_offset;
2728 int i, buf_size, ngroups, index_entry_size;
2730 guint8 *data_p, *data_buf;
2731 guint32 *index_offsets;
2733 ngroups = (noffsets + (group_size - 1)) / group_size;
2735 index_offsets = g_new0 (guint32, ngroups);
2737 buf_size = noffsets * 4;
2738 p = buf = (guint8 *)g_malloc0 (buf_size);
2741 for (i = 0; i < noffsets; ++i) {
2742 //printf ("D: %d -> %d\n", i, offsets [i]);
2743 if ((i % group_size) == 0) {
2744 index_offsets [i / group_size] = p - buf;
2745 /* Emit the full value for these entries */
2746 encode_value (offsets [i], p, &p);
2748 /* The offsets are allowed to be non-increasing */
2749 //g_assert (offsets [i] >= current_offset);
2750 encode_value (offsets [i] - current_offset, p, &p);
2752 current_offset = offsets [i];
2757 if (ngroups && index_offsets [ngroups - 1] < 65000)
2758 index_entry_size = 2;
2760 index_entry_size = 4;
2762 buf_size = (data_p - data_buf) + (ngroups * 4) + 16;
2763 p = buf = (guint8 *)g_malloc0 (buf_size);
2765 /* Emit the header */
2766 encode_int (noffsets, p, &p);
2767 encode_int (group_size, p, &p);
2768 encode_int (ngroups, p, &p);
2769 encode_int (index_entry_size, p, &p);
2771 /* Emit the index */
2772 for (i = 0; i < ngroups; ++i) {
2773 if (index_entry_size == 2)
2774 encode_int16 (index_offsets [i], p, &p);
2776 encode_int (index_offsets [i], p, &p);
2779 memcpy (p, data_buf, data_p - data_buf);
2780 p += data_p - data_buf;
2782 g_assert (p - buf <= buf_size);
2784 emit_aot_data (acfg, table, symbol, buf, p - buf);
2789 return (int)(p - buf);
2793 get_image_index (MonoAotCompile *cfg, MonoImage *image)
2797 index = GPOINTER_TO_UINT (g_hash_table_lookup (cfg->image_hash, image));
2801 index = g_hash_table_size (cfg->image_hash);
2802 g_hash_table_insert (cfg->image_hash, image, GUINT_TO_POINTER (index + 1));
2803 g_ptr_array_add (cfg->image_table, image);
2809 find_typespec_for_class (MonoAotCompile *acfg, MonoClass *klass)
2812 int len = acfg->image->tables [MONO_TABLE_TYPESPEC].rows;
2814 /* FIXME: Search referenced images as well */
2815 if (!acfg->typespec_classes) {
2816 acfg->typespec_classes = (MonoClass **)mono_mempool_alloc0 (acfg->mempool, sizeof (MonoClass*) * len);
2817 for (i = 0; i < len; ++i) {
2819 acfg->typespec_classes [i] = mono_class_get_and_inflate_typespec_checked (acfg->image, MONO_TOKEN_TYPE_SPEC | (i + 1), NULL, &error);
2820 g_assert (mono_error_ok (&error)); /* FIXME error handling */
2823 for (i = 0; i < len; ++i) {
2824 if (acfg->typespec_classes [i] == klass)
2829 return MONO_TOKEN_TYPE_SPEC | (i + 1);
2835 encode_method_ref (MonoAotCompile *acfg, MonoMethod *method, guint8 *buf, guint8 **endbuf);
2838 encode_klass_ref (MonoAotCompile *acfg, MonoClass *klass, guint8 *buf, guint8 **endbuf);
2841 encode_ginst (MonoAotCompile *acfg, MonoGenericInst *inst, guint8 *buf, guint8 **endbuf);
2844 encode_type (MonoAotCompile *acfg, MonoType *t, guint8 *buf, guint8 **endbuf);
2847 encode_klass_ref_inner (MonoAotCompile *acfg, MonoClass *klass, guint8 *buf, guint8 **endbuf)
2852 * The encoding begins with one of the MONO_AOT_TYPEREF values, followed by additional
2856 if (klass->generic_class) {
2858 g_assert (klass->type_token);
2860 /* Find a typespec for a class if possible */
2861 token = find_typespec_for_class (acfg, klass);
2863 encode_value (MONO_AOT_TYPEREF_TYPESPEC_TOKEN, p, &p);
2864 encode_value (token, p, &p);
2866 MonoClass *gclass = klass->generic_class->container_class;
2867 MonoGenericInst *inst = klass->generic_class->context.class_inst;
2868 static int count = 0;
2871 encode_value (MONO_AOT_TYPEREF_GINST, p, &p);
2872 encode_klass_ref (acfg, gclass, p, &p);
2873 encode_ginst (acfg, inst, p, &p);
2877 } else if (klass->type_token) {
2878 int iindex = get_image_index (acfg, klass->image);
2880 g_assert (mono_metadata_token_code (klass->type_token) == MONO_TOKEN_TYPE_DEF);
2882 encode_value (MONO_AOT_TYPEREF_TYPEDEF_INDEX, p, &p);
2883 encode_value (klass->type_token - MONO_TOKEN_TYPE_DEF, p, &p);
2885 encode_value (MONO_AOT_TYPEREF_TYPEDEF_INDEX_IMAGE, p, &p);
2886 encode_value (klass->type_token - MONO_TOKEN_TYPE_DEF, p, &p);
2887 encode_value (get_image_index (acfg, klass->image), p, &p);
2889 } else if ((klass->byval_arg.type == MONO_TYPE_VAR) || (klass->byval_arg.type == MONO_TYPE_MVAR)) {
2890 MonoGenericContainer *container = mono_type_get_generic_param_owner (&klass->byval_arg);
2891 MonoGenericParam *par = klass->byval_arg.data.generic_param;
2893 encode_value (MONO_AOT_TYPEREF_VAR, p, &p);
2895 encode_value (par->gshared_constraint ? 1 : 0, p, &p);
2896 if (par->gshared_constraint) {
2897 MonoGSharedGenericParam *gpar = (MonoGSharedGenericParam*)par;
2898 encode_type (acfg, par->gshared_constraint, p, &p);
2899 encode_klass_ref (acfg, mono_class_from_generic_parameter (gpar->parent, NULL, klass->byval_arg.type == MONO_TYPE_MVAR), p, &p);
2901 encode_value (klass->byval_arg.type, p, &p);
2902 encode_value (mono_type_get_generic_param_num (&klass->byval_arg), p, &p);
2904 encode_value (container->is_anonymous ? 0 : 1, p, &p);
2906 if (!container->is_anonymous) {
2907 encode_value (container->is_method, p, &p);
2908 if (container->is_method)
2909 encode_method_ref (acfg, container->owner.method, p, &p);
2911 encode_klass_ref (acfg, container->owner.klass, p, &p);
2914 } else if (klass->byval_arg.type == MONO_TYPE_PTR) {
2915 encode_value (MONO_AOT_TYPEREF_PTR, p, &p);
2916 encode_type (acfg, &klass->byval_arg, p, &p);
2919 g_assert (klass->rank > 0);
2920 encode_value (MONO_AOT_TYPEREF_ARRAY, p, &p);
2921 encode_value (klass->rank, p, &p);
2922 encode_klass_ref (acfg, klass->element_class, p, &p);
2930 * Encode a reference to KLASS. We use our home-grown encoding instead of the
2931 * standard metadata encoding.
2934 encode_klass_ref (MonoAotCompile *acfg, MonoClass *klass, guint8 *buf, guint8 **endbuf)
2936 gboolean shared = FALSE;
2939 * The encoding of generic instances is large so emit them only once.
2941 if (klass->generic_class) {
2943 g_assert (klass->type_token);
2945 /* Find a typespec for a class if possible */
2946 token = find_typespec_for_class (acfg, klass);
2949 } else if ((klass->byval_arg.type == MONO_TYPE_VAR) || (klass->byval_arg.type == MONO_TYPE_MVAR)) {
2954 guint offset = GPOINTER_TO_UINT (g_hash_table_lookup (acfg->klass_blob_hash, klass));
2958 buf2 = (guint8 *)g_malloc (1024);
2961 encode_klass_ref_inner (acfg, klass, p, &p);
2962 g_assert (p - buf2 < 1024);
2964 offset = add_to_blob (acfg, buf2, p - buf2);
2967 g_hash_table_insert (acfg->klass_blob_hash, klass, GUINT_TO_POINTER (offset + 1));
2973 encode_value (MONO_AOT_TYPEREF_BLOB_INDEX, p, &p);
2974 encode_value (offset, p, &p);
2979 encode_klass_ref_inner (acfg, klass, buf, endbuf);
2983 encode_field_info (MonoAotCompile *cfg, MonoClassField *field, guint8 *buf, guint8 **endbuf)
2985 guint32 token = mono_get_field_token (field);
2988 encode_klass_ref (cfg, field->parent, p, &p);
2989 g_assert (mono_metadata_token_code (token) == MONO_TOKEN_FIELD_DEF);
2990 encode_value (token - MONO_TOKEN_FIELD_DEF, p, &p);
2995 encode_ginst (MonoAotCompile *acfg, MonoGenericInst *inst, guint8 *buf, guint8 **endbuf)
3000 encode_value (inst->type_argc, p, &p);
3001 for (i = 0; i < inst->type_argc; ++i)
3002 encode_klass_ref (acfg, mono_class_from_mono_type (inst->type_argv [i]), p, &p);
3007 encode_generic_context (MonoAotCompile *acfg, MonoGenericContext *context, guint8 *buf, guint8 **endbuf)
3010 MonoGenericInst *inst;
3012 inst = context->class_inst;
3014 g_assert (inst->type_argc);
3015 encode_ginst (acfg, inst, p, &p);
3017 encode_value (0, p, &p);
3019 inst = context->method_inst;
3021 g_assert (inst->type_argc);
3022 encode_ginst (acfg, inst, p, &p);
3024 encode_value (0, p, &p);
3030 encode_type (MonoAotCompile *acfg, MonoType *t, guint8 *buf, guint8 **endbuf)
3034 g_assert (t->num_mods == 0);
3035 /* t->attrs can be ignored */
3036 //g_assert (t->attrs == 0);
3039 *p = MONO_TYPE_PINNED;
3043 *p = MONO_TYPE_BYREF;
3051 case MONO_TYPE_VOID:
3052 case MONO_TYPE_BOOLEAN:
3053 case MONO_TYPE_CHAR:
3066 case MONO_TYPE_STRING:
3067 case MONO_TYPE_OBJECT:
3068 case MONO_TYPE_TYPEDBYREF:
3070 case MONO_TYPE_VALUETYPE:
3071 case MONO_TYPE_CLASS:
3072 encode_klass_ref (acfg, mono_class_from_mono_type (t), p, &p);
3074 case MONO_TYPE_SZARRAY:
3075 encode_klass_ref (acfg, t->data.klass, p, &p);
3078 encode_type (acfg, t->data.type, p, &p);
3080 case MONO_TYPE_GENERICINST: {
3081 MonoClass *gclass = t->data.generic_class->container_class;
3082 MonoGenericInst *inst = t->data.generic_class->context.class_inst;
3084 encode_klass_ref (acfg, gclass, p, &p);
3085 encode_ginst (acfg, inst, p, &p);
3088 case MONO_TYPE_ARRAY: {
3089 MonoArrayType *array = t->data.array;
3092 encode_klass_ref (acfg, array->eklass, p, &p);
3093 encode_value (array->rank, p, &p);
3094 encode_value (array->numsizes, p, &p);
3095 for (i = 0; i < array->numsizes; ++i)
3096 encode_value (array->sizes [i], p, &p);
3097 encode_value (array->numlobounds, p, &p);
3098 for (i = 0; i < array->numlobounds; ++i)
3099 encode_value (array->lobounds [i], p, &p);
3103 case MONO_TYPE_MVAR:
3104 encode_klass_ref (acfg, mono_class_from_mono_type (t), p, &p);
3107 g_assert_not_reached ();
3114 encode_signature (MonoAotCompile *acfg, MonoMethodSignature *sig, guint8 *buf, guint8 **endbuf)
3120 /* Similar to the metadata encoding */
3121 if (sig->generic_param_count)
3125 if (sig->explicit_this)
3127 flags |= (sig->call_convention & 0x0F);
3131 if (sig->generic_param_count)
3132 encode_value (sig->generic_param_count, p, &p);
3133 encode_value (sig->param_count, p, &p);
3135 encode_type (acfg, sig->ret, p, &p);
3136 for (i = 0; i < sig->param_count; ++i) {
3137 if (sig->sentinelpos == i) {
3138 *p = MONO_TYPE_SENTINEL;
3141 encode_type (acfg, sig->params [i], p, &p);
3147 #define MAX_IMAGE_INDEX 250
3150 encode_method_ref (MonoAotCompile *acfg, MonoMethod *method, guint8 *buf, guint8 **endbuf)
3152 guint32 image_index = get_image_index (acfg, method->klass->image);
3153 guint32 token = method->token;
3154 MonoJumpInfoToken *ji;
3158 * The encoding for most methods is as follows:
3159 * - image index encoded as a leb128
3160 * - token index encoded as a leb128
3161 * Values of image index >= MONO_AOT_METHODREF_MIN are used to mark additional
3162 * types of method encodings.
3165 /* Mark methods which can't use aot trampolines because they need the further
3166 * processing in mono_magic_trampoline () which requires a MonoMethod*.
3168 if ((method->is_generic && (method->flags & METHOD_ATTRIBUTE_VIRTUAL)) ||
3169 (method->iflags & METHOD_IMPL_ATTRIBUTE_SYNCHRONIZED))
3170 encode_value ((MONO_AOT_METHODREF_NO_AOT_TRAMPOLINE << 24), p, &p);
3172 if (method->wrapper_type) {
3173 WrapperInfo *info = mono_marshal_get_wrapper_info (method);
3175 encode_value ((MONO_AOT_METHODREF_WRAPPER << 24), p, &p);
3177 encode_value (method->wrapper_type, p, &p);
3179 switch (method->wrapper_type) {
3180 case MONO_WRAPPER_REMOTING_INVOKE:
3181 case MONO_WRAPPER_REMOTING_INVOKE_WITH_CHECK:
3182 case MONO_WRAPPER_XDOMAIN_INVOKE: {
3185 m = mono_marshal_method_from_wrapper (method);
3187 encode_method_ref (acfg, m, p, &p);
3190 case MONO_WRAPPER_PROXY_ISINST:
3191 case MONO_WRAPPER_LDFLD:
3192 case MONO_WRAPPER_LDFLDA:
3193 case MONO_WRAPPER_STFLD:
3194 case MONO_WRAPPER_ISINST: {
3196 encode_klass_ref (acfg, info->d.proxy.klass, p, &p);
3199 case MONO_WRAPPER_LDFLD_REMOTE:
3200 case MONO_WRAPPER_STFLD_REMOTE:
3202 case MONO_WRAPPER_ALLOC: {
3203 /* The GC name is saved once in MonoAotFileInfo */
3204 g_assert (info->d.alloc.alloc_type != -1);
3205 encode_value (info->d.alloc.alloc_type, p, &p);
3208 case MONO_WRAPPER_WRITE_BARRIER: {
3212 case MONO_WRAPPER_STELEMREF: {
3214 encode_value (info->subtype, p, &p);
3215 if (info->subtype == WRAPPER_SUBTYPE_VIRTUAL_STELEMREF)
3216 encode_value (info->d.virtual_stelemref.kind, p, &p);
3219 case MONO_WRAPPER_UNKNOWN: {
3221 encode_value (info->subtype, p, &p);
3222 if (info->subtype == WRAPPER_SUBTYPE_PTR_TO_STRUCTURE ||
3223 info->subtype == WRAPPER_SUBTYPE_STRUCTURE_TO_PTR)
3224 encode_klass_ref (acfg, method->klass, p, &p);
3225 else if (info->subtype == WRAPPER_SUBTYPE_SYNCHRONIZED_INNER)
3226 encode_method_ref (acfg, info->d.synchronized_inner.method, p, &p);
3227 else if (info->subtype == WRAPPER_SUBTYPE_ARRAY_ACCESSOR)
3228 encode_method_ref (acfg, info->d.array_accessor.method, p, &p);
3229 else if (info->subtype == WRAPPER_SUBTYPE_GSHAREDVT_IN_SIG)
3230 encode_signature (acfg, info->d.gsharedvt.sig, p, &p);
3231 else if (info->subtype == WRAPPER_SUBTYPE_GSHAREDVT_OUT_SIG)
3232 encode_signature (acfg, info->d.gsharedvt.sig, p, &p);
3235 case MONO_WRAPPER_MANAGED_TO_NATIVE: {
3237 encode_value (info->subtype, p, &p);
3238 if (info->subtype == WRAPPER_SUBTYPE_ICALL_WRAPPER) {
3239 strcpy ((char*)p, method->name);
3240 p += strlen (method->name) + 1;
3241 } else if (info->subtype == WRAPPER_SUBTYPE_NATIVE_FUNC_AOT) {
3242 encode_method_ref (acfg, info->d.managed_to_native.method, p, &p);
3244 g_assert (info->subtype == WRAPPER_SUBTYPE_NONE || info->subtype == WRAPPER_SUBTYPE_PINVOKE);
3245 encode_method_ref (acfg, info->d.managed_to_native.method, p, &p);
3249 case MONO_WRAPPER_SYNCHRONIZED: {
3252 m = mono_marshal_method_from_wrapper (method);
3254 g_assert (m != method);
3255 encode_method_ref (acfg, m, p, &p);
3258 case MONO_WRAPPER_MANAGED_TO_MANAGED: {
3260 encode_value (info->subtype, p, &p);
3262 if (info->subtype == WRAPPER_SUBTYPE_ELEMENT_ADDR) {
3263 encode_value (info->d.element_addr.rank, p, &p);
3264 encode_value (info->d.element_addr.elem_size, p, &p);
3265 } else if (info->subtype == WRAPPER_SUBTYPE_STRING_CTOR) {
3266 encode_method_ref (acfg, info->d.string_ctor.method, p, &p);
3268 g_assert_not_reached ();
3272 case MONO_WRAPPER_CASTCLASS: {
3274 encode_value (info->subtype, p, &p);
3277 case MONO_WRAPPER_RUNTIME_INVOKE: {
3279 encode_value (info->subtype, p, &p);
3280 if (info->subtype == WRAPPER_SUBTYPE_RUNTIME_INVOKE_DIRECT || info->subtype == WRAPPER_SUBTYPE_RUNTIME_INVOKE_VIRTUAL)
3281 encode_method_ref (acfg, info->d.runtime_invoke.method, p, &p);
3282 else if (info->subtype == WRAPPER_SUBTYPE_RUNTIME_INVOKE_NORMAL)
3283 encode_signature (acfg, info->d.runtime_invoke.sig, p, &p);
3286 case MONO_WRAPPER_DELEGATE_INVOKE:
3287 case MONO_WRAPPER_DELEGATE_BEGIN_INVOKE:
3288 case MONO_WRAPPER_DELEGATE_END_INVOKE: {
3289 if (method->is_inflated) {
3290 /* These wrappers are identified by their class */
3291 encode_value (1, p, &p);
3292 encode_klass_ref (acfg, method->klass, p, &p);
3294 MonoMethodSignature *sig = mono_method_signature (method);
3295 WrapperInfo *info = mono_marshal_get_wrapper_info (method);
3297 encode_value (0, p, &p);
3298 if (method->wrapper_type == MONO_WRAPPER_DELEGATE_INVOKE)
3299 encode_value (info ? info->subtype : 0, p, &p);
3300 encode_signature (acfg, sig, p, &p);
3304 case MONO_WRAPPER_NATIVE_TO_MANAGED: {
3306 encode_method_ref (acfg, info->d.native_to_managed.method, p, &p);
3307 encode_klass_ref (acfg, info->d.native_to_managed.klass, p, &p);
3311 g_assert_not_reached ();
3313 } else if (mono_method_signature (method)->is_inflated) {
3315 * This is a generic method, find the original token which referenced it and
3317 * Obtain the token from information recorded by the JIT.
3319 ji = (MonoJumpInfoToken *)g_hash_table_lookup (acfg->token_info_hash, method);
3321 image_index = get_image_index (acfg, ji->image);
3322 g_assert (image_index < MAX_IMAGE_INDEX);
3325 encode_value ((MONO_AOT_METHODREF_METHODSPEC << 24), p, &p);
3326 encode_value (image_index, p, &p);
3327 encode_value (token, p, &p);
3329 MonoMethod *declaring;
3330 MonoGenericContext *context = mono_method_get_context (method);
3332 g_assert (method->is_inflated);
3333 declaring = ((MonoMethodInflated*)method)->declaring;
3336 * This might be a non-generic method of a generic instance, which
3337 * doesn't have a token since the reference is generated by the JIT
3338 * like Nullable:Box/Unbox, or by generic sharing.
3340 encode_value ((MONO_AOT_METHODREF_GINST << 24), p, &p);
3341 /* Encode the klass */
3342 encode_klass_ref (acfg, method->klass, p, &p);
3343 /* Encode the method */
3344 image_index = get_image_index (acfg, method->klass->image);
3345 g_assert (image_index < MAX_IMAGE_INDEX);
3346 g_assert (declaring->token);
3347 token = declaring->token;
3348 g_assert (mono_metadata_token_table (token) == MONO_TABLE_METHOD);
3349 encode_value (image_index, p, &p);
3350 encode_value (token, p, &p);
3351 encode_generic_context (acfg, context, p, &p);
3353 } else if (token == 0) {
3354 /* This might be a method of a constructed type like int[,].Set */
3355 /* Obtain the token from information recorded by the JIT */
3356 ji = (MonoJumpInfoToken *)g_hash_table_lookup (acfg->token_info_hash, method);
3358 image_index = get_image_index (acfg, ji->image);
3359 g_assert (image_index < MAX_IMAGE_INDEX);
3362 encode_value ((MONO_AOT_METHODREF_METHODSPEC << 24), p, &p);
3363 encode_value (image_index, p, &p);
3364 encode_value (token, p, &p);
3367 g_assert (method->klass->rank);
3369 /* Encode directly */
3370 encode_value ((MONO_AOT_METHODREF_ARRAY << 24), p, &p);
3371 encode_klass_ref (acfg, method->klass, p, &p);
3372 if (!strcmp (method->name, ".ctor") && mono_method_signature (method)->param_count == method->klass->rank)
3373 encode_value (0, p, &p);
3374 else if (!strcmp (method->name, ".ctor") && mono_method_signature (method)->param_count == method->klass->rank * 2)
3375 encode_value (1, p, &p);
3376 else if (!strcmp (method->name, "Get"))
3377 encode_value (2, p, &p);
3378 else if (!strcmp (method->name, "Address"))
3379 encode_value (3, p, &p);
3380 else if (!strcmp (method->name, "Set"))
3381 encode_value (4, p, &p);
3383 g_assert_not_reached ();
3386 g_assert (mono_metadata_token_table (token) == MONO_TABLE_METHOD);
3388 if (image_index >= MONO_AOT_METHODREF_MIN) {
3389 encode_value ((MONO_AOT_METHODREF_LARGE_IMAGE_INDEX << 24), p, &p);
3390 encode_value (image_index, p, &p);
3391 encode_value (mono_metadata_token_index (token), p, &p);
3393 encode_value ((image_index << 24) | mono_metadata_token_index (token), p, &p);
3400 compare_patches (gconstpointer a, gconstpointer b)
3404 i = (*(MonoJumpInfo**)a)->ip.i;
3405 j = (*(MonoJumpInfo**)b)->ip.i;
3416 static G_GNUC_UNUSED char*
3417 patch_to_string (MonoJumpInfo *patch_info)
3421 str = g_string_new ("");
3423 g_string_append_printf (str, "%s(", get_patch_name (patch_info->type));
3425 switch (patch_info->type) {
3426 case MONO_PATCH_INFO_VTABLE:
3427 mono_type_get_desc (str, &patch_info->data.klass->byval_arg, TRUE);
3432 g_string_append_printf (str, ")");
3433 return g_string_free (str, FALSE);
3439 * Return whenever PATCH_INFO refers to a direct call, and thus requires a
3442 static inline gboolean
3443 is_plt_patch (MonoJumpInfo *patch_info)
3445 switch (patch_info->type) {
3446 case MONO_PATCH_INFO_METHOD:
3447 case MONO_PATCH_INFO_INTERNAL_METHOD:
3448 case MONO_PATCH_INFO_JIT_ICALL_ADDR:
3449 case MONO_PATCH_INFO_ICALL_ADDR_CALL:
3450 case MONO_PATCH_INFO_RGCTX_FETCH:
3460 * Return the symbol identifying the plt entry PLT_OFFSET.
3463 get_plt_symbol (MonoAotCompile *acfg, int plt_offset, MonoJumpInfo *patch_info)
3467 * The Apple linker reorganizes object files, so it doesn't like branches to local
3468 * labels, since those have no relocations.
3470 return g_strdup_printf ("%sp_%d", acfg->llvm_label_prefix, plt_offset);
3472 return g_strdup_printf ("%sp_%d", acfg->temp_prefix, plt_offset);
3479 * Return a PLT entry which belongs to the method identified by PATCH_INFO.
3481 static MonoPltEntry*
3482 get_plt_entry (MonoAotCompile *acfg, MonoJumpInfo *patch_info)
3485 gboolean synchronized = FALSE;
3486 static int synchronized_symbol_idx;
3488 if (!is_plt_patch (patch_info))
3491 if (!acfg->patch_to_plt_entry [patch_info->type])
3492 acfg->patch_to_plt_entry [patch_info->type] = g_hash_table_new (mono_patch_info_hash, mono_patch_info_equal);
3493 res = (MonoPltEntry *)g_hash_table_lookup (acfg->patch_to_plt_entry [patch_info->type], patch_info);
3495 if (!acfg->llvm && patch_info->type == MONO_PATCH_INFO_METHOD && (patch_info->data.method->iflags & METHOD_IMPL_ATTRIBUTE_SYNCHRONIZED)) {
3497 * Allocate a separate PLT slot for each such patch, since some plt
3498 * entries will refer to the method itself, and some will refer to the
3502 synchronized = TRUE;
3506 MonoJumpInfo *new_ji;
3508 new_ji = mono_patch_info_dup_mp (acfg->mempool, patch_info);
3510 res = (MonoPltEntry *)mono_mempool_alloc0 (acfg->mempool, sizeof (MonoPltEntry));
3511 res->plt_offset = acfg->plt_offset;
3513 res->symbol = get_plt_symbol (acfg, res->plt_offset, patch_info);
3514 if (acfg->aot_opts.write_symbols)
3515 res->debug_sym = get_plt_entry_debug_sym (acfg, res->ji, acfg->plt_entry_debug_sym_cache);
3517 /* Avoid duplicate symbols because we don't cache */
3518 res->symbol = g_strdup_printf ("%s_%d", res->symbol, synchronized_symbol_idx);
3520 res->debug_sym = g_strdup_printf ("%s_%d", res->debug_sym, synchronized_symbol_idx);
3521 synchronized_symbol_idx ++;
3524 res->llvm_symbol = g_strdup_printf ("%s_%s_llvm", res->symbol, res->debug_sym);
3526 res->llvm_symbol = g_strdup_printf ("%s_llvm", res->symbol);
3528 g_hash_table_insert (acfg->patch_to_plt_entry [new_ji->type], new_ji, res);
3530 g_hash_table_insert (acfg->plt_offset_to_entry, GUINT_TO_POINTER (res->plt_offset), res);
3532 //g_assert (mono_patch_info_equal (patch_info, new_ji));
3533 //mono_print_ji (patch_info); printf ("\n");
3534 //g_hash_table_print_stats (acfg->patch_to_plt_entry);
3536 acfg->plt_offset ++;
3545 * Returns the offset of the GOT slot where the runtime object resulting from resolving
3546 * JI could be found if it exists, otherwise allocates a new one.
3549 get_got_offset (MonoAotCompile *acfg, gboolean llvm, MonoJumpInfo *ji)
3552 GotInfo *info = llvm ? &acfg->llvm_got_info : &acfg->got_info;
3554 got_offset = GPOINTER_TO_UINT (g_hash_table_lookup (info->patch_to_got_offset_by_type [ji->type], ji));
3556 return got_offset - 1;
3559 got_offset = acfg->llvm_got_offset;
3560 acfg->llvm_got_offset ++;
3562 got_offset = acfg->got_offset;
3563 acfg->got_offset ++;
3566 acfg->stats.got_slots ++;
3567 acfg->stats.got_slot_types [ji->type] ++;
3569 g_hash_table_insert (info->patch_to_got_offset, ji, GUINT_TO_POINTER (got_offset + 1));
3570 g_hash_table_insert (info->patch_to_got_offset_by_type [ji->type], ji, GUINT_TO_POINTER (got_offset + 1));
3571 g_ptr_array_add (info->got_patches, ji);
3576 /* Add a method to the list of methods which need to be emitted */
3578 add_method_with_index (MonoAotCompile *acfg, MonoMethod *method, int index, gboolean extra)
3581 if (!g_hash_table_lookup (acfg->method_indexes, method)) {
3582 g_ptr_array_add (acfg->methods, method);
3583 g_hash_table_insert (acfg->method_indexes, method, GUINT_TO_POINTER (index + 1));
3584 acfg->nmethods = acfg->methods->len + 1;
3587 if (method->wrapper_type || extra)
3588 g_ptr_array_add (acfg->extra_methods, method);
3592 prefer_gsharedvt_method (MonoAotCompile *acfg, MonoMethod *method)
3594 /* One instantiation with valuetypes is generated for each async method */
3595 if (method->klass->image == mono_defaults.corlib && (!strcmp (method->klass->name, "AsyncMethodBuilderCore") || !strcmp (method->klass->name, "AsyncVoidMethodBuilder")))
3602 get_method_index (MonoAotCompile *acfg, MonoMethod *method)
3604 int index = GPOINTER_TO_UINT (g_hash_table_lookup (acfg->method_indexes, method));
3612 add_method_full (MonoAotCompile *acfg, MonoMethod *method, gboolean extra, int depth)
3616 index = GPOINTER_TO_UINT (g_hash_table_lookup (acfg->method_indexes, method));
3620 index = acfg->method_index;
3621 add_method_with_index (acfg, method, index, extra);
3623 g_ptr_array_add (acfg->method_order, GUINT_TO_POINTER (index));
3625 g_hash_table_insert (acfg->method_depth, method, GUINT_TO_POINTER (depth));
3627 acfg->method_index ++;
3633 add_method (MonoAotCompile *acfg, MonoMethod *method)
3635 return add_method_full (acfg, method, FALSE, 0);
3639 add_extra_method_with_depth (MonoAotCompile *acfg, MonoMethod *method, int depth)
3641 if (mono_method_is_generic_sharable_full (method, TRUE, TRUE, FALSE))
3642 method = mini_get_shared_method (method);
3643 else if ((acfg->opts & MONO_OPT_GSHAREDVT) && prefer_gsharedvt_method (acfg, method) && mono_method_is_generic_sharable_full (method, FALSE, FALSE, TRUE))
3644 /* Use the gsharedvt version */
3645 method = mini_get_shared_method_full (method, TRUE, TRUE);
3647 if (acfg->aot_opts.log_generics)
3648 aot_printf (acfg, "%*sAdding method %s.\n", depth, "", mono_method_get_full_name (method));
3650 add_method_full (acfg, method, TRUE, depth);
3654 add_extra_method (MonoAotCompile *acfg, MonoMethod *method)
3656 add_extra_method_with_depth (acfg, method, 0);
3660 add_jit_icall_wrapper (gpointer key, gpointer value, gpointer user_data)
3662 MonoAotCompile *acfg = (MonoAotCompile *)user_data;
3663 MonoJitICallInfo *callinfo = (MonoJitICallInfo *)value;
3664 MonoMethod *wrapper;
3670 name = g_strdup_printf ("__icall_wrapper_%s", callinfo->name);
3671 wrapper = mono_marshal_get_icall_wrapper (callinfo->sig, name, callinfo->func, TRUE);
3674 add_method (acfg, wrapper);
3678 get_runtime_invoke_sig (MonoMethodSignature *sig)
3680 MonoMethodBuilder *mb;
3683 mb = mono_mb_new (mono_defaults.object_class, "FOO", MONO_WRAPPER_NONE);
3684 m = mono_mb_create_method (mb, sig, 16);
3685 return mono_marshal_get_runtime_invoke (m, FALSE);
3689 get_runtime_invoke (MonoAotCompile *acfg, MonoMethod *method, gboolean virtual_)
3691 return mono_marshal_get_runtime_invoke (method, virtual_);
3695 can_marshal_struct (MonoClass *klass)
3697 MonoClassField *field;
3698 gboolean can_marshal = TRUE;
3699 gpointer iter = NULL;
3700 MonoMarshalType *info;
3703 if ((klass->flags & TYPE_ATTRIBUTE_LAYOUT_MASK) == TYPE_ATTRIBUTE_AUTO_LAYOUT)
3706 info = mono_marshal_load_type_info (klass);
3708 /* Only allow a few field types to avoid asserts in the marshalling code */
3709 while ((field = mono_class_get_fields (klass, &iter))) {
3710 if ((field->type->attrs & FIELD_ATTRIBUTE_STATIC))
3713 switch (field->type->type) {
3718 case MONO_TYPE_BOOLEAN:
3721 case MONO_TYPE_CHAR:
3729 case MONO_TYPE_STRING:
3731 case MONO_TYPE_VALUETYPE:
3732 if (!mono_class_from_mono_type (field->type)->enumtype && !can_marshal_struct (mono_class_from_mono_type (field->type)))
3733 can_marshal = FALSE;
3735 case MONO_TYPE_SZARRAY: {
3736 gboolean has_mspec = FALSE;
3739 for (i = 0; i < info->num_fields; ++i) {
3740 if (info->fields [i].field == field && info->fields [i].mspec)
3745 can_marshal = FALSE;
3749 can_marshal = FALSE;
3755 /* Its hard to compute whenever these can be marshalled or not */
3756 if (!strcmp (klass->name_space, "System.Net.NetworkInformation.MacOsStructs") && strcmp (klass->name, "sockaddr_dl"))
3763 create_gsharedvt_inst (MonoAotCompile *acfg, MonoMethod *method, MonoGenericContext *ctx)
3765 /* Create a vtype instantiation */
3766 MonoGenericContext shared_context;
3768 MonoGenericInst *inst;
3769 MonoGenericContainer *container;
3770 MonoClass **constraints;
3773 memset (ctx, 0, sizeof (MonoGenericContext));
3775 if (method->klass->generic_container) {
3776 shared_context = method->klass->generic_container->context;
3777 inst = shared_context.class_inst;
3779 args = g_new0 (MonoType*, inst->type_argc);
3780 for (i = 0; i < inst->type_argc; ++i) {
3781 args [i] = &mono_defaults.int_class->byval_arg;
3783 ctx->class_inst = mono_metadata_get_generic_inst (inst->type_argc, args);
3785 if (method->is_generic) {
3786 container = mono_method_get_generic_container (method);
3787 shared_context = container->context;
3788 inst = shared_context.method_inst;
3790 args = g_new0 (MonoType*, inst->type_argc);
3791 for (i = 0; i < container->type_argc; ++i) {
3792 MonoGenericParamInfo *info = &container->type_params [i].info;
3793 gboolean ref_only = FALSE;
3795 if (info && info->constraints) {
3796 constraints = info->constraints;
3798 while (*constraints) {
3799 MonoClass *cklass = *constraints;
3800 if (!(cklass == mono_defaults.object_class || (cklass->image == mono_defaults.corlib && !strcmp (cklass->name, "ValueType"))))
3801 /* Inflaring the method with our vtype would not be valid */
3808 args [i] = &mono_defaults.object_class->byval_arg;
3810 args [i] = &mono_defaults.int_class->byval_arg;
3812 ctx->method_inst = mono_metadata_get_generic_inst (inst->type_argc, args);
3817 add_wrappers (MonoAotCompile *acfg)
3819 MonoMethod *method, *m;
3821 MonoMethodSignature *sig, *csig;
3825 * FIXME: Instead of AOTing all the wrappers, it might be better to redesign them
3826 * so there is only one wrapper of a given type, or inlining their contents into their
3829 for (i = 0; i < acfg->image->tables [MONO_TABLE_METHOD].rows; ++i) {
3832 guint32 token = MONO_TOKEN_METHOD_DEF | (i + 1);
3833 gboolean skip = FALSE;
3835 method = mono_get_method_checked (acfg->image, token, NULL, NULL, &error);
3836 report_loader_error (acfg, &error, "Failed to load method token 0x%x due to %s\n", i, mono_error_get_message (&error));
3838 if ((method->flags & METHOD_ATTRIBUTE_PINVOKE_IMPL) ||
3839 (method->iflags & METHOD_IMPL_ATTRIBUTE_RUNTIME) ||
3840 (method->flags & METHOD_ATTRIBUTE_ABSTRACT))
3843 /* Skip methods which can not be handled by get_runtime_invoke () */
3844 sig = mono_method_signature (method);
3847 if ((sig->ret->type == MONO_TYPE_PTR) ||
3848 (sig->ret->type == MONO_TYPE_TYPEDBYREF))
3850 if (mono_class_is_open_constructed_type (sig->ret))
3853 for (j = 0; j < sig->param_count; j++) {
3854 if (sig->params [j]->type == MONO_TYPE_TYPEDBYREF)
3856 if (mono_class_is_open_constructed_type (sig->params [j]))
3860 #ifdef MONO_ARCH_DYN_CALL_SUPPORTED
3861 if (!mono_class_is_contextbound (method->klass)) {
3862 MonoDynCallInfo *info = mono_arch_dyn_call_prepare (sig);
3863 gboolean has_nullable = FALSE;
3865 for (j = 0; j < sig->param_count; j++) {
3866 if (sig->params [j]->type == MONO_TYPE_GENERICINST && mono_class_is_nullable (mono_class_from_mono_type (sig->params [j])))
3867 has_nullable = TRUE;
3870 if (info && !has_nullable && !acfg->aot_opts.llvm_only) {
3871 /* Supported by the dynamic runtime-invoke wrapper */
3875 mono_arch_dyn_call_free (info);
3879 if (acfg->aot_opts.llvm_only)
3880 /* Supported by the gsharedvt based runtime-invoke wrapper */
3884 //printf ("%s\n", mono_method_full_name (method, TRUE));
3885 add_method (acfg, get_runtime_invoke (acfg, method, FALSE));
3889 if (strcmp (acfg->image->assembly->aname.name, "mscorlib") == 0) {
3892 /* Runtime invoke wrappers */
3894 /* void runtime-invoke () [.cctor] */
3895 csig = mono_metadata_signature_alloc (mono_defaults.corlib, 0);
3896 csig->ret = &mono_defaults.void_class->byval_arg;
3897 add_method (acfg, get_runtime_invoke_sig (csig));
3899 /* void runtime-invoke () [Finalize] */
3900 csig = mono_metadata_signature_alloc (mono_defaults.corlib, 0);
3902 csig->ret = &mono_defaults.void_class->byval_arg;
3903 add_method (acfg, get_runtime_invoke_sig (csig));
3905 /* void runtime-invoke (string) [exception ctor] */
3906 csig = mono_metadata_signature_alloc (mono_defaults.corlib, 1);
3908 csig->ret = &mono_defaults.void_class->byval_arg;
3909 csig->params [0] = &mono_defaults.string_class->byval_arg;
3910 add_method (acfg, get_runtime_invoke_sig (csig));
3912 /* void runtime-invoke (string, string) [exception ctor] */
3913 csig = mono_metadata_signature_alloc (mono_defaults.corlib, 2);
3915 csig->ret = &mono_defaults.void_class->byval_arg;
3916 csig->params [0] = &mono_defaults.string_class->byval_arg;
3917 csig->params [1] = &mono_defaults.string_class->byval_arg;
3918 add_method (acfg, get_runtime_invoke_sig (csig));
3920 /* string runtime-invoke () [Exception.ToString ()] */
3921 csig = mono_metadata_signature_alloc (mono_defaults.corlib, 0);
3923 csig->ret = &mono_defaults.string_class->byval_arg;
3924 add_method (acfg, get_runtime_invoke_sig (csig));
3926 /* void runtime-invoke (string, Exception) [exception ctor] */
3927 csig = mono_metadata_signature_alloc (mono_defaults.corlib, 2);
3929 csig->ret = &mono_defaults.void_class->byval_arg;
3930 csig->params [0] = &mono_defaults.string_class->byval_arg;
3931 csig->params [1] = &mono_defaults.exception_class->byval_arg;
3932 add_method (acfg, get_runtime_invoke_sig (csig));
3934 /* Assembly runtime-invoke (string, bool) [DoAssemblyResolve] */
3935 csig = mono_metadata_signature_alloc (mono_defaults.corlib, 2);
3937 csig->ret = &(mono_class_load_from_name (
3938 mono_defaults.corlib, "System.Reflection", "Assembly"))->byval_arg;
3939 csig->params [0] = &mono_defaults.string_class->byval_arg;
3940 csig->params [1] = &mono_defaults.boolean_class->byval_arg;
3941 add_method (acfg, get_runtime_invoke_sig (csig));
3943 /* runtime-invoke used by finalizers */
3944 add_method (acfg, get_runtime_invoke (acfg, mono_class_get_method_from_name_flags (mono_defaults.object_class, "Finalize", 0, 0), TRUE));
3946 /* This is used by mono_runtime_capture_context () */
3947 method = mono_get_context_capture_method ();
3949 add_method (acfg, get_runtime_invoke (acfg, method, FALSE));
3951 #ifdef MONO_ARCH_DYN_CALL_SUPPORTED
3952 if (!acfg->aot_opts.llvm_only)
3953 add_method (acfg, mono_marshal_get_runtime_invoke_dynamic ());
3956 /* These are used by mono_jit_runtime_invoke () to calls gsharedvt out wrappers */
3957 if (acfg->aot_opts.llvm_only) {
3960 /* Create simplified signatures which match the signature used by the gsharedvt out wrappers */
3961 for (variants = 0; variants < 4; ++variants) {
3962 for (i = 0; i < 16; ++i) {
3963 sig = mini_get_gsharedvt_out_sig_wrapper_signature ((variants & 1) > 0, (variants & 2) > 0, i);
3964 add_extra_method (acfg, mono_marshal_get_runtime_invoke_for_sig (sig));
3972 add_method (acfg, mono_marshal_get_stelemref ());
3974 if (MONO_ARCH_HAVE_TLS_GET) {
3975 /* Managed Allocators */
3976 nallocators = mono_gc_get_managed_allocator_types ();
3977 for (i = 0; i < nallocators; ++i) {
3978 m = mono_gc_get_managed_allocator_by_type (i, TRUE);
3980 add_method (acfg, m);
3982 for (i = 0; i < nallocators; ++i) {
3983 m = mono_gc_get_managed_allocator_by_type (i, FALSE);
3985 add_method (acfg, m);
3989 /* write barriers */
3990 if (mono_gc_is_moving ()) {
3991 add_method (acfg, mono_gc_get_specific_write_barrier (FALSE));
3992 add_method (acfg, mono_gc_get_specific_write_barrier (TRUE));
3995 /* Stelemref wrappers */
3997 MonoMethod **wrappers;
4000 wrappers = mono_marshal_get_virtual_stelemref_wrappers (&nwrappers);
4001 for (i = 0; i < nwrappers; ++i)
4002 add_method (acfg, wrappers [i]);
4006 /* castclass_with_check wrapper */
4007 add_method (acfg, mono_marshal_get_castclass_with_cache ());
4008 /* isinst_with_check wrapper */
4009 add_method (acfg, mono_marshal_get_isinst_with_cache ());
4011 /* JIT icall wrappers */
4012 /* FIXME: locking - this is "safe" as full-AOT threads don't mutate the icall hash*/
4013 g_hash_table_foreach (mono_get_jit_icall_info (), add_jit_icall_wrapper, acfg);
4017 * remoting-invoke-with-check wrappers are very frequent, so avoid emitting them,
4018 * we use the original method instead at runtime.
4019 * Since full-aot doesn't support remoting, this is not a problem.
4022 /* remoting-invoke wrappers */
4023 for (i = 0; i < acfg->image->tables [MONO_TABLE_METHOD].rows; ++i) {
4025 MonoMethodSignature *sig;
4027 token = MONO_TOKEN_METHOD_DEF | (i + 1);
4028 method = mono_get_method_checked (acfg->image, token, NULL, NULL, &error);
4029 g_assert (mono_error_ok (&error)); /* FIXME don't swallow the error */
4031 sig = mono_method_signature (method);
4033 if (sig->hasthis && (method->klass->marshalbyref || method->klass == mono_defaults.object_class)) {
4034 m = mono_marshal_get_remoting_invoke_with_check (method);
4036 add_method (acfg, m);
4041 /* delegate-invoke wrappers */
4042 for (i = 0; i < acfg->image->tables [MONO_TABLE_TYPEDEF].rows; ++i) {
4045 MonoCustomAttrInfo *cattr;
4047 token = MONO_TOKEN_TYPE_DEF | (i + 1);
4048 klass = mono_class_get_checked (acfg->image, token, &error);
4051 mono_error_cleanup (&error);
4055 if (!klass->delegate || klass == mono_defaults.delegate_class || klass == mono_defaults.multicastdelegate_class)
4058 if (!klass->generic_container) {
4059 method = mono_get_delegate_invoke (klass);
4061 m = mono_marshal_get_delegate_invoke (method, NULL);
4063 add_method (acfg, m);
4065 method = mono_class_get_method_from_name_flags (klass, "BeginInvoke", -1, 0);
4067 add_method (acfg, mono_marshal_get_delegate_begin_invoke (method));
4069 method = mono_class_get_method_from_name_flags (klass, "EndInvoke", -1, 0);
4071 add_method (acfg, mono_marshal_get_delegate_end_invoke (method));
4073 cattr = mono_custom_attrs_from_class_checked (klass, &error);
4074 if (!is_ok (&error)) {
4075 mono_error_cleanup (&error);
4082 for (j = 0; j < cattr->num_attrs; ++j)
4083 if (cattr->attrs [j].ctor && (!strcmp (cattr->attrs [j].ctor->klass->name, "MonoNativeFunctionWrapperAttribute") || !strcmp (cattr->attrs [j].ctor->klass->name, "UnmanagedFunctionPointerAttribute")))
4085 if (j < cattr->num_attrs) {
4087 MonoMethod *wrapper;
4088 MonoMethod *del_invoke;
4090 /* Add wrappers needed by mono_ftnptr_to_delegate () */
4091 invoke = mono_get_delegate_invoke (klass);
4092 wrapper = mono_marshal_get_native_func_wrapper_aot (klass);
4093 del_invoke = mono_marshal_get_delegate_invoke_internal (invoke, FALSE, TRUE, wrapper);
4094 add_method (acfg, wrapper);
4095 add_method (acfg, del_invoke);
4098 } else if ((acfg->opts & MONO_OPT_GSHAREDVT) && klass->generic_container) {
4100 MonoGenericContext ctx;
4101 MonoMethod *inst, *gshared;
4104 * Emit gsharedvt versions of the generic delegate-invoke wrappers
4107 method = mono_get_delegate_invoke (klass);
4108 create_gsharedvt_inst (acfg, method, &ctx);
4110 inst = mono_class_inflate_generic_method_checked (method, &ctx, &error);
4111 g_assert (mono_error_ok (&error)); /* FIXME don't swallow the error */
4113 m = mono_marshal_get_delegate_invoke (inst, NULL);
4114 g_assert (m->is_inflated);
4116 gshared = mini_get_shared_method_full (m, FALSE, TRUE);
4117 add_extra_method (acfg, gshared);
4120 method = mono_get_delegate_begin_invoke (klass);
4121 create_gsharedvt_inst (acfg, method, &ctx);
4123 inst = mono_class_inflate_generic_method_checked (method, &ctx, &error);
4124 g_assert (mono_error_ok (&error)); /* FIXME don't swallow the error */
4126 m = mono_marshal_get_delegate_begin_invoke (inst);
4127 g_assert (m->is_inflated);
4129 gshared = mini_get_shared_method_full (m, FALSE, TRUE);
4130 add_extra_method (acfg, gshared);
4133 method = mono_get_delegate_end_invoke (klass);
4134 create_gsharedvt_inst (acfg, method, &ctx);
4136 inst = mono_class_inflate_generic_method_checked (method, &ctx, &error);
4137 g_assert (mono_error_ok (&error)); /* FIXME don't swallow the error */
4139 m = mono_marshal_get_delegate_end_invoke (inst);
4140 g_assert (m->is_inflated);
4142 gshared = mini_get_shared_method_full (m, FALSE, TRUE);
4143 add_extra_method (acfg, gshared);
4148 /* array access wrappers */
4149 for (i = 0; i < acfg->image->tables [MONO_TABLE_TYPESPEC].rows; ++i) {
4153 token = MONO_TOKEN_TYPE_SPEC | (i + 1);
4154 klass = mono_class_get_checked (acfg->image, token, &error);
4157 mono_error_cleanup (&error);
4161 if (!acfg->aot_opts.llvm_only && klass->rank && MONO_TYPE_IS_PRIMITIVE (&klass->element_class->byval_arg)) {
4162 MonoMethod *m, *wrapper;
4164 /* Add runtime-invoke wrappers too */
4166 m = mono_class_get_method_from_name (klass, "Get", -1);
4168 wrapper = mono_marshal_get_array_accessor_wrapper (m);
4169 add_extra_method (acfg, wrapper);
4170 add_extra_method (acfg, get_runtime_invoke (acfg, wrapper, FALSE));
4172 m = mono_class_get_method_from_name (klass, "Set", -1);
4174 wrapper = mono_marshal_get_array_accessor_wrapper (m);
4175 add_extra_method (acfg, wrapper);
4176 add_extra_method (acfg, get_runtime_invoke (acfg, wrapper, FALSE));
4180 /* Synchronized wrappers */
4181 for (i = 0; i < acfg->image->tables [MONO_TABLE_METHOD].rows; ++i) {
4183 token = MONO_TOKEN_METHOD_DEF | (i + 1);
4184 method = mono_get_method_checked (acfg->image, token, NULL, NULL, &error);
4185 report_loader_error (acfg, &error, "Failed to load method token 0x%x due to %s\n", i, mono_error_get_message (&error));
4187 if (method->iflags & METHOD_IMPL_ATTRIBUTE_SYNCHRONIZED) {
4188 if (method->is_generic) {
4190 } else if ((acfg->opts & MONO_OPT_GSHAREDVT) && method->klass->generic_container) {
4192 MonoGenericContext ctx;
4193 MonoMethod *inst, *gshared, *m;
4196 * Create a generic wrapper for a generic instance, and AOT that.
4198 create_gsharedvt_inst (acfg, method, &ctx);
4199 inst = mono_class_inflate_generic_method_checked (method, &ctx, &error);
4200 g_assert (mono_error_ok (&error)); /* FIXME don't swallow the error */
4201 m = mono_marshal_get_synchronized_wrapper (inst);
4202 g_assert (m->is_inflated);
4203 gshared = mini_get_shared_method_full (m, FALSE, TRUE);
4204 add_method (acfg, gshared);
4206 add_method (acfg, mono_marshal_get_synchronized_wrapper (method));
4211 /* pinvoke wrappers */
4212 for (i = 0; i < acfg->image->tables [MONO_TABLE_METHOD].rows; ++i) {
4215 guint32 token = MONO_TOKEN_METHOD_DEF | (i + 1);
4217 method = mono_get_method_checked (acfg->image, token, NULL, NULL, &error);
4218 report_loader_error (acfg, &error, "Failed to load method token 0x%x due to %s\n", i, mono_error_get_message (&error));
4220 if ((method->flags & METHOD_ATTRIBUTE_PINVOKE_IMPL) ||
4221 (method->iflags & METHOD_IMPL_ATTRIBUTE_INTERNAL_CALL)) {
4222 add_method (acfg, mono_marshal_get_native_wrapper (method, TRUE, TRUE));
4226 /* native-to-managed wrappers */
4227 for (i = 0; i < acfg->image->tables [MONO_TABLE_METHOD].rows; ++i) {
4230 guint32 token = MONO_TOKEN_METHOD_DEF | (i + 1);
4231 MonoCustomAttrInfo *cattr;
4234 method = mono_get_method_checked (acfg->image, token, NULL, NULL, &error);
4235 report_loader_error (acfg, &error, "Failed to load method token 0x%x due to %s\n", i, mono_error_get_message (&error));
4238 * Only generate native-to-managed wrappers for methods which have an
4239 * attribute named MonoPInvokeCallbackAttribute. We search for the attribute by
4240 * name to avoid defining a new assembly to contain it.
4242 cattr = mono_custom_attrs_from_method_checked (method, &error);
4243 if (!is_ok (&error)) {
4244 char *name = mono_method_get_full_name (method);
4245 report_loader_error (acfg, &error, "Failed to load custom attributes from method %s due to %s\n", name, mono_error_get_message (&error));
4250 for (j = 0; j < cattr->num_attrs; ++j)
4251 if (cattr->attrs [j].ctor && !strcmp (cattr->attrs [j].ctor->klass->name, "MonoPInvokeCallbackAttribute"))
4253 if (j < cattr->num_attrs) {
4254 MonoCustomAttrEntry *e = &cattr->attrs [j];
4255 MonoMethodSignature *sig = mono_method_signature (e->ctor);
4256 const char *p = (const char*)e->data;
4258 int slen, num_named, named_type;
4262 char *export_name = NULL;
4263 MonoMethod *wrapper;
4265 /* this cannot be enforced by the C# compiler so we must give the user some warning before aborting */
4266 if (!(method->flags & METHOD_ATTRIBUTE_STATIC)) {
4267 g_warning ("AOT restriction: Method '%s' must be static since it is decorated with [MonoPInvokeCallback]. See http://ios.xamarin.com/Documentation/Limitations#Reverse_Callbacks",
4268 mono_method_full_name (method, TRUE));
4272 g_assert (sig->param_count == 1);
4273 g_assert (sig->params [0]->type == MONO_TYPE_CLASS && !strcmp (mono_class_from_mono_type (sig->params [0])->name, "Type"));
4276 * Decode the cattr manually since we can't create objects
4277 * during aot compilation.
4283 /* From load_cattr_value () in reflection.c */
4284 slen = mono_metadata_decode_value (p, &p);
4285 n = (char *)g_memdup (p, slen + 1);
4287 t = mono_reflection_type_from_name_checked (n, acfg->image, &error);
4289 mono_error_assert_ok (&error);
4292 klass = mono_class_from_mono_type (t);
4293 g_assert (klass->parent == mono_defaults.multicastdelegate_class);
4297 num_named = read16 (p);
4300 g_assert (num_named < 2);
4301 if (num_named == 1) {
4305 /* parse ExportSymbol attribute */
4307 named_type = *named;
4309 /* data_type = *named; */
4312 name_len = mono_metadata_decode_blob_size (named, &named);
4313 name = (char *)g_malloc (name_len + 1);
4314 memcpy (name, named, name_len);
4315 name [name_len] = 0;
4318 g_assert (named_type == 0x54);
4319 g_assert (!strcmp (name, "ExportSymbol"));
4321 /* load_cattr_value (), string case */
4322 g_assert (*named != (char)0xff);
4323 slen = mono_metadata_decode_value (named, &named);
4324 export_name = (char *)g_malloc (slen + 1);
4325 memcpy (export_name, named, slen);
4326 export_name [slen] = 0;
4330 wrapper = mono_marshal_get_managed_wrapper (method, klass, 0);
4331 add_method (acfg, wrapper);
4333 g_hash_table_insert (acfg->export_names, wrapper, export_name);
4337 if ((method->flags & METHOD_ATTRIBUTE_PINVOKE_IMPL) ||
4338 (method->iflags & METHOD_IMPL_ATTRIBUTE_INTERNAL_CALL)) {
4339 add_method (acfg, mono_marshal_get_native_wrapper (method, TRUE, TRUE));
4343 /* StructureToPtr/PtrToStructure wrappers */
4344 for (i = 0; i < acfg->image->tables [MONO_TABLE_TYPEDEF].rows; ++i) {
4348 token = MONO_TOKEN_TYPE_DEF | (i + 1);
4349 klass = mono_class_get_checked (acfg->image, token, &error);
4352 mono_error_cleanup (&error);
4356 if (klass->valuetype && !klass->generic_container && can_marshal_struct (klass) &&
4357 !(klass->nested_in && strstr (klass->nested_in->name, "<PrivateImplementationDetails>") == klass->nested_in->name)) {
4358 add_method (acfg, mono_marshal_get_struct_to_ptr (klass));
4359 add_method (acfg, mono_marshal_get_ptr_to_struct (klass));
4365 has_type_vars (MonoClass *klass)
4367 if ((klass->byval_arg.type == MONO_TYPE_VAR) || (klass->byval_arg.type == MONO_TYPE_MVAR))
4370 return has_type_vars (klass->element_class);
4371 if (klass->generic_class) {
4372 MonoGenericContext *context = &klass->generic_class->context;
4373 if (context->class_inst) {
4376 for (i = 0; i < context->class_inst->type_argc; ++i)
4377 if (has_type_vars (mono_class_from_mono_type (context->class_inst->type_argv [i])))
4381 if (klass->generic_container)
4387 is_vt_inst (MonoGenericInst *inst)
4391 for (i = 0; i < inst->type_argc; ++i) {
4392 MonoType *t = inst->type_argv [i];
4393 if (MONO_TYPE_ISSTRUCT (t) || t->type == MONO_TYPE_VALUETYPE)
4400 method_has_type_vars (MonoMethod *method)
4402 if (has_type_vars (method->klass))
4405 if (method->is_inflated) {
4406 MonoGenericContext *context = mono_method_get_context (method);
4407 if (context->method_inst) {
4410 for (i = 0; i < context->method_inst->type_argc; ++i)
4411 if (has_type_vars (mono_class_from_mono_type (context->method_inst->type_argv [i])))
4419 gboolean mono_aot_mode_is_full (MonoAotOptions *opts)
4421 return opts->mode == MONO_AOT_MODE_FULL;
4424 static void add_generic_class_with_depth (MonoAotCompile *acfg, MonoClass *klass, int depth, const char *ref);
4427 add_generic_class (MonoAotCompile *acfg, MonoClass *klass, gboolean force, const char *ref)
4429 /* This might lead to a huge code blowup so only do it if neccesary */
4430 if (!mono_aot_mode_is_full (&acfg->aot_opts) && !force)
4433 add_generic_class_with_depth (acfg, klass, 0, ref);
4437 check_type_depth (MonoType *t, int depth)
4445 case MONO_TYPE_GENERICINST: {
4446 MonoGenericClass *gklass = t->data.generic_class;
4447 MonoGenericInst *ginst = gklass->context.class_inst;
4450 for (i = 0; i < ginst->type_argc; ++i) {
4451 if (check_type_depth (ginst->type_argv [i], depth + 1))
4465 add_types_from_method_header (MonoAotCompile *acfg, MonoMethod *method);
4468 * add_generic_class:
4470 * Add all methods of a generic class.
4473 add_generic_class_with_depth (MonoAotCompile *acfg, MonoClass *klass, int depth, const char *ref)
4476 MonoClassField *field;
4478 gboolean use_gsharedvt = FALSE;
4480 if (!acfg->ginst_hash)
4481 acfg->ginst_hash = g_hash_table_new (NULL, NULL);
4483 mono_class_init (klass);
4485 if (klass->generic_class && klass->generic_class->context.class_inst->is_open)
4488 if (has_type_vars (klass))
4491 if (!klass->generic_class && !klass->rank)
4494 if (mono_class_has_failure (klass))
4497 if (!acfg->ginst_hash)
4498 acfg->ginst_hash = g_hash_table_new (NULL, NULL);
4500 if (g_hash_table_lookup (acfg->ginst_hash, klass))
4503 if (check_type_depth (&klass->byval_arg, 0))
4506 if (acfg->aot_opts.log_generics)
4507 aot_printf (acfg, "%*sAdding generic instance %s [%s].\n", depth, "", mono_type_full_name (&klass->byval_arg), ref);
4509 g_hash_table_insert (acfg->ginst_hash, klass, klass);
4512 * Use gsharedvt for generic collections with vtype arguments to avoid code blowup.
4513 * Enable this only for some classes since gsharedvt might not support all methods.
4515 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) &&
4516 (!strcmp (klass->name, "Dictionary`2") || !strcmp (klass->name, "List`1") || !strcmp (klass->name, "ReadOnlyCollection`1")))
4517 use_gsharedvt = TRUE;
4520 while ((method = mono_class_get_methods (klass, &iter))) {
4521 if ((acfg->opts & MONO_OPT_GSHAREDVT) && method->is_inflated && mono_method_get_context (method)->method_inst) {
4523 * This is partial sharing, and we can't handle it yet
4528 if (mono_method_is_generic_sharable_full (method, FALSE, FALSE, use_gsharedvt)) {
4530 add_types_from_method_header (acfg, method);
4534 if (method->is_generic)
4539 * FIXME: Instances which are referenced by these methods are not added,
4540 * for example Array.Resize<int> for List<int>.Add ().
4542 add_extra_method_with_depth (acfg, method, depth + 1);
4546 while ((field = mono_class_get_fields (klass, &iter))) {
4547 if (field->type->type == MONO_TYPE_GENERICINST)
4548 add_generic_class_with_depth (acfg, mono_class_from_mono_type (field->type), depth + 1, "field");
4551 if (klass->delegate) {
4552 method = mono_get_delegate_invoke (klass);
4554 method = mono_marshal_get_delegate_invoke (method, NULL);
4556 if (acfg->aot_opts.log_generics)
4557 aot_printf (acfg, "%*sAdding method %s.\n", depth, "", mono_method_get_full_name (method));
4559 add_method (acfg, method);
4562 /* Add superclasses */
4564 add_generic_class_with_depth (acfg, klass->parent, depth, "parent");
4567 * For ICollection<T>, add instances of the helper methods
4568 * in Array, since a T[] could be cast to ICollection<T>.
4570 if (klass->image == mono_defaults.corlib && !strcmp (klass->name_space, "System.Collections.Generic") &&
4571 (!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"))) {
4572 MonoClass *tclass = mono_class_from_mono_type (klass->generic_class->context.class_inst->type_argv [0]);
4573 MonoClass *array_class = mono_bounded_array_class_get (tclass, 1, FALSE);
4577 if (!strcmp (klass->name, "IEnumerator`1"))
4578 name_prefix = g_strdup_printf ("%s.%s", klass->name_space, "IEnumerable`1");
4580 name_prefix = g_strdup_printf ("%s.%s", klass->name_space, klass->name);
4582 /* Add the T[]/InternalEnumerator class */
4583 if (!strcmp (klass->name, "IEnumerable`1") || !strcmp (klass->name, "IEnumerator`1")) {
4588 while ((nclass = mono_class_get_nested_types (array_class->parent, &iter))) {
4589 if (!strcmp (nclass->name, "InternalEnumerator`1"))
4593 nclass = mono_class_inflate_generic_class_checked (nclass, mono_generic_class_get_context (klass->generic_class), &error);
4594 mono_error_assert_ok (&error); /* FIXME don't swallow the error */
4595 add_generic_class (acfg, nclass, FALSE, "ICollection<T>");
4599 while ((method = mono_class_get_methods (array_class, &iter))) {
4600 if (strstr (method->name, name_prefix)) {
4601 MonoMethod *m = mono_aot_get_array_helper_from_wrapper (method);
4603 add_extra_method_with_depth (acfg, m, depth);
4607 g_free (name_prefix);
4610 /* Add an instance of GenericComparer<T> which is created dynamically by Comparer<T> */
4611 if (klass->image == mono_defaults.corlib && !strcmp (klass->name_space, "System.Collections.Generic") && !strcmp (klass->name, "Comparer`1")) {
4613 MonoClass *tclass = mono_class_from_mono_type (klass->generic_class->context.class_inst->type_argv [0]);
4614 MonoClass *icomparable, *gcomparer, *icomparable_inst;
4615 MonoGenericContext ctx;
4616 MonoType *args [16];
4618 memset (&ctx, 0, sizeof (ctx));
4620 icomparable = mono_class_load_from_name (mono_defaults.corlib, "System", "IComparable`1");
4622 args [0] = &tclass->byval_arg;
4623 ctx.class_inst = mono_metadata_get_generic_inst (1, args);
4625 icomparable_inst = mono_class_inflate_generic_class_checked (icomparable, &ctx, &error);
4626 mono_error_assert_ok (&error); /* FIXME don't swallow the error */
4628 if (mono_class_is_assignable_from (icomparable_inst, tclass)) {
4629 MonoClass *gcomparer_inst;
4630 gcomparer = mono_class_load_from_name (mono_defaults.corlib, "System.Collections.Generic", "GenericComparer`1");
4631 gcomparer_inst = mono_class_inflate_generic_class_checked (gcomparer, &ctx, &error);
4632 mono_error_assert_ok (&error); /* FIXME don't swallow the error */
4634 add_generic_class (acfg, gcomparer_inst, FALSE, "Comparer<T>");
4638 /* Add an instance of GenericEqualityComparer<T> which is created dynamically by EqualityComparer<T> */
4639 if (klass->image == mono_defaults.corlib && !strcmp (klass->name_space, "System.Collections.Generic") && !strcmp (klass->name, "EqualityComparer`1")) {
4641 MonoClass *tclass = mono_class_from_mono_type (klass->generic_class->context.class_inst->type_argv [0]);
4642 MonoClass *iface, *gcomparer, *iface_inst;
4643 MonoGenericContext ctx;
4644 MonoType *args [16];
4646 memset (&ctx, 0, sizeof (ctx));
4648 iface = mono_class_load_from_name (mono_defaults.corlib, "System", "IEquatable`1");
4650 args [0] = &tclass->byval_arg;
4651 ctx.class_inst = mono_metadata_get_generic_inst (1, args);
4653 iface_inst = mono_class_inflate_generic_class_checked (iface, &ctx, &error);
4654 mono_error_assert_ok (&error); /* FIXME don't swallow the error */
4656 if (mono_class_is_assignable_from (iface_inst, tclass)) {
4657 MonoClass *gcomparer_inst;
4660 gcomparer = mono_class_load_from_name (mono_defaults.corlib, "System.Collections.Generic", "GenericEqualityComparer`1");
4661 gcomparer_inst = mono_class_inflate_generic_class_checked (gcomparer, &ctx, &error);
4662 mono_error_assert_ok (&error); /* FIXME don't swallow the error */
4663 add_generic_class (acfg, gcomparer_inst, FALSE, "EqualityComparer<T>");
4667 /* Add an instance of EnumComparer<T> which is created dynamically by EqualityComparer<T> for enums */
4668 if (klass->image == mono_defaults.corlib && !strcmp (klass->name_space, "System.Collections.Generic") && !strcmp (klass->name, "EqualityComparer`1")) {
4669 MonoClass *enum_comparer;
4670 MonoClass *tclass = mono_class_from_mono_type (klass->generic_class->context.class_inst->type_argv [0]);
4671 MonoGenericContext ctx;
4672 MonoType *args [16];
4674 if (mono_class_is_enum (tclass)) {
4675 MonoClass *enum_comparer_inst;
4678 memset (&ctx, 0, sizeof (ctx));
4679 args [0] = &tclass->byval_arg;
4680 ctx.class_inst = mono_metadata_get_generic_inst (1, args);
4682 enum_comparer = mono_class_load_from_name (mono_defaults.corlib, "System.Collections.Generic", "EnumEqualityComparer`1");
4683 enum_comparer_inst = mono_class_inflate_generic_class_checked (enum_comparer, &ctx, &error);
4684 mono_error_assert_ok (&error); /* FIXME don't swallow the error */
4685 add_generic_class (acfg, enum_comparer_inst, FALSE, "EqualityComparer<T>");
4689 /* Add an instance of ObjectComparer<T> which is created dynamically by Comparer<T> for enums */
4690 if (klass->image == mono_defaults.corlib && !strcmp (klass->name_space, "System.Collections.Generic") && !strcmp (klass->name, "Comparer`1")) {
4691 MonoClass *comparer;
4692 MonoClass *tclass = mono_class_from_mono_type (klass->generic_class->context.class_inst->type_argv [0]);
4693 MonoGenericContext ctx;
4694 MonoType *args [16];
4696 if (mono_class_is_enum (tclass)) {
4697 MonoClass *comparer_inst;
4700 memset (&ctx, 0, sizeof (ctx));
4701 args [0] = &tclass->byval_arg;
4702 ctx.class_inst = mono_metadata_get_generic_inst (1, args);
4704 comparer = mono_class_load_from_name (mono_defaults.corlib, "System.Collections.Generic", "ObjectComparer`1");
4705 comparer_inst = mono_class_inflate_generic_class_checked (comparer, &ctx, &error);
4706 mono_error_assert_ok (&error); /* FIXME don't swallow the error */
4707 add_generic_class (acfg, comparer_inst, FALSE, "Comparer<T>");
4713 add_instances_of (MonoAotCompile *acfg, MonoClass *klass, MonoType **insts, int ninsts, gboolean force)
4716 MonoGenericContext ctx;
4717 MonoType *args [16];
4719 if (acfg->aot_opts.no_instances)
4722 memset (&ctx, 0, sizeof (ctx));
4724 for (i = 0; i < ninsts; ++i) {
4726 MonoClass *generic_inst;
4727 args [0] = insts [i];
4728 ctx.class_inst = mono_metadata_get_generic_inst (1, args);
4729 generic_inst = mono_class_inflate_generic_class_checked (klass, &ctx, &error);
4730 mono_error_assert_ok (&error); /* FIXME don't swallow the error */
4731 add_generic_class (acfg, generic_inst, force, "");
4736 add_types_from_method_header (MonoAotCompile *acfg, MonoMethod *method)
4739 MonoMethodHeader *header;
4740 MonoMethodSignature *sig;
4743 depth = GPOINTER_TO_UINT (g_hash_table_lookup (acfg->method_depth, method));
4745 sig = mono_method_signature (method);
4748 for (j = 0; j < sig->param_count; ++j)
4749 if (sig->params [j]->type == MONO_TYPE_GENERICINST)
4750 add_generic_class_with_depth (acfg, mono_class_from_mono_type (sig->params [j]), depth + 1, "arg");
4753 header = mono_method_get_header_checked (method, &error);
4756 for (j = 0; j < header->num_locals; ++j)
4757 if (header->locals [j]->type == MONO_TYPE_GENERICINST)
4758 add_generic_class_with_depth (acfg, mono_class_from_mono_type (header->locals [j]), depth + 1, "local");
4760 mono_error_cleanup (&error); /* FIXME report the error */
4765 * add_generic_instances:
4767 * Add instances referenced by the METHODSPEC/TYPESPEC table.
4770 add_generic_instances (MonoAotCompile *acfg)
4775 MonoGenericContext *context;
4777 if (acfg->aot_opts.no_instances)
4780 for (i = 0; i < acfg->image->tables [MONO_TABLE_METHODSPEC].rows; ++i) {
4782 token = MONO_TOKEN_METHOD_SPEC | (i + 1);
4783 method = mono_get_method_checked (acfg->image, token, NULL, NULL, &error);
4786 aot_printerrf (acfg, "Failed to load methodspec 0x%x due to %s.\n", token, mono_error_get_message (&error));
4787 aot_printerrf (acfg, "Run with MONO_LOG_LEVEL=debug for more information.\n");
4788 mono_error_cleanup (&error);
4792 if (method->klass->image != acfg->image)
4795 context = mono_method_get_context (method);
4797 if (context && ((context->class_inst && context->class_inst->is_open)))
4801 * For open methods, create an instantiation which can be passed to the JIT.
4802 * FIXME: Handle class_inst as well.
4804 if (context && context->method_inst && context->method_inst->is_open) {
4806 MonoGenericContext shared_context;
4807 MonoGenericInst *inst;
4808 MonoType **type_argv;
4810 MonoMethod *declaring_method;
4811 gboolean supported = TRUE;
4813 /* Check that the context doesn't contain open constructed types */
4814 if (context->class_inst) {
4815 inst = context->class_inst;
4816 for (i = 0; i < inst->type_argc; ++i) {
4817 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)
4819 if (mono_class_is_open_constructed_type (inst->type_argv [i]))
4823 if (context->method_inst) {
4824 inst = context->method_inst;
4825 for (i = 0; i < inst->type_argc; ++i) {
4826 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)
4828 if (mono_class_is_open_constructed_type (inst->type_argv [i]))
4836 memset (&shared_context, 0, sizeof (MonoGenericContext));
4838 inst = context->class_inst;
4840 type_argv = g_new0 (MonoType*, inst->type_argc);
4841 for (i = 0; i < inst->type_argc; ++i) {
4842 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)
4843 type_argv [i] = &mono_defaults.object_class->byval_arg;
4845 type_argv [i] = inst->type_argv [i];
4848 shared_context.class_inst = mono_metadata_get_generic_inst (inst->type_argc, type_argv);
4852 inst = context->method_inst;
4854 type_argv = g_new0 (MonoType*, inst->type_argc);
4855 for (i = 0; i < inst->type_argc; ++i) {
4856 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)
4857 type_argv [i] = &mono_defaults.object_class->byval_arg;
4859 type_argv [i] = inst->type_argv [i];
4862 shared_context.method_inst = mono_metadata_get_generic_inst (inst->type_argc, type_argv);
4866 if (method->is_generic || method->klass->generic_container)
4867 declaring_method = method;
4869 declaring_method = mono_method_get_declaring_generic_method (method);
4871 method = mono_class_inflate_generic_method_checked (declaring_method, &shared_context, &error);
4872 g_assert (mono_error_ok (&error)); /* FIXME don't swallow the error */
4876 * If the method is fully sharable, it was already added in place of its
4877 * generic definition.
4879 if (mono_method_is_generic_sharable_full (method, FALSE, FALSE, FALSE))
4883 * FIXME: Partially shared methods are not shared here, so we end up with
4884 * many identical methods.
4886 add_extra_method (acfg, method);
4889 for (i = 0; i < acfg->image->tables [MONO_TABLE_TYPESPEC].rows; ++i) {
4893 token = MONO_TOKEN_TYPE_SPEC | (i + 1);
4895 klass = mono_class_get_checked (acfg->image, token, &error);
4896 if (!klass || klass->rank) {
4897 mono_error_cleanup (&error);
4901 add_generic_class (acfg, klass, FALSE, "typespec");
4904 /* Add types of args/locals */
4905 for (i = 0; i < acfg->methods->len; ++i) {
4906 method = (MonoMethod *)g_ptr_array_index (acfg->methods, i);
4907 add_types_from_method_header (acfg, method);
4910 if (acfg->image == mono_defaults.corlib) {
4912 MonoType *insts [256];
4915 insts [ninsts ++] = &mono_defaults.byte_class->byval_arg;
4916 insts [ninsts ++] = &mono_defaults.sbyte_class->byval_arg;
4917 insts [ninsts ++] = &mono_defaults.int16_class->byval_arg;
4918 insts [ninsts ++] = &mono_defaults.uint16_class->byval_arg;
4919 insts [ninsts ++] = &mono_defaults.int32_class->byval_arg;
4920 insts [ninsts ++] = &mono_defaults.uint32_class->byval_arg;
4921 insts [ninsts ++] = &mono_defaults.int64_class->byval_arg;
4922 insts [ninsts ++] = &mono_defaults.uint64_class->byval_arg;
4923 insts [ninsts ++] = &mono_defaults.single_class->byval_arg;
4924 insts [ninsts ++] = &mono_defaults.double_class->byval_arg;
4925 insts [ninsts ++] = &mono_defaults.char_class->byval_arg;
4926 insts [ninsts ++] = &mono_defaults.boolean_class->byval_arg;
4928 /* Add GenericComparer<T> instances for primitive types for Enum.ToString () */
4929 klass = mono_class_try_load_from_name (acfg->image, "System.Collections.Generic", "GenericComparer`1");
4931 add_instances_of (acfg, klass, insts, ninsts, TRUE);
4932 klass = mono_class_try_load_from_name (acfg->image, "System.Collections.Generic", "GenericEqualityComparer`1");
4934 add_instances_of (acfg, klass, insts, ninsts, TRUE);
4936 /* Add instances of EnumEqualityComparer which are created by EqualityComparer<T> for enums */
4938 MonoClass *enum_comparer;
4939 MonoType *insts [16];
4943 insts [ninsts ++] = &mono_defaults.int32_class->byval_arg;
4944 insts [ninsts ++] = &mono_defaults.uint32_class->byval_arg;
4945 insts [ninsts ++] = &mono_defaults.uint16_class->byval_arg;
4946 insts [ninsts ++] = &mono_defaults.byte_class->byval_arg;
4947 enum_comparer = mono_class_load_from_name (mono_defaults.corlib, "System.Collections.Generic", "EnumEqualityComparer`1");
4948 add_instances_of (acfg, enum_comparer, insts, ninsts, FALSE);
4951 insts [ninsts ++] = &mono_defaults.int16_class->byval_arg;
4952 enum_comparer = mono_class_load_from_name (mono_defaults.corlib, "System.Collections.Generic", "ShortEnumEqualityComparer`1");
4953 add_instances_of (acfg, enum_comparer, insts, ninsts, FALSE);
4956 insts [ninsts ++] = &mono_defaults.sbyte_class->byval_arg;
4957 enum_comparer = mono_class_load_from_name (mono_defaults.corlib, "System.Collections.Generic", "SByteEnumEqualityComparer`1");
4958 add_instances_of (acfg, enum_comparer, insts, ninsts, FALSE);
4960 enum_comparer = mono_class_load_from_name (mono_defaults.corlib, "System.Collections.Generic", "LongEnumEqualityComparer`1");
4962 insts [ninsts ++] = &mono_defaults.int64_class->byval_arg;
4963 insts [ninsts ++] = &mono_defaults.uint64_class->byval_arg;
4964 add_instances_of (acfg, enum_comparer, insts, ninsts, FALSE);
4967 /* Add instances of the array generic interfaces for primitive types */
4968 /* This will add instances of the InternalArray_ helper methods in Array too */
4969 klass = mono_class_try_load_from_name (acfg->image, "System.Collections.Generic", "ICollection`1");
4971 add_instances_of (acfg, klass, insts, ninsts, TRUE);
4973 klass = mono_class_try_load_from_name (acfg->image, "System.Collections.Generic", "IList`1");
4975 add_instances_of (acfg, klass, insts, ninsts, TRUE);
4977 klass = mono_class_try_load_from_name (acfg->image, "System.Collections.Generic", "IEnumerable`1");
4979 add_instances_of (acfg, klass, insts, ninsts, TRUE);
4982 * Add a managed-to-native wrapper of Array.GetGenericValueImpl<object>, which is
4983 * used for all instances of GetGenericValueImpl by the AOT runtime.
4986 MonoGenericContext ctx;
4987 MonoType *args [16];
4988 MonoMethod *get_method;
4989 MonoClass *array_klass = mono_array_class_get (mono_defaults.object_class, 1)->parent;
4991 get_method = mono_class_get_method_from_name (array_klass, "GetGenericValueImpl", 2);
4995 memset (&ctx, 0, sizeof (ctx));
4996 args [0] = &mono_defaults.object_class->byval_arg;
4997 ctx.method_inst = mono_metadata_get_generic_inst (1, args);
4998 add_extra_method (acfg, mono_marshal_get_native_wrapper (mono_class_inflate_generic_method_checked (get_method, &ctx, &error), TRUE, TRUE));
4999 g_assert (mono_error_ok (&error)); /* FIXME don't swallow the error */
5003 /* Same for CompareExchange<T>/Exchange<T> */
5005 MonoGenericContext ctx;
5006 MonoType *args [16];
5008 MonoClass *interlocked_klass = mono_class_load_from_name (mono_defaults.corlib, "System.Threading", "Interlocked");
5009 gpointer iter = NULL;
5011 while ((m = mono_class_get_methods (interlocked_klass, &iter))) {
5012 if ((!strcmp (m->name, "CompareExchange") || !strcmp (m->name, "Exchange")) && m->is_generic) {
5014 memset (&ctx, 0, sizeof (ctx));
5015 args [0] = &mono_defaults.object_class->byval_arg;
5016 ctx.method_inst = mono_metadata_get_generic_inst (1, args);
5017 add_extra_method (acfg, mono_marshal_get_native_wrapper (mono_class_inflate_generic_method_checked (m, &ctx, &error), TRUE, TRUE));
5018 g_assert (mono_error_ok (&error)); /* FIXME don't swallow the error */
5023 /* Same for Volatile.Read/Write<T> */
5025 MonoGenericContext ctx;
5026 MonoType *args [16];
5028 MonoClass *volatile_klass = mono_class_try_load_from_name (mono_defaults.corlib, "System.Threading", "Volatile");
5029 gpointer iter = NULL;
5031 if (volatile_klass) {
5032 while ((m = mono_class_get_methods (volatile_klass, &iter))) {
5033 if ((!strcmp (m->name, "Read") || !strcmp (m->name, "Write")) && m->is_generic) {
5035 memset (&ctx, 0, sizeof (ctx));
5036 args [0] = &mono_defaults.object_class->byval_arg;
5037 ctx.method_inst = mono_metadata_get_generic_inst (1, args);
5038 add_extra_method (acfg, mono_marshal_get_native_wrapper (mono_class_inflate_generic_method_checked (m, &ctx, &error), TRUE, TRUE));
5039 g_assert (mono_error_ok (&error)); /* FIXME don't swallow the error */
5045 /* object[] accessor wrappers. */
5047 MonoClass *obj_array_class = mono_array_class_get (mono_defaults.object_class, 1);
5050 m = mono_class_get_method_from_name (obj_array_class, "Get", 1);
5053 m = mono_marshal_get_array_accessor_wrapper (m);
5054 add_extra_method (acfg, m);
5056 m = mono_class_get_method_from_name (obj_array_class, "Address", 1);
5059 m = mono_marshal_get_array_accessor_wrapper (m);
5060 add_extra_method (acfg, m);
5062 m = mono_class_get_method_from_name (obj_array_class, "Set", 2);
5065 m = mono_marshal_get_array_accessor_wrapper (m);
5066 add_extra_method (acfg, m);
5072 * is_direct_callable:
5074 * Return whenever the method identified by JI is directly callable without
5075 * going through the PLT.
5078 is_direct_callable (MonoAotCompile *acfg, MonoMethod *method, MonoJumpInfo *patch_info)
5080 if ((patch_info->type == MONO_PATCH_INFO_METHOD) && (patch_info->data.method->klass->image == acfg->image)) {
5081 MonoCompile *callee_cfg = (MonoCompile *)g_hash_table_lookup (acfg->method_to_cfg, patch_info->data.method);
5083 gboolean direct_callable = TRUE;
5085 if (direct_callable && !(!callee_cfg->has_got_slots && (callee_cfg->method->klass->flags & TYPE_ATTRIBUTE_BEFORE_FIELD_INIT)))
5086 direct_callable = FALSE;
5087 if ((callee_cfg->method->iflags & METHOD_IMPL_ATTRIBUTE_SYNCHRONIZED) && (!method || method->wrapper_type != MONO_WRAPPER_SYNCHRONIZED))
5088 // FIXME: Maybe call the wrapper directly ?
5089 direct_callable = FALSE;
5091 if (acfg->aot_opts.soft_debug || acfg->aot_opts.no_direct_calls) {
5092 /* Disable this so all calls go through load_method (), see the
5093 * mini_get_debug_options ()->load_aot_jit_info_eagerly = TRUE; line in
5094 * mono_debugger_agent_init ().
5096 direct_callable = FALSE;
5099 if (callee_cfg->method->wrapper_type == MONO_WRAPPER_ALLOC)
5100 /* sgen does some initialization when the allocator method is created */
5101 direct_callable = FALSE;
5102 if (callee_cfg->method->wrapper_type == MONO_WRAPPER_WRITE_BARRIER)
5103 /* we don't know at compile time whether sgen is concurrent or not */
5104 direct_callable = FALSE;
5106 if (direct_callable)
5109 } else if ((patch_info->type == MONO_PATCH_INFO_ICALL_ADDR_CALL && patch_info->data.method->flags & METHOD_ATTRIBUTE_PINVOKE_IMPL)) {
5110 if (acfg->aot_opts.direct_pinvoke)
5112 } else if (patch_info->type == MONO_PATCH_INFO_ICALL_ADDR_CALL) {
5113 if (acfg->aot_opts.direct_icalls)
5121 #ifdef MONO_ARCH_AOT_SUPPORTED
5123 get_pinvoke_import (MonoAotCompile *acfg, MonoMethod *method)
5125 MonoImage *image = method->klass->image;
5126 MonoMethodPInvoke *piinfo = (MonoMethodPInvoke *) method;
5127 MonoTableInfo *tables = image->tables;
5128 MonoTableInfo *im = &tables [MONO_TABLE_IMPLMAP];
5129 MonoTableInfo *mr = &tables [MONO_TABLE_MODULEREF];
5130 guint32 im_cols [MONO_IMPLMAP_SIZE];
5133 import = (char *)g_hash_table_lookup (acfg->method_to_pinvoke_import, method);
5137 if (!piinfo->implmap_idx || piinfo->implmap_idx > im->rows)
5140 mono_metadata_decode_row (im, piinfo->implmap_idx - 1, im_cols, MONO_IMPLMAP_SIZE);
5142 if (!im_cols [MONO_IMPLMAP_SCOPE] || im_cols [MONO_IMPLMAP_SCOPE] > mr->rows)
5145 import = g_strdup_printf ("%s", mono_metadata_string_heap (image, im_cols [MONO_IMPLMAP_NAME]));
5147 g_hash_table_insert (acfg->method_to_pinvoke_import, method, import);
5153 get_pinvoke_import (MonoAotCompile *acfg, MonoMethod *method)
5160 compare_lne (MonoDebugLineNumberEntry *a, MonoDebugLineNumberEntry *b)
5162 if (a->native_offset == b->native_offset)
5163 return a->il_offset - b->il_offset;
5165 return a->native_offset - b->native_offset;
5169 * compute_line_numbers:
5171 * Returns a sparse array of size CODE_SIZE containing MonoDebugSourceLocation* entries for the native offsets which have a corresponding line number
5174 static MonoDebugSourceLocation**
5175 compute_line_numbers (MonoMethod *method, int code_size, MonoDebugMethodJitInfo *debug_info)
5177 MonoDebugMethodInfo *minfo;
5178 MonoDebugLineNumberEntry *ln_array;
5179 MonoDebugSourceLocation *loc;
5180 int i, prev_line, prev_il_offset;
5181 int *native_to_il_offset = NULL;
5182 MonoDebugSourceLocation **res;
5185 minfo = mono_debug_lookup_method (method);
5188 // FIXME: This seems to happen when two methods have the same cfg->method_to_register
5189 if (debug_info->code_size != code_size)
5192 g_assert (code_size);
5194 /* Compute the native->IL offset mapping */
5196 ln_array = g_new0 (MonoDebugLineNumberEntry, debug_info->num_line_numbers);
5197 memcpy (ln_array, debug_info->line_numbers, debug_info->num_line_numbers * sizeof (MonoDebugLineNumberEntry));
5199 qsort (ln_array, debug_info->num_line_numbers, sizeof (MonoDebugLineNumberEntry), (int (*)(const void *, const void *))compare_lne);
5201 native_to_il_offset = g_new0 (int, code_size + 1);
5203 for (i = 0; i < debug_info->num_line_numbers; ++i) {
5205 MonoDebugLineNumberEntry *lne = &ln_array [i];
5208 for (j = 0; j < lne->native_offset; ++j)
5209 native_to_il_offset [j] = -1;
5212 if (i < debug_info->num_line_numbers - 1) {
5213 MonoDebugLineNumberEntry *lne_next = &ln_array [i + 1];
5215 for (j = lne->native_offset; j < lne_next->native_offset; ++j)
5216 native_to_il_offset [j] = lne->il_offset;
5218 for (j = lne->native_offset; j < code_size; ++j)
5219 native_to_il_offset [j] = lne->il_offset;
5224 /* Compute the native->line number mapping */
5225 res = g_new0 (MonoDebugSourceLocation*, code_size);
5226 prev_il_offset = -1;
5229 for (i = 0; i < code_size; ++i) {
5230 int il_offset = native_to_il_offset [i];
5232 if (il_offset == -1 || il_offset == prev_il_offset)
5234 prev_il_offset = il_offset;
5235 loc = mono_debug_symfile_lookup_location (minfo, il_offset);
5236 if (!(loc && loc->source_file))
5238 if (loc->row == prev_line) {
5239 mono_debug_symfile_free_location (loc);
5242 prev_line = loc->row;
5243 //printf ("D: %s:%d il=%x native=%x\n", loc->source_file, loc->row, il_offset, i);
5245 /* This will cover the prolog too */
5255 get_file_index (MonoAotCompile *acfg, const char *source_file)
5259 // FIXME: Free these
5260 if (!acfg->dwarf_ln_filenames)
5261 acfg->dwarf_ln_filenames = g_hash_table_new (g_str_hash, g_str_equal);
5262 findex = GPOINTER_TO_INT (g_hash_table_lookup (acfg->dwarf_ln_filenames, source_file));
5264 findex = g_hash_table_size (acfg->dwarf_ln_filenames) + 1;
5265 g_hash_table_insert (acfg->dwarf_ln_filenames, g_strdup (source_file), GINT_TO_POINTER (findex));
5266 emit_unset_mode (acfg);
5267 fprintf (acfg->fp, ".file %d \"%s\"\n", findex, mono_dwarf_escape_path (source_file));
5279 * emit_and_reloc_code:
5281 * Emit the native code in CODE, handling relocations along the way. If GOT_ONLY
5282 * is true, calls are made through the GOT too. This is used for emitting trampolines
5283 * in full-aot mode, since calls made from trampolines couldn't go through the PLT,
5284 * since trampolines are needed to make PTL work.
5287 emit_and_reloc_code (MonoAotCompile *acfg, MonoMethod *method, guint8 *code, guint32 code_len, MonoJumpInfo *relocs, gboolean got_only, MonoDebugMethodJitInfo *debug_info)
5289 int i, pindex, start_index;
5291 MonoJumpInfo *patch_info;
5292 MonoDebugSourceLocation **locs = NULL;
5293 gboolean skip, prologue_end = FALSE;
5294 #ifdef MONO_ARCH_AOT_SUPPORTED
5295 gboolean direct_call, external_call;
5297 const char *direct_call_target = 0;
5298 const char *direct_pinvoke;
5301 if (acfg->gas_line_numbers && method && debug_info) {
5302 locs = compute_line_numbers (method, code_len, debug_info);
5304 int findex = get_file_index (acfg, "<unknown>");
5305 emit_unset_mode (acfg);
5306 fprintf (acfg->fp, ".loc %d %d 0\n", findex, 1);
5310 /* Collect and sort relocations */
5311 patches = g_ptr_array_new ();
5312 for (patch_info = relocs; patch_info; patch_info = patch_info->next)
5313 g_ptr_array_add (patches, patch_info);
5314 g_ptr_array_sort (patches, compare_patches);
5317 for (i = 0; i < code_len; i += INST_LEN) {
5319 for (pindex = start_index; pindex < patches->len; ++pindex) {
5320 patch_info = (MonoJumpInfo *)g_ptr_array_index (patches, pindex);
5321 if (patch_info->ip.i >= i)
5325 if (locs && locs [i]) {
5326 MonoDebugSourceLocation *loc = locs [i];
5328 const char *options;
5330 findex = get_file_index (acfg, loc->source_file);
5331 emit_unset_mode (acfg);
5333 options = " prologue_end";
5336 prologue_end = TRUE;
5337 fprintf (acfg->fp, ".loc %d %d 0%s\n", findex, loc->row, options);
5338 mono_debug_symfile_free_location (loc);
5342 #ifdef MONO_ARCH_AOT_SUPPORTED
5343 if (patch_info && (patch_info->ip.i == i) && (pindex < patches->len)) {
5344 start_index = pindex;
5346 switch (patch_info->type) {
5347 case MONO_PATCH_INFO_NONE:
5349 case MONO_PATCH_INFO_GOT_OFFSET: {
5352 arch_emit_got_offset (acfg, code + i, &code_size);
5353 i += code_size - INST_LEN;
5355 patch_info->type = MONO_PATCH_INFO_NONE;
5358 case MONO_PATCH_INFO_OBJC_SELECTOR_REF: {
5359 int code_size, index;
5360 char *selector = (char *)patch_info->data.target;
5362 if (!acfg->objc_selector_to_index)
5363 acfg->objc_selector_to_index = g_hash_table_new (g_str_hash, g_str_equal);
5364 if (!acfg->objc_selectors)
5365 acfg->objc_selectors = g_ptr_array_new ();
5366 index = GPOINTER_TO_UINT (g_hash_table_lookup (acfg->objc_selector_to_index, selector));
5370 index = acfg->objc_selector_index;
5371 g_ptr_array_add (acfg->objc_selectors, (void*)patch_info->data.target);
5372 g_hash_table_insert (acfg->objc_selector_to_index, selector, GUINT_TO_POINTER (index + 1));
5373 acfg->objc_selector_index ++;
5376 arch_emit_objc_selector_ref (acfg, code + i, index, &code_size);
5377 i += code_size - INST_LEN;
5379 patch_info->type = MONO_PATCH_INFO_NONE;
5384 * If this patch is a call, try emitting a direct call instead of
5385 * through a PLT entry. This is possible if the called method is in
5386 * the same assembly and requires no initialization.
5388 direct_call = FALSE;
5389 external_call = FALSE;
5390 if ((patch_info->type == MONO_PATCH_INFO_METHOD) && (patch_info->data.method->klass->image == acfg->image)) {
5391 if (!got_only && is_direct_callable (acfg, method, patch_info)) {
5392 MonoCompile *callee_cfg = (MonoCompile *)g_hash_table_lookup (acfg->method_to_cfg, patch_info->data.method);
5393 //printf ("DIRECT: %s %s\n", method ? mono_method_full_name (method, TRUE) : "", mono_method_full_name (callee_cfg->method, TRUE));
5395 direct_call_target = callee_cfg->asm_symbol;
5396 patch_info->type = MONO_PATCH_INFO_NONE;
5397 acfg->stats.direct_calls ++;
5400 acfg->stats.all_calls ++;
5401 } else if (patch_info->type == MONO_PATCH_INFO_ICALL_ADDR_CALL) {
5402 if (!got_only && is_direct_callable (acfg, method, patch_info)) {
5403 if (!(patch_info->data.method->flags & METHOD_ATTRIBUTE_PINVOKE_IMPL))
5404 direct_pinvoke = mono_lookup_icall_symbol (patch_info->data.method);
5406 direct_pinvoke = get_pinvoke_import (acfg, patch_info->data.method);
5407 if (direct_pinvoke) {
5409 g_assert (strlen (direct_pinvoke) < 1000);
5410 direct_call_target = g_strdup_printf ("%s%s", acfg->user_symbol_prefix, direct_pinvoke);
5413 } else if (patch_info->type == MONO_PATCH_INFO_JIT_ICALL_ADDR) {
5414 const char *sym = mono_lookup_jit_icall_symbol (patch_info->data.name);
5415 if (!got_only && sym && acfg->aot_opts.direct_icalls) {
5416 /* Call to a C function implementing a jit icall */
5418 external_call = TRUE;
5419 g_assert (strlen (sym) < 1000);
5420 direct_call_target = g_strdup_printf ("%s%s", acfg->user_symbol_prefix, sym);
5422 } else if (patch_info->type == MONO_PATCH_INFO_INTERNAL_METHOD) {
5423 MonoJitICallInfo *info = mono_find_jit_icall_by_name (patch_info->data.name);
5424 const char *sym = mono_lookup_jit_icall_symbol (patch_info->data.name);
5425 if (!got_only && sym && acfg->aot_opts.direct_icalls && info->func == info->wrapper) {
5426 /* Call to a jit icall without a wrapper */
5428 external_call = TRUE;
5429 g_assert (strlen (sym) < 1000);
5430 direct_call_target = g_strdup_printf ("%s%s", acfg->user_symbol_prefix, sym);
5435 patch_info->type = MONO_PATCH_INFO_NONE;
5436 acfg->stats.direct_calls ++;
5439 if (!got_only && !direct_call) {
5440 MonoPltEntry *plt_entry = get_plt_entry (acfg, patch_info);
5442 /* This patch has a PLT entry, so we must emit a call to the PLT entry */
5444 direct_call_target = plt_entry->symbol;
5446 /* Nullify the patch */
5447 patch_info->type = MONO_PATCH_INFO_NONE;
5448 plt_entry->jit_used = TRUE;
5455 arch_emit_direct_call (acfg, direct_call_target, external_call, FALSE, patch_info, &call_size);
5456 i += call_size - INST_LEN;
5460 got_slot = get_got_offset (acfg, FALSE, patch_info);
5462 arch_emit_got_access (acfg, acfg->got_symbol, code + i, got_slot, &code_size);
5463 i += code_size - INST_LEN;
5469 #endif /* MONO_ARCH_AOT_SUPPORTED */
5472 /* Find next patch */
5474 for (pindex = start_index; pindex < patches->len; ++pindex) {
5475 patch_info = (MonoJumpInfo *)g_ptr_array_index (patches, pindex);
5476 if (patch_info->ip.i >= i)
5480 /* Try to emit multiple bytes at once */
5481 if (pindex < patches->len && patch_info->ip.i > i) {
5484 for (limit = i + INST_LEN; limit < patch_info->ip.i; limit += INST_LEN) {
5485 if (locs && locs [limit])
5489 emit_code_bytes (acfg, code + i, limit - i);
5490 i = limit - INST_LEN;
5492 emit_code_bytes (acfg, code + i, INST_LEN);
5503 * Return a modified version of S which only includes characters permissible in symbols.
5506 sanitize_symbol (MonoAotCompile *acfg, char *s)
5508 gboolean process = FALSE;
5517 for (i = 0; i < len; ++i)
5518 if (!(s [i] <= 0x7f && (isalnum (s [i]) || s [i] == '_')))
5523 gs = g_string_sized_new (len);
5524 for (i = 0; i < len; ++i) {
5526 if (c <= 0x7f && (isalnum (c) || c == '_')) {
5527 g_string_append_c (gs, c);
5528 } else if (c > 0x7f) {
5529 /* multi-byte utf8 */
5530 g_string_append_printf (gs, "_0x%x", c);
5533 while (c >> 6 == 0x2) {
5534 g_string_append_printf (gs, "%x", c);
5538 g_string_append_printf (gs, "_");
5541 g_string_append_c (gs, '_');
5545 res = mono_mempool_strdup (acfg->mempool, gs->str);
5546 g_string_free (gs, TRUE);
5551 get_debug_sym (MonoMethod *method, const char *prefix, GHashTable *cache)
5553 char *name1, *name2, *cached;
5554 int i, j, len, count;
5555 MonoMethod *cached_method;
5557 name1 = mono_method_full_name (method, TRUE);
5560 // This is so that we don't accidentally create a local symbol (which starts with 'L')
5561 if ((!prefix || !*prefix) && name1 [0] == 'L')
5565 len = strlen (name1);
5566 name2 = (char *)malloc (strlen (prefix) + len + 16);
5567 memcpy (name2, prefix, strlen (prefix));
5568 j = strlen (prefix);
5569 for (i = 0; i < len; ++i) {
5570 if (i == 0 && name1 [0] >= '0' && name1 [0] <= '9') {
5572 } else if (isalnum (name1 [i])) {
5573 name2 [j ++] = name1 [i];
5574 } else if (name1 [i] == ' ' && name1 [i + 1] == '(' && name1 [i + 2] == ')') {
5576 } else if (name1 [i] == ',' && name1 [i + 1] == ' ') {
5579 } else if (name1 [i] == '(' || name1 [i] == ')' || name1 [i] == '>') {
5589 cached_method = (MonoMethod *)g_hash_table_lookup (cache, name2);
5590 if (!(cached_method && cached_method != method))
5592 sprintf (name2 + j, "_%d", count);
5596 cached = g_strdup (name2);
5597 g_hash_table_insert (cache, cached, method);
5603 emit_method_code (MonoAotCompile *acfg, MonoCompile *cfg)
5608 char *debug_sym = NULL;
5609 char *symbol = NULL;
5610 int func_alignment = AOT_FUNC_ALIGNMENT;
5613 method = cfg->orig_method;
5614 code = cfg->native_code;
5616 method_index = get_method_index (acfg, method);
5617 symbol = g_strdup_printf ("%sme_%x", acfg->temp_prefix, method_index);
5619 /* Make the labels local */
5620 emit_section_change (acfg, ".text", 0);
5621 emit_alignment_code (acfg, func_alignment);
5623 if (acfg->global_symbols && acfg->need_no_dead_strip)
5624 fprintf (acfg->fp, " .no_dead_strip %s\n", cfg->asm_symbol);
5626 emit_label (acfg, cfg->asm_symbol);
5628 if (acfg->aot_opts.write_symbols && !acfg->global_symbols && !acfg->llvm) {
5630 * Write a C style symbol for every method, this has two uses:
5631 * - it works on platforms where the dwarf debugging info is not
5633 * - it allows the setting of breakpoints of aot-ed methods.
5635 debug_sym = get_debug_sym (method, "", acfg->method_label_hash);
5636 cfg->asm_debug_symbol = g_strdup (debug_sym);
5638 if (acfg->need_no_dead_strip)
5639 fprintf (acfg->fp, " .no_dead_strip %s\n", debug_sym);
5640 emit_local_symbol (acfg, debug_sym, symbol, TRUE);
5641 emit_label (acfg, debug_sym);
5644 export_name = (char *)g_hash_table_lookup (acfg->export_names, method);
5646 /* Emit a global symbol for the method */
5647 emit_global_inner (acfg, export_name, TRUE);
5648 emit_label (acfg, export_name);
5651 if (cfg->verbose_level > 0)
5652 g_print ("Method %s emitted as %s\n", mono_method_get_full_name (method), cfg->asm_symbol);
5654 acfg->stats.code_size += cfg->code_len;
5656 acfg->cfgs [method_index]->got_offset = acfg->got_offset;
5658 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 ()));
5662 if (acfg->aot_opts.write_symbols) {
5664 emit_symbol_size (acfg, debug_sym, ".");
5666 emit_symbol_size (acfg, cfg->asm_symbol, ".");
5670 emit_label (acfg, symbol);
5677 * Encode PATCH_INFO into its disk representation.
5680 encode_patch (MonoAotCompile *acfg, MonoJumpInfo *patch_info, guint8 *buf, guint8 **endbuf)
5684 switch (patch_info->type) {
5685 case MONO_PATCH_INFO_NONE:
5687 case MONO_PATCH_INFO_IMAGE:
5688 encode_value (get_image_index (acfg, patch_info->data.image), p, &p);
5690 case MONO_PATCH_INFO_MSCORLIB_GOT_ADDR:
5691 case MONO_PATCH_INFO_JIT_TLS_ID:
5692 case MONO_PATCH_INFO_GC_CARD_TABLE_ADDR:
5693 case MONO_PATCH_INFO_GC_NURSERY_START:
5694 case MONO_PATCH_INFO_GC_NURSERY_BITS:
5696 case MONO_PATCH_INFO_CASTCLASS_CACHE:
5697 encode_value (patch_info->data.index, p, &p);
5699 case MONO_PATCH_INFO_METHOD_REL:
5700 encode_value ((gint)patch_info->data.offset, p, &p);
5702 case MONO_PATCH_INFO_SWITCH: {
5703 gpointer *table = (gpointer *)patch_info->data.table->table;
5706 encode_value (patch_info->data.table->table_size, p, &p);
5707 for (k = 0; k < patch_info->data.table->table_size; k++)
5708 encode_value ((int)(gssize)table [k], p, &p);
5711 case MONO_PATCH_INFO_METHODCONST:
5712 case MONO_PATCH_INFO_METHOD:
5713 case MONO_PATCH_INFO_METHOD_JUMP:
5714 case MONO_PATCH_INFO_ICALL_ADDR:
5715 case MONO_PATCH_INFO_ICALL_ADDR_CALL:
5716 case MONO_PATCH_INFO_METHOD_RGCTX:
5717 case MONO_PATCH_INFO_METHOD_CODE_SLOT:
5718 encode_method_ref (acfg, patch_info->data.method, p, &p);
5720 case MONO_PATCH_INFO_AOT_JIT_INFO:
5721 encode_value (patch_info->data.index, p, &p);
5723 case MONO_PATCH_INFO_INTERNAL_METHOD:
5724 case MONO_PATCH_INFO_JIT_ICALL_ADDR: {
5725 guint32 len = strlen (patch_info->data.name);
5727 encode_value (len, p, &p);
5729 memcpy (p, patch_info->data.name, len);
5734 case MONO_PATCH_INFO_LDSTR: {
5735 guint32 image_index = get_image_index (acfg, patch_info->data.token->image);
5736 guint32 token = patch_info->data.token->token;
5737 g_assert (mono_metadata_token_code (token) == MONO_TOKEN_STRING);
5738 encode_value (image_index, p, &p);
5739 encode_value (patch_info->data.token->token - MONO_TOKEN_STRING, p, &p);
5742 case MONO_PATCH_INFO_RVA:
5743 case MONO_PATCH_INFO_DECLSEC:
5744 case MONO_PATCH_INFO_LDTOKEN:
5745 case MONO_PATCH_INFO_TYPE_FROM_HANDLE:
5746 encode_value (get_image_index (acfg, patch_info->data.token->image), p, &p);
5747 encode_value (patch_info->data.token->token, p, &p);
5748 encode_value (patch_info->data.token->has_context, p, &p);
5749 if (patch_info->data.token->has_context)
5750 encode_generic_context (acfg, &patch_info->data.token->context, p, &p);
5752 case MONO_PATCH_INFO_EXC_NAME: {
5753 MonoClass *ex_class;
5756 mono_class_load_from_name (mono_defaults.exception_class->image,
5757 "System", (const char *)patch_info->data.target);
5758 encode_klass_ref (acfg, ex_class, p, &p);
5761 case MONO_PATCH_INFO_R4:
5762 encode_value (*((guint32 *)patch_info->data.target), p, &p);
5764 case MONO_PATCH_INFO_R8:
5765 encode_value (((guint32 *)patch_info->data.target) [MINI_LS_WORD_IDX], p, &p);
5766 encode_value (((guint32 *)patch_info->data.target) [MINI_MS_WORD_IDX], p, &p);
5768 case MONO_PATCH_INFO_VTABLE:
5769 case MONO_PATCH_INFO_CLASS:
5770 case MONO_PATCH_INFO_IID:
5771 case MONO_PATCH_INFO_ADJUSTED_IID:
5772 encode_klass_ref (acfg, patch_info->data.klass, p, &p);
5774 case MONO_PATCH_INFO_DELEGATE_TRAMPOLINE:
5775 encode_klass_ref (acfg, patch_info->data.del_tramp->klass, p, &p);
5776 if (patch_info->data.del_tramp->method) {
5777 encode_value (1, p, &p);
5778 encode_method_ref (acfg, patch_info->data.del_tramp->method, p, &p);
5780 encode_value (0, p, &p);
5782 encode_value (patch_info->data.del_tramp->is_virtual, p, &p);
5784 case MONO_PATCH_INFO_FIELD:
5785 case MONO_PATCH_INFO_SFLDA:
5786 encode_field_info (acfg, patch_info->data.field, p, &p);
5788 case MONO_PATCH_INFO_INTERRUPTION_REQUEST_FLAG:
5790 case MONO_PATCH_INFO_RGCTX_FETCH:
5791 case MONO_PATCH_INFO_RGCTX_SLOT_INDEX: {
5792 MonoJumpInfoRgctxEntry *entry = patch_info->data.rgctx_entry;
5797 * entry->method has a lenghtly encoding and multiple rgctx_fetch entries
5798 * reference the same method, so encode the method only once.
5800 offset = GPOINTER_TO_UINT (g_hash_table_lookup (acfg->method_blob_hash, entry->method));
5802 buf2 = (guint8 *)g_malloc (1024);
5805 encode_method_ref (acfg, entry->method, p2, &p2);
5806 g_assert (p2 - buf2 < 1024);
5808 offset = add_to_blob (acfg, buf2, p2 - buf2);
5811 g_hash_table_insert (acfg->method_blob_hash, entry->method, GUINT_TO_POINTER (offset + 1));
5816 encode_value (offset, p, &p);
5817 g_assert ((int)entry->info_type < 256);
5818 g_assert (entry->data->type < 256);
5819 encode_value ((entry->in_mrgctx ? 1 : 0) | (entry->info_type << 1) | (entry->data->type << 9), p, &p);
5820 encode_patch (acfg, entry->data, p, &p);
5823 case MONO_PATCH_INFO_SEQ_POINT_INFO:
5824 case MONO_PATCH_INFO_AOT_MODULE:
5826 case MONO_PATCH_INFO_SIGNATURE:
5827 case MONO_PATCH_INFO_GSHAREDVT_IN_WRAPPER:
5828 encode_signature (acfg, (MonoMethodSignature*)patch_info->data.target, p, &p);
5830 case MONO_PATCH_INFO_TLS_OFFSET:
5831 encode_value (GPOINTER_TO_INT (patch_info->data.target), p, &p);
5833 case MONO_PATCH_INFO_GSHAREDVT_CALL:
5834 encode_signature (acfg, (MonoMethodSignature*)patch_info->data.gsharedvt->sig, p, &p);
5835 encode_method_ref (acfg, patch_info->data.gsharedvt->method, p, &p);
5837 case MONO_PATCH_INFO_GSHAREDVT_METHOD: {
5838 MonoGSharedVtMethodInfo *info = patch_info->data.gsharedvt_method;
5841 encode_method_ref (acfg, info->method, p, &p);
5842 encode_value (info->num_entries, p, &p);
5843 for (i = 0; i < info->num_entries; ++i) {
5844 MonoRuntimeGenericContextInfoTemplate *template_ = &info->entries [i];
5846 encode_value (template_->info_type, p, &p);
5847 switch (mini_rgctx_info_type_to_patch_info_type (template_->info_type)) {
5848 case MONO_PATCH_INFO_CLASS:
5849 encode_klass_ref (acfg, mono_class_from_mono_type ((MonoType *)template_->data), p, &p);
5851 case MONO_PATCH_INFO_FIELD:
5852 encode_field_info (acfg, (MonoClassField *)template_->data, p, &p);
5855 g_assert_not_reached ();
5861 case MONO_PATCH_INFO_LDSTR_LIT: {
5862 const char *s = (const char *)patch_info->data.target;
5863 int len = strlen (s);
5865 encode_value (len, p, &p);
5866 memcpy (p, s, len + 1);
5870 case MONO_PATCH_INFO_VIRT_METHOD:
5871 encode_klass_ref (acfg, patch_info->data.virt_method->klass, p, &p);
5872 encode_method_ref (acfg, patch_info->data.virt_method->method, p, &p);
5874 case MONO_PATCH_INFO_GC_SAFE_POINT_FLAG:
5877 g_warning ("unable to handle jump info %d", patch_info->type);
5878 g_assert_not_reached ();
5885 encode_patch_list (MonoAotCompile *acfg, GPtrArray *patches, int n_patches, gboolean llvm, int first_got_offset, guint8 *buf, guint8 **endbuf)
5888 guint32 pindex, offset;
5889 MonoJumpInfo *patch_info;
5891 encode_value (n_patches, p, &p);
5893 for (pindex = 0; pindex < patches->len; ++pindex) {
5894 patch_info = (MonoJumpInfo *)g_ptr_array_index (patches, pindex);
5896 if (patch_info->type == MONO_PATCH_INFO_NONE || patch_info->type == MONO_PATCH_INFO_BB)
5900 offset = get_got_offset (acfg, llvm, patch_info);
5901 encode_value (offset, p, &p);
5908 emit_method_info (MonoAotCompile *acfg, MonoCompile *cfg)
5911 int pindex, buf_size, n_patches;
5913 MonoJumpInfo *patch_info;
5914 guint32 method_index;
5916 guint32 first_got_offset;
5918 method = cfg->orig_method;
5920 method_index = get_method_index (acfg, method);
5922 /* Sort relocations */
5923 patches = g_ptr_array_new ();
5924 for (patch_info = cfg->patch_info; patch_info; patch_info = patch_info->next)
5925 g_ptr_array_add (patches, patch_info);
5926 g_ptr_array_sort (patches, compare_patches);
5928 first_got_offset = acfg->cfgs [method_index]->got_offset;
5930 /**********************/
5931 /* Encode method info */
5932 /**********************/
5934 buf_size = (patches->len < 1000) ? 40960 : 40960 + (patches->len * 64);
5935 p = buf = (guint8 *)g_malloc (buf_size);
5937 if (mono_class_get_cctor (method->klass)) {
5938 encode_value (1, p, &p);
5939 encode_klass_ref (acfg, method->klass, p, &p);
5941 /* Not needed when loading the method */
5942 encode_value (0, p, &p);
5945 g_assert (!(cfg->opt & MONO_OPT_SHARED));
5948 for (pindex = 0; pindex < patches->len; ++pindex) {
5949 patch_info = (MonoJumpInfo *)g_ptr_array_index (patches, pindex);
5951 if ((patch_info->type == MONO_PATCH_INFO_GOT_OFFSET) ||
5952 (patch_info->type == MONO_PATCH_INFO_NONE)) {
5953 patch_info->type = MONO_PATCH_INFO_NONE;
5958 if ((patch_info->type == MONO_PATCH_INFO_IMAGE) && (patch_info->data.image == acfg->image)) {
5959 /* Stored in a GOT slot initialized at module load time */
5960 patch_info->type = MONO_PATCH_INFO_NONE;
5964 if (patch_info->type == MONO_PATCH_INFO_GC_CARD_TABLE_ADDR ||
5965 patch_info->type == MONO_PATCH_INFO_GC_NURSERY_START ||
5966 patch_info->type == MONO_PATCH_INFO_GC_NURSERY_BITS ||
5967 patch_info->type == MONO_PATCH_INFO_AOT_MODULE) {
5968 /* Stored in a GOT slot initialized at module load time */
5969 patch_info->type = MONO_PATCH_INFO_NONE;
5973 if (is_plt_patch (patch_info) && !(cfg->compile_llvm && acfg->aot_opts.llvm_only)) {
5974 /* Calls are made through the PLT */
5975 patch_info->type = MONO_PATCH_INFO_NONE;
5983 g_assert (cfg->has_got_slots);
5985 encode_patch_list (acfg, patches, n_patches, cfg->compile_llvm, first_got_offset, p, &p);
5987 acfg->stats.info_size += p - buf;
5989 g_assert (p - buf < buf_size);
5991 cfg->method_info_offset = add_to_blob (acfg, buf, p - buf);
5996 get_unwind_info_offset (MonoAotCompile *acfg, guint8 *encoded, guint32 encoded_len)
5998 guint32 cache_index;
6001 /* Reuse the unwind module to canonize and store unwind info entries */
6002 cache_index = mono_cache_unwind_info (encoded, encoded_len);
6004 /* Use +/- 1 to distinguish 0s from missing entries */
6005 offset = GPOINTER_TO_UINT (g_hash_table_lookup (acfg->unwind_info_offsets, GUINT_TO_POINTER (cache_index + 1)));
6013 * It would be easier to use assembler symbols, but the caller needs an
6016 offset = acfg->unwind_info_offset;
6017 g_hash_table_insert (acfg->unwind_info_offsets, GUINT_TO_POINTER (cache_index + 1), GUINT_TO_POINTER (offset + 1));
6018 g_ptr_array_add (acfg->unwind_ops, GUINT_TO_POINTER (cache_index));
6021 encode_value (encoded_len, p, &p);
6023 acfg->unwind_info_offset += encoded_len + (p - buf);
6029 emit_exception_debug_info (MonoAotCompile *acfg, MonoCompile *cfg, gboolean store_seq_points)
6032 guint32 debug_info_size, seq_points_size;
6034 MonoMethodHeader *header;
6035 guint8 *p, *buf, *debug_info;
6036 MonoJitInfo *jinfo = cfg->jit_info;
6038 gboolean use_unwind_ops = FALSE;
6039 MonoSeqPointInfo *seq_points;
6041 code = cfg->native_code;
6042 header = cfg->header;
6044 if (!acfg->aot_opts.nodebug) {
6045 mono_debug_serialize_debug_info (cfg, &debug_info, &debug_info_size);
6048 debug_info_size = 0;
6051 seq_points = cfg->seq_point_info;
6052 seq_points_size = (store_seq_points)? mono_seq_point_info_get_write_size (seq_points) : 0;
6054 buf_size = header->num_clauses * 256 + debug_info_size + 2048 + seq_points_size + cfg->gc_map_size;
6056 p = buf = (guint8 *)g_malloc (buf_size);
6058 use_unwind_ops = cfg->unwind_ops != NULL;
6060 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);
6062 encode_value (flags, p, &p);
6064 if (use_unwind_ops) {
6065 guint32 encoded_len;
6067 guint32 unwind_desc;
6069 encoded = mono_unwind_ops_encode (cfg->unwind_ops, &encoded_len);
6071 unwind_desc = get_unwind_info_offset (acfg, encoded, encoded_len);
6072 encode_value (unwind_desc, p, &p);
6074 encode_value (jinfo->unwind_info, p, &p);
6077 /*Encode the number of holes before the number of clauses to make decoding easier*/
6078 if (jinfo->has_try_block_holes) {
6079 MonoTryBlockHoleTableJitInfo *table = mono_jit_info_get_try_block_hole_table_info (jinfo);
6080 encode_value (table->num_holes, p, &p);
6083 if (jinfo->has_arch_eh_info) {
6085 * In AOT mode, the code length is calculated from the address of the previous method,
6086 * which could include alignment padding, so calculating the start of the epilog as
6087 * code_len - epilog_size is correct any more. Save the real code len as a workaround.
6089 encode_value (jinfo->code_size, p, &p);
6092 /* Exception table */
6093 if (cfg->compile_llvm) {
6095 * When using LLVM, we can't emit some data, like pc offsets, this reg/offset etc.,
6096 * since the information is only available to llc. Instead, we let llc save the data
6097 * into the LSDA, and read it from there at runtime.
6099 /* The assembly might be CIL stripped so emit the data ourselves */
6100 if (header->num_clauses)
6101 encode_value (header->num_clauses, p, &p);
6103 for (k = 0; k < header->num_clauses; ++k) {
6104 MonoExceptionClause *clause;
6106 clause = &header->clauses [k];
6108 encode_value (clause->flags, p, &p);
6109 if (clause->data.catch_class) {
6110 encode_value (1, p, &p);
6111 encode_klass_ref (acfg, clause->data.catch_class, p, &p);
6113 encode_value (0, p, &p);
6116 /* Emit the IL ranges too, since they might not be available at runtime */
6117 encode_value (clause->try_offset, p, &p);
6118 encode_value (clause->try_len, p, &p);
6119 encode_value (clause->handler_offset, p, &p);
6120 encode_value (clause->handler_len, p, &p);
6122 /* Emit a list of nesting clauses */
6123 for (i = 0; i < header->num_clauses; ++i) {
6125 MonoExceptionClause *clause1 = &header->clauses [cindex1];
6127 MonoExceptionClause *clause2 = &header->clauses [cindex2];
6129 if (cindex1 != cindex2 && clause1->try_offset >= clause2->try_offset && clause1->handler_offset <= clause2->handler_offset)
6130 encode_value (i, p, &p);
6132 encode_value (-1, p, &p);
6135 if (jinfo->num_clauses)
6136 encode_value (jinfo->num_clauses, p, &p);
6138 for (k = 0; k < jinfo->num_clauses; ++k) {
6139 MonoJitExceptionInfo *ei = &jinfo->clauses [k];
6141 encode_value (ei->flags, p, &p);
6142 #ifdef MONO_CONTEXT_SET_LLVM_EXC_REG
6143 /* Not used for catch clauses */
6144 if (ei->flags != MONO_EXCEPTION_CLAUSE_NONE)
6145 encode_value (ei->exvar_offset, p, &p);
6147 encode_value (ei->exvar_offset, p, &p);
6150 if (ei->flags == MONO_EXCEPTION_CLAUSE_FILTER || ei->flags == MONO_EXCEPTION_CLAUSE_FINALLY)
6151 encode_value ((gint)((guint8*)ei->data.filter - code), p, &p);
6153 if (ei->data.catch_class) {
6157 buf2 = (guint8 *)g_malloc (4096);
6159 encode_klass_ref (acfg, ei->data.catch_class, p2, &p2);
6161 g_assert (len < 4096);
6162 encode_value (len, p, &p);
6163 memcpy (p, buf2, len);
6167 encode_value (0, p, &p);
6171 encode_value ((gint)((guint8*)ei->try_start - code), p, &p);
6172 encode_value ((gint)((guint8*)ei->try_end - code), p, &p);
6173 encode_value ((gint)((guint8*)ei->handler_start - code), p, &p);
6177 if (jinfo->has_try_block_holes) {
6178 MonoTryBlockHoleTableJitInfo *table = mono_jit_info_get_try_block_hole_table_info (jinfo);
6179 for (i = 0; i < table->num_holes; ++i) {
6180 MonoTryBlockHoleJitInfo *hole = &table->holes [i];
6181 encode_value (hole->clause, p, &p);
6182 encode_value (hole->length, p, &p);
6183 encode_value (hole->offset, p, &p);
6187 if (jinfo->has_arch_eh_info) {
6188 MonoArchEHJitInfo *eh_info;
6190 eh_info = mono_jit_info_get_arch_eh_info (jinfo);
6191 encode_value (eh_info->stack_size, p, &p);
6192 encode_value (eh_info->epilog_size, p, &p);
6195 if (jinfo->has_generic_jit_info) {
6196 MonoGenericJitInfo *gi = mono_jit_info_get_generic_jit_info (jinfo);
6197 MonoGenericSharingContext* gsctx = gi->generic_sharing_context;
6201 encode_value (gi->nlocs, p, &p);
6203 for (i = 0; i < gi->nlocs; ++i) {
6204 MonoDwarfLocListEntry *entry = &gi->locations [i];
6206 encode_value (entry->is_reg ? 1 : 0, p, &p);
6207 encode_value (entry->reg, p, &p);
6209 encode_value (entry->offset, p, &p);
6211 g_assert (entry->from == 0);
6213 encode_value (entry->from, p, &p);
6214 encode_value (entry->to, p, &p);
6217 if (!cfg->compile_llvm) {
6218 encode_value (gi->has_this ? 1 : 0, p, &p);
6219 encode_value (gi->this_reg, p, &p);
6220 encode_value (gi->this_offset, p, &p);
6225 * Need to encode jinfo->method too, since it is not equal to 'method'
6226 * when using generic sharing.
6228 buf2 = (guint8 *)g_malloc (4096);
6230 encode_method_ref (acfg, jinfo->d.method, p2, &p2);
6232 g_assert (len < 4096);
6233 encode_value (len, p, &p);
6234 memcpy (p, buf2, len);
6238 if (gsctx && gsctx->is_gsharedvt) {
6239 encode_value (1, p, &p);
6241 encode_value (0, p, &p);
6245 if (seq_points_size)
6246 p += mono_seq_point_info_write (seq_points, p);
6248 g_assert (debug_info_size < buf_size);
6250 encode_value (debug_info_size, p, &p);
6251 if (debug_info_size) {
6252 memcpy (p, debug_info, debug_info_size);
6253 p += debug_info_size;
6254 g_free (debug_info);
6259 encode_value (cfg->gc_map_size, p, &p);
6260 /* The GC map requires 4 bytes of alignment */
6261 while ((gsize)p % 4)
6263 memcpy (p, cfg->gc_map, cfg->gc_map_size);
6264 p += cfg->gc_map_size;
6267 acfg->stats.ex_info_size += p - buf;
6269 g_assert (p - buf < buf_size);
6272 /* The GC Map requires 4 byte alignment */
6273 cfg->ex_info_offset = add_to_blob_aligned (acfg, buf, p - buf, cfg->gc_map ? 4 : 1);
6278 emit_klass_info (MonoAotCompile *acfg, guint32 token)
6281 MonoClass *klass = mono_class_get_checked (acfg->image, token, &error);
6283 int i, buf_size, res;
6284 gboolean no_special_static, cant_encode;
6285 gpointer iter = NULL;
6288 mono_error_cleanup (&error);
6292 p = buf = (guint8 *)g_malloc (buf_size);
6294 /* Mark as unusable */
6295 encode_value (-1, p, &p);
6297 res = add_to_blob (acfg, buf, p - buf);
6303 buf_size = 10240 + (klass->vtable_size * 16);
6304 p = buf = (guint8 *)g_malloc (buf_size);
6308 mono_class_init (klass);
6310 mono_class_get_nested_types (klass, &iter);
6311 g_assert (klass->nested_classes_inited);
6313 mono_class_setup_vtable (klass);
6316 * Emit all the information which is required for creating vtables so
6317 * the runtime does not need to create the MonoMethod structures which
6318 * take up a lot of space.
6321 no_special_static = !mono_class_has_special_static_fields (klass);
6323 /* Check whenever we have enough info to encode the vtable */
6324 cant_encode = FALSE;
6325 for (i = 0; i < klass->vtable_size; ++i) {
6326 MonoMethod *cm = klass->vtable [i];
6328 if (cm && mono_method_signature (cm)->is_inflated && !g_hash_table_lookup (acfg->token_info_hash, cm))
6332 mono_class_has_finalizer (klass);
6334 if (klass->generic_container || cant_encode) {
6335 encode_value (-1, p, &p);
6337 encode_value (klass->vtable_size, p, &p);
6338 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);
6339 if (klass->has_cctor)
6340 encode_method_ref (acfg, mono_class_get_cctor (klass), p, &p);
6341 if (klass->has_finalize)
6342 encode_method_ref (acfg, mono_class_get_finalizer (klass), p, &p);
6344 encode_value (klass->instance_size, p, &p);
6345 encode_value (mono_class_data_size (klass), p, &p);
6346 encode_value (klass->packing_size, p, &p);
6347 encode_value (klass->min_align, p, &p);
6349 for (i = 0; i < klass->vtable_size; ++i) {
6350 MonoMethod *cm = klass->vtable [i];
6353 encode_method_ref (acfg, cm, p, &p);
6355 encode_value (0, p, &p);
6359 acfg->stats.class_info_size += p - buf;
6361 g_assert (p - buf < buf_size);
6362 res = add_to_blob (acfg, buf, p - buf);
6369 get_plt_entry_debug_sym (MonoAotCompile *acfg, MonoJumpInfo *ji, GHashTable *cache)
6371 char *debug_sym = NULL;
6374 if (acfg->llvm && llvm_acfg->aot_opts.static_link) {
6375 /* Need to add a prefix to create unique symbols */
6376 prefix = g_strdup_printf ("plt_%s_", acfg->assembly_name_sym);
6378 prefix = g_strdup ("plt_");
6382 case MONO_PATCH_INFO_METHOD:
6383 debug_sym = get_debug_sym (ji->data.method, prefix, cache);
6385 case MONO_PATCH_INFO_INTERNAL_METHOD:
6386 debug_sym = g_strdup_printf ("%s_jit_icall_%s", prefix, ji->data.name);
6388 case MONO_PATCH_INFO_RGCTX_FETCH:
6389 debug_sym = g_strdup_printf ("%s_rgctx_fetch_%d", prefix, acfg->label_generator ++);
6391 case MONO_PATCH_INFO_ICALL_ADDR:
6392 case MONO_PATCH_INFO_ICALL_ADDR_CALL: {
6393 char *s = get_debug_sym (ji->data.method, "", cache);
6395 debug_sym = g_strdup_printf ("%s_icall_native_%s", prefix, s);
6399 case MONO_PATCH_INFO_JIT_ICALL_ADDR:
6400 debug_sym = g_strdup_printf ("%s_jit_icall_native_%s", prefix, ji->data.name);
6408 return sanitize_symbol (acfg, debug_sym);
6412 * Calls made from AOTed code are routed through a table of jumps similar to the
6413 * ELF PLT (Program Linkage Table). Initially the PLT entries jump to code which transfers
6414 * control to the AOT runtime through a trampoline.
6417 emit_plt (MonoAotCompile *acfg)
6421 if (acfg->aot_opts.llvm_only) {
6422 g_assert (acfg->plt_offset == 1);
6428 emit_section_change (acfg, ".text", 0);
6429 emit_alignment_code (acfg, NACL_SIZE(16, kNaClAlignment));
6430 emit_info_symbol (acfg, "plt");
6431 emit_label (acfg, acfg->plt_symbol);
6433 for (i = 0; i < acfg->plt_offset; ++i) {
6434 char *debug_sym = NULL;
6435 MonoPltEntry *plt_entry = NULL;
6439 * The first plt entry is unused.
6443 plt_entry = (MonoPltEntry *)g_hash_table_lookup (acfg->plt_offset_to_entry, GUINT_TO_POINTER (i));
6445 debug_sym = plt_entry->debug_sym;
6447 if (acfg->thumb_mixed && !plt_entry->jit_used)
6448 /* Emit only a thumb version */
6451 /* Skip plt entries not actually called */
6452 if (!plt_entry->jit_used && !plt_entry->llvm_used)
6455 if (acfg->llvm && !acfg->thumb_mixed) {
6456 emit_label (acfg, plt_entry->llvm_symbol);
6458 emit_global_inner (acfg, plt_entry->llvm_symbol, TRUE);
6459 #if defined(TARGET_MACH)
6460 fprintf (acfg->fp, ".private_extern %s\n", plt_entry->llvm_symbol);
6466 if (acfg->need_no_dead_strip) {
6467 emit_unset_mode (acfg);
6468 fprintf (acfg->fp, " .no_dead_strip %s\n", debug_sym);
6470 emit_local_symbol (acfg, debug_sym, NULL, TRUE);
6471 emit_label (acfg, debug_sym);
6474 emit_label (acfg, plt_entry->symbol);
6476 arch_emit_plt_entry (acfg, acfg->got_symbol, (acfg->plt_got_offset_base + i) * sizeof (gpointer), acfg->plt_got_info_offsets [i]);
6479 emit_symbol_size (acfg, debug_sym, ".");
6482 if (acfg->thumb_mixed) {
6483 /* Make sure the ARM symbols don't alias the thumb ones */
6484 emit_zero_bytes (acfg, 16);
6487 * Emit a separate set of PLT entries using thumb2 which is called by LLVM generated
6490 for (i = 0; i < acfg->plt_offset; ++i) {
6491 char *debug_sym = NULL;
6492 MonoPltEntry *plt_entry = NULL;
6497 plt_entry = (MonoPltEntry *)g_hash_table_lookup (acfg->plt_offset_to_entry, GUINT_TO_POINTER (i));
6499 /* Skip plt entries not actually called by LLVM code */
6500 if (!plt_entry->llvm_used)
6503 if (acfg->aot_opts.write_symbols) {
6504 if (plt_entry->debug_sym)
6505 debug_sym = g_strdup_printf ("%s_thumb", plt_entry->debug_sym);
6509 #if defined(TARGET_MACH)
6510 fprintf (acfg->fp, " .thumb_func %s\n", debug_sym);
6511 fprintf (acfg->fp, " .no_dead_strip %s\n", debug_sym);
6513 emit_local_symbol (acfg, debug_sym, NULL, TRUE);
6514 emit_label (acfg, debug_sym);
6516 fprintf (acfg->fp, "\n.thumb_func\n");
6518 emit_label (acfg, plt_entry->llvm_symbol);
6521 emit_global_inner (acfg, plt_entry->llvm_symbol, TRUE);
6523 arch_emit_llvm_plt_entry (acfg, acfg->got_symbol, (acfg->plt_got_offset_base + i) * sizeof (gpointer), acfg->plt_got_info_offsets [i]);
6526 emit_symbol_size (acfg, debug_sym, ".");
6532 emit_symbol_size (acfg, acfg->plt_symbol, ".");
6534 emit_info_symbol (acfg, "plt_end");
6538 * emit_trampoline_full:
6540 * If EMIT_TINFO is TRUE, emit additional information which can be used to create a MonoJitInfo for this trampoline by
6541 * create_jit_info_for_trampoline ().
6543 static G_GNUC_UNUSED void
6544 emit_trampoline_full (MonoAotCompile *acfg, int got_offset, MonoTrampInfo *info, gboolean emit_tinfo)
6546 char start_symbol [256];
6547 char end_symbol [256];
6549 guint32 buf_size, info_offset;
6550 MonoJumpInfo *patch_info;
6563 code_size = info->code_size;
6565 unwind_ops = info->unwind_ops;
6567 #ifdef __native_client_codegen__
6568 mono_nacl_fix_patches (code, ji);
6573 sprintf (start_symbol, "%s%s", acfg->user_symbol_prefix, name);
6575 emit_section_change (acfg, ".text", 0);
6576 emit_global (acfg, start_symbol, TRUE);
6577 emit_alignment_code (acfg, AOT_FUNC_ALIGNMENT);
6578 emit_label (acfg, start_symbol);
6580 sprintf (symbol, "%snamed_%s", acfg->temp_prefix, name);
6581 emit_label (acfg, symbol);
6584 * The code should access everything through the GOT, so we pass
6587 emit_and_reloc_code (acfg, NULL, code, code_size, ji, TRUE, NULL);
6589 emit_symbol_size (acfg, start_symbol, ".");
6592 sprintf (end_symbol, "%snamede_%s", acfg->temp_prefix, name);
6593 emit_label (acfg, end_symbol);
6598 /* Sort relocations */
6599 patches = g_ptr_array_new ();
6600 for (patch_info = ji; patch_info; patch_info = patch_info->next)
6601 if (patch_info->type != MONO_PATCH_INFO_NONE)
6602 g_ptr_array_add (patches, patch_info);
6603 g_ptr_array_sort (patches, compare_patches);
6605 buf_size = patches->len * 128 + 128;
6606 buf = (guint8 *)g_malloc (buf_size);
6609 encode_patch_list (acfg, patches, patches->len, FALSE, got_offset, p, &p);
6610 g_assert (p - buf < buf_size);
6612 sprintf (symbol, "%s%s_p", acfg->user_symbol_prefix, name);
6614 info_offset = add_to_blob (acfg, buf, p - buf);
6616 emit_section_change (acfg, RODATA_SECT, 0);
6617 emit_global (acfg, symbol, FALSE);
6618 emit_label (acfg, symbol);
6620 emit_int32 (acfg, info_offset);
6624 guint32 encoded_len;
6628 * Emit additional information which can be used to reconstruct a partial MonoTrampInfo.
6630 encoded = mono_unwind_ops_encode (info->unwind_ops, &encoded_len);
6631 uw_offset = get_unwind_info_offset (acfg, encoded, encoded_len);
6634 emit_symbol_diff (acfg, end_symbol, start_symbol, 0);
6635 emit_int32 (acfg, uw_offset);
6638 /* Emit debug info */
6642 sprintf (symbol, "%s", name);
6643 sprintf (symbol2, "%snamed_%s", acfg->temp_prefix, name);
6646 mono_dwarf_writer_emit_trampoline (acfg->dwarf, symbol, symbol2, NULL, NULL, code_size, unwind_ops);
6650 static G_GNUC_UNUSED void
6651 emit_trampoline (MonoAotCompile *acfg, int got_offset, MonoTrampInfo *info)
6653 emit_trampoline_full (acfg, got_offset, info, TRUE);
6657 emit_trampolines (MonoAotCompile *acfg)
6660 char end_symbol [256];
6661 int i, tramp_got_offset;
6663 #ifdef MONO_ARCH_HAVE_FULL_AOT_TRAMPOLINES
6667 if (!mono_aot_mode_is_full (&acfg->aot_opts) || acfg->aot_opts.llvm_only)
6670 g_assert (acfg->image->assembly);
6672 /* Currently, we emit most trampolines into the mscorlib AOT image. */
6673 if (strcmp (acfg->image->assembly->aname.name, "mscorlib") == 0) {
6674 #ifdef MONO_ARCH_HAVE_FULL_AOT_TRAMPOLINES
6675 MonoTrampInfo *info;
6678 * Emit the generic trampolines.
6680 * We could save some code by treating the generic trampolines as a wrapper
6681 * method, but that approach has its own complexities, so we choose the simpler
6684 for (tramp_type = 0; tramp_type < MONO_TRAMPOLINE_NUM; ++tramp_type) {
6685 /* we overload the boolean here to indicate the slightly different trampoline needed, see mono_arch_create_generic_trampoline() */
6686 #ifdef DISABLE_REMOTING
6687 if (tramp_type == MONO_TRAMPOLINE_GENERIC_VIRTUAL_REMOTING)
6690 #ifndef MONO_ARCH_HAVE_HANDLER_BLOCK_GUARD
6691 if (tramp_type == MONO_TRAMPOLINE_HANDLER_BLOCK_GUARD)
6694 mono_arch_create_generic_trampoline ((MonoTrampolineType)tramp_type, &info, acfg->aot_opts.use_trampolines_page? 2: TRUE);
6695 emit_trampoline (acfg, acfg->got_offset, info);
6698 /* Emit the exception related code pieces */
6699 mono_arch_get_restore_context (&info, TRUE);
6700 emit_trampoline (acfg, acfg->got_offset, info);
6701 mono_arch_get_call_filter (&info, TRUE);
6702 emit_trampoline (acfg, acfg->got_offset, info);
6703 mono_arch_get_throw_exception (&info, TRUE);
6704 emit_trampoline (acfg, acfg->got_offset, info);
6705 mono_arch_get_rethrow_exception (&info, TRUE);
6706 emit_trampoline (acfg, acfg->got_offset, info);
6707 mono_arch_get_throw_corlib_exception (&info, TRUE);
6708 emit_trampoline (acfg, acfg->got_offset, info);
6710 #ifdef MONO_ARCH_HAVE_SDB_TRAMPOLINES
6711 mono_arch_create_sdb_trampoline (TRUE, &info, TRUE);
6712 emit_trampoline (acfg, acfg->got_offset, info);
6713 mono_arch_create_sdb_trampoline (FALSE, &info, TRUE);
6714 emit_trampoline (acfg, acfg->got_offset, info);
6717 #ifdef MONO_ARCH_GSHAREDVT_SUPPORTED
6718 mono_arch_get_gsharedvt_trampoline (&info, TRUE);
6720 emit_trampoline_full (acfg, acfg->got_offset, info, TRUE);
6722 /* Create a separate out trampoline for more information in stack traces */
6723 info->name = g_strdup ("gsharedvt_out_trampoline");
6724 emit_trampoline_full (acfg, acfg->got_offset, info, TRUE);
6728 #if defined(MONO_ARCH_HAVE_GET_TRAMPOLINES)
6730 GSList *l = mono_arch_get_trampolines (TRUE);
6733 MonoTrampInfo *info = (MonoTrampInfo *)l->data;
6735 emit_trampoline (acfg, acfg->got_offset, info);
6741 for (i = 0; i < acfg->aot_opts.nrgctx_fetch_trampolines; ++i) {
6744 offset = MONO_RGCTX_SLOT_MAKE_RGCTX (i);
6745 mono_arch_create_rgctx_lazy_fetch_trampoline (offset, &info, TRUE);
6746 emit_trampoline (acfg, acfg->got_offset, info);
6748 offset = MONO_RGCTX_SLOT_MAKE_MRGCTX (i);
6749 mono_arch_create_rgctx_lazy_fetch_trampoline (offset, &info, TRUE);
6750 emit_trampoline (acfg, acfg->got_offset, info);
6753 #ifdef MONO_ARCH_HAVE_GENERAL_RGCTX_LAZY_FETCH_TRAMPOLINE
6754 mono_arch_create_general_rgctx_lazy_fetch_trampoline (&info, TRUE);
6755 emit_trampoline (acfg, acfg->got_offset, info);
6761 /* delegate_invoke_impl trampolines */
6762 l = mono_arch_get_delegate_invoke_impls ();
6764 MonoTrampInfo *info = (MonoTrampInfo *)l->data;
6766 emit_trampoline (acfg, acfg->got_offset, info);
6771 #endif /* #ifdef MONO_ARCH_HAVE_FULL_AOT_TRAMPOLINES */
6773 /* Emit trampolines which are numerous */
6776 * These include the following:
6777 * - specific trampolines
6778 * - static rgctx invoke trampolines
6780 * These trampolines have the same code, they are parameterized by GOT
6782 * They are defined in this file, in the arch_... routines instead of
6783 * in tramp-<ARCH>.c, since it is easier to do it this way.
6787 * When running in aot-only mode, we can't create specific trampolines at
6788 * runtime, so we create a few, and save them in the AOT file.
6789 * Normal trampolines embed their argument as a literal inside the
6790 * trampoline code, we can't do that here, so instead we embed an offset
6791 * which needs to be added to the trampoline address to get the address of
6792 * the GOT slot which contains the argument value.
6793 * The generated trampolines jump to the generic trampolines using another
6794 * GOT slot, which will be setup by the AOT loader to point to the
6795 * generic trampoline code of the given type.
6799 * FIXME: Maybe we should use more specific trampolines (i.e. one class init for
6803 emit_section_change (acfg, ".text", 0);
6805 tramp_got_offset = acfg->got_offset;
6807 for (ntype = 0; ntype < MONO_AOT_TRAMP_NUM; ++ntype) {
6809 case MONO_AOT_TRAMP_SPECIFIC:
6810 sprintf (symbol, "specific_trampolines");
6812 case MONO_AOT_TRAMP_STATIC_RGCTX:
6813 sprintf (symbol, "static_rgctx_trampolines");
6815 case MONO_AOT_TRAMP_IMT_THUNK:
6816 sprintf (symbol, "imt_thunks");
6818 case MONO_AOT_TRAMP_GSHAREDVT_ARG:
6819 sprintf (symbol, "gsharedvt_arg_trampolines");
6822 g_assert_not_reached ();
6825 sprintf (end_symbol, "%s_e", symbol);
6827 if (acfg->aot_opts.write_symbols)
6828 emit_local_symbol (acfg, symbol, end_symbol, TRUE);
6830 emit_alignment_code (acfg, AOT_FUNC_ALIGNMENT);
6831 emit_info_symbol (acfg, symbol);
6833 acfg->trampoline_got_offset_base [ntype] = tramp_got_offset;
6835 for (i = 0; i < acfg->num_trampolines [ntype]; ++i) {
6839 case MONO_AOT_TRAMP_SPECIFIC:
6840 arch_emit_specific_trampoline (acfg, tramp_got_offset, &tramp_size);
6841 tramp_got_offset += 2;
6843 case MONO_AOT_TRAMP_STATIC_RGCTX:
6844 arch_emit_static_rgctx_trampoline (acfg, tramp_got_offset, &tramp_size);
6845 tramp_got_offset += 2;
6847 case MONO_AOT_TRAMP_IMT_THUNK:
6848 arch_emit_imt_thunk (acfg, tramp_got_offset, &tramp_size);
6849 tramp_got_offset += 1;
6851 case MONO_AOT_TRAMP_GSHAREDVT_ARG:
6852 arch_emit_gsharedvt_arg_trampoline (acfg, tramp_got_offset, &tramp_size);
6853 tramp_got_offset += 2;
6856 g_assert_not_reached ();
6858 #ifdef __native_client_codegen__
6859 /* align to avoid 32-byte boundary crossings */
6860 emit_alignment (acfg, AOT_FUNC_ALIGNMENT);
6863 if (!acfg->trampoline_size [ntype]) {
6864 g_assert (tramp_size);
6865 acfg->trampoline_size [ntype] = tramp_size;
6869 emit_label (acfg, end_symbol);
6870 emit_int32 (acfg, 0);
6873 arch_emit_specific_trampoline_pages (acfg);
6875 /* Reserve some entries at the end of the GOT for our use */
6876 acfg->num_trampoline_got_entries = tramp_got_offset - acfg->got_offset;
6879 acfg->got_offset += acfg->num_trampoline_got_entries;
6883 str_begins_with (const char *str1, const char *str2)
6885 int len = strlen (str2);
6886 return strncmp (str1, str2, len) == 0;
6890 mono_aot_readonly_field_override (MonoClassField *field)
6893 for (rdv = readonly_values; rdv; rdv = rdv->next) {
6894 char *p = rdv->name;
6896 len = strlen (field->parent->name_space);
6897 if (strncmp (p, field->parent->name_space, len))
6902 len = strlen (field->parent->name);
6903 if (strncmp (p, field->parent->name, len))
6908 if (strcmp (p, field->name))
6910 switch (rdv->type) {
6912 return &rdv->value.i1;
6914 return &rdv->value.i2;
6916 return &rdv->value.i4;
6925 add_readonly_value (MonoAotOptions *opts, const char *val)
6930 /* the format of val is:
6931 * namespace.typename.fieldname=type/value
6932 * type can be i1 for uint8/int8/boolean, i2 for uint16/int16/char, i4 for uint32/int32
6934 fval = strrchr (val, '/');
6936 fprintf (stderr, "AOT : invalid format for readonly field '%s', missing /.\n", val);
6939 tval = strrchr (val, '=');
6941 fprintf (stderr, "AOT : invalid format for readonly field '%s', missing =.\n", val);
6944 rdv = g_new0 (ReadOnlyValue, 1);
6945 rdv->name = (char *)g_malloc0 (tval - val + 1);
6946 memcpy (rdv->name, val, tval - val);
6949 if (strncmp (tval, "i1", 2) == 0) {
6950 rdv->value.i1 = atoi (fval);
6951 rdv->type = MONO_TYPE_I1;
6952 } else if (strncmp (tval, "i2", 2) == 0) {
6953 rdv->value.i2 = atoi (fval);
6954 rdv->type = MONO_TYPE_I2;
6955 } else if (strncmp (tval, "i4", 2) == 0) {
6956 rdv->value.i4 = atoi (fval);
6957 rdv->type = MONO_TYPE_I4;
6959 fprintf (stderr, "AOT : unsupported type for readonly field '%s'.\n", tval);
6962 rdv->next = readonly_values;
6963 readonly_values = rdv;
6967 clean_path (gchar * path)
6972 if (g_str_has_suffix (path, G_DIR_SEPARATOR_S))
6975 gchar *clean = g_strconcat (path, G_DIR_SEPARATOR_S, NULL);
6982 wrap_path (gchar * path)
6988 // If the string contains no spaces, just return the original string.
6989 if (strstr (path, " ") == NULL)
6992 // If the string is already wrapped in quotes, return it.
6993 len = strlen (path);
6994 if (len >= 2 && path[0] == '\"' && path[len-1] == '\"')
6997 // If the string contains spaces, then wrap it in quotes.
6998 gchar *clean = g_strdup_printf ("\"%s\"", path);
7004 mono_aot_split_options (const char *aot_options)
7006 enum MonoAotOptionState {
7007 MONO_AOT_OPTION_STATE_DEFAULT,
7008 MONO_AOT_OPTION_STATE_STRING,
7009 MONO_AOT_OPTION_STATE_ESCAPE,
7012 GPtrArray *args = g_ptr_array_new ();
7013 enum MonoAotOptionState state = MONO_AOT_OPTION_STATE_DEFAULT;
7014 gchar const *opt_start = aot_options;
7015 gboolean end_of_string = FALSE;
7018 g_return_val_if_fail (aot_options != NULL, NULL);
7020 while ((cur = *aot_options) != '\0') {
7021 if (state == MONO_AOT_OPTION_STATE_ESCAPE)
7026 // If we find a quote, then if we're in the default case then
7027 // it means we've found the start of a string, if not then it
7028 // means we've found the end of the string and should switch
7029 // back to the default case.
7031 case MONO_AOT_OPTION_STATE_DEFAULT:
7032 state = MONO_AOT_OPTION_STATE_STRING;
7034 case MONO_AOT_OPTION_STATE_STRING:
7035 state = MONO_AOT_OPTION_STATE_DEFAULT;
7037 case MONO_AOT_OPTION_STATE_ESCAPE:
7038 g_assert_not_reached ();
7043 // If we've found an escaping operator, then this means we
7044 // should not process the next character if inside a string.
7045 if (state == MONO_AOT_OPTION_STATE_STRING)
7046 state = MONO_AOT_OPTION_STATE_ESCAPE;
7049 // If we're in the default state then this means we've found
7050 // an option, store it for later processing.
7051 if (state == MONO_AOT_OPTION_STATE_DEFAULT)
7058 // If the next character is end of string, then process the last option.
7059 if (*(aot_options) == '\0') {
7060 end_of_string = TRUE;
7066 g_ptr_array_add (args, g_strndup (opt_start, aot_options - opt_start));
7067 opt_start = ++aot_options;
7077 mono_aot_parse_options (const char *aot_options, MonoAotOptions *opts)
7081 args = mono_aot_split_options (aot_options ? aot_options : "");
7082 for (int i = 0; i < args->len; ++i) {
7083 const char *arg = (const char *)g_ptr_array_index (args, i);
7085 if (str_begins_with (arg, "outfile=")) {
7086 opts->outfile = g_strdup (arg + strlen ("outfile="));
7087 } else if (str_begins_with (arg, "llvm-outfile=")) {
7088 opts->llvm_outfile = g_strdup (arg + strlen ("llvm-outfile="));
7089 } else if (str_begins_with (arg, "temp-path=")) {
7090 opts->temp_path = clean_path (g_strdup (arg + strlen ("temp-path=")));
7091 } else if (str_begins_with (arg, "save-temps")) {
7092 opts->save_temps = TRUE;
7093 } else if (str_begins_with (arg, "keep-temps")) {
7094 opts->save_temps = TRUE;
7095 } else if (str_begins_with (arg, "write-symbols")) {
7096 opts->write_symbols = TRUE;
7097 } else if (str_begins_with (arg, "no-write-symbols")) {
7098 opts->write_symbols = FALSE;
7099 } else if (str_begins_with (arg, "metadata-only")) {
7100 opts->metadata_only = TRUE;
7101 } else if (str_begins_with (arg, "bind-to-runtime-version")) {
7102 opts->bind_to_runtime_version = TRUE;
7103 } else if (str_begins_with (arg, "full")) {
7104 opts->mode = MONO_AOT_MODE_FULL;
7105 } else if (str_begins_with (arg, "hybrid")) {
7106 opts->mode = MONO_AOT_MODE_HYBRID;
7107 } else if (str_begins_with (arg, "threads=")) {
7108 opts->nthreads = atoi (arg + strlen ("threads="));
7109 } else if (str_begins_with (arg, "static")) {
7110 opts->static_link = TRUE;
7111 opts->no_dlsym = TRUE;
7112 } else if (str_begins_with (arg, "asmonly")) {
7113 opts->asm_only = TRUE;
7114 } else if (str_begins_with (arg, "asmwriter")) {
7115 opts->asm_writer = TRUE;
7116 } else if (str_begins_with (arg, "nodebug")) {
7117 opts->nodebug = TRUE;
7118 } else if (str_begins_with (arg, "dwarfdebug")) {
7119 opts->dwarf_debug = TRUE;
7120 } else if (str_begins_with (arg, "nopagetrampolines")) {
7121 opts->use_trampolines_page = FALSE;
7122 } else if (str_begins_with (arg, "ntrampolines=")) {
7123 opts->ntrampolines = atoi (arg + strlen ("ntrampolines="));
7124 } else if (str_begins_with (arg, "nrgctx-trampolines=")) {
7125 opts->nrgctx_trampolines = atoi (arg + strlen ("nrgctx-trampolines="));
7126 } else if (str_begins_with (arg, "nimt-trampolines=")) {
7127 opts->nimt_trampolines = atoi (arg + strlen ("nimt-trampolines="));
7128 } else if (str_begins_with (arg, "ngsharedvt-trampolines=")) {
7129 opts->ngsharedvt_arg_trampolines = atoi (arg + strlen ("ngsharedvt-trampolines="));
7130 } else if (str_begins_with (arg, "tool-prefix=")) {
7131 opts->tool_prefix = g_strdup (arg + strlen ("tool-prefix="));
7132 } else if (str_begins_with (arg, "ld-flags=")) {
7133 opts->ld_flags = g_strdup (arg + strlen ("ld-flags="));
7134 } else if (str_begins_with (arg, "soft-debug")) {
7135 opts->soft_debug = TRUE;
7136 } else if (str_begins_with (arg, "gen-seq-points-file=")) {
7137 debug_options.gen_seq_points_compact_data = TRUE;
7138 opts->gen_seq_points_file = TRUE;
7139 opts->gen_seq_points_file_path = g_strdup (arg + strlen ("gen-seq-points-file="));;
7140 } else if (str_begins_with (arg, "gen-seq-points-file")) {
7141 debug_options.gen_seq_points_compact_data = TRUE;
7142 opts->gen_seq_points_file = TRUE;
7143 } else if (str_begins_with (arg, "direct-pinvoke")) {
7144 opts->direct_pinvoke = TRUE;
7145 } else if (str_begins_with (arg, "direct-icalls")) {
7146 opts->direct_icalls = TRUE;
7147 } else if (str_begins_with (arg, "no-direct-calls")) {
7148 opts->no_direct_calls = TRUE;
7149 } else if (str_begins_with (arg, "print-skipped")) {
7150 opts->print_skipped_methods = TRUE;
7151 } else if (str_begins_with (arg, "stats")) {
7153 } else if (str_begins_with (arg, "no-instances")) {
7154 opts->no_instances = TRUE;
7155 } else if (str_begins_with (arg, "log-generics")) {
7156 opts->log_generics = TRUE;
7157 } else if (str_begins_with (arg, "log-instances=")) {
7158 opts->log_instances = TRUE;
7159 opts->instances_logfile_path = g_strdup (arg + strlen ("log-instances="));
7160 } else if (str_begins_with (arg, "log-instances")) {
7161 opts->log_instances = TRUE;
7162 } else if (str_begins_with (arg, "internal-logfile=")) {
7163 opts->logfile = g_strdup (arg + strlen ("internal-logfile="));
7164 } else if (str_begins_with (arg, "mtriple=")) {
7165 opts->mtriple = g_strdup (arg + strlen ("mtriple="));
7166 } else if (str_begins_with (arg, "llvm-path=")) {
7167 opts->llvm_path = clean_path (g_strdup (arg + strlen ("llvm-path=")));
7168 } else if (!strcmp (arg, "llvm")) {
7170 } else if (str_begins_with (arg, "readonly-value=")) {
7171 add_readonly_value (opts, arg + strlen ("readonly-value="));
7172 } else if (str_begins_with (arg, "info")) {
7173 printf ("AOT target setup: %s.\n", AOT_TARGET_STR);
7175 } else if (str_begins_with (arg, "gc-maps")) {
7176 mini_gc_enable_gc_maps_for_aot ();
7177 } else if (str_begins_with (arg, "dump")) {
7178 opts->dump_json = TRUE;
7179 } else if (str_begins_with (arg, "llvmonly")) {
7180 opts->mode = MONO_AOT_MODE_FULL;
7182 opts->llvm_only = TRUE;
7183 } else if (str_begins_with (arg, "data-outfile=")) {
7184 opts->data_outfile = g_strdup (arg + strlen ("data-outfile="));
7185 } else if (str_begins_with (arg, "help") || str_begins_with (arg, "?")) {
7186 printf ("Supported options for --aot:\n");
7187 printf (" outfile=\n");
7188 printf (" llvm-outfile=\n");
7189 printf (" llvm-path=\n");
7190 printf (" temp-path=\n");
7191 printf (" save-temps\n");
7192 printf (" keep-temps\n");
7193 printf (" write-symbols\n");
7194 printf (" metadata-only\n");
7195 printf (" bind-to-runtime-version\n");
7197 printf (" threads=\n");
7198 printf (" static\n");
7199 printf (" asmonly\n");
7200 printf (" asmwriter\n");
7201 printf (" nodebug\n");
7202 printf (" dwarfdebug\n");
7203 printf (" ntrampolines=\n");
7204 printf (" nrgctx-trampolines=\n");
7205 printf (" nimt-trampolines=\n");
7206 printf (" ngsharedvt-trampolines=\n");
7207 printf (" tool-prefix=\n");
7208 printf (" readonly-value=\n");
7209 printf (" soft-debug\n");
7210 printf (" gen-seq-points-file\n");
7211 printf (" gc-maps\n");
7212 printf (" print-skipped\n");
7213 printf (" no-instances\n");
7214 printf (" stats\n");
7217 printf (" help/?\n");
7220 fprintf (stderr, "AOT : Unknown argument '%s'.\n", arg);
7224 g_free ((gpointer) arg);
7227 if (opts->use_trampolines_page) {
7228 opts->ntrampolines = 0;
7229 opts->nrgctx_trampolines = 0;
7230 opts->nimt_trampolines = 0;
7231 opts->ngsharedvt_arg_trampolines = 0;
7234 g_ptr_array_free (args, /*free_seg=*/TRUE);
7238 add_token_info_hash (gpointer key, gpointer value, gpointer user_data)
7240 MonoMethod *method = (MonoMethod*)key;
7241 MonoJumpInfoToken *ji = (MonoJumpInfoToken*)value;
7242 MonoAotCompile *acfg = (MonoAotCompile *)user_data;
7243 MonoJumpInfoToken *new_ji;
7245 new_ji = (MonoJumpInfoToken *)mono_mempool_alloc0 (acfg->mempool, sizeof (MonoJumpInfoToken));
7246 new_ji->image = ji->image;
7247 new_ji->token = ji->token;
7248 g_hash_table_insert (acfg->token_info_hash, method, new_ji);
7252 can_encode_class (MonoAotCompile *acfg, MonoClass *klass)
7254 if (klass->type_token)
7256 if ((klass->byval_arg.type == MONO_TYPE_VAR) || (klass->byval_arg.type == MONO_TYPE_MVAR) || (klass->byval_arg.type == MONO_TYPE_PTR))
7259 return can_encode_class (acfg, klass->element_class);
7264 can_encode_method (MonoAotCompile *acfg, MonoMethod *method)
7266 if (method->wrapper_type) {
7267 switch (method->wrapper_type) {
7268 case MONO_WRAPPER_NONE:
7269 case MONO_WRAPPER_REMOTING_INVOKE_WITH_CHECK:
7270 case MONO_WRAPPER_XDOMAIN_INVOKE:
7271 case MONO_WRAPPER_STFLD:
7272 case MONO_WRAPPER_LDFLD:
7273 case MONO_WRAPPER_LDFLDA:
7274 case MONO_WRAPPER_LDFLD_REMOTE:
7275 case MONO_WRAPPER_STFLD_REMOTE:
7276 case MONO_WRAPPER_STELEMREF:
7277 case MONO_WRAPPER_ISINST:
7278 case MONO_WRAPPER_PROXY_ISINST:
7279 case MONO_WRAPPER_ALLOC:
7280 case MONO_WRAPPER_REMOTING_INVOKE:
7281 case MONO_WRAPPER_UNKNOWN:
7282 case MONO_WRAPPER_WRITE_BARRIER:
7283 case MONO_WRAPPER_DELEGATE_INVOKE:
7284 case MONO_WRAPPER_DELEGATE_BEGIN_INVOKE:
7285 case MONO_WRAPPER_DELEGATE_END_INVOKE:
7286 case MONO_WRAPPER_SYNCHRONIZED:
7288 case MONO_WRAPPER_MANAGED_TO_MANAGED:
7289 case MONO_WRAPPER_CASTCLASS: {
7290 WrapperInfo *info = mono_marshal_get_wrapper_info (method);
7299 //printf ("Skip (wrapper call): %d -> %s\n", patch_info->type, mono_method_full_name (patch_info->data.method, TRUE));
7303 if (!method->token) {
7304 /* The method is part of a constructed type like Int[,].Set (). */
7305 if (!g_hash_table_lookup (acfg->token_info_hash, method)) {
7306 if (method->klass->rank)
7316 can_encode_patch (MonoAotCompile *acfg, MonoJumpInfo *patch_info)
7318 switch (patch_info->type) {
7319 case MONO_PATCH_INFO_METHOD:
7320 case MONO_PATCH_INFO_METHODCONST:
7321 case MONO_PATCH_INFO_METHOD_CODE_SLOT: {
7322 MonoMethod *method = patch_info->data.method;
7324 return can_encode_method (acfg, method);
7326 case MONO_PATCH_INFO_VTABLE:
7327 case MONO_PATCH_INFO_CLASS:
7328 case MONO_PATCH_INFO_IID:
7329 case MONO_PATCH_INFO_ADJUSTED_IID:
7330 if (!can_encode_class (acfg, patch_info->data.klass)) {
7331 //printf ("Skip: %s\n", mono_type_full_name (&patch_info->data.klass->byval_arg));
7335 case MONO_PATCH_INFO_DELEGATE_TRAMPOLINE: {
7336 if (!can_encode_class (acfg, patch_info->data.del_tramp->klass)) {
7337 //printf ("Skip: %s\n", mono_type_full_name (&patch_info->data.klass->byval_arg));
7342 case MONO_PATCH_INFO_RGCTX_FETCH:
7343 case MONO_PATCH_INFO_RGCTX_SLOT_INDEX: {
7344 MonoJumpInfoRgctxEntry *entry = patch_info->data.rgctx_entry;
7346 if (!can_encode_method (acfg, entry->method))
7348 if (!can_encode_patch (acfg, entry->data))
7360 is_concrete_type (MonoType *t)
7365 if (t->type == MONO_TYPE_VAR || t->type == MONO_TYPE_MVAR)
7367 if (t->type == MONO_TYPE_GENERICINST) {
7368 MonoGenericContext *orig_ctx;
7369 MonoGenericInst *inst;
7372 if (!MONO_TYPE_ISSTRUCT (t))
7374 klass = mono_class_from_mono_type (t);
7375 orig_ctx = &klass->generic_class->context;
7377 inst = orig_ctx->class_inst;
7379 for (i = 0; i < inst->type_argc; ++i) {
7380 arg = mini_get_underlying_type (inst->type_argv [i]);
7381 if (!is_concrete_type (arg))
7385 inst = orig_ctx->method_inst;
7387 for (i = 0; i < inst->type_argc; ++i) {
7388 arg = mini_get_underlying_type (inst->type_argv [i]);
7389 if (!is_concrete_type (arg))
7397 /* LOCKING: Assumes the loader lock is held */
7399 add_gsharedvt_wrappers (MonoAotCompile *acfg, MonoMethodSignature *sig, gboolean gsharedvt_in, gboolean gsharedvt_out)
7401 MonoMethod *wrapper;
7402 gboolean concrete = TRUE;
7403 gboolean add_in = gsharedvt_in;
7404 gboolean add_out = gsharedvt_out;
7406 if (gsharedvt_in && g_hash_table_lookup (acfg->gsharedvt_in_signatures, sig))
7408 if (gsharedvt_out && g_hash_table_lookup (acfg->gsharedvt_out_signatures, sig))
7411 if (!add_in && !add_out)
7414 if (mini_is_gsharedvt_variable_signature (sig))
7418 g_hash_table_insert (acfg->gsharedvt_in_signatures, sig, sig);
7420 g_hash_table_insert (acfg->gsharedvt_out_signatures, sig, sig);
7422 if (!sig->has_type_parameters) {
7423 //printf ("%s\n", mono_signature_full_name (sig));
7426 wrapper = mini_get_gsharedvt_in_sig_wrapper (sig);
7427 add_extra_method (acfg, wrapper);
7429 if (gsharedvt_out) {
7430 wrapper = mini_get_gsharedvt_out_sig_wrapper (sig);
7431 add_extra_method (acfg, wrapper);
7434 /* For signatures creared during generic sharing, convert them to a concrete signature if possible */
7435 MonoMethodSignature *copy = mono_metadata_signature_dup (sig);
7438 //printf ("%s\n", mono_signature_full_name (sig));
7440 copy->ret = mini_get_underlying_type (sig->ret);
7441 if (!is_concrete_type (copy->ret))
7443 for (i = 0; i < sig->param_count; ++i) {
7444 copy->params [i] = mini_get_underlying_type (sig->params [i]);
7445 if (!is_concrete_type (copy->params [i]))
7449 copy->has_type_parameters = 0;
7452 wrapper = mini_get_gsharedvt_in_sig_wrapper (copy);
7453 add_extra_method (acfg, wrapper);
7456 if (gsharedvt_out) {
7457 wrapper = mini_get_gsharedvt_out_sig_wrapper (copy);
7458 add_extra_method (acfg, wrapper);
7461 //printf ("%s\n", mono_method_full_name (wrapper, 1));
7469 * AOT compile a given method.
7470 * This function might be called by multiple threads, so it must be thread-safe.
7473 compile_method (MonoAotCompile *acfg, MonoMethod *method)
7476 MonoJumpInfo *patch_info;
7479 MonoMethod *wrapped;
7483 if (acfg->aot_opts.metadata_only)
7486 mono_acfg_lock (acfg);
7487 index = get_method_index (acfg, method);
7488 mono_acfg_unlock (acfg);
7490 /* fixme: maybe we can also precompile wrapper methods */
7491 if ((method->flags & METHOD_ATTRIBUTE_PINVOKE_IMPL) ||
7492 (method->iflags & METHOD_IMPL_ATTRIBUTE_RUNTIME) ||
7493 (method->flags & METHOD_ATTRIBUTE_ABSTRACT)) {
7494 //printf ("Skip (impossible): %s\n", mono_method_full_name (method, TRUE));
7498 if (method->iflags & METHOD_IMPL_ATTRIBUTE_INTERNAL_CALL)
7501 wrapped = mono_marshal_method_from_wrapper (method);
7502 if (wrapped && (wrapped->iflags & METHOD_IMPL_ATTRIBUTE_INTERNAL_CALL) && wrapped->is_generic)
7503 // FIXME: The wrapper should be generic too, but it is not
7506 if (method->wrapper_type == MONO_WRAPPER_COMINTEROP)
7509 InterlockedIncrement (&acfg->stats.mcount);
7512 if (method->is_generic || method->klass->generic_container) {
7513 InterlockedIncrement (&acfg->stats.genericcount);
7518 //acfg->aot_opts.print_skipped_methods = TRUE;
7521 * Since these methods are the only ones which are compiled with
7522 * AOT support, and they are not used by runtime startup/shutdown code,
7523 * the runtime will not see AOT methods during AOT compilation,so it
7524 * does not need to support them by creating a fake GOT etc.
7526 flags = JIT_FLAG_AOT;
7527 if (mono_aot_mode_is_full (&acfg->aot_opts))
7528 flags = (JitFlags)(flags | JIT_FLAG_FULL_AOT);
7530 flags = (JitFlags)(flags | JIT_FLAG_LLVM);
7531 if (acfg->aot_opts.llvm_only)
7532 flags = (JitFlags)(flags | JIT_FLAG_LLVM_ONLY | JIT_FLAG_EXPLICIT_NULL_CHECKS);
7533 if (acfg->aot_opts.no_direct_calls)
7534 flags = (JitFlags)(flags | JIT_FLAG_NO_DIRECT_ICALLS);
7536 jit_timer = mono_time_track_start ();
7537 cfg = mini_method_compile (method, acfg->opts, mono_get_root_domain (), flags, 0, index);
7538 mono_time_track_end (&mono_jit_stats.jit_time, jit_timer);
7540 mono_loader_clear_error ();
7542 if (cfg->exception_type == MONO_EXCEPTION_GENERIC_SHARING_FAILED) {
7543 if (acfg->aot_opts.print_skipped_methods)
7544 printf ("Skip (gshared failure): %s (%s)\n", mono_method_get_full_name (method), cfg->exception_message);
7545 InterlockedIncrement (&acfg->stats.genericcount);
7548 if (cfg->exception_type != MONO_EXCEPTION_NONE) {
7549 if (acfg->aot_opts.print_skipped_methods)
7550 printf ("Skip (JIT failure): %s\n", mono_method_get_full_name (method));
7551 /* Let the exception happen at runtime */
7555 if (cfg->disable_aot) {
7556 if (acfg->aot_opts.print_skipped_methods)
7557 printf ("Skip (disabled): %s\n", mono_method_get_full_name (method));
7558 InterlockedIncrement (&acfg->stats.ocount);
7559 mono_destroy_compile (cfg);
7562 cfg->method_index = index;
7564 /* Nullify patches which need no aot processing */
7565 for (patch_info = cfg->patch_info; patch_info; patch_info = patch_info->next) {
7566 switch (patch_info->type) {
7567 case MONO_PATCH_INFO_LABEL:
7568 case MONO_PATCH_INFO_BB:
7569 patch_info->type = MONO_PATCH_INFO_NONE;
7576 /* Collect method->token associations from the cfg */
7577 mono_acfg_lock (acfg);
7578 g_hash_table_foreach (cfg->token_info_hash, add_token_info_hash, acfg);
7579 mono_acfg_unlock (acfg);
7580 g_hash_table_destroy (cfg->token_info_hash);
7581 cfg->token_info_hash = NULL;
7584 * Check for absolute addresses.
7587 for (patch_info = cfg->patch_info; patch_info; patch_info = patch_info->next) {
7588 switch (patch_info->type) {
7589 case MONO_PATCH_INFO_ABS:
7590 /* unable to handle this */
7599 if (acfg->aot_opts.print_skipped_methods)
7600 printf ("Skip (abs call): %s\n", mono_method_get_full_name (method));
7601 InterlockedIncrement (&acfg->stats.abscount);
7602 mono_destroy_compile (cfg);
7606 /* Lock for the rest of the code */
7607 mono_acfg_lock (acfg);
7610 acfg->stats.method_categories [METHOD_CAT_GSHAREDVT] ++;
7611 else if (cfg->gshared)
7612 acfg->stats.method_categories [METHOD_CAT_INST] ++;
7613 else if (cfg->method->wrapper_type)
7614 acfg->stats.method_categories [METHOD_CAT_WRAPPER] ++;
7616 acfg->stats.method_categories [METHOD_CAT_NORMAL] ++;
7619 * Check for methods/klasses we can't encode.
7622 for (patch_info = cfg->patch_info; patch_info; patch_info = patch_info->next) {
7623 if (!can_encode_patch (acfg, patch_info))
7628 if (acfg->aot_opts.print_skipped_methods)
7629 printf ("Skip (patches): %s\n", mono_method_get_full_name (method));
7630 acfg->stats.ocount++;
7631 mono_destroy_compile (cfg);
7632 mono_acfg_unlock (acfg);
7636 if (!cfg->compile_llvm)
7637 acfg->has_jitted_code = TRUE;
7639 if (method->is_inflated && acfg->aot_opts.log_instances) {
7640 if (acfg->instances_logfile)
7641 fprintf (acfg->instances_logfile, "%s ### %d\n", mono_method_get_full_name (method), cfg->code_size);
7643 printf ("%s ### %d\n", mono_method_get_full_name (method), cfg->code_size);
7646 /* Adds generic instances referenced by this method */
7648 * The depth is used to avoid infinite loops when generic virtual recursion is
7651 depth = GPOINTER_TO_UINT (g_hash_table_lookup (acfg->method_depth, method));
7652 if (!acfg->aot_opts.no_instances && depth < 32) {
7653 for (patch_info = cfg->patch_info; patch_info; patch_info = patch_info->next) {
7654 switch (patch_info->type) {
7655 case MONO_PATCH_INFO_RGCTX_FETCH:
7656 case MONO_PATCH_INFO_RGCTX_SLOT_INDEX:
7657 case MONO_PATCH_INFO_METHOD: {
7658 MonoMethod *m = NULL;
7660 if (patch_info->type == MONO_PATCH_INFO_RGCTX_FETCH || patch_info->type == MONO_PATCH_INFO_RGCTX_SLOT_INDEX) {
7661 MonoJumpInfoRgctxEntry *e = patch_info->data.rgctx_entry;
7663 if (e->info_type == MONO_RGCTX_INFO_GENERIC_METHOD_CODE)
7664 m = e->data->data.method;
7666 m = patch_info->data.method;
7671 if (m->is_inflated) {
7672 if (!(mono_class_generic_sharing_enabled (m->klass) &&
7673 mono_method_is_generic_sharable_full (m, FALSE, FALSE, FALSE)) &&
7674 (!method_has_type_vars (m) || mono_method_is_generic_sharable_full (m, TRUE, TRUE, FALSE))) {
7675 if (m->iflags & METHOD_IMPL_ATTRIBUTE_INTERNAL_CALL) {
7676 if (mono_aot_mode_is_full (&acfg->aot_opts) && !method_has_type_vars (m))
7677 add_extra_method_with_depth (acfg, mono_marshal_get_native_wrapper (m, TRUE, TRUE), depth + 1);
7679 add_extra_method_with_depth (acfg, m, depth + 1);
7680 add_types_from_method_header (acfg, m);
7683 add_generic_class_with_depth (acfg, m->klass, depth + 5, "method");
7685 if (m->wrapper_type == MONO_WRAPPER_MANAGED_TO_MANAGED) {
7686 WrapperInfo *info = mono_marshal_get_wrapper_info (m);
7688 if (info && info->subtype == WRAPPER_SUBTYPE_ELEMENT_ADDR)
7689 add_extra_method_with_depth (acfg, m, depth + 1);
7693 case MONO_PATCH_INFO_VTABLE: {
7694 MonoClass *klass = patch_info->data.klass;
7696 if (klass->generic_class && !mini_class_is_generic_sharable (klass))
7697 add_generic_class_with_depth (acfg, klass, depth + 5, "vtable");
7700 case MONO_PATCH_INFO_SFLDA: {
7701 MonoClass *klass = patch_info->data.field->parent;
7703 /* The .cctor needs to run at runtime. */
7704 if (klass->generic_class && !mono_generic_context_is_sharable (&klass->generic_class->context, FALSE) && mono_class_get_cctor (klass))
7705 add_extra_method_with_depth (acfg, mono_class_get_cctor (klass), depth + 1);
7714 /* Determine whenever the method has GOT slots */
7715 for (patch_info = cfg->patch_info; patch_info; patch_info = patch_info->next) {
7716 switch (patch_info->type) {
7717 case MONO_PATCH_INFO_GOT_OFFSET:
7718 case MONO_PATCH_INFO_NONE:
7719 case MONO_PATCH_INFO_GC_CARD_TABLE_ADDR:
7720 case MONO_PATCH_INFO_GC_NURSERY_START:
7721 case MONO_PATCH_INFO_GC_NURSERY_BITS:
7723 case MONO_PATCH_INFO_IMAGE:
7724 /* The assembly is stored in GOT slot 0 */
7725 if (patch_info->data.image != acfg->image)
7726 cfg->has_got_slots = TRUE;
7729 if (!is_plt_patch (patch_info) || (cfg->compile_llvm && acfg->aot_opts.llvm_only))
7730 cfg->has_got_slots = TRUE;
7735 if (!cfg->has_got_slots)
7736 InterlockedIncrement (&acfg->stats.methods_without_got_slots);
7738 /* Add gsharedvt wrappers for signatures used by the method */
7739 if (acfg->aot_opts.llvm_only) {
7742 if (!cfg->method->wrapper_type || cfg->method->wrapper_type == MONO_WRAPPER_DELEGATE_INVOKE)
7743 /* These only need out wrappers */
7744 add_gsharedvt_wrappers (acfg, mono_method_signature (cfg->method), FALSE, TRUE);
7746 for (l = cfg->signatures; l; l = l->next) {
7747 MonoMethodSignature *sig = mono_metadata_signature_dup ((MonoMethodSignature*)l->data);
7749 /* These only need in wrappers */
7750 add_gsharedvt_wrappers (acfg, sig, TRUE, FALSE);
7755 * FIXME: Instead of this mess, allocate the patches from the aot mempool.
7757 /* Make a copy of the patch info which is in the mempool */
7759 MonoJumpInfo *patches = NULL, *patches_end = NULL;
7761 for (patch_info = cfg->patch_info; patch_info; patch_info = patch_info->next) {
7762 MonoJumpInfo *new_patch_info = mono_patch_info_dup_mp (acfg->mempool, patch_info);
7765 patches = new_patch_info;
7767 patches_end->next = new_patch_info;
7768 patches_end = new_patch_info;
7770 cfg->patch_info = patches;
7772 /* Make a copy of the unwind info */
7774 GSList *l, *unwind_ops;
7778 for (l = cfg->unwind_ops; l; l = l->next) {
7779 op = (MonoUnwindOp *)mono_mempool_alloc (acfg->mempool, sizeof (MonoUnwindOp));
7780 memcpy (op, l->data, sizeof (MonoUnwindOp));
7781 unwind_ops = g_slist_prepend_mempool (acfg->mempool, unwind_ops, op);
7783 cfg->unwind_ops = g_slist_reverse (unwind_ops);
7785 /* Make a copy of the argument/local info */
7788 MonoInst **args, **locals;
7789 MonoMethodSignature *sig;
7790 MonoMethodHeader *header;
7793 sig = mono_method_signature (method);
7794 args = (MonoInst **)mono_mempool_alloc (acfg->mempool, sizeof (MonoInst*) * (sig->param_count + sig->hasthis));
7795 for (i = 0; i < sig->param_count + sig->hasthis; ++i) {
7796 args [i] = (MonoInst *)mono_mempool_alloc (acfg->mempool, sizeof (MonoInst));
7797 memcpy (args [i], cfg->args [i], sizeof (MonoInst));
7801 header = mono_method_get_header_checked (method, &error);
7802 mono_error_assert_ok (&error); /* FIXME don't swallow the error */
7803 locals = (MonoInst **)mono_mempool_alloc (acfg->mempool, sizeof (MonoInst*) * header->num_locals);
7804 for (i = 0; i < header->num_locals; ++i) {
7805 locals [i] = (MonoInst *)mono_mempool_alloc (acfg->mempool, sizeof (MonoInst));
7806 memcpy (locals [i], cfg->locals [i], sizeof (MonoInst));
7808 cfg->locals = locals;
7811 /* Free some fields used by cfg to conserve memory */
7812 mono_mempool_destroy (cfg->mempool);
7813 cfg->mempool = NULL;
7814 g_free (cfg->varinfo);
7815 cfg->varinfo = NULL;
7819 mono_regstate_free (cfg->rs);
7823 //printf ("Compile: %s\n", mono_method_full_name (method, TRUE));
7825 while (index >= acfg->cfgs_size) {
7826 MonoCompile **new_cfgs;
7829 new_size = acfg->cfgs_size * 2;
7830 new_cfgs = g_new0 (MonoCompile*, new_size);
7831 memcpy (new_cfgs, acfg->cfgs, sizeof (MonoCompile*) * acfg->cfgs_size);
7832 g_free (acfg->cfgs);
7833 acfg->cfgs = new_cfgs;
7834 acfg->cfgs_size = new_size;
7836 acfg->cfgs [index] = cfg;
7838 g_hash_table_insert (acfg->method_to_cfg, cfg->orig_method, cfg);
7840 mono_update_jit_stats (cfg);
7843 if (cfg->orig_method->wrapper_type)
7844 g_ptr_array_add (acfg->extra_methods, cfg->orig_method);
7847 mono_acfg_unlock (acfg);
7849 InterlockedIncrement (&acfg->stats.ccount);
7853 compile_thread_main (gpointer *user_data)
7855 MonoDomain *domain = (MonoDomain *)user_data [0];
7856 MonoAotCompile *acfg = (MonoAotCompile *)user_data [1];
7857 GPtrArray *methods = (GPtrArray *)user_data [2];
7860 mono_thread_attach (domain);
7862 for (i = 0; i < methods->len; ++i)
7863 compile_method (acfg, (MonoMethod *)g_ptr_array_index (methods, i));
7867 load_profile_files (MonoAotCompile *acfg)
7871 int file_index, res, method_index, i;
7874 GList *unordered, *l;
7879 tmp = g_strdup_printf ("%s/.mono/aot-profile-data/%s-%d", g_get_home_dir (), acfg->image->assembly_name, file_index);
7881 if (!g_file_test (tmp, G_FILE_TEST_IS_REGULAR)) {
7886 infile = fopen (tmp, "r");
7889 printf ("Using profile data file '%s'\n", tmp);
7894 res = fscanf (infile, "%32s\n", ver);
7895 if ((res != 1) || strcmp (ver, "#VER:2") != 0) {
7896 printf ("Profile file has wrong version or invalid.\n");
7903 MonoMethodDesc *desc;
7906 if (fgets (name, 1023, infile) == NULL)
7909 /* Kill the newline */
7910 if (strlen (name) > 0)
7911 name [strlen (name) - 1] = '\0';
7913 desc = mono_method_desc_new (name, TRUE);
7915 method = mono_method_desc_search_in_image (desc, acfg->image);
7917 if (method && mono_method_get_token (method)) {
7918 token = mono_method_get_token (method);
7919 method_index = mono_metadata_token_index (token) - 1;
7922 for (i = 0; i < acfg->method_order->len; ++i) {
7923 if (g_ptr_array_index (acfg->method_order, i) == GUINT_TO_POINTER (method_index)) {
7929 g_ptr_array_add (acfg->method_order, GUINT_TO_POINTER (method_index));
7931 //printf ("No method found matching '%s'.\n", name);
7937 /* Add missing methods */
7939 for (method_index = 0; method_index < acfg->image->tables [MONO_TABLE_METHOD].rows; ++method_index) {
7941 for (i = 0; i < acfg->method_order->len; ++i) {
7942 if (g_ptr_array_index (acfg->method_order, i) == GUINT_TO_POINTER (method_index)) {
7948 unordered = g_list_prepend (unordered, GUINT_TO_POINTER (method_index));
7950 unordered = g_list_reverse (unordered);
7951 for (l = unordered; l; l = l->next)
7952 g_ptr_array_add (acfg->method_order, l->data);
7955 /* Used by the LLVM backend */
7957 mono_aot_get_got_offset (MonoJumpInfo *ji)
7959 return get_got_offset (llvm_acfg, TRUE, ji);
7963 * mono_aot_is_shared_got_offset:
7965 * Return whenever OFFSET refers to a GOT slot which is preinitialized
7966 * when the AOT image is loaded.
7969 mono_aot_is_shared_got_offset (int offset)
7971 return offset < llvm_acfg->nshared_got_entries;
7975 mono_aot_get_method_name (MonoCompile *cfg)
7977 if (llvm_acfg->aot_opts.static_link)
7978 /* Include the assembly name too to avoid duplicate symbol errors */
7979 return g_strdup_printf ("%s_%s", llvm_acfg->assembly_name_sym, get_debug_sym (cfg->orig_method, "", llvm_acfg->method_label_hash));
7981 return get_debug_sym (cfg->orig_method, "", llvm_acfg->method_label_hash);
7985 * mono_aot_is_linkonce_method:
7987 * Return whenever METHOD should be emitted with linkonce linkage,
7988 * eliminating duplicate copies when compiling in static mode.
7991 mono_aot_is_linkonce_method (MonoMethod *method)
7995 // FIXME: Add more cases
7996 if (method->wrapper_type != MONO_WRAPPER_UNKNOWN)
7998 info = mono_marshal_get_wrapper_info (method);
7999 if ((info && (info->subtype == WRAPPER_SUBTYPE_GSHAREDVT_IN_SIG || info->subtype == WRAPPER_SUBTYPE_GSHAREDVT_OUT_SIG)))
8005 append_mangled_type (GString *s, MonoType *t)
8008 g_string_append_printf (s, "b");
8010 case MONO_TYPE_VOID:
8011 g_string_append_printf (s, "void_");
8014 g_string_append_printf (s, "i1");
8017 g_string_append_printf (s, "u1");
8020 g_string_append_printf (s, "i2");
8023 g_string_append_printf (s, "u2");
8026 g_string_append_printf (s, "i4");
8029 g_string_append_printf (s, "u4");
8032 g_string_append_printf (s, "i8");
8035 g_string_append_printf (s, "u8");
8038 g_string_append_printf (s, "ii");
8041 g_string_append_printf (s, "ui");
8044 g_string_append_printf (s, "fl");
8047 g_string_append_printf (s, "do");
8050 char *fullname = mono_type_full_name (t);
8056 * Have to create a mangled name which is:
8060 temp = g_string_new ("");
8061 len = strlen (fullname);
8062 for (i = 0; i < len; ++i) {
8063 char c = fullname [i];
8065 g_string_append_c (temp, c);
8066 } else if (c == '_') {
8067 g_string_append_c (temp, '_');
8068 g_string_append_c (temp, '_');
8070 g_string_append_c (temp, '_');
8071 g_string_append_printf (temp, "%x", (int)c);
8074 temps = g_string_free (temp, FALSE);
8075 /* Include the length to avoid different length type names aliasing each other */
8076 g_string_append_printf (s, "cl%x_%s_", strlen (temps), temps);
8085 append_mangled_signature (GString *s, MonoMethodSignature *sig)
8090 supported = append_mangled_type (s, sig->ret);
8094 g_string_append_printf (s, "this_");
8095 for (i = 0; i < sig->param_count; ++i) {
8096 supported = append_mangled_type (s, sig->params [i]);
8105 * mono_aot_get_mangled_method_name:
8107 * Return a unique mangled name for METHOD, or NULL.
8110 mono_aot_get_mangled_method_name (MonoMethod *method)
8116 // FIXME: Add more cases
8117 if (method->wrapper_type != MONO_WRAPPER_UNKNOWN)
8119 info = mono_marshal_get_wrapper_info (method);
8120 if (!(info && (info->subtype == WRAPPER_SUBTYPE_GSHAREDVT_IN_SIG || info->subtype == WRAPPER_SUBTYPE_GSHAREDVT_OUT_SIG)))
8123 s = g_string_new ("");
8125 g_string_append_printf (s, "aot_method_w_");
8127 switch (info->subtype) {
8128 case WRAPPER_SUBTYPE_GSHAREDVT_IN_SIG:
8129 g_string_append_printf (s, "gsharedvt_in_");
8131 case WRAPPER_SUBTYPE_GSHAREDVT_OUT_SIG:
8132 g_string_append_printf (s, "gsharedvt_out_");
8135 g_assert_not_reached ();
8139 supported = append_mangled_signature (s, info->d.gsharedvt.sig);
8141 g_string_free (s, TRUE);
8145 return g_string_free (s, FALSE);
8149 mono_aot_is_direct_callable (MonoJumpInfo *patch_info)
8151 return is_direct_callable (llvm_acfg, NULL, patch_info);
8155 mono_aot_mark_unused_llvm_plt_entry (MonoJumpInfo *patch_info)
8157 MonoPltEntry *plt_entry;
8159 plt_entry = get_plt_entry (llvm_acfg, patch_info);
8160 plt_entry->llvm_used = FALSE;
8164 mono_aot_get_direct_call_symbol (MonoJumpInfoType type, gconstpointer data)
8166 const char *sym = NULL;
8168 if (llvm_acfg->aot_opts.direct_icalls) {
8169 if (type == MONO_PATCH_INFO_JIT_ICALL_ADDR) {
8170 /* Call to a C function implementing a jit icall */
8171 sym = mono_lookup_jit_icall_symbol ((const char *)data);
8172 } else if (type == MONO_PATCH_INFO_ICALL_ADDR_CALL) {
8173 MonoMethod *method = (MonoMethod *)data;
8174 if (!(method->flags & METHOD_ATTRIBUTE_PINVOKE_IMPL))
8175 sym = mono_lookup_icall_symbol (method);
8176 else if (llvm_acfg->aot_opts.direct_pinvoke)
8177 sym = get_pinvoke_import (llvm_acfg, method);
8180 return g_strdup (sym);
8186 mono_aot_get_plt_symbol (MonoJumpInfoType type, gconstpointer data)
8188 MonoJumpInfo *ji = (MonoJumpInfo *)mono_mempool_alloc (llvm_acfg->mempool, sizeof (MonoJumpInfo));
8189 MonoPltEntry *plt_entry;
8190 const char *sym = NULL;
8193 ji->data.target = data;
8195 if (!can_encode_patch (llvm_acfg, ji))
8198 if (llvm_acfg->aot_opts.direct_icalls) {
8199 if (type == MONO_PATCH_INFO_JIT_ICALL_ADDR) {
8200 /* Call to a C function implementing a jit icall */
8201 sym = mono_lookup_jit_icall_symbol ((const char *)data);
8202 } else if (type == MONO_PATCH_INFO_ICALL_ADDR_CALL) {
8203 MonoMethod *method = (MonoMethod *)data;
8204 if (!(method->flags & METHOD_ATTRIBUTE_PINVOKE_IMPL))
8205 sym = mono_lookup_icall_symbol (method);
8208 return g_strdup (sym);
8211 plt_entry = get_plt_entry (llvm_acfg, ji);
8212 plt_entry->llvm_used = TRUE;
8214 #if defined(TARGET_MACH)
8215 return g_strdup_printf (plt_entry->llvm_symbol + strlen (llvm_acfg->llvm_label_prefix));
8217 return g_strdup_printf (plt_entry->llvm_symbol);
8222 mono_aot_get_method_index (MonoMethod *method)
8224 g_assert (llvm_acfg);
8225 return get_method_index (llvm_acfg, method);
8229 mono_aot_patch_info_dup (MonoJumpInfo* ji)
8233 mono_acfg_lock (llvm_acfg);
8234 res = mono_patch_info_dup_mp (llvm_acfg->mempool, ji);
8235 mono_acfg_unlock (llvm_acfg);
8241 execute_system (const char * command)
8246 // We need an extra set of quotes around the whole command to properly handle commands
8247 // with spaces since internally the command is called through "cmd /c.
8248 command = g_strdup_printf ("\"%s\"", command);
8250 int size = MultiByteToWideChar (CP_UTF8, 0 , command , -1, NULL , 0);
8251 wchar_t* wstr = g_malloc (sizeof (wchar_t) * size);
8252 MultiByteToWideChar (CP_UTF8, 0, command, -1, wstr , size);
8253 status = _wsystem (wstr);
8257 #elif defined (HAVE_SYSTEM)
8258 status = system (command);
8260 g_assert_not_reached ();
8271 * Emit the LLVM code into an LLVM bytecode file, and compile it using the LLVM
8275 emit_llvm_file (MonoAotCompile *acfg)
8277 char *command, *opts, *tempbc, *optbc, *output_fname;
8279 if (acfg->aot_opts.llvm_only && acfg->aot_opts.asm_only) {
8280 tempbc = g_strdup_printf ("%s.bc", acfg->tmpbasename);
8281 optbc = g_strdup (acfg->aot_opts.llvm_outfile);
8283 tempbc = g_strdup_printf ("%s.bc", acfg->tmpbasename);
8284 optbc = g_strdup_printf ("%s.opt.bc", acfg->tmpbasename);
8287 mono_llvm_emit_aot_module (tempbc, g_path_get_basename (acfg->image->name));
8290 * FIXME: Experiment with adding optimizations, the -std-compile-opts set takes
8291 * a lot of time, and doesn't seem to save much space.
8292 * The following optimizations cannot be enabled:
8294 * - 'jump-threading' changes our blockaddress references to int constants.
8295 * - 'basiccg' fails because it contains:
8296 * if (CS && !isa<IntrinsicInst>(II)) {
8297 * and isa<IntrinsicInst> is false for invokes to intrinsics (iltests.exe).
8298 * - 'prune-eh' and 'functionattrs' depend on 'basiccg'.
8299 * The opt list below was produced by taking the output of:
8300 * llvm-as < /dev/null | opt -O2 -disable-output -debug-pass=Arguments
8301 * then removing tailcallelim + the global opts.
8302 * strip-dead-prototypes deletes unused intrinsics definitions.
8304 /* The dse pass is disabled because of #13734 and #17616 */
8306 * The dse bug is in DeadStoreElimination.cpp:isOverwrite ():
8307 * // If we have no DataLayout information around, then the size of the store
8308 * // is inferrable from the pointee type. If they are the same type, then
8309 * // we know that the store is safe.
8310 * if (AA.getDataLayout() == 0 &&
8311 * Later.Ptr->getType() == Earlier.Ptr->getType()) {
8312 * return OverwriteComplete;
8313 * Here, if 'Earlier' refers to a memset, and Later has no size info, it mistakenly thinks the memset is redundant.
8315 if (acfg->aot_opts.llvm_only)
8316 // FIXME: This doesn't work yet
8317 opts = g_strdup ("");
8319 #if LLVM_API_VERSION > 100
8320 opts = g_strdup ("-O2");
8322 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");
8324 command = g_strdup_printf ("\"%sopt\" -f %s -o \"%s\" \"%s\"", acfg->aot_opts.llvm_path, opts, optbc, tempbc);
8325 aot_printf (acfg, "Executing opt: %s\n", command);
8326 if (execute_system (command) != 0)
8330 if (acfg->aot_opts.llvm_only && acfg->aot_opts.asm_only)
8331 /* Nothing else to do */
8334 if (acfg->aot_opts.llvm_only) {
8335 /* Use the stock clang from xcode */
8337 command = g_strdup_printf ("clang -march=x86-64 -fpic -msse -msse2 -msse3 -msse4 -O2 -fno-optimize-sibling-calls -Wno-override-module -c -o \"%s\" \"%s.opt.bc\"", acfg->llvm_ofile, acfg->tmpbasename);
8339 aot_printf (acfg, "Executing clang: %s\n", command);
8340 if (execute_system (command) != 0)
8345 if (!acfg->llc_args)
8346 acfg->llc_args = g_string_new ("");
8348 /* Verbose asm slows down llc greatly */
8349 g_string_append (acfg->llc_args, " -asm-verbose=false");
8351 if (acfg->aot_opts.mtriple)
8352 g_string_append_printf (acfg->llc_args, " -mtriple=%s", acfg->aot_opts.mtriple);
8354 g_string_append (acfg->llc_args, " -disable-gnu-eh-frame -enable-mono-eh-frame");
8356 g_string_append_printf (acfg->llc_args, " -mono-eh-frame-symbol=%s%s", acfg->user_symbol_prefix, acfg->llvm_eh_frame_symbol);
8358 #if LLVM_API_VERSION > 100
8359 g_string_append_printf (acfg->llc_args, " -disable-tail-calls");
8362 #if defined(TARGET_MACH) && defined(TARGET_ARM)
8363 /* ios requires PIC code now */
8364 g_string_append_printf (acfg->llc_args, " -relocation-model=pic");
8366 if (llvm_acfg->aot_opts.static_link)
8367 g_string_append_printf (acfg->llc_args, " -relocation-model=static");
8369 g_string_append_printf (acfg->llc_args, " -relocation-model=pic");
8372 if (acfg->llvm_owriter) {
8373 /* Emit an object file directly */
8374 output_fname = g_strdup_printf ("%s", acfg->llvm_ofile);
8375 g_string_append_printf (acfg->llc_args, " -filetype=obj");
8377 output_fname = g_strdup_printf ("%s", acfg->llvm_sfile);
8379 command = g_strdup_printf ("\"%sllc\" %s -o \"%s\" \"%s.opt.bc\"", acfg->aot_opts.llvm_path, acfg->llc_args->str, output_fname, acfg->tmpbasename);
8380 g_free (output_fname);
8382 aot_printf (acfg, "Executing llc: %s\n", command);
8384 if (execute_system (command) != 0)
8391 emit_code (MonoAotCompile *acfg)
8393 int oindex, i, prev_index;
8394 gboolean saved_unbox_info = FALSE;
8397 if (acfg->aot_opts.llvm_only)
8400 #if defined(TARGET_POWERPC64)
8401 sprintf (symbol, ".Lgot_addr");
8402 emit_section_change (acfg, ".text", 0);
8403 emit_alignment (acfg, 8);
8404 emit_label (acfg, symbol);
8405 emit_pointer (acfg, acfg->got_symbol);
8409 * This global symbol is used to compute the address of each method using the
8410 * code_offsets array. It is also used to compute the memory ranges occupied by
8411 * AOT code, so it must be equal to the address of the first emitted method.
8413 emit_section_change (acfg, ".text", 0);
8414 emit_alignment_code (acfg, 8);
8415 emit_info_symbol (acfg, "jit_code_start");
8418 * Emit some padding so the local symbol for the first method doesn't have the
8419 * same address as 'methods'.
8421 #if defined(__default_codegen__)
8422 emit_padding (acfg, 16);
8423 #elif defined(__native_client_codegen__)
8425 const int kPaddingSize = 16;
8426 guint8 pad_buffer[kPaddingSize];
8427 mono_arch_nacl_pad (pad_buffer, kPaddingSize);
8428 emit_bytes (acfg, pad_buffer, kPaddingSize);
8432 for (oindex = 0; oindex < acfg->method_order->len; ++oindex) {
8436 i = GPOINTER_TO_UINT (g_ptr_array_index (acfg->method_order, oindex));
8438 cfg = acfg->cfgs [i];
8443 method = cfg->orig_method;
8445 /* Emit unbox trampoline */
8446 if (mono_aot_mode_is_full (&acfg->aot_opts) && cfg->orig_method->klass->valuetype && !(acfg->aot_opts.llvm_only && cfg->compile_llvm)) {
8447 sprintf (symbol, "ut_%d", get_method_index (acfg, method));
8449 emit_section_change (acfg, ".text", 0);
8450 #ifdef __native_client_codegen__
8451 emit_alignment (acfg, AOT_FUNC_ALIGNMENT);
8454 if (acfg->thumb_mixed && cfg->compile_llvm) {
8455 emit_set_thumb_mode (acfg);
8456 fprintf (acfg->fp, "\n.thumb_func\n");
8459 emit_label (acfg, symbol);
8461 arch_emit_unbox_trampoline (acfg, cfg, cfg->orig_method, cfg->asm_symbol);
8463 if (acfg->thumb_mixed && cfg->compile_llvm)
8464 emit_set_arm_mode (acfg);
8466 if (!saved_unbox_info) {
8467 char user_symbol [128];
8469 sprintf (user_symbol, "%sunbox_trampoline_p", acfg->user_symbol_prefix);
8471 emit_label (acfg, "ut_end");
8473 unwind_ops = mono_unwind_get_cie_program ();
8474 save_unwind_info (acfg, user_symbol, unwind_ops);
8475 mono_free_unwind_info (unwind_ops);
8477 /* Save the unbox trampoline size */
8478 emit_symbol_diff (acfg, "ut_end", symbol, 0);
8480 saved_unbox_info = TRUE;
8484 if (cfg->compile_llvm)
8485 acfg->stats.llvm_count ++;
8487 emit_method_code (acfg, cfg);
8490 emit_section_change (acfg, ".text", 0);
8491 emit_alignment_code (acfg, 8);
8492 emit_info_symbol (acfg, "jit_code_end");
8494 /* To distinguish it from the next symbol */
8495 emit_padding (acfg, 4);
8498 * Add .no_dead_strip directives for all LLVM methods to prevent the OSX linker
8499 * from optimizing them away, since it doesn't see that code_offsets references them.
8500 * JITted methods don't need this since they are referenced using assembler local
8502 * FIXME: This is why write-symbols doesn't work on OSX ?
8504 if (acfg->llvm && acfg->need_no_dead_strip) {
8505 fprintf (acfg->fp, "\n");
8506 for (i = 0; i < acfg->nmethods; ++i) {
8507 if (acfg->cfgs [i] && acfg->cfgs [i]->compile_llvm)
8508 fprintf (acfg->fp, ".no_dead_strip %s\n", acfg->cfgs [i]->asm_symbol);
8513 * To work around linker issues, we emit a table of branches, and disassemble them at runtime.
8514 * This is PIE code, and the linker can update it if needed.
8516 sprintf (symbol, "method_addresses");
8517 emit_section_change (acfg, ".text", 1);
8518 emit_alignment_code (acfg, 8);
8519 emit_info_symbol (acfg, symbol);
8520 emit_local_symbol (acfg, symbol, "method_addresses_end", TRUE);
8521 emit_unset_mode (acfg);
8522 if (acfg->need_no_dead_strip)
8523 fprintf (acfg->fp, " .no_dead_strip %s\n", symbol);
8525 for (i = 0; i < acfg->nmethods; ++i) {
8526 #ifdef MONO_ARCH_AOT_SUPPORTED
8529 if (acfg->cfgs [i]) {
8530 if (acfg->aot_opts.llvm_only && acfg->cfgs [i]->compile_llvm)
8531 /* Obtained by calling a generated function in the LLVM image */
8532 arch_emit_direct_call (acfg, "method_addresses", FALSE, FALSE, NULL, &call_size);
8534 arch_emit_direct_call (acfg, acfg->cfgs [i]->asm_symbol, FALSE, acfg->thumb_mixed && acfg->cfgs [i]->compile_llvm, NULL, &call_size);
8536 arch_emit_direct_call (acfg, "method_addresses", FALSE, FALSE, NULL, &call_size);
8541 sprintf (symbol, "method_addresses_end");
8542 emit_label (acfg, symbol);
8545 /* Emit a sorted table mapping methods to the index of their unbox trampolines */
8546 sprintf (symbol, "unbox_trampolines");
8547 emit_section_change (acfg, RODATA_SECT, 0);
8548 emit_alignment (acfg, 8);
8549 emit_info_symbol (acfg, symbol);
8552 for (i = 0; i < acfg->nmethods; ++i) {
8557 cfg = acfg->cfgs [i];
8561 method = cfg->orig_method;
8563 if (mono_aot_mode_is_full (&acfg->aot_opts) && cfg->orig_method->klass->valuetype && !(acfg->aot_opts.llvm_only && cfg->compile_llvm)) {
8564 index = get_method_index (acfg, method);
8566 emit_int32 (acfg, index);
8567 /* Make sure the table is sorted by index */
8568 g_assert (index > prev_index);
8572 sprintf (symbol, "unbox_trampolines_end");
8573 emit_info_symbol (acfg, symbol);
8574 emit_int32 (acfg, 0);
8576 /* Emit a separate table with the trampoline addresses/offsets */
8577 sprintf (symbol, "unbox_trampoline_addresses");
8578 emit_section_change (acfg, ".text", 0);
8579 emit_alignment_code (acfg, 8);
8580 emit_info_symbol (acfg, symbol);
8582 for (i = 0; i < acfg->nmethods; ++i) {
8587 cfg = acfg->cfgs [i];
8591 method = cfg->orig_method;
8593 if (mono_aot_mode_is_full (&acfg->aot_opts) && cfg->orig_method->klass->valuetype && !(acfg->aot_opts.llvm_only && cfg->compile_llvm)) {
8594 #ifdef MONO_ARCH_AOT_SUPPORTED
8597 index = get_method_index (acfg, method);
8598 sprintf (symbol, "ut_%d", index);
8600 arch_emit_direct_call (acfg, symbol, FALSE, acfg->thumb_mixed && cfg->compile_llvm, NULL, &call_size);
8604 emit_int32 (acfg, 0);
8608 emit_info (MonoAotCompile *acfg)
8613 offsets = g_new0 (gint32, acfg->nmethods);
8615 for (oindex = 0; oindex < acfg->method_order->len; ++oindex) {
8616 i = GPOINTER_TO_UINT (g_ptr_array_index (acfg->method_order, oindex));
8618 if (acfg->cfgs [i]) {
8619 emit_method_info (acfg, acfg->cfgs [i]);
8620 offsets [i] = acfg->cfgs [i]->method_info_offset;
8626 acfg->stats.offsets_size += emit_offset_table (acfg, "method_info_offsets", MONO_AOT_TABLE_METHOD_INFO_OFFSETS, acfg->nmethods, 10, offsets);
8631 #endif /* #if !defined(DISABLE_AOT) && !defined(DISABLE_JIT) */
8633 #define rot(x,k) (((x)<<(k)) | ((x)>>(32-(k))))
8634 #define mix(a,b,c) { \
8635 a -= c; a ^= rot(c, 4); c += b; \
8636 b -= a; b ^= rot(a, 6); a += c; \
8637 c -= b; c ^= rot(b, 8); b += a; \
8638 a -= c; a ^= rot(c,16); c += b; \
8639 b -= a; b ^= rot(a,19); a += c; \
8640 c -= b; c ^= rot(b, 4); b += a; \
8642 #define final(a,b,c) { \
8643 c ^= b; c -= rot(b,14); \
8644 a ^= c; a -= rot(c,11); \
8645 b ^= a; b -= rot(a,25); \
8646 c ^= b; c -= rot(b,16); \
8647 a ^= c; a -= rot(c,4); \
8648 b ^= a; b -= rot(a,14); \
8649 c ^= b; c -= rot(b,24); \
8653 mono_aot_type_hash (MonoType *t1)
8655 guint hash = t1->type;
8657 hash |= t1->byref << 6; /* do not collide with t1->type values */
8659 case MONO_TYPE_VALUETYPE:
8660 case MONO_TYPE_CLASS:
8661 case MONO_TYPE_SZARRAY:
8662 /* check if the distribution is good enough */
8663 return ((hash << 5) - hash) ^ mono_metadata_str_hash (t1->data.klass->name);
8665 return ((hash << 5) - hash) ^ mono_metadata_type_hash (t1->data.type);
8666 case MONO_TYPE_ARRAY:
8667 return ((hash << 5) - hash) ^ mono_metadata_type_hash (&t1->data.array->eklass->byval_arg);
8668 case MONO_TYPE_GENERICINST:
8669 return ((hash << 5) - hash) ^ 0;
8676 * mono_aot_method_hash:
8678 * Return a hash code for methods which only depends on metadata.
8681 mono_aot_method_hash (MonoMethod *method)
8683 MonoMethodSignature *sig;
8687 guint32 *hashes_start, *hashes;
8689 MonoGenericInst *class_ginst = NULL;
8690 MonoGenericInst *ginst = NULL;
8692 /* Similar to the hash in mono_method_get_imt_slot () */
8694 sig = mono_method_signature (method);
8696 if (method->klass->generic_class)
8697 class_ginst = method->klass->generic_class->context.class_inst;
8698 if (method->is_inflated)
8699 ginst = ((MonoMethodInflated*)method)->context.method_inst;
8701 hashes_count = sig->param_count + 5 + (class_ginst ? class_ginst->type_argc : 0) + (ginst ? ginst->type_argc : 0);
8702 hashes_start = (guint32 *)g_malloc0 (hashes_count * sizeof (guint32));
8703 hashes = hashes_start;
8705 /* Some wrappers are assigned to random classes */
8706 if (!method->wrapper_type || method->wrapper_type == MONO_WRAPPER_REMOTING_INVOKE_WITH_CHECK)
8707 klass = method->klass;
8709 klass = mono_defaults.object_class;
8711 if (!method->wrapper_type) {
8714 if (klass->generic_class)
8715 full_name = mono_type_full_name (&klass->generic_class->container_class->byval_arg);
8717 full_name = mono_type_full_name (&klass->byval_arg);
8719 hashes [0] = mono_metadata_str_hash (full_name);
8723 hashes [0] = mono_metadata_str_hash (klass->name);
8724 hashes [1] = mono_metadata_str_hash (klass->name_space);
8726 if (method->wrapper_type == MONO_WRAPPER_STFLD || method->wrapper_type == MONO_WRAPPER_LDFLD || method->wrapper_type == MONO_WRAPPER_LDFLDA)
8727 /* The method name includes a stringified pointer */
8730 hashes [2] = mono_metadata_str_hash (method->name);
8731 hashes [3] = method->wrapper_type;
8732 hashes [4] = mono_aot_type_hash (sig->ret);
8734 for (i = 0; i < sig->param_count; i++) {
8735 hashes [hindex ++] = mono_aot_type_hash (sig->params [i]);
8738 for (i = 0; i < class_ginst->type_argc; ++i)
8739 hashes [hindex ++] = mono_aot_type_hash (class_ginst->type_argv [i]);
8742 for (i = 0; i < ginst->type_argc; ++i)
8743 hashes [hindex ++] = mono_aot_type_hash (ginst->type_argv [i]);
8745 g_assert (hindex == hashes_count);
8747 /* Setup internal state */
8748 a = b = c = 0xdeadbeef + (((guint32)hashes_count)<<2);
8750 /* Handle most of the hashes */
8751 while (hashes_count > 3) {
8760 /* Handle the last 3 hashes (all the case statements fall through) */
8761 switch (hashes_count) {
8762 case 3 : c += hashes [2];
8763 case 2 : b += hashes [1];
8764 case 1 : a += hashes [0];
8766 case 0: /* nothing left to add */
8770 free (hashes_start);
8779 * mono_aot_get_array_helper_from_wrapper;
8781 * Get the helper method in Array called by an array wrapper method.
8784 mono_aot_get_array_helper_from_wrapper (MonoMethod *method)
8788 MonoGenericContext ctx;
8789 MonoType *args [16];
8790 char *mname, *iname, *s, *s2, *helper_name = NULL;
8792 prefix = "System.Collections.Generic";
8793 s = g_strdup_printf ("%s", method->name + strlen (prefix) + 1);
8794 s2 = strstr (s, "`1.");
8800 //printf ("X: %s %s\n", iname, mname);
8802 if (!strcmp (iname, "IList"))
8803 helper_name = g_strdup_printf ("InternalArray__%s", mname);
8805 helper_name = g_strdup_printf ("InternalArray__%s_%s", iname, mname);
8806 m = mono_class_get_method_from_name (mono_defaults.array_class, helper_name, mono_method_signature (method)->param_count);
8808 g_free (helper_name);
8811 if (m->is_generic) {
8813 memset (&ctx, 0, sizeof (ctx));
8814 args [0] = &method->klass->element_class->byval_arg;
8815 ctx.method_inst = mono_metadata_get_generic_inst (1, args);
8816 m = mono_class_inflate_generic_method_checked (m, &ctx, &error);
8817 g_assert (mono_error_ok (&error)); /* FIXME don't swallow the error */
8823 #if !defined(DISABLE_AOT) && !defined(DISABLE_JIT)
8825 typedef struct HashEntry {
8826 guint32 key, value, index;
8827 struct HashEntry *next;
8831 * emit_extra_methods:
8833 * Emit methods which are not in the METHOD table, like wrappers.
8836 emit_extra_methods (MonoAotCompile *acfg)
8838 int i, table_size, buf_size;
8840 guint32 *info_offsets;
8843 HashEntry *entry, *new_entry;
8844 int nmethods, max_chain_length;
8847 info_offsets = g_new0 (guint32, acfg->extra_methods->len);
8849 /* Emit method info */
8851 for (i = 0; i < acfg->extra_methods->len; ++i) {
8852 MonoMethod *method = (MonoMethod *)g_ptr_array_index (acfg->extra_methods, i);
8853 MonoCompile *cfg = (MonoCompile *)g_hash_table_lookup (acfg->method_to_cfg, method);
8859 p = buf = (guint8 *)g_malloc (buf_size);
8863 method = cfg->method_to_register;
8865 encode_method_ref (acfg, method, p, &p);
8867 g_assert ((p - buf) < buf_size);
8869 info_offsets [i] = add_to_blob (acfg, buf, p - buf);
8874 * Construct a chained hash table for mapping indexes in extra_method_info to
8877 table_size = g_spaced_primes_closest ((int)(nmethods * 1.5));
8878 table = g_ptr_array_sized_new (table_size);
8879 for (i = 0; i < table_size; ++i)
8880 g_ptr_array_add (table, NULL);
8881 chain_lengths = g_new0 (int, table_size);
8882 max_chain_length = 0;
8883 for (i = 0; i < acfg->extra_methods->len; ++i) {
8884 MonoMethod *method = (MonoMethod *)g_ptr_array_index (acfg->extra_methods, i);
8885 MonoCompile *cfg = (MonoCompile *)g_hash_table_lookup (acfg->method_to_cfg, method);
8891 key = info_offsets [i];
8892 value = get_method_index (acfg, method);
8894 hash = mono_aot_method_hash (method) % table_size;
8895 //printf ("X: %s %x\n", mono_method_get_full_name (method), mono_aot_method_hash (method));
8897 chain_lengths [hash] ++;
8898 max_chain_length = MAX (max_chain_length, chain_lengths [hash]);
8900 new_entry = (HashEntry *)mono_mempool_alloc0 (acfg->mempool, sizeof (HashEntry));
8901 new_entry->key = key;
8902 new_entry->value = value;
8904 entry = (HashEntry *)g_ptr_array_index (table, hash);
8905 if (entry == NULL) {
8906 new_entry->index = hash;
8907 g_ptr_array_index (table, hash) = new_entry;
8910 entry = entry->next;
8912 entry->next = new_entry;
8913 new_entry->index = table->len;
8914 g_ptr_array_add (table, new_entry);
8918 //printf ("MAX: %d\n", max_chain_length);
8920 buf_size = table->len * 12 + 4;
8921 p = buf = (guint8 *)g_malloc (buf_size);
8922 encode_int (table_size, p, &p);
8924 for (i = 0; i < table->len; ++i) {
8925 HashEntry *entry = (HashEntry *)g_ptr_array_index (table, i);
8927 if (entry == NULL) {
8928 encode_int (0, p, &p);
8929 encode_int (0, p, &p);
8930 encode_int (0, p, &p);
8932 //g_assert (entry->key > 0);
8933 encode_int (entry->key, p, &p);
8934 encode_int (entry->value, p, &p);
8936 encode_int (entry->next->index, p, &p);
8938 encode_int (0, p, &p);
8941 g_assert (p - buf <= buf_size);
8943 /* Emit the table */
8944 emit_aot_data (acfg, MONO_AOT_TABLE_EXTRA_METHOD_TABLE, "extra_method_table", buf, p - buf);
8947 * Emit a table reverse mapping method indexes to their index in extra_method_info.
8948 * This is used by mono_aot_find_jit_info ().
8950 buf_size = acfg->extra_methods->len * 8 + 4;
8951 p = buf = (guint8 *)g_malloc (buf_size);
8952 encode_int (acfg->extra_methods->len, p, &p);
8953 for (i = 0; i < acfg->extra_methods->len; ++i) {
8954 MonoMethod *method = (MonoMethod *)g_ptr_array_index (acfg->extra_methods, i);
8956 encode_int (get_method_index (acfg, method), p, &p);
8957 encode_int (info_offsets [i], p, &p);
8959 emit_aot_data (acfg, MONO_AOT_TABLE_EXTRA_METHOD_INFO_OFFSETS, "extra_method_info_offsets", buf, p - buf);
8963 emit_exception_info (MonoAotCompile *acfg)
8967 SeqPointData sp_data;
8968 gboolean seq_points_to_file = FALSE;
8970 offsets = g_new0 (gint32, acfg->nmethods);
8971 for (i = 0; i < acfg->nmethods; ++i) {
8972 if (acfg->cfgs [i]) {
8973 MonoCompile *cfg = acfg->cfgs [i];
8975 // By design aot-runtime decode_exception_debug_info is not able to load sequence point debug data from a file.
8976 // As it is not possible to load debug data from a file its is also not possible to store it in a file.
8977 gboolean method_seq_points_to_file = acfg->aot_opts.gen_seq_points_file &&
8978 cfg->gen_seq_points && !cfg->gen_sdb_seq_points;
8979 gboolean method_seq_points_to_binary = cfg->gen_seq_points && !method_seq_points_to_file;
8981 emit_exception_debug_info (acfg, cfg, method_seq_points_to_binary);
8982 offsets [i] = cfg->ex_info_offset;
8984 if (method_seq_points_to_file) {
8985 if (!seq_points_to_file) {
8986 mono_seq_point_data_init (&sp_data, acfg->nmethods);
8987 seq_points_to_file = TRUE;
8989 mono_seq_point_data_add (&sp_data, cfg->method->token, cfg->method_index, cfg->seq_point_info);
8996 if (seq_points_to_file) {
8997 char *seq_points_aot_file = acfg->aot_opts.gen_seq_points_file_path ? acfg->aot_opts.gen_seq_points_file_path
8998 : g_strdup_printf("%s%s", acfg->image->name, SEQ_POINT_AOT_EXT);
8999 mono_seq_point_data_write (&sp_data, seq_points_aot_file);
9000 mono_seq_point_data_free (&sp_data);
9001 g_free (seq_points_aot_file);
9004 acfg->stats.offsets_size += emit_offset_table (acfg, "ex_info_offsets", MONO_AOT_TABLE_EX_INFO_OFFSETS, acfg->nmethods, 10, offsets);
9009 emit_unwind_info (MonoAotCompile *acfg)
9014 if (acfg->aot_opts.llvm_only) {
9015 g_assert (acfg->unwind_ops->len == 0);
9020 * The unwind info contains a lot of duplicates so we emit each unique
9021 * entry once, and only store the offset from the start of the table in the
9025 sprintf (symbol, "unwind_info");
9026 emit_section_change (acfg, RODATA_SECT, 1);
9027 emit_alignment (acfg, 8);
9028 emit_info_symbol (acfg, symbol);
9030 for (i = 0; i < acfg->unwind_ops->len; ++i) {
9031 guint32 index = GPOINTER_TO_UINT (g_ptr_array_index (acfg->unwind_ops, i));
9032 guint8 *unwind_info;
9033 guint32 unwind_info_len;
9037 unwind_info = mono_get_cached_unwind_info (index, &unwind_info_len);
9040 encode_value (unwind_info_len, p, &p);
9041 emit_bytes (acfg, buf, p - buf);
9042 emit_bytes (acfg, unwind_info, unwind_info_len);
9044 acfg->stats.unwind_info_size += (p - buf) + unwind_info_len;
9049 emit_class_info (MonoAotCompile *acfg)
9054 offsets = g_new0 (gint32, acfg->image->tables [MONO_TABLE_TYPEDEF].rows);
9055 for (i = 0; i < acfg->image->tables [MONO_TABLE_TYPEDEF].rows; ++i)
9056 offsets [i] = emit_klass_info (acfg, MONO_TOKEN_TYPE_DEF | (i + 1));
9058 acfg->stats.offsets_size += emit_offset_table (acfg, "class_info_offsets", MONO_AOT_TABLE_CLASS_INFO_OFFSETS, acfg->image->tables [MONO_TABLE_TYPEDEF].rows, 10, offsets);
9062 typedef struct ClassNameTableEntry {
9063 guint32 token, index;
9064 struct ClassNameTableEntry *next;
9065 } ClassNameTableEntry;
9068 emit_class_name_table (MonoAotCompile *acfg)
9070 int i, table_size, buf_size;
9071 guint32 token, hash;
9076 ClassNameTableEntry *entry, *new_entry;
9079 * Construct a chained hash table for mapping class names to typedef tokens.
9081 table_size = g_spaced_primes_closest ((int)(acfg->image->tables [MONO_TABLE_TYPEDEF].rows * 1.5));
9082 table = g_ptr_array_sized_new (table_size);
9083 for (i = 0; i < table_size; ++i)
9084 g_ptr_array_add (table, NULL);
9085 for (i = 0; i < acfg->image->tables [MONO_TABLE_TYPEDEF].rows; ++i) {
9087 token = MONO_TOKEN_TYPE_DEF | (i + 1);
9088 klass = mono_class_get_checked (acfg->image, token, &error);
9090 mono_error_cleanup (&error);
9093 full_name = mono_type_get_name_full (mono_class_get_type (klass), MONO_TYPE_NAME_FORMAT_FULL_NAME);
9094 hash = mono_metadata_str_hash (full_name) % table_size;
9097 /* FIXME: Allocate from the mempool */
9098 new_entry = g_new0 (ClassNameTableEntry, 1);
9099 new_entry->token = token;
9101 entry = (ClassNameTableEntry *)g_ptr_array_index (table, hash);
9102 if (entry == NULL) {
9103 new_entry->index = hash;
9104 g_ptr_array_index (table, hash) = new_entry;
9107 entry = entry->next;
9109 entry->next = new_entry;
9110 new_entry->index = table->len;
9111 g_ptr_array_add (table, new_entry);
9115 /* Emit the table */
9116 buf_size = table->len * 4 + 4;
9117 p = buf = (guint8 *)g_malloc0 (buf_size);
9119 /* FIXME: Optimize memory usage */
9120 g_assert (table_size < 65000);
9121 encode_int16 (table_size, p, &p);
9122 g_assert (table->len < 65000);
9123 for (i = 0; i < table->len; ++i) {
9124 ClassNameTableEntry *entry = (ClassNameTableEntry *)g_ptr_array_index (table, i);
9126 if (entry == NULL) {
9127 encode_int16 (0, p, &p);
9128 encode_int16 (0, p, &p);
9130 encode_int16 (mono_metadata_token_index (entry->token), p, &p);
9132 encode_int16 (entry->next->index, p, &p);
9134 encode_int16 (0, p, &p);
9137 g_assert (p - buf <= buf_size);
9139 emit_aot_data (acfg, MONO_AOT_TABLE_CLASS_NAME, "class_name_table", buf, p - buf);
9143 emit_image_table (MonoAotCompile *acfg)
9149 * The image table is small but referenced in a lot of places.
9150 * So we emit it at once, and reference its elements by an index.
9152 buf_size = acfg->image_table->len * 28 + 4;
9153 for (i = 0; i < acfg->image_table->len; i++) {
9154 MonoImage *image = (MonoImage*)g_ptr_array_index (acfg->image_table, i);
9155 MonoAssemblyName *aname = &image->assembly->aname;
9157 buf_size += strlen (image->assembly_name) + strlen (image->guid) + (aname->culture ? strlen (aname->culture) : 1) + strlen ((char*)aname->public_key_token) + 4;
9160 buf = p = (guint8 *)g_malloc0 (buf_size);
9161 encode_int (acfg->image_table->len, p, &p);
9162 for (i = 0; i < acfg->image_table->len; i++) {
9163 MonoImage *image = (MonoImage*)g_ptr_array_index (acfg->image_table, i);
9164 MonoAssemblyName *aname = &image->assembly->aname;
9166 /* FIXME: Support multi-module assemblies */
9167 g_assert (image->assembly->image == image);
9169 encode_string (image->assembly_name, p, &p);
9170 encode_string (image->guid, p, &p);
9171 encode_string (aname->culture ? aname->culture : "", p, &p);
9172 encode_string ((const char*)aname->public_key_token, p, &p);
9174 while (GPOINTER_TO_UINT (p) % 8 != 0)
9177 encode_int (aname->flags, p, &p);
9178 encode_int (aname->major, p, &p);
9179 encode_int (aname->minor, p, &p);
9180 encode_int (aname->build, p, &p);
9181 encode_int (aname->revision, p, &p);
9183 g_assert (p - buf <= buf_size);
9185 emit_aot_data (acfg, MONO_AOT_TABLE_IMAGE_TABLE, "image_table", buf, p - buf);
9191 emit_got_info (MonoAotCompile *acfg, gboolean llvm)
9193 int i, first_plt_got_patch = 0, buf_size;
9195 guint32 *got_info_offsets;
9196 GotInfo *info = llvm ? &acfg->llvm_got_info : &acfg->got_info;
9198 /* Add the patches needed by the PLT to the GOT */
9200 acfg->plt_got_offset_base = acfg->got_offset;
9201 first_plt_got_patch = info->got_patches->len;
9202 for (i = 1; i < acfg->plt_offset; ++i) {
9203 MonoPltEntry *plt_entry = (MonoPltEntry *)g_hash_table_lookup (acfg->plt_offset_to_entry, GUINT_TO_POINTER (i));
9205 g_ptr_array_add (info->got_patches, plt_entry->ji);
9207 acfg->stats.got_slot_types [plt_entry->ji->type] ++;
9210 acfg->got_offset += acfg->plt_offset;
9215 * - optimize offsets table.
9216 * - reduce number of exported symbols.
9217 * - emit info for a klass only once.
9218 * - determine when a method uses a GOT slot which is guaranteed to be already
9220 * - clean up and document the code.
9221 * - use String.Empty in class libs.
9224 /* Encode info required to decode shared GOT entries */
9225 buf_size = info->got_patches->len * 128;
9226 p = buf = (guint8 *)mono_mempool_alloc (acfg->mempool, buf_size);
9227 got_info_offsets = (guint32 *)mono_mempool_alloc (acfg->mempool, info->got_patches->len * sizeof (guint32));
9229 acfg->plt_got_info_offsets = (guint32 *)mono_mempool_alloc (acfg->mempool, acfg->plt_offset * sizeof (guint32));
9231 if (acfg->plt_offset)
9232 acfg->plt_got_info_offsets [0] = 0;
9234 for (i = 0; i < info->got_patches->len; ++i) {
9235 MonoJumpInfo *ji = (MonoJumpInfo *)g_ptr_array_index (info->got_patches, i);
9240 encode_value (ji->type, p, &p);
9242 encode_patch (acfg, ji, p, &p);
9243 acfg->stats.got_slot_info_sizes [ji->type] += p - p2;
9244 g_assert (p - buf <= buf_size);
9245 got_info_offsets [i] = add_to_blob (acfg, buf, p - buf);
9247 if (!llvm && i >= first_plt_got_patch)
9248 acfg->plt_got_info_offsets [i - first_plt_got_patch + 1] = got_info_offsets [i];
9249 acfg->stats.got_info_size += p - buf;
9252 /* Emit got_info_offsets table */
9254 /* No need to emit offsets for the got plt entries, the plt embeds them directly */
9255 acfg->stats.offsets_size += emit_offset_table (acfg, llvm ? "llvm_got_info_offsets" : "got_info_offsets", llvm ? MONO_AOT_TABLE_LLVM_GOT_INFO_OFFSETS : MONO_AOT_TABLE_GOT_INFO_OFFSETS, llvm ? acfg->llvm_got_offset : first_plt_got_patch, 10, (gint32*)got_info_offsets);
9259 emit_got (MonoAotCompile *acfg)
9263 if (acfg->aot_opts.llvm_only)
9266 /* Don't make GOT global so accesses to it don't need relocations */
9267 sprintf (symbol, "%s", acfg->got_symbol);
9270 emit_unset_mode (acfg);
9271 fprintf (acfg->fp, ".section __DATA, __bss\n");
9272 emit_alignment (acfg, 8);
9274 emit_info_symbol (acfg, "jit_got");
9275 fprintf (acfg->fp, ".lcomm %s, %d\n", acfg->got_symbol, (int)(acfg->got_offset * sizeof (gpointer)));
9277 emit_section_change (acfg, ".bss", 0);
9278 emit_alignment (acfg, 8);
9279 emit_local_symbol (acfg, symbol, "got_end", FALSE);
9280 emit_label (acfg, symbol);
9282 emit_info_symbol (acfg, "jit_got");
9283 if (acfg->got_offset > 0)
9284 emit_zero_bytes (acfg, (int)(acfg->got_offset * sizeof (gpointer)));
9287 sprintf (symbol, "got_end");
9288 emit_label (acfg, symbol);
9291 typedef struct GlobalsTableEntry {
9292 guint32 value, index;
9293 struct GlobalsTableEntry *next;
9294 } GlobalsTableEntry;
9297 emit_globals (MonoAotCompile *acfg)
9303 GlobalsTableEntry *entry, *new_entry;
9305 if (!acfg->aot_opts.static_link)
9307 if (acfg->aot_opts.llvm_only) {
9308 g_assert (acfg->globals->len == 0);
9313 * When static linking, we emit a table containing our globals.
9317 * Construct a chained hash table for mapping global names to their index in
9318 * the globals table.
9320 table_size = g_spaced_primes_closest ((int)(acfg->globals->len * 1.5));
9321 table = g_ptr_array_sized_new (table_size);
9322 for (i = 0; i < table_size; ++i)
9323 g_ptr_array_add (table, NULL);
9324 for (i = 0; i < acfg->globals->len; ++i) {
9325 char *name = (char *)g_ptr_array_index (acfg->globals, i);
9327 hash = mono_metadata_str_hash (name) % table_size;
9329 /* FIXME: Allocate from the mempool */
9330 new_entry = g_new0 (GlobalsTableEntry, 1);
9331 new_entry->value = i;
9333 entry = (GlobalsTableEntry *)g_ptr_array_index (table, hash);
9334 if (entry == NULL) {
9335 new_entry->index = hash;
9336 g_ptr_array_index (table, hash) = new_entry;
9339 entry = entry->next;
9341 entry->next = new_entry;
9342 new_entry->index = table->len;
9343 g_ptr_array_add (table, new_entry);
9347 /* Emit the table */
9348 sprintf (symbol, ".Lglobals_hash");
9349 emit_section_change (acfg, RODATA_SECT, 0);
9350 emit_alignment (acfg, 8);
9351 emit_label (acfg, symbol);
9353 /* FIXME: Optimize memory usage */
9354 g_assert (table_size < 65000);
9355 emit_int16 (acfg, table_size);
9356 for (i = 0; i < table->len; ++i) {
9357 GlobalsTableEntry *entry = (GlobalsTableEntry *)g_ptr_array_index (table, i);
9359 if (entry == NULL) {
9360 emit_int16 (acfg, 0);
9361 emit_int16 (acfg, 0);
9363 emit_int16 (acfg, entry->value + 1);
9365 emit_int16 (acfg, entry->next->index);
9367 emit_int16 (acfg, 0);
9371 /* Emit the names */
9372 for (i = 0; i < acfg->globals->len; ++i) {
9373 char *name = (char *)g_ptr_array_index (acfg->globals, i);
9375 sprintf (symbol, "name_%d", i);
9376 emit_section_change (acfg, RODATA_SECT, 1);
9378 emit_alignment (acfg, 4);
9380 emit_label (acfg, symbol);
9381 emit_string (acfg, name);
9384 /* Emit the globals table */
9385 sprintf (symbol, "globals");
9386 emit_section_change (acfg, ".data", 0);
9387 /* This is not a global, since it is accessed by the init function */
9388 emit_alignment (acfg, 8);
9389 emit_info_symbol (acfg, symbol);
9391 sprintf (symbol, "%sglobals_hash", acfg->temp_prefix);
9392 emit_pointer (acfg, symbol);
9394 for (i = 0; i < acfg->globals->len; ++i) {
9395 char *name = (char *)g_ptr_array_index (acfg->globals, i);
9397 sprintf (symbol, "name_%d", i);
9398 emit_pointer (acfg, symbol);
9400 g_assert (strlen (name) < sizeof (symbol));
9401 sprintf (symbol, "%s", name);
9402 emit_pointer (acfg, symbol);
9404 /* Null terminate the table */
9405 emit_int32 (acfg, 0);
9406 emit_int32 (acfg, 0);
9410 emit_mem_end (MonoAotCompile *acfg)
9414 if (acfg->aot_opts.llvm_only)
9417 sprintf (symbol, "mem_end");
9418 emit_section_change (acfg, ".text", 1);
9419 emit_alignment_code (acfg, 8);
9420 emit_label (acfg, symbol);
9424 init_aot_file_info (MonoAotCompile *acfg, MonoAotFileInfo *info)
9428 info->version = MONO_AOT_FILE_VERSION;
9429 info->plt_got_offset_base = acfg->plt_got_offset_base;
9430 info->got_size = acfg->got_offset * sizeof (gpointer);
9431 info->plt_size = acfg->plt_offset;
9432 info->nmethods = acfg->nmethods;
9433 info->flags = acfg->flags;
9434 info->opts = acfg->opts;
9435 info->simd_opts = acfg->simd_opts;
9436 info->gc_name_index = acfg->gc_name_offset;
9437 info->datafile_size = acfg->datafile_offset;
9438 for (i = 0; i < MONO_AOT_TABLE_NUM; ++i)
9439 info->table_offsets [i] = acfg->table_offsets [i];
9440 for (i = 0; i < MONO_AOT_TRAMP_NUM; ++i)
9441 info->num_trampolines [i] = acfg->num_trampolines [i];
9442 for (i = 0; i < MONO_AOT_TRAMP_NUM; ++i)
9443 info->trampoline_got_offset_base [i] = acfg->trampoline_got_offset_base [i];
9444 for (i = 0; i < MONO_AOT_TRAMP_NUM; ++i)
9445 info->trampoline_size [i] = acfg->trampoline_size [i];
9446 info->num_rgctx_fetch_trampolines = acfg->aot_opts.nrgctx_fetch_trampolines;
9448 info->double_align = MONO_ABI_ALIGNOF (double);
9449 info->long_align = MONO_ABI_ALIGNOF (gint64);
9450 info->generic_tramp_num = MONO_TRAMPOLINE_NUM;
9451 info->tramp_page_size = acfg->tramp_page_size;
9452 info->nshared_got_entries = acfg->nshared_got_entries;
9453 for (i = 0; i < MONO_AOT_TRAMP_NUM; ++i)
9454 info->tramp_page_code_offsets [i] = acfg->tramp_page_code_offsets [i];
9458 emit_aot_file_info (MonoAotCompile *acfg, MonoAotFileInfo *info)
9462 const char **symbols;
9464 symbols = g_new0 (const char *, MONO_AOT_FILE_INFO_NUM_SYMBOLS);
9466 symbols [sindex ++] = acfg->got_symbol;
9468 symbols [sindex ++] = g_strdup_printf ("%s%s", acfg->user_symbol_prefix, acfg->llvm_got_symbol);
9469 symbols [sindex ++] = acfg->llvm_eh_frame_symbol;
9471 symbols [sindex ++] = NULL;
9472 symbols [sindex ++] = NULL;
9474 /* llvm_get_method */
9475 symbols [sindex ++] = NULL;
9476 /* llvm_get_unbox_tramp */
9477 symbols [sindex ++] = NULL;
9478 if (!acfg->aot_opts.llvm_only) {
9479 symbols [sindex ++] = "jit_code_start";
9480 symbols [sindex ++] = "jit_code_end";
9481 symbols [sindex ++] = "method_addresses";
9483 symbols [sindex ++] = NULL;
9484 symbols [sindex ++] = NULL;
9485 symbols [sindex ++] = NULL;
9487 if (acfg->data_outfile) {
9488 for (i = 0; i < MONO_AOT_TABLE_NUM; ++i)
9489 symbols [sindex ++] = NULL;
9491 symbols [sindex ++] = "blob";
9492 symbols [sindex ++] = "class_name_table";
9493 symbols [sindex ++] = "class_info_offsets";
9494 symbols [sindex ++] = "method_info_offsets";
9495 symbols [sindex ++] = "ex_info_offsets";
9496 symbols [sindex ++] = "extra_method_info_offsets";
9497 symbols [sindex ++] = "extra_method_table";
9498 symbols [sindex ++] = "got_info_offsets";
9500 symbols [sindex ++] = "llvm_got_info_offsets";
9502 symbols [sindex ++] = NULL;
9503 symbols [sindex ++] = "image_table";
9505 symbols [sindex ++] = "mem_end";
9506 symbols [sindex ++] = "assembly_guid";
9507 symbols [sindex ++] = "runtime_version";
9508 if (acfg->num_trampoline_got_entries) {
9509 symbols [sindex ++] = "specific_trampolines";
9510 symbols [sindex ++] = "static_rgctx_trampolines";
9511 symbols [sindex ++] = "imt_thunks";
9512 symbols [sindex ++] = "gsharedvt_arg_trampolines";
9514 symbols [sindex ++] = NULL;
9515 symbols [sindex ++] = NULL;
9516 symbols [sindex ++] = NULL;
9517 symbols [sindex ++] = NULL;
9519 if (acfg->aot_opts.static_link) {
9520 symbols [sindex ++] = "globals";
9522 symbols [sindex ++] = NULL;
9524 symbols [sindex ++] = "assembly_name";
9525 symbols [sindex ++] = "plt";
9526 symbols [sindex ++] = "plt_end";
9527 symbols [sindex ++] = "unwind_info";
9528 if (!acfg->aot_opts.llvm_only) {
9529 symbols [sindex ++] = "unbox_trampolines";
9530 symbols [sindex ++] = "unbox_trampolines_end";
9531 symbols [sindex ++] = "unbox_trampoline_addresses";
9533 symbols [sindex ++] = NULL;
9534 symbols [sindex ++] = NULL;
9535 symbols [sindex ++] = NULL;
9538 g_assert (sindex == MONO_AOT_FILE_INFO_NUM_SYMBOLS);
9540 sprintf (symbol, "%smono_aot_file_info", acfg->user_symbol_prefix);
9541 emit_section_change (acfg, ".data", 0);
9542 emit_alignment (acfg, 8);
9543 emit_label (acfg, symbol);
9544 if (!acfg->aot_opts.static_link)
9545 emit_global (acfg, symbol, FALSE);
9547 /* The data emitted here must match MonoAotFileInfo. */
9549 emit_int32 (acfg, info->version);
9550 emit_int32 (acfg, info->dummy);
9553 * We emit pointers to our data structures instead of emitting global symbols which
9554 * point to them, to reduce the number of globals, and because using globals leads to
9555 * various problems (i.e. arm/thumb).
9557 for (i = 0; i < MONO_AOT_FILE_INFO_NUM_SYMBOLS; ++i)
9558 emit_pointer (acfg, symbols [i]);
9560 emit_int32 (acfg, info->plt_got_offset_base);
9561 emit_int32 (acfg, info->got_size);
9562 emit_int32 (acfg, info->plt_size);
9563 emit_int32 (acfg, info->nmethods);
9564 emit_int32 (acfg, info->flags);
9565 emit_int32 (acfg, info->opts);
9566 emit_int32 (acfg, info->simd_opts);
9567 emit_int32 (acfg, info->gc_name_index);
9568 emit_int32 (acfg, info->num_rgctx_fetch_trampolines);
9569 emit_int32 (acfg, info->double_align);
9570 emit_int32 (acfg, info->long_align);
9571 emit_int32 (acfg, info->generic_tramp_num);
9572 emit_int32 (acfg, info->tramp_page_size);
9573 emit_int32 (acfg, info->nshared_got_entries);
9574 emit_int32 (acfg, info->datafile_size);
9576 for (i = 0; i < MONO_AOT_TABLE_NUM; ++i)
9577 emit_int32 (acfg, info->table_offsets [i]);
9578 for (i = 0; i < MONO_AOT_TRAMP_NUM; ++i)
9579 emit_int32 (acfg, info->num_trampolines [i]);
9580 for (i = 0; i < MONO_AOT_TRAMP_NUM; ++i)
9581 emit_int32 (acfg, info->trampoline_got_offset_base [i]);
9582 for (i = 0; i < MONO_AOT_TRAMP_NUM; ++i)
9583 emit_int32 (acfg, info->trampoline_size [i]);
9584 for (i = 0; i < MONO_AOT_TRAMP_NUM; ++i)
9585 emit_int32 (acfg, info->tramp_page_code_offsets [i]);
9587 if (acfg->aot_opts.static_link) {
9588 emit_global_inner (acfg, acfg->static_linking_symbol, FALSE);
9589 emit_alignment (acfg, sizeof (gpointer));
9590 emit_label (acfg, acfg->static_linking_symbol);
9591 emit_pointer_2 (acfg, acfg->user_symbol_prefix, "mono_aot_file_info");
9596 * Emit a structure containing all the information not stored elsewhere.
9599 emit_file_info (MonoAotCompile *acfg)
9602 MonoAotFileInfo *info;
9604 if (acfg->aot_opts.bind_to_runtime_version) {
9605 build_info = mono_get_runtime_build_info ();
9606 emit_string_symbol (acfg, "runtime_version", build_info);
9607 g_free (build_info);
9609 emit_string_symbol (acfg, "runtime_version", "");
9612 emit_string_symbol (acfg, "assembly_guid" , acfg->image->guid);
9614 /* Emit a string holding the assembly name */
9615 emit_string_symbol (acfg, "assembly_name", acfg->image->assembly->aname.name);
9617 info = g_new0 (MonoAotFileInfo, 1);
9618 init_aot_file_info (acfg, info);
9620 if (acfg->aot_opts.static_link) {
9625 * Emit a global symbol which can be passed by an embedding app to
9626 * mono_aot_register_module (). The symbol points to a pointer to the the file info
9629 sprintf (symbol, "%smono_aot_module_%s_info", acfg->user_symbol_prefix, acfg->image->assembly->aname.name);
9631 /* Get rid of characters which cannot occur in symbols */
9633 for (p = symbol; *p; ++p) {
9634 if (!(isalnum (*p) || *p == '_'))
9637 acfg->static_linking_symbol = g_strdup (symbol);
9641 mono_llvm_emit_aot_file_info (info, acfg->has_jitted_code);
9643 emit_aot_file_info (acfg, info);
9647 emit_blob (MonoAotCompile *acfg)
9649 acfg->blob_closed = TRUE;
9651 emit_aot_data (acfg, MONO_AOT_TABLE_BLOB, "blob", (guint8*)acfg->blob.data, acfg->blob.index);
9655 emit_objc_selectors (MonoAotCompile *acfg)
9660 if (!acfg->objc_selectors || acfg->objc_selectors->len == 0)
9665 * cat > foo.m << EOF
9668 * return @selector(print:);
9673 mono_img_writer_emit_unset_mode (acfg->w);
9674 g_assert (acfg->fp);
9675 fprintf (acfg->fp, ".section __DATA,__objc_selrefs,literal_pointers,no_dead_strip\n");
9676 fprintf (acfg->fp, ".align 3\n");
9677 for (i = 0; i < acfg->objc_selectors->len; ++i) {
9678 sprintf (symbol, "L_OBJC_SELECTOR_REFERENCES_%d", i);
9679 emit_label (acfg, symbol);
9680 sprintf (symbol, "L_OBJC_METH_VAR_NAME_%d", i);
9681 emit_pointer (acfg, symbol);
9684 fprintf (acfg->fp, ".section __TEXT,__cstring,cstring_literals\n");
9685 for (i = 0; i < acfg->objc_selectors->len; ++i) {
9686 fprintf (acfg->fp, "L_OBJC_METH_VAR_NAME_%d:\n", i);
9687 fprintf (acfg->fp, ".asciz \"%s\"\n", (char*)g_ptr_array_index (acfg->objc_selectors, i));
9690 fprintf (acfg->fp, ".section __DATA,__objc_imageinfo,regular,no_dead_strip\n");
9691 fprintf (acfg->fp, ".align 3\n");
9692 fprintf (acfg->fp, "L_OBJC_IMAGE_INFO:\n");
9693 fprintf (acfg->fp, ".long 0\n");
9694 fprintf (acfg->fp, ".long 16\n");
9698 emit_dwarf_info (MonoAotCompile *acfg)
9700 #ifdef EMIT_DWARF_INFO
9704 /* DIEs for methods */
9705 for (i = 0; i < acfg->nmethods; ++i) {
9706 MonoCompile *cfg = acfg->cfgs [i];
9711 // FIXME: LLVM doesn't define .Lme_...
9712 if (cfg->compile_llvm)
9715 sprintf (symbol2, "%sme_%x", acfg->temp_prefix, i);
9717 mono_dwarf_writer_emit_method (acfg->dwarf, cfg, cfg->method, cfg->asm_symbol, symbol2, cfg->asm_debug_symbol, (guint8 *)cfg->jit_info->code_start, cfg->jit_info->code_size, cfg->args, cfg->locals, cfg->unwind_ops, mono_debug_find_method (cfg->jit_info->d.method, mono_domain_get ()));
9723 collect_methods (MonoAotCompile *acfg)
9726 MonoImage *image = acfg->image;
9728 /* Collect methods */
9729 for (i = 0; i < image->tables [MONO_TABLE_METHOD].rows; ++i) {
9732 guint32 token = MONO_TOKEN_METHOD_DEF | (i + 1);
9734 method = mono_get_method_checked (acfg->image, token, NULL, NULL, &error);
9737 aot_printerrf (acfg, "Failed to load method 0x%x from '%s' due to %s.\n", token, image->name, mono_error_get_message (&error));
9738 aot_printerrf (acfg, "Run with MONO_LOG_LEVEL=debug for more information.\n");
9739 mono_error_cleanup (&error);
9743 /* Load all methods eagerly to skip the slower lazy loading code */
9744 mono_class_setup_methods (method->klass);
9746 if (mono_aot_mode_is_full (&acfg->aot_opts) && method->iflags & METHOD_IMPL_ATTRIBUTE_INTERNAL_CALL) {
9747 /* Compile the wrapper instead */
9748 /* We do this here instead of add_wrappers () because it is easy to do it here */
9749 MonoMethod *wrapper = mono_marshal_get_native_wrapper (method, TRUE, TRUE);
9753 /* FIXME: Some mscorlib methods don't have debug info */
9755 if (acfg->aot_opts.soft_debug && !method->wrapper_type) {
9756 if (!((method->flags & METHOD_ATTRIBUTE_PINVOKE_IMPL) ||
9757 (method->iflags & METHOD_IMPL_ATTRIBUTE_RUNTIME) ||
9758 (method->flags & METHOD_ATTRIBUTE_ABSTRACT) ||
9759 (method->iflags & METHOD_IMPL_ATTRIBUTE_INTERNAL_CALL))) {
9760 if (!mono_debug_lookup_method (method)) {
9761 fprintf (stderr, "Method %s has no debug info, probably the .mdb file for the assembly is missing.\n", mono_method_get_full_name (method));
9768 if (method->is_generic || method->klass->generic_container)
9769 /* Compile the ref shared version instead */
9770 method = mini_get_shared_method (method);
9772 /* Since we add the normal methods first, their index will be equal to their zero based token index */
9773 add_method_with_index (acfg, method, i, FALSE);
9774 acfg->method_index ++;
9777 /* gsharedvt methods */
9778 for (mindex = 0; mindex < image->tables [MONO_TABLE_METHOD].rows; ++mindex) {
9781 guint32 token = MONO_TOKEN_METHOD_DEF | (mindex + 1);
9783 if (!(acfg->opts & MONO_OPT_GSHAREDVT))
9786 method = mono_get_method_checked (acfg->image, token, NULL, NULL, &error);
9787 report_loader_error (acfg, &error, "Failed to load method token 0x%x due to %s\n", i, mono_error_get_message (&error));
9789 if (method->is_generic || method->klass->generic_container) {
9790 MonoMethod *gshared;
9792 gshared = mini_get_shared_method_full (method, TRUE, TRUE);
9793 add_extra_method (acfg, gshared);
9797 add_generic_instances (acfg);
9799 if (mono_aot_mode_is_full (&acfg->aot_opts))
9800 add_wrappers (acfg);
9805 compile_methods (MonoAotCompile *acfg)
9809 if (acfg->aot_opts.nthreads > 0) {
9814 gpointer *user_data;
9815 MonoMethod **methods;
9817 methods_len = acfg->methods->len;
9819 len = acfg->methods->len / acfg->aot_opts.nthreads;
9822 * Partition the list of methods into fragments, and hand it to threads to
9825 threads = g_ptr_array_new ();
9826 /* Make a copy since acfg->methods is modified by compile_method () */
9827 methods = g_new0 (MonoMethod*, methods_len);
9828 //memcpy (methods, g_ptr_array_index (acfg->methods, 0), sizeof (MonoMethod*) * methods_len);
9829 for (i = 0; i < methods_len; ++i)
9830 methods [i] = (MonoMethod *)g_ptr_array_index (acfg->methods, i);
9832 while (i < methods_len) {
9833 frag = g_ptr_array_new ();
9834 for (j = 0; j < len; ++j) {
9835 if (i < methods_len) {
9836 g_ptr_array_add (frag, methods [i]);
9841 user_data = g_new0 (gpointer, 3);
9842 user_data [0] = mono_domain_get ();
9843 user_data [1] = acfg;
9844 user_data [2] = frag;
9846 handle = mono_threads_create_thread ((LPTHREAD_START_ROUTINE)compile_thread_main, user_data, 0, 0, NULL);
9847 g_ptr_array_add (threads, handle);
9851 for (i = 0; i < threads->len; ++i) {
9852 WaitForSingleObjectEx (g_ptr_array_index (threads, i), INFINITE, FALSE);
9858 /* Compile methods added by compile_method () or all methods if nthreads == 0 */
9859 for (i = methods_len; i < acfg->methods->len; ++i) {
9860 /* This can new methods to acfg->methods */
9861 compile_method (acfg, (MonoMethod *)g_ptr_array_index (acfg->methods, i));
9866 compile_asm (MonoAotCompile *acfg)
9868 char *command, *objfile;
9869 char *outfile_name, *tmp_outfile_name, *llvm_ofile;
9870 const char *tool_prefix = acfg->aot_opts.tool_prefix ? acfg->aot_opts.tool_prefix : "";
9871 char *ld_flags = acfg->aot_opts.ld_flags ? acfg->aot_opts.ld_flags : g_strdup("");
9873 #if defined(TARGET_AMD64) && !defined(TARGET_MACH)
9874 #define AS_OPTIONS "--64"
9875 #elif defined(TARGET_POWERPC64)
9876 #define AS_OPTIONS "-a64 -mppc64"
9877 #define LD_OPTIONS "-m elf64ppc"
9878 #elif defined(sparc) && SIZEOF_VOID_P == 8
9879 #define AS_OPTIONS "-xarch=v9"
9880 #elif defined(TARGET_X86) && defined(TARGET_MACH) && !defined(__native_client_codegen__)
9881 #define AS_OPTIONS "-arch i386"
9883 #define AS_OPTIONS ""
9886 #ifdef __native_client_codegen__
9887 #if defined(TARGET_AMD64)
9888 #define AS_NAME "nacl64-as"
9890 #define AS_NAME "nacl-as"
9892 #elif defined(TARGET_OSX)
9893 #define AS_NAME "clang"
9895 #define AS_NAME "as"
9899 #define LD_OPTIONS ""
9903 #define LD_NAME "ld -shared -G"
9904 #elif defined(__ppc__) && defined(TARGET_MACH)
9905 #define LD_NAME "gcc -dynamiclib"
9906 #elif defined(TARGET_AMD64) && defined(TARGET_MACH)
9907 #define LD_NAME "clang --shared"
9908 #elif defined(TARGET_WIN32) && !defined(TARGET_ANDROID)
9909 #define LD_NAME "gcc -shared --dll"
9910 #elif defined(TARGET_X86) && defined(TARGET_MACH) && !defined(__native_client_codegen__)
9911 #define LD_NAME "clang -m32 -dynamiclib"
9912 #elif defined(TARGET_ARM) && !defined(TARGET_ANDROID)
9913 #define LD_NAME "gcc --shared"
9916 if (acfg->aot_opts.asm_only) {
9917 aot_printf (acfg, "Output file: '%s'.\n", acfg->tmpfname);
9918 if (acfg->aot_opts.static_link)
9919 aot_printf (acfg, "Linking symbol: '%s'.\n", acfg->static_linking_symbol);
9921 aot_printf (acfg, "LLVM output file: '%s'.\n", acfg->llvm_sfile);
9925 if (acfg->aot_opts.static_link) {
9926 if (acfg->aot_opts.outfile)
9927 objfile = g_strdup_printf ("%s", acfg->aot_opts.outfile);
9929 objfile = g_strdup_printf ("%s.o", acfg->image->name);
9931 objfile = g_strdup_printf ("%s.o", acfg->tmpfname);
9935 g_string_append (acfg->as_args, "-c -x assembler");
9938 command = g_strdup_printf ("\"%s%s\" %s %s -o %s %s", tool_prefix, AS_NAME, AS_OPTIONS,
9939 acfg->as_args ? acfg->as_args->str : "",
9940 wrap_path (objfile), wrap_path (acfg->tmpfname));
9941 aot_printf (acfg, "Executing the native assembler: %s\n", command);
9942 if (execute_system (command) != 0) {
9948 if (acfg->llvm && !acfg->llvm_owriter) {
9949 command = g_strdup_printf ("\"%s%s\" %s %s -o %s %s", tool_prefix, AS_NAME, AS_OPTIONS,
9950 acfg->as_args ? acfg->as_args->str : "",
9951 wrap_path (acfg->llvm_ofile), wrap_path (acfg->llvm_sfile));
9952 aot_printf (acfg, "Executing the native assembler: %s\n", command);
9953 if (execute_system (command) != 0) {
9962 if (acfg->aot_opts.static_link) {
9963 aot_printf (acfg, "Output file: '%s'.\n", objfile);
9964 aot_printf (acfg, "Linking symbol: '%s'.\n", acfg->static_linking_symbol);
9969 if (acfg->aot_opts.outfile)
9970 outfile_name = g_strdup_printf ("%s", acfg->aot_opts.outfile);
9972 outfile_name = g_strdup_printf ("%s%s", acfg->image->name, MONO_SOLIB_EXT);
9974 tmp_outfile_name = g_strdup_printf ("%s.tmp", outfile_name);
9977 llvm_ofile = g_strdup_printf ("\"%s\"", acfg->llvm_ofile);
9979 llvm_ofile = g_strdup ("");
9982 /* replace the ; flags separators with spaces */
9983 g_strdelimit (ld_flags, ";", ' ');
9985 if (acfg->aot_opts.llvm_only)
9986 ld_flags = g_strdup_printf ("%s %s", ld_flags, "-lstdc++");
9989 command = g_strdup_printf ("%s -o %s %s %s %s", LD_NAME,
9990 wrap_path (tmp_outfile_name), wrap_path (llvm_ofile),
9991 wrap_path (g_strdup_printf ("%s.o", acfg->tmpfname)), ld_flags);
9993 command = g_strdup_printf ("\"%sld\" %s -shared -o %s %s %s %s", tool_prefix, LD_OPTIONS,
9994 wrap_path (tmp_outfile_name), wrap_path (llvm_ofile),
9995 wrap_path (g_strdup_printf ("%s.o", acfg->tmpfname)), ld_flags);
9997 aot_printf (acfg, "Executing the native linker: %s\n", command);
9998 if (execute_system (command) != 0) {
9999 g_free (tmp_outfile_name);
10000 g_free (outfile_name);
10009 /*com = g_strdup_printf ("strip --strip-unneeded %s%s", acfg->image->name, MONO_SOLIB_EXT);
10010 printf ("Stripping the binary: %s\n", com);
10011 execute_system (com);
10014 #if defined(TARGET_ARM) && !defined(TARGET_MACH)
10016 * gas generates 'mapping symbols' each time code and data is mixed, which
10017 * happens a lot in emit_and_reloc_code (), so we need to get rid of them.
10019 command = g_strdup_printf ("\"%sstrip\" --strip-symbol=\\$a --strip-symbol=\\$d %s", tool_prefix, tmp_outfile_name);
10020 aot_printf (acfg, "Stripping the binary: %s\n", command);
10021 if (execute_system (command) != 0) {
10022 g_free (tmp_outfile_name);
10023 g_free (outfile_name);
10030 rename (tmp_outfile_name, outfile_name);
10032 #if defined(TARGET_MACH)
10033 command = g_strdup_printf ("dsymutil \"%s\"", outfile_name);
10034 aot_printf (acfg, "Executing dsymutil: %s\n", command);
10035 if (execute_system (command) != 0) {
10040 if (!acfg->aot_opts.save_temps)
10043 g_free (tmp_outfile_name);
10044 g_free (outfile_name);
10047 if (acfg->aot_opts.save_temps)
10048 aot_printf (acfg, "Retained input file.\n");
10050 unlink (acfg->tmpfname);
10055 static void init_got_info (GotInfo *info)
10059 info->patch_to_got_offset = g_hash_table_new (mono_patch_info_hash, mono_patch_info_equal);
10060 info->patch_to_got_offset_by_type = g_new0 (GHashTable*, MONO_PATCH_INFO_NUM);
10061 for (i = 0; i < MONO_PATCH_INFO_NUM; ++i)
10062 info->patch_to_got_offset_by_type [i] = g_hash_table_new (mono_patch_info_hash, mono_patch_info_equal);
10063 info->got_patches = g_ptr_array_new ();
10066 static MonoAotCompile*
10067 acfg_create (MonoAssembly *ass, guint32 opts)
10069 MonoImage *image = ass->image;
10070 MonoAotCompile *acfg;
10072 acfg = g_new0 (MonoAotCompile, 1);
10073 acfg->methods = g_ptr_array_new ();
10074 acfg->method_indexes = g_hash_table_new (NULL, NULL);
10075 acfg->method_depth = g_hash_table_new (NULL, NULL);
10076 acfg->plt_offset_to_entry = g_hash_table_new (NULL, NULL);
10077 acfg->patch_to_plt_entry = g_new0 (GHashTable*, MONO_PATCH_INFO_NUM);
10078 acfg->method_to_cfg = g_hash_table_new (NULL, NULL);
10079 acfg->token_info_hash = g_hash_table_new_full (NULL, NULL, NULL, NULL);
10080 acfg->method_to_pinvoke_import = g_hash_table_new_full (NULL, NULL, NULL, g_free);
10081 acfg->image_hash = g_hash_table_new (NULL, NULL);
10082 acfg->image_table = g_ptr_array_new ();
10083 acfg->globals = g_ptr_array_new ();
10084 acfg->image = image;
10086 /* TODO: Write out set of SIMD instructions used, rather than just those available */
10087 acfg->simd_opts = mono_arch_cpu_enumerate_simd_versions ();
10088 acfg->mempool = mono_mempool_new ();
10089 acfg->extra_methods = g_ptr_array_new ();
10090 acfg->unwind_info_offsets = g_hash_table_new (NULL, NULL);
10091 acfg->unwind_ops = g_ptr_array_new ();
10092 acfg->method_label_hash = g_hash_table_new_full (g_str_hash, g_str_equal, g_free, NULL);
10093 acfg->method_order = g_ptr_array_new ();
10094 acfg->export_names = g_hash_table_new (NULL, NULL);
10095 acfg->klass_blob_hash = g_hash_table_new (NULL, NULL);
10096 acfg->method_blob_hash = g_hash_table_new (NULL, NULL);
10097 acfg->plt_entry_debug_sym_cache = g_hash_table_new (g_str_hash, g_str_equal);
10098 acfg->gsharedvt_in_signatures = g_hash_table_new ((GHashFunc)mono_signature_hash, (GEqualFunc)mono_metadata_signature_equal);
10099 acfg->gsharedvt_out_signatures = g_hash_table_new ((GHashFunc)mono_signature_hash, (GEqualFunc)mono_metadata_signature_equal);
10100 mono_os_mutex_init_recursive (&acfg->mutex);
10102 init_got_info (&acfg->got_info);
10103 init_got_info (&acfg->llvm_got_info);
10109 got_info_free (GotInfo *info)
10113 for (i = 0; i < MONO_PATCH_INFO_NUM; ++i)
10114 g_hash_table_destroy (info->patch_to_got_offset_by_type [i]);
10115 g_free (info->patch_to_got_offset_by_type);
10116 g_hash_table_destroy (info->patch_to_got_offset);
10117 g_ptr_array_free (info->got_patches, TRUE);
10121 acfg_free (MonoAotCompile *acfg)
10125 mono_img_writer_destroy (acfg->w);
10126 for (i = 0; i < acfg->nmethods; ++i)
10127 if (acfg->cfgs [i])
10128 g_free (acfg->cfgs [i]);
10129 g_free (acfg->cfgs);
10130 g_free (acfg->static_linking_symbol);
10131 g_free (acfg->got_symbol);
10132 g_free (acfg->plt_symbol);
10133 g_ptr_array_free (acfg->methods, TRUE);
10134 g_ptr_array_free (acfg->image_table, TRUE);
10135 g_ptr_array_free (acfg->globals, TRUE);
10136 g_ptr_array_free (acfg->unwind_ops, TRUE);
10137 g_hash_table_destroy (acfg->method_indexes);
10138 g_hash_table_destroy (acfg->method_depth);
10139 g_hash_table_destroy (acfg->plt_offset_to_entry);
10140 for (i = 0; i < MONO_PATCH_INFO_NUM; ++i) {
10141 if (acfg->patch_to_plt_entry [i])
10142 g_hash_table_destroy (acfg->patch_to_plt_entry [i]);
10144 g_free (acfg->patch_to_plt_entry);
10145 g_hash_table_destroy (acfg->method_to_cfg);
10146 g_hash_table_destroy (acfg->token_info_hash);
10147 g_hash_table_destroy (acfg->method_to_pinvoke_import);
10148 g_hash_table_destroy (acfg->image_hash);
10149 g_hash_table_destroy (acfg->unwind_info_offsets);
10150 g_hash_table_destroy (acfg->method_label_hash);
10151 g_hash_table_destroy (acfg->export_names);
10152 g_hash_table_destroy (acfg->plt_entry_debug_sym_cache);
10153 g_hash_table_destroy (acfg->klass_blob_hash);
10154 g_hash_table_destroy (acfg->method_blob_hash);
10155 got_info_free (&acfg->got_info);
10156 got_info_free (&acfg->llvm_got_info);
10157 mono_mempool_destroy (acfg->mempool);
10161 #define WRAPPER(e,n) n,
10162 static const char* const
10163 wrapper_type_names [MONO_WRAPPER_NUM + 1] = {
10164 #include "mono/metadata/wrapper-types.h"
10168 static G_GNUC_UNUSED const char*
10169 get_wrapper_type_name (int type)
10171 return wrapper_type_names [type];
10177 static void aot_dump (MonoAotCompile *acfg)
10183 mono_json_writer_init (&writer);
10185 mono_json_writer_object_begin(&writer);
10188 mono_json_writer_indent (&writer);
10189 mono_json_writer_object_key(&writer, "methods");
10190 mono_json_writer_array_begin (&writer);
10193 for (i = 0; i < acfg->nmethods; ++i) {
10195 MonoMethod *method;
10198 cfg = acfg->cfgs [i];
10202 method = cfg->orig_method;
10204 mono_json_writer_indent (&writer);
10205 mono_json_writer_object_begin(&writer);
10207 mono_json_writer_indent (&writer);
10208 mono_json_writer_object_key(&writer, "name");
10209 mono_json_writer_printf (&writer, "\"%s\",\n", method->name);
10211 mono_json_writer_indent (&writer);
10212 mono_json_writer_object_key(&writer, "signature");
10213 mono_json_writer_printf (&writer, "\"%s\",\n", mono_method_get_full_name (method));
10215 mono_json_writer_indent (&writer);
10216 mono_json_writer_object_key(&writer, "code_size");
10217 mono_json_writer_printf (&writer, "\"%d\",\n", cfg->code_size);
10219 klass = method->klass;
10221 mono_json_writer_indent (&writer);
10222 mono_json_writer_object_key(&writer, "class");
10223 mono_json_writer_printf (&writer, "\"%s\",\n", klass->name);
10225 mono_json_writer_indent (&writer);
10226 mono_json_writer_object_key(&writer, "namespace");
10227 mono_json_writer_printf (&writer, "\"%s\",\n", klass->name_space);
10229 mono_json_writer_indent (&writer);
10230 mono_json_writer_object_key(&writer, "wrapper_type");
10231 mono_json_writer_printf (&writer, "\"%s\",\n", get_wrapper_type_name(method->wrapper_type));
10233 mono_json_writer_indent_pop (&writer);
10234 mono_json_writer_indent (&writer);
10235 mono_json_writer_object_end (&writer);
10236 mono_json_writer_printf (&writer, ",\n");
10239 mono_json_writer_indent_pop (&writer);
10240 mono_json_writer_indent (&writer);
10241 mono_json_writer_array_end (&writer);
10242 mono_json_writer_printf (&writer, ",\n");
10246 mono_json_writer_indent_push (&writer);
10247 mono_json_writer_indent (&writer);
10248 mono_json_writer_object_key(&writer, "plt");
10249 mono_json_writer_array_begin (&writer);
10251 for (i = 0; i < acfg->plt_offset; ++i) {
10252 MonoPltEntry *plt_entry = NULL;
10257 * The first plt entry is unused.
10261 plt_entry = g_hash_table_lookup (acfg->plt_offset_to_entry, GUINT_TO_POINTER (i));
10262 ji = plt_entry->ji;
10264 mono_json_writer_indent (&writer);
10265 mono_json_writer_printf (&writer, "{ ");
10266 mono_json_writer_object_key(&writer, "symbol");
10267 mono_json_writer_printf (&writer, "\"%s\" },\n", plt_entry->symbol);
10270 mono_json_writer_indent_pop (&writer);
10271 mono_json_writer_indent (&writer);
10272 mono_json_writer_array_end (&writer);
10273 mono_json_writer_printf (&writer, ",\n");
10278 mono_json_writer_indent_push (&writer);
10279 mono_json_writer_indent (&writer);
10280 mono_json_writer_object_key(&writer, "got");
10281 mono_json_writer_array_begin (&writer);
10283 mono_json_writer_indent_push (&writer);
10284 for (i = 0; i < acfg->got_info.got_patches->len; ++i) {
10285 MonoJumpInfo *ji = g_ptr_array_index (acfg->got_info.got_patches, i);
10287 mono_json_writer_indent (&writer);
10288 mono_json_writer_printf (&writer, "{ ");
10289 mono_json_writer_object_key(&writer, "patch_name");
10290 mono_json_writer_printf (&writer, "\"%s\" },\n", get_patch_name (ji->type));
10293 mono_json_writer_indent_pop (&writer);
10294 mono_json_writer_indent (&writer);
10295 mono_json_writer_array_end (&writer);
10296 mono_json_writer_printf (&writer, ",\n");
10299 mono_json_writer_indent_pop (&writer);
10300 mono_json_writer_indent (&writer);
10301 mono_json_writer_object_end (&writer);
10303 dumpname = g_strdup_printf ("%s.json", g_path_get_basename (acfg->image->name));
10304 dumpfile = fopen (dumpname, "w+");
10307 fprintf (dumpfile, "%s", writer.text->str);
10310 mono_json_writer_destroy (&writer);
10313 static const char *preinited_jit_icalls[] = {
10314 "mono_aot_init_llvm_method",
10315 "mono_aot_init_gshared_method_this",
10316 "mono_aot_init_gshared_method_mrgctx",
10317 "mono_aot_init_gshared_method_vtable",
10318 "mono_llvm_throw_corlib_exception",
10319 "mono_init_vtable_slot",
10320 "mono_helper_ldstr_mscorlib"
10324 add_preinit_got_slots (MonoAotCompile *acfg)
10330 * Allocate the first few GOT entries to information which is needed frequently, or it is needed
10331 * during method initialization etc.
10334 ji = (MonoJumpInfo *)mono_mempool_alloc0 (acfg->mempool, sizeof (MonoJumpInfo));
10335 ji->type = MONO_PATCH_INFO_IMAGE;
10336 ji->data.image = acfg->image;
10337 get_got_offset (acfg, FALSE, ji);
10338 get_got_offset (acfg, TRUE, ji);
10340 ji = (MonoJumpInfo *)mono_mempool_alloc0 (acfg->mempool, sizeof (MonoJumpInfo));
10341 ji->type = MONO_PATCH_INFO_MSCORLIB_GOT_ADDR;
10342 get_got_offset (acfg, FALSE, ji);
10343 get_got_offset (acfg, TRUE, ji);
10345 ji = (MonoJumpInfo *)mono_mempool_alloc0 (acfg->mempool, sizeof (MonoJumpInfo));
10346 ji->type = MONO_PATCH_INFO_GC_CARD_TABLE_ADDR;
10347 get_got_offset (acfg, FALSE, ji);
10348 get_got_offset (acfg, TRUE, ji);
10350 ji = (MonoJumpInfo *)mono_mempool_alloc0 (acfg->mempool, sizeof (MonoJumpInfo));
10351 ji->type = MONO_PATCH_INFO_GC_NURSERY_START;
10352 get_got_offset (acfg, FALSE, ji);
10353 get_got_offset (acfg, TRUE, ji);
10355 ji = (MonoJumpInfo *)mono_mempool_alloc0 (acfg->mempool, sizeof (MonoJumpInfo));
10356 ji->type = MONO_PATCH_INFO_JIT_TLS_ID;
10357 get_got_offset (acfg, FALSE, ji);
10358 get_got_offset (acfg, TRUE, ji);
10360 ji = (MonoJumpInfo *)mono_mempool_alloc0 (acfg->mempool, sizeof (MonoJumpInfo));
10361 ji->type = MONO_PATCH_INFO_AOT_MODULE;
10362 get_got_offset (acfg, FALSE, ji);
10363 get_got_offset (acfg, TRUE, ji);
10365 ji = (MonoJumpInfo *)mono_mempool_alloc0 (acfg->mempool, sizeof (MonoJumpInfo));
10366 ji->type = MONO_PATCH_INFO_GC_NURSERY_BITS;
10367 get_got_offset (acfg, FALSE, ji);
10368 get_got_offset (acfg, TRUE, ji);
10370 for (i = 0; i < sizeof (preinited_jit_icalls) / sizeof (char*); ++i) {
10371 ji = (MonoJumpInfo *)mono_mempool_alloc0 (acfg->mempool, sizeof (MonoAotCompile));
10372 ji->type = MONO_PATCH_INFO_INTERNAL_METHOD;
10373 ji->data.name = preinited_jit_icalls [i];
10374 get_got_offset (acfg, FALSE, ji);
10375 get_got_offset (acfg, TRUE, ji);
10378 acfg->nshared_got_entries = acfg->got_offset;
10382 mono_compile_assembly (MonoAssembly *ass, guint32 opts, const char *aot_options)
10384 MonoImage *image = ass->image;
10387 MonoAotCompile *acfg;
10388 char *outfile_name, *tmp_outfile_name, *p;
10389 char llvm_stats_msg [256];
10393 acfg = acfg_create (ass, opts);
10395 memset (&acfg->aot_opts, 0, sizeof (acfg->aot_opts));
10396 acfg->aot_opts.write_symbols = TRUE;
10397 acfg->aot_opts.ntrampolines = 4096;
10398 acfg->aot_opts.nrgctx_trampolines = 4096;
10399 acfg->aot_opts.nimt_trampolines = 512;
10400 acfg->aot_opts.nrgctx_fetch_trampolines = 128;
10401 acfg->aot_opts.ngsharedvt_arg_trampolines = 512;
10402 acfg->aot_opts.llvm_path = g_strdup ("");
10403 acfg->aot_opts.temp_path = g_strdup ("");
10405 acfg->aot_opts.use_trampolines_page = TRUE;
10408 mono_aot_parse_options (aot_options, &acfg->aot_opts);
10410 if (acfg->aot_opts.logfile) {
10411 acfg->logfile = fopen (acfg->aot_opts.logfile, "a+");
10414 if (acfg->aot_opts.data_outfile) {
10415 acfg->data_outfile = fopen (acfg->aot_opts.data_outfile, "w+");
10416 if (!acfg->data_outfile) {
10417 aot_printerrf (acfg, "Unable to create file '%s': %s\n", acfg->aot_opts.data_outfile, strerror (errno));
10420 acfg->flags = (MonoAotFileFlags)(acfg->flags | MONO_AOT_FILE_FLAG_SEPARATE_DATA);
10423 //acfg->aot_opts.print_skipped_methods = TRUE;
10425 #if !defined(MONO_ARCH_GSHAREDVT_SUPPORTED)
10426 if (opts & MONO_OPT_GSHAREDVT) {
10427 aot_printerrf (acfg, "-O=gsharedvt not supported on this platform.\n");
10432 #if !defined(MONO_ARCH_GSHAREDVT_SUPPORTED)
10433 if (!acfg->aot_opts.llvm_only && (opts & MONO_OPT_GSHAREDVT)) {
10434 aot_printerrf (acfg, "-O=gsharedvt not supported on this platform.\n");
10439 if (acfg->aot_opts.llvm_only) {
10440 #ifndef MONO_ARCH_GSHAREDVT_SUPPORTED
10441 aot_printerrf (acfg, "--aot=llvmonly requires a runtime that supports gsharedvt.\n");
10446 #if defined(MONO_ARCH_GSHAREDVT_SUPPORTED)
10447 acfg->opts |= MONO_OPT_GSHAREDVT;
10448 opts |= MONO_OPT_GSHAREDVT;
10451 if (opts & MONO_OPT_GSHAREDVT)
10452 mono_set_generic_sharing_vt_supported (TRUE);
10454 aot_printf (acfg, "Mono Ahead of Time compiler - compiling assembly %s\n", image->name);
10456 #ifndef MONO_ARCH_HAVE_FULL_AOT_TRAMPOLINES
10457 if (mono_aot_mode_is_full (&acfg->aot_opts)) {
10458 aot_printerrf (acfg, "--aot=full is not supported on this platform.\n");
10463 if (acfg->aot_opts.direct_pinvoke && !acfg->aot_opts.static_link) {
10464 aot_printerrf (acfg, "The 'direct-pinvoke' AOT option also requires the 'static' AOT option.\n");
10468 if (acfg->aot_opts.static_link)
10469 acfg->aot_opts.asm_writer = TRUE;
10471 if (acfg->aot_opts.soft_debug) {
10472 MonoDebugOptions *opt = mini_get_debug_options ();
10474 opt->mdb_optimizations = TRUE;
10475 opt->gen_sdb_seq_points = TRUE;
10477 if (!mono_debug_enabled ()) {
10478 aot_printerrf (acfg, "The soft-debug AOT option requires the --debug option.\n");
10481 acfg->flags = (MonoAotFileFlags)(acfg->flags | MONO_AOT_FILE_FLAG_DEBUG);
10484 if (mono_use_llvm || acfg->aot_opts.llvm) {
10486 acfg->aot_opts.asm_writer = TRUE;
10487 acfg->flags = (MonoAotFileFlags)(acfg->flags | MONO_AOT_FILE_FLAG_WITH_LLVM);
10489 if (acfg->aot_opts.soft_debug) {
10490 aot_printerrf (acfg, "The 'soft-debug' option is not supported when compiling with LLVM.\n");
10496 if (acfg->aot_opts.asm_only && !acfg->aot_opts.llvm_outfile) {
10497 aot_printerrf (acfg, "Compiling with LLVM and the asm-only option requires the llvm-outputfile= option.");
10502 * Emit all LLVM code into a separate assembly/object file and link with it
10505 if (!acfg->aot_opts.asm_only) {
10506 acfg->llvm_owriter = TRUE;
10507 } else if (acfg->aot_opts.llvm_outfile) {
10508 int len = strlen (acfg->aot_opts.llvm_outfile);
10510 if (len >= 2 && acfg->aot_opts.llvm_outfile [len - 2] == '.' && acfg->aot_opts.llvm_outfile [len - 1] == 'o')
10511 acfg->llvm_owriter = TRUE;
10515 if (mono_aot_mode_is_full (&acfg->aot_opts))
10516 acfg->flags = (MonoAotFileFlags)(acfg->flags | MONO_AOT_FILE_FLAG_FULL_AOT);
10518 if (mono_threads_is_coop_enabled ())
10519 acfg->flags = (MonoAotFileFlags)(acfg->flags | MONO_AOT_FILE_FLAG_SAFEPOINTS);
10521 if (acfg->aot_opts.instances_logfile_path) {
10522 acfg->instances_logfile = fopen (acfg->aot_opts.instances_logfile_path, "w");
10523 if (!acfg->instances_logfile) {
10524 aot_printerrf (acfg, "Unable to create logfile: '%s'.\n", acfg->aot_opts.instances_logfile_path);
10529 load_profile_files (acfg);
10531 acfg->num_trampolines [MONO_AOT_TRAMP_SPECIFIC] = mono_aot_mode_is_full (&acfg->aot_opts) ? acfg->aot_opts.ntrampolines : 0;
10532 #ifdef MONO_ARCH_GSHARED_SUPPORTED
10533 acfg->num_trampolines [MONO_AOT_TRAMP_STATIC_RGCTX] = mono_aot_mode_is_full (&acfg->aot_opts) ? acfg->aot_opts.nrgctx_trampolines : 0;
10535 acfg->num_trampolines [MONO_AOT_TRAMP_IMT_THUNK] = mono_aot_mode_is_full (&acfg->aot_opts) ? acfg->aot_opts.nimt_trampolines : 0;
10536 #ifdef MONO_ARCH_GSHAREDVT_SUPPORTED
10537 if (acfg->opts & MONO_OPT_GSHAREDVT)
10538 acfg->num_trampolines [MONO_AOT_TRAMP_GSHAREDVT_ARG] = mono_aot_mode_is_full (&acfg->aot_opts) ? acfg->aot_opts.ngsharedvt_arg_trampolines : 0;
10541 acfg->temp_prefix = mono_img_writer_get_temp_label_prefix (NULL);
10545 if (acfg->llvm && acfg->thumb_mixed)
10546 acfg->flags = (MonoAotFileFlags)(acfg->flags | MONO_AOT_FILE_FLAG_LLVM_THUMB);
10547 if (acfg->aot_opts.llvm_only)
10548 acfg->flags = (MonoAotFileFlags)(acfg->flags | MONO_AOT_FILE_FLAG_LLVM_ONLY);
10550 acfg->assembly_name_sym = g_strdup (acfg->image->assembly->aname.name);
10551 /* Get rid of characters which cannot occur in symbols */
10552 for (p = acfg->assembly_name_sym; *p; ++p) {
10553 if (!(isalnum (*p) || *p == '_'))
10557 acfg->global_prefix = g_strdup_printf ("mono_aot_%s", acfg->assembly_name_sym);
10558 acfg->plt_symbol = g_strdup_printf ("%s_plt", acfg->global_prefix);
10559 acfg->got_symbol = g_strdup_printf ("%s_got", acfg->global_prefix);
10561 acfg->llvm_got_symbol = g_strdup_printf ("%s_llvm_got", acfg->global_prefix);
10562 acfg->llvm_eh_frame_symbol = g_strdup_printf ("%s_eh_frame", acfg->global_prefix);
10565 acfg->method_index = 1;
10567 if (mono_aot_mode_is_full (&acfg->aot_opts))
10568 mono_set_partial_sharing_supported (TRUE);
10570 res = collect_methods (acfg);
10574 acfg->cfgs_size = acfg->methods->len + 32;
10575 acfg->cfgs = g_new0 (MonoCompile*, acfg->cfgs_size);
10577 /* PLT offset 0 is reserved for the PLT trampoline */
10578 acfg->plt_offset = 1;
10579 add_preinit_got_slots (acfg);
10584 mono_llvm_create_aot_module (acfg->image->assembly, acfg->global_prefix, TRUE, acfg->aot_opts.static_link, acfg->aot_opts.llvm_only);
10590 compile_methods (acfg);
10594 acfg->stats.jit_time = TV_ELAPSED (atv, btv);
10600 if (acfg->aot_opts.asm_only) {
10601 if (acfg->aot_opts.outfile) {
10602 acfg->tmpfname = g_strdup_printf ("%s", acfg->aot_opts.outfile);
10603 acfg->tmpbasename = g_strdup (acfg->tmpfname);
10605 acfg->tmpbasename = g_strdup_printf ("%s", acfg->image->name);
10606 acfg->tmpfname = g_strdup_printf ("%s.s", acfg->tmpbasename);
10608 g_assert (acfg->aot_opts.llvm_outfile);
10609 acfg->llvm_sfile = g_strdup (acfg->aot_opts.llvm_outfile);
10610 if (acfg->llvm_owriter)
10611 acfg->llvm_ofile = g_strdup (acfg->aot_opts.llvm_outfile);
10613 acfg->llvm_sfile = g_strdup (acfg->aot_opts.llvm_outfile);
10615 acfg->tmpbasename = (strcmp (acfg->aot_opts.temp_path, "") == 0) ?
10616 g_strdup_printf ("%s", "temp") :
10617 g_build_filename (acfg->aot_opts.temp_path, "temp", NULL);
10619 acfg->tmpfname = g_strdup_printf ("%s.s", acfg->tmpbasename);
10620 acfg->llvm_sfile = g_strdup_printf ("%s-llvm.s", acfg->tmpbasename);
10621 acfg->llvm_ofile = g_strdup_printf ("%s-llvm.o", acfg->tmpbasename);
10626 if (acfg->aot_opts.asm_only && !acfg->aot_opts.llvm_only) {
10627 if (acfg->aot_opts.outfile)
10628 acfg->tmpfname = g_strdup_printf ("%s", acfg->aot_opts.outfile);
10630 acfg->tmpfname = g_strdup_printf ("%s.s", acfg->image->name);
10631 acfg->fp = fopen (acfg->tmpfname, "w+");
10633 int i = g_file_open_tmp ("mono_aot_XXXXXX", &acfg->tmpfname, NULL);
10634 acfg->fp = fdopen (i, "w+");
10636 if (acfg->fp == 0 && !acfg->aot_opts.llvm_only) {
10637 aot_printerrf (acfg, "Unable to open file '%s': %s\n", acfg->tmpfname, strerror (errno));
10641 acfg->w = mono_img_writer_create (acfg->fp, FALSE);
10643 tmp_outfile_name = NULL;
10644 outfile_name = NULL;
10646 /* Compute symbols for methods */
10647 for (i = 0; i < acfg->nmethods; ++i) {
10648 if (acfg->cfgs [i]) {
10649 MonoCompile *cfg = acfg->cfgs [i];
10650 int method_index = get_method_index (acfg, cfg->orig_method);
10652 if (COMPILE_LLVM (cfg))
10653 cfg->asm_symbol = g_strdup_printf ("%s%s", acfg->llvm_label_prefix, cfg->llvm_method_name);
10654 else if (acfg->global_symbols || acfg->llvm)
10655 cfg->asm_symbol = get_debug_sym (cfg->orig_method, "", acfg->method_label_hash);
10657 cfg->asm_symbol = g_strdup_printf ("%s%sm_%x", acfg->temp_prefix, acfg->llvm_label_prefix, method_index);
10658 cfg->asm_debug_symbol = cfg->asm_symbol;
10662 if (acfg->aot_opts.dwarf_debug && acfg->aot_opts.gnu_asm) {
10664 * CLANG supports GAS .file/.loc directives, so emit line number information this way
10666 acfg->gas_line_numbers = TRUE;
10669 if ((!acfg->aot_opts.nodebug || acfg->aot_opts.dwarf_debug) && acfg->has_jitted_code) {
10670 if (acfg->aot_opts.dwarf_debug && !mono_debug_enabled ()) {
10671 aot_printerrf (acfg, "The dwarf AOT option requires the --debug option.\n");
10674 acfg->dwarf = mono_dwarf_writer_create (acfg->w, NULL, 0, !acfg->gas_line_numbers);
10678 mono_img_writer_emit_start (acfg->w);
10681 mono_dwarf_writer_emit_base_info (acfg->dwarf, g_path_get_basename (acfg->image->name), mono_unwind_get_cie_program ());
10687 emit_extra_methods (acfg);
10689 emit_trampolines (acfg);
10691 emit_class_name_table (acfg);
10693 emit_got_info (acfg, FALSE);
10695 emit_got_info (acfg, TRUE);
10697 emit_exception_info (acfg);
10699 emit_unwind_info (acfg);
10701 emit_class_info (acfg);
10705 emit_image_table (acfg);
10711 * The managed allocators are GC specific, so can't use an AOT image created by one GC
10714 const char *gc_name = mono_gc_get_gc_name ();
10715 acfg->gc_name_offset = add_to_blob (acfg, (guint8*)gc_name, strlen (gc_name) + 1);
10720 emit_objc_selectors (acfg);
10722 emit_globals (acfg);
10724 emit_file_info (acfg);
10727 emit_dwarf_info (acfg);
10728 mono_dwarf_writer_close (acfg->dwarf);
10731 emit_mem_end (acfg);
10733 if (acfg->need_pt_gnu_stack) {
10734 /* This is required so the .so doesn't have an executable stack */
10735 /* The bin writer already emits this */
10736 fprintf (acfg->fp, "\n.section .note.GNU-stack,\"\",@progbits\n");
10739 if (acfg->aot_opts.data_outfile)
10740 fclose (acfg->data_outfile);
10746 res = emit_llvm_file (acfg);
10754 acfg->stats.gen_time = TV_ELAPSED (atv, btv);
10757 sprintf (llvm_stats_msg, ", LLVM: %d (%d%%)", acfg->stats.llvm_count, acfg->stats.mcount ? (acfg->stats.llvm_count * 100) / acfg->stats.mcount : 100);
10759 strcpy (llvm_stats_msg, "");
10761 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;
10763 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",
10764 (int)acfg->stats.code_size, (int)(acfg->stats.code_size * 100 / all_sizes),
10765 (int)acfg->stats.info_size, (int)(acfg->stats.info_size * 100 / all_sizes),
10766 (int)acfg->stats.ex_info_size, (int)(acfg->stats.ex_info_size * 100 / all_sizes),
10767 (int)acfg->stats.unwind_info_size, (int)(acfg->stats.unwind_info_size * 100 / all_sizes),
10768 (int)acfg->stats.class_info_size, (int)(acfg->stats.class_info_size * 100 / all_sizes),
10769 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,
10770 (int)acfg->stats.got_info_size, (int)(acfg->stats.got_info_size * 100 / all_sizes),
10771 (int)acfg->stats.offsets_size, (int)(acfg->stats.offsets_size * 100 / all_sizes),
10772 (int)(acfg->got_offset * sizeof (gpointer)));
10773 aot_printf (acfg, "Compiled: %d/%d (%d%%)%s, No GOT slots: %d (%d%%), Direct calls: %d (%d%%)\n",
10774 acfg->stats.ccount, acfg->stats.mcount, acfg->stats.mcount ? (acfg->stats.ccount * 100) / acfg->stats.mcount : 100,
10776 acfg->stats.methods_without_got_slots, acfg->stats.mcount ? (acfg->stats.methods_without_got_slots * 100) / acfg->stats.mcount : 100,
10777 acfg->stats.direct_calls, acfg->stats.all_calls ? (acfg->stats.direct_calls * 100) / acfg->stats.all_calls : 100);
10778 if (acfg->stats.genericcount)
10779 aot_printf (acfg, "%d methods are generic (%d%%)\n", acfg->stats.genericcount, acfg->stats.mcount ? (acfg->stats.genericcount * 100) / acfg->stats.mcount : 100);
10780 if (acfg->stats.abscount)
10781 aot_printf (acfg, "%d methods contain absolute addresses (%d%%)\n", acfg->stats.abscount, acfg->stats.mcount ? (acfg->stats.abscount * 100) / acfg->stats.mcount : 100);
10782 if (acfg->stats.lmfcount)
10783 aot_printf (acfg, "%d methods contain lmf pointers (%d%%)\n", acfg->stats.lmfcount, acfg->stats.mcount ? (acfg->stats.lmfcount * 100) / acfg->stats.mcount : 100);
10784 if (acfg->stats.ocount)
10785 aot_printf (acfg, "%d methods have other problems (%d%%)\n", acfg->stats.ocount, acfg->stats.mcount ? (acfg->stats.ocount * 100) / acfg->stats.mcount : 100);
10789 res = mono_img_writer_emit_writeout (acfg->w);
10794 res = compile_asm (acfg);
10801 acfg->stats.link_time = TV_ELAPSED (atv, btv);
10803 if (acfg->aot_opts.stats) {
10806 aot_printf (acfg, "GOT slot distribution:\n");
10807 for (i = 0; i < MONO_PATCH_INFO_NUM; ++i)
10808 if (acfg->stats.got_slot_types [i])
10809 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]);
10810 aot_printf (acfg, "\nMethod stats:\n");
10811 aot_printf (acfg, "\tNormal: %d\n", acfg->stats.method_categories [METHOD_CAT_NORMAL]);
10812 aot_printf (acfg, "\tInstance: %d\n", acfg->stats.method_categories [METHOD_CAT_INST]);
10813 aot_printf (acfg, "\tGSharedvt: %d\n", acfg->stats.method_categories [METHOD_CAT_GSHAREDVT]);
10814 aot_printf (acfg, "\tWrapper: %d\n", acfg->stats.method_categories [METHOD_CAT_WRAPPER]);
10817 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);
10819 if (acfg->aot_opts.dump_json)
10832 mono_aot_readonly_field_override (MonoClassField *field)
10838 mono_compile_assembly (MonoAssembly *ass, guint32 opts, const char *aot_options)
10844 mono_aot_is_shared_got_offset (int offset)