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.
11 /* Remaining AOT-only work:
12 * - optimize the trampolines, generate more code in the arch files.
13 * - make things more consistent with how elf works, for example, use ELF
15 * Remaining generics sharing work:
16 * - optimize the size of the data which is encoded.
17 * - optimize the runtime loading of data:
18 * - the trampoline code calls mono_jit_info_table_find () to find the rgctx,
19 * which loads the debugging+exception handling info for the method. This is a
20 * huge waste of time and code, since the rgctx structure is currently empty.
21 * - every shared method has a MonoGenericJitInfo structure which is only really
22 * used for handling catch clauses with open types, not a very common use case.
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.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 #define TV_DECLARE(name) gint64 name
72 #define TV_GETTIME(tv) tv = mono_100ns_ticks ()
73 #define TV_ELAPSED(start,end) (((end) - (start)) / 10)
76 #define SHARED_EXT ".dll"
77 #elif defined(__ppc__) && defined(__MACH__)
78 #define SHARED_EXT ".dylib"
80 #define SHARED_EXT ".so"
83 #define ALIGN_TO(val,align) ((((guint64)val) + ((align) - 1)) & ~((align) - 1))
84 #define ALIGN_PTR_TO(ptr,align) (gpointer)((((gssize)(ptr)) + (align - 1)) & (~(align - 1)))
85 #define ROUND_DOWN(VALUE,SIZE) ((VALUE) & ~((SIZE) - 1))
87 typedef struct MonoAotOptions {
90 gboolean write_symbols;
91 gboolean metadata_only;
92 gboolean bind_to_runtime_version;
102 int nrgctx_trampolines;
103 gboolean print_skipped_methods;
109 typedef struct MonoAotStats {
110 int ccount, mcount, lmfcount, abscount, gcount, ocount, genericcount;
111 int code_size, info_size, ex_info_size, unwind_info_size, got_size, class_info_size, got_info_size;
112 int methods_without_got_slots, direct_calls, all_calls, llvm_count;
113 int got_slots, offsets_size;
114 int got_slot_types [MONO_PATCH_INFO_NONE];
115 int jit_time, gen_time, link_time;
118 typedef struct MonoAotCompile {
121 GHashTable *method_indexes;
122 GHashTable *method_depth;
125 GHashTable *patch_to_plt_offset;
126 GHashTable *plt_offset_to_patch;
127 GHashTable *patch_to_got_offset;
128 GHashTable **patch_to_got_offset_by_type;
129 GPtrArray *got_patches;
130 GHashTable *image_hash;
131 GHashTable *method_to_cfg;
132 GHashTable *token_info_hash;
133 GPtrArray *extra_methods;
134 GPtrArray *image_table;
137 guint32 *plt_got_info_offsets;
138 guint32 got_offset, plt_offset, plt_got_offset_base;
139 guint32 final_got_size;
140 /* Number of GOT entries reserved for trampolines */
141 guint32 num_trampoline_got_entries;
143 guint32 num_trampolines [MONO_AOT_TRAMP_NUM];
144 guint32 trampoline_got_offset_base [MONO_AOT_TRAMP_NUM];
145 guint32 trampoline_size [MONO_AOT_TRAMP_NUM];
147 MonoAotOptions aot_opts;
150 MonoMemPool *mempool;
153 char *static_linking_symbol;
154 CRITICAL_SECTION mutex;
155 gboolean use_bin_writer;
157 MonoDwarfWriter *dwarf;
161 GHashTable *unwind_info_offsets;
162 GPtrArray *unwind_ops;
163 guint32 unwind_info_offset;
166 GHashTable *method_label_hash;
167 const char *temp_prefix;
168 guint32 label_generator;
170 MonoAotFileFlags flags;
171 MonoDynamicStream blob;
174 #define mono_acfg_lock(acfg) EnterCriticalSection (&((acfg)->mutex))
175 #define mono_acfg_unlock(acfg) LeaveCriticalSection (&((acfg)->mutex))
177 /* This points to the current acfg in LLVM mode */
178 static MonoAotCompile *llvm_acfg;
180 #ifdef HAVE_ARRAY_ELEM_INIT
181 #define MSGSTRFIELD(line) MSGSTRFIELD1(line)
182 #define MSGSTRFIELD1(line) str##line
183 static const struct msgstr_t {
184 #define PATCH_INFO(a,b) char MSGSTRFIELD(__LINE__) [sizeof (b)];
185 #include "patch-info.h"
188 #define PATCH_INFO(a,b) b,
189 #include "patch-info.h"
192 static const gint16 opidx [] = {
193 #define PATCH_INFO(a,b) [MONO_PATCH_INFO_ ## a] = offsetof (struct msgstr_t, MSGSTRFIELD(__LINE__)),
194 #include "patch-info.h"
198 static G_GNUC_UNUSED const char*
199 get_patch_name (int info)
201 return (const char*)&opstr + opidx [info];
205 #define PATCH_INFO(a,b) b,
206 static const char* const
207 patch_types [MONO_PATCH_INFO_NUM + 1] = {
208 #include "patch-info.h"
212 static G_GNUC_UNUSED const char*
213 get_patch_name (int info)
215 return patch_types [info];
220 /* Wrappers around the image writer functions */
223 emit_section_change (MonoAotCompile *acfg, const char *section_name, int subsection_index)
225 img_writer_emit_section_change (acfg->w, section_name, subsection_index);
229 emit_push_section (MonoAotCompile *acfg, const char *section_name, int subsection)
231 img_writer_emit_push_section (acfg->w, section_name, subsection);
235 emit_pop_section (MonoAotCompile *acfg)
237 img_writer_emit_pop_section (acfg->w);
241 emit_local_symbol (MonoAotCompile *acfg, const char *name, const char *end_label, gboolean func)
243 img_writer_emit_local_symbol (acfg->w, name, end_label, func);
247 emit_label (MonoAotCompile *acfg, const char *name)
249 img_writer_emit_label (acfg->w, name);
253 emit_bytes (MonoAotCompile *acfg, const guint8* buf, int size)
255 img_writer_emit_bytes (acfg->w, buf, size);
259 emit_string (MonoAotCompile *acfg, const char *value)
261 img_writer_emit_string (acfg->w, value);
265 emit_line (MonoAotCompile *acfg)
267 img_writer_emit_line (acfg->w);
271 emit_alignment (MonoAotCompile *acfg, int size)
273 img_writer_emit_alignment (acfg->w, size);
277 emit_pointer_unaligned (MonoAotCompile *acfg, const char *target)
279 img_writer_emit_pointer_unaligned (acfg->w, target);
283 emit_pointer (MonoAotCompile *acfg, const char *target)
285 img_writer_emit_pointer (acfg->w, target);
289 emit_int16 (MonoAotCompile *acfg, int value)
291 img_writer_emit_int16 (acfg->w, value);
295 emit_int32 (MonoAotCompile *acfg, int value)
297 img_writer_emit_int32 (acfg->w, value);
301 emit_symbol_diff (MonoAotCompile *acfg, const char *end, const char* start, int offset)
303 img_writer_emit_symbol_diff (acfg->w, end, start, offset);
307 emit_zero_bytes (MonoAotCompile *acfg, int num)
309 img_writer_emit_zero_bytes (acfg->w, num);
313 emit_byte (MonoAotCompile *acfg, guint8 val)
315 img_writer_emit_byte (acfg->w, val);
318 static G_GNUC_UNUSED void
319 emit_global_inner (MonoAotCompile *acfg, const char *name, gboolean func)
321 img_writer_emit_global (acfg->w, name, func);
325 emit_global (MonoAotCompile *acfg, const char *name, gboolean func)
327 if (acfg->aot_opts.no_dlsym) {
328 g_ptr_array_add (acfg->globals, g_strdup (name));
329 img_writer_emit_local_symbol (acfg->w, name, NULL, func);
331 img_writer_emit_global (acfg->w, name, func);
336 emit_symbol_size (MonoAotCompile *acfg, const char *name, const char *end_label)
338 img_writer_emit_symbol_size (acfg->w, name, end_label);
342 emit_string_symbol (MonoAotCompile *acfg, const char *name, const char *value)
344 img_writer_emit_section_change (acfg->w, ".text", 1);
345 emit_global (acfg, name, FALSE);
346 img_writer_emit_label (acfg->w, name);
347 img_writer_emit_string (acfg->w, value);
350 static G_GNUC_UNUSED void
351 emit_uleb128 (MonoAotCompile *acfg, guint32 value)
354 guint8 b = value & 0x7f;
356 if (value != 0) /* more bytes to come */
362 static G_GNUC_UNUSED void
363 emit_sleb128 (MonoAotCompile *acfg, gint64 value)
366 gboolean negative = (value < 0);
373 /* the following is unnecessary if the
374 * implementation of >>= uses an arithmetic rather
375 * than logical shift for a signed left operand
379 value |= - ((gint64)1 <<(size - 7));
380 /* sign bit of byte is second high order bit (0x40) */
381 if ((value == 0 && !(byte & 0x40)) ||
382 (value == -1 && (byte & 0x40)))
386 emit_byte (acfg, byte);
390 static G_GNUC_UNUSED void
391 encode_uleb128 (guint32 value, guint8 *buf, guint8 **endbuf)
396 guint8 b = value & 0x7f;
398 if (value != 0) /* more bytes to come */
406 static G_GNUC_UNUSED void
407 encode_sleb128 (gint32 value, guint8 *buf, guint8 **endbuf)
410 gboolean negative = (value < 0);
418 /* the following is unnecessary if the
419 * implementation of >>= uses an arithmetic rather
420 * than logical shift for a signed left operand
424 value |= - (1 <<(size - 7));
425 /* sign bit of byte is second high order bit (0x40) */
426 if ((value == 0 && !(byte & 0x40)) ||
427 (value == -1 && (byte & 0x40)))
437 /* ARCHITECTURE SPECIFIC CODE */
439 #if defined(TARGET_X86) || defined(TARGET_AMD64) || defined(TARGET_ARM) || defined(TARGET_POWERPC)
440 #define EMIT_DWARF_INFO 1
443 #if defined(TARGET_ARM)
444 #define AOT_FUNC_ALIGNMENT 4
446 #define AOT_FUNC_ALIGNMENT 16
449 #if defined(TARGET_POWERPC64) && !defined(__mono_ilp32__)
450 #define PPC_LD_OP "ld"
451 #define PPC_LDX_OP "ldx"
453 #define PPC_LD_OP "lwz"
454 #define PPC_LDX_OP "lwzx"
458 * arch_emit_direct_call:
460 * Emit a direct call to the symbol TARGET. CALL_SIZE is set to the size of the
464 arch_emit_direct_call (MonoAotCompile *acfg, const char *target, int *call_size)
466 #if defined(TARGET_X86) || defined(TARGET_AMD64)
467 /* Need to make sure this is exactly 5 bytes long */
468 emit_byte (acfg, '\xe8');
469 emit_symbol_diff (acfg, target, ".", -4);
471 #elif defined(TARGET_ARM)
472 if (acfg->use_bin_writer) {
479 img_writer_emit_reloc (acfg->w, R_ARM_CALL, target, -8);
480 emit_bytes (acfg, buf, 4);
482 img_writer_emit_unset_mode (acfg->w);
483 fprintf (acfg->fp, "bl %s\n", target);
486 #elif defined(TARGET_POWERPC)
487 if (acfg->use_bin_writer) {
488 g_assert_not_reached ();
490 img_writer_emit_unset_mode (acfg->w);
491 fprintf (acfg->fp, "bl %s\n", target);
495 g_assert_not_reached ();
501 * - we use an approach similar to the x86 abi: reserve a register (r30) to hold
503 * - The full-aot trampolines need access to the GOT of mscorlib, so we store
504 * in in the 2. slot of every GOT, and require every method to place the GOT
505 * address in r30, even when it doesn't access the GOT otherwise. This way,
506 * the trampolines can compute the mscorlib GOT address by loading 4(r30).
511 * PPC64 uses function descriptors which greatly complicate all code, since
512 * these are used very inconsistently in the runtime. Some functions like
513 * mono_compile_method () return ftn descriptors, while others like the
514 * trampoline creation functions do not.
515 * We assume that all GOT slots contain function descriptors, and create
516 * descriptors in aot-runtime.c when needed.
517 * The ppc64 abi uses r2 to hold the address of the TOC/GOT, which is loaded
518 * from function descriptors, we could do the same, but it would require
519 * rewriting all the ppc/aot code to handle function descriptors properly.
520 * So instead, we use the same approach as on PPC32.
521 * This is a horrible mess, but fixing it would probably lead to an even bigger
525 #ifdef MONO_ARCH_AOT_SUPPORTED
527 * arch_emit_got_offset:
529 * The memory pointed to by CODE should hold native code for computing the GOT
530 * address. Emit this code while patching it with the offset between code and
531 * the GOT. CODE_SIZE is set to the number of bytes emitted.
534 arch_emit_got_offset (MonoAotCompile *acfg, guint8 *code, int *code_size)
536 #if defined(TARGET_POWERPC64)
537 g_assert (!acfg->use_bin_writer);
538 img_writer_emit_unset_mode (acfg->w);
540 * The ppc32 code doesn't seem to work on ppc64, the assembler complains about
541 * unsupported relocations. So we store the got address into the .Lgot_addr
542 * symbol which is in the text segment, compute its address, and load it.
544 fprintf (acfg->fp, ".L%d:\n", acfg->label_generator);
545 fprintf (acfg->fp, "lis 0, (.Lgot_addr + 4 - .L%d)@h\n", acfg->label_generator);
546 fprintf (acfg->fp, "ori 0, 0, (.Lgot_addr + 4 - .L%d)@l\n", acfg->label_generator);
547 fprintf (acfg->fp, "add 30, 30, 0\n");
548 fprintf (acfg->fp, "%s 30, 0(30)\n", PPC_LD_OP);
549 acfg->label_generator ++;
551 #elif defined(TARGET_POWERPC)
552 g_assert (!acfg->use_bin_writer);
553 img_writer_emit_unset_mode (acfg->w);
554 fprintf (acfg->fp, ".L%d:\n", acfg->label_generator);
555 fprintf (acfg->fp, "lis 0, (%s + 4 - .L%d)@h\n", acfg->got_symbol, acfg->label_generator);
556 fprintf (acfg->fp, "ori 0, 0, (%s + 4 - .L%d)@l\n", acfg->got_symbol, acfg->label_generator);
557 acfg->label_generator ++;
560 guint32 offset = mono_arch_get_patch_offset (code);
561 emit_bytes (acfg, code, offset);
562 emit_symbol_diff (acfg, acfg->got_symbol, ".", offset);
564 *code_size = offset + 4;
569 * arch_emit_got_access:
571 * The memory pointed to by CODE should hold native code for loading a GOT
572 * slot. Emit this code while patching it so it accesses the GOT slot GOT_SLOT.
573 * CODE_SIZE is set to the number of bytes emitted.
576 arch_emit_got_access (MonoAotCompile *acfg, guint8 *code, int got_slot, int *code_size)
578 /* Emit beginning of instruction */
579 emit_bytes (acfg, code, mono_arch_get_patch_offset (code));
581 /* Emit the offset */
583 emit_symbol_diff (acfg, acfg->got_symbol, ".", (unsigned int) ((got_slot * sizeof (gpointer)) - 4));
584 *code_size = mono_arch_get_patch_offset (code) + 4;
585 #elif defined(TARGET_X86)
586 emit_int32 (acfg, (unsigned int) ((got_slot * sizeof (gpointer))));
587 *code_size = mono_arch_get_patch_offset (code) + 4;
588 #elif defined(TARGET_ARM)
589 emit_symbol_diff (acfg, acfg->got_symbol, ".", (unsigned int) ((got_slot * sizeof (gpointer))) - 12);
590 *code_size = mono_arch_get_patch_offset (code) + 4;
591 #elif defined(TARGET_POWERPC)
597 ppc_load32 (code, ppc_r0, got_slot * sizeof (gpointer));
598 g_assert (code - buf == 8);
599 emit_bytes (acfg, buf, code - buf);
600 *code_size = code - buf;
603 g_assert_not_reached ();
610 * arch_emit_plt_entry:
612 * Emit code for the PLT entry with index INDEX.
615 arch_emit_plt_entry (MonoAotCompile *acfg, int index)
617 #if defined(TARGET_X86)
619 /* It is filled up during loading by the AOT loader. */
620 emit_zero_bytes (acfg, 16);
622 /* Need to make sure this is 9 bytes long */
623 emit_byte (acfg, '\xe9');
624 emit_symbol_diff (acfg, acfg->plt_symbol, ".", -4);
625 emit_int32 (acfg, acfg->plt_got_info_offsets [index]);
627 #elif defined(TARGET_AMD64)
629 * We can't emit jumps because they are 32 bits only so they can't be patched.
630 * So we make indirect calls through GOT entries which are patched by the AOT
631 * loader to point to .Lpd entries.
633 /* jmpq *<offset>(%rip) */
634 emit_byte (acfg, '\xff');
635 emit_byte (acfg, '\x25');
636 emit_symbol_diff (acfg, acfg->got_symbol, ".", ((acfg->plt_got_offset_base + index) * sizeof (gpointer)) -4);
637 /* Used by mono_aot_get_plt_info_offset */
638 emit_int32 (acfg, acfg->plt_got_info_offsets [index]);
639 #elif defined(TARGET_ARM)
644 * - optimize OP_AOTCONST implementation
645 * - optimize the PLT entries
646 * - optimize SWITCH AOT implementation
649 if (acfg->use_bin_writer && FALSE) {
650 /* FIXME: mono_arch_patch_plt_entry () needs to decode this */
651 /* We only emit 1 relocation since we implement it ourselves anyway */
652 img_writer_emit_reloc (acfg->w, R_ARM_ALU_PC_G0_NC, acfg->got_symbol, ((acfg->plt_got_offset_base + index) * sizeof (gpointer)) - 8);
653 /* FIXME: A 2 instruction encoding is sufficient in most cases */
654 ARM_ADD_REG_IMM (code, ARMREG_IP, ARMREG_PC, 0, 0);
655 ARM_ADD_REG_IMM (code, ARMREG_IP, ARMREG_IP, 0, 0);
656 ARM_LDR_IMM (code, ARMREG_PC, ARMREG_IP, 0);
657 emit_bytes (acfg, buf, code - buf);
658 /* Used by mono_aot_get_plt_info_offset */
659 emit_int32 (acfg, acfg->plt_got_info_offsets [index]);
661 ARM_LDR_IMM (code, ARMREG_IP, ARMREG_PC, 0);
662 ARM_LDR_REG_REG (code, ARMREG_PC, ARMREG_PC, ARMREG_IP);
663 emit_bytes (acfg, buf, code - buf);
664 emit_symbol_diff (acfg, acfg->got_symbol, ".", ((acfg->plt_got_offset_base + index) * sizeof (gpointer)) - 4);
665 /* Used by mono_aot_get_plt_info_offset */
666 emit_int32 (acfg, acfg->plt_got_info_offsets [index]);
669 * The plt_got_info_offset is computed automatically by
670 * mono_aot_get_plt_info_offset (), so no need to save it here.
672 #elif defined(TARGET_POWERPC)
673 guint32 offset = (acfg->plt_got_offset_base + index) * sizeof (gpointer);
675 /* The GOT address is guaranteed to be in r30 by OP_LOAD_GOTADDR */
676 g_assert (!acfg->use_bin_writer);
677 img_writer_emit_unset_mode (acfg->w);
678 fprintf (acfg->fp, "lis 11, %d@h\n", offset);
679 fprintf (acfg->fp, "ori 11, 11, %d@l\n", offset);
680 fprintf (acfg->fp, "add 11, 11, 30\n");
681 fprintf (acfg->fp, "%s 11, 0(11)\n", PPC_LD_OP);
682 #ifdef PPC_USES_FUNCTION_DESCRIPTOR
683 fprintf (acfg->fp, "%s 2, %d(11)\n", PPC_LD_OP, (int)sizeof (gpointer));
684 fprintf (acfg->fp, "%s 11, 0(11)\n", PPC_LD_OP);
686 fprintf (acfg->fp, "mtctr 11\n");
687 fprintf (acfg->fp, "bctr\n");
688 emit_int32 (acfg, acfg->plt_got_info_offsets [index]);
690 g_assert_not_reached ();
695 * arch_emit_specific_trampoline:
697 * Emit code for a specific trampoline. OFFSET is the offset of the first of
698 * two GOT slots which contain the generic trampoline address and the trampoline
699 * argument. TRAMP_SIZE is set to the size of the emitted trampoline.
702 arch_emit_specific_trampoline (MonoAotCompile *acfg, int offset, int *tramp_size)
705 * The trampolines created here are variations of the specific
706 * trampolines created in mono_arch_create_specific_trampoline (). The
708 * - the generic trampoline address is taken from a got slot.
709 * - the offset of the got slot where the trampoline argument is stored
710 * is embedded in the instruction stream, and the generic trampoline
711 * can load the argument by loading the offset, adding it to the
712 * address of the trampoline to get the address of the got slot, and
713 * loading the argument from there.
714 * - all the trampolines should be of the same length.
716 #if defined(TARGET_AMD64)
717 /* This should be exactly 16 bytes long */
719 /* call *<offset>(%rip) */
720 emit_byte (acfg, '\x41');
721 emit_byte (acfg, '\xff');
722 emit_byte (acfg, '\x15');
723 emit_symbol_diff (acfg, acfg->got_symbol, ".", (offset * sizeof (gpointer)) - 4);
724 /* This should be relative to the start of the trampoline */
725 emit_symbol_diff (acfg, acfg->got_symbol, ".", (offset * sizeof (gpointer)) - 4 + 19);
726 emit_zero_bytes (acfg, 5);
727 #elif defined(TARGET_ARM)
731 /* This should be exactly 20 bytes long */
734 ARM_PUSH (code, 0x5fff);
735 ARM_LDR_IMM (code, ARMREG_R1, ARMREG_PC, 4);
736 /* Load the value from the GOT */
737 ARM_LDR_REG_REG (code, ARMREG_R1, ARMREG_PC, ARMREG_R1);
739 ARM_BLX_REG (code, ARMREG_R1);
741 g_assert (code - buf == 16);
744 emit_bytes (acfg, buf, code - buf);
746 * Only one offset is needed, since the second one would be equal to the
749 emit_symbol_diff (acfg, acfg->got_symbol, ".", (offset * sizeof (gpointer)) - 4 + 4);
750 //emit_symbol_diff (acfg, acfg->got_symbol, ".", ((offset + 1) * sizeof (gpointer)) - 4 + 8);
751 #elif defined(TARGET_POWERPC)
758 g_assert (!acfg->use_bin_writer);
761 * PPC has no ip relative addressing, so we need to compute the address
762 * of the mscorlib got. That is slow and complex, so instead, we store it
763 * in the second got slot of every aot image. The caller already computed
764 * the address of its got and placed it into r30.
766 img_writer_emit_unset_mode (acfg->w);
767 /* Load mscorlib got address */
768 fprintf (acfg->fp, "%s 0, %d(30)\n", PPC_LD_OP, (int)sizeof (gpointer));
769 /* Load generic trampoline address */
770 fprintf (acfg->fp, "lis 11, %d@h\n", (int)(offset * sizeof (gpointer)));
771 fprintf (acfg->fp, "ori 11, 11, %d@l\n", (int)(offset * sizeof (gpointer)));
772 fprintf (acfg->fp, "%s 11, 11, 0\n", PPC_LDX_OP);
773 #ifdef PPC_USES_FUNCTION_DESCRIPTOR
774 fprintf (acfg->fp, "%s 11, 0(11)\n", PPC_LD_OP);
776 fprintf (acfg->fp, "mtctr 11\n");
777 /* Load trampoline argument */
778 /* On ppc, we pass it normally to the generic trampoline */
779 fprintf (acfg->fp, "lis 11, %d@h\n", (int)((offset + 1) * sizeof (gpointer)));
780 fprintf (acfg->fp, "ori 11, 11, %d@l\n", (int)((offset + 1) * sizeof (gpointer)));
781 fprintf (acfg->fp, "%s 0, 11, 0\n", PPC_LDX_OP);
782 /* Branch to generic trampoline */
783 fprintf (acfg->fp, "bctr\n");
785 #ifdef PPC_USES_FUNCTION_DESCRIPTOR
786 *tramp_size = 10 * 4;
791 g_assert_not_reached ();
796 * arch_emit_unbox_trampoline:
798 * Emit code for the unbox trampoline for METHOD used in the full-aot case.
799 * CALL_TARGET is the symbol pointing to the native code of METHOD.
802 arch_emit_unbox_trampoline (MonoAotCompile *acfg, MonoMethod *method, MonoGenericSharingContext *gsctx, const char *call_target)
804 #if defined(TARGET_AMD64)
809 this_reg = mono_arch_get_this_arg_reg (mono_method_signature (method), gsctx, NULL);
811 amd64_alu_reg_imm (code, X86_ADD, this_reg, sizeof (MonoObject));
813 emit_bytes (acfg, buf, code - buf);
815 emit_byte (acfg, '\xe9');
816 emit_symbol_diff (acfg, call_target, ".", -4);
817 #elif defined(TARGET_ARM)
824 if (MONO_TYPE_ISSTRUCT (mono_method_signature (method)->ret))
827 ARM_ADD_REG_IMM8 (code, this_pos, this_pos, sizeof (MonoObject));
829 emit_bytes (acfg, buf, code - buf);
831 if (acfg->use_bin_writer) {
838 img_writer_emit_reloc (acfg->w, R_ARM_JUMP24, call_target, -8);
839 emit_bytes (acfg, buf, 4);
841 fprintf (acfg->fp, "\n\tb %s\n", call_target);
843 #elif defined(TARGET_POWERPC)
846 if (MONO_TYPE_ISSTRUCT (mono_method_signature (method)->ret))
849 g_assert (!acfg->use_bin_writer);
851 fprintf (acfg->fp, "\n\taddi %d, %d, %d\n", this_pos, this_pos, (int)sizeof (MonoObject));
852 fprintf (acfg->fp, "\n\tb %s\n", call_target);
854 g_assert_not_reached ();
859 * arch_emit_static_rgctx_trampoline:
861 * Emit code for a static rgctx trampoline. OFFSET is the offset of the first of
862 * two GOT slots which contain the rgctx argument, and the method to jump to.
863 * TRAMP_SIZE is set to the size of the emitted trampoline.
864 * These kinds of trampolines cannot be enumerated statically, since there could
865 * be one trampoline per method instantiation, so we emit the same code for all
866 * trampolines, and parameterize them using two GOT slots.
869 arch_emit_static_rgctx_trampoline (MonoAotCompile *acfg, int offset, int *tramp_size)
871 #if defined(TARGET_AMD64)
872 /* This should be exactly 13 bytes long */
875 /* mov <OFFSET>(%rip), %r10 */
876 emit_byte (acfg, '\x4d');
877 emit_byte (acfg, '\x8b');
878 emit_byte (acfg, '\x15');
879 emit_symbol_diff (acfg, acfg->got_symbol, ".", (offset * sizeof (gpointer)) - 4);
881 /* jmp *<offset>(%rip) */
882 emit_byte (acfg, '\xff');
883 emit_byte (acfg, '\x25');
884 emit_symbol_diff (acfg, acfg->got_symbol, ".", ((offset + 1) * sizeof (gpointer)) - 4);
885 #elif defined(TARGET_ARM)
889 /* This should be exactly 24 bytes long */
892 /* Load rgctx value */
893 ARM_LDR_IMM (code, ARMREG_IP, ARMREG_PC, 8);
894 ARM_LDR_REG_REG (code, MONO_ARCH_RGCTX_REG, ARMREG_PC, ARMREG_IP);
895 /* Load branch addr + branch */
896 ARM_LDR_IMM (code, ARMREG_IP, ARMREG_PC, 4);
897 ARM_LDR_REG_REG (code, ARMREG_PC, ARMREG_PC, ARMREG_IP);
899 g_assert (code - buf == 16);
902 emit_bytes (acfg, buf, code - buf);
903 emit_symbol_diff (acfg, acfg->got_symbol, ".", (offset * sizeof (gpointer)) - 4 + 8);
904 emit_symbol_diff (acfg, acfg->got_symbol, ".", ((offset + 1) * sizeof (gpointer)) - 4 + 4);
905 #elif defined(TARGET_POWERPC)
912 g_assert (!acfg->use_bin_writer);
915 * PPC has no ip relative addressing, so we need to compute the address
916 * of the mscorlib got. That is slow and complex, so instead, we store it
917 * in the second got slot of every aot image. The caller already computed
918 * the address of its got and placed it into r30.
920 img_writer_emit_unset_mode (acfg->w);
921 /* Load mscorlib got address */
922 fprintf (acfg->fp, "%s 0, %d(30)\n", PPC_LD_OP, (int)sizeof (gpointer));
924 fprintf (acfg->fp, "lis 11, %d@h\n", (int)(offset * sizeof (gpointer)));
925 fprintf (acfg->fp, "ori 11, 11, %d@l\n", (int)(offset * sizeof (gpointer)));
926 fprintf (acfg->fp, "%s %d, 11, 0\n", PPC_LDX_OP, MONO_ARCH_RGCTX_REG);
927 /* Load target address */
928 fprintf (acfg->fp, "lis 11, %d@h\n", (int)((offset + 1) * sizeof (gpointer)));
929 fprintf (acfg->fp, "ori 11, 11, %d@l\n", (int)((offset + 1) * sizeof (gpointer)));
930 fprintf (acfg->fp, "%s 11, 11, 0\n", PPC_LDX_OP);
931 #ifdef PPC_USES_FUNCTION_DESCRIPTOR
932 fprintf (acfg->fp, "%s 2, %d(11)\n", PPC_LD_OP, (int)sizeof (gpointer));
933 fprintf (acfg->fp, "%s 11, 0(11)\n", PPC_LD_OP);
935 fprintf (acfg->fp, "mtctr 11\n");
936 /* Branch to the target address */
937 fprintf (acfg->fp, "bctr\n");
939 #ifdef PPC_USES_FUNCTION_DESCRIPTOR
940 *tramp_size = 11 * 4;
946 g_assert_not_reached ();
951 * arch_emit_imt_thunk:
953 * Emit an IMT thunk usable in full-aot mode. The thunk uses 1 got slot which
954 * points to an array of pointer pairs. The pairs of the form [key, ptr], where
955 * key is the IMT key, and ptr holds the address of a memory location holding
956 * the address to branch to if the IMT arg matches the key. The array is
957 * terminated by a pair whose key is NULL, and whose ptr is the address of the
959 * TRAMP_SIZE is set to the size of the emitted trampoline.
962 arch_emit_imt_thunk (MonoAotCompile *acfg, int offset, int *tramp_size)
964 #if defined(TARGET_AMD64)
968 code = buf = g_malloc (256);
970 /* FIXME: Optimize this, i.e. use binary search etc. */
971 /* Maybe move the body into a separate function (slower, but much smaller) */
973 /* R10 is a free register */
976 amd64_alu_membase_imm (code, X86_CMP, AMD64_R10, 0, 0);
978 amd64_branch8 (code, X86_CC_Z, FALSE, 0);
981 amd64_alu_membase_reg (code, X86_CMP, AMD64_R10, 0, MONO_ARCH_IMT_REG);
983 amd64_branch8 (code, X86_CC_Z, FALSE, 0);
986 amd64_alu_reg_imm (code, X86_ADD, AMD64_R10, 2 * sizeof (gpointer));
987 amd64_jump_code (code, labels [0]);
990 mono_amd64_patch (labels [2], code);
991 amd64_mov_reg_membase (code, AMD64_R10, AMD64_R10, sizeof (gpointer), 8);
992 amd64_jump_membase (code, AMD64_R10, 0);
996 mono_amd64_patch (labels [1], code);
997 x86_breakpoint (code);
999 /* mov <OFFSET>(%rip), %r10 */
1000 emit_byte (acfg, '\x4d');
1001 emit_byte (acfg, '\x8b');
1002 emit_byte (acfg, '\x15');
1003 emit_symbol_diff (acfg, acfg->got_symbol, ".", (offset * sizeof (gpointer)) - 4);
1005 emit_bytes (acfg, buf, code - buf);
1007 *tramp_size = code - buf + 7;
1008 #elif defined(TARGET_ARM)
1010 guint8 *code, *code2, *labels [16];
1014 /* The IMT method is in v5 */
1016 /* Need at least two free registers, plus a slot for storing the pc */
1017 ARM_PUSH (code, (1 << ARMREG_R0)|(1 << ARMREG_R1)|(1 << ARMREG_R2));
1019 /* Load the parameter from the GOT */
1020 ARM_LDR_IMM (code, ARMREG_R0, ARMREG_PC, 0);
1021 ARM_LDR_REG_REG (code, ARMREG_R0, ARMREG_PC, ARMREG_R0);
1024 ARM_LDR_IMM (code, ARMREG_R1, ARMREG_R0, 0);
1025 ARM_CMP_REG_REG (code, ARMREG_R1, ARMREG_V5);
1027 ARM_B_COND (code, ARMCOND_EQ, 0);
1029 /* End-of-loop check */
1030 ARM_CMP_REG_IMM (code, ARMREG_R1, 0, 0);
1032 ARM_B_COND (code, ARMCOND_EQ, 0);
1035 ARM_ADD_REG_IMM8 (code, ARMREG_R0, ARMREG_R0, sizeof (gpointer) * 2);
1038 arm_patch (labels [4], labels [1]);
1041 arm_patch (labels [2], code);
1042 ARM_LDR_IMM (code, ARMREG_R0, ARMREG_R0, 4);
1043 ARM_LDR_IMM (code, ARMREG_R0, ARMREG_R0, 0);
1044 /* Save it to the third stack slot */
1045 ARM_STR_IMM (code, ARMREG_R0, ARMREG_SP, 8);
1046 /* Restore the registers and branch */
1047 ARM_POP (code, (1 << ARMREG_R0)|(1 << ARMREG_R1)|(1 << ARMREG_PC));
1050 arm_patch (labels [3], code);
1055 ARM_LDR_IMM (code2, ARMREG_R0, ARMREG_PC, (code - (labels [0] + 8)));
1057 emit_bytes (acfg, buf, code - buf);
1058 emit_symbol_diff (acfg, acfg->got_symbol, ".", (offset * sizeof (gpointer)) + (code - (labels [0] + 8)) - 4);
1060 *tramp_size = code - buf + 4;
1061 #elif defined(TARGET_POWERPC)
1063 guint8 *code, *labels [16];
1067 /* Load the mscorlib got address */
1068 ppc_ldptr (code, ppc_r11, sizeof (gpointer), ppc_r30);
1069 /* Load the parameter from the GOT */
1070 ppc_load (code, ppc_r0, offset * sizeof (gpointer));
1071 ppc_ldptr_indexed (code, ppc_r11, ppc_r11, ppc_r0);
1073 /* Load and check key */
1075 ppc_ldptr (code, ppc_r0, 0, ppc_r11);
1076 ppc_cmp (code, 0, sizeof (gpointer) == 8 ? 1 : 0, ppc_r0, MONO_ARCH_IMT_REG);
1078 ppc_bc (code, PPC_BR_TRUE, PPC_BR_EQ, 0);
1080 /* End-of-loop check */
1081 ppc_cmpi (code, 0, sizeof (gpointer) == 8 ? 1 : 0, ppc_r0, 0);
1083 ppc_bc (code, PPC_BR_TRUE, PPC_BR_EQ, 0);
1086 ppc_addi (code, ppc_r11, ppc_r11, 2 * sizeof (gpointer));
1089 mono_ppc_patch (labels [4], labels [1]);
1092 mono_ppc_patch (labels [2], code);
1093 ppc_ldptr (code, ppc_r11, sizeof (gpointer), ppc_r11);
1094 /* r11 now contains the value of the vtable slot */
1095 /* this is not a function descriptor on ppc64 */
1096 ppc_ldptr (code, ppc_r11, 0, ppc_r11);
1097 ppc_mtctr (code, ppc_r11);
1098 ppc_bcctr (code, PPC_BR_ALWAYS, 0);
1101 mono_ppc_patch (labels [3], code);
1105 *tramp_size = code - buf;
1107 emit_bytes (acfg, buf, code - buf);
1109 g_assert_not_reached ();
1114 arch_emit_autoreg (MonoAotCompile *acfg, char *symbol)
1116 #if defined(TARGET_POWERPC) && defined(__mono_ilp32__)
1117 /* Based on code generated by gcc */
1118 img_writer_emit_unset_mode (acfg->w);
1121 #if defined(_MSC_VER) || defined(MONO_CROSS_COMPILE)
1122 ".section .ctors,\"aw\",@progbits\n"
1126 ".section .opd,\"aw\"\n"
1129 ".long .%s,.TOC.@tocbase32\n"
1132 ".type .%s,@function\n"
1134 ".%s:\n", symbol, symbol, symbol, symbol, symbol, symbol, symbol, symbol);
1136 ".section .ctors,\"aw\",@progbits\n"
1140 ".section .opd,\"aw\"\n"
1143 ".long .%1$s,.TOC.@tocbase32\n"
1144 ".size %1$s,.-%1$s\n"
1146 ".type .%1$s,@function\n"
1148 ".%1$s:\n", symbol);
1159 "lis 3, .Lglobals@h\n"
1160 "ori 3, 3, .Lglobals@l\n"
1161 "bl .mono_aot_register_module\n"
1169 #if defined(_MSC_VER) || defined(MONO_CROSS_COMPILE)
1171 ".size .%s,.-.%s\n", symbol, symbol);
1174 ".size .%1$s,.-.%1$s\n", symbol);
1181 * arch_get_cie_program:
1183 * Get the unwind bytecode for the DWARF CIE.
1186 arch_get_cie_program (void)
1191 mono_add_unwind_op_def_cfa (l, (guint8*)NULL, (guint8*)NULL, AMD64_RSP, 8);
1192 mono_add_unwind_op_offset (l, (guint8*)NULL, (guint8*)NULL, AMD64_RIP, -8);
1195 #elif defined(TARGET_POWERPC)
1198 mono_add_unwind_op_def_cfa (l, (guint8*)NULL, (guint8*)NULL, ppc_r1, 0);
1206 /* END OF ARCH SPECIFIC CODE */
1209 mono_get_field_token (MonoClassField *field)
1211 MonoClass *klass = field->parent;
1214 for (i = 0; i < klass->field.count; ++i) {
1215 if (field == &klass->fields [i])
1216 return MONO_TOKEN_FIELD_DEF | (klass->field.first + 1 + i);
1219 g_assert_not_reached ();
1224 encode_value (gint32 value, guint8 *buf, guint8 **endbuf)
1228 //printf ("ENCODE: %d 0x%x.\n", value, value);
1231 * Same encoding as the one used in the metadata, extended to handle values
1232 * greater than 0x1fffffff.
1234 if ((value >= 0) && (value <= 127))
1236 else if ((value >= 0) && (value <= 16383)) {
1237 p [0] = 0x80 | (value >> 8);
1238 p [1] = value & 0xff;
1240 } else if ((value >= 0) && (value <= 0x1fffffff)) {
1241 p [0] = (value >> 24) | 0xc0;
1242 p [1] = (value >> 16) & 0xff;
1243 p [2] = (value >> 8) & 0xff;
1244 p [3] = value & 0xff;
1249 p [1] = (value >> 24) & 0xff;
1250 p [2] = (value >> 16) & 0xff;
1251 p [3] = (value >> 8) & 0xff;
1252 p [4] = value & 0xff;
1260 stream_init (MonoDynamicStream *sh)
1263 sh->alloc_size = 4096;
1264 sh->data = g_malloc (4096);
1266 /* So offsets are > 0 */
1271 make_room_in_stream (MonoDynamicStream *stream, int size)
1273 if (size <= stream->alloc_size)
1276 while (stream->alloc_size <= size) {
1277 if (stream->alloc_size < 4096)
1278 stream->alloc_size = 4096;
1280 stream->alloc_size *= 2;
1283 stream->data = g_realloc (stream->data, stream->alloc_size);
1287 add_stream_data (MonoDynamicStream *stream, const char *data, guint32 len)
1291 make_room_in_stream (stream, stream->index + len);
1292 memcpy (stream->data + stream->index, data, len);
1293 idx = stream->index;
1294 stream->index += len;
1301 * Add data to the binary blob inside the aot image. Returns the offset inside the
1302 * blob where the data was stored.
1305 add_to_blob (MonoAotCompile *acfg, guint8 *data, guint32 data_len)
1307 if (acfg->blob.alloc_size == 0)
1308 stream_init (&acfg->blob);
1310 return add_stream_data (&acfg->blob, (char*)data, data_len);
1314 * emit_offset_table:
1316 * Emit a table of increasing offsets in a compact form using differential encoding.
1317 * There is an index entry for each GROUP_SIZE number of entries. The greater the
1318 * group size, the more compact the table becomes, but the slower it becomes to compute
1319 * a given entry. Returns the size of the table.
1322 emit_offset_table (MonoAotCompile *acfg, int noffsets, int group_size, gint32 *offsets)
1324 gint32 current_offset;
1325 int i, buf_size, ngroups, index_entry_size;
1327 guint32 *index_offsets;
1329 ngroups = (noffsets + (group_size - 1)) / group_size;
1331 index_offsets = g_new0 (guint32, ngroups);
1333 buf_size = noffsets * 4;
1334 p = buf = g_malloc0 (buf_size);
1337 for (i = 0; i < noffsets; ++i) {
1338 //printf ("D: %d -> %d\n", i, offsets [i]);
1339 if ((i % group_size) == 0) {
1340 index_offsets [i / group_size] = p - buf;
1341 /* Emit the full value for these entries */
1342 encode_value (offsets [i], p, &p);
1344 /* The offsets are allowed to be non-increasing */
1345 //g_assert (offsets [i] >= current_offset);
1346 encode_value (offsets [i] - current_offset, p, &p);
1348 current_offset = offsets [i];
1351 if (ngroups && index_offsets [ngroups - 1] < 65000)
1352 index_entry_size = 2;
1354 index_entry_size = 4;
1356 /* Emit the header */
1357 emit_int32 (acfg, noffsets);
1358 emit_int32 (acfg, group_size);
1359 emit_int32 (acfg, ngroups);
1360 emit_int32 (acfg, index_entry_size);
1362 /* Emit the index */
1363 for (i = 0; i < ngroups; ++i) {
1364 if (index_entry_size == 2)
1365 emit_int16 (acfg, index_offsets [i]);
1367 emit_int32 (acfg, index_offsets [i]);
1371 emit_bytes (acfg, buf, p - buf);
1373 return (int)(p - buf) + (ngroups * 4);
1377 get_image_index (MonoAotCompile *cfg, MonoImage *image)
1381 index = GPOINTER_TO_UINT (g_hash_table_lookup (cfg->image_hash, image));
1385 index = g_hash_table_size (cfg->image_hash);
1386 g_hash_table_insert (cfg->image_hash, image, GUINT_TO_POINTER (index + 1));
1387 g_ptr_array_add (cfg->image_table, image);
1393 find_typespec_for_class (MonoAotCompile *acfg, MonoClass *klass)
1396 MonoClass *k = NULL;
1398 /* FIXME: Search referenced images as well */
1399 for (i = 0; i < acfg->image->tables [MONO_TABLE_TYPESPEC].rows; ++i) {
1400 k = mono_class_get_full (acfg->image, MONO_TOKEN_TYPE_SPEC | (i + 1), NULL);
1405 if (i < acfg->image->tables [MONO_TABLE_TYPESPEC].rows)
1406 return MONO_TOKEN_TYPE_SPEC | (i + 1);
1412 encode_method_ref (MonoAotCompile *acfg, MonoMethod *method, guint8 *buf, guint8 **endbuf);
1417 * Encode a reference to KLASS. We use our home-grown encoding instead of the
1418 * standard metadata encoding.
1421 encode_klass_ref (MonoAotCompile *acfg, MonoClass *klass, guint8 *buf, guint8 **endbuf)
1425 if (klass->generic_class) {
1427 g_assert (klass->type_token);
1429 /* Find a typespec for a class if possible */
1430 token = find_typespec_for_class (acfg, klass);
1432 encode_value (token, p, &p);
1433 encode_value (get_image_index (acfg, acfg->image), p, &p);
1435 MonoClass *gclass = klass->generic_class->container_class;
1436 MonoGenericInst *inst = klass->generic_class->context.class_inst;
1439 /* Encode it ourselves */
1441 encode_value (MONO_TOKEN_TYPE_SPEC, p, &p);
1442 encode_value (MONO_TYPE_GENERICINST, p, &p);
1443 encode_klass_ref (acfg, gclass, p, &p);
1444 encode_value (inst->type_argc, p, &p);
1445 for (i = 0; i < inst->type_argc; ++i)
1446 encode_klass_ref (acfg, mono_class_from_mono_type (inst->type_argv [i]), p, &p);
1448 } else if (klass->type_token) {
1449 g_assert (mono_metadata_token_code (klass->type_token) == MONO_TOKEN_TYPE_DEF);
1450 encode_value (klass->type_token - MONO_TOKEN_TYPE_DEF, p, &p);
1451 encode_value (get_image_index (acfg, klass->image), p, &p);
1452 } else if ((klass->byval_arg.type == MONO_TYPE_VAR) || (klass->byval_arg.type == MONO_TYPE_MVAR)) {
1453 MonoGenericContainer *container = mono_type_get_generic_param_owner (&klass->byval_arg);
1454 g_assert (container);
1457 encode_value (MONO_TOKEN_TYPE_SPEC, p, &p);
1458 encode_value (klass->byval_arg.type, p, &p);
1460 encode_value (mono_type_get_generic_param_num (&klass->byval_arg), p, &p);
1462 encode_value (container->is_method, p, &p);
1463 if (container->is_method)
1464 encode_method_ref (acfg, container->owner.method, p, &p);
1466 encode_klass_ref (acfg, container->owner.klass, p, &p);
1469 g_assert (klass->rank > 0);
1470 encode_value (MONO_TOKEN_TYPE_DEF, p, &p);
1471 encode_value (get_image_index (acfg, klass->image), p, &p);
1472 encode_value (klass->rank, p, &p);
1473 encode_klass_ref (acfg, klass->element_class, p, &p);
1479 encode_field_info (MonoAotCompile *cfg, MonoClassField *field, guint8 *buf, guint8 **endbuf)
1481 guint32 token = mono_get_field_token (field);
1484 encode_klass_ref (cfg, field->parent, p, &p);
1485 g_assert (mono_metadata_token_code (token) == MONO_TOKEN_FIELD_DEF);
1486 encode_value (token - MONO_TOKEN_FIELD_DEF, p, &p);
1491 encode_generic_context (MonoAotCompile *acfg, MonoGenericContext *context, guint8 *buf, guint8 **endbuf)
1495 MonoGenericInst *inst;
1497 /* Encode the context */
1498 inst = context->class_inst;
1499 encode_value (inst ? 1 : 0, p, &p);
1501 encode_value (inst->type_argc, p, &p);
1502 for (i = 0; i < inst->type_argc; ++i)
1503 encode_klass_ref (acfg, mono_class_from_mono_type (inst->type_argv [i]), p, &p);
1505 inst = context->method_inst;
1506 encode_value (inst ? 1 : 0, p, &p);
1508 encode_value (inst->type_argc, p, &p);
1509 for (i = 0; i < inst->type_argc; ++i)
1510 encode_klass_ref (acfg, mono_class_from_mono_type (inst->type_argv [i]), p, &p);
1516 #define MAX_IMAGE_INDEX 250
1519 encode_method_ref (MonoAotCompile *acfg, MonoMethod *method, guint8 *buf, guint8 **endbuf)
1521 guint32 image_index = get_image_index (acfg, method->klass->image);
1522 guint32 token = method->token;
1523 MonoJumpInfoToken *ji;
1528 * The encoding for most methods is as follows:
1529 * - image index encoded as a leb128
1530 * - token index encoded as a leb128
1531 * Values of image index >= MONO_AOT_METHODREF_MIN are used to mark additional
1532 * types of method encodings.
1535 g_assert (image_index < MONO_AOT_METHODREF_MIN);
1537 /* Mark methods which can't use aot trampolines because they need the further
1538 * processing in mono_magic_trampoline () which requires a MonoMethod*.
1540 if ((method->is_generic && (method->flags & METHOD_ATTRIBUTE_VIRTUAL)) ||
1541 (method->iflags & METHOD_IMPL_ATTRIBUTE_SYNCHRONIZED))
1542 encode_value ((MONO_AOT_METHODREF_NO_AOT_TRAMPOLINE << 24), p, &p);
1545 * Some wrapper methods are shared using their signature, encode their
1546 * stringified signature instead.
1547 * FIXME: Optimize disk usage
1550 if (method->wrapper_type) {
1551 if (method->wrapper_type == MONO_WRAPPER_RUNTIME_INVOKE) {
1552 char *tmpsig = mono_signature_get_desc (mono_method_signature (method), TRUE);
1553 if (strcmp (method->name, "runtime_invoke_dynamic")) {
1554 name = mono_aot_wrapper_name (method);
1555 } else if (mono_marshal_method_from_wrapper (method) != method) {
1556 /* Direct wrapper, encode it normally */
1558 name = g_strdup_printf ("(wrapper runtime-invoke):%s (%s)", method->name, tmpsig);
1561 } else if (method->wrapper_type == MONO_WRAPPER_DELEGATE_INVOKE) {
1562 char *tmpsig = mono_signature_get_desc (mono_method_signature (method), TRUE);
1563 name = g_strdup_printf ("(wrapper delegate-invoke):%s (%s)", method->name, tmpsig);
1565 } else if (method->wrapper_type == MONO_WRAPPER_DELEGATE_BEGIN_INVOKE) {
1566 char *tmpsig = mono_signature_get_desc (mono_method_signature (method), TRUE);
1567 name = g_strdup_printf ("(wrapper delegate-begin-invoke):%s (%s)", method->name, tmpsig);
1569 } else if (method->wrapper_type == MONO_WRAPPER_DELEGATE_END_INVOKE) {
1570 char *tmpsig = mono_signature_get_desc (mono_method_signature (method), TRUE);
1571 name = g_strdup_printf ("(wrapper delegate-end-invoke):%s (%s)", method->name, tmpsig);
1577 encode_value ((MONO_AOT_METHODREF_WRAPPER_NAME << 24), p, &p);
1578 strcpy ((char*)p, name);
1579 p += strlen (name) + 1;
1581 } else if (method->wrapper_type) {
1582 encode_value ((MONO_AOT_METHODREF_WRAPPER << 24), p, &p);
1584 encode_value (method->wrapper_type, p, &p);
1586 switch (method->wrapper_type) {
1587 case MONO_WRAPPER_REMOTING_INVOKE:
1588 case MONO_WRAPPER_REMOTING_INVOKE_WITH_CHECK:
1589 case MONO_WRAPPER_XDOMAIN_INVOKE: {
1592 m = mono_marshal_method_from_wrapper (method);
1594 encode_method_ref (acfg, m, p, &p);
1597 case MONO_WRAPPER_PROXY_ISINST:
1598 case MONO_WRAPPER_LDFLD:
1599 case MONO_WRAPPER_LDFLDA:
1600 case MONO_WRAPPER_STFLD:
1601 case MONO_WRAPPER_ISINST: {
1602 MonoClass *proxy_class = (MonoClass*)mono_marshal_method_from_wrapper (method);
1603 encode_klass_ref (acfg, proxy_class, p, &p);
1606 case MONO_WRAPPER_LDFLD_REMOTE:
1607 case MONO_WRAPPER_STFLD_REMOTE:
1609 case MONO_WRAPPER_ALLOC: {
1610 int alloc_type = mono_gc_get_managed_allocator_type (method);
1611 g_assert (alloc_type != -1);
1612 encode_value (alloc_type, p, &p);
1615 case MONO_WRAPPER_STELEMREF:
1617 case MONO_WRAPPER_UNKNOWN:
1618 if (strcmp (method->name, "FastMonitorEnter") == 0)
1619 encode_value (MONO_AOT_WRAPPER_MONO_ENTER, p, &p);
1620 else if (strcmp (method->name, "FastMonitorExit") == 0)
1621 encode_value (MONO_AOT_WRAPPER_MONO_EXIT, p, &p);
1623 g_assert_not_reached ();
1625 case MONO_WRAPPER_SYNCHRONIZED:
1626 case MONO_WRAPPER_MANAGED_TO_NATIVE:
1627 case MONO_WRAPPER_RUNTIME_INVOKE: {
1630 m = mono_marshal_method_from_wrapper (method);
1632 g_assert (m != method);
1633 encode_method_ref (acfg, m, p, &p);
1636 case MONO_WRAPPER_MANAGED_TO_MANAGED:
1637 if (!strcmp (method->name, "ElementAddr")) {
1638 ElementAddrWrapperInfo *info = mono_marshal_wrapper_info_from_wrapper (method);
1641 encode_value (MONO_AOT_WRAPPER_ELEMENT_ADDR, p, &p);
1642 encode_value (info->rank, p, &p);
1643 encode_value (info->elem_size, p, &p);
1645 g_assert_not_reached ();
1649 g_assert_not_reached ();
1651 } else if (mono_method_signature (method)->is_inflated) {
1653 * This is a generic method, find the original token which referenced it and
1655 * Obtain the token from information recorded by the JIT.
1657 ji = g_hash_table_lookup (acfg->token_info_hash, method);
1659 image_index = get_image_index (acfg, ji->image);
1660 g_assert (image_index < MAX_IMAGE_INDEX);
1663 encode_value ((MONO_AOT_METHODREF_METHODSPEC << 24), p, &p);
1664 encode_value (image_index, p, &p);
1665 encode_value (token, p, &p);
1667 MonoMethod *declaring;
1668 MonoGenericContext *context = mono_method_get_context (method);
1670 g_assert (method->is_inflated);
1671 declaring = ((MonoMethodInflated*)method)->declaring;
1674 * This might be a non-generic method of a generic instance, which
1675 * doesn't have a token since the reference is generated by the JIT
1676 * like Nullable:Box/Unbox, or by generic sharing.
1679 encode_value ((MONO_AOT_METHODREF_GINST << 24), p, &p);
1680 /* Encode the klass */
1681 encode_klass_ref (acfg, method->klass, p, &p);
1682 /* Encode the method */
1683 image_index = get_image_index (acfg, method->klass->image);
1684 g_assert (image_index < MAX_IMAGE_INDEX);
1685 g_assert (declaring->token);
1686 token = declaring->token;
1687 g_assert (mono_metadata_token_table (token) == MONO_TABLE_METHOD);
1688 encode_value (image_index, p, &p);
1689 encode_value (token, p, &p);
1690 encode_generic_context (acfg, context, p, &p);
1692 } else if (token == 0) {
1693 /* This might be a method of a constructed type like int[,].Set */
1694 /* Obtain the token from information recorded by the JIT */
1695 ji = g_hash_table_lookup (acfg->token_info_hash, method);
1697 image_index = get_image_index (acfg, ji->image);
1698 g_assert (image_index < MAX_IMAGE_INDEX);
1701 encode_value ((MONO_AOT_METHODREF_METHODSPEC << 24), p, &p);
1702 encode_value (image_index, p, &p);
1703 encode_value (token, p, &p);
1706 g_assert (method->klass->rank);
1708 /* Encode directly */
1709 encode_value ((MONO_AOT_METHODREF_ARRAY << 24), p, &p);
1710 encode_klass_ref (acfg, method->klass, p, &p);
1711 if (!strcmp (method->name, ".ctor") && mono_method_signature (method)->param_count == method->klass->rank)
1712 encode_value (0, p, &p);
1713 else if (!strcmp (method->name, ".ctor") && mono_method_signature (method)->param_count == method->klass->rank * 2)
1714 encode_value (1, p, &p);
1715 else if (!strcmp (method->name, "Get"))
1716 encode_value (2, p, &p);
1717 else if (!strcmp (method->name, "Address"))
1718 encode_value (3, p, &p);
1719 else if (!strcmp (method->name, "Set"))
1720 encode_value (4, p, &p);
1722 g_assert_not_reached ();
1725 g_assert (mono_metadata_token_table (token) == MONO_TABLE_METHOD);
1726 encode_value ((image_index << 24) | mono_metadata_token_index (token), p, &p);
1732 compare_patches (gconstpointer a, gconstpointer b)
1736 i = (*(MonoJumpInfo**)a)->ip.i;
1737 j = (*(MonoJumpInfo**)b)->ip.i;
1751 * Return whenever PATCH_INFO refers to a direct call, and thus requires a
1754 static inline gboolean
1755 is_plt_patch (MonoJumpInfo *patch_info)
1757 switch (patch_info->type) {
1758 case MONO_PATCH_INFO_METHOD:
1759 case MONO_PATCH_INFO_INTERNAL_METHOD:
1760 case MONO_PATCH_INFO_JIT_ICALL_ADDR:
1761 case MONO_PATCH_INFO_ICALL_ADDR:
1762 case MONO_PATCH_INFO_CLASS_INIT:
1763 case MONO_PATCH_INFO_RGCTX_FETCH:
1764 case MONO_PATCH_INFO_GENERIC_CLASS_INIT:
1765 case MONO_PATCH_INFO_MONITOR_ENTER:
1766 case MONO_PATCH_INFO_MONITOR_EXIT:
1767 case MONO_PATCH_INFO_LLVM_IMT_TRAMPOLINE:
1775 get_plt_offset (MonoAotCompile *acfg, MonoJumpInfo *patch_info)
1779 if (is_plt_patch (patch_info)) {
1780 int idx = GPOINTER_TO_UINT (g_hash_table_lookup (acfg->patch_to_plt_offset, patch_info));
1782 // FIXME: This breaks the calculation of final_got_size
1783 if (!acfg->llvm && patch_info->type == MONO_PATCH_INFO_METHOD && (patch_info->data.method->iflags & METHOD_IMPL_ATTRIBUTE_SYNCHRONIZED)) {
1785 * Allocate a separate PLT slot for each such patch, since some plt
1786 * entries will refer to the method itself, and some will refer to the
1795 MonoJumpInfo *new_ji = mono_patch_info_dup_mp (acfg->mempool, patch_info);
1797 g_assert (!acfg->final_got_size);
1799 res = acfg->plt_offset;
1800 g_hash_table_insert (acfg->plt_offset_to_patch, GUINT_TO_POINTER (res), new_ji);
1801 g_hash_table_insert (acfg->patch_to_plt_offset, new_ji, GUINT_TO_POINTER (res));
1802 acfg->plt_offset ++;
1812 * Returns the offset of the GOT slot where the runtime object resulting from resolving
1813 * JI could be found if it exists, otherwise allocates a new one.
1816 get_got_offset (MonoAotCompile *acfg, MonoJumpInfo *ji)
1820 got_offset = GPOINTER_TO_UINT (g_hash_table_lookup (acfg->patch_to_got_offset_by_type [ji->type], ji));
1822 return got_offset - 1;
1824 g_assert (!acfg->final_got_size);
1826 got_offset = acfg->got_offset;
1827 acfg->got_offset ++;
1829 acfg->stats.got_slots ++;
1830 acfg->stats.got_slot_types [ji->type] ++;
1832 g_hash_table_insert (acfg->patch_to_got_offset, ji, GUINT_TO_POINTER (got_offset + 1));
1833 g_hash_table_insert (acfg->patch_to_got_offset_by_type [ji->type], ji, GUINT_TO_POINTER (got_offset + 1));
1834 g_ptr_array_add (acfg->got_patches, ji);
1839 /* Add a method to the list of methods which need to be emitted */
1841 add_method_with_index (MonoAotCompile *acfg, MonoMethod *method, int index, gboolean extra)
1844 if (!g_hash_table_lookup (acfg->method_indexes, method)) {
1845 g_ptr_array_add (acfg->methods, method);
1846 g_hash_table_insert (acfg->method_indexes, method, GUINT_TO_POINTER (index + 1));
1847 acfg->nmethods = acfg->methods->len + 1;
1850 if (method->wrapper_type || extra)
1851 g_ptr_array_add (acfg->extra_methods, method);
1855 get_method_index (MonoAotCompile *acfg, MonoMethod *method)
1857 int index = GPOINTER_TO_UINT (g_hash_table_lookup (acfg->method_indexes, method));
1865 add_method_full (MonoAotCompile *acfg, MonoMethod *method, gboolean extra, int depth)
1869 index = GPOINTER_TO_UINT (g_hash_table_lookup (acfg->method_indexes, method));
1873 index = acfg->method_index;
1874 add_method_with_index (acfg, method, index, extra);
1876 /* FIXME: Fix quadratic behavior */
1877 acfg->method_order = g_list_append (acfg->method_order, GUINT_TO_POINTER (index));
1879 g_hash_table_insert (acfg->method_depth, method, GUINT_TO_POINTER (depth));
1881 acfg->method_index ++;
1887 add_method (MonoAotCompile *acfg, MonoMethod *method)
1889 return add_method_full (acfg, method, FALSE, 0);
1893 add_extra_method (MonoAotCompile *acfg, MonoMethod *method)
1895 add_method_full (acfg, method, TRUE, 0);
1899 add_extra_method_with_depth (MonoAotCompile *acfg, MonoMethod *method, int depth)
1901 add_method_full (acfg, method, TRUE, depth);
1905 add_jit_icall_wrapper (gpointer key, gpointer value, gpointer user_data)
1907 MonoAotCompile *acfg = user_data;
1908 MonoJitICallInfo *callinfo = value;
1909 MonoMethod *wrapper;
1915 name = g_strdup_printf ("__icall_wrapper_%s", callinfo->name);
1916 wrapper = mono_marshal_get_icall_wrapper (callinfo->sig, name, callinfo->func, check_for_pending_exc);
1919 add_method (acfg, wrapper);
1923 get_runtime_invoke_sig (MonoMethodSignature *sig)
1925 MonoMethodBuilder *mb;
1928 mb = mono_mb_new (mono_defaults.object_class, "FOO", MONO_WRAPPER_NONE);
1929 m = mono_mb_create_method (mb, sig, 16);
1930 return mono_marshal_get_runtime_invoke (m, FALSE);
1934 can_marshal_struct (MonoClass *klass)
1936 MonoClassField *field;
1937 gboolean can_marshal = TRUE;
1938 gpointer iter = NULL;
1940 if ((klass->flags & TYPE_ATTRIBUTE_LAYOUT_MASK) == TYPE_ATTRIBUTE_AUTO_LAYOUT)
1943 /* Only allow a few field types to avoid asserts in the marshalling code */
1944 while ((field = mono_class_get_fields (klass, &iter))) {
1945 if ((field->type->attrs & FIELD_ATTRIBUTE_STATIC))
1948 switch (field->type->type) {
1953 case MONO_TYPE_BOOLEAN:
1956 case MONO_TYPE_CHAR:
1964 case MONO_TYPE_STRING:
1966 case MONO_TYPE_VALUETYPE:
1967 if (!can_marshal_struct (mono_class_from_mono_type (field->type)))
1968 can_marshal = FALSE;
1971 can_marshal = FALSE;
1977 /* Its hard to compute whenever these can be marshalled or not */
1978 if (!strcmp (klass->name_space, "System.Net.NetworkInformation.MacOsStructs"))
1985 add_wrappers (MonoAotCompile *acfg)
1987 MonoMethod *method, *m;
1989 MonoMethodSignature *sig, *csig;
1993 * FIXME: Instead of AOTing all the wrappers, it might be better to redesign them
1994 * so there is only one wrapper of a given type, or inlining their contents into their
1999 * FIXME: This depends on the fact that different wrappers have different
2003 for (i = 0; i < acfg->image->tables [MONO_TABLE_METHOD].rows; ++i) {
2005 guint32 token = MONO_TOKEN_METHOD_DEF | (i + 1);
2006 gboolean skip = FALSE;
2008 method = mono_get_method (acfg->image, token, NULL);
2010 if ((method->flags & METHOD_ATTRIBUTE_PINVOKE_IMPL) ||
2011 (method->iflags & METHOD_IMPL_ATTRIBUTE_RUNTIME) ||
2012 (method->flags & METHOD_ATTRIBUTE_ABSTRACT))
2015 if (method->is_generic || method->klass->generic_container)
2018 /* Skip methods which can not be handled by get_runtime_invoke () */
2019 sig = mono_method_signature (method);
2020 if ((sig->ret->type == MONO_TYPE_PTR) ||
2021 (sig->ret->type == MONO_TYPE_TYPEDBYREF))
2024 for (j = 0; j < sig->param_count; j++) {
2025 if (sig->params [j]->type == MONO_TYPE_TYPEDBYREF)
2029 #ifdef MONO_ARCH_DYN_CALL_SUPPORTED
2030 if (!method->klass->contextbound) {
2031 MonoDynCallInfo *info = mono_arch_dyn_call_prepare (sig);
2032 gboolean has_nullable = FALSE;
2034 for (j = 0; j < sig->param_count; j++) {
2035 if (sig->params [j]->type == MONO_TYPE_GENERICINST && mono_class_is_nullable (mono_class_from_mono_type (sig->params [j])))
2036 has_nullable = TRUE;
2039 if (info && !has_nullable) {
2040 /* Supported by the dynamic runtime-invoke wrapper */
2048 //printf ("%s\n", mono_method_full_name (method, TRUE));
2049 add_method (acfg, mono_marshal_get_runtime_invoke (method, FALSE));
2053 if (strcmp (acfg->image->assembly->aname.name, "mscorlib") == 0) {
2054 #ifdef MONO_ARCH_HAVE_TLS_GET
2055 MonoMethodDesc *desc;
2056 MonoMethod *orig_method;
2060 /* Runtime invoke wrappers */
2062 /* void runtime-invoke () [.cctor] */
2063 csig = mono_metadata_signature_alloc (mono_defaults.corlib, 0);
2064 csig->ret = &mono_defaults.void_class->byval_arg;
2065 add_method (acfg, get_runtime_invoke_sig (csig));
2067 /* void runtime-invoke () [Finalize] */
2068 csig = mono_metadata_signature_alloc (mono_defaults.corlib, 0);
2070 csig->ret = &mono_defaults.void_class->byval_arg;
2071 add_method (acfg, get_runtime_invoke_sig (csig));
2073 /* void runtime-invoke (string) [exception ctor] */
2074 csig = mono_metadata_signature_alloc (mono_defaults.corlib, 1);
2076 csig->ret = &mono_defaults.void_class->byval_arg;
2077 csig->params [0] = &mono_defaults.string_class->byval_arg;
2078 add_method (acfg, get_runtime_invoke_sig (csig));
2080 /* void runtime-invoke (string, string) [exception ctor] */
2081 csig = mono_metadata_signature_alloc (mono_defaults.corlib, 2);
2083 csig->ret = &mono_defaults.void_class->byval_arg;
2084 csig->params [0] = &mono_defaults.string_class->byval_arg;
2085 csig->params [1] = &mono_defaults.string_class->byval_arg;
2086 add_method (acfg, get_runtime_invoke_sig (csig));
2088 /* string runtime-invoke () [Exception.ToString ()] */
2089 csig = mono_metadata_signature_alloc (mono_defaults.corlib, 0);
2091 csig->ret = &mono_defaults.string_class->byval_arg;
2092 add_method (acfg, get_runtime_invoke_sig (csig));
2094 /* void runtime-invoke (string, Exception) [exception ctor] */
2095 csig = mono_metadata_signature_alloc (mono_defaults.corlib, 2);
2097 csig->ret = &mono_defaults.void_class->byval_arg;
2098 csig->params [0] = &mono_defaults.string_class->byval_arg;
2099 csig->params [1] = &mono_defaults.exception_class->byval_arg;
2100 add_method (acfg, get_runtime_invoke_sig (csig));
2102 /* Assembly runtime-invoke (string, bool) [DoAssemblyResolve] */
2103 csig = mono_metadata_signature_alloc (mono_defaults.corlib, 2);
2105 csig->ret = &(mono_class_from_name (
2106 mono_defaults.corlib, "System.Reflection", "Assembly"))->byval_arg;
2107 csig->params [0] = &mono_defaults.string_class->byval_arg;
2108 csig->params [1] = &mono_defaults.boolean_class->byval_arg;
2109 add_method (acfg, get_runtime_invoke_sig (csig));
2111 /* runtime-invoke used by finalizers */
2112 add_method (acfg, mono_marshal_get_runtime_invoke (mono_class_get_method_from_name_flags (mono_defaults.object_class, "Finalize", 0, 0), TRUE));
2114 /* This is used by mono_runtime_capture_context () */
2115 method = mono_get_context_capture_method ();
2117 add_method (acfg, mono_marshal_get_runtime_invoke (method, FALSE));
2119 #ifdef MONO_ARCH_DYN_CALL_SUPPORTED
2120 add_method (acfg, mono_marshal_get_runtime_invoke_dynamic ());
2123 /* JIT icall wrappers */
2124 /* FIXME: locking */
2125 g_hash_table_foreach (mono_get_jit_icall_info (), add_jit_icall_wrapper, acfg);
2128 add_method (acfg, mono_marshal_get_stelemref ());
2130 #ifdef MONO_ARCH_HAVE_TLS_GET
2131 /* Managed Allocators */
2132 nallocators = mono_gc_get_managed_allocator_types ();
2133 for (i = 0; i < nallocators; ++i) {
2134 m = mono_gc_get_managed_allocator_by_type (i);
2136 add_method (acfg, m);
2139 /* Monitor Enter/Exit */
2140 desc = mono_method_desc_new ("Monitor:Enter", FALSE);
2141 orig_method = mono_method_desc_search_in_class (desc, mono_defaults.monitor_class);
2142 g_assert (orig_method);
2143 mono_method_desc_free (desc);
2144 method = mono_monitor_get_fast_path (orig_method);
2146 add_method (acfg, method);
2148 desc = mono_method_desc_new ("Monitor:Exit", FALSE);
2149 orig_method = mono_method_desc_search_in_class (desc, mono_defaults.monitor_class);
2150 g_assert (orig_method);
2151 mono_method_desc_free (desc);
2152 method = mono_monitor_get_fast_path (orig_method);
2154 add_method (acfg, method);
2159 * remoting-invoke-with-check wrappers are very frequent, so avoid emitting them,
2160 * we use the original method instead at runtime.
2161 * Since full-aot doesn't support remoting, this is not a problem.
2164 /* remoting-invoke wrappers */
2165 for (i = 0; i < acfg->image->tables [MONO_TABLE_METHOD].rows; ++i) {
2166 MonoMethodSignature *sig;
2168 token = MONO_TOKEN_METHOD_DEF | (i + 1);
2169 method = mono_get_method (acfg->image, token, NULL);
2171 sig = mono_method_signature (method);
2173 if (sig->hasthis && (method->klass->marshalbyref || method->klass == mono_defaults.object_class)) {
2174 m = mono_marshal_get_remoting_invoke_with_check (method);
2176 add_method (acfg, m);
2181 /* delegate-invoke wrappers */
2182 for (i = 0; i < acfg->image->tables [MONO_TABLE_TYPEDEF].rows; ++i) {
2185 token = MONO_TOKEN_TYPE_DEF | (i + 1);
2186 klass = mono_class_get (acfg->image, token);
2188 if (klass->delegate && klass != mono_defaults.delegate_class && klass != mono_defaults.multicastdelegate_class && !klass->generic_container) {
2189 method = mono_get_delegate_invoke (klass);
2191 m = mono_marshal_get_delegate_invoke (method, NULL);
2193 add_method (acfg, m);
2195 method = mono_class_get_method_from_name_flags (klass, "BeginInvoke", -1, 0);
2196 add_method (acfg, mono_marshal_get_delegate_begin_invoke (method));
2198 method = mono_class_get_method_from_name_flags (klass, "EndInvoke", -1, 0);
2199 add_method (acfg, mono_marshal_get_delegate_end_invoke (method));
2203 /* Synchronized wrappers */
2204 for (i = 0; i < acfg->image->tables [MONO_TABLE_METHOD].rows; ++i) {
2205 token = MONO_TOKEN_METHOD_DEF | (i + 1);
2206 method = mono_get_method (acfg->image, token, NULL);
2208 if (method->iflags & METHOD_IMPL_ATTRIBUTE_SYNCHRONIZED && !method->is_generic)
2209 add_method (acfg, mono_marshal_get_synchronized_wrapper (method));
2212 /* pinvoke wrappers */
2213 for (i = 0; i < acfg->image->tables [MONO_TABLE_METHOD].rows; ++i) {
2215 guint32 token = MONO_TOKEN_METHOD_DEF | (i + 1);
2217 method = mono_get_method (acfg->image, token, NULL);
2219 if ((method->flags & METHOD_ATTRIBUTE_PINVOKE_IMPL) ||
2220 (method->iflags & METHOD_IMPL_ATTRIBUTE_INTERNAL_CALL)) {
2221 add_method (acfg, mono_marshal_get_native_wrapper (method, TRUE, TRUE));
2225 /* StructureToPtr/PtrToStructure wrappers */
2226 for (i = 0; i < acfg->image->tables [MONO_TABLE_TYPEDEF].rows; ++i) {
2229 token = MONO_TOKEN_TYPE_DEF | (i + 1);
2230 klass = mono_class_get (acfg->image, token);
2232 if (klass->valuetype && !klass->generic_container && can_marshal_struct (klass)) {
2233 add_method (acfg, mono_marshal_get_struct_to_ptr (klass));
2234 add_method (acfg, mono_marshal_get_ptr_to_struct (klass));
2240 has_type_vars (MonoClass *klass)
2242 if ((klass->byval_arg.type == MONO_TYPE_VAR) || (klass->byval_arg.type == MONO_TYPE_MVAR))
2245 return has_type_vars (klass->element_class);
2246 if (klass->generic_class) {
2247 MonoGenericContext *context = &klass->generic_class->context;
2248 if (context->class_inst) {
2251 for (i = 0; i < context->class_inst->type_argc; ++i)
2252 if (has_type_vars (mono_class_from_mono_type (context->class_inst->type_argv [i])))
2260 method_has_type_vars (MonoMethod *method)
2262 if (has_type_vars (method->klass))
2265 if (method->is_inflated) {
2266 MonoGenericContext *context = mono_method_get_context (method);
2267 if (context->method_inst) {
2270 for (i = 0; i < context->method_inst->type_argc; ++i)
2271 if (has_type_vars (mono_class_from_mono_type (context->method_inst->type_argv [i])))
2279 * add_generic_class:
2281 * Add all methods of a generic class.
2284 add_generic_class (MonoAotCompile *acfg, MonoClass *klass)
2289 mono_class_init (klass);
2291 if (klass->generic_class && klass->generic_class->context.class_inst->is_open)
2294 if (has_type_vars (klass))
2297 if (!klass->generic_class && !klass->rank)
2301 while ((method = mono_class_get_methods (klass, &iter))) {
2302 if (mono_method_is_generic_sharable_impl (method, FALSE))
2306 if (method->is_generic)
2311 * FIXME: Instances which are referenced by these methods are not added,
2312 * for example Array.Resize<int> for List<int>.Add ().
2314 add_extra_method (acfg, method);
2317 if (klass->delegate) {
2318 method = mono_get_delegate_invoke (klass);
2320 method = mono_marshal_get_delegate_invoke (method, NULL);
2322 add_method (acfg, method);
2326 * For ICollection<T>, add instances of the helper methods
2327 * in Array, since a T[] could be cast to ICollection<T>.
2329 if (klass->image == mono_defaults.corlib && !strcmp (klass->name_space, "System.Collections.Generic") &&
2330 (!strcmp(klass->name, "ICollection`1") || !strcmp (klass->name, "IEnumerable`1") || !strcmp (klass->name, "IList`1") || !strcmp (klass->name, "IEnumerator`1"))) {
2331 MonoClass *tclass = mono_class_from_mono_type (klass->generic_class->context.class_inst->type_argv [0]);
2332 MonoClass *array_class = mono_bounded_array_class_get (tclass, 1, FALSE);
2336 if (!strcmp (klass->name, "IEnumerator`1"))
2337 name_prefix = g_strdup_printf ("%s.%s", klass->name_space, "IEnumerable`1");
2339 name_prefix = g_strdup_printf ("%s.%s", klass->name_space, klass->name);
2341 /* Add the T[]/InternalEnumerator class */
2342 if (!strcmp (klass->name, "IEnumerable`1") || !strcmp (klass->name, "IEnumerator`1")) {
2346 while ((nclass = mono_class_get_nested_types (array_class->parent, &iter))) {
2347 if (!strcmp (nclass->name, "InternalEnumerator`1"))
2351 nclass = mono_class_inflate_generic_class (nclass, mono_generic_class_get_context (klass->generic_class));
2352 add_generic_class (acfg, nclass);
2356 while ((method = mono_class_get_methods (array_class, &iter))) {
2357 if (strstr (method->name, name_prefix)) {
2358 MonoMethod *m = mono_aot_get_array_helper_from_wrapper (method);
2359 add_extra_method (acfg, m);
2363 g_free (name_prefix);
2366 /* Add an instance of GenericComparer<T> which is created dynamically by Comparer<T> */
2367 if (klass->image == mono_defaults.corlib && !strcmp (klass->name_space, "System.Collections.Generic") && !strcmp (klass->name, "Comparer`1")) {
2368 MonoClass *tclass = mono_class_from_mono_type (klass->generic_class->context.class_inst->type_argv [0]);
2369 MonoClass *icomparable, *gcomparer;
2370 MonoGenericContext ctx;
2371 MonoType *args [16];
2373 memset (&ctx, 0, sizeof (ctx));
2375 icomparable = mono_class_from_name (mono_defaults.corlib, "System", "IComparable`1");
2376 g_assert (icomparable);
2377 args [0] = &tclass->byval_arg;
2378 ctx.class_inst = mono_metadata_get_generic_inst (1, args);
2380 if (mono_class_is_assignable_from (mono_class_inflate_generic_class (icomparable, &ctx), tclass)) {
2381 gcomparer = mono_class_from_name (mono_defaults.corlib, "System.Collections.Generic", "GenericComparer`1");
2382 g_assert (gcomparer);
2383 add_generic_class (acfg, mono_class_inflate_generic_class (gcomparer, &ctx));
2389 add_instances_of (MonoAotCompile *acfg, MonoClass *klass, MonoType **insts, int ninsts)
2392 MonoGenericContext ctx;
2393 MonoType *args [16];
2395 memset (&ctx, 0, sizeof (ctx));
2397 for (i = 0; i < ninsts; ++i) {
2398 args [0] = insts [i];
2399 ctx.class_inst = mono_metadata_get_generic_inst (1, args);
2400 add_generic_class (acfg, mono_class_inflate_generic_class (klass, &ctx));
2405 * add_generic_instances:
2407 * Add instances referenced by the METHODSPEC/TYPESPEC table.
2410 add_generic_instances (MonoAotCompile *acfg)
2415 MonoMethodHeader *header;
2416 MonoMethodSignature *sig;
2417 MonoGenericContext *context;
2419 for (i = 0; i < acfg->image->tables [MONO_TABLE_METHODSPEC].rows; ++i) {
2420 token = MONO_TOKEN_METHOD_SPEC | (i + 1);
2421 method = mono_get_method (acfg->image, token, NULL);
2423 context = mono_method_get_context (method);
2424 if (context && ((context->class_inst && context->class_inst->is_open) ||
2425 (context->method_inst && context->method_inst->is_open)))
2428 if (method->klass->image != acfg->image)
2431 if (mono_method_is_generic_sharable_impl (method, FALSE))
2435 add_extra_method (acfg, method);
2438 for (i = 0; i < acfg->image->tables [MONO_TABLE_TYPESPEC].rows; ++i) {
2441 token = MONO_TOKEN_TYPE_SPEC | (i + 1);
2443 klass = mono_class_get (acfg->image, token);
2444 if (!klass || klass->rank)
2447 add_generic_class (acfg, klass);
2450 /* Add types of args/locals */
2451 for (i = 0; i < acfg->methods->len; ++i) {
2454 method = g_ptr_array_index (acfg->methods, i);
2456 sig = mono_method_signature (method);
2459 for (j = 0; j < sig->param_count; ++j)
2460 if (sig->params [j]->type == MONO_TYPE_GENERICINST)
2461 add_generic_class (acfg, mono_class_from_mono_type (sig->params [j]));
2464 header = mono_method_get_header (method);
2467 for (j = 0; j < header->num_locals; ++j)
2468 if (header->locals [j]->type == MONO_TYPE_GENERICINST)
2469 add_generic_class (acfg, mono_class_from_mono_type (header->locals [j]));
2473 if (acfg->image == mono_defaults.corlib) {
2475 MonoType *insts [256];
2478 insts [ninsts ++] = &mono_defaults.byte_class->byval_arg;
2479 insts [ninsts ++] = &mono_defaults.sbyte_class->byval_arg;
2480 insts [ninsts ++] = &mono_defaults.int16_class->byval_arg;
2481 insts [ninsts ++] = &mono_defaults.uint16_class->byval_arg;
2482 insts [ninsts ++] = &mono_defaults.int32_class->byval_arg;
2483 insts [ninsts ++] = &mono_defaults.uint32_class->byval_arg;
2484 insts [ninsts ++] = &mono_defaults.int64_class->byval_arg;
2485 insts [ninsts ++] = &mono_defaults.uint64_class->byval_arg;
2486 insts [ninsts ++] = &mono_defaults.single_class->byval_arg;
2487 insts [ninsts ++] = &mono_defaults.double_class->byval_arg;
2488 insts [ninsts ++] = &mono_defaults.char_class->byval_arg;
2489 insts [ninsts ++] = &mono_defaults.boolean_class->byval_arg;
2491 /* Add GenericComparer<T> instances for primitive types for Enum.ToString () */
2492 klass = mono_class_from_name (acfg->image, "System.Collections.Generic", "GenericComparer`1");
2494 add_instances_of (acfg, klass, insts, ninsts);
2495 klass = mono_class_from_name (acfg->image, "System.Collections.Generic", "GenericEqualityComparer`1");
2497 add_instances_of (acfg, klass, insts, ninsts);
2499 /* Add instances of the array generic interfaces for primitive types */
2500 /* This will add instances of the InternalArray_ helper methods in Array too */
2501 klass = mono_class_from_name (acfg->image, "System.Collections.Generic", "ICollection`1");
2503 add_instances_of (acfg, klass, insts, ninsts);
2504 klass = mono_class_from_name (acfg->image, "System.Collections.Generic", "IList`1");
2506 add_instances_of (acfg, klass, insts, ninsts);
2507 klass = mono_class_from_name (acfg->image, "System.Collections.Generic", "IEnumerable`1");
2509 add_instances_of (acfg, klass, insts, ninsts);
2512 * Add a managed-to-native wrapper of Array.GetGenericValueImpl<object>, which is
2513 * used for all instances of GetGenericValueImpl by the AOT runtime.
2516 MonoGenericContext ctx;
2517 MonoType *args [16];
2518 MonoMethod *get_method;
2519 MonoClass *array_klass = mono_array_class_get (mono_defaults.object_class, 1)->parent;
2521 get_method = mono_class_get_method_from_name (array_klass, "GetGenericValueImpl", 2);
2524 memset (&ctx, 0, sizeof (ctx));
2525 args [0] = &mono_defaults.object_class->byval_arg;
2526 ctx.method_inst = mono_metadata_get_generic_inst (1, args);
2527 add_extra_method (acfg, mono_marshal_get_native_wrapper (mono_class_inflate_generic_method (get_method, &ctx), TRUE, TRUE));
2534 * is_direct_callable:
2536 * Return whenever the method identified by JI is directly callable without
2537 * going through the PLT.
2540 is_direct_callable (MonoAotCompile *acfg, MonoMethod *method, MonoJumpInfo *patch_info)
2542 if ((patch_info->type == MONO_PATCH_INFO_METHOD) && (patch_info->data.method->klass->image == acfg->image)) {
2543 MonoCompile *callee_cfg = g_hash_table_lookup (acfg->method_to_cfg, patch_info->data.method);
2545 gboolean direct_callable = TRUE;
2547 if (direct_callable && !(!callee_cfg->has_got_slots && (callee_cfg->method->klass->flags & TYPE_ATTRIBUTE_BEFORE_FIELD_INIT)))
2548 direct_callable = FALSE;
2549 if ((callee_cfg->method->iflags & METHOD_IMPL_ATTRIBUTE_SYNCHRONIZED) && (!method || method->wrapper_type != MONO_WRAPPER_SYNCHRONIZED))
2550 // FIXME: Maybe call the wrapper directly ?
2551 direct_callable = FALSE;
2553 if (direct_callable)
2562 * emit_and_reloc_code:
2564 * Emit the native code in CODE, handling relocations along the way. If GOT_ONLY
2565 * is true, calls are made through the GOT too. This is used for emitting trampolines
2566 * in full-aot mode, since calls made from trampolines couldn't go through the PLT,
2567 * since trampolines are needed to make PTL work.
2570 emit_and_reloc_code (MonoAotCompile *acfg, MonoMethod *method, guint8 *code, guint32 code_len, MonoJumpInfo *relocs, gboolean got_only)
2572 int i, pindex, start_index, method_index;
2574 MonoJumpInfo *patch_info;
2575 MonoMethodHeader *header;
2576 gboolean skip, direct_call;
2578 char direct_call_target [128];
2581 header = mono_method_get_header (method);
2583 method_index = get_method_index (acfg, method);
2586 /* Collect and sort relocations */
2587 patches = g_ptr_array_new ();
2588 for (patch_info = relocs; patch_info; patch_info = patch_info->next)
2589 g_ptr_array_add (patches, patch_info);
2590 g_ptr_array_sort (patches, compare_patches);
2593 for (i = 0; i < code_len; i++) {
2595 for (pindex = start_index; pindex < patches->len; ++pindex) {
2596 patch_info = g_ptr_array_index (patches, pindex);
2597 if (patch_info->ip.i >= i)
2601 #ifdef MONO_ARCH_AOT_SUPPORTED
2603 if (patch_info && (patch_info->ip.i == i) && (pindex < patches->len)) {
2604 start_index = pindex;
2606 switch (patch_info->type) {
2607 case MONO_PATCH_INFO_NONE:
2609 case MONO_PATCH_INFO_GOT_OFFSET: {
2612 arch_emit_got_offset (acfg, code + i, &code_size);
2615 patch_info->type = MONO_PATCH_INFO_NONE;
2620 * If this patch is a call, try emitting a direct call instead of
2621 * through a PLT entry. This is possible if the called method is in
2622 * the same assembly and requires no initialization.
2624 direct_call = FALSE;
2625 if ((patch_info->type == MONO_PATCH_INFO_METHOD) && (patch_info->data.method->klass->image == acfg->image)) {
2626 if (!got_only && is_direct_callable (acfg, method, patch_info)) {
2627 MonoCompile *callee_cfg = g_hash_table_lookup (acfg->method_to_cfg, patch_info->data.method);
2628 //printf ("DIRECT: %s %s\n", method ? mono_method_full_name (method, TRUE) : "", mono_method_full_name (callee_cfg->method, TRUE));
2630 sprintf (direct_call_target, "%sm_%x", acfg->temp_prefix, get_method_index (acfg, callee_cfg->orig_method));
2631 patch_info->type = MONO_PATCH_INFO_NONE;
2632 acfg->stats.direct_calls ++;
2635 acfg->stats.all_calls ++;
2638 if (!got_only && !direct_call) {
2639 int plt_offset = get_plt_offset (acfg, patch_info);
2640 if (plt_offset != -1) {
2641 /* This patch has a PLT entry, so we must emit a call to the PLT entry */
2643 sprintf (direct_call_target, "%sp_%d", acfg->temp_prefix, plt_offset);
2645 /* Nullify the patch */
2646 patch_info->type = MONO_PATCH_INFO_NONE;
2653 arch_emit_direct_call (acfg, direct_call_target, &call_size);
2658 got_slot = get_got_offset (acfg, patch_info);
2660 arch_emit_got_access (acfg, code + i, got_slot, &code_size);
2667 #endif /* MONO_ARCH_AOT_SUPPORTED */
2670 /* Find next patch */
2672 for (pindex = start_index; pindex < patches->len; ++pindex) {
2673 patch_info = g_ptr_array_index (patches, pindex);
2674 if (patch_info->ip.i >= i)
2678 /* Try to emit multiple bytes at once */
2679 if (pindex < patches->len && patch_info->ip.i > i) {
2680 emit_bytes (acfg, code + i, patch_info->ip.i - i);
2681 i = patch_info->ip.i - 1;
2683 emit_bytes (acfg, code + i, 1);
2692 * Modify SYMBOL so it only includes characters permissible in symbols.
2695 sanitize_symbol (char *symbol)
2697 int i, len = strlen (symbol);
2699 for (i = 0; i < len; ++i)
2700 if (!isalnum (symbol [i]) && (symbol [i] != '_'))
2705 get_debug_sym (MonoMethod *method, const char *prefix, GHashTable *cache)
2707 char *name1, *name2, *cached;
2708 int i, j, len, count;
2710 name1 = mono_method_full_name (method, TRUE);
2711 len = strlen (name1);
2712 name2 = malloc (strlen (prefix) + len + 16);
2713 memcpy (name2, prefix, strlen (prefix));
2714 j = strlen (prefix);
2715 for (i = 0; i < len; ++i) {
2716 if (isalnum (name1 [i])) {
2717 name2 [j ++] = name1 [i];
2718 } else if (name1 [i] == ' ' && name1 [i + 1] == '(' && name1 [i + 2] == ')') {
2720 } else if (name1 [i] == ',' && name1 [i + 1] == ' ') {
2723 } else if (name1 [i] == '(' || name1 [i] == ')' || name1 [i] == '>') {
2732 while (g_hash_table_lookup (cache, name2)) {
2733 sprintf (name2 + j, "_%d", count);
2737 cached = g_strdup (name2);
2738 g_hash_table_insert (cache, cached, cached);
2744 emit_method_code (MonoAotCompile *acfg, MonoCompile *cfg)
2749 char *debug_sym = NULL;
2751 int func_alignment = AOT_FUNC_ALIGNMENT;
2752 MonoMethodHeader *header;
2754 method = cfg->orig_method;
2755 code = cfg->native_code;
2756 header = mono_method_get_header (method);
2758 method_index = get_method_index (acfg, method);
2760 /* Emit unbox trampoline */
2761 if (acfg->aot_opts.full_aot && cfg->orig_method->klass->valuetype && (method->flags & METHOD_ATTRIBUTE_VIRTUAL)) {
2762 char call_target [256];
2764 if (!method->wrapper_type && !method->is_inflated) {
2765 g_assert (method->token);
2766 sprintf (symbol, "ut_%d", mono_metadata_token_index (method->token) - 1);
2768 sprintf (symbol, "ut_e_%d", get_method_index (acfg, method));
2771 emit_section_change (acfg, ".text", 0);
2772 emit_global (acfg, symbol, TRUE);
2773 emit_label (acfg, symbol);
2775 sprintf (call_target, "%sm_%x", acfg->temp_prefix, method_index);
2777 arch_emit_unbox_trampoline (acfg, cfg->orig_method, cfg->generic_sharing_context, call_target);
2780 /* Make the labels local */
2781 sprintf (symbol, "%sm_%x", acfg->temp_prefix, method_index);
2783 emit_section_change (acfg, ".text", 0);
2784 emit_alignment (acfg, func_alignment);
2785 emit_label (acfg, symbol);
2787 if (acfg->aot_opts.write_symbols) {
2789 * Write a C style symbol for every method, this has two uses:
2790 * - it works on platforms where the dwarf debugging info is not
2792 * - it allows the setting of breakpoints of aot-ed methods.
2794 debug_sym = get_debug_sym (method, "", acfg->method_label_hash);
2796 sprintf (symbol, "%sme_%x", acfg->temp_prefix, method_index);
2797 emit_local_symbol (acfg, debug_sym, symbol, TRUE);
2798 emit_label (acfg, debug_sym);
2801 if (cfg->verbose_level > 0)
2802 g_print ("Method %s emitted as %s\n", mono_method_full_name (method, TRUE), symbol);
2804 acfg->stats.code_size += cfg->code_len;
2806 acfg->cfgs [method_index]->got_offset = acfg->got_offset;
2808 emit_and_reloc_code (acfg, method, code, cfg->code_len, cfg->patch_info, FALSE);
2812 if (acfg->aot_opts.write_symbols) {
2813 emit_symbol_size (acfg, debug_sym, ".");
2817 sprintf (symbol, "%sme_%x", acfg->temp_prefix, method_index);
2818 emit_label (acfg, symbol);
2824 * Encode PATCH_INFO into its disk representation.
2827 encode_patch (MonoAotCompile *acfg, MonoJumpInfo *patch_info, guint8 *buf, guint8 **endbuf)
2831 switch (patch_info->type) {
2832 case MONO_PATCH_INFO_NONE:
2834 case MONO_PATCH_INFO_IMAGE:
2835 encode_value (get_image_index (acfg, patch_info->data.image), p, &p);
2837 case MONO_PATCH_INFO_MSCORLIB_GOT_ADDR:
2839 case MONO_PATCH_INFO_METHOD_REL:
2840 encode_value ((gint)patch_info->data.offset, p, &p);
2842 case MONO_PATCH_INFO_SWITCH: {
2843 gpointer *table = (gpointer *)patch_info->data.table->table;
2846 encode_value (patch_info->data.table->table_size, p, &p);
2847 for (k = 0; k < patch_info->data.table->table_size; k++)
2848 encode_value ((int)(gssize)table [k], p, &p);
2851 case MONO_PATCH_INFO_METHODCONST:
2852 case MONO_PATCH_INFO_METHOD:
2853 case MONO_PATCH_INFO_METHOD_JUMP:
2854 case MONO_PATCH_INFO_ICALL_ADDR:
2855 case MONO_PATCH_INFO_METHOD_RGCTX:
2856 encode_method_ref (acfg, patch_info->data.method, p, &p);
2858 case MONO_PATCH_INFO_INTERNAL_METHOD:
2859 case MONO_PATCH_INFO_JIT_ICALL_ADDR: {
2860 guint32 len = strlen (patch_info->data.name);
2862 encode_value (len, p, &p);
2864 memcpy (p, patch_info->data.name, len);
2869 case MONO_PATCH_INFO_LDSTR: {
2870 guint32 image_index = get_image_index (acfg, patch_info->data.token->image);
2871 guint32 token = patch_info->data.token->token;
2872 g_assert (mono_metadata_token_code (token) == MONO_TOKEN_STRING);
2873 encode_value (image_index, p, &p);
2874 encode_value (patch_info->data.token->token - MONO_TOKEN_STRING, p, &p);
2877 case MONO_PATCH_INFO_RVA:
2878 case MONO_PATCH_INFO_DECLSEC:
2879 case MONO_PATCH_INFO_LDTOKEN:
2880 case MONO_PATCH_INFO_TYPE_FROM_HANDLE:
2881 encode_value (get_image_index (acfg, patch_info->data.token->image), p, &p);
2882 encode_value (patch_info->data.token->token, p, &p);
2883 encode_value (patch_info->data.token->has_context, p, &p);
2884 if (patch_info->data.token->has_context)
2885 encode_generic_context (acfg, &patch_info->data.token->context, p, &p);
2887 case MONO_PATCH_INFO_EXC_NAME: {
2888 MonoClass *ex_class;
2891 mono_class_from_name (mono_defaults.exception_class->image,
2892 "System", patch_info->data.target);
2893 g_assert (ex_class);
2894 encode_klass_ref (acfg, ex_class, p, &p);
2897 case MONO_PATCH_INFO_R4:
2898 encode_value (*((guint32 *)patch_info->data.target), p, &p);
2900 case MONO_PATCH_INFO_R8:
2901 encode_value (((guint32 *)patch_info->data.target) [MINI_LS_WORD_IDX], p, &p);
2902 encode_value (((guint32 *)patch_info->data.target) [MINI_MS_WORD_IDX], p, &p);
2904 case MONO_PATCH_INFO_VTABLE:
2905 case MONO_PATCH_INFO_CLASS:
2906 case MONO_PATCH_INFO_IID:
2907 case MONO_PATCH_INFO_ADJUSTED_IID:
2908 encode_klass_ref (acfg, patch_info->data.klass, p, &p);
2910 case MONO_PATCH_INFO_CLASS_INIT:
2911 case MONO_PATCH_INFO_DELEGATE_TRAMPOLINE:
2912 encode_klass_ref (acfg, patch_info->data.klass, p, &p);
2914 case MONO_PATCH_INFO_FIELD:
2915 case MONO_PATCH_INFO_SFLDA:
2916 encode_field_info (acfg, patch_info->data.field, p, &p);
2918 case MONO_PATCH_INFO_INTERRUPTION_REQUEST_FLAG:
2920 case MONO_PATCH_INFO_RGCTX_FETCH: {
2921 MonoJumpInfoRgctxEntry *entry = patch_info->data.rgctx_entry;
2923 encode_method_ref (acfg, entry->method, p, &p);
2924 encode_value (entry->in_mrgctx, p, &p);
2925 encode_value (entry->info_type, p, &p);
2926 encode_value (entry->data->type, p, &p);
2927 encode_patch (acfg, entry->data, p, &p);
2930 case MONO_PATCH_INFO_GENERIC_CLASS_INIT:
2931 case MONO_PATCH_INFO_MONITOR_ENTER:
2932 case MONO_PATCH_INFO_MONITOR_EXIT:
2933 case MONO_PATCH_INFO_SEQ_POINT_INFO:
2935 case MONO_PATCH_INFO_LLVM_IMT_TRAMPOLINE:
2936 encode_method_ref (acfg, patch_info->data.imt_tramp->method, p, &p);
2937 encode_value (patch_info->data.imt_tramp->vt_offset, p, &p);
2940 g_warning ("unable to handle jump info %d", patch_info->type);
2941 g_assert_not_reached ();
2948 encode_patch_list (MonoAotCompile *acfg, GPtrArray *patches, int n_patches, int first_got_offset, guint8 *buf, guint8 **endbuf)
2951 guint32 pindex, offset;
2952 MonoJumpInfo *patch_info;
2954 encode_value (n_patches, p, &p);
2956 for (pindex = 0; pindex < patches->len; ++pindex) {
2957 patch_info = g_ptr_array_index (patches, pindex);
2959 if (patch_info->type == MONO_PATCH_INFO_NONE || patch_info->type == MONO_PATCH_INFO_BB)
2963 offset = get_got_offset (acfg, patch_info);
2964 encode_value (offset, p, &p);
2971 emit_method_info (MonoAotCompile *acfg, MonoCompile *cfg)
2975 int pindex, buf_size, n_patches;
2978 MonoJumpInfo *patch_info;
2979 MonoMethodHeader *header;
2980 guint32 method_index;
2982 guint32 first_got_offset;
2984 method = cfg->orig_method;
2985 code = cfg->native_code;
2986 header = mono_method_get_header (method);
2988 method_index = get_method_index (acfg, method);
2990 /* Sort relocations */
2991 patches = g_ptr_array_new ();
2992 for (patch_info = cfg->patch_info; patch_info; patch_info = patch_info->next)
2993 g_ptr_array_add (patches, patch_info);
2994 g_ptr_array_sort (patches, compare_patches);
2996 first_got_offset = acfg->cfgs [method_index]->got_offset;
2998 /**********************/
2999 /* Encode method info */
3000 /**********************/
3002 buf_size = (patches->len < 1000) ? 40960 : 40960 + (patches->len * 64);
3003 p = buf = g_malloc (buf_size);
3005 if (mono_class_get_cctor (method->klass))
3006 encode_klass_ref (acfg, method->klass, p, &p);
3008 /* Not needed when loading the method */
3009 encode_value (0, p, &p);
3012 if (cfg->opt & MONO_OPT_SHARED) {
3013 encode_value (g_list_length (cfg->ldstr_list), p, &p);
3014 for (l = cfg->ldstr_list; l; l = l->next) {
3015 encode_value ((long)l->data, p, &p);
3019 /* Used only in shared mode */
3020 g_assert (!cfg->ldstr_list);
3023 for (pindex = 0; pindex < patches->len; ++pindex) {
3024 patch_info = g_ptr_array_index (patches, pindex);
3026 if ((patch_info->type == MONO_PATCH_INFO_GOT_OFFSET) ||
3027 (patch_info->type == MONO_PATCH_INFO_NONE)) {
3028 patch_info->type = MONO_PATCH_INFO_NONE;
3033 if ((patch_info->type == MONO_PATCH_INFO_IMAGE) && (patch_info->data.image == acfg->image)) {
3034 /* Stored in a GOT slot initialized at module load time */
3035 patch_info->type = MONO_PATCH_INFO_NONE;
3039 if (is_plt_patch (patch_info)) {
3040 /* Calls are made through the PLT */
3041 patch_info->type = MONO_PATCH_INFO_NONE;
3049 g_assert (cfg->has_got_slots);
3051 encode_patch_list (acfg, patches, n_patches, first_got_offset, p, &p);
3053 acfg->stats.info_size += p - buf;
3055 g_assert (p - buf < buf_size);
3057 cfg->method_info_offset = add_to_blob (acfg, buf, p - buf);
3062 get_unwind_info_offset (MonoAotCompile *acfg, guint8 *encoded, guint32 encoded_len)
3064 guint32 cache_index;
3067 /* Reuse the unwind module to canonize and store unwind info entries */
3068 cache_index = mono_cache_unwind_info (encoded, encoded_len);
3070 /* Use +/- 1 to distinguish 0s from missing entries */
3071 offset = GPOINTER_TO_UINT (g_hash_table_lookup (acfg->unwind_info_offsets, GUINT_TO_POINTER (cache_index + 1)));
3079 * It would be easier to use assembler symbols, but the caller needs an
3082 offset = acfg->unwind_info_offset;
3083 g_hash_table_insert (acfg->unwind_info_offsets, GUINT_TO_POINTER (cache_index + 1), GUINT_TO_POINTER (offset + 1));
3084 g_ptr_array_add (acfg->unwind_ops, GUINT_TO_POINTER (cache_index));
3087 encode_value (encoded_len, p, &p);
3089 acfg->unwind_info_offset += encoded_len + (p - buf);
3095 emit_exception_debug_info (MonoAotCompile *acfg, MonoCompile *cfg)
3098 int i, k, buf_size, method_index;
3099 guint32 debug_info_size;
3101 MonoMethodHeader *header;
3102 guint8 *p, *buf, *debug_info;
3103 MonoJitInfo *jinfo = cfg->jit_info;
3105 gboolean use_unwind_ops = FALSE;
3106 MonoSeqPointInfo *seq_points;
3108 method = cfg->orig_method;
3109 code = cfg->native_code;
3110 header = mono_method_get_header (method);
3112 method_index = get_method_index (acfg, method);
3114 if (!acfg->aot_opts.nodebug) {
3115 mono_debug_serialize_debug_info (cfg, &debug_info, &debug_info_size);
3118 debug_info_size = 0;
3121 seq_points = cfg->seq_point_info;
3123 buf_size = header->num_clauses * 256 + debug_info_size + 1024 + (seq_points ? (seq_points->len * 64) : 0);
3124 p = buf = g_malloc (buf_size);
3126 #ifdef MONO_ARCH_HAVE_XP_UNWIND
3127 use_unwind_ops = cfg->unwind_ops != NULL;
3130 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);
3132 encode_value (flags, p, &p);
3134 if (use_unwind_ops) {
3135 guint32 encoded_len;
3139 * This is a duplicate of the data in the .debug_frame section, but that
3140 * section cannot be accessed using the dl interface.
3142 encoded = mono_unwind_ops_encode (cfg->unwind_ops, &encoded_len);
3143 encode_value (get_unwind_info_offset (acfg, encoded, encoded_len), p, &p);
3146 encode_value (jinfo->used_regs, p, &p);
3149 /* Exception table */
3150 if (jinfo->num_clauses)
3151 encode_value (jinfo->num_clauses, p, &p);
3153 for (k = 0; k < jinfo->num_clauses; ++k) {
3154 MonoJitExceptionInfo *ei = &jinfo->clauses [k];
3156 encode_value (ei->flags, p, &p);
3157 encode_value (ei->exvar_offset, p, &p);
3159 if (ei->flags == MONO_EXCEPTION_CLAUSE_FILTER)
3160 encode_value ((gint)((guint8*)ei->data.filter - code), p, &p);
3162 if (ei->data.catch_class) {
3163 encode_value (1, p, &p);
3164 encode_klass_ref (acfg, ei->data.catch_class, p, &p);
3166 encode_value (0, p, &p);
3170 encode_value ((gint)((guint8*)ei->try_start - code), p, &p);
3171 encode_value ((gint)((guint8*)ei->try_end - code), p, &p);
3172 encode_value ((gint)((guint8*)ei->handler_start - code), p, &p);
3175 if (jinfo->has_generic_jit_info) {
3176 MonoGenericJitInfo *gi = mono_jit_info_get_generic_jit_info (jinfo);
3178 encode_value (gi->has_this ? 1 : 0, p, &p);
3179 encode_value (gi->this_reg, p, &p);
3180 encode_value (gi->this_offset, p, &p);
3183 * Need to encode jinfo->method too, since it is not equal to 'method'
3184 * when using generic sharing.
3186 encode_method_ref (acfg, jinfo->method, p, &p);
3190 int il_offset, native_offset, last_il_offset, last_native_offset, j;
3192 encode_value (seq_points->len, p, &p);
3193 last_il_offset = last_native_offset = 0;
3194 for (i = 0; i < seq_points->len; ++i) {
3195 SeqPoint *sp = &seq_points->seq_points [i];
3196 il_offset = sp->il_offset;
3197 native_offset = sp->native_offset;
3198 encode_value (il_offset - last_il_offset, p, &p);
3199 encode_value (native_offset - last_native_offset, p, &p);
3200 last_il_offset = il_offset;
3201 last_native_offset = native_offset;
3203 encode_value (sp->next_len, p, &p);
3204 for (j = 0; j < sp->next_len; ++j)
3205 encode_value (sp->next [j], p, &p);
3210 g_assert (debug_info_size < buf_size);
3212 encode_value (debug_info_size, p, &p);
3213 if (debug_info_size) {
3214 memcpy (p, debug_info, debug_info_size);
3215 p += debug_info_size;
3216 g_free (debug_info);
3219 acfg->stats.ex_info_size += p - buf;
3221 g_assert (p - buf < buf_size);
3224 cfg->ex_info_offset = add_to_blob (acfg, buf, p - buf);
3229 emit_klass_info (MonoAotCompile *acfg, guint32 token)
3231 MonoClass *klass = mono_class_get (acfg->image, token);
3233 int i, buf_size, res;
3234 gboolean no_special_static, cant_encode;
3235 gpointer iter = NULL;
3237 buf_size = 10240 + (klass->vtable_size * 16);
3238 p = buf = g_malloc (buf_size);
3242 mono_class_init (klass);
3244 mono_class_get_nested_types (klass, &iter);
3245 g_assert (klass->nested_classes_inited);
3247 mono_class_setup_vtable (klass);
3250 * Emit all the information which is required for creating vtables so
3251 * the runtime does not need to create the MonoMethod structures which
3252 * take up a lot of space.
3255 no_special_static = !mono_class_has_special_static_fields (klass);
3257 /* Check whenever we have enough info to encode the vtable */
3258 cant_encode = FALSE;
3259 for (i = 0; i < klass->vtable_size; ++i) {
3260 MonoMethod *cm = klass->vtable [i];
3262 if (cm && mono_method_signature (cm)->is_inflated && !g_hash_table_lookup (acfg->token_info_hash, cm))
3266 if (klass->generic_container || cant_encode) {
3267 encode_value (-1, p, &p);
3269 encode_value (klass->vtable_size, p, &p);
3270 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);
3271 if (klass->has_cctor)
3272 encode_method_ref (acfg, mono_class_get_cctor (klass), p, &p);
3273 if (klass->has_finalize)
3274 encode_method_ref (acfg, mono_class_get_finalizer (klass), p, &p);
3276 encode_value (klass->instance_size, p, &p);
3277 encode_value (mono_class_data_size (klass), p, &p);
3278 encode_value (klass->packing_size, p, &p);
3279 encode_value (klass->min_align, p, &p);
3281 for (i = 0; i < klass->vtable_size; ++i) {
3282 MonoMethod *cm = klass->vtable [i];
3285 encode_method_ref (acfg, cm, p, &p);
3287 encode_value (0, p, &p);
3291 acfg->stats.class_info_size += p - buf;
3293 g_assert (p - buf < buf_size);
3294 res = add_to_blob (acfg, buf, p - buf);
3301 * Calls made from AOTed code are routed through a table of jumps similar to the
3302 * ELF PLT (Program Linkage Table). The differences are the following:
3303 * - the ELF PLT entries make an indirect jump though the GOT so they expect the
3304 * GOT pointer to be in EBX. We want to avoid this, so our table contains direct
3305 * jumps. This means the jumps need to be patched when the address of the callee is
3306 * known. Initially the PLT entries jump to code which transfers control to the
3307 * AOT runtime through the first PLT entry.
3310 emit_plt (MonoAotCompile *acfg)
3316 cache = g_hash_table_new (g_str_hash, g_str_equal);
3319 sprintf (symbol, "plt");
3321 emit_section_change (acfg, ".text", 0);
3322 emit_global (acfg, symbol, TRUE);
3324 /* This section will be made read-write by the AOT loader */
3325 emit_alignment (acfg, mono_pagesize ());
3327 emit_alignment (acfg, 16);
3329 emit_label (acfg, symbol);
3330 emit_label (acfg, acfg->plt_symbol);
3332 for (i = 0; i < acfg->plt_offset; ++i) {
3334 char *debug_sym = NULL;
3337 sprintf (label, "%sp_%d", acfg->temp_prefix, i);
3341 * If the target is directly callable, alias the plt symbol to point to
3343 * FIXME: Use this to simplify emit_and_reloc_code ().
3344 * FIXME: Avoid the got slot.
3345 * FIXME: Add support to the binary writer.
3347 ji = g_hash_table_lookup (acfg->plt_offset_to_patch, GUINT_TO_POINTER (i));
3348 if (ji && is_direct_callable (acfg, NULL, ji) && !acfg->use_bin_writer) {
3349 MonoCompile *callee_cfg = g_hash_table_lookup (acfg->method_to_cfg, ji->data.method);
3350 fprintf (acfg->fp, "\n.set %s, .Lm_%x\n", label, get_method_index (acfg, callee_cfg->orig_method));
3355 emit_label (acfg, label);
3357 if (acfg->aot_opts.write_symbols) {
3358 MonoJumpInfo *ji = g_hash_table_lookup (acfg->plt_offset_to_patch, GUINT_TO_POINTER (i));
3362 case MONO_PATCH_INFO_METHOD:
3363 debug_sym = get_debug_sym (ji->data.method, "plt_", cache);
3365 case MONO_PATCH_INFO_INTERNAL_METHOD:
3366 debug_sym = g_strdup_printf ("plt__jit_icall_%s", ji->data.name);
3368 case MONO_PATCH_INFO_CLASS_INIT:
3369 debug_sym = g_strdup_printf ("plt__class_init_%s", mono_type_get_name (&ji->data.klass->byval_arg));
3370 sanitize_symbol (debug_sym);
3372 case MONO_PATCH_INFO_RGCTX_FETCH:
3373 debug_sym = g_strdup_printf ("plt__rgctx_fetch_%d", acfg->label_generator ++);
3375 case MONO_PATCH_INFO_ICALL_ADDR: {
3376 char *s = get_debug_sym (ji->data.method, "", cache);
3378 debug_sym = g_strdup_printf ("plt__icall_native_%s", s);
3382 case MONO_PATCH_INFO_JIT_ICALL_ADDR:
3383 debug_sym = g_strdup_printf ("plt__jit_icall_native_%s", ji->data.name);
3385 case MONO_PATCH_INFO_GENERIC_CLASS_INIT:
3386 debug_sym = g_strdup_printf ("plt__generic_class_init");
3393 emit_local_symbol (acfg, debug_sym, NULL, TRUE);
3394 emit_label (acfg, debug_sym);
3400 * The first plt entry is used to transfer code to the AOT loader.
3402 arch_emit_plt_entry (acfg, i);
3405 emit_symbol_size (acfg, debug_sym, ".");
3410 emit_symbol_size (acfg, acfg->plt_symbol, ".");
3412 sprintf (symbol, "plt_end");
3413 emit_global (acfg, symbol, TRUE);
3414 emit_label (acfg, symbol);
3416 g_hash_table_destroy (cache);
3419 static G_GNUC_UNUSED void
3420 emit_trampoline (MonoAotCompile *acfg, const char *name, guint8 *code,
3421 guint32 code_size, int got_offset, MonoJumpInfo *ji, GSList *unwind_ops)
3423 char start_symbol [256];
3425 guint32 buf_size, info_offset;
3426 MonoJumpInfo *patch_info;
3432 sprintf (start_symbol, "%s", name);
3434 emit_section_change (acfg, ".text", 0);
3435 emit_global (acfg, start_symbol, TRUE);
3436 emit_alignment (acfg, 16);
3437 emit_label (acfg, start_symbol);
3439 sprintf (symbol, "%snamed_%s", acfg->temp_prefix, name);
3440 emit_label (acfg, symbol);
3443 * The code should access everything through the GOT, so we pass
3446 emit_and_reloc_code (acfg, NULL, code, code_size, ji, TRUE);
3448 emit_symbol_size (acfg, start_symbol, ".");
3452 /* Sort relocations */
3453 patches = g_ptr_array_new ();
3454 for (patch_info = ji; patch_info; patch_info = patch_info->next)
3455 if (patch_info->type != MONO_PATCH_INFO_NONE)
3456 g_ptr_array_add (patches, patch_info);
3457 g_ptr_array_sort (patches, compare_patches);
3459 buf_size = patches->len * 128 + 128;
3460 buf = g_malloc (buf_size);
3463 encode_patch_list (acfg, patches, patches->len, got_offset, p, &p);
3464 g_assert (p - buf < buf_size);
3466 sprintf (symbol, "%s_p", name);
3468 info_offset = add_to_blob (acfg, buf, p - buf);
3470 emit_section_change (acfg, ".text", 0);
3471 emit_global (acfg, symbol, FALSE);
3472 emit_label (acfg, symbol);
3474 emit_int32 (acfg, info_offset);
3476 /* Emit debug info */
3480 sprintf (symbol, "%s", name);
3481 sprintf (symbol2, "%snamed_%s", acfg->temp_prefix, name);
3484 mono_dwarf_writer_emit_trampoline (acfg->dwarf, symbol, symbol2, NULL, NULL, code_size, unwind_ops);
3489 emit_trampolines (MonoAotCompile *acfg)
3492 int i, tramp_got_offset;
3493 MonoAotTrampoline ntype;
3494 #ifdef MONO_ARCH_HAVE_FULL_AOT_TRAMPOLINES
3502 if (!acfg->aot_opts.full_aot)
3505 g_assert (acfg->image->assembly);
3507 /* Currently, we only emit most trampolines into the mscorlib AOT image. */
3508 if (strcmp (acfg->image->assembly->aname.name, "mscorlib") == 0) {
3509 #ifdef MONO_ARCH_HAVE_FULL_AOT_TRAMPOLINES
3511 * Emit the generic trampolines.
3513 * We could save some code by treating the generic trampolines as a wrapper
3514 * method, but that approach has its own complexities, so we choose the simpler
3517 for (tramp_type = 0; tramp_type < MONO_TRAMPOLINE_NUM; ++tramp_type) {
3518 code = mono_arch_create_trampoline_code_full (tramp_type, &code_size, &ji, &unwind_ops, TRUE);
3520 /* Emit trampoline code */
3522 sprintf (symbol, "generic_trampoline_%d", tramp_type);
3524 emit_trampoline (acfg, symbol, code, code_size, acfg->got_offset, ji, unwind_ops);
3527 code = mono_arch_get_nullified_class_init_trampoline (&code_size);
3528 emit_trampoline (acfg, "nullified_class_init_trampoline", code, code_size, acfg->got_offset, NULL, NULL);
3529 #if defined(TARGET_AMD64) && defined(MONO_ARCH_MONITOR_OBJECT_REG)
3530 code = mono_arch_create_monitor_enter_trampoline_full (&code_size, &ji, TRUE);
3531 emit_trampoline (acfg, "monitor_enter_trampoline", code, code_size, acfg->got_offset, ji, NULL);
3532 code = mono_arch_create_monitor_exit_trampoline_full (&code_size, &ji, TRUE);
3533 emit_trampoline (acfg, "monitor_exit_trampoline", code, code_size, acfg->got_offset, ji, NULL);
3536 code = mono_arch_create_generic_class_init_trampoline_full (&code_size, &ji, TRUE);
3537 emit_trampoline (acfg, "generic_class_init_trampoline", code, code_size, acfg->got_offset, ji, NULL);
3539 /* Emit the exception related code pieces */
3540 code = mono_arch_get_restore_context_full (&code_size, &ji, TRUE);
3541 emit_trampoline (acfg, "restore_context", code, code_size, acfg->got_offset, ji, NULL);
3542 code = mono_arch_get_call_filter_full (&code_size, &ji, TRUE);
3543 emit_trampoline (acfg, "call_filter", code, code_size, acfg->got_offset, ji, NULL);
3544 code = mono_arch_get_throw_exception_full (&code_size, &ji, TRUE);
3545 emit_trampoline (acfg, "throw_exception", code, code_size, acfg->got_offset, ji, NULL);
3546 code = mono_arch_get_rethrow_exception_full (&code_size, &ji, TRUE);
3547 emit_trampoline (acfg, "rethrow_exception", code, code_size, acfg->got_offset, ji, NULL);
3548 #ifdef MONO_ARCH_HAVE_THROW_EXCEPTION_BY_NAME
3549 code = mono_arch_get_throw_exception_by_name_full (&code_size, &ji, TRUE);
3550 emit_trampoline (acfg, "throw_exception_by_name", code, code_size, acfg->got_offset, ji, NULL);
3552 code = mono_arch_get_throw_corlib_exception_full (&code_size, &ji, TRUE);
3553 emit_trampoline (acfg, "throw_corlib_exception", code, code_size, acfg->got_offset, ji, NULL);
3555 #if defined(TARGET_AMD64)
3556 code = mono_arch_get_throw_pending_exception_full (&code_size, &ji, TRUE);
3557 emit_trampoline (acfg, "throw_pending_exception", code, code_size, acfg->got_offset, ji, NULL);
3560 for (i = 0; i < 128; ++i) {
3563 offset = MONO_RGCTX_SLOT_MAKE_RGCTX (i);
3564 code = mono_arch_create_rgctx_lazy_fetch_trampoline_full (offset, &code_size, &ji, TRUE);
3565 sprintf (symbol, "rgctx_fetch_trampoline_%u", offset);
3566 emit_trampoline (acfg, symbol, code, code_size, acfg->got_offset, ji, NULL);
3568 offset = MONO_RGCTX_SLOT_MAKE_MRGCTX (i);
3569 code = mono_arch_create_rgctx_lazy_fetch_trampoline_full (offset, &code_size, &ji, TRUE);
3570 sprintf (symbol, "rgctx_fetch_trampoline_%u", offset);
3571 emit_trampoline (acfg, symbol, code, code_size, acfg->got_offset, ji, NULL);
3577 /* delegate_invoke_impl trampolines */
3578 l = mono_arch_get_delegate_invoke_impls ();
3580 MonoAotTrampInfo *info = l->data;
3582 emit_trampoline (acfg, info->name, info->code, info->code_size, acfg->got_offset, NULL, NULL);
3587 #endif /* #ifdef MONO_ARCH_HAVE_FULL_AOT_TRAMPOLINES */
3589 /* Emit trampolines which are numerous */
3592 * These include the following:
3593 * - specific trampolines
3594 * - static rgctx invoke trampolines
3596 * These trampolines have the same code, they are parameterized by GOT
3598 * They are defined in this file, in the arch_... routines instead of
3599 * in tramp-<ARCH>.c, since it is easier to do it this way.
3603 * When running in aot-only mode, we can't create specific trampolines at
3604 * runtime, so we create a few, and save them in the AOT file.
3605 * Normal trampolines embed their argument as a literal inside the
3606 * trampoline code, we can't do that here, so instead we embed an offset
3607 * which needs to be added to the trampoline address to get the address of
3608 * the GOT slot which contains the argument value.
3609 * The generated trampolines jump to the generic trampolines using another
3610 * GOT slot, which will be setup by the AOT loader to point to the
3611 * generic trampoline code of the given type.
3615 * FIXME: Maybe we should use more specific trampolines (i.e. one class init for
3619 emit_section_change (acfg, ".text", 0);
3621 tramp_got_offset = acfg->got_offset;
3623 for (ntype = 0; ntype < MONO_AOT_TRAMP_NUM; ++ntype) {
3625 case MONO_AOT_TRAMP_SPECIFIC:
3626 sprintf (symbol, "specific_trampolines");
3628 case MONO_AOT_TRAMP_STATIC_RGCTX:
3629 sprintf (symbol, "static_rgctx_trampolines");
3631 case MONO_AOT_TRAMP_IMT_THUNK:
3632 sprintf (symbol, "imt_thunks");
3635 g_assert_not_reached ();
3638 emit_global (acfg, symbol, TRUE);
3639 emit_alignment (acfg, 16);
3640 emit_label (acfg, symbol);
3642 acfg->trampoline_got_offset_base [ntype] = tramp_got_offset;
3644 for (i = 0; i < acfg->num_trampolines [ntype]; ++i) {
3648 case MONO_AOT_TRAMP_SPECIFIC:
3649 arch_emit_specific_trampoline (acfg, tramp_got_offset, &tramp_size);
3650 tramp_got_offset += 2;
3652 case MONO_AOT_TRAMP_STATIC_RGCTX:
3653 arch_emit_static_rgctx_trampoline (acfg, tramp_got_offset, &tramp_size);
3654 tramp_got_offset += 2;
3656 case MONO_AOT_TRAMP_IMT_THUNK:
3657 arch_emit_imt_thunk (acfg, tramp_got_offset, &tramp_size);
3658 tramp_got_offset += 1;
3661 g_assert_not_reached ();
3664 if (!acfg->trampoline_size [ntype]) {
3665 g_assert (tramp_size);
3666 acfg->trampoline_size [ntype] = tramp_size;
3671 /* Reserve some entries at the end of the GOT for our use */
3672 acfg->num_trampoline_got_entries = tramp_got_offset - acfg->got_offset;
3675 acfg->got_offset += acfg->num_trampoline_got_entries;
3679 str_begins_with (const char *str1, const char *str2)
3681 int len = strlen (str2);
3682 return strncmp (str1, str2, len) == 0;
3686 mono_aot_parse_options (const char *aot_options, MonoAotOptions *opts)
3688 gchar **args, **ptr;
3690 args = g_strsplit (aot_options ? aot_options : "", ",", -1);
3691 for (ptr = args; ptr && *ptr; ptr ++) {
3692 const char *arg = *ptr;
3694 if (str_begins_with (arg, "outfile=")) {
3695 opts->outfile = g_strdup (arg + strlen ("outfile="));
3696 } else if (str_begins_with (arg, "save-temps")) {
3697 opts->save_temps = TRUE;
3698 } else if (str_begins_with (arg, "keep-temps")) {
3699 opts->save_temps = TRUE;
3700 } else if (str_begins_with (arg, "write-symbols")) {
3701 opts->write_symbols = TRUE;
3702 } else if (str_begins_with (arg, "metadata-only")) {
3703 opts->metadata_only = TRUE;
3704 } else if (str_begins_with (arg, "bind-to-runtime-version")) {
3705 opts->bind_to_runtime_version = TRUE;
3706 } else if (str_begins_with (arg, "full")) {
3707 opts->full_aot = TRUE;
3708 } else if (str_begins_with (arg, "threads=")) {
3709 opts->nthreads = atoi (arg + strlen ("threads="));
3710 } else if (str_begins_with (arg, "static")) {
3711 opts->static_link = TRUE;
3712 opts->no_dlsym = TRUE;
3713 } else if (str_begins_with (arg, "asmonly")) {
3714 opts->asm_only = TRUE;
3715 } else if (str_begins_with (arg, "asmwriter")) {
3716 opts->asm_writer = TRUE;
3717 } else if (str_begins_with (arg, "nodebug")) {
3718 opts->nodebug = TRUE;
3719 } else if (str_begins_with (arg, "ntrampolines=")) {
3720 opts->ntrampolines = atoi (arg + strlen ("ntrampolines="));
3721 } else if (str_begins_with (arg, "nrgctx-trampolines=")) {
3722 opts->nrgctx_trampolines = atoi (arg + strlen ("nrgctx-trampolines="));
3723 } else if (str_begins_with (arg, "autoreg")) {
3724 opts->autoreg = TRUE;
3725 } else if (str_begins_with (arg, "tool-prefix=")) {
3726 opts->tool_prefix = g_strdup (arg + strlen ("tool-prefix="));
3727 } else if (str_begins_with (arg, "soft-debug")) {
3728 opts->soft_debug = TRUE;
3729 } else if (str_begins_with (arg, "print-skipped")) {
3730 opts->print_skipped_methods = TRUE;
3731 } else if (str_begins_with (arg, "stats")) {
3734 fprintf (stderr, "AOT : Unknown argument '%s'.\n", arg);
3743 add_token_info_hash (gpointer key, gpointer value, gpointer user_data)
3745 MonoMethod *method = (MonoMethod*)key;
3746 MonoJumpInfoToken *ji = (MonoJumpInfoToken*)value;
3747 MonoJumpInfoToken *new_ji = g_new0 (MonoJumpInfoToken, 1);
3748 MonoAotCompile *acfg = user_data;
3750 new_ji->image = ji->image;
3751 new_ji->token = ji->token;
3752 g_hash_table_insert (acfg->token_info_hash, method, new_ji);
3756 can_encode_class (MonoAotCompile *acfg, MonoClass *klass)
3758 if (klass->type_token)
3760 if ((klass->byval_arg.type == MONO_TYPE_VAR) || (klass->byval_arg.type == MONO_TYPE_MVAR))
3763 return can_encode_class (acfg, klass->element_class);
3768 can_encode_patch (MonoAotCompile *acfg, MonoJumpInfo *patch_info)
3770 switch (patch_info->type) {
3771 case MONO_PATCH_INFO_METHOD:
3772 case MONO_PATCH_INFO_METHODCONST: {
3773 MonoMethod *method = patch_info->data.method;
3775 if (method->wrapper_type) {
3776 switch (method->wrapper_type) {
3777 case MONO_WRAPPER_NONE:
3778 case MONO_WRAPPER_REMOTING_INVOKE_WITH_CHECK:
3779 case MONO_WRAPPER_XDOMAIN_INVOKE:
3780 case MONO_WRAPPER_STFLD:
3781 case MONO_WRAPPER_LDFLD:
3782 case MONO_WRAPPER_LDFLDA:
3783 case MONO_WRAPPER_LDFLD_REMOTE:
3784 case MONO_WRAPPER_STFLD_REMOTE:
3785 case MONO_WRAPPER_STELEMREF:
3786 case MONO_WRAPPER_ISINST:
3787 case MONO_WRAPPER_PROXY_ISINST:
3788 case MONO_WRAPPER_ALLOC:
3789 case MONO_WRAPPER_REMOTING_INVOKE:
3790 case MONO_WRAPPER_UNKNOWN:
3792 case MONO_WRAPPER_MANAGED_TO_MANAGED:
3793 if (!strcmp (method->name, "ElementAddr"))
3798 //printf ("Skip (wrapper call): %d -> %s\n", patch_info->type, mono_method_full_name (patch_info->data.method, TRUE));
3802 if (!method->token) {
3803 /* The method is part of a constructed type like Int[,].Set (). */
3804 if (!g_hash_table_lookup (acfg->token_info_hash, method)) {
3805 if (method->klass->rank)
3813 case MONO_PATCH_INFO_VTABLE:
3814 case MONO_PATCH_INFO_CLASS_INIT:
3815 case MONO_PATCH_INFO_DELEGATE_TRAMPOLINE:
3816 case MONO_PATCH_INFO_CLASS:
3817 case MONO_PATCH_INFO_IID:
3818 case MONO_PATCH_INFO_ADJUSTED_IID:
3819 if (!can_encode_class (acfg, patch_info->data.klass)) {
3820 //printf ("Skip: %s\n", mono_type_full_name (&patch_info->data.klass->byval_arg));
3824 case MONO_PATCH_INFO_RGCTX_FETCH: {
3825 MonoJumpInfoRgctxEntry *entry = patch_info->data.rgctx_entry;
3827 if (!can_encode_patch (acfg, entry->data))
3839 add_generic_class (MonoAotCompile *acfg, MonoClass *klass);
3844 * AOT compile a given method.
3845 * This function might be called by multiple threads, so it must be thread-safe.
3848 compile_method (MonoAotCompile *acfg, MonoMethod *method)
3851 MonoJumpInfo *patch_info;
3854 MonoMethod *wrapped;
3856 if (acfg->aot_opts.metadata_only)
3859 mono_acfg_lock (acfg);
3860 index = get_method_index (acfg, method);
3861 mono_acfg_unlock (acfg);
3863 /* fixme: maybe we can also precompile wrapper methods */
3864 if ((method->flags & METHOD_ATTRIBUTE_PINVOKE_IMPL) ||
3865 (method->iflags & METHOD_IMPL_ATTRIBUTE_RUNTIME) ||
3866 (method->flags & METHOD_ATTRIBUTE_ABSTRACT)) {
3867 //printf ("Skip (impossible): %s\n", mono_method_full_name (method, TRUE));
3871 if (method->iflags & METHOD_IMPL_ATTRIBUTE_INTERNAL_CALL)
3874 wrapped = mono_marshal_method_from_wrapper (method);
3875 if (wrapped && (wrapped->iflags & METHOD_IMPL_ATTRIBUTE_INTERNAL_CALL) && wrapped->is_generic)
3876 // FIXME: The wrapper should be generic too, but it is not
3879 InterlockedIncrement (&acfg->stats.mcount);
3882 if (method->is_generic || method->klass->generic_container) {
3883 InterlockedIncrement (&acfg->stats.genericcount);
3888 //acfg->aot_opts.print_skipped_methods = TRUE;
3891 * Since these methods are the only ones which are compiled with
3892 * AOT support, and they are not used by runtime startup/shutdown code,
3893 * the runtime will not see AOT methods during AOT compilation,so it
3894 * does not need to support them by creating a fake GOT etc.
3896 cfg = mini_method_compile (method, acfg->opts, mono_get_root_domain (), FALSE, TRUE, 0);
3897 if (cfg->exception_type == MONO_EXCEPTION_GENERIC_SHARING_FAILED) {
3898 //printf ("F: %s\n", mono_method_full_name (method, TRUE));
3899 InterlockedIncrement (&acfg->stats.genericcount);
3902 if (cfg->exception_type != MONO_EXCEPTION_NONE) {
3903 /* Let the exception happen at runtime */
3907 if (cfg->disable_aot) {
3908 if (acfg->aot_opts.print_skipped_methods)
3909 printf ("Skip (disabled): %s\n", mono_method_full_name (method, TRUE));
3910 InterlockedIncrement (&acfg->stats.ocount);
3911 mono_destroy_compile (cfg);
3915 /* Nullify patches which need no aot processing */
3916 for (patch_info = cfg->patch_info; patch_info; patch_info = patch_info->next) {
3917 switch (patch_info->type) {
3918 case MONO_PATCH_INFO_LABEL:
3919 case MONO_PATCH_INFO_BB:
3920 patch_info->type = MONO_PATCH_INFO_NONE;
3927 /* Collect method->token associations from the cfg */
3928 mono_acfg_lock (acfg);
3929 g_hash_table_foreach (cfg->token_info_hash, add_token_info_hash, acfg);
3930 mono_acfg_unlock (acfg);
3933 * Check for absolute addresses.
3936 for (patch_info = cfg->patch_info; patch_info; patch_info = patch_info->next) {
3937 switch (patch_info->type) {
3938 case MONO_PATCH_INFO_ABS:
3939 /* unable to handle this */
3948 if (acfg->aot_opts.print_skipped_methods)
3949 printf ("Skip (abs call): %s\n", mono_method_full_name (method, TRUE));
3950 InterlockedIncrement (&acfg->stats.abscount);
3951 mono_destroy_compile (cfg);
3955 /* Lock for the rest of the code */
3956 mono_acfg_lock (acfg);
3959 * Check for methods/klasses we can't encode.
3962 for (patch_info = cfg->patch_info; patch_info; patch_info = patch_info->next) {
3963 if (!can_encode_patch (acfg, patch_info))
3968 if (acfg->aot_opts.print_skipped_methods)
3969 printf ("Skip (patches): %s\n", mono_method_full_name (method, TRUE));
3970 acfg->stats.ocount++;
3971 mono_destroy_compile (cfg);
3972 mono_acfg_unlock (acfg);
3976 /* Adds generic instances referenced by this method */
3978 * The depth is used to avoid infinite loops when generic virtual recursion is
3981 depth = GPOINTER_TO_UINT (g_hash_table_lookup (acfg->method_depth, method));
3983 for (patch_info = cfg->patch_info; patch_info; patch_info = patch_info->next) {
3984 switch (patch_info->type) {
3985 case MONO_PATCH_INFO_METHOD: {
3986 MonoMethod *m = patch_info->data.method;
3987 if (m->is_inflated) {
3988 if (!(mono_class_generic_sharing_enabled (m->klass) &&
3989 mono_method_is_generic_sharable_impl (m, FALSE)) &&
3990 !method_has_type_vars (m)) {
3991 if (m->iflags & METHOD_IMPL_ATTRIBUTE_INTERNAL_CALL) {
3992 if (acfg->aot_opts.full_aot)
3993 add_extra_method_with_depth (acfg, mono_marshal_get_native_wrapper (m, TRUE, TRUE), depth + 1);
3995 add_extra_method_with_depth (acfg, m, depth + 1);
3998 add_generic_class (acfg, m->klass);
4000 if (m->wrapper_type == MONO_WRAPPER_MANAGED_TO_MANAGED && !strcmp (m->name, "ElementAddr"))
4001 add_extra_method_with_depth (acfg, m, depth + 1);
4004 case MONO_PATCH_INFO_VTABLE: {
4005 MonoClass *klass = patch_info->data.klass;
4007 if (klass->generic_class && !mono_generic_context_is_sharable (&klass->generic_class->context, FALSE))
4008 add_generic_class (acfg, klass);
4017 /* Determine whenever the method has GOT slots */
4018 for (patch_info = cfg->patch_info; patch_info; patch_info = patch_info->next) {
4019 switch (patch_info->type) {
4020 case MONO_PATCH_INFO_GOT_OFFSET:
4021 case MONO_PATCH_INFO_NONE:
4023 case MONO_PATCH_INFO_IMAGE:
4024 /* The assembly is stored in GOT slot 0 */
4025 if (patch_info->data.image != acfg->image)
4026 cfg->has_got_slots = TRUE;
4029 if (!is_plt_patch (patch_info))
4030 cfg->has_got_slots = TRUE;
4035 if (!cfg->has_got_slots)
4036 InterlockedIncrement (&acfg->stats.methods_without_got_slots);
4039 * FIXME: Instead of this mess, allocate the patches from the aot mempool.
4041 /* Make a copy of the patch info which is in the mempool */
4043 MonoJumpInfo *patches = NULL, *patches_end = NULL;
4045 for (patch_info = cfg->patch_info; patch_info; patch_info = patch_info->next) {
4046 MonoJumpInfo *new_patch_info = mono_patch_info_dup_mp (acfg->mempool, patch_info);
4049 patches = new_patch_info;
4051 patches_end->next = new_patch_info;
4052 patches_end = new_patch_info;
4054 cfg->patch_info = patches;
4056 /* Make a copy of the unwind info */
4058 GSList *l, *unwind_ops;
4062 for (l = cfg->unwind_ops; l; l = l->next) {
4063 op = mono_mempool_alloc (acfg->mempool, sizeof (MonoUnwindOp));
4064 memcpy (op, l->data, sizeof (MonoUnwindOp));
4065 unwind_ops = g_slist_prepend_mempool (acfg->mempool, unwind_ops, op);
4067 cfg->unwind_ops = g_slist_reverse (unwind_ops);
4069 /* Make a copy of the argument/local info */
4071 MonoInst **args, **locals;
4072 MonoMethodSignature *sig;
4073 MonoMethodHeader *header;
4076 sig = mono_method_signature (method);
4077 args = mono_mempool_alloc (acfg->mempool, sizeof (MonoInst*) * (sig->param_count + sig->hasthis));
4078 for (i = 0; i < sig->param_count + sig->hasthis; ++i) {
4079 args [i] = mono_mempool_alloc (acfg->mempool, sizeof (MonoInst));
4080 memcpy (args [i], cfg->args [i], sizeof (MonoInst));
4084 header = mono_method_get_header (method);
4085 locals = mono_mempool_alloc (acfg->mempool, sizeof (MonoInst*) * header->num_locals);
4086 for (i = 0; i < header->num_locals; ++i) {
4087 locals [i] = mono_mempool_alloc (acfg->mempool, sizeof (MonoInst));
4088 memcpy (locals [i], cfg->locals [i], sizeof (MonoInst));
4090 cfg->locals = locals;
4093 /* Free some fields used by cfg to conserve memory */
4094 mono_mempool_destroy (cfg->mempool);
4095 cfg->mempool = NULL;
4096 g_free (cfg->varinfo);
4097 cfg->varinfo = NULL;
4101 mono_regstate_free (cfg->rs);
4105 //printf ("Compile: %s\n", mono_method_full_name (method, TRUE));
4107 while (index >= acfg->cfgs_size) {
4108 MonoCompile **new_cfgs;
4111 new_size = acfg->cfgs_size * 2;
4112 new_cfgs = g_new0 (MonoCompile*, new_size);
4113 memcpy (new_cfgs, acfg->cfgs, sizeof (MonoCompile*) * acfg->cfgs_size);
4114 g_free (acfg->cfgs);
4115 acfg->cfgs = new_cfgs;
4116 acfg->cfgs_size = new_size;
4118 acfg->cfgs [index] = cfg;
4120 g_hash_table_insert (acfg->method_to_cfg, cfg->orig_method, cfg);
4123 if (cfg->orig_method->wrapper_type)
4124 g_ptr_array_add (acfg->extra_methods, cfg->orig_method);
4127 mono_acfg_unlock (acfg);
4129 InterlockedIncrement (&acfg->stats.ccount);
4133 compile_thread_main (gpointer *user_data)
4135 MonoDomain *domain = user_data [0];
4136 MonoAotCompile *acfg = user_data [1];
4137 GPtrArray *methods = user_data [2];
4140 mono_thread_attach (domain);
4142 for (i = 0; i < methods->len; ++i)
4143 compile_method (acfg, g_ptr_array_index (methods, i));
4147 load_profile_files (MonoAotCompile *acfg)
4151 int file_index, res, method_index, i;
4158 tmp = g_strdup_printf ("%s/.mono/aot-profile-data/%s-%s-%d", g_get_home_dir (), acfg->image->assembly_name, acfg->image->guid, file_index);
4160 if (!g_file_test (tmp, G_FILE_TEST_IS_REGULAR)) {
4165 infile = fopen (tmp, "r");
4168 printf ("Using profile data file '%s'\n", tmp);
4173 res = fscanf (infile, "%32s\n", ver);
4174 if ((res != 1) || strcmp (ver, "#VER:1") != 0) {
4175 printf ("Profile file has wrong version or invalid.\n");
4181 res = fscanf (infile, "%d\n", &token);
4185 method_index = mono_metadata_token_index (token) - 1;
4187 if (!g_list_find (acfg->method_order, GUINT_TO_POINTER (method_index)))
4188 acfg->method_order = g_list_append (acfg->method_order, GUINT_TO_POINTER (method_index));
4193 /* Add missing methods */
4195 for (i = 0; i < acfg->image->tables [MONO_TABLE_METHOD].rows; ++i) {
4196 if (!g_list_find (acfg->method_order, GUINT_TO_POINTER (i)))
4197 unordered = g_list_prepend (unordered, GUINT_TO_POINTER (i));
4199 unordered = g_list_reverse (unordered);
4200 if (acfg->method_order)
4201 g_list_last (acfg->method_order)->next = unordered;
4203 acfg->method_order = unordered;
4206 /* Used by the LLVM backend */
4208 mono_aot_get_got_offset (MonoJumpInfo *ji)
4210 return get_got_offset (llvm_acfg, ji);
4214 mono_aot_get_method_name (MonoCompile *cfg)
4216 guint32 method_index = get_method_index (llvm_acfg, cfg->orig_method);
4218 /* LLVM converts these to .Lm_%x */
4219 return g_strdup_printf ("m_%x", method_index);
4223 mono_aot_get_method_debug_name (MonoCompile *cfg)
4225 return get_debug_sym (cfg->orig_method, "", llvm_acfg->method_label_hash);
4229 mono_aot_get_plt_symbol (MonoJumpInfoType type, gconstpointer data)
4231 MonoJumpInfo *ji = mono_mempool_alloc (llvm_acfg->mempool, sizeof (MonoJumpInfo));
4235 ji->data.target = data;
4237 if (!can_encode_patch (llvm_acfg, ji))
4240 offset = get_plt_offset (llvm_acfg, ji);
4242 return g_strdup_printf (".Lp_%d", offset);
4246 mono_aot_patch_info_dup (MonoJumpInfo* ji)
4250 mono_acfg_lock (llvm_acfg);
4251 res = mono_patch_info_dup_mp (llvm_acfg->mempool, ji);
4252 mono_acfg_unlock (llvm_acfg);
4262 * Emit the LLVM code into an LLVM bytecode file, and compile it using the LLVM
4266 emit_llvm_file (MonoAotCompile *acfg)
4268 char *command, *opts;
4270 MonoJumpInfo *patch_info;
4273 * When using LLVM, we let llvm emit the got since the LLVM IL needs to refer
4277 /* Compute the final size of the got */
4278 for (i = 0; i < acfg->nmethods; ++i) {
4279 if (acfg->cfgs [i]) {
4280 for (patch_info = acfg->cfgs [i]->patch_info; patch_info; patch_info = patch_info->next) {
4281 if (patch_info->type != MONO_PATCH_INFO_NONE) {
4282 if (!is_plt_patch (patch_info))
4283 get_got_offset (acfg, patch_info);
4285 get_plt_offset (acfg, patch_info);
4290 acfg->final_got_size = acfg->got_offset + acfg->plt_offset;
4292 mono_llvm_emit_aot_module ("temp.bc", acfg->final_got_size);
4295 * FIXME: Experiment with adding optimizations, the -std-compile-opts set takes
4296 * a lot of time, and doesn't seem to save much space.
4297 * The following optimizations cannot be enabled:
4300 opts = g_strdup ("-instcombine -simplifycfg");
4302 command = g_strdup_printf ("opt -f %s -o temp.opt.bc temp.bc", opts);
4303 printf ("Executing opt: %s\n", command);
4304 if (system (command) != 0) {
4310 //command = g_strdup_printf ("llc -march=arm -mtriple=arm-linux-gnueabi -f -relocation-model=pic -unwind-tables temp.bc");
4311 command = g_strdup_printf ("llc -f -relocation-model=pic -unwind-tables -o temp.s temp.opt.bc");
4312 printf ("Executing llc: %s\n", command);
4314 if (system (command) != 0) {
4321 emit_code (MonoAotCompile *acfg)
4327 #if defined(TARGET_POWERPC64)
4328 sprintf (symbol, ".Lgot_addr");
4329 emit_section_change (acfg, ".text", 0);
4330 emit_alignment (acfg, 8);
4331 emit_label (acfg, symbol);
4332 emit_pointer (acfg, acfg->got_symbol);
4336 sprintf (symbol, "methods");
4337 emit_section_change (acfg, ".text", 0);
4338 emit_global (acfg, symbol, TRUE);
4339 emit_alignment (acfg, 8);
4340 emit_label (acfg, symbol);
4344 * Emit some padding so the local symbol for the first method doesn't have the
4345 * same address as 'methods'.
4347 emit_zero_bytes (acfg, 16);
4349 for (l = acfg->method_order; l != NULL; l = l->next) {
4350 i = GPOINTER_TO_UINT (l->data);
4352 if (acfg->cfgs [i]) {
4353 if (acfg->cfgs [i]->compile_llvm)
4354 acfg->stats.llvm_count ++;
4356 emit_method_code (acfg, acfg->cfgs [i]);
4360 sprintf (symbol, "methods_end");
4361 emit_section_change (acfg, ".text", 0);
4362 emit_global (acfg, symbol, FALSE);
4363 emit_alignment (acfg, 8);
4364 emit_label (acfg, symbol);
4366 sprintf (symbol, "code_offsets");
4367 emit_section_change (acfg, ".text", 1);
4368 emit_global (acfg, symbol, FALSE);
4369 emit_alignment (acfg, 8);
4370 emit_label (acfg, symbol);
4372 acfg->stats.offsets_size += acfg->nmethods * 4;
4374 for (i = 0; i < acfg->nmethods; ++i) {
4375 if (acfg->cfgs [i]) {
4376 sprintf (symbol, "%sm_%x", acfg->temp_prefix, i);
4377 emit_symbol_diff (acfg, symbol, "methods", 0);
4379 emit_int32 (acfg, 0xffffffff);
4386 emit_info (MonoAotCompile *acfg)
4393 offsets = g_new0 (gint32, acfg->nmethods);
4395 for (l = acfg->method_order; l != NULL; l = l->next) {
4396 i = GPOINTER_TO_UINT (l->data);
4398 if (acfg->cfgs [i]) {
4399 emit_method_info (acfg, acfg->cfgs [i]);
4400 offsets [i] = acfg->cfgs [i]->method_info_offset;
4406 sprintf (symbol, "method_info_offsets");
4407 emit_section_change (acfg, ".text", 1);
4408 emit_global (acfg, symbol, FALSE);
4409 emit_alignment (acfg, 8);
4410 emit_label (acfg, symbol);
4412 acfg->stats.offsets_size += emit_offset_table (acfg, acfg->nmethods, 10, offsets);
4417 #endif /* #if !defined(DISABLE_AOT) && !defined(DISABLE_JIT) */
4419 #define rot(x,k) (((x)<<(k)) | ((x)>>(32-(k))))
4420 #define mix(a,b,c) { \
4421 a -= c; a ^= rot(c, 4); c += b; \
4422 b -= a; b ^= rot(a, 6); a += c; \
4423 c -= b; c ^= rot(b, 8); b += a; \
4424 a -= c; a ^= rot(c,16); c += b; \
4425 b -= a; b ^= rot(a,19); a += c; \
4426 c -= b; c ^= rot(b, 4); b += a; \
4428 #define final(a,b,c) { \
4429 c ^= b; c -= rot(b,14); \
4430 a ^= c; a -= rot(c,11); \
4431 b ^= a; b -= rot(a,25); \
4432 c ^= b; c -= rot(b,16); \
4433 a ^= c; a -= rot(c,4); \
4434 b ^= a; b -= rot(a,14); \
4435 c ^= b; c -= rot(b,24); \
4439 mono_aot_type_hash (MonoType *t1)
4441 guint hash = t1->type;
4443 hash |= t1->byref << 6; /* do not collide with t1->type values */
4445 case MONO_TYPE_VALUETYPE:
4446 case MONO_TYPE_CLASS:
4447 case MONO_TYPE_SZARRAY:
4448 /* check if the distribution is good enough */
4449 return ((hash << 5) - hash) ^ mono_metadata_str_hash (t1->data.klass->name);
4451 return ((hash << 5) - hash) ^ mono_metadata_type_hash (t1->data.type);
4452 case MONO_TYPE_ARRAY:
4453 return ((hash << 5) - hash) ^ mono_metadata_type_hash (&t1->data.array->eklass->byval_arg);
4454 case MONO_TYPE_GENERICINST:
4455 return ((hash << 5) - hash) ^ 0;
4461 * mono_aot_method_hash:
4463 * Return a hash code for methods which only depends on metadata.
4466 mono_aot_method_hash (MonoMethod *method)
4468 MonoMethodSignature *sig;
4472 guint32 *hashes_start, *hashes;
4475 /* Similar to the hash in mono_method_get_imt_slot () */
4477 sig = mono_method_signature (method);
4479 hashes_count = sig->param_count + 5;
4480 hashes_start = malloc (hashes_count * sizeof (guint32));
4481 hashes = hashes_start;
4483 /* Some wrappers are assigned to random classes */
4484 if (!method->wrapper_type || method->wrapper_type == MONO_WRAPPER_REMOTING_INVOKE_WITH_CHECK)
4485 klass = method->klass;
4487 klass = mono_defaults.object_class;
4489 if (!method->wrapper_type) {
4490 char *full_name = mono_type_full_name (&klass->byval_arg);
4492 hashes [0] = mono_metadata_str_hash (full_name);
4496 hashes [0] = mono_metadata_str_hash (klass->name);
4497 hashes [1] = mono_metadata_str_hash (klass->name_space);
4499 if (method->wrapper_type == MONO_WRAPPER_STFLD || method->wrapper_type == MONO_WRAPPER_LDFLD || method->wrapper_type == MONO_WRAPPER_LDFLDA)
4500 /* The method name includes a stringified pointer */
4503 hashes [2] = mono_metadata_str_hash (method->name);
4504 hashes [3] = method->wrapper_type;
4505 hashes [4] = mono_aot_type_hash (sig->ret);
4506 for (i = 0; i < sig->param_count; i++) {
4507 hashes [5 + i] = mono_aot_type_hash (sig->params [i]);
4510 /* Setup internal state */
4511 a = b = c = 0xdeadbeef + (((guint32)hashes_count)<<2);
4513 /* Handle most of the hashes */
4514 while (hashes_count > 3) {
4523 /* Handle the last 3 hashes (all the case statements fall through) */
4524 switch (hashes_count) {
4525 case 3 : c += hashes [2];
4526 case 2 : b += hashes [1];
4527 case 1 : a += hashes [0];
4529 case 0: /* nothing left to add */
4533 free (hashes_start);
4542 * mono_aot_wrapper_name:
4544 * Return a string which uniqely identifies the given wrapper method.
4547 mono_aot_wrapper_name (MonoMethod *method)
4549 char *name, *tmpsig, *klass_desc;
4551 tmpsig = mono_signature_get_desc (mono_method_signature (method), TRUE);
4553 switch (method->wrapper_type) {
4554 case MONO_WRAPPER_RUNTIME_INVOKE:
4555 if (!strcmp (method->name, "runtime_invoke_dynamic"))
4556 name = g_strdup_printf ("(wrapper runtime-invoke-dynamic)");
4558 name = g_strdup_printf ("%s (%s)", method->name, tmpsig);
4560 case MONO_WRAPPER_DELEGATE_INVOKE:
4561 case MONO_WRAPPER_DELEGATE_BEGIN_INVOKE:
4562 case MONO_WRAPPER_DELEGATE_END_INVOKE:
4563 /* This is a hack to work around the fact that these wrappers get assigned to some random class */
4564 name = g_strdup_printf ("%s (%s)", method->name, tmpsig);
4567 klass_desc = mono_type_full_name (&method->klass->byval_arg);
4568 name = g_strdup_printf ("%s:%s (%s)", klass_desc, method->name, tmpsig);
4569 g_free (klass_desc);
4579 * mono_aot_get_array_helper_from_wrapper;
4581 * Get the helper method in Array called by an array wrapper method.
4584 mono_aot_get_array_helper_from_wrapper (MonoMethod *method)
4588 MonoGenericContext ctx;
4589 MonoType *args [16];
4590 char *mname, *iname, *s, *s2, *helper_name = NULL;
4592 prefix = "System.Collections.Generic";
4593 s = g_strdup_printf ("%s", method->name + strlen (prefix) + 1);
4594 s2 = strstr (s, "`1.");
4600 //printf ("X: %s %s\n", iname, mname);
4602 if (!strcmp (iname, "IList"))
4603 helper_name = g_strdup_printf ("InternalArray__%s", mname);
4605 helper_name = g_strdup_printf ("InternalArray__%s_%s", iname, mname);
4606 m = mono_class_get_method_from_name (mono_defaults.array_class, helper_name, mono_method_signature (method)->param_count);
4608 g_free (helper_name);
4611 if (m->is_generic) {
4612 memset (&ctx, 0, sizeof (ctx));
4613 args [0] = &method->klass->element_class->byval_arg;
4614 ctx.method_inst = mono_metadata_get_generic_inst (1, args);
4615 m = mono_class_inflate_generic_method (m, &ctx);
4622 * mono_aot_tramp_info_create:
4624 * Create a MonoAotTrampInfo structure from the arguments.
4627 mono_aot_tramp_info_create (const char *name, guint8 *code, guint32 code_size)
4629 MonoAotTrampInfo *info = g_new0 (MonoAotTrampInfo, 1);
4631 info->name = (char*)name;
4633 info->code_size = code_size;
4638 #if !defined(DISABLE_AOT) && !defined(DISABLE_JIT)
4640 typedef struct HashEntry {
4641 guint32 key, value, index;
4642 struct HashEntry *next;
4646 * emit_extra_methods:
4648 * Emit methods which are not in the METHOD table, like wrappers.
4651 emit_extra_methods (MonoAotCompile *acfg)
4653 int i, table_size, buf_size;
4656 guint32 *info_offsets;
4659 HashEntry *entry, *new_entry;
4660 int nmethods, max_chain_length;
4663 info_offsets = g_new0 (guint32, acfg->extra_methods->len);
4665 /* Emit method info */
4667 for (i = 0; i < acfg->extra_methods->len; ++i) {
4668 MonoMethod *method = g_ptr_array_index (acfg->extra_methods, i);
4669 MonoCompile *cfg = g_hash_table_lookup (acfg->method_to_cfg, method);
4676 p = buf = g_malloc (buf_size);
4681 if (method->wrapper_type) {
4683 * We encode some wrappers using their name, since encoding them
4684 * directly would be difficult. This also avoids creating the wrapper
4685 * methods at runtime, since they are not needed anyway.
4687 switch (method->wrapper_type) {
4688 case MONO_WRAPPER_REMOTING_INVOKE_WITH_CHECK:
4689 case MONO_WRAPPER_SYNCHRONIZED:
4690 /* encode_method_ref () can handle these */
4692 case MONO_WRAPPER_RUNTIME_INVOKE:
4693 if (mono_marshal_method_from_wrapper (method) != method && !strstr (method->name, "virtual"))
4694 /* Direct wrapper, encode normally */
4698 name = mono_aot_wrapper_name (method);
4704 encode_value (1, p, &p);
4705 encode_value (method->wrapper_type, p, &p);
4706 strcpy ((char*)p, name);
4707 p += strlen (name ) + 1;
4710 encode_value (0, p, &p);
4711 encode_method_ref (acfg, method, p, &p);
4714 g_assert ((p - buf) < buf_size);
4716 info_offsets [i] = add_to_blob (acfg, buf, p - buf);
4721 * Construct a chained hash table for mapping indexes in extra_method_info to
4724 table_size = g_spaced_primes_closest ((int)(nmethods * 1.5));
4725 table = g_ptr_array_sized_new (table_size);
4726 for (i = 0; i < table_size; ++i)
4727 g_ptr_array_add (table, NULL);
4728 chain_lengths = g_new0 (int, table_size);
4729 max_chain_length = 0;
4730 for (i = 0; i < acfg->extra_methods->len; ++i) {
4731 MonoMethod *method = g_ptr_array_index (acfg->extra_methods, i);
4732 MonoCompile *cfg = g_hash_table_lookup (acfg->method_to_cfg, method);
4738 key = info_offsets [i];
4739 value = get_method_index (acfg, method);
4741 hash = mono_aot_method_hash (method) % table_size;
4743 chain_lengths [hash] ++;
4744 max_chain_length = MAX (max_chain_length, chain_lengths [hash]);
4746 new_entry = mono_mempool_alloc0 (acfg->mempool, sizeof (HashEntry));
4747 new_entry->key = key;
4748 new_entry->value = value;
4750 entry = g_ptr_array_index (table, hash);
4751 if (entry == NULL) {
4752 new_entry->index = hash;
4753 g_ptr_array_index (table, hash) = new_entry;
4756 entry = entry->next;
4758 entry->next = new_entry;
4759 new_entry->index = table->len;
4760 g_ptr_array_add (table, new_entry);
4764 //printf ("MAX: %d\n", max_chain_length);
4766 /* Emit the table */
4767 sprintf (symbol, "extra_method_table");
4768 emit_section_change (acfg, ".text", 0);
4769 emit_global (acfg, symbol, FALSE);
4770 emit_alignment (acfg, 8);
4771 emit_label (acfg, symbol);
4773 emit_int32 (acfg, table_size);
4774 for (i = 0; i < table->len; ++i) {
4775 HashEntry *entry = g_ptr_array_index (table, i);
4777 if (entry == NULL) {
4778 emit_int32 (acfg, 0);
4779 emit_int32 (acfg, 0);
4780 emit_int32 (acfg, 0);
4782 //g_assert (entry->key > 0);
4783 emit_int32 (acfg, entry->key);
4784 emit_int32 (acfg, entry->value);
4786 emit_int32 (acfg, entry->next->index);
4788 emit_int32 (acfg, 0);
4793 * Emit a table reverse mapping method indexes to their index in extra_method_info.
4794 * This is used by mono_aot_find_jit_info ().
4796 sprintf (symbol, "extra_method_info_offsets");
4797 emit_section_change (acfg, ".text", 0);
4798 emit_global (acfg, symbol, FALSE);
4799 emit_alignment (acfg, 8);
4800 emit_label (acfg, symbol);
4802 emit_int32 (acfg, acfg->extra_methods->len);
4803 for (i = 0; i < acfg->extra_methods->len; ++i) {
4804 MonoMethod *method = g_ptr_array_index (acfg->extra_methods, i);
4806 emit_int32 (acfg, get_method_index (acfg, method));
4807 emit_int32 (acfg, info_offsets [i]);
4812 emit_exception_info (MonoAotCompile *acfg)
4818 offsets = g_new0 (gint32, acfg->nmethods);
4819 for (i = 0; i < acfg->nmethods; ++i) {
4820 if (acfg->cfgs [i]) {
4821 emit_exception_debug_info (acfg, acfg->cfgs [i]);
4822 offsets [i] = acfg->cfgs [i]->ex_info_offset;
4828 sprintf (symbol, "ex_info_offsets");
4829 emit_section_change (acfg, ".text", 1);
4830 emit_global (acfg, symbol, FALSE);
4831 emit_alignment (acfg, 8);
4832 emit_label (acfg, symbol);
4834 acfg->stats.offsets_size += emit_offset_table (acfg, acfg->nmethods, 10, offsets);
4839 emit_unwind_info (MonoAotCompile *acfg)
4845 * The unwind info contains a lot of duplicates so we emit each unique
4846 * entry once, and only store the offset from the start of the table in the
4850 sprintf (symbol, "unwind_info");
4851 emit_section_change (acfg, ".text", 1);
4852 emit_alignment (acfg, 8);
4853 emit_label (acfg, symbol);
4854 emit_global (acfg, symbol, FALSE);
4856 for (i = 0; i < acfg->unwind_ops->len; ++i) {
4857 guint32 index = GPOINTER_TO_UINT (g_ptr_array_index (acfg->unwind_ops, i));
4858 guint8 *unwind_info;
4859 guint32 unwind_info_len;
4863 unwind_info = mono_get_cached_unwind_info (index, &unwind_info_len);
4866 encode_value (unwind_info_len, p, &p);
4867 emit_bytes (acfg, buf, p - buf);
4868 emit_bytes (acfg, unwind_info, unwind_info_len);
4870 acfg->stats.unwind_info_size += (p - buf) + unwind_info_len;
4875 emit_class_info (MonoAotCompile *acfg)
4881 offsets = g_new0 (gint32, acfg->image->tables [MONO_TABLE_TYPEDEF].rows);
4882 for (i = 0; i < acfg->image->tables [MONO_TABLE_TYPEDEF].rows; ++i)
4883 offsets [i] = emit_klass_info (acfg, MONO_TOKEN_TYPE_DEF | (i + 1));
4885 sprintf (symbol, "class_info_offsets");
4886 emit_section_change (acfg, ".text", 1);
4887 emit_global (acfg, symbol, FALSE);
4888 emit_alignment (acfg, 8);
4889 emit_label (acfg, symbol);
4891 acfg->stats.offsets_size += emit_offset_table (acfg, acfg->image->tables [MONO_TABLE_TYPEDEF].rows, 10, offsets);
4895 typedef struct ClassNameTableEntry {
4896 guint32 token, index;
4897 struct ClassNameTableEntry *next;
4898 } ClassNameTableEntry;
4901 emit_class_name_table (MonoAotCompile *acfg)
4904 guint32 token, hash;
4909 ClassNameTableEntry *entry, *new_entry;
4912 * Construct a chained hash table for mapping class names to typedef tokens.
4914 table_size = g_spaced_primes_closest ((int)(acfg->image->tables [MONO_TABLE_TYPEDEF].rows * 1.5));
4915 table = g_ptr_array_sized_new (table_size);
4916 for (i = 0; i < table_size; ++i)
4917 g_ptr_array_add (table, NULL);
4918 for (i = 0; i < acfg->image->tables [MONO_TABLE_TYPEDEF].rows; ++i) {
4919 token = MONO_TOKEN_TYPE_DEF | (i + 1);
4920 klass = mono_class_get (acfg->image, token);
4921 full_name = mono_type_get_name_full (mono_class_get_type (klass), MONO_TYPE_NAME_FORMAT_FULL_NAME);
4922 hash = mono_metadata_str_hash (full_name) % table_size;
4925 /* FIXME: Allocate from the mempool */
4926 new_entry = g_new0 (ClassNameTableEntry, 1);
4927 new_entry->token = token;
4929 entry = g_ptr_array_index (table, hash);
4930 if (entry == NULL) {
4931 new_entry->index = hash;
4932 g_ptr_array_index (table, hash) = new_entry;
4935 entry = entry->next;
4937 entry->next = new_entry;
4938 new_entry->index = table->len;
4939 g_ptr_array_add (table, new_entry);
4943 /* Emit the table */
4944 sprintf (symbol, "class_name_table");
4945 emit_section_change (acfg, ".text", 0);
4946 emit_global (acfg, symbol, FALSE);
4947 emit_alignment (acfg, 8);
4948 emit_label (acfg, symbol);
4950 /* FIXME: Optimize memory usage */
4951 g_assert (table_size < 65000);
4952 emit_int16 (acfg, table_size);
4953 g_assert (table->len < 65000);
4954 for (i = 0; i < table->len; ++i) {
4955 ClassNameTableEntry *entry = g_ptr_array_index (table, i);
4957 if (entry == NULL) {
4958 emit_int16 (acfg, 0);
4959 emit_int16 (acfg, 0);
4961 emit_int16 (acfg, mono_metadata_token_index (entry->token));
4963 emit_int16 (acfg, entry->next->index);
4965 emit_int16 (acfg, 0);
4971 emit_image_table (MonoAotCompile *acfg)
4977 * The image table is small but referenced in a lot of places.
4978 * So we emit it at once, and reference its elements by an index.
4981 sprintf (symbol, "mono_image_table");
4982 emit_section_change (acfg, ".text", 1);
4983 emit_global (acfg, symbol, FALSE);
4984 emit_alignment (acfg, 8);
4985 emit_label (acfg, symbol);
4987 emit_int32 (acfg, acfg->image_table->len);
4988 for (i = 0; i < acfg->image_table->len; i++) {
4989 MonoImage *image = (MonoImage*)g_ptr_array_index (acfg->image_table, i);
4990 MonoAssemblyName *aname = &image->assembly->aname;
4992 /* FIXME: Support multi-module assemblies */
4993 g_assert (image->assembly->image == image);
4995 emit_string (acfg, image->assembly_name);
4996 emit_string (acfg, image->guid);
4997 emit_string (acfg, aname->culture ? aname->culture : "");
4998 emit_string (acfg, (const char*)aname->public_key_token);
5000 emit_alignment (acfg, 8);
5001 emit_int32 (acfg, aname->flags);
5002 emit_int32 (acfg, aname->major);
5003 emit_int32 (acfg, aname->minor);
5004 emit_int32 (acfg, aname->build);
5005 emit_int32 (acfg, aname->revision);
5010 emit_got_info (MonoAotCompile *acfg)
5013 int i, first_plt_got_patch, buf_size;
5015 guint32 *got_info_offsets;
5017 /* Add the patches needed by the PLT to the GOT */
5018 acfg->plt_got_offset_base = acfg->got_offset;
5019 first_plt_got_patch = acfg->got_patches->len;
5020 for (i = 1; i < acfg->plt_offset; ++i) {
5021 MonoJumpInfo *patch_info = g_hash_table_lookup (acfg->plt_offset_to_patch, GUINT_TO_POINTER (i));
5023 g_ptr_array_add (acfg->got_patches, patch_info);
5026 acfg->got_offset += acfg->plt_offset;
5030 * - optimize offsets table.
5031 * - reduce number of exported symbols.
5032 * - emit info for a klass only once.
5033 * - determine when a method uses a GOT slot which is guaranteed to be already
5035 * - clean up and document the code.
5036 * - use String.Empty in class libs.
5039 /* Encode info required to decode shared GOT entries */
5040 buf_size = acfg->got_patches->len * 64;
5041 p = buf = mono_mempool_alloc (acfg->mempool, buf_size);
5042 got_info_offsets = mono_mempool_alloc (acfg->mempool, acfg->got_patches->len * sizeof (guint32));
5043 acfg->plt_got_info_offsets = mono_mempool_alloc (acfg->mempool, acfg->plt_offset * sizeof (guint32));
5045 if (acfg->plt_offset)
5046 acfg->plt_got_info_offsets [0] = 0;
5047 for (i = 0; i < acfg->got_patches->len; ++i) {
5048 MonoJumpInfo *ji = g_ptr_array_index (acfg->got_patches, i);
5052 encode_value (ji->type, p, &p);
5053 encode_patch (acfg, ji, p, &p);
5055 g_assert (p - buf <= buf_size);
5056 got_info_offsets [i] = add_to_blob (acfg, buf, p - buf);
5058 if (i >= first_plt_got_patch)
5059 acfg->plt_got_info_offsets [i - first_plt_got_patch + 1] = got_info_offsets [i];
5060 acfg->stats.got_info_size += p - buf;
5063 /* Emit got_info_offsets table */
5064 sprintf (symbol, "got_info_offsets");
5065 emit_section_change (acfg, ".text", 1);
5066 emit_global (acfg, symbol, FALSE);
5067 emit_alignment (acfg, 8);
5068 emit_label (acfg, symbol);
5070 /* No need to emit offsets for the got plt entries, the plt embeds them directly */
5071 acfg->stats.offsets_size += emit_offset_table (acfg, first_plt_got_patch, 10, (gint32*)got_info_offsets);
5075 emit_got (MonoAotCompile *acfg)
5080 /* Don't make GOT global so accesses to it don't need relocations */
5081 sprintf (symbol, "%s", acfg->got_symbol);
5082 emit_section_change (acfg, ".bss", 0);
5083 emit_alignment (acfg, 8);
5084 emit_local_symbol (acfg, symbol, "got_end", FALSE);
5085 emit_label (acfg, symbol);
5086 if (acfg->got_offset > 0)
5087 emit_zero_bytes (acfg, (int)(acfg->got_offset * sizeof (gpointer)));
5089 sprintf (symbol, "got_end");
5090 emit_label (acfg, symbol);
5093 sprintf (symbol, "mono_aot_got_addr");
5094 emit_section_change (acfg, ".data", 0);
5095 emit_global (acfg, symbol, FALSE);
5096 emit_alignment (acfg, 8);
5097 emit_label (acfg, symbol);
5098 emit_pointer (acfg, acfg->got_symbol);
5101 typedef struct GlobalsTableEntry {
5102 guint32 value, index;
5103 struct GlobalsTableEntry *next;
5104 } GlobalsTableEntry;
5107 emit_globals_table (MonoAotCompile *acfg)
5113 GlobalsTableEntry *entry, *new_entry;
5116 * Construct a chained hash table for mapping global names to their index in
5117 * the globals table.
5119 table_size = g_spaced_primes_closest ((int)(acfg->globals->len * 1.5));
5120 table = g_ptr_array_sized_new (table_size);
5121 for (i = 0; i < table_size; ++i)
5122 g_ptr_array_add (table, NULL);
5123 for (i = 0; i < acfg->globals->len; ++i) {
5124 char *name = g_ptr_array_index (acfg->globals, i);
5126 hash = mono_metadata_str_hash (name) % table_size;
5128 /* FIXME: Allocate from the mempool */
5129 new_entry = g_new0 (GlobalsTableEntry, 1);
5130 new_entry->value = i;
5132 entry = g_ptr_array_index (table, hash);
5133 if (entry == NULL) {
5134 new_entry->index = hash;
5135 g_ptr_array_index (table, hash) = new_entry;
5138 entry = entry->next;
5140 entry->next = new_entry;
5141 new_entry->index = table->len;
5142 g_ptr_array_add (table, new_entry);
5146 /* Emit the table */
5147 sprintf (symbol, ".Lglobals_hash");
5148 emit_section_change (acfg, ".text", 0);
5149 emit_alignment (acfg, 8);
5150 emit_label (acfg, symbol);
5152 /* FIXME: Optimize memory usage */
5153 g_assert (table_size < 65000);
5154 emit_int16 (acfg, table_size);
5155 for (i = 0; i < table->len; ++i) {
5156 GlobalsTableEntry *entry = g_ptr_array_index (table, i);
5158 if (entry == NULL) {
5159 emit_int16 (acfg, 0);
5160 emit_int16 (acfg, 0);
5162 emit_int16 (acfg, entry->value + 1);
5164 emit_int16 (acfg, entry->next->index);
5166 emit_int16 (acfg, 0);
5170 /* Emit the names */
5171 for (i = 0; i < acfg->globals->len; ++i) {
5172 char *name = g_ptr_array_index (acfg->globals, i);
5174 sprintf (symbol, "name_%d", i);
5175 emit_section_change (acfg, ".text", 1);
5176 emit_label (acfg, symbol);
5177 emit_string (acfg, name);
5180 /* Emit the globals table */
5181 sprintf (symbol, ".Lglobals");
5182 emit_section_change (acfg, ".data", 0);
5183 /* This is not a global, since it is accessed by the init function */
5184 emit_alignment (acfg, 8);
5185 emit_label (acfg, symbol);
5187 sprintf (symbol, "%sglobals_hash", acfg->temp_prefix);
5188 emit_pointer (acfg, symbol);
5190 for (i = 0; i < acfg->globals->len; ++i) {
5191 char *name = g_ptr_array_index (acfg->globals, i);
5193 sprintf (symbol, "name_%d", i);
5194 emit_pointer (acfg, symbol);
5196 sprintf (symbol, "%s", name);
5197 emit_pointer (acfg, symbol);
5199 /* Null terminate the table */
5200 emit_int32 (acfg, 0);
5201 emit_int32 (acfg, 0);
5205 emit_globals (MonoAotCompile *acfg)
5209 emit_string_symbol (acfg, "mono_assembly_guid" , acfg->image->guid);
5211 emit_string_symbol (acfg, "mono_aot_version", MONO_AOT_FILE_VERSION);
5213 if (acfg->aot_opts.bind_to_runtime_version) {
5214 build_info = mono_get_runtime_build_info ();
5215 emit_string_symbol (acfg, "mono_runtime_version", build_info);
5216 g_free (build_info);
5218 emit_string_symbol (acfg, "mono_runtime_version", "");
5222 * When static linking, we emit a global which will point to the symbol table.
5224 if (acfg->aot_opts.static_link) {
5228 /* Emit a string holding the assembly name */
5229 emit_string_symbol (acfg, "mono_aot_assembly_name", acfg->image->assembly->aname.name);
5231 emit_globals_table (acfg);
5234 * Emit a global symbol which can be passed by an embedding app to
5235 * mono_aot_register_module ().
5237 #if defined(__MACH__)
5238 sprintf (symbol, "_mono_aot_module_%s_info", acfg->image->assembly->aname.name);
5240 sprintf (symbol, "mono_aot_module_%s_info", acfg->image->assembly->aname.name);
5243 /* Get rid of characters which cannot occur in symbols */
5245 for (p = symbol; *p; ++p) {
5246 if (!(isalnum (*p) || *p == '_'))
5249 acfg->static_linking_symbol = g_strdup (symbol);
5250 emit_global_inner (acfg, symbol, FALSE);
5251 emit_alignment (acfg, 8);
5252 emit_label (acfg, symbol);
5253 sprintf (symbol, "%sglobals", acfg->temp_prefix);
5254 emit_pointer (acfg, symbol);
5259 emit_autoreg (MonoAotCompile *acfg)
5264 * Emit a function into the .ctor section which will be called by the ELF
5265 * loader to register this module with the runtime.
5267 if (! (!acfg->use_bin_writer && acfg->aot_opts.static_link && acfg->aot_opts.autoreg))
5270 symbol = g_strdup_printf ("_%s_autoreg", acfg->static_linking_symbol);
5272 arch_emit_autoreg (acfg, symbol);
5278 emit_mem_end (MonoAotCompile *acfg)
5282 sprintf (symbol, "mem_end");
5283 emit_section_change (acfg, ".text", 1);
5284 emit_global (acfg, symbol, FALSE);
5285 emit_alignment (acfg, 8);
5286 emit_label (acfg, symbol);
5290 * Emit a structure containing all the information not stored elsewhere.
5293 emit_file_info (MonoAotCompile *acfg)
5298 sprintf (symbol, "mono_aot_file_info");
5299 emit_section_change (acfg, ".data", 0);
5300 emit_alignment (acfg, 8);
5301 emit_label (acfg, symbol);
5302 emit_global (acfg, symbol, FALSE);
5304 /* The data emitted here must match MonoAotFileInfo in aot-runtime.c. */
5305 emit_int32 (acfg, acfg->plt_got_offset_base);
5306 emit_int32 (acfg, (int)(acfg->got_offset * sizeof (gpointer)));
5307 emit_int32 (acfg, acfg->plt_offset);
5308 emit_int32 (acfg, acfg->nmethods);
5309 emit_int32 (acfg, acfg->flags);
5310 emit_int32 (acfg, acfg->opts);
5312 for (i = 0; i < MONO_AOT_TRAMP_NUM; ++i)
5313 emit_int32 (acfg, acfg->num_trampolines [i]);
5314 for (i = 0; i < MONO_AOT_TRAMP_NUM; ++i)
5315 emit_int32 (acfg, acfg->trampoline_got_offset_base [i]);
5316 for (i = 0; i < MONO_AOT_TRAMP_NUM; ++i)
5317 emit_int32 (acfg, acfg->trampoline_size [i]);
5321 emit_blob (MonoAotCompile *acfg)
5325 sprintf (symbol, "blob");
5326 emit_section_change (acfg, ".text", 1);
5327 emit_global (acfg, symbol, FALSE);
5328 emit_alignment (acfg, 8);
5329 emit_label (acfg, symbol);
5331 emit_bytes (acfg, (guint8*)acfg->blob.data, acfg->blob.index);
5335 emit_dwarf_info (MonoAotCompile *acfg)
5337 #ifdef EMIT_DWARF_INFO
5339 char symbol [128], symbol2 [128];
5341 /* DIEs for methods */
5342 for (i = 0; i < acfg->nmethods; ++i) {
5343 MonoCompile *cfg = acfg->cfgs [i];
5348 // FIXME: LLVM doesn't define .Lme_...
5349 if (cfg->compile_llvm)
5352 sprintf (symbol, "%sm_%x", acfg->temp_prefix, i);
5353 sprintf (symbol2, "%sme_%x", acfg->temp_prefix, i);
5355 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 ()));
5361 collect_methods (MonoAotCompile *acfg)
5364 MonoImage *image = acfg->image;
5366 /* Collect methods */
5367 for (i = 0; i < image->tables [MONO_TABLE_METHOD].rows; ++i) {
5369 guint32 token = MONO_TOKEN_METHOD_DEF | (i + 1);
5371 method = mono_get_method (acfg->image, token, NULL);
5374 printf ("Failed to load method 0x%x from '%s'.\n", token, image->name);
5378 /* Load all methods eagerly to skip the slower lazy loading code */
5379 mono_class_setup_methods (method->klass);
5381 if (acfg->aot_opts.full_aot && method->iflags & METHOD_IMPL_ATTRIBUTE_INTERNAL_CALL) {
5382 /* Compile the wrapper instead */
5383 /* We do this here instead of add_wrappers () because it is easy to do it here */
5384 MonoMethod *wrapper = mono_marshal_get_native_wrapper (method, check_for_pending_exc, TRUE);
5388 /* FIXME: Some mscorlib methods don't have debug info */
5390 if (acfg->aot_opts.soft_debug && !method->wrapper_type) {
5391 if (!((method->flags & METHOD_ATTRIBUTE_PINVOKE_IMPL) ||
5392 (method->iflags & METHOD_IMPL_ATTRIBUTE_RUNTIME) ||
5393 (method->flags & METHOD_ATTRIBUTE_ABSTRACT) ||
5394 (method->iflags & METHOD_IMPL_ATTRIBUTE_INTERNAL_CALL))) {
5395 if (!mono_debug_lookup_method (method)) {
5396 fprintf (stderr, "Method %s has no debug info, probably the .mdb file for the assembly is missing.\n", mono_method_full_name (method, TRUE));
5403 /* Since we add the normal methods first, their index will be equal to their zero based token index */
5404 add_method_with_index (acfg, method, i, FALSE);
5405 acfg->method_index ++;
5408 add_generic_instances (acfg);
5410 if (acfg->aot_opts.full_aot)
5411 add_wrappers (acfg);
5415 compile_methods (MonoAotCompile *acfg)
5419 if (acfg->aot_opts.nthreads > 0) {
5424 gpointer *user_data;
5425 MonoMethod **methods;
5427 methods_len = acfg->methods->len;
5429 len = acfg->methods->len / acfg->aot_opts.nthreads;
5432 * Partition the list of methods into fragments, and hand it to threads to
5435 threads = g_ptr_array_new ();
5436 /* Make a copy since acfg->methods is modified by compile_method () */
5437 methods = g_new0 (MonoMethod*, methods_len);
5438 //memcpy (methods, g_ptr_array_index (acfg->methods, 0), sizeof (MonoMethod*) * methods_len);
5439 for (i = 0; i < methods_len; ++i)
5440 methods [i] = g_ptr_array_index (acfg->methods, i);
5442 while (i < methods_len) {
5443 frag = g_ptr_array_new ();
5444 for (j = 0; j < len; ++j) {
5445 if (i < methods_len) {
5446 g_ptr_array_add (frag, methods [i]);
5451 user_data = g_new0 (gpointer, 3);
5452 user_data [0] = mono_domain_get ();
5453 user_data [1] = acfg;
5454 user_data [2] = frag;
5456 handle = mono_create_thread (NULL, 0, (gpointer)compile_thread_main, user_data, 0, NULL);
5457 g_ptr_array_add (threads, handle);
5461 for (i = 0; i < threads->len; ++i) {
5462 WaitForSingleObjectEx (g_ptr_array_index (threads, i), INFINITE, FALSE);
5468 /* Compile methods added by compile_method () or all methods if nthreads == 0 */
5469 for (i = methods_len; i < acfg->methods->len; ++i) {
5470 /* This can new methods to acfg->methods */
5471 compile_method (acfg, g_ptr_array_index (acfg->methods, i));
5476 compile_asm (MonoAotCompile *acfg)
5478 char *command, *objfile;
5479 char *outfile_name, *tmp_outfile_name;
5480 const char *tool_prefix = acfg->aot_opts.tool_prefix ? acfg->aot_opts.tool_prefix : "";
5482 #if defined(TARGET_AMD64)
5483 #define AS_OPTIONS "--64"
5484 #elif defined(TARGET_POWERPC64)
5485 #define AS_OPTIONS "-a64 -mppc64"
5486 #define LD_OPTIONS "-m elf64ppc"
5487 #elif defined(sparc) && SIZEOF_VOID_P == 8
5488 #define AS_OPTIONS "-xarch=v9"
5490 #define AS_OPTIONS ""
5494 #define LD_OPTIONS ""
5498 #define EH_LD_OPTIONS "--eh-frame-hdr"
5500 #define EH_LD_OPTIONS ""
5503 if (acfg->aot_opts.asm_only) {
5504 printf ("Output file: '%s'.\n", acfg->tmpfname);
5505 if (acfg->aot_opts.static_link)
5506 printf ("Linking symbol: '%s'.\n", acfg->static_linking_symbol);
5510 if (acfg->aot_opts.static_link) {
5511 if (acfg->aot_opts.outfile)
5512 objfile = g_strdup_printf ("%s", acfg->aot_opts.outfile);
5514 objfile = g_strdup_printf ("%s.o", acfg->image->name);
5516 objfile = g_strdup_printf ("%s.o", acfg->tmpfname);
5518 command = g_strdup_printf ("%sas %s %s -o %s", tool_prefix, AS_OPTIONS, acfg->tmpfname, objfile);
5519 printf ("Executing the native assembler: %s\n", command);
5520 if (system (command) != 0) {
5528 if (acfg->aot_opts.static_link) {
5529 printf ("Output file: '%s'.\n", objfile);
5530 printf ("Linking symbol: '%s'.\n", acfg->static_linking_symbol);
5535 if (acfg->aot_opts.outfile)
5536 outfile_name = g_strdup_printf ("%s", acfg->aot_opts.outfile);
5538 outfile_name = g_strdup_printf ("%s%s", acfg->image->name, SHARED_EXT);
5540 tmp_outfile_name = g_strdup_printf ("%s.tmp", outfile_name);
5543 command = g_strdup_printf ("ld -shared -G -o %s %s.o", tmp_outfile_name, acfg->tmpfname);
5544 #elif defined(__ppc__) && defined(__MACH__)
5545 command = g_strdup_printf ("gcc -dynamiclib -o %s %s.o", tmp_outfile_name, acfg->tmpfname);
5546 #elif defined(HOST_WIN32)
5547 command = g_strdup_printf ("gcc -shared --dll -mno-cygwin -o %s %s.o", tmp_outfile_name, acfg->tmpfname);
5549 command = g_strdup_printf ("%sld %s %s -shared -o %s %s.o", tool_prefix, EH_LD_OPTIONS, LD_OPTIONS, tmp_outfile_name, acfg->tmpfname);
5551 printf ("Executing the native linker: %s\n", command);
5552 if (system (command) != 0) {
5553 g_free (tmp_outfile_name);
5554 g_free (outfile_name);
5562 /*com = g_strdup_printf ("strip --strip-unneeded %s%s", acfg->image->name, SHARED_EXT);
5563 printf ("Stripping the binary: %s\n", com);
5567 #if defined(TARGET_ARM) && !defined(__MACH__)
5569 * gas generates 'mapping symbols' each time code and data is mixed, which
5570 * happens a lot in emit_and_reloc_code (), so we need to get rid of them.
5572 command = g_strdup_printf ("%sstrip --strip-symbol=\\$a --strip-symbol=\\$d %s", tool_prefix, tmp_outfile_name);
5573 printf ("Stripping the binary: %s\n", command);
5574 if (system (command) != 0) {
5575 g_free (tmp_outfile_name);
5576 g_free (outfile_name);
5583 rename (tmp_outfile_name, outfile_name);
5585 g_free (tmp_outfile_name);
5586 g_free (outfile_name);
5589 if (acfg->aot_opts.save_temps)
5590 printf ("Retained input file.\n");
5592 unlink (acfg->tmpfname);
5597 static MonoAotCompile*
5598 acfg_create (MonoAssembly *ass, guint32 opts)
5600 MonoImage *image = ass->image;
5601 MonoAotCompile *acfg;
5604 acfg = g_new0 (MonoAotCompile, 1);
5605 acfg->methods = g_ptr_array_new ();
5606 acfg->method_indexes = g_hash_table_new (NULL, NULL);
5607 acfg->method_depth = g_hash_table_new (NULL, NULL);
5608 acfg->plt_offset_to_patch = g_hash_table_new (NULL, NULL);
5609 acfg->patch_to_plt_offset = g_hash_table_new (mono_patch_info_hash, mono_patch_info_equal);
5610 acfg->patch_to_got_offset = g_hash_table_new (mono_patch_info_hash, mono_patch_info_equal);
5611 acfg->patch_to_got_offset_by_type = g_new0 (GHashTable*, MONO_PATCH_INFO_NUM);
5612 for (i = 0; i < MONO_PATCH_INFO_NUM; ++i)
5613 acfg->patch_to_got_offset_by_type [i] = g_hash_table_new (mono_patch_info_hash, mono_patch_info_equal);
5614 acfg->got_patches = g_ptr_array_new ();
5615 acfg->method_to_cfg = g_hash_table_new (NULL, NULL);
5616 acfg->token_info_hash = g_hash_table_new_full (NULL, NULL, NULL, g_free);
5617 acfg->image_hash = g_hash_table_new (NULL, NULL);
5618 acfg->image_table = g_ptr_array_new ();
5619 acfg->globals = g_ptr_array_new ();
5620 acfg->image = image;
5622 acfg->mempool = mono_mempool_new ();
5623 acfg->extra_methods = g_ptr_array_new ();
5624 acfg->unwind_info_offsets = g_hash_table_new (NULL, NULL);
5625 acfg->unwind_ops = g_ptr_array_new ();
5626 acfg->method_label_hash = g_hash_table_new_full (g_str_hash, g_str_equal, g_free, NULL);
5627 InitializeCriticalSection (&acfg->mutex);
5633 acfg_free (MonoAotCompile *acfg)
5637 img_writer_destroy (acfg->w);
5638 for (i = 0; i < acfg->nmethods; ++i)
5640 g_free (acfg->cfgs [i]);
5641 g_free (acfg->cfgs);
5642 g_free (acfg->static_linking_symbol);
5643 g_free (acfg->got_symbol);
5644 g_free (acfg->plt_symbol);
5645 g_ptr_array_free (acfg->methods, TRUE);
5646 g_ptr_array_free (acfg->got_patches, TRUE);
5647 g_ptr_array_free (acfg->image_table, TRUE);
5648 g_ptr_array_free (acfg->globals, TRUE);
5649 g_ptr_array_free (acfg->unwind_ops, TRUE);
5650 g_hash_table_destroy (acfg->method_indexes);
5651 g_hash_table_destroy (acfg->method_depth);
5652 g_hash_table_destroy (acfg->plt_offset_to_patch);
5653 g_hash_table_destroy (acfg->patch_to_plt_offset);
5654 g_hash_table_destroy (acfg->patch_to_got_offset);
5655 g_hash_table_destroy (acfg->method_to_cfg);
5656 g_hash_table_destroy (acfg->token_info_hash);
5657 g_hash_table_destroy (acfg->image_hash);
5658 g_hash_table_destroy (acfg->unwind_info_offsets);
5659 g_hash_table_destroy (acfg->method_label_hash);
5660 for (i = 0; i < MONO_PATCH_INFO_NUM; ++i)
5661 g_hash_table_destroy (acfg->patch_to_got_offset_by_type [i]);
5662 g_free (acfg->patch_to_got_offset_by_type);
5663 mono_mempool_destroy (acfg->mempool);
5668 mono_compile_assembly (MonoAssembly *ass, guint32 opts, const char *aot_options)
5670 MonoImage *image = ass->image;
5672 MonoAotCompile *acfg;
5673 char *outfile_name, *tmp_outfile_name, *p;
5677 printf ("Mono Ahead of Time compiler - compiling assembly %s\n", image->name);
5679 acfg = acfg_create (ass, opts);
5681 memset (&acfg->aot_opts, 0, sizeof (acfg->aot_opts));
5682 acfg->aot_opts.write_symbols = TRUE;
5683 acfg->aot_opts.ntrampolines = 1024;
5684 acfg->aot_opts.nrgctx_trampolines = 1024;
5686 mono_aot_parse_options (aot_options, &acfg->aot_opts);
5688 if (acfg->aot_opts.static_link)
5689 acfg->aot_opts.autoreg = TRUE;
5691 //acfg->aot_opts.print_skipped_methods = TRUE;
5693 #ifndef MONO_ARCH_HAVE_FULL_AOT_TRAMPOLINES
5694 if (acfg->aot_opts.full_aot) {
5695 printf ("--aot=full is not supported on this platform.\n");
5700 if (acfg->aot_opts.static_link)
5701 acfg->aot_opts.asm_writer = TRUE;
5703 if (acfg->aot_opts.soft_debug) {
5704 MonoDebugOptions *opt = mini_get_debug_options ();
5706 opt->mdb_optimizations = TRUE;
5707 opt->gen_seq_points = TRUE;
5709 if (mono_debug_format == MONO_DEBUG_FORMAT_NONE) {
5710 fprintf (stderr, "The soft-debug AOT option requires the --debug option.\n");
5717 acfg->aot_opts.asm_writer = TRUE;
5718 acfg->flags |= MONO_AOT_FILE_FLAG_WITH_LLVM;
5721 if (acfg->aot_opts.full_aot)
5722 acfg->flags |= MONO_AOT_FILE_FLAG_FULL_AOT;
5724 load_profile_files (acfg);
5726 acfg->num_trampolines [MONO_AOT_TRAMP_SPECIFIC] = acfg->aot_opts.full_aot ? acfg->aot_opts.ntrampolines : 0;
5727 #ifdef MONO_ARCH_HAVE_STATIC_RGCTX_TRAMPOLINE
5728 acfg->num_trampolines [MONO_AOT_TRAMP_STATIC_RGCTX] = acfg->aot_opts.full_aot ? acfg->aot_opts.nrgctx_trampolines : 0;
5730 acfg->num_trampolines [MONO_AOT_TRAMP_IMT_THUNK] = acfg->aot_opts.full_aot ? 128 : 0;
5732 acfg->got_symbol = g_strdup_printf ("mono_aot_%s_got", acfg->image->assembly->aname.name);
5733 acfg->plt_symbol = g_strdup_printf ("mono_aot_%s_plt", acfg->image->assembly->aname.name);
5735 /* Get rid of characters which cannot occur in symbols */
5736 for (p = acfg->got_symbol; *p; ++p) {
5737 if (!(isalnum (*p) || *p == '_'))
5740 for (p = acfg->plt_symbol; *p; ++p) {
5741 if (!(isalnum (*p) || *p == '_'))
5745 acfg->method_index = 1;
5747 collect_methods (acfg);
5749 acfg->cfgs_size = acfg->methods->len + 32;
5750 acfg->cfgs = g_new0 (MonoCompile*, acfg->cfgs_size);
5752 /* PLT offset 0 is reserved for the PLT trampoline */
5753 acfg->plt_offset = 1;
5757 mono_llvm_create_aot_module (acfg->got_symbol);
5760 /* GOT offset 0 is reserved for the address of the current assembly */
5764 ji = mono_mempool_alloc0 (acfg->mempool, sizeof (MonoAotCompile));
5765 ji->type = MONO_PATCH_INFO_IMAGE;
5766 ji->data.image = acfg->image;
5768 get_got_offset (acfg, ji);
5770 /* Slot 1 is reserved for the mscorlib got addr */
5771 ji = mono_mempool_alloc0 (acfg->mempool, sizeof (MonoAotCompile));
5772 ji->type = MONO_PATCH_INFO_MSCORLIB_GOT_ADDR;
5773 get_got_offset (acfg, ji);
5778 compile_methods (acfg);
5782 acfg->stats.jit_time = TV_ELAPSED (atv, btv);
5787 emit_llvm_file (acfg);
5790 if (!acfg->aot_opts.asm_only && !acfg->aot_opts.asm_writer && bin_writer_supported ()) {
5791 if (acfg->aot_opts.outfile)
5792 outfile_name = g_strdup_printf ("%s", acfg->aot_opts.outfile);
5794 outfile_name = g_strdup_printf ("%s%s", acfg->image->name, SHARED_EXT);
5797 * Can't use g_file_open_tmp () as it will be deleted at exit, and
5798 * it might be in another file system so the rename () won't work.
5800 tmp_outfile_name = g_strdup_printf ("%s.tmp", outfile_name);
5802 acfg->fp = fopen (tmp_outfile_name, "w");
5804 printf ("Unable to create temporary file '%s': %s\n", tmp_outfile_name, strerror (errno));
5808 acfg->w = img_writer_create (acfg->fp, TRUE);
5809 acfg->use_bin_writer = TRUE;
5812 /* Append to the .s file created by llvm */
5813 /* FIXME: Use multiple files instead */
5814 acfg->tmpfname = g_strdup ("temp.s");
5815 acfg->fp = fopen (acfg->tmpfname, "a");
5817 if (acfg->aot_opts.asm_only) {
5818 if (acfg->aot_opts.outfile)
5819 acfg->tmpfname = g_strdup_printf ("%s", acfg->aot_opts.outfile);
5821 acfg->tmpfname = g_strdup_printf ("%s.s", acfg->image->name);
5822 acfg->fp = fopen (acfg->tmpfname, "w+");
5824 int i = g_file_open_tmp ("mono_aot_XXXXXX", &acfg->tmpfname, NULL);
5825 acfg->fp = fdopen (i, "w+");
5827 g_assert (acfg->fp);
5829 acfg->w = img_writer_create (acfg->fp, FALSE);
5831 tmp_outfile_name = NULL;
5832 outfile_name = NULL;
5835 acfg->temp_prefix = img_writer_get_temp_label_prefix (acfg->w);
5837 if (!acfg->aot_opts.nodebug)
5838 acfg->dwarf = mono_dwarf_writer_create (acfg->w, NULL, 0, FALSE);
5840 img_writer_emit_start (acfg->w);
5843 mono_dwarf_writer_emit_base_info (acfg->dwarf, arch_get_cie_program ());
5849 emit_extra_methods (acfg);
5851 emit_trampolines (acfg);
5853 emit_class_name_table (acfg);
5855 emit_got_info (acfg);
5857 emit_exception_info (acfg);
5859 emit_unwind_info (acfg);
5861 emit_class_info (acfg);
5865 emit_image_table (acfg);
5869 emit_file_info (acfg);
5873 emit_globals (acfg);
5875 emit_autoreg (acfg);
5878 emit_dwarf_info (acfg);
5879 mono_dwarf_writer_close (acfg->dwarf);
5882 emit_mem_end (acfg);
5886 acfg->stats.gen_time = TV_ELAPSED (atv, btv);
5889 g_assert (acfg->got_offset == acfg->final_got_size);
5891 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);
5894 res = img_writer_emit_writeout (acfg->w);
5899 if (acfg->use_bin_writer) {
5900 int err = rename (tmp_outfile_name, outfile_name);
5903 printf ("Unable to rename '%s' to '%s': %s\n", tmp_outfile_name, outfile_name, strerror (errno));
5907 res = compile_asm (acfg);
5914 acfg->stats.link_time = TV_ELAPSED (atv, btv);
5916 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);
5917 if (acfg->stats.genericcount)
5918 printf ("%d methods are generic (%d%%)\n", acfg->stats.genericcount, acfg->stats.mcount ? (acfg->stats.genericcount * 100) / acfg->stats.mcount : 100);
5919 if (acfg->stats.abscount)
5920 printf ("%d methods contain absolute addresses (%d%%)\n", acfg->stats.abscount, acfg->stats.mcount ? (acfg->stats.abscount * 100) / acfg->stats.mcount : 100);
5921 if (acfg->stats.lmfcount)
5922 printf ("%d methods contain lmf pointers (%d%%)\n", acfg->stats.lmfcount, acfg->stats.mcount ? (acfg->stats.lmfcount * 100) / acfg->stats.mcount : 100);
5923 if (acfg->stats.ocount)
5924 printf ("%d methods have other problems (%d%%)\n", acfg->stats.ocount, acfg->stats.mcount ? (acfg->stats.ocount * 100) / acfg->stats.mcount : 100);
5926 printf ("Methods compiled with LLVM: %d (%d%%)\n", acfg->stats.llvm_count, acfg->stats.mcount ? (acfg->stats.llvm_count * 100) / acfg->stats.mcount : 100);
5927 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);
5928 printf ("Direct calls: %d (%d%%)\n", acfg->stats.direct_calls, acfg->stats.all_calls ? (acfg->stats.direct_calls * 100) / acfg->stats.all_calls : 100);
5930 if (acfg->aot_opts.stats) {
5933 printf ("GOT slot distribution:\n");
5934 for (i = 0; i < MONO_PATCH_INFO_NONE; ++i)
5935 if (acfg->stats.got_slot_types [i])
5936 printf ("\t%s: %d\n", get_patch_name (i), acfg->stats.got_slot_types [i]);
5939 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);
5947 * Support for emitting debug info for JITted code.
5949 * This works as follows:
5950 * - the runtime writes out an xdb.s file containing DWARF debug info.
5951 * - the user calls a gdb macro
5952 * - the macro compiles and loads this shared library using add-symbol-file.
5954 * This is based on the xdebug functionality in the Kaffe Java VM.
5956 * We emit assembly code instead of using the ELF writer, so we can emit debug info
5957 * incrementally as each method is JITted, and the debugger doesn't have to call
5958 * into the runtime to emit the shared library, which would cause all kinds of
5959 * complications, like threading issues, and the fact that the ELF writer's
5960 * emit_writeout () function cannot be called more than once.
5961 * GDB 7.0 and later has a JIT interface.
5964 #define USE_GDB_JIT_INTERFACE
5966 /* The recommended gdb macro is: */
5969 shell rm -f xdb.so && as --64 -o xdb.o xdb.s && ld -shared -o xdb.so xdb.o
5970 add-symbol-file xdb.so 0
5975 * GDB JIT interface definitions.
5977 * http://sources.redhat.com/gdb/onlinedocs/gdb_30.html
5986 struct jit_code_entry
5988 struct jit_code_entry *next_entry;
5989 struct jit_code_entry *prev_entry;
5990 const char *symfile_addr;
5991 guint64 symfile_size;
5994 struct jit_descriptor
5997 /* This type should be jit_actions_t, but we use guint32
5998 to be explicit about the bitwidth. */
5999 guint32 action_flag;
6000 struct jit_code_entry *relevant_entry;
6001 struct jit_code_entry *first_entry;
6006 #define MONO_NOINLINE __declspec (noinline)
6008 #define MONO_NOINLINE __attribute__((noinline))
6011 /* GDB puts a breakpoint in this function. */
6012 void MONO_NOINLINE __jit_debug_register_code(void);
6014 #if defined(ENABLE_LLVM) && ((LLVM_MAJOR_VERSION == 2 && LLVM_MINOR_VERSION >= 7) || LLVM_MAJOR_VERSION > 2)
6015 /* LLVM already defines these */
6016 extern struct jit_descriptor __jit_debug_descriptor;
6019 /* Make sure to specify the version statically, because the
6020 debugger may check the version before we can set it. */
6021 struct jit_descriptor __jit_debug_descriptor = { 1, 0, 0, 0 };
6023 void MONO_NOINLINE __jit_debug_register_code(void) { };
6026 static MonoImageWriter *xdebug_w;
6027 static MonoDwarfWriter *xdebug_writer;
6028 static FILE *xdebug_fp, *il_file;
6029 static gboolean use_gdb_interface, save_symfiles;
6030 static int il_file_line_index;
6031 static GHashTable *xdebug_syms;
6034 mono_xdebug_init (char *options)
6039 args = g_strsplit (options, ",", -1);
6040 for (ptr = args; ptr && *ptr; ptr ++) {
6043 if (!strcmp (arg, "gdb"))
6044 use_gdb_interface = TRUE;
6045 if (!strcmp (arg, "save-symfiles"))
6046 save_symfiles = TRUE;
6049 /* This file will contain the IL code for methods which don't have debug info */
6050 il_file = fopen ("xdb.il", "w");
6052 if (use_gdb_interface)
6056 xdebug_fp = fopen ("xdb.s", "w");
6058 w = img_writer_create (xdebug_fp, FALSE);
6060 img_writer_emit_start (w);
6062 xdebug_writer = mono_dwarf_writer_create (w, il_file, 0, TRUE);
6064 /* Emit something so the file has a text segment */
6065 img_writer_emit_section_change (w, ".text", 0);
6066 img_writer_emit_string (w, "");
6068 mono_dwarf_writer_emit_base_info (xdebug_writer, arch_get_cie_program ());
6072 xdebug_begin_emit (MonoImageWriter **out_w, MonoDwarfWriter **out_dw)
6075 MonoDwarfWriter *dw;
6077 w = img_writer_create (NULL, TRUE);
6079 img_writer_emit_start (w);
6081 /* This file will contain the IL code for methods which don't have debug info */
6083 il_file = fopen ("xdb.il", "w");
6085 dw = mono_dwarf_writer_create (w, il_file, il_file_line_index, FALSE);
6087 mono_dwarf_writer_emit_base_info (dw, arch_get_cie_program ());
6094 xdebug_end_emit (MonoImageWriter *w, MonoDwarfWriter *dw, MonoMethod *method)
6098 struct jit_code_entry *entry;
6100 il_file_line_index = mono_dwarf_writer_get_il_file_line_index (dw);
6101 mono_dwarf_writer_close (dw);
6103 img_writer_emit_writeout (w);
6105 img = img_writer_get_output (w, &img_size);
6107 img_writer_destroy (w);
6110 /* Save the symbol files to help debugging */
6113 static int file_counter;
6116 file_name = g_strdup_printf ("xdb-%d.o", file_counter);
6117 //printf ("%s -> %s\n", mono_method_full_name (method, TRUE), file_name);
6119 fp = fopen (file_name, "w");
6120 fwrite (img, img_size, 1, fp);
6125 /* Register the image with GDB */
6127 entry = g_malloc (sizeof (struct jit_code_entry));
6129 entry->symfile_addr = (const char*)img;
6130 entry->symfile_size = img_size;
6132 entry->next_entry = __jit_debug_descriptor.first_entry;
6133 if (__jit_debug_descriptor.first_entry)
6134 __jit_debug_descriptor.first_entry->prev_entry = entry;
6135 __jit_debug_descriptor.first_entry = entry;
6137 __jit_debug_descriptor.relevant_entry = entry;
6138 __jit_debug_descriptor.action_flag = JIT_REGISTER_FN;
6140 __jit_debug_register_code ();
6144 * mono_xdebug_flush:
6146 * This could be called from inside gdb to flush the debugging information not yet
6147 * registered with gdb.
6150 mono_xdebug_flush (void)
6153 xdebug_end_emit (xdebug_w, xdebug_writer, NULL);
6155 xdebug_begin_emit (&xdebug_w, &xdebug_writer);
6158 static int xdebug_method_count;
6161 * mono_save_xdebug_info:
6163 * Emit debugging info for METHOD into an assembly file which can be assembled
6164 * and loaded into gdb to provide debugging info for JITted code.
6165 * LOCKING: Acquires the loader lock.
6168 mono_save_xdebug_info (MonoCompile *cfg)
6170 if (use_gdb_interface) {
6171 mono_loader_lock ();
6174 xdebug_syms = g_hash_table_new_full (g_str_hash, g_str_equal, g_free, NULL);
6177 * gdb is not designed to handle 1000s of symbol files (one per method). So we
6178 * group them into groups of 100.
6180 if ((xdebug_method_count % 100) == 0)
6181 mono_xdebug_flush ();
6183 xdebug_method_count ++;
6185 mono_dwarf_writer_emit_method (xdebug_writer, cfg, cfg->jit_info->method, NULL, NULL, 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 ()));
6189 * Emit a symbol for the code by emitting it at the beginning of the text
6190 * segment, and setting the text segment to have an absolute address.
6191 * This symbol can be used to set breakpoints in gdb.
6192 * FIXME: This doesn't work when multiple methods are emitted into the same file.
6194 sym = get_debug_sym (cfg->jit_info->method, "", xdebug_syms);
6195 img_writer_emit_section_change (w, ".text", 0);
6196 if (!xdebug_text_addr) {
6197 xdebug_text_addr = cfg->jit_info->code_start;
6198 img_writer_set_section_addr (w, (gssize)xdebug_text_addr);
6200 img_writer_emit_global_with_size (w, sym, cfg->jit_info->code_size, TRUE);
6201 img_writer_emit_label (w, sym);
6202 img_writer_emit_bytes (w, cfg->jit_info->code_start, cfg->jit_info->code_size);
6206 mono_loader_unlock ();
6211 mono_loader_lock ();
6212 mono_dwarf_writer_emit_method (xdebug_writer, cfg, cfg->jit_info->method, NULL, NULL, 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 ()));
6214 mono_loader_unlock ();
6219 * mono_save_trampoline_xdebug_info:
6221 * Same as mono_save_xdebug_info, but for trampolines.
6222 * LOCKING: Acquires the loader lock.
6225 mono_save_trampoline_xdebug_info (const char *tramp_name, guint8 *code, guint32 code_size, GSList *unwind_info)
6227 if (use_gdb_interface) {
6229 MonoDwarfWriter *dw;
6231 mono_loader_lock ();
6233 xdebug_begin_emit (&w, &dw);
6235 mono_dwarf_writer_emit_trampoline (dw, tramp_name, NULL, NULL, code, code_size, unwind_info);
6237 xdebug_end_emit (w, dw, NULL);
6239 mono_loader_unlock ();
6244 mono_loader_lock ();
6245 mono_dwarf_writer_emit_trampoline (xdebug_writer, tramp_name, NULL, NULL, code, code_size, unwind_info);
6247 mono_loader_unlock ();
6256 mono_compile_assembly (MonoAssembly *ass, guint32 opts, const char *aot_options)
6262 mono_xdebug_init (char *options)
6267 mono_save_xdebug_info (MonoCompile *cfg)
6272 mono_save_trampoline_xdebug_info (const char *tramp_name, guint8 *code, guint32 code_size, GSList *unwind_info)