Remove MONO_PATCH_INFO_METHOD_REL. (#14643)
[mono-project.git] / mono / mini / aot-compiler.c
blobd75d3f934f24a2c3416570333848ffde238716bd
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 gboolean llvm_disable_self_init;
212 int nthreads;
213 int ntrampolines;
214 int nrgctx_trampolines;
215 int nimt_trampolines;
216 int ngsharedvt_arg_trampolines;
217 int nftnptr_arg_trampolines;
218 int nrgctx_fetch_trampolines;
219 int nunbox_arbitrary_trampolines;
220 gboolean print_skipped_methods;
221 gboolean stats;
222 gboolean verbose;
223 gboolean deterministic;
224 char *tool_prefix;
225 char *ld_flags;
226 char *mtriple;
227 char *llvm_path;
228 char *temp_path;
229 char *instances_logfile_path;
230 char *logfile;
231 char *llvm_opts;
232 char *llvm_llc;
233 gboolean dump_json;
234 gboolean profile_only;
235 gboolean no_opt;
236 char *clangxx;
237 char *depfile;
238 } MonoAotOptions;
240 typedef enum {
241 METHOD_CAT_NORMAL,
242 METHOD_CAT_GSHAREDVT,
243 METHOD_CAT_INST,
244 METHOD_CAT_WRAPPER,
245 METHOD_CAT_NUM
246 } MethodCategory;
248 typedef struct MonoAotStats {
249 int ccount, mcount, lmfcount, abscount, gcount, ocount, genericcount;
250 gint64 code_size, method_info_size, ex_info_size, unwind_info_size, got_size, class_info_size, got_info_size, plt_size, blob_size;
251 int methods_without_got_slots, direct_calls, all_calls, llvm_count;
252 int got_slots, offsets_size;
253 int method_categories [METHOD_CAT_NUM];
254 int got_slot_types [MONO_PATCH_INFO_NUM];
255 int got_slot_info_sizes [MONO_PATCH_INFO_NUM];
256 int jit_time, gen_time, link_time;
257 int method_ref_count, method_ref_size;
258 int class_ref_count, class_ref_size;
259 int ginst_count, ginst_size;
260 } MonoAotStats;
262 typedef struct GotInfo {
263 GHashTable *patch_to_got_offset;
264 GHashTable **patch_to_got_offset_by_type;
265 GPtrArray *got_patches;
266 } GotInfo;
268 #ifdef EMIT_WIN32_UNWIND_INFO
269 typedef struct _UnwindInfoSectionCacheItem {
270 char *xdata_section_label;
271 PUNWIND_INFO unwind_info;
272 gboolean xdata_section_emitted;
273 } UnwindInfoSectionCacheItem;
274 #endif
276 typedef struct MonoAotCompile {
277 MonoImage *image;
278 GPtrArray *methods;
279 GHashTable *method_indexes;
280 GHashTable *method_depth;
281 MonoCompile **cfgs;
282 int cfgs_size;
283 GHashTable **patch_to_plt_entry;
284 GHashTable *plt_offset_to_entry;
285 //GHashTable *patch_to_got_offset;
286 //GHashTable **patch_to_got_offset_by_type;
287 //GPtrArray *got_patches;
288 GotInfo got_info, llvm_got_info;
289 GHashTable *image_hash;
290 GHashTable *method_to_cfg;
291 GHashTable *token_info_hash;
292 GHashTable *method_to_pinvoke_import;
293 GHashTable *method_to_external_icall_symbol_name;
294 GPtrArray *extra_methods;
295 GPtrArray *image_table;
296 GPtrArray *globals;
297 GPtrArray *method_order;
298 GHashTable *dedup_stats;
299 GHashTable *dedup_cache;
300 gboolean dedup_cache_changed;
301 GHashTable *export_names;
302 /* Maps MonoClass* -> blob offset */
303 GHashTable *klass_blob_hash;
304 /* Maps MonoMethod* -> blob offset */
305 GHashTable *method_blob_hash;
306 /* Maps MonoGenericInst* -> blob offset */
307 GHashTable *ginst_blob_hash;
308 GHashTable *gsharedvt_in_signatures;
309 GHashTable *gsharedvt_out_signatures;
310 guint32 *plt_got_info_offsets;
311 guint32 got_offset, llvm_got_offset, plt_offset, plt_got_offset_base, nshared_got_entries;
312 /* Number of GOT entries reserved for trampolines */
313 guint32 num_trampoline_got_entries;
314 guint32 tramp_page_size;
316 guint32 table_offsets [MONO_AOT_TABLE_NUM];
317 guint32 num_trampolines [MONO_AOT_TRAMP_NUM];
318 guint32 trampoline_got_offset_base [MONO_AOT_TRAMP_NUM];
319 guint32 trampoline_size [MONO_AOT_TRAMP_NUM];
320 guint32 tramp_page_code_offsets [MONO_AOT_TRAMP_NUM];
322 MonoAotOptions aot_opts;
323 guint32 nmethods;
324 guint32 nextra_methods;
325 guint32 opts;
326 guint32 simd_opts;
327 MonoMemPool *mempool;
328 MonoAotStats stats;
329 int method_index;
330 char *static_linking_symbol;
331 mono_mutex_t mutex;
332 gboolean gas_line_numbers;
333 /* Whenever to emit an object file directly from llc */
334 gboolean llvm_owriter;
335 gboolean llvm_owriter_supported;
336 MonoImageWriter *w;
337 MonoDwarfWriter *dwarf;
338 FILE *fp;
339 char *tmpbasename;
340 char *tmpfname;
341 char *temp_dir_to_delete;
342 char *llvm_sfile;
343 char *llvm_ofile;
344 GSList *cie_program;
345 GHashTable *unwind_info_offsets;
346 GPtrArray *unwind_ops;
347 guint32 unwind_info_offset;
348 char *global_prefix;
349 char *got_symbol;
350 char *llvm_got_symbol;
351 char *plt_symbol;
352 char *llvm_eh_frame_symbol;
353 GHashTable *method_label_hash;
354 const char *temp_prefix;
355 const char *user_symbol_prefix;
356 const char *llvm_label_prefix;
357 const char *inst_directive;
358 int align_pad_value;
359 guint32 label_generator;
360 gboolean llvm;
361 gboolean has_jitted_code;
362 gboolean is_full_aot;
363 gboolean dedup_collect_only;
364 MonoAotFileFlags flags;
365 MonoDynamicStream blob;
366 gboolean blob_closed;
367 GHashTable *typespec_classes;
368 GString *llc_args;
369 GString *as_args;
370 char *assembly_name_sym;
371 GHashTable *plt_entry_debug_sym_cache;
372 gboolean thumb_mixed, need_no_dead_strip, need_pt_gnu_stack;
373 GHashTable *ginst_hash;
374 GHashTable *dwarf_ln_filenames;
375 gboolean global_symbols;
376 int objc_selector_index, objc_selector_index_2;
377 GPtrArray *objc_selectors;
378 GHashTable *objc_selector_to_index;
379 GList *profile_data;
380 GHashTable *profile_methods;
381 #ifdef EMIT_WIN32_UNWIND_INFO
382 GList *unwind_info_section_cache;
383 #endif
384 FILE *logfile;
385 FILE *instances_logfile;
386 FILE *data_outfile;
387 int datafile_offset;
388 int gc_name_offset;
389 // In this mode, we are emitting dedupable methods that we encounter
390 gboolean dedup_emit_mode;
391 } MonoAotCompile;
393 typedef struct {
394 int plt_offset;
395 char *symbol, *llvm_symbol, *debug_sym;
396 MonoJumpInfo *ji;
397 gboolean jit_used, llvm_used;
398 } MonoPltEntry;
400 #define mono_acfg_lock(acfg) mono_os_mutex_lock (&((acfg)->mutex))
401 #define mono_acfg_unlock(acfg) mono_os_mutex_unlock (&((acfg)->mutex))
403 /* This points to the current acfg in LLVM mode */
404 static MonoAotCompile *llvm_acfg;
406 /* Cache of decoded method external icall symbol names. */
407 /* Owned by acfg, but kept in this static as well since it is */
408 /* accessed by code paths not having access to acfg. */
409 static GHashTable *method_to_external_icall_symbol_name;
411 // This, instead of an array of pointers, to optimize away a pointer and a relocation per string.
412 #define MSGSTRFIELD(line) MSGSTRFIELD1(line)
413 #define MSGSTRFIELD1(line) str##line
414 static const struct msgstr_t {
415 #define PATCH_INFO(a,b) char MSGSTRFIELD(__LINE__) [sizeof (b)];
416 #include "patch-info.h"
417 #undef PATCH_INFO
418 } opstr = {
419 #define PATCH_INFO(a,b) b,
420 #include "patch-info.h"
421 #undef PATCH_INFO
423 static const gint16 opidx [] = {
424 #define PATCH_INFO(a,b) offsetof (struct msgstr_t, MSGSTRFIELD(__LINE__)),
425 #include "patch-info.h"
426 #undef PATCH_INFO
429 static G_GNUC_UNUSED const char*
430 get_patch_name (int info)
432 return (const char*)&opstr + opidx [info];
435 static int
436 emit_aot_image (MonoAotCompile *acfg);
438 static void
439 mono_flush_method_cache (MonoAotCompile *acfg);
441 static void
442 mono_read_method_cache (MonoAotCompile *acfg);
444 static guint32
445 get_unwind_info_offset (MonoAotCompile *acfg, guint8 *encoded, guint32 encoded_len);
447 static char*
448 get_plt_entry_debug_sym (MonoAotCompile *acfg, MonoJumpInfo *ji, GHashTable *cache);
450 static void
451 add_gsharedvt_wrappers (MonoAotCompile *acfg, MonoMethodSignature *sig, gboolean gsharedvt_in, gboolean gsharedvt_out, gboolean interp_in);
453 static void
454 add_profile_instances (MonoAotCompile *acfg, ProfileData *data);
456 static inline gboolean
457 ignore_cfg (MonoCompile *cfg)
459 return !cfg || cfg->skip;
462 static void
463 aot_printf (MonoAotCompile *acfg, const gchar *format, ...)
465 FILE *output;
466 va_list args;
468 if (acfg->logfile)
469 output = acfg->logfile;
470 else
471 output = stdout;
473 va_start (args, format);
474 vfprintf (output, format, args);
475 va_end (args);
478 static void
479 aot_printerrf (MonoAotCompile *acfg, const gchar *format, ...)
481 FILE *output;
482 va_list args;
484 if (acfg->logfile)
485 output = acfg->logfile;
486 else
487 output = stderr;
489 va_start (args, format);
490 vfprintf (output, format, args);
491 va_end (args);
494 static void
495 report_loader_error (MonoAotCompile *acfg, MonoError *error, gboolean fatal, const char *format, ...)
497 FILE *output;
498 va_list args;
500 if (mono_error_ok (error))
501 return;
503 if (acfg->logfile)
504 output = acfg->logfile;
505 else
506 output = stderr;
508 va_start (args, format);
509 vfprintf (output, format, args);
510 va_end (args);
511 mono_error_cleanup (error);
513 if (acfg->is_full_aot && fatal) {
514 fprintf (output, "FullAOT cannot continue if there are loader errors.\n");
515 exit (1);
519 /* Wrappers around the image writer functions */
521 #define MAX_SYMBOL_SIZE 256
523 static inline const char *
524 mangle_symbol (const char * symbol, char * mangled_symbol, gsize length)
526 gsize needed_size = length;
528 g_assert (NULL != symbol);
529 g_assert (NULL != mangled_symbol);
530 g_assert (0 != length);
532 #if defined(TARGET_WIN32) && defined(TARGET_X86)
533 if (symbol && '_' != symbol [0]) {
534 needed_size = g_snprintf (mangled_symbol, length, "_%s", symbol);
535 } else {
536 needed_size = g_snprintf (mangled_symbol, length, "%s", symbol);
538 #else
539 needed_size = g_snprintf (mangled_symbol, length, "%s", symbol);
540 #endif
542 g_assert (0 <= needed_size && needed_size < length);
543 return mangled_symbol;
546 static inline char *
547 mangle_symbol_alloc (const char * symbol)
549 g_assert (NULL != symbol);
551 #if defined(TARGET_WIN32) && defined(TARGET_X86)
552 if (symbol && '_' != symbol [0]) {
553 return g_strdup_printf ("_%s", symbol);
555 else {
556 return g_strdup_printf ("%s", symbol);
558 #else
559 return g_strdup_printf ("%s", symbol);
560 #endif
563 static inline void
564 emit_section_change (MonoAotCompile *acfg, const char *section_name, int subsection_index)
566 mono_img_writer_emit_section_change (acfg->w, section_name, subsection_index);
569 #if defined(TARGET_WIN32) && defined(TARGET_X86)
571 static inline void
572 emit_local_symbol (MonoAotCompile *acfg, const char *name, const char *end_label, gboolean func)
574 const char * mangled_symbol_name = name;
575 char * mangled_symbol_name_alloc = NULL;
577 if (TRUE == func) {
578 mangled_symbol_name_alloc = mangle_symbol_alloc (name);
579 mangled_symbol_name = mangled_symbol_name_alloc;
582 if (name != mangled_symbol_name && 0 != g_strcasecmp (name, mangled_symbol_name)) {
583 mono_img_writer_emit_label (acfg->w, mangled_symbol_name);
585 mono_img_writer_emit_local_symbol (acfg->w, mangled_symbol_name, end_label, func);
587 if (NULL != mangled_symbol_name_alloc) {
588 g_free (mangled_symbol_name_alloc);
592 #else
594 static inline void
595 emit_local_symbol (MonoAotCompile *acfg, const char *name, const char *end_label, gboolean func)
597 mono_img_writer_emit_local_symbol (acfg->w, name, end_label, func);
600 #endif
602 static inline void
603 emit_label (MonoAotCompile *acfg, const char *name)
605 mono_img_writer_emit_label (acfg->w, name);
608 static inline void
609 emit_bytes (MonoAotCompile *acfg, const guint8* buf, int size)
611 mono_img_writer_emit_bytes (acfg->w, buf, size);
614 static inline void
615 emit_string (MonoAotCompile *acfg, const char *value)
617 mono_img_writer_emit_string (acfg->w, value);
620 static inline void
621 emit_line (MonoAotCompile *acfg)
623 mono_img_writer_emit_line (acfg->w);
626 static inline void
627 emit_alignment (MonoAotCompile *acfg, int size)
629 mono_img_writer_emit_alignment (acfg->w, size);
632 static inline void
633 emit_alignment_code (MonoAotCompile *acfg, int size)
635 if (acfg->align_pad_value)
636 mono_img_writer_emit_alignment_fill (acfg->w, size, acfg->align_pad_value);
637 else
638 mono_img_writer_emit_alignment (acfg->w, size);
641 static inline void
642 emit_padding (MonoAotCompile *acfg, int size)
644 int i;
645 guint8 buf [16];
647 if (acfg->align_pad_value) {
648 for (i = 0; i < 16; ++i)
649 buf [i] = acfg->align_pad_value;
650 } else {
651 memset (buf, 0, sizeof (buf));
654 for (i = 0; i < size; i += 16) {
655 if (size - i < 16)
656 emit_bytes (acfg, buf, size - i);
657 else
658 emit_bytes (acfg, buf, 16);
662 static inline void
663 emit_pointer (MonoAotCompile *acfg, const char *target)
665 mono_img_writer_emit_pointer (acfg->w, target);
668 static inline void
669 emit_pointer_2 (MonoAotCompile *acfg, const char *prefix, const char *target)
671 if (prefix [0] != '\0') {
672 char *s = g_strdup_printf ("%s%s", prefix, target);
673 mono_img_writer_emit_pointer (acfg->w, s);
674 g_free (s);
675 } else {
676 mono_img_writer_emit_pointer (acfg->w, target);
680 static inline void
681 emit_int16 (MonoAotCompile *acfg, int value)
683 mono_img_writer_emit_int16 (acfg->w, value);
686 static inline void
687 emit_int32 (MonoAotCompile *acfg, int value)
689 mono_img_writer_emit_int32 (acfg->w, value);
692 static inline void
693 emit_symbol_diff (MonoAotCompile *acfg, const char *end, const char* start, int offset)
695 mono_img_writer_emit_symbol_diff (acfg->w, end, start, offset);
698 static inline void
699 emit_zero_bytes (MonoAotCompile *acfg, int num)
701 mono_img_writer_emit_zero_bytes (acfg->w, num);
704 static inline void
705 emit_byte (MonoAotCompile *acfg, guint8 val)
707 mono_img_writer_emit_byte (acfg->w, val);
710 #if defined(TARGET_WIN32) && defined(TARGET_X86)
712 static G_GNUC_UNUSED void
713 emit_global_inner (MonoAotCompile *acfg, const char *name, gboolean func)
715 const char * mangled_symbol_name = name;
716 char * mangled_symbol_name_alloc = NULL;
718 mangled_symbol_name_alloc = mangle_symbol_alloc (name);
719 mangled_symbol_name = mangled_symbol_name_alloc;
721 if (0 != g_strcasecmp (name, mangled_symbol_name)) {
722 mono_img_writer_emit_label (acfg->w, mangled_symbol_name);
724 mono_img_writer_emit_global (acfg->w, mangled_symbol_name, func);
726 if (NULL != mangled_symbol_name_alloc) {
727 g_free (mangled_symbol_name_alloc);
731 #else
733 static G_GNUC_UNUSED void
734 emit_global_inner (MonoAotCompile *acfg, const char *name, gboolean func)
736 mono_img_writer_emit_global (acfg->w, name, func);
739 #endif
741 static inline gboolean
742 link_shared_library (MonoAotCompile *acfg)
744 return !acfg->aot_opts.static_link && !acfg->aot_opts.asm_only;
747 static inline gboolean
748 add_to_global_symbol_table (MonoAotCompile *acfg)
750 #ifdef TARGET_WIN32_MSVC
751 return acfg->aot_opts.no_dlsym || link_shared_library (acfg);
752 #else
753 return acfg->aot_opts.no_dlsym;
754 #endif
757 static void
758 emit_global (MonoAotCompile *acfg, const char *name, gboolean func)
760 if (add_to_global_symbol_table (acfg))
761 g_ptr_array_add (acfg->globals, g_strdup (name));
763 if (acfg->aot_opts.no_dlsym) {
764 mono_img_writer_emit_local_symbol (acfg->w, name, NULL, func);
765 } else {
766 emit_global_inner (acfg, name, func);
770 static void
771 emit_symbol_size (MonoAotCompile *acfg, const char *name, const char *end_label)
773 mono_img_writer_emit_symbol_size (acfg->w, name, end_label);
776 /* Emit a symbol which is referenced by the MonoAotFileInfo structure */
777 static void
778 emit_info_symbol (MonoAotCompile *acfg, const char *name, gboolean func)
780 char symbol [MAX_SYMBOL_SIZE];
782 if (acfg->llvm) {
783 emit_label (acfg, name);
784 /* LLVM generated code references this */
785 sprintf (symbol, "%s%s%s", acfg->user_symbol_prefix, acfg->global_prefix, name);
786 emit_label (acfg, symbol);
788 #ifndef TARGET_WIN32_MSVC
789 emit_global_inner (acfg, symbol, FALSE);
790 #else
791 emit_global_inner (acfg, symbol, func);
792 #endif
793 } else {
794 emit_label (acfg, name);
798 static void
799 emit_string_symbol (MonoAotCompile *acfg, const char *name, const char *value)
801 if (acfg->llvm) {
802 mono_llvm_emit_aot_data (name, (guint8*)value, strlen (value) + 1);
803 return;
806 mono_img_writer_emit_section_change (acfg->w, RODATA_SECT, 1);
807 #ifdef TARGET_MACH
808 /* On apple, all symbols need to be aligned to avoid warnings from ld */
809 emit_alignment (acfg, 4);
810 #endif
811 mono_img_writer_emit_label (acfg->w, name);
812 mono_img_writer_emit_string (acfg->w, value);
815 static G_GNUC_UNUSED void
816 emit_uleb128 (MonoAotCompile *acfg, guint32 value)
818 do {
819 guint8 b = value & 0x7f;
820 value >>= 7;
821 if (value != 0) /* more bytes to come */
822 b |= 0x80;
823 emit_byte (acfg, b);
824 } while (value);
827 static G_GNUC_UNUSED void
828 emit_sleb128 (MonoAotCompile *acfg, gint64 value)
830 gboolean more = 1;
831 gboolean negative = (value < 0);
832 guint32 size = 64;
833 guint8 byte;
835 while (more) {
836 byte = value & 0x7f;
837 value >>= 7;
838 /* the following is unnecessary if the
839 * implementation of >>= uses an arithmetic rather
840 * than logical shift for a signed left operand
842 if (negative)
843 /* sign extend */
844 value |= - ((gint64)1 <<(size - 7));
845 /* sign bit of byte is second high order bit (0x40) */
846 if ((value == 0 && !(byte & 0x40)) ||
847 (value == -1 && (byte & 0x40)))
848 more = 0;
849 else
850 byte |= 0x80;
851 emit_byte (acfg, byte);
855 static G_GNUC_UNUSED void
856 encode_uleb128 (guint32 value, guint8 *buf, guint8 **endbuf)
858 guint8 *p = buf;
860 do {
861 guint8 b = value & 0x7f;
862 value >>= 7;
863 if (value != 0) /* more bytes to come */
864 b |= 0x80;
865 *p ++ = b;
866 } while (value);
868 *endbuf = p;
871 static G_GNUC_UNUSED void
872 encode_sleb128 (gint32 value, guint8 *buf, guint8 **endbuf)
874 gboolean more = 1;
875 gboolean negative = (value < 0);
876 guint32 size = 32;
877 guint8 byte;
878 guint8 *p = buf;
880 while (more) {
881 byte = value & 0x7f;
882 value >>= 7;
883 /* the following is unnecessary if the
884 * implementation of >>= uses an arithmetic rather
885 * than logical shift for a signed left operand
887 if (negative)
888 /* sign extend */
889 value |= - (1 <<(size - 7));
890 /* sign bit of byte is second high order bit (0x40) */
891 if ((value == 0 && !(byte & 0x40)) ||
892 (value == -1 && (byte & 0x40)))
893 more = 0;
894 else
895 byte |= 0x80;
896 *p ++= byte;
899 *endbuf = p;
902 static void
903 encode_int (gint32 val, guint8 *buf, guint8 **endbuf)
905 // FIXME: Big-endian
906 buf [0] = (val >> 0) & 0xff;
907 buf [1] = (val >> 8) & 0xff;
908 buf [2] = (val >> 16) & 0xff;
909 buf [3] = (val >> 24) & 0xff;
911 *endbuf = buf + 4;
914 static void
915 encode_int16 (guint16 val, guint8 *buf, guint8 **endbuf)
917 buf [0] = (val >> 0) & 0xff;
918 buf [1] = (val >> 8) & 0xff;
920 *endbuf = buf + 2;
923 static void
924 encode_string (const char *s, guint8 *buf, guint8 **endbuf)
926 int len = strlen (s);
928 memcpy (buf, s, len + 1);
929 *endbuf = buf + len + 1;
932 static void
933 emit_unset_mode (MonoAotCompile *acfg)
935 mono_img_writer_emit_unset_mode (acfg->w);
938 static G_GNUC_UNUSED void
939 emit_set_thumb_mode (MonoAotCompile *acfg)
941 emit_unset_mode (acfg);
942 fprintf (acfg->fp, ".code 16\n");
945 static G_GNUC_UNUSED void
946 emit_set_arm_mode (MonoAotCompile *acfg)
948 emit_unset_mode (acfg);
949 fprintf (acfg->fp, ".code 32\n");
952 static inline void
953 emit_code_bytes (MonoAotCompile *acfg, const guint8* buf, int size)
955 #ifdef TARGET_ARM64
956 int i;
958 g_assert (size % 4 == 0);
959 emit_unset_mode (acfg);
960 for (i = 0; i < size; i += 4)
961 fprintf (acfg->fp, "%s 0x%x\n", acfg->inst_directive, *(guint32*)(buf + i));
962 #else
963 emit_bytes (acfg, buf, size);
964 #endif
967 /* ARCHITECTURE SPECIFIC CODE */
969 #if defined(TARGET_X86) || defined(TARGET_AMD64) || defined(TARGET_ARM) || defined(TARGET_POWERPC) || defined(TARGET_ARM64) || defined (TARGET_RISCV)
970 #define EMIT_DWARF_INFO 1
971 #endif
973 #ifdef TARGET_WIN32_MSVC
974 #undef EMIT_DWARF_INFO
975 #define EMIT_WIN32_CODEVIEW_INFO
976 #endif
978 #ifdef EMIT_WIN32_UNWIND_INFO
979 static UnwindInfoSectionCacheItem *
980 get_cached_unwind_info_section_item_win32 (MonoAotCompile *acfg, const char *function_start, const char *function_end, GSList *unwind_ops);
982 static void
983 free_unwind_info_section_cache_win32 (MonoAotCompile *acfg);
985 static void
986 emit_unwind_info_data_win32 (MonoAotCompile *acfg, PUNWIND_INFO unwind_info);
988 static void
989 emit_unwind_info_sections_win32 (MonoAotCompile *acfg, const char *function_start, const char *function_end, GSList *unwind_ops);
990 #endif
992 static void
993 arch_free_unwind_info_section_cache (MonoAotCompile *acfg)
995 #ifdef EMIT_WIN32_UNWIND_INFO
996 free_unwind_info_section_cache_win32 (acfg);
997 #endif
1000 static void
1001 arch_emit_unwind_info_sections (MonoAotCompile *acfg, const char *function_start, const char *function_end, GSList *unwind_ops)
1003 #ifdef EMIT_WIN32_UNWIND_INFO
1004 gboolean own_unwind_ops = FALSE;
1005 if (!unwind_ops) {
1006 unwind_ops = mono_unwind_get_cie_program ();
1007 own_unwind_ops = TRUE;
1010 emit_unwind_info_sections_win32 (acfg, function_start, function_end, unwind_ops);
1012 if (own_unwind_ops)
1013 mono_free_unwind_info (unwind_ops);
1014 #endif
1017 #if defined(TARGET_ARM)
1018 #define AOT_FUNC_ALIGNMENT 4
1019 #else
1020 #define AOT_FUNC_ALIGNMENT 16
1021 #endif
1023 #if defined(TARGET_POWERPC64) && !defined(MONO_ARCH_ILP32)
1024 #define PPC_LD_OP "ld"
1025 #define PPC_LDX_OP "ldx"
1026 #else
1027 #define PPC_LD_OP "lwz"
1028 #define PPC_LDX_OP "lwzx"
1029 #endif
1031 #ifdef TARGET_X86_64_WIN32_MSVC
1032 #define AOT_TARGET_STR "AMD64 (WIN32) (MSVC codegen)"
1033 #elif TARGET_AMD64
1034 #define AOT_TARGET_STR "AMD64"
1035 #endif
1037 #ifdef TARGET_ARM
1038 #ifdef TARGET_MACH
1039 #define AOT_TARGET_STR "ARM (MACH)"
1040 #else
1041 #define AOT_TARGET_STR "ARM (!MACH)"
1042 #endif
1043 #endif
1045 #ifdef TARGET_ARM64
1046 #ifdef TARGET_MACH
1047 #define AOT_TARGET_STR "ARM64 (MACH)"
1048 #else
1049 #define AOT_TARGET_STR "ARM64 (!MACH)"
1050 #endif
1051 #endif
1053 #ifdef TARGET_POWERPC64
1054 #ifdef MONO_ARCH_ILP32
1055 #define AOT_TARGET_STR "POWERPC64 (mono ilp32)"
1056 #else
1057 #define AOT_TARGET_STR "POWERPC64 (!mono ilp32)"
1058 #endif
1059 #else
1060 #ifdef TARGET_POWERPC
1061 #ifdef MONO_ARCH_ILP32
1062 #define AOT_TARGET_STR "POWERPC (mono ilp32)"
1063 #else
1064 #define AOT_TARGET_STR "POWERPC (!mono ilp32)"
1065 #endif
1066 #endif
1067 #endif
1069 #ifdef TARGET_RISCV32
1070 #define AOT_TARGET_STR "RISCV32"
1071 #endif
1073 #ifdef TARGET_RISCV64
1074 #define AOT_TARGET_STR "RISCV64"
1075 #endif
1077 #ifdef TARGET_X86
1078 #ifdef TARGET_WIN32
1079 #define AOT_TARGET_STR "X86 (WIN32)"
1080 #else
1081 #define AOT_TARGET_STR "X86"
1082 #endif
1083 #endif
1085 #ifndef AOT_TARGET_STR
1086 #define AOT_TARGET_STR ""
1087 #endif
1089 static void
1090 arch_init (MonoAotCompile *acfg)
1092 acfg->llc_args = g_string_new ("");
1093 acfg->as_args = g_string_new ("");
1094 acfg->llvm_owriter_supported = TRUE;
1097 * The prefix LLVM likes to put in front of symbol names on darwin.
1098 * The mach-os specs require this for globals, but LLVM puts them in front of all
1099 * symbols. We need to handle this, since we need to refer to LLVM generated
1100 * symbols.
1102 acfg->llvm_label_prefix = "";
1103 acfg->user_symbol_prefix = "";
1105 #if TARGET_X86 || TARGET_AMD64
1106 const gboolean has_custom_args = !!acfg->aot_opts.llvm_llc;
1107 #endif
1109 #if defined(TARGET_X86)
1110 g_string_append_printf (acfg->llc_args, " -march=x86 %s", has_custom_args ? "" : "-mcpu=generic");
1111 #endif
1113 #if defined(TARGET_AMD64)
1114 g_string_append_printf (acfg->llc_args, " -march=x86-64 %s", has_custom_args ? "" : "-mcpu=generic");
1115 /* NOP */
1116 acfg->align_pad_value = 0x90;
1117 #endif
1119 #ifdef TARGET_ARM
1120 if (acfg->aot_opts.mtriple && strstr (acfg->aot_opts.mtriple, "darwin")) {
1121 g_string_append (acfg->llc_args, "-mattr=+v6");
1122 } else {
1123 if (!(acfg->aot_opts.mtriple && strstr (acfg->aot_opts.mtriple, "thumb")))
1124 g_string_append (acfg->llc_args, " -march=arm");
1126 if (acfg->aot_opts.mtriple && strstr (acfg->aot_opts.mtriple, "ios"))
1127 g_string_append (acfg->llc_args, " -mattr=+v7");
1129 #if defined(ARM_FPU_VFP_HARD)
1130 g_string_append (acfg->llc_args, " -mattr=+vfp2,-neon,+d16 -float-abi=hard");
1131 g_string_append (acfg->as_args, " -mfpu=vfp3");
1132 #elif defined(ARM_FPU_VFP)
1133 g_string_append (acfg->llc_args, " -mattr=+vfp2,-neon,+d16");
1134 g_string_append (acfg->as_args, " -mfpu=vfp3");
1135 #else
1136 #ifdef LLVM_API_VERSION > 100
1137 g_string_append (acfg->llc_args, " -mattr=+soft-float");
1138 #else
1139 g_string_append (acfg->llc_args, " -soft-float");
1140 #endif
1141 #endif
1143 if (acfg->aot_opts.mtriple && strstr (acfg->aot_opts.mtriple, "thumb"))
1144 acfg->thumb_mixed = TRUE;
1146 if (acfg->aot_opts.mtriple)
1147 mono_arch_set_target (acfg->aot_opts.mtriple);
1148 #endif
1150 #ifdef TARGET_ARM64
1151 g_string_append (acfg->llc_args, " -march=aarch64");
1152 acfg->inst_directive = ".inst";
1153 if (acfg->aot_opts.mtriple)
1154 mono_arch_set_target (acfg->aot_opts.mtriple);
1155 #endif
1157 #ifdef TARGET_MACH
1158 acfg->user_symbol_prefix = "_";
1159 acfg->llvm_label_prefix = "_";
1160 acfg->inst_directive = ".word";
1161 acfg->need_no_dead_strip = TRUE;
1162 acfg->aot_opts.gnu_asm = TRUE;
1163 #endif
1165 #if defined(__linux__) && !defined(TARGET_ARM)
1166 acfg->need_pt_gnu_stack = TRUE;
1167 #endif
1169 #ifdef TARGET_RISCV
1170 if (acfg->aot_opts.mtriple)
1171 mono_arch_set_target (acfg->aot_opts.mtriple);
1173 #ifdef TARGET_RISCV64
1175 g_string_append (acfg->as_args, " -march=rv64i ");
1176 #ifdef RISCV_FPABI_DOUBLE
1177 g_string_append (acfg->as_args, " -mabi=lp64d");
1178 #else
1179 g_string_append (acfg->as_args, " -mabi=lp64");
1180 #endif
1182 #else
1184 g_string_append (acfg->as_args, " -march=rv32i ");
1185 #ifdef RISCV_FPABI_DOUBLE
1186 g_string_append (acfg->as_args, " -mabi=ilp32d ");
1187 #else
1188 g_string_append (acfg->as_args, " -mabi=ilp32 ");
1189 #endif
1191 #endif
1193 #endif
1195 #ifdef MONOTOUCH
1196 acfg->global_symbols = TRUE;
1197 #endif
1199 #ifdef TARGET_ANDROID
1200 acfg->llvm_owriter_supported = FALSE;
1201 #endif
1204 #ifdef TARGET_ARM64
1207 /* Load the contents of GOT_SLOT into dreg, clobbering ip0 */
1208 static void
1209 arm64_emit_load_got_slot (MonoAotCompile *acfg, int dreg, int got_slot)
1211 int offset;
1213 g_assert (acfg->fp);
1214 emit_unset_mode (acfg);
1215 /* r16==ip0 */
1216 offset = (int)(got_slot * sizeof (target_mgreg_t));
1217 #ifdef TARGET_MACH
1218 /* clang's integrated assembler */
1219 fprintf (acfg->fp, "adrp x16, %s@PAGE+%d\n", acfg->got_symbol, offset & 0xfffff000);
1220 fprintf (acfg->fp, "add x16, x16, %s@PAGEOFF\n", acfg->got_symbol);
1221 fprintf (acfg->fp, "ldr x%d, [x16, #%d]\n", dreg, offset & 0xfff);
1222 #else
1223 /* Linux GAS */
1224 fprintf (acfg->fp, "adrp x16, %s+%d\n", acfg->got_symbol, offset & 0xfffff000);
1225 fprintf (acfg->fp, "add x16, x16, :lo12:%s\n", acfg->got_symbol);
1226 fprintf (acfg->fp, "ldr x%d, [x16, %d]\n", dreg, offset & 0xfff);
1227 #endif
1230 static void
1231 arm64_emit_objc_selector_ref (MonoAotCompile *acfg, guint8 *code, int index, int *code_size)
1233 int reg;
1235 g_assert (acfg->fp);
1236 emit_unset_mode (acfg);
1238 /* ldr rt, target */
1239 reg = arm_get_ldr_lit_reg (code);
1241 fprintf (acfg->fp, "adrp x%d, L_OBJC_SELECTOR_REFERENCES_%d@PAGE\n", reg, index);
1242 fprintf (acfg->fp, "add x%d, x%d, L_OBJC_SELECTOR_REFERENCES_%d@PAGEOFF\n", reg, reg, index);
1243 fprintf (acfg->fp, "ldr x%d, [x%d]\n", reg, reg);
1245 *code_size = 12;
1248 static void
1249 arm64_emit_direct_call (MonoAotCompile *acfg, const char *target, gboolean external, gboolean thumb, MonoJumpInfo *ji, int *call_size)
1251 g_assert (acfg->fp);
1252 emit_unset_mode (acfg);
1253 if (ji && ji->relocation == MONO_R_ARM64_B) {
1254 fprintf (acfg->fp, "b %s\n", target);
1255 } else {
1256 if (ji)
1257 g_assert (ji->relocation == MONO_R_ARM64_BL);
1258 fprintf (acfg->fp, "bl %s\n", target);
1260 *call_size = 4;
1263 static void
1264 arm64_emit_got_access (MonoAotCompile *acfg, guint8 *code, int got_slot, int *code_size)
1266 int reg;
1268 /* ldr rt, target */
1269 reg = arm_get_ldr_lit_reg (code);
1270 arm64_emit_load_got_slot (acfg, reg, got_slot);
1271 *code_size = 12;
1274 static void
1275 arm64_emit_plt_entry (MonoAotCompile *acfg, const char *got_symbol, int offset, int info_offset)
1277 arm64_emit_load_got_slot (acfg, ARMREG_R16, offset / sizeof (target_mgreg_t));
1278 fprintf (acfg->fp, "br x16\n");
1279 /* Used by mono_aot_get_plt_info_offset () */
1280 fprintf (acfg->fp, "%s %d\n", acfg->inst_directive, info_offset);
1283 static void
1284 arm64_emit_tramp_page_common_code (MonoAotCompile *acfg, int pagesize, int arg_reg, int *size)
1286 guint8 buf [256];
1287 guint8 *code;
1288 int imm;
1290 /* The common code */
1291 code = buf;
1292 imm = pagesize;
1293 /* The trampoline address is in IP0 */
1294 arm_movzx (code, ARMREG_IP1, imm & 0xffff, 0);
1295 arm_movkx (code, ARMREG_IP1, (imm >> 16) & 0xffff, 16);
1296 /* Compute the data slot address */
1297 arm_subx (code, ARMREG_IP0, ARMREG_IP0, ARMREG_IP1);
1298 /* Trampoline argument */
1299 arm_ldrx (code, arg_reg, ARMREG_IP0, 0);
1300 /* Address */
1301 arm_ldrx (code, ARMREG_IP0, ARMREG_IP0, 8);
1302 arm_brx (code, ARMREG_IP0);
1304 /* Emit it */
1305 emit_code_bytes (acfg, buf, code - buf);
1307 *size = code - buf;
1310 static void
1311 arm64_emit_tramp_page_specific_code (MonoAotCompile *acfg, int pagesize, int common_tramp_size, int specific_tramp_size)
1313 guint8 buf [256];
1314 guint8 *code;
1315 int i, count;
1317 count = (pagesize - common_tramp_size) / specific_tramp_size;
1318 for (i = 0; i < count; ++i) {
1319 code = buf;
1320 arm_adrx (code, ARMREG_IP0, code);
1321 /* Branch to the generic code */
1322 arm_b (code, code - 4 - (i * specific_tramp_size) - common_tramp_size);
1323 /* This has to be 2 pointers long */
1324 arm_nop (code);
1325 arm_nop (code);
1326 g_assert (code - buf == specific_tramp_size);
1327 emit_code_bytes (acfg, buf, code - buf);
1331 static void
1332 arm64_emit_specific_trampoline_pages (MonoAotCompile *acfg)
1334 guint8 buf [128];
1335 guint8 *code;
1336 guint8 *labels [16];
1337 int common_tramp_size;
1338 int specific_tramp_size = 2 * 8;
1339 int imm, pagesize;
1340 char symbol [128];
1342 if (!acfg->aot_opts.use_trampolines_page)
1343 return;
1345 #ifdef TARGET_MACH
1346 /* Have to match the target pagesize */
1347 pagesize = 16384;
1348 #else
1349 pagesize = mono_pagesize ();
1350 #endif
1351 acfg->tramp_page_size = pagesize;
1353 /* The specific trampolines */
1354 sprintf (symbol, "%sspecific_trampolines_page", acfg->user_symbol_prefix);
1355 emit_alignment (acfg, pagesize);
1356 emit_global (acfg, symbol, TRUE);
1357 emit_label (acfg, symbol);
1359 /* The common code */
1360 arm64_emit_tramp_page_common_code (acfg, pagesize, ARMREG_IP1, &common_tramp_size);
1361 acfg->tramp_page_code_offsets [MONO_AOT_TRAMP_SPECIFIC] = common_tramp_size;
1363 arm64_emit_tramp_page_specific_code (acfg, pagesize, common_tramp_size, specific_tramp_size);
1365 /* The rgctx trampolines */
1366 /* These are the same as the specific trampolines, but they load the argument into MONO_ARCH_RGCTX_REG */
1367 sprintf (symbol, "%srgctx_trampolines_page", acfg->user_symbol_prefix);
1368 emit_alignment (acfg, pagesize);
1369 emit_global (acfg, symbol, TRUE);
1370 emit_label (acfg, symbol);
1372 /* The common code */
1373 arm64_emit_tramp_page_common_code (acfg, pagesize, MONO_ARCH_RGCTX_REG, &common_tramp_size);
1374 acfg->tramp_page_code_offsets [MONO_AOT_TRAMP_STATIC_RGCTX] = common_tramp_size;
1376 arm64_emit_tramp_page_specific_code (acfg, pagesize, common_tramp_size, specific_tramp_size);
1378 /* The gsharedvt arg trampolines */
1379 /* These are the same as the specific trampolines */
1380 sprintf (symbol, "%sgsharedvt_arg_trampolines_page", acfg->user_symbol_prefix);
1381 emit_alignment (acfg, pagesize);
1382 emit_global (acfg, symbol, TRUE);
1383 emit_label (acfg, symbol);
1385 arm64_emit_tramp_page_common_code (acfg, pagesize, ARMREG_IP1, &common_tramp_size);
1386 acfg->tramp_page_code_offsets [MONO_AOT_TRAMP_GSHAREDVT_ARG] = common_tramp_size;
1388 arm64_emit_tramp_page_specific_code (acfg, pagesize, common_tramp_size, specific_tramp_size);
1390 /* Unbox arbitrary trampolines */
1391 sprintf (symbol, "%sunbox_arbitrary_trampolines_page", acfg->user_symbol_prefix);
1392 emit_alignment (acfg, pagesize);
1393 emit_global (acfg, symbol, TRUE);
1394 emit_label (acfg, symbol);
1396 code = buf;
1397 imm = pagesize;
1399 /* Unbox this arg */
1400 arm_addx_imm (code, ARMREG_R0, ARMREG_R0, MONO_ABI_SIZEOF (MonoObject));
1402 /* The trampoline address is in IP0 */
1403 arm_movzx (code, ARMREG_IP1, imm & 0xffff, 0);
1404 arm_movkx (code, ARMREG_IP1, (imm >> 16) & 0xffff, 16);
1405 /* Compute the data slot address */
1406 arm_subx (code, ARMREG_IP0, ARMREG_IP0, ARMREG_IP1);
1407 /* Address */
1408 arm_ldrx (code, ARMREG_IP0, ARMREG_IP0, 0);
1409 arm_brx (code, ARMREG_IP0);
1411 /* Emit it */
1412 emit_code_bytes (acfg, buf, code - buf);
1414 common_tramp_size = code - buf;
1415 acfg->tramp_page_code_offsets [MONO_AOT_TRAMP_UNBOX_ARBITRARY] = common_tramp_size;
1417 arm64_emit_tramp_page_specific_code (acfg, pagesize, common_tramp_size, specific_tramp_size);
1419 /* The IMT trampolines */
1420 sprintf (symbol, "%simt_trampolines_page", acfg->user_symbol_prefix);
1421 emit_alignment (acfg, pagesize);
1422 emit_global (acfg, symbol, TRUE);
1423 emit_label (acfg, symbol);
1425 code = buf;
1426 imm = pagesize;
1427 /* The trampoline address is in IP0 */
1428 arm_movzx (code, ARMREG_IP1, imm & 0xffff, 0);
1429 arm_movkx (code, ARMREG_IP1, (imm >> 16) & 0xffff, 16);
1430 /* Compute the data slot address */
1431 arm_subx (code, ARMREG_IP0, ARMREG_IP0, ARMREG_IP1);
1432 /* Trampoline argument */
1433 arm_ldrx (code, ARMREG_IP1, ARMREG_IP0, 0);
1435 /* Same as arch_emit_imt_trampoline () */
1436 labels [0] = code;
1437 arm_ldrx (code, ARMREG_IP0, ARMREG_IP1, 0);
1438 arm_cmpx (code, ARMREG_IP0, MONO_ARCH_RGCTX_REG);
1439 labels [1] = code;
1440 arm_bcc (code, ARMCOND_EQ, 0);
1442 /* End-of-loop check */
1443 labels [2] = code;
1444 arm_cbzx (code, ARMREG_IP0, 0);
1446 /* Loop footer */
1447 arm_addx_imm (code, ARMREG_IP1, ARMREG_IP1, 2 * 8);
1448 arm_b (code, labels [0]);
1450 /* Match */
1451 mono_arm_patch (labels [1], code, MONO_R_ARM64_BCC);
1452 /* Load vtable slot addr */
1453 arm_ldrx (code, ARMREG_IP0, ARMREG_IP1, 8);
1454 /* Load vtable slot */
1455 arm_ldrx (code, ARMREG_IP0, ARMREG_IP0, 0);
1456 arm_brx (code, ARMREG_IP0);
1458 /* No match */
1459 mono_arm_patch (labels [2], code, MONO_R_ARM64_CBZ);
1460 /* Load fail addr */
1461 arm_ldrx (code, ARMREG_IP0, ARMREG_IP1, 8);
1462 arm_brx (code, ARMREG_IP0);
1464 emit_code_bytes (acfg, buf, code - buf);
1466 common_tramp_size = code - buf;
1467 acfg->tramp_page_code_offsets [MONO_AOT_TRAMP_IMT] = common_tramp_size;
1469 arm64_emit_tramp_page_specific_code (acfg, pagesize, common_tramp_size, specific_tramp_size);
1472 static void
1473 arm64_emit_specific_trampoline (MonoAotCompile *acfg, int offset, int *tramp_size)
1475 /* Load argument from second GOT slot */
1476 arm64_emit_load_got_slot (acfg, ARMREG_R17, offset + 1);
1477 /* Load generic trampoline address from first GOT slot */
1478 arm64_emit_load_got_slot (acfg, ARMREG_R16, offset);
1479 fprintf (acfg->fp, "br x16\n");
1480 *tramp_size = 7 * 4;
1483 static void
1484 arm64_emit_unbox_trampoline (MonoAotCompile *acfg, MonoCompile *cfg, MonoMethod *method, const char *call_target)
1486 emit_unset_mode (acfg);
1487 fprintf (acfg->fp, "add x0, x0, %d\n", (int)(MONO_ABI_SIZEOF (MonoObject)));
1488 fprintf (acfg->fp, "b %s\n", call_target);
1491 static void
1492 arm64_emit_static_rgctx_trampoline (MonoAotCompile *acfg, int offset, int *tramp_size)
1494 /* Similar to the specific trampolines, but use the rgctx reg instead of ip1 */
1496 /* Load argument from first GOT slot */
1497 arm64_emit_load_got_slot (acfg, MONO_ARCH_RGCTX_REG, offset);
1498 /* Load generic trampoline address from second GOT slot */
1499 arm64_emit_load_got_slot (acfg, ARMREG_R16, offset + 1);
1500 fprintf (acfg->fp, "br x16\n");
1501 *tramp_size = 7 * 4;
1504 static void
1505 arm64_emit_imt_trampoline (MonoAotCompile *acfg, int offset, int *tramp_size)
1507 guint8 buf [128];
1508 guint8 *code, *labels [16];
1510 /* Load parameter from GOT slot into ip1 */
1511 arm64_emit_load_got_slot (acfg, ARMREG_R17, offset);
1513 code = buf;
1514 labels [0] = code;
1515 arm_ldrx (code, ARMREG_IP0, ARMREG_IP1, 0);
1516 arm_cmpx (code, ARMREG_IP0, MONO_ARCH_RGCTX_REG);
1517 labels [1] = code;
1518 arm_bcc (code, ARMCOND_EQ, 0);
1520 /* End-of-loop check */
1521 labels [2] = code;
1522 arm_cbzx (code, ARMREG_IP0, 0);
1524 /* Loop footer */
1525 arm_addx_imm (code, ARMREG_IP1, ARMREG_IP1, 2 * 8);
1526 arm_b (code, labels [0]);
1528 /* Match */
1529 mono_arm_patch (labels [1], code, MONO_R_ARM64_BCC);
1530 /* Load vtable slot addr */
1531 arm_ldrx (code, ARMREG_IP0, ARMREG_IP1, 8);
1532 /* Load vtable slot */
1533 arm_ldrx (code, ARMREG_IP0, ARMREG_IP0, 0);
1534 arm_brx (code, ARMREG_IP0);
1536 /* No match */
1537 mono_arm_patch (labels [2], code, MONO_R_ARM64_CBZ);
1538 /* Load fail addr */
1539 arm_ldrx (code, ARMREG_IP0, ARMREG_IP1, 8);
1540 arm_brx (code, ARMREG_IP0);
1542 emit_code_bytes (acfg, buf, code - buf);
1544 *tramp_size = code - buf + (3 * 4);
1547 static void
1548 arm64_emit_gsharedvt_arg_trampoline (MonoAotCompile *acfg, int offset, int *tramp_size)
1550 /* Similar to the specific trampolines, but the address is in the second slot */
1551 /* Load argument from first GOT slot */
1552 arm64_emit_load_got_slot (acfg, ARMREG_R17, offset);
1553 /* Load generic trampoline address from second GOT slot */
1554 arm64_emit_load_got_slot (acfg, ARMREG_R16, offset + 1);
1555 fprintf (acfg->fp, "br x16\n");
1556 *tramp_size = 7 * 4;
1560 #endif
1562 #ifdef MONO_ARCH_AOT_SUPPORTED
1564 * arch_emit_direct_call:
1566 * Emit a direct call to the symbol TARGET. CALL_SIZE is set to the size of the
1567 * calling code.
1569 static void
1570 arch_emit_direct_call (MonoAotCompile *acfg, const char *target, gboolean external, gboolean thumb, MonoJumpInfo *ji, int *call_size)
1572 #if defined(TARGET_X86) || defined(TARGET_AMD64)
1573 /* Need to make sure this is exactly 5 bytes long */
1574 emit_unset_mode (acfg);
1575 fprintf (acfg->fp, "call %s\n", target);
1576 *call_size = 5;
1577 #elif defined(TARGET_ARM)
1578 emit_unset_mode (acfg);
1579 if (thumb)
1580 fprintf (acfg->fp, "blx %s\n", target);
1581 else
1582 fprintf (acfg->fp, "bl %s\n", target);
1583 *call_size = 4;
1584 #elif defined(TARGET_ARM64)
1585 arm64_emit_direct_call (acfg, target, external, thumb, ji, call_size);
1586 #elif defined(TARGET_POWERPC)
1587 emit_unset_mode (acfg);
1588 fprintf (acfg->fp, "bl %s\n", target);
1589 *call_size = 4;
1590 #else
1591 g_assert_not_reached ();
1592 #endif
1595 static void
1596 arch_emit_label_address (MonoAotCompile *acfg, const char *target, gboolean external_call, gboolean thumb, MonoJumpInfo *ji, int *call_size)
1598 #if defined(TARGET_ARM) && defined(TARGET_ANDROID)
1599 /* binutils ld does not support branch islands on arm32 */
1600 if (!thumb) {
1601 emit_unset_mode (acfg);
1602 fprintf (acfg->fp, "ldr pc,=%s\n", target);
1603 fprintf (acfg->fp, ".ltorg\n");
1604 *call_size = 8;
1605 } else
1606 #endif
1607 arch_emit_direct_call (acfg, target, external_call, thumb, ji, call_size);
1609 #endif
1612 * PPC32 design:
1613 * - we use an approach similar to the x86 abi: reserve a register (r30) to hold
1614 * the GOT pointer.
1615 * - The full-aot trampolines need access to the GOT of mscorlib, so we store
1616 * in in the 2. slot of every GOT, and require every method to place the GOT
1617 * address in r30, even when it doesn't access the GOT otherwise. This way,
1618 * the trampolines can compute the mscorlib GOT address by loading 4(r30).
1622 * PPC64 design:
1623 * PPC64 uses function descriptors which greatly complicate all code, since
1624 * these are used very inconsistently in the runtime. Some functions like
1625 * mono_compile_method () return ftn descriptors, while others like the
1626 * trampoline creation functions do not.
1627 * We assume that all GOT slots contain function descriptors, and create
1628 * descriptors in aot-runtime.c when needed.
1629 * The ppc64 abi uses r2 to hold the address of the TOC/GOT, which is loaded
1630 * from function descriptors, we could do the same, but it would require
1631 * rewriting all the ppc/aot code to handle function descriptors properly.
1632 * So instead, we use the same approach as on PPC32.
1633 * This is a horrible mess, but fixing it would probably lead to an even bigger
1634 * one.
1638 * X86 design:
1639 * - similar to the PPC32 design, we reserve EBX to hold the GOT pointer.
1642 #ifdef MONO_ARCH_AOT_SUPPORTED
1644 * arch_emit_got_offset:
1646 * The memory pointed to by CODE should hold native code for computing the GOT
1647 * address (OP_LOAD_GOTADDR). Emit this code while patching it with the offset
1648 * between code and the GOT. CODE_SIZE is set to the number of bytes emitted.
1650 static void
1651 arch_emit_got_offset (MonoAotCompile *acfg, guint8 *code, int *code_size)
1653 #if defined(TARGET_POWERPC64)
1654 emit_unset_mode (acfg);
1656 * The ppc32 code doesn't seem to work on ppc64, the assembler complains about
1657 * unsupported relocations. So we store the got address into the .Lgot_addr
1658 * symbol which is in the text segment, compute its address, and load it.
1660 fprintf (acfg->fp, ".L%d:\n", acfg->label_generator);
1661 fprintf (acfg->fp, "lis 0, (.Lgot_addr + 4 - .L%d)@h\n", acfg->label_generator);
1662 fprintf (acfg->fp, "ori 0, 0, (.Lgot_addr + 4 - .L%d)@l\n", acfg->label_generator);
1663 fprintf (acfg->fp, "add 30, 30, 0\n");
1664 fprintf (acfg->fp, "%s 30, 0(30)\n", PPC_LD_OP);
1665 acfg->label_generator ++;
1666 *code_size = 16;
1667 #elif defined(TARGET_POWERPC)
1668 emit_unset_mode (acfg);
1669 fprintf (acfg->fp, ".L%d:\n", acfg->label_generator);
1670 fprintf (acfg->fp, "lis 0, (%s + 4 - .L%d)@h\n", acfg->got_symbol, acfg->label_generator);
1671 fprintf (acfg->fp, "ori 0, 0, (%s + 4 - .L%d)@l\n", acfg->got_symbol, acfg->label_generator);
1672 acfg->label_generator ++;
1673 *code_size = 8;
1674 #else
1675 guint32 offset = mono_arch_get_patch_offset (code);
1676 emit_bytes (acfg, code, offset);
1677 emit_symbol_diff (acfg, acfg->got_symbol, ".", offset);
1679 *code_size = offset + 4;
1680 #endif
1684 * arch_emit_got_access:
1686 * The memory pointed to by CODE should hold native code for loading a GOT
1687 * slot (OP_AOTCONST/OP_GOT_ENTRY). Emit this code while patching it so it accesses the
1688 * GOT slot GOT_SLOT. CODE_SIZE is set to the number of bytes emitted.
1690 static void
1691 arch_emit_got_access (MonoAotCompile *acfg, const char *got_symbol, guint8 *code, int got_slot, int *code_size)
1693 #ifdef TARGET_AMD64
1694 /* mov reg, got+offset(%rip) */
1695 if (acfg->llvm) {
1696 /* The GOT symbol is in the LLVM module, the clang assembler has problems emitting symbol diffs for it */
1697 int dreg;
1698 int rex_r;
1700 /* Decode reg, see amd64_mov_reg_membase () */
1701 rex_r = code [0] & AMD64_REX_R;
1702 g_assert (code [0] == 0x49 + rex_r);
1703 g_assert (code [1] == 0x8b);
1704 dreg = ((code [2] >> 3) & 0x7) + (rex_r ? 8 : 0);
1706 emit_unset_mode (acfg);
1707 fprintf (acfg->fp, "mov %s+%d(%%rip), %s\n", got_symbol, (unsigned int) ((got_slot * sizeof (target_mgreg_t))), mono_arch_regname (dreg));
1708 *code_size = 7;
1709 } else {
1710 emit_bytes (acfg, code, mono_arch_get_patch_offset (code));
1711 emit_symbol_diff (acfg, got_symbol, ".", (unsigned int) ((got_slot * sizeof (target_mgreg_t)) - 4));
1712 *code_size = mono_arch_get_patch_offset (code) + 4;
1714 #elif defined(TARGET_X86)
1715 emit_bytes (acfg, code, mono_arch_get_patch_offset (code));
1716 emit_int32 (acfg, (unsigned int) ((got_slot * sizeof (target_mgreg_t))));
1717 *code_size = mono_arch_get_patch_offset (code) + 4;
1718 #elif defined(TARGET_ARM)
1719 emit_bytes (acfg, code, mono_arch_get_patch_offset (code));
1720 emit_symbol_diff (acfg, got_symbol, ".", (unsigned int) ((got_slot * sizeof (target_mgreg_t))) - 12);
1721 *code_size = mono_arch_get_patch_offset (code) + 4;
1722 #elif defined(TARGET_ARM64)
1723 emit_bytes (acfg, code, mono_arch_get_patch_offset (code));
1724 arm64_emit_got_access (acfg, code, got_slot, code_size);
1725 #elif defined(TARGET_POWERPC)
1727 guint8 buf [32];
1729 emit_bytes (acfg, code, mono_arch_get_patch_offset (code));
1730 code = buf;
1731 ppc_load32 (code, ppc_r0, got_slot * sizeof (target_mgreg_t));
1732 g_assert (code - buf == 8);
1733 emit_bytes (acfg, buf, code - buf);
1734 *code_size = code - buf;
1736 #else
1737 g_assert_not_reached ();
1738 #endif
1741 #endif
1743 #ifdef MONO_ARCH_AOT_SUPPORTED
1745 * arch_emit_objc_selector_ref:
1747 * Emit the implementation of OP_OBJC_GET_SELECTOR, which itself implements @selector(foo:) in objective-c.
1749 static void
1750 arch_emit_objc_selector_ref (MonoAotCompile *acfg, guint8 *code, int index, int *code_size)
1752 #if defined(TARGET_ARM)
1753 char symbol1 [MAX_SYMBOL_SIZE];
1754 char symbol2 [MAX_SYMBOL_SIZE];
1755 int lindex = acfg->objc_selector_index_2 ++;
1757 /* Emit ldr.imm/b */
1758 emit_bytes (acfg, code, 8);
1760 sprintf (symbol1, "L_OBJC_SELECTOR_%d", lindex);
1761 sprintf (symbol2, "L_OBJC_SELECTOR_REFERENCES_%d", index);
1763 emit_label (acfg, symbol1);
1764 mono_img_writer_emit_unset_mode (acfg->w);
1765 fprintf (acfg->fp, ".long %s-(%s+12)", symbol2, symbol1);
1767 *code_size = 12;
1768 #elif defined(TARGET_ARM64)
1769 arm64_emit_objc_selector_ref (acfg, code, index, code_size);
1770 #else
1771 g_assert_not_reached ();
1772 #endif
1774 #endif
1777 * arch_emit_plt_entry:
1779 * Emit code for the PLT entry.
1780 * The plt entry should look like this:
1781 * <indirect jump to GOT_SYMBOL + OFFSET>
1782 * <INFO_OFFSET embedded into the instruction stream>
1784 static void
1785 arch_emit_plt_entry (MonoAotCompile *acfg, const char *got_symbol, int offset, int info_offset)
1787 #if defined(TARGET_X86)
1788 /* jmp *<offset>(%ebx) */
1789 emit_byte (acfg, 0xff);
1790 emit_byte (acfg, 0xa3);
1791 emit_int32 (acfg, offset);
1792 /* Used by mono_aot_get_plt_info_offset */
1793 emit_int32 (acfg, info_offset);
1794 #elif defined(TARGET_AMD64)
1795 emit_unset_mode (acfg);
1796 fprintf (acfg->fp, "jmp *%s+%d(%%rip)\n", got_symbol, offset);
1797 /* Used by mono_aot_get_plt_info_offset */
1798 emit_int32 (acfg, info_offset);
1799 acfg->stats.plt_size += 10;
1800 #elif defined(TARGET_ARM)
1801 guint8 buf [256];
1802 guint8 *code;
1804 code = buf;
1805 ARM_LDR_IMM (code, ARMREG_IP, ARMREG_PC, 0);
1806 ARM_LDR_REG_REG (code, ARMREG_PC, ARMREG_PC, ARMREG_IP);
1807 emit_bytes (acfg, buf, code - buf);
1808 emit_symbol_diff (acfg, got_symbol, ".", offset - 4);
1809 /* Used by mono_aot_get_plt_info_offset */
1810 emit_int32 (acfg, info_offset);
1811 #elif defined(TARGET_ARM64)
1812 arm64_emit_plt_entry (acfg, got_symbol, offset, info_offset);
1813 #elif defined(TARGET_POWERPC)
1814 /* The GOT address is guaranteed to be in r30 by OP_LOAD_GOTADDR */
1815 emit_unset_mode (acfg);
1816 fprintf (acfg->fp, "lis 11, %d@h\n", offset);
1817 fprintf (acfg->fp, "ori 11, 11, %d@l\n", offset);
1818 fprintf (acfg->fp, "add 11, 11, 30\n");
1819 fprintf (acfg->fp, "%s 11, 0(11)\n", PPC_LD_OP);
1820 #ifdef PPC_USES_FUNCTION_DESCRIPTOR
1821 fprintf (acfg->fp, "%s 2, %d(11)\n", PPC_LD_OP, (int)sizeof (target_mgreg_t));
1822 fprintf (acfg->fp, "%s 11, 0(11)\n", PPC_LD_OP);
1823 #endif
1824 fprintf (acfg->fp, "mtctr 11\n");
1825 fprintf (acfg->fp, "bctr\n");
1826 emit_int32 (acfg, info_offset);
1827 #else
1828 g_assert_not_reached ();
1829 #endif
1833 * arch_emit_llvm_plt_entry:
1835 * Same as arch_emit_plt_entry, but handles calls from LLVM generated code.
1836 * This is only needed on arm to handle thumb interop.
1838 static void
1839 arch_emit_llvm_plt_entry (MonoAotCompile *acfg, const char *got_symbol, int offset, int info_offset)
1841 #if defined(TARGET_ARM)
1842 /* LLVM calls the PLT entries using bl, so these have to be thumb2 */
1843 /* The caller already transitioned to thumb */
1844 /* The code below should be 12 bytes long */
1845 /* clang has trouble encoding these instructions, so emit the binary */
1846 #if 0
1847 fprintf (acfg->fp, "ldr ip, [pc, #8]\n");
1848 /* thumb can't encode ld pc, [pc, ip] */
1849 fprintf (acfg->fp, "add ip, pc, ip\n");
1850 fprintf (acfg->fp, "ldr ip, [ip, #0]\n");
1851 fprintf (acfg->fp, "bx ip\n");
1852 #endif
1853 emit_set_thumb_mode (acfg);
1854 fprintf (acfg->fp, ".4byte 0xc008f8df\n");
1855 fprintf (acfg->fp, ".2byte 0x44fc\n");
1856 fprintf (acfg->fp, ".4byte 0xc000f8dc\n");
1857 fprintf (acfg->fp, ".2byte 0x4760\n");
1858 emit_symbol_diff (acfg, got_symbol, ".", offset + 4);
1859 emit_int32 (acfg, info_offset);
1860 emit_unset_mode (acfg);
1861 emit_set_arm_mode (acfg);
1862 #else
1863 g_assert_not_reached ();
1864 #endif
1867 /* Save unwind_info in the module and emit the offset to the information at symbol */
1868 static void save_unwind_info (MonoAotCompile *acfg, char *symbol, GSList *unwind_ops)
1870 guint32 uw_offset, encoded_len;
1871 guint8 *encoded;
1873 emit_section_change (acfg, RODATA_SECT, 0);
1874 emit_global (acfg, symbol, FALSE);
1875 emit_label (acfg, symbol);
1877 encoded = mono_unwind_ops_encode (unwind_ops, &encoded_len);
1878 uw_offset = get_unwind_info_offset (acfg, encoded, encoded_len);
1879 g_free (encoded);
1880 emit_int32 (acfg, uw_offset);
1884 * arch_emit_specific_trampoline_pages:
1886 * Emits a page full of trampolines: each trampoline uses its own address to
1887 * lookup both the generic trampoline code and the data argument.
1888 * This page can be remapped in process multiple times so we can get an
1889 * unlimited number of trampolines.
1890 * Specifically this implementation uses the following trick: two memory pages
1891 * are allocated, with the first containing the data and the second containing the trampolines.
1892 * To reduce trampoline size, each trampoline jumps at the start of the page where a common
1893 * implementation does all the lifting.
1894 * Note that the ARM single trampoline size is 8 bytes, exactly like the data that needs to be stored
1895 * on the arm 32 bit system.
1897 static void
1898 arch_emit_specific_trampoline_pages (MonoAotCompile *acfg)
1900 #if defined(TARGET_ARM)
1901 guint8 buf [128];
1902 guint8 *code;
1903 guint8 *loop_start, *loop_branch_back, *loop_end_check, *imt_found_check;
1904 int i;
1905 int pagesize = MONO_AOT_TRAMP_PAGE_SIZE;
1906 GSList *unwind_ops = NULL;
1907 #define COMMON_TRAMP_SIZE 16
1908 int count = (pagesize - COMMON_TRAMP_SIZE) / 8;
1909 int imm8, rot_amount;
1910 char symbol [128];
1912 if (!acfg->aot_opts.use_trampolines_page)
1913 return;
1915 acfg->tramp_page_size = pagesize;
1917 sprintf (symbol, "%sspecific_trampolines_page", acfg->user_symbol_prefix);
1918 emit_alignment (acfg, pagesize);
1919 emit_global (acfg, symbol, TRUE);
1920 emit_label (acfg, symbol);
1922 /* emit the generic code first, the trampoline address + 8 is in the lr register */
1923 code = buf;
1924 imm8 = mono_arm_is_rotated_imm8 (pagesize, &rot_amount);
1925 ARM_SUB_REG_IMM (code, ARMREG_LR, ARMREG_LR, imm8, rot_amount);
1926 ARM_LDR_IMM (code, ARMREG_R1, ARMREG_LR, -8);
1927 ARM_LDR_IMM (code, ARMREG_PC, ARMREG_LR, -4);
1928 ARM_NOP (code);
1929 g_assert (code - buf == COMMON_TRAMP_SIZE);
1931 /* Emit it */
1932 emit_bytes (acfg, buf, code - buf);
1934 for (i = 0; i < count; ++i) {
1935 code = buf;
1936 ARM_PUSH (code, 0x5fff);
1937 ARM_BL (code, 0);
1938 arm_patch (code - 4, code - COMMON_TRAMP_SIZE - 8 * (i + 1));
1939 g_assert (code - buf == 8);
1940 emit_bytes (acfg, buf, code - buf);
1943 /* now the rgctx trampolines: each specific trampolines puts in the ip register
1944 * the instruction pointer address, so the generic trampoline at the start of the page
1945 * subtracts 4096 to get to the data page and loads the values
1946 * We again fit the generic trampiline in 16 bytes.
1948 sprintf (symbol, "%srgctx_trampolines_page", acfg->user_symbol_prefix);
1949 emit_global (acfg, symbol, TRUE);
1950 emit_label (acfg, symbol);
1951 code = buf;
1952 imm8 = mono_arm_is_rotated_imm8 (pagesize, &rot_amount);
1953 ARM_SUB_REG_IMM (code, ARMREG_IP, ARMREG_IP, imm8, rot_amount);
1954 ARM_LDR_IMM (code, MONO_ARCH_RGCTX_REG, ARMREG_IP, -8);
1955 ARM_LDR_IMM (code, ARMREG_PC, ARMREG_IP, -4);
1956 ARM_NOP (code);
1957 g_assert (code - buf == COMMON_TRAMP_SIZE);
1959 /* Emit it */
1960 emit_bytes (acfg, buf, code - buf);
1962 for (i = 0; i < count; ++i) {
1963 code = buf;
1964 ARM_MOV_REG_REG (code, ARMREG_IP, ARMREG_PC);
1965 ARM_B (code, 0);
1966 arm_patch (code - 4, code - COMMON_TRAMP_SIZE - 8 * (i + 1));
1967 g_assert (code - buf == 8);
1968 emit_bytes (acfg, buf, code - buf);
1972 * gsharedvt arg trampolines: see arch_emit_gsharedvt_arg_trampoline ()
1974 sprintf (symbol, "%sgsharedvt_arg_trampolines_page", acfg->user_symbol_prefix);
1975 emit_global (acfg, symbol, TRUE);
1976 emit_label (acfg, symbol);
1977 code = buf;
1978 ARM_PUSH (code, (1 << ARMREG_R0) | (1 << ARMREG_R1) | (1 << ARMREG_R2) | (1 << ARMREG_R3));
1979 imm8 = mono_arm_is_rotated_imm8 (pagesize, &rot_amount);
1980 ARM_SUB_REG_IMM (code, ARMREG_IP, ARMREG_IP, imm8, rot_amount);
1981 ARM_LDR_IMM (code, ARMREG_R0, ARMREG_IP, -8);
1982 ARM_LDR_IMM (code, ARMREG_PC, ARMREG_IP, -4);
1983 g_assert (code - buf == COMMON_TRAMP_SIZE);
1984 /* Emit it */
1985 emit_bytes (acfg, buf, code - buf);
1987 for (i = 0; i < count; ++i) {
1988 code = buf;
1989 ARM_MOV_REG_REG (code, ARMREG_IP, ARMREG_PC);
1990 ARM_B (code, 0);
1991 arm_patch (code - 4, code - COMMON_TRAMP_SIZE - 8 * (i + 1));
1992 g_assert (code - buf == 8);
1993 emit_bytes (acfg, buf, code - buf);
1996 /* now the unbox arbitrary trampolines: each specific trampolines puts in the ip register
1997 * the instruction pointer address, so the generic trampoline at the start of the page
1998 * subtracts 4096 to get to the data page and loads the target addr.
1999 * We again fit the generic trampoline in 16 bytes.
2001 sprintf (symbol, "%sunbox_arbitrary_trampolines_page", acfg->user_symbol_prefix);
2002 emit_global (acfg, symbol, TRUE);
2003 emit_label (acfg, symbol);
2004 code = buf;
2006 ARM_ADD_REG_IMM8 (code, ARMREG_R0, ARMREG_R0, MONO_ABI_SIZEOF (MonoObject));
2007 imm8 = mono_arm_is_rotated_imm8 (pagesize, &rot_amount);
2008 ARM_SUB_REG_IMM (code, ARMREG_IP, ARMREG_IP, imm8, rot_amount);
2009 ARM_LDR_IMM (code, ARMREG_PC, ARMREG_IP, -4);
2010 ARM_NOP (code);
2011 g_assert (code - buf == COMMON_TRAMP_SIZE);
2013 /* Emit it */
2014 emit_bytes (acfg, buf, code - buf);
2016 for (i = 0; i < count; ++i) {
2017 code = buf;
2018 ARM_MOV_REG_REG (code, ARMREG_IP, ARMREG_PC);
2019 ARM_B (code, 0);
2020 arm_patch (code - 4, code - COMMON_TRAMP_SIZE - 8 * (i + 1));
2021 g_assert (code - buf == 8);
2022 emit_bytes (acfg, buf, code - buf);
2025 /* now the imt trampolines: each specific trampolines puts in the ip register
2026 * the instruction pointer address, so the generic trampoline at the start of the page
2027 * subtracts 4096 to get to the data page and loads the values
2029 #define IMT_TRAMP_SIZE 72
2030 sprintf (symbol, "%simt_trampolines_page", acfg->user_symbol_prefix);
2031 emit_global (acfg, symbol, TRUE);
2032 emit_label (acfg, symbol);
2033 code = buf;
2034 /* Need at least two free registers, plus a slot for storing the pc */
2035 ARM_PUSH (code, (1 << ARMREG_R0)|(1 << ARMREG_R1)|(1 << ARMREG_R2));
2037 imm8 = mono_arm_is_rotated_imm8 (pagesize, &rot_amount);
2038 ARM_SUB_REG_IMM (code, ARMREG_IP, ARMREG_IP, imm8, rot_amount);
2039 ARM_LDR_IMM (code, ARMREG_R0, ARMREG_IP, -8);
2041 /* The IMT method is in v5, r0 has the imt array address */
2043 loop_start = code;
2044 ARM_LDR_IMM (code, ARMREG_R1, ARMREG_R0, 0);
2045 ARM_CMP_REG_REG (code, ARMREG_R1, ARMREG_V5);
2046 imt_found_check = code;
2047 ARM_B_COND (code, ARMCOND_EQ, 0);
2049 /* End-of-loop check */
2050 ARM_CMP_REG_IMM (code, ARMREG_R1, 0, 0);
2051 loop_end_check = code;
2052 ARM_B_COND (code, ARMCOND_EQ, 0);
2054 /* Loop footer */
2055 ARM_ADD_REG_IMM8 (code, ARMREG_R0, ARMREG_R0, sizeof (target_mgreg_t) * 2);
2056 loop_branch_back = code;
2057 ARM_B (code, 0);
2058 arm_patch (loop_branch_back, loop_start);
2060 /* Match */
2061 arm_patch (imt_found_check, code);
2062 ARM_LDR_IMM (code, ARMREG_R0, ARMREG_R0, 4);
2063 ARM_LDR_IMM (code, ARMREG_R0, ARMREG_R0, 0);
2064 /* Save it to the third stack slot */
2065 ARM_STR_IMM (code, ARMREG_R0, ARMREG_SP, 8);
2066 /* Restore the registers and branch */
2067 ARM_POP (code, (1 << ARMREG_R0)|(1 << ARMREG_R1)|(1 << ARMREG_PC));
2069 /* No match */
2070 arm_patch (loop_end_check, code);
2071 ARM_LDR_IMM (code, ARMREG_R0, ARMREG_R0, 4);
2072 ARM_STR_IMM (code, ARMREG_R0, ARMREG_SP, 8);
2073 ARM_POP (code, (1 << ARMREG_R0)|(1 << ARMREG_R1)|(1 << ARMREG_PC));
2074 ARM_NOP (code);
2076 /* Emit it */
2077 g_assert (code - buf == IMT_TRAMP_SIZE);
2078 emit_bytes (acfg, buf, code - buf);
2080 for (i = 0; i < count; ++i) {
2081 code = buf;
2082 ARM_MOV_REG_REG (code, ARMREG_IP, ARMREG_PC);
2083 ARM_B (code, 0);
2084 arm_patch (code - 4, code - IMT_TRAMP_SIZE - 8 * (i + 1));
2085 g_assert (code - buf == 8);
2086 emit_bytes (acfg, buf, code - buf);
2089 acfg->tramp_page_code_offsets [MONO_AOT_TRAMP_SPECIFIC] = 16;
2090 acfg->tramp_page_code_offsets [MONO_AOT_TRAMP_STATIC_RGCTX] = 16;
2091 acfg->tramp_page_code_offsets [MONO_AOT_TRAMP_IMT] = 72;
2092 acfg->tramp_page_code_offsets [MONO_AOT_TRAMP_GSHAREDVT_ARG] = 16;
2093 acfg->tramp_page_code_offsets [MONO_AOT_TRAMP_UNBOX_ARBITRARY] = 16;
2095 /* Unwind info for specifc trampolines */
2096 sprintf (symbol, "%sspecific_trampolines_page_gen_p", acfg->user_symbol_prefix);
2097 /* We unwind to the original caller, from the stack, since lr is clobbered */
2098 mono_add_unwind_op_def_cfa (unwind_ops, 0, 0, ARMREG_SP, 14 * sizeof (target_mgreg_t));
2099 mono_add_unwind_op_offset (unwind_ops, 0, 0, ARMREG_LR, -4);
2100 save_unwind_info (acfg, symbol, unwind_ops);
2101 mono_free_unwind_info (unwind_ops);
2103 sprintf (symbol, "%sspecific_trampolines_page_sp_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, 14 * sizeof (target_mgreg_t));
2106 save_unwind_info (acfg, symbol, unwind_ops);
2107 mono_free_unwind_info (unwind_ops);
2109 /* Unwind info for rgctx trampolines */
2110 sprintf (symbol, "%srgctx_trampolines_page_gen_p", acfg->user_symbol_prefix);
2111 mono_add_unwind_op_def_cfa (unwind_ops, 0, 0, ARMREG_SP, 0);
2112 save_unwind_info (acfg, symbol, unwind_ops);
2114 sprintf (symbol, "%srgctx_trampolines_page_sp_p", acfg->user_symbol_prefix);
2115 save_unwind_info (acfg, symbol, unwind_ops);
2116 mono_free_unwind_info (unwind_ops);
2118 /* Unwind info for gsharedvt trampolines */
2119 sprintf (symbol, "%sgsharedvt_trampolines_page_gen_p", acfg->user_symbol_prefix);
2120 mono_add_unwind_op_def_cfa (unwind_ops, 0, 0, ARMREG_SP, 0);
2121 mono_add_unwind_op_def_cfa_offset (unwind_ops, 4, 0, 4 * sizeof (target_mgreg_t));
2122 save_unwind_info (acfg, symbol, unwind_ops);
2123 mono_free_unwind_info (unwind_ops);
2125 sprintf (symbol, "%sgsharedvt_trampolines_page_sp_p", acfg->user_symbol_prefix);
2126 mono_add_unwind_op_def_cfa (unwind_ops, 0, 0, ARMREG_SP, 0);
2127 save_unwind_info (acfg, symbol, unwind_ops);
2128 mono_free_unwind_info (unwind_ops);
2130 /* Unwind info for unbox arbitrary trampolines */
2131 sprintf (symbol, "%sunbox_arbitrary_trampolines_page_gen_p", acfg->user_symbol_prefix);
2132 mono_add_unwind_op_def_cfa (unwind_ops, 0, 0, ARMREG_SP, 0);
2133 save_unwind_info (acfg, symbol, unwind_ops);
2135 sprintf (symbol, "%sunbox_arbitrary_trampolines_page_sp_p", acfg->user_symbol_prefix);
2136 save_unwind_info (acfg, symbol, unwind_ops);
2137 mono_free_unwind_info (unwind_ops);
2139 /* Unwind info for imt trampolines */
2140 sprintf (symbol, "%simt_trampolines_page_gen_p", acfg->user_symbol_prefix);
2141 mono_add_unwind_op_def_cfa (unwind_ops, 0, 0, ARMREG_SP, 0);
2142 mono_add_unwind_op_def_cfa_offset (unwind_ops, 4, 0, 3 * sizeof (target_mgreg_t));
2143 save_unwind_info (acfg, symbol, unwind_ops);
2144 mono_free_unwind_info (unwind_ops);
2146 sprintf (symbol, "%simt_trampolines_page_sp_p", acfg->user_symbol_prefix);
2147 mono_add_unwind_op_def_cfa (unwind_ops, 0, 0, ARMREG_SP, 0);
2148 save_unwind_info (acfg, symbol, unwind_ops);
2149 mono_free_unwind_info (unwind_ops);
2150 #elif defined(TARGET_ARM64)
2151 arm64_emit_specific_trampoline_pages (acfg);
2152 #endif
2156 * arch_emit_specific_trampoline:
2158 * Emit code for a specific trampoline. OFFSET is the offset of the first of
2159 * two GOT slots which contain the generic trampoline address and the trampoline
2160 * argument. TRAMP_SIZE is set to the size of the emitted trampoline.
2162 static void
2163 arch_emit_specific_trampoline (MonoAotCompile *acfg, int offset, int *tramp_size)
2166 * The trampolines created here are variations of the specific
2167 * trampolines created in mono_arch_create_specific_trampoline (). The
2168 * differences are:
2169 * - the generic trampoline address is taken from a got slot.
2170 * - the offset of the got slot where the trampoline argument is stored
2171 * is embedded in the instruction stream, and the generic trampoline
2172 * can load the argument by loading the offset, adding it to the
2173 * address of the trampoline to get the address of the got slot, and
2174 * loading the argument from there.
2175 * - all the trampolines should be of the same length.
2177 #if defined(TARGET_AMD64)
2178 /* This should be exactly 8 bytes long */
2179 *tramp_size = 8;
2180 /* call *<offset>(%rip) */
2181 if (acfg->llvm) {
2182 emit_unset_mode (acfg);
2183 fprintf (acfg->fp, "call *%s+%d(%%rip)\n", acfg->got_symbol, (int)(offset * sizeof (target_mgreg_t)));
2184 emit_zero_bytes (acfg, 2);
2185 } else {
2186 emit_byte (acfg, '\x41');
2187 emit_byte (acfg, '\xff');
2188 emit_byte (acfg, '\x15');
2189 emit_symbol_diff (acfg, acfg->got_symbol, ".", (offset * sizeof (target_mgreg_t)) - 4);
2190 emit_zero_bytes (acfg, 1);
2192 #elif defined(TARGET_ARM)
2193 guint8 buf [128];
2194 guint8 *code;
2196 /* This should be exactly 20 bytes long */
2197 *tramp_size = 20;
2198 code = buf;
2199 ARM_PUSH (code, 0x5fff);
2200 ARM_LDR_IMM (code, ARMREG_R1, ARMREG_PC, 4);
2201 /* Load the value from the GOT */
2202 ARM_LDR_REG_REG (code, ARMREG_R1, ARMREG_PC, ARMREG_R1);
2203 /* Branch to it */
2204 ARM_BLX_REG (code, ARMREG_R1);
2206 g_assert (code - buf == 16);
2208 /* Emit it */
2209 emit_bytes (acfg, buf, code - buf);
2211 * Only one offset is needed, since the second one would be equal to the
2212 * first one.
2214 emit_symbol_diff (acfg, acfg->got_symbol, ".", (offset * sizeof (target_mgreg_t)) - 4 + 4);
2215 //emit_symbol_diff (acfg, acfg->got_symbol, ".", ((offset + 1) * sizeof (target_mgreg_t)) - 4 + 8);
2216 #elif defined(TARGET_ARM64)
2217 arm64_emit_specific_trampoline (acfg, offset, tramp_size);
2218 #elif defined(TARGET_POWERPC)
2219 guint8 buf [128];
2220 guint8 *code;
2222 *tramp_size = 4;
2223 code = buf;
2226 * PPC has no ip relative addressing, so we need to compute the address
2227 * of the mscorlib got. That is slow and complex, so instead, we store it
2228 * in the second got slot of every aot image. The caller already computed
2229 * the address of its got and placed it into r30.
2231 emit_unset_mode (acfg);
2232 /* Load mscorlib got address */
2233 fprintf (acfg->fp, "%s 0, %d(30)\n", PPC_LD_OP, (int)sizeof (target_mgreg_t));
2234 /* Load generic trampoline address */
2235 fprintf (acfg->fp, "lis 11, %d@h\n", (int)(offset * sizeof (target_mgreg_t)));
2236 fprintf (acfg->fp, "ori 11, 11, %d@l\n", (int)(offset * sizeof (target_mgreg_t)));
2237 fprintf (acfg->fp, "%s 11, 11, 0\n", PPC_LDX_OP);
2238 #ifdef PPC_USES_FUNCTION_DESCRIPTOR
2239 fprintf (acfg->fp, "%s 11, 0(11)\n", PPC_LD_OP);
2240 #endif
2241 fprintf (acfg->fp, "mtctr 11\n");
2242 /* Load trampoline argument */
2243 /* On ppc, we pass it normally to the generic trampoline */
2244 fprintf (acfg->fp, "lis 11, %d@h\n", (int)((offset + 1) * sizeof (target_mgreg_t)));
2245 fprintf (acfg->fp, "ori 11, 11, %d@l\n", (int)((offset + 1) * sizeof (target_mgreg_t)));
2246 fprintf (acfg->fp, "%s 0, 11, 0\n", PPC_LDX_OP);
2247 /* Branch to generic trampoline */
2248 fprintf (acfg->fp, "bctr\n");
2250 #ifdef PPC_USES_FUNCTION_DESCRIPTOR
2251 *tramp_size = 10 * 4;
2252 #else
2253 *tramp_size = 9 * 4;
2254 #endif
2255 #elif defined(TARGET_X86)
2256 guint8 buf [128];
2257 guint8 *code;
2259 /* Similar to the PPC code above */
2261 /* FIXME: Could this clobber the register needed by get_vcall_slot () ? */
2263 code = buf;
2264 /* Load mscorlib got address */
2265 x86_mov_reg_membase (code, X86_ECX, MONO_ARCH_GOT_REG, sizeof (target_mgreg_t), 4);
2266 /* Push trampoline argument */
2267 x86_push_membase (code, X86_ECX, (offset + 1) * sizeof (target_mgreg_t));
2268 /* Load generic trampoline address */
2269 x86_mov_reg_membase (code, X86_ECX, X86_ECX, offset * sizeof (target_mgreg_t), 4);
2270 /* Branch to generic trampoline */
2271 x86_jump_reg (code, X86_ECX);
2273 emit_bytes (acfg, buf, code - buf);
2275 *tramp_size = 17;
2276 g_assert (code - buf == *tramp_size);
2277 #else
2278 g_assert_not_reached ();
2279 #endif
2283 * arch_emit_unbox_trampoline:
2285 * Emit code for the unbox trampoline for METHOD used in the full-aot case.
2286 * CALL_TARGET is the symbol pointing to the native code of METHOD.
2288 * See mono_aot_get_unbox_trampoline.
2290 static void
2291 arch_emit_unbox_trampoline (MonoAotCompile *acfg, MonoCompile *cfg, MonoMethod *method, const char *call_target)
2293 #if defined(TARGET_AMD64)
2294 guint8 buf [32];
2295 guint8 *code;
2296 int this_reg;
2298 this_reg = mono_arch_get_this_arg_reg (NULL);
2299 code = buf;
2300 amd64_alu_reg_imm (code, X86_ADD, this_reg, MONO_ABI_SIZEOF (MonoObject));
2302 emit_bytes (acfg, buf, code - buf);
2303 /* jump <method> */
2304 if (acfg->llvm) {
2305 emit_unset_mode (acfg);
2306 fprintf (acfg->fp, "jmp %s\n", call_target);
2307 } else {
2308 emit_byte (acfg, '\xe9');
2309 emit_symbol_diff (acfg, call_target, ".", -4);
2311 #elif defined(TARGET_X86)
2312 guint8 buf [32];
2313 guint8 *code;
2314 int this_pos = 4;
2316 code = buf;
2318 x86_alu_membase_imm (code, X86_ADD, X86_ESP, this_pos, MONO_ABI_SIZEOF (MonoObject));
2320 emit_bytes (acfg, buf, code - buf);
2322 /* jump <method> */
2323 emit_byte (acfg, '\xe9');
2324 emit_symbol_diff (acfg, call_target, ".", -4);
2325 #elif defined(TARGET_ARM)
2326 guint8 buf [128];
2327 guint8 *code;
2329 if (acfg->thumb_mixed && cfg->compile_llvm) {
2330 fprintf (acfg->fp, "add r0, r0, #%d\n", (int)MONO_ABI_SIZEOF (MonoObject));
2331 fprintf (acfg->fp, "b %s\n", call_target);
2332 fprintf (acfg->fp, ".arm\n");
2333 fprintf (acfg->fp, ".align 2\n");
2334 return;
2337 code = buf;
2339 ARM_ADD_REG_IMM8 (code, ARMREG_R0, ARMREG_R0, MONO_ABI_SIZEOF (MonoObject));
2341 emit_bytes (acfg, buf, code - buf);
2342 /* jump to method */
2343 if (acfg->thumb_mixed && cfg->compile_llvm)
2344 fprintf (acfg->fp, "\n\tbx %s\n", call_target);
2345 else
2346 fprintf (acfg->fp, "\n\tb %s\n", call_target);
2347 #elif defined(TARGET_ARM64)
2348 arm64_emit_unbox_trampoline (acfg, cfg, method, call_target);
2349 #elif defined(TARGET_POWERPC)
2350 int this_pos = 3;
2352 fprintf (acfg->fp, "\n\taddi %d, %d, %d\n", this_pos, this_pos, (int)MONO_ABI_SIZEOF (MonoObject));
2353 fprintf (acfg->fp, "\n\tb %s\n", call_target);
2354 #else
2355 g_assert_not_reached ();
2356 #endif
2360 * arch_emit_static_rgctx_trampoline:
2362 * Emit code for a static rgctx trampoline. OFFSET is the offset of the first of
2363 * two GOT slots which contain the rgctx argument, and the method to jump to.
2364 * TRAMP_SIZE is set to the size of the emitted trampoline.
2365 * These kinds of trampolines cannot be enumerated statically, since there could
2366 * be one trampoline per method instantiation, so we emit the same code for all
2367 * trampolines, and parameterize them using two GOT slots.
2369 static void
2370 arch_emit_static_rgctx_trampoline (MonoAotCompile *acfg, int offset, int *tramp_size)
2372 #if defined(TARGET_AMD64)
2373 /* This should be exactly 13 bytes long */
2374 *tramp_size = 13;
2376 if (acfg->llvm) {
2377 emit_unset_mode (acfg);
2378 fprintf (acfg->fp, "mov %s+%d(%%rip), %%r10\n", acfg->got_symbol, (int)(offset * sizeof (target_mgreg_t)));
2379 fprintf (acfg->fp, "jmp *%s+%d(%%rip)\n", acfg->got_symbol, (int)((offset + 1) * sizeof (target_mgreg_t)));
2380 } else {
2381 /* mov <OFFSET>(%rip), %r10 */
2382 emit_byte (acfg, '\x4d');
2383 emit_byte (acfg, '\x8b');
2384 emit_byte (acfg, '\x15');
2385 emit_symbol_diff (acfg, acfg->got_symbol, ".", (offset * sizeof (target_mgreg_t)) - 4);
2387 /* jmp *<offset>(%rip) */
2388 emit_byte (acfg, '\xff');
2389 emit_byte (acfg, '\x25');
2390 emit_symbol_diff (acfg, acfg->got_symbol, ".", ((offset + 1) * sizeof (target_mgreg_t)) - 4);
2392 #elif defined(TARGET_ARM)
2393 guint8 buf [128];
2394 guint8 *code;
2396 /* This should be exactly 24 bytes long */
2397 *tramp_size = 24;
2398 code = buf;
2399 /* Load rgctx value */
2400 ARM_LDR_IMM (code, ARMREG_IP, ARMREG_PC, 8);
2401 ARM_LDR_REG_REG (code, MONO_ARCH_RGCTX_REG, ARMREG_PC, ARMREG_IP);
2402 /* Load branch addr + branch */
2403 ARM_LDR_IMM (code, ARMREG_IP, ARMREG_PC, 4);
2404 ARM_LDR_REG_REG (code, ARMREG_PC, ARMREG_PC, ARMREG_IP);
2406 g_assert (code - buf == 16);
2408 /* Emit it */
2409 emit_bytes (acfg, buf, code - buf);
2410 emit_symbol_diff (acfg, acfg->got_symbol, ".", (offset * sizeof (target_mgreg_t)) - 4 + 8);
2411 emit_symbol_diff (acfg, acfg->got_symbol, ".", ((offset + 1) * sizeof (target_mgreg_t)) - 4 + 4);
2412 #elif defined(TARGET_ARM64)
2413 arm64_emit_static_rgctx_trampoline (acfg, offset, tramp_size);
2414 #elif defined(TARGET_POWERPC)
2415 guint8 buf [128];
2416 guint8 *code;
2418 *tramp_size = 4;
2419 code = buf;
2422 * PPC has no ip relative addressing, so we need to compute the address
2423 * of the mscorlib got. That is slow and complex, so instead, we store it
2424 * in the second got slot of every aot image. The caller already computed
2425 * the address of its got and placed it into r30.
2427 emit_unset_mode (acfg);
2428 /* Load mscorlib got address */
2429 fprintf (acfg->fp, "%s 0, %d(30)\n", PPC_LD_OP, (int)sizeof (target_mgreg_t));
2430 /* Load rgctx */
2431 fprintf (acfg->fp, "lis 11, %d@h\n", (int)(offset * sizeof (target_mgreg_t)));
2432 fprintf (acfg->fp, "ori 11, 11, %d@l\n", (int)(offset * sizeof (target_mgreg_t)));
2433 fprintf (acfg->fp, "%s %d, 11, 0\n", PPC_LDX_OP, MONO_ARCH_RGCTX_REG);
2434 /* Load target address */
2435 fprintf (acfg->fp, "lis 11, %d@h\n", (int)((offset + 1) * sizeof (target_mgreg_t)));
2436 fprintf (acfg->fp, "ori 11, 11, %d@l\n", (int)((offset + 1) * sizeof (target_mgreg_t)));
2437 fprintf (acfg->fp, "%s 11, 11, 0\n", PPC_LDX_OP);
2438 #ifdef PPC_USES_FUNCTION_DESCRIPTOR
2439 fprintf (acfg->fp, "%s 2, %d(11)\n", PPC_LD_OP, (int)sizeof (target_mgreg_t));
2440 fprintf (acfg->fp, "%s 11, 0(11)\n", PPC_LD_OP);
2441 #endif
2442 fprintf (acfg->fp, "mtctr 11\n");
2443 /* Branch to the target address */
2444 fprintf (acfg->fp, "bctr\n");
2446 #ifdef PPC_USES_FUNCTION_DESCRIPTOR
2447 *tramp_size = 11 * 4;
2448 #else
2449 *tramp_size = 9 * 4;
2450 #endif
2452 #elif defined(TARGET_X86)
2453 guint8 buf [128];
2454 guint8 *code;
2456 /* Similar to the PPC code above */
2458 g_assert (MONO_ARCH_RGCTX_REG != X86_ECX);
2460 code = buf;
2461 /* Load mscorlib got address */
2462 x86_mov_reg_membase (code, X86_ECX, MONO_ARCH_GOT_REG, sizeof (target_mgreg_t), 4);
2463 /* Load arg */
2464 x86_mov_reg_membase (code, MONO_ARCH_RGCTX_REG, X86_ECX, offset * sizeof (target_mgreg_t), 4);
2465 /* Branch to the target address */
2466 x86_jump_membase (code, X86_ECX, (offset + 1) * sizeof (target_mgreg_t));
2468 emit_bytes (acfg, buf, code - buf);
2470 *tramp_size = 15;
2471 g_assert (code - buf == *tramp_size);
2472 #else
2473 g_assert_not_reached ();
2474 #endif
2478 * arch_emit_imt_trampoline:
2480 * Emit an IMT trampoline usable in full-aot mode. The trampoline uses 1 got slot which
2481 * points to an array of pointer pairs. The pairs of the form [key, ptr], where
2482 * key is the IMT key, and ptr holds the address of a memory location holding
2483 * the address to branch to if the IMT arg matches the key. The array is
2484 * terminated by a pair whose key is NULL, and whose ptr is the address of the
2485 * fail_tramp.
2486 * TRAMP_SIZE is set to the size of the emitted trampoline.
2488 static void
2489 arch_emit_imt_trampoline (MonoAotCompile *acfg, int offset, int *tramp_size)
2491 #if defined(TARGET_AMD64)
2492 guint8 *buf, *code;
2493 guint8 *labels [16];
2494 guint8 mov_buf[3];
2495 guint8 *mov_buf_ptr = mov_buf;
2497 const int kSizeOfMove = 7;
2499 code = buf = (guint8 *)g_malloc (256);
2501 /* FIXME: Optimize this, i.e. use binary search etc. */
2502 /* Maybe move the body into a separate function (slower, but much smaller) */
2504 /* MONO_ARCH_IMT_SCRATCH_REG is a free register */
2506 if (acfg->llvm) {
2507 emit_unset_mode (acfg);
2508 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));
2511 labels [0] = code;
2512 amd64_alu_membase_imm (code, X86_CMP, MONO_ARCH_IMT_SCRATCH_REG, 0, 0);
2513 labels [1] = code;
2514 amd64_branch8 (code, X86_CC_Z, 0, FALSE);
2516 /* Check key */
2517 amd64_alu_membase_reg_size (code, X86_CMP, MONO_ARCH_IMT_SCRATCH_REG, 0, MONO_ARCH_IMT_REG, sizeof (target_mgreg_t));
2518 labels [2] = code;
2519 amd64_branch8 (code, X86_CC_Z, 0, FALSE);
2521 /* Loop footer */
2522 amd64_alu_reg_imm (code, X86_ADD, MONO_ARCH_IMT_SCRATCH_REG, 2 * sizeof (target_mgreg_t));
2523 amd64_jump_code (code, labels [0]);
2525 /* Match */
2526 mono_amd64_patch (labels [2], code);
2527 amd64_mov_reg_membase (code, MONO_ARCH_IMT_SCRATCH_REG, MONO_ARCH_IMT_SCRATCH_REG, sizeof (target_mgreg_t), sizeof (target_mgreg_t));
2528 amd64_jump_membase (code, MONO_ARCH_IMT_SCRATCH_REG, 0);
2530 /* No match */
2531 mono_amd64_patch (labels [1], code);
2532 /* Load fail tramp */
2533 amd64_alu_reg_imm (code, X86_ADD, MONO_ARCH_IMT_SCRATCH_REG, sizeof (target_mgreg_t));
2534 /* Check if there is a fail tramp */
2535 amd64_alu_membase_imm (code, X86_CMP, MONO_ARCH_IMT_SCRATCH_REG, 0, 0);
2536 labels [3] = code;
2537 amd64_branch8 (code, X86_CC_Z, 0, FALSE);
2538 /* Jump to fail tramp */
2539 amd64_jump_membase (code, MONO_ARCH_IMT_SCRATCH_REG, 0);
2541 /* Fail */
2542 mono_amd64_patch (labels [3], code);
2543 x86_breakpoint (code);
2545 if (!acfg->llvm) {
2546 /* mov <OFFSET>(%rip), MONO_ARCH_IMT_SCRATCH_REG */
2547 amd64_emit_rex (mov_buf_ptr, sizeof(gpointer), MONO_ARCH_IMT_SCRATCH_REG, 0, AMD64_RIP);
2548 *(mov_buf_ptr)++ = (unsigned char)0x8b; /* mov opcode */
2549 x86_address_byte (mov_buf_ptr, 0, MONO_ARCH_IMT_SCRATCH_REG & 0x7, 5);
2550 emit_bytes (acfg, mov_buf, mov_buf_ptr - mov_buf);
2551 emit_symbol_diff (acfg, acfg->got_symbol, ".", (offset * sizeof (target_mgreg_t)) - 4);
2553 emit_bytes (acfg, buf, code - buf);
2555 *tramp_size = code - buf + kSizeOfMove;
2557 g_free (buf);
2559 #elif defined(TARGET_X86)
2560 guint8 *buf, *code;
2561 guint8 *labels [16];
2563 code = buf = g_malloc (256);
2565 /* Allocate a temporary stack slot */
2566 x86_push_reg (code, X86_EAX);
2567 /* Save EAX */
2568 x86_push_reg (code, X86_EAX);
2570 /* Load mscorlib got address */
2571 x86_mov_reg_membase (code, X86_EAX, MONO_ARCH_GOT_REG, sizeof (target_mgreg_t), 4);
2572 /* Load arg */
2573 x86_mov_reg_membase (code, X86_EAX, X86_EAX, offset * sizeof (target_mgreg_t), 4);
2575 labels [0] = code;
2576 x86_alu_membase_imm (code, X86_CMP, X86_EAX, 0, 0);
2577 labels [1] = code;
2578 x86_branch8 (code, X86_CC_Z, FALSE, 0);
2580 /* Check key */
2581 x86_alu_membase_reg (code, X86_CMP, X86_EAX, 0, MONO_ARCH_IMT_REG);
2582 labels [2] = code;
2583 x86_branch8 (code, X86_CC_Z, FALSE, 0);
2585 /* Loop footer */
2586 x86_alu_reg_imm (code, X86_ADD, X86_EAX, 2 * sizeof (target_mgreg_t));
2587 x86_jump_code (code, labels [0]);
2589 /* Match */
2590 mono_x86_patch (labels [2], code);
2591 x86_mov_reg_membase (code, X86_EAX, X86_EAX, sizeof (target_mgreg_t), 4);
2592 x86_mov_reg_membase (code, X86_EAX, X86_EAX, 0, 4);
2593 /* Save the target address to the temporary stack location */
2594 x86_mov_membase_reg (code, X86_ESP, 4, X86_EAX, 4);
2595 /* Restore EAX */
2596 x86_pop_reg (code, X86_EAX);
2597 /* Jump to the target address */
2598 x86_ret (code);
2600 /* No match */
2601 mono_x86_patch (labels [1], code);
2602 /* Load fail tramp */
2603 x86_mov_reg_membase (code, X86_EAX, X86_EAX, sizeof (target_mgreg_t), 4);
2604 x86_alu_membase_imm (code, X86_CMP, X86_EAX, 0, 0);
2605 labels [3] = code;
2606 x86_branch8 (code, X86_CC_Z, FALSE, 0);
2607 /* Jump to fail tramp */
2608 x86_mov_membase_reg (code, X86_ESP, 4, X86_EAX, 4);
2609 x86_pop_reg (code, X86_EAX);
2610 x86_ret (code);
2612 /* Fail */
2613 mono_x86_patch (labels [3], code);
2614 x86_breakpoint (code);
2616 emit_bytes (acfg, buf, code - buf);
2618 *tramp_size = code - buf;
2620 g_free (buf);
2622 #elif defined(TARGET_ARM)
2623 guint8 buf [128];
2624 guint8 *code, *code2, *labels [16];
2626 code = buf;
2628 /* The IMT method is in v5 */
2630 /* Need at least two free registers, plus a slot for storing the pc */
2631 ARM_PUSH (code, (1 << ARMREG_R0)|(1 << ARMREG_R1)|(1 << ARMREG_R2));
2632 labels [0] = code;
2633 /* Load the parameter from the GOT */
2634 ARM_LDR_IMM (code, ARMREG_R0, ARMREG_PC, 0);
2635 ARM_LDR_REG_REG (code, ARMREG_R0, ARMREG_PC, ARMREG_R0);
2637 labels [1] = code;
2638 ARM_LDR_IMM (code, ARMREG_R1, ARMREG_R0, 0);
2639 ARM_CMP_REG_REG (code, ARMREG_R1, ARMREG_V5);
2640 labels [2] = code;
2641 ARM_B_COND (code, ARMCOND_EQ, 0);
2643 /* End-of-loop check */
2644 ARM_CMP_REG_IMM (code, ARMREG_R1, 0, 0);
2645 labels [3] = code;
2646 ARM_B_COND (code, ARMCOND_EQ, 0);
2648 /* Loop footer */
2649 ARM_ADD_REG_IMM8 (code, ARMREG_R0, ARMREG_R0, sizeof (target_mgreg_t) * 2);
2650 labels [4] = code;
2651 ARM_B (code, 0);
2652 arm_patch (labels [4], labels [1]);
2654 /* Match */
2655 arm_patch (labels [2], code);
2656 ARM_LDR_IMM (code, ARMREG_R0, ARMREG_R0, 4);
2657 ARM_LDR_IMM (code, ARMREG_R0, ARMREG_R0, 0);
2658 /* Save it to the third stack slot */
2659 ARM_STR_IMM (code, ARMREG_R0, ARMREG_SP, 8);
2660 /* Restore the registers and branch */
2661 ARM_POP (code, (1 << ARMREG_R0)|(1 << ARMREG_R1)|(1 << ARMREG_PC));
2663 /* No match */
2664 arm_patch (labels [3], code);
2665 ARM_LDR_IMM (code, ARMREG_R0, ARMREG_R0, 4);
2666 ARM_STR_IMM (code, ARMREG_R0, ARMREG_SP, 8);
2667 ARM_POP (code, (1 << ARMREG_R0)|(1 << ARMREG_R1)|(1 << ARMREG_PC));
2669 /* Fixup offset */
2670 code2 = labels [0];
2671 ARM_LDR_IMM (code2, ARMREG_R0, ARMREG_PC, (code - (labels [0] + 8)));
2673 emit_bytes (acfg, buf, code - buf);
2674 emit_symbol_diff (acfg, acfg->got_symbol, ".", (offset * sizeof (target_mgreg_t)) + (code - (labels [0] + 8)) - 4);
2676 *tramp_size = code - buf + 4;
2677 #elif defined(TARGET_ARM64)
2678 arm64_emit_imt_trampoline (acfg, offset, tramp_size);
2679 #elif defined(TARGET_POWERPC)
2680 guint8 buf [128];
2681 guint8 *code, *labels [16];
2683 code = buf;
2685 /* Load the mscorlib got address */
2686 ppc_ldptr (code, ppc_r12, sizeof (target_mgreg_t), ppc_r30);
2687 /* Load the parameter from the GOT */
2688 ppc_load (code, ppc_r0, offset * sizeof (target_mgreg_t));
2689 ppc_ldptr_indexed (code, ppc_r12, ppc_r12, ppc_r0);
2691 /* Load and check key */
2692 labels [1] = code;
2693 ppc_ldptr (code, ppc_r0, 0, ppc_r12);
2694 ppc_cmp (code, 0, sizeof (target_mgreg_t) == 8 ? 1 : 0, ppc_r0, MONO_ARCH_IMT_REG);
2695 labels [2] = code;
2696 ppc_bc (code, PPC_BR_TRUE, PPC_BR_EQ, 0);
2698 /* End-of-loop check */
2699 ppc_cmpi (code, 0, sizeof (target_mgreg_t) == 8 ? 1 : 0, ppc_r0, 0);
2700 labels [3] = code;
2701 ppc_bc (code, PPC_BR_TRUE, PPC_BR_EQ, 0);
2703 /* Loop footer */
2704 ppc_addi (code, ppc_r12, ppc_r12, 2 * sizeof (target_mgreg_t));
2705 labels [4] = code;
2706 ppc_b (code, 0);
2707 mono_ppc_patch (labels [4], labels [1]);
2709 /* Match */
2710 mono_ppc_patch (labels [2], code);
2711 ppc_ldptr (code, ppc_r12, sizeof (target_mgreg_t), ppc_r12);
2712 /* r12 now contains the value of the vtable slot */
2713 /* this is not a function descriptor on ppc64 */
2714 ppc_ldptr (code, ppc_r12, 0, ppc_r12);
2715 ppc_mtctr (code, ppc_r12);
2716 ppc_bcctr (code, PPC_BR_ALWAYS, 0);
2718 /* Fail */
2719 mono_ppc_patch (labels [3], code);
2720 /* FIXME: */
2721 ppc_break (code);
2723 *tramp_size = code - buf;
2725 emit_bytes (acfg, buf, code - buf);
2726 #else
2727 g_assert_not_reached ();
2728 #endif
2732 #if defined (TARGET_AMD64)
2734 static void
2735 amd64_emit_load_got_slot (MonoAotCompile *acfg, int dreg, int got_slot)
2738 g_assert (acfg->fp);
2739 emit_unset_mode (acfg);
2741 fprintf (acfg->fp, "mov %s+%d(%%rip), %s\n", acfg->got_symbol, (unsigned int) ((got_slot * sizeof (target_mgreg_t))), mono_arch_regname (dreg));
2744 #endif
2748 * arch_emit_gsharedvt_arg_trampoline:
2750 * Emit code for a gsharedvt arg trampoline. OFFSET is the offset of the first of
2751 * two GOT slots which contain the argument, and the code to jump to.
2752 * TRAMP_SIZE is set to the size of the emitted trampoline.
2753 * These kinds of trampolines cannot be enumerated statically, since there could
2754 * be one trampoline per method instantiation, so we emit the same code for all
2755 * trampolines, and parameterize them using two GOT slots.
2757 static void
2758 arch_emit_gsharedvt_arg_trampoline (MonoAotCompile *acfg, int offset, int *tramp_size)
2760 #if defined(TARGET_X86)
2761 guint8 buf [128];
2762 guint8 *code;
2764 /* Similar to the PPC code above */
2766 g_assert (MONO_ARCH_RGCTX_REG != X86_ECX);
2768 code = buf;
2769 /* Load mscorlib got address */
2770 x86_mov_reg_membase (code, X86_ECX, MONO_ARCH_GOT_REG, sizeof (target_mgreg_t), 4);
2771 /* Load arg */
2772 x86_mov_reg_membase (code, X86_EAX, X86_ECX, offset * sizeof (target_mgreg_t), 4);
2773 /* Branch to the target address */
2774 x86_jump_membase (code, X86_ECX, (offset + 1) * sizeof (target_mgreg_t));
2776 emit_bytes (acfg, buf, code - buf);
2778 *tramp_size = 15;
2779 g_assert (code - buf == *tramp_size);
2780 #elif defined(TARGET_ARM)
2781 guint8 buf [128];
2782 guint8 *code;
2784 /* The same as mono_arch_get_gsharedvt_arg_trampoline (), but for AOT */
2785 /* Similar to arch_emit_specific_trampoline () */
2786 *tramp_size = 24;
2787 code = buf;
2788 ARM_PUSH (code, (1 << ARMREG_R0) | (1 << ARMREG_R1) | (1 << ARMREG_R2) | (1 << ARMREG_R3));
2789 ARM_LDR_IMM (code, ARMREG_R1, ARMREG_PC, 8);
2790 /* Load the arg value from the GOT */
2791 ARM_LDR_REG_REG (code, ARMREG_R0, ARMREG_PC, ARMREG_R1);
2792 /* Load the addr from the GOT */
2793 ARM_LDR_REG_REG (code, ARMREG_R1, ARMREG_PC, ARMREG_R1);
2794 /* Branch to it */
2795 ARM_BX (code, ARMREG_R1);
2797 g_assert (code - buf == 20);
2799 /* Emit it */
2800 emit_bytes (acfg, buf, code - buf);
2801 emit_symbol_diff (acfg, acfg->got_symbol, ".", (offset * sizeof (target_mgreg_t)) + 4);
2802 #elif defined(TARGET_ARM64)
2803 arm64_emit_gsharedvt_arg_trampoline (acfg, offset, tramp_size);
2804 #elif defined (TARGET_AMD64)
2806 amd64_emit_load_got_slot (acfg, AMD64_RAX, offset);
2807 amd64_emit_load_got_slot (acfg, MONO_ARCH_IMT_SCRATCH_REG, offset + 1);
2808 g_assert (AMD64_R11 == MONO_ARCH_IMT_SCRATCH_REG);
2809 fprintf (acfg->fp, "jmp *%%r11\n");
2811 *tramp_size = 0x11;
2812 #else
2813 g_assert_not_reached ();
2814 #endif
2817 static void
2818 arch_emit_ftnptr_arg_trampoline (MonoAotCompile *acfg, int offset, int *tramp_size)
2820 #if defined(TARGET_ARM)
2821 guint8 buf [128];
2822 guint8 *code;
2824 *tramp_size = 32;
2825 code = buf;
2827 /* Load target address and push it on stack */
2828 ARM_LDR_IMM (code, ARMREG_IP, ARMREG_PC, 16);
2829 ARM_LDR_REG_REG (code, ARMREG_IP, ARMREG_PC, ARMREG_IP);
2830 ARM_PUSH (code, 1 << ARMREG_IP);
2831 /* Load argument in ARMREG_IP */
2832 ARM_LDR_IMM (code, ARMREG_IP, ARMREG_PC, 8);
2833 ARM_LDR_REG_REG (code, ARMREG_IP, ARMREG_PC, ARMREG_IP);
2834 /* Branch */
2835 ARM_POP (code, 1 << ARMREG_PC);
2837 g_assert (code - buf == 24);
2839 /* Emit it */
2840 emit_bytes (acfg, buf, code - buf);
2841 emit_symbol_diff (acfg, acfg->got_symbol, ".", ((offset + 1) * sizeof (target_mgreg_t)) + 12); // offset from ldr pc to addr
2842 emit_symbol_diff (acfg, acfg->got_symbol, ".", (offset * sizeof (target_mgreg_t)) + 4); // offset from ldr pc to arg
2843 #else
2844 g_assert_not_reached ();
2845 #endif
2848 static void
2849 arch_emit_unbox_arbitrary_trampoline (MonoAotCompile *acfg, int offset, int *tramp_size)
2851 #if defined(TARGET_ARM64)
2852 emit_unset_mode (acfg);
2853 fprintf (acfg->fp, "add x0, x0, %d\n", (int)(MONO_ABI_SIZEOF (MonoObject)));
2854 arm64_emit_load_got_slot (acfg, ARMREG_R17, offset);
2855 fprintf (acfg->fp, "br x17\n");
2856 *tramp_size = 5 * 4;
2857 #elif defined (TARGET_AMD64)
2858 guint8 buf [32];
2859 guint8 *code;
2860 int this_reg;
2862 this_reg = mono_arch_get_this_arg_reg (NULL);
2863 code = buf;
2864 amd64_alu_reg_imm (code, X86_ADD, this_reg, MONO_ABI_SIZEOF (MonoObject));
2865 emit_bytes (acfg, buf, code - buf);
2867 amd64_emit_load_got_slot (acfg, AMD64_RAX, offset);
2868 fprintf (acfg->fp, "jmp *%%rax\n");
2870 *tramp_size = 13;
2871 #elif defined (TARGET_ARM)
2872 guint8 buf [32];
2873 guint8 *code, *label;
2875 code = buf;
2876 /* Unbox */
2877 ARM_ADD_REG_IMM8 (code, ARMREG_R0, ARMREG_R0, MONO_ABI_SIZEOF (MonoObject));
2879 label = code;
2880 /* Calculate GOT slot */
2881 ARM_LDR_IMM (code, ARMREG_IP, ARMREG_PC, 0);
2882 /* Load target addr into PC*/
2883 ARM_LDR_REG_REG (code, ARMREG_PC, ARMREG_PC, ARMREG_IP);
2885 g_assert (code - buf == 12);
2887 /* Emit it */
2888 emit_bytes (acfg, buf, code - buf);
2889 emit_symbol_diff (acfg, acfg->got_symbol, ".", (offset * sizeof (target_mgreg_t)) + (code - (label + 8)) - 4);
2890 *tramp_size = 4 * 4;
2891 #else
2892 g_error ("NOT IMPLEMENTED: needed for AOT<>interp mixed mode transition");
2893 #endif
2896 /* END OF ARCH SPECIFIC CODE */
2898 static guint32
2899 mono_get_field_token (MonoClassField *field)
2901 MonoClass *klass = field->parent;
2902 int i;
2904 int fcount = mono_class_get_field_count (klass);
2905 MonoClassField *klass_fields = m_class_get_fields (klass);
2906 for (i = 0; i < fcount; ++i) {
2907 if (field == &klass_fields [i])
2908 return MONO_TOKEN_FIELD_DEF | (mono_class_get_first_field_idx (klass) + 1 + i);
2911 g_assert_not_reached ();
2912 return 0;
2915 static inline void
2916 encode_value (gint32 value, guint8 *buf, guint8 **endbuf)
2918 guint8 *p = buf;
2920 //printf ("ENCODE: %d 0x%x.\n", value, value);
2923 * Same encoding as the one used in the metadata, extended to handle values
2924 * greater than 0x1fffffff.
2926 if ((value >= 0) && (value <= 127))
2927 *p++ = value;
2928 else if ((value >= 0) && (value <= 16383)) {
2929 p [0] = 0x80 | (value >> 8);
2930 p [1] = value & 0xff;
2931 p += 2;
2932 } else if ((value >= 0) && (value <= 0x1fffffff)) {
2933 p [0] = (value >> 24) | 0xc0;
2934 p [1] = (value >> 16) & 0xff;
2935 p [2] = (value >> 8) & 0xff;
2936 p [3] = value & 0xff;
2937 p += 4;
2939 else {
2940 p [0] = 0xff;
2941 p [1] = (value >> 24) & 0xff;
2942 p [2] = (value >> 16) & 0xff;
2943 p [3] = (value >> 8) & 0xff;
2944 p [4] = value & 0xff;
2945 p += 5;
2947 if (endbuf)
2948 *endbuf = p;
2951 static void
2952 stream_init (MonoDynamicStream *sh)
2954 sh->index = 0;
2955 sh->alloc_size = 4096;
2956 sh->data = (char *)g_malloc (4096);
2958 /* So offsets are > 0 */
2959 sh->data [0] = 0;
2960 sh->index ++;
2963 static void
2964 make_room_in_stream (MonoDynamicStream *stream, int size)
2966 if (size <= stream->alloc_size)
2967 return;
2969 while (stream->alloc_size <= size) {
2970 if (stream->alloc_size < 4096)
2971 stream->alloc_size = 4096;
2972 else
2973 stream->alloc_size *= 2;
2976 stream->data = (char *)g_realloc (stream->data, stream->alloc_size);
2979 static guint32
2980 add_stream_data (MonoDynamicStream *stream, const char *data, guint32 len)
2982 guint32 idx;
2984 make_room_in_stream (stream, stream->index + len);
2985 memcpy (stream->data + stream->index, data, len);
2986 idx = stream->index;
2987 stream->index += len;
2988 return idx;
2992 * add_to_blob:
2994 * Add data to the binary blob inside the aot image. Returns the offset inside the
2995 * blob where the data was stored.
2997 static guint32
2998 add_to_blob (MonoAotCompile *acfg, const guint8 *data, guint32 data_len)
3000 g_assert (!acfg->blob_closed);
3002 if (acfg->blob.alloc_size == 0)
3003 stream_init (&acfg->blob);
3005 acfg->stats.blob_size += data_len;
3007 return add_stream_data (&acfg->blob, (char*)data, data_len);
3010 static guint32
3011 add_to_blob_aligned (MonoAotCompile *acfg, const guint8 *data, guint32 data_len, guint32 align)
3013 char buf [4] = {0};
3014 guint32 count;
3016 if (acfg->blob.alloc_size == 0)
3017 stream_init (&acfg->blob);
3019 count = acfg->blob.index % align;
3021 /* we assume the stream data will be aligned */
3022 if (count)
3023 add_stream_data (&acfg->blob, buf, 4 - count);
3025 return add_stream_data (&acfg->blob, (char*)data, data_len);
3028 /* Emit a table of data into the aot image */
3029 static void
3030 emit_aot_data (MonoAotCompile *acfg, MonoAotFileTable table, const char *symbol, guint8 *data, int size)
3032 if (acfg->data_outfile) {
3033 acfg->table_offsets [(int)table] = acfg->datafile_offset;
3034 fwrite (data,1, size, acfg->data_outfile);
3035 acfg->datafile_offset += size;
3036 // align the data to 8 bytes. Put zeros in the file (so that every build results in consistent output).
3037 int align = 8 - size % 8;
3038 acfg->datafile_offset += align;
3039 guint8 align_buf [16];
3040 memset (&align_buf, 0, sizeof (align_buf));
3041 fwrite (align_buf, align, 1, acfg->data_outfile);
3042 } else if (acfg->llvm) {
3043 mono_llvm_emit_aot_data (symbol, data, size);
3044 } else {
3045 emit_section_change (acfg, RODATA_SECT, 0);
3046 emit_alignment (acfg, 8);
3047 emit_label (acfg, symbol);
3048 emit_bytes (acfg, data, size);
3053 * emit_offset_table:
3055 * Emit a table of increasing offsets in a compact form using differential encoding.
3056 * There is an index entry for each GROUP_SIZE number of entries. The greater the
3057 * group size, the more compact the table becomes, but the slower it becomes to compute
3058 * a given entry. Returns the size of the table.
3060 static guint32
3061 emit_offset_table (MonoAotCompile *acfg, const char *symbol, MonoAotFileTable table, int noffsets, int group_size, gint32 *offsets)
3063 gint32 current_offset;
3064 int i, buf_size, ngroups, index_entry_size;
3065 guint8 *p, *buf;
3066 guint8 *data_p, *data_buf;
3067 guint32 *index_offsets;
3069 ngroups = (noffsets + (group_size - 1)) / group_size;
3071 index_offsets = g_new0 (guint32, ngroups);
3073 buf_size = noffsets * 4;
3074 p = buf = (guint8 *)g_malloc0 (buf_size);
3076 current_offset = 0;
3077 for (i = 0; i < noffsets; ++i) {
3078 //printf ("D: %d -> %d\n", i, offsets [i]);
3079 if ((i % group_size) == 0) {
3080 index_offsets [i / group_size] = p - buf;
3081 /* Emit the full value for these entries */
3082 encode_value (offsets [i], p, &p);
3083 } else {
3084 /* The offsets are allowed to be non-increasing */
3085 //g_assert (offsets [i] >= current_offset);
3086 encode_value (offsets [i] - current_offset, p, &p);
3088 current_offset = offsets [i];
3090 data_buf = buf;
3091 data_p = p;
3093 if (ngroups && index_offsets [ngroups - 1] < 65000)
3094 index_entry_size = 2;
3095 else
3096 index_entry_size = 4;
3098 buf_size = (data_p - data_buf) + (ngroups * 4) + 16;
3099 p = buf = (guint8 *)g_malloc0 (buf_size);
3101 /* Emit the header */
3102 encode_int (noffsets, p, &p);
3103 encode_int (group_size, p, &p);
3104 encode_int (ngroups, p, &p);
3105 encode_int (index_entry_size, p, &p);
3107 /* Emit the index */
3108 for (i = 0; i < ngroups; ++i) {
3109 if (index_entry_size == 2)
3110 encode_int16 (index_offsets [i], p, &p);
3111 else
3112 encode_int (index_offsets [i], p, &p);
3114 /* Emit the data */
3115 memcpy (p, data_buf, data_p - data_buf);
3116 p += data_p - data_buf;
3118 g_assert (p - buf <= buf_size);
3120 emit_aot_data (acfg, table, symbol, buf, p - buf);
3122 g_free (buf);
3123 g_free (data_buf);
3125 return (int)(p - buf);
3128 static guint32
3129 get_image_index (MonoAotCompile *cfg, MonoImage *image)
3131 guint32 index;
3133 index = GPOINTER_TO_UINT (g_hash_table_lookup (cfg->image_hash, image));
3134 if (index)
3135 return index - 1;
3136 else {
3137 index = g_hash_table_size (cfg->image_hash);
3138 g_hash_table_insert (cfg->image_hash, image, GUINT_TO_POINTER (index + 1));
3139 g_ptr_array_add (cfg->image_table, image);
3140 return index;
3144 static guint32
3145 find_typespec_for_class (MonoAotCompile *acfg, MonoClass *klass)
3147 int i;
3148 int len = acfg->image->tables [MONO_TABLE_TYPESPEC].rows;
3150 /* FIXME: Search referenced images as well */
3151 if (!acfg->typespec_classes) {
3152 acfg->typespec_classes = g_hash_table_new (NULL, NULL);
3153 for (i = 0; i < len; i++) {
3154 ERROR_DECL (error);
3155 int typespec = MONO_TOKEN_TYPE_SPEC | (i + 1);
3156 MonoClass *klass_key = mono_class_get_and_inflate_typespec_checked (acfg->image, typespec, NULL, error);
3157 if (!is_ok (error)) {
3158 mono_error_cleanup (error);
3159 continue;
3161 g_hash_table_insert (acfg->typespec_classes, klass_key, GINT_TO_POINTER (typespec));
3164 return GPOINTER_TO_INT (g_hash_table_lookup (acfg->typespec_classes, klass));
3167 static void
3168 encode_method_ref (MonoAotCompile *acfg, MonoMethod *method, guint8 *buf, guint8 **endbuf);
3170 static void
3171 encode_klass_ref (MonoAotCompile *acfg, MonoClass *klass, guint8 *buf, guint8 **endbuf);
3173 static void
3174 encode_ginst (MonoAotCompile *acfg, MonoGenericInst *inst, guint8 *buf, guint8 **endbuf);
3176 static void
3177 encode_type (MonoAotCompile *acfg, MonoType *t, guint8 *buf, guint8 **endbuf);
3179 static guint32
3180 get_shared_ginst_ref (MonoAotCompile *acfg, MonoGenericInst *ginst);
3182 static void
3183 encode_klass_ref_inner (MonoAotCompile *acfg, MonoClass *klass, guint8 *buf, guint8 **endbuf)
3185 guint8 *p = buf;
3188 * The encoding begins with one of the MONO_AOT_TYPEREF values, followed by additional
3189 * information.
3192 if (mono_class_is_ginst (klass)) {
3193 guint32 token;
3194 g_assert (m_class_get_type_token (klass));
3196 /* Find a typespec for a class if possible */
3197 token = find_typespec_for_class (acfg, klass);
3198 if (token) {
3199 encode_value (MONO_AOT_TYPEREF_TYPESPEC_TOKEN, p, &p);
3200 encode_value (token, p, &p);
3201 } else {
3202 MonoClass *gclass = mono_class_get_generic_class (klass)->container_class;
3203 MonoGenericInst *inst = mono_class_get_generic_class (klass)->context.class_inst;
3204 static int count = 0;
3205 guint8 *p1 = p;
3207 encode_value (MONO_AOT_TYPEREF_GINST, p, &p);
3208 encode_klass_ref (acfg, gclass, p, &p);
3209 guint32 offset = get_shared_ginst_ref (acfg, inst);
3210 encode_value (offset, p, &p);
3212 count += p - p1;
3214 } else if (m_class_get_type_token (klass)) {
3215 int iindex = get_image_index (acfg, m_class_get_image (klass));
3217 g_assert (mono_metadata_token_code (m_class_get_type_token (klass)) == MONO_TOKEN_TYPE_DEF);
3218 if (iindex == 0) {
3219 encode_value (MONO_AOT_TYPEREF_TYPEDEF_INDEX, p, &p);
3220 encode_value (m_class_get_type_token (klass) - MONO_TOKEN_TYPE_DEF, p, &p);
3221 } else {
3222 encode_value (MONO_AOT_TYPEREF_TYPEDEF_INDEX_IMAGE, p, &p);
3223 encode_value (m_class_get_type_token (klass) - MONO_TOKEN_TYPE_DEF, p, &p);
3224 encode_value (get_image_index (acfg, m_class_get_image (klass)), p, &p);
3226 } else if ((m_class_get_byval_arg (klass)->type == MONO_TYPE_VAR) || (m_class_get_byval_arg (klass)->type == MONO_TYPE_MVAR)) {
3227 MonoGenericContainer *container = mono_type_get_generic_param_owner (m_class_get_byval_arg (klass));
3228 MonoGenericParam *par = m_class_get_byval_arg (klass)->data.generic_param;
3230 encode_value (MONO_AOT_TYPEREF_VAR, p, &p);
3232 encode_value (par->gshared_constraint ? 1 : 0, p, &p);
3233 if (par->gshared_constraint) {
3234 MonoGSharedGenericParam *gpar = (MonoGSharedGenericParam*)par;
3235 encode_type (acfg, par->gshared_constraint, p, &p);
3236 encode_klass_ref (acfg, mono_class_create_generic_parameter (gpar->parent), p, &p);
3237 } else {
3238 encode_value (m_class_get_byval_arg (klass)->type, p, &p);
3239 encode_value (mono_type_get_generic_param_num (m_class_get_byval_arg (klass)), p, &p);
3241 encode_value (container->is_anonymous ? 0 : 1, p, &p);
3243 if (!container->is_anonymous) {
3244 encode_value (container->is_method, p, &p);
3245 if (container->is_method)
3246 encode_method_ref (acfg, container->owner.method, p, &p);
3247 else
3248 encode_klass_ref (acfg, container->owner.klass, p, &p);
3251 } else if (m_class_get_byval_arg (klass)->type == MONO_TYPE_PTR) {
3252 encode_value (MONO_AOT_TYPEREF_PTR, p, &p);
3253 encode_type (acfg, m_class_get_byval_arg (klass), p, &p);
3254 } else {
3255 /* Array class */
3256 g_assert (m_class_get_rank (klass) > 0);
3257 encode_value (MONO_AOT_TYPEREF_ARRAY, p, &p);
3258 encode_value (m_class_get_rank (klass), p, &p);
3259 encode_klass_ref (acfg, m_class_get_element_class (klass), p, &p);
3262 acfg->stats.class_ref_count++;
3263 acfg->stats.class_ref_size += p - buf;
3265 *endbuf = p;
3268 static guint32
3269 get_shared_klass_ref (MonoAotCompile *acfg, MonoClass *klass)
3271 guint offset = GPOINTER_TO_UINT (g_hash_table_lookup (acfg->klass_blob_hash, klass));
3272 guint8 *buf2, *p;
3274 if (!offset) {
3275 buf2 = (guint8 *)g_malloc (1024);
3276 p = buf2;
3278 encode_klass_ref_inner (acfg, klass, p, &p);
3279 g_assert (p - buf2 < 1024);
3281 offset = add_to_blob (acfg, buf2, p - buf2);
3282 g_free (buf2);
3284 g_hash_table_insert (acfg->klass_blob_hash, klass, GUINT_TO_POINTER (offset + 1));
3285 } else {
3286 offset --;
3289 return offset;
3293 * encode_klass_ref:
3295 * Encode a reference to KLASS. We use our home-grown encoding instead of the
3296 * standard metadata encoding.
3298 static void
3299 encode_klass_ref (MonoAotCompile *acfg, MonoClass *klass, guint8 *buf, guint8 **endbuf)
3301 gboolean shared = FALSE;
3304 * The encoding of generic instances is large so emit them only once.
3306 if (mono_class_is_ginst (klass)) {
3307 guint32 token;
3308 g_assert (m_class_get_type_token (klass));
3310 /* Find a typespec for a class if possible */
3311 token = find_typespec_for_class (acfg, klass);
3312 if (!token)
3313 shared = TRUE;
3314 } else if ((m_class_get_byval_arg (klass)->type == MONO_TYPE_VAR) || (m_class_get_byval_arg (klass)->type == MONO_TYPE_MVAR)) {
3315 shared = TRUE;
3318 if (shared) {
3319 guint8 *p;
3320 guint32 offset = get_shared_klass_ref (acfg, klass);
3322 p = buf;
3323 encode_value (MONO_AOT_TYPEREF_BLOB_INDEX, p, &p);
3324 encode_value (offset, p, &p);
3325 *endbuf = p;
3326 return;
3329 encode_klass_ref_inner (acfg, klass, buf, endbuf);
3332 static void
3333 encode_field_info (MonoAotCompile *cfg, MonoClassField *field, guint8 *buf, guint8 **endbuf)
3335 guint32 token = mono_get_field_token (field);
3336 guint8 *p = buf;
3338 encode_klass_ref (cfg, field->parent, p, &p);
3339 g_assert (mono_metadata_token_code (token) == MONO_TOKEN_FIELD_DEF);
3340 encode_value (token - MONO_TOKEN_FIELD_DEF, p, &p);
3341 *endbuf = p;
3344 static void
3345 encode_ginst (MonoAotCompile *acfg, MonoGenericInst *inst, guint8 *buf, guint8 **endbuf)
3347 guint8 *p = buf;
3348 int i;
3350 encode_value (inst->type_argc, p, &p);
3351 for (i = 0; i < inst->type_argc; ++i)
3352 encode_klass_ref (acfg, mono_class_from_mono_type_internal (inst->type_argv [i]), p, &p);
3354 acfg->stats.ginst_count++;
3355 acfg->stats.ginst_size += p - buf;
3357 *endbuf = p;
3360 static guint32
3361 get_shared_ginst_ref (MonoAotCompile *acfg, MonoGenericInst *ginst)
3363 guint32 offset = GPOINTER_TO_UINT (g_hash_table_lookup (acfg->ginst_blob_hash, ginst));
3364 if (!offset) {
3365 guint8 *buf2, *p2;
3367 buf2 = (guint8 *)g_malloc (1024);
3368 p2 = buf2;
3370 encode_ginst (acfg, ginst, p2, &p2);
3371 g_assert (p2 - buf2 < 1024);
3373 offset = add_to_blob (acfg, buf2, p2 - buf2);
3374 g_free (buf2);
3376 g_hash_table_insert (acfg->ginst_blob_hash, ginst, GUINT_TO_POINTER (offset + 1));
3377 } else {
3378 offset --;
3380 return offset;
3383 static void
3384 encode_generic_context (MonoAotCompile *acfg, MonoGenericContext *context, guint8 *buf, guint8 **endbuf)
3386 guint8 *p = buf;
3387 MonoGenericInst *inst;
3388 guint32 flags = (context->class_inst ? 1 : 0) | (context->method_inst ? 2 : 0);
3390 g_assert (flags);
3392 encode_value (flags, p, &p);
3393 inst = context->class_inst;
3394 if (inst) {
3395 guint32 offset = get_shared_ginst_ref (acfg, inst);
3396 encode_value (offset, p, &p);
3398 inst = context->method_inst;
3399 if (inst) {
3400 guint32 offset = get_shared_ginst_ref (acfg, inst);
3401 encode_value (offset, p, &p);
3403 *endbuf = p;
3406 static void
3407 encode_type (MonoAotCompile *acfg, MonoType *t, guint8 *buf, guint8 **endbuf)
3409 guint8 *p = buf;
3411 if (t->has_cmods) {
3412 int count = mono_type_custom_modifier_count (t);
3414 *p = MONO_TYPE_CMOD_REQD;
3415 ++p;
3417 encode_value (count, p, &p);
3418 for (int i = 0; i < count; ++i) {
3419 ERROR_DECL (error);
3420 gboolean required;
3421 MonoType *cmod_type = mono_type_get_custom_modifier (t, i, &required, error);
3422 mono_error_assert_ok (error);
3423 encode_value (required, p, &p);
3424 encode_type (acfg, cmod_type, p, &p);
3428 /* t->attrs can be ignored */
3429 //g_assert (t->attrs == 0);
3431 if (t->pinned) {
3432 *p = MONO_TYPE_PINNED;
3433 ++p;
3435 if (t->byref) {
3436 *p = MONO_TYPE_BYREF;
3437 ++p;
3440 *p = t->type;
3441 p ++;
3443 switch (t->type) {
3444 case MONO_TYPE_VOID:
3445 case MONO_TYPE_BOOLEAN:
3446 case MONO_TYPE_CHAR:
3447 case MONO_TYPE_I1:
3448 case MONO_TYPE_U1:
3449 case MONO_TYPE_I2:
3450 case MONO_TYPE_U2:
3451 case MONO_TYPE_I4:
3452 case MONO_TYPE_U4:
3453 case MONO_TYPE_I8:
3454 case MONO_TYPE_U8:
3455 case MONO_TYPE_R4:
3456 case MONO_TYPE_R8:
3457 case MONO_TYPE_I:
3458 case MONO_TYPE_U:
3459 case MONO_TYPE_STRING:
3460 case MONO_TYPE_OBJECT:
3461 case MONO_TYPE_TYPEDBYREF:
3462 break;
3463 case MONO_TYPE_VALUETYPE:
3464 case MONO_TYPE_CLASS:
3465 encode_klass_ref (acfg, mono_class_from_mono_type_internal (t), p, &p);
3466 break;
3467 case MONO_TYPE_SZARRAY:
3468 encode_klass_ref (acfg, t->data.klass, p, &p);
3469 break;
3470 case MONO_TYPE_PTR:
3471 encode_type (acfg, t->data.type, p, &p);
3472 break;
3473 case MONO_TYPE_GENERICINST: {
3474 MonoClass *gclass = t->data.generic_class->container_class;
3475 MonoGenericInst *inst = t->data.generic_class->context.class_inst;
3477 encode_klass_ref (acfg, gclass, p, &p);
3478 encode_ginst (acfg, inst, p, &p);
3479 break;
3481 case MONO_TYPE_ARRAY: {
3482 MonoArrayType *array = t->data.array;
3483 int i;
3485 encode_klass_ref (acfg, array->eklass, p, &p);
3486 encode_value (array->rank, p, &p);
3487 encode_value (array->numsizes, p, &p);
3488 for (i = 0; i < array->numsizes; ++i)
3489 encode_value (array->sizes [i], p, &p);
3490 encode_value (array->numlobounds, p, &p);
3491 for (i = 0; i < array->numlobounds; ++i)
3492 encode_value (array->lobounds [i], p, &p);
3493 break;
3495 case MONO_TYPE_VAR:
3496 case MONO_TYPE_MVAR:
3497 encode_klass_ref (acfg, mono_class_from_mono_type_internal (t), p, &p);
3498 break;
3499 default:
3500 g_assert_not_reached ();
3503 *endbuf = p;
3506 static void
3507 encode_signature (MonoAotCompile *acfg, MonoMethodSignature *sig, guint8 *buf, guint8 **endbuf)
3509 guint8 *p = buf;
3510 guint32 flags = 0;
3511 int i;
3513 /* Similar to the metadata encoding */
3514 if (sig->generic_param_count)
3515 flags |= 0x10;
3516 if (sig->hasthis)
3517 flags |= 0x20;
3518 if (sig->explicit_this)
3519 flags |= 0x40;
3520 flags |= (sig->call_convention & 0x0F);
3522 *p = flags;
3523 ++p;
3524 if (sig->generic_param_count)
3525 encode_value (sig->generic_param_count, p, &p);
3526 encode_value (sig->param_count, p, &p);
3528 encode_type (acfg, sig->ret, p, &p);
3529 for (i = 0; i < sig->param_count; ++i) {
3530 if (sig->sentinelpos == i) {
3531 *p = MONO_TYPE_SENTINEL;
3532 ++p;
3534 encode_type (acfg, sig->params [i], p, &p);
3537 *endbuf = p;
3540 static void
3541 encode_icall (gpointer func, guint8 *p, guint8 **end)
3543 MonoJitICallInfo *callinfo = mono_find_jit_icall_by_addr (func);
3544 g_assert (callinfo);
3545 strcpy ((char *) p, callinfo->name);
3546 p += strlen (callinfo->name) + 1;
3547 *end = p;
3550 #define MAX_IMAGE_INDEX 250
3552 static void
3553 encode_method_ref (MonoAotCompile *acfg, MonoMethod *method, guint8 *buf, guint8 **endbuf)
3555 guint32 image_index = get_image_index (acfg, m_class_get_image (method->klass));
3556 guint32 token = method->token;
3557 MonoJumpInfoToken *ji;
3558 guint8 *p = buf;
3561 * The encoding for most methods is as follows:
3562 * - image index encoded as a leb128
3563 * - token index encoded as a leb128
3564 * Values of image index >= MONO_AOT_METHODREF_MIN are used to mark additional
3565 * types of method encodings.
3568 /* Mark methods which can't use aot trampolines because they need the further
3569 * processing in mono_magic_trampoline () which requires a MonoMethod*.
3571 if ((method->is_generic && (method->flags & METHOD_ATTRIBUTE_VIRTUAL)) ||
3572 (method->iflags & METHOD_IMPL_ATTRIBUTE_SYNCHRONIZED))
3573 encode_value ((MONO_AOT_METHODREF_NO_AOT_TRAMPOLINE << 24), p, &p);
3575 if (method->wrapper_type) {
3576 WrapperInfo *info = mono_marshal_get_wrapper_info (method);
3578 encode_value ((MONO_AOT_METHODREF_WRAPPER << 24), p, &p);
3580 encode_value (method->wrapper_type, p, &p);
3582 switch (method->wrapper_type) {
3583 case MONO_WRAPPER_REMOTING_INVOKE:
3584 case MONO_WRAPPER_REMOTING_INVOKE_WITH_CHECK:
3585 case MONO_WRAPPER_XDOMAIN_INVOKE: {
3586 MonoMethod *m;
3588 m = mono_marshal_method_from_wrapper (method);
3589 g_assert (m);
3590 encode_method_ref (acfg, m, p, &p);
3591 break;
3593 case MONO_WRAPPER_PROXY_ISINST:
3594 case MONO_WRAPPER_LDFLD:
3595 case MONO_WRAPPER_LDFLDA:
3596 case MONO_WRAPPER_STFLD: {
3597 g_assert (info);
3598 encode_klass_ref (acfg, info->d.proxy.klass, p, &p);
3599 break;
3601 case MONO_WRAPPER_ALLOC: {
3602 /* The GC name is saved once in MonoAotFileInfo */
3603 g_assert (info->d.alloc.alloc_type != -1);
3604 encode_value (info->d.alloc.alloc_type, p, &p);
3605 break;
3607 case MONO_WRAPPER_WRITE_BARRIER: {
3608 g_assert (info);
3609 break;
3611 case MONO_WRAPPER_STELEMREF: {
3612 g_assert (info);
3613 encode_value (info->subtype, p, &p);
3614 if (info->subtype == WRAPPER_SUBTYPE_VIRTUAL_STELEMREF)
3615 encode_value (info->d.virtual_stelemref.kind, p, &p);
3616 break;
3618 case MONO_WRAPPER_OTHER: {
3619 g_assert (info);
3620 encode_value (info->subtype, p, &p);
3621 if (info->subtype == WRAPPER_SUBTYPE_PTR_TO_STRUCTURE ||
3622 info->subtype == WRAPPER_SUBTYPE_STRUCTURE_TO_PTR)
3623 encode_klass_ref (acfg, method->klass, p, &p);
3624 else if (info->subtype == WRAPPER_SUBTYPE_SYNCHRONIZED_INNER)
3625 encode_method_ref (acfg, info->d.synchronized_inner.method, p, &p);
3626 else if (info->subtype == WRAPPER_SUBTYPE_ARRAY_ACCESSOR)
3627 encode_method_ref (acfg, info->d.array_accessor.method, p, &p);
3628 else if (info->subtype == WRAPPER_SUBTYPE_INTERP_IN)
3629 encode_signature (acfg, info->d.interp_in.sig, p, &p);
3630 else if (info->subtype == WRAPPER_SUBTYPE_GSHAREDVT_IN_SIG)
3631 encode_signature (acfg, info->d.gsharedvt.sig, p, &p);
3632 else if (info->subtype == WRAPPER_SUBTYPE_GSHAREDVT_OUT_SIG)
3633 encode_signature (acfg, info->d.gsharedvt.sig, p, &p);
3634 else if (info->subtype == WRAPPER_SUBTYPE_INTERP_LMF)
3635 encode_icall (info->d.icall.func, p, &p);
3636 else if (info->subtype == WRAPPER_SUBTYPE_AOT_INIT)
3637 encode_value (info->d.aot_init.subtype, p, &p);
3638 break;
3640 case MONO_WRAPPER_MANAGED_TO_NATIVE: {
3641 g_assert (info);
3642 encode_value (info->subtype, p, &p);
3643 if (info->subtype == WRAPPER_SUBTYPE_ICALL_WRAPPER) {
3644 encode_icall (info->d.icall.func, p, &p);
3645 } else if (info->subtype == WRAPPER_SUBTYPE_NATIVE_FUNC_AOT) {
3646 encode_method_ref (acfg, info->d.managed_to_native.method, p, &p);
3647 } else {
3648 g_assert (info->subtype == WRAPPER_SUBTYPE_NONE || info->subtype == WRAPPER_SUBTYPE_PINVOKE);
3649 encode_method_ref (acfg, info->d.managed_to_native.method, p, &p);
3651 break;
3653 case MONO_WRAPPER_SYNCHRONIZED: {
3654 MonoMethod *m;
3656 m = mono_marshal_method_from_wrapper (method);
3657 g_assert (m);
3658 g_assert (m != method);
3659 encode_method_ref (acfg, m, p, &p);
3660 break;
3662 case MONO_WRAPPER_MANAGED_TO_MANAGED: {
3663 g_assert (info);
3664 encode_value (info->subtype, p, &p);
3666 if (info->subtype == WRAPPER_SUBTYPE_ELEMENT_ADDR) {
3667 encode_value (info->d.element_addr.rank, p, &p);
3668 encode_value (info->d.element_addr.elem_size, p, &p);
3669 } else if (info->subtype == WRAPPER_SUBTYPE_STRING_CTOR) {
3670 encode_method_ref (acfg, info->d.string_ctor.method, p, &p);
3671 } else {
3672 g_assert_not_reached ();
3674 break;
3676 case MONO_WRAPPER_CASTCLASS: {
3677 g_assert (info);
3678 encode_value (info->subtype, p, &p);
3679 break;
3681 case MONO_WRAPPER_RUNTIME_INVOKE: {
3682 g_assert (info);
3683 encode_value (info->subtype, p, &p);
3684 if (info->subtype == WRAPPER_SUBTYPE_RUNTIME_INVOKE_DIRECT || info->subtype == WRAPPER_SUBTYPE_RUNTIME_INVOKE_VIRTUAL)
3685 encode_method_ref (acfg, info->d.runtime_invoke.method, p, &p);
3686 else if (info->subtype == WRAPPER_SUBTYPE_RUNTIME_INVOKE_NORMAL)
3687 encode_signature (acfg, info->d.runtime_invoke.sig, p, &p);
3688 break;
3690 case MONO_WRAPPER_DELEGATE_INVOKE:
3691 case MONO_WRAPPER_DELEGATE_BEGIN_INVOKE:
3692 case MONO_WRAPPER_DELEGATE_END_INVOKE: {
3693 if (method->is_inflated) {
3694 /* These wrappers are identified by their class */
3695 encode_value (1, p, &p);
3696 encode_klass_ref (acfg, method->klass, p, &p);
3697 } else {
3698 MonoMethodSignature *sig = mono_method_signature_internal (method);
3699 WrapperInfo *info = mono_marshal_get_wrapper_info (method);
3701 encode_value (0, p, &p);
3702 if (method->wrapper_type == MONO_WRAPPER_DELEGATE_INVOKE)
3703 encode_value (info ? info->subtype : 0, p, &p);
3704 encode_signature (acfg, sig, p, &p);
3706 break;
3708 case MONO_WRAPPER_NATIVE_TO_MANAGED: {
3709 g_assert (info);
3710 encode_method_ref (acfg, info->d.native_to_managed.method, p, &p);
3711 encode_klass_ref (acfg, info->d.native_to_managed.klass, p, &p);
3712 break;
3714 default:
3715 g_assert_not_reached ();
3717 } else if (mono_method_signature_internal (method)->is_inflated) {
3719 * This is a generic method, find the original token which referenced it and
3720 * encode that.
3721 * Obtain the token from information recorded by the JIT.
3723 ji = (MonoJumpInfoToken *)g_hash_table_lookup (acfg->token_info_hash, method);
3724 if (ji) {
3725 image_index = get_image_index (acfg, ji->image);
3726 g_assert (image_index < MAX_IMAGE_INDEX);
3727 token = ji->token;
3729 encode_value ((MONO_AOT_METHODREF_METHODSPEC << 24), p, &p);
3730 encode_value (image_index, p, &p);
3731 encode_value (token, p, &p);
3732 } else if (g_hash_table_lookup (acfg->method_blob_hash, method)) {
3733 /* Already emitted as part of an rgctx fetch */
3734 guint32 offset = GPOINTER_TO_UINT (g_hash_table_lookup (acfg->method_blob_hash, method));
3735 offset --;
3737 encode_value ((MONO_AOT_METHODREF_BLOB_INDEX << 24), p, &p);
3738 encode_value (offset, p, &p);
3739 } else {
3740 MonoMethod *declaring;
3741 MonoGenericContext *context = mono_method_get_context (method);
3743 g_assert (method->is_inflated);
3744 declaring = ((MonoMethodInflated*)method)->declaring;
3747 * This might be a non-generic method of a generic instance, which
3748 * doesn't have a token since the reference is generated by the JIT
3749 * like Nullable:Box/Unbox, or by generic sharing.
3751 encode_value ((MONO_AOT_METHODREF_GINST << 24), p, &p);
3752 /* Encode the klass */
3753 encode_klass_ref (acfg, method->klass, p, &p);
3754 /* Encode the method */
3755 image_index = get_image_index (acfg, m_class_get_image (method->klass));
3756 g_assert (image_index < MAX_IMAGE_INDEX);
3757 g_assert (declaring->token);
3758 token = declaring->token;
3759 g_assert (mono_metadata_token_table (token) == MONO_TABLE_METHOD);
3760 encode_value (image_index, p, &p);
3761 encode_value (mono_metadata_token_index (token), p, &p);
3762 encode_generic_context (acfg, context, p, &p);
3764 } else if (token == 0) {
3765 /* This might be a method of a constructed type like int[,].Set */
3766 /* Obtain the token from information recorded by the JIT */
3767 ji = (MonoJumpInfoToken *)g_hash_table_lookup (acfg->token_info_hash, method);
3768 if (ji) {
3769 image_index = get_image_index (acfg, ji->image);
3770 g_assert (image_index < MAX_IMAGE_INDEX);
3771 token = ji->token;
3773 encode_value ((MONO_AOT_METHODREF_METHODSPEC << 24), p, &p);
3774 encode_value (image_index, p, &p);
3775 encode_value (token, p, &p);
3776 } else {
3777 /* Array methods */
3778 g_assert (m_class_get_rank (method->klass));
3780 /* Encode directly */
3781 encode_value ((MONO_AOT_METHODREF_ARRAY << 24), p, &p);
3782 encode_klass_ref (acfg, method->klass, p, &p);
3783 if (!strcmp (method->name, ".ctor") && mono_method_signature_internal (method)->param_count == m_class_get_rank (method->klass))
3784 encode_value (0, p, &p);
3785 else if (!strcmp (method->name, ".ctor") && mono_method_signature_internal (method)->param_count == m_class_get_rank (method->klass) * 2)
3786 encode_value (1, p, &p);
3787 else if (!strcmp (method->name, "Get"))
3788 encode_value (2, p, &p);
3789 else if (!strcmp (method->name, "Address"))
3790 encode_value (3, p, &p);
3791 else if (!strcmp (method->name, "Set"))
3792 encode_value (4, p, &p);
3793 else
3794 g_assert_not_reached ();
3796 } else {
3797 g_assert (mono_metadata_token_table (token) == MONO_TABLE_METHOD);
3799 if (image_index >= MONO_AOT_METHODREF_MIN) {
3800 encode_value ((MONO_AOT_METHODREF_LARGE_IMAGE_INDEX << 24), p, &p);
3801 encode_value (image_index, p, &p);
3802 encode_value (mono_metadata_token_index (token), p, &p);
3803 } else {
3804 encode_value ((image_index << 24) | mono_metadata_token_index (token), p, &p);
3808 acfg->stats.method_ref_count++;
3809 acfg->stats.method_ref_size += p - buf;
3811 *endbuf = p;
3814 static guint32
3815 get_shared_method_ref (MonoAotCompile *acfg, MonoMethod *method)
3817 guint32 offset = GPOINTER_TO_UINT (g_hash_table_lookup (acfg->method_blob_hash, method));
3818 if (!offset) {
3819 guint8 *buf2, *p2;
3821 buf2 = (guint8 *)g_malloc (1024);
3822 p2 = buf2;
3824 encode_method_ref (acfg, method, p2, &p2);
3825 g_assert (p2 - buf2 < 1024);
3827 offset = add_to_blob (acfg, buf2, p2 - buf2);
3828 g_free (buf2);
3830 g_hash_table_insert (acfg->method_blob_hash, method, GUINT_TO_POINTER (offset + 1));
3831 } else {
3832 offset --;
3834 return offset;
3837 static gint
3838 compare_patches (gconstpointer a, gconstpointer b)
3840 int i, j;
3842 i = (*(MonoJumpInfo**)a)->ip.i;
3843 j = (*(MonoJumpInfo**)b)->ip.i;
3845 if (i < j)
3846 return -1;
3847 else
3848 if (i > j)
3849 return 1;
3850 else
3851 return 0;
3854 static G_GNUC_UNUSED char*
3855 patch_to_string (MonoJumpInfo *patch_info)
3857 GString *str;
3859 str = g_string_new ("");
3861 g_string_append_printf (str, "%s(", get_patch_name (patch_info->type));
3863 switch (patch_info->type) {
3864 case MONO_PATCH_INFO_VTABLE:
3865 mono_type_get_desc (str, m_class_get_byval_arg (patch_info->data.klass), TRUE);
3866 break;
3867 default:
3868 break;
3870 g_string_append_printf (str, ")");
3871 return g_string_free (str, FALSE);
3875 * is_plt_patch:
3877 * Return whenever PATCH_INFO refers to a direct call, and thus requires a
3878 * PLT entry.
3880 static inline gboolean
3881 is_plt_patch (MonoJumpInfo *patch_info)
3883 switch (patch_info->type) {
3884 case MONO_PATCH_INFO_METHOD:
3885 case MONO_PATCH_INFO_JIT_ICALL_ID:
3886 case MONO_PATCH_INFO_JIT_ICALL_ADDR:
3887 case MONO_PATCH_INFO_ICALL_ADDR_CALL:
3888 case MONO_PATCH_INFO_RGCTX_FETCH:
3889 case MONO_PATCH_INFO_TRAMPOLINE_FUNC_ADDR:
3890 case MONO_PATCH_INFO_SPECIFIC_TRAMPOLINE_LAZY_FETCH_ADDR:
3891 return TRUE;
3892 case MONO_PATCH_INFO_JIT_ICALL_ADDR_NOCALL:
3893 default:
3894 return FALSE;
3899 * get_plt_symbol:
3901 * Return the symbol identifying the plt entry PLT_OFFSET.
3903 static char*
3904 get_plt_symbol (MonoAotCompile *acfg, int plt_offset, MonoJumpInfo *patch_info)
3906 #ifdef TARGET_MACH
3908 * The Apple linker reorganizes object files, so it doesn't like branches to local
3909 * labels, since those have no relocations.
3911 return g_strdup_printf ("%sp_%d", acfg->llvm_label_prefix, plt_offset);
3912 #else
3913 return g_strdup_printf ("%sp_%d", acfg->temp_prefix, plt_offset);
3914 #endif
3918 * get_plt_entry:
3920 * Return a PLT entry which belongs to the method identified by PATCH_INFO.
3922 static MonoPltEntry*
3923 get_plt_entry (MonoAotCompile *acfg, MonoJumpInfo *patch_info)
3925 MonoPltEntry *res;
3926 gboolean synchronized = FALSE;
3927 static int synchronized_symbol_idx;
3929 if (!is_plt_patch (patch_info))
3930 return NULL;
3932 if (!acfg->patch_to_plt_entry [patch_info->type])
3933 acfg->patch_to_plt_entry [patch_info->type] = g_hash_table_new (mono_patch_info_hash, mono_patch_info_equal);
3934 res = (MonoPltEntry *)g_hash_table_lookup (acfg->patch_to_plt_entry [patch_info->type], patch_info);
3936 if (!acfg->llvm && patch_info->type == MONO_PATCH_INFO_METHOD && (patch_info->data.method->iflags & METHOD_IMPL_ATTRIBUTE_SYNCHRONIZED)) {
3938 * Allocate a separate PLT slot for each such patch, since some plt
3939 * entries will refer to the method itself, and some will refer to the
3940 * wrapper.
3942 res = NULL;
3943 synchronized = TRUE;
3946 if (!res) {
3947 MonoJumpInfo *new_ji;
3949 new_ji = mono_patch_info_dup_mp (acfg->mempool, patch_info);
3951 res = (MonoPltEntry *)mono_mempool_alloc0 (acfg->mempool, sizeof (MonoPltEntry));
3952 res->plt_offset = acfg->plt_offset;
3953 res->ji = new_ji;
3954 res->symbol = get_plt_symbol (acfg, res->plt_offset, patch_info);
3955 if (acfg->aot_opts.write_symbols)
3956 res->debug_sym = get_plt_entry_debug_sym (acfg, res->ji, acfg->plt_entry_debug_sym_cache);
3957 if (synchronized) {
3958 /* Avoid duplicate symbols because we don't cache */
3959 res->symbol = g_strdup_printf ("%s_%d", res->symbol, synchronized_symbol_idx);
3960 if (res->debug_sym)
3961 res->debug_sym = g_strdup_printf ("%s_%d", res->debug_sym, synchronized_symbol_idx);
3962 synchronized_symbol_idx ++;
3965 if (res->debug_sym)
3966 res->llvm_symbol = g_strdup_printf ("%s_%s_llvm", res->symbol, res->debug_sym);
3967 else
3968 res->llvm_symbol = g_strdup_printf ("%s_llvm", res->symbol);
3969 if (strstr (res->llvm_symbol, acfg->temp_prefix) == res->llvm_symbol) {
3970 /* The llvm symbol shouldn't be temporary, since the llvm generated object file references it */
3971 char *tmp = res->llvm_symbol;
3972 res->llvm_symbol = g_strdup (res->llvm_symbol + strlen (acfg->temp_prefix));
3973 g_free (tmp);
3976 g_hash_table_insert (acfg->patch_to_plt_entry [new_ji->type], new_ji, res);
3978 g_hash_table_insert (acfg->plt_offset_to_entry, GUINT_TO_POINTER (res->plt_offset), res);
3980 //g_assert (mono_patch_info_equal (patch_info, new_ji));
3981 //mono_print_ji (patch_info); printf ("\n");
3982 //g_hash_table_print_stats (acfg->patch_to_plt_entry);
3984 acfg->plt_offset ++;
3987 return res;
3990 static guint32
3991 lookup_got_offset (MonoAotCompile *acfg, gboolean llvm, MonoJumpInfo *ji)
3993 guint32 got_offset;
3994 GotInfo *info = llvm ? &acfg->llvm_got_info : &acfg->got_info;
3996 got_offset = GPOINTER_TO_UINT (g_hash_table_lookup (info->patch_to_got_offset_by_type [ji->type], ji));
3997 if (got_offset)
3998 return got_offset - 1;
3999 g_assert_not_reached ();
4003 * get_got_offset:
4005 * Returns the offset of the GOT slot where the runtime object resulting from resolving
4006 * JI could be found if it exists, otherwise allocates a new one.
4008 static guint32
4009 get_got_offset (MonoAotCompile *acfg, gboolean llvm, MonoJumpInfo *ji)
4011 guint32 got_offset;
4012 GotInfo *info = llvm ? &acfg->llvm_got_info : &acfg->got_info;
4014 got_offset = GPOINTER_TO_UINT (g_hash_table_lookup (info->patch_to_got_offset_by_type [ji->type], ji));
4015 if (got_offset)
4016 return got_offset - 1;
4018 if (llvm) {
4019 got_offset = acfg->llvm_got_offset;
4020 acfg->llvm_got_offset ++;
4021 } else {
4022 got_offset = acfg->got_offset;
4023 acfg->got_offset ++;
4026 acfg->stats.got_slots ++;
4027 acfg->stats.got_slot_types [ji->type] ++;
4029 g_hash_table_insert (info->patch_to_got_offset, ji, GUINT_TO_POINTER (got_offset + 1));
4030 g_hash_table_insert (info->patch_to_got_offset_by_type [ji->type], ji, GUINT_TO_POINTER (got_offset + 1));
4031 g_ptr_array_add (info->got_patches, ji);
4033 return got_offset;
4036 /* Add a method to the list of methods which need to be emitted */
4037 static void
4038 add_method_with_index (MonoAotCompile *acfg, MonoMethod *method, int index, gboolean extra)
4040 g_assert (method);
4041 if (!g_hash_table_lookup (acfg->method_indexes, method)) {
4042 g_ptr_array_add (acfg->methods, method);
4043 g_hash_table_insert (acfg->method_indexes, method, GUINT_TO_POINTER (index + 1));
4044 acfg->nmethods = acfg->methods->len + 1;
4047 if (method->wrapper_type || extra) {
4048 int token = mono_metadata_token_index (method->token) - 1;
4049 if (token < 0)
4050 acfg->nextra_methods++;
4051 g_ptr_array_add (acfg->extra_methods, method);
4055 static gboolean
4056 prefer_gsharedvt_method (MonoAotCompile *acfg, MonoMethod *method)
4058 /* One instantiation with valuetypes is generated for each async method */
4059 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")))
4060 return TRUE;
4061 else
4062 return FALSE;
4065 static guint32
4066 get_method_index (MonoAotCompile *acfg, MonoMethod *method)
4068 int index = GPOINTER_TO_UINT (g_hash_table_lookup (acfg->method_indexes, method));
4070 g_assert (index);
4072 return index - 1;
4075 static int
4076 add_method_full (MonoAotCompile *acfg, MonoMethod *method, gboolean extra, int depth)
4078 int index;
4080 index = GPOINTER_TO_UINT (g_hash_table_lookup (acfg->method_indexes, method));
4081 if (index)
4082 return index - 1;
4084 index = acfg->method_index;
4085 add_method_with_index (acfg, method, index, extra);
4087 g_ptr_array_add (acfg->method_order, GUINT_TO_POINTER (index));
4089 g_hash_table_insert (acfg->method_depth, method, GUINT_TO_POINTER (depth));
4091 acfg->method_index ++;
4093 return index;
4096 static int
4097 add_method (MonoAotCompile *acfg, MonoMethod *method)
4099 return add_method_full (acfg, method, FALSE, 0);
4102 static void
4103 mono_dedup_cache_method (MonoAotCompile *acfg, MonoMethod *method)
4105 g_assert (acfg->dedup_stats);
4107 char *name = mono_aot_get_mangled_method_name (method);
4108 g_assert (name);
4110 // For stats
4111 char *stats_name = g_strdup (name);
4113 g_assert (acfg->dedup_cache);
4115 if (!g_hash_table_lookup (acfg->dedup_cache, name)) {
4116 // This AOTCompile owns this method
4117 // We do this to decide whether to write it to disk
4118 // during a dedup run (first phase, where we skip).
4120 // If never changed, then maybe can avoid a recompile
4121 // of the cache.
4123 // Files not read in during last phase.
4124 acfg->dedup_cache_changed = TRUE;
4126 // owns name
4127 g_hash_table_insert (acfg->dedup_cache, name, method);
4128 } else {
4129 // owns name
4130 g_free (name);
4133 guint count = GPOINTER_TO_UINT (g_hash_table_lookup (acfg->dedup_stats, stats_name));
4134 count++;
4135 g_hash_table_insert (acfg->dedup_stats, stats_name, GUINT_TO_POINTER (count));
4138 static void
4139 add_extra_method_with_depth (MonoAotCompile *acfg, MonoMethod *method, int depth)
4141 ERROR_DECL (error);
4143 if (mono_method_is_generic_sharable_full (method, TRUE, TRUE, FALSE)) {
4144 method = mini_get_shared_method_full (method, SHARE_MODE_NONE, error);
4145 if (!is_ok (error)) {
4146 /* vtype constraint */
4147 mono_error_cleanup (error);
4148 return;
4150 } else if ((acfg->opts & MONO_OPT_GSHAREDVT) && prefer_gsharedvt_method (acfg, method) && mono_method_is_generic_sharable_full (method, FALSE, FALSE, TRUE)) {
4151 /* Use the gsharedvt version */
4152 method = mini_get_shared_method_full (method, SHARE_MODE_GSHAREDVT, error);
4153 mono_error_assert_ok (error);
4156 if ((acfg->aot_opts.dedup || acfg->aot_opts.dedup_include) && mono_aot_can_dedup (method)) {
4157 mono_dedup_cache_method (acfg, method);
4159 if (!acfg->dedup_emit_mode)
4160 return;
4163 if (acfg->aot_opts.log_generics)
4164 aot_printf (acfg, "%*sAdding method %s.\n", depth, "", mono_method_get_full_name (method));
4166 add_method_full (acfg, method, TRUE, depth);
4169 static void
4170 add_extra_method (MonoAotCompile *acfg, MonoMethod *method)
4172 add_extra_method_with_depth (acfg, method, 0);
4175 static void
4176 add_jit_icall_wrapper (MonoAotCompile *acfg, MonoJitICallInfo *callinfo)
4178 if (!callinfo->sig)
4179 return;
4181 g_assert (callinfo->name && callinfo->func);
4183 add_method (acfg, mono_marshal_get_icall_wrapper (callinfo, TRUE));
4186 static void
4187 add_lazy_init_wrappers (MonoAotCompile *acfg)
4189 add_method (acfg, mono_marshal_get_aot_init_wrapper (AOT_INIT_METHOD));
4190 add_method (acfg, mono_marshal_get_aot_init_wrapper (AOT_INIT_METHOD_GSHARED_MRGCTX));
4191 add_method (acfg, mono_marshal_get_aot_init_wrapper (AOT_INIT_METHOD_GSHARED_VTABLE));
4192 add_method (acfg, mono_marshal_get_aot_init_wrapper (AOT_INIT_METHOD_GSHARED_THIS));
4195 static MonoMethod*
4196 get_runtime_invoke_sig (MonoMethodSignature *sig)
4198 MonoMethodBuilder *mb;
4199 MonoMethod *m;
4201 mb = mono_mb_new (mono_defaults.object_class, "FOO", MONO_WRAPPER_NONE);
4202 m = mono_mb_create_method (mb, sig, 16);
4203 MonoMethod *invoke = mono_marshal_get_runtime_invoke (m, FALSE);
4204 mono_mb_free (mb);
4205 return invoke;
4208 static MonoMethod*
4209 get_runtime_invoke (MonoAotCompile *acfg, MonoMethod *method, gboolean virtual_)
4211 return mono_marshal_get_runtime_invoke (method, virtual_);
4214 static gboolean
4215 can_marshal_struct (MonoClass *klass)
4217 MonoClassField *field;
4218 gboolean can_marshal = TRUE;
4219 gpointer iter = NULL;
4220 MonoMarshalType *info;
4221 int i;
4223 if (mono_class_is_auto_layout (klass))
4224 return FALSE;
4226 info = mono_marshal_load_type_info (klass);
4228 /* Only allow a few field types to avoid asserts in the marshalling code */
4229 while ((field = mono_class_get_fields_internal (klass, &iter))) {
4230 if ((field->type->attrs & FIELD_ATTRIBUTE_STATIC))
4231 continue;
4233 switch (field->type->type) {
4234 case MONO_TYPE_I4:
4235 case MONO_TYPE_U4:
4236 case MONO_TYPE_I1:
4237 case MONO_TYPE_U1:
4238 case MONO_TYPE_BOOLEAN:
4239 case MONO_TYPE_I2:
4240 case MONO_TYPE_U2:
4241 case MONO_TYPE_CHAR:
4242 case MONO_TYPE_I8:
4243 case MONO_TYPE_U8:
4244 case MONO_TYPE_I:
4245 case MONO_TYPE_U:
4246 case MONO_TYPE_PTR:
4247 case MONO_TYPE_R4:
4248 case MONO_TYPE_R8:
4249 case MONO_TYPE_STRING:
4250 break;
4251 case MONO_TYPE_VALUETYPE:
4252 if (!m_class_is_enumtype (mono_class_from_mono_type_internal (field->type)) && !can_marshal_struct (mono_class_from_mono_type_internal (field->type)))
4253 can_marshal = FALSE;
4254 break;
4255 case MONO_TYPE_SZARRAY: {
4256 gboolean has_mspec = FALSE;
4258 if (info) {
4259 for (i = 0; i < info->num_fields; ++i) {
4260 if (info->fields [i].field == field && info->fields [i].mspec)
4261 has_mspec = TRUE;
4264 if (!has_mspec)
4265 can_marshal = FALSE;
4266 break;
4268 default:
4269 can_marshal = FALSE;
4270 break;
4274 /* Special cases */
4275 /* Its hard to compute whenever these can be marshalled or not */
4276 if (!strcmp (m_class_get_name_space (klass), "System.Net.NetworkInformation.MacOsStructs") && strcmp (m_class_get_name (klass), "sockaddr_dl"))
4277 return TRUE;
4279 return can_marshal;
4282 static void
4283 create_gsharedvt_inst (MonoAotCompile *acfg, MonoMethod *method, MonoGenericContext *ctx)
4285 /* Create a vtype instantiation */
4286 MonoGenericContext shared_context;
4287 MonoType **args;
4288 MonoGenericInst *inst;
4289 MonoGenericContainer *container;
4290 MonoClass **constraints;
4291 int i;
4293 memset (ctx, 0, sizeof (MonoGenericContext));
4295 if (mono_class_is_gtd (method->klass)) {
4296 shared_context = mono_class_get_generic_container (method->klass)->context;
4297 inst = shared_context.class_inst;
4299 args = g_new0 (MonoType*, inst->type_argc);
4300 for (i = 0; i < inst->type_argc; ++i) {
4301 args [i] = mono_get_int_type ();
4303 ctx->class_inst = mono_metadata_get_generic_inst (inst->type_argc, args);
4305 if (method->is_generic) {
4306 container = mono_method_get_generic_container (method);
4307 g_assert (!container->is_anonymous && container->is_method);
4308 shared_context = container->context;
4309 inst = shared_context.method_inst;
4311 args = g_new0 (MonoType*, inst->type_argc);
4312 for (i = 0; i < container->type_argc; ++i) {
4313 MonoGenericParamInfo *info = mono_generic_param_info (&container->type_params [i]);
4314 gboolean ref_only = FALSE;
4316 if (info && info->constraints) {
4317 constraints = info->constraints;
4319 while (*constraints) {
4320 MonoClass *cklass = *constraints;
4321 if (!(cklass == mono_defaults.object_class || (m_class_get_image (cklass) == mono_defaults.corlib && !strcmp (m_class_get_name (cklass), "ValueType"))))
4322 /* Inflaring the method with our vtype would not be valid */
4323 ref_only = TRUE;
4324 constraints ++;
4328 if (ref_only)
4329 args [i] = mono_get_object_type ();
4330 else
4331 args [i] = mono_get_int_type ();
4333 ctx->method_inst = mono_metadata_get_generic_inst (inst->type_argc, args);
4337 static void
4338 add_gc_wrappers (MonoAotCompile *acfg)
4340 MonoMethod *m;
4341 /* Managed Allocators */
4342 int nallocators = mono_gc_get_managed_allocator_types ();
4343 for (int i = 0; i < nallocators; ++i) {
4344 if ((m = mono_gc_get_managed_allocator_by_type (i, MANAGED_ALLOCATOR_REGULAR)))
4345 add_method (acfg, m);
4346 if ((m = mono_gc_get_managed_allocator_by_type (i, MANAGED_ALLOCATOR_SLOW_PATH)))
4347 add_method (acfg, m);
4348 if ((m = mono_gc_get_managed_allocator_by_type (i, MANAGED_ALLOCATOR_PROFILER)))
4349 add_method (acfg, m);
4352 /* write barriers */
4353 if (mono_gc_is_moving ()) {
4354 add_method (acfg, mono_gc_get_specific_write_barrier (FALSE));
4355 add_method (acfg, mono_gc_get_specific_write_barrier (TRUE));
4359 static gboolean
4360 contains_disable_reflection_attribute (MonoCustomAttrInfo *cattr)
4362 for (int i = 0; i < cattr->num_attrs; ++i) {
4363 MonoCustomAttrEntry *attr = &cattr->attrs [i];
4365 if (!attr->ctor)
4366 return FALSE;
4368 if (strcmp (m_class_get_name_space (attr->ctor->klass), "System.Runtime.CompilerServices"))
4369 return FALSE;
4371 if (strcmp (m_class_get_name (attr->ctor->klass), "DisablePrivateReflectionAttribute"))
4372 return FALSE;
4375 return TRUE;
4378 gboolean
4379 mono_aot_can_specialize (MonoMethod *method)
4381 if (!method)
4382 return FALSE;
4384 if (method->wrapper_type != MONO_WRAPPER_NONE)
4385 return FALSE;
4387 // If it's not private, we can't specialize
4388 if ((method->flags & METHOD_ATTRIBUTE_MEMBER_ACCESS_MASK) != METHOD_ATTRIBUTE_PRIVATE)
4389 return FALSE;
4391 // If it has the attribute disabling the specialization, we can't specialize
4393 // Set by linker, indicates that the method can be found through reflection
4394 // and that call-site specialization shouldn't be done.
4396 // Important that this attribute is used for *nothing else*
4398 // If future authors make use of it (to disable more optimizations),
4399 // change this place to use a new attribute.
4400 ERROR_DECL (cattr_error);
4401 MonoCustomAttrInfo *cattr = mono_custom_attrs_from_class_checked (method->klass, cattr_error);
4403 if (!is_ok (cattr_error)) {
4404 mono_error_cleanup (cattr_error);
4405 goto cleanup_false;
4406 } else if (cattr && contains_disable_reflection_attribute (cattr)) {
4407 goto cleanup_true;
4410 cattr = mono_custom_attrs_from_method_checked (method, cattr_error);
4412 if (!is_ok (cattr_error)) {
4413 mono_error_cleanup (cattr_error);
4414 goto cleanup_false;
4415 } else if (cattr && contains_disable_reflection_attribute (cattr)) {
4416 goto cleanup_true;
4417 } else {
4418 goto cleanup_false;
4421 cleanup_false:
4422 if (cattr)
4423 mono_custom_attrs_free (cattr);
4424 return FALSE;
4426 cleanup_true:
4427 if (cattr)
4428 mono_custom_attrs_free (cattr);
4429 return TRUE;
4432 static void
4433 add_wrappers (MonoAotCompile *acfg)
4435 MonoMethod *method, *m;
4436 int i, j;
4437 MonoMethodSignature *sig, *csig;
4438 guint32 token;
4441 * FIXME: Instead of AOTing all the wrappers, it might be better to redesign them
4442 * so there is only one wrapper of a given type, or inlining their contents into their
4443 * callers.
4445 for (i = 0; i < acfg->image->tables [MONO_TABLE_METHOD].rows; ++i) {
4446 ERROR_DECL (error);
4447 MonoMethod *method;
4448 guint32 token = MONO_TOKEN_METHOD_DEF | (i + 1);
4449 gboolean skip = FALSE;
4451 method = mono_get_method_checked (acfg->image, token, NULL, NULL, error);
4452 report_loader_error (acfg, error, TRUE, "Failed to load method token 0x%x due to %s\n", i, mono_error_get_message (error));
4454 if ((method->flags & METHOD_ATTRIBUTE_PINVOKE_IMPL) ||
4455 (method->iflags & METHOD_IMPL_ATTRIBUTE_RUNTIME) ||
4456 (method->flags & METHOD_ATTRIBUTE_ABSTRACT))
4457 skip = TRUE;
4459 /* Skip methods which can not be handled by get_runtime_invoke () */
4460 sig = mono_method_signature_internal (method);
4461 if (!sig)
4462 continue;
4463 if ((sig->ret->type == MONO_TYPE_PTR) ||
4464 (sig->ret->type == MONO_TYPE_TYPEDBYREF))
4465 skip = TRUE;
4466 if (mono_class_is_open_constructed_type (sig->ret))
4467 skip = TRUE;
4469 for (j = 0; j < sig->param_count; j++) {
4470 if (sig->params [j]->type == MONO_TYPE_TYPEDBYREF)
4471 skip = TRUE;
4472 if (mono_class_is_open_constructed_type (sig->params [j]))
4473 skip = TRUE;
4476 #ifdef MONO_ARCH_DYN_CALL_SUPPORTED
4477 if (!mono_class_is_contextbound (method->klass)) {
4478 MonoDynCallInfo *info = mono_arch_dyn_call_prepare (sig);
4479 gboolean has_nullable = FALSE;
4481 for (j = 0; j < sig->param_count; j++) {
4482 if (sig->params [j]->type == MONO_TYPE_GENERICINST && mono_class_is_nullable (mono_class_from_mono_type_internal (sig->params [j])))
4483 has_nullable = TRUE;
4486 if (info && !has_nullable && !acfg->aot_opts.llvm_only) {
4487 /* Supported by the dynamic runtime-invoke wrapper */
4488 skip = TRUE;
4490 if (info)
4491 mono_arch_dyn_call_free (info);
4493 #endif
4495 if (acfg->aot_opts.llvm_only)
4496 /* Supported by the gsharedvt based runtime-invoke wrapper */
4497 skip = TRUE;
4499 if (!skip) {
4500 //printf ("%s\n", mono_method_full_name (method, TRUE));
4501 add_method (acfg, get_runtime_invoke (acfg, method, FALSE));
4505 if (mono_is_corlib_image (acfg->image->assembly->image)) {
4506 /* Runtime invoke wrappers */
4508 MonoType *void_type = mono_get_void_type ();
4509 MonoType *string_type = m_class_get_byval_arg (mono_defaults.string_class);
4511 /* void runtime-invoke () [.cctor] */
4512 csig = mono_metadata_signature_alloc (mono_defaults.corlib, 0);
4513 csig->ret = void_type;
4514 add_method (acfg, get_runtime_invoke_sig (csig));
4516 /* void runtime-invoke () [Finalize] */
4517 csig = mono_metadata_signature_alloc (mono_defaults.corlib, 0);
4518 csig->hasthis = 1;
4519 csig->ret = void_type;
4520 add_method (acfg, get_runtime_invoke_sig (csig));
4522 /* void runtime-invoke (string) [exception ctor] */
4523 csig = mono_metadata_signature_alloc (mono_defaults.corlib, 1);
4524 csig->hasthis = 1;
4525 csig->ret = void_type;
4526 csig->params [0] = string_type;
4527 add_method (acfg, get_runtime_invoke_sig (csig));
4529 /* void runtime-invoke (string, string) [exception ctor] */
4530 csig = mono_metadata_signature_alloc (mono_defaults.corlib, 2);
4531 csig->hasthis = 1;
4532 csig->ret = void_type;
4533 csig->params [0] = string_type;
4534 csig->params [1] = string_type;
4535 add_method (acfg, get_runtime_invoke_sig (csig));
4537 /* string runtime-invoke () [Exception.ToString ()] */
4538 csig = mono_metadata_signature_alloc (mono_defaults.corlib, 0);
4539 csig->hasthis = 1;
4540 csig->ret = string_type;
4541 add_method (acfg, get_runtime_invoke_sig (csig));
4543 /* void runtime-invoke (string, Exception) [exception ctor] */
4544 csig = mono_metadata_signature_alloc (mono_defaults.corlib, 2);
4545 csig->hasthis = 1;
4546 csig->ret = void_type;
4547 csig->params [0] = string_type;
4548 csig->params [1] = m_class_get_byval_arg (mono_defaults.exception_class);
4549 add_method (acfg, get_runtime_invoke_sig (csig));
4551 /* Assembly runtime-invoke (string, Assembly, bool) [DoAssemblyResolve] */
4552 csig = mono_metadata_signature_alloc (mono_defaults.corlib, 3);
4553 csig->hasthis = 1;
4554 csig->ret = m_class_get_byval_arg (mono_class_load_from_name (mono_defaults.corlib, "System.Reflection", "Assembly"));
4555 csig->params [0] = string_type;
4556 csig->params [1] = m_class_get_byval_arg (mono_class_load_from_name (mono_defaults.corlib, "System.Reflection", "Assembly"));
4557 csig->params [2] = m_class_get_byval_arg (mono_defaults.boolean_class);
4558 add_method (acfg, get_runtime_invoke_sig (csig));
4560 /* runtime-invoke used by finalizers */
4561 add_method (acfg, get_runtime_invoke (acfg, get_method_nofail (mono_defaults.object_class, "Finalize", 0, 0), TRUE));
4563 /* This is used by mono_runtime_capture_context () */
4564 method = mono_get_context_capture_method ();
4565 if (method)
4566 add_method (acfg, get_runtime_invoke (acfg, method, FALSE));
4568 #ifdef MONO_ARCH_DYN_CALL_SUPPORTED
4569 if (!acfg->aot_opts.llvm_only)
4570 add_method (acfg, mono_marshal_get_runtime_invoke_dynamic ());
4571 #endif
4573 /* These are used by mono_jit_runtime_invoke () to calls gsharedvt out wrappers */
4574 if (acfg->aot_opts.llvm_only) {
4575 int variants;
4577 /* Create simplified signatures which match the signature used by the gsharedvt out wrappers */
4578 for (variants = 0; variants < 4; ++variants) {
4579 for (i = 0; i < 40; ++i) {
4580 sig = mini_get_gsharedvt_out_sig_wrapper_signature ((variants & 1) > 0, (variants & 2) > 0, i);
4581 add_extra_method (acfg, mono_marshal_get_runtime_invoke_for_sig (sig));
4583 g_free (sig);
4588 /* stelemref */
4589 add_method (acfg, mono_marshal_get_stelemref ());
4591 add_gc_wrappers (acfg);
4593 /* Stelemref wrappers */
4595 MonoMethod **wrappers;
4596 int nwrappers;
4598 wrappers = mono_marshal_get_virtual_stelemref_wrappers (&nwrappers);
4599 for (i = 0; i < nwrappers; ++i)
4600 add_method (acfg, wrappers [i]);
4601 g_free (wrappers);
4604 /* castclass_with_check wrapper */
4605 add_method (acfg, mono_marshal_get_castclass_with_cache ());
4606 /* isinst_with_check wrapper */
4607 add_method (acfg, mono_marshal_get_isinst_with_cache ());
4609 /* JIT icall wrappers */
4610 /* FIXME: locking - this is "safe" as full-AOT threads don't mutate the icall data */
4611 for (int i = 0; i < MONO_JIT_ICALL_count; ++i)
4612 add_jit_icall_wrapper (acfg, mono_find_jit_icall_info ((MonoJitICallId)i));
4616 * remoting-invoke-with-check wrappers are very frequent, so avoid emitting them,
4617 * we use the original method instead at runtime.
4618 * Since full-aot doesn't support remoting, this is not a problem.
4620 #if 0
4621 /* remoting-invoke wrappers */
4622 for (i = 0; i < acfg->image->tables [MONO_TABLE_METHOD].rows; ++i) {
4623 ERROR_DECL (error);
4624 MonoMethodSignature *sig;
4626 token = MONO_TOKEN_METHOD_DEF | (i + 1);
4627 method = mono_get_method_checked (acfg->image, token, NULL, NULL, error);
4628 g_assert (mono_error_ok (error)); /* FIXME don't swallow the error */
4630 sig = mono_method_signature_internal (method);
4632 if (sig->hasthis && (method->klass->marshalbyref || method->klass == mono_defaults.object_class)) {
4633 m = mono_marshal_get_remoting_invoke_with_check (method);
4635 add_method (acfg, m);
4638 #endif
4640 /* delegate-invoke wrappers */
4641 for (i = 0; i < acfg->image->tables [MONO_TABLE_TYPEDEF].rows; ++i) {
4642 ERROR_DECL (error);
4643 MonoClass *klass;
4645 token = MONO_TOKEN_TYPE_DEF | (i + 1);
4646 klass = mono_class_get_checked (acfg->image, token, error);
4648 if (!klass) {
4649 mono_error_cleanup (error);
4650 continue;
4653 if (!m_class_is_delegate (klass) || klass == mono_defaults.delegate_class || klass == mono_defaults.multicastdelegate_class)
4654 continue;
4656 if (!mono_class_is_gtd (klass)) {
4657 method = mono_get_delegate_invoke_internal (klass);
4659 m = mono_marshal_get_delegate_invoke (method, NULL);
4661 add_method (acfg, m);
4663 method = try_get_method_nofail (klass, "BeginInvoke", -1, 0);
4664 if (method)
4665 add_method (acfg, mono_marshal_get_delegate_begin_invoke (method));
4667 method = try_get_method_nofail (klass, "EndInvoke", -1, 0);
4668 if (method)
4669 add_method (acfg, mono_marshal_get_delegate_end_invoke (method));
4671 MonoCustomAttrInfo *cattr;
4672 cattr = mono_custom_attrs_from_class_checked (klass, error);
4673 if (!is_ok (error)) {
4674 mono_error_cleanup (error);
4675 g_assert (!cattr);
4676 continue;
4679 if (cattr) {
4680 int j;
4682 for (j = 0; j < cattr->num_attrs; ++j)
4683 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")))
4684 break;
4685 if (j < cattr->num_attrs) {
4686 MonoMethod *invoke;
4687 MonoMethod *wrapper;
4688 MonoMethod *del_invoke;
4690 /* Add wrappers needed by mono_ftnptr_to_delegate () */
4691 invoke = mono_get_delegate_invoke_internal (klass);
4692 wrapper = mono_marshal_get_native_func_wrapper_aot (klass);
4693 del_invoke = mono_marshal_get_delegate_invoke_internal (invoke, FALSE, TRUE, wrapper);
4694 add_method (acfg, wrapper);
4695 add_method (acfg, del_invoke);
4697 mono_custom_attrs_free (cattr);
4699 } else if ((acfg->opts & MONO_OPT_GSHAREDVT) && mono_class_is_gtd (klass)) {
4700 ERROR_DECL (error);
4701 MonoGenericContext ctx;
4702 MonoMethod *inst, *gshared;
4705 * Emit gsharedvt versions of the generic delegate-invoke wrappers
4707 /* Invoke */
4708 method = mono_get_delegate_invoke_internal (klass);
4709 create_gsharedvt_inst (acfg, method, &ctx);
4711 inst = mono_class_inflate_generic_method_checked (method, &ctx, error);
4712 g_assert (mono_error_ok (error)); /* FIXME don't swallow the error */
4714 m = mono_marshal_get_delegate_invoke (inst, NULL);
4715 g_assert (m->is_inflated);
4717 gshared = mini_get_shared_method_full (m, SHARE_MODE_GSHAREDVT, error);
4718 mono_error_assert_ok (error);
4720 add_extra_method (acfg, gshared);
4722 /* begin-invoke */
4723 method = mono_get_delegate_begin_invoke_internal (klass);
4724 if (method) {
4725 create_gsharedvt_inst (acfg, method, &ctx);
4727 inst = mono_class_inflate_generic_method_checked (method, &ctx, error);
4728 g_assert (mono_error_ok (error)); /* FIXME don't swallow the error */
4730 m = mono_marshal_get_delegate_begin_invoke (inst);
4731 g_assert (m->is_inflated);
4733 gshared = mini_get_shared_method_full (m, SHARE_MODE_GSHAREDVT, error);
4734 mono_error_assert_ok (error);
4736 add_extra_method (acfg, gshared);
4739 /* end-invoke */
4740 method = mono_get_delegate_end_invoke_internal (klass);
4741 if (method) {
4742 create_gsharedvt_inst (acfg, method, &ctx);
4744 inst = mono_class_inflate_generic_method_checked (method, &ctx, error);
4745 g_assert (mono_error_ok (error)); /* FIXME don't swallow the error */
4747 m = mono_marshal_get_delegate_end_invoke (inst);
4748 g_assert (m->is_inflated);
4750 gshared = mini_get_shared_method_full (m, SHARE_MODE_GSHAREDVT, error);
4751 mono_error_assert_ok (error);
4753 add_extra_method (acfg, gshared);
4758 /* array access wrappers */
4759 for (i = 0; i < acfg->image->tables [MONO_TABLE_TYPESPEC].rows; ++i) {
4760 ERROR_DECL (error);
4761 MonoClass *klass;
4763 token = MONO_TOKEN_TYPE_SPEC | (i + 1);
4764 klass = mono_class_get_checked (acfg->image, token, error);
4766 if (!klass) {
4767 mono_error_cleanup (error);
4768 continue;
4771 if (m_class_get_rank (klass) && MONO_TYPE_IS_PRIMITIVE (m_class_get_byval_arg (m_class_get_element_class (klass)))) {
4772 MonoMethod *m, *wrapper;
4774 /* Add runtime-invoke wrappers too */
4776 m = get_method_nofail (klass, "Get", -1, 0);
4777 g_assert (m);
4778 wrapper = mono_marshal_get_array_accessor_wrapper (m);
4779 add_extra_method (acfg, wrapper);
4780 if (!acfg->aot_opts.llvm_only)
4781 add_extra_method (acfg, get_runtime_invoke (acfg, wrapper, FALSE));
4783 m = get_method_nofail (klass, "Set", -1, 0);
4784 g_assert (m);
4785 wrapper = mono_marshal_get_array_accessor_wrapper (m);
4786 add_extra_method (acfg, wrapper);
4787 if (!acfg->aot_opts.llvm_only)
4788 add_extra_method (acfg, get_runtime_invoke (acfg, wrapper, FALSE));
4792 /* Synchronized wrappers */
4793 for (i = 0; i < acfg->image->tables [MONO_TABLE_METHOD].rows; ++i) {
4794 ERROR_DECL (error);
4795 token = MONO_TOKEN_METHOD_DEF | (i + 1);
4796 method = mono_get_method_checked (acfg->image, token, NULL, NULL, error);
4797 report_loader_error (acfg, error, TRUE, "Failed to load method token 0x%x due to %s\n", i, mono_error_get_message (error));
4799 if (method->iflags & METHOD_IMPL_ATTRIBUTE_SYNCHRONIZED) {
4800 if (method->is_generic) {
4801 // FIXME:
4802 } else if ((acfg->opts & MONO_OPT_GSHAREDVT) && mono_class_is_gtd (method->klass)) {
4803 ERROR_DECL (error);
4804 MonoGenericContext ctx;
4805 MonoMethod *inst, *gshared, *m;
4808 * Create a generic wrapper for a generic instance, and AOT that.
4810 create_gsharedvt_inst (acfg, method, &ctx);
4811 inst = mono_class_inflate_generic_method_checked (method, &ctx, error);
4812 g_assert (mono_error_ok (error)); /* FIXME don't swallow the error */
4813 m = mono_marshal_get_synchronized_wrapper (inst);
4814 g_assert (m->is_inflated);
4815 gshared = mini_get_shared_method_full (m, SHARE_MODE_GSHAREDVT, error);
4816 mono_error_assert_ok (error);
4818 add_method (acfg, gshared);
4819 } else {
4820 add_method (acfg, mono_marshal_get_synchronized_wrapper (method));
4825 /* pinvoke wrappers */
4826 for (i = 0; i < acfg->image->tables [MONO_TABLE_METHOD].rows; ++i) {
4827 ERROR_DECL (error);
4828 MonoMethod *method;
4829 guint32 token = MONO_TOKEN_METHOD_DEF | (i + 1);
4831 method = mono_get_method_checked (acfg->image, token, NULL, NULL, error);
4832 report_loader_error (acfg, error, TRUE, "Failed to load method token 0x%x due to %s\n", i, mono_error_get_message (error));
4834 if ((method->flags & METHOD_ATTRIBUTE_PINVOKE_IMPL) ||
4835 (method->iflags & METHOD_IMPL_ATTRIBUTE_INTERNAL_CALL)) {
4836 add_method (acfg, mono_marshal_get_native_wrapper (method, TRUE, TRUE));
4839 if (method->iflags & METHOD_IMPL_ATTRIBUTE_INTERNAL_CALL) {
4840 if (acfg->aot_opts.llvm_only) {
4841 /* The wrappers have a different signature (hasthis is not set) so need to add this too */
4842 add_gsharedvt_wrappers (acfg, mono_method_signature_internal (method), FALSE, TRUE, FALSE);
4847 /* native-to-managed wrappers */
4848 for (i = 0; i < acfg->image->tables [MONO_TABLE_METHOD].rows; ++i) {
4849 ERROR_DECL (error);
4850 MonoMethod *method;
4851 guint32 token = MONO_TOKEN_METHOD_DEF | (i + 1);
4852 MonoCustomAttrInfo *cattr;
4853 int j;
4855 method = mono_get_method_checked (acfg->image, token, NULL, NULL, error);
4856 report_loader_error (acfg, error, TRUE, "Failed to load method token 0x%x due to %s\n", i, mono_error_get_message (error));
4859 * Only generate native-to-managed wrappers for methods which have an
4860 * attribute named MonoPInvokeCallbackAttribute. We search for the attribute by
4861 * name to avoid defining a new assembly to contain it.
4863 cattr = mono_custom_attrs_from_method_checked (method, error);
4864 if (!is_ok (error)) {
4865 char *name = mono_method_get_full_name (method);
4866 report_loader_error (acfg, error, TRUE, "Failed to load custom attributes from method %s due to %s\n", name, mono_error_get_message (error));
4867 g_free (name);
4870 if (cattr) {
4871 for (j = 0; j < cattr->num_attrs; ++j)
4872 if (cattr->attrs [j].ctor && !strcmp (m_class_get_name (cattr->attrs [j].ctor->klass), "MonoPInvokeCallbackAttribute"))
4873 break;
4874 if (j < cattr->num_attrs) {
4875 MonoCustomAttrEntry *e = &cattr->attrs [j];
4876 MonoMethodSignature *sig = mono_method_signature_internal (e->ctor);
4877 const char *p = (const char*)e->data;
4878 const char *named;
4879 int slen, num_named, named_type;
4880 char *n;
4881 MonoType *t;
4882 MonoClass *klass;
4883 char *export_name = NULL;
4884 MonoMethod *wrapper;
4886 /* this cannot be enforced by the C# compiler so we must give the user some warning before aborting */
4887 if (!(method->flags & METHOD_ATTRIBUTE_STATIC)) {
4888 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",
4889 mono_method_full_name (method, TRUE));
4890 exit (1);
4893 g_assert (sig->param_count == 1);
4894 g_assert (sig->params [0]->type == MONO_TYPE_CLASS && !strcmp (m_class_get_name (mono_class_from_mono_type_internal (sig->params [0])), "Type"));
4897 * Decode the cattr manually since we can't create objects
4898 * during aot compilation.
4901 /* Skip prolog */
4902 p += 2;
4904 /* From load_cattr_value () in reflection.c */
4905 slen = mono_metadata_decode_value (p, &p);
4906 n = (char *)g_memdup (p, slen + 1);
4907 n [slen] = 0;
4908 t = mono_reflection_type_from_name_checked (n, acfg->image, error);
4909 g_assert (t);
4910 mono_error_assert_ok (error);
4911 g_free (n);
4913 klass = mono_class_from_mono_type_internal (t);
4914 g_assert (m_class_get_parent (klass) == mono_defaults.multicastdelegate_class);
4916 p += slen;
4918 num_named = read16 (p);
4919 p += 2;
4921 g_assert (num_named < 2);
4922 if (num_named == 1) {
4923 int name_len;
4924 char *name;
4926 /* parse ExportSymbol attribute */
4927 named = p;
4928 named_type = *named;
4929 named += 1;
4930 /* data_type = *named; */
4931 named += 1;
4933 name_len = mono_metadata_decode_blob_size (named, &named);
4934 name = (char *)g_malloc (name_len + 1);
4935 memcpy (name, named, name_len);
4936 name [name_len] = 0;
4937 named += name_len;
4939 g_assert (named_type == 0x54);
4940 g_assert (!strcmp (name, "ExportSymbol"));
4942 /* load_cattr_value (), string case */
4943 MONO_DISABLE_WARNING (4310) // cast truncates constant value
4944 g_assert (*named != (char)0xFF);
4945 MONO_RESTORE_WARNING
4946 slen = mono_metadata_decode_value (named, &named);
4947 export_name = (char *)g_malloc (slen + 1);
4948 memcpy (export_name, named, slen);
4949 export_name [slen] = 0;
4950 named += slen;
4953 wrapper = mono_marshal_get_managed_wrapper (method, klass, 0, error);
4954 mono_error_assert_ok (error);
4956 add_method (acfg, wrapper);
4957 if (export_name)
4958 g_hash_table_insert (acfg->export_names, wrapper, export_name);
4960 g_free (cattr);
4963 if ((method->flags & METHOD_ATTRIBUTE_PINVOKE_IMPL) ||
4964 (method->iflags & METHOD_IMPL_ATTRIBUTE_INTERNAL_CALL)) {
4965 add_method (acfg, mono_marshal_get_native_wrapper (method, TRUE, TRUE));
4969 /* StructureToPtr/PtrToStructure wrappers */
4970 for (i = 0; i < acfg->image->tables [MONO_TABLE_TYPEDEF].rows; ++i) {
4971 ERROR_DECL (error);
4972 MonoClass *klass;
4974 token = MONO_TOKEN_TYPE_DEF | (i + 1);
4975 klass = mono_class_get_checked (acfg->image, token, error);
4977 if (!klass) {
4978 mono_error_cleanup (error);
4979 continue;
4982 if (m_class_is_valuetype (klass) && !mono_class_is_gtd (klass) && can_marshal_struct (klass) &&
4983 !(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)))) {
4984 add_method (acfg, mono_marshal_get_struct_to_ptr (klass));
4985 add_method (acfg, mono_marshal_get_ptr_to_struct (klass));
4990 static gboolean
4991 has_type_vars (MonoClass *klass)
4993 if ((m_class_get_byval_arg (klass)->type == MONO_TYPE_VAR) || (m_class_get_byval_arg (klass)->type == MONO_TYPE_MVAR))
4994 return TRUE;
4995 if (m_class_get_rank (klass))
4996 return has_type_vars (m_class_get_element_class (klass));
4997 if (mono_class_is_ginst (klass)) {
4998 MonoGenericContext *context = &mono_class_get_generic_class (klass)->context;
4999 if (context->class_inst) {
5000 int i;
5002 for (i = 0; i < context->class_inst->type_argc; ++i)
5003 if (has_type_vars (mono_class_from_mono_type_internal (context->class_inst->type_argv [i])))
5004 return TRUE;
5007 if (mono_class_is_gtd (klass))
5008 return TRUE;
5009 return FALSE;
5012 static gboolean
5013 is_vt_inst (MonoGenericInst *inst)
5015 int i;
5017 for (i = 0; i < inst->type_argc; ++i) {
5018 MonoType *t = inst->type_argv [i];
5019 if (MONO_TYPE_ISSTRUCT (t) || t->type == MONO_TYPE_VALUETYPE)
5020 return TRUE;
5022 return FALSE;
5025 static gboolean
5026 method_has_type_vars (MonoMethod *method)
5028 if (has_type_vars (method->klass))
5029 return TRUE;
5031 if (method->is_inflated) {
5032 MonoGenericContext *context = mono_method_get_context (method);
5033 if (context->method_inst) {
5034 int i;
5036 for (i = 0; i < context->method_inst->type_argc; ++i)
5037 if (has_type_vars (mono_class_from_mono_type_internal (context->method_inst->type_argv [i])))
5038 return TRUE;
5041 return FALSE;
5044 static
5045 gboolean mono_aot_mode_is_full (MonoAotOptions *opts)
5047 return opts->mode == MONO_AOT_MODE_FULL;
5050 static
5051 gboolean mono_aot_mode_is_interp (MonoAotOptions *opts)
5053 return opts->interp;
5056 static
5057 gboolean mono_aot_mode_is_hybrid (MonoAotOptions *opts)
5059 return opts->mode == MONO_AOT_MODE_HYBRID;
5062 static void add_generic_class_with_depth (MonoAotCompile *acfg, MonoClass *klass, int depth, const char *ref);
5064 static void
5065 add_generic_class (MonoAotCompile *acfg, MonoClass *klass, gboolean force, const char *ref)
5067 /* This might lead to a huge code blowup so only do it if neccesary */
5068 if (!mono_aot_mode_is_full (&acfg->aot_opts) && !mono_aot_mode_is_hybrid (&acfg->aot_opts) && !force)
5069 return;
5071 add_generic_class_with_depth (acfg, klass, 0, ref);
5074 static gboolean
5075 check_type_depth (MonoType *t, int depth)
5077 int i;
5079 if (depth > 8)
5080 return TRUE;
5082 switch (t->type) {
5083 case MONO_TYPE_GENERICINST: {
5084 MonoGenericClass *gklass = t->data.generic_class;
5085 MonoGenericInst *ginst = gklass->context.class_inst;
5087 if (ginst) {
5088 for (i = 0; i < ginst->type_argc; ++i) {
5089 if (check_type_depth (ginst->type_argv [i], depth + 1))
5090 return TRUE;
5093 break;
5095 default:
5096 break;
5099 return FALSE;
5102 static void
5103 add_types_from_method_header (MonoAotCompile *acfg, MonoMethod *method);
5106 * add_generic_class:
5108 * Add all methods of a generic class.
5110 static void
5111 add_generic_class_with_depth (MonoAotCompile *acfg, MonoClass *klass, int depth, const char *ref)
5113 MonoMethod *method;
5114 MonoClassField *field;
5115 gpointer iter;
5116 gboolean use_gsharedvt = FALSE;
5118 if (!acfg->ginst_hash)
5119 acfg->ginst_hash = g_hash_table_new (NULL, NULL);
5121 mono_class_init_internal (klass);
5123 if (mono_class_is_ginst (klass) && mono_class_get_generic_class (klass)->context.class_inst->is_open)
5124 return;
5126 if (has_type_vars (klass))
5127 return;
5129 if (!mono_class_is_ginst (klass) && !m_class_get_rank (klass))
5130 return;
5132 if (mono_class_has_failure (klass))
5133 return;
5135 if (!acfg->ginst_hash)
5136 acfg->ginst_hash = g_hash_table_new (NULL, NULL);
5138 if (g_hash_table_lookup (acfg->ginst_hash, klass))
5139 return;
5141 if (check_type_depth (m_class_get_byval_arg (klass), 0))
5142 return;
5144 if (acfg->aot_opts.log_generics) {
5145 char *s = mono_type_full_name (m_class_get_byval_arg (klass));
5146 aot_printf (acfg, "%*sAdding generic instance %s [%s].\n", depth, "", s, ref);
5147 g_free (s);
5150 g_hash_table_insert (acfg->ginst_hash, klass, klass);
5153 * Use gsharedvt for generic collections with vtype arguments to avoid code blowup.
5154 * Enable this only for some classes since gsharedvt might not support all methods.
5156 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) &&
5157 (!strcmp (m_class_get_name (klass), "Dictionary`2") || !strcmp (m_class_get_name (klass), "List`1") || !strcmp (m_class_get_name (klass), "ReadOnlyCollection`1")))
5158 use_gsharedvt = TRUE;
5160 iter = NULL;
5161 while ((method = mono_class_get_methods (klass, &iter))) {
5162 if ((acfg->opts & MONO_OPT_GSHAREDVT) && method->is_inflated && mono_method_get_context (method)->method_inst) {
5164 * This is partial sharing, and we can't handle it yet
5166 continue;
5169 if (mono_method_is_generic_sharable_full (method, FALSE, FALSE, use_gsharedvt)) {
5170 /* Already added */
5171 add_types_from_method_header (acfg, method);
5172 continue;
5175 if (method->is_generic)
5176 /* FIXME: */
5177 continue;
5180 * FIXME: Instances which are referenced by these methods are not added,
5181 * for example Array.Resize<int> for List<int>.Add ().
5183 add_extra_method_with_depth (acfg, method, depth + 1);
5186 iter = NULL;
5187 while ((field = mono_class_get_fields_internal (klass, &iter))) {
5188 if (field->type->type == MONO_TYPE_GENERICINST)
5189 add_generic_class_with_depth (acfg, mono_class_from_mono_type_internal (field->type), depth + 1, "field");
5192 if (m_class_is_delegate (klass)) {
5193 method = mono_get_delegate_invoke_internal (klass);
5195 method = mono_marshal_get_delegate_invoke (method, NULL);
5197 if (acfg->aot_opts.log_generics)
5198 aot_printf (acfg, "%*sAdding method %s.\n", depth, "", mono_method_get_full_name (method));
5200 add_method (acfg, method);
5203 /* Add superclasses */
5204 if (m_class_get_parent (klass))
5205 add_generic_class_with_depth (acfg, m_class_get_parent (klass), depth, "parent");
5207 const char *klass_name = m_class_get_name (klass);
5208 const char *klass_name_space = m_class_get_name_space (klass);
5209 const gboolean in_corlib = m_class_get_image (klass) == mono_defaults.corlib;
5211 * For ICollection<T>, add instances of the helper methods
5212 * in Array, since a T[] could be cast to ICollection<T>.
5214 if (in_corlib && !strcmp (klass_name_space, "System.Collections.Generic") &&
5215 (!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"))) {
5216 MonoClass *tclass = mono_class_from_mono_type_internal (mono_class_get_generic_class (klass)->context.class_inst->type_argv [0]);
5217 MonoClass *array_class = mono_class_create_bounded_array (tclass, 1, FALSE);
5218 gpointer iter;
5219 char *name_prefix;
5221 if (!strcmp (klass_name, "IEnumerator`1"))
5222 name_prefix = g_strdup_printf ("%s.%s", klass_name_space, "IEnumerable`1");
5223 else
5224 name_prefix = g_strdup_printf ("%s.%s", klass_name_space, klass_name);
5226 /* Add the T[]/InternalEnumerator class */
5227 if (!strcmp (klass_name, "IEnumerable`1") || !strcmp (klass_name, "IEnumerator`1")) {
5228 ERROR_DECL (error);
5229 MonoClass *nclass;
5231 iter = NULL;
5232 while ((nclass = mono_class_get_nested_types (m_class_get_parent (array_class), &iter))) {
5233 if (!strcmp (m_class_get_name (nclass), "InternalEnumerator`1"))
5234 break;
5236 g_assert (nclass);
5237 nclass = mono_class_inflate_generic_class_checked (nclass, mono_generic_class_get_context (mono_class_get_generic_class (klass)), error);
5238 mono_error_assert_ok (error); /* FIXME don't swallow the error */
5239 add_generic_class (acfg, nclass, FALSE, "ICollection<T>");
5242 iter = NULL;
5243 while ((method = mono_class_get_methods (array_class, &iter))) {
5244 if (!strncmp (method->name, name_prefix, strlen (name_prefix))) {
5245 MonoMethod *m = mono_aot_get_array_helper_from_wrapper (method);
5247 if (m->is_inflated && !mono_method_is_generic_sharable_full (m, FALSE, FALSE, FALSE))
5248 add_extra_method_with_depth (acfg, m, depth);
5252 g_free (name_prefix);
5255 /* Add an instance of GenericComparer<T> which is created dynamically by Comparer<T> */
5256 if (in_corlib && !strcmp (klass_name_space, "System.Collections.Generic") && !strcmp (klass_name, "Comparer`1")) {
5257 ERROR_DECL (error);
5258 MonoClass *tclass = mono_class_from_mono_type_internal (mono_class_get_generic_class (klass)->context.class_inst->type_argv [0]);
5259 MonoClass *icomparable, *gcomparer, *icomparable_inst;
5260 MonoGenericContext ctx;
5261 MonoType *args [16];
5263 memset (&ctx, 0, sizeof (ctx));
5265 icomparable = mono_class_load_from_name (mono_defaults.corlib, "System", "IComparable`1");
5267 args [0] = m_class_get_byval_arg (tclass);
5268 ctx.class_inst = mono_metadata_get_generic_inst (1, args);
5270 icomparable_inst = mono_class_inflate_generic_class_checked (icomparable, &ctx, error);
5271 mono_error_assert_ok (error); /* FIXME don't swallow the error */
5273 if (mono_class_is_assignable_from_internal (icomparable_inst, tclass)) {
5274 MonoClass *gcomparer_inst;
5275 gcomparer = mono_class_load_from_name (mono_defaults.corlib, "System.Collections.Generic", "GenericComparer`1");
5276 gcomparer_inst = mono_class_inflate_generic_class_checked (gcomparer, &ctx, error);
5277 mono_error_assert_ok (error); /* FIXME don't swallow the error */
5279 add_generic_class (acfg, gcomparer_inst, FALSE, "Comparer<T>");
5283 /* Add an instance of GenericEqualityComparer<T> which is created dynamically by EqualityComparer<T> */
5284 if (in_corlib && !strcmp (klass_name_space, "System.Collections.Generic") && !strcmp (klass_name, "EqualityComparer`1")) {
5285 ERROR_DECL (error);
5286 MonoClass *tclass = mono_class_from_mono_type_internal (mono_class_get_generic_class (klass)->context.class_inst->type_argv [0]);
5287 MonoClass *iface, *gcomparer, *iface_inst;
5288 MonoGenericContext ctx;
5289 MonoType *args [16];
5291 memset (&ctx, 0, sizeof (ctx));
5293 iface = mono_class_load_from_name (mono_defaults.corlib, "System", "IEquatable`1");
5294 g_assert (iface);
5295 args [0] = m_class_get_byval_arg (tclass);
5296 ctx.class_inst = mono_metadata_get_generic_inst (1, args);
5298 iface_inst = mono_class_inflate_generic_class_checked (iface, &ctx, error);
5299 mono_error_assert_ok (error); /* FIXME don't swallow the error */
5301 if (mono_class_is_assignable_from_internal (iface_inst, tclass)) {
5302 MonoClass *gcomparer_inst;
5303 ERROR_DECL (error);
5305 gcomparer = mono_class_load_from_name (mono_defaults.corlib, "System.Collections.Generic", "GenericEqualityComparer`1");
5306 gcomparer_inst = mono_class_inflate_generic_class_checked (gcomparer, &ctx, error);
5307 mono_error_assert_ok (error); /* FIXME don't swallow the error */
5308 add_generic_class (acfg, gcomparer_inst, FALSE, "EqualityComparer<T>");
5312 /* Add an instance of EnumComparer<T> which is created dynamically by EqualityComparer<T> for enums */
5313 if (in_corlib && !strcmp (klass_name_space, "System.Collections.Generic") && !strcmp (klass_name, "EqualityComparer`1")) {
5314 MonoClass *enum_comparer;
5315 MonoClass *tclass = mono_class_from_mono_type_internal (mono_class_get_generic_class (klass)->context.class_inst->type_argv [0]);
5316 MonoGenericContext ctx;
5317 MonoType *args [16];
5319 if (m_class_is_enumtype (tclass)) {
5320 MonoClass *enum_comparer_inst;
5321 ERROR_DECL (error);
5323 memset (&ctx, 0, sizeof (ctx));
5324 args [0] = m_class_get_byval_arg (tclass);
5325 ctx.class_inst = mono_metadata_get_generic_inst (1, args);
5327 enum_comparer = mono_class_load_from_name (mono_defaults.corlib, "System.Collections.Generic", "EnumEqualityComparer`1");
5328 enum_comparer_inst = mono_class_inflate_generic_class_checked (enum_comparer, &ctx, error);
5329 mono_error_assert_ok (error); /* FIXME don't swallow the error */
5330 add_generic_class (acfg, enum_comparer_inst, FALSE, "EqualityComparer<T>");
5334 /* Add an instance of ObjectComparer<T> which is created dynamically by Comparer<T> for enums */
5335 if (in_corlib && !strcmp (klass_name_space, "System.Collections.Generic") && !strcmp (klass_name, "Comparer`1")) {
5336 MonoClass *comparer;
5337 MonoClass *tclass = mono_class_from_mono_type_internal (mono_class_get_generic_class (klass)->context.class_inst->type_argv [0]);
5338 MonoGenericContext ctx;
5339 MonoType *args [16];
5341 if (m_class_is_enumtype (tclass)) {
5342 MonoClass *comparer_inst;
5343 ERROR_DECL (error);
5345 memset (&ctx, 0, sizeof (ctx));
5346 args [0] = m_class_get_byval_arg (tclass);
5347 ctx.class_inst = mono_metadata_get_generic_inst (1, args);
5349 comparer = mono_class_load_from_name (mono_defaults.corlib, "System.Collections.Generic", "ObjectComparer`1");
5350 comparer_inst = mono_class_inflate_generic_class_checked (comparer, &ctx, error);
5351 mono_error_assert_ok (error); /* FIXME don't swallow the error */
5352 add_generic_class (acfg, comparer_inst, FALSE, "Comparer<T>");
5357 static void
5358 add_instances_of (MonoAotCompile *acfg, MonoClass *klass, MonoType **insts, int ninsts, gboolean force)
5360 int i;
5361 MonoGenericContext ctx;
5362 MonoType *args [16];
5364 if (acfg->aot_opts.no_instances)
5365 return;
5367 memset (&ctx, 0, sizeof (ctx));
5369 for (i = 0; i < ninsts; ++i) {
5370 ERROR_DECL (error);
5371 MonoClass *generic_inst;
5372 args [0] = insts [i];
5373 ctx.class_inst = mono_metadata_get_generic_inst (1, args);
5374 generic_inst = mono_class_inflate_generic_class_checked (klass, &ctx, error);
5375 mono_error_assert_ok (error); /* FIXME don't swallow the error */
5376 add_generic_class (acfg, generic_inst, force, "");
5380 static void
5381 add_types_from_method_header (MonoAotCompile *acfg, MonoMethod *method)
5383 ERROR_DECL (error);
5384 MonoMethodHeader *header;
5385 MonoMethodSignature *sig;
5386 int j, depth;
5388 depth = GPOINTER_TO_UINT (g_hash_table_lookup (acfg->method_depth, method));
5390 sig = mono_method_signature_internal (method);
5392 if (sig) {
5393 for (j = 0; j < sig->param_count; ++j)
5394 if (sig->params [j]->type == MONO_TYPE_GENERICINST)
5395 add_generic_class_with_depth (acfg, mono_class_from_mono_type_internal (sig->params [j]), depth + 1, "arg");
5398 header = mono_method_get_header_checked (method, error);
5400 if (header) {
5401 for (j = 0; j < header->num_locals; ++j)
5402 if (header->locals [j]->type == MONO_TYPE_GENERICINST)
5403 add_generic_class_with_depth (acfg, mono_class_from_mono_type_internal (header->locals [j]), depth + 1, "local");
5404 mono_metadata_free_mh (header);
5405 } else {
5406 mono_error_cleanup (error); /* FIXME report the error */
5412 * add_generic_instances:
5414 * Add instances referenced by the METHODSPEC/TYPESPEC table.
5416 static void
5417 add_generic_instances (MonoAotCompile *acfg)
5419 int i;
5420 guint32 token;
5421 MonoMethod *method;
5422 MonoGenericContext *context;
5424 if (acfg->aot_opts.no_instances)
5425 return;
5427 for (i = 0; i < acfg->image->tables [MONO_TABLE_METHODSPEC].rows; ++i) {
5428 ERROR_DECL (error);
5429 token = MONO_TOKEN_METHOD_SPEC | (i + 1);
5430 method = mono_get_method_checked (acfg->image, token, NULL, NULL, error);
5432 if (!method) {
5433 aot_printerrf (acfg, "Failed to load methodspec 0x%x due to %s.\n", token, mono_error_get_message (error));
5434 aot_printerrf (acfg, "Run with MONO_LOG_LEVEL=debug for more information.\n");
5435 mono_error_cleanup (error);
5436 continue;
5439 if (m_class_get_image (method->klass) != acfg->image)
5440 continue;
5442 context = mono_method_get_context (method);
5444 if (context && ((context->class_inst && context->class_inst->is_open)))
5445 continue;
5448 * For open methods, create an instantiation which can be passed to the JIT.
5449 * FIXME: Handle class_inst as well.
5451 if (context && context->method_inst && context->method_inst->is_open) {
5452 ERROR_DECL (error);
5453 MonoGenericContext shared_context;
5454 MonoGenericInst *inst;
5455 MonoType **type_argv;
5456 int i;
5457 MonoMethod *declaring_method;
5458 gboolean supported = TRUE;
5460 /* Check that the context doesn't contain open constructed types */
5461 if (context->class_inst) {
5462 inst = context->class_inst;
5463 for (i = 0; i < inst->type_argc; ++i) {
5464 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)
5465 continue;
5466 if (mono_class_is_open_constructed_type (inst->type_argv [i]))
5467 supported = FALSE;
5470 if (context->method_inst) {
5471 inst = context->method_inst;
5472 for (i = 0; i < inst->type_argc; ++i) {
5473 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)
5474 continue;
5475 if (mono_class_is_open_constructed_type (inst->type_argv [i]))
5476 supported = FALSE;
5480 if (!supported)
5481 continue;
5483 memset (&shared_context, 0, sizeof (MonoGenericContext));
5485 inst = context->class_inst;
5486 if (inst) {
5487 type_argv = g_new0 (MonoType*, inst->type_argc);
5488 for (i = 0; i < inst->type_argc; ++i) {
5489 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)
5490 type_argv [i] = mono_get_object_type ();
5491 else
5492 type_argv [i] = inst->type_argv [i];
5495 shared_context.class_inst = mono_metadata_get_generic_inst (inst->type_argc, type_argv);
5496 g_free (type_argv);
5499 inst = context->method_inst;
5500 if (inst) {
5501 type_argv = g_new0 (MonoType*, inst->type_argc);
5502 for (i = 0; i < inst->type_argc; ++i) {
5503 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)
5504 type_argv [i] = mono_get_object_type ();
5505 else
5506 type_argv [i] = inst->type_argv [i];
5509 shared_context.method_inst = mono_metadata_get_generic_inst (inst->type_argc, type_argv);
5510 g_free (type_argv);
5513 if (method->is_generic || mono_class_is_gtd (method->klass))
5514 declaring_method = method;
5515 else
5516 declaring_method = mono_method_get_declaring_generic_method (method);
5518 method = mono_class_inflate_generic_method_checked (declaring_method, &shared_context, error);
5519 g_assert (mono_error_ok (error)); /* FIXME don't swallow the error */
5523 * If the method is fully sharable, it was already added in place of its
5524 * generic definition.
5526 if (mono_method_is_generic_sharable_full (method, FALSE, FALSE, FALSE))
5527 continue;
5530 * FIXME: Partially shared methods are not shared here, so we end up with
5531 * many identical methods.
5533 add_extra_method (acfg, method);
5536 for (i = 0; i < acfg->image->tables [MONO_TABLE_TYPESPEC].rows; ++i) {
5537 ERROR_DECL (error);
5538 MonoClass *klass;
5540 token = MONO_TOKEN_TYPE_SPEC | (i + 1);
5542 klass = mono_class_get_checked (acfg->image, token, error);
5543 if (!klass || m_class_get_rank (klass)) {
5544 mono_error_cleanup (error);
5545 continue;
5548 add_generic_class (acfg, klass, FALSE, "typespec");
5551 /* Add types of args/locals */
5552 for (i = 0; i < acfg->methods->len; ++i) {
5553 method = (MonoMethod *)g_ptr_array_index (acfg->methods, i);
5554 add_types_from_method_header (acfg, method);
5557 if (acfg->image == mono_defaults.corlib) {
5558 MonoClass *klass;
5559 MonoType *insts [256];
5560 int ninsts = 0;
5562 MonoType *byte_type = m_class_get_byval_arg (mono_defaults.byte_class);
5563 MonoType *sbyte_type = m_class_get_byval_arg (mono_defaults.sbyte_class);
5564 MonoType *int16_type = m_class_get_byval_arg (mono_defaults.int16_class);
5565 MonoType *uint16_type = m_class_get_byval_arg (mono_defaults.uint16_class);
5566 MonoType *int32_type = mono_get_int32_type ();
5567 MonoType *uint32_type = m_class_get_byval_arg (mono_defaults.uint32_class);
5568 MonoType *int64_type = m_class_get_byval_arg (mono_defaults.int64_class);
5569 MonoType *uint64_type = m_class_get_byval_arg (mono_defaults.uint64_class);
5570 MonoType *object_type = mono_get_object_type ();
5572 insts [ninsts ++] = byte_type;
5573 insts [ninsts ++] = sbyte_type;
5574 insts [ninsts ++] = int16_type;
5575 insts [ninsts ++] = uint16_type;
5576 insts [ninsts ++] = int32_type;
5577 insts [ninsts ++] = uint32_type;
5578 insts [ninsts ++] = int64_type;
5579 insts [ninsts ++] = uint64_type;
5580 insts [ninsts ++] = m_class_get_byval_arg (mono_defaults.single_class);
5581 insts [ninsts ++] = m_class_get_byval_arg (mono_defaults.double_class);
5582 insts [ninsts ++] = m_class_get_byval_arg (mono_defaults.char_class);
5583 insts [ninsts ++] = m_class_get_byval_arg (mono_defaults.boolean_class);
5585 /* Add GenericComparer<T> instances for primitive types for Enum.ToString () */
5586 klass = mono_class_try_load_from_name (acfg->image, "System.Collections.Generic", "GenericComparer`1");
5587 if (klass)
5588 add_instances_of (acfg, klass, insts, ninsts, TRUE);
5589 klass = mono_class_try_load_from_name (acfg->image, "System.Collections.Generic", "GenericEqualityComparer`1");
5590 if (klass)
5591 add_instances_of (acfg, klass, insts, ninsts, TRUE);
5593 /* Add instances of EnumEqualityComparer which are created by EqualityComparer<T> for enums */
5595 MonoClass *enum_comparer;
5596 MonoType *insts [16];
5597 int ninsts;
5599 ninsts = 0;
5600 insts [ninsts ++] = int32_type;
5601 insts [ninsts ++] = uint32_type;
5602 insts [ninsts ++] = uint16_type;
5603 insts [ninsts ++] = byte_type;
5604 enum_comparer = mono_class_load_from_name (mono_defaults.corlib, "System.Collections.Generic", "EnumEqualityComparer`1");
5605 add_instances_of (acfg, enum_comparer, insts, ninsts, FALSE);
5607 ninsts = 0;
5608 insts [ninsts ++] = int16_type;
5609 enum_comparer = mono_class_load_from_name (mono_defaults.corlib, "System.Collections.Generic", "ShortEnumEqualityComparer`1");
5610 add_instances_of (acfg, enum_comparer, insts, ninsts, FALSE);
5612 ninsts = 0;
5613 insts [ninsts ++] = sbyte_type;
5614 enum_comparer = mono_class_load_from_name (mono_defaults.corlib, "System.Collections.Generic", "SByteEnumEqualityComparer`1");
5615 add_instances_of (acfg, enum_comparer, insts, ninsts, FALSE);
5617 enum_comparer = mono_class_load_from_name (mono_defaults.corlib, "System.Collections.Generic", "LongEnumEqualityComparer`1");
5618 ninsts = 0;
5619 insts [ninsts ++] = int64_type;
5620 insts [ninsts ++] = uint64_type;
5621 add_instances_of (acfg, enum_comparer, insts, ninsts, FALSE);
5624 /* Add instances of the array generic interfaces for primitive types */
5625 /* This will add instances of the InternalArray_ helper methods in Array too */
5626 klass = mono_class_try_load_from_name (acfg->image, "System.Collections.Generic", "ICollection`1");
5627 if (klass)
5628 add_instances_of (acfg, klass, insts, ninsts, TRUE);
5630 klass = mono_class_try_load_from_name (acfg->image, "System.Collections.Generic", "IList`1");
5631 if (klass)
5632 add_instances_of (acfg, klass, insts, ninsts, TRUE);
5634 klass = mono_class_try_load_from_name (acfg->image, "System.Collections.Generic", "IEnumerable`1");
5635 if (klass)
5636 add_instances_of (acfg, klass, insts, ninsts, TRUE);
5639 * Add a managed-to-native wrapper of Array.GetGenericValueImpl<object>, which is
5640 * used for all instances of GetGenericValueImpl by the AOT runtime.
5643 ERROR_DECL (error);
5644 MonoGenericContext ctx;
5645 MonoType *args [16];
5646 MonoMethod *get_method;
5647 MonoClass *array_klass = m_class_get_parent (mono_class_create_array (mono_defaults.object_class, 1));
5649 get_method = mono_class_get_method_from_name_checked (array_klass, "GetGenericValueImpl", 2, 0, error);
5650 mono_error_assert_ok (error);
5652 if (get_method) {
5653 memset (&ctx, 0, sizeof (ctx));
5654 args [0] = object_type;
5655 ctx.method_inst = mono_metadata_get_generic_inst (1, args);
5656 add_extra_method (acfg, mono_marshal_get_native_wrapper (mono_class_inflate_generic_method_checked (get_method, &ctx, error), TRUE, TRUE));
5657 mono_error_assert_ok (error); /* FIXME don't swallow the error */
5661 /* Same for CompareExchange<T>/Exchange<T> */
5663 MonoGenericContext ctx;
5664 MonoType *args [16];
5665 MonoMethod *m;
5666 MonoClass *interlocked_klass = mono_class_load_from_name (mono_defaults.corlib, "System.Threading", "Interlocked");
5667 gpointer iter = NULL;
5669 while ((m = mono_class_get_methods (interlocked_klass, &iter))) {
5670 if ((!strcmp (m->name, "CompareExchange") || !strcmp (m->name, "Exchange")) && m->is_generic) {
5671 ERROR_DECL (error);
5672 memset (&ctx, 0, sizeof (ctx));
5673 args [0] = object_type;
5674 ctx.method_inst = mono_metadata_get_generic_inst (1, args);
5675 add_extra_method (acfg, mono_marshal_get_native_wrapper (mono_class_inflate_generic_method_checked (m, &ctx, error), TRUE, TRUE));
5676 g_assert (mono_error_ok (error)); /* FIXME don't swallow the error */
5681 /* Same for Volatile.Read/Write<T> */
5683 MonoGenericContext ctx;
5684 MonoType *args [16];
5685 MonoMethod *m;
5686 MonoClass *volatile_klass = mono_class_try_load_from_name (mono_defaults.corlib, "System.Threading", "Volatile");
5687 gpointer iter = NULL;
5689 if (volatile_klass) {
5690 while ((m = mono_class_get_methods (volatile_klass, &iter))) {
5691 if ((!strcmp (m->name, "Read") || !strcmp (m->name, "Write")) && m->is_generic) {
5692 ERROR_DECL (error);
5693 memset (&ctx, 0, sizeof (ctx));
5694 args [0] = object_type;
5695 ctx.method_inst = mono_metadata_get_generic_inst (1, args);
5696 add_extra_method (acfg, mono_marshal_get_native_wrapper (mono_class_inflate_generic_method_checked (m, &ctx, error), TRUE, TRUE));
5697 g_assert (mono_error_ok (error)); /* FIXME don't swallow the error */
5703 /* object[] accessor wrappers. */
5704 for (i = 1; i < 4; ++i) {
5705 MonoClass *obj_array_class = mono_class_create_array (mono_defaults.object_class, i);
5706 MonoMethod *m;
5708 m = get_method_nofail (obj_array_class, "Get", i, 0);
5709 g_assert (m);
5711 m = mono_marshal_get_array_accessor_wrapper (m);
5712 add_extra_method (acfg, m);
5714 m = get_method_nofail (obj_array_class, "Address", i, 0);
5715 g_assert (m);
5717 m = mono_marshal_get_array_accessor_wrapper (m);
5718 add_extra_method (acfg, m);
5720 m = get_method_nofail (obj_array_class, "Set", i + 1, 0);
5721 g_assert (m);
5723 m = mono_marshal_get_array_accessor_wrapper (m);
5724 add_extra_method (acfg, m);
5729 static char *
5730 decode_direct_icall_symbol_name_attribute (MonoMethod *method)
5732 ERROR_DECL (error);
5734 int j = 0;
5735 char *symbol_name = NULL;
5737 MonoCustomAttrInfo *cattr = mono_custom_attrs_from_method_checked (method, error);
5738 if (mono_error_ok(error) && cattr) {
5739 for (j = 0; j < cattr->num_attrs; j++)
5740 if (cattr->attrs [j].ctor && !strcmp (m_class_get_name (cattr->attrs [j].ctor->klass), "MonoDirectICallSymbolNameAttribute"))
5741 break;
5743 if (j < cattr->num_attrs) {
5744 MonoCustomAttrEntry *e = &cattr->attrs [j];
5745 MonoMethodSignature *sig = mono_method_signature_internal (e->ctor);
5746 if (e->data && sig && sig->param_count == 1 && sig->params [0]->type == MONO_TYPE_STRING) {
5748 * Decode the cattr manually since we can't create objects
5749 * during aot compilation.
5752 /* Skip prolog */
5753 const char *p = ((const char*)e->data) + 2;
5754 int slen = mono_metadata_decode_value (p, &p);
5756 symbol_name = (char *)g_memdup (p, slen + 1);
5757 if (symbol_name)
5758 symbol_name [slen] = 0;
5763 return symbol_name;
5765 static const char*
5766 lookup_external_icall_symbol_name_aot (MonoMethod *method)
5768 g_assert (method_to_external_icall_symbol_name);
5770 gpointer key, value;
5771 if (g_hash_table_lookup_extended (method_to_external_icall_symbol_name, method, &key, &value))
5772 return (const char*)value;
5774 char *symbol_name = decode_direct_icall_symbol_name_attribute (method);
5775 g_hash_table_insert (method_to_external_icall_symbol_name, method, symbol_name);
5777 return symbol_name;
5780 static const char*
5781 lookup_icall_symbol_name_aot (MonoMethod *method)
5783 const char * symbol_name = mono_lookup_icall_symbol (method);
5784 if (!symbol_name)
5785 symbol_name = lookup_external_icall_symbol_name_aot (method);
5787 return symbol_name;
5790 gboolean
5791 mono_aot_direct_icalls_enabled_for_method (MonoCompile *cfg, MonoMethod *method)
5793 gboolean enable_icall = FALSE;
5794 if (cfg->compile_aot)
5795 enable_icall = lookup_external_icall_symbol_name_aot (method) ? TRUE : FALSE;
5796 else
5797 enable_icall = FALSE;
5799 return enable_icall;
5803 * is_direct_callable:
5805 * Return whenever the method identified by JI is directly callable without
5806 * going through the PLT.
5808 static gboolean
5809 is_direct_callable (MonoAotCompile *acfg, MonoMethod *method, MonoJumpInfo *patch_info)
5811 if ((patch_info->type == MONO_PATCH_INFO_METHOD) && (m_class_get_image (patch_info->data.method->klass) == acfg->image)) {
5812 MonoCompile *callee_cfg = (MonoCompile *)g_hash_table_lookup (acfg->method_to_cfg, patch_info->data.method);
5813 if (callee_cfg) {
5814 gboolean direct_callable = TRUE;
5816 if (direct_callable && (acfg->aot_opts.dedup || acfg->aot_opts.dedup_include) && mono_aot_can_dedup (patch_info->data.method))
5817 direct_callable = FALSE;
5819 if (direct_callable && (!acfg->llvm || acfg->aot_opts.llvm_disable_self_init) && !(!callee_cfg->has_got_slots && mono_class_is_before_field_init (callee_cfg->method->klass)))
5820 direct_callable = FALSE;
5822 if (direct_callable && !strcmp (callee_cfg->method->name, ".cctor"))
5823 direct_callable = FALSE;
5826 // FIXME: Support inflated methods, it asserts in mono_aot_init_gshared_method_this () because the method is not in
5827 // amodule->extra_methods.
5829 if (direct_callable && callee_cfg->method->is_inflated)
5830 direct_callable = FALSE;
5832 if (direct_callable && (callee_cfg->method->iflags & METHOD_IMPL_ATTRIBUTE_SYNCHRONIZED) && (!method || method->wrapper_type != MONO_WRAPPER_SYNCHRONIZED))
5833 // FIXME: Maybe call the wrapper directly ?
5834 direct_callable = FALSE;
5836 if (direct_callable && (acfg->aot_opts.soft_debug || acfg->aot_opts.no_direct_calls)) {
5837 /* Disable this so all calls go through load_method (), see the
5838 * mini_get_debug_options ()->load_aot_jit_info_eagerly = TRUE; line in
5839 * mono_debugger_agent_init ().
5841 direct_callable = FALSE;
5844 if (direct_callable && (callee_cfg->method->wrapper_type == MONO_WRAPPER_ALLOC))
5845 /* sgen does some initialization when the allocator method is created */
5846 direct_callable = FALSE;
5847 if (direct_callable && (callee_cfg->method->wrapper_type == MONO_WRAPPER_WRITE_BARRIER))
5848 /* we don't know at compile time whether sgen is concurrent or not */
5849 direct_callable = FALSE;
5851 if (direct_callable)
5852 return TRUE;
5854 } else if ((patch_info->type == MONO_PATCH_INFO_ICALL_ADDR_CALL && patch_info->data.method->flags & METHOD_ATTRIBUTE_PINVOKE_IMPL)) {
5855 if (acfg->aot_opts.direct_pinvoke)
5856 return TRUE;
5857 } else if (patch_info->type == MONO_PATCH_INFO_ICALL_ADDR_CALL) {
5858 if (acfg->aot_opts.direct_icalls)
5859 return TRUE;
5860 return FALSE;
5863 return FALSE;
5866 #ifdef MONO_ARCH_AOT_SUPPORTED
5867 static const char *
5868 get_pinvoke_import (MonoAotCompile *acfg, MonoMethod *method)
5870 MonoImage *image = m_class_get_image (method->klass);
5871 MonoMethodPInvoke *piinfo = (MonoMethodPInvoke *) method;
5872 MonoTableInfo *tables = image->tables;
5873 MonoTableInfo *im = &tables [MONO_TABLE_IMPLMAP];
5874 MonoTableInfo *mr = &tables [MONO_TABLE_MODULEREF];
5875 guint32 im_cols [MONO_IMPLMAP_SIZE];
5876 char *import;
5878 import = (char *)g_hash_table_lookup (acfg->method_to_pinvoke_import, method);
5879 if (import != NULL)
5880 return import;
5882 if (!piinfo->implmap_idx || piinfo->implmap_idx > im->rows)
5883 return NULL;
5885 mono_metadata_decode_row (im, piinfo->implmap_idx - 1, im_cols, MONO_IMPLMAP_SIZE);
5887 if (!im_cols [MONO_IMPLMAP_SCOPE] || im_cols [MONO_IMPLMAP_SCOPE] > mr->rows)
5888 return NULL;
5890 import = g_strdup_printf ("%s", mono_metadata_string_heap (image, im_cols [MONO_IMPLMAP_NAME]));
5892 g_hash_table_insert (acfg->method_to_pinvoke_import, method, import);
5894 return import;
5896 #else
5897 static const char *
5898 get_pinvoke_import (MonoAotCompile *acfg, MonoMethod *method)
5900 return NULL;
5902 #endif
5904 static gint
5905 compare_lne (MonoDebugLineNumberEntry *a, MonoDebugLineNumberEntry *b)
5907 if (a->native_offset == b->native_offset)
5908 return a->il_offset - b->il_offset;
5909 else
5910 return a->native_offset - b->native_offset;
5914 * compute_line_numbers:
5916 * Returns a sparse array of size CODE_SIZE containing MonoDebugSourceLocation* entries for the native offsets which have a corresponding line number
5917 * entry.
5919 static MonoDebugSourceLocation**
5920 compute_line_numbers (MonoMethod *method, int code_size, MonoDebugMethodJitInfo *debug_info)
5922 MonoDebugMethodInfo *minfo;
5923 MonoDebugLineNumberEntry *ln_array;
5924 MonoDebugSourceLocation *loc;
5925 int i, prev_line, prev_il_offset;
5926 int *native_to_il_offset = NULL;
5927 MonoDebugSourceLocation **res;
5928 gboolean first;
5930 minfo = mono_debug_lookup_method (method);
5931 if (!minfo)
5932 return NULL;
5933 // FIXME: This seems to happen when two methods have the same cfg->method_to_register
5934 if (debug_info->code_size != code_size)
5935 return NULL;
5937 g_assert (code_size);
5939 /* Compute the native->IL offset mapping */
5941 ln_array = g_new0 (MonoDebugLineNumberEntry, debug_info->num_line_numbers);
5942 memcpy (ln_array, debug_info->line_numbers, debug_info->num_line_numbers * sizeof (MonoDebugLineNumberEntry));
5944 qsort (ln_array, debug_info->num_line_numbers, sizeof (MonoDebugLineNumberEntry), (int (*)(const void *, const void *))compare_lne);
5946 native_to_il_offset = g_new0 (int, code_size + 1);
5948 for (i = 0; i < debug_info->num_line_numbers; ++i) {
5949 int j;
5950 MonoDebugLineNumberEntry *lne = &ln_array [i];
5952 if (i == 0) {
5953 for (j = 0; j < lne->native_offset; ++j)
5954 native_to_il_offset [j] = -1;
5957 if (i < debug_info->num_line_numbers - 1) {
5958 MonoDebugLineNumberEntry *lne_next = &ln_array [i + 1];
5960 for (j = lne->native_offset; j < lne_next->native_offset; ++j)
5961 native_to_il_offset [j] = lne->il_offset;
5962 } else {
5963 for (j = lne->native_offset; j < code_size; ++j)
5964 native_to_il_offset [j] = lne->il_offset;
5967 g_free (ln_array);
5969 /* Compute the native->line number mapping */
5970 res = g_new0 (MonoDebugSourceLocation*, code_size);
5971 prev_il_offset = -1;
5972 prev_line = -1;
5973 first = TRUE;
5974 for (i = 0; i < code_size; ++i) {
5975 int il_offset = native_to_il_offset [i];
5977 if (il_offset == -1 || il_offset == prev_il_offset)
5978 continue;
5979 prev_il_offset = il_offset;
5980 loc = mono_debug_method_lookup_location (minfo, il_offset);
5981 if (!(loc && loc->source_file))
5982 continue;
5983 if (loc->row == prev_line) {
5984 mono_debug_free_source_location (loc);
5985 continue;
5987 prev_line = loc->row;
5988 //printf ("D: %s:%d il=%x native=%x\n", loc->source_file, loc->row, il_offset, i);
5989 if (first)
5990 /* This will cover the prolog too */
5991 res [0] = loc;
5992 else
5993 res [i] = loc;
5994 first = FALSE;
5996 return res;
5999 static int
6000 get_file_index (MonoAotCompile *acfg, const char *source_file)
6002 int findex;
6004 // FIXME: Free these
6005 if (!acfg->dwarf_ln_filenames)
6006 acfg->dwarf_ln_filenames = g_hash_table_new (g_str_hash, g_str_equal);
6007 findex = GPOINTER_TO_INT (g_hash_table_lookup (acfg->dwarf_ln_filenames, source_file));
6008 if (!findex) {
6009 findex = g_hash_table_size (acfg->dwarf_ln_filenames) + 1;
6010 g_hash_table_insert (acfg->dwarf_ln_filenames, g_strdup (source_file), GINT_TO_POINTER (findex));
6011 emit_unset_mode (acfg);
6012 fprintf (acfg->fp, ".file %d \"%s\"\n", findex, mono_dwarf_escape_path (source_file));
6014 return findex;
6017 #ifdef TARGET_ARM64
6018 #define INST_LEN 4
6019 #else
6020 #define INST_LEN 1
6021 #endif
6024 * emit_and_reloc_code:
6026 * Emit the native code in CODE, handling relocations along the way. If GOT_ONLY
6027 * is true, calls are made through the GOT too. This is used for emitting trampolines
6028 * in full-aot mode, since calls made from trampolines couldn't go through the PLT,
6029 * since trampolines are needed to make PLT work.
6031 static void
6032 emit_and_reloc_code (MonoAotCompile *acfg, MonoMethod *method, guint8 *code, guint32 code_len, MonoJumpInfo *relocs, gboolean got_only, MonoDebugMethodJitInfo *debug_info)
6034 int i, pindex, start_index;
6035 GPtrArray *patches;
6036 MonoJumpInfo *patch_info;
6037 MonoDebugSourceLocation **locs = NULL;
6038 gboolean skip, prologue_end = FALSE;
6039 #ifdef MONO_ARCH_AOT_SUPPORTED
6040 gboolean direct_call, external_call;
6041 guint32 got_slot;
6042 const char *direct_call_target = 0;
6043 const char *direct_pinvoke;
6044 #endif
6046 if (acfg->gas_line_numbers && method && debug_info) {
6047 locs = compute_line_numbers (method, code_len, debug_info);
6048 if (!locs) {
6049 int findex = get_file_index (acfg, "<unknown>");
6050 emit_unset_mode (acfg);
6051 fprintf (acfg->fp, ".loc %d %d 0\n", findex, 1);
6055 /* Collect and sort relocations */
6056 patches = g_ptr_array_new ();
6057 for (patch_info = relocs; patch_info; patch_info = patch_info->next)
6058 g_ptr_array_add (patches, patch_info);
6059 g_ptr_array_sort (patches, compare_patches);
6061 start_index = 0;
6062 for (i = 0; i < code_len; i += INST_LEN) {
6063 patch_info = NULL;
6064 for (pindex = start_index; pindex < patches->len; ++pindex) {
6065 patch_info = (MonoJumpInfo *)g_ptr_array_index (patches, pindex);
6066 if (patch_info->ip.i >= i)
6067 break;
6070 if (locs && locs [i]) {
6071 MonoDebugSourceLocation *loc = locs [i];
6072 int findex;
6073 const char *options;
6075 findex = get_file_index (acfg, loc->source_file);
6076 emit_unset_mode (acfg);
6077 if (!prologue_end)
6078 options = " prologue_end";
6079 else
6080 options = "";
6081 prologue_end = TRUE;
6082 fprintf (acfg->fp, ".loc %d %d 0%s\n", findex, loc->row, options);
6083 mono_debug_free_source_location (loc);
6086 skip = FALSE;
6087 #ifdef MONO_ARCH_AOT_SUPPORTED
6088 if (patch_info && (patch_info->ip.i == i) && (pindex < patches->len)) {
6089 start_index = pindex;
6091 switch (patch_info->type) {
6092 case MONO_PATCH_INFO_NONE:
6093 break;
6094 case MONO_PATCH_INFO_GOT_OFFSET: {
6095 int code_size;
6097 arch_emit_got_offset (acfg, code + i, &code_size);
6098 i += code_size - INST_LEN;
6099 skip = TRUE;
6100 patch_info->type = MONO_PATCH_INFO_NONE;
6101 break;
6103 case MONO_PATCH_INFO_OBJC_SELECTOR_REF: {
6104 int code_size, index;
6105 char *selector = (char *)patch_info->data.target;
6107 if (!acfg->objc_selector_to_index)
6108 acfg->objc_selector_to_index = g_hash_table_new (g_str_hash, g_str_equal);
6109 if (!acfg->objc_selectors)
6110 acfg->objc_selectors = g_ptr_array_new ();
6111 index = GPOINTER_TO_UINT (g_hash_table_lookup (acfg->objc_selector_to_index, selector));
6112 if (index)
6113 index --;
6114 else {
6115 index = acfg->objc_selector_index;
6116 g_ptr_array_add (acfg->objc_selectors, (void*)patch_info->data.target);
6117 g_hash_table_insert (acfg->objc_selector_to_index, selector, GUINT_TO_POINTER (index + 1));
6118 acfg->objc_selector_index ++;
6121 arch_emit_objc_selector_ref (acfg, code + i, index, &code_size);
6122 i += code_size - INST_LEN;
6123 skip = TRUE;
6124 patch_info->type = MONO_PATCH_INFO_NONE;
6125 break;
6127 default: {
6129 * If this patch is a call, try emitting a direct call instead of
6130 * through a PLT entry. This is possible if the called method is in
6131 * the same assembly and requires no initialization.
6133 direct_call = FALSE;
6134 external_call = FALSE;
6135 if ((patch_info->type == MONO_PATCH_INFO_METHOD) && (m_class_get_image (patch_info->data.method->klass) == acfg->image)) {
6136 if (!got_only && is_direct_callable (acfg, method, patch_info)) {
6137 MonoCompile *callee_cfg = (MonoCompile *)g_hash_table_lookup (acfg->method_to_cfg, patch_info->data.method);
6139 // Don't compile inflated methods if we're doing dedup
6140 if (acfg->aot_opts.dedup && !mono_aot_can_dedup (patch_info->data.method)) {
6141 char *name = mono_aot_get_mangled_method_name (patch_info->data.method);
6142 mono_trace (G_LOG_LEVEL_DEBUG, MONO_TRACE_AOT, "DIRECT CALL: %s by %s", name, method ? mono_method_full_name (method, TRUE) : "");
6143 g_free (name);
6145 direct_call = TRUE;
6146 direct_call_target = callee_cfg->asm_symbol;
6147 patch_info->type = MONO_PATCH_INFO_NONE;
6148 acfg->stats.direct_calls ++;
6152 acfg->stats.all_calls ++;
6153 } else if (patch_info->type == MONO_PATCH_INFO_ICALL_ADDR_CALL) {
6154 if (!got_only && is_direct_callable (acfg, method, patch_info)) {
6155 if (!(patch_info->data.method->flags & METHOD_ATTRIBUTE_PINVOKE_IMPL))
6156 direct_pinvoke = lookup_icall_symbol_name_aot (patch_info->data.method);
6157 else
6158 direct_pinvoke = get_pinvoke_import (acfg, patch_info->data.method);
6159 if (direct_pinvoke) {
6160 direct_call = TRUE;
6161 g_assert (strlen (direct_pinvoke) < 1000);
6162 direct_call_target = g_strdup_printf ("%s%s", acfg->user_symbol_prefix, direct_pinvoke);
6165 } else if (patch_info->type == MONO_PATCH_INFO_JIT_ICALL_ADDR) {
6166 const char *sym = mono_lookup_jit_icall_symbol (patch_info->data.name);
6167 if (!got_only && sym && acfg->aot_opts.direct_icalls) {
6168 /* Call to a C function implementing a jit icall */
6169 direct_call = TRUE;
6170 external_call = TRUE;
6171 g_assert (strlen (sym) < 1000);
6172 direct_call_target = g_strdup_printf ("%s%s", acfg->user_symbol_prefix, sym);
6174 } else if (patch_info->type == MONO_PATCH_INFO_JIT_ICALL_ID) {
6175 MonoJitICallInfo * const info = mono_find_jit_icall_info (patch_info->data.jit_icall_id);
6176 const char * const sym = info->c_symbol;
6177 if (!got_only && sym && acfg->aot_opts.direct_icalls && info->func == info->wrapper) {
6178 /* Call to a jit icall without a wrapper */
6179 direct_call = TRUE;
6180 external_call = TRUE;
6181 g_assert (strlen (sym) < 1000);
6182 direct_call_target = g_strdup_printf ("%s%s", acfg->user_symbol_prefix, sym);
6185 if (direct_call) {
6186 patch_info->type = MONO_PATCH_INFO_NONE;
6187 acfg->stats.direct_calls ++;
6190 if (!got_only && !direct_call) {
6191 MonoPltEntry *plt_entry = get_plt_entry (acfg, patch_info);
6192 if (plt_entry) {
6193 /* This patch has a PLT entry, so we must emit a call to the PLT entry */
6194 direct_call = TRUE;
6195 direct_call_target = plt_entry->symbol;
6197 /* Nullify the patch */
6198 patch_info->type = MONO_PATCH_INFO_NONE;
6199 plt_entry->jit_used = TRUE;
6203 if (direct_call) {
6204 int call_size;
6206 arch_emit_direct_call (acfg, direct_call_target, external_call, FALSE, patch_info, &call_size);
6207 i += call_size - INST_LEN;
6208 } else {
6209 int code_size;
6211 got_slot = get_got_offset (acfg, FALSE, patch_info);
6213 arch_emit_got_access (acfg, acfg->got_symbol, code + i, got_slot, &code_size);
6214 i += code_size - INST_LEN;
6216 skip = TRUE;
6220 #endif /* MONO_ARCH_AOT_SUPPORTED */
6222 if (!skip) {
6223 /* Find next patch */
6224 patch_info = NULL;
6225 for (pindex = start_index; pindex < patches->len; ++pindex) {
6226 patch_info = (MonoJumpInfo *)g_ptr_array_index (patches, pindex);
6227 if (patch_info->ip.i >= i)
6228 break;
6231 /* Try to emit multiple bytes at once */
6232 if (pindex < patches->len && patch_info->ip.i > i) {
6233 int limit;
6235 for (limit = i + INST_LEN; limit < patch_info->ip.i; limit += INST_LEN) {
6236 if (locs && locs [limit])
6237 break;
6240 emit_code_bytes (acfg, code + i, limit - i);
6241 i = limit - INST_LEN;
6242 } else {
6243 emit_code_bytes (acfg, code + i, INST_LEN);
6248 g_ptr_array_free (patches, TRUE);
6249 g_free (locs);
6253 * sanitize_symbol:
6255 * Return a modified version of S which only includes characters permissible in symbols.
6257 static char*
6258 sanitize_symbol (MonoAotCompile *acfg, char *s)
6260 gboolean process = FALSE;
6261 int i, len;
6262 GString *gs;
6263 char *res;
6265 if (!s)
6266 return s;
6268 len = strlen (s);
6269 for (i = 0; i < len; ++i)
6270 if (!(s [i] <= 0x7f && (isalnum (s [i]) || s [i] == '_')))
6271 process = TRUE;
6272 if (!process)
6273 return s;
6275 gs = g_string_sized_new (len);
6276 for (i = 0; i < len; ++i) {
6277 guint8 c = s [i];
6278 if (c <= 0x7f && (isalnum (c) || c == '_')) {
6279 g_string_append_c (gs, c);
6280 } else if (c > 0x7f) {
6281 /* multi-byte utf8 */
6282 g_string_append_printf (gs, "_0x%x", c);
6283 i ++;
6284 c = s [i];
6285 while (c >> 6 == 0x2) {
6286 g_string_append_printf (gs, "%x", c);
6287 i ++;
6288 c = s [i];
6290 g_string_append_printf (gs, "_");
6291 i --;
6292 } else {
6293 g_string_append_c (gs, '_');
6297 res = mono_mempool_strdup (acfg->mempool, gs->str);
6298 g_string_free (gs, TRUE);
6299 return res;
6302 static char*
6303 get_debug_sym (MonoMethod *method, const char *prefix, GHashTable *cache)
6305 char *name1, *name2, *cached;
6306 int i, j, len, count;
6307 MonoMethod *cached_method;
6309 name1 = mono_method_full_name (method, TRUE);
6311 #ifdef TARGET_MACH
6312 // This is so that we don't accidentally create a local symbol (which starts with 'L')
6313 if ((!prefix || !*prefix) && name1 [0] == 'L')
6314 prefix = "_";
6315 #endif
6317 #if defined(TARGET_WIN32) && defined(TARGET_X86)
6318 char adjustedPrefix [MAX_SYMBOL_SIZE];
6319 prefix = mangle_symbol (prefix, adjustedPrefix, G_N_ELEMENTS (adjustedPrefix));
6320 #endif
6322 len = strlen (name1);
6323 name2 = (char *) g_malloc (strlen (prefix) + len + 16);
6324 memcpy (name2, prefix, strlen (prefix));
6325 j = strlen (prefix);
6326 for (i = 0; i < len; ++i) {
6327 if (i == 0 && name1 [0] >= '0' && name1 [0] <= '9') {
6328 name2 [j ++] = '_';
6329 } else if (isalnum (name1 [i])) {
6330 name2 [j ++] = name1 [i];
6331 } else if (name1 [i] == ' ' && name1 [i + 1] == '(' && name1 [i + 2] == ')') {
6332 i += 2;
6333 } else if (name1 [i] == ',' && name1 [i + 1] == ' ') {
6334 name2 [j ++] = '_';
6335 i++;
6336 } else if (name1 [i] == '(' || name1 [i] == ')' || name1 [i] == '>') {
6337 } else
6338 name2 [j ++] = '_';
6340 name2 [j] = '\0';
6342 g_free (name1);
6344 count = 0;
6345 while (TRUE) {
6346 cached_method = (MonoMethod *)g_hash_table_lookup (cache, name2);
6347 if (!(cached_method && cached_method != method))
6348 break;
6349 sprintf (name2 + j, "_%d", count);
6350 count ++;
6353 cached = g_strdup (name2);
6354 g_hash_table_insert (cache, cached, method);
6356 return name2;
6359 static void
6360 emit_method_code (MonoAotCompile *acfg, MonoCompile *cfg)
6362 MonoMethod *method;
6363 int method_index;
6364 guint8 *code;
6365 char *debug_sym = NULL;
6366 char *symbol = NULL;
6367 int func_alignment = AOT_FUNC_ALIGNMENT;
6368 char *export_name;
6370 g_assert (!ignore_cfg (cfg));
6372 method = cfg->orig_method;
6373 code = cfg->native_code;
6375 method_index = get_method_index (acfg, method);
6376 symbol = g_strdup_printf ("%sme_%x", acfg->temp_prefix, method_index);
6378 /* Make the labels local */
6379 emit_section_change (acfg, ".text", 0);
6380 emit_alignment_code (acfg, func_alignment);
6382 if (acfg->global_symbols && acfg->need_no_dead_strip)
6383 fprintf (acfg->fp, " .no_dead_strip %s\n", cfg->asm_symbol);
6385 emit_label (acfg, cfg->asm_symbol);
6387 if (acfg->aot_opts.write_symbols && !acfg->global_symbols && !acfg->llvm) {
6389 * Write a C style symbol for every method, this has two uses:
6390 * - it works on platforms where the dwarf debugging info is not
6391 * yet supported.
6392 * - it allows the setting of breakpoints of aot-ed methods.
6395 // Comment out to force dedup to link these symbols and forbid compiling
6396 // in duplicated code. This is an "assert when linking if broken" trick.
6397 /*if (mono_aot_can_dedup (method) && (acfg->aot_opts.dedup || acfg->aot_opts.dedup_include))*/
6398 /*debug_sym = mono_aot_get_mangled_method_name (method);*/
6399 /*else*/
6400 debug_sym = get_debug_sym (method, "", acfg->method_label_hash);
6402 cfg->asm_debug_symbol = g_strdup (debug_sym);
6404 if (acfg->need_no_dead_strip)
6405 fprintf (acfg->fp, " .no_dead_strip %s\n", debug_sym);
6407 // Comment out to force dedup to link these symbols and forbid compiling
6408 // in duplicated code. This is an "assert when linking if broken" trick.
6409 /*if (mono_aot_can_dedup (method) && (acfg->aot_opts.dedup || acfg->aot_opts.dedup_include))*/
6410 /*emit_global_inner (acfg, debug_sym, TRUE);*/
6411 /*else*/
6412 emit_local_symbol (acfg, debug_sym, symbol, TRUE);
6414 emit_label (acfg, debug_sym);
6417 export_name = (char *)g_hash_table_lookup (acfg->export_names, method);
6418 if (export_name) {
6419 /* Emit a global symbol for the method */
6420 emit_global_inner (acfg, export_name, TRUE);
6421 emit_label (acfg, export_name);
6424 if (cfg->verbose_level > 0 && !ignore_cfg (cfg))
6425 g_print ("Method %s emitted as %s\n", mono_method_get_full_name (method), cfg->asm_symbol);
6427 acfg->stats.code_size += cfg->code_len;
6429 acfg->cfgs [method_index]->got_offset = acfg->got_offset;
6431 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 ()));
6433 emit_line (acfg);
6435 if (acfg->aot_opts.write_symbols) {
6436 if (debug_sym)
6437 emit_symbol_size (acfg, debug_sym, ".");
6438 else
6439 emit_symbol_size (acfg, cfg->asm_symbol, ".");
6440 g_free (debug_sym);
6443 emit_label (acfg, symbol);
6445 arch_emit_unwind_info_sections (acfg, cfg->asm_symbol, symbol, cfg->unwind_ops);
6447 g_free (symbol);
6451 * encode_patch:
6453 * Encode PATCH_INFO into its disk representation.
6455 static void
6456 encode_patch (MonoAotCompile *acfg, MonoJumpInfo *patch_info, guint8 *buf, guint8 **endbuf)
6458 guint8 *p = buf;
6460 switch (patch_info->type) {
6461 case MONO_PATCH_INFO_NONE:
6462 break;
6463 case MONO_PATCH_INFO_IMAGE:
6464 encode_value (get_image_index (acfg, patch_info->data.image), p, &p);
6465 break;
6466 case MONO_PATCH_INFO_MSCORLIB_GOT_ADDR:
6467 case MONO_PATCH_INFO_GC_CARD_TABLE_ADDR:
6468 case MONO_PATCH_INFO_GC_NURSERY_START:
6469 case MONO_PATCH_INFO_GC_NURSERY_BITS:
6470 break;
6471 case MONO_PATCH_INFO_SWITCH: {
6472 gpointer *table = (gpointer *)patch_info->data.table->table;
6473 int k;
6475 encode_value (patch_info->data.table->table_size, p, &p);
6476 for (k = 0; k < patch_info->data.table->table_size; k++)
6477 encode_value ((int)(gssize)table [k], p, &p);
6478 break;
6480 case MONO_PATCH_INFO_METHODCONST:
6481 case MONO_PATCH_INFO_METHOD:
6482 case MONO_PATCH_INFO_METHOD_JUMP:
6483 case MONO_PATCH_INFO_METHOD_FTNDESC:
6484 case MONO_PATCH_INFO_ICALL_ADDR:
6485 case MONO_PATCH_INFO_ICALL_ADDR_CALL:
6486 case MONO_PATCH_INFO_METHOD_RGCTX:
6487 case MONO_PATCH_INFO_METHOD_CODE_SLOT:
6488 encode_method_ref (acfg, patch_info->data.method, p, &p);
6489 break;
6490 case MONO_PATCH_INFO_AOT_JIT_INFO:
6491 case MONO_PATCH_INFO_GET_TLS_TRAMP:
6492 case MONO_PATCH_INFO_SET_TLS_TRAMP:
6493 case MONO_PATCH_INFO_TRAMPOLINE_FUNC_ADDR:
6494 case MONO_PATCH_INFO_CASTCLASS_CACHE:
6495 encode_value (patch_info->data.index, p, &p);
6496 break;
6497 case MONO_PATCH_INFO_JIT_ICALL_ID:
6498 encode_value (patch_info->data.jit_icall_id, p, &p);
6499 break;
6500 case MONO_PATCH_INFO_SPECIFIC_TRAMPOLINE_LAZY_FETCH_ADDR:
6501 encode_value (patch_info->data.uindex, p, &p);
6502 break;
6503 case MONO_PATCH_INFO_LDSTR_LIT:
6504 case MONO_PATCH_INFO_JIT_ICALL_ADDR:
6505 case MONO_PATCH_INFO_JIT_ICALL_ADDR_NOCALL: {
6506 guint32 len = strlen (patch_info->data.name);
6508 encode_value (len, p, &p);
6510 memcpy (p, patch_info->data.name, len + 1);
6511 p += len + 1;
6512 break;
6514 case MONO_PATCH_INFO_LDSTR: {
6515 guint32 image_index = get_image_index (acfg, patch_info->data.token->image);
6516 guint32 token = patch_info->data.token->token;
6517 g_assert (mono_metadata_token_code (token) == MONO_TOKEN_STRING);
6518 encode_value (image_index, p, &p);
6519 encode_value (patch_info->data.token->token - MONO_TOKEN_STRING, p, &p);
6520 break;
6522 case MONO_PATCH_INFO_RVA:
6523 case MONO_PATCH_INFO_DECLSEC:
6524 case MONO_PATCH_INFO_LDTOKEN:
6525 case MONO_PATCH_INFO_TYPE_FROM_HANDLE:
6526 encode_value (get_image_index (acfg, patch_info->data.token->image), p, &p);
6527 encode_value (patch_info->data.token->token, p, &p);
6528 encode_value (patch_info->data.token->has_context, p, &p);
6529 if (patch_info->data.token->has_context)
6530 encode_generic_context (acfg, &patch_info->data.token->context, p, &p);
6531 break;
6532 case MONO_PATCH_INFO_EXC_NAME: {
6533 MonoClass *ex_class;
6535 ex_class =
6536 mono_class_load_from_name (m_class_get_image (mono_defaults.exception_class),
6537 "System", (const char *)patch_info->data.target);
6538 encode_klass_ref (acfg, ex_class, p, &p);
6539 break;
6541 case MONO_PATCH_INFO_R4:
6542 encode_value (*((guint32 *)patch_info->data.target), p, &p);
6543 break;
6544 case MONO_PATCH_INFO_R8:
6545 encode_value (((guint32 *)patch_info->data.target) [MINI_LS_WORD_IDX], p, &p);
6546 encode_value (((guint32 *)patch_info->data.target) [MINI_MS_WORD_IDX], p, &p);
6547 break;
6548 case MONO_PATCH_INFO_VTABLE:
6549 case MONO_PATCH_INFO_CLASS:
6550 case MONO_PATCH_INFO_IID:
6551 case MONO_PATCH_INFO_ADJUSTED_IID:
6552 encode_klass_ref (acfg, patch_info->data.klass, p, &p);
6553 break;
6554 case MONO_PATCH_INFO_DELEGATE_TRAMPOLINE:
6555 encode_klass_ref (acfg, patch_info->data.del_tramp->klass, p, &p);
6556 if (patch_info->data.del_tramp->method) {
6557 encode_value (1, p, &p);
6558 encode_method_ref (acfg, patch_info->data.del_tramp->method, p, &p);
6559 } else {
6560 encode_value (0, p, &p);
6562 encode_value (patch_info->data.del_tramp->is_virtual, p, &p);
6563 break;
6564 case MONO_PATCH_INFO_FIELD:
6565 case MONO_PATCH_INFO_SFLDA:
6566 encode_field_info (acfg, patch_info->data.field, p, &p);
6567 break;
6568 case MONO_PATCH_INFO_INTERRUPTION_REQUEST_FLAG:
6569 break;
6570 case MONO_PATCH_INFO_PROFILER_ALLOCATION_COUNT:
6571 case MONO_PATCH_INFO_PROFILER_CLAUSE_COUNT:
6572 break;
6573 case MONO_PATCH_INFO_RGCTX_FETCH:
6574 case MONO_PATCH_INFO_RGCTX_SLOT_INDEX: {
6575 MonoJumpInfoRgctxEntry *entry = patch_info->data.rgctx_entry;
6576 guint32 offset;
6579 * entry->d.klass/method has a lenghtly encoding and multiple rgctx_fetch entries
6580 * reference the same klass/method, so encode it only once.
6581 * For patches which refer to got entries, this sharing is done by get_got_offset, but
6582 * these are not got entries.
6584 if (entry->in_mrgctx) {
6585 offset = get_shared_method_ref (acfg, entry->d.method);
6586 } else {
6587 offset = get_shared_klass_ref (acfg, entry->d.klass);
6590 encode_value (offset, p, &p);
6591 g_assert ((int)entry->info_type < 256);
6592 g_assert (entry->data->type < 256);
6593 encode_value ((entry->in_mrgctx ? 1 : 0) | (entry->info_type << 1) | (entry->data->type << 9), p, &p);
6594 encode_patch (acfg, entry->data, p, &p);
6595 break;
6597 case MONO_PATCH_INFO_SEQ_POINT_INFO:
6598 case MONO_PATCH_INFO_AOT_MODULE:
6599 break;
6600 case MONO_PATCH_INFO_SIGNATURE:
6601 case MONO_PATCH_INFO_GSHAREDVT_IN_WRAPPER:
6602 encode_signature (acfg, (MonoMethodSignature*)patch_info->data.target, p, &p);
6603 break;
6604 case MONO_PATCH_INFO_GSHAREDVT_CALL:
6605 encode_signature (acfg, (MonoMethodSignature*)patch_info->data.gsharedvt->sig, p, &p);
6606 encode_method_ref (acfg, patch_info->data.gsharedvt->method, p, &p);
6607 break;
6608 case MONO_PATCH_INFO_GSHAREDVT_METHOD: {
6609 MonoGSharedVtMethodInfo *info = patch_info->data.gsharedvt_method;
6610 int i;
6612 encode_method_ref (acfg, info->method, p, &p);
6613 encode_value (info->num_entries, p, &p);
6614 for (i = 0; i < info->num_entries; ++i) {
6615 MonoRuntimeGenericContextInfoTemplate *template_ = &info->entries [i];
6617 encode_value (template_->info_type, p, &p);
6618 switch (mini_rgctx_info_type_to_patch_info_type (template_->info_type)) {
6619 case MONO_PATCH_INFO_CLASS:
6620 encode_klass_ref (acfg, mono_class_from_mono_type_internal ((MonoType *)template_->data), p, &p);
6621 break;
6622 case MONO_PATCH_INFO_FIELD:
6623 encode_field_info (acfg, (MonoClassField *)template_->data, p, &p);
6624 break;
6625 default:
6626 g_assert_not_reached ();
6627 break;
6630 break;
6632 case MONO_PATCH_INFO_VIRT_METHOD:
6633 encode_klass_ref (acfg, patch_info->data.virt_method->klass, p, &p);
6634 encode_method_ref (acfg, patch_info->data.virt_method->method, p, &p);
6635 break;
6636 case MONO_PATCH_INFO_GC_SAFE_POINT_FLAG:
6637 break;
6638 default:
6639 g_warning ("unable to handle jump info %d", patch_info->type);
6640 g_assert_not_reached ();
6643 *endbuf = p;
6646 static void
6647 encode_patch_list (MonoAotCompile *acfg, GPtrArray *patches, int n_patches, gboolean llvm, guint8 *buf, guint8 **endbuf)
6649 guint8 *p = buf;
6650 guint32 pindex, offset;
6651 MonoJumpInfo *patch_info;
6653 encode_value (n_patches, p, &p);
6655 for (pindex = 0; pindex < patches->len; ++pindex) {
6656 patch_info = (MonoJumpInfo *)g_ptr_array_index (patches, pindex);
6658 if (patch_info->type == MONO_PATCH_INFO_NONE || patch_info->type == MONO_PATCH_INFO_BB)
6659 /* Nothing to do */
6660 continue;
6661 /* This shouldn't allocate a new offset */
6662 offset = lookup_got_offset (acfg, llvm, patch_info);
6663 encode_value (offset, p, &p);
6666 *endbuf = p;
6669 static void
6670 emit_method_info (MonoAotCompile *acfg, MonoCompile *cfg)
6672 MonoMethod *method;
6673 int pindex, buf_size, n_patches;
6674 GPtrArray *patches;
6675 MonoJumpInfo *patch_info;
6676 guint8 *p, *buf;
6677 guint32 offset;
6678 gboolean needs_ctx = FALSE;
6680 method = cfg->orig_method;
6682 (void)get_method_index (acfg, method);
6684 /* Sort relocations */
6685 patches = g_ptr_array_new ();
6686 for (patch_info = cfg->patch_info; patch_info; patch_info = patch_info->next)
6687 g_ptr_array_add (patches, patch_info);
6688 if (!acfg->aot_opts.llvm_only)
6689 g_ptr_array_sort (patches, compare_patches);
6691 /**********************/
6692 /* Encode method info */
6693 /**********************/
6695 g_assert (!(cfg->opt & MONO_OPT_SHARED));
6697 guint32 *got_offsets = g_new0 (guint32, patches->len);
6699 n_patches = 0;
6700 for (pindex = 0; pindex < patches->len; ++pindex) {
6701 patch_info = (MonoJumpInfo *)g_ptr_array_index (patches, pindex);
6703 if ((patch_info->type == MONO_PATCH_INFO_GOT_OFFSET) ||
6704 (patch_info->type == MONO_PATCH_INFO_NONE)) {
6705 patch_info->type = MONO_PATCH_INFO_NONE;
6706 /* Nothing to do */
6707 continue;
6710 if ((patch_info->type == MONO_PATCH_INFO_IMAGE) && (patch_info->data.image == acfg->image)) {
6711 /* Stored in a GOT slot initialized at module load time */
6712 patch_info->type = MONO_PATCH_INFO_NONE;
6713 continue;
6716 if (patch_info->type == MONO_PATCH_INFO_GC_CARD_TABLE_ADDR ||
6717 patch_info->type == MONO_PATCH_INFO_GC_NURSERY_START ||
6718 patch_info->type == MONO_PATCH_INFO_GC_NURSERY_BITS ||
6719 patch_info->type == MONO_PATCH_INFO_AOT_MODULE) {
6720 /* Stored in a GOT slot initialized at module load time */
6721 patch_info->type = MONO_PATCH_INFO_NONE;
6722 continue;
6725 if (is_plt_patch (patch_info) && !(cfg->compile_llvm && acfg->aot_opts.llvm_only)) {
6726 /* Calls are made through the PLT */
6727 patch_info->type = MONO_PATCH_INFO_NONE;
6728 continue;
6731 if (acfg->aot_opts.llvm_only && patch_info->type == MONO_PATCH_INFO_METHOD)
6732 needs_ctx = TRUE;
6734 /* This shouldn't allocate a new offset */
6735 offset = lookup_got_offset (acfg, cfg->compile_llvm, patch_info);
6736 if (offset >= acfg->nshared_got_entries)
6737 got_offsets [n_patches ++] = offset;
6740 if (n_patches)
6741 g_assert (cfg->has_got_slots);
6743 buf_size = (patches->len < 1000) ? 40960 : 40960 + (patches->len * 64);
6744 p = buf = (guint8 *)g_malloc (buf_size);
6746 MonoGenericContext *ctx = mono_method_get_context (cfg->method);
6748 guint8 flags = 0;
6749 if (mono_class_get_cctor (method->klass))
6750 flags |= MONO_AOT_METHOD_FLAG_HAS_CCTOR;
6751 if (mini_jit_info_is_gsharedvt (cfg->jit_info) && mini_is_gsharedvt_variable_signature (mono_method_signature_internal (jinfo_get_method (cfg->jit_info))))
6752 flags |= MONO_AOT_METHOD_FLAG_GSHAREDVT_VARIABLE;
6753 if (n_patches)
6754 flags |= MONO_AOT_METHOD_FLAG_HAS_PATCHES;
6755 if (needs_ctx && ctx)
6756 flags |= MONO_AOT_METHOD_FLAG_HAS_CTX;
6757 encode_value (flags, p, &p);
6758 if (flags & MONO_AOT_METHOD_FLAG_HAS_CCTOR)
6759 encode_klass_ref (acfg, method->klass, p, &p);
6760 if (needs_ctx && ctx)
6761 encode_generic_context (acfg, ctx, p, &p);
6763 if (n_patches) {
6764 encode_value (n_patches, p, &p);
6765 for (int i = 0; i < n_patches; ++i)
6766 encode_value (got_offsets [i], p, &p);
6769 g_ptr_array_free (patches, TRUE);
6770 g_free (got_offsets);
6772 acfg->stats.method_info_size += p - buf;
6774 g_assert (p - buf < buf_size);
6776 cfg->method_info_offset = add_to_blob (acfg, buf, p - buf);
6777 g_free (buf);
6780 static guint32
6781 get_unwind_info_offset (MonoAotCompile *acfg, guint8 *encoded, guint32 encoded_len)
6783 guint32 cache_index;
6784 guint32 offset;
6786 /* Reuse the unwind module to canonize and store unwind info entries */
6787 cache_index = mono_cache_unwind_info (encoded, encoded_len);
6789 /* Use +/- 1 to distinguish 0s from missing entries */
6790 offset = GPOINTER_TO_UINT (g_hash_table_lookup (acfg->unwind_info_offsets, GUINT_TO_POINTER (cache_index + 1)));
6791 if (offset)
6792 return offset - 1;
6793 else {
6794 guint8 buf [16];
6795 guint8 *p;
6798 * It would be easier to use assembler symbols, but the caller needs an
6799 * offset now.
6801 offset = acfg->unwind_info_offset;
6802 g_hash_table_insert (acfg->unwind_info_offsets, GUINT_TO_POINTER (cache_index + 1), GUINT_TO_POINTER (offset + 1));
6803 g_ptr_array_add (acfg->unwind_ops, GUINT_TO_POINTER (cache_index));
6805 p = buf;
6806 encode_value (encoded_len, p, &p);
6808 acfg->unwind_info_offset += encoded_len + (p - buf);
6809 return offset;
6813 static void
6814 emit_exception_debug_info (MonoAotCompile *acfg, MonoCompile *cfg, gboolean store_seq_points)
6816 int i, k, buf_size;
6817 guint32 debug_info_size, seq_points_size;
6818 guint8 *code;
6819 MonoMethodHeader *header;
6820 guint8 *p, *buf, *debug_info;
6821 MonoJitInfo *jinfo = cfg->jit_info;
6822 guint32 flags;
6823 gboolean use_unwind_ops = FALSE;
6824 MonoSeqPointInfo *seq_points;
6826 code = cfg->native_code;
6827 header = cfg->header;
6829 if (!acfg->aot_opts.nodebug) {
6830 mono_debug_serialize_debug_info (cfg, &debug_info, &debug_info_size);
6831 } else {
6832 debug_info = NULL;
6833 debug_info_size = 0;
6836 seq_points = cfg->seq_point_info;
6837 seq_points_size = (store_seq_points)? mono_seq_point_info_get_write_size (seq_points) : 0;
6839 buf_size = header->num_clauses * 256 + debug_info_size + 2048 + seq_points_size + cfg->gc_map_size;
6840 if (jinfo->has_try_block_holes) {
6841 MonoTryBlockHoleTableJitInfo *table = mono_jit_info_get_try_block_hole_table_info (jinfo);
6842 buf_size += table->num_holes * 16;
6845 p = buf = (guint8 *)g_malloc (buf_size);
6847 use_unwind_ops = cfg->unwind_ops != NULL;
6849 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);
6851 encode_value (flags, p, &p);
6853 if (use_unwind_ops) {
6854 guint32 encoded_len;
6855 guint8 *encoded;
6856 guint32 unwind_desc;
6858 encoded = mono_unwind_ops_encode (cfg->unwind_ops, &encoded_len);
6860 unwind_desc = get_unwind_info_offset (acfg, encoded, encoded_len);
6861 encode_value (unwind_desc, p, &p);
6863 g_free (encoded);
6864 } else {
6865 encode_value (jinfo->unwind_info, p, &p);
6868 /*Encode the number of holes before the number of clauses to make decoding easier*/
6869 if (jinfo->has_try_block_holes) {
6870 MonoTryBlockHoleTableJitInfo *table = mono_jit_info_get_try_block_hole_table_info (jinfo);
6871 encode_value (table->num_holes, p, &p);
6874 if (jinfo->has_arch_eh_info) {
6876 * In AOT mode, the code length is calculated from the address of the previous method,
6877 * which could include alignment padding, so calculating the start of the epilog as
6878 * code_len - epilog_size is correct any more. Save the real code len as a workaround.
6880 encode_value (jinfo->code_size, p, &p);
6883 /* Exception table */
6884 if (cfg->compile_llvm) {
6886 * When using LLVM, we can't emit some data, like pc offsets, this reg/offset etc.,
6887 * since the information is only available to llc. Instead, we let llc save the data
6888 * into the LSDA, and read it from there at runtime.
6890 /* The assembly might be CIL stripped so emit the data ourselves */
6891 if (header->num_clauses)
6892 encode_value (header->num_clauses, p, &p);
6894 for (k = 0; k < header->num_clauses; ++k) {
6895 MonoExceptionClause *clause;
6897 clause = &header->clauses [k];
6899 encode_value (clause->flags, p, &p);
6900 if (!(clause->flags == MONO_EXCEPTION_CLAUSE_FILTER || clause->flags == MONO_EXCEPTION_CLAUSE_FINALLY)) {
6901 if (clause->data.catch_class) {
6902 guint8 *buf2, *p2;
6903 int len;
6905 buf2 = (guint8 *)g_malloc (4096);
6906 p2 = buf2;
6907 encode_klass_ref (acfg, clause->data.catch_class, p2, &p2);
6908 len = p2 - buf2;
6909 g_assert (len < 4096);
6910 encode_value (len, p, &p);
6911 memcpy (p, buf2, len);
6912 p += p2 - buf2;
6913 g_free (buf2);
6914 } else {
6915 encode_value (0, p, &p);
6919 /* Emit the IL ranges too, since they might not be available at runtime */
6920 encode_value (clause->try_offset, p, &p);
6921 encode_value (clause->try_len, p, &p);
6922 encode_value (clause->handler_offset, p, &p);
6923 encode_value (clause->handler_len, p, &p);
6925 /* Emit a list of nesting clauses */
6926 for (i = 0; i < header->num_clauses; ++i) {
6927 gint32 cindex1 = k;
6928 MonoExceptionClause *clause1 = &header->clauses [cindex1];
6929 gint32 cindex2 = i;
6930 MonoExceptionClause *clause2 = &header->clauses [cindex2];
6932 if (cindex1 != cindex2 && clause1->try_offset >= clause2->try_offset && clause1->handler_offset <= clause2->handler_offset)
6933 encode_value (i, p, &p);
6935 encode_value (-1, p, &p);
6937 } else {
6938 if (jinfo->num_clauses)
6939 encode_value (jinfo->num_clauses, p, &p);
6941 for (k = 0; k < jinfo->num_clauses; ++k) {
6942 MonoJitExceptionInfo *ei = &jinfo->clauses [k];
6944 encode_value (ei->flags, p, &p);
6945 #ifdef MONO_CONTEXT_SET_LLVM_EXC_REG
6946 /* Not used for catch clauses */
6947 if (ei->flags != MONO_EXCEPTION_CLAUSE_NONE)
6948 encode_value (ei->exvar_offset, p, &p);
6949 #else
6950 encode_value (ei->exvar_offset, p, &p);
6951 #endif
6953 if (ei->flags == MONO_EXCEPTION_CLAUSE_FILTER || ei->flags == MONO_EXCEPTION_CLAUSE_FINALLY)
6954 encode_value ((gint)((guint8*)ei->data.filter - code), p, &p);
6955 else {
6956 if (ei->data.catch_class) {
6957 guint8 *buf2, *p2;
6958 int len;
6960 buf2 = (guint8 *)g_malloc (4096);
6961 p2 = buf2;
6962 encode_klass_ref (acfg, ei->data.catch_class, p2, &p2);
6963 len = p2 - buf2;
6964 g_assert (len < 4096);
6965 encode_value (len, p, &p);
6966 memcpy (p, buf2, len);
6967 p += p2 - buf2;
6968 g_free (buf2);
6969 } else {
6970 encode_value (0, p, &p);
6974 encode_value ((gint)((guint8*)ei->try_start - code), p, &p);
6975 encode_value ((gint)((guint8*)ei->try_end - code), p, &p);
6976 encode_value ((gint)((guint8*)ei->handler_start - code), p, &p);
6980 if (jinfo->has_try_block_holes) {
6981 MonoTryBlockHoleTableJitInfo *table = mono_jit_info_get_try_block_hole_table_info (jinfo);
6982 for (i = 0; i < table->num_holes; ++i) {
6983 MonoTryBlockHoleJitInfo *hole = &table->holes [i];
6984 encode_value (hole->clause, p, &p);
6985 encode_value (hole->length, p, &p);
6986 encode_value (hole->offset, p, &p);
6990 if (jinfo->has_arch_eh_info) {
6991 MonoArchEHJitInfo *eh_info;
6993 eh_info = mono_jit_info_get_arch_eh_info (jinfo);
6994 encode_value (eh_info->stack_size, p, &p);
6995 encode_value (eh_info->epilog_size, p, &p);
6998 if (jinfo->has_generic_jit_info) {
6999 MonoGenericJitInfo *gi = mono_jit_info_get_generic_jit_info (jinfo);
7000 MonoGenericSharingContext* gsctx = gi->generic_sharing_context;
7001 guint8 *buf2, *p2;
7002 int len;
7004 encode_value (gi->nlocs, p, &p);
7005 if (gi->nlocs) {
7006 for (i = 0; i < gi->nlocs; ++i) {
7007 MonoDwarfLocListEntry *entry = &gi->locations [i];
7009 encode_value (entry->is_reg ? 1 : 0, p, &p);
7010 encode_value (entry->reg, p, &p);
7011 if (!entry->is_reg)
7012 encode_value (entry->offset, p, &p);
7013 if (i == 0)
7014 g_assert (entry->from == 0);
7015 else
7016 encode_value (entry->from, p, &p);
7017 encode_value (entry->to, p, &p);
7019 } else {
7020 if (!cfg->compile_llvm) {
7021 encode_value (gi->has_this ? 1 : 0, p, &p);
7022 encode_value (gi->this_reg, p, &p);
7023 encode_value (gi->this_offset, p, &p);
7028 * Need to encode jinfo->method too, since it is not equal to 'method'
7029 * when using generic sharing.
7031 buf2 = (guint8 *)g_malloc (4096);
7032 p2 = buf2;
7033 encode_method_ref (acfg, jinfo->d.method, p2, &p2);
7034 len = p2 - buf2;
7035 g_assert (len < 4096);
7036 encode_value (len, p, &p);
7037 memcpy (p, buf2, len);
7038 p += p2 - buf2;
7039 g_free (buf2);
7041 if (gsctx && gsctx->is_gsharedvt) {
7042 encode_value (1, p, &p);
7043 } else {
7044 encode_value (0, p, &p);
7048 if (seq_points_size)
7049 p += mono_seq_point_info_write (seq_points, p);
7051 g_assert (debug_info_size < buf_size);
7053 encode_value (debug_info_size, p, &p);
7054 if (debug_info_size) {
7055 memcpy (p, debug_info, debug_info_size);
7056 p += debug_info_size;
7057 g_free (debug_info);
7060 /* GC Map */
7061 if (cfg->gc_map) {
7062 encode_value (cfg->gc_map_size, p, &p);
7063 /* The GC map requires 4 bytes of alignment */
7064 while ((gsize)p % 4)
7065 p ++;
7066 memcpy (p, cfg->gc_map, cfg->gc_map_size);
7067 p += cfg->gc_map_size;
7070 acfg->stats.ex_info_size += p - buf;
7072 g_assert (p - buf < buf_size);
7074 /* Emit info */
7075 /* The GC Map requires 4 byte alignment */
7076 cfg->ex_info_offset = add_to_blob_aligned (acfg, buf, p - buf, cfg->gc_map ? 4 : 1);
7077 g_free (buf);
7080 static guint32
7081 emit_klass_info (MonoAotCompile *acfg, guint32 token)
7083 ERROR_DECL (error);
7084 MonoClass *klass = mono_class_get_checked (acfg->image, token, error);
7085 guint8 *p, *buf;
7086 int i, buf_size, res;
7087 gboolean no_special_static, cant_encode;
7088 gpointer iter = NULL;
7090 if (!klass) {
7091 mono_error_cleanup (error);
7093 buf_size = 16;
7095 p = buf = (guint8 *)g_malloc (buf_size);
7097 /* Mark as unusable */
7098 encode_value (-1, p, &p);
7100 res = add_to_blob (acfg, buf, p - buf);
7101 g_free (buf);
7103 return res;
7106 buf_size = 10240 + (m_class_get_vtable_size (klass) * 16);
7107 p = buf = (guint8 *)g_malloc (buf_size);
7109 g_assert (klass);
7111 mono_class_init_internal (klass);
7113 mono_class_get_nested_types (klass, &iter);
7114 g_assert (m_class_is_nested_classes_inited (klass));
7116 mono_class_setup_vtable (klass);
7119 * Emit all the information which is required for creating vtables so
7120 * the runtime does not need to create the MonoMethod structures which
7121 * take up a lot of space.
7124 no_special_static = !mono_class_has_special_static_fields (klass);
7126 /* Check whenever we have enough info to encode the vtable */
7127 cant_encode = FALSE;
7128 MonoMethod **klass_vtable = m_class_get_vtable (klass);
7129 for (i = 0; i < m_class_get_vtable_size (klass); ++i) {
7130 MonoMethod *cm = klass_vtable [i];
7132 if (cm && mono_method_signature_internal (cm)->is_inflated && !g_hash_table_lookup (acfg->token_info_hash, cm))
7133 cant_encode = TRUE;
7136 mono_class_has_finalizer (klass);
7137 if (mono_class_has_failure (klass))
7138 cant_encode = TRUE;
7140 if (mono_class_is_gtd (klass) || cant_encode) {
7141 encode_value (-1, p, &p);
7142 } else {
7143 gboolean has_nested = mono_class_get_nested_classes_property (klass) != NULL;
7144 encode_value (m_class_get_vtable_size (klass), p, &p);
7145 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);
7146 if (m_class_has_cctor (klass))
7147 encode_method_ref (acfg, mono_class_get_cctor (klass), p, &p);
7148 if (m_class_has_finalize (klass))
7149 encode_method_ref (acfg, mono_class_get_finalizer (klass), p, &p);
7151 encode_value (m_class_get_instance_size (klass), p, &p);
7152 encode_value (mono_class_data_size (klass), p, &p);
7153 encode_value (m_class_get_packing_size (klass), p, &p);
7154 encode_value (m_class_get_min_align (klass), p, &p);
7156 for (i = 0; i < m_class_get_vtable_size (klass); ++i) {
7157 MonoMethod *cm = klass_vtable [i];
7159 if (cm)
7160 encode_method_ref (acfg, cm, p, &p);
7161 else
7162 encode_value (0, p, &p);
7166 acfg->stats.class_info_size += p - buf;
7168 g_assert (p - buf < buf_size);
7169 res = add_to_blob (acfg, buf, p - buf);
7170 g_free (buf);
7172 return res;
7175 static char*
7176 get_plt_entry_debug_sym (MonoAotCompile *acfg, MonoJumpInfo *ji, GHashTable *cache)
7178 char *debug_sym = NULL;
7179 char *prefix;
7181 if (acfg->llvm && llvm_acfg->aot_opts.static_link) {
7182 /* Need to add a prefix to create unique symbols */
7183 prefix = g_strdup_printf ("plt_%s_", acfg->assembly_name_sym);
7184 } else {
7185 #if defined(TARGET_WIN32) && defined(TARGET_X86)
7186 prefix = mangle_symbol_alloc ("plt_");
7187 #else
7188 prefix = g_strdup ("plt_");
7189 #endif
7192 switch (ji->type) {
7193 case MONO_PATCH_INFO_METHOD:
7194 debug_sym = get_debug_sym (ji->data.method, prefix, cache);
7195 break;
7196 case MONO_PATCH_INFO_JIT_ICALL_ID:
7197 debug_sym = g_strdup_printf ("%s_jit_icall_%s", prefix, mono_find_jit_icall_info (ji->data.jit_icall_id)->name);
7198 break;
7199 case MONO_PATCH_INFO_RGCTX_FETCH:
7200 debug_sym = g_strdup_printf ("%s_rgctx_fetch_%d", prefix, acfg->label_generator ++);
7201 break;
7202 case MONO_PATCH_INFO_ICALL_ADDR:
7203 case MONO_PATCH_INFO_ICALL_ADDR_CALL: {
7204 char *s = get_debug_sym (ji->data.method, "", cache);
7206 debug_sym = g_strdup_printf ("%s_icall_native_%s", prefix, s);
7207 g_free (s);
7208 break;
7210 case MONO_PATCH_INFO_TRAMPOLINE_FUNC_ADDR:
7211 debug_sym = g_strdup_printf ("%s_jit_icall_native_trampoline_func_%d", prefix, ji->data.index);
7212 break;
7213 case MONO_PATCH_INFO_SPECIFIC_TRAMPOLINE_LAZY_FETCH_ADDR:
7214 debug_sym = g_strdup_printf ("%s_jit_icall_native_specific_trampoline_lazy_fetch_%u", prefix, ji->data.uindex);
7215 break;
7216 case MONO_PATCH_INFO_JIT_ICALL_ADDR:
7217 debug_sym = g_strdup_printf ("%s_jit_icall_native_%s", prefix, ji->data.name);
7218 break;
7219 default:
7220 break;
7223 g_free (prefix);
7225 return sanitize_symbol (acfg, debug_sym);
7229 * Calls made from AOTed code are routed through a table of jumps similar to the
7230 * ELF PLT (Program Linkage Table). Initially the PLT entries jump to code which transfers
7231 * control to the AOT runtime through a trampoline.
7233 static void
7234 emit_plt (MonoAotCompile *acfg)
7236 int i;
7238 if (acfg->aot_opts.llvm_only) {
7239 g_assert (acfg->plt_offset == 1);
7240 return;
7243 emit_line (acfg);
7245 emit_section_change (acfg, ".text", 0);
7246 emit_alignment_code (acfg, 16);
7247 emit_info_symbol (acfg, "plt", TRUE);
7248 emit_label (acfg, acfg->plt_symbol);
7250 for (i = 0; i < acfg->plt_offset; ++i) {
7251 char *debug_sym = NULL;
7252 MonoPltEntry *plt_entry = NULL;
7254 if (i == 0)
7256 * The first plt entry is unused.
7258 continue;
7260 plt_entry = (MonoPltEntry *)g_hash_table_lookup (acfg->plt_offset_to_entry, GUINT_TO_POINTER (i));
7262 debug_sym = plt_entry->debug_sym;
7264 if (acfg->thumb_mixed && !plt_entry->jit_used)
7265 /* Emit only a thumb version */
7266 continue;
7268 /* Skip plt entries not actually called */
7269 if (!plt_entry->jit_used && !plt_entry->llvm_used)
7270 continue;
7272 if (acfg->llvm && !acfg->thumb_mixed) {
7273 emit_label (acfg, plt_entry->llvm_symbol);
7274 if (acfg->llvm) {
7275 emit_global_inner (acfg, plt_entry->llvm_symbol, TRUE);
7276 #if defined(TARGET_MACH)
7277 fprintf (acfg->fp, ".private_extern %s\n", plt_entry->llvm_symbol);
7278 #endif
7282 if (debug_sym) {
7283 if (acfg->need_no_dead_strip) {
7284 emit_unset_mode (acfg);
7285 fprintf (acfg->fp, " .no_dead_strip %s\n", debug_sym);
7287 emit_local_symbol (acfg, debug_sym, NULL, TRUE);
7288 emit_label (acfg, debug_sym);
7291 emit_label (acfg, plt_entry->symbol);
7293 arch_emit_plt_entry (acfg, acfg->got_symbol, (acfg->plt_got_offset_base + i) * sizeof (target_mgreg_t), acfg->plt_got_info_offsets [i]);
7295 if (debug_sym)
7296 emit_symbol_size (acfg, debug_sym, ".");
7299 if (acfg->thumb_mixed) {
7300 /* Make sure the ARM symbols don't alias the thumb ones */
7301 emit_zero_bytes (acfg, 16);
7304 * Emit a separate set of PLT entries using thumb2 which is called by LLVM generated
7305 * code.
7307 for (i = 0; i < acfg->plt_offset; ++i) {
7308 char *debug_sym = NULL;
7309 MonoPltEntry *plt_entry = NULL;
7311 if (i == 0)
7312 continue;
7314 plt_entry = (MonoPltEntry *)g_hash_table_lookup (acfg->plt_offset_to_entry, GUINT_TO_POINTER (i));
7316 /* Skip plt entries not actually called by LLVM code */
7317 if (!plt_entry->llvm_used)
7318 continue;
7320 if (acfg->aot_opts.write_symbols) {
7321 if (plt_entry->debug_sym)
7322 debug_sym = g_strdup_printf ("%s_thumb", plt_entry->debug_sym);
7325 if (debug_sym) {
7326 #if defined(TARGET_MACH)
7327 fprintf (acfg->fp, " .thumb_func %s\n", debug_sym);
7328 fprintf (acfg->fp, " .no_dead_strip %s\n", debug_sym);
7329 #endif
7330 emit_local_symbol (acfg, debug_sym, NULL, TRUE);
7331 emit_label (acfg, debug_sym);
7333 fprintf (acfg->fp, "\n.thumb_func\n");
7335 emit_label (acfg, plt_entry->llvm_symbol);
7337 if (acfg->llvm)
7338 emit_global_inner (acfg, plt_entry->llvm_symbol, TRUE);
7340 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]);
7342 if (debug_sym) {
7343 emit_symbol_size (acfg, debug_sym, ".");
7344 g_free (debug_sym);
7349 emit_symbol_size (acfg, acfg->plt_symbol, ".");
7351 emit_info_symbol (acfg, "plt_end", TRUE);
7353 arch_emit_unwind_info_sections (acfg, "plt", "plt_end", NULL);
7357 * emit_trampoline_full:
7359 * If EMIT_TINFO is TRUE, emit additional information which can be used to create a MonoJitInfo for this trampoline by
7360 * create_jit_info_for_trampoline ().
7362 static G_GNUC_UNUSED void
7363 emit_trampoline_full (MonoAotCompile *acfg, MonoTrampInfo *info, gboolean emit_tinfo)
7365 char start_symbol [MAX_SYMBOL_SIZE];
7366 char end_symbol [MAX_SYMBOL_SIZE];
7367 char symbol [MAX_SYMBOL_SIZE];
7368 guint32 buf_size, info_offset;
7369 MonoJumpInfo *patch_info;
7370 guint8 *buf, *p;
7371 GPtrArray *patches;
7372 char *name;
7373 guint8 *code;
7374 guint32 code_size;
7375 MonoJumpInfo *ji;
7376 GSList *unwind_ops;
7378 g_assert (info);
7380 name = info->name;
7381 code = info->code;
7382 code_size = info->code_size;
7383 ji = info->ji;
7384 unwind_ops = info->unwind_ops;
7386 /* Emit code */
7388 sprintf (start_symbol, "%s%s", acfg->user_symbol_prefix, name);
7390 emit_section_change (acfg, ".text", 0);
7391 emit_global (acfg, start_symbol, TRUE);
7392 emit_alignment_code (acfg, AOT_FUNC_ALIGNMENT);
7393 emit_label (acfg, start_symbol);
7395 sprintf (symbol, "%snamed_%s", acfg->temp_prefix, name);
7396 emit_label (acfg, symbol);
7399 * The code should access everything through the GOT, so we pass
7400 * TRUE here.
7402 emit_and_reloc_code (acfg, NULL, code, code_size, ji, TRUE, NULL);
7404 emit_symbol_size (acfg, start_symbol, ".");
7406 if (emit_tinfo) {
7407 sprintf (end_symbol, "%snamede_%s", acfg->temp_prefix, name);
7408 emit_label (acfg, end_symbol);
7411 /* Emit info */
7413 /* Sort relocations */
7414 patches = g_ptr_array_new ();
7415 for (patch_info = ji; patch_info; patch_info = patch_info->next)
7416 if (patch_info->type != MONO_PATCH_INFO_NONE)
7417 g_ptr_array_add (patches, patch_info);
7418 g_ptr_array_sort (patches, compare_patches);
7420 buf_size = patches->len * 128 + 128;
7421 buf = (guint8 *)g_malloc (buf_size);
7422 p = buf;
7424 encode_patch_list (acfg, patches, patches->len, FALSE, p, &p);
7425 g_assert (p - buf < buf_size);
7426 g_ptr_array_free (patches, TRUE);
7428 sprintf (symbol, "%s%s_p", acfg->user_symbol_prefix, name);
7430 info_offset = add_to_blob (acfg, buf, p - buf);
7432 emit_section_change (acfg, RODATA_SECT, 0);
7433 emit_global (acfg, symbol, FALSE);
7434 emit_label (acfg, symbol);
7436 emit_int32 (acfg, info_offset);
7438 if (emit_tinfo) {
7439 guint8 *encoded;
7440 guint32 encoded_len;
7441 guint32 uw_offset;
7444 * Emit additional information which can be used to reconstruct a partial MonoTrampInfo.
7446 encoded = mono_unwind_ops_encode (info->unwind_ops, &encoded_len);
7447 uw_offset = get_unwind_info_offset (acfg, encoded, encoded_len);
7448 g_free (encoded);
7450 emit_symbol_diff (acfg, end_symbol, start_symbol, 0);
7451 emit_int32 (acfg, uw_offset);
7454 /* Emit debug info */
7455 if (unwind_ops) {
7456 char symbol2 [MAX_SYMBOL_SIZE];
7458 sprintf (symbol, "%s", name);
7459 sprintf (symbol2, "%snamed_%s", acfg->temp_prefix, name);
7461 arch_emit_unwind_info_sections (acfg, start_symbol, end_symbol, unwind_ops);
7463 if (acfg->dwarf)
7464 mono_dwarf_writer_emit_trampoline (acfg->dwarf, symbol, symbol2, NULL, NULL, code_size, unwind_ops);
7467 g_free (buf);
7470 static G_GNUC_UNUSED void
7471 emit_trampoline (MonoAotCompile *acfg, MonoTrampInfo *info)
7473 emit_trampoline_full (acfg, info, TRUE);
7476 static void
7477 emit_trampolines (MonoAotCompile *acfg)
7479 char symbol [MAX_SYMBOL_SIZE];
7480 char end_symbol [MAX_SYMBOL_SIZE];
7481 int i, tramp_got_offset;
7482 int ntype;
7483 #ifdef MONO_ARCH_HAVE_FULL_AOT_TRAMPOLINES
7484 int tramp_type;
7485 #endif
7487 if (!mono_aot_mode_is_full (&acfg->aot_opts) && !mono_aot_mode_is_interp (&acfg->aot_opts))
7488 return;
7489 if (acfg->aot_opts.llvm_only)
7490 return;
7492 g_assert (acfg->image->assembly);
7494 /* Currently, we emit most trampolines into the mscorlib AOT image. */
7495 if (mono_is_corlib_image(acfg->image->assembly->image)) {
7496 #ifdef MONO_ARCH_HAVE_FULL_AOT_TRAMPOLINES
7497 MonoTrampInfo *info;
7500 * Emit the generic trampolines.
7502 * We could save some code by treating the generic trampolines as a wrapper
7503 * method, but that approach has its own complexities, so we choose the simpler
7504 * method.
7506 for (tramp_type = 0; tramp_type < MONO_TRAMPOLINE_NUM; ++tramp_type) {
7507 /* we overload the boolean here to indicate the slightly different trampoline needed, see mono_arch_create_generic_trampoline() */
7508 #ifdef DISABLE_REMOTING
7509 if (tramp_type == MONO_TRAMPOLINE_GENERIC_VIRTUAL_REMOTING)
7510 continue;
7511 #endif
7512 mono_arch_create_generic_trampoline ((MonoTrampolineType)tramp_type, &info, acfg->aot_opts.use_trampolines_page? 2: TRUE);
7513 emit_trampoline (acfg, info);
7514 mono_tramp_info_free (info);
7517 /* Emit the exception related code pieces */
7518 mono_arch_get_restore_context (&info, TRUE);
7519 emit_trampoline (acfg, info);
7520 mono_tramp_info_free (info);
7522 mono_arch_get_call_filter (&info, TRUE);
7523 emit_trampoline (acfg, info);
7524 mono_tramp_info_free (info);
7526 mono_arch_get_throw_exception (&info, TRUE);
7527 emit_trampoline (acfg, info);
7528 mono_tramp_info_free (info);
7530 mono_arch_get_rethrow_exception (&info, TRUE);
7531 emit_trampoline (acfg, info);
7532 mono_tramp_info_free (info);
7534 mono_arch_get_rethrow_preserve_exception (&info, TRUE);
7535 emit_trampoline (acfg, info);
7536 mono_tramp_info_free (info);
7538 mono_arch_get_throw_corlib_exception (&info, TRUE);
7539 emit_trampoline (acfg, info);
7540 mono_tramp_info_free (info);
7542 #ifdef MONO_ARCH_HAVE_SDB_TRAMPOLINES
7543 mono_arch_create_sdb_trampoline (TRUE, &info, TRUE);
7544 emit_trampoline (acfg, info);
7545 mono_tramp_info_free (info);
7547 mono_arch_create_sdb_trampoline (FALSE, &info, TRUE);
7548 emit_trampoline (acfg, info);
7549 mono_tramp_info_free (info);
7550 #endif
7552 #ifdef MONO_ARCH_GSHAREDVT_SUPPORTED
7553 mono_arch_get_gsharedvt_trampoline (&info, TRUE);
7554 if (info) {
7555 emit_trampoline_full (acfg, info, TRUE);
7557 /* Create a separate out trampoline for more information in stack traces */
7558 info->name = g_strdup ("gsharedvt_out_trampoline");
7559 emit_trampoline_full (acfg, info, TRUE);
7560 mono_tramp_info_free (info);
7562 #endif
7564 #if defined(MONO_ARCH_HAVE_GET_TRAMPOLINES)
7566 GSList *l = mono_arch_get_trampolines (TRUE);
7568 while (l) {
7569 MonoTrampInfo *info = (MonoTrampInfo *)l->data;
7571 emit_trampoline (acfg, info);
7572 l = l->next;
7575 #endif
7577 for (i = 0; i < acfg->aot_opts.nrgctx_fetch_trampolines; ++i) {
7578 int offset;
7580 offset = MONO_RGCTX_SLOT_MAKE_RGCTX (i);
7581 mono_arch_create_rgctx_lazy_fetch_trampoline (offset, &info, TRUE);
7582 emit_trampoline (acfg, info);
7583 mono_tramp_info_free (info);
7585 offset = MONO_RGCTX_SLOT_MAKE_MRGCTX (i);
7586 mono_arch_create_rgctx_lazy_fetch_trampoline (offset, &info, TRUE);
7587 emit_trampoline (acfg, info);
7588 mono_tramp_info_free (info);
7591 #ifdef MONO_ARCH_HAVE_GENERAL_RGCTX_LAZY_FETCH_TRAMPOLINE
7592 mono_arch_create_general_rgctx_lazy_fetch_trampoline (&info, TRUE);
7593 emit_trampoline (acfg, info);
7594 mono_tramp_info_free (info);
7595 #endif
7598 GSList *l;
7600 /* delegate_invoke_impl trampolines */
7601 l = mono_arch_get_delegate_invoke_impls ();
7602 while (l) {
7603 MonoTrampInfo *info = (MonoTrampInfo *)l->data;
7605 emit_trampoline (acfg, info);
7606 l = l->next;
7610 if (mono_aot_mode_is_interp (&acfg->aot_opts) && mono_is_corlib_image (acfg->image->assembly->image)) {
7611 mono_arch_get_interp_to_native_trampoline (&info);
7612 emit_trampoline (acfg, info);
7614 #ifdef MONO_ARCH_HAVE_INTERP_ENTRY_TRAMPOLINE
7615 mono_arch_get_native_to_interp_trampoline (&info);
7616 emit_trampoline (acfg, info);
7617 #endif
7620 #endif /* #ifdef MONO_ARCH_HAVE_FULL_AOT_TRAMPOLINES */
7622 /* Emit trampolines which are numerous */
7625 * These include the following:
7626 * - specific trampolines
7627 * - static rgctx invoke trampolines
7628 * - imt trampolines
7629 * These trampolines have the same code, they are parameterized by GOT
7630 * slots.
7631 * They are defined in this file, in the arch_... routines instead of
7632 * in tramp-<ARCH>.c, since it is easier to do it this way.
7636 * When running in aot-only mode, we can't create specific trampolines at
7637 * runtime, so we create a few, and save them in the AOT file.
7638 * Normal trampolines embed their argument as a literal inside the
7639 * trampoline code, we can't do that here, so instead we embed an offset
7640 * which needs to be added to the trampoline address to get the address of
7641 * the GOT slot which contains the argument value.
7642 * The generated trampolines jump to the generic trampolines using another
7643 * GOT slot, which will be setup by the AOT loader to point to the
7644 * generic trampoline code of the given type.
7648 * FIXME: Maybe we should use more specific trampolines (i.e. one class init for
7649 * each class).
7652 emit_section_change (acfg, ".text", 0);
7654 tramp_got_offset = acfg->got_offset;
7656 for (ntype = 0; ntype < MONO_AOT_TRAMP_NUM; ++ntype) {
7657 switch (ntype) {
7658 case MONO_AOT_TRAMP_SPECIFIC:
7659 sprintf (symbol, "specific_trampolines");
7660 break;
7661 case MONO_AOT_TRAMP_STATIC_RGCTX:
7662 sprintf (symbol, "static_rgctx_trampolines");
7663 break;
7664 case MONO_AOT_TRAMP_IMT:
7665 sprintf (symbol, "imt_trampolines");
7666 break;
7667 case MONO_AOT_TRAMP_GSHAREDVT_ARG:
7668 sprintf (symbol, "gsharedvt_arg_trampolines");
7669 break;
7670 case MONO_AOT_TRAMP_FTNPTR_ARG:
7671 sprintf (symbol, "ftnptr_arg_trampolines");
7672 break;
7673 case MONO_AOT_TRAMP_UNBOX_ARBITRARY:
7674 sprintf (symbol, "unbox_arbitrary_trampolines");
7675 break;
7676 default:
7677 g_assert_not_reached ();
7680 sprintf (end_symbol, "%s_e", symbol);
7682 if (acfg->aot_opts.write_symbols)
7683 emit_local_symbol (acfg, symbol, end_symbol, TRUE);
7685 emit_alignment_code (acfg, AOT_FUNC_ALIGNMENT);
7686 emit_info_symbol (acfg, symbol, TRUE);
7688 acfg->trampoline_got_offset_base [ntype] = tramp_got_offset;
7690 for (i = 0; i < acfg->num_trampolines [ntype]; ++i) {
7691 int tramp_size = 0;
7693 switch (ntype) {
7694 case MONO_AOT_TRAMP_SPECIFIC:
7695 arch_emit_specific_trampoline (acfg, tramp_got_offset, &tramp_size);
7696 tramp_got_offset += 2;
7697 break;
7698 case MONO_AOT_TRAMP_STATIC_RGCTX:
7699 arch_emit_static_rgctx_trampoline (acfg, tramp_got_offset, &tramp_size);
7700 tramp_got_offset += 2;
7701 break;
7702 case MONO_AOT_TRAMP_IMT:
7703 arch_emit_imt_trampoline (acfg, tramp_got_offset, &tramp_size);
7704 tramp_got_offset += 1;
7705 break;
7706 case MONO_AOT_TRAMP_GSHAREDVT_ARG:
7707 arch_emit_gsharedvt_arg_trampoline (acfg, tramp_got_offset, &tramp_size);
7708 tramp_got_offset += 2;
7709 break;
7710 case MONO_AOT_TRAMP_FTNPTR_ARG:
7711 arch_emit_ftnptr_arg_trampoline (acfg, tramp_got_offset, &tramp_size);
7712 tramp_got_offset += 2;
7713 break;
7714 case MONO_AOT_TRAMP_UNBOX_ARBITRARY:
7715 arch_emit_unbox_arbitrary_trampoline (acfg, tramp_got_offset, &tramp_size);
7716 tramp_got_offset += 1;
7717 break;
7718 default:
7719 g_assert_not_reached ();
7721 if (!acfg->trampoline_size [ntype]) {
7722 g_assert (tramp_size);
7723 acfg->trampoline_size [ntype] = tramp_size;
7727 emit_label (acfg, end_symbol);
7728 emit_int32 (acfg, 0);
7731 arch_emit_specific_trampoline_pages (acfg);
7733 /* Reserve some entries at the end of the GOT for our use */
7734 acfg->num_trampoline_got_entries = tramp_got_offset - acfg->got_offset;
7737 acfg->got_offset += acfg->num_trampoline_got_entries;
7740 static gboolean
7741 str_begins_with (const char *str1, const char *str2)
7743 int len = strlen (str2);
7744 return strncmp (str1, str2, len) == 0;
7747 void*
7748 mono_aot_readonly_field_override (MonoClassField *field)
7750 ReadOnlyValue *rdv;
7751 for (rdv = readonly_values; rdv; rdv = rdv->next) {
7752 char *p = rdv->name;
7753 int len;
7754 len = strlen (m_class_get_name_space (field->parent));
7755 if (strncmp (p, m_class_get_name_space (field->parent), len))
7756 continue;
7757 p += len;
7758 if (*p++ != '.')
7759 continue;
7760 len = strlen (m_class_get_name (field->parent));
7761 if (strncmp (p, m_class_get_name (field->parent), len))
7762 continue;
7763 p += len;
7764 if (*p++ != '.')
7765 continue;
7766 if (strcmp (p, field->name))
7767 continue;
7768 switch (rdv->type) {
7769 case MONO_TYPE_I1:
7770 return &rdv->value.i1;
7771 case MONO_TYPE_I2:
7772 return &rdv->value.i2;
7773 case MONO_TYPE_I4:
7774 return &rdv->value.i4;
7775 default:
7776 break;
7779 return NULL;
7782 static void
7783 add_readonly_value (MonoAotOptions *opts, const char *val)
7785 ReadOnlyValue *rdv;
7786 const char *fval;
7787 const char *tval;
7788 /* the format of val is:
7789 * namespace.typename.fieldname=type/value
7790 * type can be i1 for uint8/int8/boolean, i2 for uint16/int16/char, i4 for uint32/int32
7792 fval = strrchr (val, '/');
7793 if (!fval) {
7794 fprintf (stderr, "AOT : invalid format for readonly field '%s', missing /.\n", val);
7795 exit (1);
7797 tval = strrchr (val, '=');
7798 if (!tval) {
7799 fprintf (stderr, "AOT : invalid format for readonly field '%s', missing =.\n", val);
7800 exit (1);
7802 rdv = g_new0 (ReadOnlyValue, 1);
7803 rdv->name = (char *)g_malloc0 (tval - val + 1);
7804 memcpy (rdv->name, val, tval - val);
7805 tval++;
7806 fval++;
7807 if (strncmp (tval, "i1", 2) == 0) {
7808 rdv->value.i1 = atoi (fval);
7809 rdv->type = MONO_TYPE_I1;
7810 } else if (strncmp (tval, "i2", 2) == 0) {
7811 rdv->value.i2 = atoi (fval);
7812 rdv->type = MONO_TYPE_I2;
7813 } else if (strncmp (tval, "i4", 2) == 0) {
7814 rdv->value.i4 = atoi (fval);
7815 rdv->type = MONO_TYPE_I4;
7816 } else {
7817 fprintf (stderr, "AOT : unsupported type for readonly field '%s'.\n", tval);
7818 exit (1);
7820 rdv->next = readonly_values;
7821 readonly_values = rdv;
7824 static gchar *
7825 clean_path (gchar * path)
7827 if (!path)
7828 return NULL;
7830 if (g_str_has_suffix (path, G_DIR_SEPARATOR_S))
7831 return path;
7833 gchar *clean = g_strconcat (path, G_DIR_SEPARATOR_S, NULL);
7834 g_free (path);
7836 return clean;
7839 static const gchar *
7840 wrap_path (const gchar * path)
7842 int len;
7843 if (!path)
7844 return NULL;
7846 // If the string contains no spaces, just return the original string.
7847 if (strstr (path, " ") == NULL)
7848 return path;
7850 // If the string is already wrapped in quotes, return it.
7851 len = strlen (path);
7852 if (len >= 2 && path[0] == '\"' && path[len-1] == '\"')
7853 return path;
7855 // If the string contains spaces, then wrap it in quotes.
7856 gchar *clean = g_strdup_printf ("\"%s\"", path);
7858 return clean;
7861 // Duplicate a char range and add it to a ptrarray, but only if it is nonempty
7862 static void
7863 ptr_array_add_range_if_nonempty(GPtrArray *args, gchar const *start, gchar const *end)
7865 ptrdiff_t len = end-start;
7866 if (len > 0)
7867 g_ptr_array_add (args, g_strndup (start, len));
7870 static GPtrArray *
7871 mono_aot_split_options (const char *aot_options)
7873 enum MonoAotOptionState {
7874 MONO_AOT_OPTION_STATE_DEFAULT,
7875 MONO_AOT_OPTION_STATE_STRING,
7876 MONO_AOT_OPTION_STATE_ESCAPE,
7879 GPtrArray *args = g_ptr_array_new ();
7880 enum MonoAotOptionState state = MONO_AOT_OPTION_STATE_DEFAULT;
7881 gchar const *opt_start = aot_options;
7882 gboolean end_of_string = FALSE;
7883 gchar cur;
7885 g_return_val_if_fail (aot_options != NULL, NULL);
7887 while ((cur = *aot_options) != '\0') {
7888 if (state == MONO_AOT_OPTION_STATE_ESCAPE)
7889 goto next;
7891 switch (cur) {
7892 case '"':
7893 // If we find a quote, then if we're in the default case then
7894 // it means we've found the start of a string, if not then it
7895 // means we've found the end of the string and should switch
7896 // back to the default case.
7897 switch (state) {
7898 case MONO_AOT_OPTION_STATE_DEFAULT:
7899 state = MONO_AOT_OPTION_STATE_STRING;
7900 break;
7901 case MONO_AOT_OPTION_STATE_STRING:
7902 state = MONO_AOT_OPTION_STATE_DEFAULT;
7903 break;
7904 case MONO_AOT_OPTION_STATE_ESCAPE:
7905 g_assert_not_reached ();
7906 break;
7908 break;
7909 case '\\':
7910 // If we've found an escaping operator, then this means we
7911 // should not process the next character if inside a string.
7912 if (state == MONO_AOT_OPTION_STATE_STRING)
7913 state = MONO_AOT_OPTION_STATE_ESCAPE;
7914 break;
7915 case ',':
7916 // If we're in the default state then this means we've found
7917 // an option, store it for later processing.
7918 if (state == MONO_AOT_OPTION_STATE_DEFAULT)
7919 goto new_opt;
7920 break;
7923 next:
7924 aot_options++;
7925 restart:
7926 // If the next character is end of string, then process the last option.
7927 if (*(aot_options) == '\0') {
7928 end_of_string = TRUE;
7929 goto new_opt;
7931 continue;
7933 new_opt:
7934 ptr_array_add_range_if_nonempty (args, opt_start, aot_options);
7935 opt_start = ++aot_options;
7936 if (end_of_string)
7937 break;
7938 goto restart; // Check for null and continue loop
7941 return args;
7944 static void
7945 mono_aot_parse_options (const char *aot_options, MonoAotOptions *opts)
7947 GPtrArray* args;
7949 args = mono_aot_split_options (aot_options ? aot_options : "");
7950 for (int i = 0; i < args->len; ++i) {
7951 const char *arg = (const char *)g_ptr_array_index (args, i);
7953 if (str_begins_with (arg, "outfile=")) {
7954 opts->outfile = g_strdup (arg + strlen ("outfile="));
7955 } else if (str_begins_with (arg, "llvm-outfile=")) {
7956 opts->llvm_outfile = g_strdup (arg + strlen ("llvm-outfile="));
7957 } else if (str_begins_with (arg, "temp-path=")) {
7958 opts->temp_path = clean_path (g_strdup (arg + strlen ("temp-path=")));
7959 } else if (str_begins_with (arg, "save-temps")) {
7960 opts->save_temps = TRUE;
7961 } else if (str_begins_with (arg, "keep-temps")) {
7962 opts->save_temps = TRUE;
7963 } else if (str_begins_with (arg, "write-symbols")) {
7964 opts->write_symbols = TRUE;
7965 } else if (str_begins_with (arg, "no-write-symbols")) {
7966 opts->write_symbols = FALSE;
7967 // Intentionally undocumented -- one-off experiment
7968 } else if (str_begins_with (arg, "metadata-only")) {
7969 opts->metadata_only = TRUE;
7970 } else if (str_begins_with (arg, "bind-to-runtime-version")) {
7971 opts->bind_to_runtime_version = TRUE;
7972 } else if (str_begins_with (arg, "full")) {
7973 opts->mode = MONO_AOT_MODE_FULL;
7974 } else if (str_begins_with (arg, "hybrid")) {
7975 opts->mode = MONO_AOT_MODE_HYBRID;
7976 } else if (str_begins_with (arg, "interp")) {
7977 opts->interp = TRUE;
7978 } else if (str_begins_with (arg, "threads=")) {
7979 opts->nthreads = atoi (arg + strlen ("threads="));
7980 } else if (str_begins_with (arg, "static")) {
7981 opts->static_link = TRUE;
7982 opts->no_dlsym = TRUE;
7983 } else if (str_begins_with (arg, "asmonly")) {
7984 opts->asm_only = TRUE;
7985 } else if (str_begins_with (arg, "asmwriter")) {
7986 opts->asm_writer = TRUE;
7987 } else if (str_begins_with (arg, "nodebug")) {
7988 opts->nodebug = TRUE;
7989 } else if (str_begins_with (arg, "dwarfdebug")) {
7990 opts->dwarf_debug = TRUE;
7991 // Intentionally undocumented -- No one remembers what this does. It appears to be ARM-only
7992 } else if (str_begins_with (arg, "nopagetrampolines")) {
7993 opts->use_trampolines_page = FALSE;
7994 } else if (str_begins_with (arg, "ntrampolines=")) {
7995 opts->ntrampolines = atoi (arg + strlen ("ntrampolines="));
7996 } else if (str_begins_with (arg, "nrgctx-trampolines=")) {
7997 opts->nrgctx_trampolines = atoi (arg + strlen ("nrgctx-trampolines="));
7998 } else if (str_begins_with (arg, "nrgctx-fetch-trampolines=")) {
7999 opts->nrgctx_fetch_trampolines = atoi (arg + strlen ("nrgctx-fetch-trampolines="));
8000 } else if (str_begins_with (arg, "nimt-trampolines=")) {
8001 opts->nimt_trampolines = atoi (arg + strlen ("nimt-trampolines="));
8002 } else if (str_begins_with (arg, "ngsharedvt-trampolines=")) {
8003 opts->ngsharedvt_arg_trampolines = atoi (arg + strlen ("ngsharedvt-trampolines="));
8004 } else if (str_begins_with (arg, "nftnptr-arg-trampolines=")) {
8005 opts->nftnptr_arg_trampolines = atoi (arg + strlen ("nftnptr-arg-trampolines="));
8006 } else if (str_begins_with (arg, "nunbox-arbitrary-trampolines=")) {
8007 opts->nunbox_arbitrary_trampolines = atoi (arg + strlen ("unbox-arbitrary-trampolines="));
8008 } else if (str_begins_with (arg, "tool-prefix=")) {
8009 opts->tool_prefix = g_strdup (arg + strlen ("tool-prefix="));
8010 } else if (str_begins_with (arg, "ld-flags=")) {
8011 opts->ld_flags = g_strdup (arg + strlen ("ld-flags="));
8012 } else if (str_begins_with (arg, "soft-debug")) {
8013 opts->soft_debug = TRUE;
8014 // Intentionally undocumented x2-- deprecated
8015 } else if (str_begins_with (arg, "gen-seq-points-file=")) {
8016 fprintf (stderr, "Mono Warning: aot option gen-seq-points-file= is deprecated.\n");
8017 } else if (str_begins_with (arg, "gen-seq-points-file")) {
8018 fprintf (stderr, "Mono Warning: aot option gen-seq-points-file is deprecated.\n");
8019 } else if (str_begins_with (arg, "msym-dir=")) {
8020 mini_debug_options.no_seq_points_compact_data = FALSE;
8021 opts->gen_msym_dir = TRUE;
8022 opts->gen_msym_dir_path = g_strdup (arg + strlen ("msym_dir="));
8023 } else if (str_begins_with (arg, "direct-pinvoke")) {
8024 opts->direct_pinvoke = TRUE;
8025 } else if (str_begins_with (arg, "direct-icalls")) {
8026 opts->direct_icalls = TRUE;
8027 } else if (str_begins_with (arg, "no-direct-calls")) {
8028 opts->no_direct_calls = TRUE;
8029 } else if (str_begins_with (arg, "print-skipped")) {
8030 opts->print_skipped_methods = TRUE;
8031 } else if (str_begins_with (arg, "stats")) {
8032 opts->stats = TRUE;
8033 // Intentionally undocumented-- has no known function other than to debug the compiler
8034 } else if (str_begins_with (arg, "no-instances")) {
8035 opts->no_instances = TRUE;
8036 // Intentionally undocumented x4-- Used for internal debugging of compiler
8037 } else if (str_begins_with (arg, "log-generics")) {
8038 opts->log_generics = TRUE;
8039 } else if (str_begins_with (arg, "log-instances=")) {
8040 opts->log_instances = TRUE;
8041 opts->instances_logfile_path = g_strdup (arg + strlen ("log-instances="));
8042 } else if (str_begins_with (arg, "log-instances")) {
8043 opts->log_instances = TRUE;
8044 } else if (str_begins_with (arg, "internal-logfile=")) {
8045 opts->logfile = g_strdup (arg + strlen ("internal-logfile="));
8046 } else if (str_begins_with (arg, "dedup-skip")) {
8047 opts->dedup = TRUE;
8048 } else if (str_begins_with (arg, "dedup-include=")) {
8049 opts->dedup_include = g_strdup (arg + strlen ("dedup-include="));
8050 } else if (str_begins_with (arg, "mtriple=")) {
8051 opts->mtriple = g_strdup (arg + strlen ("mtriple="));
8052 } else if (str_begins_with (arg, "llvm-path=")) {
8053 opts->llvm_path = clean_path (g_strdup (arg + strlen ("llvm-path=")));
8054 } else if (!strcmp (arg, "try-llvm")) {
8055 // If we can load LLVM, use it
8056 // Note: if you call this function from anywhere but mono_compile_assembly,
8057 // this will only set the try_llvm attribute and not do the probing / set the
8058 // attribute.
8059 opts->try_llvm = TRUE;
8060 } else if (!strcmp (arg, "llvm")) {
8061 opts->llvm = TRUE;
8062 } else if (str_begins_with (arg, "readonly-value=")) {
8063 add_readonly_value (opts, arg + strlen ("readonly-value="));
8064 } else if (str_begins_with (arg, "info")) {
8065 printf ("AOT target setup: %s.\n", AOT_TARGET_STR);
8066 exit (0);
8067 // Intentionally undocumented: Used for precise stack maps, which are not available yet
8068 } else if (str_begins_with (arg, "gc-maps")) {
8069 mini_gc_enable_gc_maps_for_aot ();
8070 // Intentionally undocumented: Used for internal debugging
8071 } else if (str_begins_with (arg, "dump")) {
8072 opts->dump_json = TRUE;
8073 } else if (str_begins_with (arg, "llvmonly")) {
8074 opts->mode = MONO_AOT_MODE_FULL;
8075 opts->llvm = TRUE;
8076 opts->llvm_only = TRUE;
8077 } else if (str_begins_with (arg, "data-outfile=")) {
8078 opts->data_outfile = g_strdup (arg + strlen ("data-outfile="));
8079 } else if (str_begins_with (arg, "profile=")) {
8080 opts->profile_files = g_list_append (opts->profile_files, g_strdup (arg + strlen ("profile=")));
8081 } else if (!strcmp (arg, "profile-only")) {
8082 opts->profile_only = TRUE;
8083 } else if (!strcmp (arg, "verbose")) {
8084 opts->verbose = TRUE;
8085 } else if (str_begins_with (arg, "llvmopts=")){
8086 opts->llvm_opts = g_strdup (arg + strlen ("llvmopts="));
8087 } else if (str_begins_with (arg, "llvmllc=")){
8088 opts->llvm_llc = g_strdup (arg + strlen ("llvmllc="));
8089 } else if (!strcmp (arg, "deterministic")) {
8090 opts->deterministic = TRUE;
8091 } else if (!strcmp (arg, "no-opt")) {
8092 opts->no_opt = TRUE;
8093 } else if (str_begins_with (arg, "clangxx=")) {
8094 opts->clangxx = g_strdup (arg + strlen ("clangxx="));
8095 } else if (str_begins_with (arg, "depfile=")) {
8096 opts->depfile = g_strdup (arg + strlen ("depfile="));
8097 } else if (str_begins_with (arg, "help") || str_begins_with (arg, "?")) {
8098 printf ("Supported options for --aot:\n");
8099 printf (" asmonly\n");
8100 printf (" bind-to-runtime-version\n");
8101 printf (" bitcode\n");
8102 printf (" data-outfile=\n");
8103 printf (" direct-icalls\n");
8104 printf (" direct-pinvoke\n");
8105 printf (" dwarfdebug\n");
8106 printf (" full\n");
8107 printf (" hybrid\n");
8108 printf (" info\n");
8109 printf (" keep-temps\n");
8110 printf (" llvm\n");
8111 printf (" llvmonly\n");
8112 printf (" llvm-outfile=\n");
8113 printf (" llvm-path=\n");
8114 printf (" msym-dir=\n");
8115 printf (" mtriple\n");
8116 printf (" nimt-trampolines=\n");
8117 printf (" nodebug\n");
8118 printf (" no-direct-calls\n");
8119 printf (" no-write-symbols\n");
8120 printf (" nrgctx-trampolines=\n");
8121 printf (" nrgctx-fetch-trampolines=\n");
8122 printf (" ngsharedvt-trampolines=\n");
8123 printf (" nftnptr-arg-trampolines=\n");
8124 printf (" nunbox-arbitrary-trampolines=\n");
8125 printf (" ntrampolines=\n");
8126 printf (" outfile=\n");
8127 printf (" profile=\n");
8128 printf (" profile-only\n");
8129 printf (" print-skipped-methods\n");
8130 printf (" readonly-value=\n");
8131 printf (" save-temps\n");
8132 printf (" soft-debug\n");
8133 printf (" static\n");
8134 printf (" stats\n");
8135 printf (" temp-path=\n");
8136 printf (" tool-prefix=\n");
8137 printf (" threads=\n");
8138 printf (" write-symbols\n");
8139 printf (" verbose\n");
8140 printf (" no-opt\n");
8141 printf (" llvmopts=\n");
8142 printf (" llvmllc=\n");
8143 printf (" clangxx=\n");
8144 printf (" depfile=\n");
8145 printf (" help/?\n");
8146 exit (0);
8147 } else {
8148 fprintf (stderr, "AOT : Unknown argument '%s'.\n", arg);
8149 exit (1);
8152 g_free ((gpointer) arg);
8155 if (opts->use_trampolines_page) {
8156 opts->ntrampolines = 0;
8157 opts->nrgctx_trampolines = 0;
8158 opts->nimt_trampolines = 0;
8159 opts->ngsharedvt_arg_trampolines = 0;
8160 opts->nftnptr_arg_trampolines = 0;
8161 opts->nunbox_arbitrary_trampolines = 0;
8164 g_ptr_array_free (args, /*free_seg=*/TRUE);
8167 static void
8168 add_token_info_hash (gpointer key, gpointer value, gpointer user_data)
8170 MonoMethod *method = (MonoMethod*)key;
8171 MonoJumpInfoToken *ji = (MonoJumpInfoToken*)value;
8172 MonoAotCompile *acfg = (MonoAotCompile *)user_data;
8173 MonoJumpInfoToken *new_ji;
8175 new_ji = (MonoJumpInfoToken *)mono_mempool_alloc0 (acfg->mempool, sizeof (MonoJumpInfoToken));
8176 new_ji->image = ji->image;
8177 new_ji->token = ji->token;
8178 g_hash_table_insert (acfg->token_info_hash, method, new_ji);
8181 static gboolean
8182 can_encode_class (MonoAotCompile *acfg, MonoClass *klass)
8184 if (m_class_get_type_token (klass))
8185 return TRUE;
8186 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))
8187 return TRUE;
8188 if (m_class_get_rank (klass))
8189 return can_encode_class (acfg, m_class_get_element_class (klass));
8190 return FALSE;
8193 static gboolean
8194 can_encode_method (MonoAotCompile *acfg, MonoMethod *method)
8196 if (method->wrapper_type) {
8197 switch (method->wrapper_type) {
8198 case MONO_WRAPPER_NONE:
8199 case MONO_WRAPPER_REMOTING_INVOKE_WITH_CHECK:
8200 case MONO_WRAPPER_XDOMAIN_INVOKE:
8201 case MONO_WRAPPER_STFLD:
8202 case MONO_WRAPPER_LDFLD:
8203 case MONO_WRAPPER_LDFLDA:
8204 case MONO_WRAPPER_STELEMREF:
8205 case MONO_WRAPPER_PROXY_ISINST:
8206 case MONO_WRAPPER_ALLOC:
8207 case MONO_WRAPPER_REMOTING_INVOKE:
8208 case MONO_WRAPPER_OTHER:
8209 case MONO_WRAPPER_WRITE_BARRIER:
8210 case MONO_WRAPPER_DELEGATE_INVOKE:
8211 case MONO_WRAPPER_DELEGATE_BEGIN_INVOKE:
8212 case MONO_WRAPPER_DELEGATE_END_INVOKE:
8213 case MONO_WRAPPER_SYNCHRONIZED:
8214 case MONO_WRAPPER_MANAGED_TO_NATIVE:
8215 break;
8216 case MONO_WRAPPER_MANAGED_TO_MANAGED:
8217 case MONO_WRAPPER_CASTCLASS: {
8218 WrapperInfo *info = mono_marshal_get_wrapper_info (method);
8220 if (info)
8221 return TRUE;
8222 else
8223 return FALSE;
8224 break;
8226 default:
8227 //printf ("Skip (wrapper call): %d -> %s\n", patch_info->type, mono_method_full_name (patch_info->data.method, TRUE));
8228 return FALSE;
8230 } else {
8231 if (!method->token) {
8232 /* The method is part of a constructed type like Int[,].Set (). */
8233 if (!g_hash_table_lookup (acfg->token_info_hash, method)) {
8234 if (m_class_get_rank (method->klass))
8235 return TRUE;
8236 return FALSE;
8240 return TRUE;
8243 static gboolean
8244 can_encode_patch (MonoAotCompile *acfg, MonoJumpInfo *patch_info)
8246 switch (patch_info->type) {
8247 case MONO_PATCH_INFO_METHOD:
8248 case MONO_PATCH_INFO_METHOD_FTNDESC:
8249 case MONO_PATCH_INFO_METHODCONST:
8250 case MONO_PATCH_INFO_METHOD_CODE_SLOT: {
8251 MonoMethod *method = patch_info->data.method;
8253 return can_encode_method (acfg, method);
8255 case MONO_PATCH_INFO_VTABLE:
8256 case MONO_PATCH_INFO_CLASS:
8257 case MONO_PATCH_INFO_IID:
8258 case MONO_PATCH_INFO_ADJUSTED_IID:
8259 if (!can_encode_class (acfg, patch_info->data.klass)) {
8260 //printf ("Skip: %s\n", mono_type_full_name (m_class_get_byval_arg (patch_info->data.klass)));
8261 return FALSE;
8263 break;
8264 case MONO_PATCH_INFO_DELEGATE_TRAMPOLINE: {
8265 if (!can_encode_class (acfg, patch_info->data.del_tramp->klass)) {
8266 //printf ("Skip: %s\n", mono_type_full_name (m_class_get_byval_arg (patch_info->data.klass)));
8267 return FALSE;
8269 break;
8271 case MONO_PATCH_INFO_RGCTX_FETCH:
8272 case MONO_PATCH_INFO_RGCTX_SLOT_INDEX: {
8273 MonoJumpInfoRgctxEntry *entry = patch_info->data.rgctx_entry;
8275 if (entry->in_mrgctx) {
8276 if (!can_encode_method (acfg, entry->d.method))
8277 return FALSE;
8278 } else {
8279 if (!can_encode_class (acfg, entry->d.klass))
8280 return FALSE;
8282 if (!can_encode_patch (acfg, entry->data))
8283 return FALSE;
8284 break;
8286 default:
8287 break;
8290 return TRUE;
8293 static gboolean
8294 is_concrete_type (MonoType *t)
8296 MonoClass *klass;
8297 int i;
8299 if (t->type == MONO_TYPE_VAR || t->type == MONO_TYPE_MVAR)
8300 return FALSE;
8301 if (t->type == MONO_TYPE_GENERICINST) {
8302 MonoGenericContext *orig_ctx;
8303 MonoGenericInst *inst;
8304 MonoType *arg;
8306 if (!MONO_TYPE_ISSTRUCT (t))
8307 return TRUE;
8308 klass = mono_class_from_mono_type_internal (t);
8309 orig_ctx = &mono_class_get_generic_class (klass)->context;
8311 inst = orig_ctx->class_inst;
8312 if (inst) {
8313 for (i = 0; i < inst->type_argc; ++i) {
8314 arg = mini_get_underlying_type (inst->type_argv [i]);
8315 if (!is_concrete_type (arg))
8316 return FALSE;
8319 inst = orig_ctx->method_inst;
8320 if (inst) {
8321 for (i = 0; i < inst->type_argc; ++i) {
8322 arg = mini_get_underlying_type (inst->type_argv [i]);
8323 if (!is_concrete_type (arg))
8324 return FALSE;
8328 return TRUE;
8331 static MonoMethodSignature*
8332 get_concrete_sig (MonoMethodSignature *sig)
8334 gboolean concrete = TRUE;
8336 if (!sig->has_type_parameters)
8337 return sig;
8339 /* For signatures created during generic sharing, convert them to a concrete signature if possible */
8340 MonoMethodSignature *copy = mono_metadata_signature_dup (sig);
8341 int i;
8343 //printf ("%s\n", mono_signature_full_name (sig));
8345 if (sig->ret->byref)
8346 copy->ret = m_class_get_this_arg (mono_defaults.int_class);
8347 else
8348 copy->ret = mini_get_underlying_type (sig->ret);
8349 if (!is_concrete_type (copy->ret))
8350 concrete = FALSE;
8351 for (i = 0; i < sig->param_count; ++i) {
8352 if (sig->params [i]->byref) {
8353 MonoType *t = m_class_get_byval_arg (mono_class_from_mono_type_internal (sig->params [i]));
8354 t = mini_get_underlying_type (t);
8355 copy->params [i] = m_class_get_this_arg (mono_class_from_mono_type_internal (t));
8356 } else {
8357 copy->params [i] = mini_get_underlying_type (sig->params [i]);
8359 if (!is_concrete_type (copy->params [i]))
8360 concrete = FALSE;
8362 copy->has_type_parameters = 0;
8363 if (!concrete)
8364 return NULL;
8365 return copy;
8368 /* LOCKING: Assumes the loader lock is held */
8369 static void
8370 add_gsharedvt_wrappers (MonoAotCompile *acfg, MonoMethodSignature *sig, gboolean gsharedvt_in, gboolean gsharedvt_out, gboolean interp_in)
8372 MonoMethod *wrapper;
8373 gboolean add_in = gsharedvt_in;
8374 gboolean add_out = gsharedvt_out;
8376 if (gsharedvt_in && g_hash_table_lookup (acfg->gsharedvt_in_signatures, sig))
8377 add_in = FALSE;
8378 if (gsharedvt_out && g_hash_table_lookup (acfg->gsharedvt_out_signatures, sig))
8379 add_out = FALSE;
8381 if (!add_in && !add_out)
8382 return;
8384 if (mini_is_gsharedvt_variable_signature (sig))
8385 return;
8387 if (add_in)
8388 g_hash_table_insert (acfg->gsharedvt_in_signatures, sig, sig);
8389 if (add_out)
8390 g_hash_table_insert (acfg->gsharedvt_out_signatures, sig, sig);
8392 sig = get_concrete_sig (sig);
8393 if (!sig)
8394 return;
8395 //printf ("%s\n", mono_signature_full_name (sig));
8397 if (gsharedvt_in) {
8398 wrapper = mini_get_gsharedvt_in_sig_wrapper (sig);
8399 add_extra_method (acfg, wrapper);
8401 if (gsharedvt_out) {
8402 wrapper = mini_get_gsharedvt_out_sig_wrapper (sig);
8403 add_extra_method (acfg, wrapper);
8406 #ifndef MONO_ARCH_HAVE_INTERP_ENTRY_TRAMPOLINE
8407 if (interp_in) {
8408 wrapper = mini_get_interp_in_wrapper (sig);
8409 add_extra_method (acfg, wrapper);
8410 //printf ("X: %s\n", mono_method_full_name (wrapper, 1));
8412 #endif
8416 * compile_method:
8418 * AOT compile a given method.
8419 * This function might be called by multiple threads, so it must be thread-safe.
8421 static void
8422 compile_method (MonoAotCompile *acfg, MonoMethod *method)
8424 MonoCompile *cfg;
8425 MonoJumpInfo *patch_info;
8426 gboolean skip;
8427 int index, depth;
8428 MonoMethod *wrapped;
8429 gint64 jit_time_start;
8430 JitFlags flags;
8432 if (acfg->aot_opts.metadata_only)
8433 return;
8435 mono_acfg_lock (acfg);
8436 index = get_method_index (acfg, method);
8437 mono_acfg_unlock (acfg);
8439 /* fixme: maybe we can also precompile wrapper methods */
8440 if ((method->flags & METHOD_ATTRIBUTE_PINVOKE_IMPL) ||
8441 (method->iflags & METHOD_IMPL_ATTRIBUTE_RUNTIME) ||
8442 (method->flags & METHOD_ATTRIBUTE_ABSTRACT)) {
8443 //printf ("Skip (impossible): %s\n", mono_method_full_name (method, TRUE));
8444 return;
8447 if (method->iflags & METHOD_IMPL_ATTRIBUTE_INTERNAL_CALL)
8448 return;
8450 wrapped = mono_marshal_method_from_wrapper (method);
8451 if (wrapped && (wrapped->iflags & METHOD_IMPL_ATTRIBUTE_INTERNAL_CALL) && wrapped->is_generic)
8452 // FIXME: The wrapper should be generic too, but it is not
8453 return;
8455 if (method->wrapper_type == MONO_WRAPPER_COMINTEROP)
8456 return;
8458 if (acfg->aot_opts.profile_only && !method->is_inflated && !g_hash_table_lookup (acfg->profile_methods, method))
8459 return;
8461 mono_atomic_inc_i32 (&acfg->stats.mcount);
8463 #if 0
8464 if (method->is_generic || mono_class_is_gtd (method->klass)) {
8465 mono_atomic_inc_i32 (&acfg->stats.genericcount);
8466 return;
8468 #endif
8470 //acfg->aot_opts.print_skipped_methods = TRUE;
8473 * Since these methods are the only ones which are compiled with
8474 * AOT support, and they are not used by runtime startup/shutdown code,
8475 * the runtime will not see AOT methods during AOT compilation,so it
8476 * does not need to support them by creating a fake GOT etc.
8478 flags = JIT_FLAG_AOT;
8479 if (mono_aot_mode_is_full (&acfg->aot_opts))
8480 flags = (JitFlags)(flags | JIT_FLAG_FULL_AOT);
8481 if (acfg->llvm)
8482 flags = (JitFlags)(flags | JIT_FLAG_LLVM);
8483 if (acfg->aot_opts.llvm_only)
8484 flags = (JitFlags)(flags | JIT_FLAG_LLVM_ONLY | JIT_FLAG_EXPLICIT_NULL_CHECKS);
8485 if (acfg->aot_opts.no_direct_calls)
8486 flags = (JitFlags)(flags | JIT_FLAG_NO_DIRECT_ICALLS);
8487 if (acfg->aot_opts.direct_pinvoke)
8488 flags = (JitFlags)(flags | JIT_FLAG_DIRECT_PINVOKE);
8489 if (acfg->aot_opts.interp)
8490 flags = (JitFlags)(flags | JIT_FLAG_INTERP);
8492 jit_time_start = mono_time_track_start ();
8493 cfg = mini_method_compile (method, acfg->opts, mono_get_root_domain (), flags, 0, index);
8494 mono_time_track_end (&mono_jit_stats.jit_time, jit_time_start);
8496 if (cfg->exception_type == MONO_EXCEPTION_GENERIC_SHARING_FAILED) {
8497 if (acfg->aot_opts.print_skipped_methods)
8498 printf ("Skip (gshared failure): %s (%s)\n", mono_method_get_full_name (method), cfg->exception_message);
8499 mono_atomic_inc_i32 (&acfg->stats.genericcount);
8500 return;
8502 if (cfg->exception_type != MONO_EXCEPTION_NONE) {
8503 /* Some instances cannot be JITted due to constraints etc. */
8504 if (!method->is_inflated)
8505 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));
8506 /* Let the exception happen at runtime */
8507 return;
8510 if (cfg->disable_aot) {
8511 if (acfg->aot_opts.print_skipped_methods)
8512 printf ("Skip (disabled): %s\n", mono_method_get_full_name (method));
8513 mono_atomic_inc_i32 (&acfg->stats.ocount);
8514 return;
8516 cfg->method_index = index;
8518 /* Nullify patches which need no aot processing */
8519 for (patch_info = cfg->patch_info; patch_info; patch_info = patch_info->next) {
8520 switch (patch_info->type) {
8521 case MONO_PATCH_INFO_LABEL:
8522 case MONO_PATCH_INFO_BB:
8523 patch_info->type = MONO_PATCH_INFO_NONE;
8524 break;
8525 default:
8526 break;
8530 /* Collect method->token associations from the cfg */
8531 mono_acfg_lock (acfg);
8532 g_hash_table_foreach (cfg->token_info_hash, add_token_info_hash, acfg);
8533 mono_acfg_unlock (acfg);
8534 g_hash_table_destroy (cfg->token_info_hash);
8535 cfg->token_info_hash = NULL;
8538 * Check for absolute addresses.
8540 skip = FALSE;
8541 for (patch_info = cfg->patch_info; patch_info; patch_info = patch_info->next) {
8542 switch (patch_info->type) {
8543 case MONO_PATCH_INFO_ABS:
8544 /* unable to handle this */
8545 skip = TRUE;
8546 break;
8547 default:
8548 break;
8552 if (skip) {
8553 if (acfg->aot_opts.print_skipped_methods)
8554 printf ("Skip (abs call): %s\n", mono_method_get_full_name (method));
8555 mono_atomic_inc_i32 (&acfg->stats.abscount);
8556 return;
8559 /* Lock for the rest of the code */
8560 mono_acfg_lock (acfg);
8562 if (cfg->gsharedvt)
8563 acfg->stats.method_categories [METHOD_CAT_GSHAREDVT] ++;
8564 else if (cfg->gshared)
8565 acfg->stats.method_categories [METHOD_CAT_INST] ++;
8566 else if (cfg->method->wrapper_type)
8567 acfg->stats.method_categories [METHOD_CAT_WRAPPER] ++;
8568 else
8569 acfg->stats.method_categories [METHOD_CAT_NORMAL] ++;
8572 * Check for methods/klasses we can't encode.
8574 skip = FALSE;
8575 for (patch_info = cfg->patch_info; patch_info; patch_info = patch_info->next) {
8576 if (!can_encode_patch (acfg, patch_info))
8577 skip = TRUE;
8580 if (skip) {
8581 if (acfg->aot_opts.print_skipped_methods)
8582 printf ("Skip (patches): %s\n", mono_method_get_full_name (method));
8583 acfg->stats.ocount++;
8584 mono_acfg_unlock (acfg);
8585 return;
8588 if (!cfg->compile_llvm)
8589 acfg->has_jitted_code = TRUE;
8591 if (method->is_inflated && acfg->aot_opts.log_instances) {
8592 if (acfg->instances_logfile)
8593 fprintf (acfg->instances_logfile, "%s ### %d\n", mono_method_get_full_name (method), cfg->code_size);
8594 else
8595 printf ("%s ### %d\n", mono_method_get_full_name (method), cfg->code_size);
8598 /* Adds generic instances referenced by this method */
8600 * The depth is used to avoid infinite loops when generic virtual recursion is
8601 * encountered.
8603 depth = GPOINTER_TO_UINT (g_hash_table_lookup (acfg->method_depth, method));
8604 if (!acfg->aot_opts.no_instances && depth < 32 && (mono_aot_mode_is_full (&acfg->aot_opts) || mono_aot_mode_is_hybrid (&acfg->aot_opts))) {
8605 for (patch_info = cfg->patch_info; patch_info; patch_info = patch_info->next) {
8606 switch (patch_info->type) {
8607 case MONO_PATCH_INFO_RGCTX_FETCH:
8608 case MONO_PATCH_INFO_RGCTX_SLOT_INDEX:
8609 case MONO_PATCH_INFO_METHOD:
8610 case MONO_PATCH_INFO_METHOD_FTNDESC:
8611 case MONO_PATCH_INFO_METHOD_RGCTX: {
8612 MonoMethod *m = NULL;
8614 if (patch_info->type == MONO_PATCH_INFO_RGCTX_FETCH || patch_info->type == MONO_PATCH_INFO_RGCTX_SLOT_INDEX) {
8615 MonoJumpInfoRgctxEntry *e = patch_info->data.rgctx_entry;
8617 if (e->info_type == MONO_RGCTX_INFO_GENERIC_METHOD_CODE || e->info_type == MONO_RGCTX_INFO_METHOD_FTNDESC)
8618 m = e->data->data.method;
8619 } else {
8620 m = patch_info->data.method;
8623 if (!m)
8624 break;
8625 if (m->is_inflated && (mono_aot_mode_is_full (&acfg->aot_opts) || mono_aot_mode_is_hybrid (&acfg->aot_opts))) {
8626 if (!(mono_class_generic_sharing_enabled (m->klass) &&
8627 mono_method_is_generic_sharable_full (m, FALSE, FALSE, FALSE)) &&
8628 (!method_has_type_vars (m) || mono_method_is_generic_sharable_full (m, TRUE, TRUE, FALSE))) {
8629 if (m->iflags & METHOD_IMPL_ATTRIBUTE_INTERNAL_CALL) {
8630 if (mono_aot_mode_is_full (&acfg->aot_opts) && !method_has_type_vars (m))
8631 add_extra_method_with_depth (acfg, mono_marshal_get_native_wrapper (m, TRUE, TRUE), depth + 1);
8632 } else {
8633 add_extra_method_with_depth (acfg, m, depth + 1);
8634 add_types_from_method_header (acfg, m);
8637 add_generic_class_with_depth (acfg, m->klass, depth + 5, "method");
8639 if (m->wrapper_type == MONO_WRAPPER_MANAGED_TO_MANAGED) {
8640 WrapperInfo *info = mono_marshal_get_wrapper_info (m);
8642 if (info && info->subtype == WRAPPER_SUBTYPE_ELEMENT_ADDR)
8643 add_extra_method_with_depth (acfg, m, depth + 1);
8645 break;
8647 case MONO_PATCH_INFO_VTABLE: {
8648 MonoClass *klass = patch_info->data.klass;
8650 if (mono_class_is_ginst (klass) && !mini_class_is_generic_sharable (klass))
8651 add_generic_class_with_depth (acfg, klass, depth + 5, "vtable");
8652 break;
8654 case MONO_PATCH_INFO_SFLDA: {
8655 MonoClass *klass = patch_info->data.field->parent;
8657 /* The .cctor needs to run at runtime. */
8658 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))
8659 add_extra_method_with_depth (acfg, mono_class_get_cctor (klass), depth + 1);
8660 break;
8662 default:
8663 break;
8668 /* Determine whenever the method has GOT slots */
8669 for (patch_info = cfg->patch_info; patch_info; patch_info = patch_info->next) {
8670 switch (patch_info->type) {
8671 case MONO_PATCH_INFO_GOT_OFFSET:
8672 case MONO_PATCH_INFO_NONE:
8673 case MONO_PATCH_INFO_GC_CARD_TABLE_ADDR:
8674 case MONO_PATCH_INFO_GC_NURSERY_START:
8675 case MONO_PATCH_INFO_GC_NURSERY_BITS:
8676 break;
8677 case MONO_PATCH_INFO_IMAGE:
8678 /* The assembly is stored in GOT slot 0 */
8679 if (patch_info->data.image != acfg->image)
8680 cfg->has_got_slots = TRUE;
8681 break;
8682 default:
8683 if (!is_plt_patch (patch_info) || (cfg->compile_llvm && acfg->aot_opts.llvm_only))
8684 cfg->has_got_slots = TRUE;
8685 break;
8689 if (!cfg->has_got_slots)
8690 mono_atomic_inc_i32 (&acfg->stats.methods_without_got_slots);
8692 /* Add gsharedvt wrappers for signatures used by the method */
8693 if (acfg->aot_opts.llvm_only) {
8694 GSList *l;
8696 if (!cfg->method->wrapper_type || cfg->method->wrapper_type == MONO_WRAPPER_DELEGATE_INVOKE)
8697 /* These only need out wrappers */
8698 add_gsharedvt_wrappers (acfg, mono_method_signature_internal (cfg->method), FALSE, TRUE, FALSE);
8700 for (l = cfg->signatures; l; l = l->next) {
8701 MonoMethodSignature *sig = mono_metadata_signature_dup ((MonoMethodSignature*)l->data);
8703 /* These only need in wrappers */
8704 add_gsharedvt_wrappers (acfg, sig, TRUE, FALSE, FALSE);
8707 for (l = cfg->interp_in_signatures; l; l = l->next) {
8708 MonoMethodSignature *sig = mono_metadata_signature_dup ((MonoMethodSignature*)l->data);
8710 add_gsharedvt_wrappers (acfg, sig, TRUE, FALSE, FALSE);
8712 } else if (mono_aot_mode_is_full (&acfg->aot_opts) && mono_aot_mode_is_interp (&acfg->aot_opts)) {
8713 /* The interpreter uses these wrappers to call aot-ed code */
8714 if (!cfg->method->wrapper_type || cfg->method->wrapper_type == MONO_WRAPPER_DELEGATE_INVOKE)
8715 add_gsharedvt_wrappers (acfg, mono_method_signature_internal (cfg->method), FALSE, TRUE, TRUE);
8718 if (cfg->llvm_only)
8719 acfg->stats.llvm_count ++;
8722 * FIXME: Instead of this mess, allocate the patches from the aot mempool.
8724 /* Make a copy of the patch info which is in the mempool */
8726 MonoJumpInfo *patches = NULL, *patches_end = NULL;
8728 for (patch_info = cfg->patch_info; patch_info; patch_info = patch_info->next) {
8729 MonoJumpInfo *new_patch_info = mono_patch_info_dup_mp (acfg->mempool, patch_info);
8731 if (!patches)
8732 patches = new_patch_info;
8733 else
8734 patches_end->next = new_patch_info;
8735 patches_end = new_patch_info;
8737 cfg->patch_info = patches;
8739 /* Make a copy of the unwind info */
8741 GSList *l, *unwind_ops;
8742 MonoUnwindOp *op;
8744 unwind_ops = NULL;
8745 for (l = cfg->unwind_ops; l; l = l->next) {
8746 op = (MonoUnwindOp *)mono_mempool_alloc (acfg->mempool, sizeof (MonoUnwindOp));
8747 memcpy (op, l->data, sizeof (MonoUnwindOp));
8748 unwind_ops = g_slist_prepend_mempool (acfg->mempool, unwind_ops, op);
8750 cfg->unwind_ops = g_slist_reverse (unwind_ops);
8752 /* Make a copy of the argument/local info */
8754 ERROR_DECL (error);
8755 MonoInst **args, **locals;
8756 MonoMethodSignature *sig;
8757 MonoMethodHeader *header;
8758 int i;
8760 sig = mono_method_signature_internal (method);
8761 args = (MonoInst **)mono_mempool_alloc (acfg->mempool, sizeof (MonoInst*) * (sig->param_count + sig->hasthis));
8762 for (i = 0; i < sig->param_count + sig->hasthis; ++i) {
8763 args [i] = (MonoInst *)mono_mempool_alloc (acfg->mempool, sizeof (MonoInst));
8764 memcpy (args [i], cfg->args [i], sizeof (MonoInst));
8766 cfg->args = args;
8768 header = mono_method_get_header_checked (method, error);
8769 mono_error_assert_ok (error); /* FIXME don't swallow the error */
8770 locals = (MonoInst **)mono_mempool_alloc (acfg->mempool, sizeof (MonoInst*) * header->num_locals);
8771 for (i = 0; i < header->num_locals; ++i) {
8772 locals [i] = (MonoInst *)mono_mempool_alloc (acfg->mempool, sizeof (MonoInst));
8773 memcpy (locals [i], cfg->locals [i], sizeof (MonoInst));
8775 mono_metadata_free_mh (header);
8776 cfg->locals = locals;
8779 /* Free some fields used by cfg to conserve memory */
8780 mono_empty_compile (cfg);
8782 //printf ("Compile: %s\n", mono_method_full_name (method, TRUE));
8784 while (index >= acfg->cfgs_size) {
8785 MonoCompile **new_cfgs;
8786 int new_size;
8788 new_size = acfg->cfgs_size * 2;
8789 new_cfgs = g_new0 (MonoCompile*, new_size);
8790 memcpy (new_cfgs, acfg->cfgs, sizeof (MonoCompile*) * acfg->cfgs_size);
8791 g_free (acfg->cfgs);
8792 acfg->cfgs = new_cfgs;
8793 acfg->cfgs_size = new_size;
8795 acfg->cfgs [index] = cfg;
8797 g_hash_table_insert (acfg->method_to_cfg, cfg->orig_method, cfg);
8799 /* Update global stats while holding a lock. */
8800 mono_update_jit_stats (cfg);
8803 if (cfg->orig_method->wrapper_type)
8804 g_ptr_array_add (acfg->extra_methods, cfg->orig_method);
8807 mono_acfg_unlock (acfg);
8809 mono_atomic_inc_i32 (&acfg->stats.ccount);
8812 static mono_thread_start_return_t WINAPI
8813 compile_thread_main (gpointer user_data)
8815 MonoAotCompile *acfg = ((MonoAotCompile **)user_data) [0];
8816 GPtrArray *methods = ((GPtrArray **)user_data) [1];
8817 int i;
8819 ERROR_DECL (error);
8820 MonoInternalThread *internal = mono_thread_internal_current ();
8821 MonoString *str = mono_string_new_checked (mono_domain_get (), "AOT compiler", error);
8822 mono_error_assert_ok (error);
8823 mono_thread_set_name_internal (internal, str, TRUE, FALSE, error);
8824 mono_error_assert_ok (error);
8826 for (i = 0; i < methods->len; ++i)
8827 compile_method (acfg, (MonoMethod *)g_ptr_array_index (methods, i));
8829 return 0;
8832 /* Used by the LLVM backend */
8833 guint32
8834 mono_aot_get_got_offset (MonoJumpInfo *ji)
8836 return get_got_offset (llvm_acfg, TRUE, ji);
8840 * mono_aot_is_shared_got_offset:
8842 * Return whenever OFFSET refers to a GOT slot which is preinitialized
8843 * when the AOT image is loaded.
8845 gboolean
8846 mono_aot_is_shared_got_offset (int offset)
8848 return offset < llvm_acfg->nshared_got_entries;
8851 char*
8852 mono_aot_get_method_name (MonoCompile *cfg)
8854 MonoMethod *method = cfg->orig_method;
8856 /* Use the mangled name if possible */
8857 if (method->wrapper_type == MONO_WRAPPER_OTHER) {
8858 WrapperInfo *info = mono_marshal_get_wrapper_info (method);
8859 if (info->subtype == WRAPPER_SUBTYPE_GSHAREDVT_IN_SIG || info->subtype == WRAPPER_SUBTYPE_GSHAREDVT_OUT_SIG)
8860 return mono_aot_get_mangled_method_name (method);
8863 if (llvm_acfg->aot_opts.static_link)
8864 /* Include the assembly name too to avoid duplicate symbol errors */
8865 return g_strdup_printf ("%s_%s", llvm_acfg->assembly_name_sym, get_debug_sym (cfg->orig_method, "", llvm_acfg->method_label_hash));
8866 else
8867 return get_debug_sym (cfg->orig_method, "", llvm_acfg->method_label_hash);
8870 static gboolean
8871 append_mangled_type (GString *s, MonoType *t)
8873 if (t->byref)
8874 g_string_append_printf (s, "b");
8875 switch (t->type) {
8876 case MONO_TYPE_VOID:
8877 g_string_append_printf (s, "void");
8878 break;
8879 case MONO_TYPE_I1:
8880 g_string_append_printf (s, "i1");
8881 break;
8882 case MONO_TYPE_U1:
8883 g_string_append_printf (s, "u1");
8884 break;
8885 case MONO_TYPE_I2:
8886 g_string_append_printf (s, "i2");
8887 break;
8888 case MONO_TYPE_U2:
8889 g_string_append_printf (s, "u2");
8890 break;
8891 case MONO_TYPE_I4:
8892 g_string_append_printf (s, "i4");
8893 break;
8894 case MONO_TYPE_U4:
8895 g_string_append_printf (s, "u4");
8896 break;
8897 case MONO_TYPE_I8:
8898 g_string_append_printf (s, "i8");
8899 break;
8900 case MONO_TYPE_U8:
8901 g_string_append_printf (s, "u8");
8902 break;
8903 case MONO_TYPE_I:
8904 g_string_append_printf (s, "ii");
8905 break;
8906 case MONO_TYPE_U:
8907 g_string_append_printf (s, "ui");
8908 break;
8909 case MONO_TYPE_R4:
8910 g_string_append_printf (s, "fl");
8911 break;
8912 case MONO_TYPE_R8:
8913 g_string_append_printf (s, "do");
8914 break;
8915 case MONO_TYPE_OBJECT:
8916 g_string_append_printf (s, "obj");
8917 break;
8918 default: {
8919 char *fullname = mono_type_full_name (t);
8920 GString *temp;
8921 char *temps;
8922 int i, len;
8925 * Have to create a mangled name which is:
8926 * - a valid symbol
8927 * - unique
8929 temp = g_string_new ("");
8930 len = strlen (fullname);
8931 for (i = 0; i < len; ++i) {
8932 char c = fullname [i];
8933 if (isalnum (c)) {
8934 g_string_append_c (temp, c);
8935 } else if (c == '_') {
8936 g_string_append_c (temp, '_');
8937 g_string_append_c (temp, '_');
8938 } else {
8939 g_string_append_c (temp, '_');
8940 g_string_append_printf (temp, "%x", (int)c);
8943 temps = g_string_free (temp, FALSE);
8944 /* Include the length to avoid different length type names aliasing each other */
8945 g_string_append_printf (s, "cl%x_%s_", (int)strlen (temps), temps);
8946 g_free (temps);
8949 if (t->attrs)
8950 g_string_append_printf (s, "_attrs_%d", t->attrs);
8951 return TRUE;
8954 static gboolean
8955 append_mangled_signature (GString *s, MonoMethodSignature *sig)
8957 int i;
8958 gboolean supported;
8960 if (sig->pinvoke)
8961 g_string_append_printf (s, "pinvoke_");
8962 supported = append_mangled_type (s, sig->ret);
8963 if (!supported)
8964 return FALSE;
8965 g_string_append_printf (s, "_");
8966 if (sig->hasthis)
8967 g_string_append_printf (s, "this_");
8968 for (i = 0; i < sig->param_count; ++i) {
8969 supported = append_mangled_type (s, sig->params [i]);
8970 if (!supported)
8971 return FALSE;
8974 return TRUE;
8977 static void
8978 append_mangled_wrapper_type (GString *s, guint32 wrapper_type)
8980 const char *label;
8982 switch (wrapper_type) {
8983 case MONO_WRAPPER_REMOTING_INVOKE:
8984 label = "remoting_invoke";
8985 break;
8986 case MONO_WRAPPER_REMOTING_INVOKE_WITH_CHECK:
8987 label = "remoting_invoke_check";
8988 break;
8989 case MONO_WRAPPER_XDOMAIN_INVOKE:
8990 label = "remoting_invoke_xdomain";
8991 break;
8992 case MONO_WRAPPER_PROXY_ISINST:
8993 label = "proxy_isinst";
8994 break;
8995 case MONO_WRAPPER_LDFLD:
8996 label = "ldfld";
8997 break;
8998 case MONO_WRAPPER_LDFLDA:
8999 label = "ldflda";
9000 break;
9001 case MONO_WRAPPER_STFLD:
9002 label = "stfld";
9003 break;
9004 case MONO_WRAPPER_ALLOC:
9005 label = "alloc";
9006 break;
9007 case MONO_WRAPPER_WRITE_BARRIER:
9008 label = "write_barrier";
9009 break;
9010 case MONO_WRAPPER_STELEMREF:
9011 label = "stelemref";
9012 break;
9013 case MONO_WRAPPER_OTHER:
9014 label = "unknown";
9015 break;
9016 case MONO_WRAPPER_MANAGED_TO_NATIVE:
9017 label = "man2native";
9018 break;
9019 case MONO_WRAPPER_SYNCHRONIZED:
9020 label = "synch";
9021 break;
9022 case MONO_WRAPPER_MANAGED_TO_MANAGED:
9023 label = "man2man";
9024 break;
9025 case MONO_WRAPPER_CASTCLASS:
9026 label = "castclass";
9027 break;
9028 case MONO_WRAPPER_RUNTIME_INVOKE:
9029 label = "run_invoke";
9030 break;
9031 case MONO_WRAPPER_DELEGATE_INVOKE:
9032 label = "del_inv";
9033 break;
9034 case MONO_WRAPPER_DELEGATE_BEGIN_INVOKE:
9035 label = "del_beg_inv";
9036 break;
9037 case MONO_WRAPPER_DELEGATE_END_INVOKE:
9038 label = "del_end_inv";
9039 break;
9040 case MONO_WRAPPER_NATIVE_TO_MANAGED:
9041 label = "native2man";
9042 break;
9043 default:
9044 g_assert_not_reached ();
9047 g_string_append_printf (s, "%s_", label);
9050 static void
9051 append_mangled_wrapper_subtype (GString *s, WrapperSubtype subtype)
9053 const char *label;
9055 switch (subtype)
9057 case WRAPPER_SUBTYPE_NONE:
9058 return;
9059 case WRAPPER_SUBTYPE_ELEMENT_ADDR:
9060 label = "elem_addr";
9061 break;
9062 case WRAPPER_SUBTYPE_STRING_CTOR:
9063 label = "str_ctor";
9064 break;
9065 case WRAPPER_SUBTYPE_VIRTUAL_STELEMREF:
9066 label = "virt_stelem";
9067 break;
9068 case WRAPPER_SUBTYPE_FAST_MONITOR_ENTER:
9069 label = "fast_mon_enter";
9070 break;
9071 case WRAPPER_SUBTYPE_FAST_MONITOR_ENTER_V4:
9072 label = "fast_mon_enter_4";
9073 break;
9074 case WRAPPER_SUBTYPE_FAST_MONITOR_EXIT:
9075 label = "fast_monitor_exit";
9076 break;
9077 case WRAPPER_SUBTYPE_PTR_TO_STRUCTURE:
9078 label = "ptr2struct";
9079 break;
9080 case WRAPPER_SUBTYPE_STRUCTURE_TO_PTR:
9081 label = "struct2ptr";
9082 break;
9083 case WRAPPER_SUBTYPE_CASTCLASS_WITH_CACHE:
9084 label = "castclass_w_cache";
9085 break;
9086 case WRAPPER_SUBTYPE_ISINST_WITH_CACHE:
9087 label = "isinst_w_cache";
9088 break;
9089 case WRAPPER_SUBTYPE_RUNTIME_INVOKE_NORMAL:
9090 label = "run_inv_norm";
9091 break;
9092 case WRAPPER_SUBTYPE_RUNTIME_INVOKE_DYNAMIC:
9093 label = "run_inv_dyn";
9094 break;
9095 case WRAPPER_SUBTYPE_RUNTIME_INVOKE_DIRECT:
9096 label = "run_inv_dir";
9097 break;
9098 case WRAPPER_SUBTYPE_RUNTIME_INVOKE_VIRTUAL:
9099 label = "run_inv_vir";
9100 break;
9101 case WRAPPER_SUBTYPE_ICALL_WRAPPER:
9102 label = "icall";
9103 break;
9104 case WRAPPER_SUBTYPE_NATIVE_FUNC_AOT:
9105 label = "native_func_aot";
9106 break;
9107 case WRAPPER_SUBTYPE_PINVOKE:
9108 label = "pinvoke";
9109 break;
9110 case WRAPPER_SUBTYPE_SYNCHRONIZED_INNER:
9111 label = "synch_inner";
9112 break;
9113 case WRAPPER_SUBTYPE_GSHAREDVT_IN:
9114 label = "gshared_in";
9115 break;
9116 case WRAPPER_SUBTYPE_GSHAREDVT_OUT:
9117 label = "gshared_out";
9118 break;
9119 case WRAPPER_SUBTYPE_ARRAY_ACCESSOR:
9120 label = "array_acc";
9121 break;
9122 case WRAPPER_SUBTYPE_GENERIC_ARRAY_HELPER:
9123 label = "generic_arry_help";
9124 break;
9125 case WRAPPER_SUBTYPE_DELEGATE_INVOKE_VIRTUAL:
9126 label = "del_inv_virt";
9127 break;
9128 case WRAPPER_SUBTYPE_DELEGATE_INVOKE_BOUND:
9129 label = "del_inv_bound";
9130 break;
9131 case WRAPPER_SUBTYPE_INTERP_IN:
9132 label = "interp_in";
9133 break;
9134 case WRAPPER_SUBTYPE_INTERP_LMF:
9135 label = "interp_lmf";
9136 break;
9137 case WRAPPER_SUBTYPE_GSHAREDVT_IN_SIG:
9138 label = "gsharedvt_in_sig";
9139 break;
9140 case WRAPPER_SUBTYPE_GSHAREDVT_OUT_SIG:
9141 label = "gsharedvt_out_sig";
9142 break;
9143 case WRAPPER_SUBTYPE_AOT_INIT:
9144 label = "aot_init";
9145 break;
9146 default:
9147 g_assert_not_reached ();
9150 g_string_append_printf (s, "%s_", label);
9153 static char *
9154 sanitize_mangled_string (const char *input)
9156 GString *s = g_string_new ("");
9158 for (int i=0; input [i] != '\0'; i++) {
9159 char c = input [i];
9160 switch (c) {
9161 case '.':
9162 g_string_append (s, "_dot_");
9163 break;
9164 case ' ':
9165 g_string_append (s, "_");
9166 break;
9167 case '`':
9168 g_string_append (s, "_bt_");
9169 break;
9170 case '<':
9171 g_string_append (s, "_le_");
9172 break;
9173 case '>':
9174 g_string_append (s, "_gt_");
9175 break;
9176 case '/':
9177 g_string_append (s, "_sl_");
9178 break;
9179 case '[':
9180 g_string_append (s, "_lbrack_");
9181 break;
9182 case ']':
9183 g_string_append (s, "_rbrack_");
9184 break;
9185 case '(':
9186 g_string_append (s, "_lparen_");
9187 break;
9188 case '-':
9189 g_string_append (s, "_dash_");
9190 break;
9191 case ')':
9192 g_string_append (s, "_rparen_");
9193 break;
9194 case ',':
9195 g_string_append (s, "_comma_");
9196 break;
9197 case ':':
9198 g_string_append (s, "_colon_");
9199 break;
9200 default:
9201 g_string_append_c (s, c);
9205 return g_string_free (s, FALSE);
9208 static gboolean
9209 append_mangled_klass (GString *s, MonoClass *klass)
9211 char *klass_desc = mono_class_full_name (klass);
9212 g_string_append_printf (s, "_%s_%s_", m_class_get_name_space (klass), klass_desc);
9213 g_free (klass_desc);
9215 // Success
9216 return TRUE;
9219 static gboolean
9220 append_mangled_method (GString *s, MonoMethod *method);
9222 static gboolean
9223 append_mangled_wrapper (GString *s, MonoMethod *method)
9225 gboolean success = TRUE;
9226 gboolean append_sig = TRUE;
9227 WrapperInfo *info = mono_marshal_get_wrapper_info (method);
9228 g_string_append_printf (s, "wrapper_");
9229 /* Most wrappers are in mscorlib */
9230 if (m_class_get_image (method->klass) != mono_get_corlib ())
9231 g_string_append_printf (s, "%s_", m_class_get_image (method->klass)->assembly->aname.name);
9233 if (method->wrapper_type != MONO_WRAPPER_OTHER && method->wrapper_type != MONO_WRAPPER_MANAGED_TO_NATIVE)
9234 append_mangled_wrapper_type (s, method->wrapper_type);
9236 switch (method->wrapper_type) {
9237 case MONO_WRAPPER_REMOTING_INVOKE:
9238 case MONO_WRAPPER_REMOTING_INVOKE_WITH_CHECK:
9239 case MONO_WRAPPER_XDOMAIN_INVOKE: {
9240 MonoMethod *m = mono_marshal_method_from_wrapper (method);
9241 g_assert (m);
9242 success = success && append_mangled_method (s, m);
9243 break;
9245 case MONO_WRAPPER_PROXY_ISINST:
9246 case MONO_WRAPPER_LDFLD:
9247 case MONO_WRAPPER_LDFLDA:
9248 case MONO_WRAPPER_STFLD: {
9249 g_assert (info);
9250 success = success && append_mangled_klass (s, info->d.proxy.klass);
9251 break;
9253 case MONO_WRAPPER_ALLOC: {
9254 /* The GC name is saved once in MonoAotFileInfo */
9255 g_assert (info->d.alloc.alloc_type != -1);
9256 g_string_append_printf (s, "%d_", info->d.alloc.alloc_type);
9257 // SlowAlloc, etc
9258 g_string_append_printf (s, "%s_", method->name);
9259 break;
9261 case MONO_WRAPPER_WRITE_BARRIER: {
9262 g_string_append_printf (s, "%s_", method->name);
9263 break;
9265 case MONO_WRAPPER_STELEMREF: {
9266 append_mangled_wrapper_subtype (s, info->subtype);
9267 if (info->subtype == WRAPPER_SUBTYPE_VIRTUAL_STELEMREF)
9268 g_string_append_printf (s, "%d", info->d.virtual_stelemref.kind);
9269 break;
9271 case MONO_WRAPPER_OTHER: {
9272 append_mangled_wrapper_subtype (s, info->subtype);
9273 if (info->subtype == WRAPPER_SUBTYPE_PTR_TO_STRUCTURE ||
9274 info->subtype == WRAPPER_SUBTYPE_STRUCTURE_TO_PTR)
9275 success = success && append_mangled_klass (s, method->klass);
9276 else if (info->subtype == WRAPPER_SUBTYPE_SYNCHRONIZED_INNER)
9277 success = success && append_mangled_method (s, info->d.synchronized_inner.method);
9278 else if (info->subtype == WRAPPER_SUBTYPE_ARRAY_ACCESSOR)
9279 success = success && append_mangled_method (s, info->d.array_accessor.method);
9280 else if (info->subtype == WRAPPER_SUBTYPE_INTERP_IN)
9281 append_mangled_signature (s, info->d.interp_in.sig);
9282 else if (info->subtype == WRAPPER_SUBTYPE_GSHAREDVT_IN_SIG) {
9283 append_mangled_signature (s, info->d.gsharedvt.sig);
9284 append_sig = FALSE;
9285 } else if (info->subtype == WRAPPER_SUBTYPE_GSHAREDVT_OUT_SIG) {
9286 append_mangled_signature (s, info->d.gsharedvt.sig);
9287 append_sig = FALSE;
9288 } else if (info->subtype == WRAPPER_SUBTYPE_INTERP_LMF)
9289 g_string_append_printf (s, "%s", method->name);
9290 else if (info->subtype == WRAPPER_SUBTYPE_AOT_INIT) {
9291 g_string_append_printf (s, "%s_%d_", m_class_get_image (method->klass)->assembly->aname.name, info->d.aot_init.subtype);
9292 append_sig = FALSE;
9294 break;
9296 case MONO_WRAPPER_MANAGED_TO_NATIVE: {
9297 append_mangled_wrapper_subtype (s, info->subtype);
9298 if (info->subtype == WRAPPER_SUBTYPE_ICALL_WRAPPER) {
9299 const char *name = method->name;
9300 const char *prefix = "__icall_wrapper_";
9301 if (strstr (name, prefix) == name)
9302 name += strlen (prefix);
9303 g_string_append_printf (s, "%s", name);
9304 append_sig = FALSE;
9305 } else if (info->subtype == WRAPPER_SUBTYPE_NATIVE_FUNC_AOT) {
9306 success = success && append_mangled_method (s, info->d.managed_to_native.method);
9307 } else {
9308 g_assert (info->subtype == WRAPPER_SUBTYPE_NONE || info->subtype == WRAPPER_SUBTYPE_PINVOKE);
9309 success = success && append_mangled_method (s, info->d.managed_to_native.method);
9311 break;
9313 case MONO_WRAPPER_SYNCHRONIZED: {
9314 MonoMethod *m;
9316 m = mono_marshal_method_from_wrapper (method);
9317 g_assert (m);
9318 g_assert (m != method);
9319 success = success && append_mangled_method (s, m);
9320 break;
9322 case MONO_WRAPPER_MANAGED_TO_MANAGED: {
9323 append_mangled_wrapper_subtype (s, info->subtype);
9325 if (info->subtype == WRAPPER_SUBTYPE_ELEMENT_ADDR) {
9326 g_string_append_printf (s, "%d_", info->d.element_addr.rank);
9327 g_string_append_printf (s, "%d_", info->d.element_addr.elem_size);
9328 } else if (info->subtype == WRAPPER_SUBTYPE_STRING_CTOR) {
9329 success = success && append_mangled_method (s, info->d.string_ctor.method);
9330 } else if (info->subtype == WRAPPER_SUBTYPE_GENERIC_ARRAY_HELPER) {
9331 success = success && append_mangled_method (s, info->d.generic_array_helper.method);
9332 } else {
9333 success = FALSE;
9335 break;
9337 case MONO_WRAPPER_CASTCLASS: {
9338 append_mangled_wrapper_subtype (s, info->subtype);
9339 break;
9341 case MONO_WRAPPER_RUNTIME_INVOKE: {
9342 append_mangled_wrapper_subtype (s, info->subtype);
9343 if (info->subtype == WRAPPER_SUBTYPE_RUNTIME_INVOKE_DIRECT || info->subtype == WRAPPER_SUBTYPE_RUNTIME_INVOKE_VIRTUAL)
9344 success = success && append_mangled_method (s, info->d.runtime_invoke.method);
9345 else if (info->subtype == WRAPPER_SUBTYPE_RUNTIME_INVOKE_NORMAL)
9346 success = success && append_mangled_signature (s, info->d.runtime_invoke.sig);
9347 break;
9349 case MONO_WRAPPER_DELEGATE_INVOKE:
9350 case MONO_WRAPPER_DELEGATE_BEGIN_INVOKE:
9351 case MONO_WRAPPER_DELEGATE_END_INVOKE: {
9352 if (method->is_inflated) {
9353 /* These wrappers are identified by their class */
9354 g_string_append_printf (s, "i_");
9355 success = success && append_mangled_klass (s, method->klass);
9356 } else {
9357 WrapperInfo *info = mono_marshal_get_wrapper_info (method);
9359 g_string_append_printf (s, "u_");
9360 if (method->wrapper_type == MONO_WRAPPER_DELEGATE_INVOKE)
9361 append_mangled_wrapper_subtype (s, info->subtype);
9362 g_string_append_printf (s, "u_sigstart");
9364 break;
9366 case MONO_WRAPPER_NATIVE_TO_MANAGED: {
9367 g_assert (info);
9368 success = success && append_mangled_method (s, info->d.native_to_managed.method);
9369 success = success && append_mangled_klass (s, method->klass);
9370 break;
9372 default:
9373 g_assert_not_reached ();
9375 if (success && append_sig)
9376 success = append_mangled_signature (s, mono_method_signature_internal (method));
9377 return success;
9380 static void
9381 append_mangled_ginst (GString *str, MonoGenericInst *ginst)
9383 int i;
9385 for (i = 0; i < ginst->type_argc; ++i) {
9386 if (i > 0)
9387 g_string_append (str, ", ");
9388 MonoType *type = ginst->type_argv [i];
9389 switch (type->type) {
9390 case MONO_TYPE_VAR:
9391 case MONO_TYPE_MVAR: {
9392 MonoType *constraint = NULL;
9393 if (type->data.generic_param)
9394 constraint = type->data.generic_param->gshared_constraint;
9395 if (constraint) {
9396 g_assert (constraint->type != MONO_TYPE_VAR && constraint->type != MONO_TYPE_MVAR);
9397 g_string_append (str, "gshared:");
9398 mono_type_get_desc (str, constraint, TRUE);
9399 break;
9401 // Else falls through to common case
9403 default:
9404 mono_type_get_desc (str, type, TRUE);
9409 static void
9410 append_mangled_context (GString *str, MonoGenericContext *context)
9412 GString *res = g_string_new ("");
9414 g_string_append_printf (res, "gens_");
9415 g_string_append (res, "00");
9417 gboolean good = context->class_inst && context->class_inst->type_argc > 0;
9418 good = good || (context->method_inst && context->method_inst->type_argc > 0);
9419 g_assert (good);
9421 if (context->class_inst)
9422 append_mangled_ginst (res, context->class_inst);
9423 if (context->method_inst) {
9424 if (context->class_inst)
9425 g_string_append (res, "11");
9426 append_mangled_ginst (res, context->method_inst);
9428 g_string_append_printf (str, "gens_%s", res->str);
9429 g_free (res);
9432 static gboolean
9433 append_mangled_method (GString *s, MonoMethod *method)
9435 if (method->wrapper_type)
9436 return append_mangled_wrapper (s, method);
9438 if (method->is_inflated) {
9439 g_string_append_printf (s, "inflated_");
9440 MonoMethodInflated *imethod = (MonoMethodInflated*) method;
9441 g_assert (imethod->context.class_inst != NULL || imethod->context.method_inst != NULL);
9443 append_mangled_context (s, &imethod->context);
9444 g_string_append_printf (s, "_declared_by_%s_", m_class_get_image (imethod->declaring->klass)->assembly->aname.name);
9445 append_mangled_method (s, imethod->declaring);
9446 } else if (method->is_generic) {
9447 g_string_append_printf (s, "%s_", m_class_get_image (method->klass)->assembly->aname.name);
9449 g_string_append_printf (s, "generic_");
9450 append_mangled_klass (s, method->klass);
9451 g_string_append_printf (s, "_%s_", method->name);
9453 MonoGenericContainer *container = mono_method_get_generic_container (method);
9454 g_string_append_printf (s, "_");
9455 append_mangled_context (s, &container->context);
9457 return append_mangled_signature (s, mono_method_signature_internal (method));
9458 } else {
9459 g_string_append_printf (s, "%s", m_class_get_image (method->klass)->assembly->aname.name);
9460 append_mangled_klass (s, method->klass);
9461 g_string_append_printf (s, "_%s_", method->name);
9462 if (!append_mangled_signature (s, mono_method_signature_internal (method))) {
9463 g_string_free (s, TRUE);
9464 return FALSE;
9468 return TRUE;
9472 * mono_aot_get_mangled_method_name:
9474 * Return a unique mangled name for METHOD, or NULL.
9476 char*
9477 mono_aot_get_mangled_method_name (MonoMethod *method)
9479 // FIXME: use static cache (mempool?)
9480 // We call this a *lot*
9482 GString *s = g_string_new ("aot_");
9483 if (!append_mangled_method (s, method)) {
9484 g_string_free (s, TRUE);
9485 return NULL;
9486 } else {
9487 char *out = g_string_free (s, FALSE);
9488 // Scrub method and class names
9489 char *cleaned = sanitize_mangled_string (out);
9490 g_free (out);
9491 return cleaned;
9495 gboolean
9496 mono_aot_is_direct_callable (MonoJumpInfo *patch_info)
9498 return is_direct_callable (llvm_acfg, NULL, patch_info);
9501 void
9502 mono_aot_mark_unused_llvm_plt_entry (MonoJumpInfo *patch_info)
9504 MonoPltEntry *plt_entry;
9506 plt_entry = get_plt_entry (llvm_acfg, patch_info);
9507 plt_entry->llvm_used = FALSE;
9510 char*
9511 mono_aot_get_direct_call_symbol (MonoJumpInfoType type, gconstpointer data)
9513 const char *sym = NULL;
9515 if (llvm_acfg->aot_opts.direct_icalls) {
9516 if (type == MONO_PATCH_INFO_JIT_ICALL_ADDR) {
9517 /* Call to a C function implementing a jit icall */
9518 sym = mono_lookup_jit_icall_symbol ((const char *)data);
9519 } else if (type == MONO_PATCH_INFO_ICALL_ADDR_CALL) {
9520 MonoMethod *method = (MonoMethod *)data;
9521 if (!(method->flags & METHOD_ATTRIBUTE_PINVOKE_IMPL))
9522 sym = lookup_icall_symbol_name_aot (method);
9523 else if (llvm_acfg->aot_opts.direct_pinvoke)
9524 sym = get_pinvoke_import (llvm_acfg, method);
9525 } else if (type == MONO_PATCH_INFO_JIT_ICALL_ID) {
9526 MonoJitICallInfo const * const info = mono_find_jit_icall_info ((MonoJitICallId)(gsize)data);
9527 char const * const name = info->c_symbol;
9528 if (name && info->func == info->wrapper)
9529 sym = name;
9531 if (sym)
9532 return g_strdup (sym);
9534 return NULL;
9537 char*
9538 mono_aot_get_plt_symbol (MonoJumpInfoType type, gconstpointer data)
9540 MonoJumpInfo *ji = (MonoJumpInfo *)mono_mempool_alloc (llvm_acfg->mempool, sizeof (MonoJumpInfo));
9541 MonoPltEntry *plt_entry;
9542 const char *sym = NULL;
9544 ji->type = type;
9545 ji->data.target = data;
9547 if (!can_encode_patch (llvm_acfg, ji))
9548 return NULL;
9550 if (llvm_acfg->aot_opts.direct_icalls) {
9551 if (type == MONO_PATCH_INFO_JIT_ICALL_ADDR) {
9552 /* Call to a C function implementing a jit icall */
9553 sym = mono_lookup_jit_icall_symbol ((const char *)data);
9554 } else if (type == MONO_PATCH_INFO_ICALL_ADDR_CALL) {
9555 MonoMethod *method = (MonoMethod *)data;
9556 if (!(method->flags & METHOD_ATTRIBUTE_PINVOKE_IMPL))
9557 sym = lookup_icall_symbol_name_aot (method);
9559 if (sym)
9560 return g_strdup (sym);
9563 plt_entry = get_plt_entry (llvm_acfg, ji);
9564 plt_entry->llvm_used = TRUE;
9566 #if defined(TARGET_MACH)
9567 return g_strdup (plt_entry->llvm_symbol + strlen (llvm_acfg->llvm_label_prefix));
9568 #else
9569 return g_strdup (plt_entry->llvm_symbol);
9570 #endif
9574 mono_aot_get_method_index (MonoMethod *method)
9576 g_assert (llvm_acfg);
9577 return get_method_index (llvm_acfg, method);
9580 MonoJumpInfo*
9581 mono_aot_patch_info_dup (MonoJumpInfo* ji)
9583 MonoJumpInfo *res;
9585 mono_acfg_lock (llvm_acfg);
9586 res = mono_patch_info_dup_mp (llvm_acfg->mempool, ji);
9587 mono_acfg_unlock (llvm_acfg);
9589 return res;
9592 static int
9593 execute_system (const char * command)
9595 int status = 0;
9597 #if G_HAVE_API_SUPPORT(HAVE_CLASSIC_WINAPI_SUPPORT) && defined(HOST_WIN32)
9598 // We need an extra set of quotes around the whole command to properly handle commands
9599 // with spaces since internally the command is called through "cmd /c.
9600 char * quoted_command = g_strdup_printf ("\"%s\"", command);
9602 int size = MultiByteToWideChar (CP_UTF8, 0 , quoted_command , -1, NULL , 0);
9603 wchar_t* wstr = g_malloc (sizeof (wchar_t) * size);
9604 MultiByteToWideChar (CP_UTF8, 0, quoted_command, -1, wstr , size);
9605 status = _wsystem (wstr);
9606 g_free (wstr);
9608 g_free (quoted_command);
9609 #elif defined (HAVE_SYSTEM)
9610 status = system (command);
9611 #else
9612 g_assert_not_reached ();
9613 #endif
9615 return status;
9618 #ifdef ENABLE_LLVM
9621 * emit_llvm_file:
9623 * Emit the LLVM code into an LLVM bytecode file, and compile it using the LLVM
9624 * tools.
9626 static gboolean
9627 emit_llvm_file (MonoAotCompile *acfg)
9629 char *command, *opts, *tempbc, *optbc, *output_fname;
9631 if (acfg->aot_opts.llvm_only && acfg->aot_opts.asm_only) {
9632 if (acfg->aot_opts.no_opt)
9633 tempbc = g_strdup (acfg->aot_opts.llvm_outfile);
9634 else
9635 tempbc = g_strdup_printf ("%s.bc", acfg->tmpbasename);
9636 optbc = g_strdup (acfg->aot_opts.llvm_outfile);
9637 } else {
9638 tempbc = g_strdup_printf ("%s.bc", acfg->tmpbasename);
9639 optbc = g_strdup_printf ("%s.opt.bc", acfg->tmpbasename);
9642 mono_llvm_emit_aot_module (tempbc, g_path_get_basename (acfg->image->name));
9644 if (acfg->aot_opts.no_opt)
9645 return TRUE;
9647 * FIXME: Experiment with adding optimizations, the -std-compile-opts set takes
9648 * a lot of time, and doesn't seem to save much space.
9649 * The following optimizations cannot be enabled:
9650 * - 'tailcallelim'
9651 * - 'jump-threading' changes our blockaddress references to int constants.
9652 * - 'basiccg' fails because it contains:
9653 * if (CS && !isa<IntrinsicInst>(II)) {
9654 * and isa<IntrinsicInst> is false for invokes to intrinsics (iltests.exe).
9655 * - 'prune-eh' and 'functionattrs' depend on 'basiccg'.
9656 * The opt list below was produced by taking the output of:
9657 * llvm-as < /dev/null | opt -O2 -disable-output -debug-pass=Arguments
9658 * then removing tailcallelim + the global opts.
9659 * strip-dead-prototypes deletes unused intrinsics definitions.
9661 /* The dse pass is disabled because of #13734 and #17616 */
9663 * The dse bug is in DeadStoreElimination.cpp:isOverwrite ():
9664 * // If we have no DataLayout information around, then the size of the store
9665 * // is inferrable from the pointee type. If they are the same type, then
9666 * // we know that the store is safe.
9667 * if (AA.getDataLayout() == 0 &&
9668 * Later.Ptr->getType() == Earlier.Ptr->getType()) {
9669 * return OverwriteComplete;
9670 * Here, if 'Earlier' refers to a memset, and Later has no size info, it mistakenly thinks the memset is redundant.
9672 if (acfg->aot_opts.llvm_only) {
9673 // FIXME: This doesn't work yet
9674 opts = g_strdup ("");
9675 } else {
9676 #if LLVM_API_VERSION > 100
9677 opts = g_strdup ("-O2 -disable-tail-calls -place-safepoints -spp-all-backedges");
9678 #else
9679 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 -place-safepoints -spp-all-backedges");
9680 #endif
9681 if (acfg->aot_opts.llvm_opts) {
9682 opts = g_strdup_printf ("%s %s", opts, acfg->aot_opts.llvm_opts);
9686 command = g_strdup_printf ("\"%sopt\" -f %s -o \"%s\" \"%s\"", acfg->aot_opts.llvm_path, opts, optbc, tempbc);
9687 aot_printf (acfg, "Executing opt: %s\n", command);
9688 if (execute_system (command) != 0)
9689 return FALSE;
9690 g_free (opts);
9692 if (acfg->aot_opts.llvm_only && acfg->aot_opts.asm_only)
9693 /* Nothing else to do */
9694 return TRUE;
9696 if (acfg->aot_opts.llvm_only) {
9697 /* Use the stock clang from xcode */
9698 // FIXME: arch
9699 command = g_strdup_printf ("%s -fexceptions -fpic -O2 -fno-optimize-sibling-calls -Wno-override-module -c -o \"%s\" \"%s.opt.bc\"", acfg->aot_opts.clangxx, acfg->llvm_ofile, acfg->tmpbasename);
9701 aot_printf (acfg, "Executing clang: %s\n", command);
9702 if (execute_system (command) != 0)
9703 return FALSE;
9704 return TRUE;
9707 if (!acfg->llc_args)
9708 acfg->llc_args = g_string_new ("");
9710 /* Verbose asm slows down llc greatly */
9711 g_string_append (acfg->llc_args, " -asm-verbose=false");
9713 if (acfg->aot_opts.mtriple)
9714 g_string_append_printf (acfg->llc_args, " -mtriple=%s", acfg->aot_opts.mtriple);
9716 #if defined(TARGET_X86_64_WIN32_MSVC) && LLVM_API_VERSION >= 600
9717 if (!acfg->aot_opts.mtriple)
9718 g_string_append_printf (acfg->llc_args, " -mtriple=%s", "x86_64-pc-windows-msvc");
9719 #endif
9721 g_string_append (acfg->llc_args, " -disable-gnu-eh-frame -enable-mono-eh-frame");
9723 g_string_append_printf (acfg->llc_args, " -mono-eh-frame-symbol=%s%s", acfg->user_symbol_prefix, acfg->llvm_eh_frame_symbol);
9725 #if LLVM_API_VERSION > 100
9726 g_string_append_printf (acfg->llc_args, " -disable-tail-calls");
9727 #endif
9729 #if LLVM_API_VERSION > 500 && (defined(TARGET_AMD64) || defined(TARGET_X86))
9730 /* This generates stack adjustments in the middle of functions breaking unwind info */
9731 g_string_append_printf (acfg->llc_args, " -no-x86-call-frame-opt");
9732 #endif
9734 #if ( defined(TARGET_MACH) && defined(TARGET_ARM) ) || defined(TARGET_ORBIS) || defined(TARGET_X86_64_WIN32_MSVC)
9735 g_string_append_printf (acfg->llc_args, " -relocation-model=pic");
9736 #else
9737 if (llvm_acfg->aot_opts.static_link)
9738 g_string_append_printf (acfg->llc_args, " -relocation-model=static");
9739 else
9740 g_string_append_printf (acfg->llc_args, " -relocation-model=pic");
9741 #endif
9743 if (acfg->llvm_owriter) {
9744 /* Emit an object file directly */
9745 output_fname = g_strdup_printf ("%s", acfg->llvm_ofile);
9746 g_string_append_printf (acfg->llc_args, " -filetype=obj");
9747 } else {
9748 output_fname = g_strdup_printf ("%s", acfg->llvm_sfile);
9751 if (acfg->aot_opts.llvm_llc) {
9752 g_string_append_printf (acfg->llc_args, " %s", acfg->aot_opts.llvm_llc);
9755 command = g_strdup_printf ("\"%sllc\" %s -o \"%s\" \"%s.opt.bc\"", acfg->aot_opts.llvm_path, acfg->llc_args->str, output_fname, acfg->tmpbasename);
9756 g_free (output_fname);
9758 aot_printf (acfg, "Executing llc: %s\n", command);
9760 if (execute_system (command) != 0)
9761 return FALSE;
9762 return TRUE;
9764 #endif
9766 /* Set the skip flag for methods which do not need to be emitted because of dedup */
9767 static void
9768 dedup_skip_methods (MonoAotCompile *acfg)
9770 int oindex, i;
9772 if (acfg->aot_opts.llvm_only)
9773 return;
9775 for (oindex = 0; oindex < acfg->method_order->len; ++oindex) {
9776 MonoCompile *cfg;
9777 MonoMethod *method;
9779 i = GPOINTER_TO_UINT (g_ptr_array_index (acfg->method_order, oindex));
9781 cfg = acfg->cfgs [i];
9783 if (!cfg)
9784 continue;
9786 method = cfg->orig_method;
9788 gboolean dedup_collect = acfg->aot_opts.dedup || (acfg->aot_opts.dedup_include && !acfg->dedup_emit_mode);
9789 gboolean dedupable = mono_aot_can_dedup (method);
9791 // cfg->skip is vital for LLVM to work, can't just continue in this loop
9792 if (dedupable && strcmp (method->name, "wbarrier_conc") && dedup_collect) {
9793 mono_dedup_cache_method (acfg, method);
9795 // Don't compile inflated methods if we're in first phase of
9796 // dedup
9798 // In second phase, we emit methods that
9799 // are dedupable. We also emit later methods
9800 // which are referenced by them and added later.
9801 // For this reason, when in the dedup_include mode,
9802 // we never set skip.
9803 if (acfg->aot_opts.dedup)
9804 cfg->skip = TRUE;
9807 // Don't compile anything in this mode
9808 if (acfg->aot_opts.dedup_include && !acfg->dedup_emit_mode)
9809 cfg->skip = TRUE;
9811 // Compile everything in this mode
9812 if (acfg->aot_opts.dedup_include && acfg->dedup_emit_mode)
9813 cfg->skip = FALSE;
9815 /*if (dedup_collect) {*/
9816 /*char *name = mono_aot_get_mangled_method_name (method);*/
9818 /*if (ignore_cfg (cfg))*/
9819 /*aot_printf (acfg, "Dedup Skipping %s\n", acfg->image->name, name);*/
9820 /*else*/
9821 /*aot_printf (acfg, "Dedup Keeping %s\n", acfg->image->name, name);*/
9823 /*g_free (name);*/
9824 /*}*/
9828 static void
9829 emit_code (MonoAotCompile *acfg)
9831 int oindex, i, prev_index;
9832 gboolean saved_unbox_info = FALSE; // See mono_aot_get_unbox_trampoline.
9833 char symbol [MAX_SYMBOL_SIZE];
9835 if (acfg->aot_opts.llvm_only)
9836 return;
9838 #if defined(TARGET_POWERPC64)
9839 sprintf (symbol, ".Lgot_addr");
9840 emit_section_change (acfg, ".text", 0);
9841 emit_alignment (acfg, 8);
9842 emit_label (acfg, symbol);
9843 emit_pointer (acfg, acfg->got_symbol);
9844 #endif
9847 * This global symbol is used to compute the address of each method using the
9848 * code_offsets array. It is also used to compute the memory ranges occupied by
9849 * AOT code, so it must be equal to the address of the first emitted method.
9851 emit_section_change (acfg, ".text", 0);
9852 emit_alignment_code (acfg, 8);
9853 emit_info_symbol (acfg, "jit_code_start", TRUE);
9856 * Emit some padding so the local symbol for the first method doesn't have the
9857 * same address as 'methods'.
9859 emit_padding (acfg, 16);
9861 for (oindex = 0; oindex < acfg->method_order->len; ++oindex) {
9862 MonoCompile *cfg;
9863 MonoMethod *method;
9865 i = GPOINTER_TO_UINT (g_ptr_array_index (acfg->method_order, oindex));
9867 cfg = acfg->cfgs [i];
9869 if (!cfg)
9870 continue;
9872 method = cfg->orig_method;
9874 if (ignore_cfg (cfg))
9875 continue;
9877 /* Emit unbox trampoline */
9878 if (mono_aot_mode_is_full (&acfg->aot_opts) && m_class_is_valuetype (cfg->orig_method->klass)) {
9879 sprintf (symbol, "ut_%d", get_method_index (acfg, method));
9881 emit_section_change (acfg, ".text", 0);
9883 if (acfg->thumb_mixed && cfg->compile_llvm) {
9884 emit_set_thumb_mode (acfg);
9885 fprintf (acfg->fp, "\n.thumb_func\n");
9888 emit_label (acfg, symbol);
9890 arch_emit_unbox_trampoline (acfg, cfg, cfg->orig_method, cfg->asm_symbol);
9892 if (acfg->thumb_mixed && cfg->compile_llvm)
9893 emit_set_arm_mode (acfg);
9895 if (!saved_unbox_info) {
9896 char user_symbol [128];
9897 GSList *unwind_ops;
9898 sprintf (user_symbol, "%sunbox_trampoline_p", acfg->user_symbol_prefix);
9900 emit_label (acfg, "ut_end");
9902 unwind_ops = mono_unwind_get_cie_program ();
9903 save_unwind_info (acfg, user_symbol, unwind_ops);
9904 mono_free_unwind_info (unwind_ops);
9906 /* Save the unbox trampoline size */
9907 #ifdef TARGET_AMD64
9908 // LLVM unbox trampolines vary in size, 6 or 9 bytes,
9909 // due to the last instruction being 2 or 5 bytes.
9910 // There is no need to describe interior bytes of instructions
9911 // however, so state the size as if the last instruction is size 1.
9912 emit_int32 (acfg, 5);
9913 #else
9914 emit_symbol_diff (acfg, "ut_end", symbol, 0);
9915 #endif
9916 saved_unbox_info = TRUE;
9920 if (cfg->compile_llvm) {
9921 acfg->stats.llvm_count ++;
9922 } else {
9923 emit_method_code (acfg, cfg);
9927 emit_section_change (acfg, ".text", 0);
9928 emit_alignment_code (acfg, 8);
9929 emit_info_symbol (acfg, "jit_code_end", TRUE);
9931 /* To distinguish it from the next symbol */
9932 emit_padding (acfg, 4);
9935 * Add .no_dead_strip directives for all LLVM methods to prevent the OSX linker
9936 * from optimizing them away, since it doesn't see that code_offsets references them.
9937 * JITted methods don't need this since they are referenced using assembler local
9938 * symbols.
9939 * FIXME: This is why write-symbols doesn't work on OSX ?
9941 if (acfg->llvm && acfg->need_no_dead_strip) {
9942 fprintf (acfg->fp, "\n");
9943 for (i = 0; i < acfg->nmethods; ++i) {
9944 if (acfg->cfgs [i] && acfg->cfgs [i]->compile_llvm)
9945 fprintf (acfg->fp, ".no_dead_strip %s\n", acfg->cfgs [i]->asm_symbol);
9950 * To work around linker issues, we emit a table of branches, and disassemble them at runtime.
9951 * This is PIE code, and the linker can update it if needed.
9954 sprintf (symbol, "method_addresses");
9955 emit_section_change (acfg, ".text", 1);
9956 emit_alignment_code (acfg, 8);
9957 emit_info_symbol (acfg, symbol, TRUE);
9958 if (acfg->aot_opts.write_symbols)
9959 emit_local_symbol (acfg, symbol, "method_addresses_end", TRUE);
9960 emit_unset_mode (acfg);
9961 if (acfg->need_no_dead_strip)
9962 fprintf (acfg->fp, " .no_dead_strip %s\n", symbol);
9964 for (i = 0; i < acfg->nmethods; ++i) {
9965 #ifdef MONO_ARCH_AOT_SUPPORTED
9966 int call_size;
9968 if (!ignore_cfg (acfg->cfgs [i])) {
9969 arch_emit_label_address (acfg, acfg->cfgs [i]->asm_symbol, FALSE, acfg->thumb_mixed && acfg->cfgs [i]->compile_llvm, NULL, &call_size);
9970 } else {
9971 arch_emit_label_address (acfg, symbol, FALSE, FALSE, NULL, &call_size);
9973 #endif
9976 sprintf (symbol, "method_addresses_end");
9977 emit_label (acfg, symbol);
9978 emit_line (acfg);
9980 /* Emit a sorted table mapping methods to the index of their unbox trampolines */
9981 sprintf (symbol, "unbox_trampolines");
9982 emit_section_change (acfg, RODATA_SECT, 0);
9983 emit_alignment (acfg, 8);
9984 emit_info_symbol (acfg, symbol, FALSE);
9986 prev_index = -1;
9987 for (i = 0; i < acfg->nmethods; ++i) {
9988 MonoCompile *cfg;
9989 MonoMethod *method;
9990 int index;
9992 cfg = acfg->cfgs [i];
9993 if (ignore_cfg (cfg))
9994 continue;
9996 method = cfg->orig_method;
9998 if (mono_aot_mode_is_full (&acfg->aot_opts) && m_class_is_valuetype (cfg->orig_method->klass)) {
9999 index = get_method_index (acfg, method);
10001 emit_int32 (acfg, index);
10002 /* Make sure the table is sorted by index */
10003 g_assert (index > prev_index);
10004 prev_index = index;
10007 sprintf (symbol, "unbox_trampolines_end");
10008 emit_info_symbol (acfg, symbol, FALSE);
10009 emit_int32 (acfg, 0);
10011 /* Emit a separate table with the trampoline addresses/offsets */
10012 sprintf (symbol, "unbox_trampoline_addresses");
10013 emit_section_change (acfg, ".text", 0);
10014 emit_alignment_code (acfg, 8);
10015 emit_info_symbol (acfg, symbol, TRUE);
10017 for (i = 0; i < acfg->nmethods; ++i) {
10018 MonoCompile *cfg;
10019 MonoMethod *method;
10020 int index;
10022 cfg = acfg->cfgs [i];
10023 if (ignore_cfg (cfg))
10024 continue;
10026 method = cfg->orig_method;
10028 if (mono_aot_mode_is_full (&acfg->aot_opts) && m_class_is_valuetype (cfg->orig_method->klass)) {
10029 #ifdef MONO_ARCH_AOT_SUPPORTED
10030 int call_size;
10032 index = get_method_index (acfg, method);
10033 sprintf (symbol, "ut_%d", index);
10035 arch_emit_direct_call (acfg, symbol, FALSE, acfg->thumb_mixed && cfg->compile_llvm, NULL, &call_size);
10036 #endif
10039 emit_int32 (acfg, 0);
10042 static void
10043 emit_info (MonoAotCompile *acfg)
10045 int oindex, i;
10046 gint32 *offsets;
10048 offsets = g_new0 (gint32, acfg->nmethods);
10050 for (oindex = 0; oindex < acfg->method_order->len; ++oindex) {
10051 i = GPOINTER_TO_UINT (g_ptr_array_index (acfg->method_order, oindex));
10053 if (acfg->cfgs [i]) {
10054 emit_method_info (acfg, acfg->cfgs [i]);
10055 offsets [i] = acfg->cfgs [i]->method_info_offset;
10056 } else {
10057 offsets [i] = 0;
10061 acfg->stats.offsets_size += emit_offset_table (acfg, "method_info_offsets", MONO_AOT_TABLE_METHOD_INFO_OFFSETS, acfg->nmethods, 10, offsets);
10063 g_free (offsets);
10066 #endif /* #if !defined(DISABLE_AOT) && !defined(DISABLE_JIT) */
10068 #define rot(x,k) (((x)<<(k)) | ((x)>>(32-(k))))
10069 #define mix(a,b,c) { \
10070 a -= c; a ^= rot(c, 4); c += b; \
10071 b -= a; b ^= rot(a, 6); a += c; \
10072 c -= b; c ^= rot(b, 8); b += a; \
10073 a -= c; a ^= rot(c,16); c += b; \
10074 b -= a; b ^= rot(a,19); a += c; \
10075 c -= b; c ^= rot(b, 4); b += a; \
10077 #define mono_final(a,b,c) { \
10078 c ^= b; c -= rot(b,14); \
10079 a ^= c; a -= rot(c,11); \
10080 b ^= a; b -= rot(a,25); \
10081 c ^= b; c -= rot(b,16); \
10082 a ^= c; a -= rot(c,4); \
10083 b ^= a; b -= rot(a,14); \
10084 c ^= b; c -= rot(b,24); \
10087 static guint
10088 mono_aot_type_hash (MonoType *t1)
10090 guint hash = t1->type;
10092 hash |= t1->byref << 6; /* do not collide with t1->type values */
10093 switch (t1->type) {
10094 case MONO_TYPE_VALUETYPE:
10095 case MONO_TYPE_CLASS:
10096 case MONO_TYPE_SZARRAY:
10097 /* check if the distribution is good enough */
10098 return ((hash << 5) - hash) ^ mono_metadata_str_hash (m_class_get_name (t1->data.klass));
10099 case MONO_TYPE_PTR:
10100 return ((hash << 5) - hash) ^ mono_metadata_type_hash (t1->data.type);
10101 case MONO_TYPE_ARRAY:
10102 return ((hash << 5) - hash) ^ mono_metadata_type_hash (m_class_get_byval_arg (t1->data.array->eklass));
10103 case MONO_TYPE_GENERICINST:
10104 return ((hash << 5) - hash) ^ 0;
10105 default:
10106 return hash;
10111 * mono_aot_method_hash:
10113 * Return a hash code for methods which only depends on metadata.
10115 guint32
10116 mono_aot_method_hash (MonoMethod *method)
10118 MonoMethodSignature *sig;
10119 MonoClass *klass;
10120 int i, hindex;
10121 int hashes_count;
10122 guint32 *hashes_start, *hashes;
10123 guint32 a, b, c;
10124 MonoGenericInst *class_ginst = NULL;
10125 MonoGenericInst *ginst = NULL;
10127 /* Similar to the hash in mono_method_get_imt_slot () */
10129 sig = mono_method_signature_internal (method);
10131 if (mono_class_is_ginst (method->klass))
10132 class_ginst = mono_class_get_generic_class (method->klass)->context.class_inst;
10133 if (method->is_inflated)
10134 ginst = ((MonoMethodInflated*)method)->context.method_inst;
10136 hashes_count = sig->param_count + 5 + (class_ginst ? class_ginst->type_argc : 0) + (ginst ? ginst->type_argc : 0);
10137 hashes_start = (guint32 *)g_malloc0 (hashes_count * sizeof (guint32));
10138 hashes = hashes_start;
10140 /* Some wrappers are assigned to random classes */
10141 if (!method->wrapper_type || method->wrapper_type == MONO_WRAPPER_REMOTING_INVOKE_WITH_CHECK)
10142 klass = method->klass;
10143 else
10144 klass = mono_defaults.object_class;
10146 if (!method->wrapper_type) {
10147 char *full_name;
10149 if (mono_class_is_ginst (klass))
10150 full_name = mono_type_full_name (m_class_get_byval_arg (mono_class_get_generic_class (klass)->container_class));
10151 else
10152 full_name = mono_type_full_name (m_class_get_byval_arg (klass));
10154 hashes [0] = mono_metadata_str_hash (full_name);
10155 hashes [1] = 0;
10156 g_free (full_name);
10157 } else {
10158 hashes [0] = mono_metadata_str_hash (m_class_get_name (klass));
10159 hashes [1] = mono_metadata_str_hash (m_class_get_name_space (klass));
10161 if (method->wrapper_type == MONO_WRAPPER_STFLD || method->wrapper_type == MONO_WRAPPER_LDFLD || method->wrapper_type == MONO_WRAPPER_LDFLDA)
10162 /* The method name includes a stringified pointer */
10163 hashes [2] = 0;
10164 else
10165 hashes [2] = mono_metadata_str_hash (method->name);
10166 hashes [3] = method->wrapper_type;
10167 hashes [4] = mono_aot_type_hash (sig->ret);
10168 hindex = 5;
10169 for (i = 0; i < sig->param_count; i++) {
10170 hashes [hindex ++] = mono_aot_type_hash (sig->params [i]);
10172 if (class_ginst) {
10173 for (i = 0; i < class_ginst->type_argc; ++i)
10174 hashes [hindex ++] = mono_aot_type_hash (class_ginst->type_argv [i]);
10176 if (ginst) {
10177 for (i = 0; i < ginst->type_argc; ++i)
10178 hashes [hindex ++] = mono_aot_type_hash (ginst->type_argv [i]);
10180 g_assert (hindex == hashes_count);
10182 /* Setup internal state */
10183 a = b = c = 0xdeadbeef + (((guint32)hashes_count)<<2);
10185 /* Handle most of the hashes */
10186 while (hashes_count > 3) {
10187 a += hashes [0];
10188 b += hashes [1];
10189 c += hashes [2];
10190 mix (a,b,c);
10191 hashes_count -= 3;
10192 hashes += 3;
10195 /* Handle the last 3 hashes (all the case statements fall through) */
10196 switch (hashes_count) {
10197 case 3 : c += hashes [2];
10198 case 2 : b += hashes [1];
10199 case 1 : a += hashes [0];
10200 mono_final (a,b,c);
10201 case 0: /* nothing left to add */
10202 break;
10205 g_free (hashes_start);
10207 return c;
10209 #undef rot
10210 #undef mix
10211 #undef mono_final
10214 * mono_aot_get_array_helper_from_wrapper;
10216 * Get the helper method in Array called by an array wrapper method.
10218 MonoMethod*
10219 mono_aot_get_array_helper_from_wrapper (MonoMethod *method)
10221 MonoMethod *m;
10222 const char *prefix;
10223 MonoGenericContext ctx;
10224 MonoType *args [16];
10225 char *mname, *iname, *s, *s2, *helper_name = NULL;
10227 prefix = "System.Collections.Generic";
10228 s = g_strdup_printf ("%s", method->name + strlen (prefix) + 1);
10229 s2 = strstr (s, "`1.");
10230 g_assert (s2);
10231 s2 [0] = '\0';
10232 iname = s;
10233 mname = s2 + 3;
10235 //printf ("X: %s %s\n", iname, mname);
10237 if (!strcmp (iname, "IList"))
10238 helper_name = g_strdup_printf ("InternalArray__%s", mname);
10239 else
10240 helper_name = g_strdup_printf ("InternalArray__%s_%s", iname, mname);
10241 m = get_method_nofail (mono_defaults.array_class, helper_name, mono_method_signature_internal (method)->param_count, 0);
10242 g_assert (m);
10243 g_free (helper_name);
10244 g_free (s);
10246 if (m->is_generic) {
10247 ERROR_DECL (error);
10248 memset (&ctx, 0, sizeof (ctx));
10249 args [0] = m_class_get_byval_arg (m_class_get_element_class (method->klass));
10250 ctx.method_inst = mono_metadata_get_generic_inst (1, args);
10251 m = mono_class_inflate_generic_method_checked (m, &ctx, error);
10252 g_assert (mono_error_ok (error)); /* FIXME don't swallow the error */
10255 return m;
10258 #if !defined(DISABLE_AOT) && !defined(DISABLE_JIT)
10260 typedef struct HashEntry {
10261 guint32 key, value, index;
10262 struct HashEntry *next;
10263 } HashEntry;
10266 * emit_extra_methods:
10268 * Emit methods which are not in the METHOD table, like wrappers.
10270 static void
10271 emit_extra_methods (MonoAotCompile *acfg)
10273 int i, table_size, buf_size;
10274 guint8 *p, *buf;
10275 guint32 *info_offsets;
10276 guint32 hash;
10277 GPtrArray *table;
10278 HashEntry *entry, *new_entry;
10279 int nmethods, max_chain_length;
10280 int *chain_lengths;
10282 info_offsets = g_new0 (guint32, acfg->extra_methods->len);
10284 /* Emit method info */
10285 nmethods = 0;
10286 for (i = 0; i < acfg->extra_methods->len; ++i) {
10287 MonoMethod *method = (MonoMethod *)g_ptr_array_index (acfg->extra_methods, i);
10288 MonoCompile *cfg = (MonoCompile *)g_hash_table_lookup (acfg->method_to_cfg, method);
10290 if (ignore_cfg (cfg))
10291 continue;
10293 buf_size = 10240;
10294 p = buf = (guint8 *)g_malloc (buf_size);
10296 nmethods ++;
10298 method = cfg->method_to_register;
10300 encode_method_ref (acfg, method, p, &p);
10302 g_assert ((p - buf) < buf_size);
10304 info_offsets [i] = add_to_blob (acfg, buf, p - buf);
10305 g_free (buf);
10309 * Construct a chained hash table for mapping indexes in extra_method_info to
10310 * method indexes.
10312 table_size = g_spaced_primes_closest ((int)(nmethods * 1.5));
10313 table = g_ptr_array_sized_new (table_size);
10314 for (i = 0; i < table_size; ++i)
10315 g_ptr_array_add (table, NULL);
10316 chain_lengths = g_new0 (int, table_size);
10317 max_chain_length = 0;
10318 for (i = 0; i < acfg->extra_methods->len; ++i) {
10319 MonoMethod *method = (MonoMethod *)g_ptr_array_index (acfg->extra_methods, i);
10320 MonoCompile *cfg = (MonoCompile *)g_hash_table_lookup (acfg->method_to_cfg, method);
10321 guint32 key, value;
10323 if (ignore_cfg (cfg))
10324 continue;
10326 key = info_offsets [i];
10327 value = get_method_index (acfg, method);
10329 hash = mono_aot_method_hash (method) % table_size;
10330 //printf ("X: %s %x\n", mono_method_get_full_name (method), mono_aot_method_hash (method));
10332 chain_lengths [hash] ++;
10333 max_chain_length = MAX (max_chain_length, chain_lengths [hash]);
10335 new_entry = (HashEntry *)mono_mempool_alloc0 (acfg->mempool, sizeof (HashEntry));
10336 new_entry->key = key;
10337 new_entry->value = value;
10339 entry = (HashEntry *)g_ptr_array_index (table, hash);
10340 if (entry == NULL) {
10341 new_entry->index = hash;
10342 g_ptr_array_index (table, hash) = new_entry;
10343 } else {
10344 while (entry->next)
10345 entry = entry->next;
10347 entry->next = new_entry;
10348 new_entry->index = table->len;
10349 g_ptr_array_add (table, new_entry);
10352 g_free (chain_lengths);
10354 //printf ("MAX: %d\n", max_chain_length);
10356 buf_size = table->len * 12 + 4;
10357 p = buf = (guint8 *)g_malloc (buf_size);
10358 encode_int (table_size, p, &p);
10360 for (i = 0; i < table->len; ++i) {
10361 HashEntry *entry = (HashEntry *)g_ptr_array_index (table, i);
10363 if (entry == NULL) {
10364 encode_int (0, p, &p);
10365 encode_int (0, p, &p);
10366 encode_int (0, p, &p);
10367 } else {
10368 //g_assert (entry->key > 0);
10369 encode_int (entry->key, p, &p);
10370 encode_int (entry->value, p, &p);
10371 if (entry->next)
10372 encode_int (entry->next->index, p, &p);
10373 else
10374 encode_int (0, p, &p);
10377 g_assert (p - buf <= buf_size);
10379 /* Emit the table */
10380 emit_aot_data (acfg, MONO_AOT_TABLE_EXTRA_METHOD_TABLE, "extra_method_table", buf, p - buf);
10382 g_free (buf);
10385 * Emit a table reverse mapping method indexes to their index in extra_method_info.
10386 * This is used by mono_aot_find_jit_info ().
10388 buf_size = acfg->extra_methods->len * 8 + 4;
10389 p = buf = (guint8 *)g_malloc (buf_size);
10390 encode_int (acfg->extra_methods->len, p, &p);
10391 for (i = 0; i < acfg->extra_methods->len; ++i) {
10392 MonoMethod *method = (MonoMethod *)g_ptr_array_index (acfg->extra_methods, i);
10394 encode_int (get_method_index (acfg, method), p, &p);
10395 encode_int (info_offsets [i], p, &p);
10397 emit_aot_data (acfg, MONO_AOT_TABLE_EXTRA_METHOD_INFO_OFFSETS, "extra_method_info_offsets", buf, p - buf);
10399 g_free (buf);
10400 g_free (info_offsets);
10401 g_ptr_array_free (table, TRUE);
10404 static void
10405 generate_aotid (guint8* aotid)
10407 gpointer rand_handle;
10408 ERROR_DECL (error);
10410 mono_rand_open ();
10411 rand_handle = mono_rand_init (NULL, 0);
10413 mono_rand_try_get_bytes (&rand_handle, aotid, 16, error);
10414 mono_error_assert_ok (error);
10416 mono_rand_close (rand_handle);
10419 static void
10420 emit_exception_info (MonoAotCompile *acfg)
10422 int i;
10423 gint32 *offsets;
10424 SeqPointData sp_data;
10425 gboolean seq_points_to_file = FALSE;
10427 offsets = g_new0 (gint32, acfg->nmethods);
10428 for (i = 0; i < acfg->nmethods; ++i) {
10429 if (acfg->cfgs [i]) {
10430 MonoCompile *cfg = acfg->cfgs [i];
10432 // By design aot-runtime decode_exception_debug_info is not able to load sequence point debug data from a file.
10433 // As it is not possible to load debug data from a file its is also not possible to store it in a file.
10434 gboolean method_seq_points_to_file = acfg->aot_opts.gen_msym_dir &&
10435 cfg->gen_seq_points && !cfg->gen_sdb_seq_points;
10436 gboolean method_seq_points_to_binary = cfg->gen_seq_points && !method_seq_points_to_file;
10438 emit_exception_debug_info (acfg, cfg, method_seq_points_to_binary);
10439 offsets [i] = cfg->ex_info_offset;
10441 if (method_seq_points_to_file) {
10442 if (!seq_points_to_file) {
10443 mono_seq_point_data_init (&sp_data, acfg->nmethods);
10444 seq_points_to_file = TRUE;
10446 mono_seq_point_data_add (&sp_data, cfg->method->token, cfg->method_index, cfg->seq_point_info);
10448 } else {
10449 offsets [i] = 0;
10453 if (seq_points_to_file) {
10454 char *aotid = mono_guid_to_string_minimal (acfg->image->aotid);
10455 char *dir = g_build_filename (acfg->aot_opts.gen_msym_dir_path, aotid, NULL);
10456 char *image_basename = g_path_get_basename (acfg->image->name);
10457 char *aot_file = g_strdup_printf("%s%s", image_basename, SEQ_POINT_AOT_EXT);
10458 char *aot_file_path = g_build_filename (dir, aot_file, NULL);
10460 if (g_ensure_directory_exists (aot_file_path) == FALSE) {
10461 fprintf (stderr, "AOT : failed to create msym directory: %s\n", aot_file_path);
10462 exit (1);
10465 mono_seq_point_data_write (&sp_data, aot_file_path);
10466 mono_seq_point_data_free (&sp_data);
10468 g_free (aotid);
10469 g_free (dir);
10470 g_free (image_basename);
10471 g_free (aot_file);
10472 g_free (aot_file_path);
10475 acfg->stats.offsets_size += emit_offset_table (acfg, "ex_info_offsets", MONO_AOT_TABLE_EX_INFO_OFFSETS, acfg->nmethods, 10, offsets);
10476 g_free (offsets);
10479 static void
10480 emit_unwind_info (MonoAotCompile *acfg)
10482 int i;
10483 char symbol [128];
10485 if (acfg->aot_opts.llvm_only) {
10486 g_assert (acfg->unwind_ops->len == 0);
10487 return;
10491 * The unwind info contains a lot of duplicates so we emit each unique
10492 * entry once, and only store the offset from the start of the table in the
10493 * exception info.
10496 sprintf (symbol, "unwind_info");
10497 emit_section_change (acfg, RODATA_SECT, 1);
10498 emit_alignment (acfg, 8);
10499 emit_info_symbol (acfg, symbol, TRUE);
10501 for (i = 0; i < acfg->unwind_ops->len; ++i) {
10502 guint32 index = GPOINTER_TO_UINT (g_ptr_array_index (acfg->unwind_ops, i));
10503 guint8 *unwind_info;
10504 guint32 unwind_info_len;
10505 guint8 buf [16];
10506 guint8 *p;
10508 unwind_info = mono_get_cached_unwind_info (index, &unwind_info_len);
10510 p = buf;
10511 encode_value (unwind_info_len, p, &p);
10512 emit_bytes (acfg, buf, p - buf);
10513 emit_bytes (acfg, unwind_info, unwind_info_len);
10515 acfg->stats.unwind_info_size += (p - buf) + unwind_info_len;
10519 static void
10520 emit_class_info (MonoAotCompile *acfg)
10522 int i;
10523 gint32 *offsets;
10525 offsets = g_new0 (gint32, acfg->image->tables [MONO_TABLE_TYPEDEF].rows);
10526 for (i = 0; i < acfg->image->tables [MONO_TABLE_TYPEDEF].rows; ++i)
10527 offsets [i] = emit_klass_info (acfg, MONO_TOKEN_TYPE_DEF | (i + 1));
10529 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);
10530 g_free (offsets);
10533 typedef struct ClassNameTableEntry {
10534 guint32 token, index;
10535 struct ClassNameTableEntry *next;
10536 } ClassNameTableEntry;
10538 static void
10539 emit_class_name_table (MonoAotCompile *acfg)
10541 int i, table_size, buf_size;
10542 guint32 token, hash;
10543 MonoClass *klass;
10544 GPtrArray *table;
10545 char *full_name;
10546 guint8 *buf, *p;
10547 ClassNameTableEntry *entry, *new_entry;
10550 * Construct a chained hash table for mapping class names to typedef tokens.
10552 table_size = g_spaced_primes_closest ((int)(acfg->image->tables [MONO_TABLE_TYPEDEF].rows * 1.5));
10553 table = g_ptr_array_sized_new (table_size);
10554 for (i = 0; i < table_size; ++i)
10555 g_ptr_array_add (table, NULL);
10556 for (i = 0; i < acfg->image->tables [MONO_TABLE_TYPEDEF].rows; ++i) {
10557 ERROR_DECL (error);
10558 token = MONO_TOKEN_TYPE_DEF | (i + 1);
10559 klass = mono_class_get_checked (acfg->image, token, error);
10560 if (!klass) {
10561 mono_error_cleanup (error);
10562 continue;
10564 full_name = mono_type_get_name_full (m_class_get_byval_arg (klass), MONO_TYPE_NAME_FORMAT_FULL_NAME);
10565 hash = mono_metadata_str_hash (full_name) % table_size;
10566 g_free (full_name);
10568 /* FIXME: Allocate from the mempool */
10569 new_entry = g_new0 (ClassNameTableEntry, 1);
10570 new_entry->token = token;
10572 entry = (ClassNameTableEntry *)g_ptr_array_index (table, hash);
10573 if (entry == NULL) {
10574 new_entry->index = hash;
10575 g_ptr_array_index (table, hash) = new_entry;
10576 } else {
10577 while (entry->next)
10578 entry = entry->next;
10580 entry->next = new_entry;
10581 new_entry->index = table->len;
10582 g_ptr_array_add (table, new_entry);
10586 /* Emit the table */
10587 buf_size = table->len * 4 + 4;
10588 p = buf = (guint8 *)g_malloc0 (buf_size);
10590 /* FIXME: Optimize memory usage */
10591 g_assert (table_size < 65000);
10592 encode_int16 (table_size, p, &p);
10593 g_assert (table->len < 65000);
10594 for (i = 0; i < table->len; ++i) {
10595 ClassNameTableEntry *entry = (ClassNameTableEntry *)g_ptr_array_index (table, i);
10597 if (entry == NULL) {
10598 encode_int16 (0, p, &p);
10599 encode_int16 (0, p, &p);
10600 } else {
10601 encode_int16 (mono_metadata_token_index (entry->token), p, &p);
10602 if (entry->next)
10603 encode_int16 (entry->next->index, p, &p);
10604 else
10605 encode_int16 (0, p, &p);
10607 g_free (entry);
10609 g_assert (p - buf <= buf_size);
10610 g_ptr_array_free (table, TRUE);
10612 emit_aot_data (acfg, MONO_AOT_TABLE_CLASS_NAME, "class_name_table", buf, p - buf);
10614 g_free (buf);
10617 static void
10618 emit_image_table (MonoAotCompile *acfg)
10620 int i, buf_size;
10621 guint8 *buf, *p;
10624 * The image table is small but referenced in a lot of places.
10625 * So we emit it at once, and reference its elements by an index.
10627 buf_size = acfg->image_table->len * 28 + 4;
10628 for (i = 0; i < acfg->image_table->len; i++) {
10629 MonoImage *image = (MonoImage*)g_ptr_array_index (acfg->image_table, i);
10630 MonoAssemblyName *aname = &image->assembly->aname;
10632 buf_size += strlen (image->assembly_name) + strlen (image->guid) + (aname->culture ? strlen (aname->culture) : 1) + strlen ((char*)aname->public_key_token) + 4;
10635 buf = p = (guint8 *)g_malloc0 (buf_size);
10636 encode_int (acfg->image_table->len, p, &p);
10637 for (i = 0; i < acfg->image_table->len; i++) {
10638 MonoImage *image = (MonoImage*)g_ptr_array_index (acfg->image_table, i);
10639 MonoAssemblyName *aname = &image->assembly->aname;
10641 /* FIXME: Support multi-module assemblies */
10642 g_assert (image->assembly->image == image);
10644 encode_string (image->assembly_name, p, &p);
10645 encode_string (image->guid, p, &p);
10646 encode_string (aname->culture ? aname->culture : "", p, &p);
10647 encode_string ((const char*)aname->public_key_token, p, &p);
10649 while (GPOINTER_TO_UINT (p) % 8 != 0)
10650 p ++;
10652 encode_int (aname->flags, p, &p);
10653 encode_int (aname->major, p, &p);
10654 encode_int (aname->minor, p, &p);
10655 encode_int (aname->build, p, &p);
10656 encode_int (aname->revision, p, &p);
10658 g_assert (p - buf <= buf_size);
10660 emit_aot_data (acfg, MONO_AOT_TABLE_IMAGE_TABLE, "image_table", buf, p - buf);
10662 g_free (buf);
10665 static void
10666 emit_weak_field_indexes (MonoAotCompile *acfg)
10668 GHashTable *indexes;
10669 GHashTableIter iter;
10670 gpointer key, value;
10671 int buf_size;
10672 guint8 *buf, *p;
10674 /* Emit a table of weak field indexes, since computing these at runtime is expensive */
10675 mono_assembly_init_weak_fields (acfg->image);
10676 indexes = acfg->image->weak_field_indexes;
10677 g_assert (indexes);
10679 buf_size = (g_hash_table_size (indexes) + 1) * 4;
10680 buf = p = (guint8 *)g_malloc0 (buf_size);
10682 encode_int (g_hash_table_size (indexes), p, &p);
10683 g_hash_table_iter_init (&iter, indexes);
10684 while (g_hash_table_iter_next (&iter, &key, &value)) {
10685 guint32 index = GPOINTER_TO_UINT (key);
10686 encode_int (index, p, &p);
10688 g_assert (p - buf <= buf_size);
10690 emit_aot_data (acfg, MONO_AOT_TABLE_WEAK_FIELD_INDEXES, "weak_field_indexes", buf, p - buf);
10692 g_free (buf);
10695 static void
10696 emit_got_info (MonoAotCompile *acfg, gboolean llvm)
10698 int i, first_plt_got_patch = 0, buf_size;
10699 guint8 *p, *buf;
10700 guint32 *got_info_offsets;
10701 GotInfo *info = llvm ? &acfg->llvm_got_info : &acfg->got_info;
10703 /* Add the patches needed by the PLT to the GOT */
10704 if (!llvm) {
10705 acfg->plt_got_offset_base = acfg->got_offset;
10706 first_plt_got_patch = info->got_patches->len;
10707 for (i = 1; i < acfg->plt_offset; ++i) {
10708 MonoPltEntry *plt_entry = (MonoPltEntry *)g_hash_table_lookup (acfg->plt_offset_to_entry, GUINT_TO_POINTER (i));
10710 g_ptr_array_add (info->got_patches, plt_entry->ji);
10712 acfg->stats.got_slot_types [plt_entry->ji->type] ++;
10715 acfg->got_offset += acfg->plt_offset;
10719 * FIXME:
10720 * - optimize offsets table.
10721 * - reduce number of exported symbols.
10722 * - emit info for a klass only once.
10723 * - determine when a method uses a GOT slot which is guaranteed to be already
10724 * initialized.
10725 * - clean up and document the code.
10726 * - use String.Empty in class libs.
10729 /* Encode info required to decode shared GOT entries */
10730 buf_size = info->got_patches->len * 128;
10731 p = buf = (guint8 *)mono_mempool_alloc (acfg->mempool, buf_size);
10732 got_info_offsets = (guint32 *)mono_mempool_alloc (acfg->mempool, info->got_patches->len * sizeof (guint32));
10733 if (!llvm) {
10734 acfg->plt_got_info_offsets = (guint32 *)mono_mempool_alloc (acfg->mempool, acfg->plt_offset * sizeof (guint32));
10735 /* Unused */
10736 if (acfg->plt_offset)
10737 acfg->plt_got_info_offsets [0] = 0;
10739 for (i = 0; i < info->got_patches->len; ++i) {
10740 MonoJumpInfo *ji = (MonoJumpInfo *)g_ptr_array_index (info->got_patches, i);
10741 guint8 *p2;
10743 p = buf;
10745 encode_value (ji->type, p, &p);
10746 p2 = p;
10747 encode_patch (acfg, ji, p, &p);
10748 acfg->stats.got_slot_info_sizes [ji->type] += p - p2;
10749 g_assert (p - buf <= buf_size);
10750 got_info_offsets [i] = add_to_blob (acfg, buf, p - buf);
10752 if (!llvm && i >= first_plt_got_patch)
10753 acfg->plt_got_info_offsets [i - first_plt_got_patch + 1] = got_info_offsets [i];
10754 acfg->stats.got_info_size += p - buf;
10757 /* Emit got_info_offsets table */
10759 /* No need to emit offsets for the got plt entries, the plt embeds them directly */
10760 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);
10763 static void
10764 emit_got (MonoAotCompile *acfg)
10766 char symbol [MAX_SYMBOL_SIZE];
10768 if (acfg->aot_opts.llvm_only)
10769 return;
10771 /* Don't make GOT global so accesses to it don't need relocations */
10772 sprintf (symbol, "%s", acfg->got_symbol);
10774 #ifdef TARGET_MACH
10775 emit_unset_mode (acfg);
10776 fprintf (acfg->fp, ".section __DATA, __bss\n");
10777 emit_alignment (acfg, 8);
10778 if (acfg->llvm)
10779 emit_info_symbol (acfg, "jit_got", FALSE);
10780 fprintf (acfg->fp, ".lcomm %s, %d\n", acfg->got_symbol, (int)(acfg->got_offset * sizeof (target_mgreg_t)));
10781 #else
10782 emit_section_change (acfg, ".bss", 0);
10783 emit_alignment (acfg, 8);
10784 if (acfg->aot_opts.write_symbols)
10785 emit_local_symbol (acfg, symbol, "got_end", FALSE);
10786 emit_label (acfg, symbol);
10787 if (acfg->llvm)
10788 emit_info_symbol (acfg, "jit_got", FALSE);
10789 if (acfg->got_offset > 0)
10790 emit_zero_bytes (acfg, (int)(acfg->got_offset * sizeof (target_mgreg_t)));
10791 #endif
10793 sprintf (symbol, "got_end");
10794 emit_label (acfg, symbol);
10797 typedef struct GlobalsTableEntry {
10798 guint32 value, index;
10799 struct GlobalsTableEntry *next;
10800 } GlobalsTableEntry;
10802 #ifdef TARGET_WIN32_MSVC
10803 #define DLL_ENTRY_POINT "DllMain"
10805 static void
10806 emit_library_info (MonoAotCompile *acfg)
10808 // Only include for shared libraries linked directly from generated object.
10809 if (link_shared_library (acfg)) {
10810 char *name = NULL;
10811 char symbol [MAX_SYMBOL_SIZE];
10813 // Ask linker to export all global symbols.
10814 emit_section_change (acfg, ".drectve", 0);
10815 for (guint i = 0; i < acfg->globals->len; ++i) {
10816 name = (char *)g_ptr_array_index (acfg->globals, i);
10817 g_assert (name != NULL);
10818 sprintf_s (symbol, MAX_SYMBOL_SIZE, " /EXPORT:%s", name);
10819 emit_string (acfg, symbol);
10822 // Emit DLLMain function, needed by MSVC linker for DLL's.
10823 // NOTE, DllMain should not go into exports above.
10824 emit_section_change (acfg, ".text", 0);
10825 emit_global (acfg, DLL_ENTRY_POINT, TRUE);
10826 emit_label (acfg, DLL_ENTRY_POINT);
10828 // Simple implementation of DLLMain, just returning TRUE.
10829 // For more information about DLLMain: https://msdn.microsoft.com/en-us/library/windows/desktop/ms682583(v=vs.85).aspx
10830 fprintf (acfg->fp, "movl $1, %%eax\n");
10831 fprintf (acfg->fp, "ret\n");
10833 // Inform linker about our dll entry function.
10834 emit_section_change (acfg, ".drectve", 0);
10835 emit_string (acfg, "/ENTRY:" DLL_ENTRY_POINT);
10836 return;
10840 #else
10842 static inline void
10843 emit_library_info (MonoAotCompile *acfg)
10845 return;
10847 #endif
10849 static void
10850 emit_globals (MonoAotCompile *acfg)
10852 int i, table_size;
10853 guint32 hash;
10854 GPtrArray *table;
10855 char symbol [1024];
10856 GlobalsTableEntry *entry, *new_entry;
10858 if (!acfg->aot_opts.static_link)
10859 return;
10861 if (acfg->aot_opts.llvm_only) {
10862 g_assert (acfg->globals->len == 0);
10863 return;
10867 * When static linking, we emit a table containing our globals.
10871 * Construct a chained hash table for mapping global names to their index in
10872 * the globals table.
10874 table_size = g_spaced_primes_closest ((int)(acfg->globals->len * 1.5));
10875 table = g_ptr_array_sized_new (table_size);
10876 for (i = 0; i < table_size; ++i)
10877 g_ptr_array_add (table, NULL);
10878 for (i = 0; i < acfg->globals->len; ++i) {
10879 char *name = (char *)g_ptr_array_index (acfg->globals, i);
10881 hash = mono_metadata_str_hash (name) % table_size;
10883 /* FIXME: Allocate from the mempool */
10884 new_entry = g_new0 (GlobalsTableEntry, 1);
10885 new_entry->value = i;
10887 entry = (GlobalsTableEntry *)g_ptr_array_index (table, hash);
10888 if (entry == NULL) {
10889 new_entry->index = hash;
10890 g_ptr_array_index (table, hash) = new_entry;
10891 } else {
10892 while (entry->next)
10893 entry = entry->next;
10895 entry->next = new_entry;
10896 new_entry->index = table->len;
10897 g_ptr_array_add (table, new_entry);
10901 /* Emit the table */
10902 sprintf (symbol, ".Lglobals_hash");
10903 emit_section_change (acfg, RODATA_SECT, 0);
10904 emit_alignment (acfg, 8);
10905 emit_label (acfg, symbol);
10907 /* FIXME: Optimize memory usage */
10908 g_assert (table_size < 65000);
10909 emit_int16 (acfg, table_size);
10910 for (i = 0; i < table->len; ++i) {
10911 GlobalsTableEntry *entry = (GlobalsTableEntry *)g_ptr_array_index (table, i);
10913 if (entry == NULL) {
10914 emit_int16 (acfg, 0);
10915 emit_int16 (acfg, 0);
10916 } else {
10917 emit_int16 (acfg, entry->value + 1);
10918 if (entry->next)
10919 emit_int16 (acfg, entry->next->index);
10920 else
10921 emit_int16 (acfg, 0);
10925 /* Emit the names */
10926 for (i = 0; i < acfg->globals->len; ++i) {
10927 char *name = (char *)g_ptr_array_index (acfg->globals, i);
10929 sprintf (symbol, "name_%d", i);
10930 emit_section_change (acfg, RODATA_SECT, 1);
10931 #ifdef TARGET_MACH
10932 emit_alignment (acfg, 4);
10933 #endif
10934 emit_label (acfg, symbol);
10935 emit_string (acfg, name);
10938 /* Emit the globals table */
10939 sprintf (symbol, "globals");
10940 emit_section_change (acfg, ".data", 0);
10941 /* This is not a global, since it is accessed by the init function */
10942 emit_alignment (acfg, 8);
10943 emit_info_symbol (acfg, symbol, FALSE);
10945 sprintf (symbol, "%sglobals_hash", acfg->temp_prefix);
10946 emit_pointer (acfg, symbol);
10948 for (i = 0; i < acfg->globals->len; ++i) {
10949 char *name = (char *)g_ptr_array_index (acfg->globals, i);
10951 sprintf (symbol, "name_%d", i);
10952 emit_pointer (acfg, symbol);
10954 g_assert (strlen (name) < sizeof (symbol));
10955 sprintf (symbol, "%s", name);
10956 emit_pointer (acfg, symbol);
10958 /* Null terminate the table */
10959 emit_int32 (acfg, 0);
10960 emit_int32 (acfg, 0);
10963 static void
10964 emit_mem_end (MonoAotCompile *acfg)
10966 char symbol [128];
10968 if (acfg->aot_opts.llvm_only)
10969 return;
10971 sprintf (symbol, "mem_end");
10972 emit_section_change (acfg, ".text", 1);
10973 emit_alignment_code (acfg, 8);
10974 emit_label (acfg, symbol);
10977 static void
10978 init_aot_file_info (MonoAotCompile *acfg, MonoAotFileInfo *info)
10980 int i;
10982 info->version = MONO_AOT_FILE_VERSION;
10983 info->plt_got_offset_base = acfg->plt_got_offset_base;
10984 info->got_size = acfg->got_offset * sizeof (target_mgreg_t);
10985 info->plt_size = acfg->plt_offset;
10986 info->nmethods = acfg->nmethods;
10987 info->nextra_methods = acfg->nextra_methods;
10988 info->flags = acfg->flags;
10989 info->opts = acfg->opts;
10990 info->simd_opts = acfg->simd_opts;
10991 info->gc_name_index = acfg->gc_name_offset;
10992 info->datafile_size = acfg->datafile_offset;
10993 for (i = 0; i < MONO_AOT_TABLE_NUM; ++i)
10994 info->table_offsets [i] = acfg->table_offsets [i];
10995 for (i = 0; i < MONO_AOT_TRAMP_NUM; ++i)
10996 info->num_trampolines [i] = acfg->num_trampolines [i];
10997 for (i = 0; i < MONO_AOT_TRAMP_NUM; ++i)
10998 info->trampoline_got_offset_base [i] = acfg->trampoline_got_offset_base [i];
10999 for (i = 0; i < MONO_AOT_TRAMP_NUM; ++i)
11000 info->trampoline_size [i] = acfg->trampoline_size [i];
11001 info->num_rgctx_fetch_trampolines = acfg->aot_opts.nrgctx_fetch_trampolines;
11003 int card_table_shift_bits = 0;
11004 target_mgreg_t card_table_mask = 0;
11006 mono_gc_get_target_card_table (&card_table_shift_bits, &card_table_mask);
11009 * Sanity checking variables used to make sure the host and target
11010 * environment matches when cross compiling.
11012 info->double_align = MONO_ABI_ALIGNOF (double);
11013 info->long_align = MONO_ABI_ALIGNOF (gint64);
11014 info->generic_tramp_num = MONO_TRAMPOLINE_NUM;
11015 info->card_table_shift_bits = card_table_shift_bits;
11016 info->card_table_mask = card_table_mask;
11018 info->tramp_page_size = acfg->tramp_page_size;
11019 info->nshared_got_entries = acfg->nshared_got_entries;
11020 for (i = 0; i < MONO_AOT_TRAMP_NUM; ++i)
11021 info->tramp_page_code_offsets [i] = acfg->tramp_page_code_offsets [i];
11023 memcpy(&info->aotid, acfg->image->aotid, 16);
11026 static void
11027 emit_aot_file_info (MonoAotCompile *acfg, MonoAotFileInfo *info)
11029 char symbol [MAX_SYMBOL_SIZE];
11030 int i, sindex;
11031 const char **symbols;
11033 symbols = g_new0 (const char *, MONO_AOT_FILE_INFO_NUM_SYMBOLS);
11034 sindex = 0;
11035 symbols [sindex ++] = acfg->got_symbol;
11036 if (acfg->llvm) {
11037 symbols [sindex ++] = g_strdup_printf ("%s%s", acfg->user_symbol_prefix, acfg->llvm_got_symbol);
11038 symbols [sindex ++] = acfg->llvm_eh_frame_symbol;
11039 } else {
11040 symbols [sindex ++] = NULL;
11041 symbols [sindex ++] = NULL;
11043 /* llvm_get_method */
11044 symbols [sindex ++] = NULL;
11045 /* llvm_get_unbox_tramp */
11046 symbols [sindex ++] = NULL;
11047 if (!acfg->aot_opts.llvm_only) {
11048 symbols [sindex ++] = "jit_code_start";
11049 symbols [sindex ++] = "jit_code_end";
11050 symbols [sindex ++] = "method_addresses";
11051 } else {
11052 symbols [sindex ++] = NULL;
11053 symbols [sindex ++] = NULL;
11054 symbols [sindex ++] = NULL;
11056 symbols [sindex ++] = NULL;
11057 symbols [sindex ++] = NULL;
11059 if (acfg->data_outfile) {
11060 for (i = 0; i < MONO_AOT_TABLE_NUM; ++i)
11061 symbols [sindex ++] = NULL;
11062 } else {
11063 symbols [sindex ++] = "blob";
11064 symbols [sindex ++] = "class_name_table";
11065 symbols [sindex ++] = "class_info_offsets";
11066 symbols [sindex ++] = "method_info_offsets";
11067 symbols [sindex ++] = "ex_info_offsets";
11068 symbols [sindex ++] = "extra_method_info_offsets";
11069 symbols [sindex ++] = "extra_method_table";
11070 symbols [sindex ++] = "got_info_offsets";
11071 if (acfg->llvm)
11072 symbols [sindex ++] = "llvm_got_info_offsets";
11073 else
11074 symbols [sindex ++] = NULL;
11075 symbols [sindex ++] = "image_table";
11076 symbols [sindex ++] = "weak_field_indexes";
11079 symbols [sindex ++] = "mem_end";
11080 symbols [sindex ++] = "assembly_guid";
11081 symbols [sindex ++] = "runtime_version";
11082 if (acfg->num_trampoline_got_entries) {
11083 symbols [sindex ++] = "specific_trampolines";
11084 symbols [sindex ++] = "static_rgctx_trampolines";
11085 symbols [sindex ++] = "imt_trampolines";
11086 symbols [sindex ++] = "gsharedvt_arg_trampolines";
11087 symbols [sindex ++] = "ftnptr_arg_trampolines";
11088 symbols [sindex ++] = "unbox_arbitrary_trampolines";
11089 } else {
11090 symbols [sindex ++] = NULL;
11091 symbols [sindex ++] = NULL;
11092 symbols [sindex ++] = NULL;
11093 symbols [sindex ++] = NULL;
11094 symbols [sindex ++] = NULL;
11095 symbols [sindex ++] = NULL;
11097 if (acfg->aot_opts.static_link) {
11098 symbols [sindex ++] = "globals";
11099 } else {
11100 symbols [sindex ++] = NULL;
11102 symbols [sindex ++] = "assembly_name";
11103 symbols [sindex ++] = "plt";
11104 symbols [sindex ++] = "plt_end";
11105 symbols [sindex ++] = "unwind_info";
11106 if (!acfg->aot_opts.llvm_only) {
11107 symbols [sindex ++] = "unbox_trampolines";
11108 symbols [sindex ++] = "unbox_trampolines_end";
11109 symbols [sindex ++] = "unbox_trampoline_addresses";
11110 } else {
11111 symbols [sindex ++] = NULL;
11112 symbols [sindex ++] = NULL;
11113 symbols [sindex ++] = NULL;
11116 g_assert (sindex == MONO_AOT_FILE_INFO_NUM_SYMBOLS);
11118 sprintf (symbol, "%smono_aot_file_info", acfg->user_symbol_prefix);
11119 emit_section_change (acfg, ".data", 0);
11120 emit_alignment (acfg, 8);
11121 emit_label (acfg, symbol);
11122 if (!acfg->aot_opts.static_link)
11123 emit_global (acfg, symbol, FALSE);
11125 /* The data emitted here must match MonoAotFileInfo. */
11127 emit_int32 (acfg, info->version);
11128 emit_int32 (acfg, info->dummy);
11131 * We emit pointers to our data structures instead of emitting global symbols which
11132 * point to them, to reduce the number of globals, and because using globals leads to
11133 * various problems (i.e. arm/thumb).
11135 for (i = 0; i < MONO_AOT_FILE_INFO_NUM_SYMBOLS; ++i)
11136 emit_pointer (acfg, symbols [i]);
11138 emit_int32 (acfg, info->plt_got_offset_base);
11139 emit_int32 (acfg, info->got_size);
11140 emit_int32 (acfg, info->plt_size);
11141 emit_int32 (acfg, info->nmethods);
11142 emit_int32 (acfg, info->nextra_methods);
11143 emit_int32 (acfg, info->flags);
11144 emit_int32 (acfg, info->opts);
11145 emit_int32 (acfg, info->simd_opts);
11146 emit_int32 (acfg, info->gc_name_index);
11147 emit_int32 (acfg, info->num_rgctx_fetch_trampolines);
11148 emit_int32 (acfg, info->double_align);
11149 emit_int32 (acfg, info->long_align);
11150 emit_int32 (acfg, info->generic_tramp_num);
11151 emit_int32 (acfg, info->card_table_shift_bits);
11152 emit_int32 (acfg, info->card_table_mask);
11153 emit_int32 (acfg, info->tramp_page_size);
11154 emit_int32 (acfg, info->nshared_got_entries);
11155 emit_int32 (acfg, info->datafile_size);
11156 emit_int32 (acfg, 0);
11157 emit_int32 (acfg, 0);
11159 for (i = 0; i < MONO_AOT_TABLE_NUM; ++i)
11160 emit_int32 (acfg, info->table_offsets [i]);
11161 for (i = 0; i < MONO_AOT_TRAMP_NUM; ++i)
11162 emit_int32 (acfg, info->num_trampolines [i]);
11163 for (i = 0; i < MONO_AOT_TRAMP_NUM; ++i)
11164 emit_int32 (acfg, info->trampoline_got_offset_base [i]);
11165 for (i = 0; i < MONO_AOT_TRAMP_NUM; ++i)
11166 emit_int32 (acfg, info->trampoline_size [i]);
11167 for (i = 0; i < MONO_AOT_TRAMP_NUM; ++i)
11168 emit_int32 (acfg, info->tramp_page_code_offsets [i]);
11170 emit_bytes (acfg, info->aotid, 16);
11172 if (acfg->aot_opts.static_link) {
11173 emit_global_inner (acfg, acfg->static_linking_symbol, FALSE);
11174 emit_alignment (acfg, sizeof (target_mgreg_t));
11175 emit_label (acfg, acfg->static_linking_symbol);
11176 emit_pointer_2 (acfg, acfg->user_symbol_prefix, "mono_aot_file_info");
11181 * Emit a structure containing all the information not stored elsewhere.
11183 static void
11184 emit_file_info (MonoAotCompile *acfg)
11186 char *build_info;
11187 MonoAotFileInfo *info;
11189 if (acfg->aot_opts.bind_to_runtime_version) {
11190 build_info = mono_get_runtime_build_info ();
11191 emit_string_symbol (acfg, "runtime_version", build_info);
11192 g_free (build_info);
11193 } else {
11194 emit_string_symbol (acfg, "runtime_version", "");
11197 emit_string_symbol (acfg, "assembly_guid" , acfg->image->guid);
11199 /* Emit a string holding the assembly name */
11200 emit_string_symbol (acfg, "assembly_name", acfg->image->assembly->aname.name);
11202 info = g_new0 (MonoAotFileInfo, 1);
11203 init_aot_file_info (acfg, info);
11205 if (acfg->aot_opts.static_link) {
11206 char symbol [MAX_SYMBOL_SIZE];
11207 char *p;
11210 * Emit a global symbol which can be passed by an embedding app to
11211 * mono_aot_register_module (). The symbol points to a pointer to the the file info
11212 * structure.
11214 sprintf (symbol, "%smono_aot_module_%s_info", acfg->user_symbol_prefix, acfg->image->assembly->aname.name);
11216 /* Get rid of characters which cannot occur in symbols */
11217 p = symbol;
11218 for (p = symbol; *p; ++p) {
11219 if (!(isalnum (*p) || *p == '_'))
11220 *p = '_';
11222 acfg->static_linking_symbol = g_strdup (symbol);
11225 if (acfg->llvm)
11226 mono_llvm_emit_aot_file_info (info, acfg->has_jitted_code);
11227 else
11228 emit_aot_file_info (acfg, info);
11231 static void
11232 emit_blob (MonoAotCompile *acfg)
11234 acfg->blob_closed = TRUE;
11236 emit_aot_data (acfg, MONO_AOT_TABLE_BLOB, "blob", (guint8*)acfg->blob.data, acfg->blob.index);
11239 static void
11240 emit_objc_selectors (MonoAotCompile *acfg)
11242 int i;
11243 char symbol [128];
11245 if (!acfg->objc_selectors || acfg->objc_selectors->len == 0)
11246 return;
11249 * From
11250 * cat > foo.m << EOF
11251 * void *ret ()
11253 * return @selector(print:);
11255 * EOF
11258 mono_img_writer_emit_unset_mode (acfg->w);
11259 g_assert (acfg->fp);
11260 fprintf (acfg->fp, ".section __DATA,__objc_selrefs,literal_pointers,no_dead_strip\n");
11261 fprintf (acfg->fp, ".align 3\n");
11262 for (i = 0; i < acfg->objc_selectors->len; ++i) {
11263 sprintf (symbol, "L_OBJC_SELECTOR_REFERENCES_%d", i);
11264 emit_label (acfg, symbol);
11265 sprintf (symbol, "L_OBJC_METH_VAR_NAME_%d", i);
11266 emit_pointer (acfg, symbol);
11269 fprintf (acfg->fp, ".section __TEXT,__cstring,cstring_literals\n");
11270 for (i = 0; i < acfg->objc_selectors->len; ++i) {
11271 fprintf (acfg->fp, "L_OBJC_METH_VAR_NAME_%d:\n", i);
11272 fprintf (acfg->fp, ".asciz \"%s\"\n", (char*)g_ptr_array_index (acfg->objc_selectors, i));
11275 fprintf (acfg->fp, ".section __DATA,__objc_imageinfo,regular,no_dead_strip\n");
11276 fprintf (acfg->fp, ".align 3\n");
11277 fprintf (acfg->fp, "L_OBJC_IMAGE_INFO:\n");
11278 fprintf (acfg->fp, ".long 0\n");
11279 fprintf (acfg->fp, ".long 16\n");
11282 static void
11283 emit_dwarf_info (MonoAotCompile *acfg)
11285 #ifdef EMIT_DWARF_INFO
11286 int i;
11287 char symbol2 [128];
11289 /* DIEs for methods */
11290 for (i = 0; i < acfg->nmethods; ++i) {
11291 MonoCompile *cfg = acfg->cfgs [i];
11293 if (ignore_cfg (cfg))
11294 continue;
11296 // FIXME: LLVM doesn't define .Lme_...
11297 if (cfg->compile_llvm)
11298 continue;
11300 sprintf (symbol2, "%sme_%x", acfg->temp_prefix, i);
11302 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 ()));
11304 #endif
11307 #ifdef EMIT_WIN32_CODEVIEW_INFO
11308 typedef struct _CodeViewSubSectionData
11310 gchar *start_section;
11311 gchar *end_section;
11312 gchar *start_section_record;
11313 gchar *end_section_record;
11314 int section_type;
11315 int section_record_type;
11316 int section_id;
11317 } CodeViewSubsectionData;
11319 typedef struct _CodeViewCompilerVersion
11321 gint major;
11322 gint minor;
11323 gint revision;
11324 gint patch;
11325 } CodeViewCompilerVersion;
11327 #define CODEVIEW_SUBSECTION_SYMBOL_TYPE 0xF1
11328 #define CODEVIEW_SUBSECTION_RECORD_COMPILER_TYPE 0x113c
11329 #define CODEVIEW_SUBSECTION_RECORD_FUNCTION_START_TYPE 0x1147
11330 #define CODEVIEW_SUBSECTION_RECORD_FUNCTION_END_TYPE 0x114F
11331 #define CODEVIEW_CSHARP_LANGUAGE_TYPE 0x0A
11332 #define CODEVIEW_CPU_TYPE 0x0
11333 #define CODEVIEW_MAGIC_HEADER 0x4
11335 static void
11336 codeview_clear_subsection_data (CodeViewSubsectionData *section_data)
11338 g_free (section_data->start_section);
11339 g_free (section_data->end_section);
11340 g_free (section_data->start_section_record);
11341 g_free (section_data->end_section_record);
11343 memset (section_data, 0, sizeof (CodeViewSubsectionData));
11346 static void
11347 codeview_parse_compiler_version (gchar *version, CodeViewCompilerVersion *data)
11349 gint values[4] = { 0 };
11350 gint *value = values;
11352 while (*version && (value < values + G_N_ELEMENTS (values))) {
11353 if (isdigit (*version)) {
11354 *value *= 10;
11355 *value += *version - '0';
11357 else if (*version == '.') {
11358 value++;
11361 version++;
11364 data->major = values[0];
11365 data->minor = values[1];
11366 data->revision = values[2];
11367 data->patch = values[3];
11370 static void
11371 emit_codeview_start_subsection (MonoAotCompile *acfg, int section_id, int section_type, int section_record_type, CodeViewSubsectionData *section_data)
11373 // Starting a new subsection, clear old data.
11374 codeview_clear_subsection_data (section_data);
11376 // Keep subsection data.
11377 section_data->section_id = section_id;
11378 section_data->section_type = section_type;
11379 section_data->section_record_type = section_record_type;
11381 // Allocate all labels used in subsection.
11382 section_data->start_section = g_strdup_printf ("%scvs_%d", acfg->temp_prefix, section_data->section_id);
11383 section_data->end_section = g_strdup_printf ("%scvse_%d", acfg->temp_prefix, section_data->section_id);
11384 section_data->start_section_record = g_strdup_printf ("%scvsr_%d", acfg->temp_prefix, section_data->section_id);
11385 section_data->end_section_record = g_strdup_printf ("%scvsre_%d", acfg->temp_prefix, section_data->section_id);
11387 // Subsection type, function symbol.
11388 emit_int32 (acfg, section_data->section_type);
11390 // Subsection size.
11391 emit_symbol_diff (acfg, section_data->end_section, section_data->start_section, 0);
11392 emit_label (acfg, section_data->start_section);
11394 // Subsection record size.
11395 fprintf (acfg->fp, "\t.word %s - %s\n", section_data->end_section_record, section_data->start_section_record);
11396 emit_label (acfg, section_data->start_section_record);
11398 // Subsection record type.
11399 emit_int16 (acfg, section_record_type);
11402 static void
11403 emit_codeview_end_subsection (MonoAotCompile *acfg, CodeViewSubsectionData *section_data, int *section_id)
11405 g_assert (section_data->start_section);
11406 g_assert (section_data->end_section);
11407 g_assert (section_data->start_section_record);
11408 g_assert (section_data->end_section_record);
11410 emit_label (acfg, section_data->end_section_record);
11412 if (section_data->section_record_type == CODEVIEW_SUBSECTION_RECORD_FUNCTION_START_TYPE) {
11413 // Emit record length.
11414 emit_int16 (acfg, 2);
11416 // Emit specific record type end.
11417 emit_int16 (acfg, CODEVIEW_SUBSECTION_RECORD_FUNCTION_END_TYPE);
11420 emit_label (acfg, section_data->end_section);
11422 // Next subsection needs to be 4 byte aligned.
11423 emit_alignment (acfg, 4);
11425 *section_id = section_data->section_id + 1;
11426 codeview_clear_subsection_data (section_data);
11429 inline static void
11430 emit_codeview_start_symbol_subsection (MonoAotCompile *acfg, int section_id, int section_record_type, CodeViewSubsectionData *section_data)
11432 emit_codeview_start_subsection (acfg, section_id, CODEVIEW_SUBSECTION_SYMBOL_TYPE, section_record_type, section_data);
11435 inline static void
11436 emit_codeview_end_symbol_subsection (MonoAotCompile *acfg, CodeViewSubsectionData *section_data, int *section_id)
11438 emit_codeview_end_subsection (acfg, section_data, section_id);
11441 static void
11442 emit_codeview_compiler_info (MonoAotCompile *acfg, int *section_id)
11444 CodeViewSubsectionData section_data = { 0 };
11445 CodeViewCompilerVersion compiler_version = { 0 };
11447 // Start new compiler record subsection.
11448 emit_codeview_start_symbol_subsection (acfg, *section_id, CODEVIEW_SUBSECTION_RECORD_COMPILER_TYPE, &section_data);
11450 emit_int32 (acfg, CODEVIEW_CSHARP_LANGUAGE_TYPE);
11451 emit_int16 (acfg, CODEVIEW_CPU_TYPE);
11453 // Get compiler version information.
11454 codeview_parse_compiler_version (VERSION, &compiler_version);
11456 // Compiler frontend version, 4 digits.
11457 emit_int16 (acfg, compiler_version.major);
11458 emit_int16 (acfg, compiler_version.minor);
11459 emit_int16 (acfg, compiler_version.revision);
11460 emit_int16 (acfg, compiler_version.patch);
11462 // Compiler backend version, 4 digits (currently same as frontend).
11463 emit_int16 (acfg, compiler_version.major);
11464 emit_int16 (acfg, compiler_version.minor);
11465 emit_int16 (acfg, compiler_version.revision);
11466 emit_int16 (acfg, compiler_version.patch);
11468 // Compiler string.
11469 emit_string (acfg, "Mono AOT compiler");
11471 // Done with section.
11472 emit_codeview_end_symbol_subsection (acfg, &section_data, section_id);
11475 static void
11476 emit_codeview_function_info (MonoAotCompile *acfg, MonoMethod *method, int *section_id, gchar *symbol, gchar *symbol_start, gchar *symbol_end)
11478 CodeViewSubsectionData section_data = { 0 };
11479 gchar *full_method_name = NULL;
11481 // Start new function record subsection.
11482 emit_codeview_start_symbol_subsection (acfg, *section_id, CODEVIEW_SUBSECTION_RECORD_FUNCTION_START_TYPE, &section_data);
11484 // Emit 3 int 0 byte padding, currently not used.
11485 emit_zero_bytes (acfg, sizeof (int) * 3);
11487 // Emit size of function.
11488 emit_symbol_diff (acfg, symbol_end, symbol_start, 0);
11490 // Emit 3 int 0 byte padding, currently not used.
11491 emit_zero_bytes (acfg, sizeof (int) * 3);
11493 // Emit reallocation info.
11494 fprintf (acfg->fp, "\t.secrel32 %s\n", symbol);
11495 fprintf (acfg->fp, "\t.secidx %s\n", symbol);
11497 // Emit flag, currently not used.
11498 emit_zero_bytes (acfg, 1);
11500 // Emit function name, exclude signature since it should be described by own metadata.
11501 full_method_name = mono_method_full_name (method, FALSE);
11502 emit_string (acfg, full_method_name ? full_method_name : "");
11503 g_free (full_method_name);
11505 // Done with section.
11506 emit_codeview_end_symbol_subsection (acfg, &section_data, section_id);
11509 static void
11510 emit_codeview_info (MonoAotCompile *acfg)
11512 int i;
11513 int section_id = 0;
11514 gchar symbol_buffer[MAX_SYMBOL_SIZE];
11516 // Emit codeview debug info section
11517 emit_section_change (acfg, ".debug$S", 0);
11519 // Emit magic header.
11520 emit_int32 (acfg, CODEVIEW_MAGIC_HEADER);
11522 emit_codeview_compiler_info (acfg, &section_id);
11524 for (i = 0; i < acfg->nmethods; ++i) {
11525 MonoCompile *cfg = acfg->cfgs[i];
11527 if (!cfg || COMPILE_LLVM (cfg))
11528 continue;
11530 int ret = g_snprintf (symbol_buffer, G_N_ELEMENTS (symbol_buffer), "%sme_%x", acfg->temp_prefix, i);
11531 if (ret > 0 && ret < G_N_ELEMENTS (symbol_buffer))
11532 emit_codeview_function_info (acfg, cfg->method, &section_id, cfg->asm_debug_symbol, cfg->asm_symbol, symbol_buffer);
11535 #else
11536 static void
11537 emit_codeview_info (MonoAotCompile *acfg)
11540 #endif /* EMIT_WIN32_CODEVIEW_INFO */
11542 #ifdef EMIT_WIN32_UNWIND_INFO
11543 static UnwindInfoSectionCacheItem *
11544 get_cached_unwind_info_section_item_win32 (MonoAotCompile *acfg, const char *function_start, const char *function_end, GSList *unwind_ops)
11546 UnwindInfoSectionCacheItem *item = NULL;
11548 if (!acfg->unwind_info_section_cache)
11549 acfg->unwind_info_section_cache = g_list_alloc ();
11551 PUNWIND_INFO unwind_info = mono_arch_unwindinfo_alloc_unwind_info (unwind_ops);
11553 // Search for unwind info in cache.
11554 GList *list = acfg->unwind_info_section_cache;
11555 int list_size = 0;
11556 while (list && list->data) {
11557 item = (UnwindInfoSectionCacheItem*)list->data;
11558 if (!memcmp (unwind_info, item->unwind_info, sizeof (UNWIND_INFO))) {
11559 // Cache hit, return cached item.
11560 return item;
11562 list = list->next;
11563 list_size++;
11566 // Add to cache.
11567 if (acfg->unwind_info_section_cache) {
11568 item = g_new0 (UnwindInfoSectionCacheItem, 1);
11569 if (item) {
11570 // Format .xdata section label for function, used to get unwind info address RVA.
11571 // Since the unwind info is similar for most functions, the symbol will be reused.
11572 item->xdata_section_label = g_strdup_printf ("%sunwind_%d", acfg->temp_prefix, list_size);
11574 // Cache unwind info data, used when checking cache for matching unwind info. NOTE, cache takes
11575 //over ownership of unwind info.
11576 item->unwind_info = unwind_info;
11578 // Needs to be emitted once.
11579 item->xdata_section_emitted = FALSE;
11581 // Prepend to beginning of list to speed up inserts.
11582 acfg->unwind_info_section_cache = g_list_prepend (acfg->unwind_info_section_cache, (gpointer)item);
11586 return item;
11589 static void
11590 free_unwind_info_section_cache_win32 (MonoAotCompile *acfg)
11592 GList *list = acfg->unwind_info_section_cache;
11594 while (list) {
11595 UnwindInfoSectionCacheItem *item = (UnwindInfoSectionCacheItem *)list->data;
11596 if (item) {
11597 g_free (item->xdata_section_label);
11598 mono_arch_unwindinfo_free_unwind_info (item->unwind_info);
11600 g_free (item);
11601 list->data = NULL;
11604 list = list->next;
11607 g_list_free (acfg->unwind_info_section_cache);
11608 acfg->unwind_info_section_cache = NULL;
11611 static void
11612 emit_unwind_info_data_win32 (MonoAotCompile *acfg, PUNWIND_INFO unwind_info)
11614 // Emit the unwind info struct.
11615 emit_bytes (acfg, (guint8*)unwind_info, sizeof (UNWIND_INFO) - (sizeof (UNWIND_CODE) * MONO_MAX_UNWIND_CODES));
11617 // Emit all unwind codes encoded in unwind info struct.
11618 PUNWIND_CODE current_unwind_node = &unwind_info->UnwindCode[MONO_MAX_UNWIND_CODES - unwind_info->CountOfCodes];
11619 PUNWIND_CODE last_unwind_node = &unwind_info->UnwindCode[MONO_MAX_UNWIND_CODES];
11621 while (current_unwind_node < last_unwind_node) {
11622 guint8 node_count = 0;
11623 switch (current_unwind_node->UnwindOp) {
11624 case UWOP_PUSH_NONVOL:
11625 case UWOP_ALLOC_SMALL:
11626 case UWOP_SET_FPREG:
11627 case UWOP_PUSH_MACHFRAME:
11628 node_count = 1;
11629 break;
11630 case UWOP_SAVE_NONVOL:
11631 case UWOP_SAVE_XMM128:
11632 node_count = 2;
11633 break;
11634 case UWOP_SAVE_NONVOL_FAR:
11635 case UWOP_SAVE_XMM128_FAR:
11636 node_count = 3;
11637 break;
11638 case UWOP_ALLOC_LARGE:
11639 if (current_unwind_node->OpInfo == 0)
11640 node_count = 2;
11641 else
11642 node_count = 3;
11643 break;
11644 default:
11645 g_assert (!"Unknown unwind opcode.");
11648 while (node_count > 0) {
11649 g_assert (current_unwind_node < last_unwind_node);
11651 //Emit current node.
11652 emit_bytes (acfg, (guint8*)current_unwind_node, sizeof (UNWIND_CODE));
11654 node_count--;
11655 current_unwind_node++;
11660 // Emit unwind info sections for each function. Unwind info on Windows x64 is emitted into two different sections.
11661 // .pdata includes the serialized DWORD aligned RVA's of function start, end and address of serialized
11662 // UNWIND_INFO struct emitted into .xdata, see https://msdn.microsoft.com/en-us/library/ft9x1kdx.aspx.
11663 // .xdata section includes DWORD aligned serialized version of UNWIND_INFO struct, https://msdn.microsoft.com/en-us/library/ddssxxy8.aspx.
11664 static void
11665 emit_unwind_info_sections_win32 (MonoAotCompile *acfg, const char *function_start, const char *function_end, GSList *unwind_ops)
11667 char *pdata_section_label = NULL;
11669 int temp_prefix_len = (acfg->temp_prefix != NULL) ? strlen (acfg->temp_prefix) : 0;
11670 if (strncmp (function_start, acfg->temp_prefix, temp_prefix_len)) {
11671 temp_prefix_len = 0;
11674 // Format .pdata section label for function.
11675 pdata_section_label = g_strdup_printf ("%spdata_%s", acfg->temp_prefix, function_start + temp_prefix_len);
11677 UnwindInfoSectionCacheItem *cache_item = get_cached_unwind_info_section_item_win32 (acfg, function_start, function_end, unwind_ops);
11678 g_assert (cache_item && cache_item->xdata_section_label && cache_item->unwind_info);
11680 // Emit .pdata section.
11681 emit_section_change (acfg, ".pdata", 0);
11682 emit_alignment (acfg, sizeof (DWORD));
11683 emit_label (acfg, pdata_section_label);
11685 // Emit function start address RVA.
11686 fprintf (acfg->fp, "\t.long %s@IMGREL\n", function_start);
11688 // Emit function end address RVA.
11689 fprintf (acfg->fp, "\t.long %s@IMGREL\n", function_end);
11691 // Emit unwind info address RVA.
11692 fprintf (acfg->fp, "\t.long %s@IMGREL\n", cache_item->xdata_section_label);
11694 if (!cache_item->xdata_section_emitted) {
11695 // Emit .xdata section.
11696 emit_section_change (acfg, ".xdata", 0);
11697 emit_alignment (acfg, sizeof (DWORD));
11698 emit_label (acfg, cache_item->xdata_section_label);
11700 // Emit unwind info into .xdata section.
11701 emit_unwind_info_data_win32 (acfg, cache_item->unwind_info);
11702 cache_item->xdata_section_emitted = TRUE;
11705 g_free (pdata_section_label);
11707 #endif
11709 static gboolean
11710 should_emit_gsharedvt_method (MonoAotCompile *acfg, MonoMethod *method)
11712 #ifdef TARGET_WASM
11713 if (acfg->image == mono_get_corlib () && !strcmp (m_class_get_name (method->klass), "Vector`1"))
11714 /* The SIMD fallback code in Vector<T> is very large, and not likely to be used */
11715 return FALSE;
11716 #endif
11717 return TRUE;
11720 static gboolean
11721 collect_methods (MonoAotCompile *acfg)
11723 int mindex, i;
11724 MonoImage *image = acfg->image;
11726 /* Collect methods */
11727 for (i = 0; i < image->tables [MONO_TABLE_METHOD].rows; ++i) {
11728 ERROR_DECL (error);
11729 MonoMethod *method;
11730 guint32 token = MONO_TOKEN_METHOD_DEF | (i + 1);
11732 method = mono_get_method_checked (acfg->image, token, NULL, NULL, error);
11734 if (!method) {
11735 aot_printerrf (acfg, "Failed to load method 0x%x from '%s' due to %s.\n", token, image->name, mono_error_get_message (error));
11736 aot_printerrf (acfg, "Run with MONO_LOG_LEVEL=debug for more information.\n");
11737 mono_error_cleanup (error);
11738 return FALSE;
11741 /* Load all methods eagerly to skip the slower lazy loading code */
11742 mono_class_setup_methods (method->klass);
11744 if (mono_aot_mode_is_full (&acfg->aot_opts) && method->iflags & METHOD_IMPL_ATTRIBUTE_INTERNAL_CALL) {
11745 /* Compile the wrapper instead */
11746 /* We do this here instead of add_wrappers () because it is easy to do it here */
11747 MonoMethod *wrapper = mono_marshal_get_native_wrapper (method, TRUE, TRUE);
11748 method = wrapper;
11751 /* FIXME: Some mscorlib methods don't have debug info */
11753 if (acfg->aot_opts.soft_debug && !method->wrapper_type) {
11754 if (!((method->flags & METHOD_ATTRIBUTE_PINVOKE_IMPL) ||
11755 (method->iflags & METHOD_IMPL_ATTRIBUTE_RUNTIME) ||
11756 (method->flags & METHOD_ATTRIBUTE_ABSTRACT) ||
11757 (method->iflags & METHOD_IMPL_ATTRIBUTE_INTERNAL_CALL))) {
11758 if (!mono_debug_lookup_method (method)) {
11759 fprintf (stderr, "Method %s has no debug info, probably the .mdb file for the assembly is missing.\n", mono_method_get_full_name (method));
11760 exit (1);
11766 if (method->is_generic || mono_class_is_gtd (method->klass)) {
11767 /* Compile the ref shared version instead */
11768 method = mini_get_shared_method_full (method, SHARE_MODE_NONE, error);
11769 if (!method) {
11770 aot_printerrf (acfg, "Failed to load method 0x%x from '%s' due to %s.\n", token, image->name, mono_error_get_message (error));
11771 aot_printerrf (acfg, "Run with MONO_LOG_LEVEL=debug for more information.\n");
11772 mono_error_cleanup (error);
11773 return FALSE;
11777 /* Since we add the normal methods first, their index will be equal to their zero based token index */
11778 add_method_with_index (acfg, method, i, FALSE);
11779 acfg->method_index ++;
11782 /* gsharedvt methods */
11783 for (mindex = 0; mindex < image->tables [MONO_TABLE_METHOD].rows; ++mindex) {
11784 ERROR_DECL (error);
11785 MonoMethod *method;
11786 guint32 token = MONO_TOKEN_METHOD_DEF | (mindex + 1);
11788 if (!(acfg->opts & MONO_OPT_GSHAREDVT))
11789 continue;
11791 method = mono_get_method_checked (acfg->image, token, NULL, NULL, error);
11792 report_loader_error (acfg, error, TRUE, "Failed to load method token 0x%x due to %s\n", i, mono_error_get_message (error));
11794 if ((method->is_generic || mono_class_is_gtd (method->klass)) && should_emit_gsharedvt_method (acfg, method)) {
11795 MonoMethod *gshared;
11797 gshared = mini_get_shared_method_full (method, SHARE_MODE_GSHAREDVT, error);
11798 mono_error_assert_ok (error);
11800 add_extra_method (acfg, gshared);
11804 if (mono_aot_mode_is_full (&acfg->aot_opts) || mono_aot_mode_is_hybrid (&acfg->aot_opts))
11805 add_generic_instances (acfg);
11807 if (mono_aot_mode_is_full (&acfg->aot_opts))
11808 add_wrappers (acfg);
11809 return TRUE;
11812 static void
11813 compile_methods (MonoAotCompile *acfg)
11815 int i, methods_len;
11817 if (acfg->aot_opts.nthreads > 0) {
11818 GPtrArray *frag;
11819 int len, j;
11820 GPtrArray *threads;
11821 MonoThreadHandle *thread_handle;
11822 gpointer *user_data;
11823 MonoMethod **methods;
11825 methods_len = acfg->methods->len;
11827 len = acfg->methods->len / acfg->aot_opts.nthreads;
11828 g_assert (len > 0);
11830 * Partition the list of methods into fragments, and hand it to threads to
11831 * process.
11833 threads = g_ptr_array_new ();
11834 /* Make a copy since acfg->methods is modified by compile_method () */
11835 methods = g_new0 (MonoMethod*, methods_len);
11836 //memcpy (methods, g_ptr_array_index (acfg->methods, 0), sizeof (MonoMethod*) * methods_len);
11837 for (i = 0; i < methods_len; ++i)
11838 methods [i] = (MonoMethod *)g_ptr_array_index (acfg->methods, i);
11839 i = 0;
11840 while (i < methods_len) {
11841 ERROR_DECL (error);
11842 MonoInternalThread *thread;
11844 frag = g_ptr_array_new ();
11845 for (j = 0; j < len; ++j) {
11846 if (i < methods_len) {
11847 g_ptr_array_add (frag, methods [i]);
11848 i ++;
11852 user_data = g_new0 (gpointer, 3);
11853 user_data [0] = acfg;
11854 user_data [1] = frag;
11856 thread = mono_thread_create_internal (mono_domain_get (), (gpointer)compile_thread_main, user_data, MONO_THREAD_CREATE_FLAGS_NONE, error);
11857 mono_error_assert_ok (error);
11859 thread_handle = mono_threads_open_thread_handle (thread->handle);
11860 g_ptr_array_add (threads, thread_handle);
11862 g_free (methods);
11864 for (i = 0; i < threads->len; ++i) {
11865 mono_thread_info_wait_one_handle ((MonoThreadHandle*)g_ptr_array_index (threads, i), MONO_INFINITE_WAIT, FALSE);
11866 mono_threads_close_thread_handle ((MonoThreadHandle*)g_ptr_array_index (threads, i));
11868 } else {
11869 methods_len = 0;
11872 /* Compile methods added by compile_method () or all methods if nthreads == 0 */
11873 for (i = methods_len; i < acfg->methods->len; ++i) {
11874 /* This can add new methods to acfg->methods */
11875 compile_method (acfg, (MonoMethod *)g_ptr_array_index (acfg->methods, i));
11878 #ifdef ENABLE_LLVM
11879 if (acfg->llvm)
11880 mono_llvm_fixup_aot_module ();
11881 #endif
11884 static int
11885 compile_asm (MonoAotCompile *acfg)
11887 char *command, *objfile;
11888 char *outfile_name, *tmp_outfile_name, *llvm_ofile;
11889 const char *tool_prefix = acfg->aot_opts.tool_prefix ? acfg->aot_opts.tool_prefix : "";
11890 char *ld_flags = acfg->aot_opts.ld_flags ? acfg->aot_opts.ld_flags : g_strdup("");
11892 #ifdef TARGET_WIN32_MSVC
11893 #define AS_OPTIONS "-c -x assembler"
11894 #elif defined(TARGET_AMD64) && !defined(TARGET_MACH)
11895 #define AS_OPTIONS "--64"
11896 #elif defined(TARGET_POWERPC64)
11897 #define AS_OPTIONS "-a64 -mppc64"
11898 #elif defined(sparc) && TARGET_SIZEOF_VOID_P == 8
11899 #define AS_OPTIONS "-xarch=v9"
11900 #elif defined(TARGET_X86) && defined(TARGET_MACH)
11901 #define AS_OPTIONS "-arch i386"
11902 #elif defined(TARGET_X86) && !defined(TARGET_MACH)
11903 #define AS_OPTIONS "--32"
11904 #else
11905 #define AS_OPTIONS ""
11906 #endif
11908 #if defined(TARGET_OSX)
11909 #define AS_NAME "clang"
11910 #elif defined(TARGET_WIN32_MSVC)
11911 #define AS_NAME "clang.exe"
11912 #else
11913 #define AS_NAME "as"
11914 #endif
11916 #ifdef TARGET_WIN32_MSVC
11917 #define AS_OBJECT_FILE_SUFFIX "obj"
11918 #else
11919 #define AS_OBJECT_FILE_SUFFIX "o"
11920 #endif
11922 #if defined(sparc)
11923 #define LD_NAME "ld"
11924 #define LD_OPTIONS "-shared -G"
11925 #elif defined(__ppc__) && defined(TARGET_MACH)
11926 #define LD_NAME "gcc"
11927 #define LD_OPTIONS "-dynamiclib"
11928 #elif defined(TARGET_AMD64) && defined(TARGET_MACH)
11929 #define LD_NAME "clang"
11930 #define LD_OPTIONS "--shared"
11931 #elif defined(TARGET_WIN32_MSVC)
11932 #define LD_NAME "link.exe"
11933 #define LD_OPTIONS "/DLL /MACHINE:X64 /NOLOGO /INCREMENTAL:NO"
11934 #define LD_DEBUG_OPTIONS LD_OPTIONS " /DEBUG"
11935 #elif defined(TARGET_WIN32) && !defined(TARGET_ANDROID)
11936 #define LD_NAME "gcc"
11937 #define LD_OPTIONS "-shared"
11938 #elif defined(TARGET_X86) && defined(TARGET_MACH)
11939 #define LD_NAME "clang"
11940 #define LD_OPTIONS "-m32 -dynamiclib"
11941 #elif defined(TARGET_X86) && !defined(TARGET_MACH)
11942 #define LD_OPTIONS "-m elf_i386"
11943 #elif defined(TARGET_ARM) && !defined(TARGET_ANDROID)
11944 #define LD_NAME "gcc"
11945 #define LD_OPTIONS "--shared"
11946 #elif defined(TARGET_POWERPC64)
11947 #define LD_OPTIONS "-m elf64ppc"
11948 #endif
11950 #ifndef LD_OPTIONS
11951 #define LD_OPTIONS ""
11952 #endif
11954 if (acfg->aot_opts.asm_only) {
11955 aot_printf (acfg, "Output file: '%s'.\n", acfg->tmpfname);
11956 if (acfg->aot_opts.static_link)
11957 aot_printf (acfg, "Linking symbol: '%s'.\n", acfg->static_linking_symbol);
11958 if (acfg->llvm)
11959 aot_printf (acfg, "LLVM output file: '%s'.\n", acfg->llvm_sfile);
11960 return 0;
11963 if (acfg->aot_opts.static_link) {
11964 if (acfg->aot_opts.outfile)
11965 objfile = g_strdup_printf ("%s", acfg->aot_opts.outfile);
11966 else
11967 objfile = g_strdup_printf ("%s." AS_OBJECT_FILE_SUFFIX, acfg->image->name);
11968 } else {
11969 objfile = g_strdup_printf ("%s." AS_OBJECT_FILE_SUFFIX, acfg->tmpfname);
11972 #ifdef TARGET_OSX
11973 g_string_append (acfg->as_args, "-c -x assembler");
11974 #endif
11976 command = g_strdup_printf ("\"%s%s\" %s %s -o %s %s", tool_prefix, AS_NAME, AS_OPTIONS,
11977 acfg->as_args ? acfg->as_args->str : "",
11978 wrap_path (objfile), wrap_path (acfg->tmpfname));
11979 aot_printf (acfg, "Executing the native assembler: %s\n", command);
11980 if (execute_system (command) != 0) {
11981 g_free (command);
11982 g_free (objfile);
11983 return 1;
11986 if (acfg->llvm && !acfg->llvm_owriter) {
11987 command = g_strdup_printf ("\"%s%s\" %s %s -o %s %s", tool_prefix, AS_NAME, AS_OPTIONS,
11988 acfg->as_args ? acfg->as_args->str : "",
11989 wrap_path (acfg->llvm_ofile), wrap_path (acfg->llvm_sfile));
11990 aot_printf (acfg, "Executing the native assembler: %s\n", command);
11991 if (execute_system (command) != 0) {
11992 g_free (command);
11993 g_free (objfile);
11994 return 1;
11998 g_free (command);
12000 if (acfg->aot_opts.static_link) {
12001 aot_printf (acfg, "Output file: '%s'.\n", objfile);
12002 aot_printf (acfg, "Linking symbol: '%s'.\n", acfg->static_linking_symbol);
12003 g_free (objfile);
12004 return 0;
12007 if (acfg->aot_opts.outfile)
12008 outfile_name = g_strdup_printf ("%s", acfg->aot_opts.outfile);
12009 else
12010 outfile_name = g_strdup_printf ("%s%s", acfg->image->name, MONO_SOLIB_EXT);
12012 tmp_outfile_name = g_strdup_printf ("%s.tmp", outfile_name);
12014 if (acfg->llvm) {
12015 llvm_ofile = g_strdup_printf ("\"%s\"", acfg->llvm_ofile);
12016 } else {
12017 llvm_ofile = g_strdup ("");
12020 /* replace the ; flags separators with spaces */
12021 g_strdelimit (ld_flags, ';', ' ');
12023 if (acfg->aot_opts.llvm_only)
12024 ld_flags = g_strdup_printf ("%s %s", ld_flags, "-lstdc++");
12026 #ifdef TARGET_WIN32_MSVC
12027 g_assert (tmp_outfile_name != NULL);
12028 g_assert (objfile != NULL);
12029 command = g_strdup_printf ("\"%s%s\" %s %s /OUT:%s %s %s", tool_prefix, LD_NAME,
12030 acfg->aot_opts.nodebug ? LD_OPTIONS : LD_DEBUG_OPTIONS, ld_flags, wrap_path (tmp_outfile_name), wrap_path (objfile), wrap_path (llvm_ofile));
12031 #elif defined(LD_NAME)
12032 command = g_strdup_printf ("%s%s %s -o %s %s %s %s", tool_prefix, LD_NAME, LD_OPTIONS,
12033 wrap_path (tmp_outfile_name), wrap_path (llvm_ofile),
12034 wrap_path (g_strdup_printf ("%s." AS_OBJECT_FILE_SUFFIX, acfg->tmpfname)), ld_flags);
12035 #else
12036 // Default (linux)
12037 if (acfg->aot_opts.tool_prefix) {
12038 /* Cross compiling */
12039 command = g_strdup_printf ("\"%sld\" %s -shared -o %s %s %s %s", tool_prefix, LD_OPTIONS,
12040 wrap_path (tmp_outfile_name), wrap_path (llvm_ofile),
12041 wrap_path (g_strdup_printf ("%s." AS_OBJECT_FILE_SUFFIX, acfg->tmpfname)), ld_flags);
12042 } else {
12043 char *args = g_strdup_printf ("%s -shared -o %s %s %s %s", LD_OPTIONS,
12044 wrap_path (tmp_outfile_name), wrap_path (llvm_ofile),
12045 wrap_path (g_strdup_printf ("%s." AS_OBJECT_FILE_SUFFIX, acfg->tmpfname)), ld_flags);
12047 if (acfg->aot_opts.llvm_only) {
12048 command = g_strdup_printf ("%s %s", acfg->aot_opts.clangxx, args);
12049 } else {
12050 command = g_strdup_printf ("\"%sld\" %s", tool_prefix, args);
12052 g_free (args);
12054 #endif
12055 aot_printf (acfg, "Executing the native linker: %s\n", command);
12056 if (execute_system (command) != 0) {
12057 g_free (tmp_outfile_name);
12058 g_free (outfile_name);
12059 g_free (command);
12060 g_free (objfile);
12061 g_free (ld_flags);
12062 return 1;
12065 g_free (command);
12067 /*com = g_strdup_printf ("strip --strip-unneeded %s%s", acfg->image->name, MONO_SOLIB_EXT);
12068 printf ("Stripping the binary: %s\n", com);
12069 execute_system (com);
12070 g_free (com);*/
12072 #if defined(TARGET_ARM) && !defined(TARGET_MACH)
12074 * gas generates 'mapping symbols' each time code and data is mixed, which
12075 * happens a lot in emit_and_reloc_code (), so we need to get rid of them.
12077 command = g_strdup_printf ("\"%sstrip\" --strip-symbol=\\$a --strip-symbol=\\$d %s", wrap_path(tool_prefix), wrap_path(tmp_outfile_name));
12078 aot_printf (acfg, "Stripping the binary: %s\n", command);
12079 if (execute_system (command) != 0) {
12080 g_free (tmp_outfile_name);
12081 g_free (outfile_name);
12082 g_free (command);
12083 g_free (objfile);
12084 return 1;
12086 #endif
12088 if (0 != rename (tmp_outfile_name, outfile_name)) {
12089 if (G_FILE_ERROR_EXIST == g_file_error_from_errno (errno)) {
12090 /* Since we are rebuilding the module we need to be able to replace any old copies. Remove old file and retry rename operation. */
12091 unlink (outfile_name);
12092 rename (tmp_outfile_name, outfile_name);
12096 #if defined(TARGET_MACH)
12097 command = g_strdup_printf ("dsymutil \"%s\"", outfile_name);
12098 aot_printf (acfg, "Executing dsymutil: %s\n", command);
12099 if (execute_system (command) != 0) {
12100 return 1;
12102 #endif
12104 if (!acfg->aot_opts.save_temps)
12105 unlink (objfile);
12107 g_free (tmp_outfile_name);
12108 g_free (outfile_name);
12109 g_free (objfile);
12111 if (acfg->aot_opts.save_temps)
12112 aot_printf (acfg, "Retained input file.\n");
12113 else
12114 unlink (acfg->tmpfname);
12116 return 0;
12119 static guint8
12120 profread_byte (FILE *infile)
12122 guint8 i;
12123 int res;
12125 res = fread (&i, 1, 1, infile);
12126 g_assert (res == 1);
12127 return i;
12130 static int
12131 profread_int (FILE *infile)
12133 int i, res;
12135 res = fread (&i, 4, 1, infile);
12136 g_assert (res == 1);
12137 return i;
12140 static char*
12141 profread_string (FILE *infile)
12143 int len, res;
12144 char *pbuf;
12146 len = profread_int (infile);
12147 pbuf = (char*)g_malloc (len + 1);
12148 res = fread (pbuf, 1, len, infile);
12149 g_assert (res == len);
12150 pbuf [len] = '\0';
12151 return pbuf;
12154 static void
12155 load_profile_file (MonoAotCompile *acfg, char *filename)
12157 FILE *infile;
12158 char buf [1024];
12159 int res, len, version;
12160 char magic [32];
12162 infile = fopen (filename, "r");
12163 if (!infile) {
12164 fprintf (stderr, "Unable to open file '%s': %s.\n", filename, strerror (errno));
12165 exit (1);
12168 printf ("Using profile data file '%s'\n", filename);
12170 sprintf (magic, AOT_PROFILER_MAGIC);
12171 len = strlen (magic);
12172 res = fread (buf, 1, len, infile);
12173 magic [len] = '\0';
12174 buf [len] = '\0';
12175 if ((res != len) || strcmp (buf, magic) != 0) {
12176 printf ("Profile file has wrong header: '%s'.\n", buf);
12177 fclose (infile);
12178 exit (1);
12180 guint32 expected_version = (AOT_PROFILER_MAJOR_VERSION << 16) | AOT_PROFILER_MINOR_VERSION;
12181 version = profread_int (infile);
12182 if (version != expected_version) {
12183 printf ("Profile file has wrong version 0x%4x, expected 0x%4x.\n", version, expected_version);
12184 fclose (infile);
12185 exit (1);
12188 ProfileData *data = g_new0 (ProfileData, 1);
12189 data->images = g_hash_table_new (NULL, NULL);
12190 data->classes = g_hash_table_new (NULL, NULL);
12191 data->ginsts = g_hash_table_new (NULL, NULL);
12192 data->methods = g_hash_table_new (NULL, NULL);
12194 while (TRUE) {
12195 int type = profread_byte (infile);
12196 int id = profread_int (infile);
12198 if (type == AOTPROF_RECORD_NONE)
12199 break;
12201 switch (type) {
12202 case AOTPROF_RECORD_IMAGE: {
12203 ImageProfileData *idata = g_new0 (ImageProfileData, 1);
12204 idata->name = profread_string (infile);
12205 char *mvid = profread_string (infile);
12206 g_free (mvid);
12207 g_hash_table_insert (data->images, GINT_TO_POINTER (id), idata);
12208 break;
12210 case AOTPROF_RECORD_GINST: {
12211 int i;
12212 int len = profread_int (infile);
12214 GInstProfileData *gdata = g_new0 (GInstProfileData, 1);
12215 gdata->argc = len;
12216 gdata->argv = g_new0 (ClassProfileData*, len);
12218 for (i = 0; i < len; ++i) {
12219 int class_id = profread_int (infile);
12221 gdata->argv [i] = (ClassProfileData*)g_hash_table_lookup (data->classes, GINT_TO_POINTER (class_id));
12222 g_assert (gdata->argv [i]);
12224 g_hash_table_insert (data->ginsts, GINT_TO_POINTER (id), gdata);
12225 break;
12227 case AOTPROF_RECORD_TYPE: {
12228 int type = profread_byte (infile);
12230 switch (type) {
12231 case MONO_TYPE_CLASS: {
12232 int image_id = profread_int (infile);
12233 int ginst_id = profread_int (infile);
12234 char *class_name = profread_string (infile);
12236 ImageProfileData *image = (ImageProfileData*)g_hash_table_lookup (data->images, GINT_TO_POINTER (image_id));
12237 g_assert (image);
12239 char *p = strrchr (class_name, '.');
12240 g_assert (p);
12241 *p = '\0';
12243 ClassProfileData *cdata = g_new0 (ClassProfileData, 1);
12244 cdata->image = image;
12245 cdata->ns = g_strdup (class_name);
12246 cdata->name = g_strdup (p + 1);
12248 if (ginst_id != -1) {
12249 cdata->inst = (GInstProfileData*)g_hash_table_lookup (data->ginsts, GINT_TO_POINTER (ginst_id));
12250 g_assert (cdata->inst);
12252 g_free (class_name);
12254 g_hash_table_insert (data->classes, GINT_TO_POINTER (id), cdata);
12255 break;
12257 #if 0
12258 case MONO_TYPE_SZARRAY: {
12259 int elem_id = profread_int (infile);
12260 // FIXME:
12261 break;
12263 #endif
12264 default:
12265 g_assert_not_reached ();
12266 break;
12268 break;
12270 case AOTPROF_RECORD_METHOD: {
12271 int class_id = profread_int (infile);
12272 int ginst_id = profread_int (infile);
12273 int param_count = profread_int (infile);
12274 char *method_name = profread_string (infile);
12275 char *sig = profread_string (infile);
12277 ClassProfileData *klass = (ClassProfileData*)g_hash_table_lookup (data->classes, GINT_TO_POINTER (class_id));
12278 g_assert (klass);
12280 MethodProfileData *mdata = g_new0 (MethodProfileData, 1);
12281 mdata->id = id;
12282 mdata->klass = klass;
12283 mdata->name = method_name;
12284 mdata->signature = sig;
12285 mdata->param_count = param_count;
12287 if (ginst_id != -1) {
12288 mdata->inst = (GInstProfileData*)g_hash_table_lookup (data->ginsts, GINT_TO_POINTER (ginst_id));
12289 g_assert (mdata->inst);
12291 g_hash_table_insert (data->methods, GINT_TO_POINTER (id), mdata);
12292 break;
12294 default:
12295 printf ("%d\n", type);
12296 g_assert_not_reached ();
12297 break;
12301 fclose (infile);
12302 acfg->profile_data = g_list_append (acfg->profile_data, data);
12305 static void
12306 resolve_class (ClassProfileData *cdata);
12308 static void
12309 resolve_ginst (GInstProfileData *inst_data)
12311 int i;
12313 if (inst_data->inst)
12314 return;
12316 for (i = 0; i < inst_data->argc; ++i) {
12317 resolve_class (inst_data->argv [i]);
12318 if (!inst_data->argv [i]->klass)
12319 return;
12321 MonoType **args = g_new0 (MonoType*, inst_data->argc);
12322 for (i = 0; i < inst_data->argc; ++i)
12323 args [i] = m_class_get_byval_arg (inst_data->argv [i]->klass);
12325 inst_data->inst = mono_metadata_get_generic_inst (inst_data->argc, args);
12328 static void
12329 resolve_class (ClassProfileData *cdata)
12331 ERROR_DECL (error);
12332 MonoClass *klass;
12334 if (!cdata->image->image)
12335 return;
12337 klass = mono_class_from_name_checked (cdata->image->image, cdata->ns, cdata->name, error);
12338 if (!klass) {
12339 //printf ("[%s] %s.%s\n", cdata->image->name, cdata->ns, cdata->name);
12340 return;
12342 if (cdata->inst) {
12343 resolve_ginst (cdata->inst);
12344 if (!cdata->inst->inst)
12345 return;
12346 MonoGenericContext ctx;
12348 memset (&ctx, 0, sizeof (ctx));
12349 ctx.class_inst = cdata->inst->inst;
12350 cdata->klass = mono_class_inflate_generic_class_checked (klass, &ctx, error);
12351 } else {
12352 cdata->klass = klass;
12357 * Resolve the profile data to the corresponding loaded classes/methods etc. if possible.
12359 static void
12360 resolve_profile_data (MonoAotCompile *acfg, ProfileData *data, MonoAssembly* current)
12362 GHashTableIter iter;
12363 gpointer key, value;
12364 int i;
12366 if (!data)
12367 return;
12369 /* Images */
12370 GPtrArray *assemblies = mono_domain_get_assemblies (mono_get_root_domain (), FALSE);
12371 g_hash_table_iter_init (&iter, data->images);
12372 while (g_hash_table_iter_next (&iter, &key, &value)) {
12373 ImageProfileData *idata = (ImageProfileData*)value;
12375 if (!strcmp (current->aname.name, idata->name)) {
12376 idata->image = current->image;
12377 break;
12380 for (i = 0; i < assemblies->len; ++i) {
12381 MonoAssembly *ass = (MonoAssembly*)g_ptr_array_index (assemblies, i);
12383 if (!strcmp (ass->aname.name, idata->name)) {
12384 idata->image = ass->image;
12385 break;
12389 g_ptr_array_free (assemblies, TRUE);
12391 /* Classes */
12392 g_hash_table_iter_init (&iter, data->classes);
12393 while (g_hash_table_iter_next (&iter, &key, &value)) {
12394 ClassProfileData *cdata = (ClassProfileData*)value;
12396 if (!cdata->image->image) {
12397 if (acfg->aot_opts.verbose)
12398 printf ("Unable to load class '%s.%s' because its image '%s' is not loaded.\n", cdata->ns, cdata->name, cdata->image->name);
12399 continue;
12402 resolve_class (cdata);
12404 if (cdata->klass)
12405 printf ("%s %s %s\n", cdata->ns, cdata->name, mono_class_full_name (cdata->klass));
12409 /* Methods */
12410 g_hash_table_iter_init (&iter, data->methods);
12411 while (g_hash_table_iter_next (&iter, &key, &value)) {
12412 MethodProfileData *mdata = (MethodProfileData*)value;
12413 MonoClass *klass;
12414 MonoMethod *m;
12415 gpointer miter;
12417 resolve_class (mdata->klass);
12418 klass = mdata->klass->klass;
12419 if (!klass) {
12420 if (acfg->aot_opts.verbose)
12421 printf ("Unable to load method '%s' because its class '%s.%s' is not loaded.\n", mdata->name, mdata->klass->ns, mdata->klass->name);
12422 continue;
12424 miter = NULL;
12425 while ((m = mono_class_get_methods (klass, &miter))) {
12426 ERROR_DECL (error);
12428 if (strcmp (m->name, mdata->name))
12429 continue;
12430 MonoMethodSignature *sig = mono_method_signature_internal (m);
12431 if (!sig)
12432 continue;
12433 if (sig->param_count != mdata->param_count)
12434 continue;
12435 if (mdata->inst) {
12436 resolve_ginst (mdata->inst);
12437 if (!mdata->inst->inst)
12438 continue;
12439 MonoGenericContext ctx;
12441 memset (&ctx, 0, sizeof (ctx));
12442 ctx.method_inst = mdata->inst->inst;
12444 m = mono_class_inflate_generic_method_checked (m, &ctx, error);
12445 if (!m)
12446 continue;
12447 sig = mono_method_signature_checked (m, error);
12448 if (!is_ok (error)) {
12449 mono_error_cleanup (error);
12450 continue;
12453 char *sig_str = mono_signature_full_name (sig);
12454 gboolean match = !strcmp (sig_str, mdata->signature);
12455 g_free (sig_str);
12456 if (!match)
12458 continue;
12459 //printf ("%s\n", mono_method_full_name (m, 1));
12460 mdata->method = m;
12461 break;
12463 if (!mdata->method) {
12464 if (acfg->aot_opts.verbose)
12465 printf ("Unable to load method '%s' from class '%s', not found.\n", mdata->name, mono_class_full_name (klass));
12470 static gboolean
12471 inst_references_image (MonoGenericInst *inst, MonoImage *image)
12473 int i;
12475 for (i = 0; i < inst->type_argc; ++i) {
12476 MonoClass *k = mono_class_from_mono_type_internal (inst->type_argv [i]);
12477 if (m_class_get_image (k) == image)
12478 return TRUE;
12479 if (mono_class_is_ginst (k)) {
12480 MonoGenericInst *kinst = mono_class_get_context (k)->class_inst;
12481 if (inst_references_image (kinst, image))
12482 return TRUE;
12485 return FALSE;
12488 static gboolean
12489 is_local_inst (MonoGenericInst *inst, MonoImage *image)
12491 int i;
12493 for (i = 0; i < inst->type_argc; ++i) {
12494 MonoClass *k = mono_class_from_mono_type_internal (inst->type_argv [i]);
12495 if (!MONO_TYPE_IS_PRIMITIVE (inst->type_argv [i]) && m_class_get_image (k) != image)
12496 return FALSE;
12498 return TRUE;
12501 static void
12502 add_profile_instances (MonoAotCompile *acfg, ProfileData *data)
12504 GHashTableIter iter;
12505 gpointer key, value;
12506 int count = 0;
12508 if (!data)
12509 return;
12511 if (acfg->aot_opts.profile_only) {
12512 /* Add methods referenced by the profile */
12513 g_hash_table_iter_init (&iter, data->methods);
12514 while (g_hash_table_iter_next (&iter, &key, &value)) {
12515 MethodProfileData *mdata = (MethodProfileData*)value;
12516 MonoMethod *m = mdata->method;
12518 if (!m)
12519 continue;
12520 if (m->is_inflated)
12521 continue;
12522 add_extra_method (acfg, m);
12523 g_hash_table_insert (acfg->profile_methods, m, m);
12524 count ++;
12529 * Add method instances 'related' to this assembly to the AOT image.
12531 g_hash_table_iter_init (&iter, data->methods);
12532 while (g_hash_table_iter_next (&iter, &key, &value)) {
12533 MethodProfileData *mdata = (MethodProfileData*)value;
12534 MonoMethod *m = mdata->method;
12535 MonoGenericContext *ctx;
12537 if (!m)
12538 continue;
12539 if (!m->is_inflated)
12540 continue;
12542 ctx = mono_method_get_context (m);
12543 /* For simplicity, add instances which reference the assembly we are compiling */
12544 if (((ctx->class_inst && inst_references_image (ctx->class_inst, acfg->image)) ||
12545 (ctx->method_inst && inst_references_image (ctx->method_inst, acfg->image))) &&
12546 !mono_method_is_generic_sharable_full (m, FALSE, FALSE, FALSE)) {
12547 //printf ("%s\n", mono_method_full_name (m, TRUE));
12548 add_extra_method (acfg, m);
12549 count ++;
12550 } else if (m_class_get_image (m->klass) == acfg->image &&
12551 ((ctx->class_inst && is_local_inst (ctx->class_inst, acfg->image)) ||
12552 (ctx->method_inst && is_local_inst (ctx->method_inst, acfg->image))) &&
12553 !mono_method_is_generic_sharable_full (m, FALSE, FALSE, FALSE)) {
12554 /* Add instances where the gtd is in the assembly and its inflated with types from this assembly or corlib */
12555 //printf ("%s\n", mono_method_full_name (m, TRUE));
12556 add_extra_method (acfg, m);
12557 count ++;
12560 * FIXME: We might skip some instances, for example:
12561 * Foo<Bar> won't be compiled when compiling Foo's assembly since it doesn't match the first case,
12562 * and it won't be compiled when compiling Bar's assembly if Foo's assembly is not loaded.
12566 printf ("Added %d methods from profile.\n", count);
12569 static void
12570 init_got_info (GotInfo *info)
12572 int i;
12574 info->patch_to_got_offset = g_hash_table_new (mono_patch_info_hash, mono_patch_info_equal);
12575 info->patch_to_got_offset_by_type = g_new0 (GHashTable*, MONO_PATCH_INFO_NUM);
12576 for (i = 0; i < MONO_PATCH_INFO_NUM; ++i)
12577 info->patch_to_got_offset_by_type [i] = g_hash_table_new (mono_patch_info_hash, mono_patch_info_equal);
12578 info->got_patches = g_ptr_array_new ();
12581 static MonoAotCompile*
12582 acfg_create (MonoAssembly *ass, guint32 opts)
12584 MonoImage *image = ass->image;
12585 MonoAotCompile *acfg;
12587 acfg = g_new0 (MonoAotCompile, 1);
12588 acfg->methods = g_ptr_array_new ();
12589 acfg->method_indexes = g_hash_table_new (NULL, NULL);
12590 acfg->method_depth = g_hash_table_new (NULL, NULL);
12591 acfg->plt_offset_to_entry = g_hash_table_new (NULL, NULL);
12592 acfg->patch_to_plt_entry = g_new0 (GHashTable*, MONO_PATCH_INFO_NUM);
12593 acfg->method_to_cfg = g_hash_table_new (NULL, NULL);
12594 acfg->token_info_hash = g_hash_table_new_full (NULL, NULL, NULL, NULL);
12595 acfg->method_to_pinvoke_import = g_hash_table_new_full (NULL, NULL, NULL, g_free);
12596 acfg->method_to_external_icall_symbol_name = g_hash_table_new_full (NULL, NULL, NULL, g_free);
12597 acfg->image_hash = g_hash_table_new (NULL, NULL);
12598 acfg->image_table = g_ptr_array_new ();
12599 acfg->globals = g_ptr_array_new ();
12600 acfg->image = image;
12601 acfg->opts = opts;
12602 /* TODO: Write out set of SIMD instructions used, rather than just those available */
12603 #ifndef MONO_CROSS_COMPILE
12604 acfg->simd_opts = mono_arch_cpu_enumerate_simd_versions ();
12605 #endif
12606 acfg->mempool = mono_mempool_new ();
12607 acfg->extra_methods = g_ptr_array_new ();
12608 acfg->unwind_info_offsets = g_hash_table_new (NULL, NULL);
12609 acfg->unwind_ops = g_ptr_array_new ();
12610 acfg->method_label_hash = g_hash_table_new_full (g_str_hash, g_str_equal, g_free, NULL);
12611 acfg->method_order = g_ptr_array_new ();
12612 acfg->export_names = g_hash_table_new (NULL, NULL);
12613 acfg->klass_blob_hash = g_hash_table_new (NULL, NULL);
12614 acfg->method_blob_hash = g_hash_table_new (NULL, NULL);
12615 acfg->ginst_blob_hash = g_hash_table_new (mono_metadata_generic_inst_hash, mono_metadata_generic_inst_equal);
12616 acfg->plt_entry_debug_sym_cache = g_hash_table_new (g_str_hash, g_str_equal);
12617 acfg->gsharedvt_in_signatures = g_hash_table_new ((GHashFunc)mono_signature_hash, (GEqualFunc)mono_metadata_signature_equal);
12618 acfg->gsharedvt_out_signatures = g_hash_table_new ((GHashFunc)mono_signature_hash, (GEqualFunc)mono_metadata_signature_equal);
12619 acfg->profile_methods = g_hash_table_new (NULL, NULL);
12620 mono_os_mutex_init_recursive (&acfg->mutex);
12622 init_got_info (&acfg->got_info);
12623 init_got_info (&acfg->llvm_got_info);
12625 method_to_external_icall_symbol_name = acfg->method_to_external_icall_symbol_name;
12626 return acfg;
12629 static void
12630 got_info_free (GotInfo *info)
12632 int i;
12634 for (i = 0; i < MONO_PATCH_INFO_NUM; ++i)
12635 g_hash_table_destroy (info->patch_to_got_offset_by_type [i]);
12636 g_free (info->patch_to_got_offset_by_type);
12637 g_hash_table_destroy (info->patch_to_got_offset);
12638 g_ptr_array_free (info->got_patches, TRUE);
12641 static void
12642 acfg_free (MonoAotCompile *acfg)
12644 int i;
12646 mono_img_writer_destroy (acfg->w);
12647 for (i = 0; i < acfg->nmethods; ++i)
12648 if (acfg->cfgs [i])
12649 mono_destroy_compile (acfg->cfgs [i]);
12651 g_free (acfg->cfgs);
12653 g_free (acfg->static_linking_symbol);
12654 g_free (acfg->got_symbol);
12655 g_free (acfg->plt_symbol);
12656 g_ptr_array_free (acfg->methods, TRUE);
12657 g_ptr_array_free (acfg->image_table, TRUE);
12658 g_ptr_array_free (acfg->globals, TRUE);
12659 g_ptr_array_free (acfg->unwind_ops, TRUE);
12660 g_hash_table_destroy (acfg->method_indexes);
12661 g_hash_table_destroy (acfg->method_depth);
12662 g_hash_table_destroy (acfg->plt_offset_to_entry);
12663 for (i = 0; i < MONO_PATCH_INFO_NUM; ++i)
12664 g_hash_table_destroy (acfg->patch_to_plt_entry [i]);
12665 g_free (acfg->patch_to_plt_entry);
12666 g_hash_table_destroy (acfg->method_to_cfg);
12667 g_hash_table_destroy (acfg->token_info_hash);
12668 g_hash_table_destroy (acfg->method_to_pinvoke_import);
12669 g_hash_table_destroy (acfg->method_to_external_icall_symbol_name);
12670 g_hash_table_destroy (acfg->image_hash);
12671 g_hash_table_destroy (acfg->unwind_info_offsets);
12672 g_hash_table_destroy (acfg->method_label_hash);
12673 g_hash_table_destroy (acfg->typespec_classes);
12674 g_hash_table_destroy (acfg->export_names);
12675 g_hash_table_destroy (acfg->plt_entry_debug_sym_cache);
12676 g_hash_table_destroy (acfg->klass_blob_hash);
12677 g_hash_table_destroy (acfg->method_blob_hash);
12678 got_info_free (&acfg->got_info);
12679 got_info_free (&acfg->llvm_got_info);
12680 arch_free_unwind_info_section_cache (acfg);
12681 mono_mempool_destroy (acfg->mempool);
12683 method_to_external_icall_symbol_name = NULL;
12684 g_free (acfg);
12687 #define WRAPPER(e,n) n,
12688 static const char* const
12689 wrapper_type_names [MONO_WRAPPER_NUM + 1] = {
12690 #include "mono/metadata/wrapper-types.h"
12691 NULL
12694 static G_GNUC_UNUSED const char*
12695 get_wrapper_type_name (int type)
12697 return wrapper_type_names [type];
12700 //#define DUMP_PLT
12701 //#define DUMP_GOT
12703 static void aot_dump (MonoAotCompile *acfg)
12705 FILE *dumpfile;
12706 char * dumpname;
12708 JsonWriter writer;
12709 mono_json_writer_init (&writer);
12711 mono_json_writer_object_begin(&writer);
12713 // Methods
12714 mono_json_writer_indent (&writer);
12715 mono_json_writer_object_key(&writer, "methods");
12716 mono_json_writer_array_begin (&writer);
12718 int i;
12719 for (i = 0; i < acfg->nmethods; ++i) {
12720 MonoCompile *cfg;
12721 MonoMethod *method;
12722 MonoClass *klass;
12724 cfg = acfg->cfgs [i];
12725 if (ignore_cfg (cfg))
12726 continue;
12728 method = cfg->orig_method;
12730 mono_json_writer_indent (&writer);
12731 mono_json_writer_object_begin(&writer);
12733 mono_json_writer_indent (&writer);
12734 mono_json_writer_object_key(&writer, "name");
12735 mono_json_writer_printf (&writer, "\"%s\",\n", method->name);
12737 mono_json_writer_indent (&writer);
12738 mono_json_writer_object_key(&writer, "signature");
12739 mono_json_writer_printf (&writer, "\"%s\",\n", mono_method_get_full_name (method));
12741 mono_json_writer_indent (&writer);
12742 mono_json_writer_object_key(&writer, "code_size");
12743 mono_json_writer_printf (&writer, "\"%d\",\n", cfg->code_size);
12745 klass = method->klass;
12747 mono_json_writer_indent (&writer);
12748 mono_json_writer_object_key(&writer, "class");
12749 mono_json_writer_printf (&writer, "\"%s\",\n", m_class_get_name (klass));
12751 mono_json_writer_indent (&writer);
12752 mono_json_writer_object_key(&writer, "namespace");
12753 mono_json_writer_printf (&writer, "\"%s\",\n", m_class_get_name_space (klass));
12755 mono_json_writer_indent (&writer);
12756 mono_json_writer_object_key(&writer, "wrapper_type");
12757 mono_json_writer_printf (&writer, "\"%s\",\n", get_wrapper_type_name(method->wrapper_type));
12759 mono_json_writer_indent_pop (&writer);
12760 mono_json_writer_indent (&writer);
12761 mono_json_writer_object_end (&writer);
12762 mono_json_writer_printf (&writer, ",\n");
12765 mono_json_writer_indent_pop (&writer);
12766 mono_json_writer_indent (&writer);
12767 mono_json_writer_array_end (&writer);
12768 mono_json_writer_printf (&writer, ",\n");
12770 // PLT entries
12771 #ifdef DUMP_PLT
12772 mono_json_writer_indent_push (&writer);
12773 mono_json_writer_indent (&writer);
12774 mono_json_writer_object_key(&writer, "plt");
12775 mono_json_writer_array_begin (&writer);
12777 for (i = 0; i < acfg->plt_offset; ++i) {
12778 MonoPltEntry *plt_entry = NULL;
12779 MonoJumpInfo *ji;
12781 if (i == 0)
12783 * The first plt entry is unused.
12785 continue;
12787 plt_entry = g_hash_table_lookup (acfg->plt_offset_to_entry, GUINT_TO_POINTER (i));
12788 ji = plt_entry->ji;
12790 mono_json_writer_indent (&writer);
12791 mono_json_writer_printf (&writer, "{ ");
12792 mono_json_writer_object_key(&writer, "symbol");
12793 mono_json_writer_printf (&writer, "\"%s\" },\n", plt_entry->symbol);
12796 mono_json_writer_indent_pop (&writer);
12797 mono_json_writer_indent (&writer);
12798 mono_json_writer_array_end (&writer);
12799 mono_json_writer_printf (&writer, ",\n");
12800 #endif
12802 // GOT entries
12803 #ifdef DUMP_GOT
12804 mono_json_writer_indent_push (&writer);
12805 mono_json_writer_indent (&writer);
12806 mono_json_writer_object_key(&writer, "got");
12807 mono_json_writer_array_begin (&writer);
12809 mono_json_writer_indent_push (&writer);
12810 for (i = 0; i < acfg->got_info.got_patches->len; ++i) {
12811 MonoJumpInfo *ji = g_ptr_array_index (acfg->got_info.got_patches, i);
12813 mono_json_writer_indent (&writer);
12814 mono_json_writer_printf (&writer, "{ ");
12815 mono_json_writer_object_key(&writer, "patch_name");
12816 mono_json_writer_printf (&writer, "\"%s\" },\n", get_patch_name (ji->type));
12819 mono_json_writer_indent_pop (&writer);
12820 mono_json_writer_indent (&writer);
12821 mono_json_writer_array_end (&writer);
12822 mono_json_writer_printf (&writer, ",\n");
12823 #endif
12825 mono_json_writer_indent_pop (&writer);
12826 mono_json_writer_indent (&writer);
12827 mono_json_writer_object_end (&writer);
12829 dumpname = g_strdup_printf ("%s.json", g_path_get_basename (acfg->image->name));
12830 dumpfile = fopen (dumpname, "w+");
12831 g_free (dumpname);
12833 fprintf (dumpfile, "%s", writer.text->str);
12834 fclose (dumpfile);
12836 mono_json_writer_destroy (&writer);
12839 static const MonoJitICallId preinited_jit_icalls [] = {
12840 MONO_JIT_ICALL_mini_llvm_init_method,
12841 MONO_JIT_ICALL_mini_llvm_init_gshared_method_this,
12842 MONO_JIT_ICALL_mini_llvm_init_gshared_method_mrgctx,
12843 MONO_JIT_ICALL_mini_llvm_init_gshared_method_vtable,
12844 MONO_JIT_ICALL_mini_llvmonly_throw_nullref_exception,
12845 MONO_JIT_ICALL_mono_llvm_throw_corlib_exception,
12846 MONO_JIT_ICALL_mono_threads_state_poll,
12847 MONO_JIT_ICALL_mini_llvmonly_init_vtable_slot,
12848 MONO_JIT_ICALL_mono_helper_ldstr_mscorlib,
12849 MONO_JIT_ICALL_mono_fill_method_rgctx,
12850 MONO_JIT_ICALL_mono_fill_class_rgctx
12853 static void
12854 add_preinit_slot (MonoAotCompile *acfg, MonoJumpInfo *ji)
12856 if (!acfg->aot_opts.llvm_only)
12857 get_got_offset (acfg, FALSE, ji);
12858 get_got_offset (acfg, TRUE, ji);
12861 static void
12862 add_preinit_got_slots (MonoAotCompile *acfg)
12864 MonoJumpInfo *ji;
12865 int i;
12868 * Allocate the first few GOT entries to information which is needed frequently, or it is needed
12869 * during method initialization etc.
12872 ji = (MonoJumpInfo *)mono_mempool_alloc0 (acfg->mempool, sizeof (MonoJumpInfo));
12873 ji->type = MONO_PATCH_INFO_IMAGE;
12874 ji->data.image = acfg->image;
12875 add_preinit_slot (acfg, ji);
12877 ji = (MonoJumpInfo *)mono_mempool_alloc0 (acfg->mempool, sizeof (MonoJumpInfo));
12878 ji->type = MONO_PATCH_INFO_MSCORLIB_GOT_ADDR;
12879 add_preinit_slot (acfg, ji);
12881 ji = (MonoJumpInfo *)mono_mempool_alloc0 (acfg->mempool, sizeof (MonoJumpInfo));
12882 ji->type = MONO_PATCH_INFO_GC_CARD_TABLE_ADDR;
12883 add_preinit_slot (acfg, ji);
12885 ji = (MonoJumpInfo *)mono_mempool_alloc0 (acfg->mempool, sizeof (MonoJumpInfo));
12886 ji->type = MONO_PATCH_INFO_GC_NURSERY_START;
12887 add_preinit_slot (acfg, ji);
12889 ji = (MonoJumpInfo *)mono_mempool_alloc0 (acfg->mempool, sizeof (MonoJumpInfo));
12890 ji->type = MONO_PATCH_INFO_AOT_MODULE;
12891 add_preinit_slot (acfg, ji);
12893 ji = (MonoJumpInfo *)mono_mempool_alloc0 (acfg->mempool, sizeof (MonoJumpInfo));
12894 ji->type = MONO_PATCH_INFO_GC_NURSERY_BITS;
12895 add_preinit_slot (acfg, ji);
12897 ji = (MonoJumpInfo *)mono_mempool_alloc0 (acfg->mempool, sizeof (MonoJumpInfo));
12898 ji->type = MONO_PATCH_INFO_INTERRUPTION_REQUEST_FLAG;
12899 add_preinit_slot (acfg, ji);
12901 ji = (MonoJumpInfo *)mono_mempool_alloc0 (acfg->mempool, sizeof (MonoJumpInfo));
12902 ji->type = MONO_PATCH_INFO_GC_SAFE_POINT_FLAG;
12903 add_preinit_slot (acfg, ji);
12905 if (!acfg->aot_opts.llvm_only) {
12906 for (i = 0; i < TLS_KEY_NUM; i++) {
12907 ji = (MonoJumpInfo *)mono_mempool_alloc0 (acfg->mempool, sizeof (MonoJumpInfo));
12908 ji->type = MONO_PATCH_INFO_GET_TLS_TRAMP;
12909 ji->data.index = i;
12910 add_preinit_slot (acfg, ji);
12912 ji = (MonoJumpInfo *)mono_mempool_alloc0 (acfg->mempool, sizeof (MonoJumpInfo));
12913 ji->type = MONO_PATCH_INFO_SET_TLS_TRAMP;
12914 ji->data.index = i;
12915 add_preinit_slot (acfg, ji);
12919 /* Called by native-to-managed wrappers on possibly unattached threads */
12920 ji = (MonoJumpInfo *)mono_mempool_alloc0 (acfg->mempool, sizeof (MonoJumpInfo));
12921 ji->type = MONO_PATCH_INFO_JIT_ICALL_ADDR_NOCALL;
12922 ji->data.name = "mono_threads_attach_coop";
12923 add_preinit_slot (acfg, ji);
12925 for (i = 0; i < G_N_ELEMENTS (preinited_jit_icalls); ++i) {
12926 ji = (MonoJumpInfo *)mono_mempool_alloc0 (acfg->mempool, sizeof (MonoAotCompile));
12927 ji->type = MONO_PATCH_INFO_JIT_ICALL_ID;
12928 ji->data.jit_icall_id = preinited_jit_icalls [i];
12929 add_preinit_slot (acfg, ji);
12932 if (acfg->aot_opts.llvm_only)
12933 acfg->nshared_got_entries = acfg->llvm_got_offset;
12934 else
12935 acfg->nshared_got_entries = acfg->got_offset;
12936 g_assert (acfg->nshared_got_entries);
12939 static void
12940 mono_dedup_log_stats (MonoAotCompile *acfg)
12942 GHashTableIter iter;
12943 g_assert (acfg->dedup_stats);
12945 if (!acfg->dedup_emit_mode)
12946 return;
12948 // If dedup_emit_mode, acfg is the dummy dedup module that consolidates
12949 // deduped modules
12950 g_hash_table_iter_init (&iter, acfg->method_to_cfg);
12951 MonoCompile *dcfg = NULL;
12952 MonoMethod *method = NULL;
12954 size_t wrappers_size_saved = 0;
12955 size_t inflated_size_saved = 0;
12956 size_t copied_singles = 0;
12957 int wrappers_saved = 0;
12958 int instances_saved = 0;
12959 int copied = 0;
12961 while (g_hash_table_iter_next (&iter, (gpointer *) &method, (gpointer *)&dcfg)) {
12962 gchar *dedup_name = mono_aot_get_mangled_method_name (method);
12963 guint count = GPOINTER_TO_UINT(g_hash_table_lookup (acfg->dedup_stats, dedup_name));
12965 if (count == 0)
12966 continue;
12968 if (acfg->dedup_emit_mode) {
12969 // Size *saved* is the size due to things not emitted.
12970 if (count < 2) {
12971 // Just moved, didn't save space / dedup
12972 copied ++;
12973 copied_singles += dcfg->code_len;
12974 } else if (method->wrapper_type != MONO_WRAPPER_NONE) {
12975 wrappers_saved ++;
12976 wrappers_size_saved += dcfg->code_len * (count - 1);
12977 } else {
12978 instances_saved ++;
12979 inflated_size_saved += dcfg->code_len * (count - 1);
12982 if (acfg->aot_opts.dedup) {
12983 if (method->wrapper_type != MONO_WRAPPER_NONE) {
12984 wrappers_saved ++;
12985 wrappers_size_saved += dcfg->code_len * count;
12986 } else {
12987 instances_saved ++;
12988 inflated_size_saved += dcfg->code_len * count;
12993 aot_printf (acfg, "Dedup Pass: Size Saved From Deduped Wrappers:\t%d methods, %zu bytes\n", wrappers_saved, wrappers_size_saved);
12994 aot_printf (acfg, "Dedup Pass: Size Saved From Inflated Methods:\t%d methods, %zu bytes\n", instances_saved, inflated_size_saved);
12995 if (acfg->dedup_emit_mode)
12996 aot_printf (acfg, "Dedup Pass: Size of Moved But Not Deduped (only 1 copy) Methods:\t%d methods, %zu bytes\n", copied, copied_singles);
12998 g_hash_table_destroy (acfg->dedup_stats);
12999 acfg->dedup_stats = NULL;
13002 // Flush the cache to tell future calls what to skip
13003 static void
13004 mono_flush_method_cache (MonoAotCompile *acfg)
13006 GHashTable *method_cache = acfg->dedup_cache;
13007 char *filename = g_strdup_printf ("%s.dedup", acfg->image->name);
13008 if (!acfg->dedup_cache_changed || !acfg->aot_opts.dedup) {
13009 g_free (filename);
13010 return;
13013 acfg->dedup_cache = NULL;
13015 FILE *cache = fopen (filename, "w");
13017 if (!cache)
13018 g_error ("Could not create cache at %s because of error: %s\n", filename, strerror (errno));
13020 GHashTableIter iter;
13021 gchar *name = NULL;
13022 g_hash_table_iter_init (&iter, method_cache);
13023 gboolean cont = TRUE;
13024 while (cont && g_hash_table_iter_next (&iter, (gpointer *) &name, NULL)) {
13025 int res = fprintf (cache, "%s\n", name);
13026 cont = res >= 0;
13028 // FIXME: don't assert if error when flushing
13029 g_assert (cont);
13031 fclose (cache);
13032 g_free (filename);
13034 // The keys are all in the imageset, nothing to free
13035 // Values are just pointers to memory owned elsewhere, or sentinels
13036 g_hash_table_destroy (method_cache);
13039 // Read in what has been emitted by previous invocations,
13040 // what can be skipped
13041 static void
13042 mono_read_method_cache (MonoAotCompile *acfg)
13044 char *filename = g_strdup_printf ("%s.dedup", acfg->image->name);
13045 // Only do once, when dedup_cache is null
13046 if (acfg->dedup_cache)
13047 goto early_exit;
13049 if (acfg->aot_opts.dedup_include || acfg->aot_opts.dedup)
13050 g_assert (acfg->dedup_stats);
13052 // only in skip mode
13053 if (!acfg->aot_opts.dedup)
13054 goto early_exit;
13056 g_assert (acfg->dedup_cache);
13058 FILE *cache;
13059 cache = fopen (filename, "r");
13060 if (!cache)
13061 goto early_exit;
13063 // Since we do pointer comparisons, and it can't be allocated at
13064 // the address 0x1 due to alignment, we use this as a sentinel
13065 gpointer other_acfg_sentinel;
13066 other_acfg_sentinel = GINT_TO_POINTER (0x1);
13068 if (fseek (cache, 0L, SEEK_END))
13069 goto cleanup;
13071 size_t fileLength;
13072 fileLength = ftell (cache);
13073 g_assert (fileLength > 0);
13075 if (fseek (cache, 0L, SEEK_SET))
13076 goto cleanup;
13078 // Avoid thousands of new malloc entries
13079 // FIXME: allocate into imageset, so we don't need to free.
13080 // put the other mangled names there too.
13081 char *bulk;
13082 bulk = g_malloc0 (fileLength * sizeof (char));
13083 size_t offset;
13084 offset = 0;
13086 while (fgets (&bulk [offset], fileLength - offset, cache)) {
13087 // strip newline
13088 char *line = &bulk [offset];
13089 size_t len = strlen (line);
13090 if (len == 0)
13091 break;
13093 if (len >= 0 && line [len] == '\n')
13094 line [len] = '\0';
13095 offset += strlen (line) + 1;
13096 g_assert (fileLength >= offset);
13098 g_hash_table_insert (acfg->dedup_cache, line, other_acfg_sentinel);
13101 cleanup:
13102 fclose (cache);
13104 early_exit:
13105 g_free (filename);
13106 return;
13109 typedef struct {
13110 GHashTable *cache;
13111 GHashTable *stats;
13112 gboolean emit_inflated_methods;
13113 MonoAssembly *inflated_assembly;
13114 } MonoAotState;
13116 static MonoAotState *
13117 alloc_aot_state (void)
13119 MonoAotState *state = g_malloc (sizeof (MonoAotState));
13120 // FIXME: Should this own the memory?
13121 state->cache = g_hash_table_new (g_str_hash, g_str_equal);
13122 state->stats = g_hash_table_new (g_str_hash, g_str_equal);
13123 // Start in "collect mode"
13124 state->emit_inflated_methods = FALSE;
13125 state->inflated_assembly = NULL;
13126 return state;
13129 static void
13130 free_aot_state (MonoAotState *astate)
13132 g_hash_table_destroy (astate->cache);
13133 g_free (astate);
13136 static void
13137 mono_add_deferred_extra_methods (MonoAotCompile *acfg, MonoAotState *astate)
13139 GHashTableIter iter;
13140 gchar *name = NULL;
13141 MonoMethod *method = NULL;
13143 acfg->dedup_emit_mode = TRUE;
13145 g_hash_table_iter_init (&iter, astate->cache);
13146 while (g_hash_table_iter_next (&iter, (gpointer *) &name, (gpointer *) &method)) {
13147 add_method_full (acfg, method, TRUE, 0);
13149 return;
13152 static void
13153 mono_setup_dedup_state (MonoAotCompile *acfg, MonoAotState **global_aot_state, MonoAssembly *ass, MonoAotState **astate, gboolean *is_dedup_dummy)
13155 if (!acfg->aot_opts.dedup_include && !acfg->aot_opts.dedup)
13156 return;
13158 if (global_aot_state && *global_aot_state && acfg->aot_opts.dedup_include) {
13159 // Thread the state through when making the inflate pass
13160 *astate = *global_aot_state;
13163 if (!*astate) {
13164 *astate = alloc_aot_state ();
13165 *global_aot_state = *astate;
13168 acfg->dedup_cache = (*astate)->cache;
13169 acfg->dedup_stats = (*astate)->stats;
13171 // fills out acfg->dedup_cache
13172 if (acfg->aot_opts.dedup)
13173 mono_read_method_cache (acfg);
13175 if (!(*astate)->inflated_assembly && acfg->aot_opts.dedup_include) {
13176 gchar **asm_path = g_strsplit (ass->image->name, G_DIR_SEPARATOR_S, 0);
13177 gchar *asm_file = NULL;
13179 // Get the last part of the path, the filename
13180 for (int i=0; asm_path [i] != NULL; i++)
13181 asm_file = asm_path [i];
13183 if (!strcmp (acfg->aot_opts.dedup_include, asm_file)) {
13184 // Save
13185 *is_dedup_dummy = TRUE;
13186 (*astate)->inflated_assembly = ass;
13188 g_strfreev (asm_path);
13189 } else if ((*astate)->inflated_assembly) {
13190 *is_dedup_dummy = (ass == (*astate)->inflated_assembly);
13194 int
13195 mono_compile_deferred_assemblies (guint32 opts, const char *aot_options, gpointer **aot_state)
13197 // create assembly, loop and add extra_methods
13198 // in add_generic_instances , rip out what's in that for loop
13199 // and apply that to this aot_state inside of mono_compile_assembly
13200 MonoAotState *astate;
13201 astate = *(MonoAotState **)aot_state;
13202 g_assert (astate);
13204 // FIXME: allow suffixes?
13205 if (!astate->inflated_assembly) {
13206 const char* inflate = strstr (aot_options, "dedup-inflate");
13207 if (!inflate)
13208 return 0;
13209 else
13210 g_error ("Error: mono was not given an assembly with the provided inflate name\n");
13213 // Switch modes
13214 astate->emit_inflated_methods = TRUE;
13216 int res = mono_compile_assembly (astate->inflated_assembly, opts, aot_options, aot_state);
13218 *aot_state = NULL;
13219 free_aot_state (astate);
13221 return res;
13224 #ifndef MONO_ARCH_HAVE_INTERP_ENTRY_TRAMPOLINE
13225 static MonoMethodSignature * const * const interp_in_static_sigs [] = {
13226 &mono_icall_sig_bool_ptr_int32_ptrref,
13227 &mono_icall_sig_bool_ptr_ptrref,
13228 &mono_icall_sig_int32_int32_ptrref,
13229 &mono_icall_sig_int32_int32_ptr_ptrref,
13230 &mono_icall_sig_int32_ptr_int32_ptr,
13231 &mono_icall_sig_int32_ptr_int32_ptrref,
13232 &mono_icall_sig_int32_ptr_ptrref,
13233 &mono_icall_sig_object_object_ptr_ptr_ptr,
13234 &mono_icall_sig_object,
13235 &mono_icall_sig_ptr_int32_ptrref,
13236 &mono_icall_sig_ptr_ptr_int32_ptr_ptr_ptrref,
13237 &mono_icall_sig_ptr_ptr_int32_ptr_ptrref,
13238 &mono_icall_sig_ptr_ptr_int32_ptrref,
13239 &mono_icall_sig_ptr_ptr_ptr_int32_ptrref,
13240 &mono_icall_sig_ptr_ptr_ptr_ptrref_ptrref,
13241 &mono_icall_sig_ptr_ptr_ptr_ptr_ptrref,
13242 &mono_icall_sig_ptr_ptr_ptr_ptrref,
13243 &mono_icall_sig_ptr_ptr_ptrref,
13244 &mono_icall_sig_ptr_ptr_uint32_ptrref,
13245 &mono_icall_sig_ptr_uint32_ptrref,
13246 &mono_icall_sig_void_object_ptr_ptr_ptr,
13247 &mono_icall_sig_void_ptr_ptr_int32_ptr_ptrref_ptr_ptrref,
13248 &mono_icall_sig_void_ptr_ptr_int32_ptr_ptrref,
13249 &mono_icall_sig_void_ptr_ptr_ptrref,
13250 &mono_icall_sig_void_ptr_ptrref,
13251 &mono_icall_sig_void_ptr,
13252 &mono_icall_sig_void_int32_ptrref,
13253 &mono_icall_sig_void_uint32_ptrref,
13254 &mono_icall_sig_void,
13256 #endif
13259 mono_compile_assembly (MonoAssembly *ass, guint32 opts, const char *aot_options, gpointer **global_aot_state)
13261 MonoImage *image = ass->image;
13262 int res;
13263 MonoAotCompile *acfg;
13264 char *p;
13265 TV_DECLARE (atv);
13266 TV_DECLARE (btv);
13268 acfg = acfg_create (ass, opts);
13270 memset (&acfg->aot_opts, 0, sizeof (acfg->aot_opts));
13271 acfg->aot_opts.write_symbols = TRUE;
13272 acfg->aot_opts.ntrampolines = 4096;
13273 acfg->aot_opts.nrgctx_trampolines = 4096;
13274 acfg->aot_opts.nimt_trampolines = 512;
13275 acfg->aot_opts.nrgctx_fetch_trampolines = 128;
13276 acfg->aot_opts.ngsharedvt_arg_trampolines = 512;
13277 #ifdef MONO_ARCH_HAVE_FTNPTR_ARG_TRAMPOLINE
13278 acfg->aot_opts.nftnptr_arg_trampolines = 128;
13279 #endif
13280 acfg->aot_opts.nunbox_arbitrary_trampolines = 256;
13281 if (!acfg->aot_opts.llvm_path)
13282 acfg->aot_opts.llvm_path = g_strdup ("");
13283 acfg->aot_opts.temp_path = g_strdup ("");
13284 #ifdef MONOTOUCH
13285 acfg->aot_opts.use_trampolines_page = TRUE;
13286 #endif
13287 acfg->aot_opts.clangxx = g_strdup ("clang++");
13289 mono_aot_parse_options (aot_options, &acfg->aot_opts);
13291 // start dedup
13292 MonoAotState *astate = NULL;
13293 gboolean is_dedup_dummy = FALSE;
13294 mono_setup_dedup_state (acfg, (MonoAotState **) global_aot_state, ass, &astate, &is_dedup_dummy);
13296 // Process later
13297 if (is_dedup_dummy && astate && !astate->emit_inflated_methods)
13298 return 0;
13300 if (acfg->aot_opts.dedup_include && !is_dedup_dummy)
13301 acfg->dedup_collect_only = TRUE;
13302 // end dedup
13304 if (acfg->aot_opts.logfile) {
13305 acfg->logfile = fopen (acfg->aot_opts.logfile, "a+");
13308 if (acfg->aot_opts.data_outfile) {
13309 acfg->data_outfile = fopen (acfg->aot_opts.data_outfile, "w+");
13310 if (!acfg->data_outfile) {
13311 aot_printerrf (acfg, "Unable to create file '%s': %s\n", acfg->aot_opts.data_outfile, strerror (errno));
13312 return 1;
13314 acfg->flags = (MonoAotFileFlags)(acfg->flags | MONO_AOT_FILE_FLAG_SEPARATE_DATA);
13317 //acfg->aot_opts.print_skipped_methods = TRUE;
13319 #if !defined(MONO_ARCH_GSHAREDVT_SUPPORTED)
13320 if (acfg->opts & MONO_OPT_GSHAREDVT) {
13321 aot_printerrf (acfg, "-O=gsharedvt not supported on this platform.\n");
13322 return 1;
13324 if (acfg->aot_opts.llvm_only) {
13325 aot_printerrf (acfg, "--aot=llvmonly requires a runtime that supports gsharedvt.\n");
13326 return 1;
13328 #else
13329 if (acfg->aot_opts.llvm_only || mono_aot_mode_is_full (&acfg->aot_opts) || mono_aot_mode_is_hybrid (&acfg->aot_opts))
13330 acfg->opts |= MONO_OPT_GSHAREDVT;
13331 #endif
13333 #if !defined(ENABLE_LLVM)
13334 if (acfg->aot_opts.llvm_only) {
13335 aot_printerrf (acfg, "--aot=llvmonly requires a runtime compiled with llvm support.\n");
13336 return 1;
13338 #endif
13340 if (acfg->opts & MONO_OPT_GSHAREDVT)
13341 mono_set_generic_sharing_vt_supported (TRUE);
13343 if (!acfg->dedup_collect_only)
13344 aot_printf (acfg, "Mono Ahead of Time compiler - compiling assembly %s\n", image->name);
13346 if (!acfg->aot_opts.deterministic)
13347 generate_aotid ((guint8*) &acfg->image->aotid);
13349 char *aotid = mono_guid_to_string (acfg->image->aotid);
13350 if (!acfg->dedup_collect_only)
13351 aot_printf (acfg, "AOTID %s\n", aotid);
13352 g_free (aotid);
13354 #ifndef MONO_ARCH_HAVE_FULL_AOT_TRAMPOLINES
13355 if (mono_aot_mode_is_full (&acfg->aot_opts)) {
13356 aot_printerrf (acfg, "--aot=full is not supported on this platform.\n");
13357 return 1;
13359 #endif
13361 if (acfg->aot_opts.direct_pinvoke && !acfg->aot_opts.static_link) {
13362 aot_printerrf (acfg, "The 'direct-pinvoke' AOT option also requires the 'static' AOT option.\n");
13363 return 1;
13366 if (acfg->aot_opts.static_link)
13367 acfg->aot_opts.asm_writer = TRUE;
13369 if (acfg->aot_opts.soft_debug) {
13370 MonoDebugOptions *opt = mini_get_debug_options ();
13372 opt->mdb_optimizations = TRUE;
13373 opt->gen_sdb_seq_points = TRUE;
13375 if (!mono_debug_enabled ()) {
13376 aot_printerrf (acfg, "The soft-debug AOT option requires the --debug option.\n");
13377 return 1;
13379 acfg->flags = (MonoAotFileFlags)(acfg->flags | MONO_AOT_FILE_FLAG_DEBUG);
13382 if (acfg->aot_opts.try_llvm)
13383 acfg->aot_opts.llvm = mini_llvm_init ();
13385 if (mono_use_llvm || acfg->aot_opts.llvm) {
13386 acfg->llvm = TRUE;
13387 acfg->aot_opts.asm_writer = TRUE;
13388 acfg->flags = (MonoAotFileFlags)(acfg->flags | MONO_AOT_FILE_FLAG_WITH_LLVM);
13390 if (acfg->aot_opts.soft_debug) {
13391 aot_printerrf (acfg, "The 'soft-debug' option is not supported when compiling with LLVM.\n");
13392 return 1;
13395 mini_llvm_init ();
13397 if (acfg->aot_opts.asm_only && !acfg->aot_opts.llvm_outfile) {
13398 aot_printerrf (acfg, "Compiling with LLVM and the asm-only option requires the llvm-outfile= option.\n");
13399 return 1;
13403 if (mono_aot_mode_is_full (&acfg->aot_opts)) {
13404 acfg->flags = (MonoAotFileFlags)(acfg->flags | MONO_AOT_FILE_FLAG_FULL_AOT);
13405 acfg->is_full_aot = TRUE;
13408 if (mono_aot_mode_is_interp (&acfg->aot_opts)) {
13409 acfg->flags = (MonoAotFileFlags)(acfg->flags | MONO_AOT_FILE_FLAG_INTERP);
13410 acfg->is_full_aot = TRUE;
13413 if (mini_safepoints_enabled ())
13414 acfg->flags = (MonoAotFileFlags)(acfg->flags | MONO_AOT_FILE_FLAG_SAFEPOINTS);
13416 // The methods in dedup-emit amodules must be available on runtime startup
13417 // Note: Only one such amodule can have this attribute
13418 if (astate && astate->emit_inflated_methods)
13419 acfg->flags = (MonoAotFileFlags)(acfg->flags | MONO_AOT_FILE_FLAG_EAGER_LOAD);
13422 if (acfg->aot_opts.instances_logfile_path) {
13423 acfg->instances_logfile = fopen (acfg->aot_opts.instances_logfile_path, "w");
13424 if (!acfg->instances_logfile) {
13425 aot_printerrf (acfg, "Unable to create logfile: '%s'.\n", acfg->aot_opts.instances_logfile_path);
13426 return 1;
13430 if (acfg->aot_opts.profile_files) {
13431 GList *l;
13433 for (l = acfg->aot_opts.profile_files; l; l = l->next) {
13434 load_profile_file (acfg, (char*)l->data);
13438 if (!(mono_aot_mode_is_interp (&acfg->aot_opts) && !mono_aot_mode_is_full (&acfg->aot_opts))) {
13439 for (int method_index = 0; method_index < acfg->image->tables [MONO_TABLE_METHOD].rows; ++method_index)
13440 g_ptr_array_add (acfg->method_order,GUINT_TO_POINTER (method_index));
13443 acfg->num_trampolines [MONO_AOT_TRAMP_SPECIFIC] = mono_aot_mode_is_full (&acfg->aot_opts) ? acfg->aot_opts.ntrampolines : 0;
13444 #ifdef MONO_ARCH_GSHARED_SUPPORTED
13445 acfg->num_trampolines [MONO_AOT_TRAMP_STATIC_RGCTX] = mono_aot_mode_is_full (&acfg->aot_opts) ? acfg->aot_opts.nrgctx_trampolines : 0;
13446 #endif
13447 acfg->num_trampolines [MONO_AOT_TRAMP_IMT] = mono_aot_mode_is_full (&acfg->aot_opts) ? acfg->aot_opts.nimt_trampolines : 0;
13448 #ifdef MONO_ARCH_GSHAREDVT_SUPPORTED
13449 if (acfg->opts & MONO_OPT_GSHAREDVT)
13450 acfg->num_trampolines [MONO_AOT_TRAMP_GSHAREDVT_ARG] = mono_aot_mode_is_full (&acfg->aot_opts) ? acfg->aot_opts.ngsharedvt_arg_trampolines : 0;
13451 #endif
13452 #ifdef MONO_ARCH_HAVE_FTNPTR_ARG_TRAMPOLINE
13453 acfg->num_trampolines [MONO_AOT_TRAMP_FTNPTR_ARG] = mono_aot_mode_is_interp (&acfg->aot_opts) ? acfg->aot_opts.nftnptr_arg_trampolines : 0;
13454 #endif
13455 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;
13457 acfg->temp_prefix = mono_img_writer_get_temp_label_prefix (NULL);
13459 arch_init (acfg);
13461 if (mono_use_llvm || acfg->aot_opts.llvm) {
13463 * Emit all LLVM code into a separate assembly/object file and link with it
13464 * normally.
13466 if (!acfg->aot_opts.asm_only && acfg->llvm_owriter_supported) {
13467 acfg->llvm_owriter = TRUE;
13468 } else if (acfg->aot_opts.llvm_outfile) {
13469 int len = strlen (acfg->aot_opts.llvm_outfile);
13471 if (len >= 2 && acfg->aot_opts.llvm_outfile [len - 2] == '.' && acfg->aot_opts.llvm_outfile [len - 1] == 'o')
13472 acfg->llvm_owriter = TRUE;
13476 if (acfg->llvm && acfg->thumb_mixed)
13477 acfg->flags = (MonoAotFileFlags)(acfg->flags | MONO_AOT_FILE_FLAG_LLVM_THUMB);
13478 if (acfg->aot_opts.llvm_only)
13479 acfg->flags = (MonoAotFileFlags)(acfg->flags | MONO_AOT_FILE_FLAG_LLVM_ONLY);
13481 acfg->assembly_name_sym = g_strdup (acfg->image->assembly->aname.name);
13482 /* Get rid of characters which cannot occur in symbols */
13483 for (p = acfg->assembly_name_sym; *p; ++p) {
13484 if (!(isalnum (*p) || *p == '_'))
13485 *p = '_';
13488 acfg->global_prefix = g_strdup_printf ("mono_aot_%s", acfg->assembly_name_sym);
13489 acfg->plt_symbol = g_strdup_printf ("%s_plt", acfg->global_prefix);
13490 acfg->got_symbol = g_strdup_printf ("%s_got", acfg->global_prefix);
13491 if (acfg->llvm) {
13492 acfg->llvm_got_symbol = g_strdup_printf ("%s_llvm_got", acfg->global_prefix);
13493 acfg->llvm_eh_frame_symbol = g_strdup_printf ("%s_eh_frame", acfg->global_prefix);
13496 acfg->method_index = 1;
13498 if (mono_aot_mode_is_full (&acfg->aot_opts) || mono_aot_mode_is_hybrid (&acfg->aot_opts))
13499 mono_set_partial_sharing_supported (TRUE);
13501 if (!(mono_aot_mode_is_interp (&acfg->aot_opts) && !mono_aot_mode_is_full (&acfg->aot_opts))) {
13502 res = collect_methods (acfg);
13503 if (!res)
13504 return 1;
13507 // If we're emitting all of the inflated methods into a dummy
13508 // Assembly, then after extra_methods is set up, we're done
13509 // in this function.
13510 if (astate && astate->emit_inflated_methods)
13511 mono_add_deferred_extra_methods (acfg, astate);
13514 GList *l;
13516 for (l = acfg->profile_data; l; l = l->next)
13517 resolve_profile_data (acfg, (ProfileData*)l->data, ass);
13518 for (l = acfg->profile_data; l; l = l->next)
13519 add_profile_instances (acfg, (ProfileData*)l->data);
13522 acfg->cfgs_size = acfg->methods->len + 32;
13523 acfg->cfgs = g_new0 (MonoCompile*, acfg->cfgs_size);
13525 /* PLT offset 0 is reserved for the PLT trampoline */
13526 acfg->plt_offset = 1;
13527 add_preinit_got_slots (acfg);
13529 #ifdef ENABLE_LLVM
13530 if (acfg->llvm) {
13531 llvm_acfg = acfg;
13532 LLVMModuleFlags flags = 0;
13533 #ifdef EMIT_DWARF_INFO
13534 flags = LLVM_MODULE_FLAG_DWARF;
13535 #endif
13536 #ifdef EMIT_WIN32_CODEVIEW_INFO
13537 flags = LLVM_MODULE_FLAG_CODEVIEW;
13538 #endif
13539 if (acfg->aot_opts.static_link)
13540 flags = (LLVMModuleFlags)(flags | LLVM_MODULE_FLAG_STATIC);
13541 if (acfg->aot_opts.llvm_only)
13542 flags = (LLVMModuleFlags)(flags | LLVM_MODULE_FLAG_LLVM_ONLY);
13543 if (acfg->aot_opts.interp)
13544 flags = (LLVMModuleFlags)(flags | LLVM_MODULE_FLAG_INTERP);
13545 mono_llvm_create_aot_module (acfg->image->assembly, acfg->global_prefix, acfg->nshared_got_entries, flags);
13547 add_lazy_init_wrappers (acfg);
13549 #endif
13551 if (mono_aot_mode_is_interp (&acfg->aot_opts) && mono_is_corlib_image (acfg->image->assembly->image)) {
13552 MonoMethod *wrapper = mini_get_interp_lmf_wrapper ("mono_interp_to_native_trampoline", (gpointer) mono_interp_to_native_trampoline);
13553 add_method (acfg, wrapper);
13555 wrapper = mini_get_interp_lmf_wrapper ("mono_interp_entry_from_trampoline", (gpointer) mono_interp_entry_from_trampoline);
13556 add_method (acfg, wrapper);
13558 #ifndef MONO_ARCH_HAVE_INTERP_ENTRY_TRAMPOLINE
13559 for (int i = 0; i < G_N_ELEMENTS (interp_in_static_sigs); i++) {
13560 MonoMethodSignature *sig = *interp_in_static_sigs [i];
13561 sig = mono_metadata_signature_dup_full (mono_get_corlib (), sig);
13562 sig->pinvoke = FALSE;
13563 wrapper = mini_get_interp_in_wrapper (sig);
13564 add_method (acfg, wrapper);
13566 #endif
13568 /* required for mixed mode */
13569 if (strcmp (acfg->image->assembly->aname.name, "mscorlib") == 0) {
13570 add_gc_wrappers (acfg);
13572 for (int i = 0; i < MONO_JIT_ICALL_count; ++i)
13573 add_jit_icall_wrapper (acfg, mono_find_jit_icall_info ((MonoJitICallId)i));
13577 TV_GETTIME (atv);
13579 compile_methods (acfg);
13581 TV_GETTIME (btv);
13583 acfg->stats.jit_time = TV_ELAPSED (atv, btv);
13585 dedup_skip_methods (acfg);
13587 if (acfg->aot_opts.dedup_include && !is_dedup_dummy)
13588 /* We only collected methods from this assembly */
13589 return 0;
13591 return emit_aot_image (acfg);
13594 static void
13595 print_stats (MonoAotCompile *acfg)
13597 int i;
13598 gint64 all_sizes;
13599 char llvm_stats_msg [256];
13601 if (acfg->llvm && !acfg->aot_opts.llvm_only)
13602 sprintf (llvm_stats_msg, ", LLVM: %d (%d%%)", acfg->stats.llvm_count, acfg->stats.mcount ? (acfg->stats.llvm_count * 100) / acfg->stats.mcount : 100);
13603 else
13604 strcpy (llvm_stats_msg, "");
13606 all_sizes = acfg->stats.code_size + acfg->stats.method_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;
13608 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, BLOB: %d\n",
13609 (int)acfg->stats.code_size, (int)(acfg->stats.code_size * 100 / all_sizes),
13610 (int)acfg->stats.method_info_size, (int)(acfg->stats.method_info_size * 100 / all_sizes),
13611 (int)acfg->stats.ex_info_size, (int)(acfg->stats.ex_info_size * 100 / all_sizes),
13612 (int)acfg->stats.unwind_info_size, (int)(acfg->stats.unwind_info_size * 100 / all_sizes),
13613 (int)acfg->stats.class_info_size, (int)(acfg->stats.class_info_size * 100 / all_sizes),
13614 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,
13615 (int)acfg->stats.got_info_size, (int)(acfg->stats.got_info_size * 100 / all_sizes),
13616 (int)acfg->stats.offsets_size, (int)(acfg->stats.offsets_size * 100 / all_sizes),
13617 (int)(acfg->got_offset * sizeof (target_mgreg_t)),
13618 (int)acfg->stats.blob_size);
13619 aot_printf (acfg, "Compiled: %d/%d (%d%%)%s, No GOT slots: %d (%d%%), Direct calls: %d (%d%%)\n",
13620 acfg->stats.ccount, acfg->stats.mcount, acfg->stats.mcount ? (acfg->stats.ccount * 100) / acfg->stats.mcount : 100,
13621 llvm_stats_msg,
13622 acfg->stats.methods_without_got_slots, acfg->stats.mcount ? (acfg->stats.methods_without_got_slots * 100) / acfg->stats.mcount : 100,
13623 acfg->stats.direct_calls, acfg->stats.all_calls ? (acfg->stats.direct_calls * 100) / acfg->stats.all_calls : 100);
13624 if (acfg->stats.genericcount)
13625 aot_printf (acfg, "%d methods failed gsharing (%d%%)\n", acfg->stats.genericcount, acfg->stats.mcount ? (acfg->stats.genericcount * 100) / acfg->stats.mcount : 100);
13626 if (acfg->stats.abscount)
13627 aot_printf (acfg, "%d methods contain absolute addresses (%d%%)\n", acfg->stats.abscount, acfg->stats.mcount ? (acfg->stats.abscount * 100) / acfg->stats.mcount : 100);
13628 if (acfg->stats.lmfcount)
13629 aot_printf (acfg, "%d methods contain lmf pointers (%d%%)\n", acfg->stats.lmfcount, acfg->stats.mcount ? (acfg->stats.lmfcount * 100) / acfg->stats.mcount : 100);
13630 if (acfg->stats.ocount)
13631 aot_printf (acfg, "%d methods have other problems (%d%%)\n", acfg->stats.ocount, acfg->stats.mcount ? (acfg->stats.ocount * 100) / acfg->stats.mcount : 100);
13633 aot_printf (acfg, "GOT slot distribution:\n");
13634 int nslots = 0;
13635 int size = 0;
13636 for (i = 0; i < MONO_PATCH_INFO_NUM; ++i) {
13637 nslots += acfg->stats.got_slot_types [i];
13638 size += acfg->stats.got_slot_info_sizes [i];
13639 if (acfg->stats.got_slot_types [i])
13640 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]);
13642 aot_printf (acfg, "GOT SLOTS: %d, INFO SIZE: %d\n", nslots, size);
13644 aot_printf (acfg, "\nEncoding stats:\n");
13645 aot_printf (acfg, "\tMethod ref: %d (%dk)\n", acfg->stats.method_ref_count, acfg->stats.method_ref_size / 1024);
13646 aot_printf (acfg, "\tClass ref: %d (%dk)\n", acfg->stats.class_ref_count, acfg->stats.class_ref_size / 1024);
13647 aot_printf (acfg, "\tGinst: %d (%dk)\n", acfg->stats.ginst_count, acfg->stats.ginst_size / 1024);
13649 aot_printf (acfg, "\nMethod stats:\n");
13650 aot_printf (acfg, "\tNormal: %d\n", acfg->stats.method_categories [METHOD_CAT_NORMAL]);
13651 aot_printf (acfg, "\tInstance: %d\n", acfg->stats.method_categories [METHOD_CAT_INST]);
13652 aot_printf (acfg, "\tGSharedvt: %d\n", acfg->stats.method_categories [METHOD_CAT_GSHAREDVT]);
13653 aot_printf (acfg, "\tWrapper: %d\n", acfg->stats.method_categories [METHOD_CAT_WRAPPER]);
13655 if (acfg->aot_opts.dedup || acfg->dedup_emit_mode)
13656 mono_dedup_log_stats (acfg);
13659 static void
13660 create_depfile (MonoAotCompile *acfg)
13662 FILE *depfile;
13664 // FIXME: Support other configurations
13665 g_assert (acfg->aot_opts.llvm_only && acfg->aot_opts.asm_only && acfg->aot_opts.llvm_outfile);
13667 depfile = fopen (acfg->aot_opts.depfile, "w");
13668 g_assert (depfile);
13670 int ntargets = 1;
13671 char **targets = g_new0 (char*, ntargets);
13672 targets [0] = acfg->aot_opts.llvm_outfile;
13673 for (int tindex = 0; tindex < ntargets; ++tindex) {
13674 fprintf (depfile, "%s: ", targets [tindex]);
13675 for (int i = 0; i < acfg->image_table->len; i++) {
13676 MonoImage *image = (MonoImage*)g_ptr_array_index (acfg->image_table, i);
13677 fprintf (depfile, " %s", image->filename);
13679 fprintf (depfile, "\n");
13681 g_free (targets);
13682 fclose (depfile);
13685 static int
13686 emit_aot_image (MonoAotCompile *acfg)
13688 int i, res;
13689 TV_DECLARE (atv);
13690 TV_DECLARE (btv);
13692 TV_GETTIME (atv);
13694 #ifdef ENABLE_LLVM
13695 if (acfg->llvm) {
13696 if (acfg->aot_opts.asm_only) {
13697 if (acfg->aot_opts.outfile) {
13698 acfg->tmpfname = g_strdup_printf ("%s", acfg->aot_opts.outfile);
13699 acfg->tmpbasename = g_strdup (acfg->tmpfname);
13700 } else {
13701 acfg->tmpbasename = g_strdup_printf ("%s", acfg->image->name);
13702 acfg->tmpfname = g_strdup_printf ("%s.s", acfg->tmpbasename);
13704 g_assert (acfg->aot_opts.llvm_outfile);
13705 acfg->llvm_sfile = g_strdup (acfg->aot_opts.llvm_outfile);
13706 if (acfg->llvm_owriter)
13707 acfg->llvm_ofile = g_strdup (acfg->aot_opts.llvm_outfile);
13708 else
13709 acfg->llvm_sfile = g_strdup (acfg->aot_opts.llvm_outfile);
13710 } else {
13711 gchar *temp_path;
13712 if (strcmp (acfg->aot_opts.temp_path, "") != 0) {
13713 temp_path = g_strdup (acfg->aot_opts.temp_path);
13714 } else {
13715 temp_path = g_mkdtemp (g_strdup ("mono_aot_XXXXXX"));
13716 g_assertf (temp_path, "mkdtemp failed, error = (%d) %s", errno, g_strerror (errno));
13717 acfg->temp_dir_to_delete = g_strdup (temp_path);
13720 acfg->tmpbasename = g_build_filename (temp_path, "temp", NULL);
13721 acfg->tmpfname = g_strdup_printf ("%s.s", acfg->tmpbasename);
13722 acfg->llvm_sfile = g_strdup_printf ("%s-llvm.s", acfg->tmpbasename);
13723 acfg->llvm_ofile = g_strdup_printf ("%s-llvm." AS_OBJECT_FILE_SUFFIX, acfg->tmpbasename);
13725 g_free (temp_path);
13728 #endif
13730 if (acfg->aot_opts.asm_only && !acfg->aot_opts.llvm_only) {
13731 if (acfg->aot_opts.outfile)
13732 acfg->tmpfname = g_strdup_printf ("%s", acfg->aot_opts.outfile);
13733 else
13734 acfg->tmpfname = g_strdup_printf ("%s.s", acfg->image->name);
13735 acfg->fp = fopen (acfg->tmpfname, "w+");
13736 } else {
13737 if (strcmp (acfg->aot_opts.temp_path, "") == 0) {
13738 int i = g_file_open_tmp ("mono_aot_XXXXXX", &acfg->tmpfname, NULL);
13739 acfg->fp = fdopen (i, "w+");
13740 } else {
13741 acfg->tmpbasename = g_build_filename (acfg->aot_opts.temp_path, "temp", NULL);
13742 acfg->tmpfname = g_strdup_printf ("%s.s", acfg->tmpbasename);
13743 acfg->fp = fopen (acfg->tmpfname, "w+");
13746 if (acfg->fp == 0 && !acfg->aot_opts.llvm_only) {
13747 aot_printerrf (acfg, "Unable to open file '%s': %s\n", acfg->tmpfname, strerror (errno));
13748 return 1;
13750 if (acfg->fp)
13751 acfg->w = mono_img_writer_create (acfg->fp, FALSE);
13753 /* Compute symbols for methods */
13754 for (i = 0; i < acfg->nmethods; ++i) {
13755 if (acfg->cfgs [i]) {
13756 MonoCompile *cfg = acfg->cfgs [i];
13757 int method_index = get_method_index (acfg, cfg->orig_method);
13759 if (cfg->asm_symbol) {
13760 // Set by method emitter in backend
13761 if (acfg->llvm_label_prefix) {
13762 char *old_symbol = cfg->asm_symbol;
13763 cfg->asm_symbol = g_strdup_printf ("%s%s", acfg->llvm_label_prefix, cfg->asm_symbol);
13764 g_free (old_symbol);
13766 } else if (COMPILE_LLVM (cfg)) {
13767 cfg->asm_symbol = g_strdup_printf ("%s%s", acfg->llvm_label_prefix, cfg->llvm_method_name);
13768 } else if (acfg->global_symbols || acfg->llvm) {
13769 cfg->asm_symbol = get_debug_sym (cfg->orig_method, "", acfg->method_label_hash);
13770 } else {
13771 cfg->asm_symbol = g_strdup_printf ("%s%sm_%x", acfg->temp_prefix, acfg->llvm_label_prefix, method_index);
13773 cfg->asm_debug_symbol = cfg->asm_symbol;
13777 if (acfg->aot_opts.dwarf_debug && acfg->aot_opts.gnu_asm) {
13779 * CLANG supports GAS .file/.loc directives, so emit line number information this way
13781 acfg->gas_line_numbers = TRUE;
13784 #ifdef EMIT_DWARF_INFO
13785 if ((!acfg->aot_opts.nodebug || acfg->aot_opts.dwarf_debug) && acfg->has_jitted_code) {
13786 if (acfg->aot_opts.dwarf_debug && !mono_debug_enabled ()) {
13787 aot_printerrf (acfg, "The dwarf AOT option requires the --debug option.\n");
13788 return 1;
13790 acfg->dwarf = mono_dwarf_writer_create (acfg->w, NULL, 0, !acfg->gas_line_numbers);
13792 #endif /* EMIT_DWARF_INFO */
13794 if (acfg->w)
13795 mono_img_writer_emit_start (acfg->w);
13797 if (acfg->dwarf)
13798 mono_dwarf_writer_emit_base_info (acfg->dwarf, g_path_get_basename (acfg->image->name), mono_unwind_get_cie_program ());
13800 if (acfg->aot_opts.dedup)
13801 mono_flush_method_cache (acfg);
13803 emit_code (acfg);
13805 emit_info (acfg);
13807 emit_extra_methods (acfg);
13809 emit_trampolines (acfg);
13811 emit_class_name_table (acfg);
13813 emit_got_info (acfg, FALSE);
13814 if (acfg->llvm)
13815 emit_got_info (acfg, TRUE);
13817 emit_exception_info (acfg);
13819 emit_unwind_info (acfg);
13821 emit_class_info (acfg);
13823 emit_plt (acfg);
13825 emit_image_table (acfg);
13827 emit_weak_field_indexes (acfg);
13829 emit_got (acfg);
13833 * The managed allocators are GC specific, so can't use an AOT image created by one GC
13834 * in another.
13836 const char *gc_name = mono_gc_get_gc_name ();
13837 acfg->gc_name_offset = add_to_blob (acfg, (guint8*)gc_name, strlen (gc_name) + 1);
13840 emit_blob (acfg);
13842 emit_objc_selectors (acfg);
13844 emit_globals (acfg);
13846 emit_file_info (acfg);
13848 if (acfg->dwarf) {
13849 emit_dwarf_info (acfg);
13850 mono_dwarf_writer_close (acfg->dwarf);
13851 } else {
13852 if (!acfg->aot_opts.nodebug)
13853 emit_codeview_info (acfg);
13856 emit_mem_end (acfg);
13858 if (acfg->need_pt_gnu_stack) {
13859 /* This is required so the .so doesn't have an executable stack */
13860 /* The bin writer already emits this */
13861 fprintf (acfg->fp, "\n.section .note.GNU-stack,\"\",@progbits\n");
13864 if (acfg->aot_opts.data_outfile)
13865 fclose (acfg->data_outfile);
13867 #ifdef ENABLE_LLVM
13868 if (acfg->llvm) {
13869 gboolean res;
13871 res = emit_llvm_file (acfg);
13872 if (!res)
13873 return 1;
13875 #endif
13877 emit_library_info (acfg);
13879 TV_GETTIME (btv);
13881 acfg->stats.gen_time = TV_ELAPSED (atv, btv);
13883 if (!acfg->aot_opts.stats)
13884 aot_printf (acfg, "Compiled: %d/%d\n", acfg->stats.ccount, acfg->stats.mcount);
13886 TV_GETTIME (atv);
13887 if (acfg->w) {
13888 res = mono_img_writer_emit_writeout (acfg->w);
13889 if (res != 0) {
13890 acfg_free (acfg);
13891 return res;
13893 res = compile_asm (acfg);
13894 if (res != 0) {
13895 acfg_free (acfg);
13896 return res;
13899 TV_GETTIME (btv);
13900 acfg->stats.link_time = TV_ELAPSED (atv, btv);
13902 if (acfg->aot_opts.stats)
13903 print_stats (acfg);
13905 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);
13907 if (acfg->aot_opts.depfile)
13908 create_depfile (acfg);
13910 if (acfg->aot_opts.dump_json)
13911 aot_dump (acfg);
13913 if (!acfg->aot_opts.save_temps && acfg->temp_dir_to_delete) {
13914 char *command = g_strdup_printf ("rm -r %s", acfg->temp_dir_to_delete);
13915 execute_system (command);
13916 g_free (command);
13919 acfg_free (acfg);
13921 return 0;
13924 #else
13926 /* AOT disabled */
13928 void*
13929 mono_aot_readonly_field_override (MonoClassField *field)
13931 return NULL;
13935 mono_compile_assembly (MonoAssembly *ass, guint32 opts, const char *aot_options, gpointer **aot_state)
13937 return 0;
13940 gboolean
13941 mono_aot_is_shared_got_offset (int offset)
13943 return FALSE;
13947 mono_compile_deferred_assemblies (guint32 opts, const char *aot_options, gpointer **aot_state)
13949 g_assert_not_reached ();
13950 return 0;
13953 gboolean
13954 mono_aot_direct_icalls_enabled_for_method (MonoCompile *cfg, MonoMethod *method)
13956 g_assert_not_reached ();
13957 return 0;
13960 #endif