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"
69 #if !defined(DISABLE_AOT) && !defined(DISABLE_JIT)
71 #if defined(__linux__) || defined(__native_client_codegen__)
72 #define RODATA_SECT ".rodata"
74 #define RODATA_SECT ".text"
77 #define TV_DECLARE(name) gint64 name
78 #define TV_GETTIME(tv) tv = mono_100ns_ticks ()
79 #define TV_ELAPSED(start,end) (((end) - (start)) / 10)
82 #define SHARED_EXT ".dll"
83 #elif defined(__ppc__) && defined(__APPLE__)
84 #define SHARED_EXT ".dylib"
85 #elif defined(__APPLE__) && defined(TARGET_X86) && !defined(__native_client_codegen__)
86 #define SHARED_EXT ".dylib"
88 #define SHARED_EXT ".so"
91 #define ALIGN_TO(val,align) ((((guint64)val) + ((align) - 1)) & ~((align) - 1))
92 #define ALIGN_PTR_TO(ptr,align) (gpointer)((((gssize)(ptr)) + (align - 1)) & (~(align - 1)))
93 #define ROUND_DOWN(VALUE,SIZE) ((VALUE) & ~((SIZE) - 1))
95 /* predefined values for static readonly fields without needed to run the .cctor */
96 typedef struct _ReadOnlyValue ReadOnlyValue;
97 struct _ReadOnlyValue {
100 int type; /* to be used later for typechecking to prevent user errors */
109 static ReadOnlyValue *readonly_values = NULL;
111 typedef struct MonoAotOptions {
114 gboolean write_symbols;
115 gboolean metadata_only;
116 gboolean bind_to_runtime_version;
119 gboolean static_link;
124 gboolean log_generics;
125 gboolean direct_pinvoke;
126 gboolean direct_icalls;
129 int nrgctx_trampolines;
130 int nimt_trampolines;
131 gboolean print_skipped_methods;
139 typedef struct MonoAotStats {
140 int ccount, mcount, lmfcount, abscount, gcount, ocount, genericcount;
141 int code_size, info_size, ex_info_size, unwind_info_size, got_size, class_info_size, got_info_size;
142 int methods_without_got_slots, direct_calls, all_calls, llvm_count;
143 int got_slots, offsets_size;
144 int got_slot_types [MONO_PATCH_INFO_NONE];
145 int got_slot_info_sizes [MONO_PATCH_INFO_NONE];
146 int jit_time, gen_time, link_time;
149 typedef struct MonoAotCompile {
152 GHashTable *method_indexes;
153 GHashTable *method_depth;
156 GHashTable *patch_to_plt_entry;
157 GHashTable *plt_offset_to_entry;
158 GHashTable *patch_to_got_offset;
159 GHashTable **patch_to_got_offset_by_type;
160 GPtrArray *got_patches;
161 GHashTable *image_hash;
162 GHashTable *method_to_cfg;
163 GHashTable *token_info_hash;
164 GHashTable *method_to_pinvoke_import;
165 GPtrArray *extra_methods;
166 GPtrArray *image_table;
168 GPtrArray *method_order;
169 GHashTable *export_names;
170 /* Maps MonoClass* -> blob offset */
171 GHashTable *klass_blob_hash;
172 /* Maps MonoMethod* -> blob offset */
173 GHashTable *method_blob_hash;
174 guint32 *plt_got_info_offsets;
175 guint32 got_offset, plt_offset, plt_got_offset_base;
176 guint32 final_got_size;
177 /* Number of GOT entries reserved for trampolines */
178 guint32 num_trampoline_got_entries;
180 guint32 num_trampolines [MONO_AOT_TRAMP_NUM];
181 guint32 trampoline_got_offset_base [MONO_AOT_TRAMP_NUM];
182 guint32 trampoline_size [MONO_AOT_TRAMP_NUM];
184 MonoAotOptions aot_opts;
187 MonoMemPool *mempool;
190 char *static_linking_symbol;
191 CRITICAL_SECTION mutex;
192 gboolean use_bin_writer;
194 MonoDwarfWriter *dwarf;
198 GHashTable *unwind_info_offsets;
199 GPtrArray *unwind_ops;
200 guint32 unwind_info_offset;
201 char *got_symbol_base;
204 GHashTable *method_label_hash;
205 const char *temp_prefix;
206 const char *llvm_label_prefix;
207 guint32 label_generator;
209 MonoAotFileFlags flags;
210 MonoDynamicStream blob;
211 MonoClass **typespec_classes;
214 char *assembly_name_sym;
215 GHashTable *plt_entry_debug_sym_cache;
216 gboolean thumb_mixed, need_no_dead_strip, need_pt_gnu_stack;
217 GHashTable *ginst_hash;
222 char *symbol, *llvm_symbol, *debug_sym;
224 gboolean jit_used, llvm_used;
227 #define mono_acfg_lock(acfg) EnterCriticalSection (&((acfg)->mutex))
228 #define mono_acfg_unlock(acfg) LeaveCriticalSection (&((acfg)->mutex))
230 /* This points to the current acfg in LLVM mode */
231 static MonoAotCompile *llvm_acfg;
233 #ifdef HAVE_ARRAY_ELEM_INIT
234 #define MSGSTRFIELD(line) MSGSTRFIELD1(line)
235 #define MSGSTRFIELD1(line) str##line
236 static const struct msgstr_t {
237 #define PATCH_INFO(a,b) char MSGSTRFIELD(__LINE__) [sizeof (b)];
238 #include "patch-info.h"
241 #define PATCH_INFO(a,b) b,
242 #include "patch-info.h"
245 static const gint16 opidx [] = {
246 #define PATCH_INFO(a,b) [MONO_PATCH_INFO_ ## a] = offsetof (struct msgstr_t, MSGSTRFIELD(__LINE__)),
247 #include "patch-info.h"
251 static G_GNUC_UNUSED const char*
252 get_patch_name (int info)
254 return (const char*)&opstr + opidx [info];
258 #define PATCH_INFO(a,b) b,
259 static const char* const
260 patch_types [MONO_PATCH_INFO_NUM + 1] = {
261 #include "patch-info.h"
265 static G_GNUC_UNUSED const char*
266 get_patch_name (int info)
268 return patch_types [info];
274 get_plt_entry_debug_sym (MonoAotCompile *acfg, MonoJumpInfo *ji, GHashTable *cache);
276 /* Wrappers around the image writer functions */
279 emit_section_change (MonoAotCompile *acfg, const char *section_name, int subsection_index)
281 img_writer_emit_section_change (acfg->w, section_name, subsection_index);
285 emit_push_section (MonoAotCompile *acfg, const char *section_name, int subsection)
287 img_writer_emit_push_section (acfg->w, section_name, subsection);
291 emit_pop_section (MonoAotCompile *acfg)
293 img_writer_emit_pop_section (acfg->w);
297 emit_local_symbol (MonoAotCompile *acfg, const char *name, const char *end_label, gboolean func)
299 img_writer_emit_local_symbol (acfg->w, name, end_label, func);
303 emit_label (MonoAotCompile *acfg, const char *name)
305 img_writer_emit_label (acfg->w, name);
309 emit_bytes (MonoAotCompile *acfg, const guint8* buf, int size)
311 img_writer_emit_bytes (acfg->w, buf, size);
315 emit_string (MonoAotCompile *acfg, const char *value)
317 img_writer_emit_string (acfg->w, value);
321 emit_line (MonoAotCompile *acfg)
323 img_writer_emit_line (acfg->w);
327 emit_alignment (MonoAotCompile *acfg, int size)
329 img_writer_emit_alignment (acfg->w, size);
333 emit_pointer_unaligned (MonoAotCompile *acfg, const char *target)
335 img_writer_emit_pointer_unaligned (acfg->w, target);
339 emit_pointer (MonoAotCompile *acfg, const char *target)
341 img_writer_emit_pointer (acfg->w, target);
345 emit_int16 (MonoAotCompile *acfg, int value)
347 img_writer_emit_int16 (acfg->w, value);
351 emit_int32 (MonoAotCompile *acfg, int value)
353 img_writer_emit_int32 (acfg->w, value);
357 emit_symbol_diff (MonoAotCompile *acfg, const char *end, const char* start, int offset)
359 img_writer_emit_symbol_diff (acfg->w, end, start, offset);
363 emit_zero_bytes (MonoAotCompile *acfg, int num)
365 img_writer_emit_zero_bytes (acfg->w, num);
369 emit_byte (MonoAotCompile *acfg, guint8 val)
371 img_writer_emit_byte (acfg->w, val);
374 #ifdef __native_client_codegen__
376 emit_nacl_call_alignment (MonoAotCompile *acfg)
378 img_writer_emit_nacl_call_alignment (acfg->w);
382 static G_GNUC_UNUSED void
383 emit_global_inner (MonoAotCompile *acfg, const char *name, gboolean func)
385 img_writer_emit_global (acfg->w, name, func);
389 emit_global (MonoAotCompile *acfg, const char *name, gboolean func)
391 if (acfg->aot_opts.no_dlsym) {
392 g_ptr_array_add (acfg->globals, g_strdup (name));
393 img_writer_emit_local_symbol (acfg->w, name, NULL, func);
395 img_writer_emit_global (acfg->w, name, func);
400 emit_symbol_size (MonoAotCompile *acfg, const char *name, const char *end_label)
402 img_writer_emit_symbol_size (acfg->w, name, end_label);
406 emit_string_symbol (MonoAotCompile *acfg, const char *name, const char *value)
408 img_writer_emit_section_change (acfg->w, RODATA_SECT, 1);
410 /* On apple, all symbols need to be aligned to avoid warnings from ld */
411 emit_alignment (acfg, 4);
413 img_writer_emit_label (acfg->w, name);
414 img_writer_emit_string (acfg->w, value);
417 static G_GNUC_UNUSED void
418 emit_uleb128 (MonoAotCompile *acfg, guint32 value)
421 guint8 b = value & 0x7f;
423 if (value != 0) /* more bytes to come */
429 static G_GNUC_UNUSED void
430 emit_sleb128 (MonoAotCompile *acfg, gint64 value)
433 gboolean negative = (value < 0);
440 /* the following is unnecessary if the
441 * implementation of >>= uses an arithmetic rather
442 * than logical shift for a signed left operand
446 value |= - ((gint64)1 <<(size - 7));
447 /* sign bit of byte is second high order bit (0x40) */
448 if ((value == 0 && !(byte & 0x40)) ||
449 (value == -1 && (byte & 0x40)))
453 emit_byte (acfg, byte);
457 static G_GNUC_UNUSED void
458 encode_uleb128 (guint32 value, guint8 *buf, guint8 **endbuf)
463 guint8 b = value & 0x7f;
465 if (value != 0) /* more bytes to come */
473 static G_GNUC_UNUSED void
474 encode_sleb128 (gint32 value, guint8 *buf, guint8 **endbuf)
477 gboolean negative = (value < 0);
485 /* the following is unnecessary if the
486 * implementation of >>= uses an arithmetic rather
487 * than logical shift for a signed left operand
491 value |= - (1 <<(size - 7));
492 /* sign bit of byte is second high order bit (0x40) */
493 if ((value == 0 && !(byte & 0x40)) ||
494 (value == -1 && (byte & 0x40)))
504 /* ARCHITECTURE SPECIFIC CODE */
506 #if defined(TARGET_X86) || defined(TARGET_AMD64) || defined(TARGET_ARM) || defined(TARGET_POWERPC)
507 #define EMIT_DWARF_INFO 1
510 #if defined(TARGET_ARM)
511 #define AOT_FUNC_ALIGNMENT 4
513 #define AOT_FUNC_ALIGNMENT 16
515 #if (defined(TARGET_X86) || defined(TARGET_AMD64)) && defined(__native_client_codegen__)
516 #undef AOT_FUNC_ALIGNMENT
517 #define AOT_FUNC_ALIGNMENT 32
520 #if defined(TARGET_POWERPC64) && !defined(__mono_ilp32__)
521 #define PPC_LD_OP "ld"
522 #define PPC_LDX_OP "ldx"
524 #define PPC_LD_OP "lwz"
525 #define PPC_LDX_OP "lwzx"
529 #define AOT_TARGET_STR "AMD64"
534 #define AOT_TARGET_STR "ARM (MACH)"
536 #define AOT_TARGET_STR "ARM (!MACH)"
540 #ifdef TARGET_POWERPC64
541 #ifdef __mono_ilp32__
542 #define AOT_TARGET_STR "POWERPC64 (mono ilp32)"
544 #define AOT_TARGET_STR "POWERPC64 (!mono ilp32)"
547 #ifdef TARGET_POWERPC
548 #ifdef __mono_ilp32__
549 #define AOT_TARGET_STR "POWERPC (mono ilp32)"
551 #define AOT_TARGET_STR "POWERPC (!mono ilp32)"
558 #define AOT_TARGET_STR "X86 (WIN32)"
559 #elif defined(__native_client_codegen__)
560 #define AOT_TARGET_STR "X86 (native client codegen)"
562 #define AOT_TARGET_STR "X86 (!native client codegen)"
566 #ifndef AOT_TARGET_STR
567 #define AOT_TARGET_STR ""
571 arch_init (MonoAotCompile *acfg)
573 acfg->llc_args = g_string_new ("");
574 acfg->as_args = g_string_new ("");
577 * The prefix LLVM likes to put in front of symbol names on darwin.
578 * The mach-os specs require this for globals, but LLVM puts them in front of all
579 * symbols. We need to handle this, since we need to refer to LLVM generated
582 acfg->llvm_label_prefix = "";
585 if (acfg->aot_opts.mtriple && strstr (acfg->aot_opts.mtriple, "darwin")) {
586 g_string_append (acfg->llc_args, "-mattr=+v6");
589 g_string_append (acfg->llc_args, " -mattr=+vfp2,+d16");
590 g_string_append (acfg->as_args, " -mfpu=vfp3");
592 g_string_append (acfg->llc_args, " -soft-float");
595 if (acfg->aot_opts.mtriple && strstr (acfg->aot_opts.mtriple, "thumb"))
596 acfg->thumb_mixed = TRUE;
598 if (acfg->aot_opts.mtriple)
599 mono_arch_set_target (acfg->aot_opts.mtriple);
603 acfg->llvm_label_prefix = "_";
604 acfg->need_no_dead_strip = TRUE;
607 #if defined(__linux__) && !defined(TARGET_ARM)
608 acfg->need_pt_gnu_stack = TRUE;
613 * arch_emit_direct_call:
615 * Emit a direct call to the symbol TARGET. CALL_SIZE is set to the size of the
619 arch_emit_direct_call (MonoAotCompile *acfg, const char *target, int *call_size)
621 #if defined(TARGET_X86) || defined(TARGET_AMD64)
622 /* Need to make sure this is exactly 5 bytes long */
623 if (FALSE && !acfg->use_bin_writer) {
624 img_writer_emit_unset_mode (acfg->w);
625 fprintf (acfg->fp, "call %s\n", target);
627 emit_byte (acfg, '\xe8');
628 emit_symbol_diff (acfg, target, ".", -4);
631 #elif defined(TARGET_ARM)
632 if (acfg->use_bin_writer) {
639 img_writer_emit_reloc (acfg->w, R_ARM_CALL, target, -8);
640 emit_bytes (acfg, buf, 4);
642 img_writer_emit_unset_mode (acfg->w);
643 fprintf (acfg->fp, "bl %s\n", target);
646 #elif defined(TARGET_POWERPC)
647 if (acfg->use_bin_writer) {
648 g_assert_not_reached ();
650 img_writer_emit_unset_mode (acfg->w);
651 fprintf (acfg->fp, "bl %s\n", target);
655 g_assert_not_reached ();
661 * - we use an approach similar to the x86 abi: reserve a register (r30) to hold
663 * - The full-aot trampolines need access to the GOT of mscorlib, so we store
664 * in in the 2. slot of every GOT, and require every method to place the GOT
665 * address in r30, even when it doesn't access the GOT otherwise. This way,
666 * the trampolines can compute the mscorlib GOT address by loading 4(r30).
671 * PPC64 uses function descriptors which greatly complicate all code, since
672 * these are used very inconsistently in the runtime. Some functions like
673 * mono_compile_method () return ftn descriptors, while others like the
674 * trampoline creation functions do not.
675 * We assume that all GOT slots contain function descriptors, and create
676 * descriptors in aot-runtime.c when needed.
677 * The ppc64 abi uses r2 to hold the address of the TOC/GOT, which is loaded
678 * from function descriptors, we could do the same, but it would require
679 * rewriting all the ppc/aot code to handle function descriptors properly.
680 * So instead, we use the same approach as on PPC32.
681 * This is a horrible mess, but fixing it would probably lead to an even bigger
687 * - similar to the PPC32 design, we reserve EBX to hold the GOT pointer.
690 #ifdef MONO_ARCH_AOT_SUPPORTED
692 * arch_emit_got_offset:
694 * The memory pointed to by CODE should hold native code for computing the GOT
695 * address. Emit this code while patching it with the offset between code and
696 * the GOT. CODE_SIZE is set to the number of bytes emitted.
699 arch_emit_got_offset (MonoAotCompile *acfg, guint8 *code, int *code_size)
701 #if defined(TARGET_POWERPC64)
702 g_assert (!acfg->use_bin_writer);
703 img_writer_emit_unset_mode (acfg->w);
705 * The ppc32 code doesn't seem to work on ppc64, the assembler complains about
706 * unsupported relocations. So we store the got address into the .Lgot_addr
707 * symbol which is in the text segment, compute its address, and load it.
709 fprintf (acfg->fp, ".L%d:\n", acfg->label_generator);
710 fprintf (acfg->fp, "lis 0, (.Lgot_addr + 4 - .L%d)@h\n", acfg->label_generator);
711 fprintf (acfg->fp, "ori 0, 0, (.Lgot_addr + 4 - .L%d)@l\n", acfg->label_generator);
712 fprintf (acfg->fp, "add 30, 30, 0\n");
713 fprintf (acfg->fp, "%s 30, 0(30)\n", PPC_LD_OP);
714 acfg->label_generator ++;
716 #elif defined(TARGET_POWERPC)
717 g_assert (!acfg->use_bin_writer);
718 img_writer_emit_unset_mode (acfg->w);
719 fprintf (acfg->fp, ".L%d:\n", acfg->label_generator);
720 fprintf (acfg->fp, "lis 0, (%s + 4 - .L%d)@h\n", acfg->got_symbol, acfg->label_generator);
721 fprintf (acfg->fp, "ori 0, 0, (%s + 4 - .L%d)@l\n", acfg->got_symbol, acfg->label_generator);
722 acfg->label_generator ++;
725 guint32 offset = mono_arch_get_patch_offset (code);
726 emit_bytes (acfg, code, offset);
727 emit_symbol_diff (acfg, acfg->got_symbol, ".", offset);
729 *code_size = offset + 4;
734 * arch_emit_got_access:
736 * The memory pointed to by CODE should hold native code for loading a GOT
737 * slot. Emit this code while patching it so it accesses the GOT slot GOT_SLOT.
738 * CODE_SIZE is set to the number of bytes emitted.
741 arch_emit_got_access (MonoAotCompile *acfg, guint8 *code, int got_slot, int *code_size)
743 /* Emit beginning of instruction */
744 emit_bytes (acfg, code, mono_arch_get_patch_offset (code));
746 /* Emit the offset */
748 emit_symbol_diff (acfg, acfg->got_symbol, ".", (unsigned int) ((got_slot * sizeof (gpointer)) - 4));
749 *code_size = mono_arch_get_patch_offset (code) + 4;
750 #elif defined(TARGET_X86)
751 emit_int32 (acfg, (unsigned int) ((got_slot * sizeof (gpointer))));
752 *code_size = mono_arch_get_patch_offset (code) + 4;
753 #elif defined(TARGET_ARM)
754 emit_symbol_diff (acfg, acfg->got_symbol, ".", (unsigned int) ((got_slot * sizeof (gpointer))) - 12);
755 *code_size = mono_arch_get_patch_offset (code) + 4;
756 #elif defined(TARGET_POWERPC)
762 ppc_load32 (code, ppc_r0, got_slot * sizeof (gpointer));
763 g_assert (code - buf == 8);
764 emit_bytes (acfg, buf, code - buf);
765 *code_size = code - buf;
768 g_assert_not_reached ();
775 * arch_emit_plt_entry:
777 * Emit code for the PLT entry with index INDEX.
780 arch_emit_plt_entry (MonoAotCompile *acfg, int index)
782 #if defined(TARGET_X86)
783 guint32 offset = (acfg->plt_got_offset_base + index) * sizeof (gpointer);
784 #if defined(__default_codegen__)
785 /* jmp *<offset>(%ebx) */
786 emit_byte (acfg, 0xff);
787 emit_byte (acfg, 0xa3);
788 emit_int32 (acfg, offset);
789 /* Used by mono_aot_get_plt_info_offset */
790 emit_int32 (acfg, acfg->plt_got_info_offsets [index]);
791 #elif defined(__native_client_codegen__)
792 const guint8 kSizeOfNaClJmp = 11;
793 guint8 bytes[kSizeOfNaClJmp];
794 guint8 *pbytes = &bytes[0];
796 x86_jump_membase32 (pbytes, X86_EBX, offset);
797 emit_bytes (acfg, bytes, kSizeOfNaClJmp);
798 /* four bytes of data, used by mono_arch_patch_plt_entry */
799 /* For Native Client, make this work with data embedded in push. */
800 emit_byte (acfg, 0x68); /* hide data in a push */
801 emit_int32 (acfg, acfg->plt_got_info_offsets [index]);
802 emit_alignment (acfg, AOT_FUNC_ALIGNMENT);
803 #endif /*__native_client_codegen__*/
804 #elif defined(TARGET_AMD64)
805 #if defined(__default_codegen__)
807 * We can't emit jumps because they are 32 bits only so they can't be patched.
808 * So we make indirect calls through GOT entries which are patched by the AOT
809 * loader to point to .Lpd entries.
811 /* jmpq *<offset>(%rip) */
812 emit_byte (acfg, '\xff');
813 emit_byte (acfg, '\x25');
814 emit_symbol_diff (acfg, acfg->got_symbol, ".", ((acfg->plt_got_offset_base + index) * sizeof (gpointer)) -4);
815 /* Used by mono_aot_get_plt_info_offset */
816 emit_int32 (acfg, acfg->plt_got_info_offsets [index]);
817 #elif defined(__native_client_codegen__)
819 guint8 *buf_aligned = ALIGN_TO(buf, kNaClAlignment);
820 guint8 *code = buf_aligned;
822 /* mov <OFFSET>(%rip), %r11d */
823 emit_byte (acfg, '\x45');
824 emit_byte (acfg, '\x8b');
825 emit_byte (acfg, '\x1d');
826 emit_symbol_diff (acfg, acfg->got_symbol, ".", ((acfg->plt_got_offset_base + index) * sizeof (gpointer)) -4);
828 amd64_jump_reg (code, AMD64_R11);
829 /* This should be constant for the plt patch */
830 g_assert ((size_t)(code-buf_aligned) == 10);
831 emit_bytes (acfg, buf_aligned, code - buf_aligned);
833 /* Hide data in a push imm32 so it passes validation */
834 emit_byte (acfg, 0x68); /* push */
835 emit_int32 (acfg, acfg->plt_got_info_offsets [index]);
836 emit_alignment (acfg, AOT_FUNC_ALIGNMENT);
837 #endif /*__native_client_codegen__*/
838 #elif defined(TARGET_ARM)
843 ARM_LDR_IMM (code, ARMREG_IP, ARMREG_PC, 0);
844 ARM_LDR_REG_REG (code, ARMREG_PC, ARMREG_PC, ARMREG_IP);
845 emit_bytes (acfg, buf, code - buf);
846 emit_symbol_diff (acfg, acfg->got_symbol, ".", ((acfg->plt_got_offset_base + index) * sizeof (gpointer)) - 4);
847 /* Used by mono_aot_get_plt_info_offset */
848 emit_int32 (acfg, acfg->plt_got_info_offsets [index]);
849 #elif defined(TARGET_POWERPC)
850 guint32 offset = (acfg->plt_got_offset_base + index) * sizeof (gpointer);
852 /* The GOT address is guaranteed to be in r30 by OP_LOAD_GOTADDR */
853 g_assert (!acfg->use_bin_writer);
854 img_writer_emit_unset_mode (acfg->w);
855 fprintf (acfg->fp, "lis 11, %d@h\n", offset);
856 fprintf (acfg->fp, "ori 11, 11, %d@l\n", offset);
857 fprintf (acfg->fp, "add 11, 11, 30\n");
858 fprintf (acfg->fp, "%s 11, 0(11)\n", PPC_LD_OP);
859 #ifdef PPC_USES_FUNCTION_DESCRIPTOR
860 fprintf (acfg->fp, "%s 2, %d(11)\n", PPC_LD_OP, (int)sizeof (gpointer));
861 fprintf (acfg->fp, "%s 11, 0(11)\n", PPC_LD_OP);
863 fprintf (acfg->fp, "mtctr 11\n");
864 fprintf (acfg->fp, "bctr\n");
865 emit_int32 (acfg, acfg->plt_got_info_offsets [index]);
867 g_assert_not_reached ();
872 arch_emit_llvm_plt_entry (MonoAotCompile *acfg, int index)
874 #if defined(TARGET_ARM)
876 /* LLVM calls the PLT entries using bl, so emit a stub */
877 /* FIXME: Too much overhead on every call */
878 fprintf (acfg->fp, ".thumb_func\n");
879 fprintf (acfg->fp, "bx pc\n");
880 fprintf (acfg->fp, "nop\n");
881 fprintf (acfg->fp, ".arm\n");
883 /* LLVM calls the PLT entries using bl, so these have to be thumb2 */
884 /* The caller already transitioned to thumb */
885 /* The code below should be 12 bytes long */
886 fprintf (acfg->fp, "ldr ip, [pc, #8]\n");
887 /* thumb can't encode ld pc, [pc, ip] */
888 fprintf (acfg->fp, "add ip, pc, ip\n");
889 fprintf (acfg->fp, "ldr ip, [ip, #0]\n");
890 fprintf (acfg->fp, "bx ip\n");
891 emit_symbol_diff (acfg, acfg->got_symbol, ".", ((acfg->plt_got_offset_base + index) * sizeof (gpointer)) + 4);
892 emit_int32 (acfg, acfg->plt_got_info_offsets [index]);
894 g_assert_not_reached ();
899 * arch_emit_specific_trampoline:
901 * Emit code for a specific trampoline. OFFSET is the offset of the first of
902 * two GOT slots which contain the generic trampoline address and the trampoline
903 * argument. TRAMP_SIZE is set to the size of the emitted trampoline.
906 arch_emit_specific_trampoline (MonoAotCompile *acfg, int offset, int *tramp_size)
909 * The trampolines created here are variations of the specific
910 * trampolines created in mono_arch_create_specific_trampoline (). The
912 * - the generic trampoline address is taken from a got slot.
913 * - the offset of the got slot where the trampoline argument is stored
914 * is embedded in the instruction stream, and the generic trampoline
915 * can load the argument by loading the offset, adding it to the
916 * address of the trampoline to get the address of the got slot, and
917 * loading the argument from there.
918 * - all the trampolines should be of the same length.
920 #if defined(TARGET_AMD64)
921 #if defined(__default_codegen__)
922 /* This should be exactly 16 bytes long */
924 /* call *<offset>(%rip) */
925 emit_byte (acfg, '\x41');
926 emit_byte (acfg, '\xff');
927 emit_byte (acfg, '\x15');
928 emit_symbol_diff (acfg, acfg->got_symbol, ".", (offset * sizeof (gpointer)) - 4);
929 /* This should be relative to the start of the trampoline */
930 emit_symbol_diff (acfg, acfg->got_symbol, ".", ((offset+1) * sizeof (gpointer)) + 7);
931 emit_zero_bytes (acfg, 5);
932 #elif defined(__native_client_codegen__)
934 guint8 *buf_aligned = ALIGN_TO(buf, kNaClAlignment);
935 guint8 *code = buf_aligned;
940 /* Emit this call in 'code' so we can find out how long it is. */
941 amd64_call_reg (code, AMD64_R11);
942 call_start = mono_arch_nacl_skip_nops (buf_aligned);
943 call_len = code - call_start;
945 /* The tramp_size is twice the NaCl alignment because it starts with */
946 /* a call which needs to be aligned to the end of the boundary. */
947 *tramp_size = kNaClAlignment*2;
949 /* Emit nops to align call site below which is 7 bytes plus */
950 /* the length of the call sequence emitted above. */
951 /* Note: this requires the specific trampoline starts on a */
952 /* kNaclAlignedment aligned address, which it does because */
953 /* it's its own function that is aligned. */
955 guint8 *nopbuf_aligned = ALIGN_TO (nop_buf, kNaClAlignment);
956 guint8 *nopbuf_end = mono_arch_nacl_pad (nopbuf_aligned, kNaClAlignment - 7 - (call_len));
957 emit_bytes (acfg, nopbuf_aligned, nopbuf_end - nopbuf_aligned);
959 /* The trampoline is stored at the offset'th pointer, the -4 is */
960 /* present because RIP relative addressing starts at the end of */
961 /* the current instruction, while the label "." is relative to */
962 /* the beginning of the current asm location, which in this case */
963 /* is not the mov instruction, but the offset itself, due to the */
964 /* way the bytes and ints are emitted here. */
965 got_offset = (offset * sizeof(gpointer)) - 4;
967 /* mov <OFFSET>(%rip), %r11d */
968 emit_byte (acfg, '\x45');
969 emit_byte (acfg, '\x8b');
970 emit_byte (acfg, '\x1d');
971 emit_symbol_diff (acfg, acfg->got_symbol, ".", got_offset);
974 emit_bytes (acfg, call_start, call_len);
976 /* The arg is stored at the offset+1 pointer, relative to beginning */
977 /* of trampoline: 7 for mov, plus the call length, and 1 for push. */
978 got_offset = ((offset + 1) * sizeof(gpointer)) + 7 + call_len + 1;
980 /* We can't emit this data directly, hide in a "push imm32" */
981 emit_byte (acfg, '\x68'); /* push */
982 emit_symbol_diff (acfg, acfg->got_symbol, ".", got_offset);
983 emit_alignment (acfg, kNaClAlignment);
984 #endif /*__native_client_codegen__*/
985 #elif defined(TARGET_ARM)
989 /* This should be exactly 20 bytes long */
992 ARM_PUSH (code, 0x5fff);
993 ARM_LDR_IMM (code, ARMREG_R1, ARMREG_PC, 4);
994 /* Load the value from the GOT */
995 ARM_LDR_REG_REG (code, ARMREG_R1, ARMREG_PC, ARMREG_R1);
997 ARM_BLX_REG (code, ARMREG_R1);
999 g_assert (code - buf == 16);
1002 emit_bytes (acfg, buf, code - buf);
1004 * Only one offset is needed, since the second one would be equal to the
1007 emit_symbol_diff (acfg, acfg->got_symbol, ".", (offset * sizeof (gpointer)) - 4 + 4);
1008 //emit_symbol_diff (acfg, acfg->got_symbol, ".", ((offset + 1) * sizeof (gpointer)) - 4 + 8);
1009 #elif defined(TARGET_POWERPC)
1016 g_assert (!acfg->use_bin_writer);
1019 * PPC has no ip relative addressing, so we need to compute the address
1020 * of the mscorlib got. That is slow and complex, so instead, we store it
1021 * in the second got slot of every aot image. The caller already computed
1022 * the address of its got and placed it into r30.
1024 img_writer_emit_unset_mode (acfg->w);
1025 /* Load mscorlib got address */
1026 fprintf (acfg->fp, "%s 0, %d(30)\n", PPC_LD_OP, (int)sizeof (gpointer));
1027 /* Load generic trampoline address */
1028 fprintf (acfg->fp, "lis 11, %d@h\n", (int)(offset * sizeof (gpointer)));
1029 fprintf (acfg->fp, "ori 11, 11, %d@l\n", (int)(offset * sizeof (gpointer)));
1030 fprintf (acfg->fp, "%s 11, 11, 0\n", PPC_LDX_OP);
1031 #ifdef PPC_USES_FUNCTION_DESCRIPTOR
1032 fprintf (acfg->fp, "%s 11, 0(11)\n", PPC_LD_OP);
1034 fprintf (acfg->fp, "mtctr 11\n");
1035 /* Load trampoline argument */
1036 /* On ppc, we pass it normally to the generic trampoline */
1037 fprintf (acfg->fp, "lis 11, %d@h\n", (int)((offset + 1) * sizeof (gpointer)));
1038 fprintf (acfg->fp, "ori 11, 11, %d@l\n", (int)((offset + 1) * sizeof (gpointer)));
1039 fprintf (acfg->fp, "%s 0, 11, 0\n", PPC_LDX_OP);
1040 /* Branch to generic trampoline */
1041 fprintf (acfg->fp, "bctr\n");
1043 #ifdef PPC_USES_FUNCTION_DESCRIPTOR
1044 *tramp_size = 10 * 4;
1046 *tramp_size = 9 * 4;
1048 #elif defined(TARGET_X86)
1052 /* Similar to the PPC code above */
1054 /* FIXME: Could this clobber the register needed by get_vcall_slot () ? */
1056 /* We clobber ECX, since EAX is used as MONO_ARCH_MONITOR_OBJECT_REG */
1057 #ifdef MONO_ARCH_MONITOR_OBJECT_REG
1058 g_assert (MONO_ARCH_MONITOR_OBJECT_REG != X86_ECX);
1062 /* Load mscorlib got address */
1063 x86_mov_reg_membase (code, X86_ECX, MONO_ARCH_GOT_REG, sizeof (gpointer), 4);
1064 /* Push trampoline argument */
1065 x86_push_membase (code, X86_ECX, (offset + 1) * sizeof (gpointer));
1066 /* Load generic trampoline address */
1067 x86_mov_reg_membase (code, X86_ECX, X86_ECX, offset * sizeof (gpointer), 4);
1068 /* Branch to generic trampoline */
1069 x86_jump_reg (code, X86_ECX);
1071 #ifdef __native_client_codegen__
1073 /* emit nops to next 32 byte alignment */
1074 int a = (~kNaClAlignmentMask) & ((code - buf) + kNaClAlignment - 1);
1075 while (code < (buf + a)) x86_nop(code);
1078 emit_bytes (acfg, buf, code - buf);
1080 *tramp_size = NACL_SIZE(17, kNaClAlignment);
1081 g_assert (code - buf == *tramp_size);
1083 g_assert_not_reached ();
1088 * arch_emit_unbox_trampoline:
1090 * Emit code for the unbox trampoline for METHOD used in the full-aot case.
1091 * CALL_TARGET is the symbol pointing to the native code of METHOD.
1094 arch_emit_unbox_trampoline (MonoAotCompile *acfg, MonoCompile *cfg, MonoMethod *method, const char *call_target)
1096 #if defined(TARGET_AMD64)
1101 this_reg = mono_arch_get_this_arg_reg (NULL);
1103 amd64_alu_reg_imm (code, X86_ADD, this_reg, sizeof (MonoObject));
1105 emit_bytes (acfg, buf, code - buf);
1107 emit_byte (acfg, '\xe9');
1108 emit_symbol_diff (acfg, call_target, ".", -4);
1109 #elif defined(TARGET_X86)
1116 x86_alu_membase_imm (code, X86_ADD, X86_ESP, this_pos, sizeof (MonoObject));
1118 emit_bytes (acfg, buf, code - buf);
1121 emit_byte (acfg, '\xe9');
1122 emit_symbol_diff (acfg, call_target, ".", -4);
1123 #elif defined(TARGET_ARM)
1127 if (acfg->thumb_mixed && cfg->compile_llvm) {
1128 fprintf (acfg->fp, "add r0, r0, #%d\n", sizeof (MonoObject));
1129 fprintf (acfg->fp, "b %s\n", call_target);
1130 fprintf (acfg->fp, ".arm\n");
1136 ARM_ADD_REG_IMM8 (code, ARMREG_R0, ARMREG_R0, sizeof (MonoObject));
1138 emit_bytes (acfg, buf, code - buf);
1139 /* jump to method */
1140 if (acfg->use_bin_writer) {
1147 img_writer_emit_reloc (acfg->w, R_ARM_JUMP24, call_target, -8);
1148 emit_bytes (acfg, buf, 4);
1150 if (acfg->thumb_mixed && cfg->compile_llvm)
1151 fprintf (acfg->fp, "\n\tbx %s\n", call_target);
1153 fprintf (acfg->fp, "\n\tb %s\n", call_target);
1155 #elif defined(TARGET_POWERPC)
1158 g_assert (!acfg->use_bin_writer);
1160 fprintf (acfg->fp, "\n\taddi %d, %d, %d\n", this_pos, this_pos, (int)sizeof (MonoObject));
1161 fprintf (acfg->fp, "\n\tb %s\n", call_target);
1163 g_assert_not_reached ();
1168 * arch_emit_static_rgctx_trampoline:
1170 * Emit code for a static rgctx trampoline. OFFSET is the offset of the first of
1171 * two GOT slots which contain the rgctx argument, and the method to jump to.
1172 * TRAMP_SIZE is set to the size of the emitted trampoline.
1173 * These kinds of trampolines cannot be enumerated statically, since there could
1174 * be one trampoline per method instantiation, so we emit the same code for all
1175 * trampolines, and parameterize them using two GOT slots.
1178 arch_emit_static_rgctx_trampoline (MonoAotCompile *acfg, int offset, int *tramp_size)
1180 #if defined(TARGET_AMD64)
1181 #if defined(__default_codegen__)
1182 /* This should be exactly 13 bytes long */
1185 /* mov <OFFSET>(%rip), %r10 */
1186 emit_byte (acfg, '\x4d');
1187 emit_byte (acfg, '\x8b');
1188 emit_byte (acfg, '\x15');
1189 emit_symbol_diff (acfg, acfg->got_symbol, ".", (offset * sizeof (gpointer)) - 4);
1191 /* jmp *<offset>(%rip) */
1192 emit_byte (acfg, '\xff');
1193 emit_byte (acfg, '\x25');
1194 emit_symbol_diff (acfg, acfg->got_symbol, ".", ((offset + 1) * sizeof (gpointer)) - 4);
1195 #elif defined(__native_client_codegen__)
1197 guint8 *buf_aligned = ALIGN_TO(buf, kNaClAlignment);
1198 guint8 *code = buf_aligned;
1200 /* mov <OFFSET>(%rip), %r10d */
1201 emit_byte (acfg, '\x45');
1202 emit_byte (acfg, '\x8b');
1203 emit_byte (acfg, '\x15');
1204 emit_symbol_diff (acfg, acfg->got_symbol, ".", (offset * sizeof (gpointer)) - 4);
1206 /* mov <OFFSET>(%rip), %r11d */
1207 emit_byte (acfg, '\x45');
1208 emit_byte (acfg, '\x8b');
1209 emit_byte (acfg, '\x1d');
1210 emit_symbol_diff (acfg, acfg->got_symbol, ".", ((offset + 1) * sizeof (gpointer)) - 4);
1213 amd64_jump_reg (code, AMD64_R11);
1214 emit_bytes (acfg, buf_aligned, code - buf_aligned);
1216 emit_alignment (acfg, kNaClAlignment);
1217 *tramp_size = kNaClAlignment;
1218 #endif /*__native_client_codegen__*/
1220 #elif defined(TARGET_ARM)
1224 /* This should be exactly 24 bytes long */
1227 /* Load rgctx value */
1228 ARM_LDR_IMM (code, ARMREG_IP, ARMREG_PC, 8);
1229 ARM_LDR_REG_REG (code, MONO_ARCH_RGCTX_REG, ARMREG_PC, ARMREG_IP);
1230 /* Load branch addr + branch */
1231 ARM_LDR_IMM (code, ARMREG_IP, ARMREG_PC, 4);
1232 ARM_LDR_REG_REG (code, ARMREG_PC, ARMREG_PC, ARMREG_IP);
1234 g_assert (code - buf == 16);
1237 emit_bytes (acfg, buf, code - buf);
1238 emit_symbol_diff (acfg, acfg->got_symbol, ".", (offset * sizeof (gpointer)) - 4 + 8);
1239 emit_symbol_diff (acfg, acfg->got_symbol, ".", ((offset + 1) * sizeof (gpointer)) - 4 + 4);
1240 #elif defined(TARGET_POWERPC)
1247 g_assert (!acfg->use_bin_writer);
1250 * PPC has no ip relative addressing, so we need to compute the address
1251 * of the mscorlib got. That is slow and complex, so instead, we store it
1252 * in the second got slot of every aot image. The caller already computed
1253 * the address of its got and placed it into r30.
1255 img_writer_emit_unset_mode (acfg->w);
1256 /* Load mscorlib got address */
1257 fprintf (acfg->fp, "%s 0, %d(30)\n", PPC_LD_OP, (int)sizeof (gpointer));
1259 fprintf (acfg->fp, "lis 11, %d@h\n", (int)(offset * sizeof (gpointer)));
1260 fprintf (acfg->fp, "ori 11, 11, %d@l\n", (int)(offset * sizeof (gpointer)));
1261 fprintf (acfg->fp, "%s %d, 11, 0\n", PPC_LDX_OP, MONO_ARCH_RGCTX_REG);
1262 /* Load target address */
1263 fprintf (acfg->fp, "lis 11, %d@h\n", (int)((offset + 1) * sizeof (gpointer)));
1264 fprintf (acfg->fp, "ori 11, 11, %d@l\n", (int)((offset + 1) * sizeof (gpointer)));
1265 fprintf (acfg->fp, "%s 11, 11, 0\n", PPC_LDX_OP);
1266 #ifdef PPC_USES_FUNCTION_DESCRIPTOR
1267 fprintf (acfg->fp, "%s 2, %d(11)\n", PPC_LD_OP, (int)sizeof (gpointer));
1268 fprintf (acfg->fp, "%s 11, 0(11)\n", PPC_LD_OP);
1270 fprintf (acfg->fp, "mtctr 11\n");
1271 /* Branch to the target address */
1272 fprintf (acfg->fp, "bctr\n");
1274 #ifdef PPC_USES_FUNCTION_DESCRIPTOR
1275 *tramp_size = 11 * 4;
1277 *tramp_size = 9 * 4;
1280 #elif defined(TARGET_X86)
1284 /* Similar to the PPC code above */
1286 g_assert (MONO_ARCH_RGCTX_REG != X86_ECX);
1289 /* Load mscorlib got address */
1290 x86_mov_reg_membase (code, X86_ECX, MONO_ARCH_GOT_REG, sizeof (gpointer), 4);
1292 x86_mov_reg_membase (code, MONO_ARCH_RGCTX_REG, X86_ECX, offset * sizeof (gpointer), 4);
1293 /* Branch to the target address */
1294 x86_jump_membase (code, X86_ECX, (offset + 1) * sizeof (gpointer));
1296 #ifdef __native_client_codegen__
1298 /* emit nops to next 32 byte alignment */
1299 int a = (~kNaClAlignmentMask) & ((code - buf) + kNaClAlignment - 1);
1300 while (code < (buf + a)) x86_nop(code);
1304 emit_bytes (acfg, buf, code - buf);
1306 *tramp_size = NACL_SIZE (15, kNaClAlignment);
1307 g_assert (code - buf == *tramp_size);
1309 g_assert_not_reached ();
1314 * arch_emit_imt_thunk:
1316 * Emit an IMT thunk usable in full-aot mode. The thunk uses 1 got slot which
1317 * points to an array of pointer pairs. The pairs of the form [key, ptr], where
1318 * key is the IMT key, and ptr holds the address of a memory location holding
1319 * the address to branch to if the IMT arg matches the key. The array is
1320 * terminated by a pair whose key is NULL, and whose ptr is the address of the
1322 * TRAMP_SIZE is set to the size of the emitted trampoline.
1325 arch_emit_imt_thunk (MonoAotCompile *acfg, int offset, int *tramp_size)
1327 #if defined(TARGET_AMD64)
1329 #if defined(__native_client_codegen__)
1334 guint8 *mov_buf_ptr = mov_buf;
1336 const int kSizeOfMove = 7;
1337 #if defined(__default_codegen__)
1338 code = buf = g_malloc (256);
1339 #elif defined(__native_client_codegen__)
1340 buf_alloc = g_malloc (256 + kNaClAlignment + kSizeOfMove);
1341 buf = ((guint)buf_alloc + kNaClAlignment) & ~kNaClAlignmentMask;
1342 /* The RIP relative move below is emitted first */
1347 /* FIXME: Optimize this, i.e. use binary search etc. */
1348 /* Maybe move the body into a separate function (slower, but much smaller) */
1350 /* MONO_ARCH_IMT_SCRATCH_REG is a free register */
1353 amd64_alu_membase_imm (code, X86_CMP, MONO_ARCH_IMT_SCRATCH_REG, 0, 0);
1355 amd64_branch8 (code, X86_CC_Z, 0, FALSE);
1358 amd64_alu_membase_reg_size (code, X86_CMP, MONO_ARCH_IMT_SCRATCH_REG, 0, MONO_ARCH_IMT_REG, sizeof (gpointer));
1360 amd64_branch8 (code, X86_CC_Z, 0, FALSE);
1363 amd64_alu_reg_imm (code, X86_ADD, MONO_ARCH_IMT_SCRATCH_REG, 2 * sizeof (gpointer));
1364 amd64_jump_code (code, labels [0]);
1367 mono_amd64_patch (labels [2], code);
1368 amd64_mov_reg_membase (code, MONO_ARCH_IMT_SCRATCH_REG, MONO_ARCH_IMT_SCRATCH_REG, sizeof (gpointer), sizeof (gpointer));
1369 amd64_jump_membase (code, MONO_ARCH_IMT_SCRATCH_REG, 0);
1373 mono_amd64_patch (labels [1], code);
1374 x86_breakpoint (code);
1376 /* mov <OFFSET>(%rip), MONO_ARCH_IMT_SCRATCH_REG */
1377 amd64_emit_rex (mov_buf_ptr, sizeof(gpointer), MONO_ARCH_IMT_SCRATCH_REG, 0, AMD64_RIP);
1378 *(mov_buf_ptr)++ = (unsigned char)0x8b; /* mov opcode */
1379 x86_address_byte (mov_buf_ptr, 0, MONO_ARCH_IMT_SCRATCH_REG & 0x7, 5);
1380 emit_bytes (acfg, mov_buf, mov_buf_ptr - mov_buf);
1381 emit_symbol_diff (acfg, acfg->got_symbol, ".", (offset * sizeof (gpointer)) - 4);
1383 emit_bytes (acfg, buf, code - buf);
1385 *tramp_size = code - buf + kSizeOfMove;
1386 #if defined(__native_client_codegen__)
1387 /* The tramp will be padded to the next kNaClAlignment bundle. */
1388 *tramp_size = ALIGN_TO ((*tramp_size), kNaClAlignment);
1391 #if defined(__default_codegen__)
1393 #elif defined(__native_client_codegen__)
1397 #elif defined(TARGET_X86)
1399 #ifdef __native_client_codegen__
1404 #if defined(__default_codegen__)
1405 code = buf = g_malloc (256);
1406 #elif defined(__native_client_codegen__)
1407 buf_alloc = g_malloc (256 + kNaClAlignment);
1408 code = buf = ((guint)buf_alloc + kNaClAlignment) & ~kNaClAlignmentMask;
1411 /* Allocate a temporary stack slot */
1412 x86_push_reg (code, X86_EAX);
1414 x86_push_reg (code, X86_EAX);
1416 /* Load mscorlib got address */
1417 x86_mov_reg_membase (code, X86_EAX, MONO_ARCH_GOT_REG, sizeof (gpointer), 4);
1419 x86_mov_reg_membase (code, X86_EAX, X86_EAX, offset * sizeof (gpointer), 4);
1422 x86_alu_membase_imm (code, X86_CMP, X86_EAX, 0, 0);
1424 x86_branch8 (code, X86_CC_Z, FALSE, 0);
1427 x86_alu_membase_reg (code, X86_CMP, X86_EAX, 0, MONO_ARCH_IMT_REG);
1429 x86_branch8 (code, X86_CC_Z, FALSE, 0);
1432 x86_alu_reg_imm (code, X86_ADD, X86_EAX, 2 * sizeof (gpointer));
1433 x86_jump_code (code, labels [0]);
1436 mono_x86_patch (labels [2], code);
1437 x86_mov_reg_membase (code, X86_EAX, X86_EAX, sizeof (gpointer), 4);
1438 x86_mov_reg_membase (code, X86_EAX, X86_EAX, 0, 4);
1439 /* Save the target address to the temporary stack location */
1440 x86_mov_membase_reg (code, X86_ESP, 4, X86_EAX, 4);
1442 x86_pop_reg (code, X86_EAX);
1443 /* Jump to the target address */
1448 mono_x86_patch (labels [1], code);
1449 x86_breakpoint (code);
1451 #ifdef __native_client_codegen__
1453 /* emit nops to next 32 byte alignment */
1454 int a = (~kNaClAlignmentMask) & ((code - buf) + kNaClAlignment - 1);
1455 while (code < (buf + a)) x86_nop(code);
1458 emit_bytes (acfg, buf, code - buf);
1460 *tramp_size = code - buf;
1462 #if defined(__default_codegen__)
1464 #elif defined(__native_client_codegen__)
1468 #elif defined(TARGET_ARM)
1470 guint8 *code, *code2, *labels [16];
1474 /* The IMT method is in v5 */
1476 /* Need at least two free registers, plus a slot for storing the pc */
1477 ARM_PUSH (code, (1 << ARMREG_R0)|(1 << ARMREG_R1)|(1 << ARMREG_R2));
1479 /* Load the parameter from the GOT */
1480 ARM_LDR_IMM (code, ARMREG_R0, ARMREG_PC, 0);
1481 ARM_LDR_REG_REG (code, ARMREG_R0, ARMREG_PC, ARMREG_R0);
1484 ARM_LDR_IMM (code, ARMREG_R1, ARMREG_R0, 0);
1485 ARM_CMP_REG_REG (code, ARMREG_R1, ARMREG_V5);
1487 ARM_B_COND (code, ARMCOND_EQ, 0);
1489 /* End-of-loop check */
1490 ARM_CMP_REG_IMM (code, ARMREG_R1, 0, 0);
1492 ARM_B_COND (code, ARMCOND_EQ, 0);
1495 ARM_ADD_REG_IMM8 (code, ARMREG_R0, ARMREG_R0, sizeof (gpointer) * 2);
1498 arm_patch (labels [4], labels [1]);
1501 arm_patch (labels [2], code);
1502 ARM_LDR_IMM (code, ARMREG_R0, ARMREG_R0, 4);
1503 ARM_LDR_IMM (code, ARMREG_R0, ARMREG_R0, 0);
1504 /* Save it to the third stack slot */
1505 ARM_STR_IMM (code, ARMREG_R0, ARMREG_SP, 8);
1506 /* Restore the registers and branch */
1507 ARM_POP (code, (1 << ARMREG_R0)|(1 << ARMREG_R1)|(1 << ARMREG_PC));
1510 arm_patch (labels [3], code);
1511 ARM_LDR_IMM (code, ARMREG_R0, ARMREG_R0, 4);
1512 ARM_STR_IMM (code, ARMREG_R0, ARMREG_SP, 8);
1513 ARM_POP (code, (1 << ARMREG_R0)|(1 << ARMREG_R1)|(1 << ARMREG_PC));
1517 ARM_LDR_IMM (code2, ARMREG_R0, ARMREG_PC, (code - (labels [0] + 8)));
1519 emit_bytes (acfg, buf, code - buf);
1520 emit_symbol_diff (acfg, acfg->got_symbol, ".", (offset * sizeof (gpointer)) + (code - (labels [0] + 8)) - 4);
1522 *tramp_size = code - buf + 4;
1523 #elif defined(TARGET_POWERPC)
1525 guint8 *code, *labels [16];
1529 /* Load the mscorlib got address */
1530 ppc_ldptr (code, ppc_r11, sizeof (gpointer), ppc_r30);
1531 /* Load the parameter from the GOT */
1532 ppc_load (code, ppc_r0, offset * sizeof (gpointer));
1533 ppc_ldptr_indexed (code, ppc_r11, ppc_r11, ppc_r0);
1535 /* Load and check key */
1537 ppc_ldptr (code, ppc_r0, 0, ppc_r11);
1538 ppc_cmp (code, 0, sizeof (gpointer) == 8 ? 1 : 0, ppc_r0, MONO_ARCH_IMT_REG);
1540 ppc_bc (code, PPC_BR_TRUE, PPC_BR_EQ, 0);
1542 /* End-of-loop check */
1543 ppc_cmpi (code, 0, sizeof (gpointer) == 8 ? 1 : 0, ppc_r0, 0);
1545 ppc_bc (code, PPC_BR_TRUE, PPC_BR_EQ, 0);
1548 ppc_addi (code, ppc_r11, ppc_r11, 2 * sizeof (gpointer));
1551 mono_ppc_patch (labels [4], labels [1]);
1554 mono_ppc_patch (labels [2], code);
1555 ppc_ldptr (code, ppc_r11, sizeof (gpointer), ppc_r11);
1556 /* r11 now contains the value of the vtable slot */
1557 /* this is not a function descriptor on ppc64 */
1558 ppc_ldptr (code, ppc_r11, 0, ppc_r11);
1559 ppc_mtctr (code, ppc_r11);
1560 ppc_bcctr (code, PPC_BR_ALWAYS, 0);
1563 mono_ppc_patch (labels [3], code);
1567 *tramp_size = code - buf;
1569 emit_bytes (acfg, buf, code - buf);
1571 g_assert_not_reached ();
1576 arch_emit_autoreg (MonoAotCompile *acfg, char *symbol)
1578 #if defined(TARGET_POWERPC) && defined(__mono_ilp32__)
1579 /* Based on code generated by gcc */
1580 img_writer_emit_unset_mode (acfg->w);
1583 #if defined(_MSC_VER) || defined(MONO_CROSS_COMPILE)
1584 ".section .ctors,\"aw\",@progbits\n"
1588 ".section .opd,\"aw\"\n"
1591 ".long .%s,.TOC.@tocbase32\n"
1594 ".type .%s,@function\n"
1596 ".%s:\n", symbol, symbol, symbol, symbol, symbol, symbol, symbol, symbol);
1598 ".section .ctors,\"aw\",@progbits\n"
1602 ".section .opd,\"aw\"\n"
1605 ".long .%1$s,.TOC.@tocbase32\n"
1606 ".size %1$s,.-%1$s\n"
1608 ".type .%1$s,@function\n"
1610 ".%1$s:\n", symbol);
1621 "lis 3, .Lglobals@h\n"
1622 "ori 3, 3, .Lglobals@l\n"
1623 "bl .mono_aot_register_module\n"
1631 #if defined(_MSC_VER) || defined(MONO_CROSS_COMPILE)
1633 ".size .%s,.-.%s\n", symbol, symbol);
1636 ".size .%1$s,.-.%1$s\n", symbol);
1642 /* END OF ARCH SPECIFIC CODE */
1645 mono_get_field_token (MonoClassField *field)
1647 MonoClass *klass = field->parent;
1650 for (i = 0; i < klass->field.count; ++i) {
1651 if (field == &klass->fields [i])
1652 return MONO_TOKEN_FIELD_DEF | (klass->field.first + 1 + i);
1655 g_assert_not_reached ();
1660 encode_value (gint32 value, guint8 *buf, guint8 **endbuf)
1664 //printf ("ENCODE: %d 0x%x.\n", value, value);
1667 * Same encoding as the one used in the metadata, extended to handle values
1668 * greater than 0x1fffffff.
1670 if ((value >= 0) && (value <= 127))
1672 else if ((value >= 0) && (value <= 16383)) {
1673 p [0] = 0x80 | (value >> 8);
1674 p [1] = value & 0xff;
1676 } else if ((value >= 0) && (value <= 0x1fffffff)) {
1677 p [0] = (value >> 24) | 0xc0;
1678 p [1] = (value >> 16) & 0xff;
1679 p [2] = (value >> 8) & 0xff;
1680 p [3] = value & 0xff;
1685 p [1] = (value >> 24) & 0xff;
1686 p [2] = (value >> 16) & 0xff;
1687 p [3] = (value >> 8) & 0xff;
1688 p [4] = value & 0xff;
1696 stream_init (MonoDynamicStream *sh)
1699 sh->alloc_size = 4096;
1700 sh->data = g_malloc (4096);
1702 /* So offsets are > 0 */
1708 make_room_in_stream (MonoDynamicStream *stream, int size)
1710 if (size <= stream->alloc_size)
1713 while (stream->alloc_size <= size) {
1714 if (stream->alloc_size < 4096)
1715 stream->alloc_size = 4096;
1717 stream->alloc_size *= 2;
1720 stream->data = g_realloc (stream->data, stream->alloc_size);
1724 add_stream_data (MonoDynamicStream *stream, const char *data, guint32 len)
1728 make_room_in_stream (stream, stream->index + len);
1729 memcpy (stream->data + stream->index, data, len);
1730 idx = stream->index;
1731 stream->index += len;
1738 * Add data to the binary blob inside the aot image. Returns the offset inside the
1739 * blob where the data was stored.
1742 add_to_blob (MonoAotCompile *acfg, const guint8 *data, guint32 data_len)
1744 if (acfg->blob.alloc_size == 0)
1745 stream_init (&acfg->blob);
1747 return add_stream_data (&acfg->blob, (char*)data, data_len);
1751 add_to_blob_aligned (MonoAotCompile *acfg, const guint8 *data, guint32 data_len, guint32 align)
1756 if (acfg->blob.alloc_size == 0)
1757 stream_init (&acfg->blob);
1759 count = acfg->blob.index % align;
1761 /* we assume the stream data will be aligned */
1763 add_stream_data (&acfg->blob, buf, 4 - count);
1765 return add_stream_data (&acfg->blob, (char*)data, data_len);
1769 * emit_offset_table:
1771 * Emit a table of increasing offsets in a compact form using differential encoding.
1772 * There is an index entry for each GROUP_SIZE number of entries. The greater the
1773 * group size, the more compact the table becomes, but the slower it becomes to compute
1774 * a given entry. Returns the size of the table.
1777 emit_offset_table (MonoAotCompile *acfg, int noffsets, int group_size, gint32 *offsets)
1779 gint32 current_offset;
1780 int i, buf_size, ngroups, index_entry_size;
1782 guint32 *index_offsets;
1784 ngroups = (noffsets + (group_size - 1)) / group_size;
1786 index_offsets = g_new0 (guint32, ngroups);
1788 buf_size = noffsets * 4;
1789 p = buf = g_malloc0 (buf_size);
1792 for (i = 0; i < noffsets; ++i) {
1793 //printf ("D: %d -> %d\n", i, offsets [i]);
1794 if ((i % group_size) == 0) {
1795 index_offsets [i / group_size] = p - buf;
1796 /* Emit the full value for these entries */
1797 encode_value (offsets [i], p, &p);
1799 /* The offsets are allowed to be non-increasing */
1800 //g_assert (offsets [i] >= current_offset);
1801 encode_value (offsets [i] - current_offset, p, &p);
1803 current_offset = offsets [i];
1806 if (ngroups && index_offsets [ngroups - 1] < 65000)
1807 index_entry_size = 2;
1809 index_entry_size = 4;
1811 /* Emit the header */
1812 emit_int32 (acfg, noffsets);
1813 emit_int32 (acfg, group_size);
1814 emit_int32 (acfg, ngroups);
1815 emit_int32 (acfg, index_entry_size);
1817 /* Emit the index */
1818 for (i = 0; i < ngroups; ++i) {
1819 if (index_entry_size == 2)
1820 emit_int16 (acfg, index_offsets [i]);
1822 emit_int32 (acfg, index_offsets [i]);
1826 emit_bytes (acfg, buf, p - buf);
1828 return (int)(p - buf) + (ngroups * 4);
1832 get_image_index (MonoAotCompile *cfg, MonoImage *image)
1836 index = GPOINTER_TO_UINT (g_hash_table_lookup (cfg->image_hash, image));
1840 index = g_hash_table_size (cfg->image_hash);
1841 g_hash_table_insert (cfg->image_hash, image, GUINT_TO_POINTER (index + 1));
1842 g_ptr_array_add (cfg->image_table, image);
1848 find_typespec_for_class (MonoAotCompile *acfg, MonoClass *klass)
1851 int len = acfg->image->tables [MONO_TABLE_TYPESPEC].rows;
1853 /* FIXME: Search referenced images as well */
1854 if (!acfg->typespec_classes) {
1855 acfg->typespec_classes = mono_mempool_alloc0 (acfg->mempool, sizeof (MonoClass*) * len);
1856 for (i = 0; i < len; ++i) {
1857 acfg->typespec_classes [i] = mono_class_get_full (acfg->image, MONO_TOKEN_TYPE_SPEC | (i + 1), NULL);
1860 for (i = 0; i < len; ++i) {
1861 if (acfg->typespec_classes [i] == klass)
1866 return MONO_TOKEN_TYPE_SPEC | (i + 1);
1872 encode_method_ref (MonoAotCompile *acfg, MonoMethod *method, guint8 *buf, guint8 **endbuf);
1875 encode_klass_ref (MonoAotCompile *acfg, MonoClass *klass, guint8 *buf, guint8 **endbuf);
1878 encode_ginst (MonoAotCompile *acfg, MonoGenericInst *inst, guint8 *buf, guint8 **endbuf);
1881 encode_type (MonoAotCompile *acfg, MonoType *t, guint8 *buf, guint8 **endbuf);
1884 encode_klass_ref_inner (MonoAotCompile *acfg, MonoClass *klass, guint8 *buf, guint8 **endbuf)
1889 * The encoding begins with one of the MONO_AOT_TYPEREF values, followed by additional
1893 if (klass->generic_class) {
1895 g_assert (klass->type_token);
1897 /* Find a typespec for a class if possible */
1898 token = find_typespec_for_class (acfg, klass);
1900 encode_value (MONO_AOT_TYPEREF_TYPESPEC_TOKEN, p, &p);
1901 encode_value (token, p, &p);
1903 MonoClass *gclass = klass->generic_class->container_class;
1904 MonoGenericInst *inst = klass->generic_class->context.class_inst;
1905 static int count = 0;
1908 encode_value (MONO_AOT_TYPEREF_GINST, p, &p);
1909 encode_klass_ref (acfg, gclass, p, &p);
1910 encode_ginst (acfg, inst, p, &p);
1914 } else if (klass->type_token) {
1915 int iindex = get_image_index (acfg, klass->image);
1917 g_assert (mono_metadata_token_code (klass->type_token) == MONO_TOKEN_TYPE_DEF);
1919 encode_value (MONO_AOT_TYPEREF_TYPEDEF_INDEX, p, &p);
1920 encode_value (klass->type_token - MONO_TOKEN_TYPE_DEF, p, &p);
1922 encode_value (MONO_AOT_TYPEREF_TYPEDEF_INDEX_IMAGE, p, &p);
1923 encode_value (klass->type_token - MONO_TOKEN_TYPE_DEF, p, &p);
1924 encode_value (get_image_index (acfg, klass->image), p, &p);
1926 } else if ((klass->byval_arg.type == MONO_TYPE_VAR) || (klass->byval_arg.type == MONO_TYPE_MVAR)) {
1927 MonoGenericContainer *container = mono_type_get_generic_param_owner (&klass->byval_arg);
1928 g_assert (container);
1930 encode_value (MONO_AOT_TYPEREF_VAR, p, &p);
1931 encode_value (klass->byval_arg.type, p, &p);
1932 encode_value (mono_type_get_generic_param_num (&klass->byval_arg), p, &p);
1934 encode_value (container->is_method, p, &p);
1935 if (container->is_method)
1936 encode_method_ref (acfg, container->owner.method, p, &p);
1938 encode_klass_ref (acfg, container->owner.klass, p, &p);
1939 } else if (klass->byval_arg.type == MONO_TYPE_PTR) {
1940 encode_value (MONO_AOT_TYPEREF_PTR, p, &p);
1941 encode_type (acfg, &klass->byval_arg, p, &p);
1944 g_assert (klass->rank > 0);
1945 encode_value (MONO_AOT_TYPEREF_ARRAY, p, &p);
1946 encode_value (klass->rank, p, &p);
1947 encode_klass_ref (acfg, klass->element_class, p, &p);
1955 * Encode a reference to KLASS. We use our home-grown encoding instead of the
1956 * standard metadata encoding.
1959 encode_klass_ref (MonoAotCompile *acfg, MonoClass *klass, guint8 *buf, guint8 **endbuf)
1961 gboolean shared = FALSE;
1964 * The encoding of generic instances is large so emit them only once.
1966 if (klass->generic_class) {
1968 g_assert (klass->type_token);
1970 /* Find a typespec for a class if possible */
1971 token = find_typespec_for_class (acfg, klass);
1974 } else if ((klass->byval_arg.type == MONO_TYPE_VAR) || (klass->byval_arg.type == MONO_TYPE_MVAR)) {
1979 guint offset = GPOINTER_TO_UINT (g_hash_table_lookup (acfg->klass_blob_hash, klass));
1983 buf2 = g_malloc (1024);
1986 encode_klass_ref_inner (acfg, klass, p, &p);
1987 g_assert (p - buf2 < 1024);
1989 offset = add_to_blob (acfg, buf2, p - buf2);
1992 g_hash_table_insert (acfg->klass_blob_hash, klass, GUINT_TO_POINTER (offset + 1));
1998 encode_value (MONO_AOT_TYPEREF_BLOB_INDEX, p, &p);
1999 encode_value (offset, p, &p);
2004 encode_klass_ref_inner (acfg, klass, buf, endbuf);
2008 encode_field_info (MonoAotCompile *cfg, MonoClassField *field, guint8 *buf, guint8 **endbuf)
2010 guint32 token = mono_get_field_token (field);
2013 encode_klass_ref (cfg, field->parent, p, &p);
2014 g_assert (mono_metadata_token_code (token) == MONO_TOKEN_FIELD_DEF);
2015 encode_value (token - MONO_TOKEN_FIELD_DEF, p, &p);
2020 encode_ginst (MonoAotCompile *acfg, MonoGenericInst *inst, guint8 *buf, guint8 **endbuf)
2025 encode_value (inst->type_argc, p, &p);
2026 for (i = 0; i < inst->type_argc; ++i)
2027 encode_klass_ref (acfg, mono_class_from_mono_type (inst->type_argv [i]), p, &p);
2032 encode_generic_context (MonoAotCompile *acfg, MonoGenericContext *context, guint8 *buf, guint8 **endbuf)
2035 MonoGenericInst *inst;
2037 inst = context->class_inst;
2039 g_assert (inst->type_argc);
2040 encode_ginst (acfg, inst, p, &p);
2042 encode_value (0, p, &p);
2044 inst = context->method_inst;
2046 g_assert (inst->type_argc);
2047 encode_ginst (acfg, inst, p, &p);
2049 encode_value (0, p, &p);
2055 encode_type (MonoAotCompile *acfg, MonoType *t, guint8 *buf, guint8 **endbuf)
2059 g_assert (t->num_mods == 0);
2060 /* t->attrs can be ignored */
2061 //g_assert (t->attrs == 0);
2064 *p = MONO_TYPE_PINNED;
2068 *p = MONO_TYPE_BYREF;
2076 case MONO_TYPE_VOID:
2077 case MONO_TYPE_BOOLEAN:
2078 case MONO_TYPE_CHAR:
2091 case MONO_TYPE_STRING:
2092 case MONO_TYPE_OBJECT:
2093 case MONO_TYPE_TYPEDBYREF:
2095 case MONO_TYPE_VALUETYPE:
2096 case MONO_TYPE_CLASS:
2097 encode_klass_ref (acfg, mono_class_from_mono_type (t), p, &p);
2099 case MONO_TYPE_SZARRAY:
2100 encode_klass_ref (acfg, t->data.klass, p, &p);
2103 encode_type (acfg, t->data.type, p, &p);
2105 case MONO_TYPE_GENERICINST: {
2106 MonoClass *gclass = t->data.generic_class->container_class;
2107 MonoGenericInst *inst = t->data.generic_class->context.class_inst;
2109 encode_klass_ref (acfg, gclass, p, &p);
2110 encode_ginst (acfg, inst, p, &p);
2113 case MONO_TYPE_ARRAY: {
2114 MonoArrayType *array = t->data.array;
2117 encode_klass_ref (acfg, array->eklass, p, &p);
2118 encode_value (array->rank, p, &p);
2119 encode_value (array->numsizes, p, &p);
2120 for (i = 0; i < array->numsizes; ++i)
2121 encode_value (array->sizes [i], p, &p);
2122 encode_value (array->numlobounds, p, &p);
2123 for (i = 0; i < array->numlobounds; ++i)
2124 encode_value (array->lobounds [i], p, &p);
2128 g_assert_not_reached ();
2135 encode_signature (MonoAotCompile *acfg, MonoMethodSignature *sig, guint8 *buf, guint8 **endbuf)
2141 /* Similar to the metadata encoding */
2142 if (sig->generic_param_count)
2146 if (sig->explicit_this)
2148 flags |= (sig->call_convention & 0x0F);
2152 if (sig->generic_param_count)
2153 encode_value (sig->generic_param_count, p, &p);
2154 encode_value (sig->param_count, p, &p);
2156 encode_type (acfg, sig->ret, p, &p);
2157 for (i = 0; i < sig->param_count; ++i) {
2158 if (sig->sentinelpos == i) {
2159 *p = MONO_TYPE_SENTINEL;
2162 encode_type (acfg, sig->params [i], p, &p);
2168 #define MAX_IMAGE_INDEX 250
2171 encode_method_ref (MonoAotCompile *acfg, MonoMethod *method, guint8 *buf, guint8 **endbuf)
2173 guint32 image_index = get_image_index (acfg, method->klass->image);
2174 guint32 token = method->token;
2175 MonoJumpInfoToken *ji;
2179 * The encoding for most methods is as follows:
2180 * - image index encoded as a leb128
2181 * - token index encoded as a leb128
2182 * Values of image index >= MONO_AOT_METHODREF_MIN are used to mark additional
2183 * types of method encodings.
2186 g_assert (image_index < MONO_AOT_METHODREF_MIN);
2188 /* Mark methods which can't use aot trampolines because they need the further
2189 * processing in mono_magic_trampoline () which requires a MonoMethod*.
2191 if ((method->is_generic && (method->flags & METHOD_ATTRIBUTE_VIRTUAL)) ||
2192 (method->iflags & METHOD_IMPL_ATTRIBUTE_SYNCHRONIZED))
2193 encode_value ((MONO_AOT_METHODREF_NO_AOT_TRAMPOLINE << 24), p, &p);
2195 if (method->wrapper_type) {
2196 encode_value ((MONO_AOT_METHODREF_WRAPPER << 24), p, &p);
2198 encode_value (method->wrapper_type, p, &p);
2200 switch (method->wrapper_type) {
2201 case MONO_WRAPPER_REMOTING_INVOKE:
2202 case MONO_WRAPPER_REMOTING_INVOKE_WITH_CHECK:
2203 case MONO_WRAPPER_XDOMAIN_INVOKE: {
2206 m = mono_marshal_method_from_wrapper (method);
2208 encode_method_ref (acfg, m, p, &p);
2211 case MONO_WRAPPER_PROXY_ISINST:
2212 case MONO_WRAPPER_LDFLD:
2213 case MONO_WRAPPER_LDFLDA:
2214 case MONO_WRAPPER_STFLD:
2215 case MONO_WRAPPER_ISINST: {
2216 MonoClass *proxy_class = mono_marshal_get_wrapper_info (method);
2217 encode_klass_ref (acfg, proxy_class, p, &p);
2220 case MONO_WRAPPER_LDFLD_REMOTE:
2221 case MONO_WRAPPER_STFLD_REMOTE:
2223 case MONO_WRAPPER_ALLOC: {
2224 AllocatorWrapperInfo *info = mono_marshal_get_wrapper_info (method);
2226 /* The GC name is saved once in MonoAotFileInfo */
2227 g_assert (info->alloc_type != -1);
2228 encode_value (info->alloc_type, p, &p);
2231 case MONO_WRAPPER_WRITE_BARRIER:
2233 case MONO_WRAPPER_STELEMREF: {
2234 WrapperInfo *info = mono_marshal_get_wrapper_info (method);
2237 encode_value (info->subtype, p, &p);
2238 if (info->subtype == WRAPPER_SUBTYPE_VIRTUAL_STELEMREF)
2239 encode_value (info->d.virtual_stelemref.kind, p, &p);
2242 case MONO_WRAPPER_UNKNOWN: {
2243 WrapperInfo *info = mono_marshal_get_wrapper_info (method);
2246 encode_value (info->subtype, p, &p);
2247 if (info->subtype == WRAPPER_SUBTYPE_PTR_TO_STRUCTURE ||
2248 info->subtype == WRAPPER_SUBTYPE_STRUCTURE_TO_PTR)
2249 encode_klass_ref (acfg, method->klass, p, &p);
2250 else if (info->subtype == WRAPPER_SUBTYPE_SYNCHRONIZED_INNER)
2251 encode_method_ref (acfg, info->d.synchronized_inner.method, p, &p);
2254 case MONO_WRAPPER_MANAGED_TO_NATIVE: {
2255 WrapperInfo *info = mono_marshal_get_wrapper_info (method);
2258 encode_value (info->subtype, p, &p);
2259 if (info->subtype == WRAPPER_SUBTYPE_ICALL_WRAPPER) {
2260 strcpy ((char*)p, method->name);
2261 p += strlen (method->name) + 1;
2263 g_assert (info->subtype == WRAPPER_SUBTYPE_NONE);
2264 encode_method_ref (acfg, info->d.managed_to_native.method, p, &p);
2268 case MONO_WRAPPER_SYNCHRONIZED: {
2271 m = mono_marshal_method_from_wrapper (method);
2273 g_assert (m != method);
2274 encode_method_ref (acfg, m, p, &p);
2277 case MONO_WRAPPER_MANAGED_TO_MANAGED: {
2278 WrapperInfo *info = mono_marshal_get_wrapper_info (method);
2281 encode_value (info->subtype, p, &p);
2283 if (info->subtype == WRAPPER_SUBTYPE_ELEMENT_ADDR) {
2284 encode_value (info->d.element_addr.rank, p, &p);
2285 encode_value (info->d.element_addr.elem_size, p, &p);
2286 } else if (info->subtype == WRAPPER_SUBTYPE_STRING_CTOR) {
2287 encode_method_ref (acfg, info->d.string_ctor.method, p, &p);
2289 g_assert_not_reached ();
2293 case MONO_WRAPPER_CASTCLASS: {
2294 WrapperInfo *info = mono_marshal_get_wrapper_info (method);
2297 encode_value (info->subtype, p, &p);
2300 case MONO_WRAPPER_RUNTIME_INVOKE: {
2301 WrapperInfo *info = mono_marshal_get_wrapper_info (method);
2304 encode_value (info->subtype, p, &p);
2305 if (info->subtype == WRAPPER_SUBTYPE_RUNTIME_INVOKE_DIRECT || info->subtype == WRAPPER_SUBTYPE_RUNTIME_INVOKE_VIRTUAL)
2306 encode_method_ref (acfg, info->d.runtime_invoke.method, p, &p);
2308 MonoMethodSignature *sig;
2310 encode_value (0, p, &p);
2312 sig = mono_method_signature (method);
2313 encode_signature (acfg, sig, p, &p);
2317 case MONO_WRAPPER_DELEGATE_INVOKE:
2318 case MONO_WRAPPER_DELEGATE_BEGIN_INVOKE:
2319 case MONO_WRAPPER_DELEGATE_END_INVOKE: {
2320 MonoMethodSignature *sig = mono_method_signature (method);
2321 encode_signature (acfg, sig, p, &p);
2324 case MONO_WRAPPER_NATIVE_TO_MANAGED: {
2325 WrapperInfo *info = mono_marshal_get_wrapper_info (method);
2328 encode_method_ref (acfg, info->d.native_to_managed.method, p, &p);
2329 encode_klass_ref (acfg, info->d.native_to_managed.klass, p, &p);
2333 g_assert_not_reached ();
2335 } else if (mono_method_signature (method)->is_inflated) {
2337 * This is a generic method, find the original token which referenced it and
2339 * Obtain the token from information recorded by the JIT.
2341 ji = g_hash_table_lookup (acfg->token_info_hash, method);
2343 image_index = get_image_index (acfg, ji->image);
2344 g_assert (image_index < MAX_IMAGE_INDEX);
2347 encode_value ((MONO_AOT_METHODREF_METHODSPEC << 24), p, &p);
2348 encode_value (image_index, p, &p);
2349 encode_value (token, p, &p);
2351 MonoMethod *declaring;
2352 MonoGenericContext *context = mono_method_get_context (method);
2354 g_assert (method->is_inflated);
2355 declaring = ((MonoMethodInflated*)method)->declaring;
2358 * This might be a non-generic method of a generic instance, which
2359 * doesn't have a token since the reference is generated by the JIT
2360 * like Nullable:Box/Unbox, or by generic sharing.
2363 encode_value ((MONO_AOT_METHODREF_GINST << 24), p, &p);
2364 /* Encode the klass */
2365 encode_klass_ref (acfg, method->klass, p, &p);
2366 /* Encode the method */
2367 image_index = get_image_index (acfg, method->klass->image);
2368 g_assert (image_index < MAX_IMAGE_INDEX);
2369 g_assert (declaring->token);
2370 token = declaring->token;
2371 g_assert (mono_metadata_token_table (token) == MONO_TABLE_METHOD);
2372 encode_value (image_index, p, &p);
2373 encode_value (token, p, &p);
2374 encode_generic_context (acfg, context, p, &p);
2376 } else if (token == 0) {
2377 /* This might be a method of a constructed type like int[,].Set */
2378 /* Obtain the token from information recorded by the JIT */
2379 ji = g_hash_table_lookup (acfg->token_info_hash, method);
2381 image_index = get_image_index (acfg, ji->image);
2382 g_assert (image_index < MAX_IMAGE_INDEX);
2385 encode_value ((MONO_AOT_METHODREF_METHODSPEC << 24), p, &p);
2386 encode_value (image_index, p, &p);
2387 encode_value (token, p, &p);
2390 g_assert (method->klass->rank);
2392 /* Encode directly */
2393 encode_value ((MONO_AOT_METHODREF_ARRAY << 24), p, &p);
2394 encode_klass_ref (acfg, method->klass, p, &p);
2395 if (!strcmp (method->name, ".ctor") && mono_method_signature (method)->param_count == method->klass->rank)
2396 encode_value (0, p, &p);
2397 else if (!strcmp (method->name, ".ctor") && mono_method_signature (method)->param_count == method->klass->rank * 2)
2398 encode_value (1, p, &p);
2399 else if (!strcmp (method->name, "Get"))
2400 encode_value (2, p, &p);
2401 else if (!strcmp (method->name, "Address"))
2402 encode_value (3, p, &p);
2403 else if (!strcmp (method->name, "Set"))
2404 encode_value (4, p, &p);
2406 g_assert_not_reached ();
2409 g_assert (mono_metadata_token_table (token) == MONO_TABLE_METHOD);
2410 encode_value ((image_index << 24) | mono_metadata_token_index (token), p, &p);
2416 compare_patches (gconstpointer a, gconstpointer b)
2420 i = (*(MonoJumpInfo**)a)->ip.i;
2421 j = (*(MonoJumpInfo**)b)->ip.i;
2432 static G_GNUC_UNUSED char*
2433 patch_to_string (MonoJumpInfo *patch_info)
2437 str = g_string_new ("");
2439 g_string_append_printf (str, "%s(", get_patch_name (patch_info->type));
2441 switch (patch_info->type) {
2442 case MONO_PATCH_INFO_VTABLE:
2443 mono_type_get_desc (str, &patch_info->data.klass->byval_arg, TRUE);
2448 g_string_append_printf (str, ")");
2449 return g_string_free (str, FALSE);
2455 * Return whenever PATCH_INFO refers to a direct call, and thus requires a
2458 static inline gboolean
2459 is_plt_patch (MonoJumpInfo *patch_info)
2461 switch (patch_info->type) {
2462 case MONO_PATCH_INFO_METHOD:
2463 case MONO_PATCH_INFO_INTERNAL_METHOD:
2464 case MONO_PATCH_INFO_JIT_ICALL_ADDR:
2465 case MONO_PATCH_INFO_ICALL_ADDR:
2466 case MONO_PATCH_INFO_CLASS_INIT:
2467 case MONO_PATCH_INFO_RGCTX_FETCH:
2468 case MONO_PATCH_INFO_GENERIC_CLASS_INIT:
2469 case MONO_PATCH_INFO_MONITOR_ENTER:
2470 case MONO_PATCH_INFO_MONITOR_EXIT:
2471 case MONO_PATCH_INFO_LLVM_IMT_TRAMPOLINE:
2481 * Return the symbol identifying the plt entry PLT_OFFSET.
2484 get_plt_symbol (MonoAotCompile *acfg, int plt_offset, MonoJumpInfo *patch_info)
2488 * The Apple linker reorganizes object files, so it doesn't like branches to local
2489 * labels, since those have no relocations.
2491 return g_strdup_printf ("%sp_%d", acfg->llvm_label_prefix, plt_offset);
2493 return g_strdup_printf ("%sp_%d", acfg->temp_prefix, plt_offset);
2500 * Return a PLT entry which belongs to the method identified by PATCH_INFO.
2502 static MonoPltEntry*
2503 get_plt_entry (MonoAotCompile *acfg, MonoJumpInfo *patch_info)
2507 if (!is_plt_patch (patch_info))
2510 res = g_hash_table_lookup (acfg->patch_to_plt_entry, patch_info);
2512 // FIXME: This breaks the calculation of final_got_size
2513 if (!acfg->llvm && patch_info->type == MONO_PATCH_INFO_METHOD && (patch_info->data.method->iflags & METHOD_IMPL_ATTRIBUTE_SYNCHRONIZED)) {
2515 * Allocate a separate PLT slot for each such patch, since some plt
2516 * entries will refer to the method itself, and some will refer to the
2523 MonoJumpInfo *new_ji;
2525 g_assert (!acfg->final_got_size);
2527 new_ji = mono_patch_info_dup_mp (acfg->mempool, patch_info);
2529 res = mono_mempool_alloc0 (acfg->mempool, sizeof (MonoPltEntry));
2530 res->plt_offset = acfg->plt_offset;
2532 res->symbol = get_plt_symbol (acfg, res->plt_offset, patch_info);
2533 if (acfg->aot_opts.write_symbols)
2534 res->debug_sym = get_plt_entry_debug_sym (acfg, res->ji, acfg->plt_entry_debug_sym_cache);
2536 res->llvm_symbol = g_strdup_printf ("%s_%s_llvm", res->symbol, res->debug_sym);
2538 res->llvm_symbol = g_strdup_printf ("%s_llvm", res->symbol);
2540 g_hash_table_insert (acfg->patch_to_plt_entry, new_ji, res);
2542 g_hash_table_insert (acfg->plt_offset_to_entry, GUINT_TO_POINTER (res->plt_offset), res);
2544 acfg->plt_offset ++;
2553 * Returns the offset of the GOT slot where the runtime object resulting from resolving
2554 * JI could be found if it exists, otherwise allocates a new one.
2557 get_got_offset (MonoAotCompile *acfg, MonoJumpInfo *ji)
2561 got_offset = GPOINTER_TO_UINT (g_hash_table_lookup (acfg->patch_to_got_offset_by_type [ji->type], ji));
2563 return got_offset - 1;
2565 got_offset = acfg->got_offset;
2566 acfg->got_offset ++;
2568 if (acfg->final_got_size)
2569 g_assert (got_offset < acfg->final_got_size);
2571 acfg->stats.got_slots ++;
2572 acfg->stats.got_slot_types [ji->type] ++;
2574 g_hash_table_insert (acfg->patch_to_got_offset, ji, GUINT_TO_POINTER (got_offset + 1));
2575 g_hash_table_insert (acfg->patch_to_got_offset_by_type [ji->type], ji, GUINT_TO_POINTER (got_offset + 1));
2576 g_ptr_array_add (acfg->got_patches, ji);
2581 /* Add a method to the list of methods which need to be emitted */
2583 add_method_with_index (MonoAotCompile *acfg, MonoMethod *method, int index, gboolean extra)
2586 if (!g_hash_table_lookup (acfg->method_indexes, method)) {
2587 g_ptr_array_add (acfg->methods, method);
2588 g_hash_table_insert (acfg->method_indexes, method, GUINT_TO_POINTER (index + 1));
2589 acfg->nmethods = acfg->methods->len + 1;
2592 if (method->wrapper_type || extra)
2593 g_ptr_array_add (acfg->extra_methods, method);
2597 get_method_index (MonoAotCompile *acfg, MonoMethod *method)
2599 int index = GPOINTER_TO_UINT (g_hash_table_lookup (acfg->method_indexes, method));
2607 add_method_full (MonoAotCompile *acfg, MonoMethod *method, gboolean extra, int depth)
2611 index = GPOINTER_TO_UINT (g_hash_table_lookup (acfg->method_indexes, method));
2615 index = acfg->method_index;
2616 add_method_with_index (acfg, method, index, extra);
2618 g_ptr_array_add (acfg->method_order, GUINT_TO_POINTER (index));
2620 g_hash_table_insert (acfg->method_depth, method, GUINT_TO_POINTER (depth));
2622 acfg->method_index ++;
2628 add_method (MonoAotCompile *acfg, MonoMethod *method)
2630 return add_method_full (acfg, method, FALSE, 0);
2634 add_extra_method (MonoAotCompile *acfg, MonoMethod *method)
2636 add_method_full (acfg, method, TRUE, 0);
2640 add_extra_method_with_depth (MonoAotCompile *acfg, MonoMethod *method, int depth)
2642 if (acfg->aot_opts.log_generics)
2643 printf ("%*sAdding method %s.\n", depth, "", mono_method_full_name (method, TRUE));
2645 add_method_full (acfg, method, TRUE, depth);
2649 add_jit_icall_wrapper (gpointer key, gpointer value, gpointer user_data)
2651 MonoAotCompile *acfg = user_data;
2652 MonoJitICallInfo *callinfo = value;
2653 MonoMethod *wrapper;
2659 name = g_strdup_printf ("__icall_wrapper_%s", callinfo->name);
2660 wrapper = mono_marshal_get_icall_wrapper (callinfo->sig, name, callinfo->func, check_for_pending_exc);
2663 add_method (acfg, wrapper);
2667 get_runtime_invoke_sig (MonoMethodSignature *sig)
2669 MonoMethodBuilder *mb;
2672 mb = mono_mb_new (mono_defaults.object_class, "FOO", MONO_WRAPPER_NONE);
2673 m = mono_mb_create_method (mb, sig, 16);
2674 return mono_marshal_get_runtime_invoke (m, FALSE);
2678 can_marshal_struct (MonoClass *klass)
2680 MonoClassField *field;
2681 gboolean can_marshal = TRUE;
2682 gpointer iter = NULL;
2684 if ((klass->flags & TYPE_ATTRIBUTE_LAYOUT_MASK) == TYPE_ATTRIBUTE_AUTO_LAYOUT)
2687 /* Only allow a few field types to avoid asserts in the marshalling code */
2688 while ((field = mono_class_get_fields (klass, &iter))) {
2689 if ((field->type->attrs & FIELD_ATTRIBUTE_STATIC))
2692 switch (field->type->type) {
2697 case MONO_TYPE_BOOLEAN:
2700 case MONO_TYPE_CHAR:
2708 case MONO_TYPE_STRING:
2710 case MONO_TYPE_VALUETYPE:
2711 if (!mono_class_from_mono_type (field->type)->enumtype && !can_marshal_struct (mono_class_from_mono_type (field->type)))
2712 can_marshal = FALSE;
2715 can_marshal = FALSE;
2721 /* Its hard to compute whenever these can be marshalled or not */
2722 if (!strcmp (klass->name_space, "System.Net.NetworkInformation.MacOsStructs"))
2729 add_wrappers (MonoAotCompile *acfg)
2731 MonoMethod *method, *m;
2733 MonoMethodSignature *sig, *csig;
2737 * FIXME: Instead of AOTing all the wrappers, it might be better to redesign them
2738 * so there is only one wrapper of a given type, or inlining their contents into their
2743 * FIXME: This depends on the fact that different wrappers have different
2747 for (i = 0; i < acfg->image->tables [MONO_TABLE_METHOD].rows; ++i) {
2749 guint32 token = MONO_TOKEN_METHOD_DEF | (i + 1);
2750 gboolean skip = FALSE;
2752 method = mono_get_method (acfg->image, token, NULL);
2754 if ((method->flags & METHOD_ATTRIBUTE_PINVOKE_IMPL) ||
2755 (method->iflags & METHOD_IMPL_ATTRIBUTE_RUNTIME) ||
2756 (method->flags & METHOD_ATTRIBUTE_ABSTRACT))
2759 if (method->is_generic || method->klass->generic_container)
2762 /* Skip methods which can not be handled by get_runtime_invoke () */
2763 sig = mono_method_signature (method);
2766 if ((sig->ret->type == MONO_TYPE_PTR) ||
2767 (sig->ret->type == MONO_TYPE_TYPEDBYREF))
2770 for (j = 0; j < sig->param_count; j++) {
2771 if (sig->params [j]->type == MONO_TYPE_TYPEDBYREF)
2775 #ifdef MONO_ARCH_DYN_CALL_SUPPORTED
2776 if (!method->klass->contextbound) {
2777 MonoDynCallInfo *info = mono_arch_dyn_call_prepare (sig);
2778 gboolean has_nullable = FALSE;
2780 for (j = 0; j < sig->param_count; j++) {
2781 if (sig->params [j]->type == MONO_TYPE_GENERICINST && mono_class_is_nullable (mono_class_from_mono_type (sig->params [j])))
2782 has_nullable = TRUE;
2785 if (info && !has_nullable) {
2786 /* Supported by the dynamic runtime-invoke wrapper */
2794 //printf ("%s\n", mono_method_full_name (method, TRUE));
2795 add_method (acfg, mono_marshal_get_runtime_invoke (method, FALSE));
2799 if (strcmp (acfg->image->assembly->aname.name, "mscorlib") == 0) {
2800 #ifdef MONO_ARCH_HAVE_TLS_GET
2801 MonoMethodDesc *desc;
2802 MonoMethod *orig_method;
2806 /* Runtime invoke wrappers */
2808 /* void runtime-invoke () [.cctor] */
2809 csig = mono_metadata_signature_alloc (mono_defaults.corlib, 0);
2810 csig->ret = &mono_defaults.void_class->byval_arg;
2811 add_method (acfg, get_runtime_invoke_sig (csig));
2813 /* void runtime-invoke () [Finalize] */
2814 csig = mono_metadata_signature_alloc (mono_defaults.corlib, 0);
2816 csig->ret = &mono_defaults.void_class->byval_arg;
2817 add_method (acfg, get_runtime_invoke_sig (csig));
2819 /* void runtime-invoke (string) [exception ctor] */
2820 csig = mono_metadata_signature_alloc (mono_defaults.corlib, 1);
2822 csig->ret = &mono_defaults.void_class->byval_arg;
2823 csig->params [0] = &mono_defaults.string_class->byval_arg;
2824 add_method (acfg, get_runtime_invoke_sig (csig));
2826 /* void runtime-invoke (string, string) [exception ctor] */
2827 csig = mono_metadata_signature_alloc (mono_defaults.corlib, 2);
2829 csig->ret = &mono_defaults.void_class->byval_arg;
2830 csig->params [0] = &mono_defaults.string_class->byval_arg;
2831 csig->params [1] = &mono_defaults.string_class->byval_arg;
2832 add_method (acfg, get_runtime_invoke_sig (csig));
2834 /* string runtime-invoke () [Exception.ToString ()] */
2835 csig = mono_metadata_signature_alloc (mono_defaults.corlib, 0);
2837 csig->ret = &mono_defaults.string_class->byval_arg;
2838 add_method (acfg, get_runtime_invoke_sig (csig));
2840 /* void runtime-invoke (string, Exception) [exception ctor] */
2841 csig = mono_metadata_signature_alloc (mono_defaults.corlib, 2);
2843 csig->ret = &mono_defaults.void_class->byval_arg;
2844 csig->params [0] = &mono_defaults.string_class->byval_arg;
2845 csig->params [1] = &mono_defaults.exception_class->byval_arg;
2846 add_method (acfg, get_runtime_invoke_sig (csig));
2848 /* Assembly runtime-invoke (string, bool) [DoAssemblyResolve] */
2849 csig = mono_metadata_signature_alloc (mono_defaults.corlib, 2);
2851 csig->ret = &(mono_class_from_name (
2852 mono_defaults.corlib, "System.Reflection", "Assembly"))->byval_arg;
2853 csig->params [0] = &mono_defaults.string_class->byval_arg;
2854 csig->params [1] = &mono_defaults.boolean_class->byval_arg;
2855 add_method (acfg, get_runtime_invoke_sig (csig));
2857 /* runtime-invoke used by finalizers */
2858 add_method (acfg, mono_marshal_get_runtime_invoke (mono_class_get_method_from_name_flags (mono_defaults.object_class, "Finalize", 0, 0), TRUE));
2860 /* This is used by mono_runtime_capture_context () */
2861 method = mono_get_context_capture_method ();
2863 add_method (acfg, mono_marshal_get_runtime_invoke (method, FALSE));
2865 #ifdef MONO_ARCH_DYN_CALL_SUPPORTED
2866 add_method (acfg, mono_marshal_get_runtime_invoke_dynamic ());
2869 /* JIT icall wrappers */
2870 /* FIXME: locking */
2871 g_hash_table_foreach (mono_get_jit_icall_info (), add_jit_icall_wrapper, acfg);
2874 add_method (acfg, mono_marshal_get_stelemref ());
2876 #ifdef MONO_ARCH_HAVE_TLS_GET
2877 /* Managed Allocators */
2878 nallocators = mono_gc_get_managed_allocator_types ();
2879 for (i = 0; i < nallocators; ++i) {
2880 m = mono_gc_get_managed_allocator_by_type (i);
2882 add_method (acfg, m);
2885 /* Monitor Enter/Exit */
2886 desc = mono_method_desc_new ("Monitor:Enter(object,bool&)", FALSE);
2887 orig_method = mono_method_desc_search_in_class (desc, mono_defaults.monitor_class);
2888 /* This is a v4 method */
2890 method = mono_monitor_get_fast_path (orig_method);
2892 add_method (acfg, method);
2894 mono_method_desc_free (desc);
2896 desc = mono_method_desc_new ("Monitor:Exit(object)", FALSE);
2897 orig_method = mono_method_desc_search_in_class (desc, mono_defaults.monitor_class);
2898 g_assert (orig_method);
2899 mono_method_desc_free (desc);
2900 method = mono_monitor_get_fast_path (orig_method);
2902 add_method (acfg, method);
2905 /* Stelemref wrappers */
2906 /* There is only a constant number of these, iterating over all types should handle them all */
2907 for (i = 0; i < acfg->image->tables [MONO_TABLE_TYPEDEF].rows; ++i) {
2910 token = MONO_TOKEN_TYPE_DEF | (i + 1);
2911 klass = mono_class_get (acfg->image, token);
2913 add_method (acfg, mono_marshal_get_virtual_stelemref (mono_array_class_get (klass, 1)));
2915 mono_loader_clear_error ();
2918 /* castclass_with_check wrapper */
2919 add_method (acfg, mono_marshal_get_castclass_with_cache ());
2920 /* isinst_with_check wrapper */
2921 add_method (acfg, mono_marshal_get_isinst_with_cache ());
2923 #if defined(MONO_ARCH_ENABLE_MONITOR_IL_FASTPATH)
2925 MonoMethodDesc *desc;
2928 desc = mono_method_desc_new ("Monitor:Enter(object,bool&)", FALSE);
2929 m = mono_method_desc_search_in_class (desc, mono_defaults.monitor_class);
2930 mono_method_desc_free (desc);
2932 m = mono_monitor_get_fast_path (m);
2934 add_method (acfg, m);
2941 * remoting-invoke-with-check wrappers are very frequent, so avoid emitting them,
2942 * we use the original method instead at runtime.
2943 * Since full-aot doesn't support remoting, this is not a problem.
2946 /* remoting-invoke wrappers */
2947 for (i = 0; i < acfg->image->tables [MONO_TABLE_METHOD].rows; ++i) {
2948 MonoMethodSignature *sig;
2950 token = MONO_TOKEN_METHOD_DEF | (i + 1);
2951 method = mono_get_method (acfg->image, token, NULL);
2953 sig = mono_method_signature (method);
2955 if (sig->hasthis && (method->klass->marshalbyref || method->klass == mono_defaults.object_class)) {
2956 m = mono_marshal_get_remoting_invoke_with_check (method);
2958 add_method (acfg, m);
2963 /* delegate-invoke wrappers */
2964 for (i = 0; i < acfg->image->tables [MONO_TABLE_TYPEDEF].rows; ++i) {
2967 token = MONO_TOKEN_TYPE_DEF | (i + 1);
2968 klass = mono_class_get (acfg->image, token);
2971 mono_loader_clear_error ();
2975 if (klass->delegate && klass != mono_defaults.delegate_class && klass != mono_defaults.multicastdelegate_class && !klass->generic_container) {
2976 method = mono_get_delegate_invoke (klass);
2978 m = mono_marshal_get_delegate_invoke (method, NULL);
2980 add_method (acfg, m);
2982 method = mono_class_get_method_from_name_flags (klass, "BeginInvoke", -1, 0);
2984 add_method (acfg, mono_marshal_get_delegate_begin_invoke (method));
2986 method = mono_class_get_method_from_name_flags (klass, "EndInvoke", -1, 0);
2988 add_method (acfg, mono_marshal_get_delegate_end_invoke (method));
2992 /* Synchronized wrappers */
2993 for (i = 0; i < acfg->image->tables [MONO_TABLE_METHOD].rows; ++i) {
2994 token = MONO_TOKEN_METHOD_DEF | (i + 1);
2995 method = mono_get_method (acfg->image, token, NULL);
2997 if (method->iflags & METHOD_IMPL_ATTRIBUTE_SYNCHRONIZED && !method->is_generic)
2998 add_method (acfg, mono_marshal_get_synchronized_wrapper (method));
3001 /* pinvoke wrappers */
3002 for (i = 0; i < acfg->image->tables [MONO_TABLE_METHOD].rows; ++i) {
3004 guint32 token = MONO_TOKEN_METHOD_DEF | (i + 1);
3006 method = mono_get_method (acfg->image, token, NULL);
3008 if ((method->flags & METHOD_ATTRIBUTE_PINVOKE_IMPL) ||
3009 (method->iflags & METHOD_IMPL_ATTRIBUTE_INTERNAL_CALL)) {
3010 add_method (acfg, mono_marshal_get_native_wrapper (method, TRUE, TRUE));
3014 /* native-to-managed wrappers */
3015 for (i = 0; i < acfg->image->tables [MONO_TABLE_METHOD].rows; ++i) {
3017 guint32 token = MONO_TOKEN_METHOD_DEF | (i + 1);
3018 MonoCustomAttrInfo *cattr;
3021 method = mono_get_method (acfg->image, token, NULL);
3024 * Only generate native-to-managed wrappers for methods which have an
3025 * attribute named MonoPInvokeCallbackAttribute. We search for the attribute by
3026 * name to avoid defining a new assembly to contain it.
3028 cattr = mono_custom_attrs_from_method (method);
3031 for (j = 0; j < cattr->num_attrs; ++j)
3032 if (cattr->attrs [j].ctor && !strcmp (cattr->attrs [j].ctor->klass->name, "MonoPInvokeCallbackAttribute"))
3034 if (j < cattr->num_attrs) {
3035 MonoCustomAttrEntry *e = &cattr->attrs [j];
3036 MonoMethodSignature *sig = mono_method_signature (e->ctor);
3037 const char *p = (const char*)e->data;
3039 int slen, num_named, named_type, data_type;
3043 char *export_name = NULL;
3044 MonoMethod *wrapper;
3046 /* this cannot be enforced by the C# compiler so we must give the user some warning before aborting */
3047 if (!(method->flags & METHOD_ATTRIBUTE_STATIC)) {
3048 g_warning ("AOT restriction: Method '%s' must be static since it is decorated with [MonoPInvokeCallback]. See http://ios.xamarin.com/Documentation/Limitations#Reverse_Callbacks",
3049 mono_method_full_name (method, TRUE));
3053 g_assert (sig->param_count == 1);
3054 g_assert (sig->params [0]->type == MONO_TYPE_CLASS && !strcmp (mono_class_from_mono_type (sig->params [0])->name, "Type"));
3057 * Decode the cattr manually since we can't create objects
3058 * during aot compilation.
3064 /* From load_cattr_value () in reflection.c */
3065 slen = mono_metadata_decode_value (p, &p);
3066 n = g_memdup (p, slen + 1);
3068 t = mono_reflection_type_from_name (n, acfg->image);
3072 klass = mono_class_from_mono_type (t);
3073 g_assert (klass->parent == mono_defaults.multicastdelegate_class);
3077 num_named = read16 (p);
3080 g_assert (num_named < 2);
3081 if (num_named == 1) {
3084 MonoType *prop_type;
3086 /* parse ExportSymbol attribute */
3088 named_type = *named;
3093 name_len = mono_metadata_decode_blob_size (named, &named);
3094 name = g_malloc (name_len + 1);
3095 memcpy (name, named, name_len);
3096 name [name_len] = 0;
3099 g_assert (named_type == 0x54);
3100 g_assert (!strcmp (name, "ExportSymbol"));
3102 prop_type = &mono_defaults.string_class->byval_arg;
3104 /* load_cattr_value (), string case */
3105 g_assert (*named != (char)0xff);
3106 slen = mono_metadata_decode_value (named, &named);
3107 export_name = g_malloc (slen + 1);
3108 memcpy (export_name, named, slen);
3109 export_name [slen] = 0;
3113 wrapper = mono_marshal_get_managed_wrapper (method, klass, 0);
3114 add_method (acfg, wrapper);
3116 g_hash_table_insert (acfg->export_names, wrapper, export_name);
3120 if ((method->flags & METHOD_ATTRIBUTE_PINVOKE_IMPL) ||
3121 (method->iflags & METHOD_IMPL_ATTRIBUTE_INTERNAL_CALL)) {
3122 add_method (acfg, mono_marshal_get_native_wrapper (method, TRUE, TRUE));
3126 /* StructureToPtr/PtrToStructure wrappers */
3127 for (i = 0; i < acfg->image->tables [MONO_TABLE_TYPEDEF].rows; ++i) {
3130 token = MONO_TOKEN_TYPE_DEF | (i + 1);
3131 klass = mono_class_get (acfg->image, token);
3134 mono_loader_clear_error ();
3138 if (klass->valuetype && !klass->generic_container && can_marshal_struct (klass)) {
3139 add_method (acfg, mono_marshal_get_struct_to_ptr (klass));
3140 add_method (acfg, mono_marshal_get_ptr_to_struct (klass));
3146 has_type_vars (MonoClass *klass)
3148 if ((klass->byval_arg.type == MONO_TYPE_VAR) || (klass->byval_arg.type == MONO_TYPE_MVAR))
3151 return has_type_vars (klass->element_class);
3152 if (klass->generic_class) {
3153 MonoGenericContext *context = &klass->generic_class->context;
3154 if (context->class_inst) {
3157 for (i = 0; i < context->class_inst->type_argc; ++i)
3158 if (has_type_vars (mono_class_from_mono_type (context->class_inst->type_argv [i])))
3166 method_has_type_vars (MonoMethod *method)
3168 if (has_type_vars (method->klass))
3171 if (method->is_inflated) {
3172 MonoGenericContext *context = mono_method_get_context (method);
3173 if (context->method_inst) {
3176 for (i = 0; i < context->method_inst->type_argc; ++i)
3177 if (has_type_vars (mono_class_from_mono_type (context->method_inst->type_argv [i])))
3184 static void add_generic_class_with_depth (MonoAotCompile *acfg, MonoClass *klass, int depth, const char *ref);
3187 add_generic_class (MonoAotCompile *acfg, MonoClass *klass, gboolean force, const char *ref)
3189 /* This might lead to a huge code blowup so only do it if neccesary */
3190 if (!acfg->aot_opts.full_aot && !force)
3193 add_generic_class_with_depth (acfg, klass, 0, ref);
3197 check_type_depth (MonoType *t, int depth)
3205 case MONO_TYPE_GENERICINST: {
3206 MonoGenericClass *gklass = t->data.generic_class;
3207 MonoGenericInst *ginst = gklass->context.class_inst;
3210 for (i = 0; i < ginst->type_argc; ++i) {
3211 if (check_type_depth (ginst->type_argv [i], depth + 1))
3225 * add_generic_class:
3227 * Add all methods of a generic class.
3230 add_generic_class_with_depth (MonoAotCompile *acfg, MonoClass *klass, int depth, const char *ref)
3235 if (!acfg->ginst_hash)
3236 acfg->ginst_hash = g_hash_table_new (NULL, NULL);
3238 mono_class_init (klass);
3240 if (klass->generic_class && klass->generic_class->context.class_inst->is_open)
3243 if (has_type_vars (klass))
3246 if (!klass->generic_class && !klass->rank)
3249 if (!acfg->ginst_hash)
3250 acfg->ginst_hash = g_hash_table_new (NULL, NULL);
3252 if (g_hash_table_lookup (acfg->ginst_hash, klass))
3255 if (check_type_depth (&klass->byval_arg, 0))
3258 if (acfg->aot_opts.log_generics)
3259 printf ("%*sAdding generic instance %s [%s].\n", depth, "", mono_type_full_name (&klass->byval_arg), ref);
3261 g_hash_table_insert (acfg->ginst_hash, klass, klass);
3264 while ((method = mono_class_get_methods (klass, &iter))) {
3265 if (mono_method_is_generic_sharable_impl_full (method, FALSE, FALSE))
3269 if (method->is_generic)
3274 * FIXME: Instances which are referenced by these methods are not added,
3275 * for example Array.Resize<int> for List<int>.Add ().
3277 add_extra_method_with_depth (acfg, method, depth + 1);
3280 if (klass->delegate) {
3281 method = mono_get_delegate_invoke (klass);
3283 method = mono_marshal_get_delegate_invoke (method, NULL);
3285 if (acfg->aot_opts.log_generics)
3286 printf ("%*sAdding method %s.\n", depth, "", mono_method_full_name (method, TRUE));
3288 add_method (acfg, method);
3291 /* Add superclasses */
3293 add_generic_class_with_depth (acfg, klass->parent, depth, "parent");
3296 * For ICollection<T>, add instances of the helper methods
3297 * in Array, since a T[] could be cast to ICollection<T>.
3299 if (klass->image == mono_defaults.corlib && !strcmp (klass->name_space, "System.Collections.Generic") &&
3300 (!strcmp(klass->name, "ICollection`1") || !strcmp (klass->name, "IEnumerable`1") || !strcmp (klass->name, "IList`1") || !strcmp (klass->name, "IEnumerator`1"))) {
3301 MonoClass *tclass = mono_class_from_mono_type (klass->generic_class->context.class_inst->type_argv [0]);
3302 MonoClass *array_class = mono_bounded_array_class_get (tclass, 1, FALSE);
3306 if (!strcmp (klass->name, "IEnumerator`1"))
3307 name_prefix = g_strdup_printf ("%s.%s", klass->name_space, "IEnumerable`1");
3309 name_prefix = g_strdup_printf ("%s.%s", klass->name_space, klass->name);
3311 /* Add the T[]/InternalEnumerator class */
3312 if (!strcmp (klass->name, "IEnumerable`1") || !strcmp (klass->name, "IEnumerator`1")) {
3316 while ((nclass = mono_class_get_nested_types (array_class->parent, &iter))) {
3317 if (!strcmp (nclass->name, "InternalEnumerator`1"))
3321 nclass = mono_class_inflate_generic_class (nclass, mono_generic_class_get_context (klass->generic_class));
3322 add_generic_class (acfg, nclass, FALSE, "ICollection<T>");
3326 while ((method = mono_class_get_methods (array_class, &iter))) {
3327 if (strstr (method->name, name_prefix)) {
3328 MonoMethod *m = mono_aot_get_array_helper_from_wrapper (method);
3330 add_extra_method_with_depth (acfg, m, depth);
3334 g_free (name_prefix);
3337 /* Add an instance of GenericComparer<T> which is created dynamically by Comparer<T> */
3338 if (klass->image == mono_defaults.corlib && !strcmp (klass->name_space, "System.Collections.Generic") && !strcmp (klass->name, "Comparer`1")) {
3339 MonoClass *tclass = mono_class_from_mono_type (klass->generic_class->context.class_inst->type_argv [0]);
3340 MonoClass *icomparable, *gcomparer;
3341 MonoGenericContext ctx;
3342 MonoType *args [16];
3344 memset (&ctx, 0, sizeof (ctx));
3346 icomparable = mono_class_from_name (mono_defaults.corlib, "System", "IComparable`1");
3347 g_assert (icomparable);
3348 args [0] = &tclass->byval_arg;
3349 ctx.class_inst = mono_metadata_get_generic_inst (1, args);
3351 if (mono_class_is_assignable_from (mono_class_inflate_generic_class (icomparable, &ctx), tclass)) {
3352 gcomparer = mono_class_from_name (mono_defaults.corlib, "System.Collections.Generic", "GenericComparer`1");
3353 g_assert (gcomparer);
3354 add_generic_class (acfg, mono_class_inflate_generic_class (gcomparer, &ctx), FALSE, "Comparer<T>");
3358 /* Add an instance of GenericEqualityComparer<T> which is created dynamically by EqualityComparer<T> */
3359 if (klass->image == mono_defaults.corlib && !strcmp (klass->name_space, "System.Collections.Generic") && !strcmp (klass->name, "EqualityComparer`1")) {
3360 MonoClass *tclass = mono_class_from_mono_type (klass->generic_class->context.class_inst->type_argv [0]);
3361 MonoClass *iface, *gcomparer;
3362 MonoGenericContext ctx;
3363 MonoType *args [16];
3365 memset (&ctx, 0, sizeof (ctx));
3367 iface = mono_class_from_name (mono_defaults.corlib, "System", "IEquatable`1");
3369 args [0] = &tclass->byval_arg;
3370 ctx.class_inst = mono_metadata_get_generic_inst (1, args);
3372 if (mono_class_is_assignable_from (mono_class_inflate_generic_class (iface, &ctx), tclass)) {
3373 gcomparer = mono_class_from_name (mono_defaults.corlib, "System.Collections.Generic", "GenericEqualityComparer`1");
3374 g_assert (gcomparer);
3375 add_generic_class (acfg, mono_class_inflate_generic_class (gcomparer, &ctx), FALSE, "EqualityComparer<T>");
3381 add_instances_of (MonoAotCompile *acfg, MonoClass *klass, MonoType **insts, int ninsts, gboolean force)
3384 MonoGenericContext ctx;
3385 MonoType *args [16];
3387 memset (&ctx, 0, sizeof (ctx));
3389 for (i = 0; i < ninsts; ++i) {
3390 args [0] = insts [i];
3391 ctx.class_inst = mono_metadata_get_generic_inst (1, args);
3392 add_generic_class (acfg, mono_class_inflate_generic_class (klass, &ctx), force, "");
3397 add_types_from_method_header (MonoAotCompile *acfg, MonoMethod *method)
3399 MonoMethodHeader *header;
3400 MonoMethodSignature *sig;
3403 depth = GPOINTER_TO_UINT (g_hash_table_lookup (acfg->method_depth, method));
3405 sig = mono_method_signature (method);
3408 for (j = 0; j < sig->param_count; ++j)
3409 if (sig->params [j]->type == MONO_TYPE_GENERICINST)
3410 add_generic_class_with_depth (acfg, mono_class_from_mono_type (sig->params [j]), depth + 1, "arg");
3413 header = mono_method_get_header (method);
3416 for (j = 0; j < header->num_locals; ++j)
3417 if (header->locals [j]->type == MONO_TYPE_GENERICINST)
3418 add_generic_class_with_depth (acfg, mono_class_from_mono_type (header->locals [j]), depth + 1, "local");
3423 * add_generic_instances:
3425 * Add instances referenced by the METHODSPEC/TYPESPEC table.
3428 add_generic_instances (MonoAotCompile *acfg)
3433 MonoGenericContext *context;
3435 for (i = 0; i < acfg->image->tables [MONO_TABLE_METHODSPEC].rows; ++i) {
3436 token = MONO_TOKEN_METHOD_SPEC | (i + 1);
3437 method = mono_get_method (acfg->image, token, NULL);
3442 if (method->klass->image != acfg->image)
3445 context = mono_method_get_context (method);
3447 if (context && ((context->class_inst && context->class_inst->is_open)))
3451 * For open methods, create an instantiation which can be passed to the JIT.
3452 * FIXME: Handle class_inst as well.
3454 if (context && context->method_inst && context->method_inst->is_open) {
3455 MonoGenericContext shared_context;
3456 MonoGenericInst *inst;
3457 MonoType **type_argv;
3459 MonoMethod *declaring_method;
3460 gboolean supported = TRUE;
3462 /* Check that the context doesn't contain open constructed types */
3463 if (context->class_inst) {
3464 inst = context->class_inst;
3465 for (i = 0; i < inst->type_argc; ++i) {
3466 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)
3468 if (mono_class_is_open_constructed_type (inst->type_argv [i]))
3472 if (context->method_inst) {
3473 inst = context->method_inst;
3474 for (i = 0; i < inst->type_argc; ++i) {
3475 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)
3477 if (mono_class_is_open_constructed_type (inst->type_argv [i]))
3485 memset (&shared_context, 0, sizeof (MonoGenericContext));
3487 inst = context->class_inst;
3489 type_argv = g_new0 (MonoType*, inst->type_argc);
3490 for (i = 0; i < inst->type_argc; ++i) {
3491 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)
3492 type_argv [i] = &mono_defaults.object_class->byval_arg;
3494 type_argv [i] = inst->type_argv [i];
3497 shared_context.class_inst = mono_metadata_get_generic_inst (inst->type_argc, type_argv);
3501 inst = context->method_inst;
3503 type_argv = g_new0 (MonoType*, inst->type_argc);
3504 for (i = 0; i < inst->type_argc; ++i) {
3505 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)
3506 type_argv [i] = &mono_defaults.object_class->byval_arg;
3508 type_argv [i] = inst->type_argv [i];
3511 shared_context.method_inst = mono_metadata_get_generic_inst (inst->type_argc, type_argv);
3515 if (method->is_generic || method->klass->generic_container)
3516 declaring_method = method;
3518 declaring_method = mono_method_get_declaring_generic_method (method);
3520 method = mono_class_inflate_generic_method (declaring_method, &shared_context);
3524 * If the method is fully sharable, it was already added in place of its
3525 * generic definition.
3527 if (mono_method_is_generic_sharable_impl_full (method, FALSE, FALSE))
3531 * FIXME: Partially shared methods are not shared here, so we end up with
3532 * many identical methods.
3534 add_extra_method (acfg, method);
3537 for (i = 0; i < acfg->image->tables [MONO_TABLE_TYPESPEC].rows; ++i) {
3540 token = MONO_TOKEN_TYPE_SPEC | (i + 1);
3542 klass = mono_class_get (acfg->image, token);
3543 if (!klass || klass->rank) {
3544 mono_loader_clear_error ();
3548 add_generic_class (acfg, klass, FALSE, "typespec");
3551 /* Add types of args/locals */
3552 for (i = 0; i < acfg->methods->len; ++i) {
3553 method = g_ptr_array_index (acfg->methods, i);
3554 add_types_from_method_header (acfg, method);
3557 if (acfg->image == mono_defaults.corlib) {
3559 MonoType *insts [256];
3562 insts [ninsts ++] = &mono_defaults.byte_class->byval_arg;
3563 insts [ninsts ++] = &mono_defaults.sbyte_class->byval_arg;
3564 insts [ninsts ++] = &mono_defaults.int16_class->byval_arg;
3565 insts [ninsts ++] = &mono_defaults.uint16_class->byval_arg;
3566 insts [ninsts ++] = &mono_defaults.int32_class->byval_arg;
3567 insts [ninsts ++] = &mono_defaults.uint32_class->byval_arg;
3568 insts [ninsts ++] = &mono_defaults.int64_class->byval_arg;
3569 insts [ninsts ++] = &mono_defaults.uint64_class->byval_arg;
3570 insts [ninsts ++] = &mono_defaults.single_class->byval_arg;
3571 insts [ninsts ++] = &mono_defaults.double_class->byval_arg;
3572 insts [ninsts ++] = &mono_defaults.char_class->byval_arg;
3573 insts [ninsts ++] = &mono_defaults.boolean_class->byval_arg;
3575 /* Add GenericComparer<T> instances for primitive types for Enum.ToString () */
3576 klass = mono_class_from_name (acfg->image, "System.Collections.Generic", "GenericComparer`1");
3578 add_instances_of (acfg, klass, insts, ninsts, TRUE);
3579 klass = mono_class_from_name (acfg->image, "System.Collections.Generic", "GenericEqualityComparer`1");
3581 add_instances_of (acfg, klass, insts, ninsts, TRUE);
3583 /* Add instances of the array generic interfaces for primitive types */
3584 /* This will add instances of the InternalArray_ helper methods in Array too */
3585 klass = mono_class_from_name (acfg->image, "System.Collections.Generic", "ICollection`1");
3587 add_instances_of (acfg, klass, insts, ninsts, TRUE);
3588 klass = mono_class_from_name (acfg->image, "System.Collections.Generic", "IList`1");
3590 add_instances_of (acfg, klass, insts, ninsts, TRUE);
3591 klass = mono_class_from_name (acfg->image, "System.Collections.Generic", "IEnumerable`1");
3593 add_instances_of (acfg, klass, insts, ninsts, TRUE);
3596 * Add a managed-to-native wrapper of Array.GetGenericValueImpl<object>, which is
3597 * used for all instances of GetGenericValueImpl by the AOT runtime.
3600 MonoGenericContext ctx;
3601 MonoType *args [16];
3602 MonoMethod *get_method;
3603 MonoClass *array_klass = mono_array_class_get (mono_defaults.object_class, 1)->parent;
3605 get_method = mono_class_get_method_from_name (array_klass, "GetGenericValueImpl", 2);
3608 memset (&ctx, 0, sizeof (ctx));
3609 args [0] = &mono_defaults.object_class->byval_arg;
3610 ctx.method_inst = mono_metadata_get_generic_inst (1, args);
3611 add_extra_method (acfg, mono_marshal_get_native_wrapper (mono_class_inflate_generic_method (get_method, &ctx), TRUE, TRUE));
3615 /* Same for CompareExchange<T>/Exchange<T> */
3617 MonoGenericContext ctx;
3618 MonoType *args [16];
3620 MonoClass *interlocked_klass = mono_class_from_name (mono_defaults.corlib, "System.Threading", "Interlocked");
3621 gpointer iter = NULL;
3623 while ((m = mono_class_get_methods (interlocked_klass, &iter))) {
3624 if ((!strcmp (m->name, "CompareExchange") || !strcmp (m->name, "Exchange")) && m->is_generic) {
3625 memset (&ctx, 0, sizeof (ctx));
3626 args [0] = &mono_defaults.object_class->byval_arg;
3627 ctx.method_inst = mono_metadata_get_generic_inst (1, args);
3628 add_extra_method (acfg, mono_marshal_get_native_wrapper (mono_class_inflate_generic_method (m, &ctx), TRUE, TRUE));
3636 * is_direct_callable:
3638 * Return whenever the method identified by JI is directly callable without
3639 * going through the PLT.
3642 is_direct_callable (MonoAotCompile *acfg, MonoMethod *method, MonoJumpInfo *patch_info)
3644 if ((patch_info->type == MONO_PATCH_INFO_METHOD) && (patch_info->data.method->klass->image == acfg->image)) {
3645 MonoCompile *callee_cfg = g_hash_table_lookup (acfg->method_to_cfg, patch_info->data.method);
3647 gboolean direct_callable = TRUE;
3649 if (direct_callable && !(!callee_cfg->has_got_slots && (callee_cfg->method->klass->flags & TYPE_ATTRIBUTE_BEFORE_FIELD_INIT)))
3650 direct_callable = FALSE;
3651 if ((callee_cfg->method->iflags & METHOD_IMPL_ATTRIBUTE_SYNCHRONIZED) && (!method || method->wrapper_type != MONO_WRAPPER_SYNCHRONIZED))
3652 // FIXME: Maybe call the wrapper directly ?
3653 direct_callable = FALSE;
3655 if (acfg->aot_opts.soft_debug) {
3656 /* Disable this so all calls go through load_method (), see the
3657 * mini_get_debug_options ()->load_aot_jit_info_eagerly = TRUE; line in
3658 * mono_debugger_agent_init ().
3660 direct_callable = FALSE;
3663 if (direct_callable)
3666 } else if ((patch_info->type == MONO_PATCH_INFO_ICALL_ADDR && patch_info->data.method->flags & METHOD_ATTRIBUTE_PINVOKE_IMPL)) {
3667 if (acfg->aot_opts.direct_pinvoke)
3669 } else if (patch_info->type == MONO_PATCH_INFO_ICALL_ADDR) {
3670 if (acfg->aot_opts.direct_icalls)
3679 get_pinvoke_import (MonoAotCompile *acfg, MonoMethod *method)
3681 MonoImage *image = method->klass->image;
3682 MonoMethodPInvoke *piinfo = (MonoMethodPInvoke *) method;
3683 MonoTableInfo *tables = image->tables;
3684 MonoTableInfo *im = &tables [MONO_TABLE_IMPLMAP];
3685 MonoTableInfo *mr = &tables [MONO_TABLE_MODULEREF];
3686 guint32 im_cols [MONO_IMPLMAP_SIZE];
3689 import = g_hash_table_lookup (acfg->method_to_pinvoke_import, method);
3693 if (!piinfo->implmap_idx || piinfo->implmap_idx > im->rows)
3696 mono_metadata_decode_row (im, piinfo->implmap_idx - 1, im_cols, MONO_IMPLMAP_SIZE);
3698 if (!im_cols [MONO_IMPLMAP_SCOPE] || im_cols [MONO_IMPLMAP_SCOPE] > mr->rows)
3701 import = g_strdup_printf ("%s", mono_metadata_string_heap (image, im_cols [MONO_IMPLMAP_NAME]));
3703 g_hash_table_insert (acfg->method_to_pinvoke_import, method, import);
3709 * emit_and_reloc_code:
3711 * Emit the native code in CODE, handling relocations along the way. If GOT_ONLY
3712 * is true, calls are made through the GOT too. This is used for emitting trampolines
3713 * in full-aot mode, since calls made from trampolines couldn't go through the PLT,
3714 * since trampolines are needed to make PTL work.
3717 emit_and_reloc_code (MonoAotCompile *acfg, MonoMethod *method, guint8 *code, guint32 code_len, MonoJumpInfo *relocs, gboolean got_only)
3719 int i, pindex, start_index, method_index;
3721 MonoJumpInfo *patch_info;
3722 MonoMethodHeader *header;
3723 gboolean skip, direct_call;
3725 char direct_call_target [1024];
3726 const char *direct_pinvoke;
3729 header = mono_method_get_header (method);
3731 method_index = get_method_index (acfg, method);
3734 /* Collect and sort relocations */
3735 patches = g_ptr_array_new ();
3736 for (patch_info = relocs; patch_info; patch_info = patch_info->next)
3737 g_ptr_array_add (patches, patch_info);
3738 g_ptr_array_sort (patches, compare_patches);
3741 for (i = 0; i < code_len; i++) {
3743 for (pindex = start_index; pindex < patches->len; ++pindex) {
3744 patch_info = g_ptr_array_index (patches, pindex);
3745 if (patch_info->ip.i >= i)
3749 #ifdef MONO_ARCH_AOT_SUPPORTED
3751 if (patch_info && (patch_info->ip.i == i) && (pindex < patches->len)) {
3752 start_index = pindex;
3754 switch (patch_info->type) {
3755 case MONO_PATCH_INFO_NONE:
3757 case MONO_PATCH_INFO_GOT_OFFSET: {
3760 arch_emit_got_offset (acfg, code + i, &code_size);
3763 patch_info->type = MONO_PATCH_INFO_NONE;
3768 * If this patch is a call, try emitting a direct call instead of
3769 * through a PLT entry. This is possible if the called method is in
3770 * the same assembly and requires no initialization.
3772 direct_call = FALSE;
3773 if ((patch_info->type == MONO_PATCH_INFO_METHOD) && (patch_info->data.method->klass->image == acfg->image)) {
3774 if (!got_only && is_direct_callable (acfg, method, patch_info)) {
3775 MonoCompile *callee_cfg = g_hash_table_lookup (acfg->method_to_cfg, patch_info->data.method);
3776 //printf ("DIRECT: %s %s\n", method ? mono_method_full_name (method, TRUE) : "", mono_method_full_name (callee_cfg->method, TRUE));
3778 g_assert (strlen (callee_cfg->asm_symbol) < 1000);
3779 sprintf (direct_call_target, "%s", callee_cfg->asm_symbol);
3782 acfg->stats.all_calls ++;
3783 } else if (patch_info->type == MONO_PATCH_INFO_ICALL_ADDR) {
3784 if (!got_only && is_direct_callable (acfg, method, patch_info)) {
3785 if (!(patch_info->data.method->flags & METHOD_ATTRIBUTE_PINVOKE_IMPL))
3786 direct_pinvoke = mono_lookup_icall_symbol (patch_info->data.method);
3788 direct_pinvoke = get_pinvoke_import (acfg, patch_info->data.method);
3789 if (direct_pinvoke) {
3791 #if defined(__APPLE__)
3797 g_assert (strlen (direct_pinvoke) < 1000);
3798 sprintf (direct_call_target, "%s%s", prefix, direct_pinvoke);
3804 patch_info->type = MONO_PATCH_INFO_NONE;
3805 acfg->stats.direct_calls ++;
3808 if (!got_only && !direct_call) {
3809 MonoPltEntry *plt_entry = get_plt_entry (acfg, patch_info);
3811 /* This patch has a PLT entry, so we must emit a call to the PLT entry */
3813 sprintf (direct_call_target, "%s", plt_entry->symbol);
3815 /* Nullify the patch */
3816 patch_info->type = MONO_PATCH_INFO_NONE;
3817 plt_entry->jit_used = TRUE;
3824 arch_emit_direct_call (acfg, direct_call_target, &call_size);
3829 got_slot = get_got_offset (acfg, patch_info);
3831 arch_emit_got_access (acfg, code + i, got_slot, &code_size);
3838 #endif /* MONO_ARCH_AOT_SUPPORTED */
3841 /* Find next patch */
3843 for (pindex = start_index; pindex < patches->len; ++pindex) {
3844 patch_info = g_ptr_array_index (patches, pindex);
3845 if (patch_info->ip.i >= i)
3849 /* Try to emit multiple bytes at once */
3850 if (pindex < patches->len && patch_info->ip.i > i) {
3851 emit_bytes (acfg, code + i, patch_info->ip.i - i);
3852 i = patch_info->ip.i - 1;
3854 emit_bytes (acfg, code + i, 1);
3863 * Modify SYMBOL so it only includes characters permissible in symbols.
3866 sanitize_symbol (char *symbol)
3868 int i, len = strlen (symbol);
3870 for (i = 0; i < len; ++i)
3871 if (!isalnum (symbol [i]) && (symbol [i] != '_'))
3876 get_debug_sym (MonoMethod *method, const char *prefix, GHashTable *cache)
3878 char *name1, *name2, *cached;
3879 int i, j, len, count;
3881 name1 = mono_method_full_name (method, TRUE);
3882 len = strlen (name1);
3883 name2 = malloc (strlen (prefix) + len + 16);
3884 memcpy (name2, prefix, strlen (prefix));
3885 j = strlen (prefix);
3886 for (i = 0; i < len; ++i) {
3887 if (isalnum (name1 [i])) {
3888 name2 [j ++] = name1 [i];
3889 } else if (name1 [i] == ' ' && name1 [i + 1] == '(' && name1 [i + 2] == ')') {
3891 } else if (name1 [i] == ',' && name1 [i + 1] == ' ') {
3894 } else if (name1 [i] == '(' || name1 [i] == ')' || name1 [i] == '>') {
3903 while (g_hash_table_lookup (cache, name2)) {
3904 sprintf (name2 + j, "_%d", count);
3908 cached = g_strdup (name2);
3909 g_hash_table_insert (cache, cached, cached);
3915 emit_method_code (MonoAotCompile *acfg, MonoCompile *cfg)
3920 char *debug_sym = NULL;
3922 int func_alignment = AOT_FUNC_ALIGNMENT;
3923 MonoMethodHeader *header;
3926 method = cfg->orig_method;
3927 code = cfg->native_code;
3928 header = cfg->header;
3930 method_index = get_method_index (acfg, method);
3932 /* Make the labels local */
3933 sprintf (symbol, "%s", cfg->asm_symbol);
3935 emit_section_change (acfg, ".text", 0);
3936 emit_alignment (acfg, func_alignment);
3937 emit_label (acfg, symbol);
3939 if (acfg->aot_opts.write_symbols) {
3941 * Write a C style symbol for every method, this has two uses:
3942 * - it works on platforms where the dwarf debugging info is not
3944 * - it allows the setting of breakpoints of aot-ed methods.
3946 debug_sym = get_debug_sym (method, "", acfg->method_label_hash);
3948 sprintf (symbol, "%sme_%x", acfg->temp_prefix, method_index);
3949 if (acfg->need_no_dead_strip)
3950 fprintf (acfg->fp, " .no_dead_strip %s\n", debug_sym);
3951 emit_local_symbol (acfg, debug_sym, symbol, TRUE);
3952 emit_label (acfg, debug_sym);
3955 export_name = g_hash_table_lookup (acfg->export_names, method);
3957 /* Emit a global symbol for the method */
3958 emit_global_inner (acfg, export_name, TRUE);
3959 emit_label (acfg, export_name);
3962 if (cfg->verbose_level > 0)
3963 g_print ("Method %s emitted as %s\n", mono_method_full_name (method, TRUE), symbol);
3965 acfg->stats.code_size += cfg->code_len;
3967 acfg->cfgs [method_index]->got_offset = acfg->got_offset;
3969 emit_and_reloc_code (acfg, method, code, cfg->code_len, cfg->patch_info, FALSE);
3973 if (acfg->aot_opts.write_symbols) {
3974 emit_symbol_size (acfg, debug_sym, ".");
3978 sprintf (symbol, "%sme_%x", acfg->temp_prefix, method_index);
3979 emit_label (acfg, symbol);
3985 * Encode PATCH_INFO into its disk representation.
3988 encode_patch (MonoAotCompile *acfg, MonoJumpInfo *patch_info, guint8 *buf, guint8 **endbuf)
3992 switch (patch_info->type) {
3993 case MONO_PATCH_INFO_NONE:
3995 case MONO_PATCH_INFO_IMAGE:
3996 encode_value (get_image_index (acfg, patch_info->data.image), p, &p);
3998 case MONO_PATCH_INFO_MSCORLIB_GOT_ADDR:
3999 case MONO_PATCH_INFO_GC_CARD_TABLE_ADDR:
4000 case MONO_PATCH_INFO_CASTCLASS_CACHE:
4002 case MONO_PATCH_INFO_METHOD_REL:
4003 encode_value ((gint)patch_info->data.offset, p, &p);
4005 case MONO_PATCH_INFO_SWITCH: {
4006 gpointer *table = (gpointer *)patch_info->data.table->table;
4009 encode_value (patch_info->data.table->table_size, p, &p);
4010 for (k = 0; k < patch_info->data.table->table_size; k++)
4011 encode_value ((int)(gssize)table [k], p, &p);
4014 case MONO_PATCH_INFO_METHODCONST:
4015 case MONO_PATCH_INFO_METHOD:
4016 case MONO_PATCH_INFO_METHOD_JUMP:
4017 case MONO_PATCH_INFO_ICALL_ADDR:
4018 case MONO_PATCH_INFO_METHOD_RGCTX:
4019 encode_method_ref (acfg, patch_info->data.method, p, &p);
4021 case MONO_PATCH_INFO_INTERNAL_METHOD:
4022 case MONO_PATCH_INFO_JIT_ICALL_ADDR: {
4023 guint32 len = strlen (patch_info->data.name);
4025 encode_value (len, p, &p);
4027 memcpy (p, patch_info->data.name, len);
4032 case MONO_PATCH_INFO_LDSTR: {
4033 guint32 image_index = get_image_index (acfg, patch_info->data.token->image);
4034 guint32 token = patch_info->data.token->token;
4035 g_assert (mono_metadata_token_code (token) == MONO_TOKEN_STRING);
4036 encode_value (image_index, p, &p);
4037 encode_value (patch_info->data.token->token - MONO_TOKEN_STRING, p, &p);
4040 case MONO_PATCH_INFO_RVA:
4041 case MONO_PATCH_INFO_DECLSEC:
4042 case MONO_PATCH_INFO_LDTOKEN:
4043 case MONO_PATCH_INFO_TYPE_FROM_HANDLE:
4044 encode_value (get_image_index (acfg, patch_info->data.token->image), p, &p);
4045 encode_value (patch_info->data.token->token, p, &p);
4046 encode_value (patch_info->data.token->has_context, p, &p);
4047 if (patch_info->data.token->has_context)
4048 encode_generic_context (acfg, &patch_info->data.token->context, p, &p);
4050 case MONO_PATCH_INFO_EXC_NAME: {
4051 MonoClass *ex_class;
4054 mono_class_from_name (mono_defaults.exception_class->image,
4055 "System", patch_info->data.target);
4056 g_assert (ex_class);
4057 encode_klass_ref (acfg, ex_class, p, &p);
4060 case MONO_PATCH_INFO_R4:
4061 encode_value (*((guint32 *)patch_info->data.target), p, &p);
4063 case MONO_PATCH_INFO_R8:
4064 encode_value (((guint32 *)patch_info->data.target) [MINI_LS_WORD_IDX], p, &p);
4065 encode_value (((guint32 *)patch_info->data.target) [MINI_MS_WORD_IDX], p, &p);
4067 case MONO_PATCH_INFO_VTABLE:
4068 case MONO_PATCH_INFO_CLASS:
4069 case MONO_PATCH_INFO_IID:
4070 case MONO_PATCH_INFO_ADJUSTED_IID:
4071 encode_klass_ref (acfg, patch_info->data.klass, p, &p);
4073 case MONO_PATCH_INFO_CLASS_INIT:
4074 case MONO_PATCH_INFO_DELEGATE_TRAMPOLINE:
4075 encode_klass_ref (acfg, patch_info->data.klass, p, &p);
4077 case MONO_PATCH_INFO_FIELD:
4078 case MONO_PATCH_INFO_SFLDA:
4079 encode_field_info (acfg, patch_info->data.field, p, &p);
4081 case MONO_PATCH_INFO_INTERRUPTION_REQUEST_FLAG:
4083 case MONO_PATCH_INFO_RGCTX_FETCH: {
4084 MonoJumpInfoRgctxEntry *entry = patch_info->data.rgctx_entry;
4089 * entry->method has a lenghtly encoding and multiple rgctx_fetch entries
4090 * reference the same method, so encode the method only once.
4092 offset = GPOINTER_TO_UINT (g_hash_table_lookup (acfg->method_blob_hash, entry->method));
4094 buf2 = g_malloc (1024);
4097 encode_method_ref (acfg, entry->method, p2, &p2);
4098 g_assert (p2 - buf2 < 1024);
4100 offset = add_to_blob (acfg, buf2, p2 - buf2);
4103 g_hash_table_insert (acfg->method_blob_hash, entry->method, GUINT_TO_POINTER (offset + 1));
4108 encode_value (offset, p, &p);
4109 g_assert (entry->info_type < 256);
4110 g_assert (entry->data->type < 256);
4111 encode_value ((entry->in_mrgctx ? 1 : 0) | (entry->info_type << 1) | (entry->data->type << 9), p, &p);
4112 encode_patch (acfg, entry->data, p, &p);
4115 case MONO_PATCH_INFO_GENERIC_CLASS_INIT:
4116 case MONO_PATCH_INFO_MONITOR_ENTER:
4117 case MONO_PATCH_INFO_MONITOR_EXIT:
4118 case MONO_PATCH_INFO_SEQ_POINT_INFO:
4120 case MONO_PATCH_INFO_LLVM_IMT_TRAMPOLINE:
4121 encode_method_ref (acfg, patch_info->data.imt_tramp->method, p, &p);
4122 encode_value (patch_info->data.imt_tramp->vt_offset, p, &p);
4124 case MONO_PATCH_INFO_SIGNATURE:
4125 encode_signature (acfg, (MonoMethodSignature*)patch_info->data.target, p, &p);
4128 g_warning ("unable to handle jump info %d", patch_info->type);
4129 g_assert_not_reached ();
4136 encode_patch_list (MonoAotCompile *acfg, GPtrArray *patches, int n_patches, int first_got_offset, guint8 *buf, guint8 **endbuf)
4139 guint32 pindex, offset;
4140 MonoJumpInfo *patch_info;
4142 encode_value (n_patches, p, &p);
4144 for (pindex = 0; pindex < patches->len; ++pindex) {
4145 patch_info = g_ptr_array_index (patches, pindex);
4147 if (patch_info->type == MONO_PATCH_INFO_NONE || patch_info->type == MONO_PATCH_INFO_BB)
4151 offset = get_got_offset (acfg, patch_info);
4152 encode_value (offset, p, &p);
4159 emit_method_info (MonoAotCompile *acfg, MonoCompile *cfg)
4163 int pindex, buf_size, n_patches;
4165 MonoJumpInfo *patch_info;
4166 MonoMethodHeader *header;
4167 guint32 method_index;
4169 guint32 first_got_offset;
4171 method = cfg->orig_method;
4172 header = mono_method_get_header (method);
4174 method_index = get_method_index (acfg, method);
4176 /* Sort relocations */
4177 patches = g_ptr_array_new ();
4178 for (patch_info = cfg->patch_info; patch_info; patch_info = patch_info->next)
4179 g_ptr_array_add (patches, patch_info);
4180 g_ptr_array_sort (patches, compare_patches);
4182 first_got_offset = acfg->cfgs [method_index]->got_offset;
4184 /**********************/
4185 /* Encode method info */
4186 /**********************/
4188 buf_size = (patches->len < 1000) ? 40960 : 40960 + (patches->len * 64);
4189 p = buf = g_malloc (buf_size);
4191 if (mono_class_get_cctor (method->klass))
4192 encode_klass_ref (acfg, method->klass, p, &p);
4194 /* Not needed when loading the method */
4195 encode_value (0, p, &p);
4198 if (cfg->opt & MONO_OPT_SHARED) {
4199 encode_value (g_list_length (cfg->ldstr_list), p, &p);
4200 for (l = cfg->ldstr_list; l; l = l->next) {
4201 encode_value ((long)l->data, p, &p);
4205 /* Used only in shared mode */
4206 g_assert (!cfg->ldstr_list);
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_GOT_OFFSET) ||
4213 (patch_info->type == MONO_PATCH_INFO_NONE)) {
4214 patch_info->type = MONO_PATCH_INFO_NONE;
4219 if ((patch_info->type == MONO_PATCH_INFO_IMAGE) && (patch_info->data.image == acfg->image)) {
4220 /* Stored in a GOT slot initialized at module load time */
4221 patch_info->type = MONO_PATCH_INFO_NONE;
4225 if (patch_info->type == MONO_PATCH_INFO_GC_CARD_TABLE_ADDR) {
4226 /* Stored in a GOT slot initialized at module load time */
4227 patch_info->type = MONO_PATCH_INFO_NONE;
4231 if (is_plt_patch (patch_info)) {
4232 /* Calls are made through the PLT */
4233 patch_info->type = MONO_PATCH_INFO_NONE;
4241 g_assert (cfg->has_got_slots);
4243 encode_patch_list (acfg, patches, n_patches, first_got_offset, p, &p);
4245 acfg->stats.info_size += p - buf;
4247 g_assert (p - buf < buf_size);
4249 cfg->method_info_offset = add_to_blob (acfg, buf, p - buf);
4254 get_unwind_info_offset (MonoAotCompile *acfg, guint8 *encoded, guint32 encoded_len)
4256 guint32 cache_index;
4259 /* Reuse the unwind module to canonize and store unwind info entries */
4260 cache_index = mono_cache_unwind_info (encoded, encoded_len);
4262 /* Use +/- 1 to distinguish 0s from missing entries */
4263 offset = GPOINTER_TO_UINT (g_hash_table_lookup (acfg->unwind_info_offsets, GUINT_TO_POINTER (cache_index + 1)));
4271 * It would be easier to use assembler symbols, but the caller needs an
4274 offset = acfg->unwind_info_offset;
4275 g_hash_table_insert (acfg->unwind_info_offsets, GUINT_TO_POINTER (cache_index + 1), GUINT_TO_POINTER (offset + 1));
4276 g_ptr_array_add (acfg->unwind_ops, GUINT_TO_POINTER (cache_index));
4279 encode_value (encoded_len, p, &p);
4281 acfg->unwind_info_offset += encoded_len + (p - buf);
4287 emit_exception_debug_info (MonoAotCompile *acfg, MonoCompile *cfg)
4290 int i, k, buf_size, method_index;
4291 guint32 debug_info_size;
4293 MonoMethodHeader *header;
4294 guint8 *p, *buf, *debug_info;
4295 MonoJitInfo *jinfo = cfg->jit_info;
4297 gboolean use_unwind_ops = FALSE;
4298 MonoSeqPointInfo *seq_points;
4300 method = cfg->orig_method;
4301 code = cfg->native_code;
4302 header = cfg->header;
4304 method_index = get_method_index (acfg, method);
4306 if (!acfg->aot_opts.nodebug) {
4307 mono_debug_serialize_debug_info (cfg, &debug_info, &debug_info_size);
4310 debug_info_size = 0;
4313 seq_points = cfg->seq_point_info;
4315 buf_size = header->num_clauses * 256 + debug_info_size + 2048 + (seq_points ? (seq_points->len * 64) : 0) + cfg->gc_map_size;
4316 p = buf = g_malloc (buf_size);
4318 #ifdef MONO_ARCH_HAVE_XP_UNWIND
4319 use_unwind_ops = cfg->unwind_ops != NULL;
4322 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);
4324 encode_value (flags, p, &p);
4326 if (use_unwind_ops) {
4327 guint32 encoded_len;
4331 * This is a duplicate of the data in the .debug_frame section, but that
4332 * section cannot be accessed using the dl interface.
4334 encoded = mono_unwind_ops_encode (cfg->unwind_ops, &encoded_len);
4335 encode_value (get_unwind_info_offset (acfg, encoded, encoded_len), p, &p);
4338 encode_value (jinfo->used_regs, p, &p);
4341 /*Encode the number of holes before the number of clauses to make decoding easier*/
4342 if (jinfo->has_try_block_holes) {
4343 MonoTryBlockHoleTableJitInfo *table = mono_jit_info_get_try_block_hole_table_info (jinfo);
4344 encode_value (table->num_holes, p, &p);
4347 /* Exception table */
4348 if (cfg->compile_llvm) {
4350 * When using LLVM, we can't emit some data, like pc offsets, this reg/offset etc.,
4351 * since the information is only available to llc. Instead, we let llc save the data
4352 * into the LSDA, and read it from there at runtime.
4354 /* The assembly might be CIL stripped so emit the data ourselves */
4355 if (header->num_clauses)
4356 encode_value (header->num_clauses, p, &p);
4358 for (k = 0; k < header->num_clauses; ++k) {
4359 MonoExceptionClause *clause;
4361 clause = &header->clauses [k];
4363 encode_value (clause->flags, p, &p);
4364 if (clause->data.catch_class) {
4365 encode_value (1, p, &p);
4366 encode_klass_ref (acfg, clause->data.catch_class, p, &p);
4368 encode_value (0, p, &p);
4371 /* Emit a list of nesting clauses */
4372 for (i = 0; i < header->num_clauses; ++i) {
4374 MonoExceptionClause *clause1 = &header->clauses [cindex1];
4376 MonoExceptionClause *clause2 = &header->clauses [cindex2];
4378 if (cindex1 != cindex2 && clause1->try_offset >= clause2->try_offset && clause1->handler_offset <= clause2->handler_offset)
4379 encode_value (i, p, &p);
4381 encode_value (-1, p, &p);
4384 if (jinfo->num_clauses)
4385 encode_value (jinfo->num_clauses, p, &p);
4387 for (k = 0; k < jinfo->num_clauses; ++k) {
4388 MonoJitExceptionInfo *ei = &jinfo->clauses [k];
4390 encode_value (ei->flags, p, &p);
4391 encode_value (ei->exvar_offset, p, &p);
4393 if (ei->flags == MONO_EXCEPTION_CLAUSE_FILTER || ei->flags == MONO_EXCEPTION_CLAUSE_FINALLY)
4394 encode_value ((gint)((guint8*)ei->data.filter - code), p, &p);
4396 if (ei->data.catch_class) {
4397 encode_value (1, p, &p);
4398 encode_klass_ref (acfg, ei->data.catch_class, p, &p);
4400 encode_value (0, p, &p);
4404 encode_value ((gint)((guint8*)ei->try_start - code), p, &p);
4405 encode_value ((gint)((guint8*)ei->try_end - code), p, &p);
4406 encode_value ((gint)((guint8*)ei->handler_start - code), p, &p);
4410 if (jinfo->has_generic_jit_info) {
4411 MonoGenericJitInfo *gi = mono_jit_info_get_generic_jit_info (jinfo);
4415 encode_value (gi->nlocs, p, &p);
4417 for (i = 0; i < gi->nlocs; ++i) {
4418 MonoDwarfLocListEntry *entry = &gi->locations [i];
4420 encode_value (entry->is_reg ? 1 : 0, p, &p);
4421 encode_value (entry->reg, p, &p);
4423 encode_value (entry->offset, p, &p);
4425 g_assert (entry->from == 0);
4427 encode_value (entry->from, p, &p);
4428 encode_value (entry->to, p, &p);
4431 if (!cfg->compile_llvm) {
4432 encode_value (gi->has_this ? 1 : 0, p, &p);
4433 encode_value (gi->this_reg, p, &p);
4434 encode_value (gi->this_offset, p, &p);
4439 * Need to encode jinfo->method too, since it is not equal to 'method'
4440 * when using generic sharing.
4442 encode_method_ref (acfg, jinfo->method, p, &p);
4445 if (jinfo->has_try_block_holes) {
4446 MonoTryBlockHoleTableJitInfo *table = mono_jit_info_get_try_block_hole_table_info (jinfo);
4447 for (i = 0; i < table->num_holes; ++i) {
4448 MonoTryBlockHoleJitInfo *hole = &table->holes [i];
4449 encode_value (hole->clause, p, &p);
4450 encode_value (hole->length, p, &p);
4451 encode_value (hole->offset, p, &p);
4455 if (jinfo->has_arch_eh_info) {
4456 MonoArchEHJitInfo *eh_info;
4458 eh_info = mono_jit_info_get_arch_eh_info (jinfo);
4459 encode_value (eh_info->stack_size, p, &p);
4463 int il_offset, native_offset, last_il_offset, last_native_offset, j;
4465 encode_value (seq_points->len, p, &p);
4466 last_il_offset = last_native_offset = 0;
4467 for (i = 0; i < seq_points->len; ++i) {
4468 SeqPoint *sp = &seq_points->seq_points [i];
4469 il_offset = sp->il_offset;
4470 native_offset = sp->native_offset;
4471 encode_value (il_offset - last_il_offset, p, &p);
4472 encode_value (native_offset - last_native_offset, p, &p);
4473 last_il_offset = il_offset;
4474 last_native_offset = native_offset;
4476 encode_value (sp->next_len, p, &p);
4477 for (j = 0; j < sp->next_len; ++j)
4478 encode_value (sp->next [j], p, &p);
4482 g_assert (debug_info_size < buf_size);
4484 encode_value (debug_info_size, p, &p);
4485 if (debug_info_size) {
4486 memcpy (p, debug_info, debug_info_size);
4487 p += debug_info_size;
4488 g_free (debug_info);
4493 encode_value (cfg->gc_map_size, p, &p);
4494 /* The GC map requires 4 bytes of alignment */
4495 while ((gsize)p % 4)
4497 memcpy (p, cfg->gc_map, cfg->gc_map_size);
4498 p += cfg->gc_map_size;
4501 acfg->stats.ex_info_size += p - buf;
4503 g_assert (p - buf < buf_size);
4506 /* The GC Map requires 4 byte alignment */
4507 cfg->ex_info_offset = add_to_blob_aligned (acfg, buf, p - buf, cfg->gc_map ? 4 : 1);
4512 emit_klass_info (MonoAotCompile *acfg, guint32 token)
4514 MonoClass *klass = mono_class_get (acfg->image, token);
4516 int i, buf_size, res;
4517 gboolean no_special_static, cant_encode;
4518 gpointer iter = NULL;
4521 mono_loader_clear_error ();
4525 p = buf = g_malloc (buf_size);
4527 /* Mark as unusable */
4528 encode_value (-1, p, &p);
4530 res = add_to_blob (acfg, buf, p - buf);
4536 buf_size = 10240 + (klass->vtable_size * 16);
4537 p = buf = g_malloc (buf_size);
4541 mono_class_init (klass);
4543 mono_class_get_nested_types (klass, &iter);
4544 g_assert (klass->nested_classes_inited);
4546 mono_class_setup_vtable (klass);
4549 * Emit all the information which is required for creating vtables so
4550 * the runtime does not need to create the MonoMethod structures which
4551 * take up a lot of space.
4554 no_special_static = !mono_class_has_special_static_fields (klass);
4556 /* Check whenever we have enough info to encode the vtable */
4557 cant_encode = FALSE;
4558 for (i = 0; i < klass->vtable_size; ++i) {
4559 MonoMethod *cm = klass->vtable [i];
4561 if (cm && mono_method_signature (cm)->is_inflated && !g_hash_table_lookup (acfg->token_info_hash, cm))
4565 mono_class_has_finalizer (klass);
4567 if (klass->generic_container || cant_encode) {
4568 encode_value (-1, p, &p);
4570 encode_value (klass->vtable_size, p, &p);
4571 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);
4572 if (klass->has_cctor)
4573 encode_method_ref (acfg, mono_class_get_cctor (klass), p, &p);
4574 if (klass->has_finalize)
4575 encode_method_ref (acfg, mono_class_get_finalizer (klass), p, &p);
4577 encode_value (klass->instance_size, p, &p);
4578 encode_value (mono_class_data_size (klass), p, &p);
4579 encode_value (klass->packing_size, p, &p);
4580 encode_value (klass->min_align, p, &p);
4582 for (i = 0; i < klass->vtable_size; ++i) {
4583 MonoMethod *cm = klass->vtable [i];
4586 encode_method_ref (acfg, cm, p, &p);
4588 encode_value (0, p, &p);
4592 acfg->stats.class_info_size += p - buf;
4594 g_assert (p - buf < buf_size);
4595 res = add_to_blob (acfg, buf, p - buf);
4602 get_plt_entry_debug_sym (MonoAotCompile *acfg, MonoJumpInfo *ji, GHashTable *cache)
4604 char *debug_sym = NULL;
4607 case MONO_PATCH_INFO_METHOD:
4608 debug_sym = get_debug_sym (ji->data.method, "plt_", cache);
4610 case MONO_PATCH_INFO_INTERNAL_METHOD:
4611 debug_sym = g_strdup_printf ("plt__jit_icall_%s", ji->data.name);
4613 case MONO_PATCH_INFO_CLASS_INIT:
4614 debug_sym = g_strdup_printf ("plt__class_init_%s", mono_type_get_name (&ji->data.klass->byval_arg));
4615 sanitize_symbol (debug_sym);
4617 case MONO_PATCH_INFO_RGCTX_FETCH:
4618 debug_sym = g_strdup_printf ("plt__rgctx_fetch_%d", acfg->label_generator ++);
4620 case MONO_PATCH_INFO_ICALL_ADDR: {
4621 char *s = get_debug_sym (ji->data.method, "", cache);
4623 debug_sym = g_strdup_printf ("plt__icall_native_%s", s);
4627 case MONO_PATCH_INFO_JIT_ICALL_ADDR:
4628 debug_sym = g_strdup_printf ("plt__jit_icall_native_%s", ji->data.name);
4630 case MONO_PATCH_INFO_GENERIC_CLASS_INIT:
4631 debug_sym = g_strdup_printf ("plt__generic_class_init");
4641 * Calls made from AOTed code are routed through a table of jumps similar to the
4642 * ELF PLT (Program Linkage Table). Initially the PLT entries jump to code which transfers
4643 * control to the AOT runtime through a trampoline.
4646 emit_plt (MonoAotCompile *acfg)
4652 sprintf (symbol, "plt");
4654 emit_section_change (acfg, ".text", 0);
4655 emit_alignment (acfg, NACL_SIZE(16, kNaClAlignment));
4656 emit_label (acfg, symbol);
4657 emit_label (acfg, acfg->plt_symbol);
4659 for (i = 0; i < acfg->plt_offset; ++i) {
4660 char *debug_sym = NULL;
4661 MonoPltEntry *plt_entry = NULL;
4666 * The first plt entry is unused.
4670 plt_entry = g_hash_table_lookup (acfg->plt_offset_to_entry, GUINT_TO_POINTER (i));
4675 * If the target is directly callable, alias the plt symbol to point to
4677 * FIXME: Use this to simplify emit_and_reloc_code ().
4678 * FIXME: Avoid the got slot.
4679 * FIXME: Add support to the binary writer.
4681 if (ji && is_direct_callable (acfg, NULL, ji) && !acfg->use_bin_writer) {
4682 MonoCompile *callee_cfg = g_hash_table_lookup (acfg->method_to_cfg, ji->data.method);
4685 if (acfg->thumb_mixed && !callee_cfg->compile_llvm) {
4686 /* LLVM calls the PLT entries using bl, so emit a stub */
4687 fprintf (acfg->fp, "\n.thumb_func\n");
4688 emit_label (acfg, plt_entry->llvm_symbol);
4689 fprintf (acfg->fp, "bx pc\n");
4690 fprintf (acfg->fp, "nop\n");
4691 fprintf (acfg->fp, ".arm\n");
4692 fprintf (acfg->fp, "b %s\n", callee_cfg->asm_symbol);
4694 fprintf (acfg->fp, "\n.set %s, %s\n", plt_entry->llvm_symbol, callee_cfg->asm_symbol);
4701 debug_sym = plt_entry->debug_sym;
4703 if (acfg->thumb_mixed && !plt_entry->jit_used)
4704 /* Emit only a thumb version */
4707 if (!acfg->thumb_mixed)
4708 emit_label (acfg, plt_entry->llvm_symbol);
4711 if (acfg->need_no_dead_strip)
4712 fprintf (acfg->fp, " .no_dead_strip %s\n", debug_sym);
4713 emit_local_symbol (acfg, debug_sym, NULL, TRUE);
4714 emit_label (acfg, debug_sym);
4717 emit_label (acfg, plt_entry->symbol);
4719 arch_emit_plt_entry (acfg, i);
4722 emit_symbol_size (acfg, debug_sym, ".");
4725 if (acfg->thumb_mixed) {
4726 /* Make sure the ARM symbols don't alias the thumb ones */
4727 emit_zero_bytes (acfg, 16);
4730 * Emit a separate set of PLT entries using thumb2 which is called by LLVM generated
4733 for (i = 0; i < acfg->plt_offset; ++i) {
4734 char *debug_sym = NULL;
4735 MonoPltEntry *plt_entry = NULL;
4741 plt_entry = g_hash_table_lookup (acfg->plt_offset_to_entry, GUINT_TO_POINTER (i));
4744 if (ji && is_direct_callable (acfg, NULL, ji) && !acfg->use_bin_writer)
4747 /* Skip plt entries not actually called by LLVM code */
4748 if (!plt_entry->llvm_used)
4751 if (acfg->aot_opts.write_symbols) {
4752 if (plt_entry->debug_sym)
4753 debug_sym = g_strdup_printf ("%s_thumb", plt_entry->debug_sym);
4757 #if defined(__APPLE__)
4758 fprintf (acfg->fp, " .thumb_func %s\n", debug_sym);
4759 fprintf (acfg->fp, " .no_dead_strip %s\n", debug_sym);
4761 emit_local_symbol (acfg, debug_sym, NULL, TRUE);
4762 emit_label (acfg, debug_sym);
4764 fprintf (acfg->fp, "\n.thumb_func\n");
4766 emit_label (acfg, plt_entry->llvm_symbol);
4768 arch_emit_llvm_plt_entry (acfg, i);
4771 emit_symbol_size (acfg, debug_sym, ".");
4777 emit_symbol_size (acfg, acfg->plt_symbol, ".");
4779 sprintf (symbol, "plt_end");
4780 emit_label (acfg, symbol);
4783 static G_GNUC_UNUSED void
4784 emit_trampoline (MonoAotCompile *acfg, int got_offset, MonoTrampInfo *info)
4786 char start_symbol [256];
4788 guint32 buf_size, info_offset;
4789 MonoJumpInfo *patch_info;
4800 code_size = info->code_size;
4802 unwind_ops = info->unwind_ops;
4804 #ifdef __native_client_codegen__
4805 mono_nacl_fix_patches (code, ji);
4810 sprintf (start_symbol, "%s", name);
4812 emit_section_change (acfg, ".text", 0);
4813 emit_global (acfg, start_symbol, TRUE);
4814 emit_alignment (acfg, AOT_FUNC_ALIGNMENT);
4815 emit_label (acfg, start_symbol);
4817 sprintf (symbol, "%snamed_%s", acfg->temp_prefix, name);
4818 emit_label (acfg, symbol);
4821 * The code should access everything through the GOT, so we pass
4824 emit_and_reloc_code (acfg, NULL, code, code_size, ji, TRUE);
4826 emit_symbol_size (acfg, start_symbol, ".");
4830 /* Sort relocations */
4831 patches = g_ptr_array_new ();
4832 for (patch_info = ji; patch_info; patch_info = patch_info->next)
4833 if (patch_info->type != MONO_PATCH_INFO_NONE)
4834 g_ptr_array_add (patches, patch_info);
4835 g_ptr_array_sort (patches, compare_patches);
4837 buf_size = patches->len * 128 + 128;
4838 buf = g_malloc (buf_size);
4841 encode_patch_list (acfg, patches, patches->len, got_offset, p, &p);
4842 g_assert (p - buf < buf_size);
4844 sprintf (symbol, "%s_p", name);
4846 info_offset = add_to_blob (acfg, buf, p - buf);
4848 emit_section_change (acfg, RODATA_SECT, 0);
4849 emit_global (acfg, symbol, FALSE);
4850 emit_label (acfg, symbol);
4852 emit_int32 (acfg, info_offset);
4854 /* Emit debug info */
4858 sprintf (symbol, "%s", name);
4859 sprintf (symbol2, "%snamed_%s", acfg->temp_prefix, name);
4862 mono_dwarf_writer_emit_trampoline (acfg->dwarf, symbol, symbol2, NULL, NULL, code_size, unwind_ops);
4867 emit_trampolines (MonoAotCompile *acfg)
4870 char end_symbol [256];
4871 int i, tramp_got_offset;
4872 MonoAotTrampoline ntype;
4873 #ifdef MONO_ARCH_HAVE_FULL_AOT_TRAMPOLINES
4877 if (!acfg->aot_opts.full_aot)
4880 g_assert (acfg->image->assembly);
4882 /* Currently, we emit most trampolines into the mscorlib AOT image. */
4883 if (strcmp (acfg->image->assembly->aname.name, "mscorlib") == 0) {
4884 #ifdef MONO_ARCH_HAVE_FULL_AOT_TRAMPOLINES
4885 MonoTrampInfo *info;
4888 * Emit the generic trampolines.
4890 * We could save some code by treating the generic trampolines as a wrapper
4891 * method, but that approach has its own complexities, so we choose the simpler
4894 for (tramp_type = 0; tramp_type < MONO_TRAMPOLINE_NUM; ++tramp_type) {
4895 mono_arch_create_generic_trampoline (tramp_type, &info, TRUE);
4896 emit_trampoline (acfg, acfg->got_offset, info);
4899 mono_arch_get_nullified_class_init_trampoline (&info);
4900 emit_trampoline (acfg, acfg->got_offset, info);
4901 #if defined(MONO_ARCH_MONITOR_OBJECT_REG)
4902 mono_arch_create_monitor_enter_trampoline (&info, TRUE);
4903 emit_trampoline (acfg, acfg->got_offset, info);
4904 mono_arch_create_monitor_exit_trampoline (&info, TRUE);
4905 emit_trampoline (acfg, acfg->got_offset, info);
4908 mono_arch_create_generic_class_init_trampoline (&info, TRUE);
4909 emit_trampoline (acfg, acfg->got_offset, info);
4911 /* Emit the exception related code pieces */
4912 mono_arch_get_restore_context (&info, TRUE);
4913 emit_trampoline (acfg, acfg->got_offset, info);
4914 mono_arch_get_call_filter (&info, TRUE);
4915 emit_trampoline (acfg, acfg->got_offset, info);
4916 mono_arch_get_throw_exception (&info, TRUE);
4917 emit_trampoline (acfg, acfg->got_offset, info);
4918 mono_arch_get_rethrow_exception (&info, TRUE);
4919 emit_trampoline (acfg, acfg->got_offset, info);
4920 mono_arch_get_throw_corlib_exception (&info, TRUE);
4921 emit_trampoline (acfg, acfg->got_offset, info);
4923 #if defined(MONO_ARCH_HAVE_GET_TRAMPOLINES)
4925 GSList *l = mono_arch_get_trampolines (TRUE);
4928 MonoTrampInfo *info = l->data;
4930 emit_trampoline (acfg, acfg->got_offset, info);
4936 for (i = 0; i < 128; ++i) {
4939 offset = MONO_RGCTX_SLOT_MAKE_RGCTX (i);
4940 mono_arch_create_rgctx_lazy_fetch_trampoline (offset, &info, TRUE);
4941 emit_trampoline (acfg, acfg->got_offset, info);
4943 offset = MONO_RGCTX_SLOT_MAKE_MRGCTX (i);
4944 mono_arch_create_rgctx_lazy_fetch_trampoline (offset, &info, TRUE);
4945 emit_trampoline (acfg, acfg->got_offset, info);
4951 /* delegate_invoke_impl trampolines */
4952 l = mono_arch_get_delegate_invoke_impls ();
4954 MonoTrampInfo *info = l->data;
4956 emit_trampoline (acfg, acfg->got_offset, info);
4961 #endif /* #ifdef MONO_ARCH_HAVE_FULL_AOT_TRAMPOLINES */
4963 /* Emit trampolines which are numerous */
4966 * These include the following:
4967 * - specific trampolines
4968 * - static rgctx invoke trampolines
4970 * These trampolines have the same code, they are parameterized by GOT
4972 * They are defined in this file, in the arch_... routines instead of
4973 * in tramp-<ARCH>.c, since it is easier to do it this way.
4977 * When running in aot-only mode, we can't create specific trampolines at
4978 * runtime, so we create a few, and save them in the AOT file.
4979 * Normal trampolines embed their argument as a literal inside the
4980 * trampoline code, we can't do that here, so instead we embed an offset
4981 * which needs to be added to the trampoline address to get the address of
4982 * the GOT slot which contains the argument value.
4983 * The generated trampolines jump to the generic trampolines using another
4984 * GOT slot, which will be setup by the AOT loader to point to the
4985 * generic trampoline code of the given type.
4989 * FIXME: Maybe we should use more specific trampolines (i.e. one class init for
4993 emit_section_change (acfg, ".text", 0);
4995 tramp_got_offset = acfg->got_offset;
4997 for (ntype = 0; ntype < MONO_AOT_TRAMP_NUM; ++ntype) {
4999 case MONO_AOT_TRAMP_SPECIFIC:
5000 sprintf (symbol, "specific_trampolines");
5002 case MONO_AOT_TRAMP_STATIC_RGCTX:
5003 sprintf (symbol, "static_rgctx_trampolines");
5005 case MONO_AOT_TRAMP_IMT_THUNK:
5006 sprintf (symbol, "imt_thunks");
5009 g_assert_not_reached ();
5012 sprintf (end_symbol, "%s_e", symbol);
5014 if (acfg->aot_opts.write_symbols)
5015 emit_local_symbol (acfg, symbol, end_symbol, TRUE);
5017 emit_alignment (acfg, AOT_FUNC_ALIGNMENT);
5018 emit_label (acfg, symbol);
5020 acfg->trampoline_got_offset_base [ntype] = tramp_got_offset;
5022 for (i = 0; i < acfg->num_trampolines [ntype]; ++i) {
5026 case MONO_AOT_TRAMP_SPECIFIC:
5027 arch_emit_specific_trampoline (acfg, tramp_got_offset, &tramp_size);
5028 tramp_got_offset += 2;
5030 case MONO_AOT_TRAMP_STATIC_RGCTX:
5031 arch_emit_static_rgctx_trampoline (acfg, tramp_got_offset, &tramp_size);
5032 tramp_got_offset += 2;
5034 case MONO_AOT_TRAMP_IMT_THUNK:
5035 arch_emit_imt_thunk (acfg, tramp_got_offset, &tramp_size);
5036 tramp_got_offset += 1;
5039 g_assert_not_reached ();
5041 #ifdef __native_client_codegen__
5042 /* align to avoid 32-byte boundary crossings */
5043 emit_alignment (acfg, AOT_FUNC_ALIGNMENT);
5046 if (!acfg->trampoline_size [ntype]) {
5047 g_assert (tramp_size);
5048 acfg->trampoline_size [ntype] = tramp_size;
5052 emit_label (acfg, end_symbol);
5055 /* Reserve some entries at the end of the GOT for our use */
5056 acfg->num_trampoline_got_entries = tramp_got_offset - acfg->got_offset;
5059 acfg->got_offset += acfg->num_trampoline_got_entries;
5063 str_begins_with (const char *str1, const char *str2)
5065 int len = strlen (str2);
5066 return strncmp (str1, str2, len) == 0;
5070 mono_aot_readonly_field_override (MonoClassField *field)
5073 for (rdv = readonly_values; rdv; rdv = rdv->next) {
5074 char *p = rdv->name;
5076 len = strlen (field->parent->name_space);
5077 if (strncmp (p, field->parent->name_space, len))
5082 len = strlen (field->parent->name);
5083 if (strncmp (p, field->parent->name, len))
5088 if (strcmp (p, field->name))
5090 switch (rdv->type) {
5092 return &rdv->value.i1;
5094 return &rdv->value.i2;
5096 return &rdv->value.i4;
5105 add_readonly_value (MonoAotOptions *opts, const char *val)
5110 /* the format of val is:
5111 * namespace.typename.fieldname=type/value
5112 * type can be i1 for uint8/int8/boolean, i2 for uint16/int16/char, i4 for uint32/int32
5114 fval = strrchr (val, '/');
5116 fprintf (stderr, "AOT : invalid format for readonly field '%s', missing /.\n", val);
5119 tval = strrchr (val, '=');
5121 fprintf (stderr, "AOT : invalid format for readonly field '%s', missing =.\n", val);
5124 rdv = g_new0 (ReadOnlyValue, 1);
5125 rdv->name = g_malloc0 (tval - val + 1);
5126 memcpy (rdv->name, val, tval - val);
5129 if (strncmp (tval, "i1", 2) == 0) {
5130 rdv->value.i1 = atoi (fval);
5131 rdv->type = MONO_TYPE_I1;
5132 } else if (strncmp (tval, "i2", 2) == 0) {
5133 rdv->value.i2 = atoi (fval);
5134 rdv->type = MONO_TYPE_I2;
5135 } else if (strncmp (tval, "i4", 2) == 0) {
5136 rdv->value.i4 = atoi (fval);
5137 rdv->type = MONO_TYPE_I4;
5139 fprintf (stderr, "AOT : unsupported type for readonly field '%s'.\n", tval);
5142 rdv->next = readonly_values;
5143 readonly_values = rdv;
5147 mono_aot_parse_options (const char *aot_options, MonoAotOptions *opts)
5149 gchar **args, **ptr;
5151 args = g_strsplit (aot_options ? aot_options : "", ",", -1);
5152 for (ptr = args; ptr && *ptr; ptr ++) {
5153 const char *arg = *ptr;
5155 if (str_begins_with (arg, "outfile=")) {
5156 opts->outfile = g_strdup (arg + strlen ("outfile="));
5157 } else if (str_begins_with (arg, "save-temps")) {
5158 opts->save_temps = TRUE;
5159 } else if (str_begins_with (arg, "keep-temps")) {
5160 opts->save_temps = TRUE;
5161 } else if (str_begins_with (arg, "write-symbols")) {
5162 opts->write_symbols = TRUE;
5163 } else if (str_begins_with (arg, "no-write-symbols")) {
5164 opts->write_symbols = FALSE;
5165 } else if (str_begins_with (arg, "metadata-only")) {
5166 opts->metadata_only = TRUE;
5167 } else if (str_begins_with (arg, "bind-to-runtime-version")) {
5168 opts->bind_to_runtime_version = TRUE;
5169 } else if (str_begins_with (arg, "full")) {
5170 opts->full_aot = TRUE;
5171 } else if (str_begins_with (arg, "threads=")) {
5172 opts->nthreads = atoi (arg + strlen ("threads="));
5173 } else if (str_begins_with (arg, "static")) {
5174 opts->static_link = TRUE;
5175 opts->no_dlsym = TRUE;
5176 } else if (str_begins_with (arg, "asmonly")) {
5177 opts->asm_only = TRUE;
5178 } else if (str_begins_with (arg, "asmwriter")) {
5179 opts->asm_writer = TRUE;
5180 } else if (str_begins_with (arg, "nodebug")) {
5181 opts->nodebug = TRUE;
5182 } else if (str_begins_with (arg, "ntrampolines=")) {
5183 opts->ntrampolines = atoi (arg + strlen ("ntrampolines="));
5184 } else if (str_begins_with (arg, "nrgctx-trampolines=")) {
5185 opts->nrgctx_trampolines = atoi (arg + strlen ("nrgctx-trampolines="));
5186 } else if (str_begins_with (arg, "nimt-trampolines=")) {
5187 opts->nimt_trampolines = atoi (arg + strlen ("nimt-trampolines="));
5188 } else if (str_begins_with (arg, "autoreg")) {
5189 opts->autoreg = TRUE;
5190 } else if (str_begins_with (arg, "tool-prefix=")) {
5191 opts->tool_prefix = g_strdup (arg + strlen ("tool-prefix="));
5192 } else if (str_begins_with (arg, "soft-debug")) {
5193 opts->soft_debug = TRUE;
5194 } else if (str_begins_with (arg, "direct-pinvoke")) {
5195 opts->direct_pinvoke = TRUE;
5196 } else if (str_begins_with (arg, "direct-icalls")) {
5197 opts->direct_icalls = TRUE;
5198 } else if (str_begins_with (arg, "print-skipped")) {
5199 opts->print_skipped_methods = TRUE;
5200 } else if (str_begins_with (arg, "stats")) {
5202 } else if (str_begins_with (arg, "log-generics")) {
5203 opts->log_generics = TRUE;
5204 } else if (str_begins_with (arg, "mtriple=")) {
5205 opts->mtriple = g_strdup (arg + strlen ("mtriple="));
5206 } else if (str_begins_with (arg, "llvm-path=")) {
5207 opts->llvm_path = g_strdup (arg + strlen ("llvm-path="));
5208 } else if (str_begins_with (arg, "readonly-value=")) {
5209 add_readonly_value (opts, arg + strlen ("readonly-value="));
5210 } else if (str_begins_with (arg, "info")) {
5211 printf ("AOT target setup: %s.\n", AOT_TARGET_STR);
5213 } else if (str_begins_with (arg, "help") || str_begins_with (arg, "?")) {
5214 printf ("Supported options for --aot:\n");
5215 printf (" outfile=\n");
5216 printf (" save-temps\n");
5217 printf (" keep-temps\n");
5218 printf (" write-symbols\n");
5219 printf (" metadata-only\n");
5220 printf (" bind-to-runtime-version\n");
5222 printf (" threads=\n");
5223 printf (" static\n");
5224 printf (" asmonly\n");
5225 printf (" asmwriter\n");
5226 printf (" nodebug\n");
5227 printf (" ntrampolines=\n");
5228 printf (" nrgctx-trampolines=\n");
5229 printf (" nimt-trampolines=\n");
5230 printf (" autoreg\n");
5231 printf (" tool-prefix=\n");
5232 printf (" readonly-value=\n");
5233 printf (" soft-debug\n");
5234 printf (" print-skipped\n");
5235 printf (" stats\n");
5237 printf (" help/?\n");
5240 fprintf (stderr, "AOT : Unknown argument '%s'.\n", arg);
5249 add_token_info_hash (gpointer key, gpointer value, gpointer user_data)
5251 MonoMethod *method = (MonoMethod*)key;
5252 MonoJumpInfoToken *ji = (MonoJumpInfoToken*)value;
5253 MonoJumpInfoToken *new_ji = g_new0 (MonoJumpInfoToken, 1);
5254 MonoAotCompile *acfg = user_data;
5256 new_ji->image = ji->image;
5257 new_ji->token = ji->token;
5258 g_hash_table_insert (acfg->token_info_hash, method, new_ji);
5262 can_encode_class (MonoAotCompile *acfg, MonoClass *klass)
5264 if (klass->type_token)
5266 if ((klass->byval_arg.type == MONO_TYPE_VAR) || (klass->byval_arg.type == MONO_TYPE_MVAR) || (klass->byval_arg.type == MONO_TYPE_PTR))
5269 return can_encode_class (acfg, klass->element_class);
5274 can_encode_patch (MonoAotCompile *acfg, MonoJumpInfo *patch_info)
5276 switch (patch_info->type) {
5277 case MONO_PATCH_INFO_METHOD:
5278 case MONO_PATCH_INFO_METHODCONST: {
5279 MonoMethod *method = patch_info->data.method;
5281 if (method->wrapper_type) {
5282 switch (method->wrapper_type) {
5283 case MONO_WRAPPER_NONE:
5284 case MONO_WRAPPER_REMOTING_INVOKE_WITH_CHECK:
5285 case MONO_WRAPPER_XDOMAIN_INVOKE:
5286 case MONO_WRAPPER_STFLD:
5287 case MONO_WRAPPER_LDFLD:
5288 case MONO_WRAPPER_LDFLDA:
5289 case MONO_WRAPPER_LDFLD_REMOTE:
5290 case MONO_WRAPPER_STFLD_REMOTE:
5291 case MONO_WRAPPER_STELEMREF:
5292 case MONO_WRAPPER_ISINST:
5293 case MONO_WRAPPER_PROXY_ISINST:
5294 case MONO_WRAPPER_ALLOC:
5295 case MONO_WRAPPER_REMOTING_INVOKE:
5296 case MONO_WRAPPER_UNKNOWN:
5297 case MONO_WRAPPER_WRITE_BARRIER:
5299 case MONO_WRAPPER_MANAGED_TO_MANAGED:
5300 case MONO_WRAPPER_CASTCLASS: {
5301 WrapperInfo *info = mono_marshal_get_wrapper_info (method);
5310 //printf ("Skip (wrapper call): %d -> %s\n", patch_info->type, mono_method_full_name (patch_info->data.method, TRUE));
5314 if (!method->token) {
5315 /* The method is part of a constructed type like Int[,].Set (). */
5316 if (!g_hash_table_lookup (acfg->token_info_hash, method)) {
5317 if (method->klass->rank)
5325 case MONO_PATCH_INFO_VTABLE:
5326 case MONO_PATCH_INFO_CLASS_INIT:
5327 case MONO_PATCH_INFO_DELEGATE_TRAMPOLINE:
5328 case MONO_PATCH_INFO_CLASS:
5329 case MONO_PATCH_INFO_IID:
5330 case MONO_PATCH_INFO_ADJUSTED_IID:
5331 if (!can_encode_class (acfg, patch_info->data.klass)) {
5332 //printf ("Skip: %s\n", mono_type_full_name (&patch_info->data.klass->byval_arg));
5336 case MONO_PATCH_INFO_RGCTX_FETCH: {
5337 MonoJumpInfoRgctxEntry *entry = patch_info->data.rgctx_entry;
5339 if (!can_encode_patch (acfg, entry->data))
5353 * AOT compile a given method.
5354 * This function might be called by multiple threads, so it must be thread-safe.
5357 compile_method (MonoAotCompile *acfg, MonoMethod *method)
5360 MonoJumpInfo *patch_info;
5363 MonoMethod *wrapped;
5365 if (acfg->aot_opts.metadata_only)
5368 mono_acfg_lock (acfg);
5369 index = get_method_index (acfg, method);
5370 mono_acfg_unlock (acfg);
5372 /* fixme: maybe we can also precompile wrapper methods */
5373 if ((method->flags & METHOD_ATTRIBUTE_PINVOKE_IMPL) ||
5374 (method->iflags & METHOD_IMPL_ATTRIBUTE_RUNTIME) ||
5375 (method->flags & METHOD_ATTRIBUTE_ABSTRACT)) {
5376 //printf ("Skip (impossible): %s\n", mono_method_full_name (method, TRUE));
5380 if (method->iflags & METHOD_IMPL_ATTRIBUTE_INTERNAL_CALL)
5383 wrapped = mono_marshal_method_from_wrapper (method);
5384 if (wrapped && (wrapped->iflags & METHOD_IMPL_ATTRIBUTE_INTERNAL_CALL) && wrapped->is_generic)
5385 // FIXME: The wrapper should be generic too, but it is not
5388 if (method->wrapper_type == MONO_WRAPPER_COMINTEROP)
5391 InterlockedIncrement (&acfg->stats.mcount);
5394 if (method->is_generic || method->klass->generic_container) {
5395 InterlockedIncrement (&acfg->stats.genericcount);
5400 //acfg->aot_opts.print_skipped_methods = TRUE;
5403 * Since these methods are the only ones which are compiled with
5404 * AOT support, and they are not used by runtime startup/shutdown code,
5405 * the runtime will not see AOT methods during AOT compilation,so it
5406 * does not need to support them by creating a fake GOT etc.
5408 cfg = mini_method_compile (method, acfg->opts, mono_get_root_domain (), FALSE, TRUE, 0);
5409 if (cfg->exception_type == MONO_EXCEPTION_GENERIC_SHARING_FAILED) {
5410 //printf ("F: %s\n", mono_method_full_name (method, TRUE));
5411 InterlockedIncrement (&acfg->stats.genericcount);
5414 if (cfg->exception_type != MONO_EXCEPTION_NONE) {
5415 if (acfg->aot_opts.print_skipped_methods)
5416 printf ("Skip (JIT failure): %s\n", mono_method_full_name (method, TRUE));
5417 /* Let the exception happen at runtime */
5421 if (cfg->disable_aot) {
5422 if (acfg->aot_opts.print_skipped_methods)
5423 printf ("Skip (disabled): %s\n", mono_method_full_name (method, TRUE));
5424 InterlockedIncrement (&acfg->stats.ocount);
5425 mono_destroy_compile (cfg);
5429 /* Nullify patches which need no aot processing */
5430 for (patch_info = cfg->patch_info; patch_info; patch_info = patch_info->next) {
5431 switch (patch_info->type) {
5432 case MONO_PATCH_INFO_LABEL:
5433 case MONO_PATCH_INFO_BB:
5434 patch_info->type = MONO_PATCH_INFO_NONE;
5441 /* Collect method->token associations from the cfg */
5442 mono_acfg_lock (acfg);
5443 g_hash_table_foreach (cfg->token_info_hash, add_token_info_hash, acfg);
5444 mono_acfg_unlock (acfg);
5447 * Check for absolute addresses.
5450 for (patch_info = cfg->patch_info; patch_info; patch_info = patch_info->next) {
5451 switch (patch_info->type) {
5452 case MONO_PATCH_INFO_ABS:
5453 /* unable to handle this */
5462 if (acfg->aot_opts.print_skipped_methods)
5463 printf ("Skip (abs call): %s\n", mono_method_full_name (method, TRUE));
5464 InterlockedIncrement (&acfg->stats.abscount);
5465 mono_destroy_compile (cfg);
5469 /* Lock for the rest of the code */
5470 mono_acfg_lock (acfg);
5473 * Check for methods/klasses we can't encode.
5476 for (patch_info = cfg->patch_info; patch_info; patch_info = patch_info->next) {
5477 if (!can_encode_patch (acfg, patch_info))
5482 if (acfg->aot_opts.print_skipped_methods)
5483 printf ("Skip (patches): %s\n", mono_method_full_name (method, TRUE));
5484 acfg->stats.ocount++;
5485 mono_destroy_compile (cfg);
5486 mono_acfg_unlock (acfg);
5490 /* Adds generic instances referenced by this method */
5492 * The depth is used to avoid infinite loops when generic virtual recursion is
5495 depth = GPOINTER_TO_UINT (g_hash_table_lookup (acfg->method_depth, method));
5497 for (patch_info = cfg->patch_info; patch_info; patch_info = patch_info->next) {
5498 switch (patch_info->type) {
5499 case MONO_PATCH_INFO_METHOD: {
5500 MonoMethod *m = patch_info->data.method;
5501 if (m->is_inflated) {
5502 if (!(mono_class_generic_sharing_enabled (m->klass) &&
5503 mono_method_is_generic_sharable_impl (m, FALSE)) &&
5504 !method_has_type_vars (m)) {
5505 if (m->iflags & METHOD_IMPL_ATTRIBUTE_INTERNAL_CALL) {
5506 if (acfg->aot_opts.full_aot)
5507 add_extra_method_with_depth (acfg, mono_marshal_get_native_wrapper (m, TRUE, TRUE), depth + 1);
5509 add_extra_method_with_depth (acfg, m, depth + 1);
5510 add_types_from_method_header (acfg, m);
5513 add_generic_class_with_depth (acfg, m->klass, depth + 5, "method");
5515 if (m->wrapper_type == MONO_WRAPPER_MANAGED_TO_MANAGED && !strcmp (m->name, "ElementAddr"))
5516 add_extra_method_with_depth (acfg, m, depth + 1);
5519 case MONO_PATCH_INFO_VTABLE: {
5520 MonoClass *klass = patch_info->data.klass;
5522 if (klass->generic_class && !mono_generic_context_is_sharable (&klass->generic_class->context, FALSE))
5523 add_generic_class_with_depth (acfg, klass, depth + 5, "vtable");
5526 case MONO_PATCH_INFO_SFLDA: {
5527 MonoClass *klass = patch_info->data.field->parent;
5529 /* The .cctor needs to run at runtime. */
5530 if (klass->generic_class && !mono_generic_context_is_sharable (&klass->generic_class->context, FALSE) && mono_class_get_cctor (klass))
5531 add_extra_method_with_depth (acfg, mono_class_get_cctor (klass), depth + 1);
5540 /* Determine whenever the method has GOT slots */
5541 for (patch_info = cfg->patch_info; patch_info; patch_info = patch_info->next) {
5542 switch (patch_info->type) {
5543 case MONO_PATCH_INFO_GOT_OFFSET:
5544 case MONO_PATCH_INFO_NONE:
5545 case MONO_PATCH_INFO_GC_CARD_TABLE_ADDR:
5547 case MONO_PATCH_INFO_IMAGE:
5548 /* The assembly is stored in GOT slot 0 */
5549 if (patch_info->data.image != acfg->image)
5550 cfg->has_got_slots = TRUE;
5553 if (!is_plt_patch (patch_info))
5554 cfg->has_got_slots = TRUE;
5559 if (!cfg->has_got_slots)
5560 InterlockedIncrement (&acfg->stats.methods_without_got_slots);
5563 * FIXME: Instead of this mess, allocate the patches from the aot mempool.
5565 /* Make a copy of the patch info which is in the mempool */
5567 MonoJumpInfo *patches = NULL, *patches_end = NULL;
5569 for (patch_info = cfg->patch_info; patch_info; patch_info = patch_info->next) {
5570 MonoJumpInfo *new_patch_info = mono_patch_info_dup_mp (acfg->mempool, patch_info);
5573 patches = new_patch_info;
5575 patches_end->next = new_patch_info;
5576 patches_end = new_patch_info;
5578 cfg->patch_info = patches;
5580 /* Make a copy of the unwind info */
5582 GSList *l, *unwind_ops;
5586 for (l = cfg->unwind_ops; l; l = l->next) {
5587 op = mono_mempool_alloc (acfg->mempool, sizeof (MonoUnwindOp));
5588 memcpy (op, l->data, sizeof (MonoUnwindOp));
5589 unwind_ops = g_slist_prepend_mempool (acfg->mempool, unwind_ops, op);
5591 cfg->unwind_ops = g_slist_reverse (unwind_ops);
5593 /* Make a copy of the argument/local info */
5595 MonoInst **args, **locals;
5596 MonoMethodSignature *sig;
5597 MonoMethodHeader *header;
5600 sig = mono_method_signature (method);
5601 args = mono_mempool_alloc (acfg->mempool, sizeof (MonoInst*) * (sig->param_count + sig->hasthis));
5602 for (i = 0; i < sig->param_count + sig->hasthis; ++i) {
5603 args [i] = mono_mempool_alloc (acfg->mempool, sizeof (MonoInst));
5604 memcpy (args [i], cfg->args [i], sizeof (MonoInst));
5608 header = mono_method_get_header (method);
5609 locals = mono_mempool_alloc (acfg->mempool, sizeof (MonoInst*) * header->num_locals);
5610 for (i = 0; i < header->num_locals; ++i) {
5611 locals [i] = mono_mempool_alloc (acfg->mempool, sizeof (MonoInst));
5612 memcpy (locals [i], cfg->locals [i], sizeof (MonoInst));
5614 cfg->locals = locals;
5617 /* Free some fields used by cfg to conserve memory */
5618 mono_mempool_destroy (cfg->mempool);
5619 cfg->mempool = NULL;
5620 g_free (cfg->varinfo);
5621 cfg->varinfo = NULL;
5625 mono_regstate_free (cfg->rs);
5629 //printf ("Compile: %s\n", mono_method_full_name (method, TRUE));
5631 while (index >= acfg->cfgs_size) {
5632 MonoCompile **new_cfgs;
5635 new_size = acfg->cfgs_size * 2;
5636 new_cfgs = g_new0 (MonoCompile*, new_size);
5637 memcpy (new_cfgs, acfg->cfgs, sizeof (MonoCompile*) * acfg->cfgs_size);
5638 g_free (acfg->cfgs);
5639 acfg->cfgs = new_cfgs;
5640 acfg->cfgs_size = new_size;
5642 acfg->cfgs [index] = cfg;
5644 g_hash_table_insert (acfg->method_to_cfg, cfg->orig_method, cfg);
5647 if (cfg->orig_method->wrapper_type)
5648 g_ptr_array_add (acfg->extra_methods, cfg->orig_method);
5651 mono_acfg_unlock (acfg);
5653 InterlockedIncrement (&acfg->stats.ccount);
5657 compile_thread_main (gpointer *user_data)
5659 MonoDomain *domain = user_data [0];
5660 MonoAotCompile *acfg = user_data [1];
5661 GPtrArray *methods = user_data [2];
5664 mono_thread_attach (domain);
5666 for (i = 0; i < methods->len; ++i)
5667 compile_method (acfg, g_ptr_array_index (methods, i));
5671 load_profile_files (MonoAotCompile *acfg)
5675 int file_index, res, method_index, i;
5678 GList *unordered, *l;
5683 tmp = g_strdup_printf ("%s/.mono/aot-profile-data/%s-%d", g_get_home_dir (), acfg->image->assembly_name, file_index);
5685 if (!g_file_test (tmp, G_FILE_TEST_IS_REGULAR)) {
5690 infile = fopen (tmp, "r");
5693 printf ("Using profile data file '%s'\n", tmp);
5698 res = fscanf (infile, "%32s\n", ver);
5699 if ((res != 1) || strcmp (ver, "#VER:2") != 0) {
5700 printf ("Profile file has wrong version or invalid.\n");
5707 MonoMethodDesc *desc;
5710 if (fgets (name, 1023, infile) == NULL)
5713 /* Kill the newline */
5714 if (strlen (name) > 0)
5715 name [strlen (name) - 1] = '\0';
5717 desc = mono_method_desc_new (name, TRUE);
5719 method = mono_method_desc_search_in_image (desc, acfg->image);
5721 if (method && mono_method_get_token (method)) {
5722 token = mono_method_get_token (method);
5723 method_index = mono_metadata_token_index (token) - 1;
5726 for (i = 0; i < acfg->method_order->len; ++i) {
5727 if (g_ptr_array_index (acfg->method_order, i) == GUINT_TO_POINTER (method_index)) {
5733 g_ptr_array_add (acfg->method_order, GUINT_TO_POINTER (method_index));
5735 //printf ("No method found matching '%s'.\n", name);
5741 /* Add missing methods */
5743 for (method_index = 0; method_index < acfg->image->tables [MONO_TABLE_METHOD].rows; ++method_index) {
5745 for (i = 0; i < acfg->method_order->len; ++i) {
5746 if (g_ptr_array_index (acfg->method_order, i) == GUINT_TO_POINTER (method_index)) {
5752 unordered = g_list_prepend (unordered, GUINT_TO_POINTER (method_index));
5754 unordered = g_list_reverse (unordered);
5755 for (l = unordered; l; l = l->next)
5756 g_ptr_array_add (acfg->method_order, l->data);
5759 /* Used by the LLVM backend */
5761 mono_aot_get_got_offset (MonoJumpInfo *ji)
5763 return get_got_offset (llvm_acfg, ji);
5767 mono_aot_get_method_name (MonoCompile *cfg)
5769 if (llvm_acfg->aot_opts.static_link)
5770 /* Include the assembly name too to avoid duplicate symbol errors */
5771 return g_strdup_printf ("%s_%s", llvm_acfg->assembly_name_sym, get_debug_sym (cfg->orig_method, "", llvm_acfg->method_label_hash));
5773 return get_debug_sym (cfg->orig_method, "", llvm_acfg->method_label_hash);
5777 mono_aot_get_plt_symbol (MonoJumpInfoType type, gconstpointer data)
5779 MonoJumpInfo *ji = mono_mempool_alloc (llvm_acfg->mempool, sizeof (MonoJumpInfo));
5780 MonoPltEntry *plt_entry;
5783 ji->data.target = data;
5785 if (!can_encode_patch (llvm_acfg, ji))
5788 plt_entry = get_plt_entry (llvm_acfg, ji);
5789 plt_entry->llvm_used = TRUE;
5791 #if defined(__APPLE__)
5792 return g_strdup_printf (plt_entry->llvm_symbol + strlen (llvm_acfg->llvm_label_prefix));
5794 return g_strdup_printf (plt_entry->llvm_symbol);
5799 mono_aot_patch_info_dup (MonoJumpInfo* ji)
5803 mono_acfg_lock (llvm_acfg);
5804 res = mono_patch_info_dup_mp (llvm_acfg->mempool, ji);
5805 mono_acfg_unlock (llvm_acfg);
5815 * Emit the LLVM code into an LLVM bytecode file, and compile it using the LLVM
5819 emit_llvm_file (MonoAotCompile *acfg)
5821 char *command, *opts;
5823 MonoJumpInfo *patch_info;
5826 * When using LLVM, we let llvm emit the got since the LLVM IL needs to refer
5830 /* Compute the final size of the got */
5831 for (i = 0; i < acfg->nmethods; ++i) {
5832 if (acfg->cfgs [i]) {
5833 for (patch_info = acfg->cfgs [i]->patch_info; patch_info; patch_info = patch_info->next) {
5834 if (patch_info->type != MONO_PATCH_INFO_NONE) {
5835 if (!is_plt_patch (patch_info))
5836 get_got_offset (acfg, patch_info);
5838 get_plt_entry (acfg, patch_info);
5844 acfg->final_got_size = acfg->got_offset + acfg->plt_offset;
5846 if (acfg->aot_opts.full_aot) {
5850 * Need to add the got entries used by the trampolines.
5851 * This is only a conservative approximation.
5853 if (strcmp (acfg->image->assembly->aname.name, "mscorlib") == 0) {
5854 /* For the generic + rgctx trampolines */
5855 acfg->final_got_size += 200;
5856 /* For the specific trampolines */
5857 for (ntype = 0; ntype < MONO_AOT_TRAMP_NUM; ++ntype)
5858 acfg->final_got_size += acfg->num_trampolines [ntype] * 2;
5863 mono_llvm_emit_aot_module ("temp.bc", acfg->final_got_size);
5866 * FIXME: Experiment with adding optimizations, the -std-compile-opts set takes
5867 * a lot of time, and doesn't seem to save much space.
5868 * The following optimizations cannot be enabled:
5870 * - 'jump-threading' changes our blockaddress references to int constants.
5871 * - 'basiccg' fails because it contains:
5872 * if (CS && !isa<IntrinsicInst>(II)) {
5873 * and isa<IntrinsicInst> is false for invokes to intrinsics (iltests.exe).
5874 * - 'prune-eh' and 'functionattrs' depend on 'basiccg'.
5875 * The opt list below was produced by taking the output of:
5876 * llvm-as < /dev/null | opt -O2 -disable-output -debug-pass=Arguments
5877 * then removing tailcallelim + the global opts, and adding a second gvn.
5879 opts = g_strdup ("-instcombine -simplifycfg");
5880 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");
5882 command = g_strdup_printf ("%sopt -f %s -o temp.opt.bc temp.bc", acfg->aot_opts.llvm_path, opts);
5883 printf ("Executing opt: %s\n", command);
5884 if (system (command) != 0) {
5890 if (!acfg->llc_args)
5891 acfg->llc_args = g_string_new ("");
5893 /* Verbose asm slows down llc greatly */
5894 g_string_append (acfg->llc_args, " -asm-verbose=false");
5896 if (acfg->aot_opts.mtriple)
5897 g_string_append_printf (acfg->llc_args, " -mtriple=%s", acfg->aot_opts.mtriple);
5899 if (llvm_acfg->aot_opts.static_link)
5900 g_string_append_printf (acfg->llc_args, " -relocation-model=static");
5902 g_string_append_printf (acfg->llc_args, " -relocation-model=pic");
5903 unlink (acfg->tmpfname);
5905 command = g_strdup_printf ("%sllc %s -disable-gnu-eh-frame -enable-mono-eh-frame -o %s temp.opt.bc", acfg->aot_opts.llvm_path, acfg->llc_args->str, acfg->tmpfname);
5907 printf ("Executing llc: %s\n", command);
5909 if (system (command) != 0) {
5916 emit_code (MonoAotCompile *acfg)
5918 int oindex, i, prev_index;
5920 char end_symbol [256];
5922 #if defined(TARGET_POWERPC64)
5923 sprintf (symbol, ".Lgot_addr");
5924 emit_section_change (acfg, ".text", 0);
5925 emit_alignment (acfg, 8);
5926 emit_label (acfg, symbol);
5927 emit_pointer (acfg, acfg->got_symbol);
5931 * This global symbol is used to compute the address of each method using the
5932 * code_offsets array. It is also used to compute the memory ranges occupied by
5933 * AOT code, so it must be equal to the address of the first emitted method.
5935 sprintf (symbol, "methods");
5936 emit_section_change (acfg, ".text", 0);
5937 emit_alignment (acfg, 8);
5939 for (i = 0; i < acfg->nmethods; ++i) {
5940 if (acfg->cfgs [i] && acfg->cfgs [i]->compile_llvm) {
5941 fprintf (acfg->fp, "\n.set methods, %s\n", acfg->cfgs [i]->asm_symbol);
5945 if (i == acfg->nmethods)
5946 /* No LLVM compiled methods */
5947 emit_label (acfg, symbol);
5949 emit_label (acfg, symbol);
5953 * Emit some padding so the local symbol for the first method doesn't have the
5954 * same address as 'methods'.
5956 #if defined(__default_codegen__)
5957 emit_zero_bytes (acfg, 16);
5958 #elif defined(__native_client_codegen__)
5960 const int kPaddingSize = 16;
5961 guint8 pad_buffer[kPaddingSize];
5962 mono_arch_nacl_pad (pad_buffer, kPaddingSize);
5963 emit_bytes (acfg, pad_buffer, kPaddingSize);
5967 for (oindex = 0; oindex < acfg->method_order->len; ++oindex) {
5971 i = GPOINTER_TO_UINT (g_ptr_array_index (acfg->method_order, oindex));
5973 cfg = acfg->cfgs [i];
5978 method = cfg->orig_method;
5980 /* Emit unbox trampoline */
5981 if (acfg->aot_opts.full_aot && cfg->orig_method->klass->valuetype && (method->flags & METHOD_ATTRIBUTE_VIRTUAL)) {
5982 sprintf (symbol, "ut_%d", get_method_index (acfg, method));
5984 emit_section_change (acfg, ".text", 0);
5985 #ifdef __native_client_codegen__
5986 emit_alignment (acfg, AOT_FUNC_ALIGNMENT);
5989 if (acfg->thumb_mixed && cfg->compile_llvm)
5990 fprintf (acfg->fp, "\n.thumb_func\n");
5992 emit_label (acfg, symbol);
5994 arch_emit_unbox_trampoline (acfg, cfg, cfg->orig_method, cfg->asm_symbol);
5997 if (cfg->compile_llvm)
5998 acfg->stats.llvm_count ++;
6000 emit_method_code (acfg, cfg);
6003 sprintf (symbol, "methods_end");
6004 emit_section_change (acfg, ".text", 0);
6005 emit_alignment (acfg, 8);
6006 emit_label (acfg, symbol);
6009 * Add .no_dead_strip directives for all LLVM methods to prevent the OSX linker
6010 * from optimizing them away, since it doesn't see that code_offsets references them.
6011 * JITted methods don't need this since they are referenced using assembler local
6013 * FIXME: This is why write-symbols doesn't work on OSX ?
6015 if (acfg->llvm && acfg->need_no_dead_strip) {
6016 fprintf (acfg->fp, "\n");
6017 for (i = 0; i < acfg->nmethods; ++i) {
6018 if (acfg->cfgs [i] && acfg->cfgs [i]->compile_llvm)
6019 fprintf (acfg->fp, ".no_dead_strip %s\n", acfg->cfgs [i]->asm_symbol);
6023 sprintf (symbol, "code_offsets");
6024 emit_section_change (acfg, RODATA_SECT, 1);
6025 emit_alignment (acfg, 8);
6026 emit_label (acfg, symbol);
6028 acfg->stats.offsets_size += acfg->nmethods * 4;
6030 sprintf (end_symbol, "methods");
6031 for (i = 0; i < acfg->nmethods; ++i) {
6032 if (acfg->cfgs [i]) {
6033 emit_symbol_diff (acfg, acfg->cfgs [i]->asm_symbol, end_symbol, 0);
6035 emit_int32 (acfg, 0xffffffff);
6040 /* Emit a sorted table mapping methods to their unbox trampolines */
6041 sprintf (symbol, "unbox_trampolines");
6042 emit_section_change (acfg, RODATA_SECT, 1);
6043 emit_alignment (acfg, 8);
6044 emit_label (acfg, symbol);
6046 sprintf (end_symbol, "methods");
6048 for (i = 0; i < acfg->nmethods; ++i) {
6053 cfg = acfg->cfgs [i];
6057 method = cfg->orig_method;
6059 if (acfg->aot_opts.full_aot && cfg->orig_method->klass->valuetype && (method->flags & METHOD_ATTRIBUTE_VIRTUAL)) {
6060 index = get_method_index (acfg, method);
6061 sprintf (symbol, "ut_%d", index);
6063 emit_int32 (acfg, index);
6064 emit_symbol_diff (acfg, symbol, end_symbol, 0);
6065 /* Make sure the table is sorted by index */
6066 g_assert (index > prev_index);
6070 sprintf (symbol, "unbox_trampolines_end");
6071 emit_label (acfg, symbol);
6075 emit_info (MonoAotCompile *acfg)
6081 offsets = g_new0 (gint32, acfg->nmethods);
6083 for (oindex = 0; oindex < acfg->method_order->len; ++oindex) {
6084 i = GPOINTER_TO_UINT (g_ptr_array_index (acfg->method_order, oindex));
6086 if (acfg->cfgs [i]) {
6087 emit_method_info (acfg, acfg->cfgs [i]);
6088 offsets [i] = acfg->cfgs [i]->method_info_offset;
6094 sprintf (symbol, "method_info_offsets");
6095 emit_section_change (acfg, RODATA_SECT, 1);
6096 emit_alignment (acfg, 8);
6097 emit_label (acfg, symbol);
6099 acfg->stats.offsets_size += emit_offset_table (acfg, acfg->nmethods, 10, offsets);
6104 #endif /* #if !defined(DISABLE_AOT) && !defined(DISABLE_JIT) */
6106 #define rot(x,k) (((x)<<(k)) | ((x)>>(32-(k))))
6107 #define mix(a,b,c) { \
6108 a -= c; a ^= rot(c, 4); c += b; \
6109 b -= a; b ^= rot(a, 6); a += c; \
6110 c -= b; c ^= rot(b, 8); b += a; \
6111 a -= c; a ^= rot(c,16); c += b; \
6112 b -= a; b ^= rot(a,19); a += c; \
6113 c -= b; c ^= rot(b, 4); b += a; \
6115 #define final(a,b,c) { \
6116 c ^= b; c -= rot(b,14); \
6117 a ^= c; a -= rot(c,11); \
6118 b ^= a; b -= rot(a,25); \
6119 c ^= b; c -= rot(b,16); \
6120 a ^= c; a -= rot(c,4); \
6121 b ^= a; b -= rot(a,14); \
6122 c ^= b; c -= rot(b,24); \
6126 mono_aot_type_hash (MonoType *t1)
6128 guint hash = t1->type;
6130 hash |= t1->byref << 6; /* do not collide with t1->type values */
6132 case MONO_TYPE_VALUETYPE:
6133 case MONO_TYPE_CLASS:
6134 case MONO_TYPE_SZARRAY:
6135 /* check if the distribution is good enough */
6136 return ((hash << 5) - hash) ^ mono_metadata_str_hash (t1->data.klass->name);
6138 return ((hash << 5) - hash) ^ mono_metadata_type_hash (t1->data.type);
6139 case MONO_TYPE_ARRAY:
6140 return ((hash << 5) - hash) ^ mono_metadata_type_hash (&t1->data.array->eklass->byval_arg);
6141 case MONO_TYPE_GENERICINST:
6142 return ((hash << 5) - hash) ^ 0;
6149 * mono_aot_method_hash:
6151 * Return a hash code for methods which only depends on metadata.
6154 mono_aot_method_hash (MonoMethod *method)
6156 MonoMethodSignature *sig;
6160 guint32 *hashes_start, *hashes;
6162 MonoGenericInst *ginst = NULL;
6164 /* Similar to the hash in mono_method_get_imt_slot () */
6166 sig = mono_method_signature (method);
6168 if (method->is_inflated)
6169 ginst = ((MonoMethodInflated*)method)->context.method_inst;
6171 hashes_count = sig->param_count + 5 + (ginst ? ginst->type_argc : 0);
6172 hashes_start = g_malloc0 (hashes_count * sizeof (guint32));
6173 hashes = hashes_start;
6175 /* Some wrappers are assigned to random classes */
6176 if (!method->wrapper_type || method->wrapper_type == MONO_WRAPPER_REMOTING_INVOKE_WITH_CHECK)
6177 klass = method->klass;
6179 klass = mono_defaults.object_class;
6181 if (!method->wrapper_type) {
6182 char *full_name = mono_type_full_name (&klass->byval_arg);
6184 hashes [0] = mono_metadata_str_hash (full_name);
6188 hashes [0] = mono_metadata_str_hash (klass->name);
6189 hashes [1] = mono_metadata_str_hash (klass->name_space);
6191 if (method->wrapper_type == MONO_WRAPPER_STFLD || method->wrapper_type == MONO_WRAPPER_LDFLD || method->wrapper_type == MONO_WRAPPER_LDFLDA)
6192 /* The method name includes a stringified pointer */
6195 hashes [2] = mono_metadata_str_hash (method->name);
6196 hashes [3] = method->wrapper_type;
6197 hashes [4] = mono_aot_type_hash (sig->ret);
6199 for (i = 0; i < sig->param_count; i++) {
6200 hashes [hindex ++] = mono_aot_type_hash (sig->params [i]);
6203 for (i = 0; i < ginst->type_argc; ++i)
6204 hashes [hindex ++] = mono_aot_type_hash (ginst->type_argv [i]);
6206 g_assert (hindex == hashes_count);
6208 /* Setup internal state */
6209 a = b = c = 0xdeadbeef + (((guint32)hashes_count)<<2);
6211 /* Handle most of the hashes */
6212 while (hashes_count > 3) {
6221 /* Handle the last 3 hashes (all the case statements fall through) */
6222 switch (hashes_count) {
6223 case 3 : c += hashes [2];
6224 case 2 : b += hashes [1];
6225 case 1 : a += hashes [0];
6227 case 0: /* nothing left to add */
6231 free (hashes_start);
6240 * mono_aot_wrapper_name:
6242 * Return a string which uniqely identifies the given wrapper method.
6245 mono_aot_wrapper_name (MonoMethod *method)
6247 char *name, *tmpsig, *klass_desc;
6249 tmpsig = mono_signature_get_desc (mono_method_signature (method), TRUE);
6251 switch (method->wrapper_type) {
6252 case MONO_WRAPPER_RUNTIME_INVOKE:
6253 if (!strcmp (method->name, "runtime_invoke_dynamic"))
6254 name = g_strdup_printf ("(wrapper runtime-invoke-dynamic)");
6256 name = g_strdup_printf ("%s (%s)", method->name, tmpsig);
6259 klass_desc = mono_type_full_name (&method->klass->byval_arg);
6260 name = g_strdup_printf ("%s:%s (%s)", klass_desc, method->name, tmpsig);
6261 g_free (klass_desc);
6271 * mono_aot_get_array_helper_from_wrapper;
6273 * Get the helper method in Array called by an array wrapper method.
6276 mono_aot_get_array_helper_from_wrapper (MonoMethod *method)
6280 MonoGenericContext ctx;
6281 MonoType *args [16];
6282 char *mname, *iname, *s, *s2, *helper_name = NULL;
6284 prefix = "System.Collections.Generic";
6285 s = g_strdup_printf ("%s", method->name + strlen (prefix) + 1);
6286 s2 = strstr (s, "`1.");
6292 //printf ("X: %s %s\n", iname, mname);
6294 if (!strcmp (iname, "IList"))
6295 helper_name = g_strdup_printf ("InternalArray__%s", mname);
6297 helper_name = g_strdup_printf ("InternalArray__%s_%s", iname, mname);
6298 m = mono_class_get_method_from_name (mono_defaults.array_class, helper_name, mono_method_signature (method)->param_count);
6300 g_free (helper_name);
6303 if (m->is_generic) {
6304 memset (&ctx, 0, sizeof (ctx));
6305 args [0] = &method->klass->element_class->byval_arg;
6306 ctx.method_inst = mono_metadata_get_generic_inst (1, args);
6307 m = mono_class_inflate_generic_method (m, &ctx);
6313 #if !defined(DISABLE_AOT) && !defined(DISABLE_JIT)
6315 typedef struct HashEntry {
6316 guint32 key, value, index;
6317 struct HashEntry *next;
6321 * emit_extra_methods:
6323 * Emit methods which are not in the METHOD table, like wrappers.
6326 emit_extra_methods (MonoAotCompile *acfg)
6328 int i, table_size, buf_size;
6331 guint32 *info_offsets;
6334 HashEntry *entry, *new_entry;
6335 int nmethods, max_chain_length;
6338 info_offsets = g_new0 (guint32, acfg->extra_methods->len);
6340 /* Emit method info */
6342 for (i = 0; i < acfg->extra_methods->len; ++i) {
6343 MonoMethod *method = g_ptr_array_index (acfg->extra_methods, i);
6344 MonoCompile *cfg = g_hash_table_lookup (acfg->method_to_cfg, method);
6350 p = buf = g_malloc (buf_size);
6354 method = cfg->method_to_register;
6356 encode_method_ref (acfg, method, p, &p);
6358 g_assert ((p - buf) < buf_size);
6360 info_offsets [i] = add_to_blob (acfg, buf, p - buf);
6365 * Construct a chained hash table for mapping indexes in extra_method_info to
6368 table_size = g_spaced_primes_closest ((int)(nmethods * 1.5));
6369 table = g_ptr_array_sized_new (table_size);
6370 for (i = 0; i < table_size; ++i)
6371 g_ptr_array_add (table, NULL);
6372 chain_lengths = g_new0 (int, table_size);
6373 max_chain_length = 0;
6374 for (i = 0; i < acfg->extra_methods->len; ++i) {
6375 MonoMethod *method = g_ptr_array_index (acfg->extra_methods, i);
6376 MonoCompile *cfg = g_hash_table_lookup (acfg->method_to_cfg, method);
6382 key = info_offsets [i];
6383 value = get_method_index (acfg, method);
6385 hash = mono_aot_method_hash (method) % table_size;
6387 chain_lengths [hash] ++;
6388 max_chain_length = MAX (max_chain_length, chain_lengths [hash]);
6390 new_entry = mono_mempool_alloc0 (acfg->mempool, sizeof (HashEntry));
6391 new_entry->key = key;
6392 new_entry->value = value;
6394 entry = g_ptr_array_index (table, hash);
6395 if (entry == NULL) {
6396 new_entry->index = hash;
6397 g_ptr_array_index (table, hash) = new_entry;
6400 entry = entry->next;
6402 entry->next = new_entry;
6403 new_entry->index = table->len;
6404 g_ptr_array_add (table, new_entry);
6408 //printf ("MAX: %d\n", max_chain_length);
6410 /* Emit the table */
6411 sprintf (symbol, "extra_method_table");
6412 emit_section_change (acfg, RODATA_SECT, 0);
6413 emit_alignment (acfg, 8);
6414 emit_label (acfg, symbol);
6416 emit_int32 (acfg, table_size);
6417 for (i = 0; i < table->len; ++i) {
6418 HashEntry *entry = g_ptr_array_index (table, i);
6420 if (entry == NULL) {
6421 emit_int32 (acfg, 0);
6422 emit_int32 (acfg, 0);
6423 emit_int32 (acfg, 0);
6425 //g_assert (entry->key > 0);
6426 emit_int32 (acfg, entry->key);
6427 emit_int32 (acfg, entry->value);
6429 emit_int32 (acfg, entry->next->index);
6431 emit_int32 (acfg, 0);
6436 * Emit a table reverse mapping method indexes to their index in extra_method_info.
6437 * This is used by mono_aot_find_jit_info ().
6439 sprintf (symbol, "extra_method_info_offsets");
6440 emit_section_change (acfg, RODATA_SECT, 0);
6441 emit_alignment (acfg, 8);
6442 emit_label (acfg, symbol);
6444 emit_int32 (acfg, acfg->extra_methods->len);
6445 for (i = 0; i < acfg->extra_methods->len; ++i) {
6446 MonoMethod *method = g_ptr_array_index (acfg->extra_methods, i);
6448 emit_int32 (acfg, get_method_index (acfg, method));
6449 emit_int32 (acfg, info_offsets [i]);
6454 emit_exception_info (MonoAotCompile *acfg)
6460 offsets = g_new0 (gint32, acfg->nmethods);
6461 for (i = 0; i < acfg->nmethods; ++i) {
6462 if (acfg->cfgs [i]) {
6463 emit_exception_debug_info (acfg, acfg->cfgs [i]);
6464 offsets [i] = acfg->cfgs [i]->ex_info_offset;
6470 sprintf (symbol, "ex_info_offsets");
6471 emit_section_change (acfg, RODATA_SECT, 1);
6472 emit_alignment (acfg, 8);
6473 emit_label (acfg, symbol);
6475 acfg->stats.offsets_size += emit_offset_table (acfg, acfg->nmethods, 10, offsets);
6480 emit_unwind_info (MonoAotCompile *acfg)
6486 * The unwind info contains a lot of duplicates so we emit each unique
6487 * entry once, and only store the offset from the start of the table in the
6491 sprintf (symbol, "unwind_info");
6492 emit_section_change (acfg, RODATA_SECT, 1);
6493 emit_alignment (acfg, 8);
6494 emit_label (acfg, symbol);
6496 for (i = 0; i < acfg->unwind_ops->len; ++i) {
6497 guint32 index = GPOINTER_TO_UINT (g_ptr_array_index (acfg->unwind_ops, i));
6498 guint8 *unwind_info;
6499 guint32 unwind_info_len;
6503 unwind_info = mono_get_cached_unwind_info (index, &unwind_info_len);
6506 encode_value (unwind_info_len, p, &p);
6507 emit_bytes (acfg, buf, p - buf);
6508 emit_bytes (acfg, unwind_info, unwind_info_len);
6510 acfg->stats.unwind_info_size += (p - buf) + unwind_info_len;
6515 emit_class_info (MonoAotCompile *acfg)
6521 offsets = g_new0 (gint32, acfg->image->tables [MONO_TABLE_TYPEDEF].rows);
6522 for (i = 0; i < acfg->image->tables [MONO_TABLE_TYPEDEF].rows; ++i)
6523 offsets [i] = emit_klass_info (acfg, MONO_TOKEN_TYPE_DEF | (i + 1));
6525 sprintf (symbol, "class_info_offsets");
6526 emit_section_change (acfg, RODATA_SECT, 1);
6527 emit_alignment (acfg, 8);
6528 emit_label (acfg, symbol);
6530 acfg->stats.offsets_size += emit_offset_table (acfg, acfg->image->tables [MONO_TABLE_TYPEDEF].rows, 10, offsets);
6534 typedef struct ClassNameTableEntry {
6535 guint32 token, index;
6536 struct ClassNameTableEntry *next;
6537 } ClassNameTableEntry;
6540 emit_class_name_table (MonoAotCompile *acfg)
6543 guint32 token, hash;
6548 ClassNameTableEntry *entry, *new_entry;
6551 * Construct a chained hash table for mapping class names to typedef tokens.
6553 table_size = g_spaced_primes_closest ((int)(acfg->image->tables [MONO_TABLE_TYPEDEF].rows * 1.5));
6554 table = g_ptr_array_sized_new (table_size);
6555 for (i = 0; i < table_size; ++i)
6556 g_ptr_array_add (table, NULL);
6557 for (i = 0; i < acfg->image->tables [MONO_TABLE_TYPEDEF].rows; ++i) {
6558 token = MONO_TOKEN_TYPE_DEF | (i + 1);
6559 klass = mono_class_get (acfg->image, token);
6561 mono_loader_clear_error ();
6564 full_name = mono_type_get_name_full (mono_class_get_type (klass), MONO_TYPE_NAME_FORMAT_FULL_NAME);
6565 hash = mono_metadata_str_hash (full_name) % table_size;
6568 /* FIXME: Allocate from the mempool */
6569 new_entry = g_new0 (ClassNameTableEntry, 1);
6570 new_entry->token = token;
6572 entry = g_ptr_array_index (table, hash);
6573 if (entry == NULL) {
6574 new_entry->index = hash;
6575 g_ptr_array_index (table, hash) = new_entry;
6578 entry = entry->next;
6580 entry->next = new_entry;
6581 new_entry->index = table->len;
6582 g_ptr_array_add (table, new_entry);
6586 /* Emit the table */
6587 sprintf (symbol, "class_name_table");
6588 emit_section_change (acfg, RODATA_SECT, 0);
6589 emit_alignment (acfg, 8);
6590 emit_label (acfg, symbol);
6592 /* FIXME: Optimize memory usage */
6593 g_assert (table_size < 65000);
6594 emit_int16 (acfg, table_size);
6595 g_assert (table->len < 65000);
6596 for (i = 0; i < table->len; ++i) {
6597 ClassNameTableEntry *entry = g_ptr_array_index (table, i);
6599 if (entry == NULL) {
6600 emit_int16 (acfg, 0);
6601 emit_int16 (acfg, 0);
6603 emit_int16 (acfg, mono_metadata_token_index (entry->token));
6605 emit_int16 (acfg, entry->next->index);
6607 emit_int16 (acfg, 0);
6613 emit_image_table (MonoAotCompile *acfg)
6619 * The image table is small but referenced in a lot of places.
6620 * So we emit it at once, and reference its elements by an index.
6623 sprintf (symbol, "image_table");
6624 emit_section_change (acfg, RODATA_SECT, 1);
6625 emit_alignment (acfg, 8);
6626 emit_label (acfg, symbol);
6628 emit_int32 (acfg, acfg->image_table->len);
6629 for (i = 0; i < acfg->image_table->len; i++) {
6630 MonoImage *image = (MonoImage*)g_ptr_array_index (acfg->image_table, i);
6631 MonoAssemblyName *aname = &image->assembly->aname;
6633 /* FIXME: Support multi-module assemblies */
6634 g_assert (image->assembly->image == image);
6636 emit_string (acfg, image->assembly_name);
6637 emit_string (acfg, image->guid);
6638 emit_string (acfg, aname->culture ? aname->culture : "");
6639 emit_string (acfg, (const char*)aname->public_key_token);
6641 emit_alignment (acfg, 8);
6642 emit_int32 (acfg, aname->flags);
6643 emit_int32 (acfg, aname->major);
6644 emit_int32 (acfg, aname->minor);
6645 emit_int32 (acfg, aname->build);
6646 emit_int32 (acfg, aname->revision);
6651 emit_got_info (MonoAotCompile *acfg)
6654 int i, first_plt_got_patch, buf_size;
6656 guint32 *got_info_offsets;
6658 /* Add the patches needed by the PLT to the GOT */
6659 acfg->plt_got_offset_base = acfg->got_offset;
6660 first_plt_got_patch = acfg->got_patches->len;
6661 for (i = 1; i < acfg->plt_offset; ++i) {
6662 MonoPltEntry *plt_entry = g_hash_table_lookup (acfg->plt_offset_to_entry, GUINT_TO_POINTER (i));
6664 g_ptr_array_add (acfg->got_patches, plt_entry->ji);
6666 acfg->stats.got_slot_types [plt_entry->ji->type] ++;
6669 acfg->got_offset += acfg->plt_offset;
6673 * - optimize offsets table.
6674 * - reduce number of exported symbols.
6675 * - emit info for a klass only once.
6676 * - determine when a method uses a GOT slot which is guaranteed to be already
6678 * - clean up and document the code.
6679 * - use String.Empty in class libs.
6682 /* Encode info required to decode shared GOT entries */
6683 buf_size = acfg->got_patches->len * 128;
6684 p = buf = mono_mempool_alloc (acfg->mempool, buf_size);
6685 got_info_offsets = mono_mempool_alloc (acfg->mempool, acfg->got_patches->len * sizeof (guint32));
6686 acfg->plt_got_info_offsets = mono_mempool_alloc (acfg->mempool, acfg->plt_offset * sizeof (guint32));
6688 if (acfg->plt_offset)
6689 acfg->plt_got_info_offsets [0] = 0;
6690 for (i = 0; i < acfg->got_patches->len; ++i) {
6691 MonoJumpInfo *ji = g_ptr_array_index (acfg->got_patches, i);
6696 encode_value (ji->type, p, &p);
6698 encode_patch (acfg, ji, p, &p);
6699 acfg->stats.got_slot_info_sizes [ji->type] += p - p2;
6700 g_assert (p - buf <= buf_size);
6701 got_info_offsets [i] = add_to_blob (acfg, buf, p - buf);
6703 if (i >= first_plt_got_patch)
6704 acfg->plt_got_info_offsets [i - first_plt_got_patch + 1] = got_info_offsets [i];
6705 acfg->stats.got_info_size += p - buf;
6708 /* Emit got_info_offsets table */
6709 sprintf (symbol, "got_info_offsets");
6710 emit_section_change (acfg, RODATA_SECT, 1);
6711 emit_alignment (acfg, 8);
6712 emit_label (acfg, symbol);
6714 /* No need to emit offsets for the got plt entries, the plt embeds them directly */
6715 acfg->stats.offsets_size += emit_offset_table (acfg, first_plt_got_patch, 10, (gint32*)got_info_offsets);
6719 emit_got (MonoAotCompile *acfg)
6724 /* Don't make GOT global so accesses to it don't need relocations */
6725 sprintf (symbol, "%s", acfg->got_symbol);
6726 emit_section_change (acfg, ".bss", 0);
6727 emit_alignment (acfg, 8);
6728 emit_local_symbol (acfg, symbol, "got_end", FALSE);
6729 emit_label (acfg, symbol);
6730 if (acfg->got_offset > 0)
6731 emit_zero_bytes (acfg, (int)(acfg->got_offset * sizeof (gpointer)));
6733 sprintf (symbol, "got_end");
6734 emit_label (acfg, symbol);
6738 typedef struct GlobalsTableEntry {
6739 guint32 value, index;
6740 struct GlobalsTableEntry *next;
6741 } GlobalsTableEntry;
6744 emit_globals (MonoAotCompile *acfg)
6750 GlobalsTableEntry *entry, *new_entry;
6752 if (!acfg->aot_opts.static_link)
6756 * When static linking, we emit a table containing our globals.
6760 * Construct a chained hash table for mapping global names to their index in
6761 * the globals table.
6763 table_size = g_spaced_primes_closest ((int)(acfg->globals->len * 1.5));
6764 table = g_ptr_array_sized_new (table_size);
6765 for (i = 0; i < table_size; ++i)
6766 g_ptr_array_add (table, NULL);
6767 for (i = 0; i < acfg->globals->len; ++i) {
6768 char *name = g_ptr_array_index (acfg->globals, i);
6770 hash = mono_metadata_str_hash (name) % table_size;
6772 /* FIXME: Allocate from the mempool */
6773 new_entry = g_new0 (GlobalsTableEntry, 1);
6774 new_entry->value = i;
6776 entry = g_ptr_array_index (table, hash);
6777 if (entry == NULL) {
6778 new_entry->index = hash;
6779 g_ptr_array_index (table, hash) = new_entry;
6782 entry = entry->next;
6784 entry->next = new_entry;
6785 new_entry->index = table->len;
6786 g_ptr_array_add (table, new_entry);
6790 /* Emit the table */
6791 sprintf (symbol, ".Lglobals_hash");
6792 emit_section_change (acfg, RODATA_SECT, 0);
6793 emit_alignment (acfg, 8);
6794 emit_label (acfg, symbol);
6796 /* FIXME: Optimize memory usage */
6797 g_assert (table_size < 65000);
6798 emit_int16 (acfg, table_size);
6799 for (i = 0; i < table->len; ++i) {
6800 GlobalsTableEntry *entry = g_ptr_array_index (table, i);
6802 if (entry == NULL) {
6803 emit_int16 (acfg, 0);
6804 emit_int16 (acfg, 0);
6806 emit_int16 (acfg, entry->value + 1);
6808 emit_int16 (acfg, entry->next->index);
6810 emit_int16 (acfg, 0);
6814 /* Emit the names */
6815 for (i = 0; i < acfg->globals->len; ++i) {
6816 char *name = g_ptr_array_index (acfg->globals, i);
6818 sprintf (symbol, "name_%d", i);
6819 emit_section_change (acfg, RODATA_SECT, 1);
6821 emit_alignment (acfg, 4);
6823 emit_label (acfg, symbol);
6824 emit_string (acfg, name);
6827 /* Emit the globals table */
6828 sprintf (symbol, "globals");
6829 emit_section_change (acfg, ".data", 0);
6830 /* This is not a global, since it is accessed by the init function */
6831 emit_alignment (acfg, 8);
6832 emit_label (acfg, symbol);
6834 sprintf (symbol, "%sglobals_hash", acfg->temp_prefix);
6835 emit_pointer (acfg, symbol);
6837 for (i = 0; i < acfg->globals->len; ++i) {
6838 char *name = g_ptr_array_index (acfg->globals, i);
6840 sprintf (symbol, "name_%d", i);
6841 emit_pointer (acfg, symbol);
6843 sprintf (symbol, "%s", name);
6844 emit_pointer (acfg, symbol);
6846 /* Null terminate the table */
6847 emit_int32 (acfg, 0);
6848 emit_int32 (acfg, 0);
6852 emit_autoreg (MonoAotCompile *acfg)
6857 * Emit a function into the .ctor section which will be called by the ELF
6858 * loader to register this module with the runtime.
6860 if (! (!acfg->use_bin_writer && acfg->aot_opts.static_link && acfg->aot_opts.autoreg))
6863 symbol = g_strdup_printf ("_%s_autoreg", acfg->static_linking_symbol);
6865 arch_emit_autoreg (acfg, symbol);
6871 emit_mem_end (MonoAotCompile *acfg)
6875 sprintf (symbol, "mem_end");
6876 emit_section_change (acfg, ".text", 1);
6877 emit_alignment (acfg, 8);
6878 emit_label (acfg, symbol);
6882 * Emit a structure containing all the information not stored elsewhere.
6885 emit_file_info (MonoAotCompile *acfg)
6890 const char *gc_name;
6893 emit_string_symbol (acfg, "assembly_guid" , acfg->image->guid);
6895 if (acfg->aot_opts.bind_to_runtime_version) {
6896 build_info = mono_get_runtime_build_info ();
6897 emit_string_symbol (acfg, "runtime_version", build_info);
6898 g_free (build_info);
6900 emit_string_symbol (acfg, "runtime_version", "");
6903 /* Emit a string holding the assembly name */
6904 emit_string_symbol (acfg, "assembly_name", acfg->image->assembly->aname.name);
6907 * The managed allocators are GC specific, so can't use an AOT image created by one GC
6910 gc_name = mono_gc_get_gc_name ();
6911 gc_name_offset = add_to_blob (acfg, (guint8*)gc_name, strlen (gc_name) + 1);
6913 sprintf (symbol, "mono_aot_file_info");
6914 emit_section_change (acfg, ".data", 0);
6915 emit_alignment (acfg, 8);
6916 emit_label (acfg, symbol);
6917 if (!acfg->aot_opts.static_link)
6918 emit_global (acfg, symbol, FALSE);
6920 /* The data emitted here must match MonoAotFileInfo. */
6922 emit_int32 (acfg, MONO_AOT_FILE_VERSION);
6923 emit_int32 (acfg, 0);
6926 * We emit pointers to our data structures instead of emitting global symbols which
6927 * point to them, to reduce the number of globals, and because using globals leads to
6928 * various problems (i.e. arm/thumb).
6930 emit_pointer (acfg, acfg->got_symbol);
6931 emit_pointer (acfg, "methods");
6934 * Emit a reference to the mono_eh_frame table created by our modified LLVM compiler.
6936 emit_pointer (acfg, "mono_eh_frame");
6938 emit_pointer (acfg, NULL);
6940 emit_pointer (acfg, "blob");
6941 emit_pointer (acfg, "class_name_table");
6942 emit_pointer (acfg, "class_info_offsets");
6943 emit_pointer (acfg, "method_info_offsets");
6944 emit_pointer (acfg, "ex_info_offsets");
6945 emit_pointer (acfg, "code_offsets");
6946 emit_pointer (acfg, "extra_method_info_offsets");
6947 emit_pointer (acfg, "extra_method_table");
6948 emit_pointer (acfg, "got_info_offsets");
6949 emit_pointer (acfg, "methods_end");
6950 emit_pointer (acfg, "unwind_info");
6951 emit_pointer (acfg, "mem_end");
6952 emit_pointer (acfg, "image_table");
6953 emit_pointer (acfg, "plt");
6954 emit_pointer (acfg, "plt_end");
6955 emit_pointer (acfg, "assembly_guid");
6956 emit_pointer (acfg, "runtime_version");
6957 if (acfg->num_trampoline_got_entries) {
6958 emit_pointer (acfg, "specific_trampolines");
6959 emit_pointer (acfg, "static_rgctx_trampolines");
6960 emit_pointer (acfg, "imt_thunks");
6962 emit_pointer (acfg, NULL);
6963 emit_pointer (acfg, NULL);
6964 emit_pointer (acfg, NULL);
6966 if (acfg->thumb_mixed) {
6967 emit_pointer (acfg, "thumb_end");
6969 emit_pointer (acfg, NULL);
6971 if (acfg->aot_opts.static_link) {
6972 emit_pointer (acfg, "globals");
6974 emit_pointer (acfg, NULL);
6976 emit_pointer (acfg, "assembly_name");
6977 emit_pointer (acfg, "unbox_trampolines");
6978 emit_pointer (acfg, "unbox_trampolines_end");
6980 emit_int32 (acfg, acfg->plt_got_offset_base);
6981 emit_int32 (acfg, (int)(acfg->got_offset * sizeof (gpointer)));
6982 emit_int32 (acfg, acfg->plt_offset);
6983 emit_int32 (acfg, acfg->nmethods);
6984 emit_int32 (acfg, acfg->flags);
6985 emit_int32 (acfg, acfg->opts);
6986 emit_int32 (acfg, gc_name_offset);
6988 for (i = 0; i < MONO_AOT_TRAMP_NUM; ++i)
6989 emit_int32 (acfg, acfg->num_trampolines [i]);
6990 for (i = 0; i < MONO_AOT_TRAMP_NUM; ++i)
6991 emit_int32 (acfg, acfg->trampoline_got_offset_base [i]);
6992 for (i = 0; i < MONO_AOT_TRAMP_NUM; ++i)
6993 emit_int32 (acfg, acfg->trampoline_size [i]);
6995 #if defined (TARGET_ARM) && defined (__APPLE__)
7000 t.type = MONO_TYPE_R8;
7001 mono_type_size (&t, &align);
7003 emit_int32 (acfg, align);
7005 t.type = MONO_TYPE_I8;
7006 mono_type_size (&t, &align);
7008 emit_int32 (acfg, align);
7011 emit_int32 (acfg, __alignof__ (double));
7012 emit_int32 (acfg, __alignof__ (gint64));
7015 if (acfg->aot_opts.static_link) {
7019 * Emit a global symbol which can be passed by an embedding app to
7020 * mono_aot_register_module (). The symbol points to a pointer to the the file info
7023 #if defined(__APPLE__) && !defined(__native_client_codegen__)
7024 sprintf (symbol, "_mono_aot_module_%s_info", acfg->image->assembly->aname.name);
7026 sprintf (symbol, "mono_aot_module_%s_info", acfg->image->assembly->aname.name);
7029 /* Get rid of characters which cannot occur in symbols */
7031 for (p = symbol; *p; ++p) {
7032 if (!(isalnum (*p) || *p == '_'))
7035 acfg->static_linking_symbol = g_strdup (symbol);
7036 emit_global_inner (acfg, symbol, FALSE);
7037 emit_label (acfg, symbol);
7038 emit_pointer (acfg, "mono_aot_file_info");
7043 emit_blob (MonoAotCompile *acfg)
7047 sprintf (symbol, "blob");
7048 emit_section_change (acfg, RODATA_SECT, 1);
7049 emit_alignment (acfg, 8);
7050 emit_label (acfg, symbol);
7052 emit_bytes (acfg, (guint8*)acfg->blob.data, acfg->blob.index);
7056 emit_dwarf_info (MonoAotCompile *acfg)
7058 #ifdef EMIT_DWARF_INFO
7060 char symbol [128], symbol2 [128];
7062 /* DIEs for methods */
7063 for (i = 0; i < acfg->nmethods; ++i) {
7064 MonoCompile *cfg = acfg->cfgs [i];
7069 // FIXME: LLVM doesn't define .Lme_...
7070 if (cfg->compile_llvm)
7073 sprintf (symbol, "%s", cfg->asm_symbol);
7074 sprintf (symbol2, "%sme_%x", acfg->temp_prefix, i);
7076 mono_dwarf_writer_emit_method (acfg->dwarf, cfg, cfg->method, 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 ()));
7082 collect_methods (MonoAotCompile *acfg)
7085 MonoImage *image = acfg->image;
7087 /* Collect methods */
7088 for (i = 0; i < image->tables [MONO_TABLE_METHOD].rows; ++i) {
7090 guint32 token = MONO_TOKEN_METHOD_DEF | (i + 1);
7092 method = mono_get_method (acfg->image, token, NULL);
7095 printf ("Failed to load method 0x%x from '%s'.\n", token, image->name);
7099 /* Load all methods eagerly to skip the slower lazy loading code */
7100 mono_class_setup_methods (method->klass);
7102 if (acfg->aot_opts.full_aot && method->iflags & METHOD_IMPL_ATTRIBUTE_INTERNAL_CALL) {
7103 /* Compile the wrapper instead */
7104 /* We do this here instead of add_wrappers () because it is easy to do it here */
7105 MonoMethod *wrapper = mono_marshal_get_native_wrapper (method, check_for_pending_exc, TRUE);
7109 /* FIXME: Some mscorlib methods don't have debug info */
7111 if (acfg->aot_opts.soft_debug && !method->wrapper_type) {
7112 if (!((method->flags & METHOD_ATTRIBUTE_PINVOKE_IMPL) ||
7113 (method->iflags & METHOD_IMPL_ATTRIBUTE_RUNTIME) ||
7114 (method->flags & METHOD_ATTRIBUTE_ABSTRACT) ||
7115 (method->iflags & METHOD_IMPL_ATTRIBUTE_INTERNAL_CALL))) {
7116 if (!mono_debug_lookup_method (method)) {
7117 fprintf (stderr, "Method %s has no debug info, probably the .mdb file for the assembly is missing.\n", mono_method_full_name (method, TRUE));
7124 /* Since we add the normal methods first, their index will be equal to their zero based token index */
7125 add_method_with_index (acfg, method, i, FALSE);
7126 acfg->method_index ++;
7129 add_generic_instances (acfg);
7131 if (acfg->aot_opts.full_aot)
7132 add_wrappers (acfg);
7136 compile_methods (MonoAotCompile *acfg)
7140 if (acfg->aot_opts.nthreads > 0) {
7145 gpointer *user_data;
7146 MonoMethod **methods;
7148 methods_len = acfg->methods->len;
7150 len = acfg->methods->len / acfg->aot_opts.nthreads;
7153 * Partition the list of methods into fragments, and hand it to threads to
7156 threads = g_ptr_array_new ();
7157 /* Make a copy since acfg->methods is modified by compile_method () */
7158 methods = g_new0 (MonoMethod*, methods_len);
7159 //memcpy (methods, g_ptr_array_index (acfg->methods, 0), sizeof (MonoMethod*) * methods_len);
7160 for (i = 0; i < methods_len; ++i)
7161 methods [i] = g_ptr_array_index (acfg->methods, i);
7163 while (i < methods_len) {
7164 frag = g_ptr_array_new ();
7165 for (j = 0; j < len; ++j) {
7166 if (i < methods_len) {
7167 g_ptr_array_add (frag, methods [i]);
7172 user_data = g_new0 (gpointer, 3);
7173 user_data [0] = mono_domain_get ();
7174 user_data [1] = acfg;
7175 user_data [2] = frag;
7177 handle = mono_create_thread (NULL, 0, (gpointer)compile_thread_main, user_data, 0, NULL);
7178 g_ptr_array_add (threads, handle);
7182 for (i = 0; i < threads->len; ++i) {
7183 WaitForSingleObjectEx (g_ptr_array_index (threads, i), INFINITE, FALSE);
7189 /* Compile methods added by compile_method () or all methods if nthreads == 0 */
7190 for (i = methods_len; i < acfg->methods->len; ++i) {
7191 /* This can new methods to acfg->methods */
7192 compile_method (acfg, g_ptr_array_index (acfg->methods, i));
7197 compile_asm (MonoAotCompile *acfg)
7199 char *command, *objfile;
7200 char *outfile_name, *tmp_outfile_name;
7201 const char *tool_prefix = acfg->aot_opts.tool_prefix ? acfg->aot_opts.tool_prefix : "";
7203 #if defined(TARGET_AMD64)
7204 #define AS_OPTIONS "--64"
7205 #elif defined(TARGET_POWERPC64)
7206 #define AS_OPTIONS "-a64 -mppc64"
7207 #define LD_OPTIONS "-m elf64ppc"
7208 #elif defined(sparc) && SIZEOF_VOID_P == 8
7209 #define AS_OPTIONS "-xarch=v9"
7210 #elif defined(TARGET_X86) && defined(__APPLE__) && !defined(__native_client_codegen__)
7211 #define AS_OPTIONS "-arch i386 -W"
7213 #define AS_OPTIONS ""
7216 #ifdef __native_client_codegen__
7217 #if defined(TARGET_AMD64)
7218 #define AS_NAME "nacl64-as"
7220 #define AS_NAME "nacl-as"
7223 #define AS_NAME "as"
7227 #define LD_OPTIONS ""
7230 #define EH_LD_OPTIONS ""
7232 if (acfg->aot_opts.asm_only) {
7233 printf ("Output file: '%s'.\n", acfg->tmpfname);
7234 if (acfg->aot_opts.static_link)
7235 printf ("Linking symbol: '%s'.\n", acfg->static_linking_symbol);
7239 if (acfg->aot_opts.static_link) {
7240 if (acfg->aot_opts.outfile)
7241 objfile = g_strdup_printf ("%s", acfg->aot_opts.outfile);
7243 objfile = g_strdup_printf ("%s.o", acfg->image->name);
7245 objfile = g_strdup_printf ("%s.o", acfg->tmpfname);
7247 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);
7248 printf ("Executing the native assembler: %s\n", command);
7249 if (system (command) != 0) {
7257 if (acfg->aot_opts.static_link) {
7258 printf ("Output file: '%s'.\n", objfile);
7259 printf ("Linking symbol: '%s'.\n", acfg->static_linking_symbol);
7264 if (acfg->aot_opts.outfile)
7265 outfile_name = g_strdup_printf ("%s", acfg->aot_opts.outfile);
7267 outfile_name = g_strdup_printf ("%s%s", acfg->image->name, SHARED_EXT);
7269 tmp_outfile_name = g_strdup_printf ("%s.tmp", outfile_name);
7272 command = g_strdup_printf ("ld -shared -G -o %s %s.o", tmp_outfile_name, acfg->tmpfname);
7273 #elif defined(__ppc__) && defined(__APPLE__)
7274 command = g_strdup_printf ("gcc -dynamiclib -o %s %s.o", tmp_outfile_name, acfg->tmpfname);
7275 #elif defined(HOST_WIN32)
7276 command = g_strdup_printf ("gcc -shared --dll -mno-cygwin -o %s %s.o", tmp_outfile_name, acfg->tmpfname);
7277 #elif defined(TARGET_X86) && defined(__APPLE__) && !defined(__native_client_codegen__)
7278 command = g_strdup_printf ("gcc -m32 -dynamiclib -o %s %s.o", tmp_outfile_name, acfg->tmpfname);
7280 command = g_strdup_printf ("%sld %s %s -shared -o %s %s.o", tool_prefix, EH_LD_OPTIONS, LD_OPTIONS, tmp_outfile_name, acfg->tmpfname);
7282 printf ("Executing the native linker: %s\n", command);
7283 if (system (command) != 0) {
7284 g_free (tmp_outfile_name);
7285 g_free (outfile_name);
7293 /*com = g_strdup_printf ("strip --strip-unneeded %s%s", acfg->image->name, SHARED_EXT);
7294 printf ("Stripping the binary: %s\n", com);
7298 #if defined(TARGET_ARM) && !defined(__APPLE__)
7300 * gas generates 'mapping symbols' each time code and data is mixed, which
7301 * happens a lot in emit_and_reloc_code (), so we need to get rid of them.
7303 command = g_strdup_printf ("%sstrip --strip-symbol=\\$a --strip-symbol=\\$d %s", tool_prefix, tmp_outfile_name);
7304 printf ("Stripping the binary: %s\n", command);
7305 if (system (command) != 0) {
7306 g_free (tmp_outfile_name);
7307 g_free (outfile_name);
7314 rename (tmp_outfile_name, outfile_name);
7316 g_free (tmp_outfile_name);
7317 g_free (outfile_name);
7320 if (acfg->aot_opts.save_temps)
7321 printf ("Retained input file.\n");
7323 unlink (acfg->tmpfname);
7328 static MonoAotCompile*
7329 acfg_create (MonoAssembly *ass, guint32 opts)
7331 MonoImage *image = ass->image;
7332 MonoAotCompile *acfg;
7335 acfg = g_new0 (MonoAotCompile, 1);
7336 acfg->methods = g_ptr_array_new ();
7337 acfg->method_indexes = g_hash_table_new (NULL, NULL);
7338 acfg->method_depth = g_hash_table_new (NULL, NULL);
7339 acfg->plt_offset_to_entry = g_hash_table_new (NULL, NULL);
7340 acfg->patch_to_plt_entry = g_hash_table_new (mono_patch_info_hash, mono_patch_info_equal);
7341 acfg->patch_to_got_offset = g_hash_table_new (mono_patch_info_hash, mono_patch_info_equal);
7342 acfg->patch_to_got_offset_by_type = g_new0 (GHashTable*, MONO_PATCH_INFO_NUM);
7343 for (i = 0; i < MONO_PATCH_INFO_NUM; ++i)
7344 acfg->patch_to_got_offset_by_type [i] = g_hash_table_new (mono_patch_info_hash, mono_patch_info_equal);
7345 acfg->got_patches = g_ptr_array_new ();
7346 acfg->method_to_cfg = g_hash_table_new (NULL, NULL);
7347 acfg->token_info_hash = g_hash_table_new_full (NULL, NULL, NULL, g_free);
7348 acfg->method_to_pinvoke_import = g_hash_table_new_full (NULL, NULL, NULL, g_free);
7349 acfg->image_hash = g_hash_table_new (NULL, NULL);
7350 acfg->image_table = g_ptr_array_new ();
7351 acfg->globals = g_ptr_array_new ();
7352 acfg->image = image;
7354 acfg->mempool = mono_mempool_new ();
7355 acfg->extra_methods = g_ptr_array_new ();
7356 acfg->unwind_info_offsets = g_hash_table_new (NULL, NULL);
7357 acfg->unwind_ops = g_ptr_array_new ();
7358 acfg->method_label_hash = g_hash_table_new_full (g_str_hash, g_str_equal, g_free, NULL);
7359 acfg->method_order = g_ptr_array_new ();
7360 acfg->export_names = g_hash_table_new (NULL, NULL);
7361 acfg->klass_blob_hash = g_hash_table_new (NULL, NULL);
7362 acfg->method_blob_hash = g_hash_table_new (NULL, NULL);
7363 acfg->plt_entry_debug_sym_cache = g_hash_table_new (g_str_hash, g_str_equal);
7364 InitializeCriticalSection (&acfg->mutex);
7370 acfg_free (MonoAotCompile *acfg)
7374 img_writer_destroy (acfg->w);
7375 for (i = 0; i < acfg->nmethods; ++i)
7377 g_free (acfg->cfgs [i]);
7378 g_free (acfg->cfgs);
7379 g_free (acfg->static_linking_symbol);
7380 g_free (acfg->got_symbol);
7381 g_free (acfg->plt_symbol);
7382 g_ptr_array_free (acfg->methods, TRUE);
7383 g_ptr_array_free (acfg->got_patches, TRUE);
7384 g_ptr_array_free (acfg->image_table, TRUE);
7385 g_ptr_array_free (acfg->globals, TRUE);
7386 g_ptr_array_free (acfg->unwind_ops, TRUE);
7387 g_hash_table_destroy (acfg->method_indexes);
7388 g_hash_table_destroy (acfg->method_depth);
7389 g_hash_table_destroy (acfg->plt_offset_to_entry);
7390 g_hash_table_destroy (acfg->patch_to_plt_entry);
7391 g_hash_table_destroy (acfg->patch_to_got_offset);
7392 g_hash_table_destroy (acfg->method_to_cfg);
7393 g_hash_table_destroy (acfg->token_info_hash);
7394 g_hash_table_destroy (acfg->method_to_pinvoke_import);
7395 g_hash_table_destroy (acfg->image_hash);
7396 g_hash_table_destroy (acfg->unwind_info_offsets);
7397 g_hash_table_destroy (acfg->method_label_hash);
7398 g_hash_table_destroy (acfg->export_names);
7399 g_hash_table_destroy (acfg->plt_entry_debug_sym_cache);
7400 g_hash_table_destroy (acfg->klass_blob_hash);
7401 g_hash_table_destroy (acfg->method_blob_hash);
7402 for (i = 0; i < MONO_PATCH_INFO_NUM; ++i)
7403 g_hash_table_destroy (acfg->patch_to_got_offset_by_type [i]);
7404 g_free (acfg->patch_to_got_offset_by_type);
7405 mono_mempool_destroy (acfg->mempool);
7410 mono_compile_assembly (MonoAssembly *ass, guint32 opts, const char *aot_options)
7412 MonoImage *image = ass->image;
7414 MonoAotCompile *acfg;
7415 char *outfile_name, *tmp_outfile_name, *p;
7419 printf ("Mono Ahead of Time compiler - compiling assembly %s\n", image->name);
7421 acfg = acfg_create (ass, opts);
7423 memset (&acfg->aot_opts, 0, sizeof (acfg->aot_opts));
7424 acfg->aot_opts.write_symbols = TRUE;
7425 acfg->aot_opts.ntrampolines = 1024;
7426 acfg->aot_opts.nrgctx_trampolines = 1024;
7427 acfg->aot_opts.nimt_trampolines = 128;
7428 acfg->aot_opts.llvm_path = g_strdup ("");
7430 mono_aot_parse_options (aot_options, &acfg->aot_opts);
7432 if (acfg->aot_opts.static_link)
7433 acfg->aot_opts.autoreg = TRUE;
7435 //acfg->aot_opts.print_skipped_methods = TRUE;
7437 #ifndef MONO_ARCH_HAVE_FULL_AOT_TRAMPOLINES
7438 if (acfg->aot_opts.full_aot) {
7439 printf ("--aot=full is not supported on this platform.\n");
7444 if (acfg->aot_opts.direct_pinvoke && !acfg->aot_opts.static_link) {
7445 fprintf (stderr, "The 'direct-pinvoke' AOT option also requires the 'static' AOT option.\n");
7449 if (acfg->aot_opts.static_link)
7450 acfg->aot_opts.asm_writer = TRUE;
7452 if (acfg->aot_opts.soft_debug) {
7453 MonoDebugOptions *opt = mini_get_debug_options ();
7455 opt->mdb_optimizations = TRUE;
7456 opt->gen_seq_points = TRUE;
7458 if (mono_debug_format == MONO_DEBUG_FORMAT_NONE) {
7459 fprintf (stderr, "The soft-debug AOT option requires the --debug option.\n");
7462 acfg->flags |= MONO_AOT_FILE_FLAG_DEBUG;
7465 if (mono_use_llvm) {
7467 acfg->aot_opts.asm_writer = TRUE;
7468 acfg->flags |= MONO_AOT_FILE_FLAG_WITH_LLVM;
7470 if (acfg->aot_opts.soft_debug) {
7471 fprintf (stderr, "The 'soft-debug' option is not supported when compiling with LLVM.\n");
7476 if (acfg->aot_opts.full_aot)
7477 acfg->flags |= MONO_AOT_FILE_FLAG_FULL_AOT;
7479 load_profile_files (acfg);
7481 acfg->num_trampolines [MONO_AOT_TRAMP_SPECIFIC] = acfg->aot_opts.full_aot ? acfg->aot_opts.ntrampolines : 0;
7482 #ifdef MONO_ARCH_GSHARED_SUPPORTED
7483 acfg->num_trampolines [MONO_AOT_TRAMP_STATIC_RGCTX] = acfg->aot_opts.full_aot ? acfg->aot_opts.nrgctx_trampolines : 0;
7485 acfg->num_trampolines [MONO_AOT_TRAMP_IMT_THUNK] = acfg->aot_opts.full_aot ? acfg->aot_opts.nimt_trampolines : 0;
7487 acfg->temp_prefix = img_writer_get_temp_label_prefix (NULL);
7491 acfg->got_symbol_base = g_strdup_printf ("mono_aot_%s_got", acfg->image->assembly->aname.name);
7492 acfg->plt_symbol = g_strdup_printf ("%smono_aot_%s_plt", acfg->llvm_label_prefix, acfg->image->assembly->aname.name);
7493 acfg->assembly_name_sym = g_strdup (acfg->image->assembly->aname.name);
7495 /* Get rid of characters which cannot occur in symbols */
7496 for (p = acfg->got_symbol_base; *p; ++p) {
7497 if (!(isalnum (*p) || *p == '_'))
7500 for (p = acfg->plt_symbol; *p; ++p) {
7501 if (!(isalnum (*p) || *p == '_'))
7504 for (p = acfg->assembly_name_sym; *p; ++p) {
7505 if (!(isalnum (*p) || *p == '_'))
7509 acfg->method_index = 1;
7511 collect_methods (acfg);
7513 acfg->cfgs_size = acfg->methods->len + 32;
7514 acfg->cfgs = g_new0 (MonoCompile*, acfg->cfgs_size);
7516 /* PLT offset 0 is reserved for the PLT trampoline */
7517 acfg->plt_offset = 1;
7522 mono_llvm_create_aot_module (acfg->got_symbol_base);
7526 /* GOT offset 0 is reserved for the address of the current assembly */
7530 ji = mono_mempool_alloc0 (acfg->mempool, sizeof (MonoAotCompile));
7531 ji->type = MONO_PATCH_INFO_IMAGE;
7532 ji->data.image = acfg->image;
7534 get_got_offset (acfg, ji);
7536 /* Slot 1 is reserved for the mscorlib got addr */
7537 ji = mono_mempool_alloc0 (acfg->mempool, sizeof (MonoAotCompile));
7538 ji->type = MONO_PATCH_INFO_MSCORLIB_GOT_ADDR;
7539 get_got_offset (acfg, ji);
7541 /* This is very common */
7542 ji = mono_mempool_alloc0 (acfg->mempool, sizeof (MonoAotCompile));
7543 ji->type = MONO_PATCH_INFO_GC_CARD_TABLE_ADDR;
7544 get_got_offset (acfg, ji);
7549 compile_methods (acfg);
7553 acfg->stats.jit_time = TV_ELAPSED (atv, btv);
7559 if (acfg->aot_opts.asm_only) {
7560 if (acfg->aot_opts.outfile)
7561 acfg->tmpfname = g_strdup_printf ("%s", acfg->aot_opts.outfile);
7563 acfg->tmpfname = g_strdup_printf ("%s.s", acfg->image->name);
7565 acfg->tmpfname = g_strdup ("temp.s");
7568 emit_llvm_file (acfg);
7572 if (!acfg->aot_opts.asm_only && !acfg->aot_opts.asm_writer && bin_writer_supported ()) {
7573 if (acfg->aot_opts.outfile)
7574 outfile_name = g_strdup_printf ("%s", acfg->aot_opts.outfile);
7576 outfile_name = g_strdup_printf ("%s%s", acfg->image->name, SHARED_EXT);
7579 * Can't use g_file_open_tmp () as it will be deleted at exit, and
7580 * it might be in another file system so the rename () won't work.
7582 tmp_outfile_name = g_strdup_printf ("%s.tmp", outfile_name);
7584 acfg->fp = fopen (tmp_outfile_name, "w");
7586 printf ("Unable to create temporary file '%s': %s\n", tmp_outfile_name, strerror (errno));
7590 acfg->w = img_writer_create (acfg->fp, TRUE);
7591 acfg->use_bin_writer = TRUE;
7594 /* Append to the .s file created by llvm */
7595 /* FIXME: Use multiple files instead */
7596 acfg->fp = fopen (acfg->tmpfname, "a+");
7598 if (acfg->aot_opts.asm_only) {
7599 if (acfg->aot_opts.outfile)
7600 acfg->tmpfname = g_strdup_printf ("%s", acfg->aot_opts.outfile);
7602 acfg->tmpfname = g_strdup_printf ("%s.s", acfg->image->name);
7603 acfg->fp = fopen (acfg->tmpfname, "w+");
7605 int i = g_file_open_tmp ("mono_aot_XXXXXX", &acfg->tmpfname, NULL);
7606 acfg->fp = fdopen (i, "w+");
7608 if (acfg->fp == 0) {
7609 fprintf (stderr, "Unable to open file '%s': %s\n", acfg->tmpfname, strerror (errno));
7613 acfg->w = img_writer_create (acfg->fp, FALSE);
7615 tmp_outfile_name = NULL;
7616 outfile_name = NULL;
7619 acfg->got_symbol = g_strdup_printf ("%s%s", acfg->llvm_label_prefix, acfg->got_symbol_base);
7621 /* Compute symbols for methods */
7622 for (i = 0; i < acfg->nmethods; ++i) {
7623 if (acfg->cfgs [i]) {
7624 MonoCompile *cfg = acfg->cfgs [i];
7625 int method_index = get_method_index (acfg, cfg->orig_method);
7627 if (COMPILE_LLVM (cfg))
7628 cfg->asm_symbol = g_strdup_printf ("%s%s", acfg->llvm_label_prefix, cfg->llvm_method_name);
7630 cfg->asm_symbol = g_strdup_printf ("%s%sm_%x", acfg->temp_prefix, acfg->llvm_label_prefix, method_index);
7634 if (!acfg->aot_opts.nodebug)
7635 acfg->dwarf = mono_dwarf_writer_create (acfg->w, NULL, 0, FALSE);
7637 img_writer_emit_start (acfg->w);
7640 mono_dwarf_writer_emit_base_info (acfg->dwarf, mono_unwind_get_cie_program ());
7642 if (acfg->thumb_mixed) {
7645 * This global symbol marks the end of THUMB code, and the beginning of ARM
7646 * code generated by our JIT.
7648 sprintf (symbol, "thumb_end");
7649 emit_section_change (acfg, ".text", 0);
7650 emit_label (acfg, symbol);
7651 emit_zero_bytes (acfg, 16);
7653 fprintf (acfg->fp, ".arm\n");
7660 emit_extra_methods (acfg);
7662 emit_trampolines (acfg);
7664 emit_class_name_table (acfg);
7666 emit_got_info (acfg);
7668 emit_exception_info (acfg);
7670 emit_unwind_info (acfg);
7672 emit_class_info (acfg);
7676 emit_image_table (acfg);
7680 emit_file_info (acfg);
7684 emit_globals (acfg);
7686 emit_autoreg (acfg);
7689 emit_dwarf_info (acfg);
7690 mono_dwarf_writer_close (acfg->dwarf);
7693 emit_mem_end (acfg);
7695 if (acfg->need_pt_gnu_stack) {
7696 /* This is required so the .so doesn't have an executable stack */
7697 /* The bin writer already emits this */
7698 if (!acfg->use_bin_writer)
7699 fprintf (acfg->fp, "\n.section .note.GNU-stack,\"\",@progbits\n");
7704 acfg->stats.gen_time = TV_ELAPSED (atv, btv);
7707 g_assert (acfg->got_offset <= acfg->final_got_size);
7709 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);
7712 res = img_writer_emit_writeout (acfg->w);
7717 if (acfg->use_bin_writer) {
7718 int err = rename (tmp_outfile_name, outfile_name);
7721 printf ("Unable to rename '%s' to '%s': %s\n", tmp_outfile_name, outfile_name, strerror (errno));
7725 res = compile_asm (acfg);
7732 acfg->stats.link_time = TV_ELAPSED (atv, btv);
7734 printf ("Compiled %d out of %d methods (%d%%)\n", acfg->stats.ccount, acfg->stats.mcount, acfg->stats.mcount ? (acfg->stats.ccount * 100) / acfg->stats.mcount : 100);
7735 if (acfg->stats.genericcount)
7736 printf ("%d methods are generic (%d%%)\n", acfg->stats.genericcount, acfg->stats.mcount ? (acfg->stats.genericcount * 100) / acfg->stats.mcount : 100);
7737 if (acfg->stats.abscount)
7738 printf ("%d methods contain absolute addresses (%d%%)\n", acfg->stats.abscount, acfg->stats.mcount ? (acfg->stats.abscount * 100) / acfg->stats.mcount : 100);
7739 if (acfg->stats.lmfcount)
7740 printf ("%d methods contain lmf pointers (%d%%)\n", acfg->stats.lmfcount, acfg->stats.mcount ? (acfg->stats.lmfcount * 100) / acfg->stats.mcount : 100);
7741 if (acfg->stats.ocount)
7742 printf ("%d methods have other problems (%d%%)\n", acfg->stats.ocount, acfg->stats.mcount ? (acfg->stats.ocount * 100) / acfg->stats.mcount : 100);
7744 printf ("Methods compiled with LLVM: %d (%d%%)\n", acfg->stats.llvm_count, acfg->stats.mcount ? (acfg->stats.llvm_count * 100) / acfg->stats.mcount : 100);
7745 printf ("Methods without GOT slots: %d (%d%%)\n", acfg->stats.methods_without_got_slots, acfg->stats.mcount ? (acfg->stats.methods_without_got_slots * 100) / acfg->stats.mcount : 100);
7746 printf ("Direct calls: %d (%d%%)\n", acfg->stats.direct_calls, acfg->stats.all_calls ? (acfg->stats.direct_calls * 100) / acfg->stats.all_calls : 100);
7748 if (acfg->aot_opts.stats) {
7751 printf ("GOT slot distribution:\n");
7752 for (i = 0; i < MONO_PATCH_INFO_NONE; ++i)
7753 if (acfg->stats.got_slot_types [i])
7754 printf ("\t%s: %d (%d)\n", get_patch_name (i), acfg->stats.got_slot_types [i], acfg->stats.got_slot_info_sizes [i]);
7757 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);
7769 mono_aot_readonly_field_override (MonoClassField *field)
7775 mono_compile_assembly (MonoAssembly *ass, guint32 opts, const char *aot_options)