[arm64] Set a llvm target layout. Assert in llvm if the target layout is not set...
[mono-project.git] / mono / mini / aot-compiler.c
blobd0d6835c87064ef670446e3e166d1cbf4f6082d4
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 #define MAX_IMAGE_INDEX 250
3542 static void
3543 encode_method_ref (MonoAotCompile *acfg, MonoMethod *method, guint8 *buf, guint8 **endbuf)
3545 guint32 image_index = get_image_index (acfg, m_class_get_image (method->klass));
3546 guint32 token = method->token;
3547 MonoJumpInfoToken *ji;
3548 guint8 *p = buf;
3551 * The encoding for most methods is as follows:
3552 * - image index encoded as a leb128
3553 * - token index encoded as a leb128
3554 * Values of image index >= MONO_AOT_METHODREF_MIN are used to mark additional
3555 * types of method encodings.
3558 /* Mark methods which can't use aot trampolines because they need the further
3559 * processing in mono_magic_trampoline () which requires a MonoMethod*.
3561 if ((method->is_generic && (method->flags & METHOD_ATTRIBUTE_VIRTUAL)) ||
3562 (method->iflags & METHOD_IMPL_ATTRIBUTE_SYNCHRONIZED))
3563 encode_value ((MONO_AOT_METHODREF_NO_AOT_TRAMPOLINE << 24), p, &p);
3565 if (method->wrapper_type) {
3566 WrapperInfo *info = mono_marshal_get_wrapper_info (method);
3568 encode_value ((MONO_AOT_METHODREF_WRAPPER << 24), p, &p);
3570 encode_value (method->wrapper_type, p, &p);
3572 switch (method->wrapper_type) {
3573 case MONO_WRAPPER_REMOTING_INVOKE:
3574 case MONO_WRAPPER_REMOTING_INVOKE_WITH_CHECK:
3575 case MONO_WRAPPER_XDOMAIN_INVOKE: {
3576 MonoMethod *m;
3578 m = mono_marshal_method_from_wrapper (method);
3579 g_assert (m);
3580 encode_method_ref (acfg, m, p, &p);
3581 break;
3583 case MONO_WRAPPER_PROXY_ISINST:
3584 case MONO_WRAPPER_LDFLD:
3585 case MONO_WRAPPER_LDFLDA:
3586 case MONO_WRAPPER_STFLD: {
3587 g_assert (info);
3588 encode_klass_ref (acfg, info->d.proxy.klass, p, &p);
3589 break;
3591 case MONO_WRAPPER_ALLOC: {
3592 /* The GC name is saved once in MonoAotFileInfo */
3593 g_assert (info->d.alloc.alloc_type != -1);
3594 encode_value (info->d.alloc.alloc_type, p, &p);
3595 break;
3597 case MONO_WRAPPER_WRITE_BARRIER: {
3598 g_assert (info);
3599 break;
3601 case MONO_WRAPPER_STELEMREF: {
3602 g_assert (info);
3603 encode_value (info->subtype, p, &p);
3604 if (info->subtype == WRAPPER_SUBTYPE_VIRTUAL_STELEMREF)
3605 encode_value (info->d.virtual_stelemref.kind, p, &p);
3606 break;
3608 case MONO_WRAPPER_OTHER: {
3609 g_assert (info);
3610 encode_value (info->subtype, p, &p);
3611 if (info->subtype == WRAPPER_SUBTYPE_PTR_TO_STRUCTURE ||
3612 info->subtype == WRAPPER_SUBTYPE_STRUCTURE_TO_PTR)
3613 encode_klass_ref (acfg, method->klass, p, &p);
3614 else if (info->subtype == WRAPPER_SUBTYPE_SYNCHRONIZED_INNER)
3615 encode_method_ref (acfg, info->d.synchronized_inner.method, p, &p);
3616 else if (info->subtype == WRAPPER_SUBTYPE_ARRAY_ACCESSOR)
3617 encode_method_ref (acfg, info->d.array_accessor.method, p, &p);
3618 else if (info->subtype == WRAPPER_SUBTYPE_INTERP_IN)
3619 encode_signature (acfg, info->d.interp_in.sig, p, &p);
3620 else if (info->subtype == WRAPPER_SUBTYPE_GSHAREDVT_IN_SIG)
3621 encode_signature (acfg, info->d.gsharedvt.sig, p, &p);
3622 else if (info->subtype == WRAPPER_SUBTYPE_GSHAREDVT_OUT_SIG)
3623 encode_signature (acfg, info->d.gsharedvt.sig, p, &p);
3624 else if (info->subtype == WRAPPER_SUBTYPE_INTERP_LMF)
3625 encode_value (info->d.icall.jit_icall_id, p, &p);
3626 else if (info->subtype == WRAPPER_SUBTYPE_AOT_INIT)
3627 encode_value (info->d.aot_init.subtype, p, &p);
3628 break;
3630 case MONO_WRAPPER_MANAGED_TO_NATIVE: {
3631 g_assert (info);
3632 encode_value (info->subtype, p, &p);
3633 if (info->subtype == WRAPPER_SUBTYPE_ICALL_WRAPPER) {
3634 encode_value (info->d.icall.jit_icall_id, p, &p);
3635 } else if (info->subtype == WRAPPER_SUBTYPE_NATIVE_FUNC_AOT) {
3636 encode_method_ref (acfg, info->d.managed_to_native.method, p, &p);
3637 } else {
3638 g_assert (info->subtype == WRAPPER_SUBTYPE_NONE || info->subtype == WRAPPER_SUBTYPE_PINVOKE);
3639 encode_method_ref (acfg, info->d.managed_to_native.method, p, &p);
3641 break;
3643 case MONO_WRAPPER_SYNCHRONIZED: {
3644 MonoMethod *m;
3646 m = mono_marshal_method_from_wrapper (method);
3647 g_assert (m);
3648 g_assert (m != method);
3649 encode_method_ref (acfg, m, p, &p);
3650 break;
3652 case MONO_WRAPPER_MANAGED_TO_MANAGED: {
3653 g_assert (info);
3654 encode_value (info->subtype, p, &p);
3656 if (info->subtype == WRAPPER_SUBTYPE_ELEMENT_ADDR) {
3657 encode_value (info->d.element_addr.rank, p, &p);
3658 encode_value (info->d.element_addr.elem_size, p, &p);
3659 } else if (info->subtype == WRAPPER_SUBTYPE_STRING_CTOR) {
3660 encode_method_ref (acfg, info->d.string_ctor.method, p, &p);
3661 } else {
3662 g_assert_not_reached ();
3664 break;
3666 case MONO_WRAPPER_CASTCLASS: {
3667 g_assert (info);
3668 encode_value (info->subtype, p, &p);
3669 break;
3671 case MONO_WRAPPER_RUNTIME_INVOKE: {
3672 g_assert (info);
3673 encode_value (info->subtype, p, &p);
3674 if (info->subtype == WRAPPER_SUBTYPE_RUNTIME_INVOKE_DIRECT || info->subtype == WRAPPER_SUBTYPE_RUNTIME_INVOKE_VIRTUAL)
3675 encode_method_ref (acfg, info->d.runtime_invoke.method, p, &p);
3676 else if (info->subtype == WRAPPER_SUBTYPE_RUNTIME_INVOKE_NORMAL)
3677 encode_signature (acfg, info->d.runtime_invoke.sig, p, &p);
3678 break;
3680 case MONO_WRAPPER_DELEGATE_INVOKE:
3681 case MONO_WRAPPER_DELEGATE_BEGIN_INVOKE:
3682 case MONO_WRAPPER_DELEGATE_END_INVOKE: {
3683 if (method->is_inflated) {
3684 /* These wrappers are identified by their class */
3685 encode_value (1, p, &p);
3686 encode_klass_ref (acfg, method->klass, p, &p);
3687 } else {
3688 MonoMethodSignature *sig = mono_method_signature_internal (method);
3689 WrapperInfo *info = mono_marshal_get_wrapper_info (method);
3691 encode_value (0, p, &p);
3692 if (method->wrapper_type == MONO_WRAPPER_DELEGATE_INVOKE)
3693 encode_value (info ? info->subtype : 0, p, &p);
3694 encode_signature (acfg, sig, p, &p);
3696 break;
3698 case MONO_WRAPPER_NATIVE_TO_MANAGED: {
3699 g_assert (info);
3700 encode_method_ref (acfg, info->d.native_to_managed.method, p, &p);
3701 encode_klass_ref (acfg, info->d.native_to_managed.klass, p, &p);
3702 break;
3704 default:
3705 g_assert_not_reached ();
3707 } else if (mono_method_signature_internal (method)->is_inflated) {
3709 * This is a generic method, find the original token which referenced it and
3710 * encode that.
3711 * Obtain the token from information recorded by the JIT.
3713 ji = (MonoJumpInfoToken *)g_hash_table_lookup (acfg->token_info_hash, method);
3714 if (ji) {
3715 image_index = get_image_index (acfg, ji->image);
3716 g_assert (image_index < MAX_IMAGE_INDEX);
3717 token = ji->token;
3719 encode_value ((MONO_AOT_METHODREF_METHODSPEC << 24), p, &p);
3720 encode_value (image_index, p, &p);
3721 encode_value (token, p, &p);
3722 } else if (g_hash_table_lookup (acfg->method_blob_hash, method)) {
3723 /* Already emitted as part of an rgctx fetch */
3724 guint32 offset = GPOINTER_TO_UINT (g_hash_table_lookup (acfg->method_blob_hash, method));
3725 offset --;
3727 encode_value ((MONO_AOT_METHODREF_BLOB_INDEX << 24), p, &p);
3728 encode_value (offset, p, &p);
3729 } else {
3730 MonoMethod *declaring;
3731 MonoGenericContext *context = mono_method_get_context (method);
3733 g_assert (method->is_inflated);
3734 declaring = ((MonoMethodInflated*)method)->declaring;
3737 * This might be a non-generic method of a generic instance, which
3738 * doesn't have a token since the reference is generated by the JIT
3739 * like Nullable:Box/Unbox, or by generic sharing.
3741 encode_value ((MONO_AOT_METHODREF_GINST << 24), p, &p);
3742 /* Encode the klass */
3743 encode_klass_ref (acfg, method->klass, p, &p);
3744 /* Encode the method */
3745 image_index = get_image_index (acfg, m_class_get_image (method->klass));
3746 g_assert (image_index < MAX_IMAGE_INDEX);
3747 g_assert (declaring->token);
3748 token = declaring->token;
3749 g_assert (mono_metadata_token_table (token) == MONO_TABLE_METHOD);
3750 encode_value (image_index, p, &p);
3751 encode_value (mono_metadata_token_index (token), p, &p);
3752 encode_generic_context (acfg, context, p, &p);
3754 } else if (token == 0) {
3755 /* This might be a method of a constructed type like int[,].Set */
3756 /* Obtain the token from information recorded by the JIT */
3757 ji = (MonoJumpInfoToken *)g_hash_table_lookup (acfg->token_info_hash, method);
3758 if (ji) {
3759 image_index = get_image_index (acfg, ji->image);
3760 g_assert (image_index < MAX_IMAGE_INDEX);
3761 token = ji->token;
3763 encode_value ((MONO_AOT_METHODREF_METHODSPEC << 24), p, &p);
3764 encode_value (image_index, p, &p);
3765 encode_value (token, p, &p);
3766 } else {
3767 /* Array methods */
3768 g_assert (m_class_get_rank (method->klass));
3770 /* Encode directly */
3771 encode_value ((MONO_AOT_METHODREF_ARRAY << 24), p, &p);
3772 encode_klass_ref (acfg, method->klass, p, &p);
3773 if (!strcmp (method->name, ".ctor") && mono_method_signature_internal (method)->param_count == m_class_get_rank (method->klass))
3774 encode_value (0, p, &p);
3775 else if (!strcmp (method->name, ".ctor") && mono_method_signature_internal (method)->param_count == m_class_get_rank (method->klass) * 2)
3776 encode_value (1, p, &p);
3777 else if (!strcmp (method->name, "Get"))
3778 encode_value (2, p, &p);
3779 else if (!strcmp (method->name, "Address"))
3780 encode_value (3, p, &p);
3781 else if (!strcmp (method->name, "Set"))
3782 encode_value (4, p, &p);
3783 else
3784 g_assert_not_reached ();
3786 } else {
3787 g_assert (mono_metadata_token_table (token) == MONO_TABLE_METHOD);
3789 if (image_index >= MONO_AOT_METHODREF_MIN) {
3790 encode_value ((MONO_AOT_METHODREF_LARGE_IMAGE_INDEX << 24), p, &p);
3791 encode_value (image_index, p, &p);
3792 encode_value (mono_metadata_token_index (token), p, &p);
3793 } else {
3794 encode_value ((image_index << 24) | mono_metadata_token_index (token), p, &p);
3798 acfg->stats.method_ref_count++;
3799 acfg->stats.method_ref_size += p - buf;
3801 *endbuf = p;
3804 static guint32
3805 get_shared_method_ref (MonoAotCompile *acfg, MonoMethod *method)
3807 guint32 offset = GPOINTER_TO_UINT (g_hash_table_lookup (acfg->method_blob_hash, method));
3808 if (!offset) {
3809 guint8 *buf2, *p2;
3811 buf2 = (guint8 *)g_malloc (1024);
3812 p2 = buf2;
3814 encode_method_ref (acfg, method, p2, &p2);
3815 g_assert (p2 - buf2 < 1024);
3817 offset = add_to_blob (acfg, buf2, p2 - buf2);
3818 g_free (buf2);
3820 g_hash_table_insert (acfg->method_blob_hash, method, GUINT_TO_POINTER (offset + 1));
3821 } else {
3822 offset --;
3824 return offset;
3827 static gint
3828 compare_patches (gconstpointer a, gconstpointer b)
3830 int i, j;
3832 i = (*(MonoJumpInfo**)a)->ip.i;
3833 j = (*(MonoJumpInfo**)b)->ip.i;
3835 if (i < j)
3836 return -1;
3837 else
3838 if (i > j)
3839 return 1;
3840 else
3841 return 0;
3844 static G_GNUC_UNUSED char*
3845 patch_to_string (MonoJumpInfo *patch_info)
3847 GString *str;
3849 str = g_string_new ("");
3851 g_string_append_printf (str, "%s(", get_patch_name (patch_info->type));
3853 switch (patch_info->type) {
3854 case MONO_PATCH_INFO_VTABLE:
3855 mono_type_get_desc (str, m_class_get_byval_arg (patch_info->data.klass), TRUE);
3856 break;
3857 default:
3858 break;
3860 g_string_append_printf (str, ")");
3861 return g_string_free (str, FALSE);
3865 * is_plt_patch:
3867 * Return whenever PATCH_INFO refers to a direct call, and thus requires a
3868 * PLT entry.
3870 static inline gboolean
3871 is_plt_patch (MonoJumpInfo *patch_info)
3873 switch (patch_info->type) {
3874 case MONO_PATCH_INFO_METHOD:
3875 case MONO_PATCH_INFO_JIT_ICALL_ID:
3876 case MONO_PATCH_INFO_JIT_ICALL_ADDR:
3877 case MONO_PATCH_INFO_ICALL_ADDR_CALL:
3878 case MONO_PATCH_INFO_RGCTX_FETCH:
3879 case MONO_PATCH_INFO_TRAMPOLINE_FUNC_ADDR:
3880 case MONO_PATCH_INFO_SPECIFIC_TRAMPOLINE_LAZY_FETCH_ADDR:
3881 return TRUE;
3882 case MONO_PATCH_INFO_JIT_ICALL_ADDR_NOCALL:
3883 default:
3884 return FALSE;
3889 * get_plt_symbol:
3891 * Return the symbol identifying the plt entry PLT_OFFSET.
3893 static char*
3894 get_plt_symbol (MonoAotCompile *acfg, int plt_offset, MonoJumpInfo *patch_info)
3896 #ifdef TARGET_MACH
3898 * The Apple linker reorganizes object files, so it doesn't like branches to local
3899 * labels, since those have no relocations.
3901 return g_strdup_printf ("%sp_%d", acfg->llvm_label_prefix, plt_offset);
3902 #else
3903 return g_strdup_printf ("%sp_%d", acfg->temp_prefix, plt_offset);
3904 #endif
3908 * get_plt_entry:
3910 * Return a PLT entry which belongs to the method identified by PATCH_INFO.
3912 static MonoPltEntry*
3913 get_plt_entry (MonoAotCompile *acfg, MonoJumpInfo *patch_info)
3915 MonoPltEntry *res;
3916 gboolean synchronized = FALSE;
3917 static int synchronized_symbol_idx;
3919 if (!is_plt_patch (patch_info))
3920 return NULL;
3922 if (!acfg->patch_to_plt_entry [patch_info->type])
3923 acfg->patch_to_plt_entry [patch_info->type] = g_hash_table_new (mono_patch_info_hash, mono_patch_info_equal);
3924 res = (MonoPltEntry *)g_hash_table_lookup (acfg->patch_to_plt_entry [patch_info->type], patch_info);
3926 if (!acfg->llvm && patch_info->type == MONO_PATCH_INFO_METHOD && (patch_info->data.method->iflags & METHOD_IMPL_ATTRIBUTE_SYNCHRONIZED)) {
3928 * Allocate a separate PLT slot for each such patch, since some plt
3929 * entries will refer to the method itself, and some will refer to the
3930 * wrapper.
3932 res = NULL;
3933 synchronized = TRUE;
3936 if (!res) {
3937 MonoJumpInfo *new_ji;
3939 new_ji = mono_patch_info_dup_mp (acfg->mempool, patch_info);
3941 res = (MonoPltEntry *)mono_mempool_alloc0 (acfg->mempool, sizeof (MonoPltEntry));
3942 res->plt_offset = acfg->plt_offset;
3943 res->ji = new_ji;
3944 res->symbol = get_plt_symbol (acfg, res->plt_offset, patch_info);
3945 if (acfg->aot_opts.write_symbols)
3946 res->debug_sym = get_plt_entry_debug_sym (acfg, res->ji, acfg->plt_entry_debug_sym_cache);
3947 if (synchronized) {
3948 /* Avoid duplicate symbols because we don't cache */
3949 res->symbol = g_strdup_printf ("%s_%d", res->symbol, synchronized_symbol_idx);
3950 if (res->debug_sym)
3951 res->debug_sym = g_strdup_printf ("%s_%d", res->debug_sym, synchronized_symbol_idx);
3952 synchronized_symbol_idx ++;
3955 if (res->debug_sym)
3956 res->llvm_symbol = g_strdup_printf ("%s_%s_llvm", res->symbol, res->debug_sym);
3957 else
3958 res->llvm_symbol = g_strdup_printf ("%s_llvm", res->symbol);
3959 if (strstr (res->llvm_symbol, acfg->temp_prefix) == res->llvm_symbol) {
3960 /* The llvm symbol shouldn't be temporary, since the llvm generated object file references it */
3961 char *tmp = res->llvm_symbol;
3962 res->llvm_symbol = g_strdup (res->llvm_symbol + strlen (acfg->temp_prefix));
3963 g_free (tmp);
3966 g_hash_table_insert (acfg->patch_to_plt_entry [new_ji->type], new_ji, res);
3968 g_hash_table_insert (acfg->plt_offset_to_entry, GUINT_TO_POINTER (res->plt_offset), res);
3970 //g_assert (mono_patch_info_equal (patch_info, new_ji));
3971 //mono_print_ji (patch_info); printf ("\n");
3972 //g_hash_table_print_stats (acfg->patch_to_plt_entry);
3974 acfg->plt_offset ++;
3977 return res;
3980 static guint32
3981 lookup_got_offset (MonoAotCompile *acfg, gboolean llvm, MonoJumpInfo *ji)
3983 guint32 got_offset;
3984 GotInfo *info = llvm ? &acfg->llvm_got_info : &acfg->got_info;
3986 got_offset = GPOINTER_TO_UINT (g_hash_table_lookup (info->patch_to_got_offset_by_type [ji->type], ji));
3987 if (got_offset)
3988 return got_offset - 1;
3989 g_assert_not_reached ();
3993 * get_got_offset:
3995 * Returns the offset of the GOT slot where the runtime object resulting from resolving
3996 * JI could be found if it exists, otherwise allocates a new one.
3998 static guint32
3999 get_got_offset (MonoAotCompile *acfg, gboolean llvm, MonoJumpInfo *ji)
4001 guint32 got_offset;
4002 GotInfo *info = llvm ? &acfg->llvm_got_info : &acfg->got_info;
4004 got_offset = GPOINTER_TO_UINT (g_hash_table_lookup (info->patch_to_got_offset_by_type [ji->type], ji));
4005 if (got_offset)
4006 return got_offset - 1;
4008 if (llvm) {
4009 got_offset = acfg->llvm_got_offset;
4010 acfg->llvm_got_offset ++;
4011 } else {
4012 got_offset = acfg->got_offset;
4013 acfg->got_offset ++;
4016 acfg->stats.got_slots ++;
4017 acfg->stats.got_slot_types [ji->type] ++;
4019 g_hash_table_insert (info->patch_to_got_offset, ji, GUINT_TO_POINTER (got_offset + 1));
4020 g_hash_table_insert (info->patch_to_got_offset_by_type [ji->type], ji, GUINT_TO_POINTER (got_offset + 1));
4021 g_ptr_array_add (info->got_patches, ji);
4023 return got_offset;
4026 /* Add a method to the list of methods which need to be emitted */
4027 static void
4028 add_method_with_index (MonoAotCompile *acfg, MonoMethod *method, int index, gboolean extra)
4030 g_assert (method);
4031 if (!g_hash_table_lookup (acfg->method_indexes, method)) {
4032 g_ptr_array_add (acfg->methods, method);
4033 g_hash_table_insert (acfg->method_indexes, method, GUINT_TO_POINTER (index + 1));
4034 acfg->nmethods = acfg->methods->len + 1;
4037 if (method->wrapper_type || extra) {
4038 int token = mono_metadata_token_index (method->token) - 1;
4039 if (token < 0)
4040 acfg->nextra_methods++;
4041 g_ptr_array_add (acfg->extra_methods, method);
4045 static gboolean
4046 prefer_gsharedvt_method (MonoAotCompile *acfg, MonoMethod *method)
4048 /* One instantiation with valuetypes is generated for each async method */
4049 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")))
4050 return TRUE;
4051 else
4052 return FALSE;
4055 static guint32
4056 get_method_index (MonoAotCompile *acfg, MonoMethod *method)
4058 int index = GPOINTER_TO_UINT (g_hash_table_lookup (acfg->method_indexes, method));
4060 g_assert (index);
4062 return index - 1;
4065 static int
4066 add_method_full (MonoAotCompile *acfg, MonoMethod *method, gboolean extra, int depth)
4068 int index;
4070 index = GPOINTER_TO_UINT (g_hash_table_lookup (acfg->method_indexes, method));
4071 if (index)
4072 return index - 1;
4074 index = acfg->method_index;
4075 add_method_with_index (acfg, method, index, extra);
4077 g_ptr_array_add (acfg->method_order, GUINT_TO_POINTER (index));
4079 g_hash_table_insert (acfg->method_depth, method, GUINT_TO_POINTER (depth));
4081 acfg->method_index ++;
4083 return index;
4086 static int
4087 add_method (MonoAotCompile *acfg, MonoMethod *method)
4089 return add_method_full (acfg, method, FALSE, 0);
4092 static void
4093 mono_dedup_cache_method (MonoAotCompile *acfg, MonoMethod *method)
4095 g_assert (acfg->dedup_stats);
4097 char *name = mono_aot_get_mangled_method_name (method);
4098 g_assert (name);
4100 // For stats
4101 char *stats_name = g_strdup (name);
4103 g_assert (acfg->dedup_cache);
4105 if (!g_hash_table_lookup (acfg->dedup_cache, name)) {
4106 // This AOTCompile owns this method
4107 // We do this to decide whether to write it to disk
4108 // during a dedup run (first phase, where we skip).
4110 // If never changed, then maybe can avoid a recompile
4111 // of the cache.
4113 // Files not read in during last phase.
4114 acfg->dedup_cache_changed = TRUE;
4116 // owns name
4117 g_hash_table_insert (acfg->dedup_cache, name, method);
4118 } else {
4119 // owns name
4120 g_free (name);
4123 guint count = GPOINTER_TO_UINT (g_hash_table_lookup (acfg->dedup_stats, stats_name));
4124 count++;
4125 g_hash_table_insert (acfg->dedup_stats, stats_name, GUINT_TO_POINTER (count));
4128 static void
4129 add_extra_method_with_depth (MonoAotCompile *acfg, MonoMethod *method, int depth)
4131 ERROR_DECL (error);
4133 if (mono_method_is_generic_sharable_full (method, TRUE, TRUE, FALSE)) {
4134 method = mini_get_shared_method_full (method, SHARE_MODE_NONE, error);
4135 if (!is_ok (error)) {
4136 /* vtype constraint */
4137 mono_error_cleanup (error);
4138 return;
4140 } else if ((acfg->opts & MONO_OPT_GSHAREDVT) && prefer_gsharedvt_method (acfg, method) && mono_method_is_generic_sharable_full (method, FALSE, FALSE, TRUE)) {
4141 /* Use the gsharedvt version */
4142 method = mini_get_shared_method_full (method, SHARE_MODE_GSHAREDVT, error);
4143 mono_error_assert_ok (error);
4146 if ((acfg->aot_opts.dedup || acfg->aot_opts.dedup_include) && mono_aot_can_dedup (method)) {
4147 mono_dedup_cache_method (acfg, method);
4149 if (!acfg->dedup_emit_mode)
4150 return;
4153 if (acfg->aot_opts.log_generics)
4154 aot_printf (acfg, "%*sAdding method %s.\n", depth, "", mono_method_get_full_name (method));
4156 add_method_full (acfg, method, TRUE, depth);
4159 static void
4160 add_extra_method (MonoAotCompile *acfg, MonoMethod *method)
4162 add_extra_method_with_depth (acfg, method, 0);
4165 static void
4166 add_jit_icall_wrapper (MonoAotCompile *acfg, MonoJitICallInfo *callinfo)
4168 if (!callinfo->sig)
4169 return;
4171 g_assert (callinfo->name && callinfo->func);
4173 add_method (acfg, mono_marshal_get_icall_wrapper (callinfo, TRUE));
4176 static void
4177 add_lazy_init_wrappers (MonoAotCompile *acfg)
4179 add_method (acfg, mono_marshal_get_aot_init_wrapper (AOT_INIT_METHOD));
4180 add_method (acfg, mono_marshal_get_aot_init_wrapper (AOT_INIT_METHOD_GSHARED_MRGCTX));
4181 add_method (acfg, mono_marshal_get_aot_init_wrapper (AOT_INIT_METHOD_GSHARED_VTABLE));
4182 add_method (acfg, mono_marshal_get_aot_init_wrapper (AOT_INIT_METHOD_GSHARED_THIS));
4185 static MonoMethod*
4186 get_runtime_invoke_sig (MonoMethodSignature *sig)
4188 MonoMethodBuilder *mb;
4189 MonoMethod *m;
4191 mb = mono_mb_new (mono_defaults.object_class, "FOO", MONO_WRAPPER_NONE);
4192 m = mono_mb_create_method (mb, sig, 16);
4193 MonoMethod *invoke = mono_marshal_get_runtime_invoke (m, FALSE);
4194 mono_mb_free (mb);
4195 return invoke;
4198 static MonoMethod*
4199 get_runtime_invoke (MonoAotCompile *acfg, MonoMethod *method, gboolean virtual_)
4201 return mono_marshal_get_runtime_invoke (method, virtual_);
4204 static gboolean
4205 can_marshal_struct (MonoClass *klass)
4207 MonoClassField *field;
4208 gboolean can_marshal = TRUE;
4209 gpointer iter = NULL;
4210 MonoMarshalType *info;
4211 int i;
4213 if (mono_class_is_auto_layout (klass))
4214 return FALSE;
4216 info = mono_marshal_load_type_info (klass);
4218 /* Only allow a few field types to avoid asserts in the marshalling code */
4219 while ((field = mono_class_get_fields_internal (klass, &iter))) {
4220 if ((field->type->attrs & FIELD_ATTRIBUTE_STATIC))
4221 continue;
4223 switch (field->type->type) {
4224 case MONO_TYPE_I4:
4225 case MONO_TYPE_U4:
4226 case MONO_TYPE_I1:
4227 case MONO_TYPE_U1:
4228 case MONO_TYPE_BOOLEAN:
4229 case MONO_TYPE_I2:
4230 case MONO_TYPE_U2:
4231 case MONO_TYPE_CHAR:
4232 case MONO_TYPE_I8:
4233 case MONO_TYPE_U8:
4234 case MONO_TYPE_I:
4235 case MONO_TYPE_U:
4236 case MONO_TYPE_PTR:
4237 case MONO_TYPE_R4:
4238 case MONO_TYPE_R8:
4239 case MONO_TYPE_STRING:
4240 break;
4241 case MONO_TYPE_VALUETYPE:
4242 if (!m_class_is_enumtype (mono_class_from_mono_type_internal (field->type)) && !can_marshal_struct (mono_class_from_mono_type_internal (field->type)))
4243 can_marshal = FALSE;
4244 break;
4245 case MONO_TYPE_SZARRAY: {
4246 gboolean has_mspec = FALSE;
4248 if (info) {
4249 for (i = 0; i < info->num_fields; ++i) {
4250 if (info->fields [i].field == field && info->fields [i].mspec)
4251 has_mspec = TRUE;
4254 if (!has_mspec)
4255 can_marshal = FALSE;
4256 break;
4258 default:
4259 can_marshal = FALSE;
4260 break;
4264 /* Special cases */
4265 /* Its hard to compute whenever these can be marshalled or not */
4266 if (!strcmp (m_class_get_name_space (klass), "System.Net.NetworkInformation.MacOsStructs") && strcmp (m_class_get_name (klass), "sockaddr_dl"))
4267 return TRUE;
4269 return can_marshal;
4272 static void
4273 create_gsharedvt_inst (MonoAotCompile *acfg, MonoMethod *method, MonoGenericContext *ctx)
4275 /* Create a vtype instantiation */
4276 MonoGenericContext shared_context;
4277 MonoType **args;
4278 MonoGenericInst *inst;
4279 MonoGenericContainer *container;
4280 MonoClass **constraints;
4281 int i;
4283 memset (ctx, 0, sizeof (MonoGenericContext));
4285 if (mono_class_is_gtd (method->klass)) {
4286 shared_context = mono_class_get_generic_container (method->klass)->context;
4287 inst = shared_context.class_inst;
4289 args = g_new0 (MonoType*, inst->type_argc);
4290 for (i = 0; i < inst->type_argc; ++i) {
4291 args [i] = mono_get_int_type ();
4293 ctx->class_inst = mono_metadata_get_generic_inst (inst->type_argc, args);
4295 if (method->is_generic) {
4296 container = mono_method_get_generic_container (method);
4297 g_assert (!container->is_anonymous && container->is_method);
4298 shared_context = container->context;
4299 inst = shared_context.method_inst;
4301 args = g_new0 (MonoType*, inst->type_argc);
4302 for (i = 0; i < container->type_argc; ++i) {
4303 MonoGenericParamInfo *info = mono_generic_param_info (&container->type_params [i]);
4304 gboolean ref_only = FALSE;
4306 if (info && info->constraints) {
4307 constraints = info->constraints;
4309 while (*constraints) {
4310 MonoClass *cklass = *constraints;
4311 if (!(cklass == mono_defaults.object_class || (m_class_get_image (cklass) == mono_defaults.corlib && !strcmp (m_class_get_name (cklass), "ValueType"))))
4312 /* Inflaring the method with our vtype would not be valid */
4313 ref_only = TRUE;
4314 constraints ++;
4318 if (ref_only)
4319 args [i] = mono_get_object_type ();
4320 else
4321 args [i] = mono_get_int_type ();
4323 ctx->method_inst = mono_metadata_get_generic_inst (inst->type_argc, args);
4327 static void
4328 add_gc_wrappers (MonoAotCompile *acfg)
4330 MonoMethod *m;
4331 /* Managed Allocators */
4332 int nallocators = mono_gc_get_managed_allocator_types ();
4333 for (int i = 0; i < nallocators; ++i) {
4334 if ((m = mono_gc_get_managed_allocator_by_type (i, MANAGED_ALLOCATOR_REGULAR)))
4335 add_method (acfg, m);
4336 if ((m = mono_gc_get_managed_allocator_by_type (i, MANAGED_ALLOCATOR_SLOW_PATH)))
4337 add_method (acfg, m);
4338 if ((m = mono_gc_get_managed_allocator_by_type (i, MANAGED_ALLOCATOR_PROFILER)))
4339 add_method (acfg, m);
4342 /* write barriers */
4343 if (mono_gc_is_moving ()) {
4344 add_method (acfg, mono_gc_get_specific_write_barrier (FALSE));
4345 add_method (acfg, mono_gc_get_specific_write_barrier (TRUE));
4349 static gboolean
4350 contains_disable_reflection_attribute (MonoCustomAttrInfo *cattr)
4352 for (int i = 0; i < cattr->num_attrs; ++i) {
4353 MonoCustomAttrEntry *attr = &cattr->attrs [i];
4355 if (!attr->ctor)
4356 return FALSE;
4358 if (strcmp (m_class_get_name_space (attr->ctor->klass), "System.Runtime.CompilerServices"))
4359 return FALSE;
4361 if (strcmp (m_class_get_name (attr->ctor->klass), "DisablePrivateReflectionAttribute"))
4362 return FALSE;
4365 return TRUE;
4368 gboolean
4369 mono_aot_can_specialize (MonoMethod *method)
4371 if (!method)
4372 return FALSE;
4374 if (method->wrapper_type != MONO_WRAPPER_NONE)
4375 return FALSE;
4377 // If it's not private, we can't specialize
4378 if ((method->flags & METHOD_ATTRIBUTE_MEMBER_ACCESS_MASK) != METHOD_ATTRIBUTE_PRIVATE)
4379 return FALSE;
4381 // If it has the attribute disabling the specialization, we can't specialize
4383 // Set by linker, indicates that the method can be found through reflection
4384 // and that call-site specialization shouldn't be done.
4386 // Important that this attribute is used for *nothing else*
4388 // If future authors make use of it (to disable more optimizations),
4389 // change this place to use a new attribute.
4390 ERROR_DECL (cattr_error);
4391 MonoCustomAttrInfo *cattr = mono_custom_attrs_from_class_checked (method->klass, cattr_error);
4393 if (!is_ok (cattr_error)) {
4394 mono_error_cleanup (cattr_error);
4395 goto cleanup_false;
4396 } else if (cattr && contains_disable_reflection_attribute (cattr)) {
4397 goto cleanup_true;
4400 cattr = mono_custom_attrs_from_method_checked (method, cattr_error);
4402 if (!is_ok (cattr_error)) {
4403 mono_error_cleanup (cattr_error);
4404 goto cleanup_false;
4405 } else if (cattr && contains_disable_reflection_attribute (cattr)) {
4406 goto cleanup_true;
4407 } else {
4408 goto cleanup_false;
4411 cleanup_false:
4412 if (cattr)
4413 mono_custom_attrs_free (cattr);
4414 return FALSE;
4416 cleanup_true:
4417 if (cattr)
4418 mono_custom_attrs_free (cattr);
4419 return TRUE;
4422 static void
4423 add_wrappers (MonoAotCompile *acfg)
4425 MonoMethod *method, *m;
4426 int i, j;
4427 MonoMethodSignature *sig, *csig;
4428 guint32 token;
4431 * FIXME: Instead of AOTing all the wrappers, it might be better to redesign them
4432 * so there is only one wrapper of a given type, or inlining their contents into their
4433 * callers.
4435 for (i = 0; i < acfg->image->tables [MONO_TABLE_METHOD].rows; ++i) {
4436 ERROR_DECL (error);
4437 MonoMethod *method;
4438 guint32 token = MONO_TOKEN_METHOD_DEF | (i + 1);
4439 gboolean skip = FALSE;
4441 method = mono_get_method_checked (acfg->image, token, NULL, NULL, error);
4442 report_loader_error (acfg, error, TRUE, "Failed to load method token 0x%x due to %s\n", i, mono_error_get_message (error));
4444 if ((method->flags & METHOD_ATTRIBUTE_PINVOKE_IMPL) ||
4445 (method->iflags & METHOD_IMPL_ATTRIBUTE_RUNTIME) ||
4446 (method->flags & METHOD_ATTRIBUTE_ABSTRACT))
4447 skip = TRUE;
4449 /* Skip methods which can not be handled by get_runtime_invoke () */
4450 sig = mono_method_signature_internal (method);
4451 if (!sig)
4452 continue;
4453 if ((sig->ret->type == MONO_TYPE_PTR) ||
4454 (sig->ret->type == MONO_TYPE_TYPEDBYREF))
4455 skip = TRUE;
4456 if (mono_class_is_open_constructed_type (sig->ret))
4457 skip = TRUE;
4459 for (j = 0; j < sig->param_count; j++) {
4460 if (sig->params [j]->type == MONO_TYPE_TYPEDBYREF)
4461 skip = TRUE;
4462 if (mono_class_is_open_constructed_type (sig->params [j]))
4463 skip = TRUE;
4466 #ifdef MONO_ARCH_DYN_CALL_SUPPORTED
4467 if (!mono_class_is_contextbound (method->klass)) {
4468 MonoDynCallInfo *info = mono_arch_dyn_call_prepare (sig);
4469 gboolean has_nullable = FALSE;
4471 for (j = 0; j < sig->param_count; j++) {
4472 if (sig->params [j]->type == MONO_TYPE_GENERICINST && mono_class_is_nullable (mono_class_from_mono_type_internal (sig->params [j])))
4473 has_nullable = TRUE;
4476 if (info && !has_nullable && !acfg->aot_opts.llvm_only) {
4477 /* Supported by the dynamic runtime-invoke wrapper */
4478 skip = TRUE;
4480 if (info)
4481 mono_arch_dyn_call_free (info);
4483 #endif
4485 if (acfg->aot_opts.llvm_only)
4486 /* Supported by the gsharedvt based runtime-invoke wrapper */
4487 skip = TRUE;
4489 if (!skip) {
4490 //printf ("%s\n", mono_method_full_name (method, TRUE));
4491 add_method (acfg, get_runtime_invoke (acfg, method, FALSE));
4495 if (mono_is_corlib_image (acfg->image->assembly->image)) {
4496 /* Runtime invoke wrappers */
4498 MonoType *void_type = mono_get_void_type ();
4499 MonoType *string_type = m_class_get_byval_arg (mono_defaults.string_class);
4501 /* void runtime-invoke () [.cctor] */
4502 csig = mono_metadata_signature_alloc (mono_defaults.corlib, 0);
4503 csig->ret = void_type;
4504 add_method (acfg, get_runtime_invoke_sig (csig));
4506 /* void runtime-invoke () [Finalize] */
4507 csig = mono_metadata_signature_alloc (mono_defaults.corlib, 0);
4508 csig->hasthis = 1;
4509 csig->ret = void_type;
4510 add_method (acfg, get_runtime_invoke_sig (csig));
4512 /* void runtime-invoke (string) [exception ctor] */
4513 csig = mono_metadata_signature_alloc (mono_defaults.corlib, 1);
4514 csig->hasthis = 1;
4515 csig->ret = void_type;
4516 csig->params [0] = string_type;
4517 add_method (acfg, get_runtime_invoke_sig (csig));
4519 /* void runtime-invoke (string, string) [exception ctor] */
4520 csig = mono_metadata_signature_alloc (mono_defaults.corlib, 2);
4521 csig->hasthis = 1;
4522 csig->ret = void_type;
4523 csig->params [0] = string_type;
4524 csig->params [1] = string_type;
4525 add_method (acfg, get_runtime_invoke_sig (csig));
4527 /* string runtime-invoke () [Exception.ToString ()] */
4528 csig = mono_metadata_signature_alloc (mono_defaults.corlib, 0);
4529 csig->hasthis = 1;
4530 csig->ret = string_type;
4531 add_method (acfg, get_runtime_invoke_sig (csig));
4533 /* void runtime-invoke (string, Exception) [exception ctor] */
4534 csig = mono_metadata_signature_alloc (mono_defaults.corlib, 2);
4535 csig->hasthis = 1;
4536 csig->ret = void_type;
4537 csig->params [0] = string_type;
4538 csig->params [1] = m_class_get_byval_arg (mono_defaults.exception_class);
4539 add_method (acfg, get_runtime_invoke_sig (csig));
4541 /* Assembly runtime-invoke (string, Assembly, bool) [DoAssemblyResolve] */
4542 csig = mono_metadata_signature_alloc (mono_defaults.corlib, 3);
4543 csig->hasthis = 1;
4544 csig->ret = m_class_get_byval_arg (mono_class_load_from_name (mono_defaults.corlib, "System.Reflection", "Assembly"));
4545 csig->params [0] = string_type;
4546 csig->params [1] = m_class_get_byval_arg (mono_class_load_from_name (mono_defaults.corlib, "System.Reflection", "Assembly"));
4547 csig->params [2] = m_class_get_byval_arg (mono_defaults.boolean_class);
4548 add_method (acfg, get_runtime_invoke_sig (csig));
4550 /* runtime-invoke used by finalizers */
4551 add_method (acfg, get_runtime_invoke (acfg, get_method_nofail (mono_defaults.object_class, "Finalize", 0, 0), TRUE));
4553 /* This is used by mono_runtime_capture_context () */
4554 method = mono_get_context_capture_method ();
4555 if (method)
4556 add_method (acfg, get_runtime_invoke (acfg, method, FALSE));
4558 #ifdef MONO_ARCH_DYN_CALL_SUPPORTED
4559 if (!acfg->aot_opts.llvm_only)
4560 add_method (acfg, mono_marshal_get_runtime_invoke_dynamic ());
4561 #endif
4563 /* These are used by mono_jit_runtime_invoke () to calls gsharedvt out wrappers */
4564 if (acfg->aot_opts.llvm_only) {
4565 int variants;
4567 /* Create simplified signatures which match the signature used by the gsharedvt out wrappers */
4568 for (variants = 0; variants < 4; ++variants) {
4569 for (i = 0; i < 40; ++i) {
4570 sig = mini_get_gsharedvt_out_sig_wrapper_signature ((variants & 1) > 0, (variants & 2) > 0, i);
4571 add_extra_method (acfg, mono_marshal_get_runtime_invoke_for_sig (sig));
4573 g_free (sig);
4578 /* stelemref */
4579 add_method (acfg, mono_marshal_get_stelemref ());
4581 add_gc_wrappers (acfg);
4583 /* Stelemref wrappers */
4585 MonoMethod **wrappers;
4586 int nwrappers;
4588 wrappers = mono_marshal_get_virtual_stelemref_wrappers (&nwrappers);
4589 for (i = 0; i < nwrappers; ++i)
4590 add_method (acfg, wrappers [i]);
4591 g_free (wrappers);
4594 /* castclass_with_check wrapper */
4595 add_method (acfg, mono_marshal_get_castclass_with_cache ());
4596 /* isinst_with_check wrapper */
4597 add_method (acfg, mono_marshal_get_isinst_with_cache ());
4599 /* JIT icall wrappers */
4600 /* FIXME: locking - this is "safe" as full-AOT threads don't mutate the icall data */
4601 for (int i = 0; i < MONO_JIT_ICALL_count; ++i)
4602 add_jit_icall_wrapper (acfg, mono_find_jit_icall_info ((MonoJitICallId)i));
4606 * remoting-invoke-with-check wrappers are very frequent, so avoid emitting them,
4607 * we use the original method instead at runtime.
4608 * Since full-aot doesn't support remoting, this is not a problem.
4610 #if 0
4611 /* remoting-invoke wrappers */
4612 for (i = 0; i < acfg->image->tables [MONO_TABLE_METHOD].rows; ++i) {
4613 ERROR_DECL (error);
4614 MonoMethodSignature *sig;
4616 token = MONO_TOKEN_METHOD_DEF | (i + 1);
4617 method = mono_get_method_checked (acfg->image, token, NULL, NULL, error);
4618 g_assert (mono_error_ok (error)); /* FIXME don't swallow the error */
4620 sig = mono_method_signature_internal (method);
4622 if (sig->hasthis && (method->klass->marshalbyref || method->klass == mono_defaults.object_class)) {
4623 m = mono_marshal_get_remoting_invoke_with_check (method);
4625 add_method (acfg, m);
4628 #endif
4630 /* delegate-invoke wrappers */
4631 for (i = 0; i < acfg->image->tables [MONO_TABLE_TYPEDEF].rows; ++i) {
4632 ERROR_DECL (error);
4633 MonoClass *klass;
4635 token = MONO_TOKEN_TYPE_DEF | (i + 1);
4636 klass = mono_class_get_checked (acfg->image, token, error);
4638 if (!klass) {
4639 mono_error_cleanup (error);
4640 continue;
4643 if (!m_class_is_delegate (klass) || klass == mono_defaults.delegate_class || klass == mono_defaults.multicastdelegate_class)
4644 continue;
4646 if (!mono_class_is_gtd (klass)) {
4647 method = mono_get_delegate_invoke_internal (klass);
4649 m = mono_marshal_get_delegate_invoke (method, NULL);
4651 add_method (acfg, m);
4653 method = try_get_method_nofail (klass, "BeginInvoke", -1, 0);
4654 if (method)
4655 add_method (acfg, mono_marshal_get_delegate_begin_invoke (method));
4657 method = try_get_method_nofail (klass, "EndInvoke", -1, 0);
4658 if (method)
4659 add_method (acfg, mono_marshal_get_delegate_end_invoke (method));
4661 MonoCustomAttrInfo *cattr;
4662 cattr = mono_custom_attrs_from_class_checked (klass, error);
4663 if (!is_ok (error)) {
4664 mono_error_cleanup (error);
4665 g_assert (!cattr);
4666 continue;
4669 if (cattr) {
4670 int j;
4672 for (j = 0; j < cattr->num_attrs; ++j)
4673 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")))
4674 break;
4675 if (j < cattr->num_attrs) {
4676 MonoMethod *invoke;
4677 MonoMethod *wrapper;
4678 MonoMethod *del_invoke;
4680 /* Add wrappers needed by mono_ftnptr_to_delegate () */
4681 invoke = mono_get_delegate_invoke_internal (klass);
4682 wrapper = mono_marshal_get_native_func_wrapper_aot (klass);
4683 del_invoke = mono_marshal_get_delegate_invoke_internal (invoke, FALSE, TRUE, wrapper);
4684 add_method (acfg, wrapper);
4685 add_method (acfg, del_invoke);
4687 mono_custom_attrs_free (cattr);
4689 } else if ((acfg->opts & MONO_OPT_GSHAREDVT) && mono_class_is_gtd (klass)) {
4690 ERROR_DECL (error);
4691 MonoGenericContext ctx;
4692 MonoMethod *inst, *gshared;
4695 * Emit gsharedvt versions of the generic delegate-invoke wrappers
4697 /* Invoke */
4698 method = mono_get_delegate_invoke_internal (klass);
4699 create_gsharedvt_inst (acfg, method, &ctx);
4701 inst = mono_class_inflate_generic_method_checked (method, &ctx, error);
4702 g_assert (mono_error_ok (error)); /* FIXME don't swallow the error */
4704 m = mono_marshal_get_delegate_invoke (inst, NULL);
4705 g_assert (m->is_inflated);
4707 gshared = mini_get_shared_method_full (m, SHARE_MODE_GSHAREDVT, error);
4708 mono_error_assert_ok (error);
4710 add_extra_method (acfg, gshared);
4712 /* begin-invoke */
4713 method = mono_get_delegate_begin_invoke_internal (klass);
4714 if (method) {
4715 create_gsharedvt_inst (acfg, method, &ctx);
4717 inst = mono_class_inflate_generic_method_checked (method, &ctx, error);
4718 g_assert (mono_error_ok (error)); /* FIXME don't swallow the error */
4720 m = mono_marshal_get_delegate_begin_invoke (inst);
4721 g_assert (m->is_inflated);
4723 gshared = mini_get_shared_method_full (m, SHARE_MODE_GSHAREDVT, error);
4724 mono_error_assert_ok (error);
4726 add_extra_method (acfg, gshared);
4729 /* end-invoke */
4730 method = mono_get_delegate_end_invoke_internal (klass);
4731 if (method) {
4732 create_gsharedvt_inst (acfg, method, &ctx);
4734 inst = mono_class_inflate_generic_method_checked (method, &ctx, error);
4735 g_assert (mono_error_ok (error)); /* FIXME don't swallow the error */
4737 m = mono_marshal_get_delegate_end_invoke (inst);
4738 g_assert (m->is_inflated);
4740 gshared = mini_get_shared_method_full (m, SHARE_MODE_GSHAREDVT, error);
4741 mono_error_assert_ok (error);
4743 add_extra_method (acfg, gshared);
4748 /* array access wrappers */
4749 for (i = 0; i < acfg->image->tables [MONO_TABLE_TYPESPEC].rows; ++i) {
4750 ERROR_DECL (error);
4751 MonoClass *klass;
4753 token = MONO_TOKEN_TYPE_SPEC | (i + 1);
4754 klass = mono_class_get_checked (acfg->image, token, error);
4756 if (!klass) {
4757 mono_error_cleanup (error);
4758 continue;
4761 if (m_class_get_rank (klass) && MONO_TYPE_IS_PRIMITIVE (m_class_get_byval_arg (m_class_get_element_class (klass)))) {
4762 MonoMethod *m, *wrapper;
4764 /* Add runtime-invoke wrappers too */
4766 m = get_method_nofail (klass, "Get", -1, 0);
4767 g_assert (m);
4768 wrapper = mono_marshal_get_array_accessor_wrapper (m);
4769 add_extra_method (acfg, wrapper);
4770 if (!acfg->aot_opts.llvm_only)
4771 add_extra_method (acfg, get_runtime_invoke (acfg, wrapper, FALSE));
4773 m = get_method_nofail (klass, "Set", -1, 0);
4774 g_assert (m);
4775 wrapper = mono_marshal_get_array_accessor_wrapper (m);
4776 add_extra_method (acfg, wrapper);
4777 if (!acfg->aot_opts.llvm_only)
4778 add_extra_method (acfg, get_runtime_invoke (acfg, wrapper, FALSE));
4782 /* Synchronized wrappers */
4783 for (i = 0; i < acfg->image->tables [MONO_TABLE_METHOD].rows; ++i) {
4784 ERROR_DECL (error);
4785 token = MONO_TOKEN_METHOD_DEF | (i + 1);
4786 method = mono_get_method_checked (acfg->image, token, NULL, NULL, error);
4787 report_loader_error (acfg, error, TRUE, "Failed to load method token 0x%x due to %s\n", i, mono_error_get_message (error));
4789 if (method->iflags & METHOD_IMPL_ATTRIBUTE_SYNCHRONIZED) {
4790 if (method->is_generic) {
4791 // FIXME:
4792 } else if ((acfg->opts & MONO_OPT_GSHAREDVT) && mono_class_is_gtd (method->klass)) {
4793 ERROR_DECL (error);
4794 MonoGenericContext ctx;
4795 MonoMethod *inst, *gshared, *m;
4798 * Create a generic wrapper for a generic instance, and AOT that.
4800 create_gsharedvt_inst (acfg, method, &ctx);
4801 inst = mono_class_inflate_generic_method_checked (method, &ctx, error);
4802 g_assert (mono_error_ok (error)); /* FIXME don't swallow the error */
4803 m = mono_marshal_get_synchronized_wrapper (inst);
4804 g_assert (m->is_inflated);
4805 gshared = mini_get_shared_method_full (m, SHARE_MODE_GSHAREDVT, error);
4806 mono_error_assert_ok (error);
4808 add_method (acfg, gshared);
4809 } else {
4810 add_method (acfg, mono_marshal_get_synchronized_wrapper (method));
4815 /* pinvoke wrappers */
4816 for (i = 0; i < acfg->image->tables [MONO_TABLE_METHOD].rows; ++i) {
4817 ERROR_DECL (error);
4818 MonoMethod *method;
4819 guint32 token = MONO_TOKEN_METHOD_DEF | (i + 1);
4821 method = mono_get_method_checked (acfg->image, token, NULL, NULL, error);
4822 report_loader_error (acfg, error, TRUE, "Failed to load method token 0x%x due to %s\n", i, mono_error_get_message (error));
4824 if ((method->flags & METHOD_ATTRIBUTE_PINVOKE_IMPL) ||
4825 (method->iflags & METHOD_IMPL_ATTRIBUTE_INTERNAL_CALL)) {
4826 add_method (acfg, mono_marshal_get_native_wrapper (method, TRUE, TRUE));
4829 if (method->iflags & METHOD_IMPL_ATTRIBUTE_INTERNAL_CALL) {
4830 if (acfg->aot_opts.llvm_only) {
4831 /* The wrappers have a different signature (hasthis is not set) so need to add this too */
4832 add_gsharedvt_wrappers (acfg, mono_method_signature_internal (method), FALSE, TRUE, FALSE);
4837 /* native-to-managed wrappers */
4838 for (i = 0; i < acfg->image->tables [MONO_TABLE_METHOD].rows; ++i) {
4839 ERROR_DECL (error);
4840 MonoMethod *method;
4841 guint32 token = MONO_TOKEN_METHOD_DEF | (i + 1);
4842 MonoCustomAttrInfo *cattr;
4843 int j;
4845 method = mono_get_method_checked (acfg->image, token, NULL, NULL, error);
4846 report_loader_error (acfg, error, TRUE, "Failed to load method token 0x%x due to %s\n", i, mono_error_get_message (error));
4849 * Only generate native-to-managed wrappers for methods which have an
4850 * attribute named MonoPInvokeCallbackAttribute. We search for the attribute by
4851 * name to avoid defining a new assembly to contain it.
4853 cattr = mono_custom_attrs_from_method_checked (method, error);
4854 if (!is_ok (error)) {
4855 char *name = mono_method_get_full_name (method);
4856 report_loader_error (acfg, error, TRUE, "Failed to load custom attributes from method %s due to %s\n", name, mono_error_get_message (error));
4857 g_free (name);
4860 if (cattr) {
4861 for (j = 0; j < cattr->num_attrs; ++j)
4862 if (cattr->attrs [j].ctor && !strcmp (m_class_get_name (cattr->attrs [j].ctor->klass), "MonoPInvokeCallbackAttribute"))
4863 break;
4864 if (j < cattr->num_attrs) {
4865 MonoCustomAttrEntry *e = &cattr->attrs [j];
4866 MonoMethodSignature *sig = mono_method_signature_internal (e->ctor);
4867 const char *p = (const char*)e->data;
4868 const char *named;
4869 int slen, num_named, named_type;
4870 char *n;
4871 MonoType *t;
4872 MonoClass *klass;
4873 char *export_name = NULL;
4874 MonoMethod *wrapper;
4876 /* this cannot be enforced by the C# compiler so we must give the user some warning before aborting */
4877 if (!(method->flags & METHOD_ATTRIBUTE_STATIC)) {
4878 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",
4879 mono_method_full_name (method, TRUE));
4880 exit (1);
4883 g_assert (sig->param_count == 1);
4884 g_assert (sig->params [0]->type == MONO_TYPE_CLASS && !strcmp (m_class_get_name (mono_class_from_mono_type_internal (sig->params [0])), "Type"));
4887 * Decode the cattr manually since we can't create objects
4888 * during aot compilation.
4891 /* Skip prolog */
4892 p += 2;
4894 /* From load_cattr_value () in reflection.c */
4895 slen = mono_metadata_decode_value (p, &p);
4896 n = (char *)g_memdup (p, slen + 1);
4897 n [slen] = 0;
4898 t = mono_reflection_type_from_name_checked (n, acfg->image, error);
4899 g_assert (t);
4900 mono_error_assert_ok (error);
4901 g_free (n);
4903 klass = mono_class_from_mono_type_internal (t);
4904 g_assert (m_class_get_parent (klass) == mono_defaults.multicastdelegate_class);
4906 p += slen;
4908 num_named = read16 (p);
4909 p += 2;
4911 g_assert (num_named < 2);
4912 if (num_named == 1) {
4913 int name_len;
4914 char *name;
4916 /* parse ExportSymbol attribute */
4917 named = p;
4918 named_type = *named;
4919 named += 1;
4920 /* data_type = *named; */
4921 named += 1;
4923 name_len = mono_metadata_decode_blob_size (named, &named);
4924 name = (char *)g_malloc (name_len + 1);
4925 memcpy (name, named, name_len);
4926 name [name_len] = 0;
4927 named += name_len;
4929 g_assert (named_type == 0x54);
4930 g_assert (!strcmp (name, "ExportSymbol"));
4932 /* load_cattr_value (), string case */
4933 MONO_DISABLE_WARNING (4310) // cast truncates constant value
4934 g_assert (*named != (char)0xFF);
4935 MONO_RESTORE_WARNING
4936 slen = mono_metadata_decode_value (named, &named);
4937 export_name = (char *)g_malloc (slen + 1);
4938 memcpy (export_name, named, slen);
4939 export_name [slen] = 0;
4940 named += slen;
4943 wrapper = mono_marshal_get_managed_wrapper (method, klass, 0, error);
4944 mono_error_assert_ok (error);
4946 add_method (acfg, wrapper);
4947 if (export_name)
4948 g_hash_table_insert (acfg->export_names, wrapper, export_name);
4950 g_free (cattr);
4953 if ((method->flags & METHOD_ATTRIBUTE_PINVOKE_IMPL) ||
4954 (method->iflags & METHOD_IMPL_ATTRIBUTE_INTERNAL_CALL)) {
4955 add_method (acfg, mono_marshal_get_native_wrapper (method, TRUE, TRUE));
4959 /* StructureToPtr/PtrToStructure wrappers */
4960 for (i = 0; i < acfg->image->tables [MONO_TABLE_TYPEDEF].rows; ++i) {
4961 ERROR_DECL (error);
4962 MonoClass *klass;
4964 token = MONO_TOKEN_TYPE_DEF | (i + 1);
4965 klass = mono_class_get_checked (acfg->image, token, error);
4967 if (!klass) {
4968 mono_error_cleanup (error);
4969 continue;
4972 if (m_class_is_valuetype (klass) && !mono_class_is_gtd (klass) && can_marshal_struct (klass) &&
4973 !(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)))) {
4974 add_method (acfg, mono_marshal_get_struct_to_ptr (klass));
4975 add_method (acfg, mono_marshal_get_ptr_to_struct (klass));
4980 static gboolean
4981 has_type_vars (MonoClass *klass)
4983 if ((m_class_get_byval_arg (klass)->type == MONO_TYPE_VAR) || (m_class_get_byval_arg (klass)->type == MONO_TYPE_MVAR))
4984 return TRUE;
4985 if (m_class_get_rank (klass))
4986 return has_type_vars (m_class_get_element_class (klass));
4987 if (mono_class_is_ginst (klass)) {
4988 MonoGenericContext *context = &mono_class_get_generic_class (klass)->context;
4989 if (context->class_inst) {
4990 int i;
4992 for (i = 0; i < context->class_inst->type_argc; ++i)
4993 if (has_type_vars (mono_class_from_mono_type_internal (context->class_inst->type_argv [i])))
4994 return TRUE;
4997 if (mono_class_is_gtd (klass))
4998 return TRUE;
4999 return FALSE;
5002 static gboolean
5003 is_vt_inst (MonoGenericInst *inst)
5005 int i;
5007 for (i = 0; i < inst->type_argc; ++i) {
5008 MonoType *t = inst->type_argv [i];
5009 if (MONO_TYPE_ISSTRUCT (t) || t->type == MONO_TYPE_VALUETYPE)
5010 return TRUE;
5012 return FALSE;
5015 static gboolean
5016 method_has_type_vars (MonoMethod *method)
5018 if (has_type_vars (method->klass))
5019 return TRUE;
5021 if (method->is_inflated) {
5022 MonoGenericContext *context = mono_method_get_context (method);
5023 if (context->method_inst) {
5024 int i;
5026 for (i = 0; i < context->method_inst->type_argc; ++i)
5027 if (has_type_vars (mono_class_from_mono_type_internal (context->method_inst->type_argv [i])))
5028 return TRUE;
5031 return FALSE;
5034 static
5035 gboolean mono_aot_mode_is_full (MonoAotOptions *opts)
5037 return opts->mode == MONO_AOT_MODE_FULL;
5040 static
5041 gboolean mono_aot_mode_is_interp (MonoAotOptions *opts)
5043 return opts->interp;
5046 static
5047 gboolean mono_aot_mode_is_hybrid (MonoAotOptions *opts)
5049 return opts->mode == MONO_AOT_MODE_HYBRID;
5052 static void add_generic_class_with_depth (MonoAotCompile *acfg, MonoClass *klass, int depth, const char *ref);
5054 static void
5055 add_generic_class (MonoAotCompile *acfg, MonoClass *klass, gboolean force, const char *ref)
5057 /* This might lead to a huge code blowup so only do it if neccesary */
5058 if (!mono_aot_mode_is_full (&acfg->aot_opts) && !mono_aot_mode_is_hybrid (&acfg->aot_opts) && !force)
5059 return;
5061 add_generic_class_with_depth (acfg, klass, 0, ref);
5064 static gboolean
5065 check_type_depth (MonoType *t, int depth)
5067 int i;
5069 if (depth > 8)
5070 return TRUE;
5072 switch (t->type) {
5073 case MONO_TYPE_GENERICINST: {
5074 MonoGenericClass *gklass = t->data.generic_class;
5075 MonoGenericInst *ginst = gklass->context.class_inst;
5077 if (ginst) {
5078 for (i = 0; i < ginst->type_argc; ++i) {
5079 if (check_type_depth (ginst->type_argv [i], depth + 1))
5080 return TRUE;
5083 break;
5085 default:
5086 break;
5089 return FALSE;
5092 static void
5093 add_types_from_method_header (MonoAotCompile *acfg, MonoMethod *method);
5096 * add_generic_class:
5098 * Add all methods of a generic class.
5100 static void
5101 add_generic_class_with_depth (MonoAotCompile *acfg, MonoClass *klass, int depth, const char *ref)
5103 MonoMethod *method;
5104 MonoClassField *field;
5105 gpointer iter;
5106 gboolean use_gsharedvt = FALSE;
5108 if (!acfg->ginst_hash)
5109 acfg->ginst_hash = g_hash_table_new (NULL, NULL);
5111 mono_class_init_internal (klass);
5113 if (mono_class_is_ginst (klass) && mono_class_get_generic_class (klass)->context.class_inst->is_open)
5114 return;
5116 if (has_type_vars (klass))
5117 return;
5119 if (!mono_class_is_ginst (klass) && !m_class_get_rank (klass))
5120 return;
5122 if (mono_class_has_failure (klass))
5123 return;
5125 if (!acfg->ginst_hash)
5126 acfg->ginst_hash = g_hash_table_new (NULL, NULL);
5128 if (g_hash_table_lookup (acfg->ginst_hash, klass))
5129 return;
5131 if (check_type_depth (m_class_get_byval_arg (klass), 0))
5132 return;
5134 if (acfg->aot_opts.log_generics) {
5135 char *s = mono_type_full_name (m_class_get_byval_arg (klass));
5136 aot_printf (acfg, "%*sAdding generic instance %s [%s].\n", depth, "", s, ref);
5137 g_free (s);
5140 g_hash_table_insert (acfg->ginst_hash, klass, klass);
5143 * Use gsharedvt for generic collections with vtype arguments to avoid code blowup.
5144 * Enable this only for some classes since gsharedvt might not support all methods.
5146 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) &&
5147 (!strcmp (m_class_get_name (klass), "Dictionary`2") || !strcmp (m_class_get_name (klass), "List`1") || !strcmp (m_class_get_name (klass), "ReadOnlyCollection`1")))
5148 use_gsharedvt = TRUE;
5150 iter = NULL;
5151 while ((method = mono_class_get_methods (klass, &iter))) {
5152 if ((acfg->opts & MONO_OPT_GSHAREDVT) && method->is_inflated && mono_method_get_context (method)->method_inst) {
5154 * This is partial sharing, and we can't handle it yet
5156 continue;
5159 if (mono_method_is_generic_sharable_full (method, FALSE, FALSE, use_gsharedvt)) {
5160 /* Already added */
5161 add_types_from_method_header (acfg, method);
5162 continue;
5165 if (method->is_generic)
5166 /* FIXME: */
5167 continue;
5170 * FIXME: Instances which are referenced by these methods are not added,
5171 * for example Array.Resize<int> for List<int>.Add ().
5173 add_extra_method_with_depth (acfg, method, depth + 1);
5176 iter = NULL;
5177 while ((field = mono_class_get_fields_internal (klass, &iter))) {
5178 if (field->type->type == MONO_TYPE_GENERICINST)
5179 add_generic_class_with_depth (acfg, mono_class_from_mono_type_internal (field->type), depth + 1, "field");
5182 if (m_class_is_delegate (klass)) {
5183 method = mono_get_delegate_invoke_internal (klass);
5185 method = mono_marshal_get_delegate_invoke (method, NULL);
5187 if (acfg->aot_opts.log_generics)
5188 aot_printf (acfg, "%*sAdding method %s.\n", depth, "", mono_method_get_full_name (method));
5190 add_method (acfg, method);
5193 /* Add superclasses */
5194 if (m_class_get_parent (klass))
5195 add_generic_class_with_depth (acfg, m_class_get_parent (klass), depth, "parent");
5197 const char *klass_name = m_class_get_name (klass);
5198 const char *klass_name_space = m_class_get_name_space (klass);
5199 const gboolean in_corlib = m_class_get_image (klass) == mono_defaults.corlib;
5201 * For ICollection<T>, add instances of the helper methods
5202 * in Array, since a T[] could be cast to ICollection<T>.
5204 if (in_corlib && !strcmp (klass_name_space, "System.Collections.Generic") &&
5205 (!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"))) {
5206 MonoClass *tclass = mono_class_from_mono_type_internal (mono_class_get_generic_class (klass)->context.class_inst->type_argv [0]);
5207 MonoClass *array_class = mono_class_create_bounded_array (tclass, 1, FALSE);
5208 gpointer iter;
5209 char *name_prefix;
5211 if (!strcmp (klass_name, "IEnumerator`1"))
5212 name_prefix = g_strdup_printf ("%s.%s", klass_name_space, "IEnumerable`1");
5213 else
5214 name_prefix = g_strdup_printf ("%s.%s", klass_name_space, klass_name);
5216 /* Add the T[]/InternalEnumerator class */
5217 if (!strcmp (klass_name, "IEnumerable`1") || !strcmp (klass_name, "IEnumerator`1")) {
5218 ERROR_DECL (error);
5219 MonoClass *nclass;
5221 iter = NULL;
5222 while ((nclass = mono_class_get_nested_types (m_class_get_parent (array_class), &iter))) {
5223 if (!strcmp (m_class_get_name (nclass), "InternalEnumerator`1"))
5224 break;
5226 g_assert (nclass);
5227 nclass = mono_class_inflate_generic_class_checked (nclass, mono_generic_class_get_context (mono_class_get_generic_class (klass)), error);
5228 mono_error_assert_ok (error); /* FIXME don't swallow the error */
5229 add_generic_class (acfg, nclass, FALSE, "ICollection<T>");
5232 iter = NULL;
5233 while ((method = mono_class_get_methods (array_class, &iter))) {
5234 if (!strncmp (method->name, name_prefix, strlen (name_prefix))) {
5235 MonoMethod *m = mono_aot_get_array_helper_from_wrapper (method);
5237 if (m->is_inflated && !mono_method_is_generic_sharable_full (m, FALSE, FALSE, FALSE))
5238 add_extra_method_with_depth (acfg, m, depth);
5242 g_free (name_prefix);
5245 /* Add an instance of GenericComparer<T> which is created dynamically by Comparer<T> */
5246 if (in_corlib && !strcmp (klass_name_space, "System.Collections.Generic") && !strcmp (klass_name, "Comparer`1")) {
5247 ERROR_DECL (error);
5248 MonoClass *tclass = mono_class_from_mono_type_internal (mono_class_get_generic_class (klass)->context.class_inst->type_argv [0]);
5249 MonoClass *icomparable, *gcomparer, *icomparable_inst;
5250 MonoGenericContext ctx;
5251 MonoType *args [16];
5253 memset (&ctx, 0, sizeof (ctx));
5255 icomparable = mono_class_load_from_name (mono_defaults.corlib, "System", "IComparable`1");
5257 args [0] = m_class_get_byval_arg (tclass);
5258 ctx.class_inst = mono_metadata_get_generic_inst (1, args);
5260 icomparable_inst = mono_class_inflate_generic_class_checked (icomparable, &ctx, error);
5261 mono_error_assert_ok (error); /* FIXME don't swallow the error */
5263 if (mono_class_is_assignable_from_internal (icomparable_inst, tclass)) {
5264 MonoClass *gcomparer_inst;
5265 gcomparer = mono_class_load_from_name (mono_defaults.corlib, "System.Collections.Generic", "GenericComparer`1");
5266 gcomparer_inst = mono_class_inflate_generic_class_checked (gcomparer, &ctx, error);
5267 mono_error_assert_ok (error); /* FIXME don't swallow the error */
5269 add_generic_class (acfg, gcomparer_inst, FALSE, "Comparer<T>");
5273 /* Add an instance of GenericEqualityComparer<T> which is created dynamically by EqualityComparer<T> */
5274 if (in_corlib && !strcmp (klass_name_space, "System.Collections.Generic") && !strcmp (klass_name, "EqualityComparer`1")) {
5275 ERROR_DECL (error);
5276 MonoClass *tclass = mono_class_from_mono_type_internal (mono_class_get_generic_class (klass)->context.class_inst->type_argv [0]);
5277 MonoClass *iface, *gcomparer, *iface_inst;
5278 MonoGenericContext ctx;
5279 MonoType *args [16];
5281 memset (&ctx, 0, sizeof (ctx));
5283 iface = mono_class_load_from_name (mono_defaults.corlib, "System", "IEquatable`1");
5284 g_assert (iface);
5285 args [0] = m_class_get_byval_arg (tclass);
5286 ctx.class_inst = mono_metadata_get_generic_inst (1, args);
5288 iface_inst = mono_class_inflate_generic_class_checked (iface, &ctx, error);
5289 mono_error_assert_ok (error); /* FIXME don't swallow the error */
5291 if (mono_class_is_assignable_from_internal (iface_inst, tclass)) {
5292 MonoClass *gcomparer_inst;
5293 ERROR_DECL (error);
5295 gcomparer = mono_class_load_from_name (mono_defaults.corlib, "System.Collections.Generic", "GenericEqualityComparer`1");
5296 gcomparer_inst = mono_class_inflate_generic_class_checked (gcomparer, &ctx, error);
5297 mono_error_assert_ok (error); /* FIXME don't swallow the error */
5298 add_generic_class (acfg, gcomparer_inst, FALSE, "EqualityComparer<T>");
5302 /* Add an instance of EnumComparer<T> which is created dynamically by EqualityComparer<T> for enums */
5303 if (in_corlib && !strcmp (klass_name_space, "System.Collections.Generic") && !strcmp (klass_name, "EqualityComparer`1")) {
5304 MonoClass *enum_comparer;
5305 MonoClass *tclass = mono_class_from_mono_type_internal (mono_class_get_generic_class (klass)->context.class_inst->type_argv [0]);
5306 MonoGenericContext ctx;
5307 MonoType *args [16];
5309 if (m_class_is_enumtype (tclass)) {
5310 MonoClass *enum_comparer_inst;
5311 ERROR_DECL (error);
5313 memset (&ctx, 0, sizeof (ctx));
5314 args [0] = m_class_get_byval_arg (tclass);
5315 ctx.class_inst = mono_metadata_get_generic_inst (1, args);
5317 enum_comparer = mono_class_load_from_name (mono_defaults.corlib, "System.Collections.Generic", "EnumEqualityComparer`1");
5318 enum_comparer_inst = mono_class_inflate_generic_class_checked (enum_comparer, &ctx, error);
5319 mono_error_assert_ok (error); /* FIXME don't swallow the error */
5320 add_generic_class (acfg, enum_comparer_inst, FALSE, "EqualityComparer<T>");
5324 /* Add an instance of ObjectComparer<T> which is created dynamically by Comparer<T> for enums */
5325 if (in_corlib && !strcmp (klass_name_space, "System.Collections.Generic") && !strcmp (klass_name, "Comparer`1")) {
5326 MonoClass *comparer;
5327 MonoClass *tclass = mono_class_from_mono_type_internal (mono_class_get_generic_class (klass)->context.class_inst->type_argv [0]);
5328 MonoGenericContext ctx;
5329 MonoType *args [16];
5331 if (m_class_is_enumtype (tclass)) {
5332 MonoClass *comparer_inst;
5333 ERROR_DECL (error);
5335 memset (&ctx, 0, sizeof (ctx));
5336 args [0] = m_class_get_byval_arg (tclass);
5337 ctx.class_inst = mono_metadata_get_generic_inst (1, args);
5339 comparer = mono_class_load_from_name (mono_defaults.corlib, "System.Collections.Generic", "ObjectComparer`1");
5340 comparer_inst = mono_class_inflate_generic_class_checked (comparer, &ctx, error);
5341 mono_error_assert_ok (error); /* FIXME don't swallow the error */
5342 add_generic_class (acfg, comparer_inst, FALSE, "Comparer<T>");
5347 static void
5348 add_instances_of (MonoAotCompile *acfg, MonoClass *klass, MonoType **insts, int ninsts, gboolean force)
5350 int i;
5351 MonoGenericContext ctx;
5352 MonoType *args [16];
5354 if (acfg->aot_opts.no_instances)
5355 return;
5357 memset (&ctx, 0, sizeof (ctx));
5359 for (i = 0; i < ninsts; ++i) {
5360 ERROR_DECL (error);
5361 MonoClass *generic_inst;
5362 args [0] = insts [i];
5363 ctx.class_inst = mono_metadata_get_generic_inst (1, args);
5364 generic_inst = mono_class_inflate_generic_class_checked (klass, &ctx, error);
5365 mono_error_assert_ok (error); /* FIXME don't swallow the error */
5366 add_generic_class (acfg, generic_inst, force, "");
5370 static void
5371 add_types_from_method_header (MonoAotCompile *acfg, MonoMethod *method)
5373 ERROR_DECL (error);
5374 MonoMethodHeader *header;
5375 MonoMethodSignature *sig;
5376 int j, depth;
5378 depth = GPOINTER_TO_UINT (g_hash_table_lookup (acfg->method_depth, method));
5380 sig = mono_method_signature_internal (method);
5382 if (sig) {
5383 for (j = 0; j < sig->param_count; ++j)
5384 if (sig->params [j]->type == MONO_TYPE_GENERICINST)
5385 add_generic_class_with_depth (acfg, mono_class_from_mono_type_internal (sig->params [j]), depth + 1, "arg");
5388 header = mono_method_get_header_checked (method, error);
5390 if (header) {
5391 for (j = 0; j < header->num_locals; ++j)
5392 if (header->locals [j]->type == MONO_TYPE_GENERICINST)
5393 add_generic_class_with_depth (acfg, mono_class_from_mono_type_internal (header->locals [j]), depth + 1, "local");
5394 mono_metadata_free_mh (header);
5395 } else {
5396 mono_error_cleanup (error); /* FIXME report the error */
5402 * add_generic_instances:
5404 * Add instances referenced by the METHODSPEC/TYPESPEC table.
5406 static void
5407 add_generic_instances (MonoAotCompile *acfg)
5409 int i;
5410 guint32 token;
5411 MonoMethod *method;
5412 MonoGenericContext *context;
5414 if (acfg->aot_opts.no_instances)
5415 return;
5417 for (i = 0; i < acfg->image->tables [MONO_TABLE_METHODSPEC].rows; ++i) {
5418 ERROR_DECL (error);
5419 token = MONO_TOKEN_METHOD_SPEC | (i + 1);
5420 method = mono_get_method_checked (acfg->image, token, NULL, NULL, error);
5422 if (!method) {
5423 aot_printerrf (acfg, "Failed to load methodspec 0x%x due to %s.\n", token, mono_error_get_message (error));
5424 aot_printerrf (acfg, "Run with MONO_LOG_LEVEL=debug for more information.\n");
5425 mono_error_cleanup (error);
5426 continue;
5429 if (m_class_get_image (method->klass) != acfg->image)
5430 continue;
5432 context = mono_method_get_context (method);
5434 if (context && ((context->class_inst && context->class_inst->is_open)))
5435 continue;
5438 * For open methods, create an instantiation which can be passed to the JIT.
5439 * FIXME: Handle class_inst as well.
5441 if (context && context->method_inst && context->method_inst->is_open) {
5442 ERROR_DECL (error);
5443 MonoGenericContext shared_context;
5444 MonoGenericInst *inst;
5445 MonoType **type_argv;
5446 int i;
5447 MonoMethod *declaring_method;
5448 gboolean supported = TRUE;
5450 /* Check that the context doesn't contain open constructed types */
5451 if (context->class_inst) {
5452 inst = context->class_inst;
5453 for (i = 0; i < inst->type_argc; ++i) {
5454 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)
5455 continue;
5456 if (mono_class_is_open_constructed_type (inst->type_argv [i]))
5457 supported = FALSE;
5460 if (context->method_inst) {
5461 inst = context->method_inst;
5462 for (i = 0; i < inst->type_argc; ++i) {
5463 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)
5464 continue;
5465 if (mono_class_is_open_constructed_type (inst->type_argv [i]))
5466 supported = FALSE;
5470 if (!supported)
5471 continue;
5473 memset (&shared_context, 0, sizeof (MonoGenericContext));
5475 inst = context->class_inst;
5476 if (inst) {
5477 type_argv = g_new0 (MonoType*, inst->type_argc);
5478 for (i = 0; i < inst->type_argc; ++i) {
5479 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)
5480 type_argv [i] = mono_get_object_type ();
5481 else
5482 type_argv [i] = inst->type_argv [i];
5485 shared_context.class_inst = mono_metadata_get_generic_inst (inst->type_argc, type_argv);
5486 g_free (type_argv);
5489 inst = context->method_inst;
5490 if (inst) {
5491 type_argv = g_new0 (MonoType*, inst->type_argc);
5492 for (i = 0; i < inst->type_argc; ++i) {
5493 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)
5494 type_argv [i] = mono_get_object_type ();
5495 else
5496 type_argv [i] = inst->type_argv [i];
5499 shared_context.method_inst = mono_metadata_get_generic_inst (inst->type_argc, type_argv);
5500 g_free (type_argv);
5503 if (method->is_generic || mono_class_is_gtd (method->klass))
5504 declaring_method = method;
5505 else
5506 declaring_method = mono_method_get_declaring_generic_method (method);
5508 method = mono_class_inflate_generic_method_checked (declaring_method, &shared_context, error);
5509 g_assert (mono_error_ok (error)); /* FIXME don't swallow the error */
5513 * If the method is fully sharable, it was already added in place of its
5514 * generic definition.
5516 if (mono_method_is_generic_sharable_full (method, FALSE, FALSE, FALSE))
5517 continue;
5520 * FIXME: Partially shared methods are not shared here, so we end up with
5521 * many identical methods.
5523 add_extra_method (acfg, method);
5526 for (i = 0; i < acfg->image->tables [MONO_TABLE_TYPESPEC].rows; ++i) {
5527 ERROR_DECL (error);
5528 MonoClass *klass;
5530 token = MONO_TOKEN_TYPE_SPEC | (i + 1);
5532 klass = mono_class_get_checked (acfg->image, token, error);
5533 if (!klass || m_class_get_rank (klass)) {
5534 mono_error_cleanup (error);
5535 continue;
5538 add_generic_class (acfg, klass, FALSE, "typespec");
5541 /* Add types of args/locals */
5542 for (i = 0; i < acfg->methods->len; ++i) {
5543 method = (MonoMethod *)g_ptr_array_index (acfg->methods, i);
5544 add_types_from_method_header (acfg, method);
5547 if (acfg->image == mono_defaults.corlib) {
5548 MonoClass *klass;
5549 MonoType *insts [256];
5550 int ninsts = 0;
5552 MonoType *byte_type = m_class_get_byval_arg (mono_defaults.byte_class);
5553 MonoType *sbyte_type = m_class_get_byval_arg (mono_defaults.sbyte_class);
5554 MonoType *int16_type = m_class_get_byval_arg (mono_defaults.int16_class);
5555 MonoType *uint16_type = m_class_get_byval_arg (mono_defaults.uint16_class);
5556 MonoType *int32_type = mono_get_int32_type ();
5557 MonoType *uint32_type = m_class_get_byval_arg (mono_defaults.uint32_class);
5558 MonoType *int64_type = m_class_get_byval_arg (mono_defaults.int64_class);
5559 MonoType *uint64_type = m_class_get_byval_arg (mono_defaults.uint64_class);
5560 MonoType *object_type = mono_get_object_type ();
5562 insts [ninsts ++] = byte_type;
5563 insts [ninsts ++] = sbyte_type;
5564 insts [ninsts ++] = int16_type;
5565 insts [ninsts ++] = uint16_type;
5566 insts [ninsts ++] = int32_type;
5567 insts [ninsts ++] = uint32_type;
5568 insts [ninsts ++] = int64_type;
5569 insts [ninsts ++] = uint64_type;
5570 insts [ninsts ++] = m_class_get_byval_arg (mono_defaults.single_class);
5571 insts [ninsts ++] = m_class_get_byval_arg (mono_defaults.double_class);
5572 insts [ninsts ++] = m_class_get_byval_arg (mono_defaults.char_class);
5573 insts [ninsts ++] = m_class_get_byval_arg (mono_defaults.boolean_class);
5575 /* Add GenericComparer<T> instances for primitive types for Enum.ToString () */
5576 klass = mono_class_try_load_from_name (acfg->image, "System.Collections.Generic", "GenericComparer`1");
5577 if (klass)
5578 add_instances_of (acfg, klass, insts, ninsts, TRUE);
5579 klass = mono_class_try_load_from_name (acfg->image, "System.Collections.Generic", "GenericEqualityComparer`1");
5580 if (klass)
5581 add_instances_of (acfg, klass, insts, ninsts, TRUE);
5583 /* Add instances of EnumEqualityComparer which are created by EqualityComparer<T> for enums */
5585 MonoClass *enum_comparer;
5586 MonoType *insts [16];
5587 int ninsts;
5589 ninsts = 0;
5590 insts [ninsts ++] = int32_type;
5591 insts [ninsts ++] = uint32_type;
5592 insts [ninsts ++] = uint16_type;
5593 insts [ninsts ++] = byte_type;
5594 enum_comparer = mono_class_load_from_name (mono_defaults.corlib, "System.Collections.Generic", "EnumEqualityComparer`1");
5595 add_instances_of (acfg, enum_comparer, insts, ninsts, FALSE);
5597 ninsts = 0;
5598 insts [ninsts ++] = int16_type;
5599 enum_comparer = mono_class_load_from_name (mono_defaults.corlib, "System.Collections.Generic", "ShortEnumEqualityComparer`1");
5600 add_instances_of (acfg, enum_comparer, insts, ninsts, FALSE);
5602 ninsts = 0;
5603 insts [ninsts ++] = sbyte_type;
5604 enum_comparer = mono_class_load_from_name (mono_defaults.corlib, "System.Collections.Generic", "SByteEnumEqualityComparer`1");
5605 add_instances_of (acfg, enum_comparer, insts, ninsts, FALSE);
5607 enum_comparer = mono_class_load_from_name (mono_defaults.corlib, "System.Collections.Generic", "LongEnumEqualityComparer`1");
5608 ninsts = 0;
5609 insts [ninsts ++] = int64_type;
5610 insts [ninsts ++] = uint64_type;
5611 add_instances_of (acfg, enum_comparer, insts, ninsts, FALSE);
5614 /* Add instances of the array generic interfaces for primitive types */
5615 /* This will add instances of the InternalArray_ helper methods in Array too */
5616 klass = mono_class_try_load_from_name (acfg->image, "System.Collections.Generic", "ICollection`1");
5617 if (klass)
5618 add_instances_of (acfg, klass, insts, ninsts, TRUE);
5620 klass = mono_class_try_load_from_name (acfg->image, "System.Collections.Generic", "IList`1");
5621 if (klass)
5622 add_instances_of (acfg, klass, insts, ninsts, TRUE);
5624 klass = mono_class_try_load_from_name (acfg->image, "System.Collections.Generic", "IEnumerable`1");
5625 if (klass)
5626 add_instances_of (acfg, klass, insts, ninsts, TRUE);
5629 * Add a managed-to-native wrapper of Array.GetGenericValueImpl<object>, which is
5630 * used for all instances of GetGenericValueImpl by the AOT runtime.
5633 ERROR_DECL (error);
5634 MonoGenericContext ctx;
5635 MonoType *args [16];
5636 MonoMethod *get_method;
5637 MonoClass *array_klass = m_class_get_parent (mono_class_create_array (mono_defaults.object_class, 1));
5639 get_method = mono_class_get_method_from_name_checked (array_klass, "GetGenericValueImpl", 2, 0, error);
5640 mono_error_assert_ok (error);
5642 if (get_method) {
5643 memset (&ctx, 0, sizeof (ctx));
5644 args [0] = object_type;
5645 ctx.method_inst = mono_metadata_get_generic_inst (1, args);
5646 add_extra_method (acfg, mono_marshal_get_native_wrapper (mono_class_inflate_generic_method_checked (get_method, &ctx, error), TRUE, TRUE));
5647 mono_error_assert_ok (error); /* FIXME don't swallow the error */
5651 /* Same for CompareExchange<T>/Exchange<T> */
5653 MonoGenericContext ctx;
5654 MonoType *args [16];
5655 MonoMethod *m;
5656 MonoClass *interlocked_klass = mono_class_load_from_name (mono_defaults.corlib, "System.Threading", "Interlocked");
5657 gpointer iter = NULL;
5659 while ((m = mono_class_get_methods (interlocked_klass, &iter))) {
5660 if ((!strcmp (m->name, "CompareExchange") || !strcmp (m->name, "Exchange")) && m->is_generic) {
5661 ERROR_DECL (error);
5662 memset (&ctx, 0, sizeof (ctx));
5663 args [0] = object_type;
5664 ctx.method_inst = mono_metadata_get_generic_inst (1, args);
5665 add_extra_method (acfg, mono_marshal_get_native_wrapper (mono_class_inflate_generic_method_checked (m, &ctx, error), TRUE, TRUE));
5666 g_assert (mono_error_ok (error)); /* FIXME don't swallow the error */
5671 /* Same for Volatile.Read/Write<T> */
5673 MonoGenericContext ctx;
5674 MonoType *args [16];
5675 MonoMethod *m;
5676 MonoClass *volatile_klass = mono_class_try_load_from_name (mono_defaults.corlib, "System.Threading", "Volatile");
5677 gpointer iter = NULL;
5679 if (volatile_klass) {
5680 while ((m = mono_class_get_methods (volatile_klass, &iter))) {
5681 if ((!strcmp (m->name, "Read") || !strcmp (m->name, "Write")) && m->is_generic) {
5682 ERROR_DECL (error);
5683 memset (&ctx, 0, sizeof (ctx));
5684 args [0] = object_type;
5685 ctx.method_inst = mono_metadata_get_generic_inst (1, args);
5686 add_extra_method (acfg, mono_marshal_get_native_wrapper (mono_class_inflate_generic_method_checked (m, &ctx, error), TRUE, TRUE));
5687 g_assert (mono_error_ok (error)); /* FIXME don't swallow the error */
5693 /* object[] accessor wrappers. */
5694 for (i = 1; i < 4; ++i) {
5695 MonoClass *obj_array_class = mono_class_create_array (mono_defaults.object_class, i);
5696 MonoMethod *m;
5698 m = get_method_nofail (obj_array_class, "Get", i, 0);
5699 g_assert (m);
5701 m = mono_marshal_get_array_accessor_wrapper (m);
5702 add_extra_method (acfg, m);
5704 m = get_method_nofail (obj_array_class, "Address", i, 0);
5705 g_assert (m);
5707 m = mono_marshal_get_array_accessor_wrapper (m);
5708 add_extra_method (acfg, m);
5710 m = get_method_nofail (obj_array_class, "Set", i + 1, 0);
5711 g_assert (m);
5713 m = mono_marshal_get_array_accessor_wrapper (m);
5714 add_extra_method (acfg, m);
5719 static char *
5720 decode_direct_icall_symbol_name_attribute (MonoMethod *method)
5722 ERROR_DECL (error);
5724 int j = 0;
5725 char *symbol_name = NULL;
5727 MonoCustomAttrInfo *cattr = mono_custom_attrs_from_method_checked (method, error);
5728 if (mono_error_ok(error) && cattr) {
5729 for (j = 0; j < cattr->num_attrs; j++)
5730 if (cattr->attrs [j].ctor && !strcmp (m_class_get_name (cattr->attrs [j].ctor->klass), "MonoDirectICallSymbolNameAttribute"))
5731 break;
5733 if (j < cattr->num_attrs) {
5734 MonoCustomAttrEntry *e = &cattr->attrs [j];
5735 MonoMethodSignature *sig = mono_method_signature_internal (e->ctor);
5736 if (e->data && sig && sig->param_count == 1 && sig->params [0]->type == MONO_TYPE_STRING) {
5738 * Decode the cattr manually since we can't create objects
5739 * during aot compilation.
5742 /* Skip prolog */
5743 const char *p = ((const char*)e->data) + 2;
5744 int slen = mono_metadata_decode_value (p, &p);
5746 symbol_name = (char *)g_memdup (p, slen + 1);
5747 if (symbol_name)
5748 symbol_name [slen] = 0;
5753 return symbol_name;
5755 static const char*
5756 lookup_external_icall_symbol_name_aot (MonoMethod *method)
5758 g_assert (method_to_external_icall_symbol_name);
5760 gpointer key, value;
5761 if (g_hash_table_lookup_extended (method_to_external_icall_symbol_name, method, &key, &value))
5762 return (const char*)value;
5764 char *symbol_name = decode_direct_icall_symbol_name_attribute (method);
5765 g_hash_table_insert (method_to_external_icall_symbol_name, method, symbol_name);
5767 return symbol_name;
5770 static const char*
5771 lookup_icall_symbol_name_aot (MonoMethod *method)
5773 const char * symbol_name = mono_lookup_icall_symbol (method);
5774 if (!symbol_name)
5775 symbol_name = lookup_external_icall_symbol_name_aot (method);
5777 return symbol_name;
5780 gboolean
5781 mono_aot_direct_icalls_enabled_for_method (MonoCompile *cfg, MonoMethod *method)
5783 gboolean enable_icall = FALSE;
5784 if (cfg->compile_aot)
5785 enable_icall = lookup_external_icall_symbol_name_aot (method) ? TRUE : FALSE;
5786 else
5787 enable_icall = FALSE;
5789 return enable_icall;
5793 * is_direct_callable:
5795 * Return whenever the method identified by JI is directly callable without
5796 * going through the PLT.
5798 static gboolean
5799 is_direct_callable (MonoAotCompile *acfg, MonoMethod *method, MonoJumpInfo *patch_info)
5801 if ((patch_info->type == MONO_PATCH_INFO_METHOD) && (m_class_get_image (patch_info->data.method->klass) == acfg->image)) {
5802 MonoCompile *callee_cfg = (MonoCompile *)g_hash_table_lookup (acfg->method_to_cfg, patch_info->data.method);
5803 if (callee_cfg) {
5804 gboolean direct_callable = TRUE;
5806 if (direct_callable && (acfg->aot_opts.dedup || acfg->aot_opts.dedup_include) && mono_aot_can_dedup (patch_info->data.method))
5807 direct_callable = FALSE;
5809 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)))
5810 direct_callable = FALSE;
5812 if (direct_callable && !strcmp (callee_cfg->method->name, ".cctor"))
5813 direct_callable = FALSE;
5816 // FIXME: Support inflated methods, it asserts in mono_aot_init_gshared_method_this () because the method is not in
5817 // amodule->extra_methods.
5819 if (direct_callable && callee_cfg->method->is_inflated)
5820 direct_callable = FALSE;
5822 if (direct_callable && (callee_cfg->method->iflags & METHOD_IMPL_ATTRIBUTE_SYNCHRONIZED) && (!method || method->wrapper_type != MONO_WRAPPER_SYNCHRONIZED))
5823 // FIXME: Maybe call the wrapper directly ?
5824 direct_callable = FALSE;
5826 if (direct_callable && (acfg->aot_opts.soft_debug || acfg->aot_opts.no_direct_calls)) {
5827 /* Disable this so all calls go through load_method (), see the
5828 * mini_get_debug_options ()->load_aot_jit_info_eagerly = TRUE; line in
5829 * mono_debugger_agent_init ().
5831 direct_callable = FALSE;
5834 if (direct_callable && (callee_cfg->method->wrapper_type == MONO_WRAPPER_ALLOC))
5835 /* sgen does some initialization when the allocator method is created */
5836 direct_callable = FALSE;
5837 if (direct_callable && (callee_cfg->method->wrapper_type == MONO_WRAPPER_WRITE_BARRIER))
5838 /* we don't know at compile time whether sgen is concurrent or not */
5839 direct_callable = FALSE;
5841 if (direct_callable)
5842 return TRUE;
5844 } else if ((patch_info->type == MONO_PATCH_INFO_ICALL_ADDR_CALL && patch_info->data.method->flags & METHOD_ATTRIBUTE_PINVOKE_IMPL)) {
5845 if (acfg->aot_opts.direct_pinvoke)
5846 return TRUE;
5847 } else if (patch_info->type == MONO_PATCH_INFO_ICALL_ADDR_CALL) {
5848 if (acfg->aot_opts.direct_icalls)
5849 return TRUE;
5850 return FALSE;
5853 return FALSE;
5856 #ifdef MONO_ARCH_AOT_SUPPORTED
5857 static const char *
5858 get_pinvoke_import (MonoAotCompile *acfg, MonoMethod *method)
5860 MonoImage *image = m_class_get_image (method->klass);
5861 MonoMethodPInvoke *piinfo = (MonoMethodPInvoke *) method;
5862 MonoTableInfo *tables = image->tables;
5863 MonoTableInfo *im = &tables [MONO_TABLE_IMPLMAP];
5864 MonoTableInfo *mr = &tables [MONO_TABLE_MODULEREF];
5865 guint32 im_cols [MONO_IMPLMAP_SIZE];
5866 char *import;
5868 import = (char *)g_hash_table_lookup (acfg->method_to_pinvoke_import, method);
5869 if (import != NULL)
5870 return import;
5872 if (!piinfo->implmap_idx || piinfo->implmap_idx > im->rows)
5873 return NULL;
5875 mono_metadata_decode_row (im, piinfo->implmap_idx - 1, im_cols, MONO_IMPLMAP_SIZE);
5877 if (!im_cols [MONO_IMPLMAP_SCOPE] || im_cols [MONO_IMPLMAP_SCOPE] > mr->rows)
5878 return NULL;
5880 import = g_strdup_printf ("%s", mono_metadata_string_heap (image, im_cols [MONO_IMPLMAP_NAME]));
5882 g_hash_table_insert (acfg->method_to_pinvoke_import, method, import);
5884 return import;
5886 #else
5887 static const char *
5888 get_pinvoke_import (MonoAotCompile *acfg, MonoMethod *method)
5890 return NULL;
5892 #endif
5894 static gint
5895 compare_lne (MonoDebugLineNumberEntry *a, MonoDebugLineNumberEntry *b)
5897 if (a->native_offset == b->native_offset)
5898 return a->il_offset - b->il_offset;
5899 else
5900 return a->native_offset - b->native_offset;
5904 * compute_line_numbers:
5906 * Returns a sparse array of size CODE_SIZE containing MonoDebugSourceLocation* entries for the native offsets which have a corresponding line number
5907 * entry.
5909 static MonoDebugSourceLocation**
5910 compute_line_numbers (MonoMethod *method, int code_size, MonoDebugMethodJitInfo *debug_info)
5912 MonoDebugMethodInfo *minfo;
5913 MonoDebugLineNumberEntry *ln_array;
5914 MonoDebugSourceLocation *loc;
5915 int i, prev_line, prev_il_offset;
5916 int *native_to_il_offset = NULL;
5917 MonoDebugSourceLocation **res;
5918 gboolean first;
5920 minfo = mono_debug_lookup_method (method);
5921 if (!minfo)
5922 return NULL;
5923 // FIXME: This seems to happen when two methods have the same cfg->method_to_register
5924 if (debug_info->code_size != code_size)
5925 return NULL;
5927 g_assert (code_size);
5929 /* Compute the native->IL offset mapping */
5931 ln_array = g_new0 (MonoDebugLineNumberEntry, debug_info->num_line_numbers);
5932 memcpy (ln_array, debug_info->line_numbers, debug_info->num_line_numbers * sizeof (MonoDebugLineNumberEntry));
5934 qsort (ln_array, debug_info->num_line_numbers, sizeof (MonoDebugLineNumberEntry), (int (*)(const void *, const void *))compare_lne);
5936 native_to_il_offset = g_new0 (int, code_size + 1);
5938 for (i = 0; i < debug_info->num_line_numbers; ++i) {
5939 int j;
5940 MonoDebugLineNumberEntry *lne = &ln_array [i];
5942 if (i == 0) {
5943 for (j = 0; j < lne->native_offset; ++j)
5944 native_to_il_offset [j] = -1;
5947 if (i < debug_info->num_line_numbers - 1) {
5948 MonoDebugLineNumberEntry *lne_next = &ln_array [i + 1];
5950 for (j = lne->native_offset; j < lne_next->native_offset; ++j)
5951 native_to_il_offset [j] = lne->il_offset;
5952 } else {
5953 for (j = lne->native_offset; j < code_size; ++j)
5954 native_to_il_offset [j] = lne->il_offset;
5957 g_free (ln_array);
5959 /* Compute the native->line number mapping */
5960 res = g_new0 (MonoDebugSourceLocation*, code_size);
5961 prev_il_offset = -1;
5962 prev_line = -1;
5963 first = TRUE;
5964 for (i = 0; i < code_size; ++i) {
5965 int il_offset = native_to_il_offset [i];
5967 if (il_offset == -1 || il_offset == prev_il_offset)
5968 continue;
5969 prev_il_offset = il_offset;
5970 loc = mono_debug_method_lookup_location (minfo, il_offset);
5971 if (!(loc && loc->source_file))
5972 continue;
5973 if (loc->row == prev_line) {
5974 mono_debug_free_source_location (loc);
5975 continue;
5977 prev_line = loc->row;
5978 //printf ("D: %s:%d il=%x native=%x\n", loc->source_file, loc->row, il_offset, i);
5979 if (first)
5980 /* This will cover the prolog too */
5981 res [0] = loc;
5982 else
5983 res [i] = loc;
5984 first = FALSE;
5986 return res;
5989 static int
5990 get_file_index (MonoAotCompile *acfg, const char *source_file)
5992 int findex;
5994 // FIXME: Free these
5995 if (!acfg->dwarf_ln_filenames)
5996 acfg->dwarf_ln_filenames = g_hash_table_new (g_str_hash, g_str_equal);
5997 findex = GPOINTER_TO_INT (g_hash_table_lookup (acfg->dwarf_ln_filenames, source_file));
5998 if (!findex) {
5999 findex = g_hash_table_size (acfg->dwarf_ln_filenames) + 1;
6000 g_hash_table_insert (acfg->dwarf_ln_filenames, g_strdup (source_file), GINT_TO_POINTER (findex));
6001 emit_unset_mode (acfg);
6002 fprintf (acfg->fp, ".file %d \"%s\"\n", findex, mono_dwarf_escape_path (source_file));
6004 return findex;
6007 #ifdef TARGET_ARM64
6008 #define INST_LEN 4
6009 #else
6010 #define INST_LEN 1
6011 #endif
6014 * emit_and_reloc_code:
6016 * Emit the native code in CODE, handling relocations along the way. If GOT_ONLY
6017 * is true, calls are made through the GOT too. This is used for emitting trampolines
6018 * in full-aot mode, since calls made from trampolines couldn't go through the PLT,
6019 * since trampolines are needed to make PLT work.
6021 static void
6022 emit_and_reloc_code (MonoAotCompile *acfg, MonoMethod *method, guint8 *code, guint32 code_len, MonoJumpInfo *relocs, gboolean got_only, MonoDebugMethodJitInfo *debug_info)
6024 int i, pindex, start_index;
6025 GPtrArray *patches;
6026 MonoJumpInfo *patch_info;
6027 MonoDebugSourceLocation **locs = NULL;
6028 gboolean skip, prologue_end = FALSE;
6029 #ifdef MONO_ARCH_AOT_SUPPORTED
6030 gboolean direct_call, external_call;
6031 guint32 got_slot;
6032 const char *direct_call_target = 0;
6033 const char *direct_pinvoke;
6034 #endif
6036 if (acfg->gas_line_numbers && method && debug_info) {
6037 locs = compute_line_numbers (method, code_len, debug_info);
6038 if (!locs) {
6039 int findex = get_file_index (acfg, "<unknown>");
6040 emit_unset_mode (acfg);
6041 fprintf (acfg->fp, ".loc %d %d 0\n", findex, 1);
6045 /* Collect and sort relocations */
6046 patches = g_ptr_array_new ();
6047 for (patch_info = relocs; patch_info; patch_info = patch_info->next)
6048 g_ptr_array_add (patches, patch_info);
6049 g_ptr_array_sort (patches, compare_patches);
6051 start_index = 0;
6052 for (i = 0; i < code_len; i += INST_LEN) {
6053 patch_info = NULL;
6054 for (pindex = start_index; pindex < patches->len; ++pindex) {
6055 patch_info = (MonoJumpInfo *)g_ptr_array_index (patches, pindex);
6056 if (patch_info->ip.i >= i)
6057 break;
6060 if (locs && locs [i]) {
6061 MonoDebugSourceLocation *loc = locs [i];
6062 int findex;
6063 const char *options;
6065 findex = get_file_index (acfg, loc->source_file);
6066 emit_unset_mode (acfg);
6067 if (!prologue_end)
6068 options = " prologue_end";
6069 else
6070 options = "";
6071 prologue_end = TRUE;
6072 fprintf (acfg->fp, ".loc %d %d 0%s\n", findex, loc->row, options);
6073 mono_debug_free_source_location (loc);
6076 skip = FALSE;
6077 #ifdef MONO_ARCH_AOT_SUPPORTED
6078 if (patch_info && (patch_info->ip.i == i) && (pindex < patches->len)) {
6079 start_index = pindex;
6081 switch (patch_info->type) {
6082 case MONO_PATCH_INFO_NONE:
6083 break;
6084 case MONO_PATCH_INFO_GOT_OFFSET: {
6085 int code_size;
6087 arch_emit_got_offset (acfg, code + i, &code_size);
6088 i += code_size - INST_LEN;
6089 skip = TRUE;
6090 patch_info->type = MONO_PATCH_INFO_NONE;
6091 break;
6093 case MONO_PATCH_INFO_OBJC_SELECTOR_REF: {
6094 int code_size, index;
6095 char *selector = (char *)patch_info->data.target;
6097 if (!acfg->objc_selector_to_index)
6098 acfg->objc_selector_to_index = g_hash_table_new (g_str_hash, g_str_equal);
6099 if (!acfg->objc_selectors)
6100 acfg->objc_selectors = g_ptr_array_new ();
6101 index = GPOINTER_TO_UINT (g_hash_table_lookup (acfg->objc_selector_to_index, selector));
6102 if (index)
6103 index --;
6104 else {
6105 index = acfg->objc_selector_index;
6106 g_ptr_array_add (acfg->objc_selectors, (void*)patch_info->data.target);
6107 g_hash_table_insert (acfg->objc_selector_to_index, selector, GUINT_TO_POINTER (index + 1));
6108 acfg->objc_selector_index ++;
6111 arch_emit_objc_selector_ref (acfg, code + i, index, &code_size);
6112 i += code_size - INST_LEN;
6113 skip = TRUE;
6114 patch_info->type = MONO_PATCH_INFO_NONE;
6115 break;
6117 default: {
6119 * If this patch is a call, try emitting a direct call instead of
6120 * through a PLT entry. This is possible if the called method is in
6121 * the same assembly and requires no initialization.
6123 direct_call = FALSE;
6124 external_call = FALSE;
6125 if ((patch_info->type == MONO_PATCH_INFO_METHOD) && (m_class_get_image (patch_info->data.method->klass) == acfg->image)) {
6126 if (!got_only && is_direct_callable (acfg, method, patch_info)) {
6127 MonoCompile *callee_cfg = (MonoCompile *)g_hash_table_lookup (acfg->method_to_cfg, patch_info->data.method);
6129 // Don't compile inflated methods if we're doing dedup
6130 if (acfg->aot_opts.dedup && !mono_aot_can_dedup (patch_info->data.method)) {
6131 char *name = mono_aot_get_mangled_method_name (patch_info->data.method);
6132 mono_trace (G_LOG_LEVEL_DEBUG, MONO_TRACE_AOT, "DIRECT CALL: %s by %s", name, method ? mono_method_full_name (method, TRUE) : "");
6133 g_free (name);
6135 direct_call = TRUE;
6136 direct_call_target = callee_cfg->asm_symbol;
6137 patch_info->type = MONO_PATCH_INFO_NONE;
6138 acfg->stats.direct_calls ++;
6142 acfg->stats.all_calls ++;
6143 } else if (patch_info->type == MONO_PATCH_INFO_ICALL_ADDR_CALL) {
6144 if (!got_only && is_direct_callable (acfg, method, patch_info)) {
6145 if (!(patch_info->data.method->flags & METHOD_ATTRIBUTE_PINVOKE_IMPL))
6146 direct_pinvoke = lookup_icall_symbol_name_aot (patch_info->data.method);
6147 else
6148 direct_pinvoke = get_pinvoke_import (acfg, patch_info->data.method);
6149 if (direct_pinvoke) {
6150 direct_call = TRUE;
6151 g_assert (strlen (direct_pinvoke) < 1000);
6152 direct_call_target = g_strdup_printf ("%s%s", acfg->user_symbol_prefix, direct_pinvoke);
6155 } else if (patch_info->type == MONO_PATCH_INFO_JIT_ICALL_ADDR) {
6156 const char *sym = mono_find_jit_icall_info (patch_info->data.jit_icall_id)->c_symbol;
6157 if (!got_only && sym && acfg->aot_opts.direct_icalls) {
6158 /* Call to a C function implementing a jit icall */
6159 direct_call = TRUE;
6160 external_call = TRUE;
6161 g_assert (strlen (sym) < 1000);
6162 direct_call_target = g_strdup_printf ("%s%s", acfg->user_symbol_prefix, sym);
6164 } else if (patch_info->type == MONO_PATCH_INFO_JIT_ICALL_ID) {
6165 MonoJitICallInfo * const info = mono_find_jit_icall_info (patch_info->data.jit_icall_id);
6166 const char * const sym = info->c_symbol;
6167 if (!got_only && sym && acfg->aot_opts.direct_icalls && info->func == info->wrapper) {
6168 /* Call to a jit icall without a wrapper */
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);
6175 if (direct_call) {
6176 patch_info->type = MONO_PATCH_INFO_NONE;
6177 acfg->stats.direct_calls ++;
6180 if (!got_only && !direct_call) {
6181 MonoPltEntry *plt_entry = get_plt_entry (acfg, patch_info);
6182 if (plt_entry) {
6183 /* This patch has a PLT entry, so we must emit a call to the PLT entry */
6184 direct_call = TRUE;
6185 direct_call_target = plt_entry->symbol;
6187 /* Nullify the patch */
6188 patch_info->type = MONO_PATCH_INFO_NONE;
6189 plt_entry->jit_used = TRUE;
6193 if (direct_call) {
6194 int call_size;
6196 arch_emit_direct_call (acfg, direct_call_target, external_call, FALSE, patch_info, &call_size);
6197 i += call_size - INST_LEN;
6198 } else {
6199 int code_size;
6201 got_slot = get_got_offset (acfg, FALSE, patch_info);
6203 arch_emit_got_access (acfg, acfg->got_symbol, code + i, got_slot, &code_size);
6204 i += code_size - INST_LEN;
6206 skip = TRUE;
6210 #endif /* MONO_ARCH_AOT_SUPPORTED */
6212 if (!skip) {
6213 /* Find next patch */
6214 patch_info = NULL;
6215 for (pindex = start_index; pindex < patches->len; ++pindex) {
6216 patch_info = (MonoJumpInfo *)g_ptr_array_index (patches, pindex);
6217 if (patch_info->ip.i >= i)
6218 break;
6221 /* Try to emit multiple bytes at once */
6222 if (pindex < patches->len && patch_info->ip.i > i) {
6223 int limit;
6225 for (limit = i + INST_LEN; limit < patch_info->ip.i; limit += INST_LEN) {
6226 if (locs && locs [limit])
6227 break;
6230 emit_code_bytes (acfg, code + i, limit - i);
6231 i = limit - INST_LEN;
6232 } else {
6233 emit_code_bytes (acfg, code + i, INST_LEN);
6238 g_ptr_array_free (patches, TRUE);
6239 g_free (locs);
6243 * sanitize_symbol:
6245 * Return a modified version of S which only includes characters permissible in symbols.
6247 static char*
6248 sanitize_symbol (MonoAotCompile *acfg, char *s)
6250 gboolean process = FALSE;
6251 int i, len;
6252 GString *gs;
6253 char *res;
6255 if (!s)
6256 return s;
6258 len = strlen (s);
6259 for (i = 0; i < len; ++i)
6260 if (!(s [i] <= 0x7f && (isalnum (s [i]) || s [i] == '_')))
6261 process = TRUE;
6262 if (!process)
6263 return s;
6265 gs = g_string_sized_new (len);
6266 for (i = 0; i < len; ++i) {
6267 guint8 c = s [i];
6268 if (c <= 0x7f && (isalnum (c) || c == '_')) {
6269 g_string_append_c (gs, c);
6270 } else if (c > 0x7f) {
6271 /* multi-byte utf8 */
6272 g_string_append_printf (gs, "_0x%x", c);
6273 i ++;
6274 c = s [i];
6275 while (c >> 6 == 0x2) {
6276 g_string_append_printf (gs, "%x", c);
6277 i ++;
6278 c = s [i];
6280 g_string_append_printf (gs, "_");
6281 i --;
6282 } else {
6283 g_string_append_c (gs, '_');
6287 res = mono_mempool_strdup (acfg->mempool, gs->str);
6288 g_string_free (gs, TRUE);
6289 return res;
6292 static char*
6293 get_debug_sym (MonoMethod *method, const char *prefix, GHashTable *cache)
6295 char *name1, *name2, *cached;
6296 int i, j, len, count;
6297 MonoMethod *cached_method;
6299 name1 = mono_method_full_name (method, TRUE);
6301 #ifdef TARGET_MACH
6302 // This is so that we don't accidentally create a local symbol (which starts with 'L')
6303 if ((!prefix || !*prefix) && name1 [0] == 'L')
6304 prefix = "_";
6305 #endif
6307 #if defined(TARGET_WIN32) && defined(TARGET_X86)
6308 char adjustedPrefix [MAX_SYMBOL_SIZE];
6309 prefix = mangle_symbol (prefix, adjustedPrefix, G_N_ELEMENTS (adjustedPrefix));
6310 #endif
6312 len = strlen (name1);
6313 name2 = (char *) g_malloc (strlen (prefix) + len + 16);
6314 memcpy (name2, prefix, strlen (prefix));
6315 j = strlen (prefix);
6316 for (i = 0; i < len; ++i) {
6317 if (i == 0 && name1 [0] >= '0' && name1 [0] <= '9') {
6318 name2 [j ++] = '_';
6319 } else if (isalnum (name1 [i])) {
6320 name2 [j ++] = name1 [i];
6321 } else if (name1 [i] == ' ' && name1 [i + 1] == '(' && name1 [i + 2] == ')') {
6322 i += 2;
6323 } else if (name1 [i] == ',' && name1 [i + 1] == ' ') {
6324 name2 [j ++] = '_';
6325 i++;
6326 } else if (name1 [i] == '(' || name1 [i] == ')' || name1 [i] == '>') {
6327 } else
6328 name2 [j ++] = '_';
6330 name2 [j] = '\0';
6332 g_free (name1);
6334 count = 0;
6335 while (TRUE) {
6336 cached_method = (MonoMethod *)g_hash_table_lookup (cache, name2);
6337 if (!(cached_method && cached_method != method))
6338 break;
6339 sprintf (name2 + j, "_%d", count);
6340 count ++;
6343 cached = g_strdup (name2);
6344 g_hash_table_insert (cache, cached, method);
6346 return name2;
6349 static void
6350 emit_method_code (MonoAotCompile *acfg, MonoCompile *cfg)
6352 MonoMethod *method;
6353 int method_index;
6354 guint8 *code;
6355 char *debug_sym = NULL;
6356 char *symbol = NULL;
6357 int func_alignment = AOT_FUNC_ALIGNMENT;
6358 char *export_name;
6360 g_assert (!ignore_cfg (cfg));
6362 method = cfg->orig_method;
6363 code = cfg->native_code;
6365 method_index = get_method_index (acfg, method);
6366 symbol = g_strdup_printf ("%sme_%x", acfg->temp_prefix, method_index);
6368 /* Make the labels local */
6369 emit_section_change (acfg, ".text", 0);
6370 emit_alignment_code (acfg, func_alignment);
6372 if (acfg->global_symbols && acfg->need_no_dead_strip)
6373 fprintf (acfg->fp, " .no_dead_strip %s\n", cfg->asm_symbol);
6375 emit_label (acfg, cfg->asm_symbol);
6377 if (acfg->aot_opts.write_symbols && !acfg->global_symbols && !acfg->llvm) {
6379 * Write a C style symbol for every method, this has two uses:
6380 * - it works on platforms where the dwarf debugging info is not
6381 * yet supported.
6382 * - it allows the setting of breakpoints of aot-ed methods.
6385 // Comment out to force dedup to link these symbols and forbid compiling
6386 // in duplicated code. This is an "assert when linking if broken" trick.
6387 /*if (mono_aot_can_dedup (method) && (acfg->aot_opts.dedup || acfg->aot_opts.dedup_include))*/
6388 /*debug_sym = mono_aot_get_mangled_method_name (method);*/
6389 /*else*/
6390 debug_sym = get_debug_sym (method, "", acfg->method_label_hash);
6392 cfg->asm_debug_symbol = g_strdup (debug_sym);
6394 if (acfg->need_no_dead_strip)
6395 fprintf (acfg->fp, " .no_dead_strip %s\n", debug_sym);
6397 // Comment out to force dedup to link these symbols and forbid compiling
6398 // in duplicated code. This is an "assert when linking if broken" trick.
6399 /*if (mono_aot_can_dedup (method) && (acfg->aot_opts.dedup || acfg->aot_opts.dedup_include))*/
6400 /*emit_global_inner (acfg, debug_sym, TRUE);*/
6401 /*else*/
6402 emit_local_symbol (acfg, debug_sym, symbol, TRUE);
6404 emit_label (acfg, debug_sym);
6407 export_name = (char *)g_hash_table_lookup (acfg->export_names, method);
6408 if (export_name) {
6409 /* Emit a global symbol for the method */
6410 emit_global_inner (acfg, export_name, TRUE);
6411 emit_label (acfg, export_name);
6414 if (cfg->verbose_level > 0 && !ignore_cfg (cfg))
6415 g_print ("Method %s emitted as %s\n", mono_method_get_full_name (method), cfg->asm_symbol);
6417 acfg->stats.code_size += cfg->code_len;
6419 acfg->cfgs [method_index]->got_offset = acfg->got_offset;
6421 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 ()));
6423 emit_line (acfg);
6425 if (acfg->aot_opts.write_symbols) {
6426 if (debug_sym)
6427 emit_symbol_size (acfg, debug_sym, ".");
6428 else
6429 emit_symbol_size (acfg, cfg->asm_symbol, ".");
6430 g_free (debug_sym);
6433 emit_label (acfg, symbol);
6435 arch_emit_unwind_info_sections (acfg, cfg->asm_symbol, symbol, cfg->unwind_ops);
6437 g_free (symbol);
6441 * encode_patch:
6443 * Encode PATCH_INFO into its disk representation.
6445 static void
6446 encode_patch (MonoAotCompile *acfg, MonoJumpInfo *patch_info, guint8 *buf, guint8 **endbuf)
6448 guint8 *p = buf;
6450 switch (patch_info->type) {
6451 case MONO_PATCH_INFO_NONE:
6452 break;
6453 case MONO_PATCH_INFO_IMAGE:
6454 encode_value (get_image_index (acfg, patch_info->data.image), p, &p);
6455 break;
6456 case MONO_PATCH_INFO_MSCORLIB_GOT_ADDR:
6457 case MONO_PATCH_INFO_GC_CARD_TABLE_ADDR:
6458 case MONO_PATCH_INFO_GC_NURSERY_START:
6459 case MONO_PATCH_INFO_GC_NURSERY_BITS:
6460 break;
6461 case MONO_PATCH_INFO_SWITCH: {
6462 gpointer *table = (gpointer *)patch_info->data.table->table;
6463 int k;
6465 encode_value (patch_info->data.table->table_size, p, &p);
6466 for (k = 0; k < patch_info->data.table->table_size; k++)
6467 encode_value ((int)(gssize)table [k], p, &p);
6468 break;
6470 case MONO_PATCH_INFO_METHODCONST:
6471 case MONO_PATCH_INFO_METHOD:
6472 case MONO_PATCH_INFO_METHOD_JUMP:
6473 case MONO_PATCH_INFO_METHOD_FTNDESC:
6474 case MONO_PATCH_INFO_ICALL_ADDR:
6475 case MONO_PATCH_INFO_ICALL_ADDR_CALL:
6476 case MONO_PATCH_INFO_METHOD_RGCTX:
6477 case MONO_PATCH_INFO_METHOD_CODE_SLOT:
6478 encode_method_ref (acfg, patch_info->data.method, p, &p);
6479 break;
6480 case MONO_PATCH_INFO_AOT_JIT_INFO:
6481 case MONO_PATCH_INFO_GET_TLS_TRAMP:
6482 case MONO_PATCH_INFO_SET_TLS_TRAMP:
6483 case MONO_PATCH_INFO_TRAMPOLINE_FUNC_ADDR:
6484 case MONO_PATCH_INFO_CASTCLASS_CACHE:
6485 encode_value (patch_info->data.index, p, &p);
6486 break;
6487 case MONO_PATCH_INFO_JIT_ICALL_ID:
6488 case MONO_PATCH_INFO_JIT_ICALL_ADDR:
6489 case MONO_PATCH_INFO_JIT_ICALL_ADDR_NOCALL:
6490 encode_value (patch_info->data.jit_icall_id, p, &p);
6491 break;
6492 case MONO_PATCH_INFO_SPECIFIC_TRAMPOLINE_LAZY_FETCH_ADDR:
6493 encode_value (patch_info->data.uindex, p, &p);
6494 break;
6495 case MONO_PATCH_INFO_LDSTR_LIT: {
6496 guint32 len = strlen (patch_info->data.name);
6497 encode_value (len, p, &p);
6498 memcpy (p, patch_info->data.name, len + 1);
6499 p += len + 1;
6500 break;
6502 case MONO_PATCH_INFO_LDSTR: {
6503 guint32 image_index = get_image_index (acfg, patch_info->data.token->image);
6504 guint32 token = patch_info->data.token->token;
6505 g_assert (mono_metadata_token_code (token) == MONO_TOKEN_STRING);
6506 encode_value (image_index, p, &p);
6507 encode_value (patch_info->data.token->token - MONO_TOKEN_STRING, p, &p);
6508 break;
6510 case MONO_PATCH_INFO_RVA:
6511 case MONO_PATCH_INFO_DECLSEC:
6512 case MONO_PATCH_INFO_LDTOKEN:
6513 case MONO_PATCH_INFO_TYPE_FROM_HANDLE:
6514 encode_value (get_image_index (acfg, patch_info->data.token->image), p, &p);
6515 encode_value (patch_info->data.token->token, p, &p);
6516 encode_value (patch_info->data.token->has_context, p, &p);
6517 if (patch_info->data.token->has_context)
6518 encode_generic_context (acfg, &patch_info->data.token->context, p, &p);
6519 break;
6520 case MONO_PATCH_INFO_EXC_NAME: {
6521 MonoClass *ex_class;
6523 ex_class =
6524 mono_class_load_from_name (m_class_get_image (mono_defaults.exception_class),
6525 "System", (const char *)patch_info->data.target);
6526 encode_klass_ref (acfg, ex_class, p, &p);
6527 break;
6529 case MONO_PATCH_INFO_R4:
6530 encode_value (*((guint32 *)patch_info->data.target), p, &p);
6531 break;
6532 case MONO_PATCH_INFO_R8:
6533 encode_value (((guint32 *)patch_info->data.target) [MINI_LS_WORD_IDX], p, &p);
6534 encode_value (((guint32 *)patch_info->data.target) [MINI_MS_WORD_IDX], p, &p);
6535 break;
6536 case MONO_PATCH_INFO_VTABLE:
6537 case MONO_PATCH_INFO_CLASS:
6538 case MONO_PATCH_INFO_IID:
6539 case MONO_PATCH_INFO_ADJUSTED_IID:
6540 encode_klass_ref (acfg, patch_info->data.klass, p, &p);
6541 break;
6542 case MONO_PATCH_INFO_DELEGATE_TRAMPOLINE:
6543 encode_klass_ref (acfg, patch_info->data.del_tramp->klass, p, &p);
6544 if (patch_info->data.del_tramp->method) {
6545 encode_value (1, p, &p);
6546 encode_method_ref (acfg, patch_info->data.del_tramp->method, p, &p);
6547 } else {
6548 encode_value (0, p, &p);
6550 encode_value (patch_info->data.del_tramp->is_virtual, p, &p);
6551 break;
6552 case MONO_PATCH_INFO_FIELD:
6553 case MONO_PATCH_INFO_SFLDA:
6554 encode_field_info (acfg, patch_info->data.field, p, &p);
6555 break;
6556 case MONO_PATCH_INFO_INTERRUPTION_REQUEST_FLAG:
6557 break;
6558 case MONO_PATCH_INFO_PROFILER_ALLOCATION_COUNT:
6559 case MONO_PATCH_INFO_PROFILER_CLAUSE_COUNT:
6560 break;
6561 case MONO_PATCH_INFO_RGCTX_FETCH:
6562 case MONO_PATCH_INFO_RGCTX_SLOT_INDEX: {
6563 MonoJumpInfoRgctxEntry *entry = patch_info->data.rgctx_entry;
6564 guint32 offset;
6567 * entry->d.klass/method has a lenghtly encoding and multiple rgctx_fetch entries
6568 * reference the same klass/method, so encode it only once.
6569 * For patches which refer to got entries, this sharing is done by get_got_offset, but
6570 * these are not got entries.
6572 if (entry->in_mrgctx) {
6573 offset = get_shared_method_ref (acfg, entry->d.method);
6574 } else {
6575 offset = get_shared_klass_ref (acfg, entry->d.klass);
6578 encode_value (offset, p, &p);
6579 g_assert ((int)entry->info_type < 256);
6580 g_assert (entry->data->type < 256);
6581 encode_value ((entry->in_mrgctx ? 1 : 0) | (entry->info_type << 1) | (entry->data->type << 9), p, &p);
6582 encode_patch (acfg, entry->data, p, &p);
6583 break;
6585 case MONO_PATCH_INFO_SEQ_POINT_INFO:
6586 case MONO_PATCH_INFO_AOT_MODULE:
6587 break;
6588 case MONO_PATCH_INFO_SIGNATURE:
6589 case MONO_PATCH_INFO_GSHAREDVT_IN_WRAPPER:
6590 encode_signature (acfg, (MonoMethodSignature*)patch_info->data.target, p, &p);
6591 break;
6592 case MONO_PATCH_INFO_GSHAREDVT_CALL:
6593 encode_signature (acfg, (MonoMethodSignature*)patch_info->data.gsharedvt->sig, p, &p);
6594 encode_method_ref (acfg, patch_info->data.gsharedvt->method, p, &p);
6595 break;
6596 case MONO_PATCH_INFO_GSHAREDVT_METHOD: {
6597 MonoGSharedVtMethodInfo *info = patch_info->data.gsharedvt_method;
6598 int i;
6600 encode_method_ref (acfg, info->method, p, &p);
6601 encode_value (info->num_entries, p, &p);
6602 for (i = 0; i < info->num_entries; ++i) {
6603 MonoRuntimeGenericContextInfoTemplate *template_ = &info->entries [i];
6605 encode_value (template_->info_type, p, &p);
6606 switch (mini_rgctx_info_type_to_patch_info_type (template_->info_type)) {
6607 case MONO_PATCH_INFO_CLASS:
6608 encode_klass_ref (acfg, mono_class_from_mono_type_internal ((MonoType *)template_->data), p, &p);
6609 break;
6610 case MONO_PATCH_INFO_FIELD:
6611 encode_field_info (acfg, (MonoClassField *)template_->data, p, &p);
6612 break;
6613 default:
6614 g_assert_not_reached ();
6615 break;
6618 break;
6620 case MONO_PATCH_INFO_VIRT_METHOD:
6621 encode_klass_ref (acfg, patch_info->data.virt_method->klass, p, &p);
6622 encode_method_ref (acfg, patch_info->data.virt_method->method, p, &p);
6623 break;
6624 case MONO_PATCH_INFO_GC_SAFE_POINT_FLAG:
6625 break;
6626 default:
6627 g_warning ("unable to handle jump info %d", patch_info->type);
6628 g_assert_not_reached ();
6631 *endbuf = p;
6634 static void
6635 encode_patch_list (MonoAotCompile *acfg, GPtrArray *patches, int n_patches, gboolean llvm, guint8 *buf, guint8 **endbuf)
6637 guint8 *p = buf;
6638 guint32 pindex, offset;
6639 MonoJumpInfo *patch_info;
6641 encode_value (n_patches, p, &p);
6643 for (pindex = 0; pindex < patches->len; ++pindex) {
6644 patch_info = (MonoJumpInfo *)g_ptr_array_index (patches, pindex);
6646 if (patch_info->type == MONO_PATCH_INFO_NONE || patch_info->type == MONO_PATCH_INFO_BB)
6647 /* Nothing to do */
6648 continue;
6649 /* This shouldn't allocate a new offset */
6650 offset = lookup_got_offset (acfg, llvm, patch_info);
6651 encode_value (offset, p, &p);
6654 *endbuf = p;
6657 static void
6658 emit_method_info (MonoAotCompile *acfg, MonoCompile *cfg)
6660 MonoMethod *method;
6661 int pindex, buf_size, n_patches;
6662 GPtrArray *patches;
6663 MonoJumpInfo *patch_info;
6664 guint8 *p, *buf;
6665 guint32 offset;
6666 gboolean needs_ctx = FALSE;
6668 method = cfg->orig_method;
6670 (void)get_method_index (acfg, method);
6672 /* Sort relocations */
6673 patches = g_ptr_array_new ();
6674 for (patch_info = cfg->patch_info; patch_info; patch_info = patch_info->next)
6675 g_ptr_array_add (patches, patch_info);
6676 if (!acfg->aot_opts.llvm_only)
6677 g_ptr_array_sort (patches, compare_patches);
6679 /**********************/
6680 /* Encode method info */
6681 /**********************/
6683 g_assert (!(cfg->opt & MONO_OPT_SHARED));
6685 guint32 *got_offsets = g_new0 (guint32, patches->len);
6687 n_patches = 0;
6688 for (pindex = 0; pindex < patches->len; ++pindex) {
6689 patch_info = (MonoJumpInfo *)g_ptr_array_index (patches, pindex);
6691 if ((patch_info->type == MONO_PATCH_INFO_GOT_OFFSET) ||
6692 (patch_info->type == MONO_PATCH_INFO_NONE)) {
6693 patch_info->type = MONO_PATCH_INFO_NONE;
6694 /* Nothing to do */
6695 continue;
6698 if ((patch_info->type == MONO_PATCH_INFO_IMAGE) && (patch_info->data.image == acfg->image)) {
6699 /* Stored in a GOT slot initialized at module load time */
6700 patch_info->type = MONO_PATCH_INFO_NONE;
6701 continue;
6704 if (patch_info->type == MONO_PATCH_INFO_GC_CARD_TABLE_ADDR ||
6705 patch_info->type == MONO_PATCH_INFO_GC_NURSERY_START ||
6706 patch_info->type == MONO_PATCH_INFO_GC_NURSERY_BITS ||
6707 patch_info->type == MONO_PATCH_INFO_AOT_MODULE) {
6708 /* Stored in a GOT slot initialized at module load time */
6709 patch_info->type = MONO_PATCH_INFO_NONE;
6710 continue;
6713 if (is_plt_patch (patch_info) && !(cfg->compile_llvm && acfg->aot_opts.llvm_only)) {
6714 /* Calls are made through the PLT */
6715 patch_info->type = MONO_PATCH_INFO_NONE;
6716 continue;
6719 if (acfg->aot_opts.llvm_only && patch_info->type == MONO_PATCH_INFO_METHOD)
6720 needs_ctx = TRUE;
6722 /* This shouldn't allocate a new offset */
6723 offset = lookup_got_offset (acfg, cfg->compile_llvm, patch_info);
6724 if (offset >= acfg->nshared_got_entries)
6725 got_offsets [n_patches ++] = offset;
6728 if (n_patches)
6729 g_assert (cfg->has_got_slots);
6731 buf_size = (patches->len < 1000) ? 40960 : 40960 + (patches->len * 64);
6732 p = buf = (guint8 *)g_malloc (buf_size);
6734 MonoGenericContext *ctx = mono_method_get_context (cfg->method);
6736 guint8 flags = 0;
6737 if (mono_class_get_cctor (method->klass))
6738 flags |= MONO_AOT_METHOD_FLAG_HAS_CCTOR;
6739 if (mini_jit_info_is_gsharedvt (cfg->jit_info) && mini_is_gsharedvt_variable_signature (mono_method_signature_internal (jinfo_get_method (cfg->jit_info))))
6740 flags |= MONO_AOT_METHOD_FLAG_GSHAREDVT_VARIABLE;
6741 if (n_patches)
6742 flags |= MONO_AOT_METHOD_FLAG_HAS_PATCHES;
6743 if (needs_ctx && ctx)
6744 flags |= MONO_AOT_METHOD_FLAG_HAS_CTX;
6745 encode_value (flags, p, &p);
6746 if (flags & MONO_AOT_METHOD_FLAG_HAS_CCTOR)
6747 encode_klass_ref (acfg, method->klass, p, &p);
6748 if (needs_ctx && ctx)
6749 encode_generic_context (acfg, ctx, p, &p);
6751 if (n_patches) {
6752 encode_value (n_patches, p, &p);
6753 for (int i = 0; i < n_patches; ++i)
6754 encode_value (got_offsets [i], p, &p);
6757 g_ptr_array_free (patches, TRUE);
6758 g_free (got_offsets);
6760 acfg->stats.method_info_size += p - buf;
6762 g_assert (p - buf < buf_size);
6764 cfg->method_info_offset = add_to_blob (acfg, buf, p - buf);
6765 g_free (buf);
6768 static guint32
6769 get_unwind_info_offset (MonoAotCompile *acfg, guint8 *encoded, guint32 encoded_len)
6771 guint32 cache_index;
6772 guint32 offset;
6774 /* Reuse the unwind module to canonize and store unwind info entries */
6775 cache_index = mono_cache_unwind_info (encoded, encoded_len);
6777 /* Use +/- 1 to distinguish 0s from missing entries */
6778 offset = GPOINTER_TO_UINT (g_hash_table_lookup (acfg->unwind_info_offsets, GUINT_TO_POINTER (cache_index + 1)));
6779 if (offset)
6780 return offset - 1;
6781 else {
6782 guint8 buf [16];
6783 guint8 *p;
6786 * It would be easier to use assembler symbols, but the caller needs an
6787 * offset now.
6789 offset = acfg->unwind_info_offset;
6790 g_hash_table_insert (acfg->unwind_info_offsets, GUINT_TO_POINTER (cache_index + 1), GUINT_TO_POINTER (offset + 1));
6791 g_ptr_array_add (acfg->unwind_ops, GUINT_TO_POINTER (cache_index));
6793 p = buf;
6794 encode_value (encoded_len, p, &p);
6796 acfg->unwind_info_offset += encoded_len + (p - buf);
6797 return offset;
6801 static void
6802 emit_exception_debug_info (MonoAotCompile *acfg, MonoCompile *cfg, gboolean store_seq_points)
6804 int i, k, buf_size;
6805 guint32 debug_info_size, seq_points_size;
6806 guint8 *code;
6807 MonoMethodHeader *header;
6808 guint8 *p, *buf, *debug_info;
6809 MonoJitInfo *jinfo = cfg->jit_info;
6810 guint32 flags;
6811 gboolean use_unwind_ops = FALSE;
6812 MonoSeqPointInfo *seq_points;
6814 code = cfg->native_code;
6815 header = cfg->header;
6817 if (!acfg->aot_opts.nodebug) {
6818 mono_debug_serialize_debug_info (cfg, &debug_info, &debug_info_size);
6819 } else {
6820 debug_info = NULL;
6821 debug_info_size = 0;
6824 seq_points = cfg->seq_point_info;
6825 seq_points_size = (store_seq_points)? mono_seq_point_info_get_write_size (seq_points) : 0;
6827 buf_size = header->num_clauses * 256 + debug_info_size + 2048 + seq_points_size + cfg->gc_map_size;
6828 if (jinfo->has_try_block_holes) {
6829 MonoTryBlockHoleTableJitInfo *table = mono_jit_info_get_try_block_hole_table_info (jinfo);
6830 buf_size += table->num_holes * 16;
6833 p = buf = (guint8 *)g_malloc (buf_size);
6835 use_unwind_ops = cfg->unwind_ops != NULL;
6837 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);
6839 encode_value (flags, p, &p);
6841 if (use_unwind_ops) {
6842 guint32 encoded_len;
6843 guint8 *encoded;
6844 guint32 unwind_desc;
6846 encoded = mono_unwind_ops_encode (cfg->unwind_ops, &encoded_len);
6848 unwind_desc = get_unwind_info_offset (acfg, encoded, encoded_len);
6849 encode_value (unwind_desc, p, &p);
6851 g_free (encoded);
6852 } else {
6853 encode_value (jinfo->unwind_info, p, &p);
6856 /*Encode the number of holes before the number of clauses to make decoding easier*/
6857 if (jinfo->has_try_block_holes) {
6858 MonoTryBlockHoleTableJitInfo *table = mono_jit_info_get_try_block_hole_table_info (jinfo);
6859 encode_value (table->num_holes, p, &p);
6862 if (jinfo->has_arch_eh_info) {
6864 * In AOT mode, the code length is calculated from the address of the previous method,
6865 * which could include alignment padding, so calculating the start of the epilog as
6866 * code_len - epilog_size is correct any more. Save the real code len as a workaround.
6868 encode_value (jinfo->code_size, p, &p);
6871 /* Exception table */
6872 if (cfg->compile_llvm) {
6874 * When using LLVM, we can't emit some data, like pc offsets, this reg/offset etc.,
6875 * since the information is only available to llc. Instead, we let llc save the data
6876 * into the LSDA, and read it from there at runtime.
6878 /* The assembly might be CIL stripped so emit the data ourselves */
6879 if (header->num_clauses)
6880 encode_value (header->num_clauses, p, &p);
6882 for (k = 0; k < header->num_clauses; ++k) {
6883 MonoExceptionClause *clause;
6885 clause = &header->clauses [k];
6887 encode_value (clause->flags, p, &p);
6888 if (!(clause->flags == MONO_EXCEPTION_CLAUSE_FILTER || clause->flags == MONO_EXCEPTION_CLAUSE_FINALLY)) {
6889 if (clause->data.catch_class) {
6890 guint8 *buf2, *p2;
6891 int len;
6893 buf2 = (guint8 *)g_malloc (4096);
6894 p2 = buf2;
6895 encode_klass_ref (acfg, clause->data.catch_class, p2, &p2);
6896 len = p2 - buf2;
6897 g_assert (len < 4096);
6898 encode_value (len, p, &p);
6899 memcpy (p, buf2, len);
6900 p += p2 - buf2;
6901 g_free (buf2);
6902 } else {
6903 encode_value (0, p, &p);
6907 /* Emit the IL ranges too, since they might not be available at runtime */
6908 encode_value (clause->try_offset, p, &p);
6909 encode_value (clause->try_len, p, &p);
6910 encode_value (clause->handler_offset, p, &p);
6911 encode_value (clause->handler_len, p, &p);
6913 /* Emit a list of nesting clauses */
6914 for (i = 0; i < header->num_clauses; ++i) {
6915 gint32 cindex1 = k;
6916 MonoExceptionClause *clause1 = &header->clauses [cindex1];
6917 gint32 cindex2 = i;
6918 MonoExceptionClause *clause2 = &header->clauses [cindex2];
6920 if (cindex1 != cindex2 && clause1->try_offset >= clause2->try_offset && clause1->handler_offset <= clause2->handler_offset)
6921 encode_value (i, p, &p);
6923 encode_value (-1, p, &p);
6925 } else {
6926 if (jinfo->num_clauses)
6927 encode_value (jinfo->num_clauses, p, &p);
6929 for (k = 0; k < jinfo->num_clauses; ++k) {
6930 MonoJitExceptionInfo *ei = &jinfo->clauses [k];
6932 encode_value (ei->flags, p, &p);
6933 #ifdef MONO_CONTEXT_SET_LLVM_EXC_REG
6934 /* Not used for catch clauses */
6935 if (ei->flags != MONO_EXCEPTION_CLAUSE_NONE)
6936 encode_value (ei->exvar_offset, p, &p);
6937 #else
6938 encode_value (ei->exvar_offset, p, &p);
6939 #endif
6941 if (ei->flags == MONO_EXCEPTION_CLAUSE_FILTER || ei->flags == MONO_EXCEPTION_CLAUSE_FINALLY)
6942 encode_value ((gint)((guint8*)ei->data.filter - code), p, &p);
6943 else {
6944 if (ei->data.catch_class) {
6945 guint8 *buf2, *p2;
6946 int len;
6948 buf2 = (guint8 *)g_malloc (4096);
6949 p2 = buf2;
6950 encode_klass_ref (acfg, ei->data.catch_class, p2, &p2);
6951 len = p2 - buf2;
6952 g_assert (len < 4096);
6953 encode_value (len, p, &p);
6954 memcpy (p, buf2, len);
6955 p += p2 - buf2;
6956 g_free (buf2);
6957 } else {
6958 encode_value (0, p, &p);
6962 encode_value ((gint)((guint8*)ei->try_start - code), p, &p);
6963 encode_value ((gint)((guint8*)ei->try_end - code), p, &p);
6964 encode_value ((gint)((guint8*)ei->handler_start - code), p, &p);
6968 if (jinfo->has_try_block_holes) {
6969 MonoTryBlockHoleTableJitInfo *table = mono_jit_info_get_try_block_hole_table_info (jinfo);
6970 for (i = 0; i < table->num_holes; ++i) {
6971 MonoTryBlockHoleJitInfo *hole = &table->holes [i];
6972 encode_value (hole->clause, p, &p);
6973 encode_value (hole->length, p, &p);
6974 encode_value (hole->offset, p, &p);
6978 if (jinfo->has_arch_eh_info) {
6979 MonoArchEHJitInfo *eh_info;
6981 eh_info = mono_jit_info_get_arch_eh_info (jinfo);
6982 encode_value (eh_info->stack_size, p, &p);
6983 encode_value (eh_info->epilog_size, p, &p);
6986 if (jinfo->has_generic_jit_info) {
6987 MonoGenericJitInfo *gi = mono_jit_info_get_generic_jit_info (jinfo);
6988 MonoGenericSharingContext* gsctx = gi->generic_sharing_context;
6989 guint8 *buf2, *p2;
6990 int len;
6992 encode_value (gi->nlocs, p, &p);
6993 if (gi->nlocs) {
6994 for (i = 0; i < gi->nlocs; ++i) {
6995 MonoDwarfLocListEntry *entry = &gi->locations [i];
6997 encode_value (entry->is_reg ? 1 : 0, p, &p);
6998 encode_value (entry->reg, p, &p);
6999 if (!entry->is_reg)
7000 encode_value (entry->offset, p, &p);
7001 if (i == 0)
7002 g_assert (entry->from == 0);
7003 else
7004 encode_value (entry->from, p, &p);
7005 encode_value (entry->to, p, &p);
7007 } else {
7008 if (!cfg->compile_llvm) {
7009 encode_value (gi->has_this ? 1 : 0, p, &p);
7010 encode_value (gi->this_reg, p, &p);
7011 encode_value (gi->this_offset, p, &p);
7016 * Need to encode jinfo->method too, since it is not equal to 'method'
7017 * when using generic sharing.
7019 buf2 = (guint8 *)g_malloc (4096);
7020 p2 = buf2;
7021 encode_method_ref (acfg, jinfo->d.method, p2, &p2);
7022 len = p2 - buf2;
7023 g_assert (len < 4096);
7024 encode_value (len, p, &p);
7025 memcpy (p, buf2, len);
7026 p += p2 - buf2;
7027 g_free (buf2);
7029 if (gsctx && gsctx->is_gsharedvt) {
7030 encode_value (1, p, &p);
7031 } else {
7032 encode_value (0, p, &p);
7036 if (seq_points_size)
7037 p += mono_seq_point_info_write (seq_points, p);
7039 g_assert (debug_info_size < buf_size);
7041 encode_value (debug_info_size, p, &p);
7042 if (debug_info_size) {
7043 memcpy (p, debug_info, debug_info_size);
7044 p += debug_info_size;
7045 g_free (debug_info);
7048 /* GC Map */
7049 if (cfg->gc_map) {
7050 encode_value (cfg->gc_map_size, p, &p);
7051 /* The GC map requires 4 bytes of alignment */
7052 while ((gsize)p % 4)
7053 p ++;
7054 memcpy (p, cfg->gc_map, cfg->gc_map_size);
7055 p += cfg->gc_map_size;
7058 acfg->stats.ex_info_size += p - buf;
7060 g_assert (p - buf < buf_size);
7062 /* Emit info */
7063 /* The GC Map requires 4 byte alignment */
7064 cfg->ex_info_offset = add_to_blob_aligned (acfg, buf, p - buf, cfg->gc_map ? 4 : 1);
7065 g_free (buf);
7068 static guint32
7069 emit_klass_info (MonoAotCompile *acfg, guint32 token)
7071 ERROR_DECL (error);
7072 MonoClass *klass = mono_class_get_checked (acfg->image, token, error);
7073 guint8 *p, *buf;
7074 int i, buf_size, res;
7075 gboolean no_special_static, cant_encode;
7076 gpointer iter = NULL;
7078 if (!klass) {
7079 mono_error_cleanup (error);
7081 buf_size = 16;
7083 p = buf = (guint8 *)g_malloc (buf_size);
7085 /* Mark as unusable */
7086 encode_value (-1, p, &p);
7088 res = add_to_blob (acfg, buf, p - buf);
7089 g_free (buf);
7091 return res;
7094 buf_size = 10240 + (m_class_get_vtable_size (klass) * 16);
7095 p = buf = (guint8 *)g_malloc (buf_size);
7097 g_assert (klass);
7099 mono_class_init_internal (klass);
7101 mono_class_get_nested_types (klass, &iter);
7102 g_assert (m_class_is_nested_classes_inited (klass));
7104 mono_class_setup_vtable (klass);
7107 * Emit all the information which is required for creating vtables so
7108 * the runtime does not need to create the MonoMethod structures which
7109 * take up a lot of space.
7112 no_special_static = !mono_class_has_special_static_fields (klass);
7114 /* Check whenever we have enough info to encode the vtable */
7115 cant_encode = FALSE;
7116 MonoMethod **klass_vtable = m_class_get_vtable (klass);
7117 for (i = 0; i < m_class_get_vtable_size (klass); ++i) {
7118 MonoMethod *cm = klass_vtable [i];
7120 if (cm && mono_method_signature_internal (cm)->is_inflated && !g_hash_table_lookup (acfg->token_info_hash, cm))
7121 cant_encode = TRUE;
7124 mono_class_has_finalizer (klass);
7125 if (mono_class_has_failure (klass))
7126 cant_encode = TRUE;
7128 if (mono_class_is_gtd (klass) || cant_encode) {
7129 encode_value (-1, p, &p);
7130 } else {
7131 gboolean has_nested = mono_class_get_nested_classes_property (klass) != NULL;
7132 encode_value (m_class_get_vtable_size (klass), p, &p);
7133 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);
7134 if (m_class_has_cctor (klass))
7135 encode_method_ref (acfg, mono_class_get_cctor (klass), p, &p);
7136 if (m_class_has_finalize (klass))
7137 encode_method_ref (acfg, mono_class_get_finalizer (klass), p, &p);
7139 encode_value (m_class_get_instance_size (klass), p, &p);
7140 encode_value (mono_class_data_size (klass), p, &p);
7141 encode_value (m_class_get_packing_size (klass), p, &p);
7142 encode_value (m_class_get_min_align (klass), p, &p);
7144 for (i = 0; i < m_class_get_vtable_size (klass); ++i) {
7145 MonoMethod *cm = klass_vtable [i];
7147 if (cm)
7148 encode_method_ref (acfg, cm, p, &p);
7149 else
7150 encode_value (0, p, &p);
7154 acfg->stats.class_info_size += p - buf;
7156 g_assert (p - buf < buf_size);
7157 res = add_to_blob (acfg, buf, p - buf);
7158 g_free (buf);
7160 return res;
7163 static char*
7164 get_plt_entry_debug_sym (MonoAotCompile *acfg, MonoJumpInfo *ji, GHashTable *cache)
7166 char *debug_sym = NULL;
7167 char *prefix;
7169 if (acfg->llvm && llvm_acfg->aot_opts.static_link) {
7170 /* Need to add a prefix to create unique symbols */
7171 prefix = g_strdup_printf ("plt_%s_", acfg->assembly_name_sym);
7172 } else {
7173 #if defined(TARGET_WIN32) && defined(TARGET_X86)
7174 prefix = mangle_symbol_alloc ("plt_");
7175 #else
7176 prefix = g_strdup ("plt_");
7177 #endif
7180 switch (ji->type) {
7181 case MONO_PATCH_INFO_METHOD:
7182 debug_sym = get_debug_sym (ji->data.method, prefix, cache);
7183 break;
7184 case MONO_PATCH_INFO_JIT_ICALL_ID:
7185 debug_sym = g_strdup_printf ("%s_jit_icall_%s", prefix, mono_find_jit_icall_info (ji->data.jit_icall_id)->name);
7186 break;
7187 case MONO_PATCH_INFO_RGCTX_FETCH:
7188 debug_sym = g_strdup_printf ("%s_rgctx_fetch_%d", prefix, acfg->label_generator ++);
7189 break;
7190 case MONO_PATCH_INFO_ICALL_ADDR:
7191 case MONO_PATCH_INFO_ICALL_ADDR_CALL: {
7192 char *s = get_debug_sym (ji->data.method, "", cache);
7194 debug_sym = g_strdup_printf ("%s_icall_native_%s", prefix, s);
7195 g_free (s);
7196 break;
7198 case MONO_PATCH_INFO_TRAMPOLINE_FUNC_ADDR:
7199 debug_sym = g_strdup_printf ("%s_jit_icall_native_trampoline_func_%li", prefix, ji->data.index);
7200 break;
7201 case MONO_PATCH_INFO_SPECIFIC_TRAMPOLINE_LAZY_FETCH_ADDR:
7202 debug_sym = g_strdup_printf ("%s_jit_icall_native_specific_trampoline_lazy_fetch_%lu", prefix, ji->data.uindex);
7203 break;
7204 case MONO_PATCH_INFO_JIT_ICALL_ADDR:
7205 debug_sym = g_strdup_printf ("%s_jit_icall_native_%s", prefix, mono_find_jit_icall_info (ji->data.jit_icall_id)->name);
7206 break;
7207 default:
7208 break;
7211 g_free (prefix);
7213 return sanitize_symbol (acfg, debug_sym);
7217 * Calls made from AOTed code are routed through a table of jumps similar to the
7218 * ELF PLT (Program Linkage Table). Initially the PLT entries jump to code which transfers
7219 * control to the AOT runtime through a trampoline.
7221 static void
7222 emit_plt (MonoAotCompile *acfg)
7224 int i;
7226 if (acfg->aot_opts.llvm_only) {
7227 g_assert (acfg->plt_offset == 1);
7228 return;
7231 emit_line (acfg);
7233 emit_section_change (acfg, ".text", 0);
7234 emit_alignment_code (acfg, 16);
7235 emit_info_symbol (acfg, "plt", TRUE);
7236 emit_label (acfg, acfg->plt_symbol);
7238 for (i = 0; i < acfg->plt_offset; ++i) {
7239 char *debug_sym = NULL;
7240 MonoPltEntry *plt_entry = NULL;
7242 if (i == 0)
7244 * The first plt entry is unused.
7246 continue;
7248 plt_entry = (MonoPltEntry *)g_hash_table_lookup (acfg->plt_offset_to_entry, GUINT_TO_POINTER (i));
7250 debug_sym = plt_entry->debug_sym;
7252 if (acfg->thumb_mixed && !plt_entry->jit_used)
7253 /* Emit only a thumb version */
7254 continue;
7256 /* Skip plt entries not actually called */
7257 if (!plt_entry->jit_used && !plt_entry->llvm_used)
7258 continue;
7260 if (acfg->llvm && !acfg->thumb_mixed) {
7261 emit_label (acfg, plt_entry->llvm_symbol);
7262 if (acfg->llvm) {
7263 emit_global_inner (acfg, plt_entry->llvm_symbol, TRUE);
7264 #if defined(TARGET_MACH)
7265 fprintf (acfg->fp, ".private_extern %s\n", plt_entry->llvm_symbol);
7266 #endif
7270 if (debug_sym) {
7271 if (acfg->need_no_dead_strip) {
7272 emit_unset_mode (acfg);
7273 fprintf (acfg->fp, " .no_dead_strip %s\n", debug_sym);
7275 emit_local_symbol (acfg, debug_sym, NULL, TRUE);
7276 emit_label (acfg, debug_sym);
7279 emit_label (acfg, plt_entry->symbol);
7281 arch_emit_plt_entry (acfg, acfg->got_symbol, (acfg->plt_got_offset_base + i) * sizeof (target_mgreg_t), acfg->plt_got_info_offsets [i]);
7283 if (debug_sym)
7284 emit_symbol_size (acfg, debug_sym, ".");
7287 if (acfg->thumb_mixed) {
7288 /* Make sure the ARM symbols don't alias the thumb ones */
7289 emit_zero_bytes (acfg, 16);
7292 * Emit a separate set of PLT entries using thumb2 which is called by LLVM generated
7293 * code.
7295 for (i = 0; i < acfg->plt_offset; ++i) {
7296 char *debug_sym = NULL;
7297 MonoPltEntry *plt_entry = NULL;
7299 if (i == 0)
7300 continue;
7302 plt_entry = (MonoPltEntry *)g_hash_table_lookup (acfg->plt_offset_to_entry, GUINT_TO_POINTER (i));
7304 /* Skip plt entries not actually called by LLVM code */
7305 if (!plt_entry->llvm_used)
7306 continue;
7308 if (acfg->aot_opts.write_symbols) {
7309 if (plt_entry->debug_sym)
7310 debug_sym = g_strdup_printf ("%s_thumb", plt_entry->debug_sym);
7313 if (debug_sym) {
7314 #if defined(TARGET_MACH)
7315 fprintf (acfg->fp, " .thumb_func %s\n", debug_sym);
7316 fprintf (acfg->fp, " .no_dead_strip %s\n", debug_sym);
7317 #endif
7318 emit_local_symbol (acfg, debug_sym, NULL, TRUE);
7319 emit_label (acfg, debug_sym);
7321 fprintf (acfg->fp, "\n.thumb_func\n");
7323 emit_label (acfg, plt_entry->llvm_symbol);
7325 if (acfg->llvm)
7326 emit_global_inner (acfg, plt_entry->llvm_symbol, TRUE);
7328 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]);
7330 if (debug_sym) {
7331 emit_symbol_size (acfg, debug_sym, ".");
7332 g_free (debug_sym);
7337 emit_symbol_size (acfg, acfg->plt_symbol, ".");
7339 emit_info_symbol (acfg, "plt_end", TRUE);
7341 arch_emit_unwind_info_sections (acfg, "plt", "plt_end", NULL);
7345 * emit_trampoline_full:
7347 * If EMIT_TINFO is TRUE, emit additional information which can be used to create a MonoJitInfo for this trampoline by
7348 * create_jit_info_for_trampoline ().
7350 static G_GNUC_UNUSED void
7351 emit_trampoline_full (MonoAotCompile *acfg, MonoTrampInfo *info, gboolean emit_tinfo)
7353 char start_symbol [MAX_SYMBOL_SIZE];
7354 char end_symbol [MAX_SYMBOL_SIZE];
7355 char symbol [MAX_SYMBOL_SIZE];
7356 guint32 buf_size, info_offset;
7357 MonoJumpInfo *patch_info;
7358 guint8 *buf, *p;
7359 GPtrArray *patches;
7360 char *name;
7361 guint8 *code;
7362 guint32 code_size;
7363 MonoJumpInfo *ji;
7364 GSList *unwind_ops;
7366 g_assert (info);
7368 name = info->name;
7369 code = info->code;
7370 code_size = info->code_size;
7371 ji = info->ji;
7372 unwind_ops = info->unwind_ops;
7374 /* Emit code */
7376 sprintf (start_symbol, "%s%s", acfg->user_symbol_prefix, name);
7378 emit_section_change (acfg, ".text", 0);
7379 emit_global (acfg, start_symbol, TRUE);
7380 emit_alignment_code (acfg, AOT_FUNC_ALIGNMENT);
7381 emit_label (acfg, start_symbol);
7383 sprintf (symbol, "%snamed_%s", acfg->temp_prefix, name);
7384 emit_label (acfg, symbol);
7387 * The code should access everything through the GOT, so we pass
7388 * TRUE here.
7390 emit_and_reloc_code (acfg, NULL, code, code_size, ji, TRUE, NULL);
7392 emit_symbol_size (acfg, start_symbol, ".");
7394 if (emit_tinfo) {
7395 sprintf (end_symbol, "%snamede_%s", acfg->temp_prefix, name);
7396 emit_label (acfg, end_symbol);
7399 /* Emit info */
7401 /* Sort relocations */
7402 patches = g_ptr_array_new ();
7403 for (patch_info = ji; patch_info; patch_info = patch_info->next)
7404 if (patch_info->type != MONO_PATCH_INFO_NONE)
7405 g_ptr_array_add (patches, patch_info);
7406 g_ptr_array_sort (patches, compare_patches);
7408 buf_size = patches->len * 128 + 128;
7409 buf = (guint8 *)g_malloc (buf_size);
7410 p = buf;
7412 encode_patch_list (acfg, patches, patches->len, FALSE, p, &p);
7413 g_assert (p - buf < buf_size);
7414 g_ptr_array_free (patches, TRUE);
7416 sprintf (symbol, "%s%s_p", acfg->user_symbol_prefix, name);
7418 info_offset = add_to_blob (acfg, buf, p - buf);
7420 emit_section_change (acfg, RODATA_SECT, 0);
7421 emit_global (acfg, symbol, FALSE);
7422 emit_label (acfg, symbol);
7424 emit_int32 (acfg, info_offset);
7426 if (emit_tinfo) {
7427 guint8 *encoded;
7428 guint32 encoded_len;
7429 guint32 uw_offset;
7432 * Emit additional information which can be used to reconstruct a partial MonoTrampInfo.
7434 encoded = mono_unwind_ops_encode (info->unwind_ops, &encoded_len);
7435 uw_offset = get_unwind_info_offset (acfg, encoded, encoded_len);
7436 g_free (encoded);
7438 emit_symbol_diff (acfg, end_symbol, start_symbol, 0);
7439 emit_int32 (acfg, uw_offset);
7442 /* Emit debug info */
7443 if (unwind_ops) {
7444 char symbol2 [MAX_SYMBOL_SIZE];
7446 sprintf (symbol, "%s", name);
7447 sprintf (symbol2, "%snamed_%s", acfg->temp_prefix, name);
7449 arch_emit_unwind_info_sections (acfg, start_symbol, end_symbol, unwind_ops);
7451 if (acfg->dwarf)
7452 mono_dwarf_writer_emit_trampoline (acfg->dwarf, symbol, symbol2, NULL, NULL, code_size, unwind_ops);
7455 g_free (buf);
7458 static G_GNUC_UNUSED void
7459 emit_trampoline (MonoAotCompile *acfg, MonoTrampInfo *info)
7461 emit_trampoline_full (acfg, info, TRUE);
7464 static void
7465 emit_trampolines (MonoAotCompile *acfg)
7467 char symbol [MAX_SYMBOL_SIZE];
7468 char end_symbol [MAX_SYMBOL_SIZE];
7469 int i, tramp_got_offset;
7470 int ntype;
7471 #ifdef MONO_ARCH_HAVE_FULL_AOT_TRAMPOLINES
7472 int tramp_type;
7473 #endif
7475 if (!mono_aot_mode_is_full (&acfg->aot_opts) && !mono_aot_mode_is_interp (&acfg->aot_opts))
7476 return;
7477 if (acfg->aot_opts.llvm_only)
7478 return;
7480 g_assert (acfg->image->assembly);
7482 /* Currently, we emit most trampolines into the mscorlib AOT image. */
7483 if (mono_is_corlib_image(acfg->image->assembly->image)) {
7484 #ifdef MONO_ARCH_HAVE_FULL_AOT_TRAMPOLINES
7485 MonoTrampInfo *info;
7488 * Emit the generic trampolines.
7490 * We could save some code by treating the generic trampolines as a wrapper
7491 * method, but that approach has its own complexities, so we choose the simpler
7492 * method.
7494 for (tramp_type = 0; tramp_type < MONO_TRAMPOLINE_NUM; ++tramp_type) {
7495 /* we overload the boolean here to indicate the slightly different trampoline needed, see mono_arch_create_generic_trampoline() */
7496 #ifdef DISABLE_REMOTING
7497 if (tramp_type == MONO_TRAMPOLINE_GENERIC_VIRTUAL_REMOTING)
7498 continue;
7499 #endif
7500 mono_arch_create_generic_trampoline ((MonoTrampolineType)tramp_type, &info, acfg->aot_opts.use_trampolines_page? 2: TRUE);
7501 emit_trampoline (acfg, info);
7502 mono_tramp_info_free (info);
7505 /* Emit the exception related code pieces */
7506 mono_arch_get_restore_context (&info, TRUE);
7507 emit_trampoline (acfg, info);
7508 mono_tramp_info_free (info);
7510 mono_arch_get_call_filter (&info, TRUE);
7511 emit_trampoline (acfg, info);
7512 mono_tramp_info_free (info);
7514 mono_arch_get_throw_exception (&info, TRUE);
7515 emit_trampoline (acfg, info);
7516 mono_tramp_info_free (info);
7518 mono_arch_get_rethrow_exception (&info, TRUE);
7519 emit_trampoline (acfg, info);
7520 mono_tramp_info_free (info);
7522 mono_arch_get_rethrow_preserve_exception (&info, TRUE);
7523 emit_trampoline (acfg, info);
7524 mono_tramp_info_free (info);
7526 mono_arch_get_throw_corlib_exception (&info, TRUE);
7527 emit_trampoline (acfg, info);
7528 mono_tramp_info_free (info);
7530 #ifdef MONO_ARCH_HAVE_SDB_TRAMPOLINES
7531 mono_arch_create_sdb_trampoline (TRUE, &info, TRUE);
7532 emit_trampoline (acfg, info);
7533 mono_tramp_info_free (info);
7535 mono_arch_create_sdb_trampoline (FALSE, &info, TRUE);
7536 emit_trampoline (acfg, info);
7537 mono_tramp_info_free (info);
7538 #endif
7540 #ifdef MONO_ARCH_GSHAREDVT_SUPPORTED
7541 mono_arch_get_gsharedvt_trampoline (&info, TRUE);
7542 if (info) {
7543 emit_trampoline_full (acfg, info, TRUE);
7545 /* Create a separate out trampoline for more information in stack traces */
7546 info->name = g_strdup ("gsharedvt_out_trampoline");
7547 emit_trampoline_full (acfg, info, TRUE);
7548 mono_tramp_info_free (info);
7550 #endif
7552 #if defined(MONO_ARCH_HAVE_GET_TRAMPOLINES)
7554 GSList *l = mono_arch_get_trampolines (TRUE);
7556 while (l) {
7557 MonoTrampInfo *info = (MonoTrampInfo *)l->data;
7559 emit_trampoline (acfg, info);
7560 l = l->next;
7563 #endif
7565 for (i = 0; i < acfg->aot_opts.nrgctx_fetch_trampolines; ++i) {
7566 int offset;
7568 offset = MONO_RGCTX_SLOT_MAKE_RGCTX (i);
7569 mono_arch_create_rgctx_lazy_fetch_trampoline (offset, &info, TRUE);
7570 emit_trampoline (acfg, info);
7571 mono_tramp_info_free (info);
7573 offset = MONO_RGCTX_SLOT_MAKE_MRGCTX (i);
7574 mono_arch_create_rgctx_lazy_fetch_trampoline (offset, &info, TRUE);
7575 emit_trampoline (acfg, info);
7576 mono_tramp_info_free (info);
7579 #ifdef MONO_ARCH_HAVE_GENERAL_RGCTX_LAZY_FETCH_TRAMPOLINE
7580 mono_arch_create_general_rgctx_lazy_fetch_trampoline (&info, TRUE);
7581 emit_trampoline (acfg, info);
7582 mono_tramp_info_free (info);
7583 #endif
7586 GSList *l;
7588 /* delegate_invoke_impl trampolines */
7589 l = mono_arch_get_delegate_invoke_impls ();
7590 while (l) {
7591 MonoTrampInfo *info = (MonoTrampInfo *)l->data;
7593 emit_trampoline (acfg, info);
7594 l = l->next;
7598 if (mono_aot_mode_is_interp (&acfg->aot_opts) && mono_is_corlib_image (acfg->image->assembly->image)) {
7599 mono_arch_get_interp_to_native_trampoline (&info);
7600 emit_trampoline (acfg, info);
7602 #ifdef MONO_ARCH_HAVE_INTERP_ENTRY_TRAMPOLINE
7603 mono_arch_get_native_to_interp_trampoline (&info);
7604 emit_trampoline (acfg, info);
7605 #endif
7608 #endif /* #ifdef MONO_ARCH_HAVE_FULL_AOT_TRAMPOLINES */
7610 /* Emit trampolines which are numerous */
7613 * These include the following:
7614 * - specific trampolines
7615 * - static rgctx invoke trampolines
7616 * - imt trampolines
7617 * These trampolines have the same code, they are parameterized by GOT
7618 * slots.
7619 * They are defined in this file, in the arch_... routines instead of
7620 * in tramp-<ARCH>.c, since it is easier to do it this way.
7624 * When running in aot-only mode, we can't create specific trampolines at
7625 * runtime, so we create a few, and save them in the AOT file.
7626 * Normal trampolines embed their argument as a literal inside the
7627 * trampoline code, we can't do that here, so instead we embed an offset
7628 * which needs to be added to the trampoline address to get the address of
7629 * the GOT slot which contains the argument value.
7630 * The generated trampolines jump to the generic trampolines using another
7631 * GOT slot, which will be setup by the AOT loader to point to the
7632 * generic trampoline code of the given type.
7636 * FIXME: Maybe we should use more specific trampolines (i.e. one class init for
7637 * each class).
7640 emit_section_change (acfg, ".text", 0);
7642 tramp_got_offset = acfg->got_offset;
7644 for (ntype = 0; ntype < MONO_AOT_TRAMP_NUM; ++ntype) {
7645 switch (ntype) {
7646 case MONO_AOT_TRAMP_SPECIFIC:
7647 sprintf (symbol, "specific_trampolines");
7648 break;
7649 case MONO_AOT_TRAMP_STATIC_RGCTX:
7650 sprintf (symbol, "static_rgctx_trampolines");
7651 break;
7652 case MONO_AOT_TRAMP_IMT:
7653 sprintf (symbol, "imt_trampolines");
7654 break;
7655 case MONO_AOT_TRAMP_GSHAREDVT_ARG:
7656 sprintf (symbol, "gsharedvt_arg_trampolines");
7657 break;
7658 case MONO_AOT_TRAMP_FTNPTR_ARG:
7659 sprintf (symbol, "ftnptr_arg_trampolines");
7660 break;
7661 case MONO_AOT_TRAMP_UNBOX_ARBITRARY:
7662 sprintf (symbol, "unbox_arbitrary_trampolines");
7663 break;
7664 default:
7665 g_assert_not_reached ();
7668 sprintf (end_symbol, "%s_e", symbol);
7670 if (acfg->aot_opts.write_symbols)
7671 emit_local_symbol (acfg, symbol, end_symbol, TRUE);
7673 emit_alignment_code (acfg, AOT_FUNC_ALIGNMENT);
7674 emit_info_symbol (acfg, symbol, TRUE);
7676 acfg->trampoline_got_offset_base [ntype] = tramp_got_offset;
7678 for (i = 0; i < acfg->num_trampolines [ntype]; ++i) {
7679 int tramp_size = 0;
7681 switch (ntype) {
7682 case MONO_AOT_TRAMP_SPECIFIC:
7683 arch_emit_specific_trampoline (acfg, tramp_got_offset, &tramp_size);
7684 tramp_got_offset += 2;
7685 break;
7686 case MONO_AOT_TRAMP_STATIC_RGCTX:
7687 arch_emit_static_rgctx_trampoline (acfg, tramp_got_offset, &tramp_size);
7688 tramp_got_offset += 2;
7689 break;
7690 case MONO_AOT_TRAMP_IMT:
7691 arch_emit_imt_trampoline (acfg, tramp_got_offset, &tramp_size);
7692 tramp_got_offset += 1;
7693 break;
7694 case MONO_AOT_TRAMP_GSHAREDVT_ARG:
7695 arch_emit_gsharedvt_arg_trampoline (acfg, tramp_got_offset, &tramp_size);
7696 tramp_got_offset += 2;
7697 break;
7698 case MONO_AOT_TRAMP_FTNPTR_ARG:
7699 arch_emit_ftnptr_arg_trampoline (acfg, tramp_got_offset, &tramp_size);
7700 tramp_got_offset += 2;
7701 break;
7702 case MONO_AOT_TRAMP_UNBOX_ARBITRARY:
7703 arch_emit_unbox_arbitrary_trampoline (acfg, tramp_got_offset, &tramp_size);
7704 tramp_got_offset += 1;
7705 break;
7706 default:
7707 g_assert_not_reached ();
7709 if (!acfg->trampoline_size [ntype]) {
7710 g_assert (tramp_size);
7711 acfg->trampoline_size [ntype] = tramp_size;
7715 emit_label (acfg, end_symbol);
7716 emit_int32 (acfg, 0);
7719 arch_emit_specific_trampoline_pages (acfg);
7721 /* Reserve some entries at the end of the GOT for our use */
7722 acfg->num_trampoline_got_entries = tramp_got_offset - acfg->got_offset;
7725 acfg->got_offset += acfg->num_trampoline_got_entries;
7728 static gboolean
7729 str_begins_with (const char *str1, const char *str2)
7731 int len = strlen (str2);
7732 return strncmp (str1, str2, len) == 0;
7735 void*
7736 mono_aot_readonly_field_override (MonoClassField *field)
7738 ReadOnlyValue *rdv;
7739 for (rdv = readonly_values; rdv; rdv = rdv->next) {
7740 char *p = rdv->name;
7741 int len;
7742 len = strlen (m_class_get_name_space (field->parent));
7743 if (strncmp (p, m_class_get_name_space (field->parent), len))
7744 continue;
7745 p += len;
7746 if (*p++ != '.')
7747 continue;
7748 len = strlen (m_class_get_name (field->parent));
7749 if (strncmp (p, m_class_get_name (field->parent), len))
7750 continue;
7751 p += len;
7752 if (*p++ != '.')
7753 continue;
7754 if (strcmp (p, field->name))
7755 continue;
7756 switch (rdv->type) {
7757 case MONO_TYPE_I1:
7758 return &rdv->value.i1;
7759 case MONO_TYPE_I2:
7760 return &rdv->value.i2;
7761 case MONO_TYPE_I4:
7762 return &rdv->value.i4;
7763 default:
7764 break;
7767 return NULL;
7770 static void
7771 add_readonly_value (MonoAotOptions *opts, const char *val)
7773 ReadOnlyValue *rdv;
7774 const char *fval;
7775 const char *tval;
7776 /* the format of val is:
7777 * namespace.typename.fieldname=type/value
7778 * type can be i1 for uint8/int8/boolean, i2 for uint16/int16/char, i4 for uint32/int32
7780 fval = strrchr (val, '/');
7781 if (!fval) {
7782 fprintf (stderr, "AOT : invalid format for readonly field '%s', missing /.\n", val);
7783 exit (1);
7785 tval = strrchr (val, '=');
7786 if (!tval) {
7787 fprintf (stderr, "AOT : invalid format for readonly field '%s', missing =.\n", val);
7788 exit (1);
7790 rdv = g_new0 (ReadOnlyValue, 1);
7791 rdv->name = (char *)g_malloc0 (tval - val + 1);
7792 memcpy (rdv->name, val, tval - val);
7793 tval++;
7794 fval++;
7795 if (strncmp (tval, "i1", 2) == 0) {
7796 rdv->value.i1 = atoi (fval);
7797 rdv->type = MONO_TYPE_I1;
7798 } else if (strncmp (tval, "i2", 2) == 0) {
7799 rdv->value.i2 = atoi (fval);
7800 rdv->type = MONO_TYPE_I2;
7801 } else if (strncmp (tval, "i4", 2) == 0) {
7802 rdv->value.i4 = atoi (fval);
7803 rdv->type = MONO_TYPE_I4;
7804 } else {
7805 fprintf (stderr, "AOT : unsupported type for readonly field '%s'.\n", tval);
7806 exit (1);
7808 rdv->next = readonly_values;
7809 readonly_values = rdv;
7812 static gchar *
7813 clean_path (gchar * path)
7815 if (!path)
7816 return NULL;
7818 if (g_str_has_suffix (path, G_DIR_SEPARATOR_S))
7819 return path;
7821 gchar *clean = g_strconcat (path, G_DIR_SEPARATOR_S, NULL);
7822 g_free (path);
7824 return clean;
7827 static const gchar *
7828 wrap_path (const gchar * path)
7830 int len;
7831 if (!path)
7832 return NULL;
7834 // If the string contains no spaces, just return the original string.
7835 if (strstr (path, " ") == NULL)
7836 return path;
7838 // If the string is already wrapped in quotes, return it.
7839 len = strlen (path);
7840 if (len >= 2 && path[0] == '\"' && path[len-1] == '\"')
7841 return path;
7843 // If the string contains spaces, then wrap it in quotes.
7844 gchar *clean = g_strdup_printf ("\"%s\"", path);
7846 return clean;
7849 // Duplicate a char range and add it to a ptrarray, but only if it is nonempty
7850 static void
7851 ptr_array_add_range_if_nonempty(GPtrArray *args, gchar const *start, gchar const *end)
7853 ptrdiff_t len = end-start;
7854 if (len > 0)
7855 g_ptr_array_add (args, g_strndup (start, len));
7858 static GPtrArray *
7859 mono_aot_split_options (const char *aot_options)
7861 enum MonoAotOptionState {
7862 MONO_AOT_OPTION_STATE_DEFAULT,
7863 MONO_AOT_OPTION_STATE_STRING,
7864 MONO_AOT_OPTION_STATE_ESCAPE,
7867 GPtrArray *args = g_ptr_array_new ();
7868 enum MonoAotOptionState state = MONO_AOT_OPTION_STATE_DEFAULT;
7869 gchar const *opt_start = aot_options;
7870 gboolean end_of_string = FALSE;
7871 gchar cur;
7873 g_return_val_if_fail (aot_options != NULL, NULL);
7875 while ((cur = *aot_options) != '\0') {
7876 if (state == MONO_AOT_OPTION_STATE_ESCAPE)
7877 goto next;
7879 switch (cur) {
7880 case '"':
7881 // If we find a quote, then if we're in the default case then
7882 // it means we've found the start of a string, if not then it
7883 // means we've found the end of the string and should switch
7884 // back to the default case.
7885 switch (state) {
7886 case MONO_AOT_OPTION_STATE_DEFAULT:
7887 state = MONO_AOT_OPTION_STATE_STRING;
7888 break;
7889 case MONO_AOT_OPTION_STATE_STRING:
7890 state = MONO_AOT_OPTION_STATE_DEFAULT;
7891 break;
7892 case MONO_AOT_OPTION_STATE_ESCAPE:
7893 g_assert_not_reached ();
7894 break;
7896 break;
7897 case '\\':
7898 // If we've found an escaping operator, then this means we
7899 // should not process the next character if inside a string.
7900 if (state == MONO_AOT_OPTION_STATE_STRING)
7901 state = MONO_AOT_OPTION_STATE_ESCAPE;
7902 break;
7903 case ',':
7904 // If we're in the default state then this means we've found
7905 // an option, store it for later processing.
7906 if (state == MONO_AOT_OPTION_STATE_DEFAULT)
7907 goto new_opt;
7908 break;
7911 next:
7912 aot_options++;
7913 restart:
7914 // If the next character is end of string, then process the last option.
7915 if (*(aot_options) == '\0') {
7916 end_of_string = TRUE;
7917 goto new_opt;
7919 continue;
7921 new_opt:
7922 ptr_array_add_range_if_nonempty (args, opt_start, aot_options);
7923 opt_start = ++aot_options;
7924 if (end_of_string)
7925 break;
7926 goto restart; // Check for null and continue loop
7929 return args;
7932 static void
7933 mono_aot_parse_options (const char *aot_options, MonoAotOptions *opts)
7935 GPtrArray* args;
7937 args = mono_aot_split_options (aot_options ? aot_options : "");
7938 for (int i = 0; i < args->len; ++i) {
7939 const char *arg = (const char *)g_ptr_array_index (args, i);
7941 if (str_begins_with (arg, "outfile=")) {
7942 opts->outfile = g_strdup (arg + strlen ("outfile="));
7943 } else if (str_begins_with (arg, "llvm-outfile=")) {
7944 opts->llvm_outfile = g_strdup (arg + strlen ("llvm-outfile="));
7945 } else if (str_begins_with (arg, "temp-path=")) {
7946 opts->temp_path = clean_path (g_strdup (arg + strlen ("temp-path=")));
7947 } else if (str_begins_with (arg, "save-temps")) {
7948 opts->save_temps = TRUE;
7949 } else if (str_begins_with (arg, "keep-temps")) {
7950 opts->save_temps = TRUE;
7951 } else if (str_begins_with (arg, "write-symbols")) {
7952 opts->write_symbols = TRUE;
7953 } else if (str_begins_with (arg, "no-write-symbols")) {
7954 opts->write_symbols = FALSE;
7955 // Intentionally undocumented -- one-off experiment
7956 } else if (str_begins_with (arg, "metadata-only")) {
7957 opts->metadata_only = TRUE;
7958 } else if (str_begins_with (arg, "bind-to-runtime-version")) {
7959 opts->bind_to_runtime_version = TRUE;
7960 } else if (str_begins_with (arg, "full")) {
7961 opts->mode = MONO_AOT_MODE_FULL;
7962 } else if (str_begins_with (arg, "hybrid")) {
7963 opts->mode = MONO_AOT_MODE_HYBRID;
7964 } else if (str_begins_with (arg, "interp")) {
7965 opts->interp = TRUE;
7966 } else if (str_begins_with (arg, "threads=")) {
7967 opts->nthreads = atoi (arg + strlen ("threads="));
7968 } else if (str_begins_with (arg, "static")) {
7969 opts->static_link = TRUE;
7970 opts->no_dlsym = TRUE;
7971 } else if (str_begins_with (arg, "asmonly")) {
7972 opts->asm_only = TRUE;
7973 } else if (str_begins_with (arg, "asmwriter")) {
7974 opts->asm_writer = TRUE;
7975 } else if (str_begins_with (arg, "nodebug")) {
7976 opts->nodebug = TRUE;
7977 } else if (str_begins_with (arg, "dwarfdebug")) {
7978 opts->dwarf_debug = TRUE;
7979 // Intentionally undocumented -- No one remembers what this does. It appears to be ARM-only
7980 } else if (str_begins_with (arg, "nopagetrampolines")) {
7981 opts->use_trampolines_page = FALSE;
7982 } else if (str_begins_with (arg, "ntrampolines=")) {
7983 opts->ntrampolines = atoi (arg + strlen ("ntrampolines="));
7984 } else if (str_begins_with (arg, "nrgctx-trampolines=")) {
7985 opts->nrgctx_trampolines = atoi (arg + strlen ("nrgctx-trampolines="));
7986 } else if (str_begins_with (arg, "nrgctx-fetch-trampolines=")) {
7987 opts->nrgctx_fetch_trampolines = atoi (arg + strlen ("nrgctx-fetch-trampolines="));
7988 } else if (str_begins_with (arg, "nimt-trampolines=")) {
7989 opts->nimt_trampolines = atoi (arg + strlen ("nimt-trampolines="));
7990 } else if (str_begins_with (arg, "ngsharedvt-trampolines=")) {
7991 opts->ngsharedvt_arg_trampolines = atoi (arg + strlen ("ngsharedvt-trampolines="));
7992 } else if (str_begins_with (arg, "nftnptr-arg-trampolines=")) {
7993 opts->nftnptr_arg_trampolines = atoi (arg + strlen ("nftnptr-arg-trampolines="));
7994 } else if (str_begins_with (arg, "nunbox-arbitrary-trampolines=")) {
7995 opts->nunbox_arbitrary_trampolines = atoi (arg + strlen ("unbox-arbitrary-trampolines="));
7996 } else if (str_begins_with (arg, "tool-prefix=")) {
7997 opts->tool_prefix = g_strdup (arg + strlen ("tool-prefix="));
7998 } else if (str_begins_with (arg, "ld-flags=")) {
7999 opts->ld_flags = g_strdup (arg + strlen ("ld-flags="));
8000 } else if (str_begins_with (arg, "soft-debug")) {
8001 opts->soft_debug = TRUE;
8002 // Intentionally undocumented x2-- deprecated
8003 } else if (str_begins_with (arg, "gen-seq-points-file=")) {
8004 fprintf (stderr, "Mono Warning: aot option gen-seq-points-file= is deprecated.\n");
8005 } else if (str_begins_with (arg, "gen-seq-points-file")) {
8006 fprintf (stderr, "Mono Warning: aot option gen-seq-points-file is deprecated.\n");
8007 } else if (str_begins_with (arg, "msym-dir=")) {
8008 mini_debug_options.no_seq_points_compact_data = FALSE;
8009 opts->gen_msym_dir = TRUE;
8010 opts->gen_msym_dir_path = g_strdup (arg + strlen ("msym_dir="));
8011 } else if (str_begins_with (arg, "direct-pinvoke")) {
8012 opts->direct_pinvoke = TRUE;
8013 } else if (str_begins_with (arg, "direct-icalls")) {
8014 opts->direct_icalls = TRUE;
8015 } else if (str_begins_with (arg, "no-direct-calls")) {
8016 opts->no_direct_calls = TRUE;
8017 } else if (str_begins_with (arg, "print-skipped")) {
8018 opts->print_skipped_methods = TRUE;
8019 } else if (str_begins_with (arg, "stats")) {
8020 opts->stats = TRUE;
8021 // Intentionally undocumented-- has no known function other than to debug the compiler
8022 } else if (str_begins_with (arg, "no-instances")) {
8023 opts->no_instances = TRUE;
8024 // Intentionally undocumented x4-- Used for internal debugging of compiler
8025 } else if (str_begins_with (arg, "log-generics")) {
8026 opts->log_generics = TRUE;
8027 } else if (str_begins_with (arg, "log-instances=")) {
8028 opts->log_instances = TRUE;
8029 opts->instances_logfile_path = g_strdup (arg + strlen ("log-instances="));
8030 } else if (str_begins_with (arg, "log-instances")) {
8031 opts->log_instances = TRUE;
8032 } else if (str_begins_with (arg, "internal-logfile=")) {
8033 opts->logfile = g_strdup (arg + strlen ("internal-logfile="));
8034 } else if (str_begins_with (arg, "dedup-skip")) {
8035 opts->dedup = TRUE;
8036 } else if (str_begins_with (arg, "dedup-include=")) {
8037 opts->dedup_include = g_strdup (arg + strlen ("dedup-include="));
8038 } else if (str_begins_with (arg, "mtriple=")) {
8039 opts->mtriple = g_strdup (arg + strlen ("mtriple="));
8040 } else if (str_begins_with (arg, "llvm-path=")) {
8041 opts->llvm_path = clean_path (g_strdup (arg + strlen ("llvm-path=")));
8042 } else if (!strcmp (arg, "try-llvm")) {
8043 // If we can load LLVM, use it
8044 // Note: if you call this function from anywhere but mono_compile_assembly,
8045 // this will only set the try_llvm attribute and not do the probing / set the
8046 // attribute.
8047 opts->try_llvm = TRUE;
8048 } else if (!strcmp (arg, "llvm")) {
8049 opts->llvm = TRUE;
8050 } else if (str_begins_with (arg, "readonly-value=")) {
8051 add_readonly_value (opts, arg + strlen ("readonly-value="));
8052 } else if (str_begins_with (arg, "info")) {
8053 printf ("AOT target setup: %s.\n", AOT_TARGET_STR);
8054 exit (0);
8055 // Intentionally undocumented: Used for precise stack maps, which are not available yet
8056 } else if (str_begins_with (arg, "gc-maps")) {
8057 mini_gc_enable_gc_maps_for_aot ();
8058 // Intentionally undocumented: Used for internal debugging
8059 } else if (str_begins_with (arg, "dump")) {
8060 opts->dump_json = TRUE;
8061 } else if (str_begins_with (arg, "llvmonly")) {
8062 opts->mode = MONO_AOT_MODE_FULL;
8063 opts->llvm = TRUE;
8064 opts->llvm_only = TRUE;
8065 } else if (str_begins_with (arg, "data-outfile=")) {
8066 opts->data_outfile = g_strdup (arg + strlen ("data-outfile="));
8067 } else if (str_begins_with (arg, "profile=")) {
8068 opts->profile_files = g_list_append (opts->profile_files, g_strdup (arg + strlen ("profile=")));
8069 } else if (!strcmp (arg, "profile-only")) {
8070 opts->profile_only = TRUE;
8071 } else if (!strcmp (arg, "verbose")) {
8072 opts->verbose = TRUE;
8073 } else if (str_begins_with (arg, "llvmopts=")){
8074 opts->llvm_opts = g_strdup (arg + strlen ("llvmopts="));
8075 } else if (str_begins_with (arg, "llvmllc=")){
8076 opts->llvm_llc = g_strdup (arg + strlen ("llvmllc="));
8077 } else if (!strcmp (arg, "deterministic")) {
8078 opts->deterministic = TRUE;
8079 } else if (!strcmp (arg, "no-opt")) {
8080 opts->no_opt = TRUE;
8081 } else if (str_begins_with (arg, "clangxx=")) {
8082 opts->clangxx = g_strdup (arg + strlen ("clangxx="));
8083 } else if (str_begins_with (arg, "depfile=")) {
8084 opts->depfile = g_strdup (arg + strlen ("depfile="));
8085 } else if (str_begins_with (arg, "help") || str_begins_with (arg, "?")) {
8086 printf ("Supported options for --aot:\n");
8087 printf (" asmonly\n");
8088 printf (" bind-to-runtime-version\n");
8089 printf (" bitcode\n");
8090 printf (" data-outfile=\n");
8091 printf (" direct-icalls\n");
8092 printf (" direct-pinvoke\n");
8093 printf (" dwarfdebug\n");
8094 printf (" full\n");
8095 printf (" hybrid\n");
8096 printf (" info\n");
8097 printf (" keep-temps\n");
8098 printf (" llvm\n");
8099 printf (" llvmonly\n");
8100 printf (" llvm-outfile=\n");
8101 printf (" llvm-path=\n");
8102 printf (" msym-dir=\n");
8103 printf (" mtriple\n");
8104 printf (" nimt-trampolines=\n");
8105 printf (" nodebug\n");
8106 printf (" no-direct-calls\n");
8107 printf (" no-write-symbols\n");
8108 printf (" nrgctx-trampolines=\n");
8109 printf (" nrgctx-fetch-trampolines=\n");
8110 printf (" ngsharedvt-trampolines=\n");
8111 printf (" nftnptr-arg-trampolines=\n");
8112 printf (" nunbox-arbitrary-trampolines=\n");
8113 printf (" ntrampolines=\n");
8114 printf (" outfile=\n");
8115 printf (" profile=\n");
8116 printf (" profile-only\n");
8117 printf (" print-skipped-methods\n");
8118 printf (" readonly-value=\n");
8119 printf (" save-temps\n");
8120 printf (" soft-debug\n");
8121 printf (" static\n");
8122 printf (" stats\n");
8123 printf (" temp-path=\n");
8124 printf (" tool-prefix=\n");
8125 printf (" threads=\n");
8126 printf (" write-symbols\n");
8127 printf (" verbose\n");
8128 printf (" no-opt\n");
8129 printf (" llvmopts=\n");
8130 printf (" llvmllc=\n");
8131 printf (" clangxx=\n");
8132 printf (" depfile=\n");
8133 printf (" help/?\n");
8134 exit (0);
8135 } else {
8136 fprintf (stderr, "AOT : Unknown argument '%s'.\n", arg);
8137 exit (1);
8140 g_free ((gpointer) arg);
8143 if (opts->use_trampolines_page) {
8144 opts->ntrampolines = 0;
8145 opts->nrgctx_trampolines = 0;
8146 opts->nimt_trampolines = 0;
8147 opts->ngsharedvt_arg_trampolines = 0;
8148 opts->nftnptr_arg_trampolines = 0;
8149 opts->nunbox_arbitrary_trampolines = 0;
8152 g_ptr_array_free (args, /*free_seg=*/TRUE);
8155 static void
8156 add_token_info_hash (gpointer key, gpointer value, gpointer user_data)
8158 MonoMethod *method = (MonoMethod*)key;
8159 MonoJumpInfoToken *ji = (MonoJumpInfoToken*)value;
8160 MonoAotCompile *acfg = (MonoAotCompile *)user_data;
8161 MonoJumpInfoToken *new_ji;
8163 new_ji = (MonoJumpInfoToken *)mono_mempool_alloc0 (acfg->mempool, sizeof (MonoJumpInfoToken));
8164 new_ji->image = ji->image;
8165 new_ji->token = ji->token;
8166 g_hash_table_insert (acfg->token_info_hash, method, new_ji);
8169 static gboolean
8170 can_encode_class (MonoAotCompile *acfg, MonoClass *klass)
8172 if (m_class_get_type_token (klass))
8173 return TRUE;
8174 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))
8175 return TRUE;
8176 if (m_class_get_rank (klass))
8177 return can_encode_class (acfg, m_class_get_element_class (klass));
8178 return FALSE;
8181 static gboolean
8182 can_encode_method (MonoAotCompile *acfg, MonoMethod *method)
8184 if (method->wrapper_type) {
8185 switch (method->wrapper_type) {
8186 case MONO_WRAPPER_NONE:
8187 case MONO_WRAPPER_REMOTING_INVOKE_WITH_CHECK:
8188 case MONO_WRAPPER_XDOMAIN_INVOKE:
8189 case MONO_WRAPPER_STFLD:
8190 case MONO_WRAPPER_LDFLD:
8191 case MONO_WRAPPER_LDFLDA:
8192 case MONO_WRAPPER_STELEMREF:
8193 case MONO_WRAPPER_PROXY_ISINST:
8194 case MONO_WRAPPER_ALLOC:
8195 case MONO_WRAPPER_REMOTING_INVOKE:
8196 case MONO_WRAPPER_OTHER:
8197 case MONO_WRAPPER_WRITE_BARRIER:
8198 case MONO_WRAPPER_DELEGATE_INVOKE:
8199 case MONO_WRAPPER_DELEGATE_BEGIN_INVOKE:
8200 case MONO_WRAPPER_DELEGATE_END_INVOKE:
8201 case MONO_WRAPPER_SYNCHRONIZED:
8202 case MONO_WRAPPER_MANAGED_TO_NATIVE:
8203 break;
8204 case MONO_WRAPPER_MANAGED_TO_MANAGED:
8205 case MONO_WRAPPER_CASTCLASS: {
8206 WrapperInfo *info = mono_marshal_get_wrapper_info (method);
8208 if (info)
8209 return TRUE;
8210 else
8211 return FALSE;
8212 break;
8214 default:
8215 //printf ("Skip (wrapper call): %d -> %s\n", patch_info->type, mono_method_full_name (patch_info->data.method, TRUE));
8216 return FALSE;
8218 } else {
8219 if (!method->token) {
8220 /* The method is part of a constructed type like Int[,].Set (). */
8221 if (!g_hash_table_lookup (acfg->token_info_hash, method)) {
8222 if (m_class_get_rank (method->klass))
8223 return TRUE;
8224 return FALSE;
8228 return TRUE;
8231 static gboolean
8232 can_encode_patch (MonoAotCompile *acfg, MonoJumpInfo *patch_info)
8234 switch (patch_info->type) {
8235 case MONO_PATCH_INFO_METHOD:
8236 case MONO_PATCH_INFO_METHOD_FTNDESC:
8237 case MONO_PATCH_INFO_METHODCONST:
8238 case MONO_PATCH_INFO_METHOD_CODE_SLOT: {
8239 MonoMethod *method = patch_info->data.method;
8241 return can_encode_method (acfg, method);
8243 case MONO_PATCH_INFO_VTABLE:
8244 case MONO_PATCH_INFO_CLASS:
8245 case MONO_PATCH_INFO_IID:
8246 case MONO_PATCH_INFO_ADJUSTED_IID:
8247 if (!can_encode_class (acfg, patch_info->data.klass)) {
8248 //printf ("Skip: %s\n", mono_type_full_name (m_class_get_byval_arg (patch_info->data.klass)));
8249 return FALSE;
8251 break;
8252 case MONO_PATCH_INFO_DELEGATE_TRAMPOLINE: {
8253 if (!can_encode_class (acfg, patch_info->data.del_tramp->klass)) {
8254 //printf ("Skip: %s\n", mono_type_full_name (m_class_get_byval_arg (patch_info->data.klass)));
8255 return FALSE;
8257 break;
8259 case MONO_PATCH_INFO_RGCTX_FETCH:
8260 case MONO_PATCH_INFO_RGCTX_SLOT_INDEX: {
8261 MonoJumpInfoRgctxEntry *entry = patch_info->data.rgctx_entry;
8263 if (entry->in_mrgctx) {
8264 if (!can_encode_method (acfg, entry->d.method))
8265 return FALSE;
8266 } else {
8267 if (!can_encode_class (acfg, entry->d.klass))
8268 return FALSE;
8270 if (!can_encode_patch (acfg, entry->data))
8271 return FALSE;
8272 break;
8274 default:
8275 break;
8278 return TRUE;
8281 static gboolean
8282 is_concrete_type (MonoType *t)
8284 MonoClass *klass;
8285 int i;
8287 if (t->type == MONO_TYPE_VAR || t->type == MONO_TYPE_MVAR)
8288 return FALSE;
8289 if (t->type == MONO_TYPE_GENERICINST) {
8290 MonoGenericContext *orig_ctx;
8291 MonoGenericInst *inst;
8292 MonoType *arg;
8294 if (!MONO_TYPE_ISSTRUCT (t))
8295 return TRUE;
8296 klass = mono_class_from_mono_type_internal (t);
8297 orig_ctx = &mono_class_get_generic_class (klass)->context;
8299 inst = orig_ctx->class_inst;
8300 if (inst) {
8301 for (i = 0; i < inst->type_argc; ++i) {
8302 arg = mini_get_underlying_type (inst->type_argv [i]);
8303 if (!is_concrete_type (arg))
8304 return FALSE;
8307 inst = orig_ctx->method_inst;
8308 if (inst) {
8309 for (i = 0; i < inst->type_argc; ++i) {
8310 arg = mini_get_underlying_type (inst->type_argv [i]);
8311 if (!is_concrete_type (arg))
8312 return FALSE;
8316 return TRUE;
8319 static MonoMethodSignature*
8320 get_concrete_sig (MonoMethodSignature *sig)
8322 gboolean concrete = TRUE;
8324 if (!sig->has_type_parameters)
8325 return sig;
8327 /* For signatures created during generic sharing, convert them to a concrete signature if possible */
8328 MonoMethodSignature *copy = mono_metadata_signature_dup (sig);
8329 int i;
8331 //printf ("%s\n", mono_signature_full_name (sig));
8333 if (sig->ret->byref)
8334 copy->ret = m_class_get_this_arg (mono_defaults.int_class);
8335 else
8336 copy->ret = mini_get_underlying_type (sig->ret);
8337 if (!is_concrete_type (copy->ret))
8338 concrete = FALSE;
8339 for (i = 0; i < sig->param_count; ++i) {
8340 if (sig->params [i]->byref) {
8341 MonoType *t = m_class_get_byval_arg (mono_class_from_mono_type_internal (sig->params [i]));
8342 t = mini_get_underlying_type (t);
8343 copy->params [i] = m_class_get_this_arg (mono_class_from_mono_type_internal (t));
8344 } else {
8345 copy->params [i] = mini_get_underlying_type (sig->params [i]);
8347 if (!is_concrete_type (copy->params [i]))
8348 concrete = FALSE;
8350 copy->has_type_parameters = 0;
8351 if (!concrete)
8352 return NULL;
8353 return copy;
8356 /* LOCKING: Assumes the loader lock is held */
8357 static void
8358 add_gsharedvt_wrappers (MonoAotCompile *acfg, MonoMethodSignature *sig, gboolean gsharedvt_in, gboolean gsharedvt_out, gboolean interp_in)
8360 MonoMethod *wrapper;
8361 gboolean add_in = gsharedvt_in;
8362 gboolean add_out = gsharedvt_out;
8364 if (gsharedvt_in && g_hash_table_lookup (acfg->gsharedvt_in_signatures, sig))
8365 add_in = FALSE;
8366 if (gsharedvt_out && g_hash_table_lookup (acfg->gsharedvt_out_signatures, sig))
8367 add_out = FALSE;
8369 if (!add_in && !add_out)
8370 return;
8372 if (mini_is_gsharedvt_variable_signature (sig))
8373 return;
8375 if (add_in)
8376 g_hash_table_insert (acfg->gsharedvt_in_signatures, sig, sig);
8377 if (add_out)
8378 g_hash_table_insert (acfg->gsharedvt_out_signatures, sig, sig);
8380 sig = get_concrete_sig (sig);
8381 if (!sig)
8382 return;
8383 //printf ("%s\n", mono_signature_full_name (sig));
8385 if (gsharedvt_in) {
8386 wrapper = mini_get_gsharedvt_in_sig_wrapper (sig);
8387 add_extra_method (acfg, wrapper);
8389 if (gsharedvt_out) {
8390 wrapper = mini_get_gsharedvt_out_sig_wrapper (sig);
8391 add_extra_method (acfg, wrapper);
8394 #ifndef MONO_ARCH_HAVE_INTERP_ENTRY_TRAMPOLINE
8395 if (interp_in) {
8396 wrapper = mini_get_interp_in_wrapper (sig);
8397 add_extra_method (acfg, wrapper);
8398 //printf ("X: %s\n", mono_method_full_name (wrapper, 1));
8400 #endif
8404 * compile_method:
8406 * AOT compile a given method.
8407 * This function might be called by multiple threads, so it must be thread-safe.
8409 static void
8410 compile_method (MonoAotCompile *acfg, MonoMethod *method)
8412 MonoCompile *cfg;
8413 MonoJumpInfo *patch_info;
8414 gboolean skip;
8415 int index, depth;
8416 MonoMethod *wrapped;
8417 gint64 jit_time_start;
8418 JitFlags flags;
8420 if (acfg->aot_opts.metadata_only)
8421 return;
8423 mono_acfg_lock (acfg);
8424 index = get_method_index (acfg, method);
8425 mono_acfg_unlock (acfg);
8427 /* fixme: maybe we can also precompile wrapper methods */
8428 if ((method->flags & METHOD_ATTRIBUTE_PINVOKE_IMPL) ||
8429 (method->iflags & METHOD_IMPL_ATTRIBUTE_RUNTIME) ||
8430 (method->flags & METHOD_ATTRIBUTE_ABSTRACT)) {
8431 //printf ("Skip (impossible): %s\n", mono_method_full_name (method, TRUE));
8432 return;
8435 if (method->iflags & METHOD_IMPL_ATTRIBUTE_INTERNAL_CALL)
8436 return;
8438 wrapped = mono_marshal_method_from_wrapper (method);
8439 if (wrapped && (wrapped->iflags & METHOD_IMPL_ATTRIBUTE_INTERNAL_CALL) && wrapped->is_generic)
8440 // FIXME: The wrapper should be generic too, but it is not
8441 return;
8443 if (method->wrapper_type == MONO_WRAPPER_COMINTEROP)
8444 return;
8446 if (acfg->aot_opts.profile_only && !method->is_inflated && !g_hash_table_lookup (acfg->profile_methods, method))
8447 return;
8449 mono_atomic_inc_i32 (&acfg->stats.mcount);
8451 #if 0
8452 if (method->is_generic || mono_class_is_gtd (method->klass)) {
8453 mono_atomic_inc_i32 (&acfg->stats.genericcount);
8454 return;
8456 #endif
8458 //acfg->aot_opts.print_skipped_methods = TRUE;
8461 * Since these methods are the only ones which are compiled with
8462 * AOT support, and they are not used by runtime startup/shutdown code,
8463 * the runtime will not see AOT methods during AOT compilation,so it
8464 * does not need to support them by creating a fake GOT etc.
8466 flags = JIT_FLAG_AOT;
8467 if (mono_aot_mode_is_full (&acfg->aot_opts))
8468 flags = (JitFlags)(flags | JIT_FLAG_FULL_AOT);
8469 if (acfg->llvm)
8470 flags = (JitFlags)(flags | JIT_FLAG_LLVM);
8471 if (acfg->aot_opts.llvm_only)
8472 flags = (JitFlags)(flags | JIT_FLAG_LLVM_ONLY | JIT_FLAG_EXPLICIT_NULL_CHECKS);
8473 if (acfg->aot_opts.no_direct_calls)
8474 flags = (JitFlags)(flags | JIT_FLAG_NO_DIRECT_ICALLS);
8475 if (acfg->aot_opts.direct_pinvoke)
8476 flags = (JitFlags)(flags | JIT_FLAG_DIRECT_PINVOKE);
8477 if (acfg->aot_opts.interp)
8478 flags = (JitFlags)(flags | JIT_FLAG_INTERP);
8480 jit_time_start = mono_time_track_start ();
8481 cfg = mini_method_compile (method, acfg->opts, mono_get_root_domain (), flags, 0, index);
8482 mono_time_track_end (&mono_jit_stats.jit_time, jit_time_start);
8484 if (cfg->exception_type == MONO_EXCEPTION_GENERIC_SHARING_FAILED) {
8485 if (acfg->aot_opts.print_skipped_methods)
8486 printf ("Skip (gshared failure): %s (%s)\n", mono_method_get_full_name (method), cfg->exception_message);
8487 mono_atomic_inc_i32 (&acfg->stats.genericcount);
8488 return;
8490 if (cfg->exception_type != MONO_EXCEPTION_NONE) {
8491 /* Some instances cannot be JITted due to constraints etc. */
8492 if (!method->is_inflated)
8493 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));
8494 /* Let the exception happen at runtime */
8495 return;
8498 if (cfg->disable_aot) {
8499 if (acfg->aot_opts.print_skipped_methods)
8500 printf ("Skip (disabled): %s\n", mono_method_get_full_name (method));
8501 mono_atomic_inc_i32 (&acfg->stats.ocount);
8502 return;
8504 cfg->method_index = index;
8506 /* Nullify patches which need no aot processing */
8507 for (patch_info = cfg->patch_info; patch_info; patch_info = patch_info->next) {
8508 switch (patch_info->type) {
8509 case MONO_PATCH_INFO_LABEL:
8510 case MONO_PATCH_INFO_BB:
8511 patch_info->type = MONO_PATCH_INFO_NONE;
8512 break;
8513 default:
8514 break;
8518 /* Collect method->token associations from the cfg */
8519 mono_acfg_lock (acfg);
8520 g_hash_table_foreach (cfg->token_info_hash, add_token_info_hash, acfg);
8521 mono_acfg_unlock (acfg);
8522 g_hash_table_destroy (cfg->token_info_hash);
8523 cfg->token_info_hash = NULL;
8526 * Check for absolute addresses.
8528 skip = FALSE;
8529 for (patch_info = cfg->patch_info; patch_info; patch_info = patch_info->next) {
8530 switch (patch_info->type) {
8531 case MONO_PATCH_INFO_ABS:
8532 /* unable to handle this */
8533 skip = TRUE;
8534 break;
8535 default:
8536 break;
8540 if (skip) {
8541 if (acfg->aot_opts.print_skipped_methods)
8542 printf ("Skip (abs call): %s\n", mono_method_get_full_name (method));
8543 mono_atomic_inc_i32 (&acfg->stats.abscount);
8544 return;
8547 /* Lock for the rest of the code */
8548 mono_acfg_lock (acfg);
8550 if (cfg->gsharedvt)
8551 acfg->stats.method_categories [METHOD_CAT_GSHAREDVT] ++;
8552 else if (cfg->gshared)
8553 acfg->stats.method_categories [METHOD_CAT_INST] ++;
8554 else if (cfg->method->wrapper_type)
8555 acfg->stats.method_categories [METHOD_CAT_WRAPPER] ++;
8556 else
8557 acfg->stats.method_categories [METHOD_CAT_NORMAL] ++;
8560 * Check for methods/klasses we can't encode.
8562 skip = FALSE;
8563 for (patch_info = cfg->patch_info; patch_info; patch_info = patch_info->next) {
8564 if (!can_encode_patch (acfg, patch_info))
8565 skip = TRUE;
8568 if (skip) {
8569 if (acfg->aot_opts.print_skipped_methods)
8570 printf ("Skip (patches): %s\n", mono_method_get_full_name (method));
8571 acfg->stats.ocount++;
8572 mono_acfg_unlock (acfg);
8573 return;
8576 if (!cfg->compile_llvm)
8577 acfg->has_jitted_code = TRUE;
8579 if (method->is_inflated && acfg->aot_opts.log_instances) {
8580 if (acfg->instances_logfile)
8581 fprintf (acfg->instances_logfile, "%s ### %d\n", mono_method_get_full_name (method), cfg->code_size);
8582 else
8583 printf ("%s ### %d\n", mono_method_get_full_name (method), cfg->code_size);
8586 /* Adds generic instances referenced by this method */
8588 * The depth is used to avoid infinite loops when generic virtual recursion is
8589 * encountered.
8591 depth = GPOINTER_TO_UINT (g_hash_table_lookup (acfg->method_depth, method));
8592 if (!acfg->aot_opts.no_instances && depth < 32 && (mono_aot_mode_is_full (&acfg->aot_opts) || mono_aot_mode_is_hybrid (&acfg->aot_opts))) {
8593 for (patch_info = cfg->patch_info; patch_info; patch_info = patch_info->next) {
8594 switch (patch_info->type) {
8595 case MONO_PATCH_INFO_RGCTX_FETCH:
8596 case MONO_PATCH_INFO_RGCTX_SLOT_INDEX:
8597 case MONO_PATCH_INFO_METHOD:
8598 case MONO_PATCH_INFO_METHOD_FTNDESC:
8599 case MONO_PATCH_INFO_METHOD_RGCTX: {
8600 MonoMethod *m = NULL;
8602 if (patch_info->type == MONO_PATCH_INFO_RGCTX_FETCH || patch_info->type == MONO_PATCH_INFO_RGCTX_SLOT_INDEX) {
8603 MonoJumpInfoRgctxEntry *e = patch_info->data.rgctx_entry;
8605 if (e->info_type == MONO_RGCTX_INFO_GENERIC_METHOD_CODE || e->info_type == MONO_RGCTX_INFO_METHOD_FTNDESC)
8606 m = e->data->data.method;
8607 } else {
8608 m = patch_info->data.method;
8611 if (!m)
8612 break;
8613 if (m->is_inflated && (mono_aot_mode_is_full (&acfg->aot_opts) || mono_aot_mode_is_hybrid (&acfg->aot_opts))) {
8614 if (!(mono_class_generic_sharing_enabled (m->klass) &&
8615 mono_method_is_generic_sharable_full (m, FALSE, FALSE, FALSE)) &&
8616 (!method_has_type_vars (m) || mono_method_is_generic_sharable_full (m, TRUE, TRUE, FALSE))) {
8617 if (m->iflags & METHOD_IMPL_ATTRIBUTE_INTERNAL_CALL) {
8618 if (mono_aot_mode_is_full (&acfg->aot_opts) && !method_has_type_vars (m))
8619 add_extra_method_with_depth (acfg, mono_marshal_get_native_wrapper (m, TRUE, TRUE), depth + 1);
8620 } else {
8621 add_extra_method_with_depth (acfg, m, depth + 1);
8622 add_types_from_method_header (acfg, m);
8625 add_generic_class_with_depth (acfg, m->klass, depth + 5, "method");
8627 if (m->wrapper_type == MONO_WRAPPER_MANAGED_TO_MANAGED) {
8628 WrapperInfo *info = mono_marshal_get_wrapper_info (m);
8630 if (info && info->subtype == WRAPPER_SUBTYPE_ELEMENT_ADDR)
8631 add_extra_method_with_depth (acfg, m, depth + 1);
8633 break;
8635 case MONO_PATCH_INFO_VTABLE: {
8636 MonoClass *klass = patch_info->data.klass;
8638 if (mono_class_is_ginst (klass) && !mini_class_is_generic_sharable (klass))
8639 add_generic_class_with_depth (acfg, klass, depth + 5, "vtable");
8640 break;
8642 case MONO_PATCH_INFO_SFLDA: {
8643 MonoClass *klass = patch_info->data.field->parent;
8645 /* The .cctor needs to run at runtime. */
8646 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))
8647 add_extra_method_with_depth (acfg, mono_class_get_cctor (klass), depth + 1);
8648 break;
8650 default:
8651 break;
8656 /* Determine whenever the method has GOT slots */
8657 for (patch_info = cfg->patch_info; patch_info; patch_info = patch_info->next) {
8658 switch (patch_info->type) {
8659 case MONO_PATCH_INFO_GOT_OFFSET:
8660 case MONO_PATCH_INFO_NONE:
8661 case MONO_PATCH_INFO_GC_CARD_TABLE_ADDR:
8662 case MONO_PATCH_INFO_GC_NURSERY_START:
8663 case MONO_PATCH_INFO_GC_NURSERY_BITS:
8664 break;
8665 case MONO_PATCH_INFO_IMAGE:
8666 /* The assembly is stored in GOT slot 0 */
8667 if (patch_info->data.image != acfg->image)
8668 cfg->has_got_slots = TRUE;
8669 break;
8670 default:
8671 if (!is_plt_patch (patch_info) || (cfg->compile_llvm && acfg->aot_opts.llvm_only))
8672 cfg->has_got_slots = TRUE;
8673 break;
8677 if (!cfg->has_got_slots)
8678 mono_atomic_inc_i32 (&acfg->stats.methods_without_got_slots);
8680 /* Add gsharedvt wrappers for signatures used by the method */
8681 if (acfg->aot_opts.llvm_only) {
8682 GSList *l;
8684 if (!cfg->method->wrapper_type || cfg->method->wrapper_type == MONO_WRAPPER_DELEGATE_INVOKE)
8685 /* These only need out wrappers */
8686 add_gsharedvt_wrappers (acfg, mono_method_signature_internal (cfg->method), FALSE, TRUE, FALSE);
8688 for (l = cfg->signatures; l; l = l->next) {
8689 MonoMethodSignature *sig = mono_metadata_signature_dup ((MonoMethodSignature*)l->data);
8691 /* These only need in wrappers */
8692 add_gsharedvt_wrappers (acfg, sig, TRUE, FALSE, FALSE);
8695 for (l = cfg->interp_in_signatures; l; l = l->next) {
8696 MonoMethodSignature *sig = mono_metadata_signature_dup ((MonoMethodSignature*)l->data);
8698 add_gsharedvt_wrappers (acfg, sig, TRUE, FALSE, FALSE);
8700 } else if (mono_aot_mode_is_full (&acfg->aot_opts) && mono_aot_mode_is_interp (&acfg->aot_opts)) {
8701 /* The interpreter uses these wrappers to call aot-ed code */
8702 if (!cfg->method->wrapper_type || cfg->method->wrapper_type == MONO_WRAPPER_DELEGATE_INVOKE)
8703 add_gsharedvt_wrappers (acfg, mono_method_signature_internal (cfg->method), FALSE, TRUE, TRUE);
8706 if (cfg->llvm_only)
8707 acfg->stats.llvm_count ++;
8710 * FIXME: Instead of this mess, allocate the patches from the aot mempool.
8712 /* Make a copy of the patch info which is in the mempool */
8714 MonoJumpInfo *patches = NULL, *patches_end = NULL;
8716 for (patch_info = cfg->patch_info; patch_info; patch_info = patch_info->next) {
8717 MonoJumpInfo *new_patch_info = mono_patch_info_dup_mp (acfg->mempool, patch_info);
8719 if (!patches)
8720 patches = new_patch_info;
8721 else
8722 patches_end->next = new_patch_info;
8723 patches_end = new_patch_info;
8725 cfg->patch_info = patches;
8727 /* Make a copy of the unwind info */
8729 GSList *l, *unwind_ops;
8730 MonoUnwindOp *op;
8732 unwind_ops = NULL;
8733 for (l = cfg->unwind_ops; l; l = l->next) {
8734 op = (MonoUnwindOp *)mono_mempool_alloc (acfg->mempool, sizeof (MonoUnwindOp));
8735 memcpy (op, l->data, sizeof (MonoUnwindOp));
8736 unwind_ops = g_slist_prepend_mempool (acfg->mempool, unwind_ops, op);
8738 cfg->unwind_ops = g_slist_reverse (unwind_ops);
8740 /* Make a copy of the argument/local info */
8742 ERROR_DECL (error);
8743 MonoInst **args, **locals;
8744 MonoMethodSignature *sig;
8745 MonoMethodHeader *header;
8746 int i;
8748 sig = mono_method_signature_internal (method);
8749 args = (MonoInst **)mono_mempool_alloc (acfg->mempool, sizeof (MonoInst*) * (sig->param_count + sig->hasthis));
8750 for (i = 0; i < sig->param_count + sig->hasthis; ++i) {
8751 args [i] = (MonoInst *)mono_mempool_alloc (acfg->mempool, sizeof (MonoInst));
8752 memcpy (args [i], cfg->args [i], sizeof (MonoInst));
8754 cfg->args = args;
8756 header = mono_method_get_header_checked (method, error);
8757 mono_error_assert_ok (error); /* FIXME don't swallow the error */
8758 locals = (MonoInst **)mono_mempool_alloc (acfg->mempool, sizeof (MonoInst*) * header->num_locals);
8759 for (i = 0; i < header->num_locals; ++i) {
8760 locals [i] = (MonoInst *)mono_mempool_alloc (acfg->mempool, sizeof (MonoInst));
8761 memcpy (locals [i], cfg->locals [i], sizeof (MonoInst));
8763 mono_metadata_free_mh (header);
8764 cfg->locals = locals;
8767 /* Free some fields used by cfg to conserve memory */
8768 mono_empty_compile (cfg);
8770 //printf ("Compile: %s\n", mono_method_full_name (method, TRUE));
8772 while (index >= acfg->cfgs_size) {
8773 MonoCompile **new_cfgs;
8774 int new_size;
8776 new_size = acfg->cfgs_size * 2;
8777 new_cfgs = g_new0 (MonoCompile*, new_size);
8778 memcpy (new_cfgs, acfg->cfgs, sizeof (MonoCompile*) * acfg->cfgs_size);
8779 g_free (acfg->cfgs);
8780 acfg->cfgs = new_cfgs;
8781 acfg->cfgs_size = new_size;
8783 acfg->cfgs [index] = cfg;
8785 g_hash_table_insert (acfg->method_to_cfg, cfg->orig_method, cfg);
8787 /* Update global stats while holding a lock. */
8788 mono_update_jit_stats (cfg);
8791 if (cfg->orig_method->wrapper_type)
8792 g_ptr_array_add (acfg->extra_methods, cfg->orig_method);
8795 mono_acfg_unlock (acfg);
8797 mono_atomic_inc_i32 (&acfg->stats.ccount);
8800 static mono_thread_start_return_t WINAPI
8801 compile_thread_main (gpointer user_data)
8803 MonoAotCompile *acfg = ((MonoAotCompile **)user_data) [0];
8804 GPtrArray *methods = ((GPtrArray **)user_data) [1];
8805 int i;
8807 ERROR_DECL (error);
8808 MonoInternalThread *internal = mono_thread_internal_current ();
8809 MonoString *str = mono_string_new_checked (mono_domain_get (), "AOT compiler", error);
8810 mono_error_assert_ok (error);
8811 mono_thread_set_name_internal (internal, str, TRUE, FALSE, error);
8812 mono_error_assert_ok (error);
8814 for (i = 0; i < methods->len; ++i)
8815 compile_method (acfg, (MonoMethod *)g_ptr_array_index (methods, i));
8817 return 0;
8820 /* Used by the LLVM backend */
8821 guint32
8822 mono_aot_get_got_offset (MonoJumpInfo *ji)
8824 return get_got_offset (llvm_acfg, TRUE, ji);
8828 * mono_aot_is_shared_got_offset:
8830 * Return whenever OFFSET refers to a GOT slot which is preinitialized
8831 * when the AOT image is loaded.
8833 gboolean
8834 mono_aot_is_shared_got_offset (int offset)
8836 return offset < llvm_acfg->nshared_got_entries;
8839 char*
8840 mono_aot_get_method_name (MonoCompile *cfg)
8842 MonoMethod *method = cfg->orig_method;
8844 /* Use the mangled name if possible */
8845 if (method->wrapper_type == MONO_WRAPPER_OTHER) {
8846 WrapperInfo *info = mono_marshal_get_wrapper_info (method);
8847 if (info->subtype == WRAPPER_SUBTYPE_GSHAREDVT_IN_SIG || info->subtype == WRAPPER_SUBTYPE_GSHAREDVT_OUT_SIG)
8848 return mono_aot_get_mangled_method_name (method);
8851 if (llvm_acfg->aot_opts.static_link)
8852 /* Include the assembly name too to avoid duplicate symbol errors */
8853 return g_strdup_printf ("%s_%s", llvm_acfg->assembly_name_sym, get_debug_sym (cfg->orig_method, "", llvm_acfg->method_label_hash));
8854 else
8855 return get_debug_sym (cfg->orig_method, "", llvm_acfg->method_label_hash);
8858 static gboolean
8859 append_mangled_type (GString *s, MonoType *t)
8861 if (t->byref)
8862 g_string_append_printf (s, "b");
8863 switch (t->type) {
8864 case MONO_TYPE_VOID:
8865 g_string_append_printf (s, "void");
8866 break;
8867 case MONO_TYPE_I1:
8868 g_string_append_printf (s, "i1");
8869 break;
8870 case MONO_TYPE_U1:
8871 g_string_append_printf (s, "u1");
8872 break;
8873 case MONO_TYPE_I2:
8874 g_string_append_printf (s, "i2");
8875 break;
8876 case MONO_TYPE_U2:
8877 g_string_append_printf (s, "u2");
8878 break;
8879 case MONO_TYPE_I4:
8880 g_string_append_printf (s, "i4");
8881 break;
8882 case MONO_TYPE_U4:
8883 g_string_append_printf (s, "u4");
8884 break;
8885 case MONO_TYPE_I8:
8886 g_string_append_printf (s, "i8");
8887 break;
8888 case MONO_TYPE_U8:
8889 g_string_append_printf (s, "u8");
8890 break;
8891 case MONO_TYPE_I:
8892 g_string_append_printf (s, "ii");
8893 break;
8894 case MONO_TYPE_U:
8895 g_string_append_printf (s, "ui");
8896 break;
8897 case MONO_TYPE_R4:
8898 g_string_append_printf (s, "fl");
8899 break;
8900 case MONO_TYPE_R8:
8901 g_string_append_printf (s, "do");
8902 break;
8903 case MONO_TYPE_OBJECT:
8904 g_string_append_printf (s, "obj");
8905 break;
8906 default: {
8907 char *fullname = mono_type_full_name (t);
8908 GString *temp;
8909 char *temps;
8910 int i, len;
8913 * Have to create a mangled name which is:
8914 * - a valid symbol
8915 * - unique
8917 temp = g_string_new ("");
8918 len = strlen (fullname);
8919 for (i = 0; i < len; ++i) {
8920 char c = fullname [i];
8921 if (isalnum (c)) {
8922 g_string_append_c (temp, c);
8923 } else if (c == '_') {
8924 g_string_append_c (temp, '_');
8925 g_string_append_c (temp, '_');
8926 } else {
8927 g_string_append_c (temp, '_');
8928 g_string_append_printf (temp, "%x", (int)c);
8931 temps = g_string_free (temp, FALSE);
8932 /* Include the length to avoid different length type names aliasing each other */
8933 g_string_append_printf (s, "cl%x_%s_", (int)strlen (temps), temps);
8934 g_free (temps);
8937 if (t->attrs)
8938 g_string_append_printf (s, "_attrs_%d", t->attrs);
8939 return TRUE;
8942 static gboolean
8943 append_mangled_signature (GString *s, MonoMethodSignature *sig)
8945 int i;
8946 gboolean supported;
8948 if (sig->pinvoke)
8949 g_string_append_printf (s, "pinvoke_");
8950 supported = append_mangled_type (s, sig->ret);
8951 if (!supported)
8952 return FALSE;
8953 g_string_append_printf (s, "_");
8954 if (sig->hasthis)
8955 g_string_append_printf (s, "this_");
8956 for (i = 0; i < sig->param_count; ++i) {
8957 supported = append_mangled_type (s, sig->params [i]);
8958 if (!supported)
8959 return FALSE;
8962 return TRUE;
8965 static void
8966 append_mangled_wrapper_type (GString *s, guint32 wrapper_type)
8968 const char *label;
8970 switch (wrapper_type) {
8971 case MONO_WRAPPER_REMOTING_INVOKE:
8972 label = "remoting_invoke";
8973 break;
8974 case MONO_WRAPPER_REMOTING_INVOKE_WITH_CHECK:
8975 label = "remoting_invoke_check";
8976 break;
8977 case MONO_WRAPPER_XDOMAIN_INVOKE:
8978 label = "remoting_invoke_xdomain";
8979 break;
8980 case MONO_WRAPPER_PROXY_ISINST:
8981 label = "proxy_isinst";
8982 break;
8983 case MONO_WRAPPER_LDFLD:
8984 label = "ldfld";
8985 break;
8986 case MONO_WRAPPER_LDFLDA:
8987 label = "ldflda";
8988 break;
8989 case MONO_WRAPPER_STFLD:
8990 label = "stfld";
8991 break;
8992 case MONO_WRAPPER_ALLOC:
8993 label = "alloc";
8994 break;
8995 case MONO_WRAPPER_WRITE_BARRIER:
8996 label = "write_barrier";
8997 break;
8998 case MONO_WRAPPER_STELEMREF:
8999 label = "stelemref";
9000 break;
9001 case MONO_WRAPPER_OTHER:
9002 label = "unknown";
9003 break;
9004 case MONO_WRAPPER_MANAGED_TO_NATIVE:
9005 label = "man2native";
9006 break;
9007 case MONO_WRAPPER_SYNCHRONIZED:
9008 label = "synch";
9009 break;
9010 case MONO_WRAPPER_MANAGED_TO_MANAGED:
9011 label = "man2man";
9012 break;
9013 case MONO_WRAPPER_CASTCLASS:
9014 label = "castclass";
9015 break;
9016 case MONO_WRAPPER_RUNTIME_INVOKE:
9017 label = "run_invoke";
9018 break;
9019 case MONO_WRAPPER_DELEGATE_INVOKE:
9020 label = "del_inv";
9021 break;
9022 case MONO_WRAPPER_DELEGATE_BEGIN_INVOKE:
9023 label = "del_beg_inv";
9024 break;
9025 case MONO_WRAPPER_DELEGATE_END_INVOKE:
9026 label = "del_end_inv";
9027 break;
9028 case MONO_WRAPPER_NATIVE_TO_MANAGED:
9029 label = "native2man";
9030 break;
9031 default:
9032 g_assert_not_reached ();
9035 g_string_append_printf (s, "%s_", label);
9038 static void
9039 append_mangled_wrapper_subtype (GString *s, WrapperSubtype subtype)
9041 const char *label;
9043 switch (subtype)
9045 case WRAPPER_SUBTYPE_NONE:
9046 return;
9047 case WRAPPER_SUBTYPE_ELEMENT_ADDR:
9048 label = "elem_addr";
9049 break;
9050 case WRAPPER_SUBTYPE_STRING_CTOR:
9051 label = "str_ctor";
9052 break;
9053 case WRAPPER_SUBTYPE_VIRTUAL_STELEMREF:
9054 label = "virt_stelem";
9055 break;
9056 case WRAPPER_SUBTYPE_FAST_MONITOR_ENTER:
9057 label = "fast_mon_enter";
9058 break;
9059 case WRAPPER_SUBTYPE_FAST_MONITOR_ENTER_V4:
9060 label = "fast_mon_enter_4";
9061 break;
9062 case WRAPPER_SUBTYPE_FAST_MONITOR_EXIT:
9063 label = "fast_monitor_exit";
9064 break;
9065 case WRAPPER_SUBTYPE_PTR_TO_STRUCTURE:
9066 label = "ptr2struct";
9067 break;
9068 case WRAPPER_SUBTYPE_STRUCTURE_TO_PTR:
9069 label = "struct2ptr";
9070 break;
9071 case WRAPPER_SUBTYPE_CASTCLASS_WITH_CACHE:
9072 label = "castclass_w_cache";
9073 break;
9074 case WRAPPER_SUBTYPE_ISINST_WITH_CACHE:
9075 label = "isinst_w_cache";
9076 break;
9077 case WRAPPER_SUBTYPE_RUNTIME_INVOKE_NORMAL:
9078 label = "run_inv_norm";
9079 break;
9080 case WRAPPER_SUBTYPE_RUNTIME_INVOKE_DYNAMIC:
9081 label = "run_inv_dyn";
9082 break;
9083 case WRAPPER_SUBTYPE_RUNTIME_INVOKE_DIRECT:
9084 label = "run_inv_dir";
9085 break;
9086 case WRAPPER_SUBTYPE_RUNTIME_INVOKE_VIRTUAL:
9087 label = "run_inv_vir";
9088 break;
9089 case WRAPPER_SUBTYPE_ICALL_WRAPPER:
9090 label = "icall";
9091 break;
9092 case WRAPPER_SUBTYPE_NATIVE_FUNC_AOT:
9093 label = "native_func_aot";
9094 break;
9095 case WRAPPER_SUBTYPE_PINVOKE:
9096 label = "pinvoke";
9097 break;
9098 case WRAPPER_SUBTYPE_SYNCHRONIZED_INNER:
9099 label = "synch_inner";
9100 break;
9101 case WRAPPER_SUBTYPE_GSHAREDVT_IN:
9102 label = "gshared_in";
9103 break;
9104 case WRAPPER_SUBTYPE_GSHAREDVT_OUT:
9105 label = "gshared_out";
9106 break;
9107 case WRAPPER_SUBTYPE_ARRAY_ACCESSOR:
9108 label = "array_acc";
9109 break;
9110 case WRAPPER_SUBTYPE_GENERIC_ARRAY_HELPER:
9111 label = "generic_arry_help";
9112 break;
9113 case WRAPPER_SUBTYPE_DELEGATE_INVOKE_VIRTUAL:
9114 label = "del_inv_virt";
9115 break;
9116 case WRAPPER_SUBTYPE_DELEGATE_INVOKE_BOUND:
9117 label = "del_inv_bound";
9118 break;
9119 case WRAPPER_SUBTYPE_INTERP_IN:
9120 label = "interp_in";
9121 break;
9122 case WRAPPER_SUBTYPE_INTERP_LMF:
9123 label = "interp_lmf";
9124 break;
9125 case WRAPPER_SUBTYPE_GSHAREDVT_IN_SIG:
9126 label = "gsharedvt_in_sig";
9127 break;
9128 case WRAPPER_SUBTYPE_GSHAREDVT_OUT_SIG:
9129 label = "gsharedvt_out_sig";
9130 break;
9131 case WRAPPER_SUBTYPE_AOT_INIT:
9132 label = "aot_init";
9133 break;
9134 default:
9135 g_assert_not_reached ();
9138 g_string_append_printf (s, "%s_", label);
9141 static char *
9142 sanitize_mangled_string (const char *input)
9144 GString *s = g_string_new ("");
9146 for (int i=0; input [i] != '\0'; i++) {
9147 char c = input [i];
9148 switch (c) {
9149 case '.':
9150 g_string_append (s, "_dot_");
9151 break;
9152 case ' ':
9153 g_string_append (s, "_");
9154 break;
9155 case '`':
9156 g_string_append (s, "_bt_");
9157 break;
9158 case '<':
9159 g_string_append (s, "_le_");
9160 break;
9161 case '>':
9162 g_string_append (s, "_gt_");
9163 break;
9164 case '/':
9165 g_string_append (s, "_sl_");
9166 break;
9167 case '[':
9168 g_string_append (s, "_lbrack_");
9169 break;
9170 case ']':
9171 g_string_append (s, "_rbrack_");
9172 break;
9173 case '(':
9174 g_string_append (s, "_lparen_");
9175 break;
9176 case '-':
9177 g_string_append (s, "_dash_");
9178 break;
9179 case ')':
9180 g_string_append (s, "_rparen_");
9181 break;
9182 case ',':
9183 g_string_append (s, "_comma_");
9184 break;
9185 case ':':
9186 g_string_append (s, "_colon_");
9187 break;
9188 default:
9189 g_string_append_c (s, c);
9193 return g_string_free (s, FALSE);
9196 static gboolean
9197 append_mangled_klass (GString *s, MonoClass *klass)
9199 char *klass_desc = mono_class_full_name (klass);
9200 g_string_append_printf (s, "_%s_%s_", m_class_get_name_space (klass), klass_desc);
9201 g_free (klass_desc);
9203 // Success
9204 return TRUE;
9207 static gboolean
9208 append_mangled_method (GString *s, MonoMethod *method);
9210 static gboolean
9211 append_mangled_wrapper (GString *s, MonoMethod *method)
9213 gboolean success = TRUE;
9214 gboolean append_sig = TRUE;
9215 WrapperInfo *info = mono_marshal_get_wrapper_info (method);
9216 g_string_append_printf (s, "wrapper_");
9217 /* Most wrappers are in mscorlib */
9218 if (m_class_get_image (method->klass) != mono_get_corlib ())
9219 g_string_append_printf (s, "%s_", m_class_get_image (method->klass)->assembly->aname.name);
9221 if (method->wrapper_type != MONO_WRAPPER_OTHER && method->wrapper_type != MONO_WRAPPER_MANAGED_TO_NATIVE)
9222 append_mangled_wrapper_type (s, method->wrapper_type);
9224 switch (method->wrapper_type) {
9225 case MONO_WRAPPER_REMOTING_INVOKE:
9226 case MONO_WRAPPER_REMOTING_INVOKE_WITH_CHECK:
9227 case MONO_WRAPPER_XDOMAIN_INVOKE: {
9228 MonoMethod *m = mono_marshal_method_from_wrapper (method);
9229 g_assert (m);
9230 success = success && append_mangled_method (s, m);
9231 break;
9233 case MONO_WRAPPER_PROXY_ISINST:
9234 case MONO_WRAPPER_LDFLD:
9235 case MONO_WRAPPER_LDFLDA:
9236 case MONO_WRAPPER_STFLD: {
9237 g_assert (info);
9238 success = success && append_mangled_klass (s, info->d.proxy.klass);
9239 break;
9241 case MONO_WRAPPER_ALLOC: {
9242 /* The GC name is saved once in MonoAotFileInfo */
9243 g_assert (info->d.alloc.alloc_type != -1);
9244 g_string_append_printf (s, "%d_", info->d.alloc.alloc_type);
9245 // SlowAlloc, etc
9246 g_string_append_printf (s, "%s_", method->name);
9247 break;
9249 case MONO_WRAPPER_WRITE_BARRIER: {
9250 g_string_append_printf (s, "%s_", method->name);
9251 break;
9253 case MONO_WRAPPER_STELEMREF: {
9254 append_mangled_wrapper_subtype (s, info->subtype);
9255 if (info->subtype == WRAPPER_SUBTYPE_VIRTUAL_STELEMREF)
9256 g_string_append_printf (s, "%d", info->d.virtual_stelemref.kind);
9257 break;
9259 case MONO_WRAPPER_OTHER: {
9260 append_mangled_wrapper_subtype (s, info->subtype);
9261 if (info->subtype == WRAPPER_SUBTYPE_PTR_TO_STRUCTURE ||
9262 info->subtype == WRAPPER_SUBTYPE_STRUCTURE_TO_PTR)
9263 success = success && append_mangled_klass (s, method->klass);
9264 else if (info->subtype == WRAPPER_SUBTYPE_SYNCHRONIZED_INNER)
9265 success = success && append_mangled_method (s, info->d.synchronized_inner.method);
9266 else if (info->subtype == WRAPPER_SUBTYPE_ARRAY_ACCESSOR)
9267 success = success && append_mangled_method (s, info->d.array_accessor.method);
9268 else if (info->subtype == WRAPPER_SUBTYPE_INTERP_IN)
9269 append_mangled_signature (s, info->d.interp_in.sig);
9270 else if (info->subtype == WRAPPER_SUBTYPE_GSHAREDVT_IN_SIG) {
9271 append_mangled_signature (s, info->d.gsharedvt.sig);
9272 append_sig = FALSE;
9273 } else if (info->subtype == WRAPPER_SUBTYPE_GSHAREDVT_OUT_SIG) {
9274 append_mangled_signature (s, info->d.gsharedvt.sig);
9275 append_sig = FALSE;
9276 } else if (info->subtype == WRAPPER_SUBTYPE_INTERP_LMF)
9277 g_string_append_printf (s, "%s", method->name);
9278 else if (info->subtype == WRAPPER_SUBTYPE_AOT_INIT) {
9279 g_string_append_printf (s, "%s_%d_", m_class_get_image (method->klass)->assembly->aname.name, info->d.aot_init.subtype);
9280 append_sig = FALSE;
9282 break;
9284 case MONO_WRAPPER_MANAGED_TO_NATIVE: {
9285 append_mangled_wrapper_subtype (s, info->subtype);
9286 if (info->subtype == WRAPPER_SUBTYPE_ICALL_WRAPPER) {
9287 const char *name = method->name;
9288 const char *prefix = "__icall_wrapper_";
9289 if (strstr (name, prefix) == name)
9290 name += strlen (prefix);
9291 g_string_append_printf (s, "%s", name);
9292 append_sig = FALSE;
9293 } else if (info->subtype == WRAPPER_SUBTYPE_NATIVE_FUNC_AOT) {
9294 success = success && append_mangled_method (s, info->d.managed_to_native.method);
9295 } else {
9296 g_assert (info->subtype == WRAPPER_SUBTYPE_NONE || info->subtype == WRAPPER_SUBTYPE_PINVOKE);
9297 success = success && append_mangled_method (s, info->d.managed_to_native.method);
9299 break;
9301 case MONO_WRAPPER_SYNCHRONIZED: {
9302 MonoMethod *m;
9304 m = mono_marshal_method_from_wrapper (method);
9305 g_assert (m);
9306 g_assert (m != method);
9307 success = success && append_mangled_method (s, m);
9308 break;
9310 case MONO_WRAPPER_MANAGED_TO_MANAGED: {
9311 append_mangled_wrapper_subtype (s, info->subtype);
9313 if (info->subtype == WRAPPER_SUBTYPE_ELEMENT_ADDR) {
9314 g_string_append_printf (s, "%d_", info->d.element_addr.rank);
9315 g_string_append_printf (s, "%d_", info->d.element_addr.elem_size);
9316 } else if (info->subtype == WRAPPER_SUBTYPE_STRING_CTOR) {
9317 success = success && append_mangled_method (s, info->d.string_ctor.method);
9318 } else if (info->subtype == WRAPPER_SUBTYPE_GENERIC_ARRAY_HELPER) {
9319 success = success && append_mangled_method (s, info->d.generic_array_helper.method);
9320 } else {
9321 success = FALSE;
9323 break;
9325 case MONO_WRAPPER_CASTCLASS: {
9326 append_mangled_wrapper_subtype (s, info->subtype);
9327 break;
9329 case MONO_WRAPPER_RUNTIME_INVOKE: {
9330 append_mangled_wrapper_subtype (s, info->subtype);
9331 if (info->subtype == WRAPPER_SUBTYPE_RUNTIME_INVOKE_DIRECT || info->subtype == WRAPPER_SUBTYPE_RUNTIME_INVOKE_VIRTUAL)
9332 success = success && append_mangled_method (s, info->d.runtime_invoke.method);
9333 else if (info->subtype == WRAPPER_SUBTYPE_RUNTIME_INVOKE_NORMAL)
9334 success = success && append_mangled_signature (s, info->d.runtime_invoke.sig);
9335 break;
9337 case MONO_WRAPPER_DELEGATE_INVOKE:
9338 case MONO_WRAPPER_DELEGATE_BEGIN_INVOKE:
9339 case MONO_WRAPPER_DELEGATE_END_INVOKE: {
9340 if (method->is_inflated) {
9341 /* These wrappers are identified by their class */
9342 g_string_append_printf (s, "i_");
9343 success = success && append_mangled_klass (s, method->klass);
9344 } else {
9345 WrapperInfo *info = mono_marshal_get_wrapper_info (method);
9347 g_string_append_printf (s, "u_");
9348 if (method->wrapper_type == MONO_WRAPPER_DELEGATE_INVOKE)
9349 append_mangled_wrapper_subtype (s, info->subtype);
9350 g_string_append_printf (s, "u_sigstart");
9352 break;
9354 case MONO_WRAPPER_NATIVE_TO_MANAGED: {
9355 g_assert (info);
9356 success = success && append_mangled_method (s, info->d.native_to_managed.method);
9357 success = success && append_mangled_klass (s, method->klass);
9358 break;
9360 default:
9361 g_assert_not_reached ();
9363 if (success && append_sig)
9364 success = append_mangled_signature (s, mono_method_signature_internal (method));
9365 return success;
9368 static void
9369 append_mangled_ginst (GString *str, MonoGenericInst *ginst)
9371 int i;
9373 for (i = 0; i < ginst->type_argc; ++i) {
9374 if (i > 0)
9375 g_string_append (str, ", ");
9376 MonoType *type = ginst->type_argv [i];
9377 switch (type->type) {
9378 case MONO_TYPE_VAR:
9379 case MONO_TYPE_MVAR: {
9380 MonoType *constraint = NULL;
9381 if (type->data.generic_param)
9382 constraint = type->data.generic_param->gshared_constraint;
9383 if (constraint) {
9384 g_assert (constraint->type != MONO_TYPE_VAR && constraint->type != MONO_TYPE_MVAR);
9385 g_string_append (str, "gshared:");
9386 mono_type_get_desc (str, constraint, TRUE);
9387 break;
9389 // Else falls through to common case
9391 default:
9392 mono_type_get_desc (str, type, TRUE);
9397 static void
9398 append_mangled_context (GString *str, MonoGenericContext *context)
9400 GString *res = g_string_new ("");
9402 g_string_append_printf (res, "gens_");
9403 g_string_append (res, "00");
9405 gboolean good = context->class_inst && context->class_inst->type_argc > 0;
9406 good = good || (context->method_inst && context->method_inst->type_argc > 0);
9407 g_assert (good);
9409 if (context->class_inst)
9410 append_mangled_ginst (res, context->class_inst);
9411 if (context->method_inst) {
9412 if (context->class_inst)
9413 g_string_append (res, "11");
9414 append_mangled_ginst (res, context->method_inst);
9416 g_string_append_printf (str, "gens_%s", res->str);
9417 g_free (res);
9420 static gboolean
9421 append_mangled_method (GString *s, MonoMethod *method)
9423 if (method->wrapper_type)
9424 return append_mangled_wrapper (s, method);
9426 if (method->is_inflated) {
9427 g_string_append_printf (s, "inflated_");
9428 MonoMethodInflated *imethod = (MonoMethodInflated*) method;
9429 g_assert (imethod->context.class_inst != NULL || imethod->context.method_inst != NULL);
9431 append_mangled_context (s, &imethod->context);
9432 g_string_append_printf (s, "_declared_by_%s_", m_class_get_image (imethod->declaring->klass)->assembly->aname.name);
9433 append_mangled_method (s, imethod->declaring);
9434 } else if (method->is_generic) {
9435 g_string_append_printf (s, "%s_", m_class_get_image (method->klass)->assembly->aname.name);
9437 g_string_append_printf (s, "generic_");
9438 append_mangled_klass (s, method->klass);
9439 g_string_append_printf (s, "_%s_", method->name);
9441 MonoGenericContainer *container = mono_method_get_generic_container (method);
9442 g_string_append_printf (s, "_");
9443 append_mangled_context (s, &container->context);
9445 return append_mangled_signature (s, mono_method_signature_internal (method));
9446 } else {
9447 g_string_append_printf (s, "%s", m_class_get_image (method->klass)->assembly->aname.name);
9448 append_mangled_klass (s, method->klass);
9449 g_string_append_printf (s, "_%s_", method->name);
9450 if (!append_mangled_signature (s, mono_method_signature_internal (method))) {
9451 g_string_free (s, TRUE);
9452 return FALSE;
9456 return TRUE;
9460 * mono_aot_get_mangled_method_name:
9462 * Return a unique mangled name for METHOD, or NULL.
9464 char*
9465 mono_aot_get_mangled_method_name (MonoMethod *method)
9467 // FIXME: use static cache (mempool?)
9468 // We call this a *lot*
9470 GString *s = g_string_new ("aot_");
9471 if (!append_mangled_method (s, method)) {
9472 g_string_free (s, TRUE);
9473 return NULL;
9474 } else {
9475 char *out = g_string_free (s, FALSE);
9476 // Scrub method and class names
9477 char *cleaned = sanitize_mangled_string (out);
9478 g_free (out);
9479 return cleaned;
9483 gboolean
9484 mono_aot_is_direct_callable (MonoJumpInfo *patch_info)
9486 return is_direct_callable (llvm_acfg, NULL, patch_info);
9489 void
9490 mono_aot_mark_unused_llvm_plt_entry (MonoJumpInfo *patch_info)
9492 MonoPltEntry *plt_entry;
9494 plt_entry = get_plt_entry (llvm_acfg, patch_info);
9495 plt_entry->llvm_used = FALSE;
9498 char*
9499 mono_aot_get_direct_call_symbol (MonoJumpInfoType type, gconstpointer data)
9501 const char *sym = NULL;
9503 if (llvm_acfg->aot_opts.direct_icalls) {
9504 if (type == MONO_PATCH_INFO_JIT_ICALL_ADDR) {
9505 /* Call to a C function implementing a jit icall */
9506 sym = mono_find_jit_icall_info ((MonoJitICallId)(gsize)data)->c_symbol;
9507 } else if (type == MONO_PATCH_INFO_ICALL_ADDR_CALL) {
9508 MonoMethod *method = (MonoMethod *)data;
9509 if (!(method->flags & METHOD_ATTRIBUTE_PINVOKE_IMPL))
9510 sym = lookup_icall_symbol_name_aot (method);
9511 else if (llvm_acfg->aot_opts.direct_pinvoke)
9512 sym = get_pinvoke_import (llvm_acfg, method);
9513 } else if (type == MONO_PATCH_INFO_JIT_ICALL_ID) {
9514 MonoJitICallInfo const * const info = mono_find_jit_icall_info ((MonoJitICallId)(gsize)data);
9515 char const * const name = info->c_symbol;
9516 if (name && info->func == info->wrapper)
9517 sym = name;
9519 if (sym)
9520 return g_strdup (sym);
9522 return NULL;
9525 char*
9526 mono_aot_get_plt_symbol (MonoJumpInfoType type, gconstpointer data)
9528 MonoJumpInfo *ji = (MonoJumpInfo *)mono_mempool_alloc (llvm_acfg->mempool, sizeof (MonoJumpInfo));
9529 MonoPltEntry *plt_entry;
9530 const char *sym = NULL;
9532 ji->type = type;
9533 ji->data.target = data;
9535 if (!can_encode_patch (llvm_acfg, ji))
9536 return NULL;
9538 if (llvm_acfg->aot_opts.direct_icalls) {
9539 if (type == MONO_PATCH_INFO_JIT_ICALL_ADDR) {
9540 /* Call to a C function implementing a jit icall */
9541 sym = mono_find_jit_icall_info ((MonoJitICallId)(gsize)data)->c_symbol;
9542 } else if (type == MONO_PATCH_INFO_ICALL_ADDR_CALL) {
9543 MonoMethod *method = (MonoMethod *)data;
9544 if (!(method->flags & METHOD_ATTRIBUTE_PINVOKE_IMPL))
9545 sym = lookup_icall_symbol_name_aot (method);
9547 if (sym)
9548 return g_strdup (sym);
9551 plt_entry = get_plt_entry (llvm_acfg, ji);
9552 plt_entry->llvm_used = TRUE;
9554 #if defined(TARGET_MACH)
9555 return g_strdup (plt_entry->llvm_symbol + strlen (llvm_acfg->llvm_label_prefix));
9556 #else
9557 return g_strdup (plt_entry->llvm_symbol);
9558 #endif
9562 mono_aot_get_method_index (MonoMethod *method)
9564 g_assert (llvm_acfg);
9565 return get_method_index (llvm_acfg, method);
9568 MonoJumpInfo*
9569 mono_aot_patch_info_dup (MonoJumpInfo* ji)
9571 MonoJumpInfo *res;
9573 mono_acfg_lock (llvm_acfg);
9574 res = mono_patch_info_dup_mp (llvm_acfg->mempool, ji);
9575 mono_acfg_unlock (llvm_acfg);
9577 return res;
9580 static int
9581 execute_system (const char * command)
9583 int status = 0;
9585 #if G_HAVE_API_SUPPORT(HAVE_CLASSIC_WINAPI_SUPPORT) && defined(HOST_WIN32)
9586 // We need an extra set of quotes around the whole command to properly handle commands
9587 // with spaces since internally the command is called through "cmd /c.
9588 char * quoted_command = g_strdup_printf ("\"%s\"", command);
9590 int size = MultiByteToWideChar (CP_UTF8, 0 , quoted_command , -1, NULL , 0);
9591 wchar_t* wstr = g_malloc (sizeof (wchar_t) * size);
9592 MultiByteToWideChar (CP_UTF8, 0, quoted_command, -1, wstr , size);
9593 status = _wsystem (wstr);
9594 g_free (wstr);
9596 g_free (quoted_command);
9597 #elif defined (HAVE_SYSTEM)
9598 status = system (command);
9599 #else
9600 g_assert_not_reached ();
9601 #endif
9603 return status;
9606 #ifdef ENABLE_LLVM
9609 * emit_llvm_file:
9611 * Emit the LLVM code into an LLVM bytecode file, and compile it using the LLVM
9612 * tools.
9614 static gboolean
9615 emit_llvm_file (MonoAotCompile *acfg)
9617 char *command, *opts, *tempbc, *optbc, *output_fname;
9619 if (acfg->aot_opts.llvm_only && acfg->aot_opts.asm_only) {
9620 if (acfg->aot_opts.no_opt)
9621 tempbc = g_strdup (acfg->aot_opts.llvm_outfile);
9622 else
9623 tempbc = g_strdup_printf ("%s.bc", acfg->tmpbasename);
9624 optbc = g_strdup (acfg->aot_opts.llvm_outfile);
9625 } else {
9626 tempbc = g_strdup_printf ("%s.bc", acfg->tmpbasename);
9627 optbc = g_strdup_printf ("%s.opt.bc", acfg->tmpbasename);
9630 mono_llvm_emit_aot_module (tempbc, g_path_get_basename (acfg->image->name));
9632 if (acfg->aot_opts.no_opt)
9633 return TRUE;
9635 * FIXME: Experiment with adding optimizations, the -std-compile-opts set takes
9636 * a lot of time, and doesn't seem to save much space.
9637 * The following optimizations cannot be enabled:
9638 * - 'tailcallelim'
9639 * - 'jump-threading' changes our blockaddress references to int constants.
9640 * - 'basiccg' fails because it contains:
9641 * if (CS && !isa<IntrinsicInst>(II)) {
9642 * and isa<IntrinsicInst> is false for invokes to intrinsics (iltests.exe).
9643 * - 'prune-eh' and 'functionattrs' depend on 'basiccg'.
9644 * The opt list below was produced by taking the output of:
9645 * llvm-as < /dev/null | opt -O2 -disable-output -debug-pass=Arguments
9646 * then removing tailcallelim + the global opts.
9647 * strip-dead-prototypes deletes unused intrinsics definitions.
9649 /* The dse pass is disabled because of #13734 and #17616 */
9651 * The dse bug is in DeadStoreElimination.cpp:isOverwrite ():
9652 * // If we have no DataLayout information around, then the size of the store
9653 * // is inferrable from the pointee type. If they are the same type, then
9654 * // we know that the store is safe.
9655 * if (AA.getDataLayout() == 0 &&
9656 * Later.Ptr->getType() == Earlier.Ptr->getType()) {
9657 * return OverwriteComplete;
9658 * Here, if 'Earlier' refers to a memset, and Later has no size info, it mistakenly thinks the memset is redundant.
9660 if (acfg->aot_opts.llvm_only) {
9661 // FIXME: This doesn't work yet
9662 opts = g_strdup ("");
9663 } else {
9664 #if LLVM_API_VERSION > 100
9665 opts = g_strdup ("-O2 -disable-tail-calls -place-safepoints -spp-all-backedges");
9666 #else
9667 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");
9668 #endif
9669 if (acfg->aot_opts.llvm_opts) {
9670 opts = g_strdup_printf ("%s %s", opts, acfg->aot_opts.llvm_opts);
9674 command = g_strdup_printf ("\"%sopt\" -f %s -o \"%s\" \"%s\"", acfg->aot_opts.llvm_path, opts, optbc, tempbc);
9675 aot_printf (acfg, "Executing opt: %s\n", command);
9676 if (execute_system (command) != 0)
9677 return FALSE;
9678 g_free (opts);
9680 if (acfg->aot_opts.llvm_only && acfg->aot_opts.asm_only)
9681 /* Nothing else to do */
9682 return TRUE;
9684 if (acfg->aot_opts.llvm_only) {
9685 /* Use the stock clang from xcode */
9686 // FIXME: arch
9687 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);
9689 aot_printf (acfg, "Executing clang: %s\n", command);
9690 if (execute_system (command) != 0)
9691 return FALSE;
9692 return TRUE;
9695 if (!acfg->llc_args)
9696 acfg->llc_args = g_string_new ("");
9698 /* Verbose asm slows down llc greatly */
9699 g_string_append (acfg->llc_args, " -asm-verbose=false");
9701 if (acfg->aot_opts.mtriple)
9702 g_string_append_printf (acfg->llc_args, " -mtriple=%s", acfg->aot_opts.mtriple);
9704 #if defined(TARGET_X86_64_WIN32_MSVC) && LLVM_API_VERSION >= 600
9705 if (!acfg->aot_opts.mtriple)
9706 g_string_append_printf (acfg->llc_args, " -mtriple=%s", "x86_64-pc-windows-msvc");
9707 #endif
9709 g_string_append (acfg->llc_args, " -disable-gnu-eh-frame -enable-mono-eh-frame");
9711 g_string_append_printf (acfg->llc_args, " -mono-eh-frame-symbol=%s%s", acfg->user_symbol_prefix, acfg->llvm_eh_frame_symbol);
9713 #if LLVM_API_VERSION > 100
9714 g_string_append_printf (acfg->llc_args, " -disable-tail-calls");
9715 #endif
9717 #if LLVM_API_VERSION > 500 && (defined(TARGET_AMD64) || defined(TARGET_X86))
9718 /* This generates stack adjustments in the middle of functions breaking unwind info */
9719 g_string_append_printf (acfg->llc_args, " -no-x86-call-frame-opt");
9720 #endif
9722 #if ( defined(TARGET_MACH) && defined(TARGET_ARM) ) || defined(TARGET_ORBIS) || defined(TARGET_X86_64_WIN32_MSVC)
9723 g_string_append_printf (acfg->llc_args, " -relocation-model=pic");
9724 #else
9725 if (llvm_acfg->aot_opts.static_link)
9726 g_string_append_printf (acfg->llc_args, " -relocation-model=static");
9727 else
9728 g_string_append_printf (acfg->llc_args, " -relocation-model=pic");
9729 #endif
9731 if (acfg->llvm_owriter) {
9732 /* Emit an object file directly */
9733 output_fname = g_strdup_printf ("%s", acfg->llvm_ofile);
9734 g_string_append_printf (acfg->llc_args, " -filetype=obj");
9735 } else {
9736 output_fname = g_strdup_printf ("%s", acfg->llvm_sfile);
9739 if (acfg->aot_opts.llvm_llc) {
9740 g_string_append_printf (acfg->llc_args, " %s", acfg->aot_opts.llvm_llc);
9743 command = g_strdup_printf ("\"%sllc\" %s -o \"%s\" \"%s.opt.bc\"", acfg->aot_opts.llvm_path, acfg->llc_args->str, output_fname, acfg->tmpbasename);
9744 g_free (output_fname);
9746 aot_printf (acfg, "Executing llc: %s\n", command);
9748 if (execute_system (command) != 0)
9749 return FALSE;
9750 return TRUE;
9752 #endif
9754 /* Set the skip flag for methods which do not need to be emitted because of dedup */
9755 static void
9756 dedup_skip_methods (MonoAotCompile *acfg)
9758 int oindex, i;
9760 if (acfg->aot_opts.llvm_only)
9761 return;
9763 for (oindex = 0; oindex < acfg->method_order->len; ++oindex) {
9764 MonoCompile *cfg;
9765 MonoMethod *method;
9767 i = GPOINTER_TO_UINT (g_ptr_array_index (acfg->method_order, oindex));
9769 cfg = acfg->cfgs [i];
9771 if (!cfg)
9772 continue;
9774 method = cfg->orig_method;
9776 gboolean dedup_collect = acfg->aot_opts.dedup || (acfg->aot_opts.dedup_include && !acfg->dedup_emit_mode);
9777 gboolean dedupable = mono_aot_can_dedup (method);
9779 // cfg->skip is vital for LLVM to work, can't just continue in this loop
9780 if (dedupable && strcmp (method->name, "wbarrier_conc") && dedup_collect) {
9781 mono_dedup_cache_method (acfg, method);
9783 // Don't compile inflated methods if we're in first phase of
9784 // dedup
9786 // In second phase, we emit methods that
9787 // are dedupable. We also emit later methods
9788 // which are referenced by them and added later.
9789 // For this reason, when in the dedup_include mode,
9790 // we never set skip.
9791 if (acfg->aot_opts.dedup)
9792 cfg->skip = TRUE;
9795 // Don't compile anything in this mode
9796 if (acfg->aot_opts.dedup_include && !acfg->dedup_emit_mode)
9797 cfg->skip = TRUE;
9799 // Compile everything in this mode
9800 if (acfg->aot_opts.dedup_include && acfg->dedup_emit_mode)
9801 cfg->skip = FALSE;
9803 /*if (dedup_collect) {*/
9804 /*char *name = mono_aot_get_mangled_method_name (method);*/
9806 /*if (ignore_cfg (cfg))*/
9807 /*aot_printf (acfg, "Dedup Skipping %s\n", acfg->image->name, name);*/
9808 /*else*/
9809 /*aot_printf (acfg, "Dedup Keeping %s\n", acfg->image->name, name);*/
9811 /*g_free (name);*/
9812 /*}*/
9816 static void
9817 emit_code (MonoAotCompile *acfg)
9819 int oindex, i, prev_index;
9820 gboolean saved_unbox_info = FALSE; // See mono_aot_get_unbox_trampoline.
9821 char symbol [MAX_SYMBOL_SIZE];
9823 if (acfg->aot_opts.llvm_only)
9824 return;
9826 #if defined(TARGET_POWERPC64)
9827 sprintf (symbol, ".Lgot_addr");
9828 emit_section_change (acfg, ".text", 0);
9829 emit_alignment (acfg, 8);
9830 emit_label (acfg, symbol);
9831 emit_pointer (acfg, acfg->got_symbol);
9832 #endif
9835 * This global symbol is used to compute the address of each method using the
9836 * code_offsets array. It is also used to compute the memory ranges occupied by
9837 * AOT code, so it must be equal to the address of the first emitted method.
9839 emit_section_change (acfg, ".text", 0);
9840 emit_alignment_code (acfg, 8);
9841 emit_info_symbol (acfg, "jit_code_start", TRUE);
9844 * Emit some padding so the local symbol for the first method doesn't have the
9845 * same address as 'methods'.
9847 emit_padding (acfg, 16);
9849 for (oindex = 0; oindex < acfg->method_order->len; ++oindex) {
9850 MonoCompile *cfg;
9851 MonoMethod *method;
9853 i = GPOINTER_TO_UINT (g_ptr_array_index (acfg->method_order, oindex));
9855 cfg = acfg->cfgs [i];
9857 if (!cfg)
9858 continue;
9860 method = cfg->orig_method;
9862 if (ignore_cfg (cfg))
9863 continue;
9865 /* Emit unbox trampoline */
9866 if (mono_aot_mode_is_full (&acfg->aot_opts) && m_class_is_valuetype (cfg->orig_method->klass)) {
9867 sprintf (symbol, "ut_%d", get_method_index (acfg, method));
9869 emit_section_change (acfg, ".text", 0);
9871 if (acfg->thumb_mixed && cfg->compile_llvm) {
9872 emit_set_thumb_mode (acfg);
9873 fprintf (acfg->fp, "\n.thumb_func\n");
9876 emit_label (acfg, symbol);
9878 arch_emit_unbox_trampoline (acfg, cfg, cfg->orig_method, cfg->asm_symbol);
9880 if (acfg->thumb_mixed && cfg->compile_llvm)
9881 emit_set_arm_mode (acfg);
9883 if (!saved_unbox_info) {
9884 char user_symbol [128];
9885 GSList *unwind_ops;
9886 sprintf (user_symbol, "%sunbox_trampoline_p", acfg->user_symbol_prefix);
9888 emit_label (acfg, "ut_end");
9890 unwind_ops = mono_unwind_get_cie_program ();
9891 save_unwind_info (acfg, user_symbol, unwind_ops);
9892 mono_free_unwind_info (unwind_ops);
9894 /* Save the unbox trampoline size */
9895 #ifdef TARGET_AMD64
9896 // LLVM unbox trampolines vary in size, 6 or 9 bytes,
9897 // due to the last instruction being 2 or 5 bytes.
9898 // There is no need to describe interior bytes of instructions
9899 // however, so state the size as if the last instruction is size 1.
9900 emit_int32 (acfg, 5);
9901 #else
9902 emit_symbol_diff (acfg, "ut_end", symbol, 0);
9903 #endif
9904 saved_unbox_info = TRUE;
9908 if (cfg->compile_llvm) {
9909 acfg->stats.llvm_count ++;
9910 } else {
9911 emit_method_code (acfg, cfg);
9915 emit_section_change (acfg, ".text", 0);
9916 emit_alignment_code (acfg, 8);
9917 emit_info_symbol (acfg, "jit_code_end", TRUE);
9919 /* To distinguish it from the next symbol */
9920 emit_padding (acfg, 4);
9923 * Add .no_dead_strip directives for all LLVM methods to prevent the OSX linker
9924 * from optimizing them away, since it doesn't see that code_offsets references them.
9925 * JITted methods don't need this since they are referenced using assembler local
9926 * symbols.
9927 * FIXME: This is why write-symbols doesn't work on OSX ?
9929 if (acfg->llvm && acfg->need_no_dead_strip) {
9930 fprintf (acfg->fp, "\n");
9931 for (i = 0; i < acfg->nmethods; ++i) {
9932 if (acfg->cfgs [i] && acfg->cfgs [i]->compile_llvm)
9933 fprintf (acfg->fp, ".no_dead_strip %s\n", acfg->cfgs [i]->asm_symbol);
9938 * To work around linker issues, we emit a table of branches, and disassemble them at runtime.
9939 * This is PIE code, and the linker can update it if needed.
9942 sprintf (symbol, "method_addresses");
9943 emit_section_change (acfg, ".text", 1);
9944 emit_alignment_code (acfg, 8);
9945 emit_info_symbol (acfg, symbol, TRUE);
9946 if (acfg->aot_opts.write_symbols)
9947 emit_local_symbol (acfg, symbol, "method_addresses_end", TRUE);
9948 emit_unset_mode (acfg);
9949 if (acfg->need_no_dead_strip)
9950 fprintf (acfg->fp, " .no_dead_strip %s\n", symbol);
9952 for (i = 0; i < acfg->nmethods; ++i) {
9953 #ifdef MONO_ARCH_AOT_SUPPORTED
9954 int call_size;
9956 if (!ignore_cfg (acfg->cfgs [i])) {
9957 arch_emit_label_address (acfg, acfg->cfgs [i]->asm_symbol, FALSE, acfg->thumb_mixed && acfg->cfgs [i]->compile_llvm, NULL, &call_size);
9958 } else {
9959 arch_emit_label_address (acfg, symbol, FALSE, FALSE, NULL, &call_size);
9961 #endif
9964 sprintf (symbol, "method_addresses_end");
9965 emit_label (acfg, symbol);
9966 emit_line (acfg);
9968 /* Emit a sorted table mapping methods to the index of their unbox trampolines */
9969 sprintf (symbol, "unbox_trampolines");
9970 emit_section_change (acfg, RODATA_SECT, 0);
9971 emit_alignment (acfg, 8);
9972 emit_info_symbol (acfg, symbol, FALSE);
9974 prev_index = -1;
9975 for (i = 0; i < acfg->nmethods; ++i) {
9976 MonoCompile *cfg;
9977 MonoMethod *method;
9978 int index;
9980 cfg = acfg->cfgs [i];
9981 if (ignore_cfg (cfg))
9982 continue;
9984 method = cfg->orig_method;
9986 if (mono_aot_mode_is_full (&acfg->aot_opts) && m_class_is_valuetype (cfg->orig_method->klass)) {
9987 index = get_method_index (acfg, method);
9989 emit_int32 (acfg, index);
9990 /* Make sure the table is sorted by index */
9991 g_assert (index > prev_index);
9992 prev_index = index;
9995 sprintf (symbol, "unbox_trampolines_end");
9996 emit_info_symbol (acfg, symbol, FALSE);
9997 emit_int32 (acfg, 0);
9999 /* Emit a separate table with the trampoline addresses/offsets */
10000 sprintf (symbol, "unbox_trampoline_addresses");
10001 emit_section_change (acfg, ".text", 0);
10002 emit_alignment_code (acfg, 8);
10003 emit_info_symbol (acfg, symbol, TRUE);
10005 for (i = 0; i < acfg->nmethods; ++i) {
10006 MonoCompile *cfg;
10007 MonoMethod *method;
10008 int index;
10010 cfg = acfg->cfgs [i];
10011 if (ignore_cfg (cfg))
10012 continue;
10014 method = cfg->orig_method;
10016 if (mono_aot_mode_is_full (&acfg->aot_opts) && m_class_is_valuetype (cfg->orig_method->klass)) {
10017 #ifdef MONO_ARCH_AOT_SUPPORTED
10018 int call_size;
10020 index = get_method_index (acfg, method);
10021 sprintf (symbol, "ut_%d", index);
10023 arch_emit_direct_call (acfg, symbol, FALSE, acfg->thumb_mixed && cfg->compile_llvm, NULL, &call_size);
10024 #endif
10027 emit_int32 (acfg, 0);
10030 static void
10031 emit_info (MonoAotCompile *acfg)
10033 int oindex, i;
10034 gint32 *offsets;
10036 offsets = g_new0 (gint32, acfg->nmethods);
10038 for (oindex = 0; oindex < acfg->method_order->len; ++oindex) {
10039 i = GPOINTER_TO_UINT (g_ptr_array_index (acfg->method_order, oindex));
10041 if (acfg->cfgs [i]) {
10042 emit_method_info (acfg, acfg->cfgs [i]);
10043 offsets [i] = acfg->cfgs [i]->method_info_offset;
10044 } else {
10045 offsets [i] = 0;
10049 acfg->stats.offsets_size += emit_offset_table (acfg, "method_info_offsets", MONO_AOT_TABLE_METHOD_INFO_OFFSETS, acfg->nmethods, 10, offsets);
10051 g_free (offsets);
10054 #endif /* #if !defined(DISABLE_AOT) && !defined(DISABLE_JIT) */
10056 #define rot(x,k) (((x)<<(k)) | ((x)>>(32-(k))))
10057 #define mix(a,b,c) { \
10058 a -= c; a ^= rot(c, 4); c += b; \
10059 b -= a; b ^= rot(a, 6); a += c; \
10060 c -= b; c ^= rot(b, 8); b += a; \
10061 a -= c; a ^= rot(c,16); c += b; \
10062 b -= a; b ^= rot(a,19); a += c; \
10063 c -= b; c ^= rot(b, 4); b += a; \
10065 #define mono_final(a,b,c) { \
10066 c ^= b; c -= rot(b,14); \
10067 a ^= c; a -= rot(c,11); \
10068 b ^= a; b -= rot(a,25); \
10069 c ^= b; c -= rot(b,16); \
10070 a ^= c; a -= rot(c,4); \
10071 b ^= a; b -= rot(a,14); \
10072 c ^= b; c -= rot(b,24); \
10075 static guint
10076 mono_aot_type_hash (MonoType *t1)
10078 guint hash = t1->type;
10080 hash |= t1->byref << 6; /* do not collide with t1->type values */
10081 switch (t1->type) {
10082 case MONO_TYPE_VALUETYPE:
10083 case MONO_TYPE_CLASS:
10084 case MONO_TYPE_SZARRAY:
10085 /* check if the distribution is good enough */
10086 return ((hash << 5) - hash) ^ mono_metadata_str_hash (m_class_get_name (t1->data.klass));
10087 case MONO_TYPE_PTR:
10088 return ((hash << 5) - hash) ^ mono_metadata_type_hash (t1->data.type);
10089 case MONO_TYPE_ARRAY:
10090 return ((hash << 5) - hash) ^ mono_metadata_type_hash (m_class_get_byval_arg (t1->data.array->eklass));
10091 case MONO_TYPE_GENERICINST:
10092 return ((hash << 5) - hash) ^ 0;
10093 default:
10094 return hash;
10099 * mono_aot_method_hash:
10101 * Return a hash code for methods which only depends on metadata.
10103 guint32
10104 mono_aot_method_hash (MonoMethod *method)
10106 MonoMethodSignature *sig;
10107 MonoClass *klass;
10108 int i, hindex;
10109 int hashes_count;
10110 guint32 *hashes_start, *hashes;
10111 guint32 a, b, c;
10112 MonoGenericInst *class_ginst = NULL;
10113 MonoGenericInst *ginst = NULL;
10115 /* Similar to the hash in mono_method_get_imt_slot () */
10117 sig = mono_method_signature_internal (method);
10119 if (mono_class_is_ginst (method->klass))
10120 class_ginst = mono_class_get_generic_class (method->klass)->context.class_inst;
10121 if (method->is_inflated)
10122 ginst = ((MonoMethodInflated*)method)->context.method_inst;
10124 hashes_count = sig->param_count + 5 + (class_ginst ? class_ginst->type_argc : 0) + (ginst ? ginst->type_argc : 0);
10125 hashes_start = (guint32 *)g_malloc0 (hashes_count * sizeof (guint32));
10126 hashes = hashes_start;
10128 /* Some wrappers are assigned to random classes */
10129 if (!method->wrapper_type || method->wrapper_type == MONO_WRAPPER_REMOTING_INVOKE_WITH_CHECK)
10130 klass = method->klass;
10131 else
10132 klass = mono_defaults.object_class;
10134 if (!method->wrapper_type) {
10135 char *full_name;
10137 if (mono_class_is_ginst (klass))
10138 full_name = mono_type_full_name (m_class_get_byval_arg (mono_class_get_generic_class (klass)->container_class));
10139 else
10140 full_name = mono_type_full_name (m_class_get_byval_arg (klass));
10142 hashes [0] = mono_metadata_str_hash (full_name);
10143 hashes [1] = 0;
10144 g_free (full_name);
10145 } else {
10146 hashes [0] = mono_metadata_str_hash (m_class_get_name (klass));
10147 hashes [1] = mono_metadata_str_hash (m_class_get_name_space (klass));
10149 if (method->wrapper_type == MONO_WRAPPER_STFLD || method->wrapper_type == MONO_WRAPPER_LDFLD || method->wrapper_type == MONO_WRAPPER_LDFLDA)
10150 /* The method name includes a stringified pointer */
10151 hashes [2] = 0;
10152 else
10153 hashes [2] = mono_metadata_str_hash (method->name);
10154 hashes [3] = method->wrapper_type;
10155 hashes [4] = mono_aot_type_hash (sig->ret);
10156 hindex = 5;
10157 for (i = 0; i < sig->param_count; i++) {
10158 hashes [hindex ++] = mono_aot_type_hash (sig->params [i]);
10160 if (class_ginst) {
10161 for (i = 0; i < class_ginst->type_argc; ++i)
10162 hashes [hindex ++] = mono_aot_type_hash (class_ginst->type_argv [i]);
10164 if (ginst) {
10165 for (i = 0; i < ginst->type_argc; ++i)
10166 hashes [hindex ++] = mono_aot_type_hash (ginst->type_argv [i]);
10168 g_assert (hindex == hashes_count);
10170 /* Setup internal state */
10171 a = b = c = 0xdeadbeef + (((guint32)hashes_count)<<2);
10173 /* Handle most of the hashes */
10174 while (hashes_count > 3) {
10175 a += hashes [0];
10176 b += hashes [1];
10177 c += hashes [2];
10178 mix (a,b,c);
10179 hashes_count -= 3;
10180 hashes += 3;
10183 /* Handle the last 3 hashes (all the case statements fall through) */
10184 switch (hashes_count) {
10185 case 3 : c += hashes [2];
10186 case 2 : b += hashes [1];
10187 case 1 : a += hashes [0];
10188 mono_final (a,b,c);
10189 case 0: /* nothing left to add */
10190 break;
10193 g_free (hashes_start);
10195 return c;
10197 #undef rot
10198 #undef mix
10199 #undef mono_final
10202 * mono_aot_get_array_helper_from_wrapper;
10204 * Get the helper method in Array called by an array wrapper method.
10206 MonoMethod*
10207 mono_aot_get_array_helper_from_wrapper (MonoMethod *method)
10209 MonoMethod *m;
10210 const char *prefix;
10211 MonoGenericContext ctx;
10212 MonoType *args [16];
10213 char *mname, *iname, *s, *s2, *helper_name = NULL;
10215 prefix = "System.Collections.Generic";
10216 s = g_strdup_printf ("%s", method->name + strlen (prefix) + 1);
10217 s2 = strstr (s, "`1.");
10218 g_assert (s2);
10219 s2 [0] = '\0';
10220 iname = s;
10221 mname = s2 + 3;
10223 //printf ("X: %s %s\n", iname, mname);
10225 if (!strcmp (iname, "IList"))
10226 helper_name = g_strdup_printf ("InternalArray__%s", mname);
10227 else
10228 helper_name = g_strdup_printf ("InternalArray__%s_%s", iname, mname);
10229 m = get_method_nofail (mono_defaults.array_class, helper_name, mono_method_signature_internal (method)->param_count, 0);
10230 g_assert (m);
10231 g_free (helper_name);
10232 g_free (s);
10234 if (m->is_generic) {
10235 ERROR_DECL (error);
10236 memset (&ctx, 0, sizeof (ctx));
10237 args [0] = m_class_get_byval_arg (m_class_get_element_class (method->klass));
10238 ctx.method_inst = mono_metadata_get_generic_inst (1, args);
10239 m = mono_class_inflate_generic_method_checked (m, &ctx, error);
10240 g_assert (mono_error_ok (error)); /* FIXME don't swallow the error */
10243 return m;
10246 #if !defined(DISABLE_AOT) && !defined(DISABLE_JIT)
10248 typedef struct HashEntry {
10249 guint32 key, value, index;
10250 struct HashEntry *next;
10251 } HashEntry;
10254 * emit_extra_methods:
10256 * Emit methods which are not in the METHOD table, like wrappers.
10258 static void
10259 emit_extra_methods (MonoAotCompile *acfg)
10261 int i, table_size, buf_size;
10262 guint8 *p, *buf;
10263 guint32 *info_offsets;
10264 guint32 hash;
10265 GPtrArray *table;
10266 HashEntry *entry, *new_entry;
10267 int nmethods, max_chain_length;
10268 int *chain_lengths;
10270 info_offsets = g_new0 (guint32, acfg->extra_methods->len);
10272 /* Emit method info */
10273 nmethods = 0;
10274 for (i = 0; i < acfg->extra_methods->len; ++i) {
10275 MonoMethod *method = (MonoMethod *)g_ptr_array_index (acfg->extra_methods, i);
10276 MonoCompile *cfg = (MonoCompile *)g_hash_table_lookup (acfg->method_to_cfg, method);
10278 if (ignore_cfg (cfg))
10279 continue;
10281 buf_size = 10240;
10282 p = buf = (guint8 *)g_malloc (buf_size);
10284 nmethods ++;
10286 method = cfg->method_to_register;
10288 encode_method_ref (acfg, method, p, &p);
10290 g_assert ((p - buf) < buf_size);
10292 info_offsets [i] = add_to_blob (acfg, buf, p - buf);
10293 g_free (buf);
10297 * Construct a chained hash table for mapping indexes in extra_method_info to
10298 * method indexes.
10300 table_size = g_spaced_primes_closest ((int)(nmethods * 1.5));
10301 table = g_ptr_array_sized_new (table_size);
10302 for (i = 0; i < table_size; ++i)
10303 g_ptr_array_add (table, NULL);
10304 chain_lengths = g_new0 (int, table_size);
10305 max_chain_length = 0;
10306 for (i = 0; i < acfg->extra_methods->len; ++i) {
10307 MonoMethod *method = (MonoMethod *)g_ptr_array_index (acfg->extra_methods, i);
10308 MonoCompile *cfg = (MonoCompile *)g_hash_table_lookup (acfg->method_to_cfg, method);
10309 guint32 key, value;
10311 if (ignore_cfg (cfg))
10312 continue;
10314 key = info_offsets [i];
10315 value = get_method_index (acfg, method);
10317 hash = mono_aot_method_hash (method) % table_size;
10318 //printf ("X: %s %x\n", mono_method_get_full_name (method), mono_aot_method_hash (method));
10320 chain_lengths [hash] ++;
10321 max_chain_length = MAX (max_chain_length, chain_lengths [hash]);
10323 new_entry = (HashEntry *)mono_mempool_alloc0 (acfg->mempool, sizeof (HashEntry));
10324 new_entry->key = key;
10325 new_entry->value = value;
10327 entry = (HashEntry *)g_ptr_array_index (table, hash);
10328 if (entry == NULL) {
10329 new_entry->index = hash;
10330 g_ptr_array_index (table, hash) = new_entry;
10331 } else {
10332 while (entry->next)
10333 entry = entry->next;
10335 entry->next = new_entry;
10336 new_entry->index = table->len;
10337 g_ptr_array_add (table, new_entry);
10340 g_free (chain_lengths);
10342 //printf ("MAX: %d\n", max_chain_length);
10344 buf_size = table->len * 12 + 4;
10345 p = buf = (guint8 *)g_malloc (buf_size);
10346 encode_int (table_size, p, &p);
10348 for (i = 0; i < table->len; ++i) {
10349 HashEntry *entry = (HashEntry *)g_ptr_array_index (table, i);
10351 if (entry == NULL) {
10352 encode_int (0, p, &p);
10353 encode_int (0, p, &p);
10354 encode_int (0, p, &p);
10355 } else {
10356 //g_assert (entry->key > 0);
10357 encode_int (entry->key, p, &p);
10358 encode_int (entry->value, p, &p);
10359 if (entry->next)
10360 encode_int (entry->next->index, p, &p);
10361 else
10362 encode_int (0, p, &p);
10365 g_assert (p - buf <= buf_size);
10367 /* Emit the table */
10368 emit_aot_data (acfg, MONO_AOT_TABLE_EXTRA_METHOD_TABLE, "extra_method_table", buf, p - buf);
10370 g_free (buf);
10373 * Emit a table reverse mapping method indexes to their index in extra_method_info.
10374 * This is used by mono_aot_find_jit_info ().
10376 buf_size = acfg->extra_methods->len * 8 + 4;
10377 p = buf = (guint8 *)g_malloc (buf_size);
10378 encode_int (acfg->extra_methods->len, p, &p);
10379 for (i = 0; i < acfg->extra_methods->len; ++i) {
10380 MonoMethod *method = (MonoMethod *)g_ptr_array_index (acfg->extra_methods, i);
10382 encode_int (get_method_index (acfg, method), p, &p);
10383 encode_int (info_offsets [i], p, &p);
10385 emit_aot_data (acfg, MONO_AOT_TABLE_EXTRA_METHOD_INFO_OFFSETS, "extra_method_info_offsets", buf, p - buf);
10387 g_free (buf);
10388 g_free (info_offsets);
10389 g_ptr_array_free (table, TRUE);
10392 static void
10393 generate_aotid (guint8* aotid)
10395 gpointer rand_handle;
10396 ERROR_DECL (error);
10398 mono_rand_open ();
10399 rand_handle = mono_rand_init (NULL, 0);
10401 mono_rand_try_get_bytes (&rand_handle, aotid, 16, error);
10402 mono_error_assert_ok (error);
10404 mono_rand_close (rand_handle);
10407 static void
10408 emit_exception_info (MonoAotCompile *acfg)
10410 int i;
10411 gint32 *offsets;
10412 SeqPointData sp_data;
10413 gboolean seq_points_to_file = FALSE;
10415 offsets = g_new0 (gint32, acfg->nmethods);
10416 for (i = 0; i < acfg->nmethods; ++i) {
10417 if (acfg->cfgs [i]) {
10418 MonoCompile *cfg = acfg->cfgs [i];
10420 // By design aot-runtime decode_exception_debug_info is not able to load sequence point debug data from a file.
10421 // As it is not possible to load debug data from a file its is also not possible to store it in a file.
10422 gboolean method_seq_points_to_file = acfg->aot_opts.gen_msym_dir &&
10423 cfg->gen_seq_points && !cfg->gen_sdb_seq_points;
10424 gboolean method_seq_points_to_binary = cfg->gen_seq_points && !method_seq_points_to_file;
10426 emit_exception_debug_info (acfg, cfg, method_seq_points_to_binary);
10427 offsets [i] = cfg->ex_info_offset;
10429 if (method_seq_points_to_file) {
10430 if (!seq_points_to_file) {
10431 mono_seq_point_data_init (&sp_data, acfg->nmethods);
10432 seq_points_to_file = TRUE;
10434 mono_seq_point_data_add (&sp_data, cfg->method->token, cfg->method_index, cfg->seq_point_info);
10436 } else {
10437 offsets [i] = 0;
10441 if (seq_points_to_file) {
10442 char *aotid = mono_guid_to_string_minimal (acfg->image->aotid);
10443 char *dir = g_build_filename (acfg->aot_opts.gen_msym_dir_path, aotid, NULL);
10444 char *image_basename = g_path_get_basename (acfg->image->name);
10445 char *aot_file = g_strdup_printf("%s%s", image_basename, SEQ_POINT_AOT_EXT);
10446 char *aot_file_path = g_build_filename (dir, aot_file, NULL);
10448 if (g_ensure_directory_exists (aot_file_path) == FALSE) {
10449 fprintf (stderr, "AOT : failed to create msym directory: %s\n", aot_file_path);
10450 exit (1);
10453 mono_seq_point_data_write (&sp_data, aot_file_path);
10454 mono_seq_point_data_free (&sp_data);
10456 g_free (aotid);
10457 g_free (dir);
10458 g_free (image_basename);
10459 g_free (aot_file);
10460 g_free (aot_file_path);
10463 acfg->stats.offsets_size += emit_offset_table (acfg, "ex_info_offsets", MONO_AOT_TABLE_EX_INFO_OFFSETS, acfg->nmethods, 10, offsets);
10464 g_free (offsets);
10467 static void
10468 emit_unwind_info (MonoAotCompile *acfg)
10470 int i;
10471 char symbol [128];
10473 if (acfg->aot_opts.llvm_only) {
10474 g_assert (acfg->unwind_ops->len == 0);
10475 return;
10479 * The unwind info contains a lot of duplicates so we emit each unique
10480 * entry once, and only store the offset from the start of the table in the
10481 * exception info.
10484 sprintf (symbol, "unwind_info");
10485 emit_section_change (acfg, RODATA_SECT, 1);
10486 emit_alignment (acfg, 8);
10487 emit_info_symbol (acfg, symbol, TRUE);
10489 for (i = 0; i < acfg->unwind_ops->len; ++i) {
10490 guint32 index = GPOINTER_TO_UINT (g_ptr_array_index (acfg->unwind_ops, i));
10491 guint8 *unwind_info;
10492 guint32 unwind_info_len;
10493 guint8 buf [16];
10494 guint8 *p;
10496 unwind_info = mono_get_cached_unwind_info (index, &unwind_info_len);
10498 p = buf;
10499 encode_value (unwind_info_len, p, &p);
10500 emit_bytes (acfg, buf, p - buf);
10501 emit_bytes (acfg, unwind_info, unwind_info_len);
10503 acfg->stats.unwind_info_size += (p - buf) + unwind_info_len;
10507 static void
10508 emit_class_info (MonoAotCompile *acfg)
10510 int i;
10511 gint32 *offsets;
10513 offsets = g_new0 (gint32, acfg->image->tables [MONO_TABLE_TYPEDEF].rows);
10514 for (i = 0; i < acfg->image->tables [MONO_TABLE_TYPEDEF].rows; ++i)
10515 offsets [i] = emit_klass_info (acfg, MONO_TOKEN_TYPE_DEF | (i + 1));
10517 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);
10518 g_free (offsets);
10521 typedef struct ClassNameTableEntry {
10522 guint32 token, index;
10523 struct ClassNameTableEntry *next;
10524 } ClassNameTableEntry;
10526 static void
10527 emit_class_name_table (MonoAotCompile *acfg)
10529 int i, table_size, buf_size;
10530 guint32 token, hash;
10531 MonoClass *klass;
10532 GPtrArray *table;
10533 char *full_name;
10534 guint8 *buf, *p;
10535 ClassNameTableEntry *entry, *new_entry;
10538 * Construct a chained hash table for mapping class names to typedef tokens.
10540 table_size = g_spaced_primes_closest ((int)(acfg->image->tables [MONO_TABLE_TYPEDEF].rows * 1.5));
10541 table = g_ptr_array_sized_new (table_size);
10542 for (i = 0; i < table_size; ++i)
10543 g_ptr_array_add (table, NULL);
10544 for (i = 0; i < acfg->image->tables [MONO_TABLE_TYPEDEF].rows; ++i) {
10545 ERROR_DECL (error);
10546 token = MONO_TOKEN_TYPE_DEF | (i + 1);
10547 klass = mono_class_get_checked (acfg->image, token, error);
10548 if (!klass) {
10549 mono_error_cleanup (error);
10550 continue;
10552 full_name = mono_type_get_name_full (m_class_get_byval_arg (klass), MONO_TYPE_NAME_FORMAT_FULL_NAME);
10553 hash = mono_metadata_str_hash (full_name) % table_size;
10554 g_free (full_name);
10556 /* FIXME: Allocate from the mempool */
10557 new_entry = g_new0 (ClassNameTableEntry, 1);
10558 new_entry->token = token;
10560 entry = (ClassNameTableEntry *)g_ptr_array_index (table, hash);
10561 if (entry == NULL) {
10562 new_entry->index = hash;
10563 g_ptr_array_index (table, hash) = new_entry;
10564 } else {
10565 while (entry->next)
10566 entry = entry->next;
10568 entry->next = new_entry;
10569 new_entry->index = table->len;
10570 g_ptr_array_add (table, new_entry);
10574 /* Emit the table */
10575 buf_size = table->len * 4 + 4;
10576 p = buf = (guint8 *)g_malloc0 (buf_size);
10578 /* FIXME: Optimize memory usage */
10579 g_assert (table_size < 65000);
10580 encode_int16 (table_size, p, &p);
10581 g_assert (table->len < 65000);
10582 for (i = 0; i < table->len; ++i) {
10583 ClassNameTableEntry *entry = (ClassNameTableEntry *)g_ptr_array_index (table, i);
10585 if (entry == NULL) {
10586 encode_int16 (0, p, &p);
10587 encode_int16 (0, p, &p);
10588 } else {
10589 encode_int16 (mono_metadata_token_index (entry->token), p, &p);
10590 if (entry->next)
10591 encode_int16 (entry->next->index, p, &p);
10592 else
10593 encode_int16 (0, p, &p);
10595 g_free (entry);
10597 g_assert (p - buf <= buf_size);
10598 g_ptr_array_free (table, TRUE);
10600 emit_aot_data (acfg, MONO_AOT_TABLE_CLASS_NAME, "class_name_table", buf, p - buf);
10602 g_free (buf);
10605 static void
10606 emit_image_table (MonoAotCompile *acfg)
10608 int i, buf_size;
10609 guint8 *buf, *p;
10612 * The image table is small but referenced in a lot of places.
10613 * So we emit it at once, and reference its elements by an index.
10615 buf_size = acfg->image_table->len * 28 + 4;
10616 for (i = 0; i < acfg->image_table->len; i++) {
10617 MonoImage *image = (MonoImage*)g_ptr_array_index (acfg->image_table, i);
10618 MonoAssemblyName *aname = &image->assembly->aname;
10620 buf_size += strlen (image->assembly_name) + strlen (image->guid) + (aname->culture ? strlen (aname->culture) : 1) + strlen ((char*)aname->public_key_token) + 4;
10623 buf = p = (guint8 *)g_malloc0 (buf_size);
10624 encode_int (acfg->image_table->len, p, &p);
10625 for (i = 0; i < acfg->image_table->len; i++) {
10626 MonoImage *image = (MonoImage*)g_ptr_array_index (acfg->image_table, i);
10627 MonoAssemblyName *aname = &image->assembly->aname;
10629 /* FIXME: Support multi-module assemblies */
10630 g_assert (image->assembly->image == image);
10632 encode_string (image->assembly_name, p, &p);
10633 encode_string (image->guid, p, &p);
10634 encode_string (aname->culture ? aname->culture : "", p, &p);
10635 encode_string ((const char*)aname->public_key_token, p, &p);
10637 while (GPOINTER_TO_UINT (p) % 8 != 0)
10638 p ++;
10640 encode_int (aname->flags, p, &p);
10641 encode_int (aname->major, p, &p);
10642 encode_int (aname->minor, p, &p);
10643 encode_int (aname->build, p, &p);
10644 encode_int (aname->revision, p, &p);
10646 g_assert (p - buf <= buf_size);
10648 emit_aot_data (acfg, MONO_AOT_TABLE_IMAGE_TABLE, "image_table", buf, p - buf);
10650 g_free (buf);
10653 static void
10654 emit_weak_field_indexes (MonoAotCompile *acfg)
10656 GHashTable *indexes;
10657 GHashTableIter iter;
10658 gpointer key, value;
10659 int buf_size;
10660 guint8 *buf, *p;
10662 /* Emit a table of weak field indexes, since computing these at runtime is expensive */
10663 mono_assembly_init_weak_fields (acfg->image);
10664 indexes = acfg->image->weak_field_indexes;
10665 g_assert (indexes);
10667 buf_size = (g_hash_table_size (indexes) + 1) * 4;
10668 buf = p = (guint8 *)g_malloc0 (buf_size);
10670 encode_int (g_hash_table_size (indexes), p, &p);
10671 g_hash_table_iter_init (&iter, indexes);
10672 while (g_hash_table_iter_next (&iter, &key, &value)) {
10673 guint32 index = GPOINTER_TO_UINT (key);
10674 encode_int (index, p, &p);
10676 g_assert (p - buf <= buf_size);
10678 emit_aot_data (acfg, MONO_AOT_TABLE_WEAK_FIELD_INDEXES, "weak_field_indexes", buf, p - buf);
10680 g_free (buf);
10683 static void
10684 emit_got_info (MonoAotCompile *acfg, gboolean llvm)
10686 int i, first_plt_got_patch = 0, buf_size;
10687 guint8 *p, *buf;
10688 guint32 *got_info_offsets;
10689 GotInfo *info = llvm ? &acfg->llvm_got_info : &acfg->got_info;
10691 /* Add the patches needed by the PLT to the GOT */
10692 if (!llvm) {
10693 acfg->plt_got_offset_base = acfg->got_offset;
10694 first_plt_got_patch = info->got_patches->len;
10695 for (i = 1; i < acfg->plt_offset; ++i) {
10696 MonoPltEntry *plt_entry = (MonoPltEntry *)g_hash_table_lookup (acfg->plt_offset_to_entry, GUINT_TO_POINTER (i));
10698 g_ptr_array_add (info->got_patches, plt_entry->ji);
10700 acfg->stats.got_slot_types [plt_entry->ji->type] ++;
10703 acfg->got_offset += acfg->plt_offset;
10707 * FIXME:
10708 * - optimize offsets table.
10709 * - reduce number of exported symbols.
10710 * - emit info for a klass only once.
10711 * - determine when a method uses a GOT slot which is guaranteed to be already
10712 * initialized.
10713 * - clean up and document the code.
10714 * - use String.Empty in class libs.
10717 /* Encode info required to decode shared GOT entries */
10718 buf_size = info->got_patches->len * 128;
10719 p = buf = (guint8 *)mono_mempool_alloc (acfg->mempool, buf_size);
10720 got_info_offsets = (guint32 *)mono_mempool_alloc (acfg->mempool, info->got_patches->len * sizeof (guint32));
10721 if (!llvm) {
10722 acfg->plt_got_info_offsets = (guint32 *)mono_mempool_alloc (acfg->mempool, acfg->plt_offset * sizeof (guint32));
10723 /* Unused */
10724 if (acfg->plt_offset)
10725 acfg->plt_got_info_offsets [0] = 0;
10727 for (i = 0; i < info->got_patches->len; ++i) {
10728 MonoJumpInfo *ji = (MonoJumpInfo *)g_ptr_array_index (info->got_patches, i);
10729 guint8 *p2;
10731 p = buf;
10733 encode_value (ji->type, p, &p);
10734 p2 = p;
10735 encode_patch (acfg, ji, p, &p);
10736 acfg->stats.got_slot_info_sizes [ji->type] += p - p2;
10737 g_assert (p - buf <= buf_size);
10738 got_info_offsets [i] = add_to_blob (acfg, buf, p - buf);
10740 if (!llvm && i >= first_plt_got_patch)
10741 acfg->plt_got_info_offsets [i - first_plt_got_patch + 1] = got_info_offsets [i];
10742 acfg->stats.got_info_size += p - buf;
10745 /* Emit got_info_offsets table */
10747 /* No need to emit offsets for the got plt entries, the plt embeds them directly */
10748 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);
10751 static void
10752 emit_got (MonoAotCompile *acfg)
10754 char symbol [MAX_SYMBOL_SIZE];
10756 if (acfg->aot_opts.llvm_only)
10757 return;
10759 /* Don't make GOT global so accesses to it don't need relocations */
10760 sprintf (symbol, "%s", acfg->got_symbol);
10762 #ifdef TARGET_MACH
10763 emit_unset_mode (acfg);
10764 fprintf (acfg->fp, ".section __DATA, __bss\n");
10765 emit_alignment (acfg, 8);
10766 if (acfg->llvm)
10767 emit_info_symbol (acfg, "jit_got", FALSE);
10768 fprintf (acfg->fp, ".lcomm %s, %d\n", acfg->got_symbol, (int)(acfg->got_offset * sizeof (target_mgreg_t)));
10769 #else
10770 emit_section_change (acfg, ".bss", 0);
10771 emit_alignment (acfg, 8);
10772 if (acfg->aot_opts.write_symbols)
10773 emit_local_symbol (acfg, symbol, "got_end", FALSE);
10774 emit_label (acfg, symbol);
10775 if (acfg->llvm)
10776 emit_info_symbol (acfg, "jit_got", FALSE);
10777 if (acfg->got_offset > 0)
10778 emit_zero_bytes (acfg, (int)(acfg->got_offset * sizeof (target_mgreg_t)));
10779 #endif
10781 sprintf (symbol, "got_end");
10782 emit_label (acfg, symbol);
10785 typedef struct GlobalsTableEntry {
10786 guint32 value, index;
10787 struct GlobalsTableEntry *next;
10788 } GlobalsTableEntry;
10790 #ifdef TARGET_WIN32_MSVC
10791 #define DLL_ENTRY_POINT "DllMain"
10793 static void
10794 emit_library_info (MonoAotCompile *acfg)
10796 // Only include for shared libraries linked directly from generated object.
10797 if (link_shared_library (acfg)) {
10798 char *name = NULL;
10799 char symbol [MAX_SYMBOL_SIZE];
10801 // Ask linker to export all global symbols.
10802 emit_section_change (acfg, ".drectve", 0);
10803 for (guint i = 0; i < acfg->globals->len; ++i) {
10804 name = (char *)g_ptr_array_index (acfg->globals, i);
10805 g_assert (name != NULL);
10806 sprintf_s (symbol, MAX_SYMBOL_SIZE, " /EXPORT:%s", name);
10807 emit_string (acfg, symbol);
10810 // Emit DLLMain function, needed by MSVC linker for DLL's.
10811 // NOTE, DllMain should not go into exports above.
10812 emit_section_change (acfg, ".text", 0);
10813 emit_global (acfg, DLL_ENTRY_POINT, TRUE);
10814 emit_label (acfg, DLL_ENTRY_POINT);
10816 // Simple implementation of DLLMain, just returning TRUE.
10817 // For more information about DLLMain: https://msdn.microsoft.com/en-us/library/windows/desktop/ms682583(v=vs.85).aspx
10818 fprintf (acfg->fp, "movl $1, %%eax\n");
10819 fprintf (acfg->fp, "ret\n");
10821 // Inform linker about our dll entry function.
10822 emit_section_change (acfg, ".drectve", 0);
10823 emit_string (acfg, "/ENTRY:" DLL_ENTRY_POINT);
10824 return;
10828 #else
10830 static inline void
10831 emit_library_info (MonoAotCompile *acfg)
10833 return;
10835 #endif
10837 static void
10838 emit_globals (MonoAotCompile *acfg)
10840 int i, table_size;
10841 guint32 hash;
10842 GPtrArray *table;
10843 char symbol [1024];
10844 GlobalsTableEntry *entry, *new_entry;
10846 if (!acfg->aot_opts.static_link)
10847 return;
10849 if (acfg->aot_opts.llvm_only) {
10850 g_assert (acfg->globals->len == 0);
10851 return;
10855 * When static linking, we emit a table containing our globals.
10859 * Construct a chained hash table for mapping global names to their index in
10860 * the globals table.
10862 table_size = g_spaced_primes_closest ((int)(acfg->globals->len * 1.5));
10863 table = g_ptr_array_sized_new (table_size);
10864 for (i = 0; i < table_size; ++i)
10865 g_ptr_array_add (table, NULL);
10866 for (i = 0; i < acfg->globals->len; ++i) {
10867 char *name = (char *)g_ptr_array_index (acfg->globals, i);
10869 hash = mono_metadata_str_hash (name) % table_size;
10871 /* FIXME: Allocate from the mempool */
10872 new_entry = g_new0 (GlobalsTableEntry, 1);
10873 new_entry->value = i;
10875 entry = (GlobalsTableEntry *)g_ptr_array_index (table, hash);
10876 if (entry == NULL) {
10877 new_entry->index = hash;
10878 g_ptr_array_index (table, hash) = new_entry;
10879 } else {
10880 while (entry->next)
10881 entry = entry->next;
10883 entry->next = new_entry;
10884 new_entry->index = table->len;
10885 g_ptr_array_add (table, new_entry);
10889 /* Emit the table */
10890 sprintf (symbol, ".Lglobals_hash");
10891 emit_section_change (acfg, RODATA_SECT, 0);
10892 emit_alignment (acfg, 8);
10893 emit_label (acfg, symbol);
10895 /* FIXME: Optimize memory usage */
10896 g_assert (table_size < 65000);
10897 emit_int16 (acfg, table_size);
10898 for (i = 0; i < table->len; ++i) {
10899 GlobalsTableEntry *entry = (GlobalsTableEntry *)g_ptr_array_index (table, i);
10901 if (entry == NULL) {
10902 emit_int16 (acfg, 0);
10903 emit_int16 (acfg, 0);
10904 } else {
10905 emit_int16 (acfg, entry->value + 1);
10906 if (entry->next)
10907 emit_int16 (acfg, entry->next->index);
10908 else
10909 emit_int16 (acfg, 0);
10913 /* Emit the names */
10914 for (i = 0; i < acfg->globals->len; ++i) {
10915 char *name = (char *)g_ptr_array_index (acfg->globals, i);
10917 sprintf (symbol, "name_%d", i);
10918 emit_section_change (acfg, RODATA_SECT, 1);
10919 #ifdef TARGET_MACH
10920 emit_alignment (acfg, 4);
10921 #endif
10922 emit_label (acfg, symbol);
10923 emit_string (acfg, name);
10926 /* Emit the globals table */
10927 sprintf (symbol, "globals");
10928 emit_section_change (acfg, ".data", 0);
10929 /* This is not a global, since it is accessed by the init function */
10930 emit_alignment (acfg, 8);
10931 emit_info_symbol (acfg, symbol, FALSE);
10933 sprintf (symbol, "%sglobals_hash", acfg->temp_prefix);
10934 emit_pointer (acfg, symbol);
10936 for (i = 0; i < acfg->globals->len; ++i) {
10937 char *name = (char *)g_ptr_array_index (acfg->globals, i);
10939 sprintf (symbol, "name_%d", i);
10940 emit_pointer (acfg, symbol);
10942 g_assert (strlen (name) < sizeof (symbol));
10943 sprintf (symbol, "%s", name);
10944 emit_pointer (acfg, symbol);
10946 /* Null terminate the table */
10947 emit_int32 (acfg, 0);
10948 emit_int32 (acfg, 0);
10951 static void
10952 emit_mem_end (MonoAotCompile *acfg)
10954 char symbol [128];
10956 if (acfg->aot_opts.llvm_only)
10957 return;
10959 sprintf (symbol, "mem_end");
10960 emit_section_change (acfg, ".text", 1);
10961 emit_alignment_code (acfg, 8);
10962 emit_label (acfg, symbol);
10965 static void
10966 init_aot_file_info (MonoAotCompile *acfg, MonoAotFileInfo *info)
10968 int i;
10970 info->version = MONO_AOT_FILE_VERSION;
10971 info->plt_got_offset_base = acfg->plt_got_offset_base;
10972 info->got_size = acfg->got_offset * sizeof (target_mgreg_t);
10973 info->plt_size = acfg->plt_offset;
10974 info->nmethods = acfg->nmethods;
10975 info->nextra_methods = acfg->nextra_methods;
10976 info->flags = acfg->flags;
10977 info->opts = acfg->opts;
10978 info->simd_opts = acfg->simd_opts;
10979 info->gc_name_index = acfg->gc_name_offset;
10980 info->datafile_size = acfg->datafile_offset;
10981 for (i = 0; i < MONO_AOT_TABLE_NUM; ++i)
10982 info->table_offsets [i] = acfg->table_offsets [i];
10983 for (i = 0; i < MONO_AOT_TRAMP_NUM; ++i)
10984 info->num_trampolines [i] = acfg->num_trampolines [i];
10985 for (i = 0; i < MONO_AOT_TRAMP_NUM; ++i)
10986 info->trampoline_got_offset_base [i] = acfg->trampoline_got_offset_base [i];
10987 for (i = 0; i < MONO_AOT_TRAMP_NUM; ++i)
10988 info->trampoline_size [i] = acfg->trampoline_size [i];
10989 info->num_rgctx_fetch_trampolines = acfg->aot_opts.nrgctx_fetch_trampolines;
10991 int card_table_shift_bits = 0;
10992 target_mgreg_t card_table_mask = 0;
10994 mono_gc_get_target_card_table (&card_table_shift_bits, &card_table_mask);
10997 * Sanity checking variables used to make sure the host and target
10998 * environment matches when cross compiling.
11000 info->double_align = MONO_ABI_ALIGNOF (double);
11001 info->long_align = MONO_ABI_ALIGNOF (gint64);
11002 info->generic_tramp_num = MONO_TRAMPOLINE_NUM;
11003 info->card_table_shift_bits = card_table_shift_bits;
11004 info->card_table_mask = card_table_mask;
11006 info->tramp_page_size = acfg->tramp_page_size;
11007 info->nshared_got_entries = acfg->nshared_got_entries;
11008 for (i = 0; i < MONO_AOT_TRAMP_NUM; ++i)
11009 info->tramp_page_code_offsets [i] = acfg->tramp_page_code_offsets [i];
11011 memcpy(&info->aotid, acfg->image->aotid, 16);
11014 static void
11015 emit_aot_file_info (MonoAotCompile *acfg, MonoAotFileInfo *info)
11017 char symbol [MAX_SYMBOL_SIZE];
11018 int i, sindex;
11019 const char **symbols;
11021 symbols = g_new0 (const char *, MONO_AOT_FILE_INFO_NUM_SYMBOLS);
11022 sindex = 0;
11023 symbols [sindex ++] = acfg->got_symbol;
11024 if (acfg->llvm) {
11025 symbols [sindex ++] = g_strdup_printf ("%s%s", acfg->user_symbol_prefix, acfg->llvm_got_symbol);
11026 symbols [sindex ++] = acfg->llvm_eh_frame_symbol;
11027 } else {
11028 symbols [sindex ++] = NULL;
11029 symbols [sindex ++] = NULL;
11031 /* llvm_get_method */
11032 symbols [sindex ++] = NULL;
11033 /* llvm_get_unbox_tramp */
11034 symbols [sindex ++] = NULL;
11035 if (!acfg->aot_opts.llvm_only) {
11036 symbols [sindex ++] = "jit_code_start";
11037 symbols [sindex ++] = "jit_code_end";
11038 symbols [sindex ++] = "method_addresses";
11039 } else {
11040 symbols [sindex ++] = NULL;
11041 symbols [sindex ++] = NULL;
11042 symbols [sindex ++] = NULL;
11044 symbols [sindex ++] = NULL;
11045 symbols [sindex ++] = NULL;
11047 if (acfg->data_outfile) {
11048 for (i = 0; i < MONO_AOT_TABLE_NUM; ++i)
11049 symbols [sindex ++] = NULL;
11050 } else {
11051 symbols [sindex ++] = "blob";
11052 symbols [sindex ++] = "class_name_table";
11053 symbols [sindex ++] = "class_info_offsets";
11054 symbols [sindex ++] = "method_info_offsets";
11055 symbols [sindex ++] = "ex_info_offsets";
11056 symbols [sindex ++] = "extra_method_info_offsets";
11057 symbols [sindex ++] = "extra_method_table";
11058 symbols [sindex ++] = "got_info_offsets";
11059 if (acfg->llvm)
11060 symbols [sindex ++] = "llvm_got_info_offsets";
11061 else
11062 symbols [sindex ++] = NULL;
11063 symbols [sindex ++] = "image_table";
11064 symbols [sindex ++] = "weak_field_indexes";
11067 symbols [sindex ++] = "mem_end";
11068 symbols [sindex ++] = "assembly_guid";
11069 symbols [sindex ++] = "runtime_version";
11070 if (acfg->num_trampoline_got_entries) {
11071 symbols [sindex ++] = "specific_trampolines";
11072 symbols [sindex ++] = "static_rgctx_trampolines";
11073 symbols [sindex ++] = "imt_trampolines";
11074 symbols [sindex ++] = "gsharedvt_arg_trampolines";
11075 symbols [sindex ++] = "ftnptr_arg_trampolines";
11076 symbols [sindex ++] = "unbox_arbitrary_trampolines";
11077 } else {
11078 symbols [sindex ++] = NULL;
11079 symbols [sindex ++] = NULL;
11080 symbols [sindex ++] = NULL;
11081 symbols [sindex ++] = NULL;
11082 symbols [sindex ++] = NULL;
11083 symbols [sindex ++] = NULL;
11085 if (acfg->aot_opts.static_link) {
11086 symbols [sindex ++] = "globals";
11087 } else {
11088 symbols [sindex ++] = NULL;
11090 symbols [sindex ++] = "assembly_name";
11091 symbols [sindex ++] = "plt";
11092 symbols [sindex ++] = "plt_end";
11093 symbols [sindex ++] = "unwind_info";
11094 if (!acfg->aot_opts.llvm_only) {
11095 symbols [sindex ++] = "unbox_trampolines";
11096 symbols [sindex ++] = "unbox_trampolines_end";
11097 symbols [sindex ++] = "unbox_trampoline_addresses";
11098 } else {
11099 symbols [sindex ++] = NULL;
11100 symbols [sindex ++] = NULL;
11101 symbols [sindex ++] = NULL;
11104 g_assert (sindex == MONO_AOT_FILE_INFO_NUM_SYMBOLS);
11106 sprintf (symbol, "%smono_aot_file_info", acfg->user_symbol_prefix);
11107 emit_section_change (acfg, ".data", 0);
11108 emit_alignment (acfg, 8);
11109 emit_label (acfg, symbol);
11110 if (!acfg->aot_opts.static_link)
11111 emit_global (acfg, symbol, FALSE);
11113 /* The data emitted here must match MonoAotFileInfo. */
11115 emit_int32 (acfg, info->version);
11116 emit_int32 (acfg, info->dummy);
11119 * We emit pointers to our data structures instead of emitting global symbols which
11120 * point to them, to reduce the number of globals, and because using globals leads to
11121 * various problems (i.e. arm/thumb).
11123 for (i = 0; i < MONO_AOT_FILE_INFO_NUM_SYMBOLS; ++i)
11124 emit_pointer (acfg, symbols [i]);
11126 emit_int32 (acfg, info->plt_got_offset_base);
11127 emit_int32 (acfg, info->got_size);
11128 emit_int32 (acfg, info->plt_size);
11129 emit_int32 (acfg, info->nmethods);
11130 emit_int32 (acfg, info->nextra_methods);
11131 emit_int32 (acfg, info->flags);
11132 emit_int32 (acfg, info->opts);
11133 emit_int32 (acfg, info->simd_opts);
11134 emit_int32 (acfg, info->gc_name_index);
11135 emit_int32 (acfg, info->num_rgctx_fetch_trampolines);
11136 emit_int32 (acfg, info->double_align);
11137 emit_int32 (acfg, info->long_align);
11138 emit_int32 (acfg, info->generic_tramp_num);
11139 emit_int32 (acfg, info->card_table_shift_bits);
11140 emit_int32 (acfg, info->card_table_mask);
11141 emit_int32 (acfg, info->tramp_page_size);
11142 emit_int32 (acfg, info->nshared_got_entries);
11143 emit_int32 (acfg, info->datafile_size);
11144 emit_int32 (acfg, 0);
11145 emit_int32 (acfg, 0);
11147 for (i = 0; i < MONO_AOT_TABLE_NUM; ++i)
11148 emit_int32 (acfg, info->table_offsets [i]);
11149 for (i = 0; i < MONO_AOT_TRAMP_NUM; ++i)
11150 emit_int32 (acfg, info->num_trampolines [i]);
11151 for (i = 0; i < MONO_AOT_TRAMP_NUM; ++i)
11152 emit_int32 (acfg, info->trampoline_got_offset_base [i]);
11153 for (i = 0; i < MONO_AOT_TRAMP_NUM; ++i)
11154 emit_int32 (acfg, info->trampoline_size [i]);
11155 for (i = 0; i < MONO_AOT_TRAMP_NUM; ++i)
11156 emit_int32 (acfg, info->tramp_page_code_offsets [i]);
11158 emit_bytes (acfg, info->aotid, 16);
11160 if (acfg->aot_opts.static_link) {
11161 emit_global_inner (acfg, acfg->static_linking_symbol, FALSE);
11162 emit_alignment (acfg, sizeof (target_mgreg_t));
11163 emit_label (acfg, acfg->static_linking_symbol);
11164 emit_pointer_2 (acfg, acfg->user_symbol_prefix, "mono_aot_file_info");
11169 * Emit a structure containing all the information not stored elsewhere.
11171 static void
11172 emit_file_info (MonoAotCompile *acfg)
11174 char *build_info;
11175 MonoAotFileInfo *info;
11177 if (acfg->aot_opts.bind_to_runtime_version) {
11178 build_info = mono_get_runtime_build_info ();
11179 emit_string_symbol (acfg, "runtime_version", build_info);
11180 g_free (build_info);
11181 } else {
11182 emit_string_symbol (acfg, "runtime_version", "");
11185 emit_string_symbol (acfg, "assembly_guid" , acfg->image->guid);
11187 /* Emit a string holding the assembly name */
11188 emit_string_symbol (acfg, "assembly_name", acfg->image->assembly->aname.name);
11190 info = g_new0 (MonoAotFileInfo, 1);
11191 init_aot_file_info (acfg, info);
11193 if (acfg->aot_opts.static_link) {
11194 char symbol [MAX_SYMBOL_SIZE];
11195 char *p;
11198 * Emit a global symbol which can be passed by an embedding app to
11199 * mono_aot_register_module (). The symbol points to a pointer to the the file info
11200 * structure.
11202 sprintf (symbol, "%smono_aot_module_%s_info", acfg->user_symbol_prefix, acfg->image->assembly->aname.name);
11204 /* Get rid of characters which cannot occur in symbols */
11205 p = symbol;
11206 for (p = symbol; *p; ++p) {
11207 if (!(isalnum (*p) || *p == '_'))
11208 *p = '_';
11210 acfg->static_linking_symbol = g_strdup (symbol);
11213 if (acfg->llvm)
11214 mono_llvm_emit_aot_file_info (info, acfg->has_jitted_code);
11215 else
11216 emit_aot_file_info (acfg, info);
11219 static void
11220 emit_blob (MonoAotCompile *acfg)
11222 acfg->blob_closed = TRUE;
11224 emit_aot_data (acfg, MONO_AOT_TABLE_BLOB, "blob", (guint8*)acfg->blob.data, acfg->blob.index);
11227 static void
11228 emit_objc_selectors (MonoAotCompile *acfg)
11230 int i;
11231 char symbol [128];
11233 if (!acfg->objc_selectors || acfg->objc_selectors->len == 0)
11234 return;
11237 * From
11238 * cat > foo.m << EOF
11239 * void *ret ()
11241 * return @selector(print:);
11243 * EOF
11246 mono_img_writer_emit_unset_mode (acfg->w);
11247 g_assert (acfg->fp);
11248 fprintf (acfg->fp, ".section __DATA,__objc_selrefs,literal_pointers,no_dead_strip\n");
11249 fprintf (acfg->fp, ".align 3\n");
11250 for (i = 0; i < acfg->objc_selectors->len; ++i) {
11251 sprintf (symbol, "L_OBJC_SELECTOR_REFERENCES_%d", i);
11252 emit_label (acfg, symbol);
11253 sprintf (symbol, "L_OBJC_METH_VAR_NAME_%d", i);
11254 emit_pointer (acfg, symbol);
11257 fprintf (acfg->fp, ".section __TEXT,__cstring,cstring_literals\n");
11258 for (i = 0; i < acfg->objc_selectors->len; ++i) {
11259 fprintf (acfg->fp, "L_OBJC_METH_VAR_NAME_%d:\n", i);
11260 fprintf (acfg->fp, ".asciz \"%s\"\n", (char*)g_ptr_array_index (acfg->objc_selectors, i));
11263 fprintf (acfg->fp, ".section __DATA,__objc_imageinfo,regular,no_dead_strip\n");
11264 fprintf (acfg->fp, ".align 3\n");
11265 fprintf (acfg->fp, "L_OBJC_IMAGE_INFO:\n");
11266 fprintf (acfg->fp, ".long 0\n");
11267 fprintf (acfg->fp, ".long 16\n");
11270 static void
11271 emit_dwarf_info (MonoAotCompile *acfg)
11273 #ifdef EMIT_DWARF_INFO
11274 int i;
11275 char symbol2 [128];
11277 /* DIEs for methods */
11278 for (i = 0; i < acfg->nmethods; ++i) {
11279 MonoCompile *cfg = acfg->cfgs [i];
11281 if (ignore_cfg (cfg))
11282 continue;
11284 // FIXME: LLVM doesn't define .Lme_...
11285 if (cfg->compile_llvm)
11286 continue;
11288 sprintf (symbol2, "%sme_%x", acfg->temp_prefix, i);
11290 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 ()));
11292 #endif
11295 #ifdef EMIT_WIN32_CODEVIEW_INFO
11296 typedef struct _CodeViewSubSectionData
11298 gchar *start_section;
11299 gchar *end_section;
11300 gchar *start_section_record;
11301 gchar *end_section_record;
11302 int section_type;
11303 int section_record_type;
11304 int section_id;
11305 } CodeViewSubsectionData;
11307 typedef struct _CodeViewCompilerVersion
11309 gint major;
11310 gint minor;
11311 gint revision;
11312 gint patch;
11313 } CodeViewCompilerVersion;
11315 #define CODEVIEW_SUBSECTION_SYMBOL_TYPE 0xF1
11316 #define CODEVIEW_SUBSECTION_RECORD_COMPILER_TYPE 0x113c
11317 #define CODEVIEW_SUBSECTION_RECORD_FUNCTION_START_TYPE 0x1147
11318 #define CODEVIEW_SUBSECTION_RECORD_FUNCTION_END_TYPE 0x114F
11319 #define CODEVIEW_CSHARP_LANGUAGE_TYPE 0x0A
11320 #define CODEVIEW_CPU_TYPE 0x0
11321 #define CODEVIEW_MAGIC_HEADER 0x4
11323 static void
11324 codeview_clear_subsection_data (CodeViewSubsectionData *section_data)
11326 g_free (section_data->start_section);
11327 g_free (section_data->end_section);
11328 g_free (section_data->start_section_record);
11329 g_free (section_data->end_section_record);
11331 memset (section_data, 0, sizeof (CodeViewSubsectionData));
11334 static void
11335 codeview_parse_compiler_version (gchar *version, CodeViewCompilerVersion *data)
11337 gint values[4] = { 0 };
11338 gint *value = values;
11340 while (*version && (value < values + G_N_ELEMENTS (values))) {
11341 if (isdigit (*version)) {
11342 *value *= 10;
11343 *value += *version - '0';
11345 else if (*version == '.') {
11346 value++;
11349 version++;
11352 data->major = values[0];
11353 data->minor = values[1];
11354 data->revision = values[2];
11355 data->patch = values[3];
11358 static void
11359 emit_codeview_start_subsection (MonoAotCompile *acfg, int section_id, int section_type, int section_record_type, CodeViewSubsectionData *section_data)
11361 // Starting a new subsection, clear old data.
11362 codeview_clear_subsection_data (section_data);
11364 // Keep subsection data.
11365 section_data->section_id = section_id;
11366 section_data->section_type = section_type;
11367 section_data->section_record_type = section_record_type;
11369 // Allocate all labels used in subsection.
11370 section_data->start_section = g_strdup_printf ("%scvs_%d", acfg->temp_prefix, section_data->section_id);
11371 section_data->end_section = g_strdup_printf ("%scvse_%d", acfg->temp_prefix, section_data->section_id);
11372 section_data->start_section_record = g_strdup_printf ("%scvsr_%d", acfg->temp_prefix, section_data->section_id);
11373 section_data->end_section_record = g_strdup_printf ("%scvsre_%d", acfg->temp_prefix, section_data->section_id);
11375 // Subsection type, function symbol.
11376 emit_int32 (acfg, section_data->section_type);
11378 // Subsection size.
11379 emit_symbol_diff (acfg, section_data->end_section, section_data->start_section, 0);
11380 emit_label (acfg, section_data->start_section);
11382 // Subsection record size.
11383 fprintf (acfg->fp, "\t.word %s - %s\n", section_data->end_section_record, section_data->start_section_record);
11384 emit_label (acfg, section_data->start_section_record);
11386 // Subsection record type.
11387 emit_int16 (acfg, section_record_type);
11390 static void
11391 emit_codeview_end_subsection (MonoAotCompile *acfg, CodeViewSubsectionData *section_data, int *section_id)
11393 g_assert (section_data->start_section);
11394 g_assert (section_data->end_section);
11395 g_assert (section_data->start_section_record);
11396 g_assert (section_data->end_section_record);
11398 emit_label (acfg, section_data->end_section_record);
11400 if (section_data->section_record_type == CODEVIEW_SUBSECTION_RECORD_FUNCTION_START_TYPE) {
11401 // Emit record length.
11402 emit_int16 (acfg, 2);
11404 // Emit specific record type end.
11405 emit_int16 (acfg, CODEVIEW_SUBSECTION_RECORD_FUNCTION_END_TYPE);
11408 emit_label (acfg, section_data->end_section);
11410 // Next subsection needs to be 4 byte aligned.
11411 emit_alignment (acfg, 4);
11413 *section_id = section_data->section_id + 1;
11414 codeview_clear_subsection_data (section_data);
11417 inline static void
11418 emit_codeview_start_symbol_subsection (MonoAotCompile *acfg, int section_id, int section_record_type, CodeViewSubsectionData *section_data)
11420 emit_codeview_start_subsection (acfg, section_id, CODEVIEW_SUBSECTION_SYMBOL_TYPE, section_record_type, section_data);
11423 inline static void
11424 emit_codeview_end_symbol_subsection (MonoAotCompile *acfg, CodeViewSubsectionData *section_data, int *section_id)
11426 emit_codeview_end_subsection (acfg, section_data, section_id);
11429 static void
11430 emit_codeview_compiler_info (MonoAotCompile *acfg, int *section_id)
11432 CodeViewSubsectionData section_data = { 0 };
11433 CodeViewCompilerVersion compiler_version = { 0 };
11435 // Start new compiler record subsection.
11436 emit_codeview_start_symbol_subsection (acfg, *section_id, CODEVIEW_SUBSECTION_RECORD_COMPILER_TYPE, &section_data);
11438 emit_int32 (acfg, CODEVIEW_CSHARP_LANGUAGE_TYPE);
11439 emit_int16 (acfg, CODEVIEW_CPU_TYPE);
11441 // Get compiler version information.
11442 codeview_parse_compiler_version (VERSION, &compiler_version);
11444 // Compiler frontend version, 4 digits.
11445 emit_int16 (acfg, compiler_version.major);
11446 emit_int16 (acfg, compiler_version.minor);
11447 emit_int16 (acfg, compiler_version.revision);
11448 emit_int16 (acfg, compiler_version.patch);
11450 // Compiler backend version, 4 digits (currently same as frontend).
11451 emit_int16 (acfg, compiler_version.major);
11452 emit_int16 (acfg, compiler_version.minor);
11453 emit_int16 (acfg, compiler_version.revision);
11454 emit_int16 (acfg, compiler_version.patch);
11456 // Compiler string.
11457 emit_string (acfg, "Mono AOT compiler");
11459 // Done with section.
11460 emit_codeview_end_symbol_subsection (acfg, &section_data, section_id);
11463 static void
11464 emit_codeview_function_info (MonoAotCompile *acfg, MonoMethod *method, int *section_id, gchar *symbol, gchar *symbol_start, gchar *symbol_end)
11466 CodeViewSubsectionData section_data = { 0 };
11467 gchar *full_method_name = NULL;
11469 // Start new function record subsection.
11470 emit_codeview_start_symbol_subsection (acfg, *section_id, CODEVIEW_SUBSECTION_RECORD_FUNCTION_START_TYPE, &section_data);
11472 // Emit 3 int 0 byte padding, currently not used.
11473 emit_zero_bytes (acfg, sizeof (int) * 3);
11475 // Emit size of function.
11476 emit_symbol_diff (acfg, symbol_end, symbol_start, 0);
11478 // Emit 3 int 0 byte padding, currently not used.
11479 emit_zero_bytes (acfg, sizeof (int) * 3);
11481 // Emit reallocation info.
11482 fprintf (acfg->fp, "\t.secrel32 %s\n", symbol);
11483 fprintf (acfg->fp, "\t.secidx %s\n", symbol);
11485 // Emit flag, currently not used.
11486 emit_zero_bytes (acfg, 1);
11488 // Emit function name, exclude signature since it should be described by own metadata.
11489 full_method_name = mono_method_full_name (method, FALSE);
11490 emit_string (acfg, full_method_name ? full_method_name : "");
11491 g_free (full_method_name);
11493 // Done with section.
11494 emit_codeview_end_symbol_subsection (acfg, &section_data, section_id);
11497 static void
11498 emit_codeview_info (MonoAotCompile *acfg)
11500 int i;
11501 int section_id = 0;
11502 gchar symbol_buffer[MAX_SYMBOL_SIZE];
11504 // Emit codeview debug info section
11505 emit_section_change (acfg, ".debug$S", 0);
11507 // Emit magic header.
11508 emit_int32 (acfg, CODEVIEW_MAGIC_HEADER);
11510 emit_codeview_compiler_info (acfg, &section_id);
11512 for (i = 0; i < acfg->nmethods; ++i) {
11513 MonoCompile *cfg = acfg->cfgs[i];
11515 if (!cfg || COMPILE_LLVM (cfg))
11516 continue;
11518 int ret = g_snprintf (symbol_buffer, G_N_ELEMENTS (symbol_buffer), "%sme_%x", acfg->temp_prefix, i);
11519 if (ret > 0 && ret < G_N_ELEMENTS (symbol_buffer))
11520 emit_codeview_function_info (acfg, cfg->method, &section_id, cfg->asm_debug_symbol, cfg->asm_symbol, symbol_buffer);
11523 #else
11524 static void
11525 emit_codeview_info (MonoAotCompile *acfg)
11528 #endif /* EMIT_WIN32_CODEVIEW_INFO */
11530 #ifdef EMIT_WIN32_UNWIND_INFO
11531 static UnwindInfoSectionCacheItem *
11532 get_cached_unwind_info_section_item_win32 (MonoAotCompile *acfg, const char *function_start, const char *function_end, GSList *unwind_ops)
11534 UnwindInfoSectionCacheItem *item = NULL;
11536 if (!acfg->unwind_info_section_cache)
11537 acfg->unwind_info_section_cache = g_list_alloc ();
11539 PUNWIND_INFO unwind_info = mono_arch_unwindinfo_alloc_unwind_info (unwind_ops);
11541 // Search for unwind info in cache.
11542 GList *list = acfg->unwind_info_section_cache;
11543 int list_size = 0;
11544 while (list && list->data) {
11545 item = (UnwindInfoSectionCacheItem*)list->data;
11546 if (!memcmp (unwind_info, item->unwind_info, sizeof (UNWIND_INFO))) {
11547 // Cache hit, return cached item.
11548 return item;
11550 list = list->next;
11551 list_size++;
11554 // Add to cache.
11555 if (acfg->unwind_info_section_cache) {
11556 item = g_new0 (UnwindInfoSectionCacheItem, 1);
11557 if (item) {
11558 // Format .xdata section label for function, used to get unwind info address RVA.
11559 // Since the unwind info is similar for most functions, the symbol will be reused.
11560 item->xdata_section_label = g_strdup_printf ("%sunwind_%d", acfg->temp_prefix, list_size);
11562 // Cache unwind info data, used when checking cache for matching unwind info. NOTE, cache takes
11563 //over ownership of unwind info.
11564 item->unwind_info = unwind_info;
11566 // Needs to be emitted once.
11567 item->xdata_section_emitted = FALSE;
11569 // Prepend to beginning of list to speed up inserts.
11570 acfg->unwind_info_section_cache = g_list_prepend (acfg->unwind_info_section_cache, (gpointer)item);
11574 return item;
11577 static void
11578 free_unwind_info_section_cache_win32 (MonoAotCompile *acfg)
11580 GList *list = acfg->unwind_info_section_cache;
11582 while (list) {
11583 UnwindInfoSectionCacheItem *item = (UnwindInfoSectionCacheItem *)list->data;
11584 if (item) {
11585 g_free (item->xdata_section_label);
11586 mono_arch_unwindinfo_free_unwind_info (item->unwind_info);
11588 g_free (item);
11589 list->data = NULL;
11592 list = list->next;
11595 g_list_free (acfg->unwind_info_section_cache);
11596 acfg->unwind_info_section_cache = NULL;
11599 static void
11600 emit_unwind_info_data_win32 (MonoAotCompile *acfg, PUNWIND_INFO unwind_info)
11602 // Emit the unwind info struct.
11603 emit_bytes (acfg, (guint8*)unwind_info, sizeof (UNWIND_INFO) - (sizeof (UNWIND_CODE) * MONO_MAX_UNWIND_CODES));
11605 // Emit all unwind codes encoded in unwind info struct.
11606 PUNWIND_CODE current_unwind_node = &unwind_info->UnwindCode[MONO_MAX_UNWIND_CODES - unwind_info->CountOfCodes];
11607 PUNWIND_CODE last_unwind_node = &unwind_info->UnwindCode[MONO_MAX_UNWIND_CODES];
11609 while (current_unwind_node < last_unwind_node) {
11610 guint8 node_count = 0;
11611 switch (current_unwind_node->UnwindOp) {
11612 case UWOP_PUSH_NONVOL:
11613 case UWOP_ALLOC_SMALL:
11614 case UWOP_SET_FPREG:
11615 case UWOP_PUSH_MACHFRAME:
11616 node_count = 1;
11617 break;
11618 case UWOP_SAVE_NONVOL:
11619 case UWOP_SAVE_XMM128:
11620 node_count = 2;
11621 break;
11622 case UWOP_SAVE_NONVOL_FAR:
11623 case UWOP_SAVE_XMM128_FAR:
11624 node_count = 3;
11625 break;
11626 case UWOP_ALLOC_LARGE:
11627 if (current_unwind_node->OpInfo == 0)
11628 node_count = 2;
11629 else
11630 node_count = 3;
11631 break;
11632 default:
11633 g_assert (!"Unknown unwind opcode.");
11636 while (node_count > 0) {
11637 g_assert (current_unwind_node < last_unwind_node);
11639 //Emit current node.
11640 emit_bytes (acfg, (guint8*)current_unwind_node, sizeof (UNWIND_CODE));
11642 node_count--;
11643 current_unwind_node++;
11648 // Emit unwind info sections for each function. Unwind info on Windows x64 is emitted into two different sections.
11649 // .pdata includes the serialized DWORD aligned RVA's of function start, end and address of serialized
11650 // UNWIND_INFO struct emitted into .xdata, see https://msdn.microsoft.com/en-us/library/ft9x1kdx.aspx.
11651 // .xdata section includes DWORD aligned serialized version of UNWIND_INFO struct, https://msdn.microsoft.com/en-us/library/ddssxxy8.aspx.
11652 static void
11653 emit_unwind_info_sections_win32 (MonoAotCompile *acfg, const char *function_start, const char *function_end, GSList *unwind_ops)
11655 char *pdata_section_label = NULL;
11657 int temp_prefix_len = (acfg->temp_prefix != NULL) ? strlen (acfg->temp_prefix) : 0;
11658 if (strncmp (function_start, acfg->temp_prefix, temp_prefix_len)) {
11659 temp_prefix_len = 0;
11662 // Format .pdata section label for function.
11663 pdata_section_label = g_strdup_printf ("%spdata_%s", acfg->temp_prefix, function_start + temp_prefix_len);
11665 UnwindInfoSectionCacheItem *cache_item = get_cached_unwind_info_section_item_win32 (acfg, function_start, function_end, unwind_ops);
11666 g_assert (cache_item && cache_item->xdata_section_label && cache_item->unwind_info);
11668 // Emit .pdata section.
11669 emit_section_change (acfg, ".pdata", 0);
11670 emit_alignment (acfg, sizeof (DWORD));
11671 emit_label (acfg, pdata_section_label);
11673 // Emit function start address RVA.
11674 fprintf (acfg->fp, "\t.long %s@IMGREL\n", function_start);
11676 // Emit function end address RVA.
11677 fprintf (acfg->fp, "\t.long %s@IMGREL\n", function_end);
11679 // Emit unwind info address RVA.
11680 fprintf (acfg->fp, "\t.long %s@IMGREL\n", cache_item->xdata_section_label);
11682 if (!cache_item->xdata_section_emitted) {
11683 // Emit .xdata section.
11684 emit_section_change (acfg, ".xdata", 0);
11685 emit_alignment (acfg, sizeof (DWORD));
11686 emit_label (acfg, cache_item->xdata_section_label);
11688 // Emit unwind info into .xdata section.
11689 emit_unwind_info_data_win32 (acfg, cache_item->unwind_info);
11690 cache_item->xdata_section_emitted = TRUE;
11693 g_free (pdata_section_label);
11695 #endif
11697 static gboolean
11698 should_emit_gsharedvt_method (MonoAotCompile *acfg, MonoMethod *method)
11700 #ifdef TARGET_WASM
11701 if (acfg->image == mono_get_corlib () && !strcmp (m_class_get_name (method->klass), "Vector`1"))
11702 /* The SIMD fallback code in Vector<T> is very large, and not likely to be used */
11703 return FALSE;
11704 #endif
11705 return TRUE;
11708 static gboolean
11709 collect_methods (MonoAotCompile *acfg)
11711 int mindex, i;
11712 MonoImage *image = acfg->image;
11714 /* Collect methods */
11715 for (i = 0; i < image->tables [MONO_TABLE_METHOD].rows; ++i) {
11716 ERROR_DECL (error);
11717 MonoMethod *method;
11718 guint32 token = MONO_TOKEN_METHOD_DEF | (i + 1);
11720 method = mono_get_method_checked (acfg->image, token, NULL, NULL, error);
11722 if (!method) {
11723 aot_printerrf (acfg, "Failed to load method 0x%x from '%s' due to %s.\n", token, image->name, mono_error_get_message (error));
11724 aot_printerrf (acfg, "Run with MONO_LOG_LEVEL=debug for more information.\n");
11725 mono_error_cleanup (error);
11726 return FALSE;
11729 /* Load all methods eagerly to skip the slower lazy loading code */
11730 mono_class_setup_methods (method->klass);
11732 if (mono_aot_mode_is_full (&acfg->aot_opts) && method->iflags & METHOD_IMPL_ATTRIBUTE_INTERNAL_CALL) {
11733 /* Compile the wrapper instead */
11734 /* We do this here instead of add_wrappers () because it is easy to do it here */
11735 MonoMethod *wrapper = mono_marshal_get_native_wrapper (method, TRUE, TRUE);
11736 method = wrapper;
11739 /* FIXME: Some mscorlib methods don't have debug info */
11741 if (acfg->aot_opts.soft_debug && !method->wrapper_type) {
11742 if (!((method->flags & METHOD_ATTRIBUTE_PINVOKE_IMPL) ||
11743 (method->iflags & METHOD_IMPL_ATTRIBUTE_RUNTIME) ||
11744 (method->flags & METHOD_ATTRIBUTE_ABSTRACT) ||
11745 (method->iflags & METHOD_IMPL_ATTRIBUTE_INTERNAL_CALL))) {
11746 if (!mono_debug_lookup_method (method)) {
11747 fprintf (stderr, "Method %s has no debug info, probably the .mdb file for the assembly is missing.\n", mono_method_get_full_name (method));
11748 exit (1);
11754 if (method->is_generic || mono_class_is_gtd (method->klass)) {
11755 /* Compile the ref shared version instead */
11756 method = mini_get_shared_method_full (method, SHARE_MODE_NONE, error);
11757 if (!method) {
11758 aot_printerrf (acfg, "Failed to load method 0x%x from '%s' due to %s.\n", token, image->name, mono_error_get_message (error));
11759 aot_printerrf (acfg, "Run with MONO_LOG_LEVEL=debug for more information.\n");
11760 mono_error_cleanup (error);
11761 return FALSE;
11765 /* Since we add the normal methods first, their index will be equal to their zero based token index */
11766 add_method_with_index (acfg, method, i, FALSE);
11767 acfg->method_index ++;
11770 /* gsharedvt methods */
11771 for (mindex = 0; mindex < image->tables [MONO_TABLE_METHOD].rows; ++mindex) {
11772 ERROR_DECL (error);
11773 MonoMethod *method;
11774 guint32 token = MONO_TOKEN_METHOD_DEF | (mindex + 1);
11776 if (!(acfg->opts & MONO_OPT_GSHAREDVT))
11777 continue;
11779 method = mono_get_method_checked (acfg->image, token, NULL, NULL, error);
11780 report_loader_error (acfg, error, TRUE, "Failed to load method token 0x%x due to %s\n", i, mono_error_get_message (error));
11782 if ((method->is_generic || mono_class_is_gtd (method->klass)) && should_emit_gsharedvt_method (acfg, method)) {
11783 MonoMethod *gshared;
11785 gshared = mini_get_shared_method_full (method, SHARE_MODE_GSHAREDVT, error);
11786 mono_error_assert_ok (error);
11788 add_extra_method (acfg, gshared);
11792 if (mono_aot_mode_is_full (&acfg->aot_opts) || mono_aot_mode_is_hybrid (&acfg->aot_opts))
11793 add_generic_instances (acfg);
11795 if (mono_aot_mode_is_full (&acfg->aot_opts))
11796 add_wrappers (acfg);
11797 return TRUE;
11800 static void
11801 compile_methods (MonoAotCompile *acfg)
11803 int i, methods_len;
11805 if (acfg->aot_opts.nthreads > 0) {
11806 GPtrArray *frag;
11807 int len, j;
11808 GPtrArray *threads;
11809 MonoThreadHandle *thread_handle;
11810 gpointer *user_data;
11811 MonoMethod **methods;
11813 methods_len = acfg->methods->len;
11815 len = acfg->methods->len / acfg->aot_opts.nthreads;
11816 g_assert (len > 0);
11818 * Partition the list of methods into fragments, and hand it to threads to
11819 * process.
11821 threads = g_ptr_array_new ();
11822 /* Make a copy since acfg->methods is modified by compile_method () */
11823 methods = g_new0 (MonoMethod*, methods_len);
11824 //memcpy (methods, g_ptr_array_index (acfg->methods, 0), sizeof (MonoMethod*) * methods_len);
11825 for (i = 0; i < methods_len; ++i)
11826 methods [i] = (MonoMethod *)g_ptr_array_index (acfg->methods, i);
11827 i = 0;
11828 while (i < methods_len) {
11829 ERROR_DECL (error);
11830 MonoInternalThread *thread;
11832 frag = g_ptr_array_new ();
11833 for (j = 0; j < len; ++j) {
11834 if (i < methods_len) {
11835 g_ptr_array_add (frag, methods [i]);
11836 i ++;
11840 user_data = g_new0 (gpointer, 3);
11841 user_data [0] = acfg;
11842 user_data [1] = frag;
11844 thread = mono_thread_create_internal (mono_domain_get (), (gpointer)compile_thread_main, user_data, MONO_THREAD_CREATE_FLAGS_NONE, error);
11845 mono_error_assert_ok (error);
11847 thread_handle = mono_threads_open_thread_handle (thread->handle);
11848 g_ptr_array_add (threads, thread_handle);
11850 g_free (methods);
11852 for (i = 0; i < threads->len; ++i) {
11853 mono_thread_info_wait_one_handle ((MonoThreadHandle*)g_ptr_array_index (threads, i), MONO_INFINITE_WAIT, FALSE);
11854 mono_threads_close_thread_handle ((MonoThreadHandle*)g_ptr_array_index (threads, i));
11856 } else {
11857 methods_len = 0;
11860 /* Compile methods added by compile_method () or all methods if nthreads == 0 */
11861 for (i = methods_len; i < acfg->methods->len; ++i) {
11862 /* This can add new methods to acfg->methods */
11863 compile_method (acfg, (MonoMethod *)g_ptr_array_index (acfg->methods, i));
11866 #ifdef ENABLE_LLVM
11867 if (acfg->llvm)
11868 mono_llvm_fixup_aot_module ();
11869 #endif
11872 static int
11873 compile_asm (MonoAotCompile *acfg)
11875 char *command, *objfile;
11876 char *outfile_name, *tmp_outfile_name, *llvm_ofile;
11877 const char *tool_prefix = acfg->aot_opts.tool_prefix ? acfg->aot_opts.tool_prefix : "";
11878 char *ld_flags = acfg->aot_opts.ld_flags ? acfg->aot_opts.ld_flags : g_strdup("");
11880 #ifdef TARGET_WIN32_MSVC
11881 #define AS_OPTIONS "-c -x assembler"
11882 #elif defined(TARGET_AMD64) && !defined(TARGET_MACH)
11883 #define AS_OPTIONS "--64"
11884 #elif defined(TARGET_POWERPC64)
11885 #define AS_OPTIONS "-a64 -mppc64"
11886 #elif defined(sparc) && TARGET_SIZEOF_VOID_P == 8
11887 #define AS_OPTIONS "-xarch=v9"
11888 #elif defined(TARGET_X86) && defined(TARGET_MACH)
11889 #define AS_OPTIONS "-arch i386"
11890 #elif defined(TARGET_X86) && !defined(TARGET_MACH)
11891 #define AS_OPTIONS "--32"
11892 #else
11893 #define AS_OPTIONS ""
11894 #endif
11896 #if defined(TARGET_OSX)
11897 #define AS_NAME "clang"
11898 #elif defined(TARGET_WIN32_MSVC)
11899 #define AS_NAME "clang.exe"
11900 #else
11901 #define AS_NAME "as"
11902 #endif
11904 #ifdef TARGET_WIN32_MSVC
11905 #define AS_OBJECT_FILE_SUFFIX "obj"
11906 #else
11907 #define AS_OBJECT_FILE_SUFFIX "o"
11908 #endif
11910 #if defined(sparc)
11911 #define LD_NAME "ld"
11912 #define LD_OPTIONS "-shared -G"
11913 #elif defined(__ppc__) && defined(TARGET_MACH)
11914 #define LD_NAME "gcc"
11915 #define LD_OPTIONS "-dynamiclib"
11916 #elif defined(TARGET_AMD64) && defined(TARGET_MACH)
11917 #define LD_NAME "clang"
11918 #define LD_OPTIONS "--shared"
11919 #elif defined(TARGET_WIN32_MSVC)
11920 #define LD_NAME "link.exe"
11921 #define LD_OPTIONS "/DLL /MACHINE:X64 /NOLOGO /INCREMENTAL:NO"
11922 #define LD_DEBUG_OPTIONS LD_OPTIONS " /DEBUG"
11923 #elif defined(TARGET_WIN32) && !defined(TARGET_ANDROID)
11924 #define LD_NAME "gcc"
11925 #define LD_OPTIONS "-shared"
11926 #elif defined(TARGET_X86) && defined(TARGET_MACH)
11927 #define LD_NAME "clang"
11928 #define LD_OPTIONS "-m32 -dynamiclib"
11929 #elif defined(TARGET_X86) && !defined(TARGET_MACH)
11930 #define LD_OPTIONS "-m elf_i386"
11931 #elif defined(TARGET_ARM) && !defined(TARGET_ANDROID)
11932 #define LD_NAME "gcc"
11933 #define LD_OPTIONS "--shared"
11934 #elif defined(TARGET_POWERPC64)
11935 #define LD_OPTIONS "-m elf64ppc"
11936 #endif
11938 #ifndef LD_OPTIONS
11939 #define LD_OPTIONS ""
11940 #endif
11942 if (acfg->aot_opts.asm_only) {
11943 aot_printf (acfg, "Output file: '%s'.\n", acfg->tmpfname);
11944 if (acfg->aot_opts.static_link)
11945 aot_printf (acfg, "Linking symbol: '%s'.\n", acfg->static_linking_symbol);
11946 if (acfg->llvm)
11947 aot_printf (acfg, "LLVM output file: '%s'.\n", acfg->llvm_sfile);
11948 return 0;
11951 if (acfg->aot_opts.static_link) {
11952 if (acfg->aot_opts.outfile)
11953 objfile = g_strdup_printf ("%s", acfg->aot_opts.outfile);
11954 else
11955 objfile = g_strdup_printf ("%s." AS_OBJECT_FILE_SUFFIX, acfg->image->name);
11956 } else {
11957 objfile = g_strdup_printf ("%s." AS_OBJECT_FILE_SUFFIX, acfg->tmpfname);
11960 #ifdef TARGET_OSX
11961 g_string_append (acfg->as_args, "-c -x assembler");
11962 #endif
11964 command = g_strdup_printf ("\"%s%s\" %s %s -o %s %s", tool_prefix, AS_NAME, AS_OPTIONS,
11965 acfg->as_args ? acfg->as_args->str : "",
11966 wrap_path (objfile), wrap_path (acfg->tmpfname));
11967 aot_printf (acfg, "Executing the native assembler: %s\n", command);
11968 if (execute_system (command) != 0) {
11969 g_free (command);
11970 g_free (objfile);
11971 return 1;
11974 if (acfg->llvm && !acfg->llvm_owriter) {
11975 command = g_strdup_printf ("\"%s%s\" %s %s -o %s %s", tool_prefix, AS_NAME, AS_OPTIONS,
11976 acfg->as_args ? acfg->as_args->str : "",
11977 wrap_path (acfg->llvm_ofile), wrap_path (acfg->llvm_sfile));
11978 aot_printf (acfg, "Executing the native assembler: %s\n", command);
11979 if (execute_system (command) != 0) {
11980 g_free (command);
11981 g_free (objfile);
11982 return 1;
11986 g_free (command);
11988 if (acfg->aot_opts.static_link) {
11989 aot_printf (acfg, "Output file: '%s'.\n", objfile);
11990 aot_printf (acfg, "Linking symbol: '%s'.\n", acfg->static_linking_symbol);
11991 g_free (objfile);
11992 return 0;
11995 if (acfg->aot_opts.outfile)
11996 outfile_name = g_strdup_printf ("%s", acfg->aot_opts.outfile);
11997 else
11998 outfile_name = g_strdup_printf ("%s%s", acfg->image->name, MONO_SOLIB_EXT);
12000 tmp_outfile_name = g_strdup_printf ("%s.tmp", outfile_name);
12002 if (acfg->llvm) {
12003 llvm_ofile = g_strdup_printf ("\"%s\"", acfg->llvm_ofile);
12004 } else {
12005 llvm_ofile = g_strdup ("");
12008 /* replace the ; flags separators with spaces */
12009 g_strdelimit (ld_flags, ';', ' ');
12011 if (acfg->aot_opts.llvm_only)
12012 ld_flags = g_strdup_printf ("%s %s", ld_flags, "-lstdc++");
12014 #ifdef TARGET_WIN32_MSVC
12015 g_assert (tmp_outfile_name != NULL);
12016 g_assert (objfile != NULL);
12017 command = g_strdup_printf ("\"%s%s\" %s %s /OUT:%s %s %s", tool_prefix, LD_NAME,
12018 acfg->aot_opts.nodebug ? LD_OPTIONS : LD_DEBUG_OPTIONS, ld_flags, wrap_path (tmp_outfile_name), wrap_path (objfile), wrap_path (llvm_ofile));
12019 #elif defined(LD_NAME)
12020 command = g_strdup_printf ("%s%s %s -o %s %s %s %s", tool_prefix, LD_NAME, LD_OPTIONS,
12021 wrap_path (tmp_outfile_name), wrap_path (llvm_ofile),
12022 wrap_path (g_strdup_printf ("%s." AS_OBJECT_FILE_SUFFIX, acfg->tmpfname)), ld_flags);
12023 #else
12024 // Default (linux)
12025 if (acfg->aot_opts.tool_prefix) {
12026 /* Cross compiling */
12027 command = g_strdup_printf ("\"%sld\" %s -shared -o %s %s %s %s", tool_prefix, LD_OPTIONS,
12028 wrap_path (tmp_outfile_name), wrap_path (llvm_ofile),
12029 wrap_path (g_strdup_printf ("%s." AS_OBJECT_FILE_SUFFIX, acfg->tmpfname)), ld_flags);
12030 } else {
12031 char *args = g_strdup_printf ("%s -shared -o %s %s %s %s", LD_OPTIONS,
12032 wrap_path (tmp_outfile_name), wrap_path (llvm_ofile),
12033 wrap_path (g_strdup_printf ("%s." AS_OBJECT_FILE_SUFFIX, acfg->tmpfname)), ld_flags);
12035 if (acfg->aot_opts.llvm_only) {
12036 command = g_strdup_printf ("%s %s", acfg->aot_opts.clangxx, args);
12037 } else {
12038 command = g_strdup_printf ("\"%sld\" %s", tool_prefix, args);
12040 g_free (args);
12042 #endif
12043 aot_printf (acfg, "Executing the native linker: %s\n", command);
12044 if (execute_system (command) != 0) {
12045 g_free (tmp_outfile_name);
12046 g_free (outfile_name);
12047 g_free (command);
12048 g_free (objfile);
12049 g_free (ld_flags);
12050 return 1;
12053 g_free (command);
12055 /*com = g_strdup_printf ("strip --strip-unneeded %s%s", acfg->image->name, MONO_SOLIB_EXT);
12056 printf ("Stripping the binary: %s\n", com);
12057 execute_system (com);
12058 g_free (com);*/
12060 #if defined(TARGET_ARM) && !defined(TARGET_MACH)
12062 * gas generates 'mapping symbols' each time code and data is mixed, which
12063 * happens a lot in emit_and_reloc_code (), so we need to get rid of them.
12065 command = g_strdup_printf ("\"%sstrip\" --strip-symbol=\\$a --strip-symbol=\\$d %s", wrap_path(tool_prefix), wrap_path(tmp_outfile_name));
12066 aot_printf (acfg, "Stripping the binary: %s\n", command);
12067 if (execute_system (command) != 0) {
12068 g_free (tmp_outfile_name);
12069 g_free (outfile_name);
12070 g_free (command);
12071 g_free (objfile);
12072 return 1;
12074 #endif
12076 if (0 != rename (tmp_outfile_name, outfile_name)) {
12077 if (G_FILE_ERROR_EXIST == g_file_error_from_errno (errno)) {
12078 /* Since we are rebuilding the module we need to be able to replace any old copies. Remove old file and retry rename operation. */
12079 unlink (outfile_name);
12080 rename (tmp_outfile_name, outfile_name);
12084 #if defined(TARGET_MACH)
12085 command = g_strdup_printf ("dsymutil \"%s\"", outfile_name);
12086 aot_printf (acfg, "Executing dsymutil: %s\n", command);
12087 if (execute_system (command) != 0) {
12088 return 1;
12090 #endif
12092 if (!acfg->aot_opts.save_temps)
12093 unlink (objfile);
12095 g_free (tmp_outfile_name);
12096 g_free (outfile_name);
12097 g_free (objfile);
12099 if (acfg->aot_opts.save_temps)
12100 aot_printf (acfg, "Retained input file.\n");
12101 else
12102 unlink (acfg->tmpfname);
12104 return 0;
12107 static guint8
12108 profread_byte (FILE *infile)
12110 guint8 i;
12111 int res;
12113 res = fread (&i, 1, 1, infile);
12114 g_assert (res == 1);
12115 return i;
12118 static int
12119 profread_int (FILE *infile)
12121 int i, res;
12123 res = fread (&i, 4, 1, infile);
12124 g_assert (res == 1);
12125 return i;
12128 static char*
12129 profread_string (FILE *infile)
12131 int len, res;
12132 char *pbuf;
12134 len = profread_int (infile);
12135 pbuf = (char*)g_malloc (len + 1);
12136 res = fread (pbuf, 1, len, infile);
12137 g_assert (res == len);
12138 pbuf [len] = '\0';
12139 return pbuf;
12142 static void
12143 load_profile_file (MonoAotCompile *acfg, char *filename)
12145 FILE *infile;
12146 char buf [1024];
12147 int res, len, version;
12148 char magic [32];
12150 infile = fopen (filename, "r");
12151 if (!infile) {
12152 fprintf (stderr, "Unable to open file '%s': %s.\n", filename, strerror (errno));
12153 exit (1);
12156 printf ("Using profile data file '%s'\n", filename);
12158 sprintf (magic, AOT_PROFILER_MAGIC);
12159 len = strlen (magic);
12160 res = fread (buf, 1, len, infile);
12161 magic [len] = '\0';
12162 buf [len] = '\0';
12163 if ((res != len) || strcmp (buf, magic) != 0) {
12164 printf ("Profile file has wrong header: '%s'.\n", buf);
12165 fclose (infile);
12166 exit (1);
12168 guint32 expected_version = (AOT_PROFILER_MAJOR_VERSION << 16) | AOT_PROFILER_MINOR_VERSION;
12169 version = profread_int (infile);
12170 if (version != expected_version) {
12171 printf ("Profile file has wrong version 0x%4x, expected 0x%4x.\n", version, expected_version);
12172 fclose (infile);
12173 exit (1);
12176 ProfileData *data = g_new0 (ProfileData, 1);
12177 data->images = g_hash_table_new (NULL, NULL);
12178 data->classes = g_hash_table_new (NULL, NULL);
12179 data->ginsts = g_hash_table_new (NULL, NULL);
12180 data->methods = g_hash_table_new (NULL, NULL);
12182 while (TRUE) {
12183 int type = profread_byte (infile);
12184 int id = profread_int (infile);
12186 if (type == AOTPROF_RECORD_NONE)
12187 break;
12189 switch (type) {
12190 case AOTPROF_RECORD_IMAGE: {
12191 ImageProfileData *idata = g_new0 (ImageProfileData, 1);
12192 idata->name = profread_string (infile);
12193 char *mvid = profread_string (infile);
12194 g_free (mvid);
12195 g_hash_table_insert (data->images, GINT_TO_POINTER (id), idata);
12196 break;
12198 case AOTPROF_RECORD_GINST: {
12199 int i;
12200 int len = profread_int (infile);
12202 GInstProfileData *gdata = g_new0 (GInstProfileData, 1);
12203 gdata->argc = len;
12204 gdata->argv = g_new0 (ClassProfileData*, len);
12206 for (i = 0; i < len; ++i) {
12207 int class_id = profread_int (infile);
12209 gdata->argv [i] = (ClassProfileData*)g_hash_table_lookup (data->classes, GINT_TO_POINTER (class_id));
12210 g_assert (gdata->argv [i]);
12212 g_hash_table_insert (data->ginsts, GINT_TO_POINTER (id), gdata);
12213 break;
12215 case AOTPROF_RECORD_TYPE: {
12216 int type = profread_byte (infile);
12218 switch (type) {
12219 case MONO_TYPE_CLASS: {
12220 int image_id = profread_int (infile);
12221 int ginst_id = profread_int (infile);
12222 char *class_name = profread_string (infile);
12224 ImageProfileData *image = (ImageProfileData*)g_hash_table_lookup (data->images, GINT_TO_POINTER (image_id));
12225 g_assert (image);
12227 char *p = strrchr (class_name, '.');
12228 g_assert (p);
12229 *p = '\0';
12231 ClassProfileData *cdata = g_new0 (ClassProfileData, 1);
12232 cdata->image = image;
12233 cdata->ns = g_strdup (class_name);
12234 cdata->name = g_strdup (p + 1);
12236 if (ginst_id != -1) {
12237 cdata->inst = (GInstProfileData*)g_hash_table_lookup (data->ginsts, GINT_TO_POINTER (ginst_id));
12238 g_assert (cdata->inst);
12240 g_free (class_name);
12242 g_hash_table_insert (data->classes, GINT_TO_POINTER (id), cdata);
12243 break;
12245 #if 0
12246 case MONO_TYPE_SZARRAY: {
12247 int elem_id = profread_int (infile);
12248 // FIXME:
12249 break;
12251 #endif
12252 default:
12253 g_assert_not_reached ();
12254 break;
12256 break;
12258 case AOTPROF_RECORD_METHOD: {
12259 int class_id = profread_int (infile);
12260 int ginst_id = profread_int (infile);
12261 int param_count = profread_int (infile);
12262 char *method_name = profread_string (infile);
12263 char *sig = profread_string (infile);
12265 ClassProfileData *klass = (ClassProfileData*)g_hash_table_lookup (data->classes, GINT_TO_POINTER (class_id));
12266 g_assert (klass);
12268 MethodProfileData *mdata = g_new0 (MethodProfileData, 1);
12269 mdata->id = id;
12270 mdata->klass = klass;
12271 mdata->name = method_name;
12272 mdata->signature = sig;
12273 mdata->param_count = param_count;
12275 if (ginst_id != -1) {
12276 mdata->inst = (GInstProfileData*)g_hash_table_lookup (data->ginsts, GINT_TO_POINTER (ginst_id));
12277 g_assert (mdata->inst);
12279 g_hash_table_insert (data->methods, GINT_TO_POINTER (id), mdata);
12280 break;
12282 default:
12283 printf ("%d\n", type);
12284 g_assert_not_reached ();
12285 break;
12289 fclose (infile);
12290 acfg->profile_data = g_list_append (acfg->profile_data, data);
12293 static void
12294 resolve_class (ClassProfileData *cdata);
12296 static void
12297 resolve_ginst (GInstProfileData *inst_data)
12299 int i;
12301 if (inst_data->inst)
12302 return;
12304 for (i = 0; i < inst_data->argc; ++i) {
12305 resolve_class (inst_data->argv [i]);
12306 if (!inst_data->argv [i]->klass)
12307 return;
12309 MonoType **args = g_new0 (MonoType*, inst_data->argc);
12310 for (i = 0; i < inst_data->argc; ++i)
12311 args [i] = m_class_get_byval_arg (inst_data->argv [i]->klass);
12313 inst_data->inst = mono_metadata_get_generic_inst (inst_data->argc, args);
12316 static void
12317 resolve_class (ClassProfileData *cdata)
12319 ERROR_DECL (error);
12320 MonoClass *klass;
12322 if (!cdata->image->image)
12323 return;
12325 klass = mono_class_from_name_checked (cdata->image->image, cdata->ns, cdata->name, error);
12326 if (!klass) {
12327 //printf ("[%s] %s.%s\n", cdata->image->name, cdata->ns, cdata->name);
12328 return;
12330 if (cdata->inst) {
12331 resolve_ginst (cdata->inst);
12332 if (!cdata->inst->inst)
12333 return;
12334 MonoGenericContext ctx;
12336 memset (&ctx, 0, sizeof (ctx));
12337 ctx.class_inst = cdata->inst->inst;
12338 cdata->klass = mono_class_inflate_generic_class_checked (klass, &ctx, error);
12339 } else {
12340 cdata->klass = klass;
12345 * Resolve the profile data to the corresponding loaded classes/methods etc. if possible.
12347 static void
12348 resolve_profile_data (MonoAotCompile *acfg, ProfileData *data, MonoAssembly* current)
12350 GHashTableIter iter;
12351 gpointer key, value;
12352 int i;
12354 if (!data)
12355 return;
12357 /* Images */
12358 GPtrArray *assemblies = mono_domain_get_assemblies (mono_get_root_domain (), FALSE);
12359 g_hash_table_iter_init (&iter, data->images);
12360 while (g_hash_table_iter_next (&iter, &key, &value)) {
12361 ImageProfileData *idata = (ImageProfileData*)value;
12363 if (!strcmp (current->aname.name, idata->name)) {
12364 idata->image = current->image;
12365 break;
12368 for (i = 0; i < assemblies->len; ++i) {
12369 MonoAssembly *ass = (MonoAssembly*)g_ptr_array_index (assemblies, i);
12371 if (!strcmp (ass->aname.name, idata->name)) {
12372 idata->image = ass->image;
12373 break;
12377 g_ptr_array_free (assemblies, TRUE);
12379 /* Classes */
12380 g_hash_table_iter_init (&iter, data->classes);
12381 while (g_hash_table_iter_next (&iter, &key, &value)) {
12382 ClassProfileData *cdata = (ClassProfileData*)value;
12384 if (!cdata->image->image) {
12385 if (acfg->aot_opts.verbose)
12386 printf ("Unable to load class '%s.%s' because its image '%s' is not loaded.\n", cdata->ns, cdata->name, cdata->image->name);
12387 continue;
12390 resolve_class (cdata);
12392 if (cdata->klass)
12393 printf ("%s %s %s\n", cdata->ns, cdata->name, mono_class_full_name (cdata->klass));
12397 /* Methods */
12398 g_hash_table_iter_init (&iter, data->methods);
12399 while (g_hash_table_iter_next (&iter, &key, &value)) {
12400 MethodProfileData *mdata = (MethodProfileData*)value;
12401 MonoClass *klass;
12402 MonoMethod *m;
12403 gpointer miter;
12405 resolve_class (mdata->klass);
12406 klass = mdata->klass->klass;
12407 if (!klass) {
12408 if (acfg->aot_opts.verbose)
12409 printf ("Unable to load method '%s' because its class '%s.%s' is not loaded.\n", mdata->name, mdata->klass->ns, mdata->klass->name);
12410 continue;
12412 miter = NULL;
12413 while ((m = mono_class_get_methods (klass, &miter))) {
12414 ERROR_DECL (error);
12416 if (strcmp (m->name, mdata->name))
12417 continue;
12418 MonoMethodSignature *sig = mono_method_signature_internal (m);
12419 if (!sig)
12420 continue;
12421 if (sig->param_count != mdata->param_count)
12422 continue;
12423 if (mdata->inst) {
12424 resolve_ginst (mdata->inst);
12425 if (!mdata->inst->inst)
12426 continue;
12427 MonoGenericContext ctx;
12429 memset (&ctx, 0, sizeof (ctx));
12430 ctx.method_inst = mdata->inst->inst;
12432 m = mono_class_inflate_generic_method_checked (m, &ctx, error);
12433 if (!m)
12434 continue;
12435 sig = mono_method_signature_checked (m, error);
12436 if (!is_ok (error)) {
12437 mono_error_cleanup (error);
12438 continue;
12441 char *sig_str = mono_signature_full_name (sig);
12442 gboolean match = !strcmp (sig_str, mdata->signature);
12443 g_free (sig_str);
12444 if (!match)
12446 continue;
12447 //printf ("%s\n", mono_method_full_name (m, 1));
12448 mdata->method = m;
12449 break;
12451 if (!mdata->method) {
12452 if (acfg->aot_opts.verbose)
12453 printf ("Unable to load method '%s' from class '%s', not found.\n", mdata->name, mono_class_full_name (klass));
12458 static gboolean
12459 inst_references_image (MonoGenericInst *inst, MonoImage *image)
12461 int i;
12463 for (i = 0; i < inst->type_argc; ++i) {
12464 MonoClass *k = mono_class_from_mono_type_internal (inst->type_argv [i]);
12465 if (m_class_get_image (k) == image)
12466 return TRUE;
12467 if (mono_class_is_ginst (k)) {
12468 MonoGenericInst *kinst = mono_class_get_context (k)->class_inst;
12469 if (inst_references_image (kinst, image))
12470 return TRUE;
12473 return FALSE;
12476 static gboolean
12477 is_local_inst (MonoGenericInst *inst, MonoImage *image)
12479 int i;
12481 for (i = 0; i < inst->type_argc; ++i) {
12482 MonoClass *k = mono_class_from_mono_type_internal (inst->type_argv [i]);
12483 if (!MONO_TYPE_IS_PRIMITIVE (inst->type_argv [i]) && m_class_get_image (k) != image)
12484 return FALSE;
12486 return TRUE;
12489 static void
12490 add_profile_instances (MonoAotCompile *acfg, ProfileData *data)
12492 GHashTableIter iter;
12493 gpointer key, value;
12494 int count = 0;
12496 if (!data)
12497 return;
12499 if (acfg->aot_opts.profile_only) {
12500 /* Add methods referenced by the profile */
12501 g_hash_table_iter_init (&iter, data->methods);
12502 while (g_hash_table_iter_next (&iter, &key, &value)) {
12503 MethodProfileData *mdata = (MethodProfileData*)value;
12504 MonoMethod *m = mdata->method;
12506 if (!m)
12507 continue;
12508 if (m->is_inflated)
12509 continue;
12510 add_extra_method (acfg, m);
12511 g_hash_table_insert (acfg->profile_methods, m, m);
12512 count ++;
12517 * Add method instances 'related' to this assembly to the AOT image.
12519 g_hash_table_iter_init (&iter, data->methods);
12520 while (g_hash_table_iter_next (&iter, &key, &value)) {
12521 MethodProfileData *mdata = (MethodProfileData*)value;
12522 MonoMethod *m = mdata->method;
12523 MonoGenericContext *ctx;
12525 if (!m)
12526 continue;
12527 if (!m->is_inflated)
12528 continue;
12530 ctx = mono_method_get_context (m);
12531 /* For simplicity, add instances which reference the assembly we are compiling */
12532 if (((ctx->class_inst && inst_references_image (ctx->class_inst, acfg->image)) ||
12533 (ctx->method_inst && inst_references_image (ctx->method_inst, acfg->image))) &&
12534 !mono_method_is_generic_sharable_full (m, FALSE, FALSE, FALSE)) {
12535 //printf ("%s\n", mono_method_full_name (m, TRUE));
12536 add_extra_method (acfg, m);
12537 count ++;
12538 } else if (m_class_get_image (m->klass) == acfg->image &&
12539 ((ctx->class_inst && is_local_inst (ctx->class_inst, acfg->image)) ||
12540 (ctx->method_inst && is_local_inst (ctx->method_inst, acfg->image))) &&
12541 !mono_method_is_generic_sharable_full (m, FALSE, FALSE, FALSE)) {
12542 /* Add instances where the gtd is in the assembly and its inflated with types from this assembly or corlib */
12543 //printf ("%s\n", mono_method_full_name (m, TRUE));
12544 add_extra_method (acfg, m);
12545 count ++;
12548 * FIXME: We might skip some instances, for example:
12549 * Foo<Bar> won't be compiled when compiling Foo's assembly since it doesn't match the first case,
12550 * and it won't be compiled when compiling Bar's assembly if Foo's assembly is not loaded.
12554 printf ("Added %d methods from profile.\n", count);
12557 static void
12558 init_got_info (GotInfo *info)
12560 int i;
12562 info->patch_to_got_offset = g_hash_table_new (mono_patch_info_hash, mono_patch_info_equal);
12563 info->patch_to_got_offset_by_type = g_new0 (GHashTable*, MONO_PATCH_INFO_NUM);
12564 for (i = 0; i < MONO_PATCH_INFO_NUM; ++i)
12565 info->patch_to_got_offset_by_type [i] = g_hash_table_new (mono_patch_info_hash, mono_patch_info_equal);
12566 info->got_patches = g_ptr_array_new ();
12569 static MonoAotCompile*
12570 acfg_create (MonoAssembly *ass, guint32 opts)
12572 MonoImage *image = ass->image;
12573 MonoAotCompile *acfg;
12575 acfg = g_new0 (MonoAotCompile, 1);
12576 acfg->methods = g_ptr_array_new ();
12577 acfg->method_indexes = g_hash_table_new (NULL, NULL);
12578 acfg->method_depth = g_hash_table_new (NULL, NULL);
12579 acfg->plt_offset_to_entry = g_hash_table_new (NULL, NULL);
12580 acfg->patch_to_plt_entry = g_new0 (GHashTable*, MONO_PATCH_INFO_NUM);
12581 acfg->method_to_cfg = g_hash_table_new (NULL, NULL);
12582 acfg->token_info_hash = g_hash_table_new_full (NULL, NULL, NULL, NULL);
12583 acfg->method_to_pinvoke_import = g_hash_table_new_full (NULL, NULL, NULL, g_free);
12584 acfg->method_to_external_icall_symbol_name = g_hash_table_new_full (NULL, NULL, NULL, g_free);
12585 acfg->image_hash = g_hash_table_new (NULL, NULL);
12586 acfg->image_table = g_ptr_array_new ();
12587 acfg->globals = g_ptr_array_new ();
12588 acfg->image = image;
12589 acfg->opts = opts;
12590 /* TODO: Write out set of SIMD instructions used, rather than just those available */
12591 #ifndef MONO_CROSS_COMPILE
12592 acfg->simd_opts = mono_arch_cpu_enumerate_simd_versions ();
12593 #endif
12594 acfg->mempool = mono_mempool_new ();
12595 acfg->extra_methods = g_ptr_array_new ();
12596 acfg->unwind_info_offsets = g_hash_table_new (NULL, NULL);
12597 acfg->unwind_ops = g_ptr_array_new ();
12598 acfg->method_label_hash = g_hash_table_new_full (g_str_hash, g_str_equal, g_free, NULL);
12599 acfg->method_order = g_ptr_array_new ();
12600 acfg->export_names = g_hash_table_new (NULL, NULL);
12601 acfg->klass_blob_hash = g_hash_table_new (NULL, NULL);
12602 acfg->method_blob_hash = g_hash_table_new (NULL, NULL);
12603 acfg->ginst_blob_hash = g_hash_table_new (mono_metadata_generic_inst_hash, mono_metadata_generic_inst_equal);
12604 acfg->plt_entry_debug_sym_cache = g_hash_table_new (g_str_hash, g_str_equal);
12605 acfg->gsharedvt_in_signatures = g_hash_table_new ((GHashFunc)mono_signature_hash, (GEqualFunc)mono_metadata_signature_equal);
12606 acfg->gsharedvt_out_signatures = g_hash_table_new ((GHashFunc)mono_signature_hash, (GEqualFunc)mono_metadata_signature_equal);
12607 acfg->profile_methods = g_hash_table_new (NULL, NULL);
12608 mono_os_mutex_init_recursive (&acfg->mutex);
12610 init_got_info (&acfg->got_info);
12611 init_got_info (&acfg->llvm_got_info);
12613 method_to_external_icall_symbol_name = acfg->method_to_external_icall_symbol_name;
12614 return acfg;
12617 static void
12618 got_info_free (GotInfo *info)
12620 int i;
12622 for (i = 0; i < MONO_PATCH_INFO_NUM; ++i)
12623 g_hash_table_destroy (info->patch_to_got_offset_by_type [i]);
12624 g_free (info->patch_to_got_offset_by_type);
12625 g_hash_table_destroy (info->patch_to_got_offset);
12626 g_ptr_array_free (info->got_patches, TRUE);
12629 static void
12630 acfg_free (MonoAotCompile *acfg)
12632 int i;
12634 mono_img_writer_destroy (acfg->w);
12635 for (i = 0; i < acfg->nmethods; ++i)
12636 if (acfg->cfgs [i])
12637 mono_destroy_compile (acfg->cfgs [i]);
12639 g_free (acfg->cfgs);
12641 g_free (acfg->static_linking_symbol);
12642 g_free (acfg->got_symbol);
12643 g_free (acfg->plt_symbol);
12644 g_ptr_array_free (acfg->methods, TRUE);
12645 g_ptr_array_free (acfg->image_table, TRUE);
12646 g_ptr_array_free (acfg->globals, TRUE);
12647 g_ptr_array_free (acfg->unwind_ops, TRUE);
12648 g_hash_table_destroy (acfg->method_indexes);
12649 g_hash_table_destroy (acfg->method_depth);
12650 g_hash_table_destroy (acfg->plt_offset_to_entry);
12651 for (i = 0; i < MONO_PATCH_INFO_NUM; ++i)
12652 g_hash_table_destroy (acfg->patch_to_plt_entry [i]);
12653 g_free (acfg->patch_to_plt_entry);
12654 g_hash_table_destroy (acfg->method_to_cfg);
12655 g_hash_table_destroy (acfg->token_info_hash);
12656 g_hash_table_destroy (acfg->method_to_pinvoke_import);
12657 g_hash_table_destroy (acfg->method_to_external_icall_symbol_name);
12658 g_hash_table_destroy (acfg->image_hash);
12659 g_hash_table_destroy (acfg->unwind_info_offsets);
12660 g_hash_table_destroy (acfg->method_label_hash);
12661 g_hash_table_destroy (acfg->typespec_classes);
12662 g_hash_table_destroy (acfg->export_names);
12663 g_hash_table_destroy (acfg->plt_entry_debug_sym_cache);
12664 g_hash_table_destroy (acfg->klass_blob_hash);
12665 g_hash_table_destroy (acfg->method_blob_hash);
12666 got_info_free (&acfg->got_info);
12667 got_info_free (&acfg->llvm_got_info);
12668 arch_free_unwind_info_section_cache (acfg);
12669 mono_mempool_destroy (acfg->mempool);
12671 method_to_external_icall_symbol_name = NULL;
12672 g_free (acfg);
12675 #define WRAPPER(e,n) n,
12676 static const char* const
12677 wrapper_type_names [MONO_WRAPPER_NUM + 1] = {
12678 #include "mono/metadata/wrapper-types.h"
12679 NULL
12682 static G_GNUC_UNUSED const char*
12683 get_wrapper_type_name (int type)
12685 return wrapper_type_names [type];
12688 //#define DUMP_PLT
12689 //#define DUMP_GOT
12691 static void aot_dump (MonoAotCompile *acfg)
12693 FILE *dumpfile;
12694 char * dumpname;
12696 JsonWriter writer;
12697 mono_json_writer_init (&writer);
12699 mono_json_writer_object_begin(&writer);
12701 // Methods
12702 mono_json_writer_indent (&writer);
12703 mono_json_writer_object_key(&writer, "methods");
12704 mono_json_writer_array_begin (&writer);
12706 int i;
12707 for (i = 0; i < acfg->nmethods; ++i) {
12708 MonoCompile *cfg;
12709 MonoMethod *method;
12710 MonoClass *klass;
12712 cfg = acfg->cfgs [i];
12713 if (ignore_cfg (cfg))
12714 continue;
12716 method = cfg->orig_method;
12718 mono_json_writer_indent (&writer);
12719 mono_json_writer_object_begin(&writer);
12721 mono_json_writer_indent (&writer);
12722 mono_json_writer_object_key(&writer, "name");
12723 mono_json_writer_printf (&writer, "\"%s\",\n", method->name);
12725 mono_json_writer_indent (&writer);
12726 mono_json_writer_object_key(&writer, "signature");
12727 mono_json_writer_printf (&writer, "\"%s\",\n", mono_method_get_full_name (method));
12729 mono_json_writer_indent (&writer);
12730 mono_json_writer_object_key(&writer, "code_size");
12731 mono_json_writer_printf (&writer, "\"%d\",\n", cfg->code_size);
12733 klass = method->klass;
12735 mono_json_writer_indent (&writer);
12736 mono_json_writer_object_key(&writer, "class");
12737 mono_json_writer_printf (&writer, "\"%s\",\n", m_class_get_name (klass));
12739 mono_json_writer_indent (&writer);
12740 mono_json_writer_object_key(&writer, "namespace");
12741 mono_json_writer_printf (&writer, "\"%s\",\n", m_class_get_name_space (klass));
12743 mono_json_writer_indent (&writer);
12744 mono_json_writer_object_key(&writer, "wrapper_type");
12745 mono_json_writer_printf (&writer, "\"%s\",\n", get_wrapper_type_name(method->wrapper_type));
12747 mono_json_writer_indent_pop (&writer);
12748 mono_json_writer_indent (&writer);
12749 mono_json_writer_object_end (&writer);
12750 mono_json_writer_printf (&writer, ",\n");
12753 mono_json_writer_indent_pop (&writer);
12754 mono_json_writer_indent (&writer);
12755 mono_json_writer_array_end (&writer);
12756 mono_json_writer_printf (&writer, ",\n");
12758 // PLT entries
12759 #ifdef DUMP_PLT
12760 mono_json_writer_indent_push (&writer);
12761 mono_json_writer_indent (&writer);
12762 mono_json_writer_object_key(&writer, "plt");
12763 mono_json_writer_array_begin (&writer);
12765 for (i = 0; i < acfg->plt_offset; ++i) {
12766 MonoPltEntry *plt_entry = NULL;
12767 MonoJumpInfo *ji;
12769 if (i == 0)
12771 * The first plt entry is unused.
12773 continue;
12775 plt_entry = g_hash_table_lookup (acfg->plt_offset_to_entry, GUINT_TO_POINTER (i));
12776 ji = plt_entry->ji;
12778 mono_json_writer_indent (&writer);
12779 mono_json_writer_printf (&writer, "{ ");
12780 mono_json_writer_object_key(&writer, "symbol");
12781 mono_json_writer_printf (&writer, "\"%s\" },\n", plt_entry->symbol);
12784 mono_json_writer_indent_pop (&writer);
12785 mono_json_writer_indent (&writer);
12786 mono_json_writer_array_end (&writer);
12787 mono_json_writer_printf (&writer, ",\n");
12788 #endif
12790 // GOT entries
12791 #ifdef DUMP_GOT
12792 mono_json_writer_indent_push (&writer);
12793 mono_json_writer_indent (&writer);
12794 mono_json_writer_object_key(&writer, "got");
12795 mono_json_writer_array_begin (&writer);
12797 mono_json_writer_indent_push (&writer);
12798 for (i = 0; i < acfg->got_info.got_patches->len; ++i) {
12799 MonoJumpInfo *ji = g_ptr_array_index (acfg->got_info.got_patches, i);
12801 mono_json_writer_indent (&writer);
12802 mono_json_writer_printf (&writer, "{ ");
12803 mono_json_writer_object_key(&writer, "patch_name");
12804 mono_json_writer_printf (&writer, "\"%s\" },\n", get_patch_name (ji->type));
12807 mono_json_writer_indent_pop (&writer);
12808 mono_json_writer_indent (&writer);
12809 mono_json_writer_array_end (&writer);
12810 mono_json_writer_printf (&writer, ",\n");
12811 #endif
12813 mono_json_writer_indent_pop (&writer);
12814 mono_json_writer_indent (&writer);
12815 mono_json_writer_object_end (&writer);
12817 dumpname = g_strdup_printf ("%s.json", g_path_get_basename (acfg->image->name));
12818 dumpfile = fopen (dumpname, "w+");
12819 g_free (dumpname);
12821 fprintf (dumpfile, "%s", writer.text->str);
12822 fclose (dumpfile);
12824 mono_json_writer_destroy (&writer);
12827 static const MonoJitICallId preinited_jit_icalls [] = {
12828 MONO_JIT_ICALL_mini_llvm_init_method,
12829 MONO_JIT_ICALL_mini_llvm_init_gshared_method_this,
12830 MONO_JIT_ICALL_mini_llvm_init_gshared_method_mrgctx,
12831 MONO_JIT_ICALL_mini_llvm_init_gshared_method_vtable,
12832 MONO_JIT_ICALL_mini_llvmonly_throw_nullref_exception,
12833 MONO_JIT_ICALL_mono_llvm_throw_corlib_exception,
12834 MONO_JIT_ICALL_mono_threads_state_poll,
12835 MONO_JIT_ICALL_mini_llvmonly_init_vtable_slot,
12836 MONO_JIT_ICALL_mono_helper_ldstr_mscorlib,
12837 MONO_JIT_ICALL_mono_fill_method_rgctx,
12838 MONO_JIT_ICALL_mono_fill_class_rgctx
12841 static void
12842 add_preinit_slot (MonoAotCompile *acfg, MonoJumpInfo *ji)
12844 if (!acfg->aot_opts.llvm_only)
12845 get_got_offset (acfg, FALSE, ji);
12846 get_got_offset (acfg, TRUE, ji);
12849 static void
12850 add_preinit_got_slots (MonoAotCompile *acfg)
12852 MonoJumpInfo *ji;
12853 int i;
12856 * Allocate the first few GOT entries to information which is needed frequently, or it is needed
12857 * during method initialization etc.
12860 ji = (MonoJumpInfo *)mono_mempool_alloc0 (acfg->mempool, sizeof (MonoJumpInfo));
12861 ji->type = MONO_PATCH_INFO_IMAGE;
12862 ji->data.image = acfg->image;
12863 add_preinit_slot (acfg, ji);
12865 ji = (MonoJumpInfo *)mono_mempool_alloc0 (acfg->mempool, sizeof (MonoJumpInfo));
12866 ji->type = MONO_PATCH_INFO_MSCORLIB_GOT_ADDR;
12867 add_preinit_slot (acfg, ji);
12869 ji = (MonoJumpInfo *)mono_mempool_alloc0 (acfg->mempool, sizeof (MonoJumpInfo));
12870 ji->type = MONO_PATCH_INFO_GC_CARD_TABLE_ADDR;
12871 add_preinit_slot (acfg, ji);
12873 ji = (MonoJumpInfo *)mono_mempool_alloc0 (acfg->mempool, sizeof (MonoJumpInfo));
12874 ji->type = MONO_PATCH_INFO_GC_NURSERY_START;
12875 add_preinit_slot (acfg, ji);
12877 ji = (MonoJumpInfo *)mono_mempool_alloc0 (acfg->mempool, sizeof (MonoJumpInfo));
12878 ji->type = MONO_PATCH_INFO_AOT_MODULE;
12879 add_preinit_slot (acfg, ji);
12881 ji = (MonoJumpInfo *)mono_mempool_alloc0 (acfg->mempool, sizeof (MonoJumpInfo));
12882 ji->type = MONO_PATCH_INFO_GC_NURSERY_BITS;
12883 add_preinit_slot (acfg, ji);
12885 ji = (MonoJumpInfo *)mono_mempool_alloc0 (acfg->mempool, sizeof (MonoJumpInfo));
12886 ji->type = MONO_PATCH_INFO_INTERRUPTION_REQUEST_FLAG;
12887 add_preinit_slot (acfg, ji);
12889 ji = (MonoJumpInfo *)mono_mempool_alloc0 (acfg->mempool, sizeof (MonoJumpInfo));
12890 ji->type = MONO_PATCH_INFO_GC_SAFE_POINT_FLAG;
12891 add_preinit_slot (acfg, ji);
12893 if (!acfg->aot_opts.llvm_only) {
12894 for (i = 0; i < TLS_KEY_NUM; i++) {
12895 ji = (MonoJumpInfo *)mono_mempool_alloc0 (acfg->mempool, sizeof (MonoJumpInfo));
12896 ji->type = MONO_PATCH_INFO_GET_TLS_TRAMP;
12897 ji->data.index = i;
12898 add_preinit_slot (acfg, ji);
12900 ji = (MonoJumpInfo *)mono_mempool_alloc0 (acfg->mempool, sizeof (MonoJumpInfo));
12901 ji->type = MONO_PATCH_INFO_SET_TLS_TRAMP;
12902 ji->data.index = i;
12903 add_preinit_slot (acfg, ji);
12907 /* Called by native-to-managed wrappers on possibly unattached threads */
12908 ji = (MonoJumpInfo *)mono_mempool_alloc0 (acfg->mempool, sizeof (MonoJumpInfo));
12909 ji->type = MONO_PATCH_INFO_JIT_ICALL_ADDR_NOCALL;
12910 ji->data.jit_icall_id = MONO_JIT_ICALL_mono_threads_attach_coop;
12911 add_preinit_slot (acfg, ji);
12913 for (i = 0; i < G_N_ELEMENTS (preinited_jit_icalls); ++i) {
12914 ji = (MonoJumpInfo *)mono_mempool_alloc0 (acfg->mempool, sizeof (MonoAotCompile));
12915 ji->type = MONO_PATCH_INFO_JIT_ICALL_ID;
12916 ji->data.jit_icall_id = preinited_jit_icalls [i];
12917 add_preinit_slot (acfg, ji);
12920 if (acfg->aot_opts.llvm_only)
12921 acfg->nshared_got_entries = acfg->llvm_got_offset;
12922 else
12923 acfg->nshared_got_entries = acfg->got_offset;
12924 g_assert (acfg->nshared_got_entries);
12927 static void
12928 mono_dedup_log_stats (MonoAotCompile *acfg)
12930 GHashTableIter iter;
12931 g_assert (acfg->dedup_stats);
12933 if (!acfg->dedup_emit_mode)
12934 return;
12936 // If dedup_emit_mode, acfg is the dummy dedup module that consolidates
12937 // deduped modules
12938 g_hash_table_iter_init (&iter, acfg->method_to_cfg);
12939 MonoCompile *dcfg = NULL;
12940 MonoMethod *method = NULL;
12942 size_t wrappers_size_saved = 0;
12943 size_t inflated_size_saved = 0;
12944 size_t copied_singles = 0;
12945 int wrappers_saved = 0;
12946 int instances_saved = 0;
12947 int copied = 0;
12949 while (g_hash_table_iter_next (&iter, (gpointer *) &method, (gpointer *)&dcfg)) {
12950 gchar *dedup_name = mono_aot_get_mangled_method_name (method);
12951 guint count = GPOINTER_TO_UINT(g_hash_table_lookup (acfg->dedup_stats, dedup_name));
12953 if (count == 0)
12954 continue;
12956 if (acfg->dedup_emit_mode) {
12957 // Size *saved* is the size due to things not emitted.
12958 if (count < 2) {
12959 // Just moved, didn't save space / dedup
12960 copied ++;
12961 copied_singles += dcfg->code_len;
12962 } else if (method->wrapper_type != MONO_WRAPPER_NONE) {
12963 wrappers_saved ++;
12964 wrappers_size_saved += dcfg->code_len * (count - 1);
12965 } else {
12966 instances_saved ++;
12967 inflated_size_saved += dcfg->code_len * (count - 1);
12970 if (acfg->aot_opts.dedup) {
12971 if (method->wrapper_type != MONO_WRAPPER_NONE) {
12972 wrappers_saved ++;
12973 wrappers_size_saved += dcfg->code_len * count;
12974 } else {
12975 instances_saved ++;
12976 inflated_size_saved += dcfg->code_len * count;
12981 aot_printf (acfg, "Dedup Pass: Size Saved From Deduped Wrappers:\t%d methods, %zu bytes\n", wrappers_saved, wrappers_size_saved);
12982 aot_printf (acfg, "Dedup Pass: Size Saved From Inflated Methods:\t%d methods, %zu bytes\n", instances_saved, inflated_size_saved);
12983 if (acfg->dedup_emit_mode)
12984 aot_printf (acfg, "Dedup Pass: Size of Moved But Not Deduped (only 1 copy) Methods:\t%d methods, %zu bytes\n", copied, copied_singles);
12986 g_hash_table_destroy (acfg->dedup_stats);
12987 acfg->dedup_stats = NULL;
12990 // Flush the cache to tell future calls what to skip
12991 static void
12992 mono_flush_method_cache (MonoAotCompile *acfg)
12994 GHashTable *method_cache = acfg->dedup_cache;
12995 char *filename = g_strdup_printf ("%s.dedup", acfg->image->name);
12996 if (!acfg->dedup_cache_changed || !acfg->aot_opts.dedup) {
12997 g_free (filename);
12998 return;
13001 acfg->dedup_cache = NULL;
13003 FILE *cache = fopen (filename, "w");
13005 if (!cache)
13006 g_error ("Could not create cache at %s because of error: %s\n", filename, strerror (errno));
13008 GHashTableIter iter;
13009 gchar *name = NULL;
13010 g_hash_table_iter_init (&iter, method_cache);
13011 gboolean cont = TRUE;
13012 while (cont && g_hash_table_iter_next (&iter, (gpointer *) &name, NULL)) {
13013 int res = fprintf (cache, "%s\n", name);
13014 cont = res >= 0;
13016 // FIXME: don't assert if error when flushing
13017 g_assert (cont);
13019 fclose (cache);
13020 g_free (filename);
13022 // The keys are all in the imageset, nothing to free
13023 // Values are just pointers to memory owned elsewhere, or sentinels
13024 g_hash_table_destroy (method_cache);
13027 // Read in what has been emitted by previous invocations,
13028 // what can be skipped
13029 static void
13030 mono_read_method_cache (MonoAotCompile *acfg)
13032 char *filename = g_strdup_printf ("%s.dedup", acfg->image->name);
13033 // Only do once, when dedup_cache is null
13034 if (acfg->dedup_cache)
13035 goto early_exit;
13037 if (acfg->aot_opts.dedup_include || acfg->aot_opts.dedup)
13038 g_assert (acfg->dedup_stats);
13040 // only in skip mode
13041 if (!acfg->aot_opts.dedup)
13042 goto early_exit;
13044 g_assert (acfg->dedup_cache);
13046 FILE *cache;
13047 cache = fopen (filename, "r");
13048 if (!cache)
13049 goto early_exit;
13051 // Since we do pointer comparisons, and it can't be allocated at
13052 // the address 0x1 due to alignment, we use this as a sentinel
13053 gpointer other_acfg_sentinel;
13054 other_acfg_sentinel = GINT_TO_POINTER (0x1);
13056 if (fseek (cache, 0L, SEEK_END))
13057 goto cleanup;
13059 size_t fileLength;
13060 fileLength = ftell (cache);
13061 g_assert (fileLength > 0);
13063 if (fseek (cache, 0L, SEEK_SET))
13064 goto cleanup;
13066 // Avoid thousands of new malloc entries
13067 // FIXME: allocate into imageset, so we don't need to free.
13068 // put the other mangled names there too.
13069 char *bulk;
13070 bulk = g_malloc0 (fileLength * sizeof (char));
13071 size_t offset;
13072 offset = 0;
13074 while (fgets (&bulk [offset], fileLength - offset, cache)) {
13075 // strip newline
13076 char *line = &bulk [offset];
13077 size_t len = strlen (line);
13078 if (len == 0)
13079 break;
13081 if (len >= 0 && line [len] == '\n')
13082 line [len] = '\0';
13083 offset += strlen (line) + 1;
13084 g_assert (fileLength >= offset);
13086 g_hash_table_insert (acfg->dedup_cache, line, other_acfg_sentinel);
13089 cleanup:
13090 fclose (cache);
13092 early_exit:
13093 g_free (filename);
13094 return;
13097 typedef struct {
13098 GHashTable *cache;
13099 GHashTable *stats;
13100 gboolean emit_inflated_methods;
13101 MonoAssembly *inflated_assembly;
13102 } MonoAotState;
13104 static MonoAotState *
13105 alloc_aot_state (void)
13107 MonoAotState *state = g_malloc (sizeof (MonoAotState));
13108 // FIXME: Should this own the memory?
13109 state->cache = g_hash_table_new (g_str_hash, g_str_equal);
13110 state->stats = g_hash_table_new (g_str_hash, g_str_equal);
13111 // Start in "collect mode"
13112 state->emit_inflated_methods = FALSE;
13113 state->inflated_assembly = NULL;
13114 return state;
13117 static void
13118 free_aot_state (MonoAotState *astate)
13120 g_hash_table_destroy (astate->cache);
13121 g_free (astate);
13124 static void
13125 mono_add_deferred_extra_methods (MonoAotCompile *acfg, MonoAotState *astate)
13127 GHashTableIter iter;
13128 gchar *name = NULL;
13129 MonoMethod *method = NULL;
13131 acfg->dedup_emit_mode = TRUE;
13133 g_hash_table_iter_init (&iter, astate->cache);
13134 while (g_hash_table_iter_next (&iter, (gpointer *) &name, (gpointer *) &method)) {
13135 add_method_full (acfg, method, TRUE, 0);
13137 return;
13140 static void
13141 mono_setup_dedup_state (MonoAotCompile *acfg, MonoAotState **global_aot_state, MonoAssembly *ass, MonoAotState **astate, gboolean *is_dedup_dummy)
13143 if (!acfg->aot_opts.dedup_include && !acfg->aot_opts.dedup)
13144 return;
13146 if (global_aot_state && *global_aot_state && acfg->aot_opts.dedup_include) {
13147 // Thread the state through when making the inflate pass
13148 *astate = *global_aot_state;
13151 if (!*astate) {
13152 *astate = alloc_aot_state ();
13153 *global_aot_state = *astate;
13156 acfg->dedup_cache = (*astate)->cache;
13157 acfg->dedup_stats = (*astate)->stats;
13159 // fills out acfg->dedup_cache
13160 if (acfg->aot_opts.dedup)
13161 mono_read_method_cache (acfg);
13163 if (!(*astate)->inflated_assembly && acfg->aot_opts.dedup_include) {
13164 gchar **asm_path = g_strsplit (ass->image->name, G_DIR_SEPARATOR_S, 0);
13165 gchar *asm_file = NULL;
13167 // Get the last part of the path, the filename
13168 for (int i=0; asm_path [i] != NULL; i++)
13169 asm_file = asm_path [i];
13171 if (!strcmp (acfg->aot_opts.dedup_include, asm_file)) {
13172 // Save
13173 *is_dedup_dummy = TRUE;
13174 (*astate)->inflated_assembly = ass;
13176 g_strfreev (asm_path);
13177 } else if ((*astate)->inflated_assembly) {
13178 *is_dedup_dummy = (ass == (*astate)->inflated_assembly);
13182 int
13183 mono_compile_deferred_assemblies (guint32 opts, const char *aot_options, gpointer **aot_state)
13185 // create assembly, loop and add extra_methods
13186 // in add_generic_instances , rip out what's in that for loop
13187 // and apply that to this aot_state inside of mono_compile_assembly
13188 MonoAotState *astate;
13189 astate = *(MonoAotState **)aot_state;
13190 g_assert (astate);
13192 // FIXME: allow suffixes?
13193 if (!astate->inflated_assembly) {
13194 const char* inflate = strstr (aot_options, "dedup-inflate");
13195 if (!inflate)
13196 return 0;
13197 else
13198 g_error ("Error: mono was not given an assembly with the provided inflate name\n");
13201 // Switch modes
13202 astate->emit_inflated_methods = TRUE;
13204 int res = mono_compile_assembly (astate->inflated_assembly, opts, aot_options, aot_state);
13206 *aot_state = NULL;
13207 free_aot_state (astate);
13209 return res;
13212 #ifndef MONO_ARCH_HAVE_INTERP_ENTRY_TRAMPOLINE
13213 static MonoMethodSignature * const * const interp_in_static_sigs [] = {
13214 &mono_icall_sig_bool_ptr_int32_ptrref,
13215 &mono_icall_sig_bool_ptr_ptrref,
13216 &mono_icall_sig_int32_int32_ptrref,
13217 &mono_icall_sig_int32_int32_ptr_ptrref,
13218 &mono_icall_sig_int32_ptr_int32_ptr,
13219 &mono_icall_sig_int32_ptr_int32_ptrref,
13220 &mono_icall_sig_int32_ptr_ptrref,
13221 &mono_icall_sig_object_object_ptr_ptr_ptr,
13222 &mono_icall_sig_object,
13223 &mono_icall_sig_ptr_int32_ptrref,
13224 &mono_icall_sig_ptr_ptr_int32_ptr_ptr_ptrref,
13225 &mono_icall_sig_ptr_ptr_int32_ptr_ptrref,
13226 &mono_icall_sig_ptr_ptr_int32_ptrref,
13227 &mono_icall_sig_ptr_ptr_ptr_int32_ptrref,
13228 &mono_icall_sig_ptr_ptr_ptr_ptrref_ptrref,
13229 &mono_icall_sig_ptr_ptr_ptr_ptr_ptrref,
13230 &mono_icall_sig_ptr_ptr_ptr_ptrref,
13231 &mono_icall_sig_ptr_ptr_ptrref,
13232 &mono_icall_sig_ptr_ptr_uint32_ptrref,
13233 &mono_icall_sig_ptr_uint32_ptrref,
13234 &mono_icall_sig_void_object_ptr_ptr_ptr,
13235 &mono_icall_sig_void_ptr_ptr_int32_ptr_ptrref_ptr_ptrref,
13236 &mono_icall_sig_void_ptr_ptr_int32_ptr_ptrref,
13237 &mono_icall_sig_void_ptr_ptr_ptrref,
13238 &mono_icall_sig_void_ptr_ptrref,
13239 &mono_icall_sig_void_ptr,
13240 &mono_icall_sig_void_int32_ptrref,
13241 &mono_icall_sig_void_uint32_ptrref,
13242 &mono_icall_sig_void,
13244 #endif
13247 mono_compile_assembly (MonoAssembly *ass, guint32 opts, const char *aot_options, gpointer **global_aot_state)
13249 MonoImage *image = ass->image;
13250 int res;
13251 MonoAotCompile *acfg;
13252 char *p;
13253 TV_DECLARE (atv);
13254 TV_DECLARE (btv);
13256 acfg = acfg_create (ass, opts);
13258 memset (&acfg->aot_opts, 0, sizeof (acfg->aot_opts));
13259 acfg->aot_opts.write_symbols = TRUE;
13260 acfg->aot_opts.ntrampolines = 4096;
13261 acfg->aot_opts.nrgctx_trampolines = 4096;
13262 acfg->aot_opts.nimt_trampolines = 512;
13263 acfg->aot_opts.nrgctx_fetch_trampolines = 128;
13264 acfg->aot_opts.ngsharedvt_arg_trampolines = 512;
13265 #ifdef MONO_ARCH_HAVE_FTNPTR_ARG_TRAMPOLINE
13266 acfg->aot_opts.nftnptr_arg_trampolines = 128;
13267 #endif
13268 acfg->aot_opts.nunbox_arbitrary_trampolines = 256;
13269 if (!acfg->aot_opts.llvm_path)
13270 acfg->aot_opts.llvm_path = g_strdup ("");
13271 acfg->aot_opts.temp_path = g_strdup ("");
13272 #ifdef MONOTOUCH
13273 acfg->aot_opts.use_trampolines_page = TRUE;
13274 #endif
13275 acfg->aot_opts.clangxx = g_strdup ("clang++");
13277 mono_aot_parse_options (aot_options, &acfg->aot_opts);
13279 // start dedup
13280 MonoAotState *astate = NULL;
13281 gboolean is_dedup_dummy = FALSE;
13282 mono_setup_dedup_state (acfg, (MonoAotState **) global_aot_state, ass, &astate, &is_dedup_dummy);
13284 // Process later
13285 if (is_dedup_dummy && astate && !astate->emit_inflated_methods)
13286 return 0;
13288 if (acfg->aot_opts.dedup_include && !is_dedup_dummy)
13289 acfg->dedup_collect_only = TRUE;
13290 // end dedup
13292 if (acfg->aot_opts.logfile) {
13293 acfg->logfile = fopen (acfg->aot_opts.logfile, "a+");
13296 if (acfg->aot_opts.data_outfile) {
13297 acfg->data_outfile = fopen (acfg->aot_opts.data_outfile, "w+");
13298 if (!acfg->data_outfile) {
13299 aot_printerrf (acfg, "Unable to create file '%s': %s\n", acfg->aot_opts.data_outfile, strerror (errno));
13300 return 1;
13302 acfg->flags = (MonoAotFileFlags)(acfg->flags | MONO_AOT_FILE_FLAG_SEPARATE_DATA);
13305 //acfg->aot_opts.print_skipped_methods = TRUE;
13307 #if !defined(MONO_ARCH_GSHAREDVT_SUPPORTED)
13308 if (acfg->opts & MONO_OPT_GSHAREDVT) {
13309 aot_printerrf (acfg, "-O=gsharedvt not supported on this platform.\n");
13310 return 1;
13312 if (acfg->aot_opts.llvm_only) {
13313 aot_printerrf (acfg, "--aot=llvmonly requires a runtime that supports gsharedvt.\n");
13314 return 1;
13316 #else
13317 if (acfg->aot_opts.llvm_only || mono_aot_mode_is_full (&acfg->aot_opts) || mono_aot_mode_is_hybrid (&acfg->aot_opts))
13318 acfg->opts |= MONO_OPT_GSHAREDVT;
13319 #endif
13321 #if !defined(ENABLE_LLVM)
13322 if (acfg->aot_opts.llvm_only) {
13323 aot_printerrf (acfg, "--aot=llvmonly requires a runtime compiled with llvm support.\n");
13324 return 1;
13326 #endif
13328 if (acfg->opts & MONO_OPT_GSHAREDVT)
13329 mono_set_generic_sharing_vt_supported (TRUE);
13331 if (!acfg->dedup_collect_only)
13332 aot_printf (acfg, "Mono Ahead of Time compiler - compiling assembly %s\n", image->name);
13334 if (!acfg->aot_opts.deterministic)
13335 generate_aotid ((guint8*) &acfg->image->aotid);
13337 char *aotid = mono_guid_to_string (acfg->image->aotid);
13338 if (!acfg->dedup_collect_only)
13339 aot_printf (acfg, "AOTID %s\n", aotid);
13340 g_free (aotid);
13342 #ifndef MONO_ARCH_HAVE_FULL_AOT_TRAMPOLINES
13343 if (mono_aot_mode_is_full (&acfg->aot_opts)) {
13344 aot_printerrf (acfg, "--aot=full is not supported on this platform.\n");
13345 return 1;
13347 #endif
13349 if (acfg->aot_opts.direct_pinvoke && !acfg->aot_opts.static_link) {
13350 aot_printerrf (acfg, "The 'direct-pinvoke' AOT option also requires the 'static' AOT option.\n");
13351 return 1;
13354 if (acfg->aot_opts.static_link)
13355 acfg->aot_opts.asm_writer = TRUE;
13357 if (acfg->aot_opts.soft_debug) {
13358 MonoDebugOptions *opt = mini_get_debug_options ();
13360 opt->mdb_optimizations = TRUE;
13361 opt->gen_sdb_seq_points = TRUE;
13363 if (!mono_debug_enabled ()) {
13364 aot_printerrf (acfg, "The soft-debug AOT option requires the --debug option.\n");
13365 return 1;
13367 acfg->flags = (MonoAotFileFlags)(acfg->flags | MONO_AOT_FILE_FLAG_DEBUG);
13370 if (acfg->aot_opts.try_llvm)
13371 acfg->aot_opts.llvm = mini_llvm_init ();
13373 if (mono_use_llvm || acfg->aot_opts.llvm) {
13374 acfg->llvm = TRUE;
13375 acfg->aot_opts.asm_writer = TRUE;
13376 acfg->flags = (MonoAotFileFlags)(acfg->flags | MONO_AOT_FILE_FLAG_WITH_LLVM);
13378 if (acfg->aot_opts.soft_debug) {
13379 aot_printerrf (acfg, "The 'soft-debug' option is not supported when compiling with LLVM.\n");
13380 return 1;
13383 mini_llvm_init ();
13385 if (acfg->aot_opts.asm_only && !acfg->aot_opts.llvm_outfile) {
13386 aot_printerrf (acfg, "Compiling with LLVM and the asm-only option requires the llvm-outfile= option.\n");
13387 return 1;
13391 if (mono_aot_mode_is_full (&acfg->aot_opts)) {
13392 acfg->flags = (MonoAotFileFlags)(acfg->flags | MONO_AOT_FILE_FLAG_FULL_AOT);
13393 acfg->is_full_aot = TRUE;
13396 if (mono_aot_mode_is_interp (&acfg->aot_opts)) {
13397 acfg->flags = (MonoAotFileFlags)(acfg->flags | MONO_AOT_FILE_FLAG_INTERP);
13398 acfg->is_full_aot = TRUE;
13401 if (mini_safepoints_enabled ())
13402 acfg->flags = (MonoAotFileFlags)(acfg->flags | MONO_AOT_FILE_FLAG_SAFEPOINTS);
13404 // The methods in dedup-emit amodules must be available on runtime startup
13405 // Note: Only one such amodule can have this attribute
13406 if (astate && astate->emit_inflated_methods)
13407 acfg->flags = (MonoAotFileFlags)(acfg->flags | MONO_AOT_FILE_FLAG_EAGER_LOAD);
13410 if (acfg->aot_opts.instances_logfile_path) {
13411 acfg->instances_logfile = fopen (acfg->aot_opts.instances_logfile_path, "w");
13412 if (!acfg->instances_logfile) {
13413 aot_printerrf (acfg, "Unable to create logfile: '%s'.\n", acfg->aot_opts.instances_logfile_path);
13414 return 1;
13418 if (acfg->aot_opts.profile_files) {
13419 GList *l;
13421 for (l = acfg->aot_opts.profile_files; l; l = l->next) {
13422 load_profile_file (acfg, (char*)l->data);
13426 if (!(mono_aot_mode_is_interp (&acfg->aot_opts) && !mono_aot_mode_is_full (&acfg->aot_opts))) {
13427 for (int method_index = 0; method_index < acfg->image->tables [MONO_TABLE_METHOD].rows; ++method_index)
13428 g_ptr_array_add (acfg->method_order,GUINT_TO_POINTER (method_index));
13431 acfg->num_trampolines [MONO_AOT_TRAMP_SPECIFIC] = mono_aot_mode_is_full (&acfg->aot_opts) ? acfg->aot_opts.ntrampolines : 0;
13432 #ifdef MONO_ARCH_GSHARED_SUPPORTED
13433 acfg->num_trampolines [MONO_AOT_TRAMP_STATIC_RGCTX] = mono_aot_mode_is_full (&acfg->aot_opts) ? acfg->aot_opts.nrgctx_trampolines : 0;
13434 #endif
13435 acfg->num_trampolines [MONO_AOT_TRAMP_IMT] = mono_aot_mode_is_full (&acfg->aot_opts) ? acfg->aot_opts.nimt_trampolines : 0;
13436 #ifdef MONO_ARCH_GSHAREDVT_SUPPORTED
13437 if (acfg->opts & MONO_OPT_GSHAREDVT)
13438 acfg->num_trampolines [MONO_AOT_TRAMP_GSHAREDVT_ARG] = mono_aot_mode_is_full (&acfg->aot_opts) ? acfg->aot_opts.ngsharedvt_arg_trampolines : 0;
13439 #endif
13440 #ifdef MONO_ARCH_HAVE_FTNPTR_ARG_TRAMPOLINE
13441 acfg->num_trampolines [MONO_AOT_TRAMP_FTNPTR_ARG] = mono_aot_mode_is_interp (&acfg->aot_opts) ? acfg->aot_opts.nftnptr_arg_trampolines : 0;
13442 #endif
13443 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;
13445 acfg->temp_prefix = mono_img_writer_get_temp_label_prefix (NULL);
13447 arch_init (acfg);
13449 if (mono_use_llvm || acfg->aot_opts.llvm) {
13451 * Emit all LLVM code into a separate assembly/object file and link with it
13452 * normally.
13454 if (!acfg->aot_opts.asm_only && acfg->llvm_owriter_supported) {
13455 acfg->llvm_owriter = TRUE;
13456 } else if (acfg->aot_opts.llvm_outfile) {
13457 int len = strlen (acfg->aot_opts.llvm_outfile);
13459 if (len >= 2 && acfg->aot_opts.llvm_outfile [len - 2] == '.' && acfg->aot_opts.llvm_outfile [len - 1] == 'o')
13460 acfg->llvm_owriter = TRUE;
13464 if (acfg->llvm && acfg->thumb_mixed)
13465 acfg->flags = (MonoAotFileFlags)(acfg->flags | MONO_AOT_FILE_FLAG_LLVM_THUMB);
13466 if (acfg->aot_opts.llvm_only)
13467 acfg->flags = (MonoAotFileFlags)(acfg->flags | MONO_AOT_FILE_FLAG_LLVM_ONLY);
13469 acfg->assembly_name_sym = g_strdup (acfg->image->assembly->aname.name);
13470 /* Get rid of characters which cannot occur in symbols */
13471 for (p = acfg->assembly_name_sym; *p; ++p) {
13472 if (!(isalnum (*p) || *p == '_'))
13473 *p = '_';
13476 acfg->global_prefix = g_strdup_printf ("mono_aot_%s", acfg->assembly_name_sym);
13477 acfg->plt_symbol = g_strdup_printf ("%s_plt", acfg->global_prefix);
13478 acfg->got_symbol = g_strdup_printf ("%s_got", acfg->global_prefix);
13479 if (acfg->llvm) {
13480 acfg->llvm_got_symbol = g_strdup_printf ("%s_llvm_got", acfg->global_prefix);
13481 acfg->llvm_eh_frame_symbol = g_strdup_printf ("%s_eh_frame", acfg->global_prefix);
13484 acfg->method_index = 1;
13486 if (mono_aot_mode_is_full (&acfg->aot_opts) || mono_aot_mode_is_hybrid (&acfg->aot_opts))
13487 mono_set_partial_sharing_supported (TRUE);
13489 if (!(mono_aot_mode_is_interp (&acfg->aot_opts) && !mono_aot_mode_is_full (&acfg->aot_opts))) {
13490 res = collect_methods (acfg);
13491 if (!res)
13492 return 1;
13495 // If we're emitting all of the inflated methods into a dummy
13496 // Assembly, then after extra_methods is set up, we're done
13497 // in this function.
13498 if (astate && astate->emit_inflated_methods)
13499 mono_add_deferred_extra_methods (acfg, astate);
13502 GList *l;
13504 for (l = acfg->profile_data; l; l = l->next)
13505 resolve_profile_data (acfg, (ProfileData*)l->data, ass);
13506 for (l = acfg->profile_data; l; l = l->next)
13507 add_profile_instances (acfg, (ProfileData*)l->data);
13510 acfg->cfgs_size = acfg->methods->len + 32;
13511 acfg->cfgs = g_new0 (MonoCompile*, acfg->cfgs_size);
13513 /* PLT offset 0 is reserved for the PLT trampoline */
13514 acfg->plt_offset = 1;
13515 add_preinit_got_slots (acfg);
13517 #ifdef ENABLE_LLVM
13518 if (acfg->llvm) {
13519 llvm_acfg = acfg;
13520 LLVMModuleFlags flags = 0;
13521 #ifdef EMIT_DWARF_INFO
13522 flags = LLVM_MODULE_FLAG_DWARF;
13523 #endif
13524 #ifdef EMIT_WIN32_CODEVIEW_INFO
13525 flags = LLVM_MODULE_FLAG_CODEVIEW;
13526 #endif
13527 if (acfg->aot_opts.static_link)
13528 flags = (LLVMModuleFlags)(flags | LLVM_MODULE_FLAG_STATIC);
13529 if (acfg->aot_opts.llvm_only)
13530 flags = (LLVMModuleFlags)(flags | LLVM_MODULE_FLAG_LLVM_ONLY);
13531 if (acfg->aot_opts.interp)
13532 flags = (LLVMModuleFlags)(flags | LLVM_MODULE_FLAG_INTERP);
13533 mono_llvm_create_aot_module (acfg->image->assembly, acfg->global_prefix, acfg->nshared_got_entries, flags);
13535 add_lazy_init_wrappers (acfg);
13537 #endif
13539 if (mono_aot_mode_is_interp (&acfg->aot_opts) && mono_is_corlib_image (acfg->image->assembly->image)) {
13540 MonoMethod *wrapper = mini_get_interp_lmf_wrapper ("mono_interp_to_native_trampoline", (gpointer) mono_interp_to_native_trampoline);
13541 add_method (acfg, wrapper);
13543 wrapper = mini_get_interp_lmf_wrapper ("mono_interp_entry_from_trampoline", (gpointer) mono_interp_entry_from_trampoline);
13544 add_method (acfg, wrapper);
13546 #ifndef MONO_ARCH_HAVE_INTERP_ENTRY_TRAMPOLINE
13547 for (int i = 0; i < G_N_ELEMENTS (interp_in_static_sigs); i++) {
13548 MonoMethodSignature *sig = *interp_in_static_sigs [i];
13549 sig = mono_metadata_signature_dup_full (mono_get_corlib (), sig);
13550 sig->pinvoke = FALSE;
13551 wrapper = mini_get_interp_in_wrapper (sig);
13552 add_method (acfg, wrapper);
13554 #endif
13556 /* required for mixed mode */
13557 if (strcmp (acfg->image->assembly->aname.name, "mscorlib") == 0) {
13558 add_gc_wrappers (acfg);
13560 for (int i = 0; i < MONO_JIT_ICALL_count; ++i)
13561 add_jit_icall_wrapper (acfg, mono_find_jit_icall_info ((MonoJitICallId)i));
13565 TV_GETTIME (atv);
13567 compile_methods (acfg);
13569 TV_GETTIME (btv);
13571 acfg->stats.jit_time = TV_ELAPSED (atv, btv);
13573 dedup_skip_methods (acfg);
13575 if (acfg->aot_opts.dedup_include && !is_dedup_dummy)
13576 /* We only collected methods from this assembly */
13577 return 0;
13579 return emit_aot_image (acfg);
13582 static void
13583 print_stats (MonoAotCompile *acfg)
13585 int i;
13586 gint64 all_sizes;
13587 char llvm_stats_msg [256];
13589 if (acfg->llvm && !acfg->aot_opts.llvm_only)
13590 sprintf (llvm_stats_msg, ", LLVM: %d (%d%%)", acfg->stats.llvm_count, acfg->stats.mcount ? (acfg->stats.llvm_count * 100) / acfg->stats.mcount : 100);
13591 else
13592 strcpy (llvm_stats_msg, "");
13594 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;
13596 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",
13597 (int)acfg->stats.code_size, (int)(acfg->stats.code_size * 100 / all_sizes),
13598 (int)acfg->stats.method_info_size, (int)(acfg->stats.method_info_size * 100 / all_sizes),
13599 (int)acfg->stats.ex_info_size, (int)(acfg->stats.ex_info_size * 100 / all_sizes),
13600 (int)acfg->stats.unwind_info_size, (int)(acfg->stats.unwind_info_size * 100 / all_sizes),
13601 (int)acfg->stats.class_info_size, (int)(acfg->stats.class_info_size * 100 / all_sizes),
13602 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,
13603 (int)acfg->stats.got_info_size, (int)(acfg->stats.got_info_size * 100 / all_sizes),
13604 (int)acfg->stats.offsets_size, (int)(acfg->stats.offsets_size * 100 / all_sizes),
13605 (int)(acfg->got_offset * sizeof (target_mgreg_t)),
13606 (int)acfg->stats.blob_size);
13607 aot_printf (acfg, "Compiled: %d/%d (%d%%)%s, No GOT slots: %d (%d%%), Direct calls: %d (%d%%)\n",
13608 acfg->stats.ccount, acfg->stats.mcount, acfg->stats.mcount ? (acfg->stats.ccount * 100) / acfg->stats.mcount : 100,
13609 llvm_stats_msg,
13610 acfg->stats.methods_without_got_slots, acfg->stats.mcount ? (acfg->stats.methods_without_got_slots * 100) / acfg->stats.mcount : 100,
13611 acfg->stats.direct_calls, acfg->stats.all_calls ? (acfg->stats.direct_calls * 100) / acfg->stats.all_calls : 100);
13612 if (acfg->stats.genericcount)
13613 aot_printf (acfg, "%d methods failed gsharing (%d%%)\n", acfg->stats.genericcount, acfg->stats.mcount ? (acfg->stats.genericcount * 100) / acfg->stats.mcount : 100);
13614 if (acfg->stats.abscount)
13615 aot_printf (acfg, "%d methods contain absolute addresses (%d%%)\n", acfg->stats.abscount, acfg->stats.mcount ? (acfg->stats.abscount * 100) / acfg->stats.mcount : 100);
13616 if (acfg->stats.lmfcount)
13617 aot_printf (acfg, "%d methods contain lmf pointers (%d%%)\n", acfg->stats.lmfcount, acfg->stats.mcount ? (acfg->stats.lmfcount * 100) / acfg->stats.mcount : 100);
13618 if (acfg->stats.ocount)
13619 aot_printf (acfg, "%d methods have other problems (%d%%)\n", acfg->stats.ocount, acfg->stats.mcount ? (acfg->stats.ocount * 100) / acfg->stats.mcount : 100);
13621 aot_printf (acfg, "GOT slot distribution:\n");
13622 int nslots = 0;
13623 int size = 0;
13624 for (i = 0; i < MONO_PATCH_INFO_NUM; ++i) {
13625 nslots += acfg->stats.got_slot_types [i];
13626 size += acfg->stats.got_slot_info_sizes [i];
13627 if (acfg->stats.got_slot_types [i])
13628 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]);
13630 aot_printf (acfg, "GOT SLOTS: %d, INFO SIZE: %d\n", nslots, size);
13632 aot_printf (acfg, "\nEncoding stats:\n");
13633 aot_printf (acfg, "\tMethod ref: %d (%dk)\n", acfg->stats.method_ref_count, acfg->stats.method_ref_size / 1024);
13634 aot_printf (acfg, "\tClass ref: %d (%dk)\n", acfg->stats.class_ref_count, acfg->stats.class_ref_size / 1024);
13635 aot_printf (acfg, "\tGinst: %d (%dk)\n", acfg->stats.ginst_count, acfg->stats.ginst_size / 1024);
13637 aot_printf (acfg, "\nMethod stats:\n");
13638 aot_printf (acfg, "\tNormal: %d\n", acfg->stats.method_categories [METHOD_CAT_NORMAL]);
13639 aot_printf (acfg, "\tInstance: %d\n", acfg->stats.method_categories [METHOD_CAT_INST]);
13640 aot_printf (acfg, "\tGSharedvt: %d\n", acfg->stats.method_categories [METHOD_CAT_GSHAREDVT]);
13641 aot_printf (acfg, "\tWrapper: %d\n", acfg->stats.method_categories [METHOD_CAT_WRAPPER]);
13643 if (acfg->aot_opts.dedup || acfg->dedup_emit_mode)
13644 mono_dedup_log_stats (acfg);
13647 static void
13648 create_depfile (MonoAotCompile *acfg)
13650 FILE *depfile;
13652 // FIXME: Support other configurations
13653 g_assert (acfg->aot_opts.llvm_only && acfg->aot_opts.asm_only && acfg->aot_opts.llvm_outfile);
13655 depfile = fopen (acfg->aot_opts.depfile, "w");
13656 g_assert (depfile);
13658 int ntargets = 1;
13659 char **targets = g_new0 (char*, ntargets);
13660 targets [0] = acfg->aot_opts.llvm_outfile;
13661 for (int tindex = 0; tindex < ntargets; ++tindex) {
13662 fprintf (depfile, "%s: ", targets [tindex]);
13663 for (int i = 0; i < acfg->image_table->len; i++) {
13664 MonoImage *image = (MonoImage*)g_ptr_array_index (acfg->image_table, i);
13665 fprintf (depfile, " %s", image->filename);
13667 fprintf (depfile, "\n");
13669 g_free (targets);
13670 fclose (depfile);
13673 static int
13674 emit_aot_image (MonoAotCompile *acfg)
13676 int i, res;
13677 TV_DECLARE (atv);
13678 TV_DECLARE (btv);
13680 TV_GETTIME (atv);
13682 #ifdef ENABLE_LLVM
13683 if (acfg->llvm) {
13684 if (acfg->aot_opts.asm_only) {
13685 if (acfg->aot_opts.outfile) {
13686 acfg->tmpfname = g_strdup_printf ("%s", acfg->aot_opts.outfile);
13687 acfg->tmpbasename = g_strdup (acfg->tmpfname);
13688 } else {
13689 acfg->tmpbasename = g_strdup_printf ("%s", acfg->image->name);
13690 acfg->tmpfname = g_strdup_printf ("%s.s", acfg->tmpbasename);
13692 g_assert (acfg->aot_opts.llvm_outfile);
13693 acfg->llvm_sfile = g_strdup (acfg->aot_opts.llvm_outfile);
13694 if (acfg->llvm_owriter)
13695 acfg->llvm_ofile = g_strdup (acfg->aot_opts.llvm_outfile);
13696 else
13697 acfg->llvm_sfile = g_strdup (acfg->aot_opts.llvm_outfile);
13698 } else {
13699 gchar *temp_path;
13700 if (strcmp (acfg->aot_opts.temp_path, "") != 0) {
13701 temp_path = g_strdup (acfg->aot_opts.temp_path);
13702 } else {
13703 temp_path = g_mkdtemp (g_strdup ("mono_aot_XXXXXX"));
13704 g_assertf (temp_path, "mkdtemp failed, error = (%d) %s", errno, g_strerror (errno));
13705 acfg->temp_dir_to_delete = g_strdup (temp_path);
13708 acfg->tmpbasename = g_build_filename (temp_path, "temp", NULL);
13709 acfg->tmpfname = g_strdup_printf ("%s.s", acfg->tmpbasename);
13710 acfg->llvm_sfile = g_strdup_printf ("%s-llvm.s", acfg->tmpbasename);
13711 acfg->llvm_ofile = g_strdup_printf ("%s-llvm." AS_OBJECT_FILE_SUFFIX, acfg->tmpbasename);
13713 g_free (temp_path);
13716 #endif
13718 if (acfg->aot_opts.asm_only && !acfg->aot_opts.llvm_only) {
13719 if (acfg->aot_opts.outfile)
13720 acfg->tmpfname = g_strdup_printf ("%s", acfg->aot_opts.outfile);
13721 else
13722 acfg->tmpfname = g_strdup_printf ("%s.s", acfg->image->name);
13723 acfg->fp = fopen (acfg->tmpfname, "w+");
13724 } else {
13725 if (strcmp (acfg->aot_opts.temp_path, "") == 0) {
13726 int i = g_file_open_tmp ("mono_aot_XXXXXX", &acfg->tmpfname, NULL);
13727 acfg->fp = fdopen (i, "w+");
13728 } else {
13729 acfg->tmpbasename = g_build_filename (acfg->aot_opts.temp_path, "temp", NULL);
13730 acfg->tmpfname = g_strdup_printf ("%s.s", acfg->tmpbasename);
13731 acfg->fp = fopen (acfg->tmpfname, "w+");
13734 if (acfg->fp == 0 && !acfg->aot_opts.llvm_only) {
13735 aot_printerrf (acfg, "Unable to open file '%s': %s\n", acfg->tmpfname, strerror (errno));
13736 return 1;
13738 if (acfg->fp)
13739 acfg->w = mono_img_writer_create (acfg->fp, FALSE);
13741 /* Compute symbols for methods */
13742 for (i = 0; i < acfg->nmethods; ++i) {
13743 if (acfg->cfgs [i]) {
13744 MonoCompile *cfg = acfg->cfgs [i];
13745 int method_index = get_method_index (acfg, cfg->orig_method);
13747 if (cfg->asm_symbol) {
13748 // Set by method emitter in backend
13749 if (acfg->llvm_label_prefix) {
13750 char *old_symbol = cfg->asm_symbol;
13751 cfg->asm_symbol = g_strdup_printf ("%s%s", acfg->llvm_label_prefix, cfg->asm_symbol);
13752 g_free (old_symbol);
13754 } else if (COMPILE_LLVM (cfg)) {
13755 cfg->asm_symbol = g_strdup_printf ("%s%s", acfg->llvm_label_prefix, cfg->llvm_method_name);
13756 } else if (acfg->global_symbols || acfg->llvm) {
13757 cfg->asm_symbol = get_debug_sym (cfg->orig_method, "", acfg->method_label_hash);
13758 } else {
13759 cfg->asm_symbol = g_strdup_printf ("%s%sm_%x", acfg->temp_prefix, acfg->llvm_label_prefix, method_index);
13761 cfg->asm_debug_symbol = cfg->asm_symbol;
13765 if (acfg->aot_opts.dwarf_debug && acfg->aot_opts.gnu_asm) {
13767 * CLANG supports GAS .file/.loc directives, so emit line number information this way
13769 acfg->gas_line_numbers = TRUE;
13772 #ifdef EMIT_DWARF_INFO
13773 if ((!acfg->aot_opts.nodebug || acfg->aot_opts.dwarf_debug) && acfg->has_jitted_code) {
13774 if (acfg->aot_opts.dwarf_debug && !mono_debug_enabled ()) {
13775 aot_printerrf (acfg, "The dwarf AOT option requires the --debug option.\n");
13776 return 1;
13778 acfg->dwarf = mono_dwarf_writer_create (acfg->w, NULL, 0, !acfg->gas_line_numbers);
13780 #endif /* EMIT_DWARF_INFO */
13782 if (acfg->w)
13783 mono_img_writer_emit_start (acfg->w);
13785 if (acfg->dwarf)
13786 mono_dwarf_writer_emit_base_info (acfg->dwarf, g_path_get_basename (acfg->image->name), mono_unwind_get_cie_program ());
13788 if (acfg->aot_opts.dedup)
13789 mono_flush_method_cache (acfg);
13791 emit_code (acfg);
13793 emit_info (acfg);
13795 emit_extra_methods (acfg);
13797 emit_trampolines (acfg);
13799 emit_class_name_table (acfg);
13801 emit_got_info (acfg, FALSE);
13802 if (acfg->llvm)
13803 emit_got_info (acfg, TRUE);
13805 emit_exception_info (acfg);
13807 emit_unwind_info (acfg);
13809 emit_class_info (acfg);
13811 emit_plt (acfg);
13813 emit_image_table (acfg);
13815 emit_weak_field_indexes (acfg);
13817 emit_got (acfg);
13821 * The managed allocators are GC specific, so can't use an AOT image created by one GC
13822 * in another.
13824 const char *gc_name = mono_gc_get_gc_name ();
13825 acfg->gc_name_offset = add_to_blob (acfg, (guint8*)gc_name, strlen (gc_name) + 1);
13828 emit_blob (acfg);
13830 emit_objc_selectors (acfg);
13832 emit_globals (acfg);
13834 emit_file_info (acfg);
13836 if (acfg->dwarf) {
13837 emit_dwarf_info (acfg);
13838 mono_dwarf_writer_close (acfg->dwarf);
13839 } else {
13840 if (!acfg->aot_opts.nodebug)
13841 emit_codeview_info (acfg);
13844 emit_mem_end (acfg);
13846 if (acfg->need_pt_gnu_stack) {
13847 /* This is required so the .so doesn't have an executable stack */
13848 /* The bin writer already emits this */
13849 fprintf (acfg->fp, "\n.section .note.GNU-stack,\"\",@progbits\n");
13852 if (acfg->aot_opts.data_outfile)
13853 fclose (acfg->data_outfile);
13855 #ifdef ENABLE_LLVM
13856 if (acfg->llvm) {
13857 gboolean res;
13859 res = emit_llvm_file (acfg);
13860 if (!res)
13861 return 1;
13863 #endif
13865 emit_library_info (acfg);
13867 TV_GETTIME (btv);
13869 acfg->stats.gen_time = TV_ELAPSED (atv, btv);
13871 if (!acfg->aot_opts.stats)
13872 aot_printf (acfg, "Compiled: %d/%d\n", acfg->stats.ccount, acfg->stats.mcount);
13874 TV_GETTIME (atv);
13875 if (acfg->w) {
13876 res = mono_img_writer_emit_writeout (acfg->w);
13877 if (res != 0) {
13878 acfg_free (acfg);
13879 return res;
13881 res = compile_asm (acfg);
13882 if (res != 0) {
13883 acfg_free (acfg);
13884 return res;
13887 TV_GETTIME (btv);
13888 acfg->stats.link_time = TV_ELAPSED (atv, btv);
13890 if (acfg->aot_opts.stats)
13891 print_stats (acfg);
13893 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);
13895 if (acfg->aot_opts.depfile)
13896 create_depfile (acfg);
13898 if (acfg->aot_opts.dump_json)
13899 aot_dump (acfg);
13901 if (!acfg->aot_opts.save_temps && acfg->temp_dir_to_delete) {
13902 char *command = g_strdup_printf ("rm -r %s", acfg->temp_dir_to_delete);
13903 execute_system (command);
13904 g_free (command);
13907 acfg_free (acfg);
13909 return 0;
13912 #else
13914 /* AOT disabled */
13916 void*
13917 mono_aot_readonly_field_override (MonoClassField *field)
13919 return NULL;
13923 mono_compile_assembly (MonoAssembly *ass, guint32 opts, const char *aot_options, gpointer **aot_state)
13925 return 0;
13928 gboolean
13929 mono_aot_is_shared_got_offset (int offset)
13931 return FALSE;
13935 mono_compile_deferred_assemblies (guint32 opts, const char *aot_options, gpointer **aot_state)
13937 g_assert_not_reached ();
13938 return 0;
13941 gboolean
13942 mono_aot_direct_icalls_enabled_for_method (MonoCompile *cfg, MonoMethod *method)
13944 g_assert_not_reached ();
13945 return 0;
13948 #endif