[jit] Constant folding for some Math operations on doubles (#9281)
[mono-project.git] / mono / mini / aot-compiler.c
bloba83bc03a4e52ef5115dd8acfb9fd1fec6a85f7b6
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 static MonoMethod*
73 try_get_method_nofail (MonoClass *klass, const char *method_name, int param_count, int flags)
75 MonoMethod *result;
76 ERROR_DECL (error);
77 result = mono_class_get_method_from_name_checked (klass, method_name, param_count, flags, error);
78 mono_error_assert_ok (error);
79 return result;
82 static MonoMethod*
83 get_method_nofail (MonoClass *klass, const char *method_name, int param_count, int flags)
85 MonoMethod *result = try_get_method_nofail (klass, method_name, param_count, flags);
86 g_assertf (result, "Expected to find method %s in klass %s", method_name, m_class_get_name (klass));
87 return result;
90 #if !defined(DISABLE_AOT) && !defined(DISABLE_JIT)
92 // Use MSVC toolchain, Clang for MSVC using MSVC codegen and linker, when compiling for AMD64
93 // targeting WIN32 platforms running AOT compiler on WIN32 platform with VS installation.
94 #if defined(TARGET_AMD64) && defined(TARGET_WIN32) && defined(HOST_WIN32) && defined(_MSC_VER)
95 #define TARGET_X86_64_WIN32_MSVC
96 #endif
98 #if defined(TARGET_X86_64_WIN32_MSVC)
99 #define TARGET_WIN32_MSVC
100 #endif
102 // Emit native unwind info on Windows platforms (different from DWARF). Emitted unwind info
103 // works when using the MSVC toolchain using Clang for MSVC codegen and linker. Only supported when
104 // compiling for AMD64 (Windows x64 platforms).
105 #if defined(TARGET_WIN32_MSVC) && defined(MONO_ARCH_HAVE_UNWIND_TABLE)
106 #define EMIT_WIN32_UNWIND_INFO
107 #endif
109 #if defined(__linux__)
110 #define RODATA_SECT ".rodata"
111 #elif defined(TARGET_MACH)
112 #define RODATA_SECT ".section __TEXT, __const"
113 #elif defined(TARGET_WIN32_MSVC)
114 #define RODATA_SECT ".rdata"
115 #else
116 #define RODATA_SECT ".text"
117 #endif
119 #define TV_DECLARE(name) gint64 name
120 #define TV_GETTIME(tv) tv = mono_100ns_ticks ()
121 #define TV_ELAPSED(start,end) (((end) - (start)) / 10)
123 #define ROUND_DOWN(VALUE,SIZE) ((VALUE) & ~((SIZE) - 1))
125 typedef struct {
126 char *name;
127 MonoImage *image;
128 } ImageProfileData;
130 typedef struct ClassProfileData ClassProfileData;
132 typedef struct {
133 int argc;
134 ClassProfileData **argv;
135 MonoGenericInst *inst;
136 } GInstProfileData;
138 struct ClassProfileData {
139 ImageProfileData *image;
140 char *ns, *name;
141 GInstProfileData *inst;
142 MonoClass *klass;
145 typedef struct {
146 ClassProfileData *klass;
147 int id;
148 char *name;
149 int param_count;
150 char *signature;
151 GInstProfileData *inst;
152 MonoMethod *method;
153 } MethodProfileData;
155 typedef struct {
156 GHashTable *images, *classes, *ginsts, *methods;
157 } ProfileData;
159 /* predefined values for static readonly fields without needed to run the .cctor */
160 typedef struct _ReadOnlyValue ReadOnlyValue;
161 struct _ReadOnlyValue {
162 ReadOnlyValue *next;
163 char *name;
164 int type; /* to be used later for typechecking to prevent user errors */
165 union {
166 guint8 i1;
167 guint16 i2;
168 guint32 i4;
169 guint64 i8;
170 gpointer ptr;
171 } value;
173 static ReadOnlyValue *readonly_values;
175 typedef struct MonoAotOptions {
176 char *outfile;
177 char *llvm_outfile;
178 char *data_outfile;
179 GList *profile_files;
180 gboolean save_temps;
181 gboolean write_symbols;
182 gboolean metadata_only;
183 gboolean bind_to_runtime_version;
184 MonoAotMode mode;
185 gboolean interp;
186 gboolean no_dlsym;
187 gboolean static_link;
188 gboolean asm_only;
189 gboolean asm_writer;
190 gboolean nodebug;
191 gboolean dwarf_debug;
192 gboolean soft_debug;
193 gboolean log_generics;
194 gboolean log_instances;
195 gboolean gen_msym_dir;
196 char *gen_msym_dir_path;
197 gboolean direct_pinvoke;
198 gboolean direct_icalls;
199 gboolean no_direct_calls;
200 gboolean use_trampolines_page;
201 gboolean no_instances;
202 // We are collecting inflated methods and emitting non-inflated
203 gboolean dedup;
204 // The name of the assembly for which the AOT module is going to have all deduped methods moved to.
205 // When set, we are emitting inflated methods only
206 char *dedup_include;
207 gboolean gnu_asm;
208 gboolean try_llvm;
209 gboolean llvm;
210 gboolean llvm_only;
211 int nthreads;
212 int ntrampolines;
213 int nrgctx_trampolines;
214 int nimt_trampolines;
215 int ngsharedvt_arg_trampolines;
216 int nftnptr_arg_trampolines;
217 int nrgctx_fetch_trampolines;
218 int nunbox_arbitrary_trampolines;
219 gboolean print_skipped_methods;
220 gboolean stats;
221 gboolean verbose;
222 gboolean deterministic;
223 char *tool_prefix;
224 char *ld_flags;
225 char *mtriple;
226 char *llvm_path;
227 char *temp_path;
228 char *instances_logfile_path;
229 char *logfile;
230 char *llvm_opts;
231 char *llvm_llc;
232 gboolean dump_json;
233 gboolean profile_only;
234 gboolean no_opt;
235 char *clangxx;
236 } MonoAotOptions;
238 typedef enum {
239 METHOD_CAT_NORMAL,
240 METHOD_CAT_GSHAREDVT,
241 METHOD_CAT_INST,
242 METHOD_CAT_WRAPPER,
243 METHOD_CAT_NUM
244 } MethodCategory;
246 typedef struct MonoAotStats {
247 int ccount, mcount, lmfcount, abscount, gcount, ocount, genericcount;
248 gint64 code_size, info_size, ex_info_size, unwind_info_size, got_size, class_info_size, got_info_size, plt_size;
249 int methods_without_got_slots, direct_calls, all_calls, llvm_count;
250 int got_slots, offsets_size;
251 int method_categories [METHOD_CAT_NUM];
252 int got_slot_types [MONO_PATCH_INFO_NUM];
253 int got_slot_info_sizes [MONO_PATCH_INFO_NUM];
254 int jit_time, gen_time, link_time;
255 } MonoAotStats;
257 typedef struct GotInfo {
258 GHashTable *patch_to_got_offset;
259 GHashTable **patch_to_got_offset_by_type;
260 GPtrArray *got_patches;
261 } GotInfo;
263 #ifdef EMIT_WIN32_UNWIND_INFO
264 typedef struct _UnwindInfoSectionCacheItem {
265 char *xdata_section_label;
266 PUNWIND_INFO unwind_info;
267 gboolean xdata_section_emitted;
268 } UnwindInfoSectionCacheItem;
269 #endif
271 typedef struct MonoAotCompile {
272 MonoImage *image;
273 GPtrArray *methods;
274 GHashTable *method_indexes;
275 GHashTable *method_depth;
276 MonoCompile **cfgs;
277 int cfgs_size;
278 GHashTable **patch_to_plt_entry;
279 GHashTable *plt_offset_to_entry;
280 //GHashTable *patch_to_got_offset;
281 //GHashTable **patch_to_got_offset_by_type;
282 //GPtrArray *got_patches;
283 GotInfo got_info, llvm_got_info;
284 GHashTable *image_hash;
285 GHashTable *method_to_cfg;
286 GHashTable *token_info_hash;
287 GHashTable *method_to_pinvoke_import;
288 GPtrArray *extra_methods;
289 GPtrArray *image_table;
290 GPtrArray *globals;
291 GPtrArray *method_order;
292 GHashTable *dedup_stats;
293 GHashTable *dedup_cache;
294 gboolean dedup_cache_changed;
295 GHashTable *export_names;
296 /* Maps MonoClass* -> blob offset */
297 GHashTable *klass_blob_hash;
298 /* Maps MonoMethod* -> blob offset */
299 GHashTable *method_blob_hash;
300 GHashTable *gsharedvt_in_signatures;
301 GHashTable *gsharedvt_out_signatures;
302 guint32 *plt_got_info_offsets;
303 guint32 got_offset, llvm_got_offset, plt_offset, plt_got_offset_base, nshared_got_entries;
304 /* Number of GOT entries reserved for trampolines */
305 guint32 num_trampoline_got_entries;
306 guint32 tramp_page_size;
308 guint32 table_offsets [MONO_AOT_TABLE_NUM];
309 guint32 num_trampolines [MONO_AOT_TRAMP_NUM];
310 guint32 trampoline_got_offset_base [MONO_AOT_TRAMP_NUM];
311 guint32 trampoline_size [MONO_AOT_TRAMP_NUM];
312 guint32 tramp_page_code_offsets [MONO_AOT_TRAMP_NUM];
314 MonoAotOptions aot_opts;
315 guint32 nmethods;
316 guint32 nextra_methods;
317 guint32 opts;
318 guint32 simd_opts;
319 MonoMemPool *mempool;
320 MonoAotStats stats;
321 int method_index;
322 char *static_linking_symbol;
323 mono_mutex_t mutex;
324 gboolean gas_line_numbers;
325 /* Whenever to emit an object file directly from llc */
326 gboolean llvm_owriter;
327 gboolean llvm_owriter_supported;
328 MonoImageWriter *w;
329 MonoDwarfWriter *dwarf;
330 FILE *fp;
331 char *tmpbasename;
332 char *tmpfname;
333 char *temp_dir_to_delete;
334 char *llvm_sfile;
335 char *llvm_ofile;
336 GSList *cie_program;
337 GHashTable *unwind_info_offsets;
338 GPtrArray *unwind_ops;
339 guint32 unwind_info_offset;
340 char *global_prefix;
341 char *got_symbol;
342 char *llvm_got_symbol;
343 char *plt_symbol;
344 char *llvm_eh_frame_symbol;
345 GHashTable *method_label_hash;
346 const char *temp_prefix;
347 const char *user_symbol_prefix;
348 const char *llvm_label_prefix;
349 const char *inst_directive;
350 int align_pad_value;
351 guint32 label_generator;
352 gboolean llvm;
353 gboolean has_jitted_code;
354 gboolean is_full_aot;
355 gboolean dedup_collect_only;
356 MonoAotFileFlags flags;
357 MonoDynamicStream blob;
358 gboolean blob_closed;
359 GHashTable *typespec_classes;
360 GString *llc_args;
361 GString *as_args;
362 char *assembly_name_sym;
363 GHashTable *plt_entry_debug_sym_cache;
364 gboolean thumb_mixed, need_no_dead_strip, need_pt_gnu_stack;
365 GHashTable *ginst_hash;
366 GHashTable *dwarf_ln_filenames;
367 gboolean global_symbols;
368 int objc_selector_index, objc_selector_index_2;
369 GPtrArray *objc_selectors;
370 GHashTable *objc_selector_to_index;
371 GList *profile_data;
372 GHashTable *profile_methods;
373 #ifdef EMIT_WIN32_UNWIND_INFO
374 GList *unwind_info_section_cache;
375 #endif
376 FILE *logfile;
377 FILE *instances_logfile;
378 FILE *data_outfile;
379 int datafile_offset;
380 int gc_name_offset;
381 // In this mode, we are emitting dedupable methods that we encounter
382 gboolean dedup_emit_mode;
383 } MonoAotCompile;
385 typedef struct {
386 int plt_offset;
387 char *symbol, *llvm_symbol, *debug_sym;
388 MonoJumpInfo *ji;
389 gboolean jit_used, llvm_used;
390 } MonoPltEntry;
392 #define mono_acfg_lock(acfg) mono_os_mutex_lock (&((acfg)->mutex))
393 #define mono_acfg_unlock(acfg) mono_os_mutex_unlock (&((acfg)->mutex))
395 /* This points to the current acfg in LLVM mode */
396 static MonoAotCompile *llvm_acfg;
398 // This, instead of an array of pointers, to optimize away a pointer and a relocation per string.
399 #define MSGSTRFIELD(line) MSGSTRFIELD1(line)
400 #define MSGSTRFIELD1(line) str##line
401 static const struct msgstr_t {
402 #define PATCH_INFO(a,b) char MSGSTRFIELD(__LINE__) [sizeof (b)];
403 #include "patch-info.h"
404 #undef PATCH_INFO
405 } opstr = {
406 #define PATCH_INFO(a,b) b,
407 #include "patch-info.h"
408 #undef PATCH_INFO
410 static const gint16 opidx [] = {
411 #define PATCH_INFO(a,b) offsetof (struct msgstr_t, MSGSTRFIELD(__LINE__)),
412 #include "patch-info.h"
413 #undef PATCH_INFO
416 static G_GNUC_UNUSED const char*
417 get_patch_name (int info)
419 return (const char*)&opstr + opidx [info];
422 static int
423 emit_aot_image (MonoAotCompile *acfg);
425 static void
426 mono_flush_method_cache (MonoAotCompile *acfg);
428 static void
429 mono_read_method_cache (MonoAotCompile *acfg);
431 static guint32
432 get_unwind_info_offset (MonoAotCompile *acfg, guint8 *encoded, guint32 encoded_len);
434 static char*
435 get_plt_entry_debug_sym (MonoAotCompile *acfg, MonoJumpInfo *ji, GHashTable *cache);
437 static void
438 add_gsharedvt_wrappers (MonoAotCompile *acfg, MonoMethodSignature *sig, gboolean gsharedvt_in, gboolean gsharedvt_out, gboolean interp_in);
440 static void
441 add_profile_instances (MonoAotCompile *acfg, ProfileData *data);
443 static inline gboolean
444 ignore_cfg (MonoCompile *cfg)
446 return !cfg || cfg->skip;
449 static void
450 aot_printf (MonoAotCompile *acfg, const gchar *format, ...)
452 FILE *output;
453 va_list args;
455 if (acfg->logfile)
456 output = acfg->logfile;
457 else
458 output = stdout;
460 va_start (args, format);
461 vfprintf (output, format, args);
462 va_end (args);
465 static void
466 aot_printerrf (MonoAotCompile *acfg, const gchar *format, ...)
468 FILE *output;
469 va_list args;
471 if (acfg->logfile)
472 output = acfg->logfile;
473 else
474 output = stderr;
476 va_start (args, format);
477 vfprintf (output, format, args);
478 va_end (args);
481 static void
482 report_loader_error (MonoAotCompile *acfg, MonoError *error, gboolean fatal, const char *format, ...)
484 FILE *output;
485 va_list args;
487 if (mono_error_ok (error))
488 return;
490 if (acfg->logfile)
491 output = acfg->logfile;
492 else
493 output = stderr;
495 va_start (args, format);
496 vfprintf (output, format, args);
497 va_end (args);
498 mono_error_cleanup (error);
500 if (acfg->is_full_aot && fatal) {
501 fprintf (output, "FullAOT cannot continue if there are loader errors.\n");
502 exit (1);
506 /* Wrappers around the image writer functions */
508 #define MAX_SYMBOL_SIZE 256
510 static inline const char *
511 mangle_symbol (const char * symbol, char * mangled_symbol, gsize length)
513 gsize needed_size = length;
515 g_assert (NULL != symbol);
516 g_assert (NULL != mangled_symbol);
517 g_assert (0 != length);
519 #if defined(TARGET_WIN32) && defined(TARGET_X86)
520 if (symbol && '_' != symbol [0]) {
521 needed_size = g_snprintf (mangled_symbol, length, "_%s", symbol);
522 } else {
523 needed_size = g_snprintf (mangled_symbol, length, "%s", symbol);
525 #else
526 needed_size = g_snprintf (mangled_symbol, length, "%s", symbol);
527 #endif
529 g_assert (0 <= needed_size && needed_size < length);
530 return mangled_symbol;
533 static inline char *
534 mangle_symbol_alloc (const char * symbol)
536 g_assert (NULL != symbol);
538 #if defined(TARGET_WIN32) && defined(TARGET_X86)
539 if (symbol && '_' != symbol [0]) {
540 return g_strdup_printf ("_%s", symbol);
542 else {
543 return g_strdup_printf ("%s", symbol);
545 #else
546 return g_strdup_printf ("%s", symbol);
547 #endif
550 static inline void
551 emit_section_change (MonoAotCompile *acfg, const char *section_name, int subsection_index)
553 mono_img_writer_emit_section_change (acfg->w, section_name, subsection_index);
556 #if defined(TARGET_WIN32) && defined(TARGET_X86)
558 static inline void
559 emit_local_symbol (MonoAotCompile *acfg, const char *name, const char *end_label, gboolean func)
561 const char * mangled_symbol_name = name;
562 char * mangled_symbol_name_alloc = NULL;
564 if (TRUE == func) {
565 mangled_symbol_name_alloc = mangle_symbol_alloc (name);
566 mangled_symbol_name = mangled_symbol_name_alloc;
569 if (name != mangled_symbol_name && 0 != g_strcasecmp (name, mangled_symbol_name)) {
570 mono_img_writer_emit_label (acfg->w, mangled_symbol_name);
572 mono_img_writer_emit_local_symbol (acfg->w, mangled_symbol_name, end_label, func);
574 if (NULL != mangled_symbol_name_alloc) {
575 g_free (mangled_symbol_name_alloc);
579 #else
581 static inline void
582 emit_local_symbol (MonoAotCompile *acfg, const char *name, const char *end_label, gboolean func)
584 mono_img_writer_emit_local_symbol (acfg->w, name, end_label, func);
587 #endif
589 static inline void
590 emit_label (MonoAotCompile *acfg, const char *name)
592 mono_img_writer_emit_label (acfg->w, name);
595 static inline void
596 emit_bytes (MonoAotCompile *acfg, const guint8* buf, int size)
598 mono_img_writer_emit_bytes (acfg->w, buf, size);
601 static inline void
602 emit_string (MonoAotCompile *acfg, const char *value)
604 mono_img_writer_emit_string (acfg->w, value);
607 static inline void
608 emit_line (MonoAotCompile *acfg)
610 mono_img_writer_emit_line (acfg->w);
613 static inline void
614 emit_alignment (MonoAotCompile *acfg, int size)
616 mono_img_writer_emit_alignment (acfg->w, size);
619 static inline void
620 emit_alignment_code (MonoAotCompile *acfg, int size)
622 if (acfg->align_pad_value)
623 mono_img_writer_emit_alignment_fill (acfg->w, size, acfg->align_pad_value);
624 else
625 mono_img_writer_emit_alignment (acfg->w, size);
628 static inline void
629 emit_padding (MonoAotCompile *acfg, int size)
631 int i;
632 guint8 buf [16];
634 if (acfg->align_pad_value) {
635 for (i = 0; i < 16; ++i)
636 buf [i] = acfg->align_pad_value;
637 } else {
638 memset (buf, 0, sizeof (buf));
641 for (i = 0; i < size; i += 16) {
642 if (size - i < 16)
643 emit_bytes (acfg, buf, size - i);
644 else
645 emit_bytes (acfg, buf, 16);
649 static inline void
650 emit_pointer (MonoAotCompile *acfg, const char *target)
652 mono_img_writer_emit_pointer (acfg->w, target);
655 static inline void
656 emit_pointer_2 (MonoAotCompile *acfg, const char *prefix, const char *target)
658 if (prefix [0] != '\0') {
659 char *s = g_strdup_printf ("%s%s", prefix, target);
660 mono_img_writer_emit_pointer (acfg->w, s);
661 g_free (s);
662 } else {
663 mono_img_writer_emit_pointer (acfg->w, target);
667 static inline void
668 emit_int16 (MonoAotCompile *acfg, int value)
670 mono_img_writer_emit_int16 (acfg->w, value);
673 static inline void
674 emit_int32 (MonoAotCompile *acfg, int value)
676 mono_img_writer_emit_int32 (acfg->w, value);
679 static inline void
680 emit_symbol_diff (MonoAotCompile *acfg, const char *end, const char* start, int offset)
682 mono_img_writer_emit_symbol_diff (acfg->w, end, start, offset);
685 static inline void
686 emit_zero_bytes (MonoAotCompile *acfg, int num)
688 mono_img_writer_emit_zero_bytes (acfg->w, num);
691 static inline void
692 emit_byte (MonoAotCompile *acfg, guint8 val)
694 mono_img_writer_emit_byte (acfg->w, val);
697 #if defined(TARGET_WIN32) && defined(TARGET_X86)
699 static G_GNUC_UNUSED void
700 emit_global_inner (MonoAotCompile *acfg, const char *name, gboolean func)
702 const char * mangled_symbol_name = name;
703 char * mangled_symbol_name_alloc = NULL;
705 mangled_symbol_name_alloc = mangle_symbol_alloc (name);
706 mangled_symbol_name = mangled_symbol_name_alloc;
708 if (0 != g_strcasecmp (name, mangled_symbol_name)) {
709 mono_img_writer_emit_label (acfg->w, mangled_symbol_name);
711 mono_img_writer_emit_global (acfg->w, mangled_symbol_name, func);
713 if (NULL != mangled_symbol_name_alloc) {
714 g_free (mangled_symbol_name_alloc);
718 #else
720 static G_GNUC_UNUSED void
721 emit_global_inner (MonoAotCompile *acfg, const char *name, gboolean func)
723 mono_img_writer_emit_global (acfg->w, name, func);
726 #endif
728 static inline gboolean
729 link_shared_library (MonoAotCompile *acfg)
731 return !acfg->aot_opts.static_link && !acfg->aot_opts.asm_only;
734 static inline gboolean
735 add_to_global_symbol_table (MonoAotCompile *acfg)
737 #ifdef TARGET_WIN32_MSVC
738 return acfg->aot_opts.no_dlsym || link_shared_library (acfg);
739 #else
740 return acfg->aot_opts.no_dlsym;
741 #endif
744 static void
745 emit_global (MonoAotCompile *acfg, const char *name, gboolean func)
747 if (add_to_global_symbol_table (acfg))
748 g_ptr_array_add (acfg->globals, g_strdup (name));
750 if (acfg->aot_opts.no_dlsym) {
751 mono_img_writer_emit_local_symbol (acfg->w, name, NULL, func);
752 } else {
753 emit_global_inner (acfg, name, func);
757 static void
758 emit_symbol_size (MonoAotCompile *acfg, const char *name, const char *end_label)
760 mono_img_writer_emit_symbol_size (acfg->w, name, end_label);
763 /* Emit a symbol which is referenced by the MonoAotFileInfo structure */
764 static void
765 emit_info_symbol (MonoAotCompile *acfg, const char *name, gboolean func)
767 char symbol [MAX_SYMBOL_SIZE];
769 if (acfg->llvm) {
770 emit_label (acfg, name);
771 /* LLVM generated code references this */
772 sprintf (symbol, "%s%s%s", acfg->user_symbol_prefix, acfg->global_prefix, name);
773 emit_label (acfg, symbol);
775 #ifndef TARGET_WIN32_MSVC
776 emit_global_inner (acfg, symbol, FALSE);
777 #else
778 emit_global_inner (acfg, symbol, func);
779 #endif
780 } else {
781 emit_label (acfg, name);
785 static void
786 emit_string_symbol (MonoAotCompile *acfg, const char *name, const char *value)
788 if (acfg->llvm) {
789 mono_llvm_emit_aot_data (name, (guint8*)value, strlen (value) + 1);
790 return;
793 mono_img_writer_emit_section_change (acfg->w, RODATA_SECT, 1);
794 #ifdef TARGET_MACH
795 /* On apple, all symbols need to be aligned to avoid warnings from ld */
796 emit_alignment (acfg, 4);
797 #endif
798 mono_img_writer_emit_label (acfg->w, name);
799 mono_img_writer_emit_string (acfg->w, value);
802 static G_GNUC_UNUSED void
803 emit_uleb128 (MonoAotCompile *acfg, guint32 value)
805 do {
806 guint8 b = value & 0x7f;
807 value >>= 7;
808 if (value != 0) /* more bytes to come */
809 b |= 0x80;
810 emit_byte (acfg, b);
811 } while (value);
814 static G_GNUC_UNUSED void
815 emit_sleb128 (MonoAotCompile *acfg, gint64 value)
817 gboolean more = 1;
818 gboolean negative = (value < 0);
819 guint32 size = 64;
820 guint8 byte;
822 while (more) {
823 byte = value & 0x7f;
824 value >>= 7;
825 /* the following is unnecessary if the
826 * implementation of >>= uses an arithmetic rather
827 * than logical shift for a signed left operand
829 if (negative)
830 /* sign extend */
831 value |= - ((gint64)1 <<(size - 7));
832 /* sign bit of byte is second high order bit (0x40) */
833 if ((value == 0 && !(byte & 0x40)) ||
834 (value == -1 && (byte & 0x40)))
835 more = 0;
836 else
837 byte |= 0x80;
838 emit_byte (acfg, byte);
842 static G_GNUC_UNUSED void
843 encode_uleb128 (guint32 value, guint8 *buf, guint8 **endbuf)
845 guint8 *p = buf;
847 do {
848 guint8 b = value & 0x7f;
849 value >>= 7;
850 if (value != 0) /* more bytes to come */
851 b |= 0x80;
852 *p ++ = b;
853 } while (value);
855 *endbuf = p;
858 static G_GNUC_UNUSED void
859 encode_sleb128 (gint32 value, guint8 *buf, guint8 **endbuf)
861 gboolean more = 1;
862 gboolean negative = (value < 0);
863 guint32 size = 32;
864 guint8 byte;
865 guint8 *p = buf;
867 while (more) {
868 byte = value & 0x7f;
869 value >>= 7;
870 /* the following is unnecessary if the
871 * implementation of >>= uses an arithmetic rather
872 * than logical shift for a signed left operand
874 if (negative)
875 /* sign extend */
876 value |= - (1 <<(size - 7));
877 /* sign bit of byte is second high order bit (0x40) */
878 if ((value == 0 && !(byte & 0x40)) ||
879 (value == -1 && (byte & 0x40)))
880 more = 0;
881 else
882 byte |= 0x80;
883 *p ++= byte;
886 *endbuf = p;
889 static void
890 encode_int (gint32 val, guint8 *buf, guint8 **endbuf)
892 // FIXME: Big-endian
893 buf [0] = (val >> 0) & 0xff;
894 buf [1] = (val >> 8) & 0xff;
895 buf [2] = (val >> 16) & 0xff;
896 buf [3] = (val >> 24) & 0xff;
898 *endbuf = buf + 4;
901 static void
902 encode_int16 (guint16 val, guint8 *buf, guint8 **endbuf)
904 buf [0] = (val >> 0) & 0xff;
905 buf [1] = (val >> 8) & 0xff;
907 *endbuf = buf + 2;
910 static void
911 encode_string (const char *s, guint8 *buf, guint8 **endbuf)
913 int len = strlen (s);
915 memcpy (buf, s, len + 1);
916 *endbuf = buf + len + 1;
919 static void
920 emit_unset_mode (MonoAotCompile *acfg)
922 mono_img_writer_emit_unset_mode (acfg->w);
925 static G_GNUC_UNUSED void
926 emit_set_thumb_mode (MonoAotCompile *acfg)
928 emit_unset_mode (acfg);
929 fprintf (acfg->fp, ".code 16\n");
932 static G_GNUC_UNUSED void
933 emit_set_arm_mode (MonoAotCompile *acfg)
935 emit_unset_mode (acfg);
936 fprintf (acfg->fp, ".code 32\n");
939 static inline void
940 emit_code_bytes (MonoAotCompile *acfg, const guint8* buf, int size)
942 #ifdef TARGET_ARM64
943 int i;
945 g_assert (size % 4 == 0);
946 emit_unset_mode (acfg);
947 for (i = 0; i < size; i += 4)
948 fprintf (acfg->fp, "%s 0x%x\n", acfg->inst_directive, *(guint32*)(buf + i));
949 #else
950 emit_bytes (acfg, buf, size);
951 #endif
954 /* ARCHITECTURE SPECIFIC CODE */
956 #if defined(TARGET_X86) || defined(TARGET_AMD64) || defined(TARGET_ARM) || defined(TARGET_POWERPC) || defined(TARGET_ARM64) || defined (TARGET_RISCV)
957 #define EMIT_DWARF_INFO 1
958 #endif
960 #ifdef TARGET_WIN32_MSVC
961 #undef EMIT_DWARF_INFO
962 #define EMIT_WIN32_CODEVIEW_INFO
963 #endif
965 #ifdef EMIT_WIN32_UNWIND_INFO
966 static UnwindInfoSectionCacheItem *
967 get_cached_unwind_info_section_item_win32 (MonoAotCompile *acfg, const char *function_start, const char *function_end, GSList *unwind_ops);
969 static void
970 free_unwind_info_section_cache_win32 (MonoAotCompile *acfg);
972 static void
973 emit_unwind_info_data_win32 (MonoAotCompile *acfg, PUNWIND_INFO unwind_info);
975 static void
976 emit_unwind_info_sections_win32 (MonoAotCompile *acfg, const char *function_start, const char *function_end, GSList *unwind_ops);
977 #endif
979 static void
980 arch_free_unwind_info_section_cache (MonoAotCompile *acfg)
982 #ifdef EMIT_WIN32_UNWIND_INFO
983 free_unwind_info_section_cache_win32 (acfg);
984 #endif
987 static void
988 arch_emit_unwind_info_sections (MonoAotCompile *acfg, const char *function_start, const char *function_end, GSList *unwind_ops)
990 #ifdef EMIT_WIN32_UNWIND_INFO
991 gboolean own_unwind_ops = FALSE;
992 if (!unwind_ops) {
993 unwind_ops = mono_unwind_get_cie_program ();
994 own_unwind_ops = TRUE;
997 emit_unwind_info_sections_win32 (acfg, function_start, function_end, unwind_ops);
999 if (own_unwind_ops)
1000 mono_free_unwind_info (unwind_ops);
1001 #endif
1004 #if defined(TARGET_ARM)
1005 #define AOT_FUNC_ALIGNMENT 4
1006 #else
1007 #define AOT_FUNC_ALIGNMENT 16
1008 #endif
1010 #if defined(TARGET_POWERPC64) && !defined(MONO_ARCH_ILP32)
1011 #define PPC_LD_OP "ld"
1012 #define PPC_LDX_OP "ldx"
1013 #else
1014 #define PPC_LD_OP "lwz"
1015 #define PPC_LDX_OP "lwzx"
1016 #endif
1018 #ifdef TARGET_X86_64_WIN32_MSVC
1019 #define AOT_TARGET_STR "AMD64 (WIN32) (MSVC codegen)"
1020 #elif TARGET_AMD64
1021 #define AOT_TARGET_STR "AMD64"
1022 #endif
1024 #ifdef TARGET_ARM
1025 #ifdef TARGET_MACH
1026 #define AOT_TARGET_STR "ARM (MACH)"
1027 #else
1028 #define AOT_TARGET_STR "ARM (!MACH)"
1029 #endif
1030 #endif
1032 #ifdef TARGET_ARM64
1033 #ifdef TARGET_MACH
1034 #define AOT_TARGET_STR "ARM64 (MACH)"
1035 #else
1036 #define AOT_TARGET_STR "ARM64 (!MACH)"
1037 #endif
1038 #endif
1040 #ifdef TARGET_POWERPC64
1041 #ifdef MONO_ARCH_ILP32
1042 #define AOT_TARGET_STR "POWERPC64 (mono ilp32)"
1043 #else
1044 #define AOT_TARGET_STR "POWERPC64 (!mono ilp32)"
1045 #endif
1046 #else
1047 #ifdef TARGET_POWERPC
1048 #ifdef MONO_ARCH_ILP32
1049 #define AOT_TARGET_STR "POWERPC (mono ilp32)"
1050 #else
1051 #define AOT_TARGET_STR "POWERPC (!mono ilp32)"
1052 #endif
1053 #endif
1054 #endif
1056 #ifdef TARGET_RISCV32
1057 #define AOT_TARGET_STR "RISCV32"
1058 #endif
1060 #ifdef TARGET_RISCV64
1061 #define AOT_TARGET_STR "RISCV64"
1062 #endif
1064 #ifdef TARGET_X86
1065 #ifdef TARGET_WIN32
1066 #define AOT_TARGET_STR "X86 (WIN32)"
1067 #else
1068 #define AOT_TARGET_STR "X86"
1069 #endif
1070 #endif
1072 #ifndef AOT_TARGET_STR
1073 #define AOT_TARGET_STR ""
1074 #endif
1076 static void
1077 arch_init (MonoAotCompile *acfg)
1079 acfg->llc_args = g_string_new ("");
1080 acfg->as_args = g_string_new ("");
1081 acfg->llvm_owriter_supported = TRUE;
1084 * The prefix LLVM likes to put in front of symbol names on darwin.
1085 * The mach-os specs require this for globals, but LLVM puts them in front of all
1086 * symbols. We need to handle this, since we need to refer to LLVM generated
1087 * symbols.
1089 acfg->llvm_label_prefix = "";
1090 acfg->user_symbol_prefix = "";
1092 #if defined(TARGET_X86)
1093 g_string_append (acfg->llc_args, " -march=x86 -mattr=sse4.1");
1094 #endif
1096 #if defined(TARGET_AMD64)
1097 g_string_append (acfg->llc_args, " -march=x86-64 -mattr=sse4.1");
1098 /* NOP */
1099 acfg->align_pad_value = 0x90;
1100 #endif
1102 #ifdef TARGET_ARM
1103 if (acfg->aot_opts.mtriple && strstr (acfg->aot_opts.mtriple, "darwin")) {
1104 g_string_append (acfg->llc_args, "-mattr=+v6");
1105 } else {
1106 g_string_append (acfg->llc_args, " -march=arm");
1107 #if defined(ARM_FPU_VFP_HARD)
1108 g_string_append (acfg->llc_args, " -mattr=+vfp2,-neon,+d16 -float-abi=hard");
1109 g_string_append (acfg->as_args, " -mfpu=vfp3");
1110 #elif defined(ARM_FPU_VFP)
1111 g_string_append (acfg->llc_args, " -mattr=+vfp2,-neon,+d16");
1112 g_string_append (acfg->as_args, " -mfpu=vfp3");
1113 #else
1114 #ifdef LLVM_API_VERSION > 100
1115 g_string_append (acfg->llc_args, " -mattr=+soft-float");
1116 #else
1117 g_string_append (acfg->llc_args, " -soft-float");
1118 #endif
1119 #endif
1121 if (acfg->aot_opts.mtriple && strstr (acfg->aot_opts.mtriple, "thumb"))
1122 acfg->thumb_mixed = TRUE;
1124 if (acfg->aot_opts.mtriple)
1125 mono_arch_set_target (acfg->aot_opts.mtriple);
1126 #endif
1128 #ifdef TARGET_ARM64
1129 g_string_append (acfg->llc_args, " -march=aarch64");
1130 acfg->inst_directive = ".inst";
1131 if (acfg->aot_opts.mtriple)
1132 mono_arch_set_target (acfg->aot_opts.mtriple);
1133 #endif
1135 #ifdef TARGET_MACH
1136 acfg->user_symbol_prefix = "_";
1137 acfg->llvm_label_prefix = "_";
1138 acfg->inst_directive = ".word";
1139 acfg->need_no_dead_strip = TRUE;
1140 acfg->aot_opts.gnu_asm = TRUE;
1141 #endif
1143 #if defined(__linux__) && !defined(TARGET_ARM)
1144 acfg->need_pt_gnu_stack = TRUE;
1145 #endif
1147 #ifdef TARGET_RISCV
1148 if (acfg->aot_opts.mtriple)
1149 mono_arch_set_target (acfg->aot_opts.mtriple);
1151 #ifdef TARGET_RISCV64
1153 g_string_append (acfg->as_args, " -march=rv64i ");
1154 #ifdef RISCV_FPABI_DOUBLE
1155 g_string_append (acfg->as_args, " -mabi=lp64d");
1156 #else
1157 g_string_append (acfg->as_args, " -mabi=lp64");
1158 #endif
1160 #else
1162 g_string_append (acfg->as_args, " -march=rv32i ");
1163 #ifdef RISCV_FPABI_DOUBLE
1164 g_string_append (acfg->as_args, " -mabi=ilp32d ");
1165 #else
1166 g_string_append (acfg->as_args, " -mabi=ilp32 ");
1167 #endif
1169 #endif
1171 #endif
1173 #ifdef MONOTOUCH
1174 acfg->global_symbols = TRUE;
1175 #endif
1177 #ifdef TARGET_ANDROID
1178 acfg->llvm_owriter_supported = FALSE;
1179 #endif
1182 #ifdef TARGET_ARM64
1185 /* Load the contents of GOT_SLOT into dreg, clobbering ip0 */
1186 static void
1187 arm64_emit_load_got_slot (MonoAotCompile *acfg, int dreg, int got_slot)
1189 int offset;
1191 g_assert (acfg->fp);
1192 emit_unset_mode (acfg);
1193 /* r16==ip0 */
1194 offset = (int)(got_slot * sizeof (target_mgreg_t));
1195 #ifdef TARGET_MACH
1196 /* clang's integrated assembler */
1197 fprintf (acfg->fp, "adrp x16, %s@PAGE+%d\n", acfg->got_symbol, offset & 0xfffff000);
1198 fprintf (acfg->fp, "add x16, x16, %s@PAGEOFF\n", acfg->got_symbol);
1199 fprintf (acfg->fp, "ldr x%d, [x16, #%d]\n", dreg, offset & 0xfff);
1200 #else
1201 /* Linux GAS */
1202 fprintf (acfg->fp, "adrp x16, %s+%d\n", acfg->got_symbol, offset & 0xfffff000);
1203 fprintf (acfg->fp, "add x16, x16, :lo12:%s\n", acfg->got_symbol);
1204 fprintf (acfg->fp, "ldr x%d, [x16, %d]\n", dreg, offset & 0xfff);
1205 #endif
1208 static void
1209 arm64_emit_objc_selector_ref (MonoAotCompile *acfg, guint8 *code, int index, int *code_size)
1211 int reg;
1213 g_assert (acfg->fp);
1214 emit_unset_mode (acfg);
1216 /* ldr rt, target */
1217 reg = arm_get_ldr_lit_reg (code);
1219 fprintf (acfg->fp, "adrp x%d, L_OBJC_SELECTOR_REFERENCES_%d@PAGE\n", reg, index);
1220 fprintf (acfg->fp, "add x%d, x%d, L_OBJC_SELECTOR_REFERENCES_%d@PAGEOFF\n", reg, reg, index);
1221 fprintf (acfg->fp, "ldr x%d, [x%d]\n", reg, reg);
1223 *code_size = 12;
1226 static void
1227 arm64_emit_direct_call (MonoAotCompile *acfg, const char *target, gboolean external, gboolean thumb, MonoJumpInfo *ji, int *call_size)
1229 g_assert (acfg->fp);
1230 emit_unset_mode (acfg);
1231 if (ji && ji->relocation == MONO_R_ARM64_B) {
1232 fprintf (acfg->fp, "b %s\n", target);
1233 } else {
1234 if (ji)
1235 g_assert (ji->relocation == MONO_R_ARM64_BL);
1236 fprintf (acfg->fp, "bl %s\n", target);
1238 *call_size = 4;
1241 static void
1242 arm64_emit_got_access (MonoAotCompile *acfg, guint8 *code, int got_slot, int *code_size)
1244 int reg;
1246 /* ldr rt, target */
1247 reg = arm_get_ldr_lit_reg (code);
1248 arm64_emit_load_got_slot (acfg, reg, got_slot);
1249 *code_size = 12;
1252 static void
1253 arm64_emit_plt_entry (MonoAotCompile *acfg, const char *got_symbol, int offset, int info_offset)
1255 arm64_emit_load_got_slot (acfg, ARMREG_R16, offset / sizeof (target_mgreg_t));
1256 fprintf (acfg->fp, "br x16\n");
1257 /* Used by mono_aot_get_plt_info_offset () */
1258 fprintf (acfg->fp, "%s %d\n", acfg->inst_directive, info_offset);
1261 static void
1262 arm64_emit_tramp_page_common_code (MonoAotCompile *acfg, int pagesize, int arg_reg, int *size)
1264 guint8 buf [256];
1265 guint8 *code;
1266 int imm;
1268 /* The common code */
1269 code = buf;
1270 imm = pagesize;
1271 /* The trampoline address is in IP0 */
1272 arm_movzx (code, ARMREG_IP1, imm & 0xffff, 0);
1273 arm_movkx (code, ARMREG_IP1, (imm >> 16) & 0xffff, 16);
1274 /* Compute the data slot address */
1275 arm_subx (code, ARMREG_IP0, ARMREG_IP0, ARMREG_IP1);
1276 /* Trampoline argument */
1277 arm_ldrx (code, arg_reg, ARMREG_IP0, 0);
1278 /* Address */
1279 arm_ldrx (code, ARMREG_IP0, ARMREG_IP0, 8);
1280 arm_brx (code, ARMREG_IP0);
1282 /* Emit it */
1283 emit_code_bytes (acfg, buf, code - buf);
1285 *size = code - buf;
1288 static void
1289 arm64_emit_tramp_page_specific_code (MonoAotCompile *acfg, int pagesize, int common_tramp_size, int specific_tramp_size)
1291 guint8 buf [256];
1292 guint8 *code;
1293 int i, count;
1295 count = (pagesize - common_tramp_size) / specific_tramp_size;
1296 for (i = 0; i < count; ++i) {
1297 code = buf;
1298 arm_adrx (code, ARMREG_IP0, code);
1299 /* Branch to the generic code */
1300 arm_b (code, code - 4 - (i * specific_tramp_size) - common_tramp_size);
1301 /* This has to be 2 pointers long */
1302 arm_nop (code);
1303 arm_nop (code);
1304 g_assert (code - buf == specific_tramp_size);
1305 emit_code_bytes (acfg, buf, code - buf);
1309 static void
1310 arm64_emit_specific_trampoline_pages (MonoAotCompile *acfg)
1312 guint8 buf [128];
1313 guint8 *code;
1314 guint8 *labels [16];
1315 int common_tramp_size;
1316 int specific_tramp_size = 2 * 8;
1317 int imm, pagesize;
1318 char symbol [128];
1320 if (!acfg->aot_opts.use_trampolines_page)
1321 return;
1323 #ifdef TARGET_MACH
1324 /* Have to match the target pagesize */
1325 pagesize = 16384;
1326 #else
1327 pagesize = mono_pagesize ();
1328 #endif
1329 acfg->tramp_page_size = pagesize;
1331 /* The specific trampolines */
1332 sprintf (symbol, "%sspecific_trampolines_page", acfg->user_symbol_prefix);
1333 emit_alignment (acfg, pagesize);
1334 emit_global (acfg, symbol, TRUE);
1335 emit_label (acfg, symbol);
1337 /* The common code */
1338 arm64_emit_tramp_page_common_code (acfg, pagesize, ARMREG_IP1, &common_tramp_size);
1339 acfg->tramp_page_code_offsets [MONO_AOT_TRAMP_SPECIFIC] = common_tramp_size;
1341 arm64_emit_tramp_page_specific_code (acfg, pagesize, common_tramp_size, specific_tramp_size);
1343 /* The rgctx trampolines */
1344 /* These are the same as the specific trampolines, but they load the argument into MONO_ARCH_RGCTX_REG */
1345 sprintf (symbol, "%srgctx_trampolines_page", acfg->user_symbol_prefix);
1346 emit_alignment (acfg, pagesize);
1347 emit_global (acfg, symbol, TRUE);
1348 emit_label (acfg, symbol);
1350 /* The common code */
1351 arm64_emit_tramp_page_common_code (acfg, pagesize, MONO_ARCH_RGCTX_REG, &common_tramp_size);
1352 acfg->tramp_page_code_offsets [MONO_AOT_TRAMP_STATIC_RGCTX] = common_tramp_size;
1354 arm64_emit_tramp_page_specific_code (acfg, pagesize, common_tramp_size, specific_tramp_size);
1356 /* The gsharedvt arg trampolines */
1357 /* These are the same as the specific trampolines */
1358 sprintf (symbol, "%sgsharedvt_arg_trampolines_page", acfg->user_symbol_prefix);
1359 emit_alignment (acfg, pagesize);
1360 emit_global (acfg, symbol, TRUE);
1361 emit_label (acfg, symbol);
1363 arm64_emit_tramp_page_common_code (acfg, pagesize, ARMREG_IP1, &common_tramp_size);
1364 acfg->tramp_page_code_offsets [MONO_AOT_TRAMP_GSHAREDVT_ARG] = common_tramp_size;
1366 arm64_emit_tramp_page_specific_code (acfg, pagesize, common_tramp_size, specific_tramp_size);
1368 /* Unbox arbitrary trampolines */
1369 sprintf (symbol, "%sunbox_arbitrary_trampolines_page", acfg->user_symbol_prefix);
1370 emit_alignment (acfg, pagesize);
1371 emit_global (acfg, symbol, TRUE);
1372 emit_label (acfg, symbol);
1374 code = buf;
1375 imm = pagesize;
1377 /* Unbox this arg */
1378 arm_addx_imm (code, ARMREG_R0, ARMREG_R0, MONO_ABI_SIZEOF (MonoObject));
1380 /* The trampoline address is in IP0 */
1381 arm_movzx (code, ARMREG_IP1, imm & 0xffff, 0);
1382 arm_movkx (code, ARMREG_IP1, (imm >> 16) & 0xffff, 16);
1383 /* Compute the data slot address */
1384 arm_subx (code, ARMREG_IP0, ARMREG_IP0, ARMREG_IP1);
1385 /* Address */
1386 arm_ldrx (code, ARMREG_IP0, ARMREG_IP0, 0);
1387 arm_brx (code, ARMREG_IP0);
1389 /* Emit it */
1390 emit_code_bytes (acfg, buf, code - buf);
1392 common_tramp_size = code - buf;
1393 acfg->tramp_page_code_offsets [MONO_AOT_TRAMP_UNBOX_ARBITRARY] = common_tramp_size;
1395 arm64_emit_tramp_page_specific_code (acfg, pagesize, common_tramp_size, specific_tramp_size);
1397 /* The IMT trampolines */
1398 sprintf (symbol, "%simt_trampolines_page", acfg->user_symbol_prefix);
1399 emit_alignment (acfg, pagesize);
1400 emit_global (acfg, symbol, TRUE);
1401 emit_label (acfg, symbol);
1403 code = buf;
1404 imm = pagesize;
1405 /* The trampoline address is in IP0 */
1406 arm_movzx (code, ARMREG_IP1, imm & 0xffff, 0);
1407 arm_movkx (code, ARMREG_IP1, (imm >> 16) & 0xffff, 16);
1408 /* Compute the data slot address */
1409 arm_subx (code, ARMREG_IP0, ARMREG_IP0, ARMREG_IP1);
1410 /* Trampoline argument */
1411 arm_ldrx (code, ARMREG_IP1, ARMREG_IP0, 0);
1413 /* Same as arch_emit_imt_trampoline () */
1414 labels [0] = code;
1415 arm_ldrx (code, ARMREG_IP0, ARMREG_IP1, 0);
1416 arm_cmpx (code, ARMREG_IP0, MONO_ARCH_RGCTX_REG);
1417 labels [1] = code;
1418 arm_bcc (code, ARMCOND_EQ, 0);
1420 /* End-of-loop check */
1421 labels [2] = code;
1422 arm_cbzx (code, ARMREG_IP0, 0);
1424 /* Loop footer */
1425 arm_addx_imm (code, ARMREG_IP1, ARMREG_IP1, 2 * 8);
1426 arm_b (code, labels [0]);
1428 /* Match */
1429 mono_arm_patch (labels [1], code, MONO_R_ARM64_BCC);
1430 /* Load vtable slot addr */
1431 arm_ldrx (code, ARMREG_IP0, ARMREG_IP1, 8);
1432 /* Load vtable slot */
1433 arm_ldrx (code, ARMREG_IP0, ARMREG_IP0, 0);
1434 arm_brx (code, ARMREG_IP0);
1436 /* No match */
1437 mono_arm_patch (labels [2], code, MONO_R_ARM64_CBZ);
1438 /* Load fail addr */
1439 arm_ldrx (code, ARMREG_IP0, ARMREG_IP1, 8);
1440 arm_brx (code, ARMREG_IP0);
1442 emit_code_bytes (acfg, buf, code - buf);
1444 common_tramp_size = code - buf;
1445 acfg->tramp_page_code_offsets [MONO_AOT_TRAMP_IMT] = common_tramp_size;
1447 arm64_emit_tramp_page_specific_code (acfg, pagesize, common_tramp_size, specific_tramp_size);
1450 static void
1451 arm64_emit_specific_trampoline (MonoAotCompile *acfg, int offset, int *tramp_size)
1453 /* Load argument from second GOT slot */
1454 arm64_emit_load_got_slot (acfg, ARMREG_R17, offset + 1);
1455 /* Load generic trampoline address from first GOT slot */
1456 arm64_emit_load_got_slot (acfg, ARMREG_R16, offset);
1457 fprintf (acfg->fp, "br x16\n");
1458 *tramp_size = 7 * 4;
1461 static void
1462 arm64_emit_unbox_trampoline (MonoAotCompile *acfg, MonoCompile *cfg, MonoMethod *method, const char *call_target)
1464 emit_unset_mode (acfg);
1465 fprintf (acfg->fp, "add x0, x0, %d\n", (int)(MONO_ABI_SIZEOF (MonoObject)));
1466 fprintf (acfg->fp, "b %s\n", call_target);
1469 static void
1470 arm64_emit_static_rgctx_trampoline (MonoAotCompile *acfg, int offset, int *tramp_size)
1472 /* Similar to the specific trampolines, but use the rgctx reg instead of ip1 */
1474 /* Load argument from first GOT slot */
1475 arm64_emit_load_got_slot (acfg, MONO_ARCH_RGCTX_REG, offset);
1476 /* Load generic trampoline address from second GOT slot */
1477 arm64_emit_load_got_slot (acfg, ARMREG_R16, offset + 1);
1478 fprintf (acfg->fp, "br x16\n");
1479 *tramp_size = 7 * 4;
1482 static void
1483 arm64_emit_imt_trampoline (MonoAotCompile *acfg, int offset, int *tramp_size)
1485 guint8 buf [128];
1486 guint8 *code, *labels [16];
1488 /* Load parameter from GOT slot into ip1 */
1489 arm64_emit_load_got_slot (acfg, ARMREG_R17, offset);
1491 code = buf;
1492 labels [0] = code;
1493 arm_ldrx (code, ARMREG_IP0, ARMREG_IP1, 0);
1494 arm_cmpx (code, ARMREG_IP0, MONO_ARCH_RGCTX_REG);
1495 labels [1] = code;
1496 arm_bcc (code, ARMCOND_EQ, 0);
1498 /* End-of-loop check */
1499 labels [2] = code;
1500 arm_cbzx (code, ARMREG_IP0, 0);
1502 /* Loop footer */
1503 arm_addx_imm (code, ARMREG_IP1, ARMREG_IP1, 2 * 8);
1504 arm_b (code, labels [0]);
1506 /* Match */
1507 mono_arm_patch (labels [1], code, MONO_R_ARM64_BCC);
1508 /* Load vtable slot addr */
1509 arm_ldrx (code, ARMREG_IP0, ARMREG_IP1, 8);
1510 /* Load vtable slot */
1511 arm_ldrx (code, ARMREG_IP0, ARMREG_IP0, 0);
1512 arm_brx (code, ARMREG_IP0);
1514 /* No match */
1515 mono_arm_patch (labels [2], code, MONO_R_ARM64_CBZ);
1516 /* Load fail addr */
1517 arm_ldrx (code, ARMREG_IP0, ARMREG_IP1, 8);
1518 arm_brx (code, ARMREG_IP0);
1520 emit_code_bytes (acfg, buf, code - buf);
1522 *tramp_size = code - buf + (3 * 4);
1525 static void
1526 arm64_emit_gsharedvt_arg_trampoline (MonoAotCompile *acfg, int offset, int *tramp_size)
1528 /* Similar to the specific trampolines, but the address is in the second slot */
1529 /* Load argument from first GOT slot */
1530 arm64_emit_load_got_slot (acfg, ARMREG_R17, offset);
1531 /* Load generic trampoline address from second GOT slot */
1532 arm64_emit_load_got_slot (acfg, ARMREG_R16, offset + 1);
1533 fprintf (acfg->fp, "br x16\n");
1534 *tramp_size = 7 * 4;
1538 #endif
1540 #ifdef MONO_ARCH_AOT_SUPPORTED
1542 * arch_emit_direct_call:
1544 * Emit a direct call to the symbol TARGET. CALL_SIZE is set to the size of the
1545 * calling code.
1547 static void
1548 arch_emit_direct_call (MonoAotCompile *acfg, const char *target, gboolean external, gboolean thumb, MonoJumpInfo *ji, int *call_size)
1550 #if defined(TARGET_X86) || defined(TARGET_AMD64)
1551 /* Need to make sure this is exactly 5 bytes long */
1552 emit_unset_mode (acfg);
1553 fprintf (acfg->fp, "call %s\n", target);
1554 *call_size = 5;
1555 #elif defined(TARGET_ARM)
1556 emit_unset_mode (acfg);
1557 if (thumb)
1558 fprintf (acfg->fp, "blx %s\n", target);
1559 else
1560 fprintf (acfg->fp, "bl %s\n", target);
1561 *call_size = 4;
1562 #elif defined(TARGET_ARM64)
1563 arm64_emit_direct_call (acfg, target, external, thumb, ji, call_size);
1564 #elif defined(TARGET_POWERPC)
1565 emit_unset_mode (acfg);
1566 fprintf (acfg->fp, "bl %s\n", target);
1567 *call_size = 4;
1568 #else
1569 g_assert_not_reached ();
1570 #endif
1572 #endif
1575 * PPC32 design:
1576 * - we use an approach similar to the x86 abi: reserve a register (r30) to hold
1577 * the GOT pointer.
1578 * - The full-aot trampolines need access to the GOT of mscorlib, so we store
1579 * in in the 2. slot of every GOT, and require every method to place the GOT
1580 * address in r30, even when it doesn't access the GOT otherwise. This way,
1581 * the trampolines can compute the mscorlib GOT address by loading 4(r30).
1585 * PPC64 design:
1586 * PPC64 uses function descriptors which greatly complicate all code, since
1587 * these are used very inconsistently in the runtime. Some functions like
1588 * mono_compile_method () return ftn descriptors, while others like the
1589 * trampoline creation functions do not.
1590 * We assume that all GOT slots contain function descriptors, and create
1591 * descriptors in aot-runtime.c when needed.
1592 * The ppc64 abi uses r2 to hold the address of the TOC/GOT, which is loaded
1593 * from function descriptors, we could do the same, but it would require
1594 * rewriting all the ppc/aot code to handle function descriptors properly.
1595 * So instead, we use the same approach as on PPC32.
1596 * This is a horrible mess, but fixing it would probably lead to an even bigger
1597 * one.
1601 * X86 design:
1602 * - similar to the PPC32 design, we reserve EBX to hold the GOT pointer.
1605 #ifdef MONO_ARCH_AOT_SUPPORTED
1607 * arch_emit_got_offset:
1609 * The memory pointed to by CODE should hold native code for computing the GOT
1610 * address (OP_LOAD_GOTADDR). Emit this code while patching it with the offset
1611 * between code and the GOT. CODE_SIZE is set to the number of bytes emitted.
1613 static void
1614 arch_emit_got_offset (MonoAotCompile *acfg, guint8 *code, int *code_size)
1616 #if defined(TARGET_POWERPC64)
1617 emit_unset_mode (acfg);
1619 * The ppc32 code doesn't seem to work on ppc64, the assembler complains about
1620 * unsupported relocations. So we store the got address into the .Lgot_addr
1621 * symbol which is in the text segment, compute its address, and load it.
1623 fprintf (acfg->fp, ".L%d:\n", acfg->label_generator);
1624 fprintf (acfg->fp, "lis 0, (.Lgot_addr + 4 - .L%d)@h\n", acfg->label_generator);
1625 fprintf (acfg->fp, "ori 0, 0, (.Lgot_addr + 4 - .L%d)@l\n", acfg->label_generator);
1626 fprintf (acfg->fp, "add 30, 30, 0\n");
1627 fprintf (acfg->fp, "%s 30, 0(30)\n", PPC_LD_OP);
1628 acfg->label_generator ++;
1629 *code_size = 16;
1630 #elif defined(TARGET_POWERPC)
1631 emit_unset_mode (acfg);
1632 fprintf (acfg->fp, ".L%d:\n", acfg->label_generator);
1633 fprintf (acfg->fp, "lis 0, (%s + 4 - .L%d)@h\n", acfg->got_symbol, acfg->label_generator);
1634 fprintf (acfg->fp, "ori 0, 0, (%s + 4 - .L%d)@l\n", acfg->got_symbol, acfg->label_generator);
1635 acfg->label_generator ++;
1636 *code_size = 8;
1637 #else
1638 guint32 offset = mono_arch_get_patch_offset (code);
1639 emit_bytes (acfg, code, offset);
1640 emit_symbol_diff (acfg, acfg->got_symbol, ".", offset);
1642 *code_size = offset + 4;
1643 #endif
1647 * arch_emit_got_access:
1649 * The memory pointed to by CODE should hold native code for loading a GOT
1650 * slot (OP_AOTCONST/OP_GOT_ENTRY). Emit this code while patching it so it accesses the
1651 * GOT slot GOT_SLOT. CODE_SIZE is set to the number of bytes emitted.
1653 static void
1654 arch_emit_got_access (MonoAotCompile *acfg, const char *got_symbol, guint8 *code, int got_slot, int *code_size)
1656 #ifdef TARGET_AMD64
1657 /* mov reg, got+offset(%rip) */
1658 if (acfg->llvm) {
1659 /* The GOT symbol is in the LLVM module, the clang assembler has problems emitting symbol diffs for it */
1660 int dreg;
1661 int rex_r;
1663 /* Decode reg, see amd64_mov_reg_membase () */
1664 rex_r = code [0] & AMD64_REX_R;
1665 g_assert (code [0] == 0x49 + rex_r);
1666 g_assert (code [1] == 0x8b);
1667 dreg = ((code [2] >> 3) & 0x7) + (rex_r ? 8 : 0);
1669 emit_unset_mode (acfg);
1670 fprintf (acfg->fp, "mov %s+%d(%%rip), %s\n", got_symbol, (unsigned int) ((got_slot * sizeof (target_mgreg_t))), mono_arch_regname (dreg));
1671 *code_size = 7;
1672 } else {
1673 emit_bytes (acfg, code, mono_arch_get_patch_offset (code));
1674 emit_symbol_diff (acfg, got_symbol, ".", (unsigned int) ((got_slot * sizeof (target_mgreg_t)) - 4));
1675 *code_size = mono_arch_get_patch_offset (code) + 4;
1677 #elif defined(TARGET_X86)
1678 emit_bytes (acfg, code, mono_arch_get_patch_offset (code));
1679 emit_int32 (acfg, (unsigned int) ((got_slot * sizeof (target_mgreg_t))));
1680 *code_size = mono_arch_get_patch_offset (code) + 4;
1681 #elif defined(TARGET_ARM)
1682 emit_bytes (acfg, code, mono_arch_get_patch_offset (code));
1683 emit_symbol_diff (acfg, got_symbol, ".", (unsigned int) ((got_slot * sizeof (target_mgreg_t))) - 12);
1684 *code_size = mono_arch_get_patch_offset (code) + 4;
1685 #elif defined(TARGET_ARM64)
1686 emit_bytes (acfg, code, mono_arch_get_patch_offset (code));
1687 arm64_emit_got_access (acfg, code, got_slot, code_size);
1688 #elif defined(TARGET_POWERPC)
1690 guint8 buf [32];
1692 emit_bytes (acfg, code, mono_arch_get_patch_offset (code));
1693 code = buf;
1694 ppc_load32 (code, ppc_r0, got_slot * sizeof (target_mgreg_t));
1695 g_assert (code - buf == 8);
1696 emit_bytes (acfg, buf, code - buf);
1697 *code_size = code - buf;
1699 #else
1700 g_assert_not_reached ();
1701 #endif
1704 #endif
1706 #ifdef MONO_ARCH_AOT_SUPPORTED
1708 * arch_emit_objc_selector_ref:
1710 * Emit the implementation of OP_OBJC_GET_SELECTOR, which itself implements @selector(foo:) in objective-c.
1712 static void
1713 arch_emit_objc_selector_ref (MonoAotCompile *acfg, guint8 *code, int index, int *code_size)
1715 #if defined(TARGET_ARM)
1716 char symbol1 [MAX_SYMBOL_SIZE];
1717 char symbol2 [MAX_SYMBOL_SIZE];
1718 int lindex = acfg->objc_selector_index_2 ++;
1720 /* Emit ldr.imm/b */
1721 emit_bytes (acfg, code, 8);
1723 sprintf (symbol1, "L_OBJC_SELECTOR_%d", lindex);
1724 sprintf (symbol2, "L_OBJC_SELECTOR_REFERENCES_%d", index);
1726 emit_label (acfg, symbol1);
1727 mono_img_writer_emit_unset_mode (acfg->w);
1728 fprintf (acfg->fp, ".long %s-(%s+12)", symbol2, symbol1);
1730 *code_size = 12;
1731 #elif defined(TARGET_ARM64)
1732 arm64_emit_objc_selector_ref (acfg, code, index, code_size);
1733 #else
1734 g_assert_not_reached ();
1735 #endif
1737 #endif
1740 * arch_emit_plt_entry:
1742 * Emit code for the PLT entry.
1743 * The plt entry should look like this:
1744 * <indirect jump to GOT_SYMBOL + OFFSET>
1745 * <INFO_OFFSET embedded into the instruction stream>
1747 static void
1748 arch_emit_plt_entry (MonoAotCompile *acfg, const char *got_symbol, int offset, int info_offset)
1750 #if defined(TARGET_X86)
1751 /* jmp *<offset>(%ebx) */
1752 emit_byte (acfg, 0xff);
1753 emit_byte (acfg, 0xa3);
1754 emit_int32 (acfg, offset);
1755 /* Used by mono_aot_get_plt_info_offset */
1756 emit_int32 (acfg, info_offset);
1757 #elif defined(TARGET_AMD64)
1758 emit_unset_mode (acfg);
1759 fprintf (acfg->fp, "jmp *%s+%d(%%rip)\n", got_symbol, offset);
1760 /* Used by mono_aot_get_plt_info_offset */
1761 emit_int32 (acfg, info_offset);
1762 acfg->stats.plt_size += 10;
1763 #elif defined(TARGET_ARM)
1764 guint8 buf [256];
1765 guint8 *code;
1767 code = buf;
1768 ARM_LDR_IMM (code, ARMREG_IP, ARMREG_PC, 0);
1769 ARM_LDR_REG_REG (code, ARMREG_PC, ARMREG_PC, ARMREG_IP);
1770 emit_bytes (acfg, buf, code - buf);
1771 emit_symbol_diff (acfg, got_symbol, ".", offset - 4);
1772 /* Used by mono_aot_get_plt_info_offset */
1773 emit_int32 (acfg, info_offset);
1774 #elif defined(TARGET_ARM64)
1775 arm64_emit_plt_entry (acfg, got_symbol, offset, info_offset);
1776 #elif defined(TARGET_POWERPC)
1777 /* The GOT address is guaranteed to be in r30 by OP_LOAD_GOTADDR */
1778 emit_unset_mode (acfg);
1779 fprintf (acfg->fp, "lis 11, %d@h\n", offset);
1780 fprintf (acfg->fp, "ori 11, 11, %d@l\n", offset);
1781 fprintf (acfg->fp, "add 11, 11, 30\n");
1782 fprintf (acfg->fp, "%s 11, 0(11)\n", PPC_LD_OP);
1783 #ifdef PPC_USES_FUNCTION_DESCRIPTOR
1784 fprintf (acfg->fp, "%s 2, %d(11)\n", PPC_LD_OP, (int)sizeof (target_mgreg_t));
1785 fprintf (acfg->fp, "%s 11, 0(11)\n", PPC_LD_OP);
1786 #endif
1787 fprintf (acfg->fp, "mtctr 11\n");
1788 fprintf (acfg->fp, "bctr\n");
1789 emit_int32 (acfg, info_offset);
1790 #else
1791 g_assert_not_reached ();
1792 #endif
1796 * arch_emit_llvm_plt_entry:
1798 * Same as arch_emit_plt_entry, but handles calls from LLVM generated code.
1799 * This is only needed on arm to handle thumb interop.
1801 static void
1802 arch_emit_llvm_plt_entry (MonoAotCompile *acfg, const char *got_symbol, int offset, int info_offset)
1804 #if defined(TARGET_ARM)
1805 /* LLVM calls the PLT entries using bl, so these have to be thumb2 */
1806 /* The caller already transitioned to thumb */
1807 /* The code below should be 12 bytes long */
1808 /* clang has trouble encoding these instructions, so emit the binary */
1809 #if 0
1810 fprintf (acfg->fp, "ldr ip, [pc, #8]\n");
1811 /* thumb can't encode ld pc, [pc, ip] */
1812 fprintf (acfg->fp, "add ip, pc, ip\n");
1813 fprintf (acfg->fp, "ldr ip, [ip, #0]\n");
1814 fprintf (acfg->fp, "bx ip\n");
1815 #endif
1816 emit_set_thumb_mode (acfg);
1817 fprintf (acfg->fp, ".4byte 0xc008f8df\n");
1818 fprintf (acfg->fp, ".2byte 0x44fc\n");
1819 fprintf (acfg->fp, ".4byte 0xc000f8dc\n");
1820 fprintf (acfg->fp, ".2byte 0x4760\n");
1821 emit_symbol_diff (acfg, got_symbol, ".", offset + 4);
1822 emit_int32 (acfg, info_offset);
1823 emit_unset_mode (acfg);
1824 emit_set_arm_mode (acfg);
1825 #else
1826 g_assert_not_reached ();
1827 #endif
1830 /* Save unwind_info in the module and emit the offset to the information at symbol */
1831 static void save_unwind_info (MonoAotCompile *acfg, char *symbol, GSList *unwind_ops)
1833 guint32 uw_offset, encoded_len;
1834 guint8 *encoded;
1836 emit_section_change (acfg, RODATA_SECT, 0);
1837 emit_global (acfg, symbol, FALSE);
1838 emit_label (acfg, symbol);
1840 encoded = mono_unwind_ops_encode (unwind_ops, &encoded_len);
1841 uw_offset = get_unwind_info_offset (acfg, encoded, encoded_len);
1842 g_free (encoded);
1843 emit_int32 (acfg, uw_offset);
1847 * arch_emit_specific_trampoline_pages:
1849 * Emits a page full of trampolines: each trampoline uses its own address to
1850 * lookup both the generic trampoline code and the data argument.
1851 * This page can be remapped in process multiple times so we can get an
1852 * unlimited number of trampolines.
1853 * Specifically this implementation uses the following trick: two memory pages
1854 * are allocated, with the first containing the data and the second containing the trampolines.
1855 * To reduce trampoline size, each trampoline jumps at the start of the page where a common
1856 * implementation does all the lifting.
1857 * Note that the ARM single trampoline size is 8 bytes, exactly like the data that needs to be stored
1858 * on the arm 32 bit system.
1860 static void
1861 arch_emit_specific_trampoline_pages (MonoAotCompile *acfg)
1863 #if defined(TARGET_ARM)
1864 guint8 buf [128];
1865 guint8 *code;
1866 guint8 *loop_start, *loop_branch_back, *loop_end_check, *imt_found_check;
1867 int i;
1868 int pagesize = MONO_AOT_TRAMP_PAGE_SIZE;
1869 GSList *unwind_ops = NULL;
1870 #define COMMON_TRAMP_SIZE 16
1871 int count = (pagesize - COMMON_TRAMP_SIZE) / 8;
1872 int imm8, rot_amount;
1873 char symbol [128];
1875 if (!acfg->aot_opts.use_trampolines_page)
1876 return;
1878 acfg->tramp_page_size = pagesize;
1880 sprintf (symbol, "%sspecific_trampolines_page", acfg->user_symbol_prefix);
1881 emit_alignment (acfg, pagesize);
1882 emit_global (acfg, symbol, TRUE);
1883 emit_label (acfg, symbol);
1885 /* emit the generic code first, the trampoline address + 8 is in the lr register */
1886 code = buf;
1887 imm8 = mono_arm_is_rotated_imm8 (pagesize, &rot_amount);
1888 ARM_SUB_REG_IMM (code, ARMREG_LR, ARMREG_LR, imm8, rot_amount);
1889 ARM_LDR_IMM (code, ARMREG_R1, ARMREG_LR, -8);
1890 ARM_LDR_IMM (code, ARMREG_PC, ARMREG_LR, -4);
1891 ARM_NOP (code);
1892 g_assert (code - buf == COMMON_TRAMP_SIZE);
1894 /* Emit it */
1895 emit_bytes (acfg, buf, code - buf);
1897 for (i = 0; i < count; ++i) {
1898 code = buf;
1899 ARM_PUSH (code, 0x5fff);
1900 ARM_BL (code, 0);
1901 arm_patch (code - 4, code - COMMON_TRAMP_SIZE - 8 * (i + 1));
1902 g_assert (code - buf == 8);
1903 emit_bytes (acfg, buf, code - buf);
1906 /* now the rgctx trampolines: each specific trampolines puts in the ip register
1907 * the instruction pointer address, so the generic trampoline at the start of the page
1908 * subtracts 4096 to get to the data page and loads the values
1909 * We again fit the generic trampiline in 16 bytes.
1911 sprintf (symbol, "%srgctx_trampolines_page", acfg->user_symbol_prefix);
1912 emit_global (acfg, symbol, TRUE);
1913 emit_label (acfg, symbol);
1914 code = buf;
1915 imm8 = mono_arm_is_rotated_imm8 (pagesize, &rot_amount);
1916 ARM_SUB_REG_IMM (code, ARMREG_IP, ARMREG_IP, imm8, rot_amount);
1917 ARM_LDR_IMM (code, MONO_ARCH_RGCTX_REG, ARMREG_IP, -8);
1918 ARM_LDR_IMM (code, ARMREG_PC, ARMREG_IP, -4);
1919 ARM_NOP (code);
1920 g_assert (code - buf == COMMON_TRAMP_SIZE);
1922 /* Emit it */
1923 emit_bytes (acfg, buf, code - buf);
1925 for (i = 0; i < count; ++i) {
1926 code = buf;
1927 ARM_MOV_REG_REG (code, ARMREG_IP, ARMREG_PC);
1928 ARM_B (code, 0);
1929 arm_patch (code - 4, code - COMMON_TRAMP_SIZE - 8 * (i + 1));
1930 g_assert (code - buf == 8);
1931 emit_bytes (acfg, buf, code - buf);
1935 * gsharedvt arg trampolines: see arch_emit_gsharedvt_arg_trampoline ()
1937 sprintf (symbol, "%sgsharedvt_arg_trampolines_page", acfg->user_symbol_prefix);
1938 emit_global (acfg, symbol, TRUE);
1939 emit_label (acfg, symbol);
1940 code = buf;
1941 ARM_PUSH (code, (1 << ARMREG_R0) | (1 << ARMREG_R1) | (1 << ARMREG_R2) | (1 << ARMREG_R3));
1942 imm8 = mono_arm_is_rotated_imm8 (pagesize, &rot_amount);
1943 ARM_SUB_REG_IMM (code, ARMREG_IP, ARMREG_IP, imm8, rot_amount);
1944 ARM_LDR_IMM (code, ARMREG_R0, ARMREG_IP, -8);
1945 ARM_LDR_IMM (code, ARMREG_PC, ARMREG_IP, -4);
1946 g_assert (code - buf == COMMON_TRAMP_SIZE);
1947 /* Emit it */
1948 emit_bytes (acfg, buf, code - buf);
1950 for (i = 0; i < count; ++i) {
1951 code = buf;
1952 ARM_MOV_REG_REG (code, ARMREG_IP, ARMREG_PC);
1953 ARM_B (code, 0);
1954 arm_patch (code - 4, code - COMMON_TRAMP_SIZE - 8 * (i + 1));
1955 g_assert (code - buf == 8);
1956 emit_bytes (acfg, buf, code - buf);
1959 /* now the unbox arbitrary trampolines: each specific trampolines puts in the ip register
1960 * the instruction pointer address, so the generic trampoline at the start of the page
1961 * subtracts 4096 to get to the data page and loads the target addr.
1962 * We again fit the generic trampoline in 16 bytes.
1964 sprintf (symbol, "%sunbox_arbitrary_trampolines_page", acfg->user_symbol_prefix);
1965 emit_global (acfg, symbol, TRUE);
1966 emit_label (acfg, symbol);
1967 code = buf;
1969 ARM_ADD_REG_IMM8 (code, ARMREG_R0, ARMREG_R0, MONO_ABI_SIZEOF (MonoObject));
1970 imm8 = mono_arm_is_rotated_imm8 (pagesize, &rot_amount);
1971 ARM_SUB_REG_IMM (code, ARMREG_IP, ARMREG_IP, imm8, rot_amount);
1972 ARM_LDR_IMM (code, ARMREG_PC, ARMREG_IP, -4);
1973 ARM_NOP (code);
1974 g_assert (code - buf == COMMON_TRAMP_SIZE);
1976 /* Emit it */
1977 emit_bytes (acfg, buf, code - buf);
1979 for (i = 0; i < count; ++i) {
1980 code = buf;
1981 ARM_MOV_REG_REG (code, ARMREG_IP, ARMREG_PC);
1982 ARM_B (code, 0);
1983 arm_patch (code - 4, code - COMMON_TRAMP_SIZE - 8 * (i + 1));
1984 g_assert (code - buf == 8);
1985 emit_bytes (acfg, buf, code - buf);
1988 /* now the imt trampolines: each specific trampolines puts in the ip register
1989 * the instruction pointer address, so the generic trampoline at the start of the page
1990 * subtracts 4096 to get to the data page and loads the values
1992 #define IMT_TRAMP_SIZE 72
1993 sprintf (symbol, "%simt_trampolines_page", acfg->user_symbol_prefix);
1994 emit_global (acfg, symbol, TRUE);
1995 emit_label (acfg, symbol);
1996 code = buf;
1997 /* Need at least two free registers, plus a slot for storing the pc */
1998 ARM_PUSH (code, (1 << ARMREG_R0)|(1 << ARMREG_R1)|(1 << ARMREG_R2));
2000 imm8 = mono_arm_is_rotated_imm8 (pagesize, &rot_amount);
2001 ARM_SUB_REG_IMM (code, ARMREG_IP, ARMREG_IP, imm8, rot_amount);
2002 ARM_LDR_IMM (code, ARMREG_R0, ARMREG_IP, -8);
2004 /* The IMT method is in v5, r0 has the imt array address */
2006 loop_start = code;
2007 ARM_LDR_IMM (code, ARMREG_R1, ARMREG_R0, 0);
2008 ARM_CMP_REG_REG (code, ARMREG_R1, ARMREG_V5);
2009 imt_found_check = code;
2010 ARM_B_COND (code, ARMCOND_EQ, 0);
2012 /* End-of-loop check */
2013 ARM_CMP_REG_IMM (code, ARMREG_R1, 0, 0);
2014 loop_end_check = code;
2015 ARM_B_COND (code, ARMCOND_EQ, 0);
2017 /* Loop footer */
2018 ARM_ADD_REG_IMM8 (code, ARMREG_R0, ARMREG_R0, sizeof (target_mgreg_t) * 2);
2019 loop_branch_back = code;
2020 ARM_B (code, 0);
2021 arm_patch (loop_branch_back, loop_start);
2023 /* Match */
2024 arm_patch (imt_found_check, code);
2025 ARM_LDR_IMM (code, ARMREG_R0, ARMREG_R0, 4);
2026 ARM_LDR_IMM (code, ARMREG_R0, ARMREG_R0, 0);
2027 /* Save it to the third stack slot */
2028 ARM_STR_IMM (code, ARMREG_R0, ARMREG_SP, 8);
2029 /* Restore the registers and branch */
2030 ARM_POP (code, (1 << ARMREG_R0)|(1 << ARMREG_R1)|(1 << ARMREG_PC));
2032 /* No match */
2033 arm_patch (loop_end_check, code);
2034 ARM_LDR_IMM (code, ARMREG_R0, ARMREG_R0, 4);
2035 ARM_STR_IMM (code, ARMREG_R0, ARMREG_SP, 8);
2036 ARM_POP (code, (1 << ARMREG_R0)|(1 << ARMREG_R1)|(1 << ARMREG_PC));
2037 ARM_NOP (code);
2039 /* Emit it */
2040 g_assert (code - buf == IMT_TRAMP_SIZE);
2041 emit_bytes (acfg, buf, code - buf);
2043 for (i = 0; i < count; ++i) {
2044 code = buf;
2045 ARM_MOV_REG_REG (code, ARMREG_IP, ARMREG_PC);
2046 ARM_B (code, 0);
2047 arm_patch (code - 4, code - IMT_TRAMP_SIZE - 8 * (i + 1));
2048 g_assert (code - buf == 8);
2049 emit_bytes (acfg, buf, code - buf);
2052 acfg->tramp_page_code_offsets [MONO_AOT_TRAMP_SPECIFIC] = 16;
2053 acfg->tramp_page_code_offsets [MONO_AOT_TRAMP_STATIC_RGCTX] = 16;
2054 acfg->tramp_page_code_offsets [MONO_AOT_TRAMP_IMT] = 72;
2055 acfg->tramp_page_code_offsets [MONO_AOT_TRAMP_GSHAREDVT_ARG] = 16;
2056 acfg->tramp_page_code_offsets [MONO_AOT_TRAMP_UNBOX_ARBITRARY] = 16;
2058 /* Unwind info for specifc trampolines */
2059 sprintf (symbol, "%sspecific_trampolines_page_gen_p", acfg->user_symbol_prefix);
2060 /* We unwind to the original caller, from the stack, since lr is clobbered */
2061 mono_add_unwind_op_def_cfa (unwind_ops, 0, 0, ARMREG_SP, 14 * sizeof (target_mgreg_t));
2062 mono_add_unwind_op_offset (unwind_ops, 0, 0, ARMREG_LR, -4);
2063 save_unwind_info (acfg, symbol, unwind_ops);
2064 mono_free_unwind_info (unwind_ops);
2066 sprintf (symbol, "%sspecific_trampolines_page_sp_p", acfg->user_symbol_prefix);
2067 mono_add_unwind_op_def_cfa (unwind_ops, 0, 0, ARMREG_SP, 0);
2068 mono_add_unwind_op_def_cfa_offset (unwind_ops, 4, 0, 14 * sizeof (target_mgreg_t));
2069 save_unwind_info (acfg, symbol, unwind_ops);
2070 mono_free_unwind_info (unwind_ops);
2072 /* Unwind info for rgctx trampolines */
2073 sprintf (symbol, "%srgctx_trampolines_page_gen_p", acfg->user_symbol_prefix);
2074 mono_add_unwind_op_def_cfa (unwind_ops, 0, 0, ARMREG_SP, 0);
2075 save_unwind_info (acfg, symbol, unwind_ops);
2077 sprintf (symbol, "%srgctx_trampolines_page_sp_p", acfg->user_symbol_prefix);
2078 save_unwind_info (acfg, symbol, unwind_ops);
2079 mono_free_unwind_info (unwind_ops);
2081 /* Unwind info for gsharedvt trampolines */
2082 sprintf (symbol, "%sgsharedvt_trampolines_page_gen_p", acfg->user_symbol_prefix);
2083 mono_add_unwind_op_def_cfa (unwind_ops, 0, 0, ARMREG_SP, 0);
2084 mono_add_unwind_op_def_cfa_offset (unwind_ops, 4, 0, 4 * sizeof (target_mgreg_t));
2085 save_unwind_info (acfg, symbol, unwind_ops);
2086 mono_free_unwind_info (unwind_ops);
2088 sprintf (symbol, "%sgsharedvt_trampolines_page_sp_p", acfg->user_symbol_prefix);
2089 mono_add_unwind_op_def_cfa (unwind_ops, 0, 0, ARMREG_SP, 0);
2090 save_unwind_info (acfg, symbol, unwind_ops);
2091 mono_free_unwind_info (unwind_ops);
2093 /* Unwind info for unbox arbitrary trampolines */
2094 sprintf (symbol, "%sunbox_arbitrary_trampolines_page_gen_p", acfg->user_symbol_prefix);
2095 mono_add_unwind_op_def_cfa (unwind_ops, 0, 0, ARMREG_SP, 0);
2096 save_unwind_info (acfg, symbol, unwind_ops);
2098 sprintf (symbol, "%sunbox_arbitrary_trampolines_page_sp_p", acfg->user_symbol_prefix);
2099 save_unwind_info (acfg, symbol, unwind_ops);
2100 mono_free_unwind_info (unwind_ops);
2102 /* Unwind info for imt trampolines */
2103 sprintf (symbol, "%simt_trampolines_page_gen_p", acfg->user_symbol_prefix);
2104 mono_add_unwind_op_def_cfa (unwind_ops, 0, 0, ARMREG_SP, 0);
2105 mono_add_unwind_op_def_cfa_offset (unwind_ops, 4, 0, 3 * sizeof (target_mgreg_t));
2106 save_unwind_info (acfg, symbol, unwind_ops);
2107 mono_free_unwind_info (unwind_ops);
2109 sprintf (symbol, "%simt_trampolines_page_sp_p", acfg->user_symbol_prefix);
2110 mono_add_unwind_op_def_cfa (unwind_ops, 0, 0, ARMREG_SP, 0);
2111 save_unwind_info (acfg, symbol, unwind_ops);
2112 mono_free_unwind_info (unwind_ops);
2113 #elif defined(TARGET_ARM64)
2114 arm64_emit_specific_trampoline_pages (acfg);
2115 #endif
2119 * arch_emit_specific_trampoline:
2121 * Emit code for a specific trampoline. OFFSET is the offset of the first of
2122 * two GOT slots which contain the generic trampoline address and the trampoline
2123 * argument. TRAMP_SIZE is set to the size of the emitted trampoline.
2125 static void
2126 arch_emit_specific_trampoline (MonoAotCompile *acfg, int offset, int *tramp_size)
2129 * The trampolines created here are variations of the specific
2130 * trampolines created in mono_arch_create_specific_trampoline (). The
2131 * differences are:
2132 * - the generic trampoline address is taken from a got slot.
2133 * - the offset of the got slot where the trampoline argument is stored
2134 * is embedded in the instruction stream, and the generic trampoline
2135 * can load the argument by loading the offset, adding it to the
2136 * address of the trampoline to get the address of the got slot, and
2137 * loading the argument from there.
2138 * - all the trampolines should be of the same length.
2140 #if defined(TARGET_AMD64)
2141 /* This should be exactly 8 bytes long */
2142 *tramp_size = 8;
2143 /* call *<offset>(%rip) */
2144 if (acfg->llvm) {
2145 emit_unset_mode (acfg);
2146 fprintf (acfg->fp, "call *%s+%d(%%rip)\n", acfg->got_symbol, (int)(offset * sizeof (target_mgreg_t)));
2147 emit_zero_bytes (acfg, 2);
2148 } else {
2149 emit_byte (acfg, '\x41');
2150 emit_byte (acfg, '\xff');
2151 emit_byte (acfg, '\x15');
2152 emit_symbol_diff (acfg, acfg->got_symbol, ".", (offset * sizeof (target_mgreg_t)) - 4);
2153 emit_zero_bytes (acfg, 1);
2155 #elif defined(TARGET_ARM)
2156 guint8 buf [128];
2157 guint8 *code;
2159 /* This should be exactly 20 bytes long */
2160 *tramp_size = 20;
2161 code = buf;
2162 ARM_PUSH (code, 0x5fff);
2163 ARM_LDR_IMM (code, ARMREG_R1, ARMREG_PC, 4);
2164 /* Load the value from the GOT */
2165 ARM_LDR_REG_REG (code, ARMREG_R1, ARMREG_PC, ARMREG_R1);
2166 /* Branch to it */
2167 ARM_BLX_REG (code, ARMREG_R1);
2169 g_assert (code - buf == 16);
2171 /* Emit it */
2172 emit_bytes (acfg, buf, code - buf);
2174 * Only one offset is needed, since the second one would be equal to the
2175 * first one.
2177 emit_symbol_diff (acfg, acfg->got_symbol, ".", (offset * sizeof (target_mgreg_t)) - 4 + 4);
2178 //emit_symbol_diff (acfg, acfg->got_symbol, ".", ((offset + 1) * sizeof (target_mgreg_t)) - 4 + 8);
2179 #elif defined(TARGET_ARM64)
2180 arm64_emit_specific_trampoline (acfg, offset, tramp_size);
2181 #elif defined(TARGET_POWERPC)
2182 guint8 buf [128];
2183 guint8 *code;
2185 *tramp_size = 4;
2186 code = buf;
2189 * PPC has no ip relative addressing, so we need to compute the address
2190 * of the mscorlib got. That is slow and complex, so instead, we store it
2191 * in the second got slot of every aot image. The caller already computed
2192 * the address of its got and placed it into r30.
2194 emit_unset_mode (acfg);
2195 /* Load mscorlib got address */
2196 fprintf (acfg->fp, "%s 0, %d(30)\n", PPC_LD_OP, (int)sizeof (target_mgreg_t));
2197 /* Load generic trampoline address */
2198 fprintf (acfg->fp, "lis 11, %d@h\n", (int)(offset * sizeof (target_mgreg_t)));
2199 fprintf (acfg->fp, "ori 11, 11, %d@l\n", (int)(offset * sizeof (target_mgreg_t)));
2200 fprintf (acfg->fp, "%s 11, 11, 0\n", PPC_LDX_OP);
2201 #ifdef PPC_USES_FUNCTION_DESCRIPTOR
2202 fprintf (acfg->fp, "%s 11, 0(11)\n", PPC_LD_OP);
2203 #endif
2204 fprintf (acfg->fp, "mtctr 11\n");
2205 /* Load trampoline argument */
2206 /* On ppc, we pass it normally to the generic trampoline */
2207 fprintf (acfg->fp, "lis 11, %d@h\n", (int)((offset + 1) * sizeof (target_mgreg_t)));
2208 fprintf (acfg->fp, "ori 11, 11, %d@l\n", (int)((offset + 1) * sizeof (target_mgreg_t)));
2209 fprintf (acfg->fp, "%s 0, 11, 0\n", PPC_LDX_OP);
2210 /* Branch to generic trampoline */
2211 fprintf (acfg->fp, "bctr\n");
2213 #ifdef PPC_USES_FUNCTION_DESCRIPTOR
2214 *tramp_size = 10 * 4;
2215 #else
2216 *tramp_size = 9 * 4;
2217 #endif
2218 #elif defined(TARGET_X86)
2219 guint8 buf [128];
2220 guint8 *code;
2222 /* Similar to the PPC code above */
2224 /* FIXME: Could this clobber the register needed by get_vcall_slot () ? */
2226 code = buf;
2227 /* Load mscorlib got address */
2228 x86_mov_reg_membase (code, X86_ECX, MONO_ARCH_GOT_REG, sizeof (target_mgreg_t), 4);
2229 /* Push trampoline argument */
2230 x86_push_membase (code, X86_ECX, (offset + 1) * sizeof (target_mgreg_t));
2231 /* Load generic trampoline address */
2232 x86_mov_reg_membase (code, X86_ECX, X86_ECX, offset * sizeof (target_mgreg_t), 4);
2233 /* Branch to generic trampoline */
2234 x86_jump_reg (code, X86_ECX);
2236 emit_bytes (acfg, buf, code - buf);
2238 *tramp_size = 17;
2239 g_assert (code - buf == *tramp_size);
2240 #else
2241 g_assert_not_reached ();
2242 #endif
2246 * arch_emit_unbox_trampoline:
2248 * Emit code for the unbox trampoline for METHOD used in the full-aot case.
2249 * CALL_TARGET is the symbol pointing to the native code of METHOD.
2251 * See mono_aot_get_unbox_trampoline.
2253 static void
2254 arch_emit_unbox_trampoline (MonoAotCompile *acfg, MonoCompile *cfg, MonoMethod *method, const char *call_target)
2256 #if defined(TARGET_AMD64)
2257 guint8 buf [32];
2258 guint8 *code;
2259 int this_reg;
2261 this_reg = mono_arch_get_this_arg_reg (NULL);
2262 code = buf;
2263 amd64_alu_reg_imm (code, X86_ADD, this_reg, MONO_ABI_SIZEOF (MonoObject));
2265 emit_bytes (acfg, buf, code - buf);
2266 /* jump <method> */
2267 if (acfg->llvm) {
2268 emit_unset_mode (acfg);
2269 fprintf (acfg->fp, "jmp %s\n", call_target);
2270 } else {
2271 emit_byte (acfg, '\xe9');
2272 emit_symbol_diff (acfg, call_target, ".", -4);
2274 #elif defined(TARGET_X86)
2275 guint8 buf [32];
2276 guint8 *code;
2277 int this_pos = 4;
2279 code = buf;
2281 x86_alu_membase_imm (code, X86_ADD, X86_ESP, this_pos, MONO_ABI_SIZEOF (MonoObject));
2283 emit_bytes (acfg, buf, code - buf);
2285 /* jump <method> */
2286 emit_byte (acfg, '\xe9');
2287 emit_symbol_diff (acfg, call_target, ".", -4);
2288 #elif defined(TARGET_ARM)
2289 guint8 buf [128];
2290 guint8 *code;
2292 if (acfg->thumb_mixed && cfg->compile_llvm) {
2293 fprintf (acfg->fp, "add r0, r0, #%d\n", (int)MONO_ABI_SIZEOF (MonoObject));
2294 fprintf (acfg->fp, "b %s\n", call_target);
2295 fprintf (acfg->fp, ".arm\n");
2296 fprintf (acfg->fp, ".align 2\n");
2297 return;
2300 code = buf;
2302 ARM_ADD_REG_IMM8 (code, ARMREG_R0, ARMREG_R0, MONO_ABI_SIZEOF (MonoObject));
2304 emit_bytes (acfg, buf, code - buf);
2305 /* jump to method */
2306 if (acfg->thumb_mixed && cfg->compile_llvm)
2307 fprintf (acfg->fp, "\n\tbx %s\n", call_target);
2308 else
2309 fprintf (acfg->fp, "\n\tb %s\n", call_target);
2310 #elif defined(TARGET_ARM64)
2311 arm64_emit_unbox_trampoline (acfg, cfg, method, call_target);
2312 #elif defined(TARGET_POWERPC)
2313 int this_pos = 3;
2315 fprintf (acfg->fp, "\n\taddi %d, %d, %d\n", this_pos, this_pos, (int)MONO_ABI_SIZEOF (MonoObject));
2316 fprintf (acfg->fp, "\n\tb %s\n", call_target);
2317 #else
2318 g_assert_not_reached ();
2319 #endif
2323 * arch_emit_static_rgctx_trampoline:
2325 * Emit code for a static rgctx trampoline. OFFSET is the offset of the first of
2326 * two GOT slots which contain the rgctx argument, and the method to jump to.
2327 * TRAMP_SIZE is set to the size of the emitted trampoline.
2328 * These kinds of trampolines cannot be enumerated statically, since there could
2329 * be one trampoline per method instantiation, so we emit the same code for all
2330 * trampolines, and parameterize them using two GOT slots.
2332 static void
2333 arch_emit_static_rgctx_trampoline (MonoAotCompile *acfg, int offset, int *tramp_size)
2335 #if defined(TARGET_AMD64)
2336 /* This should be exactly 13 bytes long */
2337 *tramp_size = 13;
2339 if (acfg->llvm) {
2340 emit_unset_mode (acfg);
2341 fprintf (acfg->fp, "mov %s+%d(%%rip), %%r10\n", acfg->got_symbol, (int)(offset * sizeof (target_mgreg_t)));
2342 fprintf (acfg->fp, "jmp *%s+%d(%%rip)\n", acfg->got_symbol, (int)((offset + 1) * sizeof (target_mgreg_t)));
2343 } else {
2344 /* mov <OFFSET>(%rip), %r10 */
2345 emit_byte (acfg, '\x4d');
2346 emit_byte (acfg, '\x8b');
2347 emit_byte (acfg, '\x15');
2348 emit_symbol_diff (acfg, acfg->got_symbol, ".", (offset * sizeof (target_mgreg_t)) - 4);
2350 /* jmp *<offset>(%rip) */
2351 emit_byte (acfg, '\xff');
2352 emit_byte (acfg, '\x25');
2353 emit_symbol_diff (acfg, acfg->got_symbol, ".", ((offset + 1) * sizeof (target_mgreg_t)) - 4);
2355 #elif defined(TARGET_ARM)
2356 guint8 buf [128];
2357 guint8 *code;
2359 /* This should be exactly 24 bytes long */
2360 *tramp_size = 24;
2361 code = buf;
2362 /* Load rgctx value */
2363 ARM_LDR_IMM (code, ARMREG_IP, ARMREG_PC, 8);
2364 ARM_LDR_REG_REG (code, MONO_ARCH_RGCTX_REG, ARMREG_PC, ARMREG_IP);
2365 /* Load branch addr + branch */
2366 ARM_LDR_IMM (code, ARMREG_IP, ARMREG_PC, 4);
2367 ARM_LDR_REG_REG (code, ARMREG_PC, ARMREG_PC, ARMREG_IP);
2369 g_assert (code - buf == 16);
2371 /* Emit it */
2372 emit_bytes (acfg, buf, code - buf);
2373 emit_symbol_diff (acfg, acfg->got_symbol, ".", (offset * sizeof (target_mgreg_t)) - 4 + 8);
2374 emit_symbol_diff (acfg, acfg->got_symbol, ".", ((offset + 1) * sizeof (target_mgreg_t)) - 4 + 4);
2375 #elif defined(TARGET_ARM64)
2376 arm64_emit_static_rgctx_trampoline (acfg, offset, tramp_size);
2377 #elif defined(TARGET_POWERPC)
2378 guint8 buf [128];
2379 guint8 *code;
2381 *tramp_size = 4;
2382 code = buf;
2385 * PPC has no ip relative addressing, so we need to compute the address
2386 * of the mscorlib got. That is slow and complex, so instead, we store it
2387 * in the second got slot of every aot image. The caller already computed
2388 * the address of its got and placed it into r30.
2390 emit_unset_mode (acfg);
2391 /* Load mscorlib got address */
2392 fprintf (acfg->fp, "%s 0, %d(30)\n", PPC_LD_OP, (int)sizeof (target_mgreg_t));
2393 /* Load rgctx */
2394 fprintf (acfg->fp, "lis 11, %d@h\n", (int)(offset * sizeof (target_mgreg_t)));
2395 fprintf (acfg->fp, "ori 11, 11, %d@l\n", (int)(offset * sizeof (target_mgreg_t)));
2396 fprintf (acfg->fp, "%s %d, 11, 0\n", PPC_LDX_OP, MONO_ARCH_RGCTX_REG);
2397 /* Load target address */
2398 fprintf (acfg->fp, "lis 11, %d@h\n", (int)((offset + 1) * sizeof (target_mgreg_t)));
2399 fprintf (acfg->fp, "ori 11, 11, %d@l\n", (int)((offset + 1) * sizeof (target_mgreg_t)));
2400 fprintf (acfg->fp, "%s 11, 11, 0\n", PPC_LDX_OP);
2401 #ifdef PPC_USES_FUNCTION_DESCRIPTOR
2402 fprintf (acfg->fp, "%s 2, %d(11)\n", PPC_LD_OP, (int)sizeof (target_mgreg_t));
2403 fprintf (acfg->fp, "%s 11, 0(11)\n", PPC_LD_OP);
2404 #endif
2405 fprintf (acfg->fp, "mtctr 11\n");
2406 /* Branch to the target address */
2407 fprintf (acfg->fp, "bctr\n");
2409 #ifdef PPC_USES_FUNCTION_DESCRIPTOR
2410 *tramp_size = 11 * 4;
2411 #else
2412 *tramp_size = 9 * 4;
2413 #endif
2415 #elif defined(TARGET_X86)
2416 guint8 buf [128];
2417 guint8 *code;
2419 /* Similar to the PPC code above */
2421 g_assert (MONO_ARCH_RGCTX_REG != X86_ECX);
2423 code = buf;
2424 /* Load mscorlib got address */
2425 x86_mov_reg_membase (code, X86_ECX, MONO_ARCH_GOT_REG, sizeof (target_mgreg_t), 4);
2426 /* Load arg */
2427 x86_mov_reg_membase (code, MONO_ARCH_RGCTX_REG, X86_ECX, offset * sizeof (target_mgreg_t), 4);
2428 /* Branch to the target address */
2429 x86_jump_membase (code, X86_ECX, (offset + 1) * sizeof (target_mgreg_t));
2431 emit_bytes (acfg, buf, code - buf);
2433 *tramp_size = 15;
2434 g_assert (code - buf == *tramp_size);
2435 #else
2436 g_assert_not_reached ();
2437 #endif
2441 * arch_emit_imt_trampoline:
2443 * Emit an IMT trampoline usable in full-aot mode. The trampoline uses 1 got slot which
2444 * points to an array of pointer pairs. The pairs of the form [key, ptr], where
2445 * key is the IMT key, and ptr holds the address of a memory location holding
2446 * the address to branch to if the IMT arg matches the key. The array is
2447 * terminated by a pair whose key is NULL, and whose ptr is the address of the
2448 * fail_tramp.
2449 * TRAMP_SIZE is set to the size of the emitted trampoline.
2451 static void
2452 arch_emit_imt_trampoline (MonoAotCompile *acfg, int offset, int *tramp_size)
2454 #if defined(TARGET_AMD64)
2455 guint8 *buf, *code;
2456 guint8 *labels [16];
2457 guint8 mov_buf[3];
2458 guint8 *mov_buf_ptr = mov_buf;
2460 const int kSizeOfMove = 7;
2462 code = buf = (guint8 *)g_malloc (256);
2464 /* FIXME: Optimize this, i.e. use binary search etc. */
2465 /* Maybe move the body into a separate function (slower, but much smaller) */
2467 /* MONO_ARCH_IMT_SCRATCH_REG is a free register */
2469 if (acfg->llvm) {
2470 emit_unset_mode (acfg);
2471 fprintf (acfg->fp, "mov %s+%d(%%rip), %s\n", acfg->got_symbol, (int)(offset * sizeof (target_mgreg_t)), mono_arch_regname (MONO_ARCH_IMT_SCRATCH_REG));
2474 labels [0] = code;
2475 amd64_alu_membase_imm (code, X86_CMP, MONO_ARCH_IMT_SCRATCH_REG, 0, 0);
2476 labels [1] = code;
2477 amd64_branch8 (code, X86_CC_Z, 0, FALSE);
2479 /* Check key */
2480 amd64_alu_membase_reg_size (code, X86_CMP, MONO_ARCH_IMT_SCRATCH_REG, 0, MONO_ARCH_IMT_REG, sizeof (target_mgreg_t));
2481 labels [2] = code;
2482 amd64_branch8 (code, X86_CC_Z, 0, FALSE);
2484 /* Loop footer */
2485 amd64_alu_reg_imm (code, X86_ADD, MONO_ARCH_IMT_SCRATCH_REG, 2 * sizeof (target_mgreg_t));
2486 amd64_jump_code (code, labels [0]);
2488 /* Match */
2489 mono_amd64_patch (labels [2], code);
2490 amd64_mov_reg_membase (code, MONO_ARCH_IMT_SCRATCH_REG, MONO_ARCH_IMT_SCRATCH_REG, sizeof (target_mgreg_t), sizeof (target_mgreg_t));
2491 amd64_jump_membase (code, MONO_ARCH_IMT_SCRATCH_REG, 0);
2493 /* No match */
2494 mono_amd64_patch (labels [1], code);
2495 /* Load fail tramp */
2496 amd64_alu_reg_imm (code, X86_ADD, MONO_ARCH_IMT_SCRATCH_REG, sizeof (target_mgreg_t));
2497 /* Check if there is a fail tramp */
2498 amd64_alu_membase_imm (code, X86_CMP, MONO_ARCH_IMT_SCRATCH_REG, 0, 0);
2499 labels [3] = code;
2500 amd64_branch8 (code, X86_CC_Z, 0, FALSE);
2501 /* Jump to fail tramp */
2502 amd64_jump_membase (code, MONO_ARCH_IMT_SCRATCH_REG, 0);
2504 /* Fail */
2505 mono_amd64_patch (labels [3], code);
2506 x86_breakpoint (code);
2508 if (!acfg->llvm) {
2509 /* mov <OFFSET>(%rip), MONO_ARCH_IMT_SCRATCH_REG */
2510 amd64_emit_rex (mov_buf_ptr, sizeof(gpointer), MONO_ARCH_IMT_SCRATCH_REG, 0, AMD64_RIP);
2511 *(mov_buf_ptr)++ = (unsigned char)0x8b; /* mov opcode */
2512 x86_address_byte (mov_buf_ptr, 0, MONO_ARCH_IMT_SCRATCH_REG & 0x7, 5);
2513 emit_bytes (acfg, mov_buf, mov_buf_ptr - mov_buf);
2514 emit_symbol_diff (acfg, acfg->got_symbol, ".", (offset * sizeof (target_mgreg_t)) - 4);
2516 emit_bytes (acfg, buf, code - buf);
2518 *tramp_size = code - buf + kSizeOfMove;
2520 g_free (buf);
2522 #elif defined(TARGET_X86)
2523 guint8 *buf, *code;
2524 guint8 *labels [16];
2526 code = buf = g_malloc (256);
2528 /* Allocate a temporary stack slot */
2529 x86_push_reg (code, X86_EAX);
2530 /* Save EAX */
2531 x86_push_reg (code, X86_EAX);
2533 /* Load mscorlib got address */
2534 x86_mov_reg_membase (code, X86_EAX, MONO_ARCH_GOT_REG, sizeof (target_mgreg_t), 4);
2535 /* Load arg */
2536 x86_mov_reg_membase (code, X86_EAX, X86_EAX, offset * sizeof (target_mgreg_t), 4);
2538 labels [0] = code;
2539 x86_alu_membase_imm (code, X86_CMP, X86_EAX, 0, 0);
2540 labels [1] = code;
2541 x86_branch8 (code, X86_CC_Z, FALSE, 0);
2543 /* Check key */
2544 x86_alu_membase_reg (code, X86_CMP, X86_EAX, 0, MONO_ARCH_IMT_REG);
2545 labels [2] = code;
2546 x86_branch8 (code, X86_CC_Z, FALSE, 0);
2548 /* Loop footer */
2549 x86_alu_reg_imm (code, X86_ADD, X86_EAX, 2 * sizeof (target_mgreg_t));
2550 x86_jump_code (code, labels [0]);
2552 /* Match */
2553 mono_x86_patch (labels [2], code);
2554 x86_mov_reg_membase (code, X86_EAX, X86_EAX, sizeof (target_mgreg_t), 4);
2555 x86_mov_reg_membase (code, X86_EAX, X86_EAX, 0, 4);
2556 /* Save the target address to the temporary stack location */
2557 x86_mov_membase_reg (code, X86_ESP, 4, X86_EAX, 4);
2558 /* Restore EAX */
2559 x86_pop_reg (code, X86_EAX);
2560 /* Jump to the target address */
2561 x86_ret (code);
2563 /* No match */
2564 mono_x86_patch (labels [1], code);
2565 /* Load fail tramp */
2566 x86_mov_reg_membase (code, X86_EAX, X86_EAX, sizeof (target_mgreg_t), 4);
2567 x86_alu_membase_imm (code, X86_CMP, X86_EAX, 0, 0);
2568 labels [3] = code;
2569 x86_branch8 (code, X86_CC_Z, FALSE, 0);
2570 /* Jump to fail tramp */
2571 x86_mov_membase_reg (code, X86_ESP, 4, X86_EAX, 4);
2572 x86_pop_reg (code, X86_EAX);
2573 x86_ret (code);
2575 /* Fail */
2576 mono_x86_patch (labels [3], code);
2577 x86_breakpoint (code);
2579 emit_bytes (acfg, buf, code - buf);
2581 *tramp_size = code - buf;
2583 g_free (buf);
2585 #elif defined(TARGET_ARM)
2586 guint8 buf [128];
2587 guint8 *code, *code2, *labels [16];
2589 code = buf;
2591 /* The IMT method is in v5 */
2593 /* Need at least two free registers, plus a slot for storing the pc */
2594 ARM_PUSH (code, (1 << ARMREG_R0)|(1 << ARMREG_R1)|(1 << ARMREG_R2));
2595 labels [0] = code;
2596 /* Load the parameter from the GOT */
2597 ARM_LDR_IMM (code, ARMREG_R0, ARMREG_PC, 0);
2598 ARM_LDR_REG_REG (code, ARMREG_R0, ARMREG_PC, ARMREG_R0);
2600 labels [1] = code;
2601 ARM_LDR_IMM (code, ARMREG_R1, ARMREG_R0, 0);
2602 ARM_CMP_REG_REG (code, ARMREG_R1, ARMREG_V5);
2603 labels [2] = code;
2604 ARM_B_COND (code, ARMCOND_EQ, 0);
2606 /* End-of-loop check */
2607 ARM_CMP_REG_IMM (code, ARMREG_R1, 0, 0);
2608 labels [3] = code;
2609 ARM_B_COND (code, ARMCOND_EQ, 0);
2611 /* Loop footer */
2612 ARM_ADD_REG_IMM8 (code, ARMREG_R0, ARMREG_R0, sizeof (target_mgreg_t) * 2);
2613 labels [4] = code;
2614 ARM_B (code, 0);
2615 arm_patch (labels [4], labels [1]);
2617 /* Match */
2618 arm_patch (labels [2], code);
2619 ARM_LDR_IMM (code, ARMREG_R0, ARMREG_R0, 4);
2620 ARM_LDR_IMM (code, ARMREG_R0, ARMREG_R0, 0);
2621 /* Save it to the third stack slot */
2622 ARM_STR_IMM (code, ARMREG_R0, ARMREG_SP, 8);
2623 /* Restore the registers and branch */
2624 ARM_POP (code, (1 << ARMREG_R0)|(1 << ARMREG_R1)|(1 << ARMREG_PC));
2626 /* No match */
2627 arm_patch (labels [3], code);
2628 ARM_LDR_IMM (code, ARMREG_R0, ARMREG_R0, 4);
2629 ARM_STR_IMM (code, ARMREG_R0, ARMREG_SP, 8);
2630 ARM_POP (code, (1 << ARMREG_R0)|(1 << ARMREG_R1)|(1 << ARMREG_PC));
2632 /* Fixup offset */
2633 code2 = labels [0];
2634 ARM_LDR_IMM (code2, ARMREG_R0, ARMREG_PC, (code - (labels [0] + 8)));
2636 emit_bytes (acfg, buf, code - buf);
2637 emit_symbol_diff (acfg, acfg->got_symbol, ".", (offset * sizeof (target_mgreg_t)) + (code - (labels [0] + 8)) - 4);
2639 *tramp_size = code - buf + 4;
2640 #elif defined(TARGET_ARM64)
2641 arm64_emit_imt_trampoline (acfg, offset, tramp_size);
2642 #elif defined(TARGET_POWERPC)
2643 guint8 buf [128];
2644 guint8 *code, *labels [16];
2646 code = buf;
2648 /* Load the mscorlib got address */
2649 ppc_ldptr (code, ppc_r12, sizeof (target_mgreg_t), ppc_r30);
2650 /* Load the parameter from the GOT */
2651 ppc_load (code, ppc_r0, offset * sizeof (target_mgreg_t));
2652 ppc_ldptr_indexed (code, ppc_r12, ppc_r12, ppc_r0);
2654 /* Load and check key */
2655 labels [1] = code;
2656 ppc_ldptr (code, ppc_r0, 0, ppc_r12);
2657 ppc_cmp (code, 0, sizeof (target_mgreg_t) == 8 ? 1 : 0, ppc_r0, MONO_ARCH_IMT_REG);
2658 labels [2] = code;
2659 ppc_bc (code, PPC_BR_TRUE, PPC_BR_EQ, 0);
2661 /* End-of-loop check */
2662 ppc_cmpi (code, 0, sizeof (target_mgreg_t) == 8 ? 1 : 0, ppc_r0, 0);
2663 labels [3] = code;
2664 ppc_bc (code, PPC_BR_TRUE, PPC_BR_EQ, 0);
2666 /* Loop footer */
2667 ppc_addi (code, ppc_r12, ppc_r12, 2 * sizeof (target_mgreg_t));
2668 labels [4] = code;
2669 ppc_b (code, 0);
2670 mono_ppc_patch (labels [4], labels [1]);
2672 /* Match */
2673 mono_ppc_patch (labels [2], code);
2674 ppc_ldptr (code, ppc_r12, sizeof (target_mgreg_t), ppc_r12);
2675 /* r12 now contains the value of the vtable slot */
2676 /* this is not a function descriptor on ppc64 */
2677 ppc_ldptr (code, ppc_r12, 0, ppc_r12);
2678 ppc_mtctr (code, ppc_r12);
2679 ppc_bcctr (code, PPC_BR_ALWAYS, 0);
2681 /* Fail */
2682 mono_ppc_patch (labels [3], code);
2683 /* FIXME: */
2684 ppc_break (code);
2686 *tramp_size = code - buf;
2688 emit_bytes (acfg, buf, code - buf);
2689 #else
2690 g_assert_not_reached ();
2691 #endif
2695 #if defined (TARGET_AMD64)
2697 static void
2698 amd64_emit_load_got_slot (MonoAotCompile *acfg, int dreg, int got_slot)
2701 g_assert (acfg->fp);
2702 emit_unset_mode (acfg);
2704 fprintf (acfg->fp, "mov %s+%d(%%rip), %s\n", acfg->got_symbol, (unsigned int) ((got_slot * sizeof (target_mgreg_t))), mono_arch_regname (dreg));
2707 #endif
2711 * arch_emit_gsharedvt_arg_trampoline:
2713 * Emit code for a gsharedvt arg trampoline. OFFSET is the offset of the first of
2714 * two GOT slots which contain the argument, and the code to jump to.
2715 * TRAMP_SIZE is set to the size of the emitted trampoline.
2716 * These kinds of trampolines cannot be enumerated statically, since there could
2717 * be one trampoline per method instantiation, so we emit the same code for all
2718 * trampolines, and parameterize them using two GOT slots.
2720 static void
2721 arch_emit_gsharedvt_arg_trampoline (MonoAotCompile *acfg, int offset, int *tramp_size)
2723 #if defined(TARGET_X86)
2724 guint8 buf [128];
2725 guint8 *code;
2727 /* Similar to the PPC code above */
2729 g_assert (MONO_ARCH_RGCTX_REG != X86_ECX);
2731 code = buf;
2732 /* Load mscorlib got address */
2733 x86_mov_reg_membase (code, X86_ECX, MONO_ARCH_GOT_REG, sizeof (target_mgreg_t), 4);
2734 /* Load arg */
2735 x86_mov_reg_membase (code, X86_EAX, X86_ECX, offset * sizeof (target_mgreg_t), 4);
2736 /* Branch to the target address */
2737 x86_jump_membase (code, X86_ECX, (offset + 1) * sizeof (target_mgreg_t));
2739 emit_bytes (acfg, buf, code - buf);
2741 *tramp_size = 15;
2742 g_assert (code - buf == *tramp_size);
2743 #elif defined(TARGET_ARM)
2744 guint8 buf [128];
2745 guint8 *code;
2747 /* The same as mono_arch_get_gsharedvt_arg_trampoline (), but for AOT */
2748 /* Similar to arch_emit_specific_trampoline () */
2749 *tramp_size = 24;
2750 code = buf;
2751 ARM_PUSH (code, (1 << ARMREG_R0) | (1 << ARMREG_R1) | (1 << ARMREG_R2) | (1 << ARMREG_R3));
2752 ARM_LDR_IMM (code, ARMREG_R1, ARMREG_PC, 8);
2753 /* Load the arg value from the GOT */
2754 ARM_LDR_REG_REG (code, ARMREG_R0, ARMREG_PC, ARMREG_R1);
2755 /* Load the addr from the GOT */
2756 ARM_LDR_REG_REG (code, ARMREG_R1, ARMREG_PC, ARMREG_R1);
2757 /* Branch to it */
2758 ARM_BX (code, ARMREG_R1);
2760 g_assert (code - buf == 20);
2762 /* Emit it */
2763 emit_bytes (acfg, buf, code - buf);
2764 emit_symbol_diff (acfg, acfg->got_symbol, ".", (offset * sizeof (target_mgreg_t)) + 4);
2765 #elif defined(TARGET_ARM64)
2766 arm64_emit_gsharedvt_arg_trampoline (acfg, offset, tramp_size);
2767 #elif defined (TARGET_AMD64)
2769 amd64_emit_load_got_slot (acfg, AMD64_RAX, offset);
2770 amd64_emit_load_got_slot (acfg, MONO_ARCH_IMT_SCRATCH_REG, offset + 1);
2771 g_assert (AMD64_R11 == MONO_ARCH_IMT_SCRATCH_REG);
2772 fprintf (acfg->fp, "jmp *%%r11\n");
2774 *tramp_size = 0x11;
2775 #else
2776 g_assert_not_reached ();
2777 #endif
2780 static void
2781 arch_emit_ftnptr_arg_trampoline (MonoAotCompile *acfg, int offset, int *tramp_size)
2783 #if defined(TARGET_ARM)
2784 guint8 buf [128];
2785 guint8 *code;
2787 *tramp_size = 32;
2788 code = buf;
2790 /* Load target address and push it on stack */
2791 ARM_LDR_IMM (code, ARMREG_IP, ARMREG_PC, 16);
2792 ARM_LDR_REG_REG (code, ARMREG_IP, ARMREG_PC, ARMREG_IP);
2793 ARM_PUSH (code, 1 << ARMREG_IP);
2794 /* Load argument in ARMREG_IP */
2795 ARM_LDR_IMM (code, ARMREG_IP, ARMREG_PC, 8);
2796 ARM_LDR_REG_REG (code, ARMREG_IP, ARMREG_PC, ARMREG_IP);
2797 /* Branch */
2798 ARM_POP (code, 1 << ARMREG_PC);
2800 g_assert (code - buf == 24);
2802 /* Emit it */
2803 emit_bytes (acfg, buf, code - buf);
2804 emit_symbol_diff (acfg, acfg->got_symbol, ".", ((offset + 1) * sizeof (target_mgreg_t)) + 12); // offset from ldr pc to addr
2805 emit_symbol_diff (acfg, acfg->got_symbol, ".", (offset * sizeof (target_mgreg_t)) + 4); // offset from ldr pc to arg
2806 #else
2807 g_assert_not_reached ();
2808 #endif
2811 static void
2812 arch_emit_unbox_arbitrary_trampoline (MonoAotCompile *acfg, int offset, int *tramp_size)
2814 #if defined(TARGET_ARM64)
2815 emit_unset_mode (acfg);
2816 fprintf (acfg->fp, "add x0, x0, %d\n", (int)(MONO_ABI_SIZEOF (MonoObject)));
2817 arm64_emit_load_got_slot (acfg, ARMREG_R17, offset);
2818 fprintf (acfg->fp, "br x17\n");
2819 *tramp_size = 5 * 4;
2820 #elif defined (TARGET_AMD64)
2821 guint8 buf [32];
2822 guint8 *code;
2823 int this_reg;
2825 this_reg = mono_arch_get_this_arg_reg (NULL);
2826 code = buf;
2827 amd64_alu_reg_imm (code, X86_ADD, this_reg, MONO_ABI_SIZEOF (MonoObject));
2828 emit_bytes (acfg, buf, code - buf);
2830 amd64_emit_load_got_slot (acfg, AMD64_RAX, offset);
2831 fprintf (acfg->fp, "jmp *%%rax\n");
2833 *tramp_size = 13;
2834 #elif defined (TARGET_ARM)
2835 guint8 buf [32];
2836 guint8 *code, *label;
2838 code = buf;
2839 /* Unbox */
2840 ARM_ADD_REG_IMM8 (code, ARMREG_R0, ARMREG_R0, MONO_ABI_SIZEOF (MonoObject));
2842 label = code;
2843 /* Calculate GOT slot */
2844 ARM_LDR_IMM (code, ARMREG_IP, ARMREG_PC, 0);
2845 /* Load target addr into PC*/
2846 ARM_LDR_REG_REG (code, ARMREG_PC, ARMREG_PC, ARMREG_IP);
2848 g_assert (code - buf == 12);
2850 /* Emit it */
2851 emit_bytes (acfg, buf, code - buf);
2852 emit_symbol_diff (acfg, acfg->got_symbol, ".", (offset * sizeof (target_mgreg_t)) + (code - (label + 8)) - 4);
2853 *tramp_size = 4 * 4;
2854 #else
2855 g_error ("NOT IMPLEMENTED: needed for AOT<>interp mixed mode transition");
2856 #endif
2859 /* END OF ARCH SPECIFIC CODE */
2861 static guint32
2862 mono_get_field_token (MonoClassField *field)
2864 MonoClass *klass = field->parent;
2865 int i;
2867 int fcount = mono_class_get_field_count (klass);
2868 MonoClassField *klass_fields = m_class_get_fields (klass);
2869 for (i = 0; i < fcount; ++i) {
2870 if (field == &klass_fields [i])
2871 return MONO_TOKEN_FIELD_DEF | (mono_class_get_first_field_idx (klass) + 1 + i);
2874 g_assert_not_reached ();
2875 return 0;
2878 static inline void
2879 encode_value (gint32 value, guint8 *buf, guint8 **endbuf)
2881 guint8 *p = buf;
2883 //printf ("ENCODE: %d 0x%x.\n", value, value);
2886 * Same encoding as the one used in the metadata, extended to handle values
2887 * greater than 0x1fffffff.
2889 if ((value >= 0) && (value <= 127))
2890 *p++ = value;
2891 else if ((value >= 0) && (value <= 16383)) {
2892 p [0] = 0x80 | (value >> 8);
2893 p [1] = value & 0xff;
2894 p += 2;
2895 } else if ((value >= 0) && (value <= 0x1fffffff)) {
2896 p [0] = (value >> 24) | 0xc0;
2897 p [1] = (value >> 16) & 0xff;
2898 p [2] = (value >> 8) & 0xff;
2899 p [3] = value & 0xff;
2900 p += 4;
2902 else {
2903 p [0] = 0xff;
2904 p [1] = (value >> 24) & 0xff;
2905 p [2] = (value >> 16) & 0xff;
2906 p [3] = (value >> 8) & 0xff;
2907 p [4] = value & 0xff;
2908 p += 5;
2910 if (endbuf)
2911 *endbuf = p;
2914 static void
2915 stream_init (MonoDynamicStream *sh)
2917 sh->index = 0;
2918 sh->alloc_size = 4096;
2919 sh->data = (char *)g_malloc (4096);
2921 /* So offsets are > 0 */
2922 sh->data [0] = 0;
2923 sh->index ++;
2926 static void
2927 make_room_in_stream (MonoDynamicStream *stream, int size)
2929 if (size <= stream->alloc_size)
2930 return;
2932 while (stream->alloc_size <= size) {
2933 if (stream->alloc_size < 4096)
2934 stream->alloc_size = 4096;
2935 else
2936 stream->alloc_size *= 2;
2939 stream->data = (char *)g_realloc (stream->data, stream->alloc_size);
2942 static guint32
2943 add_stream_data (MonoDynamicStream *stream, const char *data, guint32 len)
2945 guint32 idx;
2947 make_room_in_stream (stream, stream->index + len);
2948 memcpy (stream->data + stream->index, data, len);
2949 idx = stream->index;
2950 stream->index += len;
2951 return idx;
2955 * add_to_blob:
2957 * Add data to the binary blob inside the aot image. Returns the offset inside the
2958 * blob where the data was stored.
2960 static guint32
2961 add_to_blob (MonoAotCompile *acfg, const guint8 *data, guint32 data_len)
2963 g_assert (!acfg->blob_closed);
2965 if (acfg->blob.alloc_size == 0)
2966 stream_init (&acfg->blob);
2968 return add_stream_data (&acfg->blob, (char*)data, data_len);
2971 static guint32
2972 add_to_blob_aligned (MonoAotCompile *acfg, const guint8 *data, guint32 data_len, guint32 align)
2974 char buf [4] = {0};
2975 guint32 count;
2977 if (acfg->blob.alloc_size == 0)
2978 stream_init (&acfg->blob);
2980 count = acfg->blob.index % align;
2982 /* we assume the stream data will be aligned */
2983 if (count)
2984 add_stream_data (&acfg->blob, buf, 4 - count);
2986 return add_stream_data (&acfg->blob, (char*)data, data_len);
2989 /* Emit a table of data into the aot image */
2990 static void
2991 emit_aot_data (MonoAotCompile *acfg, MonoAotFileTable table, const char *symbol, guint8 *data, int size)
2993 if (acfg->data_outfile) {
2994 acfg->table_offsets [(int)table] = acfg->datafile_offset;
2995 fwrite (data,1, size, acfg->data_outfile);
2996 acfg->datafile_offset += size;
2997 // align the data to 8 bytes. Put zeros in the file (so that every build results in consistent output).
2998 int align = 8 - size % 8;
2999 acfg->datafile_offset += align;
3000 guint8 align_buf [16];
3001 memset (&align_buf, 0, sizeof (align_buf));
3002 fwrite (align_buf, align, 1, acfg->data_outfile);
3003 } else if (acfg->llvm) {
3004 mono_llvm_emit_aot_data (symbol, data, size);
3005 } else {
3006 emit_section_change (acfg, RODATA_SECT, 0);
3007 emit_alignment (acfg, 8);
3008 emit_label (acfg, symbol);
3009 emit_bytes (acfg, data, size);
3014 * emit_offset_table:
3016 * Emit a table of increasing offsets in a compact form using differential encoding.
3017 * There is an index entry for each GROUP_SIZE number of entries. The greater the
3018 * group size, the more compact the table becomes, but the slower it becomes to compute
3019 * a given entry. Returns the size of the table.
3021 static guint32
3022 emit_offset_table (MonoAotCompile *acfg, const char *symbol, MonoAotFileTable table, int noffsets, int group_size, gint32 *offsets)
3024 gint32 current_offset;
3025 int i, buf_size, ngroups, index_entry_size;
3026 guint8 *p, *buf;
3027 guint8 *data_p, *data_buf;
3028 guint32 *index_offsets;
3030 ngroups = (noffsets + (group_size - 1)) / group_size;
3032 index_offsets = g_new0 (guint32, ngroups);
3034 buf_size = noffsets * 4;
3035 p = buf = (guint8 *)g_malloc0 (buf_size);
3037 current_offset = 0;
3038 for (i = 0; i < noffsets; ++i) {
3039 //printf ("D: %d -> %d\n", i, offsets [i]);
3040 if ((i % group_size) == 0) {
3041 index_offsets [i / group_size] = p - buf;
3042 /* Emit the full value for these entries */
3043 encode_value (offsets [i], p, &p);
3044 } else {
3045 /* The offsets are allowed to be non-increasing */
3046 //g_assert (offsets [i] >= current_offset);
3047 encode_value (offsets [i] - current_offset, p, &p);
3049 current_offset = offsets [i];
3051 data_buf = buf;
3052 data_p = p;
3054 if (ngroups && index_offsets [ngroups - 1] < 65000)
3055 index_entry_size = 2;
3056 else
3057 index_entry_size = 4;
3059 buf_size = (data_p - data_buf) + (ngroups * 4) + 16;
3060 p = buf = (guint8 *)g_malloc0 (buf_size);
3062 /* Emit the header */
3063 encode_int (noffsets, p, &p);
3064 encode_int (group_size, p, &p);
3065 encode_int (ngroups, p, &p);
3066 encode_int (index_entry_size, p, &p);
3068 /* Emit the index */
3069 for (i = 0; i < ngroups; ++i) {
3070 if (index_entry_size == 2)
3071 encode_int16 (index_offsets [i], p, &p);
3072 else
3073 encode_int (index_offsets [i], p, &p);
3075 /* Emit the data */
3076 memcpy (p, data_buf, data_p - data_buf);
3077 p += data_p - data_buf;
3079 g_assert (p - buf <= buf_size);
3081 emit_aot_data (acfg, table, symbol, buf, p - buf);
3083 g_free (buf);
3084 g_free (data_buf);
3086 return (int)(p - buf);
3089 static guint32
3090 get_image_index (MonoAotCompile *cfg, MonoImage *image)
3092 guint32 index;
3094 index = GPOINTER_TO_UINT (g_hash_table_lookup (cfg->image_hash, image));
3095 if (index)
3096 return index - 1;
3097 else {
3098 index = g_hash_table_size (cfg->image_hash);
3099 g_hash_table_insert (cfg->image_hash, image, GUINT_TO_POINTER (index + 1));
3100 g_ptr_array_add (cfg->image_table, image);
3101 return index;
3105 static guint32
3106 find_typespec_for_class (MonoAotCompile *acfg, MonoClass *klass)
3108 int i;
3109 int len = acfg->image->tables [MONO_TABLE_TYPESPEC].rows;
3111 /* FIXME: Search referenced images as well */
3112 if (!acfg->typespec_classes) {
3113 acfg->typespec_classes = g_hash_table_new (NULL, NULL);
3114 for (i = 0; i < len; i++) {
3115 ERROR_DECL (error);
3116 int typespec = MONO_TOKEN_TYPE_SPEC | (i + 1);
3117 MonoClass *klass_key = mono_class_get_and_inflate_typespec_checked (acfg->image, typespec, NULL, error);
3118 if (!is_ok (error)) {
3119 mono_error_cleanup (error);
3120 continue;
3122 g_hash_table_insert (acfg->typespec_classes, klass_key, GINT_TO_POINTER (typespec));
3125 return GPOINTER_TO_INT (g_hash_table_lookup (acfg->typespec_classes, klass));
3128 static void
3129 encode_method_ref (MonoAotCompile *acfg, MonoMethod *method, guint8 *buf, guint8 **endbuf);
3131 static void
3132 encode_klass_ref (MonoAotCompile *acfg, MonoClass *klass, guint8 *buf, guint8 **endbuf);
3134 static void
3135 encode_ginst (MonoAotCompile *acfg, MonoGenericInst *inst, guint8 *buf, guint8 **endbuf);
3137 static void
3138 encode_type (MonoAotCompile *acfg, MonoType *t, guint8 *buf, guint8 **endbuf);
3140 static void
3141 encode_klass_ref_inner (MonoAotCompile *acfg, MonoClass *klass, guint8 *buf, guint8 **endbuf)
3143 guint8 *p = buf;
3146 * The encoding begins with one of the MONO_AOT_TYPEREF values, followed by additional
3147 * information.
3150 if (mono_class_is_ginst (klass)) {
3151 guint32 token;
3152 g_assert (m_class_get_type_token (klass));
3154 /* Find a typespec for a class if possible */
3155 token = find_typespec_for_class (acfg, klass);
3156 if (token) {
3157 encode_value (MONO_AOT_TYPEREF_TYPESPEC_TOKEN, p, &p);
3158 encode_value (token, p, &p);
3159 } else {
3160 MonoClass *gclass = mono_class_get_generic_class (klass)->container_class;
3161 MonoGenericInst *inst = mono_class_get_generic_class (klass)->context.class_inst;
3162 static int count = 0;
3163 guint8 *p1 = p;
3165 encode_value (MONO_AOT_TYPEREF_GINST, p, &p);
3166 encode_klass_ref (acfg, gclass, p, &p);
3167 encode_ginst (acfg, inst, p, &p);
3169 count += p - p1;
3171 } else if (m_class_get_type_token (klass)) {
3172 int iindex = get_image_index (acfg, m_class_get_image (klass));
3174 g_assert (mono_metadata_token_code (m_class_get_type_token (klass)) == MONO_TOKEN_TYPE_DEF);
3175 if (iindex == 0) {
3176 encode_value (MONO_AOT_TYPEREF_TYPEDEF_INDEX, p, &p);
3177 encode_value (m_class_get_type_token (klass) - MONO_TOKEN_TYPE_DEF, p, &p);
3178 } else {
3179 encode_value (MONO_AOT_TYPEREF_TYPEDEF_INDEX_IMAGE, p, &p);
3180 encode_value (m_class_get_type_token (klass) - MONO_TOKEN_TYPE_DEF, p, &p);
3181 encode_value (get_image_index (acfg, m_class_get_image (klass)), p, &p);
3183 } else if ((m_class_get_byval_arg (klass)->type == MONO_TYPE_VAR) || (m_class_get_byval_arg (klass)->type == MONO_TYPE_MVAR)) {
3184 MonoGenericContainer *container = mono_type_get_generic_param_owner (m_class_get_byval_arg (klass));
3185 MonoGenericParam *par = m_class_get_byval_arg (klass)->data.generic_param;
3187 encode_value (MONO_AOT_TYPEREF_VAR, p, &p);
3189 encode_value (par->gshared_constraint ? 1 : 0, p, &p);
3190 if (par->gshared_constraint) {
3191 MonoGSharedGenericParam *gpar = (MonoGSharedGenericParam*)par;
3192 encode_type (acfg, par->gshared_constraint, p, &p);
3193 encode_klass_ref (acfg, mono_class_create_generic_parameter (gpar->parent), p, &p);
3194 } else {
3195 encode_value (m_class_get_byval_arg (klass)->type, p, &p);
3196 encode_value (mono_type_get_generic_param_num (m_class_get_byval_arg (klass)), p, &p);
3198 encode_value (container->is_anonymous ? 0 : 1, p, &p);
3200 if (!container->is_anonymous) {
3201 encode_value (container->is_method, p, &p);
3202 if (container->is_method)
3203 encode_method_ref (acfg, container->owner.method, p, &p);
3204 else
3205 encode_klass_ref (acfg, container->owner.klass, p, &p);
3208 } else if (m_class_get_byval_arg (klass)->type == MONO_TYPE_PTR) {
3209 encode_value (MONO_AOT_TYPEREF_PTR, p, &p);
3210 encode_type (acfg, m_class_get_byval_arg (klass), p, &p);
3211 } else {
3212 /* Array class */
3213 g_assert (m_class_get_rank (klass) > 0);
3214 encode_value (MONO_AOT_TYPEREF_ARRAY, p, &p);
3215 encode_value (m_class_get_rank (klass), p, &p);
3216 encode_klass_ref (acfg, m_class_get_element_class (klass), p, &p);
3218 *endbuf = p;
3222 * encode_klass_ref:
3224 * Encode a reference to KLASS. We use our home-grown encoding instead of the
3225 * standard metadata encoding.
3227 static void
3228 encode_klass_ref (MonoAotCompile *acfg, MonoClass *klass, guint8 *buf, guint8 **endbuf)
3230 gboolean shared = FALSE;
3233 * The encoding of generic instances is large so emit them only once.
3235 if (mono_class_is_ginst (klass)) {
3236 guint32 token;
3237 g_assert (m_class_get_type_token (klass));
3239 /* Find a typespec for a class if possible */
3240 token = find_typespec_for_class (acfg, klass);
3241 if (!token)
3242 shared = TRUE;
3243 } else if ((m_class_get_byval_arg (klass)->type == MONO_TYPE_VAR) || (m_class_get_byval_arg (klass)->type == MONO_TYPE_MVAR)) {
3244 shared = TRUE;
3247 if (shared) {
3248 guint offset = GPOINTER_TO_UINT (g_hash_table_lookup (acfg->klass_blob_hash, klass));
3249 guint8 *buf2, *p;
3251 if (!offset) {
3252 buf2 = (guint8 *)g_malloc (1024);
3253 p = buf2;
3255 encode_klass_ref_inner (acfg, klass, p, &p);
3256 g_assert (p - buf2 < 1024);
3258 offset = add_to_blob (acfg, buf2, p - buf2);
3259 g_free (buf2);
3261 g_hash_table_insert (acfg->klass_blob_hash, klass, GUINT_TO_POINTER (offset + 1));
3262 } else {
3263 offset --;
3266 p = buf;
3267 encode_value (MONO_AOT_TYPEREF_BLOB_INDEX, p, &p);
3268 encode_value (offset, p, &p);
3269 *endbuf = p;
3270 return;
3273 encode_klass_ref_inner (acfg, klass, buf, endbuf);
3276 static void
3277 encode_field_info (MonoAotCompile *cfg, MonoClassField *field, guint8 *buf, guint8 **endbuf)
3279 guint32 token = mono_get_field_token (field);
3280 guint8 *p = buf;
3282 encode_klass_ref (cfg, field->parent, p, &p);
3283 g_assert (mono_metadata_token_code (token) == MONO_TOKEN_FIELD_DEF);
3284 encode_value (token - MONO_TOKEN_FIELD_DEF, p, &p);
3285 *endbuf = p;
3288 static void
3289 encode_ginst (MonoAotCompile *acfg, MonoGenericInst *inst, guint8 *buf, guint8 **endbuf)
3291 guint8 *p = buf;
3292 int i;
3294 encode_value (inst->type_argc, p, &p);
3295 for (i = 0; i < inst->type_argc; ++i)
3296 encode_klass_ref (acfg, mono_class_from_mono_type_internal (inst->type_argv [i]), p, &p);
3297 *endbuf = p;
3300 static void
3301 encode_generic_context (MonoAotCompile *acfg, MonoGenericContext *context, guint8 *buf, guint8 **endbuf)
3303 guint8 *p = buf;
3304 MonoGenericInst *inst;
3306 inst = context->class_inst;
3307 if (inst) {
3308 g_assert (inst->type_argc);
3309 encode_ginst (acfg, inst, p, &p);
3310 } else {
3311 encode_value (0, p, &p);
3313 inst = context->method_inst;
3314 if (inst) {
3315 g_assert (inst->type_argc);
3316 encode_ginst (acfg, inst, p, &p);
3317 } else {
3318 encode_value (0, p, &p);
3320 *endbuf = p;
3323 static void
3324 encode_type (MonoAotCompile *acfg, MonoType *t, guint8 *buf, guint8 **endbuf)
3326 guint8 *p = buf;
3328 if (t->has_cmods) {
3329 MonoCustomModContainer *cm = mono_type_get_cmods (t);
3331 *p = MONO_TYPE_CMOD_REQD;
3332 ++p;
3334 encode_value (cm->count, p, &p);
3335 int iindex = get_image_index (acfg, cm->image);
3336 encode_value (iindex, p, &p);
3337 for (int i = 0; i < cm->count; ++i) {
3338 encode_value (cm->modifiers [i].required, p, &p);
3339 encode_value (cm->modifiers [i].token, p, &p);
3343 /* t->attrs can be ignored */
3344 //g_assert (t->attrs == 0);
3346 if (t->pinned) {
3347 *p = MONO_TYPE_PINNED;
3348 ++p;
3350 if (t->byref) {
3351 *p = MONO_TYPE_BYREF;
3352 ++p;
3355 *p = t->type;
3356 p ++;
3358 switch (t->type) {
3359 case MONO_TYPE_VOID:
3360 case MONO_TYPE_BOOLEAN:
3361 case MONO_TYPE_CHAR:
3362 case MONO_TYPE_I1:
3363 case MONO_TYPE_U1:
3364 case MONO_TYPE_I2:
3365 case MONO_TYPE_U2:
3366 case MONO_TYPE_I4:
3367 case MONO_TYPE_U4:
3368 case MONO_TYPE_I8:
3369 case MONO_TYPE_U8:
3370 case MONO_TYPE_R4:
3371 case MONO_TYPE_R8:
3372 case MONO_TYPE_I:
3373 case MONO_TYPE_U:
3374 case MONO_TYPE_STRING:
3375 case MONO_TYPE_OBJECT:
3376 case MONO_TYPE_TYPEDBYREF:
3377 break;
3378 case MONO_TYPE_VALUETYPE:
3379 case MONO_TYPE_CLASS:
3380 encode_klass_ref (acfg, mono_class_from_mono_type_internal (t), p, &p);
3381 break;
3382 case MONO_TYPE_SZARRAY:
3383 encode_klass_ref (acfg, t->data.klass, p, &p);
3384 break;
3385 case MONO_TYPE_PTR:
3386 encode_type (acfg, t->data.type, p, &p);
3387 break;
3388 case MONO_TYPE_GENERICINST: {
3389 MonoClass *gclass = t->data.generic_class->container_class;
3390 MonoGenericInst *inst = t->data.generic_class->context.class_inst;
3392 encode_klass_ref (acfg, gclass, p, &p);
3393 encode_ginst (acfg, inst, p, &p);
3394 break;
3396 case MONO_TYPE_ARRAY: {
3397 MonoArrayType *array = t->data.array;
3398 int i;
3400 encode_klass_ref (acfg, array->eklass, p, &p);
3401 encode_value (array->rank, p, &p);
3402 encode_value (array->numsizes, p, &p);
3403 for (i = 0; i < array->numsizes; ++i)
3404 encode_value (array->sizes [i], p, &p);
3405 encode_value (array->numlobounds, p, &p);
3406 for (i = 0; i < array->numlobounds; ++i)
3407 encode_value (array->lobounds [i], p, &p);
3408 break;
3410 case MONO_TYPE_VAR:
3411 case MONO_TYPE_MVAR:
3412 encode_klass_ref (acfg, mono_class_from_mono_type_internal (t), p, &p);
3413 break;
3414 default:
3415 g_assert_not_reached ();
3418 *endbuf = p;
3421 static void
3422 encode_signature (MonoAotCompile *acfg, MonoMethodSignature *sig, guint8 *buf, guint8 **endbuf)
3424 guint8 *p = buf;
3425 guint32 flags = 0;
3426 int i;
3428 /* Similar to the metadata encoding */
3429 if (sig->generic_param_count)
3430 flags |= 0x10;
3431 if (sig->hasthis)
3432 flags |= 0x20;
3433 if (sig->explicit_this)
3434 flags |= 0x40;
3435 flags |= (sig->call_convention & 0x0F);
3437 *p = flags;
3438 ++p;
3439 if (sig->generic_param_count)
3440 encode_value (sig->generic_param_count, p, &p);
3441 encode_value (sig->param_count, p, &p);
3443 encode_type (acfg, sig->ret, p, &p);
3444 for (i = 0; i < sig->param_count; ++i) {
3445 if (sig->sentinelpos == i) {
3446 *p = MONO_TYPE_SENTINEL;
3447 ++p;
3449 encode_type (acfg, sig->params [i], p, &p);
3452 *endbuf = p;
3455 static void
3456 encode_icall (gpointer func, guint8 *p, guint8 **end)
3458 MonoJitICallInfo *callinfo = mono_find_jit_icall_by_addr (func);
3459 g_assert (callinfo);
3460 strcpy ((char *) p, callinfo->name);
3461 p += strlen (callinfo->name) + 1;
3462 *end = p;
3465 #define MAX_IMAGE_INDEX 250
3467 static void
3468 encode_method_ref (MonoAotCompile *acfg, MonoMethod *method, guint8 *buf, guint8 **endbuf)
3470 guint32 image_index = get_image_index (acfg, m_class_get_image (method->klass));
3471 guint32 token = method->token;
3472 MonoJumpInfoToken *ji;
3473 guint8 *p = buf;
3476 * The encoding for most methods is as follows:
3477 * - image index encoded as a leb128
3478 * - token index encoded as a leb128
3479 * Values of image index >= MONO_AOT_METHODREF_MIN are used to mark additional
3480 * types of method encodings.
3483 /* Mark methods which can't use aot trampolines because they need the further
3484 * processing in mono_magic_trampoline () which requires a MonoMethod*.
3486 if ((method->is_generic && (method->flags & METHOD_ATTRIBUTE_VIRTUAL)) ||
3487 (method->iflags & METHOD_IMPL_ATTRIBUTE_SYNCHRONIZED))
3488 encode_value ((MONO_AOT_METHODREF_NO_AOT_TRAMPOLINE << 24), p, &p);
3490 if (method->wrapper_type) {
3491 WrapperInfo *info = mono_marshal_get_wrapper_info (method);
3493 encode_value ((MONO_AOT_METHODREF_WRAPPER << 24), p, &p);
3495 encode_value (method->wrapper_type, p, &p);
3497 switch (method->wrapper_type) {
3498 case MONO_WRAPPER_REMOTING_INVOKE:
3499 case MONO_WRAPPER_REMOTING_INVOKE_WITH_CHECK:
3500 case MONO_WRAPPER_XDOMAIN_INVOKE: {
3501 MonoMethod *m;
3503 m = mono_marshal_method_from_wrapper (method);
3504 g_assert (m);
3505 encode_method_ref (acfg, m, p, &p);
3506 break;
3508 case MONO_WRAPPER_PROXY_ISINST:
3509 case MONO_WRAPPER_LDFLD:
3510 case MONO_WRAPPER_LDFLDA:
3511 case MONO_WRAPPER_STFLD: {
3512 g_assert (info);
3513 encode_klass_ref (acfg, info->d.proxy.klass, p, &p);
3514 break;
3516 case MONO_WRAPPER_ALLOC: {
3517 /* The GC name is saved once in MonoAotFileInfo */
3518 g_assert (info->d.alloc.alloc_type != -1);
3519 encode_value (info->d.alloc.alloc_type, p, &p);
3520 break;
3522 case MONO_WRAPPER_WRITE_BARRIER: {
3523 g_assert (info);
3524 break;
3526 case MONO_WRAPPER_STELEMREF: {
3527 g_assert (info);
3528 encode_value (info->subtype, p, &p);
3529 if (info->subtype == WRAPPER_SUBTYPE_VIRTUAL_STELEMREF)
3530 encode_value (info->d.virtual_stelemref.kind, p, &p);
3531 break;
3533 case MONO_WRAPPER_OTHER: {
3534 g_assert (info);
3535 encode_value (info->subtype, p, &p);
3536 if (info->subtype == WRAPPER_SUBTYPE_PTR_TO_STRUCTURE ||
3537 info->subtype == WRAPPER_SUBTYPE_STRUCTURE_TO_PTR)
3538 encode_klass_ref (acfg, method->klass, p, &p);
3539 else if (info->subtype == WRAPPER_SUBTYPE_SYNCHRONIZED_INNER)
3540 encode_method_ref (acfg, info->d.synchronized_inner.method, p, &p);
3541 else if (info->subtype == WRAPPER_SUBTYPE_ARRAY_ACCESSOR)
3542 encode_method_ref (acfg, info->d.array_accessor.method, p, &p);
3543 else if (info->subtype == WRAPPER_SUBTYPE_INTERP_IN)
3544 encode_signature (acfg, info->d.interp_in.sig, p, &p);
3545 else if (info->subtype == WRAPPER_SUBTYPE_GSHAREDVT_IN_SIG)
3546 encode_signature (acfg, info->d.gsharedvt.sig, p, &p);
3547 else if (info->subtype == WRAPPER_SUBTYPE_GSHAREDVT_OUT_SIG)
3548 encode_signature (acfg, info->d.gsharedvt.sig, p, &p);
3549 else if (info->subtype == WRAPPER_SUBTYPE_INTERP_LMF)
3550 encode_icall (info->d.icall.func, p, &p);
3551 break;
3553 case MONO_WRAPPER_MANAGED_TO_NATIVE: {
3554 g_assert (info);
3555 encode_value (info->subtype, p, &p);
3556 if (info->subtype == WRAPPER_SUBTYPE_ICALL_WRAPPER) {
3557 encode_icall (info->d.icall.func, p, &p);
3558 } else if (info->subtype == WRAPPER_SUBTYPE_NATIVE_FUNC_AOT) {
3559 encode_method_ref (acfg, info->d.managed_to_native.method, p, &p);
3560 } else {
3561 g_assert (info->subtype == WRAPPER_SUBTYPE_NONE || info->subtype == WRAPPER_SUBTYPE_PINVOKE);
3562 encode_method_ref (acfg, info->d.managed_to_native.method, p, &p);
3564 break;
3566 case MONO_WRAPPER_SYNCHRONIZED: {
3567 MonoMethod *m;
3569 m = mono_marshal_method_from_wrapper (method);
3570 g_assert (m);
3571 g_assert (m != method);
3572 encode_method_ref (acfg, m, p, &p);
3573 break;
3575 case MONO_WRAPPER_MANAGED_TO_MANAGED: {
3576 g_assert (info);
3577 encode_value (info->subtype, p, &p);
3579 if (info->subtype == WRAPPER_SUBTYPE_ELEMENT_ADDR) {
3580 encode_value (info->d.element_addr.rank, p, &p);
3581 encode_value (info->d.element_addr.elem_size, p, &p);
3582 } else if (info->subtype == WRAPPER_SUBTYPE_STRING_CTOR) {
3583 encode_method_ref (acfg, info->d.string_ctor.method, p, &p);
3584 } else {
3585 g_assert_not_reached ();
3587 break;
3589 case MONO_WRAPPER_CASTCLASS: {
3590 g_assert (info);
3591 encode_value (info->subtype, p, &p);
3592 break;
3594 case MONO_WRAPPER_RUNTIME_INVOKE: {
3595 g_assert (info);
3596 encode_value (info->subtype, p, &p);
3597 if (info->subtype == WRAPPER_SUBTYPE_RUNTIME_INVOKE_DIRECT || info->subtype == WRAPPER_SUBTYPE_RUNTIME_INVOKE_VIRTUAL)
3598 encode_method_ref (acfg, info->d.runtime_invoke.method, p, &p);
3599 else if (info->subtype == WRAPPER_SUBTYPE_RUNTIME_INVOKE_NORMAL)
3600 encode_signature (acfg, info->d.runtime_invoke.sig, p, &p);
3601 break;
3603 case MONO_WRAPPER_DELEGATE_INVOKE:
3604 case MONO_WRAPPER_DELEGATE_BEGIN_INVOKE:
3605 case MONO_WRAPPER_DELEGATE_END_INVOKE: {
3606 if (method->is_inflated) {
3607 /* These wrappers are identified by their class */
3608 encode_value (1, p, &p);
3609 encode_klass_ref (acfg, method->klass, p, &p);
3610 } else {
3611 MonoMethodSignature *sig = mono_method_signature_internal (method);
3612 WrapperInfo *info = mono_marshal_get_wrapper_info (method);
3614 encode_value (0, p, &p);
3615 if (method->wrapper_type == MONO_WRAPPER_DELEGATE_INVOKE)
3616 encode_value (info ? info->subtype : 0, p, &p);
3617 encode_signature (acfg, sig, p, &p);
3619 break;
3621 case MONO_WRAPPER_NATIVE_TO_MANAGED: {
3622 g_assert (info);
3623 encode_method_ref (acfg, info->d.native_to_managed.method, p, &p);
3624 encode_klass_ref (acfg, info->d.native_to_managed.klass, p, &p);
3625 break;
3627 default:
3628 g_assert_not_reached ();
3630 } else if (mono_method_signature_internal (method)->is_inflated) {
3632 * This is a generic method, find the original token which referenced it and
3633 * encode that.
3634 * Obtain the token from information recorded by the JIT.
3636 ji = (MonoJumpInfoToken *)g_hash_table_lookup (acfg->token_info_hash, method);
3637 if (ji) {
3638 image_index = get_image_index (acfg, ji->image);
3639 g_assert (image_index < MAX_IMAGE_INDEX);
3640 token = ji->token;
3642 encode_value ((MONO_AOT_METHODREF_METHODSPEC << 24), p, &p);
3643 encode_value (image_index, p, &p);
3644 encode_value (token, p, &p);
3645 } else {
3646 MonoMethod *declaring;
3647 MonoGenericContext *context = mono_method_get_context (method);
3649 g_assert (method->is_inflated);
3650 declaring = ((MonoMethodInflated*)method)->declaring;
3653 * This might be a non-generic method of a generic instance, which
3654 * doesn't have a token since the reference is generated by the JIT
3655 * like Nullable:Box/Unbox, or by generic sharing.
3657 encode_value ((MONO_AOT_METHODREF_GINST << 24), p, &p);
3658 /* Encode the klass */
3659 encode_klass_ref (acfg, method->klass, p, &p);
3660 /* Encode the method */
3661 image_index = get_image_index (acfg, m_class_get_image (method->klass));
3662 g_assert (image_index < MAX_IMAGE_INDEX);
3663 g_assert (declaring->token);
3664 token = declaring->token;
3665 g_assert (mono_metadata_token_table (token) == MONO_TABLE_METHOD);
3666 encode_value (image_index, p, &p);
3667 encode_value (token, p, &p);
3668 encode_generic_context (acfg, context, p, &p);
3670 } else if (token == 0) {
3671 /* This might be a method of a constructed type like int[,].Set */
3672 /* Obtain the token from information recorded by the JIT */
3673 ji = (MonoJumpInfoToken *)g_hash_table_lookup (acfg->token_info_hash, method);
3674 if (ji) {
3675 image_index = get_image_index (acfg, ji->image);
3676 g_assert (image_index < MAX_IMAGE_INDEX);
3677 token = ji->token;
3679 encode_value ((MONO_AOT_METHODREF_METHODSPEC << 24), p, &p);
3680 encode_value (image_index, p, &p);
3681 encode_value (token, p, &p);
3682 } else {
3683 /* Array methods */
3684 g_assert (m_class_get_rank (method->klass));
3686 /* Encode directly */
3687 encode_value ((MONO_AOT_METHODREF_ARRAY << 24), p, &p);
3688 encode_klass_ref (acfg, method->klass, p, &p);
3689 if (!strcmp (method->name, ".ctor") && mono_method_signature_internal (method)->param_count == m_class_get_rank (method->klass))
3690 encode_value (0, p, &p);
3691 else if (!strcmp (method->name, ".ctor") && mono_method_signature_internal (method)->param_count == m_class_get_rank (method->klass) * 2)
3692 encode_value (1, p, &p);
3693 else if (!strcmp (method->name, "Get"))
3694 encode_value (2, p, &p);
3695 else if (!strcmp (method->name, "Address"))
3696 encode_value (3, p, &p);
3697 else if (!strcmp (method->name, "Set"))
3698 encode_value (4, p, &p);
3699 else
3700 g_assert_not_reached ();
3702 } else {
3703 g_assert (mono_metadata_token_table (token) == MONO_TABLE_METHOD);
3705 if (image_index >= MONO_AOT_METHODREF_MIN) {
3706 encode_value ((MONO_AOT_METHODREF_LARGE_IMAGE_INDEX << 24), p, &p);
3707 encode_value (image_index, p, &p);
3708 encode_value (mono_metadata_token_index (token), p, &p);
3709 } else {
3710 encode_value ((image_index << 24) | mono_metadata_token_index (token), p, &p);
3713 *endbuf = p;
3716 static gint
3717 compare_patches (gconstpointer a, gconstpointer b)
3719 int i, j;
3721 i = (*(MonoJumpInfo**)a)->ip.i;
3722 j = (*(MonoJumpInfo**)b)->ip.i;
3724 if (i < j)
3725 return -1;
3726 else
3727 if (i > j)
3728 return 1;
3729 else
3730 return 0;
3733 static G_GNUC_UNUSED char*
3734 patch_to_string (MonoJumpInfo *patch_info)
3736 GString *str;
3738 str = g_string_new ("");
3740 g_string_append_printf (str, "%s(", get_patch_name (patch_info->type));
3742 switch (patch_info->type) {
3743 case MONO_PATCH_INFO_VTABLE:
3744 mono_type_get_desc (str, m_class_get_byval_arg (patch_info->data.klass), TRUE);
3745 break;
3746 default:
3747 break;
3749 g_string_append_printf (str, ")");
3750 return g_string_free (str, FALSE);
3754 * is_plt_patch:
3756 * Return whenever PATCH_INFO refers to a direct call, and thus requires a
3757 * PLT entry.
3759 static inline gboolean
3760 is_plt_patch (MonoJumpInfo *patch_info)
3762 switch (patch_info->type) {
3763 case MONO_PATCH_INFO_METHOD:
3764 case MONO_PATCH_INFO_JIT_ICALL:
3765 case MONO_PATCH_INFO_JIT_ICALL_ADDR:
3766 case MONO_PATCH_INFO_ICALL_ADDR_CALL:
3767 case MONO_PATCH_INFO_RGCTX_FETCH:
3768 return TRUE;
3769 default:
3770 return FALSE;
3775 * get_plt_symbol:
3777 * Return the symbol identifying the plt entry PLT_OFFSET.
3779 static char*
3780 get_plt_symbol (MonoAotCompile *acfg, int plt_offset, MonoJumpInfo *patch_info)
3782 #ifdef TARGET_MACH
3784 * The Apple linker reorganizes object files, so it doesn't like branches to local
3785 * labels, since those have no relocations.
3787 return g_strdup_printf ("%sp_%d", acfg->llvm_label_prefix, plt_offset);
3788 #else
3789 return g_strdup_printf ("%sp_%d", acfg->temp_prefix, plt_offset);
3790 #endif
3794 * get_plt_entry:
3796 * Return a PLT entry which belongs to the method identified by PATCH_INFO.
3798 static MonoPltEntry*
3799 get_plt_entry (MonoAotCompile *acfg, MonoJumpInfo *patch_info)
3801 MonoPltEntry *res;
3802 gboolean synchronized = FALSE;
3803 static int synchronized_symbol_idx;
3805 if (!is_plt_patch (patch_info))
3806 return NULL;
3808 if (!acfg->patch_to_plt_entry [patch_info->type])
3809 acfg->patch_to_plt_entry [patch_info->type] = g_hash_table_new (mono_patch_info_hash, mono_patch_info_equal);
3810 res = (MonoPltEntry *)g_hash_table_lookup (acfg->patch_to_plt_entry [patch_info->type], patch_info);
3812 if (!acfg->llvm && patch_info->type == MONO_PATCH_INFO_METHOD && (patch_info->data.method->iflags & METHOD_IMPL_ATTRIBUTE_SYNCHRONIZED)) {
3814 * Allocate a separate PLT slot for each such patch, since some plt
3815 * entries will refer to the method itself, and some will refer to the
3816 * wrapper.
3818 res = NULL;
3819 synchronized = TRUE;
3822 if (!res) {
3823 MonoJumpInfo *new_ji;
3825 new_ji = mono_patch_info_dup_mp (acfg->mempool, patch_info);
3827 res = (MonoPltEntry *)mono_mempool_alloc0 (acfg->mempool, sizeof (MonoPltEntry));
3828 res->plt_offset = acfg->plt_offset;
3829 res->ji = new_ji;
3830 res->symbol = get_plt_symbol (acfg, res->plt_offset, patch_info);
3831 if (acfg->aot_opts.write_symbols)
3832 res->debug_sym = get_plt_entry_debug_sym (acfg, res->ji, acfg->plt_entry_debug_sym_cache);
3833 if (synchronized) {
3834 /* Avoid duplicate symbols because we don't cache */
3835 res->symbol = g_strdup_printf ("%s_%d", res->symbol, synchronized_symbol_idx);
3836 if (res->debug_sym)
3837 res->debug_sym = g_strdup_printf ("%s_%d", res->debug_sym, synchronized_symbol_idx);
3838 synchronized_symbol_idx ++;
3841 if (res->debug_sym)
3842 res->llvm_symbol = g_strdup_printf ("%s_%s_llvm", res->symbol, res->debug_sym);
3843 else
3844 res->llvm_symbol = g_strdup_printf ("%s_llvm", res->symbol);
3845 if (strstr (res->llvm_symbol, acfg->temp_prefix) == res->llvm_symbol) {
3846 /* The llvm symbol shouldn't be temporary, since the llvm generated object file references it */
3847 char *tmp = res->llvm_symbol;
3848 res->llvm_symbol = g_strdup (res->llvm_symbol + strlen (acfg->temp_prefix));
3849 g_free (tmp);
3852 g_hash_table_insert (acfg->patch_to_plt_entry [new_ji->type], new_ji, res);
3854 g_hash_table_insert (acfg->plt_offset_to_entry, GUINT_TO_POINTER (res->plt_offset), res);
3856 //g_assert (mono_patch_info_equal (patch_info, new_ji));
3857 //mono_print_ji (patch_info); printf ("\n");
3858 //g_hash_table_print_stats (acfg->patch_to_plt_entry);
3860 acfg->plt_offset ++;
3863 return res;
3866 static guint32
3867 lookup_got_offset (MonoAotCompile *acfg, gboolean llvm, MonoJumpInfo *ji)
3869 guint32 got_offset;
3870 GotInfo *info = llvm ? &acfg->llvm_got_info : &acfg->got_info;
3872 got_offset = GPOINTER_TO_UINT (g_hash_table_lookup (info->patch_to_got_offset_by_type [ji->type], ji));
3873 if (got_offset)
3874 return got_offset - 1;
3875 g_assert_not_reached ();
3879 * get_got_offset:
3881 * Returns the offset of the GOT slot where the runtime object resulting from resolving
3882 * JI could be found if it exists, otherwise allocates a new one.
3884 static guint32
3885 get_got_offset (MonoAotCompile *acfg, gboolean llvm, MonoJumpInfo *ji)
3887 guint32 got_offset;
3888 GotInfo *info = llvm ? &acfg->llvm_got_info : &acfg->got_info;
3890 got_offset = GPOINTER_TO_UINT (g_hash_table_lookup (info->patch_to_got_offset_by_type [ji->type], ji));
3891 if (got_offset)
3892 return got_offset - 1;
3894 if (llvm) {
3895 got_offset = acfg->llvm_got_offset;
3896 acfg->llvm_got_offset ++;
3897 } else {
3898 got_offset = acfg->got_offset;
3899 acfg->got_offset ++;
3902 acfg->stats.got_slots ++;
3903 acfg->stats.got_slot_types [ji->type] ++;
3905 g_hash_table_insert (info->patch_to_got_offset, ji, GUINT_TO_POINTER (got_offset + 1));
3906 g_hash_table_insert (info->patch_to_got_offset_by_type [ji->type], ji, GUINT_TO_POINTER (got_offset + 1));
3907 g_ptr_array_add (info->got_patches, ji);
3909 return got_offset;
3912 /* Add a method to the list of methods which need to be emitted */
3913 static void
3914 add_method_with_index (MonoAotCompile *acfg, MonoMethod *method, int index, gboolean extra)
3916 g_assert (method);
3917 if (!g_hash_table_lookup (acfg->method_indexes, method)) {
3918 g_ptr_array_add (acfg->methods, method);
3919 g_hash_table_insert (acfg->method_indexes, method, GUINT_TO_POINTER (index + 1));
3920 acfg->nmethods = acfg->methods->len + 1;
3923 if (method->wrapper_type || extra) {
3924 int token = mono_metadata_token_index (method->token) - 1;
3925 if (token < 0)
3926 acfg->nextra_methods++;
3927 g_ptr_array_add (acfg->extra_methods, method);
3931 static gboolean
3932 prefer_gsharedvt_method (MonoAotCompile *acfg, MonoMethod *method)
3934 /* One instantiation with valuetypes is generated for each async method */
3935 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")))
3936 return TRUE;
3937 else
3938 return FALSE;
3941 static guint32
3942 get_method_index (MonoAotCompile *acfg, MonoMethod *method)
3944 int index = GPOINTER_TO_UINT (g_hash_table_lookup (acfg->method_indexes, method));
3946 g_assert (index);
3948 return index - 1;
3951 static int
3952 add_method_full (MonoAotCompile *acfg, MonoMethod *method, gboolean extra, int depth)
3954 int index;
3956 index = GPOINTER_TO_UINT (g_hash_table_lookup (acfg->method_indexes, method));
3957 if (index)
3958 return index - 1;
3960 index = acfg->method_index;
3961 add_method_with_index (acfg, method, index, extra);
3963 g_ptr_array_add (acfg->method_order, GUINT_TO_POINTER (index));
3965 g_hash_table_insert (acfg->method_depth, method, GUINT_TO_POINTER (depth));
3967 acfg->method_index ++;
3969 return index;
3972 static int
3973 add_method (MonoAotCompile *acfg, MonoMethod *method)
3975 return add_method_full (acfg, method, FALSE, 0);
3978 static void
3979 mono_dedup_cache_method (MonoAotCompile *acfg, MonoMethod *method)
3981 g_assert (acfg->dedup_stats);
3983 char *name = mono_aot_get_mangled_method_name (method);
3984 g_assert (name);
3986 // For stats
3987 char *stats_name = g_strdup (name);
3989 g_assert (acfg->dedup_cache);
3991 if (!g_hash_table_lookup (acfg->dedup_cache, name)) {
3992 // This AOTCompile owns this method
3993 // We do this to decide whether to write it to disk
3994 // during a dedup run (first phase, where we skip).
3996 // If never changed, then maybe can avoid a recompile
3997 // of the cache.
3999 // Files not read in during last phase.
4000 acfg->dedup_cache_changed = TRUE;
4002 // owns name
4003 g_hash_table_insert (acfg->dedup_cache, name, method);
4004 } else {
4005 // owns name
4006 g_free (name);
4009 guint count = GPOINTER_TO_UINT (g_hash_table_lookup (acfg->dedup_stats, stats_name));
4010 count++;
4011 g_hash_table_insert (acfg->dedup_stats, stats_name, GUINT_TO_POINTER (count));
4014 static void
4015 add_extra_method_with_depth (MonoAotCompile *acfg, MonoMethod *method, int depth)
4017 ERROR_DECL (error);
4019 if (mono_method_is_generic_sharable_full (method, TRUE, TRUE, FALSE)) {
4020 method = mini_get_shared_method_full (method, SHARE_MODE_NONE, error);
4021 mono_error_assert_ok (error);
4022 } else if ((acfg->opts & MONO_OPT_GSHAREDVT) && prefer_gsharedvt_method (acfg, method) && mono_method_is_generic_sharable_full (method, FALSE, FALSE, TRUE)) {
4023 /* Use the gsharedvt version */
4024 method = mini_get_shared_method_full (method, SHARE_MODE_GSHAREDVT, error);
4025 mono_error_assert_ok (error);
4028 if ((acfg->aot_opts.dedup || acfg->aot_opts.dedup_include) && mono_aot_can_dedup (method)) {
4029 mono_dedup_cache_method (acfg, method);
4031 if (!acfg->dedup_emit_mode)
4032 return;
4035 if (acfg->aot_opts.log_generics)
4036 aot_printf (acfg, "%*sAdding method %s.\n", depth, "", mono_method_get_full_name (method));
4038 add_method_full (acfg, method, TRUE, depth);
4041 static void
4042 add_extra_method (MonoAotCompile *acfg, MonoMethod *method)
4044 add_extra_method_with_depth (acfg, method, 0);
4047 static void
4048 add_jit_icall_wrapper (gpointer key, gpointer value, gpointer user_data)
4050 MonoAotCompile *acfg = (MonoAotCompile *)user_data;
4051 MonoJitICallInfo *callinfo = (MonoJitICallInfo *)value;
4052 MonoMethod *wrapper;
4053 char *name;
4055 if (!callinfo->sig)
4056 return;
4058 name = g_strdup_printf ("__icall_wrapper_%s", callinfo->name);
4059 wrapper = mono_marshal_get_icall_wrapper (callinfo->sig, name, callinfo->func, TRUE);
4060 g_free (name);
4062 add_method (acfg, wrapper);
4065 static MonoMethod*
4066 get_runtime_invoke_sig (MonoMethodSignature *sig)
4068 MonoMethodBuilder *mb;
4069 MonoMethod *m;
4071 mb = mono_mb_new (mono_defaults.object_class, "FOO", MONO_WRAPPER_NONE);
4072 m = mono_mb_create_method (mb, sig, 16);
4073 MonoMethod *invoke = mono_marshal_get_runtime_invoke (m, FALSE);
4074 mono_mb_free (mb);
4075 return invoke;
4078 static MonoMethod*
4079 get_runtime_invoke (MonoAotCompile *acfg, MonoMethod *method, gboolean virtual_)
4081 return mono_marshal_get_runtime_invoke (method, virtual_);
4084 static gboolean
4085 can_marshal_struct (MonoClass *klass)
4087 MonoClassField *field;
4088 gboolean can_marshal = TRUE;
4089 gpointer iter = NULL;
4090 MonoMarshalType *info;
4091 int i;
4093 if (mono_class_is_auto_layout (klass))
4094 return FALSE;
4096 info = mono_marshal_load_type_info (klass);
4098 /* Only allow a few field types to avoid asserts in the marshalling code */
4099 while ((field = mono_class_get_fields_internal (klass, &iter))) {
4100 if ((field->type->attrs & FIELD_ATTRIBUTE_STATIC))
4101 continue;
4103 switch (field->type->type) {
4104 case MONO_TYPE_I4:
4105 case MONO_TYPE_U4:
4106 case MONO_TYPE_I1:
4107 case MONO_TYPE_U1:
4108 case MONO_TYPE_BOOLEAN:
4109 case MONO_TYPE_I2:
4110 case MONO_TYPE_U2:
4111 case MONO_TYPE_CHAR:
4112 case MONO_TYPE_I8:
4113 case MONO_TYPE_U8:
4114 case MONO_TYPE_I:
4115 case MONO_TYPE_U:
4116 case MONO_TYPE_PTR:
4117 case MONO_TYPE_R4:
4118 case MONO_TYPE_R8:
4119 case MONO_TYPE_STRING:
4120 break;
4121 case MONO_TYPE_VALUETYPE:
4122 if (!m_class_is_enumtype (mono_class_from_mono_type_internal (field->type)) && !can_marshal_struct (mono_class_from_mono_type_internal (field->type)))
4123 can_marshal = FALSE;
4124 break;
4125 case MONO_TYPE_SZARRAY: {
4126 gboolean has_mspec = FALSE;
4128 if (info) {
4129 for (i = 0; i < info->num_fields; ++i) {
4130 if (info->fields [i].field == field && info->fields [i].mspec)
4131 has_mspec = TRUE;
4134 if (!has_mspec)
4135 can_marshal = FALSE;
4136 break;
4138 default:
4139 can_marshal = FALSE;
4140 break;
4144 /* Special cases */
4145 /* Its hard to compute whenever these can be marshalled or not */
4146 if (!strcmp (m_class_get_name_space (klass), "System.Net.NetworkInformation.MacOsStructs") && strcmp (m_class_get_name (klass), "sockaddr_dl"))
4147 return TRUE;
4149 return can_marshal;
4152 static void
4153 create_gsharedvt_inst (MonoAotCompile *acfg, MonoMethod *method, MonoGenericContext *ctx)
4155 /* Create a vtype instantiation */
4156 MonoGenericContext shared_context;
4157 MonoType **args;
4158 MonoGenericInst *inst;
4159 MonoGenericContainer *container;
4160 MonoClass **constraints;
4161 int i;
4163 memset (ctx, 0, sizeof (MonoGenericContext));
4165 if (mono_class_is_gtd (method->klass)) {
4166 shared_context = mono_class_get_generic_container (method->klass)->context;
4167 inst = shared_context.class_inst;
4169 args = g_new0 (MonoType*, inst->type_argc);
4170 for (i = 0; i < inst->type_argc; ++i) {
4171 args [i] = mono_get_int_type ();
4173 ctx->class_inst = mono_metadata_get_generic_inst (inst->type_argc, args);
4175 if (method->is_generic) {
4176 container = mono_method_get_generic_container (method);
4177 g_assert (!container->is_anonymous && container->is_method);
4178 shared_context = container->context;
4179 inst = shared_context.method_inst;
4181 args = g_new0 (MonoType*, inst->type_argc);
4182 for (i = 0; i < container->type_argc; ++i) {
4183 MonoGenericParamInfo *info = mono_generic_param_info (&container->type_params [i]);
4184 gboolean ref_only = FALSE;
4186 if (info && info->constraints) {
4187 constraints = info->constraints;
4189 while (*constraints) {
4190 MonoClass *cklass = *constraints;
4191 if (!(cklass == mono_defaults.object_class || (m_class_get_image (cklass) == mono_defaults.corlib && !strcmp (m_class_get_name (cklass), "ValueType"))))
4192 /* Inflaring the method with our vtype would not be valid */
4193 ref_only = TRUE;
4194 constraints ++;
4198 if (ref_only)
4199 args [i] = mono_get_object_type ();
4200 else
4201 args [i] = mono_get_int_type ();
4203 ctx->method_inst = mono_metadata_get_generic_inst (inst->type_argc, args);
4207 static void
4208 add_wrappers (MonoAotCompile *acfg)
4210 MonoMethod *method, *m;
4211 int i, j;
4212 MonoMethodSignature *sig, *csig;
4213 guint32 token;
4216 * FIXME: Instead of AOTing all the wrappers, it might be better to redesign them
4217 * so there is only one wrapper of a given type, or inlining their contents into their
4218 * callers.
4220 for (i = 0; i < acfg->image->tables [MONO_TABLE_METHOD].rows; ++i) {
4221 ERROR_DECL (error);
4222 MonoMethod *method;
4223 guint32 token = MONO_TOKEN_METHOD_DEF | (i + 1);
4224 gboolean skip = FALSE;
4226 method = mono_get_method_checked (acfg->image, token, NULL, NULL, error);
4227 report_loader_error (acfg, error, TRUE, "Failed to load method token 0x%x due to %s\n", i, mono_error_get_message (error));
4229 if ((method->flags & METHOD_ATTRIBUTE_PINVOKE_IMPL) ||
4230 (method->iflags & METHOD_IMPL_ATTRIBUTE_RUNTIME) ||
4231 (method->flags & METHOD_ATTRIBUTE_ABSTRACT))
4232 skip = TRUE;
4234 /* Skip methods which can not be handled by get_runtime_invoke () */
4235 sig = mono_method_signature_internal (method);
4236 if (!sig)
4237 continue;
4238 if ((sig->ret->type == MONO_TYPE_PTR) ||
4239 (sig->ret->type == MONO_TYPE_TYPEDBYREF))
4240 skip = TRUE;
4241 if (mono_class_is_open_constructed_type (sig->ret))
4242 skip = TRUE;
4244 for (j = 0; j < sig->param_count; j++) {
4245 if (sig->params [j]->type == MONO_TYPE_TYPEDBYREF)
4246 skip = TRUE;
4247 if (mono_class_is_open_constructed_type (sig->params [j]))
4248 skip = TRUE;
4251 #ifdef MONO_ARCH_DYN_CALL_SUPPORTED
4252 if (!mono_class_is_contextbound (method->klass)) {
4253 MonoDynCallInfo *info = mono_arch_dyn_call_prepare (sig);
4254 gboolean has_nullable = FALSE;
4256 for (j = 0; j < sig->param_count; j++) {
4257 if (sig->params [j]->type == MONO_TYPE_GENERICINST && mono_class_is_nullable (mono_class_from_mono_type_internal (sig->params [j])))
4258 has_nullable = TRUE;
4261 if (info && !has_nullable && !acfg->aot_opts.llvm_only) {
4262 /* Supported by the dynamic runtime-invoke wrapper */
4263 skip = TRUE;
4265 if (info)
4266 mono_arch_dyn_call_free (info);
4268 #endif
4270 if (acfg->aot_opts.llvm_only)
4271 /* Supported by the gsharedvt based runtime-invoke wrapper */
4272 skip = TRUE;
4274 if (!skip) {
4275 //printf ("%s\n", mono_method_full_name (method, TRUE));
4276 add_method (acfg, get_runtime_invoke (acfg, method, FALSE));
4280 if (mono_is_corlib_image (acfg->image->assembly->image)) {
4281 int nallocators;
4283 /* Runtime invoke wrappers */
4285 MonoType *void_type = mono_get_void_type ();
4286 MonoType *string_type = m_class_get_byval_arg (mono_defaults.string_class);
4288 /* void runtime-invoke () [.cctor] */
4289 csig = mono_metadata_signature_alloc (mono_defaults.corlib, 0);
4290 csig->ret = void_type;
4291 add_method (acfg, get_runtime_invoke_sig (csig));
4293 /* void runtime-invoke () [Finalize] */
4294 csig = mono_metadata_signature_alloc (mono_defaults.corlib, 0);
4295 csig->hasthis = 1;
4296 csig->ret = void_type;
4297 add_method (acfg, get_runtime_invoke_sig (csig));
4299 /* void runtime-invoke (string) [exception ctor] */
4300 csig = mono_metadata_signature_alloc (mono_defaults.corlib, 1);
4301 csig->hasthis = 1;
4302 csig->ret = void_type;
4303 csig->params [0] = string_type;
4304 add_method (acfg, get_runtime_invoke_sig (csig));
4306 /* void runtime-invoke (string, string) [exception ctor] */
4307 csig = mono_metadata_signature_alloc (mono_defaults.corlib, 2);
4308 csig->hasthis = 1;
4309 csig->ret = void_type;
4310 csig->params [0] = string_type;
4311 csig->params [1] = string_type;
4312 add_method (acfg, get_runtime_invoke_sig (csig));
4314 /* string runtime-invoke () [Exception.ToString ()] */
4315 csig = mono_metadata_signature_alloc (mono_defaults.corlib, 0);
4316 csig->hasthis = 1;
4317 csig->ret = string_type;
4318 add_method (acfg, get_runtime_invoke_sig (csig));
4320 /* void runtime-invoke (string, Exception) [exception ctor] */
4321 csig = mono_metadata_signature_alloc (mono_defaults.corlib, 2);
4322 csig->hasthis = 1;
4323 csig->ret = void_type;
4324 csig->params [0] = string_type;
4325 csig->params [1] = m_class_get_byval_arg (mono_defaults.exception_class);
4326 add_method (acfg, get_runtime_invoke_sig (csig));
4328 /* Assembly runtime-invoke (string, Assembly, bool) [DoAssemblyResolve] */
4329 csig = mono_metadata_signature_alloc (mono_defaults.corlib, 3);
4330 csig->hasthis = 1;
4331 csig->ret = m_class_get_byval_arg (mono_class_load_from_name (mono_defaults.corlib, "System.Reflection", "Assembly"));
4332 csig->params [0] = string_type;
4333 csig->params [1] = m_class_get_byval_arg (mono_class_load_from_name (mono_defaults.corlib, "System.Reflection", "Assembly"));
4334 csig->params [2] = m_class_get_byval_arg (mono_defaults.boolean_class);
4335 add_method (acfg, get_runtime_invoke_sig (csig));
4337 /* runtime-invoke used by finalizers */
4338 add_method (acfg, get_runtime_invoke (acfg, get_method_nofail (mono_defaults.object_class, "Finalize", 0, 0), TRUE));
4340 /* This is used by mono_runtime_capture_context () */
4341 method = mono_get_context_capture_method ();
4342 if (method)
4343 add_method (acfg, get_runtime_invoke (acfg, method, FALSE));
4345 #ifdef MONO_ARCH_DYN_CALL_SUPPORTED
4346 if (!acfg->aot_opts.llvm_only)
4347 add_method (acfg, mono_marshal_get_runtime_invoke_dynamic ());
4348 #endif
4350 /* These are used by mono_jit_runtime_invoke () to calls gsharedvt out wrappers */
4351 if (acfg->aot_opts.llvm_only) {
4352 int variants;
4354 /* Create simplified signatures which match the signature used by the gsharedvt out wrappers */
4355 for (variants = 0; variants < 4; ++variants) {
4356 for (i = 0; i < 40; ++i) {
4357 sig = mini_get_gsharedvt_out_sig_wrapper_signature ((variants & 1) > 0, (variants & 2) > 0, i);
4358 add_extra_method (acfg, mono_marshal_get_runtime_invoke_for_sig (sig));
4360 g_free (sig);
4365 /* stelemref */
4366 add_method (acfg, mono_marshal_get_stelemref ());
4368 /* Managed Allocators */
4369 nallocators = mono_gc_get_managed_allocator_types ();
4370 for (i = 0; i < nallocators; ++i) {
4371 if ((m = mono_gc_get_managed_allocator_by_type (i, MANAGED_ALLOCATOR_REGULAR)))
4372 add_method (acfg, m);
4373 if ((m = mono_gc_get_managed_allocator_by_type (i, MANAGED_ALLOCATOR_SLOW_PATH)))
4374 add_method (acfg, m);
4375 if ((m = mono_gc_get_managed_allocator_by_type (i, MANAGED_ALLOCATOR_PROFILER)))
4376 add_method (acfg, m);
4379 /* write barriers */
4380 if (mono_gc_is_moving ()) {
4381 add_method (acfg, mono_gc_get_specific_write_barrier (FALSE));
4382 add_method (acfg, mono_gc_get_specific_write_barrier (TRUE));
4385 /* Stelemref wrappers */
4387 MonoMethod **wrappers;
4388 int nwrappers;
4390 wrappers = mono_marshal_get_virtual_stelemref_wrappers (&nwrappers);
4391 for (i = 0; i < nwrappers; ++i)
4392 add_method (acfg, wrappers [i]);
4393 g_free (wrappers);
4396 /* castclass_with_check wrapper */
4397 add_method (acfg, mono_marshal_get_castclass_with_cache ());
4398 /* isinst_with_check wrapper */
4399 add_method (acfg, mono_marshal_get_isinst_with_cache ());
4401 /* JIT icall wrappers */
4402 /* FIXME: locking - this is "safe" as full-AOT threads don't mutate the icall hash*/
4403 g_hash_table_foreach (mono_get_jit_icall_info (), add_jit_icall_wrapper, acfg);
4407 * remoting-invoke-with-check wrappers are very frequent, so avoid emitting them,
4408 * we use the original method instead at runtime.
4409 * Since full-aot doesn't support remoting, this is not a problem.
4411 #if 0
4412 /* remoting-invoke wrappers */
4413 for (i = 0; i < acfg->image->tables [MONO_TABLE_METHOD].rows; ++i) {
4414 ERROR_DECL (error);
4415 MonoMethodSignature *sig;
4417 token = MONO_TOKEN_METHOD_DEF | (i + 1);
4418 method = mono_get_method_checked (acfg->image, token, NULL, NULL, error);
4419 g_assert (mono_error_ok (error)); /* FIXME don't swallow the error */
4421 sig = mono_method_signature_internal (method);
4423 if (sig->hasthis && (method->klass->marshalbyref || method->klass == mono_defaults.object_class)) {
4424 m = mono_marshal_get_remoting_invoke_with_check (method);
4426 add_method (acfg, m);
4429 #endif
4431 /* delegate-invoke wrappers */
4432 for (i = 0; i < acfg->image->tables [MONO_TABLE_TYPEDEF].rows; ++i) {
4433 ERROR_DECL (error);
4434 MonoClass *klass;
4435 MonoCustomAttrInfo *cattr;
4437 token = MONO_TOKEN_TYPE_DEF | (i + 1);
4438 klass = mono_class_get_checked (acfg->image, token, error);
4440 if (!klass) {
4441 mono_error_cleanup (error);
4442 continue;
4445 if (!m_class_is_delegate (klass) || klass == mono_defaults.delegate_class || klass == mono_defaults.multicastdelegate_class)
4446 continue;
4448 if (!mono_class_is_gtd (klass)) {
4449 method = mono_get_delegate_invoke_internal (klass);
4451 m = mono_marshal_get_delegate_invoke (method, NULL);
4453 add_method (acfg, m);
4455 method = try_get_method_nofail (klass, "BeginInvoke", -1, 0);
4456 if (method)
4457 add_method (acfg, mono_marshal_get_delegate_begin_invoke (method));
4459 method = try_get_method_nofail (klass, "EndInvoke", -1, 0);
4460 if (method)
4461 add_method (acfg, mono_marshal_get_delegate_end_invoke (method));
4463 cattr = mono_custom_attrs_from_class_checked (klass, error);
4464 if (!is_ok (error)) {
4465 mono_error_cleanup (error);
4466 continue;
4469 if (cattr) {
4470 int j;
4472 for (j = 0; j < cattr->num_attrs; ++j)
4473 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")))
4474 break;
4475 if (j < cattr->num_attrs) {
4476 MonoMethod *invoke;
4477 MonoMethod *wrapper;
4478 MonoMethod *del_invoke;
4480 /* Add wrappers needed by mono_ftnptr_to_delegate () */
4481 invoke = mono_get_delegate_invoke_internal (klass);
4482 wrapper = mono_marshal_get_native_func_wrapper_aot (klass);
4483 del_invoke = mono_marshal_get_delegate_invoke_internal (invoke, FALSE, TRUE, wrapper);
4484 add_method (acfg, wrapper);
4485 add_method (acfg, del_invoke);
4488 } else if ((acfg->opts & MONO_OPT_GSHAREDVT) && mono_class_is_gtd (klass)) {
4489 ERROR_DECL (error);
4490 MonoGenericContext ctx;
4491 MonoMethod *inst, *gshared;
4494 * Emit gsharedvt versions of the generic delegate-invoke wrappers
4496 /* Invoke */
4497 method = mono_get_delegate_invoke_internal (klass);
4498 create_gsharedvt_inst (acfg, method, &ctx);
4500 inst = mono_class_inflate_generic_method_checked (method, &ctx, error);
4501 g_assert (mono_error_ok (error)); /* FIXME don't swallow the error */
4503 m = mono_marshal_get_delegate_invoke (inst, NULL);
4504 g_assert (m->is_inflated);
4506 gshared = mini_get_shared_method_full (m, SHARE_MODE_GSHAREDVT, error);
4507 mono_error_assert_ok (error);
4509 add_extra_method (acfg, gshared);
4511 /* begin-invoke */
4512 method = mono_get_delegate_begin_invoke_internal (klass);
4513 if (method) {
4514 create_gsharedvt_inst (acfg, method, &ctx);
4516 inst = mono_class_inflate_generic_method_checked (method, &ctx, error);
4517 g_assert (mono_error_ok (error)); /* FIXME don't swallow the error */
4519 m = mono_marshal_get_delegate_begin_invoke (inst);
4520 g_assert (m->is_inflated);
4522 gshared = mini_get_shared_method_full (m, SHARE_MODE_GSHAREDVT, error);
4523 mono_error_assert_ok (error);
4525 add_extra_method (acfg, gshared);
4528 /* end-invoke */
4529 method = mono_get_delegate_end_invoke_internal (klass);
4530 if (method) {
4531 create_gsharedvt_inst (acfg, method, &ctx);
4533 inst = mono_class_inflate_generic_method_checked (method, &ctx, error);
4534 g_assert (mono_error_ok (error)); /* FIXME don't swallow the error */
4536 m = mono_marshal_get_delegate_end_invoke (inst);
4537 g_assert (m->is_inflated);
4539 gshared = mini_get_shared_method_full (m, SHARE_MODE_GSHAREDVT, error);
4540 mono_error_assert_ok (error);
4542 add_extra_method (acfg, gshared);
4547 /* array access wrappers */
4548 for (i = 0; i < acfg->image->tables [MONO_TABLE_TYPESPEC].rows; ++i) {
4549 ERROR_DECL (error);
4550 MonoClass *klass;
4552 token = MONO_TOKEN_TYPE_SPEC | (i + 1);
4553 klass = mono_class_get_checked (acfg->image, token, error);
4555 if (!klass) {
4556 mono_error_cleanup (error);
4557 continue;
4560 if (m_class_get_rank (klass) && MONO_TYPE_IS_PRIMITIVE (m_class_get_byval_arg (m_class_get_element_class (klass)))) {
4561 MonoMethod *m, *wrapper;
4563 /* Add runtime-invoke wrappers too */
4565 m = get_method_nofail (klass, "Get", -1, 0);
4566 g_assert (m);
4567 wrapper = mono_marshal_get_array_accessor_wrapper (m);
4568 add_extra_method (acfg, wrapper);
4569 if (!acfg->aot_opts.llvm_only)
4570 add_extra_method (acfg, get_runtime_invoke (acfg, wrapper, FALSE));
4572 m = get_method_nofail (klass, "Set", -1, 0);
4573 g_assert (m);
4574 wrapper = mono_marshal_get_array_accessor_wrapper (m);
4575 add_extra_method (acfg, wrapper);
4576 if (!acfg->aot_opts.llvm_only)
4577 add_extra_method (acfg, get_runtime_invoke (acfg, wrapper, FALSE));
4581 /* Synchronized wrappers */
4582 for (i = 0; i < acfg->image->tables [MONO_TABLE_METHOD].rows; ++i) {
4583 ERROR_DECL (error);
4584 token = MONO_TOKEN_METHOD_DEF | (i + 1);
4585 method = mono_get_method_checked (acfg->image, token, NULL, NULL, error);
4586 report_loader_error (acfg, error, TRUE, "Failed to load method token 0x%x due to %s\n", i, mono_error_get_message (error));
4588 if (method->iflags & METHOD_IMPL_ATTRIBUTE_SYNCHRONIZED) {
4589 if (method->is_generic) {
4590 // FIXME:
4591 } else if ((acfg->opts & MONO_OPT_GSHAREDVT) && mono_class_is_gtd (method->klass)) {
4592 ERROR_DECL (error);
4593 MonoGenericContext ctx;
4594 MonoMethod *inst, *gshared, *m;
4597 * Create a generic wrapper for a generic instance, and AOT that.
4599 create_gsharedvt_inst (acfg, method, &ctx);
4600 inst = mono_class_inflate_generic_method_checked (method, &ctx, error);
4601 g_assert (mono_error_ok (error)); /* FIXME don't swallow the error */
4602 m = mono_marshal_get_synchronized_wrapper (inst);
4603 g_assert (m->is_inflated);
4604 gshared = mini_get_shared_method_full (m, SHARE_MODE_GSHAREDVT, error);
4605 mono_error_assert_ok (error);
4607 add_method (acfg, gshared);
4608 } else {
4609 add_method (acfg, mono_marshal_get_synchronized_wrapper (method));
4614 /* pinvoke wrappers */
4615 for (i = 0; i < acfg->image->tables [MONO_TABLE_METHOD].rows; ++i) {
4616 ERROR_DECL (error);
4617 MonoMethod *method;
4618 guint32 token = MONO_TOKEN_METHOD_DEF | (i + 1);
4620 method = mono_get_method_checked (acfg->image, token, NULL, NULL, error);
4621 report_loader_error (acfg, error, TRUE, "Failed to load method token 0x%x due to %s\n", i, mono_error_get_message (error));
4623 if ((method->flags & METHOD_ATTRIBUTE_PINVOKE_IMPL) ||
4624 (method->iflags & METHOD_IMPL_ATTRIBUTE_INTERNAL_CALL)) {
4625 add_method (acfg, mono_marshal_get_native_wrapper (method, TRUE, TRUE));
4628 if (method->iflags & METHOD_IMPL_ATTRIBUTE_INTERNAL_CALL) {
4629 if (acfg->aot_opts.llvm_only) {
4630 /* The wrappers have a different signature (hasthis is not set) so need to add this too */
4631 add_gsharedvt_wrappers (acfg, mono_method_signature_internal (method), FALSE, TRUE, FALSE);
4636 /* native-to-managed wrappers */
4637 for (i = 0; i < acfg->image->tables [MONO_TABLE_METHOD].rows; ++i) {
4638 ERROR_DECL (error);
4639 MonoMethod *method;
4640 guint32 token = MONO_TOKEN_METHOD_DEF | (i + 1);
4641 MonoCustomAttrInfo *cattr;
4642 int j;
4644 method = mono_get_method_checked (acfg->image, token, NULL, NULL, error);
4645 report_loader_error (acfg, error, TRUE, "Failed to load method token 0x%x due to %s\n", i, mono_error_get_message (error));
4648 * Only generate native-to-managed wrappers for methods which have an
4649 * attribute named MonoPInvokeCallbackAttribute. We search for the attribute by
4650 * name to avoid defining a new assembly to contain it.
4652 cattr = mono_custom_attrs_from_method_checked (method, error);
4653 if (!is_ok (error)) {
4654 char *name = mono_method_get_full_name (method);
4655 report_loader_error (acfg, error, TRUE, "Failed to load custom attributes from method %s due to %s\n", name, mono_error_get_message (error));
4656 g_free (name);
4659 if (cattr) {
4660 for (j = 0; j < cattr->num_attrs; ++j)
4661 if (cattr->attrs [j].ctor && !strcmp (m_class_get_name (cattr->attrs [j].ctor->klass), "MonoPInvokeCallbackAttribute"))
4662 break;
4663 if (j < cattr->num_attrs) {
4664 MonoCustomAttrEntry *e = &cattr->attrs [j];
4665 MonoMethodSignature *sig = mono_method_signature_internal (e->ctor);
4666 const char *p = (const char*)e->data;
4667 const char *named;
4668 int slen, num_named, named_type;
4669 char *n;
4670 MonoType *t;
4671 MonoClass *klass;
4672 char *export_name = NULL;
4673 MonoMethod *wrapper;
4675 /* this cannot be enforced by the C# compiler so we must give the user some warning before aborting */
4676 if (!(method->flags & METHOD_ATTRIBUTE_STATIC)) {
4677 g_warning ("AOT restriction: Method '%s' must be static since it is decorated with [MonoPInvokeCallback]. See https://docs.microsoft.com/xamarin/ios/internals/limitations#reverse-callbacks",
4678 mono_method_full_name (method, TRUE));
4679 exit (1);
4682 g_assert (sig->param_count == 1);
4683 g_assert (sig->params [0]->type == MONO_TYPE_CLASS && !strcmp (m_class_get_name (mono_class_from_mono_type_internal (sig->params [0])), "Type"));
4686 * Decode the cattr manually since we can't create objects
4687 * during aot compilation.
4690 /* Skip prolog */
4691 p += 2;
4693 /* From load_cattr_value () in reflection.c */
4694 slen = mono_metadata_decode_value (p, &p);
4695 n = (char *)g_memdup (p, slen + 1);
4696 n [slen] = 0;
4697 t = mono_reflection_type_from_name_checked (n, acfg->image, error);
4698 g_assert (t);
4699 mono_error_assert_ok (error);
4700 g_free (n);
4702 klass = mono_class_from_mono_type_internal (t);
4703 g_assert (m_class_get_parent (klass) == mono_defaults.multicastdelegate_class);
4705 p += slen;
4707 num_named = read16 (p);
4708 p += 2;
4710 g_assert (num_named < 2);
4711 if (num_named == 1) {
4712 int name_len;
4713 char *name;
4715 /* parse ExportSymbol attribute */
4716 named = p;
4717 named_type = *named;
4718 named += 1;
4719 /* data_type = *named; */
4720 named += 1;
4722 name_len = mono_metadata_decode_blob_size (named, &named);
4723 name = (char *)g_malloc (name_len + 1);
4724 memcpy (name, named, name_len);
4725 name [name_len] = 0;
4726 named += name_len;
4728 g_assert (named_type == 0x54);
4729 g_assert (!strcmp (name, "ExportSymbol"));
4731 /* load_cattr_value (), string case */
4732 g_assert (*named != (char)0xff);
4733 slen = mono_metadata_decode_value (named, &named);
4734 export_name = (char *)g_malloc (slen + 1);
4735 memcpy (export_name, named, slen);
4736 export_name [slen] = 0;
4737 named += slen;
4740 wrapper = mono_marshal_get_managed_wrapper (method, klass, 0, error);
4741 mono_error_assert_ok (error);
4743 add_method (acfg, wrapper);
4744 if (export_name)
4745 g_hash_table_insert (acfg->export_names, wrapper, export_name);
4747 g_free (cattr);
4750 if ((method->flags & METHOD_ATTRIBUTE_PINVOKE_IMPL) ||
4751 (method->iflags & METHOD_IMPL_ATTRIBUTE_INTERNAL_CALL)) {
4752 add_method (acfg, mono_marshal_get_native_wrapper (method, TRUE, TRUE));
4756 /* StructureToPtr/PtrToStructure wrappers */
4757 for (i = 0; i < acfg->image->tables [MONO_TABLE_TYPEDEF].rows; ++i) {
4758 ERROR_DECL (error);
4759 MonoClass *klass;
4761 token = MONO_TOKEN_TYPE_DEF | (i + 1);
4762 klass = mono_class_get_checked (acfg->image, token, error);
4764 if (!klass) {
4765 mono_error_cleanup (error);
4766 continue;
4769 if (m_class_is_valuetype (klass) && !mono_class_is_gtd (klass) && can_marshal_struct (klass) &&
4770 !(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)))) {
4771 add_method (acfg, mono_marshal_get_struct_to_ptr (klass));
4772 add_method (acfg, mono_marshal_get_ptr_to_struct (klass));
4777 static gboolean
4778 has_type_vars (MonoClass *klass)
4780 if ((m_class_get_byval_arg (klass)->type == MONO_TYPE_VAR) || (m_class_get_byval_arg (klass)->type == MONO_TYPE_MVAR))
4781 return TRUE;
4782 if (m_class_get_rank (klass))
4783 return has_type_vars (m_class_get_element_class (klass));
4784 if (mono_class_is_ginst (klass)) {
4785 MonoGenericContext *context = &mono_class_get_generic_class (klass)->context;
4786 if (context->class_inst) {
4787 int i;
4789 for (i = 0; i < context->class_inst->type_argc; ++i)
4790 if (has_type_vars (mono_class_from_mono_type_internal (context->class_inst->type_argv [i])))
4791 return TRUE;
4794 if (mono_class_is_gtd (klass))
4795 return TRUE;
4796 return FALSE;
4799 static gboolean
4800 is_vt_inst (MonoGenericInst *inst)
4802 int i;
4804 for (i = 0; i < inst->type_argc; ++i) {
4805 MonoType *t = inst->type_argv [i];
4806 if (MONO_TYPE_ISSTRUCT (t) || t->type == MONO_TYPE_VALUETYPE)
4807 return TRUE;
4809 return FALSE;
4812 static gboolean
4813 method_has_type_vars (MonoMethod *method)
4815 if (has_type_vars (method->klass))
4816 return TRUE;
4818 if (method->is_inflated) {
4819 MonoGenericContext *context = mono_method_get_context (method);
4820 if (context->method_inst) {
4821 int i;
4823 for (i = 0; i < context->method_inst->type_argc; ++i)
4824 if (has_type_vars (mono_class_from_mono_type_internal (context->method_inst->type_argv [i])))
4825 return TRUE;
4828 return FALSE;
4831 static
4832 gboolean mono_aot_mode_is_full (MonoAotOptions *opts)
4834 return opts->mode == MONO_AOT_MODE_FULL;
4837 static
4838 gboolean mono_aot_mode_is_interp (MonoAotOptions *opts)
4840 return opts->interp;
4843 static
4844 gboolean mono_aot_mode_is_hybrid (MonoAotOptions *opts)
4846 return opts->mode == MONO_AOT_MODE_HYBRID;
4849 static void add_generic_class_with_depth (MonoAotCompile *acfg, MonoClass *klass, int depth, const char *ref);
4851 static void
4852 add_generic_class (MonoAotCompile *acfg, MonoClass *klass, gboolean force, const char *ref)
4854 /* This might lead to a huge code blowup so only do it if neccesary */
4855 if (!mono_aot_mode_is_full (&acfg->aot_opts) && !mono_aot_mode_is_hybrid (&acfg->aot_opts) && !force)
4856 return;
4858 add_generic_class_with_depth (acfg, klass, 0, ref);
4861 static gboolean
4862 check_type_depth (MonoType *t, int depth)
4864 int i;
4866 if (depth > 8)
4867 return TRUE;
4869 switch (t->type) {
4870 case MONO_TYPE_GENERICINST: {
4871 MonoGenericClass *gklass = t->data.generic_class;
4872 MonoGenericInst *ginst = gklass->context.class_inst;
4874 if (ginst) {
4875 for (i = 0; i < ginst->type_argc; ++i) {
4876 if (check_type_depth (ginst->type_argv [i], depth + 1))
4877 return TRUE;
4880 break;
4882 default:
4883 break;
4886 return FALSE;
4889 static void
4890 add_types_from_method_header (MonoAotCompile *acfg, MonoMethod *method);
4893 * add_generic_class:
4895 * Add all methods of a generic class.
4897 static void
4898 add_generic_class_with_depth (MonoAotCompile *acfg, MonoClass *klass, int depth, const char *ref)
4900 MonoMethod *method;
4901 MonoClassField *field;
4902 gpointer iter;
4903 gboolean use_gsharedvt = FALSE;
4905 if (!acfg->ginst_hash)
4906 acfg->ginst_hash = g_hash_table_new (NULL, NULL);
4908 mono_class_init_internal (klass);
4910 if (mono_class_is_ginst (klass) && mono_class_get_generic_class (klass)->context.class_inst->is_open)
4911 return;
4913 if (has_type_vars (klass))
4914 return;
4916 if (!mono_class_is_ginst (klass) && !m_class_get_rank (klass))
4917 return;
4919 if (mono_class_has_failure (klass))
4920 return;
4922 if (!acfg->ginst_hash)
4923 acfg->ginst_hash = g_hash_table_new (NULL, NULL);
4925 if (g_hash_table_lookup (acfg->ginst_hash, klass))
4926 return;
4928 if (check_type_depth (m_class_get_byval_arg (klass), 0))
4929 return;
4931 if (acfg->aot_opts.log_generics) {
4932 char *s = mono_type_full_name (m_class_get_byval_arg (klass));
4933 aot_printf (acfg, "%*sAdding generic instance %s [%s].\n", depth, "", s, ref);
4934 g_free (s);
4937 g_hash_table_insert (acfg->ginst_hash, klass, klass);
4940 * Use gsharedvt for generic collections with vtype arguments to avoid code blowup.
4941 * Enable this only for some classes since gsharedvt might not support all methods.
4943 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) &&
4944 (!strcmp (m_class_get_name (klass), "Dictionary`2") || !strcmp (m_class_get_name (klass), "List`1") || !strcmp (m_class_get_name (klass), "ReadOnlyCollection`1")))
4945 use_gsharedvt = TRUE;
4947 iter = NULL;
4948 while ((method = mono_class_get_methods (klass, &iter))) {
4949 if ((acfg->opts & MONO_OPT_GSHAREDVT) && method->is_inflated && mono_method_get_context (method)->method_inst) {
4951 * This is partial sharing, and we can't handle it yet
4953 continue;
4956 if (mono_method_is_generic_sharable_full (method, FALSE, FALSE, use_gsharedvt)) {
4957 /* Already added */
4958 add_types_from_method_header (acfg, method);
4959 continue;
4962 if (method->is_generic)
4963 /* FIXME: */
4964 continue;
4967 * FIXME: Instances which are referenced by these methods are not added,
4968 * for example Array.Resize<int> for List<int>.Add ().
4970 add_extra_method_with_depth (acfg, method, depth + 1);
4973 iter = NULL;
4974 while ((field = mono_class_get_fields_internal (klass, &iter))) {
4975 if (field->type->type == MONO_TYPE_GENERICINST)
4976 add_generic_class_with_depth (acfg, mono_class_from_mono_type_internal (field->type), depth + 1, "field");
4979 if (m_class_is_delegate (klass)) {
4980 method = mono_get_delegate_invoke_internal (klass);
4982 method = mono_marshal_get_delegate_invoke (method, NULL);
4984 if (acfg->aot_opts.log_generics)
4985 aot_printf (acfg, "%*sAdding method %s.\n", depth, "", mono_method_get_full_name (method));
4987 add_method (acfg, method);
4990 /* Add superclasses */
4991 if (m_class_get_parent (klass))
4992 add_generic_class_with_depth (acfg, m_class_get_parent (klass), depth, "parent");
4994 const char *klass_name = m_class_get_name (klass);
4995 const char *klass_name_space = m_class_get_name_space (klass);
4996 const gboolean in_corlib = m_class_get_image (klass) == mono_defaults.corlib;
4998 * For ICollection<T>, add instances of the helper methods
4999 * in Array, since a T[] could be cast to ICollection<T>.
5001 if (in_corlib && !strcmp (klass_name_space, "System.Collections.Generic") &&
5002 (!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"))) {
5003 MonoClass *tclass = mono_class_from_mono_type_internal (mono_class_get_generic_class (klass)->context.class_inst->type_argv [0]);
5004 MonoClass *array_class = mono_class_create_bounded_array (tclass, 1, FALSE);
5005 gpointer iter;
5006 char *name_prefix;
5008 if (!strcmp (klass_name, "IEnumerator`1"))
5009 name_prefix = g_strdup_printf ("%s.%s", klass_name_space, "IEnumerable`1");
5010 else
5011 name_prefix = g_strdup_printf ("%s.%s", klass_name_space, klass_name);
5013 /* Add the T[]/InternalEnumerator class */
5014 if (!strcmp (klass_name, "IEnumerable`1") || !strcmp (klass_name, "IEnumerator`1")) {
5015 ERROR_DECL (error);
5016 MonoClass *nclass;
5018 iter = NULL;
5019 while ((nclass = mono_class_get_nested_types (m_class_get_parent (array_class), &iter))) {
5020 if (!strcmp (m_class_get_name (nclass), "InternalEnumerator`1"))
5021 break;
5023 g_assert (nclass);
5024 nclass = mono_class_inflate_generic_class_checked (nclass, mono_generic_class_get_context (mono_class_get_generic_class (klass)), error);
5025 mono_error_assert_ok (error); /* FIXME don't swallow the error */
5026 add_generic_class (acfg, nclass, FALSE, "ICollection<T>");
5029 iter = NULL;
5030 while ((method = mono_class_get_methods (array_class, &iter))) {
5031 if (!strncmp (method->name, name_prefix, strlen (name_prefix))) {
5032 MonoMethod *m = mono_aot_get_array_helper_from_wrapper (method);
5034 if (m->is_inflated && !mono_method_is_generic_sharable_full (m, FALSE, FALSE, FALSE))
5035 add_extra_method_with_depth (acfg, m, depth);
5039 g_free (name_prefix);
5042 /* Add an instance of GenericComparer<T> which is created dynamically by Comparer<T> */
5043 if (in_corlib && !strcmp (klass_name_space, "System.Collections.Generic") && !strcmp (klass_name, "Comparer`1")) {
5044 ERROR_DECL (error);
5045 MonoClass *tclass = mono_class_from_mono_type_internal (mono_class_get_generic_class (klass)->context.class_inst->type_argv [0]);
5046 MonoClass *icomparable, *gcomparer, *icomparable_inst;
5047 MonoGenericContext ctx;
5048 MonoType *args [16];
5050 memset (&ctx, 0, sizeof (ctx));
5052 icomparable = mono_class_load_from_name (mono_defaults.corlib, "System", "IComparable`1");
5054 args [0] = m_class_get_byval_arg (tclass);
5055 ctx.class_inst = mono_metadata_get_generic_inst (1, args);
5057 icomparable_inst = mono_class_inflate_generic_class_checked (icomparable, &ctx, error);
5058 mono_error_assert_ok (error); /* FIXME don't swallow the error */
5060 if (mono_class_is_assignable_from_internal (icomparable_inst, tclass)) {
5061 MonoClass *gcomparer_inst;
5062 gcomparer = mono_class_load_from_name (mono_defaults.corlib, "System.Collections.Generic", "GenericComparer`1");
5063 gcomparer_inst = mono_class_inflate_generic_class_checked (gcomparer, &ctx, error);
5064 mono_error_assert_ok (error); /* FIXME don't swallow the error */
5066 add_generic_class (acfg, gcomparer_inst, FALSE, "Comparer<T>");
5070 /* Add an instance of GenericEqualityComparer<T> which is created dynamically by EqualityComparer<T> */
5071 if (in_corlib && !strcmp (klass_name_space, "System.Collections.Generic") && !strcmp (klass_name, "EqualityComparer`1")) {
5072 ERROR_DECL (error);
5073 MonoClass *tclass = mono_class_from_mono_type_internal (mono_class_get_generic_class (klass)->context.class_inst->type_argv [0]);
5074 MonoClass *iface, *gcomparer, *iface_inst;
5075 MonoGenericContext ctx;
5076 MonoType *args [16];
5078 memset (&ctx, 0, sizeof (ctx));
5080 iface = mono_class_load_from_name (mono_defaults.corlib, "System", "IEquatable`1");
5081 g_assert (iface);
5082 args [0] = m_class_get_byval_arg (tclass);
5083 ctx.class_inst = mono_metadata_get_generic_inst (1, args);
5085 iface_inst = mono_class_inflate_generic_class_checked (iface, &ctx, error);
5086 mono_error_assert_ok (error); /* FIXME don't swallow the error */
5088 if (mono_class_is_assignable_from_internal (iface_inst, tclass)) {
5089 MonoClass *gcomparer_inst;
5090 ERROR_DECL (error);
5092 gcomparer = mono_class_load_from_name (mono_defaults.corlib, "System.Collections.Generic", "GenericEqualityComparer`1");
5093 gcomparer_inst = mono_class_inflate_generic_class_checked (gcomparer, &ctx, error);
5094 mono_error_assert_ok (error); /* FIXME don't swallow the error */
5095 add_generic_class (acfg, gcomparer_inst, FALSE, "EqualityComparer<T>");
5099 /* Add an instance of EnumComparer<T> which is created dynamically by EqualityComparer<T> for enums */
5100 if (in_corlib && !strcmp (klass_name_space, "System.Collections.Generic") && !strcmp (klass_name, "EqualityComparer`1")) {
5101 MonoClass *enum_comparer;
5102 MonoClass *tclass = mono_class_from_mono_type_internal (mono_class_get_generic_class (klass)->context.class_inst->type_argv [0]);
5103 MonoGenericContext ctx;
5104 MonoType *args [16];
5106 if (m_class_is_enumtype (tclass)) {
5107 MonoClass *enum_comparer_inst;
5108 ERROR_DECL (error);
5110 memset (&ctx, 0, sizeof (ctx));
5111 args [0] = m_class_get_byval_arg (tclass);
5112 ctx.class_inst = mono_metadata_get_generic_inst (1, args);
5114 enum_comparer = mono_class_load_from_name (mono_defaults.corlib, "System.Collections.Generic", "EnumEqualityComparer`1");
5115 enum_comparer_inst = mono_class_inflate_generic_class_checked (enum_comparer, &ctx, error);
5116 mono_error_assert_ok (error); /* FIXME don't swallow the error */
5117 add_generic_class (acfg, enum_comparer_inst, FALSE, "EqualityComparer<T>");
5121 /* Add an instance of ObjectComparer<T> which is created dynamically by Comparer<T> for enums */
5122 if (in_corlib && !strcmp (klass_name_space, "System.Collections.Generic") && !strcmp (klass_name, "Comparer`1")) {
5123 MonoClass *comparer;
5124 MonoClass *tclass = mono_class_from_mono_type_internal (mono_class_get_generic_class (klass)->context.class_inst->type_argv [0]);
5125 MonoGenericContext ctx;
5126 MonoType *args [16];
5128 if (m_class_is_enumtype (tclass)) {
5129 MonoClass *comparer_inst;
5130 ERROR_DECL (error);
5132 memset (&ctx, 0, sizeof (ctx));
5133 args [0] = m_class_get_byval_arg (tclass);
5134 ctx.class_inst = mono_metadata_get_generic_inst (1, args);
5136 comparer = mono_class_load_from_name (mono_defaults.corlib, "System.Collections.Generic", "ObjectComparer`1");
5137 comparer_inst = mono_class_inflate_generic_class_checked (comparer, &ctx, error);
5138 mono_error_assert_ok (error); /* FIXME don't swallow the error */
5139 add_generic_class (acfg, comparer_inst, FALSE, "Comparer<T>");
5144 static void
5145 add_instances_of (MonoAotCompile *acfg, MonoClass *klass, MonoType **insts, int ninsts, gboolean force)
5147 int i;
5148 MonoGenericContext ctx;
5149 MonoType *args [16];
5151 if (acfg->aot_opts.no_instances)
5152 return;
5154 memset (&ctx, 0, sizeof (ctx));
5156 for (i = 0; i < ninsts; ++i) {
5157 ERROR_DECL (error);
5158 MonoClass *generic_inst;
5159 args [0] = insts [i];
5160 ctx.class_inst = mono_metadata_get_generic_inst (1, args);
5161 generic_inst = mono_class_inflate_generic_class_checked (klass, &ctx, error);
5162 mono_error_assert_ok (error); /* FIXME don't swallow the error */
5163 add_generic_class (acfg, generic_inst, force, "");
5167 static void
5168 add_types_from_method_header (MonoAotCompile *acfg, MonoMethod *method)
5170 ERROR_DECL (error);
5171 MonoMethodHeader *header;
5172 MonoMethodSignature *sig;
5173 int j, depth;
5175 depth = GPOINTER_TO_UINT (g_hash_table_lookup (acfg->method_depth, method));
5177 sig = mono_method_signature_checked (method, error);
5178 if (sig) {
5179 for (j = 0; j < sig->param_count; ++j)
5180 if (sig->params [j]->type == MONO_TYPE_GENERICINST)
5181 add_generic_class_with_depth (acfg, mono_class_from_mono_type_internal (sig->params [j]), depth + 1, "arg");
5182 } else {
5183 mono_error_cleanup (error);
5186 header = mono_method_get_header_checked (method, error);
5188 if (header) {
5189 for (j = 0; j < header->num_locals; ++j)
5190 if (header->locals [j]->type == MONO_TYPE_GENERICINST)
5191 add_generic_class_with_depth (acfg, mono_class_from_mono_type_internal (header->locals [j]), depth + 1, "local");
5192 mono_metadata_free_mh (header);
5193 } else {
5194 mono_error_cleanup (error); /* FIXME report the error */
5200 * add_generic_instances:
5202 * Add instances referenced by the METHODSPEC/TYPESPEC table.
5204 static void
5205 add_generic_instances (MonoAotCompile *acfg)
5207 int i;
5208 guint32 token;
5209 MonoMethod *method;
5210 MonoGenericContext *context;
5212 if (acfg->aot_opts.no_instances)
5213 return;
5215 for (i = 0; i < acfg->image->tables [MONO_TABLE_METHODSPEC].rows; ++i) {
5216 ERROR_DECL (error);
5217 token = MONO_TOKEN_METHOD_SPEC | (i + 1);
5218 method = mono_get_method_checked (acfg->image, token, NULL, NULL, error);
5220 if (!method) {
5221 aot_printerrf (acfg, "Failed to load methodspec 0x%x due to %s.\n", token, mono_error_get_message (error));
5222 aot_printerrf (acfg, "Run with MONO_LOG_LEVEL=debug for more information.\n");
5223 mono_error_cleanup (error);
5224 continue;
5227 if (m_class_get_image (method->klass) != acfg->image)
5228 continue;
5230 context = mono_method_get_context (method);
5232 if (context && ((context->class_inst && context->class_inst->is_open)))
5233 continue;
5236 * For open methods, create an instantiation which can be passed to the JIT.
5237 * FIXME: Handle class_inst as well.
5239 if (context && context->method_inst && context->method_inst->is_open) {
5240 ERROR_DECL (error);
5241 MonoGenericContext shared_context;
5242 MonoGenericInst *inst;
5243 MonoType **type_argv;
5244 int i;
5245 MonoMethod *declaring_method;
5246 gboolean supported = TRUE;
5248 /* Check that the context doesn't contain open constructed types */
5249 if (context->class_inst) {
5250 inst = context->class_inst;
5251 for (i = 0; i < inst->type_argc; ++i) {
5252 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)
5253 continue;
5254 if (mono_class_is_open_constructed_type (inst->type_argv [i]))
5255 supported = FALSE;
5258 if (context->method_inst) {
5259 inst = context->method_inst;
5260 for (i = 0; i < inst->type_argc; ++i) {
5261 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)
5262 continue;
5263 if (mono_class_is_open_constructed_type (inst->type_argv [i]))
5264 supported = FALSE;
5268 if (!supported)
5269 continue;
5271 memset (&shared_context, 0, sizeof (MonoGenericContext));
5273 inst = context->class_inst;
5274 if (inst) {
5275 type_argv = g_new0 (MonoType*, inst->type_argc);
5276 for (i = 0; i < inst->type_argc; ++i) {
5277 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)
5278 type_argv [i] = mono_get_object_type ();
5279 else
5280 type_argv [i] = inst->type_argv [i];
5283 shared_context.class_inst = mono_metadata_get_generic_inst (inst->type_argc, type_argv);
5284 g_free (type_argv);
5287 inst = context->method_inst;
5288 if (inst) {
5289 type_argv = g_new0 (MonoType*, inst->type_argc);
5290 for (i = 0; i < inst->type_argc; ++i) {
5291 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)
5292 type_argv [i] = mono_get_object_type ();
5293 else
5294 type_argv [i] = inst->type_argv [i];
5297 shared_context.method_inst = mono_metadata_get_generic_inst (inst->type_argc, type_argv);
5298 g_free (type_argv);
5301 if (method->is_generic || mono_class_is_gtd (method->klass))
5302 declaring_method = method;
5303 else
5304 declaring_method = mono_method_get_declaring_generic_method (method);
5306 method = mono_class_inflate_generic_method_checked (declaring_method, &shared_context, error);
5307 g_assert (mono_error_ok (error)); /* FIXME don't swallow the error */
5311 * If the method is fully sharable, it was already added in place of its
5312 * generic definition.
5314 if (mono_method_is_generic_sharable_full (method, FALSE, FALSE, FALSE))
5315 continue;
5318 * FIXME: Partially shared methods are not shared here, so we end up with
5319 * many identical methods.
5321 add_extra_method (acfg, method);
5324 for (i = 0; i < acfg->image->tables [MONO_TABLE_TYPESPEC].rows; ++i) {
5325 ERROR_DECL (error);
5326 MonoClass *klass;
5328 token = MONO_TOKEN_TYPE_SPEC | (i + 1);
5330 klass = mono_class_get_checked (acfg->image, token, error);
5331 if (!klass || m_class_get_rank (klass)) {
5332 mono_error_cleanup (error);
5333 continue;
5336 add_generic_class (acfg, klass, FALSE, "typespec");
5339 /* Add types of args/locals */
5340 for (i = 0; i < acfg->methods->len; ++i) {
5341 method = (MonoMethod *)g_ptr_array_index (acfg->methods, i);
5342 add_types_from_method_header (acfg, method);
5345 if (acfg->image == mono_defaults.corlib) {
5346 MonoClass *klass;
5347 MonoType *insts [256];
5348 int ninsts = 0;
5350 MonoType *byte_type = m_class_get_byval_arg (mono_defaults.byte_class);
5351 MonoType *sbyte_type = m_class_get_byval_arg (mono_defaults.sbyte_class);
5352 MonoType *int16_type = m_class_get_byval_arg (mono_defaults.int16_class);
5353 MonoType *uint16_type = m_class_get_byval_arg (mono_defaults.uint16_class);
5354 MonoType *int32_type = mono_get_int32_type ();
5355 MonoType *uint32_type = m_class_get_byval_arg (mono_defaults.uint32_class);
5356 MonoType *int64_type = m_class_get_byval_arg (mono_defaults.int64_class);
5357 MonoType *uint64_type = m_class_get_byval_arg (mono_defaults.uint64_class);
5358 MonoType *object_type = mono_get_object_type ();
5360 insts [ninsts ++] = byte_type;
5361 insts [ninsts ++] = sbyte_type;
5362 insts [ninsts ++] = int16_type;
5363 insts [ninsts ++] = uint16_type;
5364 insts [ninsts ++] = int32_type;
5365 insts [ninsts ++] = uint32_type;
5366 insts [ninsts ++] = int64_type;
5367 insts [ninsts ++] = uint64_type;
5368 insts [ninsts ++] = m_class_get_byval_arg (mono_defaults.single_class);
5369 insts [ninsts ++] = m_class_get_byval_arg (mono_defaults.double_class);
5370 insts [ninsts ++] = m_class_get_byval_arg (mono_defaults.char_class);
5371 insts [ninsts ++] = m_class_get_byval_arg (mono_defaults.boolean_class);
5373 /* Add GenericComparer<T> instances for primitive types for Enum.ToString () */
5374 klass = mono_class_try_load_from_name (acfg->image, "System.Collections.Generic", "GenericComparer`1");
5375 if (klass)
5376 add_instances_of (acfg, klass, insts, ninsts, TRUE);
5377 klass = mono_class_try_load_from_name (acfg->image, "System.Collections.Generic", "GenericEqualityComparer`1");
5378 if (klass)
5379 add_instances_of (acfg, klass, insts, ninsts, TRUE);
5381 /* Add instances of EnumEqualityComparer which are created by EqualityComparer<T> for enums */
5383 MonoClass *enum_comparer;
5384 MonoType *insts [16];
5385 int ninsts;
5387 ninsts = 0;
5388 insts [ninsts ++] = int32_type;
5389 insts [ninsts ++] = uint32_type;
5390 insts [ninsts ++] = uint16_type;
5391 insts [ninsts ++] = byte_type;
5392 enum_comparer = mono_class_load_from_name (mono_defaults.corlib, "System.Collections.Generic", "EnumEqualityComparer`1");
5393 add_instances_of (acfg, enum_comparer, insts, ninsts, FALSE);
5395 ninsts = 0;
5396 insts [ninsts ++] = int16_type;
5397 enum_comparer = mono_class_load_from_name (mono_defaults.corlib, "System.Collections.Generic", "ShortEnumEqualityComparer`1");
5398 add_instances_of (acfg, enum_comparer, insts, ninsts, FALSE);
5400 ninsts = 0;
5401 insts [ninsts ++] = sbyte_type;
5402 enum_comparer = mono_class_load_from_name (mono_defaults.corlib, "System.Collections.Generic", "SByteEnumEqualityComparer`1");
5403 add_instances_of (acfg, enum_comparer, insts, ninsts, FALSE);
5405 enum_comparer = mono_class_load_from_name (mono_defaults.corlib, "System.Collections.Generic", "LongEnumEqualityComparer`1");
5406 ninsts = 0;
5407 insts [ninsts ++] = int64_type;
5408 insts [ninsts ++] = uint64_type;
5409 add_instances_of (acfg, enum_comparer, insts, ninsts, FALSE);
5412 /* Add instances of the array generic interfaces for primitive types */
5413 /* This will add instances of the InternalArray_ helper methods in Array too */
5414 klass = mono_class_try_load_from_name (acfg->image, "System.Collections.Generic", "ICollection`1");
5415 if (klass)
5416 add_instances_of (acfg, klass, insts, ninsts, TRUE);
5418 klass = mono_class_try_load_from_name (acfg->image, "System.Collections.Generic", "IList`1");
5419 if (klass)
5420 add_instances_of (acfg, klass, insts, ninsts, TRUE);
5422 klass = mono_class_try_load_from_name (acfg->image, "System.Collections.Generic", "IEnumerable`1");
5423 if (klass)
5424 add_instances_of (acfg, klass, insts, ninsts, TRUE);
5427 * Add a managed-to-native wrapper of Array.GetGenericValueImpl<object>, which is
5428 * used for all instances of GetGenericValueImpl by the AOT runtime.
5431 ERROR_DECL (error);
5432 MonoGenericContext ctx;
5433 MonoType *args [16];
5434 MonoMethod *get_method;
5435 MonoClass *array_klass = m_class_get_parent (mono_class_create_array (mono_defaults.object_class, 1));
5437 get_method = mono_class_get_method_from_name_checked (array_klass, "GetGenericValueImpl", 2, 0, error);
5438 mono_error_assert_ok (error);
5440 if (get_method) {
5441 memset (&ctx, 0, sizeof (ctx));
5442 args [0] = object_type;
5443 ctx.method_inst = mono_metadata_get_generic_inst (1, args);
5444 add_extra_method (acfg, mono_marshal_get_native_wrapper (mono_class_inflate_generic_method_checked (get_method, &ctx, error), TRUE, TRUE));
5445 mono_error_assert_ok (error); /* FIXME don't swallow the error */
5449 /* Same for CompareExchange<T>/Exchange<T> */
5451 MonoGenericContext ctx;
5452 MonoType *args [16];
5453 MonoMethod *m;
5454 MonoClass *interlocked_klass = mono_class_load_from_name (mono_defaults.corlib, "System.Threading", "Interlocked");
5455 gpointer iter = NULL;
5457 while ((m = mono_class_get_methods (interlocked_klass, &iter))) {
5458 if ((!strcmp (m->name, "CompareExchange") || !strcmp (m->name, "Exchange")) && m->is_generic) {
5459 ERROR_DECL (error);
5460 memset (&ctx, 0, sizeof (ctx));
5461 args [0] = object_type;
5462 ctx.method_inst = mono_metadata_get_generic_inst (1, args);
5463 add_extra_method (acfg, mono_marshal_get_native_wrapper (mono_class_inflate_generic_method_checked (m, &ctx, error), TRUE, TRUE));
5464 g_assert (mono_error_ok (error)); /* FIXME don't swallow the error */
5469 /* Same for Volatile.Read/Write<T> */
5471 MonoGenericContext ctx;
5472 MonoType *args [16];
5473 MonoMethod *m;
5474 MonoClass *volatile_klass = mono_class_try_load_from_name (mono_defaults.corlib, "System.Threading", "Volatile");
5475 gpointer iter = NULL;
5477 if (volatile_klass) {
5478 while ((m = mono_class_get_methods (volatile_klass, &iter))) {
5479 if ((!strcmp (m->name, "Read") || !strcmp (m->name, "Write")) && m->is_generic) {
5480 ERROR_DECL (error);
5481 memset (&ctx, 0, sizeof (ctx));
5482 args [0] = object_type;
5483 ctx.method_inst = mono_metadata_get_generic_inst (1, args);
5484 add_extra_method (acfg, mono_marshal_get_native_wrapper (mono_class_inflate_generic_method_checked (m, &ctx, error), TRUE, TRUE));
5485 g_assert (mono_error_ok (error)); /* FIXME don't swallow the error */
5491 /* object[] accessor wrappers. */
5492 for (i = 1; i < 4; ++i) {
5493 MonoClass *obj_array_class = mono_class_create_array (mono_defaults.object_class, i);
5494 MonoMethod *m;
5496 m = get_method_nofail (obj_array_class, "Get", i, 0);
5497 g_assert (m);
5499 m = mono_marshal_get_array_accessor_wrapper (m);
5500 add_extra_method (acfg, m);
5502 m = get_method_nofail (obj_array_class, "Address", i, 0);
5503 g_assert (m);
5505 m = mono_marshal_get_array_accessor_wrapper (m);
5506 add_extra_method (acfg, m);
5508 m = get_method_nofail (obj_array_class, "Set", i + 1, 0);
5509 g_assert (m);
5511 m = mono_marshal_get_array_accessor_wrapper (m);
5512 add_extra_method (acfg, m);
5518 * is_direct_callable:
5520 * Return whenever the method identified by JI is directly callable without
5521 * going through the PLT.
5523 static gboolean
5524 is_direct_callable (MonoAotCompile *acfg, MonoMethod *method, MonoJumpInfo *patch_info)
5526 if ((patch_info->type == MONO_PATCH_INFO_METHOD) && (m_class_get_image (patch_info->data.method->klass) == acfg->image)) {
5527 MonoCompile *callee_cfg = (MonoCompile *)g_hash_table_lookup (acfg->method_to_cfg, patch_info->data.method);
5528 if (callee_cfg) {
5529 gboolean direct_callable = TRUE;
5531 if (direct_callable && (acfg->aot_opts.dedup || acfg->aot_opts.dedup_include) && mono_aot_can_dedup (patch_info->data.method))
5532 direct_callable = FALSE;
5534 if (direct_callable && !(!callee_cfg->has_got_slots && mono_class_is_before_field_init (callee_cfg->method->klass)))
5535 direct_callable = FALSE;
5536 if ((callee_cfg->method->iflags & METHOD_IMPL_ATTRIBUTE_SYNCHRONIZED) && (!method || method->wrapper_type != MONO_WRAPPER_SYNCHRONIZED))
5537 // FIXME: Maybe call the wrapper directly ?
5538 direct_callable = FALSE;
5540 if (acfg->aot_opts.soft_debug || acfg->aot_opts.no_direct_calls) {
5541 /* Disable this so all calls go through load_method (), see the
5542 * mini_get_debug_options ()->load_aot_jit_info_eagerly = TRUE; line in
5543 * mono_debugger_agent_init ().
5545 direct_callable = FALSE;
5548 if (callee_cfg->method->wrapper_type == MONO_WRAPPER_ALLOC)
5549 /* sgen does some initialization when the allocator method is created */
5550 direct_callable = FALSE;
5551 if (callee_cfg->method->wrapper_type == MONO_WRAPPER_WRITE_BARRIER)
5552 /* we don't know at compile time whether sgen is concurrent or not */
5553 direct_callable = FALSE;
5555 if (direct_callable)
5556 return TRUE;
5558 } else if ((patch_info->type == MONO_PATCH_INFO_ICALL_ADDR_CALL && patch_info->data.method->flags & METHOD_ATTRIBUTE_PINVOKE_IMPL)) {
5559 if (acfg->aot_opts.direct_pinvoke)
5560 return TRUE;
5561 } else if (patch_info->type == MONO_PATCH_INFO_ICALL_ADDR_CALL) {
5562 if (acfg->aot_opts.direct_icalls)
5563 return TRUE;
5564 return FALSE;
5567 return FALSE;
5570 #ifdef MONO_ARCH_AOT_SUPPORTED
5571 static const char *
5572 get_pinvoke_import (MonoAotCompile *acfg, MonoMethod *method)
5574 MonoImage *image = m_class_get_image (method->klass);
5575 MonoMethodPInvoke *piinfo = (MonoMethodPInvoke *) method;
5576 MonoTableInfo *tables = image->tables;
5577 MonoTableInfo *im = &tables [MONO_TABLE_IMPLMAP];
5578 MonoTableInfo *mr = &tables [MONO_TABLE_MODULEREF];
5579 guint32 im_cols [MONO_IMPLMAP_SIZE];
5580 char *import;
5582 import = (char *)g_hash_table_lookup (acfg->method_to_pinvoke_import, method);
5583 if (import != NULL)
5584 return import;
5586 if (!piinfo->implmap_idx || piinfo->implmap_idx > im->rows)
5587 return NULL;
5589 mono_metadata_decode_row (im, piinfo->implmap_idx - 1, im_cols, MONO_IMPLMAP_SIZE);
5591 if (!im_cols [MONO_IMPLMAP_SCOPE] || im_cols [MONO_IMPLMAP_SCOPE] > mr->rows)
5592 return NULL;
5594 import = g_strdup_printf ("%s", mono_metadata_string_heap (image, im_cols [MONO_IMPLMAP_NAME]));
5596 g_hash_table_insert (acfg->method_to_pinvoke_import, method, import);
5598 return import;
5600 #else
5601 static const char *
5602 get_pinvoke_import (MonoAotCompile *acfg, MonoMethod *method)
5604 return NULL;
5606 #endif
5608 static gint
5609 compare_lne (MonoDebugLineNumberEntry *a, MonoDebugLineNumberEntry *b)
5611 if (a->native_offset == b->native_offset)
5612 return a->il_offset - b->il_offset;
5613 else
5614 return a->native_offset - b->native_offset;
5618 * compute_line_numbers:
5620 * Returns a sparse array of size CODE_SIZE containing MonoDebugSourceLocation* entries for the native offsets which have a corresponding line number
5621 * entry.
5623 static MonoDebugSourceLocation**
5624 compute_line_numbers (MonoMethod *method, int code_size, MonoDebugMethodJitInfo *debug_info)
5626 MonoDebugMethodInfo *minfo;
5627 MonoDebugLineNumberEntry *ln_array;
5628 MonoDebugSourceLocation *loc;
5629 int i, prev_line, prev_il_offset;
5630 int *native_to_il_offset = NULL;
5631 MonoDebugSourceLocation **res;
5632 gboolean first;
5634 minfo = mono_debug_lookup_method (method);
5635 if (!minfo)
5636 return NULL;
5637 // FIXME: This seems to happen when two methods have the same cfg->method_to_register
5638 if (debug_info->code_size != code_size)
5639 return NULL;
5641 g_assert (code_size);
5643 /* Compute the native->IL offset mapping */
5645 ln_array = g_new0 (MonoDebugLineNumberEntry, debug_info->num_line_numbers);
5646 memcpy (ln_array, debug_info->line_numbers, debug_info->num_line_numbers * sizeof (MonoDebugLineNumberEntry));
5648 qsort (ln_array, debug_info->num_line_numbers, sizeof (MonoDebugLineNumberEntry), (int (*)(const void *, const void *))compare_lne);
5650 native_to_il_offset = g_new0 (int, code_size + 1);
5652 for (i = 0; i < debug_info->num_line_numbers; ++i) {
5653 int j;
5654 MonoDebugLineNumberEntry *lne = &ln_array [i];
5656 if (i == 0) {
5657 for (j = 0; j < lne->native_offset; ++j)
5658 native_to_il_offset [j] = -1;
5661 if (i < debug_info->num_line_numbers - 1) {
5662 MonoDebugLineNumberEntry *lne_next = &ln_array [i + 1];
5664 for (j = lne->native_offset; j < lne_next->native_offset; ++j)
5665 native_to_il_offset [j] = lne->il_offset;
5666 } else {
5667 for (j = lne->native_offset; j < code_size; ++j)
5668 native_to_il_offset [j] = lne->il_offset;
5671 g_free (ln_array);
5673 /* Compute the native->line number mapping */
5674 res = g_new0 (MonoDebugSourceLocation*, code_size);
5675 prev_il_offset = -1;
5676 prev_line = -1;
5677 first = TRUE;
5678 for (i = 0; i < code_size; ++i) {
5679 int il_offset = native_to_il_offset [i];
5681 if (il_offset == -1 || il_offset == prev_il_offset)
5682 continue;
5683 prev_il_offset = il_offset;
5684 loc = mono_debug_method_lookup_location (minfo, il_offset);
5685 if (!(loc && loc->source_file))
5686 continue;
5687 if (loc->row == prev_line) {
5688 mono_debug_free_source_location (loc);
5689 continue;
5691 prev_line = loc->row;
5692 //printf ("D: %s:%d il=%x native=%x\n", loc->source_file, loc->row, il_offset, i);
5693 if (first)
5694 /* This will cover the prolog too */
5695 res [0] = loc;
5696 else
5697 res [i] = loc;
5698 first = FALSE;
5700 return res;
5703 static int
5704 get_file_index (MonoAotCompile *acfg, const char *source_file)
5706 int findex;
5708 // FIXME: Free these
5709 if (!acfg->dwarf_ln_filenames)
5710 acfg->dwarf_ln_filenames = g_hash_table_new (g_str_hash, g_str_equal);
5711 findex = GPOINTER_TO_INT (g_hash_table_lookup (acfg->dwarf_ln_filenames, source_file));
5712 if (!findex) {
5713 findex = g_hash_table_size (acfg->dwarf_ln_filenames) + 1;
5714 g_hash_table_insert (acfg->dwarf_ln_filenames, g_strdup (source_file), GINT_TO_POINTER (findex));
5715 emit_unset_mode (acfg);
5716 fprintf (acfg->fp, ".file %d \"%s\"\n", findex, mono_dwarf_escape_path (source_file));
5718 return findex;
5721 #ifdef TARGET_ARM64
5722 #define INST_LEN 4
5723 #else
5724 #define INST_LEN 1
5725 #endif
5728 * emit_and_reloc_code:
5730 * Emit the native code in CODE, handling relocations along the way. If GOT_ONLY
5731 * is true, calls are made through the GOT too. This is used for emitting trampolines
5732 * in full-aot mode, since calls made from trampolines couldn't go through the PLT,
5733 * since trampolines are needed to make PTL work.
5735 static void
5736 emit_and_reloc_code (MonoAotCompile *acfg, MonoMethod *method, guint8 *code, guint32 code_len, MonoJumpInfo *relocs, gboolean got_only, MonoDebugMethodJitInfo *debug_info)
5738 int i, pindex, start_index;
5739 GPtrArray *patches;
5740 MonoJumpInfo *patch_info;
5741 MonoDebugSourceLocation **locs = NULL;
5742 gboolean skip, prologue_end = FALSE;
5743 #ifdef MONO_ARCH_AOT_SUPPORTED
5744 gboolean direct_call, external_call;
5745 guint32 got_slot;
5746 const char *direct_call_target = 0;
5747 const char *direct_pinvoke;
5748 #endif
5750 if (acfg->gas_line_numbers && method && debug_info) {
5751 locs = compute_line_numbers (method, code_len, debug_info);
5752 if (!locs) {
5753 int findex = get_file_index (acfg, "<unknown>");
5754 emit_unset_mode (acfg);
5755 fprintf (acfg->fp, ".loc %d %d 0\n", findex, 1);
5759 /* Collect and sort relocations */
5760 patches = g_ptr_array_new ();
5761 for (patch_info = relocs; patch_info; patch_info = patch_info->next)
5762 g_ptr_array_add (patches, patch_info);
5763 g_ptr_array_sort (patches, compare_patches);
5765 start_index = 0;
5766 for (i = 0; i < code_len; i += INST_LEN) {
5767 patch_info = NULL;
5768 for (pindex = start_index; pindex < patches->len; ++pindex) {
5769 patch_info = (MonoJumpInfo *)g_ptr_array_index (patches, pindex);
5770 if (patch_info->ip.i >= i)
5771 break;
5774 if (locs && locs [i]) {
5775 MonoDebugSourceLocation *loc = locs [i];
5776 int findex;
5777 const char *options;
5779 findex = get_file_index (acfg, loc->source_file);
5780 emit_unset_mode (acfg);
5781 if (!prologue_end)
5782 options = " prologue_end";
5783 else
5784 options = "";
5785 prologue_end = TRUE;
5786 fprintf (acfg->fp, ".loc %d %d 0%s\n", findex, loc->row, options);
5787 mono_debug_free_source_location (loc);
5790 skip = FALSE;
5791 #ifdef MONO_ARCH_AOT_SUPPORTED
5792 if (patch_info && (patch_info->ip.i == i) && (pindex < patches->len)) {
5793 start_index = pindex;
5795 switch (patch_info->type) {
5796 case MONO_PATCH_INFO_NONE:
5797 break;
5798 case MONO_PATCH_INFO_GOT_OFFSET: {
5799 int code_size;
5801 arch_emit_got_offset (acfg, code + i, &code_size);
5802 i += code_size - INST_LEN;
5803 skip = TRUE;
5804 patch_info->type = MONO_PATCH_INFO_NONE;
5805 break;
5807 case MONO_PATCH_INFO_OBJC_SELECTOR_REF: {
5808 int code_size, index;
5809 char *selector = (char *)patch_info->data.target;
5811 if (!acfg->objc_selector_to_index)
5812 acfg->objc_selector_to_index = g_hash_table_new (g_str_hash, g_str_equal);
5813 if (!acfg->objc_selectors)
5814 acfg->objc_selectors = g_ptr_array_new ();
5815 index = GPOINTER_TO_UINT (g_hash_table_lookup (acfg->objc_selector_to_index, selector));
5816 if (index)
5817 index --;
5818 else {
5819 index = acfg->objc_selector_index;
5820 g_ptr_array_add (acfg->objc_selectors, (void*)patch_info->data.target);
5821 g_hash_table_insert (acfg->objc_selector_to_index, selector, GUINT_TO_POINTER (index + 1));
5822 acfg->objc_selector_index ++;
5825 arch_emit_objc_selector_ref (acfg, code + i, index, &code_size);
5826 i += code_size - INST_LEN;
5827 skip = TRUE;
5828 patch_info->type = MONO_PATCH_INFO_NONE;
5829 break;
5831 default: {
5833 * If this patch is a call, try emitting a direct call instead of
5834 * through a PLT entry. This is possible if the called method is in
5835 * the same assembly and requires no initialization.
5837 direct_call = FALSE;
5838 external_call = FALSE;
5839 if ((patch_info->type == MONO_PATCH_INFO_METHOD) && (m_class_get_image (patch_info->data.method->klass) == acfg->image)) {
5840 if (!got_only && is_direct_callable (acfg, method, patch_info)) {
5841 MonoCompile *callee_cfg = (MonoCompile *)g_hash_table_lookup (acfg->method_to_cfg, patch_info->data.method);
5843 // Don't compile inflated methods if we're doing dedup
5844 if (acfg->aot_opts.dedup && !mono_aot_can_dedup (patch_info->data.method)) {
5845 char *name = mono_aot_get_mangled_method_name (patch_info->data.method);
5846 mono_trace (G_LOG_LEVEL_DEBUG, MONO_TRACE_AOT, "DIRECT CALL: %s by %s", name, method ? mono_method_full_name (method, TRUE) : "");
5847 g_free (name);
5849 direct_call = TRUE;
5850 direct_call_target = callee_cfg->asm_symbol;
5851 patch_info->type = MONO_PATCH_INFO_NONE;
5852 acfg->stats.direct_calls ++;
5856 acfg->stats.all_calls ++;
5857 } else if (patch_info->type == MONO_PATCH_INFO_ICALL_ADDR_CALL) {
5858 if (!got_only && is_direct_callable (acfg, method, patch_info)) {
5859 if (!(patch_info->data.method->flags & METHOD_ATTRIBUTE_PINVOKE_IMPL))
5860 direct_pinvoke = mono_lookup_icall_symbol (patch_info->data.method);
5861 else
5862 direct_pinvoke = get_pinvoke_import (acfg, patch_info->data.method);
5863 if (direct_pinvoke) {
5864 direct_call = TRUE;
5865 g_assert (strlen (direct_pinvoke) < 1000);
5866 direct_call_target = g_strdup_printf ("%s%s", acfg->user_symbol_prefix, direct_pinvoke);
5869 } else if (patch_info->type == MONO_PATCH_INFO_JIT_ICALL_ADDR) {
5870 const char *sym = mono_lookup_jit_icall_symbol (patch_info->data.name);
5871 if (!got_only && sym && acfg->aot_opts.direct_icalls) {
5872 /* Call to a C function implementing a jit icall */
5873 direct_call = TRUE;
5874 external_call = TRUE;
5875 g_assert (strlen (sym) < 1000);
5876 direct_call_target = g_strdup_printf ("%s%s", acfg->user_symbol_prefix, sym);
5878 } else if (patch_info->type == MONO_PATCH_INFO_JIT_ICALL) {
5879 MonoJitICallInfo *info = mono_find_jit_icall_by_name (patch_info->data.name);
5880 const char *sym = mono_lookup_jit_icall_symbol (patch_info->data.name);
5881 if (!got_only && sym && acfg->aot_opts.direct_icalls && info->func == info->wrapper) {
5882 /* Call to a jit icall without a wrapper */
5883 direct_call = TRUE;
5884 external_call = TRUE;
5885 g_assert (strlen (sym) < 1000);
5886 direct_call_target = g_strdup_printf ("%s%s", acfg->user_symbol_prefix, sym);
5890 if (direct_call) {
5891 patch_info->type = MONO_PATCH_INFO_NONE;
5892 acfg->stats.direct_calls ++;
5895 if (!got_only && !direct_call) {
5896 MonoPltEntry *plt_entry = get_plt_entry (acfg, patch_info);
5897 if (plt_entry) {
5898 /* This patch has a PLT entry, so we must emit a call to the PLT entry */
5899 direct_call = TRUE;
5900 direct_call_target = plt_entry->symbol;
5902 /* Nullify the patch */
5903 patch_info->type = MONO_PATCH_INFO_NONE;
5904 plt_entry->jit_used = TRUE;
5908 if (direct_call) {
5909 int call_size;
5911 arch_emit_direct_call (acfg, direct_call_target, external_call, FALSE, patch_info, &call_size);
5912 i += call_size - INST_LEN;
5913 } else {
5914 int code_size;
5916 got_slot = get_got_offset (acfg, FALSE, patch_info);
5918 arch_emit_got_access (acfg, acfg->got_symbol, code + i, got_slot, &code_size);
5919 i += code_size - INST_LEN;
5921 skip = TRUE;
5925 #endif /* MONO_ARCH_AOT_SUPPORTED */
5927 if (!skip) {
5928 /* Find next patch */
5929 patch_info = NULL;
5930 for (pindex = start_index; pindex < patches->len; ++pindex) {
5931 patch_info = (MonoJumpInfo *)g_ptr_array_index (patches, pindex);
5932 if (patch_info->ip.i >= i)
5933 break;
5936 /* Try to emit multiple bytes at once */
5937 if (pindex < patches->len && patch_info->ip.i > i) {
5938 int limit;
5940 for (limit = i + INST_LEN; limit < patch_info->ip.i; limit += INST_LEN) {
5941 if (locs && locs [limit])
5942 break;
5945 emit_code_bytes (acfg, code + i, limit - i);
5946 i = limit - INST_LEN;
5947 } else {
5948 emit_code_bytes (acfg, code + i, INST_LEN);
5953 g_ptr_array_free (patches, TRUE);
5954 g_free (locs);
5958 * sanitize_symbol:
5960 * Return a modified version of S which only includes characters permissible in symbols.
5962 static char*
5963 sanitize_symbol (MonoAotCompile *acfg, char *s)
5965 gboolean process = FALSE;
5966 int i, len;
5967 GString *gs;
5968 char *res;
5970 if (!s)
5971 return s;
5973 len = strlen (s);
5974 for (i = 0; i < len; ++i)
5975 if (!(s [i] <= 0x7f && (isalnum (s [i]) || s [i] == '_')))
5976 process = TRUE;
5977 if (!process)
5978 return s;
5980 gs = g_string_sized_new (len);
5981 for (i = 0; i < len; ++i) {
5982 guint8 c = s [i];
5983 if (c <= 0x7f && (isalnum (c) || c == '_')) {
5984 g_string_append_c (gs, c);
5985 } else if (c > 0x7f) {
5986 /* multi-byte utf8 */
5987 g_string_append_printf (gs, "_0x%x", c);
5988 i ++;
5989 c = s [i];
5990 while (c >> 6 == 0x2) {
5991 g_string_append_printf (gs, "%x", c);
5992 i ++;
5993 c = s [i];
5995 g_string_append_printf (gs, "_");
5996 i --;
5997 } else {
5998 g_string_append_c (gs, '_');
6002 res = mono_mempool_strdup (acfg->mempool, gs->str);
6003 g_string_free (gs, TRUE);
6004 return res;
6007 static char*
6008 get_debug_sym (MonoMethod *method, const char *prefix, GHashTable *cache)
6010 char *name1, *name2, *cached;
6011 int i, j, len, count;
6012 MonoMethod *cached_method;
6014 name1 = mono_method_full_name (method, TRUE);
6016 #ifdef TARGET_MACH
6017 // This is so that we don't accidentally create a local symbol (which starts with 'L')
6018 if ((!prefix || !*prefix) && name1 [0] == 'L')
6019 prefix = "_";
6020 #endif
6022 #if defined(TARGET_WIN32) && defined(TARGET_X86)
6023 char adjustedPrefix [MAX_SYMBOL_SIZE];
6024 prefix = mangle_symbol (prefix, adjustedPrefix, G_N_ELEMENTS (adjustedPrefix));
6025 #endif
6027 len = strlen (name1);
6028 name2 = (char *)malloc (strlen (prefix) + len + 16);
6029 memcpy (name2, prefix, strlen (prefix));
6030 j = strlen (prefix);
6031 for (i = 0; i < len; ++i) {
6032 if (i == 0 && name1 [0] >= '0' && name1 [0] <= '9') {
6033 name2 [j ++] = '_';
6034 } else if (isalnum (name1 [i])) {
6035 name2 [j ++] = name1 [i];
6036 } else if (name1 [i] == ' ' && name1 [i + 1] == '(' && name1 [i + 2] == ')') {
6037 i += 2;
6038 } else if (name1 [i] == ',' && name1 [i + 1] == ' ') {
6039 name2 [j ++] = '_';
6040 i++;
6041 } else if (name1 [i] == '(' || name1 [i] == ')' || name1 [i] == '>') {
6042 } else
6043 name2 [j ++] = '_';
6045 name2 [j] = '\0';
6047 g_free (name1);
6049 count = 0;
6050 while (TRUE) {
6051 cached_method = (MonoMethod *)g_hash_table_lookup (cache, name2);
6052 if (!(cached_method && cached_method != method))
6053 break;
6054 sprintf (name2 + j, "_%d", count);
6055 count ++;
6058 cached = g_strdup (name2);
6059 g_hash_table_insert (cache, cached, method);
6061 return name2;
6064 static void
6065 emit_method_code (MonoAotCompile *acfg, MonoCompile *cfg)
6067 MonoMethod *method;
6068 int method_index;
6069 guint8 *code;
6070 char *debug_sym = NULL;
6071 char *symbol = NULL;
6072 int func_alignment = AOT_FUNC_ALIGNMENT;
6073 char *export_name;
6075 g_assert (!ignore_cfg (cfg));
6077 method = cfg->orig_method;
6078 code = cfg->native_code;
6080 method_index = get_method_index (acfg, method);
6081 symbol = g_strdup_printf ("%sme_%x", acfg->temp_prefix, method_index);
6083 /* Make the labels local */
6084 emit_section_change (acfg, ".text", 0);
6085 emit_alignment_code (acfg, func_alignment);
6087 if (acfg->global_symbols && acfg->need_no_dead_strip)
6088 fprintf (acfg->fp, " .no_dead_strip %s\n", cfg->asm_symbol);
6090 emit_label (acfg, cfg->asm_symbol);
6092 if (acfg->aot_opts.write_symbols && !acfg->global_symbols && !acfg->llvm) {
6094 * Write a C style symbol for every method, this has two uses:
6095 * - it works on platforms where the dwarf debugging info is not
6096 * yet supported.
6097 * - it allows the setting of breakpoints of aot-ed methods.
6100 // Comment out to force dedup to link these symbols and forbid compiling
6101 // in duplicated code. This is an "assert when linking if broken" trick.
6102 /*if (mono_aot_can_dedup (method) && (acfg->aot_opts.dedup || acfg->aot_opts.dedup_include))*/
6103 /*debug_sym = mono_aot_get_mangled_method_name (method);*/
6104 /*else*/
6105 debug_sym = get_debug_sym (method, "", acfg->method_label_hash);
6107 cfg->asm_debug_symbol = g_strdup (debug_sym);
6109 if (acfg->need_no_dead_strip)
6110 fprintf (acfg->fp, " .no_dead_strip %s\n", debug_sym);
6112 // Comment out to force dedup to link these symbols and forbid compiling
6113 // in duplicated code. This is an "assert when linking if broken" trick.
6114 /*if (mono_aot_can_dedup (method) && (acfg->aot_opts.dedup || acfg->aot_opts.dedup_include))*/
6115 /*emit_global_inner (acfg, debug_sym, TRUE);*/
6116 /*else*/
6117 emit_local_symbol (acfg, debug_sym, symbol, TRUE);
6119 emit_label (acfg, debug_sym);
6122 export_name = (char *)g_hash_table_lookup (acfg->export_names, method);
6123 if (export_name) {
6124 /* Emit a global symbol for the method */
6125 emit_global_inner (acfg, export_name, TRUE);
6126 emit_label (acfg, export_name);
6129 if (cfg->verbose_level > 0 && !ignore_cfg (cfg))
6130 g_print ("Method %s emitted as %s\n", mono_method_get_full_name (method), cfg->asm_symbol);
6132 acfg->stats.code_size += cfg->code_len;
6134 acfg->cfgs [method_index]->got_offset = acfg->got_offset;
6136 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 ()));
6138 emit_line (acfg);
6140 if (acfg->aot_opts.write_symbols) {
6141 if (debug_sym)
6142 emit_symbol_size (acfg, debug_sym, ".");
6143 else
6144 emit_symbol_size (acfg, cfg->asm_symbol, ".");
6145 g_free (debug_sym);
6148 emit_label (acfg, symbol);
6150 arch_emit_unwind_info_sections (acfg, cfg->asm_symbol, symbol, cfg->unwind_ops);
6152 g_free (symbol);
6156 * encode_patch:
6158 * Encode PATCH_INFO into its disk representation.
6160 static void
6161 encode_patch (MonoAotCompile *acfg, MonoJumpInfo *patch_info, guint8 *buf, guint8 **endbuf)
6163 guint8 *p = buf;
6165 switch (patch_info->type) {
6166 case MONO_PATCH_INFO_NONE:
6167 break;
6168 case MONO_PATCH_INFO_IMAGE:
6169 encode_value (get_image_index (acfg, patch_info->data.image), p, &p);
6170 break;
6171 case MONO_PATCH_INFO_MSCORLIB_GOT_ADDR:
6172 case MONO_PATCH_INFO_GC_CARD_TABLE_ADDR:
6173 case MONO_PATCH_INFO_GC_NURSERY_START:
6174 case MONO_PATCH_INFO_GC_NURSERY_BITS:
6175 break;
6176 case MONO_PATCH_INFO_CASTCLASS_CACHE:
6177 encode_value (patch_info->data.index, p, &p);
6178 break;
6179 case MONO_PATCH_INFO_METHOD_REL:
6180 encode_value ((gint)patch_info->data.offset, p, &p);
6181 break;
6182 case MONO_PATCH_INFO_SWITCH: {
6183 gpointer *table = (gpointer *)patch_info->data.table->table;
6184 int k;
6186 encode_value (patch_info->data.table->table_size, p, &p);
6187 for (k = 0; k < patch_info->data.table->table_size; k++)
6188 encode_value ((int)(gssize)table [k], p, &p);
6189 break;
6191 case MONO_PATCH_INFO_METHODCONST:
6192 case MONO_PATCH_INFO_METHOD:
6193 case MONO_PATCH_INFO_METHOD_JUMP:
6194 case MONO_PATCH_INFO_METHOD_FTNDESC:
6195 case MONO_PATCH_INFO_ICALL_ADDR:
6196 case MONO_PATCH_INFO_ICALL_ADDR_CALL:
6197 case MONO_PATCH_INFO_METHOD_RGCTX:
6198 case MONO_PATCH_INFO_METHOD_CODE_SLOT:
6199 encode_method_ref (acfg, patch_info->data.method, p, &p);
6200 break;
6201 case MONO_PATCH_INFO_AOT_JIT_INFO:
6202 case MONO_PATCH_INFO_GET_TLS_TRAMP:
6203 case MONO_PATCH_INFO_SET_TLS_TRAMP:
6204 encode_value (patch_info->data.index, p, &p);
6205 break;
6206 case MONO_PATCH_INFO_JIT_ICALL:
6207 case MONO_PATCH_INFO_JIT_ICALL_ADDR:
6208 case MONO_PATCH_INFO_JIT_ICALL_ADDR_NOCALL: {
6209 guint32 len = strlen (patch_info->data.name);
6211 encode_value (len, p, &p);
6213 memcpy (p, patch_info->data.name, len);
6214 p += len;
6215 *p++ = '\0';
6216 break;
6218 case MONO_PATCH_INFO_LDSTR: {
6219 guint32 image_index = get_image_index (acfg, patch_info->data.token->image);
6220 guint32 token = patch_info->data.token->token;
6221 g_assert (mono_metadata_token_code (token) == MONO_TOKEN_STRING);
6222 encode_value (image_index, p, &p);
6223 encode_value (patch_info->data.token->token - MONO_TOKEN_STRING, p, &p);
6224 break;
6226 case MONO_PATCH_INFO_RVA:
6227 case MONO_PATCH_INFO_DECLSEC:
6228 case MONO_PATCH_INFO_LDTOKEN:
6229 case MONO_PATCH_INFO_TYPE_FROM_HANDLE:
6230 encode_value (get_image_index (acfg, patch_info->data.token->image), p, &p);
6231 encode_value (patch_info->data.token->token, p, &p);
6232 encode_value (patch_info->data.token->has_context, p, &p);
6233 if (patch_info->data.token->has_context)
6234 encode_generic_context (acfg, &patch_info->data.token->context, p, &p);
6235 break;
6236 case MONO_PATCH_INFO_EXC_NAME: {
6237 MonoClass *ex_class;
6239 ex_class =
6240 mono_class_load_from_name (m_class_get_image (mono_defaults.exception_class),
6241 "System", (const char *)patch_info->data.target);
6242 encode_klass_ref (acfg, ex_class, p, &p);
6243 break;
6245 case MONO_PATCH_INFO_R4:
6246 encode_value (*((guint32 *)patch_info->data.target), p, &p);
6247 break;
6248 case MONO_PATCH_INFO_R8:
6249 encode_value (((guint32 *)patch_info->data.target) [MINI_LS_WORD_IDX], p, &p);
6250 encode_value (((guint32 *)patch_info->data.target) [MINI_MS_WORD_IDX], p, &p);
6251 break;
6252 case MONO_PATCH_INFO_VTABLE:
6253 case MONO_PATCH_INFO_CLASS:
6254 case MONO_PATCH_INFO_IID:
6255 case MONO_PATCH_INFO_ADJUSTED_IID:
6256 encode_klass_ref (acfg, patch_info->data.klass, p, &p);
6257 break;
6258 case MONO_PATCH_INFO_DELEGATE_TRAMPOLINE:
6259 encode_klass_ref (acfg, patch_info->data.del_tramp->klass, p, &p);
6260 if (patch_info->data.del_tramp->method) {
6261 encode_value (1, p, &p);
6262 encode_method_ref (acfg, patch_info->data.del_tramp->method, p, &p);
6263 } else {
6264 encode_value (0, p, &p);
6266 encode_value (patch_info->data.del_tramp->is_virtual, p, &p);
6267 break;
6268 case MONO_PATCH_INFO_FIELD:
6269 case MONO_PATCH_INFO_SFLDA:
6270 encode_field_info (acfg, patch_info->data.field, p, &p);
6271 break;
6272 case MONO_PATCH_INFO_INTERRUPTION_REQUEST_FLAG:
6273 break;
6274 case MONO_PATCH_INFO_PROFILER_ALLOCATION_COUNT:
6275 case MONO_PATCH_INFO_PROFILER_CLAUSE_COUNT:
6276 break;
6277 case MONO_PATCH_INFO_RGCTX_FETCH:
6278 case MONO_PATCH_INFO_RGCTX_SLOT_INDEX: {
6279 MonoJumpInfoRgctxEntry *entry = patch_info->data.rgctx_entry;
6280 guint32 offset;
6281 guint8 *buf2, *p2;
6284 * entry->method has a lenghtly encoding and multiple rgctx_fetch entries
6285 * reference the same method, so encode the method only once.
6287 offset = GPOINTER_TO_UINT (g_hash_table_lookup (acfg->method_blob_hash, entry->method));
6288 if (!offset) {
6289 buf2 = (guint8 *)g_malloc (1024);
6290 p2 = buf2;
6292 encode_method_ref (acfg, entry->method, p2, &p2);
6293 g_assert (p2 - buf2 < 1024);
6295 offset = add_to_blob (acfg, buf2, p2 - buf2);
6296 g_free (buf2);
6298 g_hash_table_insert (acfg->method_blob_hash, entry->method, GUINT_TO_POINTER (offset + 1));
6299 } else {
6300 offset --;
6303 encode_value (offset, p, &p);
6304 g_assert ((int)entry->info_type < 256);
6305 g_assert (entry->data->type < 256);
6306 encode_value ((entry->in_mrgctx ? 1 : 0) | (entry->info_type << 1) | (entry->data->type << 9), p, &p);
6307 encode_patch (acfg, entry->data, p, &p);
6308 break;
6310 case MONO_PATCH_INFO_SEQ_POINT_INFO:
6311 case MONO_PATCH_INFO_AOT_MODULE:
6312 break;
6313 case MONO_PATCH_INFO_SIGNATURE:
6314 case MONO_PATCH_INFO_GSHAREDVT_IN_WRAPPER:
6315 encode_signature (acfg, (MonoMethodSignature*)patch_info->data.target, p, &p);
6316 break;
6317 case MONO_PATCH_INFO_GSHAREDVT_CALL:
6318 encode_signature (acfg, (MonoMethodSignature*)patch_info->data.gsharedvt->sig, p, &p);
6319 encode_method_ref (acfg, patch_info->data.gsharedvt->method, p, &p);
6320 break;
6321 case MONO_PATCH_INFO_GSHAREDVT_METHOD: {
6322 MonoGSharedVtMethodInfo *info = patch_info->data.gsharedvt_method;
6323 int i;
6325 encode_method_ref (acfg, info->method, p, &p);
6326 encode_value (info->num_entries, p, &p);
6327 for (i = 0; i < info->num_entries; ++i) {
6328 MonoRuntimeGenericContextInfoTemplate *template_ = &info->entries [i];
6330 encode_value (template_->info_type, p, &p);
6331 switch (mini_rgctx_info_type_to_patch_info_type (template_->info_type)) {
6332 case MONO_PATCH_INFO_CLASS:
6333 encode_klass_ref (acfg, mono_class_from_mono_type_internal ((MonoType *)template_->data), p, &p);
6334 break;
6335 case MONO_PATCH_INFO_FIELD:
6336 encode_field_info (acfg, (MonoClassField *)template_->data, p, &p);
6337 break;
6338 default:
6339 g_assert_not_reached ();
6340 break;
6343 break;
6345 case MONO_PATCH_INFO_LDSTR_LIT: {
6346 const char *s = (const char *)patch_info->data.target;
6347 int len = strlen (s);
6349 encode_value (len, p, &p);
6350 memcpy (p, s, len + 1);
6351 p += len + 1;
6352 break;
6354 case MONO_PATCH_INFO_VIRT_METHOD:
6355 encode_klass_ref (acfg, patch_info->data.virt_method->klass, p, &p);
6356 encode_method_ref (acfg, patch_info->data.virt_method->method, p, &p);
6357 break;
6358 case MONO_PATCH_INFO_GC_SAFE_POINT_FLAG:
6359 break;
6360 default:
6361 g_warning ("unable to handle jump info %d", patch_info->type);
6362 g_assert_not_reached ();
6365 *endbuf = p;
6368 static void
6369 encode_patch_list (MonoAotCompile *acfg, GPtrArray *patches, int n_patches, gboolean llvm, guint8 *buf, guint8 **endbuf)
6371 guint8 *p = buf;
6372 guint32 pindex, offset;
6373 MonoJumpInfo *patch_info;
6375 encode_value (n_patches, p, &p);
6377 for (pindex = 0; pindex < patches->len; ++pindex) {
6378 patch_info = (MonoJumpInfo *)g_ptr_array_index (patches, pindex);
6380 if (patch_info->type == MONO_PATCH_INFO_NONE || patch_info->type == MONO_PATCH_INFO_BB)
6381 /* Nothing to do */
6382 continue;
6383 /* This shouldn't allocate a new offset */
6384 offset = lookup_got_offset (acfg, llvm, patch_info);
6385 encode_value (offset, p, &p);
6388 *endbuf = p;
6391 static void
6392 emit_method_info (MonoAotCompile *acfg, MonoCompile *cfg)
6394 MonoMethod *method;
6395 int pindex, buf_size, n_patches;
6396 GPtrArray *patches;
6397 MonoJumpInfo *patch_info;
6398 guint8 *p, *buf;
6400 method = cfg->orig_method;
6402 (void)get_method_index (acfg, method);
6404 /* Sort relocations */
6405 patches = g_ptr_array_new ();
6406 for (patch_info = cfg->patch_info; patch_info; patch_info = patch_info->next)
6407 g_ptr_array_add (patches, patch_info);
6408 if (!acfg->aot_opts.llvm_only)
6409 g_ptr_array_sort (patches, compare_patches);
6411 /**********************/
6412 /* Encode method info */
6413 /**********************/
6415 buf_size = (patches->len < 1000) ? 40960 : 40960 + (patches->len * 64);
6416 p = buf = (guint8 *)g_malloc (buf_size);
6418 guint8 flags = 0;
6419 if (mono_class_get_cctor (method->klass))
6420 flags |= MONO_AOT_METHOD_FLAG_HAS_CCTOR;
6421 if (mini_jit_info_is_gsharedvt (cfg->jit_info) && mini_is_gsharedvt_variable_signature (mono_method_signature_internal (jinfo_get_method (cfg->jit_info))))
6422 flags |= MONO_AOT_METHOD_FLAG_GSHAREDVT_VARIABLE;
6423 encode_value (flags, p, &p);
6424 if (flags & MONO_AOT_METHOD_FLAG_HAS_CCTOR)
6425 encode_klass_ref (acfg, method->klass, p, &p);
6427 g_assert (!(cfg->opt & MONO_OPT_SHARED));
6429 n_patches = 0;
6430 for (pindex = 0; pindex < patches->len; ++pindex) {
6431 patch_info = (MonoJumpInfo *)g_ptr_array_index (patches, pindex);
6433 if ((patch_info->type == MONO_PATCH_INFO_GOT_OFFSET) ||
6434 (patch_info->type == MONO_PATCH_INFO_NONE)) {
6435 patch_info->type = MONO_PATCH_INFO_NONE;
6436 /* Nothing to do */
6437 continue;
6440 if ((patch_info->type == MONO_PATCH_INFO_IMAGE) && (patch_info->data.image == acfg->image)) {
6441 /* Stored in a GOT slot initialized at module load time */
6442 patch_info->type = MONO_PATCH_INFO_NONE;
6443 continue;
6446 if (patch_info->type == MONO_PATCH_INFO_GC_CARD_TABLE_ADDR ||
6447 patch_info->type == MONO_PATCH_INFO_GC_NURSERY_START ||
6448 patch_info->type == MONO_PATCH_INFO_GC_NURSERY_BITS ||
6449 patch_info->type == MONO_PATCH_INFO_AOT_MODULE) {
6450 /* Stored in a GOT slot initialized at module load time */
6451 patch_info->type = MONO_PATCH_INFO_NONE;
6452 continue;
6455 if (is_plt_patch (patch_info) && !(cfg->compile_llvm && acfg->aot_opts.llvm_only)) {
6456 /* Calls are made through the PLT */
6457 patch_info->type = MONO_PATCH_INFO_NONE;
6458 continue;
6461 n_patches ++;
6464 if (n_patches)
6465 g_assert (cfg->has_got_slots);
6467 encode_patch_list (acfg, patches, n_patches, cfg->compile_llvm, p, &p);
6469 g_ptr_array_free (patches, TRUE);
6471 acfg->stats.info_size += p - buf;
6473 g_assert (p - buf < buf_size);
6475 cfg->method_info_offset = add_to_blob (acfg, buf, p - buf);
6476 g_free (buf);
6479 static guint32
6480 get_unwind_info_offset (MonoAotCompile *acfg, guint8 *encoded, guint32 encoded_len)
6482 guint32 cache_index;
6483 guint32 offset;
6485 /* Reuse the unwind module to canonize and store unwind info entries */
6486 cache_index = mono_cache_unwind_info (encoded, encoded_len);
6488 /* Use +/- 1 to distinguish 0s from missing entries */
6489 offset = GPOINTER_TO_UINT (g_hash_table_lookup (acfg->unwind_info_offsets, GUINT_TO_POINTER (cache_index + 1)));
6490 if (offset)
6491 return offset - 1;
6492 else {
6493 guint8 buf [16];
6494 guint8 *p;
6497 * It would be easier to use assembler symbols, but the caller needs an
6498 * offset now.
6500 offset = acfg->unwind_info_offset;
6501 g_hash_table_insert (acfg->unwind_info_offsets, GUINT_TO_POINTER (cache_index + 1), GUINT_TO_POINTER (offset + 1));
6502 g_ptr_array_add (acfg->unwind_ops, GUINT_TO_POINTER (cache_index));
6504 p = buf;
6505 encode_value (encoded_len, p, &p);
6507 acfg->unwind_info_offset += encoded_len + (p - buf);
6508 return offset;
6512 static void
6513 emit_exception_debug_info (MonoAotCompile *acfg, MonoCompile *cfg, gboolean store_seq_points)
6515 int i, k, buf_size;
6516 guint32 debug_info_size, seq_points_size;
6517 guint8 *code;
6518 MonoMethodHeader *header;
6519 guint8 *p, *buf, *debug_info;
6520 MonoJitInfo *jinfo = cfg->jit_info;
6521 guint32 flags;
6522 gboolean use_unwind_ops = FALSE;
6523 MonoSeqPointInfo *seq_points;
6525 code = cfg->native_code;
6526 header = cfg->header;
6528 if (!acfg->aot_opts.nodebug) {
6529 mono_debug_serialize_debug_info (cfg, &debug_info, &debug_info_size);
6530 } else {
6531 debug_info = NULL;
6532 debug_info_size = 0;
6535 seq_points = cfg->seq_point_info;
6536 seq_points_size = (store_seq_points)? mono_seq_point_info_get_write_size (seq_points) : 0;
6538 buf_size = header->num_clauses * 256 + debug_info_size + 2048 + seq_points_size + cfg->gc_map_size;
6539 if (jinfo->has_try_block_holes) {
6540 MonoTryBlockHoleTableJitInfo *table = mono_jit_info_get_try_block_hole_table_info (jinfo);
6541 buf_size += table->num_holes * 16;
6544 p = buf = (guint8 *)g_malloc (buf_size);
6546 use_unwind_ops = cfg->unwind_ops != NULL;
6548 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);
6550 encode_value (flags, p, &p);
6552 if (use_unwind_ops) {
6553 guint32 encoded_len;
6554 guint8 *encoded;
6555 guint32 unwind_desc;
6557 encoded = mono_unwind_ops_encode (cfg->unwind_ops, &encoded_len);
6559 unwind_desc = get_unwind_info_offset (acfg, encoded, encoded_len);
6560 encode_value (unwind_desc, p, &p);
6562 g_free (encoded);
6563 } else {
6564 encode_value (jinfo->unwind_info, p, &p);
6567 /*Encode the number of holes before the number of clauses to make decoding easier*/
6568 if (jinfo->has_try_block_holes) {
6569 MonoTryBlockHoleTableJitInfo *table = mono_jit_info_get_try_block_hole_table_info (jinfo);
6570 encode_value (table->num_holes, p, &p);
6573 if (jinfo->has_arch_eh_info) {
6575 * In AOT mode, the code length is calculated from the address of the previous method,
6576 * which could include alignment padding, so calculating the start of the epilog as
6577 * code_len - epilog_size is correct any more. Save the real code len as a workaround.
6579 encode_value (jinfo->code_size, p, &p);
6582 /* Exception table */
6583 if (cfg->compile_llvm) {
6585 * When using LLVM, we can't emit some data, like pc offsets, this reg/offset etc.,
6586 * since the information is only available to llc. Instead, we let llc save the data
6587 * into the LSDA, and read it from there at runtime.
6589 /* The assembly might be CIL stripped so emit the data ourselves */
6590 if (header->num_clauses)
6591 encode_value (header->num_clauses, p, &p);
6593 for (k = 0; k < header->num_clauses; ++k) {
6594 MonoExceptionClause *clause;
6596 clause = &header->clauses [k];
6598 encode_value (clause->flags, p, &p);
6599 if (!(clause->flags == MONO_EXCEPTION_CLAUSE_FILTER || clause->flags == MONO_EXCEPTION_CLAUSE_FINALLY)) {
6600 if (clause->data.catch_class) {
6601 guint8 *buf2, *p2;
6602 int len;
6604 buf2 = (guint8 *)g_malloc (4096);
6605 p2 = buf2;
6606 encode_klass_ref (acfg, clause->data.catch_class, p2, &p2);
6607 len = p2 - buf2;
6608 g_assert (len < 4096);
6609 encode_value (len, p, &p);
6610 memcpy (p, buf2, len);
6611 p += p2 - buf2;
6612 g_free (buf2);
6613 } else {
6614 encode_value (0, p, &p);
6618 /* Emit the IL ranges too, since they might not be available at runtime */
6619 encode_value (clause->try_offset, p, &p);
6620 encode_value (clause->try_len, p, &p);
6621 encode_value (clause->handler_offset, p, &p);
6622 encode_value (clause->handler_len, p, &p);
6624 /* Emit a list of nesting clauses */
6625 for (i = 0; i < header->num_clauses; ++i) {
6626 gint32 cindex1 = k;
6627 MonoExceptionClause *clause1 = &header->clauses [cindex1];
6628 gint32 cindex2 = i;
6629 MonoExceptionClause *clause2 = &header->clauses [cindex2];
6631 if (cindex1 != cindex2 && clause1->try_offset >= clause2->try_offset && clause1->handler_offset <= clause2->handler_offset)
6632 encode_value (i, p, &p);
6634 encode_value (-1, p, &p);
6636 } else {
6637 if (jinfo->num_clauses)
6638 encode_value (jinfo->num_clauses, p, &p);
6640 for (k = 0; k < jinfo->num_clauses; ++k) {
6641 MonoJitExceptionInfo *ei = &jinfo->clauses [k];
6643 encode_value (ei->flags, p, &p);
6644 #ifdef MONO_CONTEXT_SET_LLVM_EXC_REG
6645 /* Not used for catch clauses */
6646 if (ei->flags != MONO_EXCEPTION_CLAUSE_NONE)
6647 encode_value (ei->exvar_offset, p, &p);
6648 #else
6649 encode_value (ei->exvar_offset, p, &p);
6650 #endif
6652 if (ei->flags == MONO_EXCEPTION_CLAUSE_FILTER || ei->flags == MONO_EXCEPTION_CLAUSE_FINALLY)
6653 encode_value ((gint)((guint8*)ei->data.filter - code), p, &p);
6654 else {
6655 if (ei->data.catch_class) {
6656 guint8 *buf2, *p2;
6657 int len;
6659 buf2 = (guint8 *)g_malloc (4096);
6660 p2 = buf2;
6661 encode_klass_ref (acfg, ei->data.catch_class, p2, &p2);
6662 len = p2 - buf2;
6663 g_assert (len < 4096);
6664 encode_value (len, p, &p);
6665 memcpy (p, buf2, len);
6666 p += p2 - buf2;
6667 g_free (buf2);
6668 } else {
6669 encode_value (0, p, &p);
6673 encode_value ((gint)((guint8*)ei->try_start - code), p, &p);
6674 encode_value ((gint)((guint8*)ei->try_end - code), p, &p);
6675 encode_value ((gint)((guint8*)ei->handler_start - code), p, &p);
6679 if (jinfo->has_try_block_holes) {
6680 MonoTryBlockHoleTableJitInfo *table = mono_jit_info_get_try_block_hole_table_info (jinfo);
6681 for (i = 0; i < table->num_holes; ++i) {
6682 MonoTryBlockHoleJitInfo *hole = &table->holes [i];
6683 encode_value (hole->clause, p, &p);
6684 encode_value (hole->length, p, &p);
6685 encode_value (hole->offset, p, &p);
6689 if (jinfo->has_arch_eh_info) {
6690 MonoArchEHJitInfo *eh_info;
6692 eh_info = mono_jit_info_get_arch_eh_info (jinfo);
6693 encode_value (eh_info->stack_size, p, &p);
6694 encode_value (eh_info->epilog_size, p, &p);
6697 if (jinfo->has_generic_jit_info) {
6698 MonoGenericJitInfo *gi = mono_jit_info_get_generic_jit_info (jinfo);
6699 MonoGenericSharingContext* gsctx = gi->generic_sharing_context;
6700 guint8 *buf2, *p2;
6701 int len;
6703 encode_value (gi->nlocs, p, &p);
6704 if (gi->nlocs) {
6705 for (i = 0; i < gi->nlocs; ++i) {
6706 MonoDwarfLocListEntry *entry = &gi->locations [i];
6708 encode_value (entry->is_reg ? 1 : 0, p, &p);
6709 encode_value (entry->reg, p, &p);
6710 if (!entry->is_reg)
6711 encode_value (entry->offset, p, &p);
6712 if (i == 0)
6713 g_assert (entry->from == 0);
6714 else
6715 encode_value (entry->from, p, &p);
6716 encode_value (entry->to, p, &p);
6718 } else {
6719 if (!cfg->compile_llvm) {
6720 encode_value (gi->has_this ? 1 : 0, p, &p);
6721 encode_value (gi->this_reg, p, &p);
6722 encode_value (gi->this_offset, p, &p);
6727 * Need to encode jinfo->method too, since it is not equal to 'method'
6728 * when using generic sharing.
6730 buf2 = (guint8 *)g_malloc (4096);
6731 p2 = buf2;
6732 encode_method_ref (acfg, jinfo->d.method, p2, &p2);
6733 len = p2 - buf2;
6734 g_assert (len < 4096);
6735 encode_value (len, p, &p);
6736 memcpy (p, buf2, len);
6737 p += p2 - buf2;
6738 g_free (buf2);
6740 if (gsctx && gsctx->is_gsharedvt) {
6741 encode_value (1, p, &p);
6742 } else {
6743 encode_value (0, p, &p);
6747 if (seq_points_size)
6748 p += mono_seq_point_info_write (seq_points, p);
6750 g_assert (debug_info_size < buf_size);
6752 encode_value (debug_info_size, p, &p);
6753 if (debug_info_size) {
6754 memcpy (p, debug_info, debug_info_size);
6755 p += debug_info_size;
6756 g_free (debug_info);
6759 /* GC Map */
6760 if (cfg->gc_map) {
6761 encode_value (cfg->gc_map_size, p, &p);
6762 /* The GC map requires 4 bytes of alignment */
6763 while ((gsize)p % 4)
6764 p ++;
6765 memcpy (p, cfg->gc_map, cfg->gc_map_size);
6766 p += cfg->gc_map_size;
6769 acfg->stats.ex_info_size += p - buf;
6771 g_assert (p - buf < buf_size);
6773 /* Emit info */
6774 /* The GC Map requires 4 byte alignment */
6775 cfg->ex_info_offset = add_to_blob_aligned (acfg, buf, p - buf, cfg->gc_map ? 4 : 1);
6776 g_free (buf);
6779 static guint32
6780 emit_klass_info (MonoAotCompile *acfg, guint32 token)
6782 ERROR_DECL (error);
6783 MonoClass *klass = mono_class_get_checked (acfg->image, token, error);
6784 guint8 *p, *buf;
6785 int i, buf_size, res;
6786 gboolean no_special_static, cant_encode;
6787 gpointer iter = NULL;
6789 if (!klass) {
6790 mono_error_cleanup (error);
6792 buf_size = 16;
6794 p = buf = (guint8 *)g_malloc (buf_size);
6796 /* Mark as unusable */
6797 encode_value (-1, p, &p);
6799 res = add_to_blob (acfg, buf, p - buf);
6800 g_free (buf);
6802 return res;
6805 buf_size = 10240 + (m_class_get_vtable_size (klass) * 16);
6806 p = buf = (guint8 *)g_malloc (buf_size);
6808 g_assert (klass);
6810 mono_class_init_internal (klass);
6812 mono_class_get_nested_types (klass, &iter);
6813 g_assert (m_class_is_nested_classes_inited (klass));
6815 mono_class_setup_vtable (klass);
6818 * Emit all the information which is required for creating vtables so
6819 * the runtime does not need to create the MonoMethod structures which
6820 * take up a lot of space.
6823 no_special_static = !mono_class_has_special_static_fields (klass);
6825 /* Check whenever we have enough info to encode the vtable */
6826 cant_encode = FALSE;
6827 MonoMethod **klass_vtable = m_class_get_vtable (klass);
6828 for (i = 0; i < m_class_get_vtable_size (klass); ++i) {
6829 MonoMethod *cm = klass_vtable [i];
6831 if (cm && mono_method_signature_internal (cm)->is_inflated && !g_hash_table_lookup (acfg->token_info_hash, cm))
6832 cant_encode = TRUE;
6835 mono_class_has_finalizer (klass);
6836 if (mono_class_has_failure (klass))
6837 cant_encode = TRUE;
6839 if (mono_class_is_gtd (klass) || cant_encode) {
6840 encode_value (-1, p, &p);
6841 } else {
6842 gboolean has_nested = mono_class_get_nested_classes_property (klass) != NULL;
6843 encode_value (m_class_get_vtable_size (klass), p, &p);
6844 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);
6845 if (m_class_has_cctor (klass))
6846 encode_method_ref (acfg, mono_class_get_cctor (klass), p, &p);
6847 if (m_class_has_finalize (klass))
6848 encode_method_ref (acfg, mono_class_get_finalizer (klass), p, &p);
6850 encode_value (m_class_get_instance_size (klass), p, &p);
6851 encode_value (mono_class_data_size (klass), p, &p);
6852 encode_value (m_class_get_packing_size (klass), p, &p);
6853 encode_value (m_class_get_min_align (klass), p, &p);
6855 for (i = 0; i < m_class_get_vtable_size (klass); ++i) {
6856 MonoMethod *cm = klass_vtable [i];
6858 if (cm)
6859 encode_method_ref (acfg, cm, p, &p);
6860 else
6861 encode_value (0, p, &p);
6865 acfg->stats.class_info_size += p - buf;
6867 g_assert (p - buf < buf_size);
6868 res = add_to_blob (acfg, buf, p - buf);
6869 g_free (buf);
6871 return res;
6874 static char*
6875 get_plt_entry_debug_sym (MonoAotCompile *acfg, MonoJumpInfo *ji, GHashTable *cache)
6877 char *debug_sym = NULL;
6878 char *prefix;
6880 if (acfg->llvm && llvm_acfg->aot_opts.static_link) {
6881 /* Need to add a prefix to create unique symbols */
6882 prefix = g_strdup_printf ("plt_%s_", acfg->assembly_name_sym);
6883 } else {
6884 #if defined(TARGET_WIN32) && defined(TARGET_X86)
6885 prefix = mangle_symbol_alloc ("plt_");
6886 #else
6887 prefix = g_strdup ("plt_");
6888 #endif
6891 switch (ji->type) {
6892 case MONO_PATCH_INFO_METHOD:
6893 debug_sym = get_debug_sym (ji->data.method, prefix, cache);
6894 break;
6895 case MONO_PATCH_INFO_JIT_ICALL:
6896 debug_sym = g_strdup_printf ("%s_jit_icall_%s", prefix, ji->data.name);
6897 break;
6898 case MONO_PATCH_INFO_RGCTX_FETCH:
6899 debug_sym = g_strdup_printf ("%s_rgctx_fetch_%d", prefix, acfg->label_generator ++);
6900 break;
6901 case MONO_PATCH_INFO_ICALL_ADDR:
6902 case MONO_PATCH_INFO_ICALL_ADDR_CALL: {
6903 char *s = get_debug_sym (ji->data.method, "", cache);
6905 debug_sym = g_strdup_printf ("%s_icall_native_%s", prefix, s);
6906 g_free (s);
6907 break;
6909 case MONO_PATCH_INFO_JIT_ICALL_ADDR:
6910 debug_sym = g_strdup_printf ("%s_jit_icall_native_%s", prefix, ji->data.name);
6911 break;
6912 default:
6913 break;
6916 g_free (prefix);
6918 return sanitize_symbol (acfg, debug_sym);
6922 * Calls made from AOTed code are routed through a table of jumps similar to the
6923 * ELF PLT (Program Linkage Table). Initially the PLT entries jump to code which transfers
6924 * control to the AOT runtime through a trampoline.
6926 static void
6927 emit_plt (MonoAotCompile *acfg)
6929 int i;
6931 if (acfg->aot_opts.llvm_only) {
6932 g_assert (acfg->plt_offset == 1);
6933 return;
6936 emit_line (acfg);
6938 emit_section_change (acfg, ".text", 0);
6939 emit_alignment_code (acfg, 16);
6940 emit_info_symbol (acfg, "plt", TRUE);
6941 emit_label (acfg, acfg->plt_symbol);
6943 for (i = 0; i < acfg->plt_offset; ++i) {
6944 char *debug_sym = NULL;
6945 MonoPltEntry *plt_entry = NULL;
6947 if (i == 0)
6949 * The first plt entry is unused.
6951 continue;
6953 plt_entry = (MonoPltEntry *)g_hash_table_lookup (acfg->plt_offset_to_entry, GUINT_TO_POINTER (i));
6955 debug_sym = plt_entry->debug_sym;
6957 if (acfg->thumb_mixed && !plt_entry->jit_used)
6958 /* Emit only a thumb version */
6959 continue;
6961 /* Skip plt entries not actually called */
6962 if (!plt_entry->jit_used && !plt_entry->llvm_used)
6963 continue;
6965 if (acfg->llvm && !acfg->thumb_mixed) {
6966 emit_label (acfg, plt_entry->llvm_symbol);
6967 if (acfg->llvm) {
6968 emit_global_inner (acfg, plt_entry->llvm_symbol, TRUE);
6969 #if defined(TARGET_MACH)
6970 fprintf (acfg->fp, ".private_extern %s\n", plt_entry->llvm_symbol);
6971 #endif
6975 if (debug_sym) {
6976 if (acfg->need_no_dead_strip) {
6977 emit_unset_mode (acfg);
6978 fprintf (acfg->fp, " .no_dead_strip %s\n", debug_sym);
6980 emit_local_symbol (acfg, debug_sym, NULL, TRUE);
6981 emit_label (acfg, debug_sym);
6984 emit_label (acfg, plt_entry->symbol);
6986 arch_emit_plt_entry (acfg, acfg->got_symbol, (acfg->plt_got_offset_base + i) * sizeof (target_mgreg_t), acfg->plt_got_info_offsets [i]);
6988 if (debug_sym)
6989 emit_symbol_size (acfg, debug_sym, ".");
6992 if (acfg->thumb_mixed) {
6993 /* Make sure the ARM symbols don't alias the thumb ones */
6994 emit_zero_bytes (acfg, 16);
6997 * Emit a separate set of PLT entries using thumb2 which is called by LLVM generated
6998 * code.
7000 for (i = 0; i < acfg->plt_offset; ++i) {
7001 char *debug_sym = NULL;
7002 MonoPltEntry *plt_entry = NULL;
7004 if (i == 0)
7005 continue;
7007 plt_entry = (MonoPltEntry *)g_hash_table_lookup (acfg->plt_offset_to_entry, GUINT_TO_POINTER (i));
7009 /* Skip plt entries not actually called by LLVM code */
7010 if (!plt_entry->llvm_used)
7011 continue;
7013 if (acfg->aot_opts.write_symbols) {
7014 if (plt_entry->debug_sym)
7015 debug_sym = g_strdup_printf ("%s_thumb", plt_entry->debug_sym);
7018 if (debug_sym) {
7019 #if defined(TARGET_MACH)
7020 fprintf (acfg->fp, " .thumb_func %s\n", debug_sym);
7021 fprintf (acfg->fp, " .no_dead_strip %s\n", debug_sym);
7022 #endif
7023 emit_local_symbol (acfg, debug_sym, NULL, TRUE);
7024 emit_label (acfg, debug_sym);
7026 fprintf (acfg->fp, "\n.thumb_func\n");
7028 emit_label (acfg, plt_entry->llvm_symbol);
7030 if (acfg->llvm)
7031 emit_global_inner (acfg, plt_entry->llvm_symbol, TRUE);
7033 arch_emit_llvm_plt_entry (acfg, acfg->got_symbol, (acfg->plt_got_offset_base + i) * sizeof (target_mgreg_t), acfg->plt_got_info_offsets [i]);
7035 if (debug_sym) {
7036 emit_symbol_size (acfg, debug_sym, ".");
7037 g_free (debug_sym);
7042 emit_symbol_size (acfg, acfg->plt_symbol, ".");
7044 emit_info_symbol (acfg, "plt_end", TRUE);
7046 arch_emit_unwind_info_sections (acfg, "plt", "plt_end", NULL);
7050 * emit_trampoline_full:
7052 * If EMIT_TINFO is TRUE, emit additional information which can be used to create a MonoJitInfo for this trampoline by
7053 * create_jit_info_for_trampoline ().
7055 static G_GNUC_UNUSED void
7056 emit_trampoline_full (MonoAotCompile *acfg, MonoTrampInfo *info, gboolean emit_tinfo)
7058 char start_symbol [MAX_SYMBOL_SIZE];
7059 char end_symbol [MAX_SYMBOL_SIZE];
7060 char symbol [MAX_SYMBOL_SIZE];
7061 guint32 buf_size, info_offset;
7062 MonoJumpInfo *patch_info;
7063 guint8 *buf, *p;
7064 GPtrArray *patches;
7065 char *name;
7066 guint8 *code;
7067 guint32 code_size;
7068 MonoJumpInfo *ji;
7069 GSList *unwind_ops;
7071 g_assert (info);
7073 name = info->name;
7074 code = info->code;
7075 code_size = info->code_size;
7076 ji = info->ji;
7077 unwind_ops = info->unwind_ops;
7079 /* Emit code */
7081 sprintf (start_symbol, "%s%s", acfg->user_symbol_prefix, name);
7083 emit_section_change (acfg, ".text", 0);
7084 emit_global (acfg, start_symbol, TRUE);
7085 emit_alignment_code (acfg, AOT_FUNC_ALIGNMENT);
7086 emit_label (acfg, start_symbol);
7088 sprintf (symbol, "%snamed_%s", acfg->temp_prefix, name);
7089 emit_label (acfg, symbol);
7092 * The code should access everything through the GOT, so we pass
7093 * TRUE here.
7095 emit_and_reloc_code (acfg, NULL, code, code_size, ji, TRUE, NULL);
7097 emit_symbol_size (acfg, start_symbol, ".");
7099 if (emit_tinfo) {
7100 sprintf (end_symbol, "%snamede_%s", acfg->temp_prefix, name);
7101 emit_label (acfg, end_symbol);
7104 /* Emit info */
7106 /* Sort relocations */
7107 patches = g_ptr_array_new ();
7108 for (patch_info = ji; patch_info; patch_info = patch_info->next)
7109 if (patch_info->type != MONO_PATCH_INFO_NONE)
7110 g_ptr_array_add (patches, patch_info);
7111 g_ptr_array_sort (patches, compare_patches);
7113 buf_size = patches->len * 128 + 128;
7114 buf = (guint8 *)g_malloc (buf_size);
7115 p = buf;
7117 encode_patch_list (acfg, patches, patches->len, FALSE, p, &p);
7118 g_assert (p - buf < buf_size);
7119 g_ptr_array_free (patches, TRUE);
7121 sprintf (symbol, "%s%s_p", acfg->user_symbol_prefix, name);
7123 info_offset = add_to_blob (acfg, buf, p - buf);
7125 emit_section_change (acfg, RODATA_SECT, 0);
7126 emit_global (acfg, symbol, FALSE);
7127 emit_label (acfg, symbol);
7129 emit_int32 (acfg, info_offset);
7131 if (emit_tinfo) {
7132 guint8 *encoded;
7133 guint32 encoded_len;
7134 guint32 uw_offset;
7137 * Emit additional information which can be used to reconstruct a partial MonoTrampInfo.
7139 encoded = mono_unwind_ops_encode (info->unwind_ops, &encoded_len);
7140 uw_offset = get_unwind_info_offset (acfg, encoded, encoded_len);
7141 g_free (encoded);
7143 emit_symbol_diff (acfg, end_symbol, start_symbol, 0);
7144 emit_int32 (acfg, uw_offset);
7147 /* Emit debug info */
7148 if (unwind_ops) {
7149 char symbol2 [MAX_SYMBOL_SIZE];
7151 sprintf (symbol, "%s", name);
7152 sprintf (symbol2, "%snamed_%s", acfg->temp_prefix, name);
7154 arch_emit_unwind_info_sections (acfg, start_symbol, end_symbol, unwind_ops);
7156 if (acfg->dwarf)
7157 mono_dwarf_writer_emit_trampoline (acfg->dwarf, symbol, symbol2, NULL, NULL, code_size, unwind_ops);
7160 g_free (buf);
7163 static G_GNUC_UNUSED void
7164 emit_trampoline (MonoAotCompile *acfg, MonoTrampInfo *info)
7166 emit_trampoline_full (acfg, info, TRUE);
7169 static void
7170 emit_trampolines (MonoAotCompile *acfg)
7172 char symbol [MAX_SYMBOL_SIZE];
7173 char end_symbol [MAX_SYMBOL_SIZE];
7174 int i, tramp_got_offset;
7175 int ntype;
7176 #ifdef MONO_ARCH_HAVE_FULL_AOT_TRAMPOLINES
7177 int tramp_type;
7178 #endif
7180 if (!mono_aot_mode_is_full (&acfg->aot_opts) && !mono_aot_mode_is_interp (&acfg->aot_opts))
7181 return;
7182 if (acfg->aot_opts.llvm_only)
7183 return;
7185 g_assert (acfg->image->assembly);
7187 /* Currently, we emit most trampolines into the mscorlib AOT image. */
7188 if (mono_is_corlib_image(acfg->image->assembly->image)) {
7189 #ifdef MONO_ARCH_HAVE_FULL_AOT_TRAMPOLINES
7190 MonoTrampInfo *info;
7193 * Emit the generic trampolines.
7195 * We could save some code by treating the generic trampolines as a wrapper
7196 * method, but that approach has its own complexities, so we choose the simpler
7197 * method.
7199 for (tramp_type = 0; tramp_type < MONO_TRAMPOLINE_NUM; ++tramp_type) {
7200 /* we overload the boolean here to indicate the slightly different trampoline needed, see mono_arch_create_generic_trampoline() */
7201 #ifdef DISABLE_REMOTING
7202 if (tramp_type == MONO_TRAMPOLINE_GENERIC_VIRTUAL_REMOTING)
7203 continue;
7204 #endif
7205 mono_arch_create_generic_trampoline ((MonoTrampolineType)tramp_type, &info, acfg->aot_opts.use_trampolines_page? 2: TRUE);
7206 emit_trampoline (acfg, info);
7207 mono_tramp_info_free (info);
7210 /* Emit the exception related code pieces */
7211 mono_arch_get_restore_context (&info, TRUE);
7212 emit_trampoline (acfg, info);
7213 mono_tramp_info_free (info);
7215 mono_arch_get_call_filter (&info, TRUE);
7216 emit_trampoline (acfg, info);
7217 mono_tramp_info_free (info);
7219 mono_arch_get_throw_exception (&info, TRUE);
7220 emit_trampoline (acfg, info);
7221 mono_tramp_info_free (info);
7223 mono_arch_get_rethrow_exception (&info, TRUE);
7224 emit_trampoline (acfg, info);
7225 mono_tramp_info_free (info);
7227 mono_arch_get_rethrow_preserve_exception (&info, TRUE);
7228 emit_trampoline (acfg, info);
7229 mono_tramp_info_free (info);
7231 mono_arch_get_throw_corlib_exception (&info, TRUE);
7232 emit_trampoline (acfg, info);
7233 mono_tramp_info_free (info);
7235 #ifdef MONO_ARCH_HAVE_SDB_TRAMPOLINES
7236 mono_arch_create_sdb_trampoline (TRUE, &info, TRUE);
7237 emit_trampoline (acfg, info);
7238 mono_tramp_info_free (info);
7240 mono_arch_create_sdb_trampoline (FALSE, &info, TRUE);
7241 emit_trampoline (acfg, info);
7242 mono_tramp_info_free (info);
7243 #endif
7245 #ifdef MONO_ARCH_GSHAREDVT_SUPPORTED
7246 mono_arch_get_gsharedvt_trampoline (&info, TRUE);
7247 if (info) {
7248 emit_trampoline_full (acfg, info, TRUE);
7250 /* Create a separate out trampoline for more information in stack traces */
7251 info->name = g_strdup ("gsharedvt_out_trampoline");
7252 emit_trampoline_full (acfg, info, TRUE);
7253 mono_tramp_info_free (info);
7255 #endif
7257 #if defined(MONO_ARCH_HAVE_GET_TRAMPOLINES)
7259 GSList *l = mono_arch_get_trampolines (TRUE);
7261 while (l) {
7262 MonoTrampInfo *info = (MonoTrampInfo *)l->data;
7264 emit_trampoline (acfg, info);
7265 l = l->next;
7268 #endif
7270 for (i = 0; i < acfg->aot_opts.nrgctx_fetch_trampolines; ++i) {
7271 int offset;
7273 offset = MONO_RGCTX_SLOT_MAKE_RGCTX (i);
7274 mono_arch_create_rgctx_lazy_fetch_trampoline (offset, &info, TRUE);
7275 emit_trampoline (acfg, info);
7276 mono_tramp_info_free (info);
7278 offset = MONO_RGCTX_SLOT_MAKE_MRGCTX (i);
7279 mono_arch_create_rgctx_lazy_fetch_trampoline (offset, &info, TRUE);
7280 emit_trampoline (acfg, info);
7281 mono_tramp_info_free (info);
7284 #ifdef MONO_ARCH_HAVE_GENERAL_RGCTX_LAZY_FETCH_TRAMPOLINE
7285 mono_arch_create_general_rgctx_lazy_fetch_trampoline (&info, TRUE);
7286 emit_trampoline (acfg, info);
7287 mono_tramp_info_free (info);
7288 #endif
7291 GSList *l;
7293 /* delegate_invoke_impl trampolines */
7294 l = mono_arch_get_delegate_invoke_impls ();
7295 while (l) {
7296 MonoTrampInfo *info = (MonoTrampInfo *)l->data;
7298 emit_trampoline (acfg, info);
7299 l = l->next;
7303 if (mono_aot_mode_is_interp (&acfg->aot_opts)) {
7304 mono_arch_get_interp_to_native_trampoline (&info);
7305 emit_trampoline (acfg, info);
7307 #ifdef MONO_ARCH_HAVE_INTERP_ENTRY_TRAMPOLINE
7308 mono_arch_get_native_to_interp_trampoline (&info);
7309 emit_trampoline (acfg, info);
7310 #endif
7313 #endif /* #ifdef MONO_ARCH_HAVE_FULL_AOT_TRAMPOLINES */
7315 /* Emit trampolines which are numerous */
7318 * These include the following:
7319 * - specific trampolines
7320 * - static rgctx invoke trampolines
7321 * - imt trampolines
7322 * These trampolines have the same code, they are parameterized by GOT
7323 * slots.
7324 * They are defined in this file, in the arch_... routines instead of
7325 * in tramp-<ARCH>.c, since it is easier to do it this way.
7329 * When running in aot-only mode, we can't create specific trampolines at
7330 * runtime, so we create a few, and save them in the AOT file.
7331 * Normal trampolines embed their argument as a literal inside the
7332 * trampoline code, we can't do that here, so instead we embed an offset
7333 * which needs to be added to the trampoline address to get the address of
7334 * the GOT slot which contains the argument value.
7335 * The generated trampolines jump to the generic trampolines using another
7336 * GOT slot, which will be setup by the AOT loader to point to the
7337 * generic trampoline code of the given type.
7341 * FIXME: Maybe we should use more specific trampolines (i.e. one class init for
7342 * each class).
7345 emit_section_change (acfg, ".text", 0);
7347 tramp_got_offset = acfg->got_offset;
7349 for (ntype = 0; ntype < MONO_AOT_TRAMP_NUM; ++ntype) {
7350 switch (ntype) {
7351 case MONO_AOT_TRAMP_SPECIFIC:
7352 sprintf (symbol, "specific_trampolines");
7353 break;
7354 case MONO_AOT_TRAMP_STATIC_RGCTX:
7355 sprintf (symbol, "static_rgctx_trampolines");
7356 break;
7357 case MONO_AOT_TRAMP_IMT:
7358 sprintf (symbol, "imt_trampolines");
7359 break;
7360 case MONO_AOT_TRAMP_GSHAREDVT_ARG:
7361 sprintf (symbol, "gsharedvt_arg_trampolines");
7362 break;
7363 case MONO_AOT_TRAMP_FTNPTR_ARG:
7364 sprintf (symbol, "ftnptr_arg_trampolines");
7365 break;
7366 case MONO_AOT_TRAMP_UNBOX_ARBITRARY:
7367 sprintf (symbol, "unbox_arbitrary_trampolines");
7368 break;
7369 default:
7370 g_assert_not_reached ();
7373 sprintf (end_symbol, "%s_e", symbol);
7375 if (acfg->aot_opts.write_symbols)
7376 emit_local_symbol (acfg, symbol, end_symbol, TRUE);
7378 emit_alignment_code (acfg, AOT_FUNC_ALIGNMENT);
7379 emit_info_symbol (acfg, symbol, TRUE);
7381 acfg->trampoline_got_offset_base [ntype] = tramp_got_offset;
7383 for (i = 0; i < acfg->num_trampolines [ntype]; ++i) {
7384 int tramp_size = 0;
7386 switch (ntype) {
7387 case MONO_AOT_TRAMP_SPECIFIC:
7388 arch_emit_specific_trampoline (acfg, tramp_got_offset, &tramp_size);
7389 tramp_got_offset += 2;
7390 break;
7391 case MONO_AOT_TRAMP_STATIC_RGCTX:
7392 arch_emit_static_rgctx_trampoline (acfg, tramp_got_offset, &tramp_size);
7393 tramp_got_offset += 2;
7394 break;
7395 case MONO_AOT_TRAMP_IMT:
7396 arch_emit_imt_trampoline (acfg, tramp_got_offset, &tramp_size);
7397 tramp_got_offset += 1;
7398 break;
7399 case MONO_AOT_TRAMP_GSHAREDVT_ARG:
7400 arch_emit_gsharedvt_arg_trampoline (acfg, tramp_got_offset, &tramp_size);
7401 tramp_got_offset += 2;
7402 break;
7403 case MONO_AOT_TRAMP_FTNPTR_ARG:
7404 arch_emit_ftnptr_arg_trampoline (acfg, tramp_got_offset, &tramp_size);
7405 tramp_got_offset += 2;
7406 break;
7407 case MONO_AOT_TRAMP_UNBOX_ARBITRARY:
7408 arch_emit_unbox_arbitrary_trampoline (acfg, tramp_got_offset, &tramp_size);
7409 tramp_got_offset += 1;
7410 break;
7411 default:
7412 g_assert_not_reached ();
7414 if (!acfg->trampoline_size [ntype]) {
7415 g_assert (tramp_size);
7416 acfg->trampoline_size [ntype] = tramp_size;
7420 emit_label (acfg, end_symbol);
7421 emit_int32 (acfg, 0);
7424 arch_emit_specific_trampoline_pages (acfg);
7426 /* Reserve some entries at the end of the GOT for our use */
7427 acfg->num_trampoline_got_entries = tramp_got_offset - acfg->got_offset;
7430 acfg->got_offset += acfg->num_trampoline_got_entries;
7433 static gboolean
7434 str_begins_with (const char *str1, const char *str2)
7436 int len = strlen (str2);
7437 return strncmp (str1, str2, len) == 0;
7440 void*
7441 mono_aot_readonly_field_override (MonoClassField *field)
7443 ReadOnlyValue *rdv;
7444 for (rdv = readonly_values; rdv; rdv = rdv->next) {
7445 char *p = rdv->name;
7446 int len;
7447 len = strlen (m_class_get_name_space (field->parent));
7448 if (strncmp (p, m_class_get_name_space (field->parent), len))
7449 continue;
7450 p += len;
7451 if (*p++ != '.')
7452 continue;
7453 len = strlen (m_class_get_name (field->parent));
7454 if (strncmp (p, m_class_get_name (field->parent), len))
7455 continue;
7456 p += len;
7457 if (*p++ != '.')
7458 continue;
7459 if (strcmp (p, field->name))
7460 continue;
7461 switch (rdv->type) {
7462 case MONO_TYPE_I1:
7463 return &rdv->value.i1;
7464 case MONO_TYPE_I2:
7465 return &rdv->value.i2;
7466 case MONO_TYPE_I4:
7467 return &rdv->value.i4;
7468 default:
7469 break;
7472 return NULL;
7475 static void
7476 add_readonly_value (MonoAotOptions *opts, const char *val)
7478 ReadOnlyValue *rdv;
7479 const char *fval;
7480 const char *tval;
7481 /* the format of val is:
7482 * namespace.typename.fieldname=type/value
7483 * type can be i1 for uint8/int8/boolean, i2 for uint16/int16/char, i4 for uint32/int32
7485 fval = strrchr (val, '/');
7486 if (!fval) {
7487 fprintf (stderr, "AOT : invalid format for readonly field '%s', missing /.\n", val);
7488 exit (1);
7490 tval = strrchr (val, '=');
7491 if (!tval) {
7492 fprintf (stderr, "AOT : invalid format for readonly field '%s', missing =.\n", val);
7493 exit (1);
7495 rdv = g_new0 (ReadOnlyValue, 1);
7496 rdv->name = (char *)g_malloc0 (tval - val + 1);
7497 memcpy (rdv->name, val, tval - val);
7498 tval++;
7499 fval++;
7500 if (strncmp (tval, "i1", 2) == 0) {
7501 rdv->value.i1 = atoi (fval);
7502 rdv->type = MONO_TYPE_I1;
7503 } else if (strncmp (tval, "i2", 2) == 0) {
7504 rdv->value.i2 = atoi (fval);
7505 rdv->type = MONO_TYPE_I2;
7506 } else if (strncmp (tval, "i4", 2) == 0) {
7507 rdv->value.i4 = atoi (fval);
7508 rdv->type = MONO_TYPE_I4;
7509 } else {
7510 fprintf (stderr, "AOT : unsupported type for readonly field '%s'.\n", tval);
7511 exit (1);
7513 rdv->next = readonly_values;
7514 readonly_values = rdv;
7517 static gchar *
7518 clean_path (gchar * path)
7520 if (!path)
7521 return NULL;
7523 if (g_str_has_suffix (path, G_DIR_SEPARATOR_S))
7524 return path;
7526 gchar *clean = g_strconcat (path, G_DIR_SEPARATOR_S, NULL);
7527 g_free (path);
7529 return clean;
7532 static const gchar *
7533 wrap_path (const gchar * path)
7535 int len;
7536 if (!path)
7537 return NULL;
7539 // If the string contains no spaces, just return the original string.
7540 if (strstr (path, " ") == NULL)
7541 return path;
7543 // If the string is already wrapped in quotes, return it.
7544 len = strlen (path);
7545 if (len >= 2 && path[0] == '\"' && path[len-1] == '\"')
7546 return path;
7548 // If the string contains spaces, then wrap it in quotes.
7549 gchar *clean = g_strdup_printf ("\"%s\"", path);
7551 return clean;
7554 // Duplicate a char range and add it to a ptrarray, but only if it is nonempty
7555 static void
7556 ptr_array_add_range_if_nonempty(GPtrArray *args, gchar const *start, gchar const *end)
7558 ptrdiff_t len = end-start;
7559 if (len > 0)
7560 g_ptr_array_add (args, g_strndup (start, len));
7563 static GPtrArray *
7564 mono_aot_split_options (const char *aot_options)
7566 enum MonoAotOptionState {
7567 MONO_AOT_OPTION_STATE_DEFAULT,
7568 MONO_AOT_OPTION_STATE_STRING,
7569 MONO_AOT_OPTION_STATE_ESCAPE,
7572 GPtrArray *args = g_ptr_array_new ();
7573 enum MonoAotOptionState state = MONO_AOT_OPTION_STATE_DEFAULT;
7574 gchar const *opt_start = aot_options;
7575 gboolean end_of_string = FALSE;
7576 gchar cur;
7578 g_return_val_if_fail (aot_options != NULL, NULL);
7580 while ((cur = *aot_options) != '\0') {
7581 if (state == MONO_AOT_OPTION_STATE_ESCAPE)
7582 goto next;
7584 switch (cur) {
7585 case '"':
7586 // If we find a quote, then if we're in the default case then
7587 // it means we've found the start of a string, if not then it
7588 // means we've found the end of the string and should switch
7589 // back to the default case.
7590 switch (state) {
7591 case MONO_AOT_OPTION_STATE_DEFAULT:
7592 state = MONO_AOT_OPTION_STATE_STRING;
7593 break;
7594 case MONO_AOT_OPTION_STATE_STRING:
7595 state = MONO_AOT_OPTION_STATE_DEFAULT;
7596 break;
7597 case MONO_AOT_OPTION_STATE_ESCAPE:
7598 g_assert_not_reached ();
7599 break;
7601 break;
7602 case '\\':
7603 // If we've found an escaping operator, then this means we
7604 // should not process the next character if inside a string.
7605 if (state == MONO_AOT_OPTION_STATE_STRING)
7606 state = MONO_AOT_OPTION_STATE_ESCAPE;
7607 break;
7608 case ',':
7609 // If we're in the default state then this means we've found
7610 // an option, store it for later processing.
7611 if (state == MONO_AOT_OPTION_STATE_DEFAULT)
7612 goto new_opt;
7613 break;
7616 next:
7617 aot_options++;
7618 restart:
7619 // If the next character is end of string, then process the last option.
7620 if (*(aot_options) == '\0') {
7621 end_of_string = TRUE;
7622 goto new_opt;
7624 continue;
7626 new_opt:
7627 ptr_array_add_range_if_nonempty (args, opt_start, aot_options);
7628 opt_start = ++aot_options;
7629 if (end_of_string)
7630 break;
7631 goto restart; // Check for null and continue loop
7634 return args;
7637 static void
7638 mono_aot_parse_options (const char *aot_options, MonoAotOptions *opts)
7640 GPtrArray* args;
7642 args = mono_aot_split_options (aot_options ? aot_options : "");
7643 for (int i = 0; i < args->len; ++i) {
7644 const char *arg = (const char *)g_ptr_array_index (args, i);
7646 if (str_begins_with (arg, "outfile=")) {
7647 opts->outfile = g_strdup (arg + strlen ("outfile="));
7648 } else if (str_begins_with (arg, "llvm-outfile=")) {
7649 opts->llvm_outfile = g_strdup (arg + strlen ("llvm-outfile="));
7650 } else if (str_begins_with (arg, "temp-path=")) {
7651 opts->temp_path = clean_path (g_strdup (arg + strlen ("temp-path=")));
7652 } else if (str_begins_with (arg, "save-temps")) {
7653 opts->save_temps = TRUE;
7654 } else if (str_begins_with (arg, "keep-temps")) {
7655 opts->save_temps = TRUE;
7656 } else if (str_begins_with (arg, "write-symbols")) {
7657 opts->write_symbols = TRUE;
7658 } else if (str_begins_with (arg, "no-write-symbols")) {
7659 opts->write_symbols = FALSE;
7660 // Intentionally undocumented -- one-off experiment
7661 } else if (str_begins_with (arg, "metadata-only")) {
7662 opts->metadata_only = TRUE;
7663 } else if (str_begins_with (arg, "bind-to-runtime-version")) {
7664 opts->bind_to_runtime_version = TRUE;
7665 } else if (str_begins_with (arg, "full")) {
7666 opts->mode = MONO_AOT_MODE_FULL;
7667 } else if (str_begins_with (arg, "hybrid")) {
7668 opts->mode = MONO_AOT_MODE_HYBRID;
7669 } else if (str_begins_with (arg, "interp")) {
7670 opts->interp = TRUE;
7671 } else if (str_begins_with (arg, "threads=")) {
7672 opts->nthreads = atoi (arg + strlen ("threads="));
7673 } else if (str_begins_with (arg, "static")) {
7674 opts->static_link = TRUE;
7675 opts->no_dlsym = TRUE;
7676 } else if (str_begins_with (arg, "asmonly")) {
7677 opts->asm_only = TRUE;
7678 } else if (str_begins_with (arg, "asmwriter")) {
7679 opts->asm_writer = TRUE;
7680 } else if (str_begins_with (arg, "nodebug")) {
7681 opts->nodebug = TRUE;
7682 } else if (str_begins_with (arg, "dwarfdebug")) {
7683 opts->dwarf_debug = TRUE;
7684 // Intentionally undocumented -- No one remembers what this does. It appears to be ARM-only
7685 } else if (str_begins_with (arg, "nopagetrampolines")) {
7686 opts->use_trampolines_page = FALSE;
7687 } else if (str_begins_with (arg, "ntrampolines=")) {
7688 opts->ntrampolines = atoi (arg + strlen ("ntrampolines="));
7689 } else if (str_begins_with (arg, "nrgctx-trampolines=")) {
7690 opts->nrgctx_trampolines = atoi (arg + strlen ("nrgctx-trampolines="));
7691 } else if (str_begins_with (arg, "nrgctx-fetch-trampolines=")) {
7692 opts->nrgctx_fetch_trampolines = atoi (arg + strlen ("nrgctx-fetch-trampolines="));
7693 } else if (str_begins_with (arg, "nimt-trampolines=")) {
7694 opts->nimt_trampolines = atoi (arg + strlen ("nimt-trampolines="));
7695 } else if (str_begins_with (arg, "ngsharedvt-trampolines=")) {
7696 opts->ngsharedvt_arg_trampolines = atoi (arg + strlen ("ngsharedvt-trampolines="));
7697 } else if (str_begins_with (arg, "nftnptr-arg-trampolines=")) {
7698 opts->nftnptr_arg_trampolines = atoi (arg + strlen ("nftnptr-arg-trampolines="));
7699 } else if (str_begins_with (arg, "nunbox-arbitrary-trampolines=")) {
7700 opts->nunbox_arbitrary_trampolines = atoi (arg + strlen ("unbox-arbitrary-trampolines="));
7701 } else if (str_begins_with (arg, "tool-prefix=")) {
7702 opts->tool_prefix = g_strdup (arg + strlen ("tool-prefix="));
7703 } else if (str_begins_with (arg, "ld-flags=")) {
7704 opts->ld_flags = g_strdup (arg + strlen ("ld-flags="));
7705 } else if (str_begins_with (arg, "soft-debug")) {
7706 opts->soft_debug = TRUE;
7707 // Intentionally undocumented x2-- deprecated
7708 } else if (str_begins_with (arg, "gen-seq-points-file=")) {
7709 fprintf (stderr, "Mono Warning: aot option gen-seq-points-file= is deprecated.\n");
7710 } else if (str_begins_with (arg, "gen-seq-points-file")) {
7711 fprintf (stderr, "Mono Warning: aot option gen-seq-points-file is deprecated.\n");
7712 } else if (str_begins_with (arg, "msym-dir=")) {
7713 mini_debug_options.no_seq_points_compact_data = FALSE;
7714 opts->gen_msym_dir = TRUE;
7715 opts->gen_msym_dir_path = g_strdup (arg + strlen ("msym_dir="));;
7716 } else if (str_begins_with (arg, "direct-pinvoke")) {
7717 opts->direct_pinvoke = TRUE;
7718 } else if (str_begins_with (arg, "direct-icalls")) {
7719 opts->direct_icalls = TRUE;
7720 } else if (str_begins_with (arg, "no-direct-calls")) {
7721 opts->no_direct_calls = TRUE;
7722 } else if (str_begins_with (arg, "print-skipped")) {
7723 opts->print_skipped_methods = TRUE;
7724 } else if (str_begins_with (arg, "stats")) {
7725 opts->stats = TRUE;
7726 // Intentionally undocumented-- has no known function other than to debug the compiler
7727 } else if (str_begins_with (arg, "no-instances")) {
7728 opts->no_instances = TRUE;
7729 // Intentionally undocumented x4-- Used for internal debugging of compiler
7730 } else if (str_begins_with (arg, "log-generics")) {
7731 opts->log_generics = TRUE;
7732 } else if (str_begins_with (arg, "log-instances=")) {
7733 opts->log_instances = TRUE;
7734 opts->instances_logfile_path = g_strdup (arg + strlen ("log-instances="));
7735 } else if (str_begins_with (arg, "log-instances")) {
7736 opts->log_instances = TRUE;
7737 } else if (str_begins_with (arg, "internal-logfile=")) {
7738 opts->logfile = g_strdup (arg + strlen ("internal-logfile="));
7739 } else if (str_begins_with (arg, "dedup-skip")) {
7740 opts->dedup = TRUE;
7741 } else if (str_begins_with (arg, "dedup-include=")) {
7742 opts->dedup_include = g_strdup (arg + strlen ("dedup-include="));
7743 } else if (str_begins_with (arg, "mtriple=")) {
7744 opts->mtriple = g_strdup (arg + strlen ("mtriple="));
7745 } else if (str_begins_with (arg, "llvm-path=")) {
7746 opts->llvm_path = clean_path (g_strdup (arg + strlen ("llvm-path=")));
7747 } else if (!strcmp (arg, "try-llvm")) {
7748 // If we can load LLVM, use it
7749 // Note: if you call this function from anywhere but mono_compile_assembly,
7750 // this will only set the try_llvm attribute and not do the probing / set the
7751 // attribute.
7752 opts->try_llvm = TRUE;
7753 } else if (!strcmp (arg, "llvm")) {
7754 opts->llvm = TRUE;
7755 } else if (str_begins_with (arg, "readonly-value=")) {
7756 add_readonly_value (opts, arg + strlen ("readonly-value="));
7757 } else if (str_begins_with (arg, "info")) {
7758 printf ("AOT target setup: %s.\n", AOT_TARGET_STR);
7759 exit (0);
7760 // Intentionally undocumented: Used for precise stack maps, which are not available yet
7761 } else if (str_begins_with (arg, "gc-maps")) {
7762 mini_gc_enable_gc_maps_for_aot ();
7763 // Intentionally undocumented: Used for internal debugging
7764 } else if (str_begins_with (arg, "dump")) {
7765 opts->dump_json = TRUE;
7766 } else if (str_begins_with (arg, "llvmonly")) {
7767 opts->mode = MONO_AOT_MODE_FULL;
7768 opts->llvm = TRUE;
7769 opts->llvm_only = TRUE;
7770 } else if (str_begins_with (arg, "data-outfile=")) {
7771 opts->data_outfile = g_strdup (arg + strlen ("data-outfile="));
7772 } else if (str_begins_with (arg, "profile=")) {
7773 opts->profile_files = g_list_append (opts->profile_files, g_strdup (arg + strlen ("profile=")));
7774 } else if (!strcmp (arg, "profile-only")) {
7775 opts->profile_only = TRUE;
7776 } else if (!strcmp (arg, "verbose")) {
7777 opts->verbose = TRUE;
7778 } else if (str_begins_with (arg, "llvmopts=")){
7779 opts->llvm_opts = g_strdup (arg + strlen ("llvmopts="));
7780 } else if (str_begins_with (arg, "llvmllc=")){
7781 opts->llvm_llc = g_strdup (arg + strlen ("llvmllc="));
7782 } else if (!strcmp (arg, "deterministic")) {
7783 opts->deterministic = TRUE;
7784 } else if (!strcmp (arg, "no-opt")) {
7785 opts->no_opt = TRUE;
7786 } else if (str_begins_with (arg, "clangxx=")) {
7787 opts->clangxx = g_strdup (arg + strlen ("clangxx="));;
7788 } else if (str_begins_with (arg, "help") || str_begins_with (arg, "?")) {
7789 printf ("Supported options for --aot:\n");
7790 printf (" asmonly\n");
7791 printf (" bind-to-runtime-version\n");
7792 printf (" bitcode\n");
7793 printf (" data-outfile=\n");
7794 printf (" direct-icalls\n");
7795 printf (" direct-pinvoke\n");
7796 printf (" dwarfdebug\n");
7797 printf (" full\n");
7798 printf (" hybrid\n");
7799 printf (" info\n");
7800 printf (" keep-temps\n");
7801 printf (" llvm\n");
7802 printf (" llvmonly\n");
7803 printf (" llvm-outfile=\n");
7804 printf (" llvm-path=\n");
7805 printf (" msym-dir=\n");
7806 printf (" mtriple\n");
7807 printf (" nimt-trampolines=\n");
7808 printf (" nodebug\n");
7809 printf (" no-direct-calls\n");
7810 printf (" no-write-symbols\n");
7811 printf (" nrgctx-trampolines=\n");
7812 printf (" nrgctx-fetch-trampolines=\n");
7813 printf (" ngsharedvt-trampolines=\n");
7814 printf (" nftnptr-arg-trampolines=\n");
7815 printf (" nunbox-arbitrary-trampolines=\n");
7816 printf (" ntrampolines=\n");
7817 printf (" outfile=\n");
7818 printf (" profile=\n");
7819 printf (" profile-only\n");
7820 printf (" print-skipped-methods\n");
7821 printf (" readonly-value=\n");
7822 printf (" save-temps\n");
7823 printf (" soft-debug\n");
7824 printf (" static\n");
7825 printf (" stats\n");
7826 printf (" temp-path=\n");
7827 printf (" tool-prefix=\n");
7828 printf (" threads=\n");
7829 printf (" write-symbols\n");
7830 printf (" verbose\n");
7831 printf (" no-opt\n");
7832 printf (" llvmopts=\n");
7833 printf (" llvmllc=\n");
7834 printf (" clangxx=\n");
7835 printf (" help/?\n");
7836 exit (0);
7837 } else {
7838 fprintf (stderr, "AOT : Unknown argument '%s'.\n", arg);
7839 exit (1);
7842 g_free ((gpointer) arg);
7845 if (opts->use_trampolines_page) {
7846 opts->ntrampolines = 0;
7847 opts->nrgctx_trampolines = 0;
7848 opts->nimt_trampolines = 0;
7849 opts->ngsharedvt_arg_trampolines = 0;
7850 opts->nftnptr_arg_trampolines = 0;
7851 opts->nunbox_arbitrary_trampolines = 0;
7854 g_ptr_array_free (args, /*free_seg=*/TRUE);
7857 static void
7858 add_token_info_hash (gpointer key, gpointer value, gpointer user_data)
7860 MonoMethod *method = (MonoMethod*)key;
7861 MonoJumpInfoToken *ji = (MonoJumpInfoToken*)value;
7862 MonoAotCompile *acfg = (MonoAotCompile *)user_data;
7863 MonoJumpInfoToken *new_ji;
7865 new_ji = (MonoJumpInfoToken *)mono_mempool_alloc0 (acfg->mempool, sizeof (MonoJumpInfoToken));
7866 new_ji->image = ji->image;
7867 new_ji->token = ji->token;
7868 g_hash_table_insert (acfg->token_info_hash, method, new_ji);
7871 static gboolean
7872 can_encode_class (MonoAotCompile *acfg, MonoClass *klass)
7874 if (m_class_get_type_token (klass))
7875 return TRUE;
7876 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))
7877 return TRUE;
7878 if (m_class_get_rank (klass))
7879 return can_encode_class (acfg, m_class_get_element_class (klass));
7880 return FALSE;
7883 static gboolean
7884 can_encode_method (MonoAotCompile *acfg, MonoMethod *method)
7886 if (method->wrapper_type) {
7887 switch (method->wrapper_type) {
7888 case MONO_WRAPPER_NONE:
7889 case MONO_WRAPPER_REMOTING_INVOKE_WITH_CHECK:
7890 case MONO_WRAPPER_XDOMAIN_INVOKE:
7891 case MONO_WRAPPER_STFLD:
7892 case MONO_WRAPPER_LDFLD:
7893 case MONO_WRAPPER_LDFLDA:
7894 case MONO_WRAPPER_STELEMREF:
7895 case MONO_WRAPPER_PROXY_ISINST:
7896 case MONO_WRAPPER_ALLOC:
7897 case MONO_WRAPPER_REMOTING_INVOKE:
7898 case MONO_WRAPPER_OTHER:
7899 case MONO_WRAPPER_WRITE_BARRIER:
7900 case MONO_WRAPPER_DELEGATE_INVOKE:
7901 case MONO_WRAPPER_DELEGATE_BEGIN_INVOKE:
7902 case MONO_WRAPPER_DELEGATE_END_INVOKE:
7903 case MONO_WRAPPER_SYNCHRONIZED:
7904 case MONO_WRAPPER_MANAGED_TO_NATIVE:
7905 break;
7906 case MONO_WRAPPER_MANAGED_TO_MANAGED:
7907 case MONO_WRAPPER_CASTCLASS: {
7908 WrapperInfo *info = mono_marshal_get_wrapper_info (method);
7910 if (info)
7911 return TRUE;
7912 else
7913 return FALSE;
7914 break;
7916 default:
7917 //printf ("Skip (wrapper call): %d -> %s\n", patch_info->type, mono_method_full_name (patch_info->data.method, TRUE));
7918 return FALSE;
7920 } else {
7921 if (!method->token) {
7922 /* The method is part of a constructed type like Int[,].Set (). */
7923 if (!g_hash_table_lookup (acfg->token_info_hash, method)) {
7924 if (m_class_get_rank (method->klass))
7925 return TRUE;
7926 return FALSE;
7930 return TRUE;
7933 static gboolean
7934 can_encode_patch (MonoAotCompile *acfg, MonoJumpInfo *patch_info)
7936 switch (patch_info->type) {
7937 case MONO_PATCH_INFO_METHOD:
7938 case MONO_PATCH_INFO_METHOD_FTNDESC:
7939 case MONO_PATCH_INFO_METHODCONST:
7940 case MONO_PATCH_INFO_METHOD_CODE_SLOT: {
7941 MonoMethod *method = patch_info->data.method;
7943 return can_encode_method (acfg, method);
7945 case MONO_PATCH_INFO_VTABLE:
7946 case MONO_PATCH_INFO_CLASS:
7947 case MONO_PATCH_INFO_IID:
7948 case MONO_PATCH_INFO_ADJUSTED_IID:
7949 if (!can_encode_class (acfg, patch_info->data.klass)) {
7950 //printf ("Skip: %s\n", mono_type_full_name (m_class_get_byval_arg (patch_info->data.klass)));
7951 return FALSE;
7953 break;
7954 case MONO_PATCH_INFO_DELEGATE_TRAMPOLINE: {
7955 if (!can_encode_class (acfg, patch_info->data.del_tramp->klass)) {
7956 //printf ("Skip: %s\n", mono_type_full_name (m_class_get_byval_arg (patch_info->data.klass)));
7957 return FALSE;
7959 break;
7961 case MONO_PATCH_INFO_RGCTX_FETCH:
7962 case MONO_PATCH_INFO_RGCTX_SLOT_INDEX: {
7963 MonoJumpInfoRgctxEntry *entry = patch_info->data.rgctx_entry;
7965 if (!can_encode_method (acfg, entry->method))
7966 return FALSE;
7967 if (!can_encode_patch (acfg, entry->data))
7968 return FALSE;
7969 break;
7971 default:
7972 break;
7975 return TRUE;
7978 static gboolean
7979 is_concrete_type (MonoType *t)
7981 MonoClass *klass;
7982 int i;
7984 if (t->type == MONO_TYPE_VAR || t->type == MONO_TYPE_MVAR)
7985 return FALSE;
7986 if (t->type == MONO_TYPE_GENERICINST) {
7987 MonoGenericContext *orig_ctx;
7988 MonoGenericInst *inst;
7989 MonoType *arg;
7991 if (!MONO_TYPE_ISSTRUCT (t))
7992 return TRUE;
7993 klass = mono_class_from_mono_type_internal (t);
7994 orig_ctx = &mono_class_get_generic_class (klass)->context;
7996 inst = orig_ctx->class_inst;
7997 if (inst) {
7998 for (i = 0; i < inst->type_argc; ++i) {
7999 arg = mini_get_underlying_type (inst->type_argv [i]);
8000 if (!is_concrete_type (arg))
8001 return FALSE;
8004 inst = orig_ctx->method_inst;
8005 if (inst) {
8006 for (i = 0; i < inst->type_argc; ++i) {
8007 arg = mini_get_underlying_type (inst->type_argv [i]);
8008 if (!is_concrete_type (arg))
8009 return FALSE;
8013 return TRUE;
8016 /* LOCKING: Assumes the loader lock is held */
8017 static void
8018 add_gsharedvt_wrappers (MonoAotCompile *acfg, MonoMethodSignature *sig, gboolean gsharedvt_in, gboolean gsharedvt_out, gboolean interp_in)
8020 MonoMethod *wrapper;
8021 gboolean concrete = TRUE;
8022 gboolean add_in = gsharedvt_in;
8023 gboolean add_out = gsharedvt_out;
8025 if (gsharedvt_in && g_hash_table_lookup (acfg->gsharedvt_in_signatures, sig))
8026 add_in = FALSE;
8027 if (gsharedvt_out && g_hash_table_lookup (acfg->gsharedvt_out_signatures, sig))
8028 add_out = FALSE;
8030 if (!add_in && !add_out)
8031 return;
8033 if (mini_is_gsharedvt_variable_signature (sig))
8034 return;
8036 if (add_in)
8037 g_hash_table_insert (acfg->gsharedvt_in_signatures, sig, sig);
8038 if (add_out)
8039 g_hash_table_insert (acfg->gsharedvt_out_signatures, sig, sig);
8041 if (sig->has_type_parameters) {
8042 /* For signatures created during generic sharing, convert them to a concrete signature if possible */
8043 MonoMethodSignature *copy = mono_metadata_signature_dup (sig);
8044 int i;
8046 //printf ("%s\n", mono_signature_full_name (sig));
8048 if (sig->ret->byref)
8049 copy->ret = m_class_get_this_arg (mono_defaults.int_class);
8050 else
8051 copy->ret = mini_get_underlying_type (sig->ret);
8052 if (!is_concrete_type (copy->ret))
8053 concrete = FALSE;
8054 for (i = 0; i < sig->param_count; ++i) {
8055 if (sig->params [i]->byref) {
8056 MonoType *t = m_class_get_byval_arg (mono_class_from_mono_type_internal (sig->params [i]));
8057 t = mini_get_underlying_type (t);
8058 copy->params [i] = m_class_get_this_arg (mono_class_from_mono_type_internal (t));
8059 } else {
8060 copy->params [i] = mini_get_underlying_type (sig->params [i]);
8062 if (!is_concrete_type (copy->params [i]))
8063 concrete = FALSE;
8065 copy->has_type_parameters = 0;
8066 if (!concrete)
8067 return;
8068 sig = copy;
8071 //printf ("%s\n", mono_signature_full_name (sig));
8073 if (gsharedvt_in) {
8074 wrapper = mini_get_gsharedvt_in_sig_wrapper (sig);
8075 add_extra_method (acfg, wrapper);
8077 if (gsharedvt_out) {
8078 wrapper = mini_get_gsharedvt_out_sig_wrapper (sig);
8079 add_extra_method (acfg, wrapper);
8081 #ifndef MONO_ARCH_HAVE_INTERP_ENTRY_TRAMPOLINE
8082 if (interp_in) {
8083 wrapper = mini_get_interp_in_wrapper (sig);
8084 add_extra_method (acfg, wrapper);
8085 //printf ("X: %s\n", mono_method_full_name (wrapper, 1));
8087 #endif
8091 * compile_method:
8093 * AOT compile a given method.
8094 * This function might be called by multiple threads, so it must be thread-safe.
8096 static void
8097 compile_method (MonoAotCompile *acfg, MonoMethod *method)
8099 MonoCompile *cfg;
8100 MonoJumpInfo *patch_info;
8101 gboolean skip;
8102 int index, depth;
8103 MonoMethod *wrapped;
8104 GTimer *jit_timer;
8105 JitFlags flags;
8107 if (acfg->aot_opts.metadata_only)
8108 return;
8110 mono_acfg_lock (acfg);
8111 index = get_method_index (acfg, method);
8112 mono_acfg_unlock (acfg);
8114 /* fixme: maybe we can also precompile wrapper methods */
8115 if ((method->flags & METHOD_ATTRIBUTE_PINVOKE_IMPL) ||
8116 (method->iflags & METHOD_IMPL_ATTRIBUTE_RUNTIME) ||
8117 (method->flags & METHOD_ATTRIBUTE_ABSTRACT)) {
8118 //printf ("Skip (impossible): %s\n", mono_method_full_name (method, TRUE));
8119 return;
8122 if (method->iflags & METHOD_IMPL_ATTRIBUTE_INTERNAL_CALL)
8123 return;
8125 wrapped = mono_marshal_method_from_wrapper (method);
8126 if (wrapped && (wrapped->iflags & METHOD_IMPL_ATTRIBUTE_INTERNAL_CALL) && wrapped->is_generic)
8127 // FIXME: The wrapper should be generic too, but it is not
8128 return;
8130 if (method->wrapper_type == MONO_WRAPPER_COMINTEROP)
8131 return;
8133 if (acfg->aot_opts.profile_only && !method->is_inflated && !g_hash_table_lookup (acfg->profile_methods, method))
8134 return;
8136 if (method->is_generic || mono_class_is_gtd (method->klass))
8137 /* generic method which has no ref instantiation */
8138 return;
8140 mono_atomic_inc_i32 (&acfg->stats.mcount);
8142 #if 0
8143 if (method->is_generic || mono_class_is_gtd (method->klass)) {
8144 mono_atomic_inc_i32 (&acfg->stats.genericcount);
8145 return;
8147 #endif
8149 //acfg->aot_opts.print_skipped_methods = TRUE;
8152 * Since these methods are the only ones which are compiled with
8153 * AOT support, and they are not used by runtime startup/shutdown code,
8154 * the runtime will not see AOT methods during AOT compilation,so it
8155 * does not need to support them by creating a fake GOT etc.
8157 flags = JIT_FLAG_AOT;
8158 if (mono_aot_mode_is_full (&acfg->aot_opts))
8159 flags = (JitFlags)(flags | JIT_FLAG_FULL_AOT);
8160 if (acfg->llvm)
8161 flags = (JitFlags)(flags | JIT_FLAG_LLVM);
8162 if (acfg->aot_opts.llvm_only)
8163 flags = (JitFlags)(flags | JIT_FLAG_LLVM_ONLY | JIT_FLAG_EXPLICIT_NULL_CHECKS);
8164 if (acfg->aot_opts.no_direct_calls)
8165 flags = (JitFlags)(flags | JIT_FLAG_NO_DIRECT_ICALLS);
8166 if (acfg->aot_opts.direct_pinvoke)
8167 flags = (JitFlags)(flags | JIT_FLAG_DIRECT_PINVOKE);
8168 if (acfg->aot_opts.interp)
8169 flags = (JitFlags)(flags | JIT_FLAG_INTERP);
8171 jit_timer = mono_time_track_start ();
8172 cfg = mini_method_compile (method, acfg->opts, mono_get_root_domain (), flags, 0, index);
8173 mono_time_track_end (&mono_jit_stats.jit_time, jit_timer);
8175 if (cfg->exception_type == MONO_EXCEPTION_GENERIC_SHARING_FAILED) {
8176 if (acfg->aot_opts.print_skipped_methods)
8177 printf ("Skip (gshared failure): %s (%s)\n", mono_method_get_full_name (method), cfg->exception_message);
8178 mono_atomic_inc_i32 (&acfg->stats.genericcount);
8179 return;
8181 if (cfg->exception_type != MONO_EXCEPTION_NONE) {
8182 /* Some instances cannot be JITted due to constraints etc. */
8183 if (!method->is_inflated)
8184 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));
8185 /* Let the exception happen at runtime */
8186 return;
8189 if (cfg->disable_aot) {
8190 if (acfg->aot_opts.print_skipped_methods)
8191 printf ("Skip (disabled): %s\n", mono_method_get_full_name (method));
8192 mono_atomic_inc_i32 (&acfg->stats.ocount);
8193 return;
8195 cfg->method_index = index;
8197 /* Nullify patches which need no aot processing */
8198 for (patch_info = cfg->patch_info; patch_info; patch_info = patch_info->next) {
8199 switch (patch_info->type) {
8200 case MONO_PATCH_INFO_LABEL:
8201 case MONO_PATCH_INFO_BB:
8202 patch_info->type = MONO_PATCH_INFO_NONE;
8203 break;
8204 default:
8205 break;
8209 /* Collect method->token associations from the cfg */
8210 mono_acfg_lock (acfg);
8211 g_hash_table_foreach (cfg->token_info_hash, add_token_info_hash, acfg);
8212 mono_acfg_unlock (acfg);
8213 g_hash_table_destroy (cfg->token_info_hash);
8214 cfg->token_info_hash = NULL;
8217 * Check for absolute addresses.
8219 skip = FALSE;
8220 for (patch_info = cfg->patch_info; patch_info; patch_info = patch_info->next) {
8221 switch (patch_info->type) {
8222 case MONO_PATCH_INFO_ABS:
8223 /* unable to handle this */
8224 skip = TRUE;
8225 break;
8226 default:
8227 break;
8231 if (skip) {
8232 if (acfg->aot_opts.print_skipped_methods)
8233 printf ("Skip (abs call): %s\n", mono_method_get_full_name (method));
8234 mono_atomic_inc_i32 (&acfg->stats.abscount);
8235 return;
8238 /* Lock for the rest of the code */
8239 mono_acfg_lock (acfg);
8241 if (cfg->gsharedvt)
8242 acfg->stats.method_categories [METHOD_CAT_GSHAREDVT] ++;
8243 else if (cfg->gshared)
8244 acfg->stats.method_categories [METHOD_CAT_INST] ++;
8245 else if (cfg->method->wrapper_type)
8246 acfg->stats.method_categories [METHOD_CAT_WRAPPER] ++;
8247 else
8248 acfg->stats.method_categories [METHOD_CAT_NORMAL] ++;
8251 * Check for methods/klasses we can't encode.
8253 skip = FALSE;
8254 for (patch_info = cfg->patch_info; patch_info; patch_info = patch_info->next) {
8255 if (!can_encode_patch (acfg, patch_info))
8256 skip = TRUE;
8259 if (skip) {
8260 if (acfg->aot_opts.print_skipped_methods)
8261 printf ("Skip (patches): %s\n", mono_method_get_full_name (method));
8262 acfg->stats.ocount++;
8263 mono_acfg_unlock (acfg);
8264 return;
8267 if (!cfg->compile_llvm)
8268 acfg->has_jitted_code = TRUE;
8270 if (method->is_inflated && acfg->aot_opts.log_instances) {
8271 if (acfg->instances_logfile)
8272 fprintf (acfg->instances_logfile, "%s ### %d\n", mono_method_get_full_name (method), cfg->code_size);
8273 else
8274 printf ("%s ### %d\n", mono_method_get_full_name (method), cfg->code_size);
8277 /* Adds generic instances referenced by this method */
8279 * The depth is used to avoid infinite loops when generic virtual recursion is
8280 * encountered.
8282 depth = GPOINTER_TO_UINT (g_hash_table_lookup (acfg->method_depth, method));
8283 if (!acfg->aot_opts.no_instances && depth < 32 && (mono_aot_mode_is_full (&acfg->aot_opts) || mono_aot_mode_is_hybrid (&acfg->aot_opts))) {
8284 for (patch_info = cfg->patch_info; patch_info; patch_info = patch_info->next) {
8285 switch (patch_info->type) {
8286 case MONO_PATCH_INFO_RGCTX_FETCH:
8287 case MONO_PATCH_INFO_RGCTX_SLOT_INDEX:
8288 case MONO_PATCH_INFO_METHOD:
8289 case MONO_PATCH_INFO_METHOD_FTNDESC:
8290 case MONO_PATCH_INFO_METHOD_RGCTX: {
8291 MonoMethod *m = NULL;
8293 if (patch_info->type == MONO_PATCH_INFO_RGCTX_FETCH || patch_info->type == MONO_PATCH_INFO_RGCTX_SLOT_INDEX) {
8294 MonoJumpInfoRgctxEntry *e = patch_info->data.rgctx_entry;
8296 if (e->info_type == MONO_RGCTX_INFO_GENERIC_METHOD_CODE || e->info_type == MONO_RGCTX_INFO_METHOD_FTNDESC)
8297 m = e->data->data.method;
8298 } else {
8299 m = patch_info->data.method;
8302 if (!m)
8303 break;
8304 if (m->is_inflated && (mono_aot_mode_is_full (&acfg->aot_opts) || mono_aot_mode_is_hybrid (&acfg->aot_opts))) {
8305 if (!(mono_class_generic_sharing_enabled (m->klass) &&
8306 mono_method_is_generic_sharable_full (m, FALSE, FALSE, FALSE)) &&
8307 (!method_has_type_vars (m) || mono_method_is_generic_sharable_full (m, TRUE, TRUE, FALSE))) {
8308 if (m->iflags & METHOD_IMPL_ATTRIBUTE_INTERNAL_CALL) {
8309 if (mono_aot_mode_is_full (&acfg->aot_opts) && !method_has_type_vars (m))
8310 add_extra_method_with_depth (acfg, mono_marshal_get_native_wrapper (m, TRUE, TRUE), depth + 1);
8311 } else {
8312 add_extra_method_with_depth (acfg, m, depth + 1);
8313 add_types_from_method_header (acfg, m);
8316 add_generic_class_with_depth (acfg, m->klass, depth + 5, "method");
8318 if (m->wrapper_type == MONO_WRAPPER_MANAGED_TO_MANAGED) {
8319 WrapperInfo *info = mono_marshal_get_wrapper_info (m);
8321 if (info && info->subtype == WRAPPER_SUBTYPE_ELEMENT_ADDR)
8322 add_extra_method_with_depth (acfg, m, depth + 1);
8324 break;
8326 case MONO_PATCH_INFO_VTABLE: {
8327 MonoClass *klass = patch_info->data.klass;
8329 if (mono_class_is_ginst (klass) && !mini_class_is_generic_sharable (klass))
8330 add_generic_class_with_depth (acfg, klass, depth + 5, "vtable");
8331 break;
8333 case MONO_PATCH_INFO_SFLDA: {
8334 MonoClass *klass = patch_info->data.field->parent;
8336 /* The .cctor needs to run at runtime. */
8337 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))
8338 add_extra_method_with_depth (acfg, mono_class_get_cctor (klass), depth + 1);
8339 break;
8341 default:
8342 break;
8347 /* Determine whenever the method has GOT slots */
8348 for (patch_info = cfg->patch_info; patch_info; patch_info = patch_info->next) {
8349 switch (patch_info->type) {
8350 case MONO_PATCH_INFO_GOT_OFFSET:
8351 case MONO_PATCH_INFO_NONE:
8352 case MONO_PATCH_INFO_GC_CARD_TABLE_ADDR:
8353 case MONO_PATCH_INFO_GC_NURSERY_START:
8354 case MONO_PATCH_INFO_GC_NURSERY_BITS:
8355 break;
8356 case MONO_PATCH_INFO_IMAGE:
8357 /* The assembly is stored in GOT slot 0 */
8358 if (patch_info->data.image != acfg->image)
8359 cfg->has_got_slots = TRUE;
8360 break;
8361 default:
8362 if (!is_plt_patch (patch_info) || (cfg->compile_llvm && acfg->aot_opts.llvm_only))
8363 cfg->has_got_slots = TRUE;
8364 break;
8368 if (!cfg->has_got_slots)
8369 mono_atomic_inc_i32 (&acfg->stats.methods_without_got_slots);
8371 /* Add gsharedvt wrappers for signatures used by the method */
8372 if (acfg->aot_opts.llvm_only) {
8373 GSList *l;
8375 if (!cfg->method->wrapper_type || cfg->method->wrapper_type == MONO_WRAPPER_DELEGATE_INVOKE)
8376 /* These only need out wrappers */
8377 add_gsharedvt_wrappers (acfg, mono_method_signature_internal (cfg->method), FALSE, TRUE, FALSE);
8379 for (l = cfg->signatures; l; l = l->next) {
8380 MonoMethodSignature *sig = mono_metadata_signature_dup ((MonoMethodSignature*)l->data);
8382 /* These only need in wrappers */
8383 add_gsharedvt_wrappers (acfg, sig, TRUE, FALSE, FALSE);
8385 } else if (mono_aot_mode_is_full (&acfg->aot_opts) && mono_aot_mode_is_interp (&acfg->aot_opts)) {
8386 /* The interpreter uses these wrappers to call aot-ed code */
8387 if (!cfg->method->wrapper_type || cfg->method->wrapper_type == MONO_WRAPPER_DELEGATE_INVOKE)
8388 add_gsharedvt_wrappers (acfg, mono_method_signature_internal (cfg->method), FALSE, TRUE, TRUE);
8392 * FIXME: Instead of this mess, allocate the patches from the aot mempool.
8394 /* Make a copy of the patch info which is in the mempool */
8396 MonoJumpInfo *patches = NULL, *patches_end = NULL;
8398 for (patch_info = cfg->patch_info; patch_info; patch_info = patch_info->next) {
8399 MonoJumpInfo *new_patch_info = mono_patch_info_dup_mp (acfg->mempool, patch_info);
8401 if (!patches)
8402 patches = new_patch_info;
8403 else
8404 patches_end->next = new_patch_info;
8405 patches_end = new_patch_info;
8407 cfg->patch_info = patches;
8409 /* Make a copy of the unwind info */
8411 GSList *l, *unwind_ops;
8412 MonoUnwindOp *op;
8414 unwind_ops = NULL;
8415 for (l = cfg->unwind_ops; l; l = l->next) {
8416 op = (MonoUnwindOp *)mono_mempool_alloc (acfg->mempool, sizeof (MonoUnwindOp));
8417 memcpy (op, l->data, sizeof (MonoUnwindOp));
8418 unwind_ops = g_slist_prepend_mempool (acfg->mempool, unwind_ops, op);
8420 cfg->unwind_ops = g_slist_reverse (unwind_ops);
8422 /* Make a copy of the argument/local info */
8424 ERROR_DECL (error);
8425 MonoInst **args, **locals;
8426 MonoMethodSignature *sig;
8427 MonoMethodHeader *header;
8428 int i;
8430 sig = mono_method_signature_internal (method);
8431 args = (MonoInst **)mono_mempool_alloc (acfg->mempool, sizeof (MonoInst*) * (sig->param_count + sig->hasthis));
8432 for (i = 0; i < sig->param_count + sig->hasthis; ++i) {
8433 args [i] = (MonoInst *)mono_mempool_alloc (acfg->mempool, sizeof (MonoInst));
8434 memcpy (args [i], cfg->args [i], sizeof (MonoInst));
8436 cfg->args = args;
8438 header = mono_method_get_header_checked (method, error);
8439 mono_error_assert_ok (error); /* FIXME don't swallow the error */
8440 locals = (MonoInst **)mono_mempool_alloc (acfg->mempool, sizeof (MonoInst*) * header->num_locals);
8441 for (i = 0; i < header->num_locals; ++i) {
8442 locals [i] = (MonoInst *)mono_mempool_alloc (acfg->mempool, sizeof (MonoInst));
8443 memcpy (locals [i], cfg->locals [i], sizeof (MonoInst));
8445 mono_metadata_free_mh (header);
8446 cfg->locals = locals;
8449 /* Free some fields used by cfg to conserve memory */
8450 mono_empty_compile (cfg);
8452 //printf ("Compile: %s\n", mono_method_full_name (method, TRUE));
8454 while (index >= acfg->cfgs_size) {
8455 MonoCompile **new_cfgs;
8456 int new_size;
8458 new_size = acfg->cfgs_size * 2;
8459 new_cfgs = g_new0 (MonoCompile*, new_size);
8460 memcpy (new_cfgs, acfg->cfgs, sizeof (MonoCompile*) * acfg->cfgs_size);
8461 g_free (acfg->cfgs);
8462 acfg->cfgs = new_cfgs;
8463 acfg->cfgs_size = new_size;
8465 acfg->cfgs [index] = cfg;
8467 g_hash_table_insert (acfg->method_to_cfg, cfg->orig_method, cfg);
8469 /* Update global stats while holding a lock. */
8470 mono_update_jit_stats (cfg);
8473 if (cfg->orig_method->wrapper_type)
8474 g_ptr_array_add (acfg->extra_methods, cfg->orig_method);
8477 mono_acfg_unlock (acfg);
8479 mono_atomic_inc_i32 (&acfg->stats.ccount);
8482 static mono_thread_start_return_t WINAPI
8483 compile_thread_main (gpointer user_data)
8485 MonoAotCompile *acfg = ((MonoAotCompile **)user_data) [0];
8486 GPtrArray *methods = ((GPtrArray **)user_data) [1];
8487 int i;
8489 ERROR_DECL (error);
8490 MonoInternalThread *internal = mono_thread_internal_current ();
8491 MonoString *str = mono_string_new_checked (mono_domain_get (), "AOT compiler", error);
8492 mono_error_assert_ok (error);
8493 mono_thread_set_name_internal (internal, str, TRUE, FALSE, error);
8494 mono_error_assert_ok (error);
8496 for (i = 0; i < methods->len; ++i)
8497 compile_method (acfg, (MonoMethod *)g_ptr_array_index (methods, i));
8499 return 0;
8502 /* Used by the LLVM backend */
8503 guint32
8504 mono_aot_get_got_offset (MonoJumpInfo *ji)
8506 return get_got_offset (llvm_acfg, TRUE, ji);
8510 * mono_aot_is_shared_got_offset:
8512 * Return whenever OFFSET refers to a GOT slot which is preinitialized
8513 * when the AOT image is loaded.
8515 gboolean
8516 mono_aot_is_shared_got_offset (int offset)
8518 return offset < llvm_acfg->nshared_got_entries;
8521 char*
8522 mono_aot_get_method_name (MonoCompile *cfg)
8524 MonoMethod *method = cfg->orig_method;
8526 /* Use the mangled name if possible */
8527 if (method->wrapper_type == MONO_WRAPPER_OTHER) {
8528 WrapperInfo *info = mono_marshal_get_wrapper_info (method);
8529 if (info->subtype == WRAPPER_SUBTYPE_GSHAREDVT_IN_SIG || info->subtype == WRAPPER_SUBTYPE_GSHAREDVT_OUT_SIG)
8530 return mono_aot_get_mangled_method_name (method);
8533 if (llvm_acfg->aot_opts.static_link)
8534 /* Include the assembly name too to avoid duplicate symbol errors */
8535 return g_strdup_printf ("%s_%s", llvm_acfg->assembly_name_sym, get_debug_sym (cfg->orig_method, "", llvm_acfg->method_label_hash));
8536 else
8537 return get_debug_sym (cfg->orig_method, "", llvm_acfg->method_label_hash);
8540 static gboolean
8541 append_mangled_type (GString *s, MonoType *t)
8543 if (t->byref)
8544 g_string_append_printf (s, "b");
8545 switch (t->type) {
8546 case MONO_TYPE_VOID:
8547 g_string_append_printf (s, "void");
8548 break;
8549 case MONO_TYPE_I1:
8550 g_string_append_printf (s, "i1");
8551 break;
8552 case MONO_TYPE_U1:
8553 g_string_append_printf (s, "u1");
8554 break;
8555 case MONO_TYPE_I2:
8556 g_string_append_printf (s, "i2");
8557 break;
8558 case MONO_TYPE_U2:
8559 g_string_append_printf (s, "u2");
8560 break;
8561 case MONO_TYPE_I4:
8562 g_string_append_printf (s, "i4");
8563 break;
8564 case MONO_TYPE_U4:
8565 g_string_append_printf (s, "u4");
8566 break;
8567 case MONO_TYPE_I8:
8568 g_string_append_printf (s, "i8");
8569 break;
8570 case MONO_TYPE_U8:
8571 g_string_append_printf (s, "u8");
8572 break;
8573 case MONO_TYPE_I:
8574 g_string_append_printf (s, "ii");
8575 break;
8576 case MONO_TYPE_U:
8577 g_string_append_printf (s, "ui");
8578 break;
8579 case MONO_TYPE_R4:
8580 g_string_append_printf (s, "fl");
8581 break;
8582 case MONO_TYPE_R8:
8583 g_string_append_printf (s, "do");
8584 break;
8585 case MONO_TYPE_OBJECT:
8586 g_string_append_printf (s, "obj");
8587 break;
8588 default: {
8589 char *fullname = mono_type_full_name (t);
8590 GString *temp;
8591 char *temps;
8592 int i, len;
8595 * Have to create a mangled name which is:
8596 * - a valid symbol
8597 * - unique
8599 temp = g_string_new ("");
8600 len = strlen (fullname);
8601 for (i = 0; i < len; ++i) {
8602 char c = fullname [i];
8603 if (isalnum (c)) {
8604 g_string_append_c (temp, c);
8605 } else if (c == '_') {
8606 g_string_append_c (temp, '_');
8607 g_string_append_c (temp, '_');
8608 } else {
8609 g_string_append_c (temp, '_');
8610 g_string_append_printf (temp, "%x", (int)c);
8613 temps = g_string_free (temp, FALSE);
8614 /* Include the length to avoid different length type names aliasing each other */
8615 g_string_append_printf (s, "cl%x_%s_", (int)strlen (temps), temps);
8616 g_free (temps);
8619 if (t->attrs)
8620 g_string_append_printf (s, "_attrs_%d", t->attrs);
8621 return TRUE;
8624 static gboolean
8625 append_mangled_signature (GString *s, MonoMethodSignature *sig)
8627 int i;
8628 gboolean supported;
8630 if (sig->pinvoke)
8631 g_string_append_printf (s, "pinvoke_");
8632 supported = append_mangled_type (s, sig->ret);
8633 if (!supported)
8634 return FALSE;
8635 g_string_append_printf (s, "_");
8636 if (sig->hasthis)
8637 g_string_append_printf (s, "this_");
8638 for (i = 0; i < sig->param_count; ++i) {
8639 supported = append_mangled_type (s, sig->params [i]);
8640 if (!supported)
8641 return FALSE;
8644 return TRUE;
8647 static void
8648 append_mangled_wrapper_type (GString *s, guint32 wrapper_type)
8650 const char *label;
8652 switch (wrapper_type) {
8653 case MONO_WRAPPER_REMOTING_INVOKE:
8654 label = "remoting_invoke";
8655 break;
8656 case MONO_WRAPPER_REMOTING_INVOKE_WITH_CHECK:
8657 label = "remoting_invoke_check";
8658 break;
8659 case MONO_WRAPPER_XDOMAIN_INVOKE:
8660 label = "remoting_invoke_xdomain";
8661 break;
8662 case MONO_WRAPPER_PROXY_ISINST:
8663 label = "proxy_isinst";
8664 break;
8665 case MONO_WRAPPER_LDFLD:
8666 label = "ldfld";
8667 break;
8668 case MONO_WRAPPER_LDFLDA:
8669 label = "ldflda";
8670 break;
8671 case MONO_WRAPPER_STFLD:
8672 label = "stfld";
8673 break;
8674 case MONO_WRAPPER_ALLOC:
8675 label = "alloc";
8676 break;
8677 case MONO_WRAPPER_WRITE_BARRIER:
8678 label = "write_barrier";
8679 break;
8680 case MONO_WRAPPER_STELEMREF:
8681 label = "stelemref";
8682 break;
8683 case MONO_WRAPPER_OTHER:
8684 label = "unknown";
8685 break;
8686 case MONO_WRAPPER_MANAGED_TO_NATIVE:
8687 label = "man2native";
8688 break;
8689 case MONO_WRAPPER_SYNCHRONIZED:
8690 label = "synch";
8691 break;
8692 case MONO_WRAPPER_MANAGED_TO_MANAGED:
8693 label = "man2man";
8694 break;
8695 case MONO_WRAPPER_CASTCLASS:
8696 label = "castclass";
8697 break;
8698 case MONO_WRAPPER_RUNTIME_INVOKE:
8699 label = "run_invoke";
8700 break;
8701 case MONO_WRAPPER_DELEGATE_INVOKE:
8702 label = "del_inv";
8703 break;
8704 case MONO_WRAPPER_DELEGATE_BEGIN_INVOKE:
8705 label = "del_beg_inv";
8706 break;
8707 case MONO_WRAPPER_DELEGATE_END_INVOKE:
8708 label = "del_end_inv";
8709 break;
8710 case MONO_WRAPPER_NATIVE_TO_MANAGED:
8711 label = "native2man";
8712 break;
8713 default:
8714 g_assert_not_reached ();
8717 g_string_append_printf (s, "%s_", label);
8720 static void
8721 append_mangled_wrapper_subtype (GString *s, WrapperSubtype subtype)
8723 const char *label;
8725 switch (subtype)
8727 case WRAPPER_SUBTYPE_NONE:
8728 return;
8729 case WRAPPER_SUBTYPE_ELEMENT_ADDR:
8730 label = "elem_addr";
8731 break;
8732 case WRAPPER_SUBTYPE_STRING_CTOR:
8733 label = "str_ctor";
8734 break;
8735 case WRAPPER_SUBTYPE_VIRTUAL_STELEMREF:
8736 label = "virt_stelem";
8737 break;
8738 case WRAPPER_SUBTYPE_FAST_MONITOR_ENTER:
8739 label = "fast_mon_enter";
8740 break;
8741 case WRAPPER_SUBTYPE_FAST_MONITOR_ENTER_V4:
8742 label = "fast_mon_enter_4";
8743 break;
8744 case WRAPPER_SUBTYPE_FAST_MONITOR_EXIT:
8745 label = "fast_monitor_exit";
8746 break;
8747 case WRAPPER_SUBTYPE_PTR_TO_STRUCTURE:
8748 label = "ptr2struct";
8749 break;
8750 case WRAPPER_SUBTYPE_STRUCTURE_TO_PTR:
8751 label = "struct2ptr";
8752 break;
8753 case WRAPPER_SUBTYPE_CASTCLASS_WITH_CACHE:
8754 label = "castclass_w_cache";
8755 break;
8756 case WRAPPER_SUBTYPE_ISINST_WITH_CACHE:
8757 label = "isinst_w_cache";
8758 break;
8759 case WRAPPER_SUBTYPE_RUNTIME_INVOKE_NORMAL:
8760 label = "run_inv_norm";
8761 break;
8762 case WRAPPER_SUBTYPE_RUNTIME_INVOKE_DYNAMIC:
8763 label = "run_inv_dyn";
8764 break;
8765 case WRAPPER_SUBTYPE_RUNTIME_INVOKE_DIRECT:
8766 label = "run_inv_dir";
8767 break;
8768 case WRAPPER_SUBTYPE_RUNTIME_INVOKE_VIRTUAL:
8769 label = "run_inv_vir";
8770 break;
8771 case WRAPPER_SUBTYPE_ICALL_WRAPPER:
8772 label = "icall";
8773 break;
8774 case WRAPPER_SUBTYPE_NATIVE_FUNC_AOT:
8775 label = "native_func_aot";
8776 break;
8777 case WRAPPER_SUBTYPE_PINVOKE:
8778 label = "pinvoke";
8779 break;
8780 case WRAPPER_SUBTYPE_SYNCHRONIZED_INNER:
8781 label = "synch_inner";
8782 break;
8783 case WRAPPER_SUBTYPE_GSHAREDVT_IN:
8784 label = "gshared_in";
8785 break;
8786 case WRAPPER_SUBTYPE_GSHAREDVT_OUT:
8787 label = "gshared_out";
8788 break;
8789 case WRAPPER_SUBTYPE_ARRAY_ACCESSOR:
8790 label = "array_acc";
8791 break;
8792 case WRAPPER_SUBTYPE_GENERIC_ARRAY_HELPER:
8793 label = "generic_arry_help";
8794 break;
8795 case WRAPPER_SUBTYPE_DELEGATE_INVOKE_VIRTUAL:
8796 label = "del_inv_virt";
8797 break;
8798 case WRAPPER_SUBTYPE_DELEGATE_INVOKE_BOUND:
8799 label = "del_inv_bound";
8800 break;
8801 case WRAPPER_SUBTYPE_INTERP_IN:
8802 label = "interp_in";
8803 break;
8804 case WRAPPER_SUBTYPE_INTERP_LMF:
8805 label = "interp_lmf";
8806 break;
8807 case WRAPPER_SUBTYPE_GSHAREDVT_IN_SIG:
8808 label = "gsharedvt_in_sig";
8809 break;
8810 case WRAPPER_SUBTYPE_GSHAREDVT_OUT_SIG:
8811 label = "gsharedvt_out_sig";
8812 break;
8813 default:
8814 g_assert_not_reached ();
8817 g_string_append_printf (s, "%s_", label);
8820 static char *
8821 sanitize_mangled_string (const char *input)
8823 GString *s = g_string_new ("");
8825 for (int i=0; input [i] != '\0'; i++) {
8826 char c = input [i];
8827 switch (c) {
8828 case '.':
8829 g_string_append (s, "_dot_");
8830 break;
8831 case ' ':
8832 g_string_append (s, "_");
8833 break;
8834 case '`':
8835 g_string_append (s, "_bt_");
8836 break;
8837 case '<':
8838 g_string_append (s, "_le_");
8839 break;
8840 case '>':
8841 g_string_append (s, "_gt_");
8842 break;
8843 case '/':
8844 g_string_append (s, "_sl_");
8845 break;
8846 case '[':
8847 g_string_append (s, "_lbrack_");
8848 break;
8849 case ']':
8850 g_string_append (s, "_rbrack_");
8851 break;
8852 case '(':
8853 g_string_append (s, "_lparen_");
8854 break;
8855 case '-':
8856 g_string_append (s, "_dash_");
8857 break;
8858 case ')':
8859 g_string_append (s, "_rparen_");
8860 break;
8861 case ',':
8862 g_string_append (s, "_comma_");
8863 break;
8864 case ':':
8865 g_string_append (s, "_colon_");
8866 break;
8867 default:
8868 g_string_append_c (s, c);
8872 return g_string_free (s, FALSE);
8875 static gboolean
8876 append_mangled_klass (GString *s, MonoClass *klass)
8878 char *klass_desc = mono_class_full_name (klass);
8879 g_string_append_printf (s, "_%s_%s_", m_class_get_name_space (klass), klass_desc);
8880 g_free (klass_desc);
8882 // Success
8883 return TRUE;
8886 static gboolean
8887 append_mangled_method (GString *s, MonoMethod *method);
8889 static gboolean
8890 append_mangled_wrapper (GString *s, MonoMethod *method)
8892 gboolean success = TRUE;
8893 gboolean append_sig = TRUE;
8894 WrapperInfo *info = mono_marshal_get_wrapper_info (method);
8895 g_string_append_printf (s, "wrapper_");
8896 /* Most wrappers are in mscorlib */
8897 if (m_class_get_image (method->klass) != mono_get_corlib ())
8898 g_string_append_printf (s, "%s_", m_class_get_image (method->klass)->assembly->aname.name);
8900 if (method->wrapper_type != MONO_WRAPPER_OTHER)
8901 append_mangled_wrapper_type (s, method->wrapper_type);
8903 switch (method->wrapper_type) {
8904 case MONO_WRAPPER_REMOTING_INVOKE:
8905 case MONO_WRAPPER_REMOTING_INVOKE_WITH_CHECK:
8906 case MONO_WRAPPER_XDOMAIN_INVOKE: {
8907 MonoMethod *m = mono_marshal_method_from_wrapper (method);
8908 g_assert (m);
8909 success = success && append_mangled_method (s, m);
8910 break;
8912 case MONO_WRAPPER_PROXY_ISINST:
8913 case MONO_WRAPPER_LDFLD:
8914 case MONO_WRAPPER_LDFLDA:
8915 case MONO_WRAPPER_STFLD: {
8916 g_assert (info);
8917 success = success && append_mangled_klass (s, info->d.proxy.klass);
8918 break;
8920 case MONO_WRAPPER_ALLOC: {
8921 /* The GC name is saved once in MonoAotFileInfo */
8922 g_assert (info->d.alloc.alloc_type != -1);
8923 g_string_append_printf (s, "%d_", info->d.alloc.alloc_type);
8924 // SlowAlloc, etc
8925 g_string_append_printf (s, "%s_", method->name);
8926 break;
8928 case MONO_WRAPPER_WRITE_BARRIER: {
8929 g_string_append_printf (s, "%s_", method->name);
8930 break;
8932 case MONO_WRAPPER_STELEMREF: {
8933 append_mangled_wrapper_subtype (s, info->subtype);
8934 if (info->subtype == WRAPPER_SUBTYPE_VIRTUAL_STELEMREF)
8935 g_string_append_printf (s, "%d", info->d.virtual_stelemref.kind);
8936 break;
8938 case MONO_WRAPPER_OTHER: {
8939 append_mangled_wrapper_subtype (s, info->subtype);
8940 if (info->subtype == WRAPPER_SUBTYPE_PTR_TO_STRUCTURE ||
8941 info->subtype == WRAPPER_SUBTYPE_STRUCTURE_TO_PTR)
8942 success = success && append_mangled_klass (s, method->klass);
8943 else if (info->subtype == WRAPPER_SUBTYPE_SYNCHRONIZED_INNER)
8944 success = success && append_mangled_method (s, info->d.synchronized_inner.method);
8945 else if (info->subtype == WRAPPER_SUBTYPE_ARRAY_ACCESSOR)
8946 success = success && append_mangled_method (s, info->d.array_accessor.method);
8947 else if (info->subtype == WRAPPER_SUBTYPE_INTERP_IN)
8948 append_mangled_signature (s, info->d.interp_in.sig);
8949 else if (info->subtype == WRAPPER_SUBTYPE_GSHAREDVT_IN_SIG) {
8950 append_mangled_signature (s, info->d.gsharedvt.sig);
8951 append_sig = FALSE;
8952 } else if (info->subtype == WRAPPER_SUBTYPE_GSHAREDVT_OUT_SIG) {
8953 append_mangled_signature (s, info->d.gsharedvt.sig);
8954 append_sig = FALSE;
8955 } else if (info->subtype == WRAPPER_SUBTYPE_INTERP_LMF)
8956 g_string_append_printf (s, "%s", method->name);
8957 break;
8959 case MONO_WRAPPER_MANAGED_TO_NATIVE: {
8960 append_mangled_wrapper_subtype (s, info->subtype);
8961 if (info->subtype == WRAPPER_SUBTYPE_ICALL_WRAPPER) {
8962 g_string_append_printf (s, "%s", method->name);
8963 } else if (info->subtype == WRAPPER_SUBTYPE_NATIVE_FUNC_AOT) {
8964 success = success && append_mangled_method (s, info->d.managed_to_native.method);
8965 } else {
8966 g_assert (info->subtype == WRAPPER_SUBTYPE_NONE || info->subtype == WRAPPER_SUBTYPE_PINVOKE);
8967 success = success && append_mangled_method (s, info->d.managed_to_native.method);
8969 break;
8971 case MONO_WRAPPER_SYNCHRONIZED: {
8972 MonoMethod *m;
8974 m = mono_marshal_method_from_wrapper (method);
8975 g_assert (m);
8976 g_assert (m != method);
8977 success = success && append_mangled_method (s, m);
8978 break;
8980 case MONO_WRAPPER_MANAGED_TO_MANAGED: {
8981 append_mangled_wrapper_subtype (s, info->subtype);
8983 if (info->subtype == WRAPPER_SUBTYPE_ELEMENT_ADDR) {
8984 g_string_append_printf (s, "%d_", info->d.element_addr.rank);
8985 g_string_append_printf (s, "%d_", info->d.element_addr.elem_size);
8986 } else if (info->subtype == WRAPPER_SUBTYPE_STRING_CTOR) {
8987 success = success && append_mangled_method (s, info->d.string_ctor.method);
8988 } else if (info->subtype == WRAPPER_SUBTYPE_GENERIC_ARRAY_HELPER) {
8989 success = success && append_mangled_method (s, info->d.generic_array_helper.method);
8990 } else {
8991 success = FALSE;
8993 break;
8995 case MONO_WRAPPER_CASTCLASS: {
8996 append_mangled_wrapper_subtype (s, info->subtype);
8997 break;
8999 case MONO_WRAPPER_RUNTIME_INVOKE: {
9000 append_mangled_wrapper_subtype (s, info->subtype);
9001 if (info->subtype == WRAPPER_SUBTYPE_RUNTIME_INVOKE_DIRECT || info->subtype == WRAPPER_SUBTYPE_RUNTIME_INVOKE_VIRTUAL)
9002 success = success && append_mangled_method (s, info->d.runtime_invoke.method);
9003 else if (info->subtype == WRAPPER_SUBTYPE_RUNTIME_INVOKE_NORMAL)
9004 success = success && append_mangled_signature (s, info->d.runtime_invoke.sig);
9005 break;
9007 case MONO_WRAPPER_DELEGATE_INVOKE:
9008 case MONO_WRAPPER_DELEGATE_BEGIN_INVOKE:
9009 case MONO_WRAPPER_DELEGATE_END_INVOKE: {
9010 if (method->is_inflated) {
9011 /* These wrappers are identified by their class */
9012 g_string_append_printf (s, "i_");
9013 success = success && append_mangled_klass (s, method->klass);
9014 } else {
9015 WrapperInfo *info = mono_marshal_get_wrapper_info (method);
9017 g_string_append_printf (s, "u_");
9018 if (method->wrapper_type == MONO_WRAPPER_DELEGATE_INVOKE)
9019 append_mangled_wrapper_subtype (s, info->subtype);
9020 g_string_append_printf (s, "u_sigstart");
9022 break;
9024 case MONO_WRAPPER_NATIVE_TO_MANAGED: {
9025 g_assert (info);
9026 success = success && append_mangled_method (s, info->d.native_to_managed.method);
9027 success = success && append_mangled_klass (s, method->klass);
9028 break;
9030 default:
9031 g_assert_not_reached ();
9033 if (success && append_sig)
9034 success = append_mangled_signature (s, mono_method_signature_internal (method));
9035 return success;
9038 static void
9039 append_mangled_ginst (GString *str, MonoGenericInst *ginst)
9041 int i;
9043 for (i = 0; i < ginst->type_argc; ++i) {
9044 if (i > 0)
9045 g_string_append (str, ", ");
9046 MonoType *type = ginst->type_argv [i];
9047 switch (type->type) {
9048 case MONO_TYPE_VAR:
9049 case MONO_TYPE_MVAR: {
9050 MonoType *constraint = NULL;
9051 if (type->data.generic_param)
9052 constraint = type->data.generic_param->gshared_constraint;
9053 if (constraint) {
9054 g_assert (constraint->type != MONO_TYPE_VAR && constraint->type != MONO_TYPE_MVAR);
9055 g_string_append (str, "gshared:");
9056 mono_type_get_desc (str, constraint, TRUE);
9057 break;
9059 // Else falls through to common case
9061 default:
9062 mono_type_get_desc (str, type, TRUE);
9067 static void
9068 append_mangled_context (GString *str, MonoGenericContext *context)
9070 GString *res = g_string_new ("");
9072 g_string_append_printf (res, "gens_");
9073 g_string_append (res, "00");
9075 gboolean good = context->class_inst && context->class_inst->type_argc > 0;
9076 good = good || (context->method_inst && context->method_inst->type_argc > 0);
9077 g_assert (good);
9079 if (context->class_inst)
9080 append_mangled_ginst (res, context->class_inst);
9081 if (context->method_inst) {
9082 if (context->class_inst)
9083 g_string_append (res, "11");
9084 append_mangled_ginst (res, context->method_inst);
9086 g_string_append_printf (str, "gens_%s", res->str);
9087 g_free (res);
9090 static gboolean
9091 append_mangled_method (GString *s, MonoMethod *method)
9093 if (method->wrapper_type)
9094 return append_mangled_wrapper (s, method);
9096 if (method->is_inflated) {
9097 g_string_append_printf (s, "inflated_");
9098 MonoMethodInflated *imethod = (MonoMethodInflated*) method;
9099 g_assert (imethod->context.class_inst != NULL || imethod->context.method_inst != NULL);
9101 append_mangled_context (s, &imethod->context);
9102 g_string_append_printf (s, "_declared_by_%s_", m_class_get_image (imethod->declaring->klass)->assembly->aname.name);
9103 append_mangled_method (s, imethod->declaring);
9104 } else if (method->is_generic) {
9105 g_string_append_printf (s, "%s_", m_class_get_image (method->klass)->assembly->aname.name);
9107 g_string_append_printf (s, "generic_");
9108 append_mangled_klass (s, method->klass);
9109 g_string_append_printf (s, "_%s_", method->name);
9111 MonoGenericContainer *container = mono_method_get_generic_container (method);
9112 g_string_append_printf (s, "_");
9113 append_mangled_context (s, &container->context);
9115 return append_mangled_signature (s, mono_method_signature_internal (method));
9116 } else {
9117 g_string_append_printf (s, "_");
9118 append_mangled_klass (s, method->klass);
9119 g_string_append_printf (s, "_%s_", method->name);
9120 if (!append_mangled_signature (s, mono_method_signature_internal (method))) {
9121 g_string_free (s, TRUE);
9122 return FALSE;
9126 return TRUE;
9130 * mono_aot_get_mangled_method_name:
9132 * Return a unique mangled name for METHOD, or NULL.
9134 char*
9135 mono_aot_get_mangled_method_name (MonoMethod *method)
9137 // FIXME: use static cache (mempool?)
9138 // We call this a *lot*
9140 GString *s = g_string_new ("aot_");
9141 if (!append_mangled_method (s, method)) {
9142 g_string_free (s, TRUE);
9143 return NULL;
9144 } else {
9145 char *out = g_string_free (s, FALSE);
9146 // Scrub method and class names
9147 char *cleaned = sanitize_mangled_string (out);
9148 g_free (out);
9149 return cleaned;
9153 gboolean
9154 mono_aot_is_direct_callable (MonoJumpInfo *patch_info)
9156 return is_direct_callable (llvm_acfg, NULL, patch_info);
9159 void
9160 mono_aot_mark_unused_llvm_plt_entry (MonoJumpInfo *patch_info)
9162 MonoPltEntry *plt_entry;
9164 plt_entry = get_plt_entry (llvm_acfg, patch_info);
9165 plt_entry->llvm_used = FALSE;
9168 char*
9169 mono_aot_get_direct_call_symbol (MonoJumpInfoType type, gconstpointer data)
9171 const char *sym = NULL;
9173 if (llvm_acfg->aot_opts.direct_icalls) {
9174 if (type == MONO_PATCH_INFO_JIT_ICALL_ADDR) {
9175 /* Call to a C function implementing a jit icall */
9176 sym = mono_lookup_jit_icall_symbol ((const char *)data);
9177 } else if (type == MONO_PATCH_INFO_ICALL_ADDR_CALL) {
9178 MonoMethod *method = (MonoMethod *)data;
9179 if (!(method->flags & METHOD_ATTRIBUTE_PINVOKE_IMPL))
9180 sym = mono_lookup_icall_symbol (method);
9181 else if (llvm_acfg->aot_opts.direct_pinvoke)
9182 sym = get_pinvoke_import (llvm_acfg, method);
9183 } else if (type == MONO_PATCH_INFO_JIT_ICALL) {
9184 MonoJitICallInfo *info = mono_find_jit_icall_by_name ((const char*)data);
9185 const char *name = mono_lookup_jit_icall_symbol ((const char*)data);
9186 if (name && llvm_acfg->aot_opts.direct_icalls && info->func == info->wrapper)
9187 sym = name;
9189 if (sym)
9190 return g_strdup (sym);
9192 return NULL;
9195 char*
9196 mono_aot_get_plt_symbol (MonoJumpInfoType type, gconstpointer data)
9198 MonoJumpInfo *ji = (MonoJumpInfo *)mono_mempool_alloc (llvm_acfg->mempool, sizeof (MonoJumpInfo));
9199 MonoPltEntry *plt_entry;
9200 const char *sym = NULL;
9202 ji->type = type;
9203 ji->data.target = data;
9205 if (!can_encode_patch (llvm_acfg, ji))
9206 return NULL;
9208 if (llvm_acfg->aot_opts.direct_icalls) {
9209 if (type == MONO_PATCH_INFO_JIT_ICALL_ADDR) {
9210 /* Call to a C function implementing a jit icall */
9211 sym = mono_lookup_jit_icall_symbol ((const char *)data);
9212 } else if (type == MONO_PATCH_INFO_ICALL_ADDR_CALL) {
9213 MonoMethod *method = (MonoMethod *)data;
9214 if (!(method->flags & METHOD_ATTRIBUTE_PINVOKE_IMPL))
9215 sym = mono_lookup_icall_symbol (method);
9217 if (sym)
9218 return g_strdup (sym);
9221 plt_entry = get_plt_entry (llvm_acfg, ji);
9222 plt_entry->llvm_used = TRUE;
9224 #if defined(TARGET_MACH)
9225 return g_strdup (plt_entry->llvm_symbol + strlen (llvm_acfg->llvm_label_prefix));
9226 #else
9227 return g_strdup (plt_entry->llvm_symbol);
9228 #endif
9232 mono_aot_get_method_index (MonoMethod *method)
9234 g_assert (llvm_acfg);
9235 return get_method_index (llvm_acfg, method);
9238 MonoJumpInfo*
9239 mono_aot_patch_info_dup (MonoJumpInfo* ji)
9241 MonoJumpInfo *res;
9243 mono_acfg_lock (llvm_acfg);
9244 res = mono_patch_info_dup_mp (llvm_acfg->mempool, ji);
9245 mono_acfg_unlock (llvm_acfg);
9247 return res;
9250 static int
9251 execute_system (const char * command)
9253 int status = 0;
9255 #if G_HAVE_API_SUPPORT(HAVE_CLASSIC_WINAPI_SUPPORT) && defined(HOST_WIN32)
9256 // We need an extra set of quotes around the whole command to properly handle commands
9257 // with spaces since internally the command is called through "cmd /c.
9258 char * quoted_command = g_strdup_printf ("\"%s\"", command);
9260 int size = MultiByteToWideChar (CP_UTF8, 0 , quoted_command , -1, NULL , 0);
9261 wchar_t* wstr = g_malloc (sizeof (wchar_t) * size);
9262 MultiByteToWideChar (CP_UTF8, 0, quoted_command, -1, wstr , size);
9263 status = _wsystem (wstr);
9264 g_free (wstr);
9266 g_free (quoted_command);
9267 #elif defined (HAVE_SYSTEM)
9268 status = system (command);
9269 #else
9270 g_assert_not_reached ();
9271 #endif
9273 return status;
9276 #ifdef ENABLE_LLVM
9279 * emit_llvm_file:
9281 * Emit the LLVM code into an LLVM bytecode file, and compile it using the LLVM
9282 * tools.
9284 static gboolean
9285 emit_llvm_file (MonoAotCompile *acfg)
9287 char *command, *opts, *tempbc, *optbc, *output_fname;
9289 if (acfg->aot_opts.llvm_only && acfg->aot_opts.asm_only) {
9290 if (acfg->aot_opts.no_opt)
9291 tempbc = g_strdup (acfg->aot_opts.llvm_outfile);
9292 else
9293 tempbc = g_strdup_printf ("%s.bc", acfg->tmpbasename);
9294 optbc = g_strdup (acfg->aot_opts.llvm_outfile);
9295 } else {
9296 tempbc = g_strdup_printf ("%s.bc", acfg->tmpbasename);
9297 optbc = g_strdup_printf ("%s.opt.bc", acfg->tmpbasename);
9300 mono_llvm_emit_aot_module (tempbc, g_path_get_basename (acfg->image->name));
9302 if (acfg->aot_opts.no_opt)
9303 return TRUE;
9305 * FIXME: Experiment with adding optimizations, the -std-compile-opts set takes
9306 * a lot of time, and doesn't seem to save much space.
9307 * The following optimizations cannot be enabled:
9308 * - 'tailcallelim'
9309 * - 'jump-threading' changes our blockaddress references to int constants.
9310 * - 'basiccg' fails because it contains:
9311 * if (CS && !isa<IntrinsicInst>(II)) {
9312 * and isa<IntrinsicInst> is false for invokes to intrinsics (iltests.exe).
9313 * - 'prune-eh' and 'functionattrs' depend on 'basiccg'.
9314 * The opt list below was produced by taking the output of:
9315 * llvm-as < /dev/null | opt -O2 -disable-output -debug-pass=Arguments
9316 * then removing tailcallelim + the global opts.
9317 * strip-dead-prototypes deletes unused intrinsics definitions.
9319 /* The dse pass is disabled because of #13734 and #17616 */
9321 * The dse bug is in DeadStoreElimination.cpp:isOverwrite ():
9322 * // If we have no DataLayout information around, then the size of the store
9323 * // is inferrable from the pointee type. If they are the same type, then
9324 * // we know that the store is safe.
9325 * if (AA.getDataLayout() == 0 &&
9326 * Later.Ptr->getType() == Earlier.Ptr->getType()) {
9327 * return OverwriteComplete;
9328 * Here, if 'Earlier' refers to a memset, and Later has no size info, it mistakenly thinks the memset is redundant.
9330 if (acfg->aot_opts.llvm_only) {
9331 // FIXME: This doesn't work yet
9332 opts = g_strdup ("");
9333 } else {
9334 #if LLVM_API_VERSION > 100
9335 opts = g_strdup ("-O2 -disable-tail-calls");
9336 #else
9337 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");
9338 #endif
9339 if (acfg->aot_opts.llvm_opts) {
9340 opts = g_strdup_printf ("%s %s", opts, acfg->aot_opts.llvm_opts);
9344 command = g_strdup_printf ("\"%sopt\" -f %s -o \"%s\" \"%s\"", acfg->aot_opts.llvm_path, opts, optbc, tempbc);
9345 aot_printf (acfg, "Executing opt: %s\n", command);
9346 if (execute_system (command) != 0)
9347 return FALSE;
9348 g_free (opts);
9350 if (acfg->aot_opts.llvm_only && acfg->aot_opts.asm_only)
9351 /* Nothing else to do */
9352 return TRUE;
9354 if (acfg->aot_opts.llvm_only) {
9355 /* Use the stock clang from xcode */
9356 // FIXME: arch
9357 command = g_strdup_printf ("%s -fexceptions -march=x86-64 -fpic -msse -msse2 -msse3 -msse4 -O2 -fno-optimize-sibling-calls -Wno-override-module -c -o \"%s\" \"%s.opt.bc\"", acfg->aot_opts.clangxx, acfg->llvm_ofile, acfg->tmpbasename);
9359 aot_printf (acfg, "Executing clang: %s\n", command);
9360 if (execute_system (command) != 0)
9361 return FALSE;
9362 return TRUE;
9365 if (!acfg->llc_args)
9366 acfg->llc_args = g_string_new ("");
9368 /* Verbose asm slows down llc greatly */
9369 g_string_append (acfg->llc_args, " -asm-verbose=false");
9371 if (acfg->aot_opts.mtriple)
9372 g_string_append_printf (acfg->llc_args, " -mtriple=%s", acfg->aot_opts.mtriple);
9374 g_string_append (acfg->llc_args, " -disable-gnu-eh-frame -enable-mono-eh-frame");
9376 g_string_append_printf (acfg->llc_args, " -mono-eh-frame-symbol=%s%s", acfg->user_symbol_prefix, acfg->llvm_eh_frame_symbol);
9378 #if LLVM_API_VERSION > 100
9379 g_string_append_printf (acfg->llc_args, " -disable-tail-calls");
9380 #endif
9382 #if LLVM_API_VERSION > 500 && (defined(TARGET_AMD64) || defined(TARGET_X86))
9383 /* This generates stack adjustments in the middle of functions breaking unwind info */
9384 g_string_append_printf (acfg->llc_args, " -no-x86-call-frame-opt");
9385 #endif
9387 #if ( defined(TARGET_MACH) && defined(TARGET_ARM) ) || defined(TARGET_ORBIS)
9388 /* ios requires PIC code now */
9389 g_string_append_printf (acfg->llc_args, " -relocation-model=pic");
9390 #else
9391 if (llvm_acfg->aot_opts.static_link)
9392 g_string_append_printf (acfg->llc_args, " -relocation-model=static");
9393 else
9394 g_string_append_printf (acfg->llc_args, " -relocation-model=pic");
9395 #endif
9397 if (acfg->llvm_owriter) {
9398 /* Emit an object file directly */
9399 output_fname = g_strdup_printf ("%s", acfg->llvm_ofile);
9400 g_string_append_printf (acfg->llc_args, " -filetype=obj");
9401 } else {
9402 output_fname = g_strdup_printf ("%s", acfg->llvm_sfile);
9405 if (acfg->aot_opts.llvm_llc) {
9406 g_string_append_printf (acfg->llc_args, " %s", acfg->aot_opts.llvm_llc);
9409 command = g_strdup_printf ("\"%sllc\" %s -o \"%s\" \"%s.opt.bc\"", acfg->aot_opts.llvm_path, acfg->llc_args->str, output_fname, acfg->tmpbasename);
9410 g_free (output_fname);
9412 aot_printf (acfg, "Executing llc: %s\n", command);
9414 if (execute_system (command) != 0)
9415 return FALSE;
9416 return TRUE;
9418 #endif
9420 /* Set the skip flag for methods which do not need to be emitted because of dedup */
9421 static void
9422 dedup_skip_methods (MonoAotCompile *acfg)
9424 int oindex, i;
9426 if (acfg->aot_opts.llvm_only)
9427 return;
9429 for (oindex = 0; oindex < acfg->method_order->len; ++oindex) {
9430 MonoCompile *cfg;
9431 MonoMethod *method;
9433 i = GPOINTER_TO_UINT (g_ptr_array_index (acfg->method_order, oindex));
9435 cfg = acfg->cfgs [i];
9437 if (!cfg)
9438 continue;
9440 method = cfg->orig_method;
9442 gboolean dedup_collect = acfg->aot_opts.dedup || (acfg->aot_opts.dedup_include && !acfg->dedup_emit_mode);
9443 gboolean dedupable = mono_aot_can_dedup (method);
9445 // cfg->skip is vital for LLVM to work, can't just continue in this loop
9446 if (dedupable && strcmp (method->name, "wbarrier_conc") && dedup_collect) {
9447 mono_dedup_cache_method (acfg, method);
9449 // Don't compile inflated methods if we're in first phase of
9450 // dedup
9452 // In second phase, we emit methods that
9453 // are dedupable. We also emit later methods
9454 // which are referenced by them and added later.
9455 // For this reason, when in the dedup_include mode,
9456 // we never set skip.
9457 if (acfg->aot_opts.dedup)
9458 cfg->skip = TRUE;
9461 // Don't compile anything in this mode
9462 if (acfg->aot_opts.dedup_include && !acfg->dedup_emit_mode)
9463 cfg->skip = TRUE;
9465 // Compile everything in this mode
9466 if (acfg->aot_opts.dedup_include && acfg->dedup_emit_mode)
9467 cfg->skip = FALSE;
9469 /*if (dedup_collect) {*/
9470 /*char *name = mono_aot_get_mangled_method_name (method);*/
9472 /*if (ignore_cfg (cfg))*/
9473 /*aot_printf (acfg, "Dedup Skipping %s\n", acfg->image->name, name);*/
9474 /*else*/
9475 /*aot_printf (acfg, "Dedup Keeping %s\n", acfg->image->name, name);*/
9477 /*g_free (name);*/
9478 /*}*/
9482 static void
9483 emit_code (MonoAotCompile *acfg)
9485 int oindex, i, prev_index;
9486 gboolean saved_unbox_info = FALSE; // See mono_aot_get_unbox_trampoline.
9487 char symbol [MAX_SYMBOL_SIZE];
9489 if (acfg->aot_opts.llvm_only)
9490 return;
9492 #if defined(TARGET_POWERPC64)
9493 sprintf (symbol, ".Lgot_addr");
9494 emit_section_change (acfg, ".text", 0);
9495 emit_alignment (acfg, 8);
9496 emit_label (acfg, symbol);
9497 emit_pointer (acfg, acfg->got_symbol);
9498 #endif
9501 * This global symbol is used to compute the address of each method using the
9502 * code_offsets array. It is also used to compute the memory ranges occupied by
9503 * AOT code, so it must be equal to the address of the first emitted method.
9505 emit_section_change (acfg, ".text", 0);
9506 emit_alignment_code (acfg, 8);
9507 emit_info_symbol (acfg, "jit_code_start", TRUE);
9510 * Emit some padding so the local symbol for the first method doesn't have the
9511 * same address as 'methods'.
9513 emit_padding (acfg, 16);
9515 for (oindex = 0; oindex < acfg->method_order->len; ++oindex) {
9516 MonoCompile *cfg;
9517 MonoMethod *method;
9519 i = GPOINTER_TO_UINT (g_ptr_array_index (acfg->method_order, oindex));
9521 cfg = acfg->cfgs [i];
9523 if (!cfg)
9524 continue;
9526 method = cfg->orig_method;
9528 if (ignore_cfg (cfg))
9529 continue;
9531 /* Emit unbox trampoline */
9532 if (mono_aot_mode_is_full (&acfg->aot_opts) && m_class_is_valuetype (cfg->orig_method->klass)) {
9533 sprintf (symbol, "ut_%d", get_method_index (acfg, method));
9535 emit_section_change (acfg, ".text", 0);
9537 if (acfg->thumb_mixed && cfg->compile_llvm) {
9538 emit_set_thumb_mode (acfg);
9539 fprintf (acfg->fp, "\n.thumb_func\n");
9542 emit_label (acfg, symbol);
9544 arch_emit_unbox_trampoline (acfg, cfg, cfg->orig_method, cfg->asm_symbol);
9546 if (acfg->thumb_mixed && cfg->compile_llvm)
9547 emit_set_arm_mode (acfg);
9549 if (!saved_unbox_info) {
9550 char user_symbol [128];
9551 GSList *unwind_ops;
9552 sprintf (user_symbol, "%sunbox_trampoline_p", acfg->user_symbol_prefix);
9554 emit_label (acfg, "ut_end");
9556 unwind_ops = mono_unwind_get_cie_program ();
9557 save_unwind_info (acfg, user_symbol, unwind_ops);
9558 mono_free_unwind_info (unwind_ops);
9560 /* Save the unbox trampoline size */
9561 #ifdef TARGET_AMD64
9562 // LLVM unbox trampolines vary in size, 6 or 9 bytes,
9563 // due to the last instruction being 2 or 5 bytes.
9564 // There is no need to describe interior bytes of instructions
9565 // however, so state the size as if the last instruction is size 1.
9566 emit_int32 (acfg, 5);
9567 #else
9568 emit_symbol_diff (acfg, "ut_end", symbol, 0);
9569 #endif
9570 saved_unbox_info = TRUE;
9574 if (cfg->compile_llvm) {
9575 acfg->stats.llvm_count ++;
9576 } else {
9577 emit_method_code (acfg, cfg);
9581 emit_section_change (acfg, ".text", 0);
9582 emit_alignment_code (acfg, 8);
9583 emit_info_symbol (acfg, "jit_code_end", TRUE);
9585 /* To distinguish it from the next symbol */
9586 emit_padding (acfg, 4);
9589 * Add .no_dead_strip directives for all LLVM methods to prevent the OSX linker
9590 * from optimizing them away, since it doesn't see that code_offsets references them.
9591 * JITted methods don't need this since they are referenced using assembler local
9592 * symbols.
9593 * FIXME: This is why write-symbols doesn't work on OSX ?
9595 if (acfg->llvm && acfg->need_no_dead_strip) {
9596 fprintf (acfg->fp, "\n");
9597 for (i = 0; i < acfg->nmethods; ++i) {
9598 if (acfg->cfgs [i] && acfg->cfgs [i]->compile_llvm)
9599 fprintf (acfg->fp, ".no_dead_strip %s\n", acfg->cfgs [i]->asm_symbol);
9604 * To work around linker issues, we emit a table of branches, and disassemble them at runtime.
9605 * This is PIE code, and the linker can update it if needed.
9608 sprintf (symbol, "method_addresses");
9609 emit_section_change (acfg, ".text", 1);
9610 emit_alignment_code (acfg, 8);
9611 emit_info_symbol (acfg, symbol, TRUE);
9612 if (acfg->aot_opts.write_symbols)
9613 emit_local_symbol (acfg, symbol, "method_addresses_end", TRUE);
9614 emit_unset_mode (acfg);
9615 if (acfg->need_no_dead_strip)
9616 fprintf (acfg->fp, " .no_dead_strip %s\n", symbol);
9618 for (i = 0; i < acfg->nmethods; ++i) {
9619 #ifdef MONO_ARCH_AOT_SUPPORTED
9620 int call_size;
9622 if (!ignore_cfg (acfg->cfgs [i])) {
9623 arch_emit_direct_call (acfg, acfg->cfgs [i]->asm_symbol, FALSE, acfg->thumb_mixed && acfg->cfgs [i]->compile_llvm, NULL, &call_size);
9624 } else {
9625 arch_emit_direct_call (acfg, symbol, FALSE, FALSE, NULL, &call_size);
9627 #endif
9630 sprintf (symbol, "method_addresses_end");
9631 emit_label (acfg, symbol);
9632 emit_line (acfg);
9634 /* Emit a sorted table mapping methods to the index of their unbox trampolines */
9635 sprintf (symbol, "unbox_trampolines");
9636 emit_section_change (acfg, RODATA_SECT, 0);
9637 emit_alignment (acfg, 8);
9638 emit_info_symbol (acfg, symbol, FALSE);
9640 prev_index = -1;
9641 for (i = 0; i < acfg->nmethods; ++i) {
9642 MonoCompile *cfg;
9643 MonoMethod *method;
9644 int index;
9646 cfg = acfg->cfgs [i];
9647 if (ignore_cfg (cfg))
9648 continue;
9650 method = cfg->orig_method;
9652 if (mono_aot_mode_is_full (&acfg->aot_opts) && m_class_is_valuetype (cfg->orig_method->klass)) {
9653 index = get_method_index (acfg, method);
9655 emit_int32 (acfg, index);
9656 /* Make sure the table is sorted by index */
9657 g_assert (index > prev_index);
9658 prev_index = index;
9661 sprintf (symbol, "unbox_trampolines_end");
9662 emit_info_symbol (acfg, symbol, FALSE);
9663 emit_int32 (acfg, 0);
9665 /* Emit a separate table with the trampoline addresses/offsets */
9666 sprintf (symbol, "unbox_trampoline_addresses");
9667 emit_section_change (acfg, ".text", 0);
9668 emit_alignment_code (acfg, 8);
9669 emit_info_symbol (acfg, symbol, TRUE);
9671 for (i = 0; i < acfg->nmethods; ++i) {
9672 MonoCompile *cfg;
9673 MonoMethod *method;
9674 int index;
9676 cfg = acfg->cfgs [i];
9677 if (ignore_cfg (cfg))
9678 continue;
9680 method = cfg->orig_method;
9682 if (mono_aot_mode_is_full (&acfg->aot_opts) && m_class_is_valuetype (cfg->orig_method->klass)) {
9683 #ifdef MONO_ARCH_AOT_SUPPORTED
9684 int call_size;
9686 index = get_method_index (acfg, method);
9687 sprintf (symbol, "ut_%d", index);
9689 arch_emit_direct_call (acfg, symbol, FALSE, acfg->thumb_mixed && cfg->compile_llvm, NULL, &call_size);
9690 #endif
9693 emit_int32 (acfg, 0);
9696 static void
9697 emit_info (MonoAotCompile *acfg)
9699 int oindex, i;
9700 gint32 *offsets;
9702 offsets = g_new0 (gint32, acfg->nmethods);
9704 for (oindex = 0; oindex < acfg->method_order->len; ++oindex) {
9705 i = GPOINTER_TO_UINT (g_ptr_array_index (acfg->method_order, oindex));
9707 if (acfg->cfgs [i]) {
9708 emit_method_info (acfg, acfg->cfgs [i]);
9709 offsets [i] = acfg->cfgs [i]->method_info_offset;
9710 } else {
9711 offsets [i] = 0;
9715 acfg->stats.offsets_size += emit_offset_table (acfg, "method_info_offsets", MONO_AOT_TABLE_METHOD_INFO_OFFSETS, acfg->nmethods, 10, offsets);
9717 g_free (offsets);
9720 #endif /* #if !defined(DISABLE_AOT) && !defined(DISABLE_JIT) */
9722 #define rot(x,k) (((x)<<(k)) | ((x)>>(32-(k))))
9723 #define mix(a,b,c) { \
9724 a -= c; a ^= rot(c, 4); c += b; \
9725 b -= a; b ^= rot(a, 6); a += c; \
9726 c -= b; c ^= rot(b, 8); b += a; \
9727 a -= c; a ^= rot(c,16); c += b; \
9728 b -= a; b ^= rot(a,19); a += c; \
9729 c -= b; c ^= rot(b, 4); b += a; \
9731 #define mono_final(a,b,c) { \
9732 c ^= b; c -= rot(b,14); \
9733 a ^= c; a -= rot(c,11); \
9734 b ^= a; b -= rot(a,25); \
9735 c ^= b; c -= rot(b,16); \
9736 a ^= c; a -= rot(c,4); \
9737 b ^= a; b -= rot(a,14); \
9738 c ^= b; c -= rot(b,24); \
9741 static guint
9742 mono_aot_type_hash (MonoType *t1)
9744 guint hash = t1->type;
9746 hash |= t1->byref << 6; /* do not collide with t1->type values */
9747 switch (t1->type) {
9748 case MONO_TYPE_VALUETYPE:
9749 case MONO_TYPE_CLASS:
9750 case MONO_TYPE_SZARRAY:
9751 /* check if the distribution is good enough */
9752 return ((hash << 5) - hash) ^ mono_metadata_str_hash (m_class_get_name (t1->data.klass));
9753 case MONO_TYPE_PTR:
9754 return ((hash << 5) - hash) ^ mono_metadata_type_hash (t1->data.type);
9755 case MONO_TYPE_ARRAY:
9756 return ((hash << 5) - hash) ^ mono_metadata_type_hash (m_class_get_byval_arg (t1->data.array->eklass));
9757 case MONO_TYPE_GENERICINST:
9758 return ((hash << 5) - hash) ^ 0;
9759 default:
9760 return hash;
9765 * mono_aot_method_hash:
9767 * Return a hash code for methods which only depends on metadata.
9769 guint32
9770 mono_aot_method_hash (MonoMethod *method)
9772 MonoMethodSignature *sig;
9773 MonoClass *klass;
9774 int i, hindex;
9775 int hashes_count;
9776 guint32 *hashes_start, *hashes;
9777 guint32 a, b, c;
9778 MonoGenericInst *class_ginst = NULL;
9779 MonoGenericInst *ginst = NULL;
9781 /* Similar to the hash in mono_method_get_imt_slot () */
9783 sig = mono_method_signature_internal (method);
9785 if (mono_class_is_ginst (method->klass))
9786 class_ginst = mono_class_get_generic_class (method->klass)->context.class_inst;
9787 if (method->is_inflated)
9788 ginst = ((MonoMethodInflated*)method)->context.method_inst;
9790 hashes_count = sig->param_count + 5 + (class_ginst ? class_ginst->type_argc : 0) + (ginst ? ginst->type_argc : 0);
9791 hashes_start = (guint32 *)g_malloc0 (hashes_count * sizeof (guint32));
9792 hashes = hashes_start;
9794 /* Some wrappers are assigned to random classes */
9795 if (!method->wrapper_type || method->wrapper_type == MONO_WRAPPER_REMOTING_INVOKE_WITH_CHECK)
9796 klass = method->klass;
9797 else
9798 klass = mono_defaults.object_class;
9800 if (!method->wrapper_type) {
9801 char *full_name;
9803 if (mono_class_is_ginst (klass))
9804 full_name = mono_type_full_name (m_class_get_byval_arg (mono_class_get_generic_class (klass)->container_class));
9805 else
9806 full_name = mono_type_full_name (m_class_get_byval_arg (klass));
9808 hashes [0] = mono_metadata_str_hash (full_name);
9809 hashes [1] = 0;
9810 g_free (full_name);
9811 } else {
9812 hashes [0] = mono_metadata_str_hash (m_class_get_name (klass));
9813 hashes [1] = mono_metadata_str_hash (m_class_get_name_space (klass));
9815 if (method->wrapper_type == MONO_WRAPPER_STFLD || method->wrapper_type == MONO_WRAPPER_LDFLD || method->wrapper_type == MONO_WRAPPER_LDFLDA)
9816 /* The method name includes a stringified pointer */
9817 hashes [2] = 0;
9818 else
9819 hashes [2] = mono_metadata_str_hash (method->name);
9820 hashes [3] = method->wrapper_type;
9821 hashes [4] = mono_aot_type_hash (sig->ret);
9822 hindex = 5;
9823 for (i = 0; i < sig->param_count; i++) {
9824 hashes [hindex ++] = mono_aot_type_hash (sig->params [i]);
9826 if (class_ginst) {
9827 for (i = 0; i < class_ginst->type_argc; ++i)
9828 hashes [hindex ++] = mono_aot_type_hash (class_ginst->type_argv [i]);
9830 if (ginst) {
9831 for (i = 0; i < ginst->type_argc; ++i)
9832 hashes [hindex ++] = mono_aot_type_hash (ginst->type_argv [i]);
9834 g_assert (hindex == hashes_count);
9836 /* Setup internal state */
9837 a = b = c = 0xdeadbeef + (((guint32)hashes_count)<<2);
9839 /* Handle most of the hashes */
9840 while (hashes_count > 3) {
9841 a += hashes [0];
9842 b += hashes [1];
9843 c += hashes [2];
9844 mix (a,b,c);
9845 hashes_count -= 3;
9846 hashes += 3;
9849 /* Handle the last 3 hashes (all the case statements fall through) */
9850 switch (hashes_count) {
9851 case 3 : c += hashes [2];
9852 case 2 : b += hashes [1];
9853 case 1 : a += hashes [0];
9854 mono_final (a,b,c);
9855 case 0: /* nothing left to add */
9856 break;
9859 g_free (hashes_start);
9861 return c;
9863 #undef rot
9864 #undef mix
9865 #undef mono_final
9868 * mono_aot_get_array_helper_from_wrapper;
9870 * Get the helper method in Array called by an array wrapper method.
9872 MonoMethod*
9873 mono_aot_get_array_helper_from_wrapper (MonoMethod *method)
9875 MonoMethod *m;
9876 const char *prefix;
9877 MonoGenericContext ctx;
9878 MonoType *args [16];
9879 char *mname, *iname, *s, *s2, *helper_name = NULL;
9881 prefix = "System.Collections.Generic";
9882 s = g_strdup_printf ("%s", method->name + strlen (prefix) + 1);
9883 s2 = strstr (s, "`1.");
9884 g_assert (s2);
9885 s2 [0] = '\0';
9886 iname = s;
9887 mname = s2 + 3;
9889 //printf ("X: %s %s\n", iname, mname);
9891 if (!strcmp (iname, "IList"))
9892 helper_name = g_strdup_printf ("InternalArray__%s", mname);
9893 else
9894 helper_name = g_strdup_printf ("InternalArray__%s_%s", iname, mname);
9895 m = get_method_nofail (mono_defaults.array_class, helper_name, mono_method_signature_internal (method)->param_count, 0);
9896 g_assert (m);
9897 g_free (helper_name);
9898 g_free (s);
9900 if (m->is_generic) {
9901 ERROR_DECL (error);
9902 memset (&ctx, 0, sizeof (ctx));
9903 args [0] = m_class_get_byval_arg (m_class_get_element_class (method->klass));
9904 ctx.method_inst = mono_metadata_get_generic_inst (1, args);
9905 m = mono_class_inflate_generic_method_checked (m, &ctx, error);
9906 g_assert (mono_error_ok (error)); /* FIXME don't swallow the error */
9909 return m;
9912 #if !defined(DISABLE_AOT) && !defined(DISABLE_JIT)
9914 typedef struct HashEntry {
9915 guint32 key, value, index;
9916 struct HashEntry *next;
9917 } HashEntry;
9920 * emit_extra_methods:
9922 * Emit methods which are not in the METHOD table, like wrappers.
9924 static void
9925 emit_extra_methods (MonoAotCompile *acfg)
9927 int i, table_size, buf_size;
9928 guint8 *p, *buf;
9929 guint32 *info_offsets;
9930 guint32 hash;
9931 GPtrArray *table;
9932 HashEntry *entry, *new_entry;
9933 int nmethods, max_chain_length;
9934 int *chain_lengths;
9936 info_offsets = g_new0 (guint32, acfg->extra_methods->len);
9938 /* Emit method info */
9939 nmethods = 0;
9940 for (i = 0; i < acfg->extra_methods->len; ++i) {
9941 MonoMethod *method = (MonoMethod *)g_ptr_array_index (acfg->extra_methods, i);
9942 MonoCompile *cfg = (MonoCompile *)g_hash_table_lookup (acfg->method_to_cfg, method);
9944 if (ignore_cfg (cfg))
9945 continue;
9947 buf_size = 10240;
9948 p = buf = (guint8 *)g_malloc (buf_size);
9950 nmethods ++;
9952 method = cfg->method_to_register;
9954 encode_method_ref (acfg, method, p, &p);
9956 g_assert ((p - buf) < buf_size);
9958 info_offsets [i] = add_to_blob (acfg, buf, p - buf);
9959 g_free (buf);
9963 * Construct a chained hash table for mapping indexes in extra_method_info to
9964 * method indexes.
9966 table_size = g_spaced_primes_closest ((int)(nmethods * 1.5));
9967 table = g_ptr_array_sized_new (table_size);
9968 for (i = 0; i < table_size; ++i)
9969 g_ptr_array_add (table, NULL);
9970 chain_lengths = g_new0 (int, table_size);
9971 max_chain_length = 0;
9972 for (i = 0; i < acfg->extra_methods->len; ++i) {
9973 MonoMethod *method = (MonoMethod *)g_ptr_array_index (acfg->extra_methods, i);
9974 MonoCompile *cfg = (MonoCompile *)g_hash_table_lookup (acfg->method_to_cfg, method);
9975 guint32 key, value;
9977 if (ignore_cfg (cfg))
9978 continue;
9980 key = info_offsets [i];
9981 value = get_method_index (acfg, method);
9983 hash = mono_aot_method_hash (method) % table_size;
9984 //printf ("X: %s %x\n", mono_method_get_full_name (method), mono_aot_method_hash (method));
9986 chain_lengths [hash] ++;
9987 max_chain_length = MAX (max_chain_length, chain_lengths [hash]);
9989 new_entry = (HashEntry *)mono_mempool_alloc0 (acfg->mempool, sizeof (HashEntry));
9990 new_entry->key = key;
9991 new_entry->value = value;
9993 entry = (HashEntry *)g_ptr_array_index (table, hash);
9994 if (entry == NULL) {
9995 new_entry->index = hash;
9996 g_ptr_array_index (table, hash) = new_entry;
9997 } else {
9998 while (entry->next)
9999 entry = entry->next;
10001 entry->next = new_entry;
10002 new_entry->index = table->len;
10003 g_ptr_array_add (table, new_entry);
10006 g_free (chain_lengths);
10008 //printf ("MAX: %d\n", max_chain_length);
10010 buf_size = table->len * 12 + 4;
10011 p = buf = (guint8 *)g_malloc (buf_size);
10012 encode_int (table_size, p, &p);
10014 for (i = 0; i < table->len; ++i) {
10015 HashEntry *entry = (HashEntry *)g_ptr_array_index (table, i);
10017 if (entry == NULL) {
10018 encode_int (0, p, &p);
10019 encode_int (0, p, &p);
10020 encode_int (0, p, &p);
10021 } else {
10022 //g_assert (entry->key > 0);
10023 encode_int (entry->key, p, &p);
10024 encode_int (entry->value, p, &p);
10025 if (entry->next)
10026 encode_int (entry->next->index, p, &p);
10027 else
10028 encode_int (0, p, &p);
10031 g_assert (p - buf <= buf_size);
10033 /* Emit the table */
10034 emit_aot_data (acfg, MONO_AOT_TABLE_EXTRA_METHOD_TABLE, "extra_method_table", buf, p - buf);
10036 g_free (buf);
10039 * Emit a table reverse mapping method indexes to their index in extra_method_info.
10040 * This is used by mono_aot_find_jit_info ().
10042 buf_size = acfg->extra_methods->len * 8 + 4;
10043 p = buf = (guint8 *)g_malloc (buf_size);
10044 encode_int (acfg->extra_methods->len, p, &p);
10045 for (i = 0; i < acfg->extra_methods->len; ++i) {
10046 MonoMethod *method = (MonoMethod *)g_ptr_array_index (acfg->extra_methods, i);
10048 encode_int (get_method_index (acfg, method), p, &p);
10049 encode_int (info_offsets [i], p, &p);
10051 emit_aot_data (acfg, MONO_AOT_TABLE_EXTRA_METHOD_INFO_OFFSETS, "extra_method_info_offsets", buf, p - buf);
10053 g_free (buf);
10054 g_free (info_offsets);
10055 g_ptr_array_free (table, TRUE);
10058 static void
10059 generate_aotid (guint8* aotid)
10061 gpointer rand_handle;
10062 ERROR_DECL (error);
10064 mono_rand_open ();
10065 rand_handle = mono_rand_init (NULL, 0);
10067 mono_rand_try_get_bytes (&rand_handle, aotid, 16, error);
10068 mono_error_assert_ok (error);
10070 mono_rand_close (rand_handle);
10073 static void
10074 emit_exception_info (MonoAotCompile *acfg)
10076 int i;
10077 gint32 *offsets;
10078 SeqPointData sp_data;
10079 gboolean seq_points_to_file = FALSE;
10081 offsets = g_new0 (gint32, acfg->nmethods);
10082 for (i = 0; i < acfg->nmethods; ++i) {
10083 if (acfg->cfgs [i]) {
10084 MonoCompile *cfg = acfg->cfgs [i];
10086 // By design aot-runtime decode_exception_debug_info is not able to load sequence point debug data from a file.
10087 // As it is not possible to load debug data from a file its is also not possible to store it in a file.
10088 gboolean method_seq_points_to_file = acfg->aot_opts.gen_msym_dir &&
10089 cfg->gen_seq_points && !cfg->gen_sdb_seq_points;
10090 gboolean method_seq_points_to_binary = cfg->gen_seq_points && !method_seq_points_to_file;
10092 emit_exception_debug_info (acfg, cfg, method_seq_points_to_binary);
10093 offsets [i] = cfg->ex_info_offset;
10095 if (method_seq_points_to_file) {
10096 if (!seq_points_to_file) {
10097 mono_seq_point_data_init (&sp_data, acfg->nmethods);
10098 seq_points_to_file = TRUE;
10100 mono_seq_point_data_add (&sp_data, cfg->method->token, cfg->method_index, cfg->seq_point_info);
10102 } else {
10103 offsets [i] = 0;
10107 if (seq_points_to_file) {
10108 char *aotid = mono_guid_to_string_minimal (acfg->image->aotid);
10109 char *dir = g_build_filename (acfg->aot_opts.gen_msym_dir_path, aotid, NULL);
10110 char *image_basename = g_path_get_basename (acfg->image->name);
10111 char *aot_file = g_strdup_printf("%s%s", image_basename, SEQ_POINT_AOT_EXT);
10112 char *aot_file_path = g_build_filename (dir, aot_file, NULL);
10114 if (g_ensure_directory_exists (aot_file_path) == FALSE) {
10115 fprintf (stderr, "AOT : failed to create msym directory: %s\n", aot_file_path);
10116 exit (1);
10119 mono_seq_point_data_write (&sp_data, aot_file_path);
10120 mono_seq_point_data_free (&sp_data);
10122 g_free (aotid);
10123 g_free (dir);
10124 g_free (image_basename);
10125 g_free (aot_file);
10126 g_free (aot_file_path);
10129 acfg->stats.offsets_size += emit_offset_table (acfg, "ex_info_offsets", MONO_AOT_TABLE_EX_INFO_OFFSETS, acfg->nmethods, 10, offsets);
10130 g_free (offsets);
10133 static void
10134 emit_unwind_info (MonoAotCompile *acfg)
10136 int i;
10137 char symbol [128];
10139 if (acfg->aot_opts.llvm_only) {
10140 g_assert (acfg->unwind_ops->len == 0);
10141 return;
10145 * The unwind info contains a lot of duplicates so we emit each unique
10146 * entry once, and only store the offset from the start of the table in the
10147 * exception info.
10150 sprintf (symbol, "unwind_info");
10151 emit_section_change (acfg, RODATA_SECT, 1);
10152 emit_alignment (acfg, 8);
10153 emit_info_symbol (acfg, symbol, TRUE);
10155 for (i = 0; i < acfg->unwind_ops->len; ++i) {
10156 guint32 index = GPOINTER_TO_UINT (g_ptr_array_index (acfg->unwind_ops, i));
10157 guint8 *unwind_info;
10158 guint32 unwind_info_len;
10159 guint8 buf [16];
10160 guint8 *p;
10162 unwind_info = mono_get_cached_unwind_info (index, &unwind_info_len);
10164 p = buf;
10165 encode_value (unwind_info_len, p, &p);
10166 emit_bytes (acfg, buf, p - buf);
10167 emit_bytes (acfg, unwind_info, unwind_info_len);
10169 acfg->stats.unwind_info_size += (p - buf) + unwind_info_len;
10173 static void
10174 emit_class_info (MonoAotCompile *acfg)
10176 int i;
10177 gint32 *offsets;
10179 offsets = g_new0 (gint32, acfg->image->tables [MONO_TABLE_TYPEDEF].rows);
10180 for (i = 0; i < acfg->image->tables [MONO_TABLE_TYPEDEF].rows; ++i)
10181 offsets [i] = emit_klass_info (acfg, MONO_TOKEN_TYPE_DEF | (i + 1));
10183 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);
10184 g_free (offsets);
10187 typedef struct ClassNameTableEntry {
10188 guint32 token, index;
10189 struct ClassNameTableEntry *next;
10190 } ClassNameTableEntry;
10192 static void
10193 emit_class_name_table (MonoAotCompile *acfg)
10195 int i, table_size, buf_size;
10196 guint32 token, hash;
10197 MonoClass *klass;
10198 GPtrArray *table;
10199 char *full_name;
10200 guint8 *buf, *p;
10201 ClassNameTableEntry *entry, *new_entry;
10204 * Construct a chained hash table for mapping class names to typedef tokens.
10206 table_size = g_spaced_primes_closest ((int)(acfg->image->tables [MONO_TABLE_TYPEDEF].rows * 1.5));
10207 table = g_ptr_array_sized_new (table_size);
10208 for (i = 0; i < table_size; ++i)
10209 g_ptr_array_add (table, NULL);
10210 for (i = 0; i < acfg->image->tables [MONO_TABLE_TYPEDEF].rows; ++i) {
10211 ERROR_DECL (error);
10212 token = MONO_TOKEN_TYPE_DEF | (i + 1);
10213 klass = mono_class_get_checked (acfg->image, token, error);
10214 if (!klass) {
10215 mono_error_cleanup (error);
10216 continue;
10218 full_name = mono_type_get_name_full (m_class_get_byval_arg (klass), MONO_TYPE_NAME_FORMAT_FULL_NAME);
10219 hash = mono_metadata_str_hash (full_name) % table_size;
10220 g_free (full_name);
10222 /* FIXME: Allocate from the mempool */
10223 new_entry = g_new0 (ClassNameTableEntry, 1);
10224 new_entry->token = token;
10226 entry = (ClassNameTableEntry *)g_ptr_array_index (table, hash);
10227 if (entry == NULL) {
10228 new_entry->index = hash;
10229 g_ptr_array_index (table, hash) = new_entry;
10230 } else {
10231 while (entry->next)
10232 entry = entry->next;
10234 entry->next = new_entry;
10235 new_entry->index = table->len;
10236 g_ptr_array_add (table, new_entry);
10240 /* Emit the table */
10241 buf_size = table->len * 4 + 4;
10242 p = buf = (guint8 *)g_malloc0 (buf_size);
10244 /* FIXME: Optimize memory usage */
10245 g_assert (table_size < 65000);
10246 encode_int16 (table_size, p, &p);
10247 g_assert (table->len < 65000);
10248 for (i = 0; i < table->len; ++i) {
10249 ClassNameTableEntry *entry = (ClassNameTableEntry *)g_ptr_array_index (table, i);
10251 if (entry == NULL) {
10252 encode_int16 (0, p, &p);
10253 encode_int16 (0, p, &p);
10254 } else {
10255 encode_int16 (mono_metadata_token_index (entry->token), p, &p);
10256 if (entry->next)
10257 encode_int16 (entry->next->index, p, &p);
10258 else
10259 encode_int16 (0, p, &p);
10261 g_free (entry);
10263 g_assert (p - buf <= buf_size);
10264 g_ptr_array_free (table, TRUE);
10266 emit_aot_data (acfg, MONO_AOT_TABLE_CLASS_NAME, "class_name_table", buf, p - buf);
10268 g_free (buf);
10271 static void
10272 emit_image_table (MonoAotCompile *acfg)
10274 int i, buf_size;
10275 guint8 *buf, *p;
10278 * The image table is small but referenced in a lot of places.
10279 * So we emit it at once, and reference its elements by an index.
10281 buf_size = acfg->image_table->len * 28 + 4;
10282 for (i = 0; i < acfg->image_table->len; i++) {
10283 MonoImage *image = (MonoImage*)g_ptr_array_index (acfg->image_table, i);
10284 MonoAssemblyName *aname = &image->assembly->aname;
10286 buf_size += strlen (image->assembly_name) + strlen (image->guid) + (aname->culture ? strlen (aname->culture) : 1) + strlen ((char*)aname->public_key_token) + 4;
10289 buf = p = (guint8 *)g_malloc0 (buf_size);
10290 encode_int (acfg->image_table->len, p, &p);
10291 for (i = 0; i < acfg->image_table->len; i++) {
10292 MonoImage *image = (MonoImage*)g_ptr_array_index (acfg->image_table, i);
10293 MonoAssemblyName *aname = &image->assembly->aname;
10295 /* FIXME: Support multi-module assemblies */
10296 g_assert (image->assembly->image == image);
10298 encode_string (image->assembly_name, p, &p);
10299 encode_string (image->guid, p, &p);
10300 encode_string (aname->culture ? aname->culture : "", p, &p);
10301 encode_string ((const char*)aname->public_key_token, p, &p);
10303 while (GPOINTER_TO_UINT (p) % 8 != 0)
10304 p ++;
10306 encode_int (aname->flags, p, &p);
10307 encode_int (aname->major, p, &p);
10308 encode_int (aname->minor, p, &p);
10309 encode_int (aname->build, p, &p);
10310 encode_int (aname->revision, p, &p);
10312 g_assert (p - buf <= buf_size);
10314 emit_aot_data (acfg, MONO_AOT_TABLE_IMAGE_TABLE, "image_table", buf, p - buf);
10316 g_free (buf);
10319 static void
10320 emit_weak_field_indexes (MonoAotCompile *acfg)
10322 GHashTable *indexes;
10323 GHashTableIter iter;
10324 gpointer key, value;
10325 int buf_size;
10326 guint8 *buf, *p;
10328 /* Emit a table of weak field indexes, since computing these at runtime is expensive */
10329 mono_assembly_init_weak_fields (acfg->image);
10330 indexes = acfg->image->weak_field_indexes;
10331 g_assert (indexes);
10333 buf_size = (g_hash_table_size (indexes) + 1) * 4;
10334 buf = p = (guint8 *)g_malloc0 (buf_size);
10336 encode_int (g_hash_table_size (indexes), p, &p);
10337 g_hash_table_iter_init (&iter, indexes);
10338 while (g_hash_table_iter_next (&iter, &key, &value)) {
10339 guint32 index = GPOINTER_TO_UINT (key);
10340 encode_int (index, p, &p);
10342 g_assert (p - buf <= buf_size);
10344 emit_aot_data (acfg, MONO_AOT_TABLE_WEAK_FIELD_INDEXES, "weak_field_indexes", buf, p - buf);
10346 g_free (buf);
10349 static void
10350 emit_got_info (MonoAotCompile *acfg, gboolean llvm)
10352 int i, first_plt_got_patch = 0, buf_size;
10353 guint8 *p, *buf;
10354 guint32 *got_info_offsets;
10355 GotInfo *info = llvm ? &acfg->llvm_got_info : &acfg->got_info;
10357 /* Add the patches needed by the PLT to the GOT */
10358 if (!llvm) {
10359 acfg->plt_got_offset_base = acfg->got_offset;
10360 first_plt_got_patch = info->got_patches->len;
10361 for (i = 1; i < acfg->plt_offset; ++i) {
10362 MonoPltEntry *plt_entry = (MonoPltEntry *)g_hash_table_lookup (acfg->plt_offset_to_entry, GUINT_TO_POINTER (i));
10364 g_ptr_array_add (info->got_patches, plt_entry->ji);
10366 acfg->stats.got_slot_types [plt_entry->ji->type] ++;
10369 acfg->got_offset += acfg->plt_offset;
10373 * FIXME:
10374 * - optimize offsets table.
10375 * - reduce number of exported symbols.
10376 * - emit info for a klass only once.
10377 * - determine when a method uses a GOT slot which is guaranteed to be already
10378 * initialized.
10379 * - clean up and document the code.
10380 * - use String.Empty in class libs.
10383 /* Encode info required to decode shared GOT entries */
10384 buf_size = info->got_patches->len * 128;
10385 p = buf = (guint8 *)mono_mempool_alloc (acfg->mempool, buf_size);
10386 got_info_offsets = (guint32 *)mono_mempool_alloc (acfg->mempool, info->got_patches->len * sizeof (guint32));
10387 if (!llvm) {
10388 acfg->plt_got_info_offsets = (guint32 *)mono_mempool_alloc (acfg->mempool, acfg->plt_offset * sizeof (guint32));
10389 /* Unused */
10390 if (acfg->plt_offset)
10391 acfg->plt_got_info_offsets [0] = 0;
10393 for (i = 0; i < info->got_patches->len; ++i) {
10394 MonoJumpInfo *ji = (MonoJumpInfo *)g_ptr_array_index (info->got_patches, i);
10395 guint8 *p2;
10397 p = buf;
10399 encode_value (ji->type, p, &p);
10400 p2 = p;
10401 encode_patch (acfg, ji, p, &p);
10402 acfg->stats.got_slot_info_sizes [ji->type] += p - p2;
10403 g_assert (p - buf <= buf_size);
10404 got_info_offsets [i] = add_to_blob (acfg, buf, p - buf);
10406 if (!llvm && i >= first_plt_got_patch)
10407 acfg->plt_got_info_offsets [i - first_plt_got_patch + 1] = got_info_offsets [i];
10408 acfg->stats.got_info_size += p - buf;
10411 /* Emit got_info_offsets table */
10413 /* No need to emit offsets for the got plt entries, the plt embeds them directly */
10414 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);
10417 static void
10418 emit_got (MonoAotCompile *acfg)
10420 char symbol [MAX_SYMBOL_SIZE];
10422 if (acfg->aot_opts.llvm_only)
10423 return;
10425 /* Don't make GOT global so accesses to it don't need relocations */
10426 sprintf (symbol, "%s", acfg->got_symbol);
10428 #ifdef TARGET_MACH
10429 emit_unset_mode (acfg);
10430 fprintf (acfg->fp, ".section __DATA, __bss\n");
10431 emit_alignment (acfg, 8);
10432 if (acfg->llvm)
10433 emit_info_symbol (acfg, "jit_got", FALSE);
10434 fprintf (acfg->fp, ".lcomm %s, %d\n", acfg->got_symbol, (int)(acfg->got_offset * sizeof (target_mgreg_t)));
10435 #else
10436 emit_section_change (acfg, ".bss", 0);
10437 emit_alignment (acfg, 8);
10438 if (acfg->aot_opts.write_symbols)
10439 emit_local_symbol (acfg, symbol, "got_end", FALSE);
10440 emit_label (acfg, symbol);
10441 if (acfg->llvm)
10442 emit_info_symbol (acfg, "jit_got", FALSE);
10443 if (acfg->got_offset > 0)
10444 emit_zero_bytes (acfg, (int)(acfg->got_offset * sizeof (target_mgreg_t)));
10445 #endif
10447 sprintf (symbol, "got_end");
10448 emit_label (acfg, symbol);
10451 typedef struct GlobalsTableEntry {
10452 guint32 value, index;
10453 struct GlobalsTableEntry *next;
10454 } GlobalsTableEntry;
10456 #ifdef TARGET_WIN32_MSVC
10457 #define DLL_ENTRY_POINT "DllMain"
10459 static void
10460 emit_library_info (MonoAotCompile *acfg)
10462 // Only include for shared libraries linked directly from generated object.
10463 if (link_shared_library (acfg)) {
10464 char *name = NULL;
10465 char symbol [MAX_SYMBOL_SIZE];
10467 // Ask linker to export all global symbols.
10468 emit_section_change (acfg, ".drectve", 0);
10469 for (guint i = 0; i < acfg->globals->len; ++i) {
10470 name = (char *)g_ptr_array_index (acfg->globals, i);
10471 g_assert (name != NULL);
10472 sprintf_s (symbol, MAX_SYMBOL_SIZE, " /EXPORT:%s", name);
10473 emit_string (acfg, symbol);
10476 // Emit DLLMain function, needed by MSVC linker for DLL's.
10477 // NOTE, DllMain should not go into exports above.
10478 emit_section_change (acfg, ".text", 0);
10479 emit_global (acfg, DLL_ENTRY_POINT, TRUE);
10480 emit_label (acfg, DLL_ENTRY_POINT);
10482 // Simple implementation of DLLMain, just returning TRUE.
10483 // For more information about DLLMain: https://msdn.microsoft.com/en-us/library/windows/desktop/ms682583(v=vs.85).aspx
10484 fprintf (acfg->fp, "movl $1, %%eax\n");
10485 fprintf (acfg->fp, "ret\n");
10487 // Inform linker about our dll entry function.
10488 emit_section_change (acfg, ".drectve", 0);
10489 emit_string (acfg, "/ENTRY:" DLL_ENTRY_POINT);
10490 return;
10494 #else
10496 static inline void
10497 emit_library_info (MonoAotCompile *acfg)
10499 return;
10501 #endif
10503 static void
10504 emit_globals (MonoAotCompile *acfg)
10506 int i, table_size;
10507 guint32 hash;
10508 GPtrArray *table;
10509 char symbol [1024];
10510 GlobalsTableEntry *entry, *new_entry;
10512 if (!acfg->aot_opts.static_link)
10513 return;
10515 if (acfg->aot_opts.llvm_only) {
10516 g_assert (acfg->globals->len == 0);
10517 return;
10521 * When static linking, we emit a table containing our globals.
10525 * Construct a chained hash table for mapping global names to their index in
10526 * the globals table.
10528 table_size = g_spaced_primes_closest ((int)(acfg->globals->len * 1.5));
10529 table = g_ptr_array_sized_new (table_size);
10530 for (i = 0; i < table_size; ++i)
10531 g_ptr_array_add (table, NULL);
10532 for (i = 0; i < acfg->globals->len; ++i) {
10533 char *name = (char *)g_ptr_array_index (acfg->globals, i);
10535 hash = mono_metadata_str_hash (name) % table_size;
10537 /* FIXME: Allocate from the mempool */
10538 new_entry = g_new0 (GlobalsTableEntry, 1);
10539 new_entry->value = i;
10541 entry = (GlobalsTableEntry *)g_ptr_array_index (table, hash);
10542 if (entry == NULL) {
10543 new_entry->index = hash;
10544 g_ptr_array_index (table, hash) = new_entry;
10545 } else {
10546 while (entry->next)
10547 entry = entry->next;
10549 entry->next = new_entry;
10550 new_entry->index = table->len;
10551 g_ptr_array_add (table, new_entry);
10555 /* Emit the table */
10556 sprintf (symbol, ".Lglobals_hash");
10557 emit_section_change (acfg, RODATA_SECT, 0);
10558 emit_alignment (acfg, 8);
10559 emit_label (acfg, symbol);
10561 /* FIXME: Optimize memory usage */
10562 g_assert (table_size < 65000);
10563 emit_int16 (acfg, table_size);
10564 for (i = 0; i < table->len; ++i) {
10565 GlobalsTableEntry *entry = (GlobalsTableEntry *)g_ptr_array_index (table, i);
10567 if (entry == NULL) {
10568 emit_int16 (acfg, 0);
10569 emit_int16 (acfg, 0);
10570 } else {
10571 emit_int16 (acfg, entry->value + 1);
10572 if (entry->next)
10573 emit_int16 (acfg, entry->next->index);
10574 else
10575 emit_int16 (acfg, 0);
10579 /* Emit the names */
10580 for (i = 0; i < acfg->globals->len; ++i) {
10581 char *name = (char *)g_ptr_array_index (acfg->globals, i);
10583 sprintf (symbol, "name_%d", i);
10584 emit_section_change (acfg, RODATA_SECT, 1);
10585 #ifdef TARGET_MACH
10586 emit_alignment (acfg, 4);
10587 #endif
10588 emit_label (acfg, symbol);
10589 emit_string (acfg, name);
10592 /* Emit the globals table */
10593 sprintf (symbol, "globals");
10594 emit_section_change (acfg, ".data", 0);
10595 /* This is not a global, since it is accessed by the init function */
10596 emit_alignment (acfg, 8);
10597 emit_info_symbol (acfg, symbol, FALSE);
10599 sprintf (symbol, "%sglobals_hash", acfg->temp_prefix);
10600 emit_pointer (acfg, symbol);
10602 for (i = 0; i < acfg->globals->len; ++i) {
10603 char *name = (char *)g_ptr_array_index (acfg->globals, i);
10605 sprintf (symbol, "name_%d", i);
10606 emit_pointer (acfg, symbol);
10608 g_assert (strlen (name) < sizeof (symbol));
10609 sprintf (symbol, "%s", name);
10610 emit_pointer (acfg, symbol);
10612 /* Null terminate the table */
10613 emit_int32 (acfg, 0);
10614 emit_int32 (acfg, 0);
10617 static void
10618 emit_mem_end (MonoAotCompile *acfg)
10620 char symbol [128];
10622 if (acfg->aot_opts.llvm_only)
10623 return;
10625 sprintf (symbol, "mem_end");
10626 emit_section_change (acfg, ".text", 1);
10627 emit_alignment_code (acfg, 8);
10628 emit_label (acfg, symbol);
10631 static void
10632 init_aot_file_info (MonoAotCompile *acfg, MonoAotFileInfo *info)
10634 int i;
10636 info->version = MONO_AOT_FILE_VERSION;
10637 info->plt_got_offset_base = acfg->plt_got_offset_base;
10638 info->got_size = acfg->got_offset * sizeof (target_mgreg_t);
10639 info->plt_size = acfg->plt_offset;
10640 info->nmethods = acfg->nmethods;
10641 info->nextra_methods = acfg->nextra_methods;
10642 info->flags = acfg->flags;
10643 info->opts = acfg->opts;
10644 info->simd_opts = acfg->simd_opts;
10645 info->gc_name_index = acfg->gc_name_offset;
10646 info->datafile_size = acfg->datafile_offset;
10647 for (i = 0; i < MONO_AOT_TABLE_NUM; ++i)
10648 info->table_offsets [i] = acfg->table_offsets [i];
10649 for (i = 0; i < MONO_AOT_TRAMP_NUM; ++i)
10650 info->num_trampolines [i] = acfg->num_trampolines [i];
10651 for (i = 0; i < MONO_AOT_TRAMP_NUM; ++i)
10652 info->trampoline_got_offset_base [i] = acfg->trampoline_got_offset_base [i];
10653 for (i = 0; i < MONO_AOT_TRAMP_NUM; ++i)
10654 info->trampoline_size [i] = acfg->trampoline_size [i];
10655 info->num_rgctx_fetch_trampolines = acfg->aot_opts.nrgctx_fetch_trampolines;
10657 int card_table_shift_bits = 0;
10658 target_mgreg_t card_table_mask = 0;
10660 mono_gc_get_target_card_table (&card_table_shift_bits, &card_table_mask);
10663 * Sanity checking variables used to make sure the host and target
10664 * environment matches when cross compiling.
10666 info->double_align = MONO_ABI_ALIGNOF (double);
10667 info->long_align = MONO_ABI_ALIGNOF (gint64);
10668 info->generic_tramp_num = MONO_TRAMPOLINE_NUM;
10669 info->card_table_shift_bits = card_table_shift_bits;
10670 info->card_table_mask = card_table_mask;
10672 info->tramp_page_size = acfg->tramp_page_size;
10673 info->nshared_got_entries = acfg->nshared_got_entries;
10674 for (i = 0; i < MONO_AOT_TRAMP_NUM; ++i)
10675 info->tramp_page_code_offsets [i] = acfg->tramp_page_code_offsets [i];
10677 memcpy(&info->aotid, acfg->image->aotid, 16);
10680 static void
10681 emit_aot_file_info (MonoAotCompile *acfg, MonoAotFileInfo *info)
10683 char symbol [MAX_SYMBOL_SIZE];
10684 int i, sindex;
10685 const char **symbols;
10687 symbols = g_new0 (const char *, MONO_AOT_FILE_INFO_NUM_SYMBOLS);
10688 sindex = 0;
10689 symbols [sindex ++] = acfg->got_symbol;
10690 if (acfg->llvm) {
10691 symbols [sindex ++] = g_strdup_printf ("%s%s", acfg->user_symbol_prefix, acfg->llvm_got_symbol);
10692 symbols [sindex ++] = acfg->llvm_eh_frame_symbol;
10693 } else {
10694 symbols [sindex ++] = NULL;
10695 symbols [sindex ++] = NULL;
10697 /* llvm_get_method */
10698 symbols [sindex ++] = NULL;
10699 /* llvm_get_unbox_tramp */
10700 symbols [sindex ++] = NULL;
10701 if (!acfg->aot_opts.llvm_only) {
10702 symbols [sindex ++] = "jit_code_start";
10703 symbols [sindex ++] = "jit_code_end";
10704 symbols [sindex ++] = "method_addresses";
10705 } else {
10706 symbols [sindex ++] = NULL;
10707 symbols [sindex ++] = NULL;
10708 symbols [sindex ++] = NULL;
10710 symbols [sindex ++] = NULL;
10711 symbols [sindex ++] = NULL;
10713 if (acfg->data_outfile) {
10714 for (i = 0; i < MONO_AOT_TABLE_NUM; ++i)
10715 symbols [sindex ++] = NULL;
10716 } else {
10717 symbols [sindex ++] = "blob";
10718 symbols [sindex ++] = "class_name_table";
10719 symbols [sindex ++] = "class_info_offsets";
10720 symbols [sindex ++] = "method_info_offsets";
10721 symbols [sindex ++] = "ex_info_offsets";
10722 symbols [sindex ++] = "extra_method_info_offsets";
10723 symbols [sindex ++] = "extra_method_table";
10724 symbols [sindex ++] = "got_info_offsets";
10725 if (acfg->llvm)
10726 symbols [sindex ++] = "llvm_got_info_offsets";
10727 else
10728 symbols [sindex ++] = NULL;
10729 symbols [sindex ++] = "image_table";
10730 symbols [sindex ++] = "weak_field_indexes";
10733 symbols [sindex ++] = "mem_end";
10734 symbols [sindex ++] = "assembly_guid";
10735 symbols [sindex ++] = "runtime_version";
10736 if (acfg->num_trampoline_got_entries) {
10737 symbols [sindex ++] = "specific_trampolines";
10738 symbols [sindex ++] = "static_rgctx_trampolines";
10739 symbols [sindex ++] = "imt_trampolines";
10740 symbols [sindex ++] = "gsharedvt_arg_trampolines";
10741 symbols [sindex ++] = "ftnptr_arg_trampolines";
10742 symbols [sindex ++] = "unbox_arbitrary_trampolines";
10743 } else {
10744 symbols [sindex ++] = NULL;
10745 symbols [sindex ++] = NULL;
10746 symbols [sindex ++] = NULL;
10747 symbols [sindex ++] = NULL;
10748 symbols [sindex ++] = NULL;
10749 symbols [sindex ++] = NULL;
10751 if (acfg->aot_opts.static_link) {
10752 symbols [sindex ++] = "globals";
10753 } else {
10754 symbols [sindex ++] = NULL;
10756 symbols [sindex ++] = "assembly_name";
10757 symbols [sindex ++] = "plt";
10758 symbols [sindex ++] = "plt_end";
10759 symbols [sindex ++] = "unwind_info";
10760 if (!acfg->aot_opts.llvm_only) {
10761 symbols [sindex ++] = "unbox_trampolines";
10762 symbols [sindex ++] = "unbox_trampolines_end";
10763 symbols [sindex ++] = "unbox_trampoline_addresses";
10764 } else {
10765 symbols [sindex ++] = NULL;
10766 symbols [sindex ++] = NULL;
10767 symbols [sindex ++] = NULL;
10770 g_assert (sindex == MONO_AOT_FILE_INFO_NUM_SYMBOLS);
10772 sprintf (symbol, "%smono_aot_file_info", acfg->user_symbol_prefix);
10773 emit_section_change (acfg, ".data", 0);
10774 emit_alignment (acfg, 8);
10775 emit_label (acfg, symbol);
10776 if (!acfg->aot_opts.static_link)
10777 emit_global (acfg, symbol, FALSE);
10779 /* The data emitted here must match MonoAotFileInfo. */
10781 emit_int32 (acfg, info->version);
10782 emit_int32 (acfg, info->dummy);
10785 * We emit pointers to our data structures instead of emitting global symbols which
10786 * point to them, to reduce the number of globals, and because using globals leads to
10787 * various problems (i.e. arm/thumb).
10789 for (i = 0; i < MONO_AOT_FILE_INFO_NUM_SYMBOLS; ++i)
10790 emit_pointer (acfg, symbols [i]);
10792 emit_int32 (acfg, info->plt_got_offset_base);
10793 emit_int32 (acfg, info->got_size);
10794 emit_int32 (acfg, info->plt_size);
10795 emit_int32 (acfg, info->nmethods);
10796 emit_int32 (acfg, info->nextra_methods);
10797 emit_int32 (acfg, info->flags);
10798 emit_int32 (acfg, info->opts);
10799 emit_int32 (acfg, info->simd_opts);
10800 emit_int32 (acfg, info->gc_name_index);
10801 emit_int32 (acfg, info->num_rgctx_fetch_trampolines);
10802 emit_int32 (acfg, info->double_align);
10803 emit_int32 (acfg, info->long_align);
10804 emit_int32 (acfg, info->generic_tramp_num);
10805 emit_int32 (acfg, info->card_table_shift_bits);
10806 emit_int32 (acfg, info->card_table_mask);
10807 emit_int32 (acfg, info->tramp_page_size);
10808 emit_int32 (acfg, info->nshared_got_entries);
10809 emit_int32 (acfg, info->datafile_size);
10810 emit_int32 (acfg, 0);
10811 emit_int32 (acfg, 0);
10813 for (i = 0; i < MONO_AOT_TABLE_NUM; ++i)
10814 emit_int32 (acfg, info->table_offsets [i]);
10815 for (i = 0; i < MONO_AOT_TRAMP_NUM; ++i)
10816 emit_int32 (acfg, info->num_trampolines [i]);
10817 for (i = 0; i < MONO_AOT_TRAMP_NUM; ++i)
10818 emit_int32 (acfg, info->trampoline_got_offset_base [i]);
10819 for (i = 0; i < MONO_AOT_TRAMP_NUM; ++i)
10820 emit_int32 (acfg, info->trampoline_size [i]);
10821 for (i = 0; i < MONO_AOT_TRAMP_NUM; ++i)
10822 emit_int32 (acfg, info->tramp_page_code_offsets [i]);
10824 emit_bytes (acfg, info->aotid, 16);
10826 if (acfg->aot_opts.static_link) {
10827 emit_global_inner (acfg, acfg->static_linking_symbol, FALSE);
10828 emit_alignment (acfg, sizeof (target_mgreg_t));
10829 emit_label (acfg, acfg->static_linking_symbol);
10830 emit_pointer_2 (acfg, acfg->user_symbol_prefix, "mono_aot_file_info");
10835 * Emit a structure containing all the information not stored elsewhere.
10837 static void
10838 emit_file_info (MonoAotCompile *acfg)
10840 char *build_info;
10841 MonoAotFileInfo *info;
10843 if (acfg->aot_opts.bind_to_runtime_version) {
10844 build_info = mono_get_runtime_build_info ();
10845 emit_string_symbol (acfg, "runtime_version", build_info);
10846 g_free (build_info);
10847 } else {
10848 emit_string_symbol (acfg, "runtime_version", "");
10851 emit_string_symbol (acfg, "assembly_guid" , acfg->image->guid);
10853 /* Emit a string holding the assembly name */
10854 emit_string_symbol (acfg, "assembly_name", acfg->image->assembly->aname.name);
10856 info = g_new0 (MonoAotFileInfo, 1);
10857 init_aot_file_info (acfg, info);
10859 if (acfg->aot_opts.static_link) {
10860 char symbol [MAX_SYMBOL_SIZE];
10861 char *p;
10864 * Emit a global symbol which can be passed by an embedding app to
10865 * mono_aot_register_module (). The symbol points to a pointer to the the file info
10866 * structure.
10868 sprintf (symbol, "%smono_aot_module_%s_info", acfg->user_symbol_prefix, acfg->image->assembly->aname.name);
10870 /* Get rid of characters which cannot occur in symbols */
10871 p = symbol;
10872 for (p = symbol; *p; ++p) {
10873 if (!(isalnum (*p) || *p == '_'))
10874 *p = '_';
10876 acfg->static_linking_symbol = g_strdup (symbol);
10879 if (acfg->llvm)
10880 mono_llvm_emit_aot_file_info (info, acfg->has_jitted_code);
10881 else
10882 emit_aot_file_info (acfg, info);
10885 static void
10886 emit_blob (MonoAotCompile *acfg)
10888 acfg->blob_closed = TRUE;
10890 emit_aot_data (acfg, MONO_AOT_TABLE_BLOB, "blob", (guint8*)acfg->blob.data, acfg->blob.index);
10893 static void
10894 emit_objc_selectors (MonoAotCompile *acfg)
10896 int i;
10897 char symbol [128];
10899 if (!acfg->objc_selectors || acfg->objc_selectors->len == 0)
10900 return;
10903 * From
10904 * cat > foo.m << EOF
10905 * void *ret ()
10907 * return @selector(print:);
10909 * EOF
10912 mono_img_writer_emit_unset_mode (acfg->w);
10913 g_assert (acfg->fp);
10914 fprintf (acfg->fp, ".section __DATA,__objc_selrefs,literal_pointers,no_dead_strip\n");
10915 fprintf (acfg->fp, ".align 3\n");
10916 for (i = 0; i < acfg->objc_selectors->len; ++i) {
10917 sprintf (symbol, "L_OBJC_SELECTOR_REFERENCES_%d", i);
10918 emit_label (acfg, symbol);
10919 sprintf (symbol, "L_OBJC_METH_VAR_NAME_%d", i);
10920 emit_pointer (acfg, symbol);
10923 fprintf (acfg->fp, ".section __TEXT,__cstring,cstring_literals\n");
10924 for (i = 0; i < acfg->objc_selectors->len; ++i) {
10925 fprintf (acfg->fp, "L_OBJC_METH_VAR_NAME_%d:\n", i);
10926 fprintf (acfg->fp, ".asciz \"%s\"\n", (char*)g_ptr_array_index (acfg->objc_selectors, i));
10929 fprintf (acfg->fp, ".section __DATA,__objc_imageinfo,regular,no_dead_strip\n");
10930 fprintf (acfg->fp, ".align 3\n");
10931 fprintf (acfg->fp, "L_OBJC_IMAGE_INFO:\n");
10932 fprintf (acfg->fp, ".long 0\n");
10933 fprintf (acfg->fp, ".long 16\n");
10936 static void
10937 emit_dwarf_info (MonoAotCompile *acfg)
10939 #ifdef EMIT_DWARF_INFO
10940 int i;
10941 char symbol2 [128];
10943 /* DIEs for methods */
10944 for (i = 0; i < acfg->nmethods; ++i) {
10945 MonoCompile *cfg = acfg->cfgs [i];
10947 if (ignore_cfg (cfg))
10948 continue;
10950 // FIXME: LLVM doesn't define .Lme_...
10951 if (cfg->compile_llvm)
10952 continue;
10954 sprintf (symbol2, "%sme_%x", acfg->temp_prefix, i);
10956 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 ()));
10958 #endif
10961 #ifdef EMIT_WIN32_CODEVIEW_INFO
10962 typedef struct _CodeViewSubSectionData
10964 gchar *start_section;
10965 gchar *end_section;
10966 gchar *start_section_record;
10967 gchar *end_section_record;
10968 int section_type;
10969 int section_record_type;
10970 int section_id;
10971 } CodeViewSubsectionData;
10973 typedef struct _CodeViewCompilerVersion
10975 gint major;
10976 gint minor;
10977 gint revision;
10978 gint patch;
10979 } CodeViewCompilerVersion;
10981 #define CODEVIEW_SUBSECTION_SYMBOL_TYPE 0xF1
10982 #define CODEVIEW_SUBSECTION_RECORD_COMPILER_TYPE 0x113c
10983 #define CODEVIEW_SUBSECTION_RECORD_FUNCTION_START_TYPE 0x1147
10984 #define CODEVIEW_SUBSECTION_RECORD_FUNCTION_END_TYPE 0x114F
10985 #define CODEVIEW_CSHARP_LANGUAGE_TYPE 0x0A
10986 #define CODEVIEW_CPU_TYPE 0x0
10987 #define CODEVIEW_MAGIC_HEADER 0x4
10989 static void
10990 codeview_clear_subsection_data (CodeViewSubsectionData *section_data)
10992 g_free (section_data->start_section);
10993 g_free (section_data->end_section);
10994 g_free (section_data->start_section_record);
10995 g_free (section_data->end_section_record);
10997 memset (section_data, 0, sizeof (CodeViewSubsectionData));
11000 static void
11001 codeview_parse_compiler_version (gchar *version, CodeViewCompilerVersion *data)
11003 gint values[4] = { 0 };
11004 gint *value = values;
11006 while (*version && (value < values + G_N_ELEMENTS (values))) {
11007 if (isdigit (*version)) {
11008 *value *= 10;
11009 *value += *version - '0';
11011 else if (*version == '.') {
11012 value++;
11015 version++;
11018 data->major = values[0];
11019 data->minor = values[1];
11020 data->revision = values[2];
11021 data->patch = values[3];
11024 static void
11025 emit_codeview_start_subsection (MonoAotCompile *acfg, int section_id, int section_type, int section_record_type, CodeViewSubsectionData *section_data)
11027 // Starting a new subsection, clear old data.
11028 codeview_clear_subsection_data (section_data);
11030 // Keep subsection data.
11031 section_data->section_id = section_id;
11032 section_data->section_type = section_type;
11033 section_data->section_record_type = section_record_type;
11035 // Allocate all labels used in subsection.
11036 section_data->start_section = g_strdup_printf ("%scvs_%d", acfg->temp_prefix, section_data->section_id);
11037 section_data->end_section = g_strdup_printf ("%scvse_%d", acfg->temp_prefix, section_data->section_id);
11038 section_data->start_section_record = g_strdup_printf ("%scvsr_%d", acfg->temp_prefix, section_data->section_id);
11039 section_data->end_section_record = g_strdup_printf ("%scvsre_%d", acfg->temp_prefix, section_data->section_id);
11041 // Subsection type, function symbol.
11042 emit_int32 (acfg, section_data->section_type);
11044 // Subsection size.
11045 emit_symbol_diff (acfg, section_data->end_section, section_data->start_section, 0);
11046 emit_label (acfg, section_data->start_section);
11048 // Subsection record size.
11049 fprintf (acfg->fp, "\t.word %s - %s\n", section_data->end_section_record, section_data->start_section_record);
11050 emit_label (acfg, section_data->start_section_record);
11052 // Subsection record type.
11053 emit_int16 (acfg, section_record_type);
11056 static void
11057 emit_codeview_end_subsection (MonoAotCompile *acfg, CodeViewSubsectionData *section_data, int *section_id)
11059 g_assert (section_data->start_section);
11060 g_assert (section_data->end_section);
11061 g_assert (section_data->start_section_record);
11062 g_assert (section_data->end_section_record);
11064 emit_label (acfg, section_data->end_section_record);
11066 if (section_data->section_record_type == CODEVIEW_SUBSECTION_RECORD_FUNCTION_START_TYPE) {
11067 // Emit record length.
11068 emit_int16 (acfg, 2);
11070 // Emit specific record type end.
11071 emit_int16 (acfg, CODEVIEW_SUBSECTION_RECORD_FUNCTION_END_TYPE);
11074 emit_label (acfg, section_data->end_section);
11076 // Next subsection needs to be 4 byte aligned.
11077 emit_alignment (acfg, 4);
11079 *section_id = section_data->section_id + 1;
11080 codeview_clear_subsection_data (section_data);
11083 inline static void
11084 emit_codeview_start_symbol_subsection (MonoAotCompile *acfg, int section_id, int section_record_type, CodeViewSubsectionData *section_data)
11086 emit_codeview_start_subsection (acfg, section_id, CODEVIEW_SUBSECTION_SYMBOL_TYPE, section_record_type, section_data);
11089 inline static void
11090 emit_codeview_end_symbol_subsection (MonoAotCompile *acfg, CodeViewSubsectionData *section_data, int *section_id)
11092 emit_codeview_end_subsection (acfg, section_data, section_id);
11095 static void
11096 emit_codeview_compiler_info (MonoAotCompile *acfg, int *section_id)
11098 CodeViewSubsectionData section_data = { 0 };
11099 CodeViewCompilerVersion compiler_version = { 0 };
11101 // Start new compiler record subsection.
11102 emit_codeview_start_symbol_subsection (acfg, *section_id, CODEVIEW_SUBSECTION_RECORD_COMPILER_TYPE, &section_data);
11104 emit_int32 (acfg, CODEVIEW_CSHARP_LANGUAGE_TYPE);
11105 emit_int16 (acfg, CODEVIEW_CPU_TYPE);
11107 // Get compiler version information.
11108 codeview_parse_compiler_version (VERSION, &compiler_version);
11110 // Compiler frontend version, 4 digits.
11111 emit_int16 (acfg, compiler_version.major);
11112 emit_int16 (acfg, compiler_version.minor);
11113 emit_int16 (acfg, compiler_version.revision);
11114 emit_int16 (acfg, compiler_version.patch);
11116 // Compiler backend version, 4 digits (currently same as frontend).
11117 emit_int16 (acfg, compiler_version.major);
11118 emit_int16 (acfg, compiler_version.minor);
11119 emit_int16 (acfg, compiler_version.revision);
11120 emit_int16 (acfg, compiler_version.patch);
11122 // Compiler string.
11123 emit_string (acfg, "Mono AOT compiler");
11125 // Done with section.
11126 emit_codeview_end_symbol_subsection (acfg, &section_data, section_id);
11129 static void
11130 emit_codeview_function_info (MonoAotCompile *acfg, MonoMethod *method, int *section_id, gchar *symbol, gchar *symbol_start, gchar *symbol_end)
11132 CodeViewSubsectionData section_data = { 0 };
11133 gchar *full_method_name = NULL;
11135 // Start new function record subsection.
11136 emit_codeview_start_symbol_subsection (acfg, *section_id, CODEVIEW_SUBSECTION_RECORD_FUNCTION_START_TYPE, &section_data);
11138 // Emit 3 int 0 byte padding, currently not used.
11139 emit_zero_bytes (acfg, sizeof (int) * 3);
11141 // Emit size of function.
11142 emit_symbol_diff (acfg, symbol_end, symbol_start, 0);
11144 // Emit 3 int 0 byte padding, currently not used.
11145 emit_zero_bytes (acfg, sizeof (int) * 3);
11147 // Emit reallocation info.
11148 fprintf (acfg->fp, "\t.secrel32 %s\n", symbol);
11149 fprintf (acfg->fp, "\t.secidx %s\n", symbol);
11151 // Emit flag, currently not used.
11152 emit_zero_bytes (acfg, 1);
11154 // Emit function name, exclude signature since it should be described by own metadata.
11155 full_method_name = mono_method_full_name (method, FALSE);
11156 emit_string (acfg, full_method_name ? full_method_name : "");
11157 g_free (full_method_name);
11159 // Done with section.
11160 emit_codeview_end_symbol_subsection (acfg, &section_data, section_id);
11163 static void
11164 emit_codeview_info (MonoAotCompile *acfg)
11166 int i;
11167 int section_id = 0;
11168 gchar symbol_buffer[MAX_SYMBOL_SIZE];
11170 // Emit codeview debug info section
11171 emit_section_change (acfg, ".debug$S", 0);
11173 // Emit magic header.
11174 emit_int32 (acfg, CODEVIEW_MAGIC_HEADER);
11176 emit_codeview_compiler_info (acfg, &section_id);
11178 for (i = 0; i < acfg->nmethods; ++i) {
11179 MonoCompile *cfg = acfg->cfgs[i];
11181 if (!cfg || COMPILE_LLVM (cfg))
11182 continue;
11184 int ret = g_snprintf (symbol_buffer, G_N_ELEMENTS (symbol_buffer), "%sme_%x", acfg->temp_prefix, i);
11185 if (ret > 0 && ret < G_N_ELEMENTS (symbol_buffer))
11186 emit_codeview_function_info (acfg, cfg->method, &section_id, cfg->asm_debug_symbol, cfg->asm_symbol, symbol_buffer);
11189 #else
11190 static void
11191 emit_codeview_info (MonoAotCompile *acfg)
11194 #endif /* EMIT_WIN32_CODEVIEW_INFO */
11196 #ifdef EMIT_WIN32_UNWIND_INFO
11197 static UnwindInfoSectionCacheItem *
11198 get_cached_unwind_info_section_item_win32 (MonoAotCompile *acfg, const char *function_start, const char *function_end, GSList *unwind_ops)
11200 UnwindInfoSectionCacheItem *item = NULL;
11202 if (!acfg->unwind_info_section_cache)
11203 acfg->unwind_info_section_cache = g_list_alloc ();
11205 PUNWIND_INFO unwind_info = mono_arch_unwindinfo_alloc_unwind_info (unwind_ops);
11207 // Search for unwind info in cache.
11208 GList *list = acfg->unwind_info_section_cache;
11209 int list_size = 0;
11210 while (list && list->data) {
11211 item = (UnwindInfoSectionCacheItem*)list->data;
11212 if (!memcmp (unwind_info, item->unwind_info, sizeof (UNWIND_INFO))) {
11213 // Cache hit, return cached item.
11214 return item;
11216 list = list->next;
11217 list_size++;
11220 // Add to cache.
11221 if (acfg->unwind_info_section_cache) {
11222 item = g_new0 (UnwindInfoSectionCacheItem, 1);
11223 if (item) {
11224 // Format .xdata section label for function, used to get unwind info address RVA.
11225 // Since the unwind info is similar for most functions, the symbol will be reused.
11226 item->xdata_section_label = g_strdup_printf ("%sunwind_%d", acfg->temp_prefix, list_size);
11228 // Cache unwind info data, used when checking cache for matching unwind info. NOTE, cache takes
11229 //over ownership of unwind info.
11230 item->unwind_info = unwind_info;
11232 // Needs to be emitted once.
11233 item->xdata_section_emitted = FALSE;
11235 // Prepend to beginning of list to speed up inserts.
11236 acfg->unwind_info_section_cache = g_list_prepend (acfg->unwind_info_section_cache, (gpointer)item);
11240 return item;
11243 static void
11244 free_unwind_info_section_cache_win32 (MonoAotCompile *acfg)
11246 GList *list = acfg->unwind_info_section_cache;
11248 while (list) {
11249 UnwindInfoSectionCacheItem *item = (UnwindInfoSectionCacheItem *)list->data;
11250 if (item) {
11251 g_free (item->xdata_section_label);
11252 mono_arch_unwindinfo_free_unwind_info (item->unwind_info);
11254 g_free (item);
11255 list->data = NULL;
11258 list = list->next;
11261 g_list_free (acfg->unwind_info_section_cache);
11262 acfg->unwind_info_section_cache = NULL;
11265 static void
11266 emit_unwind_info_data_win32 (MonoAotCompile *acfg, PUNWIND_INFO unwind_info)
11268 // Emit the unwind info struct.
11269 emit_bytes (acfg, (guint8*)unwind_info, sizeof (UNWIND_INFO) - (sizeof (UNWIND_CODE) * MONO_MAX_UNWIND_CODES));
11271 // Emit all unwind codes encoded in unwind info struct.
11272 PUNWIND_CODE current_unwind_node = &unwind_info->UnwindCode[MONO_MAX_UNWIND_CODES - unwind_info->CountOfCodes];
11273 PUNWIND_CODE last_unwind_node = &unwind_info->UnwindCode[MONO_MAX_UNWIND_CODES];
11275 while (current_unwind_node < last_unwind_node) {
11276 guint8 node_count = 0;
11277 switch (current_unwind_node->UnwindOp) {
11278 case UWOP_PUSH_NONVOL:
11279 case UWOP_ALLOC_SMALL:
11280 case UWOP_SET_FPREG:
11281 case UWOP_PUSH_MACHFRAME:
11282 node_count = 1;
11283 break;
11284 case UWOP_SAVE_NONVOL:
11285 case UWOP_SAVE_XMM128:
11286 node_count = 2;
11287 break;
11288 case UWOP_SAVE_NONVOL_FAR:
11289 case UWOP_SAVE_XMM128_FAR:
11290 node_count = 3;
11291 break;
11292 case UWOP_ALLOC_LARGE:
11293 if (current_unwind_node->OpInfo == 0)
11294 node_count = 2;
11295 else
11296 node_count = 3;
11297 break;
11298 default:
11299 g_assert (!"Unknown unwind opcode.");
11302 while (node_count > 0) {
11303 g_assert (current_unwind_node < last_unwind_node);
11305 //Emit current node.
11306 emit_bytes (acfg, (guint8*)current_unwind_node, sizeof (UNWIND_CODE));
11308 node_count--;
11309 current_unwind_node++;
11314 // Emit unwind info sections for each function. Unwind info on Windows x64 is emitted into two different sections.
11315 // .pdata includes the serialized DWORD aligned RVA's of function start, end and address of serialized
11316 // UNWIND_INFO struct emitted into .xdata, see https://msdn.microsoft.com/en-us/library/ft9x1kdx.aspx.
11317 // .xdata section includes DWORD aligned serialized version of UNWIND_INFO struct, https://msdn.microsoft.com/en-us/library/ddssxxy8.aspx.
11318 static void
11319 emit_unwind_info_sections_win32 (MonoAotCompile *acfg, const char *function_start, const char *function_end, GSList *unwind_ops)
11321 char *pdata_section_label = NULL;
11323 int temp_prefix_len = (acfg->temp_prefix != NULL) ? strlen (acfg->temp_prefix) : 0;
11324 if (strncmp (function_start, acfg->temp_prefix, temp_prefix_len)) {
11325 temp_prefix_len = 0;
11328 // Format .pdata section label for function.
11329 pdata_section_label = g_strdup_printf ("%spdata_%s", acfg->temp_prefix, function_start + temp_prefix_len);
11331 UnwindInfoSectionCacheItem *cache_item = get_cached_unwind_info_section_item_win32 (acfg, function_start, function_end, unwind_ops);
11332 g_assert (cache_item && cache_item->xdata_section_label && cache_item->unwind_info);
11334 // Emit .pdata section.
11335 emit_section_change (acfg, ".pdata", 0);
11336 emit_alignment (acfg, sizeof (DWORD));
11337 emit_label (acfg, pdata_section_label);
11339 // Emit function start address RVA.
11340 fprintf (acfg->fp, "\t.long %s@IMGREL\n", function_start);
11342 // Emit function end address RVA.
11343 fprintf (acfg->fp, "\t.long %s@IMGREL\n", function_end);
11345 // Emit unwind info address RVA.
11346 fprintf (acfg->fp, "\t.long %s@IMGREL\n", cache_item->xdata_section_label);
11348 if (!cache_item->xdata_section_emitted) {
11349 // Emit .xdata section.
11350 emit_section_change (acfg, ".xdata", 0);
11351 emit_alignment (acfg, sizeof (DWORD));
11352 emit_label (acfg, cache_item->xdata_section_label);
11354 // Emit unwind info into .xdata section.
11355 emit_unwind_info_data_win32 (acfg, cache_item->unwind_info);
11356 cache_item->xdata_section_emitted = TRUE;
11359 g_free (pdata_section_label);
11361 #endif
11363 static gboolean
11364 should_emit_gsharedvt_method (MonoAotCompile *acfg, MonoMethod *method)
11366 #ifdef TARGET_WASM
11367 if (acfg->image == mono_get_corlib () && !strcmp (m_class_get_name (method->klass), "Vector`1"))
11368 /* The SIMD fallback code in Vector<T> is very large, and not likely to be used */
11369 return FALSE;
11370 #endif
11371 return TRUE;
11374 static gboolean
11375 collect_methods (MonoAotCompile *acfg)
11377 int mindex, i;
11378 MonoImage *image = acfg->image;
11380 /* Collect methods */
11381 for (i = 0; i < image->tables [MONO_TABLE_METHOD].rows; ++i) {
11382 ERROR_DECL (error);
11383 MonoMethod *method;
11384 guint32 token = MONO_TOKEN_METHOD_DEF | (i + 1);
11386 method = mono_get_method_checked (acfg->image, token, NULL, NULL, error);
11388 if (!method) {
11389 aot_printerrf (acfg, "Failed to load method 0x%x from '%s' due to %s.\n", token, image->name, mono_error_get_message (error));
11390 aot_printerrf (acfg, "Run with MONO_LOG_LEVEL=debug for more information.\n");
11391 mono_error_cleanup (error);
11392 return FALSE;
11395 /* Load all methods eagerly to skip the slower lazy loading code */
11396 mono_class_setup_methods (method->klass);
11398 if (mono_aot_mode_is_full (&acfg->aot_opts) && method->iflags & METHOD_IMPL_ATTRIBUTE_INTERNAL_CALL) {
11399 /* Compile the wrapper instead */
11400 /* We do this here instead of add_wrappers () because it is easy to do it here */
11401 MonoMethod *wrapper = mono_marshal_get_native_wrapper (method, TRUE, TRUE);
11402 method = wrapper;
11405 /* FIXME: Some mscorlib methods don't have debug info */
11407 if (acfg->aot_opts.soft_debug && !method->wrapper_type) {
11408 if (!((method->flags & METHOD_ATTRIBUTE_PINVOKE_IMPL) ||
11409 (method->iflags & METHOD_IMPL_ATTRIBUTE_RUNTIME) ||
11410 (method->flags & METHOD_ATTRIBUTE_ABSTRACT) ||
11411 (method->iflags & METHOD_IMPL_ATTRIBUTE_INTERNAL_CALL))) {
11412 if (!mono_debug_lookup_method (method)) {
11413 fprintf (stderr, "Method %s has no debug info, probably the .mdb file for the assembly is missing.\n", mono_method_get_full_name (method));
11414 exit (1);
11420 if (method->is_generic || mono_class_is_gtd (method->klass)) {
11421 /* Compile the ref shared version instead */
11422 MonoMethod *shared_method = mini_get_shared_method_full (method, SHARE_MODE_NONE, error);
11423 if (!shared_method) {
11424 /* Fails ref constraints */
11425 /* Keep the original method, compile_method () will skip it */
11426 } else {
11427 method = shared_method;
11431 /* Since we add the normal methods first, their index will be equal to their zero based token index */
11432 add_method_with_index (acfg, method, i, FALSE);
11433 acfg->method_index ++;
11436 /* gsharedvt methods */
11437 for (mindex = 0; mindex < image->tables [MONO_TABLE_METHOD].rows; ++mindex) {
11438 ERROR_DECL (error);
11439 MonoMethod *method;
11440 guint32 token = MONO_TOKEN_METHOD_DEF | (mindex + 1);
11442 if (!(acfg->opts & MONO_OPT_GSHAREDVT))
11443 continue;
11445 method = mono_get_method_checked (acfg->image, token, NULL, NULL, error);
11446 report_loader_error (acfg, error, TRUE, "Failed to load method token 0x%x due to %s\n", i, mono_error_get_message (error));
11448 if ((method->is_generic || mono_class_is_gtd (method->klass)) && should_emit_gsharedvt_method (acfg, method)) {
11449 MonoMethod *gshared;
11451 gshared = mini_get_shared_method_full (method, SHARE_MODE_GSHAREDVT, error);
11452 mono_error_assert_ok (error);
11454 add_extra_method (acfg, gshared);
11458 if (mono_aot_mode_is_full (&acfg->aot_opts) || mono_aot_mode_is_hybrid (&acfg->aot_opts))
11459 add_generic_instances (acfg);
11461 if (mono_aot_mode_is_full (&acfg->aot_opts))
11462 add_wrappers (acfg);
11463 return TRUE;
11466 static void
11467 compile_methods (MonoAotCompile *acfg)
11469 int i, methods_len;
11471 if (acfg->aot_opts.nthreads > 0) {
11472 GPtrArray *frag;
11473 int len, j;
11474 GPtrArray *threads;
11475 MonoThreadHandle *thread_handle;
11476 gpointer *user_data;
11477 MonoMethod **methods;
11479 methods_len = acfg->methods->len;
11481 len = acfg->methods->len / acfg->aot_opts.nthreads;
11482 g_assert (len > 0);
11484 * Partition the list of methods into fragments, and hand it to threads to
11485 * process.
11487 threads = g_ptr_array_new ();
11488 /* Make a copy since acfg->methods is modified by compile_method () */
11489 methods = g_new0 (MonoMethod*, methods_len);
11490 //memcpy (methods, g_ptr_array_index (acfg->methods, 0), sizeof (MonoMethod*) * methods_len);
11491 for (i = 0; i < methods_len; ++i)
11492 methods [i] = (MonoMethod *)g_ptr_array_index (acfg->methods, i);
11493 i = 0;
11494 while (i < methods_len) {
11495 ERROR_DECL (error);
11496 MonoInternalThread *thread;
11498 frag = g_ptr_array_new ();
11499 for (j = 0; j < len; ++j) {
11500 if (i < methods_len) {
11501 g_ptr_array_add (frag, methods [i]);
11502 i ++;
11506 user_data = g_new0 (gpointer, 3);
11507 user_data [0] = acfg;
11508 user_data [1] = frag;
11510 thread = mono_thread_create_internal (mono_domain_get (), (gpointer)compile_thread_main, user_data, MONO_THREAD_CREATE_FLAGS_NONE, error);
11511 mono_error_assert_ok (error);
11513 thread_handle = mono_threads_open_thread_handle (thread->handle);
11514 g_ptr_array_add (threads, thread_handle);
11516 g_free (methods);
11518 for (i = 0; i < threads->len; ++i) {
11519 mono_thread_info_wait_one_handle ((MonoThreadHandle*)g_ptr_array_index (threads, i), MONO_INFINITE_WAIT, FALSE);
11520 mono_threads_close_thread_handle ((MonoThreadHandle*)g_ptr_array_index (threads, i));
11522 } else {
11523 methods_len = 0;
11526 /* Compile methods added by compile_method () or all methods if nthreads == 0 */
11527 for (i = methods_len; i < acfg->methods->len; ++i) {
11528 /* This can add new methods to acfg->methods */
11529 compile_method (acfg, (MonoMethod *)g_ptr_array_index (acfg->methods, i));
11532 #ifdef ENABLE_LLVM
11533 if (acfg->llvm)
11534 mono_llvm_fixup_aot_module ();
11535 #endif
11538 static int
11539 compile_asm (MonoAotCompile *acfg)
11541 char *command, *objfile;
11542 char *outfile_name, *tmp_outfile_name, *llvm_ofile;
11543 const char *tool_prefix = acfg->aot_opts.tool_prefix ? acfg->aot_opts.tool_prefix : "";
11544 char *ld_flags = acfg->aot_opts.ld_flags ? acfg->aot_opts.ld_flags : g_strdup("");
11546 #ifdef TARGET_WIN32_MSVC
11547 #define AS_OPTIONS "-c -x assembler"
11548 #elif defined(TARGET_AMD64) && !defined(TARGET_MACH)
11549 #define AS_OPTIONS "--64"
11550 #elif defined(TARGET_POWERPC64)
11551 #define AS_OPTIONS "-a64 -mppc64"
11552 #elif defined(sparc) && TARGET_SIZEOF_VOID_P == 8
11553 #define AS_OPTIONS "-xarch=v9"
11554 #elif defined(TARGET_X86) && defined(TARGET_MACH)
11555 #define AS_OPTIONS "-arch i386"
11556 #elif defined(TARGET_X86) && !defined(TARGET_MACH)
11557 #define AS_OPTIONS "--32"
11558 #else
11559 #define AS_OPTIONS ""
11560 #endif
11562 #if defined(TARGET_OSX)
11563 #define AS_NAME "clang"
11564 #elif defined(TARGET_WIN32_MSVC)
11565 #define AS_NAME "clang.exe"
11566 #else
11567 #define AS_NAME "as"
11568 #endif
11570 #ifdef TARGET_WIN32_MSVC
11571 #define AS_OBJECT_FILE_SUFFIX "obj"
11572 #else
11573 #define AS_OBJECT_FILE_SUFFIX "o"
11574 #endif
11576 #if defined(sparc)
11577 #define LD_NAME "ld"
11578 #define LD_OPTIONS "-shared -G"
11579 #elif defined(__ppc__) && defined(TARGET_MACH)
11580 #define LD_NAME "gcc"
11581 #define LD_OPTIONS "-dynamiclib"
11582 #elif defined(TARGET_AMD64) && defined(TARGET_MACH)
11583 #define LD_NAME "clang"
11584 #define LD_OPTIONS "--shared"
11585 #elif defined(TARGET_WIN32_MSVC)
11586 #define LD_NAME "link.exe"
11587 #define LD_OPTIONS "/DLL /MACHINE:X64 /NOLOGO /INCREMENTAL:NO"
11588 #define LD_DEBUG_OPTIONS LD_OPTIONS " /DEBUG"
11589 #elif defined(TARGET_WIN32) && !defined(TARGET_ANDROID)
11590 #define LD_NAME "gcc"
11591 #define LD_OPTIONS "-shared"
11592 #elif defined(TARGET_X86) && defined(TARGET_MACH)
11593 #define LD_NAME "clang"
11594 #define LD_OPTIONS "-m32 -dynamiclib"
11595 #elif defined(TARGET_X86) && !defined(TARGET_MACH)
11596 #define LD_OPTIONS "-m elf_i386"
11597 #elif defined(TARGET_ARM) && !defined(TARGET_ANDROID)
11598 #define LD_NAME "gcc"
11599 #define LD_OPTIONS "--shared"
11600 #elif defined(TARGET_POWERPC64)
11601 #define LD_OPTIONS "-m elf64ppc"
11602 #endif
11604 #ifndef LD_OPTIONS
11605 #define LD_OPTIONS ""
11606 #endif
11608 if (acfg->aot_opts.asm_only) {
11609 aot_printf (acfg, "Output file: '%s'.\n", acfg->tmpfname);
11610 if (acfg->aot_opts.static_link)
11611 aot_printf (acfg, "Linking symbol: '%s'.\n", acfg->static_linking_symbol);
11612 if (acfg->llvm)
11613 aot_printf (acfg, "LLVM output file: '%s'.\n", acfg->llvm_sfile);
11614 return 0;
11617 if (acfg->aot_opts.static_link) {
11618 if (acfg->aot_opts.outfile)
11619 objfile = g_strdup_printf ("%s", acfg->aot_opts.outfile);
11620 else
11621 objfile = g_strdup_printf ("%s." AS_OBJECT_FILE_SUFFIX, acfg->image->name);
11622 } else {
11623 objfile = g_strdup_printf ("%s." AS_OBJECT_FILE_SUFFIX, acfg->tmpfname);
11626 #ifdef TARGET_OSX
11627 g_string_append (acfg->as_args, "-c -x assembler");
11628 #endif
11630 command = g_strdup_printf ("\"%s%s\" %s %s -o %s %s", tool_prefix, AS_NAME, AS_OPTIONS,
11631 acfg->as_args ? acfg->as_args->str : "",
11632 wrap_path (objfile), wrap_path (acfg->tmpfname));
11633 aot_printf (acfg, "Executing the native assembler: %s\n", command);
11634 if (execute_system (command) != 0) {
11635 g_free (command);
11636 g_free (objfile);
11637 return 1;
11640 if (acfg->llvm && !acfg->llvm_owriter) {
11641 command = g_strdup_printf ("\"%s%s\" %s %s -o %s %s", tool_prefix, AS_NAME, AS_OPTIONS,
11642 acfg->as_args ? acfg->as_args->str : "",
11643 wrap_path (acfg->llvm_ofile), wrap_path (acfg->llvm_sfile));
11644 aot_printf (acfg, "Executing the native assembler: %s\n", command);
11645 if (execute_system (command) != 0) {
11646 g_free (command);
11647 g_free (objfile);
11648 return 1;
11652 g_free (command);
11654 if (acfg->aot_opts.static_link) {
11655 aot_printf (acfg, "Output file: '%s'.\n", objfile);
11656 aot_printf (acfg, "Linking symbol: '%s'.\n", acfg->static_linking_symbol);
11657 g_free (objfile);
11658 return 0;
11661 if (acfg->aot_opts.outfile)
11662 outfile_name = g_strdup_printf ("%s", acfg->aot_opts.outfile);
11663 else
11664 outfile_name = g_strdup_printf ("%s%s", acfg->image->name, MONO_SOLIB_EXT);
11666 tmp_outfile_name = g_strdup_printf ("%s.tmp", outfile_name);
11668 if (acfg->llvm) {
11669 llvm_ofile = g_strdup_printf ("\"%s\"", acfg->llvm_ofile);
11670 } else {
11671 llvm_ofile = g_strdup ("");
11674 /* replace the ; flags separators with spaces */
11675 g_strdelimit (ld_flags, ';', ' ');
11677 if (acfg->aot_opts.llvm_only)
11678 ld_flags = g_strdup_printf ("%s %s", ld_flags, "-lstdc++");
11680 #ifdef TARGET_WIN32_MSVC
11681 g_assert (tmp_outfile_name != NULL);
11682 g_assert (objfile != NULL);
11683 command = g_strdup_printf ("\"%s%s\" %s %s /OUT:%s %s %s", tool_prefix, LD_NAME,
11684 acfg->aot_opts.nodebug ? LD_OPTIONS : LD_DEBUG_OPTIONS, ld_flags, wrap_path (tmp_outfile_name), wrap_path (objfile), wrap_path (llvm_ofile));
11685 #elif defined(LD_NAME)
11686 command = g_strdup_printf ("%s%s %s -o %s %s %s %s", tool_prefix, LD_NAME, LD_OPTIONS,
11687 wrap_path (tmp_outfile_name), wrap_path (llvm_ofile),
11688 wrap_path (g_strdup_printf ("%s." AS_OBJECT_FILE_SUFFIX, acfg->tmpfname)), ld_flags);
11689 #else
11690 // Default (linux)
11691 if (acfg->aot_opts.tool_prefix) {
11692 /* Cross compiling */
11693 command = g_strdup_printf ("\"%sld\" %s -shared -o %s %s %s %s", tool_prefix, LD_OPTIONS,
11694 wrap_path (tmp_outfile_name), wrap_path (llvm_ofile),
11695 wrap_path (g_strdup_printf ("%s." AS_OBJECT_FILE_SUFFIX, acfg->tmpfname)), ld_flags);
11696 } else {
11697 char *args = g_strdup_printf ("%s -shared -o %s %s %s %s", LD_OPTIONS,
11698 wrap_path (tmp_outfile_name), wrap_path (llvm_ofile),
11699 wrap_path (g_strdup_printf ("%s." AS_OBJECT_FILE_SUFFIX, acfg->tmpfname)), ld_flags);
11701 if (acfg->aot_opts.llvm_only) {
11702 command = g_strdup_printf ("%s %s", acfg->aot_opts.clangxx, args);
11703 } else {
11704 command = g_strdup_printf ("\"%sld\" %s", tool_prefix, args);
11706 g_free (args);
11708 #endif
11709 aot_printf (acfg, "Executing the native linker: %s\n", command);
11710 if (execute_system (command) != 0) {
11711 g_free (tmp_outfile_name);
11712 g_free (outfile_name);
11713 g_free (command);
11714 g_free (objfile);
11715 g_free (ld_flags);
11716 return 1;
11719 g_free (command);
11721 /*com = g_strdup_printf ("strip --strip-unneeded %s%s", acfg->image->name, MONO_SOLIB_EXT);
11722 printf ("Stripping the binary: %s\n", com);
11723 execute_system (com);
11724 g_free (com);*/
11726 #if defined(TARGET_ARM) && !defined(TARGET_MACH)
11728 * gas generates 'mapping symbols' each time code and data is mixed, which
11729 * happens a lot in emit_and_reloc_code (), so we need to get rid of them.
11731 command = g_strdup_printf ("\"%sstrip\" --strip-symbol=\\$a --strip-symbol=\\$d %s", wrap_path(tool_prefix), wrap_path(tmp_outfile_name));
11732 aot_printf (acfg, "Stripping the binary: %s\n", command);
11733 if (execute_system (command) != 0) {
11734 g_free (tmp_outfile_name);
11735 g_free (outfile_name);
11736 g_free (command);
11737 g_free (objfile);
11738 return 1;
11740 #endif
11742 if (0 != rename (tmp_outfile_name, outfile_name)) {
11743 if (G_FILE_ERROR_EXIST == g_file_error_from_errno (errno)) {
11744 /* Since we are rebuilding the module we need to be able to replace any old copies. Remove old file and retry rename operation. */
11745 unlink (outfile_name);
11746 rename (tmp_outfile_name, outfile_name);
11750 #if defined(TARGET_MACH)
11751 command = g_strdup_printf ("dsymutil \"%s\"", outfile_name);
11752 aot_printf (acfg, "Executing dsymutil: %s\n", command);
11753 if (execute_system (command) != 0) {
11754 return 1;
11756 #endif
11758 if (!acfg->aot_opts.save_temps)
11759 unlink (objfile);
11761 g_free (tmp_outfile_name);
11762 g_free (outfile_name);
11763 g_free (objfile);
11765 if (acfg->aot_opts.save_temps)
11766 aot_printf (acfg, "Retained input file.\n");
11767 else
11768 unlink (acfg->tmpfname);
11770 return 0;
11773 static guint8
11774 profread_byte (FILE *infile)
11776 guint8 i;
11777 int res;
11779 res = fread (&i, 1, 1, infile);
11780 g_assert (res == 1);
11781 return i;
11784 static int
11785 profread_int (FILE *infile)
11787 int i, res;
11789 res = fread (&i, 4, 1, infile);
11790 g_assert (res == 1);
11791 return i;
11794 static char*
11795 profread_string (FILE *infile)
11797 int len, res;
11798 char *pbuf;
11800 len = profread_int (infile);
11801 pbuf = (char*)g_malloc (len + 1);
11802 res = fread (pbuf, 1, len, infile);
11803 g_assert (res == len);
11804 pbuf [len] = '\0';
11805 return pbuf;
11808 static void
11809 load_profile_file (MonoAotCompile *acfg, char *filename)
11811 FILE *infile;
11812 char buf [1024];
11813 int res, len, version;
11814 char magic [32];
11816 infile = fopen (filename, "r");
11817 if (!infile) {
11818 fprintf (stderr, "Unable to open file '%s': %s.\n", filename, strerror (errno));
11819 exit (1);
11822 printf ("Using profile data file '%s'\n", filename);
11824 sprintf (magic, AOT_PROFILER_MAGIC);
11825 len = strlen (magic);
11826 res = fread (buf, 1, len, infile);
11827 magic [len] = '\0';
11828 buf [len] = '\0';
11829 if ((res != len) || strcmp (buf, magic) != 0) {
11830 printf ("Profile file has wrong header: '%s'.\n", buf);
11831 fclose (infile);
11832 exit (1);
11834 guint32 expected_version = (AOT_PROFILER_MAJOR_VERSION << 16) | AOT_PROFILER_MINOR_VERSION;
11835 version = profread_int (infile);
11836 if (version != expected_version) {
11837 printf ("Profile file has wrong version 0x%4x, expected 0x%4x.\n", version, expected_version);
11838 fclose (infile);
11839 exit (1);
11842 ProfileData *data = g_new0 (ProfileData, 1);
11843 data->images = g_hash_table_new (NULL, NULL);
11844 data->classes = g_hash_table_new (NULL, NULL);
11845 data->ginsts = g_hash_table_new (NULL, NULL);
11846 data->methods = g_hash_table_new (NULL, NULL);
11848 while (TRUE) {
11849 int type = profread_byte (infile);
11850 int id = profread_int (infile);
11852 if (type == AOTPROF_RECORD_NONE)
11853 break;
11855 switch (type) {
11856 case AOTPROF_RECORD_IMAGE: {
11857 ImageProfileData *idata = g_new0 (ImageProfileData, 1);
11858 idata->name = profread_string (infile);
11859 char *mvid = profread_string (infile);
11860 g_free (mvid);
11861 g_hash_table_insert (data->images, GINT_TO_POINTER (id), idata);
11862 break;
11864 case AOTPROF_RECORD_GINST: {
11865 int i;
11866 int len = profread_int (infile);
11868 GInstProfileData *gdata = g_new0 (GInstProfileData, 1);
11869 gdata->argc = len;
11870 gdata->argv = g_new0 (ClassProfileData*, len);
11872 for (i = 0; i < len; ++i) {
11873 int class_id = profread_int (infile);
11875 gdata->argv [i] = (ClassProfileData*)g_hash_table_lookup (data->classes, GINT_TO_POINTER (class_id));
11876 g_assert (gdata->argv [i]);
11878 g_hash_table_insert (data->ginsts, GINT_TO_POINTER (id), gdata);
11879 break;
11881 case AOTPROF_RECORD_TYPE: {
11882 int type = profread_byte (infile);
11884 switch (type) {
11885 case MONO_TYPE_CLASS: {
11886 int image_id = profread_int (infile);
11887 int ginst_id = profread_int (infile);
11888 char *class_name = profread_string (infile);
11890 ImageProfileData *image = (ImageProfileData*)g_hash_table_lookup (data->images, GINT_TO_POINTER (image_id));
11891 g_assert (image);
11893 char *p = strrchr (class_name, '.');
11894 g_assert (p);
11895 *p = '\0';
11897 ClassProfileData *cdata = g_new0 (ClassProfileData, 1);
11898 cdata->image = image;
11899 cdata->ns = g_strdup (class_name);
11900 cdata->name = g_strdup (p + 1);
11902 if (ginst_id != -1) {
11903 cdata->inst = (GInstProfileData*)g_hash_table_lookup (data->ginsts, GINT_TO_POINTER (ginst_id));
11904 g_assert (cdata->inst);
11906 g_free (class_name);
11908 g_hash_table_insert (data->classes, GINT_TO_POINTER (id), cdata);
11909 break;
11911 #if 0
11912 case MONO_TYPE_SZARRAY: {
11913 int elem_id = profread_int (infile);
11914 // FIXME:
11915 break;
11917 #endif
11918 default:
11919 g_assert_not_reached ();
11920 break;
11922 break;
11924 case AOTPROF_RECORD_METHOD: {
11925 int class_id = profread_int (infile);
11926 int ginst_id = profread_int (infile);
11927 int param_count = profread_int (infile);
11928 char *method_name = profread_string (infile);
11929 char *sig = profread_string (infile);
11931 ClassProfileData *klass = (ClassProfileData*)g_hash_table_lookup (data->classes, GINT_TO_POINTER (class_id));
11932 g_assert (klass);
11934 MethodProfileData *mdata = g_new0 (MethodProfileData, 1);
11935 mdata->id = id;
11936 mdata->klass = klass;
11937 mdata->name = method_name;
11938 mdata->signature = sig;
11939 mdata->param_count = param_count;
11941 if (ginst_id != -1) {
11942 mdata->inst = (GInstProfileData*)g_hash_table_lookup (data->ginsts, GINT_TO_POINTER (ginst_id));
11943 g_assert (mdata->inst);
11945 g_hash_table_insert (data->methods, GINT_TO_POINTER (id), mdata);
11946 break;
11948 default:
11949 printf ("%d\n", type);
11950 g_assert_not_reached ();
11951 break;
11955 fclose (infile);
11956 acfg->profile_data = g_list_append (acfg->profile_data, data);
11959 static void
11960 resolve_class (ClassProfileData *cdata);
11962 static void
11963 resolve_ginst (GInstProfileData *inst_data)
11965 int i;
11967 if (inst_data->inst)
11968 return;
11970 for (i = 0; i < inst_data->argc; ++i) {
11971 resolve_class (inst_data->argv [i]);
11972 if (!inst_data->argv [i]->klass)
11973 return;
11975 MonoType **args = g_new0 (MonoType*, inst_data->argc);
11976 for (i = 0; i < inst_data->argc; ++i)
11977 args [i] = m_class_get_byval_arg (inst_data->argv [i]->klass);
11979 inst_data->inst = mono_metadata_get_generic_inst (inst_data->argc, args);
11982 static void
11983 resolve_class (ClassProfileData *cdata)
11985 ERROR_DECL (error);
11986 MonoClass *klass;
11988 if (!cdata->image->image)
11989 return;
11991 klass = mono_class_from_name_checked (cdata->image->image, cdata->ns, cdata->name, error);
11992 if (!klass) {
11993 //printf ("[%s] %s.%s\n", cdata->image->name, cdata->ns, cdata->name);
11994 return;
11996 if (cdata->inst) {
11997 resolve_ginst (cdata->inst);
11998 if (!cdata->inst->inst)
11999 return;
12000 MonoGenericContext ctx;
12002 memset (&ctx, 0, sizeof (ctx));
12003 ctx.class_inst = cdata->inst->inst;
12004 cdata->klass = mono_class_inflate_generic_class_checked (klass, &ctx, error);
12005 } else {
12006 cdata->klass = klass;
12011 * Resolve the profile data to the corresponding loaded classes/methods etc. if possible.
12013 static void
12014 resolve_profile_data (MonoAotCompile *acfg, ProfileData *data)
12016 GHashTableIter iter;
12017 gpointer key, value;
12018 int i;
12020 if (!data)
12021 return;
12023 /* Images */
12024 GPtrArray *assemblies = mono_domain_get_assemblies (mono_get_root_domain (), FALSE);
12025 g_hash_table_iter_init (&iter, data->images);
12026 while (g_hash_table_iter_next (&iter, &key, &value)) {
12027 ImageProfileData *idata = (ImageProfileData*)value;
12029 for (i = 0; i < assemblies->len; ++i) {
12030 MonoAssembly *ass = (MonoAssembly*)g_ptr_array_index (assemblies, i);
12032 if (!strcmp (ass->aname.name, idata->name)) {
12033 idata->image = ass->image;
12034 break;
12038 g_ptr_array_free (assemblies, TRUE);
12040 /* Classes */
12041 g_hash_table_iter_init (&iter, data->classes);
12042 while (g_hash_table_iter_next (&iter, &key, &value)) {
12043 ClassProfileData *cdata = (ClassProfileData*)value;
12045 if (!cdata->image->image) {
12046 if (acfg->aot_opts.verbose)
12047 printf ("Unable to load class '%s.%s' because its image '%s' is not loaded.\n", cdata->ns, cdata->name, cdata->image->name);
12048 continue;
12051 resolve_class (cdata);
12053 if (cdata->klass)
12054 printf ("%s %s %s\n", cdata->ns, cdata->name, mono_class_full_name (cdata->klass));
12058 /* Methods */
12059 g_hash_table_iter_init (&iter, data->methods);
12060 while (g_hash_table_iter_next (&iter, &key, &value)) {
12061 MethodProfileData *mdata = (MethodProfileData*)value;
12062 MonoClass *klass;
12063 MonoMethod *m;
12064 gpointer miter;
12066 resolve_class (mdata->klass);
12067 klass = mdata->klass->klass;
12068 if (!klass) {
12069 if (acfg->aot_opts.verbose)
12070 printf ("Unable to load method '%s' because its class '%s.%s' is not loaded.\n", mdata->name, mdata->klass->ns, mdata->klass->name);
12071 continue;
12073 miter = NULL;
12074 while ((m = mono_class_get_methods (klass, &miter))) {
12075 ERROR_DECL (error);
12077 if (strcmp (m->name, mdata->name))
12078 continue;
12079 MonoMethodSignature *sig = mono_method_signature_internal (m);
12080 if (!sig)
12081 continue;
12082 if (sig->param_count != mdata->param_count)
12083 continue;
12084 if (mdata->inst) {
12085 resolve_ginst (mdata->inst);
12086 if (!mdata->inst->inst)
12087 continue;
12088 MonoGenericContext ctx;
12090 memset (&ctx, 0, sizeof (ctx));
12091 ctx.method_inst = mdata->inst->inst;
12093 m = mono_class_inflate_generic_method_checked (m, &ctx, error);
12094 if (!m)
12095 continue;
12096 sig = mono_method_signature_checked (m, error);
12097 if (!is_ok (error)) {
12098 mono_error_cleanup (error);
12099 continue;
12102 char *sig_str = mono_signature_full_name (sig);
12103 gboolean match = !strcmp (sig_str, mdata->signature);
12104 g_free (sig_str);
12105 if (!match)
12107 continue;
12108 //printf ("%s\n", mono_method_full_name (m, 1));
12109 mdata->method = m;
12110 break;
12112 if (!mdata->method) {
12113 if (acfg->aot_opts.verbose)
12114 printf ("Unable to load method '%s' from class '%s', not found.\n", mdata->name, mono_class_full_name (klass));
12119 static gboolean
12120 inst_references_image (MonoGenericInst *inst, MonoImage *image)
12122 int i;
12124 for (i = 0; i < inst->type_argc; ++i) {
12125 MonoClass *k = mono_class_from_mono_type_internal (inst->type_argv [i]);
12126 if (m_class_get_image (k) == image)
12127 return TRUE;
12128 if (mono_class_is_ginst (k)) {
12129 MonoGenericInst *kinst = mono_class_get_context (k)->class_inst;
12130 if (inst_references_image (kinst, image))
12131 return TRUE;
12134 return FALSE;
12137 static gboolean
12138 is_local_inst (MonoGenericInst *inst, MonoImage *image)
12140 int i;
12142 for (i = 0; i < inst->type_argc; ++i) {
12143 MonoClass *k = mono_class_from_mono_type_internal (inst->type_argv [i]);
12144 if (!MONO_TYPE_IS_PRIMITIVE (inst->type_argv [i]) && m_class_get_image (k) != image)
12145 return FALSE;
12147 return TRUE;
12150 static void
12151 add_profile_instances (MonoAotCompile *acfg, ProfileData *data)
12153 GHashTableIter iter;
12154 gpointer key, value;
12155 int count = 0;
12157 if (!data)
12158 return;
12160 if (acfg->aot_opts.profile_only) {
12161 /* Add methods referenced by the profile */
12162 g_hash_table_iter_init (&iter, data->methods);
12163 while (g_hash_table_iter_next (&iter, &key, &value)) {
12164 MethodProfileData *mdata = (MethodProfileData*)value;
12165 MonoMethod *m = mdata->method;
12167 if (!m)
12168 continue;
12169 if (m->is_inflated)
12170 continue;
12171 add_extra_method (acfg, m);
12172 g_hash_table_insert (acfg->profile_methods, m, m);
12173 count ++;
12178 * Add method instances 'related' to this assembly to the AOT image.
12180 g_hash_table_iter_init (&iter, data->methods);
12181 while (g_hash_table_iter_next (&iter, &key, &value)) {
12182 MethodProfileData *mdata = (MethodProfileData*)value;
12183 MonoMethod *m = mdata->method;
12184 MonoGenericContext *ctx;
12186 if (!m)
12187 continue;
12188 if (!m->is_inflated)
12189 continue;
12191 ctx = mono_method_get_context (m);
12192 /* For simplicity, add instances which reference the assembly we are compiling */
12193 if (((ctx->class_inst && inst_references_image (ctx->class_inst, acfg->image)) ||
12194 (ctx->method_inst && inst_references_image (ctx->method_inst, acfg->image))) &&
12195 !mono_method_is_generic_sharable_full (m, FALSE, FALSE, FALSE)) {
12196 //printf ("%s\n", mono_method_full_name (m, TRUE));
12197 add_extra_method (acfg, m);
12198 count ++;
12199 } else if (m_class_get_image (m->klass) == acfg->image &&
12200 ((ctx->class_inst && is_local_inst (ctx->class_inst, acfg->image)) ||
12201 (ctx->method_inst && is_local_inst (ctx->method_inst, acfg->image))) &&
12202 !mono_method_is_generic_sharable_full (m, FALSE, FALSE, FALSE)) {
12203 /* Add instances where the gtd is in the assembly and its inflated with types from this assembly or corlib */
12204 //printf ("%s\n", mono_method_full_name (m, TRUE));
12205 add_extra_method (acfg, m);
12206 count ++;
12209 * FIXME: We might skip some instances, for example:
12210 * Foo<Bar> won't be compiled when compiling Foo's assembly since it doesn't match the first case,
12211 * and it won't be compiled when compiling Bar's assembly if Foo's assembly is not loaded.
12215 printf ("Added %d methods from profile.\n", count);
12218 static void
12219 init_got_info (GotInfo *info)
12221 int i;
12223 info->patch_to_got_offset = g_hash_table_new (mono_patch_info_hash, mono_patch_info_equal);
12224 info->patch_to_got_offset_by_type = g_new0 (GHashTable*, MONO_PATCH_INFO_NUM);
12225 for (i = 0; i < MONO_PATCH_INFO_NUM; ++i)
12226 info->patch_to_got_offset_by_type [i] = g_hash_table_new (mono_patch_info_hash, mono_patch_info_equal);
12227 info->got_patches = g_ptr_array_new ();
12230 static MonoAotCompile*
12231 acfg_create (MonoAssembly *ass, guint32 opts)
12233 MonoImage *image = ass->image;
12234 MonoAotCompile *acfg;
12236 acfg = g_new0 (MonoAotCompile, 1);
12237 acfg->methods = g_ptr_array_new ();
12238 acfg->method_indexes = g_hash_table_new (NULL, NULL);
12239 acfg->method_depth = g_hash_table_new (NULL, NULL);
12240 acfg->plt_offset_to_entry = g_hash_table_new (NULL, NULL);
12241 acfg->patch_to_plt_entry = g_new0 (GHashTable*, MONO_PATCH_INFO_NUM);
12242 acfg->method_to_cfg = g_hash_table_new (NULL, NULL);
12243 acfg->token_info_hash = g_hash_table_new_full (NULL, NULL, NULL, NULL);
12244 acfg->method_to_pinvoke_import = g_hash_table_new_full (NULL, NULL, NULL, g_free);
12245 acfg->image_hash = g_hash_table_new (NULL, NULL);
12246 acfg->image_table = g_ptr_array_new ();
12247 acfg->globals = g_ptr_array_new ();
12248 acfg->image = image;
12249 acfg->opts = opts;
12250 /* TODO: Write out set of SIMD instructions used, rather than just those available */
12251 #ifndef MONO_CROSS_COMPILE
12252 acfg->simd_opts = mono_arch_cpu_enumerate_simd_versions ();
12253 #endif
12254 acfg->mempool = mono_mempool_new ();
12255 acfg->extra_methods = g_ptr_array_new ();
12256 acfg->unwind_info_offsets = g_hash_table_new (NULL, NULL);
12257 acfg->unwind_ops = g_ptr_array_new ();
12258 acfg->method_label_hash = g_hash_table_new_full (g_str_hash, g_str_equal, g_free, NULL);
12259 acfg->method_order = g_ptr_array_new ();
12260 acfg->export_names = g_hash_table_new (NULL, NULL);
12261 acfg->klass_blob_hash = g_hash_table_new (NULL, NULL);
12262 acfg->method_blob_hash = g_hash_table_new (NULL, NULL);
12263 acfg->plt_entry_debug_sym_cache = g_hash_table_new (g_str_hash, g_str_equal);
12264 acfg->gsharedvt_in_signatures = g_hash_table_new ((GHashFunc)mono_signature_hash, (GEqualFunc)mono_metadata_signature_equal);
12265 acfg->gsharedvt_out_signatures = g_hash_table_new ((GHashFunc)mono_signature_hash, (GEqualFunc)mono_metadata_signature_equal);
12266 acfg->profile_methods = g_hash_table_new (NULL, NULL);
12267 mono_os_mutex_init_recursive (&acfg->mutex);
12269 init_got_info (&acfg->got_info);
12270 init_got_info (&acfg->llvm_got_info);
12272 return acfg;
12275 static void
12276 got_info_free (GotInfo *info)
12278 int i;
12280 for (i = 0; i < MONO_PATCH_INFO_NUM; ++i)
12281 g_hash_table_destroy (info->patch_to_got_offset_by_type [i]);
12282 g_free (info->patch_to_got_offset_by_type);
12283 g_hash_table_destroy (info->patch_to_got_offset);
12284 g_ptr_array_free (info->got_patches, TRUE);
12287 static void
12288 acfg_free (MonoAotCompile *acfg)
12290 int i;
12292 mono_img_writer_destroy (acfg->w);
12293 for (i = 0; i < acfg->nmethods; ++i)
12294 if (acfg->cfgs [i])
12295 mono_destroy_compile (acfg->cfgs [i]);
12297 g_free (acfg->cfgs);
12299 g_free (acfg->static_linking_symbol);
12300 g_free (acfg->got_symbol);
12301 g_free (acfg->plt_symbol);
12302 g_ptr_array_free (acfg->methods, TRUE);
12303 g_ptr_array_free (acfg->image_table, TRUE);
12304 g_ptr_array_free (acfg->globals, TRUE);
12305 g_ptr_array_free (acfg->unwind_ops, TRUE);
12306 g_hash_table_destroy (acfg->method_indexes);
12307 g_hash_table_destroy (acfg->method_depth);
12308 g_hash_table_destroy (acfg->plt_offset_to_entry);
12309 for (i = 0; i < MONO_PATCH_INFO_NUM; ++i)
12310 g_hash_table_destroy (acfg->patch_to_plt_entry [i]);
12311 g_free (acfg->patch_to_plt_entry);
12312 g_hash_table_destroy (acfg->method_to_cfg);
12313 g_hash_table_destroy (acfg->token_info_hash);
12314 g_hash_table_destroy (acfg->method_to_pinvoke_import);
12315 g_hash_table_destroy (acfg->image_hash);
12316 g_hash_table_destroy (acfg->unwind_info_offsets);
12317 g_hash_table_destroy (acfg->method_label_hash);
12318 g_hash_table_destroy (acfg->typespec_classes);
12319 g_hash_table_destroy (acfg->export_names);
12320 g_hash_table_destroy (acfg->plt_entry_debug_sym_cache);
12321 g_hash_table_destroy (acfg->klass_blob_hash);
12322 g_hash_table_destroy (acfg->method_blob_hash);
12323 got_info_free (&acfg->got_info);
12324 got_info_free (&acfg->llvm_got_info);
12325 arch_free_unwind_info_section_cache (acfg);
12326 mono_mempool_destroy (acfg->mempool);
12327 g_free (acfg);
12330 #define WRAPPER(e,n) n,
12331 static const char* const
12332 wrapper_type_names [MONO_WRAPPER_NUM + 1] = {
12333 #include "mono/metadata/wrapper-types.h"
12334 NULL
12337 static G_GNUC_UNUSED const char*
12338 get_wrapper_type_name (int type)
12340 return wrapper_type_names [type];
12343 //#define DUMP_PLT
12344 //#define DUMP_GOT
12346 static void aot_dump (MonoAotCompile *acfg)
12348 FILE *dumpfile;
12349 char * dumpname;
12351 JsonWriter writer;
12352 mono_json_writer_init (&writer);
12354 mono_json_writer_object_begin(&writer);
12356 // Methods
12357 mono_json_writer_indent (&writer);
12358 mono_json_writer_object_key(&writer, "methods");
12359 mono_json_writer_array_begin (&writer);
12361 int i;
12362 for (i = 0; i < acfg->nmethods; ++i) {
12363 MonoCompile *cfg;
12364 MonoMethod *method;
12365 MonoClass *klass;
12367 cfg = acfg->cfgs [i];
12368 if (ignore_cfg (cfg))
12369 continue;
12371 method = cfg->orig_method;
12373 mono_json_writer_indent (&writer);
12374 mono_json_writer_object_begin(&writer);
12376 mono_json_writer_indent (&writer);
12377 mono_json_writer_object_key(&writer, "name");
12378 mono_json_writer_printf (&writer, "\"%s\",\n", method->name);
12380 mono_json_writer_indent (&writer);
12381 mono_json_writer_object_key(&writer, "signature");
12382 mono_json_writer_printf (&writer, "\"%s\",\n", mono_method_get_full_name (method));
12384 mono_json_writer_indent (&writer);
12385 mono_json_writer_object_key(&writer, "code_size");
12386 mono_json_writer_printf (&writer, "\"%d\",\n", cfg->code_size);
12388 klass = method->klass;
12390 mono_json_writer_indent (&writer);
12391 mono_json_writer_object_key(&writer, "class");
12392 mono_json_writer_printf (&writer, "\"%s\",\n", m_class_get_name (klass));
12394 mono_json_writer_indent (&writer);
12395 mono_json_writer_object_key(&writer, "namespace");
12396 mono_json_writer_printf (&writer, "\"%s\",\n", m_class_get_name_space (klass));
12398 mono_json_writer_indent (&writer);
12399 mono_json_writer_object_key(&writer, "wrapper_type");
12400 mono_json_writer_printf (&writer, "\"%s\",\n", get_wrapper_type_name(method->wrapper_type));
12402 mono_json_writer_indent_pop (&writer);
12403 mono_json_writer_indent (&writer);
12404 mono_json_writer_object_end (&writer);
12405 mono_json_writer_printf (&writer, ",\n");
12408 mono_json_writer_indent_pop (&writer);
12409 mono_json_writer_indent (&writer);
12410 mono_json_writer_array_end (&writer);
12411 mono_json_writer_printf (&writer, ",\n");
12413 // PLT entries
12414 #ifdef DUMP_PLT
12415 mono_json_writer_indent_push (&writer);
12416 mono_json_writer_indent (&writer);
12417 mono_json_writer_object_key(&writer, "plt");
12418 mono_json_writer_array_begin (&writer);
12420 for (i = 0; i < acfg->plt_offset; ++i) {
12421 MonoPltEntry *plt_entry = NULL;
12422 MonoJumpInfo *ji;
12424 if (i == 0)
12426 * The first plt entry is unused.
12428 continue;
12430 plt_entry = g_hash_table_lookup (acfg->plt_offset_to_entry, GUINT_TO_POINTER (i));
12431 ji = plt_entry->ji;
12433 mono_json_writer_indent (&writer);
12434 mono_json_writer_printf (&writer, "{ ");
12435 mono_json_writer_object_key(&writer, "symbol");
12436 mono_json_writer_printf (&writer, "\"%s\" },\n", plt_entry->symbol);
12439 mono_json_writer_indent_pop (&writer);
12440 mono_json_writer_indent (&writer);
12441 mono_json_writer_array_end (&writer);
12442 mono_json_writer_printf (&writer, ",\n");
12443 #endif
12445 // GOT entries
12446 #ifdef DUMP_GOT
12447 mono_json_writer_indent_push (&writer);
12448 mono_json_writer_indent (&writer);
12449 mono_json_writer_object_key(&writer, "got");
12450 mono_json_writer_array_begin (&writer);
12452 mono_json_writer_indent_push (&writer);
12453 for (i = 0; i < acfg->got_info.got_patches->len; ++i) {
12454 MonoJumpInfo *ji = g_ptr_array_index (acfg->got_info.got_patches, i);
12456 mono_json_writer_indent (&writer);
12457 mono_json_writer_printf (&writer, "{ ");
12458 mono_json_writer_object_key(&writer, "patch_name");
12459 mono_json_writer_printf (&writer, "\"%s\" },\n", get_patch_name (ji->type));
12462 mono_json_writer_indent_pop (&writer);
12463 mono_json_writer_indent (&writer);
12464 mono_json_writer_array_end (&writer);
12465 mono_json_writer_printf (&writer, ",\n");
12466 #endif
12468 mono_json_writer_indent_pop (&writer);
12469 mono_json_writer_indent (&writer);
12470 mono_json_writer_object_end (&writer);
12472 dumpname = g_strdup_printf ("%s.json", g_path_get_basename (acfg->image->name));
12473 dumpfile = fopen (dumpname, "w+");
12474 g_free (dumpname);
12476 fprintf (dumpfile, "%s", writer.text->str);
12477 fclose (dumpfile);
12479 mono_json_writer_destroy (&writer);
12482 static const char *preinited_jit_icalls[] = {
12483 "mono_aot_init_llvm_method",
12484 "mono_aot_init_gshared_method_this",
12485 "mono_aot_init_gshared_method_mrgctx",
12486 "mono_aot_init_gshared_method_vtable",
12487 "mono_llvm_throw_corlib_exception",
12488 "mini_llvmonly_init_vtable_slot",
12489 "mono_helper_ldstr_mscorlib"
12492 static void
12493 add_preinit_got_slots (MonoAotCompile *acfg)
12495 MonoJumpInfo *ji;
12496 int i;
12499 * Allocate the first few GOT entries to information which is needed frequently, or it is needed
12500 * during method initialization etc.
12503 ji = (MonoJumpInfo *)mono_mempool_alloc0 (acfg->mempool, sizeof (MonoJumpInfo));
12504 ji->type = MONO_PATCH_INFO_IMAGE;
12505 ji->data.image = acfg->image;
12506 get_got_offset (acfg, FALSE, ji);
12507 get_got_offset (acfg, TRUE, ji);
12509 ji = (MonoJumpInfo *)mono_mempool_alloc0 (acfg->mempool, sizeof (MonoJumpInfo));
12510 ji->type = MONO_PATCH_INFO_MSCORLIB_GOT_ADDR;
12511 get_got_offset (acfg, FALSE, ji);
12512 get_got_offset (acfg, TRUE, ji);
12514 ji = (MonoJumpInfo *)mono_mempool_alloc0 (acfg->mempool, sizeof (MonoJumpInfo));
12515 ji->type = MONO_PATCH_INFO_GC_CARD_TABLE_ADDR;
12516 get_got_offset (acfg, FALSE, ji);
12517 get_got_offset (acfg, TRUE, ji);
12519 ji = (MonoJumpInfo *)mono_mempool_alloc0 (acfg->mempool, sizeof (MonoJumpInfo));
12520 ji->type = MONO_PATCH_INFO_GC_NURSERY_START;
12521 get_got_offset (acfg, FALSE, ji);
12522 get_got_offset (acfg, TRUE, ji);
12524 ji = (MonoJumpInfo *)mono_mempool_alloc0 (acfg->mempool, sizeof (MonoJumpInfo));
12525 ji->type = MONO_PATCH_INFO_AOT_MODULE;
12526 get_got_offset (acfg, FALSE, ji);
12527 get_got_offset (acfg, TRUE, ji);
12529 ji = (MonoJumpInfo *)mono_mempool_alloc0 (acfg->mempool, sizeof (MonoJumpInfo));
12530 ji->type = MONO_PATCH_INFO_GC_NURSERY_BITS;
12531 get_got_offset (acfg, FALSE, ji);
12532 get_got_offset (acfg, TRUE, ji);
12534 ji = (MonoJumpInfo *)mono_mempool_alloc0 (acfg->mempool, sizeof (MonoJumpInfo));
12535 ji->type = MONO_PATCH_INFO_INTERRUPTION_REQUEST_FLAG;
12536 get_got_offset (acfg, FALSE, ji);
12537 get_got_offset (acfg, TRUE, ji);
12539 for (i = 0; i < TLS_KEY_NUM; i++) {
12540 ji = (MonoJumpInfo *)mono_mempool_alloc0 (acfg->mempool, sizeof (MonoJumpInfo));
12541 ji->type = MONO_PATCH_INFO_GET_TLS_TRAMP;
12542 ji->data.index = i;
12543 get_got_offset (acfg, FALSE, ji);
12544 get_got_offset (acfg, TRUE, ji);
12546 ji = (MonoJumpInfo *)mono_mempool_alloc0 (acfg->mempool, sizeof (MonoJumpInfo));
12547 ji->type = MONO_PATCH_INFO_SET_TLS_TRAMP;
12548 ji->data.index = i;
12549 get_got_offset (acfg, FALSE, ji);
12550 get_got_offset (acfg, TRUE, ji);
12553 /* Called by native-to-managed wrappers on possibly unattached threads */
12554 ji = (MonoJumpInfo *)mono_mempool_alloc0 (acfg->mempool, sizeof (MonoJumpInfo));
12555 ji->type = MONO_PATCH_INFO_JIT_ICALL_ADDR_NOCALL;
12556 ji->data.name = "mono_threads_attach_coop";
12557 get_got_offset (acfg, FALSE, ji);
12558 get_got_offset (acfg, TRUE, ji);
12560 for (i = 0; i < sizeof (preinited_jit_icalls) / sizeof (char*); ++i) {
12561 ji = (MonoJumpInfo *)mono_mempool_alloc0 (acfg->mempool, sizeof (MonoAotCompile));
12562 ji->type = MONO_PATCH_INFO_JIT_ICALL;
12563 ji->data.name = preinited_jit_icalls [i];
12564 get_got_offset (acfg, FALSE, ji);
12565 get_got_offset (acfg, TRUE, ji);
12568 acfg->nshared_got_entries = acfg->got_offset;
12571 static void
12572 mono_dedup_log_stats (MonoAotCompile *acfg)
12574 GHashTableIter iter;
12575 g_assert (acfg->dedup_stats);
12577 // If dedup_emit_mode, acfg is the dummy dedup module that consolidates
12578 // deduped modules
12579 g_hash_table_iter_init (&iter, acfg->method_to_cfg);
12580 MonoCompile *dcfg = NULL;
12581 MonoMethod *method = NULL;
12583 size_t wrappers_size_saved = 0;
12584 size_t inflated_size_saved = 0;
12585 size_t copied_singles = 0;
12586 int wrappers_saved = 0;
12587 int instances_saved = 0;
12588 int copied = 0;
12590 while (g_hash_table_iter_next (&iter, (gpointer *) &method, (gpointer *)&dcfg)) {
12591 gchar *dedup_name = mono_aot_get_mangled_method_name (method);
12592 guint count = GPOINTER_TO_UINT(g_hash_table_lookup (acfg->dedup_stats, dedup_name));
12594 if (count == 0)
12595 continue;
12597 if (acfg->dedup_emit_mode) {
12598 // Size *saved* is the size due to things not emitted.
12599 if (count < 2) {
12600 // Just moved, didn't save space / dedup
12601 copied ++;
12602 copied_singles += dcfg->code_len;
12603 } else if (method->wrapper_type != MONO_WRAPPER_NONE) {
12604 wrappers_saved ++;
12605 wrappers_size_saved += dcfg->code_len * (count - 1);
12606 } else {
12607 instances_saved ++;
12608 inflated_size_saved += dcfg->code_len * (count - 1);
12611 if (acfg->aot_opts.dedup) {
12612 if (method->wrapper_type != MONO_WRAPPER_NONE) {
12613 wrappers_saved ++;
12614 wrappers_size_saved += dcfg->code_len * count;
12615 } else {
12616 instances_saved ++;
12617 inflated_size_saved += dcfg->code_len * count;
12622 aot_printf (acfg, "Dedup Pass: Size Saved From Deduped Wrappers:\t%d methods, %zu bytes\n", wrappers_saved, wrappers_size_saved);
12623 aot_printf (acfg, "Dedup Pass: Size Saved From Inflated Methods:\t%d methods, %zu bytes\n", instances_saved, inflated_size_saved);
12624 if (acfg->dedup_emit_mode)
12625 aot_printf (acfg, "Dedup Pass: Size of Moved But Not Deduped (only 1 copy) Methods:\t%d methods, %zu bytes\n", copied, copied_singles);
12627 g_hash_table_destroy (acfg->dedup_stats);
12628 acfg->dedup_stats = NULL;
12631 // Flush the cache to tell future calls what to skip
12632 static void
12633 mono_flush_method_cache (MonoAotCompile *acfg)
12635 GHashTable *method_cache = acfg->dedup_cache;
12636 char *filename = g_strdup_printf ("%s.dedup", acfg->image->name);
12637 if (!acfg->dedup_cache_changed || !acfg->aot_opts.dedup) {
12638 g_free (filename);
12639 return;
12642 acfg->dedup_cache = NULL;
12644 FILE *cache = fopen (filename, "w");
12646 if (!cache)
12647 g_error ("Could not create cache at %s because of error: %s\n", filename, strerror (errno));
12649 GHashTableIter iter;
12650 gchar *name = NULL;
12651 g_hash_table_iter_init (&iter, method_cache);
12652 gboolean cont = TRUE;
12653 while (cont && g_hash_table_iter_next (&iter, (gpointer *) &name, NULL)) {
12654 int res = fprintf (cache, "%s\n", name);
12655 cont = res >= 0;
12657 // FIXME: don't assert if error when flushing
12658 g_assert (cont);
12660 fclose (cache);
12661 g_free (filename);
12663 // The keys are all in the imageset, nothing to free
12664 // Values are just pointers to memory owned elsewhere, or sentinels
12665 g_hash_table_destroy (method_cache);
12668 // Read in what has been emitted by previous invocations,
12669 // what can be skipped
12670 static void
12671 mono_read_method_cache (MonoAotCompile *acfg)
12673 char *filename = g_strdup_printf ("%s.dedup", acfg->image->name);
12674 // Only do once, when dedup_cache is null
12675 if (acfg->dedup_cache)
12676 goto early_exit;
12678 if (acfg->aot_opts.dedup_include || acfg->aot_opts.dedup)
12679 g_assert (acfg->dedup_stats);
12681 // only in skip mode
12682 if (!acfg->aot_opts.dedup)
12683 goto early_exit;
12685 g_assert (acfg->dedup_cache);
12687 FILE *cache;
12688 cache = fopen (filename, "r");
12689 if (!cache)
12690 goto early_exit;
12692 // Since we do pointer comparisons, and it can't be allocated at
12693 // the address 0x1 due to alignment, we use this as a sentinel
12694 gpointer other_acfg_sentinel;
12695 other_acfg_sentinel = GINT_TO_POINTER (0x1);
12697 if (fseek (cache, 0L, SEEK_END))
12698 goto cleanup;
12700 size_t fileLength;
12701 fileLength = ftell (cache);
12702 g_assert (fileLength > 0);
12704 if (fseek (cache, 0L, SEEK_SET))
12705 goto cleanup;
12707 // Avoid thousands of new malloc entries
12708 // FIXME: allocate into imageset, so we don't need to free.
12709 // put the other mangled names there too.
12710 char *bulk;
12711 bulk = g_malloc0 (fileLength * sizeof (char));
12712 size_t offset;
12713 offset = 0;
12715 while (fgets (&bulk [offset], fileLength - offset, cache)) {
12716 // strip newline
12717 char *line = &bulk [offset];
12718 size_t len = strlen (line);
12719 if (len == 0)
12720 break;
12722 if (len >= 0 && line [len] == '\n')
12723 line [len] = '\0';
12724 offset += strlen (line) + 1;
12725 g_assert (fileLength >= offset);
12727 g_hash_table_insert (acfg->dedup_cache, line, other_acfg_sentinel);
12730 cleanup:
12731 fclose (cache);
12733 early_exit:
12734 g_free (filename);
12735 return;
12738 typedef struct {
12739 GHashTable *cache;
12740 GHashTable *stats;
12741 gboolean emit_inflated_methods;
12742 MonoAssembly *inflated_assembly;
12743 } MonoAotState;
12745 static MonoAotState *
12746 alloc_aot_state (void)
12748 MonoAotState *state = g_malloc (sizeof (MonoAotState));
12749 // FIXME: Should this own the memory?
12750 state->cache = g_hash_table_new (g_str_hash, g_str_equal);
12751 state->stats = g_hash_table_new (g_str_hash, g_str_equal);
12752 // Start in "collect mode"
12753 state->emit_inflated_methods = FALSE;
12754 state->inflated_assembly = NULL;
12755 return state;
12758 static void
12759 free_aot_state (MonoAotState *astate)
12761 g_hash_table_destroy (astate->cache);
12762 g_free (astate);
12765 static void
12766 mono_add_deferred_extra_methods (MonoAotCompile *acfg, MonoAotState *astate)
12768 GHashTableIter iter;
12769 gchar *name = NULL;
12770 MonoMethod *method = NULL;
12772 acfg->dedup_emit_mode = TRUE;
12774 g_hash_table_iter_init (&iter, astate->cache);
12775 while (g_hash_table_iter_next (&iter, (gpointer *) &name, (gpointer *) &method)) {
12776 add_method_full (acfg, method, TRUE, 0);
12778 return;
12781 static void
12782 mono_setup_dedup_state (MonoAotCompile *acfg, MonoAotState **global_aot_state, MonoAssembly *ass, MonoAotState **astate, gboolean *is_dedup_dummy)
12784 if (!acfg->aot_opts.dedup_include && !acfg->aot_opts.dedup)
12785 return;
12787 if (global_aot_state && *global_aot_state && acfg->aot_opts.dedup_include) {
12788 // Thread the state through when making the inflate pass
12789 *astate = *global_aot_state;
12792 if (!*astate) {
12793 *astate = alloc_aot_state ();
12794 *global_aot_state = *astate;
12797 acfg->dedup_cache = (*astate)->cache;
12798 acfg->dedup_stats = (*astate)->stats;
12800 // fills out acfg->dedup_cache
12801 if (acfg->aot_opts.dedup)
12802 mono_read_method_cache (acfg);
12804 if (!(*astate)->inflated_assembly && acfg->aot_opts.dedup_include) {
12805 gchar **asm_path = g_strsplit (ass->image->name, G_DIR_SEPARATOR_S, 0);
12806 gchar *asm_file = NULL;
12808 // Get the last part of the path, the filename
12809 for (int i=0; asm_path [i] != NULL; i++)
12810 asm_file = asm_path [i];
12812 if (!strcmp (acfg->aot_opts.dedup_include, asm_file)) {
12813 // Save
12814 *is_dedup_dummy = TRUE;
12815 (*astate)->inflated_assembly = ass;
12817 g_strfreev (asm_path);
12818 } else if ((*astate)->inflated_assembly) {
12819 *is_dedup_dummy = (ass == (*astate)->inflated_assembly);
12823 int
12824 mono_compile_deferred_assemblies (guint32 opts, const char *aot_options, gpointer **aot_state)
12826 // create assembly, loop and add extra_methods
12827 // in add_generic_instances , rip out what's in that for loop
12828 // and apply that to this aot_state inside of mono_compile_assembly
12829 MonoAotState *astate;
12830 astate = *(MonoAotState **)aot_state;
12831 g_assert (astate);
12833 // FIXME: allow suffixes?
12834 if (!astate->inflated_assembly) {
12835 const char* inflate = strstr (aot_options, "dedup-inflate");
12836 if (!inflate)
12837 return 0;
12838 else
12839 g_error ("Error: mono was not given an assembly with the provided inflate name\n");
12842 // Switch modes
12843 astate->emit_inflated_methods = TRUE;
12845 int res = mono_compile_assembly (astate->inflated_assembly, opts, aot_options, aot_state);
12847 *aot_state = NULL;
12848 free_aot_state (astate);
12850 return res;
12853 #ifndef MONO_ARCH_HAVE_INTERP_ENTRY_TRAMPOLINE
12854 static const char* interp_in_static_sigs[] = {
12855 "bool ptr int32 ptr&",
12856 "bool ptr ptr&",
12857 "int32 int32 ptr&",
12858 "int32 int32 ptr ptr&",
12859 "int32 ptr int32 ptr",
12860 "int32 ptr int32 ptr&",
12861 "int32 ptr ptr&",
12862 "object object ptr ptr ptr",
12863 "object",
12864 "ptr int32 ptr&",
12865 "ptr ptr int32 ptr ptr ptr&",
12866 "ptr ptr int32 ptr ptr&",
12867 "ptr ptr int32 ptr&",
12868 "ptr ptr ptr int32 ptr&",
12869 "ptr ptr ptr ptr& ptr&",
12870 "ptr ptr ptr ptr ptr&",
12871 "ptr ptr ptr ptr&",
12872 "ptr ptr ptr&",
12873 "ptr ptr uint32 ptr&",
12874 "ptr uint32 ptr&",
12875 "void object ptr ptr ptr",
12876 "void ptr ptr int32 ptr ptr& ptr ptr&",
12877 "void ptr ptr int32 ptr ptr&",
12878 "void ptr ptr ptr&",
12879 "void ptr ptr&",
12880 "void ptr",
12881 "void int32 ptr&",
12882 "void uint32 ptr&",
12883 "void"
12885 #endif
12888 mono_compile_assembly (MonoAssembly *ass, guint32 opts, const char *aot_options, gpointer **global_aot_state)
12890 MonoImage *image = ass->image;
12891 int res;
12892 MonoAotCompile *acfg;
12893 char *p;
12894 TV_DECLARE (atv);
12895 TV_DECLARE (btv);
12897 acfg = acfg_create (ass, opts);
12899 memset (&acfg->aot_opts, 0, sizeof (acfg->aot_opts));
12900 acfg->aot_opts.write_symbols = TRUE;
12901 acfg->aot_opts.ntrampolines = 4096;
12902 acfg->aot_opts.nrgctx_trampolines = 4096;
12903 acfg->aot_opts.nimt_trampolines = 512;
12904 acfg->aot_opts.nrgctx_fetch_trampolines = 128;
12905 acfg->aot_opts.ngsharedvt_arg_trampolines = 512;
12906 #ifdef MONO_ARCH_HAVE_FTNPTR_ARG_TRAMPOLINE
12907 acfg->aot_opts.nftnptr_arg_trampolines = 128;
12908 #endif
12909 acfg->aot_opts.nunbox_arbitrary_trampolines = 256;
12910 acfg->aot_opts.llvm_path = g_strdup ("");
12911 acfg->aot_opts.temp_path = g_strdup ("");
12912 #ifdef MONOTOUCH
12913 acfg->aot_opts.use_trampolines_page = TRUE;
12914 #endif
12915 acfg->aot_opts.clangxx = g_strdup ("clang++");
12917 mono_aot_parse_options (aot_options, &acfg->aot_opts);
12919 // start dedup
12920 MonoAotState *astate = NULL;
12921 gboolean is_dedup_dummy = FALSE;
12922 mono_setup_dedup_state (acfg, (MonoAotState **) global_aot_state, ass, &astate, &is_dedup_dummy);
12924 // Process later
12925 if (is_dedup_dummy && astate && !astate->emit_inflated_methods)
12926 return 0;
12928 if (acfg->aot_opts.dedup_include && !is_dedup_dummy)
12929 acfg->dedup_collect_only = TRUE;
12930 // end dedup
12932 if (acfg->aot_opts.logfile) {
12933 acfg->logfile = fopen (acfg->aot_opts.logfile, "a+");
12936 if (acfg->aot_opts.data_outfile) {
12937 acfg->data_outfile = fopen (acfg->aot_opts.data_outfile, "w+");
12938 if (!acfg->data_outfile) {
12939 aot_printerrf (acfg, "Unable to create file '%s': %s\n", acfg->aot_opts.data_outfile, strerror (errno));
12940 return 1;
12942 acfg->flags = (MonoAotFileFlags)(acfg->flags | MONO_AOT_FILE_FLAG_SEPARATE_DATA);
12945 //acfg->aot_opts.print_skipped_methods = TRUE;
12947 #if !defined(MONO_ARCH_GSHAREDVT_SUPPORTED)
12948 if (acfg->opts & MONO_OPT_GSHAREDVT) {
12949 aot_printerrf (acfg, "-O=gsharedvt not supported on this platform.\n");
12950 return 1;
12952 if (acfg->aot_opts.llvm_only) {
12953 aot_printerrf (acfg, "--aot=llvmonly requires a runtime that supports gsharedvt.\n");
12954 return 1;
12956 #else
12957 if (acfg->aot_opts.llvm_only || mono_aot_mode_is_full (&acfg->aot_opts) || mono_aot_mode_is_hybrid (&acfg->aot_opts))
12958 acfg->opts |= MONO_OPT_GSHAREDVT;
12959 #endif
12961 #if !defined(ENABLE_LLVM)
12962 if (acfg->aot_opts.llvm_only) {
12963 aot_printerrf (acfg, "--aot=llvmonly requires a runtime compiled with llvm support.\n");
12964 return 1;
12966 #endif
12968 if (acfg->opts & MONO_OPT_GSHAREDVT)
12969 mono_set_generic_sharing_vt_supported (TRUE);
12971 if (acfg->dedup_collect_only)
12972 aot_printf (acfg, "Dedup collect: %s\n", image->name);
12973 else
12974 aot_printf (acfg, "Mono Ahead of Time compiler - compiling assembly %s\n", image->name);
12976 if (!acfg->aot_opts.deterministic)
12977 generate_aotid ((guint8*) &acfg->image->aotid);
12979 char *aotid = mono_guid_to_string (acfg->image->aotid);
12980 if (!acfg->dedup_collect_only)
12981 aot_printf (acfg, "AOTID %s\n", aotid);
12982 g_free (aotid);
12984 #ifndef MONO_ARCH_HAVE_FULL_AOT_TRAMPOLINES
12985 if (mono_aot_mode_is_full (&acfg->aot_opts)) {
12986 aot_printerrf (acfg, "--aot=full is not supported on this platform.\n");
12987 return 1;
12989 #endif
12991 if (acfg->aot_opts.direct_pinvoke && !acfg->aot_opts.static_link) {
12992 aot_printerrf (acfg, "The 'direct-pinvoke' AOT option also requires the 'static' AOT option.\n");
12993 return 1;
12996 if (acfg->aot_opts.static_link)
12997 acfg->aot_opts.asm_writer = TRUE;
12999 if (acfg->aot_opts.soft_debug) {
13000 MonoDebugOptions *opt = mini_get_debug_options ();
13002 opt->mdb_optimizations = TRUE;
13003 opt->gen_sdb_seq_points = TRUE;
13005 if (!mono_debug_enabled ()) {
13006 aot_printerrf (acfg, "The soft-debug AOT option requires the --debug option.\n");
13007 return 1;
13009 acfg->flags = (MonoAotFileFlags)(acfg->flags | MONO_AOT_FILE_FLAG_DEBUG);
13012 if (acfg->aot_opts.try_llvm)
13013 acfg->aot_opts.llvm = mini_llvm_init ();
13015 if (mono_use_llvm || acfg->aot_opts.llvm) {
13016 acfg->llvm = TRUE;
13017 acfg->aot_opts.asm_writer = TRUE;
13018 acfg->flags = (MonoAotFileFlags)(acfg->flags | MONO_AOT_FILE_FLAG_WITH_LLVM);
13020 if (acfg->aot_opts.soft_debug) {
13021 aot_printerrf (acfg, "The 'soft-debug' option is not supported when compiling with LLVM.\n");
13022 return 1;
13025 mini_llvm_init ();
13027 if (acfg->aot_opts.asm_only && !acfg->aot_opts.llvm_outfile) {
13028 aot_printerrf (acfg, "Compiling with LLVM and the asm-only option requires the llvm-outfile= option.\n");
13029 return 1;
13033 if (mono_aot_mode_is_full (&acfg->aot_opts)) {
13034 acfg->flags = (MonoAotFileFlags)(acfg->flags | MONO_AOT_FILE_FLAG_FULL_AOT);
13035 acfg->is_full_aot = TRUE;
13038 if (mono_aot_mode_is_interp (&acfg->aot_opts)) {
13039 acfg->flags = (MonoAotFileFlags)(acfg->flags | MONO_AOT_FILE_FLAG_INTERP);
13040 acfg->is_full_aot = TRUE;
13043 if (mini_safepoints_enabled ())
13044 acfg->flags = (MonoAotFileFlags)(acfg->flags | MONO_AOT_FILE_FLAG_SAFEPOINTS);
13046 // The methods in dedup-emit amodules must be available on runtime startup
13047 // Note: Only one such amodule can have this attribute
13048 if (astate && astate->emit_inflated_methods)
13049 acfg->flags = (MonoAotFileFlags)(acfg->flags | MONO_AOT_FILE_FLAG_EAGER_LOAD);
13052 if (acfg->aot_opts.instances_logfile_path) {
13053 acfg->instances_logfile = fopen (acfg->aot_opts.instances_logfile_path, "w");
13054 if (!acfg->instances_logfile) {
13055 aot_printerrf (acfg, "Unable to create logfile: '%s'.\n", acfg->aot_opts.instances_logfile_path);
13056 return 1;
13060 if (acfg->aot_opts.profile_files) {
13061 GList *l;
13063 for (l = acfg->aot_opts.profile_files; l; l = l->next) {
13064 load_profile_file (acfg, (char*)l->data);
13068 if (!(mono_aot_mode_is_interp (&acfg->aot_opts) && !mono_aot_mode_is_full (&acfg->aot_opts))) {
13069 for (int method_index = 0; method_index < acfg->image->tables [MONO_TABLE_METHOD].rows; ++method_index)
13070 g_ptr_array_add (acfg->method_order,GUINT_TO_POINTER (method_index));
13073 acfg->num_trampolines [MONO_AOT_TRAMP_SPECIFIC] = mono_aot_mode_is_full (&acfg->aot_opts) ? acfg->aot_opts.ntrampolines : 0;
13074 #ifdef MONO_ARCH_GSHARED_SUPPORTED
13075 acfg->num_trampolines [MONO_AOT_TRAMP_STATIC_RGCTX] = mono_aot_mode_is_full (&acfg->aot_opts) ? acfg->aot_opts.nrgctx_trampolines : 0;
13076 #endif
13077 acfg->num_trampolines [MONO_AOT_TRAMP_IMT] = mono_aot_mode_is_full (&acfg->aot_opts) ? acfg->aot_opts.nimt_trampolines : 0;
13078 #ifdef MONO_ARCH_GSHAREDVT_SUPPORTED
13079 if (acfg->opts & MONO_OPT_GSHAREDVT)
13080 acfg->num_trampolines [MONO_AOT_TRAMP_GSHAREDVT_ARG] = mono_aot_mode_is_full (&acfg->aot_opts) ? acfg->aot_opts.ngsharedvt_arg_trampolines : 0;
13081 #endif
13082 #ifdef MONO_ARCH_HAVE_FTNPTR_ARG_TRAMPOLINE
13083 acfg->num_trampolines [MONO_AOT_TRAMP_FTNPTR_ARG] = mono_aot_mode_is_interp (&acfg->aot_opts) ? acfg->aot_opts.nftnptr_arg_trampolines : 0;
13084 #endif
13085 acfg->num_trampolines [MONO_AOT_TRAMP_UNBOX_ARBITRARY] = mono_aot_mode_is_interp (&acfg->aot_opts) && mono_aot_mode_is_full (&acfg->aot_opts) ? acfg->aot_opts.nunbox_arbitrary_trampolines : 0;
13087 acfg->temp_prefix = mono_img_writer_get_temp_label_prefix (NULL);
13089 arch_init (acfg);
13091 if (mono_use_llvm || acfg->aot_opts.llvm) {
13093 * Emit all LLVM code into a separate assembly/object file and link with it
13094 * normally.
13096 if (!acfg->aot_opts.asm_only && acfg->llvm_owriter_supported) {
13097 acfg->llvm_owriter = TRUE;
13098 } else if (acfg->aot_opts.llvm_outfile) {
13099 int len = strlen (acfg->aot_opts.llvm_outfile);
13101 if (len >= 2 && acfg->aot_opts.llvm_outfile [len - 2] == '.' && acfg->aot_opts.llvm_outfile [len - 1] == 'o')
13102 acfg->llvm_owriter = TRUE;
13106 if (acfg->llvm && acfg->thumb_mixed)
13107 acfg->flags = (MonoAotFileFlags)(acfg->flags | MONO_AOT_FILE_FLAG_LLVM_THUMB);
13108 if (acfg->aot_opts.llvm_only)
13109 acfg->flags = (MonoAotFileFlags)(acfg->flags | MONO_AOT_FILE_FLAG_LLVM_ONLY);
13111 acfg->assembly_name_sym = g_strdup (acfg->image->assembly->aname.name);
13112 /* Get rid of characters which cannot occur in symbols */
13113 for (p = acfg->assembly_name_sym; *p; ++p) {
13114 if (!(isalnum (*p) || *p == '_'))
13115 *p = '_';
13118 acfg->global_prefix = g_strdup_printf ("mono_aot_%s", acfg->assembly_name_sym);
13119 acfg->plt_symbol = g_strdup_printf ("%s_plt", acfg->global_prefix);
13120 acfg->got_symbol = g_strdup_printf ("%s_got", acfg->global_prefix);
13121 if (acfg->llvm) {
13122 acfg->llvm_got_symbol = g_strdup_printf ("%s_llvm_got", acfg->global_prefix);
13123 acfg->llvm_eh_frame_symbol = g_strdup_printf ("%s_eh_frame", acfg->global_prefix);
13126 acfg->method_index = 1;
13128 if (mono_aot_mode_is_full (&acfg->aot_opts) || mono_aot_mode_is_hybrid (&acfg->aot_opts))
13129 mono_set_partial_sharing_supported (TRUE);
13131 if (!(mono_aot_mode_is_interp (&acfg->aot_opts) && !mono_aot_mode_is_full (&acfg->aot_opts))) {
13132 res = collect_methods (acfg);
13133 if (!res)
13134 return 1;
13137 // If we're emitting all of the inflated methods into a dummy
13138 // Assembly, then after extra_methods is set up, we're done
13139 // in this function.
13140 if (astate && astate->emit_inflated_methods)
13141 mono_add_deferred_extra_methods (acfg, astate);
13144 GList *l;
13146 for (l = acfg->profile_data; l; l = l->next)
13147 resolve_profile_data (acfg, (ProfileData*)l->data);
13148 for (l = acfg->profile_data; l; l = l->next)
13149 add_profile_instances (acfg, (ProfileData*)l->data);
13152 acfg->cfgs_size = acfg->methods->len + 32;
13153 acfg->cfgs = g_new0 (MonoCompile*, acfg->cfgs_size);
13155 /* PLT offset 0 is reserved for the PLT trampoline */
13156 acfg->plt_offset = 1;
13157 add_preinit_got_slots (acfg);
13159 #ifdef ENABLE_LLVM
13160 if (acfg->llvm) {
13161 llvm_acfg = acfg;
13162 LLVMModuleFlags flags = LLVM_MODULE_FLAG_DWARF;
13163 if (acfg->aot_opts.static_link)
13164 flags = (LLVMModuleFlags)(flags | LLVM_MODULE_FLAG_STATIC);
13165 if (acfg->aot_opts.llvm_only)
13166 flags = (LLVMModuleFlags)(flags | LLVM_MODULE_FLAG_LLVM_ONLY);
13167 if (acfg->aot_opts.interp)
13168 flags = (LLVMModuleFlags)(flags | LLVM_MODULE_FLAG_INTERP);
13169 mono_llvm_create_aot_module (acfg->image->assembly, acfg->global_prefix, acfg->nshared_got_entries, flags);
13171 #endif
13173 if (mono_aot_mode_is_interp (&acfg->aot_opts)) {
13174 MonoMethod *wrapper = mini_get_interp_lmf_wrapper ("mono_interp_to_native_trampoline", (gpointer) mono_interp_to_native_trampoline);
13175 add_method (acfg, wrapper);
13177 wrapper = mini_get_interp_lmf_wrapper ("mono_interp_entry_from_trampoline", (gpointer) mono_interp_entry_from_trampoline);
13178 add_method (acfg, wrapper);
13180 #ifndef MONO_ARCH_HAVE_INTERP_ENTRY_TRAMPOLINE
13181 for (int i = 0; i < sizeof (interp_in_static_sigs) / sizeof (const char *); i++) {
13182 MonoMethodSignature *sig = mono_create_icall_signature (interp_in_static_sigs [i]);
13183 sig = mono_metadata_signature_dup_full (mono_get_corlib (), sig);
13184 sig->pinvoke = FALSE;
13185 wrapper = mini_get_interp_in_wrapper (sig);
13186 add_method (acfg, wrapper);
13188 #endif
13191 TV_GETTIME (atv);
13193 compile_methods (acfg);
13195 TV_GETTIME (btv);
13197 acfg->stats.jit_time = TV_ELAPSED (atv, btv);
13199 dedup_skip_methods (acfg);
13201 if (acfg->aot_opts.dedup_include && !is_dedup_dummy)
13202 /* We only collected methods from this assembly */
13203 return 0;
13205 return emit_aot_image (acfg);
13208 static int
13209 emit_aot_image (MonoAotCompile *acfg)
13211 int i, res;
13212 TV_DECLARE (atv);
13213 TV_DECLARE (btv);
13214 char llvm_stats_msg [256];
13215 gint64 all_sizes;
13217 TV_GETTIME (atv);
13219 #ifdef ENABLE_LLVM
13220 if (acfg->llvm) {
13221 if (acfg->aot_opts.asm_only) {
13222 if (acfg->aot_opts.outfile) {
13223 acfg->tmpfname = g_strdup_printf ("%s", acfg->aot_opts.outfile);
13224 acfg->tmpbasename = g_strdup (acfg->tmpfname);
13225 } else {
13226 acfg->tmpbasename = g_strdup_printf ("%s", acfg->image->name);
13227 acfg->tmpfname = g_strdup_printf ("%s.s", acfg->tmpbasename);
13229 g_assert (acfg->aot_opts.llvm_outfile);
13230 acfg->llvm_sfile = g_strdup (acfg->aot_opts.llvm_outfile);
13231 if (acfg->llvm_owriter)
13232 acfg->llvm_ofile = g_strdup (acfg->aot_opts.llvm_outfile);
13233 else
13234 acfg->llvm_sfile = g_strdup (acfg->aot_opts.llvm_outfile);
13235 } else {
13236 gchar *temp_path;
13237 if (strcmp (acfg->aot_opts.temp_path, "") != 0) {
13238 temp_path = g_strdup (acfg->aot_opts.temp_path);
13239 } else {
13240 temp_path = g_mkdtemp (g_strdup ("mono_aot_XXXXXX"));
13241 g_assertf (temp_path, "mkdtemp failed, error = (%d) %s", errno, g_strerror (errno));
13242 acfg->temp_dir_to_delete = g_strdup (temp_path);
13245 acfg->tmpbasename = g_build_filename (temp_path, "temp", NULL);
13246 acfg->tmpfname = g_strdup_printf ("%s.s", acfg->tmpbasename);
13247 acfg->llvm_sfile = g_strdup_printf ("%s-llvm.s", acfg->tmpbasename);
13248 acfg->llvm_ofile = g_strdup_printf ("%s-llvm." AS_OBJECT_FILE_SUFFIX, acfg->tmpbasename);
13250 g_free (temp_path);
13253 #endif
13255 if (acfg->aot_opts.asm_only && !acfg->aot_opts.llvm_only) {
13256 if (acfg->aot_opts.outfile)
13257 acfg->tmpfname = g_strdup_printf ("%s", acfg->aot_opts.outfile);
13258 else
13259 acfg->tmpfname = g_strdup_printf ("%s.s", acfg->image->name);
13260 acfg->fp = fopen (acfg->tmpfname, "w+");
13261 } else {
13262 if (strcmp (acfg->aot_opts.temp_path, "") == 0) {
13263 int i = g_file_open_tmp ("mono_aot_XXXXXX", &acfg->tmpfname, NULL);
13264 acfg->fp = fdopen (i, "w+");
13265 } else {
13266 acfg->tmpbasename = g_build_filename (acfg->aot_opts.temp_path, "temp", NULL);
13267 acfg->tmpfname = g_strdup_printf ("%s.s", acfg->tmpbasename);
13268 acfg->fp = fopen (acfg->tmpfname, "w+");
13271 if (acfg->fp == 0 && !acfg->aot_opts.llvm_only) {
13272 aot_printerrf (acfg, "Unable to open file '%s': %s\n", acfg->tmpfname, strerror (errno));
13273 return 1;
13275 if (acfg->fp)
13276 acfg->w = mono_img_writer_create (acfg->fp, FALSE);
13278 /* Compute symbols for methods */
13279 for (i = 0; i < acfg->nmethods; ++i) {
13280 if (acfg->cfgs [i]) {
13281 MonoCompile *cfg = acfg->cfgs [i];
13282 int method_index = get_method_index (acfg, cfg->orig_method);
13284 if (COMPILE_LLVM (cfg))
13285 cfg->asm_symbol = g_strdup_printf ("%s%s", acfg->llvm_label_prefix, cfg->llvm_method_name);
13286 else if (acfg->global_symbols || acfg->llvm)
13287 cfg->asm_symbol = get_debug_sym (cfg->orig_method, "", acfg->method_label_hash);
13288 else
13289 cfg->asm_symbol = g_strdup_printf ("%s%sm_%x", acfg->temp_prefix, acfg->llvm_label_prefix, method_index);
13290 cfg->asm_debug_symbol = cfg->asm_symbol;
13294 if (acfg->aot_opts.dwarf_debug && acfg->aot_opts.gnu_asm) {
13296 * CLANG supports GAS .file/.loc directives, so emit line number information this way
13298 acfg->gas_line_numbers = TRUE;
13301 #ifdef EMIT_DWARF_INFO
13302 if ((!acfg->aot_opts.nodebug || acfg->aot_opts.dwarf_debug) && acfg->has_jitted_code) {
13303 if (acfg->aot_opts.dwarf_debug && !mono_debug_enabled ()) {
13304 aot_printerrf (acfg, "The dwarf AOT option requires the --debug option.\n");
13305 return 1;
13307 acfg->dwarf = mono_dwarf_writer_create (acfg->w, NULL, 0, !acfg->gas_line_numbers);
13309 #endif /* EMIT_DWARF_INFO */
13311 if (acfg->w)
13312 mono_img_writer_emit_start (acfg->w);
13314 if (acfg->dwarf)
13315 mono_dwarf_writer_emit_base_info (acfg->dwarf, g_path_get_basename (acfg->image->name), mono_unwind_get_cie_program ());
13317 if (acfg->aot_opts.dedup)
13318 mono_flush_method_cache (acfg);
13319 if (acfg->aot_opts.dedup || acfg->dedup_emit_mode)
13320 mono_dedup_log_stats (acfg);
13322 emit_code (acfg);
13324 emit_info (acfg);
13326 emit_extra_methods (acfg);
13328 emit_trampolines (acfg);
13330 emit_class_name_table (acfg);
13332 emit_got_info (acfg, FALSE);
13333 if (acfg->llvm)
13334 emit_got_info (acfg, TRUE);
13336 emit_exception_info (acfg);
13338 emit_unwind_info (acfg);
13340 emit_class_info (acfg);
13342 emit_plt (acfg);
13344 emit_image_table (acfg);
13346 emit_weak_field_indexes (acfg);
13348 emit_got (acfg);
13352 * The managed allocators are GC specific, so can't use an AOT image created by one GC
13353 * in another.
13355 const char *gc_name = mono_gc_get_gc_name ();
13356 acfg->gc_name_offset = add_to_blob (acfg, (guint8*)gc_name, strlen (gc_name) + 1);
13359 emit_blob (acfg);
13361 emit_objc_selectors (acfg);
13363 emit_globals (acfg);
13365 emit_file_info (acfg);
13367 if (acfg->dwarf) {
13368 emit_dwarf_info (acfg);
13369 mono_dwarf_writer_close (acfg->dwarf);
13370 } else {
13371 if (!acfg->aot_opts.nodebug)
13372 emit_codeview_info (acfg);
13375 emit_mem_end (acfg);
13377 if (acfg->need_pt_gnu_stack) {
13378 /* This is required so the .so doesn't have an executable stack */
13379 /* The bin writer already emits this */
13380 fprintf (acfg->fp, "\n.section .note.GNU-stack,\"\",@progbits\n");
13383 if (acfg->aot_opts.data_outfile)
13384 fclose (acfg->data_outfile);
13386 #ifdef ENABLE_LLVM
13387 if (acfg->llvm) {
13388 gboolean res;
13390 res = emit_llvm_file (acfg);
13391 if (!res)
13392 return 1;
13394 #endif
13396 emit_library_info (acfg);
13398 TV_GETTIME (btv);
13400 acfg->stats.gen_time = TV_ELAPSED (atv, btv);
13402 if (acfg->llvm)
13403 sprintf (llvm_stats_msg, ", LLVM: %d (%d%%)", acfg->stats.llvm_count, acfg->stats.mcount ? (acfg->stats.llvm_count * 100) / acfg->stats.mcount : 100);
13404 else
13405 strcpy (llvm_stats_msg, "");
13407 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;
13409 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",
13410 (int)acfg->stats.code_size, (int)(acfg->stats.code_size * 100 / all_sizes),
13411 (int)acfg->stats.info_size, (int)(acfg->stats.info_size * 100 / all_sizes),
13412 (int)acfg->stats.ex_info_size, (int)(acfg->stats.ex_info_size * 100 / all_sizes),
13413 (int)acfg->stats.unwind_info_size, (int)(acfg->stats.unwind_info_size * 100 / all_sizes),
13414 (int)acfg->stats.class_info_size, (int)(acfg->stats.class_info_size * 100 / all_sizes),
13415 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,
13416 (int)acfg->stats.got_info_size, (int)(acfg->stats.got_info_size * 100 / all_sizes),
13417 (int)acfg->stats.offsets_size, (int)(acfg->stats.offsets_size * 100 / all_sizes),
13418 (int)(acfg->got_offset * sizeof (target_mgreg_t)));
13419 aot_printf (acfg, "Compiled: %d/%d (%d%%)%s, No GOT slots: %d (%d%%), Direct calls: %d (%d%%)\n",
13420 acfg->stats.ccount, acfg->stats.mcount, acfg->stats.mcount ? (acfg->stats.ccount * 100) / acfg->stats.mcount : 100,
13421 llvm_stats_msg,
13422 acfg->stats.methods_without_got_slots, acfg->stats.mcount ? (acfg->stats.methods_without_got_slots * 100) / acfg->stats.mcount : 100,
13423 acfg->stats.direct_calls, acfg->stats.all_calls ? (acfg->stats.direct_calls * 100) / acfg->stats.all_calls : 100);
13424 if (acfg->stats.genericcount)
13425 aot_printf (acfg, "%d methods are generic (%d%%)\n", acfg->stats.genericcount, acfg->stats.mcount ? (acfg->stats.genericcount * 100) / acfg->stats.mcount : 100);
13426 if (acfg->stats.abscount)
13427 aot_printf (acfg, "%d methods contain absolute addresses (%d%%)\n", acfg->stats.abscount, acfg->stats.mcount ? (acfg->stats.abscount * 100) / acfg->stats.mcount : 100);
13428 if (acfg->stats.lmfcount)
13429 aot_printf (acfg, "%d methods contain lmf pointers (%d%%)\n", acfg->stats.lmfcount, acfg->stats.mcount ? (acfg->stats.lmfcount * 100) / acfg->stats.mcount : 100);
13430 if (acfg->stats.ocount)
13431 aot_printf (acfg, "%d methods have other problems (%d%%)\n", acfg->stats.ocount, acfg->stats.mcount ? (acfg->stats.ocount * 100) / acfg->stats.mcount : 100);
13433 TV_GETTIME (atv);
13434 if (acfg->w) {
13435 res = mono_img_writer_emit_writeout (acfg->w);
13436 if (res != 0) {
13437 acfg_free (acfg);
13438 return res;
13440 res = compile_asm (acfg);
13441 if (res != 0) {
13442 acfg_free (acfg);
13443 return res;
13446 TV_GETTIME (btv);
13447 acfg->stats.link_time = TV_ELAPSED (atv, btv);
13449 if (acfg->aot_opts.stats) {
13450 int i;
13452 aot_printf (acfg, "GOT slot distribution:\n");
13453 for (i = 0; i < MONO_PATCH_INFO_NUM; ++i)
13454 if (acfg->stats.got_slot_types [i])
13455 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]);
13456 aot_printf (acfg, "\nMethod stats:\n");
13457 aot_printf (acfg, "\tNormal: %d\n", acfg->stats.method_categories [METHOD_CAT_NORMAL]);
13458 aot_printf (acfg, "\tInstance: %d\n", acfg->stats.method_categories [METHOD_CAT_INST]);
13459 aot_printf (acfg, "\tGSharedvt: %d\n", acfg->stats.method_categories [METHOD_CAT_GSHAREDVT]);
13460 aot_printf (acfg, "\tWrapper: %d\n", acfg->stats.method_categories [METHOD_CAT_WRAPPER]);
13463 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);
13465 if (acfg->aot_opts.dump_json)
13466 aot_dump (acfg);
13468 if (!acfg->aot_opts.save_temps && acfg->temp_dir_to_delete) {
13469 char *command = g_strdup_printf ("rm -r %s", acfg->temp_dir_to_delete);
13470 execute_system (command);
13471 g_free (command);
13474 acfg_free (acfg);
13476 return 0;
13479 #else
13481 /* AOT disabled */
13483 void*
13484 mono_aot_readonly_field_override (MonoClassField *field)
13486 return NULL;
13490 mono_compile_assembly (MonoAssembly *ass, guint32 opts, const char *aot_options, gpointer **aot_state)
13492 return 0;
13495 gboolean
13496 mono_aot_is_shared_got_offset (int offset)
13498 return FALSE;
13502 mono_compile_deferred_assemblies (guint32 opts, const char *aot_options, gpointer **aot_state)
13504 g_assert_not_reached ();
13505 return 0;
13508 #endif