2009-09-21 Zoltan Varga <vargaz@gmail.com>
[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
25 #include "config.h"
26 #include <sys/types.h>
27 #ifdef HAVE_UNISTD_H
28 #include <unistd.h>
29 #endif
30 #ifdef HAVE_STDINT_H
31 #include <stdint.h>
32 #endif
33 #include <fcntl.h>
34 #include <ctype.h>
35 #include <string.h>
36 #ifndef PLATFORM_WIN32
37 #include <sys/time.h>
38 #else
39 #include <winsock2.h>
40 #include <windows.h>
41 #endif
42
43 #include <errno.h>
44 #include <sys/stat.h>
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.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 #define TV_DECLARE(name) gint64 name
72 #define TV_GETTIME(tv) tv = mono_100ns_ticks ()
73 #define TV_ELAPSED(start,end) (((end) - (start)) / 10)
74
75 #ifdef PLATFORM_WIN32
76 #define SHARED_EXT ".dll"
77 #elif defined(__ppc__) && defined(__MACH__)
78 #define SHARED_EXT ".dylib"
79 #else
80 #define SHARED_EXT ".so"
81 #endif
82
83 #define ALIGN_TO(val,align) ((((guint64)val) + ((align) - 1)) & ~((align) - 1))
84 #define ALIGN_PTR_TO(ptr,align) (gpointer)((((gssize)(ptr)) + (align - 1)) & (~(align - 1)))
85 #define ROUND_DOWN(VALUE,SIZE)  ((VALUE) & ~((SIZE) - 1))
86
87 typedef struct MonoAotOptions {
88         char *outfile;
89         gboolean save_temps;
90         gboolean write_symbols;
91         gboolean metadata_only;
92         gboolean bind_to_runtime_version;
93         gboolean full_aot;
94         gboolean no_dlsym;
95         gboolean static_link;
96         gboolean asm_only;
97         gboolean asm_writer;
98         gboolean nodebug;
99         int nthreads;
100         int ntrampolines;
101         gboolean print_skipped_methods;
102         char *tool_prefix;
103 } MonoAotOptions;
104
105 typedef struct MonoAotStats {
106         int ccount, mcount, lmfcount, abscount, gcount, ocount, genericcount;
107         int code_size, info_size, ex_info_size, unwind_info_size, got_size, class_info_size, got_info_size, got_info_offsets_size;
108         int methods_without_got_slots, direct_calls, all_calls;
109         int got_slots;
110         int got_slot_types [MONO_PATCH_INFO_NONE];
111         int jit_time, gen_time, link_time;
112 } MonoAotStats;
113
114 typedef struct MonoAotCompile {
115         MonoImage *image;
116         GPtrArray *methods;
117         GHashTable *method_indexes;
118         MonoCompile **cfgs;
119         int cfgs_size;
120         GHashTable *patch_to_plt_offset;
121         GHashTable *plt_offset_to_patch;
122         GHashTable *patch_to_got_offset;
123         GPtrArray *got_patches;
124         GHashTable *image_hash;
125         GHashTable *method_to_cfg;
126         GHashTable *token_info_hash;
127         GPtrArray *extra_methods;
128         GPtrArray *image_table;
129         GPtrArray *globals;
130         GList *method_order;
131         guint32 *plt_got_info_offsets;
132         guint32 got_offset, plt_offset, plt_got_offset_base;
133         /* Number of GOT entries reserved for trampolines */
134         guint32 num_trampoline_got_entries;
135
136         guint32 num_trampolines [MONO_AOT_TRAMP_NUM];
137         guint32 trampoline_got_offset_base [MONO_AOT_TRAMP_NUM];
138         guint32 trampoline_size [MONO_AOT_TRAMP_NUM];
139
140         MonoAotOptions aot_opts;
141         guint32 nmethods;
142         guint32 opts;
143         MonoMemPool *mempool;
144         MonoAotStats stats;
145         int method_index;
146         char *static_linking_symbol;
147         CRITICAL_SECTION mutex;
148         gboolean use_bin_writer;
149         MonoImageWriter *w;
150         MonoDwarfWriter *dwarf;
151         FILE *fp;
152         char *tmpfname;
153         GSList *cie_program;
154         GHashTable *unwind_info_offsets;
155         GPtrArray *unwind_ops;
156         guint32 unwind_info_offset;
157         char *got_symbol;
158         char *plt_symbol;
159         GHashTable *method_label_hash;
160         const char *temp_prefix;
161         guint32 label_generator;
162 } MonoAotCompile;
163
164 #define mono_acfg_lock(acfg) EnterCriticalSection (&((acfg)->mutex))
165 #define mono_acfg_unlock(acfg) LeaveCriticalSection (&((acfg)->mutex))
166
167 #ifdef HAVE_ARRAY_ELEM_INIT
168 #define MSGSTRFIELD(line) MSGSTRFIELD1(line)
169 #define MSGSTRFIELD1(line) str##line
170 static const struct msgstr_t {
171 #define PATCH_INFO(a,b) char MSGSTRFIELD(__LINE__) [sizeof (b)];
172 #include "patch-info.h"
173 #undef PATCH_INFO
174 } opstr = {
175 #define PATCH_INFO(a,b) b,
176 #include "patch-info.h"
177 #undef PATCH_INFO
178 };
179 static const gint16 opidx [] = {
180 #define PATCH_INFO(a,b) [MONO_PATCH_INFO_ ## a] = offsetof (struct msgstr_t, MSGSTRFIELD(__LINE__)),
181 #include "patch-info.h"
182 #undef PATCH_INFO
183 };
184
185 static G_GNUC_UNUSED const char*
186 get_patch_name (int info)
187 {
188         return (const char*)&opstr + opidx [info];
189 }
190
191 #else
192 #define PATCH_INFO(a,b) b,
193 static const char* const
194 patch_types [MONO_PATCH_INFO_NUM + 1] = {
195 #include "patch-info.h"
196         NULL
197 };
198
199 static G_GNUC_UNUSED const char*
200 get_patch_name (int info)
201 {
202         return patch_types [info];
203 }
204
205 #endif
206
207 /* Wrappers around the image writer functions */
208
209 static inline void
210 emit_section_change (MonoAotCompile *acfg, const char *section_name, int subsection_index)
211 {
212         img_writer_emit_section_change (acfg->w, section_name, subsection_index);
213 }
214
215 static inline void
216 emit_push_section (MonoAotCompile *acfg, const char *section_name, int subsection)
217 {
218         img_writer_emit_push_section (acfg->w, section_name, subsection);
219 }
220
221 static inline void
222 emit_pop_section (MonoAotCompile *acfg)
223 {
224         img_writer_emit_pop_section (acfg->w);
225 }
226
227 static inline void
228 emit_local_symbol (MonoAotCompile *acfg, const char *name, const char *end_label, gboolean func) 
229
230         img_writer_emit_local_symbol (acfg->w, name, end_label, func); 
231 }
232
233 static inline void
234 emit_label (MonoAotCompile *acfg, const char *name) 
235
236         img_writer_emit_label (acfg->w, name); 
237 }
238
239 static inline void
240 emit_bytes (MonoAotCompile *acfg, const guint8* buf, int size) 
241
242         img_writer_emit_bytes (acfg->w, buf, size); 
243 }
244
245 static inline void
246 emit_string (MonoAotCompile *acfg, const char *value) 
247
248         img_writer_emit_string (acfg->w, value); 
249 }
250
251 static inline void
252 emit_line (MonoAotCompile *acfg) 
253
254         img_writer_emit_line (acfg->w); 
255 }
256
257 static inline void
258 emit_alignment (MonoAotCompile *acfg, int size) 
259
260         img_writer_emit_alignment (acfg->w, size); 
261 }
262
263 static inline void
264 emit_pointer_unaligned (MonoAotCompile *acfg, const char *target) 
265
266         img_writer_emit_pointer_unaligned (acfg->w, target); 
267 }
268
269 static inline void
270 emit_pointer (MonoAotCompile *acfg, const char *target) 
271
272         img_writer_emit_pointer (acfg->w, target); 
273 }
274
275 static inline void
276 emit_int16 (MonoAotCompile *acfg, int value) 
277
278         img_writer_emit_int16 (acfg->w, value); 
279 }
280
281 static inline void
282 emit_int32 (MonoAotCompile *acfg, int value) 
283
284         img_writer_emit_int32 (acfg->w, value); 
285 }
286
287 static inline void
288 emit_symbol_diff (MonoAotCompile *acfg, const char *end, const char* start, int offset) 
289
290         img_writer_emit_symbol_diff (acfg->w, end, start, offset); 
291 }
292
293 static inline void
294 emit_zero_bytes (MonoAotCompile *acfg, int num) 
295
296         img_writer_emit_zero_bytes (acfg->w, num); 
297 }
298
299 static inline void
300 emit_byte (MonoAotCompile *acfg, guint8 val) 
301
302         img_writer_emit_byte (acfg->w, val); 
303 }
304
305 static G_GNUC_UNUSED void
306 emit_global_inner (MonoAotCompile *acfg, const char *name, gboolean func)
307 {
308         img_writer_emit_global (acfg->w, name, func);
309 }
310
311 static void
312 emit_global (MonoAotCompile *acfg, const char *name, gboolean func)
313 {
314         if (acfg->aot_opts.no_dlsym) {
315                 g_ptr_array_add (acfg->globals, g_strdup (name));
316                 img_writer_emit_local_symbol (acfg->w, name, NULL, func);
317         } else {
318                 img_writer_emit_global (acfg->w, name, func);
319         }
320 }
321
322 static void
323 emit_symbol_size (MonoAotCompile *acfg, const char *name, const char *end_label)
324 {
325         img_writer_emit_symbol_size (acfg->w, name, end_label);
326 }
327
328 static void
329 emit_string_symbol (MonoAotCompile *acfg, const char *name, const char *value)
330 {
331         img_writer_emit_section_change (acfg->w, ".text", 1);
332         emit_global (acfg, name, FALSE);
333         img_writer_emit_label (acfg->w, name);
334         img_writer_emit_string (acfg->w, value);
335 }
336
337 static G_GNUC_UNUSED void
338 emit_uleb128 (MonoAotCompile *acfg, guint32 value)
339 {
340         do {
341                 guint8 b = value & 0x7f;
342                 value >>= 7;
343                 if (value != 0) /* more bytes to come */
344                         b |= 0x80;
345                 emit_byte (acfg, b);
346         } while (value);
347 }
348
349 static G_GNUC_UNUSED void
350 emit_sleb128 (MonoAotCompile *acfg, gint64 value)
351 {
352         gboolean more = 1;
353         gboolean negative = (value < 0);
354         guint32 size = 64;
355         guint8 byte;
356
357         while (more) {
358                 byte = value & 0x7f;
359                 value >>= 7;
360                 /* the following is unnecessary if the
361                  * implementation of >>= uses an arithmetic rather
362                  * than logical shift for a signed left operand
363                  */
364                 if (negative)
365                         /* sign extend */
366                         value |= - ((gint64)1 <<(size - 7));
367                 /* sign bit of byte is second high order bit (0x40) */
368                 if ((value == 0 && !(byte & 0x40)) ||
369                         (value == -1 && (byte & 0x40)))
370                         more = 0;
371                 else
372                         byte |= 0x80;
373                 emit_byte (acfg, byte);
374         }
375 }
376
377 static G_GNUC_UNUSED void
378 encode_uleb128 (guint32 value, guint8 *buf, guint8 **endbuf)
379 {
380         guint8 *p = buf;
381
382         do {
383                 guint8 b = value & 0x7f;
384                 value >>= 7;
385                 if (value != 0) /* more bytes to come */
386                         b |= 0x80;
387                 *p ++ = b;
388         } while (value);
389
390         *endbuf = p;
391 }
392
393 static G_GNUC_UNUSED void
394 encode_sleb128 (gint32 value, guint8 *buf, guint8 **endbuf)
395 {
396         gboolean more = 1;
397         gboolean negative = (value < 0);
398         guint32 size = 32;
399         guint8 byte;
400         guint8 *p = buf;
401
402         while (more) {
403                 byte = value & 0x7f;
404                 value >>= 7;
405                 /* the following is unnecessary if the
406                  * implementation of >>= uses an arithmetic rather
407                  * than logical shift for a signed left operand
408                  */
409                 if (negative)
410                         /* sign extend */
411                         value |= - (1 <<(size - 7));
412                 /* sign bit of byte is second high order bit (0x40) */
413                 if ((value == 0 && !(byte & 0x40)) ||
414                         (value == -1 && (byte & 0x40)))
415                         more = 0;
416                 else
417                         byte |= 0x80;
418                 *p ++= byte;
419         }
420
421         *endbuf = p;
422 }
423
424 /* ARCHITECTURE SPECIFIC CODE */
425
426 #if defined(TARGET_X86) || defined(TARGET_AMD64) || defined(TARGET_ARM) || defined(TARGET_POWERPC)
427 #define EMIT_DWARF_INFO 1
428 #endif
429
430 #if defined(TARGET_ARM)
431 #define AOT_FUNC_ALIGNMENT 4
432 #else
433 #define AOT_FUNC_ALIGNMENT 16
434 #endif
435  
436 #if defined(TARGET_POWERPC64) && !defined(__mono_ilp32__)
437 #define PPC_LD_OP "ld"
438 #define PPC_LDX_OP "ldx"
439 #else
440 #define PPC_LD_OP "lwz"
441 #define PPC_LDX_OP "lwzx"
442 #endif
443
444 /*
445  * arch_emit_direct_call:
446  *
447  *   Emit a direct call to the symbol TARGET. CALL_SIZE is set to the size of the
448  * calling code.
449  */
450 static void
451 arch_emit_direct_call (MonoAotCompile *acfg, const char *target, int *call_size)
452 {
453 #if defined(TARGET_X86) || defined(TARGET_AMD64)
454         /* Need to make sure this is exactly 5 bytes long */
455         emit_byte (acfg, '\xe8');
456         emit_symbol_diff (acfg, target, ".", -4);
457         *call_size = 5;
458 #elif defined(TARGET_ARM)
459         if (acfg->use_bin_writer) {
460                 guint8 buf [4];
461                 guint8 *code;
462
463                 code = buf;
464                 ARM_BL (code, 0);
465
466                 img_writer_emit_reloc (acfg->w, R_ARM_CALL, target, -8);
467                 emit_bytes (acfg, buf, 4);
468         } else {
469                 img_writer_emit_unset_mode (acfg->w);
470                 fprintf (acfg->fp, "bl %s\n", target);
471         }
472         *call_size = 4;
473 #elif defined(TARGET_POWERPC)
474         if (acfg->use_bin_writer) {
475                 g_assert_not_reached ();
476         } else {
477                 img_writer_emit_unset_mode (acfg->w);
478                 fprintf (acfg->fp, "bl %s\n", target);
479                 *call_size = 4;
480         }
481 #else
482         g_assert_not_reached ();
483 #endif
484 }
485
486 /*
487  * PPC32 design:
488  * - we use an approach similar to the x86 abi: reserve a register (r30) to hold 
489  *   the GOT pointer.
490  * - The full-aot trampolines need access to the GOT of mscorlib, so we store
491  *   in in the 2. slot of every GOT, and require every method to place the GOT
492  *   address in r30, even when it doesn't access the GOT otherwise. This way,
493  *   the trampolines can compute the mscorlib GOT address by loading 4(r30).
494  */
495
496 /*
497  * PPC64 design:
498  * PPC64 uses function descriptors which greatly complicate all code, since
499  * these are used very inconsistently in the runtime. Some functions like 
500  * mono_compile_method () return ftn descriptors, while others like the
501  * trampoline creation functions do not.
502  * We assume that all GOT slots contain function descriptors, and create 
503  * descriptors in aot-runtime.c when needed.
504  * The ppc64 abi uses r2 to hold the address of the TOC/GOT, which is loaded
505  * from function descriptors, we could do the same, but it would require 
506  * rewriting all the ppc/aot code to handle function descriptors properly.
507  * So instead, we use the same approach as on PPC32.
508  * This is a horrible mess, but fixing it would probably lead to an even bigger
509  * one.
510  */
511
512 #ifdef MONO_ARCH_AOT_SUPPORTED
513 /*
514  * arch_emit_got_offset:
515  *
516  *   The memory pointed to by CODE should hold native code for computing the GOT
517  * address. Emit this code while patching it with the offset between code and
518  * the GOT. CODE_SIZE is set to the number of bytes emitted.
519  */
520 static void
521 arch_emit_got_offset (MonoAotCompile *acfg, guint8 *code, int *code_size)
522 {
523 #if defined(TARGET_POWERPC64)
524         g_assert (!acfg->use_bin_writer);
525         img_writer_emit_unset_mode (acfg->w);
526         /* 
527          * The ppc32 code doesn't seem to work on ppc64, the assembler complains about
528          * unsupported relocations. So we store the got address into the .Lgot_addr
529          * symbol which is in the text segment, compute its address, and load it.
530          */
531         fprintf (acfg->fp, ".L%d:\n", acfg->label_generator);
532         fprintf (acfg->fp, "lis 0, (.Lgot_addr + 4 - .L%d)@h\n", acfg->label_generator);
533         fprintf (acfg->fp, "ori 0, 0, (.Lgot_addr + 4 - .L%d)@l\n", acfg->label_generator);
534         fprintf (acfg->fp, "add 30, 30, 0\n");
535         fprintf (acfg->fp, "%s 30, 0(30)\n", PPC_LD_OP);
536         acfg->label_generator ++;
537         *code_size = 16;
538 #elif defined(TARGET_POWERPC)
539         g_assert (!acfg->use_bin_writer);
540         img_writer_emit_unset_mode (acfg->w);
541         fprintf (acfg->fp, ".L%d:\n", acfg->label_generator);
542         fprintf (acfg->fp, "lis 0, (%s + 4 - .L%d)@h\n", acfg->got_symbol, acfg->label_generator);
543         fprintf (acfg->fp, "ori 0, 0, (%s + 4 - .L%d)@l\n", acfg->got_symbol, acfg->label_generator);
544         acfg->label_generator ++;
545         *code_size = 8;
546 #else
547         guint32 offset = mono_arch_get_patch_offset (code);
548         emit_bytes (acfg, code, offset);
549         emit_symbol_diff (acfg, acfg->got_symbol, ".", offset);
550
551         *code_size = offset + 4;
552 #endif
553 }
554
555 /*
556  * arch_emit_got_access:
557  *
558  *   The memory pointed to by CODE should hold native code for loading a GOT
559  * slot. Emit this code while patching it so it accesses the GOT slot GOT_SLOT.
560  * CODE_SIZE is set to the number of bytes emitted.
561  */
562 static void
563 arch_emit_got_access (MonoAotCompile *acfg, guint8 *code, int got_slot, int *code_size)
564 {
565         /* Emit beginning of instruction */
566         emit_bytes (acfg, code, mono_arch_get_patch_offset (code));
567
568         /* Emit the offset */
569 #ifdef TARGET_AMD64
570         emit_symbol_diff (acfg, acfg->got_symbol, ".", (unsigned int) ((got_slot * sizeof (gpointer)) - 4));
571         *code_size = mono_arch_get_patch_offset (code) + 4;
572 #elif defined(TARGET_X86)
573         emit_int32 (acfg, (unsigned int) ((got_slot * sizeof (gpointer))));
574         *code_size = mono_arch_get_patch_offset (code) + 4;
575 #elif defined(TARGET_ARM)
576         emit_symbol_diff (acfg, acfg->got_symbol, ".", (unsigned int) ((got_slot * sizeof (gpointer))) - 12);
577         *code_size = mono_arch_get_patch_offset (code) + 4;
578 #elif defined(TARGET_POWERPC)
579         {
580                 guint8 buf [32];
581                 guint8 *code;
582
583                 code = buf;
584                 ppc_load32 (code, ppc_r0, got_slot * sizeof (gpointer));
585                 g_assert (code - buf == 8);
586                 emit_bytes (acfg, buf, code - buf);
587                 *code_size = code - buf;
588         }
589 #else
590         g_assert_not_reached ();
591 #endif
592 }
593
594 #endif
595
596 /*
597  * arch_emit_plt_entry:
598  *
599  *   Emit code for the PLT entry with index INDEX.
600  */
601 static void
602 arch_emit_plt_entry (MonoAotCompile *acfg, int index)
603 {
604 #if defined(TARGET_X86)
605                 if (index == 0) {
606                         /* It is filled up during loading by the AOT loader. */
607                         emit_zero_bytes (acfg, 16);
608                 } else {
609                         /* Need to make sure this is 9 bytes long */
610                         emit_byte (acfg, '\xe9');
611                         emit_symbol_diff (acfg, acfg->plt_symbol, ".", -4);
612                         emit_int32 (acfg, acfg->plt_got_info_offsets [index]);
613                 }
614 #elif defined(TARGET_AMD64)
615                 /*
616                  * We can't emit jumps because they are 32 bits only so they can't be patched.
617                  * So we make indirect calls through GOT entries which are patched by the AOT 
618                  * loader to point to .Lpd entries. 
619                  * An x86_64 plt entry is 10 bytes long, init_plt () depends on this.
620                  */
621                 /* jmpq *<offset>(%rip) */
622                 emit_byte (acfg, '\xff');
623                 emit_byte (acfg, '\x25');
624                 emit_symbol_diff (acfg, acfg->got_symbol, ".", ((acfg->plt_got_offset_base + index) * sizeof (gpointer)) -4);
625                 /* Used by mono_aot_get_plt_info_offset */
626                 emit_int32 (acfg, acfg->plt_got_info_offsets [index]);
627 #elif defined(TARGET_ARM)
628                 guint8 buf [256];
629                 guint8 *code;
630
631                 /* FIXME:
632                  * - optimize OP_AOTCONST implementation
633                  * - optimize the PLT entries
634                  * - optimize SWITCH AOT implementation
635                  * - implement IMT support
636                  */
637                 code = buf;
638                 if (acfg->use_bin_writer && FALSE) {
639                         /* FIXME: mono_arch_patch_plt_entry () needs to decode this */
640                         /* We only emit 1 relocation since we implement it ourselves anyway */
641                         img_writer_emit_reloc (acfg->w, R_ARM_ALU_PC_G0_NC, acfg->got_symbol, ((acfg->plt_got_offset_base + index) * sizeof (gpointer)) - 8);
642                         /* FIXME: A 2 instruction encoding is sufficient in most cases */
643                         ARM_ADD_REG_IMM (code, ARMREG_IP, ARMREG_PC, 0, 0);
644                         ARM_ADD_REG_IMM (code, ARMREG_IP, ARMREG_IP, 0, 0);
645                         ARM_LDR_IMM (code, ARMREG_PC, ARMREG_IP, 0);
646                         emit_bytes (acfg, buf, code - buf);
647                         /* Used by mono_aot_get_plt_info_offset */
648                         emit_int32 (acfg, acfg->plt_got_info_offsets [index]);
649                 } else {
650                         ARM_LDR_IMM (code, ARMREG_IP, ARMREG_PC, 0);
651                         ARM_LDR_REG_REG (code, ARMREG_PC, ARMREG_PC, ARMREG_IP);
652                         emit_bytes (acfg, buf, code - buf);
653                         emit_symbol_diff (acfg, acfg->got_symbol, ".", ((acfg->plt_got_offset_base + index) * sizeof (gpointer)) - 4);
654                         /* Used by mono_aot_get_plt_info_offset */
655                         emit_int32 (acfg, acfg->plt_got_info_offsets [index]);
656                 }
657                 /* 
658                  * The plt_got_info_offset is computed automatically by 
659                  * mono_aot_get_plt_info_offset (), so no need to save it here.
660                  */
661 #elif defined(TARGET_POWERPC)
662                 guint32 offset = (acfg->plt_got_offset_base + index) * sizeof (gpointer);
663
664                 /* The GOT address is guaranteed to be in r30 by OP_LOAD_GOTADDR */
665                 g_assert (!acfg->use_bin_writer);
666                 img_writer_emit_unset_mode (acfg->w);
667                 fprintf (acfg->fp, "lis 11, %d@h\n", offset);
668                 fprintf (acfg->fp, "ori 11, 11, %d@l\n", offset);
669                 fprintf (acfg->fp, "add 11, 11, 30\n");
670                 fprintf (acfg->fp, "%s 11, 0(11)\n", PPC_LD_OP);
671 #ifdef PPC_USES_FUNCTION_DESCRIPTOR
672                 fprintf (acfg->fp, "%s 2, %d(11)\n", PPC_LD_OP, (int)sizeof (gpointer));
673                 fprintf (acfg->fp, "%s 11, 0(11)\n", PPC_LD_OP);
674 #endif
675                 fprintf (acfg->fp, "mtctr 11\n");
676                 fprintf (acfg->fp, "bctr\n");
677                 emit_int32 (acfg, acfg->plt_got_info_offsets [index]);
678 #else
679                 g_assert_not_reached ();
680 #endif
681 }
682
683 /*
684  * arch_emit_specific_trampoline:
685  *
686  *   Emit code for a specific trampoline. OFFSET is the offset of the first of
687  * two GOT slots which contain the generic trampoline address and the trampoline
688  * argument. TRAMP_SIZE is set to the size of the emitted trampoline.
689  */
690 static void
691 arch_emit_specific_trampoline (MonoAotCompile *acfg, int offset, int *tramp_size)
692 {
693         /*
694          * The trampolines created here are variations of the specific 
695          * trampolines created in mono_arch_create_specific_trampoline (). The 
696          * differences are:
697          * - the generic trampoline address is taken from a got slot.
698          * - the offset of the got slot where the trampoline argument is stored
699          *   is embedded in the instruction stream, and the generic trampoline
700          *   can load the argument by loading the offset, adding it to the
701          *   address of the trampoline to get the address of the got slot, and
702          *   loading the argument from there.
703          * - all the trampolines should be of the same length.
704          */
705 #if defined(TARGET_AMD64)
706         /* This should be exactly 16 bytes long */
707         *tramp_size = 16;
708         /* call *<offset>(%rip) */
709         emit_byte (acfg, '\x41');
710         emit_byte (acfg, '\xff');
711         emit_byte (acfg, '\x15');
712         emit_symbol_diff (acfg, acfg->got_symbol, ".", (offset * sizeof (gpointer)) - 4);
713         /* This should be relative to the start of the trampoline */
714         emit_symbol_diff (acfg, acfg->got_symbol, ".", (offset * sizeof (gpointer)) - 4 + 19);
715         emit_zero_bytes (acfg, 5);
716 #elif defined(TARGET_ARM)
717         guint8 buf [128];
718         guint8 *code;
719
720         /* This should be exactly 20 bytes long */
721         *tramp_size = 20;
722         code = buf;
723         ARM_PUSH (code, 0x5fff);
724         ARM_LDR_IMM (code, ARMREG_R1, ARMREG_PC, 4);
725         /* Load the value from the GOT */
726         ARM_LDR_REG_REG (code, ARMREG_R1, ARMREG_PC, ARMREG_R1);
727         /* Branch to it */
728         ARM_BLX_REG (code, ARMREG_R1);
729
730         g_assert (code - buf == 16);
731
732         /* Emit it */
733         emit_bytes (acfg, buf, code - buf);
734         /* 
735          * Only one offset is needed, since the second one would be equal to the
736          * first one.
737          */
738         emit_symbol_diff (acfg, acfg->got_symbol, ".", (offset * sizeof (gpointer)) - 4 + 4);
739         //emit_symbol_diff (acfg, acfg->got_symbol, ".", ((offset + 1) * sizeof (gpointer)) - 4 + 8);
740 #elif defined(TARGET_POWERPC)
741         guint8 buf [128];
742         guint8 *code;
743
744         *tramp_size = 4;
745         code = buf;
746
747         g_assert (!acfg->use_bin_writer);
748
749         /*
750          * PPC has no ip relative addressing, so we need to compute the address
751          * of the mscorlib got. That is slow and complex, so instead, we store it
752          * in the second got slot of every aot image. The caller already computed
753          * the address of its got and placed it into r30.
754          */
755         img_writer_emit_unset_mode (acfg->w);
756         /* Load mscorlib got address */
757         fprintf (acfg->fp, "%s 0, %d(30)\n", PPC_LD_OP, (int)sizeof (gpointer));
758         /* Load generic trampoline address */
759         fprintf (acfg->fp, "lis 11, %d@h\n", (int)(offset * sizeof (gpointer)));
760         fprintf (acfg->fp, "ori 11, 11, %d@l\n", (int)(offset * sizeof (gpointer)));
761         fprintf (acfg->fp, "%s 11, 11, 0\n", PPC_LDX_OP);
762 #ifdef PPC_USES_FUNCTION_DESCRIPTOR
763         fprintf (acfg->fp, "%s 11, 0(11)\n", PPC_LD_OP);
764 #endif
765         fprintf (acfg->fp, "mtctr 11\n");
766         /* Load trampoline argument */
767         /* On ppc, we pass it normally to the generic trampoline */
768         fprintf (acfg->fp, "lis 11, %d@h\n", (int)((offset + 1) * sizeof (gpointer)));
769         fprintf (acfg->fp, "ori 11, 11, %d@l\n", (int)((offset + 1) * sizeof (gpointer)));
770         fprintf (acfg->fp, "%s 0, 11, 0\n", PPC_LDX_OP);
771         /* Branch to generic trampoline */
772         fprintf (acfg->fp, "bctr\n");
773
774 #ifdef PPC_USES_FUNCTION_DESCRIPTOR
775         *tramp_size = 10 * 4;
776 #else
777         *tramp_size = 9 * 4;
778 #endif
779 #else
780         g_assert_not_reached ();
781 #endif
782 }
783
784 /*
785  * arch_emit_unbox_trampoline:
786  *
787  *   Emit code for the unbox trampoline for METHOD used in the full-aot case.
788  * CALL_TARGET is the symbol pointing to the native code of METHOD.
789  */
790 static void
791 arch_emit_unbox_trampoline (MonoAotCompile *acfg, MonoMethod *method, MonoGenericSharingContext *gsctx, const char *call_target)
792 {
793 #if defined(TARGET_AMD64)
794         guint8 buf [32];
795         guint8 *code;
796         int this_reg;
797
798         this_reg = mono_arch_get_this_arg_reg (mono_method_signature (method), gsctx, NULL);
799         code = buf;
800         amd64_alu_reg_imm (code, X86_ADD, this_reg, sizeof (MonoObject));
801
802         emit_bytes (acfg, buf, code - buf);
803         /* jump <method> */
804         emit_byte (acfg, '\xe9');
805         emit_symbol_diff (acfg, call_target, ".", -4);
806 #elif defined(TARGET_ARM)
807         guint8 buf [128];
808         guint8 *code;
809         int this_pos = 0;
810
811         code = buf;
812
813         if (MONO_TYPE_ISSTRUCT (mono_method_signature (method)->ret))
814                 this_pos = 1;
815
816         ARM_ADD_REG_IMM8 (code, this_pos, this_pos, sizeof (MonoObject));
817
818         emit_bytes (acfg, buf, code - buf);
819         /* jump to method */
820         if (acfg->use_bin_writer) {
821                 guint8 buf [4];
822                 guint8 *code;
823
824                 code = buf;
825                 ARM_B (code, 0);
826
827                 img_writer_emit_reloc (acfg->w, R_ARM_JUMP24, call_target, -8);
828                 emit_bytes (acfg, buf, 4);
829         } else {
830                 fprintf (acfg->fp, "\n\tb %s\n", call_target);
831         }
832 #elif defined(TARGET_POWERPC)
833         int this_pos = 3;
834
835         if (MONO_TYPE_ISSTRUCT (mono_method_signature (method)->ret))
836                 this_pos = 4;
837
838         g_assert (!acfg->use_bin_writer);
839
840         fprintf (acfg->fp, "\n\taddi %d, %d, %d\n", this_pos, this_pos, (int)sizeof (MonoObject));
841         fprintf (acfg->fp, "\n\tb %s\n", call_target);
842 #else
843         g_assert_not_reached ();
844 #endif
845 }
846
847 /*
848  * arch_emit_static_rgctx_trampoline:
849  *
850  *   Emit code for a static rgctx trampoline. OFFSET is the offset of the first of
851  * two GOT slots which contain the rgctx argument, and the method to jump to.
852  * TRAMP_SIZE is set to the size of the emitted trampoline.
853  * These kinds of trampolines cannot be enumerated statically, since there could
854  * be one trampoline per method instantiation, so we emit the same code for all
855  * trampolines, and parameterize them using two GOT slots.
856  */
857 static void
858 arch_emit_static_rgctx_trampoline (MonoAotCompile *acfg, int offset, int *tramp_size)
859 {
860 #if defined(TARGET_AMD64)
861         /* This should be exactly 13 bytes long */
862         *tramp_size = 13;
863
864         /* mov <OFFSET>(%rip), %r10 */
865         emit_byte (acfg, '\x4d');
866         emit_byte (acfg, '\x8b');
867         emit_byte (acfg, '\x15');
868         emit_symbol_diff (acfg, acfg->got_symbol, ".", (offset * sizeof (gpointer)) - 4);
869
870         /* jmp *<offset>(%rip) */
871         emit_byte (acfg, '\xff');
872         emit_byte (acfg, '\x25');
873         emit_symbol_diff (acfg, acfg->got_symbol, ".", ((offset + 1) * sizeof (gpointer)) - 4);
874 #elif defined(TARGET_ARM)
875         guint8 buf [128];
876         guint8 *code;
877
878         /* This should be exactly 24 bytes long */
879         *tramp_size = 24;
880         code = buf;
881         /* Load rgctx value */
882         ARM_LDR_IMM (code, ARMREG_IP, ARMREG_PC, 8);
883         ARM_LDR_REG_REG (code, MONO_ARCH_RGCTX_REG, ARMREG_PC, ARMREG_IP);
884         /* Load branch addr + branch */
885         ARM_LDR_IMM (code, ARMREG_IP, ARMREG_PC, 4);
886         ARM_LDR_REG_REG (code, ARMREG_PC, ARMREG_PC, ARMREG_IP);
887
888         g_assert (code - buf == 16);
889
890         /* Emit it */
891         emit_bytes (acfg, buf, code - buf);
892         emit_symbol_diff (acfg, acfg->got_symbol, ".", (offset * sizeof (gpointer)) - 4 + 8);
893         emit_symbol_diff (acfg, acfg->got_symbol, ".", ((offset + 1) * sizeof (gpointer)) - 4 + 4);
894 #elif defined(TARGET_POWERPC)
895         guint8 buf [128];
896         guint8 *code;
897
898         *tramp_size = 4;
899         code = buf;
900
901         g_assert (!acfg->use_bin_writer);
902
903         /*
904          * PPC has no ip relative addressing, so we need to compute the address
905          * of the mscorlib got. That is slow and complex, so instead, we store it
906          * in the second got slot of every aot image. The caller already computed
907          * the address of its got and placed it into r30.
908          */
909         img_writer_emit_unset_mode (acfg->w);
910         /* Load mscorlib got address */
911         fprintf (acfg->fp, "%s 0, %d(30)\n", PPC_LD_OP, (int)sizeof (gpointer));
912         /* Load rgctx */
913         fprintf (acfg->fp, "lis 11, %d@h\n", (int)(offset * sizeof (gpointer)));
914         fprintf (acfg->fp, "ori 11, 11, %d@l\n", (int)(offset * sizeof (gpointer)));
915         fprintf (acfg->fp, "%s %d, 11, 0\n", PPC_LDX_OP, MONO_ARCH_RGCTX_REG);
916         /* Load target address */
917         fprintf (acfg->fp, "lis 11, %d@h\n", (int)((offset + 1) * sizeof (gpointer)));
918         fprintf (acfg->fp, "ori 11, 11, %d@l\n", (int)((offset + 1) * sizeof (gpointer)));
919         fprintf (acfg->fp, "%s 11, 11, 0\n", PPC_LDX_OP);
920 #ifdef PPC_USES_FUNCTION_DESCRIPTOR
921         fprintf (acfg->fp, "%s 2, %d(11)\n", PPC_LD_OP, (int)sizeof (gpointer));
922         fprintf (acfg->fp, "%s 11, 0(11)\n", PPC_LD_OP);
923 #endif
924         fprintf (acfg->fp, "mtctr 11\n");
925         /* Branch to the target address */
926         fprintf (acfg->fp, "bctr\n");
927
928 #ifdef PPC_USES_FUNCTION_DESCRIPTOR
929         *tramp_size = 11 * 4;
930 #else
931         *tramp_size = 9 * 4;
932 #endif
933
934 #else
935         g_assert_not_reached ();
936 #endif
937 }       
938
939 /*
940  * arch_emit_imt_thunk:
941  *
942  *   Emit an IMT thunk usable in full-aot mode. The thunk uses 1 got slot which
943  * points to an array of pointer pairs. The pairs of the form [key, ptr], where
944  * key is the IMT key, and ptr holds the address of a memory location holding
945  * the address to branch to if the IMT arg matches the key. The array is 
946  * terminated by a pair whose key is NULL, and whose ptr is the address of the 
947  * fail_tramp.
948  * TRAMP_SIZE is set to the size of the emitted trampoline.
949  */
950 static void
951 arch_emit_imt_thunk (MonoAotCompile *acfg, int offset, int *tramp_size)
952 {
953 #if defined(TARGET_AMD64)
954         guint8 *buf, *code;
955         guint8 *labels [3];
956
957         code = buf = g_malloc (256);
958
959         /* FIXME: Optimize this, i.e. use binary search etc. */
960         /* Maybe move the body into a separate function (slower, but much smaller) */
961
962         /* R10 is a free register */
963
964         labels [0] = code;
965         amd64_alu_membase_imm (code, X86_CMP, AMD64_R10, 0, 0);
966         labels [1] = code;
967         amd64_branch8 (code, X86_CC_Z, FALSE, 0);
968
969         /* Check key */
970         amd64_alu_membase_reg (code, X86_CMP, AMD64_R10, 0, MONO_ARCH_IMT_REG);
971         labels [2] = code;
972         amd64_branch8 (code, X86_CC_Z, FALSE, 0);
973
974         /* Loop footer */
975         amd64_alu_reg_imm (code, X86_ADD, AMD64_R10, 2 * sizeof (gpointer));
976         amd64_jump_code (code, labels [0]);
977
978         /* Match */
979         mono_amd64_patch (labels [2], code);
980         amd64_mov_reg_membase (code, AMD64_R10, AMD64_R10, sizeof (gpointer), 8);
981         amd64_jump_membase (code, AMD64_R10, 0);
982
983         /* No match */
984         /* FIXME: */
985         mono_amd64_patch (labels [1], code);
986         x86_breakpoint (code);
987
988         /* mov <OFFSET>(%rip), %r10 */
989         emit_byte (acfg, '\x4d');
990         emit_byte (acfg, '\x8b');
991         emit_byte (acfg, '\x15');
992         emit_symbol_diff (acfg, acfg->got_symbol, ".", (offset * sizeof (gpointer)) - 4);
993
994         emit_bytes (acfg, buf, code - buf);
995         
996         *tramp_size = code - buf + 7;
997 #elif defined(TARGET_ARM)
998         guint8 buf [128];
999         guint8 *code, *code2, *labels [16];
1000
1001         code = buf;
1002
1003         /* The IMT method is in v5 */
1004
1005         /* Need at least two free registers, plus a slot for storing the pc */
1006         ARM_PUSH (code, (1 << ARMREG_R0)|(1 << ARMREG_R1)|(1 << ARMREG_R2));
1007         labels [0] = code;
1008         /* Load the parameter from the GOT */
1009         ARM_LDR_IMM (code, ARMREG_R0, ARMREG_PC, 0);
1010         ARM_LDR_REG_REG (code, ARMREG_R0, ARMREG_PC, ARMREG_R0);
1011
1012         labels [1] = code;
1013         ARM_LDR_IMM (code, ARMREG_R1, ARMREG_R0, 0);
1014         ARM_CMP_REG_REG (code, ARMREG_R1, ARMREG_V5);
1015         labels [2] = code;
1016         ARM_B_COND (code, ARMCOND_EQ, 0);
1017
1018         /* End-of-loop check */
1019         ARM_CMP_REG_IMM (code, ARMREG_R1, 0, 0);
1020         labels [3] = code;
1021         ARM_B_COND (code, ARMCOND_EQ, 0);
1022
1023         /* Loop footer */
1024         ARM_ADD_REG_IMM8 (code, ARMREG_R0, ARMREG_R0, sizeof (gpointer) * 2);
1025         labels [4] = code;
1026         ARM_B (code, 0);
1027         arm_patch (labels [4], labels [1]);
1028
1029         /* Match */
1030         arm_patch (labels [2], code);
1031         ARM_LDR_IMM (code, ARMREG_R0, ARMREG_R0, 4);
1032         ARM_LDR_IMM (code, ARMREG_R0, ARMREG_R0, 0);
1033         /* Save it to the third stack slot */
1034         ARM_STR_IMM (code, ARMREG_R0, ARMREG_SP, 8);
1035         /* Restore the registers and branch */
1036         ARM_POP (code, (1 << ARMREG_R0)|(1 << ARMREG_R1)|(1 << ARMREG_PC));
1037
1038         /* No match */
1039         arm_patch (labels [3], code);
1040         ARM_DBRK (code);
1041
1042         /* Fixup offset */
1043         code2 = labels [0];
1044         ARM_LDR_IMM (code2, ARMREG_R0, ARMREG_PC, (code - (labels [0] + 8)));
1045
1046         emit_bytes (acfg, buf, code - buf);
1047         emit_symbol_diff (acfg, acfg->got_symbol, ".", (offset * sizeof (gpointer)) + (code - (labels [0] + 8)) - 4);
1048
1049         *tramp_size = code - buf + 4;
1050 #elif defined(TARGET_POWERPC)
1051         guint8 buf [128];
1052         guint8 *code, *labels [16];
1053
1054         code = buf;
1055
1056         /* Load the mscorlib got address */
1057         ppc_ldptr (code, ppc_r11, sizeof (gpointer), ppc_r30);
1058         /* Load the parameter from the GOT */
1059         ppc_load (code, ppc_r0, offset * sizeof (gpointer));
1060         ppc_ldptr_indexed (code, ppc_r11, ppc_r11, ppc_r0);
1061
1062         /* Load and check key */
1063         labels [1] = code;
1064         ppc_ldptr (code, ppc_r0, 0, ppc_r11);
1065         ppc_cmp (code, 0, sizeof (gpointer) == 8 ? 1 : 0, ppc_r0, MONO_ARCH_IMT_REG);
1066         labels [2] = code;
1067         ppc_bc (code, PPC_BR_TRUE, PPC_BR_EQ, 0);
1068
1069         /* End-of-loop check */
1070         ppc_cmpi (code, 0, sizeof (gpointer) == 8 ? 1 : 0, ppc_r0, 0);
1071         labels [3] = code;
1072         ppc_bc (code, PPC_BR_TRUE, PPC_BR_EQ, 0);
1073
1074         /* Loop footer */
1075         ppc_addi (code, ppc_r11, ppc_r11, 2 * sizeof (gpointer));
1076         labels [4] = code;
1077         ppc_b (code, 0);
1078         mono_ppc_patch (labels [4], labels [1]);
1079
1080         /* Match */
1081         mono_ppc_patch (labels [2], code);
1082         ppc_ldptr (code, ppc_r11, sizeof (gpointer), ppc_r11);
1083         /* r11 now contains the value of the vtable slot */
1084         /* this is not a function descriptor on ppc64 */
1085         ppc_ldptr (code, ppc_r11, 0, ppc_r11);
1086         ppc_mtctr (code, ppc_r11);
1087         ppc_bcctr (code, PPC_BR_ALWAYS, 0);
1088
1089         /* Fail */
1090         mono_ppc_patch (labels [3], code);
1091         /* FIXME: */
1092         ppc_break (code);
1093
1094         *tramp_size = code - buf;
1095
1096         emit_bytes (acfg, buf, code - buf);
1097 #else
1098         g_assert_not_reached ();
1099 #endif
1100 }
1101
1102 /*
1103  * arch_get_cie_program:
1104  *
1105  *   Get the unwind bytecode for the DWARF CIE.
1106  */
1107 static GSList*
1108 arch_get_cie_program (void)
1109 {
1110 #ifdef TARGET_AMD64
1111         GSList *l = NULL;
1112
1113         mono_add_unwind_op_def_cfa (l, (guint8*)NULL, (guint8*)NULL, AMD64_RSP, 8);
1114         mono_add_unwind_op_offset (l, (guint8*)NULL, (guint8*)NULL, AMD64_RIP, -8);
1115
1116         return l;
1117 #elif defined(TARGET_POWERPC)
1118         GSList *l = NULL;
1119
1120         mono_add_unwind_op_def_cfa (l, (guint8*)NULL, (guint8*)NULL, ppc_r1, 0);
1121
1122         return l;
1123 #else
1124         return NULL;
1125 #endif
1126 }
1127
1128 /* END OF ARCH SPECIFIC CODE */
1129
1130 static guint32
1131 mono_get_field_token (MonoClassField *field) 
1132 {
1133         MonoClass *klass = field->parent;
1134         int i;
1135
1136         for (i = 0; i < klass->field.count; ++i) {
1137                 if (field == &klass->fields [i])
1138                         return MONO_TOKEN_FIELD_DEF | (klass->field.first + 1 + i);
1139         }
1140
1141         g_assert_not_reached ();
1142         return 0;
1143 }
1144
1145 static inline void
1146 encode_value (gint32 value, guint8 *buf, guint8 **endbuf)
1147 {
1148         guint8 *p = buf;
1149
1150         //printf ("ENCODE: %d 0x%x.\n", value, value);
1151
1152         /* 
1153          * Same encoding as the one used in the metadata, extended to handle values
1154          * greater than 0x1fffffff.
1155          */
1156         if ((value >= 0) && (value <= 127))
1157                 *p++ = value;
1158         else if ((value >= 0) && (value <= 16383)) {
1159                 p [0] = 0x80 | (value >> 8);
1160                 p [1] = value & 0xff;
1161                 p += 2;
1162         } else if ((value >= 0) && (value <= 0x1fffffff)) {
1163                 p [0] = (value >> 24) | 0xc0;
1164                 p [1] = (value >> 16) & 0xff;
1165                 p [2] = (value >> 8) & 0xff;
1166                 p [3] = value & 0xff;
1167                 p += 4;
1168         }
1169         else {
1170                 p [0] = 0xff;
1171                 p [1] = (value >> 24) & 0xff;
1172                 p [2] = (value >> 16) & 0xff;
1173                 p [3] = (value >> 8) & 0xff;
1174                 p [4] = value & 0xff;
1175                 p += 5;
1176         }
1177         if (endbuf)
1178                 *endbuf = p;
1179 }
1180
1181 static guint32
1182 get_image_index (MonoAotCompile *cfg, MonoImage *image)
1183 {
1184         guint32 index;
1185
1186         index = GPOINTER_TO_UINT (g_hash_table_lookup (cfg->image_hash, image));
1187         if (index)
1188                 return index - 1;
1189         else {
1190                 index = g_hash_table_size (cfg->image_hash);
1191                 g_hash_table_insert (cfg->image_hash, image, GUINT_TO_POINTER (index + 1));
1192                 g_ptr_array_add (cfg->image_table, image);
1193                 return index;
1194         }
1195 }
1196
1197 static guint32
1198 find_typespec_for_class (MonoAotCompile *acfg, MonoClass *klass)
1199 {
1200         int i;
1201         MonoClass *k = NULL;
1202
1203         /* FIXME: Search referenced images as well */
1204         for (i = 0; i < acfg->image->tables [MONO_TABLE_TYPESPEC].rows; ++i) {
1205                 k = mono_class_get_full (acfg->image, MONO_TOKEN_TYPE_SPEC | (i + 1), NULL);
1206                 if (k == klass)
1207                         break;
1208         }
1209
1210         if (i < acfg->image->tables [MONO_TABLE_TYPESPEC].rows)
1211                 return MONO_TOKEN_TYPE_SPEC | (i + 1);
1212         else
1213                 return 0;
1214 }
1215
1216 static void
1217 encode_method_ref (MonoAotCompile *acfg, MonoMethod *method, guint8 *buf, guint8 **endbuf);
1218
1219 /*
1220  * encode_klass_ref:
1221  *
1222  *   Encode a reference to KLASS. We use our home-grown encoding instead of the
1223  * standard metadata encoding.
1224  */
1225 static void
1226 encode_klass_ref (MonoAotCompile *acfg, MonoClass *klass, guint8 *buf, guint8 **endbuf)
1227 {
1228         guint8 *p = buf;
1229
1230         if (klass->generic_class) {
1231                 guint32 token;
1232                 g_assert (klass->type_token);
1233
1234                 /* Find a typespec for a class if possible */
1235                 token = find_typespec_for_class (acfg, klass);
1236                 if (token) {
1237                         encode_value (token, p, &p);
1238                         encode_value (get_image_index (acfg, acfg->image), p, &p);
1239                 } else {
1240                         MonoClass *gclass = klass->generic_class->container_class;
1241                         MonoGenericInst *inst = klass->generic_class->context.class_inst;
1242                         int i;
1243
1244                         /* Encode it ourselves */
1245                         /* Marker */
1246                         encode_value (MONO_TOKEN_TYPE_SPEC, p, &p);
1247                         encode_value (MONO_TYPE_GENERICINST, p, &p);
1248                         encode_klass_ref (acfg, gclass, p, &p);
1249                         encode_value (inst->type_argc, p, &p);
1250                         for (i = 0; i < inst->type_argc; ++i)
1251                                 encode_klass_ref (acfg, mono_class_from_mono_type (inst->type_argv [i]), p, &p);
1252                 }
1253         } else if (klass->type_token) {
1254                 g_assert (mono_metadata_token_code (klass->type_token) == MONO_TOKEN_TYPE_DEF);
1255                 encode_value (klass->type_token - MONO_TOKEN_TYPE_DEF, p, &p);
1256                 encode_value (get_image_index (acfg, klass->image), p, &p);
1257         } else if ((klass->byval_arg.type == MONO_TYPE_VAR) || (klass->byval_arg.type == MONO_TYPE_MVAR)) {
1258                 MonoGenericContainer *container = mono_type_get_generic_param_owner (&klass->byval_arg);
1259                 g_assert (container);
1260
1261                 /* Marker */
1262                 encode_value (MONO_TOKEN_TYPE_SPEC, p, &p);
1263                 encode_value (klass->byval_arg.type, p, &p);
1264
1265                 encode_value (mono_type_get_generic_param_num (&klass->byval_arg), p, &p);
1266                 
1267                 encode_value (container->is_method, p, &p);
1268                 if (container->is_method)
1269                         encode_method_ref (acfg, container->owner.method, p, &p);
1270                 else
1271                         encode_klass_ref (acfg, container->owner.klass, p, &p);
1272         } else {
1273                 /* Array class */
1274                 g_assert (klass->rank > 0);
1275                 encode_value (MONO_TOKEN_TYPE_DEF, p, &p);
1276                 encode_value (get_image_index (acfg, klass->image), p, &p);
1277                 encode_value (klass->rank, p, &p);
1278                 encode_klass_ref (acfg, klass->element_class, p, &p);
1279         }
1280         *endbuf = p;
1281 }
1282
1283 static void
1284 encode_field_info (MonoAotCompile *cfg, MonoClassField *field, guint8 *buf, guint8 **endbuf)
1285 {
1286         guint32 token = mono_get_field_token (field);
1287         guint8 *p = buf;
1288
1289         encode_klass_ref (cfg, field->parent, p, &p);
1290         g_assert (mono_metadata_token_code (token) == MONO_TOKEN_FIELD_DEF);
1291         encode_value (token - MONO_TOKEN_FIELD_DEF, p, &p);
1292         *endbuf = p;
1293 }
1294
1295 static void
1296 encode_generic_context (MonoAotCompile *acfg, MonoGenericContext *context, guint8 *buf, guint8 **endbuf)
1297 {
1298         guint8 *p = buf;
1299         int i;
1300         MonoGenericInst *inst;
1301
1302         /* Encode the context */
1303         inst = context->class_inst;
1304         encode_value (inst ? 1 : 0, p, &p);
1305         if (inst) {
1306                 encode_value (inst->type_argc, p, &p);
1307                 for (i = 0; i < inst->type_argc; ++i)
1308                         encode_klass_ref (acfg, mono_class_from_mono_type (inst->type_argv [i]), p, &p);
1309         }
1310         inst = context->method_inst;
1311         encode_value (inst ? 1 : 0, p, &p);
1312         if (inst) {
1313                 encode_value (inst->type_argc, p, &p);
1314                 for (i = 0; i < inst->type_argc; ++i)
1315                         encode_klass_ref (acfg, mono_class_from_mono_type (inst->type_argv [i]), p, &p);
1316         }
1317
1318         *endbuf = p;
1319 }
1320
1321 #define MAX_IMAGE_INDEX 250
1322
1323 static void
1324 encode_method_ref (MonoAotCompile *acfg, MonoMethod *method, guint8 *buf, guint8 **endbuf)
1325 {
1326         guint32 image_index = get_image_index (acfg, method->klass->image);
1327         guint32 token = method->token;
1328         MonoJumpInfoToken *ji;
1329         guint8 *p = buf;
1330         char *name;
1331
1332         /*
1333          * The encoding for most methods is as follows:
1334          * - image index encoded as a leb128
1335          * - token index encoded as a leb128
1336          * Values of image index >= MONO_AOT_METHODREF_MIN are used to mark additional
1337          * types of method encodings.
1338          */
1339
1340         g_assert (image_index < MONO_AOT_METHODREF_MIN);
1341
1342         /* Mark methods which can't use aot trampolines because they need the further 
1343          * processing in mono_magic_trampoline () which requires a MonoMethod*.
1344          */
1345         if ((method->is_generic && (method->flags & METHOD_ATTRIBUTE_VIRTUAL)) ||
1346                 (method->iflags & METHOD_IMPL_ATTRIBUTE_SYNCHRONIZED))
1347                 encode_value ((MONO_AOT_METHODREF_NO_AOT_TRAMPOLINE << 24), p, &p);
1348
1349         /* 
1350          * Some wrapper methods are shared using their signature, encode their 
1351          * stringified signature instead.
1352          * FIXME: Optimize disk usage
1353          */
1354         name = NULL;
1355         if (method->wrapper_type) {
1356                 if (method->wrapper_type == MONO_WRAPPER_RUNTIME_INVOKE) {
1357                         char *tmpsig = mono_signature_get_desc (mono_method_signature (method), TRUE);
1358                         if (strcmp (method->name, "runtime_invoke_dynamic")) {
1359                                 name = mono_aot_wrapper_name (method);
1360                         } else if (mono_marshal_method_from_wrapper (method) != method) {
1361                                 /* Direct wrapper, encode it normally */
1362                         } else {
1363                                 name = g_strdup_printf ("(wrapper runtime-invoke):%s (%s)", method->name, tmpsig);
1364                         }
1365                         g_free (tmpsig);
1366                 } else if (method->wrapper_type == MONO_WRAPPER_DELEGATE_INVOKE) {
1367                         char *tmpsig = mono_signature_get_desc (mono_method_signature (method), TRUE);
1368                         name = g_strdup_printf ("(wrapper delegate-invoke):%s (%s)", method->name, tmpsig);
1369                         g_free (tmpsig);
1370                 } else if (method->wrapper_type == MONO_WRAPPER_DELEGATE_BEGIN_INVOKE) {
1371                         char *tmpsig = mono_signature_get_desc (mono_method_signature (method), TRUE);
1372                         name = g_strdup_printf ("(wrapper delegate-begin-invoke):%s (%s)", method->name, tmpsig);
1373                         g_free (tmpsig);
1374                 } else if (method->wrapper_type == MONO_WRAPPER_DELEGATE_END_INVOKE) {
1375                         char *tmpsig = mono_signature_get_desc (mono_method_signature (method), TRUE);
1376                         name = g_strdup_printf ("(wrapper delegate-end-invoke):%s (%s)", method->name, tmpsig);
1377                         g_free (tmpsig);
1378                 }
1379         }
1380
1381         if (name) {
1382                 encode_value ((MONO_AOT_METHODREF_WRAPPER_NAME << 24), p, &p);
1383                 strcpy ((char*)p, name);
1384                 p += strlen (name) + 1;
1385                 g_free (name);
1386         } else if (method->wrapper_type) {
1387                 encode_value ((MONO_AOT_METHODREF_WRAPPER << 24), p, &p);
1388
1389                 encode_value (method->wrapper_type, p, &p);
1390
1391                 switch (method->wrapper_type) {
1392                 case MONO_WRAPPER_REMOTING_INVOKE:
1393                 case MONO_WRAPPER_REMOTING_INVOKE_WITH_CHECK:
1394                 case MONO_WRAPPER_XDOMAIN_INVOKE: {
1395                         MonoMethod *m;
1396
1397                         m = mono_marshal_method_from_wrapper (method);
1398                         g_assert (m);
1399                         encode_method_ref (acfg, m, p, &p);
1400                         break;
1401                 }
1402                 case MONO_WRAPPER_PROXY_ISINST:
1403                 case MONO_WRAPPER_LDFLD:
1404                 case MONO_WRAPPER_LDFLDA:
1405                 case MONO_WRAPPER_STFLD:
1406                 case MONO_WRAPPER_ISINST: {
1407                         MonoClass *proxy_class = (MonoClass*)mono_marshal_method_from_wrapper (method);
1408                         encode_klass_ref (acfg, proxy_class, p, &p);
1409                         break;
1410                 }
1411                 case MONO_WRAPPER_LDFLD_REMOTE:
1412                 case MONO_WRAPPER_STFLD_REMOTE:
1413                         break;
1414                 case MONO_WRAPPER_ALLOC: {
1415                         int alloc_type = mono_gc_get_managed_allocator_type (method);
1416                         g_assert (alloc_type != -1);
1417                         encode_value (alloc_type, p, &p);
1418                         break;
1419                 }
1420                 case MONO_WRAPPER_STELEMREF:
1421                         break;
1422                 case MONO_WRAPPER_UNKNOWN:
1423                         if (strcmp (method->name, "FastMonitorEnter") == 0)
1424                                 encode_value (MONO_AOT_WRAPPER_MONO_ENTER, p, &p);
1425                         else if (strcmp (method->name, "FastMonitorExit") == 0)
1426                                 encode_value (MONO_AOT_WRAPPER_MONO_EXIT, p, &p);
1427                         else
1428                                 g_assert_not_reached ();
1429                         break;
1430                 case MONO_WRAPPER_SYNCHRONIZED:
1431                 case MONO_WRAPPER_MANAGED_TO_NATIVE:
1432                 case MONO_WRAPPER_RUNTIME_INVOKE: {
1433                         MonoMethod *m;
1434
1435                         m = mono_marshal_method_from_wrapper (method);
1436                         g_assert (m);
1437                         g_assert (m != method);
1438                         encode_method_ref (acfg, m, p, &p);
1439                         break;
1440                 }
1441                 default:
1442                         g_assert_not_reached ();
1443                 }
1444         } else if (mono_method_signature (method)->is_inflated) {
1445                 /* 
1446                  * This is a generic method, find the original token which referenced it and
1447                  * encode that.
1448                  * Obtain the token from information recorded by the JIT.
1449                  */
1450                 ji = g_hash_table_lookup (acfg->token_info_hash, method);
1451                 if (ji) {
1452                         image_index = get_image_index (acfg, ji->image);
1453                         g_assert (image_index < MAX_IMAGE_INDEX);
1454                         token = ji->token;
1455
1456                         encode_value ((MONO_AOT_METHODREF_METHODSPEC << 24), p, &p);
1457                         encode_value (image_index, p, &p);
1458                         encode_value (token, p, &p);
1459                 } else {
1460                         MonoMethod *declaring;
1461                         MonoGenericContext *context = mono_method_get_context (method);
1462
1463                         g_assert (method->is_inflated);
1464                         declaring = ((MonoMethodInflated*)method)->declaring;
1465
1466                         /*
1467                          * This might be a non-generic method of a generic instance, which 
1468                          * doesn't have a token since the reference is generated by the JIT 
1469                          * like Nullable:Box/Unbox, or by generic sharing.
1470                          */
1471
1472                         encode_value ((MONO_AOT_METHODREF_GINST << 24), p, &p);
1473                         /* Encode the klass */
1474                         encode_klass_ref (acfg, method->klass, p, &p);
1475                         /* Encode the method */
1476                         image_index = get_image_index (acfg, method->klass->image);
1477                         g_assert (image_index < MAX_IMAGE_INDEX);
1478                         g_assert (declaring->token);
1479                         token = declaring->token;
1480                         g_assert (mono_metadata_token_table (token) == MONO_TABLE_METHOD);
1481                         encode_value (image_index, p, &p);
1482                         encode_value (token, p, &p);
1483                         encode_generic_context (acfg, context, p, &p);
1484                 }
1485         } else if (token == 0) {
1486                 /* This might be a method of a constructed type like int[,].Set */
1487                 /* Obtain the token from information recorded by the JIT */
1488                 ji = g_hash_table_lookup (acfg->token_info_hash, method);
1489                 if (ji) {
1490                         image_index = get_image_index (acfg, ji->image);
1491                         g_assert (image_index < MAX_IMAGE_INDEX);
1492                         token = ji->token;
1493
1494                         encode_value ((MONO_AOT_METHODREF_METHODSPEC << 24), p, &p);
1495                         encode_value (image_index, p, &p);
1496                         encode_value (token, p, &p);
1497                 } else {
1498                         /* Array methods */
1499                         g_assert (method->klass->rank);
1500
1501                         /* Encode directly */
1502                         encode_value ((MONO_AOT_METHODREF_ARRAY << 24), p, &p);
1503                         encode_klass_ref (acfg, method->klass, p, &p);
1504                         if (!strcmp (method->name, ".ctor") && mono_method_signature (method)->param_count == method->klass->rank)
1505                                 encode_value (0, p, &p);
1506                         else if (!strcmp (method->name, ".ctor") && mono_method_signature (method)->param_count == method->klass->rank * 2)
1507                                 encode_value (1, p, &p);
1508                         else if (!strcmp (method->name, "Get"))
1509                                 encode_value (2, p, &p);
1510                         else if (!strcmp (method->name, "Address"))
1511                                 encode_value (3, p, &p);
1512                         else if (!strcmp (method->name, "Set"))
1513                                 encode_value (4, p, &p);
1514                         else
1515                                 g_assert_not_reached ();
1516                 }
1517         } else {
1518                 g_assert (mono_metadata_token_table (token) == MONO_TABLE_METHOD);
1519                 encode_value ((image_index << 24) | mono_metadata_token_index (token), p, &p);
1520         }
1521         *endbuf = p;
1522 }
1523
1524 static gint
1525 compare_patches (gconstpointer a, gconstpointer b)
1526 {
1527         int i, j;
1528
1529         i = (*(MonoJumpInfo**)a)->ip.i;
1530         j = (*(MonoJumpInfo**)b)->ip.i;
1531
1532         if (i < j)
1533                 return -1;
1534         else
1535                 if (i > j)
1536                         return 1;
1537         else
1538                 return 0;
1539 }
1540
1541 /*
1542  * is_plt_patch:
1543  *
1544  *   Return whenever PATCH_INFO refers to a direct call, and thus requires a
1545  * PLT entry.
1546  */
1547 static inline gboolean
1548 is_plt_patch (MonoJumpInfo *patch_info)
1549 {
1550         switch (patch_info->type) {
1551         case MONO_PATCH_INFO_METHOD:
1552         case MONO_PATCH_INFO_INTERNAL_METHOD:
1553         case MONO_PATCH_INFO_JIT_ICALL_ADDR:
1554         case MONO_PATCH_INFO_ICALL_ADDR:
1555         case MONO_PATCH_INFO_CLASS_INIT:
1556         case MONO_PATCH_INFO_RGCTX_FETCH:
1557         case MONO_PATCH_INFO_GENERIC_CLASS_INIT:
1558         case MONO_PATCH_INFO_MONITOR_ENTER:
1559         case MONO_PATCH_INFO_MONITOR_EXIT:
1560                 return TRUE;
1561         default:
1562                 return FALSE;
1563         }
1564 }
1565
1566 static int
1567 get_plt_offset (MonoAotCompile *acfg, MonoJumpInfo *patch_info)
1568 {
1569         int res = -1;
1570
1571         if (is_plt_patch (patch_info)) {
1572                 int idx = GPOINTER_TO_UINT (g_hash_table_lookup (acfg->patch_to_plt_offset, patch_info));
1573
1574                 if (patch_info->type == MONO_PATCH_INFO_METHOD && (patch_info->data.method->iflags & METHOD_IMPL_ATTRIBUTE_SYNCHRONIZED)) {
1575                         /* 
1576                          * Allocate a separate PLT slot for each such patch, since some plt
1577                          * entries will refer to the method itself, and some will refer to
1578                          * wrapper.
1579                          */
1580                         idx = 0;
1581                 }
1582
1583                 if (idx) {
1584                         res = idx;
1585                 } else {
1586                         MonoJumpInfo *new_ji = mono_patch_info_dup_mp (acfg->mempool, patch_info);
1587
1588                         res = acfg->plt_offset;
1589                         g_hash_table_insert (acfg->plt_offset_to_patch, GUINT_TO_POINTER (res), new_ji);
1590                         g_hash_table_insert (acfg->patch_to_plt_offset, new_ji, GUINT_TO_POINTER (res));
1591                         acfg->plt_offset ++;
1592                 }
1593         }
1594
1595         return res;
1596 }
1597
1598 /**
1599  * get_got_offset:
1600  *
1601  *   Returns the offset of the GOT slot where the runtime object resulting from resolving
1602  * JI could be found if it exists, otherwise allocates a new one.
1603  */
1604 static guint32
1605 get_got_offset (MonoAotCompile *acfg, MonoJumpInfo *ji)
1606 {
1607         guint32 got_offset;
1608
1609         got_offset = GPOINTER_TO_UINT (g_hash_table_lookup (acfg->patch_to_got_offset, ji));
1610         if (got_offset)
1611                 return got_offset - 1;
1612
1613         got_offset = acfg->got_offset;
1614         acfg->got_offset ++;
1615
1616         acfg->stats.got_slots ++;
1617         acfg->stats.got_slot_types [ji->type] ++;
1618
1619         g_hash_table_insert (acfg->patch_to_got_offset, ji, GUINT_TO_POINTER (got_offset + 1));
1620         g_ptr_array_add (acfg->got_patches, ji);
1621
1622         return got_offset;
1623 }
1624
1625 /* Add a method to the list of methods which need to be emitted */
1626 static void
1627 add_method_with_index (MonoAotCompile *acfg, MonoMethod *method, int index, gboolean extra)
1628 {
1629         g_assert (method);
1630         if (!g_hash_table_lookup (acfg->method_indexes, method)) {
1631                 g_ptr_array_add (acfg->methods, method);
1632                 g_hash_table_insert (acfg->method_indexes, method, GUINT_TO_POINTER (index + 1));
1633                 acfg->nmethods = acfg->methods->len + 1;
1634         }
1635
1636         if (method->wrapper_type || extra)
1637                 g_ptr_array_add (acfg->extra_methods, method);
1638 }
1639
1640 static guint32
1641 get_method_index (MonoAotCompile *acfg, MonoMethod *method)
1642 {
1643         int index = GPOINTER_TO_UINT (g_hash_table_lookup (acfg->method_indexes, method));
1644         
1645         g_assert (index);
1646
1647         return index - 1;
1648 }
1649
1650 static int
1651 add_method_full (MonoAotCompile *acfg, MonoMethod *method, gboolean extra)
1652 {
1653         int index;
1654
1655         index = GPOINTER_TO_UINT (g_hash_table_lookup (acfg->method_indexes, method));
1656         if (index)
1657                 return index - 1;
1658
1659         index = acfg->method_index;
1660         add_method_with_index (acfg, method, index, extra);
1661
1662         /* FIXME: Fix quadratic behavior */
1663         acfg->method_order = g_list_append (acfg->method_order, GUINT_TO_POINTER (index));
1664
1665         acfg->method_index ++;
1666
1667         return index;
1668 }
1669
1670 static int
1671 add_method (MonoAotCompile *acfg, MonoMethod *method)
1672 {
1673         return add_method_full (acfg, method, FALSE);
1674 }
1675
1676 static void
1677 add_extra_method (MonoAotCompile *acfg, MonoMethod *method)
1678 {
1679         add_method_full (acfg, method, TRUE);
1680 }
1681
1682 static void
1683 add_jit_icall_wrapper (gpointer key, gpointer value, gpointer user_data)
1684 {
1685         MonoAotCompile *acfg = user_data;
1686         MonoJitICallInfo *callinfo = value;
1687         MonoMethod *wrapper;
1688         char *name;
1689
1690         if (!callinfo->sig)
1691                 return;
1692
1693         name = g_strdup_printf ("__icall_wrapper_%s", callinfo->name);
1694         wrapper = mono_marshal_get_icall_wrapper (callinfo->sig, name, callinfo->func, check_for_pending_exc);
1695         g_free (name);
1696
1697         add_method (acfg, wrapper);
1698 }
1699
1700 static MonoMethod*
1701 get_runtime_invoke_sig (MonoMethodSignature *sig)
1702 {
1703         MonoMethodBuilder *mb;
1704         MonoMethod *m;
1705
1706         mb = mono_mb_new (mono_defaults.object_class, "FOO", MONO_WRAPPER_NONE);
1707         m = mono_mb_create_method (mb, sig, 16);
1708         return mono_marshal_get_runtime_invoke (m, FALSE);
1709 }
1710
1711 static void
1712 add_wrappers (MonoAotCompile *acfg)
1713 {
1714         MonoMethod *method, *m;
1715         int i, j;
1716         MonoMethodSignature *sig, *csig;
1717         guint32 token;
1718
1719         /* 
1720          * FIXME: Instead of AOTing all the wrappers, it might be better to redesign them
1721          * so there is only one wrapper of a given type, or inlining their contents into their
1722          * callers.
1723          */
1724
1725         /* 
1726          * FIXME: This depends on the fact that different wrappers have different 
1727          * names.
1728          */
1729
1730         for (i = 0; i < acfg->image->tables [MONO_TABLE_METHOD].rows; ++i) {
1731                 MonoMethod *method;
1732                 guint32 token = MONO_TOKEN_METHOD_DEF | (i + 1);
1733                 gboolean skip = FALSE;
1734
1735                 method = mono_get_method (acfg->image, token, NULL);
1736
1737                 if ((method->flags & METHOD_ATTRIBUTE_PINVOKE_IMPL) ||
1738                         (method->iflags & METHOD_IMPL_ATTRIBUTE_RUNTIME) ||
1739                         (method->flags & METHOD_ATTRIBUTE_ABSTRACT))
1740                         skip = TRUE;
1741
1742                 if (method->is_generic || method->klass->generic_container)
1743                         skip = TRUE;
1744
1745                 /* Skip methods which can not be handled by get_runtime_invoke () */
1746                 sig = mono_method_signature (method);
1747                 if ((sig->ret->type == MONO_TYPE_PTR) ||
1748                         (sig->ret->type == MONO_TYPE_TYPEDBYREF))
1749                         skip = TRUE;
1750
1751                 for (j = 0; j < sig->param_count; j++) {
1752                         if (sig->params [j]->type == MONO_TYPE_TYPEDBYREF)
1753                                 skip = TRUE;
1754                 }
1755
1756 #ifdef MONO_ARCH_DYN_CALL_SUPPORTED
1757                 if (!(method->klass->contextbound || method->string_ctor)) {
1758                         MonoDynCallInfo *info = mono_arch_dyn_call_prepare (sig);
1759
1760                         if (info) {
1761                                 /* Supported by the dynamic runtime-invoke wrapper */
1762                                 skip = TRUE;
1763                                 g_free (info);
1764                         }
1765                 }
1766 #endif
1767
1768                 if (!skip) {
1769                         printf ("%s\n", mono_method_full_name (method, TRUE));
1770                         add_method (acfg, mono_marshal_get_runtime_invoke (method, FALSE));
1771                 }
1772         }
1773
1774         if (strcmp (acfg->image->assembly->aname.name, "mscorlib") == 0) {
1775 #ifdef MONO_ARCH_HAVE_TLS_GET
1776                 MonoMethodDesc *desc;
1777                 MonoMethod *orig_method;
1778                 int nallocators;
1779 #endif
1780
1781                 /* Runtime invoke wrappers */
1782
1783                 /* void runtime-invoke () [.cctor] */
1784                 csig = mono_metadata_signature_alloc (mono_defaults.corlib, 0);
1785                 csig->ret = &mono_defaults.void_class->byval_arg;
1786                 add_method (acfg, get_runtime_invoke_sig (csig));
1787
1788                 /* void runtime-invoke () [Finalize] */
1789                 csig = mono_metadata_signature_alloc (mono_defaults.corlib, 0);
1790                 csig->hasthis = 1;
1791                 csig->ret = &mono_defaults.void_class->byval_arg;
1792                 add_method (acfg, get_runtime_invoke_sig (csig));
1793
1794                 /* void runtime-invoke (string) [exception ctor] */
1795                 csig = mono_metadata_signature_alloc (mono_defaults.corlib, 1);
1796                 csig->hasthis = 1;
1797                 csig->ret = &mono_defaults.void_class->byval_arg;
1798                 csig->params [0] = &mono_defaults.string_class->byval_arg;
1799                 add_method (acfg, get_runtime_invoke_sig (csig));
1800
1801                 /* void runtime-invoke (string, string) [exception ctor] */
1802                 csig = mono_metadata_signature_alloc (mono_defaults.corlib, 2);
1803                 csig->hasthis = 1;
1804                 csig->ret = &mono_defaults.void_class->byval_arg;
1805                 csig->params [0] = &mono_defaults.string_class->byval_arg;
1806                 csig->params [1] = &mono_defaults.string_class->byval_arg;
1807                 add_method (acfg, get_runtime_invoke_sig (csig));
1808
1809                 /* string runtime-invoke () [Exception.ToString ()] */
1810                 csig = mono_metadata_signature_alloc (mono_defaults.corlib, 0);
1811                 csig->hasthis = 1;
1812                 csig->ret = &mono_defaults.string_class->byval_arg;
1813                 add_method (acfg, get_runtime_invoke_sig (csig));
1814
1815                 /* void runtime-invoke (string, Exception) [exception ctor] */
1816                 csig = mono_metadata_signature_alloc (mono_defaults.corlib, 2);
1817                 csig->hasthis = 1;
1818                 csig->ret = &mono_defaults.void_class->byval_arg;
1819                 csig->params [0] = &mono_defaults.string_class->byval_arg;
1820                 csig->params [1] = &mono_defaults.exception_class->byval_arg;
1821                 add_method (acfg, get_runtime_invoke_sig (csig));
1822
1823                 /* Assembly runtime-invoke (string, bool) [DoAssemblyResolve] */
1824                 csig = mono_metadata_signature_alloc (mono_defaults.corlib, 2);
1825                 csig->hasthis = 1;
1826                 csig->ret = &(mono_class_from_name (
1827                                                                                         mono_defaults.corlib, "System.Reflection", "Assembly"))->byval_arg;
1828                 csig->params [0] = &mono_defaults.string_class->byval_arg;
1829                 csig->params [1] = &mono_defaults.boolean_class->byval_arg;
1830                 add_method (acfg, get_runtime_invoke_sig (csig));
1831
1832                 /* runtime-invoke used by finalizers */
1833                 add_method (acfg, mono_marshal_get_runtime_invoke (mono_class_get_method_from_name_flags (mono_defaults.object_class, "Finalize", 0, 0), TRUE));
1834
1835 #ifdef MONO_ARCH_DYN_CALL_SUPPORTED
1836                 add_method (acfg, mono_marshal_get_runtime_invoke_dynamic ());
1837 #endif
1838
1839                 /* JIT icall wrappers */
1840                 /* FIXME: locking */
1841                 g_hash_table_foreach (mono_get_jit_icall_info (), add_jit_icall_wrapper, acfg);
1842
1843                 /* stelemref */
1844                 add_method (acfg, mono_marshal_get_stelemref ());
1845
1846 #ifdef MONO_ARCH_HAVE_TLS_GET
1847                 /* Managed Allocators */
1848                 nallocators = mono_gc_get_managed_allocator_types ();
1849                 for (i = 0; i < nallocators; ++i) {
1850                         m = mono_gc_get_managed_allocator_by_type (i);
1851                         if (m)
1852                                 add_method (acfg, m);
1853                 }
1854
1855                 /* Monitor Enter/Exit */
1856                 desc = mono_method_desc_new ("Monitor:Enter", FALSE);
1857                 orig_method = mono_method_desc_search_in_class (desc, mono_defaults.monitor_class);
1858                 g_assert (orig_method);
1859                 mono_method_desc_free (desc);
1860                 method = mono_monitor_get_fast_path (orig_method);
1861                 if (method)
1862                         add_method (acfg, method);
1863
1864                 desc = mono_method_desc_new ("Monitor:Exit", FALSE);
1865                 orig_method = mono_method_desc_search_in_class (desc, mono_defaults.monitor_class);
1866                 g_assert (orig_method);
1867                 mono_method_desc_free (desc);
1868                 method = mono_monitor_get_fast_path (orig_method);
1869                 if (method)
1870                         add_method (acfg, method);
1871 #endif
1872         }
1873
1874         /* 
1875          * remoting-invoke-with-check wrappers are very frequent, so avoid emitting them,
1876          * we use the original method instead at runtime.
1877          * Since full-aot doesn't support remoting, this is not a problem.
1878          */
1879 #if 0
1880         /* remoting-invoke wrappers */
1881         for (i = 0; i < acfg->image->tables [MONO_TABLE_METHOD].rows; ++i) {
1882                 MonoMethodSignature *sig;
1883                 
1884                 token = MONO_TOKEN_METHOD_DEF | (i + 1);
1885                 method = mono_get_method (acfg->image, token, NULL);
1886
1887                 sig = mono_method_signature (method);
1888
1889                 if (sig->hasthis && (method->klass->marshalbyref || method->klass == mono_defaults.object_class)) {
1890                         m = mono_marshal_get_remoting_invoke_with_check (method);
1891
1892                         add_method (acfg, m);
1893                 }
1894         }
1895 #endif
1896
1897         /* delegate-invoke wrappers */
1898         for (i = 0; i < acfg->image->tables [MONO_TABLE_TYPEDEF].rows; ++i) {
1899                 MonoClass *klass;
1900                 
1901                 token = MONO_TOKEN_TYPE_DEF | (i + 1);
1902                 klass = mono_class_get (acfg->image, token);
1903
1904                 if (klass->delegate && klass != mono_defaults.delegate_class && klass != mono_defaults.multicastdelegate_class && !klass->generic_container) {
1905                         method = mono_get_delegate_invoke (klass);
1906
1907                         m = mono_marshal_get_delegate_invoke (method, NULL);
1908
1909                         add_method (acfg, m);
1910
1911                         method = mono_class_get_method_from_name_flags (klass, "BeginInvoke", -1, 0);
1912                         add_method (acfg, mono_marshal_get_delegate_begin_invoke (method));
1913
1914                         method = mono_class_get_method_from_name_flags (klass, "EndInvoke", -1, 0);
1915                         add_method (acfg, mono_marshal_get_delegate_end_invoke (method));
1916                 }
1917         }
1918
1919         /* Synchronized wrappers */
1920         for (i = 0; i < acfg->image->tables [MONO_TABLE_METHOD].rows; ++i) {
1921                 token = MONO_TOKEN_METHOD_DEF | (i + 1);
1922                 method = mono_get_method (acfg->image, token, NULL);
1923
1924                 if (method->iflags & METHOD_IMPL_ATTRIBUTE_SYNCHRONIZED)
1925                         add_method (acfg, mono_marshal_get_synchronized_wrapper (method));
1926         }
1927
1928         /* pinvoke wrappers */
1929         for (i = 0; i < acfg->image->tables [MONO_TABLE_METHOD].rows; ++i) {
1930                 MonoMethod *method;
1931                 guint32 token = MONO_TOKEN_METHOD_DEF | (i + 1);
1932
1933                 method = mono_get_method (acfg->image, token, NULL);
1934
1935                 if ((method->flags & METHOD_ATTRIBUTE_PINVOKE_IMPL) ||
1936                         (method->iflags & METHOD_IMPL_ATTRIBUTE_INTERNAL_CALL)) {
1937                         add_method (acfg, mono_marshal_get_native_wrapper (method, TRUE, TRUE));
1938                 }
1939         }
1940
1941         /* StructureToPtr/PtrToStructure wrappers */
1942         for (i = 0; i < acfg->image->tables [MONO_TABLE_TYPEDEF].rows; ++i) {
1943                 MonoClass *klass;
1944                 
1945                 token = MONO_TOKEN_TYPE_DEF | (i + 1);
1946                 klass = mono_class_get (acfg->image, token);
1947
1948                 if (klass->valuetype && !klass->generic_container && ((klass->flags & TYPE_ATTRIBUTE_LAYOUT_MASK) != TYPE_ATTRIBUTE_AUTO_LAYOUT)) {
1949                         gboolean can_marshal = TRUE;
1950                         gpointer iter = NULL;
1951                         MonoClassField *field;
1952
1953                         /* Only allow a few field types to avoid asserts in the marshalling code */
1954                         while ((field = mono_class_get_fields (klass, &iter))) {
1955                                 switch (field->type->type) {
1956                                 case MONO_TYPE_I4:
1957                                 case MONO_TYPE_U4:
1958                                 case MONO_TYPE_I1:
1959                                 case MONO_TYPE_U1:
1960                                 case MONO_TYPE_BOOLEAN:
1961                                 case MONO_TYPE_I2:
1962                                 case MONO_TYPE_U2:
1963                                 case MONO_TYPE_CHAR:
1964                                 case MONO_TYPE_I8:
1965                                 case MONO_TYPE_U8:
1966                                 case MONO_TYPE_PTR:
1967                                 case MONO_TYPE_R4:
1968                                 case MONO_TYPE_R8:
1969                                         break;
1970                                 default:
1971                                         can_marshal = FALSE;
1972                                         break;
1973                                 }
1974                         }
1975
1976                         if (can_marshal) {
1977                                 add_method (acfg, mono_marshal_get_struct_to_ptr (klass));
1978                                 add_method (acfg, mono_marshal_get_ptr_to_struct (klass));
1979                         }
1980                 }
1981         }
1982 }
1983
1984 static gboolean
1985 has_type_vars (MonoClass *klass)
1986 {
1987         if ((klass->byval_arg.type == MONO_TYPE_VAR) || (klass->byval_arg.type == MONO_TYPE_MVAR))
1988                 return TRUE;
1989         if (klass->rank)
1990                 return has_type_vars (klass->element_class);
1991         if (klass->generic_class) {
1992                 MonoGenericContext *context = &klass->generic_class->context;
1993                 if (context->class_inst) {
1994                         int i;
1995
1996                         for (i = 0; i < context->class_inst->type_argc; ++i)
1997                                 if (has_type_vars (mono_class_from_mono_type (context->class_inst->type_argv [i])))
1998                                         return TRUE;
1999                 }
2000         }
2001         return FALSE;
2002 }
2003
2004 static gboolean
2005 method_has_type_vars (MonoMethod *method)
2006 {
2007         if (has_type_vars (method->klass))
2008                 return TRUE;
2009
2010         if (method->is_inflated) {
2011                 MonoGenericContext *context = mono_method_get_context (method);
2012                 if (context->method_inst) {
2013                         int i;
2014
2015                         for (i = 0; i < context->method_inst->type_argc; ++i)
2016                                 if (has_type_vars (mono_class_from_mono_type (context->method_inst->type_argv [i])))
2017                                         return TRUE;
2018                 }
2019         }
2020         return FALSE;
2021 }
2022
2023 /*
2024  * add_generic_class:
2025  *
2026  *   Add all methods of a generic class.
2027  */
2028 static void
2029 add_generic_class (MonoAotCompile *acfg, MonoClass *klass)
2030 {
2031         MonoMethod *method;
2032         gpointer iter;
2033
2034         mono_class_init (klass);
2035
2036         if (klass->generic_class && klass->generic_class->context.class_inst->is_open)
2037                 return;
2038
2039         if (has_type_vars (klass))
2040                 return;
2041
2042         if (!klass->generic_class && !klass->rank)
2043                 return;
2044
2045         iter = NULL;
2046         while ((method = mono_class_get_methods (klass, &iter))) {
2047                 if (mono_method_is_generic_sharable_impl (method, FALSE))
2048                         /* Already added */
2049                         continue;
2050
2051                 if (method->is_generic)
2052                         /* FIXME: */
2053                         continue;
2054
2055                 /*
2056                  * FIXME: Instances which are referenced by these methods are not added,
2057                  * for example Array.Resize<int> for List<int>.Add ().
2058                  */
2059                 add_extra_method (acfg, method);
2060         }
2061
2062         if (klass->delegate) {
2063                 method = mono_get_delegate_invoke (klass);
2064
2065                 method = mono_marshal_get_delegate_invoke (method, NULL);
2066
2067                 add_method (acfg, method);
2068         }
2069
2070         /* 
2071          * For ICollection<T>, add instances of the helper methods
2072          * in Array, since a T[] could be cast to ICollection<T>.
2073          */
2074         if (klass->image == mono_defaults.corlib && !strcmp (klass->name_space, "System.Collections.Generic") &&
2075                 (!strcmp(klass->name, "ICollection`1") || !strcmp (klass->name, "IEnumerable`1") || !strcmp (klass->name, "IList`1") || !strcmp (klass->name, "IEnumerator`1"))) {
2076                 MonoClass *tclass = mono_class_from_mono_type (klass->generic_class->context.class_inst->type_argv [0]);
2077                 MonoClass *array_class = mono_bounded_array_class_get (tclass, 1, FALSE);
2078                 gpointer iter;
2079                 char *name_prefix;
2080
2081                 if (!strcmp (klass->name, "IEnumerator`1"))
2082                         name_prefix = g_strdup_printf ("%s.%s", klass->name_space, "IEnumerable`1");
2083                 else
2084                         name_prefix = g_strdup_printf ("%s.%s", klass->name_space, klass->name);
2085
2086                 /* Add the T[]/InternalEnumerator class */
2087                 if (!strcmp (klass->name, "IEnumerable`1") || !strcmp (klass->name, "IEnumerator`1")) {
2088                         MonoClass *nclass;
2089
2090                         iter = NULL;
2091                         while ((nclass = mono_class_get_nested_types (array_class->parent, &iter))) {
2092                                 if (!strcmp (nclass->name, "InternalEnumerator`1"))
2093                                         break;
2094                         }
2095                         g_assert (nclass);
2096                         nclass = mono_class_inflate_generic_class (nclass, mono_generic_class_get_context (klass->generic_class));
2097                         add_generic_class (acfg, nclass);
2098                 }
2099
2100                 iter = NULL;
2101                 while ((method = mono_class_get_methods (array_class, &iter))) {
2102                         if (strstr (method->name, name_prefix))
2103                                 add_extra_method (acfg, method);
2104                 }
2105
2106                 g_free (name_prefix);
2107
2108                 /* 
2109                  * Add instance of Array.GetGenericValueImpl, which is called by the
2110                  * array helper methods.
2111                  * managed-to-native wrappers are not shared, so have to generate 
2112                  * these for ref types too.
2113                  */
2114                 {
2115                         MonoGenericContext ctx;
2116                         MonoType *args [16];
2117                         static MonoMethod *get_method;
2118
2119                         if (get_method == NULL) {
2120                                 MonoClass *array_klass = mono_array_class_get (mono_defaults.int_class, 1)->parent;
2121                                 get_method = mono_class_get_method_from_name (array_klass, "GetGenericValueImpl", 2);
2122                         }
2123
2124                         if (get_method) {
2125                                 memset (&ctx, 0, sizeof (ctx));
2126                                 args [0] = &tclass->byval_arg;
2127                                 ctx.method_inst = mono_metadata_get_generic_inst (1, args);
2128                                 add_extra_method (acfg, mono_marshal_get_native_wrapper (mono_class_inflate_generic_method (get_method, &ctx), TRUE, TRUE));
2129                         }
2130                 }
2131
2132         }
2133 }
2134
2135 static void
2136 add_array_wrappers (MonoAotCompile *acfg, MonoClass *klass)
2137 {
2138         int i;
2139
2140         mono_class_setup_methods (klass);
2141         for (i = 0; i < klass->method.count; ++i) {
2142                 if (klass->methods [i]->wrapper_type == MONO_WRAPPER_MANAGED_TO_MANAGED)
2143                         add_extra_method (acfg, klass->methods [i]);
2144         }
2145 }
2146
2147 /*
2148  * add_generic_instances:
2149  *
2150  *   Add instances referenced by the METHODSPEC/TYPESPEC table.
2151  */
2152 static void
2153 add_generic_instances (MonoAotCompile *acfg)
2154 {
2155         int i;
2156         guint32 token;
2157         MonoMethod *method;
2158         MonoMethodHeader *header;
2159         MonoMethodSignature *sig;
2160         MonoGenericContext *context;
2161
2162         for (i = 0; i < acfg->image->tables [MONO_TABLE_METHODSPEC].rows; ++i) {
2163                 token = MONO_TOKEN_METHOD_SPEC | (i + 1);
2164                 method = mono_get_method (acfg->image, token, NULL);
2165
2166                 context = mono_method_get_context (method);
2167                 if (context && ((context->class_inst && context->class_inst->is_open) ||
2168                                                 (context->method_inst && context->method_inst->is_open)))
2169                         continue;
2170
2171                 if (method->klass->image != acfg->image)
2172                         continue;
2173
2174                 if (mono_method_is_generic_sharable_impl (method, FALSE))
2175                         /* Already added */
2176                         continue;
2177
2178                 add_extra_method (acfg, method);
2179         }
2180
2181         for (i = 0; i < acfg->image->tables [MONO_TABLE_TYPESPEC].rows; ++i) {
2182                 MonoClass *klass;
2183
2184                 token = MONO_TOKEN_TYPE_SPEC | (i + 1);
2185
2186                 klass = mono_class_get (acfg->image, token);
2187                 if (!klass || klass->rank)
2188                         continue;
2189
2190                 add_generic_class (acfg, klass);
2191         }
2192
2193         /* Add types of args/locals */
2194         for (i = 0; i < acfg->methods->len; ++i) {
2195                 int j;
2196
2197                 method = g_ptr_array_index (acfg->methods, i);
2198
2199                 sig = mono_method_signature (method);
2200
2201                 if (sig) {
2202                         for (j = 0; j < sig->param_count; ++j)
2203                                 if (sig->params [j]->type == MONO_TYPE_GENERICINST)
2204                                         add_generic_class (acfg, mono_class_from_mono_type (sig->params [j]));
2205                 }
2206
2207                 header = mono_method_get_header (method);
2208
2209                 if (header) {
2210                         for (j = 0; j < header->num_locals; ++j)
2211                                 if (header->locals [j]->type == MONO_TYPE_GENERICINST)
2212                                         add_generic_class (acfg, mono_class_from_mono_type (header->locals [j]));
2213                 }
2214         }
2215
2216         if (acfg->image == mono_defaults.corlib) {
2217                 /* Add GenericComparer<T> instances for primitive types for Enum.ToString () */
2218                 MonoClass *klass = mono_class_from_name (acfg->image, "System.Collections.Generic", "GenericComparer`1");
2219
2220                 if (klass) {
2221                         MonoGenericContext ctx;
2222                         MonoType *args [16];
2223
2224                         memset (&ctx, 0, sizeof (ctx));
2225
2226                         args [0] = &mono_defaults.byte_class->byval_arg;
2227                         ctx.class_inst = mono_metadata_get_generic_inst (1, args);
2228                         add_generic_class (acfg, mono_class_inflate_generic_class (klass, &ctx));
2229
2230                         args [0] = &mono_defaults.sbyte_class->byval_arg;
2231                         ctx.class_inst = mono_metadata_get_generic_inst (1, args);
2232                         add_generic_class (acfg, mono_class_inflate_generic_class (klass, &ctx));
2233
2234                         args [0] = &mono_defaults.int16_class->byval_arg;
2235                         ctx.class_inst = mono_metadata_get_generic_inst (1, args);
2236                         add_generic_class (acfg, mono_class_inflate_generic_class (klass, &ctx));
2237
2238                         args [0] = &mono_defaults.uint16_class->byval_arg;
2239                         ctx.class_inst = mono_metadata_get_generic_inst (1, args);
2240                         add_generic_class (acfg, mono_class_inflate_generic_class (klass, &ctx));
2241
2242                         args [0] = &mono_defaults.int32_class->byval_arg;
2243                         ctx.class_inst = mono_metadata_get_generic_inst (1, args);
2244                         add_generic_class (acfg, mono_class_inflate_generic_class (klass, &ctx));
2245
2246                         args [0] = &mono_defaults.uint32_class->byval_arg;
2247                         ctx.class_inst = mono_metadata_get_generic_inst (1, args);
2248                         add_generic_class (acfg, mono_class_inflate_generic_class (klass, &ctx));
2249
2250                         args [0] = &mono_defaults.int64_class->byval_arg;
2251                         ctx.class_inst = mono_metadata_get_generic_inst (1, args);
2252                         add_generic_class (acfg, mono_class_inflate_generic_class (klass, &ctx));
2253
2254                         args [0] = &mono_defaults.uint64_class->byval_arg;
2255                         ctx.class_inst = mono_metadata_get_generic_inst (1, args);
2256                         add_generic_class (acfg, mono_class_inflate_generic_class (klass, &ctx));
2257                 }
2258
2259                 /* Add GenericEqualityComparer<T> instances for primitive types */
2260                 klass = mono_class_from_name (acfg->image, "System.Collections.Generic", "GenericEqualityComparer`1");
2261
2262                 if (klass) {
2263                         MonoGenericContext ctx;
2264                         MonoType *args [16];
2265
2266                         memset (&ctx, 0, sizeof (ctx));
2267
2268                         args [0] = &mono_defaults.byte_class->byval_arg;
2269                         ctx.class_inst = mono_metadata_get_generic_inst (1, args);
2270                         add_generic_class (acfg, mono_class_inflate_generic_class (klass, &ctx));
2271
2272                         args [0] = &mono_defaults.sbyte_class->byval_arg;
2273                         ctx.class_inst = mono_metadata_get_generic_inst (1, args);
2274                         add_generic_class (acfg, mono_class_inflate_generic_class (klass, &ctx));
2275
2276                         args [0] = &mono_defaults.int16_class->byval_arg;
2277                         ctx.class_inst = mono_metadata_get_generic_inst (1, args);
2278                         add_generic_class (acfg, mono_class_inflate_generic_class (klass, &ctx));
2279
2280                         args [0] = &mono_defaults.uint16_class->byval_arg;
2281                         ctx.class_inst = mono_metadata_get_generic_inst (1, args);
2282                         add_generic_class (acfg, mono_class_inflate_generic_class (klass, &ctx));
2283
2284                         args [0] = &mono_defaults.int32_class->byval_arg;
2285                         ctx.class_inst = mono_metadata_get_generic_inst (1, args);
2286                         add_generic_class (acfg, mono_class_inflate_generic_class (klass, &ctx));
2287
2288                         args [0] = &mono_defaults.uint32_class->byval_arg;
2289                         ctx.class_inst = mono_metadata_get_generic_inst (1, args);
2290                         add_generic_class (acfg, mono_class_inflate_generic_class (klass, &ctx));
2291
2292                         args [0] = &mono_defaults.int64_class->byval_arg;
2293                         ctx.class_inst = mono_metadata_get_generic_inst (1, args);
2294                         add_generic_class (acfg, mono_class_inflate_generic_class (klass, &ctx));
2295
2296                         args [0] = &mono_defaults.uint64_class->byval_arg;
2297                         ctx.class_inst = mono_metadata_get_generic_inst (1, args);
2298                         add_generic_class (acfg, mono_class_inflate_generic_class (klass, &ctx));
2299
2300                         args [0] = &mono_defaults.char_class->byval_arg;
2301                         ctx.class_inst = mono_metadata_get_generic_inst (1, args);
2302                         add_generic_class (acfg, mono_class_inflate_generic_class (klass, &ctx));
2303
2304                         args [0] = &mono_defaults.boolean_class->byval_arg;
2305                         ctx.class_inst = mono_metadata_get_generic_inst (1, args);
2306                         add_generic_class (acfg, mono_class_inflate_generic_class (klass, &ctx));
2307
2308                         args [0] = &mono_defaults.single_class->byval_arg;
2309                         ctx.class_inst = mono_metadata_get_generic_inst (1, args);
2310                         add_generic_class (acfg, mono_class_inflate_generic_class (klass, &ctx));
2311
2312                         args [0] = &mono_defaults.double_class->byval_arg;
2313                         ctx.class_inst = mono_metadata_get_generic_inst (1, args);
2314                         add_generic_class (acfg, mono_class_inflate_generic_class (klass, &ctx));
2315
2316                 }
2317
2318                 /* Emit the array wrapper methods for arrays of primitive types */
2319                 add_array_wrappers (acfg, mono_array_class_get (mono_defaults.byte_class, 1));
2320                 add_array_wrappers (acfg, mono_array_class_get (mono_defaults.sbyte_class, 1));
2321                 add_array_wrappers (acfg, mono_array_class_get (mono_defaults.int16_class, 1));
2322                 add_array_wrappers (acfg, mono_array_class_get (mono_defaults.uint16_class, 1));
2323                 add_array_wrappers (acfg, mono_array_class_get (mono_defaults.int32_class, 1));
2324                 add_array_wrappers (acfg, mono_array_class_get (mono_defaults.uint32_class, 1));
2325                 add_array_wrappers (acfg, mono_array_class_get (mono_defaults.int64_class, 1));
2326                 add_array_wrappers (acfg, mono_array_class_get (mono_defaults.single_class, 1));
2327                 add_array_wrappers (acfg, mono_array_class_get (mono_defaults.double_class, 1));
2328                 /* These are not handled by generic sharing */
2329                 add_array_wrappers (acfg, mono_array_class_get (mono_defaults.object_class, 1));
2330                 add_array_wrappers (acfg, mono_array_class_get (mono_defaults.string_class, 1));
2331
2332                 /* Add instances of Array.GetGenericValueImpl */
2333                 {
2334                         MonoGenericContext ctx;
2335                         MonoType *args [16];
2336                         MonoMethod *method;
2337
2338                         memset (&ctx, 0, sizeof (ctx));
2339
2340                         /* 
2341                          * managed-to-native wrappers are not shared, so have to generate 
2342                          * these for ref types too.
2343                          */
2344                         klass = mono_array_class_get (mono_defaults.int_class, 1)->parent;
2345                         method = mono_class_get_method_from_name (klass, "GetGenericValueImpl", 2);
2346
2347                         if (method) {
2348                                 /* String */
2349                                 args [0] = &mono_defaults.string_class->byval_arg;
2350                                 ctx.method_inst = mono_metadata_get_generic_inst (1, args);
2351                                 add_extra_method (acfg, mono_marshal_get_native_wrapper (mono_class_inflate_generic_method (method, &ctx), TRUE, TRUE));
2352                         }
2353                 }
2354         }
2355 }
2356
2357 /*
2358  * is_direct_callable:
2359  *
2360  *   Return whenever the method identified by JI is directly callable without 
2361  * going through the PLT.
2362  */
2363 static gboolean
2364 is_direct_callable (MonoAotCompile *acfg, MonoMethod *method, MonoJumpInfo *patch_info)
2365 {
2366         if ((patch_info->type == MONO_PATCH_INFO_METHOD) && (patch_info->data.method->klass->image == acfg->image)) {
2367                 MonoCompile *callee_cfg = g_hash_table_lookup (acfg->method_to_cfg, patch_info->data.method);
2368                 if (callee_cfg) {
2369                         gboolean direct_callable = TRUE;
2370
2371                         if (direct_callable && !(!callee_cfg->has_got_slots && (callee_cfg->method->klass->flags & TYPE_ATTRIBUTE_BEFORE_FIELD_INIT)))
2372                                 direct_callable = FALSE;
2373                         if ((callee_cfg->method->iflags & METHOD_IMPL_ATTRIBUTE_SYNCHRONIZED) && (!method || method->wrapper_type != MONO_WRAPPER_SYNCHRONIZED))
2374                                 // FIXME: Maybe call the wrapper directly ?
2375                                 direct_callable = FALSE;
2376
2377                         if (direct_callable)
2378                                 return TRUE;
2379                 }
2380         }
2381
2382         return FALSE;
2383 }
2384
2385 /*
2386  * emit_and_reloc_code:
2387  *
2388  *   Emit the native code in CODE, handling relocations along the way. If GOT_ONLY
2389  * is true, calls are made through the GOT too. This is used for emitting trampolines
2390  * in full-aot mode, since calls made from trampolines couldn't go through the PLT,
2391  * since trampolines are needed to make PTL work.
2392  */
2393 static void
2394 emit_and_reloc_code (MonoAotCompile *acfg, MonoMethod *method, guint8 *code, guint32 code_len, MonoJumpInfo *relocs, gboolean got_only)
2395 {
2396         int i, pindex, start_index, method_index;
2397         GPtrArray *patches;
2398         MonoJumpInfo *patch_info;
2399         MonoMethodHeader *header;
2400         gboolean skip, direct_call;
2401         guint32 got_slot;
2402         char direct_call_target [128];
2403
2404         if (method) {
2405                 header = mono_method_get_header (method);
2406
2407                 method_index = get_method_index (acfg, method);
2408         }
2409
2410         /* Collect and sort relocations */
2411         patches = g_ptr_array_new ();
2412         for (patch_info = relocs; patch_info; patch_info = patch_info->next)
2413                 g_ptr_array_add (patches, patch_info);
2414         g_ptr_array_sort (patches, compare_patches);
2415
2416         start_index = 0;
2417         for (i = 0; i < code_len; i++) {
2418                 patch_info = NULL;
2419                 for (pindex = start_index; pindex < patches->len; ++pindex) {
2420                         patch_info = g_ptr_array_index (patches, pindex);
2421                         if (patch_info->ip.i >= i)
2422                                 break;
2423                 }
2424
2425 #ifdef MONO_ARCH_AOT_SUPPORTED
2426                 skip = FALSE;
2427                 if (patch_info && (patch_info->ip.i == i) && (pindex < patches->len)) {
2428                         start_index = pindex;
2429
2430                         switch (patch_info->type) {
2431                         case MONO_PATCH_INFO_NONE:
2432                                 break;
2433                         case MONO_PATCH_INFO_GOT_OFFSET: {
2434                                 int code_size;
2435  
2436                                 arch_emit_got_offset (acfg, code + i, &code_size);
2437                                 i += code_size - 1;
2438                                 skip = TRUE;
2439                                 patch_info->type = MONO_PATCH_INFO_NONE;
2440                                 break;
2441                         }
2442                         default: {
2443                                 /*
2444                                  * If this patch is a call, try emitting a direct call instead of
2445                                  * through a PLT entry. This is possible if the called method is in
2446                                  * the same assembly and requires no initialization.
2447                                  */
2448                                 direct_call = FALSE;
2449                                 if ((patch_info->type == MONO_PATCH_INFO_METHOD) && (patch_info->data.method->klass->image == acfg->image)) {
2450                                         if (!got_only && is_direct_callable (acfg, method, patch_info)) {
2451                                                 MonoCompile *callee_cfg = g_hash_table_lookup (acfg->method_to_cfg, patch_info->data.method);
2452                                                 //printf ("DIRECT: %s %s\n", method ? mono_method_full_name (method, TRUE) : "", mono_method_full_name (callee_cfg->method, TRUE));
2453                                                 direct_call = TRUE;
2454                                                 sprintf (direct_call_target, "%sm_%x", acfg->temp_prefix, get_method_index (acfg, callee_cfg->orig_method));
2455                                                 patch_info->type = MONO_PATCH_INFO_NONE;
2456                                                 acfg->stats.direct_calls ++;
2457                                         }
2458
2459                                         acfg->stats.all_calls ++;
2460                                 }
2461
2462                                 if (!got_only && !direct_call) {
2463                                         int plt_offset = get_plt_offset (acfg, patch_info);
2464                                         if (plt_offset != -1) {
2465                                                 /* This patch has a PLT entry, so we must emit a call to the PLT entry */
2466                                                 direct_call = TRUE;
2467                                                 sprintf (direct_call_target, "%sp_%d", acfg->temp_prefix, plt_offset);
2468                 
2469                                                 /* Nullify the patch */
2470                                                 patch_info->type = MONO_PATCH_INFO_NONE;
2471                                         }
2472                                 }
2473
2474                                 if (direct_call) {
2475                                         int call_size;
2476
2477                                         arch_emit_direct_call (acfg, direct_call_target, &call_size);
2478                                         i += call_size - 1;
2479                                 } else {
2480                                         int code_size;
2481
2482                                         got_slot = get_got_offset (acfg, patch_info);
2483
2484                                         arch_emit_got_access (acfg, code + i, got_slot, &code_size);
2485                                         i += code_size - 1;
2486                                 }
2487                                 skip = TRUE;
2488                         }
2489                         }
2490                 }
2491 #endif /* MONO_ARCH_AOT_SUPPORTED */
2492
2493                 if (!skip) {
2494                         /* Find next patch */
2495                         patch_info = NULL;
2496                         for (pindex = start_index; pindex < patches->len; ++pindex) {
2497                                 patch_info = g_ptr_array_index (patches, pindex);
2498                                 if (patch_info->ip.i >= i)
2499                                         break;
2500                         }
2501
2502                         /* Try to emit multiple bytes at once */
2503                         if (pindex < patches->len && patch_info->ip.i > i) {
2504                                 emit_bytes (acfg, code + i, patch_info->ip.i - i);
2505                                 i = patch_info->ip.i - 1;
2506                         } else {
2507                                 emit_bytes (acfg, code + i, 1);
2508                         }
2509                 }
2510         }
2511 }
2512
2513 /*
2514  * sanitize_symbol:
2515  *
2516  *   Modify SYMBOL so it only includes characters permissible in symbols.
2517  */
2518 static void
2519 sanitize_symbol (char *symbol)
2520 {
2521         int i, len = strlen (symbol);
2522
2523         for (i = 0; i < len; ++i)
2524                 if (!isalnum (symbol [i]) && (symbol [i] != '_'))
2525                         symbol [i] = '_';
2526 }
2527
2528 static char*
2529 get_debug_sym (MonoMethod *method, const char *prefix, GHashTable *cache)
2530 {
2531         char *name1, *name2, *cached;
2532         int i, j, len, count;
2533                 
2534         name1 = mono_method_full_name (method, TRUE);
2535         len = strlen (name1);
2536         name2 = malloc (strlen (prefix) + len + 16);
2537         memcpy (name2, prefix, strlen (prefix));
2538         j = strlen (prefix);
2539         for (i = 0; i < len; ++i) {
2540                 if (isalnum (name1 [i])) {
2541                         name2 [j ++] = name1 [i];
2542                 } else if (name1 [i] == ' ' && name1 [i + 1] == '(' && name1 [i + 2] == ')') {
2543                         i += 2;
2544                 } else if (name1 [i] == ',' && name1 [i + 1] == ' ') {
2545                         name2 [j ++] = '_';
2546                         i++;
2547                 } else if (name1 [i] == '(' || name1 [i] == ')' || name1 [i] == '>') {
2548                 } else
2549                         name2 [j ++] = '_';
2550         }
2551         name2 [j] = '\0';
2552
2553         g_free (name1);
2554
2555         count = 0;
2556         while (g_hash_table_lookup (cache, name2)) {
2557                 sprintf (name2 + j, "_%d", count);
2558                 count ++;
2559         }
2560
2561         cached = g_strdup (name2);
2562         g_hash_table_insert (cache, cached, cached);
2563
2564         return name2;
2565 }
2566
2567 static void
2568 emit_method_code (MonoAotCompile *acfg, MonoCompile *cfg)
2569 {
2570         MonoMethod *method;
2571         int method_index;
2572         guint8 *code;
2573         char *debug_sym = NULL;
2574         char symbol [128];
2575         int func_alignment = AOT_FUNC_ALIGNMENT;
2576         MonoMethodHeader *header;
2577
2578         method = cfg->orig_method;
2579         code = cfg->native_code;
2580         header = mono_method_get_header (method);
2581
2582         method_index = get_method_index (acfg, method);
2583
2584         /* Emit unbox trampoline */
2585         if (acfg->aot_opts.full_aot && cfg->orig_method->klass->valuetype && (method->flags & METHOD_ATTRIBUTE_VIRTUAL)) {
2586                 char call_target [256];
2587
2588                 if (!method->wrapper_type && !method->is_inflated) {
2589                         g_assert (method->token);
2590                         sprintf (symbol, "ut_%d", mono_metadata_token_index (method->token) - 1);
2591                 } else {
2592                         sprintf (symbol, "ut_e_%d", get_method_index (acfg, method));
2593                 }
2594
2595                 emit_section_change (acfg, ".text", 0);
2596                 emit_global (acfg, symbol, TRUE);
2597                 emit_label (acfg, symbol);
2598
2599                 sprintf (call_target, "%sm_%x", acfg->temp_prefix, method_index);
2600
2601                 arch_emit_unbox_trampoline (acfg, cfg->orig_method, cfg->generic_sharing_context, call_target);
2602         }
2603
2604         /* Make the labels local */
2605         sprintf (symbol, "%sm_%x", acfg->temp_prefix, method_index);
2606
2607         emit_alignment (acfg, func_alignment);
2608         emit_label (acfg, symbol);
2609
2610         if (acfg->aot_opts.write_symbols) {
2611                 /* 
2612                  * Write a C style symbol for every method, this has two uses:
2613                  * - it works on platforms where the dwarf debugging info is not
2614                  *   yet supported.
2615                  * - it allows the setting of breakpoints of aot-ed methods.
2616                  */
2617                 debug_sym = get_debug_sym (method, "", acfg->method_label_hash);
2618
2619                 sprintf (symbol, "%sme_%x", acfg->temp_prefix, method_index);
2620                 emit_local_symbol (acfg, debug_sym, symbol, TRUE);
2621                 emit_label (acfg, debug_sym);
2622         }
2623
2624         if (cfg->verbose_level > 0)
2625                 g_print ("Method %s emitted as %s\n", mono_method_full_name (method, TRUE), symbol);
2626
2627         acfg->stats.code_size += cfg->code_len;
2628
2629         acfg->cfgs [method_index]->got_offset = acfg->got_offset;
2630
2631         emit_and_reloc_code (acfg, method, code, cfg->code_len, cfg->patch_info, FALSE);
2632
2633         emit_line (acfg);
2634
2635         if (acfg->aot_opts.write_symbols) {
2636                 emit_symbol_size (acfg, debug_sym, ".");
2637                 g_free (debug_sym);
2638         }
2639
2640         sprintf (symbol, "%sme_%x", acfg->temp_prefix, method_index);
2641         emit_label (acfg, symbol);
2642 }
2643
2644 /**
2645  * encode_patch:
2646  *
2647  *  Encode PATCH_INFO into its disk representation.
2648  */
2649 static void
2650 encode_patch (MonoAotCompile *acfg, MonoJumpInfo *patch_info, guint8 *buf, guint8 **endbuf)
2651 {
2652         guint8 *p = buf;
2653
2654         switch (patch_info->type) {
2655         case MONO_PATCH_INFO_NONE:
2656                 break;
2657         case MONO_PATCH_INFO_IMAGE:
2658                 encode_value (get_image_index (acfg, patch_info->data.image), p, &p);
2659                 break;
2660         case MONO_PATCH_INFO_MSCORLIB_GOT_ADDR:
2661                 break;
2662         case MONO_PATCH_INFO_METHOD_REL:
2663                 encode_value ((gint)patch_info->data.offset, p, &p);
2664                 break;
2665         case MONO_PATCH_INFO_SWITCH: {
2666                 gpointer *table = (gpointer *)patch_info->data.table->table;
2667                 int k;
2668
2669                 encode_value (patch_info->data.table->table_size, p, &p);
2670                 for (k = 0; k < patch_info->data.table->table_size; k++)
2671                         encode_value ((int)(gssize)table [k], p, &p);
2672                 break;
2673         }
2674         case MONO_PATCH_INFO_METHODCONST:
2675         case MONO_PATCH_INFO_METHOD:
2676         case MONO_PATCH_INFO_METHOD_JUMP:
2677         case MONO_PATCH_INFO_ICALL_ADDR:
2678         case MONO_PATCH_INFO_METHOD_RGCTX:
2679                 encode_method_ref (acfg, patch_info->data.method, p, &p);
2680                 break;
2681         case MONO_PATCH_INFO_INTERNAL_METHOD:
2682         case MONO_PATCH_INFO_JIT_ICALL_ADDR: {
2683                 guint32 len = strlen (patch_info->data.name);
2684
2685                 encode_value (len, p, &p);
2686
2687                 memcpy (p, patch_info->data.name, len);
2688                 p += len;
2689                 *p++ = '\0';
2690                 break;
2691         }
2692         case MONO_PATCH_INFO_LDSTR: {
2693                 guint32 image_index = get_image_index (acfg, patch_info->data.token->image);
2694                 guint32 token = patch_info->data.token->token;
2695                 g_assert (mono_metadata_token_code (token) == MONO_TOKEN_STRING);
2696                 encode_value (image_index, p, &p);
2697                 encode_value (patch_info->data.token->token - MONO_TOKEN_STRING, p, &p);
2698                 break;
2699         }
2700         case MONO_PATCH_INFO_RVA:
2701         case MONO_PATCH_INFO_DECLSEC:
2702         case MONO_PATCH_INFO_LDTOKEN:
2703         case MONO_PATCH_INFO_TYPE_FROM_HANDLE:
2704                 encode_value (get_image_index (acfg, patch_info->data.token->image), p, &p);
2705                 encode_value (patch_info->data.token->token, p, &p);
2706                 encode_value (patch_info->data.token->has_context, p, &p);
2707                 if (patch_info->data.token->has_context)
2708                         encode_generic_context (acfg, &patch_info->data.token->context, p, &p);
2709                 break;
2710         case MONO_PATCH_INFO_EXC_NAME: {
2711                 MonoClass *ex_class;
2712
2713                 ex_class =
2714                         mono_class_from_name (mono_defaults.exception_class->image,
2715                                                                   "System", patch_info->data.target);
2716                 g_assert (ex_class);
2717                 encode_klass_ref (acfg, ex_class, p, &p);
2718                 break;
2719         }
2720         case MONO_PATCH_INFO_R4:
2721                 encode_value (*((guint32 *)patch_info->data.target), p, &p);
2722                 break;
2723         case MONO_PATCH_INFO_R8:
2724                 encode_value (*((guint32 *)patch_info->data.target), p, &p);
2725                 encode_value (*(((guint32 *)patch_info->data.target) + 1), p, &p);
2726                 break;
2727         case MONO_PATCH_INFO_VTABLE:
2728         case MONO_PATCH_INFO_CLASS:
2729         case MONO_PATCH_INFO_IID:
2730         case MONO_PATCH_INFO_ADJUSTED_IID:
2731                 encode_klass_ref (acfg, patch_info->data.klass, p, &p);
2732                 break;
2733         case MONO_PATCH_INFO_CLASS_INIT:
2734         case MONO_PATCH_INFO_DELEGATE_TRAMPOLINE:
2735                 encode_klass_ref (acfg, patch_info->data.klass, p, &p);
2736                 break;
2737         case MONO_PATCH_INFO_FIELD:
2738         case MONO_PATCH_INFO_SFLDA:
2739                 encode_field_info (acfg, patch_info->data.field, p, &p);
2740                 break;
2741         case MONO_PATCH_INFO_INTERRUPTION_REQUEST_FLAG:
2742                 break;
2743         case MONO_PATCH_INFO_RGCTX_FETCH: {
2744                 MonoJumpInfoRgctxEntry *entry = patch_info->data.rgctx_entry;
2745
2746                 encode_method_ref (acfg, entry->method, p, &p);
2747                 encode_value (entry->in_mrgctx, p, &p);
2748                 encode_value (entry->info_type, p, &p);
2749                 encode_value (entry->data->type, p, &p);
2750                 encode_patch (acfg, entry->data, p, &p);
2751                 break;
2752         }
2753         case MONO_PATCH_INFO_GENERIC_CLASS_INIT:
2754         case MONO_PATCH_INFO_MONITOR_ENTER:
2755         case MONO_PATCH_INFO_MONITOR_EXIT:
2756                 break;
2757         default:
2758                 g_warning ("unable to handle jump info %d", patch_info->type);
2759                 g_assert_not_reached ();
2760         }
2761
2762         *endbuf = p;
2763 }
2764
2765 static void
2766 encode_patch_list (MonoAotCompile *acfg, GPtrArray *patches, int n_patches, int first_got_offset, guint8 *buf, guint8 **endbuf)
2767 {
2768         guint8 *p = buf;
2769         guint32 pindex, offset;
2770         MonoJumpInfo *patch_info;
2771
2772         encode_value (n_patches, p, &p);
2773
2774         for (pindex = 0; pindex < patches->len; ++pindex) {
2775                 patch_info = g_ptr_array_index (patches, pindex);
2776
2777                 if (patch_info->type == MONO_PATCH_INFO_NONE)
2778                         /* Nothing to do */
2779                         continue;
2780
2781                 offset = get_got_offset (acfg, patch_info);
2782                 encode_value (offset, p, &p);
2783         }
2784
2785         *endbuf = p;
2786 }
2787
2788 static void
2789 emit_method_info (MonoAotCompile *acfg, MonoCompile *cfg)
2790 {
2791         MonoMethod *method;
2792         GList *l;
2793         int pindex, buf_size, n_patches;
2794         guint8 *code;
2795         char symbol [128];
2796         GPtrArray *patches;
2797         MonoJumpInfo *patch_info;
2798         MonoMethodHeader *header;
2799         guint32 method_index;
2800         guint8 *p, *buf;
2801         guint32 first_got_offset;
2802
2803         method = cfg->orig_method;
2804         code = cfg->native_code;
2805         header = mono_method_get_header (method);
2806
2807         method_index = get_method_index (acfg, method);
2808
2809         /* Make the labels local */
2810         sprintf (symbol, "%sm_%x_p", acfg->temp_prefix, method_index);
2811
2812         /* Sort relocations */
2813         patches = g_ptr_array_new ();
2814         for (patch_info = cfg->patch_info; patch_info; patch_info = patch_info->next)
2815                 g_ptr_array_add (patches, patch_info);
2816         g_ptr_array_sort (patches, compare_patches);
2817
2818         first_got_offset = acfg->cfgs [method_index]->got_offset;
2819
2820         /**********************/
2821         /* Encode method info */
2822         /**********************/
2823
2824         buf_size = (patches->len < 1000) ? 40960 : 40960 + (patches->len * 64);
2825         p = buf = g_malloc (buf_size);
2826
2827         if (mono_class_get_cctor (method->klass))
2828                 encode_klass_ref (acfg, method->klass, p, &p);
2829         else
2830                 /* Not needed when loading the method */
2831                 encode_value (0, p, &p);
2832
2833         /* String table */
2834         if (cfg->opt & MONO_OPT_SHARED) {
2835                 encode_value (g_list_length (cfg->ldstr_list), p, &p);
2836                 for (l = cfg->ldstr_list; l; l = l->next) {
2837                         encode_value ((long)l->data, p, &p);
2838                 }
2839         }
2840         else
2841                 /* Used only in shared mode */
2842                 g_assert (!cfg->ldstr_list);
2843
2844         n_patches = 0;
2845         for (pindex = 0; pindex < patches->len; ++pindex) {
2846                 patch_info = g_ptr_array_index (patches, pindex);
2847                 
2848                 if ((patch_info->type == MONO_PATCH_INFO_GOT_OFFSET) ||
2849                         (patch_info->type == MONO_PATCH_INFO_NONE)) {
2850                         patch_info->type = MONO_PATCH_INFO_NONE;
2851                         /* Nothing to do */
2852                         continue;
2853                 }
2854
2855                 if ((patch_info->type == MONO_PATCH_INFO_IMAGE) && (patch_info->data.image == acfg->image)) {
2856                         /* Stored in a GOT slot initialized at module load time */
2857                         patch_info->type = MONO_PATCH_INFO_NONE;
2858                         continue;
2859                 }
2860
2861                 if (is_plt_patch (patch_info)) {
2862                         /* Calls are made through the PLT */
2863                         patch_info->type = MONO_PATCH_INFO_NONE;
2864                         continue;
2865                 }
2866
2867                 n_patches ++;
2868         }
2869
2870         if (n_patches)
2871                 g_assert (cfg->has_got_slots);
2872
2873         encode_patch_list (acfg, patches, n_patches, first_got_offset, p, &p);
2874
2875         acfg->stats.info_size += p - buf;
2876
2877         /* Emit method info */
2878
2879         emit_label (acfg, symbol);
2880
2881         g_assert (p - buf < buf_size);
2882         emit_bytes (acfg, buf, p - buf);
2883         g_free (buf);
2884 }
2885
2886 static guint32
2887 get_unwind_info_offset (MonoAotCompile *acfg, guint8 *encoded, guint32 encoded_len)
2888 {
2889         guint32 cache_index;
2890         guint32 offset;
2891
2892         /* Reuse the unwind module to canonize and store unwind info entries */
2893         cache_index = mono_cache_unwind_info (encoded, encoded_len);
2894
2895         /* Use +/- 1 to distinguish 0s from missing entries */
2896         offset = GPOINTER_TO_UINT (g_hash_table_lookup (acfg->unwind_info_offsets, GUINT_TO_POINTER (cache_index + 1)));
2897         if (offset)
2898                 return offset - 1;
2899         else {
2900                 guint8 buf [16];
2901                 guint8 *p;
2902
2903                 /* 
2904                  * It would be easier to use assembler symbols, but the caller needs an
2905                  * offset now.
2906                  */
2907                 offset = acfg->unwind_info_offset;
2908                 g_hash_table_insert (acfg->unwind_info_offsets, GUINT_TO_POINTER (cache_index + 1), GUINT_TO_POINTER (offset + 1));
2909                 g_ptr_array_add (acfg->unwind_ops, GUINT_TO_POINTER (cache_index));
2910
2911                 p = buf;
2912                 encode_value (encoded_len, p, &p);
2913
2914                 acfg->unwind_info_offset += encoded_len + (p - buf);
2915                 return offset;
2916         }
2917 }
2918
2919 static void
2920 emit_exception_debug_info (MonoAotCompile *acfg, MonoCompile *cfg)
2921 {
2922         MonoMethod *method;
2923         int k, buf_size, method_index;
2924         guint32 debug_info_size;
2925         guint8 *code;
2926         char symbol [128];
2927         MonoMethodHeader *header;
2928         guint8 *p, *buf, *debug_info;
2929         MonoJitInfo *jinfo = cfg->jit_info;
2930         guint32 flags;
2931         gboolean use_unwind_ops = FALSE;
2932
2933         method = cfg->orig_method;
2934         code = cfg->native_code;
2935         header = mono_method_get_header (method);
2936
2937         method_index = get_method_index (acfg, method);
2938
2939         /* Make the labels local */
2940         sprintf (symbol, "%se_%x_p", acfg->temp_prefix, method_index);
2941
2942         if (!acfg->aot_opts.nodebug) {
2943                 mono_debug_serialize_debug_info (cfg, &debug_info, &debug_info_size);
2944         } else {
2945                 debug_info = NULL;
2946                 debug_info_size = 0;
2947         }
2948
2949         buf_size = header->num_clauses * 256 + debug_info_size + 1024;
2950         p = buf = g_malloc (buf_size);
2951
2952 #ifdef MONO_ARCH_HAVE_XP_UNWIND
2953         use_unwind_ops = cfg->unwind_ops != NULL;
2954 #endif
2955
2956         flags = (jinfo->has_generic_jit_info ? 1 : 0) | (use_unwind_ops ? 2 : 0) | (header->num_clauses ? 4 : 0);
2957
2958         encode_value (jinfo->code_size, p, &p);
2959         encode_value (flags, p, &p);
2960
2961         if (use_unwind_ops) {
2962                 guint32 encoded_len;
2963                 guint8 *encoded;
2964
2965                 /* 
2966                  * This is a duplicate of the data in the .debug_frame section, but that
2967                  * section cannot be accessed using the dl interface.
2968                  */
2969                 encoded = mono_unwind_ops_encode (cfg->unwind_ops, &encoded_len);
2970                 encode_value (get_unwind_info_offset (acfg, encoded, encoded_len), p, &p);
2971                 g_free (encoded);
2972         } else {
2973                 encode_value (jinfo->used_regs, p, &p);
2974         }
2975
2976         /* Exception table */
2977         if (jinfo->num_clauses)
2978                 encode_value (jinfo->num_clauses, p, &p);
2979
2980         for (k = 0; k < jinfo->num_clauses; ++k) {
2981                 MonoJitExceptionInfo *ei = &jinfo->clauses [k];
2982
2983                 encode_value (ei->flags, p, &p);
2984                 encode_value (ei->exvar_offset, p, &p);
2985
2986                 if (ei->flags == MONO_EXCEPTION_CLAUSE_FILTER)
2987                         encode_value ((gint)((guint8*)ei->data.filter - code), p, &p);
2988                 else {
2989                         if (ei->data.catch_class) {
2990                                 encode_value (1, p, &p);
2991                                 encode_klass_ref (acfg, ei->data.catch_class, p, &p);
2992                         } else {
2993                                 encode_value (0, p, &p);
2994                         }
2995                 }
2996
2997                 encode_value ((gint)((guint8*)ei->try_start - code), p, &p);
2998                 encode_value ((gint)((guint8*)ei->try_end - code), p, &p);
2999                 encode_value ((gint)((guint8*)ei->handler_start - code), p, &p);
3000         }
3001
3002         if (jinfo->has_generic_jit_info) {
3003                 MonoGenericJitInfo *gi = mono_jit_info_get_generic_jit_info (jinfo);
3004
3005                 encode_value (gi->has_this ? 1 : 0, p, &p);
3006                 encode_value (gi->this_reg, p, &p);
3007                 encode_value (gi->this_offset, p, &p);
3008
3009                 /* 
3010                  * Need to encode jinfo->method too, since it is not equal to 'method'
3011                  * when using generic sharing.
3012                  */
3013                 encode_method_ref (acfg, jinfo->method, p, &p);
3014         }
3015
3016         g_assert (debug_info_size < buf_size);
3017
3018         encode_value (debug_info_size, p, &p);
3019         if (debug_info_size) {
3020                 memcpy (p, debug_info, debug_info_size);
3021                 p += debug_info_size;
3022                 g_free (debug_info);
3023         }
3024
3025         acfg->stats.ex_info_size += p - buf;
3026
3027         /* Emit info */
3028
3029         emit_label (acfg, symbol);
3030
3031         g_assert (p - buf < buf_size);
3032         emit_bytes (acfg, buf, p - buf);
3033         g_free (buf);
3034 }
3035
3036 static void
3037 emit_klass_info (MonoAotCompile *acfg, guint32 token)
3038 {
3039         MonoClass *klass = mono_class_get (acfg->image, token);
3040         guint8 *p, *buf;
3041         int i, buf_size;
3042         char symbol [128];
3043         gboolean no_special_static, cant_encode;
3044         gpointer iter = NULL;
3045
3046         buf_size = 10240 + (klass->vtable_size * 16);
3047         p = buf = g_malloc (buf_size);
3048
3049         g_assert (klass);
3050
3051         mono_class_init (klass);
3052
3053         mono_class_get_nested_types (klass, &iter);
3054         g_assert (klass->nested_classes_inited);
3055
3056         mono_class_setup_vtable (klass);
3057
3058         /* 
3059          * Emit all the information which is required for creating vtables so
3060          * the runtime does not need to create the MonoMethod structures which
3061          * take up a lot of space.
3062          */
3063
3064         no_special_static = !mono_class_has_special_static_fields (klass);
3065
3066         /* Check whenever we have enough info to encode the vtable */
3067         cant_encode = FALSE;
3068         for (i = 0; i < klass->vtable_size; ++i) {
3069                 MonoMethod *cm = klass->vtable [i];
3070
3071                 if (cm && mono_method_signature (cm)->is_inflated && !g_hash_table_lookup (acfg->token_info_hash, cm))
3072                         cant_encode = TRUE;
3073         }
3074
3075         if (klass->generic_container || cant_encode) {
3076                 encode_value (-1, p, &p);
3077         } else {
3078                 encode_value (klass->vtable_size, p, &p);
3079                 encode_value ((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);
3080                 if (klass->has_cctor)
3081                         encode_method_ref (acfg, mono_class_get_cctor (klass), p, &p);
3082                 if (klass->has_finalize)
3083                         encode_method_ref (acfg, mono_class_get_finalizer (klass), p, &p);
3084  
3085                 encode_value (klass->instance_size, p, &p);
3086                 encode_value (mono_class_data_size (klass), p, &p);
3087                 encode_value (klass->packing_size, p, &p);
3088                 encode_value (klass->min_align, p, &p);
3089
3090                 for (i = 0; i < klass->vtable_size; ++i) {
3091                         MonoMethod *cm = klass->vtable [i];
3092
3093                         if (cm)
3094                                 encode_method_ref (acfg, cm, p, &p);
3095                         else
3096                                 encode_value (0, p, &p);
3097                 }
3098         }
3099
3100         acfg->stats.class_info_size += p - buf;
3101
3102         /* Emit the info */
3103         sprintf (symbol, "%sK_I_%x", acfg->temp_prefix, token - MONO_TOKEN_TYPE_DEF - 1);
3104         emit_label (acfg, symbol);
3105
3106         g_assert (p - buf < buf_size);
3107         emit_bytes (acfg, buf, p - buf);
3108         g_free (buf);
3109 }
3110
3111 /*
3112  * Calls made from AOTed code are routed through a table of jumps similar to the
3113  * ELF PLT (Program Linkage Table). The differences are the following:
3114  * - the ELF PLT entries make an indirect jump though the GOT so they expect the
3115  *   GOT pointer to be in EBX. We want to avoid this, so our table contains direct
3116  *   jumps. This means the jumps need to be patched when the address of the callee is
3117  *   known. Initially the PLT entries jump to code which transfers control to the
3118  *   AOT runtime through the first PLT entry.
3119  */
3120 static void
3121 emit_plt (MonoAotCompile *acfg)
3122 {
3123         char symbol [128];
3124         int i;
3125         GHashTable *cache;
3126
3127         cache = g_hash_table_new (g_str_hash, g_str_equal);
3128
3129         emit_line (acfg);
3130         sprintf (symbol, "plt");
3131
3132         emit_section_change (acfg, ".text", 0);
3133         emit_global (acfg, symbol, TRUE);
3134 #ifdef TARGET_X86
3135         /* This section will be made read-write by the AOT loader */
3136         emit_alignment (acfg, mono_pagesize ());
3137 #else
3138         emit_alignment (acfg, 16);
3139 #endif
3140         emit_label (acfg, symbol);
3141         emit_label (acfg, acfg->plt_symbol);
3142
3143         for (i = 0; i < acfg->plt_offset; ++i) {
3144                 char label [128];
3145                 char *debug_sym = NULL;
3146
3147                 sprintf (label, "%sp_%d", acfg->temp_prefix, i);
3148                 emit_label (acfg, label);
3149
3150                 if (acfg->aot_opts.write_symbols) {
3151                         MonoJumpInfo *ji = g_hash_table_lookup (acfg->plt_offset_to_patch, GUINT_TO_POINTER (i));
3152                         char *debug_sym = NULL;
3153
3154                         if (ji) {
3155                                 switch (ji->type) {
3156                                 case MONO_PATCH_INFO_METHOD:
3157                                         debug_sym = get_debug_sym (ji->data.method, "plt_", cache);
3158                                         break;
3159                                 case MONO_PATCH_INFO_INTERNAL_METHOD:
3160                                         debug_sym = g_strdup_printf ("plt__jit_icall_%s", ji->data.name);
3161                                         break;
3162                                 case MONO_PATCH_INFO_CLASS_INIT:
3163                                         debug_sym = g_strdup_printf ("plt__class_init_%s", mono_type_get_name (&ji->data.klass->byval_arg));
3164                                         sanitize_symbol (debug_sym);
3165                                         break;
3166                                 case MONO_PATCH_INFO_RGCTX_FETCH:
3167                                         debug_sym = g_strdup_printf ("plt__rgctx_fetch_%d", acfg->label_generator ++);
3168                                         break;
3169                                 case MONO_PATCH_INFO_ICALL_ADDR: {
3170                                         char *s = get_debug_sym (ji->data.method, "", cache);
3171                                         
3172                                         debug_sym = g_strdup_printf ("plt__icall_native_%s", s);
3173                                         g_free (s);
3174                                         break;
3175                                 }
3176                                 case MONO_PATCH_INFO_JIT_ICALL_ADDR:
3177                                         debug_sym = g_strdup_printf ("plt__jit_icall_native_%s", ji->data.name);
3178                                         break;
3179                                 case MONO_PATCH_INFO_GENERIC_CLASS_INIT:
3180                                         debug_sym = g_strdup_printf ("plt__generic_class_init");
3181                                         break;
3182                                 default:
3183                                         break;
3184                                 }
3185
3186                                 if (debug_sym) {
3187                                         emit_local_symbol (acfg, debug_sym, NULL, TRUE);
3188                                         emit_label (acfg, debug_sym);
3189                                 }
3190                         }
3191                 }
3192
3193                 /* 
3194                  * The first plt entry is used to transfer code to the AOT loader. 
3195                  */
3196                 arch_emit_plt_entry (acfg, i);
3197
3198                 if (debug_sym) {
3199                         emit_symbol_size (acfg, debug_sym, ".");
3200                         g_free (debug_sym);
3201                 }
3202         }
3203
3204         emit_symbol_size (acfg, acfg->plt_symbol, ".");
3205
3206         sprintf (symbol, "plt_end");
3207         emit_global (acfg, symbol, TRUE);
3208         emit_label (acfg, symbol);
3209
3210         g_hash_table_destroy (cache);
3211 }
3212
3213 static G_GNUC_UNUSED void
3214 emit_trampoline (MonoAotCompile *acfg, const char *name, guint8 *code, 
3215                                  guint32 code_size, int got_offset, MonoJumpInfo *ji, GSList *unwind_ops)
3216 {
3217         char start_symbol [256];
3218         char symbol [256];
3219         guint32 buf_size;
3220         MonoJumpInfo *patch_info;
3221         guint8 *buf, *p;
3222         GPtrArray *patches;
3223
3224         /* Emit code */
3225
3226         sprintf (start_symbol, "%s", name);
3227
3228         emit_section_change (acfg, ".text", 0);
3229         emit_global (acfg, start_symbol, TRUE);
3230         emit_alignment (acfg, 16);
3231         emit_label (acfg, start_symbol);
3232
3233         sprintf (symbol, "%snamed_%s", acfg->temp_prefix, name);
3234         emit_label (acfg, symbol);
3235
3236         /* 
3237          * The code should access everything through the GOT, so we pass
3238          * TRUE here.
3239          */
3240         emit_and_reloc_code (acfg, NULL, code, code_size, ji, TRUE);
3241
3242         emit_symbol_size (acfg, start_symbol, ".");
3243
3244         /* Emit info */
3245
3246         /* Sort relocations */
3247         patches = g_ptr_array_new ();
3248         for (patch_info = ji; patch_info; patch_info = patch_info->next)
3249                 if (patch_info->type != MONO_PATCH_INFO_NONE)
3250                         g_ptr_array_add (patches, patch_info);
3251         g_ptr_array_sort (patches, compare_patches);
3252
3253         buf_size = patches->len * 128 + 128;
3254         buf = g_malloc (buf_size);
3255         p = buf;
3256
3257         encode_patch_list (acfg, patches, patches->len, got_offset, p, &p);
3258         g_assert (p - buf < buf_size);
3259
3260         sprintf (symbol, "%s_p", name);
3261
3262         emit_section_change (acfg, ".text", 0);
3263         emit_global (acfg, symbol, FALSE);
3264         emit_label (acfg, symbol);
3265                 
3266         emit_bytes (acfg, buf, p - buf);
3267
3268         /* Emit debug info */
3269         if (unwind_ops) {
3270                 char symbol2 [256];
3271
3272                 sprintf (symbol, "%s", name);
3273                 sprintf (symbol2, "%snamed_%s", acfg->temp_prefix, name);
3274
3275                 if (acfg->dwarf)
3276                         mono_dwarf_writer_emit_trampoline (acfg->dwarf, symbol, symbol2, NULL, NULL, code_size, unwind_ops);
3277         }
3278 }
3279
3280 static void
3281 emit_trampolines (MonoAotCompile *acfg)
3282 {
3283         char symbol [256];
3284         int i, tramp_got_offset;
3285         MonoAotTrampoline ntype;
3286 #ifdef MONO_ARCH_HAVE_FULL_AOT_TRAMPOLINES
3287         int tramp_type;
3288         guint32 code_size;
3289         MonoJumpInfo *ji;
3290         guint8 *code;
3291         GSList *unwind_ops;
3292 #endif
3293
3294         if (!acfg->aot_opts.full_aot)
3295                 return;
3296         
3297         g_assert (acfg->image->assembly);
3298
3299         /* Currently, we only emit most trampolines into the mscorlib AOT image. */
3300         if (strcmp (acfg->image->assembly->aname.name, "mscorlib") == 0) {
3301 #ifdef MONO_ARCH_HAVE_FULL_AOT_TRAMPOLINES
3302                 /*
3303                  * Emit the generic trampolines.
3304                  *
3305                  * We could save some code by treating the generic trampolines as a wrapper
3306                  * method, but that approach has its own complexities, so we choose the simpler
3307                  * method.
3308                  */
3309                 for (tramp_type = 0; tramp_type < MONO_TRAMPOLINE_NUM; ++tramp_type) {
3310                         code = mono_arch_create_trampoline_code_full (tramp_type, &code_size, &ji, &unwind_ops, TRUE);
3311
3312                         /* Emit trampoline code */
3313
3314                         sprintf (symbol, "generic_trampoline_%d", tramp_type);
3315
3316                         emit_trampoline (acfg, symbol, code, code_size, acfg->got_offset, ji, unwind_ops);
3317                 }
3318
3319                 code = mono_arch_get_nullified_class_init_trampoline (&code_size);
3320                 emit_trampoline (acfg, "nullified_class_init_trampoline", code, code_size, acfg->got_offset, NULL, NULL);
3321 #if defined(TARGET_AMD64) && defined(MONO_ARCH_MONITOR_OBJECT_REG)
3322                 code = mono_arch_create_monitor_enter_trampoline_full (&code_size, &ji, TRUE);
3323                 emit_trampoline (acfg, "monitor_enter_trampoline", code, code_size, acfg->got_offset, ji, NULL);
3324                 code = mono_arch_create_monitor_exit_trampoline_full (&code_size, &ji, TRUE);
3325                 emit_trampoline (acfg, "monitor_exit_trampoline", code, code_size, acfg->got_offset, ji, NULL);
3326 #endif
3327
3328                 code = mono_arch_create_generic_class_init_trampoline_full (&code_size, &ji, TRUE);
3329                 emit_trampoline (acfg, "generic_class_init_trampoline", code, code_size, acfg->got_offset, ji, NULL);
3330
3331                 /* Emit the exception related code pieces */
3332                 code = mono_arch_get_restore_context_full (&code_size, &ji, TRUE);
3333                 emit_trampoline (acfg, "restore_context", code, code_size, acfg->got_offset, ji, NULL);
3334                 code = mono_arch_get_call_filter_full (&code_size, &ji, TRUE);
3335                 emit_trampoline (acfg, "call_filter", code, code_size, acfg->got_offset, ji, NULL);
3336                 code = mono_arch_get_throw_exception_full (&code_size, &ji, TRUE);
3337                 emit_trampoline (acfg, "throw_exception", code, code_size, acfg->got_offset, ji, NULL);
3338                 code = mono_arch_get_rethrow_exception_full (&code_size, &ji, TRUE);
3339                 emit_trampoline (acfg, "rethrow_exception", code, code_size, acfg->got_offset, ji, NULL);
3340                 code = mono_arch_get_throw_exception_by_name_full (&code_size, &ji, TRUE);
3341                 emit_trampoline (acfg, "throw_exception_by_name", code, code_size, acfg->got_offset, ji, NULL);
3342                 code = mono_arch_get_throw_corlib_exception_full (&code_size, &ji, TRUE);
3343                 emit_trampoline (acfg, "throw_corlib_exception", code, code_size, acfg->got_offset, ji, NULL);
3344
3345 #if defined(TARGET_AMD64)
3346                 code = mono_arch_get_throw_pending_exception_full (&code_size, &ji, TRUE);
3347                 emit_trampoline (acfg, "throw_pending_exception", code, code_size, acfg->got_offset, ji, NULL);
3348 #endif
3349
3350                 for (i = 0; i < 128; ++i) {
3351                         int offset;
3352
3353                         offset = MONO_RGCTX_SLOT_MAKE_RGCTX (i);
3354                         code = mono_arch_create_rgctx_lazy_fetch_trampoline_full (offset, &code_size, &ji, TRUE);
3355                         sprintf (symbol, "rgctx_fetch_trampoline_%u", offset);
3356                         emit_trampoline (acfg, symbol, code, code_size, acfg->got_offset, ji, NULL);
3357
3358                         offset = MONO_RGCTX_SLOT_MAKE_MRGCTX (i);
3359                         code = mono_arch_create_rgctx_lazy_fetch_trampoline_full (offset, &code_size, &ji, TRUE);
3360                         sprintf (symbol, "rgctx_fetch_trampoline_%u", offset);
3361                         emit_trampoline (acfg, symbol, code, code_size, acfg->got_offset, ji, NULL);
3362                 }
3363
3364                 {
3365                         GSList *l;
3366
3367                         /* delegate_invoke_impl trampolines */
3368                         l = mono_arch_get_delegate_invoke_impls ();
3369                         while (l) {
3370                                 MonoAotTrampInfo *info = l->data;
3371
3372                                 emit_trampoline (acfg, info->name, info->code, info->code_size, acfg->got_offset, NULL, NULL);
3373                                 l = l->next;
3374                         }
3375                 }
3376
3377 #endif /* #ifdef MONO_ARCH_HAVE_FULL_AOT_TRAMPOLINES */
3378
3379                 /* Emit trampolines which are numerous */
3380
3381                 /*
3382                  * These include the following:
3383                  * - specific trampolines
3384                  * - static rgctx invoke trampolines
3385                  * - imt thunks
3386                  * These trampolines have the same code, they are parameterized by GOT 
3387                  * slots. 
3388                  * They are defined in this file, in the arch_... routines instead of
3389                  * in tramp-<ARCH>.c, since it is easier to do it this way.
3390                  */
3391
3392                 /*
3393                  * When running in aot-only mode, we can't create specific trampolines at 
3394                  * runtime, so we create a few, and save them in the AOT file. 
3395                  * Normal trampolines embed their argument as a literal inside the 
3396                  * trampoline code, we can't do that here, so instead we embed an offset
3397                  * which needs to be added to the trampoline address to get the address of
3398                  * the GOT slot which contains the argument value.
3399                  * The generated trampolines jump to the generic trampolines using another
3400                  * GOT slot, which will be setup by the AOT loader to point to the 
3401                  * generic trampoline code of the given type.
3402                  */
3403
3404                 /*
3405                  * FIXME: Maybe we should use more specific trampolines (i.e. one class init for
3406                  * each class).
3407                  */
3408
3409                 emit_section_change (acfg, ".text", 0);
3410
3411                 tramp_got_offset = acfg->got_offset;
3412
3413                 for (ntype = 0; ntype < MONO_AOT_TRAMP_NUM; ++ntype) {
3414                         switch (ntype) {
3415                         case MONO_AOT_TRAMP_SPECIFIC:
3416                                 sprintf (symbol, "specific_trampolines");
3417                                 break;
3418                         case MONO_AOT_TRAMP_STATIC_RGCTX:
3419                                 sprintf (symbol, "static_rgctx_trampolines");
3420                                 break;
3421                         case MONO_AOT_TRAMP_IMT_THUNK:
3422                                 sprintf (symbol, "imt_thunks");
3423                                 break;
3424                         default:
3425                                 g_assert_not_reached ();
3426                         }
3427
3428                         emit_global (acfg, symbol, TRUE);
3429                         emit_alignment (acfg, 16);
3430                         emit_label (acfg, symbol);
3431
3432                         acfg->trampoline_got_offset_base [ntype] = tramp_got_offset;
3433
3434                         for (i = 0; i < acfg->num_trampolines [ntype]; ++i) {
3435                                 int tramp_size = 0;
3436
3437                                 switch (ntype) {
3438                                 case MONO_AOT_TRAMP_SPECIFIC:
3439                                         arch_emit_specific_trampoline (acfg, tramp_got_offset, &tramp_size);
3440                                         tramp_got_offset += 2;
3441                                 break;
3442                                 case MONO_AOT_TRAMP_STATIC_RGCTX:
3443                                         arch_emit_static_rgctx_trampoline (acfg, tramp_got_offset, &tramp_size);                                
3444                                         tramp_got_offset += 2;
3445                                         break;
3446                                 case MONO_AOT_TRAMP_IMT_THUNK:
3447                                         arch_emit_imt_thunk (acfg, tramp_got_offset, &tramp_size);
3448                                         tramp_got_offset += 1;
3449                                         break;
3450                                 default:
3451                                         g_assert_not_reached ();
3452                                 }
3453
3454                                 if (!acfg->trampoline_size [ntype]) {
3455                                         g_assert (tramp_size);
3456                                         acfg->trampoline_size [ntype] = tramp_size;
3457                                 }
3458                         }
3459                 }
3460
3461                 /* Reserve some entries at the end of the GOT for our use */
3462                 acfg->num_trampoline_got_entries = tramp_got_offset - acfg->got_offset;
3463         }
3464
3465         acfg->got_offset += acfg->num_trampoline_got_entries;
3466 }
3467
3468 static gboolean
3469 str_begins_with (const char *str1, const char *str2)
3470 {
3471         int len = strlen (str2);
3472         return strncmp (str1, str2, len) == 0;
3473 }
3474
3475 static void
3476 mono_aot_parse_options (const char *aot_options, MonoAotOptions *opts)
3477 {
3478         gchar **args, **ptr;
3479
3480         args = g_strsplit (aot_options ? aot_options : "", ",", -1);
3481         for (ptr = args; ptr && *ptr; ptr ++) {
3482                 const char *arg = *ptr;
3483
3484                 if (str_begins_with (arg, "outfile=")) {
3485                         opts->outfile = g_strdup (arg + strlen ("outfile="));
3486                 } else if (str_begins_with (arg, "save-temps")) {
3487                         opts->save_temps = TRUE;
3488                 } else if (str_begins_with (arg, "keep-temps")) {
3489                         opts->save_temps = TRUE;
3490                 } else if (str_begins_with (arg, "write-symbols")) {
3491                         opts->write_symbols = TRUE;
3492                 } else if (str_begins_with (arg, "metadata-only")) {
3493                         opts->metadata_only = TRUE;
3494                 } else if (str_begins_with (arg, "bind-to-runtime-version")) {
3495                         opts->bind_to_runtime_version = TRUE;
3496                 } else if (str_begins_with (arg, "full")) {
3497                         opts->full_aot = TRUE;
3498                 } else if (str_begins_with (arg, "threads=")) {
3499                         opts->nthreads = atoi (arg + strlen ("threads="));
3500                 } else if (str_begins_with (arg, "static")) {
3501                         opts->static_link = TRUE;
3502                         opts->no_dlsym = TRUE;
3503                 } else if (str_begins_with (arg, "asmonly")) {
3504                         opts->asm_only = TRUE;
3505                 } else if (str_begins_with (arg, "asmwriter")) {
3506                         opts->asm_writer = TRUE;
3507                 } else if (str_begins_with (arg, "nodebug")) {
3508                         opts->nodebug = TRUE;
3509                 } else if (str_begins_with (arg, "ntrampolines=")) {
3510                         opts->ntrampolines = atoi (arg + strlen ("ntrampolines="));
3511                 } else if (str_begins_with (arg, "tool-prefix=")) {
3512                         opts->tool_prefix = g_strdup (arg + strlen ("tool-prefix="));
3513                 } else {
3514                         fprintf (stderr, "AOT : Unknown argument '%s'.\n", arg);
3515                         exit (1);
3516                 }
3517         }
3518
3519         g_strfreev (args);
3520 }
3521
3522 static void
3523 add_token_info_hash (gpointer key, gpointer value, gpointer user_data)
3524 {
3525         MonoMethod *method = (MonoMethod*)key;
3526         MonoJumpInfoToken *ji = (MonoJumpInfoToken*)value;
3527         MonoJumpInfoToken *new_ji = g_new0 (MonoJumpInfoToken, 1);
3528         MonoAotCompile *acfg = user_data;
3529
3530         new_ji->image = ji->image;
3531         new_ji->token = ji->token;
3532         g_hash_table_insert (acfg->token_info_hash, method, new_ji);
3533 }
3534
3535 static gboolean
3536 can_encode_class (MonoAotCompile *acfg, MonoClass *klass)
3537 {
3538         if (klass->type_token)
3539                 return TRUE;
3540         if ((klass->byval_arg.type == MONO_TYPE_VAR) || (klass->byval_arg.type == MONO_TYPE_MVAR))
3541                 return TRUE;
3542         if (klass->rank)
3543                 return can_encode_class (acfg, klass->element_class);
3544         return FALSE;
3545 }
3546
3547 static gboolean
3548 can_encode_patch (MonoAotCompile *acfg, MonoJumpInfo *patch_info)
3549 {
3550         switch (patch_info->type) {
3551         case MONO_PATCH_INFO_METHOD:
3552         case MONO_PATCH_INFO_METHODCONST: {
3553                 MonoMethod *method = patch_info->data.method;
3554
3555                 if (method->wrapper_type) {
3556                         switch (method->wrapper_type) {
3557                         case MONO_WRAPPER_NONE:
3558                         case MONO_WRAPPER_REMOTING_INVOKE_WITH_CHECK:
3559                         case MONO_WRAPPER_XDOMAIN_INVOKE:
3560                         case MONO_WRAPPER_STFLD:
3561                         case MONO_WRAPPER_LDFLD:
3562                         case MONO_WRAPPER_LDFLDA:
3563                         case MONO_WRAPPER_LDFLD_REMOTE:
3564                         case MONO_WRAPPER_STFLD_REMOTE:
3565                         case MONO_WRAPPER_STELEMREF:
3566                         case MONO_WRAPPER_ISINST:
3567                         case MONO_WRAPPER_PROXY_ISINST:
3568                         case MONO_WRAPPER_ALLOC:
3569                         case MONO_WRAPPER_REMOTING_INVOKE:
3570                         case MONO_WRAPPER_UNKNOWN:
3571                                 break;
3572                         default:
3573                                 //printf ("Skip (wrapper call): %d -> %s\n", patch_info->type, mono_method_full_name (patch_info->data.method, TRUE));
3574                                 return FALSE;
3575                         }
3576                 } else {
3577                         if (!method->token) {
3578                                 /* The method is part of a constructed type like Int[,].Set (). */
3579                                 if (!g_hash_table_lookup (acfg->token_info_hash, method)) {
3580                                         if (method->klass->rank)
3581                                                 return TRUE;
3582                                         return FALSE;
3583                                 }
3584                         }
3585                 }
3586                 break;
3587         }
3588         case MONO_PATCH_INFO_VTABLE:
3589         case MONO_PATCH_INFO_CLASS_INIT:
3590         case MONO_PATCH_INFO_DELEGATE_TRAMPOLINE:
3591         case MONO_PATCH_INFO_CLASS:
3592         case MONO_PATCH_INFO_IID:
3593         case MONO_PATCH_INFO_ADJUSTED_IID:
3594                 if (!can_encode_class (acfg, patch_info->data.klass)) {
3595                         //printf ("Skip: %s\n", mono_type_full_name (&patch_info->data.klass->byval_arg));
3596                         return FALSE;
3597                 }
3598                 break;
3599         case MONO_PATCH_INFO_RGCTX_FETCH: {
3600                 MonoJumpInfoRgctxEntry *entry = patch_info->data.rgctx_entry;
3601
3602                 if (!can_encode_patch (acfg, entry->data))
3603                         return FALSE;
3604                 break;
3605         }
3606         default:
3607                 break;
3608         }
3609
3610         return TRUE;
3611 }
3612
3613 static void
3614 add_generic_class (MonoAotCompile *acfg, MonoClass *klass);
3615
3616 /*
3617  * compile_method:
3618  *
3619  *   AOT compile a given method.
3620  * This function might be called by multiple threads, so it must be thread-safe.
3621  */
3622 static void
3623 compile_method (MonoAotCompile *acfg, MonoMethod *method)
3624 {
3625         MonoCompile *cfg;
3626         MonoJumpInfo *patch_info;
3627         gboolean skip;
3628         int index;
3629         MonoMethod *wrapped;
3630
3631         if (acfg->aot_opts.metadata_only)
3632                 return;
3633
3634         mono_acfg_lock (acfg);
3635         index = get_method_index (acfg, method);
3636         mono_acfg_unlock (acfg);
3637
3638         /* fixme: maybe we can also precompile wrapper methods */
3639         if ((method->flags & METHOD_ATTRIBUTE_PINVOKE_IMPL) ||
3640                 (method->iflags & METHOD_IMPL_ATTRIBUTE_RUNTIME) ||
3641                 (method->flags & METHOD_ATTRIBUTE_ABSTRACT)) {
3642                 //printf ("Skip (impossible): %s\n", mono_method_full_name (method, TRUE));
3643                 return;
3644         }
3645
3646         if (method->iflags & METHOD_IMPL_ATTRIBUTE_INTERNAL_CALL)
3647                 return;
3648
3649         wrapped = mono_marshal_method_from_wrapper (method);
3650         if (wrapped && (wrapped->iflags & METHOD_IMPL_ATTRIBUTE_INTERNAL_CALL) && wrapped->is_generic)
3651                 // FIXME: The wrapper should be generic too, but it is not
3652                 return;
3653
3654         InterlockedIncrement (&acfg->stats.mcount);
3655
3656 #if 0
3657         if (method->is_generic || method->klass->generic_container) {
3658                 InterlockedIncrement (&acfg->stats.genericcount);
3659                 return;
3660         }
3661 #endif
3662
3663         //acfg->aot_opts.print_skipped_methods = TRUE;
3664
3665         /*
3666          * Since these methods are the only ones which are compiled with
3667          * AOT support, and they are not used by runtime startup/shutdown code,
3668          * the runtime will not see AOT methods during AOT compilation,so it
3669          * does not need to support them by creating a fake GOT etc.
3670          */
3671         cfg = mini_method_compile (method, acfg->opts, mono_get_root_domain (), FALSE, TRUE, 0);
3672         if (cfg->exception_type == MONO_EXCEPTION_GENERIC_SHARING_FAILED) {
3673                 //printf ("F: %s\n", mono_method_full_name (method, TRUE));
3674                 InterlockedIncrement (&acfg->stats.genericcount);
3675                 return;
3676         }
3677         if (cfg->exception_type != MONO_EXCEPTION_NONE) {
3678                 /* Let the exception happen at runtime */
3679                 return;
3680         }
3681
3682         if (cfg->disable_aot) {
3683                 if (acfg->aot_opts.print_skipped_methods)
3684                         printf ("Skip (disabled): %s\n", mono_method_full_name (method, TRUE));
3685                 InterlockedIncrement (&acfg->stats.ocount);
3686                 mono_destroy_compile (cfg);
3687                 return;
3688         }
3689
3690         /* Nullify patches which need no aot processing */
3691         for (patch_info = cfg->patch_info; patch_info; patch_info = patch_info->next) {
3692                 switch (patch_info->type) {
3693                 case MONO_PATCH_INFO_LABEL:
3694                 case MONO_PATCH_INFO_BB:
3695                         patch_info->type = MONO_PATCH_INFO_NONE;
3696                         break;
3697                 default:
3698                         break;
3699                 }
3700         }
3701
3702         /* Collect method->token associations from the cfg */
3703         mono_acfg_lock (acfg);
3704         g_hash_table_foreach (cfg->token_info_hash, add_token_info_hash, acfg);
3705         mono_acfg_unlock (acfg);
3706
3707         /*
3708          * Check for absolute addresses.
3709          */
3710         skip = FALSE;
3711         for (patch_info = cfg->patch_info; patch_info; patch_info = patch_info->next) {
3712                 switch (patch_info->type) {
3713                 case MONO_PATCH_INFO_ABS:
3714                         /* unable to handle this */
3715                         skip = TRUE;    
3716                         break;
3717                 default:
3718                         break;
3719                 }
3720         }
3721
3722         if (skip) {
3723                 if (acfg->aot_opts.print_skipped_methods)
3724                         printf ("Skip (abs call): %s\n", mono_method_full_name (method, TRUE));
3725                 InterlockedIncrement (&acfg->stats.abscount);
3726                 mono_destroy_compile (cfg);
3727                 return;
3728         }
3729
3730         /* Lock for the rest of the code */
3731         mono_acfg_lock (acfg);
3732
3733         /*
3734          * Check for methods/klasses we can't encode.
3735          */
3736         skip = FALSE;
3737         for (patch_info = cfg->patch_info; patch_info; patch_info = patch_info->next) {
3738                 if (!can_encode_patch (acfg, patch_info))
3739                         skip = TRUE;
3740         }
3741
3742         if (skip) {
3743                 if (acfg->aot_opts.print_skipped_methods)
3744                         printf ("Skip (patches): %s\n", mono_method_full_name (method, TRUE));
3745                 acfg->stats.ocount++;
3746                 mono_destroy_compile (cfg);
3747                 mono_acfg_unlock (acfg);
3748                 return;
3749         }
3750
3751         /* Adds generic instances referenced by this method */
3752         for (patch_info = cfg->patch_info; patch_info; patch_info = patch_info->next) {
3753                 switch (patch_info->type) {
3754                 case MONO_PATCH_INFO_METHOD: {
3755                         MonoMethod *m = patch_info->data.method;
3756                         if (m->is_inflated) {
3757                                 if (!(mono_class_generic_sharing_enabled (m->klass) &&
3758                                           mono_method_is_generic_sharable_impl (m, FALSE)) &&
3759                                         !method_has_type_vars (m)) {
3760                                         if (m->iflags & METHOD_IMPL_ATTRIBUTE_INTERNAL_CALL) {
3761                                                 if (acfg->aot_opts.full_aot)
3762                                                         add_extra_method (acfg, mono_marshal_get_native_wrapper (m, TRUE, TRUE));
3763                                         } else {
3764                                                 add_extra_method (acfg, m);
3765                                         }
3766                                 }
3767                                 add_generic_class (acfg, m->klass);
3768                         }
3769                         break;
3770                 }
3771                 case MONO_PATCH_INFO_VTABLE: {
3772                         MonoClass *klass = patch_info->data.klass;
3773
3774                         if (klass->generic_class && !mono_generic_context_is_sharable (&klass->generic_class->context, FALSE))
3775                                 add_generic_class (acfg, klass);
3776                         break;
3777                 }
3778                 default:
3779                         break;
3780                 }
3781         }
3782
3783         /* Determine whenever the method has GOT slots */
3784         for (patch_info = cfg->patch_info; patch_info; patch_info = patch_info->next) {
3785                 switch (patch_info->type) {
3786                 case MONO_PATCH_INFO_GOT_OFFSET:
3787                 case MONO_PATCH_INFO_NONE:
3788                         break;
3789                 case MONO_PATCH_INFO_IMAGE:
3790                         /* The assembly is stored in GOT slot 0 */
3791                         if (patch_info->data.image != acfg->image)
3792                                 cfg->has_got_slots = TRUE;
3793                         break;
3794                 default:
3795                         if (!is_plt_patch (patch_info))
3796                                 cfg->has_got_slots = TRUE;
3797                         break;
3798                 }
3799         }
3800
3801         if (!cfg->has_got_slots)
3802                 InterlockedIncrement (&acfg->stats.methods_without_got_slots);
3803
3804         /* Make a copy of the patch info which is in the mempool */
3805         {
3806                 MonoJumpInfo *patches = NULL, *patches_end = NULL;
3807
3808                 for (patch_info = cfg->patch_info; patch_info; patch_info = patch_info->next) {
3809                         MonoJumpInfo *new_patch_info = mono_patch_info_dup_mp (acfg->mempool, patch_info);
3810
3811                         if (!patches)
3812                                 patches = new_patch_info;
3813                         else
3814                                 patches_end->next = new_patch_info;
3815                         patches_end = new_patch_info;
3816                 }
3817                 cfg->patch_info = patches;
3818         }
3819         /* Make a copy of the unwind info */
3820         {
3821                 GSList *l, *unwind_ops;
3822                 MonoUnwindOp *op;
3823
3824                 unwind_ops = NULL;
3825                 for (l = cfg->unwind_ops; l; l = l->next) {
3826                         op = mono_mempool_alloc (acfg->mempool, sizeof (MonoUnwindOp));
3827                         memcpy (op, l->data, sizeof (MonoUnwindOp));
3828                         unwind_ops = g_slist_prepend_mempool (acfg->mempool, unwind_ops, op);
3829                 }
3830                 cfg->unwind_ops = g_slist_reverse (unwind_ops);
3831         }
3832         /* Make a copy of the argument/local info */
3833         {
3834                 MonoInst **args, **locals;
3835                 MonoMethodSignature *sig;
3836                 MonoMethodHeader *header;
3837                 int i;
3838                 
3839                 sig = mono_method_signature (method);
3840                 args = mono_mempool_alloc (acfg->mempool, sizeof (MonoInst*) * (sig->param_count + sig->hasthis));
3841                 for (i = 0; i < sig->param_count + sig->hasthis; ++i) {
3842                         args [i] = mono_mempool_alloc (acfg->mempool, sizeof (MonoInst));
3843                         memcpy (args [i], cfg->args [i], sizeof (MonoInst));
3844                 }
3845                 cfg->args = args;
3846
3847                 header = mono_method_get_header (method);
3848                 locals = mono_mempool_alloc (acfg->mempool, sizeof (MonoInst*) * header->num_locals);
3849                 for (i = 0; i < header->num_locals; ++i) {
3850                         locals [i] = mono_mempool_alloc (acfg->mempool, sizeof (MonoInst));
3851                         memcpy (locals [i], cfg->locals [i], sizeof (MonoInst));
3852                 }
3853                 cfg->locals = locals;
3854         }
3855
3856         /* Free some fields used by cfg to conserve memory */
3857         mono_mempool_destroy (cfg->mempool);
3858         cfg->mempool = NULL;
3859         g_free (cfg->varinfo);
3860         cfg->varinfo = NULL;
3861         g_free (cfg->vars);
3862         cfg->vars = NULL;
3863         if (cfg->rs) {
3864                 mono_regstate_free (cfg->rs);
3865                 cfg->rs = NULL;
3866         }
3867
3868         //printf ("Compile:           %s\n", mono_method_full_name (method, TRUE));
3869
3870         while (index >= acfg->cfgs_size) {
3871                 MonoCompile **new_cfgs;
3872                 int new_size;
3873
3874                 new_size = acfg->cfgs_size * 2;
3875                 new_cfgs = g_new0 (MonoCompile*, new_size);
3876                 memcpy (new_cfgs, acfg->cfgs, sizeof (MonoCompile*) * acfg->cfgs_size);
3877                 g_free (acfg->cfgs);
3878                 acfg->cfgs = new_cfgs;
3879                 acfg->cfgs_size = new_size;
3880         }
3881         acfg->cfgs [index] = cfg;
3882
3883         g_hash_table_insert (acfg->method_to_cfg, cfg->orig_method, cfg);
3884
3885         /*
3886         if (cfg->orig_method->wrapper_type)
3887                 g_ptr_array_add (acfg->extra_methods, cfg->orig_method);
3888         */
3889
3890         mono_acfg_unlock (acfg);
3891
3892         InterlockedIncrement (&acfg->stats.ccount);
3893 }
3894  
3895 static void
3896 compile_thread_main (gpointer *user_data)
3897 {
3898         MonoDomain *domain = user_data [0];
3899         MonoAotCompile *acfg = user_data [1];
3900         GPtrArray *methods = user_data [2];
3901         int i;
3902
3903         mono_thread_attach (domain);
3904
3905         for (i = 0; i < methods->len; ++i)
3906                 compile_method (acfg, g_ptr_array_index (methods, i));
3907 }
3908
3909 static void
3910 load_profile_files (MonoAotCompile *acfg)
3911 {
3912         FILE *infile;
3913         char *tmp;
3914         int file_index, res, method_index, i;
3915         char ver [256];
3916         guint32 token;
3917         GList *unordered;
3918
3919         file_index = 0;
3920         while (TRUE) {
3921                 tmp = g_strdup_printf ("%s/.mono/aot-profile-data/%s-%s-%d", g_get_home_dir (), acfg->image->assembly_name, acfg->image->guid, file_index);
3922
3923                 if (!g_file_test (tmp, G_FILE_TEST_IS_REGULAR)) {
3924                         g_free (tmp);
3925                         break;
3926                 }
3927
3928                 infile = fopen (tmp, "r");
3929                 g_assert (infile);
3930
3931                 printf ("Using profile data file '%s'\n", tmp);
3932                 g_free (tmp);
3933
3934                 file_index ++;
3935
3936                 res = fscanf (infile, "%32s\n", ver);
3937                 if ((res != 1) || strcmp (ver, "#VER:1") != 0) {
3938                         printf ("Profile file has wrong version or invalid.\n");
3939                         fclose (infile);
3940                         continue;
3941                 }
3942
3943                 while (TRUE) {
3944                         res = fscanf (infile, "%d\n", &token);
3945                         if (res < 1)
3946                                 break;
3947
3948                         method_index = mono_metadata_token_index (token) - 1;
3949
3950                         if (!g_list_find (acfg->method_order, GUINT_TO_POINTER (method_index)))
3951                                 acfg->method_order = g_list_append (acfg->method_order, GUINT_TO_POINTER (method_index));
3952                 }
3953                 fclose (infile);
3954         }
3955
3956         /* Add missing methods */
3957         unordered = NULL;
3958         for (i = 0; i < acfg->image->tables [MONO_TABLE_METHOD].rows; ++i) {
3959                 if (!g_list_find (acfg->method_order, GUINT_TO_POINTER (i)))
3960                         unordered = g_list_prepend (unordered, GUINT_TO_POINTER (i));
3961         }
3962         unordered = g_list_reverse (unordered);
3963         if (acfg->method_order)
3964                 g_list_last (acfg->method_order)->next = unordered;
3965         else
3966                 acfg->method_order = unordered;
3967 }
3968
3969 static void
3970 emit_code (MonoAotCompile *acfg)
3971 {
3972         int i;
3973         char symbol [256];
3974         GList *l;
3975
3976 #if defined(TARGET_POWERPC64)
3977         sprintf (symbol, ".Lgot_addr");
3978         emit_section_change (acfg, ".text", 0);
3979         emit_alignment (acfg, 8);
3980         emit_label (acfg, symbol);
3981         emit_pointer (acfg, acfg->got_symbol);
3982 #endif
3983
3984         sprintf (symbol, "methods");
3985         emit_section_change (acfg, ".text", 0);
3986         emit_global (acfg, symbol, TRUE);
3987         emit_alignment (acfg, 8);
3988         emit_label (acfg, symbol);
3989
3990         /* 
3991          * Emit some padding so the local symbol for the first method doesn't have the
3992          * same address as 'methods'.
3993          */
3994         emit_zero_bytes (acfg, 16);
3995
3996         for (l = acfg->method_order; l != NULL; l = l->next) {
3997                 i = GPOINTER_TO_UINT (l->data);
3998
3999                 if (acfg->cfgs [i])
4000                         emit_method_code (acfg, acfg->cfgs [i]);
4001         }
4002
4003         sprintf (symbol, "methods_end");
4004         emit_section_change (acfg, ".text", 0);
4005         emit_global (acfg, symbol, FALSE);
4006         emit_alignment (acfg, 8);
4007         emit_label (acfg, symbol);
4008
4009         sprintf (symbol, "method_offsets");
4010         emit_section_change (acfg, ".text", 1);
4011         emit_global (acfg, symbol, FALSE);
4012         emit_alignment (acfg, 8);
4013         emit_label (acfg, symbol);
4014
4015         for (i = 0; i < acfg->nmethods; ++i) {
4016                 if (acfg->cfgs [i]) {
4017                         sprintf (symbol, "%sm_%x", acfg->temp_prefix, i);
4018                         emit_symbol_diff (acfg, symbol, "methods", 0);
4019                 } else {
4020                         emit_int32 (acfg, 0xffffffff);
4021                 }
4022         }
4023         emit_line (acfg);
4024 }
4025
4026 static void
4027 emit_info (MonoAotCompile *acfg)
4028 {
4029         int i;
4030         char symbol [256];
4031         GList *l;
4032
4033         /* Emit method info */
4034         sprintf (symbol, "method_info");
4035         emit_section_change (acfg, ".text", 1);
4036         emit_global (acfg, symbol, FALSE);
4037         emit_alignment (acfg, 8);
4038         emit_label (acfg, symbol);
4039
4040         /* To reduce size of generated assembly code */
4041         sprintf (symbol, "mi");
4042         emit_label (acfg, symbol);
4043
4044         for (l = acfg->method_order; l != NULL; l = l->next) {
4045                 i = GPOINTER_TO_UINT (l->data);
4046
4047                 if (acfg->cfgs [i])
4048                         emit_method_info (acfg, acfg->cfgs [i]);
4049         }
4050
4051         sprintf (symbol, "method_info_offsets");
4052         emit_section_change (acfg, ".text", 1);
4053         emit_global (acfg, symbol, FALSE);
4054         emit_alignment (acfg, 8);
4055         emit_label (acfg, symbol);
4056
4057         for (i = 0; i < acfg->nmethods; ++i) {
4058                 if (acfg->cfgs [i]) {
4059                         sprintf (symbol, "%sm_%x_p", acfg->temp_prefix, i);
4060                         emit_symbol_diff (acfg, symbol, "mi", 0);
4061                 } else {
4062                         emit_int32 (acfg, 0);
4063                 }
4064         }
4065         emit_line (acfg);
4066 }
4067
4068 #endif /* #if !defined(DISABLE_AOT) && !defined(DISABLE_JIT) */
4069
4070 /*
4071  * mono_aot_str_hash:
4072  *
4073  * Hash function for strings which we use to hash strings for things which are
4074  * saved in the AOT image, since g_str_hash () can change.
4075  */
4076 guint
4077 mono_aot_str_hash (gconstpointer v1)
4078 {
4079         /* Same as g_str_hash () in glib */
4080         char *p = (char *) v1;
4081         guint hash = *p;
4082
4083         while (*p++) {
4084                 if (*p)
4085                         hash = (hash << 5) - hash + *p;
4086         }
4087
4088         return hash;
4089
4090
4091 #define rot(x,k) (((x)<<(k)) | ((x)>>(32-(k))))
4092 #define mix(a,b,c) { \
4093         a -= c;  a ^= rot(c, 4);  c += b; \
4094         b -= a;  b ^= rot(a, 6);  a += c; \
4095         c -= b;  c ^= rot(b, 8);  b += a; \
4096         a -= c;  a ^= rot(c,16);  c += b; \
4097         b -= a;  b ^= rot(a,19);  a += c; \
4098         c -= b;  c ^= rot(b, 4);  b += a; \
4099 }
4100 #define final(a,b,c) { \
4101         c ^= b; c -= rot(b,14); \
4102         a ^= c; a -= rot(c,11); \
4103         b ^= a; b -= rot(a,25); \
4104         c ^= b; c -= rot(b,16); \
4105         a ^= c; a -= rot(c,4);  \
4106         b ^= a; b -= rot(a,14); \
4107         c ^= b; c -= rot(b,24); \
4108 }
4109
4110 static guint
4111 mono_aot_type_hash (MonoType *t1)
4112 {
4113         guint hash = t1->type;
4114
4115         hash |= t1->byref << 6; /* do not collide with t1->type values */
4116         switch (t1->type) {
4117         case MONO_TYPE_VALUETYPE:
4118         case MONO_TYPE_CLASS:
4119         case MONO_TYPE_SZARRAY:
4120                 /* check if the distribution is good enough */
4121                 return ((hash << 5) - hash) ^ mono_aot_str_hash (t1->data.klass->name);
4122         case MONO_TYPE_PTR:
4123                 return ((hash << 5) - hash) ^ mono_aot_type_hash (t1->data.type);
4124         case MONO_TYPE_ARRAY:
4125                 return ((hash << 5) - hash) ^ mono_aot_type_hash (&t1->data.array->eklass->byval_arg);
4126         case MONO_TYPE_GENERICINST:
4127                 return ((hash << 5) - hash) ^ 0;
4128         }
4129         return hash;
4130 }
4131
4132 /*
4133  * mono_aot_method_hash:
4134  *
4135  *   Return a hash code for methods which only depends on metadata.
4136  */
4137 guint32
4138 mono_aot_method_hash (MonoMethod *method)
4139 {
4140         MonoMethodSignature *sig;
4141         MonoClass *klass;
4142         int i;
4143         int hashes_count;
4144         guint32 *hashes_start, *hashes;
4145         guint32 a, b, c;
4146
4147         /* Similar to the hash in mono_method_get_imt_slot () */
4148
4149         sig = mono_method_signature (method);
4150
4151         hashes_count = sig->param_count + 5;
4152         hashes_start = malloc (hashes_count * sizeof (guint32));
4153         hashes = hashes_start;
4154
4155         /* Some wrappers are assigned to random classes */
4156         if (!method->wrapper_type || method->wrapper_type == MONO_WRAPPER_REMOTING_INVOKE_WITH_CHECK)
4157                 klass = method->klass;
4158         else
4159                 klass = mono_defaults.object_class;
4160
4161         if (!method->wrapper_type) {
4162                 char *full_name = mono_type_full_name (&klass->byval_arg);
4163
4164                 hashes [0] = mono_aot_str_hash (full_name);
4165                 hashes [1] = 0;
4166                 g_free (full_name);
4167         } else {
4168                 hashes [0] = mono_aot_str_hash (klass->name);
4169                 hashes [1] = mono_aot_str_hash (klass->name_space);
4170         }
4171         hashes [2] = mono_aot_str_hash (method->name);
4172         hashes [3] = method->wrapper_type;
4173         hashes [4] = mono_aot_type_hash (sig->ret);
4174         for (i = 0; i < sig->param_count; i++) {
4175                 hashes [5 + i] = mono_aot_type_hash (sig->params [i]);
4176         }
4177         
4178         /* Setup internal state */
4179         a = b = c = 0xdeadbeef + (((guint32)hashes_count)<<2);
4180
4181         /* Handle most of the hashes */
4182         while (hashes_count > 3) {
4183                 a += hashes [0];
4184                 b += hashes [1];
4185                 c += hashes [2];
4186                 mix (a,b,c);
4187                 hashes_count -= 3;
4188                 hashes += 3;
4189         }
4190
4191         /* Handle the last 3 hashes (all the case statements fall through) */
4192         switch (hashes_count) { 
4193         case 3 : c += hashes [2];
4194         case 2 : b += hashes [1];
4195         case 1 : a += hashes [0];
4196                 final (a,b,c);
4197         case 0: /* nothing left to add */
4198                 break;
4199         }
4200         
4201         free (hashes_start);
4202         
4203         return c;
4204 }
4205 #undef rot
4206 #undef mix
4207 #undef final
4208
4209 /*
4210  * mono_aot_wrapper_name:
4211  *
4212  *   Return a string which uniqely identifies the given wrapper method.
4213  */
4214 char*
4215 mono_aot_wrapper_name (MonoMethod *method)
4216 {
4217         char *name, *tmpsig, *klass_desc;
4218
4219         tmpsig = mono_signature_get_desc (mono_method_signature (method), TRUE);
4220
4221         switch (method->wrapper_type) {
4222         case MONO_WRAPPER_RUNTIME_INVOKE:
4223                 if (!strcmp (method->name, "runtime_invoke_dynamic"))
4224                         name = g_strdup_printf ("(wrapper runtime-invoke-dynamic)");
4225                 else
4226                         name = g_strdup_printf ("%s (%s)", method->name, tmpsig);
4227                 break;
4228         case MONO_WRAPPER_DELEGATE_INVOKE:
4229         case MONO_WRAPPER_DELEGATE_BEGIN_INVOKE:
4230         case MONO_WRAPPER_DELEGATE_END_INVOKE:
4231                 /* This is a hack to work around the fact that these wrappers get assigned to some random class */
4232                 name = g_strdup_printf ("%s (%s)", method->name, tmpsig);
4233                 break;
4234         default:
4235                 klass_desc = mono_type_full_name (&method->klass->byval_arg);
4236
4237                 name = g_strdup_printf ("%s:%s (%s)", klass_desc, method->name, tmpsig);
4238                 break;
4239         }
4240
4241         g_free (tmpsig);
4242
4243         return name;
4244 }
4245
4246 /*
4247  * mono_aot_tramp_info_create:
4248  *
4249  *   Create a MonoAotTrampInfo structure from the arguments.
4250  */
4251 MonoAotTrampInfo*
4252 mono_aot_tramp_info_create (const char *name, guint8 *code, guint32 code_size)
4253 {
4254         MonoAotTrampInfo *info = g_new0 (MonoAotTrampInfo, 1);
4255
4256         info->name = (char*)name;
4257         info->code = code;
4258         info->code_size = code_size;
4259
4260         return info;
4261 }
4262
4263 #if !defined(DISABLE_AOT) && !defined(DISABLE_JIT)
4264
4265 typedef struct HashEntry {
4266     guint32 key, value, index;
4267         struct HashEntry *next;
4268 } HashEntry;
4269
4270 /*
4271  * emit_extra_methods:
4272  *
4273  * Emit methods which are not in the METHOD table, like wrappers.
4274  */
4275 static void
4276 emit_extra_methods (MonoAotCompile *acfg)
4277 {
4278         int i, table_size, buf_size;
4279         char symbol [256];
4280         guint8 *p, *buf;
4281         guint32 *info_offsets;
4282         guint32 hash;
4283         GPtrArray *table;
4284         HashEntry *entry, *new_entry;
4285         int nmethods, max_chain_length;
4286         int *chain_lengths;
4287
4288         info_offsets = g_new0 (guint32, acfg->extra_methods->len);
4289
4290         buf_size = acfg->extra_methods->len * 256 + 256;
4291         p = buf = g_malloc (buf_size);
4292
4293         /* Encode method info */
4294         nmethods = 0;
4295         /* So offsets are > 0 */
4296         *p = 0;
4297         p++;
4298         for (i = 0; i < acfg->extra_methods->len; ++i) {
4299                 MonoMethod *method = g_ptr_array_index (acfg->extra_methods, i);
4300                 MonoCompile *cfg = g_hash_table_lookup (acfg->method_to_cfg, method);
4301                 char *name;
4302
4303                 if (!cfg)
4304                         continue;
4305
4306                 nmethods ++;
4307                 info_offsets [i] = p - buf;
4308
4309                 name = NULL;
4310                 if (method->wrapper_type) {
4311                         /* 
4312                          * We encode some wrappers using their name, since encoding them
4313                          * directly would be difficult. This also avoids creating the wrapper
4314                          * methods at runtime, since they are not needed anyway.
4315                          */
4316                         switch (method->wrapper_type) {
4317                         case MONO_WRAPPER_REMOTING_INVOKE_WITH_CHECK:
4318                         case MONO_WRAPPER_SYNCHRONIZED:
4319                                 /* encode_method_ref () can handle these */
4320                                 break;
4321                         case MONO_WRAPPER_RUNTIME_INVOKE:
4322                                 if (mono_marshal_method_from_wrapper (method) != method && !strstr (method->name, "virtual"))
4323                                         /* Direct wrapper, encode normally */
4324                                         break;
4325                                 /* Fall through */
4326                         default:
4327                                 name = mono_aot_wrapper_name (method);
4328                                 break;
4329                         }
4330                 }
4331
4332                 if (name) {
4333                         encode_value (1, p, &p);
4334                         encode_value (method->wrapper_type, p, &p);
4335                         strcpy ((char*)p, name);
4336                         p += strlen (name ) + 1;
4337                         g_free (name);
4338                 } else {
4339                         encode_value (0, p, &p);
4340                         encode_method_ref (acfg, method, p, &p);
4341                 }
4342
4343                 g_assert ((p - buf) < buf_size);
4344         }
4345
4346         g_assert ((p - buf) < buf_size);
4347
4348         /* Emit method info */
4349         sprintf (symbol, "extra_method_info");
4350         emit_section_change (acfg, ".text", 1);
4351         emit_global (acfg, symbol, FALSE);
4352         emit_alignment (acfg, 8);
4353         emit_label (acfg, symbol);
4354
4355         emit_bytes (acfg, buf, p - buf);
4356
4357         emit_line (acfg);
4358
4359         /*
4360          * Construct a chained hash table for mapping indexes in extra_method_info to
4361          * method indexes.
4362          */
4363         table_size = g_spaced_primes_closest ((int)(nmethods * 1.5));
4364         table = g_ptr_array_sized_new (table_size);
4365         for (i = 0; i < table_size; ++i)
4366                 g_ptr_array_add (table, NULL);
4367         chain_lengths = g_new0 (int, table_size);
4368         max_chain_length = 0;
4369         for (i = 0; i < acfg->extra_methods->len; ++i) {
4370                 MonoMethod *method = g_ptr_array_index (acfg->extra_methods, i);
4371                 MonoCompile *cfg = g_hash_table_lookup (acfg->method_to_cfg, method);
4372                 guint32 key, value;
4373
4374                 if (!cfg)
4375                         continue;
4376
4377                 key = info_offsets [i];
4378                 value = get_method_index (acfg, method);
4379
4380                 hash = mono_aot_method_hash (method) % table_size;
4381
4382                 chain_lengths [hash] ++;
4383                 max_chain_length = MAX (max_chain_length, chain_lengths [hash]);
4384
4385                 /* FIXME: Allocate from the mempool */
4386                 new_entry = g_new0 (HashEntry, 1);
4387                 new_entry->key = key;
4388                 new_entry->value = value;
4389
4390                 entry = g_ptr_array_index (table, hash);
4391                 if (entry == NULL) {
4392                         new_entry->index = hash;
4393                         g_ptr_array_index (table, hash) = new_entry;
4394                 } else {
4395                         while (entry->next)
4396                                 entry = entry->next;
4397                         
4398                         entry->next = new_entry;
4399                         new_entry->index = table->len;
4400                         g_ptr_array_add (table, new_entry);
4401                 }
4402         }
4403
4404         //printf ("MAX: %d\n", max_chain_length);
4405
4406         /* Emit the table */
4407         sprintf (symbol, "extra_method_table");
4408         emit_section_change (acfg, ".text", 0);
4409         emit_global (acfg, symbol, FALSE);
4410         emit_alignment (acfg, 8);
4411         emit_label (acfg, symbol);
4412
4413         g_assert (table_size < 65000);
4414         emit_int32 (acfg, table_size);
4415         g_assert (table->len < 65000);
4416         for (i = 0; i < table->len; ++i) {
4417                 HashEntry *entry = g_ptr_array_index (table, i);
4418
4419                 if (entry == NULL) {
4420                         emit_int32 (acfg, 0);
4421                         emit_int32 (acfg, 0);
4422                         emit_int32 (acfg, 0);
4423                 } else {
4424                         g_assert (entry->key > 0);
4425                         emit_int32 (acfg, entry->key);
4426                         emit_int32 (acfg, entry->value);
4427                         if (entry->next)
4428                                 emit_int32 (acfg, entry->next->index);
4429                         else
4430                                 emit_int32 (acfg, 0);
4431                 }
4432         }
4433
4434         /* 
4435          * Emit a table reverse mapping method indexes to their index in extra_method_info.
4436          * This is used by mono_aot_find_jit_info ().
4437          */
4438         sprintf (symbol, "extra_method_info_offsets");
4439         emit_section_change (acfg, ".text", 0);
4440         emit_global (acfg, symbol, FALSE);
4441         emit_alignment (acfg, 8);
4442         emit_label (acfg, symbol);
4443
4444         emit_int32 (acfg, acfg->extra_methods->len);
4445         for (i = 0; i < acfg->extra_methods->len; ++i) {
4446                 MonoMethod *method = g_ptr_array_index (acfg->extra_methods, i);
4447
4448                 emit_int32 (acfg, get_method_index (acfg, method));
4449                 emit_int32 (acfg, info_offsets [i]);
4450         }
4451 }       
4452
4453 static void
4454 emit_method_order (MonoAotCompile *acfg)
4455 {
4456         int i, index, len;
4457         char symbol [256];
4458         GList *l;
4459
4460         sprintf (symbol, "method_order");
4461         emit_section_change (acfg, ".text", 1);
4462         emit_global (acfg, symbol, FALSE);
4463         emit_alignment (acfg, 8);
4464         emit_label (acfg, symbol);
4465
4466         /* First emit an index table */
4467         index = 0;
4468         len = 0;
4469         for (l = acfg->method_order; l != NULL; l = l->next) {
4470                 i = GPOINTER_TO_UINT (l->data);
4471
4472                 if (acfg->cfgs [i]) {
4473                         if ((index % 1024) == 0) {
4474                                 emit_int32 (acfg, i);
4475                         }
4476
4477                         index ++;
4478                 }
4479
4480                 len ++;
4481         }
4482         emit_int32 (acfg, 0xffffff);
4483
4484         /* Then emit the whole method order */
4485         for (l = acfg->method_order; l != NULL; l = l->next) {
4486                 i = GPOINTER_TO_UINT (l->data);
4487
4488                 if (acfg->cfgs [i]) {
4489                         emit_int32 (acfg, i);
4490                 }
4491         }       
4492         emit_line (acfg);
4493
4494         sprintf (symbol, "method_order_end");
4495         emit_section_change (acfg, ".text", 1);
4496         emit_global (acfg, symbol, FALSE);
4497         emit_label (acfg, symbol);
4498 }
4499
4500 static void
4501 emit_exception_info (MonoAotCompile *acfg)
4502 {
4503         int i;
4504         char symbol [256];
4505
4506         sprintf (symbol, "ex_info");
4507         emit_section_change (acfg, ".text", 1);
4508         emit_global (acfg, symbol, FALSE);
4509         emit_alignment (acfg, 8);
4510         emit_label (acfg, symbol);
4511
4512         /* To reduce size of generated assembly */
4513         sprintf (symbol, "ex");
4514         emit_label (acfg, symbol);
4515
4516         for (i = 0; i < acfg->nmethods; ++i) {
4517                 if (acfg->cfgs [i])
4518                         emit_exception_debug_info (acfg, acfg->cfgs [i]);
4519         }
4520
4521         sprintf (symbol, "ex_info_offsets");
4522         emit_section_change (acfg, ".text", 1);
4523         emit_global (acfg, symbol, FALSE);
4524         emit_alignment (acfg, 8);
4525         emit_label (acfg, symbol);
4526
4527         for (i = 0; i < acfg->nmethods; ++i) {
4528                 if (acfg->cfgs [i]) {
4529                         sprintf (symbol, "%se_%x_p", acfg->temp_prefix, i);
4530                         emit_symbol_diff (acfg, symbol, "ex", 0);
4531                 } else {
4532                         emit_int32 (acfg, 0);
4533                 }
4534         }
4535         emit_line (acfg);
4536 }
4537
4538 static void
4539 emit_unwind_info (MonoAotCompile *acfg)
4540 {
4541         int i;
4542         char symbol [128];
4543
4544         /* 
4545          * The unwind info contains a lot of duplicates so we emit each unique
4546          * entry once, and only store the offset from the start of the table in the
4547          * exception info.
4548          */
4549
4550         sprintf (symbol, "unwind_info");
4551         emit_section_change (acfg, ".text", 1);
4552         emit_alignment (acfg, 8);
4553         emit_label (acfg, symbol);
4554         emit_global (acfg, symbol, FALSE);
4555
4556         for (i = 0; i < acfg->unwind_ops->len; ++i) {
4557                 guint32 index = GPOINTER_TO_UINT (g_ptr_array_index (acfg->unwind_ops, i));
4558                 guint8 *unwind_info;
4559                 guint32 unwind_info_len;
4560                 guint8 buf [16];
4561                 guint8 *p;
4562
4563                 unwind_info = mono_get_cached_unwind_info (index, &unwind_info_len);
4564
4565                 p = buf;
4566                 encode_value (unwind_info_len, p, &p);
4567                 emit_bytes (acfg, buf, p - buf);
4568                 emit_bytes (acfg, unwind_info, unwind_info_len);
4569
4570                 acfg->stats.unwind_info_size += (p - buf) + unwind_info_len;
4571         }
4572 }
4573
4574 static void
4575 emit_class_info (MonoAotCompile *acfg)
4576 {
4577         int i;
4578         char symbol [256];
4579
4580         sprintf (symbol, "class_info");
4581         emit_section_change (acfg, ".text", 1);
4582         emit_global (acfg, symbol, FALSE);
4583         emit_alignment (acfg, 8);
4584         emit_label (acfg, symbol);
4585
4586         for (i = 0; i < acfg->image->tables [MONO_TABLE_TYPEDEF].rows; ++i)
4587                 emit_klass_info (acfg, MONO_TOKEN_TYPE_DEF | (i + 1));
4588
4589         sprintf (symbol, "class_info_offsets");
4590         emit_section_change (acfg, ".text", 1);
4591         emit_global (acfg, symbol, FALSE);
4592         emit_alignment (acfg, 8);
4593         emit_label (acfg, symbol);
4594
4595         for (i = 0; i < acfg->image->tables [MONO_TABLE_TYPEDEF].rows; ++i) {
4596                 sprintf (symbol, "%sK_I_%x", acfg->temp_prefix, i);
4597                 emit_symbol_diff (acfg, symbol, "class_info", 0);
4598         }
4599         emit_line (acfg);
4600 }
4601
4602 typedef struct ClassNameTableEntry {
4603         guint32 token, index;
4604         struct ClassNameTableEntry *next;
4605 } ClassNameTableEntry;
4606
4607 static void
4608 emit_class_name_table (MonoAotCompile *acfg)
4609 {
4610         int i, table_size;
4611         guint32 token, hash;
4612         MonoClass *klass;
4613         GPtrArray *table;
4614         char *full_name;
4615         char symbol [256];
4616         ClassNameTableEntry *entry, *new_entry;
4617
4618         /*
4619          * Construct a chained hash table for mapping class names to typedef tokens.
4620          */
4621         table_size = g_spaced_primes_closest ((int)(acfg->image->tables [MONO_TABLE_TYPEDEF].rows * 1.5));
4622         table = g_ptr_array_sized_new (table_size);
4623         for (i = 0; i < table_size; ++i)
4624                 g_ptr_array_add (table, NULL);
4625         for (i = 0; i < acfg->image->tables [MONO_TABLE_TYPEDEF].rows; ++i) {
4626                 token = MONO_TOKEN_TYPE_DEF | (i + 1);
4627                 klass = mono_class_get (acfg->image, token);
4628                 full_name = mono_type_get_name_full (mono_class_get_type (klass), MONO_TYPE_NAME_FORMAT_FULL_NAME);
4629                 hash = mono_aot_str_hash (full_name) % table_size;
4630                 g_free (full_name);
4631
4632                 /* FIXME: Allocate from the mempool */
4633                 new_entry = g_new0 (ClassNameTableEntry, 1);
4634                 new_entry->token = token;
4635
4636                 entry = g_ptr_array_index (table, hash);
4637                 if (entry == NULL) {
4638                         new_entry->index = hash;
4639                         g_ptr_array_index (table, hash) = new_entry;
4640                 } else {
4641                         while (entry->next)
4642                                 entry = entry->next;
4643                         
4644                         entry->next = new_entry;
4645                         new_entry->index = table->len;
4646                         g_ptr_array_add (table, new_entry);
4647                 }
4648         }
4649
4650         /* Emit the table */
4651         sprintf (symbol, "class_name_table");
4652         emit_section_change (acfg, ".text", 0);
4653         emit_global (acfg, symbol, FALSE);
4654         emit_alignment (acfg, 8);
4655         emit_label (acfg, symbol);
4656
4657         /* FIXME: Optimize memory usage */
4658         g_assert (table_size < 65000);
4659         emit_int16 (acfg, table_size);
4660         g_assert (table->len < 65000);
4661         for (i = 0; i < table->len; ++i) {
4662                 ClassNameTableEntry *entry = g_ptr_array_index (table, i);
4663
4664                 if (entry == NULL) {
4665                         emit_int16 (acfg, 0);
4666                         emit_int16 (acfg, 0);
4667                 } else {
4668                         emit_int16 (acfg, mono_metadata_token_index (entry->token));
4669                         if (entry->next)
4670                                 emit_int16 (acfg, entry->next->index);
4671                         else
4672                                 emit_int16 (acfg, 0);
4673                 }
4674         }
4675 }
4676
4677 static void
4678 emit_image_table (MonoAotCompile *acfg)
4679 {
4680         int i;
4681         char symbol [256];
4682
4683         /*
4684          * The image table is small but referenced in a lot of places.
4685          * So we emit it at once, and reference its elements by an index.
4686          */
4687
4688         sprintf (symbol, "mono_image_table");
4689         emit_section_change (acfg, ".text", 1);
4690         emit_global (acfg, symbol, FALSE);
4691         emit_alignment (acfg, 8);
4692         emit_label (acfg, symbol);
4693
4694         emit_int32 (acfg, acfg->image_table->len);
4695         for (i = 0; i < acfg->image_table->len; i++) {
4696                 MonoImage *image = (MonoImage*)g_ptr_array_index (acfg->image_table, i);
4697                 MonoAssemblyName *aname = &image->assembly->aname;
4698
4699                 /* FIXME: Support multi-module assemblies */
4700                 g_assert (image->assembly->image == image);
4701
4702                 emit_string (acfg, image->assembly_name);
4703                 emit_string (acfg, image->guid);
4704                 emit_string (acfg, aname->culture ? aname->culture : "");
4705                 emit_string (acfg, (const char*)aname->public_key_token);
4706
4707                 emit_alignment (acfg, 8);
4708                 emit_int32 (acfg, aname->flags);
4709                 emit_int32 (acfg, aname->major);
4710                 emit_int32 (acfg, aname->minor);
4711                 emit_int32 (acfg, aname->build);
4712                 emit_int32 (acfg, aname->revision);
4713         }
4714 }
4715
4716 static void
4717 emit_got_info (MonoAotCompile *acfg)
4718 {
4719         char symbol [256];
4720         int i, first_plt_got_patch, buf_size;
4721         guint8 *p, *buf;
4722         guint32 *got_info_offsets;
4723
4724         /* Add the patches needed by the PLT to the GOT */
4725         acfg->plt_got_offset_base = acfg->got_offset;
4726         first_plt_got_patch = acfg->got_patches->len;
4727         for (i = 1; i < acfg->plt_offset; ++i) {
4728                 MonoJumpInfo *patch_info = g_hash_table_lookup (acfg->plt_offset_to_patch, GUINT_TO_POINTER (i));
4729
4730                 g_ptr_array_add (acfg->got_patches, patch_info);
4731         }
4732
4733         acfg->got_offset += acfg->plt_offset;
4734
4735         /**
4736          * FIXME: 
4737          * - optimize offsets table.
4738          * - reduce number of exported symbols.
4739          * - emit info for a klass only once.
4740          * - determine when a method uses a GOT slot which is guaranteed to be already 
4741          *   initialized.
4742          * - clean up and document the code.
4743          * - use String.Empty in class libs.
4744          */
4745
4746         /* Encode info required to decode shared GOT entries */
4747         buf_size = acfg->got_patches->len * 64;
4748         p = buf = mono_mempool_alloc (acfg->mempool, buf_size);
4749         got_info_offsets = mono_mempool_alloc (acfg->mempool, acfg->got_patches->len * sizeof (guint32));
4750         acfg->plt_got_info_offsets = mono_mempool_alloc (acfg->mempool, acfg->plt_offset * sizeof (guint32));
4751         /* Unused */
4752         if (acfg->plt_offset)
4753                 acfg->plt_got_info_offsets [0] = 0;
4754         for (i = 0; i < acfg->got_patches->len; ++i) {
4755                 MonoJumpInfo *ji = g_ptr_array_index (acfg->got_patches, i);
4756
4757                 got_info_offsets [i] = p - buf;
4758                 if (i >= first_plt_got_patch)
4759                         acfg->plt_got_info_offsets [i - first_plt_got_patch + 1] = got_info_offsets [i];
4760                 encode_value (ji->type, p, &p);
4761                 encode_patch (acfg, ji, p, &p);
4762         }
4763
4764         g_assert (p - buf <= buf_size);
4765
4766         acfg->stats.got_info_size = p - buf;
4767
4768         /* Emit got_info table */
4769         sprintf (symbol, "got_info");
4770         emit_section_change (acfg, ".text", 1);
4771         emit_global (acfg, symbol, FALSE);
4772         emit_alignment (acfg, 8);
4773         emit_label (acfg, symbol);
4774
4775         emit_bytes (acfg, buf, p - buf);
4776
4777         /* Emit got_info_offsets table */
4778         sprintf (symbol, "got_info_offsets");
4779         emit_section_change (acfg, ".text", 1);
4780         emit_global (acfg, symbol, FALSE);
4781         emit_alignment (acfg, 8);
4782         emit_label (acfg, symbol);
4783
4784         /* No need to emit offsets for the got plt entries, the plt embeds them directly */
4785         for (i = 0; i < first_plt_got_patch; ++i)
4786                 emit_int32 (acfg, got_info_offsets [i]);
4787
4788         acfg->stats.got_info_offsets_size = acfg->got_patches->len * 4;
4789 }
4790
4791 static void
4792 emit_got (MonoAotCompile *acfg)
4793 {
4794         char symbol [256];
4795
4796         /* Don't make GOT global so accesses to it don't need relocations */
4797         sprintf (symbol, "%s", acfg->got_symbol);
4798         emit_section_change (acfg, ".bss", 0);
4799         emit_alignment (acfg, 8);
4800         emit_local_symbol (acfg, symbol, "got_end", FALSE);
4801         emit_label (acfg, symbol);
4802         if (acfg->got_offset > 0)
4803                 emit_zero_bytes (acfg, (int)(acfg->got_offset * sizeof (gpointer)));
4804
4805         sprintf (symbol, "got_end");
4806         emit_label (acfg, symbol);
4807
4808         sprintf (symbol, "mono_aot_got_addr");
4809         emit_section_change (acfg, ".data", 0);
4810         emit_global (acfg, symbol, FALSE);
4811         emit_alignment (acfg, 8);
4812         emit_label (acfg, symbol);
4813         emit_pointer (acfg, acfg->got_symbol);
4814 }
4815
4816 static void
4817 emit_globals (MonoAotCompile *acfg)
4818 {
4819         char *opts_str;
4820         char *build_info;
4821
4822         emit_string_symbol (acfg, "mono_assembly_guid" , acfg->image->guid);
4823
4824         emit_string_symbol (acfg, "mono_aot_version", MONO_AOT_FILE_VERSION);
4825
4826         opts_str = g_strdup_printf ("%d", acfg->opts);
4827         emit_string_symbol (acfg, "mono_aot_opt_flags", opts_str);
4828         g_free (opts_str);
4829
4830         emit_string_symbol (acfg, "mono_aot_full_aot", acfg->aot_opts.full_aot ? "TRUE" : "FALSE");
4831
4832         if (acfg->aot_opts.bind_to_runtime_version) {
4833                 build_info = mono_get_runtime_build_info ();
4834                 emit_string_symbol (acfg, "mono_runtime_version", build_info);
4835                 g_free (build_info);
4836         } else {
4837                 emit_string_symbol (acfg, "mono_runtime_version", "");
4838         }
4839
4840         /* 
4841          * When static linking, we emit a global which will point to the symbol table.
4842          */
4843         if (acfg->aot_opts.static_link) {
4844                 int i;
4845                 char symbol [256];
4846                 char *p;
4847
4848                 /* Emit a string holding the assembly name */
4849                 emit_string_symbol (acfg, "mono_aot_assembly_name", acfg->image->assembly->aname.name);
4850
4851                 /* Emit the names */
4852                 for (i = 0; i < acfg->globals->len; ++i) {
4853                         char *name = g_ptr_array_index (acfg->globals, i);
4854
4855                         sprintf (symbol, "name_%d", i);
4856                         emit_section_change (acfg, ".text", 1);
4857                         emit_label (acfg, symbol);
4858                         emit_string (acfg, name);
4859                 }
4860
4861                 /* Emit the globals table */
4862                 sprintf (symbol, "globals");
4863                 emit_section_change (acfg, ".data", 0);
4864                 /* This is not a global, since it is accessed by the init function */
4865                 emit_alignment (acfg, 8);
4866                 emit_label (acfg, symbol);
4867
4868                 for (i = 0; i < acfg->globals->len; ++i) {
4869                         char *name = g_ptr_array_index (acfg->globals, i);
4870
4871                         sprintf (symbol, "name_%d", i);
4872                         emit_pointer (acfg, symbol);
4873
4874                         sprintf (symbol, "%s", name);
4875                         emit_pointer (acfg, symbol);
4876                 }
4877                 /* Null terminate the table */
4878                 emit_int32 (acfg, 0);
4879                 emit_int32 (acfg, 0);
4880
4881                 /* 
4882                  * Emit a global symbol which can be passed by an embedding app to
4883                  * mono_aot_register_module ().
4884                  */
4885 #if defined(__MACH__)
4886                 sprintf (symbol, "_mono_aot_module_%s_info", acfg->image->assembly->aname.name);
4887 #else
4888                 sprintf (symbol, "mono_aot_module_%s_info", acfg->image->assembly->aname.name);
4889 #endif
4890
4891                 /* Get rid of characters which cannot occur in symbols */
4892                 p = symbol;
4893                 for (p = symbol; *p; ++p) {
4894                         if (!(isalnum (*p) || *p == '_'))
4895                                 *p = '_';
4896                 }
4897                 acfg->static_linking_symbol = g_strdup (symbol);
4898                 emit_global_inner (acfg, symbol, FALSE);
4899                 emit_alignment (acfg, 8);
4900                 emit_label (acfg, symbol);
4901                 emit_pointer (acfg, "globals");
4902         }
4903 }
4904
4905 static void
4906 emit_mem_end (MonoAotCompile *acfg)
4907 {
4908         char symbol [128];
4909
4910         sprintf (symbol, "mem_end");
4911         emit_section_change (acfg, ".text", 1);
4912         emit_global (acfg, symbol, FALSE);
4913         emit_alignment (acfg, 8);
4914         emit_label (acfg, symbol);
4915 }
4916
4917 /*
4918  * Emit a structure containing all the information not stored elsewhere.
4919  */
4920 static void
4921 emit_file_info (MonoAotCompile *acfg)
4922 {
4923         char symbol [128];
4924         int i;
4925
4926         sprintf (symbol, "mono_aot_file_info");
4927         emit_section_change (acfg, ".data", 0);
4928         emit_alignment (acfg, 8);
4929         emit_label (acfg, symbol);
4930         emit_global (acfg, symbol, FALSE);
4931
4932         /* The data emitted here must match MonoAotFileInfo in aot-runtime.c. */
4933         emit_int32 (acfg, acfg->plt_got_offset_base);
4934         emit_int32 (acfg, (int)(acfg->got_offset * sizeof (gpointer)));
4935         emit_int32 (acfg, acfg->plt_offset);
4936         emit_int32 (acfg, acfg->nmethods);
4937
4938         for (i = 0; i < MONO_AOT_TRAMP_NUM; ++i)
4939                 emit_int32 (acfg, acfg->num_trampolines [i]);
4940         for (i = 0; i < MONO_AOT_TRAMP_NUM; ++i)
4941                 emit_int32 (acfg, acfg->trampoline_got_offset_base [i]);
4942         for (i = 0; i < MONO_AOT_TRAMP_NUM; ++i)
4943                 emit_int32 (acfg, acfg->trampoline_size [i]);
4944 }
4945
4946 static void
4947 emit_dwarf_info (MonoAotCompile *acfg)
4948 {
4949 #ifdef EMIT_DWARF_INFO
4950         int i;
4951         char symbol [128], symbol2 [128];
4952
4953         /* DIEs for methods */
4954         for (i = 0; i < acfg->nmethods; ++i) {
4955                 MonoCompile *cfg = acfg->cfgs [i];
4956
4957                 if (!cfg)
4958                         continue;
4959
4960                 sprintf (symbol, "%sm_%x", acfg->temp_prefix, i);
4961                 sprintf (symbol2, "%sme_%x", acfg->temp_prefix, i);
4962
4963                 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 ()));
4964         }
4965 #endif
4966 }
4967
4968 static void
4969 collect_methods (MonoAotCompile *acfg)
4970 {
4971         int i;
4972         MonoImage *image = acfg->image;
4973
4974         /* Collect methods */
4975         for (i = 0; i < image->tables [MONO_TABLE_METHOD].rows; ++i) {
4976                 MonoMethod *method;
4977                 guint32 token = MONO_TOKEN_METHOD_DEF | (i + 1);
4978
4979                 method = mono_get_method (acfg->image, token, NULL);
4980
4981                 if (!method) {
4982                         printf ("Failed to load method 0x%x from '%s'.\n", token, image->name);
4983                         exit (1);
4984                 }
4985                         
4986                 /* Load all methods eagerly to skip the slower lazy loading code */
4987                 mono_class_setup_methods (method->klass);
4988
4989                 if (acfg->aot_opts.full_aot && method->iflags & METHOD_IMPL_ATTRIBUTE_INTERNAL_CALL) {
4990                         /* Compile the wrapper instead */
4991                         /* We do this here instead of add_wrappers () because it is easy to do it here */
4992                         MonoMethod *wrapper = mono_marshal_get_native_wrapper (method, check_for_pending_exc, TRUE);
4993                         method = wrapper;
4994                 }
4995
4996                 /* Since we add the normal methods first, their index will be equal to their zero based token index */
4997                 add_method_with_index (acfg, method, i, FALSE);
4998                 acfg->method_index ++;
4999         }
5000
5001         add_generic_instances (acfg);
5002
5003         if (acfg->aot_opts.full_aot)
5004                 add_wrappers (acfg);
5005 }
5006
5007 static void
5008 compile_methods (MonoAotCompile *acfg)
5009 {
5010         int i, methods_len;
5011
5012         if (acfg->aot_opts.nthreads > 0) {
5013                 GPtrArray *frag;
5014                 int len, j;
5015                 GPtrArray *threads;
5016                 HANDLE handle;
5017                 gpointer *user_data;
5018                 MonoMethod **methods;
5019
5020                 methods_len = acfg->methods->len;
5021
5022                 len = acfg->methods->len / acfg->aot_opts.nthreads;
5023                 g_assert (len > 0);
5024                 /* 
5025                  * Partition the list of methods into fragments, and hand it to threads to
5026                  * process.
5027                  */
5028                 threads = g_ptr_array_new ();
5029                 /* Make a copy since acfg->methods is modified by compile_method () */
5030                 methods = g_new0 (MonoMethod*, methods_len);
5031                 //memcpy (methods, g_ptr_array_index (acfg->methods, 0), sizeof (MonoMethod*) * methods_len);
5032                 for (i = 0; i < methods_len; ++i)
5033                         methods [i] = g_ptr_array_index (acfg->methods, i);
5034                 i = 0;
5035                 while (i < methods_len) {
5036                         frag = g_ptr_array_new ();
5037                         for (j = 0; j < len; ++j) {
5038                                 if (i < methods_len) {
5039                                         g_ptr_array_add (frag, methods [i]);
5040                                         i ++;
5041                                 }
5042                         }
5043
5044                         user_data = g_new0 (gpointer, 3);
5045                         user_data [0] = mono_domain_get ();
5046                         user_data [1] = acfg;
5047                         user_data [2] = frag;
5048                         
5049                         handle = mono_create_thread (NULL, 0, (gpointer)compile_thread_main, user_data, 0, NULL);
5050                         g_ptr_array_add (threads, handle);
5051                 }
5052                 g_free (methods);
5053
5054                 for (i = 0; i < threads->len; ++i) {
5055                         WaitForSingleObjectEx (g_ptr_array_index (threads, i), INFINITE, FALSE);
5056                 }
5057         } else {
5058                 methods_len = 0;
5059         }
5060
5061         /* Compile methods added by compile_method () or all methods if nthreads == 0 */
5062         for (i = methods_len; i < acfg->methods->len; ++i) {
5063                 /* This can new methods to acfg->methods */
5064                 compile_method (acfg, g_ptr_array_index (acfg->methods, i));
5065         }
5066 }
5067
5068 static int
5069 compile_asm (MonoAotCompile *acfg)
5070 {
5071         char *command, *objfile;
5072         char *outfile_name, *tmp_outfile_name;
5073         const char *tool_prefix = acfg->aot_opts.tool_prefix ? acfg->aot_opts.tool_prefix : "";
5074
5075 #if defined(TARGET_AMD64)
5076 #define AS_OPTIONS "--64"
5077 #elif defined(TARGET_POWERPC64)
5078 #define AS_OPTIONS "-a64 -mppc64"
5079 #define LD_OPTIONS "-m elf64ppc"
5080 #elif defined(sparc) && SIZEOF_VOID_P == 8
5081 #define AS_OPTIONS "-xarch=v9"
5082 #else
5083 #define AS_OPTIONS ""
5084 #endif
5085
5086 #ifndef LD_OPTIONS
5087 #define LD_OPTIONS ""
5088 #endif
5089
5090         if (acfg->aot_opts.asm_only) {
5091                 printf ("Output file: '%s'.\n", acfg->tmpfname);
5092                 if (acfg->aot_opts.static_link)
5093                         printf ("Linking symbol: '%s'.\n", acfg->static_linking_symbol);
5094                 return 0;
5095         }
5096
5097         if (acfg->aot_opts.static_link) {
5098                 if (acfg->aot_opts.outfile)
5099                         objfile = g_strdup_printf ("%s", acfg->aot_opts.outfile);
5100                 else
5101                         objfile = g_strdup_printf ("%s.o", acfg->image->name);
5102         } else {
5103                 objfile = g_strdup_printf ("%s.o", acfg->tmpfname);
5104         }
5105         command = g_strdup_printf ("%sas %s %s -o %s", tool_prefix, AS_OPTIONS, acfg->tmpfname, objfile);
5106         printf ("Executing the native assembler: %s\n", command);
5107         if (system (command) != 0) {
5108                 g_free (command);
5109                 g_free (objfile);
5110                 return 1;
5111         }
5112
5113         g_free (command);
5114
5115         if (acfg->aot_opts.static_link) {
5116                 printf ("Output file: '%s'.\n", objfile);
5117                 printf ("Linking symbol: '%s'.\n", acfg->static_linking_symbol);
5118                 g_free (objfile);
5119                 return 0;
5120         }
5121
5122         if (acfg->aot_opts.outfile)
5123                 outfile_name = g_strdup_printf ("%s", acfg->aot_opts.outfile);
5124         else
5125                 outfile_name = g_strdup_printf ("%s%s", acfg->image->name, SHARED_EXT);
5126
5127         tmp_outfile_name = g_strdup_printf ("%s.tmp", outfile_name);
5128
5129 #if defined(sparc)
5130         command = g_strdup_printf ("ld -shared -G -o %s %s.o", tmp_outfile_name, acfg->tmpfname);
5131 #elif defined(__ppc__) && defined(__MACH__)
5132         command = g_strdup_printf ("gcc -dynamiclib -o %s %s.o", tmp_outfile_name, acfg->tmpfname);
5133 #elif defined(PLATFORM_WIN32)
5134         command = g_strdup_printf ("gcc -shared --dll -mno-cygwin -o %s %s.o", tmp_outfile_name, acfg->tmpfname);
5135 #else
5136         command = g_strdup_printf ("%sld %s -shared -o %s %s.o", tool_prefix, LD_OPTIONS, tmp_outfile_name, acfg->tmpfname);
5137 #endif
5138         printf ("Executing the native linker: %s\n", command);
5139         if (system (command) != 0) {
5140                 g_free (tmp_outfile_name);
5141                 g_free (outfile_name);
5142                 g_free (command);
5143                 g_free (objfile);
5144                 return 1;
5145         }
5146
5147         g_free (command);
5148         unlink (objfile);
5149         /*com = g_strdup_printf ("strip --strip-unneeded %s%s", acfg->image->name, SHARED_EXT);
5150         printf ("Stripping the binary: %s\n", com);
5151         system (com);
5152         g_free (com);*/
5153
5154 #if defined(TARGET_ARM) && !defined(__MACH__)
5155         /* 
5156          * gas generates 'mapping symbols' each time code and data is mixed, which 
5157          * happens a lot in emit_and_reloc_code (), so we need to get rid of them.
5158          */
5159         command = g_strdup_printf ("%sstrip --strip-symbol=\\$a --strip-symbol=\\$d %s", tool_prefix, tmp_outfile_name);
5160         printf ("Stripping the binary: %s\n", command);
5161         if (system (command) != 0) {
5162                 g_free (tmp_outfile_name);
5163                 g_free (outfile_name);
5164                 g_free (command);
5165                 g_free (objfile);
5166                 return 1;
5167         }
5168 #endif
5169
5170         rename (tmp_outfile_name, outfile_name);
5171
5172         g_free (tmp_outfile_name);
5173         g_free (outfile_name);
5174         g_free (objfile);
5175
5176         if (acfg->aot_opts.save_temps)
5177                 printf ("Retained input file.\n");
5178         else
5179                 unlink (acfg->tmpfname);
5180
5181         return 0;
5182 }
5183
5184 static MonoAotCompile*
5185 acfg_create (MonoAssembly *ass, guint32 opts)
5186 {
5187         MonoImage *image = ass->image;
5188         MonoAotCompile *acfg;
5189
5190         acfg = g_new0 (MonoAotCompile, 1);
5191         acfg->methods = g_ptr_array_new ();
5192         acfg->method_indexes = g_hash_table_new (NULL, NULL);
5193         acfg->plt_offset_to_patch = g_hash_table_new (NULL, NULL);
5194         acfg->patch_to_plt_offset = g_hash_table_new (mono_patch_info_hash, mono_patch_info_equal);
5195         acfg->patch_to_got_offset = g_hash_table_new (mono_patch_info_hash, mono_patch_info_equal);
5196         acfg->got_patches = g_ptr_array_new ();
5197         acfg->method_to_cfg = g_hash_table_new (NULL, NULL);
5198         acfg->token_info_hash = g_hash_table_new_full (NULL, NULL, NULL, g_free);
5199         acfg->image_hash = g_hash_table_new (NULL, NULL);
5200         acfg->image_table = g_ptr_array_new ();
5201         acfg->globals = g_ptr_array_new ();
5202         acfg->image = image;
5203         acfg->opts = opts;
5204         acfg->mempool = mono_mempool_new ();
5205         acfg->extra_methods = g_ptr_array_new ();
5206         acfg->unwind_info_offsets = g_hash_table_new (NULL, NULL);
5207         acfg->unwind_ops = g_ptr_array_new ();
5208         acfg->method_label_hash = g_hash_table_new_full (g_str_hash, g_str_equal, g_free, NULL);
5209         InitializeCriticalSection (&acfg->mutex);
5210
5211         return acfg;
5212 }
5213
5214 static void
5215 acfg_free (MonoAotCompile *acfg)
5216 {
5217         int i;
5218
5219         img_writer_destroy (acfg->w);
5220         for (i = 0; i < acfg->nmethods; ++i)
5221                 if (acfg->cfgs [i])
5222                         g_free (acfg->cfgs [i]);
5223         g_free (acfg->cfgs);
5224         g_free (acfg->static_linking_symbol);
5225         g_free (acfg->got_symbol);
5226         g_free (acfg->plt_symbol);
5227         g_ptr_array_free (acfg->methods, TRUE);
5228         g_ptr_array_free (acfg->got_patches, TRUE);
5229         g_ptr_array_free (acfg->image_table, TRUE);
5230         g_ptr_array_free (acfg->globals, TRUE);
5231         g_ptr_array_free (acfg->unwind_ops, TRUE);
5232         g_hash_table_destroy (acfg->method_indexes);
5233         g_hash_table_destroy (acfg->plt_offset_to_patch);
5234         g_hash_table_destroy (acfg->patch_to_plt_offset);
5235         g_hash_table_destroy (acfg->patch_to_got_offset);
5236         g_hash_table_destroy (acfg->method_to_cfg);
5237         g_hash_table_destroy (acfg->token_info_hash);
5238         g_hash_table_destroy (acfg->image_hash);
5239         g_hash_table_destroy (acfg->unwind_info_offsets);
5240         g_hash_table_destroy (acfg->method_label_hash);
5241         mono_mempool_destroy (acfg->mempool);
5242         g_free (acfg);
5243 }
5244
5245 int
5246 mono_compile_assembly (MonoAssembly *ass, guint32 opts, const char *aot_options)
5247 {
5248         MonoImage *image = ass->image;
5249         int res;
5250         MonoAotCompile *acfg;
5251         char *outfile_name, *tmp_outfile_name, *p;
5252         TV_DECLARE (atv);
5253         TV_DECLARE (btv);
5254
5255         printf ("Mono Ahead of Time compiler - compiling assembly %s\n", image->name);
5256
5257         acfg = acfg_create (ass, opts);
5258
5259         memset (&acfg->aot_opts, 0, sizeof (acfg->aot_opts));
5260         acfg->aot_opts.write_symbols = TRUE;
5261         acfg->aot_opts.ntrampolines = 1024;
5262
5263         mono_aot_parse_options (aot_options, &acfg->aot_opts);
5264
5265         //acfg->aot_opts.print_skipped_methods = TRUE;
5266
5267 #ifndef MONO_ARCH_HAVE_FULL_AOT_TRAMPOLINES
5268         if (acfg->aot_opts.full_aot) {
5269                 printf ("--aot=full is not supported on this platform.\n");
5270                 return 1;
5271         }
5272 #endif
5273
5274         if (acfg->aot_opts.static_link)
5275                 acfg->aot_opts.asm_writer = TRUE;
5276
5277         load_profile_files (acfg);
5278
5279         acfg->num_trampolines [MONO_AOT_TRAMP_SPECIFIC] = acfg->aot_opts.full_aot ? acfg->aot_opts.ntrampolines : 0;
5280 #ifdef MONO_ARCH_HAVE_STATIC_RGCTX_TRAMPOLINE
5281         acfg->num_trampolines [MONO_AOT_TRAMP_STATIC_RGCTX] = acfg->aot_opts.full_aot ? 1024 : 0;
5282 #endif
5283         acfg->num_trampolines [MONO_AOT_TRAMP_IMT_THUNK] = acfg->aot_opts.full_aot ? 128 : 0;
5284
5285         acfg->got_symbol = g_strdup_printf ("mono_aot_%s_got", acfg->image->assembly->aname.name);
5286         acfg->plt_symbol = g_strdup_printf ("mono_aot_%s_plt", acfg->image->assembly->aname.name);
5287
5288         /* Get rid of characters which cannot occur in symbols */
5289         for (p = acfg->got_symbol; *p; ++p) {
5290                 if (!(isalnum (*p) || *p == '_'))
5291                         *p = '_';
5292         }
5293         for (p = acfg->plt_symbol; *p; ++p) {
5294                 if (!(isalnum (*p) || *p == '_'))
5295                         *p = '_';
5296         }
5297
5298         acfg->method_index = 1;
5299
5300         collect_methods (acfg);
5301
5302         acfg->cfgs_size = acfg->methods->len + 32;
5303         acfg->cfgs = g_new0 (MonoCompile*, acfg->cfgs_size);
5304
5305         /* PLT offset 0 is reserved for the PLT trampoline */
5306         acfg->plt_offset = 1;
5307
5308         /* GOT offset 0 is reserved for the address of the current assembly */
5309         {
5310                 MonoJumpInfo *ji;
5311
5312                 ji = mono_mempool_alloc0 (acfg->mempool, sizeof (MonoAotCompile));
5313                 ji->type = MONO_PATCH_INFO_IMAGE;
5314                 ji->data.image = acfg->image;
5315
5316                 get_got_offset (acfg, ji);
5317
5318                 /* Slot 1 is reserved for the mscorlib got addr */
5319                 ji = mono_mempool_alloc0 (acfg->mempool, sizeof (MonoAotCompile));
5320                 ji->type = MONO_PATCH_INFO_MSCORLIB_GOT_ADDR;
5321                 get_got_offset (acfg, ji);
5322         }
5323
5324         TV_GETTIME (atv);
5325
5326         compile_methods (acfg);
5327
5328         TV_GETTIME (btv);
5329
5330         acfg->stats.jit_time = TV_ELAPSED (atv, btv);
5331
5332         TV_GETTIME (atv);
5333
5334         if (!acfg->aot_opts.asm_only && !acfg->aot_opts.asm_writer && bin_writer_supported ()) {
5335                 if (acfg->aot_opts.outfile)
5336                         outfile_name = g_strdup_printf ("%s", acfg->aot_opts.outfile);
5337                 else
5338                         outfile_name = g_strdup_printf ("%s%s", acfg->image->name, SHARED_EXT);
5339
5340                 /* 
5341                  * Can't use g_file_open_tmp () as it will be deleted at exit, and
5342                  * it might be in another file system so the rename () won't work.
5343                  */
5344                 tmp_outfile_name = g_strdup_printf ("%s.tmp", outfile_name);
5345
5346                 acfg->fp = fopen (tmp_outfile_name, "w");
5347                 if (!acfg->fp) {
5348                         printf ("Unable to create temporary file '%s': %s\n", tmp_outfile_name, strerror (errno));
5349                         return 1;
5350                 }
5351
5352                 acfg->w = img_writer_create (acfg->fp, TRUE);
5353                 acfg->use_bin_writer = TRUE;
5354         } else {
5355                 if (acfg->aot_opts.asm_only) {
5356                         if (acfg->aot_opts.outfile)
5357                                 acfg->tmpfname = g_strdup_printf ("%s", acfg->aot_opts.outfile);
5358                         else
5359                                 acfg->tmpfname = g_strdup_printf ("%s.s", acfg->image->name);
5360                         acfg->fp = fopen (acfg->tmpfname, "w+");
5361                 } else {
5362                         int i = g_file_open_tmp ("mono_aot_XXXXXX", &acfg->tmpfname, NULL);
5363                         acfg->fp = fdopen (i, "w+");
5364                 }
5365                 g_assert (acfg->fp);
5366
5367                 acfg->w = img_writer_create (acfg->fp, FALSE);
5368                 
5369                 tmp_outfile_name = NULL;
5370                 outfile_name = NULL;
5371         }
5372
5373         acfg->temp_prefix = img_writer_get_temp_label_prefix (acfg->w);
5374
5375         if (!acfg->aot_opts.nodebug)
5376                 acfg->dwarf = mono_dwarf_writer_create (acfg->w, NULL, FALSE);
5377
5378         img_writer_emit_start (acfg->w);
5379
5380         if (acfg->dwarf)
5381                 mono_dwarf_writer_emit_base_info (acfg->dwarf, arch_get_cie_program ());
5382
5383         emit_code (acfg);
5384
5385         emit_info (acfg);
5386
5387         emit_extra_methods (acfg);
5388
5389         emit_method_order (acfg);
5390
5391         emit_trampolines (acfg);
5392
5393         emit_class_name_table (acfg);
5394
5395         emit_got_info (acfg);
5396
5397         emit_exception_info (acfg);
5398
5399         emit_unwind_info (acfg);
5400
5401         emit_class_info (acfg);
5402
5403         emit_plt (acfg);
5404
5405         emit_image_table (acfg);
5406
5407         emit_got (acfg);
5408
5409         emit_file_info (acfg);
5410
5411         emit_globals (acfg);
5412
5413         if (acfg->dwarf) {
5414                 emit_dwarf_info (acfg);
5415                 mono_dwarf_writer_close (acfg->dwarf);
5416         }
5417
5418         emit_mem_end (acfg);
5419
5420         TV_GETTIME (btv);
5421
5422         acfg->stats.gen_time = TV_ELAPSED (atv, btv);
5423
5424         printf ("Code: %d Info: %d Ex Info: %d Unwind Info: %d Class Info: %d PLT: %d GOT Info: %d GOT Info Offsets: %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, acfg->stats.got_info_offsets_size, (int)(acfg->got_offset * sizeof (gpointer)), (int)(acfg->nmethods * 3 * sizeof (gpointer)));
5425
5426         TV_GETTIME (atv);
5427         res = img_writer_emit_writeout (acfg->w);
5428         if (res != 0) {
5429                 acfg_free (acfg);
5430                 return res;
5431         }
5432         if (acfg->use_bin_writer) {
5433                 int err = rename (tmp_outfile_name, outfile_name);
5434
5435                 if (err) {
5436                         printf ("Unable to rename '%s' to '%s': %s\n", tmp_outfile_name, outfile_name, strerror (errno));
5437                         return 1;
5438                 }
5439         } else {
5440                 res = compile_asm (acfg);
5441                 if (res != 0) {
5442                         acfg_free (acfg);
5443                         return res;
5444                 }
5445         }
5446         TV_GETTIME (btv);
5447         acfg->stats.link_time = TV_ELAPSED (atv, btv);
5448
5449         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);
5450         if (acfg->stats.genericcount)
5451                 printf ("%d methods are generic (%d%%)\n", acfg->stats.genericcount, acfg->stats.mcount ? (acfg->stats.genericcount * 100) / acfg->stats.mcount : 100);
5452         if (acfg->stats.abscount)
5453                 printf ("%d methods contain absolute addresses (%d%%)\n", acfg->stats.abscount, acfg->stats.mcount ? (acfg->stats.abscount * 100) / acfg->stats.mcount : 100);
5454         if (acfg->stats.lmfcount)
5455                 printf ("%d methods contain lmf pointers (%d%%)\n", acfg->stats.lmfcount, acfg->stats.mcount ? (acfg->stats.lmfcount * 100) / acfg->stats.mcount : 100);
5456         if (acfg->stats.ocount)
5457                 printf ("%d methods have other problems (%d%%)\n", acfg->stats.ocount, acfg->stats.mcount ? (acfg->stats.ocount * 100) / acfg->stats.mcount : 100);
5458         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);
5459         printf ("Direct calls: %d (%d%%)\n", acfg->stats.direct_calls, acfg->stats.all_calls ? (acfg->stats.direct_calls * 100) / acfg->stats.all_calls : 100);
5460
5461         /*
5462         printf ("GOT slot distribution:\n");
5463         for (i = 0; i < MONO_PATCH_INFO_NONE; ++i)
5464                 if (acfg->stats.got_slot_types [i])
5465                         printf ("\t%s: %d\n", get_patch_name (i), acfg->stats.got_slot_types [i]);
5466         */
5467
5468         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);
5469
5470         acfg_free (acfg);
5471         
5472         return 0;
5473 }
5474  
5475 /*
5476  * Support for emitting debug info for JITted code.
5477  *
5478  *   This works as follows:
5479  * - the runtime writes out an xdb.s file containing DWARF debug info.
5480  * - the user calls a gdb macro
5481  * - the macro compiles and loads this shared library using add-symbol-file.
5482  *
5483  * This is based on the xdebug functionality in the Kaffe Java VM.
5484  * 
5485  * We emit assembly code instead of using the ELF writer, so we can emit debug info
5486  * incrementally as each method is JITted, and the debugger doesn't have to call
5487  * into the runtime to emit the shared library, which would cause all kinds of
5488  * complications, like threading issues, and the fact that the ELF writer's
5489  * emit_writeout () function cannot be called more than once.
5490  */
5491
5492 /* The recommended gdb macro is: */
5493 /*
5494   define xdb
5495   shell rm -f xdb.so && as --64 -o xdb.o xdb.s && ld -shared -o xdb.so xdb.o
5496   add-symbol-file xdb.so 0
5497   end
5498 */
5499
5500 static MonoDwarfWriter *xdebug_writer;
5501 static FILE *xdebug_fp;
5502
5503 void
5504 mono_xdebug_init (void)
5505 {
5506         FILE *il_file;
5507         MonoImageWriter *w;
5508
5509         unlink ("xdb.s");
5510         xdebug_fp = fopen ("xdb.s", "w");
5511
5512         w = img_writer_create (xdebug_fp, FALSE);
5513
5514         img_writer_emit_start (w);
5515
5516         /* This file will contain the IL code for methods which don't have debug info */
5517         il_file = fopen ("xdb.il", "w");
5518
5519         xdebug_writer = mono_dwarf_writer_create (w, il_file, TRUE);
5520
5521         /* Emit something so the file has a text segment */
5522         img_writer_emit_section_change (w, ".text", 0);
5523         img_writer_emit_string (w, "");
5524
5525         mono_dwarf_writer_emit_base_info (xdebug_writer, arch_get_cie_program ());
5526 }
5527
5528 /*
5529  * mono_save_xdebug_info:
5530  *
5531  *   Emit debugging info for METHOD into an assembly file which can be assembled
5532  * and loaded into gdb to provide debugging info for JITted code.
5533  * LOCKING: Acquires the loader lock.
5534  */
5535 void
5536 mono_save_xdebug_info (MonoCompile *cfg)
5537 {
5538         if (!xdebug_writer)
5539                 return;
5540
5541         mono_loader_lock ();
5542         mono_dwarf_writer_emit_method (xdebug_writer, cfg, cfg->jit_info->method, NULL, NULL, 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 ()));
5543         fflush (xdebug_fp);
5544         mono_loader_unlock ();
5545 }
5546
5547 /*
5548  * mono_save_trampoline_xdebug_info:
5549  *
5550  *   Same as mono_save_xdebug_info, but for trampolines.
5551  * LOCKING: Acquires the loader lock.
5552  */
5553 void
5554 mono_save_trampoline_xdebug_info (const char *tramp_name, guint8 *code, guint32 code_size, GSList *unwind_info)
5555 {
5556         if (!xdebug_writer)
5557                 return;
5558
5559         mono_loader_lock ();
5560         mono_dwarf_writer_emit_trampoline (xdebug_writer, tramp_name, NULL, NULL, code, code_size, unwind_info);
5561         fflush (xdebug_fp);
5562         mono_loader_unlock ();
5563 }
5564
5565 #else
5566
5567 /* AOT disabled */
5568
5569 int
5570 mono_compile_assembly (MonoAssembly *ass, guint32 opts, const char *aot_options)
5571 {
5572         return 0;
5573 }
5574
5575 void
5576 mono_xdebug_init (void)
5577 {
5578 }
5579
5580 void
5581 mono_save_xdebug_info (MonoCompile *cfg)
5582 {
5583 }
5584
5585 void
5586 mono_save_trampoline_xdebug_info (const char *tramp_name, guint8 *code, guint32 code_size, GSList *unwind_info)
5587 {
5588 }
5589
5590 #endif