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;
128 int nrgctx_trampolines;
129 int nimt_trampolines;
130 gboolean print_skipped_methods;
138 typedef struct MonoAotStats {
139 int ccount, mcount, lmfcount, abscount, gcount, ocount, genericcount;
140 int code_size, info_size, ex_info_size, unwind_info_size, got_size, class_info_size, got_info_size;
141 int methods_without_got_slots, direct_calls, all_calls, llvm_count;
142 int got_slots, offsets_size;
143 int got_slot_types [MONO_PATCH_INFO_NONE];
144 int got_slot_info_sizes [MONO_PATCH_INFO_NONE];
145 int jit_time, gen_time, link_time;
148 typedef struct MonoAotCompile {
151 GHashTable *method_indexes;
152 GHashTable *method_depth;
155 GHashTable *patch_to_plt_entry;
156 GHashTable *plt_offset_to_entry;
157 GHashTable *patch_to_got_offset;
158 GHashTable **patch_to_got_offset_by_type;
159 GPtrArray *got_patches;
160 GHashTable *image_hash;
161 GHashTable *method_to_cfg;
162 GHashTable *token_info_hash;
163 GHashTable *method_to_pinvoke_import;
164 GPtrArray *extra_methods;
165 GPtrArray *image_table;
167 GPtrArray *method_order;
168 GHashTable *export_names;
169 /* Maps MonoClass* -> blob offset */
170 GHashTable *klass_blob_hash;
171 /* Maps MonoMethod* -> blob offset */
172 GHashTable *method_blob_hash;
173 guint32 *plt_got_info_offsets;
174 guint32 got_offset, plt_offset, plt_got_offset_base;
175 guint32 final_got_size;
176 /* Number of GOT entries reserved for trampolines */
177 guint32 num_trampoline_got_entries;
179 guint32 num_trampolines [MONO_AOT_TRAMP_NUM];
180 guint32 trampoline_got_offset_base [MONO_AOT_TRAMP_NUM];
181 guint32 trampoline_size [MONO_AOT_TRAMP_NUM];
183 MonoAotOptions aot_opts;
186 MonoMemPool *mempool;
189 char *static_linking_symbol;
190 CRITICAL_SECTION mutex;
191 gboolean use_bin_writer;
193 MonoDwarfWriter *dwarf;
197 GHashTable *unwind_info_offsets;
198 GPtrArray *unwind_ops;
199 guint32 unwind_info_offset;
200 char *got_symbol_base;
203 GHashTable *method_label_hash;
204 const char *temp_prefix;
205 const char *llvm_label_prefix;
206 guint32 label_generator;
208 MonoAotFileFlags flags;
209 MonoDynamicStream blob;
210 MonoClass **typespec_classes;
213 char *assembly_name_sym;
214 GHashTable *plt_entry_debug_sym_cache;
215 gboolean thumb_mixed, need_no_dead_strip, need_pt_gnu_stack;
216 GHashTable *ginst_hash;
221 char *symbol, *llvm_symbol, *debug_sym;
223 gboolean jit_used, llvm_used;
226 #define mono_acfg_lock(acfg) EnterCriticalSection (&((acfg)->mutex))
227 #define mono_acfg_unlock(acfg) LeaveCriticalSection (&((acfg)->mutex))
229 /* This points to the current acfg in LLVM mode */
230 static MonoAotCompile *llvm_acfg;
232 #ifdef HAVE_ARRAY_ELEM_INIT
233 #define MSGSTRFIELD(line) MSGSTRFIELD1(line)
234 #define MSGSTRFIELD1(line) str##line
235 static const struct msgstr_t {
236 #define PATCH_INFO(a,b) char MSGSTRFIELD(__LINE__) [sizeof (b)];
237 #include "patch-info.h"
240 #define PATCH_INFO(a,b) b,
241 #include "patch-info.h"
244 static const gint16 opidx [] = {
245 #define PATCH_INFO(a,b) [MONO_PATCH_INFO_ ## a] = offsetof (struct msgstr_t, MSGSTRFIELD(__LINE__)),
246 #include "patch-info.h"
250 static G_GNUC_UNUSED const char*
251 get_patch_name (int info)
253 return (const char*)&opstr + opidx [info];
257 #define PATCH_INFO(a,b) b,
258 static const char* const
259 patch_types [MONO_PATCH_INFO_NUM + 1] = {
260 #include "patch-info.h"
264 static G_GNUC_UNUSED const char*
265 get_patch_name (int info)
267 return patch_types [info];
273 get_plt_entry_debug_sym (MonoAotCompile *acfg, MonoJumpInfo *ji, GHashTable *cache);
275 /* Wrappers around the image writer functions */
278 emit_section_change (MonoAotCompile *acfg, const char *section_name, int subsection_index)
280 img_writer_emit_section_change (acfg->w, section_name, subsection_index);
284 emit_push_section (MonoAotCompile *acfg, const char *section_name, int subsection)
286 img_writer_emit_push_section (acfg->w, section_name, subsection);
290 emit_pop_section (MonoAotCompile *acfg)
292 img_writer_emit_pop_section (acfg->w);
296 emit_local_symbol (MonoAotCompile *acfg, const char *name, const char *end_label, gboolean func)
298 img_writer_emit_local_symbol (acfg->w, name, end_label, func);
302 emit_label (MonoAotCompile *acfg, const char *name)
304 img_writer_emit_label (acfg->w, name);
308 emit_bytes (MonoAotCompile *acfg, const guint8* buf, int size)
310 img_writer_emit_bytes (acfg->w, buf, size);
314 emit_string (MonoAotCompile *acfg, const char *value)
316 img_writer_emit_string (acfg->w, value);
320 emit_line (MonoAotCompile *acfg)
322 img_writer_emit_line (acfg->w);
326 emit_alignment (MonoAotCompile *acfg, int size)
328 img_writer_emit_alignment (acfg->w, size);
332 emit_pointer_unaligned (MonoAotCompile *acfg, const char *target)
334 img_writer_emit_pointer_unaligned (acfg->w, target);
338 emit_pointer (MonoAotCompile *acfg, const char *target)
340 img_writer_emit_pointer (acfg->w, target);
344 emit_int16 (MonoAotCompile *acfg, int value)
346 img_writer_emit_int16 (acfg->w, value);
350 emit_int32 (MonoAotCompile *acfg, int value)
352 img_writer_emit_int32 (acfg->w, value);
356 emit_symbol_diff (MonoAotCompile *acfg, const char *end, const char* start, int offset)
358 img_writer_emit_symbol_diff (acfg->w, end, start, offset);
362 emit_zero_bytes (MonoAotCompile *acfg, int num)
364 img_writer_emit_zero_bytes (acfg->w, num);
368 emit_byte (MonoAotCompile *acfg, guint8 val)
370 img_writer_emit_byte (acfg->w, val);
373 #ifdef __native_client_codegen__
375 emit_nacl_call_alignment (MonoAotCompile *acfg)
377 img_writer_emit_nacl_call_alignment (acfg->w);
381 static G_GNUC_UNUSED void
382 emit_global_inner (MonoAotCompile *acfg, const char *name, gboolean func)
384 img_writer_emit_global (acfg->w, name, func);
388 emit_global (MonoAotCompile *acfg, const char *name, gboolean func)
390 if (acfg->aot_opts.no_dlsym) {
391 g_ptr_array_add (acfg->globals, g_strdup (name));
392 img_writer_emit_local_symbol (acfg->w, name, NULL, func);
394 img_writer_emit_global (acfg->w, name, func);
399 emit_symbol_size (MonoAotCompile *acfg, const char *name, const char *end_label)
401 img_writer_emit_symbol_size (acfg->w, name, end_label);
405 emit_string_symbol (MonoAotCompile *acfg, const char *name, const char *value)
407 img_writer_emit_section_change (acfg->w, RODATA_SECT, 1);
409 /* On apple, all symbols need to be aligned to avoid warnings from ld */
410 emit_alignment (acfg, 4);
412 img_writer_emit_label (acfg->w, name);
413 img_writer_emit_string (acfg->w, value);
416 static G_GNUC_UNUSED void
417 emit_uleb128 (MonoAotCompile *acfg, guint32 value)
420 guint8 b = value & 0x7f;
422 if (value != 0) /* more bytes to come */
428 static G_GNUC_UNUSED void
429 emit_sleb128 (MonoAotCompile *acfg, gint64 value)
432 gboolean negative = (value < 0);
439 /* the following is unnecessary if the
440 * implementation of >>= uses an arithmetic rather
441 * than logical shift for a signed left operand
445 value |= - ((gint64)1 <<(size - 7));
446 /* sign bit of byte is second high order bit (0x40) */
447 if ((value == 0 && !(byte & 0x40)) ||
448 (value == -1 && (byte & 0x40)))
452 emit_byte (acfg, byte);
456 static G_GNUC_UNUSED void
457 encode_uleb128 (guint32 value, guint8 *buf, guint8 **endbuf)
462 guint8 b = value & 0x7f;
464 if (value != 0) /* more bytes to come */
472 static G_GNUC_UNUSED void
473 encode_sleb128 (gint32 value, guint8 *buf, guint8 **endbuf)
476 gboolean negative = (value < 0);
484 /* the following is unnecessary if the
485 * implementation of >>= uses an arithmetic rather
486 * than logical shift for a signed left operand
490 value |= - (1 <<(size - 7));
491 /* sign bit of byte is second high order bit (0x40) */
492 if ((value == 0 && !(byte & 0x40)) ||
493 (value == -1 && (byte & 0x40)))
503 /* ARCHITECTURE SPECIFIC CODE */
505 #if defined(TARGET_X86) || defined(TARGET_AMD64) || defined(TARGET_ARM) || defined(TARGET_POWERPC)
506 #define EMIT_DWARF_INFO 1
509 #if defined(TARGET_ARM)
510 #define AOT_FUNC_ALIGNMENT 4
512 #define AOT_FUNC_ALIGNMENT 16
514 #if (defined(TARGET_X86) || defined(TARGET_AMD64)) && defined(__native_client_codegen__)
515 #undef AOT_FUNC_ALIGNMENT
516 #define AOT_FUNC_ALIGNMENT 32
519 #if defined(TARGET_POWERPC64) && !defined(__mono_ilp32__)
520 #define PPC_LD_OP "ld"
521 #define PPC_LDX_OP "ldx"
523 #define PPC_LD_OP "lwz"
524 #define PPC_LDX_OP "lwzx"
528 #define AOT_TARGET_STR "AMD64"
533 #define AOT_TARGET_STR "ARM (MACH)"
535 #define AOT_TARGET_STR "ARM (!MACH)"
539 #ifdef TARGET_POWERPC64
540 #ifdef __mono_ilp32__
541 #define AOT_TARGET_STR "POWERPC64 (mono ilp32)"
543 #define AOT_TARGET_STR "POWERPC64 (!mono ilp32)"
546 #ifdef TARGET_POWERPC
547 #ifdef __mono_ilp32__
548 #define AOT_TARGET_STR "POWERPC (mono ilp32)"
550 #define AOT_TARGET_STR "POWERPC (!mono ilp32)"
557 #define AOT_TARGET_STR "X86 (WIN32)"
558 #elif defined(__native_client_codegen__)
559 #define AOT_TARGET_STR "X86 (native client codegen)"
561 #define AOT_TARGET_STR "X86 (!native client codegen)"
565 #ifndef AOT_TARGET_STR
566 #define AOT_TARGET_STR ""
570 arch_init (MonoAotCompile *acfg)
572 acfg->llc_args = g_string_new ("");
573 acfg->as_args = g_string_new ("");
576 * The prefix LLVM likes to put in front of symbol names on darwin.
577 * The mach-os specs require this for globals, but LLVM puts them in front of all
578 * symbols. We need to handle this, since we need to refer to LLVM generated
581 acfg->llvm_label_prefix = "";
584 if (acfg->aot_opts.mtriple && strstr (acfg->aot_opts.mtriple, "darwin")) {
585 g_string_append (acfg->llc_args, "-mattr=+v6");
588 g_string_append (acfg->llc_args, " -mattr=+vfp2,+d16");
589 g_string_append (acfg->as_args, " -mfpu=vfp3");
591 g_string_append (acfg->llc_args, " -soft-float");
594 if (acfg->aot_opts.mtriple && strstr (acfg->aot_opts.mtriple, "thumb"))
595 acfg->thumb_mixed = TRUE;
597 if (acfg->aot_opts.mtriple)
598 mono_arch_set_target (acfg->aot_opts.mtriple);
602 acfg->llvm_label_prefix = "_";
603 acfg->need_no_dead_strip = TRUE;
606 #if defined(__linux__) && !defined(TARGET_ARM)
607 acfg->need_pt_gnu_stack = TRUE;
612 * arch_emit_direct_call:
614 * Emit a direct call to the symbol TARGET. CALL_SIZE is set to the size of the
618 arch_emit_direct_call (MonoAotCompile *acfg, const char *target, int *call_size)
620 #if defined(TARGET_X86) || defined(TARGET_AMD64)
621 /* Need to make sure this is exactly 5 bytes long */
622 emit_byte (acfg, '\xe8');
623 emit_symbol_diff (acfg, target, ".", -4);
625 #elif defined(TARGET_ARM)
626 if (acfg->use_bin_writer) {
633 img_writer_emit_reloc (acfg->w, R_ARM_CALL, target, -8);
634 emit_bytes (acfg, buf, 4);
636 img_writer_emit_unset_mode (acfg->w);
637 fprintf (acfg->fp, "bl %s\n", target);
640 #elif defined(TARGET_POWERPC)
641 if (acfg->use_bin_writer) {
642 g_assert_not_reached ();
644 img_writer_emit_unset_mode (acfg->w);
645 fprintf (acfg->fp, "bl %s\n", target);
649 g_assert_not_reached ();
655 * - we use an approach similar to the x86 abi: reserve a register (r30) to hold
657 * - The full-aot trampolines need access to the GOT of mscorlib, so we store
658 * in in the 2. slot of every GOT, and require every method to place the GOT
659 * address in r30, even when it doesn't access the GOT otherwise. This way,
660 * the trampolines can compute the mscorlib GOT address by loading 4(r30).
665 * PPC64 uses function descriptors which greatly complicate all code, since
666 * these are used very inconsistently in the runtime. Some functions like
667 * mono_compile_method () return ftn descriptors, while others like the
668 * trampoline creation functions do not.
669 * We assume that all GOT slots contain function descriptors, and create
670 * descriptors in aot-runtime.c when needed.
671 * The ppc64 abi uses r2 to hold the address of the TOC/GOT, which is loaded
672 * from function descriptors, we could do the same, but it would require
673 * rewriting all the ppc/aot code to handle function descriptors properly.
674 * So instead, we use the same approach as on PPC32.
675 * This is a horrible mess, but fixing it would probably lead to an even bigger
681 * - similar to the PPC32 design, we reserve EBX to hold the GOT pointer.
684 #ifdef MONO_ARCH_AOT_SUPPORTED
686 * arch_emit_got_offset:
688 * The memory pointed to by CODE should hold native code for computing the GOT
689 * address. Emit this code while patching it with the offset between code and
690 * the GOT. CODE_SIZE is set to the number of bytes emitted.
693 arch_emit_got_offset (MonoAotCompile *acfg, guint8 *code, int *code_size)
695 #if defined(TARGET_POWERPC64)
696 g_assert (!acfg->use_bin_writer);
697 img_writer_emit_unset_mode (acfg->w);
699 * The ppc32 code doesn't seem to work on ppc64, the assembler complains about
700 * unsupported relocations. So we store the got address into the .Lgot_addr
701 * symbol which is in the text segment, compute its address, and load it.
703 fprintf (acfg->fp, ".L%d:\n", acfg->label_generator);
704 fprintf (acfg->fp, "lis 0, (.Lgot_addr + 4 - .L%d)@h\n", acfg->label_generator);
705 fprintf (acfg->fp, "ori 0, 0, (.Lgot_addr + 4 - .L%d)@l\n", acfg->label_generator);
706 fprintf (acfg->fp, "add 30, 30, 0\n");
707 fprintf (acfg->fp, "%s 30, 0(30)\n", PPC_LD_OP);
708 acfg->label_generator ++;
710 #elif defined(TARGET_POWERPC)
711 g_assert (!acfg->use_bin_writer);
712 img_writer_emit_unset_mode (acfg->w);
713 fprintf (acfg->fp, ".L%d:\n", acfg->label_generator);
714 fprintf (acfg->fp, "lis 0, (%s + 4 - .L%d)@h\n", acfg->got_symbol, acfg->label_generator);
715 fprintf (acfg->fp, "ori 0, 0, (%s + 4 - .L%d)@l\n", acfg->got_symbol, acfg->label_generator);
716 acfg->label_generator ++;
719 guint32 offset = mono_arch_get_patch_offset (code);
720 emit_bytes (acfg, code, offset);
721 emit_symbol_diff (acfg, acfg->got_symbol, ".", offset);
723 *code_size = offset + 4;
728 * arch_emit_got_access:
730 * The memory pointed to by CODE should hold native code for loading a GOT
731 * slot. Emit this code while patching it so it accesses the GOT slot GOT_SLOT.
732 * CODE_SIZE is set to the number of bytes emitted.
735 arch_emit_got_access (MonoAotCompile *acfg, guint8 *code, int got_slot, int *code_size)
737 /* Emit beginning of instruction */
738 emit_bytes (acfg, code, mono_arch_get_patch_offset (code));
740 /* Emit the offset */
742 emit_symbol_diff (acfg, acfg->got_symbol, ".", (unsigned int) ((got_slot * sizeof (gpointer)) - 4));
743 *code_size = mono_arch_get_patch_offset (code) + 4;
744 #elif defined(TARGET_X86)
745 emit_int32 (acfg, (unsigned int) ((got_slot * sizeof (gpointer))));
746 *code_size = mono_arch_get_patch_offset (code) + 4;
747 #elif defined(TARGET_ARM)
748 emit_symbol_diff (acfg, acfg->got_symbol, ".", (unsigned int) ((got_slot * sizeof (gpointer))) - 12);
749 *code_size = mono_arch_get_patch_offset (code) + 4;
750 #elif defined(TARGET_POWERPC)
756 ppc_load32 (code, ppc_r0, got_slot * sizeof (gpointer));
757 g_assert (code - buf == 8);
758 emit_bytes (acfg, buf, code - buf);
759 *code_size = code - buf;
762 g_assert_not_reached ();
769 * arch_emit_plt_entry:
771 * Emit code for the PLT entry with index INDEX.
774 arch_emit_plt_entry (MonoAotCompile *acfg, int index)
776 #if defined(TARGET_X86)
777 guint32 offset = (acfg->plt_got_offset_base + index) * sizeof (gpointer);
778 #if defined(__default_codegen__)
779 /* jmp *<offset>(%ebx) */
780 emit_byte (acfg, 0xff);
781 emit_byte (acfg, 0xa3);
782 emit_int32 (acfg, offset);
783 /* Used by mono_aot_get_plt_info_offset */
784 emit_int32 (acfg, acfg->plt_got_info_offsets [index]);
785 #elif defined(__native_client_codegen__)
786 const guint8 kSizeOfNaClJmp = 11;
787 guint8 bytes[kSizeOfNaClJmp];
788 guint8 *pbytes = &bytes[0];
790 x86_jump_membase32 (pbytes, X86_EBX, offset);
791 emit_bytes (acfg, bytes, kSizeOfNaClJmp);
792 /* four bytes of data, used by mono_arch_patch_plt_entry */
793 /* For Native Client, make this work with data embedded in push. */
794 emit_byte (acfg, 0x68); /* hide data in a push */
795 emit_int32 (acfg, acfg->plt_got_info_offsets [index]);
796 emit_alignment (acfg, AOT_FUNC_ALIGNMENT);
797 #endif /*__native_client_codegen__*/
798 #elif defined(TARGET_AMD64)
799 #if defined(__default_codegen__)
801 * We can't emit jumps because they are 32 bits only so they can't be patched.
802 * So we make indirect calls through GOT entries which are patched by the AOT
803 * loader to point to .Lpd entries.
805 /* jmpq *<offset>(%rip) */
806 emit_byte (acfg, '\xff');
807 emit_byte (acfg, '\x25');
808 emit_symbol_diff (acfg, acfg->got_symbol, ".", ((acfg->plt_got_offset_base + index) * sizeof (gpointer)) -4);
809 /* Used by mono_aot_get_plt_info_offset */
810 emit_int32 (acfg, acfg->plt_got_info_offsets [index]);
811 #elif defined(__native_client_codegen__)
813 guint8 *buf_aligned = ALIGN_TO(buf, kNaClAlignment);
814 guint8 *code = buf_aligned;
816 /* mov <OFFSET>(%rip), %r11d */
817 emit_byte (acfg, '\x45');
818 emit_byte (acfg, '\x8b');
819 emit_byte (acfg, '\x1d');
820 emit_symbol_diff (acfg, acfg->got_symbol, ".", ((acfg->plt_got_offset_base + index) * sizeof (gpointer)) -4);
822 amd64_jump_reg (code, AMD64_R11);
823 /* This should be constant for the plt patch */
824 g_assert ((size_t)(code-buf_aligned) == 10);
825 emit_bytes (acfg, buf_aligned, code - buf_aligned);
827 /* Hide data in a push imm32 so it passes validation */
828 emit_byte (acfg, 0x68); /* push */
829 emit_int32 (acfg, acfg->plt_got_info_offsets [index]);
830 emit_alignment (acfg, AOT_FUNC_ALIGNMENT);
831 #endif /*__native_client_codegen__*/
832 #elif defined(TARGET_ARM)
837 ARM_LDR_IMM (code, ARMREG_IP, ARMREG_PC, 0);
838 ARM_LDR_REG_REG (code, ARMREG_PC, ARMREG_PC, ARMREG_IP);
839 emit_bytes (acfg, buf, code - buf);
840 emit_symbol_diff (acfg, acfg->got_symbol, ".", ((acfg->plt_got_offset_base + index) * sizeof (gpointer)) - 4);
841 /* Used by mono_aot_get_plt_info_offset */
842 emit_int32 (acfg, acfg->plt_got_info_offsets [index]);
843 #elif defined(TARGET_POWERPC)
844 guint32 offset = (acfg->plt_got_offset_base + index) * sizeof (gpointer);
846 /* The GOT address is guaranteed to be in r30 by OP_LOAD_GOTADDR */
847 g_assert (!acfg->use_bin_writer);
848 img_writer_emit_unset_mode (acfg->w);
849 fprintf (acfg->fp, "lis 11, %d@h\n", offset);
850 fprintf (acfg->fp, "ori 11, 11, %d@l\n", offset);
851 fprintf (acfg->fp, "add 11, 11, 30\n");
852 fprintf (acfg->fp, "%s 11, 0(11)\n", PPC_LD_OP);
853 #ifdef PPC_USES_FUNCTION_DESCRIPTOR
854 fprintf (acfg->fp, "%s 2, %d(11)\n", PPC_LD_OP, (int)sizeof (gpointer));
855 fprintf (acfg->fp, "%s 11, 0(11)\n", PPC_LD_OP);
857 fprintf (acfg->fp, "mtctr 11\n");
858 fprintf (acfg->fp, "bctr\n");
859 emit_int32 (acfg, acfg->plt_got_info_offsets [index]);
861 g_assert_not_reached ();
866 arch_emit_llvm_plt_entry (MonoAotCompile *acfg, int index)
868 #if defined(TARGET_ARM)
870 /* LLVM calls the PLT entries using bl, so emit a stub */
871 /* FIXME: Too much overhead on every call */
872 fprintf (acfg->fp, ".thumb_func\n");
873 fprintf (acfg->fp, "bx pc\n");
874 fprintf (acfg->fp, "nop\n");
875 fprintf (acfg->fp, ".arm\n");
877 /* LLVM calls the PLT entries using bl, so these have to be thumb2 */
878 /* The caller already transitioned to thumb */
879 /* The code below should be 12 bytes long */
880 fprintf (acfg->fp, "ldr ip, [pc, #8]\n");
881 /* thumb can't encode ld pc, [pc, ip] */
882 fprintf (acfg->fp, "add ip, pc, ip\n");
883 fprintf (acfg->fp, "ldr ip, [ip, #0]\n");
884 fprintf (acfg->fp, "bx ip\n");
885 emit_symbol_diff (acfg, acfg->got_symbol, ".", ((acfg->plt_got_offset_base + index) * sizeof (gpointer)) + 4);
886 emit_int32 (acfg, acfg->plt_got_info_offsets [index]);
888 g_assert_not_reached ();
893 * arch_emit_specific_trampoline:
895 * Emit code for a specific trampoline. OFFSET is the offset of the first of
896 * two GOT slots which contain the generic trampoline address and the trampoline
897 * argument. TRAMP_SIZE is set to the size of the emitted trampoline.
900 arch_emit_specific_trampoline (MonoAotCompile *acfg, int offset, int *tramp_size)
903 * The trampolines created here are variations of the specific
904 * trampolines created in mono_arch_create_specific_trampoline (). The
906 * - the generic trampoline address is taken from a got slot.
907 * - the offset of the got slot where the trampoline argument is stored
908 * is embedded in the instruction stream, and the generic trampoline
909 * can load the argument by loading the offset, adding it to the
910 * address of the trampoline to get the address of the got slot, and
911 * loading the argument from there.
912 * - all the trampolines should be of the same length.
914 #if defined(TARGET_AMD64)
915 #if defined(__default_codegen__)
916 /* This should be exactly 16 bytes long */
918 /* call *<offset>(%rip) */
919 emit_byte (acfg, '\x41');
920 emit_byte (acfg, '\xff');
921 emit_byte (acfg, '\x15');
922 emit_symbol_diff (acfg, acfg->got_symbol, ".", (offset * sizeof (gpointer)) - 4);
923 /* This should be relative to the start of the trampoline */
924 emit_symbol_diff (acfg, acfg->got_symbol, ".", ((offset+1) * sizeof (gpointer)) + 7);
925 emit_zero_bytes (acfg, 5);
926 #elif defined(__native_client_codegen__)
928 guint8 *buf_aligned = ALIGN_TO(buf, kNaClAlignment);
929 guint8 *code = buf_aligned;
934 /* Emit this call in 'code' so we can find out how long it is. */
935 amd64_call_reg (code, AMD64_R11);
936 call_start = mono_arch_nacl_skip_nops (buf_aligned);
937 call_len = code - call_start;
939 /* The tramp_size is twice the NaCl alignment because it starts with */
940 /* a call which needs to be aligned to the end of the boundary. */
941 *tramp_size = kNaClAlignment*2;
943 /* Emit nops to align call site below which is 7 bytes plus */
944 /* the length of the call sequence emitted above. */
945 /* Note: this requires the specific trampoline starts on a */
946 /* kNaclAlignedment aligned address, which it does because */
947 /* it's its own function that is aligned. */
949 guint8 *nopbuf_aligned = ALIGN_TO (nop_buf, kNaClAlignment);
950 guint8 *nopbuf_end = mono_arch_nacl_pad (nopbuf_aligned, kNaClAlignment - 7 - (call_len));
951 emit_bytes (acfg, nopbuf_aligned, nopbuf_end - nopbuf_aligned);
953 /* The trampoline is stored at the offset'th pointer, the -4 is */
954 /* present because RIP relative addressing starts at the end of */
955 /* the current instruction, while the label "." is relative to */
956 /* the beginning of the current asm location, which in this case */
957 /* is not the mov instruction, but the offset itself, due to the */
958 /* way the bytes and ints are emitted here. */
959 got_offset = (offset * sizeof(gpointer)) - 4;
961 /* mov <OFFSET>(%rip), %r11d */
962 emit_byte (acfg, '\x45');
963 emit_byte (acfg, '\x8b');
964 emit_byte (acfg, '\x1d');
965 emit_symbol_diff (acfg, acfg->got_symbol, ".", got_offset);
968 emit_bytes (acfg, call_start, call_len);
970 /* The arg is stored at the offset+1 pointer, relative to beginning */
971 /* of trampoline: 7 for mov, plus the call length, and 1 for push. */
972 got_offset = ((offset + 1) * sizeof(gpointer)) + 7 + call_len + 1;
974 /* We can't emit this data directly, hide in a "push imm32" */
975 emit_byte (acfg, '\x68'); /* push */
976 emit_symbol_diff (acfg, acfg->got_symbol, ".", got_offset);
977 emit_alignment (acfg, kNaClAlignment);
978 #endif /*__native_client_codegen__*/
979 #elif defined(TARGET_ARM)
983 /* This should be exactly 20 bytes long */
986 ARM_PUSH (code, 0x5fff);
987 ARM_LDR_IMM (code, ARMREG_R1, ARMREG_PC, 4);
988 /* Load the value from the GOT */
989 ARM_LDR_REG_REG (code, ARMREG_R1, ARMREG_PC, ARMREG_R1);
991 ARM_BLX_REG (code, ARMREG_R1);
993 g_assert (code - buf == 16);
996 emit_bytes (acfg, buf, code - buf);
998 * Only one offset is needed, since the second one would be equal to the
1001 emit_symbol_diff (acfg, acfg->got_symbol, ".", (offset * sizeof (gpointer)) - 4 + 4);
1002 //emit_symbol_diff (acfg, acfg->got_symbol, ".", ((offset + 1) * sizeof (gpointer)) - 4 + 8);
1003 #elif defined(TARGET_POWERPC)
1010 g_assert (!acfg->use_bin_writer);
1013 * PPC has no ip relative addressing, so we need to compute the address
1014 * of the mscorlib got. That is slow and complex, so instead, we store it
1015 * in the second got slot of every aot image. The caller already computed
1016 * the address of its got and placed it into r30.
1018 img_writer_emit_unset_mode (acfg->w);
1019 /* Load mscorlib got address */
1020 fprintf (acfg->fp, "%s 0, %d(30)\n", PPC_LD_OP, (int)sizeof (gpointer));
1021 /* Load generic trampoline address */
1022 fprintf (acfg->fp, "lis 11, %d@h\n", (int)(offset * sizeof (gpointer)));
1023 fprintf (acfg->fp, "ori 11, 11, %d@l\n", (int)(offset * sizeof (gpointer)));
1024 fprintf (acfg->fp, "%s 11, 11, 0\n", PPC_LDX_OP);
1025 #ifdef PPC_USES_FUNCTION_DESCRIPTOR
1026 fprintf (acfg->fp, "%s 11, 0(11)\n", PPC_LD_OP);
1028 fprintf (acfg->fp, "mtctr 11\n");
1029 /* Load trampoline argument */
1030 /* On ppc, we pass it normally to the generic trampoline */
1031 fprintf (acfg->fp, "lis 11, %d@h\n", (int)((offset + 1) * sizeof (gpointer)));
1032 fprintf (acfg->fp, "ori 11, 11, %d@l\n", (int)((offset + 1) * sizeof (gpointer)));
1033 fprintf (acfg->fp, "%s 0, 11, 0\n", PPC_LDX_OP);
1034 /* Branch to generic trampoline */
1035 fprintf (acfg->fp, "bctr\n");
1037 #ifdef PPC_USES_FUNCTION_DESCRIPTOR
1038 *tramp_size = 10 * 4;
1040 *tramp_size = 9 * 4;
1042 #elif defined(TARGET_X86)
1046 /* Similar to the PPC code above */
1048 /* FIXME: Could this clobber the register needed by get_vcall_slot () ? */
1050 /* We clobber ECX, since EAX is used as MONO_ARCH_MONITOR_OBJECT_REG */
1051 #ifdef MONO_ARCH_MONITOR_OBJECT_REG
1052 g_assert (MONO_ARCH_MONITOR_OBJECT_REG != X86_ECX);
1056 /* Load mscorlib got address */
1057 x86_mov_reg_membase (code, X86_ECX, MONO_ARCH_GOT_REG, sizeof (gpointer), 4);
1058 /* Push trampoline argument */
1059 x86_push_membase (code, X86_ECX, (offset + 1) * sizeof (gpointer));
1060 /* Load generic trampoline address */
1061 x86_mov_reg_membase (code, X86_ECX, X86_ECX, offset * sizeof (gpointer), 4);
1062 /* Branch to generic trampoline */
1063 x86_jump_reg (code, X86_ECX);
1065 #ifdef __native_client_codegen__
1067 /* emit nops to next 32 byte alignment */
1068 int a = (~kNaClAlignmentMask) & ((code - buf) + kNaClAlignment - 1);
1069 while (code < (buf + a)) x86_nop(code);
1072 emit_bytes (acfg, buf, code - buf);
1074 *tramp_size = NACL_SIZE(17, kNaClAlignment);
1075 g_assert (code - buf == *tramp_size);
1077 g_assert_not_reached ();
1082 * arch_emit_unbox_trampoline:
1084 * Emit code for the unbox trampoline for METHOD used in the full-aot case.
1085 * CALL_TARGET is the symbol pointing to the native code of METHOD.
1088 arch_emit_unbox_trampoline (MonoAotCompile *acfg, MonoCompile *cfg, MonoMethod *method, const char *call_target)
1090 #if defined(TARGET_AMD64)
1095 this_reg = mono_arch_get_this_arg_reg (NULL);
1097 amd64_alu_reg_imm (code, X86_ADD, this_reg, sizeof (MonoObject));
1099 emit_bytes (acfg, buf, code - buf);
1101 emit_byte (acfg, '\xe9');
1102 emit_symbol_diff (acfg, call_target, ".", -4);
1103 #elif defined(TARGET_X86)
1110 x86_alu_membase_imm (code, X86_ADD, X86_ESP, this_pos, sizeof (MonoObject));
1112 emit_bytes (acfg, buf, code - buf);
1115 emit_byte (acfg, '\xe9');
1116 emit_symbol_diff (acfg, call_target, ".", -4);
1117 #elif defined(TARGET_ARM)
1121 if (acfg->thumb_mixed && cfg->compile_llvm) {
1122 fprintf (acfg->fp, "add r0, r0, #%d\n", sizeof (MonoObject));
1123 fprintf (acfg->fp, "b %s\n", call_target);
1124 fprintf (acfg->fp, ".arm\n");
1130 ARM_ADD_REG_IMM8 (code, ARMREG_R0, ARMREG_R0, sizeof (MonoObject));
1132 emit_bytes (acfg, buf, code - buf);
1133 /* jump to method */
1134 if (acfg->use_bin_writer) {
1141 img_writer_emit_reloc (acfg->w, R_ARM_JUMP24, call_target, -8);
1142 emit_bytes (acfg, buf, 4);
1144 if (acfg->thumb_mixed && cfg->compile_llvm)
1145 fprintf (acfg->fp, "\n\tbx %s\n", call_target);
1147 fprintf (acfg->fp, "\n\tb %s\n", call_target);
1149 #elif defined(TARGET_POWERPC)
1152 g_assert (!acfg->use_bin_writer);
1154 fprintf (acfg->fp, "\n\taddi %d, %d, %d\n", this_pos, this_pos, (int)sizeof (MonoObject));
1155 fprintf (acfg->fp, "\n\tb %s\n", call_target);
1157 g_assert_not_reached ();
1162 * arch_emit_static_rgctx_trampoline:
1164 * Emit code for a static rgctx trampoline. OFFSET is the offset of the first of
1165 * two GOT slots which contain the rgctx argument, and the method to jump to.
1166 * TRAMP_SIZE is set to the size of the emitted trampoline.
1167 * These kinds of trampolines cannot be enumerated statically, since there could
1168 * be one trampoline per method instantiation, so we emit the same code for all
1169 * trampolines, and parameterize them using two GOT slots.
1172 arch_emit_static_rgctx_trampoline (MonoAotCompile *acfg, int offset, int *tramp_size)
1174 #if defined(TARGET_AMD64)
1175 #if defined(__default_codegen__)
1176 /* This should be exactly 13 bytes long */
1179 /* mov <OFFSET>(%rip), %r10 */
1180 emit_byte (acfg, '\x4d');
1181 emit_byte (acfg, '\x8b');
1182 emit_byte (acfg, '\x15');
1183 emit_symbol_diff (acfg, acfg->got_symbol, ".", (offset * sizeof (gpointer)) - 4);
1185 /* jmp *<offset>(%rip) */
1186 emit_byte (acfg, '\xff');
1187 emit_byte (acfg, '\x25');
1188 emit_symbol_diff (acfg, acfg->got_symbol, ".", ((offset + 1) * sizeof (gpointer)) - 4);
1189 #elif defined(__native_client_codegen__)
1191 guint8 *buf_aligned = ALIGN_TO(buf, kNaClAlignment);
1192 guint8 *code = buf_aligned;
1194 /* mov <OFFSET>(%rip), %r10d */
1195 emit_byte (acfg, '\x45');
1196 emit_byte (acfg, '\x8b');
1197 emit_byte (acfg, '\x15');
1198 emit_symbol_diff (acfg, acfg->got_symbol, ".", (offset * sizeof (gpointer)) - 4);
1200 /* mov <OFFSET>(%rip), %r11d */
1201 emit_byte (acfg, '\x45');
1202 emit_byte (acfg, '\x8b');
1203 emit_byte (acfg, '\x1d');
1204 emit_symbol_diff (acfg, acfg->got_symbol, ".", ((offset + 1) * sizeof (gpointer)) - 4);
1207 amd64_jump_reg (code, AMD64_R11);
1208 emit_bytes (acfg, buf_aligned, code - buf_aligned);
1210 emit_alignment (acfg, kNaClAlignment);
1211 *tramp_size = kNaClAlignment;
1212 #endif /*__native_client_codegen__*/
1214 #elif defined(TARGET_ARM)
1218 /* This should be exactly 24 bytes long */
1221 /* Load rgctx value */
1222 ARM_LDR_IMM (code, ARMREG_IP, ARMREG_PC, 8);
1223 ARM_LDR_REG_REG (code, MONO_ARCH_RGCTX_REG, ARMREG_PC, ARMREG_IP);
1224 /* Load branch addr + branch */
1225 ARM_LDR_IMM (code, ARMREG_IP, ARMREG_PC, 4);
1226 ARM_LDR_REG_REG (code, ARMREG_PC, ARMREG_PC, ARMREG_IP);
1228 g_assert (code - buf == 16);
1231 emit_bytes (acfg, buf, code - buf);
1232 emit_symbol_diff (acfg, acfg->got_symbol, ".", (offset * sizeof (gpointer)) - 4 + 8);
1233 emit_symbol_diff (acfg, acfg->got_symbol, ".", ((offset + 1) * sizeof (gpointer)) - 4 + 4);
1234 #elif defined(TARGET_POWERPC)
1241 g_assert (!acfg->use_bin_writer);
1244 * PPC has no ip relative addressing, so we need to compute the address
1245 * of the mscorlib got. That is slow and complex, so instead, we store it
1246 * in the second got slot of every aot image. The caller already computed
1247 * the address of its got and placed it into r30.
1249 img_writer_emit_unset_mode (acfg->w);
1250 /* Load mscorlib got address */
1251 fprintf (acfg->fp, "%s 0, %d(30)\n", PPC_LD_OP, (int)sizeof (gpointer));
1253 fprintf (acfg->fp, "lis 11, %d@h\n", (int)(offset * sizeof (gpointer)));
1254 fprintf (acfg->fp, "ori 11, 11, %d@l\n", (int)(offset * sizeof (gpointer)));
1255 fprintf (acfg->fp, "%s %d, 11, 0\n", PPC_LDX_OP, MONO_ARCH_RGCTX_REG);
1256 /* Load target address */
1257 fprintf (acfg->fp, "lis 11, %d@h\n", (int)((offset + 1) * sizeof (gpointer)));
1258 fprintf (acfg->fp, "ori 11, 11, %d@l\n", (int)((offset + 1) * sizeof (gpointer)));
1259 fprintf (acfg->fp, "%s 11, 11, 0\n", PPC_LDX_OP);
1260 #ifdef PPC_USES_FUNCTION_DESCRIPTOR
1261 fprintf (acfg->fp, "%s 2, %d(11)\n", PPC_LD_OP, (int)sizeof (gpointer));
1262 fprintf (acfg->fp, "%s 11, 0(11)\n", PPC_LD_OP);
1264 fprintf (acfg->fp, "mtctr 11\n");
1265 /* Branch to the target address */
1266 fprintf (acfg->fp, "bctr\n");
1268 #ifdef PPC_USES_FUNCTION_DESCRIPTOR
1269 *tramp_size = 11 * 4;
1271 *tramp_size = 9 * 4;
1274 #elif defined(TARGET_X86)
1278 /* Similar to the PPC code above */
1280 g_assert (MONO_ARCH_RGCTX_REG != X86_ECX);
1283 /* Load mscorlib got address */
1284 x86_mov_reg_membase (code, X86_ECX, MONO_ARCH_GOT_REG, sizeof (gpointer), 4);
1286 x86_mov_reg_membase (code, MONO_ARCH_RGCTX_REG, X86_ECX, offset * sizeof (gpointer), 4);
1287 /* Branch to the target address */
1288 x86_jump_membase (code, X86_ECX, (offset + 1) * sizeof (gpointer));
1290 #ifdef __native_client_codegen__
1292 /* emit nops to next 32 byte alignment */
1293 int a = (~kNaClAlignmentMask) & ((code - buf) + kNaClAlignment - 1);
1294 while (code < (buf + a)) x86_nop(code);
1298 emit_bytes (acfg, buf, code - buf);
1300 *tramp_size = NACL_SIZE (15, kNaClAlignment);
1301 g_assert (code - buf == *tramp_size);
1303 g_assert_not_reached ();
1308 * arch_emit_imt_thunk:
1310 * Emit an IMT thunk usable in full-aot mode. The thunk uses 1 got slot which
1311 * points to an array of pointer pairs. The pairs of the form [key, ptr], where
1312 * key is the IMT key, and ptr holds the address of a memory location holding
1313 * the address to branch to if the IMT arg matches the key. The array is
1314 * terminated by a pair whose key is NULL, and whose ptr is the address of the
1316 * TRAMP_SIZE is set to the size of the emitted trampoline.
1319 arch_emit_imt_thunk (MonoAotCompile *acfg, int offset, int *tramp_size)
1321 #if defined(TARGET_AMD64)
1323 #if defined(__native_client_codegen__)
1328 guint8 *mov_buf_ptr = mov_buf;
1330 const int kSizeOfMove = 7;
1331 #if defined(__default_codegen__)
1332 code = buf = g_malloc (256);
1333 #elif defined(__native_client_codegen__)
1334 buf_alloc = g_malloc (256 + kNaClAlignment + kSizeOfMove);
1335 buf = ((guint)buf_alloc + kNaClAlignment) & ~kNaClAlignmentMask;
1336 /* The RIP relative move below is emitted first */
1341 /* FIXME: Optimize this, i.e. use binary search etc. */
1342 /* Maybe move the body into a separate function (slower, but much smaller) */
1344 /* MONO_ARCH_IMT_SCRATCH_REG is a free register */
1347 amd64_alu_membase_imm (code, X86_CMP, MONO_ARCH_IMT_SCRATCH_REG, 0, 0);
1349 amd64_branch8 (code, X86_CC_Z, 0, FALSE);
1352 amd64_alu_membase_reg_size (code, X86_CMP, MONO_ARCH_IMT_SCRATCH_REG, 0, MONO_ARCH_IMT_REG, sizeof (gpointer));
1354 amd64_branch8 (code, X86_CC_Z, 0, FALSE);
1357 amd64_alu_reg_imm (code, X86_ADD, MONO_ARCH_IMT_SCRATCH_REG, 2 * sizeof (gpointer));
1358 amd64_jump_code (code, labels [0]);
1361 mono_amd64_patch (labels [2], code);
1362 amd64_mov_reg_membase (code, MONO_ARCH_IMT_SCRATCH_REG, MONO_ARCH_IMT_SCRATCH_REG, sizeof (gpointer), sizeof (gpointer));
1363 amd64_jump_membase (code, MONO_ARCH_IMT_SCRATCH_REG, 0);
1367 mono_amd64_patch (labels [1], code);
1368 x86_breakpoint (code);
1370 /* mov <OFFSET>(%rip), MONO_ARCH_IMT_SCRATCH_REG */
1371 amd64_emit_rex (mov_buf_ptr, sizeof(gpointer), MONO_ARCH_IMT_SCRATCH_REG, 0, AMD64_RIP);
1372 *(mov_buf_ptr)++ = (unsigned char)0x8b; /* mov opcode */
1373 x86_address_byte (mov_buf_ptr, 0, MONO_ARCH_IMT_SCRATCH_REG & 0x7, 5);
1374 emit_bytes (acfg, mov_buf, mov_buf_ptr - mov_buf);
1375 emit_symbol_diff (acfg, acfg->got_symbol, ".", (offset * sizeof (gpointer)) - 4);
1377 emit_bytes (acfg, buf, code - buf);
1379 *tramp_size = code - buf + kSizeOfMove;
1380 #if defined(__native_client_codegen__)
1381 /* The tramp will be padded to the next kNaClAlignment bundle. */
1382 *tramp_size = ALIGN_TO ((*tramp_size), kNaClAlignment);
1385 #if defined(__default_codegen__)
1387 #elif defined(__native_client_codegen__)
1391 #elif defined(TARGET_X86)
1393 #ifdef __native_client_codegen__
1398 #if defined(__default_codegen__)
1399 code = buf = g_malloc (256);
1400 #elif defined(__native_client_codegen__)
1401 buf_alloc = g_malloc (256 + kNaClAlignment);
1402 code = buf = ((guint)buf_alloc + kNaClAlignment) & ~kNaClAlignmentMask;
1405 /* Allocate a temporary stack slot */
1406 x86_push_reg (code, X86_EAX);
1408 x86_push_reg (code, X86_EAX);
1410 /* Load mscorlib got address */
1411 x86_mov_reg_membase (code, X86_EAX, MONO_ARCH_GOT_REG, sizeof (gpointer), 4);
1413 x86_mov_reg_membase (code, X86_EAX, X86_EAX, offset * sizeof (gpointer), 4);
1416 x86_alu_membase_imm (code, X86_CMP, X86_EAX, 0, 0);
1418 x86_branch8 (code, X86_CC_Z, FALSE, 0);
1421 x86_alu_membase_reg (code, X86_CMP, X86_EAX, 0, MONO_ARCH_IMT_REG);
1423 x86_branch8 (code, X86_CC_Z, FALSE, 0);
1426 x86_alu_reg_imm (code, X86_ADD, X86_EAX, 2 * sizeof (gpointer));
1427 x86_jump_code (code, labels [0]);
1430 mono_x86_patch (labels [2], code);
1431 x86_mov_reg_membase (code, X86_EAX, X86_EAX, sizeof (gpointer), 4);
1432 x86_mov_reg_membase (code, X86_EAX, X86_EAX, 0, 4);
1433 /* Save the target address to the temporary stack location */
1434 x86_mov_membase_reg (code, X86_ESP, 4, X86_EAX, 4);
1436 x86_pop_reg (code, X86_EAX);
1437 /* Jump to the target address */
1442 mono_x86_patch (labels [1], code);
1443 x86_breakpoint (code);
1445 #ifdef __native_client_codegen__
1447 /* emit nops to next 32 byte alignment */
1448 int a = (~kNaClAlignmentMask) & ((code - buf) + kNaClAlignment - 1);
1449 while (code < (buf + a)) x86_nop(code);
1452 emit_bytes (acfg, buf, code - buf);
1454 *tramp_size = code - buf;
1456 #if defined(__default_codegen__)
1458 #elif defined(__native_client_codegen__)
1462 #elif defined(TARGET_ARM)
1464 guint8 *code, *code2, *labels [16];
1468 /* The IMT method is in v5 */
1470 /* Need at least two free registers, plus a slot for storing the pc */
1471 ARM_PUSH (code, (1 << ARMREG_R0)|(1 << ARMREG_R1)|(1 << ARMREG_R2));
1473 /* Load the parameter from the GOT */
1474 ARM_LDR_IMM (code, ARMREG_R0, ARMREG_PC, 0);
1475 ARM_LDR_REG_REG (code, ARMREG_R0, ARMREG_PC, ARMREG_R0);
1478 ARM_LDR_IMM (code, ARMREG_R1, ARMREG_R0, 0);
1479 ARM_CMP_REG_REG (code, ARMREG_R1, ARMREG_V5);
1481 ARM_B_COND (code, ARMCOND_EQ, 0);
1483 /* End-of-loop check */
1484 ARM_CMP_REG_IMM (code, ARMREG_R1, 0, 0);
1486 ARM_B_COND (code, ARMCOND_EQ, 0);
1489 ARM_ADD_REG_IMM8 (code, ARMREG_R0, ARMREG_R0, sizeof (gpointer) * 2);
1492 arm_patch (labels [4], labels [1]);
1495 arm_patch (labels [2], code);
1496 ARM_LDR_IMM (code, ARMREG_R0, ARMREG_R0, 4);
1497 ARM_LDR_IMM (code, ARMREG_R0, ARMREG_R0, 0);
1498 /* Save it to the third stack slot */
1499 ARM_STR_IMM (code, ARMREG_R0, ARMREG_SP, 8);
1500 /* Restore the registers and branch */
1501 ARM_POP (code, (1 << ARMREG_R0)|(1 << ARMREG_R1)|(1 << ARMREG_PC));
1504 arm_patch (labels [3], code);
1505 ARM_LDR_IMM (code, ARMREG_R0, ARMREG_R0, 4);
1506 ARM_STR_IMM (code, ARMREG_R0, ARMREG_SP, 8);
1507 ARM_POP (code, (1 << ARMREG_R0)|(1 << ARMREG_R1)|(1 << ARMREG_PC));
1511 ARM_LDR_IMM (code2, ARMREG_R0, ARMREG_PC, (code - (labels [0] + 8)));
1513 emit_bytes (acfg, buf, code - buf);
1514 emit_symbol_diff (acfg, acfg->got_symbol, ".", (offset * sizeof (gpointer)) + (code - (labels [0] + 8)) - 4);
1516 *tramp_size = code - buf + 4;
1517 #elif defined(TARGET_POWERPC)
1519 guint8 *code, *labels [16];
1523 /* Load the mscorlib got address */
1524 ppc_ldptr (code, ppc_r11, sizeof (gpointer), ppc_r30);
1525 /* Load the parameter from the GOT */
1526 ppc_load (code, ppc_r0, offset * sizeof (gpointer));
1527 ppc_ldptr_indexed (code, ppc_r11, ppc_r11, ppc_r0);
1529 /* Load and check key */
1531 ppc_ldptr (code, ppc_r0, 0, ppc_r11);
1532 ppc_cmp (code, 0, sizeof (gpointer) == 8 ? 1 : 0, ppc_r0, MONO_ARCH_IMT_REG);
1534 ppc_bc (code, PPC_BR_TRUE, PPC_BR_EQ, 0);
1536 /* End-of-loop check */
1537 ppc_cmpi (code, 0, sizeof (gpointer) == 8 ? 1 : 0, ppc_r0, 0);
1539 ppc_bc (code, PPC_BR_TRUE, PPC_BR_EQ, 0);
1542 ppc_addi (code, ppc_r11, ppc_r11, 2 * sizeof (gpointer));
1545 mono_ppc_patch (labels [4], labels [1]);
1548 mono_ppc_patch (labels [2], code);
1549 ppc_ldptr (code, ppc_r11, sizeof (gpointer), ppc_r11);
1550 /* r11 now contains the value of the vtable slot */
1551 /* this is not a function descriptor on ppc64 */
1552 ppc_ldptr (code, ppc_r11, 0, ppc_r11);
1553 ppc_mtctr (code, ppc_r11);
1554 ppc_bcctr (code, PPC_BR_ALWAYS, 0);
1557 mono_ppc_patch (labels [3], code);
1561 *tramp_size = code - buf;
1563 emit_bytes (acfg, buf, code - buf);
1565 g_assert_not_reached ();
1570 arch_emit_autoreg (MonoAotCompile *acfg, char *symbol)
1572 #if defined(TARGET_POWERPC) && defined(__mono_ilp32__)
1573 /* Based on code generated by gcc */
1574 img_writer_emit_unset_mode (acfg->w);
1577 #if defined(_MSC_VER) || defined(MONO_CROSS_COMPILE)
1578 ".section .ctors,\"aw\",@progbits\n"
1582 ".section .opd,\"aw\"\n"
1585 ".long .%s,.TOC.@tocbase32\n"
1588 ".type .%s,@function\n"
1590 ".%s:\n", symbol, symbol, symbol, symbol, symbol, symbol, symbol, symbol);
1592 ".section .ctors,\"aw\",@progbits\n"
1596 ".section .opd,\"aw\"\n"
1599 ".long .%1$s,.TOC.@tocbase32\n"
1600 ".size %1$s,.-%1$s\n"
1602 ".type .%1$s,@function\n"
1604 ".%1$s:\n", symbol);
1615 "lis 3, .Lglobals@h\n"
1616 "ori 3, 3, .Lglobals@l\n"
1617 "bl .mono_aot_register_module\n"
1625 #if defined(_MSC_VER) || defined(MONO_CROSS_COMPILE)
1627 ".size .%s,.-.%s\n", symbol, symbol);
1630 ".size .%1$s,.-.%1$s\n", symbol);
1636 /* END OF ARCH SPECIFIC CODE */
1639 mono_get_field_token (MonoClassField *field)
1641 MonoClass *klass = field->parent;
1644 for (i = 0; i < klass->field.count; ++i) {
1645 if (field == &klass->fields [i])
1646 return MONO_TOKEN_FIELD_DEF | (klass->field.first + 1 + i);
1649 g_assert_not_reached ();
1654 encode_value (gint32 value, guint8 *buf, guint8 **endbuf)
1658 //printf ("ENCODE: %d 0x%x.\n", value, value);
1661 * Same encoding as the one used in the metadata, extended to handle values
1662 * greater than 0x1fffffff.
1664 if ((value >= 0) && (value <= 127))
1666 else if ((value >= 0) && (value <= 16383)) {
1667 p [0] = 0x80 | (value >> 8);
1668 p [1] = value & 0xff;
1670 } else if ((value >= 0) && (value <= 0x1fffffff)) {
1671 p [0] = (value >> 24) | 0xc0;
1672 p [1] = (value >> 16) & 0xff;
1673 p [2] = (value >> 8) & 0xff;
1674 p [3] = value & 0xff;
1679 p [1] = (value >> 24) & 0xff;
1680 p [2] = (value >> 16) & 0xff;
1681 p [3] = (value >> 8) & 0xff;
1682 p [4] = value & 0xff;
1690 stream_init (MonoDynamicStream *sh)
1693 sh->alloc_size = 4096;
1694 sh->data = g_malloc (4096);
1696 /* So offsets are > 0 */
1702 make_room_in_stream (MonoDynamicStream *stream, int size)
1704 if (size <= stream->alloc_size)
1707 while (stream->alloc_size <= size) {
1708 if (stream->alloc_size < 4096)
1709 stream->alloc_size = 4096;
1711 stream->alloc_size *= 2;
1714 stream->data = g_realloc (stream->data, stream->alloc_size);
1718 add_stream_data (MonoDynamicStream *stream, const char *data, guint32 len)
1722 make_room_in_stream (stream, stream->index + len);
1723 memcpy (stream->data + stream->index, data, len);
1724 idx = stream->index;
1725 stream->index += len;
1732 * Add data to the binary blob inside the aot image. Returns the offset inside the
1733 * blob where the data was stored.
1736 add_to_blob (MonoAotCompile *acfg, const guint8 *data, guint32 data_len)
1738 if (acfg->blob.alloc_size == 0)
1739 stream_init (&acfg->blob);
1741 return add_stream_data (&acfg->blob, (char*)data, data_len);
1745 add_to_blob_aligned (MonoAotCompile *acfg, const guint8 *data, guint32 data_len, guint32 align)
1750 if (acfg->blob.alloc_size == 0)
1751 stream_init (&acfg->blob);
1753 count = acfg->blob.index % align;
1755 /* we assume the stream data will be aligned */
1757 add_stream_data (&acfg->blob, buf, 4 - count);
1759 return add_stream_data (&acfg->blob, (char*)data, data_len);
1763 * emit_offset_table:
1765 * Emit a table of increasing offsets in a compact form using differential encoding.
1766 * There is an index entry for each GROUP_SIZE number of entries. The greater the
1767 * group size, the more compact the table becomes, but the slower it becomes to compute
1768 * a given entry. Returns the size of the table.
1771 emit_offset_table (MonoAotCompile *acfg, int noffsets, int group_size, gint32 *offsets)
1773 gint32 current_offset;
1774 int i, buf_size, ngroups, index_entry_size;
1776 guint32 *index_offsets;
1778 ngroups = (noffsets + (group_size - 1)) / group_size;
1780 index_offsets = g_new0 (guint32, ngroups);
1782 buf_size = noffsets * 4;
1783 p = buf = g_malloc0 (buf_size);
1786 for (i = 0; i < noffsets; ++i) {
1787 //printf ("D: %d -> %d\n", i, offsets [i]);
1788 if ((i % group_size) == 0) {
1789 index_offsets [i / group_size] = p - buf;
1790 /* Emit the full value for these entries */
1791 encode_value (offsets [i], p, &p);
1793 /* The offsets are allowed to be non-increasing */
1794 //g_assert (offsets [i] >= current_offset);
1795 encode_value (offsets [i] - current_offset, p, &p);
1797 current_offset = offsets [i];
1800 if (ngroups && index_offsets [ngroups - 1] < 65000)
1801 index_entry_size = 2;
1803 index_entry_size = 4;
1805 /* Emit the header */
1806 emit_int32 (acfg, noffsets);
1807 emit_int32 (acfg, group_size);
1808 emit_int32 (acfg, ngroups);
1809 emit_int32 (acfg, index_entry_size);
1811 /* Emit the index */
1812 for (i = 0; i < ngroups; ++i) {
1813 if (index_entry_size == 2)
1814 emit_int16 (acfg, index_offsets [i]);
1816 emit_int32 (acfg, index_offsets [i]);
1820 emit_bytes (acfg, buf, p - buf);
1822 return (int)(p - buf) + (ngroups * 4);
1826 get_image_index (MonoAotCompile *cfg, MonoImage *image)
1830 index = GPOINTER_TO_UINT (g_hash_table_lookup (cfg->image_hash, image));
1834 index = g_hash_table_size (cfg->image_hash);
1835 g_hash_table_insert (cfg->image_hash, image, GUINT_TO_POINTER (index + 1));
1836 g_ptr_array_add (cfg->image_table, image);
1842 find_typespec_for_class (MonoAotCompile *acfg, MonoClass *klass)
1845 int len = acfg->image->tables [MONO_TABLE_TYPESPEC].rows;
1847 /* FIXME: Search referenced images as well */
1848 if (!acfg->typespec_classes) {
1849 acfg->typespec_classes = mono_mempool_alloc0 (acfg->mempool, sizeof (MonoClass*) * len);
1850 for (i = 0; i < len; ++i) {
1851 acfg->typespec_classes [i] = mono_class_get_full (acfg->image, MONO_TOKEN_TYPE_SPEC | (i + 1), NULL);
1854 for (i = 0; i < len; ++i) {
1855 if (acfg->typespec_classes [i] == klass)
1860 return MONO_TOKEN_TYPE_SPEC | (i + 1);
1866 encode_method_ref (MonoAotCompile *acfg, MonoMethod *method, guint8 *buf, guint8 **endbuf);
1869 encode_klass_ref (MonoAotCompile *acfg, MonoClass *klass, guint8 *buf, guint8 **endbuf);
1872 encode_ginst (MonoAotCompile *acfg, MonoGenericInst *inst, guint8 *buf, guint8 **endbuf);
1875 encode_type (MonoAotCompile *acfg, MonoType *t, guint8 *buf, guint8 **endbuf);
1878 encode_klass_ref_inner (MonoAotCompile *acfg, MonoClass *klass, guint8 *buf, guint8 **endbuf)
1883 * The encoding begins with one of the MONO_AOT_TYPEREF values, followed by additional
1887 if (klass->generic_class) {
1889 g_assert (klass->type_token);
1891 /* Find a typespec for a class if possible */
1892 token = find_typespec_for_class (acfg, klass);
1894 encode_value (MONO_AOT_TYPEREF_TYPESPEC_TOKEN, p, &p);
1895 encode_value (token, p, &p);
1897 MonoClass *gclass = klass->generic_class->container_class;
1898 MonoGenericInst *inst = klass->generic_class->context.class_inst;
1899 static int count = 0;
1902 encode_value (MONO_AOT_TYPEREF_GINST, p, &p);
1903 encode_klass_ref (acfg, gclass, p, &p);
1904 encode_ginst (acfg, inst, p, &p);
1908 } else if (klass->type_token) {
1909 int iindex = get_image_index (acfg, klass->image);
1911 g_assert (mono_metadata_token_code (klass->type_token) == MONO_TOKEN_TYPE_DEF);
1913 encode_value (MONO_AOT_TYPEREF_TYPEDEF_INDEX, p, &p);
1914 encode_value (klass->type_token - MONO_TOKEN_TYPE_DEF, p, &p);
1916 encode_value (MONO_AOT_TYPEREF_TYPEDEF_INDEX_IMAGE, p, &p);
1917 encode_value (klass->type_token - MONO_TOKEN_TYPE_DEF, p, &p);
1918 encode_value (get_image_index (acfg, klass->image), p, &p);
1920 } else if ((klass->byval_arg.type == MONO_TYPE_VAR) || (klass->byval_arg.type == MONO_TYPE_MVAR)) {
1921 MonoGenericContainer *container = mono_type_get_generic_param_owner (&klass->byval_arg);
1922 g_assert (container);
1924 encode_value (MONO_AOT_TYPEREF_VAR, p, &p);
1925 encode_value (klass->byval_arg.type, p, &p);
1926 encode_value (mono_type_get_generic_param_num (&klass->byval_arg), p, &p);
1928 encode_value (container->is_method, p, &p);
1929 if (container->is_method)
1930 encode_method_ref (acfg, container->owner.method, p, &p);
1932 encode_klass_ref (acfg, container->owner.klass, p, &p);
1933 } else if (klass->byval_arg.type == MONO_TYPE_PTR) {
1934 encode_value (MONO_AOT_TYPEREF_PTR, p, &p);
1935 encode_type (acfg, &klass->byval_arg, p, &p);
1938 g_assert (klass->rank > 0);
1939 encode_value (MONO_AOT_TYPEREF_ARRAY, p, &p);
1940 encode_value (klass->rank, p, &p);
1941 encode_klass_ref (acfg, klass->element_class, p, &p);
1949 * Encode a reference to KLASS. We use our home-grown encoding instead of the
1950 * standard metadata encoding.
1953 encode_klass_ref (MonoAotCompile *acfg, MonoClass *klass, guint8 *buf, guint8 **endbuf)
1955 gboolean shared = FALSE;
1958 * The encoding of generic instances is large so emit them only once.
1960 if (klass->generic_class) {
1962 g_assert (klass->type_token);
1964 /* Find a typespec for a class if possible */
1965 token = find_typespec_for_class (acfg, klass);
1968 } else if ((klass->byval_arg.type == MONO_TYPE_VAR) || (klass->byval_arg.type == MONO_TYPE_MVAR)) {
1973 guint offset = GPOINTER_TO_UINT (g_hash_table_lookup (acfg->klass_blob_hash, klass));
1977 buf2 = g_malloc (1024);
1980 encode_klass_ref_inner (acfg, klass, p, &p);
1981 g_assert (p - buf2 < 1024);
1983 offset = add_to_blob (acfg, buf2, p - buf2);
1986 g_hash_table_insert (acfg->klass_blob_hash, klass, GUINT_TO_POINTER (offset + 1));
1992 encode_value (MONO_AOT_TYPEREF_BLOB_INDEX, p, &p);
1993 encode_value (offset, p, &p);
1998 encode_klass_ref_inner (acfg, klass, buf, endbuf);
2002 encode_field_info (MonoAotCompile *cfg, MonoClassField *field, guint8 *buf, guint8 **endbuf)
2004 guint32 token = mono_get_field_token (field);
2007 encode_klass_ref (cfg, field->parent, p, &p);
2008 g_assert (mono_metadata_token_code (token) == MONO_TOKEN_FIELD_DEF);
2009 encode_value (token - MONO_TOKEN_FIELD_DEF, p, &p);
2014 encode_ginst (MonoAotCompile *acfg, MonoGenericInst *inst, guint8 *buf, guint8 **endbuf)
2019 encode_value (inst->type_argc, p, &p);
2020 for (i = 0; i < inst->type_argc; ++i)
2021 encode_klass_ref (acfg, mono_class_from_mono_type (inst->type_argv [i]), p, &p);
2026 encode_generic_context (MonoAotCompile *acfg, MonoGenericContext *context, guint8 *buf, guint8 **endbuf)
2029 MonoGenericInst *inst;
2031 inst = context->class_inst;
2033 g_assert (inst->type_argc);
2034 encode_ginst (acfg, inst, p, &p);
2036 encode_value (0, p, &p);
2038 inst = context->method_inst;
2040 g_assert (inst->type_argc);
2041 encode_ginst (acfg, inst, p, &p);
2043 encode_value (0, p, &p);
2049 encode_type (MonoAotCompile *acfg, MonoType *t, guint8 *buf, guint8 **endbuf)
2053 g_assert (t->num_mods == 0);
2054 /* t->attrs can be ignored */
2055 //g_assert (t->attrs == 0);
2058 *p = MONO_TYPE_PINNED;
2062 *p = MONO_TYPE_BYREF;
2070 case MONO_TYPE_VOID:
2071 case MONO_TYPE_BOOLEAN:
2072 case MONO_TYPE_CHAR:
2085 case MONO_TYPE_STRING:
2086 case MONO_TYPE_OBJECT:
2087 case MONO_TYPE_TYPEDBYREF:
2089 case MONO_TYPE_VALUETYPE:
2090 case MONO_TYPE_CLASS:
2091 encode_klass_ref (acfg, mono_class_from_mono_type (t), p, &p);
2093 case MONO_TYPE_SZARRAY:
2094 encode_klass_ref (acfg, t->data.klass, p, &p);
2097 encode_type (acfg, t->data.type, p, &p);
2099 case MONO_TYPE_GENERICINST: {
2100 MonoClass *gclass = t->data.generic_class->container_class;
2101 MonoGenericInst *inst = t->data.generic_class->context.class_inst;
2103 encode_klass_ref (acfg, gclass, p, &p);
2104 encode_ginst (acfg, inst, p, &p);
2107 case MONO_TYPE_ARRAY: {
2108 MonoArrayType *array = t->data.array;
2111 encode_klass_ref (acfg, array->eklass, p, &p);
2112 encode_value (array->rank, p, &p);
2113 encode_value (array->numsizes, p, &p);
2114 for (i = 0; i < array->numsizes; ++i)
2115 encode_value (array->sizes [i], p, &p);
2116 encode_value (array->numlobounds, p, &p);
2117 for (i = 0; i < array->numlobounds; ++i)
2118 encode_value (array->lobounds [i], p, &p);
2122 g_assert_not_reached ();
2129 encode_signature (MonoAotCompile *acfg, MonoMethodSignature *sig, guint8 *buf, guint8 **endbuf)
2135 /* Similar to the metadata encoding */
2136 if (sig->generic_param_count)
2140 if (sig->explicit_this)
2142 flags |= (sig->call_convention & 0x0F);
2146 if (sig->generic_param_count)
2147 encode_value (sig->generic_param_count, p, &p);
2148 encode_value (sig->param_count, p, &p);
2150 encode_type (acfg, sig->ret, p, &p);
2151 for (i = 0; i < sig->param_count; ++i) {
2152 if (sig->sentinelpos == i) {
2153 *p = MONO_TYPE_SENTINEL;
2156 encode_type (acfg, sig->params [i], p, &p);
2162 #define MAX_IMAGE_INDEX 250
2165 encode_method_ref (MonoAotCompile *acfg, MonoMethod *method, guint8 *buf, guint8 **endbuf)
2167 guint32 image_index = get_image_index (acfg, method->klass->image);
2168 guint32 token = method->token;
2169 MonoJumpInfoToken *ji;
2173 * The encoding for most methods is as follows:
2174 * - image index encoded as a leb128
2175 * - token index encoded as a leb128
2176 * Values of image index >= MONO_AOT_METHODREF_MIN are used to mark additional
2177 * types of method encodings.
2180 g_assert (image_index < MONO_AOT_METHODREF_MIN);
2182 /* Mark methods which can't use aot trampolines because they need the further
2183 * processing in mono_magic_trampoline () which requires a MonoMethod*.
2185 if ((method->is_generic && (method->flags & METHOD_ATTRIBUTE_VIRTUAL)) ||
2186 (method->iflags & METHOD_IMPL_ATTRIBUTE_SYNCHRONIZED))
2187 encode_value ((MONO_AOT_METHODREF_NO_AOT_TRAMPOLINE << 24), p, &p);
2189 if (method->wrapper_type) {
2190 encode_value ((MONO_AOT_METHODREF_WRAPPER << 24), p, &p);
2192 encode_value (method->wrapper_type, p, &p);
2194 switch (method->wrapper_type) {
2195 case MONO_WRAPPER_REMOTING_INVOKE:
2196 case MONO_WRAPPER_REMOTING_INVOKE_WITH_CHECK:
2197 case MONO_WRAPPER_XDOMAIN_INVOKE: {
2200 m = mono_marshal_method_from_wrapper (method);
2202 encode_method_ref (acfg, m, p, &p);
2205 case MONO_WRAPPER_PROXY_ISINST:
2206 case MONO_WRAPPER_LDFLD:
2207 case MONO_WRAPPER_LDFLDA:
2208 case MONO_WRAPPER_STFLD:
2209 case MONO_WRAPPER_ISINST: {
2210 MonoClass *proxy_class = mono_marshal_get_wrapper_info (method);
2211 encode_klass_ref (acfg, proxy_class, p, &p);
2214 case MONO_WRAPPER_LDFLD_REMOTE:
2215 case MONO_WRAPPER_STFLD_REMOTE:
2217 case MONO_WRAPPER_ALLOC: {
2218 AllocatorWrapperInfo *info = mono_marshal_get_wrapper_info (method);
2220 /* The GC name is saved once in MonoAotFileInfo */
2221 g_assert (info->alloc_type != -1);
2222 encode_value (info->alloc_type, p, &p);
2225 case MONO_WRAPPER_WRITE_BARRIER:
2227 case MONO_WRAPPER_STELEMREF: {
2228 WrapperInfo *info = mono_marshal_get_wrapper_info (method);
2231 encode_value (info->subtype, p, &p);
2232 if (info->subtype == WRAPPER_SUBTYPE_VIRTUAL_STELEMREF)
2233 encode_value (info->d.virtual_stelemref.kind, p, &p);
2236 case MONO_WRAPPER_UNKNOWN: {
2237 WrapperInfo *info = mono_marshal_get_wrapper_info (method);
2240 encode_value (info->subtype, p, &p);
2241 if (info->subtype == WRAPPER_SUBTYPE_PTR_TO_STRUCTURE ||
2242 info->subtype == WRAPPER_SUBTYPE_STRUCTURE_TO_PTR)
2243 encode_klass_ref (acfg, method->klass, p, &p);
2246 case MONO_WRAPPER_MANAGED_TO_NATIVE: {
2247 WrapperInfo *info = mono_marshal_get_wrapper_info (method);
2250 encode_value (info->subtype, p, &p);
2251 if (info->subtype == WRAPPER_SUBTYPE_ICALL_WRAPPER) {
2252 strcpy ((char*)p, method->name);
2253 p += strlen (method->name) + 1;
2255 g_assert (info->subtype == WRAPPER_SUBTYPE_NONE);
2256 encode_method_ref (acfg, info->d.managed_to_native.method, p, &p);
2260 case MONO_WRAPPER_SYNCHRONIZED: {
2263 m = mono_marshal_method_from_wrapper (method);
2265 g_assert (m != method);
2266 encode_method_ref (acfg, m, p, &p);
2269 case MONO_WRAPPER_MANAGED_TO_MANAGED: {
2270 WrapperInfo *info = mono_marshal_get_wrapper_info (method);
2273 encode_value (info->subtype, p, &p);
2275 if (info->subtype == WRAPPER_SUBTYPE_ELEMENT_ADDR) {
2276 encode_value (info->d.element_addr.rank, p, &p);
2277 encode_value (info->d.element_addr.elem_size, p, &p);
2278 } else if (info->subtype == WRAPPER_SUBTYPE_STRING_CTOR) {
2279 encode_method_ref (acfg, info->d.string_ctor.method, p, &p);
2281 g_assert_not_reached ();
2285 case MONO_WRAPPER_CASTCLASS: {
2286 WrapperInfo *info = mono_marshal_get_wrapper_info (method);
2289 encode_value (info->subtype, p, &p);
2292 case MONO_WRAPPER_RUNTIME_INVOKE: {
2293 WrapperInfo *info = mono_marshal_get_wrapper_info (method);
2296 encode_value (info->subtype, p, &p);
2297 if (info->subtype == WRAPPER_SUBTYPE_RUNTIME_INVOKE_DIRECT || info->subtype == WRAPPER_SUBTYPE_RUNTIME_INVOKE_VIRTUAL)
2298 encode_method_ref (acfg, info->d.runtime_invoke.method, p, &p);
2300 MonoMethodSignature *sig;
2302 encode_value (0, p, &p);
2304 sig = mono_method_signature (method);
2305 encode_signature (acfg, sig, p, &p);
2309 case MONO_WRAPPER_DELEGATE_INVOKE:
2310 case MONO_WRAPPER_DELEGATE_BEGIN_INVOKE:
2311 case MONO_WRAPPER_DELEGATE_END_INVOKE: {
2312 MonoMethodSignature *sig = mono_method_signature (method);
2313 encode_signature (acfg, sig, p, &p);
2316 case MONO_WRAPPER_NATIVE_TO_MANAGED: {
2317 WrapperInfo *info = mono_marshal_get_wrapper_info (method);
2320 encode_method_ref (acfg, info->d.native_to_managed.method, p, &p);
2321 encode_klass_ref (acfg, info->d.native_to_managed.klass, p, &p);
2325 g_assert_not_reached ();
2327 } else if (mono_method_signature (method)->is_inflated) {
2329 * This is a generic method, find the original token which referenced it and
2331 * Obtain the token from information recorded by the JIT.
2333 ji = g_hash_table_lookup (acfg->token_info_hash, method);
2335 image_index = get_image_index (acfg, ji->image);
2336 g_assert (image_index < MAX_IMAGE_INDEX);
2339 encode_value ((MONO_AOT_METHODREF_METHODSPEC << 24), p, &p);
2340 encode_value (image_index, p, &p);
2341 encode_value (token, p, &p);
2343 MonoMethod *declaring;
2344 MonoGenericContext *context = mono_method_get_context (method);
2346 g_assert (method->is_inflated);
2347 declaring = ((MonoMethodInflated*)method)->declaring;
2350 * This might be a non-generic method of a generic instance, which
2351 * doesn't have a token since the reference is generated by the JIT
2352 * like Nullable:Box/Unbox, or by generic sharing.
2355 encode_value ((MONO_AOT_METHODREF_GINST << 24), p, &p);
2356 /* Encode the klass */
2357 encode_klass_ref (acfg, method->klass, p, &p);
2358 /* Encode the method */
2359 image_index = get_image_index (acfg, method->klass->image);
2360 g_assert (image_index < MAX_IMAGE_INDEX);
2361 g_assert (declaring->token);
2362 token = declaring->token;
2363 g_assert (mono_metadata_token_table (token) == MONO_TABLE_METHOD);
2364 encode_value (image_index, p, &p);
2365 encode_value (token, p, &p);
2366 encode_generic_context (acfg, context, p, &p);
2368 } else if (token == 0) {
2369 /* This might be a method of a constructed type like int[,].Set */
2370 /* Obtain the token from information recorded by the JIT */
2371 ji = g_hash_table_lookup (acfg->token_info_hash, method);
2373 image_index = get_image_index (acfg, ji->image);
2374 g_assert (image_index < MAX_IMAGE_INDEX);
2377 encode_value ((MONO_AOT_METHODREF_METHODSPEC << 24), p, &p);
2378 encode_value (image_index, p, &p);
2379 encode_value (token, p, &p);
2382 g_assert (method->klass->rank);
2384 /* Encode directly */
2385 encode_value ((MONO_AOT_METHODREF_ARRAY << 24), p, &p);
2386 encode_klass_ref (acfg, method->klass, p, &p);
2387 if (!strcmp (method->name, ".ctor") && mono_method_signature (method)->param_count == method->klass->rank)
2388 encode_value (0, p, &p);
2389 else if (!strcmp (method->name, ".ctor") && mono_method_signature (method)->param_count == method->klass->rank * 2)
2390 encode_value (1, p, &p);
2391 else if (!strcmp (method->name, "Get"))
2392 encode_value (2, p, &p);
2393 else if (!strcmp (method->name, "Address"))
2394 encode_value (3, p, &p);
2395 else if (!strcmp (method->name, "Set"))
2396 encode_value (4, p, &p);
2398 g_assert_not_reached ();
2401 g_assert (mono_metadata_token_table (token) == MONO_TABLE_METHOD);
2402 encode_value ((image_index << 24) | mono_metadata_token_index (token), p, &p);
2408 compare_patches (gconstpointer a, gconstpointer b)
2412 i = (*(MonoJumpInfo**)a)->ip.i;
2413 j = (*(MonoJumpInfo**)b)->ip.i;
2424 static G_GNUC_UNUSED char*
2425 patch_to_string (MonoJumpInfo *patch_info)
2429 str = g_string_new ("");
2431 g_string_append_printf (str, "%s(", get_patch_name (patch_info->type));
2433 switch (patch_info->type) {
2434 case MONO_PATCH_INFO_VTABLE:
2435 mono_type_get_desc (str, &patch_info->data.klass->byval_arg, TRUE);
2440 g_string_append_printf (str, ")");
2441 return g_string_free (str, FALSE);
2447 * Return whenever PATCH_INFO refers to a direct call, and thus requires a
2450 static inline gboolean
2451 is_plt_patch (MonoJumpInfo *patch_info)
2453 switch (patch_info->type) {
2454 case MONO_PATCH_INFO_METHOD:
2455 case MONO_PATCH_INFO_INTERNAL_METHOD:
2456 case MONO_PATCH_INFO_JIT_ICALL_ADDR:
2457 case MONO_PATCH_INFO_ICALL_ADDR:
2458 case MONO_PATCH_INFO_CLASS_INIT:
2459 case MONO_PATCH_INFO_RGCTX_FETCH:
2460 case MONO_PATCH_INFO_GENERIC_CLASS_INIT:
2461 case MONO_PATCH_INFO_MONITOR_ENTER:
2462 case MONO_PATCH_INFO_MONITOR_EXIT:
2463 case MONO_PATCH_INFO_LLVM_IMT_TRAMPOLINE:
2473 * Return the symbol identifying the plt entry PLT_OFFSET.
2476 get_plt_symbol (MonoAotCompile *acfg, int plt_offset, MonoJumpInfo *patch_info)
2480 * The Apple linker reorganizes object files, so it doesn't like branches to local
2481 * labels, since those have no relocations.
2483 return g_strdup_printf ("%sp_%d", acfg->llvm_label_prefix, plt_offset);
2485 return g_strdup_printf ("%sp_%d", acfg->temp_prefix, plt_offset);
2492 * Return a PLT entry which belongs to the method identified by PATCH_INFO.
2494 static MonoPltEntry*
2495 get_plt_entry (MonoAotCompile *acfg, MonoJumpInfo *patch_info)
2499 if (!is_plt_patch (patch_info))
2502 res = g_hash_table_lookup (acfg->patch_to_plt_entry, patch_info);
2504 // FIXME: This breaks the calculation of final_got_size
2505 if (!acfg->llvm && patch_info->type == MONO_PATCH_INFO_METHOD && (patch_info->data.method->iflags & METHOD_IMPL_ATTRIBUTE_SYNCHRONIZED)) {
2507 * Allocate a separate PLT slot for each such patch, since some plt
2508 * entries will refer to the method itself, and some will refer to the
2515 MonoJumpInfo *new_ji;
2517 g_assert (!acfg->final_got_size);
2519 new_ji = mono_patch_info_dup_mp (acfg->mempool, patch_info);
2521 res = mono_mempool_alloc0 (acfg->mempool, sizeof (MonoPltEntry));
2522 res->plt_offset = acfg->plt_offset;
2524 res->symbol = get_plt_symbol (acfg, res->plt_offset, patch_info);
2525 if (acfg->aot_opts.write_symbols)
2526 res->debug_sym = get_plt_entry_debug_sym (acfg, res->ji, acfg->plt_entry_debug_sym_cache);
2528 res->llvm_symbol = g_strdup_printf ("%s_%s_llvm", res->symbol, res->debug_sym);
2530 res->llvm_symbol = g_strdup_printf ("%s_llvm", res->symbol);
2532 g_hash_table_insert (acfg->patch_to_plt_entry, new_ji, res);
2534 g_hash_table_insert (acfg->plt_offset_to_entry, GUINT_TO_POINTER (res->plt_offset), res);
2536 acfg->plt_offset ++;
2545 * Returns the offset of the GOT slot where the runtime object resulting from resolving
2546 * JI could be found if it exists, otherwise allocates a new one.
2549 get_got_offset (MonoAotCompile *acfg, MonoJumpInfo *ji)
2553 got_offset = GPOINTER_TO_UINT (g_hash_table_lookup (acfg->patch_to_got_offset_by_type [ji->type], ji));
2555 return got_offset - 1;
2557 got_offset = acfg->got_offset;
2558 acfg->got_offset ++;
2560 if (acfg->final_got_size)
2561 g_assert (got_offset < acfg->final_got_size);
2563 acfg->stats.got_slots ++;
2564 acfg->stats.got_slot_types [ji->type] ++;
2566 g_hash_table_insert (acfg->patch_to_got_offset, ji, GUINT_TO_POINTER (got_offset + 1));
2567 g_hash_table_insert (acfg->patch_to_got_offset_by_type [ji->type], ji, GUINT_TO_POINTER (got_offset + 1));
2568 g_ptr_array_add (acfg->got_patches, ji);
2573 /* Add a method to the list of methods which need to be emitted */
2575 add_method_with_index (MonoAotCompile *acfg, MonoMethod *method, int index, gboolean extra)
2578 if (!g_hash_table_lookup (acfg->method_indexes, method)) {
2579 g_ptr_array_add (acfg->methods, method);
2580 g_hash_table_insert (acfg->method_indexes, method, GUINT_TO_POINTER (index + 1));
2581 acfg->nmethods = acfg->methods->len + 1;
2584 if (method->wrapper_type || extra)
2585 g_ptr_array_add (acfg->extra_methods, method);
2589 get_method_index (MonoAotCompile *acfg, MonoMethod *method)
2591 int index = GPOINTER_TO_UINT (g_hash_table_lookup (acfg->method_indexes, method));
2599 add_method_full (MonoAotCompile *acfg, MonoMethod *method, gboolean extra, int depth)
2603 index = GPOINTER_TO_UINT (g_hash_table_lookup (acfg->method_indexes, method));
2607 index = acfg->method_index;
2608 add_method_with_index (acfg, method, index, extra);
2610 g_ptr_array_add (acfg->method_order, GUINT_TO_POINTER (index));
2612 g_hash_table_insert (acfg->method_depth, method, GUINT_TO_POINTER (depth));
2614 acfg->method_index ++;
2620 add_method (MonoAotCompile *acfg, MonoMethod *method)
2622 return add_method_full (acfg, method, FALSE, 0);
2626 add_extra_method (MonoAotCompile *acfg, MonoMethod *method)
2628 add_method_full (acfg, method, TRUE, 0);
2632 add_extra_method_with_depth (MonoAotCompile *acfg, MonoMethod *method, int depth)
2634 if (acfg->aot_opts.log_generics)
2635 printf ("%*sAdding method %s.\n", depth, "", mono_method_full_name (method, TRUE));
2637 add_method_full (acfg, method, TRUE, depth);
2641 add_jit_icall_wrapper (gpointer key, gpointer value, gpointer user_data)
2643 MonoAotCompile *acfg = user_data;
2644 MonoJitICallInfo *callinfo = value;
2645 MonoMethod *wrapper;
2651 name = g_strdup_printf ("__icall_wrapper_%s", callinfo->name);
2652 wrapper = mono_marshal_get_icall_wrapper (callinfo->sig, name, callinfo->func, check_for_pending_exc);
2655 add_method (acfg, wrapper);
2659 get_runtime_invoke_sig (MonoMethodSignature *sig)
2661 MonoMethodBuilder *mb;
2664 mb = mono_mb_new (mono_defaults.object_class, "FOO", MONO_WRAPPER_NONE);
2665 m = mono_mb_create_method (mb, sig, 16);
2666 return mono_marshal_get_runtime_invoke (m, FALSE);
2670 can_marshal_struct (MonoClass *klass)
2672 MonoClassField *field;
2673 gboolean can_marshal = TRUE;
2674 gpointer iter = NULL;
2676 if ((klass->flags & TYPE_ATTRIBUTE_LAYOUT_MASK) == TYPE_ATTRIBUTE_AUTO_LAYOUT)
2679 /* Only allow a few field types to avoid asserts in the marshalling code */
2680 while ((field = mono_class_get_fields (klass, &iter))) {
2681 if ((field->type->attrs & FIELD_ATTRIBUTE_STATIC))
2684 switch (field->type->type) {
2689 case MONO_TYPE_BOOLEAN:
2692 case MONO_TYPE_CHAR:
2700 case MONO_TYPE_STRING:
2702 case MONO_TYPE_VALUETYPE:
2703 if (!mono_class_from_mono_type (field->type)->enumtype && !can_marshal_struct (mono_class_from_mono_type (field->type)))
2704 can_marshal = FALSE;
2707 can_marshal = FALSE;
2713 /* Its hard to compute whenever these can be marshalled or not */
2714 if (!strcmp (klass->name_space, "System.Net.NetworkInformation.MacOsStructs"))
2721 add_wrappers (MonoAotCompile *acfg)
2723 MonoMethod *method, *m;
2725 MonoMethodSignature *sig, *csig;
2729 * FIXME: Instead of AOTing all the wrappers, it might be better to redesign them
2730 * so there is only one wrapper of a given type, or inlining their contents into their
2735 * FIXME: This depends on the fact that different wrappers have different
2739 for (i = 0; i < acfg->image->tables [MONO_TABLE_METHOD].rows; ++i) {
2741 guint32 token = MONO_TOKEN_METHOD_DEF | (i + 1);
2742 gboolean skip = FALSE;
2744 method = mono_get_method (acfg->image, token, NULL);
2746 if ((method->flags & METHOD_ATTRIBUTE_PINVOKE_IMPL) ||
2747 (method->iflags & METHOD_IMPL_ATTRIBUTE_RUNTIME) ||
2748 (method->flags & METHOD_ATTRIBUTE_ABSTRACT))
2751 if (method->is_generic || method->klass->generic_container)
2754 /* Skip methods which can not be handled by get_runtime_invoke () */
2755 sig = mono_method_signature (method);
2758 if ((sig->ret->type == MONO_TYPE_PTR) ||
2759 (sig->ret->type == MONO_TYPE_TYPEDBYREF))
2762 for (j = 0; j < sig->param_count; j++) {
2763 if (sig->params [j]->type == MONO_TYPE_TYPEDBYREF)
2767 #ifdef MONO_ARCH_DYN_CALL_SUPPORTED
2768 if (!method->klass->contextbound) {
2769 MonoDynCallInfo *info = mono_arch_dyn_call_prepare (sig);
2770 gboolean has_nullable = FALSE;
2772 for (j = 0; j < sig->param_count; j++) {
2773 if (sig->params [j]->type == MONO_TYPE_GENERICINST && mono_class_is_nullable (mono_class_from_mono_type (sig->params [j])))
2774 has_nullable = TRUE;
2777 if (info && !has_nullable) {
2778 /* Supported by the dynamic runtime-invoke wrapper */
2786 //printf ("%s\n", mono_method_full_name (method, TRUE));
2787 add_method (acfg, mono_marshal_get_runtime_invoke (method, FALSE));
2791 if (strcmp (acfg->image->assembly->aname.name, "mscorlib") == 0) {
2792 #ifdef MONO_ARCH_HAVE_TLS_GET
2793 MonoMethodDesc *desc;
2794 MonoMethod *orig_method;
2798 /* Runtime invoke wrappers */
2800 /* void runtime-invoke () [.cctor] */
2801 csig = mono_metadata_signature_alloc (mono_defaults.corlib, 0);
2802 csig->ret = &mono_defaults.void_class->byval_arg;
2803 add_method (acfg, get_runtime_invoke_sig (csig));
2805 /* void runtime-invoke () [Finalize] */
2806 csig = mono_metadata_signature_alloc (mono_defaults.corlib, 0);
2808 csig->ret = &mono_defaults.void_class->byval_arg;
2809 add_method (acfg, get_runtime_invoke_sig (csig));
2811 /* void runtime-invoke (string) [exception ctor] */
2812 csig = mono_metadata_signature_alloc (mono_defaults.corlib, 1);
2814 csig->ret = &mono_defaults.void_class->byval_arg;
2815 csig->params [0] = &mono_defaults.string_class->byval_arg;
2816 add_method (acfg, get_runtime_invoke_sig (csig));
2818 /* void runtime-invoke (string, string) [exception ctor] */
2819 csig = mono_metadata_signature_alloc (mono_defaults.corlib, 2);
2821 csig->ret = &mono_defaults.void_class->byval_arg;
2822 csig->params [0] = &mono_defaults.string_class->byval_arg;
2823 csig->params [1] = &mono_defaults.string_class->byval_arg;
2824 add_method (acfg, get_runtime_invoke_sig (csig));
2826 /* string runtime-invoke () [Exception.ToString ()] */
2827 csig = mono_metadata_signature_alloc (mono_defaults.corlib, 0);
2829 csig->ret = &mono_defaults.string_class->byval_arg;
2830 add_method (acfg, get_runtime_invoke_sig (csig));
2832 /* void runtime-invoke (string, Exception) [exception ctor] */
2833 csig = mono_metadata_signature_alloc (mono_defaults.corlib, 2);
2835 csig->ret = &mono_defaults.void_class->byval_arg;
2836 csig->params [0] = &mono_defaults.string_class->byval_arg;
2837 csig->params [1] = &mono_defaults.exception_class->byval_arg;
2838 add_method (acfg, get_runtime_invoke_sig (csig));
2840 /* Assembly runtime-invoke (string, bool) [DoAssemblyResolve] */
2841 csig = mono_metadata_signature_alloc (mono_defaults.corlib, 2);
2843 csig->ret = &(mono_class_from_name (
2844 mono_defaults.corlib, "System.Reflection", "Assembly"))->byval_arg;
2845 csig->params [0] = &mono_defaults.string_class->byval_arg;
2846 csig->params [1] = &mono_defaults.boolean_class->byval_arg;
2847 add_method (acfg, get_runtime_invoke_sig (csig));
2849 /* runtime-invoke used by finalizers */
2850 add_method (acfg, mono_marshal_get_runtime_invoke (mono_class_get_method_from_name_flags (mono_defaults.object_class, "Finalize", 0, 0), TRUE));
2852 /* This is used by mono_runtime_capture_context () */
2853 method = mono_get_context_capture_method ();
2855 add_method (acfg, mono_marshal_get_runtime_invoke (method, FALSE));
2857 #ifdef MONO_ARCH_DYN_CALL_SUPPORTED
2858 add_method (acfg, mono_marshal_get_runtime_invoke_dynamic ());
2861 /* JIT icall wrappers */
2862 /* FIXME: locking */
2863 g_hash_table_foreach (mono_get_jit_icall_info (), add_jit_icall_wrapper, acfg);
2866 add_method (acfg, mono_marshal_get_stelemref ());
2868 #ifdef MONO_ARCH_HAVE_TLS_GET
2869 /* Managed Allocators */
2870 nallocators = mono_gc_get_managed_allocator_types ();
2871 for (i = 0; i < nallocators; ++i) {
2872 m = mono_gc_get_managed_allocator_by_type (i);
2874 add_method (acfg, m);
2877 /* Monitor Enter/Exit */
2878 desc = mono_method_desc_new ("Monitor:Enter(object,bool&)", FALSE);
2879 orig_method = mono_method_desc_search_in_class (desc, mono_defaults.monitor_class);
2880 /* This is a v4 method */
2882 method = mono_monitor_get_fast_path (orig_method);
2884 add_method (acfg, method);
2886 mono_method_desc_free (desc);
2888 desc = mono_method_desc_new ("Monitor:Exit(object)", FALSE);
2889 orig_method = mono_method_desc_search_in_class (desc, mono_defaults.monitor_class);
2890 g_assert (orig_method);
2891 mono_method_desc_free (desc);
2892 method = mono_monitor_get_fast_path (orig_method);
2894 add_method (acfg, method);
2897 /* Stelemref wrappers */
2898 /* There is only a constant number of these, iterating over all types should handle them all */
2899 for (i = 0; i < acfg->image->tables [MONO_TABLE_TYPEDEF].rows; ++i) {
2902 token = MONO_TOKEN_TYPE_DEF | (i + 1);
2903 klass = mono_class_get (acfg->image, token);
2905 add_method (acfg, mono_marshal_get_virtual_stelemref (mono_array_class_get (klass, 1)));
2907 mono_loader_clear_error ();
2910 /* castclass_with_check wrapper */
2911 add_method (acfg, mono_marshal_get_castclass_with_cache ());
2912 /* isinst_with_check wrapper */
2913 add_method (acfg, mono_marshal_get_isinst_with_cache ());
2915 #if defined(MONO_ARCH_ENABLE_MONITOR_IL_FASTPATH)
2917 MonoMethodDesc *desc;
2920 desc = mono_method_desc_new ("Monitor:Enter(object,bool&)", FALSE);
2921 m = mono_method_desc_search_in_class (desc, mono_defaults.monitor_class);
2922 mono_method_desc_free (desc);
2924 m = mono_monitor_get_fast_path (m);
2925 add_method (acfg, m);
2932 * remoting-invoke-with-check wrappers are very frequent, so avoid emitting them,
2933 * we use the original method instead at runtime.
2934 * Since full-aot doesn't support remoting, this is not a problem.
2937 /* remoting-invoke wrappers */
2938 for (i = 0; i < acfg->image->tables [MONO_TABLE_METHOD].rows; ++i) {
2939 MonoMethodSignature *sig;
2941 token = MONO_TOKEN_METHOD_DEF | (i + 1);
2942 method = mono_get_method (acfg->image, token, NULL);
2944 sig = mono_method_signature (method);
2946 if (sig->hasthis && (method->klass->marshalbyref || method->klass == mono_defaults.object_class)) {
2947 m = mono_marshal_get_remoting_invoke_with_check (method);
2949 add_method (acfg, m);
2954 /* delegate-invoke wrappers */
2955 for (i = 0; i < acfg->image->tables [MONO_TABLE_TYPEDEF].rows; ++i) {
2958 token = MONO_TOKEN_TYPE_DEF | (i + 1);
2959 klass = mono_class_get (acfg->image, token);
2962 mono_loader_clear_error ();
2966 if (klass->delegate && klass != mono_defaults.delegate_class && klass != mono_defaults.multicastdelegate_class && !klass->generic_container) {
2967 method = mono_get_delegate_invoke (klass);
2969 m = mono_marshal_get_delegate_invoke (method, NULL);
2971 add_method (acfg, m);
2973 method = mono_class_get_method_from_name_flags (klass, "BeginInvoke", -1, 0);
2975 add_method (acfg, mono_marshal_get_delegate_begin_invoke (method));
2977 method = mono_class_get_method_from_name_flags (klass, "EndInvoke", -1, 0);
2979 add_method (acfg, mono_marshal_get_delegate_end_invoke (method));
2983 /* Synchronized wrappers */
2984 for (i = 0; i < acfg->image->tables [MONO_TABLE_METHOD].rows; ++i) {
2985 token = MONO_TOKEN_METHOD_DEF | (i + 1);
2986 method = mono_get_method (acfg->image, token, NULL);
2988 if (method->iflags & METHOD_IMPL_ATTRIBUTE_SYNCHRONIZED && !method->is_generic)
2989 add_method (acfg, mono_marshal_get_synchronized_wrapper (method));
2992 /* pinvoke wrappers */
2993 for (i = 0; i < acfg->image->tables [MONO_TABLE_METHOD].rows; ++i) {
2995 guint32 token = MONO_TOKEN_METHOD_DEF | (i + 1);
2997 method = mono_get_method (acfg->image, token, NULL);
2999 if ((method->flags & METHOD_ATTRIBUTE_PINVOKE_IMPL) ||
3000 (method->iflags & METHOD_IMPL_ATTRIBUTE_INTERNAL_CALL)) {
3001 add_method (acfg, mono_marshal_get_native_wrapper (method, TRUE, TRUE));
3005 /* native-to-managed wrappers */
3006 for (i = 0; i < acfg->image->tables [MONO_TABLE_METHOD].rows; ++i) {
3008 guint32 token = MONO_TOKEN_METHOD_DEF | (i + 1);
3009 MonoCustomAttrInfo *cattr;
3012 method = mono_get_method (acfg->image, token, NULL);
3015 * Only generate native-to-managed wrappers for methods which have an
3016 * attribute named MonoPInvokeCallbackAttribute. We search for the attribute by
3017 * name to avoid defining a new assembly to contain it.
3019 cattr = mono_custom_attrs_from_method (method);
3022 for (j = 0; j < cattr->num_attrs; ++j)
3023 if (cattr->attrs [j].ctor && !strcmp (cattr->attrs [j].ctor->klass->name, "MonoPInvokeCallbackAttribute"))
3025 if (j < cattr->num_attrs) {
3026 MonoCustomAttrEntry *e = &cattr->attrs [j];
3027 MonoMethodSignature *sig = mono_method_signature (e->ctor);
3028 const char *p = (const char*)e->data;
3030 int slen, num_named, named_type, data_type;
3034 char *export_name = NULL;
3035 MonoMethod *wrapper;
3037 /* this cannot be enforced by the C# compiler so we must give the user some warning before aborting */
3038 if (!(method->flags & METHOD_ATTRIBUTE_STATIC)) {
3039 g_warning ("AOT restriction: Method '%s' must be static since it is decorated with [MonoPInvokeCallback]. See http://ios.xamarin.com/Documentation/Limitations#Reverse_Callbacks",
3040 mono_method_full_name (method, TRUE));
3044 g_assert (sig->param_count == 1);
3045 g_assert (sig->params [0]->type == MONO_TYPE_CLASS && !strcmp (mono_class_from_mono_type (sig->params [0])->name, "Type"));
3048 * Decode the cattr manually since we can't create objects
3049 * during aot compilation.
3055 /* From load_cattr_value () in reflection.c */
3056 slen = mono_metadata_decode_value (p, &p);
3057 n = g_memdup (p, slen + 1);
3059 t = mono_reflection_type_from_name (n, acfg->image);
3063 klass = mono_class_from_mono_type (t);
3064 g_assert (klass->parent == mono_defaults.multicastdelegate_class);
3068 num_named = read16 (p);
3071 g_assert (num_named < 2);
3072 if (num_named == 1) {
3075 MonoType *prop_type;
3077 /* parse ExportSymbol attribute */
3079 named_type = *named;
3084 name_len = mono_metadata_decode_blob_size (named, &named);
3085 name = g_malloc (name_len + 1);
3086 memcpy (name, named, name_len);
3087 name [name_len] = 0;
3090 g_assert (named_type == 0x54);
3091 g_assert (!strcmp (name, "ExportSymbol"));
3093 prop_type = &mono_defaults.string_class->byval_arg;
3095 /* load_cattr_value (), string case */
3096 g_assert (*named != (char)0xff);
3097 slen = mono_metadata_decode_value (named, &named);
3098 export_name = g_malloc (slen + 1);
3099 memcpy (export_name, named, slen);
3100 export_name [slen] = 0;
3104 wrapper = mono_marshal_get_managed_wrapper (method, klass, 0);
3105 add_method (acfg, wrapper);
3107 g_hash_table_insert (acfg->export_names, wrapper, export_name);
3111 if ((method->flags & METHOD_ATTRIBUTE_PINVOKE_IMPL) ||
3112 (method->iflags & METHOD_IMPL_ATTRIBUTE_INTERNAL_CALL)) {
3113 add_method (acfg, mono_marshal_get_native_wrapper (method, TRUE, TRUE));
3117 /* StructureToPtr/PtrToStructure wrappers */
3118 for (i = 0; i < acfg->image->tables [MONO_TABLE_TYPEDEF].rows; ++i) {
3121 token = MONO_TOKEN_TYPE_DEF | (i + 1);
3122 klass = mono_class_get (acfg->image, token);
3125 mono_loader_clear_error ();
3129 if (klass->valuetype && !klass->generic_container && can_marshal_struct (klass)) {
3130 add_method (acfg, mono_marshal_get_struct_to_ptr (klass));
3131 add_method (acfg, mono_marshal_get_ptr_to_struct (klass));
3137 has_type_vars (MonoClass *klass)
3139 if ((klass->byval_arg.type == MONO_TYPE_VAR) || (klass->byval_arg.type == MONO_TYPE_MVAR))
3142 return has_type_vars (klass->element_class);
3143 if (klass->generic_class) {
3144 MonoGenericContext *context = &klass->generic_class->context;
3145 if (context->class_inst) {
3148 for (i = 0; i < context->class_inst->type_argc; ++i)
3149 if (has_type_vars (mono_class_from_mono_type (context->class_inst->type_argv [i])))
3157 method_has_type_vars (MonoMethod *method)
3159 if (has_type_vars (method->klass))
3162 if (method->is_inflated) {
3163 MonoGenericContext *context = mono_method_get_context (method);
3164 if (context->method_inst) {
3167 for (i = 0; i < context->method_inst->type_argc; ++i)
3168 if (has_type_vars (mono_class_from_mono_type (context->method_inst->type_argv [i])))
3175 static void add_generic_class_with_depth (MonoAotCompile *acfg, MonoClass *klass, int depth, const char *ref);
3178 add_generic_class (MonoAotCompile *acfg, MonoClass *klass, gboolean force, const char *ref)
3180 /* This might lead to a huge code blowup so only do it if neccesary */
3181 if (!acfg->aot_opts.full_aot && !force)
3184 add_generic_class_with_depth (acfg, klass, 0, ref);
3188 check_type_depth (MonoType *t, int depth)
3196 case MONO_TYPE_GENERICINST: {
3197 MonoGenericClass *gklass = t->data.generic_class;
3198 MonoGenericInst *ginst = gklass->context.class_inst;
3201 for (i = 0; i < ginst->type_argc; ++i) {
3202 if (check_type_depth (ginst->type_argv [i], depth + 1))
3216 * add_generic_class:
3218 * Add all methods of a generic class.
3221 add_generic_class_with_depth (MonoAotCompile *acfg, MonoClass *klass, int depth, const char *ref)
3226 if (!acfg->ginst_hash)
3227 acfg->ginst_hash = g_hash_table_new (NULL, NULL);
3229 mono_class_init (klass);
3231 if (klass->generic_class && klass->generic_class->context.class_inst->is_open)
3234 if (has_type_vars (klass))
3237 if (!klass->generic_class && !klass->rank)
3240 if (!acfg->ginst_hash)
3241 acfg->ginst_hash = g_hash_table_new (NULL, NULL);
3243 if (g_hash_table_lookup (acfg->ginst_hash, klass))
3246 if (check_type_depth (&klass->byval_arg, 0))
3249 if (acfg->aot_opts.log_generics)
3250 printf ("%*sAdding generic instance %s [%s].\n", depth, "", mono_type_full_name (&klass->byval_arg), ref);
3252 g_hash_table_insert (acfg->ginst_hash, klass, klass);
3255 while ((method = mono_class_get_methods (klass, &iter))) {
3256 if (mono_method_is_generic_sharable_impl_full (method, FALSE, FALSE))
3260 if (method->is_generic)
3265 * FIXME: Instances which are referenced by these methods are not added,
3266 * for example Array.Resize<int> for List<int>.Add ().
3268 add_extra_method_with_depth (acfg, method, depth + 1);
3271 if (klass->delegate) {
3272 method = mono_get_delegate_invoke (klass);
3274 method = mono_marshal_get_delegate_invoke (method, NULL);
3276 if (acfg->aot_opts.log_generics)
3277 printf ("%*sAdding method %s.\n", depth, "", mono_method_full_name (method, TRUE));
3279 add_method (acfg, method);
3282 /* Add superclasses */
3284 add_generic_class_with_depth (acfg, klass->parent, depth, "parent");
3287 * For ICollection<T>, add instances of the helper methods
3288 * in Array, since a T[] could be cast to ICollection<T>.
3290 if (klass->image == mono_defaults.corlib && !strcmp (klass->name_space, "System.Collections.Generic") &&
3291 (!strcmp(klass->name, "ICollection`1") || !strcmp (klass->name, "IEnumerable`1") || !strcmp (klass->name, "IList`1") || !strcmp (klass->name, "IEnumerator`1"))) {
3292 MonoClass *tclass = mono_class_from_mono_type (klass->generic_class->context.class_inst->type_argv [0]);
3293 MonoClass *array_class = mono_bounded_array_class_get (tclass, 1, FALSE);
3297 if (!strcmp (klass->name, "IEnumerator`1"))
3298 name_prefix = g_strdup_printf ("%s.%s", klass->name_space, "IEnumerable`1");
3300 name_prefix = g_strdup_printf ("%s.%s", klass->name_space, klass->name);
3302 /* Add the T[]/InternalEnumerator class */
3303 if (!strcmp (klass->name, "IEnumerable`1") || !strcmp (klass->name, "IEnumerator`1")) {
3307 while ((nclass = mono_class_get_nested_types (array_class->parent, &iter))) {
3308 if (!strcmp (nclass->name, "InternalEnumerator`1"))
3312 nclass = mono_class_inflate_generic_class (nclass, mono_generic_class_get_context (klass->generic_class));
3313 add_generic_class (acfg, nclass, FALSE, "ICollection<T>");
3317 while ((method = mono_class_get_methods (array_class, &iter))) {
3318 if (strstr (method->name, name_prefix)) {
3319 MonoMethod *m = mono_aot_get_array_helper_from_wrapper (method);
3321 add_extra_method_with_depth (acfg, m, depth);
3325 g_free (name_prefix);
3328 /* Add an instance of GenericComparer<T> which is created dynamically by Comparer<T> */
3329 if (klass->image == mono_defaults.corlib && !strcmp (klass->name_space, "System.Collections.Generic") && !strcmp (klass->name, "Comparer`1")) {
3330 MonoClass *tclass = mono_class_from_mono_type (klass->generic_class->context.class_inst->type_argv [0]);
3331 MonoClass *icomparable, *gcomparer;
3332 MonoGenericContext ctx;
3333 MonoType *args [16];
3335 memset (&ctx, 0, sizeof (ctx));
3337 icomparable = mono_class_from_name (mono_defaults.corlib, "System", "IComparable`1");
3338 g_assert (icomparable);
3339 args [0] = &tclass->byval_arg;
3340 ctx.class_inst = mono_metadata_get_generic_inst (1, args);
3342 if (mono_class_is_assignable_from (mono_class_inflate_generic_class (icomparable, &ctx), tclass)) {
3343 gcomparer = mono_class_from_name (mono_defaults.corlib, "System.Collections.Generic", "GenericComparer`1");
3344 g_assert (gcomparer);
3345 add_generic_class (acfg, mono_class_inflate_generic_class (gcomparer, &ctx), FALSE, "Comparer<T>");
3349 /* Add an instance of GenericEqualityComparer<T> which is created dynamically by EqualityComparer<T> */
3350 if (klass->image == mono_defaults.corlib && !strcmp (klass->name_space, "System.Collections.Generic") && !strcmp (klass->name, "EqualityComparer`1")) {
3351 MonoClass *tclass = mono_class_from_mono_type (klass->generic_class->context.class_inst->type_argv [0]);
3352 MonoClass *iface, *gcomparer;
3353 MonoGenericContext ctx;
3354 MonoType *args [16];
3356 memset (&ctx, 0, sizeof (ctx));
3358 iface = mono_class_from_name (mono_defaults.corlib, "System", "IEquatable`1");
3360 args [0] = &tclass->byval_arg;
3361 ctx.class_inst = mono_metadata_get_generic_inst (1, args);
3363 if (mono_class_is_assignable_from (mono_class_inflate_generic_class (iface, &ctx), tclass)) {
3364 gcomparer = mono_class_from_name (mono_defaults.corlib, "System.Collections.Generic", "GenericEqualityComparer`1");
3365 g_assert (gcomparer);
3366 add_generic_class (acfg, mono_class_inflate_generic_class (gcomparer, &ctx), FALSE, "EqualityComparer<T>");
3372 add_instances_of (MonoAotCompile *acfg, MonoClass *klass, MonoType **insts, int ninsts, gboolean force)
3375 MonoGenericContext ctx;
3376 MonoType *args [16];
3378 memset (&ctx, 0, sizeof (ctx));
3380 for (i = 0; i < ninsts; ++i) {
3381 args [0] = insts [i];
3382 ctx.class_inst = mono_metadata_get_generic_inst (1, args);
3383 add_generic_class (acfg, mono_class_inflate_generic_class (klass, &ctx), force, "");
3388 * add_generic_instances:
3390 * Add instances referenced by the METHODSPEC/TYPESPEC table.
3393 add_generic_instances (MonoAotCompile *acfg)
3398 MonoMethodHeader *header;
3399 MonoMethodSignature *sig;
3400 MonoGenericContext *context;
3402 for (i = 0; i < acfg->image->tables [MONO_TABLE_METHODSPEC].rows; ++i) {
3403 token = MONO_TOKEN_METHOD_SPEC | (i + 1);
3404 method = mono_get_method (acfg->image, token, NULL);
3409 if (method->klass->image != acfg->image)
3412 context = mono_method_get_context (method);
3414 if (context && ((context->class_inst && context->class_inst->is_open)))
3418 * For open methods, create an instantiation which can be passed to the JIT.
3419 * FIXME: Handle class_inst as well.
3421 if (context && context->method_inst && context->method_inst->is_open) {
3422 MonoGenericContext shared_context;
3423 MonoGenericInst *inst;
3424 MonoType **type_argv;
3426 MonoMethod *declaring_method;
3427 gboolean supported = TRUE;
3429 /* Check that the context doesn't contain open constructed types */
3430 if (context->class_inst) {
3431 inst = context->class_inst;
3432 for (i = 0; i < inst->type_argc; ++i) {
3433 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)
3435 if (mono_class_is_open_constructed_type (inst->type_argv [i]))
3439 if (context->method_inst) {
3440 inst = context->method_inst;
3441 for (i = 0; i < inst->type_argc; ++i) {
3442 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)
3444 if (mono_class_is_open_constructed_type (inst->type_argv [i]))
3452 memset (&shared_context, 0, sizeof (MonoGenericContext));
3454 inst = context->class_inst;
3456 type_argv = g_new0 (MonoType*, inst->type_argc);
3457 for (i = 0; i < inst->type_argc; ++i) {
3458 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)
3459 type_argv [i] = &mono_defaults.object_class->byval_arg;
3461 type_argv [i] = inst->type_argv [i];
3464 shared_context.class_inst = mono_metadata_get_generic_inst (inst->type_argc, type_argv);
3468 inst = context->method_inst;
3470 type_argv = g_new0 (MonoType*, inst->type_argc);
3471 for (i = 0; i < inst->type_argc; ++i) {
3472 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)
3473 type_argv [i] = &mono_defaults.object_class->byval_arg;
3475 type_argv [i] = inst->type_argv [i];
3478 shared_context.method_inst = mono_metadata_get_generic_inst (inst->type_argc, type_argv);
3482 if (method->is_generic || method->klass->generic_container)
3483 declaring_method = method;
3485 declaring_method = mono_method_get_declaring_generic_method (method);
3487 method = mono_class_inflate_generic_method (declaring_method, &shared_context);
3491 * If the method is fully sharable, it was already added in place of its
3492 * generic definition.
3494 if (mono_method_is_generic_sharable_impl_full (method, FALSE, FALSE))
3498 * FIXME: Partially shared methods are not shared here, so we end up with
3499 * many identical methods.
3501 add_extra_method (acfg, method);
3504 for (i = 0; i < acfg->image->tables [MONO_TABLE_TYPESPEC].rows; ++i) {
3507 token = MONO_TOKEN_TYPE_SPEC | (i + 1);
3509 klass = mono_class_get (acfg->image, token);
3510 if (!klass || klass->rank) {
3511 mono_loader_clear_error ();
3515 add_generic_class (acfg, klass, FALSE, "typespec");
3518 /* Add types of args/locals */
3519 for (i = 0; i < acfg->methods->len; ++i) {
3522 method = g_ptr_array_index (acfg->methods, i);
3524 depth = GPOINTER_TO_UINT (g_hash_table_lookup (acfg->method_depth, method));
3526 sig = mono_method_signature (method);
3529 for (j = 0; j < sig->param_count; ++j)
3530 if (sig->params [j]->type == MONO_TYPE_GENERICINST)
3531 add_generic_class_with_depth (acfg, mono_class_from_mono_type (sig->params [j]), depth + 1, "arg");
3534 header = mono_method_get_header (method);
3537 for (j = 0; j < header->num_locals; ++j)
3538 if (header->locals [j]->type == MONO_TYPE_GENERICINST)
3539 add_generic_class_with_depth (acfg, mono_class_from_mono_type (header->locals [j]), depth + 1, "local");
3543 if (acfg->image == mono_defaults.corlib) {
3545 MonoType *insts [256];
3548 insts [ninsts ++] = &mono_defaults.byte_class->byval_arg;
3549 insts [ninsts ++] = &mono_defaults.sbyte_class->byval_arg;
3550 insts [ninsts ++] = &mono_defaults.int16_class->byval_arg;
3551 insts [ninsts ++] = &mono_defaults.uint16_class->byval_arg;
3552 insts [ninsts ++] = &mono_defaults.int32_class->byval_arg;
3553 insts [ninsts ++] = &mono_defaults.uint32_class->byval_arg;
3554 insts [ninsts ++] = &mono_defaults.int64_class->byval_arg;
3555 insts [ninsts ++] = &mono_defaults.uint64_class->byval_arg;
3556 insts [ninsts ++] = &mono_defaults.single_class->byval_arg;
3557 insts [ninsts ++] = &mono_defaults.double_class->byval_arg;
3558 insts [ninsts ++] = &mono_defaults.char_class->byval_arg;
3559 insts [ninsts ++] = &mono_defaults.boolean_class->byval_arg;
3561 /* Add GenericComparer<T> instances for primitive types for Enum.ToString () */
3562 klass = mono_class_from_name (acfg->image, "System.Collections.Generic", "GenericComparer`1");
3564 add_instances_of (acfg, klass, insts, ninsts, TRUE);
3565 klass = mono_class_from_name (acfg->image, "System.Collections.Generic", "GenericEqualityComparer`1");
3567 add_instances_of (acfg, klass, insts, ninsts, TRUE);
3569 /* Add instances of the array generic interfaces for primitive types */
3570 /* This will add instances of the InternalArray_ helper methods in Array too */
3571 klass = mono_class_from_name (acfg->image, "System.Collections.Generic", "ICollection`1");
3573 add_instances_of (acfg, klass, insts, ninsts, TRUE);
3574 klass = mono_class_from_name (acfg->image, "System.Collections.Generic", "IList`1");
3576 add_instances_of (acfg, klass, insts, ninsts, TRUE);
3577 klass = mono_class_from_name (acfg->image, "System.Collections.Generic", "IEnumerable`1");
3579 add_instances_of (acfg, klass, insts, ninsts, TRUE);
3582 * Add a managed-to-native wrapper of Array.GetGenericValueImpl<object>, which is
3583 * used for all instances of GetGenericValueImpl by the AOT runtime.
3586 MonoGenericContext ctx;
3587 MonoType *args [16];
3588 MonoMethod *get_method;
3589 MonoClass *array_klass = mono_array_class_get (mono_defaults.object_class, 1)->parent;
3591 get_method = mono_class_get_method_from_name (array_klass, "GetGenericValueImpl", 2);
3594 memset (&ctx, 0, sizeof (ctx));
3595 args [0] = &mono_defaults.object_class->byval_arg;
3596 ctx.method_inst = mono_metadata_get_generic_inst (1, args);
3597 add_extra_method (acfg, mono_marshal_get_native_wrapper (mono_class_inflate_generic_method (get_method, &ctx), TRUE, TRUE));
3601 /* Same for CompareExchange<T>/Exchange<T> */
3603 MonoGenericContext ctx;
3604 MonoType *args [16];
3606 MonoClass *interlocked_klass = mono_class_from_name (mono_defaults.corlib, "System.Threading", "Interlocked");
3607 gpointer iter = NULL;
3609 while ((m = mono_class_get_methods (interlocked_klass, &iter))) {
3610 if ((!strcmp (m->name, "CompareExchange") || !strcmp (m->name, "Exchange")) && m->is_generic) {
3611 memset (&ctx, 0, sizeof (ctx));
3612 args [0] = &mono_defaults.object_class->byval_arg;
3613 ctx.method_inst = mono_metadata_get_generic_inst (1, args);
3614 add_extra_method (acfg, mono_marshal_get_native_wrapper (mono_class_inflate_generic_method (m, &ctx), TRUE, TRUE));
3622 * is_direct_callable:
3624 * Return whenever the method identified by JI is directly callable without
3625 * going through the PLT.
3628 is_direct_callable (MonoAotCompile *acfg, MonoMethod *method, MonoJumpInfo *patch_info)
3630 if ((patch_info->type == MONO_PATCH_INFO_METHOD) && (patch_info->data.method->klass->image == acfg->image)) {
3631 MonoCompile *callee_cfg = g_hash_table_lookup (acfg->method_to_cfg, patch_info->data.method);
3633 gboolean direct_callable = TRUE;
3635 if (direct_callable && !(!callee_cfg->has_got_slots && (callee_cfg->method->klass->flags & TYPE_ATTRIBUTE_BEFORE_FIELD_INIT)))
3636 direct_callable = FALSE;
3637 if ((callee_cfg->method->iflags & METHOD_IMPL_ATTRIBUTE_SYNCHRONIZED) && (!method || method->wrapper_type != MONO_WRAPPER_SYNCHRONIZED))
3638 // FIXME: Maybe call the wrapper directly ?
3639 direct_callable = FALSE;
3641 if (direct_callable)
3644 } else if ((patch_info->type == MONO_PATCH_INFO_ICALL_ADDR && patch_info->data.method->flags & METHOD_ATTRIBUTE_PINVOKE_IMPL)) {
3645 if (acfg->aot_opts.direct_pinvoke)
3653 get_pinvoke_import (MonoAotCompile *acfg, MonoMethod *method)
3655 MonoImage *image = method->klass->image;
3656 MonoMethodPInvoke *piinfo = (MonoMethodPInvoke *) method;
3657 MonoTableInfo *tables = image->tables;
3658 MonoTableInfo *im = &tables [MONO_TABLE_IMPLMAP];
3659 MonoTableInfo *mr = &tables [MONO_TABLE_MODULEREF];
3660 guint32 im_cols [MONO_IMPLMAP_SIZE];
3664 import = g_hash_table_lookup (acfg->method_to_pinvoke_import, method);
3668 if (!piinfo->implmap_idx || piinfo->implmap_idx > im->rows)
3671 mono_metadata_decode_row (im, piinfo->implmap_idx - 1, im_cols, MONO_IMPLMAP_SIZE);
3673 if (!im_cols [MONO_IMPLMAP_SCOPE] || im_cols [MONO_IMPLMAP_SCOPE] > mr->rows)
3676 #if defined(__APPLE__)
3682 import = g_strdup_printf ("%s%s", prefix, mono_metadata_string_heap (image, im_cols [MONO_IMPLMAP_NAME]));
3684 g_hash_table_insert (acfg->method_to_pinvoke_import, method, import);
3690 * emit_and_reloc_code:
3692 * Emit the native code in CODE, handling relocations along the way. If GOT_ONLY
3693 * is true, calls are made through the GOT too. This is used for emitting trampolines
3694 * in full-aot mode, since calls made from trampolines couldn't go through the PLT,
3695 * since trampolines are needed to make PTL work.
3698 emit_and_reloc_code (MonoAotCompile *acfg, MonoMethod *method, guint8 *code, guint32 code_len, MonoJumpInfo *relocs, gboolean got_only)
3700 int i, pindex, start_index, method_index;
3702 MonoJumpInfo *patch_info;
3703 MonoMethodHeader *header;
3704 gboolean skip, direct_call;
3706 char direct_call_target [1024];
3707 const char *direct_pinvoke;
3710 header = mono_method_get_header (method);
3712 method_index = get_method_index (acfg, method);
3715 /* Collect and sort relocations */
3716 patches = g_ptr_array_new ();
3717 for (patch_info = relocs; patch_info; patch_info = patch_info->next)
3718 g_ptr_array_add (patches, patch_info);
3719 g_ptr_array_sort (patches, compare_patches);
3722 for (i = 0; i < code_len; i++) {
3724 for (pindex = start_index; pindex < patches->len; ++pindex) {
3725 patch_info = g_ptr_array_index (patches, pindex);
3726 if (patch_info->ip.i >= i)
3730 #ifdef MONO_ARCH_AOT_SUPPORTED
3732 if (patch_info && (patch_info->ip.i == i) && (pindex < patches->len)) {
3733 start_index = pindex;
3735 switch (patch_info->type) {
3736 case MONO_PATCH_INFO_NONE:
3738 case MONO_PATCH_INFO_GOT_OFFSET: {
3741 arch_emit_got_offset (acfg, code + i, &code_size);
3744 patch_info->type = MONO_PATCH_INFO_NONE;
3749 * If this patch is a call, try emitting a direct call instead of
3750 * through a PLT entry. This is possible if the called method is in
3751 * the same assembly and requires no initialization.
3753 direct_call = FALSE;
3754 if ((patch_info->type == MONO_PATCH_INFO_METHOD) && (patch_info->data.method->klass->image == acfg->image)) {
3755 if (!got_only && is_direct_callable (acfg, method, patch_info)) {
3756 MonoCompile *callee_cfg = g_hash_table_lookup (acfg->method_to_cfg, patch_info->data.method);
3757 //printf ("DIRECT: %s %s\n", method ? mono_method_full_name (method, TRUE) : "", mono_method_full_name (callee_cfg->method, TRUE));
3759 g_assert (strlen (callee_cfg->asm_symbol) < 1000);
3760 sprintf (direct_call_target, "%s", callee_cfg->asm_symbol);
3761 patch_info->type = MONO_PATCH_INFO_NONE;
3762 acfg->stats.direct_calls ++;
3765 acfg->stats.all_calls ++;
3766 } else if ((patch_info->type == MONO_PATCH_INFO_ICALL_ADDR) && (patch_info->data.method->flags & METHOD_ATTRIBUTE_PINVOKE_IMPL)) {
3767 if (!got_only && is_direct_callable (acfg, method, patch_info)) {
3769 direct_pinvoke = get_pinvoke_import (acfg, patch_info->data.method);
3770 g_assert (strlen (direct_pinvoke) < 1000);
3771 sprintf (direct_call_target, "%s", direct_pinvoke);
3772 patch_info->type = MONO_PATCH_INFO_NONE;
3773 acfg->stats.direct_calls ++;
3777 if (!got_only && !direct_call) {
3778 MonoPltEntry *plt_entry = get_plt_entry (acfg, patch_info);
3780 /* This patch has a PLT entry, so we must emit a call to the PLT entry */
3782 sprintf (direct_call_target, "%s", plt_entry->symbol);
3784 /* Nullify the patch */
3785 patch_info->type = MONO_PATCH_INFO_NONE;
3786 plt_entry->jit_used = TRUE;
3793 arch_emit_direct_call (acfg, direct_call_target, &call_size);
3798 got_slot = get_got_offset (acfg, patch_info);
3800 arch_emit_got_access (acfg, code + i, got_slot, &code_size);
3807 #endif /* MONO_ARCH_AOT_SUPPORTED */
3810 /* Find next patch */
3812 for (pindex = start_index; pindex < patches->len; ++pindex) {
3813 patch_info = g_ptr_array_index (patches, pindex);
3814 if (patch_info->ip.i >= i)
3818 /* Try to emit multiple bytes at once */
3819 if (pindex < patches->len && patch_info->ip.i > i) {
3820 emit_bytes (acfg, code + i, patch_info->ip.i - i);
3821 i = patch_info->ip.i - 1;
3823 emit_bytes (acfg, code + i, 1);
3832 * Modify SYMBOL so it only includes characters permissible in symbols.
3835 sanitize_symbol (char *symbol)
3837 int i, len = strlen (symbol);
3839 for (i = 0; i < len; ++i)
3840 if (!isalnum (symbol [i]) && (symbol [i] != '_'))
3845 get_debug_sym (MonoMethod *method, const char *prefix, GHashTable *cache)
3847 char *name1, *name2, *cached;
3848 int i, j, len, count;
3850 name1 = mono_method_full_name (method, TRUE);
3851 len = strlen (name1);
3852 name2 = malloc (strlen (prefix) + len + 16);
3853 memcpy (name2, prefix, strlen (prefix));
3854 j = strlen (prefix);
3855 for (i = 0; i < len; ++i) {
3856 if (isalnum (name1 [i])) {
3857 name2 [j ++] = name1 [i];
3858 } else if (name1 [i] == ' ' && name1 [i + 1] == '(' && name1 [i + 2] == ')') {
3860 } else if (name1 [i] == ',' && name1 [i + 1] == ' ') {
3863 } else if (name1 [i] == '(' || name1 [i] == ')' || name1 [i] == '>') {
3872 while (g_hash_table_lookup (cache, name2)) {
3873 sprintf (name2 + j, "_%d", count);
3877 cached = g_strdup (name2);
3878 g_hash_table_insert (cache, cached, cached);
3884 emit_method_code (MonoAotCompile *acfg, MonoCompile *cfg)
3889 char *debug_sym = NULL;
3891 int func_alignment = AOT_FUNC_ALIGNMENT;
3892 MonoMethodHeader *header;
3895 method = cfg->orig_method;
3896 code = cfg->native_code;
3897 header = cfg->header;
3899 method_index = get_method_index (acfg, method);
3901 /* Make the labels local */
3902 sprintf (symbol, "%s", cfg->asm_symbol);
3904 emit_section_change (acfg, ".text", 0);
3905 emit_alignment (acfg, func_alignment);
3906 emit_label (acfg, symbol);
3908 if (acfg->aot_opts.write_symbols) {
3910 * Write a C style symbol for every method, this has two uses:
3911 * - it works on platforms where the dwarf debugging info is not
3913 * - it allows the setting of breakpoints of aot-ed methods.
3915 debug_sym = get_debug_sym (method, "", acfg->method_label_hash);
3917 sprintf (symbol, "%sme_%x", acfg->temp_prefix, method_index);
3918 if (acfg->need_no_dead_strip)
3919 fprintf (acfg->fp, " .no_dead_strip %s\n", debug_sym);
3920 emit_local_symbol (acfg, debug_sym, symbol, TRUE);
3921 emit_label (acfg, debug_sym);
3924 export_name = g_hash_table_lookup (acfg->export_names, method);
3926 /* Emit a global symbol for the method */
3927 emit_global_inner (acfg, export_name, TRUE);
3928 emit_label (acfg, export_name);
3931 if (cfg->verbose_level > 0)
3932 g_print ("Method %s emitted as %s\n", mono_method_full_name (method, TRUE), symbol);
3934 acfg->stats.code_size += cfg->code_len;
3936 acfg->cfgs [method_index]->got_offset = acfg->got_offset;
3938 emit_and_reloc_code (acfg, method, code, cfg->code_len, cfg->patch_info, FALSE);
3942 if (acfg->aot_opts.write_symbols) {
3943 emit_symbol_size (acfg, debug_sym, ".");
3947 sprintf (symbol, "%sme_%x", acfg->temp_prefix, method_index);
3948 emit_label (acfg, symbol);
3954 * Encode PATCH_INFO into its disk representation.
3957 encode_patch (MonoAotCompile *acfg, MonoJumpInfo *patch_info, guint8 *buf, guint8 **endbuf)
3961 switch (patch_info->type) {
3962 case MONO_PATCH_INFO_NONE:
3964 case MONO_PATCH_INFO_IMAGE:
3965 encode_value (get_image_index (acfg, patch_info->data.image), p, &p);
3967 case MONO_PATCH_INFO_MSCORLIB_GOT_ADDR:
3968 case MONO_PATCH_INFO_GC_CARD_TABLE_ADDR:
3969 case MONO_PATCH_INFO_CASTCLASS_CACHE:
3971 case MONO_PATCH_INFO_METHOD_REL:
3972 encode_value ((gint)patch_info->data.offset, p, &p);
3974 case MONO_PATCH_INFO_SWITCH: {
3975 gpointer *table = (gpointer *)patch_info->data.table->table;
3978 encode_value (patch_info->data.table->table_size, p, &p);
3979 for (k = 0; k < patch_info->data.table->table_size; k++)
3980 encode_value ((int)(gssize)table [k], p, &p);
3983 case MONO_PATCH_INFO_METHODCONST:
3984 case MONO_PATCH_INFO_METHOD:
3985 case MONO_PATCH_INFO_METHOD_JUMP:
3986 case MONO_PATCH_INFO_ICALL_ADDR:
3987 case MONO_PATCH_INFO_METHOD_RGCTX:
3988 encode_method_ref (acfg, patch_info->data.method, p, &p);
3990 case MONO_PATCH_INFO_INTERNAL_METHOD:
3991 case MONO_PATCH_INFO_JIT_ICALL_ADDR: {
3992 guint32 len = strlen (patch_info->data.name);
3994 encode_value (len, p, &p);
3996 memcpy (p, patch_info->data.name, len);
4001 case MONO_PATCH_INFO_LDSTR: {
4002 guint32 image_index = get_image_index (acfg, patch_info->data.token->image);
4003 guint32 token = patch_info->data.token->token;
4004 g_assert (mono_metadata_token_code (token) == MONO_TOKEN_STRING);
4005 encode_value (image_index, p, &p);
4006 encode_value (patch_info->data.token->token - MONO_TOKEN_STRING, p, &p);
4009 case MONO_PATCH_INFO_RVA:
4010 case MONO_PATCH_INFO_DECLSEC:
4011 case MONO_PATCH_INFO_LDTOKEN:
4012 case MONO_PATCH_INFO_TYPE_FROM_HANDLE:
4013 encode_value (get_image_index (acfg, patch_info->data.token->image), p, &p);
4014 encode_value (patch_info->data.token->token, p, &p);
4015 encode_value (patch_info->data.token->has_context, p, &p);
4016 if (patch_info->data.token->has_context)
4017 encode_generic_context (acfg, &patch_info->data.token->context, p, &p);
4019 case MONO_PATCH_INFO_EXC_NAME: {
4020 MonoClass *ex_class;
4023 mono_class_from_name (mono_defaults.exception_class->image,
4024 "System", patch_info->data.target);
4025 g_assert (ex_class);
4026 encode_klass_ref (acfg, ex_class, p, &p);
4029 case MONO_PATCH_INFO_R4:
4030 encode_value (*((guint32 *)patch_info->data.target), p, &p);
4032 case MONO_PATCH_INFO_R8:
4033 encode_value (((guint32 *)patch_info->data.target) [MINI_LS_WORD_IDX], p, &p);
4034 encode_value (((guint32 *)patch_info->data.target) [MINI_MS_WORD_IDX], p, &p);
4036 case MONO_PATCH_INFO_VTABLE:
4037 case MONO_PATCH_INFO_CLASS:
4038 case MONO_PATCH_INFO_IID:
4039 case MONO_PATCH_INFO_ADJUSTED_IID:
4040 encode_klass_ref (acfg, patch_info->data.klass, p, &p);
4042 case MONO_PATCH_INFO_CLASS_INIT:
4043 case MONO_PATCH_INFO_DELEGATE_TRAMPOLINE:
4044 encode_klass_ref (acfg, patch_info->data.klass, p, &p);
4046 case MONO_PATCH_INFO_FIELD:
4047 case MONO_PATCH_INFO_SFLDA:
4048 encode_field_info (acfg, patch_info->data.field, p, &p);
4050 case MONO_PATCH_INFO_INTERRUPTION_REQUEST_FLAG:
4052 case MONO_PATCH_INFO_RGCTX_FETCH: {
4053 MonoJumpInfoRgctxEntry *entry = patch_info->data.rgctx_entry;
4058 * entry->method has a lenghtly encoding and multiple rgctx_fetch entries
4059 * reference the same method, so encode the method only once.
4061 offset = GPOINTER_TO_UINT (g_hash_table_lookup (acfg->method_blob_hash, entry->method));
4063 buf2 = g_malloc (1024);
4066 encode_method_ref (acfg, entry->method, p2, &p2);
4067 g_assert (p2 - buf2 < 1024);
4069 offset = add_to_blob (acfg, buf2, p2 - buf2);
4072 g_hash_table_insert (acfg->method_blob_hash, entry->method, GUINT_TO_POINTER (offset + 1));
4077 encode_value (offset, p, &p);
4078 g_assert (entry->info_type < 256);
4079 g_assert (entry->data->type < 256);
4080 encode_value ((entry->in_mrgctx ? 1 : 0) | (entry->info_type << 1) | (entry->data->type << 9), p, &p);
4081 encode_patch (acfg, entry->data, p, &p);
4084 case MONO_PATCH_INFO_GENERIC_CLASS_INIT:
4085 case MONO_PATCH_INFO_MONITOR_ENTER:
4086 case MONO_PATCH_INFO_MONITOR_EXIT:
4087 case MONO_PATCH_INFO_SEQ_POINT_INFO:
4089 case MONO_PATCH_INFO_LLVM_IMT_TRAMPOLINE:
4090 encode_method_ref (acfg, patch_info->data.imt_tramp->method, p, &p);
4091 encode_value (patch_info->data.imt_tramp->vt_offset, p, &p);
4093 case MONO_PATCH_INFO_SIGNATURE:
4094 encode_signature (acfg, (MonoMethodSignature*)patch_info->data.target, p, &p);
4097 g_warning ("unable to handle jump info %d", patch_info->type);
4098 g_assert_not_reached ();
4105 encode_patch_list (MonoAotCompile *acfg, GPtrArray *patches, int n_patches, int first_got_offset, guint8 *buf, guint8 **endbuf)
4108 guint32 pindex, offset;
4109 MonoJumpInfo *patch_info;
4111 encode_value (n_patches, p, &p);
4113 for (pindex = 0; pindex < patches->len; ++pindex) {
4114 patch_info = g_ptr_array_index (patches, pindex);
4116 if (patch_info->type == MONO_PATCH_INFO_NONE || patch_info->type == MONO_PATCH_INFO_BB)
4120 offset = get_got_offset (acfg, patch_info);
4121 encode_value (offset, p, &p);
4128 emit_method_info (MonoAotCompile *acfg, MonoCompile *cfg)
4132 int pindex, buf_size, n_patches;
4134 MonoJumpInfo *patch_info;
4135 MonoMethodHeader *header;
4136 guint32 method_index;
4138 guint32 first_got_offset;
4140 method = cfg->orig_method;
4141 header = mono_method_get_header (method);
4143 method_index = get_method_index (acfg, method);
4145 /* Sort relocations */
4146 patches = g_ptr_array_new ();
4147 for (patch_info = cfg->patch_info; patch_info; patch_info = patch_info->next)
4148 g_ptr_array_add (patches, patch_info);
4149 g_ptr_array_sort (patches, compare_patches);
4151 first_got_offset = acfg->cfgs [method_index]->got_offset;
4153 /**********************/
4154 /* Encode method info */
4155 /**********************/
4157 buf_size = (patches->len < 1000) ? 40960 : 40960 + (patches->len * 64);
4158 p = buf = g_malloc (buf_size);
4160 if (mono_class_get_cctor (method->klass))
4161 encode_klass_ref (acfg, method->klass, p, &p);
4163 /* Not needed when loading the method */
4164 encode_value (0, p, &p);
4167 if (cfg->opt & MONO_OPT_SHARED) {
4168 encode_value (g_list_length (cfg->ldstr_list), p, &p);
4169 for (l = cfg->ldstr_list; l; l = l->next) {
4170 encode_value ((long)l->data, p, &p);
4174 /* Used only in shared mode */
4175 g_assert (!cfg->ldstr_list);
4178 for (pindex = 0; pindex < patches->len; ++pindex) {
4179 patch_info = g_ptr_array_index (patches, pindex);
4181 if ((patch_info->type == MONO_PATCH_INFO_GOT_OFFSET) ||
4182 (patch_info->type == MONO_PATCH_INFO_NONE)) {
4183 patch_info->type = MONO_PATCH_INFO_NONE;
4188 if ((patch_info->type == MONO_PATCH_INFO_IMAGE) && (patch_info->data.image == acfg->image)) {
4189 /* Stored in a GOT slot initialized at module load time */
4190 patch_info->type = MONO_PATCH_INFO_NONE;
4194 if (patch_info->type == MONO_PATCH_INFO_GC_CARD_TABLE_ADDR) {
4195 /* Stored in a GOT slot initialized at module load time */
4196 patch_info->type = MONO_PATCH_INFO_NONE;
4200 if (is_plt_patch (patch_info)) {
4201 /* Calls are made through the PLT */
4202 patch_info->type = MONO_PATCH_INFO_NONE;
4210 g_assert (cfg->has_got_slots);
4212 encode_patch_list (acfg, patches, n_patches, first_got_offset, p, &p);
4214 acfg->stats.info_size += p - buf;
4216 g_assert (p - buf < buf_size);
4218 cfg->method_info_offset = add_to_blob (acfg, buf, p - buf);
4223 get_unwind_info_offset (MonoAotCompile *acfg, guint8 *encoded, guint32 encoded_len)
4225 guint32 cache_index;
4228 /* Reuse the unwind module to canonize and store unwind info entries */
4229 cache_index = mono_cache_unwind_info (encoded, encoded_len);
4231 /* Use +/- 1 to distinguish 0s from missing entries */
4232 offset = GPOINTER_TO_UINT (g_hash_table_lookup (acfg->unwind_info_offsets, GUINT_TO_POINTER (cache_index + 1)));
4240 * It would be easier to use assembler symbols, but the caller needs an
4243 offset = acfg->unwind_info_offset;
4244 g_hash_table_insert (acfg->unwind_info_offsets, GUINT_TO_POINTER (cache_index + 1), GUINT_TO_POINTER (offset + 1));
4245 g_ptr_array_add (acfg->unwind_ops, GUINT_TO_POINTER (cache_index));
4248 encode_value (encoded_len, p, &p);
4250 acfg->unwind_info_offset += encoded_len + (p - buf);
4256 emit_exception_debug_info (MonoAotCompile *acfg, MonoCompile *cfg)
4259 int i, k, buf_size, method_index;
4260 guint32 debug_info_size;
4262 MonoMethodHeader *header;
4263 guint8 *p, *buf, *debug_info;
4264 MonoJitInfo *jinfo = cfg->jit_info;
4266 gboolean use_unwind_ops = FALSE;
4267 MonoSeqPointInfo *seq_points;
4269 method = cfg->orig_method;
4270 code = cfg->native_code;
4271 header = cfg->header;
4273 method_index = get_method_index (acfg, method);
4275 if (!acfg->aot_opts.nodebug) {
4276 mono_debug_serialize_debug_info (cfg, &debug_info, &debug_info_size);
4279 debug_info_size = 0;
4282 seq_points = cfg->seq_point_info;
4284 buf_size = header->num_clauses * 256 + debug_info_size + 2048 + (seq_points ? (seq_points->len * 64) : 0) + cfg->gc_map_size;
4285 p = buf = g_malloc (buf_size);
4287 #ifdef MONO_ARCH_HAVE_XP_UNWIND
4288 use_unwind_ops = cfg->unwind_ops != NULL;
4291 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);
4293 encode_value (flags, p, &p);
4295 if (use_unwind_ops) {
4296 guint32 encoded_len;
4300 * This is a duplicate of the data in the .debug_frame section, but that
4301 * section cannot be accessed using the dl interface.
4303 encoded = mono_unwind_ops_encode (cfg->unwind_ops, &encoded_len);
4304 encode_value (get_unwind_info_offset (acfg, encoded, encoded_len), p, &p);
4307 encode_value (jinfo->used_regs, p, &p);
4310 /*Encode the number of holes before the number of clauses to make decoding easier*/
4311 if (jinfo->has_try_block_holes) {
4312 MonoTryBlockHoleTableJitInfo *table = mono_jit_info_get_try_block_hole_table_info (jinfo);
4313 encode_value (table->num_holes, p, &p);
4316 /* Exception table */
4317 if (cfg->compile_llvm) {
4319 * When using LLVM, we can't emit some data, like pc offsets, this reg/offset etc.,
4320 * since the information is only available to llc. Instead, we let llc save the data
4321 * into the LSDA, and read it from there at runtime.
4323 /* The assembly might be CIL stripped so emit the data ourselves */
4324 if (header->num_clauses)
4325 encode_value (header->num_clauses, p, &p);
4327 for (k = 0; k < header->num_clauses; ++k) {
4328 MonoExceptionClause *clause;
4330 clause = &header->clauses [k];
4332 encode_value (clause->flags, p, &p);
4333 if (clause->data.catch_class) {
4334 encode_value (1, p, &p);
4335 encode_klass_ref (acfg, clause->data.catch_class, p, &p);
4337 encode_value (0, p, &p);
4340 /* Emit a list of nesting clauses */
4341 for (i = 0; i < header->num_clauses; ++i) {
4343 MonoExceptionClause *clause1 = &header->clauses [cindex1];
4345 MonoExceptionClause *clause2 = &header->clauses [cindex2];
4347 if (cindex1 != cindex2 && clause1->try_offset >= clause2->try_offset && clause1->handler_offset <= clause2->handler_offset)
4348 encode_value (i, p, &p);
4350 encode_value (-1, p, &p);
4353 if (jinfo->num_clauses)
4354 encode_value (jinfo->num_clauses, p, &p);
4356 for (k = 0; k < jinfo->num_clauses; ++k) {
4357 MonoJitExceptionInfo *ei = &jinfo->clauses [k];
4359 encode_value (ei->flags, p, &p);
4360 encode_value (ei->exvar_offset, p, &p);
4362 if (ei->flags == MONO_EXCEPTION_CLAUSE_FILTER || ei->flags == MONO_EXCEPTION_CLAUSE_FINALLY)
4363 encode_value ((gint)((guint8*)ei->data.filter - code), p, &p);
4365 if (ei->data.catch_class) {
4366 encode_value (1, p, &p);
4367 encode_klass_ref (acfg, ei->data.catch_class, p, &p);
4369 encode_value (0, p, &p);
4373 encode_value ((gint)((guint8*)ei->try_start - code), p, &p);
4374 encode_value ((gint)((guint8*)ei->try_end - code), p, &p);
4375 encode_value ((gint)((guint8*)ei->handler_start - code), p, &p);
4379 if (jinfo->has_generic_jit_info) {
4380 MonoGenericJitInfo *gi = mono_jit_info_get_generic_jit_info (jinfo);
4384 encode_value (gi->nlocs, p, &p);
4386 for (i = 0; i < gi->nlocs; ++i) {
4387 MonoDwarfLocListEntry *entry = &gi->locations [i];
4389 encode_value (entry->is_reg ? 1 : 0, p, &p);
4390 encode_value (entry->reg, p, &p);
4392 encode_value (entry->offset, p, &p);
4394 g_assert (entry->from == 0);
4396 encode_value (entry->from, p, &p);
4397 encode_value (entry->to, p, &p);
4400 if (!cfg->compile_llvm) {
4401 encode_value (gi->has_this ? 1 : 0, p, &p);
4402 encode_value (gi->this_reg, p, &p);
4403 encode_value (gi->this_offset, p, &p);
4408 * Need to encode jinfo->method too, since it is not equal to 'method'
4409 * when using generic sharing.
4411 encode_method_ref (acfg, jinfo->method, p, &p);
4414 if (jinfo->has_try_block_holes) {
4415 MonoTryBlockHoleTableJitInfo *table = mono_jit_info_get_try_block_hole_table_info (jinfo);
4416 for (i = 0; i < table->num_holes; ++i) {
4417 MonoTryBlockHoleJitInfo *hole = &table->holes [i];
4418 encode_value (hole->clause, p, &p);
4419 encode_value (hole->length, p, &p);
4420 encode_value (hole->offset, p, &p);
4424 if (jinfo->has_arch_eh_info) {
4425 MonoArchEHJitInfo *eh_info;
4427 eh_info = mono_jit_info_get_arch_eh_info (jinfo);
4428 encode_value (eh_info->stack_size, p, &p);
4432 int il_offset, native_offset, last_il_offset, last_native_offset, j;
4434 encode_value (seq_points->len, p, &p);
4435 last_il_offset = last_native_offset = 0;
4436 for (i = 0; i < seq_points->len; ++i) {
4437 SeqPoint *sp = &seq_points->seq_points [i];
4438 il_offset = sp->il_offset;
4439 native_offset = sp->native_offset;
4440 encode_value (il_offset - last_il_offset, p, &p);
4441 encode_value (native_offset - last_native_offset, p, &p);
4442 last_il_offset = il_offset;
4443 last_native_offset = native_offset;
4445 encode_value (sp->next_len, p, &p);
4446 for (j = 0; j < sp->next_len; ++j)
4447 encode_value (sp->next [j], p, &p);
4451 g_assert (debug_info_size < buf_size);
4453 encode_value (debug_info_size, p, &p);
4454 if (debug_info_size) {
4455 memcpy (p, debug_info, debug_info_size);
4456 p += debug_info_size;
4457 g_free (debug_info);
4462 encode_value (cfg->gc_map_size, p, &p);
4463 /* The GC map requires 4 bytes of alignment */
4464 while ((gsize)p % 4)
4466 memcpy (p, cfg->gc_map, cfg->gc_map_size);
4467 p += cfg->gc_map_size;
4470 acfg->stats.ex_info_size += p - buf;
4472 g_assert (p - buf < buf_size);
4475 /* The GC Map requires 4 byte alignment */
4476 cfg->ex_info_offset = add_to_blob_aligned (acfg, buf, p - buf, cfg->gc_map ? 4 : 1);
4481 emit_klass_info (MonoAotCompile *acfg, guint32 token)
4483 MonoClass *klass = mono_class_get (acfg->image, token);
4485 int i, buf_size, res;
4486 gboolean no_special_static, cant_encode;
4487 gpointer iter = NULL;
4490 mono_loader_clear_error ();
4494 p = buf = g_malloc (buf_size);
4496 /* Mark as unusable */
4497 encode_value (-1, p, &p);
4499 res = add_to_blob (acfg, buf, p - buf);
4505 buf_size = 10240 + (klass->vtable_size * 16);
4506 p = buf = g_malloc (buf_size);
4510 mono_class_init (klass);
4512 mono_class_get_nested_types (klass, &iter);
4513 g_assert (klass->nested_classes_inited);
4515 mono_class_setup_vtable (klass);
4518 * Emit all the information which is required for creating vtables so
4519 * the runtime does not need to create the MonoMethod structures which
4520 * take up a lot of space.
4523 no_special_static = !mono_class_has_special_static_fields (klass);
4525 /* Check whenever we have enough info to encode the vtable */
4526 cant_encode = FALSE;
4527 for (i = 0; i < klass->vtable_size; ++i) {
4528 MonoMethod *cm = klass->vtable [i];
4530 if (cm && mono_method_signature (cm)->is_inflated && !g_hash_table_lookup (acfg->token_info_hash, cm))
4534 mono_class_has_finalizer (klass);
4536 if (klass->generic_container || cant_encode) {
4537 encode_value (-1, p, &p);
4539 encode_value (klass->vtable_size, p, &p);
4540 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);
4541 if (klass->has_cctor)
4542 encode_method_ref (acfg, mono_class_get_cctor (klass), p, &p);
4543 if (klass->has_finalize)
4544 encode_method_ref (acfg, mono_class_get_finalizer (klass), p, &p);
4546 encode_value (klass->instance_size, p, &p);
4547 encode_value (mono_class_data_size (klass), p, &p);
4548 encode_value (klass->packing_size, p, &p);
4549 encode_value (klass->min_align, p, &p);
4551 for (i = 0; i < klass->vtable_size; ++i) {
4552 MonoMethod *cm = klass->vtable [i];
4555 encode_method_ref (acfg, cm, p, &p);
4557 encode_value (0, p, &p);
4561 acfg->stats.class_info_size += p - buf;
4563 g_assert (p - buf < buf_size);
4564 res = add_to_blob (acfg, buf, p - buf);
4571 get_plt_entry_debug_sym (MonoAotCompile *acfg, MonoJumpInfo *ji, GHashTable *cache)
4573 char *debug_sym = NULL;
4576 case MONO_PATCH_INFO_METHOD:
4577 debug_sym = get_debug_sym (ji->data.method, "plt_", cache);
4579 case MONO_PATCH_INFO_INTERNAL_METHOD:
4580 debug_sym = g_strdup_printf ("plt__jit_icall_%s", ji->data.name);
4582 case MONO_PATCH_INFO_CLASS_INIT:
4583 debug_sym = g_strdup_printf ("plt__class_init_%s", mono_type_get_name (&ji->data.klass->byval_arg));
4584 sanitize_symbol (debug_sym);
4586 case MONO_PATCH_INFO_RGCTX_FETCH:
4587 debug_sym = g_strdup_printf ("plt__rgctx_fetch_%d", acfg->label_generator ++);
4589 case MONO_PATCH_INFO_ICALL_ADDR: {
4590 char *s = get_debug_sym (ji->data.method, "", cache);
4592 debug_sym = g_strdup_printf ("plt__icall_native_%s", s);
4596 case MONO_PATCH_INFO_JIT_ICALL_ADDR:
4597 debug_sym = g_strdup_printf ("plt__jit_icall_native_%s", ji->data.name);
4599 case MONO_PATCH_INFO_GENERIC_CLASS_INIT:
4600 debug_sym = g_strdup_printf ("plt__generic_class_init");
4610 * Calls made from AOTed code are routed through a table of jumps similar to the
4611 * ELF PLT (Program Linkage Table). Initially the PLT entries jump to code which transfers
4612 * control to the AOT runtime through a trampoline.
4615 emit_plt (MonoAotCompile *acfg)
4621 sprintf (symbol, "plt");
4623 emit_section_change (acfg, ".text", 0);
4624 emit_alignment (acfg, NACL_SIZE(16, kNaClAlignment));
4625 emit_label (acfg, symbol);
4626 emit_label (acfg, acfg->plt_symbol);
4628 for (i = 0; i < acfg->plt_offset; ++i) {
4629 char *debug_sym = NULL;
4630 MonoPltEntry *plt_entry = NULL;
4635 * The first plt entry is unused.
4639 plt_entry = g_hash_table_lookup (acfg->plt_offset_to_entry, GUINT_TO_POINTER (i));
4644 * If the target is directly callable, alias the plt symbol to point to
4646 * FIXME: Use this to simplify emit_and_reloc_code ().
4647 * FIXME: Avoid the got slot.
4648 * FIXME: Add support to the binary writer.
4650 if (ji && is_direct_callable (acfg, NULL, ji) && !acfg->use_bin_writer) {
4651 MonoCompile *callee_cfg = g_hash_table_lookup (acfg->method_to_cfg, ji->data.method);
4653 if (acfg->thumb_mixed && !callee_cfg->compile_llvm) {
4654 /* LLVM calls the PLT entries using bl, so emit a stub */
4655 fprintf (acfg->fp, "\n.thumb_func\n");
4656 emit_label (acfg, plt_entry->llvm_symbol);
4657 fprintf (acfg->fp, "bx pc\n");
4658 fprintf (acfg->fp, "nop\n");
4659 fprintf (acfg->fp, ".arm\n");
4660 fprintf (acfg->fp, "b %s\n", callee_cfg->asm_symbol);
4662 fprintf (acfg->fp, "\n.set %s, %s\n", plt_entry->llvm_symbol, callee_cfg->asm_symbol);
4668 debug_sym = plt_entry->debug_sym;
4670 if (acfg->thumb_mixed && !plt_entry->jit_used)
4671 /* Emit only a thumb version */
4674 if (!acfg->thumb_mixed)
4675 emit_label (acfg, plt_entry->llvm_symbol);
4678 if (acfg->need_no_dead_strip)
4679 fprintf (acfg->fp, " .no_dead_strip %s\n", debug_sym);
4680 emit_local_symbol (acfg, debug_sym, NULL, TRUE);
4681 emit_label (acfg, debug_sym);
4684 emit_label (acfg, plt_entry->symbol);
4686 arch_emit_plt_entry (acfg, i);
4689 emit_symbol_size (acfg, debug_sym, ".");
4692 if (acfg->thumb_mixed) {
4693 /* Make sure the ARM symbols don't alias the thumb ones */
4694 emit_zero_bytes (acfg, 16);
4697 * Emit a separate set of PLT entries using thumb2 which is called by LLVM generated
4700 for (i = 0; i < acfg->plt_offset; ++i) {
4701 char *debug_sym = NULL;
4702 MonoPltEntry *plt_entry = NULL;
4708 plt_entry = g_hash_table_lookup (acfg->plt_offset_to_entry, GUINT_TO_POINTER (i));
4711 if (ji && is_direct_callable (acfg, NULL, ji) && !acfg->use_bin_writer)
4714 /* Skip plt entries not actually called by LLVM code */
4715 if (!plt_entry->llvm_used)
4718 if (acfg->aot_opts.write_symbols) {
4719 if (plt_entry->debug_sym)
4720 debug_sym = g_strdup_printf ("%s_thumb", plt_entry->debug_sym);
4724 #if defined(__APPLE__)
4725 fprintf (acfg->fp, " .thumb_func %s\n", debug_sym);
4726 fprintf (acfg->fp, " .no_dead_strip %s\n", debug_sym);
4728 emit_local_symbol (acfg, debug_sym, NULL, TRUE);
4729 emit_label (acfg, debug_sym);
4731 fprintf (acfg->fp, "\n.thumb_func\n");
4733 emit_label (acfg, plt_entry->llvm_symbol);
4735 arch_emit_llvm_plt_entry (acfg, i);
4738 emit_symbol_size (acfg, debug_sym, ".");
4744 emit_symbol_size (acfg, acfg->plt_symbol, ".");
4746 sprintf (symbol, "plt_end");
4747 emit_label (acfg, symbol);
4750 static G_GNUC_UNUSED void
4751 emit_trampoline (MonoAotCompile *acfg, int got_offset, MonoTrampInfo *info)
4753 char start_symbol [256];
4755 guint32 buf_size, info_offset;
4756 MonoJumpInfo *patch_info;
4767 code_size = info->code_size;
4769 unwind_ops = info->unwind_ops;
4771 #ifdef __native_client_codegen__
4772 mono_nacl_fix_patches (code, ji);
4777 sprintf (start_symbol, "%s", name);
4779 emit_section_change (acfg, ".text", 0);
4780 emit_global (acfg, start_symbol, TRUE);
4781 emit_alignment (acfg, AOT_FUNC_ALIGNMENT);
4782 emit_label (acfg, start_symbol);
4784 sprintf (symbol, "%snamed_%s", acfg->temp_prefix, name);
4785 emit_label (acfg, symbol);
4788 * The code should access everything through the GOT, so we pass
4791 emit_and_reloc_code (acfg, NULL, code, code_size, ji, TRUE);
4793 emit_symbol_size (acfg, start_symbol, ".");
4797 /* Sort relocations */
4798 patches = g_ptr_array_new ();
4799 for (patch_info = ji; patch_info; patch_info = patch_info->next)
4800 if (patch_info->type != MONO_PATCH_INFO_NONE)
4801 g_ptr_array_add (patches, patch_info);
4802 g_ptr_array_sort (patches, compare_patches);
4804 buf_size = patches->len * 128 + 128;
4805 buf = g_malloc (buf_size);
4808 encode_patch_list (acfg, patches, patches->len, got_offset, p, &p);
4809 g_assert (p - buf < buf_size);
4811 sprintf (symbol, "%s_p", name);
4813 info_offset = add_to_blob (acfg, buf, p - buf);
4815 emit_section_change (acfg, RODATA_SECT, 0);
4816 emit_global (acfg, symbol, FALSE);
4817 emit_label (acfg, symbol);
4819 emit_int32 (acfg, info_offset);
4821 /* Emit debug info */
4825 sprintf (symbol, "%s", name);
4826 sprintf (symbol2, "%snamed_%s", acfg->temp_prefix, name);
4829 mono_dwarf_writer_emit_trampoline (acfg->dwarf, symbol, symbol2, NULL, NULL, code_size, unwind_ops);
4834 emit_trampolines (MonoAotCompile *acfg)
4837 char end_symbol [256];
4838 int i, tramp_got_offset;
4839 MonoAotTrampoline ntype;
4840 #ifdef MONO_ARCH_HAVE_FULL_AOT_TRAMPOLINES
4844 if (!acfg->aot_opts.full_aot)
4847 g_assert (acfg->image->assembly);
4849 /* Currently, we emit most trampolines into the mscorlib AOT image. */
4850 if (strcmp (acfg->image->assembly->aname.name, "mscorlib") == 0) {
4851 #ifdef MONO_ARCH_HAVE_FULL_AOT_TRAMPOLINES
4852 MonoTrampInfo *info;
4855 * Emit the generic trampolines.
4857 * We could save some code by treating the generic trampolines as a wrapper
4858 * method, but that approach has its own complexities, so we choose the simpler
4861 for (tramp_type = 0; tramp_type < MONO_TRAMPOLINE_NUM; ++tramp_type) {
4862 mono_arch_create_generic_trampoline (tramp_type, &info, TRUE);
4863 emit_trampoline (acfg, acfg->got_offset, info);
4866 mono_arch_get_nullified_class_init_trampoline (&info);
4867 emit_trampoline (acfg, acfg->got_offset, info);
4868 #if defined(MONO_ARCH_MONITOR_OBJECT_REG)
4869 mono_arch_create_monitor_enter_trampoline (&info, TRUE);
4870 emit_trampoline (acfg, acfg->got_offset, info);
4871 mono_arch_create_monitor_exit_trampoline (&info, TRUE);
4872 emit_trampoline (acfg, acfg->got_offset, info);
4875 mono_arch_create_generic_class_init_trampoline (&info, TRUE);
4876 emit_trampoline (acfg, acfg->got_offset, info);
4878 /* Emit the exception related code pieces */
4879 mono_arch_get_restore_context (&info, TRUE);
4880 emit_trampoline (acfg, acfg->got_offset, info);
4881 mono_arch_get_call_filter (&info, TRUE);
4882 emit_trampoline (acfg, acfg->got_offset, info);
4883 mono_arch_get_throw_exception (&info, TRUE);
4884 emit_trampoline (acfg, acfg->got_offset, info);
4885 mono_arch_get_rethrow_exception (&info, TRUE);
4886 emit_trampoline (acfg, acfg->got_offset, info);
4887 mono_arch_get_throw_corlib_exception (&info, TRUE);
4888 emit_trampoline (acfg, acfg->got_offset, info);
4890 #if defined(MONO_ARCH_HAVE_GET_TRAMPOLINES)
4892 GSList *l = mono_arch_get_trampolines (TRUE);
4895 MonoTrampInfo *info = l->data;
4897 emit_trampoline (acfg, acfg->got_offset, info);
4903 for (i = 0; i < 128; ++i) {
4906 offset = MONO_RGCTX_SLOT_MAKE_RGCTX (i);
4907 mono_arch_create_rgctx_lazy_fetch_trampoline (offset, &info, TRUE);
4908 emit_trampoline (acfg, acfg->got_offset, info);
4910 offset = MONO_RGCTX_SLOT_MAKE_MRGCTX (i);
4911 mono_arch_create_rgctx_lazy_fetch_trampoline (offset, &info, TRUE);
4912 emit_trampoline (acfg, acfg->got_offset, info);
4918 /* delegate_invoke_impl trampolines */
4919 l = mono_arch_get_delegate_invoke_impls ();
4921 MonoTrampInfo *info = l->data;
4923 emit_trampoline (acfg, acfg->got_offset, info);
4928 #endif /* #ifdef MONO_ARCH_HAVE_FULL_AOT_TRAMPOLINES */
4930 /* Emit trampolines which are numerous */
4933 * These include the following:
4934 * - specific trampolines
4935 * - static rgctx invoke trampolines
4937 * These trampolines have the same code, they are parameterized by GOT
4939 * They are defined in this file, in the arch_... routines instead of
4940 * in tramp-<ARCH>.c, since it is easier to do it this way.
4944 * When running in aot-only mode, we can't create specific trampolines at
4945 * runtime, so we create a few, and save them in the AOT file.
4946 * Normal trampolines embed their argument as a literal inside the
4947 * trampoline code, we can't do that here, so instead we embed an offset
4948 * which needs to be added to the trampoline address to get the address of
4949 * the GOT slot which contains the argument value.
4950 * The generated trampolines jump to the generic trampolines using another
4951 * GOT slot, which will be setup by the AOT loader to point to the
4952 * generic trampoline code of the given type.
4956 * FIXME: Maybe we should use more specific trampolines (i.e. one class init for
4960 emit_section_change (acfg, ".text", 0);
4962 tramp_got_offset = acfg->got_offset;
4964 for (ntype = 0; ntype < MONO_AOT_TRAMP_NUM; ++ntype) {
4966 case MONO_AOT_TRAMP_SPECIFIC:
4967 sprintf (symbol, "specific_trampolines");
4969 case MONO_AOT_TRAMP_STATIC_RGCTX:
4970 sprintf (symbol, "static_rgctx_trampolines");
4972 case MONO_AOT_TRAMP_IMT_THUNK:
4973 sprintf (symbol, "imt_thunks");
4976 g_assert_not_reached ();
4979 sprintf (end_symbol, "%s_e", symbol);
4981 if (acfg->aot_opts.write_symbols)
4982 emit_local_symbol (acfg, symbol, end_symbol, TRUE);
4984 emit_alignment (acfg, AOT_FUNC_ALIGNMENT);
4985 emit_label (acfg, symbol);
4987 acfg->trampoline_got_offset_base [ntype] = tramp_got_offset;
4989 for (i = 0; i < acfg->num_trampolines [ntype]; ++i) {
4993 case MONO_AOT_TRAMP_SPECIFIC:
4994 arch_emit_specific_trampoline (acfg, tramp_got_offset, &tramp_size);
4995 tramp_got_offset += 2;
4997 case MONO_AOT_TRAMP_STATIC_RGCTX:
4998 arch_emit_static_rgctx_trampoline (acfg, tramp_got_offset, &tramp_size);
4999 tramp_got_offset += 2;
5001 case MONO_AOT_TRAMP_IMT_THUNK:
5002 arch_emit_imt_thunk (acfg, tramp_got_offset, &tramp_size);
5003 tramp_got_offset += 1;
5006 g_assert_not_reached ();
5008 #ifdef __native_client_codegen__
5009 /* align to avoid 32-byte boundary crossings */
5010 emit_alignment (acfg, AOT_FUNC_ALIGNMENT);
5013 if (!acfg->trampoline_size [ntype]) {
5014 g_assert (tramp_size);
5015 acfg->trampoline_size [ntype] = tramp_size;
5019 emit_label (acfg, end_symbol);
5022 /* Reserve some entries at the end of the GOT for our use */
5023 acfg->num_trampoline_got_entries = tramp_got_offset - acfg->got_offset;
5026 acfg->got_offset += acfg->num_trampoline_got_entries;
5030 str_begins_with (const char *str1, const char *str2)
5032 int len = strlen (str2);
5033 return strncmp (str1, str2, len) == 0;
5037 mono_aot_readonly_field_override (MonoClassField *field)
5040 for (rdv = readonly_values; rdv; rdv = rdv->next) {
5041 char *p = rdv->name;
5043 len = strlen (field->parent->name_space);
5044 if (strncmp (p, field->parent->name_space, len))
5049 len = strlen (field->parent->name);
5050 if (strncmp (p, field->parent->name, len))
5055 if (strcmp (p, field->name))
5057 switch (rdv->type) {
5059 return &rdv->value.i1;
5061 return &rdv->value.i2;
5063 return &rdv->value.i4;
5072 add_readonly_value (MonoAotOptions *opts, const char *val)
5077 /* the format of val is:
5078 * namespace.typename.fieldname=type/value
5079 * type can be i1 for uint8/int8/boolean, i2 for uint16/int16/char, i4 for uint32/int32
5081 fval = strrchr (val, '/');
5083 fprintf (stderr, "AOT : invalid format for readonly field '%s', missing /.\n", val);
5086 tval = strrchr (val, '=');
5088 fprintf (stderr, "AOT : invalid format for readonly field '%s', missing =.\n", val);
5091 rdv = g_new0 (ReadOnlyValue, 1);
5092 rdv->name = g_malloc0 (tval - val + 1);
5093 memcpy (rdv->name, val, tval - val);
5096 if (strncmp (tval, "i1", 2) == 0) {
5097 rdv->value.i1 = atoi (fval);
5098 rdv->type = MONO_TYPE_I1;
5099 } else if (strncmp (tval, "i2", 2) == 0) {
5100 rdv->value.i2 = atoi (fval);
5101 rdv->type = MONO_TYPE_I2;
5102 } else if (strncmp (tval, "i4", 2) == 0) {
5103 rdv->value.i4 = atoi (fval);
5104 rdv->type = MONO_TYPE_I4;
5106 fprintf (stderr, "AOT : unsupported type for readonly field '%s'.\n", tval);
5109 rdv->next = readonly_values;
5110 readonly_values = rdv;
5114 mono_aot_parse_options (const char *aot_options, MonoAotOptions *opts)
5116 gchar **args, **ptr;
5118 args = g_strsplit (aot_options ? aot_options : "", ",", -1);
5119 for (ptr = args; ptr && *ptr; ptr ++) {
5120 const char *arg = *ptr;
5122 if (str_begins_with (arg, "outfile=")) {
5123 opts->outfile = g_strdup (arg + strlen ("outfile="));
5124 } else if (str_begins_with (arg, "save-temps")) {
5125 opts->save_temps = TRUE;
5126 } else if (str_begins_with (arg, "keep-temps")) {
5127 opts->save_temps = TRUE;
5128 } else if (str_begins_with (arg, "write-symbols")) {
5129 opts->write_symbols = TRUE;
5130 } else if (str_begins_with (arg, "no-write-symbols")) {
5131 opts->write_symbols = FALSE;
5132 } else if (str_begins_with (arg, "metadata-only")) {
5133 opts->metadata_only = TRUE;
5134 } else if (str_begins_with (arg, "bind-to-runtime-version")) {
5135 opts->bind_to_runtime_version = TRUE;
5136 } else if (str_begins_with (arg, "full")) {
5137 opts->full_aot = TRUE;
5138 } else if (str_begins_with (arg, "threads=")) {
5139 opts->nthreads = atoi (arg + strlen ("threads="));
5140 } else if (str_begins_with (arg, "static")) {
5141 opts->static_link = TRUE;
5142 opts->no_dlsym = TRUE;
5143 } else if (str_begins_with (arg, "asmonly")) {
5144 opts->asm_only = TRUE;
5145 } else if (str_begins_with (arg, "asmwriter")) {
5146 opts->asm_writer = TRUE;
5147 } else if (str_begins_with (arg, "nodebug")) {
5148 opts->nodebug = TRUE;
5149 } else if (str_begins_with (arg, "ntrampolines=")) {
5150 opts->ntrampolines = atoi (arg + strlen ("ntrampolines="));
5151 } else if (str_begins_with (arg, "nrgctx-trampolines=")) {
5152 opts->nrgctx_trampolines = atoi (arg + strlen ("nrgctx-trampolines="));
5153 } else if (str_begins_with (arg, "nimt-trampolines=")) {
5154 opts->nimt_trampolines = atoi (arg + strlen ("nimt-trampolines="));
5155 } else if (str_begins_with (arg, "autoreg")) {
5156 opts->autoreg = TRUE;
5157 } else if (str_begins_with (arg, "tool-prefix=")) {
5158 opts->tool_prefix = g_strdup (arg + strlen ("tool-prefix="));
5159 } else if (str_begins_with (arg, "soft-debug")) {
5160 opts->soft_debug = TRUE;
5161 } else if (str_begins_with (arg, "direct-pinvoke")) {
5162 opts->direct_pinvoke = TRUE;
5163 } else if (str_begins_with (arg, "print-skipped")) {
5164 opts->print_skipped_methods = TRUE;
5165 } else if (str_begins_with (arg, "stats")) {
5167 } else if (str_begins_with (arg, "log-generics")) {
5168 opts->log_generics = TRUE;
5169 } else if (str_begins_with (arg, "mtriple=")) {
5170 opts->mtriple = g_strdup (arg + strlen ("mtriple="));
5171 } else if (str_begins_with (arg, "llvm-path=")) {
5172 opts->llvm_path = g_strdup (arg + strlen ("llvm-path="));
5173 } else if (str_begins_with (arg, "readonly-value=")) {
5174 add_readonly_value (opts, arg + strlen ("readonly-value="));
5175 } else if (str_begins_with (arg, "info")) {
5176 printf ("AOT target setup: %s.\n", AOT_TARGET_STR);
5178 } else if (str_begins_with (arg, "help") || str_begins_with (arg, "?")) {
5179 printf ("Supported options for --aot:\n");
5180 printf (" outfile=\n");
5181 printf (" save-temps\n");
5182 printf (" keep-temps\n");
5183 printf (" write-symbols\n");
5184 printf (" metadata-only\n");
5185 printf (" bind-to-runtime-version\n");
5187 printf (" threads=\n");
5188 printf (" static\n");
5189 printf (" asmonly\n");
5190 printf (" asmwriter\n");
5191 printf (" nodebug\n");
5192 printf (" ntrampolines=\n");
5193 printf (" nrgctx-trampolines=\n");
5194 printf (" nimt-trampolines=\n");
5195 printf (" autoreg\n");
5196 printf (" tool-prefix=\n");
5197 printf (" readonly-value=\n");
5198 printf (" soft-debug\n");
5199 printf (" print-skipped\n");
5200 printf (" stats\n");
5202 printf (" help/?\n");
5205 fprintf (stderr, "AOT : Unknown argument '%s'.\n", arg);
5214 add_token_info_hash (gpointer key, gpointer value, gpointer user_data)
5216 MonoMethod *method = (MonoMethod*)key;
5217 MonoJumpInfoToken *ji = (MonoJumpInfoToken*)value;
5218 MonoJumpInfoToken *new_ji = g_new0 (MonoJumpInfoToken, 1);
5219 MonoAotCompile *acfg = user_data;
5221 new_ji->image = ji->image;
5222 new_ji->token = ji->token;
5223 g_hash_table_insert (acfg->token_info_hash, method, new_ji);
5227 can_encode_class (MonoAotCompile *acfg, MonoClass *klass)
5229 if (klass->type_token)
5231 if ((klass->byval_arg.type == MONO_TYPE_VAR) || (klass->byval_arg.type == MONO_TYPE_MVAR) || (klass->byval_arg.type == MONO_TYPE_PTR))
5234 return can_encode_class (acfg, klass->element_class);
5239 can_encode_patch (MonoAotCompile *acfg, MonoJumpInfo *patch_info)
5241 switch (patch_info->type) {
5242 case MONO_PATCH_INFO_METHOD:
5243 case MONO_PATCH_INFO_METHODCONST: {
5244 MonoMethod *method = patch_info->data.method;
5246 if (method->wrapper_type) {
5247 switch (method->wrapper_type) {
5248 case MONO_WRAPPER_NONE:
5249 case MONO_WRAPPER_REMOTING_INVOKE_WITH_CHECK:
5250 case MONO_WRAPPER_XDOMAIN_INVOKE:
5251 case MONO_WRAPPER_STFLD:
5252 case MONO_WRAPPER_LDFLD:
5253 case MONO_WRAPPER_LDFLDA:
5254 case MONO_WRAPPER_LDFLD_REMOTE:
5255 case MONO_WRAPPER_STFLD_REMOTE:
5256 case MONO_WRAPPER_STELEMREF:
5257 case MONO_WRAPPER_ISINST:
5258 case MONO_WRAPPER_PROXY_ISINST:
5259 case MONO_WRAPPER_ALLOC:
5260 case MONO_WRAPPER_REMOTING_INVOKE:
5261 case MONO_WRAPPER_UNKNOWN:
5262 case MONO_WRAPPER_WRITE_BARRIER:
5264 case MONO_WRAPPER_MANAGED_TO_MANAGED:
5265 case MONO_WRAPPER_CASTCLASS: {
5266 WrapperInfo *info = mono_marshal_get_wrapper_info (method);
5275 //printf ("Skip (wrapper call): %d -> %s\n", patch_info->type, mono_method_full_name (patch_info->data.method, TRUE));
5279 if (!method->token) {
5280 /* The method is part of a constructed type like Int[,].Set (). */
5281 if (!g_hash_table_lookup (acfg->token_info_hash, method)) {
5282 if (method->klass->rank)
5290 case MONO_PATCH_INFO_VTABLE:
5291 case MONO_PATCH_INFO_CLASS_INIT:
5292 case MONO_PATCH_INFO_DELEGATE_TRAMPOLINE:
5293 case MONO_PATCH_INFO_CLASS:
5294 case MONO_PATCH_INFO_IID:
5295 case MONO_PATCH_INFO_ADJUSTED_IID:
5296 if (!can_encode_class (acfg, patch_info->data.klass)) {
5297 //printf ("Skip: %s\n", mono_type_full_name (&patch_info->data.klass->byval_arg));
5301 case MONO_PATCH_INFO_RGCTX_FETCH: {
5302 MonoJumpInfoRgctxEntry *entry = patch_info->data.rgctx_entry;
5304 if (!can_encode_patch (acfg, entry->data))
5318 * AOT compile a given method.
5319 * This function might be called by multiple threads, so it must be thread-safe.
5322 compile_method (MonoAotCompile *acfg, MonoMethod *method)
5325 MonoJumpInfo *patch_info;
5328 MonoMethod *wrapped;
5330 if (acfg->aot_opts.metadata_only)
5333 mono_acfg_lock (acfg);
5334 index = get_method_index (acfg, method);
5335 mono_acfg_unlock (acfg);
5337 /* fixme: maybe we can also precompile wrapper methods */
5338 if ((method->flags & METHOD_ATTRIBUTE_PINVOKE_IMPL) ||
5339 (method->iflags & METHOD_IMPL_ATTRIBUTE_RUNTIME) ||
5340 (method->flags & METHOD_ATTRIBUTE_ABSTRACT)) {
5341 //printf ("Skip (impossible): %s\n", mono_method_full_name (method, TRUE));
5345 if (method->iflags & METHOD_IMPL_ATTRIBUTE_INTERNAL_CALL)
5348 wrapped = mono_marshal_method_from_wrapper (method);
5349 if (wrapped && (wrapped->iflags & METHOD_IMPL_ATTRIBUTE_INTERNAL_CALL) && wrapped->is_generic)
5350 // FIXME: The wrapper should be generic too, but it is not
5353 if (method->wrapper_type == MONO_WRAPPER_COMINTEROP)
5356 InterlockedIncrement (&acfg->stats.mcount);
5359 if (method->is_generic || method->klass->generic_container) {
5360 InterlockedIncrement (&acfg->stats.genericcount);
5365 //acfg->aot_opts.print_skipped_methods = TRUE;
5368 * Since these methods are the only ones which are compiled with
5369 * AOT support, and they are not used by runtime startup/shutdown code,
5370 * the runtime will not see AOT methods during AOT compilation,so it
5371 * does not need to support them by creating a fake GOT etc.
5373 cfg = mini_method_compile (method, acfg->opts, mono_get_root_domain (), FALSE, TRUE, 0);
5374 if (cfg->exception_type == MONO_EXCEPTION_GENERIC_SHARING_FAILED) {
5375 //printf ("F: %s\n", mono_method_full_name (method, TRUE));
5376 InterlockedIncrement (&acfg->stats.genericcount);
5379 if (cfg->exception_type != MONO_EXCEPTION_NONE) {
5380 if (acfg->aot_opts.print_skipped_methods)
5381 printf ("Skip (JIT failure): %s\n", mono_method_full_name (method, TRUE));
5382 /* Let the exception happen at runtime */
5386 if (cfg->disable_aot) {
5387 if (acfg->aot_opts.print_skipped_methods)
5388 printf ("Skip (disabled): %s\n", mono_method_full_name (method, TRUE));
5389 InterlockedIncrement (&acfg->stats.ocount);
5390 mono_destroy_compile (cfg);
5394 /* Nullify patches which need no aot processing */
5395 for (patch_info = cfg->patch_info; patch_info; patch_info = patch_info->next) {
5396 switch (patch_info->type) {
5397 case MONO_PATCH_INFO_LABEL:
5398 case MONO_PATCH_INFO_BB:
5399 patch_info->type = MONO_PATCH_INFO_NONE;
5406 /* Collect method->token associations from the cfg */
5407 mono_acfg_lock (acfg);
5408 g_hash_table_foreach (cfg->token_info_hash, add_token_info_hash, acfg);
5409 mono_acfg_unlock (acfg);
5412 * Check for absolute addresses.
5415 for (patch_info = cfg->patch_info; patch_info; patch_info = patch_info->next) {
5416 switch (patch_info->type) {
5417 case MONO_PATCH_INFO_ABS:
5418 /* unable to handle this */
5427 if (acfg->aot_opts.print_skipped_methods)
5428 printf ("Skip (abs call): %s\n", mono_method_full_name (method, TRUE));
5429 InterlockedIncrement (&acfg->stats.abscount);
5430 mono_destroy_compile (cfg);
5434 /* Lock for the rest of the code */
5435 mono_acfg_lock (acfg);
5438 * Check for methods/klasses we can't encode.
5441 for (patch_info = cfg->patch_info; patch_info; patch_info = patch_info->next) {
5442 if (!can_encode_patch (acfg, patch_info))
5447 if (acfg->aot_opts.print_skipped_methods)
5448 printf ("Skip (patches): %s\n", mono_method_full_name (method, TRUE));
5449 acfg->stats.ocount++;
5450 mono_destroy_compile (cfg);
5451 mono_acfg_unlock (acfg);
5455 /* Adds generic instances referenced by this method */
5457 * The depth is used to avoid infinite loops when generic virtual recursion is
5460 depth = GPOINTER_TO_UINT (g_hash_table_lookup (acfg->method_depth, method));
5462 for (patch_info = cfg->patch_info; patch_info; patch_info = patch_info->next) {
5463 switch (patch_info->type) {
5464 case MONO_PATCH_INFO_METHOD: {
5465 MonoMethod *m = patch_info->data.method;
5466 if (m->is_inflated) {
5467 if (!(mono_class_generic_sharing_enabled (m->klass) &&
5468 mono_method_is_generic_sharable_impl (m, FALSE)) &&
5469 !method_has_type_vars (m)) {
5470 if (m->iflags & METHOD_IMPL_ATTRIBUTE_INTERNAL_CALL) {
5471 if (acfg->aot_opts.full_aot)
5472 add_extra_method_with_depth (acfg, mono_marshal_get_native_wrapper (m, TRUE, TRUE), depth + 1);
5474 add_extra_method_with_depth (acfg, m, depth + 1);
5477 add_generic_class_with_depth (acfg, m->klass, depth + 5, "method");
5479 if (m->wrapper_type == MONO_WRAPPER_MANAGED_TO_MANAGED && !strcmp (m->name, "ElementAddr"))
5480 add_extra_method_with_depth (acfg, m, depth + 1);
5483 case MONO_PATCH_INFO_VTABLE: {
5484 MonoClass *klass = patch_info->data.klass;
5486 if (klass->generic_class && !mono_generic_context_is_sharable (&klass->generic_class->context, FALSE))
5487 add_generic_class_with_depth (acfg, klass, depth + 5, "vtable");
5490 case MONO_PATCH_INFO_SFLDA: {
5491 MonoClass *klass = patch_info->data.field->parent;
5493 /* The .cctor needs to run at runtime. */
5494 if (klass->generic_class && !mono_generic_context_is_sharable (&klass->generic_class->context, FALSE) && mono_class_get_cctor (klass))
5495 add_extra_method_with_depth (acfg, mono_class_get_cctor (klass), depth + 1);
5504 /* Determine whenever the method has GOT slots */
5505 for (patch_info = cfg->patch_info; patch_info; patch_info = patch_info->next) {
5506 switch (patch_info->type) {
5507 case MONO_PATCH_INFO_GOT_OFFSET:
5508 case MONO_PATCH_INFO_NONE:
5509 case MONO_PATCH_INFO_GC_CARD_TABLE_ADDR:
5511 case MONO_PATCH_INFO_IMAGE:
5512 /* The assembly is stored in GOT slot 0 */
5513 if (patch_info->data.image != acfg->image)
5514 cfg->has_got_slots = TRUE;
5517 if (!is_plt_patch (patch_info))
5518 cfg->has_got_slots = TRUE;
5523 if (!cfg->has_got_slots)
5524 InterlockedIncrement (&acfg->stats.methods_without_got_slots);
5527 * FIXME: Instead of this mess, allocate the patches from the aot mempool.
5529 /* Make a copy of the patch info which is in the mempool */
5531 MonoJumpInfo *patches = NULL, *patches_end = NULL;
5533 for (patch_info = cfg->patch_info; patch_info; patch_info = patch_info->next) {
5534 MonoJumpInfo *new_patch_info = mono_patch_info_dup_mp (acfg->mempool, patch_info);
5537 patches = new_patch_info;
5539 patches_end->next = new_patch_info;
5540 patches_end = new_patch_info;
5542 cfg->patch_info = patches;
5544 /* Make a copy of the unwind info */
5546 GSList *l, *unwind_ops;
5550 for (l = cfg->unwind_ops; l; l = l->next) {
5551 op = mono_mempool_alloc (acfg->mempool, sizeof (MonoUnwindOp));
5552 memcpy (op, l->data, sizeof (MonoUnwindOp));
5553 unwind_ops = g_slist_prepend_mempool (acfg->mempool, unwind_ops, op);
5555 cfg->unwind_ops = g_slist_reverse (unwind_ops);
5557 /* Make a copy of the argument/local info */
5559 MonoInst **args, **locals;
5560 MonoMethodSignature *sig;
5561 MonoMethodHeader *header;
5564 sig = mono_method_signature (method);
5565 args = mono_mempool_alloc (acfg->mempool, sizeof (MonoInst*) * (sig->param_count + sig->hasthis));
5566 for (i = 0; i < sig->param_count + sig->hasthis; ++i) {
5567 args [i] = mono_mempool_alloc (acfg->mempool, sizeof (MonoInst));
5568 memcpy (args [i], cfg->args [i], sizeof (MonoInst));
5572 header = mono_method_get_header (method);
5573 locals = mono_mempool_alloc (acfg->mempool, sizeof (MonoInst*) * header->num_locals);
5574 for (i = 0; i < header->num_locals; ++i) {
5575 locals [i] = mono_mempool_alloc (acfg->mempool, sizeof (MonoInst));
5576 memcpy (locals [i], cfg->locals [i], sizeof (MonoInst));
5578 cfg->locals = locals;
5581 /* Free some fields used by cfg to conserve memory */
5582 mono_mempool_destroy (cfg->mempool);
5583 cfg->mempool = NULL;
5584 g_free (cfg->varinfo);
5585 cfg->varinfo = NULL;
5589 mono_regstate_free (cfg->rs);
5593 //printf ("Compile: %s\n", mono_method_full_name (method, TRUE));
5595 while (index >= acfg->cfgs_size) {
5596 MonoCompile **new_cfgs;
5599 new_size = acfg->cfgs_size * 2;
5600 new_cfgs = g_new0 (MonoCompile*, new_size);
5601 memcpy (new_cfgs, acfg->cfgs, sizeof (MonoCompile*) * acfg->cfgs_size);
5602 g_free (acfg->cfgs);
5603 acfg->cfgs = new_cfgs;
5604 acfg->cfgs_size = new_size;
5606 acfg->cfgs [index] = cfg;
5608 g_hash_table_insert (acfg->method_to_cfg, cfg->orig_method, cfg);
5611 if (cfg->orig_method->wrapper_type)
5612 g_ptr_array_add (acfg->extra_methods, cfg->orig_method);
5615 mono_acfg_unlock (acfg);
5617 InterlockedIncrement (&acfg->stats.ccount);
5621 compile_thread_main (gpointer *user_data)
5623 MonoDomain *domain = user_data [0];
5624 MonoAotCompile *acfg = user_data [1];
5625 GPtrArray *methods = user_data [2];
5628 mono_thread_attach (domain);
5630 for (i = 0; i < methods->len; ++i)
5631 compile_method (acfg, g_ptr_array_index (methods, i));
5635 load_profile_files (MonoAotCompile *acfg)
5639 int file_index, res, method_index, i;
5642 GList *unordered, *l;
5647 tmp = g_strdup_printf ("%s/.mono/aot-profile-data/%s-%d", g_get_home_dir (), acfg->image->assembly_name, file_index);
5649 if (!g_file_test (tmp, G_FILE_TEST_IS_REGULAR)) {
5654 infile = fopen (tmp, "r");
5657 printf ("Using profile data file '%s'\n", tmp);
5662 res = fscanf (infile, "%32s\n", ver);
5663 if ((res != 1) || strcmp (ver, "#VER:2") != 0) {
5664 printf ("Profile file has wrong version or invalid.\n");
5671 MonoMethodDesc *desc;
5674 if (fgets (name, 1023, infile) == NULL)
5677 /* Kill the newline */
5678 if (strlen (name) > 0)
5679 name [strlen (name) - 1] = '\0';
5681 desc = mono_method_desc_new (name, TRUE);
5683 method = mono_method_desc_search_in_image (desc, acfg->image);
5685 if (method && mono_method_get_token (method)) {
5686 token = mono_method_get_token (method);
5687 method_index = mono_metadata_token_index (token) - 1;
5690 for (i = 0; i < acfg->method_order->len; ++i) {
5691 if (g_ptr_array_index (acfg->method_order, i) == GUINT_TO_POINTER (method_index)) {
5697 g_ptr_array_add (acfg->method_order, GUINT_TO_POINTER (method_index));
5699 //printf ("No method found matching '%s'.\n", name);
5705 /* Add missing methods */
5707 for (method_index = 0; method_index < acfg->image->tables [MONO_TABLE_METHOD].rows; ++method_index) {
5709 for (i = 0; i < acfg->method_order->len; ++i) {
5710 if (g_ptr_array_index (acfg->method_order, i) == GUINT_TO_POINTER (method_index)) {
5716 unordered = g_list_prepend (unordered, GUINT_TO_POINTER (method_index));
5718 unordered = g_list_reverse (unordered);
5719 for (l = unordered; l; l = l->next)
5720 g_ptr_array_add (acfg->method_order, l->data);
5723 /* Used by the LLVM backend */
5725 mono_aot_get_got_offset (MonoJumpInfo *ji)
5727 return get_got_offset (llvm_acfg, ji);
5731 mono_aot_get_method_name (MonoCompile *cfg)
5733 if (llvm_acfg->aot_opts.static_link)
5734 /* Include the assembly name too to avoid duplicate symbol errors */
5735 return g_strdup_printf ("%s_%s", llvm_acfg->assembly_name_sym, get_debug_sym (cfg->orig_method, "", llvm_acfg->method_label_hash));
5737 return get_debug_sym (cfg->orig_method, "", llvm_acfg->method_label_hash);
5741 mono_aot_get_plt_symbol (MonoJumpInfoType type, gconstpointer data)
5743 MonoJumpInfo *ji = mono_mempool_alloc (llvm_acfg->mempool, sizeof (MonoJumpInfo));
5744 MonoPltEntry *plt_entry;
5747 ji->data.target = data;
5749 if (!can_encode_patch (llvm_acfg, ji))
5752 plt_entry = get_plt_entry (llvm_acfg, ji);
5753 plt_entry->llvm_used = TRUE;
5755 #if defined(__APPLE__)
5756 return g_strdup_printf (plt_entry->llvm_symbol + strlen (llvm_acfg->llvm_label_prefix));
5758 return g_strdup_printf (plt_entry->llvm_symbol);
5763 mono_aot_patch_info_dup (MonoJumpInfo* ji)
5767 mono_acfg_lock (llvm_acfg);
5768 res = mono_patch_info_dup_mp (llvm_acfg->mempool, ji);
5769 mono_acfg_unlock (llvm_acfg);
5779 * Emit the LLVM code into an LLVM bytecode file, and compile it using the LLVM
5783 emit_llvm_file (MonoAotCompile *acfg)
5785 char *command, *opts;
5787 MonoJumpInfo *patch_info;
5790 * When using LLVM, we let llvm emit the got since the LLVM IL needs to refer
5794 /* Compute the final size of the got */
5795 for (i = 0; i < acfg->nmethods; ++i) {
5796 if (acfg->cfgs [i]) {
5797 for (patch_info = acfg->cfgs [i]->patch_info; patch_info; patch_info = patch_info->next) {
5798 if (patch_info->type != MONO_PATCH_INFO_NONE) {
5799 if (!is_plt_patch (patch_info))
5800 get_got_offset (acfg, patch_info);
5802 get_plt_entry (acfg, patch_info);
5808 acfg->final_got_size = acfg->got_offset + acfg->plt_offset;
5810 if (acfg->aot_opts.full_aot) {
5814 * Need to add the got entries used by the trampolines.
5815 * This is only a conservative approximation.
5817 if (strcmp (acfg->image->assembly->aname.name, "mscorlib") == 0) {
5818 /* For the generic + rgctx trampolines */
5819 acfg->final_got_size += 200;
5820 /* For the specific trampolines */
5821 for (ntype = 0; ntype < MONO_AOT_TRAMP_NUM; ++ntype)
5822 acfg->final_got_size += acfg->num_trampolines [ntype] * 2;
5827 mono_llvm_emit_aot_module ("temp.bc", acfg->final_got_size);
5830 * FIXME: Experiment with adding optimizations, the -std-compile-opts set takes
5831 * a lot of time, and doesn't seem to save much space.
5832 * The following optimizations cannot be enabled:
5834 * - 'jump-threading' changes our blockaddress references to int constants.
5835 * - 'basiccg' fails because it contains:
5836 * if (CS && !isa<IntrinsicInst>(II)) {
5837 * and isa<IntrinsicInst> is false for invokes to intrinsics (iltests.exe).
5838 * - 'prune-eh' and 'functionattrs' depend on 'basiccg'.
5839 * The opt list below was produced by taking the output of:
5840 * llvm-as < /dev/null | opt -O2 -disable-output -debug-pass=Arguments
5841 * then removing tailcallelim + the global opts, and adding a second gvn.
5843 opts = g_strdup ("-instcombine -simplifycfg");
5844 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");
5846 command = g_strdup_printf ("%sopt -f %s -o temp.opt.bc temp.bc", acfg->aot_opts.llvm_path, opts);
5847 printf ("Executing opt: %s\n", command);
5848 if (system (command) != 0) {
5854 if (!acfg->llc_args)
5855 acfg->llc_args = g_string_new ("");
5857 /* Verbose asm slows down llc greatly */
5858 g_string_append (acfg->llc_args, " -asm-verbose=false");
5860 if (acfg->aot_opts.mtriple)
5861 g_string_append_printf (acfg->llc_args, " -mtriple=%s", acfg->aot_opts.mtriple);
5863 if (llvm_acfg->aot_opts.static_link)
5864 g_string_append_printf (acfg->llc_args, " -relocation-model=static");
5866 g_string_append_printf (acfg->llc_args, " -relocation-model=pic");
5867 unlink (acfg->tmpfname);
5869 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);
5871 printf ("Executing llc: %s\n", command);
5873 if (system (command) != 0) {
5880 emit_code (MonoAotCompile *acfg)
5882 int oindex, i, prev_index;
5884 char end_symbol [256];
5886 #if defined(TARGET_POWERPC64)
5887 sprintf (symbol, ".Lgot_addr");
5888 emit_section_change (acfg, ".text", 0);
5889 emit_alignment (acfg, 8);
5890 emit_label (acfg, symbol);
5891 emit_pointer (acfg, acfg->got_symbol);
5895 * This global symbol is used to compute the address of each method using the
5896 * code_offsets array. It is also used to compute the memory ranges occupied by
5897 * AOT code, so it must be equal to the address of the first emitted method.
5899 sprintf (symbol, "methods");
5900 emit_section_change (acfg, ".text", 0);
5901 emit_alignment (acfg, 8);
5903 for (i = 0; i < acfg->nmethods; ++i) {
5904 if (acfg->cfgs [i] && acfg->cfgs [i]->compile_llvm) {
5905 fprintf (acfg->fp, "\n.set methods, %s\n", acfg->cfgs [i]->asm_symbol);
5909 if (i == acfg->nmethods)
5910 /* No LLVM compiled methods */
5911 emit_label (acfg, symbol);
5913 emit_label (acfg, symbol);
5917 * Emit some padding so the local symbol for the first method doesn't have the
5918 * same address as 'methods'.
5920 #if defined(__default_codegen__)
5921 emit_zero_bytes (acfg, 16);
5922 #elif defined(__native_client_codegen__)
5924 const int kPaddingSize = 16;
5925 guint8 pad_buffer[kPaddingSize];
5926 mono_arch_nacl_pad (pad_buffer, kPaddingSize);
5927 emit_bytes (acfg, pad_buffer, kPaddingSize);
5931 for (oindex = 0; oindex < acfg->method_order->len; ++oindex) {
5935 i = GPOINTER_TO_UINT (g_ptr_array_index (acfg->method_order, oindex));
5937 cfg = acfg->cfgs [i];
5942 method = cfg->orig_method;
5944 /* Emit unbox trampoline */
5945 if (acfg->aot_opts.full_aot && cfg->orig_method->klass->valuetype && (method->flags & METHOD_ATTRIBUTE_VIRTUAL)) {
5946 sprintf (symbol, "ut_%d", get_method_index (acfg, method));
5948 emit_section_change (acfg, ".text", 0);
5949 #ifdef __native_client_codegen__
5950 emit_alignment (acfg, AOT_FUNC_ALIGNMENT);
5953 if (acfg->thumb_mixed && cfg->compile_llvm)
5954 fprintf (acfg->fp, "\n.thumb_func\n");
5956 emit_label (acfg, symbol);
5958 arch_emit_unbox_trampoline (acfg, cfg, cfg->orig_method, cfg->asm_symbol);
5961 if (cfg->compile_llvm)
5962 acfg->stats.llvm_count ++;
5964 emit_method_code (acfg, cfg);
5967 sprintf (symbol, "methods_end");
5968 emit_section_change (acfg, ".text", 0);
5969 emit_alignment (acfg, 8);
5970 emit_label (acfg, symbol);
5973 * Add .no_dead_strip directives for all LLVM methods to prevent the OSX linker
5974 * from optimizing them away, since it doesn't see that code_offsets references them.
5975 * JITted methods don't need this since they are referenced using assembler local
5977 * FIXME: This is why write-symbols doesn't work on OSX ?
5979 if (acfg->llvm && acfg->need_no_dead_strip) {
5980 fprintf (acfg->fp, "\n");
5981 for (i = 0; i < acfg->nmethods; ++i) {
5982 if (acfg->cfgs [i] && acfg->cfgs [i]->compile_llvm)
5983 fprintf (acfg->fp, ".no_dead_strip %s\n", acfg->cfgs [i]->asm_symbol);
5987 sprintf (symbol, "code_offsets");
5988 emit_section_change (acfg, RODATA_SECT, 1);
5989 emit_alignment (acfg, 8);
5990 emit_label (acfg, symbol);
5992 acfg->stats.offsets_size += acfg->nmethods * 4;
5994 sprintf (end_symbol, "methods");
5995 for (i = 0; i < acfg->nmethods; ++i) {
5996 if (acfg->cfgs [i]) {
5997 emit_symbol_diff (acfg, acfg->cfgs [i]->asm_symbol, end_symbol, 0);
5999 emit_int32 (acfg, 0xffffffff);
6004 /* Emit a sorted table mapping methods to their unbox trampolines */
6005 sprintf (symbol, "unbox_trampolines");
6006 emit_section_change (acfg, RODATA_SECT, 1);
6007 emit_alignment (acfg, 8);
6008 emit_label (acfg, symbol);
6010 sprintf (end_symbol, "methods");
6012 for (i = 0; i < acfg->nmethods; ++i) {
6017 cfg = acfg->cfgs [i];
6021 method = cfg->orig_method;
6023 if (acfg->aot_opts.full_aot && cfg->orig_method->klass->valuetype && (method->flags & METHOD_ATTRIBUTE_VIRTUAL)) {
6024 index = get_method_index (acfg, method);
6025 sprintf (symbol, "ut_%d", index);
6027 emit_int32 (acfg, index);
6028 emit_symbol_diff (acfg, symbol, end_symbol, 0);
6029 /* Make sure the table is sorted by index */
6030 g_assert (index > prev_index);
6034 sprintf (symbol, "unbox_trampolines_end");
6035 emit_label (acfg, symbol);
6039 emit_info (MonoAotCompile *acfg)
6045 offsets = g_new0 (gint32, acfg->nmethods);
6047 for (oindex = 0; oindex < acfg->method_order->len; ++oindex) {
6048 i = GPOINTER_TO_UINT (g_ptr_array_index (acfg->method_order, oindex));
6050 if (acfg->cfgs [i]) {
6051 emit_method_info (acfg, acfg->cfgs [i]);
6052 offsets [i] = acfg->cfgs [i]->method_info_offset;
6058 sprintf (symbol, "method_info_offsets");
6059 emit_section_change (acfg, RODATA_SECT, 1);
6060 emit_alignment (acfg, 8);
6061 emit_label (acfg, symbol);
6063 acfg->stats.offsets_size += emit_offset_table (acfg, acfg->nmethods, 10, offsets);
6068 #endif /* #if !defined(DISABLE_AOT) && !defined(DISABLE_JIT) */
6070 #define rot(x,k) (((x)<<(k)) | ((x)>>(32-(k))))
6071 #define mix(a,b,c) { \
6072 a -= c; a ^= rot(c, 4); c += b; \
6073 b -= a; b ^= rot(a, 6); a += c; \
6074 c -= b; c ^= rot(b, 8); b += a; \
6075 a -= c; a ^= rot(c,16); c += b; \
6076 b -= a; b ^= rot(a,19); a += c; \
6077 c -= b; c ^= rot(b, 4); b += a; \
6079 #define final(a,b,c) { \
6080 c ^= b; c -= rot(b,14); \
6081 a ^= c; a -= rot(c,11); \
6082 b ^= a; b -= rot(a,25); \
6083 c ^= b; c -= rot(b,16); \
6084 a ^= c; a -= rot(c,4); \
6085 b ^= a; b -= rot(a,14); \
6086 c ^= b; c -= rot(b,24); \
6090 mono_aot_type_hash (MonoType *t1)
6092 guint hash = t1->type;
6094 hash |= t1->byref << 6; /* do not collide with t1->type values */
6096 case MONO_TYPE_VALUETYPE:
6097 case MONO_TYPE_CLASS:
6098 case MONO_TYPE_SZARRAY:
6099 /* check if the distribution is good enough */
6100 return ((hash << 5) - hash) ^ mono_metadata_str_hash (t1->data.klass->name);
6102 return ((hash << 5) - hash) ^ mono_metadata_type_hash (t1->data.type);
6103 case MONO_TYPE_ARRAY:
6104 return ((hash << 5) - hash) ^ mono_metadata_type_hash (&t1->data.array->eklass->byval_arg);
6105 case MONO_TYPE_GENERICINST:
6106 return ((hash << 5) - hash) ^ 0;
6113 * mono_aot_method_hash:
6115 * Return a hash code for methods which only depends on metadata.
6118 mono_aot_method_hash (MonoMethod *method)
6120 MonoMethodSignature *sig;
6124 guint32 *hashes_start, *hashes;
6126 MonoGenericInst *ginst = NULL;
6128 /* Similar to the hash in mono_method_get_imt_slot () */
6130 sig = mono_method_signature (method);
6132 if (method->is_inflated)
6133 ginst = ((MonoMethodInflated*)method)->context.method_inst;
6135 hashes_count = sig->param_count + 5 + (ginst ? ginst->type_argc : 0);
6136 hashes_start = g_malloc0 (hashes_count * sizeof (guint32));
6137 hashes = hashes_start;
6139 /* Some wrappers are assigned to random classes */
6140 if (!method->wrapper_type || method->wrapper_type == MONO_WRAPPER_REMOTING_INVOKE_WITH_CHECK)
6141 klass = method->klass;
6143 klass = mono_defaults.object_class;
6145 if (!method->wrapper_type) {
6146 char *full_name = mono_type_full_name (&klass->byval_arg);
6148 hashes [0] = mono_metadata_str_hash (full_name);
6152 hashes [0] = mono_metadata_str_hash (klass->name);
6153 hashes [1] = mono_metadata_str_hash (klass->name_space);
6155 if (method->wrapper_type == MONO_WRAPPER_STFLD || method->wrapper_type == MONO_WRAPPER_LDFLD || method->wrapper_type == MONO_WRAPPER_LDFLDA)
6156 /* The method name includes a stringified pointer */
6159 hashes [2] = mono_metadata_str_hash (method->name);
6160 hashes [3] = method->wrapper_type;
6161 hashes [4] = mono_aot_type_hash (sig->ret);
6163 for (i = 0; i < sig->param_count; i++) {
6164 hashes [hindex ++] = mono_aot_type_hash (sig->params [i]);
6167 for (i = 0; i < ginst->type_argc; ++i)
6168 hashes [hindex ++] = mono_aot_type_hash (ginst->type_argv [i]);
6170 g_assert (hindex == hashes_count);
6172 /* Setup internal state */
6173 a = b = c = 0xdeadbeef + (((guint32)hashes_count)<<2);
6175 /* Handle most of the hashes */
6176 while (hashes_count > 3) {
6185 /* Handle the last 3 hashes (all the case statements fall through) */
6186 switch (hashes_count) {
6187 case 3 : c += hashes [2];
6188 case 2 : b += hashes [1];
6189 case 1 : a += hashes [0];
6191 case 0: /* nothing left to add */
6195 free (hashes_start);
6204 * mono_aot_wrapper_name:
6206 * Return a string which uniqely identifies the given wrapper method.
6209 mono_aot_wrapper_name (MonoMethod *method)
6211 char *name, *tmpsig, *klass_desc;
6213 tmpsig = mono_signature_get_desc (mono_method_signature (method), TRUE);
6215 switch (method->wrapper_type) {
6216 case MONO_WRAPPER_RUNTIME_INVOKE:
6217 if (!strcmp (method->name, "runtime_invoke_dynamic"))
6218 name = g_strdup_printf ("(wrapper runtime-invoke-dynamic)");
6220 name = g_strdup_printf ("%s (%s)", method->name, tmpsig);
6223 klass_desc = mono_type_full_name (&method->klass->byval_arg);
6224 name = g_strdup_printf ("%s:%s (%s)", klass_desc, method->name, tmpsig);
6225 g_free (klass_desc);
6235 * mono_aot_get_array_helper_from_wrapper;
6237 * Get the helper method in Array called by an array wrapper method.
6240 mono_aot_get_array_helper_from_wrapper (MonoMethod *method)
6244 MonoGenericContext ctx;
6245 MonoType *args [16];
6246 char *mname, *iname, *s, *s2, *helper_name = NULL;
6248 prefix = "System.Collections.Generic";
6249 s = g_strdup_printf ("%s", method->name + strlen (prefix) + 1);
6250 s2 = strstr (s, "`1.");
6256 //printf ("X: %s %s\n", iname, mname);
6258 if (!strcmp (iname, "IList"))
6259 helper_name = g_strdup_printf ("InternalArray__%s", mname);
6261 helper_name = g_strdup_printf ("InternalArray__%s_%s", iname, mname);
6262 m = mono_class_get_method_from_name (mono_defaults.array_class, helper_name, mono_method_signature (method)->param_count);
6264 g_free (helper_name);
6267 if (m->is_generic) {
6268 memset (&ctx, 0, sizeof (ctx));
6269 args [0] = &method->klass->element_class->byval_arg;
6270 ctx.method_inst = mono_metadata_get_generic_inst (1, args);
6271 m = mono_class_inflate_generic_method (m, &ctx);
6277 #if !defined(DISABLE_AOT) && !defined(DISABLE_JIT)
6279 typedef struct HashEntry {
6280 guint32 key, value, index;
6281 struct HashEntry *next;
6285 * emit_extra_methods:
6287 * Emit methods which are not in the METHOD table, like wrappers.
6290 emit_extra_methods (MonoAotCompile *acfg)
6292 int i, table_size, buf_size;
6295 guint32 *info_offsets;
6298 HashEntry *entry, *new_entry;
6299 int nmethods, max_chain_length;
6302 info_offsets = g_new0 (guint32, acfg->extra_methods->len);
6304 /* Emit method info */
6306 for (i = 0; i < acfg->extra_methods->len; ++i) {
6307 MonoMethod *method = g_ptr_array_index (acfg->extra_methods, i);
6308 MonoCompile *cfg = g_hash_table_lookup (acfg->method_to_cfg, method);
6314 p = buf = g_malloc (buf_size);
6318 method = cfg->method_to_register;
6320 encode_method_ref (acfg, method, p, &p);
6322 g_assert ((p - buf) < buf_size);
6324 info_offsets [i] = add_to_blob (acfg, buf, p - buf);
6329 * Construct a chained hash table for mapping indexes in extra_method_info to
6332 table_size = g_spaced_primes_closest ((int)(nmethods * 1.5));
6333 table = g_ptr_array_sized_new (table_size);
6334 for (i = 0; i < table_size; ++i)
6335 g_ptr_array_add (table, NULL);
6336 chain_lengths = g_new0 (int, table_size);
6337 max_chain_length = 0;
6338 for (i = 0; i < acfg->extra_methods->len; ++i) {
6339 MonoMethod *method = g_ptr_array_index (acfg->extra_methods, i);
6340 MonoCompile *cfg = g_hash_table_lookup (acfg->method_to_cfg, method);
6346 key = info_offsets [i];
6347 value = get_method_index (acfg, method);
6349 hash = mono_aot_method_hash (method) % table_size;
6351 chain_lengths [hash] ++;
6352 max_chain_length = MAX (max_chain_length, chain_lengths [hash]);
6354 new_entry = mono_mempool_alloc0 (acfg->mempool, sizeof (HashEntry));
6355 new_entry->key = key;
6356 new_entry->value = value;
6358 entry = g_ptr_array_index (table, hash);
6359 if (entry == NULL) {
6360 new_entry->index = hash;
6361 g_ptr_array_index (table, hash) = new_entry;
6364 entry = entry->next;
6366 entry->next = new_entry;
6367 new_entry->index = table->len;
6368 g_ptr_array_add (table, new_entry);
6372 //printf ("MAX: %d\n", max_chain_length);
6374 /* Emit the table */
6375 sprintf (symbol, "extra_method_table");
6376 emit_section_change (acfg, RODATA_SECT, 0);
6377 emit_alignment (acfg, 8);
6378 emit_label (acfg, symbol);
6380 emit_int32 (acfg, table_size);
6381 for (i = 0; i < table->len; ++i) {
6382 HashEntry *entry = g_ptr_array_index (table, i);
6384 if (entry == NULL) {
6385 emit_int32 (acfg, 0);
6386 emit_int32 (acfg, 0);
6387 emit_int32 (acfg, 0);
6389 //g_assert (entry->key > 0);
6390 emit_int32 (acfg, entry->key);
6391 emit_int32 (acfg, entry->value);
6393 emit_int32 (acfg, entry->next->index);
6395 emit_int32 (acfg, 0);
6400 * Emit a table reverse mapping method indexes to their index in extra_method_info.
6401 * This is used by mono_aot_find_jit_info ().
6403 sprintf (symbol, "extra_method_info_offsets");
6404 emit_section_change (acfg, RODATA_SECT, 0);
6405 emit_alignment (acfg, 8);
6406 emit_label (acfg, symbol);
6408 emit_int32 (acfg, acfg->extra_methods->len);
6409 for (i = 0; i < acfg->extra_methods->len; ++i) {
6410 MonoMethod *method = g_ptr_array_index (acfg->extra_methods, i);
6412 emit_int32 (acfg, get_method_index (acfg, method));
6413 emit_int32 (acfg, info_offsets [i]);
6418 emit_exception_info (MonoAotCompile *acfg)
6424 offsets = g_new0 (gint32, acfg->nmethods);
6425 for (i = 0; i < acfg->nmethods; ++i) {
6426 if (acfg->cfgs [i]) {
6427 emit_exception_debug_info (acfg, acfg->cfgs [i]);
6428 offsets [i] = acfg->cfgs [i]->ex_info_offset;
6434 sprintf (symbol, "ex_info_offsets");
6435 emit_section_change (acfg, RODATA_SECT, 1);
6436 emit_alignment (acfg, 8);
6437 emit_label (acfg, symbol);
6439 acfg->stats.offsets_size += emit_offset_table (acfg, acfg->nmethods, 10, offsets);
6444 emit_unwind_info (MonoAotCompile *acfg)
6450 * The unwind info contains a lot of duplicates so we emit each unique
6451 * entry once, and only store the offset from the start of the table in the
6455 sprintf (symbol, "unwind_info");
6456 emit_section_change (acfg, RODATA_SECT, 1);
6457 emit_alignment (acfg, 8);
6458 emit_label (acfg, symbol);
6460 for (i = 0; i < acfg->unwind_ops->len; ++i) {
6461 guint32 index = GPOINTER_TO_UINT (g_ptr_array_index (acfg->unwind_ops, i));
6462 guint8 *unwind_info;
6463 guint32 unwind_info_len;
6467 unwind_info = mono_get_cached_unwind_info (index, &unwind_info_len);
6470 encode_value (unwind_info_len, p, &p);
6471 emit_bytes (acfg, buf, p - buf);
6472 emit_bytes (acfg, unwind_info, unwind_info_len);
6474 acfg->stats.unwind_info_size += (p - buf) + unwind_info_len;
6479 emit_class_info (MonoAotCompile *acfg)
6485 offsets = g_new0 (gint32, acfg->image->tables [MONO_TABLE_TYPEDEF].rows);
6486 for (i = 0; i < acfg->image->tables [MONO_TABLE_TYPEDEF].rows; ++i)
6487 offsets [i] = emit_klass_info (acfg, MONO_TOKEN_TYPE_DEF | (i + 1));
6489 sprintf (symbol, "class_info_offsets");
6490 emit_section_change (acfg, RODATA_SECT, 1);
6491 emit_alignment (acfg, 8);
6492 emit_label (acfg, symbol);
6494 acfg->stats.offsets_size += emit_offset_table (acfg, acfg->image->tables [MONO_TABLE_TYPEDEF].rows, 10, offsets);
6498 typedef struct ClassNameTableEntry {
6499 guint32 token, index;
6500 struct ClassNameTableEntry *next;
6501 } ClassNameTableEntry;
6504 emit_class_name_table (MonoAotCompile *acfg)
6507 guint32 token, hash;
6512 ClassNameTableEntry *entry, *new_entry;
6515 * Construct a chained hash table for mapping class names to typedef tokens.
6517 table_size = g_spaced_primes_closest ((int)(acfg->image->tables [MONO_TABLE_TYPEDEF].rows * 1.5));
6518 table = g_ptr_array_sized_new (table_size);
6519 for (i = 0; i < table_size; ++i)
6520 g_ptr_array_add (table, NULL);
6521 for (i = 0; i < acfg->image->tables [MONO_TABLE_TYPEDEF].rows; ++i) {
6522 token = MONO_TOKEN_TYPE_DEF | (i + 1);
6523 klass = mono_class_get (acfg->image, token);
6525 mono_loader_clear_error ();
6528 full_name = mono_type_get_name_full (mono_class_get_type (klass), MONO_TYPE_NAME_FORMAT_FULL_NAME);
6529 hash = mono_metadata_str_hash (full_name) % table_size;
6532 /* FIXME: Allocate from the mempool */
6533 new_entry = g_new0 (ClassNameTableEntry, 1);
6534 new_entry->token = token;
6536 entry = g_ptr_array_index (table, hash);
6537 if (entry == NULL) {
6538 new_entry->index = hash;
6539 g_ptr_array_index (table, hash) = new_entry;
6542 entry = entry->next;
6544 entry->next = new_entry;
6545 new_entry->index = table->len;
6546 g_ptr_array_add (table, new_entry);
6550 /* Emit the table */
6551 sprintf (symbol, "class_name_table");
6552 emit_section_change (acfg, RODATA_SECT, 0);
6553 emit_alignment (acfg, 8);
6554 emit_label (acfg, symbol);
6556 /* FIXME: Optimize memory usage */
6557 g_assert (table_size < 65000);
6558 emit_int16 (acfg, table_size);
6559 g_assert (table->len < 65000);
6560 for (i = 0; i < table->len; ++i) {
6561 ClassNameTableEntry *entry = g_ptr_array_index (table, i);
6563 if (entry == NULL) {
6564 emit_int16 (acfg, 0);
6565 emit_int16 (acfg, 0);
6567 emit_int16 (acfg, mono_metadata_token_index (entry->token));
6569 emit_int16 (acfg, entry->next->index);
6571 emit_int16 (acfg, 0);
6577 emit_image_table (MonoAotCompile *acfg)
6583 * The image table is small but referenced in a lot of places.
6584 * So we emit it at once, and reference its elements by an index.
6587 sprintf (symbol, "image_table");
6588 emit_section_change (acfg, RODATA_SECT, 1);
6589 emit_alignment (acfg, 8);
6590 emit_label (acfg, symbol);
6592 emit_int32 (acfg, acfg->image_table->len);
6593 for (i = 0; i < acfg->image_table->len; i++) {
6594 MonoImage *image = (MonoImage*)g_ptr_array_index (acfg->image_table, i);
6595 MonoAssemblyName *aname = &image->assembly->aname;
6597 /* FIXME: Support multi-module assemblies */
6598 g_assert (image->assembly->image == image);
6600 emit_string (acfg, image->assembly_name);
6601 emit_string (acfg, image->guid);
6602 emit_string (acfg, aname->culture ? aname->culture : "");
6603 emit_string (acfg, (const char*)aname->public_key_token);
6605 emit_alignment (acfg, 8);
6606 emit_int32 (acfg, aname->flags);
6607 emit_int32 (acfg, aname->major);
6608 emit_int32 (acfg, aname->minor);
6609 emit_int32 (acfg, aname->build);
6610 emit_int32 (acfg, aname->revision);
6615 emit_got_info (MonoAotCompile *acfg)
6618 int i, first_plt_got_patch, buf_size;
6620 guint32 *got_info_offsets;
6622 /* Add the patches needed by the PLT to the GOT */
6623 acfg->plt_got_offset_base = acfg->got_offset;
6624 first_plt_got_patch = acfg->got_patches->len;
6625 for (i = 1; i < acfg->plt_offset; ++i) {
6626 MonoPltEntry *plt_entry = g_hash_table_lookup (acfg->plt_offset_to_entry, GUINT_TO_POINTER (i));
6628 g_ptr_array_add (acfg->got_patches, plt_entry->ji);
6630 acfg->stats.got_slot_types [plt_entry->ji->type] ++;
6633 acfg->got_offset += acfg->plt_offset;
6637 * - optimize offsets table.
6638 * - reduce number of exported symbols.
6639 * - emit info for a klass only once.
6640 * - determine when a method uses a GOT slot which is guaranteed to be already
6642 * - clean up and document the code.
6643 * - use String.Empty in class libs.
6646 /* Encode info required to decode shared GOT entries */
6647 buf_size = acfg->got_patches->len * 128;
6648 p = buf = mono_mempool_alloc (acfg->mempool, buf_size);
6649 got_info_offsets = mono_mempool_alloc (acfg->mempool, acfg->got_patches->len * sizeof (guint32));
6650 acfg->plt_got_info_offsets = mono_mempool_alloc (acfg->mempool, acfg->plt_offset * sizeof (guint32));
6652 if (acfg->plt_offset)
6653 acfg->plt_got_info_offsets [0] = 0;
6654 for (i = 0; i < acfg->got_patches->len; ++i) {
6655 MonoJumpInfo *ji = g_ptr_array_index (acfg->got_patches, i);
6660 encode_value (ji->type, p, &p);
6662 encode_patch (acfg, ji, p, &p);
6663 acfg->stats.got_slot_info_sizes [ji->type] += p - p2;
6664 g_assert (p - buf <= buf_size);
6665 got_info_offsets [i] = add_to_blob (acfg, buf, p - buf);
6667 if (i >= first_plt_got_patch)
6668 acfg->plt_got_info_offsets [i - first_plt_got_patch + 1] = got_info_offsets [i];
6669 acfg->stats.got_info_size += p - buf;
6672 /* Emit got_info_offsets table */
6673 sprintf (symbol, "got_info_offsets");
6674 emit_section_change (acfg, RODATA_SECT, 1);
6675 emit_alignment (acfg, 8);
6676 emit_label (acfg, symbol);
6678 /* No need to emit offsets for the got plt entries, the plt embeds them directly */
6679 acfg->stats.offsets_size += emit_offset_table (acfg, first_plt_got_patch, 10, (gint32*)got_info_offsets);
6683 emit_got (MonoAotCompile *acfg)
6688 /* Don't make GOT global so accesses to it don't need relocations */
6689 sprintf (symbol, "%s", acfg->got_symbol);
6690 emit_section_change (acfg, ".bss", 0);
6691 emit_alignment (acfg, 8);
6692 emit_local_symbol (acfg, symbol, "got_end", FALSE);
6693 emit_label (acfg, symbol);
6694 if (acfg->got_offset > 0)
6695 emit_zero_bytes (acfg, (int)(acfg->got_offset * sizeof (gpointer)));
6697 sprintf (symbol, "got_end");
6698 emit_label (acfg, symbol);
6702 typedef struct GlobalsTableEntry {
6703 guint32 value, index;
6704 struct GlobalsTableEntry *next;
6705 } GlobalsTableEntry;
6708 emit_globals (MonoAotCompile *acfg)
6714 GlobalsTableEntry *entry, *new_entry;
6716 if (!acfg->aot_opts.static_link)
6720 * When static linking, we emit a table containing our globals.
6724 * Construct a chained hash table for mapping global names to their index in
6725 * the globals table.
6727 table_size = g_spaced_primes_closest ((int)(acfg->globals->len * 1.5));
6728 table = g_ptr_array_sized_new (table_size);
6729 for (i = 0; i < table_size; ++i)
6730 g_ptr_array_add (table, NULL);
6731 for (i = 0; i < acfg->globals->len; ++i) {
6732 char *name = g_ptr_array_index (acfg->globals, i);
6734 hash = mono_metadata_str_hash (name) % table_size;
6736 /* FIXME: Allocate from the mempool */
6737 new_entry = g_new0 (GlobalsTableEntry, 1);
6738 new_entry->value = i;
6740 entry = g_ptr_array_index (table, hash);
6741 if (entry == NULL) {
6742 new_entry->index = hash;
6743 g_ptr_array_index (table, hash) = new_entry;
6746 entry = entry->next;
6748 entry->next = new_entry;
6749 new_entry->index = table->len;
6750 g_ptr_array_add (table, new_entry);
6754 /* Emit the table */
6755 sprintf (symbol, ".Lglobals_hash");
6756 emit_section_change (acfg, RODATA_SECT, 0);
6757 emit_alignment (acfg, 8);
6758 emit_label (acfg, symbol);
6760 /* FIXME: Optimize memory usage */
6761 g_assert (table_size < 65000);
6762 emit_int16 (acfg, table_size);
6763 for (i = 0; i < table->len; ++i) {
6764 GlobalsTableEntry *entry = g_ptr_array_index (table, i);
6766 if (entry == NULL) {
6767 emit_int16 (acfg, 0);
6768 emit_int16 (acfg, 0);
6770 emit_int16 (acfg, entry->value + 1);
6772 emit_int16 (acfg, entry->next->index);
6774 emit_int16 (acfg, 0);
6778 /* Emit the names */
6779 for (i = 0; i < acfg->globals->len; ++i) {
6780 char *name = g_ptr_array_index (acfg->globals, i);
6782 sprintf (symbol, "name_%d", i);
6783 emit_section_change (acfg, RODATA_SECT, 1);
6785 emit_alignment (acfg, 4);
6787 emit_label (acfg, symbol);
6788 emit_string (acfg, name);
6791 /* Emit the globals table */
6792 sprintf (symbol, "globals");
6793 emit_section_change (acfg, ".data", 0);
6794 /* This is not a global, since it is accessed by the init function */
6795 emit_alignment (acfg, 8);
6796 emit_label (acfg, symbol);
6798 sprintf (symbol, "%sglobals_hash", acfg->temp_prefix);
6799 emit_pointer (acfg, symbol);
6801 for (i = 0; i < acfg->globals->len; ++i) {
6802 char *name = g_ptr_array_index (acfg->globals, i);
6804 sprintf (symbol, "name_%d", i);
6805 emit_pointer (acfg, symbol);
6807 sprintf (symbol, "%s", name);
6808 emit_pointer (acfg, symbol);
6810 /* Null terminate the table */
6811 emit_int32 (acfg, 0);
6812 emit_int32 (acfg, 0);
6816 emit_autoreg (MonoAotCompile *acfg)
6821 * Emit a function into the .ctor section which will be called by the ELF
6822 * loader to register this module with the runtime.
6824 if (! (!acfg->use_bin_writer && acfg->aot_opts.static_link && acfg->aot_opts.autoreg))
6827 symbol = g_strdup_printf ("_%s_autoreg", acfg->static_linking_symbol);
6829 arch_emit_autoreg (acfg, symbol);
6835 emit_mem_end (MonoAotCompile *acfg)
6839 sprintf (symbol, "mem_end");
6840 emit_section_change (acfg, ".text", 1);
6841 emit_alignment (acfg, 8);
6842 emit_label (acfg, symbol);
6846 * Emit a structure containing all the information not stored elsewhere.
6849 emit_file_info (MonoAotCompile *acfg)
6854 const char *gc_name;
6857 emit_string_symbol (acfg, "assembly_guid" , acfg->image->guid);
6859 if (acfg->aot_opts.bind_to_runtime_version) {
6860 build_info = mono_get_runtime_build_info ();
6861 emit_string_symbol (acfg, "runtime_version", build_info);
6862 g_free (build_info);
6864 emit_string_symbol (acfg, "runtime_version", "");
6867 /* Emit a string holding the assembly name */
6868 emit_string_symbol (acfg, "assembly_name", acfg->image->assembly->aname.name);
6871 * The managed allocators are GC specific, so can't use an AOT image created by one GC
6874 gc_name = mono_gc_get_gc_name ();
6875 gc_name_offset = add_to_blob (acfg, (guint8*)gc_name, strlen (gc_name) + 1);
6877 sprintf (symbol, "mono_aot_file_info");
6878 emit_section_change (acfg, ".data", 0);
6879 emit_alignment (acfg, 8);
6880 emit_label (acfg, symbol);
6881 if (!acfg->aot_opts.static_link)
6882 emit_global (acfg, symbol, FALSE);
6884 /* The data emitted here must match MonoAotFileInfo. */
6886 emit_int32 (acfg, MONO_AOT_FILE_VERSION);
6887 emit_int32 (acfg, 0);
6890 * We emit pointers to our data structures instead of emitting global symbols which
6891 * point to them, to reduce the number of globals, and because using globals leads to
6892 * various problems (i.e. arm/thumb).
6894 emit_pointer (acfg, acfg->got_symbol);
6895 emit_pointer (acfg, "methods");
6898 * Emit a reference to the mono_eh_frame table created by our modified LLVM compiler.
6900 emit_pointer (acfg, "mono_eh_frame");
6902 emit_pointer (acfg, NULL);
6904 emit_pointer (acfg, "blob");
6905 emit_pointer (acfg, "class_name_table");
6906 emit_pointer (acfg, "class_info_offsets");
6907 emit_pointer (acfg, "method_info_offsets");
6908 emit_pointer (acfg, "ex_info_offsets");
6909 emit_pointer (acfg, "code_offsets");
6910 emit_pointer (acfg, "extra_method_info_offsets");
6911 emit_pointer (acfg, "extra_method_table");
6912 emit_pointer (acfg, "got_info_offsets");
6913 emit_pointer (acfg, "methods_end");
6914 emit_pointer (acfg, "unwind_info");
6915 emit_pointer (acfg, "mem_end");
6916 emit_pointer (acfg, "image_table");
6917 emit_pointer (acfg, "plt");
6918 emit_pointer (acfg, "plt_end");
6919 emit_pointer (acfg, "assembly_guid");
6920 emit_pointer (acfg, "runtime_version");
6921 if (acfg->num_trampoline_got_entries) {
6922 emit_pointer (acfg, "specific_trampolines");
6923 emit_pointer (acfg, "static_rgctx_trampolines");
6924 emit_pointer (acfg, "imt_thunks");
6926 emit_pointer (acfg, NULL);
6927 emit_pointer (acfg, NULL);
6928 emit_pointer (acfg, NULL);
6930 if (acfg->thumb_mixed) {
6931 emit_pointer (acfg, "thumb_end");
6933 emit_pointer (acfg, NULL);
6935 if (acfg->aot_opts.static_link) {
6936 emit_pointer (acfg, "globals");
6938 emit_pointer (acfg, NULL);
6940 emit_pointer (acfg, "assembly_name");
6941 emit_pointer (acfg, "unbox_trampolines");
6942 emit_pointer (acfg, "unbox_trampolines_end");
6944 emit_int32 (acfg, acfg->plt_got_offset_base);
6945 emit_int32 (acfg, (int)(acfg->got_offset * sizeof (gpointer)));
6946 emit_int32 (acfg, acfg->plt_offset);
6947 emit_int32 (acfg, acfg->nmethods);
6948 emit_int32 (acfg, acfg->flags);
6949 emit_int32 (acfg, acfg->opts);
6950 emit_int32 (acfg, gc_name_offset);
6952 for (i = 0; i < MONO_AOT_TRAMP_NUM; ++i)
6953 emit_int32 (acfg, acfg->num_trampolines [i]);
6954 for (i = 0; i < MONO_AOT_TRAMP_NUM; ++i)
6955 emit_int32 (acfg, acfg->trampoline_got_offset_base [i]);
6956 for (i = 0; i < MONO_AOT_TRAMP_NUM; ++i)
6957 emit_int32 (acfg, acfg->trampoline_size [i]);
6959 #if defined (TARGET_ARM) && defined (__APPLE__)
6964 t.type = MONO_TYPE_R8;
6965 mono_type_size (&t, &align);
6967 emit_int32 (acfg, align);
6969 t.type = MONO_TYPE_I8;
6970 mono_type_size (&t, &align);
6972 emit_int32 (acfg, align);
6975 emit_int32 (acfg, __alignof__ (double));
6976 emit_int32 (acfg, __alignof__ (gint64));
6979 if (acfg->aot_opts.static_link) {
6983 * Emit a global symbol which can be passed by an embedding app to
6984 * mono_aot_register_module (). The symbol points to a pointer to the the file info
6987 #if defined(__APPLE__) && !defined(__native_client_codegen__)
6988 sprintf (symbol, "_mono_aot_module_%s_info", acfg->image->assembly->aname.name);
6990 sprintf (symbol, "mono_aot_module_%s_info", acfg->image->assembly->aname.name);
6993 /* Get rid of characters which cannot occur in symbols */
6995 for (p = symbol; *p; ++p) {
6996 if (!(isalnum (*p) || *p == '_'))
6999 acfg->static_linking_symbol = g_strdup (symbol);
7000 emit_global_inner (acfg, symbol, FALSE);
7001 emit_label (acfg, symbol);
7002 emit_pointer (acfg, "mono_aot_file_info");
7007 emit_blob (MonoAotCompile *acfg)
7011 sprintf (symbol, "blob");
7012 emit_section_change (acfg, RODATA_SECT, 1);
7013 emit_alignment (acfg, 8);
7014 emit_label (acfg, symbol);
7016 emit_bytes (acfg, (guint8*)acfg->blob.data, acfg->blob.index);
7020 emit_dwarf_info (MonoAotCompile *acfg)
7022 #ifdef EMIT_DWARF_INFO
7024 char symbol [128], symbol2 [128];
7026 /* DIEs for methods */
7027 for (i = 0; i < acfg->nmethods; ++i) {
7028 MonoCompile *cfg = acfg->cfgs [i];
7033 // FIXME: LLVM doesn't define .Lme_...
7034 if (cfg->compile_llvm)
7037 sprintf (symbol, "%s", cfg->asm_symbol);
7038 sprintf (symbol2, "%sme_%x", acfg->temp_prefix, i);
7040 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 ()));
7046 collect_methods (MonoAotCompile *acfg)
7049 MonoImage *image = acfg->image;
7051 /* Collect methods */
7052 for (i = 0; i < image->tables [MONO_TABLE_METHOD].rows; ++i) {
7054 guint32 token = MONO_TOKEN_METHOD_DEF | (i + 1);
7056 method = mono_get_method (acfg->image, token, NULL);
7059 printf ("Failed to load method 0x%x from '%s'.\n", token, image->name);
7063 /* Load all methods eagerly to skip the slower lazy loading code */
7064 mono_class_setup_methods (method->klass);
7066 if (acfg->aot_opts.full_aot && method->iflags & METHOD_IMPL_ATTRIBUTE_INTERNAL_CALL) {
7067 /* Compile the wrapper instead */
7068 /* We do this here instead of add_wrappers () because it is easy to do it here */
7069 MonoMethod *wrapper = mono_marshal_get_native_wrapper (method, check_for_pending_exc, TRUE);
7073 /* FIXME: Some mscorlib methods don't have debug info */
7075 if (acfg->aot_opts.soft_debug && !method->wrapper_type) {
7076 if (!((method->flags & METHOD_ATTRIBUTE_PINVOKE_IMPL) ||
7077 (method->iflags & METHOD_IMPL_ATTRIBUTE_RUNTIME) ||
7078 (method->flags & METHOD_ATTRIBUTE_ABSTRACT) ||
7079 (method->iflags & METHOD_IMPL_ATTRIBUTE_INTERNAL_CALL))) {
7080 if (!mono_debug_lookup_method (method)) {
7081 fprintf (stderr, "Method %s has no debug info, probably the .mdb file for the assembly is missing.\n", mono_method_full_name (method, TRUE));
7088 /* Since we add the normal methods first, their index will be equal to their zero based token index */
7089 add_method_with_index (acfg, method, i, FALSE);
7090 acfg->method_index ++;
7093 add_generic_instances (acfg);
7095 if (acfg->aot_opts.full_aot)
7096 add_wrappers (acfg);
7100 compile_methods (MonoAotCompile *acfg)
7104 if (acfg->aot_opts.nthreads > 0) {
7109 gpointer *user_data;
7110 MonoMethod **methods;
7112 methods_len = acfg->methods->len;
7114 len = acfg->methods->len / acfg->aot_opts.nthreads;
7117 * Partition the list of methods into fragments, and hand it to threads to
7120 threads = g_ptr_array_new ();
7121 /* Make a copy since acfg->methods is modified by compile_method () */
7122 methods = g_new0 (MonoMethod*, methods_len);
7123 //memcpy (methods, g_ptr_array_index (acfg->methods, 0), sizeof (MonoMethod*) * methods_len);
7124 for (i = 0; i < methods_len; ++i)
7125 methods [i] = g_ptr_array_index (acfg->methods, i);
7127 while (i < methods_len) {
7128 frag = g_ptr_array_new ();
7129 for (j = 0; j < len; ++j) {
7130 if (i < methods_len) {
7131 g_ptr_array_add (frag, methods [i]);
7136 user_data = g_new0 (gpointer, 3);
7137 user_data [0] = mono_domain_get ();
7138 user_data [1] = acfg;
7139 user_data [2] = frag;
7141 handle = mono_create_thread (NULL, 0, (gpointer)compile_thread_main, user_data, 0, NULL);
7142 g_ptr_array_add (threads, handle);
7146 for (i = 0; i < threads->len; ++i) {
7147 WaitForSingleObjectEx (g_ptr_array_index (threads, i), INFINITE, FALSE);
7153 /* Compile methods added by compile_method () or all methods if nthreads == 0 */
7154 for (i = methods_len; i < acfg->methods->len; ++i) {
7155 /* This can new methods to acfg->methods */
7156 compile_method (acfg, g_ptr_array_index (acfg->methods, i));
7161 compile_asm (MonoAotCompile *acfg)
7163 char *command, *objfile;
7164 char *outfile_name, *tmp_outfile_name;
7165 const char *tool_prefix = acfg->aot_opts.tool_prefix ? acfg->aot_opts.tool_prefix : "";
7167 #if defined(TARGET_AMD64)
7168 #define AS_OPTIONS "--64"
7169 #elif defined(TARGET_POWERPC64)
7170 #define AS_OPTIONS "-a64 -mppc64"
7171 #define LD_OPTIONS "-m elf64ppc"
7172 #elif defined(sparc) && SIZEOF_VOID_P == 8
7173 #define AS_OPTIONS "-xarch=v9"
7174 #elif defined(TARGET_X86) && defined(__APPLE__) && !defined(__native_client_codegen__)
7175 #define AS_OPTIONS "-arch i386 -W"
7177 #define AS_OPTIONS ""
7180 #ifdef __native_client_codegen__
7181 #if defined(TARGET_AMD64)
7182 #define AS_NAME "nacl64-as"
7184 #define AS_NAME "nacl-as"
7187 #define AS_NAME "as"
7191 #define LD_OPTIONS ""
7194 #define EH_LD_OPTIONS ""
7196 if (acfg->aot_opts.asm_only) {
7197 printf ("Output file: '%s'.\n", acfg->tmpfname);
7198 if (acfg->aot_opts.static_link)
7199 printf ("Linking symbol: '%s'.\n", acfg->static_linking_symbol);
7203 if (acfg->aot_opts.static_link) {
7204 if (acfg->aot_opts.outfile)
7205 objfile = g_strdup_printf ("%s", acfg->aot_opts.outfile);
7207 objfile = g_strdup_printf ("%s.o", acfg->image->name);
7209 objfile = g_strdup_printf ("%s.o", acfg->tmpfname);
7211 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);
7212 printf ("Executing the native assembler: %s\n", command);
7213 if (system (command) != 0) {
7221 if (acfg->aot_opts.static_link) {
7222 printf ("Output file: '%s'.\n", objfile);
7223 printf ("Linking symbol: '%s'.\n", acfg->static_linking_symbol);
7228 if (acfg->aot_opts.outfile)
7229 outfile_name = g_strdup_printf ("%s", acfg->aot_opts.outfile);
7231 outfile_name = g_strdup_printf ("%s%s", acfg->image->name, SHARED_EXT);
7233 tmp_outfile_name = g_strdup_printf ("%s.tmp", outfile_name);
7236 command = g_strdup_printf ("ld -shared -G -o %s %s.o", tmp_outfile_name, acfg->tmpfname);
7237 #elif defined(__ppc__) && defined(__APPLE__)
7238 command = g_strdup_printf ("gcc -dynamiclib -o %s %s.o", tmp_outfile_name, acfg->tmpfname);
7239 #elif defined(HOST_WIN32)
7240 command = g_strdup_printf ("gcc -shared --dll -mno-cygwin -o %s %s.o", tmp_outfile_name, acfg->tmpfname);
7241 #elif defined(TARGET_X86) && defined(__APPLE__) && !defined(__native_client_codegen__)
7242 command = g_strdup_printf ("gcc -m32 -dynamiclib -o %s %s.o", tmp_outfile_name, acfg->tmpfname);
7244 command = g_strdup_printf ("%sld %s %s -shared -o %s %s.o", tool_prefix, EH_LD_OPTIONS, LD_OPTIONS, tmp_outfile_name, acfg->tmpfname);
7246 printf ("Executing the native linker: %s\n", command);
7247 if (system (command) != 0) {
7248 g_free (tmp_outfile_name);
7249 g_free (outfile_name);
7257 /*com = g_strdup_printf ("strip --strip-unneeded %s%s", acfg->image->name, SHARED_EXT);
7258 printf ("Stripping the binary: %s\n", com);
7262 #if defined(TARGET_ARM) && !defined(__APPLE__)
7264 * gas generates 'mapping symbols' each time code and data is mixed, which
7265 * happens a lot in emit_and_reloc_code (), so we need to get rid of them.
7267 command = g_strdup_printf ("%sstrip --strip-symbol=\\$a --strip-symbol=\\$d %s", tool_prefix, tmp_outfile_name);
7268 printf ("Stripping the binary: %s\n", command);
7269 if (system (command) != 0) {
7270 g_free (tmp_outfile_name);
7271 g_free (outfile_name);
7278 rename (tmp_outfile_name, outfile_name);
7280 g_free (tmp_outfile_name);
7281 g_free (outfile_name);
7284 if (acfg->aot_opts.save_temps)
7285 printf ("Retained input file.\n");
7287 unlink (acfg->tmpfname);
7292 static MonoAotCompile*
7293 acfg_create (MonoAssembly *ass, guint32 opts)
7295 MonoImage *image = ass->image;
7296 MonoAotCompile *acfg;
7299 acfg = g_new0 (MonoAotCompile, 1);
7300 acfg->methods = g_ptr_array_new ();
7301 acfg->method_indexes = g_hash_table_new (NULL, NULL);
7302 acfg->method_depth = g_hash_table_new (NULL, NULL);
7303 acfg->plt_offset_to_entry = g_hash_table_new (NULL, NULL);
7304 acfg->patch_to_plt_entry = g_hash_table_new (mono_patch_info_hash, mono_patch_info_equal);
7305 acfg->patch_to_got_offset = g_hash_table_new (mono_patch_info_hash, mono_patch_info_equal);
7306 acfg->patch_to_got_offset_by_type = g_new0 (GHashTable*, MONO_PATCH_INFO_NUM);
7307 for (i = 0; i < MONO_PATCH_INFO_NUM; ++i)
7308 acfg->patch_to_got_offset_by_type [i] = g_hash_table_new (mono_patch_info_hash, mono_patch_info_equal);
7309 acfg->got_patches = g_ptr_array_new ();
7310 acfg->method_to_cfg = g_hash_table_new (NULL, NULL);
7311 acfg->token_info_hash = g_hash_table_new_full (NULL, NULL, NULL, g_free);
7312 acfg->method_to_pinvoke_import = g_hash_table_new_full (NULL, NULL, NULL, g_free);
7313 acfg->image_hash = g_hash_table_new (NULL, NULL);
7314 acfg->image_table = g_ptr_array_new ();
7315 acfg->globals = g_ptr_array_new ();
7316 acfg->image = image;
7318 acfg->mempool = mono_mempool_new ();
7319 acfg->extra_methods = g_ptr_array_new ();
7320 acfg->unwind_info_offsets = g_hash_table_new (NULL, NULL);
7321 acfg->unwind_ops = g_ptr_array_new ();
7322 acfg->method_label_hash = g_hash_table_new_full (g_str_hash, g_str_equal, g_free, NULL);
7323 acfg->method_order = g_ptr_array_new ();
7324 acfg->export_names = g_hash_table_new (NULL, NULL);
7325 acfg->klass_blob_hash = g_hash_table_new (NULL, NULL);
7326 acfg->method_blob_hash = g_hash_table_new (NULL, NULL);
7327 acfg->plt_entry_debug_sym_cache = g_hash_table_new (g_str_hash, g_str_equal);
7328 InitializeCriticalSection (&acfg->mutex);
7334 acfg_free (MonoAotCompile *acfg)
7338 img_writer_destroy (acfg->w);
7339 for (i = 0; i < acfg->nmethods; ++i)
7341 g_free (acfg->cfgs [i]);
7342 g_free (acfg->cfgs);
7343 g_free (acfg->static_linking_symbol);
7344 g_free (acfg->got_symbol);
7345 g_free (acfg->plt_symbol);
7346 g_ptr_array_free (acfg->methods, TRUE);
7347 g_ptr_array_free (acfg->got_patches, TRUE);
7348 g_ptr_array_free (acfg->image_table, TRUE);
7349 g_ptr_array_free (acfg->globals, TRUE);
7350 g_ptr_array_free (acfg->unwind_ops, TRUE);
7351 g_hash_table_destroy (acfg->method_indexes);
7352 g_hash_table_destroy (acfg->method_depth);
7353 g_hash_table_destroy (acfg->plt_offset_to_entry);
7354 g_hash_table_destroy (acfg->patch_to_plt_entry);
7355 g_hash_table_destroy (acfg->patch_to_got_offset);
7356 g_hash_table_destroy (acfg->method_to_cfg);
7357 g_hash_table_destroy (acfg->token_info_hash);
7358 g_hash_table_destroy (acfg->method_to_pinvoke_import);
7359 g_hash_table_destroy (acfg->image_hash);
7360 g_hash_table_destroy (acfg->unwind_info_offsets);
7361 g_hash_table_destroy (acfg->method_label_hash);
7362 g_hash_table_destroy (acfg->export_names);
7363 g_hash_table_destroy (acfg->plt_entry_debug_sym_cache);
7364 g_hash_table_destroy (acfg->klass_blob_hash);
7365 g_hash_table_destroy (acfg->method_blob_hash);
7366 for (i = 0; i < MONO_PATCH_INFO_NUM; ++i)
7367 g_hash_table_destroy (acfg->patch_to_got_offset_by_type [i]);
7368 g_free (acfg->patch_to_got_offset_by_type);
7369 mono_mempool_destroy (acfg->mempool);
7374 mono_compile_assembly (MonoAssembly *ass, guint32 opts, const char *aot_options)
7376 MonoImage *image = ass->image;
7378 MonoAotCompile *acfg;
7379 char *outfile_name, *tmp_outfile_name, *p;
7383 printf ("Mono Ahead of Time compiler - compiling assembly %s\n", image->name);
7385 acfg = acfg_create (ass, opts);
7387 memset (&acfg->aot_opts, 0, sizeof (acfg->aot_opts));
7388 acfg->aot_opts.write_symbols = TRUE;
7389 acfg->aot_opts.ntrampolines = 1024;
7390 acfg->aot_opts.nrgctx_trampolines = 1024;
7391 acfg->aot_opts.nimt_trampolines = 128;
7392 acfg->aot_opts.llvm_path = g_strdup ("");
7394 mono_aot_parse_options (aot_options, &acfg->aot_opts);
7396 if (acfg->aot_opts.static_link)
7397 acfg->aot_opts.autoreg = TRUE;
7399 //acfg->aot_opts.print_skipped_methods = TRUE;
7401 #ifndef MONO_ARCH_HAVE_FULL_AOT_TRAMPOLINES
7402 if (acfg->aot_opts.full_aot) {
7403 printf ("--aot=full is not supported on this platform.\n");
7408 if (acfg->aot_opts.direct_pinvoke && !acfg->aot_opts.static_link) {
7409 fprintf (stderr, "The 'direct-pinvoke' AOT option also requires the 'static' AOT option.\n");
7413 if (acfg->aot_opts.static_link)
7414 acfg->aot_opts.asm_writer = TRUE;
7416 if (acfg->aot_opts.soft_debug) {
7417 MonoDebugOptions *opt = mini_get_debug_options ();
7419 opt->mdb_optimizations = TRUE;
7420 opt->gen_seq_points = TRUE;
7422 if (mono_debug_format == MONO_DEBUG_FORMAT_NONE) {
7423 fprintf (stderr, "The soft-debug AOT option requires the --debug option.\n");
7426 acfg->flags |= MONO_AOT_FILE_FLAG_DEBUG;
7429 if (mono_use_llvm) {
7431 acfg->aot_opts.asm_writer = TRUE;
7432 acfg->flags |= MONO_AOT_FILE_FLAG_WITH_LLVM;
7434 if (acfg->aot_opts.soft_debug) {
7435 fprintf (stderr, "The 'soft-debug' option is not supported when compiling with LLVM.\n");
7440 if (acfg->aot_opts.full_aot)
7441 acfg->flags |= MONO_AOT_FILE_FLAG_FULL_AOT;
7443 load_profile_files (acfg);
7445 acfg->num_trampolines [MONO_AOT_TRAMP_SPECIFIC] = acfg->aot_opts.full_aot ? acfg->aot_opts.ntrampolines : 0;
7446 #ifdef MONO_ARCH_GSHARED_SUPPORTED
7447 acfg->num_trampolines [MONO_AOT_TRAMP_STATIC_RGCTX] = acfg->aot_opts.full_aot ? acfg->aot_opts.nrgctx_trampolines : 0;
7449 acfg->num_trampolines [MONO_AOT_TRAMP_IMT_THUNK] = acfg->aot_opts.full_aot ? acfg->aot_opts.nimt_trampolines : 0;
7451 acfg->temp_prefix = img_writer_get_temp_label_prefix (NULL);
7455 acfg->got_symbol_base = g_strdup_printf ("mono_aot_%s_got", acfg->image->assembly->aname.name);
7456 acfg->plt_symbol = g_strdup_printf ("%smono_aot_%s_plt", acfg->llvm_label_prefix, acfg->image->assembly->aname.name);
7457 acfg->assembly_name_sym = g_strdup (acfg->image->assembly->aname.name);
7459 /* Get rid of characters which cannot occur in symbols */
7460 for (p = acfg->got_symbol_base; *p; ++p) {
7461 if (!(isalnum (*p) || *p == '_'))
7464 for (p = acfg->plt_symbol; *p; ++p) {
7465 if (!(isalnum (*p) || *p == '_'))
7468 for (p = acfg->assembly_name_sym; *p; ++p) {
7469 if (!(isalnum (*p) || *p == '_'))
7473 acfg->method_index = 1;
7475 collect_methods (acfg);
7477 acfg->cfgs_size = acfg->methods->len + 32;
7478 acfg->cfgs = g_new0 (MonoCompile*, acfg->cfgs_size);
7480 /* PLT offset 0 is reserved for the PLT trampoline */
7481 acfg->plt_offset = 1;
7486 mono_llvm_create_aot_module (acfg->got_symbol_base);
7490 /* GOT offset 0 is reserved for the address of the current assembly */
7494 ji = mono_mempool_alloc0 (acfg->mempool, sizeof (MonoAotCompile));
7495 ji->type = MONO_PATCH_INFO_IMAGE;
7496 ji->data.image = acfg->image;
7498 get_got_offset (acfg, ji);
7500 /* Slot 1 is reserved for the mscorlib got addr */
7501 ji = mono_mempool_alloc0 (acfg->mempool, sizeof (MonoAotCompile));
7502 ji->type = MONO_PATCH_INFO_MSCORLIB_GOT_ADDR;
7503 get_got_offset (acfg, ji);
7505 /* This is very common */
7506 ji = mono_mempool_alloc0 (acfg->mempool, sizeof (MonoAotCompile));
7507 ji->type = MONO_PATCH_INFO_GC_CARD_TABLE_ADDR;
7508 get_got_offset (acfg, ji);
7513 compile_methods (acfg);
7517 acfg->stats.jit_time = TV_ELAPSED (atv, btv);
7523 if (acfg->aot_opts.asm_only) {
7524 if (acfg->aot_opts.outfile)
7525 acfg->tmpfname = g_strdup_printf ("%s", acfg->aot_opts.outfile);
7527 acfg->tmpfname = g_strdup_printf ("%s.s", acfg->image->name);
7529 acfg->tmpfname = g_strdup ("temp.s");
7532 emit_llvm_file (acfg);
7536 if (!acfg->aot_opts.asm_only && !acfg->aot_opts.asm_writer && bin_writer_supported ()) {
7537 if (acfg->aot_opts.outfile)
7538 outfile_name = g_strdup_printf ("%s", acfg->aot_opts.outfile);
7540 outfile_name = g_strdup_printf ("%s%s", acfg->image->name, SHARED_EXT);
7543 * Can't use g_file_open_tmp () as it will be deleted at exit, and
7544 * it might be in another file system so the rename () won't work.
7546 tmp_outfile_name = g_strdup_printf ("%s.tmp", outfile_name);
7548 acfg->fp = fopen (tmp_outfile_name, "w");
7550 printf ("Unable to create temporary file '%s': %s\n", tmp_outfile_name, strerror (errno));
7554 acfg->w = img_writer_create (acfg->fp, TRUE);
7555 acfg->use_bin_writer = TRUE;
7558 /* Append to the .s file created by llvm */
7559 /* FIXME: Use multiple files instead */
7560 acfg->fp = fopen (acfg->tmpfname, "a+");
7562 if (acfg->aot_opts.asm_only) {
7563 if (acfg->aot_opts.outfile)
7564 acfg->tmpfname = g_strdup_printf ("%s", acfg->aot_opts.outfile);
7566 acfg->tmpfname = g_strdup_printf ("%s.s", acfg->image->name);
7567 acfg->fp = fopen (acfg->tmpfname, "w+");
7569 int i = g_file_open_tmp ("mono_aot_XXXXXX", &acfg->tmpfname, NULL);
7570 acfg->fp = fdopen (i, "w+");
7572 if (acfg->fp == 0) {
7573 fprintf (stderr, "Unable to open file '%s': %s\n", acfg->tmpfname, strerror (errno));
7577 acfg->w = img_writer_create (acfg->fp, FALSE);
7579 tmp_outfile_name = NULL;
7580 outfile_name = NULL;
7583 acfg->got_symbol = g_strdup_printf ("%s%s", acfg->llvm_label_prefix, acfg->got_symbol_base);
7585 /* Compute symbols for methods */
7586 for (i = 0; i < acfg->nmethods; ++i) {
7587 if (acfg->cfgs [i]) {
7588 MonoCompile *cfg = acfg->cfgs [i];
7589 int method_index = get_method_index (acfg, cfg->orig_method);
7591 if (COMPILE_LLVM (cfg))
7592 cfg->asm_symbol = g_strdup_printf ("%s%s", acfg->llvm_label_prefix, cfg->llvm_method_name);
7594 cfg->asm_symbol = g_strdup_printf ("%s%sm_%x", acfg->temp_prefix, acfg->llvm_label_prefix, method_index);
7598 if (!acfg->aot_opts.nodebug)
7599 acfg->dwarf = mono_dwarf_writer_create (acfg->w, NULL, 0, FALSE);
7601 img_writer_emit_start (acfg->w);
7604 mono_dwarf_writer_emit_base_info (acfg->dwarf, mono_unwind_get_cie_program ());
7606 if (acfg->thumb_mixed) {
7609 * This global symbol marks the end of THUMB code, and the beginning of ARM
7610 * code generated by our JIT.
7612 sprintf (symbol, "thumb_end");
7613 emit_section_change (acfg, ".text", 0);
7614 emit_label (acfg, symbol);
7615 emit_zero_bytes (acfg, 16);
7617 fprintf (acfg->fp, ".arm\n");
7624 emit_extra_methods (acfg);
7626 emit_trampolines (acfg);
7628 emit_class_name_table (acfg);
7630 emit_got_info (acfg);
7632 emit_exception_info (acfg);
7634 emit_unwind_info (acfg);
7636 emit_class_info (acfg);
7640 emit_image_table (acfg);
7644 emit_file_info (acfg);
7648 emit_globals (acfg);
7650 emit_autoreg (acfg);
7653 emit_dwarf_info (acfg);
7654 mono_dwarf_writer_close (acfg->dwarf);
7657 emit_mem_end (acfg);
7659 if (acfg->need_pt_gnu_stack) {
7660 /* This is required so the .so doesn't have an executable stack */
7661 /* The bin writer already emits this */
7662 if (!acfg->use_bin_writer)
7663 fprintf (acfg->fp, "\n.section .note.GNU-stack,\"\",@progbits\n");
7668 acfg->stats.gen_time = TV_ELAPSED (atv, btv);
7671 g_assert (acfg->got_offset <= acfg->final_got_size);
7673 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);
7676 res = img_writer_emit_writeout (acfg->w);
7681 if (acfg->use_bin_writer) {
7682 int err = rename (tmp_outfile_name, outfile_name);
7685 printf ("Unable to rename '%s' to '%s': %s\n", tmp_outfile_name, outfile_name, strerror (errno));
7689 res = compile_asm (acfg);
7696 acfg->stats.link_time = TV_ELAPSED (atv, btv);
7698 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);
7699 if (acfg->stats.genericcount)
7700 printf ("%d methods are generic (%d%%)\n", acfg->stats.genericcount, acfg->stats.mcount ? (acfg->stats.genericcount * 100) / acfg->stats.mcount : 100);
7701 if (acfg->stats.abscount)
7702 printf ("%d methods contain absolute addresses (%d%%)\n", acfg->stats.abscount, acfg->stats.mcount ? (acfg->stats.abscount * 100) / acfg->stats.mcount : 100);
7703 if (acfg->stats.lmfcount)
7704 printf ("%d methods contain lmf pointers (%d%%)\n", acfg->stats.lmfcount, acfg->stats.mcount ? (acfg->stats.lmfcount * 100) / acfg->stats.mcount : 100);
7705 if (acfg->stats.ocount)
7706 printf ("%d methods have other problems (%d%%)\n", acfg->stats.ocount, acfg->stats.mcount ? (acfg->stats.ocount * 100) / acfg->stats.mcount : 100);
7708 printf ("Methods compiled with LLVM: %d (%d%%)\n", acfg->stats.llvm_count, acfg->stats.mcount ? (acfg->stats.llvm_count * 100) / acfg->stats.mcount : 100);
7709 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);
7710 printf ("Direct calls: %d (%d%%)\n", acfg->stats.direct_calls, acfg->stats.all_calls ? (acfg->stats.direct_calls * 100) / acfg->stats.all_calls : 100);
7712 if (acfg->aot_opts.stats) {
7715 printf ("GOT slot distribution:\n");
7716 for (i = 0; i < MONO_PATCH_INFO_NONE; ++i)
7717 if (acfg->stats.got_slot_types [i])
7718 printf ("\t%s: %d (%d)\n", get_patch_name (i), acfg->stats.got_slot_types [i], acfg->stats.got_slot_info_sizes [i]);
7721 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);
7733 mono_aot_readonly_field_override (MonoClassField *field)
7739 mono_compile_assembly (MonoAssembly *ass, guint32 opts, const char *aot_options)