Merge remote branch 'upstream/master'
[mono.git] / mono / mini / aot-compiler.c
1 /*
2  * aot-compiler.c: mono Ahead of Time compiler
3  *
4  * Author:
5  *   Dietmar Maurer (dietmar@ximian.com)
6  *   Zoltan Varga (vargaz@gmail.com)
7  *
8  * (C) 2002 Ximian, Inc.
9  */
10
11 /* Remaining AOT-only work:
12  * - optimize the trampolines, generate more code in the arch files.
13  * - make things more consistent with how elf works, for example, use ELF 
14  *   relocations.
15  * Remaining generics sharing work:
16  * - optimize the size of the data which is encoded.
17  * - optimize the runtime loading of data:
18  *   - the trampoline code calls mono_jit_info_table_find () to find the rgctx, 
19  *     which loads the debugging+exception handling info for the method. This is a 
20  *     huge waste of time and code, since the rgctx structure is currently empty.
21  *   - every shared method has a MonoGenericJitInfo structure which is only really
22  *     used for handling catch clauses with open types, not a very common use case.
23  */
24 #include "config.h"
25 #include <sys/types.h>
26 #ifdef HAVE_UNISTD_H
27 #include <unistd.h>
28 #endif
29 #ifdef HAVE_STDINT_H
30 #include <stdint.h>
31 #endif
32 #include <fcntl.h>
33 #include <ctype.h>
34 #include <string.h>
35 #ifndef HOST_WIN32
36 #include <sys/time.h>
37 #else
38 #include <winsock2.h>
39 #include <windows.h>
40 #endif
41
42 #include <errno.h>
43 #include <sys/stat.h>
44
45
46 #include <mono/metadata/tabledefs.h>
47 #include <mono/metadata/class.h>
48 #include <mono/metadata/object.h>
49 #include <mono/metadata/tokentype.h>
50 #include <mono/metadata/appdomain.h>
51 #include <mono/metadata/debug-helpers.h>
52 #include <mono/metadata/assembly.h>
53 #include <mono/metadata/metadata-internals.h>
54 #include <mono/metadata/marshal.h>
55 #include <mono/metadata/gc-internal.h>
56 #include <mono/metadata/monitor.h>
57 #include <mono/metadata/mempool-internals.h>
58 #include <mono/metadata/mono-endian.h>
59 #include <mono/metadata/threads-types.h>
60 #include <mono/utils/mono-logger-internal.h>
61 #include <mono/utils/mono-compiler.h>
62 #include <mono/utils/mono-time.h>
63 #include <mono/utils/mono-mmap.h>
64
65 #include "mini.h"
66 #include "image-writer.h"
67 #include "dwarfwriter.h"
68
69 #if !defined(DISABLE_AOT) && !defined(DISABLE_JIT)
70
71 #if defined(__linux__) || defined(__native_client_codegen__)
72 #define RODATA_SECT ".rodata"
73 #else
74 #define RODATA_SECT ".text"
75 #endif
76
77 #define TV_DECLARE(name) gint64 name
78 #define TV_GETTIME(tv) tv = mono_100ns_ticks ()
79 #define TV_ELAPSED(start,end) (((end) - (start)) / 10)
80
81 #ifdef TARGET_WIN32
82 #define SHARED_EXT ".dll"
83 #elif defined(__ppc__) && defined(__MACH__)
84 #define SHARED_EXT ".dylib"
85 #elif defined(__APPLE__) && defined(TARGET_X86) && !defined(__native_client_codegen__)
86 #define SHARED_EXT ".dylib"
87 #else
88 #define SHARED_EXT ".so"
89 #endif
90
91 #define ALIGN_TO(val,align) ((((guint64)val) + ((align) - 1)) & ~((align) - 1))
92 #define ALIGN_PTR_TO(ptr,align) (gpointer)((((gssize)(ptr)) + (align - 1)) & (~(align - 1)))
93 #define ROUND_DOWN(VALUE,SIZE)  ((VALUE) & ~((SIZE) - 1))
94
95 typedef struct MonoAotOptions {
96         char *outfile;
97         gboolean save_temps;
98         gboolean write_symbols;
99         gboolean metadata_only;
100         gboolean bind_to_runtime_version;
101         gboolean full_aot;
102         gboolean no_dlsym;
103         gboolean static_link;
104         gboolean asm_only;
105         gboolean asm_writer;
106         gboolean nodebug;
107         gboolean soft_debug;
108         int nthreads;
109         int ntrampolines;
110         int nrgctx_trampolines;
111         int nimt_trampolines;
112         gboolean print_skipped_methods;
113         gboolean stats;
114         char *tool_prefix;
115         gboolean autoreg;
116         char *mtriple;
117 } MonoAotOptions;
118
119 typedef struct MonoAotStats {
120         int ccount, mcount, lmfcount, abscount, gcount, ocount, genericcount;
121         int code_size, info_size, ex_info_size, unwind_info_size, got_size, class_info_size, got_info_size;
122         int methods_without_got_slots, direct_calls, all_calls, llvm_count;
123         int got_slots, offsets_size;
124         int got_slot_types [MONO_PATCH_INFO_NONE];
125         int jit_time, gen_time, link_time;
126 } MonoAotStats;
127
128 typedef struct MonoAotCompile {
129         MonoImage *image;
130         GPtrArray *methods;
131         GHashTable *method_indexes;
132         GHashTable *method_depth;
133         MonoCompile **cfgs;
134         int cfgs_size;
135         GHashTable *patch_to_plt_entry;
136         GHashTable *plt_offset_to_entry;
137         GHashTable *patch_to_got_offset;
138         GHashTable **patch_to_got_offset_by_type;
139         GPtrArray *got_patches;
140         GHashTable *image_hash;
141         GHashTable *method_to_cfg;
142         GHashTable *token_info_hash;
143         GPtrArray *extra_methods;
144         GPtrArray *image_table;
145         GPtrArray *globals;
146         GList *method_order;
147         guint32 *plt_got_info_offsets;
148         guint32 got_offset, plt_offset, plt_got_offset_base;
149         guint32 final_got_size;
150         /* Number of GOT entries reserved for trampolines */
151         guint32 num_trampoline_got_entries;
152
153         guint32 num_trampolines [MONO_AOT_TRAMP_NUM];
154         guint32 trampoline_got_offset_base [MONO_AOT_TRAMP_NUM];
155         guint32 trampoline_size [MONO_AOT_TRAMP_NUM];
156
157         MonoAotOptions aot_opts;
158         guint32 nmethods;
159         guint32 opts;
160         MonoMemPool *mempool;
161         MonoAotStats stats;
162         int method_index;
163         char *static_linking_symbol;
164         CRITICAL_SECTION mutex;
165         gboolean use_bin_writer;
166         MonoImageWriter *w;
167         MonoDwarfWriter *dwarf;
168         FILE *fp;
169         char *tmpfname;
170         GSList *cie_program;
171         GHashTable *unwind_info_offsets;
172         GPtrArray *unwind_ops;
173         guint32 unwind_info_offset;
174         char *got_symbol_base;
175         char *got_symbol;
176         char *plt_symbol;
177         GHashTable *method_label_hash;
178         const char *temp_prefix;
179         const char *llvm_label_prefix;
180         guint32 label_generator;
181         gboolean llvm;
182         MonoAotFileFlags flags;
183         MonoDynamicStream blob;
184         MonoClass **typespec_classes;
185         GString *llc_args;
186         GString *as_args;
187         gboolean thumb_mixed;
188 } MonoAotCompile;
189
190 typedef struct {
191         int plt_offset;
192         char *symbol, *llvm_symbol, *debug_sym;
193         MonoJumpInfo *ji;
194         gboolean jit_used, llvm_used;
195 } MonoPltEntry;
196
197 #define mono_acfg_lock(acfg) EnterCriticalSection (&((acfg)->mutex))
198 #define mono_acfg_unlock(acfg) LeaveCriticalSection (&((acfg)->mutex))
199
200 /* This points to the current acfg in LLVM mode */
201 static MonoAotCompile *llvm_acfg;
202
203 #ifdef HAVE_ARRAY_ELEM_INIT
204 #define MSGSTRFIELD(line) MSGSTRFIELD1(line)
205 #define MSGSTRFIELD1(line) str##line
206 static const struct msgstr_t {
207 #define PATCH_INFO(a,b) char MSGSTRFIELD(__LINE__) [sizeof (b)];
208 #include "patch-info.h"
209 #undef PATCH_INFO
210 } opstr = {
211 #define PATCH_INFO(a,b) b,
212 #include "patch-info.h"
213 #undef PATCH_INFO
214 };
215 static const gint16 opidx [] = {
216 #define PATCH_INFO(a,b) [MONO_PATCH_INFO_ ## a] = offsetof (struct msgstr_t, MSGSTRFIELD(__LINE__)),
217 #include "patch-info.h"
218 #undef PATCH_INFO
219 };
220
221 static G_GNUC_UNUSED const char*
222 get_patch_name (int info)
223 {
224         return (const char*)&opstr + opidx [info];
225 }
226
227 #else
228 #define PATCH_INFO(a,b) b,
229 static const char* const
230 patch_types [MONO_PATCH_INFO_NUM + 1] = {
231 #include "patch-info.h"
232         NULL
233 };
234
235 static G_GNUC_UNUSED const char*
236 get_patch_name (int info)
237 {
238         return patch_types [info];
239 }
240
241 #endif
242
243 /* Wrappers around the image writer functions */
244
245 static inline void
246 emit_section_change (MonoAotCompile *acfg, const char *section_name, int subsection_index)
247 {
248         img_writer_emit_section_change (acfg->w, section_name, subsection_index);
249 }
250
251 static inline void
252 emit_push_section (MonoAotCompile *acfg, const char *section_name, int subsection)
253 {
254         img_writer_emit_push_section (acfg->w, section_name, subsection);
255 }
256
257 static inline void
258 emit_pop_section (MonoAotCompile *acfg)
259 {
260         img_writer_emit_pop_section (acfg->w);
261 }
262
263 static inline void
264 emit_local_symbol (MonoAotCompile *acfg, const char *name, const char *end_label, gboolean func) 
265
266         img_writer_emit_local_symbol (acfg->w, name, end_label, func); 
267 }
268
269 static inline void
270 emit_label (MonoAotCompile *acfg, const char *name) 
271
272         img_writer_emit_label (acfg->w, name); 
273 }
274
275 static inline void
276 emit_bytes (MonoAotCompile *acfg, const guint8* buf, int size) 
277
278         img_writer_emit_bytes (acfg->w, buf, size); 
279 }
280
281 static inline void
282 emit_string (MonoAotCompile *acfg, const char *value) 
283
284         img_writer_emit_string (acfg->w, value); 
285 }
286
287 static inline void
288 emit_line (MonoAotCompile *acfg) 
289
290         img_writer_emit_line (acfg->w); 
291 }
292
293 static inline void
294 emit_alignment (MonoAotCompile *acfg, int size) 
295
296         img_writer_emit_alignment (acfg->w, size); 
297 }
298
299 static inline void
300 emit_pointer_unaligned (MonoAotCompile *acfg, const char *target) 
301
302         img_writer_emit_pointer_unaligned (acfg->w, target); 
303 }
304
305 static inline void
306 emit_pointer (MonoAotCompile *acfg, const char *target) 
307
308         img_writer_emit_pointer (acfg->w, target); 
309 }
310
311 static inline void
312 emit_int16 (MonoAotCompile *acfg, int value) 
313
314         img_writer_emit_int16 (acfg->w, value); 
315 }
316
317 static inline void
318 emit_int32 (MonoAotCompile *acfg, int value) 
319
320         img_writer_emit_int32 (acfg->w, value); 
321 }
322
323 static inline void
324 emit_symbol_diff (MonoAotCompile *acfg, const char *end, const char* start, int offset) 
325
326         img_writer_emit_symbol_diff (acfg->w, end, start, offset); 
327 }
328
329 static inline void
330 emit_zero_bytes (MonoAotCompile *acfg, int num) 
331
332         img_writer_emit_zero_bytes (acfg->w, num); 
333 }
334
335 static inline void
336 emit_byte (MonoAotCompile *acfg, guint8 val) 
337
338         img_writer_emit_byte (acfg->w, val); 
339 }
340
341 #ifdef __native_client_codegen__
342 static inline void
343 emit_nacl_call_alignment (MonoAotCompile *acfg)
344 {
345         img_writer_emit_nacl_call_alignment (acfg->w);
346 }
347 #endif
348
349 static G_GNUC_UNUSED void
350 emit_global_inner (MonoAotCompile *acfg, const char *name, gboolean func)
351 {
352         img_writer_emit_global (acfg->w, name, func);
353 }
354
355 static void
356 emit_global (MonoAotCompile *acfg, const char *name, gboolean func)
357 {
358         if (acfg->aot_opts.no_dlsym) {
359                 g_ptr_array_add (acfg->globals, g_strdup (name));
360                 img_writer_emit_local_symbol (acfg->w, name, NULL, func);
361         } else {
362                 img_writer_emit_global (acfg->w, name, func);
363         }
364 }
365
366 static void
367 emit_symbol_size (MonoAotCompile *acfg, const char *name, const char *end_label)
368 {
369         img_writer_emit_symbol_size (acfg->w, name, end_label);
370 }
371
372 static void
373 emit_string_symbol (MonoAotCompile *acfg, const char *name, const char *value)
374 {
375         img_writer_emit_section_change (acfg->w, RODATA_SECT, 1);
376         emit_global (acfg, name, FALSE);
377         img_writer_emit_label (acfg->w, name);
378         img_writer_emit_string (acfg->w, value);
379 }
380
381 static void
382 emit_local_string_symbol (MonoAotCompile *acfg, const char *name, const char *value)
383 {
384         img_writer_emit_section_change (acfg->w, RODATA_SECT, 1);
385         img_writer_emit_label (acfg->w, name);
386         img_writer_emit_string (acfg->w, value);
387 }
388
389 static G_GNUC_UNUSED void
390 emit_uleb128 (MonoAotCompile *acfg, guint32 value)
391 {
392         do {
393                 guint8 b = value & 0x7f;
394                 value >>= 7;
395                 if (value != 0) /* more bytes to come */
396                         b |= 0x80;
397                 emit_byte (acfg, b);
398         } while (value);
399 }
400
401 static G_GNUC_UNUSED void
402 emit_sleb128 (MonoAotCompile *acfg, gint64 value)
403 {
404         gboolean more = 1;
405         gboolean negative = (value < 0);
406         guint32 size = 64;
407         guint8 byte;
408
409         while (more) {
410                 byte = value & 0x7f;
411                 value >>= 7;
412                 /* the following is unnecessary if the
413                  * implementation of >>= uses an arithmetic rather
414                  * than logical shift for a signed left operand
415                  */
416                 if (negative)
417                         /* sign extend */
418                         value |= - ((gint64)1 <<(size - 7));
419                 /* sign bit of byte is second high order bit (0x40) */
420                 if ((value == 0 && !(byte & 0x40)) ||
421                         (value == -1 && (byte & 0x40)))
422                         more = 0;
423                 else
424                         byte |= 0x80;
425                 emit_byte (acfg, byte);
426         }
427 }
428
429 static G_GNUC_UNUSED void
430 encode_uleb128 (guint32 value, guint8 *buf, guint8 **endbuf)
431 {
432         guint8 *p = buf;
433
434         do {
435                 guint8 b = value & 0x7f;
436                 value >>= 7;
437                 if (value != 0) /* more bytes to come */
438                         b |= 0x80;
439                 *p ++ = b;
440         } while (value);
441
442         *endbuf = p;
443 }
444
445 static G_GNUC_UNUSED void
446 encode_sleb128 (gint32 value, guint8 *buf, guint8 **endbuf)
447 {
448         gboolean more = 1;
449         gboolean negative = (value < 0);
450         guint32 size = 32;
451         guint8 byte;
452         guint8 *p = buf;
453
454         while (more) {
455                 byte = value & 0x7f;
456                 value >>= 7;
457                 /* the following is unnecessary if the
458                  * implementation of >>= uses an arithmetic rather
459                  * than logical shift for a signed left operand
460                  */
461                 if (negative)
462                         /* sign extend */
463                         value |= - (1 <<(size - 7));
464                 /* sign bit of byte is second high order bit (0x40) */
465                 if ((value == 0 && !(byte & 0x40)) ||
466                         (value == -1 && (byte & 0x40)))
467                         more = 0;
468                 else
469                         byte |= 0x80;
470                 *p ++= byte;
471         }
472
473         *endbuf = p;
474 }
475
476 /* ARCHITECTURE SPECIFIC CODE */
477
478 #if defined(TARGET_X86) || defined(TARGET_AMD64) || defined(TARGET_ARM) || defined(TARGET_POWERPC)
479 #define EMIT_DWARF_INFO 1
480 #endif
481
482 #if defined(TARGET_ARM)
483 #define AOT_FUNC_ALIGNMENT 4
484 #else
485 #define AOT_FUNC_ALIGNMENT 16
486 #endif
487 #if (defined(TARGET_X86) || defined(TARGET_AMD64)) && defined(__native_client_codegen__)
488 #undef AOT_FUNC_ALIGNMENT
489 #define AOT_FUNC_ALIGNMENT 32
490 #endif
491  
492 #if defined(TARGET_POWERPC64) && !defined(__mono_ilp32__)
493 #define PPC_LD_OP "ld"
494 #define PPC_LDX_OP "ldx"
495 #else
496 #define PPC_LD_OP "lwz"
497 #define PPC_LDX_OP "lwzx"
498 #endif
499
500 static void
501 arch_init (MonoAotCompile *acfg)
502 {
503         acfg->llc_args = g_string_new ("");
504         acfg->as_args = g_string_new ("");
505
506         /*
507          * The prefix LLVM likes to put in front of symbol names on darwin.
508          * The mach-os specs require this for globals, but LLVM puts them in front of all
509          * symbols. We need to handle this, since we need to refer to LLVM generated
510          * symbols.
511          */
512         acfg->llvm_label_prefix = "";
513
514 #ifdef TARGET_ARM
515         if (acfg->aot_opts.mtriple && strstr (acfg->aot_opts.mtriple, "darwin")) {
516                 g_string_append (acfg->llc_args, "-mattr=+v6");
517                 acfg->llvm_label_prefix = "_";
518         } else {
519 #ifdef ARM_FPU_VFP
520                 g_string_append (acfg->llc_args, " -mattr=+vfp2,+d16");
521                 g_string_append (acfg->as_args, " -mfpu=vfp3");
522 #else
523                 g_string_append (acfg->llc_args, " -soft-float");
524 #endif
525         }
526         if (acfg->aot_opts.mtriple && strstr (acfg->aot_opts.mtriple, "thumb"))
527                 acfg->thumb_mixed = TRUE;
528
529         if (acfg->aot_opts.mtriple)
530                 mono_arch_set_target (acfg->aot_opts.mtriple);
531 #endif
532 }
533
534 /*
535  * arch_emit_direct_call:
536  *
537  *   Emit a direct call to the symbol TARGET. CALL_SIZE is set to the size of the
538  * calling code.
539  */
540 static void
541 arch_emit_direct_call (MonoAotCompile *acfg, const char *target, int *call_size)
542 {
543 #if defined(TARGET_X86) || defined(TARGET_AMD64)
544         /* Need to make sure this is exactly 5 bytes long */
545         emit_byte (acfg, '\xe8');
546         emit_symbol_diff (acfg, target, ".", -4);
547         *call_size = 5;
548 #elif defined(TARGET_ARM)
549         if (acfg->use_bin_writer) {
550                 guint8 buf [4];
551                 guint8 *code;
552
553                 code = buf;
554                 ARM_BL (code, 0);
555
556                 img_writer_emit_reloc (acfg->w, R_ARM_CALL, target, -8);
557                 emit_bytes (acfg, buf, 4);
558         } else {
559                 img_writer_emit_unset_mode (acfg->w);
560                 fprintf (acfg->fp, "bl %s\n", target);
561         }
562         *call_size = 4;
563 #elif defined(TARGET_POWERPC)
564         if (acfg->use_bin_writer) {
565                 g_assert_not_reached ();
566         } else {
567                 img_writer_emit_unset_mode (acfg->w);
568                 fprintf (acfg->fp, "bl %s\n", target);
569                 *call_size = 4;
570         }
571 #else
572         g_assert_not_reached ();
573 #endif
574 }
575
576 /*
577  * PPC32 design:
578  * - we use an approach similar to the x86 abi: reserve a register (r30) to hold 
579  *   the GOT pointer.
580  * - The full-aot trampolines need access to the GOT of mscorlib, so we store
581  *   in in the 2. slot of every GOT, and require every method to place the GOT
582  *   address in r30, even when it doesn't access the GOT otherwise. This way,
583  *   the trampolines can compute the mscorlib GOT address by loading 4(r30).
584  */
585
586 /*
587  * PPC64 design:
588  * PPC64 uses function descriptors which greatly complicate all code, since
589  * these are used very inconsistently in the runtime. Some functions like 
590  * mono_compile_method () return ftn descriptors, while others like the
591  * trampoline creation functions do not.
592  * We assume that all GOT slots contain function descriptors, and create 
593  * descriptors in aot-runtime.c when needed.
594  * The ppc64 abi uses r2 to hold the address of the TOC/GOT, which is loaded
595  * from function descriptors, we could do the same, but it would require 
596  * rewriting all the ppc/aot code to handle function descriptors properly.
597  * So instead, we use the same approach as on PPC32.
598  * This is a horrible mess, but fixing it would probably lead to an even bigger
599  * one.
600  */
601
602 /*
603  * X86 design:
604  * - similar to the PPC32 design, we reserve EBX to hold the GOT pointer.
605  */
606
607 #ifdef MONO_ARCH_AOT_SUPPORTED
608 /*
609  * arch_emit_got_offset:
610  *
611  *   The memory pointed to by CODE should hold native code for computing the GOT
612  * address. Emit this code while patching it with the offset between code and
613  * the GOT. CODE_SIZE is set to the number of bytes emitted.
614  */
615 static void
616 arch_emit_got_offset (MonoAotCompile *acfg, guint8 *code, int *code_size)
617 {
618 #if defined(TARGET_POWERPC64)
619         g_assert (!acfg->use_bin_writer);
620         img_writer_emit_unset_mode (acfg->w);
621         /* 
622          * The ppc32 code doesn't seem to work on ppc64, the assembler complains about
623          * unsupported relocations. So we store the got address into the .Lgot_addr
624          * symbol which is in the text segment, compute its address, and load it.
625          */
626         fprintf (acfg->fp, ".L%d:\n", acfg->label_generator);
627         fprintf (acfg->fp, "lis 0, (.Lgot_addr + 4 - .L%d)@h\n", acfg->label_generator);
628         fprintf (acfg->fp, "ori 0, 0, (.Lgot_addr + 4 - .L%d)@l\n", acfg->label_generator);
629         fprintf (acfg->fp, "add 30, 30, 0\n");
630         fprintf (acfg->fp, "%s 30, 0(30)\n", PPC_LD_OP);
631         acfg->label_generator ++;
632         *code_size = 16;
633 #elif defined(TARGET_POWERPC)
634         g_assert (!acfg->use_bin_writer);
635         img_writer_emit_unset_mode (acfg->w);
636         fprintf (acfg->fp, ".L%d:\n", acfg->label_generator);
637         fprintf (acfg->fp, "lis 0, (%s + 4 - .L%d)@h\n", acfg->got_symbol, acfg->label_generator);
638         fprintf (acfg->fp, "ori 0, 0, (%s + 4 - .L%d)@l\n", acfg->got_symbol, acfg->label_generator);
639         acfg->label_generator ++;
640         *code_size = 8;
641 #else
642         guint32 offset = mono_arch_get_patch_offset (code);
643         emit_bytes (acfg, code, offset);
644         emit_symbol_diff (acfg, acfg->got_symbol, ".", offset);
645
646         *code_size = offset + 4;
647 #endif
648 }
649
650 /*
651  * arch_emit_got_access:
652  *
653  *   The memory pointed to by CODE should hold native code for loading a GOT
654  * slot. Emit this code while patching it so it accesses the GOT slot GOT_SLOT.
655  * CODE_SIZE is set to the number of bytes emitted.
656  */
657 static void
658 arch_emit_got_access (MonoAotCompile *acfg, guint8 *code, int got_slot, int *code_size)
659 {
660         /* Emit beginning of instruction */
661         emit_bytes (acfg, code, mono_arch_get_patch_offset (code));
662
663         /* Emit the offset */
664 #ifdef TARGET_AMD64
665         emit_symbol_diff (acfg, acfg->got_symbol, ".", (unsigned int) ((got_slot * sizeof (gpointer)) - 4));
666         *code_size = mono_arch_get_patch_offset (code) + 4;
667 #elif defined(TARGET_X86)
668         emit_int32 (acfg, (unsigned int) ((got_slot * sizeof (gpointer))));
669         *code_size = mono_arch_get_patch_offset (code) + 4;
670 #elif defined(TARGET_ARM)
671         emit_symbol_diff (acfg, acfg->got_symbol, ".", (unsigned int) ((got_slot * sizeof (gpointer))) - 12);
672         *code_size = mono_arch_get_patch_offset (code) + 4;
673 #elif defined(TARGET_POWERPC)
674         {
675                 guint8 buf [32];
676                 guint8 *code;
677
678                 code = buf;
679                 ppc_load32 (code, ppc_r0, got_slot * sizeof (gpointer));
680                 g_assert (code - buf == 8);
681                 emit_bytes (acfg, buf, code - buf);
682                 *code_size = code - buf;
683         }
684 #else
685         g_assert_not_reached ();
686 #endif
687 }
688
689 #endif
690
691 /*
692  * arch_emit_plt_entry:
693  *
694  *   Emit code for the PLT entry with index INDEX.
695  */
696 static void
697 arch_emit_plt_entry (MonoAotCompile *acfg, int index)
698 {
699 #if defined(TARGET_X86)
700                 guint32 offset = (acfg->plt_got_offset_base + index) * sizeof (gpointer);
701 #if defined(__default_codegen__)
702                 /* jmp *<offset>(%ebx) */
703                 emit_byte (acfg, 0xff);
704                 emit_byte (acfg, 0xa3);
705                 emit_int32 (acfg, offset);
706                 /* Used by mono_aot_get_plt_info_offset */
707                 emit_int32 (acfg, acfg->plt_got_info_offsets [index]);
708 #elif defined(__native_client_codegen__)
709                 const guint8 kSizeOfNaClJmp = 11;
710                 guint8 bytes[kSizeOfNaClJmp];
711                 guint8 *pbytes = &bytes[0];
712                 
713                 x86_jump_membase32 (pbytes, X86_EBX, offset);
714                 emit_bytes (acfg, bytes, kSizeOfNaClJmp);
715                 /* four bytes of data, used by mono_arch_patch_plt_entry              */
716                 /* For Native Client, make this work with data embedded in push.      */
717                 emit_byte (acfg, 0x68);  /* hide data in a push */
718                 emit_int32 (acfg, acfg->plt_got_info_offsets [index]);
719                 emit_alignment (acfg, AOT_FUNC_ALIGNMENT);
720 #endif /*__native_client_codegen__*/
721 #elif defined(TARGET_AMD64)
722 #if defined(__default_codegen__)
723                 /*
724                  * We can't emit jumps because they are 32 bits only so they can't be patched.
725                  * So we make indirect calls through GOT entries which are patched by the AOT 
726                  * loader to point to .Lpd entries. 
727                  */
728                 /* jmpq *<offset>(%rip) */
729                 emit_byte (acfg, '\xff');
730                 emit_byte (acfg, '\x25');
731                 emit_symbol_diff (acfg, acfg->got_symbol, ".", ((acfg->plt_got_offset_base + index) * sizeof (gpointer)) -4);
732                 /* Used by mono_aot_get_plt_info_offset */
733                 emit_int32 (acfg, acfg->plt_got_info_offsets [index]);
734 #elif defined(__native_client_codegen__)
735                 guint8 buf [256];
736                 guint8 *buf_aligned = ALIGN_TO(buf, kNaClAlignment);
737                 guint8 *code = buf_aligned;
738
739                 /* mov <OFFSET>(%rip), %r11d */
740                 emit_byte (acfg, '\x45');
741                 emit_byte (acfg, '\x8b');
742                 emit_byte (acfg, '\x1d');
743                 emit_symbol_diff (acfg, acfg->got_symbol, ".", ((acfg->plt_got_offset_base + index) * sizeof (gpointer)) -4);
744
745                 amd64_jump_reg (code, AMD64_R11);
746                 /* This should be constant for the plt patch */
747                 g_assert ((size_t)(code-buf_aligned) == 10);
748                 emit_bytes (acfg, buf_aligned, code - buf_aligned);
749
750                 /* Hide data in a push imm32 so it passes validation */
751                 emit_byte (acfg, 0x68);  /* push */
752                 emit_int32 (acfg, acfg->plt_got_info_offsets [index]);
753                 emit_alignment (acfg, AOT_FUNC_ALIGNMENT);
754 #endif /*__native_client_codegen__*/
755 #elif defined(TARGET_ARM)
756                 guint8 buf [256];
757                 guint8 *code;
758
759                 code = buf;
760                 ARM_LDR_IMM (code, ARMREG_IP, ARMREG_PC, 0);
761                 ARM_LDR_REG_REG (code, ARMREG_PC, ARMREG_PC, ARMREG_IP);
762                 emit_bytes (acfg, buf, code - buf);
763                 emit_symbol_diff (acfg, acfg->got_symbol, ".", ((acfg->plt_got_offset_base + index) * sizeof (gpointer)) - 4);
764                 /* Used by mono_aot_get_plt_info_offset */
765                 emit_int32 (acfg, acfg->plt_got_info_offsets [index]);
766 #elif defined(TARGET_POWERPC)
767                 guint32 offset = (acfg->plt_got_offset_base + index) * sizeof (gpointer);
768
769                 /* The GOT address is guaranteed to be in r30 by OP_LOAD_GOTADDR */
770                 g_assert (!acfg->use_bin_writer);
771                 img_writer_emit_unset_mode (acfg->w);
772                 fprintf (acfg->fp, "lis 11, %d@h\n", offset);
773                 fprintf (acfg->fp, "ori 11, 11, %d@l\n", offset);
774                 fprintf (acfg->fp, "add 11, 11, 30\n");
775                 fprintf (acfg->fp, "%s 11, 0(11)\n", PPC_LD_OP);
776 #ifdef PPC_USES_FUNCTION_DESCRIPTOR
777                 fprintf (acfg->fp, "%s 2, %d(11)\n", PPC_LD_OP, (int)sizeof (gpointer));
778                 fprintf (acfg->fp, "%s 11, 0(11)\n", PPC_LD_OP);
779 #endif
780                 fprintf (acfg->fp, "mtctr 11\n");
781                 fprintf (acfg->fp, "bctr\n");
782                 emit_int32 (acfg, acfg->plt_got_info_offsets [index]);
783 #else
784                 g_assert_not_reached ();
785 #endif
786 }
787
788 static void
789 arch_emit_llvm_plt_entry (MonoAotCompile *acfg, int index)
790 {
791 #if defined(TARGET_ARM)
792 #if 0
793         /* LLVM calls the PLT entries using bl, so emit a stub */
794         /* FIXME: Too much overhead on every call */
795         fprintf (acfg->fp, ".thumb_func\n");
796         fprintf (acfg->fp, "bx pc\n");
797         fprintf (acfg->fp, "nop\n");
798         fprintf (acfg->fp, ".arm\n");
799 #endif
800         /* LLVM calls the PLT entries using bl, so these have to be thumb2 */
801         fprintf (acfg->fp, ".thumb_func\n");
802         /* The code below should be 12 bytes long */
803         fprintf (acfg->fp, "ldr ip, [pc, #8]\n");
804         /* thumb can't encode ld pc, [pc, ip] */
805         fprintf (acfg->fp, "add ip, pc, ip\n");
806         fprintf (acfg->fp, "ldr ip, [ip, #0]\n");
807         fprintf (acfg->fp, "bx ip\n");
808         emit_symbol_diff (acfg, acfg->got_symbol, ".", ((acfg->plt_got_offset_base + index) * sizeof (gpointer)) + 4);
809         emit_int32 (acfg, acfg->plt_got_info_offsets [index]);
810 #else
811         g_assert_not_reached ();
812 #endif
813 }
814
815 /*
816  * arch_emit_specific_trampoline:
817  *
818  *   Emit code for a specific trampoline. OFFSET is the offset of the first of
819  * two GOT slots which contain the generic trampoline address and the trampoline
820  * argument. TRAMP_SIZE is set to the size of the emitted trampoline.
821  */
822 static void
823 arch_emit_specific_trampoline (MonoAotCompile *acfg, int offset, int *tramp_size)
824 {
825         /*
826          * The trampolines created here are variations of the specific 
827          * trampolines created in mono_arch_create_specific_trampoline (). The 
828          * differences are:
829          * - the generic trampoline address is taken from a got slot.
830          * - the offset of the got slot where the trampoline argument is stored
831          *   is embedded in the instruction stream, and the generic trampoline
832          *   can load the argument by loading the offset, adding it to the
833          *   address of the trampoline to get the address of the got slot, and
834          *   loading the argument from there.
835          * - all the trampolines should be of the same length.
836          */
837 #if defined(TARGET_AMD64)
838 #if defined(__default_codegen__)
839         /* This should be exactly 16 bytes long */
840         *tramp_size = 16;
841         /* call *<offset>(%rip) */
842         emit_byte (acfg, '\x41');
843         emit_byte (acfg, '\xff');
844         emit_byte (acfg, '\x15');
845         emit_symbol_diff (acfg, acfg->got_symbol, ".", (offset * sizeof (gpointer)) - 4);
846         /* This should be relative to the start of the trampoline */
847         emit_symbol_diff (acfg, acfg->got_symbol, ".", ((offset+1) * sizeof (gpointer)) + 7);
848         emit_zero_bytes (acfg, 5);
849 #elif defined(__native_client_codegen__)
850         guint8 buf [256];
851         guint8 *buf_aligned = ALIGN_TO(buf, kNaClAlignment);
852         guint8 *code = buf_aligned;
853         guint8 *call_start;
854         size_t call_len;
855         int got_offset;
856
857         /* Emit this call in 'code' so we can find out how long it is. */
858         amd64_call_reg (code, AMD64_R11);
859         call_start = mono_arch_nacl_skip_nops (buf_aligned);
860         call_len = code - call_start;
861
862         /* The tramp_size is twice the NaCl alignment because it starts with */ 
863         /* a call which needs to be aligned to the end of the boundary.      */
864         *tramp_size = kNaClAlignment*2;
865         {
866                 /* Emit nops to align call site below which is 7 bytes plus */
867                 /* the length of the call sequence emitted above.           */
868                 /* Note: this requires the specific trampoline starts on a  */
869                 /* kNaclAlignedment aligned address, which it does because  */
870                 /* it's its own function that is aligned.                   */
871                 guint8 nop_buf[256];
872                 guint8 *nopbuf_aligned = ALIGN_TO (nop_buf, kNaClAlignment);
873                 guint8 *nopbuf_end = mono_arch_nacl_pad (nopbuf_aligned, kNaClAlignment - 7 - (call_len));
874                 emit_bytes (acfg, nopbuf_aligned, nopbuf_end - nopbuf_aligned);
875         }
876         /* The trampoline is stored at the offset'th pointer, the -4 is  */
877         /* present because RIP relative addressing starts at the end of  */
878         /* the current instruction, while the label "." is relative to   */
879         /* the beginning of the current asm location, which in this case */
880         /* is not the mov instruction, but the offset itself, due to the */
881         /* way the bytes and ints are emitted here.                      */
882         got_offset = (offset * sizeof(gpointer)) - 4;
883
884         /* mov <OFFSET>(%rip), %r11d */
885         emit_byte (acfg, '\x45');
886         emit_byte (acfg, '\x8b');
887         emit_byte (acfg, '\x1d');
888         emit_symbol_diff (acfg, acfg->got_symbol, ".", got_offset);
889
890         /* naclcall %r11 */
891         emit_bytes (acfg, call_start, call_len);
892
893         /* The arg is stored at the offset+1 pointer, relative to beginning */
894         /* of trampoline: 7 for mov, plus the call length, and 1 for push.  */
895         got_offset = ((offset + 1) * sizeof(gpointer)) + 7 + call_len + 1;
896
897         /* We can't emit this data directly, hide in a "push imm32" */
898         emit_byte (acfg, '\x68'); /* push */
899         emit_symbol_diff (acfg, acfg->got_symbol, ".", got_offset);
900         emit_alignment (acfg, kNaClAlignment);
901 #endif /*__native_client_codegen__*/
902 #elif defined(TARGET_ARM)
903         guint8 buf [128];
904         guint8 *code;
905
906         /* This should be exactly 20 bytes long */
907         *tramp_size = 20;
908         code = buf;
909         ARM_PUSH (code, 0x5fff);
910         ARM_LDR_IMM (code, ARMREG_R1, ARMREG_PC, 4);
911         /* Load the value from the GOT */
912         ARM_LDR_REG_REG (code, ARMREG_R1, ARMREG_PC, ARMREG_R1);
913         /* Branch to it */
914         ARM_BLX_REG (code, ARMREG_R1);
915
916         g_assert (code - buf == 16);
917
918         /* Emit it */
919         emit_bytes (acfg, buf, code - buf);
920         /* 
921          * Only one offset is needed, since the second one would be equal to the
922          * first one.
923          */
924         emit_symbol_diff (acfg, acfg->got_symbol, ".", (offset * sizeof (gpointer)) - 4 + 4);
925         //emit_symbol_diff (acfg, acfg->got_symbol, ".", ((offset + 1) * sizeof (gpointer)) - 4 + 8);
926 #elif defined(TARGET_POWERPC)
927         guint8 buf [128];
928         guint8 *code;
929
930         *tramp_size = 4;
931         code = buf;
932
933         g_assert (!acfg->use_bin_writer);
934
935         /*
936          * PPC has no ip relative addressing, so we need to compute the address
937          * of the mscorlib got. That is slow and complex, so instead, we store it
938          * in the second got slot of every aot image. The caller already computed
939          * the address of its got and placed it into r30.
940          */
941         img_writer_emit_unset_mode (acfg->w);
942         /* Load mscorlib got address */
943         fprintf (acfg->fp, "%s 0, %d(30)\n", PPC_LD_OP, (int)sizeof (gpointer));
944         /* Load generic trampoline address */
945         fprintf (acfg->fp, "lis 11, %d@h\n", (int)(offset * sizeof (gpointer)));
946         fprintf (acfg->fp, "ori 11, 11, %d@l\n", (int)(offset * sizeof (gpointer)));
947         fprintf (acfg->fp, "%s 11, 11, 0\n", PPC_LDX_OP);
948 #ifdef PPC_USES_FUNCTION_DESCRIPTOR
949         fprintf (acfg->fp, "%s 11, 0(11)\n", PPC_LD_OP);
950 #endif
951         fprintf (acfg->fp, "mtctr 11\n");
952         /* Load trampoline argument */
953         /* On ppc, we pass it normally to the generic trampoline */
954         fprintf (acfg->fp, "lis 11, %d@h\n", (int)((offset + 1) * sizeof (gpointer)));
955         fprintf (acfg->fp, "ori 11, 11, %d@l\n", (int)((offset + 1) * sizeof (gpointer)));
956         fprintf (acfg->fp, "%s 0, 11, 0\n", PPC_LDX_OP);
957         /* Branch to generic trampoline */
958         fprintf (acfg->fp, "bctr\n");
959
960 #ifdef PPC_USES_FUNCTION_DESCRIPTOR
961         *tramp_size = 10 * 4;
962 #else
963         *tramp_size = 9 * 4;
964 #endif
965 #elif defined(TARGET_X86)
966         guint8 buf [128];
967         guint8 *code;
968
969         /* Similar to the PPC code above */
970
971         /* FIXME: Could this clobber the register needed by get_vcall_slot () ? */
972
973         /* We clobber ECX, since EAX is used as MONO_ARCH_MONITOR_OBJECT_REG */
974 #ifdef MONO_ARCH_MONITOR_OBJECT_REG
975         g_assert (MONO_ARCH_MONITOR_OBJECT_REG != X86_ECX);
976 #endif
977
978         code = buf;
979         /* Load mscorlib got address */
980         x86_mov_reg_membase (code, X86_ECX, MONO_ARCH_GOT_REG, sizeof (gpointer), 4);
981         /* Push trampoline argument */
982         x86_push_membase (code, X86_ECX, (offset + 1) * sizeof (gpointer));
983         /* Load generic trampoline address */
984         x86_mov_reg_membase (code, X86_ECX, X86_ECX, offset * sizeof (gpointer), 4);
985         /* Branch to generic trampoline */
986         x86_jump_reg (code, X86_ECX);
987
988 #ifdef __native_client_codegen__
989         {
990                 /* emit nops to next 32 byte alignment */
991                 int a = (~kNaClAlignmentMask) & ((code - buf) + kNaClAlignment - 1);
992                 while (code < (buf + a)) x86_nop(code);
993         }
994 #endif
995         emit_bytes (acfg, buf, code - buf);
996
997         *tramp_size = NACL_SIZE(17, kNaClAlignment);
998         g_assert (code - buf == *tramp_size);
999 #else
1000         g_assert_not_reached ();
1001 #endif
1002 }
1003
1004 /*
1005  * arch_emit_unbox_trampoline:
1006  *
1007  *   Emit code for the unbox trampoline for METHOD used in the full-aot case.
1008  * CALL_TARGET is the symbol pointing to the native code of METHOD.
1009  */
1010 static void
1011 arch_emit_unbox_trampoline (MonoAotCompile *acfg, MonoMethod *method, const char *call_target)
1012 {
1013 #if defined(TARGET_AMD64)
1014         guint8 buf [32];
1015         guint8 *code;
1016         int this_reg;
1017
1018         this_reg = mono_arch_get_this_arg_reg (NULL);
1019         code = buf;
1020         amd64_alu_reg_imm (code, X86_ADD, this_reg, sizeof (MonoObject));
1021
1022         emit_bytes (acfg, buf, code - buf);
1023         /* jump <method> */
1024         emit_byte (acfg, '\xe9');
1025         emit_symbol_diff (acfg, call_target, ".", -4);
1026 #elif defined(TARGET_X86)
1027         guint8 buf [32];
1028         guint8 *code;
1029         int this_pos = 4;
1030
1031         code = buf;
1032
1033         x86_alu_membase_imm (code, X86_ADD, X86_ESP, this_pos, sizeof (MonoObject));
1034
1035         emit_bytes (acfg, buf, code - buf);
1036
1037         /* jump <method> */
1038         emit_byte (acfg, '\xe9');
1039         emit_symbol_diff (acfg, call_target, ".", -4);
1040 #elif defined(TARGET_ARM)
1041         guint8 buf [128];
1042         guint8 *code;
1043
1044         code = buf;
1045
1046         ARM_ADD_REG_IMM8 (code, ARMREG_R0, ARMREG_R0, sizeof (MonoObject));
1047
1048         emit_bytes (acfg, buf, code - buf);
1049         /* jump to method */
1050         if (acfg->use_bin_writer) {
1051                 guint8 buf [4];
1052                 guint8 *code;
1053
1054                 code = buf;
1055                 ARM_B (code, 0);
1056
1057                 img_writer_emit_reloc (acfg->w, R_ARM_JUMP24, call_target, -8);
1058                 emit_bytes (acfg, buf, 4);
1059         } else {
1060                 fprintf (acfg->fp, "\n\tb %s\n", call_target);
1061         }
1062 #elif defined(TARGET_POWERPC)
1063         int this_pos = 3;
1064
1065         g_assert (!acfg->use_bin_writer);
1066
1067         fprintf (acfg->fp, "\n\taddi %d, %d, %d\n", this_pos, this_pos, (int)sizeof (MonoObject));
1068         fprintf (acfg->fp, "\n\tb %s\n", call_target);
1069 #else
1070         g_assert_not_reached ();
1071 #endif
1072 }
1073
1074 /*
1075  * arch_emit_static_rgctx_trampoline:
1076  *
1077  *   Emit code for a static rgctx trampoline. OFFSET is the offset of the first of
1078  * two GOT slots which contain the rgctx argument, and the method to jump to.
1079  * TRAMP_SIZE is set to the size of the emitted trampoline.
1080  * These kinds of trampolines cannot be enumerated statically, since there could
1081  * be one trampoline per method instantiation, so we emit the same code for all
1082  * trampolines, and parameterize them using two GOT slots.
1083  */
1084 static void
1085 arch_emit_static_rgctx_trampoline (MonoAotCompile *acfg, int offset, int *tramp_size)
1086 {
1087 #if defined(TARGET_AMD64)
1088 #if defined(__default_codegen__)
1089         /* This should be exactly 13 bytes long */
1090         *tramp_size = 13;
1091
1092         /* mov <OFFSET>(%rip), %r10 */
1093         emit_byte (acfg, '\x4d');
1094         emit_byte (acfg, '\x8b');
1095         emit_byte (acfg, '\x15');
1096         emit_symbol_diff (acfg, acfg->got_symbol, ".", (offset * sizeof (gpointer)) - 4);
1097
1098         /* jmp *<offset>(%rip) */
1099         emit_byte (acfg, '\xff');
1100         emit_byte (acfg, '\x25');
1101         emit_symbol_diff (acfg, acfg->got_symbol, ".", ((offset + 1) * sizeof (gpointer)) - 4);
1102 #elif defined(__native_client_codegen__)
1103         guint8 buf [128];
1104         guint8 *buf_aligned = ALIGN_TO(buf, kNaClAlignment);
1105         guint8 *code = buf_aligned;
1106
1107         /* mov <OFFSET>(%rip), %r10d */
1108         emit_byte (acfg, '\x45');
1109         emit_byte (acfg, '\x8b');
1110         emit_byte (acfg, '\x15');
1111         emit_symbol_diff (acfg, acfg->got_symbol, ".", (offset * sizeof (gpointer)) - 4);
1112
1113         /* mov <OFFSET>(%rip), %r11d */
1114         emit_byte (acfg, '\x45');
1115         emit_byte (acfg, '\x8b');
1116         emit_byte (acfg, '\x1d');
1117         emit_symbol_diff (acfg, acfg->got_symbol, ".", ((offset + 1) * sizeof (gpointer)) - 4);
1118
1119         /* nacljmp *%r11 */
1120         amd64_jump_reg (code, AMD64_R11);
1121         emit_bytes (acfg, buf_aligned, code - buf_aligned);
1122
1123         emit_alignment (acfg, kNaClAlignment);
1124         *tramp_size = kNaClAlignment;
1125 #endif /*__native_client_codegen__*/
1126
1127 #elif defined(TARGET_ARM)
1128         guint8 buf [128];
1129         guint8 *code;
1130
1131         /* This should be exactly 24 bytes long */
1132         *tramp_size = 24;
1133         code = buf;
1134         /* Load rgctx value */
1135         ARM_LDR_IMM (code, ARMREG_IP, ARMREG_PC, 8);
1136         ARM_LDR_REG_REG (code, MONO_ARCH_RGCTX_REG, ARMREG_PC, ARMREG_IP);
1137         /* Load branch addr + branch */
1138         ARM_LDR_IMM (code, ARMREG_IP, ARMREG_PC, 4);
1139         ARM_LDR_REG_REG (code, ARMREG_PC, ARMREG_PC, ARMREG_IP);
1140
1141         g_assert (code - buf == 16);
1142
1143         /* Emit it */
1144         emit_bytes (acfg, buf, code - buf);
1145         emit_symbol_diff (acfg, acfg->got_symbol, ".", (offset * sizeof (gpointer)) - 4 + 8);
1146         emit_symbol_diff (acfg, acfg->got_symbol, ".", ((offset + 1) * sizeof (gpointer)) - 4 + 4);
1147 #elif defined(TARGET_POWERPC)
1148         guint8 buf [128];
1149         guint8 *code;
1150
1151         *tramp_size = 4;
1152         code = buf;
1153
1154         g_assert (!acfg->use_bin_writer);
1155
1156         /*
1157          * PPC has no ip relative addressing, so we need to compute the address
1158          * of the mscorlib got. That is slow and complex, so instead, we store it
1159          * in the second got slot of every aot image. The caller already computed
1160          * the address of its got and placed it into r30.
1161          */
1162         img_writer_emit_unset_mode (acfg->w);
1163         /* Load mscorlib got address */
1164         fprintf (acfg->fp, "%s 0, %d(30)\n", PPC_LD_OP, (int)sizeof (gpointer));
1165         /* Load rgctx */
1166         fprintf (acfg->fp, "lis 11, %d@h\n", (int)(offset * sizeof (gpointer)));
1167         fprintf (acfg->fp, "ori 11, 11, %d@l\n", (int)(offset * sizeof (gpointer)));
1168         fprintf (acfg->fp, "%s %d, 11, 0\n", PPC_LDX_OP, MONO_ARCH_RGCTX_REG);
1169         /* Load target address */
1170         fprintf (acfg->fp, "lis 11, %d@h\n", (int)((offset + 1) * sizeof (gpointer)));
1171         fprintf (acfg->fp, "ori 11, 11, %d@l\n", (int)((offset + 1) * sizeof (gpointer)));
1172         fprintf (acfg->fp, "%s 11, 11, 0\n", PPC_LDX_OP);
1173 #ifdef PPC_USES_FUNCTION_DESCRIPTOR
1174         fprintf (acfg->fp, "%s 2, %d(11)\n", PPC_LD_OP, (int)sizeof (gpointer));
1175         fprintf (acfg->fp, "%s 11, 0(11)\n", PPC_LD_OP);
1176 #endif
1177         fprintf (acfg->fp, "mtctr 11\n");
1178         /* Branch to the target address */
1179         fprintf (acfg->fp, "bctr\n");
1180
1181 #ifdef PPC_USES_FUNCTION_DESCRIPTOR
1182         *tramp_size = 11 * 4;
1183 #else
1184         *tramp_size = 9 * 4;
1185 #endif
1186
1187 #elif defined(TARGET_X86)
1188         guint8 buf [128];
1189         guint8 *code;
1190
1191         /* Similar to the PPC code above */
1192
1193         g_assert (MONO_ARCH_RGCTX_REG != X86_ECX);
1194
1195         code = buf;
1196         /* Load mscorlib got address */
1197         x86_mov_reg_membase (code, X86_ECX, MONO_ARCH_GOT_REG, sizeof (gpointer), 4);
1198         /* Load arg */
1199         x86_mov_reg_membase (code, MONO_ARCH_RGCTX_REG, X86_ECX, offset * sizeof (gpointer), 4);
1200         /* Branch to the target address */
1201         x86_jump_membase (code, X86_ECX, (offset + 1) * sizeof (gpointer));
1202
1203 #ifdef __native_client_codegen__
1204         {
1205                 /* emit nops to next 32 byte alignment */
1206                 int a = (~kNaClAlignmentMask) & ((code - buf) + kNaClAlignment - 1);
1207                 while (code < (buf + a)) x86_nop(code);
1208         }
1209 #endif
1210
1211         emit_bytes (acfg, buf, code - buf);
1212
1213         *tramp_size = NACL_SIZE (15, kNaClAlignment);
1214         g_assert (code - buf == *tramp_size);
1215 #else
1216         g_assert_not_reached ();
1217 #endif
1218 }       
1219
1220 /*
1221  * arch_emit_imt_thunk:
1222  *
1223  *   Emit an IMT thunk usable in full-aot mode. The thunk uses 1 got slot which
1224  * points to an array of pointer pairs. The pairs of the form [key, ptr], where
1225  * key is the IMT key, and ptr holds the address of a memory location holding
1226  * the address to branch to if the IMT arg matches the key. The array is 
1227  * terminated by a pair whose key is NULL, and whose ptr is the address of the 
1228  * fail_tramp.
1229  * TRAMP_SIZE is set to the size of the emitted trampoline.
1230  */
1231 static void
1232 arch_emit_imt_thunk (MonoAotCompile *acfg, int offset, int *tramp_size)
1233 {
1234 #if defined(TARGET_AMD64)
1235         guint8 *buf, *code;
1236 #if defined(__native_client_codegen__)
1237         guint8 *buf_alloc;
1238 #endif
1239         guint8 *labels [3];
1240         guint8 mov_buf[3];
1241         guint8 *mov_buf_ptr = mov_buf;
1242
1243         const int kSizeOfMove = 7;
1244 #if defined(__default_codegen__)
1245         code = buf = g_malloc (256);
1246 #elif defined(__native_client_codegen__)
1247         buf_alloc = g_malloc (256 + kNaClAlignment + kSizeOfMove);
1248         buf = ((guint)buf_alloc + kNaClAlignment) & ~kNaClAlignmentMask;
1249         /* The RIP relative move below is emitted first */
1250         buf += kSizeOfMove;
1251         code = buf;
1252 #endif
1253
1254         /* FIXME: Optimize this, i.e. use binary search etc. */
1255         /* Maybe move the body into a separate function (slower, but much smaller) */
1256
1257         /* MONO_ARCH_IMT_SCRATCH_REG is a free register */
1258
1259         labels [0] = code;
1260         amd64_alu_membase_imm (code, X86_CMP, MONO_ARCH_IMT_SCRATCH_REG, 0, 0);
1261         labels [1] = code;
1262         amd64_branch8 (code, X86_CC_Z, 0, FALSE);
1263
1264         /* Check key */
1265         amd64_alu_membase_reg_size (code, X86_CMP, MONO_ARCH_IMT_SCRATCH_REG, 0, MONO_ARCH_IMT_REG, sizeof (gpointer));
1266         labels [2] = code;
1267         amd64_branch8 (code, X86_CC_Z, 0, FALSE);
1268
1269         /* Loop footer */
1270         amd64_alu_reg_imm (code, X86_ADD, MONO_ARCH_IMT_SCRATCH_REG, 2 * sizeof (gpointer));
1271         amd64_jump_code (code, labels [0]);
1272
1273         /* Match */
1274         mono_amd64_patch (labels [2], code);
1275         amd64_mov_reg_membase (code, MONO_ARCH_IMT_SCRATCH_REG, MONO_ARCH_IMT_SCRATCH_REG, sizeof (gpointer), sizeof (gpointer));
1276         amd64_jump_membase (code, MONO_ARCH_IMT_SCRATCH_REG, 0);
1277
1278         /* No match */
1279         /* FIXME: */
1280         mono_amd64_patch (labels [1], code);
1281         x86_breakpoint (code);
1282
1283         /* mov <OFFSET>(%rip), MONO_ARCH_IMT_SCRATCH_REG */
1284         amd64_emit_rex (mov_buf_ptr, sizeof(gpointer), MONO_ARCH_IMT_SCRATCH_REG, 0, AMD64_RIP);
1285         *(mov_buf_ptr)++ = (unsigned char)0x8b; /* mov opcode */
1286         x86_address_byte (mov_buf_ptr, 0, MONO_ARCH_IMT_SCRATCH_REG & 0x7, 5);
1287         emit_bytes (acfg, mov_buf, mov_buf_ptr - mov_buf);
1288         emit_symbol_diff (acfg, acfg->got_symbol, ".", (offset * sizeof (gpointer)) - 4);
1289
1290         emit_bytes (acfg, buf, code - buf);
1291         
1292         *tramp_size = code - buf + kSizeOfMove;
1293 #if defined(__native_client_codegen__)
1294         /* The tramp will be padded to the next kNaClAlignment bundle. */
1295         *tramp_size = ALIGN_TO ((*tramp_size), kNaClAlignment);
1296 #endif
1297
1298 #if defined(__default_codegen__)
1299         g_free (buf);
1300 #elif defined(__native_client_codegen__)
1301         g_free (buf_alloc); 
1302 #endif
1303
1304 #elif defined(TARGET_X86)
1305         guint8 *buf, *code;
1306 #ifdef __native_client_codegen__
1307         guint8 *buf_alloc;
1308 #endif
1309         guint8 *labels [3];
1310
1311 #if defined(__default_codegen__)
1312         code = buf = g_malloc (256);
1313 #elif defined(__native_client_codegen__)
1314         buf_alloc = g_malloc (256 + kNaClAlignment);
1315         code = buf = ((guint)buf_alloc + kNaClAlignment) & ~kNaClAlignmentMask;
1316 #endif
1317
1318         /* Allocate a temporary stack slot */
1319         x86_push_reg (code, X86_EAX);
1320         /* Save EAX */
1321         x86_push_reg (code, X86_EAX);
1322
1323         /* Load mscorlib got address */
1324         x86_mov_reg_membase (code, X86_EAX, MONO_ARCH_GOT_REG, sizeof (gpointer), 4);
1325         /* Load arg */
1326         x86_mov_reg_membase (code, X86_EAX, X86_EAX, offset * sizeof (gpointer), 4);
1327
1328         labels [0] = code;
1329         x86_alu_membase_imm (code, X86_CMP, X86_EAX, 0, 0);
1330         labels [1] = code;
1331         x86_branch8 (code, X86_CC_Z, FALSE, 0);
1332
1333         /* Check key */
1334         x86_alu_membase_reg (code, X86_CMP, X86_EAX, 0, MONO_ARCH_IMT_REG);
1335         labels [2] = code;
1336         x86_branch8 (code, X86_CC_Z, FALSE, 0);
1337
1338         /* Loop footer */
1339         x86_alu_reg_imm (code, X86_ADD, X86_EAX, 2 * sizeof (gpointer));
1340         x86_jump_code (code, labels [0]);
1341
1342         /* Match */
1343         mono_x86_patch (labels [2], code);
1344         x86_mov_reg_membase (code, X86_EAX, X86_EAX, sizeof (gpointer), 4);
1345         x86_mov_reg_membase (code, X86_EAX, X86_EAX, 0, 4);
1346         /* Save the target address to the temporary stack location */
1347         x86_mov_membase_reg (code, X86_ESP, 4, X86_EAX, 4);
1348         /* Restore EAX */
1349         x86_pop_reg (code, X86_EAX);
1350         /* Jump to the target address */
1351         x86_ret (code);
1352
1353         /* No match */
1354         /* FIXME: */
1355         mono_x86_patch (labels [1], code);
1356         x86_breakpoint (code);
1357
1358 #ifdef __native_client_codegen__
1359         {
1360                 /* emit nops to next 32 byte alignment */
1361                 int a = (~kNaClAlignmentMask) & ((code - buf) + kNaClAlignment - 1);
1362                 while (code < (buf + a)) x86_nop(code);
1363         }
1364 #endif
1365         emit_bytes (acfg, buf, code - buf);
1366         
1367         *tramp_size = code - buf;
1368
1369 #if defined(__default_codegen__)
1370         g_free (buf);
1371 #elif defined(__native_client_codegen__)
1372         g_free (buf_alloc); 
1373 #endif
1374
1375 #elif defined(TARGET_ARM)
1376         guint8 buf [128];
1377         guint8 *code, *code2, *labels [16];
1378
1379         code = buf;
1380
1381         /* The IMT method is in v5 */
1382
1383         /* Need at least two free registers, plus a slot for storing the pc */
1384         ARM_PUSH (code, (1 << ARMREG_R0)|(1 << ARMREG_R1)|(1 << ARMREG_R2));
1385         labels [0] = code;
1386         /* Load the parameter from the GOT */
1387         ARM_LDR_IMM (code, ARMREG_R0, ARMREG_PC, 0);
1388         ARM_LDR_REG_REG (code, ARMREG_R0, ARMREG_PC, ARMREG_R0);
1389
1390         labels [1] = code;
1391         ARM_LDR_IMM (code, ARMREG_R1, ARMREG_R0, 0);
1392         ARM_CMP_REG_REG (code, ARMREG_R1, ARMREG_V5);
1393         labels [2] = code;
1394         ARM_B_COND (code, ARMCOND_EQ, 0);
1395
1396         /* End-of-loop check */
1397         ARM_CMP_REG_IMM (code, ARMREG_R1, 0, 0);
1398         labels [3] = code;
1399         ARM_B_COND (code, ARMCOND_EQ, 0);
1400
1401         /* Loop footer */
1402         ARM_ADD_REG_IMM8 (code, ARMREG_R0, ARMREG_R0, sizeof (gpointer) * 2);
1403         labels [4] = code;
1404         ARM_B (code, 0);
1405         arm_patch (labels [4], labels [1]);
1406
1407         /* Match */
1408         arm_patch (labels [2], code);
1409         ARM_LDR_IMM (code, ARMREG_R0, ARMREG_R0, 4);
1410         ARM_LDR_IMM (code, ARMREG_R0, ARMREG_R0, 0);
1411         /* Save it to the third stack slot */
1412         ARM_STR_IMM (code, ARMREG_R0, ARMREG_SP, 8);
1413         /* Restore the registers and branch */
1414         ARM_POP (code, (1 << ARMREG_R0)|(1 << ARMREG_R1)|(1 << ARMREG_PC));
1415
1416         /* No match */
1417         arm_patch (labels [3], code);
1418         ARM_DBRK (code);
1419
1420         /* Fixup offset */
1421         code2 = labels [0];
1422         ARM_LDR_IMM (code2, ARMREG_R0, ARMREG_PC, (code - (labels [0] + 8)));
1423
1424         emit_bytes (acfg, buf, code - buf);
1425         emit_symbol_diff (acfg, acfg->got_symbol, ".", (offset * sizeof (gpointer)) + (code - (labels [0] + 8)) - 4);
1426
1427         *tramp_size = code - buf + 4;
1428 #elif defined(TARGET_POWERPC)
1429         guint8 buf [128];
1430         guint8 *code, *labels [16];
1431
1432         code = buf;
1433
1434         /* Load the mscorlib got address */
1435         ppc_ldptr (code, ppc_r11, sizeof (gpointer), ppc_r30);
1436         /* Load the parameter from the GOT */
1437         ppc_load (code, ppc_r0, offset * sizeof (gpointer));
1438         ppc_ldptr_indexed (code, ppc_r11, ppc_r11, ppc_r0);
1439
1440         /* Load and check key */
1441         labels [1] = code;
1442         ppc_ldptr (code, ppc_r0, 0, ppc_r11);
1443         ppc_cmp (code, 0, sizeof (gpointer) == 8 ? 1 : 0, ppc_r0, MONO_ARCH_IMT_REG);
1444         labels [2] = code;
1445         ppc_bc (code, PPC_BR_TRUE, PPC_BR_EQ, 0);
1446
1447         /* End-of-loop check */
1448         ppc_cmpi (code, 0, sizeof (gpointer) == 8 ? 1 : 0, ppc_r0, 0);
1449         labels [3] = code;
1450         ppc_bc (code, PPC_BR_TRUE, PPC_BR_EQ, 0);
1451
1452         /* Loop footer */
1453         ppc_addi (code, ppc_r11, ppc_r11, 2 * sizeof (gpointer));
1454         labels [4] = code;
1455         ppc_b (code, 0);
1456         mono_ppc_patch (labels [4], labels [1]);
1457
1458         /* Match */
1459         mono_ppc_patch (labels [2], code);
1460         ppc_ldptr (code, ppc_r11, sizeof (gpointer), ppc_r11);
1461         /* r11 now contains the value of the vtable slot */
1462         /* this is not a function descriptor on ppc64 */
1463         ppc_ldptr (code, ppc_r11, 0, ppc_r11);
1464         ppc_mtctr (code, ppc_r11);
1465         ppc_bcctr (code, PPC_BR_ALWAYS, 0);
1466
1467         /* Fail */
1468         mono_ppc_patch (labels [3], code);
1469         /* FIXME: */
1470         ppc_break (code);
1471
1472         *tramp_size = code - buf;
1473
1474         emit_bytes (acfg, buf, code - buf);
1475 #else
1476         g_assert_not_reached ();
1477 #endif
1478 }
1479
1480 static void
1481 arch_emit_autoreg (MonoAotCompile *acfg, char *symbol)
1482 {
1483 #if defined(TARGET_POWERPC) && defined(__mono_ilp32__)
1484         /* Based on code generated by gcc */
1485         img_writer_emit_unset_mode (acfg->w);
1486
1487         fprintf (acfg->fp,
1488 #if defined(_MSC_VER) || defined(MONO_CROSS_COMPILE) 
1489                          ".section      .ctors,\"aw\",@progbits\n"
1490                          ".align 2\n"
1491                          ".globl        %s\n"
1492                          ".long %s\n"
1493                          ".section      .opd,\"aw\"\n"
1494                          ".align 2\n"
1495                          "%s:\n"
1496                          ".long .%s,.TOC.@tocbase32\n"
1497                          ".size %s,.-%s\n"
1498                          ".section .text\n"
1499                          ".type .%s,@function\n"
1500                          ".align 2\n"
1501                          ".%s:\n", symbol, symbol, symbol, symbol, symbol, symbol, symbol, symbol);
1502 #else
1503                          ".section      .ctors,\"aw\",@progbits\n"
1504                          ".align 2\n"
1505                          ".globl        %1$s\n"
1506                          ".long %1$s\n"
1507                          ".section      .opd,\"aw\"\n"
1508                          ".align 2\n"
1509                          "%1$s:\n"
1510                          ".long .%1$s,.TOC.@tocbase32\n"
1511                          ".size %1$s,.-%1$s\n"
1512                          ".section .text\n"
1513                          ".type .%1$s,@function\n"
1514                          ".align 2\n"
1515                          ".%1$s:\n", symbol);
1516 #endif
1517
1518
1519         fprintf (acfg->fp,
1520                          "stdu 1,-128(1)\n"
1521                          "mflr 0\n"
1522                          "std 31,120(1)\n"
1523                          "std 0,144(1)\n"
1524
1525                          ".Lautoreg:\n"
1526                          "lis 3, .Lglobals@h\n"
1527                          "ori 3, 3, .Lglobals@l\n"
1528                          "bl .mono_aot_register_module\n"
1529                          "ld 11,0(1)\n"
1530                          "ld 0,16(11)\n"
1531                          "mtlr 0\n"
1532                          "ld 31,-8(11)\n"
1533                          "mr 1,11\n"
1534                          "blr\n"
1535                          );
1536 #if defined(_MSC_VER) || defined(MONO_CROSS_COMPILE) 
1537                 fprintf (acfg->fp,
1538                          ".size .%s,.-.%s\n", symbol, symbol);
1539 #else
1540         fprintf (acfg->fp,
1541                          ".size .%1$s,.-.%1$s\n", symbol);
1542 #endif
1543 #else
1544 #endif
1545 }
1546
1547 /* END OF ARCH SPECIFIC CODE */
1548
1549 static guint32
1550 mono_get_field_token (MonoClassField *field) 
1551 {
1552         MonoClass *klass = field->parent;
1553         int i;
1554
1555         for (i = 0; i < klass->field.count; ++i) {
1556                 if (field == &klass->fields [i])
1557                         return MONO_TOKEN_FIELD_DEF | (klass->field.first + 1 + i);
1558         }
1559
1560         g_assert_not_reached ();
1561         return 0;
1562 }
1563
1564 static inline void
1565 encode_value (gint32 value, guint8 *buf, guint8 **endbuf)
1566 {
1567         guint8 *p = buf;
1568
1569         //printf ("ENCODE: %d 0x%x.\n", value, value);
1570
1571         /* 
1572          * Same encoding as the one used in the metadata, extended to handle values
1573          * greater than 0x1fffffff.
1574          */
1575         if ((value >= 0) && (value <= 127))
1576                 *p++ = value;
1577         else if ((value >= 0) && (value <= 16383)) {
1578                 p [0] = 0x80 | (value >> 8);
1579                 p [1] = value & 0xff;
1580                 p += 2;
1581         } else if ((value >= 0) && (value <= 0x1fffffff)) {
1582                 p [0] = (value >> 24) | 0xc0;
1583                 p [1] = (value >> 16) & 0xff;
1584                 p [2] = (value >> 8) & 0xff;
1585                 p [3] = value & 0xff;
1586                 p += 4;
1587         }
1588         else {
1589                 p [0] = 0xff;
1590                 p [1] = (value >> 24) & 0xff;
1591                 p [2] = (value >> 16) & 0xff;
1592                 p [3] = (value >> 8) & 0xff;
1593                 p [4] = value & 0xff;
1594                 p += 5;
1595         }
1596         if (endbuf)
1597                 *endbuf = p;
1598 }
1599
1600 static void
1601 stream_init (MonoDynamicStream *sh)
1602 {
1603         sh->index = 0;
1604         sh->alloc_size = 4096;
1605         sh->data = g_malloc (4096);
1606
1607         /* So offsets are > 0 */
1608         sh->data [0] = 0;
1609         sh->index ++;
1610 }
1611
1612 static void
1613 make_room_in_stream (MonoDynamicStream *stream, int size)
1614 {
1615         if (size <= stream->alloc_size)
1616                 return;
1617         
1618         while (stream->alloc_size <= size) {
1619                 if (stream->alloc_size < 4096)
1620                         stream->alloc_size = 4096;
1621                 else
1622                         stream->alloc_size *= 2;
1623         }
1624         
1625         stream->data = g_realloc (stream->data, stream->alloc_size);
1626 }
1627
1628 static guint32
1629 add_stream_data (MonoDynamicStream *stream, const char *data, guint32 len)
1630 {
1631         guint32 idx;
1632         
1633         make_room_in_stream (stream, stream->index + len);
1634         memcpy (stream->data + stream->index, data, len);
1635         idx = stream->index;
1636         stream->index += len;
1637         return idx;
1638 }
1639
1640 /*
1641  * add_to_blob:
1642  *
1643  *   Add data to the binary blob inside the aot image. Returns the offset inside the
1644  * blob where the data was stored.
1645  */
1646 static guint32
1647 add_to_blob (MonoAotCompile *acfg, const guint8 *data, guint32 data_len)
1648 {
1649         if (acfg->blob.alloc_size == 0)
1650                 stream_init (&acfg->blob);
1651
1652         return add_stream_data (&acfg->blob, (char*)data, data_len);
1653 }
1654
1655 static guint32
1656 add_to_blob_aligned (MonoAotCompile *acfg, const guint8 *data, guint32 data_len, guint32 align)
1657 {
1658         char buf [4] = {0};
1659         guint32 count;
1660
1661         if (acfg->blob.alloc_size == 0)
1662                 stream_init (&acfg->blob);
1663
1664         count = acfg->blob.index % align;
1665
1666         /* we assume the stream data will be aligned */
1667         if (count)
1668                 add_stream_data (&acfg->blob, buf, 4 - count);
1669
1670         return add_stream_data (&acfg->blob, (char*)data, data_len);
1671 }
1672
1673 /*
1674  * emit_offset_table:
1675  *
1676  *   Emit a table of increasing offsets in a compact form using differential encoding.
1677  * There is an index entry for each GROUP_SIZE number of entries. The greater the
1678  * group size, the more compact the table becomes, but the slower it becomes to compute
1679  * a given entry. Returns the size of the table.
1680  */
1681 static guint32
1682 emit_offset_table (MonoAotCompile *acfg, int noffsets, int group_size, gint32 *offsets)
1683 {
1684         gint32 current_offset;
1685         int i, buf_size, ngroups, index_entry_size;
1686         guint8 *p, *buf;
1687         guint32 *index_offsets;
1688
1689         ngroups = (noffsets + (group_size - 1)) / group_size;
1690
1691         index_offsets = g_new0 (guint32, ngroups);
1692
1693         buf_size = noffsets * 4;
1694         p = buf = g_malloc0 (buf_size);
1695
1696         current_offset = 0;
1697         for (i = 0; i < noffsets; ++i) {
1698                 //printf ("D: %d -> %d\n", i, offsets [i]);
1699                 if ((i % group_size) == 0) {
1700                         index_offsets [i / group_size] = p - buf;
1701                         /* Emit the full value for these entries */
1702                         encode_value (offsets [i], p, &p);
1703                 } else {
1704                         /* The offsets are allowed to be non-increasing */
1705                         //g_assert (offsets [i] >= current_offset);
1706                         encode_value (offsets [i] - current_offset, p, &p);
1707                 }
1708                 current_offset = offsets [i];
1709         }
1710
1711         if (ngroups && index_offsets [ngroups - 1] < 65000)
1712                 index_entry_size = 2;
1713         else
1714                 index_entry_size = 4;
1715
1716         /* Emit the header */
1717         emit_int32 (acfg, noffsets);
1718         emit_int32 (acfg, group_size);
1719         emit_int32 (acfg, ngroups);
1720         emit_int32 (acfg, index_entry_size);
1721
1722         /* Emit the index */
1723         for (i = 0; i < ngroups; ++i) {
1724                 if (index_entry_size == 2)
1725                         emit_int16 (acfg, index_offsets [i]);
1726                 else
1727                         emit_int32 (acfg, index_offsets [i]);
1728         }
1729
1730         /* Emit the data */
1731         emit_bytes (acfg, buf, p - buf);
1732
1733     return (int)(p - buf) + (ngroups * 4);
1734 }
1735
1736 static guint32
1737 get_image_index (MonoAotCompile *cfg, MonoImage *image)
1738 {
1739         guint32 index;
1740
1741         index = GPOINTER_TO_UINT (g_hash_table_lookup (cfg->image_hash, image));
1742         if (index)
1743                 return index - 1;
1744         else {
1745                 index = g_hash_table_size (cfg->image_hash);
1746                 g_hash_table_insert (cfg->image_hash, image, GUINT_TO_POINTER (index + 1));
1747                 g_ptr_array_add (cfg->image_table, image);
1748                 return index;
1749         }
1750 }
1751
1752 static guint32
1753 find_typespec_for_class (MonoAotCompile *acfg, MonoClass *klass)
1754 {
1755         int i;
1756         int len = acfg->image->tables [MONO_TABLE_TYPESPEC].rows;
1757
1758         /* FIXME: Search referenced images as well */
1759         if (!acfg->typespec_classes) {
1760                 acfg->typespec_classes = mono_mempool_alloc0 (acfg->mempool, sizeof (MonoClass*) * len);
1761                 for (i = 0; i < len; ++i) {
1762                         acfg->typespec_classes [i] = mono_class_get_full (acfg->image, MONO_TOKEN_TYPE_SPEC | (i + 1), NULL);
1763                 }
1764         }
1765         for (i = 0; i < len; ++i) {
1766                 if (acfg->typespec_classes [i] == klass)
1767                         break;
1768         }
1769
1770         if (i < len)
1771                 return MONO_TOKEN_TYPE_SPEC | (i + 1);
1772         else
1773                 return 0;
1774 }
1775
1776 static void
1777 encode_method_ref (MonoAotCompile *acfg, MonoMethod *method, guint8 *buf, guint8 **endbuf);
1778
1779 /*
1780  * encode_klass_ref:
1781  *
1782  *   Encode a reference to KLASS. We use our home-grown encoding instead of the
1783  * standard metadata encoding.
1784  */
1785 static void
1786 encode_klass_ref (MonoAotCompile *acfg, MonoClass *klass, guint8 *buf, guint8 **endbuf)
1787 {
1788         guint8 *p = buf;
1789
1790         if (klass->generic_class) {
1791                 guint32 token;
1792                 g_assert (klass->type_token);
1793
1794                 /* Find a typespec for a class if possible */
1795                 token = find_typespec_for_class (acfg, klass);
1796                 if (token) {
1797                         encode_value (token, p, &p);
1798                         encode_value (get_image_index (acfg, acfg->image), p, &p);
1799                 } else {
1800                         MonoClass *gclass = klass->generic_class->container_class;
1801                         MonoGenericInst *inst = klass->generic_class->context.class_inst;
1802                         int i;
1803
1804                         /* Encode it ourselves */
1805                         /* Marker */
1806                         encode_value (MONO_TOKEN_TYPE_SPEC, p, &p);
1807                         encode_value (MONO_TYPE_GENERICINST, p, &p);
1808                         encode_klass_ref (acfg, gclass, p, &p);
1809                         encode_value (inst->type_argc, p, &p);
1810                         for (i = 0; i < inst->type_argc; ++i)
1811                                 encode_klass_ref (acfg, mono_class_from_mono_type (inst->type_argv [i]), p, &p);
1812                 }
1813         } else if (klass->type_token) {
1814                 g_assert (mono_metadata_token_code (klass->type_token) == MONO_TOKEN_TYPE_DEF);
1815                 encode_value (klass->type_token - MONO_TOKEN_TYPE_DEF, p, &p);
1816                 encode_value (get_image_index (acfg, klass->image), p, &p);
1817         } else if ((klass->byval_arg.type == MONO_TYPE_VAR) || (klass->byval_arg.type == MONO_TYPE_MVAR)) {
1818                 MonoGenericContainer *container = mono_type_get_generic_param_owner (&klass->byval_arg);
1819                 g_assert (container);
1820
1821                 /* Marker */
1822                 encode_value (MONO_TOKEN_TYPE_SPEC, p, &p);
1823                 encode_value (klass->byval_arg.type, p, &p);
1824
1825                 encode_value (mono_type_get_generic_param_num (&klass->byval_arg), p, &p);
1826                 
1827                 encode_value (container->is_method, p, &p);
1828                 if (container->is_method)
1829                         encode_method_ref (acfg, container->owner.method, p, &p);
1830                 else
1831                         encode_klass_ref (acfg, container->owner.klass, p, &p);
1832         } else {
1833                 /* Array class */
1834                 g_assert (klass->rank > 0);
1835                 encode_value (MONO_TOKEN_TYPE_DEF, p, &p);
1836                 encode_value (get_image_index (acfg, klass->image), p, &p);
1837                 encode_value (klass->rank, p, &p);
1838                 encode_klass_ref (acfg, klass->element_class, p, &p);
1839         }
1840         *endbuf = p;
1841 }
1842
1843 static void
1844 encode_field_info (MonoAotCompile *cfg, MonoClassField *field, guint8 *buf, guint8 **endbuf)
1845 {
1846         guint32 token = mono_get_field_token (field);
1847         guint8 *p = buf;
1848
1849         encode_klass_ref (cfg, field->parent, p, &p);
1850         g_assert (mono_metadata_token_code (token) == MONO_TOKEN_FIELD_DEF);
1851         encode_value (token - MONO_TOKEN_FIELD_DEF, p, &p);
1852         *endbuf = p;
1853 }
1854
1855 static void
1856 encode_generic_context (MonoAotCompile *acfg, MonoGenericContext *context, guint8 *buf, guint8 **endbuf)
1857 {
1858         guint8 *p = buf;
1859         int i;
1860         MonoGenericInst *inst;
1861
1862         /* Encode the context */
1863         inst = context->class_inst;
1864         encode_value (inst ? 1 : 0, p, &p);
1865         if (inst) {
1866                 encode_value (inst->type_argc, p, &p);
1867                 for (i = 0; i < inst->type_argc; ++i)
1868                         encode_klass_ref (acfg, mono_class_from_mono_type (inst->type_argv [i]), p, &p);
1869         }
1870         inst = context->method_inst;
1871         encode_value (inst ? 1 : 0, p, &p);
1872         if (inst) {
1873                 encode_value (inst->type_argc, p, &p);
1874                 for (i = 0; i < inst->type_argc; ++i)
1875                         encode_klass_ref (acfg, mono_class_from_mono_type (inst->type_argv [i]), p, &p);
1876         }
1877
1878         *endbuf = p;
1879 }
1880
1881 #define MAX_IMAGE_INDEX 250
1882
1883 static void
1884 encode_method_ref (MonoAotCompile *acfg, MonoMethod *method, guint8 *buf, guint8 **endbuf)
1885 {
1886         guint32 image_index = get_image_index (acfg, method->klass->image);
1887         guint32 token = method->token;
1888         MonoJumpInfoToken *ji;
1889         guint8 *p = buf;
1890         char *name;
1891
1892         /*
1893          * The encoding for most methods is as follows:
1894          * - image index encoded as a leb128
1895          * - token index encoded as a leb128
1896          * Values of image index >= MONO_AOT_METHODREF_MIN are used to mark additional
1897          * types of method encodings.
1898          */
1899
1900         g_assert (image_index < MONO_AOT_METHODREF_MIN);
1901
1902         /* Mark methods which can't use aot trampolines because they need the further 
1903          * processing in mono_magic_trampoline () which requires a MonoMethod*.
1904          */
1905         if ((method->is_generic && (method->flags & METHOD_ATTRIBUTE_VIRTUAL)) ||
1906                 (method->iflags & METHOD_IMPL_ATTRIBUTE_SYNCHRONIZED))
1907                 encode_value ((MONO_AOT_METHODREF_NO_AOT_TRAMPOLINE << 24), p, &p);
1908
1909         /* 
1910          * Some wrapper methods are shared using their signature, encode their 
1911          * stringified signature instead.
1912          * FIXME: Optimize disk usage
1913          */
1914         name = NULL;
1915         if (method->wrapper_type) {
1916                 if (method->wrapper_type == MONO_WRAPPER_RUNTIME_INVOKE) {
1917                         char *tmpsig = mono_signature_get_desc (mono_method_signature (method), TRUE);
1918                         if (strcmp (method->name, "runtime_invoke_dynamic")) {
1919                                 name = mono_aot_wrapper_name (method);
1920                         } else if (mono_marshal_method_from_wrapper (method) != method) {
1921                                 /* Direct wrapper, encode it normally */
1922                         } else {
1923                                 name = g_strdup_printf ("(wrapper runtime-invoke):%s (%s)", method->name, tmpsig);
1924                         }
1925                         g_free (tmpsig);
1926                 } else if (method->wrapper_type == MONO_WRAPPER_DELEGATE_INVOKE) {
1927                         char *tmpsig = mono_signature_get_desc (mono_method_signature (method), TRUE);
1928                         name = g_strdup_printf ("(wrapper delegate-invoke):%s (%s)", method->name, tmpsig);
1929                         g_free (tmpsig);
1930                 } else if (method->wrapper_type == MONO_WRAPPER_DELEGATE_BEGIN_INVOKE) {
1931                         char *tmpsig = mono_signature_get_desc (mono_method_signature (method), TRUE);
1932                         name = g_strdup_printf ("(wrapper delegate-begin-invoke):%s (%s)", method->name, tmpsig);
1933                         g_free (tmpsig);
1934                 } else if (method->wrapper_type == MONO_WRAPPER_DELEGATE_END_INVOKE) {
1935                         char *tmpsig = mono_signature_get_desc (mono_method_signature (method), TRUE);
1936                         name = g_strdup_printf ("(wrapper delegate-end-invoke):%s (%s)", method->name, tmpsig);
1937                         g_free (tmpsig);
1938                 }
1939         }
1940
1941         if (name) {
1942                 encode_value ((MONO_AOT_METHODREF_WRAPPER_NAME << 24), p, &p);
1943                 strcpy ((char*)p, name);
1944                 p += strlen (name) + 1;
1945                 g_free (name);
1946         } else if (method->wrapper_type) {
1947                 encode_value ((MONO_AOT_METHODREF_WRAPPER << 24), p, &p);
1948
1949                 encode_value (method->wrapper_type, p, &p);
1950
1951                 switch (method->wrapper_type) {
1952                 case MONO_WRAPPER_REMOTING_INVOKE:
1953                 case MONO_WRAPPER_REMOTING_INVOKE_WITH_CHECK:
1954                 case MONO_WRAPPER_XDOMAIN_INVOKE: {
1955                         MonoMethod *m;
1956
1957                         m = mono_marshal_method_from_wrapper (method);
1958                         g_assert (m);
1959                         encode_method_ref (acfg, m, p, &p);
1960                         break;
1961                 }
1962                 case MONO_WRAPPER_PROXY_ISINST:
1963                 case MONO_WRAPPER_LDFLD:
1964                 case MONO_WRAPPER_LDFLDA:
1965                 case MONO_WRAPPER_STFLD:
1966                 case MONO_WRAPPER_ISINST: {
1967                         MonoClass *proxy_class = mono_marshal_get_wrapper_info (method);
1968                         encode_klass_ref (acfg, proxy_class, p, &p);
1969                         break;
1970                 }
1971                 case MONO_WRAPPER_LDFLD_REMOTE:
1972                 case MONO_WRAPPER_STFLD_REMOTE:
1973                         break;
1974                 case MONO_WRAPPER_ALLOC: {
1975                         AllocatorWrapperInfo *info = mono_marshal_get_wrapper_info (method);
1976
1977                         /* The GC name is saved once in MonoAotFileInfo */
1978                         g_assert (info->alloc_type != -1);
1979                         encode_value (info->alloc_type, p, &p);
1980                         break;
1981                 }
1982                 case MONO_WRAPPER_WRITE_BARRIER:
1983                         break;
1984                 case MONO_WRAPPER_STELEMREF: {
1985                         MonoClass *klass = mono_marshal_get_wrapper_info (method);
1986
1987                         /* Make sure this is the 'normal' stelemref wrapper, not the virtual one */
1988                         g_assert (!klass);
1989                         break;
1990                 }
1991                 case MONO_WRAPPER_UNKNOWN:
1992                         if (strcmp (method->name, "FastMonitorEnter") == 0) {
1993                                 encode_value (MONO_AOT_WRAPPER_MONO_ENTER, p, &p);
1994                         } else if (strcmp (method->name, "FastMonitorExit") == 0) {
1995                                 encode_value (MONO_AOT_WRAPPER_MONO_EXIT, p, &p);
1996                         } else if (strcmp (method->name, "PtrToStructure") == 0) {
1997                                 encode_value (MONO_AOT_WRAPPER_PTR_TO_STRUCTURE, p, &p);
1998                                 encode_klass_ref (acfg, method->klass, p, &p);
1999                         } else if (strcmp (method->name, "StructureToPtr") == 0) {
2000                                 encode_value (MONO_AOT_WRAPPER_STRUCTURE_TO_PTR, p, &p);
2001                                 encode_klass_ref (acfg, method->klass, p, &p);
2002                         } else {
2003                                 g_assert_not_reached ();
2004                         }
2005                         break;
2006                 case MONO_WRAPPER_SYNCHRONIZED:
2007                 case MONO_WRAPPER_MANAGED_TO_NATIVE:
2008                 case MONO_WRAPPER_RUNTIME_INVOKE: {
2009                         MonoMethod *m;
2010
2011                         m = mono_marshal_method_from_wrapper (method);
2012                         g_assert (m);
2013                         g_assert (m != method);
2014                         encode_method_ref (acfg, m, p, &p);
2015                         break;
2016                 }
2017                 case MONO_WRAPPER_MANAGED_TO_MANAGED:
2018                         if (!strcmp (method->name, "ElementAddr")) {
2019                                 ElementAddrWrapperInfo *info = mono_marshal_get_wrapper_info (method);
2020
2021                                 g_assert (info);
2022                                 encode_value (MONO_AOT_WRAPPER_ELEMENT_ADDR, p, &p);
2023                                 encode_value (info->rank, p, &p);
2024                                 encode_value (info->elem_size, p, &p);
2025                         } else {
2026                                 g_assert_not_reached ();
2027                         }
2028                         break;
2029                 default:
2030                         g_assert_not_reached ();
2031                 }
2032         } else if (mono_method_signature (method)->is_inflated) {
2033                 /* 
2034                  * This is a generic method, find the original token which referenced it and
2035                  * encode that.
2036                  * Obtain the token from information recorded by the JIT.
2037                  */
2038                 ji = g_hash_table_lookup (acfg->token_info_hash, method);
2039                 if (ji) {
2040                         image_index = get_image_index (acfg, ji->image);
2041                         g_assert (image_index < MAX_IMAGE_INDEX);
2042                         token = ji->token;
2043
2044                         encode_value ((MONO_AOT_METHODREF_METHODSPEC << 24), p, &p);
2045                         encode_value (image_index, p, &p);
2046                         encode_value (token, p, &p);
2047                 } else {
2048                         MonoMethod *declaring;
2049                         MonoGenericContext *context = mono_method_get_context (method);
2050
2051                         g_assert (method->is_inflated);
2052                         declaring = ((MonoMethodInflated*)method)->declaring;
2053
2054                         /*
2055                          * This might be a non-generic method of a generic instance, which 
2056                          * doesn't have a token since the reference is generated by the JIT 
2057                          * like Nullable:Box/Unbox, or by generic sharing.
2058                          */
2059
2060                         encode_value ((MONO_AOT_METHODREF_GINST << 24), p, &p);
2061                         /* Encode the klass */
2062                         encode_klass_ref (acfg, method->klass, p, &p);
2063                         /* Encode the method */
2064                         image_index = get_image_index (acfg, method->klass->image);
2065                         g_assert (image_index < MAX_IMAGE_INDEX);
2066                         g_assert (declaring->token);
2067                         token = declaring->token;
2068                         g_assert (mono_metadata_token_table (token) == MONO_TABLE_METHOD);
2069                         encode_value (image_index, p, &p);
2070                         encode_value (token, p, &p);
2071                         encode_generic_context (acfg, context, p, &p);
2072                 }
2073         } else if (token == 0) {
2074                 /* This might be a method of a constructed type like int[,].Set */
2075                 /* Obtain the token from information recorded by the JIT */
2076                 ji = g_hash_table_lookup (acfg->token_info_hash, method);
2077                 if (ji) {
2078                         image_index = get_image_index (acfg, ji->image);
2079                         g_assert (image_index < MAX_IMAGE_INDEX);
2080                         token = ji->token;
2081
2082                         encode_value ((MONO_AOT_METHODREF_METHODSPEC << 24), p, &p);
2083                         encode_value (image_index, p, &p);
2084                         encode_value (token, p, &p);
2085                 } else {
2086                         /* Array methods */
2087                         g_assert (method->klass->rank);
2088
2089                         /* Encode directly */
2090                         encode_value ((MONO_AOT_METHODREF_ARRAY << 24), p, &p);
2091                         encode_klass_ref (acfg, method->klass, p, &p);
2092                         if (!strcmp (method->name, ".ctor") && mono_method_signature (method)->param_count == method->klass->rank)
2093                                 encode_value (0, p, &p);
2094                         else if (!strcmp (method->name, ".ctor") && mono_method_signature (method)->param_count == method->klass->rank * 2)
2095                                 encode_value (1, p, &p);
2096                         else if (!strcmp (method->name, "Get"))
2097                                 encode_value (2, p, &p);
2098                         else if (!strcmp (method->name, "Address"))
2099                                 encode_value (3, p, &p);
2100                         else if (!strcmp (method->name, "Set"))
2101                                 encode_value (4, p, &p);
2102                         else
2103                                 g_assert_not_reached ();
2104                 }
2105         } else {
2106                 g_assert (mono_metadata_token_table (token) == MONO_TABLE_METHOD);
2107                 encode_value ((image_index << 24) | mono_metadata_token_index (token), p, &p);
2108         }
2109         *endbuf = p;
2110 }
2111
2112 static gint
2113 compare_patches (gconstpointer a, gconstpointer b)
2114 {
2115         int i, j;
2116
2117         i = (*(MonoJumpInfo**)a)->ip.i;
2118         j = (*(MonoJumpInfo**)b)->ip.i;
2119
2120         if (i < j)
2121                 return -1;
2122         else
2123                 if (i > j)
2124                         return 1;
2125         else
2126                 return 0;
2127 }
2128
2129 static G_GNUC_UNUSED char*
2130 patch_to_string (MonoJumpInfo *patch_info)
2131 {
2132         GString *str;
2133
2134         str = g_string_new ("");
2135
2136         g_string_append_printf (str, "%s(", get_patch_name (patch_info->type));
2137
2138         switch (patch_info->type) {
2139         case MONO_PATCH_INFO_VTABLE:
2140                 mono_type_get_desc (str, &patch_info->data.klass->byval_arg, TRUE);
2141                 break;
2142         default:
2143                 break;
2144         }
2145         g_string_append_printf (str, ")");
2146         return g_string_free (str, FALSE);
2147 }
2148
2149 /*
2150  * is_plt_patch:
2151  *
2152  *   Return whenever PATCH_INFO refers to a direct call, and thus requires a
2153  * PLT entry.
2154  */
2155 static inline gboolean
2156 is_plt_patch (MonoJumpInfo *patch_info)
2157 {
2158         switch (patch_info->type) {
2159         case MONO_PATCH_INFO_METHOD:
2160         case MONO_PATCH_INFO_INTERNAL_METHOD:
2161         case MONO_PATCH_INFO_JIT_ICALL_ADDR:
2162         case MONO_PATCH_INFO_ICALL_ADDR:
2163         case MONO_PATCH_INFO_CLASS_INIT:
2164         case MONO_PATCH_INFO_RGCTX_FETCH:
2165         case MONO_PATCH_INFO_GENERIC_CLASS_INIT:
2166         case MONO_PATCH_INFO_MONITOR_ENTER:
2167         case MONO_PATCH_INFO_MONITOR_EXIT:
2168         case MONO_PATCH_INFO_LLVM_IMT_TRAMPOLINE:
2169                 return TRUE;
2170         default:
2171                 return FALSE;
2172         }
2173 }
2174
2175 /*
2176  * get_plt_symbol:
2177  *
2178  *   Return the symbol identifying the plt entry PLT_OFFSET.
2179  */
2180 static char*
2181 get_plt_symbol (MonoAotCompile *acfg, int plt_offset, MonoJumpInfo *patch_info)
2182 {
2183 #ifdef __MACH__
2184         /* 
2185          * The Apple linker reorganizes object files, so it doesn't like branches to local
2186          * labels, since those have no relocations.
2187          */
2188         return g_strdup_printf ("%sp_%d", acfg->llvm_label_prefix, plt_offset);
2189 #else
2190         return g_strdup_printf ("%sp_%d", acfg->temp_prefix, plt_offset);
2191 #endif
2192 }
2193
2194 /*
2195  * get_plt_entry:
2196  *
2197  *   Return a PLT entry which belongs to the method identified by PATCH_INFO.
2198  */
2199 static MonoPltEntry*
2200 get_plt_entry (MonoAotCompile *acfg, MonoJumpInfo *patch_info)
2201 {
2202         MonoPltEntry *res;
2203
2204         if (!is_plt_patch (patch_info))
2205                 return NULL;
2206
2207         res = g_hash_table_lookup (acfg->patch_to_plt_entry, patch_info);
2208
2209         // FIXME: This breaks the calculation of final_got_size         
2210         if (!acfg->llvm && patch_info->type == MONO_PATCH_INFO_METHOD && (patch_info->data.method->iflags & METHOD_IMPL_ATTRIBUTE_SYNCHRONIZED)) {
2211                 /* 
2212                  * Allocate a separate PLT slot for each such patch, since some plt
2213                  * entries will refer to the method itself, and some will refer to the
2214                  * wrapper.
2215                  */
2216                 res = NULL;
2217         }
2218
2219         if (!res) {
2220                 MonoJumpInfo *new_ji;
2221
2222                 g_assert (!acfg->final_got_size);
2223
2224                 new_ji = mono_patch_info_dup_mp (acfg->mempool, patch_info);
2225
2226                 res = mono_mempool_alloc0 (acfg->mempool, sizeof (MonoPltEntry));
2227                 res->plt_offset = acfg->plt_offset;
2228                 res->ji = new_ji;
2229                 res->symbol = get_plt_symbol (acfg, res->plt_offset, patch_info);
2230                 res->llvm_symbol = g_strdup_printf ("%s_llvm", res->symbol);
2231
2232                 g_hash_table_insert (acfg->patch_to_plt_entry, new_ji, res);
2233
2234                 g_hash_table_insert (acfg->plt_offset_to_entry, GUINT_TO_POINTER (res->plt_offset), res);
2235
2236                 acfg->plt_offset ++;
2237         }
2238
2239         return res;
2240 }
2241
2242 /**
2243  * get_got_offset:
2244  *
2245  *   Returns the offset of the GOT slot where the runtime object resulting from resolving
2246  * JI could be found if it exists, otherwise allocates a new one.
2247  */
2248 static guint32
2249 get_got_offset (MonoAotCompile *acfg, MonoJumpInfo *ji)
2250 {
2251         guint32 got_offset;
2252
2253         got_offset = GPOINTER_TO_UINT (g_hash_table_lookup (acfg->patch_to_got_offset_by_type [ji->type], ji));
2254         if (got_offset)
2255                 return got_offset - 1;
2256
2257         got_offset = acfg->got_offset;
2258         acfg->got_offset ++;
2259
2260         if (acfg->final_got_size)
2261                 g_assert (got_offset < acfg->final_got_size);
2262
2263         acfg->stats.got_slots ++;
2264         acfg->stats.got_slot_types [ji->type] ++;
2265
2266         g_hash_table_insert (acfg->patch_to_got_offset, ji, GUINT_TO_POINTER (got_offset + 1));
2267         g_hash_table_insert (acfg->patch_to_got_offset_by_type [ji->type], ji, GUINT_TO_POINTER (got_offset + 1));
2268         g_ptr_array_add (acfg->got_patches, ji);
2269
2270         return got_offset;
2271 }
2272
2273 /* Add a method to the list of methods which need to be emitted */
2274 static void
2275 add_method_with_index (MonoAotCompile *acfg, MonoMethod *method, int index, gboolean extra)
2276 {
2277         g_assert (method);
2278         if (!g_hash_table_lookup (acfg->method_indexes, method)) {
2279                 g_ptr_array_add (acfg->methods, method);
2280                 g_hash_table_insert (acfg->method_indexes, method, GUINT_TO_POINTER (index + 1));
2281                 acfg->nmethods = acfg->methods->len + 1;
2282         }
2283
2284         if (method->wrapper_type || extra)
2285                 g_ptr_array_add (acfg->extra_methods, method);
2286 }
2287
2288 static guint32
2289 get_method_index (MonoAotCompile *acfg, MonoMethod *method)
2290 {
2291         int index = GPOINTER_TO_UINT (g_hash_table_lookup (acfg->method_indexes, method));
2292         
2293         g_assert (index);
2294
2295         return index - 1;
2296 }
2297
2298 static int
2299 add_method_full (MonoAotCompile *acfg, MonoMethod *method, gboolean extra, int depth)
2300 {
2301         int index;
2302
2303         index = GPOINTER_TO_UINT (g_hash_table_lookup (acfg->method_indexes, method));
2304         if (index)
2305                 return index - 1;
2306
2307         index = acfg->method_index;
2308         add_method_with_index (acfg, method, index, extra);
2309
2310         /* FIXME: Fix quadratic behavior */
2311         acfg->method_order = g_list_append (acfg->method_order, GUINT_TO_POINTER (index));
2312
2313         g_hash_table_insert (acfg->method_depth, method, GUINT_TO_POINTER (depth));
2314
2315         acfg->method_index ++;
2316
2317         return index;
2318 }
2319
2320 static int
2321 add_method (MonoAotCompile *acfg, MonoMethod *method)
2322 {
2323         return add_method_full (acfg, method, FALSE, 0);
2324 }
2325
2326 static void
2327 add_extra_method (MonoAotCompile *acfg, MonoMethod *method)
2328 {
2329         add_method_full (acfg, method, TRUE, 0);
2330 }
2331
2332 static void
2333 add_extra_method_with_depth (MonoAotCompile *acfg, MonoMethod *method, int depth)
2334 {
2335         add_method_full (acfg, method, TRUE, depth);
2336 }
2337
2338 static void
2339 add_jit_icall_wrapper (gpointer key, gpointer value, gpointer user_data)
2340 {
2341         MonoAotCompile *acfg = user_data;
2342         MonoJitICallInfo *callinfo = value;
2343         MonoMethod *wrapper;
2344         char *name;
2345
2346         if (!callinfo->sig)
2347                 return;
2348
2349         name = g_strdup_printf ("__icall_wrapper_%s", callinfo->name);
2350         wrapper = mono_marshal_get_icall_wrapper (callinfo->sig, name, callinfo->func, check_for_pending_exc);
2351         g_free (name);
2352
2353         add_method (acfg, wrapper);
2354 }
2355
2356 static MonoMethod*
2357 get_runtime_invoke_sig (MonoMethodSignature *sig)
2358 {
2359         MonoMethodBuilder *mb;
2360         MonoMethod *m;
2361
2362         mb = mono_mb_new (mono_defaults.object_class, "FOO", MONO_WRAPPER_NONE);
2363         m = mono_mb_create_method (mb, sig, 16);
2364         return mono_marshal_get_runtime_invoke (m, FALSE);
2365 }
2366
2367 static gboolean
2368 can_marshal_struct (MonoClass *klass)
2369 {
2370         MonoClassField *field;
2371         gboolean can_marshal = TRUE;
2372         gpointer iter = NULL;
2373
2374         if ((klass->flags & TYPE_ATTRIBUTE_LAYOUT_MASK) == TYPE_ATTRIBUTE_AUTO_LAYOUT)
2375                 return FALSE;
2376
2377         /* Only allow a few field types to avoid asserts in the marshalling code */
2378         while ((field = mono_class_get_fields (klass, &iter))) {
2379                 if ((field->type->attrs & FIELD_ATTRIBUTE_STATIC))
2380                         continue;
2381
2382                 switch (field->type->type) {
2383                 case MONO_TYPE_I4:
2384                 case MONO_TYPE_U4:
2385                 case MONO_TYPE_I1:
2386                 case MONO_TYPE_U1:
2387                 case MONO_TYPE_BOOLEAN:
2388                 case MONO_TYPE_I2:
2389                 case MONO_TYPE_U2:
2390                 case MONO_TYPE_CHAR:
2391                 case MONO_TYPE_I8:
2392                 case MONO_TYPE_U8:
2393                 case MONO_TYPE_I:
2394                 case MONO_TYPE_U:
2395                 case MONO_TYPE_PTR:
2396                 case MONO_TYPE_R4:
2397                 case MONO_TYPE_R8:
2398                 case MONO_TYPE_STRING:
2399                         break;
2400                 case MONO_TYPE_VALUETYPE:
2401                         if (!mono_class_from_mono_type (field->type)->enumtype && !can_marshal_struct (mono_class_from_mono_type (field->type)))
2402                                 can_marshal = FALSE;
2403                         break;
2404                 default:
2405                         can_marshal = FALSE;
2406                         break;
2407                 }
2408         }
2409
2410         /* Special cases */
2411         /* Its hard to compute whenever these can be marshalled or not */
2412         if (!strcmp (klass->name_space, "System.Net.NetworkInformation.MacOsStructs"))
2413                 return TRUE;
2414
2415         return can_marshal;
2416 }
2417
2418 static void
2419 add_wrappers (MonoAotCompile *acfg)
2420 {
2421         MonoMethod *method, *m;
2422         int i, j;
2423         MonoMethodSignature *sig, *csig;
2424         guint32 token;
2425
2426         /* 
2427          * FIXME: Instead of AOTing all the wrappers, it might be better to redesign them
2428          * so there is only one wrapper of a given type, or inlining their contents into their
2429          * callers.
2430          */
2431
2432         /* 
2433          * FIXME: This depends on the fact that different wrappers have different 
2434          * names.
2435          */
2436
2437         for (i = 0; i < acfg->image->tables [MONO_TABLE_METHOD].rows; ++i) {
2438                 MonoMethod *method;
2439                 guint32 token = MONO_TOKEN_METHOD_DEF | (i + 1);
2440                 gboolean skip = FALSE;
2441
2442                 method = mono_get_method (acfg->image, token, NULL);
2443
2444                 if ((method->flags & METHOD_ATTRIBUTE_PINVOKE_IMPL) ||
2445                         (method->iflags & METHOD_IMPL_ATTRIBUTE_RUNTIME) ||
2446                         (method->flags & METHOD_ATTRIBUTE_ABSTRACT))
2447                         skip = TRUE;
2448
2449                 if (method->is_generic || method->klass->generic_container)
2450                         skip = TRUE;
2451
2452                 /* Skip methods which can not be handled by get_runtime_invoke () */
2453                 sig = mono_method_signature (method);
2454                 if (!sig)
2455                         continue;
2456                 if ((sig->ret->type == MONO_TYPE_PTR) ||
2457                         (sig->ret->type == MONO_TYPE_TYPEDBYREF))
2458                         skip = TRUE;
2459
2460                 for (j = 0; j < sig->param_count; j++) {
2461                         if (sig->params [j]->type == MONO_TYPE_TYPEDBYREF)
2462                                 skip = TRUE;
2463                 }
2464
2465 #ifdef MONO_ARCH_DYN_CALL_SUPPORTED
2466                 if (!method->klass->contextbound) {
2467                         MonoDynCallInfo *info = mono_arch_dyn_call_prepare (sig);
2468                         gboolean has_nullable = FALSE;
2469
2470                         for (j = 0; j < sig->param_count; j++) {
2471                                 if (sig->params [j]->type == MONO_TYPE_GENERICINST && mono_class_is_nullable (mono_class_from_mono_type (sig->params [j])))
2472                                         has_nullable = TRUE;
2473                         }
2474
2475                         if (info && !has_nullable) {
2476                                 /* Supported by the dynamic runtime-invoke wrapper */
2477                                 skip = TRUE;
2478                                 g_free (info);
2479                         }
2480                 }
2481 #endif
2482
2483                 if (!skip) {
2484                         //printf ("%s\n", mono_method_full_name (method, TRUE));
2485                         add_method (acfg, mono_marshal_get_runtime_invoke (method, FALSE));
2486                 }
2487         }
2488
2489         if (strcmp (acfg->image->assembly->aname.name, "mscorlib") == 0) {
2490 #ifdef MONO_ARCH_HAVE_TLS_GET
2491                 MonoMethodDesc *desc;
2492                 MonoMethod *orig_method;
2493                 int nallocators;
2494 #endif
2495
2496                 /* Runtime invoke wrappers */
2497
2498                 /* void runtime-invoke () [.cctor] */
2499                 csig = mono_metadata_signature_alloc (mono_defaults.corlib, 0);
2500                 csig->ret = &mono_defaults.void_class->byval_arg;
2501                 add_method (acfg, get_runtime_invoke_sig (csig));
2502
2503                 /* void runtime-invoke () [Finalize] */
2504                 csig = mono_metadata_signature_alloc (mono_defaults.corlib, 0);
2505                 csig->hasthis = 1;
2506                 csig->ret = &mono_defaults.void_class->byval_arg;
2507                 add_method (acfg, get_runtime_invoke_sig (csig));
2508
2509                 /* void runtime-invoke (string) [exception ctor] */
2510                 csig = mono_metadata_signature_alloc (mono_defaults.corlib, 1);
2511                 csig->hasthis = 1;
2512                 csig->ret = &mono_defaults.void_class->byval_arg;
2513                 csig->params [0] = &mono_defaults.string_class->byval_arg;
2514                 add_method (acfg, get_runtime_invoke_sig (csig));
2515
2516                 /* void runtime-invoke (string, string) [exception ctor] */
2517                 csig = mono_metadata_signature_alloc (mono_defaults.corlib, 2);
2518                 csig->hasthis = 1;
2519                 csig->ret = &mono_defaults.void_class->byval_arg;
2520                 csig->params [0] = &mono_defaults.string_class->byval_arg;
2521                 csig->params [1] = &mono_defaults.string_class->byval_arg;
2522                 add_method (acfg, get_runtime_invoke_sig (csig));
2523
2524                 /* string runtime-invoke () [Exception.ToString ()] */
2525                 csig = mono_metadata_signature_alloc (mono_defaults.corlib, 0);
2526                 csig->hasthis = 1;
2527                 csig->ret = &mono_defaults.string_class->byval_arg;
2528                 add_method (acfg, get_runtime_invoke_sig (csig));
2529
2530                 /* void runtime-invoke (string, Exception) [exception ctor] */
2531                 csig = mono_metadata_signature_alloc (mono_defaults.corlib, 2);
2532                 csig->hasthis = 1;
2533                 csig->ret = &mono_defaults.void_class->byval_arg;
2534                 csig->params [0] = &mono_defaults.string_class->byval_arg;
2535                 csig->params [1] = &mono_defaults.exception_class->byval_arg;
2536                 add_method (acfg, get_runtime_invoke_sig (csig));
2537
2538                 /* Assembly runtime-invoke (string, bool) [DoAssemblyResolve] */
2539                 csig = mono_metadata_signature_alloc (mono_defaults.corlib, 2);
2540                 csig->hasthis = 1;
2541                 csig->ret = &(mono_class_from_name (
2542                                                                                         mono_defaults.corlib, "System.Reflection", "Assembly"))->byval_arg;
2543                 csig->params [0] = &mono_defaults.string_class->byval_arg;
2544                 csig->params [1] = &mono_defaults.boolean_class->byval_arg;
2545                 add_method (acfg, get_runtime_invoke_sig (csig));
2546
2547                 /* runtime-invoke used by finalizers */
2548                 add_method (acfg, mono_marshal_get_runtime_invoke (mono_class_get_method_from_name_flags (mono_defaults.object_class, "Finalize", 0, 0), TRUE));
2549
2550                 /* This is used by mono_runtime_capture_context () */
2551                 method = mono_get_context_capture_method ();
2552                 if (method)
2553                         add_method (acfg, mono_marshal_get_runtime_invoke (method, FALSE));
2554
2555 #ifdef MONO_ARCH_DYN_CALL_SUPPORTED
2556                 add_method (acfg, mono_marshal_get_runtime_invoke_dynamic ());
2557 #endif
2558
2559                 /* JIT icall wrappers */
2560                 /* FIXME: locking */
2561                 g_hash_table_foreach (mono_get_jit_icall_info (), add_jit_icall_wrapper, acfg);
2562
2563                 /* stelemref */
2564                 add_method (acfg, mono_marshal_get_stelemref ());
2565
2566 #ifdef MONO_ARCH_HAVE_TLS_GET
2567                 /* Managed Allocators */
2568                 nallocators = mono_gc_get_managed_allocator_types ();
2569                 for (i = 0; i < nallocators; ++i) {
2570                         m = mono_gc_get_managed_allocator_by_type (i);
2571                         if (m)
2572                                 add_method (acfg, m);
2573                 }
2574
2575                 /* Monitor Enter/Exit */
2576                 desc = mono_method_desc_new ("Monitor:Enter", FALSE);
2577                 orig_method = mono_method_desc_search_in_class (desc, mono_defaults.monitor_class);
2578                 g_assert (orig_method);
2579                 mono_method_desc_free (desc);
2580                 method = mono_monitor_get_fast_path (orig_method);
2581                 if (method)
2582                         add_method (acfg, method);
2583
2584                 desc = mono_method_desc_new ("Monitor:Exit", FALSE);
2585                 orig_method = mono_method_desc_search_in_class (desc, mono_defaults.monitor_class);
2586                 g_assert (orig_method);
2587                 mono_method_desc_free (desc);
2588                 method = mono_monitor_get_fast_path (orig_method);
2589                 if (method)
2590                         add_method (acfg, method);
2591 #endif
2592
2593                 /* Stelemref wrappers */
2594                 /* There is only a constant number of these, iterating over all types should handle them all */
2595                 for (i = 0; i < acfg->image->tables [MONO_TABLE_TYPEDEF].rows; ++i) {
2596                         MonoClass *klass;
2597                 
2598                         token = MONO_TOKEN_TYPE_DEF | (i + 1);
2599                         klass = mono_class_get (acfg->image, token);
2600                         if (klass)
2601                                 add_method (acfg, mono_marshal_get_virtual_stelemref (mono_array_class_get (klass, 1)));
2602                 }
2603         }
2604
2605         /* 
2606          * remoting-invoke-with-check wrappers are very frequent, so avoid emitting them,
2607          * we use the original method instead at runtime.
2608          * Since full-aot doesn't support remoting, this is not a problem.
2609          */
2610 #if 0
2611         /* remoting-invoke wrappers */
2612         for (i = 0; i < acfg->image->tables [MONO_TABLE_METHOD].rows; ++i) {
2613                 MonoMethodSignature *sig;
2614                 
2615                 token = MONO_TOKEN_METHOD_DEF | (i + 1);
2616                 method = mono_get_method (acfg->image, token, NULL);
2617
2618                 sig = mono_method_signature (method);
2619
2620                 if (sig->hasthis && (method->klass->marshalbyref || method->klass == mono_defaults.object_class)) {
2621                         m = mono_marshal_get_remoting_invoke_with_check (method);
2622
2623                         add_method (acfg, m);
2624                 }
2625         }
2626 #endif
2627
2628         /* delegate-invoke wrappers */
2629         for (i = 0; i < acfg->image->tables [MONO_TABLE_TYPEDEF].rows; ++i) {
2630                 MonoClass *klass;
2631                 
2632                 token = MONO_TOKEN_TYPE_DEF | (i + 1);
2633                 klass = mono_class_get (acfg->image, token);
2634
2635                 if (klass->delegate && klass != mono_defaults.delegate_class && klass != mono_defaults.multicastdelegate_class && !klass->generic_container) {
2636                         method = mono_get_delegate_invoke (klass);
2637
2638                         m = mono_marshal_get_delegate_invoke (method, NULL);
2639
2640                         add_method (acfg, m);
2641
2642                         method = mono_class_get_method_from_name_flags (klass, "BeginInvoke", -1, 0);
2643                         add_method (acfg, mono_marshal_get_delegate_begin_invoke (method));
2644
2645                         method = mono_class_get_method_from_name_flags (klass, "EndInvoke", -1, 0);
2646                         add_method (acfg, mono_marshal_get_delegate_end_invoke (method));
2647                 }
2648         }
2649
2650         /* Synchronized wrappers */
2651         for (i = 0; i < acfg->image->tables [MONO_TABLE_METHOD].rows; ++i) {
2652                 token = MONO_TOKEN_METHOD_DEF | (i + 1);
2653                 method = mono_get_method (acfg->image, token, NULL);
2654
2655                 if (method->iflags & METHOD_IMPL_ATTRIBUTE_SYNCHRONIZED && !method->is_generic)
2656                         add_method (acfg, mono_marshal_get_synchronized_wrapper (method));
2657         }
2658
2659         /* pinvoke wrappers */
2660         for (i = 0; i < acfg->image->tables [MONO_TABLE_METHOD].rows; ++i) {
2661                 MonoMethod *method;
2662                 guint32 token = MONO_TOKEN_METHOD_DEF | (i + 1);
2663
2664                 method = mono_get_method (acfg->image, token, NULL);
2665
2666                 if ((method->flags & METHOD_ATTRIBUTE_PINVOKE_IMPL) ||
2667                         (method->iflags & METHOD_IMPL_ATTRIBUTE_INTERNAL_CALL)) {
2668                         add_method (acfg, mono_marshal_get_native_wrapper (method, TRUE, TRUE));
2669                 }
2670         }
2671  
2672         /* native-to-managed wrappers */
2673         for (i = 0; i < acfg->image->tables [MONO_TABLE_METHOD].rows; ++i) {
2674                 MonoMethod *method;
2675                 guint32 token = MONO_TOKEN_METHOD_DEF | (i + 1);
2676                 MonoCustomAttrInfo *cattr;
2677                 int j;
2678
2679                 method = mono_get_method (acfg->image, token, NULL);
2680
2681                 /* 
2682                  * Only generate native-to-managed wrappers for methods which have an
2683                  * attribute named MonoPInvokeCallbackAttribute. We search for the attribute by
2684                  * name to avoid defining a new assembly to contain it.
2685                  */
2686                 cattr = mono_custom_attrs_from_method (method);
2687
2688                 if (cattr) {
2689                         for (j = 0; j < cattr->num_attrs; ++j)
2690                                 if (cattr->attrs [j].ctor && !strcmp (cattr->attrs [j].ctor->klass->name, "MonoPInvokeCallbackAttribute"))
2691                                         break;
2692                         if (j < cattr->num_attrs) {
2693                                 MonoCustomAttrEntry *e = &cattr->attrs [j];
2694                                 MonoMethodSignature *sig = mono_method_signature (e->ctor);
2695                                 const char *p = (const char*)e->data;
2696                                 int slen;
2697                                 char *n;
2698                                 MonoType *t;
2699                                 MonoClass *klass;
2700
2701                                 g_assert (method->flags & METHOD_ATTRIBUTE_STATIC);
2702
2703                                 g_assert (sig->param_count == 1);
2704                                 g_assert (sig->params [0]->type == MONO_TYPE_CLASS && !strcmp (mono_class_from_mono_type (sig->params [0])->name, "Type"));
2705
2706                                 /* 
2707                                  * Decode the cattr manually since we can't create objects
2708                                  * during aot compilation.
2709                                  */
2710                                         
2711                                 /* Skip prolog */
2712                                 p += 2;
2713
2714                                 /* From load_cattr_value () in reflection.c */
2715                                 slen = mono_metadata_decode_value (p, &p);
2716                                 n = g_memdup (p, slen + 1);
2717                                 n [slen] = 0;
2718                                 t = mono_reflection_type_from_name (n, acfg->image);
2719                                 g_assert (t);
2720                                 g_free (n);
2721
2722                                 klass = mono_class_from_mono_type (t);
2723                                 g_assert (klass->parent == mono_defaults.multicastdelegate_class);
2724
2725                                 add_method (acfg, mono_marshal_get_managed_wrapper (method, klass, 0));
2726                         }
2727                 }
2728
2729                 if ((method->flags & METHOD_ATTRIBUTE_PINVOKE_IMPL) ||
2730                         (method->iflags & METHOD_IMPL_ATTRIBUTE_INTERNAL_CALL)) {
2731                         add_method (acfg, mono_marshal_get_native_wrapper (method, TRUE, TRUE));
2732                 }
2733         }
2734
2735         /* StructureToPtr/PtrToStructure wrappers */
2736         for (i = 0; i < acfg->image->tables [MONO_TABLE_TYPEDEF].rows; ++i) {
2737                 MonoClass *klass;
2738                 
2739                 token = MONO_TOKEN_TYPE_DEF | (i + 1);
2740                 klass = mono_class_get (acfg->image, token);
2741
2742                 if (klass->valuetype && !klass->generic_container && can_marshal_struct (klass)) {
2743                         add_method (acfg, mono_marshal_get_struct_to_ptr (klass));
2744                         add_method (acfg, mono_marshal_get_ptr_to_struct (klass));
2745                 }
2746         }
2747 }
2748
2749 static gboolean
2750 has_type_vars (MonoClass *klass)
2751 {
2752         if ((klass->byval_arg.type == MONO_TYPE_VAR) || (klass->byval_arg.type == MONO_TYPE_MVAR))
2753                 return TRUE;
2754         if (klass->rank)
2755                 return has_type_vars (klass->element_class);
2756         if (klass->generic_class) {
2757                 MonoGenericContext *context = &klass->generic_class->context;
2758                 if (context->class_inst) {
2759                         int i;
2760
2761                         for (i = 0; i < context->class_inst->type_argc; ++i)
2762                                 if (has_type_vars (mono_class_from_mono_type (context->class_inst->type_argv [i])))
2763                                         return TRUE;
2764                 }
2765         }
2766         return FALSE;
2767 }
2768
2769 static gboolean
2770 method_has_type_vars (MonoMethod *method)
2771 {
2772         if (has_type_vars (method->klass))
2773                 return TRUE;
2774
2775         if (method->is_inflated) {
2776                 MonoGenericContext *context = mono_method_get_context (method);
2777                 if (context->method_inst) {
2778                         int i;
2779
2780                         for (i = 0; i < context->method_inst->type_argc; ++i)
2781                                 if (has_type_vars (mono_class_from_mono_type (context->method_inst->type_argv [i])))
2782                                         return TRUE;
2783                 }
2784         }
2785         return FALSE;
2786 }
2787
2788 static void add_generic_class_with_depth (MonoAotCompile *acfg, MonoClass *klass, int depth);
2789
2790 static void
2791 add_generic_class (MonoAotCompile *acfg, MonoClass *klass, gboolean force)
2792 {
2793         /* This might lead to a huge code blowup so only do it if neccesary */
2794         if (!acfg->aot_opts.full_aot && !force)
2795                 return;
2796
2797         add_generic_class_with_depth (acfg, klass, 0);
2798 }
2799
2800 /*
2801  * add_generic_class:
2802  *
2803  *   Add all methods of a generic class.
2804  */
2805 static void
2806 add_generic_class_with_depth (MonoAotCompile *acfg, MonoClass *klass, int depth)
2807 {
2808         MonoMethod *method;
2809         gpointer iter;
2810
2811         mono_class_init (klass);
2812
2813         if (klass->generic_class && klass->generic_class->context.class_inst->is_open)
2814                 return;
2815
2816         if (has_type_vars (klass))
2817                 return;
2818
2819         if (!klass->generic_class && !klass->rank)
2820                 return;
2821
2822         iter = NULL;
2823         while ((method = mono_class_get_methods (klass, &iter))) {
2824                 if (mono_method_is_generic_sharable_impl_full (method, FALSE, FALSE))
2825                         /* Already added */
2826                         continue;
2827
2828                 if (method->is_generic)
2829                         /* FIXME: */
2830                         continue;
2831
2832                 /*
2833                  * FIXME: Instances which are referenced by these methods are not added,
2834                  * for example Array.Resize<int> for List<int>.Add ().
2835                  */
2836                 add_extra_method_with_depth (acfg, method, depth);
2837         }
2838
2839         if (klass->delegate) {
2840                 method = mono_get_delegate_invoke (klass);
2841
2842                 method = mono_marshal_get_delegate_invoke (method, NULL);
2843
2844                 add_method (acfg, method);
2845         }
2846
2847         /* 
2848          * For ICollection<T>, add instances of the helper methods
2849          * in Array, since a T[] could be cast to ICollection<T>.
2850          */
2851         if (klass->image == mono_defaults.corlib && !strcmp (klass->name_space, "System.Collections.Generic") &&
2852                 (!strcmp(klass->name, "ICollection`1") || !strcmp (klass->name, "IEnumerable`1") || !strcmp (klass->name, "IList`1") || !strcmp (klass->name, "IEnumerator`1"))) {
2853                 MonoClass *tclass = mono_class_from_mono_type (klass->generic_class->context.class_inst->type_argv [0]);
2854                 MonoClass *array_class = mono_bounded_array_class_get (tclass, 1, FALSE);
2855                 gpointer iter;
2856                 char *name_prefix;
2857
2858                 if (!strcmp (klass->name, "IEnumerator`1"))
2859                         name_prefix = g_strdup_printf ("%s.%s", klass->name_space, "IEnumerable`1");
2860                 else
2861                         name_prefix = g_strdup_printf ("%s.%s", klass->name_space, klass->name);
2862
2863                 /* Add the T[]/InternalEnumerator class */
2864                 if (!strcmp (klass->name, "IEnumerable`1") || !strcmp (klass->name, "IEnumerator`1")) {
2865                         MonoClass *nclass;
2866
2867                         iter = NULL;
2868                         while ((nclass = mono_class_get_nested_types (array_class->parent, &iter))) {
2869                                 if (!strcmp (nclass->name, "InternalEnumerator`1"))
2870                                         break;
2871                         }
2872                         g_assert (nclass);
2873                         nclass = mono_class_inflate_generic_class (nclass, mono_generic_class_get_context (klass->generic_class));
2874                         add_generic_class (acfg, nclass, FALSE);
2875                 }
2876
2877                 iter = NULL;
2878                 while ((method = mono_class_get_methods (array_class, &iter))) {
2879                         if (strstr (method->name, name_prefix)) {
2880                                 MonoMethod *m = mono_aot_get_array_helper_from_wrapper (method);
2881                                 add_extra_method_with_depth (acfg, m, depth);
2882                         }
2883                 }
2884
2885                 g_free (name_prefix);
2886         }
2887
2888         /* Add an instance of GenericComparer<T> which is created dynamically by Comparer<T> */
2889         if (klass->image == mono_defaults.corlib && !strcmp (klass->name_space, "System.Collections.Generic") && !strcmp (klass->name, "Comparer`1")) {
2890                 MonoClass *tclass = mono_class_from_mono_type (klass->generic_class->context.class_inst->type_argv [0]);
2891                 MonoClass *icomparable, *gcomparer;
2892                 MonoGenericContext ctx;
2893                 MonoType *args [16];
2894
2895                 memset (&ctx, 0, sizeof (ctx));
2896
2897                 icomparable = mono_class_from_name (mono_defaults.corlib, "System", "IComparable`1");
2898                 g_assert (icomparable);
2899                 args [0] = &tclass->byval_arg;
2900                 ctx.class_inst = mono_metadata_get_generic_inst (1, args);
2901
2902                 if (mono_class_is_assignable_from (mono_class_inflate_generic_class (icomparable, &ctx), tclass)) {
2903                         gcomparer = mono_class_from_name (mono_defaults.corlib, "System.Collections.Generic", "GenericComparer`1");
2904                         g_assert (gcomparer);
2905                         add_generic_class (acfg, mono_class_inflate_generic_class (gcomparer, &ctx), FALSE);
2906                 }
2907         }
2908
2909         /* Add an instance of GenericEqualityComparer<T> which is created dynamically by EqualityComparer<T> */
2910         if (klass->image == mono_defaults.corlib && !strcmp (klass->name_space, "System.Collections.Generic") && !strcmp (klass->name, "EqualityComparer`1")) {
2911                 MonoClass *tclass = mono_class_from_mono_type (klass->generic_class->context.class_inst->type_argv [0]);
2912                 MonoClass *iface, *gcomparer;
2913                 MonoGenericContext ctx;
2914                 MonoType *args [16];
2915
2916                 memset (&ctx, 0, sizeof (ctx));
2917
2918                 iface = mono_class_from_name (mono_defaults.corlib, "System", "IEquatable`1");
2919                 g_assert (iface);
2920                 args [0] = &tclass->byval_arg;
2921                 ctx.class_inst = mono_metadata_get_generic_inst (1, args);
2922
2923                 if (mono_class_is_assignable_from (mono_class_inflate_generic_class (iface, &ctx), tclass)) {
2924                         gcomparer = mono_class_from_name (mono_defaults.corlib, "System.Collections.Generic", "GenericEqualityComparer`1");
2925                         g_assert (gcomparer);
2926                         add_generic_class (acfg, mono_class_inflate_generic_class (gcomparer, &ctx), FALSE);
2927                 }
2928         }
2929 }
2930
2931 static void
2932 add_instances_of (MonoAotCompile *acfg, MonoClass *klass, MonoType **insts, int ninsts, gboolean force)
2933 {
2934         int i;
2935         MonoGenericContext ctx;
2936         MonoType *args [16];
2937
2938         memset (&ctx, 0, sizeof (ctx));
2939
2940         for (i = 0; i < ninsts; ++i) {
2941                 args [0] = insts [i];
2942                 ctx.class_inst = mono_metadata_get_generic_inst (1, args);
2943                 add_generic_class (acfg, mono_class_inflate_generic_class (klass, &ctx), force);
2944         }
2945 }
2946
2947 /*
2948  * add_generic_instances:
2949  *
2950  *   Add instances referenced by the METHODSPEC/TYPESPEC table.
2951  */
2952 static void
2953 add_generic_instances (MonoAotCompile *acfg)
2954 {
2955         int i;
2956         guint32 token;
2957         MonoMethod *method;
2958         MonoMethodHeader *header;
2959         MonoMethodSignature *sig;
2960         MonoGenericContext *context;
2961
2962         for (i = 0; i < acfg->image->tables [MONO_TABLE_METHODSPEC].rows; ++i) {
2963                 token = MONO_TOKEN_METHOD_SPEC | (i + 1);
2964                 method = mono_get_method (acfg->image, token, NULL);
2965
2966                 if (!method)
2967                         continue;
2968
2969                 if (method->klass->image != acfg->image)
2970                         continue;
2971
2972                 context = mono_method_get_context (method);
2973
2974                 if (context && ((context->class_inst && context->class_inst->is_open)))
2975                         continue;
2976
2977                 /*
2978                  * For open methods, create an instantiation which can be passed to the JIT.
2979                  * FIXME: Handle class_inst as well.
2980                  */
2981                 if (context && context->method_inst && context->method_inst->is_open) {
2982                         MonoGenericContext shared_context;
2983                         MonoGenericInst *inst;
2984                         MonoType **type_argv;
2985                         int i;
2986                         MonoMethod *declaring_method;
2987                         gboolean supported = TRUE;
2988
2989                         /* Check that the context doesn't contain open constructed types */
2990                         if (context->class_inst) {
2991                                 inst = context->class_inst;
2992                                 for (i = 0; i < inst->type_argc; ++i) {
2993                                         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)
2994                                                 continue;
2995                                         if (mono_class_is_open_constructed_type (inst->type_argv [i]))
2996                                                 supported = FALSE;
2997                                 }
2998                         }
2999                         if (context->method_inst) {
3000                                 inst = context->method_inst;
3001                                 for (i = 0; i < inst->type_argc; ++i) {
3002                                         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)
3003                                                 continue;
3004                                         if (mono_class_is_open_constructed_type (inst->type_argv [i]))
3005                                                 supported = FALSE;
3006                                 }
3007                         }
3008
3009                         if (!supported)
3010                                 continue;
3011
3012                         memset (&shared_context, 0, sizeof (MonoGenericContext));
3013
3014                         inst = context->class_inst;
3015                         if (inst) {
3016                                 type_argv = g_new0 (MonoType*, inst->type_argc);
3017                                 for (i = 0; i < inst->type_argc; ++i) {
3018                                         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)
3019                                                 type_argv [i] = &mono_defaults.object_class->byval_arg;
3020                                         else
3021                                                 type_argv [i] = inst->type_argv [i];
3022                                 }
3023                                 
3024                                 shared_context.class_inst = mono_metadata_get_generic_inst (inst->type_argc, type_argv);
3025                                 g_free (type_argv);
3026                         }
3027
3028                         inst = context->method_inst;
3029                         if (inst) {
3030                                 type_argv = g_new0 (MonoType*, inst->type_argc);
3031                                 for (i = 0; i < inst->type_argc; ++i) {
3032                                         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)
3033                                                 type_argv [i] = &mono_defaults.object_class->byval_arg;
3034                                         else
3035                                                 type_argv [i] = inst->type_argv [i];
3036                                 }
3037
3038                                 shared_context.method_inst = mono_metadata_get_generic_inst (inst->type_argc, type_argv);
3039                                 g_free (type_argv);
3040                         }
3041
3042                         if (method->is_generic || method->klass->generic_container)
3043                                 declaring_method = method;
3044                         else
3045                                 declaring_method = mono_method_get_declaring_generic_method (method);
3046
3047                         method = mono_class_inflate_generic_method (declaring_method, &shared_context);
3048                 }
3049
3050                 /* 
3051                  * If the method is fully sharable, it was already added in place of its
3052                  * generic definition.
3053                  */
3054                 if (mono_method_is_generic_sharable_impl_full (method, FALSE, FALSE))
3055                         continue;
3056
3057                 /*
3058                  * FIXME: Partially shared methods are not shared here, so we end up with
3059                  * many identical methods.
3060                  */
3061                 add_extra_method (acfg, method);
3062         }
3063
3064         for (i = 0; i < acfg->image->tables [MONO_TABLE_TYPESPEC].rows; ++i) {
3065                 MonoClass *klass;
3066
3067                 token = MONO_TOKEN_TYPE_SPEC | (i + 1);
3068
3069                 klass = mono_class_get (acfg->image, token);
3070                 if (!klass || klass->rank)
3071                         continue;
3072
3073                 add_generic_class (acfg, klass, FALSE);
3074         }
3075
3076         /* Add types of args/locals */
3077         for (i = 0; i < acfg->methods->len; ++i) {
3078                 int j;
3079
3080                 method = g_ptr_array_index (acfg->methods, i);
3081
3082                 sig = mono_method_signature (method);
3083
3084                 if (sig) {
3085                         for (j = 0; j < sig->param_count; ++j)
3086                                 if (sig->params [j]->type == MONO_TYPE_GENERICINST)
3087                                         add_generic_class (acfg, mono_class_from_mono_type (sig->params [j]), FALSE);
3088                 }
3089
3090                 header = mono_method_get_header (method);
3091
3092                 if (header) {
3093                         for (j = 0; j < header->num_locals; ++j)
3094                                 if (header->locals [j]->type == MONO_TYPE_GENERICINST)
3095                                         add_generic_class (acfg, mono_class_from_mono_type (header->locals [j]), FALSE);
3096                 }
3097         }
3098
3099         if (acfg->image == mono_defaults.corlib) {
3100                 MonoClass *klass;
3101                 MonoType *insts [256];
3102                 int ninsts = 0;
3103
3104                 insts [ninsts ++] = &mono_defaults.byte_class->byval_arg;
3105                 insts [ninsts ++] = &mono_defaults.sbyte_class->byval_arg;
3106                 insts [ninsts ++] = &mono_defaults.int16_class->byval_arg;
3107                 insts [ninsts ++] = &mono_defaults.uint16_class->byval_arg;
3108                 insts [ninsts ++] = &mono_defaults.int32_class->byval_arg;
3109                 insts [ninsts ++] = &mono_defaults.uint32_class->byval_arg;
3110                 insts [ninsts ++] = &mono_defaults.int64_class->byval_arg;
3111                 insts [ninsts ++] = &mono_defaults.uint64_class->byval_arg;
3112                 insts [ninsts ++] = &mono_defaults.single_class->byval_arg;
3113                 insts [ninsts ++] = &mono_defaults.double_class->byval_arg;
3114                 insts [ninsts ++] = &mono_defaults.char_class->byval_arg;
3115                 insts [ninsts ++] = &mono_defaults.boolean_class->byval_arg;
3116
3117                 /* Add GenericComparer<T> instances for primitive types for Enum.ToString () */
3118                 klass = mono_class_from_name (acfg->image, "System.Collections.Generic", "GenericComparer`1");
3119                 if (klass)
3120                         add_instances_of (acfg, klass, insts, ninsts, TRUE);
3121                 klass = mono_class_from_name (acfg->image, "System.Collections.Generic", "GenericEqualityComparer`1");
3122                 if (klass)
3123                         add_instances_of (acfg, klass, insts, ninsts, TRUE);
3124
3125                 /* Add instances of the array generic interfaces for primitive types */
3126                 /* This will add instances of the InternalArray_ helper methods in Array too */
3127                 klass = mono_class_from_name (acfg->image, "System.Collections.Generic", "ICollection`1");
3128                 if (klass)
3129                         add_instances_of (acfg, klass, insts, ninsts, TRUE);
3130                 klass = mono_class_from_name (acfg->image, "System.Collections.Generic", "IList`1");
3131                 if (klass)
3132                         add_instances_of (acfg, klass, insts, ninsts, TRUE);
3133                 klass = mono_class_from_name (acfg->image, "System.Collections.Generic", "IEnumerable`1");
3134                 if (klass)
3135                         add_instances_of (acfg, klass, insts, ninsts, TRUE);
3136
3137                 /* 
3138                  * Add a managed-to-native wrapper of Array.GetGenericValueImpl<object>, which is
3139                  * used for all instances of GetGenericValueImpl by the AOT runtime.
3140                  */
3141                 {
3142                         MonoGenericContext ctx;
3143                         MonoType *args [16];
3144                         MonoMethod *get_method;
3145                         MonoClass *array_klass = mono_array_class_get (mono_defaults.object_class, 1)->parent;
3146
3147                         get_method = mono_class_get_method_from_name (array_klass, "GetGenericValueImpl", 2);
3148
3149                         if (get_method) {
3150                                 memset (&ctx, 0, sizeof (ctx));
3151                                 args [0] = &mono_defaults.object_class->byval_arg;
3152                                 ctx.method_inst = mono_metadata_get_generic_inst (1, args);
3153                                 add_extra_method (acfg, mono_marshal_get_native_wrapper (mono_class_inflate_generic_method (get_method, &ctx), TRUE, TRUE));
3154                         }
3155                 }
3156         }
3157 }
3158
3159 /*
3160  * is_direct_callable:
3161  *
3162  *   Return whenever the method identified by JI is directly callable without 
3163  * going through the PLT.
3164  */
3165 static gboolean
3166 is_direct_callable (MonoAotCompile *acfg, MonoMethod *method, MonoJumpInfo *patch_info)
3167 {
3168         if ((patch_info->type == MONO_PATCH_INFO_METHOD) && (patch_info->data.method->klass->image == acfg->image)) {
3169                 MonoCompile *callee_cfg = g_hash_table_lookup (acfg->method_to_cfg, patch_info->data.method);
3170                 if (callee_cfg) {
3171                         gboolean direct_callable = TRUE;
3172
3173                         if (direct_callable && !(!callee_cfg->has_got_slots && (callee_cfg->method->klass->flags & TYPE_ATTRIBUTE_BEFORE_FIELD_INIT)))
3174                                 direct_callable = FALSE;
3175                         if ((callee_cfg->method->iflags & METHOD_IMPL_ATTRIBUTE_SYNCHRONIZED) && (!method || method->wrapper_type != MONO_WRAPPER_SYNCHRONIZED))
3176                                 // FIXME: Maybe call the wrapper directly ?
3177                                 direct_callable = FALSE;
3178
3179                         if (direct_callable)
3180                                 return TRUE;
3181                 }
3182         }
3183
3184         return FALSE;
3185 }
3186
3187 /*
3188  * emit_and_reloc_code:
3189  *
3190  *   Emit the native code in CODE, handling relocations along the way. If GOT_ONLY
3191  * is true, calls are made through the GOT too. This is used for emitting trampolines
3192  * in full-aot mode, since calls made from trampolines couldn't go through the PLT,
3193  * since trampolines are needed to make PTL work.
3194  */
3195 static void
3196 emit_and_reloc_code (MonoAotCompile *acfg, MonoMethod *method, guint8 *code, guint32 code_len, MonoJumpInfo *relocs, gboolean got_only)
3197 {
3198         int i, pindex, start_index, method_index;
3199         GPtrArray *patches;
3200         MonoJumpInfo *patch_info;
3201         MonoMethodHeader *header;
3202         gboolean skip, direct_call;
3203         guint32 got_slot;
3204         char direct_call_target [1024];
3205
3206         if (method) {
3207                 header = mono_method_get_header (method);
3208
3209                 method_index = get_method_index (acfg, method);
3210         }
3211
3212         /* Collect and sort relocations */
3213         patches = g_ptr_array_new ();
3214         for (patch_info = relocs; patch_info; patch_info = patch_info->next)
3215                 g_ptr_array_add (patches, patch_info);
3216         g_ptr_array_sort (patches, compare_patches);
3217
3218         start_index = 0;
3219         for (i = 0; i < code_len; i++) {
3220                 patch_info = NULL;
3221                 for (pindex = start_index; pindex < patches->len; ++pindex) {
3222                         patch_info = g_ptr_array_index (patches, pindex);
3223                         if (patch_info->ip.i >= i)
3224                                 break;
3225                 }
3226
3227 #ifdef MONO_ARCH_AOT_SUPPORTED
3228                 skip = FALSE;
3229                 if (patch_info && (patch_info->ip.i == i) && (pindex < patches->len)) {
3230                         start_index = pindex;
3231
3232                         switch (patch_info->type) {
3233                         case MONO_PATCH_INFO_NONE:
3234                                 break;
3235                         case MONO_PATCH_INFO_GOT_OFFSET: {
3236                                 int code_size;
3237  
3238                                 arch_emit_got_offset (acfg, code + i, &code_size);
3239                                 i += code_size - 1;
3240                                 skip = TRUE;
3241                                 patch_info->type = MONO_PATCH_INFO_NONE;
3242                                 break;
3243                         }
3244                         default: {
3245                                 /*
3246                                  * If this patch is a call, try emitting a direct call instead of
3247                                  * through a PLT entry. This is possible if the called method is in
3248                                  * the same assembly and requires no initialization.
3249                                  */
3250                                 direct_call = FALSE;
3251                                 if ((patch_info->type == MONO_PATCH_INFO_METHOD) && (patch_info->data.method->klass->image == acfg->image)) {
3252                                         if (!got_only && is_direct_callable (acfg, method, patch_info)) {
3253                                                 MonoCompile *callee_cfg = g_hash_table_lookup (acfg->method_to_cfg, patch_info->data.method);
3254                                                 //printf ("DIRECT: %s %s\n", method ? mono_method_full_name (method, TRUE) : "", mono_method_full_name (callee_cfg->method, TRUE));
3255                                                 direct_call = TRUE;
3256                                                 g_assert (strlen (callee_cfg->asm_symbol) < 1000);
3257                                                 sprintf (direct_call_target, "%s", callee_cfg->asm_symbol);
3258                                                 patch_info->type = MONO_PATCH_INFO_NONE;
3259                                                 acfg->stats.direct_calls ++;
3260                                         }
3261
3262                                         acfg->stats.all_calls ++;
3263                                 }
3264
3265                                 if (!got_only && !direct_call) {
3266                                         MonoPltEntry *plt_entry = get_plt_entry (acfg, patch_info);
3267                                         if (plt_entry) {
3268                                                 /* This patch has a PLT entry, so we must emit a call to the PLT entry */
3269                                                 direct_call = TRUE;
3270                                                 sprintf (direct_call_target, "%s", plt_entry->symbol);
3271                 
3272                                                 /* Nullify the patch */
3273                                                 patch_info->type = MONO_PATCH_INFO_NONE;
3274                                                 plt_entry->jit_used = TRUE;
3275                                         }
3276                                 }
3277
3278                                 if (direct_call) {
3279                                         int call_size;
3280
3281                                         arch_emit_direct_call (acfg, direct_call_target, &call_size);
3282                                         i += call_size - 1;
3283                                 } else {
3284                                         int code_size;
3285
3286                                         got_slot = get_got_offset (acfg, patch_info);
3287
3288                                         arch_emit_got_access (acfg, code + i, got_slot, &code_size);
3289                                         i += code_size - 1;
3290                                 }
3291                                 skip = TRUE;
3292                         }
3293                         }
3294                 }
3295 #endif /* MONO_ARCH_AOT_SUPPORTED */
3296
3297                 if (!skip) {
3298                         /* Find next patch */
3299                         patch_info = NULL;
3300                         for (pindex = start_index; pindex < patches->len; ++pindex) {
3301                                 patch_info = g_ptr_array_index (patches, pindex);
3302                                 if (patch_info->ip.i >= i)
3303                                         break;
3304                         }
3305
3306                         /* Try to emit multiple bytes at once */
3307                         if (pindex < patches->len && patch_info->ip.i > i) {
3308                                 emit_bytes (acfg, code + i, patch_info->ip.i - i);
3309                                 i = patch_info->ip.i - 1;
3310                         } else {
3311                                 emit_bytes (acfg, code + i, 1);
3312                         }
3313                 }
3314         }
3315 }
3316
3317 /*
3318  * sanitize_symbol:
3319  *
3320  *   Modify SYMBOL so it only includes characters permissible in symbols.
3321  */
3322 static void
3323 sanitize_symbol (char *symbol)
3324 {
3325         int i, len = strlen (symbol);
3326
3327         for (i = 0; i < len; ++i)
3328                 if (!isalnum (symbol [i]) && (symbol [i] != '_'))
3329                         symbol [i] = '_';
3330 }
3331
3332 static char*
3333 get_debug_sym (MonoMethod *method, const char *prefix, GHashTable *cache)
3334 {
3335         char *name1, *name2, *cached;
3336         int i, j, len, count;
3337
3338         name1 = mono_method_full_name (method, TRUE);
3339         len = strlen (name1);
3340         name2 = malloc (strlen (prefix) + len + 16);
3341         memcpy (name2, prefix, strlen (prefix));
3342         j = strlen (prefix);
3343         for (i = 0; i < len; ++i) {
3344                 if (isalnum (name1 [i])) {
3345                         name2 [j ++] = name1 [i];
3346                 } else if (name1 [i] == ' ' && name1 [i + 1] == '(' && name1 [i + 2] == ')') {
3347                         i += 2;
3348                 } else if (name1 [i] == ',' && name1 [i + 1] == ' ') {
3349                         name2 [j ++] = '_';
3350                         i++;
3351                 } else if (name1 [i] == '(' || name1 [i] == ')' || name1 [i] == '>') {
3352                 } else
3353                         name2 [j ++] = '_';
3354         }
3355         name2 [j] = '\0';
3356
3357         g_free (name1);
3358
3359         count = 0;
3360         while (g_hash_table_lookup (cache, name2)) {
3361                 sprintf (name2 + j, "_%d", count);
3362                 count ++;
3363         }
3364
3365         cached = g_strdup (name2);
3366         g_hash_table_insert (cache, cached, cached);
3367
3368         return name2;
3369 }
3370
3371 static void
3372 emit_method_code (MonoAotCompile *acfg, MonoCompile *cfg)
3373 {
3374         MonoMethod *method;
3375         int method_index;
3376         guint8 *code;
3377         char *debug_sym = NULL;
3378         char symbol [128];
3379         int func_alignment = AOT_FUNC_ALIGNMENT;
3380         MonoMethodHeader *header;
3381
3382         method = cfg->orig_method;
3383         code = cfg->native_code;
3384         header = cfg->header;
3385
3386         method_index = get_method_index (acfg, method);
3387
3388         /* Make the labels local */
3389         sprintf (symbol, "%s", cfg->asm_symbol);
3390
3391         emit_section_change (acfg, ".text", 0);
3392         emit_alignment (acfg, func_alignment);
3393         emit_label (acfg, symbol);
3394
3395         if (acfg->aot_opts.write_symbols) {
3396                 /* 
3397                  * Write a C style symbol for every method, this has two uses:
3398                  * - it works on platforms where the dwarf debugging info is not
3399                  *   yet supported.
3400                  * - it allows the setting of breakpoints of aot-ed methods.
3401                  */
3402                 debug_sym = get_debug_sym (method, "", acfg->method_label_hash);
3403
3404                 sprintf (symbol, "%sme_%x", acfg->temp_prefix, method_index);
3405                 emit_local_symbol (acfg, debug_sym, symbol, TRUE);
3406                 emit_label (acfg, debug_sym);
3407         }
3408
3409         if (cfg->verbose_level > 0)
3410                 g_print ("Method %s emitted as %s\n", mono_method_full_name (method, TRUE), symbol);
3411
3412         acfg->stats.code_size += cfg->code_len;
3413
3414         acfg->cfgs [method_index]->got_offset = acfg->got_offset;
3415
3416         emit_and_reloc_code (acfg, method, code, cfg->code_len, cfg->patch_info, FALSE);
3417
3418         emit_line (acfg);
3419
3420         if (acfg->aot_opts.write_symbols) {
3421                 emit_symbol_size (acfg, debug_sym, ".");
3422                 g_free (debug_sym);
3423         }
3424
3425         sprintf (symbol, "%sme_%x", acfg->temp_prefix, method_index);
3426         emit_label (acfg, symbol);
3427 }
3428
3429 /**
3430  * encode_patch:
3431  *
3432  *  Encode PATCH_INFO into its disk representation.
3433  */
3434 static void
3435 encode_patch (MonoAotCompile *acfg, MonoJumpInfo *patch_info, guint8 *buf, guint8 **endbuf)
3436 {
3437         guint8 *p = buf;
3438
3439         switch (patch_info->type) {
3440         case MONO_PATCH_INFO_NONE:
3441                 break;
3442         case MONO_PATCH_INFO_IMAGE:
3443                 encode_value (get_image_index (acfg, patch_info->data.image), p, &p);
3444                 break;
3445         case MONO_PATCH_INFO_MSCORLIB_GOT_ADDR:
3446         case MONO_PATCH_INFO_GC_CARD_TABLE_ADDR:
3447                 break;
3448         case MONO_PATCH_INFO_METHOD_REL:
3449                 encode_value ((gint)patch_info->data.offset, p, &p);
3450                 break;
3451         case MONO_PATCH_INFO_SWITCH: {
3452                 gpointer *table = (gpointer *)patch_info->data.table->table;
3453                 int k;
3454
3455                 encode_value (patch_info->data.table->table_size, p, &p);
3456                 for (k = 0; k < patch_info->data.table->table_size; k++)
3457                         encode_value ((int)(gssize)table [k], p, &p);
3458                 break;
3459         }
3460         case MONO_PATCH_INFO_METHODCONST:
3461         case MONO_PATCH_INFO_METHOD:
3462         case MONO_PATCH_INFO_METHOD_JUMP:
3463         case MONO_PATCH_INFO_ICALL_ADDR:
3464         case MONO_PATCH_INFO_METHOD_RGCTX:
3465                 encode_method_ref (acfg, patch_info->data.method, p, &p);
3466                 break;
3467         case MONO_PATCH_INFO_INTERNAL_METHOD:
3468         case MONO_PATCH_INFO_JIT_ICALL_ADDR: {
3469                 guint32 len = strlen (patch_info->data.name);
3470
3471                 encode_value (len, p, &p);
3472
3473                 memcpy (p, patch_info->data.name, len);
3474                 p += len;
3475                 *p++ = '\0';
3476                 break;
3477         }
3478         case MONO_PATCH_INFO_LDSTR: {
3479                 guint32 image_index = get_image_index (acfg, patch_info->data.token->image);
3480                 guint32 token = patch_info->data.token->token;
3481                 g_assert (mono_metadata_token_code (token) == MONO_TOKEN_STRING);
3482                 encode_value (image_index, p, &p);
3483                 encode_value (patch_info->data.token->token - MONO_TOKEN_STRING, p, &p);
3484                 break;
3485         }
3486         case MONO_PATCH_INFO_RVA:
3487         case MONO_PATCH_INFO_DECLSEC:
3488         case MONO_PATCH_INFO_LDTOKEN:
3489         case MONO_PATCH_INFO_TYPE_FROM_HANDLE:
3490                 encode_value (get_image_index (acfg, patch_info->data.token->image), p, &p);
3491                 encode_value (patch_info->data.token->token, p, &p);
3492                 encode_value (patch_info->data.token->has_context, p, &p);
3493                 if (patch_info->data.token->has_context)
3494                         encode_generic_context (acfg, &patch_info->data.token->context, p, &p);
3495                 break;
3496         case MONO_PATCH_INFO_EXC_NAME: {
3497                 MonoClass *ex_class;
3498
3499                 ex_class =
3500                         mono_class_from_name (mono_defaults.exception_class->image,
3501                                                                   "System", patch_info->data.target);
3502                 g_assert (ex_class);
3503                 encode_klass_ref (acfg, ex_class, p, &p);
3504                 break;
3505         }
3506         case MONO_PATCH_INFO_R4:
3507                 encode_value (*((guint32 *)patch_info->data.target), p, &p);
3508                 break;
3509         case MONO_PATCH_INFO_R8:
3510                 encode_value (((guint32 *)patch_info->data.target) [MINI_LS_WORD_IDX], p, &p);
3511                 encode_value (((guint32 *)patch_info->data.target) [MINI_MS_WORD_IDX], p, &p);
3512                 break;
3513         case MONO_PATCH_INFO_VTABLE:
3514         case MONO_PATCH_INFO_CLASS:
3515         case MONO_PATCH_INFO_IID:
3516         case MONO_PATCH_INFO_ADJUSTED_IID:
3517                 encode_klass_ref (acfg, patch_info->data.klass, p, &p);
3518                 break;
3519         case MONO_PATCH_INFO_CLASS_INIT:
3520         case MONO_PATCH_INFO_DELEGATE_TRAMPOLINE:
3521                 encode_klass_ref (acfg, patch_info->data.klass, p, &p);
3522                 break;
3523         case MONO_PATCH_INFO_FIELD:
3524         case MONO_PATCH_INFO_SFLDA:
3525                 encode_field_info (acfg, patch_info->data.field, p, &p);
3526                 break;
3527         case MONO_PATCH_INFO_INTERRUPTION_REQUEST_FLAG:
3528                 break;
3529         case MONO_PATCH_INFO_RGCTX_FETCH: {
3530                 MonoJumpInfoRgctxEntry *entry = patch_info->data.rgctx_entry;
3531
3532                 encode_method_ref (acfg, entry->method, p, &p);
3533                 encode_value (entry->in_mrgctx, p, &p);
3534                 encode_value (entry->info_type, p, &p);
3535                 encode_value (entry->data->type, p, &p);
3536                 encode_patch (acfg, entry->data, p, &p);
3537                 break;
3538         }
3539         case MONO_PATCH_INFO_GENERIC_CLASS_INIT:
3540         case MONO_PATCH_INFO_MONITOR_ENTER:
3541         case MONO_PATCH_INFO_MONITOR_EXIT:
3542         case MONO_PATCH_INFO_SEQ_POINT_INFO:
3543                 break;
3544         case MONO_PATCH_INFO_LLVM_IMT_TRAMPOLINE:
3545                 encode_method_ref (acfg, patch_info->data.imt_tramp->method, p, &p);
3546                 encode_value (patch_info->data.imt_tramp->vt_offset, p, &p);
3547                 break;
3548         default:
3549                 g_warning ("unable to handle jump info %d", patch_info->type);
3550                 g_assert_not_reached ();
3551         }
3552
3553         *endbuf = p;
3554 }
3555
3556 static void
3557 encode_patch_list (MonoAotCompile *acfg, GPtrArray *patches, int n_patches, int first_got_offset, guint8 *buf, guint8 **endbuf)
3558 {
3559         guint8 *p = buf;
3560         guint32 pindex, offset;
3561         MonoJumpInfo *patch_info;
3562
3563         encode_value (n_patches, p, &p);
3564
3565         for (pindex = 0; pindex < patches->len; ++pindex) {
3566                 patch_info = g_ptr_array_index (patches, pindex);
3567
3568                 if (patch_info->type == MONO_PATCH_INFO_NONE || patch_info->type == MONO_PATCH_INFO_BB)
3569                         /* Nothing to do */
3570                         continue;
3571
3572                 offset = get_got_offset (acfg, patch_info);
3573                 encode_value (offset, p, &p);
3574         }
3575
3576         *endbuf = p;
3577 }
3578
3579 static void
3580 emit_method_info (MonoAotCompile *acfg, MonoCompile *cfg)
3581 {
3582         MonoMethod *method;
3583         GList *l;
3584         int pindex, buf_size, n_patches;
3585         guint8 *code;
3586         GPtrArray *patches;
3587         MonoJumpInfo *patch_info;
3588         MonoMethodHeader *header;
3589         guint32 method_index;
3590         guint8 *p, *buf;
3591         guint32 first_got_offset;
3592
3593         method = cfg->orig_method;
3594         code = cfg->native_code;
3595         header = mono_method_get_header (method);
3596
3597         method_index = get_method_index (acfg, method);
3598
3599         /* Sort relocations */
3600         patches = g_ptr_array_new ();
3601         for (patch_info = cfg->patch_info; patch_info; patch_info = patch_info->next)
3602                 g_ptr_array_add (patches, patch_info);
3603         g_ptr_array_sort (patches, compare_patches);
3604
3605         first_got_offset = acfg->cfgs [method_index]->got_offset;
3606
3607         /**********************/
3608         /* Encode method info */
3609         /**********************/
3610
3611         buf_size = (patches->len < 1000) ? 40960 : 40960 + (patches->len * 64);
3612         p = buf = g_malloc (buf_size);
3613
3614         if (mono_class_get_cctor (method->klass))
3615                 encode_klass_ref (acfg, method->klass, p, &p);
3616         else
3617                 /* Not needed when loading the method */
3618                 encode_value (0, p, &p);
3619
3620         /* String table */
3621         if (cfg->opt & MONO_OPT_SHARED) {
3622                 encode_value (g_list_length (cfg->ldstr_list), p, &p);
3623                 for (l = cfg->ldstr_list; l; l = l->next) {
3624                         encode_value ((long)l->data, p, &p);
3625                 }
3626         }
3627         else
3628                 /* Used only in shared mode */
3629                 g_assert (!cfg->ldstr_list);
3630
3631         n_patches = 0;
3632         for (pindex = 0; pindex < patches->len; ++pindex) {
3633                 patch_info = g_ptr_array_index (patches, pindex);
3634                 
3635                 if ((patch_info->type == MONO_PATCH_INFO_GOT_OFFSET) ||
3636                         (patch_info->type == MONO_PATCH_INFO_NONE)) {
3637                         patch_info->type = MONO_PATCH_INFO_NONE;
3638                         /* Nothing to do */
3639                         continue;
3640                 }
3641
3642                 if ((patch_info->type == MONO_PATCH_INFO_IMAGE) && (patch_info->data.image == acfg->image)) {
3643                         /* Stored in a GOT slot initialized at module load time */
3644                         patch_info->type = MONO_PATCH_INFO_NONE;
3645                         continue;
3646                 }
3647
3648                 if (patch_info->type == MONO_PATCH_INFO_GC_CARD_TABLE_ADDR) {
3649                         /* Stored in a GOT slot initialized at module load time */
3650                         patch_info->type = MONO_PATCH_INFO_NONE;
3651                         continue;
3652                 }
3653
3654                 if (is_plt_patch (patch_info)) {
3655                         /* Calls are made through the PLT */
3656                         patch_info->type = MONO_PATCH_INFO_NONE;
3657                         continue;
3658                 }
3659
3660                 n_patches ++;
3661         }
3662
3663         if (n_patches)
3664                 g_assert (cfg->has_got_slots);
3665
3666         encode_patch_list (acfg, patches, n_patches, first_got_offset, p, &p);
3667
3668         acfg->stats.info_size += p - buf;
3669
3670         g_assert (p - buf < buf_size);
3671
3672         cfg->method_info_offset = add_to_blob (acfg, buf, p - buf);
3673         g_free (buf);
3674 }
3675
3676 static guint32
3677 get_unwind_info_offset (MonoAotCompile *acfg, guint8 *encoded, guint32 encoded_len)
3678 {
3679         guint32 cache_index;
3680         guint32 offset;
3681
3682         /* Reuse the unwind module to canonize and store unwind info entries */
3683         cache_index = mono_cache_unwind_info (encoded, encoded_len);
3684
3685         /* Use +/- 1 to distinguish 0s from missing entries */
3686         offset = GPOINTER_TO_UINT (g_hash_table_lookup (acfg->unwind_info_offsets, GUINT_TO_POINTER (cache_index + 1)));
3687         if (offset)
3688                 return offset - 1;
3689         else {
3690                 guint8 buf [16];
3691                 guint8 *p;
3692
3693                 /* 
3694                  * It would be easier to use assembler symbols, but the caller needs an
3695                  * offset now.
3696                  */
3697                 offset = acfg->unwind_info_offset;
3698                 g_hash_table_insert (acfg->unwind_info_offsets, GUINT_TO_POINTER (cache_index + 1), GUINT_TO_POINTER (offset + 1));
3699                 g_ptr_array_add (acfg->unwind_ops, GUINT_TO_POINTER (cache_index));
3700
3701                 p = buf;
3702                 encode_value (encoded_len, p, &p);
3703
3704                 acfg->unwind_info_offset += encoded_len + (p - buf);
3705                 return offset;
3706         }
3707 }
3708
3709 static void
3710 emit_exception_debug_info (MonoAotCompile *acfg, MonoCompile *cfg)
3711 {
3712         MonoMethod *method;
3713         int i, k, buf_size, method_index;
3714         guint32 debug_info_size;
3715         guint8 *code;
3716         MonoMethodHeader *header;
3717         guint8 *p, *buf, *debug_info;
3718         MonoJitInfo *jinfo = cfg->jit_info;
3719         guint32 flags;
3720         gboolean use_unwind_ops = FALSE;
3721         MonoSeqPointInfo *seq_points;
3722
3723         method = cfg->orig_method;
3724         code = cfg->native_code;
3725         header = cfg->header;
3726
3727         method_index = get_method_index (acfg, method);
3728
3729         if (!acfg->aot_opts.nodebug) {
3730                 mono_debug_serialize_debug_info (cfg, &debug_info, &debug_info_size);
3731         } else {
3732                 debug_info = NULL;
3733                 debug_info_size = 0;
3734         }
3735
3736         seq_points = cfg->seq_point_info;
3737
3738         buf_size = header->num_clauses * 256 + debug_info_size + 1024 + (seq_points ? (seq_points->len * 64) : 0) + cfg->gc_map_size;
3739         p = buf = g_malloc (buf_size);
3740
3741 #ifdef MONO_ARCH_HAVE_XP_UNWIND
3742         use_unwind_ops = cfg->unwind_ops != NULL;
3743 #endif
3744
3745         flags = (jinfo->has_generic_jit_info ? 1 : 0) | (use_unwind_ops ? 2 : 0) | (header->num_clauses ? 4 : 0) | (seq_points ? 8 : 0) | (cfg->compile_llvm ? 16 : 0) | (jinfo->has_try_block_holes ? 32 : 0) | (cfg->gc_map ? 64 : 0);
3746
3747         encode_value (flags, p, &p);
3748
3749         if (use_unwind_ops) {
3750                 guint32 encoded_len;
3751                 guint8 *encoded;
3752
3753                 /* 
3754                  * This is a duplicate of the data in the .debug_frame section, but that
3755                  * section cannot be accessed using the dl interface.
3756                  */
3757                 encoded = mono_unwind_ops_encode (cfg->unwind_ops, &encoded_len);
3758                 encode_value (get_unwind_info_offset (acfg, encoded, encoded_len), p, &p);
3759                 g_free (encoded);
3760         } else {
3761                 encode_value (jinfo->used_regs, p, &p);
3762         }
3763
3764         /*Encode the number of holes before the number of clauses to make decoding easier*/
3765         if (jinfo->has_try_block_holes) {
3766                 MonoTryBlockHoleTableJitInfo *table = mono_jit_info_get_try_block_hole_table_info (jinfo);
3767                 encode_value (table->num_holes, p, &p);
3768         }
3769
3770         /* Exception table */
3771         if (cfg->compile_llvm) {
3772                 /*
3773                  * When using LLVM, we can't emit some data, like pc offsets, this reg/offset etc.,
3774                  * since the information is only available to llc. Instead, we let llc save the data
3775                  * into the LSDA, and read it from there at runtime.
3776                  */
3777                 /* The assembly might be CIL stripped so emit the data ourselves */
3778                 if (header->num_clauses)
3779                         encode_value (header->num_clauses, p, &p);
3780
3781                 for (k = 0; k < header->num_clauses; ++k) {
3782                         MonoExceptionClause *clause;
3783
3784                         clause = &header->clauses [k];
3785
3786                         encode_value (clause->flags, p, &p);
3787                         if (clause->data.catch_class) {
3788                                 encode_value (1, p, &p);
3789                                 encode_klass_ref (acfg, clause->data.catch_class, p, &p);
3790                         } else {
3791                                 encode_value (0, p, &p);
3792                         }
3793
3794                         /* Emit a list of nesting clauses */
3795                         for (i = 0; i < header->num_clauses; ++i) {
3796                                 gint32 cindex1 = k;
3797                                 MonoExceptionClause *clause1 = &header->clauses [cindex1];
3798                                 gint32 cindex2 = i;
3799                                 MonoExceptionClause *clause2 = &header->clauses [cindex2];
3800
3801                                 if (cindex1 != cindex2 && clause1->try_offset >= clause2->try_offset && clause1->handler_offset <= clause2->handler_offset)
3802                                         encode_value (i, p, &p);
3803                         }
3804                         encode_value (-1, p, &p);
3805                 }
3806         } else {
3807                 if (jinfo->num_clauses)
3808                         encode_value (jinfo->num_clauses, p, &p);
3809
3810                 for (k = 0; k < jinfo->num_clauses; ++k) {
3811                         MonoJitExceptionInfo *ei = &jinfo->clauses [k];
3812
3813                         encode_value (ei->flags, p, &p);
3814                         encode_value (ei->exvar_offset, p, &p);
3815
3816                         if (ei->flags == MONO_EXCEPTION_CLAUSE_FILTER || ei->flags == MONO_EXCEPTION_CLAUSE_FINALLY)
3817                                 encode_value ((gint)((guint8*)ei->data.filter - code), p, &p);
3818                         else {
3819                                 if (ei->data.catch_class) {
3820                                         encode_value (1, p, &p);
3821                                         encode_klass_ref (acfg, ei->data.catch_class, p, &p);
3822                                 } else {
3823                                         encode_value (0, p, &p);
3824                                 }
3825                         }
3826
3827                         encode_value ((gint)((guint8*)ei->try_start - code), p, &p);
3828                         encode_value ((gint)((guint8*)ei->try_end - code), p, &p);
3829                         encode_value ((gint)((guint8*)ei->handler_start - code), p, &p);
3830                 }
3831         }
3832
3833         if (jinfo->has_generic_jit_info) {
3834                 MonoGenericJitInfo *gi = mono_jit_info_get_generic_jit_info (jinfo);
3835
3836                 if (!cfg->compile_llvm) {
3837                         encode_value (gi->has_this ? 1 : 0, p, &p);
3838                         encode_value (gi->this_reg, p, &p);
3839                         encode_value (gi->this_offset, p, &p);
3840                 }
3841
3842                 /* 
3843                  * Need to encode jinfo->method too, since it is not equal to 'method'
3844                  * when using generic sharing.
3845                  */
3846                 encode_method_ref (acfg, jinfo->method, p, &p);
3847         }
3848
3849         if (jinfo->has_try_block_holes) {
3850                 MonoTryBlockHoleTableJitInfo *table = mono_jit_info_get_try_block_hole_table_info (jinfo);
3851                 for (i = 0; i < table->num_holes; ++i) {
3852                         MonoTryBlockHoleJitInfo *hole = &table->holes [i];
3853                         encode_value (hole->clause, p, &p);
3854                         encode_value (hole->length, p, &p);
3855                         encode_value (hole->offset, p, &p);
3856                 }
3857         }
3858
3859         if (seq_points) {
3860                 int il_offset, native_offset, last_il_offset, last_native_offset, j;
3861
3862                 encode_value (seq_points->len, p, &p);
3863                 last_il_offset = last_native_offset = 0;
3864                 for (i = 0; i < seq_points->len; ++i) {
3865                         SeqPoint *sp = &seq_points->seq_points [i];
3866                         il_offset = sp->il_offset;
3867                         native_offset = sp->native_offset;
3868                         encode_value (il_offset - last_il_offset, p, &p);
3869                         encode_value (native_offset - last_native_offset, p, &p);
3870                         last_il_offset = il_offset;
3871                         last_native_offset = native_offset;
3872
3873                         encode_value (sp->next_len, p, &p);
3874                         for (j = 0; j < sp->next_len; ++j)
3875                                 encode_value (sp->next [j], p, &p);
3876                 }
3877         }
3878                 
3879         g_assert (debug_info_size < buf_size);
3880
3881         encode_value (debug_info_size, p, &p);
3882         if (debug_info_size) {
3883                 memcpy (p, debug_info, debug_info_size);
3884                 p += debug_info_size;
3885                 g_free (debug_info);
3886         }
3887
3888         /* GC Map */
3889         if (cfg->gc_map) {
3890                 encode_value (cfg->gc_map_size, p, &p);
3891                 /* The GC map requires 4 bytes of alignment */
3892                 while ((gsize)p % 4)
3893                         p ++;
3894                 memcpy (p, cfg->gc_map, cfg->gc_map_size);
3895                 p += cfg->gc_map_size;
3896         }
3897
3898         acfg->stats.ex_info_size += p - buf;
3899
3900         g_assert (p - buf < buf_size);
3901
3902         /* Emit info */
3903         /* The GC Map requires 4 byte alignment */
3904         cfg->ex_info_offset = add_to_blob_aligned (acfg, buf, p - buf, cfg->gc_map ? 4 : 1);
3905         g_free (buf);
3906 }
3907
3908 static guint32
3909 emit_klass_info (MonoAotCompile *acfg, guint32 token)
3910 {
3911         MonoClass *klass = mono_class_get (acfg->image, token);
3912         guint8 *p, *buf;
3913         int i, buf_size, res;
3914         gboolean no_special_static, cant_encode;
3915         gpointer iter = NULL;
3916
3917         if (!klass) {
3918                 buf_size = 16;
3919
3920                 p = buf = g_malloc (buf_size);
3921
3922                 /* Mark as unusable */
3923                 encode_value (-1, p, &p);
3924
3925                 res = add_to_blob (acfg, buf, p - buf);
3926                 g_free (buf);
3927
3928                 return res;
3929         }
3930                 
3931         buf_size = 10240 + (klass->vtable_size * 16);
3932         p = buf = g_malloc (buf_size);
3933
3934         g_assert (klass);
3935
3936         mono_class_init (klass);
3937
3938         mono_class_get_nested_types (klass, &iter);
3939         g_assert (klass->nested_classes_inited);
3940
3941         mono_class_setup_vtable (klass);
3942
3943         /* 
3944          * Emit all the information which is required for creating vtables so
3945          * the runtime does not need to create the MonoMethod structures which
3946          * take up a lot of space.
3947          */
3948
3949         no_special_static = !mono_class_has_special_static_fields (klass);
3950
3951         /* Check whenever we have enough info to encode the vtable */
3952         cant_encode = FALSE;
3953         for (i = 0; i < klass->vtable_size; ++i) {
3954                 MonoMethod *cm = klass->vtable [i];
3955
3956                 if (cm && mono_method_signature (cm)->is_inflated && !g_hash_table_lookup (acfg->token_info_hash, cm))
3957                         cant_encode = TRUE;
3958         }
3959
3960         if (klass->generic_container || cant_encode) {
3961                 encode_value (-1, p, &p);
3962         } else {
3963                 encode_value (klass->vtable_size, p, &p);
3964                 encode_value ((klass->generic_container ? (1 << 8) : 0) | (no_special_static << 7) | (klass->has_static_refs << 6) | (klass->has_references << 5) | ((klass->blittable << 4) | ((klass->ext && klass->ext->nested_classes) ? 1 : 0) << 3) | (klass->has_cctor << 2) | (klass->has_finalize << 1) | klass->ghcimpl, p, &p);
3965                 if (klass->has_cctor)
3966                         encode_method_ref (acfg, mono_class_get_cctor (klass), p, &p);
3967                 if (klass->has_finalize)
3968                         encode_method_ref (acfg, mono_class_get_finalizer (klass), p, &p);
3969  
3970                 encode_value (klass->instance_size, p, &p);
3971                 encode_value (mono_class_data_size (klass), p, &p);
3972                 encode_value (klass->packing_size, p, &p);
3973                 encode_value (klass->min_align, p, &p);
3974
3975                 for (i = 0; i < klass->vtable_size; ++i) {
3976                         MonoMethod *cm = klass->vtable [i];
3977
3978                         if (cm)
3979                                 encode_method_ref (acfg, cm, p, &p);
3980                         else
3981                                 encode_value (0, p, &p);
3982                 }
3983         }
3984
3985         acfg->stats.class_info_size += p - buf;
3986
3987         g_assert (p - buf < buf_size);
3988         res = add_to_blob (acfg, buf, p - buf);
3989         g_free (buf);
3990
3991         return res;
3992 }
3993
3994 static char*
3995 get_plt_entry_debug_sym (MonoAotCompile *acfg, MonoJumpInfo *ji, GHashTable *cache)
3996 {
3997         char *debug_sym;
3998
3999         switch (ji->type) {
4000         case MONO_PATCH_INFO_METHOD:
4001                 debug_sym = get_debug_sym (ji->data.method, "plt_", cache);
4002                 break;
4003         case MONO_PATCH_INFO_INTERNAL_METHOD:
4004                 debug_sym = g_strdup_printf ("plt__jit_icall_%s", ji->data.name);
4005                 break;
4006         case MONO_PATCH_INFO_CLASS_INIT:
4007                 debug_sym = g_strdup_printf ("plt__class_init_%s", mono_type_get_name (&ji->data.klass->byval_arg));
4008                 sanitize_symbol (debug_sym);
4009                 break;
4010         case MONO_PATCH_INFO_RGCTX_FETCH:
4011                 debug_sym = g_strdup_printf ("plt__rgctx_fetch_%d", acfg->label_generator ++);
4012                 break;
4013         case MONO_PATCH_INFO_ICALL_ADDR: {
4014                 char *s = get_debug_sym (ji->data.method, "", cache);
4015                 
4016                 debug_sym = g_strdup_printf ("plt__icall_native_%s", s);
4017                 g_free (s);
4018                 break;
4019         }
4020         case MONO_PATCH_INFO_JIT_ICALL_ADDR:
4021                 debug_sym = g_strdup_printf ("plt__jit_icall_native_%s", ji->data.name);
4022                 break;
4023         case MONO_PATCH_INFO_GENERIC_CLASS_INIT:
4024                 debug_sym = g_strdup_printf ("plt__generic_class_init");
4025                 break;
4026         default:
4027                 break;
4028         }
4029
4030         return debug_sym;
4031 }
4032
4033 /*
4034  * Calls made from AOTed code are routed through a table of jumps similar to the
4035  * ELF PLT (Program Linkage Table). Initially the PLT entries jump to code which transfers
4036  * control to the AOT runtime through a trampoline.
4037  */
4038 static void
4039 emit_plt (MonoAotCompile *acfg)
4040 {
4041         char symbol [128];
4042         int i;
4043         GHashTable *cache;
4044
4045         cache = g_hash_table_new (g_str_hash, g_str_equal);
4046
4047         emit_line (acfg);
4048         sprintf (symbol, "plt");
4049
4050         emit_section_change (acfg, ".text", 0);
4051         emit_alignment (acfg, NACL_SIZE(16, kNaClAlignment));
4052         emit_label (acfg, symbol);
4053         emit_label (acfg, acfg->plt_symbol);
4054
4055         for (i = 0; i < acfg->plt_offset; ++i) {
4056                 char *debug_sym = NULL;
4057                 MonoPltEntry *plt_entry = NULL;
4058                 MonoJumpInfo *ji;
4059
4060                 if (i == 0)
4061                         /* 
4062                          * The first plt entry is unused.
4063                          */
4064                         continue;
4065
4066                 plt_entry = g_hash_table_lookup (acfg->plt_offset_to_entry, GUINT_TO_POINTER (i));
4067                 ji = plt_entry->ji;
4068
4069                 if (acfg->llvm) {
4070                         /*
4071                          * If the target is directly callable, alias the plt symbol to point to
4072                          * the method code.
4073                          * FIXME: Use this to simplify emit_and_reloc_code ().
4074                          * FIXME: Avoid the got slot.
4075                          * FIXME: Add support to the binary writer.
4076                          */
4077                         if (ji && is_direct_callable (acfg, NULL, ji) && !acfg->use_bin_writer) {
4078                                 MonoCompile *callee_cfg = g_hash_table_lookup (acfg->method_to_cfg, ji->data.method);
4079
4080                                 if (acfg->thumb_mixed && !callee_cfg->compile_llvm) {
4081                                         /* LLVM calls the PLT entries using bl, so emit a stub */
4082                                         emit_label (acfg, plt_entry->llvm_symbol);
4083                                         fprintf (acfg->fp, ".thumb_func\n");
4084                                         fprintf (acfg->fp, "bx pc\n");
4085                                         fprintf (acfg->fp, "nop\n");
4086                                         fprintf (acfg->fp, ".arm\n");
4087                                         fprintf (acfg->fp, "b %s\n", callee_cfg->asm_symbol);
4088                                 } else {
4089                                         fprintf (acfg->fp, "\n.set %s, %s\n", plt_entry->llvm_symbol, callee_cfg->asm_symbol);
4090                                 }
4091                                 continue;
4092                         }
4093                 }
4094
4095                 if (acfg->aot_opts.write_symbols)
4096                         plt_entry->debug_sym = get_plt_entry_debug_sym (acfg, ji, cache);
4097                 debug_sym = plt_entry->debug_sym;
4098
4099                 if (acfg->thumb_mixed && !plt_entry->jit_used)
4100                         /* Emit only a thumb version */
4101                         continue;
4102
4103                 if (!acfg->thumb_mixed)
4104                         emit_label (acfg, plt_entry->llvm_symbol);
4105
4106                 if (debug_sym) {
4107                         emit_local_symbol (acfg, debug_sym, NULL, TRUE);
4108                         emit_label (acfg, debug_sym);
4109                 }
4110
4111                 emit_label (acfg, plt_entry->symbol);
4112
4113                 arch_emit_plt_entry (acfg, i);
4114
4115                 if (debug_sym)
4116                         emit_symbol_size (acfg, debug_sym, ".");
4117         }
4118
4119         if (acfg->thumb_mixed) {
4120                 /* 
4121                  * Emit a separate set of PLT entries using thumb2 which is called by LLVM generated
4122                  * code.
4123                  */
4124                 for (i = 0; i < acfg->plt_offset; ++i) {
4125                         char *debug_sym = NULL;
4126                         MonoPltEntry *plt_entry = NULL;
4127                         MonoJumpInfo *ji;
4128
4129                         if (i == 0)
4130                                 continue;
4131
4132                         plt_entry = g_hash_table_lookup (acfg->plt_offset_to_entry, GUINT_TO_POINTER (i));
4133                         ji = plt_entry->ji;
4134
4135                         if (ji && is_direct_callable (acfg, NULL, ji) && !acfg->use_bin_writer)
4136                                 continue;
4137
4138                         /* Skip plt entries not actually called by LLVM code */
4139                         if (!plt_entry->llvm_used)
4140                                 continue;
4141
4142                         if (acfg->aot_opts.write_symbols) {
4143                                 if (plt_entry->debug_sym)
4144                                         debug_sym = g_strdup_printf ("%s_thumb", plt_entry->debug_sym);
4145                         }
4146
4147                         if (debug_sym) {
4148                                 emit_local_symbol (acfg, debug_sym, NULL, TRUE);
4149                                 emit_label (acfg, debug_sym);
4150                         }
4151
4152                         emit_label (acfg, plt_entry->llvm_symbol);
4153
4154                         arch_emit_llvm_plt_entry (acfg, i);
4155
4156                         if (debug_sym) {
4157                                 emit_symbol_size (acfg, debug_sym, ".");
4158                                 g_free (debug_sym);
4159                         }
4160                 }
4161         }
4162
4163         emit_symbol_size (acfg, acfg->plt_symbol, ".");
4164
4165         sprintf (symbol, "plt_end");
4166         emit_label (acfg, symbol);
4167
4168         g_hash_table_destroy (cache);
4169 }
4170
4171 static G_GNUC_UNUSED void
4172 emit_trampoline (MonoAotCompile *acfg, int got_offset, MonoTrampInfo *info)
4173 {
4174         char start_symbol [256];
4175         char symbol [256];
4176         guint32 buf_size, info_offset;
4177         MonoJumpInfo *patch_info;
4178         guint8 *buf, *p;
4179         GPtrArray *patches;
4180         char *name;
4181         guint8 *code;
4182         guint32 code_size;
4183         MonoJumpInfo *ji;
4184         GSList *unwind_ops;
4185
4186         name = info->name;
4187         code = info->code;
4188         code_size = info->code_size;
4189         ji = info->ji;
4190         unwind_ops = info->unwind_ops;
4191
4192 #ifdef __native_client_codegen__
4193         mono_nacl_fix_patches (code, ji);
4194 #endif
4195
4196         /* Emit code */
4197
4198         sprintf (start_symbol, "%s", name);
4199
4200         emit_section_change (acfg, ".text", 0);
4201         emit_global (acfg, start_symbol, TRUE);
4202         emit_alignment (acfg, AOT_FUNC_ALIGNMENT);
4203         emit_label (acfg, start_symbol);
4204
4205         sprintf (symbol, "%snamed_%s", acfg->temp_prefix, name);
4206         emit_label (acfg, symbol);
4207
4208         /* 
4209          * The code should access everything through the GOT, so we pass
4210          * TRUE here.
4211          */
4212         emit_and_reloc_code (acfg, NULL, code, code_size, ji, TRUE);
4213
4214         emit_symbol_size (acfg, start_symbol, ".");
4215
4216         /* Emit info */
4217
4218         /* Sort relocations */
4219         patches = g_ptr_array_new ();
4220         for (patch_info = ji; patch_info; patch_info = patch_info->next)
4221                 if (patch_info->type != MONO_PATCH_INFO_NONE)
4222                         g_ptr_array_add (patches, patch_info);
4223         g_ptr_array_sort (patches, compare_patches);
4224
4225         buf_size = patches->len * 128 + 128;
4226         buf = g_malloc (buf_size);
4227         p = buf;
4228
4229         encode_patch_list (acfg, patches, patches->len, got_offset, p, &p);
4230         g_assert (p - buf < buf_size);
4231
4232         sprintf (symbol, "%s_p", name);
4233
4234         info_offset = add_to_blob (acfg, buf, p - buf);
4235
4236         emit_section_change (acfg, RODATA_SECT, 0);
4237         emit_global (acfg, symbol, FALSE);
4238         emit_label (acfg, symbol);
4239
4240         emit_int32 (acfg, info_offset);
4241
4242         /* Emit debug info */
4243         if (unwind_ops) {
4244                 char symbol2 [256];
4245
4246                 sprintf (symbol, "%s", name);
4247                 sprintf (symbol2, "%snamed_%s", acfg->temp_prefix, name);
4248
4249                 if (acfg->dwarf)
4250                         mono_dwarf_writer_emit_trampoline (acfg->dwarf, symbol, symbol2, NULL, NULL, code_size, unwind_ops);
4251         }
4252 }
4253
4254 static void
4255 emit_trampolines (MonoAotCompile *acfg)
4256 {
4257         char symbol [256];
4258         int i, tramp_got_offset;
4259         MonoAotTrampoline ntype;
4260 #ifdef MONO_ARCH_HAVE_FULL_AOT_TRAMPOLINES
4261         int tramp_type;
4262         guint8 *code;
4263 #endif
4264
4265         if (!acfg->aot_opts.full_aot)
4266                 return;
4267         
4268         g_assert (acfg->image->assembly);
4269
4270         /* Currently, we emit most trampolines into the mscorlib AOT image. */
4271         if (strcmp (acfg->image->assembly->aname.name, "mscorlib") == 0) {
4272 #ifdef MONO_ARCH_HAVE_FULL_AOT_TRAMPOLINES
4273                 MonoTrampInfo *info;
4274
4275                 /*
4276                  * Emit the generic trampolines.
4277                  *
4278                  * We could save some code by treating the generic trampolines as a wrapper
4279                  * method, but that approach has its own complexities, so we choose the simpler
4280                  * method.
4281                  */
4282                 for (tramp_type = 0; tramp_type < MONO_TRAMPOLINE_NUM; ++tramp_type) {
4283                         mono_arch_create_generic_trampoline (tramp_type, &info, TRUE);
4284                         emit_trampoline (acfg, acfg->got_offset, info);
4285                 }
4286
4287                 mono_arch_get_nullified_class_init_trampoline (&info);
4288                 emit_trampoline (acfg, acfg->got_offset, info);
4289 #if defined(MONO_ARCH_MONITOR_OBJECT_REG)
4290                 mono_arch_create_monitor_enter_trampoline (&info, TRUE);
4291                 emit_trampoline (acfg, acfg->got_offset, info);
4292                 mono_arch_create_monitor_exit_trampoline (&info, TRUE);
4293                 emit_trampoline (acfg, acfg->got_offset, info);
4294 #endif
4295
4296                 mono_arch_create_generic_class_init_trampoline (&info, TRUE);
4297                 emit_trampoline (acfg, acfg->got_offset, info);
4298
4299                 /* Emit the exception related code pieces */
4300                 code = mono_arch_get_restore_context (&info, TRUE);
4301                 emit_trampoline (acfg, acfg->got_offset, info);
4302                 code = mono_arch_get_call_filter (&info, TRUE);
4303                 emit_trampoline (acfg, acfg->got_offset, info);
4304                 code = mono_arch_get_throw_exception (&info, TRUE);
4305                 emit_trampoline (acfg, acfg->got_offset, info);
4306                 code = mono_arch_get_rethrow_exception (&info, TRUE);
4307                 emit_trampoline (acfg, acfg->got_offset, info);
4308                 code = mono_arch_get_throw_corlib_exception (&info, TRUE);
4309                 emit_trampoline (acfg, acfg->got_offset, info);
4310
4311 #if defined(MONO_ARCH_HAVE_GET_TRAMPOLINES)
4312                 {
4313                         GSList *l = mono_arch_get_trampolines (TRUE);
4314
4315                         while (l) {
4316                                 MonoTrampInfo *info = l->data;
4317
4318                                 emit_trampoline (acfg, acfg->got_offset, info);
4319                                 l = l->next;
4320                         }
4321                 }
4322 #endif
4323
4324                 for (i = 0; i < 128; ++i) {
4325                         int offset;
4326
4327                         offset = MONO_RGCTX_SLOT_MAKE_RGCTX (i);
4328                         code = mono_arch_create_rgctx_lazy_fetch_trampoline (offset, &info, TRUE);
4329                         emit_trampoline (acfg, acfg->got_offset, info);
4330
4331                         offset = MONO_RGCTX_SLOT_MAKE_MRGCTX (i);
4332                         code = mono_arch_create_rgctx_lazy_fetch_trampoline (offset, &info, TRUE);
4333                         emit_trampoline (acfg, acfg->got_offset, info);
4334                 }
4335
4336                 {
4337                         GSList *l;
4338
4339                         /* delegate_invoke_impl trampolines */
4340                         l = mono_arch_get_delegate_invoke_impls ();
4341                         while (l) {
4342                                 MonoTrampInfo *info = l->data;
4343
4344                                 emit_trampoline (acfg, acfg->got_offset, info);
4345                                 l = l->next;
4346                         }
4347                 }
4348
4349 #endif /* #ifdef MONO_ARCH_HAVE_FULL_AOT_TRAMPOLINES */
4350
4351                 /* Emit trampolines which are numerous */
4352
4353                 /*
4354                  * These include the following:
4355                  * - specific trampolines
4356                  * - static rgctx invoke trampolines
4357                  * - imt thunks
4358                  * These trampolines have the same code, they are parameterized by GOT 
4359                  * slots. 
4360                  * They are defined in this file, in the arch_... routines instead of
4361                  * in tramp-<ARCH>.c, since it is easier to do it this way.
4362                  */
4363
4364                 /*
4365                  * When running in aot-only mode, we can't create specific trampolines at 
4366                  * runtime, so we create a few, and save them in the AOT file. 
4367                  * Normal trampolines embed their argument as a literal inside the 
4368                  * trampoline code, we can't do that here, so instead we embed an offset
4369                  * which needs to be added to the trampoline address to get the address of
4370                  * the GOT slot which contains the argument value.
4371                  * The generated trampolines jump to the generic trampolines using another
4372                  * GOT slot, which will be setup by the AOT loader to point to the 
4373                  * generic trampoline code of the given type.
4374                  */
4375
4376                 /*
4377                  * FIXME: Maybe we should use more specific trampolines (i.e. one class init for
4378                  * each class).
4379                  */
4380
4381                 emit_section_change (acfg, ".text", 0);
4382
4383                 tramp_got_offset = acfg->got_offset;
4384
4385                 for (ntype = 0; ntype < MONO_AOT_TRAMP_NUM; ++ntype) {
4386                         switch (ntype) {
4387                         case MONO_AOT_TRAMP_SPECIFIC:
4388                                 sprintf (symbol, "specific_trampolines");
4389                                 break;
4390                         case MONO_AOT_TRAMP_STATIC_RGCTX:
4391                                 sprintf (symbol, "static_rgctx_trampolines");
4392                                 break;
4393                         case MONO_AOT_TRAMP_IMT_THUNK:
4394                                 sprintf (symbol, "imt_thunks");
4395                                 break;
4396                         default:
4397                                 g_assert_not_reached ();
4398                         }
4399
4400                         emit_alignment (acfg, AOT_FUNC_ALIGNMENT);
4401                         emit_label (acfg, symbol);
4402
4403                         acfg->trampoline_got_offset_base [ntype] = tramp_got_offset;
4404
4405                         for (i = 0; i < acfg->num_trampolines [ntype]; ++i) {
4406                                 int tramp_size = 0;
4407
4408                                 switch (ntype) {
4409                                 case MONO_AOT_TRAMP_SPECIFIC:
4410                                         arch_emit_specific_trampoline (acfg, tramp_got_offset, &tramp_size);
4411                                         tramp_got_offset += 2;
4412                                 break;
4413                                 case MONO_AOT_TRAMP_STATIC_RGCTX:
4414                                         arch_emit_static_rgctx_trampoline (acfg, tramp_got_offset, &tramp_size);                                
4415                                         tramp_got_offset += 2;
4416                                         break;
4417                                 case MONO_AOT_TRAMP_IMT_THUNK:
4418                                         arch_emit_imt_thunk (acfg, tramp_got_offset, &tramp_size);
4419                                         tramp_got_offset += 1;
4420                                         break;
4421                                 default:
4422                                         g_assert_not_reached ();
4423                                 }
4424 #ifdef __native_client_codegen__
4425                                 /* align to avoid 32-byte boundary crossings */
4426                                 emit_alignment (acfg, AOT_FUNC_ALIGNMENT);
4427 #endif
4428
4429                                 if (!acfg->trampoline_size [ntype]) {
4430                                         g_assert (tramp_size);
4431                                         acfg->trampoline_size [ntype] = tramp_size;
4432                                 }
4433                         }
4434                 }
4435
4436                 /* Reserve some entries at the end of the GOT for our use */
4437                 acfg->num_trampoline_got_entries = tramp_got_offset - acfg->got_offset;
4438         }
4439
4440         acfg->got_offset += acfg->num_trampoline_got_entries;
4441 }
4442
4443 static gboolean
4444 str_begins_with (const char *str1, const char *str2)
4445 {
4446         int len = strlen (str2);
4447         return strncmp (str1, str2, len) == 0;
4448 }
4449
4450 static void
4451 mono_aot_parse_options (const char *aot_options, MonoAotOptions *opts)
4452 {
4453         gchar **args, **ptr;
4454
4455         args = g_strsplit (aot_options ? aot_options : "", ",", -1);
4456         for (ptr = args; ptr && *ptr; ptr ++) {
4457                 const char *arg = *ptr;
4458
4459                 if (str_begins_with (arg, "outfile=")) {
4460                         opts->outfile = g_strdup (arg + strlen ("outfile="));
4461                 } else if (str_begins_with (arg, "save-temps")) {
4462                         opts->save_temps = TRUE;
4463                 } else if (str_begins_with (arg, "keep-temps")) {
4464                         opts->save_temps = TRUE;
4465                 } else if (str_begins_with (arg, "write-symbols")) {
4466                         opts->write_symbols = TRUE;
4467                 } else if (str_begins_with (arg, "metadata-only")) {
4468                         opts->metadata_only = TRUE;
4469                 } else if (str_begins_with (arg, "bind-to-runtime-version")) {
4470                         opts->bind_to_runtime_version = TRUE;
4471                 } else if (str_begins_with (arg, "full")) {
4472                         opts->full_aot = TRUE;
4473                 } else if (str_begins_with (arg, "threads=")) {
4474                         opts->nthreads = atoi (arg + strlen ("threads="));
4475                 } else if (str_begins_with (arg, "static")) {
4476                         opts->static_link = TRUE;
4477                         opts->no_dlsym = TRUE;
4478                 } else if (str_begins_with (arg, "asmonly")) {
4479                         opts->asm_only = TRUE;
4480                 } else if (str_begins_with (arg, "asmwriter")) {
4481                         opts->asm_writer = TRUE;
4482                 } else if (str_begins_with (arg, "nodebug")) {
4483                         opts->nodebug = TRUE;
4484                 } else if (str_begins_with (arg, "ntrampolines=")) {
4485                         opts->ntrampolines = atoi (arg + strlen ("ntrampolines="));
4486                 } else if (str_begins_with (arg, "nrgctx-trampolines=")) {
4487                         opts->nrgctx_trampolines = atoi (arg + strlen ("nrgctx-trampolines="));
4488                 } else if (str_begins_with (arg, "nimt-trampolines=")) {
4489                         opts->nimt_trampolines = atoi (arg + strlen ("nimt-trampolines="));
4490                 } else if (str_begins_with (arg, "autoreg")) {
4491                         opts->autoreg = TRUE;
4492                 } else if (str_begins_with (arg, "tool-prefix=")) {
4493                         opts->tool_prefix = g_strdup (arg + strlen ("tool-prefix="));
4494                 } else if (str_begins_with (arg, "soft-debug")) {
4495                         opts->soft_debug = TRUE;
4496                 } else if (str_begins_with (arg, "print-skipped")) {
4497                         opts->print_skipped_methods = TRUE;
4498                 } else if (str_begins_with (arg, "stats")) {
4499                         opts->stats = TRUE;
4500                 } else if (str_begins_with (arg, "mtriple=")) {
4501                         opts->mtriple = g_strdup (arg + strlen ("mtriple="));
4502                 } else {
4503                         fprintf (stderr, "AOT : Unknown argument '%s'.\n", arg);
4504                         exit (1);
4505                 }
4506         }
4507
4508         g_strfreev (args);
4509 }
4510
4511 static void
4512 add_token_info_hash (gpointer key, gpointer value, gpointer user_data)
4513 {
4514         MonoMethod *method = (MonoMethod*)key;
4515         MonoJumpInfoToken *ji = (MonoJumpInfoToken*)value;
4516         MonoJumpInfoToken *new_ji = g_new0 (MonoJumpInfoToken, 1);
4517         MonoAotCompile *acfg = user_data;
4518
4519         new_ji->image = ji->image;
4520         new_ji->token = ji->token;
4521         g_hash_table_insert (acfg->token_info_hash, method, new_ji);
4522 }
4523
4524 static gboolean
4525 can_encode_class (MonoAotCompile *acfg, MonoClass *klass)
4526 {
4527         if (klass->type_token)
4528                 return TRUE;
4529         if ((klass->byval_arg.type == MONO_TYPE_VAR) || (klass->byval_arg.type == MONO_TYPE_MVAR))
4530                 return TRUE;
4531         if (klass->rank)
4532                 return can_encode_class (acfg, klass->element_class);
4533         return FALSE;
4534 }
4535
4536 static gboolean
4537 can_encode_patch (MonoAotCompile *acfg, MonoJumpInfo *patch_info)
4538 {
4539         switch (patch_info->type) {
4540         case MONO_PATCH_INFO_METHOD:
4541         case MONO_PATCH_INFO_METHODCONST: {
4542                 MonoMethod *method = patch_info->data.method;
4543
4544                 if (method->wrapper_type) {
4545                         switch (method->wrapper_type) {
4546                         case MONO_WRAPPER_NONE:
4547                         case MONO_WRAPPER_REMOTING_INVOKE_WITH_CHECK:
4548                         case MONO_WRAPPER_XDOMAIN_INVOKE:
4549                         case MONO_WRAPPER_STFLD:
4550                         case MONO_WRAPPER_LDFLD:
4551                         case MONO_WRAPPER_LDFLDA:
4552                         case MONO_WRAPPER_LDFLD_REMOTE:
4553                         case MONO_WRAPPER_STFLD_REMOTE:
4554                         case MONO_WRAPPER_STELEMREF:
4555                         case MONO_WRAPPER_ISINST:
4556                         case MONO_WRAPPER_PROXY_ISINST:
4557                         case MONO_WRAPPER_ALLOC:
4558                         case MONO_WRAPPER_REMOTING_INVOKE:
4559                         case MONO_WRAPPER_UNKNOWN:
4560                         case MONO_WRAPPER_WRITE_BARRIER:
4561                                 break;
4562                         case MONO_WRAPPER_MANAGED_TO_MANAGED:
4563                                 if (!strcmp (method->name, "ElementAddr"))
4564                                         return TRUE;
4565                                 else
4566                                         return FALSE;
4567                         default:
4568                                 //printf ("Skip (wrapper call): %d -> %s\n", patch_info->type, mono_method_full_name (patch_info->data.method, TRUE));
4569                                 return FALSE;
4570                         }
4571                 } else {
4572                         if (!method->token) {
4573                                 /* The method is part of a constructed type like Int[,].Set (). */
4574                                 if (!g_hash_table_lookup (acfg->token_info_hash, method)) {
4575                                         if (method->klass->rank)
4576                                                 return TRUE;
4577                                         return FALSE;
4578                                 }
4579                         }
4580                 }
4581                 break;
4582         }
4583         case MONO_PATCH_INFO_VTABLE:
4584         case MONO_PATCH_INFO_CLASS_INIT:
4585         case MONO_PATCH_INFO_DELEGATE_TRAMPOLINE:
4586         case MONO_PATCH_INFO_CLASS:
4587         case MONO_PATCH_INFO_IID:
4588         case MONO_PATCH_INFO_ADJUSTED_IID:
4589                 if (!can_encode_class (acfg, patch_info->data.klass)) {
4590                         //printf ("Skip: %s\n", mono_type_full_name (&patch_info->data.klass->byval_arg));
4591                         return FALSE;
4592                 }
4593                 break;
4594         case MONO_PATCH_INFO_RGCTX_FETCH: {
4595                 MonoJumpInfoRgctxEntry *entry = patch_info->data.rgctx_entry;
4596
4597                 if (!can_encode_patch (acfg, entry->data))
4598                         return FALSE;
4599                 break;
4600         }
4601         default:
4602                 break;
4603         }
4604
4605         return TRUE;
4606 }
4607
4608 /*
4609  * compile_method:
4610  *
4611  *   AOT compile a given method.
4612  * This function might be called by multiple threads, so it must be thread-safe.
4613  */
4614 static void
4615 compile_method (MonoAotCompile *acfg, MonoMethod *method)
4616 {
4617         MonoCompile *cfg;
4618         MonoJumpInfo *patch_info;
4619         gboolean skip;
4620         int index, depth;
4621         MonoMethod *wrapped;
4622
4623         if (acfg->aot_opts.metadata_only)
4624                 return;
4625
4626         mono_acfg_lock (acfg);
4627         index = get_method_index (acfg, method);
4628         mono_acfg_unlock (acfg);
4629
4630         /* fixme: maybe we can also precompile wrapper methods */
4631         if ((method->flags & METHOD_ATTRIBUTE_PINVOKE_IMPL) ||
4632                 (method->iflags & METHOD_IMPL_ATTRIBUTE_RUNTIME) ||
4633                 (method->flags & METHOD_ATTRIBUTE_ABSTRACT)) {
4634                 //printf ("Skip (impossible): %s\n", mono_method_full_name (method, TRUE));
4635                 return;
4636         }
4637
4638         if (method->iflags & METHOD_IMPL_ATTRIBUTE_INTERNAL_CALL)
4639                 return;
4640
4641         wrapped = mono_marshal_method_from_wrapper (method);
4642         if (wrapped && (wrapped->iflags & METHOD_IMPL_ATTRIBUTE_INTERNAL_CALL) && wrapped->is_generic)
4643                 // FIXME: The wrapper should be generic too, but it is not
4644                 return;
4645
4646         InterlockedIncrement (&acfg->stats.mcount);
4647
4648 #if 0
4649         if (method->is_generic || method->klass->generic_container) {
4650                 InterlockedIncrement (&acfg->stats.genericcount);
4651                 return;
4652         }
4653 #endif
4654
4655         //acfg->aot_opts.print_skipped_methods = TRUE;
4656
4657         /*
4658          * Since these methods are the only ones which are compiled with
4659          * AOT support, and they are not used by runtime startup/shutdown code,
4660          * the runtime will not see AOT methods during AOT compilation,so it
4661          * does not need to support them by creating a fake GOT etc.
4662          */
4663         cfg = mini_method_compile (method, acfg->opts, mono_get_root_domain (), FALSE, TRUE, 0);
4664         if (cfg->exception_type == MONO_EXCEPTION_GENERIC_SHARING_FAILED) {
4665                 //printf ("F: %s\n", mono_method_full_name (method, TRUE));
4666                 InterlockedIncrement (&acfg->stats.genericcount);
4667                 return;
4668         }
4669         if (cfg->exception_type != MONO_EXCEPTION_NONE) {
4670                 /* Let the exception happen at runtime */
4671                 return;
4672         }
4673
4674         if (cfg->disable_aot) {
4675                 if (acfg->aot_opts.print_skipped_methods)
4676                         printf ("Skip (disabled): %s\n", mono_method_full_name (method, TRUE));
4677                 InterlockedIncrement (&acfg->stats.ocount);
4678                 mono_destroy_compile (cfg);
4679                 return;
4680         }
4681
4682         /* Nullify patches which need no aot processing */
4683         for (patch_info = cfg->patch_info; patch_info; patch_info = patch_info->next) {
4684                 switch (patch_info->type) {
4685                 case MONO_PATCH_INFO_LABEL:
4686                 case MONO_PATCH_INFO_BB:
4687                         patch_info->type = MONO_PATCH_INFO_NONE;
4688                         break;
4689                 default:
4690                         break;
4691                 }
4692         }
4693
4694         /* Collect method->token associations from the cfg */
4695         mono_acfg_lock (acfg);
4696         g_hash_table_foreach (cfg->token_info_hash, add_token_info_hash, acfg);
4697         mono_acfg_unlock (acfg);
4698
4699         /*
4700          * Check for absolute addresses.
4701          */
4702         skip = FALSE;
4703         for (patch_info = cfg->patch_info; patch_info; patch_info = patch_info->next) {
4704                 switch (patch_info->type) {
4705                 case MONO_PATCH_INFO_ABS:
4706                         /* unable to handle this */
4707                         skip = TRUE;    
4708                         break;
4709                 default:
4710                         break;
4711                 }
4712         }
4713
4714         if (skip) {
4715                 if (acfg->aot_opts.print_skipped_methods)
4716                         printf ("Skip (abs call): %s\n", mono_method_full_name (method, TRUE));
4717                 InterlockedIncrement (&acfg->stats.abscount);
4718                 mono_destroy_compile (cfg);
4719                 return;
4720         }
4721
4722         /* Lock for the rest of the code */
4723         mono_acfg_lock (acfg);
4724
4725         /*
4726          * Check for methods/klasses we can't encode.
4727          */
4728         skip = FALSE;
4729         for (patch_info = cfg->patch_info; patch_info; patch_info = patch_info->next) {
4730                 if (!can_encode_patch (acfg, patch_info))
4731                         skip = TRUE;
4732         }
4733
4734         if (skip) {
4735                 if (acfg->aot_opts.print_skipped_methods)
4736                         printf ("Skip (patches): %s\n", mono_method_full_name (method, TRUE));
4737                 acfg->stats.ocount++;
4738                 mono_destroy_compile (cfg);
4739                 mono_acfg_unlock (acfg);
4740                 return;
4741         }
4742
4743         /* Adds generic instances referenced by this method */
4744         /* 
4745          * The depth is used to avoid infinite loops when generic virtual recursion is 
4746          * encountered.
4747          */
4748         depth = GPOINTER_TO_UINT (g_hash_table_lookup (acfg->method_depth, method));
4749         if (depth < 32) {
4750                 for (patch_info = cfg->patch_info; patch_info; patch_info = patch_info->next) {
4751                         switch (patch_info->type) {
4752                         case MONO_PATCH_INFO_METHOD: {
4753                                 MonoMethod *m = patch_info->data.method;
4754                                 if (m->is_inflated) {
4755                                         if (!(mono_class_generic_sharing_enabled (m->klass) &&
4756                                                   mono_method_is_generic_sharable_impl (m, FALSE)) &&
4757                                                 !method_has_type_vars (m)) {
4758                                                 if (m->iflags & METHOD_IMPL_ATTRIBUTE_INTERNAL_CALL) {
4759                                                         if (acfg->aot_opts.full_aot)
4760                                                                 add_extra_method_with_depth (acfg, mono_marshal_get_native_wrapper (m, TRUE, TRUE), depth + 1);
4761                                                 } else {
4762                                                         add_extra_method_with_depth (acfg, m, depth + 1);
4763                                                 }
4764                                         }
4765                                         add_generic_class_with_depth (acfg, m->klass, depth + 5);
4766                                 }
4767                                 if (m->wrapper_type == MONO_WRAPPER_MANAGED_TO_MANAGED && !strcmp (m->name, "ElementAddr"))
4768                                         add_extra_method_with_depth (acfg, m, depth + 1);
4769                                 break;
4770                         }
4771                         case MONO_PATCH_INFO_VTABLE: {
4772                                 MonoClass *klass = patch_info->data.klass;
4773
4774                                 if (klass->generic_class && !mono_generic_context_is_sharable (&klass->generic_class->context, FALSE))
4775                                         add_generic_class_with_depth (acfg, klass, depth + 5);
4776                                 break;
4777                         }
4778                         default:
4779                                 break;
4780                         }
4781                 }
4782         }
4783
4784         /* Determine whenever the method has GOT slots */
4785         for (patch_info = cfg->patch_info; patch_info; patch_info = patch_info->next) {
4786                 switch (patch_info->type) {
4787                 case MONO_PATCH_INFO_GOT_OFFSET:
4788                 case MONO_PATCH_INFO_NONE:
4789                 case MONO_PATCH_INFO_GC_CARD_TABLE_ADDR:
4790                         break;
4791                 case MONO_PATCH_INFO_IMAGE:
4792                         /* The assembly is stored in GOT slot 0 */
4793                         if (patch_info->data.image != acfg->image)
4794                                 cfg->has_got_slots = TRUE;
4795                         break;
4796                 default:
4797                         if (!is_plt_patch (patch_info))
4798                                 cfg->has_got_slots = TRUE;
4799                         break;
4800                 }
4801         }
4802
4803         if (!cfg->has_got_slots)
4804                 InterlockedIncrement (&acfg->stats.methods_without_got_slots);
4805
4806         /* 
4807          * FIXME: Instead of this mess, allocate the patches from the aot mempool.
4808          */
4809         /* Make a copy of the patch info which is in the mempool */
4810         {
4811                 MonoJumpInfo *patches = NULL, *patches_end = NULL;
4812
4813                 for (patch_info = cfg->patch_info; patch_info; patch_info = patch_info->next) {
4814                         MonoJumpInfo *new_patch_info = mono_patch_info_dup_mp (acfg->mempool, patch_info);
4815
4816                         if (!patches)
4817                                 patches = new_patch_info;
4818                         else
4819                                 patches_end->next = new_patch_info;
4820                         patches_end = new_patch_info;
4821                 }
4822                 cfg->patch_info = patches;
4823         }
4824         /* Make a copy of the unwind info */
4825         {
4826                 GSList *l, *unwind_ops;
4827                 MonoUnwindOp *op;
4828
4829                 unwind_ops = NULL;
4830                 for (l = cfg->unwind_ops; l; l = l->next) {
4831                         op = mono_mempool_alloc (acfg->mempool, sizeof (MonoUnwindOp));
4832                         memcpy (op, l->data, sizeof (MonoUnwindOp));
4833                         unwind_ops = g_slist_prepend_mempool (acfg->mempool, unwind_ops, op);
4834                 }
4835                 cfg->unwind_ops = g_slist_reverse (unwind_ops);
4836         }
4837         /* Make a copy of the argument/local info */
4838         {
4839                 MonoInst **args, **locals;
4840                 MonoMethodSignature *sig;
4841                 MonoMethodHeader *header;
4842                 int i;
4843                 
4844                 sig = mono_method_signature (method);
4845                 args = mono_mempool_alloc (acfg->mempool, sizeof (MonoInst*) * (sig->param_count + sig->hasthis));
4846                 for (i = 0; i < sig->param_count + sig->hasthis; ++i) {
4847                         args [i] = mono_mempool_alloc (acfg->mempool, sizeof (MonoInst));
4848                         memcpy (args [i], cfg->args [i], sizeof (MonoInst));
4849                 }
4850                 cfg->args = args;
4851
4852                 header = mono_method_get_header (method);
4853                 locals = mono_mempool_alloc (acfg->mempool, sizeof (MonoInst*) * header->num_locals);
4854                 for (i = 0; i < header->num_locals; ++i) {
4855                         locals [i] = mono_mempool_alloc (acfg->mempool, sizeof (MonoInst));
4856                         memcpy (locals [i], cfg->locals [i], sizeof (MonoInst));
4857                 }
4858                 cfg->locals = locals;
4859         }
4860
4861         /* Free some fields used by cfg to conserve memory */
4862         mono_mempool_destroy (cfg->mempool);
4863         cfg->mempool = NULL;
4864         g_free (cfg->varinfo);
4865         cfg->varinfo = NULL;
4866         g_free (cfg->vars);
4867         cfg->vars = NULL;
4868         if (cfg->rs) {
4869                 mono_regstate_free (cfg->rs);
4870                 cfg->rs = NULL;
4871         }
4872
4873         //printf ("Compile:           %s\n", mono_method_full_name (method, TRUE));
4874
4875         while (index >= acfg->cfgs_size) {
4876                 MonoCompile **new_cfgs;
4877                 int new_size;
4878
4879                 new_size = acfg->cfgs_size * 2;
4880                 new_cfgs = g_new0 (MonoCompile*, new_size);
4881                 memcpy (new_cfgs, acfg->cfgs, sizeof (MonoCompile*) * acfg->cfgs_size);
4882                 g_free (acfg->cfgs);
4883                 acfg->cfgs = new_cfgs;
4884                 acfg->cfgs_size = new_size;
4885         }
4886         acfg->cfgs [index] = cfg;
4887
4888         g_hash_table_insert (acfg->method_to_cfg, cfg->orig_method, cfg);
4889
4890         /*
4891         if (cfg->orig_method->wrapper_type)
4892                 g_ptr_array_add (acfg->extra_methods, cfg->orig_method);
4893         */
4894
4895         mono_acfg_unlock (acfg);
4896
4897         InterlockedIncrement (&acfg->stats.ccount);
4898 }
4899  
4900 static void
4901 compile_thread_main (gpointer *user_data)
4902 {
4903         MonoDomain *domain = user_data [0];
4904         MonoAotCompile *acfg = user_data [1];
4905         GPtrArray *methods = user_data [2];
4906         int i;
4907
4908         mono_thread_attach (domain);
4909
4910         for (i = 0; i < methods->len; ++i)
4911                 compile_method (acfg, g_ptr_array_index (methods, i));
4912 }
4913
4914 static void
4915 load_profile_files (MonoAotCompile *acfg)
4916 {
4917         FILE *infile;
4918         char *tmp;
4919         int file_index, res, method_index, i;
4920         char ver [256];
4921         guint32 token;
4922         GList *unordered;
4923
4924         file_index = 0;
4925         while (TRUE) {
4926                 tmp = g_strdup_printf ("%s/.mono/aot-profile-data/%s-%d", g_get_home_dir (), acfg->image->assembly_name, file_index);
4927
4928                 if (!g_file_test (tmp, G_FILE_TEST_IS_REGULAR)) {
4929                         g_free (tmp);
4930                         break;
4931                 }
4932
4933                 infile = fopen (tmp, "r");
4934                 g_assert (infile);
4935
4936                 printf ("Using profile data file '%s'\n", tmp);
4937                 g_free (tmp);
4938
4939                 file_index ++;
4940
4941                 res = fscanf (infile, "%32s\n", ver);
4942                 if ((res != 1) || strcmp (ver, "#VER:2") != 0) {
4943                         printf ("Profile file has wrong version or invalid.\n");
4944                         fclose (infile);
4945                         continue;
4946                 }
4947
4948                 while (TRUE) {
4949                         char name [1024];
4950                         MonoMethodDesc *desc;
4951                         MonoMethod *method;
4952
4953                         if (fgets (name, 1023, infile) == NULL)
4954                                 break;
4955
4956                         /* Kill the newline */
4957                         if (strlen (name) > 0)
4958                                 name [strlen (name) - 1] = '\0';
4959
4960                         desc = mono_method_desc_new (name, TRUE);
4961
4962                         method = mono_method_desc_search_in_image (desc, acfg->image);
4963
4964                         if (method && mono_method_get_token (method)) {
4965                                 token = mono_method_get_token (method);
4966                                 method_index = mono_metadata_token_index (token) - 1;
4967
4968                                 if (!g_list_find (acfg->method_order, GUINT_TO_POINTER (method_index))) {
4969                                         acfg->method_order = g_list_append (acfg->method_order, GUINT_TO_POINTER (method_index));
4970                                 }
4971                         } else {
4972                                 //printf ("No method found matching '%s'.\n", name);
4973                         }
4974                 }
4975                 fclose (infile);
4976         }
4977
4978         /* Add missing methods */
4979         unordered = NULL;
4980         for (i = 0; i < acfg->image->tables [MONO_TABLE_METHOD].rows; ++i) {
4981                 if (!g_list_find (acfg->method_order, GUINT_TO_POINTER (i)))
4982                         unordered = g_list_prepend (unordered, GUINT_TO_POINTER (i));
4983         }
4984         unordered = g_list_reverse (unordered);
4985         if (acfg->method_order)
4986                 g_list_last (acfg->method_order)->next = unordered;
4987         else
4988                 acfg->method_order = unordered;
4989 }
4990  
4991 /* Used by the LLVM backend */
4992 guint32
4993 mono_aot_get_got_offset (MonoJumpInfo *ji)
4994 {
4995         return get_got_offset (llvm_acfg, ji);
4996 }
4997
4998 char*
4999 mono_aot_get_method_name (MonoCompile *cfg)
5000 {
5001         return get_debug_sym (cfg->orig_method, "", llvm_acfg->method_label_hash);
5002 }
5003
5004 char*
5005 mono_aot_get_plt_symbol (MonoJumpInfoType type, gconstpointer data)
5006 {
5007         MonoJumpInfo *ji = mono_mempool_alloc (llvm_acfg->mempool, sizeof (MonoJumpInfo));
5008         MonoPltEntry *plt_entry;
5009
5010         ji->type = type;
5011         ji->data.target = data;
5012
5013         if (!can_encode_patch (llvm_acfg, ji))
5014                 return NULL;
5015
5016         plt_entry = get_plt_entry (llvm_acfg, ji);
5017         plt_entry->llvm_used = TRUE;
5018
5019         return g_strdup_printf (plt_entry->llvm_symbol);
5020 }
5021
5022 MonoJumpInfo*
5023 mono_aot_patch_info_dup (MonoJumpInfo* ji)
5024 {
5025         MonoJumpInfo *res;
5026
5027         mono_acfg_lock (llvm_acfg);
5028         res = mono_patch_info_dup_mp (llvm_acfg->mempool, ji);
5029         mono_acfg_unlock (llvm_acfg);
5030
5031         return res;
5032 }
5033
5034 #ifdef ENABLE_LLVM
5035
5036 /*
5037  * emit_llvm_file:
5038  *
5039  *   Emit the LLVM code into an LLVM bytecode file, and compile it using the LLVM
5040  * tools.
5041  */
5042 static void
5043 emit_llvm_file (MonoAotCompile *acfg)
5044 {
5045         char *command, *opts;
5046         int i;
5047         MonoJumpInfo *patch_info;
5048
5049         /*
5050          * When using LLVM, we let llvm emit the got since the LLVM IL needs to refer
5051          * to it.
5052          */
5053
5054         /* Compute the final size of the got */
5055         for (i = 0; i < acfg->nmethods; ++i) {
5056                 if (acfg->cfgs [i]) {
5057                         for (patch_info = acfg->cfgs [i]->patch_info; patch_info; patch_info = patch_info->next) {
5058                                 if (patch_info->type != MONO_PATCH_INFO_NONE) {
5059                                         if (!is_plt_patch (patch_info))
5060                                                 get_got_offset (acfg, patch_info);
5061                                         else
5062                                                 get_plt_entry (acfg, patch_info);
5063                                 }
5064                         }
5065                 }
5066         }
5067
5068         acfg->final_got_size = acfg->got_offset + acfg->plt_offset;
5069
5070         if (acfg->aot_opts.full_aot) {
5071                 int ntype;
5072
5073                 /* 
5074                  * Need to add the got entries used by the trampolines.
5075                  * This is only a conservative approximation.
5076                  */
5077                 if (strcmp (acfg->image->assembly->aname.name, "mscorlib") == 0) {
5078                         /* For the generic + rgctx trampolines */
5079                         acfg->final_got_size += 200;
5080                         /* For the specific trampolines */
5081                         for (ntype = 0; ntype < MONO_AOT_TRAMP_NUM; ++ntype)
5082                                 acfg->final_got_size += acfg->num_trampolines [ntype] * 2;
5083                 }
5084         }
5085
5086
5087         mono_llvm_emit_aot_module ("temp.bc", acfg->final_got_size);
5088
5089         /*
5090          * FIXME: Experiment with adding optimizations, the -std-compile-opts set takes
5091          * a lot of time, and doesn't seem to save much space.
5092          * The following optimizations cannot be enabled:
5093          * - 'tailcallelim'
5094          * - 'jump-threading' changes our blockaddress references to int constants.
5095          * The opt list below was produced by taking the output of:
5096          * llvm-as < /dev/null | opt -O2 -disable-output -debug-pass=Arguments
5097          * then removing tailcallelim + the global opts, and adding a second gvn.
5098          */
5099         opts = g_strdup ("-instcombine -simplifycfg");
5100         opts = g_strdup ("-simplifycfg -domtree -domfrontier -scalarrepl -instcombine -simplifycfg -basiccg -prune-eh -inline -functionattrs -domtree -domfrontier -scalarrepl -simplify-libcalls -instcombine -simplifycfg -instcombine -simplifycfg -reassociate -domtree -loops -loopsimplify -domfrontier -loopsimplify -lcssa -loop-rotate -licm -lcssa -loop-unswitch -instcombine -scalar-evolution -loopsimplify -lcssa -iv-users -indvars -loop-deletion -loopsimplify -lcssa -loop-unroll -instcombine -memdep -gvn -memdep -memcpyopt -sccp -instcombine -domtree -memdep -dse -adce -gvn -simplifycfg -preverify -domtree -verify");
5101 #if 1
5102         command = g_strdup_printf ("opt -f %s -o temp.opt.bc temp.bc", opts);
5103         printf ("Executing opt: %s\n", command);
5104         if (system (command) != 0) {
5105                 exit (1);
5106         }
5107 #endif
5108         g_free (opts);
5109
5110         if (!acfg->llc_args)
5111                 acfg->llc_args = g_string_new ("");
5112
5113         /* Verbose asm slows down llc greatly */
5114         g_string_append (acfg->llc_args, " -asm-verbose=false");
5115
5116         if (acfg->aot_opts.mtriple)
5117                 g_string_append_printf (acfg->llc_args, " -mtriple=%s", acfg->aot_opts.mtriple);
5118
5119         unlink (acfg->tmpfname);
5120
5121         command = g_strdup_printf ("llc %s -relocation-model=pic -unwind-tables -disable-gnu-eh-frame -enable-mono-eh-frame -o %s temp.opt.bc", acfg->llc_args->str, acfg->tmpfname);
5122
5123         printf ("Executing llc: %s\n", command);
5124
5125         if (system (command) != 0) {
5126                 exit (1);
5127         }
5128 }
5129 #endif
5130
5131 static void
5132 emit_code (MonoAotCompile *acfg)
5133 {
5134         int i;
5135         char symbol [256];
5136         char end_symbol [256];
5137         GList *l;
5138
5139 #if defined(TARGET_POWERPC64)
5140         sprintf (symbol, ".Lgot_addr");
5141         emit_section_change (acfg, ".text", 0);
5142         emit_alignment (acfg, 8);
5143         emit_label (acfg, symbol);
5144         emit_pointer (acfg, acfg->got_symbol);
5145 #endif
5146
5147         /* 
5148          * This global symbol is used to compute the address of each method using the
5149          * code_offsets array. It is also used to compute the memory ranges occupied by
5150          * AOT code, so it must be equal to the address of the first emitted method.
5151          */
5152         sprintf (symbol, "methods");
5153         emit_section_change (acfg, ".text", 0);
5154         emit_alignment (acfg, 8);
5155         if (acfg->llvm) {
5156                 for (i = 0; i < acfg->nmethods; ++i) {
5157                         if (acfg->cfgs [i] && acfg->cfgs [i]->compile_llvm) {
5158                                 fprintf (acfg->fp, "\n.set methods, %s\n", acfg->cfgs [i]->asm_symbol);
5159                                 break;
5160                         }
5161                 }
5162                 if (i == acfg->nmethods)
5163                         /* No LLVM compiled methods */
5164                         emit_label (acfg, symbol);
5165         } else {
5166                 emit_label (acfg, symbol);
5167         }
5168
5169         /* 
5170          * Emit some padding so the local symbol for the first method doesn't have the
5171          * same address as 'methods'.
5172          */
5173 #if defined(__default_codegen__)
5174         emit_zero_bytes (acfg, 16);
5175 #elif defined(__native_client_codegen__)
5176         {
5177                 const int kPaddingSize = 16;
5178                 guint8 pad_buffer[kPaddingSize];
5179                 mono_arch_nacl_pad (pad_buffer, kPaddingSize);
5180                 emit_bytes (acfg, pad_buffer, kPaddingSize);
5181         }
5182 #endif
5183         
5184
5185         for (l = acfg->method_order; l != NULL; l = l->next) {
5186                 MonoCompile *cfg;
5187                 MonoMethod *method;
5188
5189                 i = GPOINTER_TO_UINT (l->data);
5190
5191                 cfg = acfg->cfgs [i];
5192
5193                 if (!cfg)
5194                         continue;
5195
5196                 method = cfg->orig_method;
5197
5198                 /* Emit unbox trampoline */
5199                 if (acfg->aot_opts.full_aot && cfg->orig_method->klass->valuetype && (method->flags & METHOD_ATTRIBUTE_VIRTUAL)) {
5200                         char call_target [256];
5201
5202                         if (!method->wrapper_type && !method->is_inflated) {
5203                                 g_assert (method->token);
5204                                 sprintf (symbol, "ut_%d", mono_metadata_token_index (method->token) - 1);
5205                         } else {
5206                                 sprintf (symbol, "ut_e_%d", get_method_index (acfg, method));
5207                         }
5208
5209                         emit_section_change (acfg, ".text", 0);
5210 #ifdef __native_client_codegen__
5211                         emit_alignment (acfg, AOT_FUNC_ALIGNMENT);
5212 #endif
5213                         emit_global (acfg, symbol, TRUE);
5214                         emit_label (acfg, symbol);
5215
5216                         sprintf (call_target, "%s", cfg->asm_symbol);
5217
5218                         arch_emit_unbox_trampoline (acfg, cfg->orig_method, call_target);
5219                 }
5220
5221                 if (cfg->compile_llvm)
5222                         acfg->stats.llvm_count ++;
5223                 else
5224                         emit_method_code (acfg, cfg);
5225         }
5226
5227         sprintf (symbol, "methods_end");
5228         emit_section_change (acfg, ".text", 0);
5229         emit_alignment (acfg, 8);
5230         emit_label (acfg, symbol);
5231
5232         sprintf (symbol, "code_offsets");
5233         emit_section_change (acfg, RODATA_SECT, 1);
5234         emit_alignment (acfg, 8);
5235         emit_label (acfg, symbol);
5236
5237         acfg->stats.offsets_size += acfg->nmethods * 4;
5238
5239         sprintf (end_symbol, "methods");
5240         for (i = 0; i < acfg->nmethods; ++i) {
5241                 if (acfg->cfgs [i]) {
5242                         emit_symbol_diff (acfg, acfg->cfgs [i]->asm_symbol, end_symbol, 0);
5243                 } else {
5244                         emit_int32 (acfg, 0xffffffff);
5245                 }
5246         }
5247         emit_line (acfg);
5248 }
5249
5250 static void
5251 emit_info (MonoAotCompile *acfg)
5252 {
5253         int i;
5254         char symbol [256];
5255         GList *l;
5256         gint32 *offsets;
5257
5258         offsets = g_new0 (gint32, acfg->nmethods);
5259
5260         for (l = acfg->method_order; l != NULL; l = l->next) {
5261                 i = GPOINTER_TO_UINT (l->data);
5262
5263                 if (acfg->cfgs [i]) {
5264                         emit_method_info (acfg, acfg->cfgs [i]);
5265                         offsets [i] = acfg->cfgs [i]->method_info_offset;
5266                 } else {
5267                         offsets [i] = 0;
5268                 }
5269         }
5270
5271         sprintf (symbol, "method_info_offsets");
5272         emit_section_change (acfg, RODATA_SECT, 1);
5273         emit_alignment (acfg, 8);
5274         emit_label (acfg, symbol);
5275
5276         acfg->stats.offsets_size += emit_offset_table (acfg, acfg->nmethods, 10, offsets);
5277
5278         g_free (offsets);
5279 }
5280
5281 #endif /* #if !defined(DISABLE_AOT) && !defined(DISABLE_JIT) */
5282
5283 #define rot(x,k) (((x)<<(k)) | ((x)>>(32-(k))))
5284 #define mix(a,b,c) { \
5285         a -= c;  a ^= rot(c, 4);  c += b; \
5286         b -= a;  b ^= rot(a, 6);  a += c; \
5287         c -= b;  c ^= rot(b, 8);  b += a; \
5288         a -= c;  a ^= rot(c,16);  c += b; \
5289         b -= a;  b ^= rot(a,19);  a += c; \
5290         c -= b;  c ^= rot(b, 4);  b += a; \
5291 }
5292 #define final(a,b,c) { \
5293         c ^= b; c -= rot(b,14); \
5294         a ^= c; a -= rot(c,11); \
5295         b ^= a; b -= rot(a,25); \
5296         c ^= b; c -= rot(b,16); \
5297         a ^= c; a -= rot(c,4);  \
5298         b ^= a; b -= rot(a,14); \
5299         c ^= b; c -= rot(b,24); \
5300 }
5301
5302 static guint
5303 mono_aot_type_hash (MonoType *t1)
5304 {
5305         guint hash = t1->type;
5306
5307         hash |= t1->byref << 6; /* do not collide with t1->type values */
5308         switch (t1->type) {
5309         case MONO_TYPE_VALUETYPE:
5310         case MONO_TYPE_CLASS:
5311         case MONO_TYPE_SZARRAY:
5312                 /* check if the distribution is good enough */
5313                 return ((hash << 5) - hash) ^ mono_metadata_str_hash (t1->data.klass->name);
5314         case MONO_TYPE_PTR:
5315                 return ((hash << 5) - hash) ^ mono_metadata_type_hash (t1->data.type);
5316         case MONO_TYPE_ARRAY:
5317                 return ((hash << 5) - hash) ^ mono_metadata_type_hash (&t1->data.array->eklass->byval_arg);
5318         case MONO_TYPE_GENERICINST:
5319                 return ((hash << 5) - hash) ^ 0;
5320         }
5321         return hash;
5322 }
5323
5324 /*
5325  * mono_aot_method_hash:
5326  *
5327  *   Return a hash code for methods which only depends on metadata.
5328  */
5329 guint32
5330 mono_aot_method_hash (MonoMethod *method)
5331 {
5332         MonoMethodSignature *sig;
5333         MonoClass *klass;
5334         int i, hindex;
5335         int hashes_count;
5336         guint32 *hashes_start, *hashes;
5337         guint32 a, b, c;
5338         MonoGenericInst *ginst = NULL;
5339
5340         /* Similar to the hash in mono_method_get_imt_slot () */
5341
5342         sig = mono_method_signature (method);
5343
5344         if (method->is_inflated)
5345                 ginst = ((MonoMethodInflated*)method)->context.method_inst;
5346
5347         hashes_count = sig->param_count + 5 + (ginst ? ginst->type_argc : 0);
5348         hashes_start = g_malloc0 (hashes_count * sizeof (guint32));
5349         hashes = hashes_start;
5350
5351         /* Some wrappers are assigned to random classes */
5352         if (!method->wrapper_type || method->wrapper_type == MONO_WRAPPER_REMOTING_INVOKE_WITH_CHECK)
5353                 klass = method->klass;
5354         else
5355                 klass = mono_defaults.object_class;
5356
5357         if (!method->wrapper_type) {
5358                 char *full_name = mono_type_full_name (&klass->byval_arg);
5359
5360                 hashes [0] = mono_metadata_str_hash (full_name);
5361                 hashes [1] = 0;
5362                 g_free (full_name);
5363         } else {
5364                 hashes [0] = mono_metadata_str_hash (klass->name);
5365                 hashes [1] = mono_metadata_str_hash (klass->name_space);
5366         }
5367         if (method->wrapper_type == MONO_WRAPPER_STFLD || method->wrapper_type == MONO_WRAPPER_LDFLD || method->wrapper_type == MONO_WRAPPER_LDFLDA)
5368                 /* The method name includes a stringified pointer */
5369                 hashes [2] = 0;
5370         else
5371                 hashes [2] = mono_metadata_str_hash (method->name);
5372         hashes [3] = method->wrapper_type;
5373         hashes [4] = mono_aot_type_hash (sig->ret);
5374         hindex = 5;
5375         for (i = 0; i < sig->param_count; i++) {
5376                 hashes [hindex ++] = mono_aot_type_hash (sig->params [i]);
5377         }
5378         if (ginst) {
5379                 for (i = 0; i < ginst->type_argc; ++i)
5380                         hashes [hindex ++] = mono_aot_type_hash (ginst->type_argv [i]);
5381         }               
5382         g_assert (hindex == hashes_count);
5383
5384         /* Setup internal state */
5385         a = b = c = 0xdeadbeef + (((guint32)hashes_count)<<2);
5386
5387         /* Handle most of the hashes */
5388         while (hashes_count > 3) {
5389                 a += hashes [0];
5390                 b += hashes [1];
5391                 c += hashes [2];
5392                 mix (a,b,c);
5393                 hashes_count -= 3;
5394                 hashes += 3;
5395         }
5396
5397         /* Handle the last 3 hashes (all the case statements fall through) */
5398         switch (hashes_count) { 
5399         case 3 : c += hashes [2];
5400         case 2 : b += hashes [1];
5401         case 1 : a += hashes [0];
5402                 final (a,b,c);
5403         case 0: /* nothing left to add */
5404                 break;
5405         }
5406         
5407         free (hashes_start);
5408         
5409         return c;
5410 }
5411 #undef rot
5412 #undef mix
5413 #undef final
5414
5415 /*
5416  * mono_aot_wrapper_name:
5417  *
5418  *   Return a string which uniqely identifies the given wrapper method.
5419  */
5420 char*
5421 mono_aot_wrapper_name (MonoMethod *method)
5422 {
5423         char *name, *tmpsig, *klass_desc;
5424
5425         tmpsig = mono_signature_get_desc (mono_method_signature (method), TRUE);
5426
5427         switch (method->wrapper_type) {
5428         case MONO_WRAPPER_RUNTIME_INVOKE:
5429                 if (!strcmp (method->name, "runtime_invoke_dynamic"))
5430                         name = g_strdup_printf ("(wrapper runtime-invoke-dynamic)");
5431                 else
5432                         name = g_strdup_printf ("%s (%s)", method->name, tmpsig);
5433                 break;
5434         default:
5435                 klass_desc = mono_type_full_name (&method->klass->byval_arg);
5436                 name = g_strdup_printf ("%s:%s (%s)", klass_desc, method->name, tmpsig);
5437                 g_free (klass_desc);
5438                 break;
5439         }
5440
5441         g_free (tmpsig);
5442
5443         return name;
5444 }
5445
5446 /*
5447  * mono_aot_get_array_helper_from_wrapper;
5448  *
5449  * Get the helper method in Array called by an array wrapper method.
5450  */
5451 MonoMethod*
5452 mono_aot_get_array_helper_from_wrapper (MonoMethod *method)
5453 {
5454         MonoMethod *m;
5455         const char *prefix;
5456         MonoGenericContext ctx;
5457         MonoType *args [16];
5458         char *mname, *iname, *s, *s2, *helper_name = NULL;
5459
5460         prefix = "System.Collections.Generic";
5461         s = g_strdup_printf ("%s", method->name + strlen (prefix) + 1);
5462         s2 = strstr (s, "`1.");
5463         g_assert (s2);
5464         s2 [0] = '\0';
5465         iname = s;
5466         mname = s2 + 3;
5467
5468         //printf ("X: %s %s\n", iname, mname);
5469
5470         if (!strcmp (iname, "IList"))
5471                 helper_name = g_strdup_printf ("InternalArray__%s", mname);
5472         else
5473                 helper_name = g_strdup_printf ("InternalArray__%s_%s", iname, mname);
5474         m = mono_class_get_method_from_name (mono_defaults.array_class, helper_name, mono_method_signature (method)->param_count);
5475         g_assert (m);
5476         g_free (helper_name);
5477         g_free (s);
5478
5479         if (m->is_generic) {
5480                 memset (&ctx, 0, sizeof (ctx));
5481                 args [0] = &method->klass->element_class->byval_arg;
5482                 ctx.method_inst = mono_metadata_get_generic_inst (1, args);
5483                 m = mono_class_inflate_generic_method (m, &ctx);
5484         }
5485
5486         return m;
5487 }
5488
5489 #if !defined(DISABLE_AOT) && !defined(DISABLE_JIT)
5490
5491 typedef struct HashEntry {
5492     guint32 key, value, index;
5493         struct HashEntry *next;
5494 } HashEntry;
5495
5496 /*
5497  * emit_extra_methods:
5498  *
5499  * Emit methods which are not in the METHOD table, like wrappers.
5500  */
5501 static void
5502 emit_extra_methods (MonoAotCompile *acfg)
5503 {
5504         int i, table_size, buf_size;
5505         char symbol [256];
5506         guint8 *p, *buf;
5507         guint32 *info_offsets;
5508         guint32 hash;
5509         GPtrArray *table;
5510         HashEntry *entry, *new_entry;
5511         int nmethods, max_chain_length;
5512         int *chain_lengths;
5513
5514         info_offsets = g_new0 (guint32, acfg->extra_methods->len);
5515
5516         /* Emit method info */
5517         nmethods = 0;
5518         for (i = 0; i < acfg->extra_methods->len; ++i) {
5519                 MonoMethod *method = g_ptr_array_index (acfg->extra_methods, i);
5520                 MonoCompile *cfg = g_hash_table_lookup (acfg->method_to_cfg, method);
5521                 char *name;
5522
5523                 if (!cfg)
5524                         continue;
5525
5526                 buf_size = 10240;
5527                 p = buf = g_malloc (buf_size);
5528
5529                 nmethods ++;
5530
5531                 method = cfg->method_to_register;
5532
5533                 name = NULL;
5534                 if (method->wrapper_type) {
5535                         gboolean encode_ref = FALSE;
5536
5537                         /* 
5538                          * We encode some wrappers using their name, since encoding them
5539                          * directly would be difficult. This works because at runtime, we only need to
5540                          * check whenever a method ref matches an existing MonoMethod. The downside is
5541                          * that the method names are large, so we use the binary encoding if possible.
5542                          */
5543                         switch (method->wrapper_type) {
5544                         case MONO_WRAPPER_REMOTING_INVOKE_WITH_CHECK:
5545                         case MONO_WRAPPER_SYNCHRONIZED:
5546                                 encode_ref = TRUE;
5547                                 break;
5548                         case MONO_WRAPPER_MANAGED_TO_NATIVE:
5549                                 /* Skip JIT icall wrappers */
5550                                 if (!strstr (method->name, "__icall_wrapper"))
5551                                         encode_ref = TRUE;
5552                                 break;
5553                         case MONO_WRAPPER_UNKNOWN:
5554                                 if (!strcmp (method->name, "PtrToStructure") || !strcmp (method->name, "StructureToPtr"))
5555                                         encode_ref = TRUE;
5556                                 break;
5557                         case MONO_WRAPPER_RUNTIME_INVOKE:
5558                                 if (mono_marshal_method_from_wrapper (method) != method && !strstr (method->name, "virtual"))
5559                                         /* Direct wrapper, encode normally */
5560                                         encode_ref = TRUE;
5561                                 break;
5562                         default:
5563                                 break;
5564                         }
5565
5566                         if (!encode_ref)
5567                                 name = mono_aot_wrapper_name (method);
5568                 }
5569
5570                 if (name) {
5571                         encode_value (1, p, &p);
5572                         encode_value (method->wrapper_type, p, &p);
5573                         strcpy ((char*)p, name);
5574                         p += strlen (name ) + 1;
5575                         g_free (name);
5576                 } else {
5577                         encode_value (0, p, &p);
5578                         encode_method_ref (acfg, method, p, &p);
5579                 }
5580
5581                 g_assert ((p - buf) < buf_size);
5582
5583                 info_offsets [i] = add_to_blob (acfg, buf, p - buf);
5584                 g_free (buf);
5585         }
5586
5587         /*
5588          * Construct a chained hash table for mapping indexes in extra_method_info to
5589          * method indexes.
5590          */
5591         table_size = g_spaced_primes_closest ((int)(nmethods * 1.5));
5592         table = g_ptr_array_sized_new (table_size);
5593         for (i = 0; i < table_size; ++i)
5594                 g_ptr_array_add (table, NULL);
5595         chain_lengths = g_new0 (int, table_size);
5596         max_chain_length = 0;
5597         for (i = 0; i < acfg->extra_methods->len; ++i) {
5598                 MonoMethod *method = g_ptr_array_index (acfg->extra_methods, i);
5599                 MonoCompile *cfg = g_hash_table_lookup (acfg->method_to_cfg, method);
5600                 guint32 key, value;
5601
5602                 if (!cfg)
5603                         continue;
5604
5605                 key = info_offsets [i];
5606                 value = get_method_index (acfg, method);
5607
5608                 hash = mono_aot_method_hash (method) % table_size;
5609
5610                 chain_lengths [hash] ++;
5611                 max_chain_length = MAX (max_chain_length, chain_lengths [hash]);
5612
5613                 new_entry = mono_mempool_alloc0 (acfg->mempool, sizeof (HashEntry));
5614                 new_entry->key = key;
5615                 new_entry->value = value;
5616
5617                 entry = g_ptr_array_index (table, hash);
5618                 if (entry == NULL) {
5619                         new_entry->index = hash;
5620                         g_ptr_array_index (table, hash) = new_entry;
5621                 } else {
5622                         while (entry->next)
5623                                 entry = entry->next;
5624                         
5625                         entry->next = new_entry;
5626                         new_entry->index = table->len;
5627                         g_ptr_array_add (table, new_entry);
5628                 }
5629         }
5630
5631         //printf ("MAX: %d\n", max_chain_length);
5632
5633         /* Emit the table */
5634         sprintf (symbol, "extra_method_table");
5635         emit_section_change (acfg, RODATA_SECT, 0);
5636         emit_alignment (acfg, 8);
5637         emit_label (acfg, symbol);
5638
5639         emit_int32 (acfg, table_size);
5640         for (i = 0; i < table->len; ++i) {
5641                 HashEntry *entry = g_ptr_array_index (table, i);
5642
5643                 if (entry == NULL) {
5644                         emit_int32 (acfg, 0);
5645                         emit_int32 (acfg, 0);
5646                         emit_int32 (acfg, 0);
5647                 } else {
5648                         //g_assert (entry->key > 0);
5649                         emit_int32 (acfg, entry->key);
5650                         emit_int32 (acfg, entry->value);
5651                         if (entry->next)
5652                                 emit_int32 (acfg, entry->next->index);
5653                         else
5654                                 emit_int32 (acfg, 0);
5655                 }
5656         }
5657
5658         /* 
5659          * Emit a table reverse mapping method indexes to their index in extra_method_info.
5660          * This is used by mono_aot_find_jit_info ().
5661          */
5662         sprintf (symbol, "extra_method_info_offsets");
5663         emit_section_change (acfg, RODATA_SECT, 0);
5664         emit_alignment (acfg, 8);
5665         emit_label (acfg, symbol);
5666
5667         emit_int32 (acfg, acfg->extra_methods->len);
5668         for (i = 0; i < acfg->extra_methods->len; ++i) {
5669                 MonoMethod *method = g_ptr_array_index (acfg->extra_methods, i);
5670
5671                 emit_int32 (acfg, get_method_index (acfg, method));
5672                 emit_int32 (acfg, info_offsets [i]);
5673         }
5674 }       
5675
5676 static void
5677 emit_exception_info (MonoAotCompile *acfg)
5678 {
5679         int i;
5680         char symbol [256];
5681         gint32 *offsets;
5682
5683         offsets = g_new0 (gint32, acfg->nmethods);
5684         for (i = 0; i < acfg->nmethods; ++i) {
5685                 if (acfg->cfgs [i]) {
5686                         emit_exception_debug_info (acfg, acfg->cfgs [i]);
5687                         offsets [i] = acfg->cfgs [i]->ex_info_offset;
5688                 } else {
5689                         offsets [i] = 0;
5690                 }
5691         }
5692
5693         sprintf (symbol, "ex_info_offsets");
5694         emit_section_change (acfg, RODATA_SECT, 1);
5695         emit_alignment (acfg, 8);
5696         emit_label (acfg, symbol);
5697
5698         acfg->stats.offsets_size += emit_offset_table (acfg, acfg->nmethods, 10, offsets);
5699         g_free (offsets);
5700 }
5701
5702 static void
5703 emit_unwind_info (MonoAotCompile *acfg)
5704 {
5705         int i;
5706         char symbol [128];
5707
5708         /* 
5709          * The unwind info contains a lot of duplicates so we emit each unique
5710          * entry once, and only store the offset from the start of the table in the
5711          * exception info.
5712          */
5713
5714         sprintf (symbol, "unwind_info");
5715         emit_section_change (acfg, RODATA_SECT, 1);
5716         emit_alignment (acfg, 8);
5717         emit_label (acfg, symbol);
5718
5719         for (i = 0; i < acfg->unwind_ops->len; ++i) {
5720                 guint32 index = GPOINTER_TO_UINT (g_ptr_array_index (acfg->unwind_ops, i));
5721                 guint8 *unwind_info;
5722                 guint32 unwind_info_len;
5723                 guint8 buf [16];
5724                 guint8 *p;
5725
5726                 unwind_info = mono_get_cached_unwind_info (index, &unwind_info_len);
5727
5728                 p = buf;
5729                 encode_value (unwind_info_len, p, &p);
5730                 emit_bytes (acfg, buf, p - buf);
5731                 emit_bytes (acfg, unwind_info, unwind_info_len);
5732
5733                 acfg->stats.unwind_info_size += (p - buf) + unwind_info_len;
5734         }
5735 }
5736
5737 static void
5738 emit_class_info (MonoAotCompile *acfg)
5739 {
5740         int i;
5741         char symbol [256];
5742         gint32 *offsets;
5743
5744         offsets = g_new0 (gint32, acfg->image->tables [MONO_TABLE_TYPEDEF].rows);
5745         for (i = 0; i < acfg->image->tables [MONO_TABLE_TYPEDEF].rows; ++i)
5746                 offsets [i] = emit_klass_info (acfg, MONO_TOKEN_TYPE_DEF | (i + 1));
5747
5748         sprintf (symbol, "class_info_offsets");
5749         emit_section_change (acfg, RODATA_SECT, 1);
5750         emit_alignment (acfg, 8);
5751         emit_label (acfg, symbol);
5752
5753         acfg->stats.offsets_size += emit_offset_table (acfg, acfg->image->tables [MONO_TABLE_TYPEDEF].rows, 10, offsets);
5754         g_free (offsets);
5755 }
5756
5757 typedef struct ClassNameTableEntry {
5758         guint32 token, index;
5759         struct ClassNameTableEntry *next;
5760 } ClassNameTableEntry;
5761
5762 static void
5763 emit_class_name_table (MonoAotCompile *acfg)
5764 {
5765         int i, table_size;
5766         guint32 token, hash;
5767         MonoClass *klass;
5768         GPtrArray *table;
5769         char *full_name;
5770         char symbol [256];
5771         ClassNameTableEntry *entry, *new_entry;
5772
5773         /*
5774          * Construct a chained hash table for mapping class names to typedef tokens.
5775          */
5776         table_size = g_spaced_primes_closest ((int)(acfg->image->tables [MONO_TABLE_TYPEDEF].rows * 1.5));
5777         table = g_ptr_array_sized_new (table_size);
5778         for (i = 0; i < table_size; ++i)
5779                 g_ptr_array_add (table, NULL);
5780         for (i = 0; i < acfg->image->tables [MONO_TABLE_TYPEDEF].rows; ++i) {
5781                 token = MONO_TOKEN_TYPE_DEF | (i + 1);
5782                 klass = mono_class_get (acfg->image, token);
5783                 if (!klass)
5784                         continue;
5785                 full_name = mono_type_get_name_full (mono_class_get_type (klass), MONO_TYPE_NAME_FORMAT_FULL_NAME);
5786                 hash = mono_metadata_str_hash (full_name) % table_size;
5787                 g_free (full_name);
5788
5789                 /* FIXME: Allocate from the mempool */
5790                 new_entry = g_new0 (ClassNameTableEntry, 1);
5791                 new_entry->token = token;
5792
5793                 entry = g_ptr_array_index (table, hash);
5794                 if (entry == NULL) {
5795                         new_entry->index = hash;
5796                         g_ptr_array_index (table, hash) = new_entry;
5797                 } else {
5798                         while (entry->next)
5799                                 entry = entry->next;
5800                         
5801                         entry->next = new_entry;
5802                         new_entry->index = table->len;
5803                         g_ptr_array_add (table, new_entry);
5804                 }
5805         }
5806
5807         /* Emit the table */
5808         sprintf (symbol, "class_name_table");
5809         emit_section_change (acfg, RODATA_SECT, 0);
5810         emit_alignment (acfg, 8);
5811         emit_label (acfg, symbol);
5812
5813         /* FIXME: Optimize memory usage */
5814         g_assert (table_size < 65000);
5815         emit_int16 (acfg, table_size);
5816         g_assert (table->len < 65000);
5817         for (i = 0; i < table->len; ++i) {
5818                 ClassNameTableEntry *entry = g_ptr_array_index (table, i);
5819
5820                 if (entry == NULL) {
5821                         emit_int16 (acfg, 0);
5822                         emit_int16 (acfg, 0);
5823                 } else {
5824                         emit_int16 (acfg, mono_metadata_token_index (entry->token));
5825                         if (entry->next)
5826                                 emit_int16 (acfg, entry->next->index);
5827                         else
5828                                 emit_int16 (acfg, 0);
5829                 }
5830         }
5831 }
5832
5833 static void
5834 emit_image_table (MonoAotCompile *acfg)
5835 {
5836         int i;
5837         char symbol [256];
5838
5839         /*
5840          * The image table is small but referenced in a lot of places.
5841          * So we emit it at once, and reference its elements by an index.
5842          */
5843
5844         sprintf (symbol, "image_table");
5845         emit_section_change (acfg, RODATA_SECT, 1);
5846         emit_alignment (acfg, 8);
5847         emit_label (acfg, symbol);
5848
5849         emit_int32 (acfg, acfg->image_table->len);
5850         for (i = 0; i < acfg->image_table->len; i++) {
5851                 MonoImage *image = (MonoImage*)g_ptr_array_index (acfg->image_table, i);
5852                 MonoAssemblyName *aname = &image->assembly->aname;
5853
5854                 /* FIXME: Support multi-module assemblies */
5855                 g_assert (image->assembly->image == image);
5856
5857                 emit_string (acfg, image->assembly_name);
5858                 emit_string (acfg, image->guid);
5859                 emit_string (acfg, aname->culture ? aname->culture : "");
5860                 emit_string (acfg, (const char*)aname->public_key_token);
5861
5862                 emit_alignment (acfg, 8);
5863                 emit_int32 (acfg, aname->flags);
5864                 emit_int32 (acfg, aname->major);
5865                 emit_int32 (acfg, aname->minor);
5866                 emit_int32 (acfg, aname->build);
5867                 emit_int32 (acfg, aname->revision);
5868         }
5869 }
5870
5871 static void
5872 emit_got_info (MonoAotCompile *acfg)
5873 {
5874         char symbol [256];
5875         int i, first_plt_got_patch, buf_size;
5876         guint8 *p, *buf;
5877         guint32 *got_info_offsets;
5878
5879         /* Add the patches needed by the PLT to the GOT */
5880         acfg->plt_got_offset_base = acfg->got_offset;
5881         first_plt_got_patch = acfg->got_patches->len;
5882         for (i = 1; i < acfg->plt_offset; ++i) {
5883                 MonoPltEntry *plt_entry = g_hash_table_lookup (acfg->plt_offset_to_entry, GUINT_TO_POINTER (i));
5884
5885                 g_ptr_array_add (acfg->got_patches, plt_entry->ji);
5886         }
5887
5888         acfg->got_offset += acfg->plt_offset;
5889
5890         /**
5891          * FIXME: 
5892          * - optimize offsets table.
5893          * - reduce number of exported symbols.
5894          * - emit info for a klass only once.
5895          * - determine when a method uses a GOT slot which is guaranteed to be already 
5896          *   initialized.
5897          * - clean up and document the code.
5898          * - use String.Empty in class libs.
5899          */
5900
5901         /* Encode info required to decode shared GOT entries */
5902         buf_size = acfg->got_patches->len * 128;
5903         p = buf = mono_mempool_alloc (acfg->mempool, buf_size);
5904         got_info_offsets = mono_mempool_alloc (acfg->mempool, acfg->got_patches->len * sizeof (guint32));
5905         acfg->plt_got_info_offsets = mono_mempool_alloc (acfg->mempool, acfg->plt_offset * sizeof (guint32));
5906         /* Unused */
5907         if (acfg->plt_offset)
5908                 acfg->plt_got_info_offsets [0] = 0;
5909         for (i = 0; i < acfg->got_patches->len; ++i) {
5910                 MonoJumpInfo *ji = g_ptr_array_index (acfg->got_patches, i);
5911
5912                 p = buf;
5913
5914                 encode_value (ji->type, p, &p);
5915                 encode_patch (acfg, ji, p, &p);
5916
5917                 g_assert (p - buf <= buf_size);
5918                 got_info_offsets [i] = add_to_blob (acfg, buf, p - buf);
5919
5920                 if (i >= first_plt_got_patch)
5921                         acfg->plt_got_info_offsets [i - first_plt_got_patch + 1] = got_info_offsets [i];
5922                 acfg->stats.got_info_size += p - buf;
5923         }
5924
5925         /* Emit got_info_offsets table */
5926         sprintf (symbol, "got_info_offsets");
5927         emit_section_change (acfg, RODATA_SECT, 1);
5928         emit_alignment (acfg, 8);
5929         emit_label (acfg, symbol);
5930
5931         /* No need to emit offsets for the got plt entries, the plt embeds them directly */
5932         acfg->stats.offsets_size += emit_offset_table (acfg, first_plt_got_patch, 10, (gint32*)got_info_offsets);
5933 }
5934
5935 static void
5936 emit_got (MonoAotCompile *acfg)
5937 {
5938         char symbol [256];
5939
5940         if (!acfg->llvm) {
5941                 /* Don't make GOT global so accesses to it don't need relocations */
5942                 sprintf (symbol, "%s", acfg->got_symbol);
5943                 emit_section_change (acfg, ".bss", 0);
5944                 emit_alignment (acfg, 8);
5945                 emit_local_symbol (acfg, symbol, "got_end", FALSE);
5946                 emit_label (acfg, symbol);
5947                 if (acfg->got_offset > 0)
5948                         emit_zero_bytes (acfg, (int)(acfg->got_offset * sizeof (gpointer)));
5949
5950                 sprintf (symbol, "got_end");
5951                 emit_label (acfg, symbol);
5952         }
5953 }
5954
5955 typedef struct GlobalsTableEntry {
5956         guint32 value, index;
5957         struct GlobalsTableEntry *next;
5958 } GlobalsTableEntry;
5959
5960 static void
5961 emit_globals_table (MonoAotCompile *acfg)
5962 {
5963         int i, table_size;
5964         guint32 hash;
5965         GPtrArray *table;
5966         char symbol [256];
5967         GlobalsTableEntry *entry, *new_entry;
5968
5969         /*
5970          * Construct a chained hash table for mapping global names to their index in
5971          * the globals table.
5972          */
5973         table_size = g_spaced_primes_closest ((int)(acfg->globals->len * 1.5));
5974         table = g_ptr_array_sized_new (table_size);
5975         for (i = 0; i < table_size; ++i)
5976                 g_ptr_array_add (table, NULL);
5977         for (i = 0; i < acfg->globals->len; ++i) {
5978                 char *name = g_ptr_array_index (acfg->globals, i);
5979
5980                 hash = mono_metadata_str_hash (name) % table_size;
5981
5982                 /* FIXME: Allocate from the mempool */
5983                 new_entry = g_new0 (GlobalsTableEntry, 1);
5984                 new_entry->value = i;
5985
5986                 entry = g_ptr_array_index (table, hash);
5987                 if (entry == NULL) {
5988                         new_entry->index = hash;
5989                         g_ptr_array_index (table, hash) = new_entry;
5990                 } else {
5991                         while (entry->next)
5992                                 entry = entry->next;
5993                         
5994                         entry->next = new_entry;
5995                         new_entry->index = table->len;
5996                         g_ptr_array_add (table, new_entry);
5997                 }
5998         }
5999
6000         /* Emit the table */
6001         sprintf (symbol, ".Lglobals_hash");
6002         emit_section_change (acfg, RODATA_SECT, 0);
6003         emit_alignment (acfg, 8);
6004         emit_label (acfg, symbol);
6005
6006         /* FIXME: Optimize memory usage */
6007         g_assert (table_size < 65000);
6008         emit_int16 (acfg, table_size);
6009         for (i = 0; i < table->len; ++i) {
6010                 GlobalsTableEntry *entry = g_ptr_array_index (table, i);
6011
6012                 if (entry == NULL) {
6013                         emit_int16 (acfg, 0);
6014                         emit_int16 (acfg, 0);
6015                 } else {
6016                         emit_int16 (acfg, entry->value + 1);
6017                         if (entry->next)
6018                                 emit_int16 (acfg, entry->next->index);
6019                         else
6020                                 emit_int16 (acfg, 0);
6021                 }
6022         }
6023
6024         /* Emit the names */
6025         for (i = 0; i < acfg->globals->len; ++i) {
6026                 char *name = g_ptr_array_index (acfg->globals, i);
6027
6028                 sprintf (symbol, "name_%d", i);
6029                 emit_section_change (acfg, RODATA_SECT, 1);
6030                 emit_label (acfg, symbol);
6031                 emit_string (acfg, name);
6032         }
6033
6034         /* Emit the globals table */
6035         sprintf (symbol, ".Lglobals");
6036         emit_section_change (acfg, ".data", 0);
6037         /* This is not a global, since it is accessed by the init function */
6038         emit_alignment (acfg, 8);
6039         emit_label (acfg, symbol);
6040
6041         sprintf (symbol, "%sglobals_hash", acfg->temp_prefix);
6042         emit_pointer (acfg, symbol);
6043
6044         for (i = 0; i < acfg->globals->len; ++i) {
6045                 char *name = g_ptr_array_index (acfg->globals, i);
6046
6047                 sprintf (symbol, "name_%d", i);
6048                 emit_pointer (acfg, symbol);
6049
6050                 sprintf (symbol, "%s", name);
6051                 emit_pointer (acfg, symbol);
6052         }
6053         /* Null terminate the table */
6054         emit_int32 (acfg, 0);
6055         emit_int32 (acfg, 0);
6056 }
6057
6058 static void
6059 emit_globals (MonoAotCompile *acfg)
6060 {
6061         char *build_info;
6062
6063         emit_local_string_symbol (acfg, "assembly_guid" , acfg->image->guid);
6064
6065         if (acfg->aot_opts.bind_to_runtime_version) {
6066                 build_info = mono_get_runtime_build_info ();
6067                 emit_local_string_symbol (acfg, "runtime_version", build_info);
6068                 g_free (build_info);
6069         } else {
6070                 emit_local_string_symbol (acfg, "runtime_version", "");
6071         }
6072
6073         /* 
6074          * When static linking, we emit a global which will point to the symbol table.
6075          */
6076         if (acfg->aot_opts.static_link) {
6077                 char symbol [256];
6078                 char *p;
6079
6080                 /* Emit a string holding the assembly name */
6081                 emit_string_symbol (acfg, "mono_aot_assembly_name", acfg->image->assembly->aname.name);
6082
6083                 emit_globals_table (acfg);
6084
6085                 /* 
6086                  * Emit a global symbol which can be passed by an embedding app to
6087                  * mono_aot_register_module ().
6088                  */
6089 #if defined(__MACH__) && !defined(__native_client_codegen__)
6090                 sprintf (symbol, "_mono_aot_module_%s_info", acfg->image->assembly->aname.name);
6091 #else
6092                 sprintf (symbol, "mono_aot_module_%s_info", acfg->image->assembly->aname.name);
6093 #endif
6094
6095                 /* Get rid of characters which cannot occur in symbols */
6096                 p = symbol;
6097                 for (p = symbol; *p; ++p) {
6098                         if (!(isalnum (*p) || *p == '_'))
6099                                 *p = '_';
6100                 }
6101                 acfg->static_linking_symbol = g_strdup (symbol);
6102                 emit_global_inner (acfg, symbol, FALSE);
6103                 emit_alignment (acfg, 8);
6104                 emit_label (acfg, symbol);
6105                 sprintf (symbol, "%sglobals", acfg->temp_prefix);
6106                 emit_pointer (acfg, symbol);
6107         }
6108 }
6109
6110 static void
6111 emit_autoreg (MonoAotCompile *acfg)
6112 {
6113         char *symbol;
6114
6115         /*
6116          * Emit a function into the .ctor section which will be called by the ELF
6117          * loader to register this module with the runtime.
6118          */
6119         if (! (!acfg->use_bin_writer && acfg->aot_opts.static_link && acfg->aot_opts.autoreg))
6120                 return;
6121
6122         symbol = g_strdup_printf ("_%s_autoreg", acfg->static_linking_symbol);
6123
6124         arch_emit_autoreg (acfg, symbol);
6125
6126         g_free (symbol);
6127 }       
6128
6129 static void
6130 emit_mem_end (MonoAotCompile *acfg)
6131 {
6132         char symbol [128];
6133
6134         sprintf (symbol, "mem_end");
6135         emit_section_change (acfg, ".text", 1);
6136         emit_alignment (acfg, 8);
6137         emit_label (acfg, symbol);
6138 }
6139
6140 /*
6141  * Emit a structure containing all the information not stored elsewhere.
6142  */
6143 static void
6144 emit_file_info (MonoAotCompile *acfg)
6145 {
6146         char symbol [128];
6147         int i;
6148         int gc_name_offset;
6149         const char *gc_name;
6150
6151         /*
6152          * The managed allocators are GC specific, so can't use an AOT image created by one GC
6153          * in another.
6154          */
6155         gc_name = mono_gc_get_gc_name ();
6156         gc_name_offset = add_to_blob (acfg, (guint8*)gc_name, strlen (gc_name) + 1);
6157
6158         sprintf (symbol, "mono_aot_file_info");
6159         emit_section_change (acfg, ".data", 0);
6160         emit_alignment (acfg, 8);
6161         emit_label (acfg, symbol);
6162         emit_global (acfg, symbol, FALSE);
6163
6164         /* The data emitted here must match MonoAotFileInfo. */
6165
6166         emit_int32 (acfg, MONO_AOT_FILE_VERSION);
6167         emit_int32 (acfg, 0);
6168
6169         /* 
6170          * We emit pointers to our data structures instead of emitting global symbols which
6171          * point to them, to reduce the number of globals, and because using globals leads to
6172          * various problems (i.e. arm/thumb).
6173          */
6174         emit_pointer (acfg, acfg->got_symbol);
6175         emit_pointer (acfg, "methods");
6176         if (acfg->llvm) {
6177                 /*
6178                  * Emit a reference to the mono_eh_frame table created by our modified LLVM compiler.
6179                  */
6180                 emit_pointer (acfg, "mono_eh_frame");
6181         } else {
6182                 emit_pointer (acfg, NULL);
6183         }
6184         emit_pointer (acfg, "blob");
6185         emit_pointer (acfg, "class_name_table");
6186         emit_pointer (acfg, "class_info_offsets");
6187         emit_pointer (acfg, "method_info_offsets");
6188         emit_pointer (acfg, "ex_info_offsets");
6189         emit_pointer (acfg, "code_offsets");
6190         emit_pointer (acfg, "extra_method_info_offsets");
6191         emit_pointer (acfg, "extra_method_table");
6192         emit_pointer (acfg, "got_info_offsets");
6193         emit_pointer (acfg, "methods_end");
6194         emit_pointer (acfg, "unwind_info");
6195         emit_pointer (acfg, "mem_end");
6196         emit_pointer (acfg, "image_table");
6197         emit_pointer (acfg, "plt");
6198         emit_pointer (acfg, "plt_end");
6199         emit_pointer (acfg, "assembly_guid");
6200         emit_pointer (acfg, "runtime_version");
6201         if (acfg->num_trampoline_got_entries) {
6202                 emit_pointer (acfg, "specific_trampolines");
6203                 emit_pointer (acfg, "static_rgctx_trampolines");
6204                 emit_pointer (acfg, "imt_thunks");
6205         } else {
6206                 emit_pointer (acfg, NULL);
6207                 emit_pointer (acfg, NULL);
6208                 emit_pointer (acfg, NULL);
6209         }
6210         if (acfg->thumb_mixed) {
6211                 emit_pointer (acfg, "thumb_end");
6212         } else {
6213                 emit_pointer (acfg, NULL);
6214         }
6215
6216         emit_int32 (acfg, acfg->plt_got_offset_base);
6217         emit_int32 (acfg, (int)(acfg->got_offset * sizeof (gpointer)));
6218         emit_int32 (acfg, acfg->plt_offset);
6219         emit_int32 (acfg, acfg->nmethods);
6220         emit_int32 (acfg, acfg->flags);
6221         emit_int32 (acfg, acfg->opts);
6222         emit_int32 (acfg, gc_name_offset);
6223
6224         for (i = 0; i < MONO_AOT_TRAMP_NUM; ++i)
6225                 emit_int32 (acfg, acfg->num_trampolines [i]);
6226         for (i = 0; i < MONO_AOT_TRAMP_NUM; ++i)
6227                 emit_int32 (acfg, acfg->trampoline_got_offset_base [i]);
6228         for (i = 0; i < MONO_AOT_TRAMP_NUM; ++i)
6229                 emit_int32 (acfg, acfg->trampoline_size [i]);
6230 }
6231
6232 static void
6233 emit_blob (MonoAotCompile *acfg)
6234 {
6235         char symbol [128];
6236
6237         sprintf (symbol, "blob");
6238         emit_section_change (acfg, RODATA_SECT, 1);
6239         emit_alignment (acfg, 8);
6240         emit_label (acfg, symbol);
6241
6242         emit_bytes (acfg, (guint8*)acfg->blob.data, acfg->blob.index);
6243 }
6244
6245 static void
6246 emit_dwarf_info (MonoAotCompile *acfg)
6247 {
6248 #ifdef EMIT_DWARF_INFO
6249         int i;
6250         char symbol [128], symbol2 [128];
6251
6252         /* DIEs for methods */
6253         for (i = 0; i < acfg->nmethods; ++i) {
6254                 MonoCompile *cfg = acfg->cfgs [i];
6255
6256                 if (!cfg)
6257                         continue;
6258
6259                 // FIXME: LLVM doesn't define .Lme_...
6260                 if (cfg->compile_llvm)
6261                         continue;
6262
6263                 sprintf (symbol, "%s", cfg->asm_symbol);
6264                 sprintf (symbol2, "%sme_%x", acfg->temp_prefix, i);
6265
6266                 mono_dwarf_writer_emit_method (acfg->dwarf, cfg, cfg->method, symbol, symbol2, cfg->jit_info->code_start, cfg->jit_info->code_size, cfg->args, cfg->locals, cfg->unwind_ops, mono_debug_find_method (cfg->jit_info->method, mono_domain_get ()));
6267         }
6268 #endif
6269 }
6270
6271 static void
6272 collect_methods (MonoAotCompile *acfg)
6273 {
6274         int i;
6275         MonoImage *image = acfg->image;
6276
6277         /* Collect methods */
6278         for (i = 0; i < image->tables [MONO_TABLE_METHOD].rows; ++i) {
6279                 MonoMethod *method;
6280                 guint32 token = MONO_TOKEN_METHOD_DEF | (i + 1);
6281
6282                 method = mono_get_method (acfg->image, token, NULL);
6283
6284                 if (!method) {
6285                         printf ("Failed to load method 0x%x from '%s'.\n", token, image->name);
6286                         exit (1);
6287                 }
6288                         
6289                 /* Load all methods eagerly to skip the slower lazy loading code */
6290                 mono_class_setup_methods (method->klass);
6291
6292                 if (acfg->aot_opts.full_aot && method->iflags & METHOD_IMPL_ATTRIBUTE_INTERNAL_CALL) {
6293                         /* Compile the wrapper instead */
6294                         /* We do this here instead of add_wrappers () because it is easy to do it here */
6295                         MonoMethod *wrapper = mono_marshal_get_native_wrapper (method, check_for_pending_exc, TRUE);
6296                         method = wrapper;
6297                 }
6298
6299                 /* FIXME: Some mscorlib methods don't have debug info */
6300                 /*
6301                 if (acfg->aot_opts.soft_debug && !method->wrapper_type) {
6302                         if (!((method->flags & METHOD_ATTRIBUTE_PINVOKE_IMPL) ||
6303                                   (method->iflags & METHOD_IMPL_ATTRIBUTE_RUNTIME) ||
6304                                   (method->flags & METHOD_ATTRIBUTE_ABSTRACT) ||
6305                                   (method->iflags & METHOD_IMPL_ATTRIBUTE_INTERNAL_CALL))) {
6306                                 if (!mono_debug_lookup_method (method)) {
6307                                         fprintf (stderr, "Method %s has no debug info, probably the .mdb file for the assembly is missing.\n", mono_method_full_name (method, TRUE));
6308                                         exit (1);
6309                                 }
6310                         }
6311                 }
6312                 */
6313
6314                 /* Since we add the normal methods first, their index will be equal to their zero based token index */
6315                 add_method_with_index (acfg, method, i, FALSE);
6316                 acfg->method_index ++;
6317         }
6318
6319         add_generic_instances (acfg);
6320
6321         if (acfg->aot_opts.full_aot)
6322                 add_wrappers (acfg);
6323 }
6324
6325 static void
6326 compile_methods (MonoAotCompile *acfg)
6327 {
6328         int i, methods_len;
6329
6330         if (acfg->aot_opts.nthreads > 0) {
6331                 GPtrArray *frag;
6332                 int len, j;
6333                 GPtrArray *threads;
6334                 HANDLE handle;
6335                 gpointer *user_data;
6336                 MonoMethod **methods;
6337
6338                 methods_len = acfg->methods->len;
6339
6340                 len = acfg->methods->len / acfg->aot_opts.nthreads;
6341                 g_assert (len > 0);
6342                 /* 
6343                  * Partition the list of methods into fragments, and hand it to threads to
6344                  * process.
6345                  */
6346                 threads = g_ptr_array_new ();
6347                 /* Make a copy since acfg->methods is modified by compile_method () */
6348                 methods = g_new0 (MonoMethod*, methods_len);
6349                 //memcpy (methods, g_ptr_array_index (acfg->methods, 0), sizeof (MonoMethod*) * methods_len);
6350                 for (i = 0; i < methods_len; ++i)
6351                         methods [i] = g_ptr_array_index (acfg->methods, i);
6352                 i = 0;
6353                 while (i < methods_len) {
6354                         frag = g_ptr_array_new ();
6355                         for (j = 0; j < len; ++j) {
6356                                 if (i < methods_len) {
6357                                         g_ptr_array_add (frag, methods [i]);
6358                                         i ++;
6359                                 }
6360                         }
6361
6362                         user_data = g_new0 (gpointer, 3);
6363                         user_data [0] = mono_domain_get ();
6364                         user_data [1] = acfg;
6365                         user_data [2] = frag;
6366                         
6367                         handle = mono_create_thread (NULL, 0, (gpointer)compile_thread_main, user_data, 0, NULL);
6368                         g_ptr_array_add (threads, handle);
6369                 }
6370                 g_free (methods);
6371
6372                 for (i = 0; i < threads->len; ++i) {
6373                         WaitForSingleObjectEx (g_ptr_array_index (threads, i), INFINITE, FALSE);
6374                 }
6375         } else {
6376                 methods_len = 0;
6377         }
6378
6379         /* Compile methods added by compile_method () or all methods if nthreads == 0 */
6380         for (i = methods_len; i < acfg->methods->len; ++i) {
6381                 /* This can new methods to acfg->methods */
6382                 compile_method (acfg, g_ptr_array_index (acfg->methods, i));
6383         }
6384 }
6385
6386 static int
6387 compile_asm (MonoAotCompile *acfg)
6388 {
6389         char *command, *objfile;
6390         char *outfile_name, *tmp_outfile_name;
6391         const char *tool_prefix = acfg->aot_opts.tool_prefix ? acfg->aot_opts.tool_prefix : "";
6392
6393 #if defined(TARGET_AMD64)
6394 #define AS_OPTIONS "--64"
6395 #elif defined(TARGET_POWERPC64)
6396 #define AS_OPTIONS "-a64 -mppc64"
6397 #define LD_OPTIONS "-m elf64ppc"
6398 #elif defined(sparc) && SIZEOF_VOID_P == 8
6399 #define AS_OPTIONS "-xarch=v9"
6400 #elif defined(TARGET_X86) && defined(__APPLE__) && !defined(__native_client_codegen__)
6401 #define AS_OPTIONS "-arch i386 -W"
6402 #else
6403 #define AS_OPTIONS ""
6404 #endif
6405
6406 #ifdef __native_client_codegen__
6407 #if defined(TARGET_AMD64)
6408 #define AS_NAME "nacl64-as"
6409 #else
6410 #define AS_NAME "nacl-as"
6411 #endif
6412 #else
6413 #define AS_NAME "as"
6414 #endif
6415
6416 #ifndef LD_OPTIONS
6417 #define LD_OPTIONS ""
6418 #endif
6419
6420 #define EH_LD_OPTIONS ""
6421
6422         if (acfg->aot_opts.asm_only) {
6423                 printf ("Output file: '%s'.\n", acfg->tmpfname);
6424                 if (acfg->aot_opts.static_link)
6425                         printf ("Linking symbol: '%s'.\n", acfg->static_linking_symbol);
6426                 return 0;
6427         }
6428
6429         if (acfg->aot_opts.static_link) {
6430                 if (acfg->aot_opts.outfile)
6431                         objfile = g_strdup_printf ("%s", acfg->aot_opts.outfile);
6432                 else
6433                         objfile = g_strdup_printf ("%s.o", acfg->image->name);
6434         } else {
6435                 objfile = g_strdup_printf ("%s.o", acfg->tmpfname);
6436         }
6437         command = g_strdup_printf ("%s%s %s %s -o %s %s", tool_prefix, AS_NAME, AS_OPTIONS, acfg->as_args ? acfg->as_args->str : "", objfile, acfg->tmpfname);
6438         printf ("Executing the native assembler: %s\n", command);
6439         if (system (command) != 0) {
6440                 g_free (command);
6441                 g_free (objfile);
6442                 return 1;
6443         }
6444
6445         g_free (command);
6446
6447         if (acfg->aot_opts.static_link) {
6448                 printf ("Output file: '%s'.\n", objfile);
6449                 printf ("Linking symbol: '%s'.\n", acfg->static_linking_symbol);
6450                 g_free (objfile);
6451                 return 0;
6452         }
6453
6454         if (acfg->aot_opts.outfile)
6455                 outfile_name = g_strdup_printf ("%s", acfg->aot_opts.outfile);
6456         else
6457                 outfile_name = g_strdup_printf ("%s%s", acfg->image->name, SHARED_EXT);
6458
6459         tmp_outfile_name = g_strdup_printf ("%s.tmp", outfile_name);
6460
6461 #if defined(sparc)
6462         command = g_strdup_printf ("ld -shared -G -o %s %s.o", tmp_outfile_name, acfg->tmpfname);
6463 #elif defined(__ppc__) && defined(__MACH__)
6464         command = g_strdup_printf ("gcc -dynamiclib -o %s %s.o", tmp_outfile_name, acfg->tmpfname);
6465 #elif defined(HOST_WIN32)
6466         command = g_strdup_printf ("gcc -shared --dll -mno-cygwin -o %s %s.o", tmp_outfile_name, acfg->tmpfname);
6467 #elif defined(TARGET_X86) && defined(__APPLE__) && !defined(__native_client_codegen__)
6468         command = g_strdup_printf ("gcc -m32 -dynamiclib -o %s %s.o", tmp_outfile_name, acfg->tmpfname);
6469 #else
6470         command = g_strdup_printf ("%sld %s %s -shared -o %s %s.o", tool_prefix, EH_LD_OPTIONS, LD_OPTIONS, tmp_outfile_name, acfg->tmpfname);
6471 #endif
6472         printf ("Executing the native linker: %s\n", command);
6473         if (system (command) != 0) {
6474                 g_free (tmp_outfile_name);
6475                 g_free (outfile_name);
6476                 g_free (command);
6477                 g_free (objfile);
6478                 return 1;
6479         }
6480
6481         g_free (command);
6482         unlink (objfile);
6483         /*com = g_strdup_printf ("strip --strip-unneeded %s%s", acfg->image->name, SHARED_EXT);
6484         printf ("Stripping the binary: %s\n", com);
6485         system (com);
6486         g_free (com);*/
6487
6488 #if defined(TARGET_ARM) && !defined(__MACH__)
6489         /* 
6490          * gas generates 'mapping symbols' each time code and data is mixed, which 
6491          * happens a lot in emit_and_reloc_code (), so we need to get rid of them.
6492          */
6493         command = g_strdup_printf ("%sstrip --strip-symbol=\\$a --strip-symbol=\\$d %s", tool_prefix, tmp_outfile_name);
6494         printf ("Stripping the binary: %s\n", command);
6495         if (system (command) != 0) {
6496                 g_free (tmp_outfile_name);
6497                 g_free (outfile_name);
6498                 g_free (command);
6499                 g_free (objfile);
6500                 return 1;
6501         }
6502 #endif
6503
6504         rename (tmp_outfile_name, outfile_name);
6505
6506         g_free (tmp_outfile_name);
6507         g_free (outfile_name);
6508         g_free (objfile);
6509
6510         if (acfg->aot_opts.save_temps)
6511                 printf ("Retained input file.\n");
6512         else
6513                 unlink (acfg->tmpfname);
6514
6515         return 0;
6516 }
6517
6518 static MonoAotCompile*
6519 acfg_create (MonoAssembly *ass, guint32 opts)
6520 {
6521         MonoImage *image = ass->image;
6522         MonoAotCompile *acfg;
6523         int i;
6524
6525         acfg = g_new0 (MonoAotCompile, 1);
6526         acfg->methods = g_ptr_array_new ();
6527         acfg->method_indexes = g_hash_table_new (NULL, NULL);
6528         acfg->method_depth = g_hash_table_new (NULL, NULL);
6529         acfg->plt_offset_to_entry = g_hash_table_new (NULL, NULL);
6530         acfg->patch_to_plt_entry = g_hash_table_new (mono_patch_info_hash, mono_patch_info_equal);
6531         acfg->patch_to_got_offset = g_hash_table_new (mono_patch_info_hash, mono_patch_info_equal);
6532         acfg->patch_to_got_offset_by_type = g_new0 (GHashTable*, MONO_PATCH_INFO_NUM);
6533         for (i = 0; i < MONO_PATCH_INFO_NUM; ++i)
6534                 acfg->patch_to_got_offset_by_type [i] = g_hash_table_new (mono_patch_info_hash, mono_patch_info_equal);
6535         acfg->got_patches = g_ptr_array_new ();
6536         acfg->method_to_cfg = g_hash_table_new (NULL, NULL);
6537         acfg->token_info_hash = g_hash_table_new_full (NULL, NULL, NULL, g_free);
6538         acfg->image_hash = g_hash_table_new (NULL, NULL);
6539         acfg->image_table = g_ptr_array_new ();
6540         acfg->globals = g_ptr_array_new ();
6541         acfg->image = image;
6542         acfg->opts = opts;
6543         acfg->mempool = mono_mempool_new ();
6544         acfg->extra_methods = g_ptr_array_new ();
6545         acfg->unwind_info_offsets = g_hash_table_new (NULL, NULL);
6546         acfg->unwind_ops = g_ptr_array_new ();
6547         acfg->method_label_hash = g_hash_table_new_full (g_str_hash, g_str_equal, g_free, NULL);
6548         InitializeCriticalSection (&acfg->mutex);
6549
6550         return acfg;
6551 }
6552
6553 static void
6554 acfg_free (MonoAotCompile *acfg)
6555 {
6556         int i;
6557
6558         img_writer_destroy (acfg->w);
6559         for (i = 0; i < acfg->nmethods; ++i)
6560                 if (acfg->cfgs [i])
6561                         g_free (acfg->cfgs [i]);
6562         g_free (acfg->cfgs);
6563         g_free (acfg->static_linking_symbol);
6564         g_free (acfg->got_symbol);
6565         g_free (acfg->plt_symbol);
6566         g_ptr_array_free (acfg->methods, TRUE);
6567         g_ptr_array_free (acfg->got_patches, TRUE);
6568         g_ptr_array_free (acfg->image_table, TRUE);
6569         g_ptr_array_free (acfg->globals, TRUE);
6570         g_ptr_array_free (acfg->unwind_ops, TRUE);
6571         g_hash_table_destroy (acfg->method_indexes);
6572         g_hash_table_destroy (acfg->method_depth);
6573         g_hash_table_destroy (acfg->plt_offset_to_entry);
6574         g_hash_table_destroy (acfg->patch_to_plt_entry);
6575         g_hash_table_destroy (acfg->patch_to_got_offset);
6576         g_hash_table_destroy (acfg->method_to_cfg);
6577         g_hash_table_destroy (acfg->token_info_hash);
6578         g_hash_table_destroy (acfg->image_hash);
6579         g_hash_table_destroy (acfg->unwind_info_offsets);
6580         g_hash_table_destroy (acfg->method_label_hash);
6581         for (i = 0; i < MONO_PATCH_INFO_NUM; ++i)
6582                 g_hash_table_destroy (acfg->patch_to_got_offset_by_type [i]);
6583         g_free (acfg->patch_to_got_offset_by_type);
6584         mono_mempool_destroy (acfg->mempool);
6585         g_free (acfg);
6586 }
6587
6588 int
6589 mono_compile_assembly (MonoAssembly *ass, guint32 opts, const char *aot_options)
6590 {
6591         MonoImage *image = ass->image;
6592         int i, res;
6593         MonoAotCompile *acfg;
6594         char *outfile_name, *tmp_outfile_name, *p;
6595         TV_DECLARE (atv);
6596         TV_DECLARE (btv);
6597
6598         printf ("Mono Ahead of Time compiler - compiling assembly %s\n", image->name);
6599
6600         acfg = acfg_create (ass, opts);
6601
6602         memset (&acfg->aot_opts, 0, sizeof (acfg->aot_opts));
6603         acfg->aot_opts.write_symbols = TRUE;
6604         acfg->aot_opts.ntrampolines = 1024;
6605         acfg->aot_opts.nrgctx_trampolines = 1024;
6606         acfg->aot_opts.nimt_trampolines = 128;
6607
6608         mono_aot_parse_options (aot_options, &acfg->aot_opts);
6609
6610         if (acfg->aot_opts.static_link)
6611                 acfg->aot_opts.autoreg = TRUE;
6612
6613         //acfg->aot_opts.print_skipped_methods = TRUE;
6614
6615 #ifndef MONO_ARCH_HAVE_FULL_AOT_TRAMPOLINES
6616         if (acfg->aot_opts.full_aot) {
6617                 printf ("--aot=full is not supported on this platform.\n");
6618                 return 1;
6619         }
6620 #endif
6621
6622         if (acfg->aot_opts.static_link)
6623                 acfg->aot_opts.asm_writer = TRUE;
6624
6625         if (acfg->aot_opts.soft_debug) {
6626                 MonoDebugOptions *opt = mini_get_debug_options ();
6627
6628                 opt->mdb_optimizations = TRUE;
6629                 opt->gen_seq_points = TRUE;
6630
6631                 if (mono_debug_format == MONO_DEBUG_FORMAT_NONE) {
6632                         fprintf (stderr, "The soft-debug AOT option requires the --debug option.\n");
6633                         return 1;
6634                 }
6635                 acfg->flags |= MONO_AOT_FILE_FLAG_DEBUG;
6636         }
6637
6638         if (mono_use_llvm) {
6639                 acfg->llvm = TRUE;
6640                 acfg->aot_opts.asm_writer = TRUE;
6641                 acfg->flags |= MONO_AOT_FILE_FLAG_WITH_LLVM;
6642         }
6643
6644         if (acfg->aot_opts.full_aot)
6645                 acfg->flags |= MONO_AOT_FILE_FLAG_FULL_AOT;
6646
6647         load_profile_files (acfg);
6648
6649         acfg->num_trampolines [MONO_AOT_TRAMP_SPECIFIC] = acfg->aot_opts.full_aot ? acfg->aot_opts.ntrampolines : 0;
6650 #ifdef MONO_ARCH_HAVE_STATIC_RGCTX_TRAMPOLINE
6651         acfg->num_trampolines [MONO_AOT_TRAMP_STATIC_RGCTX] = acfg->aot_opts.full_aot ? acfg->aot_opts.nrgctx_trampolines : 0;
6652 #endif
6653         acfg->num_trampolines [MONO_AOT_TRAMP_IMT_THUNK] = acfg->aot_opts.full_aot ? acfg->aot_opts.nimt_trampolines : 0;
6654
6655         acfg->temp_prefix = img_writer_get_temp_label_prefix (NULL);
6656
6657         arch_init (acfg);
6658
6659         acfg->got_symbol_base = g_strdup_printf ("%smono_aot_%s_got", acfg->llvm_label_prefix, acfg->image->assembly->aname.name);
6660         acfg->plt_symbol = g_strdup_printf ("%smono_aot_%s_plt", acfg->llvm_label_prefix, acfg->image->assembly->aname.name);
6661
6662         /* Get rid of characters which cannot occur in symbols */
6663         for (p = acfg->got_symbol_base; *p; ++p) {
6664                 if (!(isalnum (*p) || *p == '_'))
6665                         *p = '_';
6666         }
6667         for (p = acfg->plt_symbol; *p; ++p) {
6668                 if (!(isalnum (*p) || *p == '_'))
6669                         *p = '_';
6670         }
6671
6672         acfg->method_index = 1;
6673
6674         collect_methods (acfg);
6675
6676         acfg->cfgs_size = acfg->methods->len + 32;
6677         acfg->cfgs = g_new0 (MonoCompile*, acfg->cfgs_size);
6678
6679         /* PLT offset 0 is reserved for the PLT trampoline */
6680         acfg->plt_offset = 1;
6681
6682 #ifdef ENABLE_LLVM
6683         if (acfg->llvm) {
6684                 llvm_acfg = acfg;
6685                 mono_llvm_create_aot_module (acfg->got_symbol_base);
6686         }
6687 #endif
6688
6689         /* GOT offset 0 is reserved for the address of the current assembly */
6690         {
6691                 MonoJumpInfo *ji;
6692
6693                 ji = mono_mempool_alloc0 (acfg->mempool, sizeof (MonoAotCompile));
6694                 ji->type = MONO_PATCH_INFO_IMAGE;
6695                 ji->data.image = acfg->image;
6696
6697                 get_got_offset (acfg, ji);
6698
6699                 /* Slot 1 is reserved for the mscorlib got addr */
6700                 ji = mono_mempool_alloc0 (acfg->mempool, sizeof (MonoAotCompile));
6701                 ji->type = MONO_PATCH_INFO_MSCORLIB_GOT_ADDR;
6702                 get_got_offset (acfg, ji);
6703
6704                 /* This is very common */
6705                 ji = mono_mempool_alloc0 (acfg->mempool, sizeof (MonoAotCompile));
6706                 ji->type = MONO_PATCH_INFO_GC_CARD_TABLE_ADDR;
6707                 get_got_offset (acfg, ji);
6708         }
6709
6710         TV_GETTIME (atv);
6711
6712         compile_methods (acfg);
6713
6714         TV_GETTIME (btv);
6715
6716         acfg->stats.jit_time = TV_ELAPSED (atv, btv);
6717
6718         TV_GETTIME (atv);
6719
6720 #ifdef ENABLE_LLVM
6721         if (acfg->llvm) {
6722                 if (acfg->aot_opts.asm_only) {
6723                         if (acfg->aot_opts.outfile)
6724                                 acfg->tmpfname = g_strdup_printf ("%s", acfg->aot_opts.outfile);
6725                         else
6726                                 acfg->tmpfname = g_strdup_printf ("%s.s", acfg->image->name);
6727                 } else {
6728                         acfg->tmpfname = g_strdup ("temp.s");
6729                 }
6730
6731                 emit_llvm_file (acfg);
6732         }
6733 #endif
6734
6735         if (!acfg->aot_opts.asm_only && !acfg->aot_opts.asm_writer && bin_writer_supported ()) {
6736                 if (acfg->aot_opts.outfile)
6737                         outfile_name = g_strdup_printf ("%s", acfg->aot_opts.outfile);
6738                 else
6739                         outfile_name = g_strdup_printf ("%s%s", acfg->image->name, SHARED_EXT);
6740
6741                 /* 
6742                  * Can't use g_file_open_tmp () as it will be deleted at exit, and
6743                  * it might be in another file system so the rename () won't work.
6744                  */
6745                 tmp_outfile_name = g_strdup_printf ("%s.tmp", outfile_name);
6746
6747                 acfg->fp = fopen (tmp_outfile_name, "w");
6748                 if (!acfg->fp) {
6749                         printf ("Unable to create temporary file '%s': %s\n", tmp_outfile_name, strerror (errno));
6750                         return 1;
6751                 }
6752
6753                 acfg->w = img_writer_create (acfg->fp, TRUE);
6754                 acfg->use_bin_writer = TRUE;
6755         } else {
6756                 if (acfg->llvm) {
6757                         /* Append to the .s file created by llvm */
6758                         /* FIXME: Use multiple files instead */
6759                         acfg->fp = fopen (acfg->tmpfname, "a+");
6760                 } else {
6761                         if (acfg->aot_opts.asm_only) {
6762                                 if (acfg->aot_opts.outfile)
6763                                         acfg->tmpfname = g_strdup_printf ("%s", acfg->aot_opts.outfile);
6764                                 else
6765                                         acfg->tmpfname = g_strdup_printf ("%s.s", acfg->image->name);
6766                                 acfg->fp = fopen (acfg->tmpfname, "w+");
6767                         } else {
6768                                 int i = g_file_open_tmp ("mono_aot_XXXXXX", &acfg->tmpfname, NULL);
6769                                 acfg->fp = fdopen (i, "w+");
6770                         }
6771                         g_assert (acfg->fp);
6772                 }
6773                 acfg->w = img_writer_create (acfg->fp, FALSE);
6774                 
6775                 tmp_outfile_name = NULL;
6776                 outfile_name = NULL;
6777         }
6778
6779         acfg->got_symbol = g_strdup_printf ("%s%s", acfg->llvm_label_prefix, acfg->got_symbol_base);
6780
6781         /* Compute symbols for methods */
6782         for (i = 0; i < acfg->nmethods; ++i) {
6783                 if (acfg->cfgs [i]) {
6784                         MonoCompile *cfg = acfg->cfgs [i];
6785                         int method_index = get_method_index (acfg, cfg->orig_method);
6786
6787                         if (COMPILE_LLVM (cfg))
6788                                 cfg->asm_symbol = g_strdup_printf ("%s%s", acfg->llvm_label_prefix, cfg->llvm_method_name);
6789                         else
6790                                 cfg->asm_symbol = g_strdup_printf ("%s%sm_%x", acfg->temp_prefix, acfg->llvm_label_prefix, method_index);
6791                 }
6792         }
6793
6794         if (!acfg->aot_opts.nodebug)
6795                 acfg->dwarf = mono_dwarf_writer_create (acfg->w, NULL, 0, FALSE);
6796
6797         img_writer_emit_start (acfg->w);
6798
6799         if (acfg->dwarf)
6800                 mono_dwarf_writer_emit_base_info (acfg->dwarf, mono_unwind_get_cie_program ());
6801
6802         if (acfg->thumb_mixed) {
6803                 char symbol [256];
6804                 /*
6805                  * This global symbol marks the end of THUMB code, and the beginning of ARM
6806                  * code generated by our JIT.
6807                  */
6808                 sprintf (symbol, "thumb_end");
6809                 emit_section_change (acfg, ".text", 0);
6810                 emit_label (acfg, symbol);
6811                 fprintf (acfg->fp, ".skip 16\n");
6812
6813                 fprintf (acfg->fp, ".arm\n");
6814         }
6815
6816         emit_code (acfg);
6817
6818         emit_info (acfg);
6819
6820         emit_extra_methods (acfg);
6821
6822         emit_trampolines (acfg);
6823
6824         emit_class_name_table (acfg);
6825
6826         emit_got_info (acfg);
6827
6828         emit_exception_info (acfg);
6829
6830         emit_unwind_info (acfg);
6831
6832         emit_class_info (acfg);
6833
6834         emit_plt (acfg);
6835
6836         emit_image_table (acfg);
6837
6838         emit_got (acfg);
6839
6840         emit_file_info (acfg);
6841
6842         emit_blob (acfg);
6843
6844         emit_globals (acfg);
6845
6846         emit_autoreg (acfg);
6847
6848         if (acfg->dwarf) {
6849                 emit_dwarf_info (acfg);
6850                 mono_dwarf_writer_close (acfg->dwarf);
6851         }
6852
6853         emit_mem_end (acfg);
6854
6855         TV_GETTIME (btv);
6856
6857         acfg->stats.gen_time = TV_ELAPSED (atv, btv);
6858
6859         if (acfg->llvm)
6860                 g_assert (acfg->got_offset <= acfg->final_got_size);
6861
6862         printf ("Code: %d Info: %d Ex Info: %d Unwind Info: %d Class Info: %d PLT: %d GOT Info: %d GOT: %d Offsets: %d\n", acfg->stats.code_size, acfg->stats.info_size, acfg->stats.ex_info_size, acfg->stats.unwind_info_size, acfg->stats.class_info_size, acfg->plt_offset, acfg->stats.got_info_size, (int)(acfg->got_offset * sizeof (gpointer)), acfg->stats.offsets_size);
6863
6864         TV_GETTIME (atv);
6865         res = img_writer_emit_writeout (acfg->w);
6866         if (res != 0) {
6867                 acfg_free (acfg);
6868                 return res;
6869         }
6870         if (acfg->use_bin_writer) {
6871                 int err = rename (tmp_outfile_name, outfile_name);
6872
6873                 if (err) {
6874                         printf ("Unable to rename '%s' to '%s': %s\n", tmp_outfile_name, outfile_name, strerror (errno));
6875                         return 1;
6876                 }
6877         } else {
6878                 res = compile_asm (acfg);
6879                 if (res != 0) {
6880                         acfg_free (acfg);
6881                         return res;
6882                 }
6883         }
6884         TV_GETTIME (btv);
6885         acfg->stats.link_time = TV_ELAPSED (atv, btv);
6886
6887         printf ("Compiled %d out of %d methods (%d%%)\n", acfg->stats.ccount, acfg->stats.mcount, acfg->stats.mcount ? (acfg->stats.ccount * 100) / acfg->stats.mcount : 100);
6888         if (acfg->stats.genericcount)
6889                 printf ("%d methods are generic (%d%%)\n", acfg->stats.genericcount, acfg->stats.mcount ? (acfg->stats.genericcount * 100) / acfg->stats.mcount : 100);
6890         if (acfg->stats.abscount)
6891                 printf ("%d methods contain absolute addresses (%d%%)\n", acfg->stats.abscount, acfg->stats.mcount ? (acfg->stats.abscount * 100) / acfg->stats.mcount : 100);
6892         if (acfg->stats.lmfcount)
6893                 printf ("%d methods contain lmf pointers (%d%%)\n", acfg->stats.lmfcount, acfg->stats.mcount ? (acfg->stats.lmfcount * 100) / acfg->stats.mcount : 100);
6894         if (acfg->stats.ocount)
6895                 printf ("%d methods have other problems (%d%%)\n", acfg->stats.ocount, acfg->stats.mcount ? (acfg->stats.ocount * 100) / acfg->stats.mcount : 100);
6896         if (acfg->llvm)
6897                 printf ("Methods compiled with LLVM: %d (%d%%)\n", acfg->stats.llvm_count, acfg->stats.mcount ? (acfg->stats.llvm_count * 100) / acfg->stats.mcount : 100);
6898         printf ("Methods without GOT slots: %d (%d%%)\n", acfg->stats.methods_without_got_slots, acfg->stats.mcount ? (acfg->stats.methods_without_got_slots * 100) / acfg->stats.mcount : 100);
6899         printf ("Direct calls: %d (%d%%)\n", acfg->stats.direct_calls, acfg->stats.all_calls ? (acfg->stats.direct_calls * 100) / acfg->stats.all_calls : 100);
6900
6901         if (acfg->aot_opts.stats) {
6902                 int i;
6903
6904                 printf ("GOT slot distribution:\n");
6905                 for (i = 0; i < MONO_PATCH_INFO_NONE; ++i)
6906                         if (acfg->stats.got_slot_types [i])
6907                                 printf ("\t%s: %d\n", get_patch_name (i), acfg->stats.got_slot_types [i]);
6908         }
6909
6910         printf ("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);
6911
6912         acfg_free (acfg);
6913         
6914         return 0;
6915 }
6916
6917 #else
6918
6919 /* AOT disabled */
6920
6921 int
6922 mono_compile_assembly (MonoAssembly *ass, guint32 opts, const char *aot_options)
6923 {
6924         return 0;
6925 }
6926
6927 #endif