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)
13 /* Remaining AOT-only work:
14 * - optimize the trampolines, generate more code in the arch files.
15 * - make things more consistent with how elf works, for example, use ELF
17 * Remaining generics sharing work:
18 * - optimize the size of the data which is encoded.
19 * - optimize the runtime loading of data:
20 * - the trampoline code calls mono_jit_info_table_find () to find the rgctx,
21 * which loads the debugging+exception handling info for the method. This is a
22 * huge waste of time and code, since the rgctx structure is currently empty.
25 #include <sys/types.h>
46 #include <mono/metadata/tabledefs.h>
47 #include <mono/metadata/class.h>
48 #include <mono/metadata/object.h>
49 #include <mono/metadata/tokentype.h>
50 #include <mono/metadata/appdomain.h>
51 #include <mono/metadata/debug-helpers.h>
52 #include <mono/metadata/assembly.h>
53 #include <mono/metadata/metadata-internals.h>
54 #include <mono/metadata/marshal.h>
55 #include <mono/metadata/gc-internal.h>
56 #include <mono/metadata/monitor.h>
57 #include <mono/metadata/mempool-internals.h>
58 #include <mono/metadata/mono-endian.h>
59 #include <mono/metadata/threads-types.h>
60 #include <mono/utils/mono-logger-internal.h>
61 #include <mono/utils/mono-compiler.h>
62 #include <mono/utils/mono-time.h>
63 #include <mono/utils/mono-mmap.h>
66 #include "image-writer.h"
67 #include "dwarfwriter.h"
70 #if !defined(DISABLE_AOT) && !defined(DISABLE_JIT)
72 #if defined(__linux__) || defined(__native_client_codegen__)
73 #define RODATA_SECT ".rodata"
75 #define RODATA_SECT ".text"
78 #define TV_DECLARE(name) gint64 name
79 #define TV_GETTIME(tv) tv = mono_100ns_ticks ()
80 #define TV_ELAPSED(start,end) (((end) - (start)) / 10)
83 #define SHARED_EXT ".dll"
84 #elif defined(__ppc__) && defined(TARGET_MACH)
85 #define SHARED_EXT ".dylib"
86 #elif defined(TARGET_MACH) && defined(TARGET_X86) && !defined(__native_client_codegen__)
87 #define SHARED_EXT ".dylib"
89 #define SHARED_EXT ".so"
92 #define ALIGN_TO(val,align) ((((guint64)val) + ((align) - 1)) & ~((align) - 1))
93 #define ALIGN_PTR_TO(ptr,align) (gpointer)((((gssize)(ptr)) + (align - 1)) & (~(align - 1)))
94 #define ROUND_DOWN(VALUE,SIZE) ((VALUE) & ~((SIZE) - 1))
96 /* predefined values for static readonly fields without needed to run the .cctor */
97 typedef struct _ReadOnlyValue ReadOnlyValue;
98 struct _ReadOnlyValue {
101 int type; /* to be used later for typechecking to prevent user errors */
110 static ReadOnlyValue *readonly_values = NULL;
112 typedef struct MonoAotOptions {
115 gboolean write_symbols;
116 gboolean metadata_only;
117 gboolean bind_to_runtime_version;
120 gboolean static_link;
125 gboolean log_generics;
126 gboolean direct_pinvoke;
127 gboolean direct_icalls;
128 gboolean no_direct_calls;
131 int nrgctx_trampolines;
132 int nimt_trampolines;
133 gboolean print_skipped_methods;
141 typedef struct MonoAotStats {
142 int ccount, mcount, lmfcount, abscount, gcount, ocount, genericcount;
143 int code_size, info_size, ex_info_size, unwind_info_size, got_size, class_info_size, got_info_size;
144 int methods_without_got_slots, direct_calls, all_calls, llvm_count;
145 int got_slots, offsets_size;
146 int got_slot_types [MONO_PATCH_INFO_NONE];
147 int got_slot_info_sizes [MONO_PATCH_INFO_NONE];
148 int jit_time, gen_time, link_time;
151 typedef struct MonoAotCompile {
154 GHashTable *method_indexes;
155 GHashTable *method_depth;
158 GHashTable *patch_to_plt_entry;
159 GHashTable *plt_offset_to_entry;
160 GHashTable *patch_to_got_offset;
161 GHashTable **patch_to_got_offset_by_type;
162 GPtrArray *got_patches;
163 GHashTable *image_hash;
164 GHashTable *method_to_cfg;
165 GHashTable *token_info_hash;
166 GHashTable *method_to_pinvoke_import;
167 GPtrArray *extra_methods;
168 GPtrArray *image_table;
170 GPtrArray *method_order;
171 GHashTable *export_names;
172 /* Maps MonoClass* -> blob offset */
173 GHashTable *klass_blob_hash;
174 /* Maps MonoMethod* -> blob offset */
175 GHashTable *method_blob_hash;
176 guint32 *plt_got_info_offsets;
177 guint32 got_offset, plt_offset, plt_got_offset_base;
178 guint32 final_got_size;
179 /* Number of GOT entries reserved for trampolines */
180 guint32 num_trampoline_got_entries;
182 guint32 num_trampolines [MONO_AOT_TRAMP_NUM];
183 guint32 trampoline_got_offset_base [MONO_AOT_TRAMP_NUM];
184 guint32 trampoline_size [MONO_AOT_TRAMP_NUM];
186 MonoAotOptions aot_opts;
190 MonoMemPool *mempool;
193 char *static_linking_symbol;
194 CRITICAL_SECTION mutex;
195 gboolean use_bin_writer;
197 MonoDwarfWriter *dwarf;
201 GHashTable *unwind_info_offsets;
202 GPtrArray *unwind_ops;
203 guint32 unwind_info_offset;
204 char *got_symbol_base;
207 GHashTable *method_label_hash;
208 const char *temp_prefix;
209 const char *llvm_label_prefix;
210 guint32 label_generator;
212 MonoAotFileFlags flags;
213 MonoDynamicStream blob;
214 MonoClass **typespec_classes;
217 char *assembly_name_sym;
218 GHashTable *plt_entry_debug_sym_cache;
219 gboolean thumb_mixed, need_no_dead_strip, need_pt_gnu_stack;
220 GHashTable *ginst_hash;
221 gboolean global_symbols;
223 gboolean direct_method_addresses;
229 char *symbol, *llvm_symbol, *debug_sym;
231 gboolean jit_used, llvm_used;
234 #define mono_acfg_lock(acfg) EnterCriticalSection (&((acfg)->mutex))
235 #define mono_acfg_unlock(acfg) LeaveCriticalSection (&((acfg)->mutex))
237 /* This points to the current acfg in LLVM mode */
238 static MonoAotCompile *llvm_acfg;
240 #ifdef HAVE_ARRAY_ELEM_INIT
241 #define MSGSTRFIELD(line) MSGSTRFIELD1(line)
242 #define MSGSTRFIELD1(line) str##line
243 static const struct msgstr_t {
244 #define PATCH_INFO(a,b) char MSGSTRFIELD(__LINE__) [sizeof (b)];
245 #include "patch-info.h"
248 #define PATCH_INFO(a,b) b,
249 #include "patch-info.h"
252 static const gint16 opidx [] = {
253 #define PATCH_INFO(a,b) [MONO_PATCH_INFO_ ## a] = offsetof (struct msgstr_t, MSGSTRFIELD(__LINE__)),
254 #include "patch-info.h"
258 static G_GNUC_UNUSED const char*
259 get_patch_name (int info)
261 return (const char*)&opstr + opidx [info];
265 #define PATCH_INFO(a,b) b,
266 static const char* const
267 patch_types [MONO_PATCH_INFO_NUM + 1] = {
268 #include "patch-info.h"
272 static G_GNUC_UNUSED const char*
273 get_patch_name (int info)
275 return patch_types [info];
281 get_plt_entry_debug_sym (MonoAotCompile *acfg, MonoJumpInfo *ji, GHashTable *cache);
283 /* Wrappers around the image writer functions */
286 emit_section_change (MonoAotCompile *acfg, const char *section_name, int subsection_index)
288 img_writer_emit_section_change (acfg->w, section_name, subsection_index);
292 emit_push_section (MonoAotCompile *acfg, const char *section_name, int subsection)
294 img_writer_emit_push_section (acfg->w, section_name, subsection);
298 emit_pop_section (MonoAotCompile *acfg)
300 img_writer_emit_pop_section (acfg->w);
304 emit_local_symbol (MonoAotCompile *acfg, const char *name, const char *end_label, gboolean func)
306 img_writer_emit_local_symbol (acfg->w, name, end_label, func);
310 emit_label (MonoAotCompile *acfg, const char *name)
312 img_writer_emit_label (acfg->w, name);
316 emit_bytes (MonoAotCompile *acfg, const guint8* buf, int size)
318 img_writer_emit_bytes (acfg->w, buf, size);
322 emit_string (MonoAotCompile *acfg, const char *value)
324 img_writer_emit_string (acfg->w, value);
328 emit_line (MonoAotCompile *acfg)
330 img_writer_emit_line (acfg->w);
334 emit_alignment (MonoAotCompile *acfg, int size)
336 img_writer_emit_alignment (acfg->w, size);
340 emit_pointer_unaligned (MonoAotCompile *acfg, const char *target)
342 img_writer_emit_pointer_unaligned (acfg->w, target);
346 emit_pointer (MonoAotCompile *acfg, const char *target)
348 img_writer_emit_pointer (acfg->w, target);
352 emit_int16 (MonoAotCompile *acfg, int value)
354 img_writer_emit_int16 (acfg->w, value);
358 emit_int32 (MonoAotCompile *acfg, int value)
360 img_writer_emit_int32 (acfg->w, value);
364 emit_symbol_diff (MonoAotCompile *acfg, const char *end, const char* start, int offset)
366 img_writer_emit_symbol_diff (acfg->w, end, start, offset);
370 emit_zero_bytes (MonoAotCompile *acfg, int num)
372 img_writer_emit_zero_bytes (acfg->w, num);
376 emit_byte (MonoAotCompile *acfg, guint8 val)
378 img_writer_emit_byte (acfg->w, val);
381 #ifdef __native_client_codegen__
383 emit_nacl_call_alignment (MonoAotCompile *acfg)
385 img_writer_emit_nacl_call_alignment (acfg->w);
389 static G_GNUC_UNUSED void
390 emit_global_inner (MonoAotCompile *acfg, const char *name, gboolean func)
392 img_writer_emit_global (acfg->w, name, func);
396 emit_global (MonoAotCompile *acfg, const char *name, gboolean func)
398 if (acfg->aot_opts.no_dlsym) {
399 g_ptr_array_add (acfg->globals, g_strdup (name));
400 img_writer_emit_local_symbol (acfg->w, name, NULL, func);
402 img_writer_emit_global (acfg->w, name, func);
407 emit_symbol_size (MonoAotCompile *acfg, const char *name, const char *end_label)
409 img_writer_emit_symbol_size (acfg->w, name, end_label);
413 emit_string_symbol (MonoAotCompile *acfg, const char *name, const char *value)
415 img_writer_emit_section_change (acfg->w, RODATA_SECT, 1);
417 /* On apple, all symbols need to be aligned to avoid warnings from ld */
418 emit_alignment (acfg, 4);
420 img_writer_emit_label (acfg->w, name);
421 img_writer_emit_string (acfg->w, value);
424 static G_GNUC_UNUSED void
425 emit_uleb128 (MonoAotCompile *acfg, guint32 value)
428 guint8 b = value & 0x7f;
430 if (value != 0) /* more bytes to come */
436 static G_GNUC_UNUSED void
437 emit_sleb128 (MonoAotCompile *acfg, gint64 value)
440 gboolean negative = (value < 0);
447 /* the following is unnecessary if the
448 * implementation of >>= uses an arithmetic rather
449 * than logical shift for a signed left operand
453 value |= - ((gint64)1 <<(size - 7));
454 /* sign bit of byte is second high order bit (0x40) */
455 if ((value == 0 && !(byte & 0x40)) ||
456 (value == -1 && (byte & 0x40)))
460 emit_byte (acfg, byte);
464 static G_GNUC_UNUSED void
465 encode_uleb128 (guint32 value, guint8 *buf, guint8 **endbuf)
470 guint8 b = value & 0x7f;
472 if (value != 0) /* more bytes to come */
480 static G_GNUC_UNUSED void
481 encode_sleb128 (gint32 value, guint8 *buf, guint8 **endbuf)
484 gboolean negative = (value < 0);
492 /* the following is unnecessary if the
493 * implementation of >>= uses an arithmetic rather
494 * than logical shift for a signed left operand
498 value |= - (1 <<(size - 7));
499 /* sign bit of byte is second high order bit (0x40) */
500 if ((value == 0 && !(byte & 0x40)) ||
501 (value == -1 && (byte & 0x40)))
511 /* ARCHITECTURE SPECIFIC CODE */
513 #if defined(TARGET_X86) || defined(TARGET_AMD64) || defined(TARGET_ARM) || defined(TARGET_POWERPC)
514 #define EMIT_DWARF_INFO 1
517 #if defined(TARGET_ARM)
518 #define AOT_FUNC_ALIGNMENT 4
520 #define AOT_FUNC_ALIGNMENT 16
522 #if (defined(TARGET_X86) || defined(TARGET_AMD64)) && defined(__native_client_codegen__)
523 #undef AOT_FUNC_ALIGNMENT
524 #define AOT_FUNC_ALIGNMENT 32
527 #if defined(TARGET_POWERPC64) && !defined(__mono_ilp32__)
528 #define PPC_LD_OP "ld"
529 #define PPC_LDX_OP "ldx"
531 #define PPC_LD_OP "lwz"
532 #define PPC_LDX_OP "lwzx"
536 #define AOT_TARGET_STR "AMD64"
541 #define AOT_TARGET_STR "ARM (MACH)"
543 #define AOT_TARGET_STR "ARM (!MACH)"
547 #ifdef TARGET_POWERPC64
548 #ifdef __mono_ilp32__
549 #define AOT_TARGET_STR "POWERPC64 (mono ilp32)"
551 #define AOT_TARGET_STR "POWERPC64 (!mono ilp32)"
554 #ifdef TARGET_POWERPC
555 #ifdef __mono_ilp32__
556 #define AOT_TARGET_STR "POWERPC (mono ilp32)"
558 #define AOT_TARGET_STR "POWERPC (!mono ilp32)"
565 #define AOT_TARGET_STR "X86 (WIN32)"
566 #elif defined(__native_client_codegen__)
567 #define AOT_TARGET_STR "X86 (native client codegen)"
569 #define AOT_TARGET_STR "X86 (!native client codegen)"
573 #ifndef AOT_TARGET_STR
574 #define AOT_TARGET_STR ""
578 arch_init (MonoAotCompile *acfg)
580 acfg->llc_args = g_string_new ("");
581 acfg->as_args = g_string_new ("");
584 * The prefix LLVM likes to put in front of symbol names on darwin.
585 * The mach-os specs require this for globals, but LLVM puts them in front of all
586 * symbols. We need to handle this, since we need to refer to LLVM generated
589 acfg->llvm_label_prefix = "";
592 if (acfg->aot_opts.mtriple && strstr (acfg->aot_opts.mtriple, "darwin")) {
593 g_string_append (acfg->llc_args, "-mattr=+v6");
596 g_string_append (acfg->llc_args, " -mattr=+vfp2,-neon,+d16");
597 g_string_append (acfg->as_args, " -mfpu=vfp3");
599 g_string_append (acfg->llc_args, " -soft-float");
602 if (acfg->aot_opts.mtriple && strstr (acfg->aot_opts.mtriple, "thumb"))
603 acfg->thumb_mixed = TRUE;
605 if (acfg->aot_opts.mtriple)
606 mono_arch_set_target (acfg->aot_opts.mtriple);
610 acfg->llvm_label_prefix = "_";
611 acfg->need_no_dead_strip = TRUE;
614 #if defined(__linux__) && !defined(TARGET_ARM)
615 acfg->need_pt_gnu_stack = TRUE;
619 acfg->direct_method_addresses = TRUE;
620 acfg->global_symbols = TRUE;
625 * arch_emit_direct_call:
627 * Emit a direct call to the symbol TARGET. CALL_SIZE is set to the size of the
631 arch_emit_direct_call (MonoAotCompile *acfg, const char *target, int *call_size)
633 #if defined(TARGET_X86) || defined(TARGET_AMD64)
634 /* Need to make sure this is exactly 5 bytes long */
635 if (FALSE && !acfg->use_bin_writer) {
636 img_writer_emit_unset_mode (acfg->w);
637 fprintf (acfg->fp, "call %s\n", target);
639 emit_byte (acfg, '\xe8');
640 emit_symbol_diff (acfg, target, ".", -4);
643 #elif defined(TARGET_ARM)
644 if (acfg->use_bin_writer) {
651 img_writer_emit_reloc (acfg->w, R_ARM_CALL, target, -8);
652 emit_bytes (acfg, buf, 4);
654 img_writer_emit_unset_mode (acfg->w);
655 fprintf (acfg->fp, "bl %s\n", target);
658 #elif defined(TARGET_POWERPC)
659 if (acfg->use_bin_writer) {
660 g_assert_not_reached ();
662 img_writer_emit_unset_mode (acfg->w);
663 fprintf (acfg->fp, "bl %s\n", target);
667 g_assert_not_reached ();
673 * - we use an approach similar to the x86 abi: reserve a register (r30) to hold
675 * - The full-aot trampolines need access to the GOT of mscorlib, so we store
676 * in in the 2. slot of every GOT, and require every method to place the GOT
677 * address in r30, even when it doesn't access the GOT otherwise. This way,
678 * the trampolines can compute the mscorlib GOT address by loading 4(r30).
683 * PPC64 uses function descriptors which greatly complicate all code, since
684 * these are used very inconsistently in the runtime. Some functions like
685 * mono_compile_method () return ftn descriptors, while others like the
686 * trampoline creation functions do not.
687 * We assume that all GOT slots contain function descriptors, and create
688 * descriptors in aot-runtime.c when needed.
689 * The ppc64 abi uses r2 to hold the address of the TOC/GOT, which is loaded
690 * from function descriptors, we could do the same, but it would require
691 * rewriting all the ppc/aot code to handle function descriptors properly.
692 * So instead, we use the same approach as on PPC32.
693 * This is a horrible mess, but fixing it would probably lead to an even bigger
699 * - similar to the PPC32 design, we reserve EBX to hold the GOT pointer.
702 #ifdef MONO_ARCH_AOT_SUPPORTED
704 * arch_emit_got_offset:
706 * The memory pointed to by CODE should hold native code for computing the GOT
707 * address. Emit this code while patching it with the offset between code and
708 * the GOT. CODE_SIZE is set to the number of bytes emitted.
711 arch_emit_got_offset (MonoAotCompile *acfg, guint8 *code, int *code_size)
713 #if defined(TARGET_POWERPC64)
714 g_assert (!acfg->use_bin_writer);
715 img_writer_emit_unset_mode (acfg->w);
717 * The ppc32 code doesn't seem to work on ppc64, the assembler complains about
718 * unsupported relocations. So we store the got address into the .Lgot_addr
719 * symbol which is in the text segment, compute its address, and load it.
721 fprintf (acfg->fp, ".L%d:\n", acfg->label_generator);
722 fprintf (acfg->fp, "lis 0, (.Lgot_addr + 4 - .L%d)@h\n", acfg->label_generator);
723 fprintf (acfg->fp, "ori 0, 0, (.Lgot_addr + 4 - .L%d)@l\n", acfg->label_generator);
724 fprintf (acfg->fp, "add 30, 30, 0\n");
725 fprintf (acfg->fp, "%s 30, 0(30)\n", PPC_LD_OP);
726 acfg->label_generator ++;
728 #elif defined(TARGET_POWERPC)
729 g_assert (!acfg->use_bin_writer);
730 img_writer_emit_unset_mode (acfg->w);
731 fprintf (acfg->fp, ".L%d:\n", acfg->label_generator);
732 fprintf (acfg->fp, "lis 0, (%s + 4 - .L%d)@h\n", acfg->got_symbol, acfg->label_generator);
733 fprintf (acfg->fp, "ori 0, 0, (%s + 4 - .L%d)@l\n", acfg->got_symbol, acfg->label_generator);
734 acfg->label_generator ++;
737 guint32 offset = mono_arch_get_patch_offset (code);
738 emit_bytes (acfg, code, offset);
739 emit_symbol_diff (acfg, acfg->got_symbol, ".", offset);
741 *code_size = offset + 4;
746 * arch_emit_got_access:
748 * The memory pointed to by CODE should hold native code for loading a GOT
749 * slot. Emit this code while patching it so it accesses the GOT slot GOT_SLOT.
750 * CODE_SIZE is set to the number of bytes emitted.
753 arch_emit_got_access (MonoAotCompile *acfg, guint8 *code, int got_slot, int *code_size)
755 /* Emit beginning of instruction */
756 emit_bytes (acfg, code, mono_arch_get_patch_offset (code));
758 /* Emit the offset */
760 emit_symbol_diff (acfg, acfg->got_symbol, ".", (unsigned int) ((got_slot * sizeof (gpointer)) - 4));
761 *code_size = mono_arch_get_patch_offset (code) + 4;
762 #elif defined(TARGET_X86)
763 emit_int32 (acfg, (unsigned int) ((got_slot * sizeof (gpointer))));
764 *code_size = mono_arch_get_patch_offset (code) + 4;
765 #elif defined(TARGET_ARM)
766 emit_symbol_diff (acfg, acfg->got_symbol, ".", (unsigned int) ((got_slot * sizeof (gpointer))) - 12);
767 *code_size = mono_arch_get_patch_offset (code) + 4;
768 #elif defined(TARGET_POWERPC)
774 ppc_load32 (code, ppc_r0, got_slot * sizeof (gpointer));
775 g_assert (code - buf == 8);
776 emit_bytes (acfg, buf, code - buf);
777 *code_size = code - buf;
780 g_assert_not_reached ();
787 * arch_emit_plt_entry:
789 * Emit code for the PLT entry with index INDEX.
792 arch_emit_plt_entry (MonoAotCompile *acfg, int index)
794 #if defined(TARGET_X86)
795 guint32 offset = (acfg->plt_got_offset_base + index) * sizeof (gpointer);
796 #if defined(__default_codegen__)
797 /* jmp *<offset>(%ebx) */
798 emit_byte (acfg, 0xff);
799 emit_byte (acfg, 0xa3);
800 emit_int32 (acfg, offset);
801 /* Used by mono_aot_get_plt_info_offset */
802 emit_int32 (acfg, acfg->plt_got_info_offsets [index]);
803 #elif defined(__native_client_codegen__)
804 const guint8 kSizeOfNaClJmp = 11;
805 guint8 bytes[kSizeOfNaClJmp];
806 guint8 *pbytes = &bytes[0];
808 x86_jump_membase32 (pbytes, X86_EBX, offset);
809 emit_bytes (acfg, bytes, kSizeOfNaClJmp);
810 /* four bytes of data, used by mono_arch_patch_plt_entry */
811 /* For Native Client, make this work with data embedded in push. */
812 emit_byte (acfg, 0x68); /* hide data in a push */
813 emit_int32 (acfg, acfg->plt_got_info_offsets [index]);
814 emit_alignment (acfg, AOT_FUNC_ALIGNMENT);
815 #endif /*__native_client_codegen__*/
816 #elif defined(TARGET_AMD64)
817 #if defined(__default_codegen__)
819 * We can't emit jumps because they are 32 bits only so they can't be patched.
820 * So we make indirect calls through GOT entries which are patched by the AOT
821 * loader to point to .Lpd entries.
823 /* jmpq *<offset>(%rip) */
824 emit_byte (acfg, '\xff');
825 emit_byte (acfg, '\x25');
826 emit_symbol_diff (acfg, acfg->got_symbol, ".", ((acfg->plt_got_offset_base + index) * sizeof (gpointer)) -4);
827 /* Used by mono_aot_get_plt_info_offset */
828 emit_int32 (acfg, acfg->plt_got_info_offsets [index]);
829 #elif defined(__native_client_codegen__)
831 guint8 *buf_aligned = ALIGN_TO(buf, kNaClAlignment);
832 guint8 *code = buf_aligned;
834 /* mov <OFFSET>(%rip), %r11d */
835 emit_byte (acfg, '\x45');
836 emit_byte (acfg, '\x8b');
837 emit_byte (acfg, '\x1d');
838 emit_symbol_diff (acfg, acfg->got_symbol, ".", ((acfg->plt_got_offset_base + index) * sizeof (gpointer)) -4);
840 amd64_jump_reg (code, AMD64_R11);
841 /* This should be constant for the plt patch */
842 g_assert ((size_t)(code-buf_aligned) == 10);
843 emit_bytes (acfg, buf_aligned, code - buf_aligned);
845 /* Hide data in a push imm32 so it passes validation */
846 emit_byte (acfg, 0x68); /* push */
847 emit_int32 (acfg, acfg->plt_got_info_offsets [index]);
848 emit_alignment (acfg, AOT_FUNC_ALIGNMENT);
849 #endif /*__native_client_codegen__*/
850 #elif defined(TARGET_ARM)
855 ARM_LDR_IMM (code, ARMREG_IP, ARMREG_PC, 0);
856 ARM_LDR_REG_REG (code, ARMREG_PC, ARMREG_PC, ARMREG_IP);
857 emit_bytes (acfg, buf, code - buf);
858 emit_symbol_diff (acfg, acfg->got_symbol, ".", ((acfg->plt_got_offset_base + index) * sizeof (gpointer)) - 4);
859 /* Used by mono_aot_get_plt_info_offset */
860 emit_int32 (acfg, acfg->plt_got_info_offsets [index]);
861 #elif defined(TARGET_POWERPC)
862 guint32 offset = (acfg->plt_got_offset_base + index) * sizeof (gpointer);
864 /* The GOT address is guaranteed to be in r30 by OP_LOAD_GOTADDR */
865 g_assert (!acfg->use_bin_writer);
866 img_writer_emit_unset_mode (acfg->w);
867 fprintf (acfg->fp, "lis 11, %d@h\n", offset);
868 fprintf (acfg->fp, "ori 11, 11, %d@l\n", offset);
869 fprintf (acfg->fp, "add 11, 11, 30\n");
870 fprintf (acfg->fp, "%s 11, 0(11)\n", PPC_LD_OP);
871 #ifdef PPC_USES_FUNCTION_DESCRIPTOR
872 fprintf (acfg->fp, "%s 2, %d(11)\n", PPC_LD_OP, (int)sizeof (gpointer));
873 fprintf (acfg->fp, "%s 11, 0(11)\n", PPC_LD_OP);
875 fprintf (acfg->fp, "mtctr 11\n");
876 fprintf (acfg->fp, "bctr\n");
877 emit_int32 (acfg, acfg->plt_got_info_offsets [index]);
879 g_assert_not_reached ();
884 arch_emit_llvm_plt_entry (MonoAotCompile *acfg, int index)
886 #if defined(TARGET_ARM)
888 /* LLVM calls the PLT entries using bl, so emit a stub */
889 /* FIXME: Too much overhead on every call */
890 fprintf (acfg->fp, ".thumb_func\n");
891 fprintf (acfg->fp, "bx pc\n");
892 fprintf (acfg->fp, "nop\n");
893 fprintf (acfg->fp, ".arm\n");
895 /* LLVM calls the PLT entries using bl, so these have to be thumb2 */
896 /* The caller already transitioned to thumb */
897 /* The code below should be 12 bytes long */
898 fprintf (acfg->fp, "ldr ip, [pc, #8]\n");
899 /* thumb can't encode ld pc, [pc, ip] */
900 fprintf (acfg->fp, "add ip, pc, ip\n");
901 fprintf (acfg->fp, "ldr ip, [ip, #0]\n");
902 fprintf (acfg->fp, "bx ip\n");
903 emit_symbol_diff (acfg, acfg->got_symbol, ".", ((acfg->plt_got_offset_base + index) * sizeof (gpointer)) + 4);
904 emit_int32 (acfg, acfg->plt_got_info_offsets [index]);
906 g_assert_not_reached ();
911 * arch_emit_specific_trampoline:
913 * Emit code for a specific trampoline. OFFSET is the offset of the first of
914 * two GOT slots which contain the generic trampoline address and the trampoline
915 * argument. TRAMP_SIZE is set to the size of the emitted trampoline.
918 arch_emit_specific_trampoline (MonoAotCompile *acfg, int offset, int *tramp_size)
921 * The trampolines created here are variations of the specific
922 * trampolines created in mono_arch_create_specific_trampoline (). The
924 * - the generic trampoline address is taken from a got slot.
925 * - the offset of the got slot where the trampoline argument is stored
926 * is embedded in the instruction stream, and the generic trampoline
927 * can load the argument by loading the offset, adding it to the
928 * address of the trampoline to get the address of the got slot, and
929 * loading the argument from there.
930 * - all the trampolines should be of the same length.
932 #if defined(TARGET_AMD64)
933 #if defined(__default_codegen__)
934 /* This should be exactly 16 bytes long */
936 /* call *<offset>(%rip) */
937 emit_byte (acfg, '\x41');
938 emit_byte (acfg, '\xff');
939 emit_byte (acfg, '\x15');
940 emit_symbol_diff (acfg, acfg->got_symbol, ".", (offset * sizeof (gpointer)) - 4);
941 /* This should be relative to the start of the trampoline */
942 emit_symbol_diff (acfg, acfg->got_symbol, ".", ((offset+1) * sizeof (gpointer)) + 7);
943 emit_zero_bytes (acfg, 5);
944 #elif defined(__native_client_codegen__)
946 guint8 *buf_aligned = ALIGN_TO(buf, kNaClAlignment);
947 guint8 *code = buf_aligned;
952 /* Emit this call in 'code' so we can find out how long it is. */
953 amd64_call_reg (code, AMD64_R11);
954 call_start = mono_arch_nacl_skip_nops (buf_aligned);
955 call_len = code - call_start;
957 /* The tramp_size is twice the NaCl alignment because it starts with */
958 /* a call which needs to be aligned to the end of the boundary. */
959 *tramp_size = kNaClAlignment*2;
961 /* Emit nops to align call site below which is 7 bytes plus */
962 /* the length of the call sequence emitted above. */
963 /* Note: this requires the specific trampoline starts on a */
964 /* kNaclAlignedment aligned address, which it does because */
965 /* it's its own function that is aligned. */
967 guint8 *nopbuf_aligned = ALIGN_TO (nop_buf, kNaClAlignment);
968 guint8 *nopbuf_end = mono_arch_nacl_pad (nopbuf_aligned, kNaClAlignment - 7 - (call_len));
969 emit_bytes (acfg, nopbuf_aligned, nopbuf_end - nopbuf_aligned);
971 /* The trampoline is stored at the offset'th pointer, the -4 is */
972 /* present because RIP relative addressing starts at the end of */
973 /* the current instruction, while the label "." is relative to */
974 /* the beginning of the current asm location, which in this case */
975 /* is not the mov instruction, but the offset itself, due to the */
976 /* way the bytes and ints are emitted here. */
977 got_offset = (offset * sizeof(gpointer)) - 4;
979 /* mov <OFFSET>(%rip), %r11d */
980 emit_byte (acfg, '\x45');
981 emit_byte (acfg, '\x8b');
982 emit_byte (acfg, '\x1d');
983 emit_symbol_diff (acfg, acfg->got_symbol, ".", got_offset);
986 emit_bytes (acfg, call_start, call_len);
988 /* The arg is stored at the offset+1 pointer, relative to beginning */
989 /* of trampoline: 7 for mov, plus the call length, and 1 for push. */
990 got_offset = ((offset + 1) * sizeof(gpointer)) + 7 + call_len + 1;
992 /* We can't emit this data directly, hide in a "push imm32" */
993 emit_byte (acfg, '\x68'); /* push */
994 emit_symbol_diff (acfg, acfg->got_symbol, ".", got_offset);
995 emit_alignment (acfg, kNaClAlignment);
996 #endif /*__native_client_codegen__*/
997 #elif defined(TARGET_ARM)
1001 /* This should be exactly 20 bytes long */
1004 ARM_PUSH (code, 0x5fff);
1005 ARM_LDR_IMM (code, ARMREG_R1, ARMREG_PC, 4);
1006 /* Load the value from the GOT */
1007 ARM_LDR_REG_REG (code, ARMREG_R1, ARMREG_PC, ARMREG_R1);
1009 ARM_BLX_REG (code, ARMREG_R1);
1011 g_assert (code - buf == 16);
1014 emit_bytes (acfg, buf, code - buf);
1016 * Only one offset is needed, since the second one would be equal to the
1019 emit_symbol_diff (acfg, acfg->got_symbol, ".", (offset * sizeof (gpointer)) - 4 + 4);
1020 //emit_symbol_diff (acfg, acfg->got_symbol, ".", ((offset + 1) * sizeof (gpointer)) - 4 + 8);
1021 #elif defined(TARGET_POWERPC)
1028 g_assert (!acfg->use_bin_writer);
1031 * PPC has no ip relative addressing, so we need to compute the address
1032 * of the mscorlib got. That is slow and complex, so instead, we store it
1033 * in the second got slot of every aot image. The caller already computed
1034 * the address of its got and placed it into r30.
1036 img_writer_emit_unset_mode (acfg->w);
1037 /* Load mscorlib got address */
1038 fprintf (acfg->fp, "%s 0, %d(30)\n", PPC_LD_OP, (int)sizeof (gpointer));
1039 /* Load generic trampoline address */
1040 fprintf (acfg->fp, "lis 11, %d@h\n", (int)(offset * sizeof (gpointer)));
1041 fprintf (acfg->fp, "ori 11, 11, %d@l\n", (int)(offset * sizeof (gpointer)));
1042 fprintf (acfg->fp, "%s 11, 11, 0\n", PPC_LDX_OP);
1043 #ifdef PPC_USES_FUNCTION_DESCRIPTOR
1044 fprintf (acfg->fp, "%s 11, 0(11)\n", PPC_LD_OP);
1046 fprintf (acfg->fp, "mtctr 11\n");
1047 /* Load trampoline argument */
1048 /* On ppc, we pass it normally to the generic trampoline */
1049 fprintf (acfg->fp, "lis 11, %d@h\n", (int)((offset + 1) * sizeof (gpointer)));
1050 fprintf (acfg->fp, "ori 11, 11, %d@l\n", (int)((offset + 1) * sizeof (gpointer)));
1051 fprintf (acfg->fp, "%s 0, 11, 0\n", PPC_LDX_OP);
1052 /* Branch to generic trampoline */
1053 fprintf (acfg->fp, "bctr\n");
1055 #ifdef PPC_USES_FUNCTION_DESCRIPTOR
1056 *tramp_size = 10 * 4;
1058 *tramp_size = 9 * 4;
1060 #elif defined(TARGET_X86)
1064 /* Similar to the PPC code above */
1066 /* FIXME: Could this clobber the register needed by get_vcall_slot () ? */
1068 /* We clobber ECX, since EAX is used as MONO_ARCH_MONITOR_OBJECT_REG */
1069 #ifdef MONO_ARCH_MONITOR_OBJECT_REG
1070 g_assert (MONO_ARCH_MONITOR_OBJECT_REG != X86_ECX);
1074 /* Load mscorlib got address */
1075 x86_mov_reg_membase (code, X86_ECX, MONO_ARCH_GOT_REG, sizeof (gpointer), 4);
1076 /* Push trampoline argument */
1077 x86_push_membase (code, X86_ECX, (offset + 1) * sizeof (gpointer));
1078 /* Load generic trampoline address */
1079 x86_mov_reg_membase (code, X86_ECX, X86_ECX, offset * sizeof (gpointer), 4);
1080 /* Branch to generic trampoline */
1081 x86_jump_reg (code, X86_ECX);
1083 #ifdef __native_client_codegen__
1085 /* emit nops to next 32 byte alignment */
1086 int a = (~kNaClAlignmentMask) & ((code - buf) + kNaClAlignment - 1);
1087 while (code < (buf + a)) x86_nop(code);
1090 emit_bytes (acfg, buf, code - buf);
1092 *tramp_size = NACL_SIZE(17, kNaClAlignment);
1093 g_assert (code - buf == *tramp_size);
1095 g_assert_not_reached ();
1100 * arch_emit_unbox_trampoline:
1102 * Emit code for the unbox trampoline for METHOD used in the full-aot case.
1103 * CALL_TARGET is the symbol pointing to the native code of METHOD.
1106 arch_emit_unbox_trampoline (MonoAotCompile *acfg, MonoCompile *cfg, MonoMethod *method, const char *call_target)
1108 #if defined(TARGET_AMD64)
1113 this_reg = mono_arch_get_this_arg_reg (NULL);
1115 amd64_alu_reg_imm (code, X86_ADD, this_reg, sizeof (MonoObject));
1117 emit_bytes (acfg, buf, code - buf);
1119 emit_byte (acfg, '\xe9');
1120 emit_symbol_diff (acfg, call_target, ".", -4);
1121 #elif defined(TARGET_X86)
1128 x86_alu_membase_imm (code, X86_ADD, X86_ESP, this_pos, sizeof (MonoObject));
1130 emit_bytes (acfg, buf, code - buf);
1133 emit_byte (acfg, '\xe9');
1134 emit_symbol_diff (acfg, call_target, ".", -4);
1135 #elif defined(TARGET_ARM)
1139 if (acfg->thumb_mixed && cfg->compile_llvm) {
1140 fprintf (acfg->fp, "add r0, r0, #%d\n", sizeof (MonoObject));
1141 fprintf (acfg->fp, "b %s\n", call_target);
1142 fprintf (acfg->fp, ".arm\n");
1148 ARM_ADD_REG_IMM8 (code, ARMREG_R0, ARMREG_R0, sizeof (MonoObject));
1150 emit_bytes (acfg, buf, code - buf);
1151 /* jump to method */
1152 if (acfg->use_bin_writer) {
1159 img_writer_emit_reloc (acfg->w, R_ARM_JUMP24, call_target, -8);
1160 emit_bytes (acfg, buf, 4);
1162 if (acfg->thumb_mixed && cfg->compile_llvm)
1163 fprintf (acfg->fp, "\n\tbx %s\n", call_target);
1165 fprintf (acfg->fp, "\n\tb %s\n", call_target);
1167 #elif defined(TARGET_POWERPC)
1170 g_assert (!acfg->use_bin_writer);
1172 fprintf (acfg->fp, "\n\taddi %d, %d, %d\n", this_pos, this_pos, (int)sizeof (MonoObject));
1173 fprintf (acfg->fp, "\n\tb %s\n", call_target);
1175 g_assert_not_reached ();
1180 * arch_emit_static_rgctx_trampoline:
1182 * Emit code for a static rgctx trampoline. OFFSET is the offset of the first of
1183 * two GOT slots which contain the rgctx argument, and the method to jump to.
1184 * TRAMP_SIZE is set to the size of the emitted trampoline.
1185 * These kinds of trampolines cannot be enumerated statically, since there could
1186 * be one trampoline per method instantiation, so we emit the same code for all
1187 * trampolines, and parameterize them using two GOT slots.
1190 arch_emit_static_rgctx_trampoline (MonoAotCompile *acfg, int offset, int *tramp_size)
1192 #if defined(TARGET_AMD64)
1193 #if defined(__default_codegen__)
1194 /* This should be exactly 13 bytes long */
1197 /* mov <OFFSET>(%rip), %r10 */
1198 emit_byte (acfg, '\x4d');
1199 emit_byte (acfg, '\x8b');
1200 emit_byte (acfg, '\x15');
1201 emit_symbol_diff (acfg, acfg->got_symbol, ".", (offset * sizeof (gpointer)) - 4);
1203 /* jmp *<offset>(%rip) */
1204 emit_byte (acfg, '\xff');
1205 emit_byte (acfg, '\x25');
1206 emit_symbol_diff (acfg, acfg->got_symbol, ".", ((offset + 1) * sizeof (gpointer)) - 4);
1207 #elif defined(__native_client_codegen__)
1209 guint8 *buf_aligned = ALIGN_TO(buf, kNaClAlignment);
1210 guint8 *code = buf_aligned;
1212 /* mov <OFFSET>(%rip), %r10d */
1213 emit_byte (acfg, '\x45');
1214 emit_byte (acfg, '\x8b');
1215 emit_byte (acfg, '\x15');
1216 emit_symbol_diff (acfg, acfg->got_symbol, ".", (offset * sizeof (gpointer)) - 4);
1218 /* mov <OFFSET>(%rip), %r11d */
1219 emit_byte (acfg, '\x45');
1220 emit_byte (acfg, '\x8b');
1221 emit_byte (acfg, '\x1d');
1222 emit_symbol_diff (acfg, acfg->got_symbol, ".", ((offset + 1) * sizeof (gpointer)) - 4);
1225 amd64_jump_reg (code, AMD64_R11);
1226 emit_bytes (acfg, buf_aligned, code - buf_aligned);
1228 emit_alignment (acfg, kNaClAlignment);
1229 *tramp_size = kNaClAlignment;
1230 #endif /*__native_client_codegen__*/
1232 #elif defined(TARGET_ARM)
1236 /* This should be exactly 24 bytes long */
1239 /* Load rgctx value */
1240 ARM_LDR_IMM (code, ARMREG_IP, ARMREG_PC, 8);
1241 ARM_LDR_REG_REG (code, MONO_ARCH_RGCTX_REG, ARMREG_PC, ARMREG_IP);
1242 /* Load branch addr + branch */
1243 ARM_LDR_IMM (code, ARMREG_IP, ARMREG_PC, 4);
1244 ARM_LDR_REG_REG (code, ARMREG_PC, ARMREG_PC, ARMREG_IP);
1246 g_assert (code - buf == 16);
1249 emit_bytes (acfg, buf, code - buf);
1250 emit_symbol_diff (acfg, acfg->got_symbol, ".", (offset * sizeof (gpointer)) - 4 + 8);
1251 emit_symbol_diff (acfg, acfg->got_symbol, ".", ((offset + 1) * sizeof (gpointer)) - 4 + 4);
1252 #elif defined(TARGET_POWERPC)
1259 g_assert (!acfg->use_bin_writer);
1262 * PPC has no ip relative addressing, so we need to compute the address
1263 * of the mscorlib got. That is slow and complex, so instead, we store it
1264 * in the second got slot of every aot image. The caller already computed
1265 * the address of its got and placed it into r30.
1267 img_writer_emit_unset_mode (acfg->w);
1268 /* Load mscorlib got address */
1269 fprintf (acfg->fp, "%s 0, %d(30)\n", PPC_LD_OP, (int)sizeof (gpointer));
1271 fprintf (acfg->fp, "lis 11, %d@h\n", (int)(offset * sizeof (gpointer)));
1272 fprintf (acfg->fp, "ori 11, 11, %d@l\n", (int)(offset * sizeof (gpointer)));
1273 fprintf (acfg->fp, "%s %d, 11, 0\n", PPC_LDX_OP, MONO_ARCH_RGCTX_REG);
1274 /* Load target address */
1275 fprintf (acfg->fp, "lis 11, %d@h\n", (int)((offset + 1) * sizeof (gpointer)));
1276 fprintf (acfg->fp, "ori 11, 11, %d@l\n", (int)((offset + 1) * sizeof (gpointer)));
1277 fprintf (acfg->fp, "%s 11, 11, 0\n", PPC_LDX_OP);
1278 #ifdef PPC_USES_FUNCTION_DESCRIPTOR
1279 fprintf (acfg->fp, "%s 2, %d(11)\n", PPC_LD_OP, (int)sizeof (gpointer));
1280 fprintf (acfg->fp, "%s 11, 0(11)\n", PPC_LD_OP);
1282 fprintf (acfg->fp, "mtctr 11\n");
1283 /* Branch to the target address */
1284 fprintf (acfg->fp, "bctr\n");
1286 #ifdef PPC_USES_FUNCTION_DESCRIPTOR
1287 *tramp_size = 11 * 4;
1289 *tramp_size = 9 * 4;
1292 #elif defined(TARGET_X86)
1296 /* Similar to the PPC code above */
1298 g_assert (MONO_ARCH_RGCTX_REG != X86_ECX);
1301 /* Load mscorlib got address */
1302 x86_mov_reg_membase (code, X86_ECX, MONO_ARCH_GOT_REG, sizeof (gpointer), 4);
1304 x86_mov_reg_membase (code, MONO_ARCH_RGCTX_REG, X86_ECX, offset * sizeof (gpointer), 4);
1305 /* Branch to the target address */
1306 x86_jump_membase (code, X86_ECX, (offset + 1) * sizeof (gpointer));
1308 #ifdef __native_client_codegen__
1310 /* emit nops to next 32 byte alignment */
1311 int a = (~kNaClAlignmentMask) & ((code - buf) + kNaClAlignment - 1);
1312 while (code < (buf + a)) x86_nop(code);
1316 emit_bytes (acfg, buf, code - buf);
1318 *tramp_size = NACL_SIZE (15, kNaClAlignment);
1319 g_assert (code - buf == *tramp_size);
1321 g_assert_not_reached ();
1326 * arch_emit_imt_thunk:
1328 * Emit an IMT thunk usable in full-aot mode. The thunk uses 1 got slot which
1329 * points to an array of pointer pairs. The pairs of the form [key, ptr], where
1330 * key is the IMT key, and ptr holds the address of a memory location holding
1331 * the address to branch to if the IMT arg matches the key. The array is
1332 * terminated by a pair whose key is NULL, and whose ptr is the address of the
1334 * TRAMP_SIZE is set to the size of the emitted trampoline.
1337 arch_emit_imt_thunk (MonoAotCompile *acfg, int offset, int *tramp_size)
1339 #if defined(TARGET_AMD64)
1341 #if defined(__native_client_codegen__)
1344 guint8 *labels [16];
1346 guint8 *mov_buf_ptr = mov_buf;
1348 const int kSizeOfMove = 7;
1349 #if defined(__default_codegen__)
1350 code = buf = g_malloc (256);
1351 #elif defined(__native_client_codegen__)
1352 buf_alloc = g_malloc (256 + kNaClAlignment + kSizeOfMove);
1353 buf = ((guint)buf_alloc + kNaClAlignment) & ~kNaClAlignmentMask;
1354 /* The RIP relative move below is emitted first */
1359 /* FIXME: Optimize this, i.e. use binary search etc. */
1360 /* Maybe move the body into a separate function (slower, but much smaller) */
1362 /* MONO_ARCH_IMT_SCRATCH_REG is a free register */
1365 amd64_alu_membase_imm (code, X86_CMP, MONO_ARCH_IMT_SCRATCH_REG, 0, 0);
1367 amd64_branch8 (code, X86_CC_Z, 0, FALSE);
1370 amd64_alu_membase_reg_size (code, X86_CMP, MONO_ARCH_IMT_SCRATCH_REG, 0, MONO_ARCH_IMT_REG, sizeof (gpointer));
1372 amd64_branch8 (code, X86_CC_Z, 0, FALSE);
1375 amd64_alu_reg_imm (code, X86_ADD, MONO_ARCH_IMT_SCRATCH_REG, 2 * sizeof (gpointer));
1376 amd64_jump_code (code, labels [0]);
1379 mono_amd64_patch (labels [2], code);
1380 amd64_mov_reg_membase (code, MONO_ARCH_IMT_SCRATCH_REG, MONO_ARCH_IMT_SCRATCH_REG, sizeof (gpointer), sizeof (gpointer));
1381 amd64_jump_membase (code, MONO_ARCH_IMT_SCRATCH_REG, 0);
1384 mono_amd64_patch (labels [1], code);
1385 /* Load fail tramp */
1386 amd64_alu_reg_imm (code, X86_ADD, MONO_ARCH_IMT_SCRATCH_REG, sizeof (gpointer));
1387 /* Check if there is a fail tramp */
1388 amd64_alu_membase_imm (code, X86_CMP, MONO_ARCH_IMT_SCRATCH_REG, 0, 0);
1390 amd64_branch8 (code, X86_CC_Z, 0, FALSE);
1391 /* Jump to fail tramp */
1392 amd64_jump_membase (code, MONO_ARCH_IMT_SCRATCH_REG, 0);
1395 mono_amd64_patch (labels [3], code);
1396 x86_breakpoint (code);
1398 /* mov <OFFSET>(%rip), MONO_ARCH_IMT_SCRATCH_REG */
1399 amd64_emit_rex (mov_buf_ptr, sizeof(gpointer), MONO_ARCH_IMT_SCRATCH_REG, 0, AMD64_RIP);
1400 *(mov_buf_ptr)++ = (unsigned char)0x8b; /* mov opcode */
1401 x86_address_byte (mov_buf_ptr, 0, MONO_ARCH_IMT_SCRATCH_REG & 0x7, 5);
1402 emit_bytes (acfg, mov_buf, mov_buf_ptr - mov_buf);
1403 emit_symbol_diff (acfg, acfg->got_symbol, ".", (offset * sizeof (gpointer)) - 4);
1405 emit_bytes (acfg, buf, code - buf);
1407 *tramp_size = code - buf + kSizeOfMove;
1408 #if defined(__native_client_codegen__)
1409 /* The tramp will be padded to the next kNaClAlignment bundle. */
1410 *tramp_size = ALIGN_TO ((*tramp_size), kNaClAlignment);
1413 #if defined(__default_codegen__)
1415 #elif defined(__native_client_codegen__)
1419 #elif defined(TARGET_X86)
1421 #ifdef __native_client_codegen__
1424 guint8 *labels [16];
1426 #if defined(__default_codegen__)
1427 code = buf = g_malloc (256);
1428 #elif defined(__native_client_codegen__)
1429 buf_alloc = g_malloc (256 + kNaClAlignment);
1430 code = buf = ((guint)buf_alloc + kNaClAlignment) & ~kNaClAlignmentMask;
1433 /* Allocate a temporary stack slot */
1434 x86_push_reg (code, X86_EAX);
1436 x86_push_reg (code, X86_EAX);
1438 /* Load mscorlib got address */
1439 x86_mov_reg_membase (code, X86_EAX, MONO_ARCH_GOT_REG, sizeof (gpointer), 4);
1441 x86_mov_reg_membase (code, X86_EAX, X86_EAX, offset * sizeof (gpointer), 4);
1444 x86_alu_membase_imm (code, X86_CMP, X86_EAX, 0, 0);
1446 x86_branch8 (code, X86_CC_Z, FALSE, 0);
1449 x86_alu_membase_reg (code, X86_CMP, X86_EAX, 0, MONO_ARCH_IMT_REG);
1451 x86_branch8 (code, X86_CC_Z, FALSE, 0);
1454 x86_alu_reg_imm (code, X86_ADD, X86_EAX, 2 * sizeof (gpointer));
1455 x86_jump_code (code, labels [0]);
1458 mono_x86_patch (labels [2], code);
1459 x86_mov_reg_membase (code, X86_EAX, X86_EAX, sizeof (gpointer), 4);
1460 x86_mov_reg_membase (code, X86_EAX, X86_EAX, 0, 4);
1461 /* Save the target address to the temporary stack location */
1462 x86_mov_membase_reg (code, X86_ESP, 4, X86_EAX, 4);
1464 x86_pop_reg (code, X86_EAX);
1465 /* Jump to the target address */
1469 mono_x86_patch (labels [1], code);
1470 /* Load fail tramp */
1471 x86_mov_reg_membase (code, X86_EAX, X86_EAX, sizeof (gpointer), 4);
1472 x86_alu_membase_imm (code, X86_CMP, X86_EAX, 0, 0);
1474 x86_branch8 (code, X86_CC_Z, FALSE, 0);
1475 /* Jump to fail tramp */
1476 x86_mov_membase_reg (code, X86_ESP, 4, X86_EAX, 4);
1477 x86_pop_reg (code, X86_EAX);
1481 mono_x86_patch (labels [3], code);
1482 x86_breakpoint (code);
1484 #ifdef __native_client_codegen__
1486 /* emit nops to next 32 byte alignment */
1487 int a = (~kNaClAlignmentMask) & ((code - buf) + kNaClAlignment - 1);
1488 while (code < (buf + a)) x86_nop(code);
1491 emit_bytes (acfg, buf, code - buf);
1493 *tramp_size = code - buf;
1495 #if defined(__default_codegen__)
1497 #elif defined(__native_client_codegen__)
1501 #elif defined(TARGET_ARM)
1503 guint8 *code, *code2, *labels [16];
1507 /* The IMT method is in v5 */
1509 /* Need at least two free registers, plus a slot for storing the pc */
1510 ARM_PUSH (code, (1 << ARMREG_R0)|(1 << ARMREG_R1)|(1 << ARMREG_R2));
1512 /* Load the parameter from the GOT */
1513 ARM_LDR_IMM (code, ARMREG_R0, ARMREG_PC, 0);
1514 ARM_LDR_REG_REG (code, ARMREG_R0, ARMREG_PC, ARMREG_R0);
1517 ARM_LDR_IMM (code, ARMREG_R1, ARMREG_R0, 0);
1518 ARM_CMP_REG_REG (code, ARMREG_R1, ARMREG_V5);
1520 ARM_B_COND (code, ARMCOND_EQ, 0);
1522 /* End-of-loop check */
1523 ARM_CMP_REG_IMM (code, ARMREG_R1, 0, 0);
1525 ARM_B_COND (code, ARMCOND_EQ, 0);
1528 ARM_ADD_REG_IMM8 (code, ARMREG_R0, ARMREG_R0, sizeof (gpointer) * 2);
1531 arm_patch (labels [4], labels [1]);
1534 arm_patch (labels [2], code);
1535 ARM_LDR_IMM (code, ARMREG_R0, ARMREG_R0, 4);
1536 ARM_LDR_IMM (code, ARMREG_R0, ARMREG_R0, 0);
1537 /* Save it to the third stack slot */
1538 ARM_STR_IMM (code, ARMREG_R0, ARMREG_SP, 8);
1539 /* Restore the registers and branch */
1540 ARM_POP (code, (1 << ARMREG_R0)|(1 << ARMREG_R1)|(1 << ARMREG_PC));
1543 arm_patch (labels [3], code);
1544 ARM_LDR_IMM (code, ARMREG_R0, ARMREG_R0, 4);
1545 ARM_STR_IMM (code, ARMREG_R0, ARMREG_SP, 8);
1546 ARM_POP (code, (1 << ARMREG_R0)|(1 << ARMREG_R1)|(1 << ARMREG_PC));
1550 ARM_LDR_IMM (code2, ARMREG_R0, ARMREG_PC, (code - (labels [0] + 8)));
1552 emit_bytes (acfg, buf, code - buf);
1553 emit_symbol_diff (acfg, acfg->got_symbol, ".", (offset * sizeof (gpointer)) + (code - (labels [0] + 8)) - 4);
1555 *tramp_size = code - buf + 4;
1556 #elif defined(TARGET_POWERPC)
1558 guint8 *code, *labels [16];
1562 /* Load the mscorlib got address */
1563 ppc_ldptr (code, ppc_r11, sizeof (gpointer), ppc_r30);
1564 /* Load the parameter from the GOT */
1565 ppc_load (code, ppc_r0, offset * sizeof (gpointer));
1566 ppc_ldptr_indexed (code, ppc_r11, ppc_r11, ppc_r0);
1568 /* Load and check key */
1570 ppc_ldptr (code, ppc_r0, 0, ppc_r11);
1571 ppc_cmp (code, 0, sizeof (gpointer) == 8 ? 1 : 0, ppc_r0, MONO_ARCH_IMT_REG);
1573 ppc_bc (code, PPC_BR_TRUE, PPC_BR_EQ, 0);
1575 /* End-of-loop check */
1576 ppc_cmpi (code, 0, sizeof (gpointer) == 8 ? 1 : 0, ppc_r0, 0);
1578 ppc_bc (code, PPC_BR_TRUE, PPC_BR_EQ, 0);
1581 ppc_addi (code, ppc_r11, ppc_r11, 2 * sizeof (gpointer));
1584 mono_ppc_patch (labels [4], labels [1]);
1587 mono_ppc_patch (labels [2], code);
1588 ppc_ldptr (code, ppc_r11, sizeof (gpointer), ppc_r11);
1589 /* r11 now contains the value of the vtable slot */
1590 /* this is not a function descriptor on ppc64 */
1591 ppc_ldptr (code, ppc_r11, 0, ppc_r11);
1592 ppc_mtctr (code, ppc_r11);
1593 ppc_bcctr (code, PPC_BR_ALWAYS, 0);
1596 mono_ppc_patch (labels [3], code);
1600 *tramp_size = code - buf;
1602 emit_bytes (acfg, buf, code - buf);
1604 g_assert_not_reached ();
1609 arch_emit_autoreg (MonoAotCompile *acfg, char *symbol)
1611 #if defined(TARGET_POWERPC) && defined(__mono_ilp32__)
1612 /* Based on code generated by gcc */
1613 img_writer_emit_unset_mode (acfg->w);
1616 #if defined(_MSC_VER) || defined(MONO_CROSS_COMPILE)
1617 ".section .ctors,\"aw\",@progbits\n"
1621 ".section .opd,\"aw\"\n"
1624 ".long .%s,.TOC.@tocbase32\n"
1627 ".type .%s,@function\n"
1629 ".%s:\n", symbol, symbol, symbol, symbol, symbol, symbol, symbol, symbol);
1631 ".section .ctors,\"aw\",@progbits\n"
1635 ".section .opd,\"aw\"\n"
1638 ".long .%1$s,.TOC.@tocbase32\n"
1639 ".size %1$s,.-%1$s\n"
1641 ".type .%1$s,@function\n"
1643 ".%1$s:\n", symbol);
1654 "lis 3, .Lglobals@h\n"
1655 "ori 3, 3, .Lglobals@l\n"
1656 "bl .mono_aot_register_module\n"
1664 #if defined(_MSC_VER) || defined(MONO_CROSS_COMPILE)
1666 ".size .%s,.-.%s\n", symbol, symbol);
1669 ".size .%1$s,.-.%1$s\n", symbol);
1675 /* END OF ARCH SPECIFIC CODE */
1678 mono_get_field_token (MonoClassField *field)
1680 MonoClass *klass = field->parent;
1683 for (i = 0; i < klass->field.count; ++i) {
1684 if (field == &klass->fields [i])
1685 return MONO_TOKEN_FIELD_DEF | (klass->field.first + 1 + i);
1688 g_assert_not_reached ();
1693 encode_value (gint32 value, guint8 *buf, guint8 **endbuf)
1697 //printf ("ENCODE: %d 0x%x.\n", value, value);
1700 * Same encoding as the one used in the metadata, extended to handle values
1701 * greater than 0x1fffffff.
1703 if ((value >= 0) && (value <= 127))
1705 else if ((value >= 0) && (value <= 16383)) {
1706 p [0] = 0x80 | (value >> 8);
1707 p [1] = value & 0xff;
1709 } else if ((value >= 0) && (value <= 0x1fffffff)) {
1710 p [0] = (value >> 24) | 0xc0;
1711 p [1] = (value >> 16) & 0xff;
1712 p [2] = (value >> 8) & 0xff;
1713 p [3] = value & 0xff;
1718 p [1] = (value >> 24) & 0xff;
1719 p [2] = (value >> 16) & 0xff;
1720 p [3] = (value >> 8) & 0xff;
1721 p [4] = value & 0xff;
1729 stream_init (MonoDynamicStream *sh)
1732 sh->alloc_size = 4096;
1733 sh->data = g_malloc (4096);
1735 /* So offsets are > 0 */
1741 make_room_in_stream (MonoDynamicStream *stream, int size)
1743 if (size <= stream->alloc_size)
1746 while (stream->alloc_size <= size) {
1747 if (stream->alloc_size < 4096)
1748 stream->alloc_size = 4096;
1750 stream->alloc_size *= 2;
1753 stream->data = g_realloc (stream->data, stream->alloc_size);
1757 add_stream_data (MonoDynamicStream *stream, const char *data, guint32 len)
1761 make_room_in_stream (stream, stream->index + len);
1762 memcpy (stream->data + stream->index, data, len);
1763 idx = stream->index;
1764 stream->index += len;
1771 * Add data to the binary blob inside the aot image. Returns the offset inside the
1772 * blob where the data was stored.
1775 add_to_blob (MonoAotCompile *acfg, const guint8 *data, guint32 data_len)
1777 if (acfg->blob.alloc_size == 0)
1778 stream_init (&acfg->blob);
1780 return add_stream_data (&acfg->blob, (char*)data, data_len);
1784 add_to_blob_aligned (MonoAotCompile *acfg, const guint8 *data, guint32 data_len, guint32 align)
1789 if (acfg->blob.alloc_size == 0)
1790 stream_init (&acfg->blob);
1792 count = acfg->blob.index % align;
1794 /* we assume the stream data will be aligned */
1796 add_stream_data (&acfg->blob, buf, 4 - count);
1798 return add_stream_data (&acfg->blob, (char*)data, data_len);
1802 * emit_offset_table:
1804 * Emit a table of increasing offsets in a compact form using differential encoding.
1805 * There is an index entry for each GROUP_SIZE number of entries. The greater the
1806 * group size, the more compact the table becomes, but the slower it becomes to compute
1807 * a given entry. Returns the size of the table.
1810 emit_offset_table (MonoAotCompile *acfg, int noffsets, int group_size, gint32 *offsets)
1812 gint32 current_offset;
1813 int i, buf_size, ngroups, index_entry_size;
1815 guint32 *index_offsets;
1817 ngroups = (noffsets + (group_size - 1)) / group_size;
1819 index_offsets = g_new0 (guint32, ngroups);
1821 buf_size = noffsets * 4;
1822 p = buf = g_malloc0 (buf_size);
1825 for (i = 0; i < noffsets; ++i) {
1826 //printf ("D: %d -> %d\n", i, offsets [i]);
1827 if ((i % group_size) == 0) {
1828 index_offsets [i / group_size] = p - buf;
1829 /* Emit the full value for these entries */
1830 encode_value (offsets [i], p, &p);
1832 /* The offsets are allowed to be non-increasing */
1833 //g_assert (offsets [i] >= current_offset);
1834 encode_value (offsets [i] - current_offset, p, &p);
1836 current_offset = offsets [i];
1839 if (ngroups && index_offsets [ngroups - 1] < 65000)
1840 index_entry_size = 2;
1842 index_entry_size = 4;
1844 /* Emit the header */
1845 emit_int32 (acfg, noffsets);
1846 emit_int32 (acfg, group_size);
1847 emit_int32 (acfg, ngroups);
1848 emit_int32 (acfg, index_entry_size);
1850 /* Emit the index */
1851 for (i = 0; i < ngroups; ++i) {
1852 if (index_entry_size == 2)
1853 emit_int16 (acfg, index_offsets [i]);
1855 emit_int32 (acfg, index_offsets [i]);
1859 emit_bytes (acfg, buf, p - buf);
1861 return (int)(p - buf) + (ngroups * 4);
1865 get_image_index (MonoAotCompile *cfg, MonoImage *image)
1869 index = GPOINTER_TO_UINT (g_hash_table_lookup (cfg->image_hash, image));
1873 index = g_hash_table_size (cfg->image_hash);
1874 g_hash_table_insert (cfg->image_hash, image, GUINT_TO_POINTER (index + 1));
1875 g_ptr_array_add (cfg->image_table, image);
1881 find_typespec_for_class (MonoAotCompile *acfg, MonoClass *klass)
1884 int len = acfg->image->tables [MONO_TABLE_TYPESPEC].rows;
1886 /* FIXME: Search referenced images as well */
1887 if (!acfg->typespec_classes) {
1888 acfg->typespec_classes = mono_mempool_alloc0 (acfg->mempool, sizeof (MonoClass*) * len);
1889 for (i = 0; i < len; ++i) {
1890 acfg->typespec_classes [i] = mono_class_get_full (acfg->image, MONO_TOKEN_TYPE_SPEC | (i + 1), NULL);
1893 for (i = 0; i < len; ++i) {
1894 if (acfg->typespec_classes [i] == klass)
1899 return MONO_TOKEN_TYPE_SPEC | (i + 1);
1905 encode_method_ref (MonoAotCompile *acfg, MonoMethod *method, guint8 *buf, guint8 **endbuf);
1908 encode_klass_ref (MonoAotCompile *acfg, MonoClass *klass, guint8 *buf, guint8 **endbuf);
1911 encode_ginst (MonoAotCompile *acfg, MonoGenericInst *inst, guint8 *buf, guint8 **endbuf);
1914 encode_type (MonoAotCompile *acfg, MonoType *t, guint8 *buf, guint8 **endbuf);
1917 encode_klass_ref_inner (MonoAotCompile *acfg, MonoClass *klass, guint8 *buf, guint8 **endbuf)
1922 * The encoding begins with one of the MONO_AOT_TYPEREF values, followed by additional
1926 if (klass->generic_class) {
1928 g_assert (klass->type_token);
1930 /* Find a typespec for a class if possible */
1931 token = find_typespec_for_class (acfg, klass);
1933 encode_value (MONO_AOT_TYPEREF_TYPESPEC_TOKEN, p, &p);
1934 encode_value (token, p, &p);
1936 MonoClass *gclass = klass->generic_class->container_class;
1937 MonoGenericInst *inst = klass->generic_class->context.class_inst;
1938 static int count = 0;
1941 encode_value (MONO_AOT_TYPEREF_GINST, p, &p);
1942 encode_klass_ref (acfg, gclass, p, &p);
1943 encode_ginst (acfg, inst, p, &p);
1947 } else if (klass->type_token) {
1948 int iindex = get_image_index (acfg, klass->image);
1950 g_assert (mono_metadata_token_code (klass->type_token) == MONO_TOKEN_TYPE_DEF);
1952 encode_value (MONO_AOT_TYPEREF_TYPEDEF_INDEX, p, &p);
1953 encode_value (klass->type_token - MONO_TOKEN_TYPE_DEF, p, &p);
1955 encode_value (MONO_AOT_TYPEREF_TYPEDEF_INDEX_IMAGE, p, &p);
1956 encode_value (klass->type_token - MONO_TOKEN_TYPE_DEF, p, &p);
1957 encode_value (get_image_index (acfg, klass->image), p, &p);
1959 } else if ((klass->byval_arg.type == MONO_TYPE_VAR) || (klass->byval_arg.type == MONO_TYPE_MVAR)) {
1960 MonoGenericContainer *container = mono_type_get_generic_param_owner (&klass->byval_arg);
1961 MonoGenericParam *par = klass->byval_arg.data.generic_param;
1963 encode_value (MONO_AOT_TYPEREF_VAR, p, &p);
1964 encode_value (klass->byval_arg.type, p, &p);
1965 encode_value (mono_type_get_generic_param_num (&klass->byval_arg), p, &p);
1967 encode_value (container ? 1 : 0, p, &p);
1969 encode_value (container->is_method, p, &p);
1970 g_assert (par->serial == 0);
1971 if (container->is_method)
1972 encode_method_ref (acfg, container->owner.method, p, &p);
1974 encode_klass_ref (acfg, container->owner.klass, p, &p);
1976 encode_value (par->serial, p, &p);
1978 } else if (klass->byval_arg.type == MONO_TYPE_PTR) {
1979 encode_value (MONO_AOT_TYPEREF_PTR, p, &p);
1980 encode_type (acfg, &klass->byval_arg, p, &p);
1983 g_assert (klass->rank > 0);
1984 encode_value (MONO_AOT_TYPEREF_ARRAY, p, &p);
1985 encode_value (klass->rank, p, &p);
1986 encode_klass_ref (acfg, klass->element_class, p, &p);
1994 * Encode a reference to KLASS. We use our home-grown encoding instead of the
1995 * standard metadata encoding.
1998 encode_klass_ref (MonoAotCompile *acfg, MonoClass *klass, guint8 *buf, guint8 **endbuf)
2000 gboolean shared = FALSE;
2003 * The encoding of generic instances is large so emit them only once.
2005 if (klass->generic_class) {
2007 g_assert (klass->type_token);
2009 /* Find a typespec for a class if possible */
2010 token = find_typespec_for_class (acfg, klass);
2013 } else if ((klass->byval_arg.type == MONO_TYPE_VAR) || (klass->byval_arg.type == MONO_TYPE_MVAR)) {
2018 guint offset = GPOINTER_TO_UINT (g_hash_table_lookup (acfg->klass_blob_hash, klass));
2022 buf2 = g_malloc (1024);
2025 encode_klass_ref_inner (acfg, klass, p, &p);
2026 g_assert (p - buf2 < 1024);
2028 offset = add_to_blob (acfg, buf2, p - buf2);
2031 g_hash_table_insert (acfg->klass_blob_hash, klass, GUINT_TO_POINTER (offset + 1));
2037 encode_value (MONO_AOT_TYPEREF_BLOB_INDEX, p, &p);
2038 encode_value (offset, p, &p);
2043 encode_klass_ref_inner (acfg, klass, buf, endbuf);
2047 encode_field_info (MonoAotCompile *cfg, MonoClassField *field, guint8 *buf, guint8 **endbuf)
2049 guint32 token = mono_get_field_token (field);
2052 encode_klass_ref (cfg, field->parent, p, &p);
2053 g_assert (mono_metadata_token_code (token) == MONO_TOKEN_FIELD_DEF);
2054 encode_value (token - MONO_TOKEN_FIELD_DEF, p, &p);
2059 encode_ginst (MonoAotCompile *acfg, MonoGenericInst *inst, guint8 *buf, guint8 **endbuf)
2064 encode_value (inst->type_argc, p, &p);
2065 for (i = 0; i < inst->type_argc; ++i)
2066 encode_klass_ref (acfg, mono_class_from_mono_type (inst->type_argv [i]), p, &p);
2071 encode_generic_context (MonoAotCompile *acfg, MonoGenericContext *context, guint8 *buf, guint8 **endbuf)
2074 MonoGenericInst *inst;
2076 inst = context->class_inst;
2078 g_assert (inst->type_argc);
2079 encode_ginst (acfg, inst, p, &p);
2081 encode_value (0, p, &p);
2083 inst = context->method_inst;
2085 g_assert (inst->type_argc);
2086 encode_ginst (acfg, inst, p, &p);
2088 encode_value (0, p, &p);
2094 encode_type (MonoAotCompile *acfg, MonoType *t, guint8 *buf, guint8 **endbuf)
2098 g_assert (t->num_mods == 0);
2099 /* t->attrs can be ignored */
2100 //g_assert (t->attrs == 0);
2103 *p = MONO_TYPE_PINNED;
2107 *p = MONO_TYPE_BYREF;
2115 case MONO_TYPE_VOID:
2116 case MONO_TYPE_BOOLEAN:
2117 case MONO_TYPE_CHAR:
2130 case MONO_TYPE_STRING:
2131 case MONO_TYPE_OBJECT:
2132 case MONO_TYPE_TYPEDBYREF:
2134 case MONO_TYPE_VALUETYPE:
2135 case MONO_TYPE_CLASS:
2136 encode_klass_ref (acfg, mono_class_from_mono_type (t), p, &p);
2138 case MONO_TYPE_SZARRAY:
2139 encode_klass_ref (acfg, t->data.klass, p, &p);
2142 encode_type (acfg, t->data.type, p, &p);
2144 case MONO_TYPE_GENERICINST: {
2145 MonoClass *gclass = t->data.generic_class->container_class;
2146 MonoGenericInst *inst = t->data.generic_class->context.class_inst;
2148 encode_klass_ref (acfg, gclass, p, &p);
2149 encode_ginst (acfg, inst, p, &p);
2152 case MONO_TYPE_ARRAY: {
2153 MonoArrayType *array = t->data.array;
2156 encode_klass_ref (acfg, array->eklass, p, &p);
2157 encode_value (array->rank, p, &p);
2158 encode_value (array->numsizes, p, &p);
2159 for (i = 0; i < array->numsizes; ++i)
2160 encode_value (array->sizes [i], p, &p);
2161 encode_value (array->numlobounds, p, &p);
2162 for (i = 0; i < array->numlobounds; ++i)
2163 encode_value (array->lobounds [i], p, &p);
2167 g_assert_not_reached ();
2174 encode_signature (MonoAotCompile *acfg, MonoMethodSignature *sig, guint8 *buf, guint8 **endbuf)
2180 /* Similar to the metadata encoding */
2181 if (sig->generic_param_count)
2185 if (sig->explicit_this)
2187 flags |= (sig->call_convention & 0x0F);
2191 if (sig->generic_param_count)
2192 encode_value (sig->generic_param_count, p, &p);
2193 encode_value (sig->param_count, p, &p);
2195 encode_type (acfg, sig->ret, p, &p);
2196 for (i = 0; i < sig->param_count; ++i) {
2197 if (sig->sentinelpos == i) {
2198 *p = MONO_TYPE_SENTINEL;
2201 encode_type (acfg, sig->params [i], p, &p);
2207 #define MAX_IMAGE_INDEX 250
2210 encode_method_ref (MonoAotCompile *acfg, MonoMethod *method, guint8 *buf, guint8 **endbuf)
2212 guint32 image_index = get_image_index (acfg, method->klass->image);
2213 guint32 token = method->token;
2214 MonoJumpInfoToken *ji;
2218 * The encoding for most methods is as follows:
2219 * - image index encoded as a leb128
2220 * - token index encoded as a leb128
2221 * Values of image index >= MONO_AOT_METHODREF_MIN are used to mark additional
2222 * types of method encodings.
2225 g_assert (image_index < MONO_AOT_METHODREF_MIN);
2227 /* Mark methods which can't use aot trampolines because they need the further
2228 * processing in mono_magic_trampoline () which requires a MonoMethod*.
2230 if ((method->is_generic && (method->flags & METHOD_ATTRIBUTE_VIRTUAL)) ||
2231 (method->iflags & METHOD_IMPL_ATTRIBUTE_SYNCHRONIZED))
2232 encode_value ((MONO_AOT_METHODREF_NO_AOT_TRAMPOLINE << 24), p, &p);
2234 if (method->wrapper_type) {
2235 encode_value ((MONO_AOT_METHODREF_WRAPPER << 24), p, &p);
2237 encode_value (method->wrapper_type, p, &p);
2239 switch (method->wrapper_type) {
2240 case MONO_WRAPPER_REMOTING_INVOKE:
2241 case MONO_WRAPPER_REMOTING_INVOKE_WITH_CHECK:
2242 case MONO_WRAPPER_XDOMAIN_INVOKE: {
2245 m = mono_marshal_method_from_wrapper (method);
2247 encode_method_ref (acfg, m, p, &p);
2250 case MONO_WRAPPER_PROXY_ISINST:
2251 case MONO_WRAPPER_LDFLD:
2252 case MONO_WRAPPER_LDFLDA:
2253 case MONO_WRAPPER_STFLD:
2254 case MONO_WRAPPER_ISINST: {
2255 MonoClass *proxy_class = mono_marshal_get_wrapper_info (method);
2256 encode_klass_ref (acfg, proxy_class, p, &p);
2259 case MONO_WRAPPER_LDFLD_REMOTE:
2260 case MONO_WRAPPER_STFLD_REMOTE:
2262 case MONO_WRAPPER_ALLOC: {
2263 AllocatorWrapperInfo *info = mono_marshal_get_wrapper_info (method);
2265 /* The GC name is saved once in MonoAotFileInfo */
2266 g_assert (info->alloc_type != -1);
2267 encode_value (info->alloc_type, p, &p);
2270 case MONO_WRAPPER_WRITE_BARRIER:
2272 case MONO_WRAPPER_STELEMREF: {
2273 WrapperInfo *info = mono_marshal_get_wrapper_info (method);
2276 encode_value (info->subtype, p, &p);
2277 if (info->subtype == WRAPPER_SUBTYPE_VIRTUAL_STELEMREF)
2278 encode_value (info->d.virtual_stelemref.kind, p, &p);
2281 case MONO_WRAPPER_UNKNOWN: {
2282 WrapperInfo *info = mono_marshal_get_wrapper_info (method);
2285 encode_value (info->subtype, p, &p);
2286 if (info->subtype == WRAPPER_SUBTYPE_PTR_TO_STRUCTURE ||
2287 info->subtype == WRAPPER_SUBTYPE_STRUCTURE_TO_PTR)
2288 encode_klass_ref (acfg, method->klass, p, &p);
2289 else if (info->subtype == WRAPPER_SUBTYPE_SYNCHRONIZED_INNER)
2290 encode_method_ref (acfg, info->d.synchronized_inner.method, p, &p);
2293 case MONO_WRAPPER_MANAGED_TO_NATIVE: {
2294 WrapperInfo *info = mono_marshal_get_wrapper_info (method);
2297 encode_value (info->subtype, p, &p);
2298 if (info->subtype == WRAPPER_SUBTYPE_ICALL_WRAPPER) {
2299 strcpy ((char*)p, method->name);
2300 p += strlen (method->name) + 1;
2301 } else if (info->subtype == WRAPPER_SUBTYPE_NATIVE_FUNC_AOT) {
2302 encode_method_ref (acfg, info->d.managed_to_native.method, p, &p);
2304 g_assert (info->subtype == WRAPPER_SUBTYPE_NONE);
2305 encode_method_ref (acfg, info->d.managed_to_native.method, p, &p);
2309 case MONO_WRAPPER_SYNCHRONIZED: {
2312 m = mono_marshal_method_from_wrapper (method);
2314 g_assert (m != method);
2315 encode_method_ref (acfg, m, p, &p);
2318 case MONO_WRAPPER_MANAGED_TO_MANAGED: {
2319 WrapperInfo *info = mono_marshal_get_wrapper_info (method);
2322 encode_value (info->subtype, p, &p);
2324 if (info->subtype == WRAPPER_SUBTYPE_ELEMENT_ADDR) {
2325 encode_value (info->d.element_addr.rank, p, &p);
2326 encode_value (info->d.element_addr.elem_size, p, &p);
2327 } else if (info->subtype == WRAPPER_SUBTYPE_STRING_CTOR) {
2328 encode_method_ref (acfg, info->d.string_ctor.method, p, &p);
2330 g_assert_not_reached ();
2334 case MONO_WRAPPER_CASTCLASS: {
2335 WrapperInfo *info = mono_marshal_get_wrapper_info (method);
2338 encode_value (info->subtype, p, &p);
2341 case MONO_WRAPPER_RUNTIME_INVOKE: {
2342 WrapperInfo *info = mono_marshal_get_wrapper_info (method);
2345 encode_value (info->subtype, p, &p);
2346 if (info->subtype == WRAPPER_SUBTYPE_RUNTIME_INVOKE_DIRECT || info->subtype == WRAPPER_SUBTYPE_RUNTIME_INVOKE_VIRTUAL)
2347 encode_method_ref (acfg, info->d.runtime_invoke.method, p, &p);
2349 MonoMethodSignature *sig;
2351 encode_value (0, p, &p);
2353 sig = mono_method_signature (method);
2354 encode_signature (acfg, sig, p, &p);
2358 case MONO_WRAPPER_DELEGATE_INVOKE:
2359 case MONO_WRAPPER_DELEGATE_BEGIN_INVOKE:
2360 case MONO_WRAPPER_DELEGATE_END_INVOKE: {
2361 MonoMethodSignature *sig = mono_method_signature (method);
2362 encode_signature (acfg, sig, p, &p);
2365 case MONO_WRAPPER_NATIVE_TO_MANAGED: {
2366 WrapperInfo *info = mono_marshal_get_wrapper_info (method);
2369 encode_method_ref (acfg, info->d.native_to_managed.method, p, &p);
2370 encode_klass_ref (acfg, info->d.native_to_managed.klass, p, &p);
2374 g_assert_not_reached ();
2376 } else if (mono_method_signature (method)->is_inflated) {
2378 * This is a generic method, find the original token which referenced it and
2380 * Obtain the token from information recorded by the JIT.
2382 ji = g_hash_table_lookup (acfg->token_info_hash, method);
2384 image_index = get_image_index (acfg, ji->image);
2385 g_assert (image_index < MAX_IMAGE_INDEX);
2388 encode_value ((MONO_AOT_METHODREF_METHODSPEC << 24), p, &p);
2389 encode_value (image_index, p, &p);
2390 encode_value (token, p, &p);
2392 MonoMethod *declaring;
2393 MonoGenericContext *context = mono_method_get_context (method);
2395 g_assert (method->is_inflated);
2396 declaring = ((MonoMethodInflated*)method)->declaring;
2399 * This might be a non-generic method of a generic instance, which
2400 * doesn't have a token since the reference is generated by the JIT
2401 * like Nullable:Box/Unbox, or by generic sharing.
2404 encode_value ((MONO_AOT_METHODREF_GINST << 24), p, &p);
2405 /* Encode the klass */
2406 encode_klass_ref (acfg, method->klass, p, &p);
2407 /* Encode the method */
2408 image_index = get_image_index (acfg, method->klass->image);
2409 g_assert (image_index < MAX_IMAGE_INDEX);
2410 g_assert (declaring->token);
2411 token = declaring->token;
2412 g_assert (mono_metadata_token_table (token) == MONO_TABLE_METHOD);
2413 encode_value (image_index, p, &p);
2414 encode_value (token, p, &p);
2415 encode_generic_context (acfg, context, p, &p);
2417 } else if (token == 0) {
2418 /* This might be a method of a constructed type like int[,].Set */
2419 /* Obtain the token from information recorded by the JIT */
2420 ji = g_hash_table_lookup (acfg->token_info_hash, method);
2422 image_index = get_image_index (acfg, ji->image);
2423 g_assert (image_index < MAX_IMAGE_INDEX);
2426 encode_value ((MONO_AOT_METHODREF_METHODSPEC << 24), p, &p);
2427 encode_value (image_index, p, &p);
2428 encode_value (token, p, &p);
2431 g_assert (method->klass->rank);
2433 /* Encode directly */
2434 encode_value ((MONO_AOT_METHODREF_ARRAY << 24), p, &p);
2435 encode_klass_ref (acfg, method->klass, p, &p);
2436 if (!strcmp (method->name, ".ctor") && mono_method_signature (method)->param_count == method->klass->rank)
2437 encode_value (0, p, &p);
2438 else if (!strcmp (method->name, ".ctor") && mono_method_signature (method)->param_count == method->klass->rank * 2)
2439 encode_value (1, p, &p);
2440 else if (!strcmp (method->name, "Get"))
2441 encode_value (2, p, &p);
2442 else if (!strcmp (method->name, "Address"))
2443 encode_value (3, p, &p);
2444 else if (!strcmp (method->name, "Set"))
2445 encode_value (4, p, &p);
2447 g_assert_not_reached ();
2450 g_assert (mono_metadata_token_table (token) == MONO_TABLE_METHOD);
2451 encode_value ((image_index << 24) | mono_metadata_token_index (token), p, &p);
2457 compare_patches (gconstpointer a, gconstpointer b)
2461 i = (*(MonoJumpInfo**)a)->ip.i;
2462 j = (*(MonoJumpInfo**)b)->ip.i;
2473 static G_GNUC_UNUSED char*
2474 patch_to_string (MonoJumpInfo *patch_info)
2478 str = g_string_new ("");
2480 g_string_append_printf (str, "%s(", get_patch_name (patch_info->type));
2482 switch (patch_info->type) {
2483 case MONO_PATCH_INFO_VTABLE:
2484 mono_type_get_desc (str, &patch_info->data.klass->byval_arg, TRUE);
2489 g_string_append_printf (str, ")");
2490 return g_string_free (str, FALSE);
2496 * Return whenever PATCH_INFO refers to a direct call, and thus requires a
2499 static inline gboolean
2500 is_plt_patch (MonoJumpInfo *patch_info)
2502 switch (patch_info->type) {
2503 case MONO_PATCH_INFO_METHOD:
2504 case MONO_PATCH_INFO_INTERNAL_METHOD:
2505 case MONO_PATCH_INFO_JIT_ICALL_ADDR:
2506 case MONO_PATCH_INFO_ICALL_ADDR:
2507 case MONO_PATCH_INFO_CLASS_INIT:
2508 case MONO_PATCH_INFO_RGCTX_FETCH:
2509 case MONO_PATCH_INFO_GENERIC_CLASS_INIT:
2510 case MONO_PATCH_INFO_MONITOR_ENTER:
2511 case MONO_PATCH_INFO_MONITOR_EXIT:
2512 case MONO_PATCH_INFO_LLVM_IMT_TRAMPOLINE:
2522 * Return the symbol identifying the plt entry PLT_OFFSET.
2525 get_plt_symbol (MonoAotCompile *acfg, int plt_offset, MonoJumpInfo *patch_info)
2529 * The Apple linker reorganizes object files, so it doesn't like branches to local
2530 * labels, since those have no relocations.
2532 return g_strdup_printf ("%sp_%d", acfg->llvm_label_prefix, plt_offset);
2534 return g_strdup_printf ("%sp_%d", acfg->temp_prefix, plt_offset);
2541 * Return a PLT entry which belongs to the method identified by PATCH_INFO.
2543 static MonoPltEntry*
2544 get_plt_entry (MonoAotCompile *acfg, MonoJumpInfo *patch_info)
2548 if (!is_plt_patch (patch_info))
2551 res = g_hash_table_lookup (acfg->patch_to_plt_entry, patch_info);
2553 // FIXME: This breaks the calculation of final_got_size
2554 if (!acfg->llvm && patch_info->type == MONO_PATCH_INFO_METHOD && (patch_info->data.method->iflags & METHOD_IMPL_ATTRIBUTE_SYNCHRONIZED)) {
2556 * Allocate a separate PLT slot for each such patch, since some plt
2557 * entries will refer to the method itself, and some will refer to the
2564 MonoJumpInfo *new_ji;
2566 g_assert (!acfg->final_got_size);
2568 new_ji = mono_patch_info_dup_mp (acfg->mempool, patch_info);
2570 res = mono_mempool_alloc0 (acfg->mempool, sizeof (MonoPltEntry));
2571 res->plt_offset = acfg->plt_offset;
2573 res->symbol = get_plt_symbol (acfg, res->plt_offset, patch_info);
2574 if (acfg->aot_opts.write_symbols)
2575 res->debug_sym = get_plt_entry_debug_sym (acfg, res->ji, acfg->plt_entry_debug_sym_cache);
2577 res->llvm_symbol = g_strdup_printf ("%s_%s_llvm", res->symbol, res->debug_sym);
2579 res->llvm_symbol = g_strdup_printf ("%s_llvm", res->symbol);
2581 g_hash_table_insert (acfg->patch_to_plt_entry, new_ji, res);
2583 g_hash_table_insert (acfg->plt_offset_to_entry, GUINT_TO_POINTER (res->plt_offset), res);
2585 acfg->plt_offset ++;
2594 * Returns the offset of the GOT slot where the runtime object resulting from resolving
2595 * JI could be found if it exists, otherwise allocates a new one.
2598 get_got_offset (MonoAotCompile *acfg, MonoJumpInfo *ji)
2602 got_offset = GPOINTER_TO_UINT (g_hash_table_lookup (acfg->patch_to_got_offset_by_type [ji->type], ji));
2604 return got_offset - 1;
2606 got_offset = acfg->got_offset;
2607 acfg->got_offset ++;
2609 if (acfg->final_got_size)
2610 g_assert (got_offset < acfg->final_got_size);
2612 acfg->stats.got_slots ++;
2613 acfg->stats.got_slot_types [ji->type] ++;
2615 g_hash_table_insert (acfg->patch_to_got_offset, ji, GUINT_TO_POINTER (got_offset + 1));
2616 g_hash_table_insert (acfg->patch_to_got_offset_by_type [ji->type], ji, GUINT_TO_POINTER (got_offset + 1));
2617 g_ptr_array_add (acfg->got_patches, ji);
2622 /* Add a method to the list of methods which need to be emitted */
2624 add_method_with_index (MonoAotCompile *acfg, MonoMethod *method, int index, gboolean extra)
2627 if (!g_hash_table_lookup (acfg->method_indexes, method)) {
2628 g_ptr_array_add (acfg->methods, method);
2629 g_hash_table_insert (acfg->method_indexes, method, GUINT_TO_POINTER (index + 1));
2630 acfg->nmethods = acfg->methods->len + 1;
2633 if (method->wrapper_type || extra)
2634 g_ptr_array_add (acfg->extra_methods, method);
2638 get_method_index (MonoAotCompile *acfg, MonoMethod *method)
2640 int index = GPOINTER_TO_UINT (g_hash_table_lookup (acfg->method_indexes, method));
2648 add_method_full (MonoAotCompile *acfg, MonoMethod *method, gboolean extra, int depth)
2652 index = GPOINTER_TO_UINT (g_hash_table_lookup (acfg->method_indexes, method));
2656 index = acfg->method_index;
2657 add_method_with_index (acfg, method, index, extra);
2659 g_ptr_array_add (acfg->method_order, GUINT_TO_POINTER (index));
2661 g_hash_table_insert (acfg->method_depth, method, GUINT_TO_POINTER (depth));
2663 acfg->method_index ++;
2669 add_method (MonoAotCompile *acfg, MonoMethod *method)
2671 return add_method_full (acfg, method, FALSE, 0);
2675 add_extra_method (MonoAotCompile *acfg, MonoMethod *method)
2677 add_method_full (acfg, method, TRUE, 0);
2681 add_extra_method_with_depth (MonoAotCompile *acfg, MonoMethod *method, int depth)
2683 if (acfg->aot_opts.log_generics)
2684 printf ("%*sAdding method %s.\n", depth, "", mono_method_full_name (method, TRUE));
2686 add_method_full (acfg, method, TRUE, depth);
2690 add_jit_icall_wrapper (gpointer key, gpointer value, gpointer user_data)
2692 MonoAotCompile *acfg = user_data;
2693 MonoJitICallInfo *callinfo = value;
2694 MonoMethod *wrapper;
2700 name = g_strdup_printf ("__icall_wrapper_%s", callinfo->name);
2701 wrapper = mono_marshal_get_icall_wrapper (callinfo->sig, name, callinfo->func, check_for_pending_exc);
2704 add_method (acfg, wrapper);
2708 get_runtime_invoke_sig (MonoMethodSignature *sig)
2710 MonoMethodBuilder *mb;
2713 mb = mono_mb_new (mono_defaults.object_class, "FOO", MONO_WRAPPER_NONE);
2714 m = mono_mb_create_method (mb, sig, 16);
2715 return mono_marshal_get_runtime_invoke (m, FALSE);
2719 can_marshal_struct (MonoClass *klass)
2721 MonoClassField *field;
2722 gboolean can_marshal = TRUE;
2723 gpointer iter = NULL;
2725 if ((klass->flags & TYPE_ATTRIBUTE_LAYOUT_MASK) == TYPE_ATTRIBUTE_AUTO_LAYOUT)
2728 /* Only allow a few field types to avoid asserts in the marshalling code */
2729 while ((field = mono_class_get_fields (klass, &iter))) {
2730 if ((field->type->attrs & FIELD_ATTRIBUTE_STATIC))
2733 switch (field->type->type) {
2738 case MONO_TYPE_BOOLEAN:
2741 case MONO_TYPE_CHAR:
2749 case MONO_TYPE_STRING:
2751 case MONO_TYPE_VALUETYPE:
2752 if (!mono_class_from_mono_type (field->type)->enumtype && !can_marshal_struct (mono_class_from_mono_type (field->type)))
2753 can_marshal = FALSE;
2756 can_marshal = FALSE;
2762 /* Its hard to compute whenever these can be marshalled or not */
2763 if (!strcmp (klass->name_space, "System.Net.NetworkInformation.MacOsStructs") && strcmp (klass->name, "sockaddr_dl"))
2770 add_wrappers (MonoAotCompile *acfg)
2772 MonoMethod *method, *m;
2774 MonoMethodSignature *sig, *csig;
2778 * FIXME: Instead of AOTing all the wrappers, it might be better to redesign them
2779 * so there is only one wrapper of a given type, or inlining their contents into their
2784 * FIXME: This depends on the fact that different wrappers have different
2788 for (i = 0; i < acfg->image->tables [MONO_TABLE_METHOD].rows; ++i) {
2790 guint32 token = MONO_TOKEN_METHOD_DEF | (i + 1);
2791 gboolean skip = FALSE;
2793 method = mono_get_method (acfg->image, token, NULL);
2795 if ((method->flags & METHOD_ATTRIBUTE_PINVOKE_IMPL) ||
2796 (method->iflags & METHOD_IMPL_ATTRIBUTE_RUNTIME) ||
2797 (method->flags & METHOD_ATTRIBUTE_ABSTRACT))
2800 if (method->is_generic || method->klass->generic_container)
2803 /* Skip methods which can not be handled by get_runtime_invoke () */
2804 sig = mono_method_signature (method);
2807 if ((sig->ret->type == MONO_TYPE_PTR) ||
2808 (sig->ret->type == MONO_TYPE_TYPEDBYREF))
2811 for (j = 0; j < sig->param_count; j++) {
2812 if (sig->params [j]->type == MONO_TYPE_TYPEDBYREF)
2816 #ifdef MONO_ARCH_DYN_CALL_SUPPORTED
2817 if (!method->klass->contextbound) {
2818 MonoDynCallInfo *info = mono_arch_dyn_call_prepare (sig);
2819 gboolean has_nullable = FALSE;
2821 for (j = 0; j < sig->param_count; j++) {
2822 if (sig->params [j]->type == MONO_TYPE_GENERICINST && mono_class_is_nullable (mono_class_from_mono_type (sig->params [j])))
2823 has_nullable = TRUE;
2826 if (info && !has_nullable) {
2827 /* Supported by the dynamic runtime-invoke wrapper */
2835 //printf ("%s\n", mono_method_full_name (method, TRUE));
2836 add_method (acfg, mono_marshal_get_runtime_invoke (method, FALSE));
2840 if (strcmp (acfg->image->assembly->aname.name, "mscorlib") == 0) {
2841 #ifdef MONO_ARCH_HAVE_TLS_GET
2842 MonoMethodDesc *desc;
2843 MonoMethod *orig_method;
2847 /* Runtime invoke wrappers */
2849 /* void runtime-invoke () [.cctor] */
2850 csig = mono_metadata_signature_alloc (mono_defaults.corlib, 0);
2851 csig->ret = &mono_defaults.void_class->byval_arg;
2852 add_method (acfg, get_runtime_invoke_sig (csig));
2854 /* void runtime-invoke () [Finalize] */
2855 csig = mono_metadata_signature_alloc (mono_defaults.corlib, 0);
2857 csig->ret = &mono_defaults.void_class->byval_arg;
2858 add_method (acfg, get_runtime_invoke_sig (csig));
2860 /* void runtime-invoke (string) [exception ctor] */
2861 csig = mono_metadata_signature_alloc (mono_defaults.corlib, 1);
2863 csig->ret = &mono_defaults.void_class->byval_arg;
2864 csig->params [0] = &mono_defaults.string_class->byval_arg;
2865 add_method (acfg, get_runtime_invoke_sig (csig));
2867 /* void runtime-invoke (string, string) [exception ctor] */
2868 csig = mono_metadata_signature_alloc (mono_defaults.corlib, 2);
2870 csig->ret = &mono_defaults.void_class->byval_arg;
2871 csig->params [0] = &mono_defaults.string_class->byval_arg;
2872 csig->params [1] = &mono_defaults.string_class->byval_arg;
2873 add_method (acfg, get_runtime_invoke_sig (csig));
2875 /* string runtime-invoke () [Exception.ToString ()] */
2876 csig = mono_metadata_signature_alloc (mono_defaults.corlib, 0);
2878 csig->ret = &mono_defaults.string_class->byval_arg;
2879 add_method (acfg, get_runtime_invoke_sig (csig));
2881 /* void runtime-invoke (string, Exception) [exception ctor] */
2882 csig = mono_metadata_signature_alloc (mono_defaults.corlib, 2);
2884 csig->ret = &mono_defaults.void_class->byval_arg;
2885 csig->params [0] = &mono_defaults.string_class->byval_arg;
2886 csig->params [1] = &mono_defaults.exception_class->byval_arg;
2887 add_method (acfg, get_runtime_invoke_sig (csig));
2889 /* Assembly runtime-invoke (string, bool) [DoAssemblyResolve] */
2890 csig = mono_metadata_signature_alloc (mono_defaults.corlib, 2);
2892 csig->ret = &(mono_class_from_name (
2893 mono_defaults.corlib, "System.Reflection", "Assembly"))->byval_arg;
2894 csig->params [0] = &mono_defaults.string_class->byval_arg;
2895 csig->params [1] = &mono_defaults.boolean_class->byval_arg;
2896 add_method (acfg, get_runtime_invoke_sig (csig));
2898 /* runtime-invoke used by finalizers */
2899 add_method (acfg, mono_marshal_get_runtime_invoke (mono_class_get_method_from_name_flags (mono_defaults.object_class, "Finalize", 0, 0), TRUE));
2901 /* This is used by mono_runtime_capture_context () */
2902 method = mono_get_context_capture_method ();
2904 add_method (acfg, mono_marshal_get_runtime_invoke (method, FALSE));
2906 #ifdef MONO_ARCH_DYN_CALL_SUPPORTED
2907 add_method (acfg, mono_marshal_get_runtime_invoke_dynamic ());
2910 /* JIT icall wrappers */
2911 /* FIXME: locking */
2912 g_hash_table_foreach (mono_get_jit_icall_info (), add_jit_icall_wrapper, acfg);
2915 add_method (acfg, mono_marshal_get_stelemref ());
2917 #ifdef MONO_ARCH_HAVE_TLS_GET
2918 /* Managed Allocators */
2919 nallocators = mono_gc_get_managed_allocator_types ();
2920 for (i = 0; i < nallocators; ++i) {
2921 m = mono_gc_get_managed_allocator_by_type (i);
2923 add_method (acfg, m);
2926 /* Monitor Enter/Exit */
2927 desc = mono_method_desc_new ("Monitor:Enter(object,bool&)", FALSE);
2928 orig_method = mono_method_desc_search_in_class (desc, mono_defaults.monitor_class);
2929 /* This is a v4 method */
2931 method = mono_monitor_get_fast_path (orig_method);
2933 add_method (acfg, method);
2935 mono_method_desc_free (desc);
2937 desc = mono_method_desc_new ("Monitor:Exit(object)", FALSE);
2938 orig_method = mono_method_desc_search_in_class (desc, mono_defaults.monitor_class);
2939 g_assert (orig_method);
2940 mono_method_desc_free (desc);
2941 method = mono_monitor_get_fast_path (orig_method);
2943 add_method (acfg, method);
2946 /* Stelemref wrappers */
2947 /* There is only a constant number of these, iterating over all types should handle them all */
2948 for (i = 0; i < acfg->image->tables [MONO_TABLE_TYPEDEF].rows; ++i) {
2951 token = MONO_TOKEN_TYPE_DEF | (i + 1);
2952 klass = mono_class_get (acfg->image, token);
2954 add_method (acfg, mono_marshal_get_virtual_stelemref (mono_array_class_get (klass, 1)));
2956 mono_loader_clear_error ();
2959 /* castclass_with_check wrapper */
2960 add_method (acfg, mono_marshal_get_castclass_with_cache ());
2961 /* isinst_with_check wrapper */
2962 add_method (acfg, mono_marshal_get_isinst_with_cache ());
2964 #if defined(MONO_ARCH_ENABLE_MONITOR_IL_FASTPATH)
2966 MonoMethodDesc *desc;
2969 desc = mono_method_desc_new ("Monitor:Enter(object,bool&)", FALSE);
2970 m = mono_method_desc_search_in_class (desc, mono_defaults.monitor_class);
2971 mono_method_desc_free (desc);
2973 m = mono_monitor_get_fast_path (m);
2975 add_method (acfg, m);
2982 * remoting-invoke-with-check wrappers are very frequent, so avoid emitting them,
2983 * we use the original method instead at runtime.
2984 * Since full-aot doesn't support remoting, this is not a problem.
2987 /* remoting-invoke wrappers */
2988 for (i = 0; i < acfg->image->tables [MONO_TABLE_METHOD].rows; ++i) {
2989 MonoMethodSignature *sig;
2991 token = MONO_TOKEN_METHOD_DEF | (i + 1);
2992 method = mono_get_method (acfg->image, token, NULL);
2994 sig = mono_method_signature (method);
2996 if (sig->hasthis && (method->klass->marshalbyref || method->klass == mono_defaults.object_class)) {
2997 m = mono_marshal_get_remoting_invoke_with_check (method);
2999 add_method (acfg, m);
3004 /* delegate-invoke wrappers */
3005 for (i = 0; i < acfg->image->tables [MONO_TABLE_TYPEDEF].rows; ++i) {
3007 MonoCustomAttrInfo *cattr;
3009 token = MONO_TOKEN_TYPE_DEF | (i + 1);
3010 klass = mono_class_get (acfg->image, token);
3013 mono_loader_clear_error ();
3017 if (klass->delegate && klass != mono_defaults.delegate_class && klass != mono_defaults.multicastdelegate_class && !klass->generic_container) {
3018 method = mono_get_delegate_invoke (klass);
3020 m = mono_marshal_get_delegate_invoke (method, NULL);
3022 add_method (acfg, m);
3024 method = mono_class_get_method_from_name_flags (klass, "BeginInvoke", -1, 0);
3026 add_method (acfg, mono_marshal_get_delegate_begin_invoke (method));
3028 method = mono_class_get_method_from_name_flags (klass, "EndInvoke", -1, 0);
3030 add_method (acfg, mono_marshal_get_delegate_end_invoke (method));
3032 cattr = mono_custom_attrs_from_class (klass);
3037 for (j = 0; j < cattr->num_attrs; ++j)
3038 if (cattr->attrs [j].ctor && (!strcmp (cattr->attrs [j].ctor->klass->name, "MonoNativeFunctionWrapperAttribute") || !strcmp (cattr->attrs [j].ctor->klass->name, "UnmanagedFunctionPointerAttribute")))
3040 if (j < cattr->num_attrs)
3041 add_method (acfg, mono_marshal_get_native_func_wrapper_aot (klass));
3046 /* Synchronized wrappers */
3047 for (i = 0; i < acfg->image->tables [MONO_TABLE_METHOD].rows; ++i) {
3048 token = MONO_TOKEN_METHOD_DEF | (i + 1);
3049 method = mono_get_method (acfg->image, token, NULL);
3051 if (method->iflags & METHOD_IMPL_ATTRIBUTE_SYNCHRONIZED && !method->is_generic)
3052 add_method (acfg, mono_marshal_get_synchronized_wrapper (method));
3055 /* pinvoke wrappers */
3056 for (i = 0; i < acfg->image->tables [MONO_TABLE_METHOD].rows; ++i) {
3058 guint32 token = MONO_TOKEN_METHOD_DEF | (i + 1);
3060 method = mono_get_method (acfg->image, token, NULL);
3062 if ((method->flags & METHOD_ATTRIBUTE_PINVOKE_IMPL) ||
3063 (method->iflags & METHOD_IMPL_ATTRIBUTE_INTERNAL_CALL)) {
3064 add_method (acfg, mono_marshal_get_native_wrapper (method, TRUE, TRUE));
3068 /* native-to-managed wrappers */
3069 for (i = 0; i < acfg->image->tables [MONO_TABLE_METHOD].rows; ++i) {
3071 guint32 token = MONO_TOKEN_METHOD_DEF | (i + 1);
3072 MonoCustomAttrInfo *cattr;
3075 method = mono_get_method (acfg->image, token, NULL);
3078 * Only generate native-to-managed wrappers for methods which have an
3079 * attribute named MonoPInvokeCallbackAttribute. We search for the attribute by
3080 * name to avoid defining a new assembly to contain it.
3082 cattr = mono_custom_attrs_from_method (method);
3085 for (j = 0; j < cattr->num_attrs; ++j)
3086 if (cattr->attrs [j].ctor && !strcmp (cattr->attrs [j].ctor->klass->name, "MonoPInvokeCallbackAttribute"))
3088 if (j < cattr->num_attrs) {
3089 MonoCustomAttrEntry *e = &cattr->attrs [j];
3090 MonoMethodSignature *sig = mono_method_signature (e->ctor);
3091 const char *p = (const char*)e->data;
3093 int slen, num_named, named_type, data_type;
3097 char *export_name = NULL;
3098 MonoMethod *wrapper;
3100 /* this cannot be enforced by the C# compiler so we must give the user some warning before aborting */
3101 if (!(method->flags & METHOD_ATTRIBUTE_STATIC)) {
3102 g_warning ("AOT restriction: Method '%s' must be static since it is decorated with [MonoPInvokeCallback]. See http://ios.xamarin.com/Documentation/Limitations#Reverse_Callbacks",
3103 mono_method_full_name (method, TRUE));
3107 g_assert (sig->param_count == 1);
3108 g_assert (sig->params [0]->type == MONO_TYPE_CLASS && !strcmp (mono_class_from_mono_type (sig->params [0])->name, "Type"));
3111 * Decode the cattr manually since we can't create objects
3112 * during aot compilation.
3118 /* From load_cattr_value () in reflection.c */
3119 slen = mono_metadata_decode_value (p, &p);
3120 n = g_memdup (p, slen + 1);
3122 t = mono_reflection_type_from_name (n, acfg->image);
3126 klass = mono_class_from_mono_type (t);
3127 g_assert (klass->parent == mono_defaults.multicastdelegate_class);
3131 num_named = read16 (p);
3134 g_assert (num_named < 2);
3135 if (num_named == 1) {
3138 MonoType *prop_type;
3140 /* parse ExportSymbol attribute */
3142 named_type = *named;
3147 name_len = mono_metadata_decode_blob_size (named, &named);
3148 name = g_malloc (name_len + 1);
3149 memcpy (name, named, name_len);
3150 name [name_len] = 0;
3153 g_assert (named_type == 0x54);
3154 g_assert (!strcmp (name, "ExportSymbol"));
3156 prop_type = &mono_defaults.string_class->byval_arg;
3158 /* load_cattr_value (), string case */
3159 g_assert (*named != (char)0xff);
3160 slen = mono_metadata_decode_value (named, &named);
3161 export_name = g_malloc (slen + 1);
3162 memcpy (export_name, named, slen);
3163 export_name [slen] = 0;
3167 wrapper = mono_marshal_get_managed_wrapper (method, klass, 0);
3168 add_method (acfg, wrapper);
3170 g_hash_table_insert (acfg->export_names, wrapper, export_name);
3174 if ((method->flags & METHOD_ATTRIBUTE_PINVOKE_IMPL) ||
3175 (method->iflags & METHOD_IMPL_ATTRIBUTE_INTERNAL_CALL)) {
3176 add_method (acfg, mono_marshal_get_native_wrapper (method, TRUE, TRUE));
3180 /* StructureToPtr/PtrToStructure wrappers */
3181 for (i = 0; i < acfg->image->tables [MONO_TABLE_TYPEDEF].rows; ++i) {
3184 token = MONO_TOKEN_TYPE_DEF | (i + 1);
3185 klass = mono_class_get (acfg->image, token);
3188 mono_loader_clear_error ();
3192 if (klass->valuetype && !klass->generic_container && can_marshal_struct (klass)) {
3193 add_method (acfg, mono_marshal_get_struct_to_ptr (klass));
3194 add_method (acfg, mono_marshal_get_ptr_to_struct (klass));
3200 has_type_vars (MonoClass *klass)
3202 if ((klass->byval_arg.type == MONO_TYPE_VAR) || (klass->byval_arg.type == MONO_TYPE_MVAR))
3205 return has_type_vars (klass->element_class);
3206 if (klass->generic_class) {
3207 MonoGenericContext *context = &klass->generic_class->context;
3208 if (context->class_inst) {
3211 for (i = 0; i < context->class_inst->type_argc; ++i)
3212 if (has_type_vars (mono_class_from_mono_type (context->class_inst->type_argv [i])))
3220 method_has_type_vars (MonoMethod *method)
3222 if (has_type_vars (method->klass))
3225 if (method->is_inflated) {
3226 MonoGenericContext *context = mono_method_get_context (method);
3227 if (context->method_inst) {
3230 for (i = 0; i < context->method_inst->type_argc; ++i)
3231 if (has_type_vars (mono_class_from_mono_type (context->method_inst->type_argv [i])))
3238 static void add_generic_class_with_depth (MonoAotCompile *acfg, MonoClass *klass, int depth, const char *ref);
3241 add_generic_class (MonoAotCompile *acfg, MonoClass *klass, gboolean force, const char *ref)
3243 /* This might lead to a huge code blowup so only do it if neccesary */
3244 if (!acfg->aot_opts.full_aot && !force)
3247 add_generic_class_with_depth (acfg, klass, 0, ref);
3251 check_type_depth (MonoType *t, int depth)
3259 case MONO_TYPE_GENERICINST: {
3260 MonoGenericClass *gklass = t->data.generic_class;
3261 MonoGenericInst *ginst = gklass->context.class_inst;
3264 for (i = 0; i < ginst->type_argc; ++i) {
3265 if (check_type_depth (ginst->type_argv [i], depth + 1))
3279 * add_generic_class:
3281 * Add all methods of a generic class.
3284 add_generic_class_with_depth (MonoAotCompile *acfg, MonoClass *klass, int depth, const char *ref)
3287 MonoClassField *field;
3290 if (!acfg->ginst_hash)
3291 acfg->ginst_hash = g_hash_table_new (NULL, NULL);
3293 mono_class_init (klass);
3295 if (klass->generic_class && klass->generic_class->context.class_inst->is_open)
3298 if (has_type_vars (klass))
3301 if (!klass->generic_class && !klass->rank)
3304 if (!acfg->ginst_hash)
3305 acfg->ginst_hash = g_hash_table_new (NULL, NULL);
3307 if (g_hash_table_lookup (acfg->ginst_hash, klass))
3310 if (check_type_depth (&klass->byval_arg, 0))
3313 if (acfg->aot_opts.log_generics)
3314 printf ("%*sAdding generic instance %s [%s].\n", depth, "", mono_type_full_name (&klass->byval_arg), ref);
3316 g_hash_table_insert (acfg->ginst_hash, klass, klass);
3319 while ((method = mono_class_get_methods (klass, &iter))) {
3320 if (mono_method_is_generic_sharable_impl_full (method, FALSE, FALSE))
3324 if (method->is_generic)
3329 * FIXME: Instances which are referenced by these methods are not added,
3330 * for example Array.Resize<int> for List<int>.Add ().
3332 add_extra_method_with_depth (acfg, method, depth + 1);
3336 while ((field = mono_class_get_fields (klass, &iter))) {
3337 if (field->type->type == MONO_TYPE_GENERICINST)
3338 add_generic_class_with_depth (acfg, mono_class_from_mono_type (field->type), depth + 1, "field");
3341 if (klass->delegate) {
3342 method = mono_get_delegate_invoke (klass);
3344 method = mono_marshal_get_delegate_invoke (method, NULL);
3346 if (acfg->aot_opts.log_generics)
3347 printf ("%*sAdding method %s.\n", depth, "", mono_method_full_name (method, TRUE));
3349 add_method (acfg, method);
3352 /* Add superclasses */
3354 add_generic_class_with_depth (acfg, klass->parent, depth, "parent");
3357 * For ICollection<T>, add instances of the helper methods
3358 * in Array, since a T[] could be cast to ICollection<T>.
3360 if (klass->image == mono_defaults.corlib && !strcmp (klass->name_space, "System.Collections.Generic") &&
3361 (!strcmp(klass->name, "ICollection`1") || !strcmp (klass->name, "IEnumerable`1") || !strcmp (klass->name, "IList`1") || !strcmp (klass->name, "IEnumerator`1"))) {
3362 MonoClass *tclass = mono_class_from_mono_type (klass->generic_class->context.class_inst->type_argv [0]);
3363 MonoClass *array_class = mono_bounded_array_class_get (tclass, 1, FALSE);
3367 if (!strcmp (klass->name, "IEnumerator`1"))
3368 name_prefix = g_strdup_printf ("%s.%s", klass->name_space, "IEnumerable`1");
3370 name_prefix = g_strdup_printf ("%s.%s", klass->name_space, klass->name);
3372 /* Add the T[]/InternalEnumerator class */
3373 if (!strcmp (klass->name, "IEnumerable`1") || !strcmp (klass->name, "IEnumerator`1")) {
3377 while ((nclass = mono_class_get_nested_types (array_class->parent, &iter))) {
3378 if (!strcmp (nclass->name, "InternalEnumerator`1"))
3382 nclass = mono_class_inflate_generic_class (nclass, mono_generic_class_get_context (klass->generic_class));
3383 add_generic_class (acfg, nclass, FALSE, "ICollection<T>");
3387 while ((method = mono_class_get_methods (array_class, &iter))) {
3388 if (strstr (method->name, name_prefix)) {
3389 MonoMethod *m = mono_aot_get_array_helper_from_wrapper (method);
3391 add_extra_method_with_depth (acfg, m, depth);
3395 g_free (name_prefix);
3398 /* Add an instance of GenericComparer<T> which is created dynamically by Comparer<T> */
3399 if (klass->image == mono_defaults.corlib && !strcmp (klass->name_space, "System.Collections.Generic") && !strcmp (klass->name, "Comparer`1")) {
3400 MonoClass *tclass = mono_class_from_mono_type (klass->generic_class->context.class_inst->type_argv [0]);
3401 MonoClass *icomparable, *gcomparer;
3402 MonoGenericContext ctx;
3403 MonoType *args [16];
3405 memset (&ctx, 0, sizeof (ctx));
3407 icomparable = mono_class_from_name (mono_defaults.corlib, "System", "IComparable`1");
3408 g_assert (icomparable);
3409 args [0] = &tclass->byval_arg;
3410 ctx.class_inst = mono_metadata_get_generic_inst (1, args);
3412 if (mono_class_is_assignable_from (mono_class_inflate_generic_class (icomparable, &ctx), tclass)) {
3413 gcomparer = mono_class_from_name (mono_defaults.corlib, "System.Collections.Generic", "GenericComparer`1");
3414 g_assert (gcomparer);
3415 add_generic_class (acfg, mono_class_inflate_generic_class (gcomparer, &ctx), FALSE, "Comparer<T>");
3419 /* Add an instance of GenericEqualityComparer<T> which is created dynamically by EqualityComparer<T> */
3420 if (klass->image == mono_defaults.corlib && !strcmp (klass->name_space, "System.Collections.Generic") && !strcmp (klass->name, "EqualityComparer`1")) {
3421 MonoClass *tclass = mono_class_from_mono_type (klass->generic_class->context.class_inst->type_argv [0]);
3422 MonoClass *iface, *gcomparer;
3423 MonoGenericContext ctx;
3424 MonoType *args [16];
3426 memset (&ctx, 0, sizeof (ctx));
3428 iface = mono_class_from_name (mono_defaults.corlib, "System", "IEquatable`1");
3430 args [0] = &tclass->byval_arg;
3431 ctx.class_inst = mono_metadata_get_generic_inst (1, args);
3433 if (mono_class_is_assignable_from (mono_class_inflate_generic_class (iface, &ctx), tclass)) {
3434 gcomparer = mono_class_from_name (mono_defaults.corlib, "System.Collections.Generic", "GenericEqualityComparer`1");
3435 g_assert (gcomparer);
3436 add_generic_class (acfg, mono_class_inflate_generic_class (gcomparer, &ctx), FALSE, "EqualityComparer<T>");
3442 add_instances_of (MonoAotCompile *acfg, MonoClass *klass, MonoType **insts, int ninsts, gboolean force)
3445 MonoGenericContext ctx;
3446 MonoType *args [16];
3448 memset (&ctx, 0, sizeof (ctx));
3450 for (i = 0; i < ninsts; ++i) {
3451 args [0] = insts [i];
3452 ctx.class_inst = mono_metadata_get_generic_inst (1, args);
3453 add_generic_class (acfg, mono_class_inflate_generic_class (klass, &ctx), force, "");
3458 add_types_from_method_header (MonoAotCompile *acfg, MonoMethod *method)
3460 MonoMethodHeader *header;
3461 MonoMethodSignature *sig;
3464 depth = GPOINTER_TO_UINT (g_hash_table_lookup (acfg->method_depth, method));
3466 sig = mono_method_signature (method);
3469 for (j = 0; j < sig->param_count; ++j)
3470 if (sig->params [j]->type == MONO_TYPE_GENERICINST)
3471 add_generic_class_with_depth (acfg, mono_class_from_mono_type (sig->params [j]), depth + 1, "arg");
3474 header = mono_method_get_header (method);
3477 for (j = 0; j < header->num_locals; ++j)
3478 if (header->locals [j]->type == MONO_TYPE_GENERICINST)
3479 add_generic_class_with_depth (acfg, mono_class_from_mono_type (header->locals [j]), depth + 1, "local");
3484 * add_generic_instances:
3486 * Add instances referenced by the METHODSPEC/TYPESPEC table.
3489 add_generic_instances (MonoAotCompile *acfg)
3494 MonoGenericContext *context;
3496 for (i = 0; i < acfg->image->tables [MONO_TABLE_METHODSPEC].rows; ++i) {
3497 token = MONO_TOKEN_METHOD_SPEC | (i + 1);
3498 method = mono_get_method (acfg->image, token, NULL);
3503 if (method->klass->image != acfg->image)
3506 context = mono_method_get_context (method);
3508 if (context && ((context->class_inst && context->class_inst->is_open)))
3512 * For open methods, create an instantiation which can be passed to the JIT.
3513 * FIXME: Handle class_inst as well.
3515 if (context && context->method_inst && context->method_inst->is_open) {
3516 MonoGenericContext shared_context;
3517 MonoGenericInst *inst;
3518 MonoType **type_argv;
3520 MonoMethod *declaring_method;
3521 gboolean supported = TRUE;
3523 /* Check that the context doesn't contain open constructed types */
3524 if (context->class_inst) {
3525 inst = context->class_inst;
3526 for (i = 0; i < inst->type_argc; ++i) {
3527 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)
3529 if (mono_class_is_open_constructed_type (inst->type_argv [i]))
3533 if (context->method_inst) {
3534 inst = context->method_inst;
3535 for (i = 0; i < inst->type_argc; ++i) {
3536 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)
3538 if (mono_class_is_open_constructed_type (inst->type_argv [i]))
3546 memset (&shared_context, 0, sizeof (MonoGenericContext));
3548 inst = context->class_inst;
3550 type_argv = g_new0 (MonoType*, inst->type_argc);
3551 for (i = 0; i < inst->type_argc; ++i) {
3552 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)
3553 type_argv [i] = &mono_defaults.object_class->byval_arg;
3555 type_argv [i] = inst->type_argv [i];
3558 shared_context.class_inst = mono_metadata_get_generic_inst (inst->type_argc, type_argv);
3562 inst = context->method_inst;
3564 type_argv = g_new0 (MonoType*, inst->type_argc);
3565 for (i = 0; i < inst->type_argc; ++i) {
3566 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)
3567 type_argv [i] = &mono_defaults.object_class->byval_arg;
3569 type_argv [i] = inst->type_argv [i];
3572 shared_context.method_inst = mono_metadata_get_generic_inst (inst->type_argc, type_argv);
3576 if (method->is_generic || method->klass->generic_container)
3577 declaring_method = method;
3579 declaring_method = mono_method_get_declaring_generic_method (method);
3581 method = mono_class_inflate_generic_method (declaring_method, &shared_context);
3585 * If the method is fully sharable, it was already added in place of its
3586 * generic definition.
3588 if (mono_method_is_generic_sharable_impl_full (method, FALSE, FALSE))
3592 * FIXME: Partially shared methods are not shared here, so we end up with
3593 * many identical methods.
3595 add_extra_method (acfg, method);
3598 for (i = 0; i < acfg->image->tables [MONO_TABLE_TYPESPEC].rows; ++i) {
3601 token = MONO_TOKEN_TYPE_SPEC | (i + 1);
3603 klass = mono_class_get (acfg->image, token);
3604 if (!klass || klass->rank) {
3605 mono_loader_clear_error ();
3609 add_generic_class (acfg, klass, FALSE, "typespec");
3612 /* Add types of args/locals */
3613 for (i = 0; i < acfg->methods->len; ++i) {
3614 method = g_ptr_array_index (acfg->methods, i);
3615 add_types_from_method_header (acfg, method);
3618 if (acfg->image == mono_defaults.corlib) {
3620 MonoType *insts [256];
3623 insts [ninsts ++] = &mono_defaults.byte_class->byval_arg;
3624 insts [ninsts ++] = &mono_defaults.sbyte_class->byval_arg;
3625 insts [ninsts ++] = &mono_defaults.int16_class->byval_arg;
3626 insts [ninsts ++] = &mono_defaults.uint16_class->byval_arg;
3627 insts [ninsts ++] = &mono_defaults.int32_class->byval_arg;
3628 insts [ninsts ++] = &mono_defaults.uint32_class->byval_arg;
3629 insts [ninsts ++] = &mono_defaults.int64_class->byval_arg;
3630 insts [ninsts ++] = &mono_defaults.uint64_class->byval_arg;
3631 insts [ninsts ++] = &mono_defaults.single_class->byval_arg;
3632 insts [ninsts ++] = &mono_defaults.double_class->byval_arg;
3633 insts [ninsts ++] = &mono_defaults.char_class->byval_arg;
3634 insts [ninsts ++] = &mono_defaults.boolean_class->byval_arg;
3636 /* Add GenericComparer<T> instances for primitive types for Enum.ToString () */
3637 klass = mono_class_from_name (acfg->image, "System.Collections.Generic", "GenericComparer`1");
3639 add_instances_of (acfg, klass, insts, ninsts, TRUE);
3640 klass = mono_class_from_name (acfg->image, "System.Collections.Generic", "GenericEqualityComparer`1");
3642 add_instances_of (acfg, klass, insts, ninsts, TRUE);
3644 /* Add instances of the array generic interfaces for primitive types */
3645 /* This will add instances of the InternalArray_ helper methods in Array too */
3646 klass = mono_class_from_name (acfg->image, "System.Collections.Generic", "ICollection`1");
3648 add_instances_of (acfg, klass, insts, ninsts, TRUE);
3649 klass = mono_class_from_name (acfg->image, "System.Collections.Generic", "IList`1");
3651 add_instances_of (acfg, klass, insts, ninsts, TRUE);
3652 klass = mono_class_from_name (acfg->image, "System.Collections.Generic", "IEnumerable`1");
3654 add_instances_of (acfg, klass, insts, ninsts, TRUE);
3657 * Add a managed-to-native wrapper of Array.GetGenericValueImpl<object>, which is
3658 * used for all instances of GetGenericValueImpl by the AOT runtime.
3661 MonoGenericContext ctx;
3662 MonoType *args [16];
3663 MonoMethod *get_method;
3664 MonoClass *array_klass = mono_array_class_get (mono_defaults.object_class, 1)->parent;
3666 get_method = mono_class_get_method_from_name (array_klass, "GetGenericValueImpl", 2);
3669 memset (&ctx, 0, sizeof (ctx));
3670 args [0] = &mono_defaults.object_class->byval_arg;
3671 ctx.method_inst = mono_metadata_get_generic_inst (1, args);
3672 add_extra_method (acfg, mono_marshal_get_native_wrapper (mono_class_inflate_generic_method (get_method, &ctx), TRUE, TRUE));
3676 /* Same for CompareExchange<T>/Exchange<T> */
3678 MonoGenericContext ctx;
3679 MonoType *args [16];
3681 MonoClass *interlocked_klass = mono_class_from_name (mono_defaults.corlib, "System.Threading", "Interlocked");
3682 gpointer iter = NULL;
3684 while ((m = mono_class_get_methods (interlocked_klass, &iter))) {
3685 if ((!strcmp (m->name, "CompareExchange") || !strcmp (m->name, "Exchange")) && m->is_generic) {
3686 memset (&ctx, 0, sizeof (ctx));
3687 args [0] = &mono_defaults.object_class->byval_arg;
3688 ctx.method_inst = mono_metadata_get_generic_inst (1, args);
3689 add_extra_method (acfg, mono_marshal_get_native_wrapper (mono_class_inflate_generic_method (m, &ctx), TRUE, TRUE));
3697 * is_direct_callable:
3699 * Return whenever the method identified by JI is directly callable without
3700 * going through the PLT.
3703 is_direct_callable (MonoAotCompile *acfg, MonoMethod *method, MonoJumpInfo *patch_info)
3705 if ((patch_info->type == MONO_PATCH_INFO_METHOD) && (patch_info->data.method->klass->image == acfg->image)) {
3706 MonoCompile *callee_cfg = g_hash_table_lookup (acfg->method_to_cfg, patch_info->data.method);
3708 gboolean direct_callable = TRUE;
3710 if (direct_callable && !(!callee_cfg->has_got_slots && (callee_cfg->method->klass->flags & TYPE_ATTRIBUTE_BEFORE_FIELD_INIT)))
3711 direct_callable = FALSE;
3712 if ((callee_cfg->method->iflags & METHOD_IMPL_ATTRIBUTE_SYNCHRONIZED) && (!method || method->wrapper_type != MONO_WRAPPER_SYNCHRONIZED))
3713 // FIXME: Maybe call the wrapper directly ?
3714 direct_callable = FALSE;
3716 if (acfg->aot_opts.soft_debug || acfg->aot_opts.no_direct_calls) {
3717 /* Disable this so all calls go through load_method (), see the
3718 * mini_get_debug_options ()->load_aot_jit_info_eagerly = TRUE; line in
3719 * mono_debugger_agent_init ().
3721 direct_callable = FALSE;
3724 if (direct_callable)
3727 } else if ((patch_info->type == MONO_PATCH_INFO_ICALL_ADDR && patch_info->data.method->flags & METHOD_ATTRIBUTE_PINVOKE_IMPL)) {
3728 if (acfg->aot_opts.direct_pinvoke)
3730 } else if (patch_info->type == MONO_PATCH_INFO_ICALL_ADDR) {
3731 if (acfg->aot_opts.direct_icalls)
3740 get_pinvoke_import (MonoAotCompile *acfg, MonoMethod *method)
3742 MonoImage *image = method->klass->image;
3743 MonoMethodPInvoke *piinfo = (MonoMethodPInvoke *) method;
3744 MonoTableInfo *tables = image->tables;
3745 MonoTableInfo *im = &tables [MONO_TABLE_IMPLMAP];
3746 MonoTableInfo *mr = &tables [MONO_TABLE_MODULEREF];
3747 guint32 im_cols [MONO_IMPLMAP_SIZE];
3750 import = g_hash_table_lookup (acfg->method_to_pinvoke_import, method);
3754 if (!piinfo->implmap_idx || piinfo->implmap_idx > im->rows)
3757 mono_metadata_decode_row (im, piinfo->implmap_idx - 1, im_cols, MONO_IMPLMAP_SIZE);
3759 if (!im_cols [MONO_IMPLMAP_SCOPE] || im_cols [MONO_IMPLMAP_SCOPE] > mr->rows)
3762 import = g_strdup_printf ("%s", mono_metadata_string_heap (image, im_cols [MONO_IMPLMAP_NAME]));
3764 g_hash_table_insert (acfg->method_to_pinvoke_import, method, import);
3770 * emit_and_reloc_code:
3772 * Emit the native code in CODE, handling relocations along the way. If GOT_ONLY
3773 * is true, calls are made through the GOT too. This is used for emitting trampolines
3774 * in full-aot mode, since calls made from trampolines couldn't go through the PLT,
3775 * since trampolines are needed to make PTL work.
3778 emit_and_reloc_code (MonoAotCompile *acfg, MonoMethod *method, guint8 *code, guint32 code_len, MonoJumpInfo *relocs, gboolean got_only)
3780 int i, pindex, start_index, method_index;
3782 MonoJumpInfo *patch_info;
3783 MonoMethodHeader *header;
3784 gboolean skip, direct_call;
3786 const char *direct_call_target;
3787 const char *direct_pinvoke;
3790 header = mono_method_get_header (method);
3792 method_index = get_method_index (acfg, method);
3795 /* Collect and sort relocations */
3796 patches = g_ptr_array_new ();
3797 for (patch_info = relocs; patch_info; patch_info = patch_info->next)
3798 g_ptr_array_add (patches, patch_info);
3799 g_ptr_array_sort (patches, compare_patches);
3802 for (i = 0; i < code_len; i++) {
3804 for (pindex = start_index; pindex < patches->len; ++pindex) {
3805 patch_info = g_ptr_array_index (patches, pindex);
3806 if (patch_info->ip.i >= i)
3810 #ifdef MONO_ARCH_AOT_SUPPORTED
3812 if (patch_info && (patch_info->ip.i == i) && (pindex < patches->len)) {
3813 start_index = pindex;
3815 switch (patch_info->type) {
3816 case MONO_PATCH_INFO_NONE:
3818 case MONO_PATCH_INFO_GOT_OFFSET: {
3821 arch_emit_got_offset (acfg, code + i, &code_size);
3824 patch_info->type = MONO_PATCH_INFO_NONE;
3829 * If this patch is a call, try emitting a direct call instead of
3830 * through a PLT entry. This is possible if the called method is in
3831 * the same assembly and requires no initialization.
3833 direct_call = FALSE;
3834 if ((patch_info->type == MONO_PATCH_INFO_METHOD) && (patch_info->data.method->klass->image == acfg->image)) {
3835 if (!got_only && is_direct_callable (acfg, method, patch_info)) {
3836 MonoCompile *callee_cfg = g_hash_table_lookup (acfg->method_to_cfg, patch_info->data.method);
3837 //printf ("DIRECT: %s %s\n", method ? mono_method_full_name (method, TRUE) : "", mono_method_full_name (callee_cfg->method, TRUE));
3839 direct_call_target = callee_cfg->asm_symbol;
3840 patch_info->type = MONO_PATCH_INFO_NONE;
3841 acfg->stats.direct_calls ++;
3844 acfg->stats.all_calls ++;
3845 } else if (patch_info->type == MONO_PATCH_INFO_ICALL_ADDR) {
3846 if (!got_only && is_direct_callable (acfg, method, patch_info)) {
3847 if (!(patch_info->data.method->flags & METHOD_ATTRIBUTE_PINVOKE_IMPL))
3848 direct_pinvoke = mono_lookup_icall_symbol (patch_info->data.method);
3850 direct_pinvoke = get_pinvoke_import (acfg, patch_info->data.method);
3851 if (direct_pinvoke) {
3853 #if defined(TARGET_MACH)
3859 g_assert (strlen (direct_pinvoke) < 1000);
3860 direct_call_target = g_strdup_printf ("%s%s", prefix, direct_pinvoke);
3866 patch_info->type = MONO_PATCH_INFO_NONE;
3867 acfg->stats.direct_calls ++;
3870 if (!got_only && !direct_call) {
3871 MonoPltEntry *plt_entry = get_plt_entry (acfg, patch_info);
3873 /* This patch has a PLT entry, so we must emit a call to the PLT entry */
3875 direct_call_target = plt_entry->symbol;
3877 /* Nullify the patch */
3878 patch_info->type = MONO_PATCH_INFO_NONE;
3879 plt_entry->jit_used = TRUE;
3886 arch_emit_direct_call (acfg, direct_call_target, &call_size);
3891 got_slot = get_got_offset (acfg, patch_info);
3893 arch_emit_got_access (acfg, code + i, got_slot, &code_size);
3900 #endif /* MONO_ARCH_AOT_SUPPORTED */
3903 /* Find next patch */
3905 for (pindex = start_index; pindex < patches->len; ++pindex) {
3906 patch_info = g_ptr_array_index (patches, pindex);
3907 if (patch_info->ip.i >= i)
3911 /* Try to emit multiple bytes at once */
3912 if (pindex < patches->len && patch_info->ip.i > i) {
3913 emit_bytes (acfg, code + i, patch_info->ip.i - i);
3914 i = patch_info->ip.i - 1;
3916 emit_bytes (acfg, code + i, 1);
3925 * Modify SYMBOL so it only includes characters permissible in symbols.
3928 sanitize_symbol (char *symbol)
3930 int i, len = strlen (symbol);
3932 for (i = 0; i < len; ++i)
3933 if (!isalnum (symbol [i]) && (symbol [i] != '_'))
3938 get_debug_sym (MonoMethod *method, const char *prefix, GHashTable *cache)
3940 char *name1, *name2, *cached;
3941 int i, j, len, count;
3943 name1 = mono_method_full_name (method, TRUE);
3944 len = strlen (name1);
3945 name2 = malloc (strlen (prefix) + len + 16);
3946 memcpy (name2, prefix, strlen (prefix));
3947 j = strlen (prefix);
3948 for (i = 0; i < len; ++i) {
3949 if (isalnum (name1 [i])) {
3950 name2 [j ++] = name1 [i];
3951 } else if (name1 [i] == ' ' && name1 [i + 1] == '(' && name1 [i + 2] == ')') {
3953 } else if (name1 [i] == ',' && name1 [i + 1] == ' ') {
3956 } else if (name1 [i] == '(' || name1 [i] == ')' || name1 [i] == '>') {
3965 while (g_hash_table_lookup (cache, name2)) {
3966 sprintf (name2 + j, "_%d", count);
3970 cached = g_strdup (name2);
3971 g_hash_table_insert (cache, cached, cached);
3977 emit_method_code (MonoAotCompile *acfg, MonoCompile *cfg)
3982 char *debug_sym = NULL;
3983 char *symbol = NULL;
3984 int func_alignment = AOT_FUNC_ALIGNMENT;
3985 MonoMethodHeader *header;
3988 method = cfg->orig_method;
3989 code = cfg->native_code;
3990 header = cfg->header;
3992 method_index = get_method_index (acfg, method);
3993 symbol = g_strdup_printf ("%sme_%x", acfg->temp_prefix, method_index);
3996 /* Make the labels local */
3997 emit_section_change (acfg, ".text", 0);
3998 emit_alignment (acfg, func_alignment);
4000 if (acfg->global_symbols && acfg->need_no_dead_strip)
4001 fprintf (acfg->fp, " .no_dead_strip %s\n", cfg->asm_symbol);
4003 emit_label (acfg, cfg->asm_symbol);
4005 if (acfg->aot_opts.write_symbols && !acfg->global_symbols) {
4007 * Write a C style symbol for every method, this has two uses:
4008 * - it works on platforms where the dwarf debugging info is not
4010 * - it allows the setting of breakpoints of aot-ed methods.
4012 debug_sym = get_debug_sym (method, "", acfg->method_label_hash);
4014 if (acfg->need_no_dead_strip)
4015 fprintf (acfg->fp, " .no_dead_strip %s\n", debug_sym);
4016 emit_local_symbol (acfg, debug_sym, symbol, TRUE);
4017 emit_label (acfg, debug_sym);
4020 export_name = g_hash_table_lookup (acfg->export_names, method);
4022 /* Emit a global symbol for the method */
4023 emit_global_inner (acfg, export_name, TRUE);
4024 emit_label (acfg, export_name);
4027 if (cfg->verbose_level > 0)
4028 g_print ("Method %s emitted as %s\n", mono_method_full_name (method, TRUE), cfg->asm_symbol);
4030 acfg->stats.code_size += cfg->code_len;
4032 acfg->cfgs [method_index]->got_offset = acfg->got_offset;
4034 emit_and_reloc_code (acfg, method, code, cfg->code_len, cfg->patch_info, FALSE);
4038 if (acfg->aot_opts.write_symbols) {
4039 emit_symbol_size (acfg, debug_sym, ".");
4043 emit_label (acfg, symbol);
4050 * Encode PATCH_INFO into its disk representation.
4053 encode_patch (MonoAotCompile *acfg, MonoJumpInfo *patch_info, guint8 *buf, guint8 **endbuf)
4057 switch (patch_info->type) {
4058 case MONO_PATCH_INFO_NONE:
4060 case MONO_PATCH_INFO_IMAGE:
4061 encode_value (get_image_index (acfg, patch_info->data.image), p, &p);
4063 case MONO_PATCH_INFO_MSCORLIB_GOT_ADDR:
4064 case MONO_PATCH_INFO_GC_CARD_TABLE_ADDR:
4065 case MONO_PATCH_INFO_CASTCLASS_CACHE:
4067 case MONO_PATCH_INFO_METHOD_REL:
4068 encode_value ((gint)patch_info->data.offset, p, &p);
4070 case MONO_PATCH_INFO_SWITCH: {
4071 gpointer *table = (gpointer *)patch_info->data.table->table;
4074 encode_value (patch_info->data.table->table_size, p, &p);
4075 for (k = 0; k < patch_info->data.table->table_size; k++)
4076 encode_value ((int)(gssize)table [k], p, &p);
4079 case MONO_PATCH_INFO_METHODCONST:
4080 case MONO_PATCH_INFO_METHOD:
4081 case MONO_PATCH_INFO_METHOD_JUMP:
4082 case MONO_PATCH_INFO_ICALL_ADDR:
4083 case MONO_PATCH_INFO_METHOD_RGCTX:
4084 encode_method_ref (acfg, patch_info->data.method, p, &p);
4086 case MONO_PATCH_INFO_INTERNAL_METHOD:
4087 case MONO_PATCH_INFO_JIT_ICALL_ADDR: {
4088 guint32 len = strlen (patch_info->data.name);
4090 encode_value (len, p, &p);
4092 memcpy (p, patch_info->data.name, len);
4097 case MONO_PATCH_INFO_LDSTR: {
4098 guint32 image_index = get_image_index (acfg, patch_info->data.token->image);
4099 guint32 token = patch_info->data.token->token;
4100 g_assert (mono_metadata_token_code (token) == MONO_TOKEN_STRING);
4101 encode_value (image_index, p, &p);
4102 encode_value (patch_info->data.token->token - MONO_TOKEN_STRING, p, &p);
4105 case MONO_PATCH_INFO_RVA:
4106 case MONO_PATCH_INFO_DECLSEC:
4107 case MONO_PATCH_INFO_LDTOKEN:
4108 case MONO_PATCH_INFO_TYPE_FROM_HANDLE:
4109 encode_value (get_image_index (acfg, patch_info->data.token->image), p, &p);
4110 encode_value (patch_info->data.token->token, p, &p);
4111 encode_value (patch_info->data.token->has_context, p, &p);
4112 if (patch_info->data.token->has_context)
4113 encode_generic_context (acfg, &patch_info->data.token->context, p, &p);
4115 case MONO_PATCH_INFO_EXC_NAME: {
4116 MonoClass *ex_class;
4119 mono_class_from_name (mono_defaults.exception_class->image,
4120 "System", patch_info->data.target);
4121 g_assert (ex_class);
4122 encode_klass_ref (acfg, ex_class, p, &p);
4125 case MONO_PATCH_INFO_R4:
4126 encode_value (*((guint32 *)patch_info->data.target), p, &p);
4128 case MONO_PATCH_INFO_R8:
4129 encode_value (((guint32 *)patch_info->data.target) [MINI_LS_WORD_IDX], p, &p);
4130 encode_value (((guint32 *)patch_info->data.target) [MINI_MS_WORD_IDX], p, &p);
4132 case MONO_PATCH_INFO_VTABLE:
4133 case MONO_PATCH_INFO_CLASS:
4134 case MONO_PATCH_INFO_IID:
4135 case MONO_PATCH_INFO_ADJUSTED_IID:
4136 encode_klass_ref (acfg, patch_info->data.klass, p, &p);
4138 case MONO_PATCH_INFO_CLASS_INIT:
4139 case MONO_PATCH_INFO_DELEGATE_TRAMPOLINE:
4140 encode_klass_ref (acfg, patch_info->data.klass, p, &p);
4142 case MONO_PATCH_INFO_FIELD:
4143 case MONO_PATCH_INFO_SFLDA:
4144 encode_field_info (acfg, patch_info->data.field, p, &p);
4146 case MONO_PATCH_INFO_INTERRUPTION_REQUEST_FLAG:
4148 case MONO_PATCH_INFO_RGCTX_FETCH: {
4149 MonoJumpInfoRgctxEntry *entry = patch_info->data.rgctx_entry;
4154 * entry->method has a lenghtly encoding and multiple rgctx_fetch entries
4155 * reference the same method, so encode the method only once.
4157 offset = GPOINTER_TO_UINT (g_hash_table_lookup (acfg->method_blob_hash, entry->method));
4159 buf2 = g_malloc (1024);
4162 encode_method_ref (acfg, entry->method, p2, &p2);
4163 g_assert (p2 - buf2 < 1024);
4165 offset = add_to_blob (acfg, buf2, p2 - buf2);
4168 g_hash_table_insert (acfg->method_blob_hash, entry->method, GUINT_TO_POINTER (offset + 1));
4173 encode_value (offset, p, &p);
4174 g_assert (entry->info_type < 256);
4175 g_assert (entry->data->type < 256);
4176 encode_value ((entry->in_mrgctx ? 1 : 0) | (entry->info_type << 1) | (entry->data->type << 9), p, &p);
4177 encode_patch (acfg, entry->data, p, &p);
4180 case MONO_PATCH_INFO_GENERIC_CLASS_INIT:
4181 case MONO_PATCH_INFO_MONITOR_ENTER:
4182 case MONO_PATCH_INFO_MONITOR_EXIT:
4183 case MONO_PATCH_INFO_SEQ_POINT_INFO:
4185 case MONO_PATCH_INFO_LLVM_IMT_TRAMPOLINE:
4186 encode_method_ref (acfg, patch_info->data.imt_tramp->method, p, &p);
4187 encode_value (patch_info->data.imt_tramp->vt_offset, p, &p);
4189 case MONO_PATCH_INFO_SIGNATURE:
4190 encode_signature (acfg, (MonoMethodSignature*)patch_info->data.target, p, &p);
4193 g_warning ("unable to handle jump info %d", patch_info->type);
4194 g_assert_not_reached ();
4201 encode_patch_list (MonoAotCompile *acfg, GPtrArray *patches, int n_patches, int first_got_offset, guint8 *buf, guint8 **endbuf)
4204 guint32 pindex, offset;
4205 MonoJumpInfo *patch_info;
4207 encode_value (n_patches, p, &p);
4209 for (pindex = 0; pindex < patches->len; ++pindex) {
4210 patch_info = g_ptr_array_index (patches, pindex);
4212 if (patch_info->type == MONO_PATCH_INFO_NONE || patch_info->type == MONO_PATCH_INFO_BB)
4216 offset = get_got_offset (acfg, patch_info);
4217 encode_value (offset, p, &p);
4224 emit_method_info (MonoAotCompile *acfg, MonoCompile *cfg)
4228 int pindex, buf_size, n_patches;
4230 MonoJumpInfo *patch_info;
4231 MonoMethodHeader *header;
4232 guint32 method_index;
4234 guint32 first_got_offset;
4236 method = cfg->orig_method;
4237 header = mono_method_get_header (method);
4239 method_index = get_method_index (acfg, method);
4241 /* Sort relocations */
4242 patches = g_ptr_array_new ();
4243 for (patch_info = cfg->patch_info; patch_info; patch_info = patch_info->next)
4244 g_ptr_array_add (patches, patch_info);
4245 g_ptr_array_sort (patches, compare_patches);
4247 first_got_offset = acfg->cfgs [method_index]->got_offset;
4249 /**********************/
4250 /* Encode method info */
4251 /**********************/
4253 buf_size = (patches->len < 1000) ? 40960 : 40960 + (patches->len * 64);
4254 p = buf = g_malloc (buf_size);
4256 if (mono_class_get_cctor (method->klass))
4257 encode_klass_ref (acfg, method->klass, p, &p);
4259 /* Not needed when loading the method */
4260 encode_value (0, p, &p);
4263 if (cfg->opt & MONO_OPT_SHARED) {
4264 encode_value (g_list_length (cfg->ldstr_list), p, &p);
4265 for (l = cfg->ldstr_list; l; l = l->next) {
4266 encode_value ((long)l->data, p, &p);
4270 /* Used only in shared mode */
4271 g_assert (!cfg->ldstr_list);
4274 for (pindex = 0; pindex < patches->len; ++pindex) {
4275 patch_info = g_ptr_array_index (patches, pindex);
4277 if ((patch_info->type == MONO_PATCH_INFO_GOT_OFFSET) ||
4278 (patch_info->type == MONO_PATCH_INFO_NONE)) {
4279 patch_info->type = MONO_PATCH_INFO_NONE;
4284 if ((patch_info->type == MONO_PATCH_INFO_IMAGE) && (patch_info->data.image == acfg->image)) {
4285 /* Stored in a GOT slot initialized at module load time */
4286 patch_info->type = MONO_PATCH_INFO_NONE;
4290 if (patch_info->type == MONO_PATCH_INFO_GC_CARD_TABLE_ADDR) {
4291 /* Stored in a GOT slot initialized at module load time */
4292 patch_info->type = MONO_PATCH_INFO_NONE;
4296 if (is_plt_patch (patch_info)) {
4297 /* Calls are made through the PLT */
4298 patch_info->type = MONO_PATCH_INFO_NONE;
4306 g_assert (cfg->has_got_slots);
4308 encode_patch_list (acfg, patches, n_patches, first_got_offset, p, &p);
4310 acfg->stats.info_size += p - buf;
4312 g_assert (p - buf < buf_size);
4314 cfg->method_info_offset = add_to_blob (acfg, buf, p - buf);
4319 get_unwind_info_offset (MonoAotCompile *acfg, guint8 *encoded, guint32 encoded_len)
4321 guint32 cache_index;
4324 /* Reuse the unwind module to canonize and store unwind info entries */
4325 cache_index = mono_cache_unwind_info (encoded, encoded_len);
4327 /* Use +/- 1 to distinguish 0s from missing entries */
4328 offset = GPOINTER_TO_UINT (g_hash_table_lookup (acfg->unwind_info_offsets, GUINT_TO_POINTER (cache_index + 1)));
4336 * It would be easier to use assembler symbols, but the caller needs an
4339 offset = acfg->unwind_info_offset;
4340 g_hash_table_insert (acfg->unwind_info_offsets, GUINT_TO_POINTER (cache_index + 1), GUINT_TO_POINTER (offset + 1));
4341 g_ptr_array_add (acfg->unwind_ops, GUINT_TO_POINTER (cache_index));
4344 encode_value (encoded_len, p, &p);
4346 acfg->unwind_info_offset += encoded_len + (p - buf);
4352 emit_exception_debug_info (MonoAotCompile *acfg, MonoCompile *cfg)
4355 int i, k, buf_size, method_index;
4356 guint32 debug_info_size;
4358 MonoMethodHeader *header;
4359 guint8 *p, *buf, *debug_info;
4360 MonoJitInfo *jinfo = cfg->jit_info;
4362 gboolean use_unwind_ops = FALSE;
4363 MonoSeqPointInfo *seq_points;
4365 method = cfg->orig_method;
4366 code = cfg->native_code;
4367 header = cfg->header;
4369 method_index = get_method_index (acfg, method);
4371 if (!acfg->aot_opts.nodebug) {
4372 mono_debug_serialize_debug_info (cfg, &debug_info, &debug_info_size);
4375 debug_info_size = 0;
4378 seq_points = cfg->seq_point_info;
4380 buf_size = header->num_clauses * 256 + debug_info_size + 2048 + (seq_points ? (seq_points->len * 64) : 0) + cfg->gc_map_size;
4381 p = buf = g_malloc (buf_size);
4383 #ifdef MONO_ARCH_HAVE_XP_UNWIND
4384 use_unwind_ops = cfg->unwind_ops != NULL;
4387 flags = (jinfo->has_generic_jit_info ? 1 : 0) | (use_unwind_ops ? 2 : 0) | (header->num_clauses ? 4 : 0) | (seq_points ? 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);
4389 encode_value (flags, p, &p);
4391 if (use_unwind_ops) {
4392 guint32 encoded_len;
4396 * This is a duplicate of the data in the .debug_frame section, but that
4397 * section cannot be accessed using the dl interface.
4399 encoded = mono_unwind_ops_encode (cfg->unwind_ops, &encoded_len);
4400 encode_value (get_unwind_info_offset (acfg, encoded, encoded_len), p, &p);
4403 encode_value (jinfo->used_regs, p, &p);
4406 /*Encode the number of holes before the number of clauses to make decoding easier*/
4407 if (jinfo->has_try_block_holes) {
4408 MonoTryBlockHoleTableJitInfo *table = mono_jit_info_get_try_block_hole_table_info (jinfo);
4409 encode_value (table->num_holes, p, &p);
4412 /* Exception table */
4413 if (cfg->compile_llvm) {
4415 * When using LLVM, we can't emit some data, like pc offsets, this reg/offset etc.,
4416 * since the information is only available to llc. Instead, we let llc save the data
4417 * into the LSDA, and read it from there at runtime.
4419 /* The assembly might be CIL stripped so emit the data ourselves */
4420 if (header->num_clauses)
4421 encode_value (header->num_clauses, p, &p);
4423 for (k = 0; k < header->num_clauses; ++k) {
4424 MonoExceptionClause *clause;
4426 clause = &header->clauses [k];
4428 encode_value (clause->flags, p, &p);
4429 if (clause->data.catch_class) {
4430 encode_value (1, p, &p);
4431 encode_klass_ref (acfg, clause->data.catch_class, p, &p);
4433 encode_value (0, p, &p);
4436 /* Emit a list of nesting clauses */
4437 for (i = 0; i < header->num_clauses; ++i) {
4439 MonoExceptionClause *clause1 = &header->clauses [cindex1];
4441 MonoExceptionClause *clause2 = &header->clauses [cindex2];
4443 if (cindex1 != cindex2 && clause1->try_offset >= clause2->try_offset && clause1->handler_offset <= clause2->handler_offset)
4444 encode_value (i, p, &p);
4446 encode_value (-1, p, &p);
4449 if (jinfo->num_clauses)
4450 encode_value (jinfo->num_clauses, p, &p);
4452 for (k = 0; k < jinfo->num_clauses; ++k) {
4453 MonoJitExceptionInfo *ei = &jinfo->clauses [k];
4455 encode_value (ei->flags, p, &p);
4456 encode_value (ei->exvar_offset, p, &p);
4458 if (ei->flags == MONO_EXCEPTION_CLAUSE_FILTER || ei->flags == MONO_EXCEPTION_CLAUSE_FINALLY)
4459 encode_value ((gint)((guint8*)ei->data.filter - code), p, &p);
4461 if (ei->data.catch_class) {
4462 encode_value (1, p, &p);
4463 encode_klass_ref (acfg, ei->data.catch_class, p, &p);
4465 encode_value (0, p, &p);
4469 encode_value ((gint)((guint8*)ei->try_start - code), p, &p);
4470 encode_value ((gint)((guint8*)ei->try_end - code), p, &p);
4471 encode_value ((gint)((guint8*)ei->handler_start - code), p, &p);
4475 if (jinfo->has_generic_jit_info) {
4476 MonoGenericJitInfo *gi = mono_jit_info_get_generic_jit_info (jinfo);
4480 encode_value (gi->nlocs, p, &p);
4482 for (i = 0; i < gi->nlocs; ++i) {
4483 MonoDwarfLocListEntry *entry = &gi->locations [i];
4485 encode_value (entry->is_reg ? 1 : 0, p, &p);
4486 encode_value (entry->reg, p, &p);
4488 encode_value (entry->offset, p, &p);
4490 g_assert (entry->from == 0);
4492 encode_value (entry->from, p, &p);
4493 encode_value (entry->to, p, &p);
4496 if (!cfg->compile_llvm) {
4497 encode_value (gi->has_this ? 1 : 0, p, &p);
4498 encode_value (gi->this_reg, p, &p);
4499 encode_value (gi->this_offset, p, &p);
4504 * Need to encode jinfo->method too, since it is not equal to 'method'
4505 * when using generic sharing.
4507 encode_method_ref (acfg, jinfo->method, p, &p);
4510 if (jinfo->has_try_block_holes) {
4511 MonoTryBlockHoleTableJitInfo *table = mono_jit_info_get_try_block_hole_table_info (jinfo);
4512 for (i = 0; i < table->num_holes; ++i) {
4513 MonoTryBlockHoleJitInfo *hole = &table->holes [i];
4514 encode_value (hole->clause, p, &p);
4515 encode_value (hole->length, p, &p);
4516 encode_value (hole->offset, p, &p);
4520 if (jinfo->has_arch_eh_info) {
4521 MonoArchEHJitInfo *eh_info;
4523 eh_info = mono_jit_info_get_arch_eh_info (jinfo);
4524 encode_value (eh_info->stack_size, p, &p);
4528 int il_offset, native_offset, last_il_offset, last_native_offset, j;
4530 encode_value (seq_points->len, p, &p);
4531 last_il_offset = last_native_offset = 0;
4532 for (i = 0; i < seq_points->len; ++i) {
4533 SeqPoint *sp = &seq_points->seq_points [i];
4534 il_offset = sp->il_offset;
4535 native_offset = sp->native_offset;
4536 encode_value (il_offset - last_il_offset, p, &p);
4537 encode_value (native_offset - last_native_offset, p, &p);
4538 last_il_offset = il_offset;
4539 last_native_offset = native_offset;
4541 encode_value (sp->next_len, p, &p);
4542 for (j = 0; j < sp->next_len; ++j)
4543 encode_value (sp->next [j], p, &p);
4547 g_assert (debug_info_size < buf_size);
4549 encode_value (debug_info_size, p, &p);
4550 if (debug_info_size) {
4551 memcpy (p, debug_info, debug_info_size);
4552 p += debug_info_size;
4553 g_free (debug_info);
4558 encode_value (cfg->gc_map_size, p, &p);
4559 /* The GC map requires 4 bytes of alignment */
4560 while ((gsize)p % 4)
4562 memcpy (p, cfg->gc_map, cfg->gc_map_size);
4563 p += cfg->gc_map_size;
4566 acfg->stats.ex_info_size += p - buf;
4568 g_assert (p - buf < buf_size);
4571 /* The GC Map requires 4 byte alignment */
4572 cfg->ex_info_offset = add_to_blob_aligned (acfg, buf, p - buf, cfg->gc_map ? 4 : 1);
4577 emit_klass_info (MonoAotCompile *acfg, guint32 token)
4579 MonoClass *klass = mono_class_get (acfg->image, token);
4581 int i, buf_size, res;
4582 gboolean no_special_static, cant_encode;
4583 gpointer iter = NULL;
4586 mono_loader_clear_error ();
4590 p = buf = g_malloc (buf_size);
4592 /* Mark as unusable */
4593 encode_value (-1, p, &p);
4595 res = add_to_blob (acfg, buf, p - buf);
4601 buf_size = 10240 + (klass->vtable_size * 16);
4602 p = buf = g_malloc (buf_size);
4606 mono_class_init (klass);
4608 mono_class_get_nested_types (klass, &iter);
4609 g_assert (klass->nested_classes_inited);
4611 mono_class_setup_vtable (klass);
4614 * Emit all the information which is required for creating vtables so
4615 * the runtime does not need to create the MonoMethod structures which
4616 * take up a lot of space.
4619 no_special_static = !mono_class_has_special_static_fields (klass);
4621 /* Check whenever we have enough info to encode the vtable */
4622 cant_encode = FALSE;
4623 for (i = 0; i < klass->vtable_size; ++i) {
4624 MonoMethod *cm = klass->vtable [i];
4626 if (cm && mono_method_signature (cm)->is_inflated && !g_hash_table_lookup (acfg->token_info_hash, cm))
4630 mono_class_has_finalizer (klass);
4632 if (klass->generic_container || cant_encode) {
4633 encode_value (-1, p, &p);
4635 encode_value (klass->vtable_size, p, &p);
4636 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);
4637 if (klass->has_cctor)
4638 encode_method_ref (acfg, mono_class_get_cctor (klass), p, &p);
4639 if (klass->has_finalize)
4640 encode_method_ref (acfg, mono_class_get_finalizer (klass), p, &p);
4642 encode_value (klass->instance_size, p, &p);
4643 encode_value (mono_class_data_size (klass), p, &p);
4644 encode_value (klass->packing_size, p, &p);
4645 encode_value (klass->min_align, p, &p);
4647 for (i = 0; i < klass->vtable_size; ++i) {
4648 MonoMethod *cm = klass->vtable [i];
4651 encode_method_ref (acfg, cm, p, &p);
4653 encode_value (0, p, &p);
4657 acfg->stats.class_info_size += p - buf;
4659 g_assert (p - buf < buf_size);
4660 res = add_to_blob (acfg, buf, p - buf);
4667 get_plt_entry_debug_sym (MonoAotCompile *acfg, MonoJumpInfo *ji, GHashTable *cache)
4669 char *debug_sym = NULL;
4672 case MONO_PATCH_INFO_METHOD:
4673 debug_sym = get_debug_sym (ji->data.method, "plt_", cache);
4675 case MONO_PATCH_INFO_INTERNAL_METHOD:
4676 debug_sym = g_strdup_printf ("plt__jit_icall_%s", ji->data.name);
4678 case MONO_PATCH_INFO_CLASS_INIT:
4679 debug_sym = g_strdup_printf ("plt__class_init_%s", mono_type_get_name (&ji->data.klass->byval_arg));
4680 sanitize_symbol (debug_sym);
4682 case MONO_PATCH_INFO_RGCTX_FETCH:
4683 debug_sym = g_strdup_printf ("plt__rgctx_fetch_%d", acfg->label_generator ++);
4685 case MONO_PATCH_INFO_ICALL_ADDR: {
4686 char *s = get_debug_sym (ji->data.method, "", cache);
4688 debug_sym = g_strdup_printf ("plt__icall_native_%s", s);
4692 case MONO_PATCH_INFO_JIT_ICALL_ADDR:
4693 debug_sym = g_strdup_printf ("plt__jit_icall_native_%s", ji->data.name);
4695 case MONO_PATCH_INFO_GENERIC_CLASS_INIT:
4696 debug_sym = g_strdup_printf ("plt__generic_class_init");
4706 * Calls made from AOTed code are routed through a table of jumps similar to the
4707 * ELF PLT (Program Linkage Table). Initially the PLT entries jump to code which transfers
4708 * control to the AOT runtime through a trampoline.
4711 emit_plt (MonoAotCompile *acfg)
4717 sprintf (symbol, "plt");
4719 emit_section_change (acfg, ".text", 0);
4720 emit_alignment (acfg, NACL_SIZE(16, kNaClAlignment));
4721 emit_label (acfg, symbol);
4722 emit_label (acfg, acfg->plt_symbol);
4724 for (i = 0; i < acfg->plt_offset; ++i) {
4725 char *debug_sym = NULL;
4726 MonoPltEntry *plt_entry = NULL;
4731 * The first plt entry is unused.
4735 plt_entry = g_hash_table_lookup (acfg->plt_offset_to_entry, GUINT_TO_POINTER (i));
4740 * If the target is directly callable, alias the plt symbol to point to
4742 * FIXME: Use this to simplify emit_and_reloc_code ().
4743 * FIXME: Avoid the got slot.
4744 * FIXME: Add support to the binary writer.
4746 if (ji && is_direct_callable (acfg, NULL, ji) && !acfg->use_bin_writer) {
4747 MonoCompile *callee_cfg = g_hash_table_lookup (acfg->method_to_cfg, ji->data.method);
4750 if (acfg->thumb_mixed && !callee_cfg->compile_llvm) {
4751 /* LLVM calls the PLT entries using bl, so emit a stub */
4752 fprintf (acfg->fp, "\n.thumb_func\n");
4753 emit_label (acfg, plt_entry->llvm_symbol);
4754 fprintf (acfg->fp, "bx pc\n");
4755 fprintf (acfg->fp, "nop\n");
4756 fprintf (acfg->fp, ".arm\n");
4757 fprintf (acfg->fp, "b %s\n", callee_cfg->asm_symbol);
4759 fprintf (acfg->fp, "\n.set %s, %s\n", plt_entry->llvm_symbol, callee_cfg->asm_symbol);
4766 debug_sym = plt_entry->debug_sym;
4768 if (acfg->thumb_mixed && !plt_entry->jit_used)
4769 /* Emit only a thumb version */
4772 if (acfg->llvm && !acfg->thumb_mixed)
4773 emit_label (acfg, plt_entry->llvm_symbol);
4776 if (acfg->need_no_dead_strip) {
4777 img_writer_emit_unset_mode (acfg->w);
4778 fprintf (acfg->fp, " .no_dead_strip %s\n", debug_sym);
4780 emit_local_symbol (acfg, debug_sym, NULL, TRUE);
4781 emit_label (acfg, debug_sym);
4784 emit_label (acfg, plt_entry->symbol);
4786 arch_emit_plt_entry (acfg, i);
4789 emit_symbol_size (acfg, debug_sym, ".");
4792 if (acfg->thumb_mixed) {
4793 /* Make sure the ARM symbols don't alias the thumb ones */
4794 emit_zero_bytes (acfg, 16);
4797 * Emit a separate set of PLT entries using thumb2 which is called by LLVM generated
4800 for (i = 0; i < acfg->plt_offset; ++i) {
4801 char *debug_sym = NULL;
4802 MonoPltEntry *plt_entry = NULL;
4808 plt_entry = g_hash_table_lookup (acfg->plt_offset_to_entry, GUINT_TO_POINTER (i));
4811 if (ji && is_direct_callable (acfg, NULL, ji) && !acfg->use_bin_writer)
4814 /* Skip plt entries not actually called by LLVM code */
4815 if (!plt_entry->llvm_used)
4818 if (acfg->aot_opts.write_symbols) {
4819 if (plt_entry->debug_sym)
4820 debug_sym = g_strdup_printf ("%s_thumb", plt_entry->debug_sym);
4824 #if defined(TARGET_MACH)
4825 fprintf (acfg->fp, " .thumb_func %s\n", debug_sym);
4826 fprintf (acfg->fp, " .no_dead_strip %s\n", debug_sym);
4828 emit_local_symbol (acfg, debug_sym, NULL, TRUE);
4829 emit_label (acfg, debug_sym);
4831 fprintf (acfg->fp, "\n.thumb_func\n");
4833 emit_label (acfg, plt_entry->llvm_symbol);
4835 arch_emit_llvm_plt_entry (acfg, i);
4838 emit_symbol_size (acfg, debug_sym, ".");
4844 emit_symbol_size (acfg, acfg->plt_symbol, ".");
4846 sprintf (symbol, "plt_end");
4847 emit_label (acfg, symbol);
4850 static G_GNUC_UNUSED void
4851 emit_trampoline (MonoAotCompile *acfg, int got_offset, MonoTrampInfo *info)
4853 char start_symbol [256];
4855 guint32 buf_size, info_offset;
4856 MonoJumpInfo *patch_info;
4867 code_size = info->code_size;
4869 unwind_ops = info->unwind_ops;
4871 #ifdef __native_client_codegen__
4872 mono_nacl_fix_patches (code, ji);
4877 sprintf (start_symbol, "%s", name);
4879 emit_section_change (acfg, ".text", 0);
4880 emit_global (acfg, start_symbol, TRUE);
4881 emit_alignment (acfg, AOT_FUNC_ALIGNMENT);
4882 emit_label (acfg, start_symbol);
4884 sprintf (symbol, "%snamed_%s", acfg->temp_prefix, name);
4885 emit_label (acfg, symbol);
4888 * The code should access everything through the GOT, so we pass
4891 emit_and_reloc_code (acfg, NULL, code, code_size, ji, TRUE);
4893 emit_symbol_size (acfg, start_symbol, ".");
4897 /* Sort relocations */
4898 patches = g_ptr_array_new ();
4899 for (patch_info = ji; patch_info; patch_info = patch_info->next)
4900 if (patch_info->type != MONO_PATCH_INFO_NONE)
4901 g_ptr_array_add (patches, patch_info);
4902 g_ptr_array_sort (patches, compare_patches);
4904 buf_size = patches->len * 128 + 128;
4905 buf = g_malloc (buf_size);
4908 encode_patch_list (acfg, patches, patches->len, got_offset, p, &p);
4909 g_assert (p - buf < buf_size);
4911 sprintf (symbol, "%s_p", name);
4913 info_offset = add_to_blob (acfg, buf, p - buf);
4915 emit_section_change (acfg, RODATA_SECT, 0);
4916 emit_global (acfg, symbol, FALSE);
4917 emit_label (acfg, symbol);
4919 emit_int32 (acfg, info_offset);
4921 /* Emit debug info */
4925 sprintf (symbol, "%s", name);
4926 sprintf (symbol2, "%snamed_%s", acfg->temp_prefix, name);
4929 mono_dwarf_writer_emit_trampoline (acfg->dwarf, symbol, symbol2, NULL, NULL, code_size, unwind_ops);
4934 emit_trampolines (MonoAotCompile *acfg)
4937 char end_symbol [256];
4938 int i, tramp_got_offset;
4939 MonoAotTrampoline ntype;
4940 #ifdef MONO_ARCH_HAVE_FULL_AOT_TRAMPOLINES
4944 if (!acfg->aot_opts.full_aot)
4947 g_assert (acfg->image->assembly);
4949 /* Currently, we emit most trampolines into the mscorlib AOT image. */
4950 if (strcmp (acfg->image->assembly->aname.name, "mscorlib") == 0) {
4951 #ifdef MONO_ARCH_HAVE_FULL_AOT_TRAMPOLINES
4952 MonoTrampInfo *info;
4955 * Emit the generic trampolines.
4957 * We could save some code by treating the generic trampolines as a wrapper
4958 * method, but that approach has its own complexities, so we choose the simpler
4961 for (tramp_type = 0; tramp_type < MONO_TRAMPOLINE_NUM; ++tramp_type) {
4962 mono_arch_create_generic_trampoline (tramp_type, &info, TRUE);
4963 emit_trampoline (acfg, acfg->got_offset, info);
4966 mono_arch_get_nullified_class_init_trampoline (&info);
4967 emit_trampoline (acfg, acfg->got_offset, info);
4968 #if defined(MONO_ARCH_MONITOR_OBJECT_REG)
4969 mono_arch_create_monitor_enter_trampoline (&info, TRUE);
4970 emit_trampoline (acfg, acfg->got_offset, info);
4971 mono_arch_create_monitor_exit_trampoline (&info, TRUE);
4972 emit_trampoline (acfg, acfg->got_offset, info);
4975 mono_arch_create_generic_class_init_trampoline (&info, TRUE);
4976 emit_trampoline (acfg, acfg->got_offset, info);
4978 /* Emit the exception related code pieces */
4979 mono_arch_get_restore_context (&info, TRUE);
4980 emit_trampoline (acfg, acfg->got_offset, info);
4981 mono_arch_get_call_filter (&info, TRUE);
4982 emit_trampoline (acfg, acfg->got_offset, info);
4983 mono_arch_get_throw_exception (&info, TRUE);
4984 emit_trampoline (acfg, acfg->got_offset, info);
4985 mono_arch_get_rethrow_exception (&info, TRUE);
4986 emit_trampoline (acfg, acfg->got_offset, info);
4987 mono_arch_get_throw_corlib_exception (&info, TRUE);
4988 emit_trampoline (acfg, acfg->got_offset, info);
4990 #if defined(MONO_ARCH_HAVE_GET_TRAMPOLINES)
4992 GSList *l = mono_arch_get_trampolines (TRUE);
4995 MonoTrampInfo *info = l->data;
4997 emit_trampoline (acfg, acfg->got_offset, info);
5003 for (i = 0; i < 128; ++i) {
5006 offset = MONO_RGCTX_SLOT_MAKE_RGCTX (i);
5007 mono_arch_create_rgctx_lazy_fetch_trampoline (offset, &info, TRUE);
5008 emit_trampoline (acfg, acfg->got_offset, info);
5010 offset = MONO_RGCTX_SLOT_MAKE_MRGCTX (i);
5011 mono_arch_create_rgctx_lazy_fetch_trampoline (offset, &info, TRUE);
5012 emit_trampoline (acfg, acfg->got_offset, info);
5018 /* delegate_invoke_impl trampolines */
5019 l = mono_arch_get_delegate_invoke_impls ();
5021 MonoTrampInfo *info = l->data;
5023 emit_trampoline (acfg, acfg->got_offset, info);
5028 #endif /* #ifdef MONO_ARCH_HAVE_FULL_AOT_TRAMPOLINES */
5030 /* Emit trampolines which are numerous */
5033 * These include the following:
5034 * - specific trampolines
5035 * - static rgctx invoke trampolines
5037 * These trampolines have the same code, they are parameterized by GOT
5039 * They are defined in this file, in the arch_... routines instead of
5040 * in tramp-<ARCH>.c, since it is easier to do it this way.
5044 * When running in aot-only mode, we can't create specific trampolines at
5045 * runtime, so we create a few, and save them in the AOT file.
5046 * Normal trampolines embed their argument as a literal inside the
5047 * trampoline code, we can't do that here, so instead we embed an offset
5048 * which needs to be added to the trampoline address to get the address of
5049 * the GOT slot which contains the argument value.
5050 * The generated trampolines jump to the generic trampolines using another
5051 * GOT slot, which will be setup by the AOT loader to point to the
5052 * generic trampoline code of the given type.
5056 * FIXME: Maybe we should use more specific trampolines (i.e. one class init for
5060 emit_section_change (acfg, ".text", 0);
5062 tramp_got_offset = acfg->got_offset;
5064 for (ntype = 0; ntype < MONO_AOT_TRAMP_NUM; ++ntype) {
5066 case MONO_AOT_TRAMP_SPECIFIC:
5067 sprintf (symbol, "specific_trampolines");
5069 case MONO_AOT_TRAMP_STATIC_RGCTX:
5070 sprintf (symbol, "static_rgctx_trampolines");
5072 case MONO_AOT_TRAMP_IMT_THUNK:
5073 sprintf (symbol, "imt_thunks");
5076 g_assert_not_reached ();
5079 sprintf (end_symbol, "%s_e", symbol);
5081 if (acfg->aot_opts.write_symbols)
5082 emit_local_symbol (acfg, symbol, end_symbol, TRUE);
5084 emit_alignment (acfg, AOT_FUNC_ALIGNMENT);
5085 emit_label (acfg, symbol);
5087 acfg->trampoline_got_offset_base [ntype] = tramp_got_offset;
5089 for (i = 0; i < acfg->num_trampolines [ntype]; ++i) {
5093 case MONO_AOT_TRAMP_SPECIFIC:
5094 arch_emit_specific_trampoline (acfg, tramp_got_offset, &tramp_size);
5095 tramp_got_offset += 2;
5097 case MONO_AOT_TRAMP_STATIC_RGCTX:
5098 arch_emit_static_rgctx_trampoline (acfg, tramp_got_offset, &tramp_size);
5099 tramp_got_offset += 2;
5101 case MONO_AOT_TRAMP_IMT_THUNK:
5102 arch_emit_imt_thunk (acfg, tramp_got_offset, &tramp_size);
5103 tramp_got_offset += 1;
5106 g_assert_not_reached ();
5108 #ifdef __native_client_codegen__
5109 /* align to avoid 32-byte boundary crossings */
5110 emit_alignment (acfg, AOT_FUNC_ALIGNMENT);
5113 if (!acfg->trampoline_size [ntype]) {
5114 g_assert (tramp_size);
5115 acfg->trampoline_size [ntype] = tramp_size;
5119 emit_label (acfg, end_symbol);
5122 /* Reserve some entries at the end of the GOT for our use */
5123 acfg->num_trampoline_got_entries = tramp_got_offset - acfg->got_offset;
5126 acfg->got_offset += acfg->num_trampoline_got_entries;
5130 str_begins_with (const char *str1, const char *str2)
5132 int len = strlen (str2);
5133 return strncmp (str1, str2, len) == 0;
5137 mono_aot_readonly_field_override (MonoClassField *field)
5140 for (rdv = readonly_values; rdv; rdv = rdv->next) {
5141 char *p = rdv->name;
5143 len = strlen (field->parent->name_space);
5144 if (strncmp (p, field->parent->name_space, len))
5149 len = strlen (field->parent->name);
5150 if (strncmp (p, field->parent->name, len))
5155 if (strcmp (p, field->name))
5157 switch (rdv->type) {
5159 return &rdv->value.i1;
5161 return &rdv->value.i2;
5163 return &rdv->value.i4;
5172 add_readonly_value (MonoAotOptions *opts, const char *val)
5177 /* the format of val is:
5178 * namespace.typename.fieldname=type/value
5179 * type can be i1 for uint8/int8/boolean, i2 for uint16/int16/char, i4 for uint32/int32
5181 fval = strrchr (val, '/');
5183 fprintf (stderr, "AOT : invalid format for readonly field '%s', missing /.\n", val);
5186 tval = strrchr (val, '=');
5188 fprintf (stderr, "AOT : invalid format for readonly field '%s', missing =.\n", val);
5191 rdv = g_new0 (ReadOnlyValue, 1);
5192 rdv->name = g_malloc0 (tval - val + 1);
5193 memcpy (rdv->name, val, tval - val);
5196 if (strncmp (tval, "i1", 2) == 0) {
5197 rdv->value.i1 = atoi (fval);
5198 rdv->type = MONO_TYPE_I1;
5199 } else if (strncmp (tval, "i2", 2) == 0) {
5200 rdv->value.i2 = atoi (fval);
5201 rdv->type = MONO_TYPE_I2;
5202 } else if (strncmp (tval, "i4", 2) == 0) {
5203 rdv->value.i4 = atoi (fval);
5204 rdv->type = MONO_TYPE_I4;
5206 fprintf (stderr, "AOT : unsupported type for readonly field '%s'.\n", tval);
5209 rdv->next = readonly_values;
5210 readonly_values = rdv;
5214 mono_aot_parse_options (const char *aot_options, MonoAotOptions *opts)
5216 gchar **args, **ptr;
5218 args = g_strsplit (aot_options ? aot_options : "", ",", -1);
5219 for (ptr = args; ptr && *ptr; ptr ++) {
5220 const char *arg = *ptr;
5222 if (str_begins_with (arg, "outfile=")) {
5223 opts->outfile = g_strdup (arg + strlen ("outfile="));
5224 } else if (str_begins_with (arg, "save-temps")) {
5225 opts->save_temps = TRUE;
5226 } else if (str_begins_with (arg, "keep-temps")) {
5227 opts->save_temps = TRUE;
5228 } else if (str_begins_with (arg, "write-symbols")) {
5229 opts->write_symbols = TRUE;
5230 } else if (str_begins_with (arg, "no-write-symbols")) {
5231 opts->write_symbols = FALSE;
5232 } else if (str_begins_with (arg, "metadata-only")) {
5233 opts->metadata_only = TRUE;
5234 } else if (str_begins_with (arg, "bind-to-runtime-version")) {
5235 opts->bind_to_runtime_version = TRUE;
5236 } else if (str_begins_with (arg, "full")) {
5237 opts->full_aot = TRUE;
5238 } else if (str_begins_with (arg, "threads=")) {
5239 opts->nthreads = atoi (arg + strlen ("threads="));
5240 } else if (str_begins_with (arg, "static")) {
5241 opts->static_link = TRUE;
5242 opts->no_dlsym = TRUE;
5243 } else if (str_begins_with (arg, "asmonly")) {
5244 opts->asm_only = TRUE;
5245 } else if (str_begins_with (arg, "asmwriter")) {
5246 opts->asm_writer = TRUE;
5247 } else if (str_begins_with (arg, "nodebug")) {
5248 opts->nodebug = TRUE;
5249 } else if (str_begins_with (arg, "ntrampolines=")) {
5250 opts->ntrampolines = atoi (arg + strlen ("ntrampolines="));
5251 } else if (str_begins_with (arg, "nrgctx-trampolines=")) {
5252 opts->nrgctx_trampolines = atoi (arg + strlen ("nrgctx-trampolines="));
5253 } else if (str_begins_with (arg, "nimt-trampolines=")) {
5254 opts->nimt_trampolines = atoi (arg + strlen ("nimt-trampolines="));
5255 } else if (str_begins_with (arg, "autoreg")) {
5256 opts->autoreg = TRUE;
5257 } else if (str_begins_with (arg, "tool-prefix=")) {
5258 opts->tool_prefix = g_strdup (arg + strlen ("tool-prefix="));
5259 } else if (str_begins_with (arg, "soft-debug")) {
5260 opts->soft_debug = TRUE;
5261 } else if (str_begins_with (arg, "direct-pinvoke")) {
5262 opts->direct_pinvoke = TRUE;
5263 } else if (str_begins_with (arg, "direct-icalls")) {
5264 opts->direct_icalls = TRUE;
5265 #if defined(TARGET_ARM)
5266 } else if (str_begins_with (arg, "iphone-abi")) {
5267 // older full-aot users did depend on this.
5269 } else if (str_begins_with (arg, "no-direct-calls")) {
5270 opts->no_direct_calls = TRUE;
5271 } else if (str_begins_with (arg, "print-skipped")) {
5272 opts->print_skipped_methods = TRUE;
5273 } else if (str_begins_with (arg, "stats")) {
5275 } else if (str_begins_with (arg, "log-generics")) {
5276 opts->log_generics = TRUE;
5277 } else if (str_begins_with (arg, "mtriple=")) {
5278 opts->mtriple = g_strdup (arg + strlen ("mtriple="));
5279 } else if (str_begins_with (arg, "llvm-path=")) {
5280 opts->llvm_path = g_strdup (arg + strlen ("llvm-path="));
5281 } else if (str_begins_with (arg, "readonly-value=")) {
5282 add_readonly_value (opts, arg + strlen ("readonly-value="));
5283 } else if (str_begins_with (arg, "info")) {
5284 printf ("AOT target setup: %s.\n", AOT_TARGET_STR);
5286 } else if (str_begins_with (arg, "gc-maps")) {
5287 mini_gc_enable_gc_maps_for_aot ();
5288 } else if (str_begins_with (arg, "help") || str_begins_with (arg, "?")) {
5289 printf ("Supported options for --aot:\n");
5290 printf (" outfile=\n");
5291 printf (" save-temps\n");
5292 printf (" keep-temps\n");
5293 printf (" write-symbols\n");
5294 printf (" metadata-only\n");
5295 printf (" bind-to-runtime-version\n");
5297 printf (" threads=\n");
5298 printf (" static\n");
5299 printf (" asmonly\n");
5300 printf (" asmwriter\n");
5301 printf (" nodebug\n");
5302 printf (" ntrampolines=\n");
5303 printf (" nrgctx-trampolines=\n");
5304 printf (" nimt-trampolines=\n");
5305 printf (" autoreg\n");
5306 printf (" tool-prefix=\n");
5307 printf (" readonly-value=\n");
5308 printf (" soft-debug\n");
5309 printf (" gc-maps\n");
5310 printf (" print-skipped\n");
5311 printf (" stats\n");
5313 printf (" help/?\n");
5316 fprintf (stderr, "AOT : Unknown argument '%s'.\n", arg);
5325 add_token_info_hash (gpointer key, gpointer value, gpointer user_data)
5327 MonoMethod *method = (MonoMethod*)key;
5328 MonoJumpInfoToken *ji = (MonoJumpInfoToken*)value;
5329 MonoJumpInfoToken *new_ji = g_new0 (MonoJumpInfoToken, 1);
5330 MonoAotCompile *acfg = user_data;
5332 new_ji->image = ji->image;
5333 new_ji->token = ji->token;
5334 g_hash_table_insert (acfg->token_info_hash, method, new_ji);
5338 can_encode_class (MonoAotCompile *acfg, MonoClass *klass)
5340 if (klass->type_token)
5342 if ((klass->byval_arg.type == MONO_TYPE_VAR) || (klass->byval_arg.type == MONO_TYPE_MVAR) || (klass->byval_arg.type == MONO_TYPE_PTR))
5345 return can_encode_class (acfg, klass->element_class);
5350 can_encode_patch (MonoAotCompile *acfg, MonoJumpInfo *patch_info)
5352 switch (patch_info->type) {
5353 case MONO_PATCH_INFO_METHOD:
5354 case MONO_PATCH_INFO_METHODCONST: {
5355 MonoMethod *method = patch_info->data.method;
5357 if (method->wrapper_type) {
5358 switch (method->wrapper_type) {
5359 case MONO_WRAPPER_NONE:
5360 case MONO_WRAPPER_REMOTING_INVOKE_WITH_CHECK:
5361 case MONO_WRAPPER_XDOMAIN_INVOKE:
5362 case MONO_WRAPPER_STFLD:
5363 case MONO_WRAPPER_LDFLD:
5364 case MONO_WRAPPER_LDFLDA:
5365 case MONO_WRAPPER_LDFLD_REMOTE:
5366 case MONO_WRAPPER_STFLD_REMOTE:
5367 case MONO_WRAPPER_STELEMREF:
5368 case MONO_WRAPPER_ISINST:
5369 case MONO_WRAPPER_PROXY_ISINST:
5370 case MONO_WRAPPER_ALLOC:
5371 case MONO_WRAPPER_REMOTING_INVOKE:
5372 case MONO_WRAPPER_UNKNOWN:
5373 case MONO_WRAPPER_WRITE_BARRIER:
5375 case MONO_WRAPPER_MANAGED_TO_MANAGED:
5376 case MONO_WRAPPER_CASTCLASS: {
5377 WrapperInfo *info = mono_marshal_get_wrapper_info (method);
5386 //printf ("Skip (wrapper call): %d -> %s\n", patch_info->type, mono_method_full_name (patch_info->data.method, TRUE));
5390 if (!method->token) {
5391 /* The method is part of a constructed type like Int[,].Set (). */
5392 if (!g_hash_table_lookup (acfg->token_info_hash, method)) {
5393 if (method->klass->rank)
5401 case MONO_PATCH_INFO_VTABLE:
5402 case MONO_PATCH_INFO_CLASS_INIT:
5403 case MONO_PATCH_INFO_DELEGATE_TRAMPOLINE:
5404 case MONO_PATCH_INFO_CLASS:
5405 case MONO_PATCH_INFO_IID:
5406 case MONO_PATCH_INFO_ADJUSTED_IID:
5407 if (!can_encode_class (acfg, patch_info->data.klass)) {
5408 //printf ("Skip: %s\n", mono_type_full_name (&patch_info->data.klass->byval_arg));
5412 case MONO_PATCH_INFO_RGCTX_FETCH: {
5413 MonoJumpInfoRgctxEntry *entry = patch_info->data.rgctx_entry;
5415 if (!can_encode_patch (acfg, entry->data))
5429 * AOT compile a given method.
5430 * This function might be called by multiple threads, so it must be thread-safe.
5433 compile_method (MonoAotCompile *acfg, MonoMethod *method)
5436 MonoJumpInfo *patch_info;
5439 MonoMethod *wrapped;
5441 if (acfg->aot_opts.metadata_only)
5444 mono_acfg_lock (acfg);
5445 index = get_method_index (acfg, method);
5446 mono_acfg_unlock (acfg);
5448 /* fixme: maybe we can also precompile wrapper methods */
5449 if ((method->flags & METHOD_ATTRIBUTE_PINVOKE_IMPL) ||
5450 (method->iflags & METHOD_IMPL_ATTRIBUTE_RUNTIME) ||
5451 (method->flags & METHOD_ATTRIBUTE_ABSTRACT)) {
5452 //printf ("Skip (impossible): %s\n", mono_method_full_name (method, TRUE));
5456 if (method->iflags & METHOD_IMPL_ATTRIBUTE_INTERNAL_CALL)
5459 wrapped = mono_marshal_method_from_wrapper (method);
5460 if (wrapped && (wrapped->iflags & METHOD_IMPL_ATTRIBUTE_INTERNAL_CALL) && wrapped->is_generic)
5461 // FIXME: The wrapper should be generic too, but it is not
5464 if (method->wrapper_type == MONO_WRAPPER_COMINTEROP)
5467 InterlockedIncrement (&acfg->stats.mcount);
5470 if (method->is_generic || method->klass->generic_container) {
5471 InterlockedIncrement (&acfg->stats.genericcount);
5476 //acfg->aot_opts.print_skipped_methods = TRUE;
5479 * Since these methods are the only ones which are compiled with
5480 * AOT support, and they are not used by runtime startup/shutdown code,
5481 * the runtime will not see AOT methods during AOT compilation,so it
5482 * does not need to support them by creating a fake GOT etc.
5484 cfg = mini_method_compile (method, acfg->opts, mono_get_root_domain (), FALSE, TRUE, 0);
5485 if (cfg->exception_type == MONO_EXCEPTION_GENERIC_SHARING_FAILED) {
5486 //printf ("F: %s\n", mono_method_full_name (method, TRUE));
5487 InterlockedIncrement (&acfg->stats.genericcount);
5490 if (cfg->exception_type != MONO_EXCEPTION_NONE) {
5491 if (acfg->aot_opts.print_skipped_methods)
5492 printf ("Skip (JIT failure): %s\n", mono_method_full_name (method, TRUE));
5493 /* Let the exception happen at runtime */
5497 if (cfg->disable_aot) {
5498 if (acfg->aot_opts.print_skipped_methods)
5499 printf ("Skip (disabled): %s\n", mono_method_full_name (method, TRUE));
5500 InterlockedIncrement (&acfg->stats.ocount);
5501 mono_destroy_compile (cfg);
5505 /* Nullify patches which need no aot processing */
5506 for (patch_info = cfg->patch_info; patch_info; patch_info = patch_info->next) {
5507 switch (patch_info->type) {
5508 case MONO_PATCH_INFO_LABEL:
5509 case MONO_PATCH_INFO_BB:
5510 patch_info->type = MONO_PATCH_INFO_NONE;
5517 /* Collect method->token associations from the cfg */
5518 mono_acfg_lock (acfg);
5519 g_hash_table_foreach (cfg->token_info_hash, add_token_info_hash, acfg);
5520 mono_acfg_unlock (acfg);
5523 * Check for absolute addresses.
5526 for (patch_info = cfg->patch_info; patch_info; patch_info = patch_info->next) {
5527 switch (patch_info->type) {
5528 case MONO_PATCH_INFO_ABS:
5529 /* unable to handle this */
5538 if (acfg->aot_opts.print_skipped_methods)
5539 printf ("Skip (abs call): %s\n", mono_method_full_name (method, TRUE));
5540 InterlockedIncrement (&acfg->stats.abscount);
5541 mono_destroy_compile (cfg);
5545 /* Lock for the rest of the code */
5546 mono_acfg_lock (acfg);
5549 * Check for methods/klasses we can't encode.
5552 for (patch_info = cfg->patch_info; patch_info; patch_info = patch_info->next) {
5553 if (!can_encode_patch (acfg, patch_info))
5558 if (acfg->aot_opts.print_skipped_methods)
5559 printf ("Skip (patches): %s\n", mono_method_full_name (method, TRUE));
5560 acfg->stats.ocount++;
5561 mono_destroy_compile (cfg);
5562 mono_acfg_unlock (acfg);
5566 /* Adds generic instances referenced by this method */
5568 * The depth is used to avoid infinite loops when generic virtual recursion is
5571 depth = GPOINTER_TO_UINT (g_hash_table_lookup (acfg->method_depth, method));
5573 for (patch_info = cfg->patch_info; patch_info; patch_info = patch_info->next) {
5574 switch (patch_info->type) {
5575 case MONO_PATCH_INFO_METHOD: {
5576 MonoMethod *m = patch_info->data.method;
5577 if (m->is_inflated) {
5578 if (!(mono_class_generic_sharing_enabled (m->klass) &&
5579 mono_method_is_generic_sharable_impl (m, FALSE)) &&
5580 !method_has_type_vars (m)) {
5581 if (m->iflags & METHOD_IMPL_ATTRIBUTE_INTERNAL_CALL) {
5582 if (acfg->aot_opts.full_aot)
5583 add_extra_method_with_depth (acfg, mono_marshal_get_native_wrapper (m, TRUE, TRUE), depth + 1);
5585 add_extra_method_with_depth (acfg, m, depth + 1);
5586 add_types_from_method_header (acfg, m);
5589 add_generic_class_with_depth (acfg, m->klass, depth + 5, "method");
5591 if (m->wrapper_type == MONO_WRAPPER_MANAGED_TO_MANAGED && !strcmp (m->name, "ElementAddr"))
5592 add_extra_method_with_depth (acfg, m, depth + 1);
5595 case MONO_PATCH_INFO_VTABLE: {
5596 MonoClass *klass = patch_info->data.klass;
5598 if (klass->generic_class && !mono_generic_context_is_sharable (&klass->generic_class->context, FALSE))
5599 add_generic_class_with_depth (acfg, klass, depth + 5, "vtable");
5602 case MONO_PATCH_INFO_SFLDA: {
5603 MonoClass *klass = patch_info->data.field->parent;
5605 /* The .cctor needs to run at runtime. */
5606 if (klass->generic_class && !mono_generic_context_is_sharable (&klass->generic_class->context, FALSE) && mono_class_get_cctor (klass))
5607 add_extra_method_with_depth (acfg, mono_class_get_cctor (klass), depth + 1);
5616 /* Determine whenever the method has GOT slots */
5617 for (patch_info = cfg->patch_info; patch_info; patch_info = patch_info->next) {
5618 switch (patch_info->type) {
5619 case MONO_PATCH_INFO_GOT_OFFSET:
5620 case MONO_PATCH_INFO_NONE:
5621 case MONO_PATCH_INFO_GC_CARD_TABLE_ADDR:
5623 case MONO_PATCH_INFO_IMAGE:
5624 /* The assembly is stored in GOT slot 0 */
5625 if (patch_info->data.image != acfg->image)
5626 cfg->has_got_slots = TRUE;
5629 if (!is_plt_patch (patch_info))
5630 cfg->has_got_slots = TRUE;
5635 if (!cfg->has_got_slots)
5636 InterlockedIncrement (&acfg->stats.methods_without_got_slots);
5639 * FIXME: Instead of this mess, allocate the patches from the aot mempool.
5641 /* Make a copy of the patch info which is in the mempool */
5643 MonoJumpInfo *patches = NULL, *patches_end = NULL;
5645 for (patch_info = cfg->patch_info; patch_info; patch_info = patch_info->next) {
5646 MonoJumpInfo *new_patch_info = mono_patch_info_dup_mp (acfg->mempool, patch_info);
5649 patches = new_patch_info;
5651 patches_end->next = new_patch_info;
5652 patches_end = new_patch_info;
5654 cfg->patch_info = patches;
5656 /* Make a copy of the unwind info */
5658 GSList *l, *unwind_ops;
5662 for (l = cfg->unwind_ops; l; l = l->next) {
5663 op = mono_mempool_alloc (acfg->mempool, sizeof (MonoUnwindOp));
5664 memcpy (op, l->data, sizeof (MonoUnwindOp));
5665 unwind_ops = g_slist_prepend_mempool (acfg->mempool, unwind_ops, op);
5667 cfg->unwind_ops = g_slist_reverse (unwind_ops);
5669 /* Make a copy of the argument/local info */
5671 MonoInst **args, **locals;
5672 MonoMethodSignature *sig;
5673 MonoMethodHeader *header;
5676 sig = mono_method_signature (method);
5677 args = mono_mempool_alloc (acfg->mempool, sizeof (MonoInst*) * (sig->param_count + sig->hasthis));
5678 for (i = 0; i < sig->param_count + sig->hasthis; ++i) {
5679 args [i] = mono_mempool_alloc (acfg->mempool, sizeof (MonoInst));
5680 memcpy (args [i], cfg->args [i], sizeof (MonoInst));
5684 header = mono_method_get_header (method);
5685 locals = mono_mempool_alloc (acfg->mempool, sizeof (MonoInst*) * header->num_locals);
5686 for (i = 0; i < header->num_locals; ++i) {
5687 locals [i] = mono_mempool_alloc (acfg->mempool, sizeof (MonoInst));
5688 memcpy (locals [i], cfg->locals [i], sizeof (MonoInst));
5690 cfg->locals = locals;
5693 /* Free some fields used by cfg to conserve memory */
5694 mono_mempool_destroy (cfg->mempool);
5695 cfg->mempool = NULL;
5696 g_free (cfg->varinfo);
5697 cfg->varinfo = NULL;
5701 mono_regstate_free (cfg->rs);
5705 //printf ("Compile: %s\n", mono_method_full_name (method, TRUE));
5707 while (index >= acfg->cfgs_size) {
5708 MonoCompile **new_cfgs;
5711 new_size = acfg->cfgs_size * 2;
5712 new_cfgs = g_new0 (MonoCompile*, new_size);
5713 memcpy (new_cfgs, acfg->cfgs, sizeof (MonoCompile*) * acfg->cfgs_size);
5714 g_free (acfg->cfgs);
5715 acfg->cfgs = new_cfgs;
5716 acfg->cfgs_size = new_size;
5718 acfg->cfgs [index] = cfg;
5720 g_hash_table_insert (acfg->method_to_cfg, cfg->orig_method, cfg);
5723 if (cfg->orig_method->wrapper_type)
5724 g_ptr_array_add (acfg->extra_methods, cfg->orig_method);
5727 mono_acfg_unlock (acfg);
5729 InterlockedIncrement (&acfg->stats.ccount);
5733 compile_thread_main (gpointer *user_data)
5735 MonoDomain *domain = user_data [0];
5736 MonoAotCompile *acfg = user_data [1];
5737 GPtrArray *methods = user_data [2];
5740 mono_thread_attach (domain);
5742 for (i = 0; i < methods->len; ++i)
5743 compile_method (acfg, g_ptr_array_index (methods, i));
5747 load_profile_files (MonoAotCompile *acfg)
5751 int file_index, res, method_index, i;
5754 GList *unordered, *l;
5759 tmp = g_strdup_printf ("%s/.mono/aot-profile-data/%s-%d", g_get_home_dir (), acfg->image->assembly_name, file_index);
5761 if (!g_file_test (tmp, G_FILE_TEST_IS_REGULAR)) {
5766 infile = fopen (tmp, "r");
5769 printf ("Using profile data file '%s'\n", tmp);
5774 res = fscanf (infile, "%32s\n", ver);
5775 if ((res != 1) || strcmp (ver, "#VER:2") != 0) {
5776 printf ("Profile file has wrong version or invalid.\n");
5783 MonoMethodDesc *desc;
5786 if (fgets (name, 1023, infile) == NULL)
5789 /* Kill the newline */
5790 if (strlen (name) > 0)
5791 name [strlen (name) - 1] = '\0';
5793 desc = mono_method_desc_new (name, TRUE);
5795 method = mono_method_desc_search_in_image (desc, acfg->image);
5797 if (method && mono_method_get_token (method)) {
5798 token = mono_method_get_token (method);
5799 method_index = mono_metadata_token_index (token) - 1;
5802 for (i = 0; i < acfg->method_order->len; ++i) {
5803 if (g_ptr_array_index (acfg->method_order, i) == GUINT_TO_POINTER (method_index)) {
5809 g_ptr_array_add (acfg->method_order, GUINT_TO_POINTER (method_index));
5811 //printf ("No method found matching '%s'.\n", name);
5817 /* Add missing methods */
5819 for (method_index = 0; method_index < acfg->image->tables [MONO_TABLE_METHOD].rows; ++method_index) {
5821 for (i = 0; i < acfg->method_order->len; ++i) {
5822 if (g_ptr_array_index (acfg->method_order, i) == GUINT_TO_POINTER (method_index)) {
5828 unordered = g_list_prepend (unordered, GUINT_TO_POINTER (method_index));
5830 unordered = g_list_reverse (unordered);
5831 for (l = unordered; l; l = l->next)
5832 g_ptr_array_add (acfg->method_order, l->data);
5835 /* Used by the LLVM backend */
5837 mono_aot_get_got_offset (MonoJumpInfo *ji)
5839 return get_got_offset (llvm_acfg, ji);
5843 mono_aot_get_method_name (MonoCompile *cfg)
5845 if (llvm_acfg->aot_opts.static_link)
5846 /* Include the assembly name too to avoid duplicate symbol errors */
5847 return g_strdup_printf ("%s_%s", llvm_acfg->assembly_name_sym, get_debug_sym (cfg->orig_method, "", llvm_acfg->method_label_hash));
5849 return get_debug_sym (cfg->orig_method, "", llvm_acfg->method_label_hash);
5853 mono_aot_get_plt_symbol (MonoJumpInfoType type, gconstpointer data)
5855 MonoJumpInfo *ji = mono_mempool_alloc (llvm_acfg->mempool, sizeof (MonoJumpInfo));
5856 MonoPltEntry *plt_entry;
5859 ji->data.target = data;
5861 if (!can_encode_patch (llvm_acfg, ji))
5864 plt_entry = get_plt_entry (llvm_acfg, ji);
5865 plt_entry->llvm_used = TRUE;
5867 #if defined(TARGET_MACH)
5868 return g_strdup_printf (plt_entry->llvm_symbol + strlen (llvm_acfg->llvm_label_prefix));
5870 return g_strdup_printf (plt_entry->llvm_symbol);
5875 mono_aot_patch_info_dup (MonoJumpInfo* ji)
5879 mono_acfg_lock (llvm_acfg);
5880 res = mono_patch_info_dup_mp (llvm_acfg->mempool, ji);
5881 mono_acfg_unlock (llvm_acfg);
5891 * Emit the LLVM code into an LLVM bytecode file, and compile it using the LLVM
5895 emit_llvm_file (MonoAotCompile *acfg)
5897 char *command, *opts, *tempbc;
5899 MonoJumpInfo *patch_info;
5902 * When using LLVM, we let llvm emit the got since the LLVM IL needs to refer
5906 /* Compute the final size of the got */
5907 for (i = 0; i < acfg->nmethods; ++i) {
5908 if (acfg->cfgs [i]) {
5909 for (patch_info = acfg->cfgs [i]->patch_info; patch_info; patch_info = patch_info->next) {
5910 if (patch_info->type != MONO_PATCH_INFO_NONE) {
5911 if (!is_plt_patch (patch_info))
5912 get_got_offset (acfg, patch_info);
5914 get_plt_entry (acfg, patch_info);
5920 acfg->final_got_size = acfg->got_offset + acfg->plt_offset;
5922 if (acfg->aot_opts.full_aot) {
5926 * Need to add the got entries used by the trampolines.
5927 * This is only a conservative approximation.
5929 if (strcmp (acfg->image->assembly->aname.name, "mscorlib") == 0) {
5930 /* For the generic + rgctx trampolines */
5931 acfg->final_got_size += 400;
5932 /* For the specific trampolines */
5933 for (ntype = 0; ntype < MONO_AOT_TRAMP_NUM; ++ntype)
5934 acfg->final_got_size += acfg->num_trampolines [ntype] * 2;
5939 tempbc = g_strdup_printf ("%s.bc", acfg->tmpfname);
5940 mono_llvm_emit_aot_module (tempbc, acfg->final_got_size);
5944 * FIXME: Experiment with adding optimizations, the -std-compile-opts set takes
5945 * a lot of time, and doesn't seem to save much space.
5946 * The following optimizations cannot be enabled:
5948 * - 'jump-threading' changes our blockaddress references to int constants.
5949 * - 'basiccg' fails because it contains:
5950 * if (CS && !isa<IntrinsicInst>(II)) {
5951 * and isa<IntrinsicInst> is false for invokes to intrinsics (iltests.exe).
5952 * - 'prune-eh' and 'functionattrs' depend on 'basiccg'.
5953 * The opt list below was produced by taking the output of:
5954 * llvm-as < /dev/null | opt -O2 -disable-output -debug-pass=Arguments
5955 * then removing tailcallelim + the global opts, and adding a second gvn.
5957 opts = g_strdup ("-instcombine -simplifycfg");
5958 opts = g_strdup ("-simplifycfg -domtree -domfrontier -scalarrepl -instcombine -simplifycfg -domtree -domfrontier -scalarrepl -simplify-libcalls -instcombine -simplifycfg -instcombine -simplifycfg -reassociate -domtree -loops -loop-simplify -domfrontier -loop-simplify -lcssa -loop-rotate -licm -lcssa -loop-unswitch -instcombine -scalar-evolution -loop-simplify -lcssa -iv-users -indvars -loop-deletion -loop-simplify -lcssa -loop-unroll -instcombine -memdep -gvn -memdep -memcpyopt -sccp -instcombine -domtree -memdep -dse -adce -simplifycfg -preverify -domtree -verify");
5960 command = g_strdup_printf ("%sopt -f %s -o %s.opt.bc %s.bc", acfg->aot_opts.llvm_path, opts, acfg->tmpfname, acfg->tmpfname);
5961 printf ("Executing opt: %s\n", command);
5962 if (system (command) != 0) {
5968 if (!acfg->llc_args)
5969 acfg->llc_args = g_string_new ("");
5971 /* Verbose asm slows down llc greatly */
5972 g_string_append (acfg->llc_args, " -asm-verbose=false");
5974 if (acfg->aot_opts.mtriple)
5975 g_string_append_printf (acfg->llc_args, " -mtriple=%s", acfg->aot_opts.mtriple);
5977 if (llvm_acfg->aot_opts.static_link)
5978 g_string_append_printf (acfg->llc_args, " -relocation-model=static");
5980 g_string_append_printf (acfg->llc_args, " -relocation-model=pic");
5981 unlink (acfg->tmpfname);
5983 command = g_strdup_printf ("%sllc %s -disable-gnu-eh-frame -enable-mono-eh-frame -o %s %s.opt.bc", acfg->aot_opts.llvm_path, acfg->llc_args->str, acfg->tmpfname, acfg->tmpfname);
5985 printf ("Executing llc: %s\n", command);
5987 if (system (command) != 0) {
5994 emit_code (MonoAotCompile *acfg)
5996 int oindex, i, prev_index;
5998 char end_symbol [256];
6000 #if defined(TARGET_POWERPC64)
6001 sprintf (symbol, ".Lgot_addr");
6002 emit_section_change (acfg, ".text", 0);
6003 emit_alignment (acfg, 8);
6004 emit_label (acfg, symbol);
6005 emit_pointer (acfg, acfg->got_symbol);
6009 * This global symbol is used to compute the address of each method using the
6010 * code_offsets array. It is also used to compute the memory ranges occupied by
6011 * AOT code, so it must be equal to the address of the first emitted method.
6013 sprintf (symbol, "methods");
6014 emit_section_change (acfg, ".text", 0);
6015 emit_alignment (acfg, 8);
6017 for (i = 0; i < acfg->nmethods; ++i) {
6018 if (acfg->cfgs [i] && acfg->cfgs [i]->compile_llvm) {
6019 fprintf (acfg->fp, "\n.set methods, %s\n", acfg->cfgs [i]->asm_symbol);
6023 if (i == acfg->nmethods)
6024 /* No LLVM compiled methods */
6025 emit_label (acfg, symbol);
6027 emit_label (acfg, symbol);
6031 * Emit some padding so the local symbol for the first method doesn't have the
6032 * same address as 'methods'.
6034 #if defined(__default_codegen__)
6035 emit_zero_bytes (acfg, 16);
6036 #elif defined(__native_client_codegen__)
6038 const int kPaddingSize = 16;
6039 guint8 pad_buffer[kPaddingSize];
6040 mono_arch_nacl_pad (pad_buffer, kPaddingSize);
6041 emit_bytes (acfg, pad_buffer, kPaddingSize);
6045 for (oindex = 0; oindex < acfg->method_order->len; ++oindex) {
6049 i = GPOINTER_TO_UINT (g_ptr_array_index (acfg->method_order, oindex));
6051 cfg = acfg->cfgs [i];
6056 method = cfg->orig_method;
6058 /* Emit unbox trampoline */
6059 if (acfg->aot_opts.full_aot && cfg->orig_method->klass->valuetype && (method->flags & METHOD_ATTRIBUTE_VIRTUAL)) {
6060 sprintf (symbol, "ut_%d", get_method_index (acfg, method));
6062 emit_section_change (acfg, ".text", 0);
6063 #ifdef __native_client_codegen__
6064 emit_alignment (acfg, AOT_FUNC_ALIGNMENT);
6067 if (acfg->thumb_mixed && cfg->compile_llvm)
6068 fprintf (acfg->fp, "\n.thumb_func\n");
6070 emit_label (acfg, symbol);
6072 arch_emit_unbox_trampoline (acfg, cfg, cfg->orig_method, cfg->asm_symbol);
6075 if (cfg->compile_llvm)
6076 acfg->stats.llvm_count ++;
6078 emit_method_code (acfg, cfg);
6081 sprintf (symbol, "methods_end");
6082 emit_section_change (acfg, ".text", 0);
6083 emit_alignment (acfg, 8);
6084 emit_label (acfg, symbol);
6087 * Add .no_dead_strip directives for all LLVM methods to prevent the OSX linker
6088 * from optimizing them away, since it doesn't see that code_offsets references them.
6089 * JITted methods don't need this since they are referenced using assembler local
6091 * FIXME: This is why write-symbols doesn't work on OSX ?
6093 if (acfg->llvm && acfg->need_no_dead_strip) {
6094 fprintf (acfg->fp, "\n");
6095 for (i = 0; i < acfg->nmethods; ++i) {
6096 if (acfg->cfgs [i] && acfg->cfgs [i]->compile_llvm)
6097 fprintf (acfg->fp, ".no_dead_strip %s\n", acfg->cfgs [i]->asm_symbol);
6102 if (acfg->direct_method_addresses) {
6103 acfg->flags |= MONO_AOT_FILE_FLAG_DIRECT_METHOD_ADDRESSES;
6105 sprintf (symbol, "method_addresses");
6106 emit_section_change (acfg, RODATA_SECT, 1);
6107 emit_alignment (acfg, 8);
6108 emit_label (acfg, symbol);
6110 for (i = 0; i < acfg->nmethods; ++i) {
6111 if (acfg->cfgs [i]) {
6112 emit_pointer (acfg, acfg->cfgs [i]->asm_symbol);
6114 emit_pointer (acfg, NULL);
6119 sprintf (symbol, "code_offsets");
6120 emit_section_change (acfg, RODATA_SECT, 1);
6121 emit_alignment (acfg, 8);
6122 emit_label (acfg, symbol);
6124 sprintf (symbol, "code_offsets");
6125 emit_section_change (acfg, RODATA_SECT, 1);
6126 emit_alignment (acfg, 8);
6127 emit_label (acfg, symbol);
6129 acfg->stats.offsets_size += acfg->nmethods * 4;
6131 sprintf (end_symbol, "methods");
6132 for (i = 0; i < acfg->nmethods; ++i) {
6133 if (acfg->cfgs [i]) {
6134 emit_symbol_diff (acfg, acfg->cfgs [i]->asm_symbol, end_symbol, 0);
6136 emit_int32 (acfg, 0xffffffff);
6141 sprintf (symbol, "code_offsets");
6142 emit_section_change (acfg, RODATA_SECT, 1);
6143 emit_alignment (acfg, 8);
6144 emit_label (acfg, symbol);
6146 acfg->stats.offsets_size += acfg->nmethods * 4;
6148 sprintf (end_symbol, "methods");
6149 for (i = 0; i < acfg->nmethods; ++i) {
6150 if (acfg->cfgs [i]) {
6151 emit_symbol_diff (acfg, acfg->cfgs [i]->asm_symbol, end_symbol, 0);
6153 emit_int32 (acfg, 0xffffffff);
6159 /* Emit a sorted table mapping methods to their unbox trampolines */
6160 sprintf (symbol, "unbox_trampolines");
6161 emit_section_change (acfg, RODATA_SECT, 1);
6162 emit_alignment (acfg, 8);
6163 emit_label (acfg, symbol);
6165 sprintf (end_symbol, "methods");
6167 for (i = 0; i < acfg->nmethods; ++i) {
6172 cfg = acfg->cfgs [i];
6176 method = cfg->orig_method;
6178 if (acfg->aot_opts.full_aot && cfg->orig_method->klass->valuetype && (method->flags & METHOD_ATTRIBUTE_VIRTUAL)) {
6179 index = get_method_index (acfg, method);
6180 sprintf (symbol, "ut_%d", index);
6182 emit_int32 (acfg, index);
6183 emit_symbol_diff (acfg, symbol, end_symbol, 0);
6184 /* Make sure the table is sorted by index */
6185 g_assert (index > prev_index);
6189 sprintf (symbol, "unbox_trampolines_end");
6190 emit_label (acfg, symbol);
6194 emit_info (MonoAotCompile *acfg)
6200 offsets = g_new0 (gint32, acfg->nmethods);
6202 for (oindex = 0; oindex < acfg->method_order->len; ++oindex) {
6203 i = GPOINTER_TO_UINT (g_ptr_array_index (acfg->method_order, oindex));
6205 if (acfg->cfgs [i]) {
6206 emit_method_info (acfg, acfg->cfgs [i]);
6207 offsets [i] = acfg->cfgs [i]->method_info_offset;
6213 sprintf (symbol, "method_info_offsets");
6214 emit_section_change (acfg, RODATA_SECT, 1);
6215 emit_alignment (acfg, 8);
6216 emit_label (acfg, symbol);
6218 acfg->stats.offsets_size += emit_offset_table (acfg, acfg->nmethods, 10, offsets);
6223 #endif /* #if !defined(DISABLE_AOT) && !defined(DISABLE_JIT) */
6225 #define rot(x,k) (((x)<<(k)) | ((x)>>(32-(k))))
6226 #define mix(a,b,c) { \
6227 a -= c; a ^= rot(c, 4); c += b; \
6228 b -= a; b ^= rot(a, 6); a += c; \
6229 c -= b; c ^= rot(b, 8); b += a; \
6230 a -= c; a ^= rot(c,16); c += b; \
6231 b -= a; b ^= rot(a,19); a += c; \
6232 c -= b; c ^= rot(b, 4); b += a; \
6234 #define final(a,b,c) { \
6235 c ^= b; c -= rot(b,14); \
6236 a ^= c; a -= rot(c,11); \
6237 b ^= a; b -= rot(a,25); \
6238 c ^= b; c -= rot(b,16); \
6239 a ^= c; a -= rot(c,4); \
6240 b ^= a; b -= rot(a,14); \
6241 c ^= b; c -= rot(b,24); \
6245 mono_aot_type_hash (MonoType *t1)
6247 guint hash = t1->type;
6249 hash |= t1->byref << 6; /* do not collide with t1->type values */
6251 case MONO_TYPE_VALUETYPE:
6252 case MONO_TYPE_CLASS:
6253 case MONO_TYPE_SZARRAY:
6254 /* check if the distribution is good enough */
6255 return ((hash << 5) - hash) ^ mono_metadata_str_hash (t1->data.klass->name);
6257 return ((hash << 5) - hash) ^ mono_metadata_type_hash (t1->data.type);
6258 case MONO_TYPE_ARRAY:
6259 return ((hash << 5) - hash) ^ mono_metadata_type_hash (&t1->data.array->eklass->byval_arg);
6260 case MONO_TYPE_GENERICINST:
6261 return ((hash << 5) - hash) ^ 0;
6268 * mono_aot_method_hash:
6270 * Return a hash code for methods which only depends on metadata.
6273 mono_aot_method_hash (MonoMethod *method)
6275 MonoMethodSignature *sig;
6279 guint32 *hashes_start, *hashes;
6281 MonoGenericInst *ginst = NULL;
6283 /* Similar to the hash in mono_method_get_imt_slot () */
6285 sig = mono_method_signature (method);
6287 if (method->is_inflated)
6288 ginst = ((MonoMethodInflated*)method)->context.method_inst;
6290 hashes_count = sig->param_count + 5 + (ginst ? ginst->type_argc : 0);
6291 hashes_start = g_malloc0 (hashes_count * sizeof (guint32));
6292 hashes = hashes_start;
6294 /* Some wrappers are assigned to random classes */
6295 if (!method->wrapper_type || method->wrapper_type == MONO_WRAPPER_REMOTING_INVOKE_WITH_CHECK)
6296 klass = method->klass;
6298 klass = mono_defaults.object_class;
6300 if (!method->wrapper_type) {
6301 char *full_name = mono_type_full_name (&klass->byval_arg);
6303 hashes [0] = mono_metadata_str_hash (full_name);
6307 hashes [0] = mono_metadata_str_hash (klass->name);
6308 hashes [1] = mono_metadata_str_hash (klass->name_space);
6310 if (method->wrapper_type == MONO_WRAPPER_STFLD || method->wrapper_type == MONO_WRAPPER_LDFLD || method->wrapper_type == MONO_WRAPPER_LDFLDA)
6311 /* The method name includes a stringified pointer */
6314 hashes [2] = mono_metadata_str_hash (method->name);
6315 hashes [3] = method->wrapper_type;
6316 hashes [4] = mono_aot_type_hash (sig->ret);
6318 for (i = 0; i < sig->param_count; i++) {
6319 hashes [hindex ++] = mono_aot_type_hash (sig->params [i]);
6322 for (i = 0; i < ginst->type_argc; ++i)
6323 hashes [hindex ++] = mono_aot_type_hash (ginst->type_argv [i]);
6325 g_assert (hindex == hashes_count);
6327 /* Setup internal state */
6328 a = b = c = 0xdeadbeef + (((guint32)hashes_count)<<2);
6330 /* Handle most of the hashes */
6331 while (hashes_count > 3) {
6340 /* Handle the last 3 hashes (all the case statements fall through) */
6341 switch (hashes_count) {
6342 case 3 : c += hashes [2];
6343 case 2 : b += hashes [1];
6344 case 1 : a += hashes [0];
6346 case 0: /* nothing left to add */
6350 free (hashes_start);
6359 * mono_aot_wrapper_name:
6361 * Return a string which uniqely identifies the given wrapper method.
6364 mono_aot_wrapper_name (MonoMethod *method)
6366 char *name, *tmpsig, *klass_desc;
6368 tmpsig = mono_signature_get_desc (mono_method_signature (method), TRUE);
6370 switch (method->wrapper_type) {
6371 case MONO_WRAPPER_RUNTIME_INVOKE:
6372 if (!strcmp (method->name, "runtime_invoke_dynamic"))
6373 name = g_strdup_printf ("(wrapper runtime-invoke-dynamic)");
6375 name = g_strdup_printf ("%s (%s)", method->name, tmpsig);
6378 klass_desc = mono_type_full_name (&method->klass->byval_arg);
6379 name = g_strdup_printf ("%s:%s (%s)", klass_desc, method->name, tmpsig);
6380 g_free (klass_desc);
6390 * mono_aot_get_array_helper_from_wrapper;
6392 * Get the helper method in Array called by an array wrapper method.
6395 mono_aot_get_array_helper_from_wrapper (MonoMethod *method)
6399 MonoGenericContext ctx;
6400 MonoType *args [16];
6401 char *mname, *iname, *s, *s2, *helper_name = NULL;
6403 prefix = "System.Collections.Generic";
6404 s = g_strdup_printf ("%s", method->name + strlen (prefix) + 1);
6405 s2 = strstr (s, "`1.");
6411 //printf ("X: %s %s\n", iname, mname);
6413 if (!strcmp (iname, "IList"))
6414 helper_name = g_strdup_printf ("InternalArray__%s", mname);
6416 helper_name = g_strdup_printf ("InternalArray__%s_%s", iname, mname);
6417 m = mono_class_get_method_from_name (mono_defaults.array_class, helper_name, mono_method_signature (method)->param_count);
6419 g_free (helper_name);
6422 if (m->is_generic) {
6423 memset (&ctx, 0, sizeof (ctx));
6424 args [0] = &method->klass->element_class->byval_arg;
6425 ctx.method_inst = mono_metadata_get_generic_inst (1, args);
6426 m = mono_class_inflate_generic_method (m, &ctx);
6432 #if !defined(DISABLE_AOT) && !defined(DISABLE_JIT)
6434 typedef struct HashEntry {
6435 guint32 key, value, index;
6436 struct HashEntry *next;
6440 * emit_extra_methods:
6442 * Emit methods which are not in the METHOD table, like wrappers.
6445 emit_extra_methods (MonoAotCompile *acfg)
6447 int i, table_size, buf_size;
6450 guint32 *info_offsets;
6453 HashEntry *entry, *new_entry;
6454 int nmethods, max_chain_length;
6457 info_offsets = g_new0 (guint32, acfg->extra_methods->len);
6459 /* Emit method info */
6461 for (i = 0; i < acfg->extra_methods->len; ++i) {
6462 MonoMethod *method = g_ptr_array_index (acfg->extra_methods, i);
6463 MonoCompile *cfg = g_hash_table_lookup (acfg->method_to_cfg, method);
6469 p = buf = g_malloc (buf_size);
6473 method = cfg->method_to_register;
6475 encode_method_ref (acfg, method, p, &p);
6477 g_assert ((p - buf) < buf_size);
6479 info_offsets [i] = add_to_blob (acfg, buf, p - buf);
6484 * Construct a chained hash table for mapping indexes in extra_method_info to
6487 table_size = g_spaced_primes_closest ((int)(nmethods * 1.5));
6488 table = g_ptr_array_sized_new (table_size);
6489 for (i = 0; i < table_size; ++i)
6490 g_ptr_array_add (table, NULL);
6491 chain_lengths = g_new0 (int, table_size);
6492 max_chain_length = 0;
6493 for (i = 0; i < acfg->extra_methods->len; ++i) {
6494 MonoMethod *method = g_ptr_array_index (acfg->extra_methods, i);
6495 MonoCompile *cfg = g_hash_table_lookup (acfg->method_to_cfg, method);
6501 key = info_offsets [i];
6502 value = get_method_index (acfg, method);
6504 hash = mono_aot_method_hash (method) % table_size;
6506 chain_lengths [hash] ++;
6507 max_chain_length = MAX (max_chain_length, chain_lengths [hash]);
6509 new_entry = mono_mempool_alloc0 (acfg->mempool, sizeof (HashEntry));
6510 new_entry->key = key;
6511 new_entry->value = value;
6513 entry = g_ptr_array_index (table, hash);
6514 if (entry == NULL) {
6515 new_entry->index = hash;
6516 g_ptr_array_index (table, hash) = new_entry;
6519 entry = entry->next;
6521 entry->next = new_entry;
6522 new_entry->index = table->len;
6523 g_ptr_array_add (table, new_entry);
6527 //printf ("MAX: %d\n", max_chain_length);
6529 /* Emit the table */
6530 sprintf (symbol, "extra_method_table");
6531 emit_section_change (acfg, RODATA_SECT, 0);
6532 emit_alignment (acfg, 8);
6533 emit_label (acfg, symbol);
6535 emit_int32 (acfg, table_size);
6536 for (i = 0; i < table->len; ++i) {
6537 HashEntry *entry = g_ptr_array_index (table, i);
6539 if (entry == NULL) {
6540 emit_int32 (acfg, 0);
6541 emit_int32 (acfg, 0);
6542 emit_int32 (acfg, 0);
6544 //g_assert (entry->key > 0);
6545 emit_int32 (acfg, entry->key);
6546 emit_int32 (acfg, entry->value);
6548 emit_int32 (acfg, entry->next->index);
6550 emit_int32 (acfg, 0);
6555 * Emit a table reverse mapping method indexes to their index in extra_method_info.
6556 * This is used by mono_aot_find_jit_info ().
6558 sprintf (symbol, "extra_method_info_offsets");
6559 emit_section_change (acfg, RODATA_SECT, 0);
6560 emit_alignment (acfg, 8);
6561 emit_label (acfg, symbol);
6563 emit_int32 (acfg, acfg->extra_methods->len);
6564 for (i = 0; i < acfg->extra_methods->len; ++i) {
6565 MonoMethod *method = g_ptr_array_index (acfg->extra_methods, i);
6567 emit_int32 (acfg, get_method_index (acfg, method));
6568 emit_int32 (acfg, info_offsets [i]);
6573 emit_exception_info (MonoAotCompile *acfg)
6579 offsets = g_new0 (gint32, acfg->nmethods);
6580 for (i = 0; i < acfg->nmethods; ++i) {
6581 if (acfg->cfgs [i]) {
6582 emit_exception_debug_info (acfg, acfg->cfgs [i]);
6583 offsets [i] = acfg->cfgs [i]->ex_info_offset;
6589 sprintf (symbol, "ex_info_offsets");
6590 emit_section_change (acfg, RODATA_SECT, 1);
6591 emit_alignment (acfg, 8);
6592 emit_label (acfg, symbol);
6594 acfg->stats.offsets_size += emit_offset_table (acfg, acfg->nmethods, 10, offsets);
6599 emit_unwind_info (MonoAotCompile *acfg)
6605 * The unwind info contains a lot of duplicates so we emit each unique
6606 * entry once, and only store the offset from the start of the table in the
6610 sprintf (symbol, "unwind_info");
6611 emit_section_change (acfg, RODATA_SECT, 1);
6612 emit_alignment (acfg, 8);
6613 emit_label (acfg, symbol);
6615 for (i = 0; i < acfg->unwind_ops->len; ++i) {
6616 guint32 index = GPOINTER_TO_UINT (g_ptr_array_index (acfg->unwind_ops, i));
6617 guint8 *unwind_info;
6618 guint32 unwind_info_len;
6622 unwind_info = mono_get_cached_unwind_info (index, &unwind_info_len);
6625 encode_value (unwind_info_len, p, &p);
6626 emit_bytes (acfg, buf, p - buf);
6627 emit_bytes (acfg, unwind_info, unwind_info_len);
6629 acfg->stats.unwind_info_size += (p - buf) + unwind_info_len;
6634 emit_class_info (MonoAotCompile *acfg)
6640 offsets = g_new0 (gint32, acfg->image->tables [MONO_TABLE_TYPEDEF].rows);
6641 for (i = 0; i < acfg->image->tables [MONO_TABLE_TYPEDEF].rows; ++i)
6642 offsets [i] = emit_klass_info (acfg, MONO_TOKEN_TYPE_DEF | (i + 1));
6644 sprintf (symbol, "class_info_offsets");
6645 emit_section_change (acfg, RODATA_SECT, 1);
6646 emit_alignment (acfg, 8);
6647 emit_label (acfg, symbol);
6649 acfg->stats.offsets_size += emit_offset_table (acfg, acfg->image->tables [MONO_TABLE_TYPEDEF].rows, 10, offsets);
6653 typedef struct ClassNameTableEntry {
6654 guint32 token, index;
6655 struct ClassNameTableEntry *next;
6656 } ClassNameTableEntry;
6659 emit_class_name_table (MonoAotCompile *acfg)
6662 guint32 token, hash;
6667 ClassNameTableEntry *entry, *new_entry;
6670 * Construct a chained hash table for mapping class names to typedef tokens.
6672 table_size = g_spaced_primes_closest ((int)(acfg->image->tables [MONO_TABLE_TYPEDEF].rows * 1.5));
6673 table = g_ptr_array_sized_new (table_size);
6674 for (i = 0; i < table_size; ++i)
6675 g_ptr_array_add (table, NULL);
6676 for (i = 0; i < acfg->image->tables [MONO_TABLE_TYPEDEF].rows; ++i) {
6677 token = MONO_TOKEN_TYPE_DEF | (i + 1);
6678 klass = mono_class_get (acfg->image, token);
6680 mono_loader_clear_error ();
6683 full_name = mono_type_get_name_full (mono_class_get_type (klass), MONO_TYPE_NAME_FORMAT_FULL_NAME);
6684 hash = mono_metadata_str_hash (full_name) % table_size;
6687 /* FIXME: Allocate from the mempool */
6688 new_entry = g_new0 (ClassNameTableEntry, 1);
6689 new_entry->token = token;
6691 entry = g_ptr_array_index (table, hash);
6692 if (entry == NULL) {
6693 new_entry->index = hash;
6694 g_ptr_array_index (table, hash) = new_entry;
6697 entry = entry->next;
6699 entry->next = new_entry;
6700 new_entry->index = table->len;
6701 g_ptr_array_add (table, new_entry);
6705 /* Emit the table */
6706 sprintf (symbol, "class_name_table");
6707 emit_section_change (acfg, RODATA_SECT, 0);
6708 emit_alignment (acfg, 8);
6709 emit_label (acfg, symbol);
6711 /* FIXME: Optimize memory usage */
6712 g_assert (table_size < 65000);
6713 emit_int16 (acfg, table_size);
6714 g_assert (table->len < 65000);
6715 for (i = 0; i < table->len; ++i) {
6716 ClassNameTableEntry *entry = g_ptr_array_index (table, i);
6718 if (entry == NULL) {
6719 emit_int16 (acfg, 0);
6720 emit_int16 (acfg, 0);
6722 emit_int16 (acfg, mono_metadata_token_index (entry->token));
6724 emit_int16 (acfg, entry->next->index);
6726 emit_int16 (acfg, 0);
6732 emit_image_table (MonoAotCompile *acfg)
6738 * The image table is small but referenced in a lot of places.
6739 * So we emit it at once, and reference its elements by an index.
6742 sprintf (symbol, "image_table");
6743 emit_section_change (acfg, RODATA_SECT, 1);
6744 emit_alignment (acfg, 8);
6745 emit_label (acfg, symbol);
6747 emit_int32 (acfg, acfg->image_table->len);
6748 for (i = 0; i < acfg->image_table->len; i++) {
6749 MonoImage *image = (MonoImage*)g_ptr_array_index (acfg->image_table, i);
6750 MonoAssemblyName *aname = &image->assembly->aname;
6752 /* FIXME: Support multi-module assemblies */
6753 g_assert (image->assembly->image == image);
6755 emit_string (acfg, image->assembly_name);
6756 emit_string (acfg, image->guid);
6757 emit_string (acfg, aname->culture ? aname->culture : "");
6758 emit_string (acfg, (const char*)aname->public_key_token);
6760 emit_alignment (acfg, 8);
6761 emit_int32 (acfg, aname->flags);
6762 emit_int32 (acfg, aname->major);
6763 emit_int32 (acfg, aname->minor);
6764 emit_int32 (acfg, aname->build);
6765 emit_int32 (acfg, aname->revision);
6770 emit_got_info (MonoAotCompile *acfg)
6773 int i, first_plt_got_patch, buf_size;
6775 guint32 *got_info_offsets;
6777 /* Add the patches needed by the PLT to the GOT */
6778 acfg->plt_got_offset_base = acfg->got_offset;
6779 first_plt_got_patch = acfg->got_patches->len;
6780 for (i = 1; i < acfg->plt_offset; ++i) {
6781 MonoPltEntry *plt_entry = g_hash_table_lookup (acfg->plt_offset_to_entry, GUINT_TO_POINTER (i));
6783 g_ptr_array_add (acfg->got_patches, plt_entry->ji);
6785 acfg->stats.got_slot_types [plt_entry->ji->type] ++;
6788 acfg->got_offset += acfg->plt_offset;
6792 * - optimize offsets table.
6793 * - reduce number of exported symbols.
6794 * - emit info for a klass only once.
6795 * - determine when a method uses a GOT slot which is guaranteed to be already
6797 * - clean up and document the code.
6798 * - use String.Empty in class libs.
6801 /* Encode info required to decode shared GOT entries */
6802 buf_size = acfg->got_patches->len * 128;
6803 p = buf = mono_mempool_alloc (acfg->mempool, buf_size);
6804 got_info_offsets = mono_mempool_alloc (acfg->mempool, acfg->got_patches->len * sizeof (guint32));
6805 acfg->plt_got_info_offsets = mono_mempool_alloc (acfg->mempool, acfg->plt_offset * sizeof (guint32));
6807 if (acfg->plt_offset)
6808 acfg->plt_got_info_offsets [0] = 0;
6809 for (i = 0; i < acfg->got_patches->len; ++i) {
6810 MonoJumpInfo *ji = g_ptr_array_index (acfg->got_patches, i);
6815 encode_value (ji->type, p, &p);
6817 encode_patch (acfg, ji, p, &p);
6818 acfg->stats.got_slot_info_sizes [ji->type] += p - p2;
6819 g_assert (p - buf <= buf_size);
6820 got_info_offsets [i] = add_to_blob (acfg, buf, p - buf);
6822 if (i >= first_plt_got_patch)
6823 acfg->plt_got_info_offsets [i - first_plt_got_patch + 1] = got_info_offsets [i];
6824 acfg->stats.got_info_size += p - buf;
6827 /* Emit got_info_offsets table */
6828 sprintf (symbol, "got_info_offsets");
6829 emit_section_change (acfg, RODATA_SECT, 1);
6830 emit_alignment (acfg, 8);
6831 emit_label (acfg, symbol);
6833 /* No need to emit offsets for the got plt entries, the plt embeds them directly */
6834 acfg->stats.offsets_size += emit_offset_table (acfg, first_plt_got_patch, 10, (gint32*)got_info_offsets);
6838 emit_got (MonoAotCompile *acfg)
6843 /* Don't make GOT global so accesses to it don't need relocations */
6844 sprintf (symbol, "%s", acfg->got_symbol);
6845 emit_section_change (acfg, ".bss", 0);
6846 emit_alignment (acfg, 8);
6847 emit_local_symbol (acfg, symbol, "got_end", FALSE);
6848 emit_label (acfg, symbol);
6849 if (acfg->got_offset > 0)
6850 emit_zero_bytes (acfg, (int)(acfg->got_offset * sizeof (gpointer)));
6852 sprintf (symbol, "got_end");
6853 emit_label (acfg, symbol);
6857 typedef struct GlobalsTableEntry {
6858 guint32 value, index;
6859 struct GlobalsTableEntry *next;
6860 } GlobalsTableEntry;
6863 emit_globals (MonoAotCompile *acfg)
6869 GlobalsTableEntry *entry, *new_entry;
6871 if (!acfg->aot_opts.static_link)
6875 * When static linking, we emit a table containing our globals.
6879 * Construct a chained hash table for mapping global names to their index in
6880 * the globals table.
6882 table_size = g_spaced_primes_closest ((int)(acfg->globals->len * 1.5));
6883 table = g_ptr_array_sized_new (table_size);
6884 for (i = 0; i < table_size; ++i)
6885 g_ptr_array_add (table, NULL);
6886 for (i = 0; i < acfg->globals->len; ++i) {
6887 char *name = g_ptr_array_index (acfg->globals, i);
6889 hash = mono_metadata_str_hash (name) % table_size;
6891 /* FIXME: Allocate from the mempool */
6892 new_entry = g_new0 (GlobalsTableEntry, 1);
6893 new_entry->value = i;
6895 entry = g_ptr_array_index (table, hash);
6896 if (entry == NULL) {
6897 new_entry->index = hash;
6898 g_ptr_array_index (table, hash) = new_entry;
6901 entry = entry->next;
6903 entry->next = new_entry;
6904 new_entry->index = table->len;
6905 g_ptr_array_add (table, new_entry);
6909 /* Emit the table */
6910 sprintf (symbol, ".Lglobals_hash");
6911 emit_section_change (acfg, RODATA_SECT, 0);
6912 emit_alignment (acfg, 8);
6913 emit_label (acfg, symbol);
6915 /* FIXME: Optimize memory usage */
6916 g_assert (table_size < 65000);
6917 emit_int16 (acfg, table_size);
6918 for (i = 0; i < table->len; ++i) {
6919 GlobalsTableEntry *entry = g_ptr_array_index (table, i);
6921 if (entry == NULL) {
6922 emit_int16 (acfg, 0);
6923 emit_int16 (acfg, 0);
6925 emit_int16 (acfg, entry->value + 1);
6927 emit_int16 (acfg, entry->next->index);
6929 emit_int16 (acfg, 0);
6933 /* Emit the names */
6934 for (i = 0; i < acfg->globals->len; ++i) {
6935 char *name = g_ptr_array_index (acfg->globals, i);
6937 sprintf (symbol, "name_%d", i);
6938 emit_section_change (acfg, RODATA_SECT, 1);
6940 emit_alignment (acfg, 4);
6942 emit_label (acfg, symbol);
6943 emit_string (acfg, name);
6946 /* Emit the globals table */
6947 sprintf (symbol, "globals");
6948 emit_section_change (acfg, ".data", 0);
6949 /* This is not a global, since it is accessed by the init function */
6950 emit_alignment (acfg, 8);
6951 emit_label (acfg, symbol);
6953 sprintf (symbol, "%sglobals_hash", acfg->temp_prefix);
6954 emit_pointer (acfg, symbol);
6956 for (i = 0; i < acfg->globals->len; ++i) {
6957 char *name = g_ptr_array_index (acfg->globals, i);
6959 sprintf (symbol, "name_%d", i);
6960 emit_pointer (acfg, symbol);
6962 sprintf (symbol, "%s", name);
6963 emit_pointer (acfg, symbol);
6965 /* Null terminate the table */
6966 emit_int32 (acfg, 0);
6967 emit_int32 (acfg, 0);
6971 emit_autoreg (MonoAotCompile *acfg)
6976 * Emit a function into the .ctor section which will be called by the ELF
6977 * loader to register this module with the runtime.
6979 if (! (!acfg->use_bin_writer && acfg->aot_opts.static_link && acfg->aot_opts.autoreg))
6982 symbol = g_strdup_printf ("_%s_autoreg", acfg->static_linking_symbol);
6984 arch_emit_autoreg (acfg, symbol);
6990 emit_mem_end (MonoAotCompile *acfg)
6994 sprintf (symbol, "mem_end");
6995 emit_section_change (acfg, ".text", 1);
6996 emit_alignment (acfg, 8);
6997 emit_label (acfg, symbol);
7001 * Emit a structure containing all the information not stored elsewhere.
7004 emit_file_info (MonoAotCompile *acfg)
7009 const char *gc_name;
7012 emit_string_symbol (acfg, "assembly_guid" , acfg->image->guid);
7014 if (acfg->aot_opts.bind_to_runtime_version) {
7015 build_info = mono_get_runtime_build_info ();
7016 emit_string_symbol (acfg, "runtime_version", build_info);
7017 g_free (build_info);
7019 emit_string_symbol (acfg, "runtime_version", "");
7022 /* Emit a string holding the assembly name */
7023 emit_string_symbol (acfg, "assembly_name", acfg->image->assembly->aname.name);
7026 * The managed allocators are GC specific, so can't use an AOT image created by one GC
7029 gc_name = mono_gc_get_gc_name ();
7030 gc_name_offset = add_to_blob (acfg, (guint8*)gc_name, strlen (gc_name) + 1);
7032 sprintf (symbol, "mono_aot_file_info");
7033 emit_section_change (acfg, ".data", 0);
7034 emit_alignment (acfg, 8);
7035 emit_label (acfg, symbol);
7036 if (!acfg->aot_opts.static_link)
7037 emit_global (acfg, symbol, FALSE);
7039 /* The data emitted here must match MonoAotFileInfo. */
7041 emit_int32 (acfg, MONO_AOT_FILE_VERSION);
7042 emit_int32 (acfg, 0);
7045 * We emit pointers to our data structures instead of emitting global symbols which
7046 * point to them, to reduce the number of globals, and because using globals leads to
7047 * various problems (i.e. arm/thumb).
7049 emit_pointer (acfg, acfg->got_symbol);
7050 emit_pointer (acfg, "methods");
7053 * Emit a reference to the mono_eh_frame table created by our modified LLVM compiler.
7055 emit_pointer (acfg, "mono_eh_frame");
7057 emit_pointer (acfg, NULL);
7059 emit_pointer (acfg, "blob");
7060 emit_pointer (acfg, "class_name_table");
7061 emit_pointer (acfg, "class_info_offsets");
7062 emit_pointer (acfg, "method_info_offsets");
7063 emit_pointer (acfg, "ex_info_offsets");
7064 emit_pointer (acfg, "code_offsets");
7066 emit_pointer (acfg, "method_addresses");
7068 emit_pointer (acfg, "extra_method_info_offsets");
7069 emit_pointer (acfg, "extra_method_table");
7070 emit_pointer (acfg, "got_info_offsets");
7071 emit_pointer (acfg, "methods_end");
7072 emit_pointer (acfg, "unwind_info");
7073 emit_pointer (acfg, "mem_end");
7074 emit_pointer (acfg, "image_table");
7075 emit_pointer (acfg, "plt");
7076 emit_pointer (acfg, "plt_end");
7077 emit_pointer (acfg, "assembly_guid");
7078 emit_pointer (acfg, "runtime_version");
7079 if (acfg->num_trampoline_got_entries) {
7080 emit_pointer (acfg, "specific_trampolines");
7081 emit_pointer (acfg, "static_rgctx_trampolines");
7082 emit_pointer (acfg, "imt_thunks");
7084 emit_pointer (acfg, NULL);
7085 emit_pointer (acfg, NULL);
7086 emit_pointer (acfg, NULL);
7088 if (acfg->thumb_mixed) {
7089 emit_pointer (acfg, "thumb_end");
7091 emit_pointer (acfg, NULL);
7093 if (acfg->aot_opts.static_link) {
7094 emit_pointer (acfg, "globals");
7096 emit_pointer (acfg, NULL);
7098 emit_pointer (acfg, "assembly_name");
7099 emit_pointer (acfg, "unbox_trampolines");
7100 emit_pointer (acfg, "unbox_trampolines_end");
7102 emit_int32 (acfg, acfg->plt_got_offset_base);
7103 emit_int32 (acfg, (int)(acfg->got_offset * sizeof (gpointer)));
7104 emit_int32 (acfg, acfg->plt_offset);
7105 emit_int32 (acfg, acfg->nmethods);
7106 emit_int32 (acfg, acfg->flags);
7107 emit_int32 (acfg, acfg->opts);
7108 emit_int32 (acfg, acfg->simd_opts);
7109 emit_int32 (acfg, gc_name_offset);
7111 for (i = 0; i < MONO_AOT_TRAMP_NUM; ++i)
7112 emit_int32 (acfg, acfg->num_trampolines [i]);
7113 for (i = 0; i < MONO_AOT_TRAMP_NUM; ++i)
7114 emit_int32 (acfg, acfg->trampoline_got_offset_base [i]);
7115 for (i = 0; i < MONO_AOT_TRAMP_NUM; ++i)
7116 emit_int32 (acfg, acfg->trampoline_size [i]);
7118 #if defined (TARGET_ARM) && defined (TARGET_MACH)
7123 memset (&t, 0, sizeof (MonoType));
7124 t.type = MONO_TYPE_R8;
7125 mono_type_size (&t, &align);
7127 emit_int32 (acfg, align);
7129 memset (&t, 0, sizeof (MonoType));
7130 t.type = MONO_TYPE_I8;
7131 mono_type_size (&t, &align);
7133 emit_int32 (acfg, align);
7136 emit_int32 (acfg, __alignof__ (double));
7137 emit_int32 (acfg, __alignof__ (gint64));
7140 if (acfg->aot_opts.static_link) {
7144 * Emit a global symbol which can be passed by an embedding app to
7145 * mono_aot_register_module (). The symbol points to a pointer to the the file info
7148 #if defined(TARGET_MACH) && !defined(__native_client_codegen__)
7149 sprintf (symbol, "_mono_aot_module_%s_info", acfg->image->assembly->aname.name);
7151 sprintf (symbol, "mono_aot_module_%s_info", acfg->image->assembly->aname.name);
7154 /* Get rid of characters which cannot occur in symbols */
7156 for (p = symbol; *p; ++p) {
7157 if (!(isalnum (*p) || *p == '_'))
7160 acfg->static_linking_symbol = g_strdup (symbol);
7161 emit_global_inner (acfg, symbol, FALSE);
7162 emit_label (acfg, symbol);
7163 emit_pointer (acfg, "mono_aot_file_info");
7168 emit_blob (MonoAotCompile *acfg)
7172 sprintf (symbol, "blob");
7173 emit_section_change (acfg, RODATA_SECT, 1);
7174 emit_alignment (acfg, 8);
7175 emit_label (acfg, symbol);
7177 emit_bytes (acfg, (guint8*)acfg->blob.data, acfg->blob.index);
7181 emit_dwarf_info (MonoAotCompile *acfg)
7183 #ifdef EMIT_DWARF_INFO
7187 /* DIEs for methods */
7188 for (i = 0; i < acfg->nmethods; ++i) {
7189 MonoCompile *cfg = acfg->cfgs [i];
7194 // FIXME: LLVM doesn't define .Lme_...
7195 if (cfg->compile_llvm)
7198 sprintf (symbol2, "%sme_%x", acfg->temp_prefix, i);
7200 mono_dwarf_writer_emit_method (acfg->dwarf, cfg, cfg->method, cfg->asm_symbol, symbol2, cfg->jit_info->code_start, cfg->jit_info->code_size, cfg->args, cfg->locals, cfg->unwind_ops, mono_debug_find_method (cfg->jit_info->method, mono_domain_get ()));
7206 collect_methods (MonoAotCompile *acfg)
7209 MonoImage *image = acfg->image;
7211 /* Collect methods */
7212 for (i = 0; i < image->tables [MONO_TABLE_METHOD].rows; ++i) {
7214 guint32 token = MONO_TOKEN_METHOD_DEF | (i + 1);
7216 method = mono_get_method (acfg->image, token, NULL);
7219 printf ("Failed to load method 0x%x from '%s'.\n", token, image->name);
7223 /* Load all methods eagerly to skip the slower lazy loading code */
7224 mono_class_setup_methods (method->klass);
7226 if (acfg->aot_opts.full_aot && method->iflags & METHOD_IMPL_ATTRIBUTE_INTERNAL_CALL) {
7227 /* Compile the wrapper instead */
7228 /* We do this here instead of add_wrappers () because it is easy to do it here */
7229 MonoMethod *wrapper = mono_marshal_get_native_wrapper (method, check_for_pending_exc, TRUE);
7233 /* FIXME: Some mscorlib methods don't have debug info */
7235 if (acfg->aot_opts.soft_debug && !method->wrapper_type) {
7236 if (!((method->flags & METHOD_ATTRIBUTE_PINVOKE_IMPL) ||
7237 (method->iflags & METHOD_IMPL_ATTRIBUTE_RUNTIME) ||
7238 (method->flags & METHOD_ATTRIBUTE_ABSTRACT) ||
7239 (method->iflags & METHOD_IMPL_ATTRIBUTE_INTERNAL_CALL))) {
7240 if (!mono_debug_lookup_method (method)) {
7241 fprintf (stderr, "Method %s has no debug info, probably the .mdb file for the assembly is missing.\n", mono_method_full_name (method, TRUE));
7248 /* Since we add the normal methods first, their index will be equal to their zero based token index */
7249 add_method_with_index (acfg, method, i, FALSE);
7250 acfg->method_index ++;
7253 add_generic_instances (acfg);
7255 if (acfg->aot_opts.full_aot)
7256 add_wrappers (acfg);
7260 compile_methods (MonoAotCompile *acfg)
7264 if (acfg->aot_opts.nthreads > 0) {
7269 gpointer *user_data;
7270 MonoMethod **methods;
7272 methods_len = acfg->methods->len;
7274 len = acfg->methods->len / acfg->aot_opts.nthreads;
7277 * Partition the list of methods into fragments, and hand it to threads to
7280 threads = g_ptr_array_new ();
7281 /* Make a copy since acfg->methods is modified by compile_method () */
7282 methods = g_new0 (MonoMethod*, methods_len);
7283 //memcpy (methods, g_ptr_array_index (acfg->methods, 0), sizeof (MonoMethod*) * methods_len);
7284 for (i = 0; i < methods_len; ++i)
7285 methods [i] = g_ptr_array_index (acfg->methods, i);
7287 while (i < methods_len) {
7288 frag = g_ptr_array_new ();
7289 for (j = 0; j < len; ++j) {
7290 if (i < methods_len) {
7291 g_ptr_array_add (frag, methods [i]);
7296 user_data = g_new0 (gpointer, 3);
7297 user_data [0] = mono_domain_get ();
7298 user_data [1] = acfg;
7299 user_data [2] = frag;
7301 handle = mono_create_thread (NULL, 0, (gpointer)compile_thread_main, user_data, 0, NULL);
7302 g_ptr_array_add (threads, handle);
7306 for (i = 0; i < threads->len; ++i) {
7307 WaitForSingleObjectEx (g_ptr_array_index (threads, i), INFINITE, FALSE);
7313 /* Compile methods added by compile_method () or all methods if nthreads == 0 */
7314 for (i = methods_len; i < acfg->methods->len; ++i) {
7315 /* This can new methods to acfg->methods */
7316 compile_method (acfg, g_ptr_array_index (acfg->methods, i));
7321 compile_asm (MonoAotCompile *acfg)
7323 char *command, *objfile;
7324 char *outfile_name, *tmp_outfile_name;
7325 const char *tool_prefix = acfg->aot_opts.tool_prefix ? acfg->aot_opts.tool_prefix : "";
7327 #if defined(TARGET_AMD64)
7328 #define AS_OPTIONS "--64"
7329 #elif defined(TARGET_POWERPC64)
7330 #define AS_OPTIONS "-a64 -mppc64"
7331 #define LD_OPTIONS "-m elf64ppc"
7332 #elif defined(sparc) && SIZEOF_VOID_P == 8
7333 #define AS_OPTIONS "-xarch=v9"
7334 #elif defined(TARGET_X86) && defined(TARGET_MACH) && !defined(__native_client_codegen__)
7335 #define AS_OPTIONS "-arch i386 -W"
7337 #define AS_OPTIONS ""
7340 #ifdef __native_client_codegen__
7341 #if defined(TARGET_AMD64)
7342 #define AS_NAME "nacl64-as"
7344 #define AS_NAME "nacl-as"
7347 #define AS_NAME "as"
7351 #define LD_OPTIONS ""
7354 #define EH_LD_OPTIONS ""
7356 if (acfg->aot_opts.asm_only) {
7357 printf ("Output file: '%s'.\n", acfg->tmpfname);
7358 if (acfg->aot_opts.static_link)
7359 printf ("Linking symbol: '%s'.\n", acfg->static_linking_symbol);
7363 if (acfg->aot_opts.static_link) {
7364 if (acfg->aot_opts.outfile)
7365 objfile = g_strdup_printf ("%s", acfg->aot_opts.outfile);
7367 objfile = g_strdup_printf ("%s.o", acfg->image->name);
7369 objfile = g_strdup_printf ("%s.o", acfg->tmpfname);
7371 command = g_strdup_printf ("%s%s %s %s -o %s %s", tool_prefix, AS_NAME, AS_OPTIONS, acfg->as_args ? acfg->as_args->str : "", objfile, acfg->tmpfname);
7372 printf ("Executing the native assembler: %s\n", command);
7373 if (system (command) != 0) {
7381 if (acfg->aot_opts.static_link) {
7382 printf ("Output file: '%s'.\n", objfile);
7383 printf ("Linking symbol: '%s'.\n", acfg->static_linking_symbol);
7388 if (acfg->aot_opts.outfile)
7389 outfile_name = g_strdup_printf ("%s", acfg->aot_opts.outfile);
7391 outfile_name = g_strdup_printf ("%s%s", acfg->image->name, SHARED_EXT);
7393 tmp_outfile_name = g_strdup_printf ("%s.tmp", outfile_name);
7396 command = g_strdup_printf ("ld -shared -G -o %s %s.o", tmp_outfile_name, acfg->tmpfname);
7397 #elif defined(__ppc__) && defined(TARGET_MACH)
7398 command = g_strdup_printf ("gcc -dynamiclib -o %s %s.o", tmp_outfile_name, acfg->tmpfname);
7399 #elif defined(HOST_WIN32)
7400 command = g_strdup_printf ("gcc -shared --dll -mno-cygwin -o %s %s.o", tmp_outfile_name, acfg->tmpfname);
7401 #elif defined(TARGET_X86) && defined(TARGET_MACH) && !defined(__native_client_codegen__)
7402 command = g_strdup_printf ("gcc -m32 -dynamiclib -o %s %s.o", tmp_outfile_name, acfg->tmpfname);
7404 command = g_strdup_printf ("%sld %s %s -shared -o %s %s.o", tool_prefix, EH_LD_OPTIONS, LD_OPTIONS, tmp_outfile_name, acfg->tmpfname);
7406 printf ("Executing the native linker: %s\n", command);
7407 if (system (command) != 0) {
7408 g_free (tmp_outfile_name);
7409 g_free (outfile_name);
7417 /*com = g_strdup_printf ("strip --strip-unneeded %s%s", acfg->image->name, SHARED_EXT);
7418 printf ("Stripping the binary: %s\n", com);
7422 #if defined(TARGET_ARM) && !defined(TARGET_MACH)
7424 * gas generates 'mapping symbols' each time code and data is mixed, which
7425 * happens a lot in emit_and_reloc_code (), so we need to get rid of them.
7427 command = g_strdup_printf ("%sstrip --strip-symbol=\\$a --strip-symbol=\\$d %s", tool_prefix, tmp_outfile_name);
7428 printf ("Stripping the binary: %s\n", command);
7429 if (system (command) != 0) {
7430 g_free (tmp_outfile_name);
7431 g_free (outfile_name);
7438 rename (tmp_outfile_name, outfile_name);
7440 #if defined(TARGET_MACH)
7441 command = g_strdup_printf ("dsymutil %s", outfile_name);
7442 printf ("Generating debug symbols: %s\n", command);
7443 if (system (command) != 0) {
7448 if (!acfg->aot_opts.save_temps)
7451 g_free (tmp_outfile_name);
7452 g_free (outfile_name);
7455 if (acfg->aot_opts.save_temps)
7456 printf ("Retained input file.\n");
7458 unlink (acfg->tmpfname);
7463 static MonoAotCompile*
7464 acfg_create (MonoAssembly *ass, guint32 opts)
7466 MonoImage *image = ass->image;
7467 MonoAotCompile *acfg;
7470 acfg = g_new0 (MonoAotCompile, 1);
7471 acfg->methods = g_ptr_array_new ();
7472 acfg->method_indexes = g_hash_table_new (NULL, NULL);
7473 acfg->method_depth = g_hash_table_new (NULL, NULL);
7474 acfg->plt_offset_to_entry = g_hash_table_new (NULL, NULL);
7475 acfg->patch_to_plt_entry = g_hash_table_new (mono_patch_info_hash, mono_patch_info_equal);
7476 acfg->patch_to_got_offset = g_hash_table_new (mono_patch_info_hash, mono_patch_info_equal);
7477 acfg->patch_to_got_offset_by_type = g_new0 (GHashTable*, MONO_PATCH_INFO_NUM);
7478 for (i = 0; i < MONO_PATCH_INFO_NUM; ++i)
7479 acfg->patch_to_got_offset_by_type [i] = g_hash_table_new (mono_patch_info_hash, mono_patch_info_equal);
7480 acfg->got_patches = g_ptr_array_new ();
7481 acfg->method_to_cfg = g_hash_table_new (NULL, NULL);
7482 acfg->token_info_hash = g_hash_table_new_full (NULL, NULL, NULL, g_free);
7483 acfg->method_to_pinvoke_import = g_hash_table_new_full (NULL, NULL, NULL, g_free);
7484 acfg->image_hash = g_hash_table_new (NULL, NULL);
7485 acfg->image_table = g_ptr_array_new ();
7486 acfg->globals = g_ptr_array_new ();
7487 acfg->image = image;
7489 /* TODO: Write out set of SIMD instructions used, rather than just those available */
7490 acfg->simd_opts = mono_arch_cpu_enumerate_simd_versions ();
7491 acfg->mempool = mono_mempool_new ();
7492 acfg->extra_methods = g_ptr_array_new ();
7493 acfg->unwind_info_offsets = g_hash_table_new (NULL, NULL);
7494 acfg->unwind_ops = g_ptr_array_new ();
7495 acfg->method_label_hash = g_hash_table_new_full (g_str_hash, g_str_equal, g_free, NULL);
7496 acfg->method_order = g_ptr_array_new ();
7497 acfg->export_names = g_hash_table_new (NULL, NULL);
7498 acfg->klass_blob_hash = g_hash_table_new (NULL, NULL);
7499 acfg->method_blob_hash = g_hash_table_new (NULL, NULL);
7500 acfg->plt_entry_debug_sym_cache = g_hash_table_new (g_str_hash, g_str_equal);
7501 InitializeCriticalSection (&acfg->mutex);
7507 acfg_free (MonoAotCompile *acfg)
7511 img_writer_destroy (acfg->w);
7512 for (i = 0; i < acfg->nmethods; ++i)
7514 g_free (acfg->cfgs [i]);
7515 g_free (acfg->cfgs);
7516 g_free (acfg->static_linking_symbol);
7517 g_free (acfg->got_symbol);
7518 g_free (acfg->plt_symbol);
7519 g_ptr_array_free (acfg->methods, TRUE);
7520 g_ptr_array_free (acfg->got_patches, TRUE);
7521 g_ptr_array_free (acfg->image_table, TRUE);
7522 g_ptr_array_free (acfg->globals, TRUE);
7523 g_ptr_array_free (acfg->unwind_ops, TRUE);
7524 g_hash_table_destroy (acfg->method_indexes);
7525 g_hash_table_destroy (acfg->method_depth);
7526 g_hash_table_destroy (acfg->plt_offset_to_entry);
7527 g_hash_table_destroy (acfg->patch_to_plt_entry);
7528 g_hash_table_destroy (acfg->patch_to_got_offset);
7529 g_hash_table_destroy (acfg->method_to_cfg);
7530 g_hash_table_destroy (acfg->token_info_hash);
7531 g_hash_table_destroy (acfg->method_to_pinvoke_import);
7532 g_hash_table_destroy (acfg->image_hash);
7533 g_hash_table_destroy (acfg->unwind_info_offsets);
7534 g_hash_table_destroy (acfg->method_label_hash);
7535 g_hash_table_destroy (acfg->export_names);
7536 g_hash_table_destroy (acfg->plt_entry_debug_sym_cache);
7537 g_hash_table_destroy (acfg->klass_blob_hash);
7538 g_hash_table_destroy (acfg->method_blob_hash);
7539 for (i = 0; i < MONO_PATCH_INFO_NUM; ++i)
7540 g_hash_table_destroy (acfg->patch_to_got_offset_by_type [i]);
7541 g_free (acfg->patch_to_got_offset_by_type);
7542 mono_mempool_destroy (acfg->mempool);
7547 mono_compile_assembly (MonoAssembly *ass, guint32 opts, const char *aot_options)
7549 MonoImage *image = ass->image;
7551 MonoAotCompile *acfg;
7552 char *outfile_name, *tmp_outfile_name, *p;
7556 printf ("Mono Ahead of Time compiler - compiling assembly %s\n", image->name);
7558 acfg = acfg_create (ass, opts);
7560 memset (&acfg->aot_opts, 0, sizeof (acfg->aot_opts));
7561 acfg->aot_opts.write_symbols = TRUE;
7562 acfg->aot_opts.ntrampolines = 1024;
7563 acfg->aot_opts.nrgctx_trampolines = 1024;
7564 acfg->aot_opts.nimt_trampolines = 128;
7565 acfg->aot_opts.llvm_path = g_strdup ("");
7567 mono_aot_parse_options (aot_options, &acfg->aot_opts);
7569 if (acfg->aot_opts.static_link)
7570 acfg->aot_opts.autoreg = TRUE;
7572 //acfg->aot_opts.print_skipped_methods = TRUE;
7574 #ifndef MONO_ARCH_HAVE_FULL_AOT_TRAMPOLINES
7575 if (acfg->aot_opts.full_aot) {
7576 printf ("--aot=full is not supported on this platform.\n");
7581 if (acfg->aot_opts.direct_pinvoke && !acfg->aot_opts.static_link) {
7582 fprintf (stderr, "The 'direct-pinvoke' AOT option also requires the 'static' AOT option.\n");
7586 if (acfg->aot_opts.static_link)
7587 acfg->aot_opts.asm_writer = TRUE;
7589 if (acfg->aot_opts.soft_debug) {
7590 MonoDebugOptions *opt = mini_get_debug_options ();
7592 opt->mdb_optimizations = TRUE;
7593 opt->gen_seq_points = TRUE;
7595 if (mono_debug_format == MONO_DEBUG_FORMAT_NONE) {
7596 fprintf (stderr, "The soft-debug AOT option requires the --debug option.\n");
7599 acfg->flags |= MONO_AOT_FILE_FLAG_DEBUG;
7602 if (mono_use_llvm) {
7604 acfg->aot_opts.asm_writer = TRUE;
7605 acfg->flags |= MONO_AOT_FILE_FLAG_WITH_LLVM;
7607 if (acfg->aot_opts.soft_debug) {
7608 fprintf (stderr, "The 'soft-debug' option is not supported when compiling with LLVM.\n");
7613 if (acfg->aot_opts.full_aot)
7614 acfg->flags |= MONO_AOT_FILE_FLAG_FULL_AOT;
7616 load_profile_files (acfg);
7618 acfg->num_trampolines [MONO_AOT_TRAMP_SPECIFIC] = acfg->aot_opts.full_aot ? acfg->aot_opts.ntrampolines : 0;
7619 #ifdef MONO_ARCH_GSHARED_SUPPORTED
7620 acfg->num_trampolines [MONO_AOT_TRAMP_STATIC_RGCTX] = acfg->aot_opts.full_aot ? acfg->aot_opts.nrgctx_trampolines : 0;
7622 acfg->num_trampolines [MONO_AOT_TRAMP_IMT_THUNK] = acfg->aot_opts.full_aot ? acfg->aot_opts.nimt_trampolines : 0;
7624 acfg->temp_prefix = img_writer_get_temp_label_prefix (NULL);
7628 acfg->got_symbol_base = g_strdup_printf ("mono_aot_%s_got", acfg->image->assembly->aname.name);
7629 acfg->plt_symbol = g_strdup_printf ("%smono_aot_%s_plt", acfg->llvm_label_prefix, acfg->image->assembly->aname.name);
7630 acfg->assembly_name_sym = g_strdup (acfg->image->assembly->aname.name);
7632 /* Get rid of characters which cannot occur in symbols */
7633 for (p = acfg->got_symbol_base; *p; ++p) {
7634 if (!(isalnum (*p) || *p == '_'))
7637 for (p = acfg->plt_symbol; *p; ++p) {
7638 if (!(isalnum (*p) || *p == '_'))
7641 for (p = acfg->assembly_name_sym; *p; ++p) {
7642 if (!(isalnum (*p) || *p == '_'))
7646 acfg->method_index = 1;
7648 collect_methods (acfg);
7650 acfg->cfgs_size = acfg->methods->len + 32;
7651 acfg->cfgs = g_new0 (MonoCompile*, acfg->cfgs_size);
7653 /* PLT offset 0 is reserved for the PLT trampoline */
7654 acfg->plt_offset = 1;
7659 mono_llvm_create_aot_module (acfg->got_symbol_base);
7663 /* GOT offset 0 is reserved for the address of the current assembly */
7667 ji = mono_mempool_alloc0 (acfg->mempool, sizeof (MonoAotCompile));
7668 ji->type = MONO_PATCH_INFO_IMAGE;
7669 ji->data.image = acfg->image;
7671 get_got_offset (acfg, ji);
7673 /* Slot 1 is reserved for the mscorlib got addr */
7674 ji = mono_mempool_alloc0 (acfg->mempool, sizeof (MonoAotCompile));
7675 ji->type = MONO_PATCH_INFO_MSCORLIB_GOT_ADDR;
7676 get_got_offset (acfg, ji);
7678 /* This is very common */
7679 ji = mono_mempool_alloc0 (acfg->mempool, sizeof (MonoAotCompile));
7680 ji->type = MONO_PATCH_INFO_GC_CARD_TABLE_ADDR;
7681 get_got_offset (acfg, ji);
7686 compile_methods (acfg);
7690 acfg->stats.jit_time = TV_ELAPSED (atv, btv);
7696 if (acfg->aot_opts.asm_only) {
7697 if (acfg->aot_opts.outfile)
7698 acfg->tmpfname = g_strdup_printf ("%s", acfg->aot_opts.outfile);
7700 acfg->tmpfname = g_strdup_printf ("%s.s", acfg->image->name);
7702 acfg->tmpfname = g_strdup ("temp.s");
7705 emit_llvm_file (acfg);
7709 if (!acfg->aot_opts.asm_only && !acfg->aot_opts.asm_writer && bin_writer_supported ()) {
7710 if (acfg->aot_opts.outfile)
7711 outfile_name = g_strdup_printf ("%s", acfg->aot_opts.outfile);
7713 outfile_name = g_strdup_printf ("%s%s", acfg->image->name, SHARED_EXT);
7716 * Can't use g_file_open_tmp () as it will be deleted at exit, and
7717 * it might be in another file system so the rename () won't work.
7719 tmp_outfile_name = g_strdup_printf ("%s.tmp", outfile_name);
7721 acfg->fp = fopen (tmp_outfile_name, "w");
7723 printf ("Unable to create temporary file '%s': %s\n", tmp_outfile_name, strerror (errno));
7727 acfg->w = img_writer_create (acfg->fp, TRUE);
7728 acfg->use_bin_writer = TRUE;
7731 /* Append to the .s file created by llvm */
7732 /* FIXME: Use multiple files instead */
7733 acfg->fp = fopen (acfg->tmpfname, "a+");
7735 if (acfg->aot_opts.asm_only) {
7736 if (acfg->aot_opts.outfile)
7737 acfg->tmpfname = g_strdup_printf ("%s", acfg->aot_opts.outfile);
7739 acfg->tmpfname = g_strdup_printf ("%s.s", acfg->image->name);
7740 acfg->fp = fopen (acfg->tmpfname, "w+");
7742 int i = g_file_open_tmp ("mono_aot_XXXXXX", &acfg->tmpfname, NULL);
7743 acfg->fp = fdopen (i, "w+");
7745 if (acfg->fp == 0) {
7746 fprintf (stderr, "Unable to open file '%s': %s\n", acfg->tmpfname, strerror (errno));
7750 acfg->w = img_writer_create (acfg->fp, FALSE);
7752 tmp_outfile_name = NULL;
7753 outfile_name = NULL;
7756 acfg->got_symbol = g_strdup_printf ("%s%s", acfg->llvm_label_prefix, acfg->got_symbol_base);
7758 /* Compute symbols for methods */
7759 for (i = 0; i < acfg->nmethods; ++i) {
7760 if (acfg->cfgs [i]) {
7761 MonoCompile *cfg = acfg->cfgs [i];
7762 int method_index = get_method_index (acfg, cfg->orig_method);
7764 if (COMPILE_LLVM (cfg))
7765 cfg->asm_symbol = g_strdup_printf ("%s%s", acfg->llvm_label_prefix, cfg->llvm_method_name);
7766 else if (acfg->global_symbols)
7767 cfg->asm_symbol = get_debug_sym (cfg->method, "", acfg->method_label_hash);
7769 cfg->asm_symbol = g_strdup_printf ("%s%sm_%x", acfg->temp_prefix, acfg->llvm_label_prefix, method_index);
7773 if (!acfg->aot_opts.nodebug)
7774 acfg->dwarf = mono_dwarf_writer_create (acfg->w, NULL, 0, FALSE);
7776 img_writer_emit_start (acfg->w);
7779 mono_dwarf_writer_emit_base_info (acfg->dwarf, mono_unwind_get_cie_program ());
7781 if (acfg->thumb_mixed) {
7784 * This global symbol marks the end of THUMB code, and the beginning of ARM
7785 * code generated by our JIT.
7787 sprintf (symbol, "thumb_end");
7788 emit_section_change (acfg, ".text", 0);
7789 emit_alignment (acfg, 8);
7790 emit_label (acfg, symbol);
7791 emit_zero_bytes (acfg, 16);
7793 fprintf (acfg->fp, ".arm\n");
7800 emit_extra_methods (acfg);
7802 emit_trampolines (acfg);
7804 emit_class_name_table (acfg);
7806 emit_got_info (acfg);
7808 emit_exception_info (acfg);
7810 emit_unwind_info (acfg);
7812 emit_class_info (acfg);
7816 emit_image_table (acfg);
7820 emit_file_info (acfg);
7824 emit_globals (acfg);
7826 emit_autoreg (acfg);
7829 emit_dwarf_info (acfg);
7830 mono_dwarf_writer_close (acfg->dwarf);
7833 emit_mem_end (acfg);
7835 if (acfg->need_pt_gnu_stack) {
7836 /* This is required so the .so doesn't have an executable stack */
7837 /* The bin writer already emits this */
7838 if (!acfg->use_bin_writer)
7839 fprintf (acfg->fp, "\n.section .note.GNU-stack,\"\",@progbits\n");
7844 acfg->stats.gen_time = TV_ELAPSED (atv, btv);
7847 g_assert (acfg->got_offset <= acfg->final_got_size);
7849 printf ("Code: %d Info: %d Ex Info: %d Unwind Info: %d Class Info: %d PLT: %d GOT Info: %d GOT: %d Offsets: %d\n", acfg->stats.code_size, acfg->stats.info_size, acfg->stats.ex_info_size, acfg->stats.unwind_info_size, acfg->stats.class_info_size, acfg->plt_offset, acfg->stats.got_info_size, (int)(acfg->got_offset * sizeof (gpointer)), acfg->stats.offsets_size);
7850 printf ("Compiled: %d/%d (%d%%), No GOT slots: %d (%d%%), Direct calls: %d (%d%%)\n",
7851 acfg->stats.ccount, acfg->stats.mcount, acfg->stats.mcount ? (acfg->stats.ccount * 100) / acfg->stats.mcount : 100,
7852 acfg->stats.methods_without_got_slots, acfg->stats.mcount ? (acfg->stats.methods_without_got_slots * 100) / acfg->stats.mcount : 100,
7853 acfg->stats.direct_calls, acfg->stats.all_calls ? (acfg->stats.direct_calls * 100) / acfg->stats.all_calls : 100);
7854 if (acfg->stats.genericcount)
7855 printf ("%d methods are generic (%d%%)\n", acfg->stats.genericcount, acfg->stats.mcount ? (acfg->stats.genericcount * 100) / acfg->stats.mcount : 100);
7856 if (acfg->stats.abscount)
7857 printf ("%d methods contain absolute addresses (%d%%)\n", acfg->stats.abscount, acfg->stats.mcount ? (acfg->stats.abscount * 100) / acfg->stats.mcount : 100);
7858 if (acfg->stats.lmfcount)
7859 printf ("%d methods contain lmf pointers (%d%%)\n", acfg->stats.lmfcount, acfg->stats.mcount ? (acfg->stats.lmfcount * 100) / acfg->stats.mcount : 100);
7860 if (acfg->stats.ocount)
7861 printf ("%d methods have other problems (%d%%)\n", acfg->stats.ocount, acfg->stats.mcount ? (acfg->stats.ocount * 100) / acfg->stats.mcount : 100);
7863 printf ("Methods compiled with LLVM: %d (%d%%)\n", acfg->stats.llvm_count, acfg->stats.mcount ? (acfg->stats.llvm_count * 100) / acfg->stats.mcount : 100);
7866 res = img_writer_emit_writeout (acfg->w);
7871 if (acfg->use_bin_writer) {
7872 int err = rename (tmp_outfile_name, outfile_name);
7875 printf ("Unable to rename '%s' to '%s': %s\n", tmp_outfile_name, outfile_name, strerror (errno));
7879 res = compile_asm (acfg);
7886 acfg->stats.link_time = TV_ELAPSED (atv, btv);
7888 if (acfg->aot_opts.stats) {
7891 printf ("GOT slot distribution:\n");
7892 for (i = 0; i < MONO_PATCH_INFO_NONE; ++i)
7893 if (acfg->stats.got_slot_types [i])
7894 printf ("\t%s: %d (%d)\n", get_patch_name (i), acfg->stats.got_slot_types [i], acfg->stats.got_slot_info_sizes [i]);
7897 printf ("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);
7909 mono_aot_readonly_field_override (MonoClassField *field)
7915 mono_compile_assembly (MonoAssembly *ass, guint32 opts, const char *aot_options)