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 gboolean print_skipped_methods;
107 typedef struct MonoAotStats {
108 int ccount, mcount, lmfcount, abscount, gcount, ocount, genericcount;
109 int code_size, info_size, ex_info_size, unwind_info_size, got_size, class_info_size, got_info_size, got_info_offsets_size;
110 int methods_without_got_slots, direct_calls, all_calls, llvm_count;
112 int got_slot_types [MONO_PATCH_INFO_NONE];
113 int jit_time, gen_time, link_time;
116 typedef struct MonoAotCompile {
119 GHashTable *method_indexes;
120 GHashTable *method_depth;
123 GHashTable *patch_to_plt_offset;
124 GHashTable *plt_offset_to_patch;
125 GHashTable *patch_to_got_offset;
126 GHashTable **patch_to_got_offset_by_type;
127 GPtrArray *got_patches;
128 GHashTable *image_hash;
129 GHashTable *method_to_cfg;
130 GHashTable *token_info_hash;
131 GPtrArray *extra_methods;
132 GPtrArray *image_table;
135 guint32 *plt_got_info_offsets;
136 guint32 got_offset, plt_offset, plt_got_offset_base;
137 guint32 final_got_size;
138 /* Number of GOT entries reserved for trampolines */
139 guint32 num_trampoline_got_entries;
141 guint32 num_trampolines [MONO_AOT_TRAMP_NUM];
142 guint32 trampoline_got_offset_base [MONO_AOT_TRAMP_NUM];
143 guint32 trampoline_size [MONO_AOT_TRAMP_NUM];
145 MonoAotOptions aot_opts;
148 MonoMemPool *mempool;
151 char *static_linking_symbol;
152 CRITICAL_SECTION mutex;
153 gboolean use_bin_writer;
155 MonoDwarfWriter *dwarf;
159 GHashTable *unwind_info_offsets;
160 GPtrArray *unwind_ops;
161 guint32 unwind_info_offset;
164 GHashTable *method_label_hash;
165 const char *temp_prefix;
166 guint32 label_generator;
168 MonoAotFileFlags flags;
171 #define mono_acfg_lock(acfg) EnterCriticalSection (&((acfg)->mutex))
172 #define mono_acfg_unlock(acfg) LeaveCriticalSection (&((acfg)->mutex))
174 /* This points to the current acfg in LLVM mode */
175 static MonoAotCompile *llvm_acfg;
177 #ifdef HAVE_ARRAY_ELEM_INIT
178 #define MSGSTRFIELD(line) MSGSTRFIELD1(line)
179 #define MSGSTRFIELD1(line) str##line
180 static const struct msgstr_t {
181 #define PATCH_INFO(a,b) char MSGSTRFIELD(__LINE__) [sizeof (b)];
182 #include "patch-info.h"
185 #define PATCH_INFO(a,b) b,
186 #include "patch-info.h"
189 static const gint16 opidx [] = {
190 #define PATCH_INFO(a,b) [MONO_PATCH_INFO_ ## a] = offsetof (struct msgstr_t, MSGSTRFIELD(__LINE__)),
191 #include "patch-info.h"
195 static G_GNUC_UNUSED const char*
196 get_patch_name (int info)
198 return (const char*)&opstr + opidx [info];
202 #define PATCH_INFO(a,b) b,
203 static const char* const
204 patch_types [MONO_PATCH_INFO_NUM + 1] = {
205 #include "patch-info.h"
209 static G_GNUC_UNUSED const char*
210 get_patch_name (int info)
212 return patch_types [info];
217 /* Wrappers around the image writer functions */
220 emit_section_change (MonoAotCompile *acfg, const char *section_name, int subsection_index)
222 img_writer_emit_section_change (acfg->w, section_name, subsection_index);
226 emit_push_section (MonoAotCompile *acfg, const char *section_name, int subsection)
228 img_writer_emit_push_section (acfg->w, section_name, subsection);
232 emit_pop_section (MonoAotCompile *acfg)
234 img_writer_emit_pop_section (acfg->w);
238 emit_local_symbol (MonoAotCompile *acfg, const char *name, const char *end_label, gboolean func)
240 img_writer_emit_local_symbol (acfg->w, name, end_label, func);
244 emit_label (MonoAotCompile *acfg, const char *name)
246 img_writer_emit_label (acfg->w, name);
250 emit_bytes (MonoAotCompile *acfg, const guint8* buf, int size)
252 img_writer_emit_bytes (acfg->w, buf, size);
256 emit_string (MonoAotCompile *acfg, const char *value)
258 img_writer_emit_string (acfg->w, value);
262 emit_line (MonoAotCompile *acfg)
264 img_writer_emit_line (acfg->w);
268 emit_alignment (MonoAotCompile *acfg, int size)
270 img_writer_emit_alignment (acfg->w, size);
274 emit_pointer_unaligned (MonoAotCompile *acfg, const char *target)
276 img_writer_emit_pointer_unaligned (acfg->w, target);
280 emit_pointer (MonoAotCompile *acfg, const char *target)
282 img_writer_emit_pointer (acfg->w, target);
286 emit_int16 (MonoAotCompile *acfg, int value)
288 img_writer_emit_int16 (acfg->w, value);
292 emit_int32 (MonoAotCompile *acfg, int value)
294 img_writer_emit_int32 (acfg->w, value);
298 emit_symbol_diff (MonoAotCompile *acfg, const char *end, const char* start, int offset)
300 img_writer_emit_symbol_diff (acfg->w, end, start, offset);
304 emit_zero_bytes (MonoAotCompile *acfg, int num)
306 img_writer_emit_zero_bytes (acfg->w, num);
310 emit_byte (MonoAotCompile *acfg, guint8 val)
312 img_writer_emit_byte (acfg->w, val);
315 static G_GNUC_UNUSED void
316 emit_global_inner (MonoAotCompile *acfg, const char *name, gboolean func)
318 img_writer_emit_global (acfg->w, name, func);
322 emit_global (MonoAotCompile *acfg, const char *name, gboolean func)
324 if (acfg->aot_opts.no_dlsym) {
325 g_ptr_array_add (acfg->globals, g_strdup (name));
326 img_writer_emit_local_symbol (acfg->w, name, NULL, func);
328 img_writer_emit_global (acfg->w, name, func);
333 emit_symbol_size (MonoAotCompile *acfg, const char *name, const char *end_label)
335 img_writer_emit_symbol_size (acfg->w, name, end_label);
339 emit_string_symbol (MonoAotCompile *acfg, const char *name, const char *value)
341 img_writer_emit_section_change (acfg->w, ".text", 1);
342 emit_global (acfg, name, FALSE);
343 img_writer_emit_label (acfg->w, name);
344 img_writer_emit_string (acfg->w, value);
347 static G_GNUC_UNUSED void
348 emit_uleb128 (MonoAotCompile *acfg, guint32 value)
351 guint8 b = value & 0x7f;
353 if (value != 0) /* more bytes to come */
359 static G_GNUC_UNUSED void
360 emit_sleb128 (MonoAotCompile *acfg, gint64 value)
363 gboolean negative = (value < 0);
370 /* the following is unnecessary if the
371 * implementation of >>= uses an arithmetic rather
372 * than logical shift for a signed left operand
376 value |= - ((gint64)1 <<(size - 7));
377 /* sign bit of byte is second high order bit (0x40) */
378 if ((value == 0 && !(byte & 0x40)) ||
379 (value == -1 && (byte & 0x40)))
383 emit_byte (acfg, byte);
387 static G_GNUC_UNUSED void
388 encode_uleb128 (guint32 value, guint8 *buf, guint8 **endbuf)
393 guint8 b = value & 0x7f;
395 if (value != 0) /* more bytes to come */
403 static G_GNUC_UNUSED void
404 encode_sleb128 (gint32 value, guint8 *buf, guint8 **endbuf)
407 gboolean negative = (value < 0);
415 /* the following is unnecessary if the
416 * implementation of >>= uses an arithmetic rather
417 * than logical shift for a signed left operand
421 value |= - (1 <<(size - 7));
422 /* sign bit of byte is second high order bit (0x40) */
423 if ((value == 0 && !(byte & 0x40)) ||
424 (value == -1 && (byte & 0x40)))
434 /* ARCHITECTURE SPECIFIC CODE */
436 #if defined(TARGET_X86) || defined(TARGET_AMD64) || defined(TARGET_ARM) || defined(TARGET_POWERPC)
437 #define EMIT_DWARF_INFO 1
440 #if defined(TARGET_ARM)
441 #define AOT_FUNC_ALIGNMENT 4
443 #define AOT_FUNC_ALIGNMENT 16
446 #if defined(TARGET_POWERPC64) && !defined(__mono_ilp32__)
447 #define PPC_LD_OP "ld"
448 #define PPC_LDX_OP "ldx"
450 #define PPC_LD_OP "lwz"
451 #define PPC_LDX_OP "lwzx"
455 * arch_emit_direct_call:
457 * Emit a direct call to the symbol TARGET. CALL_SIZE is set to the size of the
461 arch_emit_direct_call (MonoAotCompile *acfg, const char *target, int *call_size)
463 #if defined(TARGET_X86) || defined(TARGET_AMD64)
464 /* Need to make sure this is exactly 5 bytes long */
465 emit_byte (acfg, '\xe8');
466 emit_symbol_diff (acfg, target, ".", -4);
468 #elif defined(TARGET_ARM)
469 if (acfg->use_bin_writer) {
476 img_writer_emit_reloc (acfg->w, R_ARM_CALL, target, -8);
477 emit_bytes (acfg, buf, 4);
479 img_writer_emit_unset_mode (acfg->w);
480 fprintf (acfg->fp, "bl %s\n", target);
483 #elif defined(TARGET_POWERPC)
484 if (acfg->use_bin_writer) {
485 g_assert_not_reached ();
487 img_writer_emit_unset_mode (acfg->w);
488 fprintf (acfg->fp, "bl %s\n", target);
492 g_assert_not_reached ();
498 * - we use an approach similar to the x86 abi: reserve a register (r30) to hold
500 * - The full-aot trampolines need access to the GOT of mscorlib, so we store
501 * in in the 2. slot of every GOT, and require every method to place the GOT
502 * address in r30, even when it doesn't access the GOT otherwise. This way,
503 * the trampolines can compute the mscorlib GOT address by loading 4(r30).
508 * PPC64 uses function descriptors which greatly complicate all code, since
509 * these are used very inconsistently in the runtime. Some functions like
510 * mono_compile_method () return ftn descriptors, while others like the
511 * trampoline creation functions do not.
512 * We assume that all GOT slots contain function descriptors, and create
513 * descriptors in aot-runtime.c when needed.
514 * The ppc64 abi uses r2 to hold the address of the TOC/GOT, which is loaded
515 * from function descriptors, we could do the same, but it would require
516 * rewriting all the ppc/aot code to handle function descriptors properly.
517 * So instead, we use the same approach as on PPC32.
518 * This is a horrible mess, but fixing it would probably lead to an even bigger
522 #ifdef MONO_ARCH_AOT_SUPPORTED
524 * arch_emit_got_offset:
526 * The memory pointed to by CODE should hold native code for computing the GOT
527 * address. Emit this code while patching it with the offset between code and
528 * the GOT. CODE_SIZE is set to the number of bytes emitted.
531 arch_emit_got_offset (MonoAotCompile *acfg, guint8 *code, int *code_size)
533 #if defined(TARGET_POWERPC64)
534 g_assert (!acfg->use_bin_writer);
535 img_writer_emit_unset_mode (acfg->w);
537 * The ppc32 code doesn't seem to work on ppc64, the assembler complains about
538 * unsupported relocations. So we store the got address into the .Lgot_addr
539 * symbol which is in the text segment, compute its address, and load it.
541 fprintf (acfg->fp, ".L%d:\n", acfg->label_generator);
542 fprintf (acfg->fp, "lis 0, (.Lgot_addr + 4 - .L%d)@h\n", acfg->label_generator);
543 fprintf (acfg->fp, "ori 0, 0, (.Lgot_addr + 4 - .L%d)@l\n", acfg->label_generator);
544 fprintf (acfg->fp, "add 30, 30, 0\n");
545 fprintf (acfg->fp, "%s 30, 0(30)\n", PPC_LD_OP);
546 acfg->label_generator ++;
548 #elif defined(TARGET_POWERPC)
549 g_assert (!acfg->use_bin_writer);
550 img_writer_emit_unset_mode (acfg->w);
551 fprintf (acfg->fp, ".L%d:\n", acfg->label_generator);
552 fprintf (acfg->fp, "lis 0, (%s + 4 - .L%d)@h\n", acfg->got_symbol, acfg->label_generator);
553 fprintf (acfg->fp, "ori 0, 0, (%s + 4 - .L%d)@l\n", acfg->got_symbol, acfg->label_generator);
554 acfg->label_generator ++;
557 guint32 offset = mono_arch_get_patch_offset (code);
558 emit_bytes (acfg, code, offset);
559 emit_symbol_diff (acfg, acfg->got_symbol, ".", offset);
561 *code_size = offset + 4;
566 * arch_emit_got_access:
568 * The memory pointed to by CODE should hold native code for loading a GOT
569 * slot. Emit this code while patching it so it accesses the GOT slot GOT_SLOT.
570 * CODE_SIZE is set to the number of bytes emitted.
573 arch_emit_got_access (MonoAotCompile *acfg, guint8 *code, int got_slot, int *code_size)
575 /* Emit beginning of instruction */
576 emit_bytes (acfg, code, mono_arch_get_patch_offset (code));
578 /* Emit the offset */
580 emit_symbol_diff (acfg, acfg->got_symbol, ".", (unsigned int) ((got_slot * sizeof (gpointer)) - 4));
581 *code_size = mono_arch_get_patch_offset (code) + 4;
582 #elif defined(TARGET_X86)
583 emit_int32 (acfg, (unsigned int) ((got_slot * sizeof (gpointer))));
584 *code_size = mono_arch_get_patch_offset (code) + 4;
585 #elif defined(TARGET_ARM)
586 emit_symbol_diff (acfg, acfg->got_symbol, ".", (unsigned int) ((got_slot * sizeof (gpointer))) - 12);
587 *code_size = mono_arch_get_patch_offset (code) + 4;
588 #elif defined(TARGET_POWERPC)
594 ppc_load32 (code, ppc_r0, got_slot * sizeof (gpointer));
595 g_assert (code - buf == 8);
596 emit_bytes (acfg, buf, code - buf);
597 *code_size = code - buf;
600 g_assert_not_reached ();
607 * arch_emit_plt_entry:
609 * Emit code for the PLT entry with index INDEX.
612 arch_emit_plt_entry (MonoAotCompile *acfg, int index)
614 #if defined(TARGET_X86)
616 /* It is filled up during loading by the AOT loader. */
617 emit_zero_bytes (acfg, 16);
619 /* Need to make sure this is 9 bytes long */
620 emit_byte (acfg, '\xe9');
621 emit_symbol_diff (acfg, acfg->plt_symbol, ".", -4);
622 emit_int32 (acfg, acfg->plt_got_info_offsets [index]);
624 #elif defined(TARGET_AMD64)
626 * We can't emit jumps because they are 32 bits only so they can't be patched.
627 * So we make indirect calls through GOT entries which are patched by the AOT
628 * loader to point to .Lpd entries.
629 * An x86_64 plt entry is 10 bytes long, init_plt () depends on this.
631 /* jmpq *<offset>(%rip) */
632 emit_byte (acfg, '\xff');
633 emit_byte (acfg, '\x25');
634 emit_symbol_diff (acfg, acfg->got_symbol, ".", ((acfg->plt_got_offset_base + index) * sizeof (gpointer)) -4);
635 /* Used by mono_aot_get_plt_info_offset */
636 emit_int32 (acfg, acfg->plt_got_info_offsets [index]);
637 #elif defined(TARGET_ARM)
642 * - optimize OP_AOTCONST implementation
643 * - optimize the PLT entries
644 * - optimize SWITCH AOT implementation
645 * - implement IMT support
648 if (acfg->use_bin_writer && FALSE) {
649 /* FIXME: mono_arch_patch_plt_entry () needs to decode this */
650 /* We only emit 1 relocation since we implement it ourselves anyway */
651 img_writer_emit_reloc (acfg->w, R_ARM_ALU_PC_G0_NC, acfg->got_symbol, ((acfg->plt_got_offset_base + index) * sizeof (gpointer)) - 8);
652 /* FIXME: A 2 instruction encoding is sufficient in most cases */
653 ARM_ADD_REG_IMM (code, ARMREG_IP, ARMREG_PC, 0, 0);
654 ARM_ADD_REG_IMM (code, ARMREG_IP, ARMREG_IP, 0, 0);
655 ARM_LDR_IMM (code, ARMREG_PC, ARMREG_IP, 0);
656 emit_bytes (acfg, buf, code - buf);
657 /* Used by mono_aot_get_plt_info_offset */
658 emit_int32 (acfg, acfg->plt_got_info_offsets [index]);
660 ARM_LDR_IMM (code, ARMREG_IP, ARMREG_PC, 0);
661 ARM_LDR_REG_REG (code, ARMREG_PC, ARMREG_PC, ARMREG_IP);
662 emit_bytes (acfg, buf, code - buf);
663 emit_symbol_diff (acfg, acfg->got_symbol, ".", ((acfg->plt_got_offset_base + index) * sizeof (gpointer)) - 4);
664 /* Used by mono_aot_get_plt_info_offset */
665 emit_int32 (acfg, acfg->plt_got_info_offsets [index]);
668 * The plt_got_info_offset is computed automatically by
669 * mono_aot_get_plt_info_offset (), so no need to save it here.
671 #elif defined(TARGET_POWERPC)
672 guint32 offset = (acfg->plt_got_offset_base + index) * sizeof (gpointer);
674 /* The GOT address is guaranteed to be in r30 by OP_LOAD_GOTADDR */
675 g_assert (!acfg->use_bin_writer);
676 img_writer_emit_unset_mode (acfg->w);
677 fprintf (acfg->fp, "lis 11, %d@h\n", offset);
678 fprintf (acfg->fp, "ori 11, 11, %d@l\n", offset);
679 fprintf (acfg->fp, "add 11, 11, 30\n");
680 fprintf (acfg->fp, "%s 11, 0(11)\n", PPC_LD_OP);
681 #ifdef PPC_USES_FUNCTION_DESCRIPTOR
682 fprintf (acfg->fp, "%s 2, %d(11)\n", PPC_LD_OP, (int)sizeof (gpointer));
683 fprintf (acfg->fp, "%s 11, 0(11)\n", PPC_LD_OP);
685 fprintf (acfg->fp, "mtctr 11\n");
686 fprintf (acfg->fp, "bctr\n");
687 emit_int32 (acfg, acfg->plt_got_info_offsets [index]);
689 g_assert_not_reached ();
694 * arch_emit_specific_trampoline:
696 * Emit code for a specific trampoline. OFFSET is the offset of the first of
697 * two GOT slots which contain the generic trampoline address and the trampoline
698 * argument. TRAMP_SIZE is set to the size of the emitted trampoline.
701 arch_emit_specific_trampoline (MonoAotCompile *acfg, int offset, int *tramp_size)
704 * The trampolines created here are variations of the specific
705 * trampolines created in mono_arch_create_specific_trampoline (). The
707 * - the generic trampoline address is taken from a got slot.
708 * - the offset of the got slot where the trampoline argument is stored
709 * is embedded in the instruction stream, and the generic trampoline
710 * can load the argument by loading the offset, adding it to the
711 * address of the trampoline to get the address of the got slot, and
712 * loading the argument from there.
713 * - all the trampolines should be of the same length.
715 #if defined(TARGET_AMD64)
716 /* This should be exactly 16 bytes long */
718 /* call *<offset>(%rip) */
719 emit_byte (acfg, '\x41');
720 emit_byte (acfg, '\xff');
721 emit_byte (acfg, '\x15');
722 emit_symbol_diff (acfg, acfg->got_symbol, ".", (offset * sizeof (gpointer)) - 4);
723 /* This should be relative to the start of the trampoline */
724 emit_symbol_diff (acfg, acfg->got_symbol, ".", (offset * sizeof (gpointer)) - 4 + 19);
725 emit_zero_bytes (acfg, 5);
726 #elif defined(TARGET_ARM)
730 /* This should be exactly 20 bytes long */
733 ARM_PUSH (code, 0x5fff);
734 ARM_LDR_IMM (code, ARMREG_R1, ARMREG_PC, 4);
735 /* Load the value from the GOT */
736 ARM_LDR_REG_REG (code, ARMREG_R1, ARMREG_PC, ARMREG_R1);
738 ARM_BLX_REG (code, ARMREG_R1);
740 g_assert (code - buf == 16);
743 emit_bytes (acfg, buf, code - buf);
745 * Only one offset is needed, since the second one would be equal to the
748 emit_symbol_diff (acfg, acfg->got_symbol, ".", (offset * sizeof (gpointer)) - 4 + 4);
749 //emit_symbol_diff (acfg, acfg->got_symbol, ".", ((offset + 1) * sizeof (gpointer)) - 4 + 8);
750 #elif defined(TARGET_POWERPC)
757 g_assert (!acfg->use_bin_writer);
760 * PPC has no ip relative addressing, so we need to compute the address
761 * of the mscorlib got. That is slow and complex, so instead, we store it
762 * in the second got slot of every aot image. The caller already computed
763 * the address of its got and placed it into r30.
765 img_writer_emit_unset_mode (acfg->w);
766 /* Load mscorlib got address */
767 fprintf (acfg->fp, "%s 0, %d(30)\n", PPC_LD_OP, (int)sizeof (gpointer));
768 /* Load generic trampoline address */
769 fprintf (acfg->fp, "lis 11, %d@h\n", (int)(offset * sizeof (gpointer)));
770 fprintf (acfg->fp, "ori 11, 11, %d@l\n", (int)(offset * sizeof (gpointer)));
771 fprintf (acfg->fp, "%s 11, 11, 0\n", PPC_LDX_OP);
772 #ifdef PPC_USES_FUNCTION_DESCRIPTOR
773 fprintf (acfg->fp, "%s 11, 0(11)\n", PPC_LD_OP);
775 fprintf (acfg->fp, "mtctr 11\n");
776 /* Load trampoline argument */
777 /* On ppc, we pass it normally to the generic trampoline */
778 fprintf (acfg->fp, "lis 11, %d@h\n", (int)((offset + 1) * sizeof (gpointer)));
779 fprintf (acfg->fp, "ori 11, 11, %d@l\n", (int)((offset + 1) * sizeof (gpointer)));
780 fprintf (acfg->fp, "%s 0, 11, 0\n", PPC_LDX_OP);
781 /* Branch to generic trampoline */
782 fprintf (acfg->fp, "bctr\n");
784 #ifdef PPC_USES_FUNCTION_DESCRIPTOR
785 *tramp_size = 10 * 4;
790 g_assert_not_reached ();
795 * arch_emit_unbox_trampoline:
797 * Emit code for the unbox trampoline for METHOD used in the full-aot case.
798 * CALL_TARGET is the symbol pointing to the native code of METHOD.
801 arch_emit_unbox_trampoline (MonoAotCompile *acfg, MonoMethod *method, MonoGenericSharingContext *gsctx, const char *call_target)
803 #if defined(TARGET_AMD64)
808 this_reg = mono_arch_get_this_arg_reg (mono_method_signature (method), gsctx, NULL);
810 amd64_alu_reg_imm (code, X86_ADD, this_reg, sizeof (MonoObject));
812 emit_bytes (acfg, buf, code - buf);
814 emit_byte (acfg, '\xe9');
815 emit_symbol_diff (acfg, call_target, ".", -4);
816 #elif defined(TARGET_ARM)
823 if (MONO_TYPE_ISSTRUCT (mono_method_signature (method)->ret))
826 ARM_ADD_REG_IMM8 (code, this_pos, this_pos, sizeof (MonoObject));
828 emit_bytes (acfg, buf, code - buf);
830 if (acfg->use_bin_writer) {
837 img_writer_emit_reloc (acfg->w, R_ARM_JUMP24, call_target, -8);
838 emit_bytes (acfg, buf, 4);
840 fprintf (acfg->fp, "\n\tb %s\n", call_target);
842 #elif defined(TARGET_POWERPC)
845 if (MONO_TYPE_ISSTRUCT (mono_method_signature (method)->ret))
848 g_assert (!acfg->use_bin_writer);
850 fprintf (acfg->fp, "\n\taddi %d, %d, %d\n", this_pos, this_pos, (int)sizeof (MonoObject));
851 fprintf (acfg->fp, "\n\tb %s\n", call_target);
853 g_assert_not_reached ();
858 * arch_emit_static_rgctx_trampoline:
860 * Emit code for a static rgctx trampoline. OFFSET is the offset of the first of
861 * two GOT slots which contain the rgctx argument, and the method to jump to.
862 * TRAMP_SIZE is set to the size of the emitted trampoline.
863 * These kinds of trampolines cannot be enumerated statically, since there could
864 * be one trampoline per method instantiation, so we emit the same code for all
865 * trampolines, and parameterize them using two GOT slots.
868 arch_emit_static_rgctx_trampoline (MonoAotCompile *acfg, int offset, int *tramp_size)
870 #if defined(TARGET_AMD64)
871 /* This should be exactly 13 bytes long */
874 /* mov <OFFSET>(%rip), %r10 */
875 emit_byte (acfg, '\x4d');
876 emit_byte (acfg, '\x8b');
877 emit_byte (acfg, '\x15');
878 emit_symbol_diff (acfg, acfg->got_symbol, ".", (offset * sizeof (gpointer)) - 4);
880 /* jmp *<offset>(%rip) */
881 emit_byte (acfg, '\xff');
882 emit_byte (acfg, '\x25');
883 emit_symbol_diff (acfg, acfg->got_symbol, ".", ((offset + 1) * sizeof (gpointer)) - 4);
884 #elif defined(TARGET_ARM)
888 /* This should be exactly 24 bytes long */
891 /* Load rgctx value */
892 ARM_LDR_IMM (code, ARMREG_IP, ARMREG_PC, 8);
893 ARM_LDR_REG_REG (code, MONO_ARCH_RGCTX_REG, ARMREG_PC, ARMREG_IP);
894 /* Load branch addr + branch */
895 ARM_LDR_IMM (code, ARMREG_IP, ARMREG_PC, 4);
896 ARM_LDR_REG_REG (code, ARMREG_PC, ARMREG_PC, ARMREG_IP);
898 g_assert (code - buf == 16);
901 emit_bytes (acfg, buf, code - buf);
902 emit_symbol_diff (acfg, acfg->got_symbol, ".", (offset * sizeof (gpointer)) - 4 + 8);
903 emit_symbol_diff (acfg, acfg->got_symbol, ".", ((offset + 1) * sizeof (gpointer)) - 4 + 4);
904 #elif defined(TARGET_POWERPC)
911 g_assert (!acfg->use_bin_writer);
914 * PPC has no ip relative addressing, so we need to compute the address
915 * of the mscorlib got. That is slow and complex, so instead, we store it
916 * in the second got slot of every aot image. The caller already computed
917 * the address of its got and placed it into r30.
919 img_writer_emit_unset_mode (acfg->w);
920 /* Load mscorlib got address */
921 fprintf (acfg->fp, "%s 0, %d(30)\n", PPC_LD_OP, (int)sizeof (gpointer));
923 fprintf (acfg->fp, "lis 11, %d@h\n", (int)(offset * sizeof (gpointer)));
924 fprintf (acfg->fp, "ori 11, 11, %d@l\n", (int)(offset * sizeof (gpointer)));
925 fprintf (acfg->fp, "%s %d, 11, 0\n", PPC_LDX_OP, MONO_ARCH_RGCTX_REG);
926 /* Load target address */
927 fprintf (acfg->fp, "lis 11, %d@h\n", (int)((offset + 1) * sizeof (gpointer)));
928 fprintf (acfg->fp, "ori 11, 11, %d@l\n", (int)((offset + 1) * sizeof (gpointer)));
929 fprintf (acfg->fp, "%s 11, 11, 0\n", PPC_LDX_OP);
930 #ifdef PPC_USES_FUNCTION_DESCRIPTOR
931 fprintf (acfg->fp, "%s 2, %d(11)\n", PPC_LD_OP, (int)sizeof (gpointer));
932 fprintf (acfg->fp, "%s 11, 0(11)\n", PPC_LD_OP);
934 fprintf (acfg->fp, "mtctr 11\n");
935 /* Branch to the target address */
936 fprintf (acfg->fp, "bctr\n");
938 #ifdef PPC_USES_FUNCTION_DESCRIPTOR
939 *tramp_size = 11 * 4;
945 g_assert_not_reached ();
950 * arch_emit_imt_thunk:
952 * Emit an IMT thunk usable in full-aot mode. The thunk uses 1 got slot which
953 * points to an array of pointer pairs. The pairs of the form [key, ptr], where
954 * key is the IMT key, and ptr holds the address of a memory location holding
955 * the address to branch to if the IMT arg matches the key. The array is
956 * terminated by a pair whose key is NULL, and whose ptr is the address of the
958 * TRAMP_SIZE is set to the size of the emitted trampoline.
961 arch_emit_imt_thunk (MonoAotCompile *acfg, int offset, int *tramp_size)
963 #if defined(TARGET_AMD64)
967 code = buf = g_malloc (256);
969 /* FIXME: Optimize this, i.e. use binary search etc. */
970 /* Maybe move the body into a separate function (slower, but much smaller) */
972 /* R10 is a free register */
975 amd64_alu_membase_imm (code, X86_CMP, AMD64_R10, 0, 0);
977 amd64_branch8 (code, X86_CC_Z, FALSE, 0);
980 amd64_alu_membase_reg (code, X86_CMP, AMD64_R10, 0, MONO_ARCH_IMT_REG);
982 amd64_branch8 (code, X86_CC_Z, FALSE, 0);
985 amd64_alu_reg_imm (code, X86_ADD, AMD64_R10, 2 * sizeof (gpointer));
986 amd64_jump_code (code, labels [0]);
989 mono_amd64_patch (labels [2], code);
990 amd64_mov_reg_membase (code, AMD64_R10, AMD64_R10, sizeof (gpointer), 8);
991 amd64_jump_membase (code, AMD64_R10, 0);
995 mono_amd64_patch (labels [1], code);
996 x86_breakpoint (code);
998 /* mov <OFFSET>(%rip), %r10 */
999 emit_byte (acfg, '\x4d');
1000 emit_byte (acfg, '\x8b');
1001 emit_byte (acfg, '\x15');
1002 emit_symbol_diff (acfg, acfg->got_symbol, ".", (offset * sizeof (gpointer)) - 4);
1004 emit_bytes (acfg, buf, code - buf);
1006 *tramp_size = code - buf + 7;
1007 #elif defined(TARGET_ARM)
1009 guint8 *code, *code2, *labels [16];
1013 /* The IMT method is in v5 */
1015 /* Need at least two free registers, plus a slot for storing the pc */
1016 ARM_PUSH (code, (1 << ARMREG_R0)|(1 << ARMREG_R1)|(1 << ARMREG_R2));
1018 /* Load the parameter from the GOT */
1019 ARM_LDR_IMM (code, ARMREG_R0, ARMREG_PC, 0);
1020 ARM_LDR_REG_REG (code, ARMREG_R0, ARMREG_PC, ARMREG_R0);
1023 ARM_LDR_IMM (code, ARMREG_R1, ARMREG_R0, 0);
1024 ARM_CMP_REG_REG (code, ARMREG_R1, ARMREG_V5);
1026 ARM_B_COND (code, ARMCOND_EQ, 0);
1028 /* End-of-loop check */
1029 ARM_CMP_REG_IMM (code, ARMREG_R1, 0, 0);
1031 ARM_B_COND (code, ARMCOND_EQ, 0);
1034 ARM_ADD_REG_IMM8 (code, ARMREG_R0, ARMREG_R0, sizeof (gpointer) * 2);
1037 arm_patch (labels [4], labels [1]);
1040 arm_patch (labels [2], code);
1041 ARM_LDR_IMM (code, ARMREG_R0, ARMREG_R0, 4);
1042 ARM_LDR_IMM (code, ARMREG_R0, ARMREG_R0, 0);
1043 /* Save it to the third stack slot */
1044 ARM_STR_IMM (code, ARMREG_R0, ARMREG_SP, 8);
1045 /* Restore the registers and branch */
1046 ARM_POP (code, (1 << ARMREG_R0)|(1 << ARMREG_R1)|(1 << ARMREG_PC));
1049 arm_patch (labels [3], code);
1054 ARM_LDR_IMM (code2, ARMREG_R0, ARMREG_PC, (code - (labels [0] + 8)));
1056 emit_bytes (acfg, buf, code - buf);
1057 emit_symbol_diff (acfg, acfg->got_symbol, ".", (offset * sizeof (gpointer)) + (code - (labels [0] + 8)) - 4);
1059 *tramp_size = code - buf + 4;
1060 #elif defined(TARGET_POWERPC)
1062 guint8 *code, *labels [16];
1066 /* Load the mscorlib got address */
1067 ppc_ldptr (code, ppc_r11, sizeof (gpointer), ppc_r30);
1068 /* Load the parameter from the GOT */
1069 ppc_load (code, ppc_r0, offset * sizeof (gpointer));
1070 ppc_ldptr_indexed (code, ppc_r11, ppc_r11, ppc_r0);
1072 /* Load and check key */
1074 ppc_ldptr (code, ppc_r0, 0, ppc_r11);
1075 ppc_cmp (code, 0, sizeof (gpointer) == 8 ? 1 : 0, ppc_r0, MONO_ARCH_IMT_REG);
1077 ppc_bc (code, PPC_BR_TRUE, PPC_BR_EQ, 0);
1079 /* End-of-loop check */
1080 ppc_cmpi (code, 0, sizeof (gpointer) == 8 ? 1 : 0, ppc_r0, 0);
1082 ppc_bc (code, PPC_BR_TRUE, PPC_BR_EQ, 0);
1085 ppc_addi (code, ppc_r11, ppc_r11, 2 * sizeof (gpointer));
1088 mono_ppc_patch (labels [4], labels [1]);
1091 mono_ppc_patch (labels [2], code);
1092 ppc_ldptr (code, ppc_r11, sizeof (gpointer), ppc_r11);
1093 /* r11 now contains the value of the vtable slot */
1094 /* this is not a function descriptor on ppc64 */
1095 ppc_ldptr (code, ppc_r11, 0, ppc_r11);
1096 ppc_mtctr (code, ppc_r11);
1097 ppc_bcctr (code, PPC_BR_ALWAYS, 0);
1100 mono_ppc_patch (labels [3], code);
1104 *tramp_size = code - buf;
1106 emit_bytes (acfg, buf, code - buf);
1108 g_assert_not_reached ();
1113 * arch_get_cie_program:
1115 * Get the unwind bytecode for the DWARF CIE.
1118 arch_get_cie_program (void)
1123 mono_add_unwind_op_def_cfa (l, (guint8*)NULL, (guint8*)NULL, AMD64_RSP, 8);
1124 mono_add_unwind_op_offset (l, (guint8*)NULL, (guint8*)NULL, AMD64_RIP, -8);
1127 #elif defined(TARGET_POWERPC)
1130 mono_add_unwind_op_def_cfa (l, (guint8*)NULL, (guint8*)NULL, ppc_r1, 0);
1138 /* END OF ARCH SPECIFIC CODE */
1141 mono_get_field_token (MonoClassField *field)
1143 MonoClass *klass = field->parent;
1146 for (i = 0; i < klass->field.count; ++i) {
1147 if (field == &klass->fields [i])
1148 return MONO_TOKEN_FIELD_DEF | (klass->field.first + 1 + i);
1151 g_assert_not_reached ();
1156 encode_value (gint32 value, guint8 *buf, guint8 **endbuf)
1160 //printf ("ENCODE: %d 0x%x.\n", value, value);
1163 * Same encoding as the one used in the metadata, extended to handle values
1164 * greater than 0x1fffffff.
1166 if ((value >= 0) && (value <= 127))
1168 else if ((value >= 0) && (value <= 16383)) {
1169 p [0] = 0x80 | (value >> 8);
1170 p [1] = value & 0xff;
1172 } else if ((value >= 0) && (value <= 0x1fffffff)) {
1173 p [0] = (value >> 24) | 0xc0;
1174 p [1] = (value >> 16) & 0xff;
1175 p [2] = (value >> 8) & 0xff;
1176 p [3] = value & 0xff;
1181 p [1] = (value >> 24) & 0xff;
1182 p [2] = (value >> 16) & 0xff;
1183 p [3] = (value >> 8) & 0xff;
1184 p [4] = value & 0xff;
1192 get_image_index (MonoAotCompile *cfg, MonoImage *image)
1196 index = GPOINTER_TO_UINT (g_hash_table_lookup (cfg->image_hash, image));
1200 index = g_hash_table_size (cfg->image_hash);
1201 g_hash_table_insert (cfg->image_hash, image, GUINT_TO_POINTER (index + 1));
1202 g_ptr_array_add (cfg->image_table, image);
1208 find_typespec_for_class (MonoAotCompile *acfg, MonoClass *klass)
1211 MonoClass *k = NULL;
1213 /* FIXME: Search referenced images as well */
1214 for (i = 0; i < acfg->image->tables [MONO_TABLE_TYPESPEC].rows; ++i) {
1215 k = mono_class_get_full (acfg->image, MONO_TOKEN_TYPE_SPEC | (i + 1), NULL);
1220 if (i < acfg->image->tables [MONO_TABLE_TYPESPEC].rows)
1221 return MONO_TOKEN_TYPE_SPEC | (i + 1);
1227 encode_method_ref (MonoAotCompile *acfg, MonoMethod *method, guint8 *buf, guint8 **endbuf);
1232 * Encode a reference to KLASS. We use our home-grown encoding instead of the
1233 * standard metadata encoding.
1236 encode_klass_ref (MonoAotCompile *acfg, MonoClass *klass, guint8 *buf, guint8 **endbuf)
1240 if (klass->generic_class) {
1242 g_assert (klass->type_token);
1244 /* Find a typespec for a class if possible */
1245 token = find_typespec_for_class (acfg, klass);
1247 encode_value (token, p, &p);
1248 encode_value (get_image_index (acfg, acfg->image), p, &p);
1250 MonoClass *gclass = klass->generic_class->container_class;
1251 MonoGenericInst *inst = klass->generic_class->context.class_inst;
1254 /* Encode it ourselves */
1256 encode_value (MONO_TOKEN_TYPE_SPEC, p, &p);
1257 encode_value (MONO_TYPE_GENERICINST, p, &p);
1258 encode_klass_ref (acfg, gclass, p, &p);
1259 encode_value (inst->type_argc, p, &p);
1260 for (i = 0; i < inst->type_argc; ++i)
1261 encode_klass_ref (acfg, mono_class_from_mono_type (inst->type_argv [i]), p, &p);
1263 } else if (klass->type_token) {
1264 g_assert (mono_metadata_token_code (klass->type_token) == MONO_TOKEN_TYPE_DEF);
1265 encode_value (klass->type_token - MONO_TOKEN_TYPE_DEF, p, &p);
1266 encode_value (get_image_index (acfg, klass->image), p, &p);
1267 } else if ((klass->byval_arg.type == MONO_TYPE_VAR) || (klass->byval_arg.type == MONO_TYPE_MVAR)) {
1268 MonoGenericContainer *container = mono_type_get_generic_param_owner (&klass->byval_arg);
1269 g_assert (container);
1272 encode_value (MONO_TOKEN_TYPE_SPEC, p, &p);
1273 encode_value (klass->byval_arg.type, p, &p);
1275 encode_value (mono_type_get_generic_param_num (&klass->byval_arg), p, &p);
1277 encode_value (container->is_method, p, &p);
1278 if (container->is_method)
1279 encode_method_ref (acfg, container->owner.method, p, &p);
1281 encode_klass_ref (acfg, container->owner.klass, p, &p);
1284 g_assert (klass->rank > 0);
1285 encode_value (MONO_TOKEN_TYPE_DEF, p, &p);
1286 encode_value (get_image_index (acfg, klass->image), p, &p);
1287 encode_value (klass->rank, p, &p);
1288 encode_klass_ref (acfg, klass->element_class, p, &p);
1294 encode_field_info (MonoAotCompile *cfg, MonoClassField *field, guint8 *buf, guint8 **endbuf)
1296 guint32 token = mono_get_field_token (field);
1299 encode_klass_ref (cfg, field->parent, p, &p);
1300 g_assert (mono_metadata_token_code (token) == MONO_TOKEN_FIELD_DEF);
1301 encode_value (token - MONO_TOKEN_FIELD_DEF, p, &p);
1306 encode_generic_context (MonoAotCompile *acfg, MonoGenericContext *context, guint8 *buf, guint8 **endbuf)
1310 MonoGenericInst *inst;
1312 /* Encode the context */
1313 inst = context->class_inst;
1314 encode_value (inst ? 1 : 0, p, &p);
1316 encode_value (inst->type_argc, p, &p);
1317 for (i = 0; i < inst->type_argc; ++i)
1318 encode_klass_ref (acfg, mono_class_from_mono_type (inst->type_argv [i]), p, &p);
1320 inst = context->method_inst;
1321 encode_value (inst ? 1 : 0, p, &p);
1323 encode_value (inst->type_argc, p, &p);
1324 for (i = 0; i < inst->type_argc; ++i)
1325 encode_klass_ref (acfg, mono_class_from_mono_type (inst->type_argv [i]), p, &p);
1331 #define MAX_IMAGE_INDEX 250
1334 encode_method_ref (MonoAotCompile *acfg, MonoMethod *method, guint8 *buf, guint8 **endbuf)
1336 guint32 image_index = get_image_index (acfg, method->klass->image);
1337 guint32 token = method->token;
1338 MonoJumpInfoToken *ji;
1343 * The encoding for most methods is as follows:
1344 * - image index encoded as a leb128
1345 * - token index encoded as a leb128
1346 * Values of image index >= MONO_AOT_METHODREF_MIN are used to mark additional
1347 * types of method encodings.
1350 g_assert (image_index < MONO_AOT_METHODREF_MIN);
1352 /* Mark methods which can't use aot trampolines because they need the further
1353 * processing in mono_magic_trampoline () which requires a MonoMethod*.
1355 if ((method->is_generic && (method->flags & METHOD_ATTRIBUTE_VIRTUAL)) ||
1356 (method->iflags & METHOD_IMPL_ATTRIBUTE_SYNCHRONIZED))
1357 encode_value ((MONO_AOT_METHODREF_NO_AOT_TRAMPOLINE << 24), p, &p);
1360 * Some wrapper methods are shared using their signature, encode their
1361 * stringified signature instead.
1362 * FIXME: Optimize disk usage
1365 if (method->wrapper_type) {
1366 if (method->wrapper_type == MONO_WRAPPER_RUNTIME_INVOKE) {
1367 char *tmpsig = mono_signature_get_desc (mono_method_signature (method), TRUE);
1368 if (strcmp (method->name, "runtime_invoke_dynamic")) {
1369 name = mono_aot_wrapper_name (method);
1370 } else if (mono_marshal_method_from_wrapper (method) != method) {
1371 /* Direct wrapper, encode it normally */
1373 name = g_strdup_printf ("(wrapper runtime-invoke):%s (%s)", method->name, tmpsig);
1376 } else if (method->wrapper_type == MONO_WRAPPER_DELEGATE_INVOKE) {
1377 char *tmpsig = mono_signature_get_desc (mono_method_signature (method), TRUE);
1378 name = g_strdup_printf ("(wrapper delegate-invoke):%s (%s)", method->name, tmpsig);
1380 } else if (method->wrapper_type == MONO_WRAPPER_DELEGATE_BEGIN_INVOKE) {
1381 char *tmpsig = mono_signature_get_desc (mono_method_signature (method), TRUE);
1382 name = g_strdup_printf ("(wrapper delegate-begin-invoke):%s (%s)", method->name, tmpsig);
1384 } else if (method->wrapper_type == MONO_WRAPPER_DELEGATE_END_INVOKE) {
1385 char *tmpsig = mono_signature_get_desc (mono_method_signature (method), TRUE);
1386 name = g_strdup_printf ("(wrapper delegate-end-invoke):%s (%s)", method->name, tmpsig);
1392 encode_value ((MONO_AOT_METHODREF_WRAPPER_NAME << 24), p, &p);
1393 strcpy ((char*)p, name);
1394 p += strlen (name) + 1;
1396 } else if (method->wrapper_type) {
1397 encode_value ((MONO_AOT_METHODREF_WRAPPER << 24), p, &p);
1399 encode_value (method->wrapper_type, p, &p);
1401 switch (method->wrapper_type) {
1402 case MONO_WRAPPER_REMOTING_INVOKE:
1403 case MONO_WRAPPER_REMOTING_INVOKE_WITH_CHECK:
1404 case MONO_WRAPPER_XDOMAIN_INVOKE: {
1407 m = mono_marshal_method_from_wrapper (method);
1409 encode_method_ref (acfg, m, p, &p);
1412 case MONO_WRAPPER_PROXY_ISINST:
1413 case MONO_WRAPPER_LDFLD:
1414 case MONO_WRAPPER_LDFLDA:
1415 case MONO_WRAPPER_STFLD:
1416 case MONO_WRAPPER_ISINST: {
1417 MonoClass *proxy_class = (MonoClass*)mono_marshal_method_from_wrapper (method);
1418 encode_klass_ref (acfg, proxy_class, p, &p);
1421 case MONO_WRAPPER_LDFLD_REMOTE:
1422 case MONO_WRAPPER_STFLD_REMOTE:
1424 case MONO_WRAPPER_ALLOC: {
1425 int alloc_type = mono_gc_get_managed_allocator_type (method);
1426 g_assert (alloc_type != -1);
1427 encode_value (alloc_type, p, &p);
1430 case MONO_WRAPPER_STELEMREF:
1432 case MONO_WRAPPER_UNKNOWN:
1433 if (strcmp (method->name, "FastMonitorEnter") == 0)
1434 encode_value (MONO_AOT_WRAPPER_MONO_ENTER, p, &p);
1435 else if (strcmp (method->name, "FastMonitorExit") == 0)
1436 encode_value (MONO_AOT_WRAPPER_MONO_EXIT, p, &p);
1438 g_assert_not_reached ();
1440 case MONO_WRAPPER_SYNCHRONIZED:
1441 case MONO_WRAPPER_MANAGED_TO_NATIVE:
1442 case MONO_WRAPPER_RUNTIME_INVOKE: {
1445 m = mono_marshal_method_from_wrapper (method);
1447 g_assert (m != method);
1448 encode_method_ref (acfg, m, p, &p);
1452 g_assert_not_reached ();
1454 } else if (mono_method_signature (method)->is_inflated) {
1456 * This is a generic method, find the original token which referenced it and
1458 * Obtain the token from information recorded by the JIT.
1460 ji = g_hash_table_lookup (acfg->token_info_hash, method);
1462 image_index = get_image_index (acfg, ji->image);
1463 g_assert (image_index < MAX_IMAGE_INDEX);
1466 encode_value ((MONO_AOT_METHODREF_METHODSPEC << 24), p, &p);
1467 encode_value (image_index, p, &p);
1468 encode_value (token, p, &p);
1470 MonoMethod *declaring;
1471 MonoGenericContext *context = mono_method_get_context (method);
1473 g_assert (method->is_inflated);
1474 declaring = ((MonoMethodInflated*)method)->declaring;
1477 * This might be a non-generic method of a generic instance, which
1478 * doesn't have a token since the reference is generated by the JIT
1479 * like Nullable:Box/Unbox, or by generic sharing.
1482 encode_value ((MONO_AOT_METHODREF_GINST << 24), p, &p);
1483 /* Encode the klass */
1484 encode_klass_ref (acfg, method->klass, p, &p);
1485 /* Encode the method */
1486 image_index = get_image_index (acfg, method->klass->image);
1487 g_assert (image_index < MAX_IMAGE_INDEX);
1488 g_assert (declaring->token);
1489 token = declaring->token;
1490 g_assert (mono_metadata_token_table (token) == MONO_TABLE_METHOD);
1491 encode_value (image_index, p, &p);
1492 encode_value (token, p, &p);
1493 encode_generic_context (acfg, context, p, &p);
1495 } else if (token == 0) {
1496 /* This might be a method of a constructed type like int[,].Set */
1497 /* Obtain the token from information recorded by the JIT */
1498 ji = g_hash_table_lookup (acfg->token_info_hash, method);
1500 image_index = get_image_index (acfg, ji->image);
1501 g_assert (image_index < MAX_IMAGE_INDEX);
1504 encode_value ((MONO_AOT_METHODREF_METHODSPEC << 24), p, &p);
1505 encode_value (image_index, p, &p);
1506 encode_value (token, p, &p);
1509 g_assert (method->klass->rank);
1511 /* Encode directly */
1512 encode_value ((MONO_AOT_METHODREF_ARRAY << 24), p, &p);
1513 encode_klass_ref (acfg, method->klass, p, &p);
1514 if (!strcmp (method->name, ".ctor") && mono_method_signature (method)->param_count == method->klass->rank)
1515 encode_value (0, p, &p);
1516 else if (!strcmp (method->name, ".ctor") && mono_method_signature (method)->param_count == method->klass->rank * 2)
1517 encode_value (1, p, &p);
1518 else if (!strcmp (method->name, "Get"))
1519 encode_value (2, p, &p);
1520 else if (!strcmp (method->name, "Address"))
1521 encode_value (3, p, &p);
1522 else if (!strcmp (method->name, "Set"))
1523 encode_value (4, p, &p);
1525 g_assert_not_reached ();
1528 g_assert (mono_metadata_token_table (token) == MONO_TABLE_METHOD);
1529 encode_value ((image_index << 24) | mono_metadata_token_index (token), p, &p);
1535 compare_patches (gconstpointer a, gconstpointer b)
1539 i = (*(MonoJumpInfo**)a)->ip.i;
1540 j = (*(MonoJumpInfo**)b)->ip.i;
1554 * Return whenever PATCH_INFO refers to a direct call, and thus requires a
1557 static inline gboolean
1558 is_plt_patch (MonoJumpInfo *patch_info)
1560 switch (patch_info->type) {
1561 case MONO_PATCH_INFO_METHOD:
1562 case MONO_PATCH_INFO_INTERNAL_METHOD:
1563 case MONO_PATCH_INFO_JIT_ICALL_ADDR:
1564 case MONO_PATCH_INFO_ICALL_ADDR:
1565 case MONO_PATCH_INFO_CLASS_INIT:
1566 case MONO_PATCH_INFO_RGCTX_FETCH:
1567 case MONO_PATCH_INFO_GENERIC_CLASS_INIT:
1568 case MONO_PATCH_INFO_MONITOR_ENTER:
1569 case MONO_PATCH_INFO_MONITOR_EXIT:
1570 case MONO_PATCH_INFO_LLVM_IMT_TRAMPOLINE:
1578 get_plt_offset (MonoAotCompile *acfg, MonoJumpInfo *patch_info)
1582 if (is_plt_patch (patch_info)) {
1583 int idx = GPOINTER_TO_UINT (g_hash_table_lookup (acfg->patch_to_plt_offset, patch_info));
1585 // FIXME: This breaks the calculation of final_got_size
1586 if (!acfg->llvm && patch_info->type == MONO_PATCH_INFO_METHOD && (patch_info->data.method->iflags & METHOD_IMPL_ATTRIBUTE_SYNCHRONIZED)) {
1588 * Allocate a separate PLT slot for each such patch, since some plt
1589 * entries will refer to the method itself, and some will refer to the
1598 MonoJumpInfo *new_ji = mono_patch_info_dup_mp (acfg->mempool, patch_info);
1600 g_assert (!acfg->final_got_size);
1602 res = acfg->plt_offset;
1603 g_hash_table_insert (acfg->plt_offset_to_patch, GUINT_TO_POINTER (res), new_ji);
1604 g_hash_table_insert (acfg->patch_to_plt_offset, new_ji, GUINT_TO_POINTER (res));
1605 acfg->plt_offset ++;
1615 * Returns the offset of the GOT slot where the runtime object resulting from resolving
1616 * JI could be found if it exists, otherwise allocates a new one.
1619 get_got_offset (MonoAotCompile *acfg, MonoJumpInfo *ji)
1623 got_offset = GPOINTER_TO_UINT (g_hash_table_lookup (acfg->patch_to_got_offset_by_type [ji->type], ji));
1625 return got_offset - 1;
1627 g_assert (!acfg->final_got_size);
1629 got_offset = acfg->got_offset;
1630 acfg->got_offset ++;
1632 acfg->stats.got_slots ++;
1633 acfg->stats.got_slot_types [ji->type] ++;
1635 g_hash_table_insert (acfg->patch_to_got_offset, ji, GUINT_TO_POINTER (got_offset + 1));
1636 g_hash_table_insert (acfg->patch_to_got_offset_by_type [ji->type], ji, GUINT_TO_POINTER (got_offset + 1));
1637 g_ptr_array_add (acfg->got_patches, ji);
1642 /* Add a method to the list of methods which need to be emitted */
1644 add_method_with_index (MonoAotCompile *acfg, MonoMethod *method, int index, gboolean extra)
1647 if (!g_hash_table_lookup (acfg->method_indexes, method)) {
1648 g_ptr_array_add (acfg->methods, method);
1649 g_hash_table_insert (acfg->method_indexes, method, GUINT_TO_POINTER (index + 1));
1650 acfg->nmethods = acfg->methods->len + 1;
1653 if (method->wrapper_type || extra)
1654 g_ptr_array_add (acfg->extra_methods, method);
1658 get_method_index (MonoAotCompile *acfg, MonoMethod *method)
1660 int index = GPOINTER_TO_UINT (g_hash_table_lookup (acfg->method_indexes, method));
1668 add_method_full (MonoAotCompile *acfg, MonoMethod *method, gboolean extra, int depth)
1672 index = GPOINTER_TO_UINT (g_hash_table_lookup (acfg->method_indexes, method));
1676 index = acfg->method_index;
1677 add_method_with_index (acfg, method, index, extra);
1679 /* FIXME: Fix quadratic behavior */
1680 acfg->method_order = g_list_append (acfg->method_order, GUINT_TO_POINTER (index));
1682 g_hash_table_insert (acfg->method_depth, method, GUINT_TO_POINTER (depth));
1684 acfg->method_index ++;
1690 add_method (MonoAotCompile *acfg, MonoMethod *method)
1692 return add_method_full (acfg, method, FALSE, 0);
1696 add_extra_method (MonoAotCompile *acfg, MonoMethod *method)
1698 add_method_full (acfg, method, TRUE, 0);
1702 add_extra_method_with_depth (MonoAotCompile *acfg, MonoMethod *method, int depth)
1704 add_method_full (acfg, method, TRUE, depth);
1708 add_jit_icall_wrapper (gpointer key, gpointer value, gpointer user_data)
1710 MonoAotCompile *acfg = user_data;
1711 MonoJitICallInfo *callinfo = value;
1712 MonoMethod *wrapper;
1718 name = g_strdup_printf ("__icall_wrapper_%s", callinfo->name);
1719 wrapper = mono_marshal_get_icall_wrapper (callinfo->sig, name, callinfo->func, check_for_pending_exc);
1722 add_method (acfg, wrapper);
1726 get_runtime_invoke_sig (MonoMethodSignature *sig)
1728 MonoMethodBuilder *mb;
1731 mb = mono_mb_new (mono_defaults.object_class, "FOO", MONO_WRAPPER_NONE);
1732 m = mono_mb_create_method (mb, sig, 16);
1733 return mono_marshal_get_runtime_invoke (m, FALSE);
1737 can_marshal_struct (MonoClass *klass)
1739 MonoClassField *field;
1740 gboolean can_marshal = TRUE;
1741 gpointer iter = NULL;
1743 if ((klass->flags & TYPE_ATTRIBUTE_LAYOUT_MASK) == TYPE_ATTRIBUTE_AUTO_LAYOUT)
1746 /* Only allow a few field types to avoid asserts in the marshalling code */
1747 while ((field = mono_class_get_fields (klass, &iter))) {
1748 if ((field->type->attrs & FIELD_ATTRIBUTE_STATIC))
1751 switch (field->type->type) {
1756 case MONO_TYPE_BOOLEAN:
1759 case MONO_TYPE_CHAR:
1767 case MONO_TYPE_STRING:
1769 case MONO_TYPE_VALUETYPE:
1770 if (!can_marshal_struct (mono_class_from_mono_type (field->type)))
1771 can_marshal = FALSE;
1774 can_marshal = FALSE;
1780 /* Its hard to compute whenever these can be marshalled or not */
1781 if (!strcmp (klass->name_space, "System.Net.NetworkInformation.MacOsStructs"))
1788 add_wrappers (MonoAotCompile *acfg)
1790 MonoMethod *method, *m;
1792 MonoMethodSignature *sig, *csig;
1796 * FIXME: Instead of AOTing all the wrappers, it might be better to redesign them
1797 * so there is only one wrapper of a given type, or inlining their contents into their
1802 * FIXME: This depends on the fact that different wrappers have different
1806 for (i = 0; i < acfg->image->tables [MONO_TABLE_METHOD].rows; ++i) {
1808 guint32 token = MONO_TOKEN_METHOD_DEF | (i + 1);
1809 gboolean skip = FALSE;
1811 method = mono_get_method (acfg->image, token, NULL);
1813 if ((method->flags & METHOD_ATTRIBUTE_PINVOKE_IMPL) ||
1814 (method->iflags & METHOD_IMPL_ATTRIBUTE_RUNTIME) ||
1815 (method->flags & METHOD_ATTRIBUTE_ABSTRACT))
1818 if (method->is_generic || method->klass->generic_container)
1821 /* Skip methods which can not be handled by get_runtime_invoke () */
1822 sig = mono_method_signature (method);
1823 if ((sig->ret->type == MONO_TYPE_PTR) ||
1824 (sig->ret->type == MONO_TYPE_TYPEDBYREF))
1827 for (j = 0; j < sig->param_count; j++) {
1828 if (sig->params [j]->type == MONO_TYPE_TYPEDBYREF)
1832 #ifdef MONO_ARCH_DYN_CALL_SUPPORTED
1833 if (!method->klass->contextbound) {
1834 MonoDynCallInfo *info = mono_arch_dyn_call_prepare (sig);
1837 /* Supported by the dynamic runtime-invoke wrapper */
1845 //printf ("%s\n", mono_method_full_name (method, TRUE));
1846 add_method (acfg, mono_marshal_get_runtime_invoke (method, FALSE));
1850 if (strcmp (acfg->image->assembly->aname.name, "mscorlib") == 0) {
1851 #ifdef MONO_ARCH_HAVE_TLS_GET
1852 MonoMethodDesc *desc;
1853 MonoMethod *orig_method;
1857 /* Runtime invoke wrappers */
1859 /* void runtime-invoke () [.cctor] */
1860 csig = mono_metadata_signature_alloc (mono_defaults.corlib, 0);
1861 csig->ret = &mono_defaults.void_class->byval_arg;
1862 add_method (acfg, get_runtime_invoke_sig (csig));
1864 /* void runtime-invoke () [Finalize] */
1865 csig = mono_metadata_signature_alloc (mono_defaults.corlib, 0);
1867 csig->ret = &mono_defaults.void_class->byval_arg;
1868 add_method (acfg, get_runtime_invoke_sig (csig));
1870 /* void runtime-invoke (string) [exception ctor] */
1871 csig = mono_metadata_signature_alloc (mono_defaults.corlib, 1);
1873 csig->ret = &mono_defaults.void_class->byval_arg;
1874 csig->params [0] = &mono_defaults.string_class->byval_arg;
1875 add_method (acfg, get_runtime_invoke_sig (csig));
1877 /* void runtime-invoke (string, string) [exception ctor] */
1878 csig = mono_metadata_signature_alloc (mono_defaults.corlib, 2);
1880 csig->ret = &mono_defaults.void_class->byval_arg;
1881 csig->params [0] = &mono_defaults.string_class->byval_arg;
1882 csig->params [1] = &mono_defaults.string_class->byval_arg;
1883 add_method (acfg, get_runtime_invoke_sig (csig));
1885 /* string runtime-invoke () [Exception.ToString ()] */
1886 csig = mono_metadata_signature_alloc (mono_defaults.corlib, 0);
1888 csig->ret = &mono_defaults.string_class->byval_arg;
1889 add_method (acfg, get_runtime_invoke_sig (csig));
1891 /* void runtime-invoke (string, Exception) [exception ctor] */
1892 csig = mono_metadata_signature_alloc (mono_defaults.corlib, 2);
1894 csig->ret = &mono_defaults.void_class->byval_arg;
1895 csig->params [0] = &mono_defaults.string_class->byval_arg;
1896 csig->params [1] = &mono_defaults.exception_class->byval_arg;
1897 add_method (acfg, get_runtime_invoke_sig (csig));
1899 /* Assembly runtime-invoke (string, bool) [DoAssemblyResolve] */
1900 csig = mono_metadata_signature_alloc (mono_defaults.corlib, 2);
1902 csig->ret = &(mono_class_from_name (
1903 mono_defaults.corlib, "System.Reflection", "Assembly"))->byval_arg;
1904 csig->params [0] = &mono_defaults.string_class->byval_arg;
1905 csig->params [1] = &mono_defaults.boolean_class->byval_arg;
1906 add_method (acfg, get_runtime_invoke_sig (csig));
1908 /* runtime-invoke used by finalizers */
1909 add_method (acfg, mono_marshal_get_runtime_invoke (mono_class_get_method_from_name_flags (mono_defaults.object_class, "Finalize", 0, 0), TRUE));
1911 /* This is used by mono_runtime_capture_context () */
1912 method = mono_get_context_capture_method ();
1914 add_method (acfg, mono_marshal_get_runtime_invoke (method, FALSE));
1916 #ifdef MONO_ARCH_DYN_CALL_SUPPORTED
1917 add_method (acfg, mono_marshal_get_runtime_invoke_dynamic ());
1920 /* JIT icall wrappers */
1921 /* FIXME: locking */
1922 g_hash_table_foreach (mono_get_jit_icall_info (), add_jit_icall_wrapper, acfg);
1925 add_method (acfg, mono_marshal_get_stelemref ());
1927 #ifdef MONO_ARCH_HAVE_TLS_GET
1928 /* Managed Allocators */
1929 nallocators = mono_gc_get_managed_allocator_types ();
1930 for (i = 0; i < nallocators; ++i) {
1931 m = mono_gc_get_managed_allocator_by_type (i);
1933 add_method (acfg, m);
1936 /* Monitor Enter/Exit */
1937 desc = mono_method_desc_new ("Monitor:Enter", FALSE);
1938 orig_method = mono_method_desc_search_in_class (desc, mono_defaults.monitor_class);
1939 g_assert (orig_method);
1940 mono_method_desc_free (desc);
1941 method = mono_monitor_get_fast_path (orig_method);
1943 add_method (acfg, method);
1945 desc = mono_method_desc_new ("Monitor:Exit", FALSE);
1946 orig_method = mono_method_desc_search_in_class (desc, mono_defaults.monitor_class);
1947 g_assert (orig_method);
1948 mono_method_desc_free (desc);
1949 method = mono_monitor_get_fast_path (orig_method);
1951 add_method (acfg, method);
1956 * remoting-invoke-with-check wrappers are very frequent, so avoid emitting them,
1957 * we use the original method instead at runtime.
1958 * Since full-aot doesn't support remoting, this is not a problem.
1961 /* remoting-invoke wrappers */
1962 for (i = 0; i < acfg->image->tables [MONO_TABLE_METHOD].rows; ++i) {
1963 MonoMethodSignature *sig;
1965 token = MONO_TOKEN_METHOD_DEF | (i + 1);
1966 method = mono_get_method (acfg->image, token, NULL);
1968 sig = mono_method_signature (method);
1970 if (sig->hasthis && (method->klass->marshalbyref || method->klass == mono_defaults.object_class)) {
1971 m = mono_marshal_get_remoting_invoke_with_check (method);
1973 add_method (acfg, m);
1978 /* delegate-invoke wrappers */
1979 for (i = 0; i < acfg->image->tables [MONO_TABLE_TYPEDEF].rows; ++i) {
1982 token = MONO_TOKEN_TYPE_DEF | (i + 1);
1983 klass = mono_class_get (acfg->image, token);
1985 if (klass->delegate && klass != mono_defaults.delegate_class && klass != mono_defaults.multicastdelegate_class && !klass->generic_container) {
1986 method = mono_get_delegate_invoke (klass);
1988 m = mono_marshal_get_delegate_invoke (method, NULL);
1990 add_method (acfg, m);
1992 method = mono_class_get_method_from_name_flags (klass, "BeginInvoke", -1, 0);
1993 add_method (acfg, mono_marshal_get_delegate_begin_invoke (method));
1995 method = mono_class_get_method_from_name_flags (klass, "EndInvoke", -1, 0);
1996 add_method (acfg, mono_marshal_get_delegate_end_invoke (method));
2000 /* Synchronized wrappers */
2001 for (i = 0; i < acfg->image->tables [MONO_TABLE_METHOD].rows; ++i) {
2002 token = MONO_TOKEN_METHOD_DEF | (i + 1);
2003 method = mono_get_method (acfg->image, token, NULL);
2005 if (method->iflags & METHOD_IMPL_ATTRIBUTE_SYNCHRONIZED)
2006 add_method (acfg, mono_marshal_get_synchronized_wrapper (method));
2009 /* pinvoke wrappers */
2010 for (i = 0; i < acfg->image->tables [MONO_TABLE_METHOD].rows; ++i) {
2012 guint32 token = MONO_TOKEN_METHOD_DEF | (i + 1);
2014 method = mono_get_method (acfg->image, token, NULL);
2016 if ((method->flags & METHOD_ATTRIBUTE_PINVOKE_IMPL) ||
2017 (method->iflags & METHOD_IMPL_ATTRIBUTE_INTERNAL_CALL)) {
2018 add_method (acfg, mono_marshal_get_native_wrapper (method, TRUE, TRUE));
2022 /* StructureToPtr/PtrToStructure wrappers */
2023 for (i = 0; i < acfg->image->tables [MONO_TABLE_TYPEDEF].rows; ++i) {
2026 token = MONO_TOKEN_TYPE_DEF | (i + 1);
2027 klass = mono_class_get (acfg->image, token);
2029 if (klass->valuetype && !klass->generic_container && can_marshal_struct (klass)) {
2030 add_method (acfg, mono_marshal_get_struct_to_ptr (klass));
2031 add_method (acfg, mono_marshal_get_ptr_to_struct (klass));
2037 has_type_vars (MonoClass *klass)
2039 if ((klass->byval_arg.type == MONO_TYPE_VAR) || (klass->byval_arg.type == MONO_TYPE_MVAR))
2042 return has_type_vars (klass->element_class);
2043 if (klass->generic_class) {
2044 MonoGenericContext *context = &klass->generic_class->context;
2045 if (context->class_inst) {
2048 for (i = 0; i < context->class_inst->type_argc; ++i)
2049 if (has_type_vars (mono_class_from_mono_type (context->class_inst->type_argv [i])))
2057 method_has_type_vars (MonoMethod *method)
2059 if (has_type_vars (method->klass))
2062 if (method->is_inflated) {
2063 MonoGenericContext *context = mono_method_get_context (method);
2064 if (context->method_inst) {
2067 for (i = 0; i < context->method_inst->type_argc; ++i)
2068 if (has_type_vars (mono_class_from_mono_type (context->method_inst->type_argv [i])))
2076 * add_generic_class:
2078 * Add all methods of a generic class.
2081 add_generic_class (MonoAotCompile *acfg, MonoClass *klass)
2086 mono_class_init (klass);
2088 if (klass->generic_class && klass->generic_class->context.class_inst->is_open)
2091 if (has_type_vars (klass))
2094 if (!klass->generic_class && !klass->rank)
2098 while ((method = mono_class_get_methods (klass, &iter))) {
2099 if (mono_method_is_generic_sharable_impl (method, FALSE))
2103 if (method->is_generic)
2108 * FIXME: Instances which are referenced by these methods are not added,
2109 * for example Array.Resize<int> for List<int>.Add ().
2111 add_extra_method (acfg, method);
2114 if (klass->delegate) {
2115 method = mono_get_delegate_invoke (klass);
2117 method = mono_marshal_get_delegate_invoke (method, NULL);
2119 add_method (acfg, method);
2123 * For ICollection<T>, add instances of the helper methods
2124 * in Array, since a T[] could be cast to ICollection<T>.
2126 if (klass->image == mono_defaults.corlib && !strcmp (klass->name_space, "System.Collections.Generic") &&
2127 (!strcmp(klass->name, "ICollection`1") || !strcmp (klass->name, "IEnumerable`1") || !strcmp (klass->name, "IList`1") || !strcmp (klass->name, "IEnumerator`1"))) {
2128 MonoClass *tclass = mono_class_from_mono_type (klass->generic_class->context.class_inst->type_argv [0]);
2129 MonoClass *array_class = mono_bounded_array_class_get (tclass, 1, FALSE);
2133 if (!strcmp (klass->name, "IEnumerator`1"))
2134 name_prefix = g_strdup_printf ("%s.%s", klass->name_space, "IEnumerable`1");
2136 name_prefix = g_strdup_printf ("%s.%s", klass->name_space, klass->name);
2138 /* Add the T[]/InternalEnumerator class */
2139 if (!strcmp (klass->name, "IEnumerable`1") || !strcmp (klass->name, "IEnumerator`1")) {
2143 while ((nclass = mono_class_get_nested_types (array_class->parent, &iter))) {
2144 if (!strcmp (nclass->name, "InternalEnumerator`1"))
2148 nclass = mono_class_inflate_generic_class (nclass, mono_generic_class_get_context (klass->generic_class));
2149 add_generic_class (acfg, nclass);
2153 while ((method = mono_class_get_methods (array_class, &iter))) {
2154 if (strstr (method->name, name_prefix)) {
2155 MonoMethod *m = mono_aot_get_array_helper_from_wrapper (method);
2156 add_extra_method (acfg, m);
2160 g_free (name_prefix);
2163 /* Add an instance of GenericComparer<T> which is created dynamically by Comparer<T> */
2164 if (klass->image == mono_defaults.corlib && !strcmp (klass->name_space, "System.Collections.Generic") && !strcmp (klass->name, "Comparer`1")) {
2165 MonoClass *tclass = mono_class_from_mono_type (klass->generic_class->context.class_inst->type_argv [0]);
2166 MonoClass *icomparable, *gcomparer;
2167 MonoGenericContext ctx;
2168 MonoType *args [16];
2170 memset (&ctx, 0, sizeof (ctx));
2172 icomparable = mono_class_from_name (mono_defaults.corlib, "System", "IComparable`1");
2173 g_assert (icomparable);
2174 args [0] = &tclass->byval_arg;
2175 ctx.class_inst = mono_metadata_get_generic_inst (1, args);
2177 if (mono_class_is_assignable_from (mono_class_inflate_generic_class (icomparable, &ctx), tclass)) {
2178 gcomparer = mono_class_from_name (mono_defaults.corlib, "System.Collections.Generic", "GenericComparer`1");
2179 g_assert (gcomparer);
2180 add_generic_class (acfg, mono_class_inflate_generic_class (gcomparer, &ctx));
2186 add_instances_of (MonoAotCompile *acfg, MonoClass *klass, MonoType **insts, int ninsts)
2189 MonoGenericContext ctx;
2190 MonoType *args [16];
2192 memset (&ctx, 0, sizeof (ctx));
2194 for (i = 0; i < ninsts; ++i) {
2195 args [0] = insts [i];
2196 ctx.class_inst = mono_metadata_get_generic_inst (1, args);
2197 add_generic_class (acfg, mono_class_inflate_generic_class (klass, &ctx));
2202 * add_generic_instances:
2204 * Add instances referenced by the METHODSPEC/TYPESPEC table.
2207 add_generic_instances (MonoAotCompile *acfg)
2212 MonoMethodHeader *header;
2213 MonoMethodSignature *sig;
2214 MonoGenericContext *context;
2216 for (i = 0; i < acfg->image->tables [MONO_TABLE_METHODSPEC].rows; ++i) {
2217 token = MONO_TOKEN_METHOD_SPEC | (i + 1);
2218 method = mono_get_method (acfg->image, token, NULL);
2220 context = mono_method_get_context (method);
2221 if (context && ((context->class_inst && context->class_inst->is_open) ||
2222 (context->method_inst && context->method_inst->is_open)))
2225 if (method->klass->image != acfg->image)
2228 if (mono_method_is_generic_sharable_impl (method, FALSE))
2232 add_extra_method (acfg, method);
2235 for (i = 0; i < acfg->image->tables [MONO_TABLE_TYPESPEC].rows; ++i) {
2238 token = MONO_TOKEN_TYPE_SPEC | (i + 1);
2240 klass = mono_class_get (acfg->image, token);
2241 if (!klass || klass->rank)
2244 add_generic_class (acfg, klass);
2247 /* Add types of args/locals */
2248 for (i = 0; i < acfg->methods->len; ++i) {
2251 method = g_ptr_array_index (acfg->methods, i);
2253 sig = mono_method_signature (method);
2256 for (j = 0; j < sig->param_count; ++j)
2257 if (sig->params [j]->type == MONO_TYPE_GENERICINST)
2258 add_generic_class (acfg, mono_class_from_mono_type (sig->params [j]));
2261 header = mono_method_get_header (method);
2264 for (j = 0; j < header->num_locals; ++j)
2265 if (header->locals [j]->type == MONO_TYPE_GENERICINST)
2266 add_generic_class (acfg, mono_class_from_mono_type (header->locals [j]));
2270 if (acfg->image == mono_defaults.corlib) {
2272 MonoType *insts [256];
2275 insts [ninsts ++] = &mono_defaults.byte_class->byval_arg;
2276 insts [ninsts ++] = &mono_defaults.sbyte_class->byval_arg;
2277 insts [ninsts ++] = &mono_defaults.int16_class->byval_arg;
2278 insts [ninsts ++] = &mono_defaults.uint16_class->byval_arg;
2279 insts [ninsts ++] = &mono_defaults.int32_class->byval_arg;
2280 insts [ninsts ++] = &mono_defaults.uint32_class->byval_arg;
2281 insts [ninsts ++] = &mono_defaults.int64_class->byval_arg;
2282 insts [ninsts ++] = &mono_defaults.uint64_class->byval_arg;
2283 insts [ninsts ++] = &mono_defaults.single_class->byval_arg;
2284 insts [ninsts ++] = &mono_defaults.double_class->byval_arg;
2285 insts [ninsts ++] = &mono_defaults.char_class->byval_arg;
2286 insts [ninsts ++] = &mono_defaults.boolean_class->byval_arg;
2288 /* Add GenericComparer<T> instances for primitive types for Enum.ToString () */
2289 klass = mono_class_from_name (acfg->image, "System.Collections.Generic", "GenericComparer`1");
2291 add_instances_of (acfg, klass, insts, ninsts);
2292 klass = mono_class_from_name (acfg->image, "System.Collections.Generic", "GenericEqualityComparer`1");
2294 add_instances_of (acfg, klass, insts, ninsts);
2296 /* Add instances of the array generic interfaces for primitive types */
2297 /* This will add instances of the InternalArray_ helper methods in Array too */
2298 klass = mono_class_from_name (acfg->image, "System.Collections.Generic", "ICollection`1");
2300 add_instances_of (acfg, klass, insts, ninsts);
2301 klass = mono_class_from_name (acfg->image, "System.Collections.Generic", "IList`1");
2303 add_instances_of (acfg, klass, insts, ninsts);
2304 klass = mono_class_from_name (acfg->image, "System.Collections.Generic", "IEnumerable`1");
2306 add_instances_of (acfg, klass, insts, ninsts);
2309 * Add a managed-to-native wrapper of Array.GetGenericValueImpl<object>, which is
2310 * used for all instances of GetGenericValueImpl by the AOT runtime.
2313 MonoGenericContext ctx;
2314 MonoType *args [16];
2315 MonoMethod *get_method;
2316 MonoClass *array_klass = mono_array_class_get (mono_defaults.object_class, 1)->parent;
2318 get_method = mono_class_get_method_from_name (array_klass, "GetGenericValueImpl", 2);
2321 memset (&ctx, 0, sizeof (ctx));
2322 args [0] = &mono_defaults.object_class->byval_arg;
2323 ctx.method_inst = mono_metadata_get_generic_inst (1, args);
2324 add_extra_method (acfg, mono_marshal_get_native_wrapper (mono_class_inflate_generic_method (get_method, &ctx), TRUE, TRUE));
2331 * is_direct_callable:
2333 * Return whenever the method identified by JI is directly callable without
2334 * going through the PLT.
2337 is_direct_callable (MonoAotCompile *acfg, MonoMethod *method, MonoJumpInfo *patch_info)
2339 if ((patch_info->type == MONO_PATCH_INFO_METHOD) && (patch_info->data.method->klass->image == acfg->image)) {
2340 MonoCompile *callee_cfg = g_hash_table_lookup (acfg->method_to_cfg, patch_info->data.method);
2342 gboolean direct_callable = TRUE;
2344 if (direct_callable && !(!callee_cfg->has_got_slots && (callee_cfg->method->klass->flags & TYPE_ATTRIBUTE_BEFORE_FIELD_INIT)))
2345 direct_callable = FALSE;
2346 if ((callee_cfg->method->iflags & METHOD_IMPL_ATTRIBUTE_SYNCHRONIZED) && (!method || method->wrapper_type != MONO_WRAPPER_SYNCHRONIZED))
2347 // FIXME: Maybe call the wrapper directly ?
2348 direct_callable = FALSE;
2350 if (direct_callable)
2359 * emit_and_reloc_code:
2361 * Emit the native code in CODE, handling relocations along the way. If GOT_ONLY
2362 * is true, calls are made through the GOT too. This is used for emitting trampolines
2363 * in full-aot mode, since calls made from trampolines couldn't go through the PLT,
2364 * since trampolines are needed to make PTL work.
2367 emit_and_reloc_code (MonoAotCompile *acfg, MonoMethod *method, guint8 *code, guint32 code_len, MonoJumpInfo *relocs, gboolean got_only)
2369 int i, pindex, start_index, method_index;
2371 MonoJumpInfo *patch_info;
2372 MonoMethodHeader *header;
2373 gboolean skip, direct_call;
2375 char direct_call_target [128];
2378 header = mono_method_get_header (method);
2380 method_index = get_method_index (acfg, method);
2383 /* Collect and sort relocations */
2384 patches = g_ptr_array_new ();
2385 for (patch_info = relocs; patch_info; patch_info = patch_info->next)
2386 g_ptr_array_add (patches, patch_info);
2387 g_ptr_array_sort (patches, compare_patches);
2390 for (i = 0; i < code_len; i++) {
2392 for (pindex = start_index; pindex < patches->len; ++pindex) {
2393 patch_info = g_ptr_array_index (patches, pindex);
2394 if (patch_info->ip.i >= i)
2398 #ifdef MONO_ARCH_AOT_SUPPORTED
2400 if (patch_info && (patch_info->ip.i == i) && (pindex < patches->len)) {
2401 start_index = pindex;
2403 switch (patch_info->type) {
2404 case MONO_PATCH_INFO_NONE:
2406 case MONO_PATCH_INFO_GOT_OFFSET: {
2409 arch_emit_got_offset (acfg, code + i, &code_size);
2412 patch_info->type = MONO_PATCH_INFO_NONE;
2417 * If this patch is a call, try emitting a direct call instead of
2418 * through a PLT entry. This is possible if the called method is in
2419 * the same assembly and requires no initialization.
2421 direct_call = FALSE;
2422 if ((patch_info->type == MONO_PATCH_INFO_METHOD) && (patch_info->data.method->klass->image == acfg->image)) {
2423 if (!got_only && is_direct_callable (acfg, method, patch_info)) {
2424 MonoCompile *callee_cfg = g_hash_table_lookup (acfg->method_to_cfg, patch_info->data.method);
2425 //printf ("DIRECT: %s %s\n", method ? mono_method_full_name (method, TRUE) : "", mono_method_full_name (callee_cfg->method, TRUE));
2427 sprintf (direct_call_target, "%sm_%x", acfg->temp_prefix, get_method_index (acfg, callee_cfg->orig_method));
2428 patch_info->type = MONO_PATCH_INFO_NONE;
2429 acfg->stats.direct_calls ++;
2432 acfg->stats.all_calls ++;
2435 if (!got_only && !direct_call) {
2436 int plt_offset = get_plt_offset (acfg, patch_info);
2437 if (plt_offset != -1) {
2438 /* This patch has a PLT entry, so we must emit a call to the PLT entry */
2440 sprintf (direct_call_target, "%sp_%d", acfg->temp_prefix, plt_offset);
2442 /* Nullify the patch */
2443 patch_info->type = MONO_PATCH_INFO_NONE;
2450 arch_emit_direct_call (acfg, direct_call_target, &call_size);
2455 got_slot = get_got_offset (acfg, patch_info);
2457 arch_emit_got_access (acfg, code + i, got_slot, &code_size);
2464 #endif /* MONO_ARCH_AOT_SUPPORTED */
2467 /* Find next patch */
2469 for (pindex = start_index; pindex < patches->len; ++pindex) {
2470 patch_info = g_ptr_array_index (patches, pindex);
2471 if (patch_info->ip.i >= i)
2475 /* Try to emit multiple bytes at once */
2476 if (pindex < patches->len && patch_info->ip.i > i) {
2477 emit_bytes (acfg, code + i, patch_info->ip.i - i);
2478 i = patch_info->ip.i - 1;
2480 emit_bytes (acfg, code + i, 1);
2489 * Modify SYMBOL so it only includes characters permissible in symbols.
2492 sanitize_symbol (char *symbol)
2494 int i, len = strlen (symbol);
2496 for (i = 0; i < len; ++i)
2497 if (!isalnum (symbol [i]) && (symbol [i] != '_'))
2502 get_debug_sym (MonoMethod *method, const char *prefix, GHashTable *cache)
2504 char *name1, *name2, *cached;
2505 int i, j, len, count;
2507 name1 = mono_method_full_name (method, TRUE);
2508 len = strlen (name1);
2509 name2 = malloc (strlen (prefix) + len + 16);
2510 memcpy (name2, prefix, strlen (prefix));
2511 j = strlen (prefix);
2512 for (i = 0; i < len; ++i) {
2513 if (isalnum (name1 [i])) {
2514 name2 [j ++] = name1 [i];
2515 } else if (name1 [i] == ' ' && name1 [i + 1] == '(' && name1 [i + 2] == ')') {
2517 } else if (name1 [i] == ',' && name1 [i + 1] == ' ') {
2520 } else if (name1 [i] == '(' || name1 [i] == ')' || name1 [i] == '>') {
2529 while (g_hash_table_lookup (cache, name2)) {
2530 sprintf (name2 + j, "_%d", count);
2534 cached = g_strdup (name2);
2535 g_hash_table_insert (cache, cached, cached);
2541 emit_method_code (MonoAotCompile *acfg, MonoCompile *cfg)
2546 char *debug_sym = NULL;
2548 int func_alignment = AOT_FUNC_ALIGNMENT;
2549 MonoMethodHeader *header;
2551 method = cfg->orig_method;
2552 code = cfg->native_code;
2553 header = mono_method_get_header (method);
2555 method_index = get_method_index (acfg, method);
2557 /* Emit unbox trampoline */
2558 if (acfg->aot_opts.full_aot && cfg->orig_method->klass->valuetype && (method->flags & METHOD_ATTRIBUTE_VIRTUAL)) {
2559 char call_target [256];
2561 if (!method->wrapper_type && !method->is_inflated) {
2562 g_assert (method->token);
2563 sprintf (symbol, "ut_%d", mono_metadata_token_index (method->token) - 1);
2565 sprintf (symbol, "ut_e_%d", get_method_index (acfg, method));
2568 emit_section_change (acfg, ".text", 0);
2569 emit_global (acfg, symbol, TRUE);
2570 emit_label (acfg, symbol);
2572 sprintf (call_target, "%sm_%x", acfg->temp_prefix, method_index);
2574 arch_emit_unbox_trampoline (acfg, cfg->orig_method, cfg->generic_sharing_context, call_target);
2577 /* Make the labels local */
2578 sprintf (symbol, "%sm_%x", acfg->temp_prefix, method_index);
2580 emit_section_change (acfg, ".text", 0);
2581 emit_alignment (acfg, func_alignment);
2582 emit_label (acfg, symbol);
2584 if (acfg->aot_opts.write_symbols) {
2586 * Write a C style symbol for every method, this has two uses:
2587 * - it works on platforms where the dwarf debugging info is not
2589 * - it allows the setting of breakpoints of aot-ed methods.
2591 debug_sym = get_debug_sym (method, "", acfg->method_label_hash);
2593 sprintf (symbol, "%sme_%x", acfg->temp_prefix, method_index);
2594 emit_local_symbol (acfg, debug_sym, symbol, TRUE);
2595 emit_label (acfg, debug_sym);
2598 if (cfg->verbose_level > 0)
2599 g_print ("Method %s emitted as %s\n", mono_method_full_name (method, TRUE), symbol);
2601 acfg->stats.code_size += cfg->code_len;
2603 acfg->cfgs [method_index]->got_offset = acfg->got_offset;
2605 emit_and_reloc_code (acfg, method, code, cfg->code_len, cfg->patch_info, FALSE);
2609 if (acfg->aot_opts.write_symbols) {
2610 emit_symbol_size (acfg, debug_sym, ".");
2614 sprintf (symbol, "%sme_%x", acfg->temp_prefix, method_index);
2615 emit_label (acfg, symbol);
2621 * Encode PATCH_INFO into its disk representation.
2624 encode_patch (MonoAotCompile *acfg, MonoJumpInfo *patch_info, guint8 *buf, guint8 **endbuf)
2628 switch (patch_info->type) {
2629 case MONO_PATCH_INFO_NONE:
2631 case MONO_PATCH_INFO_IMAGE:
2632 encode_value (get_image_index (acfg, patch_info->data.image), p, &p);
2634 case MONO_PATCH_INFO_MSCORLIB_GOT_ADDR:
2636 case MONO_PATCH_INFO_METHOD_REL:
2637 encode_value ((gint)patch_info->data.offset, p, &p);
2639 case MONO_PATCH_INFO_SWITCH: {
2640 gpointer *table = (gpointer *)patch_info->data.table->table;
2643 encode_value (patch_info->data.table->table_size, p, &p);
2644 for (k = 0; k < patch_info->data.table->table_size; k++)
2645 encode_value ((int)(gssize)table [k], p, &p);
2648 case MONO_PATCH_INFO_METHODCONST:
2649 case MONO_PATCH_INFO_METHOD:
2650 case MONO_PATCH_INFO_METHOD_JUMP:
2651 case MONO_PATCH_INFO_ICALL_ADDR:
2652 case MONO_PATCH_INFO_METHOD_RGCTX:
2653 encode_method_ref (acfg, patch_info->data.method, p, &p);
2655 case MONO_PATCH_INFO_INTERNAL_METHOD:
2656 case MONO_PATCH_INFO_JIT_ICALL_ADDR: {
2657 guint32 len = strlen (patch_info->data.name);
2659 encode_value (len, p, &p);
2661 memcpy (p, patch_info->data.name, len);
2666 case MONO_PATCH_INFO_LDSTR: {
2667 guint32 image_index = get_image_index (acfg, patch_info->data.token->image);
2668 guint32 token = patch_info->data.token->token;
2669 g_assert (mono_metadata_token_code (token) == MONO_TOKEN_STRING);
2670 encode_value (image_index, p, &p);
2671 encode_value (patch_info->data.token->token - MONO_TOKEN_STRING, p, &p);
2674 case MONO_PATCH_INFO_RVA:
2675 case MONO_PATCH_INFO_DECLSEC:
2676 case MONO_PATCH_INFO_LDTOKEN:
2677 case MONO_PATCH_INFO_TYPE_FROM_HANDLE:
2678 encode_value (get_image_index (acfg, patch_info->data.token->image), p, &p);
2679 encode_value (patch_info->data.token->token, p, &p);
2680 encode_value (patch_info->data.token->has_context, p, &p);
2681 if (patch_info->data.token->has_context)
2682 encode_generic_context (acfg, &patch_info->data.token->context, p, &p);
2684 case MONO_PATCH_INFO_EXC_NAME: {
2685 MonoClass *ex_class;
2688 mono_class_from_name (mono_defaults.exception_class->image,
2689 "System", patch_info->data.target);
2690 g_assert (ex_class);
2691 encode_klass_ref (acfg, ex_class, p, &p);
2694 case MONO_PATCH_INFO_R4:
2695 encode_value (*((guint32 *)patch_info->data.target), p, &p);
2697 case MONO_PATCH_INFO_R8:
2698 encode_value (*((guint32 *)patch_info->data.target), p, &p);
2699 encode_value (*(((guint32 *)patch_info->data.target) + 1), p, &p);
2701 case MONO_PATCH_INFO_VTABLE:
2702 case MONO_PATCH_INFO_CLASS:
2703 case MONO_PATCH_INFO_IID:
2704 case MONO_PATCH_INFO_ADJUSTED_IID:
2705 encode_klass_ref (acfg, patch_info->data.klass, p, &p);
2707 case MONO_PATCH_INFO_CLASS_INIT:
2708 case MONO_PATCH_INFO_DELEGATE_TRAMPOLINE:
2709 encode_klass_ref (acfg, patch_info->data.klass, p, &p);
2711 case MONO_PATCH_INFO_FIELD:
2712 case MONO_PATCH_INFO_SFLDA:
2713 encode_field_info (acfg, patch_info->data.field, p, &p);
2715 case MONO_PATCH_INFO_INTERRUPTION_REQUEST_FLAG:
2717 case MONO_PATCH_INFO_RGCTX_FETCH: {
2718 MonoJumpInfoRgctxEntry *entry = patch_info->data.rgctx_entry;
2720 encode_method_ref (acfg, entry->method, p, &p);
2721 encode_value (entry->in_mrgctx, p, &p);
2722 encode_value (entry->info_type, p, &p);
2723 encode_value (entry->data->type, p, &p);
2724 encode_patch (acfg, entry->data, p, &p);
2727 case MONO_PATCH_INFO_GENERIC_CLASS_INIT:
2728 case MONO_PATCH_INFO_MONITOR_ENTER:
2729 case MONO_PATCH_INFO_MONITOR_EXIT:
2730 case MONO_PATCH_INFO_SEQ_POINT_INFO:
2732 case MONO_PATCH_INFO_LLVM_IMT_TRAMPOLINE:
2733 encode_method_ref (acfg, patch_info->data.imt_tramp->method, p, &p);
2734 encode_value (patch_info->data.imt_tramp->vt_offset, p, &p);
2737 g_warning ("unable to handle jump info %d", patch_info->type);
2738 g_assert_not_reached ();
2745 encode_patch_list (MonoAotCompile *acfg, GPtrArray *patches, int n_patches, int first_got_offset, guint8 *buf, guint8 **endbuf)
2748 guint32 pindex, offset;
2749 MonoJumpInfo *patch_info;
2751 encode_value (n_patches, p, &p);
2753 for (pindex = 0; pindex < patches->len; ++pindex) {
2754 patch_info = g_ptr_array_index (patches, pindex);
2756 if (patch_info->type == MONO_PATCH_INFO_NONE || patch_info->type == MONO_PATCH_INFO_BB)
2760 offset = get_got_offset (acfg, patch_info);
2761 encode_value (offset, p, &p);
2768 emit_method_info (MonoAotCompile *acfg, MonoCompile *cfg)
2772 int pindex, buf_size, n_patches;
2776 MonoJumpInfo *patch_info;
2777 MonoMethodHeader *header;
2778 guint32 method_index;
2780 guint32 first_got_offset;
2782 method = cfg->orig_method;
2783 code = cfg->native_code;
2784 header = mono_method_get_header (method);
2786 method_index = get_method_index (acfg, method);
2788 /* Make the labels local */
2789 sprintf (symbol, "%sm_%x_p", acfg->temp_prefix, method_index);
2791 /* Sort relocations */
2792 patches = g_ptr_array_new ();
2793 for (patch_info = cfg->patch_info; patch_info; patch_info = patch_info->next)
2794 g_ptr_array_add (patches, patch_info);
2795 g_ptr_array_sort (patches, compare_patches);
2797 first_got_offset = acfg->cfgs [method_index]->got_offset;
2799 /**********************/
2800 /* Encode method info */
2801 /**********************/
2803 buf_size = (patches->len < 1000) ? 40960 : 40960 + (patches->len * 64);
2804 p = buf = g_malloc (buf_size);
2806 if (mono_class_get_cctor (method->klass))
2807 encode_klass_ref (acfg, method->klass, p, &p);
2809 /* Not needed when loading the method */
2810 encode_value (0, p, &p);
2813 if (cfg->opt & MONO_OPT_SHARED) {
2814 encode_value (g_list_length (cfg->ldstr_list), p, &p);
2815 for (l = cfg->ldstr_list; l; l = l->next) {
2816 encode_value ((long)l->data, p, &p);
2820 /* Used only in shared mode */
2821 g_assert (!cfg->ldstr_list);
2824 for (pindex = 0; pindex < patches->len; ++pindex) {
2825 patch_info = g_ptr_array_index (patches, pindex);
2827 if ((patch_info->type == MONO_PATCH_INFO_GOT_OFFSET) ||
2828 (patch_info->type == MONO_PATCH_INFO_NONE)) {
2829 patch_info->type = MONO_PATCH_INFO_NONE;
2834 if ((patch_info->type == MONO_PATCH_INFO_IMAGE) && (patch_info->data.image == acfg->image)) {
2835 /* Stored in a GOT slot initialized at module load time */
2836 patch_info->type = MONO_PATCH_INFO_NONE;
2840 if (is_plt_patch (patch_info)) {
2841 /* Calls are made through the PLT */
2842 patch_info->type = MONO_PATCH_INFO_NONE;
2850 g_assert (cfg->has_got_slots);
2852 encode_patch_list (acfg, patches, n_patches, first_got_offset, p, &p);
2854 acfg->stats.info_size += p - buf;
2856 /* Emit method info */
2858 emit_label (acfg, symbol);
2860 g_assert (p - buf < buf_size);
2861 emit_bytes (acfg, buf, p - buf);
2866 get_unwind_info_offset (MonoAotCompile *acfg, guint8 *encoded, guint32 encoded_len)
2868 guint32 cache_index;
2871 /* Reuse the unwind module to canonize and store unwind info entries */
2872 cache_index = mono_cache_unwind_info (encoded, encoded_len);
2874 /* Use +/- 1 to distinguish 0s from missing entries */
2875 offset = GPOINTER_TO_UINT (g_hash_table_lookup (acfg->unwind_info_offsets, GUINT_TO_POINTER (cache_index + 1)));
2883 * It would be easier to use assembler symbols, but the caller needs an
2886 offset = acfg->unwind_info_offset;
2887 g_hash_table_insert (acfg->unwind_info_offsets, GUINT_TO_POINTER (cache_index + 1), GUINT_TO_POINTER (offset + 1));
2888 g_ptr_array_add (acfg->unwind_ops, GUINT_TO_POINTER (cache_index));
2891 encode_value (encoded_len, p, &p);
2893 acfg->unwind_info_offset += encoded_len + (p - buf);
2899 emit_exception_debug_info (MonoAotCompile *acfg, MonoCompile *cfg)
2902 int i, k, buf_size, method_index;
2903 guint32 debug_info_size;
2906 MonoMethodHeader *header;
2907 guint8 *p, *buf, *debug_info;
2908 MonoJitInfo *jinfo = cfg->jit_info;
2910 gboolean use_unwind_ops = FALSE;
2911 GPtrArray *seq_points;
2913 method = cfg->orig_method;
2914 code = cfg->native_code;
2915 header = mono_method_get_header (method);
2917 method_index = get_method_index (acfg, method);
2919 /* Make the labels local */
2920 sprintf (symbol, "%se_%x_p", acfg->temp_prefix, method_index);
2922 if (!acfg->aot_opts.nodebug) {
2923 mono_debug_serialize_debug_info (cfg, &debug_info, &debug_info_size);
2926 debug_info_size = 0;
2929 buf_size = header->num_clauses * 256 + debug_info_size + 1024 + (cfg->seq_points ? (cfg->seq_points->len * 16) : 0);
2930 p = buf = g_malloc (buf_size);
2932 #ifdef MONO_ARCH_HAVE_XP_UNWIND
2933 use_unwind_ops = cfg->unwind_ops != NULL;
2936 seq_points = cfg->seq_points;
2938 flags = (jinfo->has_generic_jit_info ? 1 : 0) | (use_unwind_ops ? 2 : 0) | (header->num_clauses ? 4 : 0) | (seq_points ? 8 : 0);
2940 if (cfg->compile_llvm) {
2941 /* Emitted by LLVM into the .eh_frame section */
2942 encode_value (0, p, &p);
2944 encode_value (jinfo->code_size, p, &p);
2946 encode_value (flags, p, &p);
2948 if (use_unwind_ops) {
2949 guint32 encoded_len;
2953 * This is a duplicate of the data in the .debug_frame section, but that
2954 * section cannot be accessed using the dl interface.
2956 encoded = mono_unwind_ops_encode (cfg->unwind_ops, &encoded_len);
2957 encode_value (get_unwind_info_offset (acfg, encoded, encoded_len), p, &p);
2960 encode_value (jinfo->used_regs, p, &p);
2963 /* Exception table */
2964 if (jinfo->num_clauses)
2965 encode_value (jinfo->num_clauses, p, &p);
2967 for (k = 0; k < jinfo->num_clauses; ++k) {
2968 MonoJitExceptionInfo *ei = &jinfo->clauses [k];
2970 encode_value (ei->flags, p, &p);
2971 encode_value (ei->exvar_offset, p, &p);
2973 if (ei->flags == MONO_EXCEPTION_CLAUSE_FILTER)
2974 encode_value ((gint)((guint8*)ei->data.filter - code), p, &p);
2976 if (ei->data.catch_class) {
2977 encode_value (1, p, &p);
2978 encode_klass_ref (acfg, ei->data.catch_class, p, &p);
2980 encode_value (0, p, &p);
2984 encode_value ((gint)((guint8*)ei->try_start - code), p, &p);
2985 encode_value ((gint)((guint8*)ei->try_end - code), p, &p);
2986 encode_value ((gint)((guint8*)ei->handler_start - code), p, &p);
2989 if (jinfo->has_generic_jit_info) {
2990 MonoGenericJitInfo *gi = mono_jit_info_get_generic_jit_info (jinfo);
2992 encode_value (gi->has_this ? 1 : 0, p, &p);
2993 encode_value (gi->this_reg, p, &p);
2994 encode_value (gi->this_offset, p, &p);
2997 * Need to encode jinfo->method too, since it is not equal to 'method'
2998 * when using generic sharing.
3000 encode_method_ref (acfg, jinfo->method, p, &p);
3004 int il_offset, native_offset, last_il_offset, last_native_offset;
3006 encode_value (seq_points->len, p, &p);
3007 last_il_offset = last_native_offset = 0;
3008 for (i = 0; i < seq_points->len; i += 2) {
3009 il_offset = GPOINTER_TO_INT (g_ptr_array_index (seq_points, i));
3010 native_offset = GPOINTER_TO_INT (g_ptr_array_index (seq_points, i + 1));
3011 encode_value (il_offset - last_il_offset, p, &p);
3012 encode_value (native_offset - last_native_offset, p, &p);
3013 last_il_offset = il_offset;
3014 last_native_offset = native_offset;
3019 g_assert (debug_info_size < buf_size);
3021 encode_value (debug_info_size, p, &p);
3022 if (debug_info_size) {
3023 memcpy (p, debug_info, debug_info_size);
3024 p += debug_info_size;
3025 g_free (debug_info);
3028 acfg->stats.ex_info_size += p - buf;
3032 emit_label (acfg, symbol);
3034 g_assert (p - buf < buf_size);
3035 emit_bytes (acfg, buf, p - buf);
3040 emit_klass_info (MonoAotCompile *acfg, guint32 token)
3042 MonoClass *klass = mono_class_get (acfg->image, token);
3046 gboolean no_special_static, cant_encode;
3047 gpointer iter = NULL;
3049 buf_size = 10240 + (klass->vtable_size * 16);
3050 p = buf = g_malloc (buf_size);
3054 mono_class_init (klass);
3056 mono_class_get_nested_types (klass, &iter);
3057 g_assert (klass->nested_classes_inited);
3059 mono_class_setup_vtable (klass);
3062 * Emit all the information which is required for creating vtables so
3063 * the runtime does not need to create the MonoMethod structures which
3064 * take up a lot of space.
3067 no_special_static = !mono_class_has_special_static_fields (klass);
3069 /* Check whenever we have enough info to encode the vtable */
3070 cant_encode = FALSE;
3071 for (i = 0; i < klass->vtable_size; ++i) {
3072 MonoMethod *cm = klass->vtable [i];
3074 if (cm && mono_method_signature (cm)->is_inflated && !g_hash_table_lookup (acfg->token_info_hash, cm))
3078 if (klass->generic_container || cant_encode) {
3079 encode_value (-1, p, &p);
3081 encode_value (klass->vtable_size, p, &p);
3082 encode_value ((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);
3083 if (klass->has_cctor)
3084 encode_method_ref (acfg, mono_class_get_cctor (klass), p, &p);
3085 if (klass->has_finalize)
3086 encode_method_ref (acfg, mono_class_get_finalizer (klass), p, &p);
3088 encode_value (klass->instance_size, p, &p);
3089 encode_value (mono_class_data_size (klass), p, &p);
3090 encode_value (klass->packing_size, p, &p);
3091 encode_value (klass->min_align, p, &p);
3093 for (i = 0; i < klass->vtable_size; ++i) {
3094 MonoMethod *cm = klass->vtable [i];
3097 encode_method_ref (acfg, cm, p, &p);
3099 encode_value (0, p, &p);
3103 acfg->stats.class_info_size += p - buf;
3106 sprintf (symbol, "%sK_I_%x", acfg->temp_prefix, token - MONO_TOKEN_TYPE_DEF - 1);
3107 emit_label (acfg, symbol);
3109 g_assert (p - buf < buf_size);
3110 emit_bytes (acfg, buf, p - buf);
3115 * Calls made from AOTed code are routed through a table of jumps similar to the
3116 * ELF PLT (Program Linkage Table). The differences are the following:
3117 * - the ELF PLT entries make an indirect jump though the GOT so they expect the
3118 * GOT pointer to be in EBX. We want to avoid this, so our table contains direct
3119 * jumps. This means the jumps need to be patched when the address of the callee is
3120 * known. Initially the PLT entries jump to code which transfers control to the
3121 * AOT runtime through the first PLT entry.
3124 emit_plt (MonoAotCompile *acfg)
3130 cache = g_hash_table_new (g_str_hash, g_str_equal);
3133 sprintf (symbol, "plt");
3135 emit_section_change (acfg, ".text", 0);
3136 emit_global (acfg, symbol, TRUE);
3138 /* This section will be made read-write by the AOT loader */
3139 emit_alignment (acfg, mono_pagesize ());
3141 emit_alignment (acfg, 16);
3143 emit_label (acfg, symbol);
3144 emit_label (acfg, acfg->plt_symbol);
3146 for (i = 0; i < acfg->plt_offset; ++i) {
3148 char *debug_sym = NULL;
3151 sprintf (label, "%sp_%d", acfg->temp_prefix, i);
3155 * If the target is directly callable, alias the plt symbol to point to
3157 * FIXME: Use this to simplify emit_and_reloc_code ().
3158 * FIXME: Avoid the got slot.
3159 * FIXME: Add support to the binary writer.
3161 ji = g_hash_table_lookup (acfg->plt_offset_to_patch, GUINT_TO_POINTER (i));
3162 if (ji && is_direct_callable (acfg, NULL, ji) && !acfg->use_bin_writer) {
3163 MonoCompile *callee_cfg = g_hash_table_lookup (acfg->method_to_cfg, ji->data.method);
3164 fprintf (acfg->fp, "\n.set %s, .Lm_%x\n", label, get_method_index (acfg, callee_cfg->orig_method));
3169 emit_label (acfg, label);
3171 if (acfg->aot_opts.write_symbols) {
3172 MonoJumpInfo *ji = g_hash_table_lookup (acfg->plt_offset_to_patch, GUINT_TO_POINTER (i));
3176 case MONO_PATCH_INFO_METHOD:
3177 debug_sym = get_debug_sym (ji->data.method, "plt_", cache);
3179 case MONO_PATCH_INFO_INTERNAL_METHOD:
3180 debug_sym = g_strdup_printf ("plt__jit_icall_%s", ji->data.name);
3182 case MONO_PATCH_INFO_CLASS_INIT:
3183 debug_sym = g_strdup_printf ("plt__class_init_%s", mono_type_get_name (&ji->data.klass->byval_arg));
3184 sanitize_symbol (debug_sym);
3186 case MONO_PATCH_INFO_RGCTX_FETCH:
3187 debug_sym = g_strdup_printf ("plt__rgctx_fetch_%d", acfg->label_generator ++);
3189 case MONO_PATCH_INFO_ICALL_ADDR: {
3190 char *s = get_debug_sym (ji->data.method, "", cache);
3192 debug_sym = g_strdup_printf ("plt__icall_native_%s", s);
3196 case MONO_PATCH_INFO_JIT_ICALL_ADDR:
3197 debug_sym = g_strdup_printf ("plt__jit_icall_native_%s", ji->data.name);
3199 case MONO_PATCH_INFO_GENERIC_CLASS_INIT:
3200 debug_sym = g_strdup_printf ("plt__generic_class_init");
3207 emit_local_symbol (acfg, debug_sym, NULL, TRUE);
3208 emit_label (acfg, debug_sym);
3214 * The first plt entry is used to transfer code to the AOT loader.
3216 arch_emit_plt_entry (acfg, i);
3219 emit_symbol_size (acfg, debug_sym, ".");
3224 emit_symbol_size (acfg, acfg->plt_symbol, ".");
3226 sprintf (symbol, "plt_end");
3227 emit_global (acfg, symbol, TRUE);
3228 emit_label (acfg, symbol);
3230 g_hash_table_destroy (cache);
3233 static G_GNUC_UNUSED void
3234 emit_trampoline (MonoAotCompile *acfg, const char *name, guint8 *code,
3235 guint32 code_size, int got_offset, MonoJumpInfo *ji, GSList *unwind_ops)
3237 char start_symbol [256];
3240 MonoJumpInfo *patch_info;
3246 sprintf (start_symbol, "%s", name);
3248 emit_section_change (acfg, ".text", 0);
3249 emit_global (acfg, start_symbol, TRUE);
3250 emit_alignment (acfg, 16);
3251 emit_label (acfg, start_symbol);
3253 sprintf (symbol, "%snamed_%s", acfg->temp_prefix, name);
3254 emit_label (acfg, symbol);
3257 * The code should access everything through the GOT, so we pass
3260 emit_and_reloc_code (acfg, NULL, code, code_size, ji, TRUE);
3262 emit_symbol_size (acfg, start_symbol, ".");
3266 /* Sort relocations */
3267 patches = g_ptr_array_new ();
3268 for (patch_info = ji; patch_info; patch_info = patch_info->next)
3269 if (patch_info->type != MONO_PATCH_INFO_NONE)
3270 g_ptr_array_add (patches, patch_info);
3271 g_ptr_array_sort (patches, compare_patches);
3273 buf_size = patches->len * 128 + 128;
3274 buf = g_malloc (buf_size);
3277 encode_patch_list (acfg, patches, patches->len, got_offset, p, &p);
3278 g_assert (p - buf < buf_size);
3280 sprintf (symbol, "%s_p", name);
3282 emit_section_change (acfg, ".text", 0);
3283 emit_global (acfg, symbol, FALSE);
3284 emit_label (acfg, symbol);
3286 emit_bytes (acfg, buf, p - buf);
3288 /* Emit debug info */
3292 sprintf (symbol, "%s", name);
3293 sprintf (symbol2, "%snamed_%s", acfg->temp_prefix, name);
3296 mono_dwarf_writer_emit_trampoline (acfg->dwarf, symbol, symbol2, NULL, NULL, code_size, unwind_ops);
3301 emit_trampolines (MonoAotCompile *acfg)
3304 int i, tramp_got_offset;
3305 MonoAotTrampoline ntype;
3306 #ifdef MONO_ARCH_HAVE_FULL_AOT_TRAMPOLINES
3314 if (!acfg->aot_opts.full_aot)
3317 g_assert (acfg->image->assembly);
3319 /* Currently, we only emit most trampolines into the mscorlib AOT image. */
3320 if (strcmp (acfg->image->assembly->aname.name, "mscorlib") == 0) {
3321 #ifdef MONO_ARCH_HAVE_FULL_AOT_TRAMPOLINES
3323 * Emit the generic trampolines.
3325 * We could save some code by treating the generic trampolines as a wrapper
3326 * method, but that approach has its own complexities, so we choose the simpler
3329 for (tramp_type = 0; tramp_type < MONO_TRAMPOLINE_NUM; ++tramp_type) {
3330 code = mono_arch_create_trampoline_code_full (tramp_type, &code_size, &ji, &unwind_ops, TRUE);
3332 /* Emit trampoline code */
3334 sprintf (symbol, "generic_trampoline_%d", tramp_type);
3336 emit_trampoline (acfg, symbol, code, code_size, acfg->got_offset, ji, unwind_ops);
3339 code = mono_arch_get_nullified_class_init_trampoline (&code_size);
3340 emit_trampoline (acfg, "nullified_class_init_trampoline", code, code_size, acfg->got_offset, NULL, NULL);
3341 #if defined(TARGET_AMD64) && defined(MONO_ARCH_MONITOR_OBJECT_REG)
3342 code = mono_arch_create_monitor_enter_trampoline_full (&code_size, &ji, TRUE);
3343 emit_trampoline (acfg, "monitor_enter_trampoline", code, code_size, acfg->got_offset, ji, NULL);
3344 code = mono_arch_create_monitor_exit_trampoline_full (&code_size, &ji, TRUE);
3345 emit_trampoline (acfg, "monitor_exit_trampoline", code, code_size, acfg->got_offset, ji, NULL);
3348 code = mono_arch_create_generic_class_init_trampoline_full (&code_size, &ji, TRUE);
3349 emit_trampoline (acfg, "generic_class_init_trampoline", code, code_size, acfg->got_offset, ji, NULL);
3351 /* Emit the exception related code pieces */
3352 code = mono_arch_get_restore_context_full (&code_size, &ji, TRUE);
3353 emit_trampoline (acfg, "restore_context", code, code_size, acfg->got_offset, ji, NULL);
3354 code = mono_arch_get_call_filter_full (&code_size, &ji, TRUE);
3355 emit_trampoline (acfg, "call_filter", code, code_size, acfg->got_offset, ji, NULL);
3356 code = mono_arch_get_throw_exception_full (&code_size, &ji, TRUE);
3357 emit_trampoline (acfg, "throw_exception", code, code_size, acfg->got_offset, ji, NULL);
3358 code = mono_arch_get_rethrow_exception_full (&code_size, &ji, TRUE);
3359 emit_trampoline (acfg, "rethrow_exception", code, code_size, acfg->got_offset, ji, NULL);
3360 code = mono_arch_get_throw_exception_by_name_full (&code_size, &ji, TRUE);
3361 emit_trampoline (acfg, "throw_exception_by_name", code, code_size, acfg->got_offset, ji, NULL);
3362 code = mono_arch_get_throw_corlib_exception_full (&code_size, &ji, TRUE);
3363 emit_trampoline (acfg, "throw_corlib_exception", code, code_size, acfg->got_offset, ji, NULL);
3365 #if defined(TARGET_AMD64)
3366 code = mono_arch_get_throw_pending_exception_full (&code_size, &ji, TRUE);
3367 emit_trampoline (acfg, "throw_pending_exception", code, code_size, acfg->got_offset, ji, NULL);
3370 for (i = 0; i < 128; ++i) {
3373 offset = MONO_RGCTX_SLOT_MAKE_RGCTX (i);
3374 code = mono_arch_create_rgctx_lazy_fetch_trampoline_full (offset, &code_size, &ji, TRUE);
3375 sprintf (symbol, "rgctx_fetch_trampoline_%u", offset);
3376 emit_trampoline (acfg, symbol, code, code_size, acfg->got_offset, ji, NULL);
3378 offset = MONO_RGCTX_SLOT_MAKE_MRGCTX (i);
3379 code = mono_arch_create_rgctx_lazy_fetch_trampoline_full (offset, &code_size, &ji, TRUE);
3380 sprintf (symbol, "rgctx_fetch_trampoline_%u", offset);
3381 emit_trampoline (acfg, symbol, code, code_size, acfg->got_offset, ji, NULL);
3387 /* delegate_invoke_impl trampolines */
3388 l = mono_arch_get_delegate_invoke_impls ();
3390 MonoAotTrampInfo *info = l->data;
3392 emit_trampoline (acfg, info->name, info->code, info->code_size, acfg->got_offset, NULL, NULL);
3397 #endif /* #ifdef MONO_ARCH_HAVE_FULL_AOT_TRAMPOLINES */
3399 /* Emit trampolines which are numerous */
3402 * These include the following:
3403 * - specific trampolines
3404 * - static rgctx invoke trampolines
3406 * These trampolines have the same code, they are parameterized by GOT
3408 * They are defined in this file, in the arch_... routines instead of
3409 * in tramp-<ARCH>.c, since it is easier to do it this way.
3413 * When running in aot-only mode, we can't create specific trampolines at
3414 * runtime, so we create a few, and save them in the AOT file.
3415 * Normal trampolines embed their argument as a literal inside the
3416 * trampoline code, we can't do that here, so instead we embed an offset
3417 * which needs to be added to the trampoline address to get the address of
3418 * the GOT slot which contains the argument value.
3419 * The generated trampolines jump to the generic trampolines using another
3420 * GOT slot, which will be setup by the AOT loader to point to the
3421 * generic trampoline code of the given type.
3425 * FIXME: Maybe we should use more specific trampolines (i.e. one class init for
3429 emit_section_change (acfg, ".text", 0);
3431 tramp_got_offset = acfg->got_offset;
3433 for (ntype = 0; ntype < MONO_AOT_TRAMP_NUM; ++ntype) {
3435 case MONO_AOT_TRAMP_SPECIFIC:
3436 sprintf (symbol, "specific_trampolines");
3438 case MONO_AOT_TRAMP_STATIC_RGCTX:
3439 sprintf (symbol, "static_rgctx_trampolines");
3441 case MONO_AOT_TRAMP_IMT_THUNK:
3442 sprintf (symbol, "imt_thunks");
3445 g_assert_not_reached ();
3448 emit_global (acfg, symbol, TRUE);
3449 emit_alignment (acfg, 16);
3450 emit_label (acfg, symbol);
3452 acfg->trampoline_got_offset_base [ntype] = tramp_got_offset;
3454 for (i = 0; i < acfg->num_trampolines [ntype]; ++i) {
3458 case MONO_AOT_TRAMP_SPECIFIC:
3459 arch_emit_specific_trampoline (acfg, tramp_got_offset, &tramp_size);
3460 tramp_got_offset += 2;
3462 case MONO_AOT_TRAMP_STATIC_RGCTX:
3463 arch_emit_static_rgctx_trampoline (acfg, tramp_got_offset, &tramp_size);
3464 tramp_got_offset += 2;
3466 case MONO_AOT_TRAMP_IMT_THUNK:
3467 arch_emit_imt_thunk (acfg, tramp_got_offset, &tramp_size);
3468 tramp_got_offset += 1;
3471 g_assert_not_reached ();
3474 if (!acfg->trampoline_size [ntype]) {
3475 g_assert (tramp_size);
3476 acfg->trampoline_size [ntype] = tramp_size;
3481 /* Reserve some entries at the end of the GOT for our use */
3482 acfg->num_trampoline_got_entries = tramp_got_offset - acfg->got_offset;
3485 acfg->got_offset += acfg->num_trampoline_got_entries;
3489 str_begins_with (const char *str1, const char *str2)
3491 int len = strlen (str2);
3492 return strncmp (str1, str2, len) == 0;
3496 mono_aot_parse_options (const char *aot_options, MonoAotOptions *opts)
3498 gchar **args, **ptr;
3500 args = g_strsplit (aot_options ? aot_options : "", ",", -1);
3501 for (ptr = args; ptr && *ptr; ptr ++) {
3502 const char *arg = *ptr;
3504 if (str_begins_with (arg, "outfile=")) {
3505 opts->outfile = g_strdup (arg + strlen ("outfile="));
3506 } else if (str_begins_with (arg, "save-temps")) {
3507 opts->save_temps = TRUE;
3508 } else if (str_begins_with (arg, "keep-temps")) {
3509 opts->save_temps = TRUE;
3510 } else if (str_begins_with (arg, "write-symbols")) {
3511 opts->write_symbols = TRUE;
3512 } else if (str_begins_with (arg, "metadata-only")) {
3513 opts->metadata_only = TRUE;
3514 } else if (str_begins_with (arg, "bind-to-runtime-version")) {
3515 opts->bind_to_runtime_version = TRUE;
3516 } else if (str_begins_with (arg, "full")) {
3517 opts->full_aot = TRUE;
3518 } else if (str_begins_with (arg, "threads=")) {
3519 opts->nthreads = atoi (arg + strlen ("threads="));
3520 } else if (str_begins_with (arg, "static")) {
3521 opts->static_link = TRUE;
3522 opts->no_dlsym = TRUE;
3523 } else if (str_begins_with (arg, "asmonly")) {
3524 opts->asm_only = TRUE;
3525 } else if (str_begins_with (arg, "asmwriter")) {
3526 opts->asm_writer = TRUE;
3527 } else if (str_begins_with (arg, "nodebug")) {
3528 opts->nodebug = TRUE;
3529 } else if (str_begins_with (arg, "ntrampolines=")) {
3530 opts->ntrampolines = atoi (arg + strlen ("ntrampolines="));
3531 } else if (str_begins_with (arg, "autoreg")) {
3532 opts->autoreg = TRUE;
3533 } else if (str_begins_with (arg, "tool-prefix=")) {
3534 opts->tool_prefix = g_strdup (arg + strlen ("tool-prefix="));
3535 } else if (str_begins_with (arg, "autoreg")) {
3536 opts->autoreg = TRUE;
3537 } else if (str_begins_with (arg, "soft-debug")) {
3538 opts->soft_debug = TRUE;
3539 } else if (str_begins_with (arg, "print-skipped")) {
3540 opts->print_skipped_methods = TRUE;
3542 fprintf (stderr, "AOT : Unknown argument '%s'.\n", arg);
3551 add_token_info_hash (gpointer key, gpointer value, gpointer user_data)
3553 MonoMethod *method = (MonoMethod*)key;
3554 MonoJumpInfoToken *ji = (MonoJumpInfoToken*)value;
3555 MonoJumpInfoToken *new_ji = g_new0 (MonoJumpInfoToken, 1);
3556 MonoAotCompile *acfg = user_data;
3558 new_ji->image = ji->image;
3559 new_ji->token = ji->token;
3560 g_hash_table_insert (acfg->token_info_hash, method, new_ji);
3564 can_encode_class (MonoAotCompile *acfg, MonoClass *klass)
3566 if (klass->type_token)
3568 if ((klass->byval_arg.type == MONO_TYPE_VAR) || (klass->byval_arg.type == MONO_TYPE_MVAR))
3571 return can_encode_class (acfg, klass->element_class);
3576 can_encode_patch (MonoAotCompile *acfg, MonoJumpInfo *patch_info)
3578 switch (patch_info->type) {
3579 case MONO_PATCH_INFO_METHOD:
3580 case MONO_PATCH_INFO_METHODCONST: {
3581 MonoMethod *method = patch_info->data.method;
3583 if (method->wrapper_type) {
3584 switch (method->wrapper_type) {
3585 case MONO_WRAPPER_NONE:
3586 case MONO_WRAPPER_REMOTING_INVOKE_WITH_CHECK:
3587 case MONO_WRAPPER_XDOMAIN_INVOKE:
3588 case MONO_WRAPPER_STFLD:
3589 case MONO_WRAPPER_LDFLD:
3590 case MONO_WRAPPER_LDFLDA:
3591 case MONO_WRAPPER_LDFLD_REMOTE:
3592 case MONO_WRAPPER_STFLD_REMOTE:
3593 case MONO_WRAPPER_STELEMREF:
3594 case MONO_WRAPPER_ISINST:
3595 case MONO_WRAPPER_PROXY_ISINST:
3596 case MONO_WRAPPER_ALLOC:
3597 case MONO_WRAPPER_REMOTING_INVOKE:
3598 case MONO_WRAPPER_UNKNOWN:
3601 //printf ("Skip (wrapper call): %d -> %s\n", patch_info->type, mono_method_full_name (patch_info->data.method, TRUE));
3605 if (!method->token) {
3606 /* The method is part of a constructed type like Int[,].Set (). */
3607 if (!g_hash_table_lookup (acfg->token_info_hash, method)) {
3608 if (method->klass->rank)
3616 case MONO_PATCH_INFO_VTABLE:
3617 case MONO_PATCH_INFO_CLASS_INIT:
3618 case MONO_PATCH_INFO_DELEGATE_TRAMPOLINE:
3619 case MONO_PATCH_INFO_CLASS:
3620 case MONO_PATCH_INFO_IID:
3621 case MONO_PATCH_INFO_ADJUSTED_IID:
3622 if (!can_encode_class (acfg, patch_info->data.klass)) {
3623 //printf ("Skip: %s\n", mono_type_full_name (&patch_info->data.klass->byval_arg));
3627 case MONO_PATCH_INFO_RGCTX_FETCH: {
3628 MonoJumpInfoRgctxEntry *entry = patch_info->data.rgctx_entry;
3630 if (!can_encode_patch (acfg, entry->data))
3642 add_generic_class (MonoAotCompile *acfg, MonoClass *klass);
3647 * AOT compile a given method.
3648 * This function might be called by multiple threads, so it must be thread-safe.
3651 compile_method (MonoAotCompile *acfg, MonoMethod *method)
3654 MonoJumpInfo *patch_info;
3657 MonoMethod *wrapped;
3659 if (acfg->aot_opts.metadata_only)
3662 mono_acfg_lock (acfg);
3663 index = get_method_index (acfg, method);
3664 mono_acfg_unlock (acfg);
3666 /* fixme: maybe we can also precompile wrapper methods */
3667 if ((method->flags & METHOD_ATTRIBUTE_PINVOKE_IMPL) ||
3668 (method->iflags & METHOD_IMPL_ATTRIBUTE_RUNTIME) ||
3669 (method->flags & METHOD_ATTRIBUTE_ABSTRACT)) {
3670 //printf ("Skip (impossible): %s\n", mono_method_full_name (method, TRUE));
3674 if (method->iflags & METHOD_IMPL_ATTRIBUTE_INTERNAL_CALL)
3677 wrapped = mono_marshal_method_from_wrapper (method);
3678 if (wrapped && (wrapped->iflags & METHOD_IMPL_ATTRIBUTE_INTERNAL_CALL) && wrapped->is_generic)
3679 // FIXME: The wrapper should be generic too, but it is not
3682 InterlockedIncrement (&acfg->stats.mcount);
3685 if (method->is_generic || method->klass->generic_container) {
3686 InterlockedIncrement (&acfg->stats.genericcount);
3691 //acfg->aot_opts.print_skipped_methods = TRUE;
3694 * Since these methods are the only ones which are compiled with
3695 * AOT support, and they are not used by runtime startup/shutdown code,
3696 * the runtime will not see AOT methods during AOT compilation,so it
3697 * does not need to support them by creating a fake GOT etc.
3699 cfg = mini_method_compile (method, acfg->opts, mono_get_root_domain (), FALSE, TRUE, 0);
3700 if (cfg->exception_type == MONO_EXCEPTION_GENERIC_SHARING_FAILED) {
3701 //printf ("F: %s\n", mono_method_full_name (method, TRUE));
3702 InterlockedIncrement (&acfg->stats.genericcount);
3705 if (cfg->exception_type != MONO_EXCEPTION_NONE) {
3706 /* Let the exception happen at runtime */
3710 if (cfg->disable_aot) {
3711 if (acfg->aot_opts.print_skipped_methods)
3712 printf ("Skip (disabled): %s\n", mono_method_full_name (method, TRUE));
3713 InterlockedIncrement (&acfg->stats.ocount);
3714 mono_destroy_compile (cfg);
3718 /* Nullify patches which need no aot processing */
3719 for (patch_info = cfg->patch_info; patch_info; patch_info = patch_info->next) {
3720 switch (patch_info->type) {
3721 case MONO_PATCH_INFO_LABEL:
3722 case MONO_PATCH_INFO_BB:
3723 patch_info->type = MONO_PATCH_INFO_NONE;
3730 /* Collect method->token associations from the cfg */
3731 mono_acfg_lock (acfg);
3732 g_hash_table_foreach (cfg->token_info_hash, add_token_info_hash, acfg);
3733 mono_acfg_unlock (acfg);
3736 * Check for absolute addresses.
3739 for (patch_info = cfg->patch_info; patch_info; patch_info = patch_info->next) {
3740 switch (patch_info->type) {
3741 case MONO_PATCH_INFO_ABS:
3742 /* unable to handle this */
3751 if (acfg->aot_opts.print_skipped_methods)
3752 printf ("Skip (abs call): %s\n", mono_method_full_name (method, TRUE));
3753 InterlockedIncrement (&acfg->stats.abscount);
3754 mono_destroy_compile (cfg);
3758 /* Lock for the rest of the code */
3759 mono_acfg_lock (acfg);
3762 * Check for methods/klasses we can't encode.
3765 for (patch_info = cfg->patch_info; patch_info; patch_info = patch_info->next) {
3766 if (!can_encode_patch (acfg, patch_info))
3771 if (acfg->aot_opts.print_skipped_methods)
3772 printf ("Skip (patches): %s\n", mono_method_full_name (method, TRUE));
3773 acfg->stats.ocount++;
3774 mono_destroy_compile (cfg);
3775 mono_acfg_unlock (acfg);
3779 /* Adds generic instances referenced by this method */
3781 * The depth is used to avoid infinite loops when generic virtual recursion is
3784 depth = GPOINTER_TO_UINT (g_hash_table_lookup (acfg->method_depth, method));
3786 for (patch_info = cfg->patch_info; patch_info; patch_info = patch_info->next) {
3787 switch (patch_info->type) {
3788 case MONO_PATCH_INFO_METHOD: {
3789 MonoMethod *m = patch_info->data.method;
3790 if (m->is_inflated) {
3791 if (!(mono_class_generic_sharing_enabled (m->klass) &&
3792 mono_method_is_generic_sharable_impl (m, FALSE)) &&
3793 !method_has_type_vars (m)) {
3794 if (m->iflags & METHOD_IMPL_ATTRIBUTE_INTERNAL_CALL) {
3795 if (acfg->aot_opts.full_aot)
3796 add_extra_method_with_depth (acfg, mono_marshal_get_native_wrapper (m, TRUE, TRUE), depth + 1);
3798 add_extra_method_with_depth (acfg, m, depth + 1);
3801 add_generic_class (acfg, m->klass);
3805 case MONO_PATCH_INFO_VTABLE: {
3806 MonoClass *klass = patch_info->data.klass;
3808 if (klass->generic_class && !mono_generic_context_is_sharable (&klass->generic_class->context, FALSE))
3809 add_generic_class (acfg, klass);
3818 /* Determine whenever the method has GOT slots */
3819 for (patch_info = cfg->patch_info; patch_info; patch_info = patch_info->next) {
3820 switch (patch_info->type) {
3821 case MONO_PATCH_INFO_GOT_OFFSET:
3822 case MONO_PATCH_INFO_NONE:
3824 case MONO_PATCH_INFO_IMAGE:
3825 /* The assembly is stored in GOT slot 0 */
3826 if (patch_info->data.image != acfg->image)
3827 cfg->has_got_slots = TRUE;
3830 if (!is_plt_patch (patch_info))
3831 cfg->has_got_slots = TRUE;
3836 if (!cfg->has_got_slots)
3837 InterlockedIncrement (&acfg->stats.methods_without_got_slots);
3840 * FIXME: Instead of this mess, allocate the patches from the aot mempool.
3842 /* Make a copy of the patch info which is in the mempool */
3844 MonoJumpInfo *patches = NULL, *patches_end = NULL;
3846 for (patch_info = cfg->patch_info; patch_info; patch_info = patch_info->next) {
3847 MonoJumpInfo *new_patch_info = mono_patch_info_dup_mp (acfg->mempool, patch_info);
3850 patches = new_patch_info;
3852 patches_end->next = new_patch_info;
3853 patches_end = new_patch_info;
3855 cfg->patch_info = patches;
3857 /* Make a copy of the unwind info */
3859 GSList *l, *unwind_ops;
3863 for (l = cfg->unwind_ops; l; l = l->next) {
3864 op = mono_mempool_alloc (acfg->mempool, sizeof (MonoUnwindOp));
3865 memcpy (op, l->data, sizeof (MonoUnwindOp));
3866 unwind_ops = g_slist_prepend_mempool (acfg->mempool, unwind_ops, op);
3868 cfg->unwind_ops = g_slist_reverse (unwind_ops);
3870 /* Make a copy of the argument/local info */
3872 MonoInst **args, **locals;
3873 MonoMethodSignature *sig;
3874 MonoMethodHeader *header;
3877 sig = mono_method_signature (method);
3878 args = mono_mempool_alloc (acfg->mempool, sizeof (MonoInst*) * (sig->param_count + sig->hasthis));
3879 for (i = 0; i < sig->param_count + sig->hasthis; ++i) {
3880 args [i] = mono_mempool_alloc (acfg->mempool, sizeof (MonoInst));
3881 memcpy (args [i], cfg->args [i], sizeof (MonoInst));
3885 header = mono_method_get_header (method);
3886 locals = mono_mempool_alloc (acfg->mempool, sizeof (MonoInst*) * header->num_locals);
3887 for (i = 0; i < header->num_locals; ++i) {
3888 locals [i] = mono_mempool_alloc (acfg->mempool, sizeof (MonoInst));
3889 memcpy (locals [i], cfg->locals [i], sizeof (MonoInst));
3891 cfg->locals = locals;
3894 /* Free some fields used by cfg to conserve memory */
3895 mono_mempool_destroy (cfg->mempool);
3896 cfg->mempool = NULL;
3897 g_free (cfg->varinfo);
3898 cfg->varinfo = NULL;
3902 mono_regstate_free (cfg->rs);
3906 //printf ("Compile: %s\n", mono_method_full_name (method, TRUE));
3908 while (index >= acfg->cfgs_size) {
3909 MonoCompile **new_cfgs;
3912 new_size = acfg->cfgs_size * 2;
3913 new_cfgs = g_new0 (MonoCompile*, new_size);
3914 memcpy (new_cfgs, acfg->cfgs, sizeof (MonoCompile*) * acfg->cfgs_size);
3915 g_free (acfg->cfgs);
3916 acfg->cfgs = new_cfgs;
3917 acfg->cfgs_size = new_size;
3919 acfg->cfgs [index] = cfg;
3921 g_hash_table_insert (acfg->method_to_cfg, cfg->orig_method, cfg);
3924 if (cfg->orig_method->wrapper_type)
3925 g_ptr_array_add (acfg->extra_methods, cfg->orig_method);
3928 mono_acfg_unlock (acfg);
3930 InterlockedIncrement (&acfg->stats.ccount);
3934 compile_thread_main (gpointer *user_data)
3936 MonoDomain *domain = user_data [0];
3937 MonoAotCompile *acfg = user_data [1];
3938 GPtrArray *methods = user_data [2];
3941 mono_thread_attach (domain);
3943 for (i = 0; i < methods->len; ++i)
3944 compile_method (acfg, g_ptr_array_index (methods, i));
3948 load_profile_files (MonoAotCompile *acfg)
3952 int file_index, res, method_index, i;
3959 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);
3961 if (!g_file_test (tmp, G_FILE_TEST_IS_REGULAR)) {
3966 infile = fopen (tmp, "r");
3969 printf ("Using profile data file '%s'\n", tmp);
3974 res = fscanf (infile, "%32s\n", ver);
3975 if ((res != 1) || strcmp (ver, "#VER:1") != 0) {
3976 printf ("Profile file has wrong version or invalid.\n");
3982 res = fscanf (infile, "%d\n", &token);
3986 method_index = mono_metadata_token_index (token) - 1;
3988 if (!g_list_find (acfg->method_order, GUINT_TO_POINTER (method_index)))
3989 acfg->method_order = g_list_append (acfg->method_order, GUINT_TO_POINTER (method_index));
3994 /* Add missing methods */
3996 for (i = 0; i < acfg->image->tables [MONO_TABLE_METHOD].rows; ++i) {
3997 if (!g_list_find (acfg->method_order, GUINT_TO_POINTER (i)))
3998 unordered = g_list_prepend (unordered, GUINT_TO_POINTER (i));
4000 unordered = g_list_reverse (unordered);
4001 if (acfg->method_order)
4002 g_list_last (acfg->method_order)->next = unordered;
4004 acfg->method_order = unordered;
4007 /* Used by the LLVM backend */
4009 mono_aot_get_got_offset (MonoJumpInfo *ji)
4011 return get_got_offset (llvm_acfg, ji);
4015 mono_aot_get_method_name (MonoCompile *cfg)
4017 guint32 method_index = get_method_index (llvm_acfg, cfg->orig_method);
4019 /* LLVM converts these to .Lm_%x */
4020 return g_strdup_printf ("m_%x", method_index);
4024 mono_aot_get_method_debug_name (MonoCompile *cfg)
4026 return get_debug_sym (cfg->orig_method, "", llvm_acfg->method_label_hash);
4030 mono_aot_get_plt_symbol (MonoJumpInfoType type, gconstpointer data)
4032 MonoJumpInfo *ji = mono_mempool_alloc (llvm_acfg->mempool, sizeof (MonoJumpInfo));
4036 ji->data.target = data;
4038 if (!can_encode_patch (llvm_acfg, ji))
4041 offset = get_plt_offset (llvm_acfg, ji);
4043 return g_strdup_printf (".Lp_%d", offset);
4047 mono_aot_patch_info_dup (MonoJumpInfo* ji)
4051 mono_acfg_lock (llvm_acfg);
4052 res = mono_patch_info_dup_mp (llvm_acfg->mempool, ji);
4053 mono_acfg_unlock (llvm_acfg);
4063 * Emit the LLVM code into an LLVM bytecode file, and compile it using the LLVM
4067 emit_llvm_file (MonoAotCompile *acfg)
4069 char *command, *opts;
4071 MonoJumpInfo *patch_info;
4074 * When using LLVM, we let llvm emit the got since the LLVM IL needs to refer
4078 /* Compute the final size of the got */
4079 for (i = 0; i < acfg->nmethods; ++i) {
4080 if (acfg->cfgs [i]) {
4081 for (patch_info = acfg->cfgs [i]->patch_info; patch_info; patch_info = patch_info->next) {
4082 if (patch_info->type != MONO_PATCH_INFO_NONE) {
4083 if (!is_plt_patch (patch_info))
4084 get_got_offset (acfg, patch_info);
4086 get_plt_offset (acfg, patch_info);
4091 acfg->final_got_size = acfg->got_offset + acfg->plt_offset;
4093 mono_llvm_emit_aot_module ("temp.bc", acfg->final_got_size);
4096 * FIXME: Experiment with adding optimizations, the -std-compile-opts set takes
4097 * a lot of time, and doesn't seem to save much space.
4098 * The following optimizations cannot be enabled:
4099 * - 'globalopt', which seems to remove our methods, even though they have a global
4100 * alias pointing at them.
4101 * - 'constmerge'/'globaldce', which seems to remove our got symbol.
4104 opts = g_strdup ("-instcombine -simplifycfg");
4106 command = g_strdup_printf ("opt -f %s -o temp.bc temp.bc", opts);
4107 printf ("Executing opt: %s\n", command);
4108 if (system (command) != 0) {
4114 //command = g_strdup_printf ("llc -march=arm -mtriple=arm-linux-gnueabi -f -relocation-model=pic -unwind-tables temp.bc");
4115 command = g_strdup_printf ("llc -f -relocation-model=pic -unwind-tables -o temp.s temp.bc");
4116 printf ("Executing llc: %s\n", command);
4118 if (system (command) != 0) {
4125 emit_code (MonoAotCompile *acfg)
4131 #if defined(TARGET_POWERPC64)
4132 sprintf (symbol, ".Lgot_addr");
4133 emit_section_change (acfg, ".text", 0);
4134 emit_alignment (acfg, 8);
4135 emit_label (acfg, symbol);
4136 emit_pointer (acfg, acfg->got_symbol);
4140 sprintf (symbol, "methods");
4141 emit_section_change (acfg, ".text", 0);
4142 emit_global (acfg, symbol, TRUE);
4143 emit_alignment (acfg, 8);
4144 emit_label (acfg, symbol);
4148 * Emit some padding so the local symbol for the first method doesn't have the
4149 * same address as 'methods'.
4151 emit_zero_bytes (acfg, 16);
4153 for (l = acfg->method_order; l != NULL; l = l->next) {
4154 i = GPOINTER_TO_UINT (l->data);
4156 if (acfg->cfgs [i]) {
4157 if (acfg->cfgs [i]->compile_llvm)
4158 acfg->stats.llvm_count ++;
4160 emit_method_code (acfg, acfg->cfgs [i]);
4164 sprintf (symbol, "methods_end");
4165 emit_section_change (acfg, ".text", 0);
4166 emit_global (acfg, symbol, FALSE);
4167 emit_alignment (acfg, 8);
4168 emit_label (acfg, symbol);
4170 sprintf (symbol, "method_offsets");
4171 emit_section_change (acfg, ".text", 1);
4172 emit_global (acfg, symbol, FALSE);
4173 emit_alignment (acfg, 8);
4174 emit_label (acfg, symbol);
4176 for (i = 0; i < acfg->nmethods; ++i) {
4177 if (acfg->cfgs [i]) {
4178 sprintf (symbol, "%sm_%x", acfg->temp_prefix, i);
4179 emit_symbol_diff (acfg, symbol, "methods", 0);
4181 emit_int32 (acfg, 0xffffffff);
4188 emit_info (MonoAotCompile *acfg)
4194 /* Emit method info */
4195 sprintf (symbol, "method_info");
4196 emit_section_change (acfg, ".text", 1);
4197 emit_global (acfg, symbol, FALSE);
4198 emit_alignment (acfg, 8);
4199 emit_label (acfg, symbol);
4201 /* To reduce size of generated assembly code */
4202 sprintf (symbol, "mi");
4203 emit_label (acfg, symbol);
4205 for (l = acfg->method_order; l != NULL; l = l->next) {
4206 i = GPOINTER_TO_UINT (l->data);
4209 emit_method_info (acfg, acfg->cfgs [i]);
4212 sprintf (symbol, "method_info_offsets");
4213 emit_section_change (acfg, ".text", 1);
4214 emit_global (acfg, symbol, FALSE);
4215 emit_alignment (acfg, 8);
4216 emit_label (acfg, symbol);
4218 for (i = 0; i < acfg->nmethods; ++i) {
4219 if (acfg->cfgs [i]) {
4220 sprintf (symbol, "%sm_%x_p", acfg->temp_prefix, i);
4221 emit_symbol_diff (acfg, symbol, "mi", 0);
4223 emit_int32 (acfg, 0);
4229 #endif /* #if !defined(DISABLE_AOT) && !defined(DISABLE_JIT) */
4232 * mono_aot_str_hash:
4234 * Hash function for strings which we use to hash strings for things which are
4235 * saved in the AOT image, since g_str_hash () can change.
4238 mono_aot_str_hash (gconstpointer v1)
4240 /* Same as g_str_hash () in glib */
4241 char *p = (char *) v1;
4246 hash = (hash << 5) - hash + *p;
4252 #define rot(x,k) (((x)<<(k)) | ((x)>>(32-(k))))
4253 #define mix(a,b,c) { \
4254 a -= c; a ^= rot(c, 4); c += b; \
4255 b -= a; b ^= rot(a, 6); a += c; \
4256 c -= b; c ^= rot(b, 8); b += a; \
4257 a -= c; a ^= rot(c,16); c += b; \
4258 b -= a; b ^= rot(a,19); a += c; \
4259 c -= b; c ^= rot(b, 4); b += a; \
4261 #define final(a,b,c) { \
4262 c ^= b; c -= rot(b,14); \
4263 a ^= c; a -= rot(c,11); \
4264 b ^= a; b -= rot(a,25); \
4265 c ^= b; c -= rot(b,16); \
4266 a ^= c; a -= rot(c,4); \
4267 b ^= a; b -= rot(a,14); \
4268 c ^= b; c -= rot(b,24); \
4272 mono_aot_type_hash (MonoType *t1)
4274 guint hash = t1->type;
4276 hash |= t1->byref << 6; /* do not collide with t1->type values */
4278 case MONO_TYPE_VALUETYPE:
4279 case MONO_TYPE_CLASS:
4280 case MONO_TYPE_SZARRAY:
4281 /* check if the distribution is good enough */
4282 return ((hash << 5) - hash) ^ mono_aot_str_hash (t1->data.klass->name);
4284 return ((hash << 5) - hash) ^ mono_aot_type_hash (t1->data.type);
4285 case MONO_TYPE_ARRAY:
4286 return ((hash << 5) - hash) ^ mono_aot_type_hash (&t1->data.array->eklass->byval_arg);
4287 case MONO_TYPE_GENERICINST:
4288 return ((hash << 5) - hash) ^ 0;
4294 * mono_aot_method_hash:
4296 * Return a hash code for methods which only depends on metadata.
4299 mono_aot_method_hash (MonoMethod *method)
4301 MonoMethodSignature *sig;
4305 guint32 *hashes_start, *hashes;
4308 /* Similar to the hash in mono_method_get_imt_slot () */
4310 sig = mono_method_signature (method);
4312 hashes_count = sig->param_count + 5;
4313 hashes_start = malloc (hashes_count * sizeof (guint32));
4314 hashes = hashes_start;
4316 /* Some wrappers are assigned to random classes */
4317 if (!method->wrapper_type || method->wrapper_type == MONO_WRAPPER_REMOTING_INVOKE_WITH_CHECK)
4318 klass = method->klass;
4320 klass = mono_defaults.object_class;
4322 if (!method->wrapper_type) {
4323 char *full_name = mono_type_full_name (&klass->byval_arg);
4325 hashes [0] = mono_aot_str_hash (full_name);
4329 hashes [0] = mono_aot_str_hash (klass->name);
4330 hashes [1] = mono_aot_str_hash (klass->name_space);
4332 if (method->wrapper_type == MONO_WRAPPER_STFLD || method->wrapper_type == MONO_WRAPPER_LDFLD || method->wrapper_type == MONO_WRAPPER_LDFLDA)
4333 /* The method name includes a stringified pointer */
4336 hashes [2] = mono_aot_str_hash (method->name);
4337 hashes [3] = method->wrapper_type;
4338 hashes [4] = mono_aot_type_hash (sig->ret);
4339 for (i = 0; i < sig->param_count; i++) {
4340 hashes [5 + i] = mono_aot_type_hash (sig->params [i]);
4343 /* Setup internal state */
4344 a = b = c = 0xdeadbeef + (((guint32)hashes_count)<<2);
4346 /* Handle most of the hashes */
4347 while (hashes_count > 3) {
4356 /* Handle the last 3 hashes (all the case statements fall through) */
4357 switch (hashes_count) {
4358 case 3 : c += hashes [2];
4359 case 2 : b += hashes [1];
4360 case 1 : a += hashes [0];
4362 case 0: /* nothing left to add */
4366 free (hashes_start);
4375 * mono_aot_wrapper_name:
4377 * Return a string which uniqely identifies the given wrapper method.
4380 mono_aot_wrapper_name (MonoMethod *method)
4382 char *name, *tmpsig, *klass_desc;
4384 tmpsig = mono_signature_get_desc (mono_method_signature (method), TRUE);
4386 switch (method->wrapper_type) {
4387 case MONO_WRAPPER_RUNTIME_INVOKE:
4388 if (!strcmp (method->name, "runtime_invoke_dynamic"))
4389 name = g_strdup_printf ("(wrapper runtime-invoke-dynamic)");
4391 name = g_strdup_printf ("%s (%s)", method->name, tmpsig);
4393 case MONO_WRAPPER_DELEGATE_INVOKE:
4394 case MONO_WRAPPER_DELEGATE_BEGIN_INVOKE:
4395 case MONO_WRAPPER_DELEGATE_END_INVOKE:
4396 /* This is a hack to work around the fact that these wrappers get assigned to some random class */
4397 name = g_strdup_printf ("%s (%s)", method->name, tmpsig);
4400 klass_desc = mono_type_full_name (&method->klass->byval_arg);
4401 name = g_strdup_printf ("%s:%s (%s)", klass_desc, method->name, tmpsig);
4402 g_free (klass_desc);
4412 * mono_aot_get_array_helper_from_wrapper;
4414 * Get the helper method in Array called by an array wrapper method.
4417 mono_aot_get_array_helper_from_wrapper (MonoMethod *method)
4421 MonoGenericContext ctx;
4422 MonoType *args [16];
4423 char *mname, *iname, *s, *s2, *helper_name = NULL;
4425 prefix = "System.Collections.Generic";
4426 s = g_strdup_printf ("%s", method->name + strlen (prefix) + 1);
4427 s2 = strstr (s, "`1.");
4433 //printf ("X: %s %s\n", iname, mname);
4435 if (!strcmp (iname, "IList"))
4436 helper_name = g_strdup_printf ("InternalArray__%s", mname);
4438 helper_name = g_strdup_printf ("InternalArray__%s_%s", iname, mname);
4439 m = mono_class_get_method_from_name (mono_defaults.array_class, helper_name, mono_method_signature (method)->param_count);
4441 g_free (helper_name);
4444 if (m->is_generic) {
4445 memset (&ctx, 0, sizeof (ctx));
4446 args [0] = &method->klass->element_class->byval_arg;
4447 ctx.method_inst = mono_metadata_get_generic_inst (1, args);
4448 m = mono_class_inflate_generic_method (m, &ctx);
4455 * mono_aot_tramp_info_create:
4457 * Create a MonoAotTrampInfo structure from the arguments.
4460 mono_aot_tramp_info_create (const char *name, guint8 *code, guint32 code_size)
4462 MonoAotTrampInfo *info = g_new0 (MonoAotTrampInfo, 1);
4464 info->name = (char*)name;
4466 info->code_size = code_size;
4471 #if !defined(DISABLE_AOT) && !defined(DISABLE_JIT)
4473 typedef struct HashEntry {
4474 guint32 key, value, index;
4475 struct HashEntry *next;
4479 * emit_extra_methods:
4481 * Emit methods which are not in the METHOD table, like wrappers.
4484 emit_extra_methods (MonoAotCompile *acfg)
4486 int i, table_size, buf_size;
4489 guint32 *info_offsets;
4492 HashEntry *entry, *new_entry;
4493 int nmethods, max_chain_length;
4496 info_offsets = g_new0 (guint32, acfg->extra_methods->len);
4498 buf_size = acfg->extra_methods->len * 256 + 256;
4499 p = buf = g_malloc (buf_size);
4501 /* Encode method info */
4503 /* So offsets are > 0 */
4506 for (i = 0; i < acfg->extra_methods->len; ++i) {
4507 MonoMethod *method = g_ptr_array_index (acfg->extra_methods, i);
4508 MonoCompile *cfg = g_hash_table_lookup (acfg->method_to_cfg, method);
4515 info_offsets [i] = p - buf;
4518 if (method->wrapper_type) {
4520 * We encode some wrappers using their name, since encoding them
4521 * directly would be difficult. This also avoids creating the wrapper
4522 * methods at runtime, since they are not needed anyway.
4524 switch (method->wrapper_type) {
4525 case MONO_WRAPPER_REMOTING_INVOKE_WITH_CHECK:
4526 case MONO_WRAPPER_SYNCHRONIZED:
4527 /* encode_method_ref () can handle these */
4529 case MONO_WRAPPER_RUNTIME_INVOKE:
4530 if (mono_marshal_method_from_wrapper (method) != method && !strstr (method->name, "virtual"))
4531 /* Direct wrapper, encode normally */
4535 name = mono_aot_wrapper_name (method);
4541 encode_value (1, p, &p);
4542 encode_value (method->wrapper_type, p, &p);
4543 strcpy ((char*)p, name);
4544 p += strlen (name ) + 1;
4547 encode_value (0, p, &p);
4548 encode_method_ref (acfg, method, p, &p);
4551 g_assert ((p - buf) < buf_size);
4554 g_assert ((p - buf) < buf_size);
4556 /* Emit method info */
4557 sprintf (symbol, "extra_method_info");
4558 emit_section_change (acfg, ".text", 1);
4559 emit_global (acfg, symbol, FALSE);
4560 emit_alignment (acfg, 8);
4561 emit_label (acfg, symbol);
4563 emit_bytes (acfg, buf, p - buf);
4568 * Construct a chained hash table for mapping indexes in extra_method_info to
4571 table_size = g_spaced_primes_closest ((int)(nmethods * 1.5));
4572 table = g_ptr_array_sized_new (table_size);
4573 for (i = 0; i < table_size; ++i)
4574 g_ptr_array_add (table, NULL);
4575 chain_lengths = g_new0 (int, table_size);
4576 max_chain_length = 0;
4577 for (i = 0; i < acfg->extra_methods->len; ++i) {
4578 MonoMethod *method = g_ptr_array_index (acfg->extra_methods, i);
4579 MonoCompile *cfg = g_hash_table_lookup (acfg->method_to_cfg, method);
4585 key = info_offsets [i];
4586 value = get_method_index (acfg, method);
4588 hash = mono_aot_method_hash (method) % table_size;
4590 chain_lengths [hash] ++;
4591 max_chain_length = MAX (max_chain_length, chain_lengths [hash]);
4593 new_entry = mono_mempool_alloc0 (acfg->mempool, sizeof (HashEntry));
4594 new_entry->key = key;
4595 new_entry->value = value;
4597 entry = g_ptr_array_index (table, hash);
4598 if (entry == NULL) {
4599 new_entry->index = hash;
4600 g_ptr_array_index (table, hash) = new_entry;
4603 entry = entry->next;
4605 entry->next = new_entry;
4606 new_entry->index = table->len;
4607 g_ptr_array_add (table, new_entry);
4611 //printf ("MAX: %d\n", max_chain_length);
4613 /* Emit the table */
4614 sprintf (symbol, "extra_method_table");
4615 emit_section_change (acfg, ".text", 0);
4616 emit_global (acfg, symbol, FALSE);
4617 emit_alignment (acfg, 8);
4618 emit_label (acfg, symbol);
4620 emit_int32 (acfg, table_size);
4621 for (i = 0; i < table->len; ++i) {
4622 HashEntry *entry = g_ptr_array_index (table, i);
4624 if (entry == NULL) {
4625 emit_int32 (acfg, 0);
4626 emit_int32 (acfg, 0);
4627 emit_int32 (acfg, 0);
4629 //g_assert (entry->key > 0);
4630 emit_int32 (acfg, entry->key);
4631 emit_int32 (acfg, entry->value);
4633 emit_int32 (acfg, entry->next->index);
4635 emit_int32 (acfg, 0);
4640 * Emit a table reverse mapping method indexes to their index in extra_method_info.
4641 * This is used by mono_aot_find_jit_info ().
4643 sprintf (symbol, "extra_method_info_offsets");
4644 emit_section_change (acfg, ".text", 0);
4645 emit_global (acfg, symbol, FALSE);
4646 emit_alignment (acfg, 8);
4647 emit_label (acfg, symbol);
4649 emit_int32 (acfg, acfg->extra_methods->len);
4650 for (i = 0; i < acfg->extra_methods->len; ++i) {
4651 MonoMethod *method = g_ptr_array_index (acfg->extra_methods, i);
4653 emit_int32 (acfg, get_method_index (acfg, method));
4654 emit_int32 (acfg, info_offsets [i]);
4659 emit_exception_info (MonoAotCompile *acfg)
4664 sprintf (symbol, "ex_info");
4665 emit_section_change (acfg, ".text", 1);
4666 emit_global (acfg, symbol, FALSE);
4667 emit_alignment (acfg, 8);
4668 emit_label (acfg, symbol);
4670 /* To reduce size of generated assembly */
4671 sprintf (symbol, "ex");
4672 emit_label (acfg, symbol);
4674 for (i = 0; i < acfg->nmethods; ++i) {
4676 emit_exception_debug_info (acfg, acfg->cfgs [i]);
4679 sprintf (symbol, "ex_info_offsets");
4680 emit_section_change (acfg, ".text", 1);
4681 emit_global (acfg, symbol, FALSE);
4682 emit_alignment (acfg, 8);
4683 emit_label (acfg, symbol);
4685 for (i = 0; i < acfg->nmethods; ++i) {
4686 if (acfg->cfgs [i]) {
4687 sprintf (symbol, "%se_%x_p", acfg->temp_prefix, i);
4688 emit_symbol_diff (acfg, symbol, "ex", 0);
4690 emit_int32 (acfg, 0);
4697 emit_unwind_info (MonoAotCompile *acfg)
4703 * The unwind info contains a lot of duplicates so we emit each unique
4704 * entry once, and only store the offset from the start of the table in the
4708 sprintf (symbol, "unwind_info");
4709 emit_section_change (acfg, ".text", 1);
4710 emit_alignment (acfg, 8);
4711 emit_label (acfg, symbol);
4712 emit_global (acfg, symbol, FALSE);
4714 for (i = 0; i < acfg->unwind_ops->len; ++i) {
4715 guint32 index = GPOINTER_TO_UINT (g_ptr_array_index (acfg->unwind_ops, i));
4716 guint8 *unwind_info;
4717 guint32 unwind_info_len;
4721 unwind_info = mono_get_cached_unwind_info (index, &unwind_info_len);
4724 encode_value (unwind_info_len, p, &p);
4725 emit_bytes (acfg, buf, p - buf);
4726 emit_bytes (acfg, unwind_info, unwind_info_len);
4728 acfg->stats.unwind_info_size += (p - buf) + unwind_info_len;
4733 emit_class_info (MonoAotCompile *acfg)
4738 sprintf (symbol, "class_info");
4739 emit_section_change (acfg, ".text", 1);
4740 emit_global (acfg, symbol, FALSE);
4741 emit_alignment (acfg, 8);
4742 emit_label (acfg, symbol);
4744 for (i = 0; i < acfg->image->tables [MONO_TABLE_TYPEDEF].rows; ++i)
4745 emit_klass_info (acfg, MONO_TOKEN_TYPE_DEF | (i + 1));
4747 sprintf (symbol, "class_info_offsets");
4748 emit_section_change (acfg, ".text", 1);
4749 emit_global (acfg, symbol, FALSE);
4750 emit_alignment (acfg, 8);
4751 emit_label (acfg, symbol);
4753 for (i = 0; i < acfg->image->tables [MONO_TABLE_TYPEDEF].rows; ++i) {
4754 sprintf (symbol, "%sK_I_%x", acfg->temp_prefix, i);
4755 emit_symbol_diff (acfg, symbol, "class_info", 0);
4760 typedef struct ClassNameTableEntry {
4761 guint32 token, index;
4762 struct ClassNameTableEntry *next;
4763 } ClassNameTableEntry;
4766 emit_class_name_table (MonoAotCompile *acfg)
4769 guint32 token, hash;
4774 ClassNameTableEntry *entry, *new_entry;
4777 * Construct a chained hash table for mapping class names to typedef tokens.
4779 table_size = g_spaced_primes_closest ((int)(acfg->image->tables [MONO_TABLE_TYPEDEF].rows * 1.5));
4780 table = g_ptr_array_sized_new (table_size);
4781 for (i = 0; i < table_size; ++i)
4782 g_ptr_array_add (table, NULL);
4783 for (i = 0; i < acfg->image->tables [MONO_TABLE_TYPEDEF].rows; ++i) {
4784 token = MONO_TOKEN_TYPE_DEF | (i + 1);
4785 klass = mono_class_get (acfg->image, token);
4786 full_name = mono_type_get_name_full (mono_class_get_type (klass), MONO_TYPE_NAME_FORMAT_FULL_NAME);
4787 hash = mono_aot_str_hash (full_name) % table_size;
4790 /* FIXME: Allocate from the mempool */
4791 new_entry = g_new0 (ClassNameTableEntry, 1);
4792 new_entry->token = token;
4794 entry = g_ptr_array_index (table, hash);
4795 if (entry == NULL) {
4796 new_entry->index = hash;
4797 g_ptr_array_index (table, hash) = new_entry;
4800 entry = entry->next;
4802 entry->next = new_entry;
4803 new_entry->index = table->len;
4804 g_ptr_array_add (table, new_entry);
4808 /* Emit the table */
4809 sprintf (symbol, "class_name_table");
4810 emit_section_change (acfg, ".text", 0);
4811 emit_global (acfg, symbol, FALSE);
4812 emit_alignment (acfg, 8);
4813 emit_label (acfg, symbol);
4815 /* FIXME: Optimize memory usage */
4816 g_assert (table_size < 65000);
4817 emit_int16 (acfg, table_size);
4818 g_assert (table->len < 65000);
4819 for (i = 0; i < table->len; ++i) {
4820 ClassNameTableEntry *entry = g_ptr_array_index (table, i);
4822 if (entry == NULL) {
4823 emit_int16 (acfg, 0);
4824 emit_int16 (acfg, 0);
4826 emit_int16 (acfg, mono_metadata_token_index (entry->token));
4828 emit_int16 (acfg, entry->next->index);
4830 emit_int16 (acfg, 0);
4836 emit_image_table (MonoAotCompile *acfg)
4842 * The image table is small but referenced in a lot of places.
4843 * So we emit it at once, and reference its elements by an index.
4846 sprintf (symbol, "mono_image_table");
4847 emit_section_change (acfg, ".text", 1);
4848 emit_global (acfg, symbol, FALSE);
4849 emit_alignment (acfg, 8);
4850 emit_label (acfg, symbol);
4852 emit_int32 (acfg, acfg->image_table->len);
4853 for (i = 0; i < acfg->image_table->len; i++) {
4854 MonoImage *image = (MonoImage*)g_ptr_array_index (acfg->image_table, i);
4855 MonoAssemblyName *aname = &image->assembly->aname;
4857 /* FIXME: Support multi-module assemblies */
4858 g_assert (image->assembly->image == image);
4860 emit_string (acfg, image->assembly_name);
4861 emit_string (acfg, image->guid);
4862 emit_string (acfg, aname->culture ? aname->culture : "");
4863 emit_string (acfg, (const char*)aname->public_key_token);
4865 emit_alignment (acfg, 8);
4866 emit_int32 (acfg, aname->flags);
4867 emit_int32 (acfg, aname->major);
4868 emit_int32 (acfg, aname->minor);
4869 emit_int32 (acfg, aname->build);
4870 emit_int32 (acfg, aname->revision);
4875 emit_got_info (MonoAotCompile *acfg)
4878 int i, first_plt_got_patch, buf_size;
4880 guint32 *got_info_offsets;
4882 /* Add the patches needed by the PLT to the GOT */
4883 acfg->plt_got_offset_base = acfg->got_offset;
4884 first_plt_got_patch = acfg->got_patches->len;
4885 for (i = 1; i < acfg->plt_offset; ++i) {
4886 MonoJumpInfo *patch_info = g_hash_table_lookup (acfg->plt_offset_to_patch, GUINT_TO_POINTER (i));
4888 g_ptr_array_add (acfg->got_patches, patch_info);
4891 acfg->got_offset += acfg->plt_offset;
4895 * - optimize offsets table.
4896 * - reduce number of exported symbols.
4897 * - emit info for a klass only once.
4898 * - determine when a method uses a GOT slot which is guaranteed to be already
4900 * - clean up and document the code.
4901 * - use String.Empty in class libs.
4904 /* Encode info required to decode shared GOT entries */
4905 buf_size = acfg->got_patches->len * 64;
4906 p = buf = mono_mempool_alloc (acfg->mempool, buf_size);
4907 got_info_offsets = mono_mempool_alloc (acfg->mempool, acfg->got_patches->len * sizeof (guint32));
4908 acfg->plt_got_info_offsets = mono_mempool_alloc (acfg->mempool, acfg->plt_offset * sizeof (guint32));
4910 if (acfg->plt_offset)
4911 acfg->plt_got_info_offsets [0] = 0;
4912 for (i = 0; i < acfg->got_patches->len; ++i) {
4913 MonoJumpInfo *ji = g_ptr_array_index (acfg->got_patches, i);
4915 got_info_offsets [i] = p - buf;
4916 if (i >= first_plt_got_patch)
4917 acfg->plt_got_info_offsets [i - first_plt_got_patch + 1] = got_info_offsets [i];
4918 encode_value (ji->type, p, &p);
4919 encode_patch (acfg, ji, p, &p);
4922 g_assert (p - buf <= buf_size);
4924 acfg->stats.got_info_size = p - buf;
4926 /* Emit got_info table */
4927 sprintf (symbol, "got_info");
4928 emit_section_change (acfg, ".text", 1);
4929 emit_global (acfg, symbol, FALSE);
4930 emit_alignment (acfg, 8);
4931 emit_label (acfg, symbol);
4933 emit_bytes (acfg, buf, p - buf);
4935 /* Emit got_info_offsets table */
4936 sprintf (symbol, "got_info_offsets");
4937 emit_section_change (acfg, ".text", 1);
4938 emit_global (acfg, symbol, FALSE);
4939 emit_alignment (acfg, 8);
4940 emit_label (acfg, symbol);
4942 /* No need to emit offsets for the got plt entries, the plt embeds them directly */
4943 for (i = 0; i < first_plt_got_patch; ++i)
4944 emit_int32 (acfg, got_info_offsets [i]);
4946 acfg->stats.got_info_offsets_size = acfg->got_patches->len * 4;
4950 emit_got (MonoAotCompile *acfg)
4955 /* Don't make GOT global so accesses to it don't need relocations */
4956 sprintf (symbol, "%s", acfg->got_symbol);
4957 emit_section_change (acfg, ".bss", 0);
4958 emit_alignment (acfg, 8);
4959 emit_local_symbol (acfg, symbol, "got_end", FALSE);
4960 emit_label (acfg, symbol);
4961 if (acfg->got_offset > 0)
4962 emit_zero_bytes (acfg, (int)(acfg->got_offset * sizeof (gpointer)));
4964 sprintf (symbol, "got_end");
4965 emit_label (acfg, symbol);
4968 sprintf (symbol, "mono_aot_got_addr");
4969 emit_section_change (acfg, ".data", 0);
4970 emit_global (acfg, symbol, FALSE);
4971 emit_alignment (acfg, 8);
4972 emit_label (acfg, symbol);
4973 emit_pointer (acfg, acfg->got_symbol);
4977 emit_globals (MonoAotCompile *acfg)
4982 emit_string_symbol (acfg, "mono_assembly_guid" , acfg->image->guid);
4984 emit_string_symbol (acfg, "mono_aot_version", MONO_AOT_FILE_VERSION);
4986 opts_str = g_strdup_printf ("%d", acfg->opts);
4987 emit_string_symbol (acfg, "mono_aot_opt_flags", opts_str);
4990 emit_string_symbol (acfg, "mono_aot_full_aot", acfg->aot_opts.full_aot ? "TRUE" : "FALSE");
4992 if (acfg->aot_opts.bind_to_runtime_version) {
4993 build_info = mono_get_runtime_build_info ();
4994 emit_string_symbol (acfg, "mono_runtime_version", build_info);
4995 g_free (build_info);
4997 emit_string_symbol (acfg, "mono_runtime_version", "");
5001 * When static linking, we emit a global which will point to the symbol table.
5003 if (acfg->aot_opts.static_link) {
5008 /* Emit a string holding the assembly name */
5009 emit_string_symbol (acfg, "mono_aot_assembly_name", acfg->image->assembly->aname.name);
5011 /* Emit the names */
5012 for (i = 0; i < acfg->globals->len; ++i) {
5013 char *name = g_ptr_array_index (acfg->globals, i);
5015 sprintf (symbol, "name_%d", i);
5016 emit_section_change (acfg, ".text", 1);
5017 emit_label (acfg, symbol);
5018 emit_string (acfg, name);
5021 /* Emit the globals table */
5022 sprintf (symbol, ".Lglobals");
5023 emit_section_change (acfg, ".data", 0);
5024 /* This is not a global, since it is accessed by the init function */
5025 emit_alignment (acfg, 8);
5026 emit_label (acfg, symbol);
5028 for (i = 0; i < acfg->globals->len; ++i) {
5029 char *name = g_ptr_array_index (acfg->globals, i);
5031 sprintf (symbol, "name_%d", i);
5032 emit_pointer (acfg, symbol);
5034 sprintf (symbol, "%s", name);
5035 emit_pointer (acfg, symbol);
5037 /* Null terminate the table */
5038 emit_int32 (acfg, 0);
5039 emit_int32 (acfg, 0);
5042 * Emit a global symbol which can be passed by an embedding app to
5043 * mono_aot_register_module ().
5045 #if defined(__MACH__)
5046 sprintf (symbol, "_mono_aot_module_%s_info", acfg->image->assembly->aname.name);
5048 sprintf (symbol, "mono_aot_module_%s_info", acfg->image->assembly->aname.name);
5051 /* Get rid of characters which cannot occur in symbols */
5053 for (p = symbol; *p; ++p) {
5054 if (!(isalnum (*p) || *p == '_'))
5057 acfg->static_linking_symbol = g_strdup (symbol);
5058 emit_global_inner (acfg, symbol, FALSE);
5059 emit_alignment (acfg, 8);
5060 emit_label (acfg, symbol);
5061 emit_pointer (acfg, ".Lglobals");
5066 emit_autoreg (MonoAotCompile *acfg)
5071 * Emit a function into the .ctor section which will be called by the ELF
5072 * loader to register this module with the runtime.
5074 if (! (!acfg->use_bin_writer && acfg->aot_opts.static_link && acfg->aot_opts.autoreg))
5077 symbol = g_strdup_printf ("_%s_autoreg", acfg->static_linking_symbol);
5079 #if defined(TARGET_POWERPC) && defined(__mono_ilp32__)
5080 /* Based on code generated by gcc */
5081 img_writer_emit_unset_mode (acfg->w);
5085 ".section .ctors,\"aw\",@progbits\n"
5089 ".section .opd,\"aw\"\n"
5092 ".long .%s,.TOC.@tocbase32\n"
5095 ".type .%s,@function\n"
5096 ".%s:\n", symbol, symbol, symbol, symbol, symbol, symbol, symbol, symbol);
5098 ".section .ctors,\"aw\",@progbits\n"
5102 ".section .opd,\"aw\"\n"
5105 ".long .%1$s,.TOC.@tocbase32\n"
5106 ".size %1$s,.-%1$s\n"
5108 ".type .%1$s,@function\n"
5109 ".%1$s:\n", symbol);
5120 "lis 3, .Lglobals@h\n"
5121 "ori 3, 3, .Lglobals@l\n"
5122 "bl .mono_aot_register_module\n"
5132 ".size .%s,.-.%s\n", symbol, symbol);
5135 ".size .%1$s,.-.%1$s\n", symbol);
5138 g_assert_not_reached ();
5145 emit_mem_end (MonoAotCompile *acfg)
5149 sprintf (symbol, "mem_end");
5150 emit_section_change (acfg, ".text", 1);
5151 emit_global (acfg, symbol, FALSE);
5152 emit_alignment (acfg, 8);
5153 emit_label (acfg, symbol);
5157 * Emit a structure containing all the information not stored elsewhere.
5160 emit_file_info (MonoAotCompile *acfg)
5165 sprintf (symbol, "mono_aot_file_info");
5166 emit_section_change (acfg, ".data", 0);
5167 emit_alignment (acfg, 8);
5168 emit_label (acfg, symbol);
5169 emit_global (acfg, symbol, FALSE);
5171 /* The data emitted here must match MonoAotFileInfo in aot-runtime.c. */
5172 emit_int32 (acfg, acfg->plt_got_offset_base);
5173 emit_int32 (acfg, (int)(acfg->got_offset * sizeof (gpointer)));
5174 emit_int32 (acfg, acfg->plt_offset);
5175 emit_int32 (acfg, acfg->nmethods);
5176 emit_int32 (acfg, acfg->flags);
5178 for (i = 0; i < MONO_AOT_TRAMP_NUM; ++i)
5179 emit_int32 (acfg, acfg->num_trampolines [i]);
5180 for (i = 0; i < MONO_AOT_TRAMP_NUM; ++i)
5181 emit_int32 (acfg, acfg->trampoline_got_offset_base [i]);
5182 for (i = 0; i < MONO_AOT_TRAMP_NUM; ++i)
5183 emit_int32 (acfg, acfg->trampoline_size [i]);
5187 emit_dwarf_info (MonoAotCompile *acfg)
5189 #ifdef EMIT_DWARF_INFO
5191 char symbol [128], symbol2 [128];
5193 /* DIEs for methods */
5194 for (i = 0; i < acfg->nmethods; ++i) {
5195 MonoCompile *cfg = acfg->cfgs [i];
5200 // FIXME: LLVM doesn't define .Lme_...
5201 if (cfg->compile_llvm)
5204 sprintf (symbol, "%sm_%x", acfg->temp_prefix, i);
5205 sprintf (symbol2, "%sme_%x", acfg->temp_prefix, i);
5207 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 ()));
5213 collect_methods (MonoAotCompile *acfg)
5216 MonoImage *image = acfg->image;
5218 /* Collect methods */
5219 for (i = 0; i < image->tables [MONO_TABLE_METHOD].rows; ++i) {
5221 guint32 token = MONO_TOKEN_METHOD_DEF | (i + 1);
5223 method = mono_get_method (acfg->image, token, NULL);
5226 printf ("Failed to load method 0x%x from '%s'.\n", token, image->name);
5230 /* Load all methods eagerly to skip the slower lazy loading code */
5231 mono_class_setup_methods (method->klass);
5233 if (acfg->aot_opts.full_aot && method->iflags & METHOD_IMPL_ATTRIBUTE_INTERNAL_CALL) {
5234 /* Compile the wrapper instead */
5235 /* We do this here instead of add_wrappers () because it is easy to do it here */
5236 MonoMethod *wrapper = mono_marshal_get_native_wrapper (method, check_for_pending_exc, TRUE);
5240 /* FIXME: Some mscorlib methods don't have debug info */
5242 if (acfg->aot_opts.soft_debug && !method->wrapper_type) {
5243 if (!((method->flags & METHOD_ATTRIBUTE_PINVOKE_IMPL) ||
5244 (method->iflags & METHOD_IMPL_ATTRIBUTE_RUNTIME) ||
5245 (method->flags & METHOD_ATTRIBUTE_ABSTRACT) ||
5246 (method->iflags & METHOD_IMPL_ATTRIBUTE_INTERNAL_CALL))) {
5247 if (!mono_debug_lookup_method (method)) {
5248 fprintf (stderr, "Method %s has no debug info, probably the .mdb file for the assembly is missing.\n", mono_method_full_name (method, TRUE));
5255 /* Since we add the normal methods first, their index will be equal to their zero based token index */
5256 add_method_with_index (acfg, method, i, FALSE);
5257 acfg->method_index ++;
5260 add_generic_instances (acfg);
5262 if (acfg->aot_opts.full_aot)
5263 add_wrappers (acfg);
5267 compile_methods (MonoAotCompile *acfg)
5271 if (acfg->aot_opts.nthreads > 0) {
5276 gpointer *user_data;
5277 MonoMethod **methods;
5279 methods_len = acfg->methods->len;
5281 len = acfg->methods->len / acfg->aot_opts.nthreads;
5284 * Partition the list of methods into fragments, and hand it to threads to
5287 threads = g_ptr_array_new ();
5288 /* Make a copy since acfg->methods is modified by compile_method () */
5289 methods = g_new0 (MonoMethod*, methods_len);
5290 //memcpy (methods, g_ptr_array_index (acfg->methods, 0), sizeof (MonoMethod*) * methods_len);
5291 for (i = 0; i < methods_len; ++i)
5292 methods [i] = g_ptr_array_index (acfg->methods, i);
5294 while (i < methods_len) {
5295 frag = g_ptr_array_new ();
5296 for (j = 0; j < len; ++j) {
5297 if (i < methods_len) {
5298 g_ptr_array_add (frag, methods [i]);
5303 user_data = g_new0 (gpointer, 3);
5304 user_data [0] = mono_domain_get ();
5305 user_data [1] = acfg;
5306 user_data [2] = frag;
5308 handle = mono_create_thread (NULL, 0, (gpointer)compile_thread_main, user_data, 0, NULL);
5309 g_ptr_array_add (threads, handle);
5313 for (i = 0; i < threads->len; ++i) {
5314 WaitForSingleObjectEx (g_ptr_array_index (threads, i), INFINITE, FALSE);
5320 /* Compile methods added by compile_method () or all methods if nthreads == 0 */
5321 for (i = methods_len; i < acfg->methods->len; ++i) {
5322 /* This can new methods to acfg->methods */
5323 compile_method (acfg, g_ptr_array_index (acfg->methods, i));
5328 compile_asm (MonoAotCompile *acfg)
5330 char *command, *objfile;
5331 char *outfile_name, *tmp_outfile_name;
5332 const char *tool_prefix = acfg->aot_opts.tool_prefix ? acfg->aot_opts.tool_prefix : "";
5334 #if defined(TARGET_AMD64)
5335 #define AS_OPTIONS "--64"
5336 #elif defined(TARGET_POWERPC64)
5337 #define AS_OPTIONS "-a64 -mppc64"
5338 #define LD_OPTIONS "-m elf64ppc"
5339 #elif defined(sparc) && SIZEOF_VOID_P == 8
5340 #define AS_OPTIONS "-xarch=v9"
5342 #define AS_OPTIONS ""
5346 #define LD_OPTIONS ""
5350 #define EH_LD_OPTIONS "--eh-frame-hdr"
5352 #define EH_LD_OPTIONS ""
5355 if (acfg->aot_opts.asm_only) {
5356 printf ("Output file: '%s'.\n", acfg->tmpfname);
5357 if (acfg->aot_opts.static_link)
5358 printf ("Linking symbol: '%s'.\n", acfg->static_linking_symbol);
5362 if (acfg->aot_opts.static_link) {
5363 if (acfg->aot_opts.outfile)
5364 objfile = g_strdup_printf ("%s", acfg->aot_opts.outfile);
5366 objfile = g_strdup_printf ("%s.o", acfg->image->name);
5368 objfile = g_strdup_printf ("%s.o", acfg->tmpfname);
5370 command = g_strdup_printf ("%sas %s %s -o %s", tool_prefix, AS_OPTIONS, acfg->tmpfname, objfile);
5371 printf ("Executing the native assembler: %s\n", command);
5372 if (system (command) != 0) {
5380 if (acfg->aot_opts.static_link) {
5381 printf ("Output file: '%s'.\n", objfile);
5382 printf ("Linking symbol: '%s'.\n", acfg->static_linking_symbol);
5387 if (acfg->aot_opts.outfile)
5388 outfile_name = g_strdup_printf ("%s", acfg->aot_opts.outfile);
5390 outfile_name = g_strdup_printf ("%s%s", acfg->image->name, SHARED_EXT);
5392 tmp_outfile_name = g_strdup_printf ("%s.tmp", outfile_name);
5395 command = g_strdup_printf ("ld -shared -G -o %s %s.o", tmp_outfile_name, acfg->tmpfname);
5396 #elif defined(__ppc__) && defined(__MACH__)
5397 command = g_strdup_printf ("gcc -dynamiclib -o %s %s.o", tmp_outfile_name, acfg->tmpfname);
5398 #elif defined(HOST_WIN32)
5399 command = g_strdup_printf ("gcc -shared --dll -mno-cygwin -o %s %s.o", tmp_outfile_name, acfg->tmpfname);
5401 command = g_strdup_printf ("%sld %s %s -shared -o %s %s.o", tool_prefix, EH_LD_OPTIONS, LD_OPTIONS, tmp_outfile_name, acfg->tmpfname);
5403 printf ("Executing the native linker: %s\n", command);
5404 if (system (command) != 0) {
5405 g_free (tmp_outfile_name);
5406 g_free (outfile_name);
5414 /*com = g_strdup_printf ("strip --strip-unneeded %s%s", acfg->image->name, SHARED_EXT);
5415 printf ("Stripping the binary: %s\n", com);
5419 #if defined(TARGET_ARM) && !defined(__MACH__)
5421 * gas generates 'mapping symbols' each time code and data is mixed, which
5422 * happens a lot in emit_and_reloc_code (), so we need to get rid of them.
5424 command = g_strdup_printf ("%sstrip --strip-symbol=\\$a --strip-symbol=\\$d %s", tool_prefix, tmp_outfile_name);
5425 printf ("Stripping the binary: %s\n", command);
5426 if (system (command) != 0) {
5427 g_free (tmp_outfile_name);
5428 g_free (outfile_name);
5435 rename (tmp_outfile_name, outfile_name);
5437 g_free (tmp_outfile_name);
5438 g_free (outfile_name);
5441 if (acfg->aot_opts.save_temps)
5442 printf ("Retained input file.\n");
5444 unlink (acfg->tmpfname);
5449 static MonoAotCompile*
5450 acfg_create (MonoAssembly *ass, guint32 opts)
5452 MonoImage *image = ass->image;
5453 MonoAotCompile *acfg;
5456 acfg = g_new0 (MonoAotCompile, 1);
5457 acfg->methods = g_ptr_array_new ();
5458 acfg->method_indexes = g_hash_table_new (NULL, NULL);
5459 acfg->method_depth = g_hash_table_new (NULL, NULL);
5460 acfg->plt_offset_to_patch = g_hash_table_new (NULL, NULL);
5461 acfg->patch_to_plt_offset = g_hash_table_new (mono_patch_info_hash, mono_patch_info_equal);
5462 acfg->patch_to_got_offset = g_hash_table_new (mono_patch_info_hash, mono_patch_info_equal);
5463 acfg->patch_to_got_offset_by_type = g_new0 (GHashTable*, MONO_PATCH_INFO_NUM);
5464 for (i = 0; i < MONO_PATCH_INFO_NUM; ++i)
5465 acfg->patch_to_got_offset_by_type [i] = g_hash_table_new (mono_patch_info_hash, mono_patch_info_equal);
5466 acfg->got_patches = g_ptr_array_new ();
5467 acfg->method_to_cfg = g_hash_table_new (NULL, NULL);
5468 acfg->token_info_hash = g_hash_table_new_full (NULL, NULL, NULL, g_free);
5469 acfg->image_hash = g_hash_table_new (NULL, NULL);
5470 acfg->image_table = g_ptr_array_new ();
5471 acfg->globals = g_ptr_array_new ();
5472 acfg->image = image;
5474 acfg->mempool = mono_mempool_new ();
5475 acfg->extra_methods = g_ptr_array_new ();
5476 acfg->unwind_info_offsets = g_hash_table_new (NULL, NULL);
5477 acfg->unwind_ops = g_ptr_array_new ();
5478 acfg->method_label_hash = g_hash_table_new_full (g_str_hash, g_str_equal, g_free, NULL);
5479 InitializeCriticalSection (&acfg->mutex);
5485 acfg_free (MonoAotCompile *acfg)
5489 img_writer_destroy (acfg->w);
5490 for (i = 0; i < acfg->nmethods; ++i)
5492 g_free (acfg->cfgs [i]);
5493 g_free (acfg->cfgs);
5494 g_free (acfg->static_linking_symbol);
5495 g_free (acfg->got_symbol);
5496 g_free (acfg->plt_symbol);
5497 g_ptr_array_free (acfg->methods, TRUE);
5498 g_ptr_array_free (acfg->got_patches, TRUE);
5499 g_ptr_array_free (acfg->image_table, TRUE);
5500 g_ptr_array_free (acfg->globals, TRUE);
5501 g_ptr_array_free (acfg->unwind_ops, TRUE);
5502 g_hash_table_destroy (acfg->method_indexes);
5503 g_hash_table_destroy (acfg->method_depth);
5504 g_hash_table_destroy (acfg->plt_offset_to_patch);
5505 g_hash_table_destroy (acfg->patch_to_plt_offset);
5506 g_hash_table_destroy (acfg->patch_to_got_offset);
5507 g_hash_table_destroy (acfg->method_to_cfg);
5508 g_hash_table_destroy (acfg->token_info_hash);
5509 g_hash_table_destroy (acfg->image_hash);
5510 g_hash_table_destroy (acfg->unwind_info_offsets);
5511 g_hash_table_destroy (acfg->method_label_hash);
5512 for (i = 0; i < MONO_PATCH_INFO_NUM; ++i)
5513 g_hash_table_destroy (acfg->patch_to_got_offset_by_type [i]);
5514 g_free (acfg->patch_to_got_offset_by_type);
5515 mono_mempool_destroy (acfg->mempool);
5520 mono_compile_assembly (MonoAssembly *ass, guint32 opts, const char *aot_options)
5522 MonoImage *image = ass->image;
5524 MonoAotCompile *acfg;
5525 char *outfile_name, *tmp_outfile_name, *p;
5529 printf ("Mono Ahead of Time compiler - compiling assembly %s\n", image->name);
5531 acfg = acfg_create (ass, opts);
5533 memset (&acfg->aot_opts, 0, sizeof (acfg->aot_opts));
5534 acfg->aot_opts.write_symbols = TRUE;
5535 acfg->aot_opts.ntrampolines = 1024;
5537 mono_aot_parse_options (aot_options, &acfg->aot_opts);
5539 if (acfg->aot_opts.static_link)
5540 acfg->aot_opts.autoreg = TRUE;
5542 //acfg->aot_opts.print_skipped_methods = TRUE;
5544 #ifndef MONO_ARCH_HAVE_FULL_AOT_TRAMPOLINES
5545 if (acfg->aot_opts.full_aot) {
5546 printf ("--aot=full is not supported on this platform.\n");
5551 if (acfg->aot_opts.static_link)
5552 acfg->aot_opts.asm_writer = TRUE;
5554 if (acfg->aot_opts.soft_debug) {
5555 MonoDebugOptions *opt = mini_get_debug_options ();
5557 opt->mdb_optimizations = TRUE;
5558 opt->gen_seq_points = TRUE;
5560 if (mono_debug_format == MONO_DEBUG_FORMAT_NONE) {
5561 fprintf (stderr, "The soft-debug AOT option requires the --debug option.\n");
5568 acfg->aot_opts.asm_writer = TRUE;
5569 acfg->flags |= MONO_AOT_FILE_FLAG_WITH_LLVM;
5572 load_profile_files (acfg);
5574 acfg->num_trampolines [MONO_AOT_TRAMP_SPECIFIC] = acfg->aot_opts.full_aot ? acfg->aot_opts.ntrampolines : 0;
5575 #ifdef MONO_ARCH_HAVE_STATIC_RGCTX_TRAMPOLINE
5576 acfg->num_trampolines [MONO_AOT_TRAMP_STATIC_RGCTX] = acfg->aot_opts.full_aot ? 1024 : 0;
5578 acfg->num_trampolines [MONO_AOT_TRAMP_IMT_THUNK] = acfg->aot_opts.full_aot ? 128 : 0;
5580 acfg->got_symbol = g_strdup_printf ("mono_aot_%s_got", acfg->image->assembly->aname.name);
5581 acfg->plt_symbol = g_strdup_printf ("mono_aot_%s_plt", acfg->image->assembly->aname.name);
5583 /* Get rid of characters which cannot occur in symbols */
5584 for (p = acfg->got_symbol; *p; ++p) {
5585 if (!(isalnum (*p) || *p == '_'))
5588 for (p = acfg->plt_symbol; *p; ++p) {
5589 if (!(isalnum (*p) || *p == '_'))
5593 acfg->method_index = 1;
5595 collect_methods (acfg);
5597 acfg->cfgs_size = acfg->methods->len + 32;
5598 acfg->cfgs = g_new0 (MonoCompile*, acfg->cfgs_size);
5600 /* PLT offset 0 is reserved for the PLT trampoline */
5601 acfg->plt_offset = 1;
5605 mono_llvm_create_aot_module (acfg->got_symbol);
5608 /* GOT offset 0 is reserved for the address of the current assembly */
5612 ji = mono_mempool_alloc0 (acfg->mempool, sizeof (MonoAotCompile));
5613 ji->type = MONO_PATCH_INFO_IMAGE;
5614 ji->data.image = acfg->image;
5616 get_got_offset (acfg, ji);
5618 /* Slot 1 is reserved for the mscorlib got addr */
5619 ji = mono_mempool_alloc0 (acfg->mempool, sizeof (MonoAotCompile));
5620 ji->type = MONO_PATCH_INFO_MSCORLIB_GOT_ADDR;
5621 get_got_offset (acfg, ji);
5626 compile_methods (acfg);
5630 acfg->stats.jit_time = TV_ELAPSED (atv, btv);
5635 emit_llvm_file (acfg);
5638 if (!acfg->aot_opts.asm_only && !acfg->aot_opts.asm_writer && bin_writer_supported ()) {
5639 if (acfg->aot_opts.outfile)
5640 outfile_name = g_strdup_printf ("%s", acfg->aot_opts.outfile);
5642 outfile_name = g_strdup_printf ("%s%s", acfg->image->name, SHARED_EXT);
5645 * Can't use g_file_open_tmp () as it will be deleted at exit, and
5646 * it might be in another file system so the rename () won't work.
5648 tmp_outfile_name = g_strdup_printf ("%s.tmp", outfile_name);
5650 acfg->fp = fopen (tmp_outfile_name, "w");
5652 printf ("Unable to create temporary file '%s': %s\n", tmp_outfile_name, strerror (errno));
5656 acfg->w = img_writer_create (acfg->fp, TRUE);
5657 acfg->use_bin_writer = TRUE;
5660 /* Append to the .s file created by llvm */
5661 /* FIXME: Use multiple files instead */
5662 acfg->tmpfname = g_strdup ("temp.s");
5663 acfg->fp = fopen (acfg->tmpfname, "a");
5665 if (acfg->aot_opts.asm_only) {
5666 if (acfg->aot_opts.outfile)
5667 acfg->tmpfname = g_strdup_printf ("%s", acfg->aot_opts.outfile);
5669 acfg->tmpfname = g_strdup_printf ("%s.s", acfg->image->name);
5670 acfg->fp = fopen (acfg->tmpfname, "w+");
5672 int i = g_file_open_tmp ("mono_aot_XXXXXX", &acfg->tmpfname, NULL);
5673 acfg->fp = fdopen (i, "w+");
5675 g_assert (acfg->fp);
5677 acfg->w = img_writer_create (acfg->fp, FALSE);
5679 tmp_outfile_name = NULL;
5680 outfile_name = NULL;
5683 acfg->temp_prefix = img_writer_get_temp_label_prefix (acfg->w);
5685 if (!acfg->aot_opts.nodebug)
5686 acfg->dwarf = mono_dwarf_writer_create (acfg->w, NULL, 0, FALSE);
5688 img_writer_emit_start (acfg->w);
5691 mono_dwarf_writer_emit_base_info (acfg->dwarf, arch_get_cie_program ());
5697 emit_extra_methods (acfg);
5699 emit_trampolines (acfg);
5701 emit_class_name_table (acfg);
5703 emit_got_info (acfg);
5705 emit_exception_info (acfg);
5707 emit_unwind_info (acfg);
5709 emit_class_info (acfg);
5713 emit_image_table (acfg);
5717 emit_file_info (acfg);
5719 emit_globals (acfg);
5721 emit_autoreg (acfg);
5724 emit_dwarf_info (acfg);
5725 mono_dwarf_writer_close (acfg->dwarf);
5728 emit_mem_end (acfg);
5732 acfg->stats.gen_time = TV_ELAPSED (atv, btv);
5735 g_assert (acfg->got_offset == acfg->final_got_size);
5737 printf ("Code: %d Info: %d Ex Info: %d Unwind Info: %d Class Info: %d PLT: %d GOT Info: %d GOT Info Offsets: %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, acfg->stats.got_info_offsets_size, (int)(acfg->got_offset * sizeof (gpointer)), (int)(acfg->nmethods * 3 * sizeof (gpointer)));
5740 res = img_writer_emit_writeout (acfg->w);
5745 if (acfg->use_bin_writer) {
5746 int err = rename (tmp_outfile_name, outfile_name);
5749 printf ("Unable to rename '%s' to '%s': %s\n", tmp_outfile_name, outfile_name, strerror (errno));
5753 res = compile_asm (acfg);
5760 acfg->stats.link_time = TV_ELAPSED (atv, btv);
5762 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);
5763 if (acfg->stats.genericcount)
5764 printf ("%d methods are generic (%d%%)\n", acfg->stats.genericcount, acfg->stats.mcount ? (acfg->stats.genericcount * 100) / acfg->stats.mcount : 100);
5765 if (acfg->stats.abscount)
5766 printf ("%d methods contain absolute addresses (%d%%)\n", acfg->stats.abscount, acfg->stats.mcount ? (acfg->stats.abscount * 100) / acfg->stats.mcount : 100);
5767 if (acfg->stats.lmfcount)
5768 printf ("%d methods contain lmf pointers (%d%%)\n", acfg->stats.lmfcount, acfg->stats.mcount ? (acfg->stats.lmfcount * 100) / acfg->stats.mcount : 100);
5769 if (acfg->stats.ocount)
5770 printf ("%d methods have other problems (%d%%)\n", acfg->stats.ocount, acfg->stats.mcount ? (acfg->stats.ocount * 100) / acfg->stats.mcount : 100);
5772 printf ("Methods compiled with LLVM: %d (%d%%)\n", acfg->stats.llvm_count, acfg->stats.mcount ? (acfg->stats.llvm_count * 100) / acfg->stats.mcount : 100);
5773 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);
5774 printf ("Direct calls: %d (%d%%)\n", acfg->stats.direct_calls, acfg->stats.all_calls ? (acfg->stats.direct_calls * 100) / acfg->stats.all_calls : 100);
5777 printf ("GOT slot distribution:\n");
5778 for (i = 0; i < MONO_PATCH_INFO_NONE; ++i)
5779 if (acfg->stats.got_slot_types [i])
5780 printf ("\t%s: %d\n", get_patch_name (i), acfg->stats.got_slot_types [i]);
5783 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);
5791 * Support for emitting debug info for JITted code.
5793 * This works as follows:
5794 * - the runtime writes out an xdb.s file containing DWARF debug info.
5795 * - the user calls a gdb macro
5796 * - the macro compiles and loads this shared library using add-symbol-file.
5798 * This is based on the xdebug functionality in the Kaffe Java VM.
5800 * We emit assembly code instead of using the ELF writer, so we can emit debug info
5801 * incrementally as each method is JITted, and the debugger doesn't have to call
5802 * into the runtime to emit the shared library, which would cause all kinds of
5803 * complications, like threading issues, and the fact that the ELF writer's
5804 * emit_writeout () function cannot be called more than once.
5805 * GDB 7.0 and later has a JIT interface.
5808 #define USE_GDB_JIT_INTERFACE
5810 /* The recommended gdb macro is: */
5813 shell rm -f xdb.so && as --64 -o xdb.o xdb.s && ld -shared -o xdb.so xdb.o
5814 add-symbol-file xdb.so 0
5819 * GDB JIT interface definitions.
5821 * http://sources.redhat.com/gdb/onlinedocs/gdb_30.html
5830 struct jit_code_entry
5832 struct jit_code_entry *next_entry;
5833 struct jit_code_entry *prev_entry;
5834 const char *symfile_addr;
5835 guint64 symfile_size;
5838 struct jit_descriptor
5841 /* This type should be jit_actions_t, but we use guint32
5842 to be explicit about the bitwidth. */
5843 guint32 action_flag;
5844 struct jit_code_entry *relevant_entry;
5845 struct jit_code_entry *first_entry;
5850 #define MONO_NOINLINE __declspec (noinline)
5852 #define MONO_NOINLINE __attribute__((noinline))
5855 /* GDB puts a breakpoint in this function. */
5856 void MONO_NOINLINE __jit_debug_register_code(void);
5858 #if defined(ENABLE_LLVM) && ((LLVM_MAJOR_VERSION == 2 && LLVM_MINOR_VERSION >= 7) || LLVM_MAJOR_VERSION > 2)
5859 /* LLVM already defines these */
5860 extern struct jit_descriptor __jit_debug_descriptor;
5863 /* Make sure to specify the version statically, because the
5864 debugger may check the version before we can set it. */
5865 struct jit_descriptor __jit_debug_descriptor = { 1, 0, 0, 0 };
5867 void MONO_NOINLINE __jit_debug_register_code(void) { };
5870 static MonoImageWriter *xdebug_w;
5871 static MonoDwarfWriter *xdebug_writer;
5872 static FILE *xdebug_fp, *il_file;
5873 static gboolean use_gdb_interface, save_symfiles;
5874 static int il_file_line_index;
5875 static GHashTable *xdebug_syms;
5878 mono_xdebug_init (char *options)
5883 args = g_strsplit (options, ",", -1);
5884 for (ptr = args; ptr && *ptr; ptr ++) {
5887 if (!strcmp (arg, "gdb"))
5888 use_gdb_interface = TRUE;
5889 if (!strcmp (arg, "save-symfiles"))
5890 save_symfiles = TRUE;
5893 /* This file will contain the IL code for methods which don't have debug info */
5894 il_file = fopen ("xdb.il", "w");
5896 if (use_gdb_interface)
5900 xdebug_fp = fopen ("xdb.s", "w");
5902 w = img_writer_create (xdebug_fp, FALSE);
5904 img_writer_emit_start (w);
5906 xdebug_writer = mono_dwarf_writer_create (w, il_file, 0, TRUE);
5908 /* Emit something so the file has a text segment */
5909 img_writer_emit_section_change (w, ".text", 0);
5910 img_writer_emit_string (w, "");
5912 mono_dwarf_writer_emit_base_info (xdebug_writer, arch_get_cie_program ());
5916 xdebug_begin_emit (MonoImageWriter **out_w, MonoDwarfWriter **out_dw)
5919 MonoDwarfWriter *dw;
5921 w = img_writer_create (NULL, TRUE);
5923 img_writer_emit_start (w);
5925 /* This file will contain the IL code for methods which don't have debug info */
5927 il_file = fopen ("xdb.il", "w");
5929 dw = mono_dwarf_writer_create (w, il_file, il_file_line_index, FALSE);
5931 mono_dwarf_writer_emit_base_info (dw, arch_get_cie_program ());
5938 xdebug_end_emit (MonoImageWriter *w, MonoDwarfWriter *dw, MonoMethod *method)
5942 struct jit_code_entry *entry;
5944 il_file_line_index = mono_dwarf_writer_get_il_file_line_index (dw);
5945 mono_dwarf_writer_close (dw);
5947 img_writer_emit_writeout (w);
5949 img = img_writer_get_output (w, &img_size);
5951 img_writer_destroy (w);
5954 /* Save the symbol files to help debugging */
5957 static int file_counter;
5960 file_name = g_strdup_printf ("xdb-%d.o", file_counter);
5961 //printf ("%s -> %s\n", mono_method_full_name (method, TRUE), file_name);
5963 fp = fopen (file_name, "w");
5964 fwrite (img, img_size, 1, fp);
5969 /* Register the image with GDB */
5971 entry = g_malloc (sizeof (struct jit_code_entry));
5973 entry->symfile_addr = (const char*)img;
5974 entry->symfile_size = img_size;
5976 entry->next_entry = __jit_debug_descriptor.first_entry;
5977 if (__jit_debug_descriptor.first_entry)
5978 __jit_debug_descriptor.first_entry->prev_entry = entry;
5979 __jit_debug_descriptor.first_entry = entry;
5981 __jit_debug_descriptor.relevant_entry = entry;
5982 __jit_debug_descriptor.action_flag = JIT_REGISTER_FN;
5984 __jit_debug_register_code ();
5988 * mono_xdebug_flush:
5990 * This could be called from inside gdb to flush the debugging information not yet
5991 * registered with gdb.
5994 mono_xdebug_flush (void)
5997 xdebug_end_emit (xdebug_w, xdebug_writer, NULL);
5999 xdebug_begin_emit (&xdebug_w, &xdebug_writer);
6002 static int xdebug_method_count;
6005 * mono_save_xdebug_info:
6007 * Emit debugging info for METHOD into an assembly file which can be assembled
6008 * and loaded into gdb to provide debugging info for JITted code.
6009 * LOCKING: Acquires the loader lock.
6012 mono_save_xdebug_info (MonoCompile *cfg)
6014 if (use_gdb_interface) {
6015 mono_loader_lock ();
6018 xdebug_syms = g_hash_table_new_full (g_str_hash, g_str_equal, g_free, NULL);
6021 * gdb is not designed to handle 1000s of symbol files (one per method). So we
6022 * group them into groups of 100.
6024 if ((xdebug_method_count % 100) == 0)
6025 mono_xdebug_flush ();
6027 xdebug_method_count ++;
6029 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 ()));
6033 * Emit a symbol for the code by emitting it at the beginning of the text
6034 * segment, and setting the text segment to have an absolute address.
6035 * This symbol can be used to set breakpoints in gdb.
6036 * FIXME: This doesn't work when multiple methods are emitted into the same file.
6038 sym = get_debug_sym (cfg->jit_info->method, "", xdebug_syms);
6039 img_writer_emit_section_change (w, ".text", 0);
6040 if (!xdebug_text_addr) {
6041 xdebug_text_addr = cfg->jit_info->code_start;
6042 img_writer_set_section_addr (w, (gssize)xdebug_text_addr);
6044 img_writer_emit_global_with_size (w, sym, cfg->jit_info->code_size, TRUE);
6045 img_writer_emit_label (w, sym);
6046 img_writer_emit_bytes (w, cfg->jit_info->code_start, cfg->jit_info->code_size);
6050 mono_loader_unlock ();
6055 mono_loader_lock ();
6056 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 ()));
6058 mono_loader_unlock ();
6063 * mono_save_trampoline_xdebug_info:
6065 * Same as mono_save_xdebug_info, but for trampolines.
6066 * LOCKING: Acquires the loader lock.
6069 mono_save_trampoline_xdebug_info (const char *tramp_name, guint8 *code, guint32 code_size, GSList *unwind_info)
6071 if (use_gdb_interface) {
6073 MonoDwarfWriter *dw;
6075 mono_loader_lock ();
6077 xdebug_begin_emit (&w, &dw);
6079 mono_dwarf_writer_emit_trampoline (dw, tramp_name, NULL, NULL, code, code_size, unwind_info);
6081 xdebug_end_emit (w, dw, NULL);
6083 mono_loader_unlock ();
6088 mono_loader_lock ();
6089 mono_dwarf_writer_emit_trampoline (xdebug_writer, tramp_name, NULL, NULL, code, code_size, unwind_info);
6091 mono_loader_unlock ();
6100 mono_compile_assembly (MonoAssembly *ass, guint32 opts, const char *aot_options)
6106 mono_xdebug_init (char *options)
6111 mono_save_xdebug_info (MonoCompile *cfg)
6116 mono_save_trampoline_xdebug_info (const char *tramp_name, guint8 *code, guint32 code_size, GSList *unwind_info)