Implement fail tramp support on arm for full-aot imt thunks.
[mono-project.git] / mono / mini / aot-compiler.c
blob95c47d36f27bd2578874a352d33f041bae13e5be
1 /*
2 * aot-compiler.c: mono Ahead of Time compiler
4 * Author:
5 * Dietmar Maurer (dietmar@ximian.com)
6 * Zoltan Varga (vargaz@gmail.com)
8 * (C) 2002 Ximian, Inc.
9 */
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
14 * relocations.
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.
24 #include "config.h"
25 #include <sys/types.h>
26 #ifdef HAVE_UNISTD_H
27 #include <unistd.h>
28 #endif
29 #ifdef HAVE_STDINT_H
30 #include <stdint.h>
31 #endif
32 #include <fcntl.h>
33 #include <ctype.h>
34 #include <string.h>
35 #ifndef HOST_WIN32
36 #include <sys/time.h>
37 #else
38 #include <winsock2.h>
39 #include <windows.h>
40 #endif
42 #include <errno.h>
43 #include <sys/stat.h>
46 #include <mono/metadata/tabledefs.h>
47 #include <mono/metadata/class.h>
48 #include <mono/metadata/object.h>
49 #include <mono/metadata/tokentype.h>
50 #include <mono/metadata/appdomain.h>
51 #include <mono/metadata/debug-helpers.h>
52 #include <mono/metadata/assembly.h>
53 #include <mono/metadata/metadata-internals.h>
54 #include <mono/metadata/marshal.h>
55 #include <mono/metadata/gc-internal.h>
56 #include <mono/metadata/monitor.h>
57 #include <mono/metadata/mempool-internals.h>
58 #include <mono/metadata/mono-endian.h>
59 #include <mono/metadata/threads-types.h>
60 #include <mono/utils/mono-logger-internal.h>
61 #include <mono/utils/mono-compiler.h>
62 #include <mono/utils/mono-time.h>
63 #include <mono/utils/mono-mmap.h>
65 #include "mini.h"
66 #include "image-writer.h"
67 #include "dwarfwriter.h"
69 #if !defined(DISABLE_AOT) && !defined(DISABLE_JIT)
71 #if defined(__linux__) || defined(__native_client_codegen__)
72 #define RODATA_SECT ".rodata"
73 #else
74 #define RODATA_SECT ".text"
75 #endif
77 #define TV_DECLARE(name) gint64 name
78 #define TV_GETTIME(tv) tv = mono_100ns_ticks ()
79 #define TV_ELAPSED(start,end) (((end) - (start)) / 10)
81 #ifdef TARGET_WIN32
82 #define SHARED_EXT ".dll"
83 #elif defined(__ppc__) && defined(__APPLE__)
84 #define SHARED_EXT ".dylib"
85 #elif defined(__APPLE__) && defined(TARGET_X86) && !defined(__native_client_codegen__)
86 #define SHARED_EXT ".dylib"
87 #else
88 #define SHARED_EXT ".so"
89 #endif
91 #define ALIGN_TO(val,align) ((((guint64)val) + ((align) - 1)) & ~((align) - 1))
92 #define ALIGN_PTR_TO(ptr,align) (gpointer)((((gssize)(ptr)) + (align - 1)) & (~(align - 1)))
93 #define ROUND_DOWN(VALUE,SIZE) ((VALUE) & ~((SIZE) - 1))
95 typedef struct MonoAotOptions {
96 char *outfile;
97 gboolean save_temps;
98 gboolean write_symbols;
99 gboolean metadata_only;
100 gboolean bind_to_runtime_version;
101 gboolean full_aot;
102 gboolean no_dlsym;
103 gboolean static_link;
104 gboolean asm_only;
105 gboolean asm_writer;
106 gboolean nodebug;
107 gboolean soft_debug;
108 int nthreads;
109 int ntrampolines;
110 int nrgctx_trampolines;
111 int nimt_trampolines;
112 gboolean print_skipped_methods;
113 gboolean stats;
114 char *tool_prefix;
115 gboolean autoreg;
116 char *mtriple;
117 char *llvm_path;
118 } MonoAotOptions;
120 typedef struct MonoAotStats {
121 int ccount, mcount, lmfcount, abscount, gcount, ocount, genericcount;
122 int code_size, info_size, ex_info_size, unwind_info_size, got_size, class_info_size, got_info_size;
123 int methods_without_got_slots, direct_calls, all_calls, llvm_count;
124 int got_slots, offsets_size;
125 int got_slot_types [MONO_PATCH_INFO_NONE];
126 int jit_time, gen_time, link_time;
127 } MonoAotStats;
129 typedef struct MonoAotCompile {
130 MonoImage *image;
131 GPtrArray *methods;
132 GHashTable *method_indexes;
133 GHashTable *method_depth;
134 MonoCompile **cfgs;
135 int cfgs_size;
136 GHashTable *patch_to_plt_entry;
137 GHashTable *plt_offset_to_entry;
138 GHashTable *patch_to_got_offset;
139 GHashTable **patch_to_got_offset_by_type;
140 GPtrArray *got_patches;
141 GHashTable *image_hash;
142 GHashTable *method_to_cfg;
143 GHashTable *token_info_hash;
144 GPtrArray *extra_methods;
145 GPtrArray *image_table;
146 GPtrArray *globals;
147 GPtrArray *method_order;
148 guint32 *plt_got_info_offsets;
149 guint32 got_offset, plt_offset, plt_got_offset_base;
150 guint32 final_got_size;
151 /* Number of GOT entries reserved for trampolines */
152 guint32 num_trampoline_got_entries;
154 guint32 num_trampolines [MONO_AOT_TRAMP_NUM];
155 guint32 trampoline_got_offset_base [MONO_AOT_TRAMP_NUM];
156 guint32 trampoline_size [MONO_AOT_TRAMP_NUM];
158 MonoAotOptions aot_opts;
159 guint32 nmethods;
160 guint32 opts;
161 MonoMemPool *mempool;
162 MonoAotStats stats;
163 int method_index;
164 char *static_linking_symbol;
165 CRITICAL_SECTION mutex;
166 gboolean use_bin_writer;
167 MonoImageWriter *w;
168 MonoDwarfWriter *dwarf;
169 FILE *fp;
170 char *tmpfname;
171 GSList *cie_program;
172 GHashTable *unwind_info_offsets;
173 GPtrArray *unwind_ops;
174 guint32 unwind_info_offset;
175 char *got_symbol_base;
176 char *got_symbol;
177 char *plt_symbol;
178 GHashTable *method_label_hash;
179 const char *temp_prefix;
180 const char *llvm_label_prefix;
181 guint32 label_generator;
182 gboolean llvm;
183 MonoAotFileFlags flags;
184 MonoDynamicStream blob;
185 MonoClass **typespec_classes;
186 GString *llc_args;
187 GString *as_args;
188 gboolean thumb_mixed, need_no_dead_strip, need_pt_gnu_stack;
189 } MonoAotCompile;
191 typedef struct {
192 int plt_offset;
193 char *symbol, *llvm_symbol, *debug_sym;
194 MonoJumpInfo *ji;
195 gboolean jit_used, llvm_used;
196 } MonoPltEntry;
198 #define mono_acfg_lock(acfg) EnterCriticalSection (&((acfg)->mutex))
199 #define mono_acfg_unlock(acfg) LeaveCriticalSection (&((acfg)->mutex))
201 /* This points to the current acfg in LLVM mode */
202 static MonoAotCompile *llvm_acfg;
204 #ifdef HAVE_ARRAY_ELEM_INIT
205 #define MSGSTRFIELD(line) MSGSTRFIELD1(line)
206 #define MSGSTRFIELD1(line) str##line
207 static const struct msgstr_t {
208 #define PATCH_INFO(a,b) char MSGSTRFIELD(__LINE__) [sizeof (b)];
209 #include "patch-info.h"
210 #undef PATCH_INFO
211 } opstr = {
212 #define PATCH_INFO(a,b) b,
213 #include "patch-info.h"
214 #undef PATCH_INFO
216 static const gint16 opidx [] = {
217 #define PATCH_INFO(a,b) [MONO_PATCH_INFO_ ## a] = offsetof (struct msgstr_t, MSGSTRFIELD(__LINE__)),
218 #include "patch-info.h"
219 #undef PATCH_INFO
222 static G_GNUC_UNUSED const char*
223 get_patch_name (int info)
225 return (const char*)&opstr + opidx [info];
228 #else
229 #define PATCH_INFO(a,b) b,
230 static const char* const
231 patch_types [MONO_PATCH_INFO_NUM + 1] = {
232 #include "patch-info.h"
233 NULL
236 static G_GNUC_UNUSED const char*
237 get_patch_name (int info)
239 return patch_types [info];
242 #endif
244 /* Wrappers around the image writer functions */
246 static inline void
247 emit_section_change (MonoAotCompile *acfg, const char *section_name, int subsection_index)
249 img_writer_emit_section_change (acfg->w, section_name, subsection_index);
252 static inline void
253 emit_push_section (MonoAotCompile *acfg, const char *section_name, int subsection)
255 img_writer_emit_push_section (acfg->w, section_name, subsection);
258 static inline void
259 emit_pop_section (MonoAotCompile *acfg)
261 img_writer_emit_pop_section (acfg->w);
264 static inline void
265 emit_local_symbol (MonoAotCompile *acfg, const char *name, const char *end_label, gboolean func)
267 img_writer_emit_local_symbol (acfg->w, name, end_label, func);
270 static inline void
271 emit_label (MonoAotCompile *acfg, const char *name)
273 img_writer_emit_label (acfg->w, name);
276 static inline void
277 emit_bytes (MonoAotCompile *acfg, const guint8* buf, int size)
279 img_writer_emit_bytes (acfg->w, buf, size);
282 static inline void
283 emit_string (MonoAotCompile *acfg, const char *value)
285 img_writer_emit_string (acfg->w, value);
288 static inline void
289 emit_line (MonoAotCompile *acfg)
291 img_writer_emit_line (acfg->w);
294 static inline void
295 emit_alignment (MonoAotCompile *acfg, int size)
297 img_writer_emit_alignment (acfg->w, size);
300 static inline void
301 emit_pointer_unaligned (MonoAotCompile *acfg, const char *target)
303 img_writer_emit_pointer_unaligned (acfg->w, target);
306 static inline void
307 emit_pointer (MonoAotCompile *acfg, const char *target)
309 img_writer_emit_pointer (acfg->w, target);
312 static inline void
313 emit_int16 (MonoAotCompile *acfg, int value)
315 img_writer_emit_int16 (acfg->w, value);
318 static inline void
319 emit_int32 (MonoAotCompile *acfg, int value)
321 img_writer_emit_int32 (acfg->w, value);
324 static inline void
325 emit_symbol_diff (MonoAotCompile *acfg, const char *end, const char* start, int offset)
327 img_writer_emit_symbol_diff (acfg->w, end, start, offset);
330 static inline void
331 emit_zero_bytes (MonoAotCompile *acfg, int num)
333 img_writer_emit_zero_bytes (acfg->w, num);
336 static inline void
337 emit_byte (MonoAotCompile *acfg, guint8 val)
339 img_writer_emit_byte (acfg->w, val);
342 #ifdef __native_client_codegen__
343 static inline void
344 emit_nacl_call_alignment (MonoAotCompile *acfg)
346 img_writer_emit_nacl_call_alignment (acfg->w);
348 #endif
350 static G_GNUC_UNUSED void
351 emit_global_inner (MonoAotCompile *acfg, const char *name, gboolean func)
353 img_writer_emit_global (acfg->w, name, func);
356 static void
357 emit_global (MonoAotCompile *acfg, const char *name, gboolean func)
359 if (acfg->aot_opts.no_dlsym) {
360 g_ptr_array_add (acfg->globals, g_strdup (name));
361 img_writer_emit_local_symbol (acfg->w, name, NULL, func);
362 } else {
363 img_writer_emit_global (acfg->w, name, func);
367 static void
368 emit_symbol_size (MonoAotCompile *acfg, const char *name, const char *end_label)
370 img_writer_emit_symbol_size (acfg->w, name, end_label);
373 static void
374 emit_string_symbol (MonoAotCompile *acfg, const char *name, const char *value)
376 img_writer_emit_section_change (acfg->w, RODATA_SECT, 1);
377 img_writer_emit_label (acfg->w, name);
378 img_writer_emit_string (acfg->w, value);
381 static G_GNUC_UNUSED void
382 emit_uleb128 (MonoAotCompile *acfg, guint32 value)
384 do {
385 guint8 b = value & 0x7f;
386 value >>= 7;
387 if (value != 0) /* more bytes to come */
388 b |= 0x80;
389 emit_byte (acfg, b);
390 } while (value);
393 static G_GNUC_UNUSED void
394 emit_sleb128 (MonoAotCompile *acfg, gint64 value)
396 gboolean more = 1;
397 gboolean negative = (value < 0);
398 guint32 size = 64;
399 guint8 byte;
401 while (more) {
402 byte = value & 0x7f;
403 value >>= 7;
404 /* the following is unnecessary if the
405 * implementation of >>= uses an arithmetic rather
406 * than logical shift for a signed left operand
408 if (negative)
409 /* sign extend */
410 value |= - ((gint64)1 <<(size - 7));
411 /* sign bit of byte is second high order bit (0x40) */
412 if ((value == 0 && !(byte & 0x40)) ||
413 (value == -1 && (byte & 0x40)))
414 more = 0;
415 else
416 byte |= 0x80;
417 emit_byte (acfg, byte);
421 static G_GNUC_UNUSED void
422 encode_uleb128 (guint32 value, guint8 *buf, guint8 **endbuf)
424 guint8 *p = buf;
426 do {
427 guint8 b = value & 0x7f;
428 value >>= 7;
429 if (value != 0) /* more bytes to come */
430 b |= 0x80;
431 *p ++ = b;
432 } while (value);
434 *endbuf = p;
437 static G_GNUC_UNUSED void
438 encode_sleb128 (gint32 value, guint8 *buf, guint8 **endbuf)
440 gboolean more = 1;
441 gboolean negative = (value < 0);
442 guint32 size = 32;
443 guint8 byte;
444 guint8 *p = buf;
446 while (more) {
447 byte = value & 0x7f;
448 value >>= 7;
449 /* the following is unnecessary if the
450 * implementation of >>= uses an arithmetic rather
451 * than logical shift for a signed left operand
453 if (negative)
454 /* sign extend */
455 value |= - (1 <<(size - 7));
456 /* sign bit of byte is second high order bit (0x40) */
457 if ((value == 0 && !(byte & 0x40)) ||
458 (value == -1 && (byte & 0x40)))
459 more = 0;
460 else
461 byte |= 0x80;
462 *p ++= byte;
465 *endbuf = p;
468 /* ARCHITECTURE SPECIFIC CODE */
470 #if defined(TARGET_X86) || defined(TARGET_AMD64) || defined(TARGET_ARM) || defined(TARGET_POWERPC)
471 #define EMIT_DWARF_INFO 1
472 #endif
474 #if defined(TARGET_ARM)
475 #define AOT_FUNC_ALIGNMENT 4
476 #else
477 #define AOT_FUNC_ALIGNMENT 16
478 #endif
479 #if (defined(TARGET_X86) || defined(TARGET_AMD64)) && defined(__native_client_codegen__)
480 #undef AOT_FUNC_ALIGNMENT
481 #define AOT_FUNC_ALIGNMENT 32
482 #endif
484 #if defined(TARGET_POWERPC64) && !defined(__mono_ilp32__)
485 #define PPC_LD_OP "ld"
486 #define PPC_LDX_OP "ldx"
487 #else
488 #define PPC_LD_OP "lwz"
489 #define PPC_LDX_OP "lwzx"
490 #endif
492 static void
493 arch_init (MonoAotCompile *acfg)
495 acfg->llc_args = g_string_new ("");
496 acfg->as_args = g_string_new ("");
499 * The prefix LLVM likes to put in front of symbol names on darwin.
500 * The mach-os specs require this for globals, but LLVM puts them in front of all
501 * symbols. We need to handle this, since we need to refer to LLVM generated
502 * symbols.
504 acfg->llvm_label_prefix = "";
506 #ifdef TARGET_ARM
507 if (acfg->aot_opts.mtriple && strstr (acfg->aot_opts.mtriple, "darwin")) {
508 g_string_append (acfg->llc_args, "-mattr=+v6");
509 } else {
510 #ifdef ARM_FPU_VFP
511 g_string_append (acfg->llc_args, " -mattr=+vfp2,+d16");
512 g_string_append (acfg->as_args, " -mfpu=vfp3");
513 #else
514 g_string_append (acfg->llc_args, " -soft-float");
515 #endif
517 if (acfg->aot_opts.mtriple && strstr (acfg->aot_opts.mtriple, "thumb"))
518 acfg->thumb_mixed = TRUE;
520 if (acfg->aot_opts.mtriple)
521 mono_arch_set_target (acfg->aot_opts.mtriple);
522 #endif
524 #ifdef __APPLE__
525 acfg->llvm_label_prefix = "_";
526 acfg->need_no_dead_strip = TRUE;
527 #endif
529 #if defined(__linux__) && !defined(TARGET_ARM)
530 acfg->need_pt_gnu_stack = TRUE;
531 #endif
535 * arch_emit_direct_call:
537 * Emit a direct call to the symbol TARGET. CALL_SIZE is set to the size of the
538 * calling code.
540 static void
541 arch_emit_direct_call (MonoAotCompile *acfg, const char *target, int *call_size)
543 #if defined(TARGET_X86) || defined(TARGET_AMD64)
544 /* Need to make sure this is exactly 5 bytes long */
545 emit_byte (acfg, '\xe8');
546 emit_symbol_diff (acfg, target, ".", -4);
547 *call_size = 5;
548 #elif defined(TARGET_ARM)
549 if (acfg->use_bin_writer) {
550 guint8 buf [4];
551 guint8 *code;
553 code = buf;
554 ARM_BL (code, 0);
556 img_writer_emit_reloc (acfg->w, R_ARM_CALL, target, -8);
557 emit_bytes (acfg, buf, 4);
558 } else {
559 img_writer_emit_unset_mode (acfg->w);
560 fprintf (acfg->fp, "bl %s\n", target);
562 *call_size = 4;
563 #elif defined(TARGET_POWERPC)
564 if (acfg->use_bin_writer) {
565 g_assert_not_reached ();
566 } else {
567 img_writer_emit_unset_mode (acfg->w);
568 fprintf (acfg->fp, "bl %s\n", target);
569 *call_size = 4;
571 #else
572 g_assert_not_reached ();
573 #endif
577 * PPC32 design:
578 * - we use an approach similar to the x86 abi: reserve a register (r30) to hold
579 * the GOT pointer.
580 * - The full-aot trampolines need access to the GOT of mscorlib, so we store
581 * in in the 2. slot of every GOT, and require every method to place the GOT
582 * address in r30, even when it doesn't access the GOT otherwise. This way,
583 * the trampolines can compute the mscorlib GOT address by loading 4(r30).
587 * PPC64 design:
588 * PPC64 uses function descriptors which greatly complicate all code, since
589 * these are used very inconsistently in the runtime. Some functions like
590 * mono_compile_method () return ftn descriptors, while others like the
591 * trampoline creation functions do not.
592 * We assume that all GOT slots contain function descriptors, and create
593 * descriptors in aot-runtime.c when needed.
594 * The ppc64 abi uses r2 to hold the address of the TOC/GOT, which is loaded
595 * from function descriptors, we could do the same, but it would require
596 * rewriting all the ppc/aot code to handle function descriptors properly.
597 * So instead, we use the same approach as on PPC32.
598 * This is a horrible mess, but fixing it would probably lead to an even bigger
599 * one.
603 * X86 design:
604 * - similar to the PPC32 design, we reserve EBX to hold the GOT pointer.
607 #ifdef MONO_ARCH_AOT_SUPPORTED
609 * arch_emit_got_offset:
611 * The memory pointed to by CODE should hold native code for computing the GOT
612 * address. Emit this code while patching it with the offset between code and
613 * the GOT. CODE_SIZE is set to the number of bytes emitted.
615 static void
616 arch_emit_got_offset (MonoAotCompile *acfg, guint8 *code, int *code_size)
618 #if defined(TARGET_POWERPC64)
619 g_assert (!acfg->use_bin_writer);
620 img_writer_emit_unset_mode (acfg->w);
622 * The ppc32 code doesn't seem to work on ppc64, the assembler complains about
623 * unsupported relocations. So we store the got address into the .Lgot_addr
624 * symbol which is in the text segment, compute its address, and load it.
626 fprintf (acfg->fp, ".L%d:\n", acfg->label_generator);
627 fprintf (acfg->fp, "lis 0, (.Lgot_addr + 4 - .L%d)@h\n", acfg->label_generator);
628 fprintf (acfg->fp, "ori 0, 0, (.Lgot_addr + 4 - .L%d)@l\n", acfg->label_generator);
629 fprintf (acfg->fp, "add 30, 30, 0\n");
630 fprintf (acfg->fp, "%s 30, 0(30)\n", PPC_LD_OP);
631 acfg->label_generator ++;
632 *code_size = 16;
633 #elif defined(TARGET_POWERPC)
634 g_assert (!acfg->use_bin_writer);
635 img_writer_emit_unset_mode (acfg->w);
636 fprintf (acfg->fp, ".L%d:\n", acfg->label_generator);
637 fprintf (acfg->fp, "lis 0, (%s + 4 - .L%d)@h\n", acfg->got_symbol, acfg->label_generator);
638 fprintf (acfg->fp, "ori 0, 0, (%s + 4 - .L%d)@l\n", acfg->got_symbol, acfg->label_generator);
639 acfg->label_generator ++;
640 *code_size = 8;
641 #else
642 guint32 offset = mono_arch_get_patch_offset (code);
643 emit_bytes (acfg, code, offset);
644 emit_symbol_diff (acfg, acfg->got_symbol, ".", offset);
646 *code_size = offset + 4;
647 #endif
651 * arch_emit_got_access:
653 * The memory pointed to by CODE should hold native code for loading a GOT
654 * slot. Emit this code while patching it so it accesses the GOT slot GOT_SLOT.
655 * CODE_SIZE is set to the number of bytes emitted.
657 static void
658 arch_emit_got_access (MonoAotCompile *acfg, guint8 *code, int got_slot, int *code_size)
660 /* Emit beginning of instruction */
661 emit_bytes (acfg, code, mono_arch_get_patch_offset (code));
663 /* Emit the offset */
664 #ifdef TARGET_AMD64
665 emit_symbol_diff (acfg, acfg->got_symbol, ".", (unsigned int) ((got_slot * sizeof (gpointer)) - 4));
666 *code_size = mono_arch_get_patch_offset (code) + 4;
667 #elif defined(TARGET_X86)
668 emit_int32 (acfg, (unsigned int) ((got_slot * sizeof (gpointer))));
669 *code_size = mono_arch_get_patch_offset (code) + 4;
670 #elif defined(TARGET_ARM)
671 emit_symbol_diff (acfg, acfg->got_symbol, ".", (unsigned int) ((got_slot * sizeof (gpointer))) - 12);
672 *code_size = mono_arch_get_patch_offset (code) + 4;
673 #elif defined(TARGET_POWERPC)
675 guint8 buf [32];
676 guint8 *code;
678 code = buf;
679 ppc_load32 (code, ppc_r0, got_slot * sizeof (gpointer));
680 g_assert (code - buf == 8);
681 emit_bytes (acfg, buf, code - buf);
682 *code_size = code - buf;
684 #else
685 g_assert_not_reached ();
686 #endif
689 #endif
692 * arch_emit_plt_entry:
694 * Emit code for the PLT entry with index INDEX.
696 static void
697 arch_emit_plt_entry (MonoAotCompile *acfg, int index)
699 #if defined(TARGET_X86)
700 guint32 offset = (acfg->plt_got_offset_base + index) * sizeof (gpointer);
701 #if defined(__default_codegen__)
702 /* jmp *<offset>(%ebx) */
703 emit_byte (acfg, 0xff);
704 emit_byte (acfg, 0xa3);
705 emit_int32 (acfg, offset);
706 /* Used by mono_aot_get_plt_info_offset */
707 emit_int32 (acfg, acfg->plt_got_info_offsets [index]);
708 #elif defined(__native_client_codegen__)
709 const guint8 kSizeOfNaClJmp = 11;
710 guint8 bytes[kSizeOfNaClJmp];
711 guint8 *pbytes = &bytes[0];
713 x86_jump_membase32 (pbytes, X86_EBX, offset);
714 emit_bytes (acfg, bytes, kSizeOfNaClJmp);
715 /* four bytes of data, used by mono_arch_patch_plt_entry */
716 /* For Native Client, make this work with data embedded in push. */
717 emit_byte (acfg, 0x68); /* hide data in a push */
718 emit_int32 (acfg, acfg->plt_got_info_offsets [index]);
719 emit_alignment (acfg, AOT_FUNC_ALIGNMENT);
720 #endif /*__native_client_codegen__*/
721 #elif defined(TARGET_AMD64)
722 #if defined(__default_codegen__)
724 * We can't emit jumps because they are 32 bits only so they can't be patched.
725 * So we make indirect calls through GOT entries which are patched by the AOT
726 * loader to point to .Lpd entries.
728 /* jmpq *<offset>(%rip) */
729 emit_byte (acfg, '\xff');
730 emit_byte (acfg, '\x25');
731 emit_symbol_diff (acfg, acfg->got_symbol, ".", ((acfg->plt_got_offset_base + index) * sizeof (gpointer)) -4);
732 /* Used by mono_aot_get_plt_info_offset */
733 emit_int32 (acfg, acfg->plt_got_info_offsets [index]);
734 #elif defined(__native_client_codegen__)
735 guint8 buf [256];
736 guint8 *buf_aligned = ALIGN_TO(buf, kNaClAlignment);
737 guint8 *code = buf_aligned;
739 /* mov <OFFSET>(%rip), %r11d */
740 emit_byte (acfg, '\x45');
741 emit_byte (acfg, '\x8b');
742 emit_byte (acfg, '\x1d');
743 emit_symbol_diff (acfg, acfg->got_symbol, ".", ((acfg->plt_got_offset_base + index) * sizeof (gpointer)) -4);
745 amd64_jump_reg (code, AMD64_R11);
746 /* This should be constant for the plt patch */
747 g_assert ((size_t)(code-buf_aligned) == 10);
748 emit_bytes (acfg, buf_aligned, code - buf_aligned);
750 /* Hide data in a push imm32 so it passes validation */
751 emit_byte (acfg, 0x68); /* push */
752 emit_int32 (acfg, acfg->plt_got_info_offsets [index]);
753 emit_alignment (acfg, AOT_FUNC_ALIGNMENT);
754 #endif /*__native_client_codegen__*/
755 #elif defined(TARGET_ARM)
756 guint8 buf [256];
757 guint8 *code;
759 code = buf;
760 ARM_LDR_IMM (code, ARMREG_IP, ARMREG_PC, 0);
761 ARM_LDR_REG_REG (code, ARMREG_PC, ARMREG_PC, ARMREG_IP);
762 emit_bytes (acfg, buf, code - buf);
763 emit_symbol_diff (acfg, acfg->got_symbol, ".", ((acfg->plt_got_offset_base + index) * sizeof (gpointer)) - 4);
764 /* Used by mono_aot_get_plt_info_offset */
765 emit_int32 (acfg, acfg->plt_got_info_offsets [index]);
766 #elif defined(TARGET_POWERPC)
767 guint32 offset = (acfg->plt_got_offset_base + index) * sizeof (gpointer);
769 /* The GOT address is guaranteed to be in r30 by OP_LOAD_GOTADDR */
770 g_assert (!acfg->use_bin_writer);
771 img_writer_emit_unset_mode (acfg->w);
772 fprintf (acfg->fp, "lis 11, %d@h\n", offset);
773 fprintf (acfg->fp, "ori 11, 11, %d@l\n", offset);
774 fprintf (acfg->fp, "add 11, 11, 30\n");
775 fprintf (acfg->fp, "%s 11, 0(11)\n", PPC_LD_OP);
776 #ifdef PPC_USES_FUNCTION_DESCRIPTOR
777 fprintf (acfg->fp, "%s 2, %d(11)\n", PPC_LD_OP, (int)sizeof (gpointer));
778 fprintf (acfg->fp, "%s 11, 0(11)\n", PPC_LD_OP);
779 #endif
780 fprintf (acfg->fp, "mtctr 11\n");
781 fprintf (acfg->fp, "bctr\n");
782 emit_int32 (acfg, acfg->plt_got_info_offsets [index]);
783 #else
784 g_assert_not_reached ();
785 #endif
788 static void
789 arch_emit_llvm_plt_entry (MonoAotCompile *acfg, int index)
791 #if defined(TARGET_ARM)
792 #if 0
793 /* LLVM calls the PLT entries using bl, so emit a stub */
794 /* FIXME: Too much overhead on every call */
795 fprintf (acfg->fp, ".thumb_func\n");
796 fprintf (acfg->fp, "bx pc\n");
797 fprintf (acfg->fp, "nop\n");
798 fprintf (acfg->fp, ".arm\n");
799 #endif
800 /* LLVM calls the PLT entries using bl, so these have to be thumb2 */
801 /* The caller already transitioned to thumb */
802 /* The code below should be 12 bytes long */
803 fprintf (acfg->fp, "ldr ip, [pc, #8]\n");
804 /* thumb can't encode ld pc, [pc, ip] */
805 fprintf (acfg->fp, "add ip, pc, ip\n");
806 fprintf (acfg->fp, "ldr ip, [ip, #0]\n");
807 fprintf (acfg->fp, "bx ip\n");
808 emit_symbol_diff (acfg, acfg->got_symbol, ".", ((acfg->plt_got_offset_base + index) * sizeof (gpointer)) + 4);
809 emit_int32 (acfg, acfg->plt_got_info_offsets [index]);
810 #else
811 g_assert_not_reached ();
812 #endif
816 * arch_emit_specific_trampoline:
818 * Emit code for a specific trampoline. OFFSET is the offset of the first of
819 * two GOT slots which contain the generic trampoline address and the trampoline
820 * argument. TRAMP_SIZE is set to the size of the emitted trampoline.
822 static void
823 arch_emit_specific_trampoline (MonoAotCompile *acfg, int offset, int *tramp_size)
826 * The trampolines created here are variations of the specific
827 * trampolines created in mono_arch_create_specific_trampoline (). The
828 * differences are:
829 * - the generic trampoline address is taken from a got slot.
830 * - the offset of the got slot where the trampoline argument is stored
831 * is embedded in the instruction stream, and the generic trampoline
832 * can load the argument by loading the offset, adding it to the
833 * address of the trampoline to get the address of the got slot, and
834 * loading the argument from there.
835 * - all the trampolines should be of the same length.
837 #if defined(TARGET_AMD64)
838 #if defined(__default_codegen__)
839 /* This should be exactly 16 bytes long */
840 *tramp_size = 16;
841 /* call *<offset>(%rip) */
842 emit_byte (acfg, '\x41');
843 emit_byte (acfg, '\xff');
844 emit_byte (acfg, '\x15');
845 emit_symbol_diff (acfg, acfg->got_symbol, ".", (offset * sizeof (gpointer)) - 4);
846 /* This should be relative to the start of the trampoline */
847 emit_symbol_diff (acfg, acfg->got_symbol, ".", ((offset+1) * sizeof (gpointer)) + 7);
848 emit_zero_bytes (acfg, 5);
849 #elif defined(__native_client_codegen__)
850 guint8 buf [256];
851 guint8 *buf_aligned = ALIGN_TO(buf, kNaClAlignment);
852 guint8 *code = buf_aligned;
853 guint8 *call_start;
854 size_t call_len;
855 int got_offset;
857 /* Emit this call in 'code' so we can find out how long it is. */
858 amd64_call_reg (code, AMD64_R11);
859 call_start = mono_arch_nacl_skip_nops (buf_aligned);
860 call_len = code - call_start;
862 /* The tramp_size is twice the NaCl alignment because it starts with */
863 /* a call which needs to be aligned to the end of the boundary. */
864 *tramp_size = kNaClAlignment*2;
866 /* Emit nops to align call site below which is 7 bytes plus */
867 /* the length of the call sequence emitted above. */
868 /* Note: this requires the specific trampoline starts on a */
869 /* kNaclAlignedment aligned address, which it does because */
870 /* it's its own function that is aligned. */
871 guint8 nop_buf[256];
872 guint8 *nopbuf_aligned = ALIGN_TO (nop_buf, kNaClAlignment);
873 guint8 *nopbuf_end = mono_arch_nacl_pad (nopbuf_aligned, kNaClAlignment - 7 - (call_len));
874 emit_bytes (acfg, nopbuf_aligned, nopbuf_end - nopbuf_aligned);
876 /* The trampoline is stored at the offset'th pointer, the -4 is */
877 /* present because RIP relative addressing starts at the end of */
878 /* the current instruction, while the label "." is relative to */
879 /* the beginning of the current asm location, which in this case */
880 /* is not the mov instruction, but the offset itself, due to the */
881 /* way the bytes and ints are emitted here. */
882 got_offset = (offset * sizeof(gpointer)) - 4;
884 /* mov <OFFSET>(%rip), %r11d */
885 emit_byte (acfg, '\x45');
886 emit_byte (acfg, '\x8b');
887 emit_byte (acfg, '\x1d');
888 emit_symbol_diff (acfg, acfg->got_symbol, ".", got_offset);
890 /* naclcall %r11 */
891 emit_bytes (acfg, call_start, call_len);
893 /* The arg is stored at the offset+1 pointer, relative to beginning */
894 /* of trampoline: 7 for mov, plus the call length, and 1 for push. */
895 got_offset = ((offset + 1) * sizeof(gpointer)) + 7 + call_len + 1;
897 /* We can't emit this data directly, hide in a "push imm32" */
898 emit_byte (acfg, '\x68'); /* push */
899 emit_symbol_diff (acfg, acfg->got_symbol, ".", got_offset);
900 emit_alignment (acfg, kNaClAlignment);
901 #endif /*__native_client_codegen__*/
902 #elif defined(TARGET_ARM)
903 guint8 buf [128];
904 guint8 *code;
906 /* This should be exactly 20 bytes long */
907 *tramp_size = 20;
908 code = buf;
909 ARM_PUSH (code, 0x5fff);
910 ARM_LDR_IMM (code, ARMREG_R1, ARMREG_PC, 4);
911 /* Load the value from the GOT */
912 ARM_LDR_REG_REG (code, ARMREG_R1, ARMREG_PC, ARMREG_R1);
913 /* Branch to it */
914 ARM_BLX_REG (code, ARMREG_R1);
916 g_assert (code - buf == 16);
918 /* Emit it */
919 emit_bytes (acfg, buf, code - buf);
921 * Only one offset is needed, since the second one would be equal to the
922 * first one.
924 emit_symbol_diff (acfg, acfg->got_symbol, ".", (offset * sizeof (gpointer)) - 4 + 4);
925 //emit_symbol_diff (acfg, acfg->got_symbol, ".", ((offset + 1) * sizeof (gpointer)) - 4 + 8);
926 #elif defined(TARGET_POWERPC)
927 guint8 buf [128];
928 guint8 *code;
930 *tramp_size = 4;
931 code = buf;
933 g_assert (!acfg->use_bin_writer);
936 * PPC has no ip relative addressing, so we need to compute the address
937 * of the mscorlib got. That is slow and complex, so instead, we store it
938 * in the second got slot of every aot image. The caller already computed
939 * the address of its got and placed it into r30.
941 img_writer_emit_unset_mode (acfg->w);
942 /* Load mscorlib got address */
943 fprintf (acfg->fp, "%s 0, %d(30)\n", PPC_LD_OP, (int)sizeof (gpointer));
944 /* Load generic trampoline address */
945 fprintf (acfg->fp, "lis 11, %d@h\n", (int)(offset * sizeof (gpointer)));
946 fprintf (acfg->fp, "ori 11, 11, %d@l\n", (int)(offset * sizeof (gpointer)));
947 fprintf (acfg->fp, "%s 11, 11, 0\n", PPC_LDX_OP);
948 #ifdef PPC_USES_FUNCTION_DESCRIPTOR
949 fprintf (acfg->fp, "%s 11, 0(11)\n", PPC_LD_OP);
950 #endif
951 fprintf (acfg->fp, "mtctr 11\n");
952 /* Load trampoline argument */
953 /* On ppc, we pass it normally to the generic trampoline */
954 fprintf (acfg->fp, "lis 11, %d@h\n", (int)((offset + 1) * sizeof (gpointer)));
955 fprintf (acfg->fp, "ori 11, 11, %d@l\n", (int)((offset + 1) * sizeof (gpointer)));
956 fprintf (acfg->fp, "%s 0, 11, 0\n", PPC_LDX_OP);
957 /* Branch to generic trampoline */
958 fprintf (acfg->fp, "bctr\n");
960 #ifdef PPC_USES_FUNCTION_DESCRIPTOR
961 *tramp_size = 10 * 4;
962 #else
963 *tramp_size = 9 * 4;
964 #endif
965 #elif defined(TARGET_X86)
966 guint8 buf [128];
967 guint8 *code;
969 /* Similar to the PPC code above */
971 /* FIXME: Could this clobber the register needed by get_vcall_slot () ? */
973 /* We clobber ECX, since EAX is used as MONO_ARCH_MONITOR_OBJECT_REG */
974 #ifdef MONO_ARCH_MONITOR_OBJECT_REG
975 g_assert (MONO_ARCH_MONITOR_OBJECT_REG != X86_ECX);
976 #endif
978 code = buf;
979 /* Load mscorlib got address */
980 x86_mov_reg_membase (code, X86_ECX, MONO_ARCH_GOT_REG, sizeof (gpointer), 4);
981 /* Push trampoline argument */
982 x86_push_membase (code, X86_ECX, (offset + 1) * sizeof (gpointer));
983 /* Load generic trampoline address */
984 x86_mov_reg_membase (code, X86_ECX, X86_ECX, offset * sizeof (gpointer), 4);
985 /* Branch to generic trampoline */
986 x86_jump_reg (code, X86_ECX);
988 #ifdef __native_client_codegen__
990 /* emit nops to next 32 byte alignment */
991 int a = (~kNaClAlignmentMask) & ((code - buf) + kNaClAlignment - 1);
992 while (code < (buf + a)) x86_nop(code);
994 #endif
995 emit_bytes (acfg, buf, code - buf);
997 *tramp_size = NACL_SIZE(17, kNaClAlignment);
998 g_assert (code - buf == *tramp_size);
999 #else
1000 g_assert_not_reached ();
1001 #endif
1005 * arch_emit_unbox_trampoline:
1007 * Emit code for the unbox trampoline for METHOD used in the full-aot case.
1008 * CALL_TARGET is the symbol pointing to the native code of METHOD.
1010 static void
1011 arch_emit_unbox_trampoline (MonoAotCompile *acfg, MonoCompile *cfg, MonoMethod *method, const char *call_target)
1013 #if defined(TARGET_AMD64)
1014 guint8 buf [32];
1015 guint8 *code;
1016 int this_reg;
1018 this_reg = mono_arch_get_this_arg_reg (NULL);
1019 code = buf;
1020 amd64_alu_reg_imm (code, X86_ADD, this_reg, sizeof (MonoObject));
1022 emit_bytes (acfg, buf, code - buf);
1023 /* jump <method> */
1024 emit_byte (acfg, '\xe9');
1025 emit_symbol_diff (acfg, call_target, ".", -4);
1026 #elif defined(TARGET_X86)
1027 guint8 buf [32];
1028 guint8 *code;
1029 int this_pos = 4;
1031 code = buf;
1033 x86_alu_membase_imm (code, X86_ADD, X86_ESP, this_pos, sizeof (MonoObject));
1035 emit_bytes (acfg, buf, code - buf);
1037 /* jump <method> */
1038 emit_byte (acfg, '\xe9');
1039 emit_symbol_diff (acfg, call_target, ".", -4);
1040 #elif defined(TARGET_ARM)
1041 guint8 buf [128];
1042 guint8 *code;
1044 if (acfg->thumb_mixed && cfg->compile_llvm) {
1045 fprintf (acfg->fp, "add r0, r0, #%d\n", sizeof (MonoObject));
1046 fprintf (acfg->fp, "b %s\n", call_target);
1047 fprintf (acfg->fp, ".arm\n");
1048 return;
1051 code = buf;
1053 ARM_ADD_REG_IMM8 (code, ARMREG_R0, ARMREG_R0, sizeof (MonoObject));
1055 emit_bytes (acfg, buf, code - buf);
1056 /* jump to method */
1057 if (acfg->use_bin_writer) {
1058 guint8 buf [4];
1059 guint8 *code;
1061 code = buf;
1062 ARM_B (code, 0);
1064 img_writer_emit_reloc (acfg->w, R_ARM_JUMP24, call_target, -8);
1065 emit_bytes (acfg, buf, 4);
1066 } else {
1067 if (acfg->thumb_mixed && cfg->compile_llvm)
1068 fprintf (acfg->fp, "\n\tbx %s\n", call_target);
1069 else
1070 fprintf (acfg->fp, "\n\tb %s\n", call_target);
1072 #elif defined(TARGET_POWERPC)
1073 int this_pos = 3;
1075 g_assert (!acfg->use_bin_writer);
1077 fprintf (acfg->fp, "\n\taddi %d, %d, %d\n", this_pos, this_pos, (int)sizeof (MonoObject));
1078 fprintf (acfg->fp, "\n\tb %s\n", call_target);
1079 #else
1080 g_assert_not_reached ();
1081 #endif
1085 * arch_emit_static_rgctx_trampoline:
1087 * Emit code for a static rgctx trampoline. OFFSET is the offset of the first of
1088 * two GOT slots which contain the rgctx argument, and the method to jump to.
1089 * TRAMP_SIZE is set to the size of the emitted trampoline.
1090 * These kinds of trampolines cannot be enumerated statically, since there could
1091 * be one trampoline per method instantiation, so we emit the same code for all
1092 * trampolines, and parameterize them using two GOT slots.
1094 static void
1095 arch_emit_static_rgctx_trampoline (MonoAotCompile *acfg, int offset, int *tramp_size)
1097 #if defined(TARGET_AMD64)
1098 #if defined(__default_codegen__)
1099 /* This should be exactly 13 bytes long */
1100 *tramp_size = 13;
1102 /* mov <OFFSET>(%rip), %r10 */
1103 emit_byte (acfg, '\x4d');
1104 emit_byte (acfg, '\x8b');
1105 emit_byte (acfg, '\x15');
1106 emit_symbol_diff (acfg, acfg->got_symbol, ".", (offset * sizeof (gpointer)) - 4);
1108 /* jmp *<offset>(%rip) */
1109 emit_byte (acfg, '\xff');
1110 emit_byte (acfg, '\x25');
1111 emit_symbol_diff (acfg, acfg->got_symbol, ".", ((offset + 1) * sizeof (gpointer)) - 4);
1112 #elif defined(__native_client_codegen__)
1113 guint8 buf [128];
1114 guint8 *buf_aligned = ALIGN_TO(buf, kNaClAlignment);
1115 guint8 *code = buf_aligned;
1117 /* mov <OFFSET>(%rip), %r10d */
1118 emit_byte (acfg, '\x45');
1119 emit_byte (acfg, '\x8b');
1120 emit_byte (acfg, '\x15');
1121 emit_symbol_diff (acfg, acfg->got_symbol, ".", (offset * sizeof (gpointer)) - 4);
1123 /* mov <OFFSET>(%rip), %r11d */
1124 emit_byte (acfg, '\x45');
1125 emit_byte (acfg, '\x8b');
1126 emit_byte (acfg, '\x1d');
1127 emit_symbol_diff (acfg, acfg->got_symbol, ".", ((offset + 1) * sizeof (gpointer)) - 4);
1129 /* nacljmp *%r11 */
1130 amd64_jump_reg (code, AMD64_R11);
1131 emit_bytes (acfg, buf_aligned, code - buf_aligned);
1133 emit_alignment (acfg, kNaClAlignment);
1134 *tramp_size = kNaClAlignment;
1135 #endif /*__native_client_codegen__*/
1137 #elif defined(TARGET_ARM)
1138 guint8 buf [128];
1139 guint8 *code;
1141 /* This should be exactly 24 bytes long */
1142 *tramp_size = 24;
1143 code = buf;
1144 /* Load rgctx value */
1145 ARM_LDR_IMM (code, ARMREG_IP, ARMREG_PC, 8);
1146 ARM_LDR_REG_REG (code, MONO_ARCH_RGCTX_REG, ARMREG_PC, ARMREG_IP);
1147 /* Load branch addr + branch */
1148 ARM_LDR_IMM (code, ARMREG_IP, ARMREG_PC, 4);
1149 ARM_LDR_REG_REG (code, ARMREG_PC, ARMREG_PC, ARMREG_IP);
1151 g_assert (code - buf == 16);
1153 /* Emit it */
1154 emit_bytes (acfg, buf, code - buf);
1155 emit_symbol_diff (acfg, acfg->got_symbol, ".", (offset * sizeof (gpointer)) - 4 + 8);
1156 emit_symbol_diff (acfg, acfg->got_symbol, ".", ((offset + 1) * sizeof (gpointer)) - 4 + 4);
1157 #elif defined(TARGET_POWERPC)
1158 guint8 buf [128];
1159 guint8 *code;
1161 *tramp_size = 4;
1162 code = buf;
1164 g_assert (!acfg->use_bin_writer);
1167 * PPC has no ip relative addressing, so we need to compute the address
1168 * of the mscorlib got. That is slow and complex, so instead, we store it
1169 * in the second got slot of every aot image. The caller already computed
1170 * the address of its got and placed it into r30.
1172 img_writer_emit_unset_mode (acfg->w);
1173 /* Load mscorlib got address */
1174 fprintf (acfg->fp, "%s 0, %d(30)\n", PPC_LD_OP, (int)sizeof (gpointer));
1175 /* Load rgctx */
1176 fprintf (acfg->fp, "lis 11, %d@h\n", (int)(offset * sizeof (gpointer)));
1177 fprintf (acfg->fp, "ori 11, 11, %d@l\n", (int)(offset * sizeof (gpointer)));
1178 fprintf (acfg->fp, "%s %d, 11, 0\n", PPC_LDX_OP, MONO_ARCH_RGCTX_REG);
1179 /* Load target address */
1180 fprintf (acfg->fp, "lis 11, %d@h\n", (int)((offset + 1) * sizeof (gpointer)));
1181 fprintf (acfg->fp, "ori 11, 11, %d@l\n", (int)((offset + 1) * sizeof (gpointer)));
1182 fprintf (acfg->fp, "%s 11, 11, 0\n", PPC_LDX_OP);
1183 #ifdef PPC_USES_FUNCTION_DESCRIPTOR
1184 fprintf (acfg->fp, "%s 2, %d(11)\n", PPC_LD_OP, (int)sizeof (gpointer));
1185 fprintf (acfg->fp, "%s 11, 0(11)\n", PPC_LD_OP);
1186 #endif
1187 fprintf (acfg->fp, "mtctr 11\n");
1188 /* Branch to the target address */
1189 fprintf (acfg->fp, "bctr\n");
1191 #ifdef PPC_USES_FUNCTION_DESCRIPTOR
1192 *tramp_size = 11 * 4;
1193 #else
1194 *tramp_size = 9 * 4;
1195 #endif
1197 #elif defined(TARGET_X86)
1198 guint8 buf [128];
1199 guint8 *code;
1201 /* Similar to the PPC code above */
1203 g_assert (MONO_ARCH_RGCTX_REG != X86_ECX);
1205 code = buf;
1206 /* Load mscorlib got address */
1207 x86_mov_reg_membase (code, X86_ECX, MONO_ARCH_GOT_REG, sizeof (gpointer), 4);
1208 /* Load arg */
1209 x86_mov_reg_membase (code, MONO_ARCH_RGCTX_REG, X86_ECX, offset * sizeof (gpointer), 4);
1210 /* Branch to the target address */
1211 x86_jump_membase (code, X86_ECX, (offset + 1) * sizeof (gpointer));
1213 #ifdef __native_client_codegen__
1215 /* emit nops to next 32 byte alignment */
1216 int a = (~kNaClAlignmentMask) & ((code - buf) + kNaClAlignment - 1);
1217 while (code < (buf + a)) x86_nop(code);
1219 #endif
1221 emit_bytes (acfg, buf, code - buf);
1223 *tramp_size = NACL_SIZE (15, kNaClAlignment);
1224 g_assert (code - buf == *tramp_size);
1225 #else
1226 g_assert_not_reached ();
1227 #endif
1231 * arch_emit_imt_thunk:
1233 * Emit an IMT thunk usable in full-aot mode. The thunk uses 1 got slot which
1234 * points to an array of pointer pairs. The pairs of the form [key, ptr], where
1235 * key is the IMT key, and ptr holds the address of a memory location holding
1236 * the address to branch to if the IMT arg matches the key. The array is
1237 * terminated by a pair whose key is NULL, and whose ptr is the address of the
1238 * fail_tramp.
1239 * TRAMP_SIZE is set to the size of the emitted trampoline.
1241 static void
1242 arch_emit_imt_thunk (MonoAotCompile *acfg, int offset, int *tramp_size)
1244 #if defined(TARGET_AMD64)
1245 guint8 *buf, *code;
1246 #if defined(__native_client_codegen__)
1247 guint8 *buf_alloc;
1248 #endif
1249 guint8 *labels [3];
1250 guint8 mov_buf[3];
1251 guint8 *mov_buf_ptr = mov_buf;
1253 const int kSizeOfMove = 7;
1254 #if defined(__default_codegen__)
1255 code = buf = g_malloc (256);
1256 #elif defined(__native_client_codegen__)
1257 buf_alloc = g_malloc (256 + kNaClAlignment + kSizeOfMove);
1258 buf = ((guint)buf_alloc + kNaClAlignment) & ~kNaClAlignmentMask;
1259 /* The RIP relative move below is emitted first */
1260 buf += kSizeOfMove;
1261 code = buf;
1262 #endif
1264 /* FIXME: Optimize this, i.e. use binary search etc. */
1265 /* Maybe move the body into a separate function (slower, but much smaller) */
1267 /* MONO_ARCH_IMT_SCRATCH_REG is a free register */
1269 labels [0] = code;
1270 amd64_alu_membase_imm (code, X86_CMP, MONO_ARCH_IMT_SCRATCH_REG, 0, 0);
1271 labels [1] = code;
1272 amd64_branch8 (code, X86_CC_Z, 0, FALSE);
1274 /* Check key */
1275 amd64_alu_membase_reg_size (code, X86_CMP, MONO_ARCH_IMT_SCRATCH_REG, 0, MONO_ARCH_IMT_REG, sizeof (gpointer));
1276 labels [2] = code;
1277 amd64_branch8 (code, X86_CC_Z, 0, FALSE);
1279 /* Loop footer */
1280 amd64_alu_reg_imm (code, X86_ADD, MONO_ARCH_IMT_SCRATCH_REG, 2 * sizeof (gpointer));
1281 amd64_jump_code (code, labels [0]);
1283 /* Match */
1284 mono_amd64_patch (labels [2], code);
1285 amd64_mov_reg_membase (code, MONO_ARCH_IMT_SCRATCH_REG, MONO_ARCH_IMT_SCRATCH_REG, sizeof (gpointer), sizeof (gpointer));
1286 amd64_jump_membase (code, MONO_ARCH_IMT_SCRATCH_REG, 0);
1288 /* No match */
1289 /* FIXME: */
1290 mono_amd64_patch (labels [1], code);
1291 x86_breakpoint (code);
1293 /* mov <OFFSET>(%rip), MONO_ARCH_IMT_SCRATCH_REG */
1294 amd64_emit_rex (mov_buf_ptr, sizeof(gpointer), MONO_ARCH_IMT_SCRATCH_REG, 0, AMD64_RIP);
1295 *(mov_buf_ptr)++ = (unsigned char)0x8b; /* mov opcode */
1296 x86_address_byte (mov_buf_ptr, 0, MONO_ARCH_IMT_SCRATCH_REG & 0x7, 5);
1297 emit_bytes (acfg, mov_buf, mov_buf_ptr - mov_buf);
1298 emit_symbol_diff (acfg, acfg->got_symbol, ".", (offset * sizeof (gpointer)) - 4);
1300 emit_bytes (acfg, buf, code - buf);
1302 *tramp_size = code - buf + kSizeOfMove;
1303 #if defined(__native_client_codegen__)
1304 /* The tramp will be padded to the next kNaClAlignment bundle. */
1305 *tramp_size = ALIGN_TO ((*tramp_size), kNaClAlignment);
1306 #endif
1308 #if defined(__default_codegen__)
1309 g_free (buf);
1310 #elif defined(__native_client_codegen__)
1311 g_free (buf_alloc);
1312 #endif
1314 #elif defined(TARGET_X86)
1315 guint8 *buf, *code;
1316 #ifdef __native_client_codegen__
1317 guint8 *buf_alloc;
1318 #endif
1319 guint8 *labels [3];
1321 #if defined(__default_codegen__)
1322 code = buf = g_malloc (256);
1323 #elif defined(__native_client_codegen__)
1324 buf_alloc = g_malloc (256 + kNaClAlignment);
1325 code = buf = ((guint)buf_alloc + kNaClAlignment) & ~kNaClAlignmentMask;
1326 #endif
1328 /* Allocate a temporary stack slot */
1329 x86_push_reg (code, X86_EAX);
1330 /* Save EAX */
1331 x86_push_reg (code, X86_EAX);
1333 /* Load mscorlib got address */
1334 x86_mov_reg_membase (code, X86_EAX, MONO_ARCH_GOT_REG, sizeof (gpointer), 4);
1335 /* Load arg */
1336 x86_mov_reg_membase (code, X86_EAX, X86_EAX, offset * sizeof (gpointer), 4);
1338 labels [0] = code;
1339 x86_alu_membase_imm (code, X86_CMP, X86_EAX, 0, 0);
1340 labels [1] = code;
1341 x86_branch8 (code, X86_CC_Z, FALSE, 0);
1343 /* Check key */
1344 x86_alu_membase_reg (code, X86_CMP, X86_EAX, 0, MONO_ARCH_IMT_REG);
1345 labels [2] = code;
1346 x86_branch8 (code, X86_CC_Z, FALSE, 0);
1348 /* Loop footer */
1349 x86_alu_reg_imm (code, X86_ADD, X86_EAX, 2 * sizeof (gpointer));
1350 x86_jump_code (code, labels [0]);
1352 /* Match */
1353 mono_x86_patch (labels [2], code);
1354 x86_mov_reg_membase (code, X86_EAX, X86_EAX, sizeof (gpointer), 4);
1355 x86_mov_reg_membase (code, X86_EAX, X86_EAX, 0, 4);
1356 /* Save the target address to the temporary stack location */
1357 x86_mov_membase_reg (code, X86_ESP, 4, X86_EAX, 4);
1358 /* Restore EAX */
1359 x86_pop_reg (code, X86_EAX);
1360 /* Jump to the target address */
1361 x86_ret (code);
1363 /* No match */
1364 /* FIXME: */
1365 mono_x86_patch (labels [1], code);
1366 x86_breakpoint (code);
1368 #ifdef __native_client_codegen__
1370 /* emit nops to next 32 byte alignment */
1371 int a = (~kNaClAlignmentMask) & ((code - buf) + kNaClAlignment - 1);
1372 while (code < (buf + a)) x86_nop(code);
1374 #endif
1375 emit_bytes (acfg, buf, code - buf);
1377 *tramp_size = code - buf;
1379 #if defined(__default_codegen__)
1380 g_free (buf);
1381 #elif defined(__native_client_codegen__)
1382 g_free (buf_alloc);
1383 #endif
1385 #elif defined(TARGET_ARM)
1386 guint8 buf [128];
1387 guint8 *code, *code2, *labels [16];
1389 code = buf;
1391 /* The IMT method is in v5 */
1393 /* Need at least two free registers, plus a slot for storing the pc */
1394 ARM_PUSH (code, (1 << ARMREG_R0)|(1 << ARMREG_R1)|(1 << ARMREG_R2));
1395 labels [0] = code;
1396 /* Load the parameter from the GOT */
1397 ARM_LDR_IMM (code, ARMREG_R0, ARMREG_PC, 0);
1398 ARM_LDR_REG_REG (code, ARMREG_R0, ARMREG_PC, ARMREG_R0);
1400 labels [1] = code;
1401 ARM_LDR_IMM (code, ARMREG_R1, ARMREG_R0, 0);
1402 ARM_CMP_REG_REG (code, ARMREG_R1, ARMREG_V5);
1403 labels [2] = code;
1404 ARM_B_COND (code, ARMCOND_EQ, 0);
1406 /* End-of-loop check */
1407 ARM_CMP_REG_IMM (code, ARMREG_R1, 0, 0);
1408 labels [3] = code;
1409 ARM_B_COND (code, ARMCOND_EQ, 0);
1411 /* Loop footer */
1412 ARM_ADD_REG_IMM8 (code, ARMREG_R0, ARMREG_R0, sizeof (gpointer) * 2);
1413 labels [4] = code;
1414 ARM_B (code, 0);
1415 arm_patch (labels [4], labels [1]);
1417 /* Match */
1418 arm_patch (labels [2], code);
1419 ARM_LDR_IMM (code, ARMREG_R0, ARMREG_R0, 4);
1420 ARM_LDR_IMM (code, ARMREG_R0, ARMREG_R0, 0);
1421 /* Save it to the third stack slot */
1422 ARM_STR_IMM (code, ARMREG_R0, ARMREG_SP, 8);
1423 /* Restore the registers and branch */
1424 ARM_POP (code, (1 << ARMREG_R0)|(1 << ARMREG_R1)|(1 << ARMREG_PC));
1426 /* No match */
1427 arm_patch (labels [3], code);
1428 ARM_LDR_IMM (code, ARMREG_R0, ARMREG_R0, 4);
1429 ARM_STR_IMM (code, ARMREG_R0, ARMREG_SP, 8);
1430 ARM_POP (code, (1 << ARMREG_R0)|(1 << ARMREG_R1)|(1 << ARMREG_PC));
1432 /* Fixup offset */
1433 code2 = labels [0];
1434 ARM_LDR_IMM (code2, ARMREG_R0, ARMREG_PC, (code - (labels [0] + 8)));
1436 emit_bytes (acfg, buf, code - buf);
1437 emit_symbol_diff (acfg, acfg->got_symbol, ".", (offset * sizeof (gpointer)) + (code - (labels [0] + 8)) - 4);
1439 *tramp_size = code - buf + 4;
1440 #elif defined(TARGET_POWERPC)
1441 guint8 buf [128];
1442 guint8 *code, *labels [16];
1444 code = buf;
1446 /* Load the mscorlib got address */
1447 ppc_ldptr (code, ppc_r11, sizeof (gpointer), ppc_r30);
1448 /* Load the parameter from the GOT */
1449 ppc_load (code, ppc_r0, offset * sizeof (gpointer));
1450 ppc_ldptr_indexed (code, ppc_r11, ppc_r11, ppc_r0);
1452 /* Load and check key */
1453 labels [1] = code;
1454 ppc_ldptr (code, ppc_r0, 0, ppc_r11);
1455 ppc_cmp (code, 0, sizeof (gpointer) == 8 ? 1 : 0, ppc_r0, MONO_ARCH_IMT_REG);
1456 labels [2] = code;
1457 ppc_bc (code, PPC_BR_TRUE, PPC_BR_EQ, 0);
1459 /* End-of-loop check */
1460 ppc_cmpi (code, 0, sizeof (gpointer) == 8 ? 1 : 0, ppc_r0, 0);
1461 labels [3] = code;
1462 ppc_bc (code, PPC_BR_TRUE, PPC_BR_EQ, 0);
1464 /* Loop footer */
1465 ppc_addi (code, ppc_r11, ppc_r11, 2 * sizeof (gpointer));
1466 labels [4] = code;
1467 ppc_b (code, 0);
1468 mono_ppc_patch (labels [4], labels [1]);
1470 /* Match */
1471 mono_ppc_patch (labels [2], code);
1472 ppc_ldptr (code, ppc_r11, sizeof (gpointer), ppc_r11);
1473 /* r11 now contains the value of the vtable slot */
1474 /* this is not a function descriptor on ppc64 */
1475 ppc_ldptr (code, ppc_r11, 0, ppc_r11);
1476 ppc_mtctr (code, ppc_r11);
1477 ppc_bcctr (code, PPC_BR_ALWAYS, 0);
1479 /* Fail */
1480 mono_ppc_patch (labels [3], code);
1481 /* FIXME: */
1482 ppc_break (code);
1484 *tramp_size = code - buf;
1486 emit_bytes (acfg, buf, code - buf);
1487 #else
1488 g_assert_not_reached ();
1489 #endif
1492 static void
1493 arch_emit_autoreg (MonoAotCompile *acfg, char *symbol)
1495 #if defined(TARGET_POWERPC) && defined(__mono_ilp32__)
1496 /* Based on code generated by gcc */
1497 img_writer_emit_unset_mode (acfg->w);
1499 fprintf (acfg->fp,
1500 #if defined(_MSC_VER) || defined(MONO_CROSS_COMPILE)
1501 ".section .ctors,\"aw\",@progbits\n"
1502 ".align 2\n"
1503 ".globl %s\n"
1504 ".long %s\n"
1505 ".section .opd,\"aw\"\n"
1506 ".align 2\n"
1507 "%s:\n"
1508 ".long .%s,.TOC.@tocbase32\n"
1509 ".size %s,.-%s\n"
1510 ".section .text\n"
1511 ".type .%s,@function\n"
1512 ".align 2\n"
1513 ".%s:\n", symbol, symbol, symbol, symbol, symbol, symbol, symbol, symbol);
1514 #else
1515 ".section .ctors,\"aw\",@progbits\n"
1516 ".align 2\n"
1517 ".globl %1$s\n"
1518 ".long %1$s\n"
1519 ".section .opd,\"aw\"\n"
1520 ".align 2\n"
1521 "%1$s:\n"
1522 ".long .%1$s,.TOC.@tocbase32\n"
1523 ".size %1$s,.-%1$s\n"
1524 ".section .text\n"
1525 ".type .%1$s,@function\n"
1526 ".align 2\n"
1527 ".%1$s:\n", symbol);
1528 #endif
1531 fprintf (acfg->fp,
1532 "stdu 1,-128(1)\n"
1533 "mflr 0\n"
1534 "std 31,120(1)\n"
1535 "std 0,144(1)\n"
1537 ".Lautoreg:\n"
1538 "lis 3, .Lglobals@h\n"
1539 "ori 3, 3, .Lglobals@l\n"
1540 "bl .mono_aot_register_module\n"
1541 "ld 11,0(1)\n"
1542 "ld 0,16(11)\n"
1543 "mtlr 0\n"
1544 "ld 31,-8(11)\n"
1545 "mr 1,11\n"
1546 "blr\n"
1548 #if defined(_MSC_VER) || defined(MONO_CROSS_COMPILE)
1549 fprintf (acfg->fp,
1550 ".size .%s,.-.%s\n", symbol, symbol);
1551 #else
1552 fprintf (acfg->fp,
1553 ".size .%1$s,.-.%1$s\n", symbol);
1554 #endif
1555 #else
1556 #endif
1559 /* END OF ARCH SPECIFIC CODE */
1561 static guint32
1562 mono_get_field_token (MonoClassField *field)
1564 MonoClass *klass = field->parent;
1565 int i;
1567 for (i = 0; i < klass->field.count; ++i) {
1568 if (field == &klass->fields [i])
1569 return MONO_TOKEN_FIELD_DEF | (klass->field.first + 1 + i);
1572 g_assert_not_reached ();
1573 return 0;
1576 static inline void
1577 encode_value (gint32 value, guint8 *buf, guint8 **endbuf)
1579 guint8 *p = buf;
1581 //printf ("ENCODE: %d 0x%x.\n", value, value);
1584 * Same encoding as the one used in the metadata, extended to handle values
1585 * greater than 0x1fffffff.
1587 if ((value >= 0) && (value <= 127))
1588 *p++ = value;
1589 else if ((value >= 0) && (value <= 16383)) {
1590 p [0] = 0x80 | (value >> 8);
1591 p [1] = value & 0xff;
1592 p += 2;
1593 } else if ((value >= 0) && (value <= 0x1fffffff)) {
1594 p [0] = (value >> 24) | 0xc0;
1595 p [1] = (value >> 16) & 0xff;
1596 p [2] = (value >> 8) & 0xff;
1597 p [3] = value & 0xff;
1598 p += 4;
1600 else {
1601 p [0] = 0xff;
1602 p [1] = (value >> 24) & 0xff;
1603 p [2] = (value >> 16) & 0xff;
1604 p [3] = (value >> 8) & 0xff;
1605 p [4] = value & 0xff;
1606 p += 5;
1608 if (endbuf)
1609 *endbuf = p;
1612 static void
1613 stream_init (MonoDynamicStream *sh)
1615 sh->index = 0;
1616 sh->alloc_size = 4096;
1617 sh->data = g_malloc (4096);
1619 /* So offsets are > 0 */
1620 sh->data [0] = 0;
1621 sh->index ++;
1624 static void
1625 make_room_in_stream (MonoDynamicStream *stream, int size)
1627 if (size <= stream->alloc_size)
1628 return;
1630 while (stream->alloc_size <= size) {
1631 if (stream->alloc_size < 4096)
1632 stream->alloc_size = 4096;
1633 else
1634 stream->alloc_size *= 2;
1637 stream->data = g_realloc (stream->data, stream->alloc_size);
1640 static guint32
1641 add_stream_data (MonoDynamicStream *stream, const char *data, guint32 len)
1643 guint32 idx;
1645 make_room_in_stream (stream, stream->index + len);
1646 memcpy (stream->data + stream->index, data, len);
1647 idx = stream->index;
1648 stream->index += len;
1649 return idx;
1653 * add_to_blob:
1655 * Add data to the binary blob inside the aot image. Returns the offset inside the
1656 * blob where the data was stored.
1658 static guint32
1659 add_to_blob (MonoAotCompile *acfg, const guint8 *data, guint32 data_len)
1661 if (acfg->blob.alloc_size == 0)
1662 stream_init (&acfg->blob);
1664 return add_stream_data (&acfg->blob, (char*)data, data_len);
1667 static guint32
1668 add_to_blob_aligned (MonoAotCompile *acfg, const guint8 *data, guint32 data_len, guint32 align)
1670 char buf [4] = {0};
1671 guint32 count;
1673 if (acfg->blob.alloc_size == 0)
1674 stream_init (&acfg->blob);
1676 count = acfg->blob.index % align;
1678 /* we assume the stream data will be aligned */
1679 if (count)
1680 add_stream_data (&acfg->blob, buf, 4 - count);
1682 return add_stream_data (&acfg->blob, (char*)data, data_len);
1686 * emit_offset_table:
1688 * Emit a table of increasing offsets in a compact form using differential encoding.
1689 * There is an index entry for each GROUP_SIZE number of entries. The greater the
1690 * group size, the more compact the table becomes, but the slower it becomes to compute
1691 * a given entry. Returns the size of the table.
1693 static guint32
1694 emit_offset_table (MonoAotCompile *acfg, int noffsets, int group_size, gint32 *offsets)
1696 gint32 current_offset;
1697 int i, buf_size, ngroups, index_entry_size;
1698 guint8 *p, *buf;
1699 guint32 *index_offsets;
1701 ngroups = (noffsets + (group_size - 1)) / group_size;
1703 index_offsets = g_new0 (guint32, ngroups);
1705 buf_size = noffsets * 4;
1706 p = buf = g_malloc0 (buf_size);
1708 current_offset = 0;
1709 for (i = 0; i < noffsets; ++i) {
1710 //printf ("D: %d -> %d\n", i, offsets [i]);
1711 if ((i % group_size) == 0) {
1712 index_offsets [i / group_size] = p - buf;
1713 /* Emit the full value for these entries */
1714 encode_value (offsets [i], p, &p);
1715 } else {
1716 /* The offsets are allowed to be non-increasing */
1717 //g_assert (offsets [i] >= current_offset);
1718 encode_value (offsets [i] - current_offset, p, &p);
1720 current_offset = offsets [i];
1723 if (ngroups && index_offsets [ngroups - 1] < 65000)
1724 index_entry_size = 2;
1725 else
1726 index_entry_size = 4;
1728 /* Emit the header */
1729 emit_int32 (acfg, noffsets);
1730 emit_int32 (acfg, group_size);
1731 emit_int32 (acfg, ngroups);
1732 emit_int32 (acfg, index_entry_size);
1734 /* Emit the index */
1735 for (i = 0; i < ngroups; ++i) {
1736 if (index_entry_size == 2)
1737 emit_int16 (acfg, index_offsets [i]);
1738 else
1739 emit_int32 (acfg, index_offsets [i]);
1742 /* Emit the data */
1743 emit_bytes (acfg, buf, p - buf);
1745 return (int)(p - buf) + (ngroups * 4);
1748 static guint32
1749 get_image_index (MonoAotCompile *cfg, MonoImage *image)
1751 guint32 index;
1753 index = GPOINTER_TO_UINT (g_hash_table_lookup (cfg->image_hash, image));
1754 if (index)
1755 return index - 1;
1756 else {
1757 index = g_hash_table_size (cfg->image_hash);
1758 g_hash_table_insert (cfg->image_hash, image, GUINT_TO_POINTER (index + 1));
1759 g_ptr_array_add (cfg->image_table, image);
1760 return index;
1764 static guint32
1765 find_typespec_for_class (MonoAotCompile *acfg, MonoClass *klass)
1767 int i;
1768 int len = acfg->image->tables [MONO_TABLE_TYPESPEC].rows;
1770 /* FIXME: Search referenced images as well */
1771 if (!acfg->typespec_classes) {
1772 acfg->typespec_classes = mono_mempool_alloc0 (acfg->mempool, sizeof (MonoClass*) * len);
1773 for (i = 0; i < len; ++i) {
1774 acfg->typespec_classes [i] = mono_class_get_full (acfg->image, MONO_TOKEN_TYPE_SPEC | (i + 1), NULL);
1777 for (i = 0; i < len; ++i) {
1778 if (acfg->typespec_classes [i] == klass)
1779 break;
1782 if (i < len)
1783 return MONO_TOKEN_TYPE_SPEC | (i + 1);
1784 else
1785 return 0;
1788 static void
1789 encode_method_ref (MonoAotCompile *acfg, MonoMethod *method, guint8 *buf, guint8 **endbuf);
1792 * encode_klass_ref:
1794 * Encode a reference to KLASS. We use our home-grown encoding instead of the
1795 * standard metadata encoding.
1797 static void
1798 encode_klass_ref (MonoAotCompile *acfg, MonoClass *klass, guint8 *buf, guint8 **endbuf)
1800 guint8 *p = buf;
1802 if (klass->generic_class) {
1803 guint32 token;
1804 g_assert (klass->type_token);
1806 /* Find a typespec for a class if possible */
1807 token = find_typespec_for_class (acfg, klass);
1808 if (token) {
1809 encode_value (token, p, &p);
1810 encode_value (get_image_index (acfg, acfg->image), p, &p);
1811 } else {
1812 MonoClass *gclass = klass->generic_class->container_class;
1813 MonoGenericInst *inst = klass->generic_class->context.class_inst;
1814 int i;
1816 /* Encode it ourselves */
1817 /* Marker */
1818 encode_value (MONO_TOKEN_TYPE_SPEC, p, &p);
1819 encode_value (MONO_TYPE_GENERICINST, p, &p);
1820 encode_klass_ref (acfg, gclass, p, &p);
1821 encode_value (inst->type_argc, p, &p);
1822 for (i = 0; i < inst->type_argc; ++i)
1823 encode_klass_ref (acfg, mono_class_from_mono_type (inst->type_argv [i]), p, &p);
1825 } else if (klass->type_token) {
1826 g_assert (mono_metadata_token_code (klass->type_token) == MONO_TOKEN_TYPE_DEF);
1827 encode_value (klass->type_token - MONO_TOKEN_TYPE_DEF, p, &p);
1828 encode_value (get_image_index (acfg, klass->image), p, &p);
1829 } else if ((klass->byval_arg.type == MONO_TYPE_VAR) || (klass->byval_arg.type == MONO_TYPE_MVAR)) {
1830 MonoGenericContainer *container = mono_type_get_generic_param_owner (&klass->byval_arg);
1831 g_assert (container);
1833 /* Marker */
1834 encode_value (MONO_TOKEN_TYPE_SPEC, p, &p);
1835 encode_value (klass->byval_arg.type, p, &p);
1837 encode_value (mono_type_get_generic_param_num (&klass->byval_arg), p, &p);
1839 encode_value (container->is_method, p, &p);
1840 if (container->is_method)
1841 encode_method_ref (acfg, container->owner.method, p, &p);
1842 else
1843 encode_klass_ref (acfg, container->owner.klass, p, &p);
1844 } else {
1845 /* Array class */
1846 g_assert (klass->rank > 0);
1847 encode_value (MONO_TOKEN_TYPE_DEF, p, &p);
1848 encode_value (get_image_index (acfg, klass->image), p, &p);
1849 encode_value (klass->rank, p, &p);
1850 encode_klass_ref (acfg, klass->element_class, p, &p);
1852 *endbuf = p;
1855 static void
1856 encode_field_info (MonoAotCompile *cfg, MonoClassField *field, guint8 *buf, guint8 **endbuf)
1858 guint32 token = mono_get_field_token (field);
1859 guint8 *p = buf;
1861 encode_klass_ref (cfg, field->parent, p, &p);
1862 g_assert (mono_metadata_token_code (token) == MONO_TOKEN_FIELD_DEF);
1863 encode_value (token - MONO_TOKEN_FIELD_DEF, p, &p);
1864 *endbuf = p;
1867 static void
1868 encode_generic_context (MonoAotCompile *acfg, MonoGenericContext *context, guint8 *buf, guint8 **endbuf)
1870 guint8 *p = buf;
1871 int i;
1872 MonoGenericInst *inst;
1874 /* Encode the context */
1875 inst = context->class_inst;
1876 encode_value (inst ? 1 : 0, p, &p);
1877 if (inst) {
1878 encode_value (inst->type_argc, p, &p);
1879 for (i = 0; i < inst->type_argc; ++i)
1880 encode_klass_ref (acfg, mono_class_from_mono_type (inst->type_argv [i]), p, &p);
1882 inst = context->method_inst;
1883 encode_value (inst ? 1 : 0, p, &p);
1884 if (inst) {
1885 encode_value (inst->type_argc, p, &p);
1886 for (i = 0; i < inst->type_argc; ++i)
1887 encode_klass_ref (acfg, mono_class_from_mono_type (inst->type_argv [i]), p, &p);
1890 *endbuf = p;
1893 #define MAX_IMAGE_INDEX 250
1895 static void
1896 encode_method_ref (MonoAotCompile *acfg, MonoMethod *method, guint8 *buf, guint8 **endbuf)
1898 guint32 image_index = get_image_index (acfg, method->klass->image);
1899 guint32 token = method->token;
1900 MonoJumpInfoToken *ji;
1901 guint8 *p = buf;
1902 char *name;
1905 * The encoding for most methods is as follows:
1906 * - image index encoded as a leb128
1907 * - token index encoded as a leb128
1908 * Values of image index >= MONO_AOT_METHODREF_MIN are used to mark additional
1909 * types of method encodings.
1912 g_assert (image_index < MONO_AOT_METHODREF_MIN);
1914 /* Mark methods which can't use aot trampolines because they need the further
1915 * processing in mono_magic_trampoline () which requires a MonoMethod*.
1917 if ((method->is_generic && (method->flags & METHOD_ATTRIBUTE_VIRTUAL)) ||
1918 (method->iflags & METHOD_IMPL_ATTRIBUTE_SYNCHRONIZED))
1919 encode_value ((MONO_AOT_METHODREF_NO_AOT_TRAMPOLINE << 24), p, &p);
1922 * Some wrapper methods are shared using their signature, encode their
1923 * stringified signature instead.
1924 * FIXME: Optimize disk usage
1926 name = NULL;
1927 if (method->wrapper_type) {
1928 if (method->wrapper_type == MONO_WRAPPER_RUNTIME_INVOKE) {
1929 char *tmpsig = mono_signature_get_desc (mono_method_signature (method), TRUE);
1930 if (strcmp (method->name, "runtime_invoke_dynamic")) {
1931 name = mono_aot_wrapper_name (method);
1932 } else if (mono_marshal_method_from_wrapper (method) != method) {
1933 /* Direct wrapper, encode it normally */
1934 } else {
1935 name = g_strdup_printf ("(wrapper runtime-invoke):%s (%s)", method->name, tmpsig);
1937 g_free (tmpsig);
1938 } else if (method->wrapper_type == MONO_WRAPPER_DELEGATE_INVOKE) {
1939 char *tmpsig = mono_signature_get_desc (mono_method_signature (method), TRUE);
1940 name = g_strdup_printf ("(wrapper delegate-invoke):%s (%s)", method->name, tmpsig);
1941 g_free (tmpsig);
1942 } else if (method->wrapper_type == MONO_WRAPPER_DELEGATE_BEGIN_INVOKE) {
1943 char *tmpsig = mono_signature_get_desc (mono_method_signature (method), TRUE);
1944 name = g_strdup_printf ("(wrapper delegate-begin-invoke):%s (%s)", method->name, tmpsig);
1945 g_free (tmpsig);
1946 } else if (method->wrapper_type == MONO_WRAPPER_DELEGATE_END_INVOKE) {
1947 char *tmpsig = mono_signature_get_desc (mono_method_signature (method), TRUE);
1948 name = g_strdup_printf ("(wrapper delegate-end-invoke):%s (%s)", method->name, tmpsig);
1949 g_free (tmpsig);
1953 if (name) {
1954 encode_value ((MONO_AOT_METHODREF_WRAPPER_NAME << 24), p, &p);
1955 strcpy ((char*)p, name);
1956 p += strlen (name) + 1;
1957 g_free (name);
1958 } else if (method->wrapper_type) {
1959 encode_value ((MONO_AOT_METHODREF_WRAPPER << 24), p, &p);
1961 encode_value (method->wrapper_type, p, &p);
1963 switch (method->wrapper_type) {
1964 case MONO_WRAPPER_REMOTING_INVOKE:
1965 case MONO_WRAPPER_REMOTING_INVOKE_WITH_CHECK:
1966 case MONO_WRAPPER_XDOMAIN_INVOKE: {
1967 MonoMethod *m;
1969 m = mono_marshal_method_from_wrapper (method);
1970 g_assert (m);
1971 encode_method_ref (acfg, m, p, &p);
1972 break;
1974 case MONO_WRAPPER_PROXY_ISINST:
1975 case MONO_WRAPPER_LDFLD:
1976 case MONO_WRAPPER_LDFLDA:
1977 case MONO_WRAPPER_STFLD:
1978 case MONO_WRAPPER_ISINST: {
1979 MonoClass *proxy_class = mono_marshal_get_wrapper_info (method);
1980 encode_klass_ref (acfg, proxy_class, p, &p);
1981 break;
1983 case MONO_WRAPPER_LDFLD_REMOTE:
1984 case MONO_WRAPPER_STFLD_REMOTE:
1985 break;
1986 case MONO_WRAPPER_ALLOC: {
1987 AllocatorWrapperInfo *info = mono_marshal_get_wrapper_info (method);
1989 /* The GC name is saved once in MonoAotFileInfo */
1990 g_assert (info->alloc_type != -1);
1991 encode_value (info->alloc_type, p, &p);
1992 break;
1994 case MONO_WRAPPER_WRITE_BARRIER:
1995 break;
1996 case MONO_WRAPPER_STELEMREF: {
1997 MonoClass *klass = mono_marshal_get_wrapper_info (method);
1999 /* Make sure this is the 'normal' stelemref wrapper, not the virtual one */
2000 g_assert (!klass);
2001 break;
2003 case MONO_WRAPPER_UNKNOWN:
2004 if (strcmp (method->name, "FastMonitorEnter") == 0) {
2005 encode_value (MONO_AOT_WRAPPER_MONO_ENTER, p, &p);
2006 } else if (strcmp (method->name, "FastMonitorExit") == 0) {
2007 encode_value (MONO_AOT_WRAPPER_MONO_EXIT, p, &p);
2008 } else if (strcmp (method->name, "PtrToStructure") == 0) {
2009 encode_value (MONO_AOT_WRAPPER_PTR_TO_STRUCTURE, p, &p);
2010 encode_klass_ref (acfg, method->klass, p, &p);
2011 } else if (strcmp (method->name, "StructureToPtr") == 0) {
2012 encode_value (MONO_AOT_WRAPPER_STRUCTURE_TO_PTR, p, &p);
2013 encode_klass_ref (acfg, method->klass, p, &p);
2014 } else {
2015 g_assert_not_reached ();
2017 break;
2018 case MONO_WRAPPER_SYNCHRONIZED:
2019 case MONO_WRAPPER_MANAGED_TO_NATIVE:
2020 case MONO_WRAPPER_RUNTIME_INVOKE: {
2021 MonoMethod *m;
2023 m = mono_marshal_method_from_wrapper (method);
2024 g_assert (m);
2025 g_assert (m != method);
2026 encode_method_ref (acfg, m, p, &p);
2027 break;
2029 case MONO_WRAPPER_MANAGED_TO_MANAGED:
2030 if (!strcmp (method->name, "ElementAddr")) {
2031 ElementAddrWrapperInfo *info = mono_marshal_get_wrapper_info (method);
2033 g_assert (info);
2034 encode_value (MONO_AOT_WRAPPER_ELEMENT_ADDR, p, &p);
2035 encode_value (info->rank, p, &p);
2036 encode_value (info->elem_size, p, &p);
2037 } else {
2038 g_assert_not_reached ();
2040 break;
2041 case MONO_WRAPPER_CASTCLASS:
2042 if (!strcmp (method->name, "__castclass_with_cache")) {
2043 encode_value (MONO_AOT_WRAPPER_CASTCLASS_WITH_CACHE, p, &p);
2044 } else if (!strcmp (method->name, "__isinst_with_cache")) {
2045 encode_value (MONO_AOT_WRAPPER_ISINST_WITH_CACHE, p, &p);
2046 } else {
2047 g_assert_not_reached ();
2049 break;
2050 default:
2051 g_assert_not_reached ();
2053 } else if (mono_method_signature (method)->is_inflated) {
2055 * This is a generic method, find the original token which referenced it and
2056 * encode that.
2057 * Obtain the token from information recorded by the JIT.
2059 ji = g_hash_table_lookup (acfg->token_info_hash, method);
2060 if (ji) {
2061 image_index = get_image_index (acfg, ji->image);
2062 g_assert (image_index < MAX_IMAGE_INDEX);
2063 token = ji->token;
2065 encode_value ((MONO_AOT_METHODREF_METHODSPEC << 24), p, &p);
2066 encode_value (image_index, p, &p);
2067 encode_value (token, p, &p);
2068 } else {
2069 MonoMethod *declaring;
2070 MonoGenericContext *context = mono_method_get_context (method);
2072 g_assert (method->is_inflated);
2073 declaring = ((MonoMethodInflated*)method)->declaring;
2076 * This might be a non-generic method of a generic instance, which
2077 * doesn't have a token since the reference is generated by the JIT
2078 * like Nullable:Box/Unbox, or by generic sharing.
2081 encode_value ((MONO_AOT_METHODREF_GINST << 24), p, &p);
2082 /* Encode the klass */
2083 encode_klass_ref (acfg, method->klass, p, &p);
2084 /* Encode the method */
2085 image_index = get_image_index (acfg, method->klass->image);
2086 g_assert (image_index < MAX_IMAGE_INDEX);
2087 g_assert (declaring->token);
2088 token = declaring->token;
2089 g_assert (mono_metadata_token_table (token) == MONO_TABLE_METHOD);
2090 encode_value (image_index, p, &p);
2091 encode_value (token, p, &p);
2092 encode_generic_context (acfg, context, p, &p);
2094 } else if (token == 0) {
2095 /* This might be a method of a constructed type like int[,].Set */
2096 /* Obtain the token from information recorded by the JIT */
2097 ji = g_hash_table_lookup (acfg->token_info_hash, method);
2098 if (ji) {
2099 image_index = get_image_index (acfg, ji->image);
2100 g_assert (image_index < MAX_IMAGE_INDEX);
2101 token = ji->token;
2103 encode_value ((MONO_AOT_METHODREF_METHODSPEC << 24), p, &p);
2104 encode_value (image_index, p, &p);
2105 encode_value (token, p, &p);
2106 } else {
2107 /* Array methods */
2108 g_assert (method->klass->rank);
2110 /* Encode directly */
2111 encode_value ((MONO_AOT_METHODREF_ARRAY << 24), p, &p);
2112 encode_klass_ref (acfg, method->klass, p, &p);
2113 if (!strcmp (method->name, ".ctor") && mono_method_signature (method)->param_count == method->klass->rank)
2114 encode_value (0, p, &p);
2115 else if (!strcmp (method->name, ".ctor") && mono_method_signature (method)->param_count == method->klass->rank * 2)
2116 encode_value (1, p, &p);
2117 else if (!strcmp (method->name, "Get"))
2118 encode_value (2, p, &p);
2119 else if (!strcmp (method->name, "Address"))
2120 encode_value (3, p, &p);
2121 else if (!strcmp (method->name, "Set"))
2122 encode_value (4, p, &p);
2123 else
2124 g_assert_not_reached ();
2126 } else {
2127 g_assert (mono_metadata_token_table (token) == MONO_TABLE_METHOD);
2128 encode_value ((image_index << 24) | mono_metadata_token_index (token), p, &p);
2130 *endbuf = p;
2133 static gint
2134 compare_patches (gconstpointer a, gconstpointer b)
2136 int i, j;
2138 i = (*(MonoJumpInfo**)a)->ip.i;
2139 j = (*(MonoJumpInfo**)b)->ip.i;
2141 if (i < j)
2142 return -1;
2143 else
2144 if (i > j)
2145 return 1;
2146 else
2147 return 0;
2150 static G_GNUC_UNUSED char*
2151 patch_to_string (MonoJumpInfo *patch_info)
2153 GString *str;
2155 str = g_string_new ("");
2157 g_string_append_printf (str, "%s(", get_patch_name (patch_info->type));
2159 switch (patch_info->type) {
2160 case MONO_PATCH_INFO_VTABLE:
2161 mono_type_get_desc (str, &patch_info->data.klass->byval_arg, TRUE);
2162 break;
2163 default:
2164 break;
2166 g_string_append_printf (str, ")");
2167 return g_string_free (str, FALSE);
2171 * is_plt_patch:
2173 * Return whenever PATCH_INFO refers to a direct call, and thus requires a
2174 * PLT entry.
2176 static inline gboolean
2177 is_plt_patch (MonoJumpInfo *patch_info)
2179 switch (patch_info->type) {
2180 case MONO_PATCH_INFO_METHOD:
2181 case MONO_PATCH_INFO_INTERNAL_METHOD:
2182 case MONO_PATCH_INFO_JIT_ICALL_ADDR:
2183 case MONO_PATCH_INFO_ICALL_ADDR:
2184 case MONO_PATCH_INFO_CLASS_INIT:
2185 case MONO_PATCH_INFO_RGCTX_FETCH:
2186 case MONO_PATCH_INFO_GENERIC_CLASS_INIT:
2187 case MONO_PATCH_INFO_MONITOR_ENTER:
2188 case MONO_PATCH_INFO_MONITOR_EXIT:
2189 case MONO_PATCH_INFO_LLVM_IMT_TRAMPOLINE:
2190 return TRUE;
2191 default:
2192 return FALSE;
2197 * get_plt_symbol:
2199 * Return the symbol identifying the plt entry PLT_OFFSET.
2201 static char*
2202 get_plt_symbol (MonoAotCompile *acfg, int plt_offset, MonoJumpInfo *patch_info)
2204 #ifdef __APPLE__
2206 * The Apple linker reorganizes object files, so it doesn't like branches to local
2207 * labels, since those have no relocations.
2209 return g_strdup_printf ("%sp_%d", acfg->llvm_label_prefix, plt_offset);
2210 #else
2211 return g_strdup_printf ("%sp_%d", acfg->temp_prefix, plt_offset);
2212 #endif
2216 * get_plt_entry:
2218 * Return a PLT entry which belongs to the method identified by PATCH_INFO.
2220 static MonoPltEntry*
2221 get_plt_entry (MonoAotCompile *acfg, MonoJumpInfo *patch_info)
2223 MonoPltEntry *res;
2225 if (!is_plt_patch (patch_info))
2226 return NULL;
2228 res = g_hash_table_lookup (acfg->patch_to_plt_entry, patch_info);
2230 // FIXME: This breaks the calculation of final_got_size
2231 if (!acfg->llvm && patch_info->type == MONO_PATCH_INFO_METHOD && (patch_info->data.method->iflags & METHOD_IMPL_ATTRIBUTE_SYNCHRONIZED)) {
2233 * Allocate a separate PLT slot for each such patch, since some plt
2234 * entries will refer to the method itself, and some will refer to the
2235 * wrapper.
2237 res = NULL;
2240 if (!res) {
2241 MonoJumpInfo *new_ji;
2243 g_assert (!acfg->final_got_size);
2245 new_ji = mono_patch_info_dup_mp (acfg->mempool, patch_info);
2247 res = mono_mempool_alloc0 (acfg->mempool, sizeof (MonoPltEntry));
2248 res->plt_offset = acfg->plt_offset;
2249 res->ji = new_ji;
2250 res->symbol = get_plt_symbol (acfg, res->plt_offset, patch_info);
2251 res->llvm_symbol = g_strdup_printf ("%s_llvm", res->symbol);
2253 g_hash_table_insert (acfg->patch_to_plt_entry, new_ji, res);
2255 g_hash_table_insert (acfg->plt_offset_to_entry, GUINT_TO_POINTER (res->plt_offset), res);
2257 acfg->plt_offset ++;
2260 return res;
2264 * get_got_offset:
2266 * Returns the offset of the GOT slot where the runtime object resulting from resolving
2267 * JI could be found if it exists, otherwise allocates a new one.
2269 static guint32
2270 get_got_offset (MonoAotCompile *acfg, MonoJumpInfo *ji)
2272 guint32 got_offset;
2274 got_offset = GPOINTER_TO_UINT (g_hash_table_lookup (acfg->patch_to_got_offset_by_type [ji->type], ji));
2275 if (got_offset)
2276 return got_offset - 1;
2278 got_offset = acfg->got_offset;
2279 acfg->got_offset ++;
2281 if (acfg->final_got_size)
2282 g_assert (got_offset < acfg->final_got_size);
2284 acfg->stats.got_slots ++;
2285 acfg->stats.got_slot_types [ji->type] ++;
2287 g_hash_table_insert (acfg->patch_to_got_offset, ji, GUINT_TO_POINTER (got_offset + 1));
2288 g_hash_table_insert (acfg->patch_to_got_offset_by_type [ji->type], ji, GUINT_TO_POINTER (got_offset + 1));
2289 g_ptr_array_add (acfg->got_patches, ji);
2291 return got_offset;
2294 /* Add a method to the list of methods which need to be emitted */
2295 static void
2296 add_method_with_index (MonoAotCompile *acfg, MonoMethod *method, int index, gboolean extra)
2298 g_assert (method);
2299 if (!g_hash_table_lookup (acfg->method_indexes, method)) {
2300 g_ptr_array_add (acfg->methods, method);
2301 g_hash_table_insert (acfg->method_indexes, method, GUINT_TO_POINTER (index + 1));
2302 acfg->nmethods = acfg->methods->len + 1;
2305 if (method->wrapper_type || extra)
2306 g_ptr_array_add (acfg->extra_methods, method);
2309 static guint32
2310 get_method_index (MonoAotCompile *acfg, MonoMethod *method)
2312 int index = GPOINTER_TO_UINT (g_hash_table_lookup (acfg->method_indexes, method));
2314 g_assert (index);
2316 return index - 1;
2319 static int
2320 add_method_full (MonoAotCompile *acfg, MonoMethod *method, gboolean extra, int depth)
2322 int index;
2324 index = GPOINTER_TO_UINT (g_hash_table_lookup (acfg->method_indexes, method));
2325 if (index)
2326 return index - 1;
2328 index = acfg->method_index;
2329 add_method_with_index (acfg, method, index, extra);
2331 g_ptr_array_add (acfg->method_order, GUINT_TO_POINTER (index));
2333 g_hash_table_insert (acfg->method_depth, method, GUINT_TO_POINTER (depth));
2335 acfg->method_index ++;
2337 return index;
2340 static int
2341 add_method (MonoAotCompile *acfg, MonoMethod *method)
2343 return add_method_full (acfg, method, FALSE, 0);
2346 static void
2347 add_extra_method (MonoAotCompile *acfg, MonoMethod *method)
2349 add_method_full (acfg, method, TRUE, 0);
2352 static void
2353 add_extra_method_with_depth (MonoAotCompile *acfg, MonoMethod *method, int depth)
2355 add_method_full (acfg, method, TRUE, depth);
2358 static void
2359 add_jit_icall_wrapper (gpointer key, gpointer value, gpointer user_data)
2361 MonoAotCompile *acfg = user_data;
2362 MonoJitICallInfo *callinfo = value;
2363 MonoMethod *wrapper;
2364 char *name;
2366 if (!callinfo->sig)
2367 return;
2369 name = g_strdup_printf ("__icall_wrapper_%s", callinfo->name);
2370 wrapper = mono_marshal_get_icall_wrapper (callinfo->sig, name, callinfo->func, check_for_pending_exc);
2371 g_free (name);
2373 add_method (acfg, wrapper);
2376 static MonoMethod*
2377 get_runtime_invoke_sig (MonoMethodSignature *sig)
2379 MonoMethodBuilder *mb;
2380 MonoMethod *m;
2382 mb = mono_mb_new (mono_defaults.object_class, "FOO", MONO_WRAPPER_NONE);
2383 m = mono_mb_create_method (mb, sig, 16);
2384 return mono_marshal_get_runtime_invoke (m, FALSE);
2387 static gboolean
2388 can_marshal_struct (MonoClass *klass)
2390 MonoClassField *field;
2391 gboolean can_marshal = TRUE;
2392 gpointer iter = NULL;
2394 if ((klass->flags & TYPE_ATTRIBUTE_LAYOUT_MASK) == TYPE_ATTRIBUTE_AUTO_LAYOUT)
2395 return FALSE;
2397 /* Only allow a few field types to avoid asserts in the marshalling code */
2398 while ((field = mono_class_get_fields (klass, &iter))) {
2399 if ((field->type->attrs & FIELD_ATTRIBUTE_STATIC))
2400 continue;
2402 switch (field->type->type) {
2403 case MONO_TYPE_I4:
2404 case MONO_TYPE_U4:
2405 case MONO_TYPE_I1:
2406 case MONO_TYPE_U1:
2407 case MONO_TYPE_BOOLEAN:
2408 case MONO_TYPE_I2:
2409 case MONO_TYPE_U2:
2410 case MONO_TYPE_CHAR:
2411 case MONO_TYPE_I8:
2412 case MONO_TYPE_U8:
2413 case MONO_TYPE_I:
2414 case MONO_TYPE_U:
2415 case MONO_TYPE_PTR:
2416 case MONO_TYPE_R4:
2417 case MONO_TYPE_R8:
2418 case MONO_TYPE_STRING:
2419 break;
2420 case MONO_TYPE_VALUETYPE:
2421 if (!mono_class_from_mono_type (field->type)->enumtype && !can_marshal_struct (mono_class_from_mono_type (field->type)))
2422 can_marshal = FALSE;
2423 break;
2424 default:
2425 can_marshal = FALSE;
2426 break;
2430 /* Special cases */
2431 /* Its hard to compute whenever these can be marshalled or not */
2432 if (!strcmp (klass->name_space, "System.Net.NetworkInformation.MacOsStructs"))
2433 return TRUE;
2435 return can_marshal;
2438 static void
2439 add_wrappers (MonoAotCompile *acfg)
2441 MonoMethod *method, *m;
2442 int i, j;
2443 MonoMethodSignature *sig, *csig;
2444 guint32 token;
2447 * FIXME: Instead of AOTing all the wrappers, it might be better to redesign them
2448 * so there is only one wrapper of a given type, or inlining their contents into their
2449 * callers.
2453 * FIXME: This depends on the fact that different wrappers have different
2454 * names.
2457 for (i = 0; i < acfg->image->tables [MONO_TABLE_METHOD].rows; ++i) {
2458 MonoMethod *method;
2459 guint32 token = MONO_TOKEN_METHOD_DEF | (i + 1);
2460 gboolean skip = FALSE;
2462 method = mono_get_method (acfg->image, token, NULL);
2464 if ((method->flags & METHOD_ATTRIBUTE_PINVOKE_IMPL) ||
2465 (method->iflags & METHOD_IMPL_ATTRIBUTE_RUNTIME) ||
2466 (method->flags & METHOD_ATTRIBUTE_ABSTRACT))
2467 skip = TRUE;
2469 if (method->is_generic || method->klass->generic_container)
2470 skip = TRUE;
2472 /* Skip methods which can not be handled by get_runtime_invoke () */
2473 sig = mono_method_signature (method);
2474 if (!sig)
2475 continue;
2476 if ((sig->ret->type == MONO_TYPE_PTR) ||
2477 (sig->ret->type == MONO_TYPE_TYPEDBYREF))
2478 skip = TRUE;
2480 for (j = 0; j < sig->param_count; j++) {
2481 if (sig->params [j]->type == MONO_TYPE_TYPEDBYREF)
2482 skip = TRUE;
2485 #ifdef MONO_ARCH_DYN_CALL_SUPPORTED
2486 if (!method->klass->contextbound) {
2487 MonoDynCallInfo *info = mono_arch_dyn_call_prepare (sig);
2488 gboolean has_nullable = FALSE;
2490 for (j = 0; j < sig->param_count; j++) {
2491 if (sig->params [j]->type == MONO_TYPE_GENERICINST && mono_class_is_nullable (mono_class_from_mono_type (sig->params [j])))
2492 has_nullable = TRUE;
2495 if (info && !has_nullable) {
2496 /* Supported by the dynamic runtime-invoke wrapper */
2497 skip = TRUE;
2498 g_free (info);
2501 #endif
2503 if (!skip) {
2504 //printf ("%s\n", mono_method_full_name (method, TRUE));
2505 add_method (acfg, mono_marshal_get_runtime_invoke (method, FALSE));
2509 if (strcmp (acfg->image->assembly->aname.name, "mscorlib") == 0) {
2510 #ifdef MONO_ARCH_HAVE_TLS_GET
2511 MonoMethodDesc *desc;
2512 MonoMethod *orig_method;
2513 int nallocators;
2514 #endif
2516 /* Runtime invoke wrappers */
2518 /* void runtime-invoke () [.cctor] */
2519 csig = mono_metadata_signature_alloc (mono_defaults.corlib, 0);
2520 csig->ret = &mono_defaults.void_class->byval_arg;
2521 add_method (acfg, get_runtime_invoke_sig (csig));
2523 /* void runtime-invoke () [Finalize] */
2524 csig = mono_metadata_signature_alloc (mono_defaults.corlib, 0);
2525 csig->hasthis = 1;
2526 csig->ret = &mono_defaults.void_class->byval_arg;
2527 add_method (acfg, get_runtime_invoke_sig (csig));
2529 /* void runtime-invoke (string) [exception ctor] */
2530 csig = mono_metadata_signature_alloc (mono_defaults.corlib, 1);
2531 csig->hasthis = 1;
2532 csig->ret = &mono_defaults.void_class->byval_arg;
2533 csig->params [0] = &mono_defaults.string_class->byval_arg;
2534 add_method (acfg, get_runtime_invoke_sig (csig));
2536 /* void runtime-invoke (string, string) [exception ctor] */
2537 csig = mono_metadata_signature_alloc (mono_defaults.corlib, 2);
2538 csig->hasthis = 1;
2539 csig->ret = &mono_defaults.void_class->byval_arg;
2540 csig->params [0] = &mono_defaults.string_class->byval_arg;
2541 csig->params [1] = &mono_defaults.string_class->byval_arg;
2542 add_method (acfg, get_runtime_invoke_sig (csig));
2544 /* string runtime-invoke () [Exception.ToString ()] */
2545 csig = mono_metadata_signature_alloc (mono_defaults.corlib, 0);
2546 csig->hasthis = 1;
2547 csig->ret = &mono_defaults.string_class->byval_arg;
2548 add_method (acfg, get_runtime_invoke_sig (csig));
2550 /* void runtime-invoke (string, Exception) [exception ctor] */
2551 csig = mono_metadata_signature_alloc (mono_defaults.corlib, 2);
2552 csig->hasthis = 1;
2553 csig->ret = &mono_defaults.void_class->byval_arg;
2554 csig->params [0] = &mono_defaults.string_class->byval_arg;
2555 csig->params [1] = &mono_defaults.exception_class->byval_arg;
2556 add_method (acfg, get_runtime_invoke_sig (csig));
2558 /* Assembly runtime-invoke (string, bool) [DoAssemblyResolve] */
2559 csig = mono_metadata_signature_alloc (mono_defaults.corlib, 2);
2560 csig->hasthis = 1;
2561 csig->ret = &(mono_class_from_name (
2562 mono_defaults.corlib, "System.Reflection", "Assembly"))->byval_arg;
2563 csig->params [0] = &mono_defaults.string_class->byval_arg;
2564 csig->params [1] = &mono_defaults.boolean_class->byval_arg;
2565 add_method (acfg, get_runtime_invoke_sig (csig));
2567 /* runtime-invoke used by finalizers */
2568 add_method (acfg, mono_marshal_get_runtime_invoke (mono_class_get_method_from_name_flags (mono_defaults.object_class, "Finalize", 0, 0), TRUE));
2570 /* This is used by mono_runtime_capture_context () */
2571 method = mono_get_context_capture_method ();
2572 if (method)
2573 add_method (acfg, mono_marshal_get_runtime_invoke (method, FALSE));
2575 #ifdef MONO_ARCH_DYN_CALL_SUPPORTED
2576 add_method (acfg, mono_marshal_get_runtime_invoke_dynamic ());
2577 #endif
2579 /* JIT icall wrappers */
2580 /* FIXME: locking */
2581 g_hash_table_foreach (mono_get_jit_icall_info (), add_jit_icall_wrapper, acfg);
2583 /* stelemref */
2584 add_method (acfg, mono_marshal_get_stelemref ());
2586 #ifdef MONO_ARCH_HAVE_TLS_GET
2587 /* Managed Allocators */
2588 nallocators = mono_gc_get_managed_allocator_types ();
2589 for (i = 0; i < nallocators; ++i) {
2590 m = mono_gc_get_managed_allocator_by_type (i);
2591 if (m)
2592 add_method (acfg, m);
2595 /* Monitor Enter/Exit */
2596 desc = mono_method_desc_new ("Monitor:Enter", FALSE);
2597 orig_method = mono_method_desc_search_in_class (desc, mono_defaults.monitor_class);
2598 g_assert (orig_method);
2599 mono_method_desc_free (desc);
2600 method = mono_monitor_get_fast_path (orig_method);
2601 if (method)
2602 add_method (acfg, method);
2604 desc = mono_method_desc_new ("Monitor:Exit", FALSE);
2605 orig_method = mono_method_desc_search_in_class (desc, mono_defaults.monitor_class);
2606 g_assert (orig_method);
2607 mono_method_desc_free (desc);
2608 method = mono_monitor_get_fast_path (orig_method);
2609 if (method)
2610 add_method (acfg, method);
2611 #endif
2613 /* Stelemref wrappers */
2614 /* There is only a constant number of these, iterating over all types should handle them all */
2615 for (i = 0; i < acfg->image->tables [MONO_TABLE_TYPEDEF].rows; ++i) {
2616 MonoClass *klass;
2618 token = MONO_TOKEN_TYPE_DEF | (i + 1);
2619 klass = mono_class_get (acfg->image, token);
2620 if (klass)
2621 add_method (acfg, mono_marshal_get_virtual_stelemref (mono_array_class_get (klass, 1)));
2622 else
2623 mono_loader_clear_error ();
2626 /* castclass_with_check wrapper */
2627 add_method (acfg, mono_marshal_get_castclass_with_cache ());
2628 /* isinst_with_check wrapper */
2629 add_method (acfg, mono_marshal_get_isinst_with_cache ());
2633 * remoting-invoke-with-check wrappers are very frequent, so avoid emitting them,
2634 * we use the original method instead at runtime.
2635 * Since full-aot doesn't support remoting, this is not a problem.
2637 #if 0
2638 /* remoting-invoke wrappers */
2639 for (i = 0; i < acfg->image->tables [MONO_TABLE_METHOD].rows; ++i) {
2640 MonoMethodSignature *sig;
2642 token = MONO_TOKEN_METHOD_DEF | (i + 1);
2643 method = mono_get_method (acfg->image, token, NULL);
2645 sig = mono_method_signature (method);
2647 if (sig->hasthis && (method->klass->marshalbyref || method->klass == mono_defaults.object_class)) {
2648 m = mono_marshal_get_remoting_invoke_with_check (method);
2650 add_method (acfg, m);
2653 #endif
2655 /* delegate-invoke wrappers */
2656 for (i = 0; i < acfg->image->tables [MONO_TABLE_TYPEDEF].rows; ++i) {
2657 MonoClass *klass;
2659 token = MONO_TOKEN_TYPE_DEF | (i + 1);
2660 klass = mono_class_get (acfg->image, token);
2662 if (!klass) {
2663 mono_loader_clear_error ();
2664 continue;
2667 if (klass->delegate && klass != mono_defaults.delegate_class && klass != mono_defaults.multicastdelegate_class && !klass->generic_container) {
2668 method = mono_get_delegate_invoke (klass);
2670 m = mono_marshal_get_delegate_invoke (method, NULL);
2672 add_method (acfg, m);
2674 method = mono_class_get_method_from_name_flags (klass, "BeginInvoke", -1, 0);
2675 add_method (acfg, mono_marshal_get_delegate_begin_invoke (method));
2677 method = mono_class_get_method_from_name_flags (klass, "EndInvoke", -1, 0);
2678 add_method (acfg, mono_marshal_get_delegate_end_invoke (method));
2682 /* Synchronized wrappers */
2683 for (i = 0; i < acfg->image->tables [MONO_TABLE_METHOD].rows; ++i) {
2684 token = MONO_TOKEN_METHOD_DEF | (i + 1);
2685 method = mono_get_method (acfg->image, token, NULL);
2687 if (method->iflags & METHOD_IMPL_ATTRIBUTE_SYNCHRONIZED && !method->is_generic)
2688 add_method (acfg, mono_marshal_get_synchronized_wrapper (method));
2691 /* pinvoke wrappers */
2692 for (i = 0; i < acfg->image->tables [MONO_TABLE_METHOD].rows; ++i) {
2693 MonoMethod *method;
2694 guint32 token = MONO_TOKEN_METHOD_DEF | (i + 1);
2696 method = mono_get_method (acfg->image, token, NULL);
2698 if ((method->flags & METHOD_ATTRIBUTE_PINVOKE_IMPL) ||
2699 (method->iflags & METHOD_IMPL_ATTRIBUTE_INTERNAL_CALL)) {
2700 add_method (acfg, mono_marshal_get_native_wrapper (method, TRUE, TRUE));
2704 /* native-to-managed wrappers */
2705 for (i = 0; i < acfg->image->tables [MONO_TABLE_METHOD].rows; ++i) {
2706 MonoMethod *method;
2707 guint32 token = MONO_TOKEN_METHOD_DEF | (i + 1);
2708 MonoCustomAttrInfo *cattr;
2709 int j;
2711 method = mono_get_method (acfg->image, token, NULL);
2714 * Only generate native-to-managed wrappers for methods which have an
2715 * attribute named MonoPInvokeCallbackAttribute. We search for the attribute by
2716 * name to avoid defining a new assembly to contain it.
2718 cattr = mono_custom_attrs_from_method (method);
2720 if (cattr) {
2721 for (j = 0; j < cattr->num_attrs; ++j)
2722 if (cattr->attrs [j].ctor && !strcmp (cattr->attrs [j].ctor->klass->name, "MonoPInvokeCallbackAttribute"))
2723 break;
2724 if (j < cattr->num_attrs) {
2725 MonoCustomAttrEntry *e = &cattr->attrs [j];
2726 MonoMethodSignature *sig = mono_method_signature (e->ctor);
2727 const char *p = (const char*)e->data;
2728 int slen;
2729 char *n;
2730 MonoType *t;
2731 MonoClass *klass;
2733 g_assert (method->flags & METHOD_ATTRIBUTE_STATIC);
2735 g_assert (sig->param_count == 1);
2736 g_assert (sig->params [0]->type == MONO_TYPE_CLASS && !strcmp (mono_class_from_mono_type (sig->params [0])->name, "Type"));
2739 * Decode the cattr manually since we can't create objects
2740 * during aot compilation.
2743 /* Skip prolog */
2744 p += 2;
2746 /* From load_cattr_value () in reflection.c */
2747 slen = mono_metadata_decode_value (p, &p);
2748 n = g_memdup (p, slen + 1);
2749 n [slen] = 0;
2750 t = mono_reflection_type_from_name (n, acfg->image);
2751 g_assert (t);
2752 g_free (n);
2754 klass = mono_class_from_mono_type (t);
2755 g_assert (klass->parent == mono_defaults.multicastdelegate_class);
2757 add_method (acfg, mono_marshal_get_managed_wrapper (method, klass, 0));
2761 if ((method->flags & METHOD_ATTRIBUTE_PINVOKE_IMPL) ||
2762 (method->iflags & METHOD_IMPL_ATTRIBUTE_INTERNAL_CALL)) {
2763 add_method (acfg, mono_marshal_get_native_wrapper (method, TRUE, TRUE));
2767 /* StructureToPtr/PtrToStructure wrappers */
2768 for (i = 0; i < acfg->image->tables [MONO_TABLE_TYPEDEF].rows; ++i) {
2769 MonoClass *klass;
2771 token = MONO_TOKEN_TYPE_DEF | (i + 1);
2772 klass = mono_class_get (acfg->image, token);
2774 if (!klass) {
2775 mono_loader_clear_error ();
2776 continue;
2779 if (klass->valuetype && !klass->generic_container && can_marshal_struct (klass)) {
2780 add_method (acfg, mono_marshal_get_struct_to_ptr (klass));
2781 add_method (acfg, mono_marshal_get_ptr_to_struct (klass));
2786 static gboolean
2787 has_type_vars (MonoClass *klass)
2789 if ((klass->byval_arg.type == MONO_TYPE_VAR) || (klass->byval_arg.type == MONO_TYPE_MVAR))
2790 return TRUE;
2791 if (klass->rank)
2792 return has_type_vars (klass->element_class);
2793 if (klass->generic_class) {
2794 MonoGenericContext *context = &klass->generic_class->context;
2795 if (context->class_inst) {
2796 int i;
2798 for (i = 0; i < context->class_inst->type_argc; ++i)
2799 if (has_type_vars (mono_class_from_mono_type (context->class_inst->type_argv [i])))
2800 return TRUE;
2803 return FALSE;
2806 static gboolean
2807 method_has_type_vars (MonoMethod *method)
2809 if (has_type_vars (method->klass))
2810 return TRUE;
2812 if (method->is_inflated) {
2813 MonoGenericContext *context = mono_method_get_context (method);
2814 if (context->method_inst) {
2815 int i;
2817 for (i = 0; i < context->method_inst->type_argc; ++i)
2818 if (has_type_vars (mono_class_from_mono_type (context->method_inst->type_argv [i])))
2819 return TRUE;
2822 return FALSE;
2825 static void add_generic_class_with_depth (MonoAotCompile *acfg, MonoClass *klass, int depth);
2827 static void
2828 add_generic_class (MonoAotCompile *acfg, MonoClass *klass, gboolean force)
2830 /* This might lead to a huge code blowup so only do it if neccesary */
2831 if (!acfg->aot_opts.full_aot && !force)
2832 return;
2834 add_generic_class_with_depth (acfg, klass, 0);
2837 static gboolean
2838 check_type_depth (MonoType *t, int depth)
2840 int i;
2842 if (depth > 8)
2843 return TRUE;
2845 switch (t->type) {
2846 case MONO_TYPE_GENERICINST: {
2847 MonoGenericClass *gklass = t->data.generic_class;
2848 MonoGenericInst *ginst = gklass->context.class_inst;
2850 if (ginst) {
2851 for (i = 0; i < ginst->type_argc; ++i) {
2852 if (check_type_depth (ginst->type_argv [i], depth + 1))
2853 return TRUE;
2856 break;
2858 default:
2859 break;
2862 return FALSE;
2866 * add_generic_class:
2868 * Add all methods of a generic class.
2870 static void
2871 add_generic_class_with_depth (MonoAotCompile *acfg, MonoClass *klass, int depth)
2873 MonoMethod *method;
2874 gpointer iter;
2876 mono_class_init (klass);
2878 if (klass->generic_class && klass->generic_class->context.class_inst->is_open)
2879 return;
2881 if (has_type_vars (klass))
2882 return;
2884 if (!klass->generic_class && !klass->rank)
2885 return;
2887 if (check_type_depth (&klass->byval_arg, 0))
2888 return;
2890 iter = NULL;
2891 while ((method = mono_class_get_methods (klass, &iter))) {
2892 if (mono_method_is_generic_sharable_impl_full (method, FALSE, FALSE))
2893 /* Already added */
2894 continue;
2896 if (method->is_generic)
2897 /* FIXME: */
2898 continue;
2901 * FIXME: Instances which are referenced by these methods are not added,
2902 * for example Array.Resize<int> for List<int>.Add ().
2904 add_extra_method_with_depth (acfg, method, depth + 1);
2907 if (klass->delegate) {
2908 method = mono_get_delegate_invoke (klass);
2910 method = mono_marshal_get_delegate_invoke (method, NULL);
2912 add_method (acfg, method);
2916 * For ICollection<T>, add instances of the helper methods
2917 * in Array, since a T[] could be cast to ICollection<T>.
2919 if (klass->image == mono_defaults.corlib && !strcmp (klass->name_space, "System.Collections.Generic") &&
2920 (!strcmp(klass->name, "ICollection`1") || !strcmp (klass->name, "IEnumerable`1") || !strcmp (klass->name, "IList`1") || !strcmp (klass->name, "IEnumerator`1"))) {
2921 MonoClass *tclass = mono_class_from_mono_type (klass->generic_class->context.class_inst->type_argv [0]);
2922 MonoClass *array_class = mono_bounded_array_class_get (tclass, 1, FALSE);
2923 gpointer iter;
2924 char *name_prefix;
2926 if (!strcmp (klass->name, "IEnumerator`1"))
2927 name_prefix = g_strdup_printf ("%s.%s", klass->name_space, "IEnumerable`1");
2928 else
2929 name_prefix = g_strdup_printf ("%s.%s", klass->name_space, klass->name);
2931 /* Add the T[]/InternalEnumerator class */
2932 if (!strcmp (klass->name, "IEnumerable`1") || !strcmp (klass->name, "IEnumerator`1")) {
2933 MonoClass *nclass;
2935 iter = NULL;
2936 while ((nclass = mono_class_get_nested_types (array_class->parent, &iter))) {
2937 if (!strcmp (nclass->name, "InternalEnumerator`1"))
2938 break;
2940 g_assert (nclass);
2941 nclass = mono_class_inflate_generic_class (nclass, mono_generic_class_get_context (klass->generic_class));
2942 add_generic_class (acfg, nclass, FALSE);
2945 iter = NULL;
2946 while ((method = mono_class_get_methods (array_class, &iter))) {
2947 if (strstr (method->name, name_prefix)) {
2948 MonoMethod *m = mono_aot_get_array_helper_from_wrapper (method);
2949 add_extra_method_with_depth (acfg, m, depth);
2953 g_free (name_prefix);
2956 /* Add an instance of GenericComparer<T> which is created dynamically by Comparer<T> */
2957 if (klass->image == mono_defaults.corlib && !strcmp (klass->name_space, "System.Collections.Generic") && !strcmp (klass->name, "Comparer`1")) {
2958 MonoClass *tclass = mono_class_from_mono_type (klass->generic_class->context.class_inst->type_argv [0]);
2959 MonoClass *icomparable, *gcomparer;
2960 MonoGenericContext ctx;
2961 MonoType *args [16];
2963 memset (&ctx, 0, sizeof (ctx));
2965 icomparable = mono_class_from_name (mono_defaults.corlib, "System", "IComparable`1");
2966 g_assert (icomparable);
2967 args [0] = &tclass->byval_arg;
2968 ctx.class_inst = mono_metadata_get_generic_inst (1, args);
2970 if (mono_class_is_assignable_from (mono_class_inflate_generic_class (icomparable, &ctx), tclass)) {
2971 gcomparer = mono_class_from_name (mono_defaults.corlib, "System.Collections.Generic", "GenericComparer`1");
2972 g_assert (gcomparer);
2973 add_generic_class (acfg, mono_class_inflate_generic_class (gcomparer, &ctx), FALSE);
2977 /* Add an instance of GenericEqualityComparer<T> which is created dynamically by EqualityComparer<T> */
2978 if (klass->image == mono_defaults.corlib && !strcmp (klass->name_space, "System.Collections.Generic") && !strcmp (klass->name, "EqualityComparer`1")) {
2979 MonoClass *tclass = mono_class_from_mono_type (klass->generic_class->context.class_inst->type_argv [0]);
2980 MonoClass *iface, *gcomparer;
2981 MonoGenericContext ctx;
2982 MonoType *args [16];
2984 memset (&ctx, 0, sizeof (ctx));
2986 iface = mono_class_from_name (mono_defaults.corlib, "System", "IEquatable`1");
2987 g_assert (iface);
2988 args [0] = &tclass->byval_arg;
2989 ctx.class_inst = mono_metadata_get_generic_inst (1, args);
2991 if (mono_class_is_assignable_from (mono_class_inflate_generic_class (iface, &ctx), tclass)) {
2992 gcomparer = mono_class_from_name (mono_defaults.corlib, "System.Collections.Generic", "GenericEqualityComparer`1");
2993 g_assert (gcomparer);
2994 add_generic_class (acfg, mono_class_inflate_generic_class (gcomparer, &ctx), FALSE);
2999 static void
3000 add_instances_of (MonoAotCompile *acfg, MonoClass *klass, MonoType **insts, int ninsts, gboolean force)
3002 int i;
3003 MonoGenericContext ctx;
3004 MonoType *args [16];
3006 memset (&ctx, 0, sizeof (ctx));
3008 for (i = 0; i < ninsts; ++i) {
3009 args [0] = insts [i];
3010 ctx.class_inst = mono_metadata_get_generic_inst (1, args);
3011 add_generic_class (acfg, mono_class_inflate_generic_class (klass, &ctx), force);
3016 * add_generic_instances:
3018 * Add instances referenced by the METHODSPEC/TYPESPEC table.
3020 static void
3021 add_generic_instances (MonoAotCompile *acfg)
3023 int i;
3024 guint32 token;
3025 MonoMethod *method;
3026 MonoMethodHeader *header;
3027 MonoMethodSignature *sig;
3028 MonoGenericContext *context;
3030 for (i = 0; i < acfg->image->tables [MONO_TABLE_METHODSPEC].rows; ++i) {
3031 token = MONO_TOKEN_METHOD_SPEC | (i + 1);
3032 method = mono_get_method (acfg->image, token, NULL);
3034 if (!method)
3035 continue;
3037 if (method->klass->image != acfg->image)
3038 continue;
3040 context = mono_method_get_context (method);
3042 if (context && ((context->class_inst && context->class_inst->is_open)))
3043 continue;
3046 * For open methods, create an instantiation which can be passed to the JIT.
3047 * FIXME: Handle class_inst as well.
3049 if (context && context->method_inst && context->method_inst->is_open) {
3050 MonoGenericContext shared_context;
3051 MonoGenericInst *inst;
3052 MonoType **type_argv;
3053 int i;
3054 MonoMethod *declaring_method;
3055 gboolean supported = TRUE;
3057 /* Check that the context doesn't contain open constructed types */
3058 if (context->class_inst) {
3059 inst = context->class_inst;
3060 for (i = 0; i < inst->type_argc; ++i) {
3061 if (MONO_TYPE_IS_REFERENCE (inst->type_argv [i]) || inst->type_argv [i]->type == MONO_TYPE_VAR || inst->type_argv [i]->type == MONO_TYPE_MVAR)
3062 continue;
3063 if (mono_class_is_open_constructed_type (inst->type_argv [i]))
3064 supported = FALSE;
3067 if (context->method_inst) {
3068 inst = context->method_inst;
3069 for (i = 0; i < inst->type_argc; ++i) {
3070 if (MONO_TYPE_IS_REFERENCE (inst->type_argv [i]) || inst->type_argv [i]->type == MONO_TYPE_VAR || inst->type_argv [i]->type == MONO_TYPE_MVAR)
3071 continue;
3072 if (mono_class_is_open_constructed_type (inst->type_argv [i]))
3073 supported = FALSE;
3077 if (!supported)
3078 continue;
3080 memset (&shared_context, 0, sizeof (MonoGenericContext));
3082 inst = context->class_inst;
3083 if (inst) {
3084 type_argv = g_new0 (MonoType*, inst->type_argc);
3085 for (i = 0; i < inst->type_argc; ++i) {
3086 if (MONO_TYPE_IS_REFERENCE (inst->type_argv [i]) || inst->type_argv [i]->type == MONO_TYPE_VAR || inst->type_argv [i]->type == MONO_TYPE_MVAR)
3087 type_argv [i] = &mono_defaults.object_class->byval_arg;
3088 else
3089 type_argv [i] = inst->type_argv [i];
3092 shared_context.class_inst = mono_metadata_get_generic_inst (inst->type_argc, type_argv);
3093 g_free (type_argv);
3096 inst = context->method_inst;
3097 if (inst) {
3098 type_argv = g_new0 (MonoType*, inst->type_argc);
3099 for (i = 0; i < inst->type_argc; ++i) {
3100 if (MONO_TYPE_IS_REFERENCE (inst->type_argv [i]) || inst->type_argv [i]->type == MONO_TYPE_VAR || inst->type_argv [i]->type == MONO_TYPE_MVAR)
3101 type_argv [i] = &mono_defaults.object_class->byval_arg;
3102 else
3103 type_argv [i] = inst->type_argv [i];
3106 shared_context.method_inst = mono_metadata_get_generic_inst (inst->type_argc, type_argv);
3107 g_free (type_argv);
3110 if (method->is_generic || method->klass->generic_container)
3111 declaring_method = method;
3112 else
3113 declaring_method = mono_method_get_declaring_generic_method (method);
3115 method = mono_class_inflate_generic_method (declaring_method, &shared_context);
3119 * If the method is fully sharable, it was already added in place of its
3120 * generic definition.
3122 if (mono_method_is_generic_sharable_impl_full (method, FALSE, FALSE))
3123 continue;
3126 * FIXME: Partially shared methods are not shared here, so we end up with
3127 * many identical methods.
3129 add_extra_method (acfg, method);
3132 for (i = 0; i < acfg->image->tables [MONO_TABLE_TYPESPEC].rows; ++i) {
3133 MonoClass *klass;
3135 token = MONO_TOKEN_TYPE_SPEC | (i + 1);
3137 klass = mono_class_get (acfg->image, token);
3138 if (!klass || klass->rank) {
3139 mono_loader_clear_error ();
3140 continue;
3143 add_generic_class (acfg, klass, FALSE);
3146 /* Add types of args/locals */
3147 for (i = 0; i < acfg->methods->len; ++i) {
3148 int j, depth;
3150 method = g_ptr_array_index (acfg->methods, i);
3152 depth = GPOINTER_TO_UINT (g_hash_table_lookup (acfg->method_depth, method));
3154 sig = mono_method_signature (method);
3156 if (sig) {
3157 for (j = 0; j < sig->param_count; ++j)
3158 if (sig->params [j]->type == MONO_TYPE_GENERICINST)
3159 add_generic_class_with_depth (acfg, mono_class_from_mono_type (sig->params [j]), depth + 1);
3162 header = mono_method_get_header (method);
3164 if (header) {
3165 for (j = 0; j < header->num_locals; ++j)
3166 if (header->locals [j]->type == MONO_TYPE_GENERICINST)
3167 add_generic_class_with_depth (acfg, mono_class_from_mono_type (header->locals [j]), depth + 1);
3171 if (acfg->image == mono_defaults.corlib) {
3172 MonoClass *klass;
3173 MonoType *insts [256];
3174 int ninsts = 0;
3176 insts [ninsts ++] = &mono_defaults.byte_class->byval_arg;
3177 insts [ninsts ++] = &mono_defaults.sbyte_class->byval_arg;
3178 insts [ninsts ++] = &mono_defaults.int16_class->byval_arg;
3179 insts [ninsts ++] = &mono_defaults.uint16_class->byval_arg;
3180 insts [ninsts ++] = &mono_defaults.int32_class->byval_arg;
3181 insts [ninsts ++] = &mono_defaults.uint32_class->byval_arg;
3182 insts [ninsts ++] = &mono_defaults.int64_class->byval_arg;
3183 insts [ninsts ++] = &mono_defaults.uint64_class->byval_arg;
3184 insts [ninsts ++] = &mono_defaults.single_class->byval_arg;
3185 insts [ninsts ++] = &mono_defaults.double_class->byval_arg;
3186 insts [ninsts ++] = &mono_defaults.char_class->byval_arg;
3187 insts [ninsts ++] = &mono_defaults.boolean_class->byval_arg;
3189 /* Add GenericComparer<T> instances for primitive types for Enum.ToString () */
3190 klass = mono_class_from_name (acfg->image, "System.Collections.Generic", "GenericComparer`1");
3191 if (klass)
3192 add_instances_of (acfg, klass, insts, ninsts, TRUE);
3193 klass = mono_class_from_name (acfg->image, "System.Collections.Generic", "GenericEqualityComparer`1");
3194 if (klass)
3195 add_instances_of (acfg, klass, insts, ninsts, TRUE);
3197 /* Add instances of the array generic interfaces for primitive types */
3198 /* This will add instances of the InternalArray_ helper methods in Array too */
3199 klass = mono_class_from_name (acfg->image, "System.Collections.Generic", "ICollection`1");
3200 if (klass)
3201 add_instances_of (acfg, klass, insts, ninsts, TRUE);
3202 klass = mono_class_from_name (acfg->image, "System.Collections.Generic", "IList`1");
3203 if (klass)
3204 add_instances_of (acfg, klass, insts, ninsts, TRUE);
3205 klass = mono_class_from_name (acfg->image, "System.Collections.Generic", "IEnumerable`1");
3206 if (klass)
3207 add_instances_of (acfg, klass, insts, ninsts, TRUE);
3210 * Add a managed-to-native wrapper of Array.GetGenericValueImpl<object>, which is
3211 * used for all instances of GetGenericValueImpl by the AOT runtime.
3214 MonoGenericContext ctx;
3215 MonoType *args [16];
3216 MonoMethod *get_method;
3217 MonoClass *array_klass = mono_array_class_get (mono_defaults.object_class, 1)->parent;
3219 get_method = mono_class_get_method_from_name (array_klass, "GetGenericValueImpl", 2);
3221 if (get_method) {
3222 memset (&ctx, 0, sizeof (ctx));
3223 args [0] = &mono_defaults.object_class->byval_arg;
3224 ctx.method_inst = mono_metadata_get_generic_inst (1, args);
3225 add_extra_method (acfg, mono_marshal_get_native_wrapper (mono_class_inflate_generic_method (get_method, &ctx), TRUE, TRUE));
3229 /* Same for CompareExchange<T> */
3231 MonoGenericContext ctx;
3232 MonoType *args [16];
3233 MonoMethod *cas_method;
3234 MonoClass *interlocked_klass = mono_class_from_name (mono_defaults.corlib, "System.Threading", "Interlocked");
3235 gpointer iter = NULL;
3237 while ((cas_method = mono_class_get_methods (interlocked_klass, &iter))) {
3238 if (!strcmp (cas_method->name, "CompareExchange") && cas_method->is_generic) {
3239 memset (&ctx, 0, sizeof (ctx));
3240 args [0] = &mono_defaults.object_class->byval_arg;
3241 ctx.method_inst = mono_metadata_get_generic_inst (1, args);
3242 add_extra_method (acfg, mono_marshal_get_native_wrapper (mono_class_inflate_generic_method (cas_method, &ctx), TRUE, TRUE));
3250 * is_direct_callable:
3252 * Return whenever the method identified by JI is directly callable without
3253 * going through the PLT.
3255 static gboolean
3256 is_direct_callable (MonoAotCompile *acfg, MonoMethod *method, MonoJumpInfo *patch_info)
3258 if ((patch_info->type == MONO_PATCH_INFO_METHOD) && (patch_info->data.method->klass->image == acfg->image)) {
3259 MonoCompile *callee_cfg = g_hash_table_lookup (acfg->method_to_cfg, patch_info->data.method);
3260 if (callee_cfg) {
3261 gboolean direct_callable = TRUE;
3263 if (direct_callable && !(!callee_cfg->has_got_slots && (callee_cfg->method->klass->flags & TYPE_ATTRIBUTE_BEFORE_FIELD_INIT)))
3264 direct_callable = FALSE;
3265 if ((callee_cfg->method->iflags & METHOD_IMPL_ATTRIBUTE_SYNCHRONIZED) && (!method || method->wrapper_type != MONO_WRAPPER_SYNCHRONIZED))
3266 // FIXME: Maybe call the wrapper directly ?
3267 direct_callable = FALSE;
3269 if (direct_callable)
3270 return TRUE;
3274 return FALSE;
3278 * emit_and_reloc_code:
3280 * Emit the native code in CODE, handling relocations along the way. If GOT_ONLY
3281 * is true, calls are made through the GOT too. This is used for emitting trampolines
3282 * in full-aot mode, since calls made from trampolines couldn't go through the PLT,
3283 * since trampolines are needed to make PTL work.
3285 static void
3286 emit_and_reloc_code (MonoAotCompile *acfg, MonoMethod *method, guint8 *code, guint32 code_len, MonoJumpInfo *relocs, gboolean got_only)
3288 int i, pindex, start_index, method_index;
3289 GPtrArray *patches;
3290 MonoJumpInfo *patch_info;
3291 MonoMethodHeader *header;
3292 gboolean skip, direct_call;
3293 guint32 got_slot;
3294 char direct_call_target [1024];
3296 if (method) {
3297 header = mono_method_get_header (method);
3299 method_index = get_method_index (acfg, method);
3302 /* Collect and sort relocations */
3303 patches = g_ptr_array_new ();
3304 for (patch_info = relocs; patch_info; patch_info = patch_info->next)
3305 g_ptr_array_add (patches, patch_info);
3306 g_ptr_array_sort (patches, compare_patches);
3308 start_index = 0;
3309 for (i = 0; i < code_len; i++) {
3310 patch_info = NULL;
3311 for (pindex = start_index; pindex < patches->len; ++pindex) {
3312 patch_info = g_ptr_array_index (patches, pindex);
3313 if (patch_info->ip.i >= i)
3314 break;
3317 #ifdef MONO_ARCH_AOT_SUPPORTED
3318 skip = FALSE;
3319 if (patch_info && (patch_info->ip.i == i) && (pindex < patches->len)) {
3320 start_index = pindex;
3322 switch (patch_info->type) {
3323 case MONO_PATCH_INFO_NONE:
3324 break;
3325 case MONO_PATCH_INFO_GOT_OFFSET: {
3326 int code_size;
3328 arch_emit_got_offset (acfg, code + i, &code_size);
3329 i += code_size - 1;
3330 skip = TRUE;
3331 patch_info->type = MONO_PATCH_INFO_NONE;
3332 break;
3334 default: {
3336 * If this patch is a call, try emitting a direct call instead of
3337 * through a PLT entry. This is possible if the called method is in
3338 * the same assembly and requires no initialization.
3340 direct_call = FALSE;
3341 if ((patch_info->type == MONO_PATCH_INFO_METHOD) && (patch_info->data.method->klass->image == acfg->image)) {
3342 if (!got_only && is_direct_callable (acfg, method, patch_info)) {
3343 MonoCompile *callee_cfg = g_hash_table_lookup (acfg->method_to_cfg, patch_info->data.method);
3344 //printf ("DIRECT: %s %s\n", method ? mono_method_full_name (method, TRUE) : "", mono_method_full_name (callee_cfg->method, TRUE));
3345 direct_call = TRUE;
3346 g_assert (strlen (callee_cfg->asm_symbol) < 1000);
3347 sprintf (direct_call_target, "%s", callee_cfg->asm_symbol);
3348 patch_info->type = MONO_PATCH_INFO_NONE;
3349 acfg->stats.direct_calls ++;
3352 acfg->stats.all_calls ++;
3355 if (!got_only && !direct_call) {
3356 MonoPltEntry *plt_entry = get_plt_entry (acfg, patch_info);
3357 if (plt_entry) {
3358 /* This patch has a PLT entry, so we must emit a call to the PLT entry */
3359 direct_call = TRUE;
3360 sprintf (direct_call_target, "%s", plt_entry->symbol);
3362 /* Nullify the patch */
3363 patch_info->type = MONO_PATCH_INFO_NONE;
3364 plt_entry->jit_used = TRUE;
3368 if (direct_call) {
3369 int call_size;
3371 arch_emit_direct_call (acfg, direct_call_target, &call_size);
3372 i += call_size - 1;
3373 } else {
3374 int code_size;
3376 got_slot = get_got_offset (acfg, patch_info);
3378 arch_emit_got_access (acfg, code + i, got_slot, &code_size);
3379 i += code_size - 1;
3381 skip = TRUE;
3385 #endif /* MONO_ARCH_AOT_SUPPORTED */
3387 if (!skip) {
3388 /* Find next patch */
3389 patch_info = NULL;
3390 for (pindex = start_index; pindex < patches->len; ++pindex) {
3391 patch_info = g_ptr_array_index (patches, pindex);
3392 if (patch_info->ip.i >= i)
3393 break;
3396 /* Try to emit multiple bytes at once */
3397 if (pindex < patches->len && patch_info->ip.i > i) {
3398 emit_bytes (acfg, code + i, patch_info->ip.i - i);
3399 i = patch_info->ip.i - 1;
3400 } else {
3401 emit_bytes (acfg, code + i, 1);
3408 * sanitize_symbol:
3410 * Modify SYMBOL so it only includes characters permissible in symbols.
3412 static void
3413 sanitize_symbol (char *symbol)
3415 int i, len = strlen (symbol);
3417 for (i = 0; i < len; ++i)
3418 if (!isalnum (symbol [i]) && (symbol [i] != '_'))
3419 symbol [i] = '_';
3422 static char*
3423 get_debug_sym (MonoMethod *method, const char *prefix, GHashTable *cache)
3425 char *name1, *name2, *cached;
3426 int i, j, len, count;
3428 name1 = mono_method_full_name (method, TRUE);
3429 len = strlen (name1);
3430 name2 = malloc (strlen (prefix) + len + 16);
3431 memcpy (name2, prefix, strlen (prefix));
3432 j = strlen (prefix);
3433 for (i = 0; i < len; ++i) {
3434 if (isalnum (name1 [i])) {
3435 name2 [j ++] = name1 [i];
3436 } else if (name1 [i] == ' ' && name1 [i + 1] == '(' && name1 [i + 2] == ')') {
3437 i += 2;
3438 } else if (name1 [i] == ',' && name1 [i + 1] == ' ') {
3439 name2 [j ++] = '_';
3440 i++;
3441 } else if (name1 [i] == '(' || name1 [i] == ')' || name1 [i] == '>') {
3442 } else
3443 name2 [j ++] = '_';
3445 name2 [j] = '\0';
3447 g_free (name1);
3449 count = 0;
3450 while (g_hash_table_lookup (cache, name2)) {
3451 sprintf (name2 + j, "_%d", count);
3452 count ++;
3455 cached = g_strdup (name2);
3456 g_hash_table_insert (cache, cached, cached);
3458 return name2;
3461 static void
3462 emit_method_code (MonoAotCompile *acfg, MonoCompile *cfg)
3464 MonoMethod *method;
3465 int method_index;
3466 guint8 *code;
3467 char *debug_sym = NULL;
3468 char symbol [128];
3469 int func_alignment = AOT_FUNC_ALIGNMENT;
3470 MonoMethodHeader *header;
3472 method = cfg->orig_method;
3473 code = cfg->native_code;
3474 header = cfg->header;
3476 method_index = get_method_index (acfg, method);
3478 /* Make the labels local */
3479 sprintf (symbol, "%s", cfg->asm_symbol);
3481 emit_section_change (acfg, ".text", 0);
3482 emit_alignment (acfg, func_alignment);
3483 emit_label (acfg, symbol);
3485 if (acfg->aot_opts.write_symbols) {
3487 * Write a C style symbol for every method, this has two uses:
3488 * - it works on platforms where the dwarf debugging info is not
3489 * yet supported.
3490 * - it allows the setting of breakpoints of aot-ed methods.
3492 debug_sym = get_debug_sym (method, "", acfg->method_label_hash);
3494 sprintf (symbol, "%sme_%x", acfg->temp_prefix, method_index);
3495 if (acfg->need_no_dead_strip)
3496 fprintf (acfg->fp, " .no_dead_strip %s\n", debug_sym);
3497 emit_local_symbol (acfg, debug_sym, symbol, TRUE);
3498 emit_label (acfg, debug_sym);
3501 if (cfg->verbose_level > 0)
3502 g_print ("Method %s emitted as %s\n", mono_method_full_name (method, TRUE), symbol);
3504 acfg->stats.code_size += cfg->code_len;
3506 acfg->cfgs [method_index]->got_offset = acfg->got_offset;
3508 emit_and_reloc_code (acfg, method, code, cfg->code_len, cfg->patch_info, FALSE);
3510 emit_line (acfg);
3512 if (acfg->aot_opts.write_symbols) {
3513 emit_symbol_size (acfg, debug_sym, ".");
3514 g_free (debug_sym);
3517 sprintf (symbol, "%sme_%x", acfg->temp_prefix, method_index);
3518 emit_label (acfg, symbol);
3522 * encode_patch:
3524 * Encode PATCH_INFO into its disk representation.
3526 static void
3527 encode_patch (MonoAotCompile *acfg, MonoJumpInfo *patch_info, guint8 *buf, guint8 **endbuf)
3529 guint8 *p = buf;
3531 switch (patch_info->type) {
3532 case MONO_PATCH_INFO_NONE:
3533 break;
3534 case MONO_PATCH_INFO_IMAGE:
3535 encode_value (get_image_index (acfg, patch_info->data.image), p, &p);
3536 break;
3537 case MONO_PATCH_INFO_MSCORLIB_GOT_ADDR:
3538 case MONO_PATCH_INFO_GC_CARD_TABLE_ADDR:
3539 case MONO_PATCH_INFO_CASTCLASS_CACHE:
3540 break;
3541 case MONO_PATCH_INFO_METHOD_REL:
3542 encode_value ((gint)patch_info->data.offset, p, &p);
3543 break;
3544 case MONO_PATCH_INFO_SWITCH: {
3545 gpointer *table = (gpointer *)patch_info->data.table->table;
3546 int k;
3548 encode_value (patch_info->data.table->table_size, p, &p);
3549 for (k = 0; k < patch_info->data.table->table_size; k++)
3550 encode_value ((int)(gssize)table [k], p, &p);
3551 break;
3553 case MONO_PATCH_INFO_METHODCONST:
3554 case MONO_PATCH_INFO_METHOD:
3555 case MONO_PATCH_INFO_METHOD_JUMP:
3556 case MONO_PATCH_INFO_ICALL_ADDR:
3557 case MONO_PATCH_INFO_METHOD_RGCTX:
3558 encode_method_ref (acfg, patch_info->data.method, p, &p);
3559 break;
3560 case MONO_PATCH_INFO_INTERNAL_METHOD:
3561 case MONO_PATCH_INFO_JIT_ICALL_ADDR: {
3562 guint32 len = strlen (patch_info->data.name);
3564 encode_value (len, p, &p);
3566 memcpy (p, patch_info->data.name, len);
3567 p += len;
3568 *p++ = '\0';
3569 break;
3571 case MONO_PATCH_INFO_LDSTR: {
3572 guint32 image_index = get_image_index (acfg, patch_info->data.token->image);
3573 guint32 token = patch_info->data.token->token;
3574 g_assert (mono_metadata_token_code (token) == MONO_TOKEN_STRING);
3575 encode_value (image_index, p, &p);
3576 encode_value (patch_info->data.token->token - MONO_TOKEN_STRING, p, &p);
3577 break;
3579 case MONO_PATCH_INFO_RVA:
3580 case MONO_PATCH_INFO_DECLSEC:
3581 case MONO_PATCH_INFO_LDTOKEN:
3582 case MONO_PATCH_INFO_TYPE_FROM_HANDLE:
3583 encode_value (get_image_index (acfg, patch_info->data.token->image), p, &p);
3584 encode_value (patch_info->data.token->token, p, &p);
3585 encode_value (patch_info->data.token->has_context, p, &p);
3586 if (patch_info->data.token->has_context)
3587 encode_generic_context (acfg, &patch_info->data.token->context, p, &p);
3588 break;
3589 case MONO_PATCH_INFO_EXC_NAME: {
3590 MonoClass *ex_class;
3592 ex_class =
3593 mono_class_from_name (mono_defaults.exception_class->image,
3594 "System", patch_info->data.target);
3595 g_assert (ex_class);
3596 encode_klass_ref (acfg, ex_class, p, &p);
3597 break;
3599 case MONO_PATCH_INFO_R4:
3600 encode_value (*((guint32 *)patch_info->data.target), p, &p);
3601 break;
3602 case MONO_PATCH_INFO_R8:
3603 encode_value (((guint32 *)patch_info->data.target) [MINI_LS_WORD_IDX], p, &p);
3604 encode_value (((guint32 *)patch_info->data.target) [MINI_MS_WORD_IDX], p, &p);
3605 break;
3606 case MONO_PATCH_INFO_VTABLE:
3607 case MONO_PATCH_INFO_CLASS:
3608 case MONO_PATCH_INFO_IID:
3609 case MONO_PATCH_INFO_ADJUSTED_IID:
3610 encode_klass_ref (acfg, patch_info->data.klass, p, &p);
3611 break;
3612 case MONO_PATCH_INFO_CLASS_INIT:
3613 case MONO_PATCH_INFO_DELEGATE_TRAMPOLINE:
3614 encode_klass_ref (acfg, patch_info->data.klass, p, &p);
3615 break;
3616 case MONO_PATCH_INFO_FIELD:
3617 case MONO_PATCH_INFO_SFLDA:
3618 encode_field_info (acfg, patch_info->data.field, p, &p);
3619 break;
3620 case MONO_PATCH_INFO_INTERRUPTION_REQUEST_FLAG:
3621 break;
3622 case MONO_PATCH_INFO_RGCTX_FETCH: {
3623 MonoJumpInfoRgctxEntry *entry = patch_info->data.rgctx_entry;
3625 encode_method_ref (acfg, entry->method, p, &p);
3626 encode_value (entry->in_mrgctx, p, &p);
3627 encode_value (entry->info_type, p, &p);
3628 encode_value (entry->data->type, p, &p);
3629 encode_patch (acfg, entry->data, p, &p);
3630 break;
3632 case MONO_PATCH_INFO_GENERIC_CLASS_INIT:
3633 case MONO_PATCH_INFO_MONITOR_ENTER:
3634 case MONO_PATCH_INFO_MONITOR_EXIT:
3635 case MONO_PATCH_INFO_SEQ_POINT_INFO:
3636 break;
3637 case MONO_PATCH_INFO_LLVM_IMT_TRAMPOLINE:
3638 encode_method_ref (acfg, patch_info->data.imt_tramp->method, p, &p);
3639 encode_value (patch_info->data.imt_tramp->vt_offset, p, &p);
3640 break;
3641 default:
3642 g_warning ("unable to handle jump info %d", patch_info->type);
3643 g_assert_not_reached ();
3646 *endbuf = p;
3649 static void
3650 encode_patch_list (MonoAotCompile *acfg, GPtrArray *patches, int n_patches, int first_got_offset, guint8 *buf, guint8 **endbuf)
3652 guint8 *p = buf;
3653 guint32 pindex, offset;
3654 MonoJumpInfo *patch_info;
3656 encode_value (n_patches, p, &p);
3658 for (pindex = 0; pindex < patches->len; ++pindex) {
3659 patch_info = g_ptr_array_index (patches, pindex);
3661 if (patch_info->type == MONO_PATCH_INFO_NONE || patch_info->type == MONO_PATCH_INFO_BB)
3662 /* Nothing to do */
3663 continue;
3665 offset = get_got_offset (acfg, patch_info);
3666 encode_value (offset, p, &p);
3669 *endbuf = p;
3672 static void
3673 emit_method_info (MonoAotCompile *acfg, MonoCompile *cfg)
3675 MonoMethod *method;
3676 GList *l;
3677 int pindex, buf_size, n_patches;
3678 guint8 *code;
3679 GPtrArray *patches;
3680 MonoJumpInfo *patch_info;
3681 MonoMethodHeader *header;
3682 guint32 method_index;
3683 guint8 *p, *buf;
3684 guint32 first_got_offset;
3686 method = cfg->orig_method;
3687 code = cfg->native_code;
3688 header = mono_method_get_header (method);
3690 method_index = get_method_index (acfg, method);
3692 /* Sort relocations */
3693 patches = g_ptr_array_new ();
3694 for (patch_info = cfg->patch_info; patch_info; patch_info = patch_info->next)
3695 g_ptr_array_add (patches, patch_info);
3696 g_ptr_array_sort (patches, compare_patches);
3698 first_got_offset = acfg->cfgs [method_index]->got_offset;
3700 /**********************/
3701 /* Encode method info */
3702 /**********************/
3704 buf_size = (patches->len < 1000) ? 40960 : 40960 + (patches->len * 64);
3705 p = buf = g_malloc (buf_size);
3707 if (mono_class_get_cctor (method->klass))
3708 encode_klass_ref (acfg, method->klass, p, &p);
3709 else
3710 /* Not needed when loading the method */
3711 encode_value (0, p, &p);
3713 /* String table */
3714 if (cfg->opt & MONO_OPT_SHARED) {
3715 encode_value (g_list_length (cfg->ldstr_list), p, &p);
3716 for (l = cfg->ldstr_list; l; l = l->next) {
3717 encode_value ((long)l->data, p, &p);
3720 else
3721 /* Used only in shared mode */
3722 g_assert (!cfg->ldstr_list);
3724 n_patches = 0;
3725 for (pindex = 0; pindex < patches->len; ++pindex) {
3726 patch_info = g_ptr_array_index (patches, pindex);
3728 if ((patch_info->type == MONO_PATCH_INFO_GOT_OFFSET) ||
3729 (patch_info->type == MONO_PATCH_INFO_NONE)) {
3730 patch_info->type = MONO_PATCH_INFO_NONE;
3731 /* Nothing to do */
3732 continue;
3735 if ((patch_info->type == MONO_PATCH_INFO_IMAGE) && (patch_info->data.image == acfg->image)) {
3736 /* Stored in a GOT slot initialized at module load time */
3737 patch_info->type = MONO_PATCH_INFO_NONE;
3738 continue;
3741 if (patch_info->type == MONO_PATCH_INFO_GC_CARD_TABLE_ADDR) {
3742 /* Stored in a GOT slot initialized at module load time */
3743 patch_info->type = MONO_PATCH_INFO_NONE;
3744 continue;
3747 if (is_plt_patch (patch_info)) {
3748 /* Calls are made through the PLT */
3749 patch_info->type = MONO_PATCH_INFO_NONE;
3750 continue;
3753 n_patches ++;
3756 if (n_patches)
3757 g_assert (cfg->has_got_slots);
3759 encode_patch_list (acfg, patches, n_patches, first_got_offset, p, &p);
3761 acfg->stats.info_size += p - buf;
3763 g_assert (p - buf < buf_size);
3765 cfg->method_info_offset = add_to_blob (acfg, buf, p - buf);
3766 g_free (buf);
3769 static guint32
3770 get_unwind_info_offset (MonoAotCompile *acfg, guint8 *encoded, guint32 encoded_len)
3772 guint32 cache_index;
3773 guint32 offset;
3775 /* Reuse the unwind module to canonize and store unwind info entries */
3776 cache_index = mono_cache_unwind_info (encoded, encoded_len);
3778 /* Use +/- 1 to distinguish 0s from missing entries */
3779 offset = GPOINTER_TO_UINT (g_hash_table_lookup (acfg->unwind_info_offsets, GUINT_TO_POINTER (cache_index + 1)));
3780 if (offset)
3781 return offset - 1;
3782 else {
3783 guint8 buf [16];
3784 guint8 *p;
3787 * It would be easier to use assembler symbols, but the caller needs an
3788 * offset now.
3790 offset = acfg->unwind_info_offset;
3791 g_hash_table_insert (acfg->unwind_info_offsets, GUINT_TO_POINTER (cache_index + 1), GUINT_TO_POINTER (offset + 1));
3792 g_ptr_array_add (acfg->unwind_ops, GUINT_TO_POINTER (cache_index));
3794 p = buf;
3795 encode_value (encoded_len, p, &p);
3797 acfg->unwind_info_offset += encoded_len + (p - buf);
3798 return offset;
3802 static void
3803 emit_exception_debug_info (MonoAotCompile *acfg, MonoCompile *cfg)
3805 MonoMethod *method;
3806 int i, k, buf_size, method_index;
3807 guint32 debug_info_size;
3808 guint8 *code;
3809 MonoMethodHeader *header;
3810 guint8 *p, *buf, *debug_info;
3811 MonoJitInfo *jinfo = cfg->jit_info;
3812 guint32 flags;
3813 gboolean use_unwind_ops = FALSE;
3814 MonoSeqPointInfo *seq_points;
3816 method = cfg->orig_method;
3817 code = cfg->native_code;
3818 header = cfg->header;
3820 method_index = get_method_index (acfg, method);
3822 if (!acfg->aot_opts.nodebug) {
3823 mono_debug_serialize_debug_info (cfg, &debug_info, &debug_info_size);
3824 } else {
3825 debug_info = NULL;
3826 debug_info_size = 0;
3829 seq_points = cfg->seq_point_info;
3831 buf_size = header->num_clauses * 256 + debug_info_size + 2048 + (seq_points ? (seq_points->len * 64) : 0) + cfg->gc_map_size;
3832 p = buf = g_malloc (buf_size);
3834 #ifdef MONO_ARCH_HAVE_XP_UNWIND
3835 use_unwind_ops = cfg->unwind_ops != NULL;
3836 #endif
3838 flags = (jinfo->has_generic_jit_info ? 1 : 0) | (use_unwind_ops ? 2 : 0) | (header->num_clauses ? 4 : 0) | (seq_points ? 8 : 0) | (cfg->compile_llvm ? 16 : 0) | (jinfo->has_try_block_holes ? 32 : 0) | (cfg->gc_map ? 64 : 0);
3840 encode_value (flags, p, &p);
3842 if (use_unwind_ops) {
3843 guint32 encoded_len;
3844 guint8 *encoded;
3847 * This is a duplicate of the data in the .debug_frame section, but that
3848 * section cannot be accessed using the dl interface.
3850 encoded = mono_unwind_ops_encode (cfg->unwind_ops, &encoded_len);
3851 encode_value (get_unwind_info_offset (acfg, encoded, encoded_len), p, &p);
3852 g_free (encoded);
3853 } else {
3854 encode_value (jinfo->used_regs, p, &p);
3857 /*Encode the number of holes before the number of clauses to make decoding easier*/
3858 if (jinfo->has_try_block_holes) {
3859 MonoTryBlockHoleTableJitInfo *table = mono_jit_info_get_try_block_hole_table_info (jinfo);
3860 encode_value (table->num_holes, p, &p);
3863 /* Exception table */
3864 if (cfg->compile_llvm) {
3866 * When using LLVM, we can't emit some data, like pc offsets, this reg/offset etc.,
3867 * since the information is only available to llc. Instead, we let llc save the data
3868 * into the LSDA, and read it from there at runtime.
3870 /* The assembly might be CIL stripped so emit the data ourselves */
3871 if (header->num_clauses)
3872 encode_value (header->num_clauses, p, &p);
3874 for (k = 0; k < header->num_clauses; ++k) {
3875 MonoExceptionClause *clause;
3877 clause = &header->clauses [k];
3879 encode_value (clause->flags, p, &p);
3880 if (clause->data.catch_class) {
3881 encode_value (1, p, &p);
3882 encode_klass_ref (acfg, clause->data.catch_class, p, &p);
3883 } else {
3884 encode_value (0, p, &p);
3887 /* Emit a list of nesting clauses */
3888 for (i = 0; i < header->num_clauses; ++i) {
3889 gint32 cindex1 = k;
3890 MonoExceptionClause *clause1 = &header->clauses [cindex1];
3891 gint32 cindex2 = i;
3892 MonoExceptionClause *clause2 = &header->clauses [cindex2];
3894 if (cindex1 != cindex2 && clause1->try_offset >= clause2->try_offset && clause1->handler_offset <= clause2->handler_offset)
3895 encode_value (i, p, &p);
3897 encode_value (-1, p, &p);
3899 } else {
3900 if (jinfo->num_clauses)
3901 encode_value (jinfo->num_clauses, p, &p);
3903 for (k = 0; k < jinfo->num_clauses; ++k) {
3904 MonoJitExceptionInfo *ei = &jinfo->clauses [k];
3906 encode_value (ei->flags, p, &p);
3907 encode_value (ei->exvar_offset, p, &p);
3909 if (ei->flags == MONO_EXCEPTION_CLAUSE_FILTER || ei->flags == MONO_EXCEPTION_CLAUSE_FINALLY)
3910 encode_value ((gint)((guint8*)ei->data.filter - code), p, &p);
3911 else {
3912 if (ei->data.catch_class) {
3913 encode_value (1, p, &p);
3914 encode_klass_ref (acfg, ei->data.catch_class, p, &p);
3915 } else {
3916 encode_value (0, p, &p);
3920 encode_value ((gint)((guint8*)ei->try_start - code), p, &p);
3921 encode_value ((gint)((guint8*)ei->try_end - code), p, &p);
3922 encode_value ((gint)((guint8*)ei->handler_start - code), p, &p);
3926 if (jinfo->has_generic_jit_info) {
3927 MonoGenericJitInfo *gi = mono_jit_info_get_generic_jit_info (jinfo);
3929 if (!cfg->compile_llvm) {
3930 encode_value (gi->has_this ? 1 : 0, p, &p);
3931 encode_value (gi->this_reg, p, &p);
3932 encode_value (gi->this_offset, p, &p);
3936 * Need to encode jinfo->method too, since it is not equal to 'method'
3937 * when using generic sharing.
3939 encode_method_ref (acfg, jinfo->method, p, &p);
3942 if (jinfo->has_try_block_holes) {
3943 MonoTryBlockHoleTableJitInfo *table = mono_jit_info_get_try_block_hole_table_info (jinfo);
3944 for (i = 0; i < table->num_holes; ++i) {
3945 MonoTryBlockHoleJitInfo *hole = &table->holes [i];
3946 encode_value (hole->clause, p, &p);
3947 encode_value (hole->length, p, &p);
3948 encode_value (hole->offset, p, &p);
3952 if (seq_points) {
3953 int il_offset, native_offset, last_il_offset, last_native_offset, j;
3955 encode_value (seq_points->len, p, &p);
3956 last_il_offset = last_native_offset = 0;
3957 for (i = 0; i < seq_points->len; ++i) {
3958 SeqPoint *sp = &seq_points->seq_points [i];
3959 il_offset = sp->il_offset;
3960 native_offset = sp->native_offset;
3961 encode_value (il_offset - last_il_offset, p, &p);
3962 encode_value (native_offset - last_native_offset, p, &p);
3963 last_il_offset = il_offset;
3964 last_native_offset = native_offset;
3966 encode_value (sp->next_len, p, &p);
3967 for (j = 0; j < sp->next_len; ++j)
3968 encode_value (sp->next [j], p, &p);
3972 g_assert (debug_info_size < buf_size);
3974 encode_value (debug_info_size, p, &p);
3975 if (debug_info_size) {
3976 memcpy (p, debug_info, debug_info_size);
3977 p += debug_info_size;
3978 g_free (debug_info);
3981 /* GC Map */
3982 if (cfg->gc_map) {
3983 encode_value (cfg->gc_map_size, p, &p);
3984 /* The GC map requires 4 bytes of alignment */
3985 while ((gsize)p % 4)
3986 p ++;
3987 memcpy (p, cfg->gc_map, cfg->gc_map_size);
3988 p += cfg->gc_map_size;
3991 acfg->stats.ex_info_size += p - buf;
3993 g_assert (p - buf < buf_size);
3995 /* Emit info */
3996 /* The GC Map requires 4 byte alignment */
3997 cfg->ex_info_offset = add_to_blob_aligned (acfg, buf, p - buf, cfg->gc_map ? 4 : 1);
3998 g_free (buf);
4001 static guint32
4002 emit_klass_info (MonoAotCompile *acfg, guint32 token)
4004 MonoClass *klass = mono_class_get (acfg->image, token);
4005 guint8 *p, *buf;
4006 int i, buf_size, res;
4007 gboolean no_special_static, cant_encode;
4008 gpointer iter = NULL;
4010 if (!klass) {
4011 mono_loader_clear_error ();
4013 buf_size = 16;
4015 p = buf = g_malloc (buf_size);
4017 /* Mark as unusable */
4018 encode_value (-1, p, &p);
4020 res = add_to_blob (acfg, buf, p - buf);
4021 g_free (buf);
4023 return res;
4026 buf_size = 10240 + (klass->vtable_size * 16);
4027 p = buf = g_malloc (buf_size);
4029 g_assert (klass);
4031 mono_class_init (klass);
4033 mono_class_get_nested_types (klass, &iter);
4034 g_assert (klass->nested_classes_inited);
4036 mono_class_setup_vtable (klass);
4039 * Emit all the information which is required for creating vtables so
4040 * the runtime does not need to create the MonoMethod structures which
4041 * take up a lot of space.
4044 no_special_static = !mono_class_has_special_static_fields (klass);
4046 /* Check whenever we have enough info to encode the vtable */
4047 cant_encode = FALSE;
4048 for (i = 0; i < klass->vtable_size; ++i) {
4049 MonoMethod *cm = klass->vtable [i];
4051 if (cm && mono_method_signature (cm)->is_inflated && !g_hash_table_lookup (acfg->token_info_hash, cm))
4052 cant_encode = TRUE;
4055 if (klass->generic_container || cant_encode) {
4056 encode_value (-1, p, &p);
4057 } else {
4058 encode_value (klass->vtable_size, p, &p);
4059 encode_value ((klass->generic_container ? (1 << 8) : 0) | (no_special_static << 7) | (klass->has_static_refs << 6) | (klass->has_references << 5) | ((klass->blittable << 4) | ((klass->ext && klass->ext->nested_classes) ? 1 : 0) << 3) | (klass->has_cctor << 2) | (klass->has_finalize << 1) | klass->ghcimpl, p, &p);
4060 if (klass->has_cctor)
4061 encode_method_ref (acfg, mono_class_get_cctor (klass), p, &p);
4062 if (klass->has_finalize)
4063 encode_method_ref (acfg, mono_class_get_finalizer (klass), p, &p);
4065 encode_value (klass->instance_size, p, &p);
4066 encode_value (mono_class_data_size (klass), p, &p);
4067 encode_value (klass->packing_size, p, &p);
4068 encode_value (klass->min_align, p, &p);
4070 for (i = 0; i < klass->vtable_size; ++i) {
4071 MonoMethod *cm = klass->vtable [i];
4073 if (cm)
4074 encode_method_ref (acfg, cm, p, &p);
4075 else
4076 encode_value (0, p, &p);
4080 acfg->stats.class_info_size += p - buf;
4082 g_assert (p - buf < buf_size);
4083 res = add_to_blob (acfg, buf, p - buf);
4084 g_free (buf);
4086 return res;
4089 static char*
4090 get_plt_entry_debug_sym (MonoAotCompile *acfg, MonoJumpInfo *ji, GHashTable *cache)
4092 char *debug_sym = NULL;
4094 switch (ji->type) {
4095 case MONO_PATCH_INFO_METHOD:
4096 debug_sym = get_debug_sym (ji->data.method, "plt_", cache);
4097 break;
4098 case MONO_PATCH_INFO_INTERNAL_METHOD:
4099 debug_sym = g_strdup_printf ("plt__jit_icall_%s", ji->data.name);
4100 break;
4101 case MONO_PATCH_INFO_CLASS_INIT:
4102 debug_sym = g_strdup_printf ("plt__class_init_%s", mono_type_get_name (&ji->data.klass->byval_arg));
4103 sanitize_symbol (debug_sym);
4104 break;
4105 case MONO_PATCH_INFO_RGCTX_FETCH:
4106 debug_sym = g_strdup_printf ("plt__rgctx_fetch_%d", acfg->label_generator ++);
4107 break;
4108 case MONO_PATCH_INFO_ICALL_ADDR: {
4109 char *s = get_debug_sym (ji->data.method, "", cache);
4111 debug_sym = g_strdup_printf ("plt__icall_native_%s", s);
4112 g_free (s);
4113 break;
4115 case MONO_PATCH_INFO_JIT_ICALL_ADDR:
4116 debug_sym = g_strdup_printf ("plt__jit_icall_native_%s", ji->data.name);
4117 break;
4118 case MONO_PATCH_INFO_GENERIC_CLASS_INIT:
4119 debug_sym = g_strdup_printf ("plt__generic_class_init");
4120 break;
4121 default:
4122 break;
4125 return debug_sym;
4129 * Calls made from AOTed code are routed through a table of jumps similar to the
4130 * ELF PLT (Program Linkage Table). Initially the PLT entries jump to code which transfers
4131 * control to the AOT runtime through a trampoline.
4133 static void
4134 emit_plt (MonoAotCompile *acfg)
4136 char symbol [128];
4137 int i;
4138 GHashTable *cache;
4140 cache = g_hash_table_new (g_str_hash, g_str_equal);
4142 emit_line (acfg);
4143 sprintf (symbol, "plt");
4145 emit_section_change (acfg, ".text", 0);
4146 emit_alignment (acfg, NACL_SIZE(16, kNaClAlignment));
4147 emit_label (acfg, symbol);
4148 emit_label (acfg, acfg->plt_symbol);
4150 for (i = 0; i < acfg->plt_offset; ++i) {
4151 char *debug_sym = NULL;
4152 MonoPltEntry *plt_entry = NULL;
4153 MonoJumpInfo *ji;
4155 if (i == 0)
4157 * The first plt entry is unused.
4159 continue;
4161 plt_entry = g_hash_table_lookup (acfg->plt_offset_to_entry, GUINT_TO_POINTER (i));
4162 ji = plt_entry->ji;
4164 if (acfg->llvm) {
4166 * If the target is directly callable, alias the plt symbol to point to
4167 * the method code.
4168 * FIXME: Use this to simplify emit_and_reloc_code ().
4169 * FIXME: Avoid the got slot.
4170 * FIXME: Add support to the binary writer.
4172 if (ji && is_direct_callable (acfg, NULL, ji) && !acfg->use_bin_writer) {
4173 MonoCompile *callee_cfg = g_hash_table_lookup (acfg->method_to_cfg, ji->data.method);
4175 if (acfg->thumb_mixed && !callee_cfg->compile_llvm) {
4176 /* LLVM calls the PLT entries using bl, so emit a stub */
4177 fprintf (acfg->fp, "\n.thumb_func\n");
4178 emit_label (acfg, plt_entry->llvm_symbol);
4179 fprintf (acfg->fp, "bx pc\n");
4180 fprintf (acfg->fp, "nop\n");
4181 fprintf (acfg->fp, ".arm\n");
4182 fprintf (acfg->fp, "b %s\n", callee_cfg->asm_symbol);
4183 } else {
4184 fprintf (acfg->fp, "\n.set %s, %s\n", plt_entry->llvm_symbol, callee_cfg->asm_symbol);
4186 continue;
4190 if (acfg->aot_opts.write_symbols)
4191 plt_entry->debug_sym = get_plt_entry_debug_sym (acfg, ji, cache);
4192 debug_sym = plt_entry->debug_sym;
4194 if (acfg->thumb_mixed && !plt_entry->jit_used)
4195 /* Emit only a thumb version */
4196 continue;
4198 if (!acfg->thumb_mixed)
4199 emit_label (acfg, plt_entry->llvm_symbol);
4201 if (debug_sym) {
4202 if (acfg->need_no_dead_strip)
4203 fprintf (acfg->fp, " .no_dead_strip %s\n", debug_sym);
4204 emit_local_symbol (acfg, debug_sym, NULL, TRUE);
4205 emit_label (acfg, debug_sym);
4208 emit_label (acfg, plt_entry->symbol);
4210 arch_emit_plt_entry (acfg, i);
4212 if (debug_sym)
4213 emit_symbol_size (acfg, debug_sym, ".");
4216 if (acfg->thumb_mixed) {
4217 /* Make sure the ARM symbols don't alias the thumb ones */
4218 emit_zero_bytes (acfg, 16);
4221 * Emit a separate set of PLT entries using thumb2 which is called by LLVM generated
4222 * code.
4224 for (i = 0; i < acfg->plt_offset; ++i) {
4225 char *debug_sym = NULL;
4226 MonoPltEntry *plt_entry = NULL;
4227 MonoJumpInfo *ji;
4229 if (i == 0)
4230 continue;
4232 plt_entry = g_hash_table_lookup (acfg->plt_offset_to_entry, GUINT_TO_POINTER (i));
4233 ji = plt_entry->ji;
4235 if (ji && is_direct_callable (acfg, NULL, ji) && !acfg->use_bin_writer)
4236 continue;
4238 /* Skip plt entries not actually called by LLVM code */
4239 if (!plt_entry->llvm_used)
4240 continue;
4242 if (acfg->aot_opts.write_symbols) {
4243 if (plt_entry->debug_sym)
4244 debug_sym = g_strdup_printf ("%s_thumb", plt_entry->debug_sym);
4247 if (debug_sym) {
4248 #if defined(__APPLE__)
4249 fprintf (acfg->fp, " .thumb_func %s\n", debug_sym);
4250 fprintf (acfg->fp, " .no_dead_strip %s\n", debug_sym);
4251 #endif
4252 emit_local_symbol (acfg, debug_sym, NULL, TRUE);
4253 emit_label (acfg, debug_sym);
4255 fprintf (acfg->fp, "\n.thumb_func\n");
4257 emit_label (acfg, plt_entry->llvm_symbol);
4259 arch_emit_llvm_plt_entry (acfg, i);
4261 if (debug_sym) {
4262 emit_symbol_size (acfg, debug_sym, ".");
4263 g_free (debug_sym);
4268 emit_symbol_size (acfg, acfg->plt_symbol, ".");
4270 sprintf (symbol, "plt_end");
4271 emit_label (acfg, symbol);
4273 g_hash_table_destroy (cache);
4276 static G_GNUC_UNUSED void
4277 emit_trampoline (MonoAotCompile *acfg, int got_offset, MonoTrampInfo *info)
4279 char start_symbol [256];
4280 char symbol [256];
4281 guint32 buf_size, info_offset;
4282 MonoJumpInfo *patch_info;
4283 guint8 *buf, *p;
4284 GPtrArray *patches;
4285 char *name;
4286 guint8 *code;
4287 guint32 code_size;
4288 MonoJumpInfo *ji;
4289 GSList *unwind_ops;
4291 name = info->name;
4292 code = info->code;
4293 code_size = info->code_size;
4294 ji = info->ji;
4295 unwind_ops = info->unwind_ops;
4297 #ifdef __native_client_codegen__
4298 mono_nacl_fix_patches (code, ji);
4299 #endif
4301 /* Emit code */
4303 sprintf (start_symbol, "%s", name);
4305 emit_section_change (acfg, ".text", 0);
4306 emit_global (acfg, start_symbol, TRUE);
4307 emit_alignment (acfg, AOT_FUNC_ALIGNMENT);
4308 emit_label (acfg, start_symbol);
4310 sprintf (symbol, "%snamed_%s", acfg->temp_prefix, name);
4311 emit_label (acfg, symbol);
4314 * The code should access everything through the GOT, so we pass
4315 * TRUE here.
4317 emit_and_reloc_code (acfg, NULL, code, code_size, ji, TRUE);
4319 emit_symbol_size (acfg, start_symbol, ".");
4321 /* Emit info */
4323 /* Sort relocations */
4324 patches = g_ptr_array_new ();
4325 for (patch_info = ji; patch_info; patch_info = patch_info->next)
4326 if (patch_info->type != MONO_PATCH_INFO_NONE)
4327 g_ptr_array_add (patches, patch_info);
4328 g_ptr_array_sort (patches, compare_patches);
4330 buf_size = patches->len * 128 + 128;
4331 buf = g_malloc (buf_size);
4332 p = buf;
4334 encode_patch_list (acfg, patches, patches->len, got_offset, p, &p);
4335 g_assert (p - buf < buf_size);
4337 sprintf (symbol, "%s_p", name);
4339 info_offset = add_to_blob (acfg, buf, p - buf);
4341 emit_section_change (acfg, RODATA_SECT, 0);
4342 emit_global (acfg, symbol, FALSE);
4343 emit_label (acfg, symbol);
4345 emit_int32 (acfg, info_offset);
4347 /* Emit debug info */
4348 if (unwind_ops) {
4349 char symbol2 [256];
4351 sprintf (symbol, "%s", name);
4352 sprintf (symbol2, "%snamed_%s", acfg->temp_prefix, name);
4354 if (acfg->dwarf)
4355 mono_dwarf_writer_emit_trampoline (acfg->dwarf, symbol, symbol2, NULL, NULL, code_size, unwind_ops);
4359 static void
4360 emit_trampolines (MonoAotCompile *acfg)
4362 char symbol [256];
4363 int i, tramp_got_offset;
4364 MonoAotTrampoline ntype;
4365 #ifdef MONO_ARCH_HAVE_FULL_AOT_TRAMPOLINES
4366 int tramp_type;
4367 guint8 *code;
4368 #endif
4370 if (!acfg->aot_opts.full_aot)
4371 return;
4373 g_assert (acfg->image->assembly);
4375 /* Currently, we emit most trampolines into the mscorlib AOT image. */
4376 if (strcmp (acfg->image->assembly->aname.name, "mscorlib") == 0) {
4377 #ifdef MONO_ARCH_HAVE_FULL_AOT_TRAMPOLINES
4378 MonoTrampInfo *info;
4381 * Emit the generic trampolines.
4383 * We could save some code by treating the generic trampolines as a wrapper
4384 * method, but that approach has its own complexities, so we choose the simpler
4385 * method.
4387 for (tramp_type = 0; tramp_type < MONO_TRAMPOLINE_NUM; ++tramp_type) {
4388 mono_arch_create_generic_trampoline (tramp_type, &info, TRUE);
4389 emit_trampoline (acfg, acfg->got_offset, info);
4392 mono_arch_get_nullified_class_init_trampoline (&info);
4393 emit_trampoline (acfg, acfg->got_offset, info);
4394 #if defined(MONO_ARCH_MONITOR_OBJECT_REG)
4395 mono_arch_create_monitor_enter_trampoline (&info, TRUE);
4396 emit_trampoline (acfg, acfg->got_offset, info);
4397 mono_arch_create_monitor_exit_trampoline (&info, TRUE);
4398 emit_trampoline (acfg, acfg->got_offset, info);
4399 #endif
4401 mono_arch_create_generic_class_init_trampoline (&info, TRUE);
4402 emit_trampoline (acfg, acfg->got_offset, info);
4404 /* Emit the exception related code pieces */
4405 code = mono_arch_get_restore_context (&info, TRUE);
4406 emit_trampoline (acfg, acfg->got_offset, info);
4407 code = mono_arch_get_call_filter (&info, TRUE);
4408 emit_trampoline (acfg, acfg->got_offset, info);
4409 code = mono_arch_get_throw_exception (&info, TRUE);
4410 emit_trampoline (acfg, acfg->got_offset, info);
4411 code = mono_arch_get_rethrow_exception (&info, TRUE);
4412 emit_trampoline (acfg, acfg->got_offset, info);
4413 code = mono_arch_get_throw_corlib_exception (&info, TRUE);
4414 emit_trampoline (acfg, acfg->got_offset, info);
4416 #if defined(MONO_ARCH_HAVE_GET_TRAMPOLINES)
4418 GSList *l = mono_arch_get_trampolines (TRUE);
4420 while (l) {
4421 MonoTrampInfo *info = l->data;
4423 emit_trampoline (acfg, acfg->got_offset, info);
4424 l = l->next;
4427 #endif
4429 for (i = 0; i < 128; ++i) {
4430 int offset;
4432 offset = MONO_RGCTX_SLOT_MAKE_RGCTX (i);
4433 code = mono_arch_create_rgctx_lazy_fetch_trampoline (offset, &info, TRUE);
4434 emit_trampoline (acfg, acfg->got_offset, info);
4436 offset = MONO_RGCTX_SLOT_MAKE_MRGCTX (i);
4437 code = mono_arch_create_rgctx_lazy_fetch_trampoline (offset, &info, TRUE);
4438 emit_trampoline (acfg, acfg->got_offset, info);
4442 GSList *l;
4444 /* delegate_invoke_impl trampolines */
4445 l = mono_arch_get_delegate_invoke_impls ();
4446 while (l) {
4447 MonoTrampInfo *info = l->data;
4449 emit_trampoline (acfg, acfg->got_offset, info);
4450 l = l->next;
4454 #endif /* #ifdef MONO_ARCH_HAVE_FULL_AOT_TRAMPOLINES */
4456 /* Emit trampolines which are numerous */
4459 * These include the following:
4460 * - specific trampolines
4461 * - static rgctx invoke trampolines
4462 * - imt thunks
4463 * These trampolines have the same code, they are parameterized by GOT
4464 * slots.
4465 * They are defined in this file, in the arch_... routines instead of
4466 * in tramp-<ARCH>.c, since it is easier to do it this way.
4470 * When running in aot-only mode, we can't create specific trampolines at
4471 * runtime, so we create a few, and save them in the AOT file.
4472 * Normal trampolines embed their argument as a literal inside the
4473 * trampoline code, we can't do that here, so instead we embed an offset
4474 * which needs to be added to the trampoline address to get the address of
4475 * the GOT slot which contains the argument value.
4476 * The generated trampolines jump to the generic trampolines using another
4477 * GOT slot, which will be setup by the AOT loader to point to the
4478 * generic trampoline code of the given type.
4482 * FIXME: Maybe we should use more specific trampolines (i.e. one class init for
4483 * each class).
4486 emit_section_change (acfg, ".text", 0);
4488 tramp_got_offset = acfg->got_offset;
4490 for (ntype = 0; ntype < MONO_AOT_TRAMP_NUM; ++ntype) {
4491 switch (ntype) {
4492 case MONO_AOT_TRAMP_SPECIFIC:
4493 sprintf (symbol, "specific_trampolines");
4494 break;
4495 case MONO_AOT_TRAMP_STATIC_RGCTX:
4496 sprintf (symbol, "static_rgctx_trampolines");
4497 break;
4498 case MONO_AOT_TRAMP_IMT_THUNK:
4499 sprintf (symbol, "imt_thunks");
4500 break;
4501 default:
4502 g_assert_not_reached ();
4505 emit_alignment (acfg, AOT_FUNC_ALIGNMENT);
4506 emit_label (acfg, symbol);
4508 acfg->trampoline_got_offset_base [ntype] = tramp_got_offset;
4510 for (i = 0; i < acfg->num_trampolines [ntype]; ++i) {
4511 int tramp_size = 0;
4513 switch (ntype) {
4514 case MONO_AOT_TRAMP_SPECIFIC:
4515 arch_emit_specific_trampoline (acfg, tramp_got_offset, &tramp_size);
4516 tramp_got_offset += 2;
4517 break;
4518 case MONO_AOT_TRAMP_STATIC_RGCTX:
4519 arch_emit_static_rgctx_trampoline (acfg, tramp_got_offset, &tramp_size);
4520 tramp_got_offset += 2;
4521 break;
4522 case MONO_AOT_TRAMP_IMT_THUNK:
4523 arch_emit_imt_thunk (acfg, tramp_got_offset, &tramp_size);
4524 tramp_got_offset += 1;
4525 break;
4526 default:
4527 g_assert_not_reached ();
4529 #ifdef __native_client_codegen__
4530 /* align to avoid 32-byte boundary crossings */
4531 emit_alignment (acfg, AOT_FUNC_ALIGNMENT);
4532 #endif
4534 if (!acfg->trampoline_size [ntype]) {
4535 g_assert (tramp_size);
4536 acfg->trampoline_size [ntype] = tramp_size;
4541 /* Reserve some entries at the end of the GOT for our use */
4542 acfg->num_trampoline_got_entries = tramp_got_offset - acfg->got_offset;
4545 acfg->got_offset += acfg->num_trampoline_got_entries;
4548 static gboolean
4549 str_begins_with (const char *str1, const char *str2)
4551 int len = strlen (str2);
4552 return strncmp (str1, str2, len) == 0;
4555 static void
4556 mono_aot_parse_options (const char *aot_options, MonoAotOptions *opts)
4558 gchar **args, **ptr;
4560 args = g_strsplit (aot_options ? aot_options : "", ",", -1);
4561 for (ptr = args; ptr && *ptr; ptr ++) {
4562 const char *arg = *ptr;
4564 if (str_begins_with (arg, "outfile=")) {
4565 opts->outfile = g_strdup (arg + strlen ("outfile="));
4566 } else if (str_begins_with (arg, "save-temps")) {
4567 opts->save_temps = TRUE;
4568 } else if (str_begins_with (arg, "keep-temps")) {
4569 opts->save_temps = TRUE;
4570 } else if (str_begins_with (arg, "write-symbols")) {
4571 opts->write_symbols = TRUE;
4572 } else if (str_begins_with (arg, "no-write-symbols")) {
4573 opts->write_symbols = FALSE;
4574 } else if (str_begins_with (arg, "metadata-only")) {
4575 opts->metadata_only = TRUE;
4576 } else if (str_begins_with (arg, "bind-to-runtime-version")) {
4577 opts->bind_to_runtime_version = TRUE;
4578 } else if (str_begins_with (arg, "full")) {
4579 opts->full_aot = TRUE;
4580 } else if (str_begins_with (arg, "threads=")) {
4581 opts->nthreads = atoi (arg + strlen ("threads="));
4582 } else if (str_begins_with (arg, "static")) {
4583 opts->static_link = TRUE;
4584 opts->no_dlsym = TRUE;
4585 } else if (str_begins_with (arg, "asmonly")) {
4586 opts->asm_only = TRUE;
4587 } else if (str_begins_with (arg, "asmwriter")) {
4588 opts->asm_writer = TRUE;
4589 } else if (str_begins_with (arg, "nodebug")) {
4590 opts->nodebug = TRUE;
4591 } else if (str_begins_with (arg, "ntrampolines=")) {
4592 opts->ntrampolines = atoi (arg + strlen ("ntrampolines="));
4593 } else if (str_begins_with (arg, "nrgctx-trampolines=")) {
4594 opts->nrgctx_trampolines = atoi (arg + strlen ("nrgctx-trampolines="));
4595 } else if (str_begins_with (arg, "nimt-trampolines=")) {
4596 opts->nimt_trampolines = atoi (arg + strlen ("nimt-trampolines="));
4597 } else if (str_begins_with (arg, "autoreg")) {
4598 opts->autoreg = TRUE;
4599 } else if (str_begins_with (arg, "tool-prefix=")) {
4600 opts->tool_prefix = g_strdup (arg + strlen ("tool-prefix="));
4601 } else if (str_begins_with (arg, "soft-debug")) {
4602 opts->soft_debug = TRUE;
4603 } else if (str_begins_with (arg, "print-skipped")) {
4604 opts->print_skipped_methods = TRUE;
4605 } else if (str_begins_with (arg, "stats")) {
4606 opts->stats = TRUE;
4607 } else if (str_begins_with (arg, "mtriple=")) {
4608 opts->mtriple = g_strdup (arg + strlen ("mtriple="));
4609 } else if (str_begins_with (arg, "llvm-path=")) {
4610 opts->llvm_path = g_strdup (arg + strlen ("llvm-path="));
4611 } else {
4612 fprintf (stderr, "AOT : Unknown argument '%s'.\n", arg);
4613 exit (1);
4617 g_strfreev (args);
4620 static void
4621 add_token_info_hash (gpointer key, gpointer value, gpointer user_data)
4623 MonoMethod *method = (MonoMethod*)key;
4624 MonoJumpInfoToken *ji = (MonoJumpInfoToken*)value;
4625 MonoJumpInfoToken *new_ji = g_new0 (MonoJumpInfoToken, 1);
4626 MonoAotCompile *acfg = user_data;
4628 new_ji->image = ji->image;
4629 new_ji->token = ji->token;
4630 g_hash_table_insert (acfg->token_info_hash, method, new_ji);
4633 static gboolean
4634 can_encode_class (MonoAotCompile *acfg, MonoClass *klass)
4636 if (klass->type_token)
4637 return TRUE;
4638 if ((klass->byval_arg.type == MONO_TYPE_VAR) || (klass->byval_arg.type == MONO_TYPE_MVAR))
4639 return TRUE;
4640 if (klass->rank)
4641 return can_encode_class (acfg, klass->element_class);
4642 return FALSE;
4645 static gboolean
4646 can_encode_patch (MonoAotCompile *acfg, MonoJumpInfo *patch_info)
4648 switch (patch_info->type) {
4649 case MONO_PATCH_INFO_METHOD:
4650 case MONO_PATCH_INFO_METHODCONST: {
4651 MonoMethod *method = patch_info->data.method;
4653 if (method->wrapper_type) {
4654 switch (method->wrapper_type) {
4655 case MONO_WRAPPER_NONE:
4656 case MONO_WRAPPER_REMOTING_INVOKE_WITH_CHECK:
4657 case MONO_WRAPPER_XDOMAIN_INVOKE:
4658 case MONO_WRAPPER_STFLD:
4659 case MONO_WRAPPER_LDFLD:
4660 case MONO_WRAPPER_LDFLDA:
4661 case MONO_WRAPPER_LDFLD_REMOTE:
4662 case MONO_WRAPPER_STFLD_REMOTE:
4663 case MONO_WRAPPER_STELEMREF:
4664 case MONO_WRAPPER_ISINST:
4665 case MONO_WRAPPER_PROXY_ISINST:
4666 case MONO_WRAPPER_ALLOC:
4667 case MONO_WRAPPER_REMOTING_INVOKE:
4668 case MONO_WRAPPER_UNKNOWN:
4669 case MONO_WRAPPER_WRITE_BARRIER:
4670 break;
4671 case MONO_WRAPPER_MANAGED_TO_MANAGED:
4672 if (!strcmp (method->name, "ElementAddr"))
4673 return TRUE;
4674 else
4675 return FALSE;
4676 case MONO_WRAPPER_CASTCLASS:
4677 if (!strcmp (method->name, "__castclass_with_cache"))
4678 return TRUE;
4679 else if (!strcmp (method->name, "__isinst_with_cache"))
4680 return TRUE;
4681 else
4682 return FALSE;
4683 default:
4684 //printf ("Skip (wrapper call): %d -> %s\n", patch_info->type, mono_method_full_name (patch_info->data.method, TRUE));
4685 return FALSE;
4687 } else {
4688 if (!method->token) {
4689 /* The method is part of a constructed type like Int[,].Set (). */
4690 if (!g_hash_table_lookup (acfg->token_info_hash, method)) {
4691 if (method->klass->rank)
4692 return TRUE;
4693 return FALSE;
4697 break;
4699 case MONO_PATCH_INFO_VTABLE:
4700 case MONO_PATCH_INFO_CLASS_INIT:
4701 case MONO_PATCH_INFO_DELEGATE_TRAMPOLINE:
4702 case MONO_PATCH_INFO_CLASS:
4703 case MONO_PATCH_INFO_IID:
4704 case MONO_PATCH_INFO_ADJUSTED_IID:
4705 if (!can_encode_class (acfg, patch_info->data.klass)) {
4706 //printf ("Skip: %s\n", mono_type_full_name (&patch_info->data.klass->byval_arg));
4707 return FALSE;
4709 break;
4710 case MONO_PATCH_INFO_RGCTX_FETCH: {
4711 MonoJumpInfoRgctxEntry *entry = patch_info->data.rgctx_entry;
4713 if (!can_encode_patch (acfg, entry->data))
4714 return FALSE;
4715 break;
4717 default:
4718 break;
4721 return TRUE;
4725 * compile_method:
4727 * AOT compile a given method.
4728 * This function might be called by multiple threads, so it must be thread-safe.
4730 static void
4731 compile_method (MonoAotCompile *acfg, MonoMethod *method)
4733 MonoCompile *cfg;
4734 MonoJumpInfo *patch_info;
4735 gboolean skip;
4736 int index, depth;
4737 MonoMethod *wrapped;
4739 if (acfg->aot_opts.metadata_only)
4740 return;
4742 mono_acfg_lock (acfg);
4743 index = get_method_index (acfg, method);
4744 mono_acfg_unlock (acfg);
4746 /* fixme: maybe we can also precompile wrapper methods */
4747 if ((method->flags & METHOD_ATTRIBUTE_PINVOKE_IMPL) ||
4748 (method->iflags & METHOD_IMPL_ATTRIBUTE_RUNTIME) ||
4749 (method->flags & METHOD_ATTRIBUTE_ABSTRACT)) {
4750 //printf ("Skip (impossible): %s\n", mono_method_full_name (method, TRUE));
4751 return;
4754 if (method->iflags & METHOD_IMPL_ATTRIBUTE_INTERNAL_CALL)
4755 return;
4757 wrapped = mono_marshal_method_from_wrapper (method);
4758 if (wrapped && (wrapped->iflags & METHOD_IMPL_ATTRIBUTE_INTERNAL_CALL) && wrapped->is_generic)
4759 // FIXME: The wrapper should be generic too, but it is not
4760 return;
4762 InterlockedIncrement (&acfg->stats.mcount);
4764 #if 0
4765 if (method->is_generic || method->klass->generic_container) {
4766 InterlockedIncrement (&acfg->stats.genericcount);
4767 return;
4769 #endif
4771 //acfg->aot_opts.print_skipped_methods = TRUE;
4774 * Since these methods are the only ones which are compiled with
4775 * AOT support, and they are not used by runtime startup/shutdown code,
4776 * the runtime will not see AOT methods during AOT compilation,so it
4777 * does not need to support them by creating a fake GOT etc.
4779 cfg = mini_method_compile (method, acfg->opts, mono_get_root_domain (), FALSE, TRUE, 0);
4780 if (cfg->exception_type == MONO_EXCEPTION_GENERIC_SHARING_FAILED) {
4781 //printf ("F: %s\n", mono_method_full_name (method, TRUE));
4782 InterlockedIncrement (&acfg->stats.genericcount);
4783 return;
4785 if (cfg->exception_type != MONO_EXCEPTION_NONE) {
4786 //printf ("E: %s\n", mono_method_full_name (method, TRUE));
4787 /* Let the exception happen at runtime */
4788 return;
4791 if (cfg->disable_aot) {
4792 if (acfg->aot_opts.print_skipped_methods)
4793 printf ("Skip (disabled): %s\n", mono_method_full_name (method, TRUE));
4794 InterlockedIncrement (&acfg->stats.ocount);
4795 mono_destroy_compile (cfg);
4796 return;
4799 /* Nullify patches which need no aot processing */
4800 for (patch_info = cfg->patch_info; patch_info; patch_info = patch_info->next) {
4801 switch (patch_info->type) {
4802 case MONO_PATCH_INFO_LABEL:
4803 case MONO_PATCH_INFO_BB:
4804 patch_info->type = MONO_PATCH_INFO_NONE;
4805 break;
4806 default:
4807 break;
4811 /* Collect method->token associations from the cfg */
4812 mono_acfg_lock (acfg);
4813 g_hash_table_foreach (cfg->token_info_hash, add_token_info_hash, acfg);
4814 mono_acfg_unlock (acfg);
4817 * Check for absolute addresses.
4819 skip = FALSE;
4820 for (patch_info = cfg->patch_info; patch_info; patch_info = patch_info->next) {
4821 switch (patch_info->type) {
4822 case MONO_PATCH_INFO_ABS:
4823 /* unable to handle this */
4824 skip = TRUE;
4825 break;
4826 default:
4827 break;
4831 if (skip) {
4832 if (acfg->aot_opts.print_skipped_methods)
4833 printf ("Skip (abs call): %s\n", mono_method_full_name (method, TRUE));
4834 InterlockedIncrement (&acfg->stats.abscount);
4835 mono_destroy_compile (cfg);
4836 return;
4839 /* Lock for the rest of the code */
4840 mono_acfg_lock (acfg);
4843 * Check for methods/klasses we can't encode.
4845 skip = FALSE;
4846 for (patch_info = cfg->patch_info; patch_info; patch_info = patch_info->next) {
4847 if (!can_encode_patch (acfg, patch_info))
4848 skip = TRUE;
4851 if (skip) {
4852 if (acfg->aot_opts.print_skipped_methods)
4853 printf ("Skip (patches): %s\n", mono_method_full_name (method, TRUE));
4854 acfg->stats.ocount++;
4855 mono_destroy_compile (cfg);
4856 mono_acfg_unlock (acfg);
4857 return;
4860 /* Adds generic instances referenced by this method */
4862 * The depth is used to avoid infinite loops when generic virtual recursion is
4863 * encountered.
4865 depth = GPOINTER_TO_UINT (g_hash_table_lookup (acfg->method_depth, method));
4866 if (depth < 32) {
4867 for (patch_info = cfg->patch_info; patch_info; patch_info = patch_info->next) {
4868 switch (patch_info->type) {
4869 case MONO_PATCH_INFO_METHOD: {
4870 MonoMethod *m = patch_info->data.method;
4871 if (m->is_inflated) {
4872 if (!(mono_class_generic_sharing_enabled (m->klass) &&
4873 mono_method_is_generic_sharable_impl (m, FALSE)) &&
4874 !method_has_type_vars (m)) {
4875 if (m->iflags & METHOD_IMPL_ATTRIBUTE_INTERNAL_CALL) {
4876 if (acfg->aot_opts.full_aot)
4877 add_extra_method_with_depth (acfg, mono_marshal_get_native_wrapper (m, TRUE, TRUE), depth + 1);
4878 } else {
4879 add_extra_method_with_depth (acfg, m, depth + 1);
4882 add_generic_class_with_depth (acfg, m->klass, depth + 5);
4884 if (m->wrapper_type == MONO_WRAPPER_MANAGED_TO_MANAGED && !strcmp (m->name, "ElementAddr"))
4885 add_extra_method_with_depth (acfg, m, depth + 1);
4886 break;
4888 case MONO_PATCH_INFO_VTABLE: {
4889 MonoClass *klass = patch_info->data.klass;
4891 if (klass->generic_class && !mono_generic_context_is_sharable (&klass->generic_class->context, FALSE))
4892 add_generic_class_with_depth (acfg, klass, depth + 5);
4893 break;
4895 default:
4896 break;
4901 /* Determine whenever the method has GOT slots */
4902 for (patch_info = cfg->patch_info; patch_info; patch_info = patch_info->next) {
4903 switch (patch_info->type) {
4904 case MONO_PATCH_INFO_GOT_OFFSET:
4905 case MONO_PATCH_INFO_NONE:
4906 case MONO_PATCH_INFO_GC_CARD_TABLE_ADDR:
4907 break;
4908 case MONO_PATCH_INFO_IMAGE:
4909 /* The assembly is stored in GOT slot 0 */
4910 if (patch_info->data.image != acfg->image)
4911 cfg->has_got_slots = TRUE;
4912 break;
4913 default:
4914 if (!is_plt_patch (patch_info))
4915 cfg->has_got_slots = TRUE;
4916 break;
4920 if (!cfg->has_got_slots)
4921 InterlockedIncrement (&acfg->stats.methods_without_got_slots);
4924 * FIXME: Instead of this mess, allocate the patches from the aot mempool.
4926 /* Make a copy of the patch info which is in the mempool */
4928 MonoJumpInfo *patches = NULL, *patches_end = NULL;
4930 for (patch_info = cfg->patch_info; patch_info; patch_info = patch_info->next) {
4931 MonoJumpInfo *new_patch_info = mono_patch_info_dup_mp (acfg->mempool, patch_info);
4933 if (!patches)
4934 patches = new_patch_info;
4935 else
4936 patches_end->next = new_patch_info;
4937 patches_end = new_patch_info;
4939 cfg->patch_info = patches;
4941 /* Make a copy of the unwind info */
4943 GSList *l, *unwind_ops;
4944 MonoUnwindOp *op;
4946 unwind_ops = NULL;
4947 for (l = cfg->unwind_ops; l; l = l->next) {
4948 op = mono_mempool_alloc (acfg->mempool, sizeof (MonoUnwindOp));
4949 memcpy (op, l->data, sizeof (MonoUnwindOp));
4950 unwind_ops = g_slist_prepend_mempool (acfg->mempool, unwind_ops, op);
4952 cfg->unwind_ops = g_slist_reverse (unwind_ops);
4954 /* Make a copy of the argument/local info */
4956 MonoInst **args, **locals;
4957 MonoMethodSignature *sig;
4958 MonoMethodHeader *header;
4959 int i;
4961 sig = mono_method_signature (method);
4962 args = mono_mempool_alloc (acfg->mempool, sizeof (MonoInst*) * (sig->param_count + sig->hasthis));
4963 for (i = 0; i < sig->param_count + sig->hasthis; ++i) {
4964 args [i] = mono_mempool_alloc (acfg->mempool, sizeof (MonoInst));
4965 memcpy (args [i], cfg->args [i], sizeof (MonoInst));
4967 cfg->args = args;
4969 header = mono_method_get_header (method);
4970 locals = mono_mempool_alloc (acfg->mempool, sizeof (MonoInst*) * header->num_locals);
4971 for (i = 0; i < header->num_locals; ++i) {
4972 locals [i] = mono_mempool_alloc (acfg->mempool, sizeof (MonoInst));
4973 memcpy (locals [i], cfg->locals [i], sizeof (MonoInst));
4975 cfg->locals = locals;
4978 /* Free some fields used by cfg to conserve memory */
4979 mono_mempool_destroy (cfg->mempool);
4980 cfg->mempool = NULL;
4981 g_free (cfg->varinfo);
4982 cfg->varinfo = NULL;
4983 g_free (cfg->vars);
4984 cfg->vars = NULL;
4985 if (cfg->rs) {
4986 mono_regstate_free (cfg->rs);
4987 cfg->rs = NULL;
4990 //printf ("Compile: %s\n", mono_method_full_name (method, TRUE));
4992 while (index >= acfg->cfgs_size) {
4993 MonoCompile **new_cfgs;
4994 int new_size;
4996 new_size = acfg->cfgs_size * 2;
4997 new_cfgs = g_new0 (MonoCompile*, new_size);
4998 memcpy (new_cfgs, acfg->cfgs, sizeof (MonoCompile*) * acfg->cfgs_size);
4999 g_free (acfg->cfgs);
5000 acfg->cfgs = new_cfgs;
5001 acfg->cfgs_size = new_size;
5003 acfg->cfgs [index] = cfg;
5005 g_hash_table_insert (acfg->method_to_cfg, cfg->orig_method, cfg);
5008 if (cfg->orig_method->wrapper_type)
5009 g_ptr_array_add (acfg->extra_methods, cfg->orig_method);
5012 mono_acfg_unlock (acfg);
5014 InterlockedIncrement (&acfg->stats.ccount);
5017 static void
5018 compile_thread_main (gpointer *user_data)
5020 MonoDomain *domain = user_data [0];
5021 MonoAotCompile *acfg = user_data [1];
5022 GPtrArray *methods = user_data [2];
5023 int i;
5025 mono_thread_attach (domain);
5027 for (i = 0; i < methods->len; ++i)
5028 compile_method (acfg, g_ptr_array_index (methods, i));
5031 static void
5032 load_profile_files (MonoAotCompile *acfg)
5034 FILE *infile;
5035 char *tmp;
5036 int file_index, res, method_index, i;
5037 char ver [256];
5038 guint32 token;
5039 GList *unordered, *l;
5040 gboolean found;
5042 file_index = 0;
5043 while (TRUE) {
5044 tmp = g_strdup_printf ("%s/.mono/aot-profile-data/%s-%d", g_get_home_dir (), acfg->image->assembly_name, file_index);
5046 if (!g_file_test (tmp, G_FILE_TEST_IS_REGULAR)) {
5047 g_free (tmp);
5048 break;
5051 infile = fopen (tmp, "r");
5052 g_assert (infile);
5054 printf ("Using profile data file '%s'\n", tmp);
5055 g_free (tmp);
5057 file_index ++;
5059 res = fscanf (infile, "%32s\n", ver);
5060 if ((res != 1) || strcmp (ver, "#VER:2") != 0) {
5061 printf ("Profile file has wrong version or invalid.\n");
5062 fclose (infile);
5063 continue;
5066 while (TRUE) {
5067 char name [1024];
5068 MonoMethodDesc *desc;
5069 MonoMethod *method;
5071 if (fgets (name, 1023, infile) == NULL)
5072 break;
5074 /* Kill the newline */
5075 if (strlen (name) > 0)
5076 name [strlen (name) - 1] = '\0';
5078 desc = mono_method_desc_new (name, TRUE);
5080 method = mono_method_desc_search_in_image (desc, acfg->image);
5082 if (method && mono_method_get_token (method)) {
5083 token = mono_method_get_token (method);
5084 method_index = mono_metadata_token_index (token) - 1;
5086 found = FALSE;
5087 for (i = 0; i < acfg->method_order->len; ++i) {
5088 if (g_ptr_array_index (acfg->method_order, i) == GUINT_TO_POINTER (method_index)) {
5089 found = TRUE;
5090 break;
5093 if (!found)
5094 g_ptr_array_add (acfg->method_order, GUINT_TO_POINTER (method_index));
5095 } else {
5096 //printf ("No method found matching '%s'.\n", name);
5099 fclose (infile);
5102 /* Add missing methods */
5103 unordered = NULL;
5104 for (method_index = 0; method_index < acfg->image->tables [MONO_TABLE_METHOD].rows; ++method_index) {
5105 found = FALSE;
5106 for (i = 0; i < acfg->method_order->len; ++i) {
5107 if (g_ptr_array_index (acfg->method_order, i) == GUINT_TO_POINTER (method_index)) {
5108 found = TRUE;
5109 break;
5112 if (!found)
5113 unordered = g_list_prepend (unordered, GUINT_TO_POINTER (method_index));
5115 unordered = g_list_reverse (unordered);
5116 for (l = unordered; l; l = l->next)
5117 g_ptr_array_add (acfg->method_order, l->data);
5120 /* Used by the LLVM backend */
5121 guint32
5122 mono_aot_get_got_offset (MonoJumpInfo *ji)
5124 return get_got_offset (llvm_acfg, ji);
5127 char*
5128 mono_aot_get_method_name (MonoCompile *cfg)
5130 if (llvm_acfg->aot_opts.static_link)
5131 /* Include the assembly name too to avoid duplicate symbol errors */
5132 return g_strdup_printf ("%s_%s", llvm_acfg->image->assembly->aname.name, get_debug_sym (cfg->orig_method, "", llvm_acfg->method_label_hash));
5133 else
5134 return get_debug_sym (cfg->orig_method, "", llvm_acfg->method_label_hash);
5137 char*
5138 mono_aot_get_plt_symbol (MonoJumpInfoType type, gconstpointer data)
5140 MonoJumpInfo *ji = mono_mempool_alloc (llvm_acfg->mempool, sizeof (MonoJumpInfo));
5141 MonoPltEntry *plt_entry;
5143 ji->type = type;
5144 ji->data.target = data;
5146 if (!can_encode_patch (llvm_acfg, ji))
5147 return NULL;
5149 plt_entry = get_plt_entry (llvm_acfg, ji);
5150 plt_entry->llvm_used = TRUE;
5152 #if defined(__APPLE__)
5153 return g_strdup_printf (plt_entry->llvm_symbol + strlen (llvm_acfg->llvm_label_prefix));
5154 #else
5155 return g_strdup_printf (plt_entry->llvm_symbol);
5156 #endif
5159 MonoJumpInfo*
5160 mono_aot_patch_info_dup (MonoJumpInfo* ji)
5162 MonoJumpInfo *res;
5164 mono_acfg_lock (llvm_acfg);
5165 res = mono_patch_info_dup_mp (llvm_acfg->mempool, ji);
5166 mono_acfg_unlock (llvm_acfg);
5168 return res;
5171 #ifdef ENABLE_LLVM
5174 * emit_llvm_file:
5176 * Emit the LLVM code into an LLVM bytecode file, and compile it using the LLVM
5177 * tools.
5179 static void
5180 emit_llvm_file (MonoAotCompile *acfg)
5182 char *command, *opts;
5183 int i;
5184 MonoJumpInfo *patch_info;
5187 * When using LLVM, we let llvm emit the got since the LLVM IL needs to refer
5188 * to it.
5191 /* Compute the final size of the got */
5192 for (i = 0; i < acfg->nmethods; ++i) {
5193 if (acfg->cfgs [i]) {
5194 for (patch_info = acfg->cfgs [i]->patch_info; patch_info; patch_info = patch_info->next) {
5195 if (patch_info->type != MONO_PATCH_INFO_NONE) {
5196 if (!is_plt_patch (patch_info))
5197 get_got_offset (acfg, patch_info);
5198 else
5199 get_plt_entry (acfg, patch_info);
5205 acfg->final_got_size = acfg->got_offset + acfg->plt_offset;
5207 if (acfg->aot_opts.full_aot) {
5208 int ntype;
5211 * Need to add the got entries used by the trampolines.
5212 * This is only a conservative approximation.
5214 if (strcmp (acfg->image->assembly->aname.name, "mscorlib") == 0) {
5215 /* For the generic + rgctx trampolines */
5216 acfg->final_got_size += 200;
5217 /* For the specific trampolines */
5218 for (ntype = 0; ntype < MONO_AOT_TRAMP_NUM; ++ntype)
5219 acfg->final_got_size += acfg->num_trampolines [ntype] * 2;
5224 mono_llvm_emit_aot_module ("temp.bc", acfg->final_got_size);
5227 * FIXME: Experiment with adding optimizations, the -std-compile-opts set takes
5228 * a lot of time, and doesn't seem to save much space.
5229 * The following optimizations cannot be enabled:
5230 * - 'tailcallelim'
5231 * - 'jump-threading' changes our blockaddress references to int constants.
5232 * The opt list below was produced by taking the output of:
5233 * llvm-as < /dev/null | opt -O2 -disable-output -debug-pass=Arguments
5234 * then removing tailcallelim + the global opts, and adding a second gvn.
5236 opts = g_strdup ("-instcombine -simplifycfg");
5237 opts = g_strdup ("-simplifycfg -domtree -domfrontier -scalarrepl -instcombine -simplifycfg -basiccg -prune-eh -inline -functionattrs -domtree -domfrontier -scalarrepl -simplify-libcalls -instcombine -simplifycfg -instcombine -simplifycfg -reassociate -domtree -loops -loopsimplify -domfrontier -loopsimplify -lcssa -loop-rotate -licm -lcssa -loop-unswitch -instcombine -scalar-evolution -loopsimplify -lcssa -iv-users -indvars -loop-deletion -loopsimplify -lcssa -loop-unroll -instcombine -memdep -gvn -memdep -memcpyopt -sccp -instcombine -domtree -memdep -dse -adce -simplifycfg -preverify -domtree -verify");
5238 #if 1
5239 command = g_strdup_printf ("%sopt -f %s -o temp.opt.bc temp.bc", acfg->aot_opts.llvm_path, opts);
5240 printf ("Executing opt: %s\n", command);
5241 if (system (command) != 0) {
5242 exit (1);
5244 #endif
5245 g_free (opts);
5247 if (!acfg->llc_args)
5248 acfg->llc_args = g_string_new ("");
5250 /* Verbose asm slows down llc greatly */
5251 g_string_append (acfg->llc_args, " -asm-verbose=false");
5253 if (acfg->aot_opts.mtriple)
5254 g_string_append_printf (acfg->llc_args, " -mtriple=%s", acfg->aot_opts.mtriple);
5256 if (llvm_acfg->aot_opts.static_link)
5257 g_string_append_printf (acfg->llc_args, " -relocation-model=static");
5258 else
5259 g_string_append_printf (acfg->llc_args, " -relocation-model=pic");
5260 unlink (acfg->tmpfname);
5262 command = g_strdup_printf ("%sllc %s -unwind-tables -disable-gnu-eh-frame -enable-mono-eh-frame -o %s temp.opt.bc", acfg->aot_opts.llvm_path, acfg->llc_args->str, acfg->tmpfname);
5264 printf ("Executing llc: %s\n", command);
5266 if (system (command) != 0) {
5267 exit (1);
5270 #endif
5272 static void
5273 emit_code (MonoAotCompile *acfg)
5275 int oindex, i;
5276 char symbol [256];
5277 char end_symbol [256];
5279 #if defined(TARGET_POWERPC64)
5280 sprintf (symbol, ".Lgot_addr");
5281 emit_section_change (acfg, ".text", 0);
5282 emit_alignment (acfg, 8);
5283 emit_label (acfg, symbol);
5284 emit_pointer (acfg, acfg->got_symbol);
5285 #endif
5288 * This global symbol is used to compute the address of each method using the
5289 * code_offsets array. It is also used to compute the memory ranges occupied by
5290 * AOT code, so it must be equal to the address of the first emitted method.
5292 sprintf (symbol, "methods");
5293 emit_section_change (acfg, ".text", 0);
5294 emit_alignment (acfg, 8);
5295 if (acfg->llvm) {
5296 for (i = 0; i < acfg->nmethods; ++i) {
5297 if (acfg->cfgs [i] && acfg->cfgs [i]->compile_llvm) {
5298 fprintf (acfg->fp, "\n.set methods, %s\n", acfg->cfgs [i]->asm_symbol);
5299 break;
5302 if (i == acfg->nmethods)
5303 /* No LLVM compiled methods */
5304 emit_label (acfg, symbol);
5305 } else {
5306 emit_label (acfg, symbol);
5310 * Emit some padding so the local symbol for the first method doesn't have the
5311 * same address as 'methods'.
5313 #if defined(__default_codegen__)
5314 emit_zero_bytes (acfg, 16);
5315 #elif defined(__native_client_codegen__)
5317 const int kPaddingSize = 16;
5318 guint8 pad_buffer[kPaddingSize];
5319 mono_arch_nacl_pad (pad_buffer, kPaddingSize);
5320 emit_bytes (acfg, pad_buffer, kPaddingSize);
5322 #endif
5324 for (oindex = 0; oindex < acfg->method_order->len; ++oindex) {
5325 MonoCompile *cfg;
5326 MonoMethod *method;
5328 i = GPOINTER_TO_UINT (g_ptr_array_index (acfg->method_order, oindex));
5330 cfg = acfg->cfgs [i];
5332 if (!cfg)
5333 continue;
5335 method = cfg->orig_method;
5337 /* Emit unbox trampoline */
5338 if (acfg->aot_opts.full_aot && cfg->orig_method->klass->valuetype && (method->flags & METHOD_ATTRIBUTE_VIRTUAL)) {
5339 if (!method->wrapper_type && !method->is_inflated) {
5340 g_assert (method->token);
5341 sprintf (symbol, "ut_%d", mono_metadata_token_index (method->token) - 1);
5342 } else {
5343 sprintf (symbol, "ut_e_%d", get_method_index (acfg, method));
5346 emit_section_change (acfg, ".text", 0);
5347 #ifdef __native_client_codegen__
5348 emit_alignment (acfg, AOT_FUNC_ALIGNMENT);
5349 #endif
5350 emit_global (acfg, symbol, TRUE);
5352 if (acfg->thumb_mixed && cfg->compile_llvm)
5353 fprintf (acfg->fp, "\n.thumb_func\n");
5355 emit_label (acfg, symbol);
5357 arch_emit_unbox_trampoline (acfg, cfg, cfg->orig_method, cfg->asm_symbol);
5360 if (cfg->compile_llvm)
5361 acfg->stats.llvm_count ++;
5362 else
5363 emit_method_code (acfg, cfg);
5366 sprintf (symbol, "methods_end");
5367 emit_section_change (acfg, ".text", 0);
5368 emit_alignment (acfg, 8);
5369 emit_label (acfg, symbol);
5372 * Add .no_dead_strip directives for all LLVM methods to prevent the OSX linker
5373 * from optimizing them away, since it doesn't see that code_offsets references them.
5374 * JITted methods don't need this since they are referenced using assembler local
5375 * symbols.
5376 * FIXME: This is why write-symbols doesn't work on OSX ?
5378 if (acfg->llvm && acfg->need_no_dead_strip) {
5379 fprintf (acfg->fp, "\n");
5380 for (i = 0; i < acfg->nmethods; ++i) {
5381 if (acfg->cfgs [i] && acfg->cfgs [i]->compile_llvm)
5382 fprintf (acfg->fp, ".no_dead_strip %s\n", acfg->cfgs [i]->asm_symbol);
5386 sprintf (symbol, "code_offsets");
5387 emit_section_change (acfg, RODATA_SECT, 1);
5388 emit_alignment (acfg, 8);
5389 emit_label (acfg, symbol);
5391 acfg->stats.offsets_size += acfg->nmethods * 4;
5393 sprintf (end_symbol, "methods");
5394 for (i = 0; i < acfg->nmethods; ++i) {
5395 if (acfg->cfgs [i]) {
5396 emit_symbol_diff (acfg, acfg->cfgs [i]->asm_symbol, end_symbol, 0);
5397 } else {
5398 emit_int32 (acfg, 0xffffffff);
5401 emit_line (acfg);
5404 static void
5405 emit_info (MonoAotCompile *acfg)
5407 int oindex, i;
5408 char symbol [256];
5409 gint32 *offsets;
5411 offsets = g_new0 (gint32, acfg->nmethods);
5413 for (oindex = 0; oindex < acfg->method_order->len; ++oindex) {
5414 i = GPOINTER_TO_UINT (g_ptr_array_index (acfg->method_order, oindex));
5416 if (acfg->cfgs [i]) {
5417 emit_method_info (acfg, acfg->cfgs [i]);
5418 offsets [i] = acfg->cfgs [i]->method_info_offset;
5419 } else {
5420 offsets [i] = 0;
5424 sprintf (symbol, "method_info_offsets");
5425 emit_section_change (acfg, RODATA_SECT, 1);
5426 emit_alignment (acfg, 8);
5427 emit_label (acfg, symbol);
5429 acfg->stats.offsets_size += emit_offset_table (acfg, acfg->nmethods, 10, offsets);
5431 g_free (offsets);
5434 #endif /* #if !defined(DISABLE_AOT) && !defined(DISABLE_JIT) */
5436 #define rot(x,k) (((x)<<(k)) | ((x)>>(32-(k))))
5437 #define mix(a,b,c) { \
5438 a -= c; a ^= rot(c, 4); c += b; \
5439 b -= a; b ^= rot(a, 6); a += c; \
5440 c -= b; c ^= rot(b, 8); b += a; \
5441 a -= c; a ^= rot(c,16); c += b; \
5442 b -= a; b ^= rot(a,19); a += c; \
5443 c -= b; c ^= rot(b, 4); b += a; \
5445 #define final(a,b,c) { \
5446 c ^= b; c -= rot(b,14); \
5447 a ^= c; a -= rot(c,11); \
5448 b ^= a; b -= rot(a,25); \
5449 c ^= b; c -= rot(b,16); \
5450 a ^= c; a -= rot(c,4); \
5451 b ^= a; b -= rot(a,14); \
5452 c ^= b; c -= rot(b,24); \
5455 static guint
5456 mono_aot_type_hash (MonoType *t1)
5458 guint hash = t1->type;
5460 hash |= t1->byref << 6; /* do not collide with t1->type values */
5461 switch (t1->type) {
5462 case MONO_TYPE_VALUETYPE:
5463 case MONO_TYPE_CLASS:
5464 case MONO_TYPE_SZARRAY:
5465 /* check if the distribution is good enough */
5466 return ((hash << 5) - hash) ^ mono_metadata_str_hash (t1->data.klass->name);
5467 case MONO_TYPE_PTR:
5468 return ((hash << 5) - hash) ^ mono_metadata_type_hash (t1->data.type);
5469 case MONO_TYPE_ARRAY:
5470 return ((hash << 5) - hash) ^ mono_metadata_type_hash (&t1->data.array->eklass->byval_arg);
5471 case MONO_TYPE_GENERICINST:
5472 return ((hash << 5) - hash) ^ 0;
5474 return hash;
5478 * mono_aot_method_hash:
5480 * Return a hash code for methods which only depends on metadata.
5482 guint32
5483 mono_aot_method_hash (MonoMethod *method)
5485 MonoMethodSignature *sig;
5486 MonoClass *klass;
5487 int i, hindex;
5488 int hashes_count;
5489 guint32 *hashes_start, *hashes;
5490 guint32 a, b, c;
5491 MonoGenericInst *ginst = NULL;
5493 /* Similar to the hash in mono_method_get_imt_slot () */
5495 sig = mono_method_signature (method);
5497 if (method->is_inflated)
5498 ginst = ((MonoMethodInflated*)method)->context.method_inst;
5500 hashes_count = sig->param_count + 5 + (ginst ? ginst->type_argc : 0);
5501 hashes_start = g_malloc0 (hashes_count * sizeof (guint32));
5502 hashes = hashes_start;
5504 /* Some wrappers are assigned to random classes */
5505 if (!method->wrapper_type || method->wrapper_type == MONO_WRAPPER_REMOTING_INVOKE_WITH_CHECK)
5506 klass = method->klass;
5507 else
5508 klass = mono_defaults.object_class;
5510 if (!method->wrapper_type) {
5511 char *full_name = mono_type_full_name (&klass->byval_arg);
5513 hashes [0] = mono_metadata_str_hash (full_name);
5514 hashes [1] = 0;
5515 g_free (full_name);
5516 } else {
5517 hashes [0] = mono_metadata_str_hash (klass->name);
5518 hashes [1] = mono_metadata_str_hash (klass->name_space);
5520 if (method->wrapper_type == MONO_WRAPPER_STFLD || method->wrapper_type == MONO_WRAPPER_LDFLD || method->wrapper_type == MONO_WRAPPER_LDFLDA)
5521 /* The method name includes a stringified pointer */
5522 hashes [2] = 0;
5523 else
5524 hashes [2] = mono_metadata_str_hash (method->name);
5525 hashes [3] = method->wrapper_type;
5526 hashes [4] = mono_aot_type_hash (sig->ret);
5527 hindex = 5;
5528 for (i = 0; i < sig->param_count; i++) {
5529 hashes [hindex ++] = mono_aot_type_hash (sig->params [i]);
5531 if (ginst) {
5532 for (i = 0; i < ginst->type_argc; ++i)
5533 hashes [hindex ++] = mono_aot_type_hash (ginst->type_argv [i]);
5535 g_assert (hindex == hashes_count);
5537 /* Setup internal state */
5538 a = b = c = 0xdeadbeef + (((guint32)hashes_count)<<2);
5540 /* Handle most of the hashes */
5541 while (hashes_count > 3) {
5542 a += hashes [0];
5543 b += hashes [1];
5544 c += hashes [2];
5545 mix (a,b,c);
5546 hashes_count -= 3;
5547 hashes += 3;
5550 /* Handle the last 3 hashes (all the case statements fall through) */
5551 switch (hashes_count) {
5552 case 3 : c += hashes [2];
5553 case 2 : b += hashes [1];
5554 case 1 : a += hashes [0];
5555 final (a,b,c);
5556 case 0: /* nothing left to add */
5557 break;
5560 free (hashes_start);
5562 return c;
5564 #undef rot
5565 #undef mix
5566 #undef final
5569 * mono_aot_wrapper_name:
5571 * Return a string which uniqely identifies the given wrapper method.
5573 char*
5574 mono_aot_wrapper_name (MonoMethod *method)
5576 char *name, *tmpsig, *klass_desc;
5578 tmpsig = mono_signature_get_desc (mono_method_signature (method), TRUE);
5580 switch (method->wrapper_type) {
5581 case MONO_WRAPPER_RUNTIME_INVOKE:
5582 if (!strcmp (method->name, "runtime_invoke_dynamic"))
5583 name = g_strdup_printf ("(wrapper runtime-invoke-dynamic)");
5584 else
5585 name = g_strdup_printf ("%s (%s)", method->name, tmpsig);
5586 break;
5587 default:
5588 klass_desc = mono_type_full_name (&method->klass->byval_arg);
5589 name = g_strdup_printf ("%s:%s (%s)", klass_desc, method->name, tmpsig);
5590 g_free (klass_desc);
5591 break;
5594 g_free (tmpsig);
5596 return name;
5600 * mono_aot_get_array_helper_from_wrapper;
5602 * Get the helper method in Array called by an array wrapper method.
5604 MonoMethod*
5605 mono_aot_get_array_helper_from_wrapper (MonoMethod *method)
5607 MonoMethod *m;
5608 const char *prefix;
5609 MonoGenericContext ctx;
5610 MonoType *args [16];
5611 char *mname, *iname, *s, *s2, *helper_name = NULL;
5613 prefix = "System.Collections.Generic";
5614 s = g_strdup_printf ("%s", method->name + strlen (prefix) + 1);
5615 s2 = strstr (s, "`1.");
5616 g_assert (s2);
5617 s2 [0] = '\0';
5618 iname = s;
5619 mname = s2 + 3;
5621 //printf ("X: %s %s\n", iname, mname);
5623 if (!strcmp (iname, "IList"))
5624 helper_name = g_strdup_printf ("InternalArray__%s", mname);
5625 else
5626 helper_name = g_strdup_printf ("InternalArray__%s_%s", iname, mname);
5627 m = mono_class_get_method_from_name (mono_defaults.array_class, helper_name, mono_method_signature (method)->param_count);
5628 g_assert (m);
5629 g_free (helper_name);
5630 g_free (s);
5632 if (m->is_generic) {
5633 memset (&ctx, 0, sizeof (ctx));
5634 args [0] = &method->klass->element_class->byval_arg;
5635 ctx.method_inst = mono_metadata_get_generic_inst (1, args);
5636 m = mono_class_inflate_generic_method (m, &ctx);
5639 return m;
5642 #if !defined(DISABLE_AOT) && !defined(DISABLE_JIT)
5644 typedef struct HashEntry {
5645 guint32 key, value, index;
5646 struct HashEntry *next;
5647 } HashEntry;
5650 * emit_extra_methods:
5652 * Emit methods which are not in the METHOD table, like wrappers.
5654 static void
5655 emit_extra_methods (MonoAotCompile *acfg)
5657 int i, table_size, buf_size;
5658 char symbol [256];
5659 guint8 *p, *buf;
5660 guint32 *info_offsets;
5661 guint32 hash;
5662 GPtrArray *table;
5663 HashEntry *entry, *new_entry;
5664 int nmethods, max_chain_length;
5665 int *chain_lengths;
5667 info_offsets = g_new0 (guint32, acfg->extra_methods->len);
5669 /* Emit method info */
5670 nmethods = 0;
5671 for (i = 0; i < acfg->extra_methods->len; ++i) {
5672 MonoMethod *method = g_ptr_array_index (acfg->extra_methods, i);
5673 MonoCompile *cfg = g_hash_table_lookup (acfg->method_to_cfg, method);
5674 char *name;
5676 if (!cfg)
5677 continue;
5679 buf_size = 10240;
5680 p = buf = g_malloc (buf_size);
5682 nmethods ++;
5684 method = cfg->method_to_register;
5686 name = NULL;
5687 if (method->wrapper_type) {
5688 gboolean encode_ref = FALSE;
5691 * We encode some wrappers using their name, since encoding them
5692 * directly would be difficult. This works because at runtime, we only need to
5693 * check whenever a method ref matches an existing MonoMethod. The downside is
5694 * that the method names are large, so we use the binary encoding if possible.
5696 switch (method->wrapper_type) {
5697 case MONO_WRAPPER_REMOTING_INVOKE_WITH_CHECK:
5698 case MONO_WRAPPER_SYNCHRONIZED:
5699 encode_ref = TRUE;
5700 break;
5701 case MONO_WRAPPER_MANAGED_TO_NATIVE:
5702 /* Skip JIT icall wrappers */
5703 if (!strstr (method->name, "__icall_wrapper"))
5704 encode_ref = TRUE;
5705 break;
5706 case MONO_WRAPPER_UNKNOWN:
5707 if (!strcmp (method->name, "PtrToStructure") || !strcmp (method->name, "StructureToPtr"))
5708 encode_ref = TRUE;
5709 break;
5710 case MONO_WRAPPER_RUNTIME_INVOKE:
5711 if (mono_marshal_method_from_wrapper (method) != method && !strstr (method->name, "virtual"))
5712 /* Direct wrapper, encode normally */
5713 encode_ref = TRUE;
5714 break;
5715 default:
5716 break;
5719 if (!encode_ref)
5720 name = mono_aot_wrapper_name (method);
5723 if (name) {
5724 encode_value (1, p, &p);
5725 encode_value (method->wrapper_type, p, &p);
5726 strcpy ((char*)p, name);
5727 p += strlen (name ) + 1;
5728 g_free (name);
5729 } else {
5730 encode_value (0, p, &p);
5731 encode_method_ref (acfg, method, p, &p);
5734 g_assert ((p - buf) < buf_size);
5736 info_offsets [i] = add_to_blob (acfg, buf, p - buf);
5737 g_free (buf);
5741 * Construct a chained hash table for mapping indexes in extra_method_info to
5742 * method indexes.
5744 table_size = g_spaced_primes_closest ((int)(nmethods * 1.5));
5745 table = g_ptr_array_sized_new (table_size);
5746 for (i = 0; i < table_size; ++i)
5747 g_ptr_array_add (table, NULL);
5748 chain_lengths = g_new0 (int, table_size);
5749 max_chain_length = 0;
5750 for (i = 0; i < acfg->extra_methods->len; ++i) {
5751 MonoMethod *method = g_ptr_array_index (acfg->extra_methods, i);
5752 MonoCompile *cfg = g_hash_table_lookup (acfg->method_to_cfg, method);
5753 guint32 key, value;
5755 if (!cfg)
5756 continue;
5758 key = info_offsets [i];
5759 value = get_method_index (acfg, method);
5761 hash = mono_aot_method_hash (method) % table_size;
5763 chain_lengths [hash] ++;
5764 max_chain_length = MAX (max_chain_length, chain_lengths [hash]);
5766 new_entry = mono_mempool_alloc0 (acfg->mempool, sizeof (HashEntry));
5767 new_entry->key = key;
5768 new_entry->value = value;
5770 entry = g_ptr_array_index (table, hash);
5771 if (entry == NULL) {
5772 new_entry->index = hash;
5773 g_ptr_array_index (table, hash) = new_entry;
5774 } else {
5775 while (entry->next)
5776 entry = entry->next;
5778 entry->next = new_entry;
5779 new_entry->index = table->len;
5780 g_ptr_array_add (table, new_entry);
5784 //printf ("MAX: %d\n", max_chain_length);
5786 /* Emit the table */
5787 sprintf (symbol, "extra_method_table");
5788 emit_section_change (acfg, RODATA_SECT, 0);
5789 emit_alignment (acfg, 8);
5790 emit_label (acfg, symbol);
5792 emit_int32 (acfg, table_size);
5793 for (i = 0; i < table->len; ++i) {
5794 HashEntry *entry = g_ptr_array_index (table, i);
5796 if (entry == NULL) {
5797 emit_int32 (acfg, 0);
5798 emit_int32 (acfg, 0);
5799 emit_int32 (acfg, 0);
5800 } else {
5801 //g_assert (entry->key > 0);
5802 emit_int32 (acfg, entry->key);
5803 emit_int32 (acfg, entry->value);
5804 if (entry->next)
5805 emit_int32 (acfg, entry->next->index);
5806 else
5807 emit_int32 (acfg, 0);
5812 * Emit a table reverse mapping method indexes to their index in extra_method_info.
5813 * This is used by mono_aot_find_jit_info ().
5815 sprintf (symbol, "extra_method_info_offsets");
5816 emit_section_change (acfg, RODATA_SECT, 0);
5817 emit_alignment (acfg, 8);
5818 emit_label (acfg, symbol);
5820 emit_int32 (acfg, acfg->extra_methods->len);
5821 for (i = 0; i < acfg->extra_methods->len; ++i) {
5822 MonoMethod *method = g_ptr_array_index (acfg->extra_methods, i);
5824 emit_int32 (acfg, get_method_index (acfg, method));
5825 emit_int32 (acfg, info_offsets [i]);
5829 static void
5830 emit_exception_info (MonoAotCompile *acfg)
5832 int i;
5833 char symbol [256];
5834 gint32 *offsets;
5836 offsets = g_new0 (gint32, acfg->nmethods);
5837 for (i = 0; i < acfg->nmethods; ++i) {
5838 if (acfg->cfgs [i]) {
5839 emit_exception_debug_info (acfg, acfg->cfgs [i]);
5840 offsets [i] = acfg->cfgs [i]->ex_info_offset;
5841 } else {
5842 offsets [i] = 0;
5846 sprintf (symbol, "ex_info_offsets");
5847 emit_section_change (acfg, RODATA_SECT, 1);
5848 emit_alignment (acfg, 8);
5849 emit_label (acfg, symbol);
5851 acfg->stats.offsets_size += emit_offset_table (acfg, acfg->nmethods, 10, offsets);
5852 g_free (offsets);
5855 static void
5856 emit_unwind_info (MonoAotCompile *acfg)
5858 int i;
5859 char symbol [128];
5862 * The unwind info contains a lot of duplicates so we emit each unique
5863 * entry once, and only store the offset from the start of the table in the
5864 * exception info.
5867 sprintf (symbol, "unwind_info");
5868 emit_section_change (acfg, RODATA_SECT, 1);
5869 emit_alignment (acfg, 8);
5870 emit_label (acfg, symbol);
5872 for (i = 0; i < acfg->unwind_ops->len; ++i) {
5873 guint32 index = GPOINTER_TO_UINT (g_ptr_array_index (acfg->unwind_ops, i));
5874 guint8 *unwind_info;
5875 guint32 unwind_info_len;
5876 guint8 buf [16];
5877 guint8 *p;
5879 unwind_info = mono_get_cached_unwind_info (index, &unwind_info_len);
5881 p = buf;
5882 encode_value (unwind_info_len, p, &p);
5883 emit_bytes (acfg, buf, p - buf);
5884 emit_bytes (acfg, unwind_info, unwind_info_len);
5886 acfg->stats.unwind_info_size += (p - buf) + unwind_info_len;
5890 static void
5891 emit_class_info (MonoAotCompile *acfg)
5893 int i;
5894 char symbol [256];
5895 gint32 *offsets;
5897 offsets = g_new0 (gint32, acfg->image->tables [MONO_TABLE_TYPEDEF].rows);
5898 for (i = 0; i < acfg->image->tables [MONO_TABLE_TYPEDEF].rows; ++i)
5899 offsets [i] = emit_klass_info (acfg, MONO_TOKEN_TYPE_DEF | (i + 1));
5901 sprintf (symbol, "class_info_offsets");
5902 emit_section_change (acfg, RODATA_SECT, 1);
5903 emit_alignment (acfg, 8);
5904 emit_label (acfg, symbol);
5906 acfg->stats.offsets_size += emit_offset_table (acfg, acfg->image->tables [MONO_TABLE_TYPEDEF].rows, 10, offsets);
5907 g_free (offsets);
5910 typedef struct ClassNameTableEntry {
5911 guint32 token, index;
5912 struct ClassNameTableEntry *next;
5913 } ClassNameTableEntry;
5915 static void
5916 emit_class_name_table (MonoAotCompile *acfg)
5918 int i, table_size;
5919 guint32 token, hash;
5920 MonoClass *klass;
5921 GPtrArray *table;
5922 char *full_name;
5923 char symbol [256];
5924 ClassNameTableEntry *entry, *new_entry;
5927 * Construct a chained hash table for mapping class names to typedef tokens.
5929 table_size = g_spaced_primes_closest ((int)(acfg->image->tables [MONO_TABLE_TYPEDEF].rows * 1.5));
5930 table = g_ptr_array_sized_new (table_size);
5931 for (i = 0; i < table_size; ++i)
5932 g_ptr_array_add (table, NULL);
5933 for (i = 0; i < acfg->image->tables [MONO_TABLE_TYPEDEF].rows; ++i) {
5934 token = MONO_TOKEN_TYPE_DEF | (i + 1);
5935 klass = mono_class_get (acfg->image, token);
5936 if (!klass) {
5937 mono_loader_clear_error ();
5938 continue;
5940 full_name = mono_type_get_name_full (mono_class_get_type (klass), MONO_TYPE_NAME_FORMAT_FULL_NAME);
5941 hash = mono_metadata_str_hash (full_name) % table_size;
5942 g_free (full_name);
5944 /* FIXME: Allocate from the mempool */
5945 new_entry = g_new0 (ClassNameTableEntry, 1);
5946 new_entry->token = token;
5948 entry = g_ptr_array_index (table, hash);
5949 if (entry == NULL) {
5950 new_entry->index = hash;
5951 g_ptr_array_index (table, hash) = new_entry;
5952 } else {
5953 while (entry->next)
5954 entry = entry->next;
5956 entry->next = new_entry;
5957 new_entry->index = table->len;
5958 g_ptr_array_add (table, new_entry);
5962 /* Emit the table */
5963 sprintf (symbol, "class_name_table");
5964 emit_section_change (acfg, RODATA_SECT, 0);
5965 emit_alignment (acfg, 8);
5966 emit_label (acfg, symbol);
5968 /* FIXME: Optimize memory usage */
5969 g_assert (table_size < 65000);
5970 emit_int16 (acfg, table_size);
5971 g_assert (table->len < 65000);
5972 for (i = 0; i < table->len; ++i) {
5973 ClassNameTableEntry *entry = g_ptr_array_index (table, i);
5975 if (entry == NULL) {
5976 emit_int16 (acfg, 0);
5977 emit_int16 (acfg, 0);
5978 } else {
5979 emit_int16 (acfg, mono_metadata_token_index (entry->token));
5980 if (entry->next)
5981 emit_int16 (acfg, entry->next->index);
5982 else
5983 emit_int16 (acfg, 0);
5988 static void
5989 emit_image_table (MonoAotCompile *acfg)
5991 int i;
5992 char symbol [256];
5995 * The image table is small but referenced in a lot of places.
5996 * So we emit it at once, and reference its elements by an index.
5999 sprintf (symbol, "image_table");
6000 emit_section_change (acfg, RODATA_SECT, 1);
6001 emit_alignment (acfg, 8);
6002 emit_label (acfg, symbol);
6004 emit_int32 (acfg, acfg->image_table->len);
6005 for (i = 0; i < acfg->image_table->len; i++) {
6006 MonoImage *image = (MonoImage*)g_ptr_array_index (acfg->image_table, i);
6007 MonoAssemblyName *aname = &image->assembly->aname;
6009 /* FIXME: Support multi-module assemblies */
6010 g_assert (image->assembly->image == image);
6012 emit_string (acfg, image->assembly_name);
6013 emit_string (acfg, image->guid);
6014 emit_string (acfg, aname->culture ? aname->culture : "");
6015 emit_string (acfg, (const char*)aname->public_key_token);
6017 emit_alignment (acfg, 8);
6018 emit_int32 (acfg, aname->flags);
6019 emit_int32 (acfg, aname->major);
6020 emit_int32 (acfg, aname->minor);
6021 emit_int32 (acfg, aname->build);
6022 emit_int32 (acfg, aname->revision);
6026 static void
6027 emit_got_info (MonoAotCompile *acfg)
6029 char symbol [256];
6030 int i, first_plt_got_patch, buf_size;
6031 guint8 *p, *buf;
6032 guint32 *got_info_offsets;
6034 /* Add the patches needed by the PLT to the GOT */
6035 acfg->plt_got_offset_base = acfg->got_offset;
6036 first_plt_got_patch = acfg->got_patches->len;
6037 for (i = 1; i < acfg->plt_offset; ++i) {
6038 MonoPltEntry *plt_entry = g_hash_table_lookup (acfg->plt_offset_to_entry, GUINT_TO_POINTER (i));
6040 g_ptr_array_add (acfg->got_patches, plt_entry->ji);
6043 acfg->got_offset += acfg->plt_offset;
6046 * FIXME:
6047 * - optimize offsets table.
6048 * - reduce number of exported symbols.
6049 * - emit info for a klass only once.
6050 * - determine when a method uses a GOT slot which is guaranteed to be already
6051 * initialized.
6052 * - clean up and document the code.
6053 * - use String.Empty in class libs.
6056 /* Encode info required to decode shared GOT entries */
6057 buf_size = acfg->got_patches->len * 128;
6058 p = buf = mono_mempool_alloc (acfg->mempool, buf_size);
6059 got_info_offsets = mono_mempool_alloc (acfg->mempool, acfg->got_patches->len * sizeof (guint32));
6060 acfg->plt_got_info_offsets = mono_mempool_alloc (acfg->mempool, acfg->plt_offset * sizeof (guint32));
6061 /* Unused */
6062 if (acfg->plt_offset)
6063 acfg->plt_got_info_offsets [0] = 0;
6064 for (i = 0; i < acfg->got_patches->len; ++i) {
6065 MonoJumpInfo *ji = g_ptr_array_index (acfg->got_patches, i);
6067 p = buf;
6069 encode_value (ji->type, p, &p);
6070 encode_patch (acfg, ji, p, &p);
6072 g_assert (p - buf <= buf_size);
6073 got_info_offsets [i] = add_to_blob (acfg, buf, p - buf);
6075 if (i >= first_plt_got_patch)
6076 acfg->plt_got_info_offsets [i - first_plt_got_patch + 1] = got_info_offsets [i];
6077 acfg->stats.got_info_size += p - buf;
6080 /* Emit got_info_offsets table */
6081 sprintf (symbol, "got_info_offsets");
6082 emit_section_change (acfg, RODATA_SECT, 1);
6083 emit_alignment (acfg, 8);
6084 emit_label (acfg, symbol);
6086 /* No need to emit offsets for the got plt entries, the plt embeds them directly */
6087 acfg->stats.offsets_size += emit_offset_table (acfg, first_plt_got_patch, 10, (gint32*)got_info_offsets);
6090 static void
6091 emit_got (MonoAotCompile *acfg)
6093 char symbol [256];
6095 if (!acfg->llvm) {
6096 /* Don't make GOT global so accesses to it don't need relocations */
6097 sprintf (symbol, "%s", acfg->got_symbol);
6098 emit_section_change (acfg, ".bss", 0);
6099 emit_alignment (acfg, 8);
6100 emit_local_symbol (acfg, symbol, "got_end", FALSE);
6101 emit_label (acfg, symbol);
6102 if (acfg->got_offset > 0)
6103 emit_zero_bytes (acfg, (int)(acfg->got_offset * sizeof (gpointer)));
6105 sprintf (symbol, "got_end");
6106 emit_label (acfg, symbol);
6110 typedef struct GlobalsTableEntry {
6111 guint32 value, index;
6112 struct GlobalsTableEntry *next;
6113 } GlobalsTableEntry;
6115 static void
6116 emit_globals (MonoAotCompile *acfg)
6118 int i, table_size;
6119 guint32 hash;
6120 GPtrArray *table;
6121 char symbol [256];
6122 GlobalsTableEntry *entry, *new_entry;
6124 if (!acfg->aot_opts.static_link)
6125 return;
6128 * When static linking, we emit a table containing our globals.
6132 * Construct a chained hash table for mapping global names to their index in
6133 * the globals table.
6135 table_size = g_spaced_primes_closest ((int)(acfg->globals->len * 1.5));
6136 table = g_ptr_array_sized_new (table_size);
6137 for (i = 0; i < table_size; ++i)
6138 g_ptr_array_add (table, NULL);
6139 for (i = 0; i < acfg->globals->len; ++i) {
6140 char *name = g_ptr_array_index (acfg->globals, i);
6142 hash = mono_metadata_str_hash (name) % table_size;
6144 /* FIXME: Allocate from the mempool */
6145 new_entry = g_new0 (GlobalsTableEntry, 1);
6146 new_entry->value = i;
6148 entry = g_ptr_array_index (table, hash);
6149 if (entry == NULL) {
6150 new_entry->index = hash;
6151 g_ptr_array_index (table, hash) = new_entry;
6152 } else {
6153 while (entry->next)
6154 entry = entry->next;
6156 entry->next = new_entry;
6157 new_entry->index = table->len;
6158 g_ptr_array_add (table, new_entry);
6162 /* Emit the table */
6163 sprintf (symbol, ".Lglobals_hash");
6164 emit_section_change (acfg, RODATA_SECT, 0);
6165 emit_alignment (acfg, 8);
6166 emit_label (acfg, symbol);
6168 /* FIXME: Optimize memory usage */
6169 g_assert (table_size < 65000);
6170 emit_int16 (acfg, table_size);
6171 for (i = 0; i < table->len; ++i) {
6172 GlobalsTableEntry *entry = g_ptr_array_index (table, i);
6174 if (entry == NULL) {
6175 emit_int16 (acfg, 0);
6176 emit_int16 (acfg, 0);
6177 } else {
6178 emit_int16 (acfg, entry->value + 1);
6179 if (entry->next)
6180 emit_int16 (acfg, entry->next->index);
6181 else
6182 emit_int16 (acfg, 0);
6186 /* Emit the names */
6187 for (i = 0; i < acfg->globals->len; ++i) {
6188 char *name = g_ptr_array_index (acfg->globals, i);
6190 sprintf (symbol, "name_%d", i);
6191 emit_section_change (acfg, RODATA_SECT, 1);
6192 emit_label (acfg, symbol);
6193 emit_string (acfg, name);
6196 /* Emit the globals table */
6197 sprintf (symbol, "globals");
6198 emit_section_change (acfg, ".data", 0);
6199 /* This is not a global, since it is accessed by the init function */
6200 emit_alignment (acfg, 8);
6201 emit_label (acfg, symbol);
6203 sprintf (symbol, "%sglobals_hash", acfg->temp_prefix);
6204 emit_pointer (acfg, symbol);
6206 for (i = 0; i < acfg->globals->len; ++i) {
6207 char *name = g_ptr_array_index (acfg->globals, i);
6209 sprintf (symbol, "name_%d", i);
6210 emit_pointer (acfg, symbol);
6212 sprintf (symbol, "%s", name);
6213 emit_pointer (acfg, symbol);
6215 /* Null terminate the table */
6216 emit_int32 (acfg, 0);
6217 emit_int32 (acfg, 0);
6220 static void
6221 emit_autoreg (MonoAotCompile *acfg)
6223 char *symbol;
6226 * Emit a function into the .ctor section which will be called by the ELF
6227 * loader to register this module with the runtime.
6229 if (! (!acfg->use_bin_writer && acfg->aot_opts.static_link && acfg->aot_opts.autoreg))
6230 return;
6232 symbol = g_strdup_printf ("_%s_autoreg", acfg->static_linking_symbol);
6234 arch_emit_autoreg (acfg, symbol);
6236 g_free (symbol);
6239 static void
6240 emit_mem_end (MonoAotCompile *acfg)
6242 char symbol [128];
6244 sprintf (symbol, "mem_end");
6245 emit_section_change (acfg, ".text", 1);
6246 emit_alignment (acfg, 8);
6247 emit_label (acfg, symbol);
6251 * Emit a structure containing all the information not stored elsewhere.
6253 static void
6254 emit_file_info (MonoAotCompile *acfg)
6256 char symbol [256];
6257 int i;
6258 int gc_name_offset;
6259 const char *gc_name;
6260 char *build_info;
6262 emit_string_symbol (acfg, "assembly_guid" , acfg->image->guid);
6264 if (acfg->aot_opts.bind_to_runtime_version) {
6265 build_info = mono_get_runtime_build_info ();
6266 emit_string_symbol (acfg, "runtime_version", build_info);
6267 g_free (build_info);
6268 } else {
6269 emit_string_symbol (acfg, "runtime_version", "");
6272 /* Emit a string holding the assembly name */
6273 emit_string_symbol (acfg, "assembly_name", acfg->image->assembly->aname.name);
6276 * The managed allocators are GC specific, so can't use an AOT image created by one GC
6277 * in another.
6279 gc_name = mono_gc_get_gc_name ();
6280 gc_name_offset = add_to_blob (acfg, (guint8*)gc_name, strlen (gc_name) + 1);
6282 sprintf (symbol, "mono_aot_file_info");
6283 emit_section_change (acfg, ".data", 0);
6284 emit_alignment (acfg, 8);
6285 emit_label (acfg, symbol);
6286 if (!acfg->aot_opts.static_link)
6287 emit_global (acfg, symbol, FALSE);
6289 /* The data emitted here must match MonoAotFileInfo. */
6291 emit_int32 (acfg, MONO_AOT_FILE_VERSION);
6292 emit_int32 (acfg, 0);
6295 * We emit pointers to our data structures instead of emitting global symbols which
6296 * point to them, to reduce the number of globals, and because using globals leads to
6297 * various problems (i.e. arm/thumb).
6299 emit_pointer (acfg, acfg->got_symbol);
6300 emit_pointer (acfg, "methods");
6301 if (acfg->llvm) {
6303 * Emit a reference to the mono_eh_frame table created by our modified LLVM compiler.
6305 emit_pointer (acfg, "mono_eh_frame");
6306 } else {
6307 emit_pointer (acfg, NULL);
6309 emit_pointer (acfg, "blob");
6310 emit_pointer (acfg, "class_name_table");
6311 emit_pointer (acfg, "class_info_offsets");
6312 emit_pointer (acfg, "method_info_offsets");
6313 emit_pointer (acfg, "ex_info_offsets");
6314 emit_pointer (acfg, "code_offsets");
6315 emit_pointer (acfg, "extra_method_info_offsets");
6316 emit_pointer (acfg, "extra_method_table");
6317 emit_pointer (acfg, "got_info_offsets");
6318 emit_pointer (acfg, "methods_end");
6319 emit_pointer (acfg, "unwind_info");
6320 emit_pointer (acfg, "mem_end");
6321 emit_pointer (acfg, "image_table");
6322 emit_pointer (acfg, "plt");
6323 emit_pointer (acfg, "plt_end");
6324 emit_pointer (acfg, "assembly_guid");
6325 emit_pointer (acfg, "runtime_version");
6326 if (acfg->num_trampoline_got_entries) {
6327 emit_pointer (acfg, "specific_trampolines");
6328 emit_pointer (acfg, "static_rgctx_trampolines");
6329 emit_pointer (acfg, "imt_thunks");
6330 } else {
6331 emit_pointer (acfg, NULL);
6332 emit_pointer (acfg, NULL);
6333 emit_pointer (acfg, NULL);
6335 if (acfg->thumb_mixed) {
6336 emit_pointer (acfg, "thumb_end");
6337 } else {
6338 emit_pointer (acfg, NULL);
6340 if (acfg->aot_opts.static_link) {
6341 emit_pointer (acfg, "globals");
6342 } else {
6343 emit_pointer (acfg, NULL);
6345 emit_pointer (acfg, "assembly_name");
6347 emit_int32 (acfg, acfg->plt_got_offset_base);
6348 emit_int32 (acfg, (int)(acfg->got_offset * sizeof (gpointer)));
6349 emit_int32 (acfg, acfg->plt_offset);
6350 emit_int32 (acfg, acfg->nmethods);
6351 emit_int32 (acfg, acfg->flags);
6352 emit_int32 (acfg, acfg->opts);
6353 emit_int32 (acfg, gc_name_offset);
6355 for (i = 0; i < MONO_AOT_TRAMP_NUM; ++i)
6356 emit_int32 (acfg, acfg->num_trampolines [i]);
6357 for (i = 0; i < MONO_AOT_TRAMP_NUM; ++i)
6358 emit_int32 (acfg, acfg->trampoline_got_offset_base [i]);
6359 for (i = 0; i < MONO_AOT_TRAMP_NUM; ++i)
6360 emit_int32 (acfg, acfg->trampoline_size [i]);
6362 #if defined (TARGET_ARM) && defined (__APPLE__)
6364 MonoType t;
6365 int align = 0;
6367 t.type = MONO_TYPE_R8;
6368 mono_type_size (&t, &align);
6370 emit_int32 (acfg, align);
6372 t.type = MONO_TYPE_I8;
6373 mono_type_size (&t, &align);
6375 emit_int32 (acfg, align);
6377 #else
6378 emit_int32 (acfg, __alignof__ (double));
6379 emit_int32 (acfg, __alignof__ (gint64));
6380 #endif
6382 if (acfg->aot_opts.static_link) {
6383 char *p;
6386 * Emit a global symbol which can be passed by an embedding app to
6387 * mono_aot_register_module (). The symbol points to a pointer to the the file info
6388 * structure.
6390 #if defined(__APPLE__) && !defined(__native_client_codegen__)
6391 sprintf (symbol, "_mono_aot_module_%s_info", acfg->image->assembly->aname.name);
6392 #else
6393 sprintf (symbol, "mono_aot_module_%s_info", acfg->image->assembly->aname.name);
6394 #endif
6396 /* Get rid of characters which cannot occur in symbols */
6397 p = symbol;
6398 for (p = symbol; *p; ++p) {
6399 if (!(isalnum (*p) || *p == '_'))
6400 *p = '_';
6402 acfg->static_linking_symbol = g_strdup (symbol);
6403 emit_global_inner (acfg, symbol, FALSE);
6404 emit_label (acfg, symbol);
6405 emit_pointer (acfg, "mono_aot_file_info");
6409 static void
6410 emit_blob (MonoAotCompile *acfg)
6412 char symbol [128];
6414 sprintf (symbol, "blob");
6415 emit_section_change (acfg, RODATA_SECT, 1);
6416 emit_alignment (acfg, 8);
6417 emit_label (acfg, symbol);
6419 emit_bytes (acfg, (guint8*)acfg->blob.data, acfg->blob.index);
6422 static void
6423 emit_dwarf_info (MonoAotCompile *acfg)
6425 #ifdef EMIT_DWARF_INFO
6426 int i;
6427 char symbol [128], symbol2 [128];
6429 /* DIEs for methods */
6430 for (i = 0; i < acfg->nmethods; ++i) {
6431 MonoCompile *cfg = acfg->cfgs [i];
6433 if (!cfg)
6434 continue;
6436 // FIXME: LLVM doesn't define .Lme_...
6437 if (cfg->compile_llvm)
6438 continue;
6440 sprintf (symbol, "%s", cfg->asm_symbol);
6441 sprintf (symbol2, "%sme_%x", acfg->temp_prefix, i);
6443 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 ()));
6445 #endif
6448 static void
6449 collect_methods (MonoAotCompile *acfg)
6451 int i;
6452 MonoImage *image = acfg->image;
6454 /* Collect methods */
6455 for (i = 0; i < image->tables [MONO_TABLE_METHOD].rows; ++i) {
6456 MonoMethod *method;
6457 guint32 token = MONO_TOKEN_METHOD_DEF | (i + 1);
6459 method = mono_get_method (acfg->image, token, NULL);
6461 if (!method) {
6462 printf ("Failed to load method 0x%x from '%s'.\n", token, image->name);
6463 exit (1);
6466 /* Load all methods eagerly to skip the slower lazy loading code */
6467 mono_class_setup_methods (method->klass);
6469 if (acfg->aot_opts.full_aot && method->iflags & METHOD_IMPL_ATTRIBUTE_INTERNAL_CALL) {
6470 /* Compile the wrapper instead */
6471 /* We do this here instead of add_wrappers () because it is easy to do it here */
6472 MonoMethod *wrapper = mono_marshal_get_native_wrapper (method, check_for_pending_exc, TRUE);
6473 method = wrapper;
6476 /* FIXME: Some mscorlib methods don't have debug info */
6478 if (acfg->aot_opts.soft_debug && !method->wrapper_type) {
6479 if (!((method->flags & METHOD_ATTRIBUTE_PINVOKE_IMPL) ||
6480 (method->iflags & METHOD_IMPL_ATTRIBUTE_RUNTIME) ||
6481 (method->flags & METHOD_ATTRIBUTE_ABSTRACT) ||
6482 (method->iflags & METHOD_IMPL_ATTRIBUTE_INTERNAL_CALL))) {
6483 if (!mono_debug_lookup_method (method)) {
6484 fprintf (stderr, "Method %s has no debug info, probably the .mdb file for the assembly is missing.\n", mono_method_full_name (method, TRUE));
6485 exit (1);
6491 /* Since we add the normal methods first, their index will be equal to their zero based token index */
6492 add_method_with_index (acfg, method, i, FALSE);
6493 acfg->method_index ++;
6496 add_generic_instances (acfg);
6498 if (acfg->aot_opts.full_aot)
6499 add_wrappers (acfg);
6502 static void
6503 compile_methods (MonoAotCompile *acfg)
6505 int i, methods_len;
6507 if (acfg->aot_opts.nthreads > 0) {
6508 GPtrArray *frag;
6509 int len, j;
6510 GPtrArray *threads;
6511 HANDLE handle;
6512 gpointer *user_data;
6513 MonoMethod **methods;
6515 methods_len = acfg->methods->len;
6517 len = acfg->methods->len / acfg->aot_opts.nthreads;
6518 g_assert (len > 0);
6520 * Partition the list of methods into fragments, and hand it to threads to
6521 * process.
6523 threads = g_ptr_array_new ();
6524 /* Make a copy since acfg->methods is modified by compile_method () */
6525 methods = g_new0 (MonoMethod*, methods_len);
6526 //memcpy (methods, g_ptr_array_index (acfg->methods, 0), sizeof (MonoMethod*) * methods_len);
6527 for (i = 0; i < methods_len; ++i)
6528 methods [i] = g_ptr_array_index (acfg->methods, i);
6529 i = 0;
6530 while (i < methods_len) {
6531 frag = g_ptr_array_new ();
6532 for (j = 0; j < len; ++j) {
6533 if (i < methods_len) {
6534 g_ptr_array_add (frag, methods [i]);
6535 i ++;
6539 user_data = g_new0 (gpointer, 3);
6540 user_data [0] = mono_domain_get ();
6541 user_data [1] = acfg;
6542 user_data [2] = frag;
6544 handle = mono_create_thread (NULL, 0, (gpointer)compile_thread_main, user_data, 0, NULL);
6545 g_ptr_array_add (threads, handle);
6547 g_free (methods);
6549 for (i = 0; i < threads->len; ++i) {
6550 WaitForSingleObjectEx (g_ptr_array_index (threads, i), INFINITE, FALSE);
6552 } else {
6553 methods_len = 0;
6556 /* Compile methods added by compile_method () or all methods if nthreads == 0 */
6557 for (i = methods_len; i < acfg->methods->len; ++i) {
6558 /* This can new methods to acfg->methods */
6559 compile_method (acfg, g_ptr_array_index (acfg->methods, i));
6563 static int
6564 compile_asm (MonoAotCompile *acfg)
6566 char *command, *objfile;
6567 char *outfile_name, *tmp_outfile_name;
6568 const char *tool_prefix = acfg->aot_opts.tool_prefix ? acfg->aot_opts.tool_prefix : "";
6570 #if defined(TARGET_AMD64)
6571 #define AS_OPTIONS "--64"
6572 #elif defined(TARGET_POWERPC64)
6573 #define AS_OPTIONS "-a64 -mppc64"
6574 #define LD_OPTIONS "-m elf64ppc"
6575 #elif defined(sparc) && SIZEOF_VOID_P == 8
6576 #define AS_OPTIONS "-xarch=v9"
6577 #elif defined(TARGET_X86) && defined(__APPLE__) && !defined(__native_client_codegen__)
6578 #define AS_OPTIONS "-arch i386 -W"
6579 #else
6580 #define AS_OPTIONS ""
6581 #endif
6583 #ifdef __native_client_codegen__
6584 #if defined(TARGET_AMD64)
6585 #define AS_NAME "nacl64-as"
6586 #else
6587 #define AS_NAME "nacl-as"
6588 #endif
6589 #else
6590 #define AS_NAME "as"
6591 #endif
6593 #ifndef LD_OPTIONS
6594 #define LD_OPTIONS ""
6595 #endif
6597 #define EH_LD_OPTIONS ""
6599 if (acfg->aot_opts.asm_only) {
6600 printf ("Output file: '%s'.\n", acfg->tmpfname);
6601 if (acfg->aot_opts.static_link)
6602 printf ("Linking symbol: '%s'.\n", acfg->static_linking_symbol);
6603 return 0;
6606 if (acfg->aot_opts.static_link) {
6607 if (acfg->aot_opts.outfile)
6608 objfile = g_strdup_printf ("%s", acfg->aot_opts.outfile);
6609 else
6610 objfile = g_strdup_printf ("%s.o", acfg->image->name);
6611 } else {
6612 objfile = g_strdup_printf ("%s.o", acfg->tmpfname);
6614 command = g_strdup_printf ("%s%s %s %s -o %s %s", tool_prefix, AS_NAME, AS_OPTIONS, acfg->as_args ? acfg->as_args->str : "", objfile, acfg->tmpfname);
6615 printf ("Executing the native assembler: %s\n", command);
6616 if (system (command) != 0) {
6617 g_free (command);
6618 g_free (objfile);
6619 return 1;
6622 g_free (command);
6624 if (acfg->aot_opts.static_link) {
6625 printf ("Output file: '%s'.\n", objfile);
6626 printf ("Linking symbol: '%s'.\n", acfg->static_linking_symbol);
6627 g_free (objfile);
6628 return 0;
6631 if (acfg->aot_opts.outfile)
6632 outfile_name = g_strdup_printf ("%s", acfg->aot_opts.outfile);
6633 else
6634 outfile_name = g_strdup_printf ("%s%s", acfg->image->name, SHARED_EXT);
6636 tmp_outfile_name = g_strdup_printf ("%s.tmp", outfile_name);
6638 #if defined(sparc)
6639 command = g_strdup_printf ("ld -shared -G -o %s %s.o", tmp_outfile_name, acfg->tmpfname);
6640 #elif defined(__ppc__) && defined(__APPLE__)
6641 command = g_strdup_printf ("gcc -dynamiclib -o %s %s.o", tmp_outfile_name, acfg->tmpfname);
6642 #elif defined(HOST_WIN32)
6643 command = g_strdup_printf ("gcc -shared --dll -mno-cygwin -o %s %s.o", tmp_outfile_name, acfg->tmpfname);
6644 #elif defined(TARGET_X86) && defined(__APPLE__) && !defined(__native_client_codegen__)
6645 command = g_strdup_printf ("gcc -m32 -dynamiclib -o %s %s.o", tmp_outfile_name, acfg->tmpfname);
6646 #else
6647 command = g_strdup_printf ("%sld %s %s -shared -o %s %s.o", tool_prefix, EH_LD_OPTIONS, LD_OPTIONS, tmp_outfile_name, acfg->tmpfname);
6648 #endif
6649 printf ("Executing the native linker: %s\n", command);
6650 if (system (command) != 0) {
6651 g_free (tmp_outfile_name);
6652 g_free (outfile_name);
6653 g_free (command);
6654 g_free (objfile);
6655 return 1;
6658 g_free (command);
6659 unlink (objfile);
6660 /*com = g_strdup_printf ("strip --strip-unneeded %s%s", acfg->image->name, SHARED_EXT);
6661 printf ("Stripping the binary: %s\n", com);
6662 system (com);
6663 g_free (com);*/
6665 #if defined(TARGET_ARM) && !defined(__APPLE__)
6667 * gas generates 'mapping symbols' each time code and data is mixed, which
6668 * happens a lot in emit_and_reloc_code (), so we need to get rid of them.
6670 command = g_strdup_printf ("%sstrip --strip-symbol=\\$a --strip-symbol=\\$d %s", tool_prefix, tmp_outfile_name);
6671 printf ("Stripping the binary: %s\n", command);
6672 if (system (command) != 0) {
6673 g_free (tmp_outfile_name);
6674 g_free (outfile_name);
6675 g_free (command);
6676 g_free (objfile);
6677 return 1;
6679 #endif
6681 rename (tmp_outfile_name, outfile_name);
6683 g_free (tmp_outfile_name);
6684 g_free (outfile_name);
6685 g_free (objfile);
6687 if (acfg->aot_opts.save_temps)
6688 printf ("Retained input file.\n");
6689 else
6690 unlink (acfg->tmpfname);
6692 return 0;
6695 static MonoAotCompile*
6696 acfg_create (MonoAssembly *ass, guint32 opts)
6698 MonoImage *image = ass->image;
6699 MonoAotCompile *acfg;
6700 int i;
6702 acfg = g_new0 (MonoAotCompile, 1);
6703 acfg->methods = g_ptr_array_new ();
6704 acfg->method_indexes = g_hash_table_new (NULL, NULL);
6705 acfg->method_depth = g_hash_table_new (NULL, NULL);
6706 acfg->plt_offset_to_entry = g_hash_table_new (NULL, NULL);
6707 acfg->patch_to_plt_entry = g_hash_table_new (mono_patch_info_hash, mono_patch_info_equal);
6708 acfg->patch_to_got_offset = g_hash_table_new (mono_patch_info_hash, mono_patch_info_equal);
6709 acfg->patch_to_got_offset_by_type = g_new0 (GHashTable*, MONO_PATCH_INFO_NUM);
6710 for (i = 0; i < MONO_PATCH_INFO_NUM; ++i)
6711 acfg->patch_to_got_offset_by_type [i] = g_hash_table_new (mono_patch_info_hash, mono_patch_info_equal);
6712 acfg->got_patches = g_ptr_array_new ();
6713 acfg->method_to_cfg = g_hash_table_new (NULL, NULL);
6714 acfg->token_info_hash = g_hash_table_new_full (NULL, NULL, NULL, g_free);
6715 acfg->image_hash = g_hash_table_new (NULL, NULL);
6716 acfg->image_table = g_ptr_array_new ();
6717 acfg->globals = g_ptr_array_new ();
6718 acfg->image = image;
6719 acfg->opts = opts;
6720 acfg->mempool = mono_mempool_new ();
6721 acfg->extra_methods = g_ptr_array_new ();
6722 acfg->unwind_info_offsets = g_hash_table_new (NULL, NULL);
6723 acfg->unwind_ops = g_ptr_array_new ();
6724 acfg->method_label_hash = g_hash_table_new_full (g_str_hash, g_str_equal, g_free, NULL);
6725 acfg->method_order = g_ptr_array_new ();
6726 InitializeCriticalSection (&acfg->mutex);
6728 return acfg;
6731 static void
6732 acfg_free (MonoAotCompile *acfg)
6734 int i;
6736 img_writer_destroy (acfg->w);
6737 for (i = 0; i < acfg->nmethods; ++i)
6738 if (acfg->cfgs [i])
6739 g_free (acfg->cfgs [i]);
6740 g_free (acfg->cfgs);
6741 g_free (acfg->static_linking_symbol);
6742 g_free (acfg->got_symbol);
6743 g_free (acfg->plt_symbol);
6744 g_ptr_array_free (acfg->methods, TRUE);
6745 g_ptr_array_free (acfg->got_patches, TRUE);
6746 g_ptr_array_free (acfg->image_table, TRUE);
6747 g_ptr_array_free (acfg->globals, TRUE);
6748 g_ptr_array_free (acfg->unwind_ops, TRUE);
6749 g_hash_table_destroy (acfg->method_indexes);
6750 g_hash_table_destroy (acfg->method_depth);
6751 g_hash_table_destroy (acfg->plt_offset_to_entry);
6752 g_hash_table_destroy (acfg->patch_to_plt_entry);
6753 g_hash_table_destroy (acfg->patch_to_got_offset);
6754 g_hash_table_destroy (acfg->method_to_cfg);
6755 g_hash_table_destroy (acfg->token_info_hash);
6756 g_hash_table_destroy (acfg->image_hash);
6757 g_hash_table_destroy (acfg->unwind_info_offsets);
6758 g_hash_table_destroy (acfg->method_label_hash);
6759 for (i = 0; i < MONO_PATCH_INFO_NUM; ++i)
6760 g_hash_table_destroy (acfg->patch_to_got_offset_by_type [i]);
6761 g_free (acfg->patch_to_got_offset_by_type);
6762 mono_mempool_destroy (acfg->mempool);
6763 g_free (acfg);
6767 mono_compile_assembly (MonoAssembly *ass, guint32 opts, const char *aot_options)
6769 MonoImage *image = ass->image;
6770 int i, res;
6771 MonoAotCompile *acfg;
6772 char *outfile_name, *tmp_outfile_name, *p;
6773 TV_DECLARE (atv);
6774 TV_DECLARE (btv);
6776 printf ("Mono Ahead of Time compiler - compiling assembly %s\n", image->name);
6778 acfg = acfg_create (ass, opts);
6780 memset (&acfg->aot_opts, 0, sizeof (acfg->aot_opts));
6781 acfg->aot_opts.write_symbols = TRUE;
6782 acfg->aot_opts.ntrampolines = 1024;
6783 acfg->aot_opts.nrgctx_trampolines = 1024;
6784 acfg->aot_opts.nimt_trampolines = 128;
6785 acfg->aot_opts.llvm_path = g_strdup ("");
6787 mono_aot_parse_options (aot_options, &acfg->aot_opts);
6789 if (acfg->aot_opts.static_link)
6790 acfg->aot_opts.autoreg = TRUE;
6792 //acfg->aot_opts.print_skipped_methods = TRUE;
6794 #ifndef MONO_ARCH_HAVE_FULL_AOT_TRAMPOLINES
6795 if (acfg->aot_opts.full_aot) {
6796 printf ("--aot=full is not supported on this platform.\n");
6797 return 1;
6799 #endif
6801 if (acfg->aot_opts.static_link)
6802 acfg->aot_opts.asm_writer = TRUE;
6804 if (acfg->aot_opts.soft_debug) {
6805 MonoDebugOptions *opt = mini_get_debug_options ();
6807 opt->mdb_optimizations = TRUE;
6808 opt->gen_seq_points = TRUE;
6810 if (mono_debug_format == MONO_DEBUG_FORMAT_NONE) {
6811 fprintf (stderr, "The soft-debug AOT option requires the --debug option.\n");
6812 return 1;
6814 acfg->flags |= MONO_AOT_FILE_FLAG_DEBUG;
6817 if (mono_use_llvm) {
6818 acfg->llvm = TRUE;
6819 acfg->aot_opts.asm_writer = TRUE;
6820 acfg->flags |= MONO_AOT_FILE_FLAG_WITH_LLVM;
6822 if (acfg->aot_opts.soft_debug) {
6823 fprintf (stderr, "The 'soft-debug' option is not supported when compiling with LLVM.\n");
6824 exit (1);
6828 if (acfg->aot_opts.full_aot)
6829 acfg->flags |= MONO_AOT_FILE_FLAG_FULL_AOT;
6831 load_profile_files (acfg);
6833 acfg->num_trampolines [MONO_AOT_TRAMP_SPECIFIC] = acfg->aot_opts.full_aot ? acfg->aot_opts.ntrampolines : 0;
6834 #ifdef MONO_ARCH_HAVE_STATIC_RGCTX_TRAMPOLINE
6835 acfg->num_trampolines [MONO_AOT_TRAMP_STATIC_RGCTX] = acfg->aot_opts.full_aot ? acfg->aot_opts.nrgctx_trampolines : 0;
6836 #endif
6837 acfg->num_trampolines [MONO_AOT_TRAMP_IMT_THUNK] = acfg->aot_opts.full_aot ? acfg->aot_opts.nimt_trampolines : 0;
6839 acfg->temp_prefix = img_writer_get_temp_label_prefix (NULL);
6841 arch_init (acfg);
6843 acfg->got_symbol_base = g_strdup_printf ("mono_aot_%s_got", acfg->image->assembly->aname.name);
6844 acfg->plt_symbol = g_strdup_printf ("%smono_aot_%s_plt", acfg->llvm_label_prefix, acfg->image->assembly->aname.name);
6846 /* Get rid of characters which cannot occur in symbols */
6847 for (p = acfg->got_symbol_base; *p; ++p) {
6848 if (!(isalnum (*p) || *p == '_'))
6849 *p = '_';
6851 for (p = acfg->plt_symbol; *p; ++p) {
6852 if (!(isalnum (*p) || *p == '_'))
6853 *p = '_';
6856 acfg->method_index = 1;
6858 collect_methods (acfg);
6860 acfg->cfgs_size = acfg->methods->len + 32;
6861 acfg->cfgs = g_new0 (MonoCompile*, acfg->cfgs_size);
6863 /* PLT offset 0 is reserved for the PLT trampoline */
6864 acfg->plt_offset = 1;
6866 #ifdef ENABLE_LLVM
6867 if (acfg->llvm) {
6868 llvm_acfg = acfg;
6869 mono_llvm_create_aot_module (acfg->got_symbol_base);
6871 #endif
6873 /* GOT offset 0 is reserved for the address of the current assembly */
6875 MonoJumpInfo *ji;
6877 ji = mono_mempool_alloc0 (acfg->mempool, sizeof (MonoAotCompile));
6878 ji->type = MONO_PATCH_INFO_IMAGE;
6879 ji->data.image = acfg->image;
6881 get_got_offset (acfg, ji);
6883 /* Slot 1 is reserved for the mscorlib got addr */
6884 ji = mono_mempool_alloc0 (acfg->mempool, sizeof (MonoAotCompile));
6885 ji->type = MONO_PATCH_INFO_MSCORLIB_GOT_ADDR;
6886 get_got_offset (acfg, ji);
6888 /* This is very common */
6889 ji = mono_mempool_alloc0 (acfg->mempool, sizeof (MonoAotCompile));
6890 ji->type = MONO_PATCH_INFO_GC_CARD_TABLE_ADDR;
6891 get_got_offset (acfg, ji);
6894 TV_GETTIME (atv);
6896 compile_methods (acfg);
6898 TV_GETTIME (btv);
6900 acfg->stats.jit_time = TV_ELAPSED (atv, btv);
6902 TV_GETTIME (atv);
6904 #ifdef ENABLE_LLVM
6905 if (acfg->llvm) {
6906 if (acfg->aot_opts.asm_only) {
6907 if (acfg->aot_opts.outfile)
6908 acfg->tmpfname = g_strdup_printf ("%s", acfg->aot_opts.outfile);
6909 else
6910 acfg->tmpfname = g_strdup_printf ("%s.s", acfg->image->name);
6911 } else {
6912 acfg->tmpfname = g_strdup ("temp.s");
6915 emit_llvm_file (acfg);
6917 #endif
6919 if (!acfg->aot_opts.asm_only && !acfg->aot_opts.asm_writer && bin_writer_supported ()) {
6920 if (acfg->aot_opts.outfile)
6921 outfile_name = g_strdup_printf ("%s", acfg->aot_opts.outfile);
6922 else
6923 outfile_name = g_strdup_printf ("%s%s", acfg->image->name, SHARED_EXT);
6926 * Can't use g_file_open_tmp () as it will be deleted at exit, and
6927 * it might be in another file system so the rename () won't work.
6929 tmp_outfile_name = g_strdup_printf ("%s.tmp", outfile_name);
6931 acfg->fp = fopen (tmp_outfile_name, "w");
6932 if (!acfg->fp) {
6933 printf ("Unable to create temporary file '%s': %s\n", tmp_outfile_name, strerror (errno));
6934 return 1;
6937 acfg->w = img_writer_create (acfg->fp, TRUE);
6938 acfg->use_bin_writer = TRUE;
6939 } else {
6940 if (acfg->llvm) {
6941 /* Append to the .s file created by llvm */
6942 /* FIXME: Use multiple files instead */
6943 acfg->fp = fopen (acfg->tmpfname, "a+");
6944 } else {
6945 if (acfg->aot_opts.asm_only) {
6946 if (acfg->aot_opts.outfile)
6947 acfg->tmpfname = g_strdup_printf ("%s", acfg->aot_opts.outfile);
6948 else
6949 acfg->tmpfname = g_strdup_printf ("%s.s", acfg->image->name);
6950 acfg->fp = fopen (acfg->tmpfname, "w+");
6951 } else {
6952 int i = g_file_open_tmp ("mono_aot_XXXXXX", &acfg->tmpfname, NULL);
6953 acfg->fp = fdopen (i, "w+");
6955 g_assert (acfg->fp);
6957 acfg->w = img_writer_create (acfg->fp, FALSE);
6959 tmp_outfile_name = NULL;
6960 outfile_name = NULL;
6963 acfg->got_symbol = g_strdup_printf ("%s%s", acfg->llvm_label_prefix, acfg->got_symbol_base);
6965 /* Compute symbols for methods */
6966 for (i = 0; i < acfg->nmethods; ++i) {
6967 if (acfg->cfgs [i]) {
6968 MonoCompile *cfg = acfg->cfgs [i];
6969 int method_index = get_method_index (acfg, cfg->orig_method);
6971 if (COMPILE_LLVM (cfg))
6972 cfg->asm_symbol = g_strdup_printf ("%s%s", acfg->llvm_label_prefix, cfg->llvm_method_name);
6973 else
6974 cfg->asm_symbol = g_strdup_printf ("%s%sm_%x", acfg->temp_prefix, acfg->llvm_label_prefix, method_index);
6978 if (!acfg->aot_opts.nodebug)
6979 acfg->dwarf = mono_dwarf_writer_create (acfg->w, NULL, 0, FALSE);
6981 img_writer_emit_start (acfg->w);
6983 if (acfg->dwarf)
6984 mono_dwarf_writer_emit_base_info (acfg->dwarf, mono_unwind_get_cie_program ());
6986 if (acfg->thumb_mixed) {
6987 char symbol [256];
6989 * This global symbol marks the end of THUMB code, and the beginning of ARM
6990 * code generated by our JIT.
6992 sprintf (symbol, "thumb_end");
6993 emit_section_change (acfg, ".text", 0);
6994 emit_label (acfg, symbol);
6995 emit_zero_bytes (acfg, 16);
6997 fprintf (acfg->fp, ".arm\n");
7000 emit_code (acfg);
7002 emit_info (acfg);
7004 emit_extra_methods (acfg);
7006 emit_trampolines (acfg);
7008 emit_class_name_table (acfg);
7010 emit_got_info (acfg);
7012 emit_exception_info (acfg);
7014 emit_unwind_info (acfg);
7016 emit_class_info (acfg);
7018 emit_plt (acfg);
7020 emit_image_table (acfg);
7022 emit_got (acfg);
7024 emit_file_info (acfg);
7026 emit_blob (acfg);
7028 emit_globals (acfg);
7030 emit_autoreg (acfg);
7032 if (acfg->dwarf) {
7033 emit_dwarf_info (acfg);
7034 mono_dwarf_writer_close (acfg->dwarf);
7037 emit_mem_end (acfg);
7039 if (acfg->need_pt_gnu_stack) {
7040 /* This is required so the .so doesn't have an executable stack */
7041 /* The bin writer already emits this */
7042 if (!acfg->use_bin_writer)
7043 fprintf (acfg->fp, "\n.section .note.GNU-stack,\"\",@progbits\n");
7046 TV_GETTIME (btv);
7048 acfg->stats.gen_time = TV_ELAPSED (atv, btv);
7050 if (acfg->llvm)
7051 g_assert (acfg->got_offset <= acfg->final_got_size);
7053 printf ("Code: %d Info: %d Ex Info: %d Unwind Info: %d Class Info: %d PLT: %d GOT Info: %d GOT: %d Offsets: %d\n", acfg->stats.code_size, acfg->stats.info_size, acfg->stats.ex_info_size, acfg->stats.unwind_info_size, acfg->stats.class_info_size, acfg->plt_offset, acfg->stats.got_info_size, (int)(acfg->got_offset * sizeof (gpointer)), acfg->stats.offsets_size);
7055 TV_GETTIME (atv);
7056 res = img_writer_emit_writeout (acfg->w);
7057 if (res != 0) {
7058 acfg_free (acfg);
7059 return res;
7061 if (acfg->use_bin_writer) {
7062 int err = rename (tmp_outfile_name, outfile_name);
7064 if (err) {
7065 printf ("Unable to rename '%s' to '%s': %s\n", tmp_outfile_name, outfile_name, strerror (errno));
7066 return 1;
7068 } else {
7069 res = compile_asm (acfg);
7070 if (res != 0) {
7071 acfg_free (acfg);
7072 return res;
7075 TV_GETTIME (btv);
7076 acfg->stats.link_time = TV_ELAPSED (atv, btv);
7078 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);
7079 if (acfg->stats.genericcount)
7080 printf ("%d methods are generic (%d%%)\n", acfg->stats.genericcount, acfg->stats.mcount ? (acfg->stats.genericcount * 100) / acfg->stats.mcount : 100);
7081 if (acfg->stats.abscount)
7082 printf ("%d methods contain absolute addresses (%d%%)\n", acfg->stats.abscount, acfg->stats.mcount ? (acfg->stats.abscount * 100) / acfg->stats.mcount : 100);
7083 if (acfg->stats.lmfcount)
7084 printf ("%d methods contain lmf pointers (%d%%)\n", acfg->stats.lmfcount, acfg->stats.mcount ? (acfg->stats.lmfcount * 100) / acfg->stats.mcount : 100);
7085 if (acfg->stats.ocount)
7086 printf ("%d methods have other problems (%d%%)\n", acfg->stats.ocount, acfg->stats.mcount ? (acfg->stats.ocount * 100) / acfg->stats.mcount : 100);
7087 if (acfg->llvm)
7088 printf ("Methods compiled with LLVM: %d (%d%%)\n", acfg->stats.llvm_count, acfg->stats.mcount ? (acfg->stats.llvm_count * 100) / acfg->stats.mcount : 100);
7089 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);
7090 printf ("Direct calls: %d (%d%%)\n", acfg->stats.direct_calls, acfg->stats.all_calls ? (acfg->stats.direct_calls * 100) / acfg->stats.all_calls : 100);
7092 if (acfg->aot_opts.stats) {
7093 int i;
7095 printf ("GOT slot distribution:\n");
7096 for (i = 0; i < MONO_PATCH_INFO_NONE; ++i)
7097 if (acfg->stats.got_slot_types [i])
7098 printf ("\t%s: %d\n", get_patch_name (i), acfg->stats.got_slot_types [i]);
7101 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);
7103 acfg_free (acfg);
7105 return 0;
7108 #else
7110 /* AOT disabled */
7113 mono_compile_assembly (MonoAssembly *ass, guint32 opts, const char *aot_options)
7115 return 0;
7118 #endif