[runtime] Compare custom modifiers in type equality
[mono-project.git] / mono / mini / aot-compiler.c
blob06aecdb277c13f4396e91f5fe1de68f8b561fbfd
1 /**
2 * \file
3 * mono Ahead of Time compiler
5 * Author:
6 * Dietmar Maurer (dietmar@ximian.com)
7 * Zoltan Varga (vargaz@gmail.com)
8 * Johan Lorensson (lateralusx.github@gmail.com)
10 * (C) 2002 Ximian, Inc.
11 * Copyright 2003-2011 Novell, Inc
12 * Copyright 2011 Xamarin Inc (http://www.xamarin.com)
13 * Licensed under the MIT license. See LICENSE file in the project root for full license information.
16 #include "config.h"
17 #include <sys/types.h>
18 #ifdef HAVE_UNISTD_H
19 #include <unistd.h>
20 #endif
21 #ifdef HAVE_STDINT_H
22 #include <stdint.h>
23 #endif
24 #include <fcntl.h>
25 #include <ctype.h>
26 #include <string.h>
27 #ifndef HOST_WIN32
28 #include <sys/time.h>
29 #else
30 #include <winsock2.h>
31 #include <windows.h>
32 #endif
34 #include <errno.h>
35 #include <sys/stat.h>
37 #include <mono/metadata/abi-details.h>
38 #include <mono/metadata/tabledefs.h>
39 #include <mono/metadata/class.h>
40 #include <mono/metadata/object.h>
41 #include <mono/metadata/tokentype.h>
42 #include <mono/metadata/appdomain.h>
43 #include <mono/metadata/debug-helpers.h>
44 #include <mono/metadata/assembly.h>
45 #include <mono/metadata/metadata-internals.h>
46 #include <mono/metadata/reflection-internals.h>
47 #include <mono/metadata/marshal.h>
48 #include <mono/metadata/gc-internals.h>
49 #include <mono/metadata/mempool-internals.h>
50 #include <mono/metadata/mono-endian.h>
51 #include <mono/metadata/threads-types.h>
52 #include <mono/metadata/custom-attrs-internals.h>
53 #include <mono/utils/mono-logger-internals.h>
54 #include <mono/utils/mono-compiler.h>
55 #include <mono/utils/mono-time.h>
56 #include <mono/utils/mono-mmap.h>
57 #include <mono/utils/mono-rand.h>
58 #include <mono/utils/json.h>
59 #include <mono/utils/mono-threads-coop.h>
60 #include <mono/profiler/aot.h>
61 #include <mono/utils/w32api.h>
63 #include "aot-compiler.h"
64 #include "aot-runtime.h"
65 #include "seq-points.h"
66 #include "image-writer.h"
67 #include "dwarfwriter.h"
68 #include "mini-gc.h"
69 #include "mini-llvm.h"
70 #include "mini-runtime.h"
72 #if !defined(DISABLE_AOT) && !defined(DISABLE_JIT)
74 // Use MSVC toolchain, Clang for MSVC using MSVC codegen and linker, when compiling for AMD64
75 // targeting WIN32 platforms running AOT compiler on WIN32 platform with VS installation.
76 #if defined(TARGET_AMD64) && defined(TARGET_WIN32) && defined(HOST_WIN32) && defined(_MSC_VER)
77 #define TARGET_X86_64_WIN32_MSVC
78 #endif
80 #if defined(TARGET_X86_64_WIN32_MSVC)
81 #define TARGET_WIN32_MSVC
82 #endif
84 // Emit native unwind info on Windows platforms (different from DWARF). Emitted unwind info
85 // works when using the MSVC toolchain using Clang for MSVC codegen and linker. Only supported when
86 // compiling for AMD64 (Windows x64 platforms).
87 #if defined(TARGET_WIN32_MSVC) && defined(MONO_ARCH_HAVE_UNWIND_TABLE)
88 #define EMIT_WIN32_UNWIND_INFO
89 #endif
91 #if defined(__linux__)
92 #define RODATA_SECT ".rodata"
93 #elif defined(TARGET_MACH)
94 #define RODATA_SECT ".section __TEXT, __const"
95 #elif defined(TARGET_WIN32_MSVC)
96 #define RODATA_SECT ".rdata"
97 #else
98 #define RODATA_SECT ".text"
99 #endif
101 #define TV_DECLARE(name) gint64 name
102 #define TV_GETTIME(tv) tv = mono_100ns_ticks ()
103 #define TV_ELAPSED(start,end) (((end) - (start)) / 10)
105 #define ROUND_DOWN(VALUE,SIZE) ((VALUE) & ~((SIZE) - 1))
107 typedef struct {
108 char *name;
109 MonoImage *image;
110 } ImageProfileData;
112 typedef struct ClassProfileData ClassProfileData;
114 typedef struct {
115 int argc;
116 ClassProfileData **argv;
117 MonoGenericInst *inst;
118 } GInstProfileData;
120 struct ClassProfileData {
121 ImageProfileData *image;
122 char *ns, *name;
123 GInstProfileData *inst;
124 MonoClass *klass;
127 typedef struct {
128 ClassProfileData *klass;
129 int id;
130 char *name;
131 int param_count;
132 char *signature;
133 GInstProfileData *inst;
134 MonoMethod *method;
135 } MethodProfileData;
137 typedef struct {
138 GHashTable *images, *classes, *ginsts, *methods;
139 } ProfileData;
141 /* predefined values for static readonly fields without needed to run the .cctor */
142 typedef struct _ReadOnlyValue ReadOnlyValue;
143 struct _ReadOnlyValue {
144 ReadOnlyValue *next;
145 char *name;
146 int type; /* to be used later for typechecking to prevent user errors */
147 union {
148 guint8 i1;
149 guint16 i2;
150 guint32 i4;
151 guint64 i8;
152 gpointer ptr;
153 } value;
155 static ReadOnlyValue *readonly_values;
157 typedef struct MonoAotOptions {
158 char *outfile;
159 char *llvm_outfile;
160 char *data_outfile;
161 GList *profile_files;
162 gboolean save_temps;
163 gboolean write_symbols;
164 gboolean metadata_only;
165 gboolean bind_to_runtime_version;
166 MonoAotMode mode;
167 gboolean interp;
168 gboolean no_dlsym;
169 gboolean static_link;
170 gboolean asm_only;
171 gboolean asm_writer;
172 gboolean nodebug;
173 gboolean dwarf_debug;
174 gboolean soft_debug;
175 gboolean log_generics;
176 gboolean log_instances;
177 gboolean gen_msym_dir;
178 char *gen_msym_dir_path;
179 gboolean direct_pinvoke;
180 gboolean direct_icalls;
181 gboolean no_direct_calls;
182 gboolean use_trampolines_page;
183 gboolean no_instances;
184 // We are collecting inflated methods and emitting non-inflated
185 gboolean dedup;
186 // The name of the assembly for which the AOT module is going to have all deduped methods moved to.
187 // When set, we are emitting inflated methods only
188 char *dedup_include;
189 gboolean gnu_asm;
190 gboolean llvm;
191 gboolean llvm_only;
192 int nthreads;
193 int ntrampolines;
194 int nrgctx_trampolines;
195 int nimt_trampolines;
196 int ngsharedvt_arg_trampolines;
197 int nrgctx_fetch_trampolines;
198 gboolean print_skipped_methods;
199 gboolean stats;
200 gboolean verbose;
201 char *tool_prefix;
202 char *ld_flags;
203 char *mtriple;
204 char *llvm_path;
205 char *temp_path;
206 char *instances_logfile_path;
207 char *logfile;
208 gboolean dump_json;
209 gboolean profile_only;
210 } MonoAotOptions;
212 typedef enum {
213 METHOD_CAT_NORMAL,
214 METHOD_CAT_GSHAREDVT,
215 METHOD_CAT_INST,
216 METHOD_CAT_WRAPPER,
217 METHOD_CAT_NUM
218 } MethodCategory;
220 typedef struct MonoAotStats {
221 int ccount, mcount, lmfcount, abscount, gcount, ocount, genericcount;
222 gint64 code_size, info_size, ex_info_size, unwind_info_size, got_size, class_info_size, got_info_size, plt_size;
223 int methods_without_got_slots, direct_calls, all_calls, llvm_count;
224 int got_slots, offsets_size;
225 int method_categories [METHOD_CAT_NUM];
226 int got_slot_types [MONO_PATCH_INFO_NUM];
227 int got_slot_info_sizes [MONO_PATCH_INFO_NUM];
228 int jit_time, gen_time, link_time;
229 } MonoAotStats;
231 typedef struct GotInfo {
232 GHashTable *patch_to_got_offset;
233 GHashTable **patch_to_got_offset_by_type;
234 GPtrArray *got_patches;
235 } GotInfo;
237 #ifdef EMIT_WIN32_UNWIND_INFO
238 typedef struct _UnwindInfoSectionCacheItem {
239 char *xdata_section_label;
240 PUNWIND_INFO unwind_info;
241 gboolean xdata_section_emitted;
242 } UnwindInfoSectionCacheItem;
243 #endif
245 typedef struct MonoAotCompile {
246 MonoImage *image;
247 GPtrArray *methods;
248 GHashTable *method_indexes;
249 GHashTable *method_depth;
250 MonoCompile **cfgs;
251 int cfgs_size;
252 GHashTable **patch_to_plt_entry;
253 GHashTable *plt_offset_to_entry;
254 //GHashTable *patch_to_got_offset;
255 //GHashTable **patch_to_got_offset_by_type;
256 //GPtrArray *got_patches;
257 GotInfo got_info, llvm_got_info;
258 GHashTable *image_hash;
259 GHashTable *method_to_cfg;
260 GHashTable *token_info_hash;
261 GHashTable *method_to_pinvoke_import;
262 GPtrArray *extra_methods;
263 GPtrArray *image_table;
264 GPtrArray *globals;
265 GPtrArray *method_order;
266 GHashTable *dedup_stats;
267 GHashTable *dedup_cache;
268 gboolean dedup_cache_changed;
269 GHashTable *export_names;
270 /* Maps MonoClass* -> blob offset */
271 GHashTable *klass_blob_hash;
272 /* Maps MonoMethod* -> blob offset */
273 GHashTable *method_blob_hash;
274 GHashTable *gsharedvt_in_signatures;
275 GHashTable *gsharedvt_out_signatures;
276 guint32 *plt_got_info_offsets;
277 guint32 got_offset, llvm_got_offset, plt_offset, plt_got_offset_base, nshared_got_entries;
278 /* Number of GOT entries reserved for trampolines */
279 guint32 num_trampoline_got_entries;
280 guint32 tramp_page_size;
282 guint32 table_offsets [MONO_AOT_TABLE_NUM];
283 guint32 num_trampolines [MONO_AOT_TRAMP_NUM];
284 guint32 trampoline_got_offset_base [MONO_AOT_TRAMP_NUM];
285 guint32 trampoline_size [MONO_AOT_TRAMP_NUM];
286 guint32 tramp_page_code_offsets [MONO_AOT_TRAMP_NUM];
288 MonoAotOptions aot_opts;
289 guint32 nmethods;
290 guint32 opts;
291 guint32 simd_opts;
292 MonoMemPool *mempool;
293 MonoAotStats stats;
294 int method_index;
295 char *static_linking_symbol;
296 mono_mutex_t mutex;
297 gboolean gas_line_numbers;
298 /* Whenever to emit an object file directly from llc */
299 gboolean llvm_owriter;
300 gboolean llvm_owriter_supported;
301 MonoImageWriter *w;
302 MonoDwarfWriter *dwarf;
303 FILE *fp;
304 char *tmpbasename;
305 char *tmpfname;
306 char *llvm_sfile;
307 char *llvm_ofile;
308 GSList *cie_program;
309 GHashTable *unwind_info_offsets;
310 GPtrArray *unwind_ops;
311 guint32 unwind_info_offset;
312 char *global_prefix;
313 char *got_symbol;
314 char *llvm_got_symbol;
315 char *plt_symbol;
316 char *llvm_eh_frame_symbol;
317 GHashTable *method_label_hash;
318 const char *temp_prefix;
319 const char *user_symbol_prefix;
320 const char *llvm_label_prefix;
321 const char *inst_directive;
322 int align_pad_value;
323 guint32 label_generator;
324 gboolean llvm;
325 gboolean has_jitted_code;
326 gboolean is_full_aot;
327 MonoAotFileFlags flags;
328 MonoDynamicStream blob;
329 gboolean blob_closed;
330 GHashTable *typespec_classes;
331 GString *llc_args;
332 GString *as_args;
333 char *assembly_name_sym;
334 GHashTable *plt_entry_debug_sym_cache;
335 gboolean thumb_mixed, need_no_dead_strip, need_pt_gnu_stack;
336 GHashTable *ginst_hash;
337 GHashTable *dwarf_ln_filenames;
338 gboolean global_symbols;
339 int objc_selector_index, objc_selector_index_2;
340 GPtrArray *objc_selectors;
341 GHashTable *objc_selector_to_index;
342 GList *profile_data;
343 GHashTable *profile_methods;
344 #ifdef EMIT_WIN32_UNWIND_INFO
345 GList *unwind_info_section_cache;
346 #endif
347 FILE *logfile;
348 FILE *instances_logfile;
349 FILE *data_outfile;
350 int datafile_offset;
351 int gc_name_offset;
352 // In this mode, we are emitting dedupable methods that we encounter
353 gboolean dedup_emit_mode;
354 } MonoAotCompile;
356 typedef struct {
357 int plt_offset;
358 char *symbol, *llvm_symbol, *debug_sym;
359 MonoJumpInfo *ji;
360 gboolean jit_used, llvm_used;
361 } MonoPltEntry;
363 #define mono_acfg_lock(acfg) mono_os_mutex_lock (&((acfg)->mutex))
364 #define mono_acfg_unlock(acfg) mono_os_mutex_unlock (&((acfg)->mutex))
366 /* This points to the current acfg in LLVM mode */
367 static MonoAotCompile *llvm_acfg;
369 #ifdef HAVE_ARRAY_ELEM_INIT
370 #define MSGSTRFIELD(line) MSGSTRFIELD1(line)
371 #define MSGSTRFIELD1(line) str##line
372 static const struct msgstr_t {
373 #define PATCH_INFO(a,b) char MSGSTRFIELD(__LINE__) [sizeof (b)];
374 #include "patch-info.h"
375 #undef PATCH_INFO
376 } opstr = {
377 #define PATCH_INFO(a,b) b,
378 #include "patch-info.h"
379 #undef PATCH_INFO
381 static const gint16 opidx [] = {
382 #define PATCH_INFO(a,b) [MONO_PATCH_INFO_ ## a] = offsetof (struct msgstr_t, MSGSTRFIELD(__LINE__)),
383 #include "patch-info.h"
384 #undef PATCH_INFO
387 static G_GNUC_UNUSED const char*
388 get_patch_name (int info)
390 return (const char*)&opstr + opidx [info];
393 #else
394 #define PATCH_INFO(a,b) b,
395 static const char* const
396 patch_types [MONO_PATCH_INFO_NUM + 1] = {
397 #include "patch-info.h"
398 NULL
401 static G_GNUC_UNUSED const char*
402 get_patch_name (int info)
404 return patch_types [info];
407 #endif
409 static void
410 mono_flush_method_cache (MonoAotCompile *acfg);
412 static void
413 mono_read_method_cache (MonoAotCompile *acfg);
415 static guint32
416 get_unwind_info_offset (MonoAotCompile *acfg, guint8 *encoded, guint32 encoded_len);
418 static char*
419 get_plt_entry_debug_sym (MonoAotCompile *acfg, MonoJumpInfo *ji, GHashTable *cache);
421 static void
422 add_gsharedvt_wrappers (MonoAotCompile *acfg, MonoMethodSignature *sig, gboolean gsharedvt_in, gboolean gsharedvt_out, gboolean interp_in);
424 static void
425 add_profile_instances (MonoAotCompile *acfg, ProfileData *data);
427 static inline gboolean
428 ignore_cfg (MonoCompile *cfg)
430 return !cfg || cfg->skip;
433 static void
434 aot_printf (MonoAotCompile *acfg, const gchar *format, ...)
436 FILE *output;
437 va_list args;
439 if (acfg->logfile)
440 output = acfg->logfile;
441 else
442 output = stdout;
444 va_start (args, format);
445 vfprintf (output, format, args);
446 va_end (args);
449 static void
450 aot_printerrf (MonoAotCompile *acfg, const gchar *format, ...)
452 FILE *output;
453 va_list args;
455 if (acfg->logfile)
456 output = acfg->logfile;
457 else
458 output = stderr;
460 va_start (args, format);
461 vfprintf (output, format, args);
462 va_end (args);
465 static void
466 report_loader_error (MonoAotCompile *acfg, MonoError *error, gboolean fatal, const char *format, ...)
468 FILE *output;
469 va_list args;
471 if (mono_error_ok (error))
472 return;
474 if (acfg->logfile)
475 output = acfg->logfile;
476 else
477 output = stderr;
479 va_start (args, format);
480 vfprintf (output, format, args);
481 va_end (args);
482 mono_error_cleanup (error);
484 if (acfg->is_full_aot && fatal) {
485 fprintf (output, "FullAOT cannot continue if there are loader errors.\n");
486 exit (1);
490 /* Wrappers around the image writer functions */
492 #define MAX_SYMBOL_SIZE 256
494 static inline const char *
495 mangle_symbol (const char * symbol, char * mangled_symbol, gsize length)
497 gsize needed_size = length;
499 g_assert (NULL != symbol);
500 g_assert (NULL != mangled_symbol);
501 g_assert (0 != length);
503 #if defined(TARGET_WIN32) && defined(TARGET_X86)
504 if (symbol && '_' != symbol [0]) {
505 needed_size = g_snprintf (mangled_symbol, length, "_%s", symbol);
506 } else {
507 needed_size = g_snprintf (mangled_symbol, length, "%s", symbol);
509 #else
510 needed_size = g_snprintf (mangled_symbol, length, "%s", symbol);
511 #endif
513 g_assert (0 <= needed_size && needed_size < length);
514 return mangled_symbol;
517 static inline char *
518 mangle_symbol_alloc (const char * symbol)
520 g_assert (NULL != symbol);
522 #if defined(TARGET_WIN32) && defined(TARGET_X86)
523 if (symbol && '_' != symbol [0]) {
524 return g_strdup_printf ("_%s", symbol);
526 else {
527 return g_strdup_printf ("%s", symbol);
529 #else
530 return g_strdup_printf ("%s", symbol);
531 #endif
534 static inline void
535 emit_section_change (MonoAotCompile *acfg, const char *section_name, int subsection_index)
537 mono_img_writer_emit_section_change (acfg->w, section_name, subsection_index);
540 #if defined(TARGET_WIN32) && defined(TARGET_X86)
542 static inline void
543 emit_local_symbol (MonoAotCompile *acfg, const char *name, const char *end_label, gboolean func)
545 const char * mangled_symbol_name = name;
546 char * mangled_symbol_name_alloc = NULL;
548 if (TRUE == func) {
549 mangled_symbol_name_alloc = mangle_symbol_alloc (name);
550 mangled_symbol_name = mangled_symbol_name_alloc;
553 if (name != mangled_symbol_name && 0 != g_strcasecmp (name, mangled_symbol_name)) {
554 mono_img_writer_emit_label (acfg->w, mangled_symbol_name);
556 mono_img_writer_emit_local_symbol (acfg->w, mangled_symbol_name, end_label, func);
558 if (NULL != mangled_symbol_name_alloc) {
559 g_free (mangled_symbol_name_alloc);
563 #else
565 static inline void
566 emit_local_symbol (MonoAotCompile *acfg, const char *name, const char *end_label, gboolean func)
568 mono_img_writer_emit_local_symbol (acfg->w, name, end_label, func);
571 #endif
573 static inline void
574 emit_label (MonoAotCompile *acfg, const char *name)
576 mono_img_writer_emit_label (acfg->w, name);
579 static inline void
580 emit_bytes (MonoAotCompile *acfg, const guint8* buf, int size)
582 mono_img_writer_emit_bytes (acfg->w, buf, size);
585 static inline void
586 emit_string (MonoAotCompile *acfg, const char *value)
588 mono_img_writer_emit_string (acfg->w, value);
591 static inline void
592 emit_line (MonoAotCompile *acfg)
594 mono_img_writer_emit_line (acfg->w);
597 static inline void
598 emit_alignment (MonoAotCompile *acfg, int size)
600 mono_img_writer_emit_alignment (acfg->w, size);
603 static inline void
604 emit_alignment_code (MonoAotCompile *acfg, int size)
606 if (acfg->align_pad_value)
607 mono_img_writer_emit_alignment_fill (acfg->w, size, acfg->align_pad_value);
608 else
609 mono_img_writer_emit_alignment (acfg->w, size);
612 static inline void
613 emit_padding (MonoAotCompile *acfg, int size)
615 int i;
616 guint8 buf [16];
618 if (acfg->align_pad_value) {
619 for (i = 0; i < 16; ++i)
620 buf [i] = acfg->align_pad_value;
621 } else {
622 memset (buf, 0, sizeof (buf));
625 for (i = 0; i < size; i += 16) {
626 if (size - i < 16)
627 emit_bytes (acfg, buf, size - i);
628 else
629 emit_bytes (acfg, buf, 16);
633 static inline void
634 emit_pointer (MonoAotCompile *acfg, const char *target)
636 mono_img_writer_emit_pointer (acfg->w, target);
639 static inline void
640 emit_pointer_2 (MonoAotCompile *acfg, const char *prefix, const char *target)
642 if (prefix [0] != '\0') {
643 char *s = g_strdup_printf ("%s%s", prefix, target);
644 mono_img_writer_emit_pointer (acfg->w, s);
645 g_free (s);
646 } else {
647 mono_img_writer_emit_pointer (acfg->w, target);
651 static inline void
652 emit_int16 (MonoAotCompile *acfg, int value)
654 mono_img_writer_emit_int16 (acfg->w, value);
657 static inline void
658 emit_int32 (MonoAotCompile *acfg, int value)
660 mono_img_writer_emit_int32 (acfg->w, value);
663 static inline void
664 emit_symbol_diff (MonoAotCompile *acfg, const char *end, const char* start, int offset)
666 mono_img_writer_emit_symbol_diff (acfg->w, end, start, offset);
669 static inline void
670 emit_zero_bytes (MonoAotCompile *acfg, int num)
672 mono_img_writer_emit_zero_bytes (acfg->w, num);
675 static inline void
676 emit_byte (MonoAotCompile *acfg, guint8 val)
678 mono_img_writer_emit_byte (acfg->w, val);
681 #if defined(TARGET_WIN32) && defined(TARGET_X86)
683 static G_GNUC_UNUSED void
684 emit_global_inner (MonoAotCompile *acfg, const char *name, gboolean func)
686 const char * mangled_symbol_name = name;
687 char * mangled_symbol_name_alloc = NULL;
689 mangled_symbol_name_alloc = mangle_symbol_alloc (name);
690 mangled_symbol_name = mangled_symbol_name_alloc;
692 if (0 != g_strcasecmp (name, mangled_symbol_name)) {
693 mono_img_writer_emit_label (acfg->w, mangled_symbol_name);
695 mono_img_writer_emit_global (acfg->w, mangled_symbol_name, func);
697 if (NULL != mangled_symbol_name_alloc) {
698 g_free (mangled_symbol_name_alloc);
702 #else
704 static G_GNUC_UNUSED void
705 emit_global_inner (MonoAotCompile *acfg, const char *name, gboolean func)
707 mono_img_writer_emit_global (acfg->w, name, func);
710 #endif
712 static inline gboolean
713 link_shared_library (MonoAotCompile *acfg)
715 return !acfg->aot_opts.static_link && !acfg->aot_opts.asm_only;
718 static inline gboolean
719 add_to_global_symbol_table (MonoAotCompile *acfg)
721 #ifdef TARGET_WIN32_MSVC
722 return acfg->aot_opts.no_dlsym || link_shared_library (acfg);
723 #else
724 return acfg->aot_opts.no_dlsym;
725 #endif
728 static void
729 emit_global (MonoAotCompile *acfg, const char *name, gboolean func)
731 if (add_to_global_symbol_table (acfg))
732 g_ptr_array_add (acfg->globals, g_strdup (name));
734 if (acfg->aot_opts.no_dlsym) {
735 mono_img_writer_emit_local_symbol (acfg->w, name, NULL, func);
736 } else {
737 emit_global_inner (acfg, name, func);
741 static void
742 emit_symbol_size (MonoAotCompile *acfg, const char *name, const char *end_label)
744 mono_img_writer_emit_symbol_size (acfg->w, name, end_label);
747 /* Emit a symbol which is referenced by the MonoAotFileInfo structure */
748 static void
749 emit_info_symbol (MonoAotCompile *acfg, const char *name)
751 char symbol [MAX_SYMBOL_SIZE];
753 if (acfg->llvm) {
754 emit_label (acfg, name);
755 /* LLVM generated code references this */
756 sprintf (symbol, "%s%s%s", acfg->user_symbol_prefix, acfg->global_prefix, name);
757 emit_label (acfg, symbol);
758 emit_global_inner (acfg, symbol, FALSE);
759 } else {
760 emit_label (acfg, name);
764 static void
765 emit_string_symbol (MonoAotCompile *acfg, const char *name, const char *value)
767 if (acfg->llvm) {
768 mono_llvm_emit_aot_data (name, (guint8*)value, strlen (value) + 1);
769 return;
772 mono_img_writer_emit_section_change (acfg->w, RODATA_SECT, 1);
773 #ifdef TARGET_MACH
774 /* On apple, all symbols need to be aligned to avoid warnings from ld */
775 emit_alignment (acfg, 4);
776 #endif
777 mono_img_writer_emit_label (acfg->w, name);
778 mono_img_writer_emit_string (acfg->w, value);
781 static G_GNUC_UNUSED void
782 emit_uleb128 (MonoAotCompile *acfg, guint32 value)
784 do {
785 guint8 b = value & 0x7f;
786 value >>= 7;
787 if (value != 0) /* more bytes to come */
788 b |= 0x80;
789 emit_byte (acfg, b);
790 } while (value);
793 static G_GNUC_UNUSED void
794 emit_sleb128 (MonoAotCompile *acfg, gint64 value)
796 gboolean more = 1;
797 gboolean negative = (value < 0);
798 guint32 size = 64;
799 guint8 byte;
801 while (more) {
802 byte = value & 0x7f;
803 value >>= 7;
804 /* the following is unnecessary if the
805 * implementation of >>= uses an arithmetic rather
806 * than logical shift for a signed left operand
808 if (negative)
809 /* sign extend */
810 value |= - ((gint64)1 <<(size - 7));
811 /* sign bit of byte is second high order bit (0x40) */
812 if ((value == 0 && !(byte & 0x40)) ||
813 (value == -1 && (byte & 0x40)))
814 more = 0;
815 else
816 byte |= 0x80;
817 emit_byte (acfg, byte);
821 static G_GNUC_UNUSED void
822 encode_uleb128 (guint32 value, guint8 *buf, guint8 **endbuf)
824 guint8 *p = buf;
826 do {
827 guint8 b = value & 0x7f;
828 value >>= 7;
829 if (value != 0) /* more bytes to come */
830 b |= 0x80;
831 *p ++ = b;
832 } while (value);
834 *endbuf = p;
837 static G_GNUC_UNUSED void
838 encode_sleb128 (gint32 value, guint8 *buf, guint8 **endbuf)
840 gboolean more = 1;
841 gboolean negative = (value < 0);
842 guint32 size = 32;
843 guint8 byte;
844 guint8 *p = buf;
846 while (more) {
847 byte = value & 0x7f;
848 value >>= 7;
849 /* the following is unnecessary if the
850 * implementation of >>= uses an arithmetic rather
851 * than logical shift for a signed left operand
853 if (negative)
854 /* sign extend */
855 value |= - (1 <<(size - 7));
856 /* sign bit of byte is second high order bit (0x40) */
857 if ((value == 0 && !(byte & 0x40)) ||
858 (value == -1 && (byte & 0x40)))
859 more = 0;
860 else
861 byte |= 0x80;
862 *p ++= byte;
865 *endbuf = p;
868 static void
869 encode_int (gint32 val, guint8 *buf, guint8 **endbuf)
871 // FIXME: Big-endian
872 buf [0] = (val >> 0) & 0xff;
873 buf [1] = (val >> 8) & 0xff;
874 buf [2] = (val >> 16) & 0xff;
875 buf [3] = (val >> 24) & 0xff;
877 *endbuf = buf + 4;
880 static void
881 encode_int16 (guint16 val, guint8 *buf, guint8 **endbuf)
883 buf [0] = (val >> 0) & 0xff;
884 buf [1] = (val >> 8) & 0xff;
886 *endbuf = buf + 2;
889 static void
890 encode_string (const char *s, guint8 *buf, guint8 **endbuf)
892 int len = strlen (s);
894 memcpy (buf, s, len + 1);
895 *endbuf = buf + len + 1;
898 static void
899 emit_unset_mode (MonoAotCompile *acfg)
901 mono_img_writer_emit_unset_mode (acfg->w);
904 static G_GNUC_UNUSED void
905 emit_set_thumb_mode (MonoAotCompile *acfg)
907 emit_unset_mode (acfg);
908 fprintf (acfg->fp, ".code 16\n");
911 static G_GNUC_UNUSED void
912 emit_set_arm_mode (MonoAotCompile *acfg)
914 emit_unset_mode (acfg);
915 fprintf (acfg->fp, ".code 32\n");
918 static inline void
919 emit_code_bytes (MonoAotCompile *acfg, const guint8* buf, int size)
921 #ifdef TARGET_ARM64
922 int i;
924 g_assert (size % 4 == 0);
925 emit_unset_mode (acfg);
926 for (i = 0; i < size; i += 4)
927 fprintf (acfg->fp, "%s 0x%x\n", acfg->inst_directive, *(guint32*)(buf + i));
928 #else
929 emit_bytes (acfg, buf, size);
930 #endif
933 /* ARCHITECTURE SPECIFIC CODE */
935 #if defined(TARGET_X86) || defined(TARGET_AMD64) || defined(TARGET_ARM) || defined(TARGET_POWERPC) || defined(TARGET_ARM64)
936 #define EMIT_DWARF_INFO 1
937 #endif
939 #ifdef TARGET_WIN32_MSVC
940 #undef EMIT_DWARF_INFO
941 #define EMIT_WIN32_CODEVIEW_INFO
942 #endif
944 #ifdef EMIT_WIN32_UNWIND_INFO
945 static UnwindInfoSectionCacheItem *
946 get_cached_unwind_info_section_item_win32 (MonoAotCompile *acfg, const char *function_start, const char *function_end, GSList *unwind_ops);
948 static void
949 free_unwind_info_section_cache_win32 (MonoAotCompile *acfg);
951 static void
952 emit_unwind_info_data_win32 (MonoAotCompile *acfg, PUNWIND_INFO unwind_info);
954 static void
955 emit_unwind_info_sections_win32 (MonoAotCompile *acfg, const char *function_start, const char *function_end, GSList *unwind_ops);
956 #endif
958 static void
959 arch_free_unwind_info_section_cache (MonoAotCompile *acfg)
961 #ifdef EMIT_WIN32_UNWIND_INFO
962 free_unwind_info_section_cache_win32 (acfg);
963 #endif
966 static void
967 arch_emit_unwind_info_sections (MonoAotCompile *acfg, const char *function_start, const char *function_end, GSList *unwind_ops)
969 #ifdef EMIT_WIN32_UNWIND_INFO
970 gboolean own_unwind_ops = FALSE;
971 if (!unwind_ops) {
972 unwind_ops = mono_unwind_get_cie_program ();
973 own_unwind_ops = TRUE;
976 emit_unwind_info_sections_win32 (acfg, function_start, function_end, unwind_ops);
978 if (own_unwind_ops)
979 mono_free_unwind_info (unwind_ops);
980 #endif
983 #if defined(TARGET_ARM)
984 #define AOT_FUNC_ALIGNMENT 4
985 #else
986 #define AOT_FUNC_ALIGNMENT 16
987 #endif
989 #if defined(TARGET_POWERPC64) && !defined(__mono_ilp32__)
990 #define PPC_LD_OP "ld"
991 #define PPC_LDX_OP "ldx"
992 #else
993 #define PPC_LD_OP "lwz"
994 #define PPC_LDX_OP "lwzx"
995 #endif
997 #ifdef TARGET_X86_64_WIN32_MSVC
998 #define AOT_TARGET_STR "AMD64 (WIN32) (MSVC codegen)"
999 #elif TARGET_AMD64
1000 #define AOT_TARGET_STR "AMD64"
1001 #endif
1003 #ifdef TARGET_ARM
1004 #ifdef TARGET_MACH
1005 #define AOT_TARGET_STR "ARM (MACH)"
1006 #else
1007 #define AOT_TARGET_STR "ARM (!MACH)"
1008 #endif
1009 #endif
1011 #ifdef TARGET_ARM64
1012 #ifdef TARGET_MACH
1013 #define AOT_TARGET_STR "ARM64 (MACH)"
1014 #else
1015 #define AOT_TARGET_STR "ARM64 (!MACH)"
1016 #endif
1017 #endif
1019 #ifdef TARGET_POWERPC64
1020 #ifdef __mono_ilp32__
1021 #define AOT_TARGET_STR "POWERPC64 (mono ilp32)"
1022 #else
1023 #define AOT_TARGET_STR "POWERPC64 (!mono ilp32)"
1024 #endif
1025 #else
1026 #ifdef TARGET_POWERPC
1027 #ifdef __mono_ilp32__
1028 #define AOT_TARGET_STR "POWERPC (mono ilp32)"
1029 #else
1030 #define AOT_TARGET_STR "POWERPC (!mono ilp32)"
1031 #endif
1032 #endif
1033 #endif
1035 #ifdef TARGET_X86
1036 #ifdef TARGET_WIN32
1037 #define AOT_TARGET_STR "X86 (WIN32)"
1038 #else
1039 #define AOT_TARGET_STR "X86"
1040 #endif
1041 #endif
1043 #ifndef AOT_TARGET_STR
1044 #define AOT_TARGET_STR ""
1045 #endif
1047 static void
1048 arch_init (MonoAotCompile *acfg)
1050 acfg->llc_args = g_string_new ("");
1051 acfg->as_args = g_string_new ("");
1052 acfg->llvm_owriter_supported = TRUE;
1055 * The prefix LLVM likes to put in front of symbol names on darwin.
1056 * The mach-os specs require this for globals, but LLVM puts them in front of all
1057 * symbols. We need to handle this, since we need to refer to LLVM generated
1058 * symbols.
1060 acfg->llvm_label_prefix = "";
1061 acfg->user_symbol_prefix = "";
1063 #if defined(TARGET_X86)
1064 g_string_append (acfg->llc_args, " -march=x86 -mattr=sse4.1");
1065 #endif
1067 #if defined(TARGET_AMD64)
1068 g_string_append (acfg->llc_args, " -march=x86-64 -mattr=sse4.1");
1069 /* NOP */
1070 acfg->align_pad_value = 0x90;
1071 #endif
1073 #ifdef TARGET_ARM
1074 if (acfg->aot_opts.mtriple && strstr (acfg->aot_opts.mtriple, "darwin")) {
1075 g_string_append (acfg->llc_args, "-mattr=+v6");
1076 } else {
1077 #if defined(ARM_FPU_VFP_HARD)
1078 g_string_append (acfg->llc_args, " -mattr=+vfp2,-neon,+d16 -float-abi=hard");
1079 g_string_append (acfg->as_args, " -mfpu=vfp3");
1080 #elif defined(ARM_FPU_VFP)
1081 g_string_append (acfg->llc_args, " -mattr=+vfp2,-neon,+d16");
1082 g_string_append (acfg->as_args, " -mfpu=vfp3");
1083 #else
1084 g_string_append (acfg->llc_args, " -soft-float");
1085 #endif
1087 if (acfg->aot_opts.mtriple && strstr (acfg->aot_opts.mtriple, "thumb"))
1088 acfg->thumb_mixed = TRUE;
1090 if (acfg->aot_opts.mtriple)
1091 mono_arch_set_target (acfg->aot_opts.mtriple);
1092 #endif
1094 #ifdef TARGET_ARM64
1095 acfg->inst_directive = ".inst";
1096 if (acfg->aot_opts.mtriple)
1097 mono_arch_set_target (acfg->aot_opts.mtriple);
1098 #endif
1100 #ifdef TARGET_MACH
1101 acfg->user_symbol_prefix = "_";
1102 acfg->llvm_label_prefix = "_";
1103 acfg->inst_directive = ".word";
1104 acfg->need_no_dead_strip = TRUE;
1105 acfg->aot_opts.gnu_asm = TRUE;
1106 #endif
1108 #if defined(__linux__) && !defined(TARGET_ARM)
1109 acfg->need_pt_gnu_stack = TRUE;
1110 #endif
1112 #ifdef MONOTOUCH
1113 acfg->global_symbols = TRUE;
1114 #endif
1116 #ifdef TARGET_ANDROID
1117 acfg->llvm_owriter_supported = FALSE;
1118 #endif
1121 #ifdef TARGET_ARM64
1124 /* Load the contents of GOT_SLOT into dreg, clobbering ip0 */
1125 static void
1126 arm64_emit_load_got_slot (MonoAotCompile *acfg, int dreg, int got_slot)
1128 int offset;
1130 g_assert (acfg->fp);
1131 emit_unset_mode (acfg);
1132 /* r16==ip0 */
1133 offset = (int)(got_slot * sizeof (gpointer));
1134 #ifdef TARGET_MACH
1135 /* clang's integrated assembler */
1136 fprintf (acfg->fp, "adrp x16, %s@PAGE+%d\n", acfg->got_symbol, offset & 0xfffff000);
1137 fprintf (acfg->fp, "add x16, x16, %s@PAGEOFF\n", acfg->got_symbol);
1138 fprintf (acfg->fp, "ldr x%d, [x16, #%d]\n", dreg, offset & 0xfff);
1139 #else
1140 /* Linux GAS */
1141 fprintf (acfg->fp, "adrp x16, %s+%d\n", acfg->got_symbol, offset & 0xfffff000);
1142 fprintf (acfg->fp, "add x16, x16, :lo12:%s\n", acfg->got_symbol);
1143 fprintf (acfg->fp, "ldr x%d, [x16, %d]\n", dreg, offset & 0xfff);
1144 #endif
1147 static void
1148 arm64_emit_objc_selector_ref (MonoAotCompile *acfg, guint8 *code, int index, int *code_size)
1150 int reg;
1152 g_assert (acfg->fp);
1153 emit_unset_mode (acfg);
1155 /* ldr rt, target */
1156 reg = arm_get_ldr_lit_reg (code);
1158 fprintf (acfg->fp, "adrp x%d, L_OBJC_SELECTOR_REFERENCES_%d@PAGE\n", reg, index);
1159 fprintf (acfg->fp, "add x%d, x%d, L_OBJC_SELECTOR_REFERENCES_%d@PAGEOFF\n", reg, reg, index);
1160 fprintf (acfg->fp, "ldr x%d, [x%d]\n", reg, reg);
1162 *code_size = 12;
1165 static void
1166 arm64_emit_direct_call (MonoAotCompile *acfg, const char *target, gboolean external, gboolean thumb, MonoJumpInfo *ji, int *call_size)
1168 g_assert (acfg->fp);
1169 emit_unset_mode (acfg);
1170 if (ji && ji->relocation == MONO_R_ARM64_B) {
1171 fprintf (acfg->fp, "b %s\n", target);
1172 } else {
1173 if (ji)
1174 g_assert (ji->relocation == MONO_R_ARM64_BL);
1175 fprintf (acfg->fp, "bl %s\n", target);
1177 *call_size = 4;
1180 static void
1181 arm64_emit_got_access (MonoAotCompile *acfg, guint8 *code, int got_slot, int *code_size)
1183 int reg;
1185 /* ldr rt, target */
1186 reg = arm_get_ldr_lit_reg (code);
1187 arm64_emit_load_got_slot (acfg, reg, got_slot);
1188 *code_size = 12;
1191 static void
1192 arm64_emit_plt_entry (MonoAotCompile *acfg, const char *got_symbol, int offset, int info_offset)
1194 arm64_emit_load_got_slot (acfg, ARMREG_R16, offset / sizeof (gpointer));
1195 fprintf (acfg->fp, "br x16\n");
1196 /* Used by mono_aot_get_plt_info_offset () */
1197 fprintf (acfg->fp, "%s %d\n", acfg->inst_directive, info_offset);
1200 static void
1201 arm64_emit_tramp_page_common_code (MonoAotCompile *acfg, int pagesize, int arg_reg, int *size)
1203 guint8 buf [256];
1204 guint8 *code;
1205 int imm;
1207 /* The common code */
1208 code = buf;
1209 imm = pagesize;
1210 /* The trampoline address is in IP0 */
1211 arm_movzx (code, ARMREG_IP1, imm & 0xffff, 0);
1212 arm_movkx (code, ARMREG_IP1, (imm >> 16) & 0xffff, 16);
1213 /* Compute the data slot address */
1214 arm_subx (code, ARMREG_IP0, ARMREG_IP0, ARMREG_IP1);
1215 /* Trampoline argument */
1216 arm_ldrx (code, arg_reg, ARMREG_IP0, 0);
1217 /* Address */
1218 arm_ldrx (code, ARMREG_IP0, ARMREG_IP0, 8);
1219 arm_brx (code, ARMREG_IP0);
1221 /* Emit it */
1222 emit_code_bytes (acfg, buf, code - buf);
1224 *size = code - buf;
1227 static void
1228 arm64_emit_tramp_page_specific_code (MonoAotCompile *acfg, int pagesize, int common_tramp_size, int specific_tramp_size)
1230 guint8 buf [256];
1231 guint8 *code;
1232 int i, count;
1234 count = (pagesize - common_tramp_size) / specific_tramp_size;
1235 for (i = 0; i < count; ++i) {
1236 code = buf;
1237 arm_adrx (code, ARMREG_IP0, code);
1238 /* Branch to the generic code */
1239 arm_b (code, code - 4 - (i * specific_tramp_size) - common_tramp_size);
1240 /* This has to be 2 pointers long */
1241 arm_nop (code);
1242 arm_nop (code);
1243 g_assert (code - buf == specific_tramp_size);
1244 emit_code_bytes (acfg, buf, code - buf);
1248 static void
1249 arm64_emit_specific_trampoline_pages (MonoAotCompile *acfg)
1251 guint8 buf [128];
1252 guint8 *code;
1253 guint8 *labels [16];
1254 int common_tramp_size;
1255 int specific_tramp_size = 2 * 8;
1256 int imm, pagesize;
1257 char symbol [128];
1259 if (!acfg->aot_opts.use_trampolines_page)
1260 return;
1262 #ifdef TARGET_MACH
1263 /* Have to match the target pagesize */
1264 pagesize = 16384;
1265 #else
1266 pagesize = mono_pagesize ();
1267 #endif
1268 acfg->tramp_page_size = pagesize;
1270 /* The specific trampolines */
1271 sprintf (symbol, "%sspecific_trampolines_page", acfg->user_symbol_prefix);
1272 emit_alignment (acfg, pagesize);
1273 emit_global (acfg, symbol, TRUE);
1274 emit_label (acfg, symbol);
1276 /* The common code */
1277 arm64_emit_tramp_page_common_code (acfg, pagesize, ARMREG_IP1, &common_tramp_size);
1278 acfg->tramp_page_code_offsets [MONO_AOT_TRAMP_SPECIFIC] = common_tramp_size;
1280 arm64_emit_tramp_page_specific_code (acfg, pagesize, common_tramp_size, specific_tramp_size);
1282 /* The rgctx trampolines */
1283 /* These are the same as the specific trampolines, but they load the argument into MONO_ARCH_RGCTX_REG */
1284 sprintf (symbol, "%srgctx_trampolines_page", acfg->user_symbol_prefix);
1285 emit_alignment (acfg, pagesize);
1286 emit_global (acfg, symbol, TRUE);
1287 emit_label (acfg, symbol);
1289 /* The common code */
1290 arm64_emit_tramp_page_common_code (acfg, pagesize, MONO_ARCH_RGCTX_REG, &common_tramp_size);
1291 acfg->tramp_page_code_offsets [MONO_AOT_TRAMP_STATIC_RGCTX] = common_tramp_size;
1293 arm64_emit_tramp_page_specific_code (acfg, pagesize, common_tramp_size, specific_tramp_size);
1295 /* The gsharedvt arg trampolines */
1296 /* These are the same as the specific trampolines */
1297 sprintf (symbol, "%sgsharedvt_arg_trampolines_page", acfg->user_symbol_prefix);
1298 emit_alignment (acfg, pagesize);
1299 emit_global (acfg, symbol, TRUE);
1300 emit_label (acfg, symbol);
1302 arm64_emit_tramp_page_common_code (acfg, pagesize, ARMREG_IP1, &common_tramp_size);
1303 acfg->tramp_page_code_offsets [MONO_AOT_TRAMP_GSHAREDVT_ARG] = common_tramp_size;
1305 arm64_emit_tramp_page_specific_code (acfg, pagesize, common_tramp_size, specific_tramp_size);
1307 /* The IMT trampolines */
1308 sprintf (symbol, "%simt_trampolines_page", acfg->user_symbol_prefix);
1309 emit_alignment (acfg, pagesize);
1310 emit_global (acfg, symbol, TRUE);
1311 emit_label (acfg, symbol);
1313 code = buf;
1314 imm = pagesize;
1315 /* The trampoline address is in IP0 */
1316 arm_movzx (code, ARMREG_IP1, imm & 0xffff, 0);
1317 arm_movkx (code, ARMREG_IP1, (imm >> 16) & 0xffff, 16);
1318 /* Compute the data slot address */
1319 arm_subx (code, ARMREG_IP0, ARMREG_IP0, ARMREG_IP1);
1320 /* Trampoline argument */
1321 arm_ldrx (code, ARMREG_IP1, ARMREG_IP0, 0);
1323 /* Same as arch_emit_imt_trampoline () */
1324 labels [0] = code;
1325 arm_ldrx (code, ARMREG_IP0, ARMREG_IP1, 0);
1326 arm_cmpx (code, ARMREG_IP0, MONO_ARCH_RGCTX_REG);
1327 labels [1] = code;
1328 arm_bcc (code, ARMCOND_EQ, 0);
1330 /* End-of-loop check */
1331 labels [2] = code;
1332 arm_cbzx (code, ARMREG_IP0, 0);
1334 /* Loop footer */
1335 arm_addx_imm (code, ARMREG_IP1, ARMREG_IP1, 2 * 8);
1336 arm_b (code, labels [0]);
1338 /* Match */
1339 mono_arm_patch (labels [1], code, MONO_R_ARM64_BCC);
1340 /* Load vtable slot addr */
1341 arm_ldrx (code, ARMREG_IP0, ARMREG_IP1, 8);
1342 /* Load vtable slot */
1343 arm_ldrx (code, ARMREG_IP0, ARMREG_IP0, 0);
1344 arm_brx (code, ARMREG_IP0);
1346 /* No match */
1347 mono_arm_patch (labels [2], code, MONO_R_ARM64_CBZ);
1348 /* Load fail addr */
1349 arm_ldrx (code, ARMREG_IP0, ARMREG_IP1, 8);
1350 arm_brx (code, ARMREG_IP0);
1352 emit_code_bytes (acfg, buf, code - buf);
1354 common_tramp_size = code - buf;
1355 acfg->tramp_page_code_offsets [MONO_AOT_TRAMP_IMT] = common_tramp_size;
1357 arm64_emit_tramp_page_specific_code (acfg, pagesize, common_tramp_size, specific_tramp_size);
1360 static void
1361 arm64_emit_specific_trampoline (MonoAotCompile *acfg, int offset, int *tramp_size)
1363 /* Load argument from second GOT slot */
1364 arm64_emit_load_got_slot (acfg, ARMREG_R17, offset + 1);
1365 /* Load generic trampoline address from first GOT slot */
1366 arm64_emit_load_got_slot (acfg, ARMREG_R16, offset);
1367 fprintf (acfg->fp, "br x16\n");
1368 *tramp_size = 7 * 4;
1371 static void
1372 arm64_emit_unbox_trampoline (MonoAotCompile *acfg, MonoCompile *cfg, MonoMethod *method, const char *call_target)
1374 emit_unset_mode (acfg);
1375 fprintf (acfg->fp, "add x0, x0, %d\n", (int)(sizeof (MonoObject)));
1376 fprintf (acfg->fp, "b %s\n", call_target);
1379 static void
1380 arm64_emit_static_rgctx_trampoline (MonoAotCompile *acfg, int offset, int *tramp_size)
1382 /* Similar to the specific trampolines, but use the rgctx reg instead of ip1 */
1384 /* Load argument from first GOT slot */
1385 arm64_emit_load_got_slot (acfg, MONO_ARCH_RGCTX_REG, offset);
1386 /* Load generic trampoline address from second GOT slot */
1387 arm64_emit_load_got_slot (acfg, ARMREG_R16, offset + 1);
1388 fprintf (acfg->fp, "br x16\n");
1389 *tramp_size = 7 * 4;
1392 static void
1393 arm64_emit_imt_trampoline (MonoAotCompile *acfg, int offset, int *tramp_size)
1395 guint8 buf [128];
1396 guint8 *code, *labels [16];
1398 /* Load parameter from GOT slot into ip1 */
1399 arm64_emit_load_got_slot (acfg, ARMREG_R17, offset);
1401 code = buf;
1402 labels [0] = code;
1403 arm_ldrx (code, ARMREG_IP0, ARMREG_IP1, 0);
1404 arm_cmpx (code, ARMREG_IP0, MONO_ARCH_RGCTX_REG);
1405 labels [1] = code;
1406 arm_bcc (code, ARMCOND_EQ, 0);
1408 /* End-of-loop check */
1409 labels [2] = code;
1410 arm_cbzx (code, ARMREG_IP0, 0);
1412 /* Loop footer */
1413 arm_addx_imm (code, ARMREG_IP1, ARMREG_IP1, 2 * 8);
1414 arm_b (code, labels [0]);
1416 /* Match */
1417 mono_arm_patch (labels [1], code, MONO_R_ARM64_BCC);
1418 /* Load vtable slot addr */
1419 arm_ldrx (code, ARMREG_IP0, ARMREG_IP1, 8);
1420 /* Load vtable slot */
1421 arm_ldrx (code, ARMREG_IP0, ARMREG_IP0, 0);
1422 arm_brx (code, ARMREG_IP0);
1424 /* No match */
1425 mono_arm_patch (labels [2], code, MONO_R_ARM64_CBZ);
1426 /* Load fail addr */
1427 arm_ldrx (code, ARMREG_IP0, ARMREG_IP1, 8);
1428 arm_brx (code, ARMREG_IP0);
1430 emit_code_bytes (acfg, buf, code - buf);
1432 *tramp_size = code - buf + (3 * 4);
1435 static void
1436 arm64_emit_gsharedvt_arg_trampoline (MonoAotCompile *acfg, int offset, int *tramp_size)
1438 /* Similar to the specific trampolines, but the address is in the second slot */
1439 /* Load argument from first GOT slot */
1440 arm64_emit_load_got_slot (acfg, ARMREG_R17, offset);
1441 /* Load generic trampoline address from second GOT slot */
1442 arm64_emit_load_got_slot (acfg, ARMREG_R16, offset + 1);
1443 fprintf (acfg->fp, "br x16\n");
1444 *tramp_size = 7 * 4;
1448 #endif
1450 #ifdef MONO_ARCH_AOT_SUPPORTED
1452 * arch_emit_direct_call:
1454 * Emit a direct call to the symbol TARGET. CALL_SIZE is set to the size of the
1455 * calling code.
1457 static void
1458 arch_emit_direct_call (MonoAotCompile *acfg, const char *target, gboolean external, gboolean thumb, MonoJumpInfo *ji, int *call_size)
1460 #if defined(TARGET_X86) || defined(TARGET_AMD64)
1461 /* Need to make sure this is exactly 5 bytes long */
1462 emit_unset_mode (acfg);
1463 fprintf (acfg->fp, "call %s\n", target);
1464 *call_size = 5;
1465 #elif defined(TARGET_ARM)
1466 emit_unset_mode (acfg);
1467 if (thumb)
1468 fprintf (acfg->fp, "blx %s\n", target);
1469 else
1470 fprintf (acfg->fp, "bl %s\n", target);
1471 *call_size = 4;
1472 #elif defined(TARGET_ARM64)
1473 arm64_emit_direct_call (acfg, target, external, thumb, ji, call_size);
1474 #elif defined(TARGET_POWERPC)
1475 emit_unset_mode (acfg);
1476 fprintf (acfg->fp, "bl %s\n", target);
1477 *call_size = 4;
1478 #else
1479 g_assert_not_reached ();
1480 #endif
1482 #endif
1485 * PPC32 design:
1486 * - we use an approach similar to the x86 abi: reserve a register (r30) to hold
1487 * the GOT pointer.
1488 * - The full-aot trampolines need access to the GOT of mscorlib, so we store
1489 * in in the 2. slot of every GOT, and require every method to place the GOT
1490 * address in r30, even when it doesn't access the GOT otherwise. This way,
1491 * the trampolines can compute the mscorlib GOT address by loading 4(r30).
1495 * PPC64 design:
1496 * PPC64 uses function descriptors which greatly complicate all code, since
1497 * these are used very inconsistently in the runtime. Some functions like
1498 * mono_compile_method () return ftn descriptors, while others like the
1499 * trampoline creation functions do not.
1500 * We assume that all GOT slots contain function descriptors, and create
1501 * descriptors in aot-runtime.c when needed.
1502 * The ppc64 abi uses r2 to hold the address of the TOC/GOT, which is loaded
1503 * from function descriptors, we could do the same, but it would require
1504 * rewriting all the ppc/aot code to handle function descriptors properly.
1505 * So instead, we use the same approach as on PPC32.
1506 * This is a horrible mess, but fixing it would probably lead to an even bigger
1507 * one.
1511 * X86 design:
1512 * - similar to the PPC32 design, we reserve EBX to hold the GOT pointer.
1515 #ifdef MONO_ARCH_AOT_SUPPORTED
1517 * arch_emit_got_offset:
1519 * The memory pointed to by CODE should hold native code for computing the GOT
1520 * address (OP_LOAD_GOTADDR). Emit this code while patching it with the offset
1521 * between code and the GOT. CODE_SIZE is set to the number of bytes emitted.
1523 static void
1524 arch_emit_got_offset (MonoAotCompile *acfg, guint8 *code, int *code_size)
1526 #if defined(TARGET_POWERPC64)
1527 emit_unset_mode (acfg);
1529 * The ppc32 code doesn't seem to work on ppc64, the assembler complains about
1530 * unsupported relocations. So we store the got address into the .Lgot_addr
1531 * symbol which is in the text segment, compute its address, and load it.
1533 fprintf (acfg->fp, ".L%d:\n", acfg->label_generator);
1534 fprintf (acfg->fp, "lis 0, (.Lgot_addr + 4 - .L%d)@h\n", acfg->label_generator);
1535 fprintf (acfg->fp, "ori 0, 0, (.Lgot_addr + 4 - .L%d)@l\n", acfg->label_generator);
1536 fprintf (acfg->fp, "add 30, 30, 0\n");
1537 fprintf (acfg->fp, "%s 30, 0(30)\n", PPC_LD_OP);
1538 acfg->label_generator ++;
1539 *code_size = 16;
1540 #elif defined(TARGET_POWERPC)
1541 emit_unset_mode (acfg);
1542 fprintf (acfg->fp, ".L%d:\n", acfg->label_generator);
1543 fprintf (acfg->fp, "lis 0, (%s + 4 - .L%d)@h\n", acfg->got_symbol, acfg->label_generator);
1544 fprintf (acfg->fp, "ori 0, 0, (%s + 4 - .L%d)@l\n", acfg->got_symbol, acfg->label_generator);
1545 acfg->label_generator ++;
1546 *code_size = 8;
1547 #else
1548 guint32 offset = mono_arch_get_patch_offset (code);
1549 emit_bytes (acfg, code, offset);
1550 emit_symbol_diff (acfg, acfg->got_symbol, ".", offset);
1552 *code_size = offset + 4;
1553 #endif
1557 * arch_emit_got_access:
1559 * The memory pointed to by CODE should hold native code for loading a GOT
1560 * slot (OP_AOTCONST/OP_GOT_ENTRY). Emit this code while patching it so it accesses the
1561 * GOT slot GOT_SLOT. CODE_SIZE is set to the number of bytes emitted.
1563 static void
1564 arch_emit_got_access (MonoAotCompile *acfg, const char *got_symbol, guint8 *code, int got_slot, int *code_size)
1566 #ifdef TARGET_AMD64
1567 /* mov reg, got+offset(%rip) */
1568 if (acfg->llvm) {
1569 /* The GOT symbol is in the LLVM module, the clang assembler has problems emitting symbol diffs for it */
1570 int dreg;
1571 int rex_r;
1573 /* Decode reg, see amd64_mov_reg_membase () */
1574 rex_r = code [0] & AMD64_REX_R;
1575 g_assert (code [0] == 0x49 + rex_r);
1576 g_assert (code [1] == 0x8b);
1577 dreg = ((code [2] >> 3) & 0x7) + (rex_r ? 8 : 0);
1579 emit_unset_mode (acfg);
1580 fprintf (acfg->fp, "mov %s+%d(%%rip), %s\n", got_symbol, (unsigned int) ((got_slot * sizeof (gpointer))), mono_arch_regname (dreg));
1581 *code_size = 7;
1582 } else {
1583 emit_bytes (acfg, code, mono_arch_get_patch_offset (code));
1584 emit_symbol_diff (acfg, got_symbol, ".", (unsigned int) ((got_slot * sizeof (gpointer)) - 4));
1585 *code_size = mono_arch_get_patch_offset (code) + 4;
1587 #elif defined(TARGET_X86)
1588 emit_bytes (acfg, code, mono_arch_get_patch_offset (code));
1589 emit_int32 (acfg, (unsigned int) ((got_slot * sizeof (gpointer))));
1590 *code_size = mono_arch_get_patch_offset (code) + 4;
1591 #elif defined(TARGET_ARM)
1592 emit_bytes (acfg, code, mono_arch_get_patch_offset (code));
1593 emit_symbol_diff (acfg, got_symbol, ".", (unsigned int) ((got_slot * sizeof (gpointer))) - 12);
1594 *code_size = mono_arch_get_patch_offset (code) + 4;
1595 #elif defined(TARGET_ARM64)
1596 emit_bytes (acfg, code, mono_arch_get_patch_offset (code));
1597 arm64_emit_got_access (acfg, code, got_slot, code_size);
1598 #elif defined(TARGET_POWERPC)
1600 guint8 buf [32];
1602 emit_bytes (acfg, code, mono_arch_get_patch_offset (code));
1603 code = buf;
1604 ppc_load32 (code, ppc_r0, got_slot * sizeof (gpointer));
1605 g_assert (code - buf == 8);
1606 emit_bytes (acfg, buf, code - buf);
1607 *code_size = code - buf;
1609 #else
1610 g_assert_not_reached ();
1611 #endif
1614 #endif
1616 #ifdef MONO_ARCH_AOT_SUPPORTED
1618 * arch_emit_objc_selector_ref:
1620 * Emit the implementation of OP_OBJC_GET_SELECTOR, which itself implements @selector(foo:) in objective-c.
1622 static void
1623 arch_emit_objc_selector_ref (MonoAotCompile *acfg, guint8 *code, int index, int *code_size)
1625 #if defined(TARGET_ARM)
1626 char symbol1 [MAX_SYMBOL_SIZE];
1627 char symbol2 [MAX_SYMBOL_SIZE];
1628 int lindex = acfg->objc_selector_index_2 ++;
1630 /* Emit ldr.imm/b */
1631 emit_bytes (acfg, code, 8);
1633 sprintf (symbol1, "L_OBJC_SELECTOR_%d", lindex);
1634 sprintf (symbol2, "L_OBJC_SELECTOR_REFERENCES_%d", index);
1636 emit_label (acfg, symbol1);
1637 mono_img_writer_emit_unset_mode (acfg->w);
1638 fprintf (acfg->fp, ".long %s-(%s+12)", symbol2, symbol1);
1640 *code_size = 12;
1641 #elif defined(TARGET_ARM64)
1642 arm64_emit_objc_selector_ref (acfg, code, index, code_size);
1643 #else
1644 g_assert_not_reached ();
1645 #endif
1647 #endif
1650 * arch_emit_plt_entry:
1652 * Emit code for the PLT entry.
1653 * The plt entry should look like this:
1654 * <indirect jump to GOT_SYMBOL + OFFSET>
1655 * <INFO_OFFSET embedded into the instruction stream>
1657 static void
1658 arch_emit_plt_entry (MonoAotCompile *acfg, const char *got_symbol, int offset, int info_offset)
1660 #if defined(TARGET_X86)
1661 /* jmp *<offset>(%ebx) */
1662 emit_byte (acfg, 0xff);
1663 emit_byte (acfg, 0xa3);
1664 emit_int32 (acfg, offset);
1665 /* Used by mono_aot_get_plt_info_offset */
1666 emit_int32 (acfg, info_offset);
1667 #elif defined(TARGET_AMD64)
1668 emit_unset_mode (acfg);
1669 fprintf (acfg->fp, "jmp *%s+%d(%%rip)\n", got_symbol, offset);
1670 /* Used by mono_aot_get_plt_info_offset */
1671 emit_int32 (acfg, info_offset);
1672 acfg->stats.plt_size += 10;
1673 #elif defined(TARGET_ARM)
1674 guint8 buf [256];
1675 guint8 *code;
1677 code = buf;
1678 ARM_LDR_IMM (code, ARMREG_IP, ARMREG_PC, 0);
1679 ARM_LDR_REG_REG (code, ARMREG_PC, ARMREG_PC, ARMREG_IP);
1680 emit_bytes (acfg, buf, code - buf);
1681 emit_symbol_diff (acfg, got_symbol, ".", offset - 4);
1682 /* Used by mono_aot_get_plt_info_offset */
1683 emit_int32 (acfg, info_offset);
1684 #elif defined(TARGET_ARM64)
1685 arm64_emit_plt_entry (acfg, got_symbol, offset, info_offset);
1686 #elif defined(TARGET_POWERPC)
1687 /* The GOT address is guaranteed to be in r30 by OP_LOAD_GOTADDR */
1688 emit_unset_mode (acfg);
1689 fprintf (acfg->fp, "lis 11, %d@h\n", offset);
1690 fprintf (acfg->fp, "ori 11, 11, %d@l\n", offset);
1691 fprintf (acfg->fp, "add 11, 11, 30\n");
1692 fprintf (acfg->fp, "%s 11, 0(11)\n", PPC_LD_OP);
1693 #ifdef PPC_USES_FUNCTION_DESCRIPTOR
1694 fprintf (acfg->fp, "%s 2, %d(11)\n", PPC_LD_OP, (int)sizeof (gpointer));
1695 fprintf (acfg->fp, "%s 11, 0(11)\n", PPC_LD_OP);
1696 #endif
1697 fprintf (acfg->fp, "mtctr 11\n");
1698 fprintf (acfg->fp, "bctr\n");
1699 emit_int32 (acfg, info_offset);
1700 #else
1701 g_assert_not_reached ();
1702 #endif
1706 * arch_emit_llvm_plt_entry:
1708 * Same as arch_emit_plt_entry, but handles calls from LLVM generated code.
1709 * This is only needed on arm to handle thumb interop.
1711 static void
1712 arch_emit_llvm_plt_entry (MonoAotCompile *acfg, const char *got_symbol, int offset, int info_offset)
1714 #if defined(TARGET_ARM)
1715 /* LLVM calls the PLT entries using bl, so these have to be thumb2 */
1716 /* The caller already transitioned to thumb */
1717 /* The code below should be 12 bytes long */
1718 /* clang has trouble encoding these instructions, so emit the binary */
1719 #if 0
1720 fprintf (acfg->fp, "ldr ip, [pc, #8]\n");
1721 /* thumb can't encode ld pc, [pc, ip] */
1722 fprintf (acfg->fp, "add ip, pc, ip\n");
1723 fprintf (acfg->fp, "ldr ip, [ip, #0]\n");
1724 fprintf (acfg->fp, "bx ip\n");
1725 #endif
1726 emit_set_thumb_mode (acfg);
1727 fprintf (acfg->fp, ".4byte 0xc008f8df\n");
1728 fprintf (acfg->fp, ".2byte 0x44fc\n");
1729 fprintf (acfg->fp, ".4byte 0xc000f8dc\n");
1730 fprintf (acfg->fp, ".2byte 0x4760\n");
1731 emit_symbol_diff (acfg, got_symbol, ".", offset + 4);
1732 emit_int32 (acfg, info_offset);
1733 emit_unset_mode (acfg);
1734 emit_set_arm_mode (acfg);
1735 #else
1736 g_assert_not_reached ();
1737 #endif
1740 /* Save unwind_info in the module and emit the offset to the information at symbol */
1741 static void save_unwind_info (MonoAotCompile *acfg, char *symbol, GSList *unwind_ops)
1743 guint32 uw_offset, encoded_len;
1744 guint8 *encoded;
1746 emit_section_change (acfg, RODATA_SECT, 0);
1747 emit_global (acfg, symbol, FALSE);
1748 emit_label (acfg, symbol);
1750 encoded = mono_unwind_ops_encode (unwind_ops, &encoded_len);
1751 uw_offset = get_unwind_info_offset (acfg, encoded, encoded_len);
1752 g_free (encoded);
1753 emit_int32 (acfg, uw_offset);
1757 * arch_emit_specific_trampoline_pages:
1759 * Emits a page full of trampolines: each trampoline uses its own address to
1760 * lookup both the generic trampoline code and the data argument.
1761 * This page can be remapped in process multiple times so we can get an
1762 * unlimited number of trampolines.
1763 * Specifically this implementation uses the following trick: two memory pages
1764 * are allocated, with the first containing the data and the second containing the trampolines.
1765 * To reduce trampoline size, each trampoline jumps at the start of the page where a common
1766 * implementation does all the lifting.
1767 * Note that the ARM single trampoline size is 8 bytes, exactly like the data that needs to be stored
1768 * on the arm 32 bit system.
1770 static void
1771 arch_emit_specific_trampoline_pages (MonoAotCompile *acfg)
1773 #if defined(TARGET_ARM)
1774 guint8 buf [128];
1775 guint8 *code;
1776 guint8 *loop_start, *loop_branch_back, *loop_end_check, *imt_found_check;
1777 int i;
1778 int pagesize = MONO_AOT_TRAMP_PAGE_SIZE;
1779 GSList *unwind_ops = NULL;
1780 #define COMMON_TRAMP_SIZE 16
1781 int count = (pagesize - COMMON_TRAMP_SIZE) / 8;
1782 int imm8, rot_amount;
1783 char symbol [128];
1785 if (!acfg->aot_opts.use_trampolines_page)
1786 return;
1788 acfg->tramp_page_size = pagesize;
1790 sprintf (symbol, "%sspecific_trampolines_page", acfg->user_symbol_prefix);
1791 emit_alignment (acfg, pagesize);
1792 emit_global (acfg, symbol, TRUE);
1793 emit_label (acfg, symbol);
1795 /* emit the generic code first, the trampoline address + 8 is in the lr register */
1796 code = buf;
1797 imm8 = mono_arm_is_rotated_imm8 (pagesize, &rot_amount);
1798 ARM_SUB_REG_IMM (code, ARMREG_LR, ARMREG_LR, imm8, rot_amount);
1799 ARM_LDR_IMM (code, ARMREG_R1, ARMREG_LR, -8);
1800 ARM_LDR_IMM (code, ARMREG_PC, ARMREG_LR, -4);
1801 ARM_NOP (code);
1802 g_assert (code - buf == COMMON_TRAMP_SIZE);
1804 /* Emit it */
1805 emit_bytes (acfg, buf, code - buf);
1807 for (i = 0; i < count; ++i) {
1808 code = buf;
1809 ARM_PUSH (code, 0x5fff);
1810 ARM_BL (code, 0);
1811 arm_patch (code - 4, code - COMMON_TRAMP_SIZE - 8 * (i + 1));
1812 g_assert (code - buf == 8);
1813 emit_bytes (acfg, buf, code - buf);
1816 /* now the rgctx trampolines: each specific trampolines puts in the ip register
1817 * the instruction pointer address, so the generic trampoline at the start of the page
1818 * subtracts 4096 to get to the data page and loads the values
1819 * We again fit the generic trampiline in 16 bytes.
1821 sprintf (symbol, "%srgctx_trampolines_page", acfg->user_symbol_prefix);
1822 emit_global (acfg, symbol, TRUE);
1823 emit_label (acfg, symbol);
1824 code = buf;
1825 imm8 = mono_arm_is_rotated_imm8 (pagesize, &rot_amount);
1826 ARM_SUB_REG_IMM (code, ARMREG_IP, ARMREG_IP, imm8, rot_amount);
1827 ARM_LDR_IMM (code, MONO_ARCH_RGCTX_REG, ARMREG_IP, -8);
1828 ARM_LDR_IMM (code, ARMREG_PC, ARMREG_IP, -4);
1829 ARM_NOP (code);
1830 g_assert (code - buf == COMMON_TRAMP_SIZE);
1832 /* Emit it */
1833 emit_bytes (acfg, buf, code - buf);
1835 for (i = 0; i < count; ++i) {
1836 code = buf;
1837 ARM_MOV_REG_REG (code, ARMREG_IP, ARMREG_PC);
1838 ARM_B (code, 0);
1839 arm_patch (code - 4, code - COMMON_TRAMP_SIZE - 8 * (i + 1));
1840 g_assert (code - buf == 8);
1841 emit_bytes (acfg, buf, code - buf);
1845 * gsharedvt arg trampolines: see arch_emit_gsharedvt_arg_trampoline ()
1847 sprintf (symbol, "%sgsharedvt_arg_trampolines_page", acfg->user_symbol_prefix);
1848 emit_global (acfg, symbol, TRUE);
1849 emit_label (acfg, symbol);
1850 code = buf;
1851 ARM_PUSH (code, (1 << ARMREG_R0) | (1 << ARMREG_R1) | (1 << ARMREG_R2) | (1 << ARMREG_R3));
1852 imm8 = mono_arm_is_rotated_imm8 (pagesize, &rot_amount);
1853 ARM_SUB_REG_IMM (code, ARMREG_IP, ARMREG_IP, imm8, rot_amount);
1854 ARM_LDR_IMM (code, ARMREG_R0, ARMREG_IP, -8);
1855 ARM_LDR_IMM (code, ARMREG_PC, ARMREG_IP, -4);
1856 g_assert (code - buf == COMMON_TRAMP_SIZE);
1857 /* Emit it */
1858 emit_bytes (acfg, buf, code - buf);
1860 for (i = 0; i < count; ++i) {
1861 code = buf;
1862 ARM_MOV_REG_REG (code, ARMREG_IP, ARMREG_PC);
1863 ARM_B (code, 0);
1864 arm_patch (code - 4, code - COMMON_TRAMP_SIZE - 8 * (i + 1));
1865 g_assert (code - buf == 8);
1866 emit_bytes (acfg, buf, code - buf);
1869 /* now the imt trampolines: each specific trampolines puts in the ip register
1870 * the instruction pointer address, so the generic trampoline at the start of the page
1871 * subtracts 4096 to get to the data page and loads the values
1873 #define IMT_TRAMP_SIZE 72
1874 sprintf (symbol, "%simt_trampolines_page", acfg->user_symbol_prefix);
1875 emit_global (acfg, symbol, TRUE);
1876 emit_label (acfg, symbol);
1877 code = buf;
1878 /* Need at least two free registers, plus a slot for storing the pc */
1879 ARM_PUSH (code, (1 << ARMREG_R0)|(1 << ARMREG_R1)|(1 << ARMREG_R2));
1881 imm8 = mono_arm_is_rotated_imm8 (pagesize, &rot_amount);
1882 ARM_SUB_REG_IMM (code, ARMREG_IP, ARMREG_IP, imm8, rot_amount);
1883 ARM_LDR_IMM (code, ARMREG_R0, ARMREG_IP, -8);
1885 /* The IMT method is in v5, r0 has the imt array address */
1887 loop_start = code;
1888 ARM_LDR_IMM (code, ARMREG_R1, ARMREG_R0, 0);
1889 ARM_CMP_REG_REG (code, ARMREG_R1, ARMREG_V5);
1890 imt_found_check = code;
1891 ARM_B_COND (code, ARMCOND_EQ, 0);
1893 /* End-of-loop check */
1894 ARM_CMP_REG_IMM (code, ARMREG_R1, 0, 0);
1895 loop_end_check = code;
1896 ARM_B_COND (code, ARMCOND_EQ, 0);
1898 /* Loop footer */
1899 ARM_ADD_REG_IMM8 (code, ARMREG_R0, ARMREG_R0, sizeof (gpointer) * 2);
1900 loop_branch_back = code;
1901 ARM_B (code, 0);
1902 arm_patch (loop_branch_back, loop_start);
1904 /* Match */
1905 arm_patch (imt_found_check, code);
1906 ARM_LDR_IMM (code, ARMREG_R0, ARMREG_R0, 4);
1907 ARM_LDR_IMM (code, ARMREG_R0, ARMREG_R0, 0);
1908 /* Save it to the third stack slot */
1909 ARM_STR_IMM (code, ARMREG_R0, ARMREG_SP, 8);
1910 /* Restore the registers and branch */
1911 ARM_POP (code, (1 << ARMREG_R0)|(1 << ARMREG_R1)|(1 << ARMREG_PC));
1913 /* No match */
1914 arm_patch (loop_end_check, code);
1915 ARM_LDR_IMM (code, ARMREG_R0, ARMREG_R0, 4);
1916 ARM_STR_IMM (code, ARMREG_R0, ARMREG_SP, 8);
1917 ARM_POP (code, (1 << ARMREG_R0)|(1 << ARMREG_R1)|(1 << ARMREG_PC));
1918 ARM_NOP (code);
1920 /* Emit it */
1921 g_assert (code - buf == IMT_TRAMP_SIZE);
1922 emit_bytes (acfg, buf, code - buf);
1924 for (i = 0; i < count; ++i) {
1925 code = buf;
1926 ARM_MOV_REG_REG (code, ARMREG_IP, ARMREG_PC);
1927 ARM_B (code, 0);
1928 arm_patch (code - 4, code - IMT_TRAMP_SIZE - 8 * (i + 1));
1929 g_assert (code - buf == 8);
1930 emit_bytes (acfg, buf, code - buf);
1933 acfg->tramp_page_code_offsets [MONO_AOT_TRAMP_SPECIFIC] = 16;
1934 acfg->tramp_page_code_offsets [MONO_AOT_TRAMP_STATIC_RGCTX] = 16;
1935 acfg->tramp_page_code_offsets [MONO_AOT_TRAMP_IMT] = 72;
1936 acfg->tramp_page_code_offsets [MONO_AOT_TRAMP_GSHAREDVT_ARG] = 16;
1938 /* Unwind info for specifc trampolines */
1939 sprintf (symbol, "%sspecific_trampolines_page_gen_p", acfg->user_symbol_prefix);
1940 /* We unwind to the original caller, from the stack, since lr is clobbered */
1941 mono_add_unwind_op_def_cfa (unwind_ops, 0, 0, ARMREG_SP, 14 * sizeof (mgreg_t));
1942 mono_add_unwind_op_offset (unwind_ops, 0, 0, ARMREG_LR, -4);
1943 save_unwind_info (acfg, symbol, unwind_ops);
1944 mono_free_unwind_info (unwind_ops);
1946 sprintf (symbol, "%sspecific_trampolines_page_sp_p", acfg->user_symbol_prefix);
1947 mono_add_unwind_op_def_cfa (unwind_ops, 0, 0, ARMREG_SP, 0);
1948 mono_add_unwind_op_def_cfa_offset (unwind_ops, 4, 0, 14 * sizeof (mgreg_t));
1949 save_unwind_info (acfg, symbol, unwind_ops);
1950 mono_free_unwind_info (unwind_ops);
1952 /* Unwind info for rgctx trampolines */
1953 sprintf (symbol, "%srgctx_trampolines_page_gen_p", acfg->user_symbol_prefix);
1954 mono_add_unwind_op_def_cfa (unwind_ops, 0, 0, ARMREG_SP, 0);
1955 save_unwind_info (acfg, symbol, unwind_ops);
1957 sprintf (symbol, "%srgctx_trampolines_page_sp_p", acfg->user_symbol_prefix);
1958 save_unwind_info (acfg, symbol, unwind_ops);
1959 mono_free_unwind_info (unwind_ops);
1961 /* Unwind info for gsharedvt trampolines */
1962 sprintf (symbol, "%sgsharedvt_trampolines_page_gen_p", acfg->user_symbol_prefix);
1963 mono_add_unwind_op_def_cfa (unwind_ops, 0, 0, ARMREG_SP, 0);
1964 mono_add_unwind_op_def_cfa_offset (unwind_ops, 4, 0, 4 * sizeof (mgreg_t));
1965 save_unwind_info (acfg, symbol, unwind_ops);
1966 mono_free_unwind_info (unwind_ops);
1968 sprintf (symbol, "%sgsharedvt_trampolines_page_sp_p", acfg->user_symbol_prefix);
1969 mono_add_unwind_op_def_cfa (unwind_ops, 0, 0, ARMREG_SP, 0);
1970 save_unwind_info (acfg, symbol, unwind_ops);
1971 mono_free_unwind_info (unwind_ops);
1973 /* Unwind info for imt trampolines */
1974 sprintf (symbol, "%simt_trampolines_page_gen_p", acfg->user_symbol_prefix);
1975 mono_add_unwind_op_def_cfa (unwind_ops, 0, 0, ARMREG_SP, 0);
1976 mono_add_unwind_op_def_cfa_offset (unwind_ops, 4, 0, 3 * sizeof (mgreg_t));
1977 save_unwind_info (acfg, symbol, unwind_ops);
1978 mono_free_unwind_info (unwind_ops);
1980 sprintf (symbol, "%simt_trampolines_page_sp_p", acfg->user_symbol_prefix);
1981 mono_add_unwind_op_def_cfa (unwind_ops, 0, 0, ARMREG_SP, 0);
1982 save_unwind_info (acfg, symbol, unwind_ops);
1983 mono_free_unwind_info (unwind_ops);
1984 #elif defined(TARGET_ARM64)
1985 arm64_emit_specific_trampoline_pages (acfg);
1986 #endif
1990 * arch_emit_specific_trampoline:
1992 * Emit code for a specific trampoline. OFFSET is the offset of the first of
1993 * two GOT slots which contain the generic trampoline address and the trampoline
1994 * argument. TRAMP_SIZE is set to the size of the emitted trampoline.
1996 static void
1997 arch_emit_specific_trampoline (MonoAotCompile *acfg, int offset, int *tramp_size)
2000 * The trampolines created here are variations of the specific
2001 * trampolines created in mono_arch_create_specific_trampoline (). The
2002 * differences are:
2003 * - the generic trampoline address is taken from a got slot.
2004 * - the offset of the got slot where the trampoline argument is stored
2005 * is embedded in the instruction stream, and the generic trampoline
2006 * can load the argument by loading the offset, adding it to the
2007 * address of the trampoline to get the address of the got slot, and
2008 * loading the argument from there.
2009 * - all the trampolines should be of the same length.
2011 #if defined(TARGET_AMD64)
2012 /* This should be exactly 8 bytes long */
2013 *tramp_size = 8;
2014 /* call *<offset>(%rip) */
2015 if (acfg->llvm) {
2016 emit_unset_mode (acfg);
2017 fprintf (acfg->fp, "call *%s+%d(%%rip)\n", acfg->got_symbol, (int)(offset * sizeof (gpointer)));
2018 emit_zero_bytes (acfg, 2);
2019 } else {
2020 emit_byte (acfg, '\x41');
2021 emit_byte (acfg, '\xff');
2022 emit_byte (acfg, '\x15');
2023 emit_symbol_diff (acfg, acfg->got_symbol, ".", (offset * sizeof (gpointer)) - 4);
2024 emit_zero_bytes (acfg, 1);
2026 #elif defined(TARGET_ARM)
2027 guint8 buf [128];
2028 guint8 *code;
2030 /* This should be exactly 20 bytes long */
2031 *tramp_size = 20;
2032 code = buf;
2033 ARM_PUSH (code, 0x5fff);
2034 ARM_LDR_IMM (code, ARMREG_R1, ARMREG_PC, 4);
2035 /* Load the value from the GOT */
2036 ARM_LDR_REG_REG (code, ARMREG_R1, ARMREG_PC, ARMREG_R1);
2037 /* Branch to it */
2038 ARM_BLX_REG (code, ARMREG_R1);
2040 g_assert (code - buf == 16);
2042 /* Emit it */
2043 emit_bytes (acfg, buf, code - buf);
2045 * Only one offset is needed, since the second one would be equal to the
2046 * first one.
2048 emit_symbol_diff (acfg, acfg->got_symbol, ".", (offset * sizeof (gpointer)) - 4 + 4);
2049 //emit_symbol_diff (acfg, acfg->got_symbol, ".", ((offset + 1) * sizeof (gpointer)) - 4 + 8);
2050 #elif defined(TARGET_ARM64)
2051 arm64_emit_specific_trampoline (acfg, offset, tramp_size);
2052 #elif defined(TARGET_POWERPC)
2053 guint8 buf [128];
2054 guint8 *code;
2056 *tramp_size = 4;
2057 code = buf;
2060 * PPC has no ip relative addressing, so we need to compute the address
2061 * of the mscorlib got. That is slow and complex, so instead, we store it
2062 * in the second got slot of every aot image. The caller already computed
2063 * the address of its got and placed it into r30.
2065 emit_unset_mode (acfg);
2066 /* Load mscorlib got address */
2067 fprintf (acfg->fp, "%s 0, %d(30)\n", PPC_LD_OP, (int)sizeof (gpointer));
2068 /* Load generic trampoline address */
2069 fprintf (acfg->fp, "lis 11, %d@h\n", (int)(offset * sizeof (gpointer)));
2070 fprintf (acfg->fp, "ori 11, 11, %d@l\n", (int)(offset * sizeof (gpointer)));
2071 fprintf (acfg->fp, "%s 11, 11, 0\n", PPC_LDX_OP);
2072 #ifdef PPC_USES_FUNCTION_DESCRIPTOR
2073 fprintf (acfg->fp, "%s 11, 0(11)\n", PPC_LD_OP);
2074 #endif
2075 fprintf (acfg->fp, "mtctr 11\n");
2076 /* Load trampoline argument */
2077 /* On ppc, we pass it normally to the generic trampoline */
2078 fprintf (acfg->fp, "lis 11, %d@h\n", (int)((offset + 1) * sizeof (gpointer)));
2079 fprintf (acfg->fp, "ori 11, 11, %d@l\n", (int)((offset + 1) * sizeof (gpointer)));
2080 fprintf (acfg->fp, "%s 0, 11, 0\n", PPC_LDX_OP);
2081 /* Branch to generic trampoline */
2082 fprintf (acfg->fp, "bctr\n");
2084 #ifdef PPC_USES_FUNCTION_DESCRIPTOR
2085 *tramp_size = 10 * 4;
2086 #else
2087 *tramp_size = 9 * 4;
2088 #endif
2089 #elif defined(TARGET_X86)
2090 guint8 buf [128];
2091 guint8 *code;
2093 /* Similar to the PPC code above */
2095 /* FIXME: Could this clobber the register needed by get_vcall_slot () ? */
2097 code = buf;
2098 /* Load mscorlib got address */
2099 x86_mov_reg_membase (code, X86_ECX, MONO_ARCH_GOT_REG, sizeof (gpointer), 4);
2100 /* Push trampoline argument */
2101 x86_push_membase (code, X86_ECX, (offset + 1) * sizeof (gpointer));
2102 /* Load generic trampoline address */
2103 x86_mov_reg_membase (code, X86_ECX, X86_ECX, offset * sizeof (gpointer), 4);
2104 /* Branch to generic trampoline */
2105 x86_jump_reg (code, X86_ECX);
2107 emit_bytes (acfg, buf, code - buf);
2109 *tramp_size = 17;
2110 g_assert (code - buf == *tramp_size);
2111 #else
2112 g_assert_not_reached ();
2113 #endif
2117 * arch_emit_unbox_trampoline:
2119 * Emit code for the unbox trampoline for METHOD used in the full-aot case.
2120 * CALL_TARGET is the symbol pointing to the native code of METHOD.
2122 static void
2123 arch_emit_unbox_trampoline (MonoAotCompile *acfg, MonoCompile *cfg, MonoMethod *method, const char *call_target)
2125 #if defined(TARGET_AMD64)
2126 guint8 buf [32];
2127 guint8 *code;
2128 int this_reg;
2130 this_reg = mono_arch_get_this_arg_reg (NULL);
2131 code = buf;
2132 amd64_alu_reg_imm (code, X86_ADD, this_reg, sizeof (MonoObject));
2134 emit_bytes (acfg, buf, code - buf);
2135 /* jump <method> */
2136 if (acfg->llvm) {
2137 emit_unset_mode (acfg);
2138 fprintf (acfg->fp, "jmp %s\n", call_target);
2139 } else {
2140 emit_byte (acfg, '\xe9');
2141 emit_symbol_diff (acfg, call_target, ".", -4);
2143 #elif defined(TARGET_X86)
2144 guint8 buf [32];
2145 guint8 *code;
2146 int this_pos = 4;
2148 code = buf;
2150 x86_alu_membase_imm (code, X86_ADD, X86_ESP, this_pos, sizeof (MonoObject));
2152 emit_bytes (acfg, buf, code - buf);
2154 /* jump <method> */
2155 emit_byte (acfg, '\xe9');
2156 emit_symbol_diff (acfg, call_target, ".", -4);
2157 #elif defined(TARGET_ARM)
2158 guint8 buf [128];
2159 guint8 *code;
2161 if (acfg->thumb_mixed && cfg->compile_llvm) {
2162 fprintf (acfg->fp, "add r0, r0, #%d\n", (int)sizeof (MonoObject));
2163 fprintf (acfg->fp, "b %s\n", call_target);
2164 fprintf (acfg->fp, ".arm\n");
2165 fprintf (acfg->fp, ".align 2\n");
2166 return;
2169 code = buf;
2171 ARM_ADD_REG_IMM8 (code, ARMREG_R0, ARMREG_R0, sizeof (MonoObject));
2173 emit_bytes (acfg, buf, code - buf);
2174 /* jump to method */
2175 if (acfg->thumb_mixed && cfg->compile_llvm)
2176 fprintf (acfg->fp, "\n\tbx %s\n", call_target);
2177 else
2178 fprintf (acfg->fp, "\n\tb %s\n", call_target);
2179 #elif defined(TARGET_ARM64)
2180 arm64_emit_unbox_trampoline (acfg, cfg, method, call_target);
2181 #elif defined(TARGET_POWERPC)
2182 int this_pos = 3;
2184 fprintf (acfg->fp, "\n\taddi %d, %d, %d\n", this_pos, this_pos, (int)sizeof (MonoObject));
2185 fprintf (acfg->fp, "\n\tb %s\n", call_target);
2186 #else
2187 g_assert_not_reached ();
2188 #endif
2192 * arch_emit_static_rgctx_trampoline:
2194 * Emit code for a static rgctx trampoline. OFFSET is the offset of the first of
2195 * two GOT slots which contain the rgctx argument, and the method to jump to.
2196 * TRAMP_SIZE is set to the size of the emitted trampoline.
2197 * These kinds of trampolines cannot be enumerated statically, since there could
2198 * be one trampoline per method instantiation, so we emit the same code for all
2199 * trampolines, and parameterize them using two GOT slots.
2201 static void
2202 arch_emit_static_rgctx_trampoline (MonoAotCompile *acfg, int offset, int *tramp_size)
2204 #if defined(TARGET_AMD64)
2205 /* This should be exactly 13 bytes long */
2206 *tramp_size = 13;
2208 if (acfg->llvm) {
2209 emit_unset_mode (acfg);
2210 fprintf (acfg->fp, "mov %s+%d(%%rip), %%r10\n", acfg->got_symbol, (int)(offset * sizeof (gpointer)));
2211 fprintf (acfg->fp, "jmp *%s+%d(%%rip)\n", acfg->got_symbol, (int)((offset + 1) * sizeof (gpointer)));
2212 } else {
2213 /* mov <OFFSET>(%rip), %r10 */
2214 emit_byte (acfg, '\x4d');
2215 emit_byte (acfg, '\x8b');
2216 emit_byte (acfg, '\x15');
2217 emit_symbol_diff (acfg, acfg->got_symbol, ".", (offset * sizeof (gpointer)) - 4);
2219 /* jmp *<offset>(%rip) */
2220 emit_byte (acfg, '\xff');
2221 emit_byte (acfg, '\x25');
2222 emit_symbol_diff (acfg, acfg->got_symbol, ".", ((offset + 1) * sizeof (gpointer)) - 4);
2224 #elif defined(TARGET_ARM)
2225 guint8 buf [128];
2226 guint8 *code;
2228 /* This should be exactly 24 bytes long */
2229 *tramp_size = 24;
2230 code = buf;
2231 /* Load rgctx value */
2232 ARM_LDR_IMM (code, ARMREG_IP, ARMREG_PC, 8);
2233 ARM_LDR_REG_REG (code, MONO_ARCH_RGCTX_REG, ARMREG_PC, ARMREG_IP);
2234 /* Load branch addr + branch */
2235 ARM_LDR_IMM (code, ARMREG_IP, ARMREG_PC, 4);
2236 ARM_LDR_REG_REG (code, ARMREG_PC, ARMREG_PC, ARMREG_IP);
2238 g_assert (code - buf == 16);
2240 /* Emit it */
2241 emit_bytes (acfg, buf, code - buf);
2242 emit_symbol_diff (acfg, acfg->got_symbol, ".", (offset * sizeof (gpointer)) - 4 + 8);
2243 emit_symbol_diff (acfg, acfg->got_symbol, ".", ((offset + 1) * sizeof (gpointer)) - 4 + 4);
2244 #elif defined(TARGET_ARM64)
2245 arm64_emit_static_rgctx_trampoline (acfg, offset, tramp_size);
2246 #elif defined(TARGET_POWERPC)
2247 guint8 buf [128];
2248 guint8 *code;
2250 *tramp_size = 4;
2251 code = buf;
2254 * PPC has no ip relative addressing, so we need to compute the address
2255 * of the mscorlib got. That is slow and complex, so instead, we store it
2256 * in the second got slot of every aot image. The caller already computed
2257 * the address of its got and placed it into r30.
2259 emit_unset_mode (acfg);
2260 /* Load mscorlib got address */
2261 fprintf (acfg->fp, "%s 0, %d(30)\n", PPC_LD_OP, (int)sizeof (gpointer));
2262 /* Load rgctx */
2263 fprintf (acfg->fp, "lis 11, %d@h\n", (int)(offset * sizeof (gpointer)));
2264 fprintf (acfg->fp, "ori 11, 11, %d@l\n", (int)(offset * sizeof (gpointer)));
2265 fprintf (acfg->fp, "%s %d, 11, 0\n", PPC_LDX_OP, MONO_ARCH_RGCTX_REG);
2266 /* Load target address */
2267 fprintf (acfg->fp, "lis 11, %d@h\n", (int)((offset + 1) * sizeof (gpointer)));
2268 fprintf (acfg->fp, "ori 11, 11, %d@l\n", (int)((offset + 1) * sizeof (gpointer)));
2269 fprintf (acfg->fp, "%s 11, 11, 0\n", PPC_LDX_OP);
2270 #ifdef PPC_USES_FUNCTION_DESCRIPTOR
2271 fprintf (acfg->fp, "%s 2, %d(11)\n", PPC_LD_OP, (int)sizeof (gpointer));
2272 fprintf (acfg->fp, "%s 11, 0(11)\n", PPC_LD_OP);
2273 #endif
2274 fprintf (acfg->fp, "mtctr 11\n");
2275 /* Branch to the target address */
2276 fprintf (acfg->fp, "bctr\n");
2278 #ifdef PPC_USES_FUNCTION_DESCRIPTOR
2279 *tramp_size = 11 * 4;
2280 #else
2281 *tramp_size = 9 * 4;
2282 #endif
2284 #elif defined(TARGET_X86)
2285 guint8 buf [128];
2286 guint8 *code;
2288 /* Similar to the PPC code above */
2290 g_assert (MONO_ARCH_RGCTX_REG != X86_ECX);
2292 code = buf;
2293 /* Load mscorlib got address */
2294 x86_mov_reg_membase (code, X86_ECX, MONO_ARCH_GOT_REG, sizeof (gpointer), 4);
2295 /* Load arg */
2296 x86_mov_reg_membase (code, MONO_ARCH_RGCTX_REG, X86_ECX, offset * sizeof (gpointer), 4);
2297 /* Branch to the target address */
2298 x86_jump_membase (code, X86_ECX, (offset + 1) * sizeof (gpointer));
2300 emit_bytes (acfg, buf, code - buf);
2302 *tramp_size = 15;
2303 g_assert (code - buf == *tramp_size);
2304 #else
2305 g_assert_not_reached ();
2306 #endif
2310 * arch_emit_imt_trampoline:
2312 * Emit an IMT trampoline usable in full-aot mode. The trampoline uses 1 got slot which
2313 * points to an array of pointer pairs. The pairs of the form [key, ptr], where
2314 * key is the IMT key, and ptr holds the address of a memory location holding
2315 * the address to branch to if the IMT arg matches the key. The array is
2316 * terminated by a pair whose key is NULL, and whose ptr is the address of the
2317 * fail_tramp.
2318 * TRAMP_SIZE is set to the size of the emitted trampoline.
2320 static void
2321 arch_emit_imt_trampoline (MonoAotCompile *acfg, int offset, int *tramp_size)
2323 #if defined(TARGET_AMD64)
2324 guint8 *buf, *code;
2325 guint8 *labels [16];
2326 guint8 mov_buf[3];
2327 guint8 *mov_buf_ptr = mov_buf;
2329 const int kSizeOfMove = 7;
2331 code = buf = (guint8 *)g_malloc (256);
2333 /* FIXME: Optimize this, i.e. use binary search etc. */
2334 /* Maybe move the body into a separate function (slower, but much smaller) */
2336 /* MONO_ARCH_IMT_SCRATCH_REG is a free register */
2338 if (acfg->llvm) {
2339 emit_unset_mode (acfg);
2340 fprintf (acfg->fp, "mov %s+%d(%%rip), %s\n", acfg->got_symbol, (int)(offset * sizeof (gpointer)), mono_arch_regname (MONO_ARCH_IMT_SCRATCH_REG));
2343 labels [0] = code;
2344 amd64_alu_membase_imm (code, X86_CMP, MONO_ARCH_IMT_SCRATCH_REG, 0, 0);
2345 labels [1] = code;
2346 amd64_branch8 (code, X86_CC_Z, 0, FALSE);
2348 /* Check key */
2349 amd64_alu_membase_reg_size (code, X86_CMP, MONO_ARCH_IMT_SCRATCH_REG, 0, MONO_ARCH_IMT_REG, sizeof (gpointer));
2350 labels [2] = code;
2351 amd64_branch8 (code, X86_CC_Z, 0, FALSE);
2353 /* Loop footer */
2354 amd64_alu_reg_imm (code, X86_ADD, MONO_ARCH_IMT_SCRATCH_REG, 2 * sizeof (gpointer));
2355 amd64_jump_code (code, labels [0]);
2357 /* Match */
2358 mono_amd64_patch (labels [2], code);
2359 amd64_mov_reg_membase (code, MONO_ARCH_IMT_SCRATCH_REG, MONO_ARCH_IMT_SCRATCH_REG, sizeof (gpointer), sizeof (gpointer));
2360 amd64_jump_membase (code, MONO_ARCH_IMT_SCRATCH_REG, 0);
2362 /* No match */
2363 mono_amd64_patch (labels [1], code);
2364 /* Load fail tramp */
2365 amd64_alu_reg_imm (code, X86_ADD, MONO_ARCH_IMT_SCRATCH_REG, sizeof (gpointer));
2366 /* Check if there is a fail tramp */
2367 amd64_alu_membase_imm (code, X86_CMP, MONO_ARCH_IMT_SCRATCH_REG, 0, 0);
2368 labels [3] = code;
2369 amd64_branch8 (code, X86_CC_Z, 0, FALSE);
2370 /* Jump to fail tramp */
2371 amd64_jump_membase (code, MONO_ARCH_IMT_SCRATCH_REG, 0);
2373 /* Fail */
2374 mono_amd64_patch (labels [3], code);
2375 x86_breakpoint (code);
2377 if (!acfg->llvm) {
2378 /* mov <OFFSET>(%rip), MONO_ARCH_IMT_SCRATCH_REG */
2379 amd64_emit_rex (mov_buf_ptr, sizeof(gpointer), MONO_ARCH_IMT_SCRATCH_REG, 0, AMD64_RIP);
2380 *(mov_buf_ptr)++ = (unsigned char)0x8b; /* mov opcode */
2381 x86_address_byte (mov_buf_ptr, 0, MONO_ARCH_IMT_SCRATCH_REG & 0x7, 5);
2382 emit_bytes (acfg, mov_buf, mov_buf_ptr - mov_buf);
2383 emit_symbol_diff (acfg, acfg->got_symbol, ".", (offset * sizeof (gpointer)) - 4);
2385 emit_bytes (acfg, buf, code - buf);
2387 *tramp_size = code - buf + kSizeOfMove;
2389 g_free (buf);
2391 #elif defined(TARGET_X86)
2392 guint8 *buf, *code;
2393 guint8 *labels [16];
2395 code = buf = g_malloc (256);
2397 /* Allocate a temporary stack slot */
2398 x86_push_reg (code, X86_EAX);
2399 /* Save EAX */
2400 x86_push_reg (code, X86_EAX);
2402 /* Load mscorlib got address */
2403 x86_mov_reg_membase (code, X86_EAX, MONO_ARCH_GOT_REG, sizeof (gpointer), 4);
2404 /* Load arg */
2405 x86_mov_reg_membase (code, X86_EAX, X86_EAX, offset * sizeof (gpointer), 4);
2407 labels [0] = code;
2408 x86_alu_membase_imm (code, X86_CMP, X86_EAX, 0, 0);
2409 labels [1] = code;
2410 x86_branch8 (code, X86_CC_Z, FALSE, 0);
2412 /* Check key */
2413 x86_alu_membase_reg (code, X86_CMP, X86_EAX, 0, MONO_ARCH_IMT_REG);
2414 labels [2] = code;
2415 x86_branch8 (code, X86_CC_Z, FALSE, 0);
2417 /* Loop footer */
2418 x86_alu_reg_imm (code, X86_ADD, X86_EAX, 2 * sizeof (gpointer));
2419 x86_jump_code (code, labels [0]);
2421 /* Match */
2422 mono_x86_patch (labels [2], code);
2423 x86_mov_reg_membase (code, X86_EAX, X86_EAX, sizeof (gpointer), 4);
2424 x86_mov_reg_membase (code, X86_EAX, X86_EAX, 0, 4);
2425 /* Save the target address to the temporary stack location */
2426 x86_mov_membase_reg (code, X86_ESP, 4, X86_EAX, 4);
2427 /* Restore EAX */
2428 x86_pop_reg (code, X86_EAX);
2429 /* Jump to the target address */
2430 x86_ret (code);
2432 /* No match */
2433 mono_x86_patch (labels [1], code);
2434 /* Load fail tramp */
2435 x86_mov_reg_membase (code, X86_EAX, X86_EAX, sizeof (gpointer), 4);
2436 x86_alu_membase_imm (code, X86_CMP, X86_EAX, 0, 0);
2437 labels [3] = code;
2438 x86_branch8 (code, X86_CC_Z, FALSE, 0);
2439 /* Jump to fail tramp */
2440 x86_mov_membase_reg (code, X86_ESP, 4, X86_EAX, 4);
2441 x86_pop_reg (code, X86_EAX);
2442 x86_ret (code);
2444 /* Fail */
2445 mono_x86_patch (labels [3], code);
2446 x86_breakpoint (code);
2448 emit_bytes (acfg, buf, code - buf);
2450 *tramp_size = code - buf;
2452 g_free (buf);
2454 #elif defined(TARGET_ARM)
2455 guint8 buf [128];
2456 guint8 *code, *code2, *labels [16];
2458 code = buf;
2460 /* The IMT method is in v5 */
2462 /* Need at least two free registers, plus a slot for storing the pc */
2463 ARM_PUSH (code, (1 << ARMREG_R0)|(1 << ARMREG_R1)|(1 << ARMREG_R2));
2464 labels [0] = code;
2465 /* Load the parameter from the GOT */
2466 ARM_LDR_IMM (code, ARMREG_R0, ARMREG_PC, 0);
2467 ARM_LDR_REG_REG (code, ARMREG_R0, ARMREG_PC, ARMREG_R0);
2469 labels [1] = code;
2470 ARM_LDR_IMM (code, ARMREG_R1, ARMREG_R0, 0);
2471 ARM_CMP_REG_REG (code, ARMREG_R1, ARMREG_V5);
2472 labels [2] = code;
2473 ARM_B_COND (code, ARMCOND_EQ, 0);
2475 /* End-of-loop check */
2476 ARM_CMP_REG_IMM (code, ARMREG_R1, 0, 0);
2477 labels [3] = code;
2478 ARM_B_COND (code, ARMCOND_EQ, 0);
2480 /* Loop footer */
2481 ARM_ADD_REG_IMM8 (code, ARMREG_R0, ARMREG_R0, sizeof (gpointer) * 2);
2482 labels [4] = code;
2483 ARM_B (code, 0);
2484 arm_patch (labels [4], labels [1]);
2486 /* Match */
2487 arm_patch (labels [2], code);
2488 ARM_LDR_IMM (code, ARMREG_R0, ARMREG_R0, 4);
2489 ARM_LDR_IMM (code, ARMREG_R0, ARMREG_R0, 0);
2490 /* Save it to the third stack slot */
2491 ARM_STR_IMM (code, ARMREG_R0, ARMREG_SP, 8);
2492 /* Restore the registers and branch */
2493 ARM_POP (code, (1 << ARMREG_R0)|(1 << ARMREG_R1)|(1 << ARMREG_PC));
2495 /* No match */
2496 arm_patch (labels [3], code);
2497 ARM_LDR_IMM (code, ARMREG_R0, ARMREG_R0, 4);
2498 ARM_STR_IMM (code, ARMREG_R0, ARMREG_SP, 8);
2499 ARM_POP (code, (1 << ARMREG_R0)|(1 << ARMREG_R1)|(1 << ARMREG_PC));
2501 /* Fixup offset */
2502 code2 = labels [0];
2503 ARM_LDR_IMM (code2, ARMREG_R0, ARMREG_PC, (code - (labels [0] + 8)));
2505 emit_bytes (acfg, buf, code - buf);
2506 emit_symbol_diff (acfg, acfg->got_symbol, ".", (offset * sizeof (gpointer)) + (code - (labels [0] + 8)) - 4);
2508 *tramp_size = code - buf + 4;
2509 #elif defined(TARGET_ARM64)
2510 arm64_emit_imt_trampoline (acfg, offset, tramp_size);
2511 #elif defined(TARGET_POWERPC)
2512 guint8 buf [128];
2513 guint8 *code, *labels [16];
2515 code = buf;
2517 /* Load the mscorlib got address */
2518 ppc_ldptr (code, ppc_r12, sizeof (gpointer), ppc_r30);
2519 /* Load the parameter from the GOT */
2520 ppc_load (code, ppc_r0, offset * sizeof (gpointer));
2521 ppc_ldptr_indexed (code, ppc_r12, ppc_r12, ppc_r0);
2523 /* Load and check key */
2524 labels [1] = code;
2525 ppc_ldptr (code, ppc_r0, 0, ppc_r12);
2526 ppc_cmp (code, 0, sizeof (gpointer) == 8 ? 1 : 0, ppc_r0, MONO_ARCH_IMT_REG);
2527 labels [2] = code;
2528 ppc_bc (code, PPC_BR_TRUE, PPC_BR_EQ, 0);
2530 /* End-of-loop check */
2531 ppc_cmpi (code, 0, sizeof (gpointer) == 8 ? 1 : 0, ppc_r0, 0);
2532 labels [3] = code;
2533 ppc_bc (code, PPC_BR_TRUE, PPC_BR_EQ, 0);
2535 /* Loop footer */
2536 ppc_addi (code, ppc_r12, ppc_r12, 2 * sizeof (gpointer));
2537 labels [4] = code;
2538 ppc_b (code, 0);
2539 mono_ppc_patch (labels [4], labels [1]);
2541 /* Match */
2542 mono_ppc_patch (labels [2], code);
2543 ppc_ldptr (code, ppc_r12, sizeof (gpointer), ppc_r12);
2544 /* r12 now contains the value of the vtable slot */
2545 /* this is not a function descriptor on ppc64 */
2546 ppc_ldptr (code, ppc_r12, 0, ppc_r12);
2547 ppc_mtctr (code, ppc_r12);
2548 ppc_bcctr (code, PPC_BR_ALWAYS, 0);
2550 /* Fail */
2551 mono_ppc_patch (labels [3], code);
2552 /* FIXME: */
2553 ppc_break (code);
2555 *tramp_size = code - buf;
2557 emit_bytes (acfg, buf, code - buf);
2558 #else
2559 g_assert_not_reached ();
2560 #endif
2564 #if defined (TARGET_AMD64)
2566 static void
2567 amd64_emit_load_got_slot (MonoAotCompile *acfg, int dreg, int got_slot)
2570 g_assert (acfg->fp);
2571 emit_unset_mode (acfg);
2573 fprintf (acfg->fp, "mov %s+%d(%%rip), %s\n", acfg->got_symbol, (unsigned int) ((got_slot * sizeof (gpointer))), mono_arch_regname (dreg));
2576 #endif
2580 * arch_emit_gsharedvt_arg_trampoline:
2582 * Emit code for a gsharedvt arg trampoline. OFFSET is the offset of the first of
2583 * two GOT slots which contain the argument, and the code to jump to.
2584 * TRAMP_SIZE is set to the size of the emitted trampoline.
2585 * These kinds of trampolines cannot be enumerated statically, since there could
2586 * be one trampoline per method instantiation, so we emit the same code for all
2587 * trampolines, and parameterize them using two GOT slots.
2589 static void
2590 arch_emit_gsharedvt_arg_trampoline (MonoAotCompile *acfg, int offset, int *tramp_size)
2592 #if defined(TARGET_X86)
2593 guint8 buf [128];
2594 guint8 *code;
2596 /* Similar to the PPC code above */
2598 g_assert (MONO_ARCH_RGCTX_REG != X86_ECX);
2600 code = buf;
2601 /* Load mscorlib got address */
2602 x86_mov_reg_membase (code, X86_ECX, MONO_ARCH_GOT_REG, sizeof (gpointer), 4);
2603 /* Load arg */
2604 x86_mov_reg_membase (code, X86_EAX, X86_ECX, offset * sizeof (gpointer), 4);
2605 /* Branch to the target address */
2606 x86_jump_membase (code, X86_ECX, (offset + 1) * sizeof (gpointer));
2608 emit_bytes (acfg, buf, code - buf);
2610 *tramp_size = 15;
2611 g_assert (code - buf == *tramp_size);
2612 #elif defined(TARGET_ARM)
2613 guint8 buf [128];
2614 guint8 *code;
2616 /* The same as mono_arch_get_gsharedvt_arg_trampoline (), but for AOT */
2617 /* Similar to arch_emit_specific_trampoline () */
2618 *tramp_size = 24;
2619 code = buf;
2620 ARM_PUSH (code, (1 << ARMREG_R0) | (1 << ARMREG_R1) | (1 << ARMREG_R2) | (1 << ARMREG_R3));
2621 ARM_LDR_IMM (code, ARMREG_R1, ARMREG_PC, 8);
2622 /* Load the arg value from the GOT */
2623 ARM_LDR_REG_REG (code, ARMREG_R0, ARMREG_PC, ARMREG_R1);
2624 /* Load the addr from the GOT */
2625 ARM_LDR_REG_REG (code, ARMREG_R1, ARMREG_PC, ARMREG_R1);
2626 /* Branch to it */
2627 ARM_BX (code, ARMREG_R1);
2629 g_assert (code - buf == 20);
2631 /* Emit it */
2632 emit_bytes (acfg, buf, code - buf);
2633 emit_symbol_diff (acfg, acfg->got_symbol, ".", (offset * sizeof (gpointer)) + 4);
2634 #elif defined(TARGET_ARM64)
2635 arm64_emit_gsharedvt_arg_trampoline (acfg, offset, tramp_size);
2636 #elif defined (TARGET_AMD64)
2638 amd64_emit_load_got_slot (acfg, AMD64_RAX, offset);
2639 amd64_emit_load_got_slot (acfg, MONO_ARCH_IMT_SCRATCH_REG, offset + 1);
2640 g_assert (AMD64_R11 == MONO_ARCH_IMT_SCRATCH_REG);
2641 fprintf (acfg->fp, "jmp *%%r11\n");
2643 *tramp_size = 0x11;
2644 #else
2645 g_assert_not_reached ();
2646 #endif
2649 /* END OF ARCH SPECIFIC CODE */
2651 static guint32
2652 mono_get_field_token (MonoClassField *field)
2654 MonoClass *klass = field->parent;
2655 int i;
2657 int fcount = mono_class_get_field_count (klass);
2658 MonoClassField *klass_fields = m_class_get_fields (klass);
2659 for (i = 0; i < fcount; ++i) {
2660 if (field == &klass_fields [i])
2661 return MONO_TOKEN_FIELD_DEF | (mono_class_get_first_field_idx (klass) + 1 + i);
2664 g_assert_not_reached ();
2665 return 0;
2668 static inline void
2669 encode_value (gint32 value, guint8 *buf, guint8 **endbuf)
2671 guint8 *p = buf;
2673 //printf ("ENCODE: %d 0x%x.\n", value, value);
2676 * Same encoding as the one used in the metadata, extended to handle values
2677 * greater than 0x1fffffff.
2679 if ((value >= 0) && (value <= 127))
2680 *p++ = value;
2681 else if ((value >= 0) && (value <= 16383)) {
2682 p [0] = 0x80 | (value >> 8);
2683 p [1] = value & 0xff;
2684 p += 2;
2685 } else if ((value >= 0) && (value <= 0x1fffffff)) {
2686 p [0] = (value >> 24) | 0xc0;
2687 p [1] = (value >> 16) & 0xff;
2688 p [2] = (value >> 8) & 0xff;
2689 p [3] = value & 0xff;
2690 p += 4;
2692 else {
2693 p [0] = 0xff;
2694 p [1] = (value >> 24) & 0xff;
2695 p [2] = (value >> 16) & 0xff;
2696 p [3] = (value >> 8) & 0xff;
2697 p [4] = value & 0xff;
2698 p += 5;
2700 if (endbuf)
2701 *endbuf = p;
2704 static void
2705 stream_init (MonoDynamicStream *sh)
2707 sh->index = 0;
2708 sh->alloc_size = 4096;
2709 sh->data = (char *)g_malloc (4096);
2711 /* So offsets are > 0 */
2712 sh->data [0] = 0;
2713 sh->index ++;
2716 static void
2717 make_room_in_stream (MonoDynamicStream *stream, int size)
2719 if (size <= stream->alloc_size)
2720 return;
2722 while (stream->alloc_size <= size) {
2723 if (stream->alloc_size < 4096)
2724 stream->alloc_size = 4096;
2725 else
2726 stream->alloc_size *= 2;
2729 stream->data = (char *)g_realloc (stream->data, stream->alloc_size);
2732 static guint32
2733 add_stream_data (MonoDynamicStream *stream, const char *data, guint32 len)
2735 guint32 idx;
2737 make_room_in_stream (stream, stream->index + len);
2738 memcpy (stream->data + stream->index, data, len);
2739 idx = stream->index;
2740 stream->index += len;
2741 return idx;
2745 * add_to_blob:
2747 * Add data to the binary blob inside the aot image. Returns the offset inside the
2748 * blob where the data was stored.
2750 static guint32
2751 add_to_blob (MonoAotCompile *acfg, const guint8 *data, guint32 data_len)
2753 g_assert (!acfg->blob_closed);
2755 if (acfg->blob.alloc_size == 0)
2756 stream_init (&acfg->blob);
2758 return add_stream_data (&acfg->blob, (char*)data, data_len);
2761 static guint32
2762 add_to_blob_aligned (MonoAotCompile *acfg, const guint8 *data, guint32 data_len, guint32 align)
2764 char buf [4] = {0};
2765 guint32 count;
2767 if (acfg->blob.alloc_size == 0)
2768 stream_init (&acfg->blob);
2770 count = acfg->blob.index % align;
2772 /* we assume the stream data will be aligned */
2773 if (count)
2774 add_stream_data (&acfg->blob, buf, 4 - count);
2776 return add_stream_data (&acfg->blob, (char*)data, data_len);
2779 /* Emit a table of data into the aot image */
2780 static void
2781 emit_aot_data (MonoAotCompile *acfg, MonoAotFileTable table, const char *symbol, guint8 *data, int size)
2783 if (acfg->data_outfile) {
2784 acfg->table_offsets [(int)table] = acfg->datafile_offset;
2785 fwrite (data,1, size, acfg->data_outfile);
2786 acfg->datafile_offset += size;
2787 // align the data to 8 bytes. Put zeros in the file (so that every build results in consistent output).
2788 int align = 8 - size % 8;
2789 acfg->datafile_offset += align;
2790 guint8 align_buf [16];
2791 memset (&align_buf, 0, sizeof (align_buf));
2792 fwrite (align_buf, align, 1, acfg->data_outfile);
2793 } else if (acfg->llvm) {
2794 mono_llvm_emit_aot_data (symbol, data, size);
2795 } else {
2796 emit_section_change (acfg, RODATA_SECT, 0);
2797 emit_alignment (acfg, 8);
2798 emit_label (acfg, symbol);
2799 emit_bytes (acfg, data, size);
2804 * emit_offset_table:
2806 * Emit a table of increasing offsets in a compact form using differential encoding.
2807 * There is an index entry for each GROUP_SIZE number of entries. The greater the
2808 * group size, the more compact the table becomes, but the slower it becomes to compute
2809 * a given entry. Returns the size of the table.
2811 static guint32
2812 emit_offset_table (MonoAotCompile *acfg, const char *symbol, MonoAotFileTable table, int noffsets, int group_size, gint32 *offsets)
2814 gint32 current_offset;
2815 int i, buf_size, ngroups, index_entry_size;
2816 guint8 *p, *buf;
2817 guint8 *data_p, *data_buf;
2818 guint32 *index_offsets;
2820 ngroups = (noffsets + (group_size - 1)) / group_size;
2822 index_offsets = g_new0 (guint32, ngroups);
2824 buf_size = noffsets * 4;
2825 p = buf = (guint8 *)g_malloc0 (buf_size);
2827 current_offset = 0;
2828 for (i = 0; i < noffsets; ++i) {
2829 //printf ("D: %d -> %d\n", i, offsets [i]);
2830 if ((i % group_size) == 0) {
2831 index_offsets [i / group_size] = p - buf;
2832 /* Emit the full value for these entries */
2833 encode_value (offsets [i], p, &p);
2834 } else {
2835 /* The offsets are allowed to be non-increasing */
2836 //g_assert (offsets [i] >= current_offset);
2837 encode_value (offsets [i] - current_offset, p, &p);
2839 current_offset = offsets [i];
2841 data_buf = buf;
2842 data_p = p;
2844 if (ngroups && index_offsets [ngroups - 1] < 65000)
2845 index_entry_size = 2;
2846 else
2847 index_entry_size = 4;
2849 buf_size = (data_p - data_buf) + (ngroups * 4) + 16;
2850 p = buf = (guint8 *)g_malloc0 (buf_size);
2852 /* Emit the header */
2853 encode_int (noffsets, p, &p);
2854 encode_int (group_size, p, &p);
2855 encode_int (ngroups, p, &p);
2856 encode_int (index_entry_size, p, &p);
2858 /* Emit the index */
2859 for (i = 0; i < ngroups; ++i) {
2860 if (index_entry_size == 2)
2861 encode_int16 (index_offsets [i], p, &p);
2862 else
2863 encode_int (index_offsets [i], p, &p);
2865 /* Emit the data */
2866 memcpy (p, data_buf, data_p - data_buf);
2867 p += data_p - data_buf;
2869 g_assert (p - buf <= buf_size);
2871 emit_aot_data (acfg, table, symbol, buf, p - buf);
2873 g_free (buf);
2874 g_free (data_buf);
2876 return (int)(p - buf);
2879 static guint32
2880 get_image_index (MonoAotCompile *cfg, MonoImage *image)
2882 guint32 index;
2884 index = GPOINTER_TO_UINT (g_hash_table_lookup (cfg->image_hash, image));
2885 if (index)
2886 return index - 1;
2887 else {
2888 index = g_hash_table_size (cfg->image_hash);
2889 g_hash_table_insert (cfg->image_hash, image, GUINT_TO_POINTER (index + 1));
2890 g_ptr_array_add (cfg->image_table, image);
2891 return index;
2895 static guint32
2896 find_typespec_for_class (MonoAotCompile *acfg, MonoClass *klass)
2898 int i;
2899 int len = acfg->image->tables [MONO_TABLE_TYPESPEC].rows;
2901 /* FIXME: Search referenced images as well */
2902 if (!acfg->typespec_classes) {
2903 acfg->typespec_classes = g_hash_table_new (NULL, NULL);
2904 for (i = 0; i < len; i++) {
2905 ERROR_DECL (error);
2906 int typespec = MONO_TOKEN_TYPE_SPEC | (i + 1);
2907 MonoClass *klass_key = mono_class_get_and_inflate_typespec_checked (acfg->image, typespec, NULL, error);
2908 if (!is_ok (error)) {
2909 mono_error_cleanup (error);
2910 continue;
2912 g_hash_table_insert (acfg->typespec_classes, klass_key, GINT_TO_POINTER (typespec));
2915 return GPOINTER_TO_INT (g_hash_table_lookup (acfg->typespec_classes, klass));
2918 static void
2919 encode_method_ref (MonoAotCompile *acfg, MonoMethod *method, guint8 *buf, guint8 **endbuf);
2921 static void
2922 encode_klass_ref (MonoAotCompile *acfg, MonoClass *klass, guint8 *buf, guint8 **endbuf);
2924 static void
2925 encode_ginst (MonoAotCompile *acfg, MonoGenericInst *inst, guint8 *buf, guint8 **endbuf);
2927 static void
2928 encode_type (MonoAotCompile *acfg, MonoType *t, guint8 *buf, guint8 **endbuf);
2930 static void
2931 encode_klass_ref_inner (MonoAotCompile *acfg, MonoClass *klass, guint8 *buf, guint8 **endbuf)
2933 guint8 *p = buf;
2936 * The encoding begins with one of the MONO_AOT_TYPEREF values, followed by additional
2937 * information.
2940 if (mono_class_is_ginst (klass)) {
2941 guint32 token;
2942 g_assert (m_class_get_type_token (klass));
2944 /* Find a typespec for a class if possible */
2945 token = find_typespec_for_class (acfg, klass);
2946 if (token) {
2947 encode_value (MONO_AOT_TYPEREF_TYPESPEC_TOKEN, p, &p);
2948 encode_value (token, p, &p);
2949 } else {
2950 MonoClass *gclass = mono_class_get_generic_class (klass)->container_class;
2951 MonoGenericInst *inst = mono_class_get_generic_class (klass)->context.class_inst;
2952 static int count = 0;
2953 guint8 *p1 = p;
2955 encode_value (MONO_AOT_TYPEREF_GINST, p, &p);
2956 encode_klass_ref (acfg, gclass, p, &p);
2957 encode_ginst (acfg, inst, p, &p);
2959 count += p - p1;
2961 } else if (m_class_get_type_token (klass)) {
2962 int iindex = get_image_index (acfg, m_class_get_image (klass));
2964 g_assert (mono_metadata_token_code (m_class_get_type_token (klass)) == MONO_TOKEN_TYPE_DEF);
2965 if (iindex == 0) {
2966 encode_value (MONO_AOT_TYPEREF_TYPEDEF_INDEX, p, &p);
2967 encode_value (m_class_get_type_token (klass) - MONO_TOKEN_TYPE_DEF, p, &p);
2968 } else {
2969 encode_value (MONO_AOT_TYPEREF_TYPEDEF_INDEX_IMAGE, p, &p);
2970 encode_value (m_class_get_type_token (klass) - MONO_TOKEN_TYPE_DEF, p, &p);
2971 encode_value (get_image_index (acfg, m_class_get_image (klass)), p, &p);
2973 } else if ((m_class_get_byval_arg (klass)->type == MONO_TYPE_VAR) || (m_class_get_byval_arg (klass)->type == MONO_TYPE_MVAR)) {
2974 MonoGenericContainer *container = mono_type_get_generic_param_owner (m_class_get_byval_arg (klass));
2975 MonoGenericParam *par = m_class_get_byval_arg (klass)->data.generic_param;
2977 encode_value (MONO_AOT_TYPEREF_VAR, p, &p);
2979 encode_value (par->gshared_constraint ? 1 : 0, p, &p);
2980 if (par->gshared_constraint) {
2981 MonoGSharedGenericParam *gpar = (MonoGSharedGenericParam*)par;
2982 encode_type (acfg, par->gshared_constraint, p, &p);
2983 encode_klass_ref (acfg, mono_class_create_generic_parameter (gpar->parent), p, &p);
2984 } else {
2985 encode_value (m_class_get_byval_arg (klass)->type, p, &p);
2986 encode_value (mono_type_get_generic_param_num (m_class_get_byval_arg (klass)), p, &p);
2988 encode_value (container->is_anonymous ? 0 : 1, p, &p);
2990 if (!container->is_anonymous) {
2991 encode_value (container->is_method, p, &p);
2992 if (container->is_method)
2993 encode_method_ref (acfg, container->owner.method, p, &p);
2994 else
2995 encode_klass_ref (acfg, container->owner.klass, p, &p);
2998 } else if (m_class_get_byval_arg (klass)->type == MONO_TYPE_PTR) {
2999 encode_value (MONO_AOT_TYPEREF_PTR, p, &p);
3000 encode_type (acfg, m_class_get_byval_arg (klass), p, &p);
3001 } else {
3002 /* Array class */
3003 g_assert (m_class_get_rank (klass) > 0);
3004 encode_value (MONO_AOT_TYPEREF_ARRAY, p, &p);
3005 encode_value (m_class_get_rank (klass), p, &p);
3006 encode_klass_ref (acfg, m_class_get_element_class (klass), p, &p);
3008 *endbuf = p;
3012 * encode_klass_ref:
3014 * Encode a reference to KLASS. We use our home-grown encoding instead of the
3015 * standard metadata encoding.
3017 static void
3018 encode_klass_ref (MonoAotCompile *acfg, MonoClass *klass, guint8 *buf, guint8 **endbuf)
3020 gboolean shared = FALSE;
3023 * The encoding of generic instances is large so emit them only once.
3025 if (mono_class_is_ginst (klass)) {
3026 guint32 token;
3027 g_assert (m_class_get_type_token (klass));
3029 /* Find a typespec for a class if possible */
3030 token = find_typespec_for_class (acfg, klass);
3031 if (!token)
3032 shared = TRUE;
3033 } else if ((m_class_get_byval_arg (klass)->type == MONO_TYPE_VAR) || (m_class_get_byval_arg (klass)->type == MONO_TYPE_MVAR)) {
3034 shared = TRUE;
3037 if (shared) {
3038 guint offset = GPOINTER_TO_UINT (g_hash_table_lookup (acfg->klass_blob_hash, klass));
3039 guint8 *buf2, *p;
3041 if (!offset) {
3042 buf2 = (guint8 *)g_malloc (1024);
3043 p = buf2;
3045 encode_klass_ref_inner (acfg, klass, p, &p);
3046 g_assert (p - buf2 < 1024);
3048 offset = add_to_blob (acfg, buf2, p - buf2);
3049 g_free (buf2);
3051 g_hash_table_insert (acfg->klass_blob_hash, klass, GUINT_TO_POINTER (offset + 1));
3052 } else {
3053 offset --;
3056 p = buf;
3057 encode_value (MONO_AOT_TYPEREF_BLOB_INDEX, p, &p);
3058 encode_value (offset, p, &p);
3059 *endbuf = p;
3060 return;
3063 encode_klass_ref_inner (acfg, klass, buf, endbuf);
3066 static void
3067 encode_field_info (MonoAotCompile *cfg, MonoClassField *field, guint8 *buf, guint8 **endbuf)
3069 guint32 token = mono_get_field_token (field);
3070 guint8 *p = buf;
3072 encode_klass_ref (cfg, field->parent, p, &p);
3073 g_assert (mono_metadata_token_code (token) == MONO_TOKEN_FIELD_DEF);
3074 encode_value (token - MONO_TOKEN_FIELD_DEF, p, &p);
3075 *endbuf = p;
3078 static void
3079 encode_ginst (MonoAotCompile *acfg, MonoGenericInst *inst, guint8 *buf, guint8 **endbuf)
3081 guint8 *p = buf;
3082 int i;
3084 encode_value (inst->type_argc, p, &p);
3085 for (i = 0; i < inst->type_argc; ++i)
3086 encode_klass_ref (acfg, mono_class_from_mono_type (inst->type_argv [i]), p, &p);
3087 *endbuf = p;
3090 static void
3091 encode_generic_context (MonoAotCompile *acfg, MonoGenericContext *context, guint8 *buf, guint8 **endbuf)
3093 guint8 *p = buf;
3094 MonoGenericInst *inst;
3096 inst = context->class_inst;
3097 if (inst) {
3098 g_assert (inst->type_argc);
3099 encode_ginst (acfg, inst, p, &p);
3100 } else {
3101 encode_value (0, p, &p);
3103 inst = context->method_inst;
3104 if (inst) {
3105 g_assert (inst->type_argc);
3106 encode_ginst (acfg, inst, p, &p);
3107 } else {
3108 encode_value (0, p, &p);
3110 *endbuf = p;
3113 static void
3114 encode_type (MonoAotCompile *acfg, MonoType *t, guint8 *buf, guint8 **endbuf)
3116 guint8 *p = buf;
3118 // Change memory allocation in decode_type if you change
3119 g_assert (!t->has_cmods);
3121 /* t->attrs can be ignored */
3122 //g_assert (t->attrs == 0);
3124 if (t->pinned) {
3125 *p = MONO_TYPE_PINNED;
3126 ++p;
3128 if (t->byref) {
3129 *p = MONO_TYPE_BYREF;
3130 ++p;
3133 *p = t->type;
3134 p ++;
3136 switch (t->type) {
3137 case MONO_TYPE_VOID:
3138 case MONO_TYPE_BOOLEAN:
3139 case MONO_TYPE_CHAR:
3140 case MONO_TYPE_I1:
3141 case MONO_TYPE_U1:
3142 case MONO_TYPE_I2:
3143 case MONO_TYPE_U2:
3144 case MONO_TYPE_I4:
3145 case MONO_TYPE_U4:
3146 case MONO_TYPE_I8:
3147 case MONO_TYPE_U8:
3148 case MONO_TYPE_R4:
3149 case MONO_TYPE_R8:
3150 case MONO_TYPE_I:
3151 case MONO_TYPE_U:
3152 case MONO_TYPE_STRING:
3153 case MONO_TYPE_OBJECT:
3154 case MONO_TYPE_TYPEDBYREF:
3155 break;
3156 case MONO_TYPE_VALUETYPE:
3157 case MONO_TYPE_CLASS:
3158 encode_klass_ref (acfg, mono_class_from_mono_type (t), p, &p);
3159 break;
3160 case MONO_TYPE_SZARRAY:
3161 encode_klass_ref (acfg, t->data.klass, p, &p);
3162 break;
3163 case MONO_TYPE_PTR:
3164 encode_type (acfg, t->data.type, p, &p);
3165 break;
3166 case MONO_TYPE_GENERICINST: {
3167 MonoClass *gclass = t->data.generic_class->container_class;
3168 MonoGenericInst *inst = t->data.generic_class->context.class_inst;
3170 encode_klass_ref (acfg, gclass, p, &p);
3171 encode_ginst (acfg, inst, p, &p);
3172 break;
3174 case MONO_TYPE_ARRAY: {
3175 MonoArrayType *array = t->data.array;
3176 int i;
3178 encode_klass_ref (acfg, array->eklass, p, &p);
3179 encode_value (array->rank, p, &p);
3180 encode_value (array->numsizes, p, &p);
3181 for (i = 0; i < array->numsizes; ++i)
3182 encode_value (array->sizes [i], p, &p);
3183 encode_value (array->numlobounds, p, &p);
3184 for (i = 0; i < array->numlobounds; ++i)
3185 encode_value (array->lobounds [i], p, &p);
3186 break;
3188 case MONO_TYPE_VAR:
3189 case MONO_TYPE_MVAR:
3190 encode_klass_ref (acfg, mono_class_from_mono_type (t), p, &p);
3191 break;
3192 default:
3193 g_assert_not_reached ();
3196 *endbuf = p;
3199 static void
3200 encode_signature (MonoAotCompile *acfg, MonoMethodSignature *sig, guint8 *buf, guint8 **endbuf)
3202 guint8 *p = buf;
3203 guint32 flags = 0;
3204 int i;
3206 /* Similar to the metadata encoding */
3207 if (sig->generic_param_count)
3208 flags |= 0x10;
3209 if (sig->hasthis)
3210 flags |= 0x20;
3211 if (sig->explicit_this)
3212 flags |= 0x40;
3213 flags |= (sig->call_convention & 0x0F);
3215 *p = flags;
3216 ++p;
3217 if (sig->generic_param_count)
3218 encode_value (sig->generic_param_count, p, &p);
3219 encode_value (sig->param_count, p, &p);
3221 encode_type (acfg, sig->ret, p, &p);
3222 for (i = 0; i < sig->param_count; ++i) {
3223 if (sig->sentinelpos == i) {
3224 *p = MONO_TYPE_SENTINEL;
3225 ++p;
3227 encode_type (acfg, sig->params [i], p, &p);
3230 *endbuf = p;
3233 #define MAX_IMAGE_INDEX 250
3235 static void
3236 encode_method_ref (MonoAotCompile *acfg, MonoMethod *method, guint8 *buf, guint8 **endbuf)
3238 guint32 image_index = get_image_index (acfg, m_class_get_image (method->klass));
3239 guint32 token = method->token;
3240 MonoJumpInfoToken *ji;
3241 guint8 *p = buf;
3244 * The encoding for most methods is as follows:
3245 * - image index encoded as a leb128
3246 * - token index encoded as a leb128
3247 * Values of image index >= MONO_AOT_METHODREF_MIN are used to mark additional
3248 * types of method encodings.
3251 /* Mark methods which can't use aot trampolines because they need the further
3252 * processing in mono_magic_trampoline () which requires a MonoMethod*.
3254 if ((method->is_generic && (method->flags & METHOD_ATTRIBUTE_VIRTUAL)) ||
3255 (method->iflags & METHOD_IMPL_ATTRIBUTE_SYNCHRONIZED))
3256 encode_value ((MONO_AOT_METHODREF_NO_AOT_TRAMPOLINE << 24), p, &p);
3258 if (method->wrapper_type) {
3259 WrapperInfo *info = mono_marshal_get_wrapper_info (method);
3261 encode_value ((MONO_AOT_METHODREF_WRAPPER << 24), p, &p);
3263 encode_value (method->wrapper_type, p, &p);
3265 switch (method->wrapper_type) {
3266 case MONO_WRAPPER_REMOTING_INVOKE:
3267 case MONO_WRAPPER_REMOTING_INVOKE_WITH_CHECK:
3268 case MONO_WRAPPER_XDOMAIN_INVOKE: {
3269 MonoMethod *m;
3271 m = mono_marshal_method_from_wrapper (method);
3272 g_assert (m);
3273 encode_method_ref (acfg, m, p, &p);
3274 break;
3276 case MONO_WRAPPER_PROXY_ISINST:
3277 case MONO_WRAPPER_LDFLD:
3278 case MONO_WRAPPER_LDFLDA:
3279 case MONO_WRAPPER_STFLD: {
3280 g_assert (info);
3281 encode_klass_ref (acfg, info->d.proxy.klass, p, &p);
3282 break;
3284 case MONO_WRAPPER_ALLOC: {
3285 /* The GC name is saved once in MonoAotFileInfo */
3286 g_assert (info->d.alloc.alloc_type != -1);
3287 encode_value (info->d.alloc.alloc_type, p, &p);
3288 break;
3290 case MONO_WRAPPER_WRITE_BARRIER: {
3291 g_assert (info);
3292 break;
3294 case MONO_WRAPPER_STELEMREF: {
3295 g_assert (info);
3296 encode_value (info->subtype, p, &p);
3297 if (info->subtype == WRAPPER_SUBTYPE_VIRTUAL_STELEMREF)
3298 encode_value (info->d.virtual_stelemref.kind, p, &p);
3299 break;
3301 case MONO_WRAPPER_UNKNOWN: {
3302 g_assert (info);
3303 encode_value (info->subtype, p, &p);
3304 if (info->subtype == WRAPPER_SUBTYPE_PTR_TO_STRUCTURE ||
3305 info->subtype == WRAPPER_SUBTYPE_STRUCTURE_TO_PTR)
3306 encode_klass_ref (acfg, method->klass, p, &p);
3307 else if (info->subtype == WRAPPER_SUBTYPE_SYNCHRONIZED_INNER)
3308 encode_method_ref (acfg, info->d.synchronized_inner.method, p, &p);
3309 else if (info->subtype == WRAPPER_SUBTYPE_ARRAY_ACCESSOR)
3310 encode_method_ref (acfg, info->d.array_accessor.method, p, &p);
3311 else if (info->subtype == WRAPPER_SUBTYPE_INTERP_IN)
3312 encode_signature (acfg, info->d.interp_in.sig, p, &p);
3313 else if (info->subtype == WRAPPER_SUBTYPE_GSHAREDVT_IN_SIG)
3314 encode_signature (acfg, info->d.gsharedvt.sig, p, &p);
3315 else if (info->subtype == WRAPPER_SUBTYPE_GSHAREDVT_OUT_SIG)
3316 encode_signature (acfg, info->d.gsharedvt.sig, p, &p);
3317 break;
3319 case MONO_WRAPPER_MANAGED_TO_NATIVE: {
3320 g_assert (info);
3321 encode_value (info->subtype, p, &p);
3322 if (info->subtype == WRAPPER_SUBTYPE_ICALL_WRAPPER) {
3323 strcpy ((char*)p, method->name);
3324 p += strlen (method->name) + 1;
3325 } else if (info->subtype == WRAPPER_SUBTYPE_NATIVE_FUNC_AOT) {
3326 encode_method_ref (acfg, info->d.managed_to_native.method, p, &p);
3327 } else {
3328 g_assert (info->subtype == WRAPPER_SUBTYPE_NONE || info->subtype == WRAPPER_SUBTYPE_PINVOKE);
3329 encode_method_ref (acfg, info->d.managed_to_native.method, p, &p);
3331 break;
3333 case MONO_WRAPPER_SYNCHRONIZED: {
3334 MonoMethod *m;
3336 m = mono_marshal_method_from_wrapper (method);
3337 g_assert (m);
3338 g_assert (m != method);
3339 encode_method_ref (acfg, m, p, &p);
3340 break;
3342 case MONO_WRAPPER_MANAGED_TO_MANAGED: {
3343 g_assert (info);
3344 encode_value (info->subtype, p, &p);
3346 if (info->subtype == WRAPPER_SUBTYPE_ELEMENT_ADDR) {
3347 encode_value (info->d.element_addr.rank, p, &p);
3348 encode_value (info->d.element_addr.elem_size, p, &p);
3349 } else if (info->subtype == WRAPPER_SUBTYPE_STRING_CTOR) {
3350 encode_method_ref (acfg, info->d.string_ctor.method, p, &p);
3351 } else {
3352 g_assert_not_reached ();
3354 break;
3356 case MONO_WRAPPER_CASTCLASS: {
3357 g_assert (info);
3358 encode_value (info->subtype, p, &p);
3359 break;
3361 case MONO_WRAPPER_RUNTIME_INVOKE: {
3362 g_assert (info);
3363 encode_value (info->subtype, p, &p);
3364 if (info->subtype == WRAPPER_SUBTYPE_RUNTIME_INVOKE_DIRECT || info->subtype == WRAPPER_SUBTYPE_RUNTIME_INVOKE_VIRTUAL)
3365 encode_method_ref (acfg, info->d.runtime_invoke.method, p, &p);
3366 else if (info->subtype == WRAPPER_SUBTYPE_RUNTIME_INVOKE_NORMAL)
3367 encode_signature (acfg, info->d.runtime_invoke.sig, p, &p);
3368 break;
3370 case MONO_WRAPPER_DELEGATE_INVOKE:
3371 case MONO_WRAPPER_DELEGATE_BEGIN_INVOKE:
3372 case MONO_WRAPPER_DELEGATE_END_INVOKE: {
3373 if (method->is_inflated) {
3374 /* These wrappers are identified by their class */
3375 encode_value (1, p, &p);
3376 encode_klass_ref (acfg, method->klass, p, &p);
3377 } else {
3378 MonoMethodSignature *sig = mono_method_signature (method);
3379 WrapperInfo *info = mono_marshal_get_wrapper_info (method);
3381 encode_value (0, p, &p);
3382 if (method->wrapper_type == MONO_WRAPPER_DELEGATE_INVOKE)
3383 encode_value (info ? info->subtype : 0, p, &p);
3384 encode_signature (acfg, sig, p, &p);
3386 break;
3388 case MONO_WRAPPER_NATIVE_TO_MANAGED: {
3389 g_assert (info);
3390 encode_method_ref (acfg, info->d.native_to_managed.method, p, &p);
3391 encode_klass_ref (acfg, info->d.native_to_managed.klass, p, &p);
3392 break;
3394 default:
3395 g_assert_not_reached ();
3397 } else if (mono_method_signature (method)->is_inflated) {
3399 * This is a generic method, find the original token which referenced it and
3400 * encode that.
3401 * Obtain the token from information recorded by the JIT.
3403 ji = (MonoJumpInfoToken *)g_hash_table_lookup (acfg->token_info_hash, method);
3404 if (ji) {
3405 image_index = get_image_index (acfg, ji->image);
3406 g_assert (image_index < MAX_IMAGE_INDEX);
3407 token = ji->token;
3409 encode_value ((MONO_AOT_METHODREF_METHODSPEC << 24), p, &p);
3410 encode_value (image_index, p, &p);
3411 encode_value (token, p, &p);
3412 } else {
3413 MonoMethod *declaring;
3414 MonoGenericContext *context = mono_method_get_context (method);
3416 g_assert (method->is_inflated);
3417 declaring = ((MonoMethodInflated*)method)->declaring;
3420 * This might be a non-generic method of a generic instance, which
3421 * doesn't have a token since the reference is generated by the JIT
3422 * like Nullable:Box/Unbox, or by generic sharing.
3424 encode_value ((MONO_AOT_METHODREF_GINST << 24), p, &p);
3425 /* Encode the klass */
3426 encode_klass_ref (acfg, method->klass, p, &p);
3427 /* Encode the method */
3428 image_index = get_image_index (acfg, m_class_get_image (method->klass));
3429 g_assert (image_index < MAX_IMAGE_INDEX);
3430 g_assert (declaring->token);
3431 token = declaring->token;
3432 g_assert (mono_metadata_token_table (token) == MONO_TABLE_METHOD);
3433 encode_value (image_index, p, &p);
3434 encode_value (token, p, &p);
3435 encode_generic_context (acfg, context, p, &p);
3437 } else if (token == 0) {
3438 /* This might be a method of a constructed type like int[,].Set */
3439 /* Obtain the token from information recorded by the JIT */
3440 ji = (MonoJumpInfoToken *)g_hash_table_lookup (acfg->token_info_hash, method);
3441 if (ji) {
3442 image_index = get_image_index (acfg, ji->image);
3443 g_assert (image_index < MAX_IMAGE_INDEX);
3444 token = ji->token;
3446 encode_value ((MONO_AOT_METHODREF_METHODSPEC << 24), p, &p);
3447 encode_value (image_index, p, &p);
3448 encode_value (token, p, &p);
3449 } else {
3450 /* Array methods */
3451 g_assert (m_class_get_rank (method->klass));
3453 /* Encode directly */
3454 encode_value ((MONO_AOT_METHODREF_ARRAY << 24), p, &p);
3455 encode_klass_ref (acfg, method->klass, p, &p);
3456 if (!strcmp (method->name, ".ctor") && mono_method_signature (method)->param_count == m_class_get_rank (method->klass))
3457 encode_value (0, p, &p);
3458 else if (!strcmp (method->name, ".ctor") && mono_method_signature (method)->param_count == m_class_get_rank (method->klass) * 2)
3459 encode_value (1, p, &p);
3460 else if (!strcmp (method->name, "Get"))
3461 encode_value (2, p, &p);
3462 else if (!strcmp (method->name, "Address"))
3463 encode_value (3, p, &p);
3464 else if (!strcmp (method->name, "Set"))
3465 encode_value (4, p, &p);
3466 else
3467 g_assert_not_reached ();
3469 } else {
3470 g_assert (mono_metadata_token_table (token) == MONO_TABLE_METHOD);
3472 if (image_index >= MONO_AOT_METHODREF_MIN) {
3473 encode_value ((MONO_AOT_METHODREF_LARGE_IMAGE_INDEX << 24), p, &p);
3474 encode_value (image_index, p, &p);
3475 encode_value (mono_metadata_token_index (token), p, &p);
3476 } else {
3477 encode_value ((image_index << 24) | mono_metadata_token_index (token), p, &p);
3480 *endbuf = p;
3483 static gint
3484 compare_patches (gconstpointer a, gconstpointer b)
3486 int i, j;
3488 i = (*(MonoJumpInfo**)a)->ip.i;
3489 j = (*(MonoJumpInfo**)b)->ip.i;
3491 if (i < j)
3492 return -1;
3493 else
3494 if (i > j)
3495 return 1;
3496 else
3497 return 0;
3500 static G_GNUC_UNUSED char*
3501 patch_to_string (MonoJumpInfo *patch_info)
3503 GString *str;
3505 str = g_string_new ("");
3507 g_string_append_printf (str, "%s(", get_patch_name (patch_info->type));
3509 switch (patch_info->type) {
3510 case MONO_PATCH_INFO_VTABLE:
3511 mono_type_get_desc (str, m_class_get_byval_arg (patch_info->data.klass), TRUE);
3512 break;
3513 default:
3514 break;
3516 g_string_append_printf (str, ")");
3517 return g_string_free (str, FALSE);
3521 * is_plt_patch:
3523 * Return whenever PATCH_INFO refers to a direct call, and thus requires a
3524 * PLT entry.
3526 static inline gboolean
3527 is_plt_patch (MonoJumpInfo *patch_info)
3529 switch (patch_info->type) {
3530 case MONO_PATCH_INFO_METHOD:
3531 case MONO_PATCH_INFO_INTERNAL_METHOD:
3532 case MONO_PATCH_INFO_JIT_ICALL_ADDR:
3533 case MONO_PATCH_INFO_ICALL_ADDR_CALL:
3534 case MONO_PATCH_INFO_RGCTX_FETCH:
3535 return TRUE;
3536 default:
3537 return FALSE;
3542 * get_plt_symbol:
3544 * Return the symbol identifying the plt entry PLT_OFFSET.
3546 static char*
3547 get_plt_symbol (MonoAotCompile *acfg, int plt_offset, MonoJumpInfo *patch_info)
3549 #ifdef TARGET_MACH
3551 * The Apple linker reorganizes object files, so it doesn't like branches to local
3552 * labels, since those have no relocations.
3554 return g_strdup_printf ("%sp_%d", acfg->llvm_label_prefix, plt_offset);
3555 #else
3556 return g_strdup_printf ("%sp_%d", acfg->temp_prefix, plt_offset);
3557 #endif
3561 * get_plt_entry:
3563 * Return a PLT entry which belongs to the method identified by PATCH_INFO.
3565 static MonoPltEntry*
3566 get_plt_entry (MonoAotCompile *acfg, MonoJumpInfo *patch_info)
3568 MonoPltEntry *res;
3569 gboolean synchronized = FALSE;
3570 static int synchronized_symbol_idx;
3572 if (!is_plt_patch (patch_info))
3573 return NULL;
3575 if (!acfg->patch_to_plt_entry [patch_info->type])
3576 acfg->patch_to_plt_entry [patch_info->type] = g_hash_table_new (mono_patch_info_hash, mono_patch_info_equal);
3577 res = (MonoPltEntry *)g_hash_table_lookup (acfg->patch_to_plt_entry [patch_info->type], patch_info);
3579 if (!acfg->llvm && patch_info->type == MONO_PATCH_INFO_METHOD && (patch_info->data.method->iflags & METHOD_IMPL_ATTRIBUTE_SYNCHRONIZED)) {
3581 * Allocate a separate PLT slot for each such patch, since some plt
3582 * entries will refer to the method itself, and some will refer to the
3583 * wrapper.
3585 res = NULL;
3586 synchronized = TRUE;
3589 if (!res) {
3590 MonoJumpInfo *new_ji;
3592 new_ji = mono_patch_info_dup_mp (acfg->mempool, patch_info);
3594 res = (MonoPltEntry *)mono_mempool_alloc0 (acfg->mempool, sizeof (MonoPltEntry));
3595 res->plt_offset = acfg->plt_offset;
3596 res->ji = new_ji;
3597 res->symbol = get_plt_symbol (acfg, res->plt_offset, patch_info);
3598 if (acfg->aot_opts.write_symbols)
3599 res->debug_sym = get_plt_entry_debug_sym (acfg, res->ji, acfg->plt_entry_debug_sym_cache);
3600 if (synchronized) {
3601 /* Avoid duplicate symbols because we don't cache */
3602 res->symbol = g_strdup_printf ("%s_%d", res->symbol, synchronized_symbol_idx);
3603 if (res->debug_sym)
3604 res->debug_sym = g_strdup_printf ("%s_%d", res->debug_sym, synchronized_symbol_idx);
3605 synchronized_symbol_idx ++;
3607 if (res->debug_sym)
3608 res->llvm_symbol = g_strdup_printf ("%s_%s_llvm", res->symbol, res->debug_sym);
3609 else
3610 res->llvm_symbol = g_strdup_printf ("%s_llvm", res->symbol);
3612 g_hash_table_insert (acfg->patch_to_plt_entry [new_ji->type], new_ji, res);
3614 g_hash_table_insert (acfg->plt_offset_to_entry, GUINT_TO_POINTER (res->plt_offset), res);
3616 //g_assert (mono_patch_info_equal (patch_info, new_ji));
3617 //mono_print_ji (patch_info); printf ("\n");
3618 //g_hash_table_print_stats (acfg->patch_to_plt_entry);
3620 acfg->plt_offset ++;
3623 return res;
3627 * get_got_offset:
3629 * Returns the offset of the GOT slot where the runtime object resulting from resolving
3630 * JI could be found if it exists, otherwise allocates a new one.
3632 static guint32
3633 get_got_offset (MonoAotCompile *acfg, gboolean llvm, MonoJumpInfo *ji)
3635 guint32 got_offset;
3636 GotInfo *info = llvm ? &acfg->llvm_got_info : &acfg->got_info;
3638 got_offset = GPOINTER_TO_UINT (g_hash_table_lookup (info->patch_to_got_offset_by_type [ji->type], ji));
3639 if (got_offset)
3640 return got_offset - 1;
3642 if (llvm) {
3643 got_offset = acfg->llvm_got_offset;
3644 acfg->llvm_got_offset ++;
3645 } else {
3646 got_offset = acfg->got_offset;
3647 acfg->got_offset ++;
3650 acfg->stats.got_slots ++;
3651 acfg->stats.got_slot_types [ji->type] ++;
3653 g_hash_table_insert (info->patch_to_got_offset, ji, GUINT_TO_POINTER (got_offset + 1));
3654 g_hash_table_insert (info->patch_to_got_offset_by_type [ji->type], ji, GUINT_TO_POINTER (got_offset + 1));
3655 g_ptr_array_add (info->got_patches, ji);
3657 return got_offset;
3660 /* Add a method to the list of methods which need to be emitted */
3661 static void
3662 add_method_with_index (MonoAotCompile *acfg, MonoMethod *method, int index, gboolean extra)
3664 g_assert (method);
3665 if (!g_hash_table_lookup (acfg->method_indexes, method)) {
3666 g_ptr_array_add (acfg->methods, method);
3667 g_hash_table_insert (acfg->method_indexes, method, GUINT_TO_POINTER (index + 1));
3668 acfg->nmethods = acfg->methods->len + 1;
3671 if (method->wrapper_type || extra)
3672 g_ptr_array_add (acfg->extra_methods, method);
3675 static gboolean
3676 prefer_gsharedvt_method (MonoAotCompile *acfg, MonoMethod *method)
3678 /* One instantiation with valuetypes is generated for each async method */
3679 if (m_class_get_image (method->klass) == mono_defaults.corlib && (!strcmp (m_class_get_name (method->klass), "AsyncMethodBuilderCore") || !strcmp (m_class_get_name (method->klass), "AsyncVoidMethodBuilder")))
3680 return TRUE;
3681 else
3682 return FALSE;
3685 static guint32
3686 get_method_index (MonoAotCompile *acfg, MonoMethod *method)
3688 int index = GPOINTER_TO_UINT (g_hash_table_lookup (acfg->method_indexes, method));
3690 g_assert (index);
3692 return index - 1;
3695 static int
3696 add_method_full (MonoAotCompile *acfg, MonoMethod *method, gboolean extra, int depth)
3698 int index;
3700 index = GPOINTER_TO_UINT (g_hash_table_lookup (acfg->method_indexes, method));
3701 if (index)
3702 return index - 1;
3704 index = acfg->method_index;
3705 add_method_with_index (acfg, method, index, extra);
3707 g_ptr_array_add (acfg->method_order, GUINT_TO_POINTER (index));
3709 g_hash_table_insert (acfg->method_depth, method, GUINT_TO_POINTER (depth));
3711 acfg->method_index ++;
3713 return index;
3716 static int
3717 add_method (MonoAotCompile *acfg, MonoMethod *method)
3719 return add_method_full (acfg, method, FALSE, 0);
3722 static void
3723 mono_dedup_cache_method (MonoAotCompile *acfg, MonoMethod *method)
3725 g_assert (acfg->dedup_stats);
3727 char *name = mono_aot_get_mangled_method_name (method);
3728 g_assert (name);
3730 // For stats
3731 char *stats_name = g_strdup (name);
3733 g_assert (acfg->dedup_cache);
3735 if (!g_hash_table_lookup (acfg->dedup_cache, name)) {
3736 // This AOTCompile owns this method
3737 // We do this to decide whether to write it to disk
3738 // during a dedup run (first phase, where we skip).
3740 // If never changed, then maybe can avoid a recompile
3741 // of the cache.
3743 // Files not read in during last phase.
3744 acfg->dedup_cache_changed = TRUE;
3746 // owns name
3747 g_hash_table_insert (acfg->dedup_cache, name, method);
3748 } else {
3749 // owns name
3750 g_free (name);
3753 guint count = GPOINTER_TO_UINT (g_hash_table_lookup (acfg->dedup_stats, stats_name));
3754 count++;
3755 g_hash_table_insert (acfg->dedup_stats, stats_name, GUINT_TO_POINTER (count));
3758 static void
3759 add_extra_method_with_depth (MonoAotCompile *acfg, MonoMethod *method, int depth)
3761 ERROR_DECL (error);
3762 if (mono_method_is_generic_sharable_full (method, TRUE, TRUE, FALSE)) {
3763 method = mini_get_shared_method_full (method, SHARE_MODE_NONE, error);
3764 mono_error_assert_ok (error);
3766 else if ((acfg->opts & MONO_OPT_GSHAREDVT) && prefer_gsharedvt_method (acfg, method) && mono_method_is_generic_sharable_full (method, FALSE, FALSE, TRUE)) {
3767 /* Use the gsharedvt version */
3768 method = mini_get_shared_method_full (method, SHARE_MODE_GSHAREDVT, error);
3769 mono_error_assert_ok (error);
3772 if ((acfg->aot_opts.dedup || acfg->aot_opts.dedup_include) && mono_aot_can_dedup (method)) {
3773 mono_dedup_cache_method (acfg, method);
3775 if (!acfg->dedup_emit_mode)
3776 return;
3779 if (acfg->aot_opts.log_generics)
3780 aot_printf (acfg, "%*sAdding method %s.\n", depth, "", mono_method_get_full_name (method));
3782 add_method_full (acfg, method, TRUE, depth);
3785 static void
3786 add_extra_method (MonoAotCompile *acfg, MonoMethod *method)
3788 add_extra_method_with_depth (acfg, method, 0);
3791 static void
3792 add_jit_icall_wrapper (gpointer key, gpointer value, gpointer user_data)
3794 MonoAotCompile *acfg = (MonoAotCompile *)user_data;
3795 MonoJitICallInfo *callinfo = (MonoJitICallInfo *)value;
3796 MonoMethod *wrapper;
3797 char *name;
3799 if (!callinfo->sig)
3800 return;
3802 name = g_strdup_printf ("__icall_wrapper_%s", callinfo->name);
3803 wrapper = mono_marshal_get_icall_wrapper (callinfo->sig, name, callinfo->func, TRUE);
3804 g_free (name);
3806 add_method (acfg, wrapper);
3809 static MonoMethod*
3810 get_runtime_invoke_sig (MonoMethodSignature *sig)
3812 MonoMethodBuilder *mb;
3813 MonoMethod *m;
3815 mb = mono_mb_new (mono_defaults.object_class, "FOO", MONO_WRAPPER_NONE);
3816 m = mono_mb_create_method (mb, sig, 16);
3817 MonoMethod *invoke = mono_marshal_get_runtime_invoke (m, FALSE);
3818 mono_mb_free (mb);
3819 return invoke;
3822 static MonoMethod*
3823 get_runtime_invoke (MonoAotCompile *acfg, MonoMethod *method, gboolean virtual_)
3825 return mono_marshal_get_runtime_invoke (method, virtual_);
3828 static gboolean
3829 can_marshal_struct (MonoClass *klass)
3831 MonoClassField *field;
3832 gboolean can_marshal = TRUE;
3833 gpointer iter = NULL;
3834 MonoMarshalType *info;
3835 int i;
3837 if (mono_class_is_auto_layout (klass))
3838 return FALSE;
3840 info = mono_marshal_load_type_info (klass);
3842 /* Only allow a few field types to avoid asserts in the marshalling code */
3843 while ((field = mono_class_get_fields (klass, &iter))) {
3844 if ((field->type->attrs & FIELD_ATTRIBUTE_STATIC))
3845 continue;
3847 switch (field->type->type) {
3848 case MONO_TYPE_I4:
3849 case MONO_TYPE_U4:
3850 case MONO_TYPE_I1:
3851 case MONO_TYPE_U1:
3852 case MONO_TYPE_BOOLEAN:
3853 case MONO_TYPE_I2:
3854 case MONO_TYPE_U2:
3855 case MONO_TYPE_CHAR:
3856 case MONO_TYPE_I8:
3857 case MONO_TYPE_U8:
3858 case MONO_TYPE_I:
3859 case MONO_TYPE_U:
3860 case MONO_TYPE_PTR:
3861 case MONO_TYPE_R4:
3862 case MONO_TYPE_R8:
3863 case MONO_TYPE_STRING:
3864 break;
3865 case MONO_TYPE_VALUETYPE:
3866 if (!m_class_is_enumtype (mono_class_from_mono_type (field->type)) && !can_marshal_struct (mono_class_from_mono_type (field->type)))
3867 can_marshal = FALSE;
3868 break;
3869 case MONO_TYPE_SZARRAY: {
3870 gboolean has_mspec = FALSE;
3872 if (info) {
3873 for (i = 0; i < info->num_fields; ++i) {
3874 if (info->fields [i].field == field && info->fields [i].mspec)
3875 has_mspec = TRUE;
3878 if (!has_mspec)
3879 can_marshal = FALSE;
3880 break;
3882 default:
3883 can_marshal = FALSE;
3884 break;
3888 /* Special cases */
3889 /* Its hard to compute whenever these can be marshalled or not */
3890 if (!strcmp (m_class_get_name_space (klass), "System.Net.NetworkInformation.MacOsStructs") && strcmp (m_class_get_name (klass), "sockaddr_dl"))
3891 return TRUE;
3893 return can_marshal;
3896 static void
3897 create_gsharedvt_inst (MonoAotCompile *acfg, MonoMethod *method, MonoGenericContext *ctx)
3899 /* Create a vtype instantiation */
3900 MonoGenericContext shared_context;
3901 MonoType **args;
3902 MonoGenericInst *inst;
3903 MonoGenericContainer *container;
3904 MonoClass **constraints;
3905 int i;
3907 memset (ctx, 0, sizeof (MonoGenericContext));
3909 if (mono_class_is_gtd (method->klass)) {
3910 shared_context = mono_class_get_generic_container (method->klass)->context;
3911 inst = shared_context.class_inst;
3913 args = g_new0 (MonoType*, inst->type_argc);
3914 for (i = 0; i < inst->type_argc; ++i) {
3915 args [i] = m_class_get_byval_arg (mono_defaults.int_class);
3917 ctx->class_inst = mono_metadata_get_generic_inst (inst->type_argc, args);
3919 if (method->is_generic) {
3920 container = mono_method_get_generic_container (method);
3921 g_assert (!container->is_anonymous && container->is_method);
3922 shared_context = container->context;
3923 inst = shared_context.method_inst;
3925 args = g_new0 (MonoType*, inst->type_argc);
3926 for (i = 0; i < container->type_argc; ++i) {
3927 MonoGenericParamInfo *info = mono_generic_param_info (&container->type_params [i]);
3928 gboolean ref_only = FALSE;
3930 if (info && info->constraints) {
3931 constraints = info->constraints;
3933 while (*constraints) {
3934 MonoClass *cklass = *constraints;
3935 if (!(cklass == mono_defaults.object_class || (m_class_get_image (cklass) == mono_defaults.corlib && !strcmp (m_class_get_name (cklass), "ValueType"))))
3936 /* Inflaring the method with our vtype would not be valid */
3937 ref_only = TRUE;
3938 constraints ++;
3942 if (ref_only)
3943 args [i] = m_class_get_byval_arg (mono_defaults.object_class);
3944 else
3945 args [i] = m_class_get_byval_arg (mono_defaults.int_class);
3947 ctx->method_inst = mono_metadata_get_generic_inst (inst->type_argc, args);
3951 static void
3952 add_wrappers (MonoAotCompile *acfg)
3954 MonoMethod *method, *m;
3955 int i, j;
3956 MonoMethodSignature *sig, *csig;
3957 guint32 token;
3960 * FIXME: Instead of AOTing all the wrappers, it might be better to redesign them
3961 * so there is only one wrapper of a given type, or inlining their contents into their
3962 * callers.
3964 for (i = 0; i < acfg->image->tables [MONO_TABLE_METHOD].rows; ++i) {
3965 ERROR_DECL (error);
3966 MonoMethod *method;
3967 guint32 token = MONO_TOKEN_METHOD_DEF | (i + 1);
3968 gboolean skip = FALSE;
3970 method = mono_get_method_checked (acfg->image, token, NULL, NULL, error);
3971 report_loader_error (acfg, error, TRUE, "Failed to load method token 0x%x due to %s\n", i, mono_error_get_message (error));
3973 if ((method->flags & METHOD_ATTRIBUTE_PINVOKE_IMPL) ||
3974 (method->iflags & METHOD_IMPL_ATTRIBUTE_RUNTIME) ||
3975 (method->flags & METHOD_ATTRIBUTE_ABSTRACT))
3976 skip = TRUE;
3978 /* Skip methods which can not be handled by get_runtime_invoke () */
3979 sig = mono_method_signature (method);
3980 if (!sig)
3981 continue;
3982 if ((sig->ret->type == MONO_TYPE_PTR) ||
3983 (sig->ret->type == MONO_TYPE_TYPEDBYREF))
3984 skip = TRUE;
3985 if (mono_class_is_open_constructed_type (sig->ret))
3986 skip = TRUE;
3988 for (j = 0; j < sig->param_count; j++) {
3989 if (sig->params [j]->type == MONO_TYPE_TYPEDBYREF)
3990 skip = TRUE;
3991 if (mono_class_is_open_constructed_type (sig->params [j]))
3992 skip = TRUE;
3995 #ifdef MONO_ARCH_DYN_CALL_SUPPORTED
3996 if (!mono_class_is_contextbound (method->klass)) {
3997 MonoDynCallInfo *info = mono_arch_dyn_call_prepare (sig);
3998 gboolean has_nullable = FALSE;
4000 for (j = 0; j < sig->param_count; j++) {
4001 if (sig->params [j]->type == MONO_TYPE_GENERICINST && mono_class_is_nullable (mono_class_from_mono_type (sig->params [j])))
4002 has_nullable = TRUE;
4005 if (info && !has_nullable && !acfg->aot_opts.llvm_only) {
4006 /* Supported by the dynamic runtime-invoke wrapper */
4007 skip = TRUE;
4009 if (info)
4010 mono_arch_dyn_call_free (info);
4012 #endif
4014 if (acfg->aot_opts.llvm_only)
4015 /* Supported by the gsharedvt based runtime-invoke wrapper */
4016 skip = TRUE;
4018 if (!skip) {
4019 //printf ("%s\n", mono_method_full_name (method, TRUE));
4020 add_method (acfg, get_runtime_invoke (acfg, method, FALSE));
4024 if (strcmp (acfg->image->assembly->aname.name, "mscorlib") == 0) {
4025 int nallocators;
4027 /* Runtime invoke wrappers */
4029 MonoType *void_type = m_class_get_byval_arg (mono_defaults.void_class);
4030 MonoType *string_type = m_class_get_byval_arg (mono_defaults.string_class);
4032 /* void runtime-invoke () [.cctor] */
4033 csig = mono_metadata_signature_alloc (mono_defaults.corlib, 0);
4034 csig->ret = void_type;
4035 add_method (acfg, get_runtime_invoke_sig (csig));
4037 /* void runtime-invoke () [Finalize] */
4038 csig = mono_metadata_signature_alloc (mono_defaults.corlib, 0);
4039 csig->hasthis = 1;
4040 csig->ret = void_type;
4041 add_method (acfg, get_runtime_invoke_sig (csig));
4043 /* void runtime-invoke (string) [exception ctor] */
4044 csig = mono_metadata_signature_alloc (mono_defaults.corlib, 1);
4045 csig->hasthis = 1;
4046 csig->ret = void_type;
4047 csig->params [0] = string_type;
4048 add_method (acfg, get_runtime_invoke_sig (csig));
4050 /* void runtime-invoke (string, string) [exception ctor] */
4051 csig = mono_metadata_signature_alloc (mono_defaults.corlib, 2);
4052 csig->hasthis = 1;
4053 csig->ret = void_type;
4054 csig->params [0] = string_type;
4055 csig->params [1] = string_type;
4056 add_method (acfg, get_runtime_invoke_sig (csig));
4058 /* string runtime-invoke () [Exception.ToString ()] */
4059 csig = mono_metadata_signature_alloc (mono_defaults.corlib, 0);
4060 csig->hasthis = 1;
4061 csig->ret = string_type;
4062 add_method (acfg, get_runtime_invoke_sig (csig));
4064 /* void runtime-invoke (string, Exception) [exception ctor] */
4065 csig = mono_metadata_signature_alloc (mono_defaults.corlib, 2);
4066 csig->hasthis = 1;
4067 csig->ret = void_type;
4068 csig->params [0] = string_type;
4069 csig->params [1] = m_class_get_byval_arg (mono_defaults.exception_class);
4070 add_method (acfg, get_runtime_invoke_sig (csig));
4072 /* Assembly runtime-invoke (string, Assembly, bool) [DoAssemblyResolve] */
4073 csig = mono_metadata_signature_alloc (mono_defaults.corlib, 3);
4074 csig->hasthis = 1;
4075 csig->ret = m_class_get_byval_arg (mono_class_load_from_name (mono_defaults.corlib, "System.Reflection", "Assembly"));
4076 csig->params [0] = string_type;
4077 csig->params [1] = m_class_get_byval_arg (mono_class_load_from_name (mono_defaults.corlib, "System.Reflection", "Assembly"));
4078 csig->params [2] = m_class_get_byval_arg (mono_defaults.boolean_class);
4079 add_method (acfg, get_runtime_invoke_sig (csig));
4081 /* runtime-invoke used by finalizers */
4082 add_method (acfg, get_runtime_invoke (acfg, mono_class_get_method_from_name_flags (mono_defaults.object_class, "Finalize", 0, 0), TRUE));
4084 /* This is used by mono_runtime_capture_context () */
4085 method = mono_get_context_capture_method ();
4086 if (method)
4087 add_method (acfg, get_runtime_invoke (acfg, method, FALSE));
4089 #ifdef MONO_ARCH_DYN_CALL_SUPPORTED
4090 if (!acfg->aot_opts.llvm_only)
4091 add_method (acfg, mono_marshal_get_runtime_invoke_dynamic ());
4092 #endif
4094 /* These are used by mono_jit_runtime_invoke () to calls gsharedvt out wrappers */
4095 if (acfg->aot_opts.llvm_only) {
4096 int variants;
4098 /* Create simplified signatures which match the signature used by the gsharedvt out wrappers */
4099 for (variants = 0; variants < 4; ++variants) {
4100 for (i = 0; i < 16; ++i) {
4101 sig = mini_get_gsharedvt_out_sig_wrapper_signature ((variants & 1) > 0, (variants & 2) > 0, i);
4102 add_extra_method (acfg, mono_marshal_get_runtime_invoke_for_sig (sig));
4104 g_free (sig);
4109 /* stelemref */
4110 add_method (acfg, mono_marshal_get_stelemref ());
4112 /* Managed Allocators */
4113 nallocators = mono_gc_get_managed_allocator_types ();
4114 for (i = 0; i < nallocators; ++i) {
4115 if ((m = mono_gc_get_managed_allocator_by_type (i, MANAGED_ALLOCATOR_REGULAR)))
4116 add_method (acfg, m);
4117 if ((m = mono_gc_get_managed_allocator_by_type (i, MANAGED_ALLOCATOR_SLOW_PATH)))
4118 add_method (acfg, m);
4119 if ((m = mono_gc_get_managed_allocator_by_type (i, MANAGED_ALLOCATOR_PROFILER)))
4120 add_method (acfg, m);
4123 /* write barriers */
4124 if (mono_gc_is_moving ()) {
4125 add_method (acfg, mono_gc_get_specific_write_barrier (FALSE));
4126 add_method (acfg, mono_gc_get_specific_write_barrier (TRUE));
4129 /* Stelemref wrappers */
4131 MonoMethod **wrappers;
4132 int nwrappers;
4134 wrappers = mono_marshal_get_virtual_stelemref_wrappers (&nwrappers);
4135 for (i = 0; i < nwrappers; ++i)
4136 add_method (acfg, wrappers [i]);
4137 g_free (wrappers);
4140 /* castclass_with_check wrapper */
4141 add_method (acfg, mono_marshal_get_castclass_with_cache ());
4142 /* isinst_with_check wrapper */
4143 add_method (acfg, mono_marshal_get_isinst_with_cache ());
4145 /* JIT icall wrappers */
4146 /* FIXME: locking - this is "safe" as full-AOT threads don't mutate the icall hash*/
4147 g_hash_table_foreach (mono_get_jit_icall_info (), add_jit_icall_wrapper, acfg);
4151 * remoting-invoke-with-check wrappers are very frequent, so avoid emitting them,
4152 * we use the original method instead at runtime.
4153 * Since full-aot doesn't support remoting, this is not a problem.
4155 #if 0
4156 /* remoting-invoke wrappers */
4157 for (i = 0; i < acfg->image->tables [MONO_TABLE_METHOD].rows; ++i) {
4158 ERROR_DECL (error);
4159 MonoMethodSignature *sig;
4161 token = MONO_TOKEN_METHOD_DEF | (i + 1);
4162 method = mono_get_method_checked (acfg->image, token, NULL, NULL, error);
4163 g_assert (mono_error_ok (error)); /* FIXME don't swallow the error */
4165 sig = mono_method_signature (method);
4167 if (sig->hasthis && (method->klass->marshalbyref || method->klass == mono_defaults.object_class)) {
4168 m = mono_marshal_get_remoting_invoke_with_check (method);
4170 add_method (acfg, m);
4173 #endif
4175 /* delegate-invoke wrappers */
4176 for (i = 0; i < acfg->image->tables [MONO_TABLE_TYPEDEF].rows; ++i) {
4177 ERROR_DECL (error);
4178 MonoClass *klass;
4179 MonoCustomAttrInfo *cattr;
4181 token = MONO_TOKEN_TYPE_DEF | (i + 1);
4182 klass = mono_class_get_checked (acfg->image, token, error);
4184 if (!klass) {
4185 mono_error_cleanup (error);
4186 continue;
4189 if (!m_class_is_delegate (klass) || klass == mono_defaults.delegate_class || klass == mono_defaults.multicastdelegate_class)
4190 continue;
4192 if (!mono_class_is_gtd (klass)) {
4193 method = mono_get_delegate_invoke (klass);
4195 m = mono_marshal_get_delegate_invoke (method, NULL);
4197 add_method (acfg, m);
4199 method = mono_class_get_method_from_name_flags (klass, "BeginInvoke", -1, 0);
4200 if (method)
4201 add_method (acfg, mono_marshal_get_delegate_begin_invoke (method));
4203 method = mono_class_get_method_from_name_flags (klass, "EndInvoke", -1, 0);
4204 if (method)
4205 add_method (acfg, mono_marshal_get_delegate_end_invoke (method));
4207 cattr = mono_custom_attrs_from_class_checked (klass, error);
4208 if (!is_ok (error)) {
4209 mono_error_cleanup (error);
4210 continue;
4213 if (cattr) {
4214 int j;
4216 for (j = 0; j < cattr->num_attrs; ++j)
4217 if (cattr->attrs [j].ctor && (!strcmp (m_class_get_name (cattr->attrs [j].ctor->klass), "MonoNativeFunctionWrapperAttribute") || !strcmp (m_class_get_name (cattr->attrs [j].ctor->klass), "UnmanagedFunctionPointerAttribute")))
4218 break;
4219 if (j < cattr->num_attrs) {
4220 MonoMethod *invoke;
4221 MonoMethod *wrapper;
4222 MonoMethod *del_invoke;
4224 /* Add wrappers needed by mono_ftnptr_to_delegate () */
4225 invoke = mono_get_delegate_invoke (klass);
4226 wrapper = mono_marshal_get_native_func_wrapper_aot (klass);
4227 del_invoke = mono_marshal_get_delegate_invoke_internal (invoke, FALSE, TRUE, wrapper);
4228 add_method (acfg, wrapper);
4229 add_method (acfg, del_invoke);
4232 } else if ((acfg->opts & MONO_OPT_GSHAREDVT) && mono_class_is_gtd (klass)) {
4233 ERROR_DECL (error);
4234 MonoGenericContext ctx;
4235 MonoMethod *inst, *gshared;
4238 * Emit gsharedvt versions of the generic delegate-invoke wrappers
4240 /* Invoke */
4241 method = mono_get_delegate_invoke (klass);
4242 create_gsharedvt_inst (acfg, method, &ctx);
4244 inst = mono_class_inflate_generic_method_checked (method, &ctx, error);
4245 g_assert (mono_error_ok (error)); /* FIXME don't swallow the error */
4247 m = mono_marshal_get_delegate_invoke (inst, NULL);
4248 g_assert (m->is_inflated);
4250 gshared = mini_get_shared_method_full (m, SHARE_MODE_GSHAREDVT, error);
4251 mono_error_assert_ok (error);
4253 add_extra_method (acfg, gshared);
4255 /* begin-invoke */
4256 method = mono_get_delegate_begin_invoke (klass);
4257 if (method) {
4258 create_gsharedvt_inst (acfg, method, &ctx);
4260 inst = mono_class_inflate_generic_method_checked (method, &ctx, error);
4261 g_assert (mono_error_ok (error)); /* FIXME don't swallow the error */
4263 m = mono_marshal_get_delegate_begin_invoke (inst);
4264 g_assert (m->is_inflated);
4266 gshared = mini_get_shared_method_full (m, SHARE_MODE_GSHAREDVT, error);
4267 mono_error_assert_ok (error);
4269 add_extra_method (acfg, gshared);
4272 /* end-invoke */
4273 method = mono_get_delegate_end_invoke (klass);
4274 if (method) {
4275 create_gsharedvt_inst (acfg, method, &ctx);
4277 inst = mono_class_inflate_generic_method_checked (method, &ctx, error);
4278 g_assert (mono_error_ok (error)); /* FIXME don't swallow the error */
4280 m = mono_marshal_get_delegate_end_invoke (inst);
4281 g_assert (m->is_inflated);
4283 gshared = mini_get_shared_method_full (m, SHARE_MODE_GSHAREDVT, error);
4284 mono_error_assert_ok (error);
4286 add_extra_method (acfg, gshared);
4291 /* array access wrappers */
4292 for (i = 0; i < acfg->image->tables [MONO_TABLE_TYPESPEC].rows; ++i) {
4293 ERROR_DECL (error);
4294 MonoClass *klass;
4296 token = MONO_TOKEN_TYPE_SPEC | (i + 1);
4297 klass = mono_class_get_checked (acfg->image, token, error);
4299 if (!klass) {
4300 mono_error_cleanup (error);
4301 continue;
4304 if (m_class_get_rank (klass) && MONO_TYPE_IS_PRIMITIVE (m_class_get_byval_arg (m_class_get_element_class (klass)))) {
4305 MonoMethod *m, *wrapper;
4307 /* Add runtime-invoke wrappers too */
4309 m = mono_class_get_method_from_name (klass, "Get", -1);
4310 g_assert (m);
4311 wrapper = mono_marshal_get_array_accessor_wrapper (m);
4312 add_extra_method (acfg, wrapper);
4313 if (!acfg->aot_opts.llvm_only)
4314 add_extra_method (acfg, get_runtime_invoke (acfg, wrapper, FALSE));
4316 m = mono_class_get_method_from_name (klass, "Set", -1);
4317 g_assert (m);
4318 wrapper = mono_marshal_get_array_accessor_wrapper (m);
4319 add_extra_method (acfg, wrapper);
4320 if (!acfg->aot_opts.llvm_only)
4321 add_extra_method (acfg, get_runtime_invoke (acfg, wrapper, FALSE));
4325 /* Synchronized wrappers */
4326 for (i = 0; i < acfg->image->tables [MONO_TABLE_METHOD].rows; ++i) {
4327 ERROR_DECL (error);
4328 token = MONO_TOKEN_METHOD_DEF | (i + 1);
4329 method = mono_get_method_checked (acfg->image, token, NULL, NULL, error);
4330 report_loader_error (acfg, error, TRUE, "Failed to load method token 0x%x due to %s\n", i, mono_error_get_message (error));
4332 if (method->iflags & METHOD_IMPL_ATTRIBUTE_SYNCHRONIZED) {
4333 if (method->is_generic) {
4334 // FIXME:
4335 } else if ((acfg->opts & MONO_OPT_GSHAREDVT) && mono_class_is_gtd (method->klass)) {
4336 ERROR_DECL (error);
4337 MonoGenericContext ctx;
4338 MonoMethod *inst, *gshared, *m;
4341 * Create a generic wrapper for a generic instance, and AOT that.
4343 create_gsharedvt_inst (acfg, method, &ctx);
4344 inst = mono_class_inflate_generic_method_checked (method, &ctx, error);
4345 g_assert (mono_error_ok (error)); /* FIXME don't swallow the error */
4346 m = mono_marshal_get_synchronized_wrapper (inst);
4347 g_assert (m->is_inflated);
4348 gshared = mini_get_shared_method_full (m, SHARE_MODE_GSHAREDVT, error);
4349 mono_error_assert_ok (error);
4351 add_method (acfg, gshared);
4352 } else {
4353 add_method (acfg, mono_marshal_get_synchronized_wrapper (method));
4358 /* pinvoke wrappers */
4359 for (i = 0; i < acfg->image->tables [MONO_TABLE_METHOD].rows; ++i) {
4360 ERROR_DECL (error);
4361 MonoMethod *method;
4362 guint32 token = MONO_TOKEN_METHOD_DEF | (i + 1);
4364 method = mono_get_method_checked (acfg->image, token, NULL, NULL, error);
4365 report_loader_error (acfg, error, TRUE, "Failed to load method token 0x%x due to %s\n", i, mono_error_get_message (error));
4367 if ((method->flags & METHOD_ATTRIBUTE_PINVOKE_IMPL) ||
4368 (method->iflags & METHOD_IMPL_ATTRIBUTE_INTERNAL_CALL)) {
4369 add_method (acfg, mono_marshal_get_native_wrapper (method, TRUE, TRUE));
4372 if (method->iflags & METHOD_IMPL_ATTRIBUTE_INTERNAL_CALL) {
4373 if (acfg->aot_opts.llvm_only) {
4374 /* The wrappers have a different signature (hasthis is not set) so need to add this too */
4375 add_gsharedvt_wrappers (acfg, mono_method_signature (method), FALSE, TRUE, FALSE);
4380 /* native-to-managed wrappers */
4381 for (i = 0; i < acfg->image->tables [MONO_TABLE_METHOD].rows; ++i) {
4382 ERROR_DECL (error);
4383 MonoMethod *method;
4384 guint32 token = MONO_TOKEN_METHOD_DEF | (i + 1);
4385 MonoCustomAttrInfo *cattr;
4386 int j;
4388 method = mono_get_method_checked (acfg->image, token, NULL, NULL, error);
4389 report_loader_error (acfg, error, TRUE, "Failed to load method token 0x%x due to %s\n", i, mono_error_get_message (error));
4392 * Only generate native-to-managed wrappers for methods which have an
4393 * attribute named MonoPInvokeCallbackAttribute. We search for the attribute by
4394 * name to avoid defining a new assembly to contain it.
4396 cattr = mono_custom_attrs_from_method_checked (method, error);
4397 if (!is_ok (error)) {
4398 char *name = mono_method_get_full_name (method);
4399 report_loader_error (acfg, error, TRUE, "Failed to load custom attributes from method %s due to %s\n", name, mono_error_get_message (error));
4400 g_free (name);
4403 if (cattr) {
4404 for (j = 0; j < cattr->num_attrs; ++j)
4405 if (cattr->attrs [j].ctor && !strcmp (m_class_get_name (cattr->attrs [j].ctor->klass), "MonoPInvokeCallbackAttribute"))
4406 break;
4407 if (j < cattr->num_attrs) {
4408 MonoCustomAttrEntry *e = &cattr->attrs [j];
4409 MonoMethodSignature *sig = mono_method_signature (e->ctor);
4410 const char *p = (const char*)e->data;
4411 const char *named;
4412 int slen, num_named, named_type;
4413 char *n;
4414 MonoType *t;
4415 MonoClass *klass;
4416 char *export_name = NULL;
4417 MonoMethod *wrapper;
4419 /* this cannot be enforced by the C# compiler so we must give the user some warning before aborting */
4420 if (!(method->flags & METHOD_ATTRIBUTE_STATIC)) {
4421 g_warning ("AOT restriction: Method '%s' must be static since it is decorated with [MonoPInvokeCallback]. See http://ios.xamarin.com/Documentation/Limitations#Reverse_Callbacks",
4422 mono_method_full_name (method, TRUE));
4423 exit (1);
4426 g_assert (sig->param_count == 1);
4427 g_assert (sig->params [0]->type == MONO_TYPE_CLASS && !strcmp (m_class_get_name (mono_class_from_mono_type (sig->params [0])), "Type"));
4430 * Decode the cattr manually since we can't create objects
4431 * during aot compilation.
4434 /* Skip prolog */
4435 p += 2;
4437 /* From load_cattr_value () in reflection.c */
4438 slen = mono_metadata_decode_value (p, &p);
4439 n = (char *)g_memdup (p, slen + 1);
4440 n [slen] = 0;
4441 t = mono_reflection_type_from_name_checked (n, acfg->image, error);
4442 g_assert (t);
4443 mono_error_assert_ok (error);
4444 g_free (n);
4446 klass = mono_class_from_mono_type (t);
4447 g_assert (m_class_get_parent (klass) == mono_defaults.multicastdelegate_class);
4449 p += slen;
4451 num_named = read16 (p);
4452 p += 2;
4454 g_assert (num_named < 2);
4455 if (num_named == 1) {
4456 int name_len;
4457 char *name;
4459 /* parse ExportSymbol attribute */
4460 named = p;
4461 named_type = *named;
4462 named += 1;
4463 /* data_type = *named; */
4464 named += 1;
4466 name_len = mono_metadata_decode_blob_size (named, &named);
4467 name = (char *)g_malloc (name_len + 1);
4468 memcpy (name, named, name_len);
4469 name [name_len] = 0;
4470 named += name_len;
4472 g_assert (named_type == 0x54);
4473 g_assert (!strcmp (name, "ExportSymbol"));
4475 /* load_cattr_value (), string case */
4476 g_assert (*named != (char)0xff);
4477 slen = mono_metadata_decode_value (named, &named);
4478 export_name = (char *)g_malloc (slen + 1);
4479 memcpy (export_name, named, slen);
4480 export_name [slen] = 0;
4481 named += slen;
4484 wrapper = mono_marshal_get_managed_wrapper (method, klass, 0, error);
4485 mono_error_assert_ok (error);
4487 add_method (acfg, wrapper);
4488 if (export_name)
4489 g_hash_table_insert (acfg->export_names, wrapper, export_name);
4491 g_free (cattr);
4494 if ((method->flags & METHOD_ATTRIBUTE_PINVOKE_IMPL) ||
4495 (method->iflags & METHOD_IMPL_ATTRIBUTE_INTERNAL_CALL)) {
4496 add_method (acfg, mono_marshal_get_native_wrapper (method, TRUE, TRUE));
4500 /* StructureToPtr/PtrToStructure wrappers */
4501 for (i = 0; i < acfg->image->tables [MONO_TABLE_TYPEDEF].rows; ++i) {
4502 ERROR_DECL (error);
4503 MonoClass *klass;
4505 token = MONO_TOKEN_TYPE_DEF | (i + 1);
4506 klass = mono_class_get_checked (acfg->image, token, error);
4508 if (!klass) {
4509 mono_error_cleanup (error);
4510 continue;
4513 if (m_class_is_valuetype (klass) && !mono_class_is_gtd (klass) && can_marshal_struct (klass) &&
4514 !(m_class_get_nested_in (klass) && strstr (m_class_get_name (m_class_get_nested_in (klass)), "<PrivateImplementationDetails>") == m_class_get_name (m_class_get_nested_in (klass)))) {
4515 add_method (acfg, mono_marshal_get_struct_to_ptr (klass));
4516 add_method (acfg, mono_marshal_get_ptr_to_struct (klass));
4521 static gboolean
4522 has_type_vars (MonoClass *klass)
4524 if ((m_class_get_byval_arg (klass)->type == MONO_TYPE_VAR) || (m_class_get_byval_arg (klass)->type == MONO_TYPE_MVAR))
4525 return TRUE;
4526 if (m_class_get_rank (klass))
4527 return has_type_vars (m_class_get_element_class (klass));
4528 if (mono_class_is_ginst (klass)) {
4529 MonoGenericContext *context = &mono_class_get_generic_class (klass)->context;
4530 if (context->class_inst) {
4531 int i;
4533 for (i = 0; i < context->class_inst->type_argc; ++i)
4534 if (has_type_vars (mono_class_from_mono_type (context->class_inst->type_argv [i])))
4535 return TRUE;
4538 if (mono_class_is_gtd (klass))
4539 return TRUE;
4540 return FALSE;
4543 static gboolean
4544 is_vt_inst (MonoGenericInst *inst)
4546 int i;
4548 for (i = 0; i < inst->type_argc; ++i) {
4549 MonoType *t = inst->type_argv [i];
4550 if (MONO_TYPE_ISSTRUCT (t) || t->type == MONO_TYPE_VALUETYPE)
4551 return TRUE;
4553 return FALSE;
4556 static gboolean
4557 method_has_type_vars (MonoMethod *method)
4559 if (has_type_vars (method->klass))
4560 return TRUE;
4562 if (method->is_inflated) {
4563 MonoGenericContext *context = mono_method_get_context (method);
4564 if (context->method_inst) {
4565 int i;
4567 for (i = 0; i < context->method_inst->type_argc; ++i)
4568 if (has_type_vars (mono_class_from_mono_type (context->method_inst->type_argv [i])))
4569 return TRUE;
4572 return FALSE;
4575 static
4576 gboolean mono_aot_mode_is_full (MonoAotOptions *opts)
4578 return opts->mode == MONO_AOT_MODE_FULL;
4581 static
4582 gboolean mono_aot_mode_is_interp (MonoAotOptions *opts)
4584 return opts->interp;
4587 static
4588 gboolean mono_aot_mode_is_hybrid (MonoAotOptions *opts)
4590 return opts->mode == MONO_AOT_MODE_HYBRID;
4593 static void add_generic_class_with_depth (MonoAotCompile *acfg, MonoClass *klass, int depth, const char *ref);
4595 static void
4596 add_generic_class (MonoAotCompile *acfg, MonoClass *klass, gboolean force, const char *ref)
4598 /* This might lead to a huge code blowup so only do it if neccesary */
4599 if (!mono_aot_mode_is_full (&acfg->aot_opts) && !mono_aot_mode_is_hybrid (&acfg->aot_opts) && !force)
4600 return;
4602 add_generic_class_with_depth (acfg, klass, 0, ref);
4605 static gboolean
4606 check_type_depth (MonoType *t, int depth)
4608 int i;
4610 if (depth > 8)
4611 return TRUE;
4613 switch (t->type) {
4614 case MONO_TYPE_GENERICINST: {
4615 MonoGenericClass *gklass = t->data.generic_class;
4616 MonoGenericInst *ginst = gklass->context.class_inst;
4618 if (ginst) {
4619 for (i = 0; i < ginst->type_argc; ++i) {
4620 if (check_type_depth (ginst->type_argv [i], depth + 1))
4621 return TRUE;
4624 break;
4626 default:
4627 break;
4630 return FALSE;
4633 static void
4634 add_types_from_method_header (MonoAotCompile *acfg, MonoMethod *method);
4637 * add_generic_class:
4639 * Add all methods of a generic class.
4641 static void
4642 add_generic_class_with_depth (MonoAotCompile *acfg, MonoClass *klass, int depth, const char *ref)
4644 MonoMethod *method;
4645 MonoClassField *field;
4646 gpointer iter;
4647 gboolean use_gsharedvt = FALSE;
4649 if (!acfg->ginst_hash)
4650 acfg->ginst_hash = g_hash_table_new (NULL, NULL);
4652 mono_class_init (klass);
4654 if (mono_class_is_ginst (klass) && mono_class_get_generic_class (klass)->context.class_inst->is_open)
4655 return;
4657 if (has_type_vars (klass))
4658 return;
4660 if (!mono_class_is_ginst (klass) && !m_class_get_rank (klass))
4661 return;
4663 if (mono_class_has_failure (klass))
4664 return;
4666 if (!acfg->ginst_hash)
4667 acfg->ginst_hash = g_hash_table_new (NULL, NULL);
4669 if (g_hash_table_lookup (acfg->ginst_hash, klass))
4670 return;
4672 if (check_type_depth (m_class_get_byval_arg (klass), 0))
4673 return;
4675 if (acfg->aot_opts.log_generics) {
4676 char *s = mono_type_full_name (m_class_get_byval_arg (klass));
4677 aot_printf (acfg, "%*sAdding generic instance %s [%s].\n", depth, "", s, ref);
4678 g_free (s);
4681 g_hash_table_insert (acfg->ginst_hash, klass, klass);
4684 * Use gsharedvt for generic collections with vtype arguments to avoid code blowup.
4685 * Enable this only for some classes since gsharedvt might not support all methods.
4687 if ((acfg->opts & MONO_OPT_GSHAREDVT) && m_class_get_image (klass) == mono_defaults.corlib && mono_class_is_ginst (klass) && mono_class_get_generic_class (klass)->context.class_inst && is_vt_inst (mono_class_get_generic_class (klass)->context.class_inst) &&
4688 (!strcmp (m_class_get_name (klass), "Dictionary`2") || !strcmp (m_class_get_name (klass), "List`1") || !strcmp (m_class_get_name (klass), "ReadOnlyCollection`1")))
4689 use_gsharedvt = TRUE;
4691 iter = NULL;
4692 while ((method = mono_class_get_methods (klass, &iter))) {
4693 if ((acfg->opts & MONO_OPT_GSHAREDVT) && method->is_inflated && mono_method_get_context (method)->method_inst) {
4695 * This is partial sharing, and we can't handle it yet
4697 continue;
4700 if (mono_method_is_generic_sharable_full (method, FALSE, FALSE, use_gsharedvt)) {
4701 /* Already added */
4702 add_types_from_method_header (acfg, method);
4703 continue;
4706 if (method->is_generic)
4707 /* FIXME: */
4708 continue;
4711 * FIXME: Instances which are referenced by these methods are not added,
4712 * for example Array.Resize<int> for List<int>.Add ().
4714 add_extra_method_with_depth (acfg, method, depth + 1);
4717 iter = NULL;
4718 while ((field = mono_class_get_fields (klass, &iter))) {
4719 if (field->type->type == MONO_TYPE_GENERICINST)
4720 add_generic_class_with_depth (acfg, mono_class_from_mono_type (field->type), depth + 1, "field");
4723 if (m_class_is_delegate (klass)) {
4724 method = mono_get_delegate_invoke (klass);
4726 method = mono_marshal_get_delegate_invoke (method, NULL);
4728 if (acfg->aot_opts.log_generics)
4729 aot_printf (acfg, "%*sAdding method %s.\n", depth, "", mono_method_get_full_name (method));
4731 add_method (acfg, method);
4734 /* Add superclasses */
4735 if (m_class_get_parent (klass))
4736 add_generic_class_with_depth (acfg, m_class_get_parent (klass), depth, "parent");
4738 const char *klass_name = m_class_get_name (klass);
4739 const char *klass_name_space = m_class_get_name_space (klass);
4740 const gboolean in_corlib = m_class_get_image (klass) == mono_defaults.corlib;
4742 * For ICollection<T>, add instances of the helper methods
4743 * in Array, since a T[] could be cast to ICollection<T>.
4745 if (in_corlib && !strcmp (klass_name_space, "System.Collections.Generic") &&
4746 (!strcmp(klass_name, "ICollection`1") || !strcmp (klass_name, "IEnumerable`1") || !strcmp (klass_name, "IList`1") || !strcmp (klass_name, "IEnumerator`1") || !strcmp (klass_name, "IReadOnlyList`1"))) {
4747 MonoClass *tclass = mono_class_from_mono_type (mono_class_get_generic_class (klass)->context.class_inst->type_argv [0]);
4748 MonoClass *array_class = mono_class_create_bounded_array (tclass, 1, FALSE);
4749 gpointer iter;
4750 char *name_prefix;
4752 if (!strcmp (klass_name, "IEnumerator`1"))
4753 name_prefix = g_strdup_printf ("%s.%s", klass_name_space, "IEnumerable`1");
4754 else
4755 name_prefix = g_strdup_printf ("%s.%s", klass_name_space, klass_name);
4757 /* Add the T[]/InternalEnumerator class */
4758 if (!strcmp (klass_name, "IEnumerable`1") || !strcmp (klass_name, "IEnumerator`1")) {
4759 ERROR_DECL (error);
4760 MonoClass *nclass;
4762 iter = NULL;
4763 while ((nclass = mono_class_get_nested_types (m_class_get_parent (array_class), &iter))) {
4764 if (!strcmp (m_class_get_name (nclass), "InternalEnumerator`1"))
4765 break;
4767 g_assert (nclass);
4768 nclass = mono_class_inflate_generic_class_checked (nclass, mono_generic_class_get_context (mono_class_get_generic_class (klass)), error);
4769 mono_error_assert_ok (error); /* FIXME don't swallow the error */
4770 add_generic_class (acfg, nclass, FALSE, "ICollection<T>");
4773 iter = NULL;
4774 while ((method = mono_class_get_methods (array_class, &iter))) {
4775 if (strstr (method->name, name_prefix)) {
4776 MonoMethod *m = mono_aot_get_array_helper_from_wrapper (method);
4778 add_extra_method_with_depth (acfg, m, depth);
4782 g_free (name_prefix);
4785 /* Add an instance of GenericComparer<T> which is created dynamically by Comparer<T> */
4786 if (in_corlib && !strcmp (klass_name_space, "System.Collections.Generic") && !strcmp (klass_name, "Comparer`1")) {
4787 ERROR_DECL (error);
4788 MonoClass *tclass = mono_class_from_mono_type (mono_class_get_generic_class (klass)->context.class_inst->type_argv [0]);
4789 MonoClass *icomparable, *gcomparer, *icomparable_inst;
4790 MonoGenericContext ctx;
4791 MonoType *args [16];
4793 memset (&ctx, 0, sizeof (ctx));
4795 icomparable = mono_class_load_from_name (mono_defaults.corlib, "System", "IComparable`1");
4797 args [0] = m_class_get_byval_arg (tclass);
4798 ctx.class_inst = mono_metadata_get_generic_inst (1, args);
4800 icomparable_inst = mono_class_inflate_generic_class_checked (icomparable, &ctx, error);
4801 mono_error_assert_ok (error); /* FIXME don't swallow the error */
4803 if (mono_class_is_assignable_from (icomparable_inst, tclass)) {
4804 MonoClass *gcomparer_inst;
4805 gcomparer = mono_class_load_from_name (mono_defaults.corlib, "System.Collections.Generic", "GenericComparer`1");
4806 gcomparer_inst = mono_class_inflate_generic_class_checked (gcomparer, &ctx, error);
4807 mono_error_assert_ok (error); /* FIXME don't swallow the error */
4809 add_generic_class (acfg, gcomparer_inst, FALSE, "Comparer<T>");
4813 /* Add an instance of GenericEqualityComparer<T> which is created dynamically by EqualityComparer<T> */
4814 if (in_corlib && !strcmp (klass_name_space, "System.Collections.Generic") && !strcmp (klass_name, "EqualityComparer`1")) {
4815 ERROR_DECL (error);
4816 MonoClass *tclass = mono_class_from_mono_type (mono_class_get_generic_class (klass)->context.class_inst->type_argv [0]);
4817 MonoClass *iface, *gcomparer, *iface_inst;
4818 MonoGenericContext ctx;
4819 MonoType *args [16];
4821 memset (&ctx, 0, sizeof (ctx));
4823 iface = mono_class_load_from_name (mono_defaults.corlib, "System", "IEquatable`1");
4824 g_assert (iface);
4825 args [0] = m_class_get_byval_arg (tclass);
4826 ctx.class_inst = mono_metadata_get_generic_inst (1, args);
4828 iface_inst = mono_class_inflate_generic_class_checked (iface, &ctx, error);
4829 mono_error_assert_ok (error); /* FIXME don't swallow the error */
4831 if (mono_class_is_assignable_from (iface_inst, tclass)) {
4832 MonoClass *gcomparer_inst;
4833 ERROR_DECL (error);
4835 gcomparer = mono_class_load_from_name (mono_defaults.corlib, "System.Collections.Generic", "GenericEqualityComparer`1");
4836 gcomparer_inst = mono_class_inflate_generic_class_checked (gcomparer, &ctx, error);
4837 mono_error_assert_ok (error); /* FIXME don't swallow the error */
4838 add_generic_class (acfg, gcomparer_inst, FALSE, "EqualityComparer<T>");
4842 /* Add an instance of EnumComparer<T> which is created dynamically by EqualityComparer<T> for enums */
4843 if (in_corlib && !strcmp (klass_name_space, "System.Collections.Generic") && !strcmp (klass_name, "EqualityComparer`1")) {
4844 MonoClass *enum_comparer;
4845 MonoClass *tclass = mono_class_from_mono_type (mono_class_get_generic_class (klass)->context.class_inst->type_argv [0]);
4846 MonoGenericContext ctx;
4847 MonoType *args [16];
4849 if (mono_class_is_enum (tclass)) {
4850 MonoClass *enum_comparer_inst;
4851 ERROR_DECL (error);
4853 memset (&ctx, 0, sizeof (ctx));
4854 args [0] = m_class_get_byval_arg (tclass);
4855 ctx.class_inst = mono_metadata_get_generic_inst (1, args);
4857 enum_comparer = mono_class_load_from_name (mono_defaults.corlib, "System.Collections.Generic", "EnumEqualityComparer`1");
4858 enum_comparer_inst = mono_class_inflate_generic_class_checked (enum_comparer, &ctx, error);
4859 mono_error_assert_ok (error); /* FIXME don't swallow the error */
4860 add_generic_class (acfg, enum_comparer_inst, FALSE, "EqualityComparer<T>");
4864 /* Add an instance of ObjectComparer<T> which is created dynamically by Comparer<T> for enums */
4865 if (in_corlib && !strcmp (klass_name_space, "System.Collections.Generic") && !strcmp (klass_name, "Comparer`1")) {
4866 MonoClass *comparer;
4867 MonoClass *tclass = mono_class_from_mono_type (mono_class_get_generic_class (klass)->context.class_inst->type_argv [0]);
4868 MonoGenericContext ctx;
4869 MonoType *args [16];
4871 if (mono_class_is_enum (tclass)) {
4872 MonoClass *comparer_inst;
4873 ERROR_DECL (error);
4875 memset (&ctx, 0, sizeof (ctx));
4876 args [0] = m_class_get_byval_arg (tclass);
4877 ctx.class_inst = mono_metadata_get_generic_inst (1, args);
4879 comparer = mono_class_load_from_name (mono_defaults.corlib, "System.Collections.Generic", "ObjectComparer`1");
4880 comparer_inst = mono_class_inflate_generic_class_checked (comparer, &ctx, error);
4881 mono_error_assert_ok (error); /* FIXME don't swallow the error */
4882 add_generic_class (acfg, comparer_inst, FALSE, "Comparer<T>");
4887 static void
4888 add_instances_of (MonoAotCompile *acfg, MonoClass *klass, MonoType **insts, int ninsts, gboolean force)
4890 int i;
4891 MonoGenericContext ctx;
4892 MonoType *args [16];
4894 if (acfg->aot_opts.no_instances)
4895 return;
4897 memset (&ctx, 0, sizeof (ctx));
4899 for (i = 0; i < ninsts; ++i) {
4900 ERROR_DECL (error);
4901 MonoClass *generic_inst;
4902 args [0] = insts [i];
4903 ctx.class_inst = mono_metadata_get_generic_inst (1, args);
4904 generic_inst = mono_class_inflate_generic_class_checked (klass, &ctx, error);
4905 mono_error_assert_ok (error); /* FIXME don't swallow the error */
4906 add_generic_class (acfg, generic_inst, force, "");
4910 static void
4911 add_types_from_method_header (MonoAotCompile *acfg, MonoMethod *method)
4913 ERROR_DECL (error);
4914 MonoMethodHeader *header;
4915 MonoMethodSignature *sig;
4916 int j, depth;
4918 depth = GPOINTER_TO_UINT (g_hash_table_lookup (acfg->method_depth, method));
4920 sig = mono_method_signature (method);
4922 if (sig) {
4923 for (j = 0; j < sig->param_count; ++j)
4924 if (sig->params [j]->type == MONO_TYPE_GENERICINST)
4925 add_generic_class_with_depth (acfg, mono_class_from_mono_type (sig->params [j]), depth + 1, "arg");
4928 header = mono_method_get_header_checked (method, error);
4930 if (header) {
4931 for (j = 0; j < header->num_locals; ++j)
4932 if (header->locals [j]->type == MONO_TYPE_GENERICINST)
4933 add_generic_class_with_depth (acfg, mono_class_from_mono_type (header->locals [j]), depth + 1, "local");
4934 mono_metadata_free_mh (header);
4935 } else {
4936 mono_error_cleanup (error); /* FIXME report the error */
4942 * add_generic_instances:
4944 * Add instances referenced by the METHODSPEC/TYPESPEC table.
4946 static void
4947 add_generic_instances (MonoAotCompile *acfg)
4949 int i;
4950 guint32 token;
4951 MonoMethod *method;
4952 MonoGenericContext *context;
4954 if (acfg->aot_opts.no_instances)
4955 return;
4957 for (i = 0; i < acfg->image->tables [MONO_TABLE_METHODSPEC].rows; ++i) {
4958 ERROR_DECL (error);
4959 token = MONO_TOKEN_METHOD_SPEC | (i + 1);
4960 method = mono_get_method_checked (acfg->image, token, NULL, NULL, error);
4962 if (!method) {
4963 aot_printerrf (acfg, "Failed to load methodspec 0x%x due to %s.\n", token, mono_error_get_message (error));
4964 aot_printerrf (acfg, "Run with MONO_LOG_LEVEL=debug for more information.\n");
4965 mono_error_cleanup (error);
4966 continue;
4969 if (m_class_get_image (method->klass) != acfg->image)
4970 continue;
4972 context = mono_method_get_context (method);
4974 if (context && ((context->class_inst && context->class_inst->is_open)))
4975 continue;
4978 * For open methods, create an instantiation which can be passed to the JIT.
4979 * FIXME: Handle class_inst as well.
4981 if (context && context->method_inst && context->method_inst->is_open) {
4982 ERROR_DECL (error);
4983 MonoGenericContext shared_context;
4984 MonoGenericInst *inst;
4985 MonoType **type_argv;
4986 int i;
4987 MonoMethod *declaring_method;
4988 gboolean supported = TRUE;
4990 /* Check that the context doesn't contain open constructed types */
4991 if (context->class_inst) {
4992 inst = context->class_inst;
4993 for (i = 0; i < inst->type_argc; ++i) {
4994 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)
4995 continue;
4996 if (mono_class_is_open_constructed_type (inst->type_argv [i]))
4997 supported = FALSE;
5000 if (context->method_inst) {
5001 inst = context->method_inst;
5002 for (i = 0; i < inst->type_argc; ++i) {
5003 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)
5004 continue;
5005 if (mono_class_is_open_constructed_type (inst->type_argv [i]))
5006 supported = FALSE;
5010 if (!supported)
5011 continue;
5013 memset (&shared_context, 0, sizeof (MonoGenericContext));
5015 inst = context->class_inst;
5016 if (inst) {
5017 type_argv = g_new0 (MonoType*, inst->type_argc);
5018 for (i = 0; i < inst->type_argc; ++i) {
5019 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)
5020 type_argv [i] = m_class_get_byval_arg (mono_defaults.object_class);
5021 else
5022 type_argv [i] = inst->type_argv [i];
5025 shared_context.class_inst = mono_metadata_get_generic_inst (inst->type_argc, type_argv);
5026 g_free (type_argv);
5029 inst = context->method_inst;
5030 if (inst) {
5031 type_argv = g_new0 (MonoType*, inst->type_argc);
5032 for (i = 0; i < inst->type_argc; ++i) {
5033 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)
5034 type_argv [i] = m_class_get_byval_arg (mono_defaults.object_class);
5035 else
5036 type_argv [i] = inst->type_argv [i];
5039 shared_context.method_inst = mono_metadata_get_generic_inst (inst->type_argc, type_argv);
5040 g_free (type_argv);
5043 if (method->is_generic || mono_class_is_gtd (method->klass))
5044 declaring_method = method;
5045 else
5046 declaring_method = mono_method_get_declaring_generic_method (method);
5048 method = mono_class_inflate_generic_method_checked (declaring_method, &shared_context, error);
5049 g_assert (mono_error_ok (error)); /* FIXME don't swallow the error */
5053 * If the method is fully sharable, it was already added in place of its
5054 * generic definition.
5056 if (mono_method_is_generic_sharable_full (method, FALSE, FALSE, FALSE))
5057 continue;
5060 * FIXME: Partially shared methods are not shared here, so we end up with
5061 * many identical methods.
5063 add_extra_method (acfg, method);
5066 for (i = 0; i < acfg->image->tables [MONO_TABLE_TYPESPEC].rows; ++i) {
5067 ERROR_DECL (error);
5068 MonoClass *klass;
5070 token = MONO_TOKEN_TYPE_SPEC | (i + 1);
5072 klass = mono_class_get_checked (acfg->image, token, error);
5073 if (!klass || m_class_get_rank (klass)) {
5074 mono_error_cleanup (error);
5075 continue;
5078 add_generic_class (acfg, klass, FALSE, "typespec");
5081 /* Add types of args/locals */
5082 for (i = 0; i < acfg->methods->len; ++i) {
5083 method = (MonoMethod *)g_ptr_array_index (acfg->methods, i);
5084 add_types_from_method_header (acfg, method);
5087 if (acfg->image == mono_defaults.corlib) {
5088 MonoClass *klass;
5089 MonoType *insts [256];
5090 int ninsts = 0;
5092 MonoType *byte_type = m_class_get_byval_arg (mono_defaults.byte_class);
5093 MonoType *sbyte_type = m_class_get_byval_arg (mono_defaults.sbyte_class);
5094 MonoType *int16_type = m_class_get_byval_arg (mono_defaults.int16_class);
5095 MonoType *uint16_type = m_class_get_byval_arg (mono_defaults.uint16_class);
5096 MonoType *int32_type = m_class_get_byval_arg (mono_defaults.int32_class);
5097 MonoType *uint32_type = m_class_get_byval_arg (mono_defaults.uint32_class);
5098 MonoType *int64_type = m_class_get_byval_arg (mono_defaults.int64_class);
5099 MonoType *uint64_type = m_class_get_byval_arg (mono_defaults.uint64_class);
5100 MonoType *object_type = m_class_get_byval_arg (mono_defaults.object_class);
5102 insts [ninsts ++] = byte_type;
5103 insts [ninsts ++] = sbyte_type;
5104 insts [ninsts ++] = int16_type;
5105 insts [ninsts ++] = uint16_type;
5106 insts [ninsts ++] = int32_type;
5107 insts [ninsts ++] = uint32_type;
5108 insts [ninsts ++] = int64_type;
5109 insts [ninsts ++] = uint64_type;
5110 insts [ninsts ++] = m_class_get_byval_arg (mono_defaults.single_class);
5111 insts [ninsts ++] = m_class_get_byval_arg (mono_defaults.double_class);
5112 insts [ninsts ++] = m_class_get_byval_arg (mono_defaults.char_class);
5113 insts [ninsts ++] = m_class_get_byval_arg (mono_defaults.boolean_class);
5115 /* Add GenericComparer<T> instances for primitive types for Enum.ToString () */
5116 klass = mono_class_try_load_from_name (acfg->image, "System.Collections.Generic", "GenericComparer`1");
5117 if (klass)
5118 add_instances_of (acfg, klass, insts, ninsts, TRUE);
5119 klass = mono_class_try_load_from_name (acfg->image, "System.Collections.Generic", "GenericEqualityComparer`1");
5120 if (klass)
5121 add_instances_of (acfg, klass, insts, ninsts, TRUE);
5123 /* Add instances of EnumEqualityComparer which are created by EqualityComparer<T> for enums */
5125 MonoClass *enum_comparer;
5126 MonoType *insts [16];
5127 int ninsts;
5129 ninsts = 0;
5130 insts [ninsts ++] = int32_type;
5131 insts [ninsts ++] = uint32_type;
5132 insts [ninsts ++] = uint16_type;
5133 insts [ninsts ++] = byte_type;
5134 enum_comparer = mono_class_load_from_name (mono_defaults.corlib, "System.Collections.Generic", "EnumEqualityComparer`1");
5135 add_instances_of (acfg, enum_comparer, insts, ninsts, FALSE);
5137 ninsts = 0;
5138 insts [ninsts ++] = int16_type;
5139 enum_comparer = mono_class_load_from_name (mono_defaults.corlib, "System.Collections.Generic", "ShortEnumEqualityComparer`1");
5140 add_instances_of (acfg, enum_comparer, insts, ninsts, FALSE);
5142 ninsts = 0;
5143 insts [ninsts ++] = sbyte_type;
5144 enum_comparer = mono_class_load_from_name (mono_defaults.corlib, "System.Collections.Generic", "SByteEnumEqualityComparer`1");
5145 add_instances_of (acfg, enum_comparer, insts, ninsts, FALSE);
5147 enum_comparer = mono_class_load_from_name (mono_defaults.corlib, "System.Collections.Generic", "LongEnumEqualityComparer`1");
5148 ninsts = 0;
5149 insts [ninsts ++] = int64_type;
5150 insts [ninsts ++] = uint64_type;
5151 add_instances_of (acfg, enum_comparer, insts, ninsts, FALSE);
5154 /* Add instances of the array generic interfaces for primitive types */
5155 /* This will add instances of the InternalArray_ helper methods in Array too */
5156 klass = mono_class_try_load_from_name (acfg->image, "System.Collections.Generic", "ICollection`1");
5157 if (klass)
5158 add_instances_of (acfg, klass, insts, ninsts, TRUE);
5160 klass = mono_class_try_load_from_name (acfg->image, "System.Collections.Generic", "IList`1");
5161 if (klass)
5162 add_instances_of (acfg, klass, insts, ninsts, TRUE);
5164 klass = mono_class_try_load_from_name (acfg->image, "System.Collections.Generic", "IEnumerable`1");
5165 if (klass)
5166 add_instances_of (acfg, klass, insts, ninsts, TRUE);
5169 * Add a managed-to-native wrapper of Array.GetGenericValueImpl<object>, which is
5170 * used for all instances of GetGenericValueImpl by the AOT runtime.
5173 MonoGenericContext ctx;
5174 MonoType *args [16];
5175 MonoMethod *get_method;
5176 MonoClass *array_klass = m_class_get_parent (mono_class_create_array (mono_defaults.object_class, 1));
5178 get_method = mono_class_get_method_from_name (array_klass, "GetGenericValueImpl", 2);
5180 if (get_method) {
5181 ERROR_DECL (error);
5182 memset (&ctx, 0, sizeof (ctx));
5183 args [0] = object_type;
5184 ctx.method_inst = mono_metadata_get_generic_inst (1, args);
5185 add_extra_method (acfg, mono_marshal_get_native_wrapper (mono_class_inflate_generic_method_checked (get_method, &ctx, error), TRUE, TRUE));
5186 g_assert (mono_error_ok (error)); /* FIXME don't swallow the error */
5190 /* Same for CompareExchange<T>/Exchange<T> */
5192 MonoGenericContext ctx;
5193 MonoType *args [16];
5194 MonoMethod *m;
5195 MonoClass *interlocked_klass = mono_class_load_from_name (mono_defaults.corlib, "System.Threading", "Interlocked");
5196 gpointer iter = NULL;
5198 while ((m = mono_class_get_methods (interlocked_klass, &iter))) {
5199 if ((!strcmp (m->name, "CompareExchange") || !strcmp (m->name, "Exchange")) && m->is_generic) {
5200 ERROR_DECL (error);
5201 memset (&ctx, 0, sizeof (ctx));
5202 args [0] = object_type;
5203 ctx.method_inst = mono_metadata_get_generic_inst (1, args);
5204 add_extra_method (acfg, mono_marshal_get_native_wrapper (mono_class_inflate_generic_method_checked (m, &ctx, error), TRUE, TRUE));
5205 g_assert (mono_error_ok (error)); /* FIXME don't swallow the error */
5210 /* Same for Volatile.Read/Write<T> */
5212 MonoGenericContext ctx;
5213 MonoType *args [16];
5214 MonoMethod *m;
5215 MonoClass *volatile_klass = mono_class_try_load_from_name (mono_defaults.corlib, "System.Threading", "Volatile");
5216 gpointer iter = NULL;
5218 if (volatile_klass) {
5219 while ((m = mono_class_get_methods (volatile_klass, &iter))) {
5220 if ((!strcmp (m->name, "Read") || !strcmp (m->name, "Write")) && m->is_generic) {
5221 ERROR_DECL (error);
5222 memset (&ctx, 0, sizeof (ctx));
5223 args [0] = object_type;
5224 ctx.method_inst = mono_metadata_get_generic_inst (1, args);
5225 add_extra_method (acfg, mono_marshal_get_native_wrapper (mono_class_inflate_generic_method_checked (m, &ctx, error), TRUE, TRUE));
5226 g_assert (mono_error_ok (error)); /* FIXME don't swallow the error */
5232 /* object[] accessor wrappers. */
5233 for (i = 1; i < 4; ++i) {
5234 MonoClass *obj_array_class = mono_class_create_array (mono_defaults.object_class, i);
5235 MonoMethod *m;
5237 m = mono_class_get_method_from_name (obj_array_class, "Get", i);
5238 g_assert (m);
5240 m = mono_marshal_get_array_accessor_wrapper (m);
5241 add_extra_method (acfg, m);
5243 m = mono_class_get_method_from_name (obj_array_class, "Address", i);
5244 g_assert (m);
5246 m = mono_marshal_get_array_accessor_wrapper (m);
5247 add_extra_method (acfg, m);
5249 m = mono_class_get_method_from_name (obj_array_class, "Set", i + 1);
5250 g_assert (m);
5252 m = mono_marshal_get_array_accessor_wrapper (m);
5253 add_extra_method (acfg, m);
5259 * is_direct_callable:
5261 * Return whenever the method identified by JI is directly callable without
5262 * going through the PLT.
5264 static gboolean
5265 is_direct_callable (MonoAotCompile *acfg, MonoMethod *method, MonoJumpInfo *patch_info)
5267 if ((patch_info->type == MONO_PATCH_INFO_METHOD) && (m_class_get_image (patch_info->data.method->klass) == acfg->image)) {
5268 MonoCompile *callee_cfg = (MonoCompile *)g_hash_table_lookup (acfg->method_to_cfg, patch_info->data.method);
5269 if (callee_cfg) {
5270 gboolean direct_callable = TRUE;
5272 if (direct_callable && (acfg->aot_opts.dedup || acfg->aot_opts.dedup_include) && mono_aot_can_dedup (patch_info->data.method))
5273 direct_callable = FALSE;
5275 if (direct_callable && !(!callee_cfg->has_got_slots && mono_class_is_before_field_init (callee_cfg->method->klass)))
5276 direct_callable = FALSE;
5277 if ((callee_cfg->method->iflags & METHOD_IMPL_ATTRIBUTE_SYNCHRONIZED) && (!method || method->wrapper_type != MONO_WRAPPER_SYNCHRONIZED))
5278 // FIXME: Maybe call the wrapper directly ?
5279 direct_callable = FALSE;
5281 if (acfg->aot_opts.soft_debug || acfg->aot_opts.no_direct_calls) {
5282 /* Disable this so all calls go through load_method (), see the
5283 * mini_get_debug_options ()->load_aot_jit_info_eagerly = TRUE; line in
5284 * mono_debugger_agent_init ().
5286 direct_callable = FALSE;
5289 if (callee_cfg->method->wrapper_type == MONO_WRAPPER_ALLOC)
5290 /* sgen does some initialization when the allocator method is created */
5291 direct_callable = FALSE;
5292 if (callee_cfg->method->wrapper_type == MONO_WRAPPER_WRITE_BARRIER)
5293 /* we don't know at compile time whether sgen is concurrent or not */
5294 direct_callable = FALSE;
5296 if (direct_callable)
5297 return TRUE;
5299 } else if ((patch_info->type == MONO_PATCH_INFO_ICALL_ADDR_CALL && patch_info->data.method->flags & METHOD_ATTRIBUTE_PINVOKE_IMPL)) {
5300 if (acfg->aot_opts.direct_pinvoke)
5301 return TRUE;
5302 } else if (patch_info->type == MONO_PATCH_INFO_ICALL_ADDR_CALL) {
5303 if (acfg->aot_opts.direct_icalls)
5304 return TRUE;
5305 return FALSE;
5308 return FALSE;
5311 #ifdef MONO_ARCH_AOT_SUPPORTED
5312 static const char *
5313 get_pinvoke_import (MonoAotCompile *acfg, MonoMethod *method)
5315 MonoImage *image = m_class_get_image (method->klass);
5316 MonoMethodPInvoke *piinfo = (MonoMethodPInvoke *) method;
5317 MonoTableInfo *tables = image->tables;
5318 MonoTableInfo *im = &tables [MONO_TABLE_IMPLMAP];
5319 MonoTableInfo *mr = &tables [MONO_TABLE_MODULEREF];
5320 guint32 im_cols [MONO_IMPLMAP_SIZE];
5321 char *import;
5323 import = (char *)g_hash_table_lookup (acfg->method_to_pinvoke_import, method);
5324 if (import != NULL)
5325 return import;
5327 if (!piinfo->implmap_idx || piinfo->implmap_idx > im->rows)
5328 return NULL;
5330 mono_metadata_decode_row (im, piinfo->implmap_idx - 1, im_cols, MONO_IMPLMAP_SIZE);
5332 if (!im_cols [MONO_IMPLMAP_SCOPE] || im_cols [MONO_IMPLMAP_SCOPE] > mr->rows)
5333 return NULL;
5335 import = g_strdup_printf ("%s", mono_metadata_string_heap (image, im_cols [MONO_IMPLMAP_NAME]));
5337 g_hash_table_insert (acfg->method_to_pinvoke_import, method, import);
5339 return import;
5341 #else
5342 static const char *
5343 get_pinvoke_import (MonoAotCompile *acfg, MonoMethod *method)
5345 return NULL;
5347 #endif
5349 static gint
5350 compare_lne (MonoDebugLineNumberEntry *a, MonoDebugLineNumberEntry *b)
5352 if (a->native_offset == b->native_offset)
5353 return a->il_offset - b->il_offset;
5354 else
5355 return a->native_offset - b->native_offset;
5359 * compute_line_numbers:
5361 * Returns a sparse array of size CODE_SIZE containing MonoDebugSourceLocation* entries for the native offsets which have a corresponding line number
5362 * entry.
5364 static MonoDebugSourceLocation**
5365 compute_line_numbers (MonoMethod *method, int code_size, MonoDebugMethodJitInfo *debug_info)
5367 MonoDebugMethodInfo *minfo;
5368 MonoDebugLineNumberEntry *ln_array;
5369 MonoDebugSourceLocation *loc;
5370 int i, prev_line, prev_il_offset;
5371 int *native_to_il_offset = NULL;
5372 MonoDebugSourceLocation **res;
5373 gboolean first;
5375 minfo = mono_debug_lookup_method (method);
5376 if (!minfo)
5377 return NULL;
5378 // FIXME: This seems to happen when two methods have the same cfg->method_to_register
5379 if (debug_info->code_size != code_size)
5380 return NULL;
5382 g_assert (code_size);
5384 /* Compute the native->IL offset mapping */
5386 ln_array = g_new0 (MonoDebugLineNumberEntry, debug_info->num_line_numbers);
5387 memcpy (ln_array, debug_info->line_numbers, debug_info->num_line_numbers * sizeof (MonoDebugLineNumberEntry));
5389 qsort (ln_array, debug_info->num_line_numbers, sizeof (MonoDebugLineNumberEntry), (int (*)(const void *, const void *))compare_lne);
5391 native_to_il_offset = g_new0 (int, code_size + 1);
5393 for (i = 0; i < debug_info->num_line_numbers; ++i) {
5394 int j;
5395 MonoDebugLineNumberEntry *lne = &ln_array [i];
5397 if (i == 0) {
5398 for (j = 0; j < lne->native_offset; ++j)
5399 native_to_il_offset [j] = -1;
5402 if (i < debug_info->num_line_numbers - 1) {
5403 MonoDebugLineNumberEntry *lne_next = &ln_array [i + 1];
5405 for (j = lne->native_offset; j < lne_next->native_offset; ++j)
5406 native_to_il_offset [j] = lne->il_offset;
5407 } else {
5408 for (j = lne->native_offset; j < code_size; ++j)
5409 native_to_il_offset [j] = lne->il_offset;
5412 g_free (ln_array);
5414 /* Compute the native->line number mapping */
5415 res = g_new0 (MonoDebugSourceLocation*, code_size);
5416 prev_il_offset = -1;
5417 prev_line = -1;
5418 first = TRUE;
5419 for (i = 0; i < code_size; ++i) {
5420 int il_offset = native_to_il_offset [i];
5422 if (il_offset == -1 || il_offset == prev_il_offset)
5423 continue;
5424 prev_il_offset = il_offset;
5425 loc = mono_debug_method_lookup_location (minfo, il_offset);
5426 if (!(loc && loc->source_file))
5427 continue;
5428 if (loc->row == prev_line) {
5429 mono_debug_free_source_location (loc);
5430 continue;
5432 prev_line = loc->row;
5433 //printf ("D: %s:%d il=%x native=%x\n", loc->source_file, loc->row, il_offset, i);
5434 if (first)
5435 /* This will cover the prolog too */
5436 res [0] = loc;
5437 else
5438 res [i] = loc;
5439 first = FALSE;
5441 return res;
5444 static int
5445 get_file_index (MonoAotCompile *acfg, const char *source_file)
5447 int findex;
5449 // FIXME: Free these
5450 if (!acfg->dwarf_ln_filenames)
5451 acfg->dwarf_ln_filenames = g_hash_table_new (g_str_hash, g_str_equal);
5452 findex = GPOINTER_TO_INT (g_hash_table_lookup (acfg->dwarf_ln_filenames, source_file));
5453 if (!findex) {
5454 findex = g_hash_table_size (acfg->dwarf_ln_filenames) + 1;
5455 g_hash_table_insert (acfg->dwarf_ln_filenames, g_strdup (source_file), GINT_TO_POINTER (findex));
5456 emit_unset_mode (acfg);
5457 fprintf (acfg->fp, ".file %d \"%s\"\n", findex, mono_dwarf_escape_path (source_file));
5459 return findex;
5462 #ifdef TARGET_ARM64
5463 #define INST_LEN 4
5464 #else
5465 #define INST_LEN 1
5466 #endif
5469 * emit_and_reloc_code:
5471 * Emit the native code in CODE, handling relocations along the way. If GOT_ONLY
5472 * is true, calls are made through the GOT too. This is used for emitting trampolines
5473 * in full-aot mode, since calls made from trampolines couldn't go through the PLT,
5474 * since trampolines are needed to make PTL work.
5476 static void
5477 emit_and_reloc_code (MonoAotCompile *acfg, MonoMethod *method, guint8 *code, guint32 code_len, MonoJumpInfo *relocs, gboolean got_only, MonoDebugMethodJitInfo *debug_info)
5479 int i, pindex, start_index;
5480 GPtrArray *patches;
5481 MonoJumpInfo *patch_info;
5482 MonoDebugSourceLocation **locs = NULL;
5483 gboolean skip, prologue_end = FALSE;
5484 #ifdef MONO_ARCH_AOT_SUPPORTED
5485 gboolean direct_call, external_call;
5486 guint32 got_slot;
5487 const char *direct_call_target = 0;
5488 const char *direct_pinvoke;
5489 #endif
5491 if (acfg->gas_line_numbers && method && debug_info) {
5492 locs = compute_line_numbers (method, code_len, debug_info);
5493 if (!locs) {
5494 int findex = get_file_index (acfg, "<unknown>");
5495 emit_unset_mode (acfg);
5496 fprintf (acfg->fp, ".loc %d %d 0\n", findex, 1);
5500 /* Collect and sort relocations */
5501 patches = g_ptr_array_new ();
5502 for (patch_info = relocs; patch_info; patch_info = patch_info->next)
5503 g_ptr_array_add (patches, patch_info);
5504 g_ptr_array_sort (patches, compare_patches);
5506 start_index = 0;
5507 for (i = 0; i < code_len; i += INST_LEN) {
5508 patch_info = NULL;
5509 for (pindex = start_index; pindex < patches->len; ++pindex) {
5510 patch_info = (MonoJumpInfo *)g_ptr_array_index (patches, pindex);
5511 if (patch_info->ip.i >= i)
5512 break;
5515 if (locs && locs [i]) {
5516 MonoDebugSourceLocation *loc = locs [i];
5517 int findex;
5518 const char *options;
5520 findex = get_file_index (acfg, loc->source_file);
5521 emit_unset_mode (acfg);
5522 if (!prologue_end)
5523 options = " prologue_end";
5524 else
5525 options = "";
5526 prologue_end = TRUE;
5527 fprintf (acfg->fp, ".loc %d %d 0%s\n", findex, loc->row, options);
5528 mono_debug_free_source_location (loc);
5531 skip = FALSE;
5532 #ifdef MONO_ARCH_AOT_SUPPORTED
5533 if (patch_info && (patch_info->ip.i == i) && (pindex < patches->len)) {
5534 start_index = pindex;
5536 switch (patch_info->type) {
5537 case MONO_PATCH_INFO_NONE:
5538 break;
5539 case MONO_PATCH_INFO_GOT_OFFSET: {
5540 int code_size;
5542 arch_emit_got_offset (acfg, code + i, &code_size);
5543 i += code_size - INST_LEN;
5544 skip = TRUE;
5545 patch_info->type = MONO_PATCH_INFO_NONE;
5546 break;
5548 case MONO_PATCH_INFO_OBJC_SELECTOR_REF: {
5549 int code_size, index;
5550 char *selector = (char *)patch_info->data.target;
5552 if (!acfg->objc_selector_to_index)
5553 acfg->objc_selector_to_index = g_hash_table_new (g_str_hash, g_str_equal);
5554 if (!acfg->objc_selectors)
5555 acfg->objc_selectors = g_ptr_array_new ();
5556 index = GPOINTER_TO_UINT (g_hash_table_lookup (acfg->objc_selector_to_index, selector));
5557 if (index)
5558 index --;
5559 else {
5560 index = acfg->objc_selector_index;
5561 g_ptr_array_add (acfg->objc_selectors, (void*)patch_info->data.target);
5562 g_hash_table_insert (acfg->objc_selector_to_index, selector, GUINT_TO_POINTER (index + 1));
5563 acfg->objc_selector_index ++;
5566 arch_emit_objc_selector_ref (acfg, code + i, index, &code_size);
5567 i += code_size - INST_LEN;
5568 skip = TRUE;
5569 patch_info->type = MONO_PATCH_INFO_NONE;
5570 break;
5572 default: {
5574 * If this patch is a call, try emitting a direct call instead of
5575 * through a PLT entry. This is possible if the called method is in
5576 * the same assembly and requires no initialization.
5578 direct_call = FALSE;
5579 external_call = FALSE;
5580 if ((patch_info->type == MONO_PATCH_INFO_METHOD) && (m_class_get_image (patch_info->data.method->klass) == acfg->image)) {
5581 if (!got_only && is_direct_callable (acfg, method, patch_info)) {
5582 MonoCompile *callee_cfg = (MonoCompile *)g_hash_table_lookup (acfg->method_to_cfg, patch_info->data.method);
5584 // Don't compile inflated methods if we're doing dedup
5585 if (acfg->aot_opts.dedup && !mono_aot_can_dedup (patch_info->data.method)) {
5586 char *name = mono_aot_get_mangled_method_name (patch_info->data.method);
5587 mono_trace (G_LOG_LEVEL_DEBUG, MONO_TRACE_AOT, "DIRECT CALL: %s by %s", name, method ? mono_method_full_name (method, TRUE) : "");
5588 g_free (name);
5590 direct_call = TRUE;
5591 direct_call_target = callee_cfg->asm_symbol;
5592 patch_info->type = MONO_PATCH_INFO_NONE;
5593 acfg->stats.direct_calls ++;
5597 acfg->stats.all_calls ++;
5598 } else if (patch_info->type == MONO_PATCH_INFO_ICALL_ADDR_CALL) {
5599 if (!got_only && is_direct_callable (acfg, method, patch_info)) {
5600 if (!(patch_info->data.method->flags & METHOD_ATTRIBUTE_PINVOKE_IMPL))
5601 direct_pinvoke = mono_lookup_icall_symbol (patch_info->data.method);
5602 else
5603 direct_pinvoke = get_pinvoke_import (acfg, patch_info->data.method);
5604 if (direct_pinvoke) {
5605 direct_call = TRUE;
5606 g_assert (strlen (direct_pinvoke) < 1000);
5607 direct_call_target = g_strdup_printf ("%s%s", acfg->user_symbol_prefix, direct_pinvoke);
5610 } else if (patch_info->type == MONO_PATCH_INFO_JIT_ICALL_ADDR) {
5611 const char *sym = mono_lookup_jit_icall_symbol (patch_info->data.name);
5612 if (!got_only && sym && acfg->aot_opts.direct_icalls) {
5613 /* Call to a C function implementing a jit icall */
5614 direct_call = TRUE;
5615 external_call = TRUE;
5616 g_assert (strlen (sym) < 1000);
5617 direct_call_target = g_strdup_printf ("%s%s", acfg->user_symbol_prefix, sym);
5619 } else if (patch_info->type == MONO_PATCH_INFO_INTERNAL_METHOD) {
5620 MonoJitICallInfo *info = mono_find_jit_icall_by_name (patch_info->data.name);
5621 const char *sym = mono_lookup_jit_icall_symbol (patch_info->data.name);
5622 if (!got_only && sym && acfg->aot_opts.direct_icalls && info->func == info->wrapper) {
5623 /* Call to a jit icall without a wrapper */
5624 direct_call = TRUE;
5625 external_call = TRUE;
5626 g_assert (strlen (sym) < 1000);
5627 direct_call_target = g_strdup_printf ("%s%s", acfg->user_symbol_prefix, sym);
5631 if (direct_call) {
5632 patch_info->type = MONO_PATCH_INFO_NONE;
5633 acfg->stats.direct_calls ++;
5636 if (!got_only && !direct_call) {
5637 MonoPltEntry *plt_entry = get_plt_entry (acfg, patch_info);
5638 if (plt_entry) {
5639 /* This patch has a PLT entry, so we must emit a call to the PLT entry */
5640 direct_call = TRUE;
5641 direct_call_target = plt_entry->symbol;
5643 /* Nullify the patch */
5644 patch_info->type = MONO_PATCH_INFO_NONE;
5645 plt_entry->jit_used = TRUE;
5649 if (direct_call) {
5650 int call_size;
5652 arch_emit_direct_call (acfg, direct_call_target, external_call, FALSE, patch_info, &call_size);
5653 i += call_size - INST_LEN;
5654 } else {
5655 int code_size;
5657 got_slot = get_got_offset (acfg, FALSE, patch_info);
5659 arch_emit_got_access (acfg, acfg->got_symbol, code + i, got_slot, &code_size);
5660 i += code_size - INST_LEN;
5662 skip = TRUE;
5666 #endif /* MONO_ARCH_AOT_SUPPORTED */
5668 if (!skip) {
5669 /* Find next patch */
5670 patch_info = NULL;
5671 for (pindex = start_index; pindex < patches->len; ++pindex) {
5672 patch_info = (MonoJumpInfo *)g_ptr_array_index (patches, pindex);
5673 if (patch_info->ip.i >= i)
5674 break;
5677 /* Try to emit multiple bytes at once */
5678 if (pindex < patches->len && patch_info->ip.i > i) {
5679 int limit;
5681 for (limit = i + INST_LEN; limit < patch_info->ip.i; limit += INST_LEN) {
5682 if (locs && locs [limit])
5683 break;
5686 emit_code_bytes (acfg, code + i, limit - i);
5687 i = limit - INST_LEN;
5688 } else {
5689 emit_code_bytes (acfg, code + i, INST_LEN);
5694 g_ptr_array_free (patches, TRUE);
5695 g_free (locs);
5699 * sanitize_symbol:
5701 * Return a modified version of S which only includes characters permissible in symbols.
5703 static char*
5704 sanitize_symbol (MonoAotCompile *acfg, char *s)
5706 gboolean process = FALSE;
5707 int i, len;
5708 GString *gs;
5709 char *res;
5711 if (!s)
5712 return s;
5714 len = strlen (s);
5715 for (i = 0; i < len; ++i)
5716 if (!(s [i] <= 0x7f && (isalnum (s [i]) || s [i] == '_')))
5717 process = TRUE;
5718 if (!process)
5719 return s;
5721 gs = g_string_sized_new (len);
5722 for (i = 0; i < len; ++i) {
5723 guint8 c = s [i];
5724 if (c <= 0x7f && (isalnum (c) || c == '_')) {
5725 g_string_append_c (gs, c);
5726 } else if (c > 0x7f) {
5727 /* multi-byte utf8 */
5728 g_string_append_printf (gs, "_0x%x", c);
5729 i ++;
5730 c = s [i];
5731 while (c >> 6 == 0x2) {
5732 g_string_append_printf (gs, "%x", c);
5733 i ++;
5734 c = s [i];
5736 g_string_append_printf (gs, "_");
5737 i --;
5738 } else {
5739 g_string_append_c (gs, '_');
5743 res = mono_mempool_strdup (acfg->mempool, gs->str);
5744 g_string_free (gs, TRUE);
5745 return res;
5748 static char*
5749 get_debug_sym (MonoMethod *method, const char *prefix, GHashTable *cache)
5751 char *name1, *name2, *cached;
5752 int i, j, len, count;
5753 MonoMethod *cached_method;
5755 name1 = mono_method_full_name (method, TRUE);
5757 #ifdef TARGET_MACH
5758 // This is so that we don't accidentally create a local symbol (which starts with 'L')
5759 if ((!prefix || !*prefix) && name1 [0] == 'L')
5760 prefix = "_";
5761 #endif
5763 #if defined(TARGET_WIN32) && defined(TARGET_X86)
5764 char adjustedPrefix [MAX_SYMBOL_SIZE];
5765 prefix = mangle_symbol (prefix, adjustedPrefix, G_N_ELEMENTS (adjustedPrefix));
5766 #endif
5768 len = strlen (name1);
5769 name2 = (char *)malloc (strlen (prefix) + len + 16);
5770 memcpy (name2, prefix, strlen (prefix));
5771 j = strlen (prefix);
5772 for (i = 0; i < len; ++i) {
5773 if (i == 0 && name1 [0] >= '0' && name1 [0] <= '9') {
5774 name2 [j ++] = '_';
5775 } else if (isalnum (name1 [i])) {
5776 name2 [j ++] = name1 [i];
5777 } else if (name1 [i] == ' ' && name1 [i + 1] == '(' && name1 [i + 2] == ')') {
5778 i += 2;
5779 } else if (name1 [i] == ',' && name1 [i + 1] == ' ') {
5780 name2 [j ++] = '_';
5781 i++;
5782 } else if (name1 [i] == '(' || name1 [i] == ')' || name1 [i] == '>') {
5783 } else
5784 name2 [j ++] = '_';
5786 name2 [j] = '\0';
5788 g_free (name1);
5790 count = 0;
5791 while (TRUE) {
5792 cached_method = (MonoMethod *)g_hash_table_lookup (cache, name2);
5793 if (!(cached_method && cached_method != method))
5794 break;
5795 sprintf (name2 + j, "_%d", count);
5796 count ++;
5799 cached = g_strdup (name2);
5800 g_hash_table_insert (cache, cached, method);
5802 return name2;
5805 static void
5806 emit_method_code (MonoAotCompile *acfg, MonoCompile *cfg)
5808 MonoMethod *method;
5809 int method_index;
5810 guint8 *code;
5811 char *debug_sym = NULL;
5812 char *symbol = NULL;
5813 int func_alignment = AOT_FUNC_ALIGNMENT;
5814 char *export_name;
5816 g_assert (!ignore_cfg (cfg));
5818 method = cfg->orig_method;
5819 code = cfg->native_code;
5821 method_index = get_method_index (acfg, method);
5822 symbol = g_strdup_printf ("%sme_%x", acfg->temp_prefix, method_index);
5824 /* Make the labels local */
5825 emit_section_change (acfg, ".text", 0);
5826 emit_alignment_code (acfg, func_alignment);
5828 if (acfg->global_symbols && acfg->need_no_dead_strip)
5829 fprintf (acfg->fp, " .no_dead_strip %s\n", cfg->asm_symbol);
5831 emit_label (acfg, cfg->asm_symbol);
5833 if (acfg->aot_opts.write_symbols && !acfg->global_symbols && !acfg->llvm) {
5835 * Write a C style symbol for every method, this has two uses:
5836 * - it works on platforms where the dwarf debugging info is not
5837 * yet supported.
5838 * - it allows the setting of breakpoints of aot-ed methods.
5841 // Comment out to force dedup to link these symbols and forbid compiling
5842 // in duplicated code. This is an "assert when linking if broken" trick.
5843 /*if (mono_aot_can_dedup (method) && (acfg->aot_opts.dedup || acfg->aot_opts.dedup_include))*/
5844 /*debug_sym = mono_aot_get_mangled_method_name (method);*/
5845 /*else*/
5846 debug_sym = get_debug_sym (method, "", acfg->method_label_hash);
5848 cfg->asm_debug_symbol = g_strdup (debug_sym);
5850 if (acfg->need_no_dead_strip)
5851 fprintf (acfg->fp, " .no_dead_strip %s\n", debug_sym);
5853 // Comment out to force dedup to link these symbols and forbid compiling
5854 // in duplicated code. This is an "assert when linking if broken" trick.
5855 /*if (mono_aot_can_dedup (method) && (acfg->aot_opts.dedup || acfg->aot_opts.dedup_include))*/
5856 /*emit_global_inner (acfg, debug_sym, TRUE);*/
5857 /*else*/
5858 emit_local_symbol (acfg, debug_sym, symbol, TRUE);
5860 emit_label (acfg, debug_sym);
5863 export_name = (char *)g_hash_table_lookup (acfg->export_names, method);
5864 if (export_name) {
5865 /* Emit a global symbol for the method */
5866 emit_global_inner (acfg, export_name, TRUE);
5867 emit_label (acfg, export_name);
5870 if (cfg->verbose_level > 0 && !ignore_cfg (cfg))
5871 g_print ("Method %s emitted as %s\n", mono_method_get_full_name (method), cfg->asm_symbol);
5873 acfg->stats.code_size += cfg->code_len;
5875 acfg->cfgs [method_index]->got_offset = acfg->got_offset;
5877 emit_and_reloc_code (acfg, method, code, cfg->code_len, cfg->patch_info, FALSE, mono_debug_find_method (cfg->jit_info->d.method, mono_domain_get ()));
5879 emit_line (acfg);
5881 if (acfg->aot_opts.write_symbols) {
5882 if (debug_sym)
5883 emit_symbol_size (acfg, debug_sym, ".");
5884 else
5885 emit_symbol_size (acfg, cfg->asm_symbol, ".");
5886 g_free (debug_sym);
5889 emit_label (acfg, symbol);
5891 arch_emit_unwind_info_sections (acfg, cfg->asm_symbol, symbol, cfg->unwind_ops);
5893 g_free (symbol);
5897 * encode_patch:
5899 * Encode PATCH_INFO into its disk representation.
5901 static void
5902 encode_patch (MonoAotCompile *acfg, MonoJumpInfo *patch_info, guint8 *buf, guint8 **endbuf)
5904 guint8 *p = buf;
5906 switch (patch_info->type) {
5907 case MONO_PATCH_INFO_NONE:
5908 break;
5909 case MONO_PATCH_INFO_IMAGE:
5910 encode_value (get_image_index (acfg, patch_info->data.image), p, &p);
5911 break;
5912 case MONO_PATCH_INFO_MSCORLIB_GOT_ADDR:
5913 case MONO_PATCH_INFO_GC_CARD_TABLE_ADDR:
5914 case MONO_PATCH_INFO_GC_NURSERY_START:
5915 case MONO_PATCH_INFO_GC_NURSERY_BITS:
5916 break;
5917 case MONO_PATCH_INFO_CASTCLASS_CACHE:
5918 encode_value (patch_info->data.index, p, &p);
5919 break;
5920 case MONO_PATCH_INFO_METHOD_REL:
5921 encode_value ((gint)patch_info->data.offset, p, &p);
5922 break;
5923 case MONO_PATCH_INFO_SWITCH: {
5924 gpointer *table = (gpointer *)patch_info->data.table->table;
5925 int k;
5927 encode_value (patch_info->data.table->table_size, p, &p);
5928 for (k = 0; k < patch_info->data.table->table_size; k++)
5929 encode_value ((int)(gssize)table [k], p, &p);
5930 break;
5932 case MONO_PATCH_INFO_METHODCONST:
5933 case MONO_PATCH_INFO_METHOD:
5934 case MONO_PATCH_INFO_METHOD_JUMP:
5935 case MONO_PATCH_INFO_ICALL_ADDR:
5936 case MONO_PATCH_INFO_ICALL_ADDR_CALL:
5937 case MONO_PATCH_INFO_METHOD_RGCTX:
5938 case MONO_PATCH_INFO_METHOD_CODE_SLOT:
5939 encode_method_ref (acfg, patch_info->data.method, p, &p);
5940 break;
5941 case MONO_PATCH_INFO_AOT_JIT_INFO:
5942 case MONO_PATCH_INFO_GET_TLS_TRAMP:
5943 case MONO_PATCH_INFO_SET_TLS_TRAMP:
5944 encode_value (patch_info->data.index, p, &p);
5945 break;
5946 case MONO_PATCH_INFO_INTERNAL_METHOD:
5947 case MONO_PATCH_INFO_JIT_ICALL_ADDR:
5948 case MONO_PATCH_INFO_JIT_ICALL_ADDR_NOCALL: {
5949 guint32 len = strlen (patch_info->data.name);
5951 encode_value (len, p, &p);
5953 memcpy (p, patch_info->data.name, len);
5954 p += len;
5955 *p++ = '\0';
5956 break;
5958 case MONO_PATCH_INFO_LDSTR: {
5959 guint32 image_index = get_image_index (acfg, patch_info->data.token->image);
5960 guint32 token = patch_info->data.token->token;
5961 g_assert (mono_metadata_token_code (token) == MONO_TOKEN_STRING);
5962 encode_value (image_index, p, &p);
5963 encode_value (patch_info->data.token->token - MONO_TOKEN_STRING, p, &p);
5964 break;
5966 case MONO_PATCH_INFO_RVA:
5967 case MONO_PATCH_INFO_DECLSEC:
5968 case MONO_PATCH_INFO_LDTOKEN:
5969 case MONO_PATCH_INFO_TYPE_FROM_HANDLE:
5970 encode_value (get_image_index (acfg, patch_info->data.token->image), p, &p);
5971 encode_value (patch_info->data.token->token, p, &p);
5972 encode_value (patch_info->data.token->has_context, p, &p);
5973 if (patch_info->data.token->has_context)
5974 encode_generic_context (acfg, &patch_info->data.token->context, p, &p);
5975 break;
5976 case MONO_PATCH_INFO_EXC_NAME: {
5977 MonoClass *ex_class;
5979 ex_class =
5980 mono_class_load_from_name (m_class_get_image (mono_defaults.exception_class),
5981 "System", (const char *)patch_info->data.target);
5982 encode_klass_ref (acfg, ex_class, p, &p);
5983 break;
5985 case MONO_PATCH_INFO_R4:
5986 encode_value (*((guint32 *)patch_info->data.target), p, &p);
5987 break;
5988 case MONO_PATCH_INFO_R8:
5989 encode_value (((guint32 *)patch_info->data.target) [MINI_LS_WORD_IDX], p, &p);
5990 encode_value (((guint32 *)patch_info->data.target) [MINI_MS_WORD_IDX], p, &p);
5991 break;
5992 case MONO_PATCH_INFO_VTABLE:
5993 case MONO_PATCH_INFO_CLASS:
5994 case MONO_PATCH_INFO_IID:
5995 case MONO_PATCH_INFO_ADJUSTED_IID:
5996 encode_klass_ref (acfg, patch_info->data.klass, p, &p);
5997 break;
5998 case MONO_PATCH_INFO_DELEGATE_TRAMPOLINE:
5999 encode_klass_ref (acfg, patch_info->data.del_tramp->klass, p, &p);
6000 if (patch_info->data.del_tramp->method) {
6001 encode_value (1, p, &p);
6002 encode_method_ref (acfg, patch_info->data.del_tramp->method, p, &p);
6003 } else {
6004 encode_value (0, p, &p);
6006 encode_value (patch_info->data.del_tramp->is_virtual, p, &p);
6007 break;
6008 case MONO_PATCH_INFO_FIELD:
6009 case MONO_PATCH_INFO_SFLDA:
6010 encode_field_info (acfg, patch_info->data.field, p, &p);
6011 break;
6012 case MONO_PATCH_INFO_INTERRUPTION_REQUEST_FLAG:
6013 break;
6014 case MONO_PATCH_INFO_PROFILER_ALLOCATION_COUNT:
6015 case MONO_PATCH_INFO_PROFILER_CLAUSE_COUNT:
6016 break;
6017 case MONO_PATCH_INFO_RGCTX_FETCH:
6018 case MONO_PATCH_INFO_RGCTX_SLOT_INDEX: {
6019 MonoJumpInfoRgctxEntry *entry = patch_info->data.rgctx_entry;
6020 guint32 offset;
6021 guint8 *buf2, *p2;
6024 * entry->method has a lenghtly encoding and multiple rgctx_fetch entries
6025 * reference the same method, so encode the method only once.
6027 offset = GPOINTER_TO_UINT (g_hash_table_lookup (acfg->method_blob_hash, entry->method));
6028 if (!offset) {
6029 buf2 = (guint8 *)g_malloc (1024);
6030 p2 = buf2;
6032 encode_method_ref (acfg, entry->method, p2, &p2);
6033 g_assert (p2 - buf2 < 1024);
6035 offset = add_to_blob (acfg, buf2, p2 - buf2);
6036 g_free (buf2);
6038 g_hash_table_insert (acfg->method_blob_hash, entry->method, GUINT_TO_POINTER (offset + 1));
6039 } else {
6040 offset --;
6043 encode_value (offset, p, &p);
6044 g_assert ((int)entry->info_type < 256);
6045 g_assert (entry->data->type < 256);
6046 encode_value ((entry->in_mrgctx ? 1 : 0) | (entry->info_type << 1) | (entry->data->type << 9), p, &p);
6047 encode_patch (acfg, entry->data, p, &p);
6048 break;
6050 case MONO_PATCH_INFO_SEQ_POINT_INFO:
6051 case MONO_PATCH_INFO_AOT_MODULE:
6052 break;
6053 case MONO_PATCH_INFO_SIGNATURE:
6054 case MONO_PATCH_INFO_GSHAREDVT_IN_WRAPPER:
6055 encode_signature (acfg, (MonoMethodSignature*)patch_info->data.target, p, &p);
6056 break;
6057 case MONO_PATCH_INFO_GSHAREDVT_CALL:
6058 encode_signature (acfg, (MonoMethodSignature*)patch_info->data.gsharedvt->sig, p, &p);
6059 encode_method_ref (acfg, patch_info->data.gsharedvt->method, p, &p);
6060 break;
6061 case MONO_PATCH_INFO_GSHAREDVT_METHOD: {
6062 MonoGSharedVtMethodInfo *info = patch_info->data.gsharedvt_method;
6063 int i;
6065 encode_method_ref (acfg, info->method, p, &p);
6066 encode_value (info->num_entries, p, &p);
6067 for (i = 0; i < info->num_entries; ++i) {
6068 MonoRuntimeGenericContextInfoTemplate *template_ = &info->entries [i];
6070 encode_value (template_->info_type, p, &p);
6071 switch (mini_rgctx_info_type_to_patch_info_type (template_->info_type)) {
6072 case MONO_PATCH_INFO_CLASS:
6073 encode_klass_ref (acfg, mono_class_from_mono_type ((MonoType *)template_->data), p, &p);
6074 break;
6075 case MONO_PATCH_INFO_FIELD:
6076 encode_field_info (acfg, (MonoClassField *)template_->data, p, &p);
6077 break;
6078 default:
6079 g_assert_not_reached ();
6080 break;
6083 break;
6085 case MONO_PATCH_INFO_LDSTR_LIT: {
6086 const char *s = (const char *)patch_info->data.target;
6087 int len = strlen (s);
6089 encode_value (len, p, &p);
6090 memcpy (p, s, len + 1);
6091 p += len + 1;
6092 break;
6094 case MONO_PATCH_INFO_VIRT_METHOD:
6095 encode_klass_ref (acfg, patch_info->data.virt_method->klass, p, &p);
6096 encode_method_ref (acfg, patch_info->data.virt_method->method, p, &p);
6097 break;
6098 case MONO_PATCH_INFO_GC_SAFE_POINT_FLAG:
6099 case MONO_PATCH_INFO_JIT_THREAD_ATTACH:
6100 break;
6101 default:
6102 g_warning ("unable to handle jump info %d", patch_info->type);
6103 g_assert_not_reached ();
6106 *endbuf = p;
6109 static void
6110 encode_patch_list (MonoAotCompile *acfg, GPtrArray *patches, int n_patches, gboolean llvm, int first_got_offset, guint8 *buf, guint8 **endbuf)
6112 guint8 *p = buf;
6113 guint32 pindex, offset;
6114 MonoJumpInfo *patch_info;
6116 encode_value (n_patches, p, &p);
6118 for (pindex = 0; pindex < patches->len; ++pindex) {
6119 patch_info = (MonoJumpInfo *)g_ptr_array_index (patches, pindex);
6121 if (patch_info->type == MONO_PATCH_INFO_NONE || patch_info->type == MONO_PATCH_INFO_BB)
6122 /* Nothing to do */
6123 continue;
6125 offset = get_got_offset (acfg, llvm, patch_info);
6126 encode_value (offset, p, &p);
6129 *endbuf = p;
6132 static void
6133 emit_method_info (MonoAotCompile *acfg, MonoCompile *cfg)
6135 MonoMethod *method;
6136 int pindex, buf_size, n_patches;
6137 GPtrArray *patches;
6138 MonoJumpInfo *patch_info;
6139 guint32 method_index;
6140 guint8 *p, *buf;
6141 guint32 first_got_offset;
6143 method = cfg->orig_method;
6145 method_index = get_method_index (acfg, method);
6147 /* Sort relocations */
6148 patches = g_ptr_array_new ();
6149 for (patch_info = cfg->patch_info; patch_info; patch_info = patch_info->next)
6150 g_ptr_array_add (patches, patch_info);
6151 g_ptr_array_sort (patches, compare_patches);
6153 first_got_offset = acfg->cfgs [method_index]->got_offset;
6155 /**********************/
6156 /* Encode method info */
6157 /**********************/
6159 buf_size = (patches->len < 1000) ? 40960 : 40960 + (patches->len * 64);
6160 p = buf = (guint8 *)g_malloc (buf_size);
6162 if (mono_class_get_cctor (method->klass)) {
6163 encode_value (1, p, &p);
6164 encode_klass_ref (acfg, method->klass, p, &p);
6165 } else {
6166 /* Not needed when loading the method */
6167 encode_value (0, p, &p);
6170 g_assert (!(cfg->opt & MONO_OPT_SHARED));
6172 n_patches = 0;
6173 for (pindex = 0; pindex < patches->len; ++pindex) {
6174 patch_info = (MonoJumpInfo *)g_ptr_array_index (patches, pindex);
6176 if ((patch_info->type == MONO_PATCH_INFO_GOT_OFFSET) ||
6177 (patch_info->type == MONO_PATCH_INFO_NONE)) {
6178 patch_info->type = MONO_PATCH_INFO_NONE;
6179 /* Nothing to do */
6180 continue;
6183 if ((patch_info->type == MONO_PATCH_INFO_IMAGE) && (patch_info->data.image == acfg->image)) {
6184 /* Stored in a GOT slot initialized at module load time */
6185 patch_info->type = MONO_PATCH_INFO_NONE;
6186 continue;
6189 if (patch_info->type == MONO_PATCH_INFO_GC_CARD_TABLE_ADDR ||
6190 patch_info->type == MONO_PATCH_INFO_GC_NURSERY_START ||
6191 patch_info->type == MONO_PATCH_INFO_GC_NURSERY_BITS ||
6192 patch_info->type == MONO_PATCH_INFO_AOT_MODULE) {
6193 /* Stored in a GOT slot initialized at module load time */
6194 patch_info->type = MONO_PATCH_INFO_NONE;
6195 continue;
6198 if (is_plt_patch (patch_info) && !(cfg->compile_llvm && acfg->aot_opts.llvm_only)) {
6199 /* Calls are made through the PLT */
6200 patch_info->type = MONO_PATCH_INFO_NONE;
6201 continue;
6204 n_patches ++;
6207 if (n_patches)
6208 g_assert (cfg->has_got_slots);
6210 encode_patch_list (acfg, patches, n_patches, cfg->compile_llvm, first_got_offset, p, &p);
6212 g_ptr_array_free (patches, TRUE);
6214 acfg->stats.info_size += p - buf;
6216 g_assert (p - buf < buf_size);
6218 cfg->method_info_offset = add_to_blob (acfg, buf, p - buf);
6219 g_free (buf);
6222 static guint32
6223 get_unwind_info_offset (MonoAotCompile *acfg, guint8 *encoded, guint32 encoded_len)
6225 guint32 cache_index;
6226 guint32 offset;
6228 /* Reuse the unwind module to canonize and store unwind info entries */
6229 cache_index = mono_cache_unwind_info (encoded, encoded_len);
6231 /* Use +/- 1 to distinguish 0s from missing entries */
6232 offset = GPOINTER_TO_UINT (g_hash_table_lookup (acfg->unwind_info_offsets, GUINT_TO_POINTER (cache_index + 1)));
6233 if (offset)
6234 return offset - 1;
6235 else {
6236 guint8 buf [16];
6237 guint8 *p;
6240 * It would be easier to use assembler symbols, but the caller needs an
6241 * offset now.
6243 offset = acfg->unwind_info_offset;
6244 g_hash_table_insert (acfg->unwind_info_offsets, GUINT_TO_POINTER (cache_index + 1), GUINT_TO_POINTER (offset + 1));
6245 g_ptr_array_add (acfg->unwind_ops, GUINT_TO_POINTER (cache_index));
6247 p = buf;
6248 encode_value (encoded_len, p, &p);
6250 acfg->unwind_info_offset += encoded_len + (p - buf);
6251 return offset;
6255 static void
6256 emit_exception_debug_info (MonoAotCompile *acfg, MonoCompile *cfg, gboolean store_seq_points)
6258 int i, k, buf_size;
6259 guint32 debug_info_size, seq_points_size;
6260 guint8 *code;
6261 MonoMethodHeader *header;
6262 guint8 *p, *buf, *debug_info;
6263 MonoJitInfo *jinfo = cfg->jit_info;
6264 guint32 flags;
6265 gboolean use_unwind_ops = FALSE;
6266 MonoSeqPointInfo *seq_points;
6268 code = cfg->native_code;
6269 header = cfg->header;
6271 if (!acfg->aot_opts.nodebug) {
6272 mono_debug_serialize_debug_info (cfg, &debug_info, &debug_info_size);
6273 } else {
6274 debug_info = NULL;
6275 debug_info_size = 0;
6278 seq_points = cfg->seq_point_info;
6279 seq_points_size = (store_seq_points)? mono_seq_point_info_get_write_size (seq_points) : 0;
6281 buf_size = header->num_clauses * 256 + debug_info_size + 2048 + seq_points_size + cfg->gc_map_size;
6282 if (jinfo->has_try_block_holes) {
6283 MonoTryBlockHoleTableJitInfo *table = mono_jit_info_get_try_block_hole_table_info (jinfo);
6284 buf_size += table->num_holes * 16;
6287 p = buf = (guint8 *)g_malloc (buf_size);
6289 use_unwind_ops = cfg->unwind_ops != NULL;
6291 flags = (jinfo->has_generic_jit_info ? 1 : 0) | (use_unwind_ops ? 2 : 0) | (header->num_clauses ? 4 : 0) | (seq_points_size ? 8 : 0) | (cfg->compile_llvm ? 16 : 0) | (jinfo->has_try_block_holes ? 32 : 0) | (cfg->gc_map ? 64 : 0) | (jinfo->has_arch_eh_info ? 128 : 0);
6293 encode_value (flags, p, &p);
6295 if (use_unwind_ops) {
6296 guint32 encoded_len;
6297 guint8 *encoded;
6298 guint32 unwind_desc;
6300 encoded = mono_unwind_ops_encode (cfg->unwind_ops, &encoded_len);
6302 unwind_desc = get_unwind_info_offset (acfg, encoded, encoded_len);
6303 encode_value (unwind_desc, p, &p);
6305 g_free (encoded);
6306 } else {
6307 encode_value (jinfo->unwind_info, p, &p);
6310 /*Encode the number of holes before the number of clauses to make decoding easier*/
6311 if (jinfo->has_try_block_holes) {
6312 MonoTryBlockHoleTableJitInfo *table = mono_jit_info_get_try_block_hole_table_info (jinfo);
6313 encode_value (table->num_holes, p, &p);
6316 if (jinfo->has_arch_eh_info) {
6318 * In AOT mode, the code length is calculated from the address of the previous method,
6319 * which could include alignment padding, so calculating the start of the epilog as
6320 * code_len - epilog_size is correct any more. Save the real code len as a workaround.
6322 encode_value (jinfo->code_size, p, &p);
6325 /* Exception table */
6326 if (cfg->compile_llvm) {
6328 * When using LLVM, we can't emit some data, like pc offsets, this reg/offset etc.,
6329 * since the information is only available to llc. Instead, we let llc save the data
6330 * into the LSDA, and read it from there at runtime.
6332 /* The assembly might be CIL stripped so emit the data ourselves */
6333 if (header->num_clauses)
6334 encode_value (header->num_clauses, p, &p);
6336 for (k = 0; k < header->num_clauses; ++k) {
6337 MonoExceptionClause *clause;
6339 clause = &header->clauses [k];
6341 encode_value (clause->flags, p, &p);
6342 if (!(clause->flags == MONO_EXCEPTION_CLAUSE_FILTER || clause->flags == MONO_EXCEPTION_CLAUSE_FINALLY)) {
6343 if (clause->data.catch_class) {
6344 guint8 *buf2, *p2;
6345 int len;
6347 buf2 = (guint8 *)g_malloc (4096);
6348 p2 = buf2;
6349 encode_klass_ref (acfg, clause->data.catch_class, p2, &p2);
6350 len = p2 - buf2;
6351 g_assert (len < 4096);
6352 encode_value (len, p, &p);
6353 memcpy (p, buf2, len);
6354 p += p2 - buf2;
6355 g_free (buf2);
6356 } else {
6357 encode_value (0, p, &p);
6361 /* Emit the IL ranges too, since they might not be available at runtime */
6362 encode_value (clause->try_offset, p, &p);
6363 encode_value (clause->try_len, p, &p);
6364 encode_value (clause->handler_offset, p, &p);
6365 encode_value (clause->handler_len, p, &p);
6367 /* Emit a list of nesting clauses */
6368 for (i = 0; i < header->num_clauses; ++i) {
6369 gint32 cindex1 = k;
6370 MonoExceptionClause *clause1 = &header->clauses [cindex1];
6371 gint32 cindex2 = i;
6372 MonoExceptionClause *clause2 = &header->clauses [cindex2];
6374 if (cindex1 != cindex2 && clause1->try_offset >= clause2->try_offset && clause1->handler_offset <= clause2->handler_offset)
6375 encode_value (i, p, &p);
6377 encode_value (-1, p, &p);
6379 } else {
6380 if (jinfo->num_clauses)
6381 encode_value (jinfo->num_clauses, p, &p);
6383 for (k = 0; k < jinfo->num_clauses; ++k) {
6384 MonoJitExceptionInfo *ei = &jinfo->clauses [k];
6386 encode_value (ei->flags, p, &p);
6387 #ifdef MONO_CONTEXT_SET_LLVM_EXC_REG
6388 /* Not used for catch clauses */
6389 if (ei->flags != MONO_EXCEPTION_CLAUSE_NONE)
6390 encode_value (ei->exvar_offset, p, &p);
6391 #else
6392 encode_value (ei->exvar_offset, p, &p);
6393 #endif
6395 if (ei->flags == MONO_EXCEPTION_CLAUSE_FILTER || ei->flags == MONO_EXCEPTION_CLAUSE_FINALLY)
6396 encode_value ((gint)((guint8*)ei->data.filter - code), p, &p);
6397 else {
6398 if (ei->data.catch_class) {
6399 guint8 *buf2, *p2;
6400 int len;
6402 buf2 = (guint8 *)g_malloc (4096);
6403 p2 = buf2;
6404 encode_klass_ref (acfg, ei->data.catch_class, p2, &p2);
6405 len = p2 - buf2;
6406 g_assert (len < 4096);
6407 encode_value (len, p, &p);
6408 memcpy (p, buf2, len);
6409 p += p2 - buf2;
6410 g_free (buf2);
6411 } else {
6412 encode_value (0, p, &p);
6416 encode_value ((gint)((guint8*)ei->try_start - code), p, &p);
6417 encode_value ((gint)((guint8*)ei->try_end - code), p, &p);
6418 encode_value ((gint)((guint8*)ei->handler_start - code), p, &p);
6422 if (jinfo->has_try_block_holes) {
6423 MonoTryBlockHoleTableJitInfo *table = mono_jit_info_get_try_block_hole_table_info (jinfo);
6424 for (i = 0; i < table->num_holes; ++i) {
6425 MonoTryBlockHoleJitInfo *hole = &table->holes [i];
6426 encode_value (hole->clause, p, &p);
6427 encode_value (hole->length, p, &p);
6428 encode_value (hole->offset, p, &p);
6432 if (jinfo->has_arch_eh_info) {
6433 MonoArchEHJitInfo *eh_info;
6435 eh_info = mono_jit_info_get_arch_eh_info (jinfo);
6436 encode_value (eh_info->stack_size, p, &p);
6437 encode_value (eh_info->epilog_size, p, &p);
6440 if (jinfo->has_generic_jit_info) {
6441 MonoGenericJitInfo *gi = mono_jit_info_get_generic_jit_info (jinfo);
6442 MonoGenericSharingContext* gsctx = gi->generic_sharing_context;
6443 guint8 *buf2, *p2;
6444 int len;
6446 encode_value (gi->nlocs, p, &p);
6447 if (gi->nlocs) {
6448 for (i = 0; i < gi->nlocs; ++i) {
6449 MonoDwarfLocListEntry *entry = &gi->locations [i];
6451 encode_value (entry->is_reg ? 1 : 0, p, &p);
6452 encode_value (entry->reg, p, &p);
6453 if (!entry->is_reg)
6454 encode_value (entry->offset, p, &p);
6455 if (i == 0)
6456 g_assert (entry->from == 0);
6457 else
6458 encode_value (entry->from, p, &p);
6459 encode_value (entry->to, p, &p);
6461 } else {
6462 if (!cfg->compile_llvm) {
6463 encode_value (gi->has_this ? 1 : 0, p, &p);
6464 encode_value (gi->this_reg, p, &p);
6465 encode_value (gi->this_offset, p, &p);
6470 * Need to encode jinfo->method too, since it is not equal to 'method'
6471 * when using generic sharing.
6473 buf2 = (guint8 *)g_malloc (4096);
6474 p2 = buf2;
6475 encode_method_ref (acfg, jinfo->d.method, p2, &p2);
6476 len = p2 - buf2;
6477 g_assert (len < 4096);
6478 encode_value (len, p, &p);
6479 memcpy (p, buf2, len);
6480 p += p2 - buf2;
6481 g_free (buf2);
6483 if (gsctx && gsctx->is_gsharedvt) {
6484 encode_value (1, p, &p);
6485 } else {
6486 encode_value (0, p, &p);
6490 if (seq_points_size)
6491 p += mono_seq_point_info_write (seq_points, p);
6493 g_assert (debug_info_size < buf_size);
6495 encode_value (debug_info_size, p, &p);
6496 if (debug_info_size) {
6497 memcpy (p, debug_info, debug_info_size);
6498 p += debug_info_size;
6499 g_free (debug_info);
6502 /* GC Map */
6503 if (cfg->gc_map) {
6504 encode_value (cfg->gc_map_size, p, &p);
6505 /* The GC map requires 4 bytes of alignment */
6506 while ((gsize)p % 4)
6507 p ++;
6508 memcpy (p, cfg->gc_map, cfg->gc_map_size);
6509 p += cfg->gc_map_size;
6512 acfg->stats.ex_info_size += p - buf;
6514 g_assert (p - buf < buf_size);
6516 /* Emit info */
6517 /* The GC Map requires 4 byte alignment */
6518 cfg->ex_info_offset = add_to_blob_aligned (acfg, buf, p - buf, cfg->gc_map ? 4 : 1);
6519 g_free (buf);
6522 static guint32
6523 emit_klass_info (MonoAotCompile *acfg, guint32 token)
6525 ERROR_DECL (error);
6526 MonoClass *klass = mono_class_get_checked (acfg->image, token, error);
6527 guint8 *p, *buf;
6528 int i, buf_size, res;
6529 gboolean no_special_static, cant_encode;
6530 gpointer iter = NULL;
6532 if (!klass) {
6533 mono_error_cleanup (error);
6535 buf_size = 16;
6537 p = buf = (guint8 *)g_malloc (buf_size);
6539 /* Mark as unusable */
6540 encode_value (-1, p, &p);
6542 res = add_to_blob (acfg, buf, p - buf);
6543 g_free (buf);
6545 return res;
6548 buf_size = 10240 + (m_class_get_vtable_size (klass) * 16);
6549 p = buf = (guint8 *)g_malloc (buf_size);
6551 g_assert (klass);
6553 mono_class_init (klass);
6555 mono_class_get_nested_types (klass, &iter);
6556 g_assert (m_class_is_nested_classes_inited (klass));
6558 mono_class_setup_vtable (klass);
6561 * Emit all the information which is required for creating vtables so
6562 * the runtime does not need to create the MonoMethod structures which
6563 * take up a lot of space.
6566 no_special_static = !mono_class_has_special_static_fields (klass);
6568 /* Check whenever we have enough info to encode the vtable */
6569 cant_encode = FALSE;
6570 MonoMethod **klass_vtable = m_class_get_vtable (klass);
6571 for (i = 0; i < m_class_get_vtable_size (klass); ++i) {
6572 MonoMethod *cm = klass_vtable [i];
6574 if (cm && mono_method_signature (cm)->is_inflated && !g_hash_table_lookup (acfg->token_info_hash, cm))
6575 cant_encode = TRUE;
6578 mono_class_has_finalizer (klass);
6579 if (mono_class_has_failure (klass))
6580 cant_encode = TRUE;
6582 if (mono_class_is_gtd (klass) || cant_encode) {
6583 encode_value (-1, p, &p);
6584 } else {
6585 gboolean has_nested = mono_class_get_nested_classes_property (klass) != NULL;
6586 encode_value (m_class_get_vtable_size (klass), p, &p);
6587 encode_value ((m_class_has_weak_fields (klass) << 9) | (mono_class_is_gtd (klass) ? (1 << 8) : 0) | (no_special_static << 7) | (m_class_has_static_refs (klass) << 6) | (m_class_has_references (klass) << 5) | ((m_class_is_blittable (klass) << 4) | (has_nested ? 1 : 0) << 3) | (m_class_has_cctor (klass) << 2) | (m_class_has_finalize (klass) << 1) | m_class_is_ghcimpl (klass), p, &p);
6588 if (m_class_has_cctor (klass))
6589 encode_method_ref (acfg, mono_class_get_cctor (klass), p, &p);
6590 if (m_class_has_finalize (klass))
6591 encode_method_ref (acfg, mono_class_get_finalizer (klass), p, &p);
6593 encode_value (m_class_get_instance_size (klass), p, &p);
6594 encode_value (mono_class_data_size (klass), p, &p);
6595 encode_value (m_class_get_packing_size (klass), p, &p);
6596 encode_value (m_class_get_min_align (klass), p, &p);
6598 for (i = 0; i < m_class_get_vtable_size (klass); ++i) {
6599 MonoMethod *cm = klass_vtable [i];
6601 if (cm)
6602 encode_method_ref (acfg, cm, p, &p);
6603 else
6604 encode_value (0, p, &p);
6608 acfg->stats.class_info_size += p - buf;
6610 g_assert (p - buf < buf_size);
6611 res = add_to_blob (acfg, buf, p - buf);
6612 g_free (buf);
6614 return res;
6617 static char*
6618 get_plt_entry_debug_sym (MonoAotCompile *acfg, MonoJumpInfo *ji, GHashTable *cache)
6620 char *debug_sym = NULL;
6621 char *prefix;
6623 if (acfg->llvm && llvm_acfg->aot_opts.static_link) {
6624 /* Need to add a prefix to create unique symbols */
6625 prefix = g_strdup_printf ("plt_%s_", acfg->assembly_name_sym);
6626 } else {
6627 #if defined(TARGET_WIN32) && defined(TARGET_X86)
6628 prefix = mangle_symbol_alloc ("plt_");
6629 #else
6630 prefix = g_strdup ("plt_");
6631 #endif
6634 switch (ji->type) {
6635 case MONO_PATCH_INFO_METHOD:
6636 debug_sym = get_debug_sym (ji->data.method, prefix, cache);
6637 break;
6638 case MONO_PATCH_INFO_INTERNAL_METHOD:
6639 debug_sym = g_strdup_printf ("%s_jit_icall_%s", prefix, ji->data.name);
6640 break;
6641 case MONO_PATCH_INFO_RGCTX_FETCH:
6642 debug_sym = g_strdup_printf ("%s_rgctx_fetch_%d", prefix, acfg->label_generator ++);
6643 break;
6644 case MONO_PATCH_INFO_ICALL_ADDR:
6645 case MONO_PATCH_INFO_ICALL_ADDR_CALL: {
6646 char *s = get_debug_sym (ji->data.method, "", cache);
6648 debug_sym = g_strdup_printf ("%s_icall_native_%s", prefix, s);
6649 g_free (s);
6650 break;
6652 case MONO_PATCH_INFO_JIT_ICALL_ADDR:
6653 debug_sym = g_strdup_printf ("%s_jit_icall_native_%s", prefix, ji->data.name);
6654 break;
6655 default:
6656 break;
6659 g_free (prefix);
6661 return sanitize_symbol (acfg, debug_sym);
6665 * Calls made from AOTed code are routed through a table of jumps similar to the
6666 * ELF PLT (Program Linkage Table). Initially the PLT entries jump to code which transfers
6667 * control to the AOT runtime through a trampoline.
6669 static void
6670 emit_plt (MonoAotCompile *acfg)
6672 int i;
6674 if (acfg->aot_opts.llvm_only) {
6675 g_assert (acfg->plt_offset == 1);
6676 return;
6679 emit_line (acfg);
6681 emit_section_change (acfg, ".text", 0);
6682 emit_alignment_code (acfg, 16);
6683 emit_info_symbol (acfg, "plt");
6684 emit_label (acfg, acfg->plt_symbol);
6686 for (i = 0; i < acfg->plt_offset; ++i) {
6687 char *debug_sym = NULL;
6688 MonoPltEntry *plt_entry = NULL;
6690 if (i == 0)
6692 * The first plt entry is unused.
6694 continue;
6696 plt_entry = (MonoPltEntry *)g_hash_table_lookup (acfg->plt_offset_to_entry, GUINT_TO_POINTER (i));
6698 debug_sym = plt_entry->debug_sym;
6700 if (acfg->thumb_mixed && !plt_entry->jit_used)
6701 /* Emit only a thumb version */
6702 continue;
6704 /* Skip plt entries not actually called */
6705 if (!plt_entry->jit_used && !plt_entry->llvm_used)
6706 continue;
6708 if (acfg->llvm && !acfg->thumb_mixed) {
6709 emit_label (acfg, plt_entry->llvm_symbol);
6710 if (acfg->llvm) {
6711 emit_global_inner (acfg, plt_entry->llvm_symbol, TRUE);
6712 #if defined(TARGET_MACH)
6713 fprintf (acfg->fp, ".private_extern %s\n", plt_entry->llvm_symbol);
6714 #endif
6718 if (debug_sym) {
6719 if (acfg->need_no_dead_strip) {
6720 emit_unset_mode (acfg);
6721 fprintf (acfg->fp, " .no_dead_strip %s\n", debug_sym);
6723 emit_local_symbol (acfg, debug_sym, NULL, TRUE);
6724 emit_label (acfg, debug_sym);
6727 emit_label (acfg, plt_entry->symbol);
6729 arch_emit_plt_entry (acfg, acfg->got_symbol, (acfg->plt_got_offset_base + i) * sizeof (gpointer), acfg->plt_got_info_offsets [i]);
6731 if (debug_sym)
6732 emit_symbol_size (acfg, debug_sym, ".");
6735 if (acfg->thumb_mixed) {
6736 /* Make sure the ARM symbols don't alias the thumb ones */
6737 emit_zero_bytes (acfg, 16);
6740 * Emit a separate set of PLT entries using thumb2 which is called by LLVM generated
6741 * code.
6743 for (i = 0; i < acfg->plt_offset; ++i) {
6744 char *debug_sym = NULL;
6745 MonoPltEntry *plt_entry = NULL;
6747 if (i == 0)
6748 continue;
6750 plt_entry = (MonoPltEntry *)g_hash_table_lookup (acfg->plt_offset_to_entry, GUINT_TO_POINTER (i));
6752 /* Skip plt entries not actually called by LLVM code */
6753 if (!plt_entry->llvm_used)
6754 continue;
6756 if (acfg->aot_opts.write_symbols) {
6757 if (plt_entry->debug_sym)
6758 debug_sym = g_strdup_printf ("%s_thumb", plt_entry->debug_sym);
6761 if (debug_sym) {
6762 #if defined(TARGET_MACH)
6763 fprintf (acfg->fp, " .thumb_func %s\n", debug_sym);
6764 fprintf (acfg->fp, " .no_dead_strip %s\n", debug_sym);
6765 #endif
6766 emit_local_symbol (acfg, debug_sym, NULL, TRUE);
6767 emit_label (acfg, debug_sym);
6769 fprintf (acfg->fp, "\n.thumb_func\n");
6771 emit_label (acfg, plt_entry->llvm_symbol);
6773 if (acfg->llvm)
6774 emit_global_inner (acfg, plt_entry->llvm_symbol, TRUE);
6776 arch_emit_llvm_plt_entry (acfg, acfg->got_symbol, (acfg->plt_got_offset_base + i) * sizeof (gpointer), acfg->plt_got_info_offsets [i]);
6778 if (debug_sym) {
6779 emit_symbol_size (acfg, debug_sym, ".");
6780 g_free (debug_sym);
6785 emit_symbol_size (acfg, acfg->plt_symbol, ".");
6787 emit_info_symbol (acfg, "plt_end");
6789 arch_emit_unwind_info_sections (acfg, "plt", "plt_end", NULL);
6793 * emit_trampoline_full:
6795 * If EMIT_TINFO is TRUE, emit additional information which can be used to create a MonoJitInfo for this trampoline by
6796 * create_jit_info_for_trampoline ().
6798 static G_GNUC_UNUSED void
6799 emit_trampoline_full (MonoAotCompile *acfg, int got_offset, MonoTrampInfo *info, gboolean emit_tinfo)
6801 char start_symbol [MAX_SYMBOL_SIZE];
6802 char end_symbol [MAX_SYMBOL_SIZE];
6803 char symbol [MAX_SYMBOL_SIZE];
6804 guint32 buf_size, info_offset;
6805 MonoJumpInfo *patch_info;
6806 guint8 *buf, *p;
6807 GPtrArray *patches;
6808 char *name;
6809 guint8 *code;
6810 guint32 code_size;
6811 MonoJumpInfo *ji;
6812 GSList *unwind_ops;
6814 g_assert (info);
6816 name = info->name;
6817 code = info->code;
6818 code_size = info->code_size;
6819 ji = info->ji;
6820 unwind_ops = info->unwind_ops;
6822 /* Emit code */
6824 sprintf (start_symbol, "%s%s", acfg->user_symbol_prefix, name);
6826 emit_section_change (acfg, ".text", 0);
6827 emit_global (acfg, start_symbol, TRUE);
6828 emit_alignment_code (acfg, AOT_FUNC_ALIGNMENT);
6829 emit_label (acfg, start_symbol);
6831 sprintf (symbol, "%snamed_%s", acfg->temp_prefix, name);
6832 emit_label (acfg, symbol);
6835 * The code should access everything through the GOT, so we pass
6836 * TRUE here.
6838 emit_and_reloc_code (acfg, NULL, code, code_size, ji, TRUE, NULL);
6840 emit_symbol_size (acfg, start_symbol, ".");
6842 if (emit_tinfo) {
6843 sprintf (end_symbol, "%snamede_%s", acfg->temp_prefix, name);
6844 emit_label (acfg, end_symbol);
6847 /* Emit info */
6849 /* Sort relocations */
6850 patches = g_ptr_array_new ();
6851 for (patch_info = ji; patch_info; patch_info = patch_info->next)
6852 if (patch_info->type != MONO_PATCH_INFO_NONE)
6853 g_ptr_array_add (patches, patch_info);
6854 g_ptr_array_sort (patches, compare_patches);
6856 buf_size = patches->len * 128 + 128;
6857 buf = (guint8 *)g_malloc (buf_size);
6858 p = buf;
6860 encode_patch_list (acfg, patches, patches->len, FALSE, got_offset, p, &p);
6861 g_assert (p - buf < buf_size);
6862 g_ptr_array_free (patches, TRUE);
6864 sprintf (symbol, "%s%s_p", acfg->user_symbol_prefix, name);
6866 info_offset = add_to_blob (acfg, buf, p - buf);
6868 emit_section_change (acfg, RODATA_SECT, 0);
6869 emit_global (acfg, symbol, FALSE);
6870 emit_label (acfg, symbol);
6872 emit_int32 (acfg, info_offset);
6874 if (emit_tinfo) {
6875 guint8 *encoded;
6876 guint32 encoded_len;
6877 guint32 uw_offset;
6880 * Emit additional information which can be used to reconstruct a partial MonoTrampInfo.
6882 encoded = mono_unwind_ops_encode (info->unwind_ops, &encoded_len);
6883 uw_offset = get_unwind_info_offset (acfg, encoded, encoded_len);
6884 g_free (encoded);
6886 emit_symbol_diff (acfg, end_symbol, start_symbol, 0);
6887 emit_int32 (acfg, uw_offset);
6890 /* Emit debug info */
6891 if (unwind_ops) {
6892 char symbol2 [MAX_SYMBOL_SIZE];
6894 sprintf (symbol, "%s", name);
6895 sprintf (symbol2, "%snamed_%s", acfg->temp_prefix, name);
6897 arch_emit_unwind_info_sections (acfg, start_symbol, end_symbol, unwind_ops);
6899 if (acfg->dwarf)
6900 mono_dwarf_writer_emit_trampoline (acfg->dwarf, symbol, symbol2, NULL, NULL, code_size, unwind_ops);
6903 g_free (buf);
6906 static G_GNUC_UNUSED void
6907 emit_trampoline (MonoAotCompile *acfg, int got_offset, MonoTrampInfo *info)
6909 emit_trampoline_full (acfg, got_offset, info, TRUE);
6912 static void
6913 emit_trampolines (MonoAotCompile *acfg)
6915 char symbol [MAX_SYMBOL_SIZE];
6916 char end_symbol [MAX_SYMBOL_SIZE];
6917 int i, tramp_got_offset;
6918 int ntype;
6919 #ifdef MONO_ARCH_HAVE_FULL_AOT_TRAMPOLINES
6920 int tramp_type;
6921 #endif
6923 if ((!mono_aot_mode_is_full (&acfg->aot_opts) || acfg->aot_opts.llvm_only) && !acfg->aot_opts.interp)
6924 return;
6926 g_assert (acfg->image->assembly);
6928 /* Currently, we emit most trampolines into the mscorlib AOT image. */
6929 if (strcmp (acfg->image->assembly->aname.name, "mscorlib") == 0) {
6930 #ifdef MONO_ARCH_HAVE_FULL_AOT_TRAMPOLINES
6931 MonoTrampInfo *info;
6934 * Emit the generic trampolines.
6936 * We could save some code by treating the generic trampolines as a wrapper
6937 * method, but that approach has its own complexities, so we choose the simpler
6938 * method.
6940 for (tramp_type = 0; tramp_type < MONO_TRAMPOLINE_NUM; ++tramp_type) {
6941 /* we overload the boolean here to indicate the slightly different trampoline needed, see mono_arch_create_generic_trampoline() */
6942 #ifdef DISABLE_REMOTING
6943 if (tramp_type == MONO_TRAMPOLINE_GENERIC_VIRTUAL_REMOTING)
6944 continue;
6945 #endif
6946 mono_arch_create_generic_trampoline ((MonoTrampolineType)tramp_type, &info, acfg->aot_opts.use_trampolines_page? 2: TRUE);
6947 emit_trampoline (acfg, acfg->got_offset, info);
6948 mono_tramp_info_free (info);
6951 /* Emit the exception related code pieces */
6952 mono_arch_get_restore_context (&info, TRUE);
6953 emit_trampoline (acfg, acfg->got_offset, info);
6954 mono_tramp_info_free (info);
6956 mono_arch_get_call_filter (&info, TRUE);
6957 emit_trampoline (acfg, acfg->got_offset, info);
6958 mono_tramp_info_free (info);
6960 mono_arch_get_throw_exception (&info, TRUE);
6961 emit_trampoline (acfg, acfg->got_offset, info);
6962 mono_tramp_info_free (info);
6964 mono_arch_get_rethrow_exception (&info, TRUE);
6965 emit_trampoline (acfg, acfg->got_offset, info);
6966 mono_tramp_info_free (info);
6968 mono_arch_get_throw_corlib_exception (&info, TRUE);
6969 emit_trampoline (acfg, acfg->got_offset, info);
6970 mono_tramp_info_free (info);
6972 #ifdef MONO_ARCH_HAVE_SDB_TRAMPOLINES
6973 mono_arch_create_sdb_trampoline (TRUE, &info, TRUE);
6974 emit_trampoline (acfg, acfg->got_offset, info);
6975 mono_tramp_info_free (info);
6977 mono_arch_create_sdb_trampoline (FALSE, &info, TRUE);
6978 emit_trampoline (acfg, acfg->got_offset, info);
6979 mono_tramp_info_free (info);
6980 #endif
6982 #ifdef MONO_ARCH_GSHAREDVT_SUPPORTED
6983 mono_arch_get_gsharedvt_trampoline (&info, TRUE);
6984 if (info) {
6985 emit_trampoline_full (acfg, acfg->got_offset, info, TRUE);
6987 /* Create a separate out trampoline for more information in stack traces */
6988 info->name = g_strdup ("gsharedvt_out_trampoline");
6989 emit_trampoline_full (acfg, acfg->got_offset, info, TRUE);
6990 mono_tramp_info_free (info);
6992 #endif
6994 #if defined(MONO_ARCH_HAVE_GET_TRAMPOLINES)
6996 GSList *l = mono_arch_get_trampolines (TRUE);
6998 while (l) {
6999 MonoTrampInfo *info = (MonoTrampInfo *)l->data;
7001 emit_trampoline (acfg, acfg->got_offset, info);
7002 l = l->next;
7005 #endif
7007 for (i = 0; i < acfg->aot_opts.nrgctx_fetch_trampolines; ++i) {
7008 int offset;
7010 offset = MONO_RGCTX_SLOT_MAKE_RGCTX (i);
7011 mono_arch_create_rgctx_lazy_fetch_trampoline (offset, &info, TRUE);
7012 emit_trampoline (acfg, acfg->got_offset, info);
7013 mono_tramp_info_free (info);
7015 offset = MONO_RGCTX_SLOT_MAKE_MRGCTX (i);
7016 mono_arch_create_rgctx_lazy_fetch_trampoline (offset, &info, TRUE);
7017 emit_trampoline (acfg, acfg->got_offset, info);
7018 mono_tramp_info_free (info);
7021 #ifdef MONO_ARCH_HAVE_GENERAL_RGCTX_LAZY_FETCH_TRAMPOLINE
7022 mono_arch_create_general_rgctx_lazy_fetch_trampoline (&info, TRUE);
7023 emit_trampoline (acfg, acfg->got_offset, info);
7024 mono_tramp_info_free (info);
7025 #endif
7028 GSList *l;
7030 /* delegate_invoke_impl trampolines */
7031 l = mono_arch_get_delegate_invoke_impls ();
7032 while (l) {
7033 MonoTrampInfo *info = (MonoTrampInfo *)l->data;
7035 emit_trampoline (acfg, acfg->got_offset, info);
7036 l = l->next;
7040 if (mono_aot_mode_is_interp (&acfg->aot_opts)) {
7041 mono_arch_get_interp_to_native_trampoline (&info);
7042 emit_trampoline (acfg, acfg->got_offset, info);
7045 #endif /* #ifdef MONO_ARCH_HAVE_FULL_AOT_TRAMPOLINES */
7047 /* Emit trampolines which are numerous */
7050 * These include the following:
7051 * - specific trampolines
7052 * - static rgctx invoke trampolines
7053 * - imt trampolines
7054 * These trampolines have the same code, they are parameterized by GOT
7055 * slots.
7056 * They are defined in this file, in the arch_... routines instead of
7057 * in tramp-<ARCH>.c, since it is easier to do it this way.
7061 * When running in aot-only mode, we can't create specific trampolines at
7062 * runtime, so we create a few, and save them in the AOT file.
7063 * Normal trampolines embed their argument as a literal inside the
7064 * trampoline code, we can't do that here, so instead we embed an offset
7065 * which needs to be added to the trampoline address to get the address of
7066 * the GOT slot which contains the argument value.
7067 * The generated trampolines jump to the generic trampolines using another
7068 * GOT slot, which will be setup by the AOT loader to point to the
7069 * generic trampoline code of the given type.
7073 * FIXME: Maybe we should use more specific trampolines (i.e. one class init for
7074 * each class).
7077 emit_section_change (acfg, ".text", 0);
7079 tramp_got_offset = acfg->got_offset;
7081 for (ntype = 0; ntype < MONO_AOT_TRAMP_NUM; ++ntype) {
7082 switch (ntype) {
7083 case MONO_AOT_TRAMP_SPECIFIC:
7084 sprintf (symbol, "specific_trampolines");
7085 break;
7086 case MONO_AOT_TRAMP_STATIC_RGCTX:
7087 sprintf (symbol, "static_rgctx_trampolines");
7088 break;
7089 case MONO_AOT_TRAMP_IMT:
7090 sprintf (symbol, "imt_trampolines");
7091 break;
7092 case MONO_AOT_TRAMP_GSHAREDVT_ARG:
7093 sprintf (symbol, "gsharedvt_arg_trampolines");
7094 break;
7095 default:
7096 g_assert_not_reached ();
7099 sprintf (end_symbol, "%s_e", symbol);
7101 if (acfg->aot_opts.write_symbols)
7102 emit_local_symbol (acfg, symbol, end_symbol, TRUE);
7104 emit_alignment_code (acfg, AOT_FUNC_ALIGNMENT);
7105 emit_info_symbol (acfg, symbol);
7107 acfg->trampoline_got_offset_base [ntype] = tramp_got_offset;
7109 for (i = 0; i < acfg->num_trampolines [ntype]; ++i) {
7110 int tramp_size = 0;
7112 switch (ntype) {
7113 case MONO_AOT_TRAMP_SPECIFIC:
7114 arch_emit_specific_trampoline (acfg, tramp_got_offset, &tramp_size);
7115 tramp_got_offset += 2;
7116 break;
7117 case MONO_AOT_TRAMP_STATIC_RGCTX:
7118 arch_emit_static_rgctx_trampoline (acfg, tramp_got_offset, &tramp_size);
7119 tramp_got_offset += 2;
7120 break;
7121 case MONO_AOT_TRAMP_IMT:
7122 arch_emit_imt_trampoline (acfg, tramp_got_offset, &tramp_size);
7123 tramp_got_offset += 1;
7124 break;
7125 case MONO_AOT_TRAMP_GSHAREDVT_ARG:
7126 arch_emit_gsharedvt_arg_trampoline (acfg, tramp_got_offset, &tramp_size);
7127 tramp_got_offset += 2;
7128 break;
7129 default:
7130 g_assert_not_reached ();
7132 if (!acfg->trampoline_size [ntype]) {
7133 g_assert (tramp_size);
7134 acfg->trampoline_size [ntype] = tramp_size;
7138 emit_label (acfg, end_symbol);
7139 emit_int32 (acfg, 0);
7142 arch_emit_specific_trampoline_pages (acfg);
7144 /* Reserve some entries at the end of the GOT for our use */
7145 acfg->num_trampoline_got_entries = tramp_got_offset - acfg->got_offset;
7148 acfg->got_offset += acfg->num_trampoline_got_entries;
7151 static gboolean
7152 str_begins_with (const char *str1, const char *str2)
7154 int len = strlen (str2);
7155 return strncmp (str1, str2, len) == 0;
7158 void*
7159 mono_aot_readonly_field_override (MonoClassField *field)
7161 ReadOnlyValue *rdv;
7162 for (rdv = readonly_values; rdv; rdv = rdv->next) {
7163 char *p = rdv->name;
7164 int len;
7165 len = strlen (m_class_get_name_space (field->parent));
7166 if (strncmp (p, m_class_get_name_space (field->parent), len))
7167 continue;
7168 p += len;
7169 if (*p++ != '.')
7170 continue;
7171 len = strlen (m_class_get_name (field->parent));
7172 if (strncmp (p, m_class_get_name (field->parent), len))
7173 continue;
7174 p += len;
7175 if (*p++ != '.')
7176 continue;
7177 if (strcmp (p, field->name))
7178 continue;
7179 switch (rdv->type) {
7180 case MONO_TYPE_I1:
7181 return &rdv->value.i1;
7182 case MONO_TYPE_I2:
7183 return &rdv->value.i2;
7184 case MONO_TYPE_I4:
7185 return &rdv->value.i4;
7186 default:
7187 break;
7190 return NULL;
7193 static void
7194 add_readonly_value (MonoAotOptions *opts, const char *val)
7196 ReadOnlyValue *rdv;
7197 const char *fval;
7198 const char *tval;
7199 /* the format of val is:
7200 * namespace.typename.fieldname=type/value
7201 * type can be i1 for uint8/int8/boolean, i2 for uint16/int16/char, i4 for uint32/int32
7203 fval = strrchr (val, '/');
7204 if (!fval) {
7205 fprintf (stderr, "AOT : invalid format for readonly field '%s', missing /.\n", val);
7206 exit (1);
7208 tval = strrchr (val, '=');
7209 if (!tval) {
7210 fprintf (stderr, "AOT : invalid format for readonly field '%s', missing =.\n", val);
7211 exit (1);
7213 rdv = g_new0 (ReadOnlyValue, 1);
7214 rdv->name = (char *)g_malloc0 (tval - val + 1);
7215 memcpy (rdv->name, val, tval - val);
7216 tval++;
7217 fval++;
7218 if (strncmp (tval, "i1", 2) == 0) {
7219 rdv->value.i1 = atoi (fval);
7220 rdv->type = MONO_TYPE_I1;
7221 } else if (strncmp (tval, "i2", 2) == 0) {
7222 rdv->value.i2 = atoi (fval);
7223 rdv->type = MONO_TYPE_I2;
7224 } else if (strncmp (tval, "i4", 2) == 0) {
7225 rdv->value.i4 = atoi (fval);
7226 rdv->type = MONO_TYPE_I4;
7227 } else {
7228 fprintf (stderr, "AOT : unsupported type for readonly field '%s'.\n", tval);
7229 exit (1);
7231 rdv->next = readonly_values;
7232 readonly_values = rdv;
7235 static gchar *
7236 clean_path (gchar * path)
7238 if (!path)
7239 return NULL;
7241 if (g_str_has_suffix (path, G_DIR_SEPARATOR_S))
7242 return path;
7244 gchar *clean = g_strconcat (path, G_DIR_SEPARATOR_S, NULL);
7245 g_free (path);
7247 return clean;
7250 static gchar *
7251 wrap_path (gchar * path)
7253 int len;
7254 if (!path)
7255 return NULL;
7257 // If the string contains no spaces, just return the original string.
7258 if (strstr (path, " ") == NULL)
7259 return path;
7261 // If the string is already wrapped in quotes, return it.
7262 len = strlen (path);
7263 if (len >= 2 && path[0] == '\"' && path[len-1] == '\"')
7264 return path;
7266 // If the string contains spaces, then wrap it in quotes.
7267 gchar *clean = g_strdup_printf ("\"%s\"", path);
7269 return clean;
7272 // Duplicate a char range and add it to a ptrarray, but only if it is nonempty
7273 static void
7274 ptr_array_add_range_if_nonempty(GPtrArray *args, gchar const *start, gchar const *end)
7276 ptrdiff_t len = end-start;
7277 if (len > 0)
7278 g_ptr_array_add (args, g_strndup (start, len));
7281 static GPtrArray *
7282 mono_aot_split_options (const char *aot_options)
7284 enum MonoAotOptionState {
7285 MONO_AOT_OPTION_STATE_DEFAULT,
7286 MONO_AOT_OPTION_STATE_STRING,
7287 MONO_AOT_OPTION_STATE_ESCAPE,
7290 GPtrArray *args = g_ptr_array_new ();
7291 enum MonoAotOptionState state = MONO_AOT_OPTION_STATE_DEFAULT;
7292 gchar const *opt_start = aot_options;
7293 gboolean end_of_string = FALSE;
7294 gchar cur;
7296 g_return_val_if_fail (aot_options != NULL, NULL);
7298 while ((cur = *aot_options) != '\0') {
7299 if (state == MONO_AOT_OPTION_STATE_ESCAPE)
7300 goto next;
7302 switch (cur) {
7303 case '"':
7304 // If we find a quote, then if we're in the default case then
7305 // it means we've found the start of a string, if not then it
7306 // means we've found the end of the string and should switch
7307 // back to the default case.
7308 switch (state) {
7309 case MONO_AOT_OPTION_STATE_DEFAULT:
7310 state = MONO_AOT_OPTION_STATE_STRING;
7311 break;
7312 case MONO_AOT_OPTION_STATE_STRING:
7313 state = MONO_AOT_OPTION_STATE_DEFAULT;
7314 break;
7315 case MONO_AOT_OPTION_STATE_ESCAPE:
7316 g_assert_not_reached ();
7317 break;
7319 break;
7320 case '\\':
7321 // If we've found an escaping operator, then this means we
7322 // should not process the next character if inside a string.
7323 if (state == MONO_AOT_OPTION_STATE_STRING)
7324 state = MONO_AOT_OPTION_STATE_ESCAPE;
7325 break;
7326 case ',':
7327 // If we're in the default state then this means we've found
7328 // an option, store it for later processing.
7329 if (state == MONO_AOT_OPTION_STATE_DEFAULT)
7330 goto new_opt;
7331 break;
7334 next:
7335 aot_options++;
7336 restart:
7337 // If the next character is end of string, then process the last option.
7338 if (*(aot_options) == '\0') {
7339 end_of_string = TRUE;
7340 goto new_opt;
7342 continue;
7344 new_opt:
7345 ptr_array_add_range_if_nonempty (args, opt_start, aot_options);
7346 opt_start = ++aot_options;
7347 if (end_of_string)
7348 break;
7349 goto restart; // Check for null and continue loop
7352 return args;
7355 static void
7356 mono_aot_parse_options (const char *aot_options, MonoAotOptions *opts)
7358 GPtrArray* args;
7360 args = mono_aot_split_options (aot_options ? aot_options : "");
7361 for (int i = 0; i < args->len; ++i) {
7362 const char *arg = (const char *)g_ptr_array_index (args, i);
7364 if (str_begins_with (arg, "outfile=")) {
7365 opts->outfile = g_strdup (arg + strlen ("outfile="));
7366 } else if (str_begins_with (arg, "llvm-outfile=")) {
7367 opts->llvm_outfile = g_strdup (arg + strlen ("llvm-outfile="));
7368 } else if (str_begins_with (arg, "temp-path=")) {
7369 opts->temp_path = clean_path (g_strdup (arg + strlen ("temp-path=")));
7370 } else if (str_begins_with (arg, "save-temps")) {
7371 opts->save_temps = TRUE;
7372 } else if (str_begins_with (arg, "keep-temps")) {
7373 opts->save_temps = TRUE;
7374 } else if (str_begins_with (arg, "write-symbols")) {
7375 opts->write_symbols = TRUE;
7376 } else if (str_begins_with (arg, "no-write-symbols")) {
7377 opts->write_symbols = FALSE;
7378 // Intentionally undocumented -- one-off experiment
7379 } else if (str_begins_with (arg, "metadata-only")) {
7380 opts->metadata_only = TRUE;
7381 } else if (str_begins_with (arg, "bind-to-runtime-version")) {
7382 opts->bind_to_runtime_version = TRUE;
7383 } else if (str_begins_with (arg, "full")) {
7384 opts->mode = MONO_AOT_MODE_FULL;
7385 } else if (str_begins_with (arg, "hybrid")) {
7386 opts->mode = MONO_AOT_MODE_HYBRID;
7387 } else if (str_begins_with (arg, "interp")) {
7388 opts->interp = TRUE;
7389 } else if (str_begins_with (arg, "threads=")) {
7390 opts->nthreads = atoi (arg + strlen ("threads="));
7391 } else if (str_begins_with (arg, "static")) {
7392 opts->static_link = TRUE;
7393 opts->no_dlsym = TRUE;
7394 } else if (str_begins_with (arg, "asmonly")) {
7395 opts->asm_only = TRUE;
7396 } else if (str_begins_with (arg, "asmwriter")) {
7397 opts->asm_writer = TRUE;
7398 } else if (str_begins_with (arg, "nodebug")) {
7399 opts->nodebug = TRUE;
7400 } else if (str_begins_with (arg, "dwarfdebug")) {
7401 opts->dwarf_debug = TRUE;
7402 // Intentionally undocumented -- No one remembers what this does. It appears to be ARM-only
7403 } else if (str_begins_with (arg, "nopagetrampolines")) {
7404 opts->use_trampolines_page = FALSE;
7405 } else if (str_begins_with (arg, "ntrampolines=")) {
7406 opts->ntrampolines = atoi (arg + strlen ("ntrampolines="));
7407 } else if (str_begins_with (arg, "nrgctx-trampolines=")) {
7408 opts->nrgctx_trampolines = atoi (arg + strlen ("nrgctx-trampolines="));
7409 } else if (str_begins_with (arg, "nrgctx-fetch-trampolines=")) {
7410 opts->nrgctx_fetch_trampolines = atoi (arg + strlen ("nrgctx-fetch-trampolines="));
7411 } else if (str_begins_with (arg, "nimt-trampolines=")) {
7412 opts->nimt_trampolines = atoi (arg + strlen ("nimt-trampolines="));
7413 } else if (str_begins_with (arg, "ngsharedvt-trampolines=")) {
7414 opts->ngsharedvt_arg_trampolines = atoi (arg + strlen ("ngsharedvt-trampolines="));
7415 } else if (str_begins_with (arg, "tool-prefix=")) {
7416 opts->tool_prefix = g_strdup (arg + strlen ("tool-prefix="));
7417 } else if (str_begins_with (arg, "ld-flags=")) {
7418 opts->ld_flags = g_strdup (arg + strlen ("ld-flags="));
7419 } else if (str_begins_with (arg, "soft-debug")) {
7420 opts->soft_debug = TRUE;
7421 // Intentionally undocumented x2-- deprecated
7422 } else if (str_begins_with (arg, "gen-seq-points-file=")) {
7423 fprintf (stderr, "Mono Warning: aot option gen-seq-points-file= is deprecated.\n");
7424 } else if (str_begins_with (arg, "gen-seq-points-file")) {
7425 fprintf (stderr, "Mono Warning: aot option gen-seq-points-file is deprecated.\n");
7426 } else if (str_begins_with (arg, "msym-dir=")) {
7427 mini_debug_options.no_seq_points_compact_data = FALSE;
7428 opts->gen_msym_dir = TRUE;
7429 opts->gen_msym_dir_path = g_strdup (arg + strlen ("msym_dir="));;
7430 } else if (str_begins_with (arg, "direct-pinvoke")) {
7431 opts->direct_pinvoke = TRUE;
7432 } else if (str_begins_with (arg, "direct-icalls")) {
7433 opts->direct_icalls = TRUE;
7434 } else if (str_begins_with (arg, "no-direct-calls")) {
7435 opts->no_direct_calls = TRUE;
7436 } else if (str_begins_with (arg, "print-skipped")) {
7437 opts->print_skipped_methods = TRUE;
7438 } else if (str_begins_with (arg, "stats")) {
7439 opts->stats = TRUE;
7440 // Intentionally undocumented-- has no known function other than to debug the compiler
7441 } else if (str_begins_with (arg, "no-instances")) {
7442 opts->no_instances = TRUE;
7443 // Intentionally undocumented x4-- Used for internal debugging of compiler
7444 } else if (str_begins_with (arg, "log-generics")) {
7445 opts->log_generics = TRUE;
7446 } else if (str_begins_with (arg, "log-instances=")) {
7447 opts->log_instances = TRUE;
7448 opts->instances_logfile_path = g_strdup (arg + strlen ("log-instances="));
7449 } else if (str_begins_with (arg, "log-instances")) {
7450 opts->log_instances = TRUE;
7451 } else if (str_begins_with (arg, "internal-logfile=")) {
7452 opts->logfile = g_strdup (arg + strlen ("internal-logfile="));
7453 } else if (str_begins_with (arg, "dedup-skip")) {
7454 opts->dedup = TRUE;
7455 } else if (str_begins_with (arg, "dedup-include=")) {
7456 opts->dedup_include = g_strdup (arg + strlen ("dedup-include="));
7457 } else if (str_begins_with (arg, "mtriple=")) {
7458 opts->mtriple = g_strdup (arg + strlen ("mtriple="));
7459 } else if (str_begins_with (arg, "llvm-path=")) {
7460 opts->llvm_path = clean_path (g_strdup (arg + strlen ("llvm-path=")));
7461 } else if (!strcmp (arg, "llvm")) {
7462 opts->llvm = TRUE;
7463 } else if (str_begins_with (arg, "readonly-value=")) {
7464 add_readonly_value (opts, arg + strlen ("readonly-value="));
7465 } else if (str_begins_with (arg, "info")) {
7466 printf ("AOT target setup: %s.\n", AOT_TARGET_STR);
7467 exit (0);
7468 // Intentionally undocumented: Used for precise stack maps, which are not available yet
7469 } else if (str_begins_with (arg, "gc-maps")) {
7470 mini_gc_enable_gc_maps_for_aot ();
7471 // Intentionally undocumented: Used for internal debugging
7472 } else if (str_begins_with (arg, "dump")) {
7473 opts->dump_json = TRUE;
7474 } else if (str_begins_with (arg, "llvmonly")) {
7475 opts->mode = MONO_AOT_MODE_FULL;
7476 opts->llvm = TRUE;
7477 opts->llvm_only = TRUE;
7478 } else if (str_begins_with (arg, "data-outfile=")) {
7479 opts->data_outfile = g_strdup (arg + strlen ("data-outfile="));
7480 } else if (str_begins_with (arg, "profile=")) {
7481 opts->profile_files = g_list_append (opts->profile_files, g_strdup (arg + strlen ("profile=")));
7482 } else if (!strcmp (arg, "profile-only")) {
7483 opts->profile_only = TRUE;
7484 } else if (!strcmp (arg, "verbose")) {
7485 opts->verbose = TRUE;
7486 } else if (str_begins_with (arg, "help") || str_begins_with (arg, "?")) {
7487 printf ("Supported options for --aot:\n");
7488 printf (" asmonly\n");
7489 printf (" bind-to-runtime-version\n");
7490 printf (" bitcode\n");
7491 printf (" data-outfile=\n");
7492 printf (" direct-icalls\n");
7493 printf (" direct-pinvoke\n");
7494 printf (" dwarfdebug\n");
7495 printf (" full\n");
7496 printf (" hybrid\n");
7497 printf (" info\n");
7498 printf (" keep-temps\n");
7499 printf (" llvm\n");
7500 printf (" llvmonly\n");
7501 printf (" llvm-outfile=\n");
7502 printf (" llvm-path=\n");
7503 printf (" msym-dir=\n");
7504 printf (" mtriple\n");
7505 printf (" nimt-trampolines=\n");
7506 printf (" nodebug\n");
7507 printf (" no-direct-calls\n");
7508 printf (" no-write-symbols\n");
7509 printf (" nrgctx-trampolines=\n");
7510 printf (" nrgctx-fetch-trampolines=\n");
7511 printf (" ngsharedvt-trampolines=\n");
7512 printf (" ntrampolines=\n");
7513 printf (" outfile=\n");
7514 printf (" profile=\n");
7515 printf (" profile-only\n");
7516 printf (" print-skipped-methods\n");
7517 printf (" readonly-value=\n");
7518 printf (" save-temps\n");
7519 printf (" soft-debug\n");
7520 printf (" static\n");
7521 printf (" stats\n");
7522 printf (" temp-path=\n");
7523 printf (" tool-prefix=\n");
7524 printf (" threads=\n");
7525 printf (" write-symbols\n");
7526 printf (" verbose\n");
7527 printf (" help/?\n");
7528 exit (0);
7529 } else {
7530 fprintf (stderr, "AOT : Unknown argument '%s'.\n", arg);
7531 exit (1);
7534 g_free ((gpointer) arg);
7537 if (opts->use_trampolines_page) {
7538 opts->ntrampolines = 0;
7539 opts->nrgctx_trampolines = 0;
7540 opts->nimt_trampolines = 0;
7541 opts->ngsharedvt_arg_trampolines = 0;
7544 g_ptr_array_free (args, /*free_seg=*/TRUE);
7547 static void
7548 add_token_info_hash (gpointer key, gpointer value, gpointer user_data)
7550 MonoMethod *method = (MonoMethod*)key;
7551 MonoJumpInfoToken *ji = (MonoJumpInfoToken*)value;
7552 MonoAotCompile *acfg = (MonoAotCompile *)user_data;
7553 MonoJumpInfoToken *new_ji;
7555 new_ji = (MonoJumpInfoToken *)mono_mempool_alloc0 (acfg->mempool, sizeof (MonoJumpInfoToken));
7556 new_ji->image = ji->image;
7557 new_ji->token = ji->token;
7558 g_hash_table_insert (acfg->token_info_hash, method, new_ji);
7561 static gboolean
7562 can_encode_class (MonoAotCompile *acfg, MonoClass *klass)
7564 if (m_class_get_type_token (klass))
7565 return TRUE;
7566 if ((m_class_get_byval_arg (klass)->type == MONO_TYPE_VAR) || (m_class_get_byval_arg (klass)->type == MONO_TYPE_MVAR) || (m_class_get_byval_arg (klass)->type == MONO_TYPE_PTR))
7567 return TRUE;
7568 if (m_class_get_rank (klass))
7569 return can_encode_class (acfg, m_class_get_element_class (klass));
7570 return FALSE;
7573 static gboolean
7574 can_encode_method (MonoAotCompile *acfg, MonoMethod *method)
7576 if (method->wrapper_type) {
7577 switch (method->wrapper_type) {
7578 case MONO_WRAPPER_NONE:
7579 case MONO_WRAPPER_REMOTING_INVOKE_WITH_CHECK:
7580 case MONO_WRAPPER_XDOMAIN_INVOKE:
7581 case MONO_WRAPPER_STFLD:
7582 case MONO_WRAPPER_LDFLD:
7583 case MONO_WRAPPER_LDFLDA:
7584 case MONO_WRAPPER_STELEMREF:
7585 case MONO_WRAPPER_PROXY_ISINST:
7586 case MONO_WRAPPER_ALLOC:
7587 case MONO_WRAPPER_REMOTING_INVOKE:
7588 case MONO_WRAPPER_UNKNOWN:
7589 case MONO_WRAPPER_WRITE_BARRIER:
7590 case MONO_WRAPPER_DELEGATE_INVOKE:
7591 case MONO_WRAPPER_DELEGATE_BEGIN_INVOKE:
7592 case MONO_WRAPPER_DELEGATE_END_INVOKE:
7593 case MONO_WRAPPER_SYNCHRONIZED:
7594 break;
7595 case MONO_WRAPPER_MANAGED_TO_MANAGED:
7596 case MONO_WRAPPER_CASTCLASS: {
7597 WrapperInfo *info = mono_marshal_get_wrapper_info (method);
7599 if (info)
7600 return TRUE;
7601 else
7602 return FALSE;
7603 break;
7605 default:
7606 //printf ("Skip (wrapper call): %d -> %s\n", patch_info->type, mono_method_full_name (patch_info->data.method, TRUE));
7607 return FALSE;
7609 } else {
7610 if (!method->token) {
7611 /* The method is part of a constructed type like Int[,].Set (). */
7612 if (!g_hash_table_lookup (acfg->token_info_hash, method)) {
7613 if (m_class_get_rank (method->klass))
7614 return TRUE;
7615 return FALSE;
7619 return TRUE;
7622 static gboolean
7623 can_encode_patch (MonoAotCompile *acfg, MonoJumpInfo *patch_info)
7625 switch (patch_info->type) {
7626 case MONO_PATCH_INFO_METHOD:
7627 case MONO_PATCH_INFO_METHODCONST:
7628 case MONO_PATCH_INFO_METHOD_CODE_SLOT: {
7629 MonoMethod *method = patch_info->data.method;
7631 return can_encode_method (acfg, method);
7633 case MONO_PATCH_INFO_VTABLE:
7634 case MONO_PATCH_INFO_CLASS:
7635 case MONO_PATCH_INFO_IID:
7636 case MONO_PATCH_INFO_ADJUSTED_IID:
7637 if (!can_encode_class (acfg, patch_info->data.klass)) {
7638 //printf ("Skip: %s\n", mono_type_full_name (&patch_info->data.klass->byval_arg));
7639 return FALSE;
7641 break;
7642 case MONO_PATCH_INFO_DELEGATE_TRAMPOLINE: {
7643 if (!can_encode_class (acfg, patch_info->data.del_tramp->klass)) {
7644 //printf ("Skip: %s\n", mono_type_full_name (&patch_info->data.klass->byval_arg));
7645 return FALSE;
7647 break;
7649 case MONO_PATCH_INFO_RGCTX_FETCH:
7650 case MONO_PATCH_INFO_RGCTX_SLOT_INDEX: {
7651 MonoJumpInfoRgctxEntry *entry = patch_info->data.rgctx_entry;
7653 if (!can_encode_method (acfg, entry->method))
7654 return FALSE;
7655 if (!can_encode_patch (acfg, entry->data))
7656 return FALSE;
7657 break;
7659 default:
7660 break;
7663 return TRUE;
7666 static gboolean
7667 is_concrete_type (MonoType *t)
7669 MonoClass *klass;
7670 int i;
7672 if (t->type == MONO_TYPE_VAR || t->type == MONO_TYPE_MVAR)
7673 return FALSE;
7674 if (t->type == MONO_TYPE_GENERICINST) {
7675 MonoGenericContext *orig_ctx;
7676 MonoGenericInst *inst;
7677 MonoType *arg;
7679 if (!MONO_TYPE_ISSTRUCT (t))
7680 return TRUE;
7681 klass = mono_class_from_mono_type (t);
7682 orig_ctx = &mono_class_get_generic_class (klass)->context;
7684 inst = orig_ctx->class_inst;
7685 if (inst) {
7686 for (i = 0; i < inst->type_argc; ++i) {
7687 arg = mini_get_underlying_type (inst->type_argv [i]);
7688 if (!is_concrete_type (arg))
7689 return FALSE;
7692 inst = orig_ctx->method_inst;
7693 if (inst) {
7694 for (i = 0; i < inst->type_argc; ++i) {
7695 arg = mini_get_underlying_type (inst->type_argv [i]);
7696 if (!is_concrete_type (arg))
7697 return FALSE;
7701 return TRUE;
7704 /* LOCKING: Assumes the loader lock is held */
7705 static void
7706 add_gsharedvt_wrappers (MonoAotCompile *acfg, MonoMethodSignature *sig, gboolean gsharedvt_in, gboolean gsharedvt_out, gboolean interp_in)
7708 MonoMethod *wrapper;
7709 gboolean concrete = TRUE;
7710 gboolean add_in = gsharedvt_in;
7711 gboolean add_out = gsharedvt_out;
7713 if (gsharedvt_in && g_hash_table_lookup (acfg->gsharedvt_in_signatures, sig))
7714 add_in = FALSE;
7715 if (gsharedvt_out && g_hash_table_lookup (acfg->gsharedvt_out_signatures, sig))
7716 add_out = FALSE;
7718 if (!add_in && !add_out)
7719 return;
7721 if (mini_is_gsharedvt_variable_signature (sig))
7722 return;
7724 if (add_in)
7725 g_hash_table_insert (acfg->gsharedvt_in_signatures, sig, sig);
7726 if (add_out)
7727 g_hash_table_insert (acfg->gsharedvt_out_signatures, sig, sig);
7729 if (sig->has_type_parameters) {
7730 /* For signatures created during generic sharing, convert them to a concrete signature if possible */
7731 MonoMethodSignature *copy = mono_metadata_signature_dup (sig);
7732 int i;
7734 //printf ("%s\n", mono_signature_full_name (sig));
7736 copy->ret = mini_get_underlying_type (sig->ret);
7737 if (!is_concrete_type (copy->ret))
7738 concrete = FALSE;
7739 for (i = 0; i < sig->param_count; ++i) {
7740 copy->params [i] = mini_get_underlying_type (sig->params [i]);
7741 if (!is_concrete_type (copy->params [i]))
7742 concrete = FALSE;
7744 copy->has_type_parameters = 0;
7745 if (!concrete)
7746 return;
7747 sig = copy;
7750 //printf ("%s\n", mono_signature_full_name (sig));
7752 if (gsharedvt_in) {
7753 wrapper = mini_get_gsharedvt_in_sig_wrapper (sig);
7754 add_extra_method (acfg, wrapper);
7756 if (gsharedvt_out) {
7757 wrapper = mini_get_gsharedvt_out_sig_wrapper (sig);
7758 add_extra_method (acfg, wrapper);
7760 if (interp_in) {
7761 wrapper = mini_get_interp_in_wrapper (sig);
7762 add_extra_method (acfg, wrapper);
7763 //printf ("X: %s\n", mono_method_full_name (wrapper, 1));
7768 * compile_method:
7770 * AOT compile a given method.
7771 * This function might be called by multiple threads, so it must be thread-safe.
7773 static void
7774 compile_method (MonoAotCompile *acfg, MonoMethod *method)
7776 MonoCompile *cfg;
7777 MonoJumpInfo *patch_info;
7778 gboolean skip;
7779 int index, depth;
7780 MonoMethod *wrapped;
7781 GTimer *jit_timer;
7782 JitFlags flags;
7784 if (acfg->aot_opts.metadata_only)
7785 return;
7787 mono_acfg_lock (acfg);
7788 index = get_method_index (acfg, method);
7789 mono_acfg_unlock (acfg);
7791 /* fixme: maybe we can also precompile wrapper methods */
7792 if ((method->flags & METHOD_ATTRIBUTE_PINVOKE_IMPL) ||
7793 (method->iflags & METHOD_IMPL_ATTRIBUTE_RUNTIME) ||
7794 (method->flags & METHOD_ATTRIBUTE_ABSTRACT)) {
7795 //printf ("Skip (impossible): %s\n", mono_method_full_name (method, TRUE));
7796 return;
7799 if (method->iflags & METHOD_IMPL_ATTRIBUTE_INTERNAL_CALL)
7800 return;
7802 wrapped = mono_marshal_method_from_wrapper (method);
7803 if (wrapped && (wrapped->iflags & METHOD_IMPL_ATTRIBUTE_INTERNAL_CALL) && wrapped->is_generic)
7804 // FIXME: The wrapper should be generic too, but it is not
7805 return;
7807 if (method->wrapper_type == MONO_WRAPPER_COMINTEROP)
7808 return;
7810 if (acfg->aot_opts.profile_only && !method->is_inflated && !g_hash_table_lookup (acfg->profile_methods, method))
7811 return;
7813 mono_atomic_inc_i32 (&acfg->stats.mcount);
7815 #if 0
7816 if (method->is_generic || mono_class_is_gtd (method->klass)) {
7817 mono_atomic_inc_i32 (&acfg->stats.genericcount);
7818 return;
7820 #endif
7822 //acfg->aot_opts.print_skipped_methods = TRUE;
7825 * Since these methods are the only ones which are compiled with
7826 * AOT support, and they are not used by runtime startup/shutdown code,
7827 * the runtime will not see AOT methods during AOT compilation,so it
7828 * does not need to support them by creating a fake GOT etc.
7830 flags = JIT_FLAG_AOT;
7831 if (mono_aot_mode_is_full (&acfg->aot_opts))
7832 flags = (JitFlags)(flags | JIT_FLAG_FULL_AOT);
7833 if (acfg->llvm)
7834 flags = (JitFlags)(flags | JIT_FLAG_LLVM);
7835 if (acfg->aot_opts.llvm_only)
7836 flags = (JitFlags)(flags | JIT_FLAG_LLVM_ONLY | JIT_FLAG_EXPLICIT_NULL_CHECKS);
7837 if (acfg->aot_opts.no_direct_calls)
7838 flags = (JitFlags)(flags | JIT_FLAG_NO_DIRECT_ICALLS);
7839 if (acfg->aot_opts.direct_pinvoke)
7840 flags = (JitFlags)(flags | JIT_FLAG_DIRECT_PINVOKE);
7842 jit_timer = mono_time_track_start ();
7843 cfg = mini_method_compile (method, acfg->opts, mono_get_root_domain (), flags, 0, index);
7844 mono_time_track_end (&mono_jit_stats.jit_time, jit_timer);
7846 if (cfg->exception_type == MONO_EXCEPTION_GENERIC_SHARING_FAILED) {
7847 if (acfg->aot_opts.print_skipped_methods)
7848 printf ("Skip (gshared failure): %s (%s)\n", mono_method_get_full_name (method), cfg->exception_message);
7849 mono_atomic_inc_i32 (&acfg->stats.genericcount);
7850 return;
7852 if (cfg->exception_type != MONO_EXCEPTION_NONE) {
7853 /* Some instances cannot be JITted due to constraints etc. */
7854 if (!method->is_inflated)
7855 report_loader_error (acfg, &cfg->error, FALSE, "Unable to compile method '%s' due to: '%s'.\n", mono_method_get_full_name (method), mono_error_get_message (&cfg->error));
7856 /* Let the exception happen at runtime */
7857 return;
7860 if (cfg->disable_aot) {
7861 if (acfg->aot_opts.print_skipped_methods)
7862 printf ("Skip (disabled): %s\n", mono_method_get_full_name (method));
7863 mono_atomic_inc_i32 (&acfg->stats.ocount);
7864 return;
7866 cfg->method_index = index;
7868 /* Nullify patches which need no aot processing */
7869 for (patch_info = cfg->patch_info; patch_info; patch_info = patch_info->next) {
7870 switch (patch_info->type) {
7871 case MONO_PATCH_INFO_LABEL:
7872 case MONO_PATCH_INFO_BB:
7873 patch_info->type = MONO_PATCH_INFO_NONE;
7874 break;
7875 default:
7876 break;
7880 /* Collect method->token associations from the cfg */
7881 mono_acfg_lock (acfg);
7882 g_hash_table_foreach (cfg->token_info_hash, add_token_info_hash, acfg);
7883 mono_acfg_unlock (acfg);
7884 g_hash_table_destroy (cfg->token_info_hash);
7885 cfg->token_info_hash = NULL;
7888 * Check for absolute addresses.
7890 skip = FALSE;
7891 for (patch_info = cfg->patch_info; patch_info; patch_info = patch_info->next) {
7892 switch (patch_info->type) {
7893 case MONO_PATCH_INFO_ABS:
7894 /* unable to handle this */
7895 skip = TRUE;
7896 break;
7897 default:
7898 break;
7902 if (skip) {
7903 if (acfg->aot_opts.print_skipped_methods)
7904 printf ("Skip (abs call): %s\n", mono_method_get_full_name (method));
7905 mono_atomic_inc_i32 (&acfg->stats.abscount);
7906 return;
7909 /* Lock for the rest of the code */
7910 mono_acfg_lock (acfg);
7912 if (cfg->gsharedvt)
7913 acfg->stats.method_categories [METHOD_CAT_GSHAREDVT] ++;
7914 else if (cfg->gshared)
7915 acfg->stats.method_categories [METHOD_CAT_INST] ++;
7916 else if (cfg->method->wrapper_type)
7917 acfg->stats.method_categories [METHOD_CAT_WRAPPER] ++;
7918 else
7919 acfg->stats.method_categories [METHOD_CAT_NORMAL] ++;
7922 * Check for methods/klasses we can't encode.
7924 skip = FALSE;
7925 for (patch_info = cfg->patch_info; patch_info; patch_info = patch_info->next) {
7926 if (!can_encode_patch (acfg, patch_info))
7927 skip = TRUE;
7930 if (skip) {
7931 if (acfg->aot_opts.print_skipped_methods)
7932 printf ("Skip (patches): %s\n", mono_method_get_full_name (method));
7933 acfg->stats.ocount++;
7934 mono_acfg_unlock (acfg);
7935 return;
7938 if (!cfg->compile_llvm)
7939 acfg->has_jitted_code = TRUE;
7941 if (method->is_inflated && acfg->aot_opts.log_instances) {
7942 if (acfg->instances_logfile)
7943 fprintf (acfg->instances_logfile, "%s ### %d\n", mono_method_get_full_name (method), cfg->code_size);
7944 else
7945 printf ("%s ### %d\n", mono_method_get_full_name (method), cfg->code_size);
7948 /* Adds generic instances referenced by this method */
7950 * The depth is used to avoid infinite loops when generic virtual recursion is
7951 * encountered.
7953 depth = GPOINTER_TO_UINT (g_hash_table_lookup (acfg->method_depth, method));
7954 if (!acfg->aot_opts.no_instances && depth < 32 && (mono_aot_mode_is_full (&acfg->aot_opts) || mono_aot_mode_is_hybrid (&acfg->aot_opts))) {
7955 for (patch_info = cfg->patch_info; patch_info; patch_info = patch_info->next) {
7956 switch (patch_info->type) {
7957 case MONO_PATCH_INFO_RGCTX_FETCH:
7958 case MONO_PATCH_INFO_RGCTX_SLOT_INDEX:
7959 case MONO_PATCH_INFO_METHOD:
7960 case MONO_PATCH_INFO_METHOD_RGCTX: {
7961 MonoMethod *m = NULL;
7963 if (patch_info->type == MONO_PATCH_INFO_RGCTX_FETCH || patch_info->type == MONO_PATCH_INFO_RGCTX_SLOT_INDEX) {
7964 MonoJumpInfoRgctxEntry *e = patch_info->data.rgctx_entry;
7966 if (e->info_type == MONO_RGCTX_INFO_GENERIC_METHOD_CODE)
7967 m = e->data->data.method;
7968 } else {
7969 m = patch_info->data.method;
7972 if (!m)
7973 break;
7974 if (m->is_inflated && (mono_aot_mode_is_full (&acfg->aot_opts) || mono_aot_mode_is_hybrid (&acfg->aot_opts))) {
7975 if (!(mono_class_generic_sharing_enabled (m->klass) &&
7976 mono_method_is_generic_sharable_full (m, FALSE, FALSE, FALSE)) &&
7977 (!method_has_type_vars (m) || mono_method_is_generic_sharable_full (m, TRUE, TRUE, FALSE))) {
7978 if (m->iflags & METHOD_IMPL_ATTRIBUTE_INTERNAL_CALL) {
7979 if (mono_aot_mode_is_full (&acfg->aot_opts) && !method_has_type_vars (m))
7980 add_extra_method_with_depth (acfg, mono_marshal_get_native_wrapper (m, TRUE, TRUE), depth + 1);
7981 } else {
7982 add_extra_method_with_depth (acfg, m, depth + 1);
7983 add_types_from_method_header (acfg, m);
7986 add_generic_class_with_depth (acfg, m->klass, depth + 5, "method");
7988 if (m->wrapper_type == MONO_WRAPPER_MANAGED_TO_MANAGED) {
7989 WrapperInfo *info = mono_marshal_get_wrapper_info (m);
7991 if (info && info->subtype == WRAPPER_SUBTYPE_ELEMENT_ADDR)
7992 add_extra_method_with_depth (acfg, m, depth + 1);
7994 break;
7996 case MONO_PATCH_INFO_VTABLE: {
7997 MonoClass *klass = patch_info->data.klass;
7999 if (mono_class_is_ginst (klass) && !mini_class_is_generic_sharable (klass))
8000 add_generic_class_with_depth (acfg, klass, depth + 5, "vtable");
8001 break;
8003 case MONO_PATCH_INFO_SFLDA: {
8004 MonoClass *klass = patch_info->data.field->parent;
8006 /* The .cctor needs to run at runtime. */
8007 if (mono_class_is_ginst (klass) && !mono_generic_context_is_sharable_full (&mono_class_get_generic_class (klass)->context, FALSE, FALSE) && mono_class_get_cctor (klass))
8008 add_extra_method_with_depth (acfg, mono_class_get_cctor (klass), depth + 1);
8009 break;
8011 default:
8012 break;
8017 /* Determine whenever the method has GOT slots */
8018 for (patch_info = cfg->patch_info; patch_info; patch_info = patch_info->next) {
8019 switch (patch_info->type) {
8020 case MONO_PATCH_INFO_GOT_OFFSET:
8021 case MONO_PATCH_INFO_NONE:
8022 case MONO_PATCH_INFO_GC_CARD_TABLE_ADDR:
8023 case MONO_PATCH_INFO_GC_NURSERY_START:
8024 case MONO_PATCH_INFO_GC_NURSERY_BITS:
8025 break;
8026 case MONO_PATCH_INFO_IMAGE:
8027 /* The assembly is stored in GOT slot 0 */
8028 if (patch_info->data.image != acfg->image)
8029 cfg->has_got_slots = TRUE;
8030 break;
8031 default:
8032 if (!is_plt_patch (patch_info) || (cfg->compile_llvm && acfg->aot_opts.llvm_only))
8033 cfg->has_got_slots = TRUE;
8034 break;
8038 if (!cfg->has_got_slots)
8039 mono_atomic_inc_i32 (&acfg->stats.methods_without_got_slots);
8041 /* Add gsharedvt wrappers for signatures used by the method */
8042 if (acfg->aot_opts.llvm_only) {
8043 GSList *l;
8045 if (!cfg->method->wrapper_type || cfg->method->wrapper_type == MONO_WRAPPER_DELEGATE_INVOKE)
8046 /* These only need out wrappers */
8047 add_gsharedvt_wrappers (acfg, mono_method_signature (cfg->method), FALSE, TRUE, FALSE);
8049 for (l = cfg->signatures; l; l = l->next) {
8050 MonoMethodSignature *sig = mono_metadata_signature_dup ((MonoMethodSignature*)l->data);
8052 /* These only need in wrappers */
8053 add_gsharedvt_wrappers (acfg, sig, TRUE, FALSE, FALSE);
8055 } else if (mono_aot_mode_is_full (&acfg->aot_opts) && mono_aot_mode_is_interp (&acfg->aot_opts)) {
8056 /* The interpreter uses these wrappers to call aot-ed code */
8057 if (!cfg->method->wrapper_type || cfg->method->wrapper_type == MONO_WRAPPER_DELEGATE_INVOKE)
8058 add_gsharedvt_wrappers (acfg, mono_method_signature (cfg->method), FALSE, TRUE, TRUE);
8062 * FIXME: Instead of this mess, allocate the patches from the aot mempool.
8064 /* Make a copy of the patch info which is in the mempool */
8066 MonoJumpInfo *patches = NULL, *patches_end = NULL;
8068 for (patch_info = cfg->patch_info; patch_info; patch_info = patch_info->next) {
8069 MonoJumpInfo *new_patch_info = mono_patch_info_dup_mp (acfg->mempool, patch_info);
8071 if (!patches)
8072 patches = new_patch_info;
8073 else
8074 patches_end->next = new_patch_info;
8075 patches_end = new_patch_info;
8077 cfg->patch_info = patches;
8079 /* Make a copy of the unwind info */
8081 GSList *l, *unwind_ops;
8082 MonoUnwindOp *op;
8084 unwind_ops = NULL;
8085 for (l = cfg->unwind_ops; l; l = l->next) {
8086 op = (MonoUnwindOp *)mono_mempool_alloc (acfg->mempool, sizeof (MonoUnwindOp));
8087 memcpy (op, l->data, sizeof (MonoUnwindOp));
8088 unwind_ops = g_slist_prepend_mempool (acfg->mempool, unwind_ops, op);
8090 cfg->unwind_ops = g_slist_reverse (unwind_ops);
8092 /* Make a copy of the argument/local info */
8094 ERROR_DECL (error);
8095 MonoInst **args, **locals;
8096 MonoMethodSignature *sig;
8097 MonoMethodHeader *header;
8098 int i;
8100 sig = mono_method_signature (method);
8101 args = (MonoInst **)mono_mempool_alloc (acfg->mempool, sizeof (MonoInst*) * (sig->param_count + sig->hasthis));
8102 for (i = 0; i < sig->param_count + sig->hasthis; ++i) {
8103 args [i] = (MonoInst *)mono_mempool_alloc (acfg->mempool, sizeof (MonoInst));
8104 memcpy (args [i], cfg->args [i], sizeof (MonoInst));
8106 cfg->args = args;
8108 header = mono_method_get_header_checked (method, error);
8109 mono_error_assert_ok (error); /* FIXME don't swallow the error */
8110 locals = (MonoInst **)mono_mempool_alloc (acfg->mempool, sizeof (MonoInst*) * header->num_locals);
8111 for (i = 0; i < header->num_locals; ++i) {
8112 locals [i] = (MonoInst *)mono_mempool_alloc (acfg->mempool, sizeof (MonoInst));
8113 memcpy (locals [i], cfg->locals [i], sizeof (MonoInst));
8115 mono_metadata_free_mh (header);
8116 cfg->locals = locals;
8119 /* Free some fields used by cfg to conserve memory */
8120 mono_empty_compile (cfg);
8122 //printf ("Compile: %s\n", mono_method_full_name (method, TRUE));
8124 while (index >= acfg->cfgs_size) {
8125 MonoCompile **new_cfgs;
8126 int new_size;
8128 new_size = acfg->cfgs_size * 2;
8129 new_cfgs = g_new0 (MonoCompile*, new_size);
8130 memcpy (new_cfgs, acfg->cfgs, sizeof (MonoCompile*) * acfg->cfgs_size);
8131 g_free (acfg->cfgs);
8132 acfg->cfgs = new_cfgs;
8133 acfg->cfgs_size = new_size;
8135 acfg->cfgs [index] = cfg;
8137 g_hash_table_insert (acfg->method_to_cfg, cfg->orig_method, cfg);
8139 /* Update global stats while holding a lock. */
8140 mono_update_jit_stats (cfg);
8143 if (cfg->orig_method->wrapper_type)
8144 g_ptr_array_add (acfg->extra_methods, cfg->orig_method);
8147 mono_acfg_unlock (acfg);
8149 mono_atomic_inc_i32 (&acfg->stats.ccount);
8152 static mono_thread_start_return_t WINAPI
8153 compile_thread_main (gpointer user_data)
8155 MonoAotCompile *acfg = ((MonoAotCompile **)user_data) [0];
8156 GPtrArray *methods = ((GPtrArray **)user_data) [1];
8157 int i;
8159 ERROR_DECL (error);
8160 MonoInternalThread *internal = mono_thread_internal_current ();
8161 MonoString *str = mono_string_new_checked (mono_domain_get (), "AOT compiler", error);
8162 mono_error_assert_ok (error);
8163 mono_thread_set_name_internal (internal, str, TRUE, FALSE, error);
8164 mono_error_assert_ok (error);
8166 for (i = 0; i < methods->len; ++i)
8167 compile_method (acfg, (MonoMethod *)g_ptr_array_index (methods, i));
8169 return 0;
8172 /* Used by the LLVM backend */
8173 guint32
8174 mono_aot_get_got_offset (MonoJumpInfo *ji)
8176 return get_got_offset (llvm_acfg, TRUE, ji);
8180 * mono_aot_is_shared_got_offset:
8182 * Return whenever OFFSET refers to a GOT slot which is preinitialized
8183 * when the AOT image is loaded.
8185 gboolean
8186 mono_aot_is_shared_got_offset (int offset)
8188 return offset < llvm_acfg->nshared_got_entries;
8191 char*
8192 mono_aot_get_method_name (MonoCompile *cfg)
8194 if (llvm_acfg->aot_opts.static_link)
8195 /* Include the assembly name too to avoid duplicate symbol errors */
8196 return g_strdup_printf ("%s_%s", llvm_acfg->assembly_name_sym, get_debug_sym (cfg->orig_method, "", llvm_acfg->method_label_hash));
8197 else
8198 return get_debug_sym (cfg->orig_method, "", llvm_acfg->method_label_hash);
8202 * mono_aot_is_linkonce_method:
8204 * Return whenever METHOD should be emitted with linkonce linkage,
8205 * eliminating duplicate copies when compiling in static mode.
8207 gboolean
8208 mono_aot_is_linkonce_method (MonoMethod *method)
8210 return FALSE;
8211 #if 0
8212 WrapperInfo *info;
8214 // FIXME: Add more cases
8215 if (method->wrapper_type != MONO_WRAPPER_UNKNOWN)
8216 return FALSE;
8217 info = mono_marshal_get_wrapper_info (method);
8218 if ((info && (info->subtype == WRAPPER_SUBTYPE_GSHAREDVT_IN_SIG || info->subtype == WRAPPER_SUBTYPE_GSHAREDVT_OUT_SIG)))
8219 return TRUE;
8220 return FALSE;
8221 #endif
8224 static gboolean
8225 append_mangled_type (GString *s, MonoType *t)
8227 if (t->byref)
8228 g_string_append_printf (s, "b");
8229 switch (t->type) {
8230 case MONO_TYPE_VOID:
8231 g_string_append_printf (s, "void_");
8232 break;
8233 case MONO_TYPE_I1:
8234 g_string_append_printf (s, "i1");
8235 break;
8236 case MONO_TYPE_U1:
8237 g_string_append_printf (s, "u1");
8238 break;
8239 case MONO_TYPE_I2:
8240 g_string_append_printf (s, "i2");
8241 break;
8242 case MONO_TYPE_U2:
8243 g_string_append_printf (s, "u2");
8244 break;
8245 case MONO_TYPE_I4:
8246 g_string_append_printf (s, "i4");
8247 break;
8248 case MONO_TYPE_U4:
8249 g_string_append_printf (s, "u4");
8250 break;
8251 case MONO_TYPE_I8:
8252 g_string_append_printf (s, "i8");
8253 break;
8254 case MONO_TYPE_U8:
8255 g_string_append_printf (s, "u8");
8256 break;
8257 case MONO_TYPE_I:
8258 g_string_append_printf (s, "ii");
8259 break;
8260 case MONO_TYPE_U:
8261 g_string_append_printf (s, "ui");
8262 break;
8263 case MONO_TYPE_R4:
8264 g_string_append_printf (s, "fl");
8265 break;
8266 case MONO_TYPE_R8:
8267 g_string_append_printf (s, "do");
8268 break;
8269 default: {
8270 char *fullname = mono_type_full_name (t);
8271 GString *temp;
8272 char *temps;
8273 int i, len;
8276 * Have to create a mangled name which is:
8277 * - a valid symbol
8278 * - unique
8280 temp = g_string_new ("");
8281 len = strlen (fullname);
8282 for (i = 0; i < len; ++i) {
8283 char c = fullname [i];
8284 if (isalnum (c)) {
8285 g_string_append_c (temp, c);
8286 } else if (c == '_') {
8287 g_string_append_c (temp, '_');
8288 g_string_append_c (temp, '_');
8289 } else {
8290 g_string_append_c (temp, '_');
8291 g_string_append_printf (temp, "%x", (int)c);
8294 temps = g_string_free (temp, FALSE);
8295 /* Include the length to avoid different length type names aliasing each other */
8296 g_string_append_printf (s, "cl%x_%s_", strlen (temps), temps);
8297 g_free (temps);
8300 if (t->attrs)
8301 g_string_append_printf (s, "_attrs_%d", t->attrs);
8302 return TRUE;
8305 static gboolean
8306 append_mangled_signature (GString *s, MonoMethodSignature *sig)
8308 int i;
8309 gboolean supported;
8311 supported = append_mangled_type (s, sig->ret);
8312 if (!supported)
8313 return FALSE;
8314 if (sig->hasthis)
8315 g_string_append_printf (s, "this_");
8316 if (sig->pinvoke)
8317 g_string_append_printf (s, "pinvoke_");
8318 for (i = 0; i < sig->param_count; ++i) {
8319 supported = append_mangled_type (s, sig->params [i]);
8320 if (!supported)
8321 return FALSE;
8324 return TRUE;
8327 static void
8328 append_mangled_wrapper_type (GString *s, guint32 wrapper_type)
8330 const char *label;
8332 switch (wrapper_type) {
8333 case MONO_WRAPPER_REMOTING_INVOKE:
8334 label = "remoting_invoke";
8335 break;
8336 case MONO_WRAPPER_REMOTING_INVOKE_WITH_CHECK:
8337 label = "remoting_invoke_check";
8338 break;
8339 case MONO_WRAPPER_XDOMAIN_INVOKE:
8340 label = "remoting_invoke_xdomain";
8341 break;
8342 case MONO_WRAPPER_PROXY_ISINST:
8343 label = "proxy_isinst";
8344 break;
8345 case MONO_WRAPPER_LDFLD:
8346 label = "ldfld";
8347 break;
8348 case MONO_WRAPPER_LDFLDA:
8349 label = "ldflda";
8350 break;
8351 case MONO_WRAPPER_STFLD:
8352 label = "stfld";
8353 break;
8354 case MONO_WRAPPER_ALLOC:
8355 label = "alloc";
8356 break;
8357 case MONO_WRAPPER_WRITE_BARRIER:
8358 label = "write_barrier";
8359 break;
8360 case MONO_WRAPPER_STELEMREF:
8361 label = "stelemref";
8362 break;
8363 case MONO_WRAPPER_UNKNOWN:
8364 label = "unknown";
8365 break;
8366 case MONO_WRAPPER_MANAGED_TO_NATIVE:
8367 label = "man2native";
8368 break;
8369 case MONO_WRAPPER_SYNCHRONIZED:
8370 label = "synch";
8371 break;
8372 case MONO_WRAPPER_MANAGED_TO_MANAGED:
8373 label = "man2man";
8374 break;
8375 case MONO_WRAPPER_CASTCLASS:
8376 label = "castclass";
8377 break;
8378 case MONO_WRAPPER_RUNTIME_INVOKE:
8379 label = "run_invoke";
8380 break;
8381 case MONO_WRAPPER_DELEGATE_INVOKE:
8382 label = "del_inv";
8383 break;
8384 case MONO_WRAPPER_DELEGATE_BEGIN_INVOKE:
8385 label = "del_beg_inv";
8386 break;
8387 case MONO_WRAPPER_DELEGATE_END_INVOKE:
8388 label = "del_end_inv";
8389 break;
8390 case MONO_WRAPPER_NATIVE_TO_MANAGED:
8391 label = "native2man";
8392 break;
8393 default:
8394 g_assert_not_reached ();
8397 g_string_append_printf (s, "%s_", label);
8400 static void
8401 append_mangled_wrapper_subtype (GString *s, WrapperSubtype subtype)
8403 const char *label;
8405 switch (subtype)
8407 case WRAPPER_SUBTYPE_NONE:
8408 return;
8409 case WRAPPER_SUBTYPE_ELEMENT_ADDR:
8410 label = "elem_addr";
8411 break;
8412 case WRAPPER_SUBTYPE_STRING_CTOR:
8413 label = "str_ctor";
8414 break;
8415 case WRAPPER_SUBTYPE_VIRTUAL_STELEMREF:
8416 label = "virt_stelem";
8417 break;
8418 case WRAPPER_SUBTYPE_FAST_MONITOR_ENTER:
8419 label = "fast_mon_enter";
8420 break;
8421 case WRAPPER_SUBTYPE_FAST_MONITOR_ENTER_V4:
8422 label = "fast_mon_enter_4";
8423 break;
8424 case WRAPPER_SUBTYPE_FAST_MONITOR_EXIT:
8425 label = "fast_monitor_exit";
8426 break;
8427 case WRAPPER_SUBTYPE_PTR_TO_STRUCTURE:
8428 label = "ptr2struct";
8429 break;
8430 case WRAPPER_SUBTYPE_STRUCTURE_TO_PTR:
8431 label = "struct2ptr";
8432 break;
8433 case WRAPPER_SUBTYPE_CASTCLASS_WITH_CACHE:
8434 label = "castclass_w_cache";
8435 break;
8436 case WRAPPER_SUBTYPE_ISINST_WITH_CACHE:
8437 label = "isinst_w_cache";
8438 break;
8439 case WRAPPER_SUBTYPE_RUNTIME_INVOKE_NORMAL:
8440 label = "run_inv_norm";
8441 break;
8442 case WRAPPER_SUBTYPE_RUNTIME_INVOKE_DYNAMIC:
8443 label = "run_inv_dyn";
8444 break;
8445 case WRAPPER_SUBTYPE_RUNTIME_INVOKE_DIRECT:
8446 label = "run_inv_dir";
8447 break;
8448 case WRAPPER_SUBTYPE_RUNTIME_INVOKE_VIRTUAL:
8449 label = "run_inv_vir";
8450 break;
8451 case WRAPPER_SUBTYPE_ICALL_WRAPPER:
8452 label = "icall";
8453 break;
8454 case WRAPPER_SUBTYPE_NATIVE_FUNC_AOT:
8455 label = "native_func_aot";
8456 break;
8457 case WRAPPER_SUBTYPE_PINVOKE:
8458 label = "pinvoke";
8459 break;
8460 case WRAPPER_SUBTYPE_SYNCHRONIZED_INNER:
8461 label = "synch_inner";
8462 break;
8463 case WRAPPER_SUBTYPE_GSHAREDVT_IN:
8464 label = "gshared_in";
8465 break;
8466 case WRAPPER_SUBTYPE_GSHAREDVT_OUT:
8467 label = "gshared_out";
8468 break;
8469 case WRAPPER_SUBTYPE_ARRAY_ACCESSOR:
8470 label = "array_acc";
8471 break;
8472 case WRAPPER_SUBTYPE_GENERIC_ARRAY_HELPER:
8473 label = "generic_arry_help";
8474 break;
8475 case WRAPPER_SUBTYPE_DELEGATE_INVOKE_VIRTUAL:
8476 label = "del_inv_virt";
8477 break;
8478 case WRAPPER_SUBTYPE_DELEGATE_INVOKE_BOUND:
8479 label = "del_inv_bound";
8480 break;
8481 case WRAPPER_SUBTYPE_INTERP_IN:
8482 label = "interp_in";
8483 break;
8484 case WRAPPER_SUBTYPE_GSHAREDVT_IN_SIG:
8485 label = "gsharedvt_in_sig";
8486 break;
8487 case WRAPPER_SUBTYPE_GSHAREDVT_OUT_SIG:
8488 label = "gsharedvt_out_sig";
8489 break;
8490 default:
8491 g_assert_not_reached ();
8494 g_string_append_printf (s, "%s_", label);
8497 static char *
8498 sanitize_mangled_string (const char *input)
8500 GString *s = g_string_new ("");
8502 for (int i=0; input [i] != '\0'; i++) {
8503 char c = input [i];
8504 switch (c) {
8505 case '.':
8506 g_string_append (s, "_dot_");
8507 break;
8508 case ' ':
8509 g_string_append (s, "_");
8510 break;
8511 case '`':
8512 g_string_append (s, "_bt_");
8513 break;
8514 case '<':
8515 g_string_append (s, "_le_");
8516 break;
8517 case '>':
8518 g_string_append (s, "_gt_");
8519 break;
8520 case '/':
8521 g_string_append (s, "_sl_");
8522 break;
8523 case '[':
8524 g_string_append (s, "_lbrack_");
8525 break;
8526 case ']':
8527 g_string_append (s, "_rbrack_");
8528 break;
8529 case '(':
8530 g_string_append (s, "_lparen_");
8531 break;
8532 case '-':
8533 g_string_append (s, "_dash_");
8534 break;
8535 case ')':
8536 g_string_append (s, "_rparen_");
8537 break;
8538 case ',':
8539 g_string_append (s, "_comma_");
8540 break;
8541 case ':':
8542 g_string_append (s, "_colon_");
8543 break;
8544 default:
8545 g_string_append_c (s, c);
8549 return g_string_free (s, FALSE);
8552 static gboolean
8553 append_mangled_klass (GString *s, MonoClass *klass)
8555 char *klass_desc = mono_class_full_name (klass);
8556 g_string_append_printf (s, "_%s_%s_", m_class_get_name_space (klass), klass_desc);
8557 g_free (klass_desc);
8559 // Success
8560 return TRUE;
8563 static gboolean
8564 append_mangled_method (GString *s, MonoMethod *method);
8566 static gboolean
8567 append_mangled_wrapper (GString *s, MonoMethod *method)
8569 gboolean success = TRUE;
8570 WrapperInfo *info = mono_marshal_get_wrapper_info (method);
8571 g_string_append_printf (s, "wrapper_");
8572 g_string_append_printf (s, "%s_", m_class_get_image (method->klass)->assembly->aname.name);
8574 append_mangled_wrapper_type (s, method->wrapper_type);
8576 switch (method->wrapper_type) {
8577 case MONO_WRAPPER_REMOTING_INVOKE:
8578 case MONO_WRAPPER_REMOTING_INVOKE_WITH_CHECK:
8579 case MONO_WRAPPER_XDOMAIN_INVOKE: {
8580 MonoMethod *m = mono_marshal_method_from_wrapper (method);
8581 g_assert (m);
8582 success = success && append_mangled_method (s, m);
8583 break;
8585 case MONO_WRAPPER_PROXY_ISINST:
8586 case MONO_WRAPPER_LDFLD:
8587 case MONO_WRAPPER_LDFLDA:
8588 case MONO_WRAPPER_STFLD: {
8589 g_assert (info);
8590 success = success && append_mangled_klass (s, info->d.proxy.klass);
8591 break;
8593 case MONO_WRAPPER_ALLOC: {
8594 /* The GC name is saved once in MonoAotFileInfo */
8595 g_assert (info->d.alloc.alloc_type != -1);
8596 g_string_append_printf (s, "%d_", info->d.alloc.alloc_type);
8597 // SlowAlloc, etc
8598 g_string_append_printf (s, "%s_", method->name);
8599 break;
8601 case MONO_WRAPPER_WRITE_BARRIER: {
8602 g_string_append_printf (s, "%s_", method->name);
8603 break;
8605 case MONO_WRAPPER_STELEMREF: {
8606 append_mangled_wrapper_subtype (s, info->subtype);
8607 if (info->subtype == WRAPPER_SUBTYPE_VIRTUAL_STELEMREF)
8608 g_string_append_printf (s, "%d", info->d.virtual_stelemref.kind);
8609 break;
8611 case MONO_WRAPPER_UNKNOWN: {
8612 append_mangled_wrapper_subtype (s, info->subtype);
8613 if (info->subtype == WRAPPER_SUBTYPE_PTR_TO_STRUCTURE ||
8614 info->subtype == WRAPPER_SUBTYPE_STRUCTURE_TO_PTR)
8615 success = success && append_mangled_klass (s, method->klass);
8616 else if (info->subtype == WRAPPER_SUBTYPE_SYNCHRONIZED_INNER)
8617 success = success && append_mangled_method (s, info->d.synchronized_inner.method);
8618 else if (info->subtype == WRAPPER_SUBTYPE_ARRAY_ACCESSOR)
8619 success = success && append_mangled_method (s, info->d.array_accessor.method);
8620 else if (info->subtype == WRAPPER_SUBTYPE_INTERP_IN)
8621 append_mangled_signature (s, info->d.interp_in.sig);
8622 else if (info->subtype == WRAPPER_SUBTYPE_GSHAREDVT_IN_SIG)
8623 append_mangled_signature (s, info->d.gsharedvt.sig);
8624 else if (info->subtype == WRAPPER_SUBTYPE_GSHAREDVT_OUT_SIG)
8625 append_mangled_signature (s, info->d.gsharedvt.sig);
8626 break;
8628 case MONO_WRAPPER_MANAGED_TO_NATIVE: {
8629 append_mangled_wrapper_subtype (s, info->subtype);
8630 if (info->subtype == WRAPPER_SUBTYPE_ICALL_WRAPPER) {
8631 g_string_append_printf (s, "%s", method->name);
8632 } else if (info->subtype == WRAPPER_SUBTYPE_NATIVE_FUNC_AOT) {
8633 success = success && append_mangled_method (s, info->d.managed_to_native.method);
8634 } else {
8635 g_assert (info->subtype == WRAPPER_SUBTYPE_NONE || info->subtype == WRAPPER_SUBTYPE_PINVOKE);
8636 success = success && append_mangled_method (s, info->d.managed_to_native.method);
8638 break;
8640 case MONO_WRAPPER_SYNCHRONIZED: {
8641 MonoMethod *m;
8643 m = mono_marshal_method_from_wrapper (method);
8644 g_assert (m);
8645 g_assert (m != method);
8646 success = success && append_mangled_method (s, m);
8647 break;
8649 case MONO_WRAPPER_MANAGED_TO_MANAGED: {
8650 append_mangled_wrapper_subtype (s, info->subtype);
8652 if (info->subtype == WRAPPER_SUBTYPE_ELEMENT_ADDR) {
8653 g_string_append_printf (s, "%d_", info->d.element_addr.rank);
8654 g_string_append_printf (s, "%d_", info->d.element_addr.elem_size);
8655 } else if (info->subtype == WRAPPER_SUBTYPE_STRING_CTOR) {
8656 success = success && append_mangled_method (s, info->d.string_ctor.method);
8657 } else if (info->subtype == WRAPPER_SUBTYPE_GENERIC_ARRAY_HELPER) {
8658 success = success && append_mangled_method (s, info->d.generic_array_helper.method);
8659 } else {
8660 success = FALSE;
8662 break;
8664 case MONO_WRAPPER_CASTCLASS: {
8665 append_mangled_wrapper_subtype (s, info->subtype);
8666 break;
8668 case MONO_WRAPPER_RUNTIME_INVOKE: {
8669 append_mangled_wrapper_subtype (s, info->subtype);
8670 if (info->subtype == WRAPPER_SUBTYPE_RUNTIME_INVOKE_DIRECT || info->subtype == WRAPPER_SUBTYPE_RUNTIME_INVOKE_VIRTUAL)
8671 success = success && append_mangled_method (s, info->d.runtime_invoke.method);
8672 else if (info->subtype == WRAPPER_SUBTYPE_RUNTIME_INVOKE_NORMAL)
8673 success = success && append_mangled_signature (s, info->d.runtime_invoke.sig);
8674 break;
8676 case MONO_WRAPPER_DELEGATE_INVOKE:
8677 case MONO_WRAPPER_DELEGATE_BEGIN_INVOKE:
8678 case MONO_WRAPPER_DELEGATE_END_INVOKE: {
8679 if (method->is_inflated) {
8680 /* These wrappers are identified by their class */
8681 g_string_append_printf (s, "i_");
8682 success = success && append_mangled_klass (s, method->klass);
8683 } else {
8684 WrapperInfo *info = mono_marshal_get_wrapper_info (method);
8686 g_string_append_printf (s, "u_");
8687 if (method->wrapper_type == MONO_WRAPPER_DELEGATE_INVOKE)
8688 append_mangled_wrapper_subtype (s, info->subtype);
8689 g_string_append_printf (s, "u_sigstart");
8691 break;
8693 case MONO_WRAPPER_NATIVE_TO_MANAGED: {
8694 g_assert (info);
8695 success = success && append_mangled_method (s, info->d.native_to_managed.method);
8696 success = success && append_mangled_klass (s, method->klass);
8697 break;
8699 default:
8700 g_assert_not_reached ();
8702 return success && append_mangled_signature (s, mono_method_signature (method));
8705 static void
8706 append_mangled_ginst (GString *str, MonoGenericInst *ginst)
8708 int i;
8710 for (i = 0; i < ginst->type_argc; ++i) {
8711 if (i > 0)
8712 g_string_append (str, ", ");
8713 MonoType *type = ginst->type_argv [i];
8714 switch (type->type) {
8715 case MONO_TYPE_VAR:
8716 case MONO_TYPE_MVAR: {
8717 MonoType *constraint = NULL;
8718 if (type->data.generic_param)
8719 constraint = type->data.generic_param->gshared_constraint;
8720 if (constraint) {
8721 g_assert (constraint->type != MONO_TYPE_VAR && constraint->type != MONO_TYPE_MVAR);
8722 g_string_append (str, "gshared:");
8723 mono_type_get_desc (str, constraint, TRUE);
8724 break;
8726 // Else falls through to common case
8728 default:
8729 mono_type_get_desc (str, type, TRUE);
8734 static void
8735 append_mangled_context (GString *str, MonoGenericContext *context)
8737 GString *res = g_string_new ("");
8739 g_string_append_printf (res, "gens_");
8740 g_string_append (res, "00");
8742 gboolean good = context->class_inst && context->class_inst->type_argc > 0;
8743 good = good || (context->method_inst && context->method_inst->type_argc > 0);
8744 g_assert (good);
8746 if (context->class_inst)
8747 append_mangled_ginst (res, context->class_inst);
8748 if (context->method_inst) {
8749 if (context->class_inst)
8750 g_string_append (res, "11");
8751 append_mangled_ginst (res, context->method_inst);
8753 g_string_append_printf (str, "gens_%s", res->str);
8754 g_free (res);
8757 static gboolean
8758 append_mangled_method (GString *s, MonoMethod *method)
8760 if (method->wrapper_type)
8761 return append_mangled_wrapper (s, method);
8763 if (method->is_inflated) {
8764 g_string_append_printf (s, "inflated_");
8765 MonoMethodInflated *imethod = (MonoMethodInflated*) method;
8766 g_assert (imethod->context.class_inst != NULL || imethod->context.method_inst != NULL);
8768 append_mangled_context (s, &imethod->context);
8769 g_string_append_printf (s, "_declared_by_");
8770 append_mangled_method (s, imethod->declaring);
8771 } else if (method->is_generic) {
8772 g_string_append_printf (s, "%s_", m_class_get_image (method->klass)->assembly->aname.name);
8774 g_string_append_printf (s, "generic_");
8775 append_mangled_klass (s, method->klass);
8776 g_string_append_printf (s, "_%s_", method->name);
8778 MonoGenericContainer *container = mono_method_get_generic_container (method);
8779 g_string_append_printf (s, "_%s");
8780 append_mangled_context (s, &container->context);
8782 return append_mangled_signature (s, mono_method_signature (method));
8783 } else {
8784 g_string_append_printf (s, "_");
8785 append_mangled_klass (s, method->klass);
8786 g_string_append_printf (s, "_%s_", method->name);
8787 if (!append_mangled_signature (s, mono_method_signature (method))) {
8788 g_string_free (s, TRUE);
8789 return FALSE;
8793 return TRUE;
8797 * mono_aot_get_mangled_method_name:
8799 * Return a unique mangled name for METHOD, or NULL.
8801 char*
8802 mono_aot_get_mangled_method_name (MonoMethod *method)
8804 // FIXME: use static cache (mempool?)
8805 // We call this a *lot*
8807 GString *s = g_string_new ("aot_");
8808 if (!append_mangled_method (s, method)) {
8809 g_string_free (s, TRUE);
8810 return NULL;
8811 } else {
8812 char *out = g_string_free (s, FALSE);
8813 // Scrub method and class names
8814 char *cleaned = sanitize_mangled_string (out);
8815 g_free (out);
8816 return cleaned;
8820 gboolean
8821 mono_aot_is_direct_callable (MonoJumpInfo *patch_info)
8823 return is_direct_callable (llvm_acfg, NULL, patch_info);
8826 void
8827 mono_aot_mark_unused_llvm_plt_entry (MonoJumpInfo *patch_info)
8829 MonoPltEntry *plt_entry;
8831 plt_entry = get_plt_entry (llvm_acfg, patch_info);
8832 plt_entry->llvm_used = FALSE;
8835 char*
8836 mono_aot_get_direct_call_symbol (MonoJumpInfoType type, gconstpointer data)
8838 const char *sym = NULL;
8840 if (llvm_acfg->aot_opts.direct_icalls) {
8841 if (type == MONO_PATCH_INFO_JIT_ICALL_ADDR) {
8842 /* Call to a C function implementing a jit icall */
8843 sym = mono_lookup_jit_icall_symbol ((const char *)data);
8844 } else if (type == MONO_PATCH_INFO_ICALL_ADDR_CALL) {
8845 MonoMethod *method = (MonoMethod *)data;
8846 if (!(method->flags & METHOD_ATTRIBUTE_PINVOKE_IMPL))
8847 sym = mono_lookup_icall_symbol (method);
8848 else if (llvm_acfg->aot_opts.direct_pinvoke)
8849 sym = get_pinvoke_import (llvm_acfg, method);
8851 if (sym)
8852 return g_strdup (sym);
8854 return NULL;
8857 char*
8858 mono_aot_get_plt_symbol (MonoJumpInfoType type, gconstpointer data)
8860 MonoJumpInfo *ji = (MonoJumpInfo *)mono_mempool_alloc (llvm_acfg->mempool, sizeof (MonoJumpInfo));
8861 MonoPltEntry *plt_entry;
8862 const char *sym = NULL;
8864 ji->type = type;
8865 ji->data.target = data;
8867 if (!can_encode_patch (llvm_acfg, ji))
8868 return NULL;
8870 if (llvm_acfg->aot_opts.direct_icalls) {
8871 if (type == MONO_PATCH_INFO_JIT_ICALL_ADDR) {
8872 /* Call to a C function implementing a jit icall */
8873 sym = mono_lookup_jit_icall_symbol ((const char *)data);
8874 } else if (type == MONO_PATCH_INFO_ICALL_ADDR_CALL) {
8875 MonoMethod *method = (MonoMethod *)data;
8876 if (!(method->flags & METHOD_ATTRIBUTE_PINVOKE_IMPL))
8877 sym = mono_lookup_icall_symbol (method);
8879 if (sym)
8880 return g_strdup (sym);
8883 plt_entry = get_plt_entry (llvm_acfg, ji);
8884 plt_entry->llvm_used = TRUE;
8886 #if defined(TARGET_MACH)
8887 return g_strdup_printf (plt_entry->llvm_symbol + strlen (llvm_acfg->llvm_label_prefix));
8888 #else
8889 return g_strdup_printf (plt_entry->llvm_symbol);
8890 #endif
8894 mono_aot_get_method_index (MonoMethod *method)
8896 g_assert (llvm_acfg);
8897 return get_method_index (llvm_acfg, method);
8900 MonoJumpInfo*
8901 mono_aot_patch_info_dup (MonoJumpInfo* ji)
8903 MonoJumpInfo *res;
8905 mono_acfg_lock (llvm_acfg);
8906 res = mono_patch_info_dup_mp (llvm_acfg->mempool, ji);
8907 mono_acfg_unlock (llvm_acfg);
8909 return res;
8912 static int
8913 execute_system (const char * command)
8915 int status = 0;
8917 #if G_HAVE_API_SUPPORT(HAVE_CLASSIC_WINAPI_SUPPORT) && defined(HOST_WIN32)
8918 // We need an extra set of quotes around the whole command to properly handle commands
8919 // with spaces since internally the command is called through "cmd /c.
8920 char * quoted_command = g_strdup_printf ("\"%s\"", command);
8922 int size = MultiByteToWideChar (CP_UTF8, 0 , quoted_command , -1, NULL , 0);
8923 wchar_t* wstr = g_malloc (sizeof (wchar_t) * size);
8924 MultiByteToWideChar (CP_UTF8, 0, quoted_command, -1, wstr , size);
8925 status = _wsystem (wstr);
8926 g_free (wstr);
8928 g_free (quoted_command);
8929 #elif defined (HAVE_SYSTEM)
8930 status = system (command);
8931 #else
8932 g_assert_not_reached ();
8933 #endif
8935 return status;
8938 #ifdef ENABLE_LLVM
8941 * emit_llvm_file:
8943 * Emit the LLVM code into an LLVM bytecode file, and compile it using the LLVM
8944 * tools.
8946 static gboolean
8947 emit_llvm_file (MonoAotCompile *acfg)
8949 char *command, *opts, *tempbc, *optbc, *output_fname;
8951 if (acfg->aot_opts.llvm_only && acfg->aot_opts.asm_only) {
8952 tempbc = g_strdup_printf ("%s.bc", acfg->tmpbasename);
8953 optbc = g_strdup (acfg->aot_opts.llvm_outfile);
8954 } else {
8955 tempbc = g_strdup_printf ("%s.bc", acfg->tmpbasename);
8956 optbc = g_strdup_printf ("%s.opt.bc", acfg->tmpbasename);
8959 mono_llvm_emit_aot_module (tempbc, g_path_get_basename (acfg->image->name));
8962 * FIXME: Experiment with adding optimizations, the -std-compile-opts set takes
8963 * a lot of time, and doesn't seem to save much space.
8964 * The following optimizations cannot be enabled:
8965 * - 'tailcallelim'
8966 * - 'jump-threading' changes our blockaddress references to int constants.
8967 * - 'basiccg' fails because it contains:
8968 * if (CS && !isa<IntrinsicInst>(II)) {
8969 * and isa<IntrinsicInst> is false for invokes to intrinsics (iltests.exe).
8970 * - 'prune-eh' and 'functionattrs' depend on 'basiccg'.
8971 * The opt list below was produced by taking the output of:
8972 * llvm-as < /dev/null | opt -O2 -disable-output -debug-pass=Arguments
8973 * then removing tailcallelim + the global opts.
8974 * strip-dead-prototypes deletes unused intrinsics definitions.
8976 /* The dse pass is disabled because of #13734 and #17616 */
8978 * The dse bug is in DeadStoreElimination.cpp:isOverwrite ():
8979 * // If we have no DataLayout information around, then the size of the store
8980 * // is inferrable from the pointee type. If they are the same type, then
8981 * // we know that the store is safe.
8982 * if (AA.getDataLayout() == 0 &&
8983 * Later.Ptr->getType() == Earlier.Ptr->getType()) {
8984 * return OverwriteComplete;
8985 * Here, if 'Earlier' refers to a memset, and Later has no size info, it mistakenly thinks the memset is redundant.
8987 if (acfg->aot_opts.llvm_only)
8988 // FIXME: This doesn't work yet
8989 opts = g_strdup ("");
8990 else
8991 #if LLVM_API_VERSION > 100
8992 opts = g_strdup ("-O2 -disable-tail-calls");
8993 #else
8994 opts = g_strdup ("-targetlibinfo -no-aa -basicaa -notti -instcombine -simplifycfg -inline-cost -inline -sroa -domtree -early-cse -lazy-value-info -correlated-propagation -simplifycfg -instcombine -simplifycfg -reassociate -domtree -loops -loop-simplify -lcssa -loop-rotate -licm -lcssa -loop-unswitch -instcombine -scalar-evolution -loop-simplify -lcssa -indvars -loop-idiom -loop-deletion -loop-unroll -memdep -gvn -memdep -memcpyopt -sccp -instcombine -lazy-value-info -correlated-propagation -domtree -memdep -adce -simplifycfg -instcombine -strip-dead-prototypes -domtree -verify");
8995 #endif
8996 command = g_strdup_printf ("\"%sopt\" -f %s -o \"%s\" \"%s\"", acfg->aot_opts.llvm_path, opts, optbc, tempbc);
8997 aot_printf (acfg, "Executing opt: %s\n", command);
8998 if (execute_system (command) != 0)
8999 return FALSE;
9000 g_free (opts);
9002 if (acfg->aot_opts.llvm_only && acfg->aot_opts.asm_only)
9003 /* Nothing else to do */
9004 return TRUE;
9006 if (acfg->aot_opts.llvm_only) {
9007 /* Use the stock clang from xcode */
9008 // FIXME: arch
9009 command = g_strdup_printf ("clang++ -fexceptions -march=x86-64 -fpic -msse -msse2 -msse3 -msse4 -O2 -fno-optimize-sibling-calls -Wno-override-module -c -o \"%s\" \"%s.opt.bc\"", acfg->llvm_ofile, acfg->tmpbasename);
9011 aot_printf (acfg, "Executing clang: %s\n", command);
9012 if (execute_system (command) != 0)
9013 return FALSE;
9014 return TRUE;
9017 if (!acfg->llc_args)
9018 acfg->llc_args = g_string_new ("");
9020 /* Verbose asm slows down llc greatly */
9021 g_string_append (acfg->llc_args, " -asm-verbose=false");
9023 if (acfg->aot_opts.mtriple)
9024 g_string_append_printf (acfg->llc_args, " -mtriple=%s", acfg->aot_opts.mtriple);
9026 g_string_append (acfg->llc_args, " -disable-gnu-eh-frame -enable-mono-eh-frame");
9028 g_string_append_printf (acfg->llc_args, " -mono-eh-frame-symbol=%s%s", acfg->user_symbol_prefix, acfg->llvm_eh_frame_symbol);
9030 #if LLVM_API_VERSION > 100
9031 g_string_append_printf (acfg->llc_args, " -disable-tail-calls");
9032 #endif
9034 #if ( defined(TARGET_MACH) && defined(TARGET_ARM) ) || defined(TARGET_ORBIS)
9035 /* ios requires PIC code now */
9036 g_string_append_printf (acfg->llc_args, " -relocation-model=pic");
9037 #else
9038 if (llvm_acfg->aot_opts.static_link)
9039 g_string_append_printf (acfg->llc_args, " -relocation-model=static");
9040 else
9041 g_string_append_printf (acfg->llc_args, " -relocation-model=pic");
9042 #endif
9044 if (acfg->llvm_owriter) {
9045 /* Emit an object file directly */
9046 output_fname = g_strdup_printf ("%s", acfg->llvm_ofile);
9047 g_string_append_printf (acfg->llc_args, " -filetype=obj");
9048 } else {
9049 output_fname = g_strdup_printf ("%s", acfg->llvm_sfile);
9051 command = g_strdup_printf ("\"%sllc\" %s -o \"%s\" \"%s.opt.bc\"", acfg->aot_opts.llvm_path, acfg->llc_args->str, output_fname, acfg->tmpbasename);
9052 g_free (output_fname);
9054 aot_printf (acfg, "Executing llc: %s\n", command);
9056 if (execute_system (command) != 0)
9057 return FALSE;
9058 return TRUE;
9060 #endif
9062 static void
9063 emit_code (MonoAotCompile *acfg)
9065 int oindex, i, prev_index;
9066 gboolean saved_unbox_info = FALSE;
9067 char symbol [MAX_SYMBOL_SIZE];
9069 if (acfg->aot_opts.llvm_only)
9070 return;
9072 #if defined(TARGET_POWERPC64)
9073 sprintf (symbol, ".Lgot_addr");
9074 emit_section_change (acfg, ".text", 0);
9075 emit_alignment (acfg, 8);
9076 emit_label (acfg, symbol);
9077 emit_pointer (acfg, acfg->got_symbol);
9078 #endif
9081 * This global symbol is used to compute the address of each method using the
9082 * code_offsets array. It is also used to compute the memory ranges occupied by
9083 * AOT code, so it must be equal to the address of the first emitted method.
9085 emit_section_change (acfg, ".text", 0);
9086 emit_alignment_code (acfg, 8);
9087 emit_info_symbol (acfg, "jit_code_start");
9090 * Emit some padding so the local symbol for the first method doesn't have the
9091 * same address as 'methods'.
9093 emit_padding (acfg, 16);
9095 for (oindex = 0; oindex < acfg->method_order->len; ++oindex) {
9096 MonoCompile *cfg;
9097 MonoMethod *method;
9099 i = GPOINTER_TO_UINT (g_ptr_array_index (acfg->method_order, oindex));
9101 cfg = acfg->cfgs [i];
9103 if (!cfg)
9104 continue;
9106 method = cfg->orig_method;
9108 gboolean dedup_collect = acfg->aot_opts.dedup || (acfg->aot_opts.dedup_include && !acfg->dedup_emit_mode);
9109 gboolean dedupable = mono_aot_can_dedup (method);
9111 // cfg->skip is vital for LLVM to work, can't just continue in this loop
9112 if (dedupable && strcmp (method->name, "wbarrier_conc") && dedup_collect) {
9113 mono_dedup_cache_method (acfg, method);
9115 // Don't compile inflated methods if we're in first phase of
9116 // dedup
9118 // In second phase, we emit methods that
9119 // are dedupable. We also emit later methods
9120 // which are referenced by them and added later.
9121 // For this reason, when in the dedup_include mode,
9122 // we never set skip.
9123 if (acfg->aot_opts.dedup)
9124 cfg->skip = TRUE;
9127 // Don't compile anything in this mode
9128 if (acfg->aot_opts.dedup_include && !acfg->dedup_emit_mode)
9129 cfg->skip = TRUE;
9131 // Compile everything in this mode
9132 if (acfg->aot_opts.dedup_include && acfg->dedup_emit_mode)
9133 cfg->skip = FALSE;
9135 /*if (dedup_collect) {*/
9136 /*char *name = mono_aot_get_mangled_method_name (method);*/
9138 /*if (ignore_cfg (cfg))*/
9139 /*aot_printf (acfg, "Dedup Skipping %s\n", acfg->image->name, name);*/
9140 /*else*/
9141 /*aot_printf (acfg, "Dedup Keeping %s\n", acfg->image->name, name);*/
9143 /*g_free (name);*/
9144 /*}*/
9146 if (ignore_cfg (cfg))
9147 continue;
9149 /* Emit unbox trampoline */
9150 if (mono_aot_mode_is_full (&acfg->aot_opts) && m_class_is_valuetype (cfg->orig_method->klass)) {
9151 sprintf (symbol, "ut_%d", get_method_index (acfg, method));
9153 emit_section_change (acfg, ".text", 0);
9155 if (acfg->thumb_mixed && cfg->compile_llvm) {
9156 emit_set_thumb_mode (acfg);
9157 fprintf (acfg->fp, "\n.thumb_func\n");
9160 emit_label (acfg, symbol);
9162 arch_emit_unbox_trampoline (acfg, cfg, cfg->orig_method, cfg->asm_symbol);
9164 if (acfg->thumb_mixed && cfg->compile_llvm)
9165 emit_set_arm_mode (acfg);
9167 if (!saved_unbox_info) {
9168 char user_symbol [128];
9169 GSList *unwind_ops;
9170 sprintf (user_symbol, "%sunbox_trampoline_p", acfg->user_symbol_prefix);
9172 emit_label (acfg, "ut_end");
9174 unwind_ops = mono_unwind_get_cie_program ();
9175 save_unwind_info (acfg, user_symbol, unwind_ops);
9176 mono_free_unwind_info (unwind_ops);
9178 /* Save the unbox trampoline size */
9179 emit_symbol_diff (acfg, "ut_end", symbol, 0);
9181 saved_unbox_info = TRUE;
9185 if (cfg->compile_llvm) {
9186 acfg->stats.llvm_count ++;
9187 } else {
9188 emit_method_code (acfg, cfg);
9192 emit_section_change (acfg, ".text", 0);
9193 emit_alignment_code (acfg, 8);
9194 emit_info_symbol (acfg, "jit_code_end");
9196 /* To distinguish it from the next symbol */
9197 emit_padding (acfg, 4);
9200 * Add .no_dead_strip directives for all LLVM methods to prevent the OSX linker
9201 * from optimizing them away, since it doesn't see that code_offsets references them.
9202 * JITted methods don't need this since they are referenced using assembler local
9203 * symbols.
9204 * FIXME: This is why write-symbols doesn't work on OSX ?
9206 if (acfg->llvm && acfg->need_no_dead_strip) {
9207 fprintf (acfg->fp, "\n");
9208 for (i = 0; i < acfg->nmethods; ++i) {
9209 if (acfg->cfgs [i] && acfg->cfgs [i]->compile_llvm)
9210 fprintf (acfg->fp, ".no_dead_strip %s\n", acfg->cfgs [i]->asm_symbol);
9215 * To work around linker issues, we emit a table of branches, and disassemble them at runtime.
9216 * This is PIE code, and the linker can update it if needed.
9219 sprintf (symbol, "method_addresses");
9220 emit_section_change (acfg, ".text", 1);
9221 emit_alignment_code (acfg, 8);
9222 emit_info_symbol (acfg, symbol);
9223 if (acfg->aot_opts.write_symbols)
9224 emit_local_symbol (acfg, symbol, "method_addresses_end", TRUE);
9225 emit_unset_mode (acfg);
9226 if (acfg->need_no_dead_strip)
9227 fprintf (acfg->fp, " .no_dead_strip %s\n", symbol);
9229 for (i = 0; i < acfg->nmethods; ++i) {
9230 #ifdef MONO_ARCH_AOT_SUPPORTED
9231 int call_size;
9233 if (!ignore_cfg (acfg->cfgs [i])) {
9234 arch_emit_direct_call (acfg, acfg->cfgs [i]->asm_symbol, FALSE, acfg->thumb_mixed && acfg->cfgs [i]->compile_llvm, NULL, &call_size);
9235 } else {
9236 arch_emit_direct_call (acfg, symbol, FALSE, FALSE, NULL, &call_size);
9238 #endif
9241 sprintf (symbol, "method_addresses_end");
9242 emit_label (acfg, symbol);
9243 emit_line (acfg);
9245 /* Emit a sorted table mapping methods to the index of their unbox trampolines */
9246 sprintf (symbol, "unbox_trampolines");
9247 emit_section_change (acfg, RODATA_SECT, 0);
9248 emit_alignment (acfg, 8);
9249 emit_info_symbol (acfg, symbol);
9251 prev_index = -1;
9252 for (i = 0; i < acfg->nmethods; ++i) {
9253 MonoCompile *cfg;
9254 MonoMethod *method;
9255 int index;
9257 cfg = acfg->cfgs [i];
9258 if (ignore_cfg (cfg))
9259 continue;
9261 method = cfg->orig_method;
9263 if (mono_aot_mode_is_full (&acfg->aot_opts) && m_class_is_valuetype (cfg->orig_method->klass)) {
9264 index = get_method_index (acfg, method);
9266 emit_int32 (acfg, index);
9267 /* Make sure the table is sorted by index */
9268 g_assert (index > prev_index);
9269 prev_index = index;
9272 sprintf (symbol, "unbox_trampolines_end");
9273 emit_info_symbol (acfg, symbol);
9274 emit_int32 (acfg, 0);
9276 /* Emit a separate table with the trampoline addresses/offsets */
9277 sprintf (symbol, "unbox_trampoline_addresses");
9278 emit_section_change (acfg, ".text", 0);
9279 emit_alignment_code (acfg, 8);
9280 emit_info_symbol (acfg, symbol);
9282 for (i = 0; i < acfg->nmethods; ++i) {
9283 MonoCompile *cfg;
9284 MonoMethod *method;
9285 int index;
9287 cfg = acfg->cfgs [i];
9288 if (ignore_cfg (cfg))
9289 continue;
9291 method = cfg->orig_method;
9293 if (mono_aot_mode_is_full (&acfg->aot_opts) && m_class_is_valuetype (cfg->orig_method->klass)) {
9294 #ifdef MONO_ARCH_AOT_SUPPORTED
9295 int call_size;
9297 index = get_method_index (acfg, method);
9298 sprintf (symbol, "ut_%d", index);
9300 arch_emit_direct_call (acfg, symbol, FALSE, acfg->thumb_mixed && cfg->compile_llvm, NULL, &call_size);
9301 #endif
9304 emit_int32 (acfg, 0);
9307 static void
9308 emit_info (MonoAotCompile *acfg)
9310 int oindex, i;
9311 gint32 *offsets;
9313 offsets = g_new0 (gint32, acfg->nmethods);
9315 for (oindex = 0; oindex < acfg->method_order->len; ++oindex) {
9316 i = GPOINTER_TO_UINT (g_ptr_array_index (acfg->method_order, oindex));
9318 if (acfg->cfgs [i]) {
9319 emit_method_info (acfg, acfg->cfgs [i]);
9320 offsets [i] = acfg->cfgs [i]->method_info_offset;
9321 } else {
9322 offsets [i] = 0;
9326 acfg->stats.offsets_size += emit_offset_table (acfg, "method_info_offsets", MONO_AOT_TABLE_METHOD_INFO_OFFSETS, acfg->nmethods, 10, offsets);
9328 g_free (offsets);
9331 #endif /* #if !defined(DISABLE_AOT) && !defined(DISABLE_JIT) */
9333 #define rot(x,k) (((x)<<(k)) | ((x)>>(32-(k))))
9334 #define mix(a,b,c) { \
9335 a -= c; a ^= rot(c, 4); c += b; \
9336 b -= a; b ^= rot(a, 6); a += c; \
9337 c -= b; c ^= rot(b, 8); b += a; \
9338 a -= c; a ^= rot(c,16); c += b; \
9339 b -= a; b ^= rot(a,19); a += c; \
9340 c -= b; c ^= rot(b, 4); b += a; \
9342 #define final(a,b,c) { \
9343 c ^= b; c -= rot(b,14); \
9344 a ^= c; a -= rot(c,11); \
9345 b ^= a; b -= rot(a,25); \
9346 c ^= b; c -= rot(b,16); \
9347 a ^= c; a -= rot(c,4); \
9348 b ^= a; b -= rot(a,14); \
9349 c ^= b; c -= rot(b,24); \
9352 static guint
9353 mono_aot_type_hash (MonoType *t1)
9355 guint hash = t1->type;
9357 hash |= t1->byref << 6; /* do not collide with t1->type values */
9358 switch (t1->type) {
9359 case MONO_TYPE_VALUETYPE:
9360 case MONO_TYPE_CLASS:
9361 case MONO_TYPE_SZARRAY:
9362 /* check if the distribution is good enough */
9363 return ((hash << 5) - hash) ^ mono_metadata_str_hash (m_class_get_name (t1->data.klass));
9364 case MONO_TYPE_PTR:
9365 return ((hash << 5) - hash) ^ mono_metadata_type_hash (t1->data.type);
9366 case MONO_TYPE_ARRAY:
9367 return ((hash << 5) - hash) ^ mono_metadata_type_hash (m_class_get_byval_arg (t1->data.array->eklass));
9368 case MONO_TYPE_GENERICINST:
9369 return ((hash << 5) - hash) ^ 0;
9370 default:
9371 return hash;
9376 * mono_aot_method_hash:
9378 * Return a hash code for methods which only depends on metadata.
9380 guint32
9381 mono_aot_method_hash (MonoMethod *method)
9383 MonoMethodSignature *sig;
9384 MonoClass *klass;
9385 int i, hindex;
9386 int hashes_count;
9387 guint32 *hashes_start, *hashes;
9388 guint32 a, b, c;
9389 MonoGenericInst *class_ginst = NULL;
9390 MonoGenericInst *ginst = NULL;
9392 /* Similar to the hash in mono_method_get_imt_slot () */
9394 sig = mono_method_signature (method);
9396 if (mono_class_is_ginst (method->klass))
9397 class_ginst = mono_class_get_generic_class (method->klass)->context.class_inst;
9398 if (method->is_inflated)
9399 ginst = ((MonoMethodInflated*)method)->context.method_inst;
9401 hashes_count = sig->param_count + 5 + (class_ginst ? class_ginst->type_argc : 0) + (ginst ? ginst->type_argc : 0);
9402 hashes_start = (guint32 *)g_malloc0 (hashes_count * sizeof (guint32));
9403 hashes = hashes_start;
9405 /* Some wrappers are assigned to random classes */
9406 if (!method->wrapper_type || method->wrapper_type == MONO_WRAPPER_REMOTING_INVOKE_WITH_CHECK)
9407 klass = method->klass;
9408 else
9409 klass = mono_defaults.object_class;
9411 if (!method->wrapper_type) {
9412 char *full_name;
9414 if (mono_class_is_ginst (klass))
9415 full_name = mono_type_full_name (m_class_get_byval_arg (mono_class_get_generic_class (klass)->container_class));
9416 else
9417 full_name = mono_type_full_name (m_class_get_byval_arg (klass));
9419 hashes [0] = mono_metadata_str_hash (full_name);
9420 hashes [1] = 0;
9421 g_free (full_name);
9422 } else {
9423 hashes [0] = mono_metadata_str_hash (m_class_get_name (klass));
9424 hashes [1] = mono_metadata_str_hash (m_class_get_name_space (klass));
9426 if (method->wrapper_type == MONO_WRAPPER_STFLD || method->wrapper_type == MONO_WRAPPER_LDFLD || method->wrapper_type == MONO_WRAPPER_LDFLDA)
9427 /* The method name includes a stringified pointer */
9428 hashes [2] = 0;
9429 else
9430 hashes [2] = mono_metadata_str_hash (method->name);
9431 hashes [3] = method->wrapper_type;
9432 hashes [4] = mono_aot_type_hash (sig->ret);
9433 hindex = 5;
9434 for (i = 0; i < sig->param_count; i++) {
9435 hashes [hindex ++] = mono_aot_type_hash (sig->params [i]);
9437 if (class_ginst) {
9438 for (i = 0; i < class_ginst->type_argc; ++i)
9439 hashes [hindex ++] = mono_aot_type_hash (class_ginst->type_argv [i]);
9441 if (ginst) {
9442 for (i = 0; i < ginst->type_argc; ++i)
9443 hashes [hindex ++] = mono_aot_type_hash (ginst->type_argv [i]);
9445 g_assert (hindex == hashes_count);
9447 /* Setup internal state */
9448 a = b = c = 0xdeadbeef + (((guint32)hashes_count)<<2);
9450 /* Handle most of the hashes */
9451 while (hashes_count > 3) {
9452 a += hashes [0];
9453 b += hashes [1];
9454 c += hashes [2];
9455 mix (a,b,c);
9456 hashes_count -= 3;
9457 hashes += 3;
9460 /* Handle the last 3 hashes (all the case statements fall through) */
9461 switch (hashes_count) {
9462 case 3 : c += hashes [2];
9463 case 2 : b += hashes [1];
9464 case 1 : a += hashes [0];
9465 final (a,b,c);
9466 case 0: /* nothing left to add */
9467 break;
9470 g_free (hashes_start);
9472 return c;
9474 #undef rot
9475 #undef mix
9476 #undef final
9479 * mono_aot_get_array_helper_from_wrapper;
9481 * Get the helper method in Array called by an array wrapper method.
9483 MonoMethod*
9484 mono_aot_get_array_helper_from_wrapper (MonoMethod *method)
9486 MonoMethod *m;
9487 const char *prefix;
9488 MonoGenericContext ctx;
9489 MonoType *args [16];
9490 char *mname, *iname, *s, *s2, *helper_name = NULL;
9492 prefix = "System.Collections.Generic";
9493 s = g_strdup_printf ("%s", method->name + strlen (prefix) + 1);
9494 s2 = strstr (s, "`1.");
9495 g_assert (s2);
9496 s2 [0] = '\0';
9497 iname = s;
9498 mname = s2 + 3;
9500 //printf ("X: %s %s\n", iname, mname);
9502 if (!strcmp (iname, "IList"))
9503 helper_name = g_strdup_printf ("InternalArray__%s", mname);
9504 else
9505 helper_name = g_strdup_printf ("InternalArray__%s_%s", iname, mname);
9506 m = mono_class_get_method_from_name (mono_defaults.array_class, helper_name, mono_method_signature (method)->param_count);
9507 g_assert (m);
9508 g_free (helper_name);
9509 g_free (s);
9511 if (m->is_generic) {
9512 ERROR_DECL (error);
9513 memset (&ctx, 0, sizeof (ctx));
9514 args [0] = m_class_get_byval_arg (m_class_get_element_class (method->klass));
9515 ctx.method_inst = mono_metadata_get_generic_inst (1, args);
9516 m = mono_class_inflate_generic_method_checked (m, &ctx, error);
9517 g_assert (mono_error_ok (error)); /* FIXME don't swallow the error */
9520 return m;
9523 #if !defined(DISABLE_AOT) && !defined(DISABLE_JIT)
9525 typedef struct HashEntry {
9526 guint32 key, value, index;
9527 struct HashEntry *next;
9528 } HashEntry;
9531 * emit_extra_methods:
9533 * Emit methods which are not in the METHOD table, like wrappers.
9535 static void
9536 emit_extra_methods (MonoAotCompile *acfg)
9538 int i, table_size, buf_size;
9539 guint8 *p, *buf;
9540 guint32 *info_offsets;
9541 guint32 hash;
9542 GPtrArray *table;
9543 HashEntry *entry, *new_entry;
9544 int nmethods, max_chain_length;
9545 int *chain_lengths;
9547 info_offsets = g_new0 (guint32, acfg->extra_methods->len);
9549 /* Emit method info */
9550 nmethods = 0;
9551 for (i = 0; i < acfg->extra_methods->len; ++i) {
9552 MonoMethod *method = (MonoMethod *)g_ptr_array_index (acfg->extra_methods, i);
9553 MonoCompile *cfg = (MonoCompile *)g_hash_table_lookup (acfg->method_to_cfg, method);
9555 if (ignore_cfg (cfg))
9556 continue;
9558 buf_size = 10240;
9559 p = buf = (guint8 *)g_malloc (buf_size);
9561 nmethods ++;
9563 method = cfg->method_to_register;
9565 encode_method_ref (acfg, method, p, &p);
9567 g_assert ((p - buf) < buf_size);
9569 info_offsets [i] = add_to_blob (acfg, buf, p - buf);
9570 g_free (buf);
9574 * Construct a chained hash table for mapping indexes in extra_method_info to
9575 * method indexes.
9577 table_size = g_spaced_primes_closest ((int)(nmethods * 1.5));
9578 table = g_ptr_array_sized_new (table_size);
9579 for (i = 0; i < table_size; ++i)
9580 g_ptr_array_add (table, NULL);
9581 chain_lengths = g_new0 (int, table_size);
9582 max_chain_length = 0;
9583 for (i = 0; i < acfg->extra_methods->len; ++i) {
9584 MonoMethod *method = (MonoMethod *)g_ptr_array_index (acfg->extra_methods, i);
9585 MonoCompile *cfg = (MonoCompile *)g_hash_table_lookup (acfg->method_to_cfg, method);
9586 guint32 key, value;
9588 if (ignore_cfg (cfg))
9589 continue;
9591 key = info_offsets [i];
9592 value = get_method_index (acfg, method);
9594 hash = mono_aot_method_hash (method) % table_size;
9595 //printf ("X: %s %x\n", mono_method_get_full_name (method), mono_aot_method_hash (method));
9597 chain_lengths [hash] ++;
9598 max_chain_length = MAX (max_chain_length, chain_lengths [hash]);
9600 new_entry = (HashEntry *)mono_mempool_alloc0 (acfg->mempool, sizeof (HashEntry));
9601 new_entry->key = key;
9602 new_entry->value = value;
9604 entry = (HashEntry *)g_ptr_array_index (table, hash);
9605 if (entry == NULL) {
9606 new_entry->index = hash;
9607 g_ptr_array_index (table, hash) = new_entry;
9608 } else {
9609 while (entry->next)
9610 entry = entry->next;
9612 entry->next = new_entry;
9613 new_entry->index = table->len;
9614 g_ptr_array_add (table, new_entry);
9617 g_free (chain_lengths);
9619 //printf ("MAX: %d\n", max_chain_length);
9621 buf_size = table->len * 12 + 4;
9622 p = buf = (guint8 *)g_malloc (buf_size);
9623 encode_int (table_size, p, &p);
9625 for (i = 0; i < table->len; ++i) {
9626 HashEntry *entry = (HashEntry *)g_ptr_array_index (table, i);
9628 if (entry == NULL) {
9629 encode_int (0, p, &p);
9630 encode_int (0, p, &p);
9631 encode_int (0, p, &p);
9632 } else {
9633 //g_assert (entry->key > 0);
9634 encode_int (entry->key, p, &p);
9635 encode_int (entry->value, p, &p);
9636 if (entry->next)
9637 encode_int (entry->next->index, p, &p);
9638 else
9639 encode_int (0, p, &p);
9642 g_assert (p - buf <= buf_size);
9644 /* Emit the table */
9645 emit_aot_data (acfg, MONO_AOT_TABLE_EXTRA_METHOD_TABLE, "extra_method_table", buf, p - buf);
9647 g_free (buf);
9650 * Emit a table reverse mapping method indexes to their index in extra_method_info.
9651 * This is used by mono_aot_find_jit_info ().
9653 buf_size = acfg->extra_methods->len * 8 + 4;
9654 p = buf = (guint8 *)g_malloc (buf_size);
9655 encode_int (acfg->extra_methods->len, p, &p);
9656 for (i = 0; i < acfg->extra_methods->len; ++i) {
9657 MonoMethod *method = (MonoMethod *)g_ptr_array_index (acfg->extra_methods, i);
9659 encode_int (get_method_index (acfg, method), p, &p);
9660 encode_int (info_offsets [i], p, &p);
9662 emit_aot_data (acfg, MONO_AOT_TABLE_EXTRA_METHOD_INFO_OFFSETS, "extra_method_info_offsets", buf, p - buf);
9664 g_free (buf);
9665 g_free (info_offsets);
9666 g_ptr_array_free (table, TRUE);
9669 static void
9670 generate_aotid (guint8* aotid)
9672 gpointer rand_handle;
9673 ERROR_DECL (error);
9675 mono_rand_open ();
9676 rand_handle = mono_rand_init (NULL, 0);
9678 mono_rand_try_get_bytes (&rand_handle, aotid, 16, error);
9679 mono_error_assert_ok (error);
9681 mono_rand_close (rand_handle);
9684 static void
9685 emit_exception_info (MonoAotCompile *acfg)
9687 int i;
9688 gint32 *offsets;
9689 SeqPointData sp_data;
9690 gboolean seq_points_to_file = FALSE;
9692 offsets = g_new0 (gint32, acfg->nmethods);
9693 for (i = 0; i < acfg->nmethods; ++i) {
9694 if (acfg->cfgs [i]) {
9695 MonoCompile *cfg = acfg->cfgs [i];
9697 // By design aot-runtime decode_exception_debug_info is not able to load sequence point debug data from a file.
9698 // As it is not possible to load debug data from a file its is also not possible to store it in a file.
9699 gboolean method_seq_points_to_file = acfg->aot_opts.gen_msym_dir &&
9700 cfg->gen_seq_points && !cfg->gen_sdb_seq_points;
9701 gboolean method_seq_points_to_binary = cfg->gen_seq_points && !method_seq_points_to_file;
9703 emit_exception_debug_info (acfg, cfg, method_seq_points_to_binary);
9704 offsets [i] = cfg->ex_info_offset;
9706 if (method_seq_points_to_file) {
9707 if (!seq_points_to_file) {
9708 mono_seq_point_data_init (&sp_data, acfg->nmethods);
9709 seq_points_to_file = TRUE;
9711 mono_seq_point_data_add (&sp_data, cfg->method->token, cfg->method_index, cfg->seq_point_info);
9713 } else {
9714 offsets [i] = 0;
9718 if (seq_points_to_file) {
9719 char *aotid = mono_guid_to_string_minimal (acfg->image->aotid);
9720 char *dir = g_build_filename (acfg->aot_opts.gen_msym_dir_path, aotid, NULL);
9721 char *image_basename = g_path_get_basename (acfg->image->name);
9722 char *aot_file = g_strdup_printf("%s%s", image_basename, SEQ_POINT_AOT_EXT);
9723 char *aot_file_path = g_build_filename (dir, aot_file, NULL);
9725 if (g_ensure_directory_exists (aot_file_path) == FALSE) {
9726 fprintf (stderr, "AOT : failed to create msym directory: %s\n", aot_file_path);
9727 exit (1);
9730 mono_seq_point_data_write (&sp_data, aot_file_path);
9731 mono_seq_point_data_free (&sp_data);
9733 g_free (aotid);
9734 g_free (dir);
9735 g_free (image_basename);
9736 g_free (aot_file);
9737 g_free (aot_file_path);
9740 acfg->stats.offsets_size += emit_offset_table (acfg, "ex_info_offsets", MONO_AOT_TABLE_EX_INFO_OFFSETS, acfg->nmethods, 10, offsets);
9741 g_free (offsets);
9744 static void
9745 emit_unwind_info (MonoAotCompile *acfg)
9747 int i;
9748 char symbol [128];
9750 if (acfg->aot_opts.llvm_only) {
9751 g_assert (acfg->unwind_ops->len == 0);
9752 return;
9756 * The unwind info contains a lot of duplicates so we emit each unique
9757 * entry once, and only store the offset from the start of the table in the
9758 * exception info.
9761 sprintf (symbol, "unwind_info");
9762 emit_section_change (acfg, RODATA_SECT, 1);
9763 emit_alignment (acfg, 8);
9764 emit_info_symbol (acfg, symbol);
9766 for (i = 0; i < acfg->unwind_ops->len; ++i) {
9767 guint32 index = GPOINTER_TO_UINT (g_ptr_array_index (acfg->unwind_ops, i));
9768 guint8 *unwind_info;
9769 guint32 unwind_info_len;
9770 guint8 buf [16];
9771 guint8 *p;
9773 unwind_info = mono_get_cached_unwind_info (index, &unwind_info_len);
9775 p = buf;
9776 encode_value (unwind_info_len, p, &p);
9777 emit_bytes (acfg, buf, p - buf);
9778 emit_bytes (acfg, unwind_info, unwind_info_len);
9780 acfg->stats.unwind_info_size += (p - buf) + unwind_info_len;
9784 static void
9785 emit_class_info (MonoAotCompile *acfg)
9787 int i;
9788 gint32 *offsets;
9790 offsets = g_new0 (gint32, acfg->image->tables [MONO_TABLE_TYPEDEF].rows);
9791 for (i = 0; i < acfg->image->tables [MONO_TABLE_TYPEDEF].rows; ++i)
9792 offsets [i] = emit_klass_info (acfg, MONO_TOKEN_TYPE_DEF | (i + 1));
9794 acfg->stats.offsets_size += emit_offset_table (acfg, "class_info_offsets", MONO_AOT_TABLE_CLASS_INFO_OFFSETS, acfg->image->tables [MONO_TABLE_TYPEDEF].rows, 10, offsets);
9795 g_free (offsets);
9798 typedef struct ClassNameTableEntry {
9799 guint32 token, index;
9800 struct ClassNameTableEntry *next;
9801 } ClassNameTableEntry;
9803 static void
9804 emit_class_name_table (MonoAotCompile *acfg)
9806 int i, table_size, buf_size;
9807 guint32 token, hash;
9808 MonoClass *klass;
9809 GPtrArray *table;
9810 char *full_name;
9811 guint8 *buf, *p;
9812 ClassNameTableEntry *entry, *new_entry;
9815 * Construct a chained hash table for mapping class names to typedef tokens.
9817 table_size = g_spaced_primes_closest ((int)(acfg->image->tables [MONO_TABLE_TYPEDEF].rows * 1.5));
9818 table = g_ptr_array_sized_new (table_size);
9819 for (i = 0; i < table_size; ++i)
9820 g_ptr_array_add (table, NULL);
9821 for (i = 0; i < acfg->image->tables [MONO_TABLE_TYPEDEF].rows; ++i) {
9822 ERROR_DECL (error);
9823 token = MONO_TOKEN_TYPE_DEF | (i + 1);
9824 klass = mono_class_get_checked (acfg->image, token, error);
9825 if (!klass) {
9826 mono_error_cleanup (error);
9827 continue;
9829 full_name = mono_type_get_name_full (mono_class_get_type (klass), MONO_TYPE_NAME_FORMAT_FULL_NAME);
9830 hash = mono_metadata_str_hash (full_name) % table_size;
9831 g_free (full_name);
9833 /* FIXME: Allocate from the mempool */
9834 new_entry = g_new0 (ClassNameTableEntry, 1);
9835 new_entry->token = token;
9837 entry = (ClassNameTableEntry *)g_ptr_array_index (table, hash);
9838 if (entry == NULL) {
9839 new_entry->index = hash;
9840 g_ptr_array_index (table, hash) = new_entry;
9841 } else {
9842 while (entry->next)
9843 entry = entry->next;
9845 entry->next = new_entry;
9846 new_entry->index = table->len;
9847 g_ptr_array_add (table, new_entry);
9851 /* Emit the table */
9852 buf_size = table->len * 4 + 4;
9853 p = buf = (guint8 *)g_malloc0 (buf_size);
9855 /* FIXME: Optimize memory usage */
9856 g_assert (table_size < 65000);
9857 encode_int16 (table_size, p, &p);
9858 g_assert (table->len < 65000);
9859 for (i = 0; i < table->len; ++i) {
9860 ClassNameTableEntry *entry = (ClassNameTableEntry *)g_ptr_array_index (table, i);
9862 if (entry == NULL) {
9863 encode_int16 (0, p, &p);
9864 encode_int16 (0, p, &p);
9865 } else {
9866 encode_int16 (mono_metadata_token_index (entry->token), p, &p);
9867 if (entry->next)
9868 encode_int16 (entry->next->index, p, &p);
9869 else
9870 encode_int16 (0, p, &p);
9872 g_free (entry);
9874 g_assert (p - buf <= buf_size);
9875 g_ptr_array_free (table, TRUE);
9877 emit_aot_data (acfg, MONO_AOT_TABLE_CLASS_NAME, "class_name_table", buf, p - buf);
9879 g_free (buf);
9882 static void
9883 emit_image_table (MonoAotCompile *acfg)
9885 int i, buf_size;
9886 guint8 *buf, *p;
9889 * The image table is small but referenced in a lot of places.
9890 * So we emit it at once, and reference its elements by an index.
9892 buf_size = acfg->image_table->len * 28 + 4;
9893 for (i = 0; i < acfg->image_table->len; i++) {
9894 MonoImage *image = (MonoImage*)g_ptr_array_index (acfg->image_table, i);
9895 MonoAssemblyName *aname = &image->assembly->aname;
9897 buf_size += strlen (image->assembly_name) + strlen (image->guid) + (aname->culture ? strlen (aname->culture) : 1) + strlen ((char*)aname->public_key_token) + 4;
9900 buf = p = (guint8 *)g_malloc0 (buf_size);
9901 encode_int (acfg->image_table->len, p, &p);
9902 for (i = 0; i < acfg->image_table->len; i++) {
9903 MonoImage *image = (MonoImage*)g_ptr_array_index (acfg->image_table, i);
9904 MonoAssemblyName *aname = &image->assembly->aname;
9906 /* FIXME: Support multi-module assemblies */
9907 g_assert (image->assembly->image == image);
9909 encode_string (image->assembly_name, p, &p);
9910 encode_string (image->guid, p, &p);
9911 encode_string (aname->culture ? aname->culture : "", p, &p);
9912 encode_string ((const char*)aname->public_key_token, p, &p);
9914 while (GPOINTER_TO_UINT (p) % 8 != 0)
9915 p ++;
9917 encode_int (aname->flags, p, &p);
9918 encode_int (aname->major, p, &p);
9919 encode_int (aname->minor, p, &p);
9920 encode_int (aname->build, p, &p);
9921 encode_int (aname->revision, p, &p);
9923 g_assert (p - buf <= buf_size);
9925 emit_aot_data (acfg, MONO_AOT_TABLE_IMAGE_TABLE, "image_table", buf, p - buf);
9927 g_free (buf);
9930 static void
9931 emit_weak_field_indexes (MonoAotCompile *acfg)
9933 GHashTable *indexes;
9934 GHashTableIter iter;
9935 gpointer key, value;
9936 int buf_size;
9937 guint8 *buf, *p;
9939 /* Emit a table of weak field indexes, since computing these at runtime is expensive */
9940 mono_assembly_init_weak_fields (acfg->image);
9941 indexes = acfg->image->weak_field_indexes;
9942 g_assert (indexes);
9944 buf_size = (g_hash_table_size (indexes) + 1) * 4;
9945 buf = p = (guint8 *)g_malloc0 (buf_size);
9947 encode_int (g_hash_table_size (indexes), p, &p);
9948 g_hash_table_iter_init (&iter, indexes);
9949 while (g_hash_table_iter_next (&iter, &key, &value)) {
9950 guint32 index = GPOINTER_TO_UINT (key);
9951 encode_int (index, p, &p);
9953 g_assert (p - buf <= buf_size);
9955 emit_aot_data (acfg, MONO_AOT_TABLE_WEAK_FIELD_INDEXES, "weak_field_indexes", buf, p - buf);
9957 g_free (buf);
9960 static void
9961 emit_got_info (MonoAotCompile *acfg, gboolean llvm)
9963 int i, first_plt_got_patch = 0, buf_size;
9964 guint8 *p, *buf;
9965 guint32 *got_info_offsets;
9966 GotInfo *info = llvm ? &acfg->llvm_got_info : &acfg->got_info;
9968 /* Add the patches needed by the PLT to the GOT */
9969 if (!llvm) {
9970 acfg->plt_got_offset_base = acfg->got_offset;
9971 first_plt_got_patch = info->got_patches->len;
9972 for (i = 1; i < acfg->plt_offset; ++i) {
9973 MonoPltEntry *plt_entry = (MonoPltEntry *)g_hash_table_lookup (acfg->plt_offset_to_entry, GUINT_TO_POINTER (i));
9975 g_ptr_array_add (info->got_patches, plt_entry->ji);
9977 acfg->stats.got_slot_types [plt_entry->ji->type] ++;
9980 acfg->got_offset += acfg->plt_offset;
9984 * FIXME:
9985 * - optimize offsets table.
9986 * - reduce number of exported symbols.
9987 * - emit info for a klass only once.
9988 * - determine when a method uses a GOT slot which is guaranteed to be already
9989 * initialized.
9990 * - clean up and document the code.
9991 * - use String.Empty in class libs.
9994 /* Encode info required to decode shared GOT entries */
9995 buf_size = info->got_patches->len * 128;
9996 p = buf = (guint8 *)mono_mempool_alloc (acfg->mempool, buf_size);
9997 got_info_offsets = (guint32 *)mono_mempool_alloc (acfg->mempool, info->got_patches->len * sizeof (guint32));
9998 if (!llvm) {
9999 acfg->plt_got_info_offsets = (guint32 *)mono_mempool_alloc (acfg->mempool, acfg->plt_offset * sizeof (guint32));
10000 /* Unused */
10001 if (acfg->plt_offset)
10002 acfg->plt_got_info_offsets [0] = 0;
10004 for (i = 0; i < info->got_patches->len; ++i) {
10005 MonoJumpInfo *ji = (MonoJumpInfo *)g_ptr_array_index (info->got_patches, i);
10006 guint8 *p2;
10008 p = buf;
10010 encode_value (ji->type, p, &p);
10011 p2 = p;
10012 encode_patch (acfg, ji, p, &p);
10013 acfg->stats.got_slot_info_sizes [ji->type] += p - p2;
10014 g_assert (p - buf <= buf_size);
10015 got_info_offsets [i] = add_to_blob (acfg, buf, p - buf);
10017 if (!llvm && i >= first_plt_got_patch)
10018 acfg->plt_got_info_offsets [i - first_plt_got_patch + 1] = got_info_offsets [i];
10019 acfg->stats.got_info_size += p - buf;
10022 /* Emit got_info_offsets table */
10024 /* No need to emit offsets for the got plt entries, the plt embeds them directly */
10025 acfg->stats.offsets_size += emit_offset_table (acfg, llvm ? "llvm_got_info_offsets" : "got_info_offsets", llvm ? MONO_AOT_TABLE_LLVM_GOT_INFO_OFFSETS : MONO_AOT_TABLE_GOT_INFO_OFFSETS, llvm ? acfg->llvm_got_offset : first_plt_got_patch, 10, (gint32*)got_info_offsets);
10028 static void
10029 emit_got (MonoAotCompile *acfg)
10031 char symbol [MAX_SYMBOL_SIZE];
10033 if (acfg->aot_opts.llvm_only)
10034 return;
10036 /* Don't make GOT global so accesses to it don't need relocations */
10037 sprintf (symbol, "%s", acfg->got_symbol);
10039 #ifdef TARGET_MACH
10040 emit_unset_mode (acfg);
10041 fprintf (acfg->fp, ".section __DATA, __bss\n");
10042 emit_alignment (acfg, 8);
10043 if (acfg->llvm)
10044 emit_info_symbol (acfg, "jit_got");
10045 fprintf (acfg->fp, ".lcomm %s, %d\n", acfg->got_symbol, (int)(acfg->got_offset * sizeof (gpointer)));
10046 #else
10047 emit_section_change (acfg, ".bss", 0);
10048 emit_alignment (acfg, 8);
10049 if (acfg->aot_opts.write_symbols)
10050 emit_local_symbol (acfg, symbol, "got_end", FALSE);
10051 emit_label (acfg, symbol);
10052 if (acfg->llvm)
10053 emit_info_symbol (acfg, "jit_got");
10054 if (acfg->got_offset > 0)
10055 emit_zero_bytes (acfg, (int)(acfg->got_offset * sizeof (gpointer)));
10056 #endif
10058 sprintf (symbol, "got_end");
10059 emit_label (acfg, symbol);
10062 typedef struct GlobalsTableEntry {
10063 guint32 value, index;
10064 struct GlobalsTableEntry *next;
10065 } GlobalsTableEntry;
10067 #ifdef TARGET_WIN32_MSVC
10068 #define DLL_ENTRY_POINT "DllMain"
10070 static void
10071 emit_library_info (MonoAotCompile *acfg)
10073 // Only include for shared libraries linked directly from generated object.
10074 if (link_shared_library (acfg)) {
10075 char *name = NULL;
10076 char symbol [MAX_SYMBOL_SIZE];
10078 // Ask linker to export all global symbols.
10079 emit_section_change (acfg, ".drectve", 0);
10080 for (guint i = 0; i < acfg->globals->len; ++i) {
10081 name = (char *)g_ptr_array_index (acfg->globals, i);
10082 g_assert (name != NULL);
10083 sprintf_s (symbol, MAX_SYMBOL_SIZE, " /EXPORT:%s", name);
10084 emit_string (acfg, symbol);
10087 // Emit DLLMain function, needed by MSVC linker for DLL's.
10088 // NOTE, DllMain should not go into exports above.
10089 emit_section_change (acfg, ".text", 0);
10090 emit_global (acfg, DLL_ENTRY_POINT, TRUE);
10091 emit_label (acfg, DLL_ENTRY_POINT);
10093 // Simple implementation of DLLMain, just returning TRUE.
10094 // For more information about DLLMain: https://msdn.microsoft.com/en-us/library/windows/desktop/ms682583(v=vs.85).aspx
10095 fprintf (acfg->fp, "movl $1, %%eax\n");
10096 fprintf (acfg->fp, "ret\n");
10098 // Inform linker about our dll entry function.
10099 emit_section_change (acfg, ".drectve", 0);
10100 emit_string (acfg, "/ENTRY:" DLL_ENTRY_POINT);
10101 return;
10105 #else
10107 static inline void
10108 emit_library_info (MonoAotCompile *acfg)
10110 return;
10112 #endif
10114 static void
10115 emit_globals (MonoAotCompile *acfg)
10117 int i, table_size;
10118 guint32 hash;
10119 GPtrArray *table;
10120 char symbol [1024];
10121 GlobalsTableEntry *entry, *new_entry;
10123 if (!acfg->aot_opts.static_link)
10124 return;
10126 if (acfg->aot_opts.llvm_only) {
10127 g_assert (acfg->globals->len == 0);
10128 return;
10132 * When static linking, we emit a table containing our globals.
10136 * Construct a chained hash table for mapping global names to their index in
10137 * the globals table.
10139 table_size = g_spaced_primes_closest ((int)(acfg->globals->len * 1.5));
10140 table = g_ptr_array_sized_new (table_size);
10141 for (i = 0; i < table_size; ++i)
10142 g_ptr_array_add (table, NULL);
10143 for (i = 0; i < acfg->globals->len; ++i) {
10144 char *name = (char *)g_ptr_array_index (acfg->globals, i);
10146 hash = mono_metadata_str_hash (name) % table_size;
10148 /* FIXME: Allocate from the mempool */
10149 new_entry = g_new0 (GlobalsTableEntry, 1);
10150 new_entry->value = i;
10152 entry = (GlobalsTableEntry *)g_ptr_array_index (table, hash);
10153 if (entry == NULL) {
10154 new_entry->index = hash;
10155 g_ptr_array_index (table, hash) = new_entry;
10156 } else {
10157 while (entry->next)
10158 entry = entry->next;
10160 entry->next = new_entry;
10161 new_entry->index = table->len;
10162 g_ptr_array_add (table, new_entry);
10166 /* Emit the table */
10167 sprintf (symbol, ".Lglobals_hash");
10168 emit_section_change (acfg, RODATA_SECT, 0);
10169 emit_alignment (acfg, 8);
10170 emit_label (acfg, symbol);
10172 /* FIXME: Optimize memory usage */
10173 g_assert (table_size < 65000);
10174 emit_int16 (acfg, table_size);
10175 for (i = 0; i < table->len; ++i) {
10176 GlobalsTableEntry *entry = (GlobalsTableEntry *)g_ptr_array_index (table, i);
10178 if (entry == NULL) {
10179 emit_int16 (acfg, 0);
10180 emit_int16 (acfg, 0);
10181 } else {
10182 emit_int16 (acfg, entry->value + 1);
10183 if (entry->next)
10184 emit_int16 (acfg, entry->next->index);
10185 else
10186 emit_int16 (acfg, 0);
10190 /* Emit the names */
10191 for (i = 0; i < acfg->globals->len; ++i) {
10192 char *name = (char *)g_ptr_array_index (acfg->globals, i);
10194 sprintf (symbol, "name_%d", i);
10195 emit_section_change (acfg, RODATA_SECT, 1);
10196 #ifdef TARGET_MACH
10197 emit_alignment (acfg, 4);
10198 #endif
10199 emit_label (acfg, symbol);
10200 emit_string (acfg, name);
10203 /* Emit the globals table */
10204 sprintf (symbol, "globals");
10205 emit_section_change (acfg, ".data", 0);
10206 /* This is not a global, since it is accessed by the init function */
10207 emit_alignment (acfg, 8);
10208 emit_info_symbol (acfg, symbol);
10210 sprintf (symbol, "%sglobals_hash", acfg->temp_prefix);
10211 emit_pointer (acfg, symbol);
10213 for (i = 0; i < acfg->globals->len; ++i) {
10214 char *name = (char *)g_ptr_array_index (acfg->globals, i);
10216 sprintf (symbol, "name_%d", i);
10217 emit_pointer (acfg, symbol);
10219 g_assert (strlen (name) < sizeof (symbol));
10220 sprintf (symbol, "%s", name);
10221 emit_pointer (acfg, symbol);
10223 /* Null terminate the table */
10224 emit_int32 (acfg, 0);
10225 emit_int32 (acfg, 0);
10228 static void
10229 emit_mem_end (MonoAotCompile *acfg)
10231 char symbol [128];
10233 if (acfg->aot_opts.llvm_only)
10234 return;
10236 sprintf (symbol, "mem_end");
10237 emit_section_change (acfg, ".text", 1);
10238 emit_alignment_code (acfg, 8);
10239 emit_label (acfg, symbol);
10242 static void
10243 init_aot_file_info (MonoAotCompile *acfg, MonoAotFileInfo *info)
10245 int i;
10247 info->version = MONO_AOT_FILE_VERSION;
10248 info->plt_got_offset_base = acfg->plt_got_offset_base;
10249 info->got_size = acfg->got_offset * sizeof (gpointer);
10250 info->plt_size = acfg->plt_offset;
10251 info->nmethods = acfg->nmethods;
10252 info->flags = acfg->flags;
10253 info->opts = acfg->opts;
10254 info->simd_opts = acfg->simd_opts;
10255 info->gc_name_index = acfg->gc_name_offset;
10256 info->datafile_size = acfg->datafile_offset;
10257 for (i = 0; i < MONO_AOT_TABLE_NUM; ++i)
10258 info->table_offsets [i] = acfg->table_offsets [i];
10259 for (i = 0; i < MONO_AOT_TRAMP_NUM; ++i)
10260 info->num_trampolines [i] = acfg->num_trampolines [i];
10261 for (i = 0; i < MONO_AOT_TRAMP_NUM; ++i)
10262 info->trampoline_got_offset_base [i] = acfg->trampoline_got_offset_base [i];
10263 for (i = 0; i < MONO_AOT_TRAMP_NUM; ++i)
10264 info->trampoline_size [i] = acfg->trampoline_size [i];
10265 info->num_rgctx_fetch_trampolines = acfg->aot_opts.nrgctx_fetch_trampolines;
10267 info->double_align = MONO_ABI_ALIGNOF (double);
10268 info->long_align = MONO_ABI_ALIGNOF (gint64);
10269 info->generic_tramp_num = MONO_TRAMPOLINE_NUM;
10270 info->tramp_page_size = acfg->tramp_page_size;
10271 info->nshared_got_entries = acfg->nshared_got_entries;
10272 for (i = 0; i < MONO_AOT_TRAMP_NUM; ++i)
10273 info->tramp_page_code_offsets [i] = acfg->tramp_page_code_offsets [i];
10275 memcpy(&info->aotid, acfg->image->aotid, 16);
10278 static void
10279 emit_aot_file_info (MonoAotCompile *acfg, MonoAotFileInfo *info)
10281 char symbol [MAX_SYMBOL_SIZE];
10282 int i, sindex;
10283 const char **symbols;
10285 symbols = g_new0 (const char *, MONO_AOT_FILE_INFO_NUM_SYMBOLS);
10286 sindex = 0;
10287 symbols [sindex ++] = acfg->got_symbol;
10288 if (acfg->llvm) {
10289 symbols [sindex ++] = g_strdup_printf ("%s%s", acfg->user_symbol_prefix, acfg->llvm_got_symbol);
10290 symbols [sindex ++] = acfg->llvm_eh_frame_symbol;
10291 } else {
10292 symbols [sindex ++] = NULL;
10293 symbols [sindex ++] = NULL;
10295 /* llvm_get_method */
10296 symbols [sindex ++] = NULL;
10297 /* llvm_get_unbox_tramp */
10298 symbols [sindex ++] = NULL;
10299 if (!acfg->aot_opts.llvm_only) {
10300 symbols [sindex ++] = "jit_code_start";
10301 symbols [sindex ++] = "jit_code_end";
10302 symbols [sindex ++] = "method_addresses";
10303 } else {
10304 symbols [sindex ++] = NULL;
10305 symbols [sindex ++] = NULL;
10306 symbols [sindex ++] = NULL;
10309 if (acfg->data_outfile) {
10310 for (i = 0; i < MONO_AOT_TABLE_NUM; ++i)
10311 symbols [sindex ++] = NULL;
10312 } else {
10313 symbols [sindex ++] = "blob";
10314 symbols [sindex ++] = "class_name_table";
10315 symbols [sindex ++] = "class_info_offsets";
10316 symbols [sindex ++] = "method_info_offsets";
10317 symbols [sindex ++] = "ex_info_offsets";
10318 symbols [sindex ++] = "extra_method_info_offsets";
10319 symbols [sindex ++] = "extra_method_table";
10320 symbols [sindex ++] = "got_info_offsets";
10321 if (acfg->llvm)
10322 symbols [sindex ++] = "llvm_got_info_offsets";
10323 else
10324 symbols [sindex ++] = NULL;
10325 symbols [sindex ++] = "image_table";
10326 symbols [sindex ++] = "weak_field_indexes";
10329 symbols [sindex ++] = "mem_end";
10330 symbols [sindex ++] = "assembly_guid";
10331 symbols [sindex ++] = "runtime_version";
10332 if (acfg->num_trampoline_got_entries) {
10333 symbols [sindex ++] = "specific_trampolines";
10334 symbols [sindex ++] = "static_rgctx_trampolines";
10335 symbols [sindex ++] = "imt_trampolines";
10336 symbols [sindex ++] = "gsharedvt_arg_trampolines";
10337 } else {
10338 symbols [sindex ++] = NULL;
10339 symbols [sindex ++] = NULL;
10340 symbols [sindex ++] = NULL;
10341 symbols [sindex ++] = NULL;
10343 if (acfg->aot_opts.static_link) {
10344 symbols [sindex ++] = "globals";
10345 } else {
10346 symbols [sindex ++] = NULL;
10348 symbols [sindex ++] = "assembly_name";
10349 symbols [sindex ++] = "plt";
10350 symbols [sindex ++] = "plt_end";
10351 symbols [sindex ++] = "unwind_info";
10352 if (!acfg->aot_opts.llvm_only) {
10353 symbols [sindex ++] = "unbox_trampolines";
10354 symbols [sindex ++] = "unbox_trampolines_end";
10355 symbols [sindex ++] = "unbox_trampoline_addresses";
10356 } else {
10357 symbols [sindex ++] = NULL;
10358 symbols [sindex ++] = NULL;
10359 symbols [sindex ++] = NULL;
10362 g_assert (sindex == MONO_AOT_FILE_INFO_NUM_SYMBOLS);
10364 sprintf (symbol, "%smono_aot_file_info", acfg->user_symbol_prefix);
10365 emit_section_change (acfg, ".data", 0);
10366 emit_alignment (acfg, 8);
10367 emit_label (acfg, symbol);
10368 if (!acfg->aot_opts.static_link)
10369 emit_global (acfg, symbol, FALSE);
10371 /* The data emitted here must match MonoAotFileInfo. */
10373 emit_int32 (acfg, info->version);
10374 emit_int32 (acfg, info->dummy);
10377 * We emit pointers to our data structures instead of emitting global symbols which
10378 * point to them, to reduce the number of globals, and because using globals leads to
10379 * various problems (i.e. arm/thumb).
10381 for (i = 0; i < MONO_AOT_FILE_INFO_NUM_SYMBOLS; ++i)
10382 emit_pointer (acfg, symbols [i]);
10384 emit_int32 (acfg, info->plt_got_offset_base);
10385 emit_int32 (acfg, info->got_size);
10386 emit_int32 (acfg, info->plt_size);
10387 emit_int32 (acfg, info->nmethods);
10388 emit_int32 (acfg, info->flags);
10389 emit_int32 (acfg, info->opts);
10390 emit_int32 (acfg, info->simd_opts);
10391 emit_int32 (acfg, info->gc_name_index);
10392 emit_int32 (acfg, info->num_rgctx_fetch_trampolines);
10393 emit_int32 (acfg, info->double_align);
10394 emit_int32 (acfg, info->long_align);
10395 emit_int32 (acfg, info->generic_tramp_num);
10396 emit_int32 (acfg, info->tramp_page_size);
10397 emit_int32 (acfg, info->nshared_got_entries);
10398 emit_int32 (acfg, info->datafile_size);
10400 for (i = 0; i < MONO_AOT_TABLE_NUM; ++i)
10401 emit_int32 (acfg, info->table_offsets [i]);
10402 for (i = 0; i < MONO_AOT_TRAMP_NUM; ++i)
10403 emit_int32 (acfg, info->num_trampolines [i]);
10404 for (i = 0; i < MONO_AOT_TRAMP_NUM; ++i)
10405 emit_int32 (acfg, info->trampoline_got_offset_base [i]);
10406 for (i = 0; i < MONO_AOT_TRAMP_NUM; ++i)
10407 emit_int32 (acfg, info->trampoline_size [i]);
10408 for (i = 0; i < MONO_AOT_TRAMP_NUM; ++i)
10409 emit_int32 (acfg, info->tramp_page_code_offsets [i]);
10411 emit_bytes (acfg, info->aotid, 16);
10413 if (acfg->aot_opts.static_link) {
10414 emit_global_inner (acfg, acfg->static_linking_symbol, FALSE);
10415 emit_alignment (acfg, sizeof (gpointer));
10416 emit_label (acfg, acfg->static_linking_symbol);
10417 emit_pointer_2 (acfg, acfg->user_symbol_prefix, "mono_aot_file_info");
10422 * Emit a structure containing all the information not stored elsewhere.
10424 static void
10425 emit_file_info (MonoAotCompile *acfg)
10427 char *build_info;
10428 MonoAotFileInfo *info;
10430 if (acfg->aot_opts.bind_to_runtime_version) {
10431 build_info = mono_get_runtime_build_info ();
10432 emit_string_symbol (acfg, "runtime_version", build_info);
10433 g_free (build_info);
10434 } else {
10435 emit_string_symbol (acfg, "runtime_version", "");
10438 emit_string_symbol (acfg, "assembly_guid" , acfg->image->guid);
10440 /* Emit a string holding the assembly name */
10441 emit_string_symbol (acfg, "assembly_name", acfg->image->assembly->aname.name);
10443 info = g_new0 (MonoAotFileInfo, 1);
10444 init_aot_file_info (acfg, info);
10446 if (acfg->aot_opts.static_link) {
10447 char symbol [MAX_SYMBOL_SIZE];
10448 char *p;
10451 * Emit a global symbol which can be passed by an embedding app to
10452 * mono_aot_register_module (). The symbol points to a pointer to the the file info
10453 * structure.
10455 sprintf (symbol, "%smono_aot_module_%s_info", acfg->user_symbol_prefix, acfg->image->assembly->aname.name);
10457 /* Get rid of characters which cannot occur in symbols */
10458 p = symbol;
10459 for (p = symbol; *p; ++p) {
10460 if (!(isalnum (*p) || *p == '_'))
10461 *p = '_';
10463 acfg->static_linking_symbol = g_strdup (symbol);
10466 if (acfg->llvm)
10467 mono_llvm_emit_aot_file_info (info, acfg->has_jitted_code);
10468 else
10469 emit_aot_file_info (acfg, info);
10472 static void
10473 emit_blob (MonoAotCompile *acfg)
10475 acfg->blob_closed = TRUE;
10477 emit_aot_data (acfg, MONO_AOT_TABLE_BLOB, "blob", (guint8*)acfg->blob.data, acfg->blob.index);
10480 static void
10481 emit_objc_selectors (MonoAotCompile *acfg)
10483 int i;
10484 char symbol [128];
10486 if (!acfg->objc_selectors || acfg->objc_selectors->len == 0)
10487 return;
10490 * From
10491 * cat > foo.m << EOF
10492 * void *ret ()
10494 * return @selector(print:);
10496 * EOF
10499 mono_img_writer_emit_unset_mode (acfg->w);
10500 g_assert (acfg->fp);
10501 fprintf (acfg->fp, ".section __DATA,__objc_selrefs,literal_pointers,no_dead_strip\n");
10502 fprintf (acfg->fp, ".align 3\n");
10503 for (i = 0; i < acfg->objc_selectors->len; ++i) {
10504 sprintf (symbol, "L_OBJC_SELECTOR_REFERENCES_%d", i);
10505 emit_label (acfg, symbol);
10506 sprintf (symbol, "L_OBJC_METH_VAR_NAME_%d", i);
10507 emit_pointer (acfg, symbol);
10510 fprintf (acfg->fp, ".section __TEXT,__cstring,cstring_literals\n");
10511 for (i = 0; i < acfg->objc_selectors->len; ++i) {
10512 fprintf (acfg->fp, "L_OBJC_METH_VAR_NAME_%d:\n", i);
10513 fprintf (acfg->fp, ".asciz \"%s\"\n", (char*)g_ptr_array_index (acfg->objc_selectors, i));
10516 fprintf (acfg->fp, ".section __DATA,__objc_imageinfo,regular,no_dead_strip\n");
10517 fprintf (acfg->fp, ".align 3\n");
10518 fprintf (acfg->fp, "L_OBJC_IMAGE_INFO:\n");
10519 fprintf (acfg->fp, ".long 0\n");
10520 fprintf (acfg->fp, ".long 16\n");
10523 static void
10524 emit_dwarf_info (MonoAotCompile *acfg)
10526 #ifdef EMIT_DWARF_INFO
10527 int i;
10528 char symbol2 [128];
10530 /* DIEs for methods */
10531 for (i = 0; i < acfg->nmethods; ++i) {
10532 MonoCompile *cfg = acfg->cfgs [i];
10534 if (ignore_cfg (cfg))
10535 continue;
10537 // FIXME: LLVM doesn't define .Lme_...
10538 if (cfg->compile_llvm)
10539 continue;
10541 sprintf (symbol2, "%sme_%x", acfg->temp_prefix, i);
10543 mono_dwarf_writer_emit_method (acfg->dwarf, cfg, cfg->method, cfg->asm_symbol, symbol2, cfg->asm_debug_symbol, (guint8 *)cfg->jit_info->code_start, cfg->jit_info->code_size, cfg->args, cfg->locals, cfg->unwind_ops, mono_debug_find_method (cfg->jit_info->d.method, mono_domain_get ()));
10545 #endif
10548 #ifdef EMIT_WIN32_CODEVIEW_INFO
10549 typedef struct _CodeViewSubSectionData
10551 gchar *start_section;
10552 gchar *end_section;
10553 gchar *start_section_record;
10554 gchar *end_section_record;
10555 int section_type;
10556 int section_record_type;
10557 int section_id;
10558 } CodeViewSubsectionData;
10560 typedef struct _CodeViewCompilerVersion
10562 gint major;
10563 gint minor;
10564 gint revision;
10565 gint patch;
10566 } CodeViewCompilerVersion;
10568 #define CODEVIEW_SUBSECTION_SYMBOL_TYPE 0xF1
10569 #define CODEVIEW_SUBSECTION_RECORD_COMPILER_TYPE 0x113c
10570 #define CODEVIEW_SUBSECTION_RECORD_FUNCTION_START_TYPE 0x1147
10571 #define CODEVIEW_SUBSECTION_RECORD_FUNCTION_END_TYPE 0x114F
10572 #define CODEVIEW_CSHARP_LANGUAGE_TYPE 0x0A
10573 #define CODEVIEW_CPU_TYPE 0x0
10574 #define CODEVIEW_MAGIC_HEADER 0x4
10576 static void
10577 codeview_clear_subsection_data (CodeViewSubsectionData *section_data)
10579 g_free (section_data->start_section);
10580 g_free (section_data->end_section);
10581 g_free (section_data->start_section_record);
10582 g_free (section_data->end_section_record);
10584 memset (section_data, 0, sizeof (CodeViewSubsectionData));
10587 static void
10588 codeview_parse_compiler_version (gchar *version, CodeViewCompilerVersion *data)
10590 gint values[4] = { 0 };
10591 gint *value = values;
10593 while (*version && (value < values + G_N_ELEMENTS (values))) {
10594 if (isdigit (*version)) {
10595 *value *= 10;
10596 *value += *version - '0';
10598 else if (*version == '.') {
10599 value++;
10602 version++;
10605 data->major = values[0];
10606 data->minor = values[1];
10607 data->revision = values[2];
10608 data->patch = values[3];
10611 static void
10612 emit_codeview_start_subsection (MonoAotCompile *acfg, int section_id, int section_type, int section_record_type, CodeViewSubsectionData *section_data)
10614 // Starting a new subsection, clear old data.
10615 codeview_clear_subsection_data (section_data);
10617 // Keep subsection data.
10618 section_data->section_id = section_id;
10619 section_data->section_type = section_type;
10620 section_data->section_record_type = section_record_type;
10622 // Allocate all labels used in subsection.
10623 section_data->start_section = g_strdup_printf ("%scvs_%d", acfg->temp_prefix, section_data->section_id);
10624 section_data->end_section = g_strdup_printf ("%scvse_%d", acfg->temp_prefix, section_data->section_id);
10625 section_data->start_section_record = g_strdup_printf ("%scvsr_%d", acfg->temp_prefix, section_data->section_id);
10626 section_data->end_section_record = g_strdup_printf ("%scvsre_%d", acfg->temp_prefix, section_data->section_id);
10628 // Subsection type, function symbol.
10629 emit_int32 (acfg, section_data->section_type);
10631 // Subsection size.
10632 emit_symbol_diff (acfg, section_data->end_section, section_data->start_section, 0);
10633 emit_label (acfg, section_data->start_section);
10635 // Subsection record size.
10636 fprintf (acfg->fp, "\t.word %s - %s\n", section_data->end_section_record, section_data->start_section_record);
10637 emit_label (acfg, section_data->start_section_record);
10639 // Subsection record type.
10640 emit_int16 (acfg, section_record_type);
10643 static void
10644 emit_codeview_end_subsection (MonoAotCompile *acfg, CodeViewSubsectionData *section_data, int *section_id)
10646 g_assert (section_data->start_section);
10647 g_assert (section_data->end_section);
10648 g_assert (section_data->start_section_record);
10649 g_assert (section_data->end_section_record);
10651 emit_label (acfg, section_data->end_section_record);
10653 if (section_data->section_record_type == CODEVIEW_SUBSECTION_RECORD_FUNCTION_START_TYPE) {
10654 // Emit record length.
10655 emit_int16 (acfg, 2);
10657 // Emit specific record type end.
10658 emit_int16 (acfg, CODEVIEW_SUBSECTION_RECORD_FUNCTION_END_TYPE);
10661 emit_label (acfg, section_data->end_section);
10663 // Next subsection needs to be 4 byte aligned.
10664 emit_alignment (acfg, 4);
10666 *section_id = section_data->section_id + 1;
10667 codeview_clear_subsection_data (section_data);
10670 inline static void
10671 emit_codeview_start_symbol_subsection (MonoAotCompile *acfg, int section_id, int section_record_type, CodeViewSubsectionData *section_data)
10673 emit_codeview_start_subsection (acfg, section_id, CODEVIEW_SUBSECTION_SYMBOL_TYPE, section_record_type, section_data);
10676 inline static void
10677 emit_codeview_end_symbol_subsection (MonoAotCompile *acfg, CodeViewSubsectionData *section_data, int *section_id)
10679 emit_codeview_end_subsection (acfg, section_data, section_id);
10682 static void
10683 emit_codeview_compiler_info (MonoAotCompile *acfg, int *section_id)
10685 CodeViewSubsectionData section_data = { 0 };
10686 CodeViewCompilerVersion compiler_version = { 0 };
10688 // Start new compiler record subsection.
10689 emit_codeview_start_symbol_subsection (acfg, *section_id, CODEVIEW_SUBSECTION_RECORD_COMPILER_TYPE, &section_data);
10691 emit_int32 (acfg, CODEVIEW_CSHARP_LANGUAGE_TYPE);
10692 emit_int16 (acfg, CODEVIEW_CPU_TYPE);
10694 // Get compiler version information.
10695 codeview_parse_compiler_version (VERSION, &compiler_version);
10697 // Compiler frontend version, 4 digits.
10698 emit_int16 (acfg, compiler_version.major);
10699 emit_int16 (acfg, compiler_version.minor);
10700 emit_int16 (acfg, compiler_version.revision);
10701 emit_int16 (acfg, compiler_version.patch);
10703 // Compiler backend version, 4 digits (currently same as frontend).
10704 emit_int16 (acfg, compiler_version.major);
10705 emit_int16 (acfg, compiler_version.minor);
10706 emit_int16 (acfg, compiler_version.revision);
10707 emit_int16 (acfg, compiler_version.patch);
10709 // Compiler string.
10710 emit_string (acfg, "Mono AOT compiler");
10712 // Done with section.
10713 emit_codeview_end_symbol_subsection (acfg, &section_data, section_id);
10716 static void
10717 emit_codeview_function_info (MonoAotCompile *acfg, MonoMethod *method, int *section_id, gchar *symbol, gchar *symbol_start, gchar *symbol_end)
10719 CodeViewSubsectionData section_data = { 0 };
10720 gchar *full_method_name = NULL;
10722 // Start new function record subsection.
10723 emit_codeview_start_symbol_subsection (acfg, *section_id, CODEVIEW_SUBSECTION_RECORD_FUNCTION_START_TYPE, &section_data);
10725 // Emit 3 int 0 byte padding, currently not used.
10726 emit_zero_bytes (acfg, sizeof (int) * 3);
10728 // Emit size of function.
10729 emit_symbol_diff (acfg, symbol_end, symbol_start, 0);
10731 // Emit 3 int 0 byte padding, currently not used.
10732 emit_zero_bytes (acfg, sizeof (int) * 3);
10734 // Emit reallocation info.
10735 fprintf (acfg->fp, "\t.secrel32 %s\n", symbol);
10736 fprintf (acfg->fp, "\t.secidx %s\n", symbol);
10738 // Emit flag, currently not used.
10739 emit_zero_bytes (acfg, 1);
10741 // Emit function name, exclude signature since it should be described by own metadata.
10742 full_method_name = mono_method_full_name (method, FALSE);
10743 emit_string (acfg, full_method_name ? full_method_name : "");
10744 g_free (full_method_name);
10746 // Done with section.
10747 emit_codeview_end_symbol_subsection (acfg, &section_data, section_id);
10750 static void
10751 emit_codeview_info (MonoAotCompile *acfg)
10753 int i;
10754 int section_id = 0;
10755 gchar symbol_buffer[MAX_SYMBOL_SIZE];
10757 // Emit codeview debug info section
10758 emit_section_change (acfg, ".debug$S", 0);
10760 // Emit magic header.
10761 emit_int32 (acfg, CODEVIEW_MAGIC_HEADER);
10763 emit_codeview_compiler_info (acfg, &section_id);
10765 for (i = 0; i < acfg->nmethods; ++i) {
10766 MonoCompile *cfg = acfg->cfgs[i];
10768 if (!cfg)
10769 continue;
10771 int ret = g_snprintf (symbol_buffer, G_N_ELEMENTS (symbol_buffer), "%sme_%x", acfg->temp_prefix, i);
10772 if (ret > 0 && ret < G_N_ELEMENTS (symbol_buffer))
10773 emit_codeview_function_info (acfg, cfg->method, &section_id, cfg->asm_debug_symbol, cfg->asm_symbol, symbol_buffer);
10776 #else
10777 static void
10778 emit_codeview_info (MonoAotCompile *acfg)
10781 #endif /* EMIT_WIN32_CODEVIEW_INFO */
10783 #ifdef EMIT_WIN32_UNWIND_INFO
10784 static UnwindInfoSectionCacheItem *
10785 get_cached_unwind_info_section_item_win32 (MonoAotCompile *acfg, const char *function_start, const char *function_end, GSList *unwind_ops)
10787 UnwindInfoSectionCacheItem *item = NULL;
10789 if (!acfg->unwind_info_section_cache)
10790 acfg->unwind_info_section_cache = g_list_alloc ();
10792 PUNWIND_INFO unwind_info = mono_arch_unwindinfo_alloc_unwind_info (unwind_ops);
10794 // Search for unwind info in cache.
10795 GList *list = acfg->unwind_info_section_cache;
10796 int list_size = 0;
10797 while (list && list->data) {
10798 item = (UnwindInfoSectionCacheItem*)list->data;
10799 if (!memcmp (unwind_info, item->unwind_info, sizeof (UNWIND_INFO))) {
10800 // Cache hit, return cached item.
10801 return item;
10803 list = list->next;
10804 list_size++;
10807 // Add to cache.
10808 if (acfg->unwind_info_section_cache) {
10809 item = g_new0 (UnwindInfoSectionCacheItem, 1);
10810 if (item) {
10811 // Format .xdata section label for function, used to get unwind info address RVA.
10812 // Since the unwind info is similar for most functions, the symbol will be reused.
10813 item->xdata_section_label = g_strdup_printf ("%sunwind_%d", acfg->temp_prefix, list_size);
10815 // Cache unwind info data, used when checking cache for matching unwind info. NOTE, cache takes
10816 //over ownership of unwind info.
10817 item->unwind_info = unwind_info;
10819 // Needs to be emitted once.
10820 item->xdata_section_emitted = FALSE;
10822 // Prepend to beginning of list to speed up inserts.
10823 acfg->unwind_info_section_cache = g_list_prepend (acfg->unwind_info_section_cache, (gpointer)item);
10827 return item;
10830 static void
10831 free_unwind_info_section_cache_win32 (MonoAotCompile *acfg)
10833 GList *list = acfg->unwind_info_section_cache;
10835 while (list) {
10836 UnwindInfoSectionCacheItem *item = (UnwindInfoSectionCacheItem *)list->data;
10837 if (item) {
10838 g_free (item->xdata_section_label);
10839 mono_arch_unwindinfo_free_unwind_info (item->unwind_info);
10841 g_free (item);
10842 list->data = NULL;
10845 list = list->next;
10848 g_list_free (acfg->unwind_info_section_cache);
10849 acfg->unwind_info_section_cache = NULL;
10852 static void
10853 emit_unwind_info_data_win32 (MonoAotCompile *acfg, PUNWIND_INFO unwind_info)
10855 // Emit the unwind info struct.
10856 emit_bytes (acfg, (guint8*)unwind_info, sizeof (UNWIND_INFO) - (sizeof (UNWIND_CODE) * MONO_MAX_UNWIND_CODES));
10858 // Emit all unwind codes encoded in unwind info struct.
10859 PUNWIND_CODE current_unwind_node = &unwind_info->UnwindCode[MONO_MAX_UNWIND_CODES - unwind_info->CountOfCodes];
10860 PUNWIND_CODE last_unwind_node = &unwind_info->UnwindCode[MONO_MAX_UNWIND_CODES];
10862 while (current_unwind_node < last_unwind_node) {
10863 guint8 node_count = 0;
10864 switch (current_unwind_node->UnwindOp) {
10865 case UWOP_PUSH_NONVOL:
10866 case UWOP_ALLOC_SMALL:
10867 case UWOP_SET_FPREG:
10868 case UWOP_PUSH_MACHFRAME:
10869 node_count = 1;
10870 break;
10871 case UWOP_SAVE_NONVOL:
10872 case UWOP_SAVE_XMM128:
10873 node_count = 2;
10874 break;
10875 case UWOP_SAVE_NONVOL_FAR:
10876 case UWOP_SAVE_XMM128_FAR:
10877 node_count = 3;
10878 break;
10879 case UWOP_ALLOC_LARGE:
10880 if (current_unwind_node->OpInfo == 0)
10881 node_count = 2;
10882 else
10883 node_count = 3;
10884 break;
10885 default:
10886 g_assert (!"Unknown unwind opcode.");
10889 while (node_count > 0) {
10890 g_assert (current_unwind_node < last_unwind_node);
10892 //Emit current node.
10893 emit_bytes (acfg, (guint8*)current_unwind_node, sizeof (UNWIND_CODE));
10895 node_count--;
10896 current_unwind_node++;
10901 // Emit unwind info sections for each function. Unwind info on Windows x64 is emitted into two different sections.
10902 // .pdata includes the serialized DWORD aligned RVA's of function start, end and address of serialized
10903 // UNWIND_INFO struct emitted into .xdata, see https://msdn.microsoft.com/en-us/library/ft9x1kdx.aspx.
10904 // .xdata section includes DWORD aligned serialized version of UNWIND_INFO struct, https://msdn.microsoft.com/en-us/library/ddssxxy8.aspx.
10905 static void
10906 emit_unwind_info_sections_win32 (MonoAotCompile *acfg, const char *function_start, const char *function_end, GSList *unwind_ops)
10908 char *pdata_section_label = NULL;
10910 int temp_prefix_len = (acfg->temp_prefix != NULL) ? strlen (acfg->temp_prefix) : 0;
10911 if (strncmp (function_start, acfg->temp_prefix, temp_prefix_len)) {
10912 temp_prefix_len = 0;
10915 // Format .pdata section label for function.
10916 pdata_section_label = g_strdup_printf ("%spdata_%s", acfg->temp_prefix, function_start + temp_prefix_len);
10918 UnwindInfoSectionCacheItem *cache_item = get_cached_unwind_info_section_item_win32 (acfg, function_start, function_end, unwind_ops);
10919 g_assert (cache_item && cache_item->xdata_section_label && cache_item->unwind_info);
10921 // Emit .pdata section.
10922 emit_section_change (acfg, ".pdata", 0);
10923 emit_alignment (acfg, sizeof (DWORD));
10924 emit_label (acfg, pdata_section_label);
10926 // Emit function start address RVA.
10927 fprintf (acfg->fp, "\t.long %s@IMGREL\n", function_start);
10929 // Emit function end address RVA.
10930 fprintf (acfg->fp, "\t.long %s@IMGREL\n", function_end);
10932 // Emit unwind info address RVA.
10933 fprintf (acfg->fp, "\t.long %s@IMGREL\n", cache_item->xdata_section_label);
10935 if (!cache_item->xdata_section_emitted) {
10936 // Emit .xdata section.
10937 emit_section_change (acfg, ".xdata", 0);
10938 emit_alignment (acfg, sizeof (DWORD));
10939 emit_label (acfg, cache_item->xdata_section_label);
10941 // Emit unwind info into .xdata section.
10942 emit_unwind_info_data_win32 (acfg, cache_item->unwind_info);
10943 cache_item->xdata_section_emitted = TRUE;
10946 g_free (pdata_section_label);
10948 #endif
10950 static gboolean
10951 collect_methods (MonoAotCompile *acfg)
10953 int mindex, i;
10954 MonoImage *image = acfg->image;
10956 /* Collect methods */
10957 for (i = 0; i < image->tables [MONO_TABLE_METHOD].rows; ++i) {
10958 ERROR_DECL (error);
10959 MonoMethod *method;
10960 guint32 token = MONO_TOKEN_METHOD_DEF | (i + 1);
10962 method = mono_get_method_checked (acfg->image, token, NULL, NULL, error);
10964 if (!method) {
10965 aot_printerrf (acfg, "Failed to load method 0x%x from '%s' due to %s.\n", token, image->name, mono_error_get_message (error));
10966 aot_printerrf (acfg, "Run with MONO_LOG_LEVEL=debug for more information.\n");
10967 mono_error_cleanup (error);
10968 return FALSE;
10971 /* Load all methods eagerly to skip the slower lazy loading code */
10972 mono_class_setup_methods (method->klass);
10974 if (mono_aot_mode_is_full (&acfg->aot_opts) && method->iflags & METHOD_IMPL_ATTRIBUTE_INTERNAL_CALL) {
10975 /* Compile the wrapper instead */
10976 /* We do this here instead of add_wrappers () because it is easy to do it here */
10977 MonoMethod *wrapper = mono_marshal_get_native_wrapper (method, TRUE, TRUE);
10978 method = wrapper;
10981 /* FIXME: Some mscorlib methods don't have debug info */
10983 if (acfg->aot_opts.soft_debug && !method->wrapper_type) {
10984 if (!((method->flags & METHOD_ATTRIBUTE_PINVOKE_IMPL) ||
10985 (method->iflags & METHOD_IMPL_ATTRIBUTE_RUNTIME) ||
10986 (method->flags & METHOD_ATTRIBUTE_ABSTRACT) ||
10987 (method->iflags & METHOD_IMPL_ATTRIBUTE_INTERNAL_CALL))) {
10988 if (!mono_debug_lookup_method (method)) {
10989 fprintf (stderr, "Method %s has no debug info, probably the .mdb file for the assembly is missing.\n", mono_method_get_full_name (method));
10990 exit (1);
10996 if (method->is_generic || mono_class_is_gtd (method->klass)) {
10997 /* Compile the ref shared version instead */
10998 method = mini_get_shared_method_full (method, SHARE_MODE_NONE, error);
10999 if (!method) {
11000 aot_printerrf (acfg, "Failed to load method 0x%x from '%s' due to %s.\n", token, image->name, mono_error_get_message (error));
11001 aot_printerrf (acfg, "Run with MONO_LOG_LEVEL=debug for more information.\n");
11002 mono_error_cleanup (error);
11003 return FALSE;
11007 /* Since we add the normal methods first, their index will be equal to their zero based token index */
11008 add_method_with_index (acfg, method, i, FALSE);
11009 acfg->method_index ++;
11012 /* gsharedvt methods */
11013 for (mindex = 0; mindex < image->tables [MONO_TABLE_METHOD].rows; ++mindex) {
11014 ERROR_DECL (error);
11015 MonoMethod *method;
11016 guint32 token = MONO_TOKEN_METHOD_DEF | (mindex + 1);
11018 if (!(acfg->opts & MONO_OPT_GSHAREDVT))
11019 continue;
11021 method = mono_get_method_checked (acfg->image, token, NULL, NULL, error);
11022 report_loader_error (acfg, error, TRUE, "Failed to load method token 0x%x due to %s\n", i, mono_error_get_message (error));
11024 if (method->is_generic || mono_class_is_gtd (method->klass)) {
11025 MonoMethod *gshared;
11027 gshared = mini_get_shared_method_full (method, SHARE_MODE_GSHAREDVT, error);
11028 mono_error_assert_ok (error);
11030 add_extra_method (acfg, gshared);
11034 if (mono_aot_mode_is_full (&acfg->aot_opts) || mono_aot_mode_is_hybrid (&acfg->aot_opts))
11035 add_generic_instances (acfg);
11037 if (mono_aot_mode_is_full (&acfg->aot_opts))
11038 add_wrappers (acfg);
11039 return TRUE;
11042 static void
11043 compile_methods (MonoAotCompile *acfg)
11045 int i, methods_len;
11047 if (acfg->aot_opts.nthreads > 0) {
11048 GPtrArray *frag;
11049 int len, j;
11050 GPtrArray *threads;
11051 MonoThreadHandle *thread_handle;
11052 gpointer *user_data;
11053 MonoMethod **methods;
11055 methods_len = acfg->methods->len;
11057 len = acfg->methods->len / acfg->aot_opts.nthreads;
11058 g_assert (len > 0);
11060 * Partition the list of methods into fragments, and hand it to threads to
11061 * process.
11063 threads = g_ptr_array_new ();
11064 /* Make a copy since acfg->methods is modified by compile_method () */
11065 methods = g_new0 (MonoMethod*, methods_len);
11066 //memcpy (methods, g_ptr_array_index (acfg->methods, 0), sizeof (MonoMethod*) * methods_len);
11067 for (i = 0; i < methods_len; ++i)
11068 methods [i] = (MonoMethod *)g_ptr_array_index (acfg->methods, i);
11069 i = 0;
11070 while (i < methods_len) {
11071 ERROR_DECL (error);
11072 MonoInternalThread *thread;
11074 frag = g_ptr_array_new ();
11075 for (j = 0; j < len; ++j) {
11076 if (i < methods_len) {
11077 g_ptr_array_add (frag, methods [i]);
11078 i ++;
11082 user_data = g_new0 (gpointer, 3);
11083 user_data [0] = acfg;
11084 user_data [1] = frag;
11086 thread = mono_thread_create_internal (mono_domain_get (), compile_thread_main, (gpointer) user_data, MONO_THREAD_CREATE_FLAGS_NONE, error);
11087 mono_error_assert_ok (error);
11089 thread_handle = mono_threads_open_thread_handle (thread->handle);
11090 g_ptr_array_add (threads, thread_handle);
11092 g_free (methods);
11094 for (i = 0; i < threads->len; ++i) {
11095 mono_thread_info_wait_one_handle (g_ptr_array_index (threads, i), MONO_INFINITE_WAIT, FALSE);
11096 mono_threads_close_thread_handle (g_ptr_array_index (threads, i));
11098 } else {
11099 methods_len = 0;
11102 /* Compile methods added by compile_method () or all methods if nthreads == 0 */
11103 for (i = methods_len; i < acfg->methods->len; ++i) {
11104 /* This can add new methods to acfg->methods */
11105 compile_method (acfg, (MonoMethod *)g_ptr_array_index (acfg->methods, i));
11109 static int
11110 compile_asm (MonoAotCompile *acfg)
11112 char *command, *objfile;
11113 char *outfile_name, *tmp_outfile_name, *llvm_ofile;
11114 const char *tool_prefix = acfg->aot_opts.tool_prefix ? acfg->aot_opts.tool_prefix : "";
11115 char *ld_flags = acfg->aot_opts.ld_flags ? acfg->aot_opts.ld_flags : g_strdup("");
11117 #ifdef TARGET_WIN32_MSVC
11118 #define AS_OPTIONS "-c -x assembler"
11119 #elif defined(TARGET_AMD64) && !defined(TARGET_MACH)
11120 #define AS_OPTIONS "--64"
11121 #elif defined(TARGET_POWERPC64)
11122 #define AS_OPTIONS "-a64 -mppc64"
11123 #elif defined(sparc) && SIZEOF_VOID_P == 8
11124 #define AS_OPTIONS "-xarch=v9"
11125 #elif defined(TARGET_X86) && defined(TARGET_MACH)
11126 #define AS_OPTIONS "-arch i386"
11127 #else
11128 #define AS_OPTIONS ""
11129 #endif
11131 #if defined(TARGET_OSX)
11132 #define AS_NAME "clang"
11133 #elif defined(TARGET_WIN32_MSVC)
11134 #define AS_NAME "clang.exe"
11135 #else
11136 #define AS_NAME "as"
11137 #endif
11139 #ifdef TARGET_WIN32_MSVC
11140 #define AS_OBJECT_FILE_SUFFIX "obj"
11141 #else
11142 #define AS_OBJECT_FILE_SUFFIX "o"
11143 #endif
11145 #if defined(sparc)
11146 #define LD_NAME "ld"
11147 #define LD_OPTIONS "-shared -G"
11148 #elif defined(__ppc__) && defined(TARGET_MACH)
11149 #define LD_NAME "gcc"
11150 #define LD_OPTIONS "-dynamiclib"
11151 #elif defined(TARGET_AMD64) && defined(TARGET_MACH)
11152 #define LD_NAME "clang"
11153 #define LD_OPTIONS "--shared"
11154 #elif defined(TARGET_WIN32_MSVC)
11155 #define LD_NAME "link.exe"
11156 #define LD_OPTIONS "/DLL /MACHINE:X64 /NOLOGO /INCREMENTAL:NO"
11157 #define LD_DEBUG_OPTIONS LD_OPTIONS " /DEBUG"
11158 #elif defined(TARGET_WIN32) && !defined(TARGET_ANDROID)
11159 #define LD_NAME "gcc"
11160 #define LD_OPTIONS "-shared"
11161 #elif defined(TARGET_X86) && defined(TARGET_MACH)
11162 #define LD_NAME "clang"
11163 #define LD_OPTIONS "-m32 -dynamiclib"
11164 #elif defined(TARGET_ARM) && !defined(TARGET_ANDROID)
11165 #define LD_NAME "gcc"
11166 #define LD_OPTIONS "--shared"
11167 #elif defined(TARGET_POWERPC64)
11168 #define LD_OPTIONS "-m elf64ppc"
11169 #endif
11171 #ifndef LD_OPTIONS
11172 #define LD_OPTIONS ""
11173 #endif
11175 if (acfg->aot_opts.asm_only) {
11176 aot_printf (acfg, "Output file: '%s'.\n", acfg->tmpfname);
11177 if (acfg->aot_opts.static_link)
11178 aot_printf (acfg, "Linking symbol: '%s'.\n", acfg->static_linking_symbol);
11179 if (acfg->llvm)
11180 aot_printf (acfg, "LLVM output file: '%s'.\n", acfg->llvm_sfile);
11181 return 0;
11184 if (acfg->aot_opts.static_link) {
11185 if (acfg->aot_opts.outfile)
11186 objfile = g_strdup_printf ("%s", acfg->aot_opts.outfile);
11187 else
11188 objfile = g_strdup_printf ("%s." AS_OBJECT_FILE_SUFFIX, acfg->image->name);
11189 } else {
11190 objfile = g_strdup_printf ("%s." AS_OBJECT_FILE_SUFFIX, acfg->tmpfname);
11193 #ifdef TARGET_OSX
11194 g_string_append (acfg->as_args, "-c -x assembler");
11195 #endif
11197 command = g_strdup_printf ("\"%s%s\" %s %s -o %s %s", tool_prefix, AS_NAME, AS_OPTIONS,
11198 acfg->as_args ? acfg->as_args->str : "",
11199 wrap_path (objfile), wrap_path (acfg->tmpfname));
11200 aot_printf (acfg, "Executing the native assembler: %s\n", command);
11201 if (execute_system (command) != 0) {
11202 g_free (command);
11203 g_free (objfile);
11204 return 1;
11207 if (acfg->llvm && !acfg->llvm_owriter) {
11208 command = g_strdup_printf ("\"%s%s\" %s %s -o %s %s", tool_prefix, AS_NAME, AS_OPTIONS,
11209 acfg->as_args ? acfg->as_args->str : "",
11210 wrap_path (acfg->llvm_ofile), wrap_path (acfg->llvm_sfile));
11211 aot_printf (acfg, "Executing the native assembler: %s\n", command);
11212 if (execute_system (command) != 0) {
11213 g_free (command);
11214 g_free (objfile);
11215 return 1;
11219 g_free (command);
11221 if (acfg->aot_opts.static_link) {
11222 aot_printf (acfg, "Output file: '%s'.\n", objfile);
11223 aot_printf (acfg, "Linking symbol: '%s'.\n", acfg->static_linking_symbol);
11224 g_free (objfile);
11225 return 0;
11228 if (acfg->aot_opts.outfile)
11229 outfile_name = g_strdup_printf ("%s", acfg->aot_opts.outfile);
11230 else
11231 outfile_name = g_strdup_printf ("%s%s", acfg->image->name, MONO_SOLIB_EXT);
11233 tmp_outfile_name = g_strdup_printf ("%s.tmp", outfile_name);
11235 if (acfg->llvm) {
11236 llvm_ofile = g_strdup_printf ("\"%s\"", acfg->llvm_ofile);
11237 } else {
11238 llvm_ofile = g_strdup ("");
11241 /* replace the ; flags separators with spaces */
11242 g_strdelimit (ld_flags, ";", ' ');
11244 if (acfg->aot_opts.llvm_only)
11245 ld_flags = g_strdup_printf ("%s %s", ld_flags, "-lstdc++");
11247 #ifdef TARGET_WIN32_MSVC
11248 g_assert (tmp_outfile_name != NULL);
11249 g_assert (objfile != NULL);
11250 command = g_strdup_printf ("\"%s%s\" %s %s /OUT:\"%s\" \"%s\"", tool_prefix, LD_NAME,
11251 acfg->aot_opts.nodebug ? LD_OPTIONS : LD_DEBUG_OPTIONS, ld_flags, tmp_outfile_name, objfile);
11252 #elif defined(LD_NAME)
11253 command = g_strdup_printf ("%s%s %s -o %s %s %s %s", tool_prefix, LD_NAME, LD_OPTIONS,
11254 wrap_path (tmp_outfile_name), wrap_path (llvm_ofile),
11255 wrap_path (g_strdup_printf ("%s." AS_OBJECT_FILE_SUFFIX, acfg->tmpfname)), ld_flags);
11256 #else
11257 // Default (linux)
11258 if (acfg->aot_opts.tool_prefix) {
11259 /* Cross compiling */
11260 command = g_strdup_printf ("\"%sld\" %s -shared -o %s %s %s %s", tool_prefix, LD_OPTIONS,
11261 wrap_path (tmp_outfile_name), wrap_path (llvm_ofile),
11262 wrap_path (g_strdup_printf ("%s." AS_OBJECT_FILE_SUFFIX, acfg->tmpfname)), ld_flags);
11263 } else {
11264 char *args = g_strdup_printf ("%s -shared -o %s %s %s %s", LD_OPTIONS,
11265 wrap_path (tmp_outfile_name), wrap_path (llvm_ofile),
11266 wrap_path (g_strdup_printf ("%s." AS_OBJECT_FILE_SUFFIX, acfg->tmpfname)), ld_flags);
11268 if (acfg->aot_opts.llvm_only) {
11269 command = g_strdup_printf ("clang++ %s", args);
11270 } else {
11271 command = g_strdup_printf ("\"%sld\" %s", tool_prefix, args);
11273 g_free (args);
11275 #endif
11276 aot_printf (acfg, "Executing the native linker: %s\n", command);
11277 if (execute_system (command) != 0) {
11278 g_free (tmp_outfile_name);
11279 g_free (outfile_name);
11280 g_free (command);
11281 g_free (objfile);
11282 g_free (ld_flags);
11283 return 1;
11286 g_free (command);
11288 /*com = g_strdup_printf ("strip --strip-unneeded %s%s", acfg->image->name, MONO_SOLIB_EXT);
11289 printf ("Stripping the binary: %s\n", com);
11290 execute_system (com);
11291 g_free (com);*/
11293 #if defined(TARGET_ARM) && !defined(TARGET_MACH)
11295 * gas generates 'mapping symbols' each time code and data is mixed, which
11296 * happens a lot in emit_and_reloc_code (), so we need to get rid of them.
11298 command = g_strdup_printf ("\"%sstrip\" --strip-symbol=\\$a --strip-symbol=\\$d %s", wrap_path(tool_prefix), wrap_path(tmp_outfile_name));
11299 aot_printf (acfg, "Stripping the binary: %s\n", command);
11300 if (execute_system (command) != 0) {
11301 g_free (tmp_outfile_name);
11302 g_free (outfile_name);
11303 g_free (command);
11304 g_free (objfile);
11305 return 1;
11307 #endif
11309 if (0 != rename (tmp_outfile_name, outfile_name)) {
11310 if (G_FILE_ERROR_EXIST == g_file_error_from_errno (errno)) {
11311 /* Since we are rebuilding the module we need to be able to replace any old copies. Remove old file and retry rename operation. */
11312 unlink (outfile_name);
11313 rename (tmp_outfile_name, outfile_name);
11317 #if defined(TARGET_MACH)
11318 command = g_strdup_printf ("dsymutil \"%s\"", outfile_name);
11319 aot_printf (acfg, "Executing dsymutil: %s\n", command);
11320 if (execute_system (command) != 0) {
11321 return 1;
11323 #endif
11325 if (!acfg->aot_opts.save_temps)
11326 unlink (objfile);
11328 g_free (tmp_outfile_name);
11329 g_free (outfile_name);
11330 g_free (objfile);
11332 if (acfg->aot_opts.save_temps)
11333 aot_printf (acfg, "Retained input file.\n");
11334 else
11335 unlink (acfg->tmpfname);
11337 return 0;
11340 static guint8
11341 profread_byte (FILE *infile)
11343 guint8 i;
11344 int res;
11346 res = fread (&i, 1, 1, infile);
11347 g_assert (res == 1);
11348 return i;
11351 static int
11352 profread_int (FILE *infile)
11354 int i, res;
11356 res = fread (&i, 4, 1, infile);
11357 g_assert (res == 1);
11358 return i;
11361 static char*
11362 profread_string (FILE *infile)
11364 int len, res;
11365 char *pbuf;
11367 len = profread_int (infile);
11368 pbuf = (char*)g_malloc (len + 1);
11369 res = fread (pbuf, 1, len, infile);
11370 g_assert (res == len);
11371 pbuf [len] = '\0';
11372 return pbuf;
11375 static void
11376 load_profile_file (MonoAotCompile *acfg, char *filename)
11378 FILE *infile;
11379 char buf [1024];
11380 int res, len, version;
11381 char magic [32];
11383 infile = fopen (filename, "r");
11384 if (!infile) {
11385 fprintf (stderr, "Unable to open file '%s': %s.\n", filename, strerror (errno));
11386 exit (1);
11389 printf ("Using profile data file '%s'\n", filename);
11391 sprintf (magic, AOT_PROFILER_MAGIC);
11392 len = strlen (magic);
11393 res = fread (buf, 1, len, infile);
11394 magic [len] = '\0';
11395 buf [len] = '\0';
11396 if ((res != len) || strcmp (buf, magic) != 0) {
11397 printf ("Profile file has wrong header: '%s'.\n", buf);
11398 fclose (infile);
11399 exit (1);
11401 guint32 expected_version = (AOT_PROFILER_MAJOR_VERSION << 16) | AOT_PROFILER_MINOR_VERSION;
11402 version = profread_int (infile);
11403 if (version != expected_version) {
11404 printf ("Profile file has wrong version 0x%4x, expected 0x%4x.\n", version, expected_version);
11405 fclose (infile);
11406 exit (1);
11409 ProfileData *data = g_new0 (ProfileData, 1);
11410 data->images = g_hash_table_new (NULL, NULL);
11411 data->classes = g_hash_table_new (NULL, NULL);
11412 data->ginsts = g_hash_table_new (NULL, NULL);
11413 data->methods = g_hash_table_new (NULL, NULL);
11415 while (TRUE) {
11416 int type = profread_byte (infile);
11417 int id = profread_int (infile);
11419 if (type == AOTPROF_RECORD_NONE)
11420 break;
11422 switch (type) {
11423 case AOTPROF_RECORD_IMAGE: {
11424 ImageProfileData *idata = g_new0 (ImageProfileData, 1);
11425 idata->name = profread_string (infile);
11426 char *mvid = profread_string (infile);
11427 g_free (mvid);
11428 g_hash_table_insert (data->images, GINT_TO_POINTER (id), idata);
11429 break;
11431 case AOTPROF_RECORD_GINST: {
11432 int i;
11433 int len = profread_int (infile);
11435 GInstProfileData *gdata = g_new0 (GInstProfileData, 1);
11436 gdata->argc = len;
11437 gdata->argv = g_new0 (ClassProfileData*, len);
11439 for (i = 0; i < len; ++i) {
11440 int class_id = profread_int (infile);
11442 gdata->argv [i] = g_hash_table_lookup (data->classes, GINT_TO_POINTER (class_id));
11443 g_assert (gdata->argv [i]);
11445 g_hash_table_insert (data->ginsts, GINT_TO_POINTER (id), gdata);
11446 break;
11448 case AOTPROF_RECORD_TYPE: {
11449 int type = profread_byte (infile);
11451 switch (type) {
11452 case MONO_TYPE_CLASS: {
11453 int image_id = profread_int (infile);
11454 int ginst_id = profread_int (infile);
11455 char *class_name = profread_string (infile);
11457 ImageProfileData *image = g_hash_table_lookup (data->images, GINT_TO_POINTER (image_id));
11458 g_assert (image);
11460 char *p = strrchr (class_name, '.');
11461 g_assert (p);
11462 *p = '\0';
11464 ClassProfileData *cdata = g_new0 (ClassProfileData, 1);
11465 cdata->image = image;
11466 cdata->ns = g_strdup (class_name);
11467 cdata->name = g_strdup (p + 1);
11469 if (ginst_id != -1) {
11470 cdata->inst = g_hash_table_lookup (data->ginsts, GINT_TO_POINTER (ginst_id));
11471 g_assert (cdata->inst);
11473 g_free (class_name);
11475 g_hash_table_insert (data->classes, GINT_TO_POINTER (id), cdata);
11476 break;
11478 #if 0
11479 case MONO_TYPE_SZARRAY: {
11480 int elem_id = profread_int (infile);
11481 // FIXME:
11482 break;
11484 #endif
11485 default:
11486 g_assert_not_reached ();
11487 break;
11489 break;
11491 case AOTPROF_RECORD_METHOD: {
11492 int class_id = profread_int (infile);
11493 int ginst_id = profread_int (infile);
11494 int param_count = profread_int (infile);
11495 char *method_name = profread_string (infile);
11496 char *sig = profread_string (infile);
11498 ClassProfileData *klass = g_hash_table_lookup (data->classes, GINT_TO_POINTER (class_id));
11499 g_assert (klass);
11501 MethodProfileData *mdata = g_new0 (MethodProfileData, 1);
11502 mdata->id = id;
11503 mdata->klass = klass;
11504 mdata->name = method_name;
11505 mdata->signature = sig;
11506 mdata->param_count = param_count;
11508 if (ginst_id != -1) {
11509 mdata->inst = g_hash_table_lookup (data->ginsts, GINT_TO_POINTER (ginst_id));
11510 g_assert (mdata->inst);
11512 g_hash_table_insert (data->methods, GINT_TO_POINTER (id), mdata);
11513 break;
11515 default:
11516 printf ("%d\n", type);
11517 g_assert_not_reached ();
11518 break;
11522 fclose (infile);
11523 acfg->profile_data = g_list_append (acfg->profile_data, data);
11526 static void
11527 resolve_class (ClassProfileData *cdata);
11529 static void
11530 resolve_ginst (GInstProfileData *inst_data)
11532 int i;
11534 if (inst_data->inst)
11535 return;
11537 for (i = 0; i < inst_data->argc; ++i) {
11538 resolve_class (inst_data->argv [i]);
11539 if (!inst_data->argv [i]->klass)
11540 return;
11542 MonoType **args = g_new0 (MonoType*, inst_data->argc);
11543 for (i = 0; i < inst_data->argc; ++i)
11544 args [i] = m_class_get_byval_arg (inst_data->argv [i]->klass);
11546 inst_data->inst = mono_metadata_get_generic_inst (inst_data->argc, args);
11549 static void
11550 resolve_class (ClassProfileData *cdata)
11552 ERROR_DECL (error);
11553 MonoClass *klass;
11555 if (!cdata->image->image)
11556 return;
11558 klass = mono_class_from_name_checked (cdata->image->image, cdata->ns, cdata->name, error);
11559 if (!klass) {
11560 //printf ("[%s] %s.%s\n", cdata->image->name, cdata->ns, cdata->name);
11561 return;
11563 if (cdata->inst) {
11564 resolve_ginst (cdata->inst);
11565 if (!cdata->inst->inst)
11566 return;
11567 MonoGenericContext ctx;
11569 memset (&ctx, 0, sizeof (ctx));
11570 ctx.class_inst = cdata->inst->inst;
11571 cdata->klass = mono_class_inflate_generic_class_checked (klass, &ctx, error);
11572 } else {
11573 cdata->klass = klass;
11578 * Resolve the profile data to the corresponding loaded classes/methods etc. if possible.
11580 static void
11581 resolve_profile_data (MonoAotCompile *acfg, ProfileData *data)
11583 GHashTableIter iter;
11584 gpointer key, value;
11585 int i;
11587 if (!data)
11588 return;
11590 /* Images */
11591 GPtrArray *assemblies = mono_domain_get_assemblies (mono_get_root_domain (), FALSE);
11592 g_hash_table_iter_init (&iter, data->images);
11593 while (g_hash_table_iter_next (&iter, &key, &value)) {
11594 ImageProfileData *idata = (ImageProfileData*)value;
11596 for (i = 0; i < assemblies->len; ++i) {
11597 MonoAssembly *ass = g_ptr_array_index (assemblies, i);
11599 if (!strcmp (ass->aname.name, idata->name)) {
11600 idata->image = ass->image;
11601 break;
11605 g_ptr_array_free (assemblies, TRUE);
11607 /* Classes */
11608 g_hash_table_iter_init (&iter, data->classes);
11609 while (g_hash_table_iter_next (&iter, &key, &value)) {
11610 ClassProfileData *cdata = (ClassProfileData*)value;
11612 if (!cdata->image->image) {
11613 if (acfg->aot_opts.verbose)
11614 printf ("Unable to load class '%s.%s' because its image '%s' is not loaded.\n", cdata->ns, cdata->name, cdata->image->name);
11615 continue;
11618 resolve_class (cdata);
11620 if (cdata->klass)
11621 printf ("%s %s %s\n", cdata->ns, cdata->name, mono_class_full_name (cdata->klass));
11625 /* Methods */
11626 g_hash_table_iter_init (&iter, data->methods);
11627 while (g_hash_table_iter_next (&iter, &key, &value)) {
11628 MethodProfileData *mdata = (MethodProfileData*)value;
11629 MonoClass *klass;
11630 MonoMethod *m;
11631 gpointer miter;
11633 resolve_class (mdata->klass);
11634 klass = mdata->klass->klass;
11635 if (!klass) {
11636 if (acfg->aot_opts.verbose)
11637 printf ("Unable to load method '%s' because its class '%s.%s' is not loaded.\n", mdata->name, mdata->klass->ns, mdata->klass->name);
11638 continue;
11640 miter = NULL;
11641 while ((m = mono_class_get_methods (klass, &miter))) {
11642 ERROR_DECL (error);
11644 if (strcmp (m->name, mdata->name))
11645 continue;
11646 MonoMethodSignature *sig = mono_method_signature (m);
11647 if (!sig)
11648 continue;
11649 if (sig->param_count != mdata->param_count)
11650 continue;
11651 if (mdata->inst) {
11652 resolve_ginst (mdata->inst);
11653 if (!mdata->inst->inst)
11654 continue;
11655 MonoGenericContext ctx;
11657 memset (&ctx, 0, sizeof (ctx));
11658 ctx.method_inst = mdata->inst->inst;
11660 m = mono_class_inflate_generic_method_checked (m, &ctx, error);
11661 if (!m)
11662 continue;
11663 sig = mono_method_signature_checked (m, error);
11664 if (!is_ok (error)) {
11665 mono_error_cleanup (error);
11666 continue;
11669 char *sig_str = mono_signature_full_name (sig);
11670 gboolean match = !strcmp (sig_str, mdata->signature);
11671 g_free (sig_str);
11672 if (!match)
11674 continue;
11675 //printf ("%s\n", mono_method_full_name (m, 1));
11676 mdata->method = m;
11677 break;
11679 if (!mdata->method) {
11680 if (acfg->aot_opts.verbose)
11681 printf ("Unable to load method '%s' from class '%s', not found.\n", mdata->name, mono_class_full_name (klass));
11686 static gboolean
11687 inst_references_image (MonoGenericInst *inst, MonoImage *image)
11689 int i;
11691 for (i = 0; i < inst->type_argc; ++i) {
11692 MonoClass *k = mono_class_from_mono_type (inst->type_argv [i]);
11693 if (m_class_get_image (k) == image)
11694 return TRUE;
11695 if (mono_class_is_ginst (k)) {
11696 MonoGenericInst *kinst = mono_class_get_context (k)->class_inst;
11697 if (inst_references_image (kinst, image))
11698 return TRUE;
11701 return FALSE;
11704 static gboolean
11705 is_local_inst (MonoGenericInst *inst, MonoImage *image)
11707 int i;
11709 for (i = 0; i < inst->type_argc; ++i) {
11710 MonoClass *k = mono_class_from_mono_type (inst->type_argv [i]);
11711 if (!MONO_TYPE_IS_PRIMITIVE (inst->type_argv [i]) && m_class_get_image (k) != image)
11712 return FALSE;
11714 return TRUE;
11717 static void
11718 add_profile_instances (MonoAotCompile *acfg, ProfileData *data)
11720 GHashTableIter iter;
11721 gpointer key, value;
11722 int count = 0;
11724 if (!data)
11725 return;
11727 if (acfg->aot_opts.profile_only) {
11728 /* Add methods referenced by the profile */
11729 g_hash_table_iter_init (&iter, data->methods);
11730 while (g_hash_table_iter_next (&iter, &key, &value)) {
11731 MethodProfileData *mdata = (MethodProfileData*)value;
11732 MonoMethod *m = mdata->method;
11734 if (!m)
11735 continue;
11736 if (m->is_inflated)
11737 continue;
11738 add_extra_method (acfg, m);
11739 g_hash_table_insert (acfg->profile_methods, m, m);
11740 count ++;
11745 * Add method instances 'related' to this assembly to the AOT image.
11747 g_hash_table_iter_init (&iter, data->methods);
11748 while (g_hash_table_iter_next (&iter, &key, &value)) {
11749 MethodProfileData *mdata = (MethodProfileData*)value;
11750 MonoMethod *m = mdata->method;
11751 MonoGenericContext *ctx;
11753 if (!m)
11754 continue;
11755 if (!m->is_inflated)
11756 continue;
11758 ctx = mono_method_get_context (m);
11759 /* For simplicity, add instances which reference the assembly we are compiling */
11760 if (((ctx->class_inst && inst_references_image (ctx->class_inst, acfg->image)) ||
11761 (ctx->method_inst && inst_references_image (ctx->method_inst, acfg->image))) &&
11762 !mono_method_is_generic_sharable_full (m, FALSE, FALSE, FALSE)) {
11763 //printf ("%s\n", mono_method_full_name (m, TRUE));
11764 add_extra_method (acfg, m);
11765 count ++;
11766 } else if (m_class_get_image (m->klass) == acfg->image &&
11767 ((ctx->class_inst && is_local_inst (ctx->class_inst, acfg->image)) ||
11768 (ctx->method_inst && is_local_inst (ctx->method_inst, acfg->image))) &&
11769 !mono_method_is_generic_sharable_full (m, FALSE, FALSE, FALSE)) {
11770 /* Add instances where the gtd is in the assembly and its inflated with types from this assembly or corlib */
11771 //printf ("%s\n", mono_method_full_name (m, TRUE));
11772 add_extra_method (acfg, m);
11773 count ++;
11776 * FIXME: We might skip some instances, for example:
11777 * Foo<Bar> won't be compiled when compiling Foo's assembly since it doesn't match the first case,
11778 * and it won't be compiled when compiling Bar's assembly if Foo's assembly is not loaded.
11782 printf ("Added %d methods from profile.\n", count);
11785 static void
11786 init_got_info (GotInfo *info)
11788 int i;
11790 info->patch_to_got_offset = g_hash_table_new (mono_patch_info_hash, mono_patch_info_equal);
11791 info->patch_to_got_offset_by_type = g_new0 (GHashTable*, MONO_PATCH_INFO_NUM);
11792 for (i = 0; i < MONO_PATCH_INFO_NUM; ++i)
11793 info->patch_to_got_offset_by_type [i] = g_hash_table_new (mono_patch_info_hash, mono_patch_info_equal);
11794 info->got_patches = g_ptr_array_new ();
11797 static MonoAotCompile*
11798 acfg_create (MonoAssembly *ass, guint32 opts)
11800 MonoImage *image = ass->image;
11801 MonoAotCompile *acfg;
11803 acfg = g_new0 (MonoAotCompile, 1);
11804 acfg->methods = g_ptr_array_new ();
11805 acfg->method_indexes = g_hash_table_new (NULL, NULL);
11806 acfg->method_depth = g_hash_table_new (NULL, NULL);
11807 acfg->plt_offset_to_entry = g_hash_table_new (NULL, NULL);
11808 acfg->patch_to_plt_entry = g_new0 (GHashTable*, MONO_PATCH_INFO_NUM);
11809 acfg->method_to_cfg = g_hash_table_new (NULL, NULL);
11810 acfg->token_info_hash = g_hash_table_new_full (NULL, NULL, NULL, NULL);
11811 acfg->method_to_pinvoke_import = g_hash_table_new_full (NULL, NULL, NULL, g_free);
11812 acfg->image_hash = g_hash_table_new (NULL, NULL);
11813 acfg->image_table = g_ptr_array_new ();
11814 acfg->globals = g_ptr_array_new ();
11815 acfg->image = image;
11816 acfg->opts = opts;
11817 /* TODO: Write out set of SIMD instructions used, rather than just those available */
11818 acfg->simd_opts = mono_arch_cpu_enumerate_simd_versions ();
11819 acfg->mempool = mono_mempool_new ();
11820 acfg->extra_methods = g_ptr_array_new ();
11821 acfg->unwind_info_offsets = g_hash_table_new (NULL, NULL);
11822 acfg->unwind_ops = g_ptr_array_new ();
11823 acfg->method_label_hash = g_hash_table_new_full (g_str_hash, g_str_equal, g_free, NULL);
11824 acfg->method_order = g_ptr_array_new ();
11825 acfg->export_names = g_hash_table_new (NULL, NULL);
11826 acfg->klass_blob_hash = g_hash_table_new (NULL, NULL);
11827 acfg->method_blob_hash = g_hash_table_new (NULL, NULL);
11828 acfg->plt_entry_debug_sym_cache = g_hash_table_new (g_str_hash, g_str_equal);
11829 acfg->gsharedvt_in_signatures = g_hash_table_new ((GHashFunc)mono_signature_hash, (GEqualFunc)mono_metadata_signature_equal);
11830 acfg->gsharedvt_out_signatures = g_hash_table_new ((GHashFunc)mono_signature_hash, (GEqualFunc)mono_metadata_signature_equal);
11831 acfg->profile_methods = g_hash_table_new (NULL, NULL);
11832 mono_os_mutex_init_recursive (&acfg->mutex);
11834 init_got_info (&acfg->got_info);
11835 init_got_info (&acfg->llvm_got_info);
11837 return acfg;
11840 static void
11841 got_info_free (GotInfo *info)
11843 int i;
11845 for (i = 0; i < MONO_PATCH_INFO_NUM; ++i)
11846 g_hash_table_destroy (info->patch_to_got_offset_by_type [i]);
11847 g_free (info->patch_to_got_offset_by_type);
11848 g_hash_table_destroy (info->patch_to_got_offset);
11849 g_ptr_array_free (info->got_patches, TRUE);
11852 static void
11853 acfg_free (MonoAotCompile *acfg)
11855 int i;
11857 mono_img_writer_destroy (acfg->w);
11858 for (i = 0; i < acfg->nmethods; ++i)
11859 if (acfg->cfgs [i])
11860 mono_destroy_compile (acfg->cfgs [i]);
11862 g_free (acfg->cfgs);
11864 g_free (acfg->static_linking_symbol);
11865 g_free (acfg->got_symbol);
11866 g_free (acfg->plt_symbol);
11867 g_ptr_array_free (acfg->methods, TRUE);
11868 g_ptr_array_free (acfg->image_table, TRUE);
11869 g_ptr_array_free (acfg->globals, TRUE);
11870 g_ptr_array_free (acfg->unwind_ops, TRUE);
11871 g_hash_table_destroy (acfg->method_indexes);
11872 g_hash_table_destroy (acfg->method_depth);
11873 g_hash_table_destroy (acfg->plt_offset_to_entry);
11874 for (i = 0; i < MONO_PATCH_INFO_NUM; ++i) {
11875 if (acfg->patch_to_plt_entry [i])
11876 g_hash_table_destroy (acfg->patch_to_plt_entry [i]);
11878 g_free (acfg->patch_to_plt_entry);
11879 g_hash_table_destroy (acfg->method_to_cfg);
11880 g_hash_table_destroy (acfg->token_info_hash);
11881 g_hash_table_destroy (acfg->method_to_pinvoke_import);
11882 g_hash_table_destroy (acfg->image_hash);
11883 g_hash_table_destroy (acfg->unwind_info_offsets);
11884 g_hash_table_destroy (acfg->method_label_hash);
11885 if (acfg->typespec_classes)
11886 g_hash_table_destroy (acfg->typespec_classes);
11887 g_hash_table_destroy (acfg->export_names);
11888 g_hash_table_destroy (acfg->plt_entry_debug_sym_cache);
11889 g_hash_table_destroy (acfg->klass_blob_hash);
11890 g_hash_table_destroy (acfg->method_blob_hash);
11891 got_info_free (&acfg->got_info);
11892 got_info_free (&acfg->llvm_got_info);
11893 arch_free_unwind_info_section_cache (acfg);
11894 mono_mempool_destroy (acfg->mempool);
11895 g_free (acfg);
11898 #define WRAPPER(e,n) n,
11899 static const char* const
11900 wrapper_type_names [MONO_WRAPPER_NUM + 1] = {
11901 #include "mono/metadata/wrapper-types.h"
11902 NULL
11905 static G_GNUC_UNUSED const char*
11906 get_wrapper_type_name (int type)
11908 return wrapper_type_names [type];
11911 //#define DUMP_PLT
11912 //#define DUMP_GOT
11914 static void aot_dump (MonoAotCompile *acfg)
11916 FILE *dumpfile;
11917 char * dumpname;
11919 JsonWriter writer;
11920 mono_json_writer_init (&writer);
11922 mono_json_writer_object_begin(&writer);
11924 // Methods
11925 mono_json_writer_indent (&writer);
11926 mono_json_writer_object_key(&writer, "methods");
11927 mono_json_writer_array_begin (&writer);
11929 int i;
11930 for (i = 0; i < acfg->nmethods; ++i) {
11931 MonoCompile *cfg;
11932 MonoMethod *method;
11933 MonoClass *klass;
11935 cfg = acfg->cfgs [i];
11936 if (ignore_cfg (cfg))
11937 continue;
11939 method = cfg->orig_method;
11941 mono_json_writer_indent (&writer);
11942 mono_json_writer_object_begin(&writer);
11944 mono_json_writer_indent (&writer);
11945 mono_json_writer_object_key(&writer, "name");
11946 mono_json_writer_printf (&writer, "\"%s\",\n", method->name);
11948 mono_json_writer_indent (&writer);
11949 mono_json_writer_object_key(&writer, "signature");
11950 mono_json_writer_printf (&writer, "\"%s\",\n", mono_method_get_full_name (method));
11952 mono_json_writer_indent (&writer);
11953 mono_json_writer_object_key(&writer, "code_size");
11954 mono_json_writer_printf (&writer, "\"%d\",\n", cfg->code_size);
11956 klass = method->klass;
11958 mono_json_writer_indent (&writer);
11959 mono_json_writer_object_key(&writer, "class");
11960 mono_json_writer_printf (&writer, "\"%s\",\n", m_class_get_name (klass));
11962 mono_json_writer_indent (&writer);
11963 mono_json_writer_object_key(&writer, "namespace");
11964 mono_json_writer_printf (&writer, "\"%s\",\n", m_class_get_name_space (klass));
11966 mono_json_writer_indent (&writer);
11967 mono_json_writer_object_key(&writer, "wrapper_type");
11968 mono_json_writer_printf (&writer, "\"%s\",\n", get_wrapper_type_name(method->wrapper_type));
11970 mono_json_writer_indent_pop (&writer);
11971 mono_json_writer_indent (&writer);
11972 mono_json_writer_object_end (&writer);
11973 mono_json_writer_printf (&writer, ",\n");
11976 mono_json_writer_indent_pop (&writer);
11977 mono_json_writer_indent (&writer);
11978 mono_json_writer_array_end (&writer);
11979 mono_json_writer_printf (&writer, ",\n");
11981 // PLT entries
11982 #ifdef DUMP_PLT
11983 mono_json_writer_indent_push (&writer);
11984 mono_json_writer_indent (&writer);
11985 mono_json_writer_object_key(&writer, "plt");
11986 mono_json_writer_array_begin (&writer);
11988 for (i = 0; i < acfg->plt_offset; ++i) {
11989 MonoPltEntry *plt_entry = NULL;
11990 MonoJumpInfo *ji;
11992 if (i == 0)
11994 * The first plt entry is unused.
11996 continue;
11998 plt_entry = g_hash_table_lookup (acfg->plt_offset_to_entry, GUINT_TO_POINTER (i));
11999 ji = plt_entry->ji;
12001 mono_json_writer_indent (&writer);
12002 mono_json_writer_printf (&writer, "{ ");
12003 mono_json_writer_object_key(&writer, "symbol");
12004 mono_json_writer_printf (&writer, "\"%s\" },\n", plt_entry->symbol);
12007 mono_json_writer_indent_pop (&writer);
12008 mono_json_writer_indent (&writer);
12009 mono_json_writer_array_end (&writer);
12010 mono_json_writer_printf (&writer, ",\n");
12011 #endif
12013 // GOT entries
12014 #ifdef DUMP_GOT
12015 mono_json_writer_indent_push (&writer);
12016 mono_json_writer_indent (&writer);
12017 mono_json_writer_object_key(&writer, "got");
12018 mono_json_writer_array_begin (&writer);
12020 mono_json_writer_indent_push (&writer);
12021 for (i = 0; i < acfg->got_info.got_patches->len; ++i) {
12022 MonoJumpInfo *ji = g_ptr_array_index (acfg->got_info.got_patches, i);
12024 mono_json_writer_indent (&writer);
12025 mono_json_writer_printf (&writer, "{ ");
12026 mono_json_writer_object_key(&writer, "patch_name");
12027 mono_json_writer_printf (&writer, "\"%s\" },\n", get_patch_name (ji->type));
12030 mono_json_writer_indent_pop (&writer);
12031 mono_json_writer_indent (&writer);
12032 mono_json_writer_array_end (&writer);
12033 mono_json_writer_printf (&writer, ",\n");
12034 #endif
12036 mono_json_writer_indent_pop (&writer);
12037 mono_json_writer_indent (&writer);
12038 mono_json_writer_object_end (&writer);
12040 dumpname = g_strdup_printf ("%s.json", g_path_get_basename (acfg->image->name));
12041 dumpfile = fopen (dumpname, "w+");
12042 g_free (dumpname);
12044 fprintf (dumpfile, "%s", writer.text->str);
12045 fclose (dumpfile);
12047 mono_json_writer_destroy (&writer);
12050 static const char *preinited_jit_icalls[] = {
12051 "mono_aot_init_llvm_method",
12052 "mono_aot_init_gshared_method_this",
12053 "mono_aot_init_gshared_method_mrgctx",
12054 "mono_aot_init_gshared_method_vtable",
12055 "mono_llvm_throw_corlib_exception",
12056 "mono_init_vtable_slot",
12057 "mono_helper_ldstr_mscorlib"
12060 static void
12061 add_preinit_got_slots (MonoAotCompile *acfg)
12063 MonoJumpInfo *ji;
12064 int i;
12067 * Allocate the first few GOT entries to information which is needed frequently, or it is needed
12068 * during method initialization etc.
12071 ji = (MonoJumpInfo *)mono_mempool_alloc0 (acfg->mempool, sizeof (MonoJumpInfo));
12072 ji->type = MONO_PATCH_INFO_IMAGE;
12073 ji->data.image = acfg->image;
12074 get_got_offset (acfg, FALSE, ji);
12075 get_got_offset (acfg, TRUE, ji);
12077 ji = (MonoJumpInfo *)mono_mempool_alloc0 (acfg->mempool, sizeof (MonoJumpInfo));
12078 ji->type = MONO_PATCH_INFO_MSCORLIB_GOT_ADDR;
12079 get_got_offset (acfg, FALSE, ji);
12080 get_got_offset (acfg, TRUE, ji);
12082 ji = (MonoJumpInfo *)mono_mempool_alloc0 (acfg->mempool, sizeof (MonoJumpInfo));
12083 ji->type = MONO_PATCH_INFO_GC_CARD_TABLE_ADDR;
12084 get_got_offset (acfg, FALSE, ji);
12085 get_got_offset (acfg, TRUE, ji);
12087 ji = (MonoJumpInfo *)mono_mempool_alloc0 (acfg->mempool, sizeof (MonoJumpInfo));
12088 ji->type = MONO_PATCH_INFO_GC_NURSERY_START;
12089 get_got_offset (acfg, FALSE, ji);
12090 get_got_offset (acfg, TRUE, ji);
12092 ji = (MonoJumpInfo *)mono_mempool_alloc0 (acfg->mempool, sizeof (MonoJumpInfo));
12093 ji->type = MONO_PATCH_INFO_AOT_MODULE;
12094 get_got_offset (acfg, FALSE, ji);
12095 get_got_offset (acfg, TRUE, ji);
12097 ji = (MonoJumpInfo *)mono_mempool_alloc0 (acfg->mempool, sizeof (MonoJumpInfo));
12098 ji->type = MONO_PATCH_INFO_GC_NURSERY_BITS;
12099 get_got_offset (acfg, FALSE, ji);
12100 get_got_offset (acfg, TRUE, ji);
12102 for (i = 0; i < TLS_KEY_NUM; i++) {
12103 ji = (MonoJumpInfo *)mono_mempool_alloc0 (acfg->mempool, sizeof (MonoJumpInfo));
12104 ji->type = MONO_PATCH_INFO_GET_TLS_TRAMP;
12105 ji->data.index = i;
12106 get_got_offset (acfg, FALSE, ji);
12107 get_got_offset (acfg, TRUE, ji);
12109 ji = (MonoJumpInfo *)mono_mempool_alloc0 (acfg->mempool, sizeof (MonoJumpInfo));
12110 ji->type = MONO_PATCH_INFO_SET_TLS_TRAMP;
12111 ji->data.index = i;
12112 get_got_offset (acfg, FALSE, ji);
12113 get_got_offset (acfg, TRUE, ji);
12116 ji = (MonoJumpInfo *)mono_mempool_alloc0 (acfg->mempool, sizeof (MonoJumpInfo));
12117 ji->type = MONO_PATCH_INFO_JIT_THREAD_ATTACH;
12118 get_got_offset (acfg, FALSE, ji);
12119 get_got_offset (acfg, TRUE, ji);
12121 /* Called by native-to-managed wrappers on possibly unattached threads */
12122 ji = (MonoJumpInfo *)mono_mempool_alloc0 (acfg->mempool, sizeof (MonoJumpInfo));
12123 ji->type = MONO_PATCH_INFO_JIT_ICALL_ADDR_NOCALL;
12124 ji->data.name = "mono_threads_attach_coop";
12125 get_got_offset (acfg, FALSE, ji);
12126 get_got_offset (acfg, TRUE, ji);
12128 for (i = 0; i < sizeof (preinited_jit_icalls) / sizeof (char*); ++i) {
12129 ji = (MonoJumpInfo *)mono_mempool_alloc0 (acfg->mempool, sizeof (MonoAotCompile));
12130 ji->type = MONO_PATCH_INFO_INTERNAL_METHOD;
12131 ji->data.name = preinited_jit_icalls [i];
12132 get_got_offset (acfg, FALSE, ji);
12133 get_got_offset (acfg, TRUE, ji);
12136 acfg->nshared_got_entries = acfg->got_offset;
12139 static void
12140 mono_dedup_log_stats (MonoAotCompile *acfg)
12142 GHashTableIter iter;
12143 g_assert (acfg->dedup_stats);
12145 // If dedup_emit_mode, acfg is the dummy dedup module that consolidates
12146 // deduped modules
12147 g_hash_table_iter_init (&iter, acfg->method_to_cfg);
12148 MonoCompile *dcfg = NULL;
12149 MonoMethod *method = NULL;
12151 size_t wrappers_size_saved = 0;
12152 size_t inflated_size_saved = 0;
12153 size_t copied_singles = 0;
12155 while (g_hash_table_iter_next (&iter, (gpointer *) &method, (gpointer *)&dcfg)) {
12156 gchar *dedup_name = mono_aot_get_mangled_method_name (method);
12157 guint count = GPOINTER_TO_UINT(g_hash_table_lookup (acfg->dedup_stats, dedup_name));
12159 if (count == 0)
12160 continue;
12162 if (acfg->dedup_emit_mode) {
12163 // Size *saved* is the size due to things not emitted.
12164 if (count < 2) {
12165 // Just moved, didn't save space / dedup
12166 copied_singles += dcfg->code_len;
12167 } else if (method->wrapper_type != MONO_WRAPPER_NONE) {
12168 wrappers_size_saved += dcfg->code_len * (count - 1);
12169 } else {
12170 inflated_size_saved += dcfg->code_len * (count - 1);
12173 if (acfg->aot_opts.dedup) {
12174 if (method->wrapper_type != MONO_WRAPPER_NONE) {
12175 wrappers_size_saved += dcfg->code_len * count;
12176 } else {
12177 inflated_size_saved += dcfg->code_len * count;
12182 aot_printf (acfg, "Dedup Pass: Size Saved From Deduped Wrappers:\t%zu bytes\n", wrappers_size_saved);
12183 aot_printf (acfg, "Dedup Pass: Size Saved From Inflated Methods:\t%zu bytes\n", inflated_size_saved);
12184 if (acfg->dedup_emit_mode)
12185 aot_printf (acfg, "Dedup Pass: Size of Moved But Not Deduped (only 1 copy) Methods:\t%zu bytes\n", copied_singles);
12187 g_hash_table_destroy (acfg->dedup_stats);
12188 acfg->dedup_stats = NULL;
12191 // Flush the cache to tell future calls what to skip
12192 static void
12193 mono_flush_method_cache (MonoAotCompile *acfg)
12195 GHashTable *method_cache = acfg->dedup_cache;
12196 char *filename = g_strdup_printf ("%s.dedup", acfg->image->name);
12197 if (!acfg->dedup_cache_changed || !acfg->aot_opts.dedup) {
12198 g_free (filename);
12199 return;
12202 acfg->dedup_cache = NULL;
12204 FILE *cache = fopen (filename, "w");
12206 if (!cache)
12207 g_error ("Could not create cache at %s because of error: %s\n", filename, strerror (errno));
12209 GHashTableIter iter;
12210 gchar *name = NULL;
12211 g_hash_table_iter_init (&iter, method_cache);
12212 gboolean cont = TRUE;
12213 while (cont && g_hash_table_iter_next (&iter, (gpointer *) &name, NULL)) {
12214 int res = fprintf (cache, "%s\n", name);
12215 cont = res >= 0;
12217 // FIXME: don't assert if error when flushing
12218 g_assert (cont);
12220 fclose (cache);
12221 g_free (filename);
12223 // The keys are all in the imageset, nothing to free
12224 // Values are just pointers to memory owned elsewhere, or sentinels
12225 g_hash_table_destroy (method_cache);
12228 // Read in what has been emitted by previous invocations,
12229 // what can be skipped
12230 static void
12231 mono_read_method_cache (MonoAotCompile *acfg)
12233 char *filename = g_strdup_printf ("%s.dedup", acfg->image->name);
12234 // Only do once, when dedup_cache is null
12235 if (acfg->dedup_cache)
12236 goto early_exit;
12238 if (acfg->aot_opts.dedup_include || acfg->aot_opts.dedup)
12239 g_assert (acfg->dedup_stats);
12241 // only in skip mode
12242 if (!acfg->aot_opts.dedup)
12243 goto early_exit;
12245 g_assert (acfg->dedup_cache);
12247 FILE *cache = fopen (filename, "r");
12248 if (!cache)
12249 goto early_exit;
12251 // Since we do pointer comparisons, and it can't be allocated at
12252 // the address 0x1 due to alignment, we use this as a sentinel
12253 gpointer other_acfg_sentinel = GINT_TO_POINTER (0x1);
12255 if (fseek (cache, 0L, SEEK_END))
12256 goto cleanup;
12258 size_t fileLength = ftell (cache);
12259 g_assert (fileLength > 0);
12261 if (fseek (cache, 0L, SEEK_SET))
12262 goto cleanup;
12264 // Avoid thousands of new malloc entries
12265 // FIXME: allocate into imageset, so we don't need to free.
12266 // put the other mangled names there too.
12267 char *bulk = g_malloc0 (fileLength * sizeof (char));
12268 size_t offset = 0;
12270 while (fgets (&bulk [offset], fileLength - offset, cache)) {
12271 // strip newline
12272 char *line = &bulk [offset];
12273 size_t len = strlen (line);
12274 if (len == 0)
12275 break;
12277 if (len >= 0 && line [len] == '\n')
12278 line [len] = '\0';
12279 offset += strlen (line) + 1;
12280 g_assert (fileLength >= offset);
12282 g_hash_table_insert (acfg->dedup_cache, line, other_acfg_sentinel);
12285 cleanup:
12286 fclose (cache);
12288 early_exit:
12289 g_free (filename);
12290 return;
12293 typedef struct {
12294 GHashTable *cache;
12295 GHashTable *stats;
12296 gboolean emit_inflated_methods;
12297 MonoAssembly *inflated_assembly;
12298 } MonoAotState;
12300 static MonoAotState *
12301 alloc_aot_state (void)
12303 MonoAotState *state = g_malloc (sizeof (MonoAotState));
12304 // FIXME: Should this own the memory?
12305 state->cache = g_hash_table_new (g_str_hash, g_str_equal);
12306 state->stats = g_hash_table_new (g_str_hash, g_str_equal);
12307 // Start in "collect mode"
12308 state->emit_inflated_methods = FALSE;
12309 state->inflated_assembly = NULL;
12310 return state;
12313 static void
12314 free_aot_state (MonoAotState *astate)
12316 g_hash_table_destroy (astate->cache);
12317 g_free (astate);
12320 static void
12321 mono_add_deferred_extra_methods (MonoAotCompile *acfg, MonoAotState *astate)
12323 GHashTableIter iter;
12324 gchar *name = NULL;
12325 MonoMethod *method = NULL;
12327 acfg->dedup_emit_mode = TRUE;
12329 g_hash_table_iter_init (&iter, astate->cache);
12330 while (g_hash_table_iter_next (&iter, (gpointer *) &name, (gpointer *) &method)) {
12331 add_method_full (acfg, method, TRUE, 0);
12333 return;
12336 static void
12337 mono_setup_dedup_state (MonoAotCompile *acfg, MonoAotState **global_aot_state, MonoAssembly *ass, MonoAotState **astate, gboolean *is_dedup_dummy)
12339 if (!acfg->aot_opts.dedup_include && !acfg->aot_opts.dedup)
12340 return;
12342 if (global_aot_state && *global_aot_state && acfg->aot_opts.dedup_include) {
12343 // Thread the state through when making the inflate pass
12344 *astate = *global_aot_state;
12347 if (!*astate) {
12348 *astate = alloc_aot_state ();
12349 *global_aot_state = *astate;
12352 acfg->dedup_cache = (*astate)->cache;
12353 acfg->dedup_stats = (*astate)->stats;
12355 // fills out acfg->dedup_cache
12356 if (acfg->aot_opts.dedup)
12357 mono_read_method_cache (acfg);
12359 if (!(*astate)->inflated_assembly && acfg->aot_opts.dedup_include) {
12360 gchar **asm_path = g_strsplit (ass->image->name, G_DIR_SEPARATOR_S, 0);
12361 gchar *asm_file = NULL;
12363 // Get the last part of the path, the filename
12364 for (int i=0; asm_path [i] != NULL; i++)
12365 asm_file = asm_path [i];
12367 if (!strcmp (acfg->aot_opts.dedup_include, asm_file)) {
12368 // Save
12369 *is_dedup_dummy = TRUE;
12370 (*astate)->inflated_assembly = ass;
12372 g_strfreev (asm_path);
12373 } else if ((*astate)->inflated_assembly) {
12374 *is_dedup_dummy = (ass == (*astate)->inflated_assembly);
12378 int
12379 mono_compile_deferred_assemblies (guint32 opts, const char *aot_options, gpointer **aot_state)
12381 // create assembly, loop and add extra_methods
12382 // in add_generic_instances , rip out what's in that for loop
12383 // and apply that to this aot_state inside of mono_compile_assembly
12384 MonoAotState *astate;
12385 astate = *(MonoAotState **)aot_state;
12386 g_assert (astate);
12388 // FIXME: allow suffixes?
12389 if (!astate->inflated_assembly) {
12390 char *inflate = strstr (aot_options, "dedup-inflate");
12391 if (!inflate)
12392 return 0;
12393 else
12394 g_error ("Error: mono was not given an assembly with the provided inflate name\n");
12397 // Switch modes
12398 astate->emit_inflated_methods = TRUE;
12400 int res = mono_compile_assembly (astate->inflated_assembly, opts, aot_options, aot_state);
12402 *aot_state = NULL;
12403 free_aot_state (astate);
12405 return res;
12408 static const char* interp_in_static_sigs[] = {
12409 "bool ptr int32 ptr&",
12410 "bool ptr ptr&",
12411 "int32 int32 ptr&",
12412 "int32 int32 ptr ptr&",
12413 "int32 ptr int32 ptr",
12414 "int32 ptr int32 ptr&",
12415 "int32 ptr ptr&",
12416 "object object ptr ptr ptr",
12417 "object",
12418 "ptr int32 ptr&",
12419 "ptr ptr int32 ptr ptr ptr&",
12420 "ptr ptr int32 ptr ptr&",
12421 "ptr ptr int32 ptr&",
12422 "ptr ptr ptr int32 ptr&",
12423 "ptr ptr ptr ptr& ptr&",
12424 "ptr ptr ptr ptr ptr&",
12425 "ptr ptr ptr ptr&",
12426 "ptr ptr ptr&",
12427 "ptr ptr uint32 ptr&",
12428 "ptr uint32 ptr&",
12429 "void object ptr ptr ptr",
12430 "void ptr ptr int32 ptr ptr& ptr ptr&",
12431 "void ptr ptr int32 ptr ptr&",
12432 "void ptr ptr ptr&",
12433 "void ptr ptr&",
12434 "void ptr",
12435 "void int32 ptr&",
12436 "void uint32 ptr&",
12437 "void"
12441 mono_compile_assembly (MonoAssembly *ass, guint32 opts, const char *aot_options, gpointer **global_aot_state)
12443 MonoImage *image = ass->image;
12444 int i, res;
12445 gint64 all_sizes;
12446 MonoAotCompile *acfg;
12447 char *outfile_name, *tmp_outfile_name, *p;
12448 char llvm_stats_msg [256];
12449 TV_DECLARE (atv);
12450 TV_DECLARE (btv);
12452 acfg = acfg_create (ass, opts);
12454 memset (&acfg->aot_opts, 0, sizeof (acfg->aot_opts));
12455 acfg->aot_opts.write_symbols = TRUE;
12456 acfg->aot_opts.ntrampolines = 4096;
12457 acfg->aot_opts.nrgctx_trampolines = 4096;
12458 acfg->aot_opts.nimt_trampolines = 512;
12459 acfg->aot_opts.nrgctx_fetch_trampolines = 128;
12460 acfg->aot_opts.ngsharedvt_arg_trampolines = 512;
12461 acfg->aot_opts.llvm_path = g_strdup ("");
12462 acfg->aot_opts.temp_path = g_strdup ("");
12463 #ifdef MONOTOUCH
12464 acfg->aot_opts.use_trampolines_page = TRUE;
12465 #endif
12467 mono_aot_parse_options (aot_options, &acfg->aot_opts);
12469 // start dedup
12470 MonoAotState *astate = NULL;
12471 gboolean is_dedup_dummy = FALSE;
12472 mono_setup_dedup_state (acfg, (MonoAotState **) global_aot_state, ass, &astate, &is_dedup_dummy);
12474 // Process later
12475 if (is_dedup_dummy && astate && !astate->emit_inflated_methods)
12476 return 0;
12478 // end dedup
12480 if (acfg->aot_opts.logfile) {
12481 acfg->logfile = fopen (acfg->aot_opts.logfile, "a+");
12484 if (acfg->aot_opts.data_outfile) {
12485 acfg->data_outfile = fopen (acfg->aot_opts.data_outfile, "w+");
12486 if (!acfg->data_outfile) {
12487 aot_printerrf (acfg, "Unable to create file '%s': %s\n", acfg->aot_opts.data_outfile, strerror (errno));
12488 return 1;
12490 acfg->flags = (MonoAotFileFlags)(acfg->flags | MONO_AOT_FILE_FLAG_SEPARATE_DATA);
12493 //acfg->aot_opts.print_skipped_methods = TRUE;
12495 #if !defined(MONO_ARCH_GSHAREDVT_SUPPORTED)
12496 if (acfg->opts & MONO_OPT_GSHAREDVT) {
12497 aot_printerrf (acfg, "-O=gsharedvt not supported on this platform.\n");
12498 return 1;
12500 if (acfg->aot_opts.llvm_only) {
12501 aot_printerrf (acfg, "--aot=llvmonly requires a runtime that supports gsharedvt.\n");
12502 return 1;
12504 #else
12505 if (acfg->aot_opts.llvm_only || mono_aot_mode_is_full (&acfg->aot_opts) || mono_aot_mode_is_hybrid (&acfg->aot_opts))
12506 acfg->opts |= MONO_OPT_GSHAREDVT;
12507 #endif
12509 #if !defined(ENABLE_LLVM)
12510 if (acfg->aot_opts.llvm_only) {
12511 aot_printerrf (acfg, "--aot=llvmonly requires a runtime compiled with llvm support.\n");
12512 return 1;
12514 #endif
12516 if (acfg->opts & MONO_OPT_GSHAREDVT)
12517 mono_set_generic_sharing_vt_supported (TRUE);
12519 aot_printf (acfg, "Mono Ahead of Time compiler - compiling assembly %s\n", image->name);
12521 generate_aotid ((guint8*) &acfg->image->aotid);
12523 char *aotid = mono_guid_to_string (acfg->image->aotid);
12524 aot_printf (acfg, "AOTID %s\n", aotid);
12525 g_free (aotid);
12527 #ifndef MONO_ARCH_HAVE_FULL_AOT_TRAMPOLINES
12528 if (mono_aot_mode_is_full (&acfg->aot_opts)) {
12529 aot_printerrf (acfg, "--aot=full is not supported on this platform.\n");
12530 return 1;
12532 #endif
12534 if (acfg->aot_opts.direct_pinvoke && !acfg->aot_opts.static_link) {
12535 aot_printerrf (acfg, "The 'direct-pinvoke' AOT option also requires the 'static' AOT option.\n");
12536 return 1;
12539 if (acfg->aot_opts.static_link)
12540 acfg->aot_opts.asm_writer = TRUE;
12542 if (acfg->aot_opts.soft_debug) {
12543 MonoDebugOptions *opt = mini_get_debug_options ();
12545 opt->mdb_optimizations = TRUE;
12546 opt->gen_sdb_seq_points = TRUE;
12548 if (!mono_debug_enabled ()) {
12549 aot_printerrf (acfg, "The soft-debug AOT option requires the --debug option.\n");
12550 return 1;
12552 acfg->flags = (MonoAotFileFlags)(acfg->flags | MONO_AOT_FILE_FLAG_DEBUG);
12555 if (mono_use_llvm || acfg->aot_opts.llvm) {
12556 acfg->llvm = TRUE;
12557 acfg->aot_opts.asm_writer = TRUE;
12558 acfg->flags = (MonoAotFileFlags)(acfg->flags | MONO_AOT_FILE_FLAG_WITH_LLVM);
12560 if (acfg->aot_opts.soft_debug) {
12561 aot_printerrf (acfg, "The 'soft-debug' option is not supported when compiling with LLVM.\n");
12562 return 1;
12565 mini_llvm_init ();
12567 if (acfg->aot_opts.asm_only && !acfg->aot_opts.llvm_outfile) {
12568 aot_printerrf (acfg, "Compiling with LLVM and the asm-only option requires the llvm-outfile= option.\n");
12569 return 1;
12573 if (mono_aot_mode_is_full (&acfg->aot_opts)) {
12574 acfg->flags = (MonoAotFileFlags)(acfg->flags | MONO_AOT_FILE_FLAG_FULL_AOT);
12575 acfg->is_full_aot = TRUE;
12578 if (mono_threads_are_safepoints_enabled ())
12579 acfg->flags = (MonoAotFileFlags)(acfg->flags | MONO_AOT_FILE_FLAG_SAFEPOINTS);
12581 // The methods in dedup-emit amodules must be available on runtime startup
12582 // Note: Only one such amodule can have this attribute
12583 if (astate && astate->emit_inflated_methods)
12584 acfg->flags = (MonoAotFileFlags)(acfg->flags | MONO_AOT_FILE_FLAG_EAGER_LOAD);
12587 if (acfg->aot_opts.instances_logfile_path) {
12588 acfg->instances_logfile = fopen (acfg->aot_opts.instances_logfile_path, "w");
12589 if (!acfg->instances_logfile) {
12590 aot_printerrf (acfg, "Unable to create logfile: '%s'.\n", acfg->aot_opts.instances_logfile_path);
12591 return 1;
12595 if (acfg->aot_opts.profile_files) {
12596 GList *l;
12598 for (l = acfg->aot_opts.profile_files; l; l = l->next) {
12599 load_profile_file (acfg, (char*)l->data);
12603 if (!(acfg->aot_opts.interp && !mono_aot_mode_is_full (&acfg->aot_opts))) {
12604 for (int method_index = 0; method_index < acfg->image->tables [MONO_TABLE_METHOD].rows; ++method_index)
12605 g_ptr_array_add (acfg->method_order,GUINT_TO_POINTER (method_index));
12608 acfg->num_trampolines [MONO_AOT_TRAMP_SPECIFIC] = mono_aot_mode_is_full (&acfg->aot_opts) ? acfg->aot_opts.ntrampolines : 0;
12609 #ifdef MONO_ARCH_GSHARED_SUPPORTED
12610 acfg->num_trampolines [MONO_AOT_TRAMP_STATIC_RGCTX] = mono_aot_mode_is_full (&acfg->aot_opts) ? acfg->aot_opts.nrgctx_trampolines : 0;
12611 #endif
12612 acfg->num_trampolines [MONO_AOT_TRAMP_IMT] = mono_aot_mode_is_full (&acfg->aot_opts) ? acfg->aot_opts.nimt_trampolines : 0;
12613 #ifdef MONO_ARCH_GSHAREDVT_SUPPORTED
12614 if (acfg->opts & MONO_OPT_GSHAREDVT)
12615 acfg->num_trampolines [MONO_AOT_TRAMP_GSHAREDVT_ARG] = mono_aot_mode_is_full (&acfg->aot_opts) ? acfg->aot_opts.ngsharedvt_arg_trampolines : 0;
12616 #endif
12618 acfg->temp_prefix = mono_img_writer_get_temp_label_prefix (NULL);
12620 arch_init (acfg);
12622 if (mono_use_llvm || acfg->aot_opts.llvm) {
12624 * Emit all LLVM code into a separate assembly/object file and link with it
12625 * normally.
12627 if (!acfg->aot_opts.asm_only && acfg->llvm_owriter_supported) {
12628 acfg->llvm_owriter = TRUE;
12629 } else if (acfg->aot_opts.llvm_outfile) {
12630 int len = strlen (acfg->aot_opts.llvm_outfile);
12632 if (len >= 2 && acfg->aot_opts.llvm_outfile [len - 2] == '.' && acfg->aot_opts.llvm_outfile [len - 1] == 'o')
12633 acfg->llvm_owriter = TRUE;
12637 if (acfg->llvm && acfg->thumb_mixed)
12638 acfg->flags = (MonoAotFileFlags)(acfg->flags | MONO_AOT_FILE_FLAG_LLVM_THUMB);
12639 if (acfg->aot_opts.llvm_only)
12640 acfg->flags = (MonoAotFileFlags)(acfg->flags | MONO_AOT_FILE_FLAG_LLVM_ONLY);
12642 acfg->assembly_name_sym = g_strdup (acfg->image->assembly->aname.name);
12643 /* Get rid of characters which cannot occur in symbols */
12644 for (p = acfg->assembly_name_sym; *p; ++p) {
12645 if (!(isalnum (*p) || *p == '_'))
12646 *p = '_';
12649 acfg->global_prefix = g_strdup_printf ("mono_aot_%s", acfg->assembly_name_sym);
12650 acfg->plt_symbol = g_strdup_printf ("%s_plt", acfg->global_prefix);
12651 acfg->got_symbol = g_strdup_printf ("%s_got", acfg->global_prefix);
12652 if (acfg->llvm) {
12653 acfg->llvm_got_symbol = g_strdup_printf ("%s_llvm_got", acfg->global_prefix);
12654 acfg->llvm_eh_frame_symbol = g_strdup_printf ("%s_eh_frame", acfg->global_prefix);
12657 acfg->method_index = 1;
12659 if (mono_aot_mode_is_full (&acfg->aot_opts) || mono_aot_mode_is_hybrid (&acfg->aot_opts))
12660 mono_set_partial_sharing_supported (TRUE);
12662 if (!(acfg->aot_opts.interp && !mono_aot_mode_is_full (&acfg->aot_opts))) {
12663 res = collect_methods (acfg);
12664 if (!res)
12665 return 1;
12668 // If we're emitting all of the inflated methods into a dummy
12669 // Assembly, then after extra_methods is set up, we're done
12670 // in this function.
12671 if (astate && astate->emit_inflated_methods)
12672 mono_add_deferred_extra_methods (acfg, astate);
12675 GList *l;
12677 for (l = acfg->profile_data; l; l = l->next)
12678 resolve_profile_data (acfg, (ProfileData*)l->data);
12679 for (l = acfg->profile_data; l; l = l->next)
12680 add_profile_instances (acfg, (ProfileData*)l->data);
12683 acfg->cfgs_size = acfg->methods->len + 32;
12684 acfg->cfgs = g_new0 (MonoCompile*, acfg->cfgs_size);
12686 /* PLT offset 0 is reserved for the PLT trampoline */
12687 acfg->plt_offset = 1;
12688 add_preinit_got_slots (acfg);
12690 #ifdef ENABLE_LLVM
12691 if (acfg->llvm) {
12692 llvm_acfg = acfg;
12693 mono_llvm_create_aot_module (acfg->image->assembly, acfg->global_prefix, acfg->nshared_got_entries, TRUE, acfg->aot_opts.static_link, acfg->aot_opts.llvm_only);
12695 #endif
12697 if (mono_aot_mode_is_interp (&acfg->aot_opts)) {
12698 for (int i = 0; i < sizeof (interp_in_static_sigs) / sizeof (const char *); i++) {
12699 MonoMethodSignature *sig = mono_create_icall_signature (interp_in_static_sigs [i]);
12700 sig = mono_metadata_signature_dup_full (mono_get_corlib (), sig);
12701 sig->pinvoke = FALSE;
12702 MonoMethod *wrapper = mini_get_interp_in_wrapper (sig);
12703 add_method (acfg, wrapper);
12707 TV_GETTIME (atv);
12709 compile_methods (acfg);
12711 TV_GETTIME (btv);
12713 acfg->stats.jit_time = TV_ELAPSED (atv, btv);
12715 TV_GETTIME (atv);
12717 #ifdef ENABLE_LLVM
12718 if (acfg->llvm) {
12719 if (acfg->aot_opts.asm_only) {
12720 if (acfg->aot_opts.outfile) {
12721 acfg->tmpfname = g_strdup_printf ("%s", acfg->aot_opts.outfile);
12722 acfg->tmpbasename = g_strdup (acfg->tmpfname);
12723 } else {
12724 acfg->tmpbasename = g_strdup_printf ("%s", acfg->image->name);
12725 acfg->tmpfname = g_strdup_printf ("%s.s", acfg->tmpbasename);
12727 g_assert (acfg->aot_opts.llvm_outfile);
12728 acfg->llvm_sfile = g_strdup (acfg->aot_opts.llvm_outfile);
12729 if (acfg->llvm_owriter)
12730 acfg->llvm_ofile = g_strdup (acfg->aot_opts.llvm_outfile);
12731 else
12732 acfg->llvm_sfile = g_strdup (acfg->aot_opts.llvm_outfile);
12733 } else {
12734 acfg->tmpbasename = (strcmp (acfg->aot_opts.temp_path, "") == 0) ?
12735 g_strdup_printf ("%s", "temp") :
12736 g_build_filename (acfg->aot_opts.temp_path, "temp", NULL);
12738 acfg->tmpfname = g_strdup_printf ("%s.s", acfg->tmpbasename);
12739 acfg->llvm_sfile = g_strdup_printf ("%s-llvm.s", acfg->tmpbasename);
12740 acfg->llvm_ofile = g_strdup_printf ("%s-llvm.o", acfg->tmpbasename);
12743 #endif
12745 if (acfg->aot_opts.asm_only && !acfg->aot_opts.llvm_only) {
12746 if (acfg->aot_opts.outfile)
12747 acfg->tmpfname = g_strdup_printf ("%s", acfg->aot_opts.outfile);
12748 else
12749 acfg->tmpfname = g_strdup_printf ("%s.s", acfg->image->name);
12750 acfg->fp = fopen (acfg->tmpfname, "w+");
12751 } else {
12752 if (strcmp (acfg->aot_opts.temp_path, "") == 0) {
12753 int i = g_file_open_tmp ("mono_aot_XXXXXX", &acfg->tmpfname, NULL);
12754 acfg->fp = fdopen (i, "w+");
12755 } else {
12756 acfg->tmpbasename = g_build_filename (acfg->aot_opts.temp_path, "temp", NULL);
12757 acfg->tmpfname = g_strdup_printf ("%s.s", acfg->tmpbasename);
12758 acfg->fp = fopen (acfg->tmpfname, "w+");
12761 if (acfg->fp == 0 && !acfg->aot_opts.llvm_only) {
12762 aot_printerrf (acfg, "Unable to open file '%s': %s\n", acfg->tmpfname, strerror (errno));
12763 return 1;
12765 if (acfg->fp)
12766 acfg->w = mono_img_writer_create (acfg->fp, FALSE);
12768 tmp_outfile_name = NULL;
12769 outfile_name = NULL;
12771 /* Compute symbols for methods */
12772 for (i = 0; i < acfg->nmethods; ++i) {
12773 if (acfg->cfgs [i]) {
12774 MonoCompile *cfg = acfg->cfgs [i];
12775 int method_index = get_method_index (acfg, cfg->orig_method);
12777 if (COMPILE_LLVM (cfg))
12778 cfg->asm_symbol = g_strdup_printf ("%s%s", acfg->llvm_label_prefix, cfg->llvm_method_name);
12779 else if (acfg->global_symbols || acfg->llvm)
12780 cfg->asm_symbol = get_debug_sym (cfg->orig_method, "", acfg->method_label_hash);
12781 else
12782 cfg->asm_symbol = g_strdup_printf ("%s%sm_%x", acfg->temp_prefix, acfg->llvm_label_prefix, method_index);
12783 cfg->asm_debug_symbol = cfg->asm_symbol;
12787 if (acfg->aot_opts.dwarf_debug && acfg->aot_opts.gnu_asm) {
12789 * CLANG supports GAS .file/.loc directives, so emit line number information this way
12791 acfg->gas_line_numbers = TRUE;
12794 #ifdef EMIT_DWARF_INFO
12795 if ((!acfg->aot_opts.nodebug || acfg->aot_opts.dwarf_debug) && acfg->has_jitted_code) {
12796 if (acfg->aot_opts.dwarf_debug && !mono_debug_enabled ()) {
12797 aot_printerrf (acfg, "The dwarf AOT option requires the --debug option.\n");
12798 return 1;
12800 acfg->dwarf = mono_dwarf_writer_create (acfg->w, NULL, 0, !acfg->gas_line_numbers);
12802 #endif /* EMIT_DWARF_INFO */
12804 if (acfg->w)
12805 mono_img_writer_emit_start (acfg->w);
12807 if (acfg->dwarf)
12808 mono_dwarf_writer_emit_base_info (acfg->dwarf, g_path_get_basename (acfg->image->name), mono_unwind_get_cie_program ());
12810 emit_code (acfg);
12811 if (acfg->aot_opts.dedup)
12812 mono_flush_method_cache (acfg);
12813 if (acfg->aot_opts.dedup || acfg->dedup_emit_mode)
12814 mono_dedup_log_stats (acfg);
12816 emit_info (acfg);
12818 emit_extra_methods (acfg);
12820 if (acfg->aot_opts.dedup_include && !is_dedup_dummy) {
12821 fclose (acfg->fp);
12822 return 0;
12825 emit_trampolines (acfg);
12827 emit_class_name_table (acfg);
12829 emit_got_info (acfg, FALSE);
12830 if (acfg->llvm)
12831 emit_got_info (acfg, TRUE);
12833 emit_exception_info (acfg);
12835 emit_unwind_info (acfg);
12837 emit_class_info (acfg);
12839 emit_plt (acfg);
12841 emit_image_table (acfg);
12843 emit_weak_field_indexes (acfg);
12845 emit_got (acfg);
12849 * The managed allocators are GC specific, so can't use an AOT image created by one GC
12850 * in another.
12852 const char *gc_name = mono_gc_get_gc_name ();
12853 acfg->gc_name_offset = add_to_blob (acfg, (guint8*)gc_name, strlen (gc_name) + 1);
12856 emit_blob (acfg);
12858 emit_objc_selectors (acfg);
12860 emit_globals (acfg);
12862 emit_file_info (acfg);
12864 emit_library_info (acfg);
12866 if (acfg->dwarf) {
12867 emit_dwarf_info (acfg);
12868 mono_dwarf_writer_close (acfg->dwarf);
12869 } else {
12870 if (!acfg->aot_opts.nodebug)
12871 emit_codeview_info (acfg);
12874 emit_mem_end (acfg);
12876 if (acfg->need_pt_gnu_stack) {
12877 /* This is required so the .so doesn't have an executable stack */
12878 /* The bin writer already emits this */
12879 fprintf (acfg->fp, "\n.section .note.GNU-stack,\"\",@progbits\n");
12882 if (acfg->aot_opts.data_outfile)
12883 fclose (acfg->data_outfile);
12885 #ifdef ENABLE_LLVM
12886 if (acfg->llvm) {
12887 gboolean res;
12889 res = emit_llvm_file (acfg);
12890 if (!res)
12891 return 1;
12893 #endif
12895 TV_GETTIME (btv);
12897 acfg->stats.gen_time = TV_ELAPSED (atv, btv);
12899 if (acfg->llvm)
12900 sprintf (llvm_stats_msg, ", LLVM: %d (%d%%)", acfg->stats.llvm_count, acfg->stats.mcount ? (acfg->stats.llvm_count * 100) / acfg->stats.mcount : 100);
12901 else
12902 strcpy (llvm_stats_msg, "");
12904 all_sizes = acfg->stats.code_size + acfg->stats.info_size + acfg->stats.ex_info_size + acfg->stats.unwind_info_size + acfg->stats.class_info_size + acfg->stats.got_info_size + acfg->stats.offsets_size + acfg->stats.plt_size;
12906 aot_printf (acfg, "Code: %d(%d%%) Info: %d(%d%%) Ex Info: %d(%d%%) Unwind Info: %d(%d%%) Class Info: %d(%d%%) PLT: %d(%d%%) GOT Info: %d(%d%%) Offsets: %d(%d%%) GOT: %d\n",
12907 (int)acfg->stats.code_size, (int)(acfg->stats.code_size * 100 / all_sizes),
12908 (int)acfg->stats.info_size, (int)(acfg->stats.info_size * 100 / all_sizes),
12909 (int)acfg->stats.ex_info_size, (int)(acfg->stats.ex_info_size * 100 / all_sizes),
12910 (int)acfg->stats.unwind_info_size, (int)(acfg->stats.unwind_info_size * 100 / all_sizes),
12911 (int)acfg->stats.class_info_size, (int)(acfg->stats.class_info_size * 100 / all_sizes),
12912 acfg->stats.plt_size ? (int)acfg->stats.plt_size : (int)acfg->plt_offset, acfg->stats.plt_size ? (int)(acfg->stats.plt_size * 100 / all_sizes) : 0,
12913 (int)acfg->stats.got_info_size, (int)(acfg->stats.got_info_size * 100 / all_sizes),
12914 (int)acfg->stats.offsets_size, (int)(acfg->stats.offsets_size * 100 / all_sizes),
12915 (int)(acfg->got_offset * sizeof (gpointer)));
12916 aot_printf (acfg, "Compiled: %d/%d (%d%%)%s, No GOT slots: %d (%d%%), Direct calls: %d (%d%%)\n",
12917 acfg->stats.ccount, acfg->stats.mcount, acfg->stats.mcount ? (acfg->stats.ccount * 100) / acfg->stats.mcount : 100,
12918 llvm_stats_msg,
12919 acfg->stats.methods_without_got_slots, acfg->stats.mcount ? (acfg->stats.methods_without_got_slots * 100) / acfg->stats.mcount : 100,
12920 acfg->stats.direct_calls, acfg->stats.all_calls ? (acfg->stats.direct_calls * 100) / acfg->stats.all_calls : 100);
12921 if (acfg->stats.genericcount)
12922 aot_printf (acfg, "%d methods are generic (%d%%)\n", acfg->stats.genericcount, acfg->stats.mcount ? (acfg->stats.genericcount * 100) / acfg->stats.mcount : 100);
12923 if (acfg->stats.abscount)
12924 aot_printf (acfg, "%d methods contain absolute addresses (%d%%)\n", acfg->stats.abscount, acfg->stats.mcount ? (acfg->stats.abscount * 100) / acfg->stats.mcount : 100);
12925 if (acfg->stats.lmfcount)
12926 aot_printf (acfg, "%d methods contain lmf pointers (%d%%)\n", acfg->stats.lmfcount, acfg->stats.mcount ? (acfg->stats.lmfcount * 100) / acfg->stats.mcount : 100);
12927 if (acfg->stats.ocount)
12928 aot_printf (acfg, "%d methods have other problems (%d%%)\n", acfg->stats.ocount, acfg->stats.mcount ? (acfg->stats.ocount * 100) / acfg->stats.mcount : 100);
12930 TV_GETTIME (atv);
12931 if (acfg->w) {
12932 res = mono_img_writer_emit_writeout (acfg->w);
12933 if (res != 0) {
12934 acfg_free (acfg);
12935 return res;
12937 res = compile_asm (acfg);
12938 if (res != 0) {
12939 acfg_free (acfg);
12940 return res;
12943 TV_GETTIME (btv);
12944 acfg->stats.link_time = TV_ELAPSED (atv, btv);
12946 if (acfg->aot_opts.stats) {
12947 int i;
12949 aot_printf (acfg, "GOT slot distribution:\n");
12950 for (i = 0; i < MONO_PATCH_INFO_NUM; ++i)
12951 if (acfg->stats.got_slot_types [i])
12952 aot_printf (acfg, "\t%s: %d (%d)\n", get_patch_name (i), acfg->stats.got_slot_types [i], acfg->stats.got_slot_info_sizes [i]);
12953 aot_printf (acfg, "\nMethod stats:\n");
12954 aot_printf (acfg, "\tNormal: %d\n", acfg->stats.method_categories [METHOD_CAT_NORMAL]);
12955 aot_printf (acfg, "\tInstance: %d\n", acfg->stats.method_categories [METHOD_CAT_INST]);
12956 aot_printf (acfg, "\tGSharedvt: %d\n", acfg->stats.method_categories [METHOD_CAT_GSHAREDVT]);
12957 aot_printf (acfg, "\tWrapper: %d\n", acfg->stats.method_categories [METHOD_CAT_WRAPPER]);
12960 aot_printf (acfg, "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);
12962 if (acfg->aot_opts.dump_json)
12963 aot_dump (acfg);
12965 acfg_free (acfg);
12967 return 0;
12970 #else
12972 /* AOT disabled */
12974 void*
12975 mono_aot_readonly_field_override (MonoClassField *field)
12977 return NULL;
12981 mono_compile_assembly (MonoAssembly *ass, guint32 opts, const char *aot_options, gpointer **aot_state)
12983 return 0;
12986 gboolean
12987 mono_aot_is_shared_got_offset (int offset)
12989 return FALSE;
12993 mono_compile_deferred_assemblies (guint32 opts, const char *aot_options, gpointer **aot_state)
12995 g_assert_not_reached ();
12996 return 0;
12999 #endif