Fix a few cppcheck errors (#4281)
[mono-project.git] / mono / mini / aot-compiler.c
blob701364be006eb4776bc2a7e94ba4ad1ebf8e7077
1 /*
2 * aot-compiler.c: mono Ahead of Time compiler
4 * Author:
5 * Dietmar Maurer (dietmar@ximian.com)
6 * Zoltan Varga (vargaz@gmail.com)
7 * Johan Lorensson (lateralusx.github@gmail.com)
9 * (C) 2002 Ximian, Inc.
10 * Copyright 2003-2011 Novell, Inc
11 * Copyright 2011 Xamarin Inc (http://www.xamarin.com)
12 * Licensed under the MIT license. See LICENSE file in the project root for full license information.
15 #include "config.h"
16 #include <sys/types.h>
17 #ifdef HAVE_UNISTD_H
18 #include <unistd.h>
19 #endif
20 #ifdef HAVE_STDINT_H
21 #include <stdint.h>
22 #endif
23 #include <fcntl.h>
24 #include <ctype.h>
25 #include <string.h>
26 #ifndef HOST_WIN32
27 #include <sys/time.h>
28 #else
29 #include <winsock2.h>
30 #include <windows.h>
31 #endif
33 #include <errno.h>
34 #include <sys/stat.h>
36 #include <mono/metadata/abi-details.h>
37 #include <mono/metadata/tabledefs.h>
38 #include <mono/metadata/class.h>
39 #include <mono/metadata/object.h>
40 #include <mono/metadata/tokentype.h>
41 #include <mono/metadata/appdomain.h>
42 #include <mono/metadata/debug-helpers.h>
43 #include <mono/metadata/assembly.h>
44 #include <mono/metadata/metadata-internals.h>
45 #include <mono/metadata/reflection-internals.h>
46 #include <mono/metadata/marshal.h>
47 #include <mono/metadata/gc-internals.h>
48 #include <mono/metadata/mempool-internals.h>
49 #include <mono/metadata/mono-endian.h>
50 #include <mono/metadata/threads-types.h>
51 #include <mono/utils/mono-logger-internals.h>
52 #include <mono/utils/mono-compiler.h>
53 #include <mono/utils/mono-time.h>
54 #include <mono/utils/mono-mmap.h>
55 #include <mono/utils/mono-rand.h>
56 #include <mono/utils/json.h>
57 #include <mono/utils/mono-threads-coop.h>
58 #include <mono/profiler/mono-profiler-aot.h>
59 #include <mono/utils/w32api.h>
61 #include "aot-compiler.h"
62 #include "seq-points.h"
63 #include "image-writer.h"
64 #include "dwarfwriter.h"
65 #include "mini-gc.h"
66 #include "mini-llvm.h"
68 #if !defined(DISABLE_AOT) && !defined(DISABLE_JIT)
70 // Use MSVC toolchain, Clang for MSVC using MSVC codegen and linker, when compiling for AMD64
71 // targeting WIN32 platforms running AOT compiler on WIN32 platform with VS installation.
72 #if defined(TARGET_AMD64) && defined(TARGET_WIN32) && defined(HOST_WIN32) && defined(_MSC_VER)
73 #define TARGET_X86_64_WIN32_MSVC
74 #endif
76 #if defined(TARGET_X86_64_WIN32_MSVC)
77 #define TARGET_WIN32_MSVC
78 #endif
80 #if defined(__linux__) || defined(__native_client_codegen__)
81 #define RODATA_SECT ".rodata"
82 #elif defined(TARGET_MACH)
83 #define RODATA_SECT ".section __TEXT, __const"
84 #elif defined(TARGET_WIN32_MSVC)
85 #define RODATA_SECT ".rdata"
86 #else
87 #define RODATA_SECT ".text"
88 #endif
90 #define TV_DECLARE(name) gint64 name
91 #define TV_GETTIME(tv) tv = mono_100ns_ticks ()
92 #define TV_ELAPSED(start,end) (((end) - (start)) / 10)
94 #define ALIGN_TO(val,align) ((((guint64)val) + ((align) - 1)) & ~((align) - 1))
95 #define ALIGN_PTR_TO(ptr,align) (gpointer)((((gssize)(ptr)) + (align - 1)) & (~(align - 1)))
96 #define ROUND_DOWN(VALUE,SIZE) ((VALUE) & ~((SIZE) - 1))
98 typedef struct {
99 char *name;
100 MonoImage *image;
101 } ImageProfileData;
103 typedef struct ClassProfileData ClassProfileData;
105 typedef struct {
106 int argc;
107 ClassProfileData **argv;
108 MonoGenericInst *inst;
109 } GInstProfileData;
111 struct ClassProfileData {
112 ImageProfileData *image;
113 char *ns, *name;
114 GInstProfileData *inst;
115 MonoClass *klass;
118 typedef struct {
119 ClassProfileData *klass;
120 int id;
121 char *name;
122 int param_count;
123 char *signature;
124 GInstProfileData *inst;
125 MonoMethod *method;
126 } MethodProfileData;
128 typedef struct {
129 GHashTable *images, *classes, *ginsts, *methods;
130 } ProfileData;
132 /* predefined values for static readonly fields without needed to run the .cctor */
133 typedef struct _ReadOnlyValue ReadOnlyValue;
134 struct _ReadOnlyValue {
135 ReadOnlyValue *next;
136 char *name;
137 int type; /* to be used later for typechecking to prevent user errors */
138 union {
139 guint8 i1;
140 guint16 i2;
141 guint32 i4;
142 guint64 i8;
143 gpointer ptr;
144 } value;
146 static ReadOnlyValue *readonly_values;
148 typedef struct MonoAotOptions {
149 char *outfile;
150 char *llvm_outfile;
151 char *data_outfile;
152 GList *profile_files;
153 gboolean save_temps;
154 gboolean write_symbols;
155 gboolean metadata_only;
156 gboolean bind_to_runtime_version;
157 MonoAotMode mode;
158 gboolean no_dlsym;
159 gboolean static_link;
160 gboolean asm_only;
161 gboolean asm_writer;
162 gboolean nodebug;
163 gboolean dwarf_debug;
164 gboolean soft_debug;
165 gboolean log_generics;
166 gboolean log_instances;
167 gboolean gen_msym_dir;
168 char *gen_msym_dir_path;
169 gboolean direct_pinvoke;
170 gboolean direct_icalls;
171 gboolean no_direct_calls;
172 gboolean use_trampolines_page;
173 gboolean no_instances;
174 gboolean gnu_asm;
175 gboolean llvm;
176 gboolean llvm_only;
177 int nthreads;
178 int ntrampolines;
179 int nrgctx_trampolines;
180 int nimt_trampolines;
181 int ngsharedvt_arg_trampolines;
182 int nrgctx_fetch_trampolines;
183 gboolean print_skipped_methods;
184 gboolean stats;
185 gboolean verbose;
186 char *tool_prefix;
187 char *ld_flags;
188 char *mtriple;
189 char *llvm_path;
190 char *temp_path;
191 char *instances_logfile_path;
192 char *logfile;
193 gboolean dump_json;
194 gboolean profile_only;
195 } MonoAotOptions;
197 typedef enum {
198 METHOD_CAT_NORMAL,
199 METHOD_CAT_GSHAREDVT,
200 METHOD_CAT_INST,
201 METHOD_CAT_WRAPPER,
202 METHOD_CAT_NUM
203 } MethodCategory;
205 typedef struct MonoAotStats {
206 int ccount, mcount, lmfcount, abscount, gcount, ocount, genericcount;
207 gint64 code_size, info_size, ex_info_size, unwind_info_size, got_size, class_info_size, got_info_size, plt_size;
208 int methods_without_got_slots, direct_calls, all_calls, llvm_count;
209 int got_slots, offsets_size;
210 int method_categories [METHOD_CAT_NUM];
211 int got_slot_types [MONO_PATCH_INFO_NUM];
212 int got_slot_info_sizes [MONO_PATCH_INFO_NUM];
213 int jit_time, gen_time, link_time;
214 } MonoAotStats;
216 typedef struct GotInfo {
217 GHashTable *patch_to_got_offset;
218 GHashTable **patch_to_got_offset_by_type;
219 GPtrArray *got_patches;
220 } GotInfo;
222 typedef struct MonoAotCompile {
223 MonoImage *image;
224 GPtrArray *methods;
225 GHashTable *method_indexes;
226 GHashTable *method_depth;
227 MonoCompile **cfgs;
228 int cfgs_size;
229 GHashTable **patch_to_plt_entry;
230 GHashTable *plt_offset_to_entry;
231 //GHashTable *patch_to_got_offset;
232 //GHashTable **patch_to_got_offset_by_type;
233 //GPtrArray *got_patches;
234 GotInfo got_info, llvm_got_info;
235 GHashTable *image_hash;
236 GHashTable *method_to_cfg;
237 GHashTable *token_info_hash;
238 GHashTable *method_to_pinvoke_import;
239 GPtrArray *extra_methods;
240 GPtrArray *image_table;
241 GPtrArray *globals;
242 GPtrArray *method_order;
243 GHashTable *export_names;
244 /* Maps MonoClass* -> blob offset */
245 GHashTable *klass_blob_hash;
246 /* Maps MonoMethod* -> blob offset */
247 GHashTable *method_blob_hash;
248 GHashTable *gsharedvt_in_signatures;
249 GHashTable *gsharedvt_out_signatures;
250 guint32 *plt_got_info_offsets;
251 guint32 got_offset, llvm_got_offset, plt_offset, plt_got_offset_base, nshared_got_entries;
252 /* Number of GOT entries reserved for trampolines */
253 guint32 num_trampoline_got_entries;
254 guint32 tramp_page_size;
256 guint32 table_offsets [MONO_AOT_TABLE_NUM];
257 guint32 num_trampolines [MONO_AOT_TRAMP_NUM];
258 guint32 trampoline_got_offset_base [MONO_AOT_TRAMP_NUM];
259 guint32 trampoline_size [MONO_AOT_TRAMP_NUM];
260 guint32 tramp_page_code_offsets [MONO_AOT_TRAMP_NUM];
262 MonoAotOptions aot_opts;
263 guint32 nmethods;
264 guint32 opts;
265 guint32 simd_opts;
266 MonoMemPool *mempool;
267 MonoAotStats stats;
268 int method_index;
269 char *static_linking_symbol;
270 mono_mutex_t mutex;
271 gboolean gas_line_numbers;
272 /* Whenever to emit an object file directly from llc */
273 gboolean llvm_owriter;
274 gboolean llvm_owriter_supported;
275 MonoImageWriter *w;
276 MonoDwarfWriter *dwarf;
277 FILE *fp;
278 char *tmpbasename;
279 char *tmpfname;
280 char *llvm_sfile;
281 char *llvm_ofile;
282 GSList *cie_program;
283 GHashTable *unwind_info_offsets;
284 GPtrArray *unwind_ops;
285 guint32 unwind_info_offset;
286 char *global_prefix;
287 char *got_symbol;
288 char *llvm_got_symbol;
289 char *plt_symbol;
290 char *llvm_eh_frame_symbol;
291 GHashTable *method_label_hash;
292 const char *temp_prefix;
293 const char *user_symbol_prefix;
294 const char *llvm_label_prefix;
295 const char *inst_directive;
296 int align_pad_value;
297 guint32 label_generator;
298 gboolean llvm;
299 gboolean has_jitted_code;
300 MonoAotFileFlags flags;
301 MonoDynamicStream blob;
302 gboolean blob_closed;
303 GHashTable *typespec_classes;
304 GString *llc_args;
305 GString *as_args;
306 char *assembly_name_sym;
307 GHashTable *plt_entry_debug_sym_cache;
308 gboolean thumb_mixed, need_no_dead_strip, need_pt_gnu_stack;
309 GHashTable *ginst_hash;
310 GHashTable *dwarf_ln_filenames;
311 gboolean global_symbols;
312 int objc_selector_index, objc_selector_index_2;
313 GPtrArray *objc_selectors;
314 GHashTable *objc_selector_to_index;
315 GList *profile_data;
316 GHashTable *profile_methods;
317 FILE *logfile;
318 FILE *instances_logfile;
319 FILE *data_outfile;
320 int datafile_offset;
321 int gc_name_offset;
322 } MonoAotCompile;
324 typedef struct {
325 int plt_offset;
326 char *symbol, *llvm_symbol, *debug_sym;
327 MonoJumpInfo *ji;
328 gboolean jit_used, llvm_used;
329 } MonoPltEntry;
331 #define mono_acfg_lock(acfg) mono_os_mutex_lock (&((acfg)->mutex))
332 #define mono_acfg_unlock(acfg) mono_os_mutex_unlock (&((acfg)->mutex))
334 /* This points to the current acfg in LLVM mode */
335 static MonoAotCompile *llvm_acfg;
337 #ifdef HAVE_ARRAY_ELEM_INIT
338 #define MSGSTRFIELD(line) MSGSTRFIELD1(line)
339 #define MSGSTRFIELD1(line) str##line
340 static const struct msgstr_t {
341 #define PATCH_INFO(a,b) char MSGSTRFIELD(__LINE__) [sizeof (b)];
342 #include "patch-info.h"
343 #undef PATCH_INFO
344 } opstr = {
345 #define PATCH_INFO(a,b) b,
346 #include "patch-info.h"
347 #undef PATCH_INFO
349 static const gint16 opidx [] = {
350 #define PATCH_INFO(a,b) [MONO_PATCH_INFO_ ## a] = offsetof (struct msgstr_t, MSGSTRFIELD(__LINE__)),
351 #include "patch-info.h"
352 #undef PATCH_INFO
355 static G_GNUC_UNUSED const char*
356 get_patch_name (int info)
358 return (const char*)&opstr + opidx [info];
361 #else
362 #define PATCH_INFO(a,b) b,
363 static const char* const
364 patch_types [MONO_PATCH_INFO_NUM + 1] = {
365 #include "patch-info.h"
366 NULL
369 static G_GNUC_UNUSED const char*
370 get_patch_name (int info)
372 return patch_types [info];
375 #endif
377 static guint32
378 get_unwind_info_offset (MonoAotCompile *acfg, guint8 *encoded, guint32 encoded_len);
380 static char*
381 get_plt_entry_debug_sym (MonoAotCompile *acfg, MonoJumpInfo *ji, GHashTable *cache);
383 static void
384 add_gsharedvt_wrappers (MonoAotCompile *acfg, MonoMethodSignature *sig, gboolean gsharedvt_in, gboolean gsharedvt_out);
386 static void
387 add_profile_instances (MonoAotCompile *acfg, ProfileData *data);
389 static void
390 aot_printf (MonoAotCompile *acfg, const gchar *format, ...)
392 FILE *output;
393 va_list args;
395 if (acfg->logfile)
396 output = acfg->logfile;
397 else
398 output = stdout;
400 va_start (args, format);
401 vfprintf (output, format, args);
402 va_end (args);
405 static void
406 aot_printerrf (MonoAotCompile *acfg, const gchar *format, ...)
408 FILE *output;
409 va_list args;
411 if (acfg->logfile)
412 output = acfg->logfile;
413 else
414 output = stderr;
416 va_start (args, format);
417 vfprintf (output, format, args);
418 va_end (args);
421 static void
422 report_loader_error (MonoAotCompile *acfg, MonoError *error, const char *format, ...)
424 FILE *output;
425 va_list args;
427 if (mono_error_ok (error))
428 return;
430 if (acfg->logfile)
431 output = acfg->logfile;
432 else
433 output = stderr;
435 va_start (args, format);
436 vfprintf (output, format, args);
437 va_end (args);
438 mono_error_cleanup (error);
440 g_error ("FullAOT cannot continue if there are loader errors");
443 /* Wrappers around the image writer functions */
445 #define MAX_SYMBOL_SIZE 256
447 static inline const char *
448 mangle_symbol (const char * symbol, char * mangled_symbol, gsize length)
450 gsize needed_size = length;
452 g_assert (NULL != symbol);
453 g_assert (NULL != mangled_symbol);
454 g_assert (0 != length);
456 #if defined(TARGET_WIN32) && defined(TARGET_X86)
457 if (symbol && '_' != symbol [0]) {
458 needed_size = g_snprintf (mangled_symbol, length, "_%s", symbol);
459 } else {
460 needed_size = g_snprintf (mangled_symbol, length, "%s", symbol);
462 #else
463 needed_size = g_snprintf (mangled_symbol, length, "%s", symbol);
464 #endif
466 g_assert (0 <= needed_size && needed_size < length);
467 return mangled_symbol;
470 static inline char *
471 mangle_symbol_alloc (const char * symbol)
473 g_assert (NULL != symbol);
475 #if defined(TARGET_WIN32) && defined(TARGET_X86)
476 if (symbol && '_' != symbol [0]) {
477 return g_strdup_printf ("_%s", symbol);
479 else {
480 return g_strdup_printf ("%s", symbol);
482 #else
483 return g_strdup_printf ("%s", symbol);
484 #endif
487 static inline void
488 emit_section_change (MonoAotCompile *acfg, const char *section_name, int subsection_index)
490 mono_img_writer_emit_section_change (acfg->w, section_name, subsection_index);
493 #if defined(TARGET_WIN32) && defined(TARGET_X86)
495 static inline void
496 emit_local_symbol (MonoAotCompile *acfg, const char *name, const char *end_label, gboolean func)
498 const char * mangled_symbol_name = name;
499 char * mangled_symbol_name_alloc = NULL;
501 if (TRUE == func) {
502 mangled_symbol_name_alloc = mangle_symbol_alloc (name);
503 mangled_symbol_name = mangled_symbol_name_alloc;
506 if (name != mangled_symbol_name && 0 != g_strcasecmp (name, mangled_symbol_name)) {
507 mono_img_writer_emit_label (acfg->w, mangled_symbol_name);
509 mono_img_writer_emit_local_symbol (acfg->w, mangled_symbol_name, end_label, func);
511 if (NULL != mangled_symbol_name_alloc) {
512 g_free (mangled_symbol_name_alloc);
516 #else
518 static inline void
519 emit_local_symbol (MonoAotCompile *acfg, const char *name, const char *end_label, gboolean func)
521 mono_img_writer_emit_local_symbol (acfg->w, name, end_label, func);
524 #endif
526 static inline void
527 emit_label (MonoAotCompile *acfg, const char *name)
529 mono_img_writer_emit_label (acfg->w, name);
532 static inline void
533 emit_bytes (MonoAotCompile *acfg, const guint8* buf, int size)
535 mono_img_writer_emit_bytes (acfg->w, buf, size);
538 static inline void
539 emit_string (MonoAotCompile *acfg, const char *value)
541 mono_img_writer_emit_string (acfg->w, value);
544 static inline void
545 emit_line (MonoAotCompile *acfg)
547 mono_img_writer_emit_line (acfg->w);
550 static inline void
551 emit_alignment (MonoAotCompile *acfg, int size)
553 mono_img_writer_emit_alignment (acfg->w, size);
556 static inline void
557 emit_alignment_code (MonoAotCompile *acfg, int size)
559 if (acfg->align_pad_value)
560 mono_img_writer_emit_alignment_fill (acfg->w, size, acfg->align_pad_value);
561 else
562 mono_img_writer_emit_alignment (acfg->w, size);
565 static inline void
566 emit_padding (MonoAotCompile *acfg, int size)
568 int i;
569 guint8 buf [16];
571 if (acfg->align_pad_value) {
572 for (i = 0; i < 16; ++i)
573 buf [i] = acfg->align_pad_value;
574 } else {
575 memset (buf, 0, sizeof (buf));
578 for (i = 0; i < size; i += 16) {
579 if (size - i < 16)
580 emit_bytes (acfg, buf, size - i);
581 else
582 emit_bytes (acfg, buf, 16);
586 static inline void
587 emit_pointer (MonoAotCompile *acfg, const char *target)
589 mono_img_writer_emit_pointer (acfg->w, target);
592 static inline void
593 emit_pointer_2 (MonoAotCompile *acfg, const char *prefix, const char *target)
595 if (prefix [0] != '\0') {
596 char *s = g_strdup_printf ("%s%s", prefix, target);
597 mono_img_writer_emit_pointer (acfg->w, s);
598 g_free (s);
599 } else {
600 mono_img_writer_emit_pointer (acfg->w, target);
604 static inline void
605 emit_int16 (MonoAotCompile *acfg, int value)
607 mono_img_writer_emit_int16 (acfg->w, value);
610 static inline void
611 emit_int32 (MonoAotCompile *acfg, int value)
613 mono_img_writer_emit_int32 (acfg->w, value);
616 static inline void
617 emit_symbol_diff (MonoAotCompile *acfg, const char *end, const char* start, int offset)
619 mono_img_writer_emit_symbol_diff (acfg->w, end, start, offset);
622 static inline void
623 emit_zero_bytes (MonoAotCompile *acfg, int num)
625 mono_img_writer_emit_zero_bytes (acfg->w, num);
628 static inline void
629 emit_byte (MonoAotCompile *acfg, guint8 val)
631 mono_img_writer_emit_byte (acfg->w, val);
634 #if defined(TARGET_WIN32) && defined(TARGET_X86)
636 static G_GNUC_UNUSED void
637 emit_global_inner (MonoAotCompile *acfg, const char *name, gboolean func)
639 const char * mangled_symbol_name = name;
640 char * mangled_symbol_name_alloc = NULL;
642 mangled_symbol_name_alloc = mangle_symbol_alloc (name);
643 mangled_symbol_name = mangled_symbol_name_alloc;
645 if (0 != g_strcasecmp (name, mangled_symbol_name)) {
646 mono_img_writer_emit_label (acfg->w, mangled_symbol_name);
648 mono_img_writer_emit_global (acfg->w, mangled_symbol_name, func);
650 if (NULL != mangled_symbol_name_alloc) {
651 g_free (mangled_symbol_name_alloc);
655 #else
657 static G_GNUC_UNUSED void
658 emit_global_inner (MonoAotCompile *acfg, const char *name, gboolean func)
660 mono_img_writer_emit_global (acfg->w, name, func);
663 #endif
665 static inline gboolean
666 link_shared_library (MonoAotCompile *acfg)
668 return !acfg->aot_opts.static_link && !acfg->aot_opts.asm_only;
671 static inline gboolean
672 add_to_global_symbol_table (MonoAotCompile *acfg)
674 #ifdef TARGET_WIN32_MSVC
675 return acfg->aot_opts.no_dlsym || link_shared_library (acfg);
676 #else
677 return acfg->aot_opts.no_dlsym;
678 #endif
681 static void
682 emit_global (MonoAotCompile *acfg, const char *name, gboolean func)
684 if (add_to_global_symbol_table (acfg))
685 g_ptr_array_add (acfg->globals, g_strdup (name));
687 if (acfg->aot_opts.no_dlsym) {
688 mono_img_writer_emit_local_symbol (acfg->w, name, NULL, func);
689 } else {
690 emit_global_inner (acfg, name, func);
694 static void
695 emit_symbol_size (MonoAotCompile *acfg, const char *name, const char *end_label)
697 mono_img_writer_emit_symbol_size (acfg->w, name, end_label);
700 /* Emit a symbol which is referenced by the MonoAotFileInfo structure */
701 static void
702 emit_info_symbol (MonoAotCompile *acfg, const char *name)
704 char symbol [MAX_SYMBOL_SIZE];
706 if (acfg->llvm) {
707 emit_label (acfg, name);
708 /* LLVM generated code references this */
709 sprintf (symbol, "%s%s%s", acfg->user_symbol_prefix, acfg->global_prefix, name);
710 emit_label (acfg, symbol);
711 emit_global_inner (acfg, symbol, FALSE);
712 } else {
713 emit_label (acfg, name);
717 static void
718 emit_string_symbol (MonoAotCompile *acfg, const char *name, const char *value)
720 if (acfg->llvm) {
721 mono_llvm_emit_aot_data (name, (guint8*)value, strlen (value) + 1);
722 return;
725 mono_img_writer_emit_section_change (acfg->w, RODATA_SECT, 1);
726 #ifdef TARGET_MACH
727 /* On apple, all symbols need to be aligned to avoid warnings from ld */
728 emit_alignment (acfg, 4);
729 #endif
730 mono_img_writer_emit_label (acfg->w, name);
731 mono_img_writer_emit_string (acfg->w, value);
734 static G_GNUC_UNUSED void
735 emit_uleb128 (MonoAotCompile *acfg, guint32 value)
737 do {
738 guint8 b = value & 0x7f;
739 value >>= 7;
740 if (value != 0) /* more bytes to come */
741 b |= 0x80;
742 emit_byte (acfg, b);
743 } while (value);
746 static G_GNUC_UNUSED void
747 emit_sleb128 (MonoAotCompile *acfg, gint64 value)
749 gboolean more = 1;
750 gboolean negative = (value < 0);
751 guint32 size = 64;
752 guint8 byte;
754 while (more) {
755 byte = value & 0x7f;
756 value >>= 7;
757 /* the following is unnecessary if the
758 * implementation of >>= uses an arithmetic rather
759 * than logical shift for a signed left operand
761 if (negative)
762 /* sign extend */
763 value |= - ((gint64)1 <<(size - 7));
764 /* sign bit of byte is second high order bit (0x40) */
765 if ((value == 0 && !(byte & 0x40)) ||
766 (value == -1 && (byte & 0x40)))
767 more = 0;
768 else
769 byte |= 0x80;
770 emit_byte (acfg, byte);
774 static G_GNUC_UNUSED void
775 encode_uleb128 (guint32 value, guint8 *buf, guint8 **endbuf)
777 guint8 *p = buf;
779 do {
780 guint8 b = value & 0x7f;
781 value >>= 7;
782 if (value != 0) /* more bytes to come */
783 b |= 0x80;
784 *p ++ = b;
785 } while (value);
787 *endbuf = p;
790 static G_GNUC_UNUSED void
791 encode_sleb128 (gint32 value, guint8 *buf, guint8 **endbuf)
793 gboolean more = 1;
794 gboolean negative = (value < 0);
795 guint32 size = 32;
796 guint8 byte;
797 guint8 *p = buf;
799 while (more) {
800 byte = value & 0x7f;
801 value >>= 7;
802 /* the following is unnecessary if the
803 * implementation of >>= uses an arithmetic rather
804 * than logical shift for a signed left operand
806 if (negative)
807 /* sign extend */
808 value |= - (1 <<(size - 7));
809 /* sign bit of byte is second high order bit (0x40) */
810 if ((value == 0 && !(byte & 0x40)) ||
811 (value == -1 && (byte & 0x40)))
812 more = 0;
813 else
814 byte |= 0x80;
815 *p ++= byte;
818 *endbuf = p;
821 static void
822 encode_int (gint32 val, guint8 *buf, guint8 **endbuf)
824 // FIXME: Big-endian
825 buf [0] = (val >> 0) & 0xff;
826 buf [1] = (val >> 8) & 0xff;
827 buf [2] = (val >> 16) & 0xff;
828 buf [3] = (val >> 24) & 0xff;
830 *endbuf = buf + 4;
833 static void
834 encode_int16 (guint16 val, guint8 *buf, guint8 **endbuf)
836 buf [0] = (val >> 0) & 0xff;
837 buf [1] = (val >> 8) & 0xff;
839 *endbuf = buf + 2;
842 static void
843 encode_string (const char *s, guint8 *buf, guint8 **endbuf)
845 int len = strlen (s);
847 memcpy (buf, s, len + 1);
848 *endbuf = buf + len + 1;
851 static void
852 emit_unset_mode (MonoAotCompile *acfg)
854 mono_img_writer_emit_unset_mode (acfg->w);
857 static G_GNUC_UNUSED void
858 emit_set_thumb_mode (MonoAotCompile *acfg)
860 emit_unset_mode (acfg);
861 fprintf (acfg->fp, ".code 16\n");
864 static G_GNUC_UNUSED void
865 emit_set_arm_mode (MonoAotCompile *acfg)
867 emit_unset_mode (acfg);
868 fprintf (acfg->fp, ".code 32\n");
871 static inline void
872 emit_code_bytes (MonoAotCompile *acfg, const guint8* buf, int size)
874 #ifdef TARGET_ARM64
875 int i;
877 g_assert (size % 4 == 0);
878 emit_unset_mode (acfg);
879 for (i = 0; i < size; i += 4)
880 fprintf (acfg->fp, "%s 0x%x\n", acfg->inst_directive, *(guint32*)(buf + i));
881 #else
882 emit_bytes (acfg, buf, size);
883 #endif
886 /* ARCHITECTURE SPECIFIC CODE */
888 #if defined(TARGET_X86) || defined(TARGET_AMD64) || defined(TARGET_ARM) || defined(TARGET_POWERPC) || defined(TARGET_ARM64)
889 #define EMIT_DWARF_INFO 1
890 #endif
892 #ifdef TARGET_WIN32_MSVC
893 #undef EMIT_DWARF_INFO
894 #endif
896 #if defined(TARGET_ARM)
897 #define AOT_FUNC_ALIGNMENT 4
898 #else
899 #define AOT_FUNC_ALIGNMENT 16
900 #endif
902 #if defined(TARGET_POWERPC64) && !defined(__mono_ilp32__)
903 #define PPC_LD_OP "ld"
904 #define PPC_LDX_OP "ldx"
905 #else
906 #define PPC_LD_OP "lwz"
907 #define PPC_LDX_OP "lwzx"
908 #endif
910 #ifdef TARGET_X86_64_WIN32_MSVC
911 #define AOT_TARGET_STR "AMD64 (WIN32) (MSVC codegen)"
912 #elif TARGET_AMD64
913 #define AOT_TARGET_STR "AMD64"
914 #endif
916 #ifdef TARGET_ARM
917 #ifdef TARGET_MACH
918 #define AOT_TARGET_STR "ARM (MACH)"
919 #else
920 #define AOT_TARGET_STR "ARM (!MACH)"
921 #endif
922 #endif
924 #ifdef TARGET_ARM64
925 #ifdef TARGET_MACH
926 #define AOT_TARGET_STR "ARM64 (MACH)"
927 #else
928 #define AOT_TARGET_STR "ARM64 (!MACH)"
929 #endif
930 #endif
932 #ifdef TARGET_POWERPC64
933 #ifdef __mono_ilp32__
934 #define AOT_TARGET_STR "POWERPC64 (mono ilp32)"
935 #else
936 #define AOT_TARGET_STR "POWERPC64 (!mono ilp32)"
937 #endif
938 #else
939 #ifdef TARGET_POWERPC
940 #ifdef __mono_ilp32__
941 #define AOT_TARGET_STR "POWERPC (mono ilp32)"
942 #else
943 #define AOT_TARGET_STR "POWERPC (!mono ilp32)"
944 #endif
945 #endif
946 #endif
948 #ifdef TARGET_X86
949 #ifdef TARGET_WIN32
950 #define AOT_TARGET_STR "X86 (WIN32)"
951 #elif defined(__native_client_codegen__)
952 #define AOT_TARGET_STR "X86 (native client codegen)"
953 #else
954 #define AOT_TARGET_STR "X86 (!native client codegen)"
955 #endif
956 #endif
958 #ifndef AOT_TARGET_STR
959 #define AOT_TARGET_STR ""
960 #endif
962 static void
963 arch_init (MonoAotCompile *acfg)
965 acfg->llc_args = g_string_new ("");
966 acfg->as_args = g_string_new ("");
967 acfg->llvm_owriter_supported = TRUE;
970 * The prefix LLVM likes to put in front of symbol names on darwin.
971 * The mach-os specs require this for globals, but LLVM puts them in front of all
972 * symbols. We need to handle this, since we need to refer to LLVM generated
973 * symbols.
975 acfg->llvm_label_prefix = "";
976 acfg->user_symbol_prefix = "";
978 #if defined(TARGET_X86)
979 g_string_append (acfg->llc_args, " -march=x86 -mattr=sse4.1");
980 #endif
982 #if defined(TARGET_AMD64)
983 g_string_append (acfg->llc_args, " -march=x86-64 -mattr=sse4.1");
984 /* NOP */
985 acfg->align_pad_value = 0x90;
986 #endif
988 #ifdef TARGET_ARM
989 if (acfg->aot_opts.mtriple && strstr (acfg->aot_opts.mtriple, "darwin")) {
990 g_string_append (acfg->llc_args, "-mattr=+v6");
991 } else {
992 #if defined(ARM_FPU_VFP_HARD)
993 g_string_append (acfg->llc_args, " -mattr=+vfp2,-neon,+d16 -float-abi=hard");
994 g_string_append (acfg->as_args, " -mfpu=vfp3");
995 #elif defined(ARM_FPU_VFP)
996 g_string_append (acfg->llc_args, " -mattr=+vfp2,-neon,+d16");
997 g_string_append (acfg->as_args, " -mfpu=vfp3");
998 #else
999 g_string_append (acfg->llc_args, " -soft-float");
1000 #endif
1002 if (acfg->aot_opts.mtriple && strstr (acfg->aot_opts.mtriple, "thumb"))
1003 acfg->thumb_mixed = TRUE;
1005 if (acfg->aot_opts.mtriple)
1006 mono_arch_set_target (acfg->aot_opts.mtriple);
1007 #endif
1009 #ifdef TARGET_ARM64
1010 acfg->inst_directive = ".inst";
1011 if (acfg->aot_opts.mtriple)
1012 mono_arch_set_target (acfg->aot_opts.mtriple);
1013 #endif
1015 #ifdef TARGET_MACH
1016 acfg->user_symbol_prefix = "_";
1017 acfg->llvm_label_prefix = "_";
1018 acfg->inst_directive = ".word";
1019 acfg->need_no_dead_strip = TRUE;
1020 acfg->aot_opts.gnu_asm = TRUE;
1021 #endif
1023 #if defined(__linux__) && !defined(TARGET_ARM)
1024 acfg->need_pt_gnu_stack = TRUE;
1025 #endif
1027 #ifdef MONOTOUCH
1028 acfg->global_symbols = TRUE;
1029 #endif
1031 #ifdef TARGET_ANDROID
1032 acfg->llvm_owriter_supported = FALSE;
1033 #endif
1036 #ifdef TARGET_ARM64
1039 /* Load the contents of GOT_SLOT into dreg, clobbering ip0 */
1040 static void
1041 arm64_emit_load_got_slot (MonoAotCompile *acfg, int dreg, int got_slot)
1043 int offset;
1045 g_assert (acfg->fp);
1046 emit_unset_mode (acfg);
1047 /* r16==ip0 */
1048 offset = (int)(got_slot * sizeof (gpointer));
1049 #ifdef TARGET_MACH
1050 /* clang's integrated assembler */
1051 fprintf (acfg->fp, "adrp x16, %s@PAGE+%d\n", acfg->got_symbol, offset & 0xfffff000);
1052 fprintf (acfg->fp, "add x16, x16, %s@PAGEOFF\n", acfg->got_symbol);
1053 fprintf (acfg->fp, "ldr x%d, [x16, #%d]\n", dreg, offset & 0xfff);
1054 #else
1055 /* Linux GAS */
1056 fprintf (acfg->fp, "adrp x16, %s+%d\n", acfg->got_symbol, offset & 0xfffff000);
1057 fprintf (acfg->fp, "add x16, x16, :lo12:%s\n", acfg->got_symbol);
1058 fprintf (acfg->fp, "ldr x%d, [x16, %d]\n", dreg, offset & 0xfff);
1059 #endif
1062 static void
1063 arm64_emit_objc_selector_ref (MonoAotCompile *acfg, guint8 *code, int index, int *code_size)
1065 int reg;
1067 g_assert (acfg->fp);
1068 emit_unset_mode (acfg);
1070 /* ldr rt, target */
1071 reg = arm_get_ldr_lit_reg (code);
1073 fprintf (acfg->fp, "adrp x%d, L_OBJC_SELECTOR_REFERENCES_%d@PAGE\n", reg, index);
1074 fprintf (acfg->fp, "add x%d, x%d, L_OBJC_SELECTOR_REFERENCES_%d@PAGEOFF\n", reg, reg, index);
1075 fprintf (acfg->fp, "ldr x%d, [x%d]\n", reg, reg);
1077 *code_size = 12;
1080 static void
1081 arm64_emit_direct_call (MonoAotCompile *acfg, const char *target, gboolean external, gboolean thumb, MonoJumpInfo *ji, int *call_size)
1083 g_assert (acfg->fp);
1084 emit_unset_mode (acfg);
1085 if (ji && ji->relocation == MONO_R_ARM64_B) {
1086 fprintf (acfg->fp, "b %s\n", target);
1087 } else {
1088 if (ji)
1089 g_assert (ji->relocation == MONO_R_ARM64_BL);
1090 fprintf (acfg->fp, "bl %s\n", target);
1092 *call_size = 4;
1095 static void
1096 arm64_emit_got_access (MonoAotCompile *acfg, guint8 *code, int got_slot, int *code_size)
1098 int reg;
1100 /* ldr rt, target */
1101 reg = arm_get_ldr_lit_reg (code);
1102 arm64_emit_load_got_slot (acfg, reg, got_slot);
1103 *code_size = 12;
1106 static void
1107 arm64_emit_plt_entry (MonoAotCompile *acfg, const char *got_symbol, int offset, int info_offset)
1109 arm64_emit_load_got_slot (acfg, ARMREG_R16, offset / sizeof (gpointer));
1110 fprintf (acfg->fp, "br x16\n");
1111 /* Used by mono_aot_get_plt_info_offset () */
1112 fprintf (acfg->fp, "%s %d\n", acfg->inst_directive, info_offset);
1115 static void
1116 arm64_emit_tramp_page_common_code (MonoAotCompile *acfg, int pagesize, int arg_reg, int *size)
1118 guint8 buf [256];
1119 guint8 *code;
1120 int imm;
1122 /* The common code */
1123 code = buf;
1124 imm = pagesize;
1125 /* The trampoline address is in IP0 */
1126 arm_movzx (code, ARMREG_IP1, imm & 0xffff, 0);
1127 arm_movkx (code, ARMREG_IP1, (imm >> 16) & 0xffff, 16);
1128 /* Compute the data slot address */
1129 arm_subx (code, ARMREG_IP0, ARMREG_IP0, ARMREG_IP1);
1130 /* Trampoline argument */
1131 arm_ldrx (code, arg_reg, ARMREG_IP0, 0);
1132 /* Address */
1133 arm_ldrx (code, ARMREG_IP0, ARMREG_IP0, 8);
1134 arm_brx (code, ARMREG_IP0);
1136 /* Emit it */
1137 emit_code_bytes (acfg, buf, code - buf);
1139 *size = code - buf;
1142 static void
1143 arm64_emit_tramp_page_specific_code (MonoAotCompile *acfg, int pagesize, int common_tramp_size, int specific_tramp_size)
1145 guint8 buf [256];
1146 guint8 *code;
1147 int i, count;
1149 count = (pagesize - common_tramp_size) / specific_tramp_size;
1150 for (i = 0; i < count; ++i) {
1151 code = buf;
1152 arm_adrx (code, ARMREG_IP0, code);
1153 /* Branch to the generic code */
1154 arm_b (code, code - 4 - (i * specific_tramp_size) - common_tramp_size);
1155 /* This has to be 2 pointers long */
1156 arm_nop (code);
1157 arm_nop (code);
1158 g_assert (code - buf == specific_tramp_size);
1159 emit_code_bytes (acfg, buf, code - buf);
1163 static void
1164 arm64_emit_specific_trampoline_pages (MonoAotCompile *acfg)
1166 guint8 buf [128];
1167 guint8 *code;
1168 guint8 *labels [16];
1169 int common_tramp_size;
1170 int specific_tramp_size = 2 * 8;
1171 int imm, pagesize;
1172 char symbol [128];
1174 if (!acfg->aot_opts.use_trampolines_page)
1175 return;
1177 #ifdef TARGET_MACH
1178 /* Have to match the target pagesize */
1179 pagesize = 16384;
1180 #else
1181 pagesize = mono_pagesize ();
1182 #endif
1183 acfg->tramp_page_size = pagesize;
1185 /* The specific trampolines */
1186 sprintf (symbol, "%sspecific_trampolines_page", acfg->user_symbol_prefix);
1187 emit_alignment (acfg, pagesize);
1188 emit_global (acfg, symbol, TRUE);
1189 emit_label (acfg, symbol);
1191 /* The common code */
1192 arm64_emit_tramp_page_common_code (acfg, pagesize, ARMREG_IP1, &common_tramp_size);
1193 acfg->tramp_page_code_offsets [MONO_AOT_TRAMP_SPECIFIC] = common_tramp_size;
1195 arm64_emit_tramp_page_specific_code (acfg, pagesize, common_tramp_size, specific_tramp_size);
1197 /* The rgctx trampolines */
1198 /* These are the same as the specific trampolines, but they load the argument into MONO_ARCH_RGCTX_REG */
1199 sprintf (symbol, "%srgctx_trampolines_page", acfg->user_symbol_prefix);
1200 emit_alignment (acfg, pagesize);
1201 emit_global (acfg, symbol, TRUE);
1202 emit_label (acfg, symbol);
1204 /* The common code */
1205 arm64_emit_tramp_page_common_code (acfg, pagesize, MONO_ARCH_RGCTX_REG, &common_tramp_size);
1206 acfg->tramp_page_code_offsets [MONO_AOT_TRAMP_STATIC_RGCTX] = common_tramp_size;
1208 arm64_emit_tramp_page_specific_code (acfg, pagesize, common_tramp_size, specific_tramp_size);
1210 /* The gsharedvt arg trampolines */
1211 /* These are the same as the specific trampolines */
1212 sprintf (symbol, "%sgsharedvt_arg_trampolines_page", acfg->user_symbol_prefix);
1213 emit_alignment (acfg, pagesize);
1214 emit_global (acfg, symbol, TRUE);
1215 emit_label (acfg, symbol);
1217 arm64_emit_tramp_page_common_code (acfg, pagesize, ARMREG_IP1, &common_tramp_size);
1218 acfg->tramp_page_code_offsets [MONO_AOT_TRAMP_GSHAREDVT_ARG] = common_tramp_size;
1220 arm64_emit_tramp_page_specific_code (acfg, pagesize, common_tramp_size, specific_tramp_size);
1222 /* The IMT trampolines */
1223 sprintf (symbol, "%simt_trampolines_page", acfg->user_symbol_prefix);
1224 emit_alignment (acfg, pagesize);
1225 emit_global (acfg, symbol, TRUE);
1226 emit_label (acfg, symbol);
1228 code = buf;
1229 imm = pagesize;
1230 /* The trampoline address is in IP0 */
1231 arm_movzx (code, ARMREG_IP1, imm & 0xffff, 0);
1232 arm_movkx (code, ARMREG_IP1, (imm >> 16) & 0xffff, 16);
1233 /* Compute the data slot address */
1234 arm_subx (code, ARMREG_IP0, ARMREG_IP0, ARMREG_IP1);
1235 /* Trampoline argument */
1236 arm_ldrx (code, ARMREG_IP1, ARMREG_IP0, 0);
1238 /* Same as arch_emit_imt_trampoline () */
1239 labels [0] = code;
1240 arm_ldrx (code, ARMREG_IP0, ARMREG_IP1, 0);
1241 arm_cmpx (code, ARMREG_IP0, MONO_ARCH_RGCTX_REG);
1242 labels [1] = code;
1243 arm_bcc (code, ARMCOND_EQ, 0);
1245 /* End-of-loop check */
1246 labels [2] = code;
1247 arm_cbzx (code, ARMREG_IP0, 0);
1249 /* Loop footer */
1250 arm_addx_imm (code, ARMREG_IP1, ARMREG_IP1, 2 * 8);
1251 arm_b (code, labels [0]);
1253 /* Match */
1254 mono_arm_patch (labels [1], code, MONO_R_ARM64_BCC);
1255 /* Load vtable slot addr */
1256 arm_ldrx (code, ARMREG_IP0, ARMREG_IP1, 8);
1257 /* Load vtable slot */
1258 arm_ldrx (code, ARMREG_IP0, ARMREG_IP0, 0);
1259 arm_brx (code, ARMREG_IP0);
1261 /* No match */
1262 mono_arm_patch (labels [2], code, MONO_R_ARM64_CBZ);
1263 /* Load fail addr */
1264 arm_ldrx (code, ARMREG_IP0, ARMREG_IP1, 8);
1265 arm_brx (code, ARMREG_IP0);
1267 emit_code_bytes (acfg, buf, code - buf);
1269 common_tramp_size = code - buf;
1270 acfg->tramp_page_code_offsets [MONO_AOT_TRAMP_IMT] = common_tramp_size;
1272 arm64_emit_tramp_page_specific_code (acfg, pagesize, common_tramp_size, specific_tramp_size);
1275 static void
1276 arm64_emit_specific_trampoline (MonoAotCompile *acfg, int offset, int *tramp_size)
1278 /* Load argument from second GOT slot */
1279 arm64_emit_load_got_slot (acfg, ARMREG_R17, offset + 1);
1280 /* Load generic trampoline address from first GOT slot */
1281 arm64_emit_load_got_slot (acfg, ARMREG_R16, offset);
1282 fprintf (acfg->fp, "br x16\n");
1283 *tramp_size = 7 * 4;
1286 static void
1287 arm64_emit_unbox_trampoline (MonoAotCompile *acfg, MonoCompile *cfg, MonoMethod *method, const char *call_target)
1289 emit_unset_mode (acfg);
1290 fprintf (acfg->fp, "add x0, x0, %d\n", (int)(sizeof (MonoObject)));
1291 fprintf (acfg->fp, "b %s\n", call_target);
1294 static void
1295 arm64_emit_static_rgctx_trampoline (MonoAotCompile *acfg, int offset, int *tramp_size)
1297 /* Similar to the specific trampolines, but use the rgctx reg instead of ip1 */
1299 /* Load argument from first GOT slot */
1300 arm64_emit_load_got_slot (acfg, MONO_ARCH_RGCTX_REG, offset);
1301 /* Load generic trampoline address from second GOT slot */
1302 arm64_emit_load_got_slot (acfg, ARMREG_R16, offset + 1);
1303 fprintf (acfg->fp, "br x16\n");
1304 *tramp_size = 7 * 4;
1307 static void
1308 arm64_emit_imt_trampoline (MonoAotCompile *acfg, int offset, int *tramp_size)
1310 guint8 buf [128];
1311 guint8 *code, *labels [16];
1313 /* Load parameter from GOT slot into ip1 */
1314 arm64_emit_load_got_slot (acfg, ARMREG_R17, offset);
1316 code = buf;
1317 labels [0] = code;
1318 arm_ldrx (code, ARMREG_IP0, ARMREG_IP1, 0);
1319 arm_cmpx (code, ARMREG_IP0, MONO_ARCH_RGCTX_REG);
1320 labels [1] = code;
1321 arm_bcc (code, ARMCOND_EQ, 0);
1323 /* End-of-loop check */
1324 labels [2] = code;
1325 arm_cbzx (code, ARMREG_IP0, 0);
1327 /* Loop footer */
1328 arm_addx_imm (code, ARMREG_IP1, ARMREG_IP1, 2 * 8);
1329 arm_b (code, labels [0]);
1331 /* Match */
1332 mono_arm_patch (labels [1], code, MONO_R_ARM64_BCC);
1333 /* Load vtable slot addr */
1334 arm_ldrx (code, ARMREG_IP0, ARMREG_IP1, 8);
1335 /* Load vtable slot */
1336 arm_ldrx (code, ARMREG_IP0, ARMREG_IP0, 0);
1337 arm_brx (code, ARMREG_IP0);
1339 /* No match */
1340 mono_arm_patch (labels [2], code, MONO_R_ARM64_CBZ);
1341 /* Load fail addr */
1342 arm_ldrx (code, ARMREG_IP0, ARMREG_IP1, 8);
1343 arm_brx (code, ARMREG_IP0);
1345 emit_code_bytes (acfg, buf, code - buf);
1347 *tramp_size = code - buf + (3 * 4);
1350 static void
1351 arm64_emit_gsharedvt_arg_trampoline (MonoAotCompile *acfg, int offset, int *tramp_size)
1353 /* Similar to the specific trampolines, but the address is in the second slot */
1354 /* Load argument from first GOT slot */
1355 arm64_emit_load_got_slot (acfg, ARMREG_R17, offset);
1356 /* Load generic trampoline address from second GOT slot */
1357 arm64_emit_load_got_slot (acfg, ARMREG_R16, offset + 1);
1358 fprintf (acfg->fp, "br x16\n");
1359 *tramp_size = 7 * 4;
1363 #endif
1365 #ifdef MONO_ARCH_AOT_SUPPORTED
1367 * arch_emit_direct_call:
1369 * Emit a direct call to the symbol TARGET. CALL_SIZE is set to the size of the
1370 * calling code.
1372 static void
1373 arch_emit_direct_call (MonoAotCompile *acfg, const char *target, gboolean external, gboolean thumb, MonoJumpInfo *ji, int *call_size)
1375 #if defined(TARGET_X86) || defined(TARGET_AMD64)
1376 /* Need to make sure this is exactly 5 bytes long */
1377 emit_unset_mode (acfg);
1378 fprintf (acfg->fp, "call %s\n", target);
1379 *call_size = 5;
1380 #elif defined(TARGET_ARM)
1381 emit_unset_mode (acfg);
1382 if (thumb)
1383 fprintf (acfg->fp, "blx %s\n", target);
1384 else
1385 fprintf (acfg->fp, "bl %s\n", target);
1386 *call_size = 4;
1387 #elif defined(TARGET_ARM64)
1388 arm64_emit_direct_call (acfg, target, external, thumb, ji, call_size);
1389 #elif defined(TARGET_POWERPC)
1390 emit_unset_mode (acfg);
1391 fprintf (acfg->fp, "bl %s\n", target);
1392 *call_size = 4;
1393 #else
1394 g_assert_not_reached ();
1395 #endif
1397 #endif
1400 * PPC32 design:
1401 * - we use an approach similar to the x86 abi: reserve a register (r30) to hold
1402 * the GOT pointer.
1403 * - The full-aot trampolines need access to the GOT of mscorlib, so we store
1404 * in in the 2. slot of every GOT, and require every method to place the GOT
1405 * address in r30, even when it doesn't access the GOT otherwise. This way,
1406 * the trampolines can compute the mscorlib GOT address by loading 4(r30).
1410 * PPC64 design:
1411 * PPC64 uses function descriptors which greatly complicate all code, since
1412 * these are used very inconsistently in the runtime. Some functions like
1413 * mono_compile_method () return ftn descriptors, while others like the
1414 * trampoline creation functions do not.
1415 * We assume that all GOT slots contain function descriptors, and create
1416 * descriptors in aot-runtime.c when needed.
1417 * The ppc64 abi uses r2 to hold the address of the TOC/GOT, which is loaded
1418 * from function descriptors, we could do the same, but it would require
1419 * rewriting all the ppc/aot code to handle function descriptors properly.
1420 * So instead, we use the same approach as on PPC32.
1421 * This is a horrible mess, but fixing it would probably lead to an even bigger
1422 * one.
1426 * X86 design:
1427 * - similar to the PPC32 design, we reserve EBX to hold the GOT pointer.
1430 #ifdef MONO_ARCH_AOT_SUPPORTED
1432 * arch_emit_got_offset:
1434 * The memory pointed to by CODE should hold native code for computing the GOT
1435 * address (OP_LOAD_GOTADDR). Emit this code while patching it with the offset
1436 * between code and the GOT. CODE_SIZE is set to the number of bytes emitted.
1438 static void
1439 arch_emit_got_offset (MonoAotCompile *acfg, guint8 *code, int *code_size)
1441 #if defined(TARGET_POWERPC64)
1442 emit_unset_mode (acfg);
1444 * The ppc32 code doesn't seem to work on ppc64, the assembler complains about
1445 * unsupported relocations. So we store the got address into the .Lgot_addr
1446 * symbol which is in the text segment, compute its address, and load it.
1448 fprintf (acfg->fp, ".L%d:\n", acfg->label_generator);
1449 fprintf (acfg->fp, "lis 0, (.Lgot_addr + 4 - .L%d)@h\n", acfg->label_generator);
1450 fprintf (acfg->fp, "ori 0, 0, (.Lgot_addr + 4 - .L%d)@l\n", acfg->label_generator);
1451 fprintf (acfg->fp, "add 30, 30, 0\n");
1452 fprintf (acfg->fp, "%s 30, 0(30)\n", PPC_LD_OP);
1453 acfg->label_generator ++;
1454 *code_size = 16;
1455 #elif defined(TARGET_POWERPC)
1456 emit_unset_mode (acfg);
1457 fprintf (acfg->fp, ".L%d:\n", acfg->label_generator);
1458 fprintf (acfg->fp, "lis 0, (%s + 4 - .L%d)@h\n", acfg->got_symbol, acfg->label_generator);
1459 fprintf (acfg->fp, "ori 0, 0, (%s + 4 - .L%d)@l\n", acfg->got_symbol, acfg->label_generator);
1460 acfg->label_generator ++;
1461 *code_size = 8;
1462 #else
1463 guint32 offset = mono_arch_get_patch_offset (code);
1464 emit_bytes (acfg, code, offset);
1465 emit_symbol_diff (acfg, acfg->got_symbol, ".", offset);
1467 *code_size = offset + 4;
1468 #endif
1472 * arch_emit_got_access:
1474 * The memory pointed to by CODE should hold native code for loading a GOT
1475 * slot (OP_AOTCONST/OP_GOT_ENTRY). Emit this code while patching it so it accesses the
1476 * GOT slot GOT_SLOT. CODE_SIZE is set to the number of bytes emitted.
1478 static void
1479 arch_emit_got_access (MonoAotCompile *acfg, const char *got_symbol, guint8 *code, int got_slot, int *code_size)
1481 #ifdef TARGET_AMD64
1482 /* mov reg, got+offset(%rip) */
1483 if (acfg->llvm) {
1484 /* The GOT symbol is in the LLVM module, the clang assembler has problems emitting symbol diffs for it */
1485 int dreg;
1486 int rex_r;
1488 /* Decode reg, see amd64_mov_reg_membase () */
1489 rex_r = code [0] & AMD64_REX_R;
1490 g_assert (code [0] == 0x49 + rex_r);
1491 g_assert (code [1] == 0x8b);
1492 dreg = ((code [2] >> 3) & 0x7) + (rex_r ? 8 : 0);
1494 emit_unset_mode (acfg);
1495 fprintf (acfg->fp, "mov %s+%d(%%rip), %s\n", got_symbol, (unsigned int) ((got_slot * sizeof (gpointer))), mono_arch_regname (dreg));
1496 *code_size = 7;
1497 } else {
1498 emit_bytes (acfg, code, mono_arch_get_patch_offset (code));
1499 emit_symbol_diff (acfg, got_symbol, ".", (unsigned int) ((got_slot * sizeof (gpointer)) - 4));
1500 *code_size = mono_arch_get_patch_offset (code) + 4;
1502 #elif defined(TARGET_X86)
1503 emit_bytes (acfg, code, mono_arch_get_patch_offset (code));
1504 emit_int32 (acfg, (unsigned int) ((got_slot * sizeof (gpointer))));
1505 *code_size = mono_arch_get_patch_offset (code) + 4;
1506 #elif defined(TARGET_ARM)
1507 emit_bytes (acfg, code, mono_arch_get_patch_offset (code));
1508 emit_symbol_diff (acfg, got_symbol, ".", (unsigned int) ((got_slot * sizeof (gpointer))) - 12);
1509 *code_size = mono_arch_get_patch_offset (code) + 4;
1510 #elif defined(TARGET_ARM64)
1511 emit_bytes (acfg, code, mono_arch_get_patch_offset (code));
1512 arm64_emit_got_access (acfg, code, got_slot, code_size);
1513 #elif defined(TARGET_POWERPC)
1515 guint8 buf [32];
1517 emit_bytes (acfg, code, mono_arch_get_patch_offset (code));
1518 code = buf;
1519 ppc_load32 (code, ppc_r0, got_slot * sizeof (gpointer));
1520 g_assert (code - buf == 8);
1521 emit_bytes (acfg, buf, code - buf);
1522 *code_size = code - buf;
1524 #else
1525 g_assert_not_reached ();
1526 #endif
1529 #endif
1531 #ifdef MONO_ARCH_AOT_SUPPORTED
1533 * arch_emit_objc_selector_ref:
1535 * Emit the implementation of OP_OBJC_GET_SELECTOR, which itself implements @selector(foo:) in objective-c.
1537 static void
1538 arch_emit_objc_selector_ref (MonoAotCompile *acfg, guint8 *code, int index, int *code_size)
1540 #if defined(TARGET_ARM)
1541 char symbol1 [MAX_SYMBOL_SIZE];
1542 char symbol2 [MAX_SYMBOL_SIZE];
1543 int lindex = acfg->objc_selector_index_2 ++;
1545 /* Emit ldr.imm/b */
1546 emit_bytes (acfg, code, 8);
1548 sprintf (symbol1, "L_OBJC_SELECTOR_%d", lindex);
1549 sprintf (symbol2, "L_OBJC_SELECTOR_REFERENCES_%d", index);
1551 emit_label (acfg, symbol1);
1552 mono_img_writer_emit_unset_mode (acfg->w);
1553 fprintf (acfg->fp, ".long %s-(%s+12)", symbol2, symbol1);
1555 *code_size = 12;
1556 #elif defined(TARGET_ARM64)
1557 arm64_emit_objc_selector_ref (acfg, code, index, code_size);
1558 #else
1559 g_assert_not_reached ();
1560 #endif
1562 #endif
1565 * arch_emit_plt_entry:
1567 * Emit code for the PLT entry.
1568 * The plt entry should look like this:
1569 * <indirect jump to GOT_SYMBOL + OFFSET>
1570 * <INFO_OFFSET embedded into the instruction stream>
1572 static void
1573 arch_emit_plt_entry (MonoAotCompile *acfg, const char *got_symbol, int offset, int info_offset)
1575 #if defined(TARGET_X86)
1576 /* jmp *<offset>(%ebx) */
1577 emit_byte (acfg, 0xff);
1578 emit_byte (acfg, 0xa3);
1579 emit_int32 (acfg, offset);
1580 /* Used by mono_aot_get_plt_info_offset */
1581 emit_int32 (acfg, info_offset);
1582 #elif defined(TARGET_AMD64)
1583 emit_unset_mode (acfg);
1584 fprintf (acfg->fp, "jmp *%s+%d(%%rip)\n", got_symbol, offset);
1585 /* Used by mono_aot_get_plt_info_offset */
1586 emit_int32 (acfg, info_offset);
1587 acfg->stats.plt_size += 10;
1588 #elif defined(TARGET_ARM)
1589 guint8 buf [256];
1590 guint8 *code;
1592 code = buf;
1593 ARM_LDR_IMM (code, ARMREG_IP, ARMREG_PC, 0);
1594 ARM_LDR_REG_REG (code, ARMREG_PC, ARMREG_PC, ARMREG_IP);
1595 emit_bytes (acfg, buf, code - buf);
1596 emit_symbol_diff (acfg, got_symbol, ".", offset - 4);
1597 /* Used by mono_aot_get_plt_info_offset */
1598 emit_int32 (acfg, info_offset);
1599 #elif defined(TARGET_ARM64)
1600 arm64_emit_plt_entry (acfg, got_symbol, offset, info_offset);
1601 #elif defined(TARGET_POWERPC)
1602 /* The GOT address is guaranteed to be in r30 by OP_LOAD_GOTADDR */
1603 emit_unset_mode (acfg);
1604 fprintf (acfg->fp, "lis 11, %d@h\n", offset);
1605 fprintf (acfg->fp, "ori 11, 11, %d@l\n", offset);
1606 fprintf (acfg->fp, "add 11, 11, 30\n");
1607 fprintf (acfg->fp, "%s 11, 0(11)\n", PPC_LD_OP);
1608 #ifdef PPC_USES_FUNCTION_DESCRIPTOR
1609 fprintf (acfg->fp, "%s 2, %d(11)\n", PPC_LD_OP, (int)sizeof (gpointer));
1610 fprintf (acfg->fp, "%s 11, 0(11)\n", PPC_LD_OP);
1611 #endif
1612 fprintf (acfg->fp, "mtctr 11\n");
1613 fprintf (acfg->fp, "bctr\n");
1614 emit_int32 (acfg, info_offset);
1615 #else
1616 g_assert_not_reached ();
1617 #endif
1621 * arch_emit_llvm_plt_entry:
1623 * Same as arch_emit_plt_entry, but handles calls from LLVM generated code.
1624 * This is only needed on arm to handle thumb interop.
1626 static void
1627 arch_emit_llvm_plt_entry (MonoAotCompile *acfg, const char *got_symbol, int offset, int info_offset)
1629 #if defined(TARGET_ARM)
1630 /* LLVM calls the PLT entries using bl, so these have to be thumb2 */
1631 /* The caller already transitioned to thumb */
1632 /* The code below should be 12 bytes long */
1633 /* clang has trouble encoding these instructions, so emit the binary */
1634 #if 0
1635 fprintf (acfg->fp, "ldr ip, [pc, #8]\n");
1636 /* thumb can't encode ld pc, [pc, ip] */
1637 fprintf (acfg->fp, "add ip, pc, ip\n");
1638 fprintf (acfg->fp, "ldr ip, [ip, #0]\n");
1639 fprintf (acfg->fp, "bx ip\n");
1640 #endif
1641 emit_set_thumb_mode (acfg);
1642 fprintf (acfg->fp, ".4byte 0xc008f8df\n");
1643 fprintf (acfg->fp, ".2byte 0x44fc\n");
1644 fprintf (acfg->fp, ".4byte 0xc000f8dc\n");
1645 fprintf (acfg->fp, ".2byte 0x4760\n");
1646 emit_symbol_diff (acfg, got_symbol, ".", offset + 4);
1647 emit_int32 (acfg, info_offset);
1648 emit_unset_mode (acfg);
1649 emit_set_arm_mode (acfg);
1650 #else
1651 g_assert_not_reached ();
1652 #endif
1655 /* Save unwind_info in the module and emit the offset to the information at symbol */
1656 static void save_unwind_info (MonoAotCompile *acfg, char *symbol, GSList *unwind_ops)
1658 guint32 uw_offset, encoded_len;
1659 guint8 *encoded;
1661 emit_section_change (acfg, RODATA_SECT, 0);
1662 emit_global (acfg, symbol, FALSE);
1663 emit_label (acfg, symbol);
1665 encoded = mono_unwind_ops_encode (unwind_ops, &encoded_len);
1666 uw_offset = get_unwind_info_offset (acfg, encoded, encoded_len);
1667 g_free (encoded);
1668 emit_int32 (acfg, uw_offset);
1672 * arch_emit_specific_trampoline_pages:
1674 * Emits a page full of trampolines: each trampoline uses its own address to
1675 * lookup both the generic trampoline code and the data argument.
1676 * This page can be remapped in process multiple times so we can get an
1677 * unlimited number of trampolines.
1678 * Specifically this implementation uses the following trick: two memory pages
1679 * are allocated, with the first containing the data and the second containing the trampolines.
1680 * To reduce trampoline size, each trampoline jumps at the start of the page where a common
1681 * implementation does all the lifting.
1682 * Note that the ARM single trampoline size is 8 bytes, exactly like the data that needs to be stored
1683 * on the arm 32 bit system.
1685 static void
1686 arch_emit_specific_trampoline_pages (MonoAotCompile *acfg)
1688 #if defined(TARGET_ARM)
1689 guint8 buf [128];
1690 guint8 *code;
1691 guint8 *loop_start, *loop_branch_back, *loop_end_check, *imt_found_check;
1692 int i;
1693 int pagesize = MONO_AOT_TRAMP_PAGE_SIZE;
1694 GSList *unwind_ops = NULL;
1695 #define COMMON_TRAMP_SIZE 16
1696 int count = (pagesize - COMMON_TRAMP_SIZE) / 8;
1697 int imm8, rot_amount;
1698 char symbol [128];
1700 if (!acfg->aot_opts.use_trampolines_page)
1701 return;
1703 acfg->tramp_page_size = pagesize;
1705 sprintf (symbol, "%sspecific_trampolines_page", acfg->user_symbol_prefix);
1706 emit_alignment (acfg, pagesize);
1707 emit_global (acfg, symbol, TRUE);
1708 emit_label (acfg, symbol);
1710 /* emit the generic code first, the trampoline address + 8 is in the lr register */
1711 code = buf;
1712 imm8 = mono_arm_is_rotated_imm8 (pagesize, &rot_amount);
1713 ARM_SUB_REG_IMM (code, ARMREG_LR, ARMREG_LR, imm8, rot_amount);
1714 ARM_LDR_IMM (code, ARMREG_R1, ARMREG_LR, -8);
1715 ARM_LDR_IMM (code, ARMREG_PC, ARMREG_LR, -4);
1716 ARM_NOP (code);
1717 g_assert (code - buf == COMMON_TRAMP_SIZE);
1719 /* Emit it */
1720 emit_bytes (acfg, buf, code - buf);
1722 for (i = 0; i < count; ++i) {
1723 code = buf;
1724 ARM_PUSH (code, 0x5fff);
1725 ARM_BL (code, 0);
1726 arm_patch (code - 4, code - COMMON_TRAMP_SIZE - 8 * (i + 1));
1727 g_assert (code - buf == 8);
1728 emit_bytes (acfg, buf, code - buf);
1731 /* now the rgctx trampolines: each specific trampolines puts in the ip register
1732 * the instruction pointer address, so the generic trampoline at the start of the page
1733 * subtracts 4096 to get to the data page and loads the values
1734 * We again fit the generic trampiline in 16 bytes.
1736 sprintf (symbol, "%srgctx_trampolines_page", acfg->user_symbol_prefix);
1737 emit_global (acfg, symbol, TRUE);
1738 emit_label (acfg, symbol);
1739 code = buf;
1740 imm8 = mono_arm_is_rotated_imm8 (pagesize, &rot_amount);
1741 ARM_SUB_REG_IMM (code, ARMREG_IP, ARMREG_IP, imm8, rot_amount);
1742 ARM_LDR_IMM (code, MONO_ARCH_RGCTX_REG, ARMREG_IP, -8);
1743 ARM_LDR_IMM (code, ARMREG_PC, ARMREG_IP, -4);
1744 ARM_NOP (code);
1745 g_assert (code - buf == COMMON_TRAMP_SIZE);
1747 /* Emit it */
1748 emit_bytes (acfg, buf, code - buf);
1750 for (i = 0; i < count; ++i) {
1751 code = buf;
1752 ARM_MOV_REG_REG (code, ARMREG_IP, ARMREG_PC);
1753 ARM_B (code, 0);
1754 arm_patch (code - 4, code - COMMON_TRAMP_SIZE - 8 * (i + 1));
1755 g_assert (code - buf == 8);
1756 emit_bytes (acfg, buf, code - buf);
1760 * gsharedvt arg trampolines: see arch_emit_gsharedvt_arg_trampoline ()
1762 sprintf (symbol, "%sgsharedvt_arg_trampolines_page", acfg->user_symbol_prefix);
1763 emit_global (acfg, symbol, TRUE);
1764 emit_label (acfg, symbol);
1765 code = buf;
1766 ARM_PUSH (code, (1 << ARMREG_R0) | (1 << ARMREG_R1) | (1 << ARMREG_R2) | (1 << ARMREG_R3));
1767 imm8 = mono_arm_is_rotated_imm8 (pagesize, &rot_amount);
1768 ARM_SUB_REG_IMM (code, ARMREG_IP, ARMREG_IP, imm8, rot_amount);
1769 ARM_LDR_IMM (code, ARMREG_R0, ARMREG_IP, -8);
1770 ARM_LDR_IMM (code, ARMREG_PC, ARMREG_IP, -4);
1771 g_assert (code - buf == COMMON_TRAMP_SIZE);
1772 /* Emit it */
1773 emit_bytes (acfg, buf, code - buf);
1775 for (i = 0; i < count; ++i) {
1776 code = buf;
1777 ARM_MOV_REG_REG (code, ARMREG_IP, ARMREG_PC);
1778 ARM_B (code, 0);
1779 arm_patch (code - 4, code - COMMON_TRAMP_SIZE - 8 * (i + 1));
1780 g_assert (code - buf == 8);
1781 emit_bytes (acfg, buf, code - buf);
1784 /* now the imt trampolines: each specific trampolines puts in the ip register
1785 * the instruction pointer address, so the generic trampoline at the start of the page
1786 * subtracts 4096 to get to the data page and loads the values
1788 #define IMT_TRAMP_SIZE 72
1789 sprintf (symbol, "%simt_trampolines_page", acfg->user_symbol_prefix);
1790 emit_global (acfg, symbol, TRUE);
1791 emit_label (acfg, symbol);
1792 code = buf;
1793 /* Need at least two free registers, plus a slot for storing the pc */
1794 ARM_PUSH (code, (1 << ARMREG_R0)|(1 << ARMREG_R1)|(1 << ARMREG_R2));
1796 imm8 = mono_arm_is_rotated_imm8 (pagesize, &rot_amount);
1797 ARM_SUB_REG_IMM (code, ARMREG_IP, ARMREG_IP, imm8, rot_amount);
1798 ARM_LDR_IMM (code, ARMREG_R0, ARMREG_IP, -8);
1800 /* The IMT method is in v5, r0 has the imt array address */
1802 loop_start = code;
1803 ARM_LDR_IMM (code, ARMREG_R1, ARMREG_R0, 0);
1804 ARM_CMP_REG_REG (code, ARMREG_R1, ARMREG_V5);
1805 imt_found_check = code;
1806 ARM_B_COND (code, ARMCOND_EQ, 0);
1808 /* End-of-loop check */
1809 ARM_CMP_REG_IMM (code, ARMREG_R1, 0, 0);
1810 loop_end_check = code;
1811 ARM_B_COND (code, ARMCOND_EQ, 0);
1813 /* Loop footer */
1814 ARM_ADD_REG_IMM8 (code, ARMREG_R0, ARMREG_R0, sizeof (gpointer) * 2);
1815 loop_branch_back = code;
1816 ARM_B (code, 0);
1817 arm_patch (loop_branch_back, loop_start);
1819 /* Match */
1820 arm_patch (imt_found_check, code);
1821 ARM_LDR_IMM (code, ARMREG_R0, ARMREG_R0, 4);
1822 ARM_LDR_IMM (code, ARMREG_R0, ARMREG_R0, 0);
1823 /* Save it to the third stack slot */
1824 ARM_STR_IMM (code, ARMREG_R0, ARMREG_SP, 8);
1825 /* Restore the registers and branch */
1826 ARM_POP (code, (1 << ARMREG_R0)|(1 << ARMREG_R1)|(1 << ARMREG_PC));
1828 /* No match */
1829 arm_patch (loop_end_check, code);
1830 ARM_LDR_IMM (code, ARMREG_R0, ARMREG_R0, 4);
1831 ARM_STR_IMM (code, ARMREG_R0, ARMREG_SP, 8);
1832 ARM_POP (code, (1 << ARMREG_R0)|(1 << ARMREG_R1)|(1 << ARMREG_PC));
1833 ARM_NOP (code);
1835 /* Emit it */
1836 g_assert (code - buf == IMT_TRAMP_SIZE);
1837 emit_bytes (acfg, buf, code - buf);
1839 for (i = 0; i < count; ++i) {
1840 code = buf;
1841 ARM_MOV_REG_REG (code, ARMREG_IP, ARMREG_PC);
1842 ARM_B (code, 0);
1843 arm_patch (code - 4, code - IMT_TRAMP_SIZE - 8 * (i + 1));
1844 g_assert (code - buf == 8);
1845 emit_bytes (acfg, buf, code - buf);
1848 acfg->tramp_page_code_offsets [MONO_AOT_TRAMP_SPECIFIC] = 16;
1849 acfg->tramp_page_code_offsets [MONO_AOT_TRAMP_STATIC_RGCTX] = 16;
1850 acfg->tramp_page_code_offsets [MONO_AOT_TRAMP_IMT] = 72;
1851 acfg->tramp_page_code_offsets [MONO_AOT_TRAMP_GSHAREDVT_ARG] = 16;
1853 /* Unwind info for specifc trampolines */
1854 sprintf (symbol, "%sspecific_trampolines_page_gen_p", acfg->user_symbol_prefix);
1855 /* We unwind to the original caller, from the stack, since lr is clobbered */
1856 mono_add_unwind_op_def_cfa (unwind_ops, 0, 0, ARMREG_SP, 14 * sizeof (mgreg_t));
1857 mono_add_unwind_op_offset (unwind_ops, 0, 0, ARMREG_LR, -4);
1858 save_unwind_info (acfg, symbol, unwind_ops);
1859 mono_free_unwind_info (unwind_ops);
1861 sprintf (symbol, "%sspecific_trampolines_page_sp_p", acfg->user_symbol_prefix);
1862 mono_add_unwind_op_def_cfa (unwind_ops, 0, 0, ARMREG_SP, 0);
1863 mono_add_unwind_op_def_cfa_offset (unwind_ops, 4, 0, 14 * sizeof (mgreg_t));
1864 save_unwind_info (acfg, symbol, unwind_ops);
1865 mono_free_unwind_info (unwind_ops);
1867 /* Unwind info for rgctx trampolines */
1868 sprintf (symbol, "%srgctx_trampolines_page_gen_p", acfg->user_symbol_prefix);
1869 mono_add_unwind_op_def_cfa (unwind_ops, 0, 0, ARMREG_SP, 0);
1870 save_unwind_info (acfg, symbol, unwind_ops);
1872 sprintf (symbol, "%srgctx_trampolines_page_sp_p", acfg->user_symbol_prefix);
1873 save_unwind_info (acfg, symbol, unwind_ops);
1874 mono_free_unwind_info (unwind_ops);
1876 /* Unwind info for gsharedvt trampolines */
1877 sprintf (symbol, "%sgsharedvt_trampolines_page_gen_p", acfg->user_symbol_prefix);
1878 mono_add_unwind_op_def_cfa (unwind_ops, 0, 0, ARMREG_SP, 0);
1879 mono_add_unwind_op_def_cfa_offset (unwind_ops, 4, 0, 4 * sizeof (mgreg_t));
1880 save_unwind_info (acfg, symbol, unwind_ops);
1881 mono_free_unwind_info (unwind_ops);
1883 sprintf (symbol, "%sgsharedvt_trampolines_page_sp_p", acfg->user_symbol_prefix);
1884 mono_add_unwind_op_def_cfa (unwind_ops, 0, 0, ARMREG_SP, 0);
1885 save_unwind_info (acfg, symbol, unwind_ops);
1886 mono_free_unwind_info (unwind_ops);
1888 /* Unwind info for imt trampolines */
1889 sprintf (symbol, "%simt_trampolines_page_gen_p", acfg->user_symbol_prefix);
1890 mono_add_unwind_op_def_cfa (unwind_ops, 0, 0, ARMREG_SP, 0);
1891 mono_add_unwind_op_def_cfa_offset (unwind_ops, 4, 0, 3 * sizeof (mgreg_t));
1892 save_unwind_info (acfg, symbol, unwind_ops);
1893 mono_free_unwind_info (unwind_ops);
1895 sprintf (symbol, "%simt_trampolines_page_sp_p", acfg->user_symbol_prefix);
1896 mono_add_unwind_op_def_cfa (unwind_ops, 0, 0, ARMREG_SP, 0);
1897 save_unwind_info (acfg, symbol, unwind_ops);
1898 mono_free_unwind_info (unwind_ops);
1899 #elif defined(TARGET_ARM64)
1900 arm64_emit_specific_trampoline_pages (acfg);
1901 #endif
1905 * arch_emit_specific_trampoline:
1907 * Emit code for a specific trampoline. OFFSET is the offset of the first of
1908 * two GOT slots which contain the generic trampoline address and the trampoline
1909 * argument. TRAMP_SIZE is set to the size of the emitted trampoline.
1911 static void
1912 arch_emit_specific_trampoline (MonoAotCompile *acfg, int offset, int *tramp_size)
1915 * The trampolines created here are variations of the specific
1916 * trampolines created in mono_arch_create_specific_trampoline (). The
1917 * differences are:
1918 * - the generic trampoline address is taken from a got slot.
1919 * - the offset of the got slot where the trampoline argument is stored
1920 * is embedded in the instruction stream, and the generic trampoline
1921 * can load the argument by loading the offset, adding it to the
1922 * address of the trampoline to get the address of the got slot, and
1923 * loading the argument from there.
1924 * - all the trampolines should be of the same length.
1926 #if defined(TARGET_AMD64)
1927 /* This should be exactly 8 bytes long */
1928 *tramp_size = 8;
1929 /* call *<offset>(%rip) */
1930 if (acfg->llvm) {
1931 emit_unset_mode (acfg);
1932 fprintf (acfg->fp, "call *%s+%d(%%rip)\n", acfg->got_symbol, (int)(offset * sizeof (gpointer)));
1933 emit_zero_bytes (acfg, 2);
1934 } else {
1935 emit_byte (acfg, '\x41');
1936 emit_byte (acfg, '\xff');
1937 emit_byte (acfg, '\x15');
1938 emit_symbol_diff (acfg, acfg->got_symbol, ".", (offset * sizeof (gpointer)) - 4);
1939 emit_zero_bytes (acfg, 1);
1941 #elif defined(TARGET_ARM)
1942 guint8 buf [128];
1943 guint8 *code;
1945 /* This should be exactly 20 bytes long */
1946 *tramp_size = 20;
1947 code = buf;
1948 ARM_PUSH (code, 0x5fff);
1949 ARM_LDR_IMM (code, ARMREG_R1, ARMREG_PC, 4);
1950 /* Load the value from the GOT */
1951 ARM_LDR_REG_REG (code, ARMREG_R1, ARMREG_PC, ARMREG_R1);
1952 /* Branch to it */
1953 ARM_BLX_REG (code, ARMREG_R1);
1955 g_assert (code - buf == 16);
1957 /* Emit it */
1958 emit_bytes (acfg, buf, code - buf);
1960 * Only one offset is needed, since the second one would be equal to the
1961 * first one.
1963 emit_symbol_diff (acfg, acfg->got_symbol, ".", (offset * sizeof (gpointer)) - 4 + 4);
1964 //emit_symbol_diff (acfg, acfg->got_symbol, ".", ((offset + 1) * sizeof (gpointer)) - 4 + 8);
1965 #elif defined(TARGET_ARM64)
1966 arm64_emit_specific_trampoline (acfg, offset, tramp_size);
1967 #elif defined(TARGET_POWERPC)
1968 guint8 buf [128];
1969 guint8 *code;
1971 *tramp_size = 4;
1972 code = buf;
1975 * PPC has no ip relative addressing, so we need to compute the address
1976 * of the mscorlib got. That is slow and complex, so instead, we store it
1977 * in the second got slot of every aot image. The caller already computed
1978 * the address of its got and placed it into r30.
1980 emit_unset_mode (acfg);
1981 /* Load mscorlib got address */
1982 fprintf (acfg->fp, "%s 0, %d(30)\n", PPC_LD_OP, (int)sizeof (gpointer));
1983 /* Load generic trampoline address */
1984 fprintf (acfg->fp, "lis 11, %d@h\n", (int)(offset * sizeof (gpointer)));
1985 fprintf (acfg->fp, "ori 11, 11, %d@l\n", (int)(offset * sizeof (gpointer)));
1986 fprintf (acfg->fp, "%s 11, 11, 0\n", PPC_LDX_OP);
1987 #ifdef PPC_USES_FUNCTION_DESCRIPTOR
1988 fprintf (acfg->fp, "%s 11, 0(11)\n", PPC_LD_OP);
1989 #endif
1990 fprintf (acfg->fp, "mtctr 11\n");
1991 /* Load trampoline argument */
1992 /* On ppc, we pass it normally to the generic trampoline */
1993 fprintf (acfg->fp, "lis 11, %d@h\n", (int)((offset + 1) * sizeof (gpointer)));
1994 fprintf (acfg->fp, "ori 11, 11, %d@l\n", (int)((offset + 1) * sizeof (gpointer)));
1995 fprintf (acfg->fp, "%s 0, 11, 0\n", PPC_LDX_OP);
1996 /* Branch to generic trampoline */
1997 fprintf (acfg->fp, "bctr\n");
1999 #ifdef PPC_USES_FUNCTION_DESCRIPTOR
2000 *tramp_size = 10 * 4;
2001 #else
2002 *tramp_size = 9 * 4;
2003 #endif
2004 #elif defined(TARGET_X86)
2005 guint8 buf [128];
2006 guint8 *code;
2008 /* Similar to the PPC code above */
2010 /* FIXME: Could this clobber the register needed by get_vcall_slot () ? */
2012 code = buf;
2013 /* Load mscorlib got address */
2014 x86_mov_reg_membase (code, X86_ECX, MONO_ARCH_GOT_REG, sizeof (gpointer), 4);
2015 /* Push trampoline argument */
2016 x86_push_membase (code, X86_ECX, (offset + 1) * sizeof (gpointer));
2017 /* Load generic trampoline address */
2018 x86_mov_reg_membase (code, X86_ECX, X86_ECX, offset * sizeof (gpointer), 4);
2019 /* Branch to generic trampoline */
2020 x86_jump_reg (code, X86_ECX);
2022 emit_bytes (acfg, buf, code - buf);
2024 *tramp_size = 17;
2025 g_assert (code - buf == *tramp_size);
2026 #else
2027 g_assert_not_reached ();
2028 #endif
2032 * arch_emit_unbox_trampoline:
2034 * Emit code for the unbox trampoline for METHOD used in the full-aot case.
2035 * CALL_TARGET is the symbol pointing to the native code of METHOD.
2037 static void
2038 arch_emit_unbox_trampoline (MonoAotCompile *acfg, MonoCompile *cfg, MonoMethod *method, const char *call_target)
2040 #if defined(TARGET_AMD64)
2041 guint8 buf [32];
2042 guint8 *code;
2043 int this_reg;
2045 this_reg = mono_arch_get_this_arg_reg (NULL);
2046 code = buf;
2047 amd64_alu_reg_imm (code, X86_ADD, this_reg, sizeof (MonoObject));
2049 emit_bytes (acfg, buf, code - buf);
2050 /* jump <method> */
2051 if (acfg->llvm) {
2052 emit_unset_mode (acfg);
2053 fprintf (acfg->fp, "jmp %s\n", call_target);
2054 } else {
2055 emit_byte (acfg, '\xe9');
2056 emit_symbol_diff (acfg, call_target, ".", -4);
2058 #elif defined(TARGET_X86)
2059 guint8 buf [32];
2060 guint8 *code;
2061 int this_pos = 4;
2063 code = buf;
2065 x86_alu_membase_imm (code, X86_ADD, X86_ESP, this_pos, sizeof (MonoObject));
2067 emit_bytes (acfg, buf, code - buf);
2069 /* jump <method> */
2070 emit_byte (acfg, '\xe9');
2071 emit_symbol_diff (acfg, call_target, ".", -4);
2072 #elif defined(TARGET_ARM)
2073 guint8 buf [128];
2074 guint8 *code;
2076 if (acfg->thumb_mixed && cfg->compile_llvm) {
2077 fprintf (acfg->fp, "add r0, r0, #%d\n", (int)sizeof (MonoObject));
2078 fprintf (acfg->fp, "b %s\n", call_target);
2079 fprintf (acfg->fp, ".arm\n");
2080 fprintf (acfg->fp, ".align 2\n");
2081 return;
2084 code = buf;
2086 ARM_ADD_REG_IMM8 (code, ARMREG_R0, ARMREG_R0, sizeof (MonoObject));
2088 emit_bytes (acfg, buf, code - buf);
2089 /* jump to method */
2090 if (acfg->thumb_mixed && cfg->compile_llvm)
2091 fprintf (acfg->fp, "\n\tbx %s\n", call_target);
2092 else
2093 fprintf (acfg->fp, "\n\tb %s\n", call_target);
2094 #elif defined(TARGET_ARM64)
2095 arm64_emit_unbox_trampoline (acfg, cfg, method, call_target);
2096 #elif defined(TARGET_POWERPC)
2097 int this_pos = 3;
2099 fprintf (acfg->fp, "\n\taddi %d, %d, %d\n", this_pos, this_pos, (int)sizeof (MonoObject));
2100 fprintf (acfg->fp, "\n\tb %s\n", call_target);
2101 #else
2102 g_assert_not_reached ();
2103 #endif
2107 * arch_emit_static_rgctx_trampoline:
2109 * Emit code for a static rgctx trampoline. OFFSET is the offset of the first of
2110 * two GOT slots which contain the rgctx argument, and the method to jump to.
2111 * TRAMP_SIZE is set to the size of the emitted trampoline.
2112 * These kinds of trampolines cannot be enumerated statically, since there could
2113 * be one trampoline per method instantiation, so we emit the same code for all
2114 * trampolines, and parameterize them using two GOT slots.
2116 static void
2117 arch_emit_static_rgctx_trampoline (MonoAotCompile *acfg, int offset, int *tramp_size)
2119 #if defined(TARGET_AMD64)
2120 /* This should be exactly 13 bytes long */
2121 *tramp_size = 13;
2123 if (acfg->llvm) {
2124 emit_unset_mode (acfg);
2125 fprintf (acfg->fp, "mov %s+%d(%%rip), %%r10\n", acfg->got_symbol, (int)(offset * sizeof (gpointer)));
2126 fprintf (acfg->fp, "jmp *%s+%d(%%rip)\n", acfg->got_symbol, (int)((offset + 1) * sizeof (gpointer)));
2127 } else {
2128 /* mov <OFFSET>(%rip), %r10 */
2129 emit_byte (acfg, '\x4d');
2130 emit_byte (acfg, '\x8b');
2131 emit_byte (acfg, '\x15');
2132 emit_symbol_diff (acfg, acfg->got_symbol, ".", (offset * sizeof (gpointer)) - 4);
2134 /* jmp *<offset>(%rip) */
2135 emit_byte (acfg, '\xff');
2136 emit_byte (acfg, '\x25');
2137 emit_symbol_diff (acfg, acfg->got_symbol, ".", ((offset + 1) * sizeof (gpointer)) - 4);
2139 #elif defined(TARGET_ARM)
2140 guint8 buf [128];
2141 guint8 *code;
2143 /* This should be exactly 24 bytes long */
2144 *tramp_size = 24;
2145 code = buf;
2146 /* Load rgctx value */
2147 ARM_LDR_IMM (code, ARMREG_IP, ARMREG_PC, 8);
2148 ARM_LDR_REG_REG (code, MONO_ARCH_RGCTX_REG, ARMREG_PC, ARMREG_IP);
2149 /* Load branch addr + branch */
2150 ARM_LDR_IMM (code, ARMREG_IP, ARMREG_PC, 4);
2151 ARM_LDR_REG_REG (code, ARMREG_PC, ARMREG_PC, ARMREG_IP);
2153 g_assert (code - buf == 16);
2155 /* Emit it */
2156 emit_bytes (acfg, buf, code - buf);
2157 emit_symbol_diff (acfg, acfg->got_symbol, ".", (offset * sizeof (gpointer)) - 4 + 8);
2158 emit_symbol_diff (acfg, acfg->got_symbol, ".", ((offset + 1) * sizeof (gpointer)) - 4 + 4);
2159 #elif defined(TARGET_ARM64)
2160 arm64_emit_static_rgctx_trampoline (acfg, offset, tramp_size);
2161 #elif defined(TARGET_POWERPC)
2162 guint8 buf [128];
2163 guint8 *code;
2165 *tramp_size = 4;
2166 code = buf;
2169 * PPC has no ip relative addressing, so we need to compute the address
2170 * of the mscorlib got. That is slow and complex, so instead, we store it
2171 * in the second got slot of every aot image. The caller already computed
2172 * the address of its got and placed it into r30.
2174 emit_unset_mode (acfg);
2175 /* Load mscorlib got address */
2176 fprintf (acfg->fp, "%s 0, %d(30)\n", PPC_LD_OP, (int)sizeof (gpointer));
2177 /* Load rgctx */
2178 fprintf (acfg->fp, "lis 11, %d@h\n", (int)(offset * sizeof (gpointer)));
2179 fprintf (acfg->fp, "ori 11, 11, %d@l\n", (int)(offset * sizeof (gpointer)));
2180 fprintf (acfg->fp, "%s %d, 11, 0\n", PPC_LDX_OP, MONO_ARCH_RGCTX_REG);
2181 /* Load target address */
2182 fprintf (acfg->fp, "lis 11, %d@h\n", (int)((offset + 1) * sizeof (gpointer)));
2183 fprintf (acfg->fp, "ori 11, 11, %d@l\n", (int)((offset + 1) * sizeof (gpointer)));
2184 fprintf (acfg->fp, "%s 11, 11, 0\n", PPC_LDX_OP);
2185 #ifdef PPC_USES_FUNCTION_DESCRIPTOR
2186 fprintf (acfg->fp, "%s 2, %d(11)\n", PPC_LD_OP, (int)sizeof (gpointer));
2187 fprintf (acfg->fp, "%s 11, 0(11)\n", PPC_LD_OP);
2188 #endif
2189 fprintf (acfg->fp, "mtctr 11\n");
2190 /* Branch to the target address */
2191 fprintf (acfg->fp, "bctr\n");
2193 #ifdef PPC_USES_FUNCTION_DESCRIPTOR
2194 *tramp_size = 11 * 4;
2195 #else
2196 *tramp_size = 9 * 4;
2197 #endif
2199 #elif defined(TARGET_X86)
2200 guint8 buf [128];
2201 guint8 *code;
2203 /* Similar to the PPC code above */
2205 g_assert (MONO_ARCH_RGCTX_REG != X86_ECX);
2207 code = buf;
2208 /* Load mscorlib got address */
2209 x86_mov_reg_membase (code, X86_ECX, MONO_ARCH_GOT_REG, sizeof (gpointer), 4);
2210 /* Load arg */
2211 x86_mov_reg_membase (code, MONO_ARCH_RGCTX_REG, X86_ECX, offset * sizeof (gpointer), 4);
2212 /* Branch to the target address */
2213 x86_jump_membase (code, X86_ECX, (offset + 1) * sizeof (gpointer));
2215 emit_bytes (acfg, buf, code - buf);
2217 *tramp_size = 15;
2218 g_assert (code - buf == *tramp_size);
2219 #else
2220 g_assert_not_reached ();
2221 #endif
2225 * arch_emit_imt_trampoline:
2227 * Emit an IMT trampoline usable in full-aot mode. The trampoline uses 1 got slot which
2228 * points to an array of pointer pairs. The pairs of the form [key, ptr], where
2229 * key is the IMT key, and ptr holds the address of a memory location holding
2230 * the address to branch to if the IMT arg matches the key. The array is
2231 * terminated by a pair whose key is NULL, and whose ptr is the address of the
2232 * fail_tramp.
2233 * TRAMP_SIZE is set to the size of the emitted trampoline.
2235 static void
2236 arch_emit_imt_trampoline (MonoAotCompile *acfg, int offset, int *tramp_size)
2238 #if defined(TARGET_AMD64)
2239 guint8 *buf, *code;
2240 guint8 *labels [16];
2241 guint8 mov_buf[3];
2242 guint8 *mov_buf_ptr = mov_buf;
2244 const int kSizeOfMove = 7;
2246 code = buf = (guint8 *)g_malloc (256);
2248 /* FIXME: Optimize this, i.e. use binary search etc. */
2249 /* Maybe move the body into a separate function (slower, but much smaller) */
2251 /* MONO_ARCH_IMT_SCRATCH_REG is a free register */
2253 if (acfg->llvm) {
2254 emit_unset_mode (acfg);
2255 fprintf (acfg->fp, "mov %s+%d(%%rip), %s\n", acfg->got_symbol, (int)(offset * sizeof (gpointer)), mono_arch_regname (MONO_ARCH_IMT_SCRATCH_REG));
2258 labels [0] = code;
2259 amd64_alu_membase_imm (code, X86_CMP, MONO_ARCH_IMT_SCRATCH_REG, 0, 0);
2260 labels [1] = code;
2261 amd64_branch8 (code, X86_CC_Z, 0, FALSE);
2263 /* Check key */
2264 amd64_alu_membase_reg_size (code, X86_CMP, MONO_ARCH_IMT_SCRATCH_REG, 0, MONO_ARCH_IMT_REG, sizeof (gpointer));
2265 labels [2] = code;
2266 amd64_branch8 (code, X86_CC_Z, 0, FALSE);
2268 /* Loop footer */
2269 amd64_alu_reg_imm (code, X86_ADD, MONO_ARCH_IMT_SCRATCH_REG, 2 * sizeof (gpointer));
2270 amd64_jump_code (code, labels [0]);
2272 /* Match */
2273 mono_amd64_patch (labels [2], code);
2274 amd64_mov_reg_membase (code, MONO_ARCH_IMT_SCRATCH_REG, MONO_ARCH_IMT_SCRATCH_REG, sizeof (gpointer), sizeof (gpointer));
2275 amd64_jump_membase (code, MONO_ARCH_IMT_SCRATCH_REG, 0);
2277 /* No match */
2278 mono_amd64_patch (labels [1], code);
2279 /* Load fail tramp */
2280 amd64_alu_reg_imm (code, X86_ADD, MONO_ARCH_IMT_SCRATCH_REG, sizeof (gpointer));
2281 /* Check if there is a fail tramp */
2282 amd64_alu_membase_imm (code, X86_CMP, MONO_ARCH_IMT_SCRATCH_REG, 0, 0);
2283 labels [3] = code;
2284 amd64_branch8 (code, X86_CC_Z, 0, FALSE);
2285 /* Jump to fail tramp */
2286 amd64_jump_membase (code, MONO_ARCH_IMT_SCRATCH_REG, 0);
2288 /* Fail */
2289 mono_amd64_patch (labels [3], code);
2290 x86_breakpoint (code);
2292 if (!acfg->llvm) {
2293 /* mov <OFFSET>(%rip), MONO_ARCH_IMT_SCRATCH_REG */
2294 amd64_emit_rex (mov_buf_ptr, sizeof(gpointer), MONO_ARCH_IMT_SCRATCH_REG, 0, AMD64_RIP);
2295 *(mov_buf_ptr)++ = (unsigned char)0x8b; /* mov opcode */
2296 x86_address_byte (mov_buf_ptr, 0, MONO_ARCH_IMT_SCRATCH_REG & 0x7, 5);
2297 emit_bytes (acfg, mov_buf, mov_buf_ptr - mov_buf);
2298 emit_symbol_diff (acfg, acfg->got_symbol, ".", (offset * sizeof (gpointer)) - 4);
2300 emit_bytes (acfg, buf, code - buf);
2302 *tramp_size = code - buf + kSizeOfMove;
2304 g_free (buf);
2306 #elif defined(TARGET_X86)
2307 guint8 *buf, *code;
2308 guint8 *labels [16];
2310 code = buf = g_malloc (256);
2312 /* Allocate a temporary stack slot */
2313 x86_push_reg (code, X86_EAX);
2314 /* Save EAX */
2315 x86_push_reg (code, X86_EAX);
2317 /* Load mscorlib got address */
2318 x86_mov_reg_membase (code, X86_EAX, MONO_ARCH_GOT_REG, sizeof (gpointer), 4);
2319 /* Load arg */
2320 x86_mov_reg_membase (code, X86_EAX, X86_EAX, offset * sizeof (gpointer), 4);
2322 labels [0] = code;
2323 x86_alu_membase_imm (code, X86_CMP, X86_EAX, 0, 0);
2324 labels [1] = code;
2325 x86_branch8 (code, X86_CC_Z, FALSE, 0);
2327 /* Check key */
2328 x86_alu_membase_reg (code, X86_CMP, X86_EAX, 0, MONO_ARCH_IMT_REG);
2329 labels [2] = code;
2330 x86_branch8 (code, X86_CC_Z, FALSE, 0);
2332 /* Loop footer */
2333 x86_alu_reg_imm (code, X86_ADD, X86_EAX, 2 * sizeof (gpointer));
2334 x86_jump_code (code, labels [0]);
2336 /* Match */
2337 mono_x86_patch (labels [2], code);
2338 x86_mov_reg_membase (code, X86_EAX, X86_EAX, sizeof (gpointer), 4);
2339 x86_mov_reg_membase (code, X86_EAX, X86_EAX, 0, 4);
2340 /* Save the target address to the temporary stack location */
2341 x86_mov_membase_reg (code, X86_ESP, 4, X86_EAX, 4);
2342 /* Restore EAX */
2343 x86_pop_reg (code, X86_EAX);
2344 /* Jump to the target address */
2345 x86_ret (code);
2347 /* No match */
2348 mono_x86_patch (labels [1], code);
2349 /* Load fail tramp */
2350 x86_mov_reg_membase (code, X86_EAX, X86_EAX, sizeof (gpointer), 4);
2351 x86_alu_membase_imm (code, X86_CMP, X86_EAX, 0, 0);
2352 labels [3] = code;
2353 x86_branch8 (code, X86_CC_Z, FALSE, 0);
2354 /* Jump to fail tramp */
2355 x86_mov_membase_reg (code, X86_ESP, 4, X86_EAX, 4);
2356 x86_pop_reg (code, X86_EAX);
2357 x86_ret (code);
2359 /* Fail */
2360 mono_x86_patch (labels [3], code);
2361 x86_breakpoint (code);
2363 emit_bytes (acfg, buf, code - buf);
2365 *tramp_size = code - buf;
2367 g_free (buf);
2369 #elif defined(TARGET_ARM)
2370 guint8 buf [128];
2371 guint8 *code, *code2, *labels [16];
2373 code = buf;
2375 /* The IMT method is in v5 */
2377 /* Need at least two free registers, plus a slot for storing the pc */
2378 ARM_PUSH (code, (1 << ARMREG_R0)|(1 << ARMREG_R1)|(1 << ARMREG_R2));
2379 labels [0] = code;
2380 /* Load the parameter from the GOT */
2381 ARM_LDR_IMM (code, ARMREG_R0, ARMREG_PC, 0);
2382 ARM_LDR_REG_REG (code, ARMREG_R0, ARMREG_PC, ARMREG_R0);
2384 labels [1] = code;
2385 ARM_LDR_IMM (code, ARMREG_R1, ARMREG_R0, 0);
2386 ARM_CMP_REG_REG (code, ARMREG_R1, ARMREG_V5);
2387 labels [2] = code;
2388 ARM_B_COND (code, ARMCOND_EQ, 0);
2390 /* End-of-loop check */
2391 ARM_CMP_REG_IMM (code, ARMREG_R1, 0, 0);
2392 labels [3] = code;
2393 ARM_B_COND (code, ARMCOND_EQ, 0);
2395 /* Loop footer */
2396 ARM_ADD_REG_IMM8 (code, ARMREG_R0, ARMREG_R0, sizeof (gpointer) * 2);
2397 labels [4] = code;
2398 ARM_B (code, 0);
2399 arm_patch (labels [4], labels [1]);
2401 /* Match */
2402 arm_patch (labels [2], code);
2403 ARM_LDR_IMM (code, ARMREG_R0, ARMREG_R0, 4);
2404 ARM_LDR_IMM (code, ARMREG_R0, ARMREG_R0, 0);
2405 /* Save it to the third stack slot */
2406 ARM_STR_IMM (code, ARMREG_R0, ARMREG_SP, 8);
2407 /* Restore the registers and branch */
2408 ARM_POP (code, (1 << ARMREG_R0)|(1 << ARMREG_R1)|(1 << ARMREG_PC));
2410 /* No match */
2411 arm_patch (labels [3], code);
2412 ARM_LDR_IMM (code, ARMREG_R0, ARMREG_R0, 4);
2413 ARM_STR_IMM (code, ARMREG_R0, ARMREG_SP, 8);
2414 ARM_POP (code, (1 << ARMREG_R0)|(1 << ARMREG_R1)|(1 << ARMREG_PC));
2416 /* Fixup offset */
2417 code2 = labels [0];
2418 ARM_LDR_IMM (code2, ARMREG_R0, ARMREG_PC, (code - (labels [0] + 8)));
2420 emit_bytes (acfg, buf, code - buf);
2421 emit_symbol_diff (acfg, acfg->got_symbol, ".", (offset * sizeof (gpointer)) + (code - (labels [0] + 8)) - 4);
2423 *tramp_size = code - buf + 4;
2424 #elif defined(TARGET_ARM64)
2425 arm64_emit_imt_trampoline (acfg, offset, tramp_size);
2426 #elif defined(TARGET_POWERPC)
2427 guint8 buf [128];
2428 guint8 *code, *labels [16];
2430 code = buf;
2432 /* Load the mscorlib got address */
2433 ppc_ldptr (code, ppc_r12, sizeof (gpointer), ppc_r30);
2434 /* Load the parameter from the GOT */
2435 ppc_load (code, ppc_r0, offset * sizeof (gpointer));
2436 ppc_ldptr_indexed (code, ppc_r12, ppc_r12, ppc_r0);
2438 /* Load and check key */
2439 labels [1] = code;
2440 ppc_ldptr (code, ppc_r0, 0, ppc_r12);
2441 ppc_cmp (code, 0, sizeof (gpointer) == 8 ? 1 : 0, ppc_r0, MONO_ARCH_IMT_REG);
2442 labels [2] = code;
2443 ppc_bc (code, PPC_BR_TRUE, PPC_BR_EQ, 0);
2445 /* End-of-loop check */
2446 ppc_cmpi (code, 0, sizeof (gpointer) == 8 ? 1 : 0, ppc_r0, 0);
2447 labels [3] = code;
2448 ppc_bc (code, PPC_BR_TRUE, PPC_BR_EQ, 0);
2450 /* Loop footer */
2451 ppc_addi (code, ppc_r12, ppc_r12, 2 * sizeof (gpointer));
2452 labels [4] = code;
2453 ppc_b (code, 0);
2454 mono_ppc_patch (labels [4], labels [1]);
2456 /* Match */
2457 mono_ppc_patch (labels [2], code);
2458 ppc_ldptr (code, ppc_r12, sizeof (gpointer), ppc_r12);
2459 /* r12 now contains the value of the vtable slot */
2460 /* this is not a function descriptor on ppc64 */
2461 ppc_ldptr (code, ppc_r12, 0, ppc_r12);
2462 ppc_mtctr (code, ppc_r12);
2463 ppc_bcctr (code, PPC_BR_ALWAYS, 0);
2465 /* Fail */
2466 mono_ppc_patch (labels [3], code);
2467 /* FIXME: */
2468 ppc_break (code);
2470 *tramp_size = code - buf;
2472 emit_bytes (acfg, buf, code - buf);
2473 #else
2474 g_assert_not_reached ();
2475 #endif
2479 #if defined (TARGET_AMD64)
2481 static void
2482 amd64_emit_load_got_slot (MonoAotCompile *acfg, int dreg, int got_slot)
2485 g_assert (acfg->fp);
2486 emit_unset_mode (acfg);
2488 fprintf (acfg->fp, "mov %s+%d(%%rip), %s\n", acfg->got_symbol, (unsigned int) ((got_slot * sizeof (gpointer))), mono_arch_regname (dreg));
2491 #endif
2495 * arch_emit_gsharedvt_arg_trampoline:
2497 * Emit code for a gsharedvt arg trampoline. OFFSET is the offset of the first of
2498 * two GOT slots which contain the argument, and the code to jump to.
2499 * TRAMP_SIZE is set to the size of the emitted trampoline.
2500 * These kinds of trampolines cannot be enumerated statically, since there could
2501 * be one trampoline per method instantiation, so we emit the same code for all
2502 * trampolines, and parameterize them using two GOT slots.
2504 static void
2505 arch_emit_gsharedvt_arg_trampoline (MonoAotCompile *acfg, int offset, int *tramp_size)
2507 #if defined(TARGET_X86)
2508 guint8 buf [128];
2509 guint8 *code;
2511 /* Similar to the PPC code above */
2513 g_assert (MONO_ARCH_RGCTX_REG != X86_ECX);
2515 code = buf;
2516 /* Load mscorlib got address */
2517 x86_mov_reg_membase (code, X86_ECX, MONO_ARCH_GOT_REG, sizeof (gpointer), 4);
2518 /* Load arg */
2519 x86_mov_reg_membase (code, X86_EAX, X86_ECX, offset * sizeof (gpointer), 4);
2520 /* Branch to the target address */
2521 x86_jump_membase (code, X86_ECX, (offset + 1) * sizeof (gpointer));
2523 emit_bytes (acfg, buf, code - buf);
2525 *tramp_size = 15;
2526 g_assert (code - buf == *tramp_size);
2527 #elif defined(TARGET_ARM)
2528 guint8 buf [128];
2529 guint8 *code;
2531 /* The same as mono_arch_get_gsharedvt_arg_trampoline (), but for AOT */
2532 /* Similar to arch_emit_specific_trampoline () */
2533 *tramp_size = 24;
2534 code = buf;
2535 ARM_PUSH (code, (1 << ARMREG_R0) | (1 << ARMREG_R1) | (1 << ARMREG_R2) | (1 << ARMREG_R3));
2536 ARM_LDR_IMM (code, ARMREG_R1, ARMREG_PC, 8);
2537 /* Load the arg value from the GOT */
2538 ARM_LDR_REG_REG (code, ARMREG_R0, ARMREG_PC, ARMREG_R1);
2539 /* Load the addr from the GOT */
2540 ARM_LDR_REG_REG (code, ARMREG_R1, ARMREG_PC, ARMREG_R1);
2541 /* Branch to it */
2542 ARM_BX (code, ARMREG_R1);
2544 g_assert (code - buf == 20);
2546 /* Emit it */
2547 emit_bytes (acfg, buf, code - buf);
2548 emit_symbol_diff (acfg, acfg->got_symbol, ".", (offset * sizeof (gpointer)) + 4);
2549 #elif defined(TARGET_ARM64)
2550 arm64_emit_gsharedvt_arg_trampoline (acfg, offset, tramp_size);
2551 #elif defined (TARGET_AMD64)
2553 amd64_emit_load_got_slot (acfg, AMD64_RAX, offset);
2554 amd64_emit_load_got_slot (acfg, MONO_ARCH_IMT_SCRATCH_REG, offset + 1);
2555 g_assert (AMD64_R11 == MONO_ARCH_IMT_SCRATCH_REG);
2556 fprintf (acfg->fp, "jmp *%%r11\n");
2558 *tramp_size = 0x11;
2559 #else
2560 g_assert_not_reached ();
2561 #endif
2564 /* END OF ARCH SPECIFIC CODE */
2566 static guint32
2567 mono_get_field_token (MonoClassField *field)
2569 MonoClass *klass = field->parent;
2570 int i;
2572 int fcount = mono_class_get_field_count (klass);
2573 for (i = 0; i < fcount; ++i) {
2574 if (field == &klass->fields [i])
2575 return MONO_TOKEN_FIELD_DEF | (mono_class_get_first_field_idx (klass) + 1 + i);
2578 g_assert_not_reached ();
2579 return 0;
2582 static inline void
2583 encode_value (gint32 value, guint8 *buf, guint8 **endbuf)
2585 guint8 *p = buf;
2587 //printf ("ENCODE: %d 0x%x.\n", value, value);
2590 * Same encoding as the one used in the metadata, extended to handle values
2591 * greater than 0x1fffffff.
2593 if ((value >= 0) && (value <= 127))
2594 *p++ = value;
2595 else if ((value >= 0) && (value <= 16383)) {
2596 p [0] = 0x80 | (value >> 8);
2597 p [1] = value & 0xff;
2598 p += 2;
2599 } else if ((value >= 0) && (value <= 0x1fffffff)) {
2600 p [0] = (value >> 24) | 0xc0;
2601 p [1] = (value >> 16) & 0xff;
2602 p [2] = (value >> 8) & 0xff;
2603 p [3] = value & 0xff;
2604 p += 4;
2606 else {
2607 p [0] = 0xff;
2608 p [1] = (value >> 24) & 0xff;
2609 p [2] = (value >> 16) & 0xff;
2610 p [3] = (value >> 8) & 0xff;
2611 p [4] = value & 0xff;
2612 p += 5;
2614 if (endbuf)
2615 *endbuf = p;
2618 static void
2619 stream_init (MonoDynamicStream *sh)
2621 sh->index = 0;
2622 sh->alloc_size = 4096;
2623 sh->data = (char *)g_malloc (4096);
2625 /* So offsets are > 0 */
2626 sh->data [0] = 0;
2627 sh->index ++;
2630 static void
2631 make_room_in_stream (MonoDynamicStream *stream, int size)
2633 if (size <= stream->alloc_size)
2634 return;
2636 while (stream->alloc_size <= size) {
2637 if (stream->alloc_size < 4096)
2638 stream->alloc_size = 4096;
2639 else
2640 stream->alloc_size *= 2;
2643 stream->data = (char *)g_realloc (stream->data, stream->alloc_size);
2646 static guint32
2647 add_stream_data (MonoDynamicStream *stream, const char *data, guint32 len)
2649 guint32 idx;
2651 make_room_in_stream (stream, stream->index + len);
2652 memcpy (stream->data + stream->index, data, len);
2653 idx = stream->index;
2654 stream->index += len;
2655 return idx;
2659 * add_to_blob:
2661 * Add data to the binary blob inside the aot image. Returns the offset inside the
2662 * blob where the data was stored.
2664 static guint32
2665 add_to_blob (MonoAotCompile *acfg, const guint8 *data, guint32 data_len)
2667 g_assert (!acfg->blob_closed);
2669 if (acfg->blob.alloc_size == 0)
2670 stream_init (&acfg->blob);
2672 return add_stream_data (&acfg->blob, (char*)data, data_len);
2675 static guint32
2676 add_to_blob_aligned (MonoAotCompile *acfg, const guint8 *data, guint32 data_len, guint32 align)
2678 char buf [4] = {0};
2679 guint32 count;
2681 if (acfg->blob.alloc_size == 0)
2682 stream_init (&acfg->blob);
2684 count = acfg->blob.index % align;
2686 /* we assume the stream data will be aligned */
2687 if (count)
2688 add_stream_data (&acfg->blob, buf, 4 - count);
2690 return add_stream_data (&acfg->blob, (char*)data, data_len);
2693 /* Emit a table of data into the aot image */
2694 static void
2695 emit_aot_data (MonoAotCompile *acfg, MonoAotFileTable table, const char *symbol, guint8 *data, int size)
2697 if (acfg->data_outfile) {
2698 acfg->table_offsets [(int)table] = acfg->datafile_offset;
2699 fwrite (data,1, size, acfg->data_outfile);
2700 acfg->datafile_offset += size;
2701 // align the data to 8 bytes. Put zeros in the file (so that every build results in consistent output).
2702 int align = 8 - size % 8;
2703 acfg->datafile_offset += align;
2704 guint8 align_buf [16];
2705 memset (&align_buf, 0, sizeof (align_buf));
2706 fwrite (align_buf, align, 1, acfg->data_outfile);
2707 } else if (acfg->llvm) {
2708 mono_llvm_emit_aot_data (symbol, data, size);
2709 } else {
2710 emit_section_change (acfg, RODATA_SECT, 0);
2711 emit_alignment (acfg, 8);
2712 emit_label (acfg, symbol);
2713 emit_bytes (acfg, data, size);
2718 * emit_offset_table:
2720 * Emit a table of increasing offsets in a compact form using differential encoding.
2721 * There is an index entry for each GROUP_SIZE number of entries. The greater the
2722 * group size, the more compact the table becomes, but the slower it becomes to compute
2723 * a given entry. Returns the size of the table.
2725 static guint32
2726 emit_offset_table (MonoAotCompile *acfg, const char *symbol, MonoAotFileTable table, int noffsets, int group_size, gint32 *offsets)
2728 gint32 current_offset;
2729 int i, buf_size, ngroups, index_entry_size;
2730 guint8 *p, *buf;
2731 guint8 *data_p, *data_buf;
2732 guint32 *index_offsets;
2734 ngroups = (noffsets + (group_size - 1)) / group_size;
2736 index_offsets = g_new0 (guint32, ngroups);
2738 buf_size = noffsets * 4;
2739 p = buf = (guint8 *)g_malloc0 (buf_size);
2741 current_offset = 0;
2742 for (i = 0; i < noffsets; ++i) {
2743 //printf ("D: %d -> %d\n", i, offsets [i]);
2744 if ((i % group_size) == 0) {
2745 index_offsets [i / group_size] = p - buf;
2746 /* Emit the full value for these entries */
2747 encode_value (offsets [i], p, &p);
2748 } else {
2749 /* The offsets are allowed to be non-increasing */
2750 //g_assert (offsets [i] >= current_offset);
2751 encode_value (offsets [i] - current_offset, p, &p);
2753 current_offset = offsets [i];
2755 data_buf = buf;
2756 data_p = p;
2758 if (ngroups && index_offsets [ngroups - 1] < 65000)
2759 index_entry_size = 2;
2760 else
2761 index_entry_size = 4;
2763 buf_size = (data_p - data_buf) + (ngroups * 4) + 16;
2764 p = buf = (guint8 *)g_malloc0 (buf_size);
2766 /* Emit the header */
2767 encode_int (noffsets, p, &p);
2768 encode_int (group_size, p, &p);
2769 encode_int (ngroups, p, &p);
2770 encode_int (index_entry_size, p, &p);
2772 /* Emit the index */
2773 for (i = 0; i < ngroups; ++i) {
2774 if (index_entry_size == 2)
2775 encode_int16 (index_offsets [i], p, &p);
2776 else
2777 encode_int (index_offsets [i], p, &p);
2779 /* Emit the data */
2780 memcpy (p, data_buf, data_p - data_buf);
2781 p += data_p - data_buf;
2783 g_assert (p - buf <= buf_size);
2785 emit_aot_data (acfg, table, symbol, buf, p - buf);
2787 g_free (buf);
2788 g_free (data_buf);
2790 return (int)(p - buf);
2793 static guint32
2794 get_image_index (MonoAotCompile *cfg, MonoImage *image)
2796 guint32 index;
2798 index = GPOINTER_TO_UINT (g_hash_table_lookup (cfg->image_hash, image));
2799 if (index)
2800 return index - 1;
2801 else {
2802 index = g_hash_table_size (cfg->image_hash);
2803 g_hash_table_insert (cfg->image_hash, image, GUINT_TO_POINTER (index + 1));
2804 g_ptr_array_add (cfg->image_table, image);
2805 return index;
2809 static guint32
2810 find_typespec_for_class (MonoAotCompile *acfg, MonoClass *klass)
2812 int i;
2813 int len = acfg->image->tables [MONO_TABLE_TYPESPEC].rows;
2815 /* FIXME: Search referenced images as well */
2816 if (!acfg->typespec_classes) {
2817 acfg->typespec_classes = g_hash_table_new (NULL, NULL);
2818 for (i = 0; i < len; i++) {
2819 MonoError error;
2820 int typespec = MONO_TOKEN_TYPE_SPEC | (i + 1);
2821 MonoClass *klass_key = mono_class_get_and_inflate_typespec_checked (acfg->image, typespec, NULL, &error);
2822 if (!is_ok (&error)) {
2823 mono_error_cleanup (&error);
2824 continue;
2826 g_hash_table_insert (acfg->typespec_classes, klass_key, GINT_TO_POINTER (typespec));
2829 return GPOINTER_TO_INT (g_hash_table_lookup (acfg->typespec_classes, klass));
2832 static void
2833 encode_method_ref (MonoAotCompile *acfg, MonoMethod *method, guint8 *buf, guint8 **endbuf);
2835 static void
2836 encode_klass_ref (MonoAotCompile *acfg, MonoClass *klass, guint8 *buf, guint8 **endbuf);
2838 static void
2839 encode_ginst (MonoAotCompile *acfg, MonoGenericInst *inst, guint8 *buf, guint8 **endbuf);
2841 static void
2842 encode_type (MonoAotCompile *acfg, MonoType *t, guint8 *buf, guint8 **endbuf);
2844 static void
2845 encode_klass_ref_inner (MonoAotCompile *acfg, MonoClass *klass, guint8 *buf, guint8 **endbuf)
2847 guint8 *p = buf;
2850 * The encoding begins with one of the MONO_AOT_TYPEREF values, followed by additional
2851 * information.
2854 if (mono_class_is_ginst (klass)) {
2855 guint32 token;
2856 g_assert (klass->type_token);
2858 /* Find a typespec for a class if possible */
2859 token = find_typespec_for_class (acfg, klass);
2860 if (token) {
2861 encode_value (MONO_AOT_TYPEREF_TYPESPEC_TOKEN, p, &p);
2862 encode_value (token, p, &p);
2863 } else {
2864 MonoClass *gclass = mono_class_get_generic_class (klass)->container_class;
2865 MonoGenericInst *inst = mono_class_get_generic_class (klass)->context.class_inst;
2866 static int count = 0;
2867 guint8 *p1 = p;
2869 encode_value (MONO_AOT_TYPEREF_GINST, p, &p);
2870 encode_klass_ref (acfg, gclass, p, &p);
2871 encode_ginst (acfg, inst, p, &p);
2873 count += p - p1;
2875 } else if (klass->type_token) {
2876 int iindex = get_image_index (acfg, klass->image);
2878 g_assert (mono_metadata_token_code (klass->type_token) == MONO_TOKEN_TYPE_DEF);
2879 if (iindex == 0) {
2880 encode_value (MONO_AOT_TYPEREF_TYPEDEF_INDEX, p, &p);
2881 encode_value (klass->type_token - MONO_TOKEN_TYPE_DEF, p, &p);
2882 } else {
2883 encode_value (MONO_AOT_TYPEREF_TYPEDEF_INDEX_IMAGE, p, &p);
2884 encode_value (klass->type_token - MONO_TOKEN_TYPE_DEF, p, &p);
2885 encode_value (get_image_index (acfg, klass->image), p, &p);
2887 } else if ((klass->byval_arg.type == MONO_TYPE_VAR) || (klass->byval_arg.type == MONO_TYPE_MVAR)) {
2888 MonoGenericContainer *container = mono_type_get_generic_param_owner (&klass->byval_arg);
2889 MonoGenericParam *par = klass->byval_arg.data.generic_param;
2891 encode_value (MONO_AOT_TYPEREF_VAR, p, &p);
2893 encode_value (par->gshared_constraint ? 1 : 0, p, &p);
2894 if (par->gshared_constraint) {
2895 MonoGSharedGenericParam *gpar = (MonoGSharedGenericParam*)par;
2896 encode_type (acfg, par->gshared_constraint, p, &p);
2897 encode_klass_ref (acfg, mono_class_from_generic_parameter (gpar->parent, NULL, klass->byval_arg.type == MONO_TYPE_MVAR), p, &p);
2898 } else {
2899 encode_value (klass->byval_arg.type, p, &p);
2900 encode_value (mono_type_get_generic_param_num (&klass->byval_arg), p, &p);
2902 encode_value (container->is_anonymous ? 0 : 1, p, &p);
2904 if (!container->is_anonymous) {
2905 encode_value (container->is_method, p, &p);
2906 if (container->is_method)
2907 encode_method_ref (acfg, container->owner.method, p, &p);
2908 else
2909 encode_klass_ref (acfg, container->owner.klass, p, &p);
2912 } else if (klass->byval_arg.type == MONO_TYPE_PTR) {
2913 encode_value (MONO_AOT_TYPEREF_PTR, p, &p);
2914 encode_type (acfg, &klass->byval_arg, p, &p);
2915 } else {
2916 /* Array class */
2917 g_assert (klass->rank > 0);
2918 encode_value (MONO_AOT_TYPEREF_ARRAY, p, &p);
2919 encode_value (klass->rank, p, &p);
2920 encode_klass_ref (acfg, klass->element_class, p, &p);
2922 *endbuf = p;
2926 * encode_klass_ref:
2928 * Encode a reference to KLASS. We use our home-grown encoding instead of the
2929 * standard metadata encoding.
2931 static void
2932 encode_klass_ref (MonoAotCompile *acfg, MonoClass *klass, guint8 *buf, guint8 **endbuf)
2934 gboolean shared = FALSE;
2937 * The encoding of generic instances is large so emit them only once.
2939 if (mono_class_is_ginst (klass)) {
2940 guint32 token;
2941 g_assert (klass->type_token);
2943 /* Find a typespec for a class if possible */
2944 token = find_typespec_for_class (acfg, klass);
2945 if (!token)
2946 shared = TRUE;
2947 } else if ((klass->byval_arg.type == MONO_TYPE_VAR) || (klass->byval_arg.type == MONO_TYPE_MVAR)) {
2948 shared = TRUE;
2951 if (shared) {
2952 guint offset = GPOINTER_TO_UINT (g_hash_table_lookup (acfg->klass_blob_hash, klass));
2953 guint8 *buf2, *p;
2955 if (!offset) {
2956 buf2 = (guint8 *)g_malloc (1024);
2957 p = buf2;
2959 encode_klass_ref_inner (acfg, klass, p, &p);
2960 g_assert (p - buf2 < 1024);
2962 offset = add_to_blob (acfg, buf2, p - buf2);
2963 g_free (buf2);
2965 g_hash_table_insert (acfg->klass_blob_hash, klass, GUINT_TO_POINTER (offset + 1));
2966 } else {
2967 offset --;
2970 p = buf;
2971 encode_value (MONO_AOT_TYPEREF_BLOB_INDEX, p, &p);
2972 encode_value (offset, p, &p);
2973 *endbuf = p;
2974 return;
2977 encode_klass_ref_inner (acfg, klass, buf, endbuf);
2980 static void
2981 encode_field_info (MonoAotCompile *cfg, MonoClassField *field, guint8 *buf, guint8 **endbuf)
2983 guint32 token = mono_get_field_token (field);
2984 guint8 *p = buf;
2986 encode_klass_ref (cfg, field->parent, p, &p);
2987 g_assert (mono_metadata_token_code (token) == MONO_TOKEN_FIELD_DEF);
2988 encode_value (token - MONO_TOKEN_FIELD_DEF, p, &p);
2989 *endbuf = p;
2992 static void
2993 encode_ginst (MonoAotCompile *acfg, MonoGenericInst *inst, guint8 *buf, guint8 **endbuf)
2995 guint8 *p = buf;
2996 int i;
2998 encode_value (inst->type_argc, p, &p);
2999 for (i = 0; i < inst->type_argc; ++i)
3000 encode_klass_ref (acfg, mono_class_from_mono_type (inst->type_argv [i]), p, &p);
3001 *endbuf = p;
3004 static void
3005 encode_generic_context (MonoAotCompile *acfg, MonoGenericContext *context, guint8 *buf, guint8 **endbuf)
3007 guint8 *p = buf;
3008 MonoGenericInst *inst;
3010 inst = context->class_inst;
3011 if (inst) {
3012 g_assert (inst->type_argc);
3013 encode_ginst (acfg, inst, p, &p);
3014 } else {
3015 encode_value (0, p, &p);
3017 inst = context->method_inst;
3018 if (inst) {
3019 g_assert (inst->type_argc);
3020 encode_ginst (acfg, inst, p, &p);
3021 } else {
3022 encode_value (0, p, &p);
3024 *endbuf = p;
3027 static void
3028 encode_type (MonoAotCompile *acfg, MonoType *t, guint8 *buf, guint8 **endbuf)
3030 guint8 *p = buf;
3032 g_assert (t->num_mods == 0);
3033 /* t->attrs can be ignored */
3034 //g_assert (t->attrs == 0);
3036 if (t->pinned) {
3037 *p = MONO_TYPE_PINNED;
3038 ++p;
3040 if (t->byref) {
3041 *p = MONO_TYPE_BYREF;
3042 ++p;
3045 *p = t->type;
3046 p ++;
3048 switch (t->type) {
3049 case MONO_TYPE_VOID:
3050 case MONO_TYPE_BOOLEAN:
3051 case MONO_TYPE_CHAR:
3052 case MONO_TYPE_I1:
3053 case MONO_TYPE_U1:
3054 case MONO_TYPE_I2:
3055 case MONO_TYPE_U2:
3056 case MONO_TYPE_I4:
3057 case MONO_TYPE_U4:
3058 case MONO_TYPE_I8:
3059 case MONO_TYPE_U8:
3060 case MONO_TYPE_R4:
3061 case MONO_TYPE_R8:
3062 case MONO_TYPE_I:
3063 case MONO_TYPE_U:
3064 case MONO_TYPE_STRING:
3065 case MONO_TYPE_OBJECT:
3066 case MONO_TYPE_TYPEDBYREF:
3067 break;
3068 case MONO_TYPE_VALUETYPE:
3069 case MONO_TYPE_CLASS:
3070 encode_klass_ref (acfg, mono_class_from_mono_type (t), p, &p);
3071 break;
3072 case MONO_TYPE_SZARRAY:
3073 encode_klass_ref (acfg, t->data.klass, p, &p);
3074 break;
3075 case MONO_TYPE_PTR:
3076 encode_type (acfg, t->data.type, p, &p);
3077 break;
3078 case MONO_TYPE_GENERICINST: {
3079 MonoClass *gclass = t->data.generic_class->container_class;
3080 MonoGenericInst *inst = t->data.generic_class->context.class_inst;
3082 encode_klass_ref (acfg, gclass, p, &p);
3083 encode_ginst (acfg, inst, p, &p);
3084 break;
3086 case MONO_TYPE_ARRAY: {
3087 MonoArrayType *array = t->data.array;
3088 int i;
3090 encode_klass_ref (acfg, array->eklass, p, &p);
3091 encode_value (array->rank, p, &p);
3092 encode_value (array->numsizes, p, &p);
3093 for (i = 0; i < array->numsizes; ++i)
3094 encode_value (array->sizes [i], p, &p);
3095 encode_value (array->numlobounds, p, &p);
3096 for (i = 0; i < array->numlobounds; ++i)
3097 encode_value (array->lobounds [i], p, &p);
3098 break;
3100 case MONO_TYPE_VAR:
3101 case MONO_TYPE_MVAR:
3102 encode_klass_ref (acfg, mono_class_from_mono_type (t), p, &p);
3103 break;
3104 default:
3105 g_assert_not_reached ();
3108 *endbuf = p;
3111 static void
3112 encode_signature (MonoAotCompile *acfg, MonoMethodSignature *sig, guint8 *buf, guint8 **endbuf)
3114 guint8 *p = buf;
3115 guint32 flags = 0;
3116 int i;
3118 /* Similar to the metadata encoding */
3119 if (sig->generic_param_count)
3120 flags |= 0x10;
3121 if (sig->hasthis)
3122 flags |= 0x20;
3123 if (sig->explicit_this)
3124 flags |= 0x40;
3125 flags |= (sig->call_convention & 0x0F);
3127 *p = flags;
3128 ++p;
3129 if (sig->generic_param_count)
3130 encode_value (sig->generic_param_count, p, &p);
3131 encode_value (sig->param_count, p, &p);
3133 encode_type (acfg, sig->ret, p, &p);
3134 for (i = 0; i < sig->param_count; ++i) {
3135 if (sig->sentinelpos == i) {
3136 *p = MONO_TYPE_SENTINEL;
3137 ++p;
3139 encode_type (acfg, sig->params [i], p, &p);
3142 *endbuf = p;
3145 #define MAX_IMAGE_INDEX 250
3147 static void
3148 encode_method_ref (MonoAotCompile *acfg, MonoMethod *method, guint8 *buf, guint8 **endbuf)
3150 guint32 image_index = get_image_index (acfg, method->klass->image);
3151 guint32 token = method->token;
3152 MonoJumpInfoToken *ji;
3153 guint8 *p = buf;
3156 * The encoding for most methods is as follows:
3157 * - image index encoded as a leb128
3158 * - token index encoded as a leb128
3159 * Values of image index >= MONO_AOT_METHODREF_MIN are used to mark additional
3160 * types of method encodings.
3163 /* Mark methods which can't use aot trampolines because they need the further
3164 * processing in mono_magic_trampoline () which requires a MonoMethod*.
3166 if ((method->is_generic && (method->flags & METHOD_ATTRIBUTE_VIRTUAL)) ||
3167 (method->iflags & METHOD_IMPL_ATTRIBUTE_SYNCHRONIZED))
3168 encode_value ((MONO_AOT_METHODREF_NO_AOT_TRAMPOLINE << 24), p, &p);
3170 if (method->wrapper_type) {
3171 WrapperInfo *info = mono_marshal_get_wrapper_info (method);
3173 encode_value ((MONO_AOT_METHODREF_WRAPPER << 24), p, &p);
3175 encode_value (method->wrapper_type, p, &p);
3177 switch (method->wrapper_type) {
3178 case MONO_WRAPPER_REMOTING_INVOKE:
3179 case MONO_WRAPPER_REMOTING_INVOKE_WITH_CHECK:
3180 case MONO_WRAPPER_XDOMAIN_INVOKE: {
3181 MonoMethod *m;
3183 m = mono_marshal_method_from_wrapper (method);
3184 g_assert (m);
3185 encode_method_ref (acfg, m, p, &p);
3186 break;
3188 case MONO_WRAPPER_PROXY_ISINST:
3189 case MONO_WRAPPER_LDFLD:
3190 case MONO_WRAPPER_LDFLDA:
3191 case MONO_WRAPPER_STFLD: {
3192 g_assert (info);
3193 encode_klass_ref (acfg, info->d.proxy.klass, p, &p);
3194 break;
3196 case MONO_WRAPPER_ALLOC: {
3197 /* The GC name is saved once in MonoAotFileInfo */
3198 g_assert (info->d.alloc.alloc_type != -1);
3199 encode_value (info->d.alloc.alloc_type, p, &p);
3200 break;
3202 case MONO_WRAPPER_WRITE_BARRIER: {
3203 g_assert (info);
3204 break;
3206 case MONO_WRAPPER_STELEMREF: {
3207 g_assert (info);
3208 encode_value (info->subtype, p, &p);
3209 if (info->subtype == WRAPPER_SUBTYPE_VIRTUAL_STELEMREF)
3210 encode_value (info->d.virtual_stelemref.kind, p, &p);
3211 break;
3213 case MONO_WRAPPER_UNKNOWN: {
3214 g_assert (info);
3215 encode_value (info->subtype, p, &p);
3216 if (info->subtype == WRAPPER_SUBTYPE_PTR_TO_STRUCTURE ||
3217 info->subtype == WRAPPER_SUBTYPE_STRUCTURE_TO_PTR)
3218 encode_klass_ref (acfg, method->klass, p, &p);
3219 else if (info->subtype == WRAPPER_SUBTYPE_SYNCHRONIZED_INNER)
3220 encode_method_ref (acfg, info->d.synchronized_inner.method, p, &p);
3221 else if (info->subtype == WRAPPER_SUBTYPE_ARRAY_ACCESSOR)
3222 encode_method_ref (acfg, info->d.array_accessor.method, p, &p);
3223 else if (info->subtype == WRAPPER_SUBTYPE_GSHAREDVT_IN_SIG)
3224 encode_signature (acfg, info->d.gsharedvt.sig, p, &p);
3225 else if (info->subtype == WRAPPER_SUBTYPE_GSHAREDVT_OUT_SIG)
3226 encode_signature (acfg, info->d.gsharedvt.sig, p, &p);
3227 break;
3229 case MONO_WRAPPER_MANAGED_TO_NATIVE: {
3230 g_assert (info);
3231 encode_value (info->subtype, p, &p);
3232 if (info->subtype == WRAPPER_SUBTYPE_ICALL_WRAPPER) {
3233 strcpy ((char*)p, method->name);
3234 p += strlen (method->name) + 1;
3235 } else if (info->subtype == WRAPPER_SUBTYPE_NATIVE_FUNC_AOT) {
3236 encode_method_ref (acfg, info->d.managed_to_native.method, p, &p);
3237 } else {
3238 g_assert (info->subtype == WRAPPER_SUBTYPE_NONE || info->subtype == WRAPPER_SUBTYPE_PINVOKE);
3239 encode_method_ref (acfg, info->d.managed_to_native.method, p, &p);
3241 break;
3243 case MONO_WRAPPER_SYNCHRONIZED: {
3244 MonoMethod *m;
3246 m = mono_marshal_method_from_wrapper (method);
3247 g_assert (m);
3248 g_assert (m != method);
3249 encode_method_ref (acfg, m, p, &p);
3250 break;
3252 case MONO_WRAPPER_MANAGED_TO_MANAGED: {
3253 g_assert (info);
3254 encode_value (info->subtype, p, &p);
3256 if (info->subtype == WRAPPER_SUBTYPE_ELEMENT_ADDR) {
3257 encode_value (info->d.element_addr.rank, p, &p);
3258 encode_value (info->d.element_addr.elem_size, p, &p);
3259 } else if (info->subtype == WRAPPER_SUBTYPE_STRING_CTOR) {
3260 encode_method_ref (acfg, info->d.string_ctor.method, p, &p);
3261 } else {
3262 g_assert_not_reached ();
3264 break;
3266 case MONO_WRAPPER_CASTCLASS: {
3267 g_assert (info);
3268 encode_value (info->subtype, p, &p);
3269 break;
3271 case MONO_WRAPPER_RUNTIME_INVOKE: {
3272 g_assert (info);
3273 encode_value (info->subtype, p, &p);
3274 if (info->subtype == WRAPPER_SUBTYPE_RUNTIME_INVOKE_DIRECT || info->subtype == WRAPPER_SUBTYPE_RUNTIME_INVOKE_VIRTUAL)
3275 encode_method_ref (acfg, info->d.runtime_invoke.method, p, &p);
3276 else if (info->subtype == WRAPPER_SUBTYPE_RUNTIME_INVOKE_NORMAL)
3277 encode_signature (acfg, info->d.runtime_invoke.sig, p, &p);
3278 break;
3280 case MONO_WRAPPER_DELEGATE_INVOKE:
3281 case MONO_WRAPPER_DELEGATE_BEGIN_INVOKE:
3282 case MONO_WRAPPER_DELEGATE_END_INVOKE: {
3283 if (method->is_inflated) {
3284 /* These wrappers are identified by their class */
3285 encode_value (1, p, &p);
3286 encode_klass_ref (acfg, method->klass, p, &p);
3287 } else {
3288 MonoMethodSignature *sig = mono_method_signature (method);
3289 WrapperInfo *info = mono_marshal_get_wrapper_info (method);
3291 encode_value (0, p, &p);
3292 if (method->wrapper_type == MONO_WRAPPER_DELEGATE_INVOKE)
3293 encode_value (info ? info->subtype : 0, p, &p);
3294 encode_signature (acfg, sig, p, &p);
3296 break;
3298 case MONO_WRAPPER_NATIVE_TO_MANAGED: {
3299 g_assert (info);
3300 encode_method_ref (acfg, info->d.native_to_managed.method, p, &p);
3301 encode_klass_ref (acfg, info->d.native_to_managed.klass, p, &p);
3302 break;
3304 default:
3305 g_assert_not_reached ();
3307 } else if (mono_method_signature (method)->is_inflated) {
3309 * This is a generic method, find the original token which referenced it and
3310 * encode that.
3311 * Obtain the token from information recorded by the JIT.
3313 ji = (MonoJumpInfoToken *)g_hash_table_lookup (acfg->token_info_hash, method);
3314 if (ji) {
3315 image_index = get_image_index (acfg, ji->image);
3316 g_assert (image_index < MAX_IMAGE_INDEX);
3317 token = ji->token;
3319 encode_value ((MONO_AOT_METHODREF_METHODSPEC << 24), p, &p);
3320 encode_value (image_index, p, &p);
3321 encode_value (token, p, &p);
3322 } else {
3323 MonoMethod *declaring;
3324 MonoGenericContext *context = mono_method_get_context (method);
3326 g_assert (method->is_inflated);
3327 declaring = ((MonoMethodInflated*)method)->declaring;
3330 * This might be a non-generic method of a generic instance, which
3331 * doesn't have a token since the reference is generated by the JIT
3332 * like Nullable:Box/Unbox, or by generic sharing.
3334 encode_value ((MONO_AOT_METHODREF_GINST << 24), p, &p);
3335 /* Encode the klass */
3336 encode_klass_ref (acfg, method->klass, p, &p);
3337 /* Encode the method */
3338 image_index = get_image_index (acfg, method->klass->image);
3339 g_assert (image_index < MAX_IMAGE_INDEX);
3340 g_assert (declaring->token);
3341 token = declaring->token;
3342 g_assert (mono_metadata_token_table (token) == MONO_TABLE_METHOD);
3343 encode_value (image_index, p, &p);
3344 encode_value (token, p, &p);
3345 encode_generic_context (acfg, context, p, &p);
3347 } else if (token == 0) {
3348 /* This might be a method of a constructed type like int[,].Set */
3349 /* Obtain the token from information recorded by the JIT */
3350 ji = (MonoJumpInfoToken *)g_hash_table_lookup (acfg->token_info_hash, method);
3351 if (ji) {
3352 image_index = get_image_index (acfg, ji->image);
3353 g_assert (image_index < MAX_IMAGE_INDEX);
3354 token = ji->token;
3356 encode_value ((MONO_AOT_METHODREF_METHODSPEC << 24), p, &p);
3357 encode_value (image_index, p, &p);
3358 encode_value (token, p, &p);
3359 } else {
3360 /* Array methods */
3361 g_assert (method->klass->rank);
3363 /* Encode directly */
3364 encode_value ((MONO_AOT_METHODREF_ARRAY << 24), p, &p);
3365 encode_klass_ref (acfg, method->klass, p, &p);
3366 if (!strcmp (method->name, ".ctor") && mono_method_signature (method)->param_count == method->klass->rank)
3367 encode_value (0, p, &p);
3368 else if (!strcmp (method->name, ".ctor") && mono_method_signature (method)->param_count == method->klass->rank * 2)
3369 encode_value (1, p, &p);
3370 else if (!strcmp (method->name, "Get"))
3371 encode_value (2, p, &p);
3372 else if (!strcmp (method->name, "Address"))
3373 encode_value (3, p, &p);
3374 else if (!strcmp (method->name, "Set"))
3375 encode_value (4, p, &p);
3376 else
3377 g_assert_not_reached ();
3379 } else {
3380 g_assert (mono_metadata_token_table (token) == MONO_TABLE_METHOD);
3382 if (image_index >= MONO_AOT_METHODREF_MIN) {
3383 encode_value ((MONO_AOT_METHODREF_LARGE_IMAGE_INDEX << 24), p, &p);
3384 encode_value (image_index, p, &p);
3385 encode_value (mono_metadata_token_index (token), p, &p);
3386 } else {
3387 encode_value ((image_index << 24) | mono_metadata_token_index (token), p, &p);
3390 *endbuf = p;
3393 static gint
3394 compare_patches (gconstpointer a, gconstpointer b)
3396 int i, j;
3398 i = (*(MonoJumpInfo**)a)->ip.i;
3399 j = (*(MonoJumpInfo**)b)->ip.i;
3401 if (i < j)
3402 return -1;
3403 else
3404 if (i > j)
3405 return 1;
3406 else
3407 return 0;
3410 static G_GNUC_UNUSED char*
3411 patch_to_string (MonoJumpInfo *patch_info)
3413 GString *str;
3415 str = g_string_new ("");
3417 g_string_append_printf (str, "%s(", get_patch_name (patch_info->type));
3419 switch (patch_info->type) {
3420 case MONO_PATCH_INFO_VTABLE:
3421 mono_type_get_desc (str, &patch_info->data.klass->byval_arg, TRUE);
3422 break;
3423 default:
3424 break;
3426 g_string_append_printf (str, ")");
3427 return g_string_free (str, FALSE);
3431 * is_plt_patch:
3433 * Return whenever PATCH_INFO refers to a direct call, and thus requires a
3434 * PLT entry.
3436 static inline gboolean
3437 is_plt_patch (MonoJumpInfo *patch_info)
3439 switch (patch_info->type) {
3440 case MONO_PATCH_INFO_METHOD:
3441 case MONO_PATCH_INFO_INTERNAL_METHOD:
3442 case MONO_PATCH_INFO_JIT_ICALL_ADDR:
3443 case MONO_PATCH_INFO_ICALL_ADDR_CALL:
3444 case MONO_PATCH_INFO_RGCTX_FETCH:
3445 return TRUE;
3446 default:
3447 return FALSE;
3452 * get_plt_symbol:
3454 * Return the symbol identifying the plt entry PLT_OFFSET.
3456 static char*
3457 get_plt_symbol (MonoAotCompile *acfg, int plt_offset, MonoJumpInfo *patch_info)
3459 #ifdef TARGET_MACH
3461 * The Apple linker reorganizes object files, so it doesn't like branches to local
3462 * labels, since those have no relocations.
3464 return g_strdup_printf ("%sp_%d", acfg->llvm_label_prefix, plt_offset);
3465 #else
3466 return g_strdup_printf ("%sp_%d", acfg->temp_prefix, plt_offset);
3467 #endif
3471 * get_plt_entry:
3473 * Return a PLT entry which belongs to the method identified by PATCH_INFO.
3475 static MonoPltEntry*
3476 get_plt_entry (MonoAotCompile *acfg, MonoJumpInfo *patch_info)
3478 MonoPltEntry *res;
3479 gboolean synchronized = FALSE;
3480 static int synchronized_symbol_idx;
3482 if (!is_plt_patch (patch_info))
3483 return NULL;
3485 if (!acfg->patch_to_plt_entry [patch_info->type])
3486 acfg->patch_to_plt_entry [patch_info->type] = g_hash_table_new (mono_patch_info_hash, mono_patch_info_equal);
3487 res = (MonoPltEntry *)g_hash_table_lookup (acfg->patch_to_plt_entry [patch_info->type], patch_info);
3489 if (!acfg->llvm && patch_info->type == MONO_PATCH_INFO_METHOD && (patch_info->data.method->iflags & METHOD_IMPL_ATTRIBUTE_SYNCHRONIZED)) {
3491 * Allocate a separate PLT slot for each such patch, since some plt
3492 * entries will refer to the method itself, and some will refer to the
3493 * wrapper.
3495 res = NULL;
3496 synchronized = TRUE;
3499 if (!res) {
3500 MonoJumpInfo *new_ji;
3502 new_ji = mono_patch_info_dup_mp (acfg->mempool, patch_info);
3504 res = (MonoPltEntry *)mono_mempool_alloc0 (acfg->mempool, sizeof (MonoPltEntry));
3505 res->plt_offset = acfg->plt_offset;
3506 res->ji = new_ji;
3507 res->symbol = get_plt_symbol (acfg, res->plt_offset, patch_info);
3508 if (acfg->aot_opts.write_symbols)
3509 res->debug_sym = get_plt_entry_debug_sym (acfg, res->ji, acfg->plt_entry_debug_sym_cache);
3510 if (synchronized) {
3511 /* Avoid duplicate symbols because we don't cache */
3512 res->symbol = g_strdup_printf ("%s_%d", res->symbol, synchronized_symbol_idx);
3513 if (res->debug_sym)
3514 res->debug_sym = g_strdup_printf ("%s_%d", res->debug_sym, synchronized_symbol_idx);
3515 synchronized_symbol_idx ++;
3517 if (res->debug_sym)
3518 res->llvm_symbol = g_strdup_printf ("%s_%s_llvm", res->symbol, res->debug_sym);
3519 else
3520 res->llvm_symbol = g_strdup_printf ("%s_llvm", res->symbol);
3522 g_hash_table_insert (acfg->patch_to_plt_entry [new_ji->type], new_ji, res);
3524 g_hash_table_insert (acfg->plt_offset_to_entry, GUINT_TO_POINTER (res->plt_offset), res);
3526 //g_assert (mono_patch_info_equal (patch_info, new_ji));
3527 //mono_print_ji (patch_info); printf ("\n");
3528 //g_hash_table_print_stats (acfg->patch_to_plt_entry);
3530 acfg->plt_offset ++;
3533 return res;
3537 * get_got_offset:
3539 * Returns the offset of the GOT slot where the runtime object resulting from resolving
3540 * JI could be found if it exists, otherwise allocates a new one.
3542 static guint32
3543 get_got_offset (MonoAotCompile *acfg, gboolean llvm, MonoJumpInfo *ji)
3545 guint32 got_offset;
3546 GotInfo *info = llvm ? &acfg->llvm_got_info : &acfg->got_info;
3548 got_offset = GPOINTER_TO_UINT (g_hash_table_lookup (info->patch_to_got_offset_by_type [ji->type], ji));
3549 if (got_offset)
3550 return got_offset - 1;
3552 if (llvm) {
3553 got_offset = acfg->llvm_got_offset;
3554 acfg->llvm_got_offset ++;
3555 } else {
3556 got_offset = acfg->got_offset;
3557 acfg->got_offset ++;
3560 acfg->stats.got_slots ++;
3561 acfg->stats.got_slot_types [ji->type] ++;
3563 g_hash_table_insert (info->patch_to_got_offset, ji, GUINT_TO_POINTER (got_offset + 1));
3564 g_hash_table_insert (info->patch_to_got_offset_by_type [ji->type], ji, GUINT_TO_POINTER (got_offset + 1));
3565 g_ptr_array_add (info->got_patches, ji);
3567 return got_offset;
3570 /* Add a method to the list of methods which need to be emitted */
3571 static void
3572 add_method_with_index (MonoAotCompile *acfg, MonoMethod *method, int index, gboolean extra)
3574 g_assert (method);
3575 if (!g_hash_table_lookup (acfg->method_indexes, method)) {
3576 g_ptr_array_add (acfg->methods, method);
3577 g_hash_table_insert (acfg->method_indexes, method, GUINT_TO_POINTER (index + 1));
3578 acfg->nmethods = acfg->methods->len + 1;
3581 if (method->wrapper_type || extra)
3582 g_ptr_array_add (acfg->extra_methods, method);
3585 static gboolean
3586 prefer_gsharedvt_method (MonoAotCompile *acfg, MonoMethod *method)
3588 /* One instantiation with valuetypes is generated for each async method */
3589 if (method->klass->image == mono_defaults.corlib && (!strcmp (method->klass->name, "AsyncMethodBuilderCore") || !strcmp (method->klass->name, "AsyncVoidMethodBuilder")))
3590 return TRUE;
3591 else
3592 return FALSE;
3595 static guint32
3596 get_method_index (MonoAotCompile *acfg, MonoMethod *method)
3598 int index = GPOINTER_TO_UINT (g_hash_table_lookup (acfg->method_indexes, method));
3600 g_assert (index);
3602 return index - 1;
3605 static int
3606 add_method_full (MonoAotCompile *acfg, MonoMethod *method, gboolean extra, int depth)
3608 int index;
3610 index = GPOINTER_TO_UINT (g_hash_table_lookup (acfg->method_indexes, method));
3611 if (index)
3612 return index - 1;
3614 index = acfg->method_index;
3615 add_method_with_index (acfg, method, index, extra);
3617 g_ptr_array_add (acfg->method_order, GUINT_TO_POINTER (index));
3619 g_hash_table_insert (acfg->method_depth, method, GUINT_TO_POINTER (depth));
3621 acfg->method_index ++;
3623 return index;
3626 static int
3627 add_method (MonoAotCompile *acfg, MonoMethod *method)
3629 return add_method_full (acfg, method, FALSE, 0);
3632 static void
3633 add_extra_method_with_depth (MonoAotCompile *acfg, MonoMethod *method, int depth)
3635 if (mono_method_is_generic_sharable_full (method, TRUE, TRUE, FALSE))
3636 method = mini_get_shared_method (method);
3637 else if ((acfg->opts & MONO_OPT_GSHAREDVT) && prefer_gsharedvt_method (acfg, method) && mono_method_is_generic_sharable_full (method, FALSE, FALSE, TRUE))
3638 /* Use the gsharedvt version */
3639 method = mini_get_shared_method_full (method, TRUE, TRUE);
3641 if (acfg->aot_opts.log_generics)
3642 aot_printf (acfg, "%*sAdding method %s.\n", depth, "", mono_method_get_full_name (method));
3644 add_method_full (acfg, method, TRUE, depth);
3647 static void
3648 add_extra_method (MonoAotCompile *acfg, MonoMethod *method)
3650 add_extra_method_with_depth (acfg, method, 0);
3653 static void
3654 add_jit_icall_wrapper (gpointer key, gpointer value, gpointer user_data)
3656 MonoAotCompile *acfg = (MonoAotCompile *)user_data;
3657 MonoJitICallInfo *callinfo = (MonoJitICallInfo *)value;
3658 MonoMethod *wrapper;
3659 char *name;
3661 if (!callinfo->sig)
3662 return;
3664 name = g_strdup_printf ("__icall_wrapper_%s", callinfo->name);
3665 wrapper = mono_marshal_get_icall_wrapper (callinfo->sig, name, callinfo->func, TRUE);
3666 g_free (name);
3668 add_method (acfg, wrapper);
3671 static MonoMethod*
3672 get_runtime_invoke_sig (MonoMethodSignature *sig)
3674 MonoMethodBuilder *mb;
3675 MonoMethod *m;
3677 mb = mono_mb_new (mono_defaults.object_class, "FOO", MONO_WRAPPER_NONE);
3678 m = mono_mb_create_method (mb, sig, 16);
3679 MonoMethod *invoke = mono_marshal_get_runtime_invoke (m, FALSE);
3680 mono_mb_free (mb);
3681 return invoke;
3684 static MonoMethod*
3685 get_runtime_invoke (MonoAotCompile *acfg, MonoMethod *method, gboolean virtual_)
3687 return mono_marshal_get_runtime_invoke (method, virtual_);
3690 static gboolean
3691 can_marshal_struct (MonoClass *klass)
3693 MonoClassField *field;
3694 gboolean can_marshal = TRUE;
3695 gpointer iter = NULL;
3696 MonoMarshalType *info;
3697 int i;
3699 if (mono_class_is_auto_layout (klass))
3700 return FALSE;
3702 info = mono_marshal_load_type_info (klass);
3704 /* Only allow a few field types to avoid asserts in the marshalling code */
3705 while ((field = mono_class_get_fields (klass, &iter))) {
3706 if ((field->type->attrs & FIELD_ATTRIBUTE_STATIC))
3707 continue;
3709 switch (field->type->type) {
3710 case MONO_TYPE_I4:
3711 case MONO_TYPE_U4:
3712 case MONO_TYPE_I1:
3713 case MONO_TYPE_U1:
3714 case MONO_TYPE_BOOLEAN:
3715 case MONO_TYPE_I2:
3716 case MONO_TYPE_U2:
3717 case MONO_TYPE_CHAR:
3718 case MONO_TYPE_I8:
3719 case MONO_TYPE_U8:
3720 case MONO_TYPE_I:
3721 case MONO_TYPE_U:
3722 case MONO_TYPE_PTR:
3723 case MONO_TYPE_R4:
3724 case MONO_TYPE_R8:
3725 case MONO_TYPE_STRING:
3726 break;
3727 case MONO_TYPE_VALUETYPE:
3728 if (!mono_class_from_mono_type (field->type)->enumtype && !can_marshal_struct (mono_class_from_mono_type (field->type)))
3729 can_marshal = FALSE;
3730 break;
3731 case MONO_TYPE_SZARRAY: {
3732 gboolean has_mspec = FALSE;
3734 if (info) {
3735 for (i = 0; i < info->num_fields; ++i) {
3736 if (info->fields [i].field == field && info->fields [i].mspec)
3737 has_mspec = TRUE;
3740 if (!has_mspec)
3741 can_marshal = FALSE;
3742 break;
3744 default:
3745 can_marshal = FALSE;
3746 break;
3750 /* Special cases */
3751 /* Its hard to compute whenever these can be marshalled or not */
3752 if (!strcmp (klass->name_space, "System.Net.NetworkInformation.MacOsStructs") && strcmp (klass->name, "sockaddr_dl"))
3753 return TRUE;
3755 return can_marshal;
3758 static void
3759 create_gsharedvt_inst (MonoAotCompile *acfg, MonoMethod *method, MonoGenericContext *ctx)
3761 /* Create a vtype instantiation */
3762 MonoGenericContext shared_context;
3763 MonoType **args;
3764 MonoGenericInst *inst;
3765 MonoGenericContainer *container;
3766 MonoClass **constraints;
3767 int i;
3769 memset (ctx, 0, sizeof (MonoGenericContext));
3771 if (mono_class_is_gtd (method->klass)) {
3772 shared_context = mono_class_get_generic_container (method->klass)->context;
3773 inst = shared_context.class_inst;
3775 args = g_new0 (MonoType*, inst->type_argc);
3776 for (i = 0; i < inst->type_argc; ++i) {
3777 args [i] = &mono_defaults.int_class->byval_arg;
3779 ctx->class_inst = mono_metadata_get_generic_inst (inst->type_argc, args);
3781 if (method->is_generic) {
3782 container = mono_method_get_generic_container (method);
3783 shared_context = container->context;
3784 inst = shared_context.method_inst;
3786 args = g_new0 (MonoType*, inst->type_argc);
3787 for (i = 0; i < container->type_argc; ++i) {
3788 MonoGenericParamInfo *info = &container->type_params [i].info;
3789 gboolean ref_only = FALSE;
3791 if (info && info->constraints) {
3792 constraints = info->constraints;
3794 while (*constraints) {
3795 MonoClass *cklass = *constraints;
3796 if (!(cklass == mono_defaults.object_class || (cklass->image == mono_defaults.corlib && !strcmp (cklass->name, "ValueType"))))
3797 /* Inflaring the method with our vtype would not be valid */
3798 ref_only = TRUE;
3799 constraints ++;
3803 if (ref_only)
3804 args [i] = &mono_defaults.object_class->byval_arg;
3805 else
3806 args [i] = &mono_defaults.int_class->byval_arg;
3808 ctx->method_inst = mono_metadata_get_generic_inst (inst->type_argc, args);
3812 static void
3813 add_wrappers (MonoAotCompile *acfg)
3815 MonoMethod *method, *m;
3816 int i, j;
3817 MonoMethodSignature *sig, *csig;
3818 guint32 token;
3821 * FIXME: Instead of AOTing all the wrappers, it might be better to redesign them
3822 * so there is only one wrapper of a given type, or inlining their contents into their
3823 * callers.
3825 for (i = 0; i < acfg->image->tables [MONO_TABLE_METHOD].rows; ++i) {
3826 MonoError error;
3827 MonoMethod *method;
3828 guint32 token = MONO_TOKEN_METHOD_DEF | (i + 1);
3829 gboolean skip = FALSE;
3831 method = mono_get_method_checked (acfg->image, token, NULL, NULL, &error);
3832 report_loader_error (acfg, &error, "Failed to load method token 0x%x due to %s\n", i, mono_error_get_message (&error));
3834 if ((method->flags & METHOD_ATTRIBUTE_PINVOKE_IMPL) ||
3835 (method->iflags & METHOD_IMPL_ATTRIBUTE_RUNTIME) ||
3836 (method->flags & METHOD_ATTRIBUTE_ABSTRACT))
3837 skip = TRUE;
3839 /* Skip methods which can not be handled by get_runtime_invoke () */
3840 sig = mono_method_signature (method);
3841 if (!sig)
3842 continue;
3843 if ((sig->ret->type == MONO_TYPE_PTR) ||
3844 (sig->ret->type == MONO_TYPE_TYPEDBYREF))
3845 skip = TRUE;
3846 if (mono_class_is_open_constructed_type (sig->ret))
3847 skip = TRUE;
3849 for (j = 0; j < sig->param_count; j++) {
3850 if (sig->params [j]->type == MONO_TYPE_TYPEDBYREF)
3851 skip = TRUE;
3852 if (mono_class_is_open_constructed_type (sig->params [j]))
3853 skip = TRUE;
3856 #ifdef MONO_ARCH_DYN_CALL_SUPPORTED
3857 if (!mono_class_is_contextbound (method->klass)) {
3858 MonoDynCallInfo *info = mono_arch_dyn_call_prepare (sig);
3859 gboolean has_nullable = FALSE;
3861 for (j = 0; j < sig->param_count; j++) {
3862 if (sig->params [j]->type == MONO_TYPE_GENERICINST && mono_class_is_nullable (mono_class_from_mono_type (sig->params [j])))
3863 has_nullable = TRUE;
3866 if (info && !has_nullable && !acfg->aot_opts.llvm_only) {
3867 /* Supported by the dynamic runtime-invoke wrapper */
3868 skip = TRUE;
3870 if (info)
3871 mono_arch_dyn_call_free (info);
3873 #endif
3875 if (acfg->aot_opts.llvm_only)
3876 /* Supported by the gsharedvt based runtime-invoke wrapper */
3877 skip = TRUE;
3879 if (!skip) {
3880 //printf ("%s\n", mono_method_full_name (method, TRUE));
3881 add_method (acfg, get_runtime_invoke (acfg, method, FALSE));
3885 if (strcmp (acfg->image->assembly->aname.name, "mscorlib") == 0) {
3886 int nallocators;
3888 /* Runtime invoke wrappers */
3890 /* void runtime-invoke () [.cctor] */
3891 csig = mono_metadata_signature_alloc (mono_defaults.corlib, 0);
3892 csig->ret = &mono_defaults.void_class->byval_arg;
3893 add_method (acfg, get_runtime_invoke_sig (csig));
3895 /* void runtime-invoke () [Finalize] */
3896 csig = mono_metadata_signature_alloc (mono_defaults.corlib, 0);
3897 csig->hasthis = 1;
3898 csig->ret = &mono_defaults.void_class->byval_arg;
3899 add_method (acfg, get_runtime_invoke_sig (csig));
3901 /* void runtime-invoke (string) [exception ctor] */
3902 csig = mono_metadata_signature_alloc (mono_defaults.corlib, 1);
3903 csig->hasthis = 1;
3904 csig->ret = &mono_defaults.void_class->byval_arg;
3905 csig->params [0] = &mono_defaults.string_class->byval_arg;
3906 add_method (acfg, get_runtime_invoke_sig (csig));
3908 /* void runtime-invoke (string, string) [exception ctor] */
3909 csig = mono_metadata_signature_alloc (mono_defaults.corlib, 2);
3910 csig->hasthis = 1;
3911 csig->ret = &mono_defaults.void_class->byval_arg;
3912 csig->params [0] = &mono_defaults.string_class->byval_arg;
3913 csig->params [1] = &mono_defaults.string_class->byval_arg;
3914 add_method (acfg, get_runtime_invoke_sig (csig));
3916 /* string runtime-invoke () [Exception.ToString ()] */
3917 csig = mono_metadata_signature_alloc (mono_defaults.corlib, 0);
3918 csig->hasthis = 1;
3919 csig->ret = &mono_defaults.string_class->byval_arg;
3920 add_method (acfg, get_runtime_invoke_sig (csig));
3922 /* void runtime-invoke (string, Exception) [exception ctor] */
3923 csig = mono_metadata_signature_alloc (mono_defaults.corlib, 2);
3924 csig->hasthis = 1;
3925 csig->ret = &mono_defaults.void_class->byval_arg;
3926 csig->params [0] = &mono_defaults.string_class->byval_arg;
3927 csig->params [1] = &mono_defaults.exception_class->byval_arg;
3928 add_method (acfg, get_runtime_invoke_sig (csig));
3930 /* Assembly runtime-invoke (string, Assembly, bool) [DoAssemblyResolve] */
3931 csig = mono_metadata_signature_alloc (mono_defaults.corlib, 3);
3932 csig->hasthis = 1;
3933 csig->ret = &(mono_class_load_from_name (
3934 mono_defaults.corlib, "System.Reflection", "Assembly"))->byval_arg;
3935 csig->params [0] = &mono_defaults.string_class->byval_arg;
3936 csig->params [1] = &(mono_class_load_from_name (mono_defaults.corlib, "System.Reflection", "Assembly"))->byval_arg;
3937 csig->params [2] = &mono_defaults.boolean_class->byval_arg;
3938 add_method (acfg, get_runtime_invoke_sig (csig));
3940 /* runtime-invoke used by finalizers */
3941 add_method (acfg, get_runtime_invoke (acfg, mono_class_get_method_from_name_flags (mono_defaults.object_class, "Finalize", 0, 0), TRUE));
3943 /* This is used by mono_runtime_capture_context () */
3944 method = mono_get_context_capture_method ();
3945 if (method)
3946 add_method (acfg, get_runtime_invoke (acfg, method, FALSE));
3948 #ifdef MONO_ARCH_DYN_CALL_SUPPORTED
3949 if (!acfg->aot_opts.llvm_only)
3950 add_method (acfg, mono_marshal_get_runtime_invoke_dynamic ());
3951 #endif
3953 /* These are used by mono_jit_runtime_invoke () to calls gsharedvt out wrappers */
3954 if (acfg->aot_opts.llvm_only) {
3955 int variants;
3957 /* Create simplified signatures which match the signature used by the gsharedvt out wrappers */
3958 for (variants = 0; variants < 4; ++variants) {
3959 for (i = 0; i < 16; ++i) {
3960 sig = mini_get_gsharedvt_out_sig_wrapper_signature ((variants & 1) > 0, (variants & 2) > 0, i);
3961 add_extra_method (acfg, mono_marshal_get_runtime_invoke_for_sig (sig));
3963 g_free (sig);
3968 /* stelemref */
3969 add_method (acfg, mono_marshal_get_stelemref ());
3971 /* Managed Allocators */
3972 nallocators = mono_gc_get_managed_allocator_types ();
3973 for (i = 0; i < nallocators; ++i) {
3974 if ((m = mono_gc_get_managed_allocator_by_type (i, MANAGED_ALLOCATOR_REGULAR)))
3975 add_method (acfg, m);
3976 if ((m = mono_gc_get_managed_allocator_by_type (i, MANAGED_ALLOCATOR_SLOW_PATH)))
3977 add_method (acfg, m);
3980 /* write barriers */
3981 if (mono_gc_is_moving ()) {
3982 add_method (acfg, mono_gc_get_specific_write_barrier (FALSE));
3983 add_method (acfg, mono_gc_get_specific_write_barrier (TRUE));
3986 /* Stelemref wrappers */
3988 MonoMethod **wrappers;
3989 int nwrappers;
3991 wrappers = mono_marshal_get_virtual_stelemref_wrappers (&nwrappers);
3992 for (i = 0; i < nwrappers; ++i)
3993 add_method (acfg, wrappers [i]);
3994 g_free (wrappers);
3997 /* castclass_with_check wrapper */
3998 add_method (acfg, mono_marshal_get_castclass_with_cache ());
3999 /* isinst_with_check wrapper */
4000 add_method (acfg, mono_marshal_get_isinst_with_cache ());
4002 /* JIT icall wrappers */
4003 /* FIXME: locking - this is "safe" as full-AOT threads don't mutate the icall hash*/
4004 g_hash_table_foreach (mono_get_jit_icall_info (), add_jit_icall_wrapper, acfg);
4008 * remoting-invoke-with-check wrappers are very frequent, so avoid emitting them,
4009 * we use the original method instead at runtime.
4010 * Since full-aot doesn't support remoting, this is not a problem.
4012 #if 0
4013 /* remoting-invoke wrappers */
4014 for (i = 0; i < acfg->image->tables [MONO_TABLE_METHOD].rows; ++i) {
4015 MonoError error;
4016 MonoMethodSignature *sig;
4018 token = MONO_TOKEN_METHOD_DEF | (i + 1);
4019 method = mono_get_method_checked (acfg->image, token, NULL, NULL, &error);
4020 g_assert (mono_error_ok (&error)); /* FIXME don't swallow the error */
4022 sig = mono_method_signature (method);
4024 if (sig->hasthis && (method->klass->marshalbyref || method->klass == mono_defaults.object_class)) {
4025 m = mono_marshal_get_remoting_invoke_with_check (method);
4027 add_method (acfg, m);
4030 #endif
4032 /* delegate-invoke wrappers */
4033 for (i = 0; i < acfg->image->tables [MONO_TABLE_TYPEDEF].rows; ++i) {
4034 MonoError error;
4035 MonoClass *klass;
4036 MonoCustomAttrInfo *cattr;
4038 token = MONO_TOKEN_TYPE_DEF | (i + 1);
4039 klass = mono_class_get_checked (acfg->image, token, &error);
4041 if (!klass) {
4042 mono_error_cleanup (&error);
4043 continue;
4046 if (!klass->delegate || klass == mono_defaults.delegate_class || klass == mono_defaults.multicastdelegate_class)
4047 continue;
4049 if (!mono_class_is_gtd (klass)) {
4050 method = mono_get_delegate_invoke (klass);
4052 m = mono_marshal_get_delegate_invoke (method, NULL);
4054 add_method (acfg, m);
4056 method = mono_class_get_method_from_name_flags (klass, "BeginInvoke", -1, 0);
4057 if (method)
4058 add_method (acfg, mono_marshal_get_delegate_begin_invoke (method));
4060 method = mono_class_get_method_from_name_flags (klass, "EndInvoke", -1, 0);
4061 if (method)
4062 add_method (acfg, mono_marshal_get_delegate_end_invoke (method));
4064 cattr = mono_custom_attrs_from_class_checked (klass, &error);
4065 if (!is_ok (&error)) {
4066 mono_error_cleanup (&error);
4067 continue;
4070 if (cattr) {
4071 int j;
4073 for (j = 0; j < cattr->num_attrs; ++j)
4074 if (cattr->attrs [j].ctor && (!strcmp (cattr->attrs [j].ctor->klass->name, "MonoNativeFunctionWrapperAttribute") || !strcmp (cattr->attrs [j].ctor->klass->name, "UnmanagedFunctionPointerAttribute")))
4075 break;
4076 if (j < cattr->num_attrs) {
4077 MonoMethod *invoke;
4078 MonoMethod *wrapper;
4079 MonoMethod *del_invoke;
4081 /* Add wrappers needed by mono_ftnptr_to_delegate () */
4082 invoke = mono_get_delegate_invoke (klass);
4083 wrapper = mono_marshal_get_native_func_wrapper_aot (klass);
4084 del_invoke = mono_marshal_get_delegate_invoke_internal (invoke, FALSE, TRUE, wrapper);
4085 add_method (acfg, wrapper);
4086 add_method (acfg, del_invoke);
4089 } else if ((acfg->opts & MONO_OPT_GSHAREDVT) && mono_class_is_gtd (klass)) {
4090 MonoError error;
4091 MonoGenericContext ctx;
4092 MonoMethod *inst, *gshared;
4095 * Emit gsharedvt versions of the generic delegate-invoke wrappers
4097 /* Invoke */
4098 method = mono_get_delegate_invoke (klass);
4099 create_gsharedvt_inst (acfg, method, &ctx);
4101 inst = mono_class_inflate_generic_method_checked (method, &ctx, &error);
4102 g_assert (mono_error_ok (&error)); /* FIXME don't swallow the error */
4104 m = mono_marshal_get_delegate_invoke (inst, NULL);
4105 g_assert (m->is_inflated);
4107 gshared = mini_get_shared_method_full (m, FALSE, TRUE);
4108 add_extra_method (acfg, gshared);
4110 /* begin-invoke */
4111 method = mono_get_delegate_begin_invoke (klass);
4112 if (method) {
4113 create_gsharedvt_inst (acfg, method, &ctx);
4115 inst = mono_class_inflate_generic_method_checked (method, &ctx, &error);
4116 g_assert (mono_error_ok (&error)); /* FIXME don't swallow the error */
4118 m = mono_marshal_get_delegate_begin_invoke (inst);
4119 g_assert (m->is_inflated);
4121 gshared = mini_get_shared_method_full (m, FALSE, TRUE);
4122 add_extra_method (acfg, gshared);
4125 /* end-invoke */
4126 method = mono_get_delegate_end_invoke (klass);
4127 if (method) {
4128 create_gsharedvt_inst (acfg, method, &ctx);
4130 inst = mono_class_inflate_generic_method_checked (method, &ctx, &error);
4131 g_assert (mono_error_ok (&error)); /* FIXME don't swallow the error */
4133 m = mono_marshal_get_delegate_end_invoke (inst);
4134 g_assert (m->is_inflated);
4136 gshared = mini_get_shared_method_full (m, FALSE, TRUE);
4137 add_extra_method (acfg, gshared);
4142 /* array access wrappers */
4143 for (i = 0; i < acfg->image->tables [MONO_TABLE_TYPESPEC].rows; ++i) {
4144 MonoError error;
4145 MonoClass *klass;
4147 token = MONO_TOKEN_TYPE_SPEC | (i + 1);
4148 klass = mono_class_get_checked (acfg->image, token, &error);
4150 if (!klass) {
4151 mono_error_cleanup (&error);
4152 continue;
4155 if (klass->rank && MONO_TYPE_IS_PRIMITIVE (&klass->element_class->byval_arg)) {
4156 MonoMethod *m, *wrapper;
4158 /* Add runtime-invoke wrappers too */
4160 m = mono_class_get_method_from_name (klass, "Get", -1);
4161 g_assert (m);
4162 wrapper = mono_marshal_get_array_accessor_wrapper (m);
4163 add_extra_method (acfg, wrapper);
4164 if (!acfg->aot_opts.llvm_only)
4165 add_extra_method (acfg, get_runtime_invoke (acfg, wrapper, FALSE));
4167 m = mono_class_get_method_from_name (klass, "Set", -1);
4168 g_assert (m);
4169 wrapper = mono_marshal_get_array_accessor_wrapper (m);
4170 add_extra_method (acfg, wrapper);
4171 if (!acfg->aot_opts.llvm_only)
4172 add_extra_method (acfg, get_runtime_invoke (acfg, wrapper, FALSE));
4176 /* Synchronized wrappers */
4177 for (i = 0; i < acfg->image->tables [MONO_TABLE_METHOD].rows; ++i) {
4178 MonoError error;
4179 token = MONO_TOKEN_METHOD_DEF | (i + 1);
4180 method = mono_get_method_checked (acfg->image, token, NULL, NULL, &error);
4181 report_loader_error (acfg, &error, "Failed to load method token 0x%x due to %s\n", i, mono_error_get_message (&error));
4183 if (method->iflags & METHOD_IMPL_ATTRIBUTE_SYNCHRONIZED) {
4184 if (method->is_generic) {
4185 // FIXME:
4186 } else if ((acfg->opts & MONO_OPT_GSHAREDVT) && mono_class_is_gtd (method->klass)) {
4187 MonoError error;
4188 MonoGenericContext ctx;
4189 MonoMethod *inst, *gshared, *m;
4192 * Create a generic wrapper for a generic instance, and AOT that.
4194 create_gsharedvt_inst (acfg, method, &ctx);
4195 inst = mono_class_inflate_generic_method_checked (method, &ctx, &error);
4196 g_assert (mono_error_ok (&error)); /* FIXME don't swallow the error */
4197 m = mono_marshal_get_synchronized_wrapper (inst);
4198 g_assert (m->is_inflated);
4199 gshared = mini_get_shared_method_full (m, FALSE, TRUE);
4200 add_method (acfg, gshared);
4201 } else {
4202 add_method (acfg, mono_marshal_get_synchronized_wrapper (method));
4207 /* pinvoke wrappers */
4208 for (i = 0; i < acfg->image->tables [MONO_TABLE_METHOD].rows; ++i) {
4209 MonoError error;
4210 MonoMethod *method;
4211 guint32 token = MONO_TOKEN_METHOD_DEF | (i + 1);
4213 method = mono_get_method_checked (acfg->image, token, NULL, NULL, &error);
4214 report_loader_error (acfg, &error, "Failed to load method token 0x%x due to %s\n", i, mono_error_get_message (&error));
4216 if ((method->flags & METHOD_ATTRIBUTE_PINVOKE_IMPL) ||
4217 (method->iflags & METHOD_IMPL_ATTRIBUTE_INTERNAL_CALL)) {
4218 add_method (acfg, mono_marshal_get_native_wrapper (method, TRUE, TRUE));
4221 if (method->iflags & METHOD_IMPL_ATTRIBUTE_INTERNAL_CALL) {
4222 if (acfg->aot_opts.llvm_only) {
4223 /* The wrappers have a different signature (hasthis is not set) so need to add this too */
4224 add_gsharedvt_wrappers (acfg, mono_method_signature (method), FALSE, TRUE);
4229 /* native-to-managed wrappers */
4230 for (i = 0; i < acfg->image->tables [MONO_TABLE_METHOD].rows; ++i) {
4231 MonoError error;
4232 MonoMethod *method;
4233 guint32 token = MONO_TOKEN_METHOD_DEF | (i + 1);
4234 MonoCustomAttrInfo *cattr;
4235 int j;
4237 method = mono_get_method_checked (acfg->image, token, NULL, NULL, &error);
4238 report_loader_error (acfg, &error, "Failed to load method token 0x%x due to %s\n", i, mono_error_get_message (&error));
4241 * Only generate native-to-managed wrappers for methods which have an
4242 * attribute named MonoPInvokeCallbackAttribute. We search for the attribute by
4243 * name to avoid defining a new assembly to contain it.
4245 cattr = mono_custom_attrs_from_method_checked (method, &error);
4246 if (!is_ok (&error)) {
4247 char *name = mono_method_get_full_name (method);
4248 report_loader_error (acfg, &error, "Failed to load custom attributes from method %s due to %s\n", name, mono_error_get_message (&error));
4249 g_free (name);
4252 if (cattr) {
4253 for (j = 0; j < cattr->num_attrs; ++j)
4254 if (cattr->attrs [j].ctor && !strcmp (cattr->attrs [j].ctor->klass->name, "MonoPInvokeCallbackAttribute"))
4255 break;
4256 if (j < cattr->num_attrs) {
4257 MonoCustomAttrEntry *e = &cattr->attrs [j];
4258 MonoMethodSignature *sig = mono_method_signature (e->ctor);
4259 const char *p = (const char*)e->data;
4260 const char *named;
4261 int slen, num_named, named_type;
4262 char *n;
4263 MonoType *t;
4264 MonoClass *klass;
4265 char *export_name = NULL;
4266 MonoMethod *wrapper;
4268 /* this cannot be enforced by the C# compiler so we must give the user some warning before aborting */
4269 if (!(method->flags & METHOD_ATTRIBUTE_STATIC)) {
4270 g_warning ("AOT restriction: Method '%s' must be static since it is decorated with [MonoPInvokeCallback]. See http://ios.xamarin.com/Documentation/Limitations#Reverse_Callbacks",
4271 mono_method_full_name (method, TRUE));
4272 exit (1);
4275 g_assert (sig->param_count == 1);
4276 g_assert (sig->params [0]->type == MONO_TYPE_CLASS && !strcmp (mono_class_from_mono_type (sig->params [0])->name, "Type"));
4279 * Decode the cattr manually since we can't create objects
4280 * during aot compilation.
4283 /* Skip prolog */
4284 p += 2;
4286 /* From load_cattr_value () in reflection.c */
4287 slen = mono_metadata_decode_value (p, &p);
4288 n = (char *)g_memdup (p, slen + 1);
4289 n [slen] = 0;
4290 t = mono_reflection_type_from_name_checked (n, acfg->image, &error);
4291 g_assert (t);
4292 mono_error_assert_ok (&error);
4293 g_free (n);
4295 klass = mono_class_from_mono_type (t);
4296 g_assert (klass->parent == mono_defaults.multicastdelegate_class);
4298 p += slen;
4300 num_named = read16 (p);
4301 p += 2;
4303 g_assert (num_named < 2);
4304 if (num_named == 1) {
4305 int name_len;
4306 char *name;
4308 /* parse ExportSymbol attribute */
4309 named = p;
4310 named_type = *named;
4311 named += 1;
4312 /* data_type = *named; */
4313 named += 1;
4315 name_len = mono_metadata_decode_blob_size (named, &named);
4316 name = (char *)g_malloc (name_len + 1);
4317 memcpy (name, named, name_len);
4318 name [name_len] = 0;
4319 named += name_len;
4321 g_assert (named_type == 0x54);
4322 g_assert (!strcmp (name, "ExportSymbol"));
4324 /* load_cattr_value (), string case */
4325 g_assert (*named != (char)0xff);
4326 slen = mono_metadata_decode_value (named, &named);
4327 export_name = (char *)g_malloc (slen + 1);
4328 memcpy (export_name, named, slen);
4329 export_name [slen] = 0;
4330 named += slen;
4333 wrapper = mono_marshal_get_managed_wrapper (method, klass, 0);
4334 add_method (acfg, wrapper);
4335 if (export_name)
4336 g_hash_table_insert (acfg->export_names, wrapper, export_name);
4338 g_free (cattr);
4341 if ((method->flags & METHOD_ATTRIBUTE_PINVOKE_IMPL) ||
4342 (method->iflags & METHOD_IMPL_ATTRIBUTE_INTERNAL_CALL)) {
4343 add_method (acfg, mono_marshal_get_native_wrapper (method, TRUE, TRUE));
4347 /* StructureToPtr/PtrToStructure wrappers */
4348 for (i = 0; i < acfg->image->tables [MONO_TABLE_TYPEDEF].rows; ++i) {
4349 MonoError error;
4350 MonoClass *klass;
4352 token = MONO_TOKEN_TYPE_DEF | (i + 1);
4353 klass = mono_class_get_checked (acfg->image, token, &error);
4355 if (!klass) {
4356 mono_error_cleanup (&error);
4357 continue;
4360 if (klass->valuetype && !mono_class_is_gtd (klass) && can_marshal_struct (klass) &&
4361 !(klass->nested_in && strstr (klass->nested_in->name, "<PrivateImplementationDetails>") == klass->nested_in->name)) {
4362 add_method (acfg, mono_marshal_get_struct_to_ptr (klass));
4363 add_method (acfg, mono_marshal_get_ptr_to_struct (klass));
4368 static gboolean
4369 has_type_vars (MonoClass *klass)
4371 if ((klass->byval_arg.type == MONO_TYPE_VAR) || (klass->byval_arg.type == MONO_TYPE_MVAR))
4372 return TRUE;
4373 if (klass->rank)
4374 return has_type_vars (klass->element_class);
4375 if (mono_class_is_ginst (klass)) {
4376 MonoGenericContext *context = &mono_class_get_generic_class (klass)->context;
4377 if (context->class_inst) {
4378 int i;
4380 for (i = 0; i < context->class_inst->type_argc; ++i)
4381 if (has_type_vars (mono_class_from_mono_type (context->class_inst->type_argv [i])))
4382 return TRUE;
4385 if (mono_class_is_gtd (klass))
4386 return TRUE;
4387 return FALSE;
4390 static gboolean
4391 is_vt_inst (MonoGenericInst *inst)
4393 int i;
4395 for (i = 0; i < inst->type_argc; ++i) {
4396 MonoType *t = inst->type_argv [i];
4397 if (MONO_TYPE_ISSTRUCT (t) || t->type == MONO_TYPE_VALUETYPE)
4398 return TRUE;
4400 return FALSE;
4403 static gboolean
4404 method_has_type_vars (MonoMethod *method)
4406 if (has_type_vars (method->klass))
4407 return TRUE;
4409 if (method->is_inflated) {
4410 MonoGenericContext *context = mono_method_get_context (method);
4411 if (context->method_inst) {
4412 int i;
4414 for (i = 0; i < context->method_inst->type_argc; ++i)
4415 if (has_type_vars (mono_class_from_mono_type (context->method_inst->type_argv [i])))
4416 return TRUE;
4419 return FALSE;
4422 static
4423 gboolean mono_aot_mode_is_full (MonoAotOptions *opts)
4425 return opts->mode == MONO_AOT_MODE_FULL;
4428 static
4429 gboolean mono_aot_mode_is_hybrid (MonoAotOptions *opts)
4431 return opts->mode == MONO_AOT_MODE_HYBRID;
4434 static void add_generic_class_with_depth (MonoAotCompile *acfg, MonoClass *klass, int depth, const char *ref);
4436 static void
4437 add_generic_class (MonoAotCompile *acfg, MonoClass *klass, gboolean force, const char *ref)
4439 /* This might lead to a huge code blowup so only do it if neccesary */
4440 if (!mono_aot_mode_is_full (&acfg->aot_opts) && !mono_aot_mode_is_hybrid (&acfg->aot_opts) && !force)
4441 return;
4443 add_generic_class_with_depth (acfg, klass, 0, ref);
4446 static gboolean
4447 check_type_depth (MonoType *t, int depth)
4449 int i;
4451 if (depth > 8)
4452 return TRUE;
4454 switch (t->type) {
4455 case MONO_TYPE_GENERICINST: {
4456 MonoGenericClass *gklass = t->data.generic_class;
4457 MonoGenericInst *ginst = gklass->context.class_inst;
4459 if (ginst) {
4460 for (i = 0; i < ginst->type_argc; ++i) {
4461 if (check_type_depth (ginst->type_argv [i], depth + 1))
4462 return TRUE;
4465 break;
4467 default:
4468 break;
4471 return FALSE;
4474 static void
4475 add_types_from_method_header (MonoAotCompile *acfg, MonoMethod *method);
4478 * add_generic_class:
4480 * Add all methods of a generic class.
4482 static void
4483 add_generic_class_with_depth (MonoAotCompile *acfg, MonoClass *klass, int depth, const char *ref)
4485 MonoMethod *method;
4486 MonoClassField *field;
4487 gpointer iter;
4488 gboolean use_gsharedvt = FALSE;
4490 if (!acfg->ginst_hash)
4491 acfg->ginst_hash = g_hash_table_new (NULL, NULL);
4493 mono_class_init (klass);
4495 if (mono_class_is_ginst (klass) && mono_class_get_generic_class (klass)->context.class_inst->is_open)
4496 return;
4498 if (has_type_vars (klass))
4499 return;
4501 if (!mono_class_is_ginst (klass) && !klass->rank)
4502 return;
4504 if (mono_class_has_failure (klass))
4505 return;
4507 if (!acfg->ginst_hash)
4508 acfg->ginst_hash = g_hash_table_new (NULL, NULL);
4510 if (g_hash_table_lookup (acfg->ginst_hash, klass))
4511 return;
4513 if (check_type_depth (&klass->byval_arg, 0))
4514 return;
4516 if (acfg->aot_opts.log_generics)
4517 aot_printf (acfg, "%*sAdding generic instance %s [%s].\n", depth, "", mono_type_full_name (&klass->byval_arg), ref);
4519 g_hash_table_insert (acfg->ginst_hash, klass, klass);
4522 * Use gsharedvt for generic collections with vtype arguments to avoid code blowup.
4523 * Enable this only for some classes since gsharedvt might not support all methods.
4525 if ((acfg->opts & MONO_OPT_GSHAREDVT) && klass->image == 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) &&
4526 (!strcmp (klass->name, "Dictionary`2") || !strcmp (klass->name, "List`1") || !strcmp (klass->name, "ReadOnlyCollection`1")))
4527 use_gsharedvt = TRUE;
4529 iter = NULL;
4530 while ((method = mono_class_get_methods (klass, &iter))) {
4531 if ((acfg->opts & MONO_OPT_GSHAREDVT) && method->is_inflated && mono_method_get_context (method)->method_inst) {
4533 * This is partial sharing, and we can't handle it yet
4535 continue;
4538 if (mono_method_is_generic_sharable_full (method, FALSE, FALSE, use_gsharedvt)) {
4539 /* Already added */
4540 add_types_from_method_header (acfg, method);
4541 continue;
4544 if (method->is_generic)
4545 /* FIXME: */
4546 continue;
4549 * FIXME: Instances which are referenced by these methods are not added,
4550 * for example Array.Resize<int> for List<int>.Add ().
4552 add_extra_method_with_depth (acfg, method, depth + 1);
4555 iter = NULL;
4556 while ((field = mono_class_get_fields (klass, &iter))) {
4557 if (field->type->type == MONO_TYPE_GENERICINST)
4558 add_generic_class_with_depth (acfg, mono_class_from_mono_type (field->type), depth + 1, "field");
4561 if (klass->delegate) {
4562 method = mono_get_delegate_invoke (klass);
4564 method = mono_marshal_get_delegate_invoke (method, NULL);
4566 if (acfg->aot_opts.log_generics)
4567 aot_printf (acfg, "%*sAdding method %s.\n", depth, "", mono_method_get_full_name (method));
4569 add_method (acfg, method);
4572 /* Add superclasses */
4573 if (klass->parent)
4574 add_generic_class_with_depth (acfg, klass->parent, depth, "parent");
4577 * For ICollection<T>, add instances of the helper methods
4578 * in Array, since a T[] could be cast to ICollection<T>.
4580 if (klass->image == mono_defaults.corlib && !strcmp (klass->name_space, "System.Collections.Generic") &&
4581 (!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"))) {
4582 MonoClass *tclass = mono_class_from_mono_type (mono_class_get_generic_class (klass)->context.class_inst->type_argv [0]);
4583 MonoClass *array_class = mono_bounded_array_class_get (tclass, 1, FALSE);
4584 gpointer iter;
4585 char *name_prefix;
4587 if (!strcmp (klass->name, "IEnumerator`1"))
4588 name_prefix = g_strdup_printf ("%s.%s", klass->name_space, "IEnumerable`1");
4589 else
4590 name_prefix = g_strdup_printf ("%s.%s", klass->name_space, klass->name);
4592 /* Add the T[]/InternalEnumerator class */
4593 if (!strcmp (klass->name, "IEnumerable`1") || !strcmp (klass->name, "IEnumerator`1")) {
4594 MonoError error;
4595 MonoClass *nclass;
4597 iter = NULL;
4598 while ((nclass = mono_class_get_nested_types (array_class->parent, &iter))) {
4599 if (!strcmp (nclass->name, "InternalEnumerator`1"))
4600 break;
4602 g_assert (nclass);
4603 nclass = mono_class_inflate_generic_class_checked (nclass, mono_generic_class_get_context (mono_class_get_generic_class (klass)), &error);
4604 mono_error_assert_ok (&error); /* FIXME don't swallow the error */
4605 add_generic_class (acfg, nclass, FALSE, "ICollection<T>");
4608 iter = NULL;
4609 while ((method = mono_class_get_methods (array_class, &iter))) {
4610 if (strstr (method->name, name_prefix)) {
4611 MonoMethod *m = mono_aot_get_array_helper_from_wrapper (method);
4613 add_extra_method_with_depth (acfg, m, depth);
4617 g_free (name_prefix);
4620 /* Add an instance of GenericComparer<T> which is created dynamically by Comparer<T> */
4621 if (klass->image == mono_defaults.corlib && !strcmp (klass->name_space, "System.Collections.Generic") && !strcmp (klass->name, "Comparer`1")) {
4622 MonoError error;
4623 MonoClass *tclass = mono_class_from_mono_type (mono_class_get_generic_class (klass)->context.class_inst->type_argv [0]);
4624 MonoClass *icomparable, *gcomparer, *icomparable_inst;
4625 MonoGenericContext ctx;
4626 MonoType *args [16];
4628 memset (&ctx, 0, sizeof (ctx));
4630 icomparable = mono_class_load_from_name (mono_defaults.corlib, "System", "IComparable`1");
4632 args [0] = &tclass->byval_arg;
4633 ctx.class_inst = mono_metadata_get_generic_inst (1, args);
4635 icomparable_inst = mono_class_inflate_generic_class_checked (icomparable, &ctx, &error);
4636 mono_error_assert_ok (&error); /* FIXME don't swallow the error */
4638 if (mono_class_is_assignable_from (icomparable_inst, tclass)) {
4639 MonoClass *gcomparer_inst;
4640 gcomparer = mono_class_load_from_name (mono_defaults.corlib, "System.Collections.Generic", "GenericComparer`1");
4641 gcomparer_inst = mono_class_inflate_generic_class_checked (gcomparer, &ctx, &error);
4642 mono_error_assert_ok (&error); /* FIXME don't swallow the error */
4644 add_generic_class (acfg, gcomparer_inst, FALSE, "Comparer<T>");
4648 /* Add an instance of GenericEqualityComparer<T> which is created dynamically by EqualityComparer<T> */
4649 if (klass->image == mono_defaults.corlib && !strcmp (klass->name_space, "System.Collections.Generic") && !strcmp (klass->name, "EqualityComparer`1")) {
4650 MonoError error;
4651 MonoClass *tclass = mono_class_from_mono_type (mono_class_get_generic_class (klass)->context.class_inst->type_argv [0]);
4652 MonoClass *iface, *gcomparer, *iface_inst;
4653 MonoGenericContext ctx;
4654 MonoType *args [16];
4656 memset (&ctx, 0, sizeof (ctx));
4658 iface = mono_class_load_from_name (mono_defaults.corlib, "System", "IEquatable`1");
4659 g_assert (iface);
4660 args [0] = &tclass->byval_arg;
4661 ctx.class_inst = mono_metadata_get_generic_inst (1, args);
4663 iface_inst = mono_class_inflate_generic_class_checked (iface, &ctx, &error);
4664 mono_error_assert_ok (&error); /* FIXME don't swallow the error */
4666 if (mono_class_is_assignable_from (iface_inst, tclass)) {
4667 MonoClass *gcomparer_inst;
4668 MonoError error;
4670 gcomparer = mono_class_load_from_name (mono_defaults.corlib, "System.Collections.Generic", "GenericEqualityComparer`1");
4671 gcomparer_inst = mono_class_inflate_generic_class_checked (gcomparer, &ctx, &error);
4672 mono_error_assert_ok (&error); /* FIXME don't swallow the error */
4673 add_generic_class (acfg, gcomparer_inst, FALSE, "EqualityComparer<T>");
4677 /* Add an instance of EnumComparer<T> which is created dynamically by EqualityComparer<T> for enums */
4678 if (klass->image == mono_defaults.corlib && !strcmp (klass->name_space, "System.Collections.Generic") && !strcmp (klass->name, "EqualityComparer`1")) {
4679 MonoClass *enum_comparer;
4680 MonoClass *tclass = mono_class_from_mono_type (mono_class_get_generic_class (klass)->context.class_inst->type_argv [0]);
4681 MonoGenericContext ctx;
4682 MonoType *args [16];
4684 if (mono_class_is_enum (tclass)) {
4685 MonoClass *enum_comparer_inst;
4686 MonoError error;
4688 memset (&ctx, 0, sizeof (ctx));
4689 args [0] = &tclass->byval_arg;
4690 ctx.class_inst = mono_metadata_get_generic_inst (1, args);
4692 enum_comparer = mono_class_load_from_name (mono_defaults.corlib, "System.Collections.Generic", "EnumEqualityComparer`1");
4693 enum_comparer_inst = mono_class_inflate_generic_class_checked (enum_comparer, &ctx, &error);
4694 mono_error_assert_ok (&error); /* FIXME don't swallow the error */
4695 add_generic_class (acfg, enum_comparer_inst, FALSE, "EqualityComparer<T>");
4699 /* Add an instance of ObjectComparer<T> which is created dynamically by Comparer<T> for enums */
4700 if (klass->image == mono_defaults.corlib && !strcmp (klass->name_space, "System.Collections.Generic") && !strcmp (klass->name, "Comparer`1")) {
4701 MonoClass *comparer;
4702 MonoClass *tclass = mono_class_from_mono_type (mono_class_get_generic_class (klass)->context.class_inst->type_argv [0]);
4703 MonoGenericContext ctx;
4704 MonoType *args [16];
4706 if (mono_class_is_enum (tclass)) {
4707 MonoClass *comparer_inst;
4708 MonoError error;
4710 memset (&ctx, 0, sizeof (ctx));
4711 args [0] = &tclass->byval_arg;
4712 ctx.class_inst = mono_metadata_get_generic_inst (1, args);
4714 comparer = mono_class_load_from_name (mono_defaults.corlib, "System.Collections.Generic", "ObjectComparer`1");
4715 comparer_inst = mono_class_inflate_generic_class_checked (comparer, &ctx, &error);
4716 mono_error_assert_ok (&error); /* FIXME don't swallow the error */
4717 add_generic_class (acfg, comparer_inst, FALSE, "Comparer<T>");
4722 static void
4723 add_instances_of (MonoAotCompile *acfg, MonoClass *klass, MonoType **insts, int ninsts, gboolean force)
4725 int i;
4726 MonoGenericContext ctx;
4727 MonoType *args [16];
4729 if (acfg->aot_opts.no_instances)
4730 return;
4732 memset (&ctx, 0, sizeof (ctx));
4734 for (i = 0; i < ninsts; ++i) {
4735 MonoError error;
4736 MonoClass *generic_inst;
4737 args [0] = insts [i];
4738 ctx.class_inst = mono_metadata_get_generic_inst (1, args);
4739 generic_inst = mono_class_inflate_generic_class_checked (klass, &ctx, &error);
4740 mono_error_assert_ok (&error); /* FIXME don't swallow the error */
4741 add_generic_class (acfg, generic_inst, force, "");
4745 static void
4746 add_types_from_method_header (MonoAotCompile *acfg, MonoMethod *method)
4748 MonoError error;
4749 MonoMethodHeader *header;
4750 MonoMethodSignature *sig;
4751 int j, depth;
4753 depth = GPOINTER_TO_UINT (g_hash_table_lookup (acfg->method_depth, method));
4755 sig = mono_method_signature (method);
4757 if (sig) {
4758 for (j = 0; j < sig->param_count; ++j)
4759 if (sig->params [j]->type == MONO_TYPE_GENERICINST)
4760 add_generic_class_with_depth (acfg, mono_class_from_mono_type (sig->params [j]), depth + 1, "arg");
4763 header = mono_method_get_header_checked (method, &error);
4765 if (header) {
4766 for (j = 0; j < header->num_locals; ++j)
4767 if (header->locals [j]->type == MONO_TYPE_GENERICINST)
4768 add_generic_class_with_depth (acfg, mono_class_from_mono_type (header->locals [j]), depth + 1, "local");
4769 mono_metadata_free_mh (header);
4770 } else {
4771 mono_error_cleanup (&error); /* FIXME report the error */
4777 * add_generic_instances:
4779 * Add instances referenced by the METHODSPEC/TYPESPEC table.
4781 static void
4782 add_generic_instances (MonoAotCompile *acfg)
4784 int i;
4785 guint32 token;
4786 MonoMethod *method;
4787 MonoGenericContext *context;
4789 if (acfg->aot_opts.no_instances)
4790 return;
4792 for (i = 0; i < acfg->image->tables [MONO_TABLE_METHODSPEC].rows; ++i) {
4793 MonoError error;
4794 token = MONO_TOKEN_METHOD_SPEC | (i + 1);
4795 method = mono_get_method_checked (acfg->image, token, NULL, NULL, &error);
4797 if (!method) {
4798 aot_printerrf (acfg, "Failed to load methodspec 0x%x due to %s.\n", token, mono_error_get_message (&error));
4799 aot_printerrf (acfg, "Run with MONO_LOG_LEVEL=debug for more information.\n");
4800 mono_error_cleanup (&error);
4801 continue;
4804 if (method->klass->image != acfg->image)
4805 continue;
4807 context = mono_method_get_context (method);
4809 if (context && ((context->class_inst && context->class_inst->is_open)))
4810 continue;
4813 * For open methods, create an instantiation which can be passed to the JIT.
4814 * FIXME: Handle class_inst as well.
4816 if (context && context->method_inst && context->method_inst->is_open) {
4817 MonoError error;
4818 MonoGenericContext shared_context;
4819 MonoGenericInst *inst;
4820 MonoType **type_argv;
4821 int i;
4822 MonoMethod *declaring_method;
4823 gboolean supported = TRUE;
4825 /* Check that the context doesn't contain open constructed types */
4826 if (context->class_inst) {
4827 inst = context->class_inst;
4828 for (i = 0; i < inst->type_argc; ++i) {
4829 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)
4830 continue;
4831 if (mono_class_is_open_constructed_type (inst->type_argv [i]))
4832 supported = FALSE;
4835 if (context->method_inst) {
4836 inst = context->method_inst;
4837 for (i = 0; i < inst->type_argc; ++i) {
4838 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)
4839 continue;
4840 if (mono_class_is_open_constructed_type (inst->type_argv [i]))
4841 supported = FALSE;
4845 if (!supported)
4846 continue;
4848 memset (&shared_context, 0, sizeof (MonoGenericContext));
4850 inst = context->class_inst;
4851 if (inst) {
4852 type_argv = g_new0 (MonoType*, inst->type_argc);
4853 for (i = 0; i < inst->type_argc; ++i) {
4854 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)
4855 type_argv [i] = &mono_defaults.object_class->byval_arg;
4856 else
4857 type_argv [i] = inst->type_argv [i];
4860 shared_context.class_inst = mono_metadata_get_generic_inst (inst->type_argc, type_argv);
4861 g_free (type_argv);
4864 inst = context->method_inst;
4865 if (inst) {
4866 type_argv = g_new0 (MonoType*, inst->type_argc);
4867 for (i = 0; i < inst->type_argc; ++i) {
4868 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)
4869 type_argv [i] = &mono_defaults.object_class->byval_arg;
4870 else
4871 type_argv [i] = inst->type_argv [i];
4874 shared_context.method_inst = mono_metadata_get_generic_inst (inst->type_argc, type_argv);
4875 g_free (type_argv);
4878 if (method->is_generic || mono_class_is_gtd (method->klass))
4879 declaring_method = method;
4880 else
4881 declaring_method = mono_method_get_declaring_generic_method (method);
4883 method = mono_class_inflate_generic_method_checked (declaring_method, &shared_context, &error);
4884 g_assert (mono_error_ok (&error)); /* FIXME don't swallow the error */
4888 * If the method is fully sharable, it was already added in place of its
4889 * generic definition.
4891 if (mono_method_is_generic_sharable_full (method, FALSE, FALSE, FALSE))
4892 continue;
4895 * FIXME: Partially shared methods are not shared here, so we end up with
4896 * many identical methods.
4898 add_extra_method (acfg, method);
4901 for (i = 0; i < acfg->image->tables [MONO_TABLE_TYPESPEC].rows; ++i) {
4902 MonoError error;
4903 MonoClass *klass;
4905 token = MONO_TOKEN_TYPE_SPEC | (i + 1);
4907 klass = mono_class_get_checked (acfg->image, token, &error);
4908 if (!klass || klass->rank) {
4909 mono_error_cleanup (&error);
4910 continue;
4913 add_generic_class (acfg, klass, FALSE, "typespec");
4916 /* Add types of args/locals */
4917 for (i = 0; i < acfg->methods->len; ++i) {
4918 method = (MonoMethod *)g_ptr_array_index (acfg->methods, i);
4919 add_types_from_method_header (acfg, method);
4922 if (acfg->image == mono_defaults.corlib) {
4923 MonoClass *klass;
4924 MonoType *insts [256];
4925 int ninsts = 0;
4927 insts [ninsts ++] = &mono_defaults.byte_class->byval_arg;
4928 insts [ninsts ++] = &mono_defaults.sbyte_class->byval_arg;
4929 insts [ninsts ++] = &mono_defaults.int16_class->byval_arg;
4930 insts [ninsts ++] = &mono_defaults.uint16_class->byval_arg;
4931 insts [ninsts ++] = &mono_defaults.int32_class->byval_arg;
4932 insts [ninsts ++] = &mono_defaults.uint32_class->byval_arg;
4933 insts [ninsts ++] = &mono_defaults.int64_class->byval_arg;
4934 insts [ninsts ++] = &mono_defaults.uint64_class->byval_arg;
4935 insts [ninsts ++] = &mono_defaults.single_class->byval_arg;
4936 insts [ninsts ++] = &mono_defaults.double_class->byval_arg;
4937 insts [ninsts ++] = &mono_defaults.char_class->byval_arg;
4938 insts [ninsts ++] = &mono_defaults.boolean_class->byval_arg;
4940 /* Add GenericComparer<T> instances for primitive types for Enum.ToString () */
4941 klass = mono_class_try_load_from_name (acfg->image, "System.Collections.Generic", "GenericComparer`1");
4942 if (klass)
4943 add_instances_of (acfg, klass, insts, ninsts, TRUE);
4944 klass = mono_class_try_load_from_name (acfg->image, "System.Collections.Generic", "GenericEqualityComparer`1");
4945 if (klass)
4946 add_instances_of (acfg, klass, insts, ninsts, TRUE);
4948 /* Add instances of EnumEqualityComparer which are created by EqualityComparer<T> for enums */
4950 MonoClass *enum_comparer;
4951 MonoType *insts [16];
4952 int ninsts;
4954 ninsts = 0;
4955 insts [ninsts ++] = &mono_defaults.int32_class->byval_arg;
4956 insts [ninsts ++] = &mono_defaults.uint32_class->byval_arg;
4957 insts [ninsts ++] = &mono_defaults.uint16_class->byval_arg;
4958 insts [ninsts ++] = &mono_defaults.byte_class->byval_arg;
4959 enum_comparer = mono_class_load_from_name (mono_defaults.corlib, "System.Collections.Generic", "EnumEqualityComparer`1");
4960 add_instances_of (acfg, enum_comparer, insts, ninsts, FALSE);
4962 ninsts = 0;
4963 insts [ninsts ++] = &mono_defaults.int16_class->byval_arg;
4964 enum_comparer = mono_class_load_from_name (mono_defaults.corlib, "System.Collections.Generic", "ShortEnumEqualityComparer`1");
4965 add_instances_of (acfg, enum_comparer, insts, ninsts, FALSE);
4967 ninsts = 0;
4968 insts [ninsts ++] = &mono_defaults.sbyte_class->byval_arg;
4969 enum_comparer = mono_class_load_from_name (mono_defaults.corlib, "System.Collections.Generic", "SByteEnumEqualityComparer`1");
4970 add_instances_of (acfg, enum_comparer, insts, ninsts, FALSE);
4972 enum_comparer = mono_class_load_from_name (mono_defaults.corlib, "System.Collections.Generic", "LongEnumEqualityComparer`1");
4973 ninsts = 0;
4974 insts [ninsts ++] = &mono_defaults.int64_class->byval_arg;
4975 insts [ninsts ++] = &mono_defaults.uint64_class->byval_arg;
4976 add_instances_of (acfg, enum_comparer, insts, ninsts, FALSE);
4979 /* Add instances of the array generic interfaces for primitive types */
4980 /* This will add instances of the InternalArray_ helper methods in Array too */
4981 klass = mono_class_try_load_from_name (acfg->image, "System.Collections.Generic", "ICollection`1");
4982 if (klass)
4983 add_instances_of (acfg, klass, insts, ninsts, TRUE);
4985 klass = mono_class_try_load_from_name (acfg->image, "System.Collections.Generic", "IList`1");
4986 if (klass)
4987 add_instances_of (acfg, klass, insts, ninsts, TRUE);
4989 klass = mono_class_try_load_from_name (acfg->image, "System.Collections.Generic", "IEnumerable`1");
4990 if (klass)
4991 add_instances_of (acfg, klass, insts, ninsts, TRUE);
4994 * Add a managed-to-native wrapper of Array.GetGenericValueImpl<object>, which is
4995 * used for all instances of GetGenericValueImpl by the AOT runtime.
4998 MonoGenericContext ctx;
4999 MonoType *args [16];
5000 MonoMethod *get_method;
5001 MonoClass *array_klass = mono_array_class_get (mono_defaults.object_class, 1)->parent;
5003 get_method = mono_class_get_method_from_name (array_klass, "GetGenericValueImpl", 2);
5005 if (get_method) {
5006 MonoError error;
5007 memset (&ctx, 0, sizeof (ctx));
5008 args [0] = &mono_defaults.object_class->byval_arg;
5009 ctx.method_inst = mono_metadata_get_generic_inst (1, args);
5010 add_extra_method (acfg, mono_marshal_get_native_wrapper (mono_class_inflate_generic_method_checked (get_method, &ctx, &error), TRUE, TRUE));
5011 g_assert (mono_error_ok (&error)); /* FIXME don't swallow the error */
5015 /* Same for CompareExchange<T>/Exchange<T> */
5017 MonoGenericContext ctx;
5018 MonoType *args [16];
5019 MonoMethod *m;
5020 MonoClass *interlocked_klass = mono_class_load_from_name (mono_defaults.corlib, "System.Threading", "Interlocked");
5021 gpointer iter = NULL;
5023 while ((m = mono_class_get_methods (interlocked_klass, &iter))) {
5024 if ((!strcmp (m->name, "CompareExchange") || !strcmp (m->name, "Exchange")) && m->is_generic) {
5025 MonoError error;
5026 memset (&ctx, 0, sizeof (ctx));
5027 args [0] = &mono_defaults.object_class->byval_arg;
5028 ctx.method_inst = mono_metadata_get_generic_inst (1, args);
5029 add_extra_method (acfg, mono_marshal_get_native_wrapper (mono_class_inflate_generic_method_checked (m, &ctx, &error), TRUE, TRUE));
5030 g_assert (mono_error_ok (&error)); /* FIXME don't swallow the error */
5035 /* Same for Volatile.Read/Write<T> */
5037 MonoGenericContext ctx;
5038 MonoType *args [16];
5039 MonoMethod *m;
5040 MonoClass *volatile_klass = mono_class_try_load_from_name (mono_defaults.corlib, "System.Threading", "Volatile");
5041 gpointer iter = NULL;
5043 if (volatile_klass) {
5044 while ((m = mono_class_get_methods (volatile_klass, &iter))) {
5045 if ((!strcmp (m->name, "Read") || !strcmp (m->name, "Write")) && m->is_generic) {
5046 MonoError error;
5047 memset (&ctx, 0, sizeof (ctx));
5048 args [0] = &mono_defaults.object_class->byval_arg;
5049 ctx.method_inst = mono_metadata_get_generic_inst (1, args);
5050 add_extra_method (acfg, mono_marshal_get_native_wrapper (mono_class_inflate_generic_method_checked (m, &ctx, &error), TRUE, TRUE));
5051 g_assert (mono_error_ok (&error)); /* FIXME don't swallow the error */
5057 /* object[] accessor wrappers. */
5058 for (i = 1; i < 4; ++i) {
5059 MonoClass *obj_array_class = mono_array_class_get (mono_defaults.object_class, i);
5060 MonoMethod *m;
5062 m = mono_class_get_method_from_name (obj_array_class, "Get", i);
5063 g_assert (m);
5065 m = mono_marshal_get_array_accessor_wrapper (m);
5066 add_extra_method (acfg, m);
5068 m = mono_class_get_method_from_name (obj_array_class, "Address", i);
5069 g_assert (m);
5071 m = mono_marshal_get_array_accessor_wrapper (m);
5072 add_extra_method (acfg, m);
5074 m = mono_class_get_method_from_name (obj_array_class, "Set", i + 1);
5075 g_assert (m);
5077 m = mono_marshal_get_array_accessor_wrapper (m);
5078 add_extra_method (acfg, m);
5084 * is_direct_callable:
5086 * Return whenever the method identified by JI is directly callable without
5087 * going through the PLT.
5089 static gboolean
5090 is_direct_callable (MonoAotCompile *acfg, MonoMethod *method, MonoJumpInfo *patch_info)
5092 if ((patch_info->type == MONO_PATCH_INFO_METHOD) && (patch_info->data.method->klass->image == acfg->image)) {
5093 MonoCompile *callee_cfg = (MonoCompile *)g_hash_table_lookup (acfg->method_to_cfg, patch_info->data.method);
5094 if (callee_cfg) {
5095 gboolean direct_callable = TRUE;
5097 if (direct_callable && !(!callee_cfg->has_got_slots && mono_class_is_before_field_init (callee_cfg->method->klass)))
5098 direct_callable = FALSE;
5099 if ((callee_cfg->method->iflags & METHOD_IMPL_ATTRIBUTE_SYNCHRONIZED) && (!method || method->wrapper_type != MONO_WRAPPER_SYNCHRONIZED))
5100 // FIXME: Maybe call the wrapper directly ?
5101 direct_callable = FALSE;
5103 if (acfg->aot_opts.soft_debug || acfg->aot_opts.no_direct_calls) {
5104 /* Disable this so all calls go through load_method (), see the
5105 * mini_get_debug_options ()->load_aot_jit_info_eagerly = TRUE; line in
5106 * mono_debugger_agent_init ().
5108 direct_callable = FALSE;
5111 if (callee_cfg->method->wrapper_type == MONO_WRAPPER_ALLOC)
5112 /* sgen does some initialization when the allocator method is created */
5113 direct_callable = FALSE;
5114 if (callee_cfg->method->wrapper_type == MONO_WRAPPER_WRITE_BARRIER)
5115 /* we don't know at compile time whether sgen is concurrent or not */
5116 direct_callable = FALSE;
5118 if (direct_callable)
5119 return TRUE;
5121 } else if ((patch_info->type == MONO_PATCH_INFO_ICALL_ADDR_CALL && patch_info->data.method->flags & METHOD_ATTRIBUTE_PINVOKE_IMPL)) {
5122 if (acfg->aot_opts.direct_pinvoke)
5123 return TRUE;
5124 } else if (patch_info->type == MONO_PATCH_INFO_ICALL_ADDR_CALL) {
5125 if (acfg->aot_opts.direct_icalls)
5126 return TRUE;
5127 return FALSE;
5130 return FALSE;
5133 #ifdef MONO_ARCH_AOT_SUPPORTED
5134 static const char *
5135 get_pinvoke_import (MonoAotCompile *acfg, MonoMethod *method)
5137 MonoImage *image = method->klass->image;
5138 MonoMethodPInvoke *piinfo = (MonoMethodPInvoke *) method;
5139 MonoTableInfo *tables = image->tables;
5140 MonoTableInfo *im = &tables [MONO_TABLE_IMPLMAP];
5141 MonoTableInfo *mr = &tables [MONO_TABLE_MODULEREF];
5142 guint32 im_cols [MONO_IMPLMAP_SIZE];
5143 char *import;
5145 import = (char *)g_hash_table_lookup (acfg->method_to_pinvoke_import, method);
5146 if (import != NULL)
5147 return import;
5149 if (!piinfo->implmap_idx || piinfo->implmap_idx > im->rows)
5150 return NULL;
5152 mono_metadata_decode_row (im, piinfo->implmap_idx - 1, im_cols, MONO_IMPLMAP_SIZE);
5154 if (!im_cols [MONO_IMPLMAP_SCOPE] || im_cols [MONO_IMPLMAP_SCOPE] > mr->rows)
5155 return NULL;
5157 import = g_strdup_printf ("%s", mono_metadata_string_heap (image, im_cols [MONO_IMPLMAP_NAME]));
5159 g_hash_table_insert (acfg->method_to_pinvoke_import, method, import);
5161 return import;
5163 #else
5164 static const char *
5165 get_pinvoke_import (MonoAotCompile *acfg, MonoMethod *method)
5167 return NULL;
5169 #endif
5171 static gint
5172 compare_lne (MonoDebugLineNumberEntry *a, MonoDebugLineNumberEntry *b)
5174 if (a->native_offset == b->native_offset)
5175 return a->il_offset - b->il_offset;
5176 else
5177 return a->native_offset - b->native_offset;
5181 * compute_line_numbers:
5183 * Returns a sparse array of size CODE_SIZE containing MonoDebugSourceLocation* entries for the native offsets which have a corresponding line number
5184 * entry.
5186 static MonoDebugSourceLocation**
5187 compute_line_numbers (MonoMethod *method, int code_size, MonoDebugMethodJitInfo *debug_info)
5189 MonoDebugMethodInfo *minfo;
5190 MonoDebugLineNumberEntry *ln_array;
5191 MonoDebugSourceLocation *loc;
5192 int i, prev_line, prev_il_offset;
5193 int *native_to_il_offset = NULL;
5194 MonoDebugSourceLocation **res;
5195 gboolean first;
5197 minfo = mono_debug_lookup_method (method);
5198 if (!minfo)
5199 return NULL;
5200 // FIXME: This seems to happen when two methods have the same cfg->method_to_register
5201 if (debug_info->code_size != code_size)
5202 return NULL;
5204 g_assert (code_size);
5206 /* Compute the native->IL offset mapping */
5208 ln_array = g_new0 (MonoDebugLineNumberEntry, debug_info->num_line_numbers);
5209 memcpy (ln_array, debug_info->line_numbers, debug_info->num_line_numbers * sizeof (MonoDebugLineNumberEntry));
5211 qsort (ln_array, debug_info->num_line_numbers, sizeof (MonoDebugLineNumberEntry), (int (*)(const void *, const void *))compare_lne);
5213 native_to_il_offset = g_new0 (int, code_size + 1);
5215 for (i = 0; i < debug_info->num_line_numbers; ++i) {
5216 int j;
5217 MonoDebugLineNumberEntry *lne = &ln_array [i];
5219 if (i == 0) {
5220 for (j = 0; j < lne->native_offset; ++j)
5221 native_to_il_offset [j] = -1;
5224 if (i < debug_info->num_line_numbers - 1) {
5225 MonoDebugLineNumberEntry *lne_next = &ln_array [i + 1];
5227 for (j = lne->native_offset; j < lne_next->native_offset; ++j)
5228 native_to_il_offset [j] = lne->il_offset;
5229 } else {
5230 for (j = lne->native_offset; j < code_size; ++j)
5231 native_to_il_offset [j] = lne->il_offset;
5234 g_free (ln_array);
5236 /* Compute the native->line number mapping */
5237 res = g_new0 (MonoDebugSourceLocation*, code_size);
5238 prev_il_offset = -1;
5239 prev_line = -1;
5240 first = TRUE;
5241 for (i = 0; i < code_size; ++i) {
5242 int il_offset = native_to_il_offset [i];
5244 if (il_offset == -1 || il_offset == prev_il_offset)
5245 continue;
5246 prev_il_offset = il_offset;
5247 loc = mono_debug_symfile_lookup_location (minfo, il_offset);
5248 if (!(loc && loc->source_file))
5249 continue;
5250 if (loc->row == prev_line) {
5251 mono_debug_symfile_free_location (loc);
5252 continue;
5254 prev_line = loc->row;
5255 //printf ("D: %s:%d il=%x native=%x\n", loc->source_file, loc->row, il_offset, i);
5256 if (first)
5257 /* This will cover the prolog too */
5258 res [0] = loc;
5259 else
5260 res [i] = loc;
5261 first = FALSE;
5263 return res;
5266 static int
5267 get_file_index (MonoAotCompile *acfg, const char *source_file)
5269 int findex;
5271 // FIXME: Free these
5272 if (!acfg->dwarf_ln_filenames)
5273 acfg->dwarf_ln_filenames = g_hash_table_new (g_str_hash, g_str_equal);
5274 findex = GPOINTER_TO_INT (g_hash_table_lookup (acfg->dwarf_ln_filenames, source_file));
5275 if (!findex) {
5276 findex = g_hash_table_size (acfg->dwarf_ln_filenames) + 1;
5277 g_hash_table_insert (acfg->dwarf_ln_filenames, g_strdup (source_file), GINT_TO_POINTER (findex));
5278 emit_unset_mode (acfg);
5279 fprintf (acfg->fp, ".file %d \"%s\"\n", findex, mono_dwarf_escape_path (source_file));
5281 return findex;
5284 #ifdef TARGET_ARM64
5285 #define INST_LEN 4
5286 #else
5287 #define INST_LEN 1
5288 #endif
5291 * emit_and_reloc_code:
5293 * Emit the native code in CODE, handling relocations along the way. If GOT_ONLY
5294 * is true, calls are made through the GOT too. This is used for emitting trampolines
5295 * in full-aot mode, since calls made from trampolines couldn't go through the PLT,
5296 * since trampolines are needed to make PTL work.
5298 static void
5299 emit_and_reloc_code (MonoAotCompile *acfg, MonoMethod *method, guint8 *code, guint32 code_len, MonoJumpInfo *relocs, gboolean got_only, MonoDebugMethodJitInfo *debug_info)
5301 int i, pindex, start_index;
5302 GPtrArray *patches;
5303 MonoJumpInfo *patch_info;
5304 MonoDebugSourceLocation **locs = NULL;
5305 gboolean skip, prologue_end = FALSE;
5306 #ifdef MONO_ARCH_AOT_SUPPORTED
5307 gboolean direct_call, external_call;
5308 guint32 got_slot;
5309 const char *direct_call_target = 0;
5310 const char *direct_pinvoke;
5311 #endif
5313 if (acfg->gas_line_numbers && method && debug_info) {
5314 locs = compute_line_numbers (method, code_len, debug_info);
5315 if (!locs) {
5316 int findex = get_file_index (acfg, "<unknown>");
5317 emit_unset_mode (acfg);
5318 fprintf (acfg->fp, ".loc %d %d 0\n", findex, 1);
5322 /* Collect and sort relocations */
5323 patches = g_ptr_array_new ();
5324 for (patch_info = relocs; patch_info; patch_info = patch_info->next)
5325 g_ptr_array_add (patches, patch_info);
5326 g_ptr_array_sort (patches, compare_patches);
5328 start_index = 0;
5329 for (i = 0; i < code_len; i += INST_LEN) {
5330 patch_info = NULL;
5331 for (pindex = start_index; pindex < patches->len; ++pindex) {
5332 patch_info = (MonoJumpInfo *)g_ptr_array_index (patches, pindex);
5333 if (patch_info->ip.i >= i)
5334 break;
5337 if (locs && locs [i]) {
5338 MonoDebugSourceLocation *loc = locs [i];
5339 int findex;
5340 const char *options;
5342 findex = get_file_index (acfg, loc->source_file);
5343 emit_unset_mode (acfg);
5344 if (!prologue_end)
5345 options = " prologue_end";
5346 else
5347 options = "";
5348 prologue_end = TRUE;
5349 fprintf (acfg->fp, ".loc %d %d 0%s\n", findex, loc->row, options);
5350 mono_debug_symfile_free_location (loc);
5353 skip = FALSE;
5354 #ifdef MONO_ARCH_AOT_SUPPORTED
5355 if (patch_info && (patch_info->ip.i == i) && (pindex < patches->len)) {
5356 start_index = pindex;
5358 switch (patch_info->type) {
5359 case MONO_PATCH_INFO_NONE:
5360 break;
5361 case MONO_PATCH_INFO_GOT_OFFSET: {
5362 int code_size;
5364 arch_emit_got_offset (acfg, code + i, &code_size);
5365 i += code_size - INST_LEN;
5366 skip = TRUE;
5367 patch_info->type = MONO_PATCH_INFO_NONE;
5368 break;
5370 case MONO_PATCH_INFO_OBJC_SELECTOR_REF: {
5371 int code_size, index;
5372 char *selector = (char *)patch_info->data.target;
5374 if (!acfg->objc_selector_to_index)
5375 acfg->objc_selector_to_index = g_hash_table_new (g_str_hash, g_str_equal);
5376 if (!acfg->objc_selectors)
5377 acfg->objc_selectors = g_ptr_array_new ();
5378 index = GPOINTER_TO_UINT (g_hash_table_lookup (acfg->objc_selector_to_index, selector));
5379 if (index)
5380 index --;
5381 else {
5382 index = acfg->objc_selector_index;
5383 g_ptr_array_add (acfg->objc_selectors, (void*)patch_info->data.target);
5384 g_hash_table_insert (acfg->objc_selector_to_index, selector, GUINT_TO_POINTER (index + 1));
5385 acfg->objc_selector_index ++;
5388 arch_emit_objc_selector_ref (acfg, code + i, index, &code_size);
5389 i += code_size - INST_LEN;
5390 skip = TRUE;
5391 patch_info->type = MONO_PATCH_INFO_NONE;
5392 break;
5394 default: {
5396 * If this patch is a call, try emitting a direct call instead of
5397 * through a PLT entry. This is possible if the called method is in
5398 * the same assembly and requires no initialization.
5400 direct_call = FALSE;
5401 external_call = FALSE;
5402 if ((patch_info->type == MONO_PATCH_INFO_METHOD) && (patch_info->data.method->klass->image == acfg->image)) {
5403 if (!got_only && is_direct_callable (acfg, method, patch_info)) {
5404 MonoCompile *callee_cfg = (MonoCompile *)g_hash_table_lookup (acfg->method_to_cfg, patch_info->data.method);
5405 //printf ("DIRECT: %s %s\n", method ? mono_method_full_name (method, TRUE) : "", mono_method_full_name (callee_cfg->method, TRUE));
5406 direct_call = TRUE;
5407 direct_call_target = callee_cfg->asm_symbol;
5408 patch_info->type = MONO_PATCH_INFO_NONE;
5409 acfg->stats.direct_calls ++;
5412 acfg->stats.all_calls ++;
5413 } else if (patch_info->type == MONO_PATCH_INFO_ICALL_ADDR_CALL) {
5414 if (!got_only && is_direct_callable (acfg, method, patch_info)) {
5415 if (!(patch_info->data.method->flags & METHOD_ATTRIBUTE_PINVOKE_IMPL))
5416 direct_pinvoke = mono_lookup_icall_symbol (patch_info->data.method);
5417 else
5418 direct_pinvoke = get_pinvoke_import (acfg, patch_info->data.method);
5419 if (direct_pinvoke) {
5420 direct_call = TRUE;
5421 g_assert (strlen (direct_pinvoke) < 1000);
5422 direct_call_target = g_strdup_printf ("%s%s", acfg->user_symbol_prefix, direct_pinvoke);
5425 } else if (patch_info->type == MONO_PATCH_INFO_JIT_ICALL_ADDR) {
5426 const char *sym = mono_lookup_jit_icall_symbol (patch_info->data.name);
5427 if (!got_only && sym && acfg->aot_opts.direct_icalls) {
5428 /* Call to a C function implementing a jit icall */
5429 direct_call = TRUE;
5430 external_call = TRUE;
5431 g_assert (strlen (sym) < 1000);
5432 direct_call_target = g_strdup_printf ("%s%s", acfg->user_symbol_prefix, sym);
5434 } else if (patch_info->type == MONO_PATCH_INFO_INTERNAL_METHOD) {
5435 MonoJitICallInfo *info = mono_find_jit_icall_by_name (patch_info->data.name);
5436 const char *sym = mono_lookup_jit_icall_symbol (patch_info->data.name);
5437 if (!got_only && sym && acfg->aot_opts.direct_icalls && info->func == info->wrapper) {
5438 /* Call to a jit icall without a wrapper */
5439 direct_call = TRUE;
5440 external_call = TRUE;
5441 g_assert (strlen (sym) < 1000);
5442 direct_call_target = g_strdup_printf ("%s%s", acfg->user_symbol_prefix, sym);
5446 if (direct_call) {
5447 patch_info->type = MONO_PATCH_INFO_NONE;
5448 acfg->stats.direct_calls ++;
5451 if (!got_only && !direct_call) {
5452 MonoPltEntry *plt_entry = get_plt_entry (acfg, patch_info);
5453 if (plt_entry) {
5454 /* This patch has a PLT entry, so we must emit a call to the PLT entry */
5455 direct_call = TRUE;
5456 direct_call_target = plt_entry->symbol;
5458 /* Nullify the patch */
5459 patch_info->type = MONO_PATCH_INFO_NONE;
5460 plt_entry->jit_used = TRUE;
5464 if (direct_call) {
5465 int call_size;
5467 arch_emit_direct_call (acfg, direct_call_target, external_call, FALSE, patch_info, &call_size);
5468 i += call_size - INST_LEN;
5469 } else {
5470 int code_size;
5472 got_slot = get_got_offset (acfg, FALSE, patch_info);
5474 arch_emit_got_access (acfg, acfg->got_symbol, code + i, got_slot, &code_size);
5475 i += code_size - INST_LEN;
5477 skip = TRUE;
5481 #endif /* MONO_ARCH_AOT_SUPPORTED */
5483 if (!skip) {
5484 /* Find next patch */
5485 patch_info = NULL;
5486 for (pindex = start_index; pindex < patches->len; ++pindex) {
5487 patch_info = (MonoJumpInfo *)g_ptr_array_index (patches, pindex);
5488 if (patch_info->ip.i >= i)
5489 break;
5492 /* Try to emit multiple bytes at once */
5493 if (pindex < patches->len && patch_info->ip.i > i) {
5494 int limit;
5496 for (limit = i + INST_LEN; limit < patch_info->ip.i; limit += INST_LEN) {
5497 if (locs && locs [limit])
5498 break;
5501 emit_code_bytes (acfg, code + i, limit - i);
5502 i = limit - INST_LEN;
5503 } else {
5504 emit_code_bytes (acfg, code + i, INST_LEN);
5509 g_ptr_array_free (patches, TRUE);
5510 g_free (locs);
5514 * sanitize_symbol:
5516 * Return a modified version of S which only includes characters permissible in symbols.
5518 static char*
5519 sanitize_symbol (MonoAotCompile *acfg, char *s)
5521 gboolean process = FALSE;
5522 int i, len;
5523 GString *gs;
5524 char *res;
5526 if (!s)
5527 return s;
5529 len = strlen (s);
5530 for (i = 0; i < len; ++i)
5531 if (!(s [i] <= 0x7f && (isalnum (s [i]) || s [i] == '_')))
5532 process = TRUE;
5533 if (!process)
5534 return s;
5536 gs = g_string_sized_new (len);
5537 for (i = 0; i < len; ++i) {
5538 guint8 c = s [i];
5539 if (c <= 0x7f && (isalnum (c) || c == '_')) {
5540 g_string_append_c (gs, c);
5541 } else if (c > 0x7f) {
5542 /* multi-byte utf8 */
5543 g_string_append_printf (gs, "_0x%x", c);
5544 i ++;
5545 c = s [i];
5546 while (c >> 6 == 0x2) {
5547 g_string_append_printf (gs, "%x", c);
5548 i ++;
5549 c = s [i];
5551 g_string_append_printf (gs, "_");
5552 i --;
5553 } else {
5554 g_string_append_c (gs, '_');
5558 res = mono_mempool_strdup (acfg->mempool, gs->str);
5559 g_string_free (gs, TRUE);
5560 return res;
5563 static char*
5564 get_debug_sym (MonoMethod *method, const char *prefix, GHashTable *cache)
5566 char *name1, *name2, *cached;
5567 int i, j, len, count;
5568 MonoMethod *cached_method;
5570 name1 = mono_method_full_name (method, TRUE);
5572 #ifdef TARGET_MACH
5573 // This is so that we don't accidentally create a local symbol (which starts with 'L')
5574 if ((!prefix || !*prefix) && name1 [0] == 'L')
5575 prefix = "_";
5576 #endif
5578 #if defined(TARGET_WIN32) && defined(TARGET_X86)
5579 char adjustedPrefix [MAX_SYMBOL_SIZE];
5580 prefix = mangle_symbol (prefix, adjustedPrefix, G_N_ELEMENTS (adjustedPrefix));
5581 #endif
5583 len = strlen (name1);
5584 name2 = (char *)malloc (strlen (prefix) + len + 16);
5585 memcpy (name2, prefix, strlen (prefix));
5586 j = strlen (prefix);
5587 for (i = 0; i < len; ++i) {
5588 if (i == 0 && name1 [0] >= '0' && name1 [0] <= '9') {
5589 name2 [j ++] = '_';
5590 } else if (isalnum (name1 [i])) {
5591 name2 [j ++] = name1 [i];
5592 } else if (name1 [i] == ' ' && name1 [i + 1] == '(' && name1 [i + 2] == ')') {
5593 i += 2;
5594 } else if (name1 [i] == ',' && name1 [i + 1] == ' ') {
5595 name2 [j ++] = '_';
5596 i++;
5597 } else if (name1 [i] == '(' || name1 [i] == ')' || name1 [i] == '>') {
5598 } else
5599 name2 [j ++] = '_';
5601 name2 [j] = '\0';
5603 g_free (name1);
5605 count = 0;
5606 while (TRUE) {
5607 cached_method = (MonoMethod *)g_hash_table_lookup (cache, name2);
5608 if (!(cached_method && cached_method != method))
5609 break;
5610 sprintf (name2 + j, "_%d", count);
5611 count ++;
5614 cached = g_strdup (name2);
5615 g_hash_table_insert (cache, cached, method);
5617 return name2;
5620 static void
5621 emit_method_code (MonoAotCompile *acfg, MonoCompile *cfg)
5623 MonoMethod *method;
5624 int method_index;
5625 guint8 *code;
5626 char *debug_sym = NULL;
5627 char *symbol = NULL;
5628 int func_alignment = AOT_FUNC_ALIGNMENT;
5629 char *export_name;
5631 method = cfg->orig_method;
5632 code = cfg->native_code;
5634 method_index = get_method_index (acfg, method);
5635 symbol = g_strdup_printf ("%sme_%x", acfg->temp_prefix, method_index);
5637 /* Make the labels local */
5638 emit_section_change (acfg, ".text", 0);
5639 emit_alignment_code (acfg, func_alignment);
5641 if (acfg->global_symbols && acfg->need_no_dead_strip)
5642 fprintf (acfg->fp, " .no_dead_strip %s\n", cfg->asm_symbol);
5644 emit_label (acfg, cfg->asm_symbol);
5646 if (acfg->aot_opts.write_symbols && !acfg->global_symbols && !acfg->llvm) {
5648 * Write a C style symbol for every method, this has two uses:
5649 * - it works on platforms where the dwarf debugging info is not
5650 * yet supported.
5651 * - it allows the setting of breakpoints of aot-ed methods.
5653 debug_sym = get_debug_sym (method, "", acfg->method_label_hash);
5654 cfg->asm_debug_symbol = g_strdup (debug_sym);
5656 if (acfg->need_no_dead_strip)
5657 fprintf (acfg->fp, " .no_dead_strip %s\n", debug_sym);
5658 emit_local_symbol (acfg, debug_sym, symbol, TRUE);
5659 emit_label (acfg, debug_sym);
5662 export_name = (char *)g_hash_table_lookup (acfg->export_names, method);
5663 if (export_name) {
5664 /* Emit a global symbol for the method */
5665 emit_global_inner (acfg, export_name, TRUE);
5666 emit_label (acfg, export_name);
5669 if (cfg->verbose_level > 0)
5670 g_print ("Method %s emitted as %s\n", mono_method_get_full_name (method), cfg->asm_symbol);
5672 acfg->stats.code_size += cfg->code_len;
5674 acfg->cfgs [method_index]->got_offset = acfg->got_offset;
5676 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 ()));
5678 emit_line (acfg);
5680 if (acfg->aot_opts.write_symbols) {
5681 if (debug_sym)
5682 emit_symbol_size (acfg, debug_sym, ".");
5683 else
5684 emit_symbol_size (acfg, cfg->asm_symbol, ".");
5685 g_free (debug_sym);
5688 emit_label (acfg, symbol);
5689 g_free (symbol);
5693 * encode_patch:
5695 * Encode PATCH_INFO into its disk representation.
5697 static void
5698 encode_patch (MonoAotCompile *acfg, MonoJumpInfo *patch_info, guint8 *buf, guint8 **endbuf)
5700 guint8 *p = buf;
5702 switch (patch_info->type) {
5703 case MONO_PATCH_INFO_NONE:
5704 break;
5705 case MONO_PATCH_INFO_IMAGE:
5706 encode_value (get_image_index (acfg, patch_info->data.image), p, &p);
5707 break;
5708 case MONO_PATCH_INFO_MSCORLIB_GOT_ADDR:
5709 case MONO_PATCH_INFO_GC_CARD_TABLE_ADDR:
5710 case MONO_PATCH_INFO_GC_NURSERY_START:
5711 case MONO_PATCH_INFO_GC_NURSERY_BITS:
5712 break;
5713 case MONO_PATCH_INFO_CASTCLASS_CACHE:
5714 encode_value (patch_info->data.index, p, &p);
5715 break;
5716 case MONO_PATCH_INFO_METHOD_REL:
5717 encode_value ((gint)patch_info->data.offset, p, &p);
5718 break;
5719 case MONO_PATCH_INFO_SWITCH: {
5720 gpointer *table = (gpointer *)patch_info->data.table->table;
5721 int k;
5723 encode_value (patch_info->data.table->table_size, p, &p);
5724 for (k = 0; k < patch_info->data.table->table_size; k++)
5725 encode_value ((int)(gssize)table [k], p, &p);
5726 break;
5728 case MONO_PATCH_INFO_METHODCONST:
5729 case MONO_PATCH_INFO_METHOD:
5730 case MONO_PATCH_INFO_METHOD_JUMP:
5731 case MONO_PATCH_INFO_ICALL_ADDR:
5732 case MONO_PATCH_INFO_ICALL_ADDR_CALL:
5733 case MONO_PATCH_INFO_METHOD_RGCTX:
5734 case MONO_PATCH_INFO_METHOD_CODE_SLOT:
5735 encode_method_ref (acfg, patch_info->data.method, p, &p);
5736 break;
5737 case MONO_PATCH_INFO_AOT_JIT_INFO:
5738 case MONO_PATCH_INFO_GET_TLS_TRAMP:
5739 case MONO_PATCH_INFO_SET_TLS_TRAMP:
5740 encode_value (patch_info->data.index, p, &p);
5741 break;
5742 case MONO_PATCH_INFO_INTERNAL_METHOD:
5743 case MONO_PATCH_INFO_JIT_ICALL_ADDR: {
5744 guint32 len = strlen (patch_info->data.name);
5746 encode_value (len, p, &p);
5748 memcpy (p, patch_info->data.name, len);
5749 p += len;
5750 *p++ = '\0';
5751 break;
5753 case MONO_PATCH_INFO_LDSTR: {
5754 guint32 image_index = get_image_index (acfg, patch_info->data.token->image);
5755 guint32 token = patch_info->data.token->token;
5756 g_assert (mono_metadata_token_code (token) == MONO_TOKEN_STRING);
5757 encode_value (image_index, p, &p);
5758 encode_value (patch_info->data.token->token - MONO_TOKEN_STRING, p, &p);
5759 break;
5761 case MONO_PATCH_INFO_RVA:
5762 case MONO_PATCH_INFO_DECLSEC:
5763 case MONO_PATCH_INFO_LDTOKEN:
5764 case MONO_PATCH_INFO_TYPE_FROM_HANDLE:
5765 encode_value (get_image_index (acfg, patch_info->data.token->image), p, &p);
5766 encode_value (patch_info->data.token->token, p, &p);
5767 encode_value (patch_info->data.token->has_context, p, &p);
5768 if (patch_info->data.token->has_context)
5769 encode_generic_context (acfg, &patch_info->data.token->context, p, &p);
5770 break;
5771 case MONO_PATCH_INFO_EXC_NAME: {
5772 MonoClass *ex_class;
5774 ex_class =
5775 mono_class_load_from_name (mono_defaults.exception_class->image,
5776 "System", (const char *)patch_info->data.target);
5777 encode_klass_ref (acfg, ex_class, p, &p);
5778 break;
5780 case MONO_PATCH_INFO_R4:
5781 encode_value (*((guint32 *)patch_info->data.target), p, &p);
5782 break;
5783 case MONO_PATCH_INFO_R8:
5784 encode_value (((guint32 *)patch_info->data.target) [MINI_LS_WORD_IDX], p, &p);
5785 encode_value (((guint32 *)patch_info->data.target) [MINI_MS_WORD_IDX], p, &p);
5786 break;
5787 case MONO_PATCH_INFO_VTABLE:
5788 case MONO_PATCH_INFO_CLASS:
5789 case MONO_PATCH_INFO_IID:
5790 case MONO_PATCH_INFO_ADJUSTED_IID:
5791 encode_klass_ref (acfg, patch_info->data.klass, p, &p);
5792 break;
5793 case MONO_PATCH_INFO_DELEGATE_TRAMPOLINE:
5794 encode_klass_ref (acfg, patch_info->data.del_tramp->klass, p, &p);
5795 if (patch_info->data.del_tramp->method) {
5796 encode_value (1, p, &p);
5797 encode_method_ref (acfg, patch_info->data.del_tramp->method, p, &p);
5798 } else {
5799 encode_value (0, p, &p);
5801 encode_value (patch_info->data.del_tramp->is_virtual, p, &p);
5802 break;
5803 case MONO_PATCH_INFO_FIELD:
5804 case MONO_PATCH_INFO_SFLDA:
5805 encode_field_info (acfg, patch_info->data.field, p, &p);
5806 break;
5807 case MONO_PATCH_INFO_INTERRUPTION_REQUEST_FLAG:
5808 break;
5809 case MONO_PATCH_INFO_RGCTX_FETCH:
5810 case MONO_PATCH_INFO_RGCTX_SLOT_INDEX: {
5811 MonoJumpInfoRgctxEntry *entry = patch_info->data.rgctx_entry;
5812 guint32 offset;
5813 guint8 *buf2, *p2;
5816 * entry->method has a lenghtly encoding and multiple rgctx_fetch entries
5817 * reference the same method, so encode the method only once.
5819 offset = GPOINTER_TO_UINT (g_hash_table_lookup (acfg->method_blob_hash, entry->method));
5820 if (!offset) {
5821 buf2 = (guint8 *)g_malloc (1024);
5822 p2 = buf2;
5824 encode_method_ref (acfg, entry->method, p2, &p2);
5825 g_assert (p2 - buf2 < 1024);
5827 offset = add_to_blob (acfg, buf2, p2 - buf2);
5828 g_free (buf2);
5830 g_hash_table_insert (acfg->method_blob_hash, entry->method, GUINT_TO_POINTER (offset + 1));
5831 } else {
5832 offset --;
5835 encode_value (offset, p, &p);
5836 g_assert ((int)entry->info_type < 256);
5837 g_assert (entry->data->type < 256);
5838 encode_value ((entry->in_mrgctx ? 1 : 0) | (entry->info_type << 1) | (entry->data->type << 9), p, &p);
5839 encode_patch (acfg, entry->data, p, &p);
5840 break;
5842 case MONO_PATCH_INFO_SEQ_POINT_INFO:
5843 case MONO_PATCH_INFO_AOT_MODULE:
5844 break;
5845 case MONO_PATCH_INFO_SIGNATURE:
5846 case MONO_PATCH_INFO_GSHAREDVT_IN_WRAPPER:
5847 encode_signature (acfg, (MonoMethodSignature*)patch_info->data.target, p, &p);
5848 break;
5849 case MONO_PATCH_INFO_GSHAREDVT_CALL:
5850 encode_signature (acfg, (MonoMethodSignature*)patch_info->data.gsharedvt->sig, p, &p);
5851 encode_method_ref (acfg, patch_info->data.gsharedvt->method, p, &p);
5852 break;
5853 case MONO_PATCH_INFO_GSHAREDVT_METHOD: {
5854 MonoGSharedVtMethodInfo *info = patch_info->data.gsharedvt_method;
5855 int i;
5857 encode_method_ref (acfg, info->method, p, &p);
5858 encode_value (info->num_entries, p, &p);
5859 for (i = 0; i < info->num_entries; ++i) {
5860 MonoRuntimeGenericContextInfoTemplate *template_ = &info->entries [i];
5862 encode_value (template_->info_type, p, &p);
5863 switch (mini_rgctx_info_type_to_patch_info_type (template_->info_type)) {
5864 case MONO_PATCH_INFO_CLASS:
5865 encode_klass_ref (acfg, mono_class_from_mono_type ((MonoType *)template_->data), p, &p);
5866 break;
5867 case MONO_PATCH_INFO_FIELD:
5868 encode_field_info (acfg, (MonoClassField *)template_->data, p, &p);
5869 break;
5870 default:
5871 g_assert_not_reached ();
5872 break;
5875 break;
5877 case MONO_PATCH_INFO_LDSTR_LIT: {
5878 const char *s = (const char *)patch_info->data.target;
5879 int len = strlen (s);
5881 encode_value (len, p, &p);
5882 memcpy (p, s, len + 1);
5883 p += len + 1;
5884 break;
5886 case MONO_PATCH_INFO_VIRT_METHOD:
5887 encode_klass_ref (acfg, patch_info->data.virt_method->klass, p, &p);
5888 encode_method_ref (acfg, patch_info->data.virt_method->method, p, &p);
5889 break;
5890 case MONO_PATCH_INFO_GC_SAFE_POINT_FLAG:
5891 case MONO_PATCH_INFO_JIT_THREAD_ATTACH:
5892 break;
5893 default:
5894 g_warning ("unable to handle jump info %d", patch_info->type);
5895 g_assert_not_reached ();
5898 *endbuf = p;
5901 static void
5902 encode_patch_list (MonoAotCompile *acfg, GPtrArray *patches, int n_patches, gboolean llvm, int first_got_offset, guint8 *buf, guint8 **endbuf)
5904 guint8 *p = buf;
5905 guint32 pindex, offset;
5906 MonoJumpInfo *patch_info;
5908 encode_value (n_patches, p, &p);
5910 for (pindex = 0; pindex < patches->len; ++pindex) {
5911 patch_info = (MonoJumpInfo *)g_ptr_array_index (patches, pindex);
5913 if (patch_info->type == MONO_PATCH_INFO_NONE || patch_info->type == MONO_PATCH_INFO_BB)
5914 /* Nothing to do */
5915 continue;
5917 offset = get_got_offset (acfg, llvm, patch_info);
5918 encode_value (offset, p, &p);
5921 *endbuf = p;
5924 static void
5925 emit_method_info (MonoAotCompile *acfg, MonoCompile *cfg)
5927 MonoMethod *method;
5928 int pindex, buf_size, n_patches;
5929 GPtrArray *patches;
5930 MonoJumpInfo *patch_info;
5931 guint32 method_index;
5932 guint8 *p, *buf;
5933 guint32 first_got_offset;
5935 method = cfg->orig_method;
5937 method_index = get_method_index (acfg, method);
5939 /* Sort relocations */
5940 patches = g_ptr_array_new ();
5941 for (patch_info = cfg->patch_info; patch_info; patch_info = patch_info->next)
5942 g_ptr_array_add (patches, patch_info);
5943 g_ptr_array_sort (patches, compare_patches);
5945 first_got_offset = acfg->cfgs [method_index]->got_offset;
5947 /**********************/
5948 /* Encode method info */
5949 /**********************/
5951 buf_size = (patches->len < 1000) ? 40960 : 40960 + (patches->len * 64);
5952 p = buf = (guint8 *)g_malloc (buf_size);
5954 if (mono_class_get_cctor (method->klass)) {
5955 encode_value (1, p, &p);
5956 encode_klass_ref (acfg, method->klass, p, &p);
5957 } else {
5958 /* Not needed when loading the method */
5959 encode_value (0, p, &p);
5962 g_assert (!(cfg->opt & MONO_OPT_SHARED));
5964 n_patches = 0;
5965 for (pindex = 0; pindex < patches->len; ++pindex) {
5966 patch_info = (MonoJumpInfo *)g_ptr_array_index (patches, pindex);
5968 if ((patch_info->type == MONO_PATCH_INFO_GOT_OFFSET) ||
5969 (patch_info->type == MONO_PATCH_INFO_NONE)) {
5970 patch_info->type = MONO_PATCH_INFO_NONE;
5971 /* Nothing to do */
5972 continue;
5975 if ((patch_info->type == MONO_PATCH_INFO_IMAGE) && (patch_info->data.image == acfg->image)) {
5976 /* Stored in a GOT slot initialized at module load time */
5977 patch_info->type = MONO_PATCH_INFO_NONE;
5978 continue;
5981 if (patch_info->type == MONO_PATCH_INFO_GC_CARD_TABLE_ADDR ||
5982 patch_info->type == MONO_PATCH_INFO_GC_NURSERY_START ||
5983 patch_info->type == MONO_PATCH_INFO_GC_NURSERY_BITS ||
5984 patch_info->type == MONO_PATCH_INFO_AOT_MODULE) {
5985 /* Stored in a GOT slot initialized at module load time */
5986 patch_info->type = MONO_PATCH_INFO_NONE;
5987 continue;
5990 if (is_plt_patch (patch_info) && !(cfg->compile_llvm && acfg->aot_opts.llvm_only)) {
5991 /* Calls are made through the PLT */
5992 patch_info->type = MONO_PATCH_INFO_NONE;
5993 continue;
5996 n_patches ++;
5999 if (n_patches)
6000 g_assert (cfg->has_got_slots);
6002 encode_patch_list (acfg, patches, n_patches, cfg->compile_llvm, first_got_offset, p, &p);
6004 g_ptr_array_free (patches, TRUE);
6006 acfg->stats.info_size += p - buf;
6008 g_assert (p - buf < buf_size);
6010 cfg->method_info_offset = add_to_blob (acfg, buf, p - buf);
6011 g_free (buf);
6014 static guint32
6015 get_unwind_info_offset (MonoAotCompile *acfg, guint8 *encoded, guint32 encoded_len)
6017 guint32 cache_index;
6018 guint32 offset;
6020 /* Reuse the unwind module to canonize and store unwind info entries */
6021 cache_index = mono_cache_unwind_info (encoded, encoded_len);
6023 /* Use +/- 1 to distinguish 0s from missing entries */
6024 offset = GPOINTER_TO_UINT (g_hash_table_lookup (acfg->unwind_info_offsets, GUINT_TO_POINTER (cache_index + 1)));
6025 if (offset)
6026 return offset - 1;
6027 else {
6028 guint8 buf [16];
6029 guint8 *p;
6032 * It would be easier to use assembler symbols, but the caller needs an
6033 * offset now.
6035 offset = acfg->unwind_info_offset;
6036 g_hash_table_insert (acfg->unwind_info_offsets, GUINT_TO_POINTER (cache_index + 1), GUINT_TO_POINTER (offset + 1));
6037 g_ptr_array_add (acfg->unwind_ops, GUINT_TO_POINTER (cache_index));
6039 p = buf;
6040 encode_value (encoded_len, p, &p);
6042 acfg->unwind_info_offset += encoded_len + (p - buf);
6043 return offset;
6047 static void
6048 emit_exception_debug_info (MonoAotCompile *acfg, MonoCompile *cfg, gboolean store_seq_points)
6050 int i, k, buf_size;
6051 guint32 debug_info_size, seq_points_size;
6052 guint8 *code;
6053 MonoMethodHeader *header;
6054 guint8 *p, *buf, *debug_info;
6055 MonoJitInfo *jinfo = cfg->jit_info;
6056 guint32 flags;
6057 gboolean use_unwind_ops = FALSE;
6058 MonoSeqPointInfo *seq_points;
6060 code = cfg->native_code;
6061 header = cfg->header;
6063 if (!acfg->aot_opts.nodebug) {
6064 mono_debug_serialize_debug_info (cfg, &debug_info, &debug_info_size);
6065 } else {
6066 debug_info = NULL;
6067 debug_info_size = 0;
6070 seq_points = cfg->seq_point_info;
6071 seq_points_size = (store_seq_points)? mono_seq_point_info_get_write_size (seq_points) : 0;
6073 buf_size = header->num_clauses * 256 + debug_info_size + 2048 + seq_points_size + cfg->gc_map_size;
6075 p = buf = (guint8 *)g_malloc (buf_size);
6077 use_unwind_ops = cfg->unwind_ops != NULL;
6079 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);
6081 encode_value (flags, p, &p);
6083 if (use_unwind_ops) {
6084 guint32 encoded_len;
6085 guint8 *encoded;
6086 guint32 unwind_desc;
6088 encoded = mono_unwind_ops_encode (cfg->unwind_ops, &encoded_len);
6090 unwind_desc = get_unwind_info_offset (acfg, encoded, encoded_len);
6091 encode_value (unwind_desc, p, &p);
6093 g_free (encoded);
6094 } else {
6095 encode_value (jinfo->unwind_info, p, &p);
6098 /*Encode the number of holes before the number of clauses to make decoding easier*/
6099 if (jinfo->has_try_block_holes) {
6100 MonoTryBlockHoleTableJitInfo *table = mono_jit_info_get_try_block_hole_table_info (jinfo);
6101 encode_value (table->num_holes, p, &p);
6104 if (jinfo->has_arch_eh_info) {
6106 * In AOT mode, the code length is calculated from the address of the previous method,
6107 * which could include alignment padding, so calculating the start of the epilog as
6108 * code_len - epilog_size is correct any more. Save the real code len as a workaround.
6110 encode_value (jinfo->code_size, p, &p);
6113 /* Exception table */
6114 if (cfg->compile_llvm) {
6116 * When using LLVM, we can't emit some data, like pc offsets, this reg/offset etc.,
6117 * since the information is only available to llc. Instead, we let llc save the data
6118 * into the LSDA, and read it from there at runtime.
6120 /* The assembly might be CIL stripped so emit the data ourselves */
6121 if (header->num_clauses)
6122 encode_value (header->num_clauses, p, &p);
6124 for (k = 0; k < header->num_clauses; ++k) {
6125 MonoExceptionClause *clause;
6127 clause = &header->clauses [k];
6129 encode_value (clause->flags, p, &p);
6130 if (clause->data.catch_class) {
6131 encode_value (1, p, &p);
6132 encode_klass_ref (acfg, clause->data.catch_class, p, &p);
6133 } else {
6134 encode_value (0, p, &p);
6137 /* Emit the IL ranges too, since they might not be available at runtime */
6138 encode_value (clause->try_offset, p, &p);
6139 encode_value (clause->try_len, p, &p);
6140 encode_value (clause->handler_offset, p, &p);
6141 encode_value (clause->handler_len, p, &p);
6143 /* Emit a list of nesting clauses */
6144 for (i = 0; i < header->num_clauses; ++i) {
6145 gint32 cindex1 = k;
6146 MonoExceptionClause *clause1 = &header->clauses [cindex1];
6147 gint32 cindex2 = i;
6148 MonoExceptionClause *clause2 = &header->clauses [cindex2];
6150 if (cindex1 != cindex2 && clause1->try_offset >= clause2->try_offset && clause1->handler_offset <= clause2->handler_offset)
6151 encode_value (i, p, &p);
6153 encode_value (-1, p, &p);
6155 } else {
6156 if (jinfo->num_clauses)
6157 encode_value (jinfo->num_clauses, p, &p);
6159 for (k = 0; k < jinfo->num_clauses; ++k) {
6160 MonoJitExceptionInfo *ei = &jinfo->clauses [k];
6162 encode_value (ei->flags, p, &p);
6163 #ifdef MONO_CONTEXT_SET_LLVM_EXC_REG
6164 /* Not used for catch clauses */
6165 if (ei->flags != MONO_EXCEPTION_CLAUSE_NONE)
6166 encode_value (ei->exvar_offset, p, &p);
6167 #else
6168 encode_value (ei->exvar_offset, p, &p);
6169 #endif
6171 if (ei->flags == MONO_EXCEPTION_CLAUSE_FILTER || ei->flags == MONO_EXCEPTION_CLAUSE_FINALLY)
6172 encode_value ((gint)((guint8*)ei->data.filter - code), p, &p);
6173 else {
6174 if (ei->data.catch_class) {
6175 guint8 *buf2, *p2;
6176 int len;
6178 buf2 = (guint8 *)g_malloc (4096);
6179 p2 = buf2;
6180 encode_klass_ref (acfg, ei->data.catch_class, p2, &p2);
6181 len = p2 - buf2;
6182 g_assert (len < 4096);
6183 encode_value (len, p, &p);
6184 memcpy (p, buf2, len);
6185 p += p2 - buf2;
6186 g_free (buf2);
6187 } else {
6188 encode_value (0, p, &p);
6192 encode_value ((gint)((guint8*)ei->try_start - code), p, &p);
6193 encode_value ((gint)((guint8*)ei->try_end - code), p, &p);
6194 encode_value ((gint)((guint8*)ei->handler_start - code), p, &p);
6198 if (jinfo->has_try_block_holes) {
6199 MonoTryBlockHoleTableJitInfo *table = mono_jit_info_get_try_block_hole_table_info (jinfo);
6200 for (i = 0; i < table->num_holes; ++i) {
6201 MonoTryBlockHoleJitInfo *hole = &table->holes [i];
6202 encode_value (hole->clause, p, &p);
6203 encode_value (hole->length, p, &p);
6204 encode_value (hole->offset, p, &p);
6208 if (jinfo->has_arch_eh_info) {
6209 MonoArchEHJitInfo *eh_info;
6211 eh_info = mono_jit_info_get_arch_eh_info (jinfo);
6212 encode_value (eh_info->stack_size, p, &p);
6213 encode_value (eh_info->epilog_size, p, &p);
6216 if (jinfo->has_generic_jit_info) {
6217 MonoGenericJitInfo *gi = mono_jit_info_get_generic_jit_info (jinfo);
6218 MonoGenericSharingContext* gsctx = gi->generic_sharing_context;
6219 guint8 *buf2, *p2;
6220 int len;
6222 encode_value (gi->nlocs, p, &p);
6223 if (gi->nlocs) {
6224 for (i = 0; i < gi->nlocs; ++i) {
6225 MonoDwarfLocListEntry *entry = &gi->locations [i];
6227 encode_value (entry->is_reg ? 1 : 0, p, &p);
6228 encode_value (entry->reg, p, &p);
6229 if (!entry->is_reg)
6230 encode_value (entry->offset, p, &p);
6231 if (i == 0)
6232 g_assert (entry->from == 0);
6233 else
6234 encode_value (entry->from, p, &p);
6235 encode_value (entry->to, p, &p);
6237 } else {
6238 if (!cfg->compile_llvm) {
6239 encode_value (gi->has_this ? 1 : 0, p, &p);
6240 encode_value (gi->this_reg, p, &p);
6241 encode_value (gi->this_offset, p, &p);
6246 * Need to encode jinfo->method too, since it is not equal to 'method'
6247 * when using generic sharing.
6249 buf2 = (guint8 *)g_malloc (4096);
6250 p2 = buf2;
6251 encode_method_ref (acfg, jinfo->d.method, p2, &p2);
6252 len = p2 - buf2;
6253 g_assert (len < 4096);
6254 encode_value (len, p, &p);
6255 memcpy (p, buf2, len);
6256 p += p2 - buf2;
6257 g_free (buf2);
6259 if (gsctx && gsctx->is_gsharedvt) {
6260 encode_value (1, p, &p);
6261 } else {
6262 encode_value (0, p, &p);
6266 if (seq_points_size)
6267 p += mono_seq_point_info_write (seq_points, p);
6269 g_assert (debug_info_size < buf_size);
6271 encode_value (debug_info_size, p, &p);
6272 if (debug_info_size) {
6273 memcpy (p, debug_info, debug_info_size);
6274 p += debug_info_size;
6275 g_free (debug_info);
6278 /* GC Map */
6279 if (cfg->gc_map) {
6280 encode_value (cfg->gc_map_size, p, &p);
6281 /* The GC map requires 4 bytes of alignment */
6282 while ((gsize)p % 4)
6283 p ++;
6284 memcpy (p, cfg->gc_map, cfg->gc_map_size);
6285 p += cfg->gc_map_size;
6288 acfg->stats.ex_info_size += p - buf;
6290 g_assert (p - buf < buf_size);
6292 /* Emit info */
6293 /* The GC Map requires 4 byte alignment */
6294 cfg->ex_info_offset = add_to_blob_aligned (acfg, buf, p - buf, cfg->gc_map ? 4 : 1);
6295 g_free (buf);
6298 static guint32
6299 emit_klass_info (MonoAotCompile *acfg, guint32 token)
6301 MonoError error;
6302 MonoClass *klass = mono_class_get_checked (acfg->image, token, &error);
6303 guint8 *p, *buf;
6304 int i, buf_size, res;
6305 gboolean no_special_static, cant_encode;
6306 gpointer iter = NULL;
6308 if (!klass) {
6309 mono_error_cleanup (&error);
6311 buf_size = 16;
6313 p = buf = (guint8 *)g_malloc (buf_size);
6315 /* Mark as unusable */
6316 encode_value (-1, p, &p);
6318 res = add_to_blob (acfg, buf, p - buf);
6319 g_free (buf);
6321 return res;
6324 buf_size = 10240 + (klass->vtable_size * 16);
6325 p = buf = (guint8 *)g_malloc (buf_size);
6327 g_assert (klass);
6329 mono_class_init (klass);
6331 mono_class_get_nested_types (klass, &iter);
6332 g_assert (klass->nested_classes_inited);
6334 mono_class_setup_vtable (klass);
6337 * Emit all the information which is required for creating vtables so
6338 * the runtime does not need to create the MonoMethod structures which
6339 * take up a lot of space.
6342 no_special_static = !mono_class_has_special_static_fields (klass);
6344 /* Check whenever we have enough info to encode the vtable */
6345 cant_encode = FALSE;
6346 for (i = 0; i < klass->vtable_size; ++i) {
6347 MonoMethod *cm = klass->vtable [i];
6349 if (cm && mono_method_signature (cm)->is_inflated && !g_hash_table_lookup (acfg->token_info_hash, cm))
6350 cant_encode = TRUE;
6353 mono_class_has_finalizer (klass);
6354 if (mono_class_has_failure (klass))
6355 cant_encode = TRUE;
6357 if (mono_class_is_gtd (klass) || cant_encode) {
6358 encode_value (-1, p, &p);
6359 } else {
6360 gboolean has_nested = mono_class_get_nested_classes_property (klass) != NULL;
6361 encode_value (klass->vtable_size, p, &p);
6362 encode_value ((mono_class_is_gtd (klass) ? (1 << 8) : 0) | (no_special_static << 7) | (klass->has_static_refs << 6) | (klass->has_references << 5) | ((klass->blittable << 4) | (has_nested ? 1 : 0) << 3) | (klass->has_cctor << 2) | (klass->has_finalize << 1) | klass->ghcimpl, p, &p);
6363 if (klass->has_cctor)
6364 encode_method_ref (acfg, mono_class_get_cctor (klass), p, &p);
6365 if (klass->has_finalize)
6366 encode_method_ref (acfg, mono_class_get_finalizer (klass), p, &p);
6368 encode_value (klass->instance_size, p, &p);
6369 encode_value (mono_class_data_size (klass), p, &p);
6370 encode_value (klass->packing_size, p, &p);
6371 encode_value (klass->min_align, p, &p);
6373 for (i = 0; i < klass->vtable_size; ++i) {
6374 MonoMethod *cm = klass->vtable [i];
6376 if (cm)
6377 encode_method_ref (acfg, cm, p, &p);
6378 else
6379 encode_value (0, p, &p);
6383 acfg->stats.class_info_size += p - buf;
6385 g_assert (p - buf < buf_size);
6386 res = add_to_blob (acfg, buf, p - buf);
6387 g_free (buf);
6389 return res;
6392 static char*
6393 get_plt_entry_debug_sym (MonoAotCompile *acfg, MonoJumpInfo *ji, GHashTable *cache)
6395 char *debug_sym = NULL;
6396 char *prefix;
6398 if (acfg->llvm && llvm_acfg->aot_opts.static_link) {
6399 /* Need to add a prefix to create unique symbols */
6400 prefix = g_strdup_printf ("plt_%s_", acfg->assembly_name_sym);
6401 } else {
6402 #if defined(TARGET_WIN32) && defined(TARGET_X86)
6403 prefix = mangle_symbol_alloc ("plt_");
6404 #else
6405 prefix = g_strdup ("plt_");
6406 #endif
6409 switch (ji->type) {
6410 case MONO_PATCH_INFO_METHOD:
6411 debug_sym = get_debug_sym (ji->data.method, prefix, cache);
6412 break;
6413 case MONO_PATCH_INFO_INTERNAL_METHOD:
6414 debug_sym = g_strdup_printf ("%s_jit_icall_%s", prefix, ji->data.name);
6415 break;
6416 case MONO_PATCH_INFO_RGCTX_FETCH:
6417 debug_sym = g_strdup_printf ("%s_rgctx_fetch_%d", prefix, acfg->label_generator ++);
6418 break;
6419 case MONO_PATCH_INFO_ICALL_ADDR:
6420 case MONO_PATCH_INFO_ICALL_ADDR_CALL: {
6421 char *s = get_debug_sym (ji->data.method, "", cache);
6423 debug_sym = g_strdup_printf ("%s_icall_native_%s", prefix, s);
6424 g_free (s);
6425 break;
6427 case MONO_PATCH_INFO_JIT_ICALL_ADDR:
6428 debug_sym = g_strdup_printf ("%s_jit_icall_native_%s", prefix, ji->data.name);
6429 break;
6430 default:
6431 break;
6434 g_free (prefix);
6436 return sanitize_symbol (acfg, debug_sym);
6440 * Calls made from AOTed code are routed through a table of jumps similar to the
6441 * ELF PLT (Program Linkage Table). Initially the PLT entries jump to code which transfers
6442 * control to the AOT runtime through a trampoline.
6444 static void
6445 emit_plt (MonoAotCompile *acfg)
6447 int i;
6449 if (acfg->aot_opts.llvm_only) {
6450 g_assert (acfg->plt_offset == 1);
6451 return;
6454 emit_line (acfg);
6456 emit_section_change (acfg, ".text", 0);
6457 emit_alignment_code (acfg, 16);
6458 emit_info_symbol (acfg, "plt");
6459 emit_label (acfg, acfg->plt_symbol);
6461 for (i = 0; i < acfg->plt_offset; ++i) {
6462 char *debug_sym = NULL;
6463 MonoPltEntry *plt_entry = NULL;
6465 if (i == 0)
6467 * The first plt entry is unused.
6469 continue;
6471 plt_entry = (MonoPltEntry *)g_hash_table_lookup (acfg->plt_offset_to_entry, GUINT_TO_POINTER (i));
6473 debug_sym = plt_entry->debug_sym;
6475 if (acfg->thumb_mixed && !plt_entry->jit_used)
6476 /* Emit only a thumb version */
6477 continue;
6479 /* Skip plt entries not actually called */
6480 if (!plt_entry->jit_used && !plt_entry->llvm_used)
6481 continue;
6483 if (acfg->llvm && !acfg->thumb_mixed) {
6484 emit_label (acfg, plt_entry->llvm_symbol);
6485 if (acfg->llvm) {
6486 emit_global_inner (acfg, plt_entry->llvm_symbol, TRUE);
6487 #if defined(TARGET_MACH)
6488 fprintf (acfg->fp, ".private_extern %s\n", plt_entry->llvm_symbol);
6489 #endif
6493 if (debug_sym) {
6494 if (acfg->need_no_dead_strip) {
6495 emit_unset_mode (acfg);
6496 fprintf (acfg->fp, " .no_dead_strip %s\n", debug_sym);
6498 emit_local_symbol (acfg, debug_sym, NULL, TRUE);
6499 emit_label (acfg, debug_sym);
6502 emit_label (acfg, plt_entry->symbol);
6504 arch_emit_plt_entry (acfg, acfg->got_symbol, (acfg->plt_got_offset_base + i) * sizeof (gpointer), acfg->plt_got_info_offsets [i]);
6506 if (debug_sym)
6507 emit_symbol_size (acfg, debug_sym, ".");
6510 if (acfg->thumb_mixed) {
6511 /* Make sure the ARM symbols don't alias the thumb ones */
6512 emit_zero_bytes (acfg, 16);
6515 * Emit a separate set of PLT entries using thumb2 which is called by LLVM generated
6516 * code.
6518 for (i = 0; i < acfg->plt_offset; ++i) {
6519 char *debug_sym = NULL;
6520 MonoPltEntry *plt_entry = NULL;
6522 if (i == 0)
6523 continue;
6525 plt_entry = (MonoPltEntry *)g_hash_table_lookup (acfg->plt_offset_to_entry, GUINT_TO_POINTER (i));
6527 /* Skip plt entries not actually called by LLVM code */
6528 if (!plt_entry->llvm_used)
6529 continue;
6531 if (acfg->aot_opts.write_symbols) {
6532 if (plt_entry->debug_sym)
6533 debug_sym = g_strdup_printf ("%s_thumb", plt_entry->debug_sym);
6536 if (debug_sym) {
6537 #if defined(TARGET_MACH)
6538 fprintf (acfg->fp, " .thumb_func %s\n", debug_sym);
6539 fprintf (acfg->fp, " .no_dead_strip %s\n", debug_sym);
6540 #endif
6541 emit_local_symbol (acfg, debug_sym, NULL, TRUE);
6542 emit_label (acfg, debug_sym);
6544 fprintf (acfg->fp, "\n.thumb_func\n");
6546 emit_label (acfg, plt_entry->llvm_symbol);
6548 if (acfg->llvm)
6549 emit_global_inner (acfg, plt_entry->llvm_symbol, TRUE);
6551 arch_emit_llvm_plt_entry (acfg, acfg->got_symbol, (acfg->plt_got_offset_base + i) * sizeof (gpointer), acfg->plt_got_info_offsets [i]);
6553 if (debug_sym) {
6554 emit_symbol_size (acfg, debug_sym, ".");
6555 g_free (debug_sym);
6560 emit_symbol_size (acfg, acfg->plt_symbol, ".");
6562 emit_info_symbol (acfg, "plt_end");
6566 * emit_trampoline_full:
6568 * If EMIT_TINFO is TRUE, emit additional information which can be used to create a MonoJitInfo for this trampoline by
6569 * create_jit_info_for_trampoline ().
6571 static G_GNUC_UNUSED void
6572 emit_trampoline_full (MonoAotCompile *acfg, int got_offset, MonoTrampInfo *info, gboolean emit_tinfo)
6574 char start_symbol [MAX_SYMBOL_SIZE];
6575 char end_symbol [MAX_SYMBOL_SIZE];
6576 char symbol [MAX_SYMBOL_SIZE];
6577 guint32 buf_size, info_offset;
6578 MonoJumpInfo *patch_info;
6579 guint8 *buf, *p;
6580 GPtrArray *patches;
6581 char *name;
6582 guint8 *code;
6583 guint32 code_size;
6584 MonoJumpInfo *ji;
6585 GSList *unwind_ops;
6587 g_assert (info);
6589 name = info->name;
6590 code = info->code;
6591 code_size = info->code_size;
6592 ji = info->ji;
6593 unwind_ops = info->unwind_ops;
6595 /* Emit code */
6597 sprintf (start_symbol, "%s%s", acfg->user_symbol_prefix, name);
6599 emit_section_change (acfg, ".text", 0);
6600 emit_global (acfg, start_symbol, TRUE);
6601 emit_alignment_code (acfg, AOT_FUNC_ALIGNMENT);
6602 emit_label (acfg, start_symbol);
6604 sprintf (symbol, "%snamed_%s", acfg->temp_prefix, name);
6605 emit_label (acfg, symbol);
6608 * The code should access everything through the GOT, so we pass
6609 * TRUE here.
6611 emit_and_reloc_code (acfg, NULL, code, code_size, ji, TRUE, NULL);
6613 emit_symbol_size (acfg, start_symbol, ".");
6615 if (emit_tinfo) {
6616 sprintf (end_symbol, "%snamede_%s", acfg->temp_prefix, name);
6617 emit_label (acfg, end_symbol);
6620 /* Emit info */
6622 /* Sort relocations */
6623 patches = g_ptr_array_new ();
6624 for (patch_info = ji; patch_info; patch_info = patch_info->next)
6625 if (patch_info->type != MONO_PATCH_INFO_NONE)
6626 g_ptr_array_add (patches, patch_info);
6627 g_ptr_array_sort (patches, compare_patches);
6629 buf_size = patches->len * 128 + 128;
6630 buf = (guint8 *)g_malloc (buf_size);
6631 p = buf;
6633 encode_patch_list (acfg, patches, patches->len, FALSE, got_offset, p, &p);
6634 g_assert (p - buf < buf_size);
6635 g_ptr_array_free (patches, TRUE);
6637 sprintf (symbol, "%s%s_p", acfg->user_symbol_prefix, name);
6639 info_offset = add_to_blob (acfg, buf, p - buf);
6641 emit_section_change (acfg, RODATA_SECT, 0);
6642 emit_global (acfg, symbol, FALSE);
6643 emit_label (acfg, symbol);
6645 emit_int32 (acfg, info_offset);
6647 if (emit_tinfo) {
6648 guint8 *encoded;
6649 guint32 encoded_len;
6650 guint32 uw_offset;
6653 * Emit additional information which can be used to reconstruct a partial MonoTrampInfo.
6655 encoded = mono_unwind_ops_encode (info->unwind_ops, &encoded_len);
6656 uw_offset = get_unwind_info_offset (acfg, encoded, encoded_len);
6657 g_free (encoded);
6659 emit_symbol_diff (acfg, end_symbol, start_symbol, 0);
6660 emit_int32 (acfg, uw_offset);
6663 /* Emit debug info */
6664 if (unwind_ops) {
6665 char symbol2 [MAX_SYMBOL_SIZE];
6667 sprintf (symbol, "%s", name);
6668 sprintf (symbol2, "%snamed_%s", acfg->temp_prefix, name);
6670 if (acfg->dwarf)
6671 mono_dwarf_writer_emit_trampoline (acfg->dwarf, symbol, symbol2, NULL, NULL, code_size, unwind_ops);
6674 g_free (buf);
6677 static G_GNUC_UNUSED void
6678 emit_trampoline (MonoAotCompile *acfg, int got_offset, MonoTrampInfo *info)
6680 emit_trampoline_full (acfg, got_offset, info, TRUE);
6683 static void
6684 emit_trampolines (MonoAotCompile *acfg)
6686 char symbol [MAX_SYMBOL_SIZE];
6687 char end_symbol [MAX_SYMBOL_SIZE];
6688 int i, tramp_got_offset;
6689 int ntype;
6690 #ifdef MONO_ARCH_HAVE_FULL_AOT_TRAMPOLINES
6691 int tramp_type;
6692 #endif
6694 if (!mono_aot_mode_is_full (&acfg->aot_opts) || acfg->aot_opts.llvm_only)
6695 return;
6697 g_assert (acfg->image->assembly);
6699 /* Currently, we emit most trampolines into the mscorlib AOT image. */
6700 if (strcmp (acfg->image->assembly->aname.name, "mscorlib") == 0) {
6701 #ifdef MONO_ARCH_HAVE_FULL_AOT_TRAMPOLINES
6702 MonoTrampInfo *info;
6705 * Emit the generic trampolines.
6707 * We could save some code by treating the generic trampolines as a wrapper
6708 * method, but that approach has its own complexities, so we choose the simpler
6709 * method.
6711 for (tramp_type = 0; tramp_type < MONO_TRAMPOLINE_NUM; ++tramp_type) {
6712 /* we overload the boolean here to indicate the slightly different trampoline needed, see mono_arch_create_generic_trampoline() */
6713 #ifdef DISABLE_REMOTING
6714 if (tramp_type == MONO_TRAMPOLINE_GENERIC_VIRTUAL_REMOTING)
6715 continue;
6716 #endif
6717 #ifndef MONO_ARCH_HAVE_HANDLER_BLOCK_GUARD
6718 if (tramp_type == MONO_TRAMPOLINE_HANDLER_BLOCK_GUARD)
6719 continue;
6720 #endif
6721 mono_arch_create_generic_trampoline ((MonoTrampolineType)tramp_type, &info, acfg->aot_opts.use_trampolines_page? 2: TRUE);
6722 emit_trampoline (acfg, acfg->got_offset, info);
6725 /* Emit the exception related code pieces */
6726 mono_arch_get_restore_context (&info, TRUE);
6727 emit_trampoline (acfg, acfg->got_offset, info);
6728 mono_arch_get_call_filter (&info, TRUE);
6729 emit_trampoline (acfg, acfg->got_offset, info);
6730 mono_arch_get_throw_exception (&info, TRUE);
6731 emit_trampoline (acfg, acfg->got_offset, info);
6732 mono_arch_get_rethrow_exception (&info, TRUE);
6733 emit_trampoline (acfg, acfg->got_offset, info);
6734 mono_arch_get_throw_corlib_exception (&info, TRUE);
6735 emit_trampoline (acfg, acfg->got_offset, info);
6737 #ifdef MONO_ARCH_HAVE_SDB_TRAMPOLINES
6738 mono_arch_create_sdb_trampoline (TRUE, &info, TRUE);
6739 emit_trampoline (acfg, acfg->got_offset, info);
6740 mono_arch_create_sdb_trampoline (FALSE, &info, TRUE);
6741 emit_trampoline (acfg, acfg->got_offset, info);
6742 #endif
6744 #ifdef MONO_ARCH_GSHAREDVT_SUPPORTED
6745 mono_arch_get_gsharedvt_trampoline (&info, TRUE);
6746 if (info) {
6747 emit_trampoline_full (acfg, acfg->got_offset, info, TRUE);
6749 /* Create a separate out trampoline for more information in stack traces */
6750 info->name = g_strdup ("gsharedvt_out_trampoline");
6751 emit_trampoline_full (acfg, acfg->got_offset, info, TRUE);
6753 #endif
6755 #if defined(MONO_ARCH_HAVE_GET_TRAMPOLINES)
6757 GSList *l = mono_arch_get_trampolines (TRUE);
6759 while (l) {
6760 MonoTrampInfo *info = (MonoTrampInfo *)l->data;
6762 emit_trampoline (acfg, acfg->got_offset, info);
6763 l = l->next;
6766 #endif
6768 for (i = 0; i < acfg->aot_opts.nrgctx_fetch_trampolines; ++i) {
6769 int offset;
6771 offset = MONO_RGCTX_SLOT_MAKE_RGCTX (i);
6772 mono_arch_create_rgctx_lazy_fetch_trampoline (offset, &info, TRUE);
6773 emit_trampoline (acfg, acfg->got_offset, info);
6774 g_free (info);
6776 offset = MONO_RGCTX_SLOT_MAKE_MRGCTX (i);
6777 mono_arch_create_rgctx_lazy_fetch_trampoline (offset, &info, TRUE);
6778 emit_trampoline (acfg, acfg->got_offset, info);
6779 g_free (info);
6782 #ifdef MONO_ARCH_HAVE_GENERAL_RGCTX_LAZY_FETCH_TRAMPOLINE
6783 mono_arch_create_general_rgctx_lazy_fetch_trampoline (&info, TRUE);
6784 emit_trampoline (acfg, acfg->got_offset, info);
6785 #endif
6788 GSList *l;
6790 /* delegate_invoke_impl trampolines */
6791 l = mono_arch_get_delegate_invoke_impls ();
6792 while (l) {
6793 MonoTrampInfo *info = (MonoTrampInfo *)l->data;
6795 emit_trampoline (acfg, acfg->got_offset, info);
6796 l = l->next;
6800 #ifdef MONO_ARCH_HAVE_HANDLER_BLOCK_GUARD_AOT
6801 mono_arch_create_handler_block_trampoline (&info, TRUE);
6802 emit_trampoline (acfg, acfg->got_offset, info);
6803 #endif
6805 #endif /* #ifdef MONO_ARCH_HAVE_FULL_AOT_TRAMPOLINES */
6807 /* Emit trampolines which are numerous */
6810 * These include the following:
6811 * - specific trampolines
6812 * - static rgctx invoke trampolines
6813 * - imt trampolines
6814 * These trampolines have the same code, they are parameterized by GOT
6815 * slots.
6816 * They are defined in this file, in the arch_... routines instead of
6817 * in tramp-<ARCH>.c, since it is easier to do it this way.
6821 * When running in aot-only mode, we can't create specific trampolines at
6822 * runtime, so we create a few, and save them in the AOT file.
6823 * Normal trampolines embed their argument as a literal inside the
6824 * trampoline code, we can't do that here, so instead we embed an offset
6825 * which needs to be added to the trampoline address to get the address of
6826 * the GOT slot which contains the argument value.
6827 * The generated trampolines jump to the generic trampolines using another
6828 * GOT slot, which will be setup by the AOT loader to point to the
6829 * generic trampoline code of the given type.
6833 * FIXME: Maybe we should use more specific trampolines (i.e. one class init for
6834 * each class).
6837 emit_section_change (acfg, ".text", 0);
6839 tramp_got_offset = acfg->got_offset;
6841 for (ntype = 0; ntype < MONO_AOT_TRAMP_NUM; ++ntype) {
6842 switch (ntype) {
6843 case MONO_AOT_TRAMP_SPECIFIC:
6844 sprintf (symbol, "specific_trampolines");
6845 break;
6846 case MONO_AOT_TRAMP_STATIC_RGCTX:
6847 sprintf (symbol, "static_rgctx_trampolines");
6848 break;
6849 case MONO_AOT_TRAMP_IMT:
6850 sprintf (symbol, "imt_trampolines");
6851 break;
6852 case MONO_AOT_TRAMP_GSHAREDVT_ARG:
6853 sprintf (symbol, "gsharedvt_arg_trampolines");
6854 break;
6855 default:
6856 g_assert_not_reached ();
6859 sprintf (end_symbol, "%s_e", symbol);
6861 if (acfg->aot_opts.write_symbols)
6862 emit_local_symbol (acfg, symbol, end_symbol, TRUE);
6864 emit_alignment_code (acfg, AOT_FUNC_ALIGNMENT);
6865 emit_info_symbol (acfg, symbol);
6867 acfg->trampoline_got_offset_base [ntype] = tramp_got_offset;
6869 for (i = 0; i < acfg->num_trampolines [ntype]; ++i) {
6870 int tramp_size = 0;
6872 switch (ntype) {
6873 case MONO_AOT_TRAMP_SPECIFIC:
6874 arch_emit_specific_trampoline (acfg, tramp_got_offset, &tramp_size);
6875 tramp_got_offset += 2;
6876 break;
6877 case MONO_AOT_TRAMP_STATIC_RGCTX:
6878 arch_emit_static_rgctx_trampoline (acfg, tramp_got_offset, &tramp_size);
6879 tramp_got_offset += 2;
6880 break;
6881 case MONO_AOT_TRAMP_IMT:
6882 arch_emit_imt_trampoline (acfg, tramp_got_offset, &tramp_size);
6883 tramp_got_offset += 1;
6884 break;
6885 case MONO_AOT_TRAMP_GSHAREDVT_ARG:
6886 arch_emit_gsharedvt_arg_trampoline (acfg, tramp_got_offset, &tramp_size);
6887 tramp_got_offset += 2;
6888 break;
6889 default:
6890 g_assert_not_reached ();
6892 if (!acfg->trampoline_size [ntype]) {
6893 g_assert (tramp_size);
6894 acfg->trampoline_size [ntype] = tramp_size;
6898 emit_label (acfg, end_symbol);
6899 emit_int32 (acfg, 0);
6902 arch_emit_specific_trampoline_pages (acfg);
6904 /* Reserve some entries at the end of the GOT for our use */
6905 acfg->num_trampoline_got_entries = tramp_got_offset - acfg->got_offset;
6908 acfg->got_offset += acfg->num_trampoline_got_entries;
6911 static gboolean
6912 str_begins_with (const char *str1, const char *str2)
6914 int len = strlen (str2);
6915 return strncmp (str1, str2, len) == 0;
6918 void*
6919 mono_aot_readonly_field_override (MonoClassField *field)
6921 ReadOnlyValue *rdv;
6922 for (rdv = readonly_values; rdv; rdv = rdv->next) {
6923 char *p = rdv->name;
6924 int len;
6925 len = strlen (field->parent->name_space);
6926 if (strncmp (p, field->parent->name_space, len))
6927 continue;
6928 p += len;
6929 if (*p++ != '.')
6930 continue;
6931 len = strlen (field->parent->name);
6932 if (strncmp (p, field->parent->name, len))
6933 continue;
6934 p += len;
6935 if (*p++ != '.')
6936 continue;
6937 if (strcmp (p, field->name))
6938 continue;
6939 switch (rdv->type) {
6940 case MONO_TYPE_I1:
6941 return &rdv->value.i1;
6942 case MONO_TYPE_I2:
6943 return &rdv->value.i2;
6944 case MONO_TYPE_I4:
6945 return &rdv->value.i4;
6946 default:
6947 break;
6950 return NULL;
6953 static void
6954 add_readonly_value (MonoAotOptions *opts, const char *val)
6956 ReadOnlyValue *rdv;
6957 const char *fval;
6958 const char *tval;
6959 /* the format of val is:
6960 * namespace.typename.fieldname=type/value
6961 * type can be i1 for uint8/int8/boolean, i2 for uint16/int16/char, i4 for uint32/int32
6963 fval = strrchr (val, '/');
6964 if (!fval) {
6965 fprintf (stderr, "AOT : invalid format for readonly field '%s', missing /.\n", val);
6966 exit (1);
6968 tval = strrchr (val, '=');
6969 if (!tval) {
6970 fprintf (stderr, "AOT : invalid format for readonly field '%s', missing =.\n", val);
6971 exit (1);
6973 rdv = g_new0 (ReadOnlyValue, 1);
6974 rdv->name = (char *)g_malloc0 (tval - val + 1);
6975 memcpy (rdv->name, val, tval - val);
6976 tval++;
6977 fval++;
6978 if (strncmp (tval, "i1", 2) == 0) {
6979 rdv->value.i1 = atoi (fval);
6980 rdv->type = MONO_TYPE_I1;
6981 } else if (strncmp (tval, "i2", 2) == 0) {
6982 rdv->value.i2 = atoi (fval);
6983 rdv->type = MONO_TYPE_I2;
6984 } else if (strncmp (tval, "i4", 2) == 0) {
6985 rdv->value.i4 = atoi (fval);
6986 rdv->type = MONO_TYPE_I4;
6987 } else {
6988 fprintf (stderr, "AOT : unsupported type for readonly field '%s'.\n", tval);
6989 exit (1);
6991 rdv->next = readonly_values;
6992 readonly_values = rdv;
6995 static gchar *
6996 clean_path (gchar * path)
6998 if (!path)
6999 return NULL;
7001 if (g_str_has_suffix (path, G_DIR_SEPARATOR_S))
7002 return path;
7004 gchar *clean = g_strconcat (path, G_DIR_SEPARATOR_S, NULL);
7005 g_free (path);
7007 return clean;
7010 static gchar *
7011 wrap_path (gchar * path)
7013 int len;
7014 if (!path)
7015 return NULL;
7017 // If the string contains no spaces, just return the original string.
7018 if (strstr (path, " ") == NULL)
7019 return path;
7021 // If the string is already wrapped in quotes, return it.
7022 len = strlen (path);
7023 if (len >= 2 && path[0] == '\"' && path[len-1] == '\"')
7024 return path;
7026 // If the string contains spaces, then wrap it in quotes.
7027 gchar *clean = g_strdup_printf ("\"%s\"", path);
7029 return clean;
7032 // Duplicate a char range and add it to a ptrarray, but only if it is nonempty
7033 static void
7034 ptr_array_add_range_if_nonempty(GPtrArray *args, gchar const *start, gchar const *end)
7036 ptrdiff_t len = end-start;
7037 if (len > 0)
7038 g_ptr_array_add (args, g_strndup (start, len));
7041 static GPtrArray *
7042 mono_aot_split_options (const char *aot_options)
7044 enum MonoAotOptionState {
7045 MONO_AOT_OPTION_STATE_DEFAULT,
7046 MONO_AOT_OPTION_STATE_STRING,
7047 MONO_AOT_OPTION_STATE_ESCAPE,
7050 GPtrArray *args = g_ptr_array_new ();
7051 enum MonoAotOptionState state = MONO_AOT_OPTION_STATE_DEFAULT;
7052 gchar const *opt_start = aot_options;
7053 gboolean end_of_string = FALSE;
7054 gchar cur;
7056 g_return_val_if_fail (aot_options != NULL, NULL);
7058 while ((cur = *aot_options) != '\0') {
7059 if (state == MONO_AOT_OPTION_STATE_ESCAPE)
7060 goto next;
7062 switch (cur) {
7063 case '"':
7064 // If we find a quote, then if we're in the default case then
7065 // it means we've found the start of a string, if not then it
7066 // means we've found the end of the string and should switch
7067 // back to the default case.
7068 switch (state) {
7069 case MONO_AOT_OPTION_STATE_DEFAULT:
7070 state = MONO_AOT_OPTION_STATE_STRING;
7071 break;
7072 case MONO_AOT_OPTION_STATE_STRING:
7073 state = MONO_AOT_OPTION_STATE_DEFAULT;
7074 break;
7075 case MONO_AOT_OPTION_STATE_ESCAPE:
7076 g_assert_not_reached ();
7077 break;
7079 break;
7080 case '\\':
7081 // If we've found an escaping operator, then this means we
7082 // should not process the next character if inside a string.
7083 if (state == MONO_AOT_OPTION_STATE_STRING)
7084 state = MONO_AOT_OPTION_STATE_ESCAPE;
7085 break;
7086 case ',':
7087 // If we're in the default state then this means we've found
7088 // an option, store it for later processing.
7089 if (state == MONO_AOT_OPTION_STATE_DEFAULT)
7090 goto new_opt;
7091 break;
7094 next:
7095 aot_options++;
7096 restart:
7097 // If the next character is end of string, then process the last option.
7098 if (*(aot_options) == '\0') {
7099 end_of_string = TRUE;
7100 goto new_opt;
7102 continue;
7104 new_opt:
7105 ptr_array_add_range_if_nonempty (args, opt_start, aot_options);
7106 opt_start = ++aot_options;
7107 if (end_of_string)
7108 break;
7109 goto restart; // Check for null and continue loop
7112 return args;
7115 static void
7116 mono_aot_parse_options (const char *aot_options, MonoAotOptions *opts)
7118 GPtrArray* args;
7120 args = mono_aot_split_options (aot_options ? aot_options : "");
7121 for (int i = 0; i < args->len; ++i) {
7122 const char *arg = (const char *)g_ptr_array_index (args, i);
7124 if (str_begins_with (arg, "outfile=")) {
7125 opts->outfile = g_strdup (arg + strlen ("outfile="));
7126 } else if (str_begins_with (arg, "llvm-outfile=")) {
7127 opts->llvm_outfile = g_strdup (arg + strlen ("llvm-outfile="));
7128 } else if (str_begins_with (arg, "temp-path=")) {
7129 opts->temp_path = clean_path (g_strdup (arg + strlen ("temp-path=")));
7130 } else if (str_begins_with (arg, "save-temps")) {
7131 opts->save_temps = TRUE;
7132 } else if (str_begins_with (arg, "keep-temps")) {
7133 opts->save_temps = TRUE;
7134 } else if (str_begins_with (arg, "write-symbols")) {
7135 opts->write_symbols = TRUE;
7136 } else if (str_begins_with (arg, "no-write-symbols")) {
7137 opts->write_symbols = FALSE;
7138 } else if (str_begins_with (arg, "metadata-only")) {
7139 opts->metadata_only = TRUE;
7140 } else if (str_begins_with (arg, "bind-to-runtime-version")) {
7141 opts->bind_to_runtime_version = TRUE;
7142 } else if (str_begins_with (arg, "full")) {
7143 opts->mode = MONO_AOT_MODE_FULL;
7144 } else if (str_begins_with (arg, "hybrid")) {
7145 opts->mode = MONO_AOT_MODE_HYBRID;
7146 } else if (str_begins_with (arg, "threads=")) {
7147 opts->nthreads = atoi (arg + strlen ("threads="));
7148 } else if (str_begins_with (arg, "static")) {
7149 opts->static_link = TRUE;
7150 opts->no_dlsym = TRUE;
7151 } else if (str_begins_with (arg, "asmonly")) {
7152 opts->asm_only = TRUE;
7153 } else if (str_begins_with (arg, "asmwriter")) {
7154 opts->asm_writer = TRUE;
7155 } else if (str_begins_with (arg, "nodebug")) {
7156 opts->nodebug = TRUE;
7157 } else if (str_begins_with (arg, "dwarfdebug")) {
7158 opts->dwarf_debug = TRUE;
7159 } else if (str_begins_with (arg, "nopagetrampolines")) {
7160 opts->use_trampolines_page = FALSE;
7161 } else if (str_begins_with (arg, "ntrampolines=")) {
7162 opts->ntrampolines = atoi (arg + strlen ("ntrampolines="));
7163 } else if (str_begins_with (arg, "nrgctx-trampolines=")) {
7164 opts->nrgctx_trampolines = atoi (arg + strlen ("nrgctx-trampolines="));
7165 } else if (str_begins_with (arg, "nrgctx-fetch-trampolines=")) {
7166 opts->nrgctx_fetch_trampolines = atoi (arg + strlen ("nrgctx-fetch-trampolines="));
7167 } else if (str_begins_with (arg, "nimt-trampolines=")) {
7168 opts->nimt_trampolines = atoi (arg + strlen ("nimt-trampolines="));
7169 } else if (str_begins_with (arg, "ngsharedvt-trampolines=")) {
7170 opts->ngsharedvt_arg_trampolines = atoi (arg + strlen ("ngsharedvt-trampolines="));
7171 } else if (str_begins_with (arg, "tool-prefix=")) {
7172 opts->tool_prefix = g_strdup (arg + strlen ("tool-prefix="));
7173 } else if (str_begins_with (arg, "ld-flags=")) {
7174 opts->ld_flags = g_strdup (arg + strlen ("ld-flags="));
7175 } else if (str_begins_with (arg, "soft-debug")) {
7176 opts->soft_debug = TRUE;
7177 } else if (str_begins_with (arg, "gen-seq-points-file=")) {
7178 fprintf (stderr, "Mono Warning: aot option gen-seq-points-file= is deprecated.\n");
7179 } else if (str_begins_with (arg, "gen-seq-points-file")) {
7180 fprintf (stderr, "Mono Warning: aot option gen-seq-points-file is deprecated.\n");
7181 } else if (str_begins_with (arg, "msym-dir=")) {
7182 debug_options.no_seq_points_compact_data = FALSE;
7183 opts->gen_msym_dir = TRUE;
7184 opts->gen_msym_dir_path = g_strdup (arg + strlen ("msym_dir="));;
7185 } else if (str_begins_with (arg, "direct-pinvoke")) {
7186 opts->direct_pinvoke = TRUE;
7187 } else if (str_begins_with (arg, "direct-icalls")) {
7188 opts->direct_icalls = TRUE;
7189 } else if (str_begins_with (arg, "no-direct-calls")) {
7190 opts->no_direct_calls = TRUE;
7191 } else if (str_begins_with (arg, "print-skipped")) {
7192 opts->print_skipped_methods = TRUE;
7193 } else if (str_begins_with (arg, "stats")) {
7194 opts->stats = TRUE;
7195 } else if (str_begins_with (arg, "no-instances")) {
7196 opts->no_instances = TRUE;
7197 } else if (str_begins_with (arg, "log-generics")) {
7198 opts->log_generics = TRUE;
7199 } else if (str_begins_with (arg, "log-instances=")) {
7200 opts->log_instances = TRUE;
7201 opts->instances_logfile_path = g_strdup (arg + strlen ("log-instances="));
7202 } else if (str_begins_with (arg, "log-instances")) {
7203 opts->log_instances = TRUE;
7204 } else if (str_begins_with (arg, "internal-logfile=")) {
7205 opts->logfile = g_strdup (arg + strlen ("internal-logfile="));
7206 } else if (str_begins_with (arg, "mtriple=")) {
7207 opts->mtriple = g_strdup (arg + strlen ("mtriple="));
7208 } else if (str_begins_with (arg, "llvm-path=")) {
7209 opts->llvm_path = clean_path (g_strdup (arg + strlen ("llvm-path=")));
7210 } else if (!strcmp (arg, "llvm")) {
7211 opts->llvm = TRUE;
7212 } else if (str_begins_with (arg, "readonly-value=")) {
7213 add_readonly_value (opts, arg + strlen ("readonly-value="));
7214 } else if (str_begins_with (arg, "info")) {
7215 printf ("AOT target setup: %s.\n", AOT_TARGET_STR);
7216 exit (0);
7217 } else if (str_begins_with (arg, "gc-maps")) {
7218 mini_gc_enable_gc_maps_for_aot ();
7219 } else if (str_begins_with (arg, "dump")) {
7220 opts->dump_json = TRUE;
7221 } else if (str_begins_with (arg, "llvmonly")) {
7222 opts->mode = MONO_AOT_MODE_FULL;
7223 opts->llvm = TRUE;
7224 opts->llvm_only = TRUE;
7225 } else if (str_begins_with (arg, "data-outfile=")) {
7226 opts->data_outfile = g_strdup (arg + strlen ("data-outfile="));
7227 } else if (str_begins_with (arg, "profile=")) {
7228 opts->profile_files = g_list_append (opts->profile_files, g_strdup (arg + strlen ("profile=")));
7229 } else if (!strcmp (arg, "profile-only")) {
7230 opts->profile_only = TRUE;
7231 } else if (!strcmp (arg, "verbose")) {
7232 opts->verbose = TRUE;
7233 } else if (str_begins_with (arg, "help") || str_begins_with (arg, "?")) {
7234 printf ("Supported options for --aot:\n");
7235 printf (" outfile=\n");
7236 printf (" llvm-outfile=\n");
7237 printf (" llvm-path=\n");
7238 printf (" temp-path=\n");
7239 printf (" save-temps\n");
7240 printf (" keep-temps\n");
7241 printf (" write-symbols\n");
7242 printf (" metadata-only\n");
7243 printf (" bind-to-runtime-version\n");
7244 printf (" full\n");
7245 printf (" threads=\n");
7246 printf (" static\n");
7247 printf (" asmonly\n");
7248 printf (" asmwriter\n");
7249 printf (" nodebug\n");
7250 printf (" dwarfdebug\n");
7251 printf (" ntrampolines=\n");
7252 printf (" nrgctx-trampolines=\n");
7253 printf (" nimt-trampolines=\n");
7254 printf (" ngsharedvt-trampolines=\n");
7255 printf (" tool-prefix=\n");
7256 printf (" readonly-value=\n");
7257 printf (" soft-debug\n");
7258 printf (" msym-dir=\n");
7259 printf (" gc-maps\n");
7260 printf (" print-skipped\n");
7261 printf (" no-instances\n");
7262 printf (" stats\n");
7263 printf (" dump\n");
7264 printf (" info\n");
7265 printf (" verbose\n");
7266 printf (" help/?\n");
7267 exit (0);
7268 } else {
7269 fprintf (stderr, "AOT : Unknown argument '%s'.\n", arg);
7270 exit (1);
7273 g_free ((gpointer) arg);
7276 if (opts->use_trampolines_page) {
7277 opts->ntrampolines = 0;
7278 opts->nrgctx_trampolines = 0;
7279 opts->nimt_trampolines = 0;
7280 opts->ngsharedvt_arg_trampolines = 0;
7283 g_ptr_array_free (args, /*free_seg=*/TRUE);
7286 static void
7287 add_token_info_hash (gpointer key, gpointer value, gpointer user_data)
7289 MonoMethod *method = (MonoMethod*)key;
7290 MonoJumpInfoToken *ji = (MonoJumpInfoToken*)value;
7291 MonoAotCompile *acfg = (MonoAotCompile *)user_data;
7292 MonoJumpInfoToken *new_ji;
7294 new_ji = (MonoJumpInfoToken *)mono_mempool_alloc0 (acfg->mempool, sizeof (MonoJumpInfoToken));
7295 new_ji->image = ji->image;
7296 new_ji->token = ji->token;
7297 g_hash_table_insert (acfg->token_info_hash, method, new_ji);
7300 static gboolean
7301 can_encode_class (MonoAotCompile *acfg, MonoClass *klass)
7303 if (klass->type_token)
7304 return TRUE;
7305 if ((klass->byval_arg.type == MONO_TYPE_VAR) || (klass->byval_arg.type == MONO_TYPE_MVAR) || (klass->byval_arg.type == MONO_TYPE_PTR))
7306 return TRUE;
7307 if (klass->rank)
7308 return can_encode_class (acfg, klass->element_class);
7309 return FALSE;
7312 static gboolean
7313 can_encode_method (MonoAotCompile *acfg, MonoMethod *method)
7315 if (method->wrapper_type) {
7316 switch (method->wrapper_type) {
7317 case MONO_WRAPPER_NONE:
7318 case MONO_WRAPPER_REMOTING_INVOKE_WITH_CHECK:
7319 case MONO_WRAPPER_XDOMAIN_INVOKE:
7320 case MONO_WRAPPER_STFLD:
7321 case MONO_WRAPPER_LDFLD:
7322 case MONO_WRAPPER_LDFLDA:
7323 case MONO_WRAPPER_STELEMREF:
7324 case MONO_WRAPPER_PROXY_ISINST:
7325 case MONO_WRAPPER_ALLOC:
7326 case MONO_WRAPPER_REMOTING_INVOKE:
7327 case MONO_WRAPPER_UNKNOWN:
7328 case MONO_WRAPPER_WRITE_BARRIER:
7329 case MONO_WRAPPER_DELEGATE_INVOKE:
7330 case MONO_WRAPPER_DELEGATE_BEGIN_INVOKE:
7331 case MONO_WRAPPER_DELEGATE_END_INVOKE:
7332 case MONO_WRAPPER_SYNCHRONIZED:
7333 break;
7334 case MONO_WRAPPER_MANAGED_TO_MANAGED:
7335 case MONO_WRAPPER_CASTCLASS: {
7336 WrapperInfo *info = mono_marshal_get_wrapper_info (method);
7338 if (info)
7339 return TRUE;
7340 else
7341 return FALSE;
7342 break;
7344 default:
7345 //printf ("Skip (wrapper call): %d -> %s\n", patch_info->type, mono_method_full_name (patch_info->data.method, TRUE));
7346 return FALSE;
7348 } else {
7349 if (!method->token) {
7350 /* The method is part of a constructed type like Int[,].Set (). */
7351 if (!g_hash_table_lookup (acfg->token_info_hash, method)) {
7352 if (method->klass->rank)
7353 return TRUE;
7354 return FALSE;
7358 return TRUE;
7361 static gboolean
7362 can_encode_patch (MonoAotCompile *acfg, MonoJumpInfo *patch_info)
7364 switch (patch_info->type) {
7365 case MONO_PATCH_INFO_METHOD:
7366 case MONO_PATCH_INFO_METHODCONST:
7367 case MONO_PATCH_INFO_METHOD_CODE_SLOT: {
7368 MonoMethod *method = patch_info->data.method;
7370 return can_encode_method (acfg, method);
7372 case MONO_PATCH_INFO_VTABLE:
7373 case MONO_PATCH_INFO_CLASS:
7374 case MONO_PATCH_INFO_IID:
7375 case MONO_PATCH_INFO_ADJUSTED_IID:
7376 if (!can_encode_class (acfg, patch_info->data.klass)) {
7377 //printf ("Skip: %s\n", mono_type_full_name (&patch_info->data.klass->byval_arg));
7378 return FALSE;
7380 break;
7381 case MONO_PATCH_INFO_DELEGATE_TRAMPOLINE: {
7382 if (!can_encode_class (acfg, patch_info->data.del_tramp->klass)) {
7383 //printf ("Skip: %s\n", mono_type_full_name (&patch_info->data.klass->byval_arg));
7384 return FALSE;
7386 break;
7388 case MONO_PATCH_INFO_RGCTX_FETCH:
7389 case MONO_PATCH_INFO_RGCTX_SLOT_INDEX: {
7390 MonoJumpInfoRgctxEntry *entry = patch_info->data.rgctx_entry;
7392 if (!can_encode_method (acfg, entry->method))
7393 return FALSE;
7394 if (!can_encode_patch (acfg, entry->data))
7395 return FALSE;
7396 break;
7398 default:
7399 break;
7402 return TRUE;
7405 static gboolean
7406 is_concrete_type (MonoType *t)
7408 MonoClass *klass;
7409 int i;
7411 if (t->type == MONO_TYPE_VAR || t->type == MONO_TYPE_MVAR)
7412 return FALSE;
7413 if (t->type == MONO_TYPE_GENERICINST) {
7414 MonoGenericContext *orig_ctx;
7415 MonoGenericInst *inst;
7416 MonoType *arg;
7418 if (!MONO_TYPE_ISSTRUCT (t))
7419 return TRUE;
7420 klass = mono_class_from_mono_type (t);
7421 orig_ctx = &mono_class_get_generic_class (klass)->context;
7423 inst = orig_ctx->class_inst;
7424 if (inst) {
7425 for (i = 0; i < inst->type_argc; ++i) {
7426 arg = mini_get_underlying_type (inst->type_argv [i]);
7427 if (!is_concrete_type (arg))
7428 return FALSE;
7431 inst = orig_ctx->method_inst;
7432 if (inst) {
7433 for (i = 0; i < inst->type_argc; ++i) {
7434 arg = mini_get_underlying_type (inst->type_argv [i]);
7435 if (!is_concrete_type (arg))
7436 return FALSE;
7440 return TRUE;
7443 /* LOCKING: Assumes the loader lock is held */
7444 static void
7445 add_gsharedvt_wrappers (MonoAotCompile *acfg, MonoMethodSignature *sig, gboolean gsharedvt_in, gboolean gsharedvt_out)
7447 MonoMethod *wrapper;
7448 gboolean concrete = TRUE;
7449 gboolean add_in = gsharedvt_in;
7450 gboolean add_out = gsharedvt_out;
7452 if (gsharedvt_in && g_hash_table_lookup (acfg->gsharedvt_in_signatures, sig))
7453 add_in = FALSE;
7454 if (gsharedvt_out && g_hash_table_lookup (acfg->gsharedvt_out_signatures, sig))
7455 add_out = FALSE;
7457 if (!add_in && !add_out)
7458 return;
7460 if (mini_is_gsharedvt_variable_signature (sig))
7461 return;
7463 if (add_in)
7464 g_hash_table_insert (acfg->gsharedvt_in_signatures, sig, sig);
7465 if (add_out)
7466 g_hash_table_insert (acfg->gsharedvt_out_signatures, sig, sig);
7468 if (!sig->has_type_parameters) {
7469 //printf ("%s\n", mono_signature_full_name (sig));
7471 if (gsharedvt_in) {
7472 wrapper = mini_get_gsharedvt_in_sig_wrapper (sig);
7473 add_extra_method (acfg, wrapper);
7475 if (gsharedvt_out) {
7476 wrapper = mini_get_gsharedvt_out_sig_wrapper (sig);
7477 add_extra_method (acfg, wrapper);
7479 } else {
7480 /* For signatures creared during generic sharing, convert them to a concrete signature if possible */
7481 MonoMethodSignature *copy = mono_metadata_signature_dup (sig);
7482 int i;
7484 //printf ("%s\n", mono_signature_full_name (sig));
7486 copy->ret = mini_get_underlying_type (sig->ret);
7487 if (!is_concrete_type (copy->ret))
7488 concrete = FALSE;
7489 for (i = 0; i < sig->param_count; ++i) {
7490 copy->params [i] = mini_get_underlying_type (sig->params [i]);
7491 if (!is_concrete_type (copy->params [i]))
7492 concrete = FALSE;
7494 if (concrete) {
7495 copy->has_type_parameters = 0;
7497 if (gsharedvt_in) {
7498 wrapper = mini_get_gsharedvt_in_sig_wrapper (copy);
7499 add_extra_method (acfg, wrapper);
7502 if (gsharedvt_out) {
7503 wrapper = mini_get_gsharedvt_out_sig_wrapper (copy);
7504 add_extra_method (acfg, wrapper);
7507 //printf ("%s\n", mono_method_full_name (wrapper, 1));
7513 * compile_method:
7515 * AOT compile a given method.
7516 * This function might be called by multiple threads, so it must be thread-safe.
7518 static void
7519 compile_method (MonoAotCompile *acfg, MonoMethod *method)
7521 MonoCompile *cfg;
7522 MonoJumpInfo *patch_info;
7523 gboolean skip;
7524 int index, depth;
7525 MonoMethod *wrapped;
7526 GTimer *jit_timer;
7527 JitFlags flags;
7529 if (acfg->aot_opts.metadata_only)
7530 return;
7532 mono_acfg_lock (acfg);
7533 index = get_method_index (acfg, method);
7534 mono_acfg_unlock (acfg);
7536 /* fixme: maybe we can also precompile wrapper methods */
7537 if ((method->flags & METHOD_ATTRIBUTE_PINVOKE_IMPL) ||
7538 (method->iflags & METHOD_IMPL_ATTRIBUTE_RUNTIME) ||
7539 (method->flags & METHOD_ATTRIBUTE_ABSTRACT)) {
7540 //printf ("Skip (impossible): %s\n", mono_method_full_name (method, TRUE));
7541 return;
7544 if (method->iflags & METHOD_IMPL_ATTRIBUTE_INTERNAL_CALL)
7545 return;
7547 wrapped = mono_marshal_method_from_wrapper (method);
7548 if (wrapped && (wrapped->iflags & METHOD_IMPL_ATTRIBUTE_INTERNAL_CALL) && wrapped->is_generic)
7549 // FIXME: The wrapper should be generic too, but it is not
7550 return;
7552 if (method->wrapper_type == MONO_WRAPPER_COMINTEROP)
7553 return;
7555 if (acfg->aot_opts.profile_only && !method->is_inflated && !g_hash_table_lookup (acfg->profile_methods, method))
7556 return;
7558 InterlockedIncrement (&acfg->stats.mcount);
7560 #if 0
7561 if (method->is_generic || mono_class_is_gtd (method->klass)) {
7562 InterlockedIncrement (&acfg->stats.genericcount);
7563 return;
7565 #endif
7567 //acfg->aot_opts.print_skipped_methods = TRUE;
7570 * Since these methods are the only ones which are compiled with
7571 * AOT support, and they are not used by runtime startup/shutdown code,
7572 * the runtime will not see AOT methods during AOT compilation,so it
7573 * does not need to support them by creating a fake GOT etc.
7575 flags = JIT_FLAG_AOT;
7576 if (mono_aot_mode_is_full (&acfg->aot_opts))
7577 flags = (JitFlags)(flags | JIT_FLAG_FULL_AOT);
7578 if (acfg->llvm)
7579 flags = (JitFlags)(flags | JIT_FLAG_LLVM);
7580 if (acfg->aot_opts.llvm_only)
7581 flags = (JitFlags)(flags | JIT_FLAG_LLVM_ONLY | JIT_FLAG_EXPLICIT_NULL_CHECKS);
7582 if (acfg->aot_opts.no_direct_calls)
7583 flags = (JitFlags)(flags | JIT_FLAG_NO_DIRECT_ICALLS);
7584 if (acfg->aot_opts.direct_pinvoke)
7585 flags = (JitFlags)(flags | JIT_FLAG_DIRECT_PINVOKE);
7587 jit_timer = mono_time_track_start ();
7588 cfg = mini_method_compile (method, acfg->opts, mono_get_root_domain (), flags, 0, index);
7589 mono_time_track_end (&mono_jit_stats.jit_time, jit_timer);
7591 if (cfg->exception_type == MONO_EXCEPTION_GENERIC_SHARING_FAILED) {
7592 if (acfg->aot_opts.print_skipped_methods)
7593 printf ("Skip (gshared failure): %s (%s)\n", mono_method_get_full_name (method), cfg->exception_message);
7594 InterlockedIncrement (&acfg->stats.genericcount);
7595 return;
7597 if (cfg->exception_type != MONO_EXCEPTION_NONE) {
7598 if (acfg->aot_opts.print_skipped_methods)
7599 printf ("Skip (JIT failure): %s\n", mono_method_get_full_name (method));
7600 /* Let the exception happen at runtime */
7601 return;
7604 if (cfg->disable_aot) {
7605 if (acfg->aot_opts.print_skipped_methods)
7606 printf ("Skip (disabled): %s\n", mono_method_get_full_name (method));
7607 InterlockedIncrement (&acfg->stats.ocount);
7608 return;
7610 cfg->method_index = index;
7612 /* Nullify patches which need no aot processing */
7613 for (patch_info = cfg->patch_info; patch_info; patch_info = patch_info->next) {
7614 switch (patch_info->type) {
7615 case MONO_PATCH_INFO_LABEL:
7616 case MONO_PATCH_INFO_BB:
7617 patch_info->type = MONO_PATCH_INFO_NONE;
7618 break;
7619 default:
7620 break;
7624 /* Collect method->token associations from the cfg */
7625 mono_acfg_lock (acfg);
7626 g_hash_table_foreach (cfg->token_info_hash, add_token_info_hash, acfg);
7627 mono_acfg_unlock (acfg);
7628 g_hash_table_destroy (cfg->token_info_hash);
7629 cfg->token_info_hash = NULL;
7632 * Check for absolute addresses.
7634 skip = FALSE;
7635 for (patch_info = cfg->patch_info; patch_info; patch_info = patch_info->next) {
7636 switch (patch_info->type) {
7637 case MONO_PATCH_INFO_ABS:
7638 /* unable to handle this */
7639 skip = TRUE;
7640 break;
7641 default:
7642 break;
7646 if (skip) {
7647 if (acfg->aot_opts.print_skipped_methods)
7648 printf ("Skip (abs call): %s\n", mono_method_get_full_name (method));
7649 InterlockedIncrement (&acfg->stats.abscount);
7650 return;
7653 /* Lock for the rest of the code */
7654 mono_acfg_lock (acfg);
7656 if (cfg->gsharedvt)
7657 acfg->stats.method_categories [METHOD_CAT_GSHAREDVT] ++;
7658 else if (cfg->gshared)
7659 acfg->stats.method_categories [METHOD_CAT_INST] ++;
7660 else if (cfg->method->wrapper_type)
7661 acfg->stats.method_categories [METHOD_CAT_WRAPPER] ++;
7662 else
7663 acfg->stats.method_categories [METHOD_CAT_NORMAL] ++;
7666 * Check for methods/klasses we can't encode.
7668 skip = FALSE;
7669 for (patch_info = cfg->patch_info; patch_info; patch_info = patch_info->next) {
7670 if (!can_encode_patch (acfg, patch_info))
7671 skip = TRUE;
7674 if (skip) {
7675 if (acfg->aot_opts.print_skipped_methods)
7676 printf ("Skip (patches): %s\n", mono_method_get_full_name (method));
7677 acfg->stats.ocount++;
7678 mono_acfg_unlock (acfg);
7679 return;
7682 if (!cfg->compile_llvm)
7683 acfg->has_jitted_code = TRUE;
7685 if (method->is_inflated && acfg->aot_opts.log_instances) {
7686 if (acfg->instances_logfile)
7687 fprintf (acfg->instances_logfile, "%s ### %d\n", mono_method_get_full_name (method), cfg->code_size);
7688 else
7689 printf ("%s ### %d\n", mono_method_get_full_name (method), cfg->code_size);
7692 /* Adds generic instances referenced by this method */
7694 * The depth is used to avoid infinite loops when generic virtual recursion is
7695 * encountered.
7697 depth = GPOINTER_TO_UINT (g_hash_table_lookup (acfg->method_depth, method));
7698 if (!acfg->aot_opts.no_instances && depth < 32 && mono_aot_mode_is_full (&acfg->aot_opts)) {
7699 for (patch_info = cfg->patch_info; patch_info; patch_info = patch_info->next) {
7700 switch (patch_info->type) {
7701 case MONO_PATCH_INFO_RGCTX_FETCH:
7702 case MONO_PATCH_INFO_RGCTX_SLOT_INDEX:
7703 case MONO_PATCH_INFO_METHOD: {
7704 MonoMethod *m = NULL;
7706 if (patch_info->type == MONO_PATCH_INFO_RGCTX_FETCH || patch_info->type == MONO_PATCH_INFO_RGCTX_SLOT_INDEX) {
7707 MonoJumpInfoRgctxEntry *e = patch_info->data.rgctx_entry;
7709 if (e->info_type == MONO_RGCTX_INFO_GENERIC_METHOD_CODE)
7710 m = e->data->data.method;
7711 } else {
7712 m = patch_info->data.method;
7715 if (!m)
7716 break;
7717 if (m->is_inflated && mono_aot_mode_is_full (&acfg->aot_opts)) {
7718 if (!(mono_class_generic_sharing_enabled (m->klass) &&
7719 mono_method_is_generic_sharable_full (m, FALSE, FALSE, FALSE)) &&
7720 (!method_has_type_vars (m) || mono_method_is_generic_sharable_full (m, TRUE, TRUE, FALSE))) {
7721 if (m->iflags & METHOD_IMPL_ATTRIBUTE_INTERNAL_CALL) {
7722 if (mono_aot_mode_is_full (&acfg->aot_opts) && !method_has_type_vars (m))
7723 add_extra_method_with_depth (acfg, mono_marshal_get_native_wrapper (m, TRUE, TRUE), depth + 1);
7724 } else {
7725 add_extra_method_with_depth (acfg, m, depth + 1);
7726 add_types_from_method_header (acfg, m);
7729 add_generic_class_with_depth (acfg, m->klass, depth + 5, "method");
7731 if (m->wrapper_type == MONO_WRAPPER_MANAGED_TO_MANAGED) {
7732 WrapperInfo *info = mono_marshal_get_wrapper_info (m);
7734 if (info && info->subtype == WRAPPER_SUBTYPE_ELEMENT_ADDR)
7735 add_extra_method_with_depth (acfg, m, depth + 1);
7737 break;
7739 case MONO_PATCH_INFO_VTABLE: {
7740 MonoClass *klass = patch_info->data.klass;
7742 if (mono_class_is_ginst (klass) && !mini_class_is_generic_sharable (klass))
7743 add_generic_class_with_depth (acfg, klass, depth + 5, "vtable");
7744 break;
7746 case MONO_PATCH_INFO_SFLDA: {
7747 MonoClass *klass = patch_info->data.field->parent;
7749 /* The .cctor needs to run at runtime. */
7750 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))
7751 add_extra_method_with_depth (acfg, mono_class_get_cctor (klass), depth + 1);
7752 break;
7754 default:
7755 break;
7760 /* Determine whenever the method has GOT slots */
7761 for (patch_info = cfg->patch_info; patch_info; patch_info = patch_info->next) {
7762 switch (patch_info->type) {
7763 case MONO_PATCH_INFO_GOT_OFFSET:
7764 case MONO_PATCH_INFO_NONE:
7765 case MONO_PATCH_INFO_GC_CARD_TABLE_ADDR:
7766 case MONO_PATCH_INFO_GC_NURSERY_START:
7767 case MONO_PATCH_INFO_GC_NURSERY_BITS:
7768 break;
7769 case MONO_PATCH_INFO_IMAGE:
7770 /* The assembly is stored in GOT slot 0 */
7771 if (patch_info->data.image != acfg->image)
7772 cfg->has_got_slots = TRUE;
7773 break;
7774 default:
7775 if (!is_plt_patch (patch_info) || (cfg->compile_llvm && acfg->aot_opts.llvm_only))
7776 cfg->has_got_slots = TRUE;
7777 break;
7781 if (!cfg->has_got_slots)
7782 InterlockedIncrement (&acfg->stats.methods_without_got_slots);
7784 /* Add gsharedvt wrappers for signatures used by the method */
7785 if (acfg->aot_opts.llvm_only) {
7786 GSList *l;
7788 if (!cfg->method->wrapper_type || cfg->method->wrapper_type == MONO_WRAPPER_DELEGATE_INVOKE)
7789 /* These only need out wrappers */
7790 add_gsharedvt_wrappers (acfg, mono_method_signature (cfg->method), FALSE, TRUE);
7792 for (l = cfg->signatures; l; l = l->next) {
7793 MonoMethodSignature *sig = mono_metadata_signature_dup ((MonoMethodSignature*)l->data);
7795 /* These only need in wrappers */
7796 add_gsharedvt_wrappers (acfg, sig, TRUE, FALSE);
7801 * FIXME: Instead of this mess, allocate the patches from the aot mempool.
7803 /* Make a copy of the patch info which is in the mempool */
7805 MonoJumpInfo *patches = NULL, *patches_end = NULL;
7807 for (patch_info = cfg->patch_info; patch_info; patch_info = patch_info->next) {
7808 MonoJumpInfo *new_patch_info = mono_patch_info_dup_mp (acfg->mempool, patch_info);
7810 if (!patches)
7811 patches = new_patch_info;
7812 else
7813 patches_end->next = new_patch_info;
7814 patches_end = new_patch_info;
7816 cfg->patch_info = patches;
7818 /* Make a copy of the unwind info */
7820 GSList *l, *unwind_ops;
7821 MonoUnwindOp *op;
7823 unwind_ops = NULL;
7824 for (l = cfg->unwind_ops; l; l = l->next) {
7825 op = (MonoUnwindOp *)mono_mempool_alloc (acfg->mempool, sizeof (MonoUnwindOp));
7826 memcpy (op, l->data, sizeof (MonoUnwindOp));
7827 unwind_ops = g_slist_prepend_mempool (acfg->mempool, unwind_ops, op);
7829 cfg->unwind_ops = g_slist_reverse (unwind_ops);
7831 /* Make a copy of the argument/local info */
7833 MonoError error;
7834 MonoInst **args, **locals;
7835 MonoMethodSignature *sig;
7836 MonoMethodHeader *header;
7837 int i;
7839 sig = mono_method_signature (method);
7840 args = (MonoInst **)mono_mempool_alloc (acfg->mempool, sizeof (MonoInst*) * (sig->param_count + sig->hasthis));
7841 for (i = 0; i < sig->param_count + sig->hasthis; ++i) {
7842 args [i] = (MonoInst *)mono_mempool_alloc (acfg->mempool, sizeof (MonoInst));
7843 memcpy (args [i], cfg->args [i], sizeof (MonoInst));
7845 cfg->args = args;
7847 header = mono_method_get_header_checked (method, &error);
7848 mono_error_assert_ok (&error); /* FIXME don't swallow the error */
7849 locals = (MonoInst **)mono_mempool_alloc (acfg->mempool, sizeof (MonoInst*) * header->num_locals);
7850 for (i = 0; i < header->num_locals; ++i) {
7851 locals [i] = (MonoInst *)mono_mempool_alloc (acfg->mempool, sizeof (MonoInst));
7852 memcpy (locals [i], cfg->locals [i], sizeof (MonoInst));
7854 mono_metadata_free_mh (header);
7855 cfg->locals = locals;
7858 /* Free some fields used by cfg to conserve memory */
7859 mono_empty_compile (cfg);
7861 //printf ("Compile: %s\n", mono_method_full_name (method, TRUE));
7863 while (index >= acfg->cfgs_size) {
7864 MonoCompile **new_cfgs;
7865 int new_size;
7867 new_size = acfg->cfgs_size * 2;
7868 new_cfgs = g_new0 (MonoCompile*, new_size);
7869 memcpy (new_cfgs, acfg->cfgs, sizeof (MonoCompile*) * acfg->cfgs_size);
7870 g_free (acfg->cfgs);
7871 acfg->cfgs = new_cfgs;
7872 acfg->cfgs_size = new_size;
7874 acfg->cfgs [index] = cfg;
7876 g_hash_table_insert (acfg->method_to_cfg, cfg->orig_method, cfg);
7878 mono_update_jit_stats (cfg);
7881 if (cfg->orig_method->wrapper_type)
7882 g_ptr_array_add (acfg->extra_methods, cfg->orig_method);
7885 mono_acfg_unlock (acfg);
7887 InterlockedIncrement (&acfg->stats.ccount);
7890 static mono_thread_start_return_t WINAPI
7891 compile_thread_main (gpointer user_data)
7893 MonoDomain *domain = ((MonoDomain **)user_data) [0];
7894 MonoAotCompile *acfg = ((MonoAotCompile **)user_data) [1];
7895 GPtrArray *methods = ((GPtrArray **)user_data) [2];
7896 int i;
7898 MonoError error;
7899 MonoThread *thread = mono_thread_attach (domain);
7900 mono_thread_set_name_internal (thread->internal_thread, mono_string_new (mono_get_root_domain (), "AOT compiler"), TRUE, &error);
7901 mono_error_assert_ok (&error);
7903 for (i = 0; i < methods->len; ++i)
7904 compile_method (acfg, (MonoMethod *)g_ptr_array_index (methods, i));
7906 return 0;
7909 /* Used by the LLVM backend */
7910 guint32
7911 mono_aot_get_got_offset (MonoJumpInfo *ji)
7913 return get_got_offset (llvm_acfg, TRUE, ji);
7917 * mono_aot_is_shared_got_offset:
7919 * Return whenever OFFSET refers to a GOT slot which is preinitialized
7920 * when the AOT image is loaded.
7922 gboolean
7923 mono_aot_is_shared_got_offset (int offset)
7925 return offset < llvm_acfg->nshared_got_entries;
7928 char*
7929 mono_aot_get_method_name (MonoCompile *cfg)
7931 if (llvm_acfg->aot_opts.static_link)
7932 /* Include the assembly name too to avoid duplicate symbol errors */
7933 return g_strdup_printf ("%s_%s", llvm_acfg->assembly_name_sym, get_debug_sym (cfg->orig_method, "", llvm_acfg->method_label_hash));
7934 else
7935 return get_debug_sym (cfg->orig_method, "", llvm_acfg->method_label_hash);
7939 * mono_aot_is_linkonce_method:
7941 * Return whenever METHOD should be emitted with linkonce linkage,
7942 * eliminating duplicate copies when compiling in static mode.
7944 gboolean
7945 mono_aot_is_linkonce_method (MonoMethod *method)
7947 return FALSE;
7948 #if 0
7949 WrapperInfo *info;
7951 // FIXME: Add more cases
7952 if (method->wrapper_type != MONO_WRAPPER_UNKNOWN)
7953 return FALSE;
7954 info = mono_marshal_get_wrapper_info (method);
7955 if ((info && (info->subtype == WRAPPER_SUBTYPE_GSHAREDVT_IN_SIG || info->subtype == WRAPPER_SUBTYPE_GSHAREDVT_OUT_SIG)))
7956 return TRUE;
7957 return FALSE;
7958 #endif
7961 static gboolean
7962 append_mangled_type (GString *s, MonoType *t)
7964 if (t->byref)
7965 g_string_append_printf (s, "b");
7966 switch (t->type) {
7967 case MONO_TYPE_VOID:
7968 g_string_append_printf (s, "void_");
7969 break;
7970 case MONO_TYPE_I1:
7971 g_string_append_printf (s, "i1");
7972 break;
7973 case MONO_TYPE_U1:
7974 g_string_append_printf (s, "u1");
7975 break;
7976 case MONO_TYPE_I2:
7977 g_string_append_printf (s, "i2");
7978 break;
7979 case MONO_TYPE_U2:
7980 g_string_append_printf (s, "u2");
7981 break;
7982 case MONO_TYPE_I4:
7983 g_string_append_printf (s, "i4");
7984 break;
7985 case MONO_TYPE_U4:
7986 g_string_append_printf (s, "u4");
7987 break;
7988 case MONO_TYPE_I8:
7989 g_string_append_printf (s, "i8");
7990 break;
7991 case MONO_TYPE_U8:
7992 g_string_append_printf (s, "u8");
7993 break;
7994 case MONO_TYPE_I:
7995 g_string_append_printf (s, "ii");
7996 break;
7997 case MONO_TYPE_U:
7998 g_string_append_printf (s, "ui");
7999 break;
8000 case MONO_TYPE_R4:
8001 g_string_append_printf (s, "fl");
8002 break;
8003 case MONO_TYPE_R8:
8004 g_string_append_printf (s, "do");
8005 break;
8006 default: {
8007 char *fullname = mono_type_full_name (t);
8008 GString *temp;
8009 char *temps;
8010 int i, len;
8013 * Have to create a mangled name which is:
8014 * - a valid symbol
8015 * - unique
8017 temp = g_string_new ("");
8018 len = strlen (fullname);
8019 for (i = 0; i < len; ++i) {
8020 char c = fullname [i];
8021 if (isalnum (c)) {
8022 g_string_append_c (temp, c);
8023 } else if (c == '_') {
8024 g_string_append_c (temp, '_');
8025 g_string_append_c (temp, '_');
8026 } else {
8027 g_string_append_c (temp, '_');
8028 g_string_append_printf (temp, "%x", (int)c);
8031 temps = g_string_free (temp, FALSE);
8032 /* Include the length to avoid different length type names aliasing each other */
8033 g_string_append_printf (s, "cl%x_%s_", strlen (temps), temps);
8034 g_free (temps);
8035 return TRUE;
8038 return TRUE;
8041 static gboolean
8042 append_mangled_signature (GString *s, MonoMethodSignature *sig)
8044 int i;
8045 gboolean supported;
8047 supported = append_mangled_type (s, sig->ret);
8048 if (!supported)
8049 return FALSE;
8050 if (sig->hasthis)
8051 g_string_append_printf (s, "this_");
8052 for (i = 0; i < sig->param_count; ++i) {
8053 supported = append_mangled_type (s, sig->params [i]);
8054 if (!supported)
8055 return FALSE;
8058 return TRUE;
8062 * mono_aot_get_mangled_method_name:
8064 * Return a unique mangled name for METHOD, or NULL.
8066 char*
8067 mono_aot_get_mangled_method_name (MonoMethod *method)
8069 WrapperInfo *info;
8070 GString *s;
8071 gboolean supported;
8073 // FIXME: Add more cases
8074 if (method->wrapper_type != MONO_WRAPPER_UNKNOWN)
8075 return NULL;
8076 info = mono_marshal_get_wrapper_info (method);
8077 if (!(info && (info->subtype == WRAPPER_SUBTYPE_GSHAREDVT_IN_SIG || info->subtype == WRAPPER_SUBTYPE_GSHAREDVT_OUT_SIG)))
8078 return NULL;
8080 s = g_string_new ("");
8082 g_string_append_printf (s, "aot_method_w_");
8084 switch (info->subtype) {
8085 case WRAPPER_SUBTYPE_GSHAREDVT_IN_SIG:
8086 g_string_append_printf (s, "gsharedvt_in_");
8087 break;
8088 case WRAPPER_SUBTYPE_GSHAREDVT_OUT_SIG:
8089 g_string_append_printf (s, "gsharedvt_out_");
8090 break;
8091 default:
8092 g_assert_not_reached ();
8093 break;
8096 supported = append_mangled_signature (s, info->d.gsharedvt.sig);
8097 if (!supported) {
8098 g_string_free (s, TRUE);
8099 return NULL;
8102 return g_string_free (s, FALSE);
8105 gboolean
8106 mono_aot_is_direct_callable (MonoJumpInfo *patch_info)
8108 return is_direct_callable (llvm_acfg, NULL, patch_info);
8111 void
8112 mono_aot_mark_unused_llvm_plt_entry (MonoJumpInfo *patch_info)
8114 MonoPltEntry *plt_entry;
8116 plt_entry = get_plt_entry (llvm_acfg, patch_info);
8117 plt_entry->llvm_used = FALSE;
8120 char*
8121 mono_aot_get_direct_call_symbol (MonoJumpInfoType type, gconstpointer data)
8123 const char *sym = NULL;
8125 if (llvm_acfg->aot_opts.direct_icalls) {
8126 if (type == MONO_PATCH_INFO_JIT_ICALL_ADDR) {
8127 /* Call to a C function implementing a jit icall */
8128 sym = mono_lookup_jit_icall_symbol ((const char *)data);
8129 } else if (type == MONO_PATCH_INFO_ICALL_ADDR_CALL) {
8130 MonoMethod *method = (MonoMethod *)data;
8131 if (!(method->flags & METHOD_ATTRIBUTE_PINVOKE_IMPL))
8132 sym = mono_lookup_icall_symbol (method);
8133 else if (llvm_acfg->aot_opts.direct_pinvoke)
8134 sym = get_pinvoke_import (llvm_acfg, method);
8136 if (sym)
8137 return g_strdup (sym);
8139 return NULL;
8142 char*
8143 mono_aot_get_plt_symbol (MonoJumpInfoType type, gconstpointer data)
8145 MonoJumpInfo *ji = (MonoJumpInfo *)mono_mempool_alloc (llvm_acfg->mempool, sizeof (MonoJumpInfo));
8146 MonoPltEntry *plt_entry;
8147 const char *sym = NULL;
8149 ji->type = type;
8150 ji->data.target = data;
8152 if (!can_encode_patch (llvm_acfg, ji))
8153 return NULL;
8155 if (llvm_acfg->aot_opts.direct_icalls) {
8156 if (type == MONO_PATCH_INFO_JIT_ICALL_ADDR) {
8157 /* Call to a C function implementing a jit icall */
8158 sym = mono_lookup_jit_icall_symbol ((const char *)data);
8159 } else if (type == MONO_PATCH_INFO_ICALL_ADDR_CALL) {
8160 MonoMethod *method = (MonoMethod *)data;
8161 if (!(method->flags & METHOD_ATTRIBUTE_PINVOKE_IMPL))
8162 sym = mono_lookup_icall_symbol (method);
8164 if (sym)
8165 return g_strdup (sym);
8168 plt_entry = get_plt_entry (llvm_acfg, ji);
8169 plt_entry->llvm_used = TRUE;
8171 #if defined(TARGET_MACH)
8172 return g_strdup_printf (plt_entry->llvm_symbol + strlen (llvm_acfg->llvm_label_prefix));
8173 #else
8174 return g_strdup_printf (plt_entry->llvm_symbol);
8175 #endif
8179 mono_aot_get_method_index (MonoMethod *method)
8181 g_assert (llvm_acfg);
8182 return get_method_index (llvm_acfg, method);
8185 MonoJumpInfo*
8186 mono_aot_patch_info_dup (MonoJumpInfo* ji)
8188 MonoJumpInfo *res;
8190 mono_acfg_lock (llvm_acfg);
8191 res = mono_patch_info_dup_mp (llvm_acfg->mempool, ji);
8192 mono_acfg_unlock (llvm_acfg);
8194 return res;
8197 static int
8198 execute_system (const char * command)
8200 int status = 0;
8202 #if HOST_WIN32
8203 // We need an extra set of quotes around the whole command to properly handle commands
8204 // with spaces since internally the command is called through "cmd /c.
8205 char * quoted_command = g_strdup_printf ("\"%s\"", command);
8207 int size = MultiByteToWideChar (CP_UTF8, 0 , quoted_command , -1, NULL , 0);
8208 wchar_t* wstr = g_malloc (sizeof (wchar_t) * size);
8209 MultiByteToWideChar (CP_UTF8, 0, quoted_command, -1, wstr , size);
8210 status = _wsystem (wstr);
8211 g_free (wstr);
8213 g_free (quoted_command);
8214 #elif defined (HAVE_SYSTEM)
8215 status = system (command);
8216 #else
8217 g_assert_not_reached ();
8218 #endif
8220 return status;
8223 #ifdef ENABLE_LLVM
8226 * emit_llvm_file:
8228 * Emit the LLVM code into an LLVM bytecode file, and compile it using the LLVM
8229 * tools.
8231 static gboolean
8232 emit_llvm_file (MonoAotCompile *acfg)
8234 char *command, *opts, *tempbc, *optbc, *output_fname;
8236 if (acfg->aot_opts.llvm_only && acfg->aot_opts.asm_only) {
8237 tempbc = g_strdup_printf ("%s.bc", acfg->tmpbasename);
8238 optbc = g_strdup (acfg->aot_opts.llvm_outfile);
8239 } else {
8240 tempbc = g_strdup_printf ("%s.bc", acfg->tmpbasename);
8241 optbc = g_strdup_printf ("%s.opt.bc", acfg->tmpbasename);
8244 mono_llvm_emit_aot_module (tempbc, g_path_get_basename (acfg->image->name));
8247 * FIXME: Experiment with adding optimizations, the -std-compile-opts set takes
8248 * a lot of time, and doesn't seem to save much space.
8249 * The following optimizations cannot be enabled:
8250 * - 'tailcallelim'
8251 * - 'jump-threading' changes our blockaddress references to int constants.
8252 * - 'basiccg' fails because it contains:
8253 * if (CS && !isa<IntrinsicInst>(II)) {
8254 * and isa<IntrinsicInst> is false for invokes to intrinsics (iltests.exe).
8255 * - 'prune-eh' and 'functionattrs' depend on 'basiccg'.
8256 * The opt list below was produced by taking the output of:
8257 * llvm-as < /dev/null | opt -O2 -disable-output -debug-pass=Arguments
8258 * then removing tailcallelim + the global opts.
8259 * strip-dead-prototypes deletes unused intrinsics definitions.
8261 /* The dse pass is disabled because of #13734 and #17616 */
8263 * The dse bug is in DeadStoreElimination.cpp:isOverwrite ():
8264 * // If we have no DataLayout information around, then the size of the store
8265 * // is inferrable from the pointee type. If they are the same type, then
8266 * // we know that the store is safe.
8267 * if (AA.getDataLayout() == 0 &&
8268 * Later.Ptr->getType() == Earlier.Ptr->getType()) {
8269 * return OverwriteComplete;
8270 * Here, if 'Earlier' refers to a memset, and Later has no size info, it mistakenly thinks the memset is redundant.
8272 if (acfg->aot_opts.llvm_only)
8273 // FIXME: This doesn't work yet
8274 opts = g_strdup ("");
8275 else
8276 #if LLVM_API_VERSION > 100
8277 opts = g_strdup ("-O2 -disable-tail-calls");
8278 #else
8279 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");
8280 #endif
8281 command = g_strdup_printf ("\"%sopt\" -f %s -o \"%s\" \"%s\"", acfg->aot_opts.llvm_path, opts, optbc, tempbc);
8282 aot_printf (acfg, "Executing opt: %s\n", command);
8283 if (execute_system (command) != 0)
8284 return FALSE;
8285 g_free (opts);
8287 if (acfg->aot_opts.llvm_only && acfg->aot_opts.asm_only)
8288 /* Nothing else to do */
8289 return TRUE;
8291 if (acfg->aot_opts.llvm_only) {
8292 /* Use the stock clang from xcode */
8293 // FIXME: arch
8294 command = g_strdup_printf ("clang++ -fexceptions -march=x86-64 -fpic -msse -msse2 -msse3 -msse4 -O2 -fno-optimize-sibling-calls -Wno-override-module -c -o \"%s\" \"%s.opt.bc\"", acfg->llvm_ofile, acfg->tmpbasename);
8296 aot_printf (acfg, "Executing clang: %s\n", command);
8297 if (execute_system (command) != 0)
8298 return FALSE;
8299 return TRUE;
8302 if (!acfg->llc_args)
8303 acfg->llc_args = g_string_new ("");
8305 /* Verbose asm slows down llc greatly */
8306 g_string_append (acfg->llc_args, " -asm-verbose=false");
8308 if (acfg->aot_opts.mtriple)
8309 g_string_append_printf (acfg->llc_args, " -mtriple=%s", acfg->aot_opts.mtriple);
8311 g_string_append (acfg->llc_args, " -disable-gnu-eh-frame -enable-mono-eh-frame");
8313 g_string_append_printf (acfg->llc_args, " -mono-eh-frame-symbol=%s%s", acfg->user_symbol_prefix, acfg->llvm_eh_frame_symbol);
8315 #if LLVM_API_VERSION > 100
8316 g_string_append_printf (acfg->llc_args, " -disable-tail-calls");
8317 #endif
8319 #if defined(TARGET_MACH) && defined(TARGET_ARM)
8320 /* ios requires PIC code now */
8321 g_string_append_printf (acfg->llc_args, " -relocation-model=pic");
8322 #else
8323 if (llvm_acfg->aot_opts.static_link)
8324 g_string_append_printf (acfg->llc_args, " -relocation-model=static");
8325 else
8326 g_string_append_printf (acfg->llc_args, " -relocation-model=pic");
8327 #endif
8329 if (acfg->llvm_owriter) {
8330 /* Emit an object file directly */
8331 output_fname = g_strdup_printf ("%s", acfg->llvm_ofile);
8332 g_string_append_printf (acfg->llc_args, " -filetype=obj");
8333 } else {
8334 output_fname = g_strdup_printf ("%s", acfg->llvm_sfile);
8336 command = g_strdup_printf ("\"%sllc\" %s -o \"%s\" \"%s.opt.bc\"", acfg->aot_opts.llvm_path, acfg->llc_args->str, output_fname, acfg->tmpbasename);
8337 g_free (output_fname);
8339 aot_printf (acfg, "Executing llc: %s\n", command);
8341 if (execute_system (command) != 0)
8342 return FALSE;
8343 return TRUE;
8345 #endif
8347 static void
8348 emit_code (MonoAotCompile *acfg)
8350 int oindex, i, prev_index;
8351 gboolean saved_unbox_info = FALSE;
8352 char symbol [MAX_SYMBOL_SIZE];
8354 if (acfg->aot_opts.llvm_only)
8355 return;
8357 #if defined(TARGET_POWERPC64)
8358 sprintf (symbol, ".Lgot_addr");
8359 emit_section_change (acfg, ".text", 0);
8360 emit_alignment (acfg, 8);
8361 emit_label (acfg, symbol);
8362 emit_pointer (acfg, acfg->got_symbol);
8363 #endif
8366 * This global symbol is used to compute the address of each method using the
8367 * code_offsets array. It is also used to compute the memory ranges occupied by
8368 * AOT code, so it must be equal to the address of the first emitted method.
8370 emit_section_change (acfg, ".text", 0);
8371 emit_alignment_code (acfg, 8);
8372 emit_info_symbol (acfg, "jit_code_start");
8375 * Emit some padding so the local symbol for the first method doesn't have the
8376 * same address as 'methods'.
8378 emit_padding (acfg, 16);
8380 for (oindex = 0; oindex < acfg->method_order->len; ++oindex) {
8381 MonoCompile *cfg;
8382 MonoMethod *method;
8384 i = GPOINTER_TO_UINT (g_ptr_array_index (acfg->method_order, oindex));
8386 cfg = acfg->cfgs [i];
8388 if (!cfg)
8389 continue;
8391 method = cfg->orig_method;
8393 /* Emit unbox trampoline */
8394 if (mono_aot_mode_is_full (&acfg->aot_opts) && cfg->orig_method->klass->valuetype) {
8395 sprintf (symbol, "ut_%d", get_method_index (acfg, method));
8397 emit_section_change (acfg, ".text", 0);
8399 if (acfg->thumb_mixed && cfg->compile_llvm) {
8400 emit_set_thumb_mode (acfg);
8401 fprintf (acfg->fp, "\n.thumb_func\n");
8404 emit_label (acfg, symbol);
8406 arch_emit_unbox_trampoline (acfg, cfg, cfg->orig_method, cfg->asm_symbol);
8408 if (acfg->thumb_mixed && cfg->compile_llvm)
8409 emit_set_arm_mode (acfg);
8411 if (!saved_unbox_info) {
8412 char user_symbol [128];
8413 GSList *unwind_ops;
8414 sprintf (user_symbol, "%sunbox_trampoline_p", acfg->user_symbol_prefix);
8416 emit_label (acfg, "ut_end");
8418 unwind_ops = mono_unwind_get_cie_program ();
8419 save_unwind_info (acfg, user_symbol, unwind_ops);
8420 mono_free_unwind_info (unwind_ops);
8422 /* Save the unbox trampoline size */
8423 emit_symbol_diff (acfg, "ut_end", symbol, 0);
8425 saved_unbox_info = TRUE;
8429 if (cfg->compile_llvm)
8430 acfg->stats.llvm_count ++;
8431 else
8432 emit_method_code (acfg, cfg);
8435 emit_section_change (acfg, ".text", 0);
8436 emit_alignment_code (acfg, 8);
8437 emit_info_symbol (acfg, "jit_code_end");
8439 /* To distinguish it from the next symbol */
8440 emit_padding (acfg, 4);
8443 * Add .no_dead_strip directives for all LLVM methods to prevent the OSX linker
8444 * from optimizing them away, since it doesn't see that code_offsets references them.
8445 * JITted methods don't need this since they are referenced using assembler local
8446 * symbols.
8447 * FIXME: This is why write-symbols doesn't work on OSX ?
8449 if (acfg->llvm && acfg->need_no_dead_strip) {
8450 fprintf (acfg->fp, "\n");
8451 for (i = 0; i < acfg->nmethods; ++i) {
8452 if (acfg->cfgs [i] && acfg->cfgs [i]->compile_llvm)
8453 fprintf (acfg->fp, ".no_dead_strip %s\n", acfg->cfgs [i]->asm_symbol);
8458 * To work around linker issues, we emit a table of branches, and disassemble them at runtime.
8459 * This is PIE code, and the linker can update it if needed.
8462 sprintf (symbol, "method_addresses");
8463 emit_section_change (acfg, ".text", 1);
8464 emit_alignment_code (acfg, 8);
8465 emit_info_symbol (acfg, symbol);
8466 if (acfg->aot_opts.write_symbols)
8467 emit_local_symbol (acfg, symbol, "method_addresses_end", TRUE);
8468 emit_unset_mode (acfg);
8469 if (acfg->need_no_dead_strip)
8470 fprintf (acfg->fp, " .no_dead_strip %s\n", symbol);
8472 for (i = 0; i < acfg->nmethods; ++i) {
8473 #ifdef MONO_ARCH_AOT_SUPPORTED
8474 int call_size;
8476 if (acfg->cfgs [i]) {
8477 arch_emit_direct_call (acfg, acfg->cfgs [i]->asm_symbol, FALSE, acfg->thumb_mixed && acfg->cfgs [i]->compile_llvm, NULL, &call_size);
8478 } else {
8479 arch_emit_direct_call (acfg, symbol, FALSE, FALSE, NULL, &call_size);
8481 #endif
8484 sprintf (symbol, "method_addresses_end");
8485 emit_label (acfg, symbol);
8486 emit_line (acfg);
8488 /* Emit a sorted table mapping methods to the index of their unbox trampolines */
8489 sprintf (symbol, "unbox_trampolines");
8490 emit_section_change (acfg, RODATA_SECT, 0);
8491 emit_alignment (acfg, 8);
8492 emit_info_symbol (acfg, symbol);
8494 prev_index = -1;
8495 for (i = 0; i < acfg->nmethods; ++i) {
8496 MonoCompile *cfg;
8497 MonoMethod *method;
8498 int index;
8500 cfg = acfg->cfgs [i];
8501 if (!cfg)
8502 continue;
8504 method = cfg->orig_method;
8506 if (mono_aot_mode_is_full (&acfg->aot_opts) && cfg->orig_method->klass->valuetype) {
8507 index = get_method_index (acfg, method);
8509 emit_int32 (acfg, index);
8510 /* Make sure the table is sorted by index */
8511 g_assert (index > prev_index);
8512 prev_index = index;
8515 sprintf (symbol, "unbox_trampolines_end");
8516 emit_info_symbol (acfg, symbol);
8517 emit_int32 (acfg, 0);
8519 /* Emit a separate table with the trampoline addresses/offsets */
8520 sprintf (symbol, "unbox_trampoline_addresses");
8521 emit_section_change (acfg, ".text", 0);
8522 emit_alignment_code (acfg, 8);
8523 emit_info_symbol (acfg, symbol);
8525 for (i = 0; i < acfg->nmethods; ++i) {
8526 MonoCompile *cfg;
8527 MonoMethod *method;
8528 int index;
8530 cfg = acfg->cfgs [i];
8531 if (!cfg)
8532 continue;
8534 method = cfg->orig_method;
8536 if (mono_aot_mode_is_full (&acfg->aot_opts) && cfg->orig_method->klass->valuetype) {
8537 #ifdef MONO_ARCH_AOT_SUPPORTED
8538 int call_size;
8540 index = get_method_index (acfg, method);
8541 sprintf (symbol, "ut_%d", index);
8543 arch_emit_direct_call (acfg, symbol, FALSE, acfg->thumb_mixed && cfg->compile_llvm, NULL, &call_size);
8544 #endif
8547 emit_int32 (acfg, 0);
8550 static void
8551 emit_info (MonoAotCompile *acfg)
8553 int oindex, i;
8554 gint32 *offsets;
8556 offsets = g_new0 (gint32, acfg->nmethods);
8558 for (oindex = 0; oindex < acfg->method_order->len; ++oindex) {
8559 i = GPOINTER_TO_UINT (g_ptr_array_index (acfg->method_order, oindex));
8561 if (acfg->cfgs [i]) {
8562 emit_method_info (acfg, acfg->cfgs [i]);
8563 offsets [i] = acfg->cfgs [i]->method_info_offset;
8564 } else {
8565 offsets [i] = 0;
8569 acfg->stats.offsets_size += emit_offset_table (acfg, "method_info_offsets", MONO_AOT_TABLE_METHOD_INFO_OFFSETS, acfg->nmethods, 10, offsets);
8571 g_free (offsets);
8574 #endif /* #if !defined(DISABLE_AOT) && !defined(DISABLE_JIT) */
8576 #define rot(x,k) (((x)<<(k)) | ((x)>>(32-(k))))
8577 #define mix(a,b,c) { \
8578 a -= c; a ^= rot(c, 4); c += b; \
8579 b -= a; b ^= rot(a, 6); a += c; \
8580 c -= b; c ^= rot(b, 8); b += a; \
8581 a -= c; a ^= rot(c,16); c += b; \
8582 b -= a; b ^= rot(a,19); a += c; \
8583 c -= b; c ^= rot(b, 4); b += a; \
8585 #define final(a,b,c) { \
8586 c ^= b; c -= rot(b,14); \
8587 a ^= c; a -= rot(c,11); \
8588 b ^= a; b -= rot(a,25); \
8589 c ^= b; c -= rot(b,16); \
8590 a ^= c; a -= rot(c,4); \
8591 b ^= a; b -= rot(a,14); \
8592 c ^= b; c -= rot(b,24); \
8595 static guint
8596 mono_aot_type_hash (MonoType *t1)
8598 guint hash = t1->type;
8600 hash |= t1->byref << 6; /* do not collide with t1->type values */
8601 switch (t1->type) {
8602 case MONO_TYPE_VALUETYPE:
8603 case MONO_TYPE_CLASS:
8604 case MONO_TYPE_SZARRAY:
8605 /* check if the distribution is good enough */
8606 return ((hash << 5) - hash) ^ mono_metadata_str_hash (t1->data.klass->name);
8607 case MONO_TYPE_PTR:
8608 return ((hash << 5) - hash) ^ mono_metadata_type_hash (t1->data.type);
8609 case MONO_TYPE_ARRAY:
8610 return ((hash << 5) - hash) ^ mono_metadata_type_hash (&t1->data.array->eklass->byval_arg);
8611 case MONO_TYPE_GENERICINST:
8612 return ((hash << 5) - hash) ^ 0;
8613 default:
8614 return hash;
8619 * mono_aot_method_hash:
8621 * Return a hash code for methods which only depends on metadata.
8623 guint32
8624 mono_aot_method_hash (MonoMethod *method)
8626 MonoMethodSignature *sig;
8627 MonoClass *klass;
8628 int i, hindex;
8629 int hashes_count;
8630 guint32 *hashes_start, *hashes;
8631 guint32 a, b, c;
8632 MonoGenericInst *class_ginst = NULL;
8633 MonoGenericInst *ginst = NULL;
8635 /* Similar to the hash in mono_method_get_imt_slot () */
8637 sig = mono_method_signature (method);
8639 if (mono_class_is_ginst (method->klass))
8640 class_ginst = mono_class_get_generic_class (method->klass)->context.class_inst;
8641 if (method->is_inflated)
8642 ginst = ((MonoMethodInflated*)method)->context.method_inst;
8644 hashes_count = sig->param_count + 5 + (class_ginst ? class_ginst->type_argc : 0) + (ginst ? ginst->type_argc : 0);
8645 hashes_start = (guint32 *)g_malloc0 (hashes_count * sizeof (guint32));
8646 hashes = hashes_start;
8648 /* Some wrappers are assigned to random classes */
8649 if (!method->wrapper_type || method->wrapper_type == MONO_WRAPPER_REMOTING_INVOKE_WITH_CHECK)
8650 klass = method->klass;
8651 else
8652 klass = mono_defaults.object_class;
8654 if (!method->wrapper_type) {
8655 char *full_name;
8657 if (mono_class_is_ginst (klass))
8658 full_name = mono_type_full_name (&mono_class_get_generic_class (klass)->container_class->byval_arg);
8659 else
8660 full_name = mono_type_full_name (&klass->byval_arg);
8662 hashes [0] = mono_metadata_str_hash (full_name);
8663 hashes [1] = 0;
8664 g_free (full_name);
8665 } else {
8666 hashes [0] = mono_metadata_str_hash (klass->name);
8667 hashes [1] = mono_metadata_str_hash (klass->name_space);
8669 if (method->wrapper_type == MONO_WRAPPER_STFLD || method->wrapper_type == MONO_WRAPPER_LDFLD || method->wrapper_type == MONO_WRAPPER_LDFLDA)
8670 /* The method name includes a stringified pointer */
8671 hashes [2] = 0;
8672 else
8673 hashes [2] = mono_metadata_str_hash (method->name);
8674 hashes [3] = method->wrapper_type;
8675 hashes [4] = mono_aot_type_hash (sig->ret);
8676 hindex = 5;
8677 for (i = 0; i < sig->param_count; i++) {
8678 hashes [hindex ++] = mono_aot_type_hash (sig->params [i]);
8680 if (class_ginst) {
8681 for (i = 0; i < class_ginst->type_argc; ++i)
8682 hashes [hindex ++] = mono_aot_type_hash (class_ginst->type_argv [i]);
8684 if (ginst) {
8685 for (i = 0; i < ginst->type_argc; ++i)
8686 hashes [hindex ++] = mono_aot_type_hash (ginst->type_argv [i]);
8688 g_assert (hindex == hashes_count);
8690 /* Setup internal state */
8691 a = b = c = 0xdeadbeef + (((guint32)hashes_count)<<2);
8693 /* Handle most of the hashes */
8694 while (hashes_count > 3) {
8695 a += hashes [0];
8696 b += hashes [1];
8697 c += hashes [2];
8698 mix (a,b,c);
8699 hashes_count -= 3;
8700 hashes += 3;
8703 /* Handle the last 3 hashes (all the case statements fall through) */
8704 switch (hashes_count) {
8705 case 3 : c += hashes [2];
8706 case 2 : b += hashes [1];
8707 case 1 : a += hashes [0];
8708 final (a,b,c);
8709 case 0: /* nothing left to add */
8710 break;
8713 g_free (hashes_start);
8715 return c;
8717 #undef rot
8718 #undef mix
8719 #undef final
8722 * mono_aot_get_array_helper_from_wrapper;
8724 * Get the helper method in Array called by an array wrapper method.
8726 MonoMethod*
8727 mono_aot_get_array_helper_from_wrapper (MonoMethod *method)
8729 MonoMethod *m;
8730 const char *prefix;
8731 MonoGenericContext ctx;
8732 MonoType *args [16];
8733 char *mname, *iname, *s, *s2, *helper_name = NULL;
8735 prefix = "System.Collections.Generic";
8736 s = g_strdup_printf ("%s", method->name + strlen (prefix) + 1);
8737 s2 = strstr (s, "`1.");
8738 g_assert (s2);
8739 s2 [0] = '\0';
8740 iname = s;
8741 mname = s2 + 3;
8743 //printf ("X: %s %s\n", iname, mname);
8745 if (!strcmp (iname, "IList"))
8746 helper_name = g_strdup_printf ("InternalArray__%s", mname);
8747 else
8748 helper_name = g_strdup_printf ("InternalArray__%s_%s", iname, mname);
8749 m = mono_class_get_method_from_name (mono_defaults.array_class, helper_name, mono_method_signature (method)->param_count);
8750 g_assert (m);
8751 g_free (helper_name);
8752 g_free (s);
8754 if (m->is_generic) {
8755 MonoError error;
8756 memset (&ctx, 0, sizeof (ctx));
8757 args [0] = &method->klass->element_class->byval_arg;
8758 ctx.method_inst = mono_metadata_get_generic_inst (1, args);
8759 m = mono_class_inflate_generic_method_checked (m, &ctx, &error);
8760 g_assert (mono_error_ok (&error)); /* FIXME don't swallow the error */
8763 return m;
8766 #if !defined(DISABLE_AOT) && !defined(DISABLE_JIT)
8768 typedef struct HashEntry {
8769 guint32 key, value, index;
8770 struct HashEntry *next;
8771 } HashEntry;
8774 * emit_extra_methods:
8776 * Emit methods which are not in the METHOD table, like wrappers.
8778 static void
8779 emit_extra_methods (MonoAotCompile *acfg)
8781 int i, table_size, buf_size;
8782 guint8 *p, *buf;
8783 guint32 *info_offsets;
8784 guint32 hash;
8785 GPtrArray *table;
8786 HashEntry *entry, *new_entry;
8787 int nmethods, max_chain_length;
8788 int *chain_lengths;
8790 info_offsets = g_new0 (guint32, acfg->extra_methods->len);
8792 /* Emit method info */
8793 nmethods = 0;
8794 for (i = 0; i < acfg->extra_methods->len; ++i) {
8795 MonoMethod *method = (MonoMethod *)g_ptr_array_index (acfg->extra_methods, i);
8796 MonoCompile *cfg = (MonoCompile *)g_hash_table_lookup (acfg->method_to_cfg, method);
8798 if (!cfg)
8799 continue;
8801 buf_size = 10240;
8802 p = buf = (guint8 *)g_malloc (buf_size);
8804 nmethods ++;
8806 method = cfg->method_to_register;
8808 encode_method_ref (acfg, method, p, &p);
8810 g_assert ((p - buf) < buf_size);
8812 info_offsets [i] = add_to_blob (acfg, buf, p - buf);
8813 g_free (buf);
8817 * Construct a chained hash table for mapping indexes in extra_method_info to
8818 * method indexes.
8820 table_size = g_spaced_primes_closest ((int)(nmethods * 1.5));
8821 table = g_ptr_array_sized_new (table_size);
8822 for (i = 0; i < table_size; ++i)
8823 g_ptr_array_add (table, NULL);
8824 chain_lengths = g_new0 (int, table_size);
8825 max_chain_length = 0;
8826 for (i = 0; i < acfg->extra_methods->len; ++i) {
8827 MonoMethod *method = (MonoMethod *)g_ptr_array_index (acfg->extra_methods, i);
8828 MonoCompile *cfg = (MonoCompile *)g_hash_table_lookup (acfg->method_to_cfg, method);
8829 guint32 key, value;
8831 if (!cfg)
8832 continue;
8834 key = info_offsets [i];
8835 value = get_method_index (acfg, method);
8837 hash = mono_aot_method_hash (method) % table_size;
8838 //printf ("X: %s %x\n", mono_method_get_full_name (method), mono_aot_method_hash (method));
8840 chain_lengths [hash] ++;
8841 max_chain_length = MAX (max_chain_length, chain_lengths [hash]);
8843 new_entry = (HashEntry *)mono_mempool_alloc0 (acfg->mempool, sizeof (HashEntry));
8844 new_entry->key = key;
8845 new_entry->value = value;
8847 entry = (HashEntry *)g_ptr_array_index (table, hash);
8848 if (entry == NULL) {
8849 new_entry->index = hash;
8850 g_ptr_array_index (table, hash) = new_entry;
8851 } else {
8852 while (entry->next)
8853 entry = entry->next;
8855 entry->next = new_entry;
8856 new_entry->index = table->len;
8857 g_ptr_array_add (table, new_entry);
8860 g_free (chain_lengths);
8862 //printf ("MAX: %d\n", max_chain_length);
8864 buf_size = table->len * 12 + 4;
8865 p = buf = (guint8 *)g_malloc (buf_size);
8866 encode_int (table_size, p, &p);
8868 for (i = 0; i < table->len; ++i) {
8869 HashEntry *entry = (HashEntry *)g_ptr_array_index (table, i);
8871 if (entry == NULL) {
8872 encode_int (0, p, &p);
8873 encode_int (0, p, &p);
8874 encode_int (0, p, &p);
8875 } else {
8876 //g_assert (entry->key > 0);
8877 encode_int (entry->key, p, &p);
8878 encode_int (entry->value, p, &p);
8879 if (entry->next)
8880 encode_int (entry->next->index, p, &p);
8881 else
8882 encode_int (0, p, &p);
8885 g_assert (p - buf <= buf_size);
8887 /* Emit the table */
8888 emit_aot_data (acfg, MONO_AOT_TABLE_EXTRA_METHOD_TABLE, "extra_method_table", buf, p - buf);
8890 g_free (buf);
8893 * Emit a table reverse mapping method indexes to their index in extra_method_info.
8894 * This is used by mono_aot_find_jit_info ().
8896 buf_size = acfg->extra_methods->len * 8 + 4;
8897 p = buf = (guint8 *)g_malloc (buf_size);
8898 encode_int (acfg->extra_methods->len, p, &p);
8899 for (i = 0; i < acfg->extra_methods->len; ++i) {
8900 MonoMethod *method = (MonoMethod *)g_ptr_array_index (acfg->extra_methods, i);
8902 encode_int (get_method_index (acfg, method), p, &p);
8903 encode_int (info_offsets [i], p, &p);
8905 emit_aot_data (acfg, MONO_AOT_TABLE_EXTRA_METHOD_INFO_OFFSETS, "extra_method_info_offsets", buf, p - buf);
8907 g_free (buf);
8908 g_free (info_offsets);
8909 g_ptr_array_free (table, TRUE);
8912 static void
8913 generate_aotid (guint8* aotid)
8915 gpointer rand_handle;
8916 MonoError error;
8918 mono_rand_open ();
8919 rand_handle = mono_rand_init (NULL, 0);
8921 mono_rand_try_get_bytes (&rand_handle, aotid, 16, &error);
8922 mono_error_assert_ok (&error);
8924 mono_rand_close (rand_handle);
8927 static void
8928 emit_exception_info (MonoAotCompile *acfg)
8930 int i;
8931 gint32 *offsets;
8932 SeqPointData sp_data;
8933 gboolean seq_points_to_file = FALSE;
8935 offsets = g_new0 (gint32, acfg->nmethods);
8936 for (i = 0; i < acfg->nmethods; ++i) {
8937 if (acfg->cfgs [i]) {
8938 MonoCompile *cfg = acfg->cfgs [i];
8940 // By design aot-runtime decode_exception_debug_info is not able to load sequence point debug data from a file.
8941 // As it is not possible to load debug data from a file its is also not possible to store it in a file.
8942 gboolean method_seq_points_to_file = acfg->aot_opts.gen_msym_dir &&
8943 cfg->gen_seq_points && !cfg->gen_sdb_seq_points;
8944 gboolean method_seq_points_to_binary = cfg->gen_seq_points && !method_seq_points_to_file;
8946 emit_exception_debug_info (acfg, cfg, method_seq_points_to_binary);
8947 offsets [i] = cfg->ex_info_offset;
8949 if (method_seq_points_to_file) {
8950 if (!seq_points_to_file) {
8951 mono_seq_point_data_init (&sp_data, acfg->nmethods);
8952 seq_points_to_file = TRUE;
8954 mono_seq_point_data_add (&sp_data, cfg->method->token, cfg->method_index, cfg->seq_point_info);
8956 } else {
8957 offsets [i] = 0;
8961 if (seq_points_to_file) {
8962 char *aotid = mono_guid_to_string_minimal (acfg->image->aotid);
8963 char *dir = g_build_filename (acfg->aot_opts.gen_msym_dir_path, aotid, NULL);
8964 char *image_basename = g_path_get_basename (acfg->image->name);
8965 char *aot_file = g_strdup_printf("%s%s", image_basename, SEQ_POINT_AOT_EXT);
8966 char *aot_file_path = g_build_filename (dir, aot_file, NULL);
8968 if (g_ensure_directory_exists (aot_file_path) == FALSE) {
8969 fprintf (stderr, "AOT : failed to create msym directory: %s\n", aot_file_path);
8970 exit (1);
8973 mono_seq_point_data_write (&sp_data, aot_file_path);
8974 mono_seq_point_data_free (&sp_data);
8976 g_free (aotid);
8977 g_free (dir);
8978 g_free (image_basename);
8979 g_free (aot_file);
8980 g_free (aot_file_path);
8983 acfg->stats.offsets_size += emit_offset_table (acfg, "ex_info_offsets", MONO_AOT_TABLE_EX_INFO_OFFSETS, acfg->nmethods, 10, offsets);
8984 g_free (offsets);
8987 static void
8988 emit_unwind_info (MonoAotCompile *acfg)
8990 int i;
8991 char symbol [128];
8993 if (acfg->aot_opts.llvm_only) {
8994 g_assert (acfg->unwind_ops->len == 0);
8995 return;
8999 * The unwind info contains a lot of duplicates so we emit each unique
9000 * entry once, and only store the offset from the start of the table in the
9001 * exception info.
9004 sprintf (symbol, "unwind_info");
9005 emit_section_change (acfg, RODATA_SECT, 1);
9006 emit_alignment (acfg, 8);
9007 emit_info_symbol (acfg, symbol);
9009 for (i = 0; i < acfg->unwind_ops->len; ++i) {
9010 guint32 index = GPOINTER_TO_UINT (g_ptr_array_index (acfg->unwind_ops, i));
9011 guint8 *unwind_info;
9012 guint32 unwind_info_len;
9013 guint8 buf [16];
9014 guint8 *p;
9016 unwind_info = mono_get_cached_unwind_info (index, &unwind_info_len);
9018 p = buf;
9019 encode_value (unwind_info_len, p, &p);
9020 emit_bytes (acfg, buf, p - buf);
9021 emit_bytes (acfg, unwind_info, unwind_info_len);
9023 acfg->stats.unwind_info_size += (p - buf) + unwind_info_len;
9027 static void
9028 emit_class_info (MonoAotCompile *acfg)
9030 int i;
9031 gint32 *offsets;
9033 offsets = g_new0 (gint32, acfg->image->tables [MONO_TABLE_TYPEDEF].rows);
9034 for (i = 0; i < acfg->image->tables [MONO_TABLE_TYPEDEF].rows; ++i)
9035 offsets [i] = emit_klass_info (acfg, MONO_TOKEN_TYPE_DEF | (i + 1));
9037 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);
9038 g_free (offsets);
9041 typedef struct ClassNameTableEntry {
9042 guint32 token, index;
9043 struct ClassNameTableEntry *next;
9044 } ClassNameTableEntry;
9046 static void
9047 emit_class_name_table (MonoAotCompile *acfg)
9049 int i, table_size, buf_size;
9050 guint32 token, hash;
9051 MonoClass *klass;
9052 GPtrArray *table;
9053 char *full_name;
9054 guint8 *buf, *p;
9055 ClassNameTableEntry *entry, *new_entry;
9058 * Construct a chained hash table for mapping class names to typedef tokens.
9060 table_size = g_spaced_primes_closest ((int)(acfg->image->tables [MONO_TABLE_TYPEDEF].rows * 1.5));
9061 table = g_ptr_array_sized_new (table_size);
9062 for (i = 0; i < table_size; ++i)
9063 g_ptr_array_add (table, NULL);
9064 for (i = 0; i < acfg->image->tables [MONO_TABLE_TYPEDEF].rows; ++i) {
9065 MonoError error;
9066 token = MONO_TOKEN_TYPE_DEF | (i + 1);
9067 klass = mono_class_get_checked (acfg->image, token, &error);
9068 if (!klass) {
9069 mono_error_cleanup (&error);
9070 continue;
9072 full_name = mono_type_get_name_full (mono_class_get_type (klass), MONO_TYPE_NAME_FORMAT_FULL_NAME);
9073 hash = mono_metadata_str_hash (full_name) % table_size;
9074 g_free (full_name);
9076 /* FIXME: Allocate from the mempool */
9077 new_entry = g_new0 (ClassNameTableEntry, 1);
9078 new_entry->token = token;
9080 entry = (ClassNameTableEntry *)g_ptr_array_index (table, hash);
9081 if (entry == NULL) {
9082 new_entry->index = hash;
9083 g_ptr_array_index (table, hash) = new_entry;
9084 } else {
9085 while (entry->next)
9086 entry = entry->next;
9088 entry->next = new_entry;
9089 new_entry->index = table->len;
9090 g_ptr_array_add (table, new_entry);
9094 /* Emit the table */
9095 buf_size = table->len * 4 + 4;
9096 p = buf = (guint8 *)g_malloc0 (buf_size);
9098 /* FIXME: Optimize memory usage */
9099 g_assert (table_size < 65000);
9100 encode_int16 (table_size, p, &p);
9101 g_assert (table->len < 65000);
9102 for (i = 0; i < table->len; ++i) {
9103 ClassNameTableEntry *entry = (ClassNameTableEntry *)g_ptr_array_index (table, i);
9105 if (entry == NULL) {
9106 encode_int16 (0, p, &p);
9107 encode_int16 (0, p, &p);
9108 } else {
9109 encode_int16 (mono_metadata_token_index (entry->token), p, &p);
9110 if (entry->next)
9111 encode_int16 (entry->next->index, p, &p);
9112 else
9113 encode_int16 (0, p, &p);
9115 g_free (entry);
9117 g_assert (p - buf <= buf_size);
9118 g_ptr_array_free (table, TRUE);
9120 emit_aot_data (acfg, MONO_AOT_TABLE_CLASS_NAME, "class_name_table", buf, p - buf);
9122 g_free (buf);
9125 static void
9126 emit_image_table (MonoAotCompile *acfg)
9128 int i, buf_size;
9129 guint8 *buf, *p;
9132 * The image table is small but referenced in a lot of places.
9133 * So we emit it at once, and reference its elements by an index.
9135 buf_size = acfg->image_table->len * 28 + 4;
9136 for (i = 0; i < acfg->image_table->len; i++) {
9137 MonoImage *image = (MonoImage*)g_ptr_array_index (acfg->image_table, i);
9138 MonoAssemblyName *aname = &image->assembly->aname;
9140 buf_size += strlen (image->assembly_name) + strlen (image->guid) + (aname->culture ? strlen (aname->culture) : 1) + strlen ((char*)aname->public_key_token) + 4;
9143 buf = p = (guint8 *)g_malloc0 (buf_size);
9144 encode_int (acfg->image_table->len, p, &p);
9145 for (i = 0; i < acfg->image_table->len; i++) {
9146 MonoImage *image = (MonoImage*)g_ptr_array_index (acfg->image_table, i);
9147 MonoAssemblyName *aname = &image->assembly->aname;
9149 /* FIXME: Support multi-module assemblies */
9150 g_assert (image->assembly->image == image);
9152 encode_string (image->assembly_name, p, &p);
9153 encode_string (image->guid, p, &p);
9154 encode_string (aname->culture ? aname->culture : "", p, &p);
9155 encode_string ((const char*)aname->public_key_token, p, &p);
9157 while (GPOINTER_TO_UINT (p) % 8 != 0)
9158 p ++;
9160 encode_int (aname->flags, p, &p);
9161 encode_int (aname->major, p, &p);
9162 encode_int (aname->minor, p, &p);
9163 encode_int (aname->build, p, &p);
9164 encode_int (aname->revision, p, &p);
9166 g_assert (p - buf <= buf_size);
9168 emit_aot_data (acfg, MONO_AOT_TABLE_IMAGE_TABLE, "image_table", buf, p - buf);
9170 g_free (buf);
9173 static void
9174 emit_got_info (MonoAotCompile *acfg, gboolean llvm)
9176 int i, first_plt_got_patch = 0, buf_size;
9177 guint8 *p, *buf;
9178 guint32 *got_info_offsets;
9179 GotInfo *info = llvm ? &acfg->llvm_got_info : &acfg->got_info;
9181 /* Add the patches needed by the PLT to the GOT */
9182 if (!llvm) {
9183 acfg->plt_got_offset_base = acfg->got_offset;
9184 first_plt_got_patch = info->got_patches->len;
9185 for (i = 1; i < acfg->plt_offset; ++i) {
9186 MonoPltEntry *plt_entry = (MonoPltEntry *)g_hash_table_lookup (acfg->plt_offset_to_entry, GUINT_TO_POINTER (i));
9188 g_ptr_array_add (info->got_patches, plt_entry->ji);
9190 acfg->stats.got_slot_types [plt_entry->ji->type] ++;
9193 acfg->got_offset += acfg->plt_offset;
9197 * FIXME:
9198 * - optimize offsets table.
9199 * - reduce number of exported symbols.
9200 * - emit info for a klass only once.
9201 * - determine when a method uses a GOT slot which is guaranteed to be already
9202 * initialized.
9203 * - clean up and document the code.
9204 * - use String.Empty in class libs.
9207 /* Encode info required to decode shared GOT entries */
9208 buf_size = info->got_patches->len * 128;
9209 p = buf = (guint8 *)mono_mempool_alloc (acfg->mempool, buf_size);
9210 got_info_offsets = (guint32 *)mono_mempool_alloc (acfg->mempool, info->got_patches->len * sizeof (guint32));
9211 if (!llvm) {
9212 acfg->plt_got_info_offsets = (guint32 *)mono_mempool_alloc (acfg->mempool, acfg->plt_offset * sizeof (guint32));
9213 /* Unused */
9214 if (acfg->plt_offset)
9215 acfg->plt_got_info_offsets [0] = 0;
9217 for (i = 0; i < info->got_patches->len; ++i) {
9218 MonoJumpInfo *ji = (MonoJumpInfo *)g_ptr_array_index (info->got_patches, i);
9219 guint8 *p2;
9221 p = buf;
9223 encode_value (ji->type, p, &p);
9224 p2 = p;
9225 encode_patch (acfg, ji, p, &p);
9226 acfg->stats.got_slot_info_sizes [ji->type] += p - p2;
9227 g_assert (p - buf <= buf_size);
9228 got_info_offsets [i] = add_to_blob (acfg, buf, p - buf);
9230 if (!llvm && i >= first_plt_got_patch)
9231 acfg->plt_got_info_offsets [i - first_plt_got_patch + 1] = got_info_offsets [i];
9232 acfg->stats.got_info_size += p - buf;
9235 /* Emit got_info_offsets table */
9237 /* No need to emit offsets for the got plt entries, the plt embeds them directly */
9238 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);
9241 static void
9242 emit_got (MonoAotCompile *acfg)
9244 char symbol [MAX_SYMBOL_SIZE];
9246 if (acfg->aot_opts.llvm_only)
9247 return;
9249 /* Don't make GOT global so accesses to it don't need relocations */
9250 sprintf (symbol, "%s", acfg->got_symbol);
9252 #ifdef TARGET_MACH
9253 emit_unset_mode (acfg);
9254 fprintf (acfg->fp, ".section __DATA, __bss\n");
9255 emit_alignment (acfg, 8);
9256 if (acfg->llvm)
9257 emit_info_symbol (acfg, "jit_got");
9258 fprintf (acfg->fp, ".lcomm %s, %d\n", acfg->got_symbol, (int)(acfg->got_offset * sizeof (gpointer)));
9259 #else
9260 emit_section_change (acfg, ".bss", 0);
9261 emit_alignment (acfg, 8);
9262 if (acfg->aot_opts.write_symbols)
9263 emit_local_symbol (acfg, symbol, "got_end", FALSE);
9264 emit_label (acfg, symbol);
9265 if (acfg->llvm)
9266 emit_info_symbol (acfg, "jit_got");
9267 if (acfg->got_offset > 0)
9268 emit_zero_bytes (acfg, (int)(acfg->got_offset * sizeof (gpointer)));
9269 #endif
9271 sprintf (symbol, "got_end");
9272 emit_label (acfg, symbol);
9275 typedef struct GlobalsTableEntry {
9276 guint32 value, index;
9277 struct GlobalsTableEntry *next;
9278 } GlobalsTableEntry;
9280 #ifdef TARGET_WIN32_MSVC
9281 #define DLL_ENTRY_POINT "DllMain"
9283 static void
9284 emit_library_info (MonoAotCompile *acfg)
9286 // Only include for shared libraries linked directly from generated object.
9287 if (link_shared_library (acfg)) {
9288 char *name = NULL;
9289 char symbol [MAX_SYMBOL_SIZE];
9291 // Ask linker to export all global symbols.
9292 emit_section_change (acfg, ".drectve", 0);
9293 for (guint i = 0; i < acfg->globals->len; ++i) {
9294 name = (char *)g_ptr_array_index (acfg->globals, i);
9295 g_assert (name != NULL);
9296 sprintf_s (symbol, MAX_SYMBOL_SIZE, " /EXPORT:%s", name);
9297 emit_string (acfg, symbol);
9300 // Emit DLLMain function, needed by MSVC linker for DLL's.
9301 // NOTE, DllMain should not go into exports above.
9302 emit_section_change (acfg, ".text", 0);
9303 emit_global (acfg, DLL_ENTRY_POINT, TRUE);
9304 emit_label (acfg, DLL_ENTRY_POINT);
9306 // Simple implementation of DLLMain, just returning TRUE.
9307 // For more information about DLLMain: https://msdn.microsoft.com/en-us/library/windows/desktop/ms682583(v=vs.85).aspx
9308 fprintf (acfg->fp, "movl $1, %%eax\n");
9309 fprintf (acfg->fp, "ret\n");
9311 // Inform linker about our dll entry function.
9312 emit_section_change (acfg, ".drectve", 0);
9313 emit_string (acfg, "/ENTRY:" DLL_ENTRY_POINT);
9314 return;
9318 #else
9320 static inline void
9321 emit_library_info (MonoAotCompile *acfg)
9323 return;
9325 #endif
9327 static void
9328 emit_globals (MonoAotCompile *acfg)
9330 int i, table_size;
9331 guint32 hash;
9332 GPtrArray *table;
9333 char symbol [1024];
9334 GlobalsTableEntry *entry, *new_entry;
9336 if (!acfg->aot_opts.static_link)
9337 return;
9339 if (acfg->aot_opts.llvm_only) {
9340 g_assert (acfg->globals->len == 0);
9341 return;
9345 * When static linking, we emit a table containing our globals.
9349 * Construct a chained hash table for mapping global names to their index in
9350 * the globals table.
9352 table_size = g_spaced_primes_closest ((int)(acfg->globals->len * 1.5));
9353 table = g_ptr_array_sized_new (table_size);
9354 for (i = 0; i < table_size; ++i)
9355 g_ptr_array_add (table, NULL);
9356 for (i = 0; i < acfg->globals->len; ++i) {
9357 char *name = (char *)g_ptr_array_index (acfg->globals, i);
9359 hash = mono_metadata_str_hash (name) % table_size;
9361 /* FIXME: Allocate from the mempool */
9362 new_entry = g_new0 (GlobalsTableEntry, 1);
9363 new_entry->value = i;
9365 entry = (GlobalsTableEntry *)g_ptr_array_index (table, hash);
9366 if (entry == NULL) {
9367 new_entry->index = hash;
9368 g_ptr_array_index (table, hash) = new_entry;
9369 } else {
9370 while (entry->next)
9371 entry = entry->next;
9373 entry->next = new_entry;
9374 new_entry->index = table->len;
9375 g_ptr_array_add (table, new_entry);
9379 /* Emit the table */
9380 sprintf (symbol, ".Lglobals_hash");
9381 emit_section_change (acfg, RODATA_SECT, 0);
9382 emit_alignment (acfg, 8);
9383 emit_label (acfg, symbol);
9385 /* FIXME: Optimize memory usage */
9386 g_assert (table_size < 65000);
9387 emit_int16 (acfg, table_size);
9388 for (i = 0; i < table->len; ++i) {
9389 GlobalsTableEntry *entry = (GlobalsTableEntry *)g_ptr_array_index (table, i);
9391 if (entry == NULL) {
9392 emit_int16 (acfg, 0);
9393 emit_int16 (acfg, 0);
9394 } else {
9395 emit_int16 (acfg, entry->value + 1);
9396 if (entry->next)
9397 emit_int16 (acfg, entry->next->index);
9398 else
9399 emit_int16 (acfg, 0);
9403 /* Emit the names */
9404 for (i = 0; i < acfg->globals->len; ++i) {
9405 char *name = (char *)g_ptr_array_index (acfg->globals, i);
9407 sprintf (symbol, "name_%d", i);
9408 emit_section_change (acfg, RODATA_SECT, 1);
9409 #ifdef TARGET_MACH
9410 emit_alignment (acfg, 4);
9411 #endif
9412 emit_label (acfg, symbol);
9413 emit_string (acfg, name);
9416 /* Emit the globals table */
9417 sprintf (symbol, "globals");
9418 emit_section_change (acfg, ".data", 0);
9419 /* This is not a global, since it is accessed by the init function */
9420 emit_alignment (acfg, 8);
9421 emit_info_symbol (acfg, symbol);
9423 sprintf (symbol, "%sglobals_hash", acfg->temp_prefix);
9424 emit_pointer (acfg, symbol);
9426 for (i = 0; i < acfg->globals->len; ++i) {
9427 char *name = (char *)g_ptr_array_index (acfg->globals, i);
9429 sprintf (symbol, "name_%d", i);
9430 emit_pointer (acfg, symbol);
9432 g_assert (strlen (name) < sizeof (symbol));
9433 sprintf (symbol, "%s", name);
9434 emit_pointer (acfg, symbol);
9436 /* Null terminate the table */
9437 emit_int32 (acfg, 0);
9438 emit_int32 (acfg, 0);
9441 static void
9442 emit_mem_end (MonoAotCompile *acfg)
9444 char symbol [128];
9446 if (acfg->aot_opts.llvm_only)
9447 return;
9449 sprintf (symbol, "mem_end");
9450 emit_section_change (acfg, ".text", 1);
9451 emit_alignment_code (acfg, 8);
9452 emit_label (acfg, symbol);
9455 static void
9456 init_aot_file_info (MonoAotCompile *acfg, MonoAotFileInfo *info)
9458 int i;
9460 info->version = MONO_AOT_FILE_VERSION;
9461 info->plt_got_offset_base = acfg->plt_got_offset_base;
9462 info->got_size = acfg->got_offset * sizeof (gpointer);
9463 info->plt_size = acfg->plt_offset;
9464 info->nmethods = acfg->nmethods;
9465 info->flags = acfg->flags;
9466 info->opts = acfg->opts;
9467 info->simd_opts = acfg->simd_opts;
9468 info->gc_name_index = acfg->gc_name_offset;
9469 info->datafile_size = acfg->datafile_offset;
9470 for (i = 0; i < MONO_AOT_TABLE_NUM; ++i)
9471 info->table_offsets [i] = acfg->table_offsets [i];
9472 for (i = 0; i < MONO_AOT_TRAMP_NUM; ++i)
9473 info->num_trampolines [i] = acfg->num_trampolines [i];
9474 for (i = 0; i < MONO_AOT_TRAMP_NUM; ++i)
9475 info->trampoline_got_offset_base [i] = acfg->trampoline_got_offset_base [i];
9476 for (i = 0; i < MONO_AOT_TRAMP_NUM; ++i)
9477 info->trampoline_size [i] = acfg->trampoline_size [i];
9478 info->num_rgctx_fetch_trampolines = acfg->aot_opts.nrgctx_fetch_trampolines;
9480 info->double_align = MONO_ABI_ALIGNOF (double);
9481 info->long_align = MONO_ABI_ALIGNOF (gint64);
9482 info->generic_tramp_num = MONO_TRAMPOLINE_NUM;
9483 info->tramp_page_size = acfg->tramp_page_size;
9484 info->nshared_got_entries = acfg->nshared_got_entries;
9485 for (i = 0; i < MONO_AOT_TRAMP_NUM; ++i)
9486 info->tramp_page_code_offsets [i] = acfg->tramp_page_code_offsets [i];
9488 memcpy(&info->aotid, acfg->image->aotid, 16);
9491 static void
9492 emit_aot_file_info (MonoAotCompile *acfg, MonoAotFileInfo *info)
9494 char symbol [MAX_SYMBOL_SIZE];
9495 int i, sindex;
9496 const char **symbols;
9498 symbols = g_new0 (const char *, MONO_AOT_FILE_INFO_NUM_SYMBOLS);
9499 sindex = 0;
9500 symbols [sindex ++] = acfg->got_symbol;
9501 if (acfg->llvm) {
9502 symbols [sindex ++] = g_strdup_printf ("%s%s", acfg->user_symbol_prefix, acfg->llvm_got_symbol);
9503 symbols [sindex ++] = acfg->llvm_eh_frame_symbol;
9504 } else {
9505 symbols [sindex ++] = NULL;
9506 symbols [sindex ++] = NULL;
9508 /* llvm_get_method */
9509 symbols [sindex ++] = NULL;
9510 /* llvm_get_unbox_tramp */
9511 symbols [sindex ++] = NULL;
9512 if (!acfg->aot_opts.llvm_only) {
9513 symbols [sindex ++] = "jit_code_start";
9514 symbols [sindex ++] = "jit_code_end";
9515 symbols [sindex ++] = "method_addresses";
9516 } else {
9517 symbols [sindex ++] = NULL;
9518 symbols [sindex ++] = NULL;
9519 symbols [sindex ++] = NULL;
9521 if (acfg->data_outfile) {
9522 for (i = 0; i < MONO_AOT_TABLE_NUM; ++i)
9523 symbols [sindex ++] = NULL;
9524 } else {
9525 symbols [sindex ++] = "blob";
9526 symbols [sindex ++] = "class_name_table";
9527 symbols [sindex ++] = "class_info_offsets";
9528 symbols [sindex ++] = "method_info_offsets";
9529 symbols [sindex ++] = "ex_info_offsets";
9530 symbols [sindex ++] = "extra_method_info_offsets";
9531 symbols [sindex ++] = "extra_method_table";
9532 symbols [sindex ++] = "got_info_offsets";
9533 if (acfg->llvm)
9534 symbols [sindex ++] = "llvm_got_info_offsets";
9535 else
9536 symbols [sindex ++] = NULL;
9537 symbols [sindex ++] = "image_table";
9539 symbols [sindex ++] = "mem_end";
9540 symbols [sindex ++] = "assembly_guid";
9541 symbols [sindex ++] = "runtime_version";
9542 if (acfg->num_trampoline_got_entries) {
9543 symbols [sindex ++] = "specific_trampolines";
9544 symbols [sindex ++] = "static_rgctx_trampolines";
9545 symbols [sindex ++] = "imt_trampolines";
9546 symbols [sindex ++] = "gsharedvt_arg_trampolines";
9547 } else {
9548 symbols [sindex ++] = NULL;
9549 symbols [sindex ++] = NULL;
9550 symbols [sindex ++] = NULL;
9551 symbols [sindex ++] = NULL;
9553 if (acfg->aot_opts.static_link) {
9554 symbols [sindex ++] = "globals";
9555 } else {
9556 symbols [sindex ++] = NULL;
9558 symbols [sindex ++] = "assembly_name";
9559 symbols [sindex ++] = "plt";
9560 symbols [sindex ++] = "plt_end";
9561 symbols [sindex ++] = "unwind_info";
9562 if (!acfg->aot_opts.llvm_only) {
9563 symbols [sindex ++] = "unbox_trampolines";
9564 symbols [sindex ++] = "unbox_trampolines_end";
9565 symbols [sindex ++] = "unbox_trampoline_addresses";
9566 } else {
9567 symbols [sindex ++] = NULL;
9568 symbols [sindex ++] = NULL;
9569 symbols [sindex ++] = NULL;
9572 g_assert (sindex == MONO_AOT_FILE_INFO_NUM_SYMBOLS);
9574 sprintf (symbol, "%smono_aot_file_info", acfg->user_symbol_prefix);
9575 emit_section_change (acfg, ".data", 0);
9576 emit_alignment (acfg, 8);
9577 emit_label (acfg, symbol);
9578 if (!acfg->aot_opts.static_link)
9579 emit_global (acfg, symbol, FALSE);
9581 /* The data emitted here must match MonoAotFileInfo. */
9583 emit_int32 (acfg, info->version);
9584 emit_int32 (acfg, info->dummy);
9587 * We emit pointers to our data structures instead of emitting global symbols which
9588 * point to them, to reduce the number of globals, and because using globals leads to
9589 * various problems (i.e. arm/thumb).
9591 for (i = 0; i < MONO_AOT_FILE_INFO_NUM_SYMBOLS; ++i)
9592 emit_pointer (acfg, symbols [i]);
9594 emit_int32 (acfg, info->plt_got_offset_base);
9595 emit_int32 (acfg, info->got_size);
9596 emit_int32 (acfg, info->plt_size);
9597 emit_int32 (acfg, info->nmethods);
9598 emit_int32 (acfg, info->flags);
9599 emit_int32 (acfg, info->opts);
9600 emit_int32 (acfg, info->simd_opts);
9601 emit_int32 (acfg, info->gc_name_index);
9602 emit_int32 (acfg, info->num_rgctx_fetch_trampolines);
9603 emit_int32 (acfg, info->double_align);
9604 emit_int32 (acfg, info->long_align);
9605 emit_int32 (acfg, info->generic_tramp_num);
9606 emit_int32 (acfg, info->tramp_page_size);
9607 emit_int32 (acfg, info->nshared_got_entries);
9608 emit_int32 (acfg, info->datafile_size);
9610 for (i = 0; i < MONO_AOT_TABLE_NUM; ++i)
9611 emit_int32 (acfg, info->table_offsets [i]);
9612 for (i = 0; i < MONO_AOT_TRAMP_NUM; ++i)
9613 emit_int32 (acfg, info->num_trampolines [i]);
9614 for (i = 0; i < MONO_AOT_TRAMP_NUM; ++i)
9615 emit_int32 (acfg, info->trampoline_got_offset_base [i]);
9616 for (i = 0; i < MONO_AOT_TRAMP_NUM; ++i)
9617 emit_int32 (acfg, info->trampoline_size [i]);
9618 for (i = 0; i < MONO_AOT_TRAMP_NUM; ++i)
9619 emit_int32 (acfg, info->tramp_page_code_offsets [i]);
9621 emit_bytes (acfg, info->aotid, 16);
9623 if (acfg->aot_opts.static_link) {
9624 emit_global_inner (acfg, acfg->static_linking_symbol, FALSE);
9625 emit_alignment (acfg, sizeof (gpointer));
9626 emit_label (acfg, acfg->static_linking_symbol);
9627 emit_pointer_2 (acfg, acfg->user_symbol_prefix, "mono_aot_file_info");
9632 * Emit a structure containing all the information not stored elsewhere.
9634 static void
9635 emit_file_info (MonoAotCompile *acfg)
9637 char *build_info;
9638 MonoAotFileInfo *info;
9640 if (acfg->aot_opts.bind_to_runtime_version) {
9641 build_info = mono_get_runtime_build_info ();
9642 emit_string_symbol (acfg, "runtime_version", build_info);
9643 g_free (build_info);
9644 } else {
9645 emit_string_symbol (acfg, "runtime_version", "");
9648 emit_string_symbol (acfg, "assembly_guid" , acfg->image->guid);
9650 /* Emit a string holding the assembly name */
9651 emit_string_symbol (acfg, "assembly_name", acfg->image->assembly->aname.name);
9653 info = g_new0 (MonoAotFileInfo, 1);
9654 init_aot_file_info (acfg, info);
9656 if (acfg->aot_opts.static_link) {
9657 char symbol [MAX_SYMBOL_SIZE];
9658 char *p;
9661 * Emit a global symbol which can be passed by an embedding app to
9662 * mono_aot_register_module (). The symbol points to a pointer to the the file info
9663 * structure.
9665 sprintf (symbol, "%smono_aot_module_%s_info", acfg->user_symbol_prefix, acfg->image->assembly->aname.name);
9667 /* Get rid of characters which cannot occur in symbols */
9668 p = symbol;
9669 for (p = symbol; *p; ++p) {
9670 if (!(isalnum (*p) || *p == '_'))
9671 *p = '_';
9673 acfg->static_linking_symbol = g_strdup (symbol);
9676 if (acfg->llvm)
9677 mono_llvm_emit_aot_file_info (info, acfg->has_jitted_code);
9678 else
9679 emit_aot_file_info (acfg, info);
9682 static void
9683 emit_blob (MonoAotCompile *acfg)
9685 acfg->blob_closed = TRUE;
9687 emit_aot_data (acfg, MONO_AOT_TABLE_BLOB, "blob", (guint8*)acfg->blob.data, acfg->blob.index);
9690 static void
9691 emit_objc_selectors (MonoAotCompile *acfg)
9693 int i;
9694 char symbol [128];
9696 if (!acfg->objc_selectors || acfg->objc_selectors->len == 0)
9697 return;
9700 * From
9701 * cat > foo.m << EOF
9702 * void *ret ()
9704 * return @selector(print:);
9706 * EOF
9709 mono_img_writer_emit_unset_mode (acfg->w);
9710 g_assert (acfg->fp);
9711 fprintf (acfg->fp, ".section __DATA,__objc_selrefs,literal_pointers,no_dead_strip\n");
9712 fprintf (acfg->fp, ".align 3\n");
9713 for (i = 0; i < acfg->objc_selectors->len; ++i) {
9714 sprintf (symbol, "L_OBJC_SELECTOR_REFERENCES_%d", i);
9715 emit_label (acfg, symbol);
9716 sprintf (symbol, "L_OBJC_METH_VAR_NAME_%d", i);
9717 emit_pointer (acfg, symbol);
9720 fprintf (acfg->fp, ".section __TEXT,__cstring,cstring_literals\n");
9721 for (i = 0; i < acfg->objc_selectors->len; ++i) {
9722 fprintf (acfg->fp, "L_OBJC_METH_VAR_NAME_%d:\n", i);
9723 fprintf (acfg->fp, ".asciz \"%s\"\n", (char*)g_ptr_array_index (acfg->objc_selectors, i));
9726 fprintf (acfg->fp, ".section __DATA,__objc_imageinfo,regular,no_dead_strip\n");
9727 fprintf (acfg->fp, ".align 3\n");
9728 fprintf (acfg->fp, "L_OBJC_IMAGE_INFO:\n");
9729 fprintf (acfg->fp, ".long 0\n");
9730 fprintf (acfg->fp, ".long 16\n");
9733 static void
9734 emit_dwarf_info (MonoAotCompile *acfg)
9736 #ifdef EMIT_DWARF_INFO
9737 int i;
9738 char symbol2 [128];
9740 /* DIEs for methods */
9741 for (i = 0; i < acfg->nmethods; ++i) {
9742 MonoCompile *cfg = acfg->cfgs [i];
9744 if (!cfg)
9745 continue;
9747 // FIXME: LLVM doesn't define .Lme_...
9748 if (cfg->compile_llvm)
9749 continue;
9751 sprintf (symbol2, "%sme_%x", acfg->temp_prefix, i);
9753 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 ()));
9755 #endif
9758 static gboolean
9759 collect_methods (MonoAotCompile *acfg)
9761 int mindex, i;
9762 MonoImage *image = acfg->image;
9764 /* Collect methods */
9765 for (i = 0; i < image->tables [MONO_TABLE_METHOD].rows; ++i) {
9766 MonoError error;
9767 MonoMethod *method;
9768 guint32 token = MONO_TOKEN_METHOD_DEF | (i + 1);
9770 method = mono_get_method_checked (acfg->image, token, NULL, NULL, &error);
9772 if (!method) {
9773 aot_printerrf (acfg, "Failed to load method 0x%x from '%s' due to %s.\n", token, image->name, mono_error_get_message (&error));
9774 aot_printerrf (acfg, "Run with MONO_LOG_LEVEL=debug for more information.\n");
9775 mono_error_cleanup (&error);
9776 return FALSE;
9779 /* Load all methods eagerly to skip the slower lazy loading code */
9780 mono_class_setup_methods (method->klass);
9782 if (mono_aot_mode_is_full (&acfg->aot_opts) && method->iflags & METHOD_IMPL_ATTRIBUTE_INTERNAL_CALL) {
9783 /* Compile the wrapper instead */
9784 /* We do this here instead of add_wrappers () because it is easy to do it here */
9785 MonoMethod *wrapper = mono_marshal_get_native_wrapper (method, TRUE, TRUE);
9786 method = wrapper;
9789 /* FIXME: Some mscorlib methods don't have debug info */
9791 if (acfg->aot_opts.soft_debug && !method->wrapper_type) {
9792 if (!((method->flags & METHOD_ATTRIBUTE_PINVOKE_IMPL) ||
9793 (method->iflags & METHOD_IMPL_ATTRIBUTE_RUNTIME) ||
9794 (method->flags & METHOD_ATTRIBUTE_ABSTRACT) ||
9795 (method->iflags & METHOD_IMPL_ATTRIBUTE_INTERNAL_CALL))) {
9796 if (!mono_debug_lookup_method (method)) {
9797 fprintf (stderr, "Method %s has no debug info, probably the .mdb file for the assembly is missing.\n", mono_method_get_full_name (method));
9798 exit (1);
9804 if (method->is_generic || mono_class_is_gtd (method->klass))
9805 /* Compile the ref shared version instead */
9806 method = mini_get_shared_method (method);
9808 /* Since we add the normal methods first, their index will be equal to their zero based token index */
9809 add_method_with_index (acfg, method, i, FALSE);
9810 acfg->method_index ++;
9813 /* gsharedvt methods */
9814 for (mindex = 0; mindex < image->tables [MONO_TABLE_METHOD].rows; ++mindex) {
9815 MonoError error;
9816 MonoMethod *method;
9817 guint32 token = MONO_TOKEN_METHOD_DEF | (mindex + 1);
9819 if (!(acfg->opts & MONO_OPT_GSHAREDVT))
9820 continue;
9822 method = mono_get_method_checked (acfg->image, token, NULL, NULL, &error);
9823 report_loader_error (acfg, &error, "Failed to load method token 0x%x due to %s\n", i, mono_error_get_message (&error));
9825 if (method->is_generic || mono_class_is_gtd (method->klass)) {
9826 MonoMethod *gshared;
9828 gshared = mini_get_shared_method_full (method, TRUE, TRUE);
9829 add_extra_method (acfg, gshared);
9833 if (mono_aot_mode_is_full (&acfg->aot_opts))
9834 add_generic_instances (acfg);
9836 if (mono_aot_mode_is_full (&acfg->aot_opts))
9837 add_wrappers (acfg);
9838 return TRUE;
9841 static void
9842 compile_methods (MonoAotCompile *acfg)
9844 int i, methods_len;
9846 if (acfg->aot_opts.nthreads > 0) {
9847 GPtrArray *frag;
9848 int len, j;
9849 GPtrArray *threads;
9850 MonoThreadHandle *thread_handle;
9851 gpointer *user_data;
9852 MonoMethod **methods;
9854 methods_len = acfg->methods->len;
9856 len = acfg->methods->len / acfg->aot_opts.nthreads;
9857 g_assert (len > 0);
9859 * Partition the list of methods into fragments, and hand it to threads to
9860 * process.
9862 threads = g_ptr_array_new ();
9863 /* Make a copy since acfg->methods is modified by compile_method () */
9864 methods = g_new0 (MonoMethod*, methods_len);
9865 //memcpy (methods, g_ptr_array_index (acfg->methods, 0), sizeof (MonoMethod*) * methods_len);
9866 for (i = 0; i < methods_len; ++i)
9867 methods [i] = (MonoMethod *)g_ptr_array_index (acfg->methods, i);
9868 i = 0;
9869 while (i < methods_len) {
9870 frag = g_ptr_array_new ();
9871 for (j = 0; j < len; ++j) {
9872 if (i < methods_len) {
9873 g_ptr_array_add (frag, methods [i]);
9874 i ++;
9878 user_data = g_new0 (gpointer, 3);
9879 user_data [0] = mono_domain_get ();
9880 user_data [1] = acfg;
9881 user_data [2] = frag;
9883 thread_handle = mono_threads_create_thread (compile_thread_main, (gpointer) user_data, NULL, NULL);
9884 g_ptr_array_add (threads, thread_handle);
9886 g_free (methods);
9888 for (i = 0; i < threads->len; ++i) {
9889 mono_thread_info_wait_one_handle (g_ptr_array_index (threads, i), MONO_INFINITE_WAIT, FALSE);
9890 mono_threads_close_thread_handle (g_ptr_array_index (threads, i));
9892 } else {
9893 methods_len = 0;
9896 /* Compile methods added by compile_method () or all methods if nthreads == 0 */
9897 for (i = methods_len; i < acfg->methods->len; ++i) {
9898 /* This can add new methods to acfg->methods */
9899 compile_method (acfg, (MonoMethod *)g_ptr_array_index (acfg->methods, i));
9903 static int
9904 compile_asm (MonoAotCompile *acfg)
9906 char *command, *objfile;
9907 char *outfile_name, *tmp_outfile_name, *llvm_ofile;
9908 const char *tool_prefix = acfg->aot_opts.tool_prefix ? acfg->aot_opts.tool_prefix : "";
9909 char *ld_flags = acfg->aot_opts.ld_flags ? acfg->aot_opts.ld_flags : g_strdup("");
9911 #ifdef TARGET_WIN32_MSVC
9912 #define AS_OPTIONS "-c -x assembler"
9913 #elif defined(TARGET_AMD64) && !defined(TARGET_MACH)
9914 #define AS_OPTIONS "--64"
9915 #elif defined(TARGET_POWERPC64)
9916 #define AS_OPTIONS "-a64 -mppc64"
9917 #elif defined(sparc) && SIZEOF_VOID_P == 8
9918 #define AS_OPTIONS "-xarch=v9"
9919 #elif defined(TARGET_X86) && defined(TARGET_MACH) && !defined(__native_client_codegen__)
9920 #define AS_OPTIONS "-arch i386"
9921 #else
9922 #define AS_OPTIONS ""
9923 #endif
9925 #ifdef __native_client_codegen__
9926 #if defined(TARGET_AMD64)
9927 #define AS_NAME "nacl64-as"
9928 #else
9929 #define AS_NAME "nacl-as"
9930 #endif
9931 #elif defined(TARGET_OSX)
9932 #define AS_NAME "clang"
9933 #elif defined(TARGET_WIN32_MSVC)
9934 #define AS_NAME "clang.exe"
9935 #else
9936 #define AS_NAME "as"
9937 #endif
9939 #ifdef TARGET_WIN32_MSVC
9940 #define AS_OBJECT_FILE_SUFFIX "obj"
9941 #else
9942 #define AS_OBJECT_FILE_SUFFIX "o"
9943 #endif
9945 #if defined(sparc)
9946 #define LD_NAME "ld"
9947 #define LD_OPTIONS "-shared -G"
9948 #elif defined(__ppc__) && defined(TARGET_MACH)
9949 #define LD_NAME "gcc"
9950 #define LD_OPTIONS "-dynamiclib"
9951 #elif defined(TARGET_AMD64) && defined(TARGET_MACH)
9952 #define LD_NAME "clang"
9953 #define LD_OPTIONS "--shared"
9954 #elif defined(TARGET_WIN32_MSVC)
9955 #define LD_NAME "link.exe"
9956 #define LD_OPTIONS "/DLL /MACHINE:X64 /NOLOGO"
9957 #elif defined(TARGET_WIN32) && !defined(TARGET_ANDROID)
9958 #define LD_NAME "gcc"
9959 #define LD_OPTIONS "-shared"
9960 #elif defined(TARGET_X86) && defined(TARGET_MACH) && !defined(__native_client_codegen__)
9961 #define LD_NAME "clang"
9962 #define LD_OPTIONS "-m32 -dynamiclib"
9963 #elif defined(TARGET_ARM) && !defined(TARGET_ANDROID)
9964 #define LD_NAME "gcc"
9965 #define LD_OPTIONS "--shared"
9966 #elif defined(TARGET_POWERPC64)
9967 #define LD_OPTIONS "-m elf64ppc"
9968 #endif
9970 #ifndef LD_OPTIONS
9971 #define LD_OPTIONS ""
9972 #endif
9974 if (acfg->aot_opts.asm_only) {
9975 aot_printf (acfg, "Output file: '%s'.\n", acfg->tmpfname);
9976 if (acfg->aot_opts.static_link)
9977 aot_printf (acfg, "Linking symbol: '%s'.\n", acfg->static_linking_symbol);
9978 if (acfg->llvm)
9979 aot_printf (acfg, "LLVM output file: '%s'.\n", acfg->llvm_sfile);
9980 return 0;
9983 if (acfg->aot_opts.static_link) {
9984 if (acfg->aot_opts.outfile)
9985 objfile = g_strdup_printf ("%s", acfg->aot_opts.outfile);
9986 else
9987 objfile = g_strdup_printf ("%s." AS_OBJECT_FILE_SUFFIX, acfg->image->name);
9988 } else {
9989 objfile = g_strdup_printf ("%s." AS_OBJECT_FILE_SUFFIX, acfg->tmpfname);
9992 #ifdef TARGET_OSX
9993 g_string_append (acfg->as_args, "-c -x assembler");
9994 #endif
9996 command = g_strdup_printf ("\"%s%s\" %s %s -o %s %s", tool_prefix, AS_NAME, AS_OPTIONS,
9997 acfg->as_args ? acfg->as_args->str : "",
9998 wrap_path (objfile), wrap_path (acfg->tmpfname));
9999 aot_printf (acfg, "Executing the native assembler: %s\n", command);
10000 if (execute_system (command) != 0) {
10001 g_free (command);
10002 g_free (objfile);
10003 return 1;
10006 if (acfg->llvm && !acfg->llvm_owriter) {
10007 command = g_strdup_printf ("\"%s%s\" %s %s -o %s %s", tool_prefix, AS_NAME, AS_OPTIONS,
10008 acfg->as_args ? acfg->as_args->str : "",
10009 wrap_path (acfg->llvm_ofile), wrap_path (acfg->llvm_sfile));
10010 aot_printf (acfg, "Executing the native assembler: %s\n", command);
10011 if (execute_system (command) != 0) {
10012 g_free (command);
10013 g_free (objfile);
10014 return 1;
10018 g_free (command);
10020 if (acfg->aot_opts.static_link) {
10021 aot_printf (acfg, "Output file: '%s'.\n", objfile);
10022 aot_printf (acfg, "Linking symbol: '%s'.\n", acfg->static_linking_symbol);
10023 g_free (objfile);
10024 return 0;
10027 if (acfg->aot_opts.outfile)
10028 outfile_name = g_strdup_printf ("%s", acfg->aot_opts.outfile);
10029 else
10030 outfile_name = g_strdup_printf ("%s%s", acfg->image->name, MONO_SOLIB_EXT);
10032 tmp_outfile_name = g_strdup_printf ("%s.tmp", outfile_name);
10034 if (acfg->llvm) {
10035 llvm_ofile = g_strdup_printf ("\"%s\"", acfg->llvm_ofile);
10036 } else {
10037 llvm_ofile = g_strdup ("");
10040 /* replace the ; flags separators with spaces */
10041 g_strdelimit (ld_flags, ";", ' ');
10043 if (acfg->aot_opts.llvm_only)
10044 ld_flags = g_strdup_printf ("%s %s", ld_flags, "-lstdc++");
10046 #ifdef TARGET_WIN32_MSVC
10047 g_assert (tmp_outfile_name != NULL);
10048 g_assert (objfile != NULL);
10049 command = g_strdup_printf ("\"%s%s\" %s %s /OUT:\"%s\" \"%s\"", tool_prefix, LD_NAME, LD_OPTIONS,
10050 ld_flags, tmp_outfile_name, objfile);
10051 #elif defined(LD_NAME)
10052 command = g_strdup_printf ("%s%s %s -o %s %s %s %s", tool_prefix, LD_NAME, LD_OPTIONS,
10053 wrap_path (tmp_outfile_name), wrap_path (llvm_ofile),
10054 wrap_path (g_strdup_printf ("%s." AS_OBJECT_FILE_SUFFIX, acfg->tmpfname)), ld_flags);
10055 #else
10056 // Default (linux)
10057 if (acfg->aot_opts.tool_prefix) {
10058 /* Cross compiling */
10059 command = g_strdup_printf ("\"%sld\" %s -shared -o %s %s %s %s", tool_prefix, LD_OPTIONS,
10060 wrap_path (tmp_outfile_name), wrap_path (llvm_ofile),
10061 wrap_path (g_strdup_printf ("%s." AS_OBJECT_FILE_SUFFIX, acfg->tmpfname)), ld_flags);
10062 } else {
10063 char *args = g_strdup_printf ("%s -shared -o %s %s %s %s", LD_OPTIONS,
10064 wrap_path (tmp_outfile_name), wrap_path (llvm_ofile),
10065 wrap_path (g_strdup_printf ("%s." AS_OBJECT_FILE_SUFFIX, acfg->tmpfname)), ld_flags);
10067 if (acfg->aot_opts.llvm_only) {
10068 command = g_strdup_printf ("clang++ %s", args);
10069 } else {
10070 command = g_strdup_printf ("\"%sld\" %s", tool_prefix, args);
10072 g_free (args);
10074 #endif
10075 aot_printf (acfg, "Executing the native linker: %s\n", command);
10076 if (execute_system (command) != 0) {
10077 g_free (tmp_outfile_name);
10078 g_free (outfile_name);
10079 g_free (command);
10080 g_free (objfile);
10081 g_free (ld_flags);
10082 return 1;
10085 g_free (command);
10087 /*com = g_strdup_printf ("strip --strip-unneeded %s%s", acfg->image->name, MONO_SOLIB_EXT);
10088 printf ("Stripping the binary: %s\n", com);
10089 execute_system (com);
10090 g_free (com);*/
10092 #if defined(TARGET_ARM) && !defined(TARGET_MACH)
10094 * gas generates 'mapping symbols' each time code and data is mixed, which
10095 * happens a lot in emit_and_reloc_code (), so we need to get rid of them.
10097 command = g_strdup_printf ("\"%sstrip\" --strip-symbol=\\$a --strip-symbol=\\$d %s", wrap_path(tool_prefix), wrap_path(tmp_outfile_name));
10098 aot_printf (acfg, "Stripping the binary: %s\n", command);
10099 if (execute_system (command) != 0) {
10100 g_free (tmp_outfile_name);
10101 g_free (outfile_name);
10102 g_free (command);
10103 g_free (objfile);
10104 return 1;
10106 #endif
10108 if (0 != rename (tmp_outfile_name, outfile_name)) {
10109 if (G_FILE_ERROR_EXIST == g_file_error_from_errno (errno)) {
10110 /* Since we are rebuilding the module we need to be able to replace any old copies. Remove old file and retry rename operation. */
10111 unlink (outfile_name);
10112 rename (tmp_outfile_name, outfile_name);
10116 #if defined(TARGET_MACH)
10117 command = g_strdup_printf ("dsymutil \"%s\"", outfile_name);
10118 aot_printf (acfg, "Executing dsymutil: %s\n", command);
10119 if (execute_system (command) != 0) {
10120 return 1;
10122 #endif
10124 if (!acfg->aot_opts.save_temps)
10125 unlink (objfile);
10127 g_free (tmp_outfile_name);
10128 g_free (outfile_name);
10129 g_free (objfile);
10131 if (acfg->aot_opts.save_temps)
10132 aot_printf (acfg, "Retained input file.\n");
10133 else
10134 unlink (acfg->tmpfname);
10136 return 0;
10139 static guint8
10140 profread_byte (FILE *infile)
10142 guint8 i;
10143 int res;
10145 res = fread (&i, 1, 1, infile);
10146 g_assert (res == 1);
10147 return i;
10150 static int
10151 profread_int (FILE *infile)
10153 int i, res;
10155 res = fread (&i, 4, 1, infile);
10156 g_assert (res == 1);
10157 return i;
10160 static char*
10161 profread_string (FILE *infile)
10163 int len, res;
10164 char buf [1024];
10165 char *pbuf;
10167 len = profread_int (infile);
10168 if (len + 1 > 1024)
10169 pbuf = g_malloc (len + 1);
10170 else
10171 pbuf = buf;
10172 res = fread (pbuf, 1, len, infile);
10173 g_assert (res == len);
10174 pbuf [len] = '\0';
10175 if (pbuf == buf)
10176 return g_strdup (buf);
10177 else
10178 return pbuf;
10181 static void
10182 load_profile_file (MonoAotCompile *acfg, char *filename)
10184 FILE *infile;
10185 char buf [1024];
10186 int res, len, version;
10187 char magic [32];
10189 infile = fopen (filename, "r");
10190 if (!infile) {
10191 fprintf (stderr, "Unable to open file '%s': %s.\n", filename, strerror (errno));
10192 exit (1);
10195 printf ("Using profile data file '%s'\n", filename);
10197 sprintf (magic, AOT_PROFILER_MAGIC);
10198 len = strlen (magic);
10199 res = fread (buf, 1, len, infile);
10200 magic [len] = '\0';
10201 buf [len] = '\0';
10202 if ((res != len) || strcmp (buf, magic) != 0) {
10203 printf ("Profile file has wrong header: '%s'.\n", buf);
10204 fclose (infile);
10205 exit (1);
10207 guint32 expected_version = (AOT_PROFILER_MAJOR_VERSION << 16) | AOT_PROFILER_MINOR_VERSION;
10208 version = profread_int (infile);
10209 if (version != expected_version) {
10210 printf ("Profile file has wrong version 0x%4x, expected 0x%4x.\n", version, expected_version);
10211 fclose (infile);
10212 exit (1);
10215 ProfileData *data = g_new0 (ProfileData, 1);
10216 data->images = g_hash_table_new (NULL, NULL);
10217 data->classes = g_hash_table_new (NULL, NULL);
10218 data->ginsts = g_hash_table_new (NULL, NULL);
10219 data->methods = g_hash_table_new (NULL, NULL);
10221 while (TRUE) {
10222 int type = profread_byte (infile);
10223 int id = profread_int (infile);
10225 if (type == AOTPROF_RECORD_NONE)
10226 break;
10228 switch (type) {
10229 case AOTPROF_RECORD_IMAGE: {
10230 ImageProfileData *idata = g_new0 (ImageProfileData, 1);
10231 idata->name = profread_string (infile);
10232 char *mvid = profread_string (infile);
10233 g_free (mvid);
10234 g_hash_table_insert (data->images, GINT_TO_POINTER (id), idata);
10235 break;
10237 case AOTPROF_RECORD_GINST: {
10238 int i;
10239 int len = profread_int (infile);
10241 GInstProfileData *gdata = g_new0 (GInstProfileData, 1);
10242 gdata->argc = len;
10243 gdata->argv = g_new0 (ClassProfileData*, len);
10245 for (i = 0; i < len; ++i) {
10246 int class_id = profread_int (infile);
10248 gdata->argv [i] = g_hash_table_lookup (data->classes, GINT_TO_POINTER (class_id));
10249 g_assert (gdata->argv [i]);
10251 g_hash_table_insert (data->ginsts, GINT_TO_POINTER (id), gdata);
10252 break;
10254 case AOTPROF_RECORD_TYPE: {
10255 int type = profread_byte (infile);
10257 switch (type) {
10258 case MONO_TYPE_CLASS: {
10259 int image_id = profread_int (infile);
10260 int ginst_id = profread_int (infile);
10261 char *class_name = profread_string (infile);
10263 ImageProfileData *image = g_hash_table_lookup (data->images, GINT_TO_POINTER (image_id));
10264 g_assert (image);
10266 char *p = strrchr (class_name, '.');
10267 g_assert (p);
10268 *p = '\0';
10270 ClassProfileData *cdata = g_new0 (ClassProfileData, 1);
10271 cdata->image = image;
10272 cdata->ns = g_strdup (class_name);
10273 cdata->name = g_strdup (p + 1);
10275 if (ginst_id != -1) {
10276 cdata->inst = g_hash_table_lookup (data->ginsts, GINT_TO_POINTER (ginst_id));
10277 g_assert (cdata->inst);
10279 g_free (class_name);
10281 g_hash_table_insert (data->classes, GINT_TO_POINTER (id), cdata);
10282 break;
10284 #if 0
10285 case MONO_TYPE_SZARRAY: {
10286 int elem_id = profread_int (infile);
10287 // FIXME:
10288 break;
10290 #endif
10291 default:
10292 g_assert_not_reached ();
10293 break;
10295 break;
10297 case AOTPROF_RECORD_METHOD: {
10298 int class_id = profread_int (infile);
10299 int ginst_id = profread_int (infile);
10300 int param_count = profread_int (infile);
10301 char *method_name = profread_string (infile);
10302 char *sig = profread_string (infile);
10304 ClassProfileData *klass = g_hash_table_lookup (data->classes, GINT_TO_POINTER (class_id));
10305 g_assert (klass);
10307 MethodProfileData *mdata = g_new0 (MethodProfileData, 1);
10308 mdata->id = id;
10309 mdata->klass = klass;
10310 mdata->name = method_name;
10311 mdata->signature = sig;
10312 mdata->param_count = param_count;
10314 if (ginst_id != -1) {
10315 mdata->inst = g_hash_table_lookup (data->ginsts, GINT_TO_POINTER (ginst_id));
10316 g_assert (mdata->inst);
10318 g_hash_table_insert (data->methods, GINT_TO_POINTER (id), mdata);
10319 break;
10321 default:
10322 printf ("%d\n", type);
10323 g_assert_not_reached ();
10324 break;
10328 fclose (infile);
10329 acfg->profile_data = g_list_append (acfg->profile_data, data);
10332 static void
10333 resolve_class (ClassProfileData *cdata);
10335 static void
10336 resolve_ginst (GInstProfileData *inst_data)
10338 int i;
10340 if (inst_data->inst)
10341 return;
10343 for (i = 0; i < inst_data->argc; ++i) {
10344 resolve_class (inst_data->argv [i]);
10345 if (!inst_data->argv [i]->klass)
10346 return;
10348 MonoType **args = g_new0 (MonoType*, inst_data->argc);
10349 for (i = 0; i < inst_data->argc; ++i)
10350 args [i] = &inst_data->argv [i]->klass->byval_arg;
10352 inst_data->inst = mono_metadata_get_generic_inst (inst_data->argc, args);
10355 static void
10356 resolve_class (ClassProfileData *cdata)
10358 MonoError error;
10359 MonoClass *klass;
10361 if (!cdata->image->image)
10362 return;
10364 klass = mono_class_from_name_checked (cdata->image->image, cdata->ns, cdata->name, &error);
10365 if (!klass) {
10366 //printf ("[%s] %s.%s\n", cdata->image->name, cdata->ns, cdata->name);
10367 return;
10369 if (cdata->inst) {
10370 resolve_ginst (cdata->inst);
10371 if (!cdata->inst->inst)
10372 return;
10373 MonoGenericContext ctx;
10375 memset (&ctx, 0, sizeof (ctx));
10376 ctx.class_inst = cdata->inst->inst;
10377 cdata->klass = mono_class_inflate_generic_class_checked (klass, &ctx, &error);
10378 } else {
10379 cdata->klass = klass;
10384 * Resolve the profile data to the corresponding loaded classes/methods etc. if possible.
10386 static void
10387 resolve_profile_data (MonoAotCompile *acfg, ProfileData *data)
10389 GHashTableIter iter;
10390 gpointer key, value;
10391 int i;
10393 if (!data)
10394 return;
10396 /* Images */
10397 GPtrArray *assemblies = mono_domain_get_assemblies (mono_get_root_domain (), FALSE);
10398 g_hash_table_iter_init (&iter, data->images);
10399 while (g_hash_table_iter_next (&iter, &key, &value)) {
10400 ImageProfileData *idata = (ImageProfileData*)value;
10402 for (i = 0; i < assemblies->len; ++i) {
10403 MonoAssembly *ass = g_ptr_array_index (assemblies, i);
10405 if (!strcmp (ass->aname.name, idata->name)) {
10406 idata->image = ass->image;
10407 break;
10411 g_ptr_array_free (assemblies, TRUE);
10413 /* Classes */
10414 g_hash_table_iter_init (&iter, data->classes);
10415 while (g_hash_table_iter_next (&iter, &key, &value)) {
10416 ClassProfileData *cdata = (ClassProfileData*)value;
10418 if (!cdata->image->image) {
10419 if (acfg->aot_opts.verbose)
10420 printf ("Unable to load class '%s.%s' because its image '%s' is not loaded.\n", cdata->ns, cdata->name, cdata->image->name);
10421 continue;
10424 resolve_class (cdata);
10426 if (cdata->klass)
10427 printf ("%s %s %s\n", cdata->ns, cdata->name, mono_class_full_name (cdata->klass));
10431 /* Methods */
10432 g_hash_table_iter_init (&iter, data->methods);
10433 while (g_hash_table_iter_next (&iter, &key, &value)) {
10434 MethodProfileData *mdata = (MethodProfileData*)value;
10435 MonoClass *klass;
10436 MonoMethod *m;
10437 gpointer miter;
10439 resolve_class (mdata->klass);
10440 klass = mdata->klass->klass;
10441 if (!klass) {
10442 if (acfg->aot_opts.verbose)
10443 printf ("Unable to load method '%s' because its class '%s.%s' is not loaded.\n", mdata->name, mdata->klass->ns, mdata->klass->name);
10444 continue;
10446 miter = NULL;
10447 while ((m = mono_class_get_methods (klass, &miter))) {
10448 MonoError error;
10450 if (strcmp (m->name, mdata->name))
10451 continue;
10452 MonoMethodSignature *sig = mono_method_signature (m);
10453 if (!sig)
10454 continue;
10455 if (sig->param_count != mdata->param_count)
10456 continue;
10457 if (mdata->inst) {
10458 resolve_ginst (mdata->inst);
10459 if (!mdata->inst->inst)
10460 continue;
10461 MonoGenericContext ctx;
10463 memset (&ctx, 0, sizeof (ctx));
10464 ctx.method_inst = mdata->inst->inst;
10466 m = mono_class_inflate_generic_method_checked (m, &ctx, &error);
10467 if (!m)
10468 continue;
10469 sig = mono_method_signature_checked (m, &error);
10470 if (!is_ok (&error)) {
10471 mono_error_cleanup (&error);
10472 continue;
10475 char *sig_str = mono_signature_full_name (sig);
10476 gboolean match = !strcmp (sig_str, mdata->signature);
10477 g_free (sig_str);
10478 if (!match)
10480 continue;
10481 //printf ("%s\n", mono_method_full_name (m, 1));
10482 mdata->method = m;
10483 break;
10485 if (!mdata->method) {
10486 if (acfg->aot_opts.verbose)
10487 printf ("Unable to load method '%s' from class '%s', not found.\n", mdata->name, mono_class_full_name (klass));
10492 static gboolean
10493 inst_references_image (MonoGenericInst *inst, MonoImage *image)
10495 int i;
10497 for (i = 0; i < inst->type_argc; ++i) {
10498 MonoClass *k = mono_class_from_mono_type (inst->type_argv [i]);
10499 if (k->image == image)
10500 return TRUE;
10501 if (mono_class_is_ginst (k)) {
10502 MonoGenericInst *kinst = mono_class_get_context (k)->class_inst;
10503 if (inst_references_image (kinst, image))
10504 return TRUE;
10507 return FALSE;
10510 static gboolean
10511 is_local_inst (MonoGenericInst *inst, MonoImage *image)
10513 int i;
10515 for (i = 0; i < inst->type_argc; ++i) {
10516 MonoClass *k = mono_class_from_mono_type (inst->type_argv [i]);
10517 if (!MONO_TYPE_IS_PRIMITIVE (inst->type_argv [i]) && k->image != image)
10518 return FALSE;
10520 return TRUE;
10523 static void
10524 add_profile_instances (MonoAotCompile *acfg, ProfileData *data)
10526 GHashTableIter iter;
10527 gpointer key, value;
10528 int count = 0;
10530 if (!data)
10531 return;
10533 if (acfg->aot_opts.profile_only) {
10534 /* Add methods referenced by the profile */
10535 g_hash_table_iter_init (&iter, data->methods);
10536 while (g_hash_table_iter_next (&iter, &key, &value)) {
10537 MethodProfileData *mdata = (MethodProfileData*)value;
10538 MonoMethod *m = mdata->method;
10540 if (!m)
10541 continue;
10542 if (m->is_inflated)
10543 continue;
10544 add_extra_method (acfg, m);
10545 g_hash_table_insert (acfg->profile_methods, m, m);
10546 count ++;
10551 * Add method instances 'related' to this assembly to the AOT image.
10553 g_hash_table_iter_init (&iter, data->methods);
10554 while (g_hash_table_iter_next (&iter, &key, &value)) {
10555 MethodProfileData *mdata = (MethodProfileData*)value;
10556 MonoMethod *m = mdata->method;
10557 MonoGenericContext *ctx;
10559 if (!m)
10560 continue;
10561 if (!m->is_inflated)
10562 continue;
10564 ctx = mono_method_get_context (m);
10565 /* For simplicity, add instances which reference the assembly we are compiling */
10566 if (((ctx->class_inst && inst_references_image (ctx->class_inst, acfg->image)) ||
10567 (ctx->method_inst && inst_references_image (ctx->method_inst, acfg->image))) &&
10568 !mono_method_is_generic_sharable_full (m, FALSE, FALSE, FALSE)) {
10569 //printf ("%s\n", mono_method_full_name (m, TRUE));
10570 add_extra_method (acfg, m);
10571 count ++;
10572 } else if (m->klass->image == acfg->image &&
10573 ((ctx->class_inst && is_local_inst (ctx->class_inst, acfg->image)) ||
10574 (ctx->method_inst && is_local_inst (ctx->method_inst, acfg->image))) &&
10575 !mono_method_is_generic_sharable_full (m, FALSE, FALSE, FALSE)) {
10576 /* Add instances where the gtd is in the assembly and its inflated with types from this assembly or corlib */
10577 //printf ("%s\n", mono_method_full_name (m, TRUE));
10578 add_extra_method (acfg, m);
10579 count ++;
10582 * FIXME: We might skip some instances, for example:
10583 * Foo<Bar> won't be compiled when compiling Foo's assembly since it doesn't match the first case,
10584 * and it won't be compiled when compiling Bar's assembly if Foo's assembly is not loaded.
10588 printf ("Added %d methods from profile.\n", count);
10591 static void
10592 init_got_info (GotInfo *info)
10594 int i;
10596 info->patch_to_got_offset = g_hash_table_new (mono_patch_info_hash, mono_patch_info_equal);
10597 info->patch_to_got_offset_by_type = g_new0 (GHashTable*, MONO_PATCH_INFO_NUM);
10598 for (i = 0; i < MONO_PATCH_INFO_NUM; ++i)
10599 info->patch_to_got_offset_by_type [i] = g_hash_table_new (mono_patch_info_hash, mono_patch_info_equal);
10600 info->got_patches = g_ptr_array_new ();
10603 static MonoAotCompile*
10604 acfg_create (MonoAssembly *ass, guint32 opts)
10606 MonoImage *image = ass->image;
10607 MonoAotCompile *acfg;
10609 acfg = g_new0 (MonoAotCompile, 1);
10610 acfg->methods = g_ptr_array_new ();
10611 acfg->method_indexes = g_hash_table_new (NULL, NULL);
10612 acfg->method_depth = g_hash_table_new (NULL, NULL);
10613 acfg->plt_offset_to_entry = g_hash_table_new (NULL, NULL);
10614 acfg->patch_to_plt_entry = g_new0 (GHashTable*, MONO_PATCH_INFO_NUM);
10615 acfg->method_to_cfg = g_hash_table_new (NULL, NULL);
10616 acfg->token_info_hash = g_hash_table_new_full (NULL, NULL, NULL, NULL);
10617 acfg->method_to_pinvoke_import = g_hash_table_new_full (NULL, NULL, NULL, g_free);
10618 acfg->image_hash = g_hash_table_new (NULL, NULL);
10619 acfg->image_table = g_ptr_array_new ();
10620 acfg->globals = g_ptr_array_new ();
10621 acfg->image = image;
10622 acfg->opts = opts;
10623 /* TODO: Write out set of SIMD instructions used, rather than just those available */
10624 acfg->simd_opts = mono_arch_cpu_enumerate_simd_versions ();
10625 acfg->mempool = mono_mempool_new ();
10626 acfg->extra_methods = g_ptr_array_new ();
10627 acfg->unwind_info_offsets = g_hash_table_new (NULL, NULL);
10628 acfg->unwind_ops = g_ptr_array_new ();
10629 acfg->method_label_hash = g_hash_table_new_full (g_str_hash, g_str_equal, g_free, NULL);
10630 acfg->method_order = g_ptr_array_new ();
10631 acfg->export_names = g_hash_table_new (NULL, NULL);
10632 acfg->klass_blob_hash = g_hash_table_new (NULL, NULL);
10633 acfg->method_blob_hash = g_hash_table_new (NULL, NULL);
10634 acfg->plt_entry_debug_sym_cache = g_hash_table_new (g_str_hash, g_str_equal);
10635 acfg->gsharedvt_in_signatures = g_hash_table_new ((GHashFunc)mono_signature_hash, (GEqualFunc)mono_metadata_signature_equal);
10636 acfg->gsharedvt_out_signatures = g_hash_table_new ((GHashFunc)mono_signature_hash, (GEqualFunc)mono_metadata_signature_equal);
10637 acfg->profile_methods = g_hash_table_new (NULL, NULL);
10638 mono_os_mutex_init_recursive (&acfg->mutex);
10640 init_got_info (&acfg->got_info);
10641 init_got_info (&acfg->llvm_got_info);
10643 return acfg;
10646 static void
10647 got_info_free (GotInfo *info)
10649 int i;
10651 for (i = 0; i < MONO_PATCH_INFO_NUM; ++i)
10652 g_hash_table_destroy (info->patch_to_got_offset_by_type [i]);
10653 g_free (info->patch_to_got_offset_by_type);
10654 g_hash_table_destroy (info->patch_to_got_offset);
10655 g_ptr_array_free (info->got_patches, TRUE);
10658 static void
10659 acfg_free (MonoAotCompile *acfg)
10661 int i;
10663 mono_img_writer_destroy (acfg->w);
10664 for (i = 0; i < acfg->nmethods; ++i)
10665 if (acfg->cfgs [i])
10666 mono_destroy_compile (acfg->cfgs [i]);
10668 g_free (acfg->cfgs);
10670 g_free (acfg->static_linking_symbol);
10671 g_free (acfg->got_symbol);
10672 g_free (acfg->plt_symbol);
10673 g_ptr_array_free (acfg->methods, TRUE);
10674 g_ptr_array_free (acfg->image_table, TRUE);
10675 g_ptr_array_free (acfg->globals, TRUE);
10676 g_ptr_array_free (acfg->unwind_ops, TRUE);
10677 g_hash_table_destroy (acfg->method_indexes);
10678 g_hash_table_destroy (acfg->method_depth);
10679 g_hash_table_destroy (acfg->plt_offset_to_entry);
10680 for (i = 0; i < MONO_PATCH_INFO_NUM; ++i) {
10681 if (acfg->patch_to_plt_entry [i])
10682 g_hash_table_destroy (acfg->patch_to_plt_entry [i]);
10684 g_free (acfg->patch_to_plt_entry);
10685 g_hash_table_destroy (acfg->method_to_cfg);
10686 g_hash_table_destroy (acfg->token_info_hash);
10687 g_hash_table_destroy (acfg->method_to_pinvoke_import);
10688 g_hash_table_destroy (acfg->image_hash);
10689 g_hash_table_destroy (acfg->unwind_info_offsets);
10690 g_hash_table_destroy (acfg->method_label_hash);
10691 if (acfg->typespec_classes)
10692 g_hash_table_destroy (acfg->typespec_classes);
10693 g_hash_table_destroy (acfg->export_names);
10694 g_hash_table_destroy (acfg->plt_entry_debug_sym_cache);
10695 g_hash_table_destroy (acfg->klass_blob_hash);
10696 g_hash_table_destroy (acfg->method_blob_hash);
10697 got_info_free (&acfg->got_info);
10698 got_info_free (&acfg->llvm_got_info);
10699 mono_mempool_destroy (acfg->mempool);
10700 g_free (acfg);
10703 #define WRAPPER(e,n) n,
10704 static const char* const
10705 wrapper_type_names [MONO_WRAPPER_NUM + 1] = {
10706 #include "mono/metadata/wrapper-types.h"
10707 NULL
10710 static G_GNUC_UNUSED const char*
10711 get_wrapper_type_name (int type)
10713 return wrapper_type_names [type];
10716 //#define DUMP_PLT
10717 //#define DUMP_GOT
10719 static void aot_dump (MonoAotCompile *acfg)
10721 FILE *dumpfile;
10722 char * dumpname;
10724 JsonWriter writer;
10725 mono_json_writer_init (&writer);
10727 mono_json_writer_object_begin(&writer);
10729 // Methods
10730 mono_json_writer_indent (&writer);
10731 mono_json_writer_object_key(&writer, "methods");
10732 mono_json_writer_array_begin (&writer);
10734 int i;
10735 for (i = 0; i < acfg->nmethods; ++i) {
10736 MonoCompile *cfg;
10737 MonoMethod *method;
10738 MonoClass *klass;
10740 cfg = acfg->cfgs [i];
10741 if (!cfg)
10742 continue;
10744 method = cfg->orig_method;
10746 mono_json_writer_indent (&writer);
10747 mono_json_writer_object_begin(&writer);
10749 mono_json_writer_indent (&writer);
10750 mono_json_writer_object_key(&writer, "name");
10751 mono_json_writer_printf (&writer, "\"%s\",\n", method->name);
10753 mono_json_writer_indent (&writer);
10754 mono_json_writer_object_key(&writer, "signature");
10755 mono_json_writer_printf (&writer, "\"%s\",\n", mono_method_get_full_name (method));
10757 mono_json_writer_indent (&writer);
10758 mono_json_writer_object_key(&writer, "code_size");
10759 mono_json_writer_printf (&writer, "\"%d\",\n", cfg->code_size);
10761 klass = method->klass;
10763 mono_json_writer_indent (&writer);
10764 mono_json_writer_object_key(&writer, "class");
10765 mono_json_writer_printf (&writer, "\"%s\",\n", klass->name);
10767 mono_json_writer_indent (&writer);
10768 mono_json_writer_object_key(&writer, "namespace");
10769 mono_json_writer_printf (&writer, "\"%s\",\n", klass->name_space);
10771 mono_json_writer_indent (&writer);
10772 mono_json_writer_object_key(&writer, "wrapper_type");
10773 mono_json_writer_printf (&writer, "\"%s\",\n", get_wrapper_type_name(method->wrapper_type));
10775 mono_json_writer_indent_pop (&writer);
10776 mono_json_writer_indent (&writer);
10777 mono_json_writer_object_end (&writer);
10778 mono_json_writer_printf (&writer, ",\n");
10781 mono_json_writer_indent_pop (&writer);
10782 mono_json_writer_indent (&writer);
10783 mono_json_writer_array_end (&writer);
10784 mono_json_writer_printf (&writer, ",\n");
10786 // PLT entries
10787 #ifdef DUMP_PLT
10788 mono_json_writer_indent_push (&writer);
10789 mono_json_writer_indent (&writer);
10790 mono_json_writer_object_key(&writer, "plt");
10791 mono_json_writer_array_begin (&writer);
10793 for (i = 0; i < acfg->plt_offset; ++i) {
10794 MonoPltEntry *plt_entry = NULL;
10795 MonoJumpInfo *ji;
10797 if (i == 0)
10799 * The first plt entry is unused.
10801 continue;
10803 plt_entry = g_hash_table_lookup (acfg->plt_offset_to_entry, GUINT_TO_POINTER (i));
10804 ji = plt_entry->ji;
10806 mono_json_writer_indent (&writer);
10807 mono_json_writer_printf (&writer, "{ ");
10808 mono_json_writer_object_key(&writer, "symbol");
10809 mono_json_writer_printf (&writer, "\"%s\" },\n", plt_entry->symbol);
10812 mono_json_writer_indent_pop (&writer);
10813 mono_json_writer_indent (&writer);
10814 mono_json_writer_array_end (&writer);
10815 mono_json_writer_printf (&writer, ",\n");
10816 #endif
10818 // GOT entries
10819 #ifdef DUMP_GOT
10820 mono_json_writer_indent_push (&writer);
10821 mono_json_writer_indent (&writer);
10822 mono_json_writer_object_key(&writer, "got");
10823 mono_json_writer_array_begin (&writer);
10825 mono_json_writer_indent_push (&writer);
10826 for (i = 0; i < acfg->got_info.got_patches->len; ++i) {
10827 MonoJumpInfo *ji = g_ptr_array_index (acfg->got_info.got_patches, i);
10829 mono_json_writer_indent (&writer);
10830 mono_json_writer_printf (&writer, "{ ");
10831 mono_json_writer_object_key(&writer, "patch_name");
10832 mono_json_writer_printf (&writer, "\"%s\" },\n", get_patch_name (ji->type));
10835 mono_json_writer_indent_pop (&writer);
10836 mono_json_writer_indent (&writer);
10837 mono_json_writer_array_end (&writer);
10838 mono_json_writer_printf (&writer, ",\n");
10839 #endif
10841 mono_json_writer_indent_pop (&writer);
10842 mono_json_writer_indent (&writer);
10843 mono_json_writer_object_end (&writer);
10845 dumpname = g_strdup_printf ("%s.json", g_path_get_basename (acfg->image->name));
10846 dumpfile = fopen (dumpname, "w+");
10847 g_free (dumpname);
10849 fprintf (dumpfile, "%s", writer.text->str);
10850 fclose (dumpfile);
10852 mono_json_writer_destroy (&writer);
10855 static const char *preinited_jit_icalls[] = {
10856 "mono_aot_init_llvm_method",
10857 "mono_aot_init_gshared_method_this",
10858 "mono_aot_init_gshared_method_mrgctx",
10859 "mono_aot_init_gshared_method_vtable",
10860 "mono_llvm_throw_corlib_exception",
10861 "mono_init_vtable_slot",
10862 "mono_helper_ldstr_mscorlib"
10865 static void
10866 add_preinit_got_slots (MonoAotCompile *acfg)
10868 MonoJumpInfo *ji;
10869 int i;
10872 * Allocate the first few GOT entries to information which is needed frequently, or it is needed
10873 * during method initialization etc.
10876 ji = (MonoJumpInfo *)mono_mempool_alloc0 (acfg->mempool, sizeof (MonoJumpInfo));
10877 ji->type = MONO_PATCH_INFO_IMAGE;
10878 ji->data.image = acfg->image;
10879 get_got_offset (acfg, FALSE, ji);
10880 get_got_offset (acfg, TRUE, ji);
10882 ji = (MonoJumpInfo *)mono_mempool_alloc0 (acfg->mempool, sizeof (MonoJumpInfo));
10883 ji->type = MONO_PATCH_INFO_MSCORLIB_GOT_ADDR;
10884 get_got_offset (acfg, FALSE, ji);
10885 get_got_offset (acfg, TRUE, ji);
10887 ji = (MonoJumpInfo *)mono_mempool_alloc0 (acfg->mempool, sizeof (MonoJumpInfo));
10888 ji->type = MONO_PATCH_INFO_GC_CARD_TABLE_ADDR;
10889 get_got_offset (acfg, FALSE, ji);
10890 get_got_offset (acfg, TRUE, ji);
10892 ji = (MonoJumpInfo *)mono_mempool_alloc0 (acfg->mempool, sizeof (MonoJumpInfo));
10893 ji->type = MONO_PATCH_INFO_GC_NURSERY_START;
10894 get_got_offset (acfg, FALSE, ji);
10895 get_got_offset (acfg, TRUE, ji);
10897 ji = (MonoJumpInfo *)mono_mempool_alloc0 (acfg->mempool, sizeof (MonoJumpInfo));
10898 ji->type = MONO_PATCH_INFO_AOT_MODULE;
10899 get_got_offset (acfg, FALSE, ji);
10900 get_got_offset (acfg, TRUE, ji);
10902 ji = (MonoJumpInfo *)mono_mempool_alloc0 (acfg->mempool, sizeof (MonoJumpInfo));
10903 ji->type = MONO_PATCH_INFO_GC_NURSERY_BITS;
10904 get_got_offset (acfg, FALSE, ji);
10905 get_got_offset (acfg, TRUE, ji);
10907 for (i = 0; i < TLS_KEY_NUM; i++) {
10908 ji = (MonoJumpInfo *)mono_mempool_alloc0 (acfg->mempool, sizeof (MonoJumpInfo));
10909 ji->type = MONO_PATCH_INFO_GET_TLS_TRAMP;
10910 ji->data.index = i;
10911 get_got_offset (acfg, FALSE, ji);
10912 get_got_offset (acfg, TRUE, ji);
10914 ji = (MonoJumpInfo *)mono_mempool_alloc0 (acfg->mempool, sizeof (MonoJumpInfo));
10915 ji->type = MONO_PATCH_INFO_SET_TLS_TRAMP;
10916 ji->data.index = i;
10917 get_got_offset (acfg, FALSE, ji);
10918 get_got_offset (acfg, TRUE, ji);
10921 ji = (MonoJumpInfo *)mono_mempool_alloc0 (acfg->mempool, sizeof (MonoJumpInfo));
10922 ji->type = MONO_PATCH_INFO_JIT_THREAD_ATTACH;
10923 get_got_offset (acfg, FALSE, ji);
10924 get_got_offset (acfg, TRUE, ji);
10926 for (i = 0; i < sizeof (preinited_jit_icalls) / sizeof (char*); ++i) {
10927 ji = (MonoJumpInfo *)mono_mempool_alloc0 (acfg->mempool, sizeof (MonoAotCompile));
10928 ji->type = MONO_PATCH_INFO_INTERNAL_METHOD;
10929 ji->data.name = preinited_jit_icalls [i];
10930 get_got_offset (acfg, FALSE, ji);
10931 get_got_offset (acfg, TRUE, ji);
10934 acfg->nshared_got_entries = acfg->got_offset;
10938 mono_compile_assembly (MonoAssembly *ass, guint32 opts, const char *aot_options)
10940 MonoImage *image = ass->image;
10941 int i, res;
10942 gint64 all_sizes;
10943 MonoAotCompile *acfg;
10944 char *outfile_name, *tmp_outfile_name, *p;
10945 char llvm_stats_msg [256];
10946 TV_DECLARE (atv);
10947 TV_DECLARE (btv);
10949 acfg = acfg_create (ass, opts);
10951 memset (&acfg->aot_opts, 0, sizeof (acfg->aot_opts));
10952 acfg->aot_opts.write_symbols = TRUE;
10953 acfg->aot_opts.ntrampolines = 4096;
10954 acfg->aot_opts.nrgctx_trampolines = 4096;
10955 acfg->aot_opts.nimt_trampolines = 512;
10956 acfg->aot_opts.nrgctx_fetch_trampolines = 128;
10957 acfg->aot_opts.ngsharedvt_arg_trampolines = 512;
10958 acfg->aot_opts.llvm_path = g_strdup ("");
10959 acfg->aot_opts.temp_path = g_strdup ("");
10960 #ifdef MONOTOUCH
10961 acfg->aot_opts.use_trampolines_page = TRUE;
10962 #endif
10964 mono_aot_parse_options (aot_options, &acfg->aot_opts);
10966 if (acfg->aot_opts.logfile) {
10967 acfg->logfile = fopen (acfg->aot_opts.logfile, "a+");
10970 if (acfg->aot_opts.data_outfile) {
10971 acfg->data_outfile = fopen (acfg->aot_opts.data_outfile, "w+");
10972 if (!acfg->data_outfile) {
10973 aot_printerrf (acfg, "Unable to create file '%s': %s\n", acfg->aot_opts.data_outfile, strerror (errno));
10974 return 1;
10976 acfg->flags = (MonoAotFileFlags)(acfg->flags | MONO_AOT_FILE_FLAG_SEPARATE_DATA);
10979 //acfg->aot_opts.print_skipped_methods = TRUE;
10981 #if !defined(MONO_ARCH_GSHAREDVT_SUPPORTED)
10982 if (acfg->opts & MONO_OPT_GSHAREDVT) {
10983 aot_printerrf (acfg, "-O=gsharedvt not supported on this platform.\n");
10984 return 1;
10986 if (acfg->aot_opts.llvm_only) {
10987 aot_printerrf (acfg, "--aot=llvmonly requires a runtime that supports gsharedvt.\n");
10988 return 1;
10990 #else
10991 if (acfg->aot_opts.llvm_only || mono_aot_mode_is_full (&acfg->aot_opts) || mono_aot_mode_is_hybrid (&acfg->aot_opts))
10992 acfg->opts |= MONO_OPT_GSHAREDVT;
10993 #endif
10995 #if !defined(ENABLE_LLVM)
10996 if (acfg->aot_opts.llvm_only) {
10997 aot_printerrf (acfg, "--aot=llvmonly requires a runtime compiled with llvm support.\n");
10998 return 1;
11000 #endif
11002 if (acfg->opts & MONO_OPT_GSHAREDVT)
11003 mono_set_generic_sharing_vt_supported (TRUE);
11005 aot_printf (acfg, "Mono Ahead of Time compiler - compiling assembly %s\n", image->name);
11007 generate_aotid ((guint8*) &acfg->image->aotid);
11009 char *aotid = mono_guid_to_string (acfg->image->aotid);
11010 aot_printf (acfg, "AOTID %s\n", aotid);
11011 g_free (aotid);
11013 #ifndef MONO_ARCH_HAVE_FULL_AOT_TRAMPOLINES
11014 if (mono_aot_mode_is_full (&acfg->aot_opts)) {
11015 aot_printerrf (acfg, "--aot=full is not supported on this platform.\n");
11016 return 1;
11018 #endif
11020 if (acfg->aot_opts.direct_pinvoke && !acfg->aot_opts.static_link) {
11021 aot_printerrf (acfg, "The 'direct-pinvoke' AOT option also requires the 'static' AOT option.\n");
11022 return 1;
11025 if (acfg->aot_opts.static_link)
11026 acfg->aot_opts.asm_writer = TRUE;
11028 if (acfg->aot_opts.soft_debug) {
11029 MonoDebugOptions *opt = mini_get_debug_options ();
11031 opt->mdb_optimizations = TRUE;
11032 opt->gen_sdb_seq_points = TRUE;
11034 if (!mono_debug_enabled ()) {
11035 aot_printerrf (acfg, "The soft-debug AOT option requires the --debug option.\n");
11036 return 1;
11038 acfg->flags = (MonoAotFileFlags)(acfg->flags | MONO_AOT_FILE_FLAG_DEBUG);
11041 if (mono_use_llvm || acfg->aot_opts.llvm) {
11042 acfg->llvm = TRUE;
11043 acfg->aot_opts.asm_writer = TRUE;
11044 acfg->flags = (MonoAotFileFlags)(acfg->flags | MONO_AOT_FILE_FLAG_WITH_LLVM);
11046 if (acfg->aot_opts.soft_debug) {
11047 aot_printerrf (acfg, "The 'soft-debug' option is not supported when compiling with LLVM.\n");
11048 return 1;
11051 mini_llvm_init ();
11053 if (acfg->aot_opts.asm_only && !acfg->aot_opts.llvm_outfile) {
11054 aot_printerrf (acfg, "Compiling with LLVM and the asm-only option requires the llvm-outfile= option.\n");
11055 return 1;
11059 if (mono_aot_mode_is_full (&acfg->aot_opts))
11060 acfg->flags = (MonoAotFileFlags)(acfg->flags | MONO_AOT_FILE_FLAG_FULL_AOT);
11062 if (mono_threads_is_coop_enabled ())
11063 acfg->flags = (MonoAotFileFlags)(acfg->flags | MONO_AOT_FILE_FLAG_SAFEPOINTS);
11065 if (acfg->aot_opts.instances_logfile_path) {
11066 acfg->instances_logfile = fopen (acfg->aot_opts.instances_logfile_path, "w");
11067 if (!acfg->instances_logfile) {
11068 aot_printerrf (acfg, "Unable to create logfile: '%s'.\n", acfg->aot_opts.instances_logfile_path);
11069 return 1;
11073 if (acfg->aot_opts.profile_files) {
11074 GList *l;
11076 for (l = acfg->aot_opts.profile_files; l; l = l->next) {
11077 load_profile_file (acfg, (char*)l->data);
11082 int method_index;
11084 for (method_index = 0; method_index < acfg->image->tables [MONO_TABLE_METHOD].rows; ++method_index) {
11085 g_ptr_array_add (acfg->method_order,GUINT_TO_POINTER (method_index));
11089 acfg->num_trampolines [MONO_AOT_TRAMP_SPECIFIC] = mono_aot_mode_is_full (&acfg->aot_opts) ? acfg->aot_opts.ntrampolines : 0;
11090 #ifdef MONO_ARCH_GSHARED_SUPPORTED
11091 acfg->num_trampolines [MONO_AOT_TRAMP_STATIC_RGCTX] = mono_aot_mode_is_full (&acfg->aot_opts) ? acfg->aot_opts.nrgctx_trampolines : 0;
11092 #endif
11093 acfg->num_trampolines [MONO_AOT_TRAMP_IMT] = mono_aot_mode_is_full (&acfg->aot_opts) ? acfg->aot_opts.nimt_trampolines : 0;
11094 #ifdef MONO_ARCH_GSHAREDVT_SUPPORTED
11095 if (acfg->opts & MONO_OPT_GSHAREDVT)
11096 acfg->num_trampolines [MONO_AOT_TRAMP_GSHAREDVT_ARG] = mono_aot_mode_is_full (&acfg->aot_opts) ? acfg->aot_opts.ngsharedvt_arg_trampolines : 0;
11097 #endif
11099 acfg->temp_prefix = mono_img_writer_get_temp_label_prefix (NULL);
11101 arch_init (acfg);
11103 if (mono_use_llvm || acfg->aot_opts.llvm) {
11106 * Emit all LLVM code into a separate assembly/object file and link with it
11107 * normally.
11109 if (!acfg->aot_opts.asm_only && acfg->llvm_owriter_supported) {
11110 acfg->llvm_owriter = TRUE;
11111 } else if (acfg->aot_opts.llvm_outfile) {
11112 int len = strlen (acfg->aot_opts.llvm_outfile);
11114 if (len >= 2 && acfg->aot_opts.llvm_outfile [len - 2] == '.' && acfg->aot_opts.llvm_outfile [len - 1] == 'o')
11115 acfg->llvm_owriter = TRUE;
11119 if (acfg->llvm && acfg->thumb_mixed)
11120 acfg->flags = (MonoAotFileFlags)(acfg->flags | MONO_AOT_FILE_FLAG_LLVM_THUMB);
11121 if (acfg->aot_opts.llvm_only)
11122 acfg->flags = (MonoAotFileFlags)(acfg->flags | MONO_AOT_FILE_FLAG_LLVM_ONLY);
11124 acfg->assembly_name_sym = g_strdup (acfg->image->assembly->aname.name);
11125 /* Get rid of characters which cannot occur in symbols */
11126 for (p = acfg->assembly_name_sym; *p; ++p) {
11127 if (!(isalnum (*p) || *p == '_'))
11128 *p = '_';
11131 acfg->global_prefix = g_strdup_printf ("mono_aot_%s", acfg->assembly_name_sym);
11132 acfg->plt_symbol = g_strdup_printf ("%s_plt", acfg->global_prefix);
11133 acfg->got_symbol = g_strdup_printf ("%s_got", acfg->global_prefix);
11134 if (acfg->llvm) {
11135 acfg->llvm_got_symbol = g_strdup_printf ("%s_llvm_got", acfg->global_prefix);
11136 acfg->llvm_eh_frame_symbol = g_strdup_printf ("%s_eh_frame", acfg->global_prefix);
11139 acfg->method_index = 1;
11141 if (mono_aot_mode_is_full (&acfg->aot_opts) || mono_aot_mode_is_hybrid (&acfg->aot_opts))
11142 mono_set_partial_sharing_supported (TRUE);
11144 res = collect_methods (acfg);
11145 if (!res)
11146 return 1;
11149 GList *l;
11151 for (l = acfg->profile_data; l; l = l->next)
11152 resolve_profile_data (acfg, (ProfileData*)l->data);
11153 for (l = acfg->profile_data; l; l = l->next)
11154 add_profile_instances (acfg, (ProfileData*)l->data);
11157 acfg->cfgs_size = acfg->methods->len + 32;
11158 acfg->cfgs = g_new0 (MonoCompile*, acfg->cfgs_size);
11160 /* PLT offset 0 is reserved for the PLT trampoline */
11161 acfg->plt_offset = 1;
11162 add_preinit_got_slots (acfg);
11164 #ifdef ENABLE_LLVM
11165 if (acfg->llvm) {
11166 llvm_acfg = acfg;
11167 mono_llvm_create_aot_module (acfg->image->assembly, acfg->global_prefix, TRUE, acfg->aot_opts.static_link, acfg->aot_opts.llvm_only);
11169 #endif
11171 TV_GETTIME (atv);
11173 compile_methods (acfg);
11175 TV_GETTIME (btv);
11177 acfg->stats.jit_time = TV_ELAPSED (atv, btv);
11179 TV_GETTIME (atv);
11181 #ifdef ENABLE_LLVM
11182 if (acfg->llvm) {
11183 if (acfg->aot_opts.asm_only) {
11184 if (acfg->aot_opts.outfile) {
11185 acfg->tmpfname = g_strdup_printf ("%s", acfg->aot_opts.outfile);
11186 acfg->tmpbasename = g_strdup (acfg->tmpfname);
11187 } else {
11188 acfg->tmpbasename = g_strdup_printf ("%s", acfg->image->name);
11189 acfg->tmpfname = g_strdup_printf ("%s.s", acfg->tmpbasename);
11191 g_assert (acfg->aot_opts.llvm_outfile);
11192 acfg->llvm_sfile = g_strdup (acfg->aot_opts.llvm_outfile);
11193 if (acfg->llvm_owriter)
11194 acfg->llvm_ofile = g_strdup (acfg->aot_opts.llvm_outfile);
11195 else
11196 acfg->llvm_sfile = g_strdup (acfg->aot_opts.llvm_outfile);
11197 } else {
11198 acfg->tmpbasename = (strcmp (acfg->aot_opts.temp_path, "") == 0) ?
11199 g_strdup_printf ("%s", "temp") :
11200 g_build_filename (acfg->aot_opts.temp_path, "temp", NULL);
11202 acfg->tmpfname = g_strdup_printf ("%s.s", acfg->tmpbasename);
11203 acfg->llvm_sfile = g_strdup_printf ("%s-llvm.s", acfg->tmpbasename);
11204 acfg->llvm_ofile = g_strdup_printf ("%s-llvm.o", acfg->tmpbasename);
11207 #endif
11209 if (acfg->aot_opts.asm_only && !acfg->aot_opts.llvm_only) {
11210 if (acfg->aot_opts.outfile)
11211 acfg->tmpfname = g_strdup_printf ("%s", acfg->aot_opts.outfile);
11212 else
11213 acfg->tmpfname = g_strdup_printf ("%s.s", acfg->image->name);
11214 acfg->fp = fopen (acfg->tmpfname, "w+");
11215 } else {
11216 int i = g_file_open_tmp ("mono_aot_XXXXXX", &acfg->tmpfname, NULL);
11217 acfg->fp = fdopen (i, "w+");
11219 if (acfg->fp == 0 && !acfg->aot_opts.llvm_only) {
11220 aot_printerrf (acfg, "Unable to open file '%s': %s\n", acfg->tmpfname, strerror (errno));
11221 return 1;
11223 if (acfg->fp)
11224 acfg->w = mono_img_writer_create (acfg->fp, FALSE);
11226 tmp_outfile_name = NULL;
11227 outfile_name = NULL;
11229 /* Compute symbols for methods */
11230 for (i = 0; i < acfg->nmethods; ++i) {
11231 if (acfg->cfgs [i]) {
11232 MonoCompile *cfg = acfg->cfgs [i];
11233 int method_index = get_method_index (acfg, cfg->orig_method);
11235 if (COMPILE_LLVM (cfg))
11236 cfg->asm_symbol = g_strdup_printf ("%s%s", acfg->llvm_label_prefix, cfg->llvm_method_name);
11237 else if (acfg->global_symbols || acfg->llvm)
11238 cfg->asm_symbol = get_debug_sym (cfg->orig_method, "", acfg->method_label_hash);
11239 else
11240 cfg->asm_symbol = g_strdup_printf ("%s%sm_%x", acfg->temp_prefix, acfg->llvm_label_prefix, method_index);
11241 cfg->asm_debug_symbol = cfg->asm_symbol;
11245 if (acfg->aot_opts.dwarf_debug && acfg->aot_opts.gnu_asm) {
11247 * CLANG supports GAS .file/.loc directives, so emit line number information this way
11249 acfg->gas_line_numbers = TRUE;
11252 #ifdef EMIT_DWARF_INFO
11253 if ((!acfg->aot_opts.nodebug || acfg->aot_opts.dwarf_debug) && acfg->has_jitted_code) {
11254 if (acfg->aot_opts.dwarf_debug && !mono_debug_enabled ()) {
11255 aot_printerrf (acfg, "The dwarf AOT option requires the --debug option.\n");
11256 return 1;
11258 acfg->dwarf = mono_dwarf_writer_create (acfg->w, NULL, 0, !acfg->gas_line_numbers);
11260 #endif /* EMIT_DWARF_INFO */
11262 if (acfg->w)
11263 mono_img_writer_emit_start (acfg->w);
11265 if (acfg->dwarf)
11266 mono_dwarf_writer_emit_base_info (acfg->dwarf, g_path_get_basename (acfg->image->name), mono_unwind_get_cie_program ());
11268 emit_code (acfg);
11270 emit_info (acfg);
11272 emit_extra_methods (acfg);
11274 emit_trampolines (acfg);
11276 emit_class_name_table (acfg);
11278 emit_got_info (acfg, FALSE);
11279 if (acfg->llvm)
11280 emit_got_info (acfg, TRUE);
11282 emit_exception_info (acfg);
11284 emit_unwind_info (acfg);
11286 emit_class_info (acfg);
11288 emit_plt (acfg);
11290 emit_image_table (acfg);
11292 emit_got (acfg);
11296 * The managed allocators are GC specific, so can't use an AOT image created by one GC
11297 * in another.
11299 const char *gc_name = mono_gc_get_gc_name ();
11300 acfg->gc_name_offset = add_to_blob (acfg, (guint8*)gc_name, strlen (gc_name) + 1);
11303 emit_blob (acfg);
11305 emit_objc_selectors (acfg);
11307 emit_globals (acfg);
11309 emit_file_info (acfg);
11311 emit_library_info (acfg);
11313 if (acfg->dwarf) {
11314 emit_dwarf_info (acfg);
11315 mono_dwarf_writer_close (acfg->dwarf);
11318 emit_mem_end (acfg);
11320 if (acfg->need_pt_gnu_stack) {
11321 /* This is required so the .so doesn't have an executable stack */
11322 /* The bin writer already emits this */
11323 fprintf (acfg->fp, "\n.section .note.GNU-stack,\"\",@progbits\n");
11326 if (acfg->aot_opts.data_outfile)
11327 fclose (acfg->data_outfile);
11329 #ifdef ENABLE_LLVM
11330 if (acfg->llvm) {
11331 gboolean res;
11333 res = emit_llvm_file (acfg);
11334 if (!res)
11335 return 1;
11337 #endif
11339 TV_GETTIME (btv);
11341 acfg->stats.gen_time = TV_ELAPSED (atv, btv);
11343 if (acfg->llvm)
11344 sprintf (llvm_stats_msg, ", LLVM: %d (%d%%)", acfg->stats.llvm_count, acfg->stats.mcount ? (acfg->stats.llvm_count * 100) / acfg->stats.mcount : 100);
11345 else
11346 strcpy (llvm_stats_msg, "");
11348 all_sizes = acfg->stats.code_size + acfg->stats.info_size + acfg->stats.ex_info_size + acfg->stats.unwind_info_size + acfg->stats.class_info_size + acfg->stats.got_info_size + acfg->stats.offsets_size + acfg->stats.plt_size;
11350 aot_printf (acfg, "Code: %d(%d%%) Info: %d(%d%%) Ex Info: %d(%d%%) Unwind Info: %d(%d%%) Class Info: %d(%d%%) PLT: %d(%d%%) GOT Info: %d(%d%%) Offsets: %d(%d%%) GOT: %d\n",
11351 (int)acfg->stats.code_size, (int)(acfg->stats.code_size * 100 / all_sizes),
11352 (int)acfg->stats.info_size, (int)(acfg->stats.info_size * 100 / all_sizes),
11353 (int)acfg->stats.ex_info_size, (int)(acfg->stats.ex_info_size * 100 / all_sizes),
11354 (int)acfg->stats.unwind_info_size, (int)(acfg->stats.unwind_info_size * 100 / all_sizes),
11355 (int)acfg->stats.class_info_size, (int)(acfg->stats.class_info_size * 100 / all_sizes),
11356 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,
11357 (int)acfg->stats.got_info_size, (int)(acfg->stats.got_info_size * 100 / all_sizes),
11358 (int)acfg->stats.offsets_size, (int)(acfg->stats.offsets_size * 100 / all_sizes),
11359 (int)(acfg->got_offset * sizeof (gpointer)));
11360 aot_printf (acfg, "Compiled: %d/%d (%d%%)%s, No GOT slots: %d (%d%%), Direct calls: %d (%d%%)\n",
11361 acfg->stats.ccount, acfg->stats.mcount, acfg->stats.mcount ? (acfg->stats.ccount * 100) / acfg->stats.mcount : 100,
11362 llvm_stats_msg,
11363 acfg->stats.methods_without_got_slots, acfg->stats.mcount ? (acfg->stats.methods_without_got_slots * 100) / acfg->stats.mcount : 100,
11364 acfg->stats.direct_calls, acfg->stats.all_calls ? (acfg->stats.direct_calls * 100) / acfg->stats.all_calls : 100);
11365 if (acfg->stats.genericcount)
11366 aot_printf (acfg, "%d methods are generic (%d%%)\n", acfg->stats.genericcount, acfg->stats.mcount ? (acfg->stats.genericcount * 100) / acfg->stats.mcount : 100);
11367 if (acfg->stats.abscount)
11368 aot_printf (acfg, "%d methods contain absolute addresses (%d%%)\n", acfg->stats.abscount, acfg->stats.mcount ? (acfg->stats.abscount * 100) / acfg->stats.mcount : 100);
11369 if (acfg->stats.lmfcount)
11370 aot_printf (acfg, "%d methods contain lmf pointers (%d%%)\n", acfg->stats.lmfcount, acfg->stats.mcount ? (acfg->stats.lmfcount * 100) / acfg->stats.mcount : 100);
11371 if (acfg->stats.ocount)
11372 aot_printf (acfg, "%d methods have other problems (%d%%)\n", acfg->stats.ocount, acfg->stats.mcount ? (acfg->stats.ocount * 100) / acfg->stats.mcount : 100);
11374 TV_GETTIME (atv);
11375 if (acfg->w) {
11376 res = mono_img_writer_emit_writeout (acfg->w);
11377 if (res != 0) {
11378 acfg_free (acfg);
11379 return res;
11381 res = compile_asm (acfg);
11382 if (res != 0) {
11383 acfg_free (acfg);
11384 return res;
11387 TV_GETTIME (btv);
11388 acfg->stats.link_time = TV_ELAPSED (atv, btv);
11390 if (acfg->aot_opts.stats) {
11391 int i;
11393 aot_printf (acfg, "GOT slot distribution:\n");
11394 for (i = 0; i < MONO_PATCH_INFO_NUM; ++i)
11395 if (acfg->stats.got_slot_types [i])
11396 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]);
11397 aot_printf (acfg, "\nMethod stats:\n");
11398 aot_printf (acfg, "\tNormal: %d\n", acfg->stats.method_categories [METHOD_CAT_NORMAL]);
11399 aot_printf (acfg, "\tInstance: %d\n", acfg->stats.method_categories [METHOD_CAT_INST]);
11400 aot_printf (acfg, "\tGSharedvt: %d\n", acfg->stats.method_categories [METHOD_CAT_GSHAREDVT]);
11401 aot_printf (acfg, "\tWrapper: %d\n", acfg->stats.method_categories [METHOD_CAT_WRAPPER]);
11404 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);
11406 if (acfg->aot_opts.dump_json)
11407 aot_dump (acfg);
11409 acfg_free (acfg);
11411 return 0;
11414 #else
11416 /* AOT disabled */
11418 void*
11419 mono_aot_readonly_field_override (MonoClassField *field)
11421 return NULL;
11425 mono_compile_assembly (MonoAssembly *ass, guint32 opts, const char *aot_options)
11427 return 0;
11430 gboolean
11431 mono_aot_is_shared_got_offset (int offset)
11433 return FALSE;
11436 #endif