2009-09-24 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 gboolean
1712 can_marshal_struct (MonoClass *klass)
1713 {
1714         MonoClassField *field;
1715         gboolean can_marshal = TRUE;
1716         gpointer iter = NULL;
1717
1718         /* Only allow a few field types to avoid asserts in the marshalling code */
1719         while ((field = mono_class_get_fields (klass, &iter))) {
1720                 if ((field->type->attrs & FIELD_ATTRIBUTE_STATIC))
1721                         continue;
1722
1723                 switch (field->type->type) {
1724                 case MONO_TYPE_I4:
1725                 case MONO_TYPE_U4:
1726                 case MONO_TYPE_I1:
1727                 case MONO_TYPE_U1:
1728                 case MONO_TYPE_BOOLEAN:
1729                 case MONO_TYPE_I2:
1730                 case MONO_TYPE_U2:
1731                 case MONO_TYPE_CHAR:
1732                 case MONO_TYPE_I8:
1733                 case MONO_TYPE_U8:
1734                 case MONO_TYPE_I:
1735                 case MONO_TYPE_U:
1736                 case MONO_TYPE_PTR:
1737                 case MONO_TYPE_R4:
1738                 case MONO_TYPE_R8:
1739                 case MONO_TYPE_STRING:
1740                         break;
1741                 case MONO_TYPE_VALUETYPE:
1742                         if (!can_marshal_struct (mono_class_from_mono_type (field->type)))
1743                                 can_marshal = FALSE;
1744                         break;
1745                 default:
1746                         can_marshal = FALSE;
1747                         break;
1748                 }
1749         }
1750
1751         return can_marshal;
1752 }
1753
1754 static void
1755 add_wrappers (MonoAotCompile *acfg)
1756 {
1757         MonoMethod *method, *m;
1758         int i, j;
1759         MonoMethodSignature *sig, *csig;
1760         guint32 token;
1761
1762         /* 
1763          * FIXME: Instead of AOTing all the wrappers, it might be better to redesign them
1764          * so there is only one wrapper of a given type, or inlining their contents into their
1765          * callers.
1766          */
1767
1768         /* 
1769          * FIXME: This depends on the fact that different wrappers have different 
1770          * names.
1771          */
1772
1773         for (i = 0; i < acfg->image->tables [MONO_TABLE_METHOD].rows; ++i) {
1774                 MonoMethod *method;
1775                 guint32 token = MONO_TOKEN_METHOD_DEF | (i + 1);
1776                 gboolean skip = FALSE;
1777
1778                 method = mono_get_method (acfg->image, token, NULL);
1779
1780                 if ((method->flags & METHOD_ATTRIBUTE_PINVOKE_IMPL) ||
1781                         (method->iflags & METHOD_IMPL_ATTRIBUTE_RUNTIME) ||
1782                         (method->flags & METHOD_ATTRIBUTE_ABSTRACT))
1783                         skip = TRUE;
1784
1785                 if (method->is_generic || method->klass->generic_container)
1786                         skip = TRUE;
1787
1788                 /* Skip methods which can not be handled by get_runtime_invoke () */
1789                 sig = mono_method_signature (method);
1790                 if ((sig->ret->type == MONO_TYPE_PTR) ||
1791                         (sig->ret->type == MONO_TYPE_TYPEDBYREF))
1792                         skip = TRUE;
1793
1794                 for (j = 0; j < sig->param_count; j++) {
1795                         if (sig->params [j]->type == MONO_TYPE_TYPEDBYREF)
1796                                 skip = TRUE;
1797                 }
1798
1799 #ifdef MONO_ARCH_DYN_CALL_SUPPORTED
1800                 if (!method->klass->contextbound) {
1801                         MonoDynCallInfo *info = mono_arch_dyn_call_prepare (sig);
1802
1803                         if (info) {
1804                                 /* Supported by the dynamic runtime-invoke wrapper */
1805                                 skip = TRUE;
1806                                 g_free (info);
1807                         }
1808                 }
1809 #endif
1810
1811                 if (!skip) {
1812                         //printf ("%s\n", mono_method_full_name (method, TRUE));
1813                         add_method (acfg, mono_marshal_get_runtime_invoke (method, FALSE));
1814                 }
1815         }
1816
1817         if (strcmp (acfg->image->assembly->aname.name, "mscorlib") == 0) {
1818 #ifdef MONO_ARCH_HAVE_TLS_GET
1819                 MonoMethodDesc *desc;
1820                 MonoMethod *orig_method;
1821                 int nallocators;
1822 #endif
1823
1824                 /* Runtime invoke wrappers */
1825
1826                 /* void runtime-invoke () [.cctor] */
1827                 csig = mono_metadata_signature_alloc (mono_defaults.corlib, 0);
1828                 csig->ret = &mono_defaults.void_class->byval_arg;
1829                 add_method (acfg, get_runtime_invoke_sig (csig));
1830
1831                 /* void runtime-invoke () [Finalize] */
1832                 csig = mono_metadata_signature_alloc (mono_defaults.corlib, 0);
1833                 csig->hasthis = 1;
1834                 csig->ret = &mono_defaults.void_class->byval_arg;
1835                 add_method (acfg, get_runtime_invoke_sig (csig));
1836
1837                 /* void runtime-invoke (string) [exception ctor] */
1838                 csig = mono_metadata_signature_alloc (mono_defaults.corlib, 1);
1839                 csig->hasthis = 1;
1840                 csig->ret = &mono_defaults.void_class->byval_arg;
1841                 csig->params [0] = &mono_defaults.string_class->byval_arg;
1842                 add_method (acfg, get_runtime_invoke_sig (csig));
1843
1844                 /* void runtime-invoke (string, string) [exception ctor] */
1845                 csig = mono_metadata_signature_alloc (mono_defaults.corlib, 2);
1846                 csig->hasthis = 1;
1847                 csig->ret = &mono_defaults.void_class->byval_arg;
1848                 csig->params [0] = &mono_defaults.string_class->byval_arg;
1849                 csig->params [1] = &mono_defaults.string_class->byval_arg;
1850                 add_method (acfg, get_runtime_invoke_sig (csig));
1851
1852                 /* string runtime-invoke () [Exception.ToString ()] */
1853                 csig = mono_metadata_signature_alloc (mono_defaults.corlib, 0);
1854                 csig->hasthis = 1;
1855                 csig->ret = &mono_defaults.string_class->byval_arg;
1856                 add_method (acfg, get_runtime_invoke_sig (csig));
1857
1858                 /* void runtime-invoke (string, Exception) [exception ctor] */
1859                 csig = mono_metadata_signature_alloc (mono_defaults.corlib, 2);
1860                 csig->hasthis = 1;
1861                 csig->ret = &mono_defaults.void_class->byval_arg;
1862                 csig->params [0] = &mono_defaults.string_class->byval_arg;
1863                 csig->params [1] = &mono_defaults.exception_class->byval_arg;
1864                 add_method (acfg, get_runtime_invoke_sig (csig));
1865
1866                 /* Assembly runtime-invoke (string, bool) [DoAssemblyResolve] */
1867                 csig = mono_metadata_signature_alloc (mono_defaults.corlib, 2);
1868                 csig->hasthis = 1;
1869                 csig->ret = &(mono_class_from_name (
1870                                                                                         mono_defaults.corlib, "System.Reflection", "Assembly"))->byval_arg;
1871                 csig->params [0] = &mono_defaults.string_class->byval_arg;
1872                 csig->params [1] = &mono_defaults.boolean_class->byval_arg;
1873                 add_method (acfg, get_runtime_invoke_sig (csig));
1874
1875                 /* runtime-invoke used by finalizers */
1876                 add_method (acfg, mono_marshal_get_runtime_invoke (mono_class_get_method_from_name_flags (mono_defaults.object_class, "Finalize", 0, 0), TRUE));
1877
1878 #ifdef MONO_ARCH_DYN_CALL_SUPPORTED
1879                 add_method (acfg, mono_marshal_get_runtime_invoke_dynamic ());
1880 #endif
1881
1882                 /* JIT icall wrappers */
1883                 /* FIXME: locking */
1884                 g_hash_table_foreach (mono_get_jit_icall_info (), add_jit_icall_wrapper, acfg);
1885
1886                 /* stelemref */
1887                 add_method (acfg, mono_marshal_get_stelemref ());
1888
1889 #ifdef MONO_ARCH_HAVE_TLS_GET
1890                 /* Managed Allocators */
1891                 nallocators = mono_gc_get_managed_allocator_types ();
1892                 for (i = 0; i < nallocators; ++i) {
1893                         m = mono_gc_get_managed_allocator_by_type (i);
1894                         if (m)
1895                                 add_method (acfg, m);
1896                 }
1897
1898                 /* Monitor Enter/Exit */
1899                 desc = mono_method_desc_new ("Monitor:Enter", FALSE);
1900                 orig_method = mono_method_desc_search_in_class (desc, mono_defaults.monitor_class);
1901                 g_assert (orig_method);
1902                 mono_method_desc_free (desc);
1903                 method = mono_monitor_get_fast_path (orig_method);
1904                 if (method)
1905                         add_method (acfg, method);
1906
1907                 desc = mono_method_desc_new ("Monitor:Exit", FALSE);
1908                 orig_method = mono_method_desc_search_in_class (desc, mono_defaults.monitor_class);
1909                 g_assert (orig_method);
1910                 mono_method_desc_free (desc);
1911                 method = mono_monitor_get_fast_path (orig_method);
1912                 if (method)
1913                         add_method (acfg, method);
1914 #endif
1915         }
1916
1917         /* 
1918          * remoting-invoke-with-check wrappers are very frequent, so avoid emitting them,
1919          * we use the original method instead at runtime.
1920          * Since full-aot doesn't support remoting, this is not a problem.
1921          */
1922 #if 0
1923         /* remoting-invoke wrappers */
1924         for (i = 0; i < acfg->image->tables [MONO_TABLE_METHOD].rows; ++i) {
1925                 MonoMethodSignature *sig;
1926                 
1927                 token = MONO_TOKEN_METHOD_DEF | (i + 1);
1928                 method = mono_get_method (acfg->image, token, NULL);
1929
1930                 sig = mono_method_signature (method);
1931
1932                 if (sig->hasthis && (method->klass->marshalbyref || method->klass == mono_defaults.object_class)) {
1933                         m = mono_marshal_get_remoting_invoke_with_check (method);
1934
1935                         add_method (acfg, m);
1936                 }
1937         }
1938 #endif
1939
1940         /* delegate-invoke wrappers */
1941         for (i = 0; i < acfg->image->tables [MONO_TABLE_TYPEDEF].rows; ++i) {
1942                 MonoClass *klass;
1943                 
1944                 token = MONO_TOKEN_TYPE_DEF | (i + 1);
1945                 klass = mono_class_get (acfg->image, token);
1946
1947                 if (klass->delegate && klass != mono_defaults.delegate_class && klass != mono_defaults.multicastdelegate_class && !klass->generic_container) {
1948                         method = mono_get_delegate_invoke (klass);
1949
1950                         m = mono_marshal_get_delegate_invoke (method, NULL);
1951
1952                         add_method (acfg, m);
1953
1954                         method = mono_class_get_method_from_name_flags (klass, "BeginInvoke", -1, 0);
1955                         add_method (acfg, mono_marshal_get_delegate_begin_invoke (method));
1956
1957                         method = mono_class_get_method_from_name_flags (klass, "EndInvoke", -1, 0);
1958                         add_method (acfg, mono_marshal_get_delegate_end_invoke (method));
1959                 }
1960         }
1961
1962         /* Synchronized wrappers */
1963         for (i = 0; i < acfg->image->tables [MONO_TABLE_METHOD].rows; ++i) {
1964                 token = MONO_TOKEN_METHOD_DEF | (i + 1);
1965                 method = mono_get_method (acfg->image, token, NULL);
1966
1967                 if (method->iflags & METHOD_IMPL_ATTRIBUTE_SYNCHRONIZED)
1968                         add_method (acfg, mono_marshal_get_synchronized_wrapper (method));
1969         }
1970
1971         /* pinvoke wrappers */
1972         for (i = 0; i < acfg->image->tables [MONO_TABLE_METHOD].rows; ++i) {
1973                 MonoMethod *method;
1974                 guint32 token = MONO_TOKEN_METHOD_DEF | (i + 1);
1975
1976                 method = mono_get_method (acfg->image, token, NULL);
1977
1978                 if ((method->flags & METHOD_ATTRIBUTE_PINVOKE_IMPL) ||
1979                         (method->iflags & METHOD_IMPL_ATTRIBUTE_INTERNAL_CALL)) {
1980                         add_method (acfg, mono_marshal_get_native_wrapper (method, TRUE, TRUE));
1981                 }
1982         }
1983
1984         /* StructureToPtr/PtrToStructure wrappers */
1985         for (i = 0; i < acfg->image->tables [MONO_TABLE_TYPEDEF].rows; ++i) {
1986                 MonoClass *klass;
1987                 
1988                 token = MONO_TOKEN_TYPE_DEF | (i + 1);
1989                 klass = mono_class_get (acfg->image, token);
1990
1991                 if (klass->valuetype && !klass->generic_container && ((klass->flags & TYPE_ATTRIBUTE_LAYOUT_MASK) != TYPE_ATTRIBUTE_AUTO_LAYOUT) && can_marshal_struct (klass)) {
1992                         add_method (acfg, mono_marshal_get_struct_to_ptr (klass));
1993                         add_method (acfg, mono_marshal_get_ptr_to_struct (klass));
1994                 }
1995         }
1996 }
1997
1998 static gboolean
1999 has_type_vars (MonoClass *klass)
2000 {
2001         if ((klass->byval_arg.type == MONO_TYPE_VAR) || (klass->byval_arg.type == MONO_TYPE_MVAR))
2002                 return TRUE;
2003         if (klass->rank)
2004                 return has_type_vars (klass->element_class);
2005         if (klass->generic_class) {
2006                 MonoGenericContext *context = &klass->generic_class->context;
2007                 if (context->class_inst) {
2008                         int i;
2009
2010                         for (i = 0; i < context->class_inst->type_argc; ++i)
2011                                 if (has_type_vars (mono_class_from_mono_type (context->class_inst->type_argv [i])))
2012                                         return TRUE;
2013                 }
2014         }
2015         return FALSE;
2016 }
2017
2018 static gboolean
2019 method_has_type_vars (MonoMethod *method)
2020 {
2021         if (has_type_vars (method->klass))
2022                 return TRUE;
2023
2024         if (method->is_inflated) {
2025                 MonoGenericContext *context = mono_method_get_context (method);
2026                 if (context->method_inst) {
2027                         int i;
2028
2029                         for (i = 0; i < context->method_inst->type_argc; ++i)
2030                                 if (has_type_vars (mono_class_from_mono_type (context->method_inst->type_argv [i])))
2031                                         return TRUE;
2032                 }
2033         }
2034         return FALSE;
2035 }
2036
2037 /*
2038  * add_generic_class:
2039  *
2040  *   Add all methods of a generic class.
2041  */
2042 static void
2043 add_generic_class (MonoAotCompile *acfg, MonoClass *klass)
2044 {
2045         MonoMethod *method;
2046         gpointer iter;
2047
2048         mono_class_init (klass);
2049
2050         if (klass->generic_class && klass->generic_class->context.class_inst->is_open)
2051                 return;
2052
2053         if (has_type_vars (klass))
2054                 return;
2055
2056         if (!klass->generic_class && !klass->rank)
2057                 return;
2058
2059         iter = NULL;
2060         while ((method = mono_class_get_methods (klass, &iter))) {
2061                 if (mono_method_is_generic_sharable_impl (method, FALSE))
2062                         /* Already added */
2063                         continue;
2064
2065                 if (method->is_generic)
2066                         /* FIXME: */
2067                         continue;
2068
2069                 /*
2070                  * FIXME: Instances which are referenced by these methods are not added,
2071                  * for example Array.Resize<int> for List<int>.Add ().
2072                  */
2073                 add_extra_method (acfg, method);
2074         }
2075
2076         if (klass->delegate) {
2077                 method = mono_get_delegate_invoke (klass);
2078
2079                 method = mono_marshal_get_delegate_invoke (method, NULL);
2080
2081                 add_method (acfg, method);
2082         }
2083
2084         /* 
2085          * For ICollection<T>, add instances of the helper methods
2086          * in Array, since a T[] could be cast to ICollection<T>.
2087          */
2088         if (klass->image == mono_defaults.corlib && !strcmp (klass->name_space, "System.Collections.Generic") &&
2089                 (!strcmp(klass->name, "ICollection`1") || !strcmp (klass->name, "IEnumerable`1") || !strcmp (klass->name, "IList`1") || !strcmp (klass->name, "IEnumerator`1"))) {
2090                 MonoClass *tclass = mono_class_from_mono_type (klass->generic_class->context.class_inst->type_argv [0]);
2091                 MonoClass *array_class = mono_bounded_array_class_get (tclass, 1, FALSE);
2092                 gpointer iter;
2093                 char *name_prefix;
2094
2095                 if (!strcmp (klass->name, "IEnumerator`1"))
2096                         name_prefix = g_strdup_printf ("%s.%s", klass->name_space, "IEnumerable`1");
2097                 else
2098                         name_prefix = g_strdup_printf ("%s.%s", klass->name_space, klass->name);
2099
2100                 /* Add the T[]/InternalEnumerator class */
2101                 if (!strcmp (klass->name, "IEnumerable`1") || !strcmp (klass->name, "IEnumerator`1")) {
2102                         MonoClass *nclass;
2103
2104                         iter = NULL;
2105                         while ((nclass = mono_class_get_nested_types (array_class->parent, &iter))) {
2106                                 if (!strcmp (nclass->name, "InternalEnumerator`1"))
2107                                         break;
2108                         }
2109                         g_assert (nclass);
2110                         nclass = mono_class_inflate_generic_class (nclass, mono_generic_class_get_context (klass->generic_class));
2111                         add_generic_class (acfg, nclass);
2112                 }
2113
2114                 iter = NULL;
2115                 while ((method = mono_class_get_methods (array_class, &iter))) {
2116                         if (strstr (method->name, name_prefix))
2117                                 add_extra_method (acfg, method);
2118                 }
2119
2120                 g_free (name_prefix);
2121
2122                 /* 
2123                  * Add instance of Array.GetGenericValueImpl, which is called by the
2124                  * array helper methods.
2125                  * managed-to-native wrappers are not shared, so have to generate 
2126                  * these for ref types too.
2127                  */
2128                 {
2129                         MonoGenericContext ctx;
2130                         MonoType *args [16];
2131                         static MonoMethod *get_method;
2132
2133                         if (get_method == NULL) {
2134                                 MonoClass *array_klass = mono_array_class_get (mono_defaults.int_class, 1)->parent;
2135                                 get_method = mono_class_get_method_from_name (array_klass, "GetGenericValueImpl", 2);
2136                         }
2137
2138                         if (get_method) {
2139                                 memset (&ctx, 0, sizeof (ctx));
2140                                 args [0] = &tclass->byval_arg;
2141                                 ctx.method_inst = mono_metadata_get_generic_inst (1, args);
2142                                 add_extra_method (acfg, mono_marshal_get_native_wrapper (mono_class_inflate_generic_method (get_method, &ctx), TRUE, TRUE));
2143                         }
2144                 }
2145
2146         }
2147 }
2148
2149 static void
2150 add_array_wrappers (MonoAotCompile *acfg, MonoClass *klass)
2151 {
2152         int i;
2153
2154         mono_class_setup_methods (klass);
2155         for (i = 0; i < klass->method.count; ++i) {
2156                 if (klass->methods [i]->wrapper_type == MONO_WRAPPER_MANAGED_TO_MANAGED)
2157                         add_extra_method (acfg, klass->methods [i]);
2158         }
2159 }
2160
2161 /*
2162  * add_generic_instances:
2163  *
2164  *   Add instances referenced by the METHODSPEC/TYPESPEC table.
2165  */
2166 static void
2167 add_generic_instances (MonoAotCompile *acfg)
2168 {
2169         int i;
2170         guint32 token;
2171         MonoMethod *method;
2172         MonoMethodHeader *header;
2173         MonoMethodSignature *sig;
2174         MonoGenericContext *context;
2175
2176         for (i = 0; i < acfg->image->tables [MONO_TABLE_METHODSPEC].rows; ++i) {
2177                 token = MONO_TOKEN_METHOD_SPEC | (i + 1);
2178                 method = mono_get_method (acfg->image, token, NULL);
2179
2180                 context = mono_method_get_context (method);
2181                 if (context && ((context->class_inst && context->class_inst->is_open) ||
2182                                                 (context->method_inst && context->method_inst->is_open)))
2183                         continue;
2184
2185                 if (method->klass->image != acfg->image)
2186                         continue;
2187
2188                 if (mono_method_is_generic_sharable_impl (method, FALSE))
2189                         /* Already added */
2190                         continue;
2191
2192                 add_extra_method (acfg, method);
2193         }
2194
2195         for (i = 0; i < acfg->image->tables [MONO_TABLE_TYPESPEC].rows; ++i) {
2196                 MonoClass *klass;
2197
2198                 token = MONO_TOKEN_TYPE_SPEC | (i + 1);
2199
2200                 klass = mono_class_get (acfg->image, token);
2201                 if (!klass || klass->rank)
2202                         continue;
2203
2204                 add_generic_class (acfg, klass);
2205         }
2206
2207         /* Add types of args/locals */
2208         for (i = 0; i < acfg->methods->len; ++i) {
2209                 int j;
2210
2211                 method = g_ptr_array_index (acfg->methods, i);
2212
2213                 sig = mono_method_signature (method);
2214
2215                 if (sig) {
2216                         for (j = 0; j < sig->param_count; ++j)
2217                                 if (sig->params [j]->type == MONO_TYPE_GENERICINST)
2218                                         add_generic_class (acfg, mono_class_from_mono_type (sig->params [j]));
2219                 }
2220
2221                 header = mono_method_get_header (method);
2222
2223                 if (header) {
2224                         for (j = 0; j < header->num_locals; ++j)
2225                                 if (header->locals [j]->type == MONO_TYPE_GENERICINST)
2226                                         add_generic_class (acfg, mono_class_from_mono_type (header->locals [j]));
2227                 }
2228         }
2229
2230         if (acfg->image == mono_defaults.corlib) {
2231                 /* Add GenericComparer<T> instances for primitive types for Enum.ToString () */
2232                 MonoClass *klass = mono_class_from_name (acfg->image, "System.Collections.Generic", "GenericComparer`1");
2233
2234                 if (klass) {
2235                         MonoGenericContext ctx;
2236                         MonoType *args [16];
2237
2238                         memset (&ctx, 0, sizeof (ctx));
2239
2240                         args [0] = &mono_defaults.byte_class->byval_arg;
2241                         ctx.class_inst = mono_metadata_get_generic_inst (1, args);
2242                         add_generic_class (acfg, mono_class_inflate_generic_class (klass, &ctx));
2243
2244                         args [0] = &mono_defaults.sbyte_class->byval_arg;
2245                         ctx.class_inst = mono_metadata_get_generic_inst (1, args);
2246                         add_generic_class (acfg, mono_class_inflate_generic_class (klass, &ctx));
2247
2248                         args [0] = &mono_defaults.int16_class->byval_arg;
2249                         ctx.class_inst = mono_metadata_get_generic_inst (1, args);
2250                         add_generic_class (acfg, mono_class_inflate_generic_class (klass, &ctx));
2251
2252                         args [0] = &mono_defaults.uint16_class->byval_arg;
2253                         ctx.class_inst = mono_metadata_get_generic_inst (1, args);
2254                         add_generic_class (acfg, mono_class_inflate_generic_class (klass, &ctx));
2255
2256                         args [0] = &mono_defaults.int32_class->byval_arg;
2257                         ctx.class_inst = mono_metadata_get_generic_inst (1, args);
2258                         add_generic_class (acfg, mono_class_inflate_generic_class (klass, &ctx));
2259
2260                         args [0] = &mono_defaults.uint32_class->byval_arg;
2261                         ctx.class_inst = mono_metadata_get_generic_inst (1, args);
2262                         add_generic_class (acfg, mono_class_inflate_generic_class (klass, &ctx));
2263
2264                         args [0] = &mono_defaults.int64_class->byval_arg;
2265                         ctx.class_inst = mono_metadata_get_generic_inst (1, args);
2266                         add_generic_class (acfg, mono_class_inflate_generic_class (klass, &ctx));
2267
2268                         args [0] = &mono_defaults.uint64_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
2273                 /* Add GenericEqualityComparer<T> instances for primitive types */
2274                 klass = mono_class_from_name (acfg->image, "System.Collections.Generic", "GenericEqualityComparer`1");
2275
2276                 if (klass) {
2277                         MonoGenericContext ctx;
2278                         MonoType *args [16];
2279
2280                         memset (&ctx, 0, sizeof (ctx));
2281
2282                         args [0] = &mono_defaults.byte_class->byval_arg;
2283                         ctx.class_inst = mono_metadata_get_generic_inst (1, args);
2284                         add_generic_class (acfg, mono_class_inflate_generic_class (klass, &ctx));
2285
2286                         args [0] = &mono_defaults.sbyte_class->byval_arg;
2287                         ctx.class_inst = mono_metadata_get_generic_inst (1, args);
2288                         add_generic_class (acfg, mono_class_inflate_generic_class (klass, &ctx));
2289
2290                         args [0] = &mono_defaults.int16_class->byval_arg;
2291                         ctx.class_inst = mono_metadata_get_generic_inst (1, args);
2292                         add_generic_class (acfg, mono_class_inflate_generic_class (klass, &ctx));
2293
2294                         args [0] = &mono_defaults.uint16_class->byval_arg;
2295                         ctx.class_inst = mono_metadata_get_generic_inst (1, args);
2296                         add_generic_class (acfg, mono_class_inflate_generic_class (klass, &ctx));
2297
2298                         args [0] = &mono_defaults.int32_class->byval_arg;
2299                         ctx.class_inst = mono_metadata_get_generic_inst (1, args);
2300                         add_generic_class (acfg, mono_class_inflate_generic_class (klass, &ctx));
2301
2302                         args [0] = &mono_defaults.uint32_class->byval_arg;
2303                         ctx.class_inst = mono_metadata_get_generic_inst (1, args);
2304                         add_generic_class (acfg, mono_class_inflate_generic_class (klass, &ctx));
2305
2306                         args [0] = &mono_defaults.int64_class->byval_arg;
2307                         ctx.class_inst = mono_metadata_get_generic_inst (1, args);
2308                         add_generic_class (acfg, mono_class_inflate_generic_class (klass, &ctx));
2309
2310                         args [0] = &mono_defaults.uint64_class->byval_arg;
2311                         ctx.class_inst = mono_metadata_get_generic_inst (1, args);
2312                         add_generic_class (acfg, mono_class_inflate_generic_class (klass, &ctx));
2313
2314                         args [0] = &mono_defaults.char_class->byval_arg;
2315                         ctx.class_inst = mono_metadata_get_generic_inst (1, args);
2316                         add_generic_class (acfg, mono_class_inflate_generic_class (klass, &ctx));
2317
2318                         args [0] = &mono_defaults.boolean_class->byval_arg;
2319                         ctx.class_inst = mono_metadata_get_generic_inst (1, args);
2320                         add_generic_class (acfg, mono_class_inflate_generic_class (klass, &ctx));
2321
2322                         args [0] = &mono_defaults.single_class->byval_arg;
2323                         ctx.class_inst = mono_metadata_get_generic_inst (1, args);
2324                         add_generic_class (acfg, mono_class_inflate_generic_class (klass, &ctx));
2325
2326                         args [0] = &mono_defaults.double_class->byval_arg;
2327                         ctx.class_inst = mono_metadata_get_generic_inst (1, args);
2328                         add_generic_class (acfg, mono_class_inflate_generic_class (klass, &ctx));
2329
2330                 }
2331
2332                 /* Emit the array wrapper methods for arrays of primitive types */
2333                 add_array_wrappers (acfg, mono_array_class_get (mono_defaults.byte_class, 1));
2334                 add_array_wrappers (acfg, mono_array_class_get (mono_defaults.sbyte_class, 1));
2335                 add_array_wrappers (acfg, mono_array_class_get (mono_defaults.int16_class, 1));
2336                 add_array_wrappers (acfg, mono_array_class_get (mono_defaults.uint16_class, 1));
2337                 add_array_wrappers (acfg, mono_array_class_get (mono_defaults.int32_class, 1));
2338                 add_array_wrappers (acfg, mono_array_class_get (mono_defaults.uint32_class, 1));
2339                 add_array_wrappers (acfg, mono_array_class_get (mono_defaults.int64_class, 1));
2340                 add_array_wrappers (acfg, mono_array_class_get (mono_defaults.single_class, 1));
2341                 add_array_wrappers (acfg, mono_array_class_get (mono_defaults.double_class, 1));
2342                 /* These are not handled by generic sharing */
2343                 add_array_wrappers (acfg, mono_array_class_get (mono_defaults.object_class, 1));
2344                 add_array_wrappers (acfg, mono_array_class_get (mono_defaults.string_class, 1));
2345
2346                 /* Add instances of Array.GetGenericValueImpl */
2347                 {
2348                         MonoGenericContext ctx;
2349                         MonoType *args [16];
2350                         MonoMethod *method;
2351
2352                         memset (&ctx, 0, sizeof (ctx));
2353
2354                         /* 
2355                          * managed-to-native wrappers are not shared, so have to generate 
2356                          * these for ref types too.
2357                          */
2358                         klass = mono_array_class_get (mono_defaults.int_class, 1)->parent;
2359                         method = mono_class_get_method_from_name (klass, "GetGenericValueImpl", 2);
2360
2361                         if (method) {
2362                                 /* String */
2363                                 args [0] = &mono_defaults.string_class->byval_arg;
2364                                 ctx.method_inst = mono_metadata_get_generic_inst (1, args);
2365                                 add_extra_method (acfg, mono_marshal_get_native_wrapper (mono_class_inflate_generic_method (method, &ctx), TRUE, TRUE));
2366                         }
2367                 }
2368         }
2369 }
2370
2371 /*
2372  * is_direct_callable:
2373  *
2374  *   Return whenever the method identified by JI is directly callable without 
2375  * going through the PLT.
2376  */
2377 static gboolean
2378 is_direct_callable (MonoAotCompile *acfg, MonoMethod *method, MonoJumpInfo *patch_info)
2379 {
2380         if ((patch_info->type == MONO_PATCH_INFO_METHOD) && (patch_info->data.method->klass->image == acfg->image)) {
2381                 MonoCompile *callee_cfg = g_hash_table_lookup (acfg->method_to_cfg, patch_info->data.method);
2382                 if (callee_cfg) {
2383                         gboolean direct_callable = TRUE;
2384
2385                         if (direct_callable && !(!callee_cfg->has_got_slots && (callee_cfg->method->klass->flags & TYPE_ATTRIBUTE_BEFORE_FIELD_INIT)))
2386                                 direct_callable = FALSE;
2387                         if ((callee_cfg->method->iflags & METHOD_IMPL_ATTRIBUTE_SYNCHRONIZED) && (!method || method->wrapper_type != MONO_WRAPPER_SYNCHRONIZED))
2388                                 // FIXME: Maybe call the wrapper directly ?
2389                                 direct_callable = FALSE;
2390
2391                         if (direct_callable)
2392                                 return TRUE;
2393                 }
2394         }
2395
2396         return FALSE;
2397 }
2398
2399 /*
2400  * emit_and_reloc_code:
2401  *
2402  *   Emit the native code in CODE, handling relocations along the way. If GOT_ONLY
2403  * is true, calls are made through the GOT too. This is used for emitting trampolines
2404  * in full-aot mode, since calls made from trampolines couldn't go through the PLT,
2405  * since trampolines are needed to make PTL work.
2406  */
2407 static void
2408 emit_and_reloc_code (MonoAotCompile *acfg, MonoMethod *method, guint8 *code, guint32 code_len, MonoJumpInfo *relocs, gboolean got_only)
2409 {
2410         int i, pindex, start_index, method_index;
2411         GPtrArray *patches;
2412         MonoJumpInfo *patch_info;
2413         MonoMethodHeader *header;
2414         gboolean skip, direct_call;
2415         guint32 got_slot;
2416         char direct_call_target [128];
2417
2418         if (method) {
2419                 header = mono_method_get_header (method);
2420
2421                 method_index = get_method_index (acfg, method);
2422         }
2423
2424         /* Collect and sort relocations */
2425         patches = g_ptr_array_new ();
2426         for (patch_info = relocs; patch_info; patch_info = patch_info->next)
2427                 g_ptr_array_add (patches, patch_info);
2428         g_ptr_array_sort (patches, compare_patches);
2429
2430         start_index = 0;
2431         for (i = 0; i < code_len; i++) {
2432                 patch_info = NULL;
2433                 for (pindex = start_index; pindex < patches->len; ++pindex) {
2434                         patch_info = g_ptr_array_index (patches, pindex);
2435                         if (patch_info->ip.i >= i)
2436                                 break;
2437                 }
2438
2439 #ifdef MONO_ARCH_AOT_SUPPORTED
2440                 skip = FALSE;
2441                 if (patch_info && (patch_info->ip.i == i) && (pindex < patches->len)) {
2442                         start_index = pindex;
2443
2444                         switch (patch_info->type) {
2445                         case MONO_PATCH_INFO_NONE:
2446                                 break;
2447                         case MONO_PATCH_INFO_GOT_OFFSET: {
2448                                 int code_size;
2449  
2450                                 arch_emit_got_offset (acfg, code + i, &code_size);
2451                                 i += code_size - 1;
2452                                 skip = TRUE;
2453                                 patch_info->type = MONO_PATCH_INFO_NONE;
2454                                 break;
2455                         }
2456                         default: {
2457                                 /*
2458                                  * If this patch is a call, try emitting a direct call instead of
2459                                  * through a PLT entry. This is possible if the called method is in
2460                                  * the same assembly and requires no initialization.
2461                                  */
2462                                 direct_call = FALSE;
2463                                 if ((patch_info->type == MONO_PATCH_INFO_METHOD) && (patch_info->data.method->klass->image == acfg->image)) {
2464                                         if (!got_only && is_direct_callable (acfg, method, patch_info)) {
2465                                                 MonoCompile *callee_cfg = g_hash_table_lookup (acfg->method_to_cfg, patch_info->data.method);
2466                                                 //printf ("DIRECT: %s %s\n", method ? mono_method_full_name (method, TRUE) : "", mono_method_full_name (callee_cfg->method, TRUE));
2467                                                 direct_call = TRUE;
2468                                                 sprintf (direct_call_target, "%sm_%x", acfg->temp_prefix, get_method_index (acfg, callee_cfg->orig_method));
2469                                                 patch_info->type = MONO_PATCH_INFO_NONE;
2470                                                 acfg->stats.direct_calls ++;
2471                                         }
2472
2473                                         acfg->stats.all_calls ++;
2474                                 }
2475
2476                                 if (!got_only && !direct_call) {
2477                                         int plt_offset = get_plt_offset (acfg, patch_info);
2478                                         if (plt_offset != -1) {
2479                                                 /* This patch has a PLT entry, so we must emit a call to the PLT entry */
2480                                                 direct_call = TRUE;
2481                                                 sprintf (direct_call_target, "%sp_%d", acfg->temp_prefix, plt_offset);
2482                 
2483                                                 /* Nullify the patch */
2484                                                 patch_info->type = MONO_PATCH_INFO_NONE;
2485                                         }
2486                                 }
2487
2488                                 if (direct_call) {
2489                                         int call_size;
2490
2491                                         arch_emit_direct_call (acfg, direct_call_target, &call_size);
2492                                         i += call_size - 1;
2493                                 } else {
2494                                         int code_size;
2495
2496                                         got_slot = get_got_offset (acfg, patch_info);
2497
2498                                         arch_emit_got_access (acfg, code + i, got_slot, &code_size);
2499                                         i += code_size - 1;
2500                                 }
2501                                 skip = TRUE;
2502                         }
2503                         }
2504                 }
2505 #endif /* MONO_ARCH_AOT_SUPPORTED */
2506
2507                 if (!skip) {
2508                         /* Find next patch */
2509                         patch_info = NULL;
2510                         for (pindex = start_index; pindex < patches->len; ++pindex) {
2511                                 patch_info = g_ptr_array_index (patches, pindex);
2512                                 if (patch_info->ip.i >= i)
2513                                         break;
2514                         }
2515
2516                         /* Try to emit multiple bytes at once */
2517                         if (pindex < patches->len && patch_info->ip.i > i) {
2518                                 emit_bytes (acfg, code + i, patch_info->ip.i - i);
2519                                 i = patch_info->ip.i - 1;
2520                         } else {
2521                                 emit_bytes (acfg, code + i, 1);
2522                         }
2523                 }
2524         }
2525 }
2526
2527 /*
2528  * sanitize_symbol:
2529  *
2530  *   Modify SYMBOL so it only includes characters permissible in symbols.
2531  */
2532 static void
2533 sanitize_symbol (char *symbol)
2534 {
2535         int i, len = strlen (symbol);
2536
2537         for (i = 0; i < len; ++i)
2538                 if (!isalnum (symbol [i]) && (symbol [i] != '_'))
2539                         symbol [i] = '_';
2540 }
2541
2542 static char*
2543 get_debug_sym (MonoMethod *method, const char *prefix, GHashTable *cache)
2544 {
2545         char *name1, *name2, *cached;
2546         int i, j, len, count;
2547                 
2548         name1 = mono_method_full_name (method, TRUE);
2549         len = strlen (name1);
2550         name2 = malloc (strlen (prefix) + len + 16);
2551         memcpy (name2, prefix, strlen (prefix));
2552         j = strlen (prefix);
2553         for (i = 0; i < len; ++i) {
2554                 if (isalnum (name1 [i])) {
2555                         name2 [j ++] = name1 [i];
2556                 } else if (name1 [i] == ' ' && name1 [i + 1] == '(' && name1 [i + 2] == ')') {
2557                         i += 2;
2558                 } else if (name1 [i] == ',' && name1 [i + 1] == ' ') {
2559                         name2 [j ++] = '_';
2560                         i++;
2561                 } else if (name1 [i] == '(' || name1 [i] == ')' || name1 [i] == '>') {
2562                 } else
2563                         name2 [j ++] = '_';
2564         }
2565         name2 [j] = '\0';
2566
2567         g_free (name1);
2568
2569         count = 0;
2570         while (g_hash_table_lookup (cache, name2)) {
2571                 sprintf (name2 + j, "_%d", count);
2572                 count ++;
2573         }
2574
2575         cached = g_strdup (name2);
2576         g_hash_table_insert (cache, cached, cached);
2577
2578         return name2;
2579 }
2580
2581 static void
2582 emit_method_code (MonoAotCompile *acfg, MonoCompile *cfg)
2583 {
2584         MonoMethod *method;
2585         int method_index;
2586         guint8 *code;
2587         char *debug_sym = NULL;
2588         char symbol [128];
2589         int func_alignment = AOT_FUNC_ALIGNMENT;
2590         MonoMethodHeader *header;
2591
2592         method = cfg->orig_method;
2593         code = cfg->native_code;
2594         header = mono_method_get_header (method);
2595
2596         method_index = get_method_index (acfg, method);
2597
2598         /* Emit unbox trampoline */
2599         if (acfg->aot_opts.full_aot && cfg->orig_method->klass->valuetype && (method->flags & METHOD_ATTRIBUTE_VIRTUAL)) {
2600                 char call_target [256];
2601
2602                 if (!method->wrapper_type && !method->is_inflated) {
2603                         g_assert (method->token);
2604                         sprintf (symbol, "ut_%d", mono_metadata_token_index (method->token) - 1);
2605                 } else {
2606                         sprintf (symbol, "ut_e_%d", get_method_index (acfg, method));
2607                 }
2608
2609                 emit_section_change (acfg, ".text", 0);
2610                 emit_global (acfg, symbol, TRUE);
2611                 emit_label (acfg, symbol);
2612
2613                 sprintf (call_target, "%sm_%x", acfg->temp_prefix, method_index);
2614
2615                 arch_emit_unbox_trampoline (acfg, cfg->orig_method, cfg->generic_sharing_context, call_target);
2616         }
2617
2618         /* Make the labels local */
2619         sprintf (symbol, "%sm_%x", acfg->temp_prefix, method_index);
2620
2621         emit_alignment (acfg, func_alignment);
2622         emit_label (acfg, symbol);
2623
2624         if (acfg->aot_opts.write_symbols) {
2625                 /* 
2626                  * Write a C style symbol for every method, this has two uses:
2627                  * - it works on platforms where the dwarf debugging info is not
2628                  *   yet supported.
2629                  * - it allows the setting of breakpoints of aot-ed methods.
2630                  */
2631                 debug_sym = get_debug_sym (method, "", acfg->method_label_hash);
2632
2633                 sprintf (symbol, "%sme_%x", acfg->temp_prefix, method_index);
2634                 emit_local_symbol (acfg, debug_sym, symbol, TRUE);
2635                 emit_label (acfg, debug_sym);
2636         }
2637
2638         if (cfg->verbose_level > 0)
2639                 g_print ("Method %s emitted as %s\n", mono_method_full_name (method, TRUE), symbol);
2640
2641         acfg->stats.code_size += cfg->code_len;
2642
2643         acfg->cfgs [method_index]->got_offset = acfg->got_offset;
2644
2645         emit_and_reloc_code (acfg, method, code, cfg->code_len, cfg->patch_info, FALSE);
2646
2647         emit_line (acfg);
2648
2649         if (acfg->aot_opts.write_symbols) {
2650                 emit_symbol_size (acfg, debug_sym, ".");
2651                 g_free (debug_sym);
2652         }
2653
2654         sprintf (symbol, "%sme_%x", acfg->temp_prefix, method_index);
2655         emit_label (acfg, symbol);
2656 }
2657
2658 /**
2659  * encode_patch:
2660  *
2661  *  Encode PATCH_INFO into its disk representation.
2662  */
2663 static void
2664 encode_patch (MonoAotCompile *acfg, MonoJumpInfo *patch_info, guint8 *buf, guint8 **endbuf)
2665 {
2666         guint8 *p = buf;
2667
2668         switch (patch_info->type) {
2669         case MONO_PATCH_INFO_NONE:
2670                 break;
2671         case MONO_PATCH_INFO_IMAGE:
2672                 encode_value (get_image_index (acfg, patch_info->data.image), p, &p);
2673                 break;
2674         case MONO_PATCH_INFO_MSCORLIB_GOT_ADDR:
2675                 break;
2676         case MONO_PATCH_INFO_METHOD_REL:
2677                 encode_value ((gint)patch_info->data.offset, p, &p);
2678                 break;
2679         case MONO_PATCH_INFO_SWITCH: {
2680                 gpointer *table = (gpointer *)patch_info->data.table->table;
2681                 int k;
2682
2683                 encode_value (patch_info->data.table->table_size, p, &p);
2684                 for (k = 0; k < patch_info->data.table->table_size; k++)
2685                         encode_value ((int)(gssize)table [k], p, &p);
2686                 break;
2687         }
2688         case MONO_PATCH_INFO_METHODCONST:
2689         case MONO_PATCH_INFO_METHOD:
2690         case MONO_PATCH_INFO_METHOD_JUMP:
2691         case MONO_PATCH_INFO_ICALL_ADDR:
2692         case MONO_PATCH_INFO_METHOD_RGCTX:
2693                 encode_method_ref (acfg, patch_info->data.method, p, &p);
2694                 break;
2695         case MONO_PATCH_INFO_INTERNAL_METHOD:
2696         case MONO_PATCH_INFO_JIT_ICALL_ADDR: {
2697                 guint32 len = strlen (patch_info->data.name);
2698
2699                 encode_value (len, p, &p);
2700
2701                 memcpy (p, patch_info->data.name, len);
2702                 p += len;
2703                 *p++ = '\0';
2704                 break;
2705         }
2706         case MONO_PATCH_INFO_LDSTR: {
2707                 guint32 image_index = get_image_index (acfg, patch_info->data.token->image);
2708                 guint32 token = patch_info->data.token->token;
2709                 g_assert (mono_metadata_token_code (token) == MONO_TOKEN_STRING);
2710                 encode_value (image_index, p, &p);
2711                 encode_value (patch_info->data.token->token - MONO_TOKEN_STRING, p, &p);
2712                 break;
2713         }
2714         case MONO_PATCH_INFO_RVA:
2715         case MONO_PATCH_INFO_DECLSEC:
2716         case MONO_PATCH_INFO_LDTOKEN:
2717         case MONO_PATCH_INFO_TYPE_FROM_HANDLE:
2718                 encode_value (get_image_index (acfg, patch_info->data.token->image), p, &p);
2719                 encode_value (patch_info->data.token->token, p, &p);
2720                 encode_value (patch_info->data.token->has_context, p, &p);
2721                 if (patch_info->data.token->has_context)
2722                         encode_generic_context (acfg, &patch_info->data.token->context, p, &p);
2723                 break;
2724         case MONO_PATCH_INFO_EXC_NAME: {
2725                 MonoClass *ex_class;
2726
2727                 ex_class =
2728                         mono_class_from_name (mono_defaults.exception_class->image,
2729                                                                   "System", patch_info->data.target);
2730                 g_assert (ex_class);
2731                 encode_klass_ref (acfg, ex_class, p, &p);
2732                 break;
2733         }
2734         case MONO_PATCH_INFO_R4:
2735                 encode_value (*((guint32 *)patch_info->data.target), p, &p);
2736                 break;
2737         case MONO_PATCH_INFO_R8:
2738                 encode_value (*((guint32 *)patch_info->data.target), p, &p);
2739                 encode_value (*(((guint32 *)patch_info->data.target) + 1), p, &p);
2740                 break;
2741         case MONO_PATCH_INFO_VTABLE:
2742         case MONO_PATCH_INFO_CLASS:
2743         case MONO_PATCH_INFO_IID:
2744         case MONO_PATCH_INFO_ADJUSTED_IID:
2745                 encode_klass_ref (acfg, patch_info->data.klass, p, &p);
2746                 break;
2747         case MONO_PATCH_INFO_CLASS_INIT:
2748         case MONO_PATCH_INFO_DELEGATE_TRAMPOLINE:
2749                 encode_klass_ref (acfg, patch_info->data.klass, p, &p);
2750                 break;
2751         case MONO_PATCH_INFO_FIELD:
2752         case MONO_PATCH_INFO_SFLDA:
2753                 encode_field_info (acfg, patch_info->data.field, p, &p);
2754                 break;
2755         case MONO_PATCH_INFO_INTERRUPTION_REQUEST_FLAG:
2756                 break;
2757         case MONO_PATCH_INFO_RGCTX_FETCH: {
2758                 MonoJumpInfoRgctxEntry *entry = patch_info->data.rgctx_entry;
2759
2760                 encode_method_ref (acfg, entry->method, p, &p);
2761                 encode_value (entry->in_mrgctx, p, &p);
2762                 encode_value (entry->info_type, p, &p);
2763                 encode_value (entry->data->type, p, &p);
2764                 encode_patch (acfg, entry->data, p, &p);
2765                 break;
2766         }
2767         case MONO_PATCH_INFO_GENERIC_CLASS_INIT:
2768         case MONO_PATCH_INFO_MONITOR_ENTER:
2769         case MONO_PATCH_INFO_MONITOR_EXIT:
2770                 break;
2771         default:
2772                 g_warning ("unable to handle jump info %d", patch_info->type);
2773                 g_assert_not_reached ();
2774         }
2775
2776         *endbuf = p;
2777 }
2778
2779 static void
2780 encode_patch_list (MonoAotCompile *acfg, GPtrArray *patches, int n_patches, int first_got_offset, guint8 *buf, guint8 **endbuf)
2781 {
2782         guint8 *p = buf;
2783         guint32 pindex, offset;
2784         MonoJumpInfo *patch_info;
2785
2786         encode_value (n_patches, p, &p);
2787
2788         for (pindex = 0; pindex < patches->len; ++pindex) {
2789                 patch_info = g_ptr_array_index (patches, pindex);
2790
2791                 if (patch_info->type == MONO_PATCH_INFO_NONE)
2792                         /* Nothing to do */
2793                         continue;
2794
2795                 offset = get_got_offset (acfg, patch_info);
2796                 encode_value (offset, p, &p);
2797         }
2798
2799         *endbuf = p;
2800 }
2801
2802 static void
2803 emit_method_info (MonoAotCompile *acfg, MonoCompile *cfg)
2804 {
2805         MonoMethod *method;
2806         GList *l;
2807         int pindex, buf_size, n_patches;
2808         guint8 *code;
2809         char symbol [128];
2810         GPtrArray *patches;
2811         MonoJumpInfo *patch_info;
2812         MonoMethodHeader *header;
2813         guint32 method_index;
2814         guint8 *p, *buf;
2815         guint32 first_got_offset;
2816
2817         method = cfg->orig_method;
2818         code = cfg->native_code;
2819         header = mono_method_get_header (method);
2820
2821         method_index = get_method_index (acfg, method);
2822
2823         /* Make the labels local */
2824         sprintf (symbol, "%sm_%x_p", acfg->temp_prefix, method_index);
2825
2826         /* Sort relocations */
2827         patches = g_ptr_array_new ();
2828         for (patch_info = cfg->patch_info; patch_info; patch_info = patch_info->next)
2829                 g_ptr_array_add (patches, patch_info);
2830         g_ptr_array_sort (patches, compare_patches);
2831
2832         first_got_offset = acfg->cfgs [method_index]->got_offset;
2833
2834         /**********************/
2835         /* Encode method info */
2836         /**********************/
2837
2838         buf_size = (patches->len < 1000) ? 40960 : 40960 + (patches->len * 64);
2839         p = buf = g_malloc (buf_size);
2840
2841         if (mono_class_get_cctor (method->klass))
2842                 encode_klass_ref (acfg, method->klass, p, &p);
2843         else
2844                 /* Not needed when loading the method */
2845                 encode_value (0, p, &p);
2846
2847         /* String table */
2848         if (cfg->opt & MONO_OPT_SHARED) {
2849                 encode_value (g_list_length (cfg->ldstr_list), p, &p);
2850                 for (l = cfg->ldstr_list; l; l = l->next) {
2851                         encode_value ((long)l->data, p, &p);
2852                 }
2853         }
2854         else
2855                 /* Used only in shared mode */
2856                 g_assert (!cfg->ldstr_list);
2857
2858         n_patches = 0;
2859         for (pindex = 0; pindex < patches->len; ++pindex) {
2860                 patch_info = g_ptr_array_index (patches, pindex);
2861                 
2862                 if ((patch_info->type == MONO_PATCH_INFO_GOT_OFFSET) ||
2863                         (patch_info->type == MONO_PATCH_INFO_NONE)) {
2864                         patch_info->type = MONO_PATCH_INFO_NONE;
2865                         /* Nothing to do */
2866                         continue;
2867                 }
2868
2869                 if ((patch_info->type == MONO_PATCH_INFO_IMAGE) && (patch_info->data.image == acfg->image)) {
2870                         /* Stored in a GOT slot initialized at module load time */
2871                         patch_info->type = MONO_PATCH_INFO_NONE;
2872                         continue;
2873                 }
2874
2875                 if (is_plt_patch (patch_info)) {
2876                         /* Calls are made through the PLT */
2877                         patch_info->type = MONO_PATCH_INFO_NONE;
2878                         continue;
2879                 }
2880
2881                 n_patches ++;
2882         }
2883
2884         if (n_patches)
2885                 g_assert (cfg->has_got_slots);
2886
2887         encode_patch_list (acfg, patches, n_patches, first_got_offset, p, &p);
2888
2889         acfg->stats.info_size += p - buf;
2890
2891         /* Emit method info */
2892
2893         emit_label (acfg, symbol);
2894
2895         g_assert (p - buf < buf_size);
2896         emit_bytes (acfg, buf, p - buf);
2897         g_free (buf);
2898 }
2899
2900 static guint32
2901 get_unwind_info_offset (MonoAotCompile *acfg, guint8 *encoded, guint32 encoded_len)
2902 {
2903         guint32 cache_index;
2904         guint32 offset;
2905
2906         /* Reuse the unwind module to canonize and store unwind info entries */
2907         cache_index = mono_cache_unwind_info (encoded, encoded_len);
2908
2909         /* Use +/- 1 to distinguish 0s from missing entries */
2910         offset = GPOINTER_TO_UINT (g_hash_table_lookup (acfg->unwind_info_offsets, GUINT_TO_POINTER (cache_index + 1)));
2911         if (offset)
2912                 return offset - 1;
2913         else {
2914                 guint8 buf [16];
2915                 guint8 *p;
2916
2917                 /* 
2918                  * It would be easier to use assembler symbols, but the caller needs an
2919                  * offset now.
2920                  */
2921                 offset = acfg->unwind_info_offset;
2922                 g_hash_table_insert (acfg->unwind_info_offsets, GUINT_TO_POINTER (cache_index + 1), GUINT_TO_POINTER (offset + 1));
2923                 g_ptr_array_add (acfg->unwind_ops, GUINT_TO_POINTER (cache_index));
2924
2925                 p = buf;
2926                 encode_value (encoded_len, p, &p);
2927
2928                 acfg->unwind_info_offset += encoded_len + (p - buf);
2929                 return offset;
2930         }
2931 }
2932
2933 static void
2934 emit_exception_debug_info (MonoAotCompile *acfg, MonoCompile *cfg)
2935 {
2936         MonoMethod *method;
2937         int k, buf_size, method_index;
2938         guint32 debug_info_size;
2939         guint8 *code;
2940         char symbol [128];
2941         MonoMethodHeader *header;
2942         guint8 *p, *buf, *debug_info;
2943         MonoJitInfo *jinfo = cfg->jit_info;
2944         guint32 flags;
2945         gboolean use_unwind_ops = FALSE;
2946
2947         method = cfg->orig_method;
2948         code = cfg->native_code;
2949         header = mono_method_get_header (method);
2950
2951         method_index = get_method_index (acfg, method);
2952
2953         /* Make the labels local */
2954         sprintf (symbol, "%se_%x_p", acfg->temp_prefix, method_index);
2955
2956         if (!acfg->aot_opts.nodebug) {
2957                 mono_debug_serialize_debug_info (cfg, &debug_info, &debug_info_size);
2958         } else {
2959                 debug_info = NULL;
2960                 debug_info_size = 0;
2961         }
2962
2963         buf_size = header->num_clauses * 256 + debug_info_size + 1024;
2964         p = buf = g_malloc (buf_size);
2965
2966 #ifdef MONO_ARCH_HAVE_XP_UNWIND
2967         use_unwind_ops = cfg->unwind_ops != NULL;
2968 #endif
2969
2970         flags = (jinfo->has_generic_jit_info ? 1 : 0) | (use_unwind_ops ? 2 : 0) | (header->num_clauses ? 4 : 0);
2971
2972         encode_value (jinfo->code_size, p, &p);
2973         encode_value (flags, p, &p);
2974
2975         if (use_unwind_ops) {
2976                 guint32 encoded_len;
2977                 guint8 *encoded;
2978
2979                 /* 
2980                  * This is a duplicate of the data in the .debug_frame section, but that
2981                  * section cannot be accessed using the dl interface.
2982                  */
2983                 encoded = mono_unwind_ops_encode (cfg->unwind_ops, &encoded_len);
2984                 encode_value (get_unwind_info_offset (acfg, encoded, encoded_len), p, &p);
2985                 g_free (encoded);
2986         } else {
2987                 encode_value (jinfo->used_regs, p, &p);
2988         }
2989
2990         /* Exception table */
2991         if (jinfo->num_clauses)
2992                 encode_value (jinfo->num_clauses, p, &p);
2993
2994         for (k = 0; k < jinfo->num_clauses; ++k) {
2995                 MonoJitExceptionInfo *ei = &jinfo->clauses [k];
2996
2997                 encode_value (ei->flags, p, &p);
2998                 encode_value (ei->exvar_offset, p, &p);
2999
3000                 if (ei->flags == MONO_EXCEPTION_CLAUSE_FILTER)
3001                         encode_value ((gint)((guint8*)ei->data.filter - code), p, &p);
3002                 else {
3003                         if (ei->data.catch_class) {
3004                                 encode_value (1, p, &p);
3005                                 encode_klass_ref (acfg, ei->data.catch_class, p, &p);
3006                         } else {
3007                                 encode_value (0, p, &p);
3008                         }
3009                 }
3010
3011                 encode_value ((gint)((guint8*)ei->try_start - code), p, &p);
3012                 encode_value ((gint)((guint8*)ei->try_end - code), p, &p);
3013                 encode_value ((gint)((guint8*)ei->handler_start - code), p, &p);
3014         }
3015
3016         if (jinfo->has_generic_jit_info) {
3017                 MonoGenericJitInfo *gi = mono_jit_info_get_generic_jit_info (jinfo);
3018
3019                 encode_value (gi->has_this ? 1 : 0, p, &p);
3020                 encode_value (gi->this_reg, p, &p);
3021                 encode_value (gi->this_offset, p, &p);
3022
3023                 /* 
3024                  * Need to encode jinfo->method too, since it is not equal to 'method'
3025                  * when using generic sharing.
3026                  */
3027                 encode_method_ref (acfg, jinfo->method, p, &p);
3028         }
3029
3030         g_assert (debug_info_size < buf_size);
3031
3032         encode_value (debug_info_size, p, &p);
3033         if (debug_info_size) {
3034                 memcpy (p, debug_info, debug_info_size);
3035                 p += debug_info_size;
3036                 g_free (debug_info);
3037         }
3038
3039         acfg->stats.ex_info_size += p - buf;
3040
3041         /* Emit info */
3042
3043         emit_label (acfg, symbol);
3044
3045         g_assert (p - buf < buf_size);
3046         emit_bytes (acfg, buf, p - buf);
3047         g_free (buf);
3048 }
3049
3050 static void
3051 emit_klass_info (MonoAotCompile *acfg, guint32 token)
3052 {
3053         MonoClass *klass = mono_class_get (acfg->image, token);
3054         guint8 *p, *buf;
3055         int i, buf_size;
3056         char symbol [128];
3057         gboolean no_special_static, cant_encode;
3058         gpointer iter = NULL;
3059
3060         buf_size = 10240 + (klass->vtable_size * 16);
3061         p = buf = g_malloc (buf_size);
3062
3063         g_assert (klass);
3064
3065         mono_class_init (klass);
3066
3067         mono_class_get_nested_types (klass, &iter);
3068         g_assert (klass->nested_classes_inited);
3069
3070         mono_class_setup_vtable (klass);
3071
3072         /* 
3073          * Emit all the information which is required for creating vtables so
3074          * the runtime does not need to create the MonoMethod structures which
3075          * take up a lot of space.
3076          */
3077
3078         no_special_static = !mono_class_has_special_static_fields (klass);
3079
3080         /* Check whenever we have enough info to encode the vtable */
3081         cant_encode = FALSE;
3082         for (i = 0; i < klass->vtable_size; ++i) {
3083                 MonoMethod *cm = klass->vtable [i];
3084
3085                 if (cm && mono_method_signature (cm)->is_inflated && !g_hash_table_lookup (acfg->token_info_hash, cm))
3086                         cant_encode = TRUE;
3087         }
3088
3089         if (klass->generic_container || cant_encode) {
3090                 encode_value (-1, p, &p);
3091         } else {
3092                 encode_value (klass->vtable_size, p, &p);
3093                 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);
3094                 if (klass->has_cctor)
3095                         encode_method_ref (acfg, mono_class_get_cctor (klass), p, &p);
3096                 if (klass->has_finalize)
3097                         encode_method_ref (acfg, mono_class_get_finalizer (klass), p, &p);
3098  
3099                 encode_value (klass->instance_size, p, &p);
3100                 encode_value (mono_class_data_size (klass), p, &p);
3101                 encode_value (klass->packing_size, p, &p);
3102                 encode_value (klass->min_align, p, &p);
3103
3104                 for (i = 0; i < klass->vtable_size; ++i) {
3105                         MonoMethod *cm = klass->vtable [i];
3106
3107                         if (cm)
3108                                 encode_method_ref (acfg, cm, p, &p);
3109                         else
3110                                 encode_value (0, p, &p);
3111                 }
3112         }
3113
3114         acfg->stats.class_info_size += p - buf;
3115
3116         /* Emit the info */
3117         sprintf (symbol, "%sK_I_%x", acfg->temp_prefix, token - MONO_TOKEN_TYPE_DEF - 1);
3118         emit_label (acfg, symbol);
3119
3120         g_assert (p - buf < buf_size);
3121         emit_bytes (acfg, buf, p - buf);
3122         g_free (buf);
3123 }
3124
3125 /*
3126  * Calls made from AOTed code are routed through a table of jumps similar to the
3127  * ELF PLT (Program Linkage Table). The differences are the following:
3128  * - the ELF PLT entries make an indirect jump though the GOT so they expect the
3129  *   GOT pointer to be in EBX. We want to avoid this, so our table contains direct
3130  *   jumps. This means the jumps need to be patched when the address of the callee is
3131  *   known. Initially the PLT entries jump to code which transfers control to the
3132  *   AOT runtime through the first PLT entry.
3133  */
3134 static void
3135 emit_plt (MonoAotCompile *acfg)
3136 {
3137         char symbol [128];
3138         int i;
3139         GHashTable *cache;
3140
3141         cache = g_hash_table_new (g_str_hash, g_str_equal);
3142
3143         emit_line (acfg);
3144         sprintf (symbol, "plt");
3145
3146         emit_section_change (acfg, ".text", 0);
3147         emit_global (acfg, symbol, TRUE);
3148 #ifdef TARGET_X86
3149         /* This section will be made read-write by the AOT loader */
3150         emit_alignment (acfg, mono_pagesize ());
3151 #else
3152         emit_alignment (acfg, 16);
3153 #endif
3154         emit_label (acfg, symbol);
3155         emit_label (acfg, acfg->plt_symbol);
3156
3157         for (i = 0; i < acfg->plt_offset; ++i) {
3158                 char label [128];
3159                 char *debug_sym = NULL;
3160
3161                 sprintf (label, "%sp_%d", acfg->temp_prefix, i);
3162                 emit_label (acfg, label);
3163
3164                 if (acfg->aot_opts.write_symbols) {
3165                         MonoJumpInfo *ji = g_hash_table_lookup (acfg->plt_offset_to_patch, GUINT_TO_POINTER (i));
3166                         char *debug_sym = NULL;
3167
3168                         if (ji) {
3169                                 switch (ji->type) {
3170                                 case MONO_PATCH_INFO_METHOD:
3171                                         debug_sym = get_debug_sym (ji->data.method, "plt_", cache);
3172                                         break;
3173                                 case MONO_PATCH_INFO_INTERNAL_METHOD:
3174                                         debug_sym = g_strdup_printf ("plt__jit_icall_%s", ji->data.name);
3175                                         break;
3176                                 case MONO_PATCH_INFO_CLASS_INIT:
3177                                         debug_sym = g_strdup_printf ("plt__class_init_%s", mono_type_get_name (&ji->data.klass->byval_arg));
3178                                         sanitize_symbol (debug_sym);
3179                                         break;
3180                                 case MONO_PATCH_INFO_RGCTX_FETCH:
3181                                         debug_sym = g_strdup_printf ("plt__rgctx_fetch_%d", acfg->label_generator ++);
3182                                         break;
3183                                 case MONO_PATCH_INFO_ICALL_ADDR: {
3184                                         char *s = get_debug_sym (ji->data.method, "", cache);
3185                                         
3186                                         debug_sym = g_strdup_printf ("plt__icall_native_%s", s);
3187                                         g_free (s);
3188                                         break;
3189                                 }
3190                                 case MONO_PATCH_INFO_JIT_ICALL_ADDR:
3191                                         debug_sym = g_strdup_printf ("plt__jit_icall_native_%s", ji->data.name);
3192                                         break;
3193                                 case MONO_PATCH_INFO_GENERIC_CLASS_INIT:
3194                                         debug_sym = g_strdup_printf ("plt__generic_class_init");
3195                                         break;
3196                                 default:
3197                                         break;
3198                                 }
3199
3200                                 if (debug_sym) {
3201                                         emit_local_symbol (acfg, debug_sym, NULL, TRUE);
3202                                         emit_label (acfg, debug_sym);
3203                                 }
3204                         }
3205                 }
3206
3207                 /* 
3208                  * The first plt entry is used to transfer code to the AOT loader. 
3209                  */
3210                 arch_emit_plt_entry (acfg, i);
3211
3212                 if (debug_sym) {
3213                         emit_symbol_size (acfg, debug_sym, ".");
3214                         g_free (debug_sym);
3215                 }
3216         }
3217
3218         emit_symbol_size (acfg, acfg->plt_symbol, ".");
3219
3220         sprintf (symbol, "plt_end");
3221         emit_global (acfg, symbol, TRUE);
3222         emit_label (acfg, symbol);
3223
3224         g_hash_table_destroy (cache);
3225 }
3226
3227 static G_GNUC_UNUSED void
3228 emit_trampoline (MonoAotCompile *acfg, const char *name, guint8 *code, 
3229                                  guint32 code_size, int got_offset, MonoJumpInfo *ji, GSList *unwind_ops)
3230 {
3231         char start_symbol [256];
3232         char symbol [256];
3233         guint32 buf_size;
3234         MonoJumpInfo *patch_info;
3235         guint8 *buf, *p;
3236         GPtrArray *patches;
3237
3238         /* Emit code */
3239
3240         sprintf (start_symbol, "%s", name);
3241
3242         emit_section_change (acfg, ".text", 0);
3243         emit_global (acfg, start_symbol, TRUE);
3244         emit_alignment (acfg, 16);
3245         emit_label (acfg, start_symbol);
3246
3247         sprintf (symbol, "%snamed_%s", acfg->temp_prefix, name);
3248         emit_label (acfg, symbol);
3249
3250         /* 
3251          * The code should access everything through the GOT, so we pass
3252          * TRUE here.
3253          */
3254         emit_and_reloc_code (acfg, NULL, code, code_size, ji, TRUE);
3255
3256         emit_symbol_size (acfg, start_symbol, ".");
3257
3258         /* Emit info */
3259
3260         /* Sort relocations */
3261         patches = g_ptr_array_new ();
3262         for (patch_info = ji; patch_info; patch_info = patch_info->next)
3263                 if (patch_info->type != MONO_PATCH_INFO_NONE)
3264                         g_ptr_array_add (patches, patch_info);
3265         g_ptr_array_sort (patches, compare_patches);
3266
3267         buf_size = patches->len * 128 + 128;
3268         buf = g_malloc (buf_size);
3269         p = buf;
3270
3271         encode_patch_list (acfg, patches, patches->len, got_offset, p, &p);
3272         g_assert (p - buf < buf_size);
3273
3274         sprintf (symbol, "%s_p", name);
3275
3276         emit_section_change (acfg, ".text", 0);
3277         emit_global (acfg, symbol, FALSE);
3278         emit_label (acfg, symbol);
3279                 
3280         emit_bytes (acfg, buf, p - buf);
3281
3282         /* Emit debug info */
3283         if (unwind_ops) {
3284                 char symbol2 [256];
3285
3286                 sprintf (symbol, "%s", name);
3287                 sprintf (symbol2, "%snamed_%s", acfg->temp_prefix, name);
3288
3289                 if (acfg->dwarf)
3290                         mono_dwarf_writer_emit_trampoline (acfg->dwarf, symbol, symbol2, NULL, NULL, code_size, unwind_ops);
3291         }
3292 }
3293
3294 static void
3295 emit_trampolines (MonoAotCompile *acfg)
3296 {
3297         char symbol [256];
3298         int i, tramp_got_offset;
3299         MonoAotTrampoline ntype;
3300 #ifdef MONO_ARCH_HAVE_FULL_AOT_TRAMPOLINES
3301         int tramp_type;
3302         guint32 code_size;
3303         MonoJumpInfo *ji;
3304         guint8 *code;
3305         GSList *unwind_ops;
3306 #endif
3307
3308         if (!acfg->aot_opts.full_aot)
3309                 return;
3310         
3311         g_assert (acfg->image->assembly);
3312
3313         /* Currently, we only emit most trampolines into the mscorlib AOT image. */
3314         if (strcmp (acfg->image->assembly->aname.name, "mscorlib") == 0) {
3315 #ifdef MONO_ARCH_HAVE_FULL_AOT_TRAMPOLINES
3316                 /*
3317                  * Emit the generic trampolines.
3318                  *
3319                  * We could save some code by treating the generic trampolines as a wrapper
3320                  * method, but that approach has its own complexities, so we choose the simpler
3321                  * method.
3322                  */
3323                 for (tramp_type = 0; tramp_type < MONO_TRAMPOLINE_NUM; ++tramp_type) {
3324                         code = mono_arch_create_trampoline_code_full (tramp_type, &code_size, &ji, &unwind_ops, TRUE);
3325
3326                         /* Emit trampoline code */
3327
3328                         sprintf (symbol, "generic_trampoline_%d", tramp_type);
3329
3330                         emit_trampoline (acfg, symbol, code, code_size, acfg->got_offset, ji, unwind_ops);
3331                 }
3332
3333                 code = mono_arch_get_nullified_class_init_trampoline (&code_size);
3334                 emit_trampoline (acfg, "nullified_class_init_trampoline", code, code_size, acfg->got_offset, NULL, NULL);
3335 #if defined(TARGET_AMD64) && defined(MONO_ARCH_MONITOR_OBJECT_REG)
3336                 code = mono_arch_create_monitor_enter_trampoline_full (&code_size, &ji, TRUE);
3337                 emit_trampoline (acfg, "monitor_enter_trampoline", code, code_size, acfg->got_offset, ji, NULL);
3338                 code = mono_arch_create_monitor_exit_trampoline_full (&code_size, &ji, TRUE);
3339                 emit_trampoline (acfg, "monitor_exit_trampoline", code, code_size, acfg->got_offset, ji, NULL);
3340 #endif
3341
3342                 code = mono_arch_create_generic_class_init_trampoline_full (&code_size, &ji, TRUE);
3343                 emit_trampoline (acfg, "generic_class_init_trampoline", code, code_size, acfg->got_offset, ji, NULL);
3344
3345                 /* Emit the exception related code pieces */
3346                 code = mono_arch_get_restore_context_full (&code_size, &ji, TRUE);
3347                 emit_trampoline (acfg, "restore_context", code, code_size, acfg->got_offset, ji, NULL);
3348                 code = mono_arch_get_call_filter_full (&code_size, &ji, TRUE);
3349                 emit_trampoline (acfg, "call_filter", code, code_size, acfg->got_offset, ji, NULL);
3350                 code = mono_arch_get_throw_exception_full (&code_size, &ji, TRUE);
3351                 emit_trampoline (acfg, "throw_exception", code, code_size, acfg->got_offset, ji, NULL);
3352                 code = mono_arch_get_rethrow_exception_full (&code_size, &ji, TRUE);
3353                 emit_trampoline (acfg, "rethrow_exception", code, code_size, acfg->got_offset, ji, NULL);
3354                 code = mono_arch_get_throw_exception_by_name_full (&code_size, &ji, TRUE);
3355                 emit_trampoline (acfg, "throw_exception_by_name", code, code_size, acfg->got_offset, ji, NULL);
3356                 code = mono_arch_get_throw_corlib_exception_full (&code_size, &ji, TRUE);
3357                 emit_trampoline (acfg, "throw_corlib_exception", code, code_size, acfg->got_offset, ji, NULL);
3358
3359 #if defined(TARGET_AMD64)
3360                 code = mono_arch_get_throw_pending_exception_full (&code_size, &ji, TRUE);
3361                 emit_trampoline (acfg, "throw_pending_exception", code, code_size, acfg->got_offset, ji, NULL);
3362 #endif
3363
3364                 for (i = 0; i < 128; ++i) {
3365                         int offset;
3366
3367                         offset = MONO_RGCTX_SLOT_MAKE_RGCTX (i);
3368                         code = mono_arch_create_rgctx_lazy_fetch_trampoline_full (offset, &code_size, &ji, TRUE);
3369                         sprintf (symbol, "rgctx_fetch_trampoline_%u", offset);
3370                         emit_trampoline (acfg, symbol, code, code_size, acfg->got_offset, ji, NULL);
3371
3372                         offset = MONO_RGCTX_SLOT_MAKE_MRGCTX (i);
3373                         code = mono_arch_create_rgctx_lazy_fetch_trampoline_full (offset, &code_size, &ji, TRUE);
3374                         sprintf (symbol, "rgctx_fetch_trampoline_%u", offset);
3375                         emit_trampoline (acfg, symbol, code, code_size, acfg->got_offset, ji, NULL);
3376                 }
3377
3378                 {
3379                         GSList *l;
3380
3381                         /* delegate_invoke_impl trampolines */
3382                         l = mono_arch_get_delegate_invoke_impls ();
3383                         while (l) {
3384                                 MonoAotTrampInfo *info = l->data;
3385
3386                                 emit_trampoline (acfg, info->name, info->code, info->code_size, acfg->got_offset, NULL, NULL);
3387                                 l = l->next;
3388                         }
3389                 }
3390
3391 #endif /* #ifdef MONO_ARCH_HAVE_FULL_AOT_TRAMPOLINES */
3392
3393                 /* Emit trampolines which are numerous */
3394
3395                 /*
3396                  * These include the following:
3397                  * - specific trampolines
3398                  * - static rgctx invoke trampolines
3399                  * - imt thunks
3400                  * These trampolines have the same code, they are parameterized by GOT 
3401                  * slots. 
3402                  * They are defined in this file, in the arch_... routines instead of
3403                  * in tramp-<ARCH>.c, since it is easier to do it this way.
3404                  */
3405
3406                 /*
3407                  * When running in aot-only mode, we can't create specific trampolines at 
3408                  * runtime, so we create a few, and save them in the AOT file. 
3409                  * Normal trampolines embed their argument as a literal inside the 
3410                  * trampoline code, we can't do that here, so instead we embed an offset
3411                  * which needs to be added to the trampoline address to get the address of
3412                  * the GOT slot which contains the argument value.
3413                  * The generated trampolines jump to the generic trampolines using another
3414                  * GOT slot, which will be setup by the AOT loader to point to the 
3415                  * generic trampoline code of the given type.
3416                  */
3417
3418                 /*
3419                  * FIXME: Maybe we should use more specific trampolines (i.e. one class init for
3420                  * each class).
3421                  */
3422
3423                 emit_section_change (acfg, ".text", 0);
3424
3425                 tramp_got_offset = acfg->got_offset;
3426
3427                 for (ntype = 0; ntype < MONO_AOT_TRAMP_NUM; ++ntype) {
3428                         switch (ntype) {
3429                         case MONO_AOT_TRAMP_SPECIFIC:
3430                                 sprintf (symbol, "specific_trampolines");
3431                                 break;
3432                         case MONO_AOT_TRAMP_STATIC_RGCTX:
3433                                 sprintf (symbol, "static_rgctx_trampolines");
3434                                 break;
3435                         case MONO_AOT_TRAMP_IMT_THUNK:
3436                                 sprintf (symbol, "imt_thunks");
3437                                 break;
3438                         default:
3439                                 g_assert_not_reached ();
3440                         }
3441
3442                         emit_global (acfg, symbol, TRUE);
3443                         emit_alignment (acfg, 16);
3444                         emit_label (acfg, symbol);
3445
3446                         acfg->trampoline_got_offset_base [ntype] = tramp_got_offset;
3447
3448                         for (i = 0; i < acfg->num_trampolines [ntype]; ++i) {
3449                                 int tramp_size = 0;
3450
3451                                 switch (ntype) {
3452                                 case MONO_AOT_TRAMP_SPECIFIC:
3453                                         arch_emit_specific_trampoline (acfg, tramp_got_offset, &tramp_size);
3454                                         tramp_got_offset += 2;
3455                                 break;
3456                                 case MONO_AOT_TRAMP_STATIC_RGCTX:
3457                                         arch_emit_static_rgctx_trampoline (acfg, tramp_got_offset, &tramp_size);                                
3458                                         tramp_got_offset += 2;
3459                                         break;
3460                                 case MONO_AOT_TRAMP_IMT_THUNK:
3461                                         arch_emit_imt_thunk (acfg, tramp_got_offset, &tramp_size);
3462                                         tramp_got_offset += 1;
3463                                         break;
3464                                 default:
3465                                         g_assert_not_reached ();
3466                                 }
3467
3468                                 if (!acfg->trampoline_size [ntype]) {
3469                                         g_assert (tramp_size);
3470                                         acfg->trampoline_size [ntype] = tramp_size;
3471                                 }
3472                         }
3473                 }
3474
3475                 /* Reserve some entries at the end of the GOT for our use */
3476                 acfg->num_trampoline_got_entries = tramp_got_offset - acfg->got_offset;
3477         }
3478
3479         acfg->got_offset += acfg->num_trampoline_got_entries;
3480 }
3481
3482 static gboolean
3483 str_begins_with (const char *str1, const char *str2)
3484 {
3485         int len = strlen (str2);
3486         return strncmp (str1, str2, len) == 0;
3487 }
3488
3489 static void
3490 mono_aot_parse_options (const char *aot_options, MonoAotOptions *opts)
3491 {
3492         gchar **args, **ptr;
3493
3494         args = g_strsplit (aot_options ? aot_options : "", ",", -1);
3495         for (ptr = args; ptr && *ptr; ptr ++) {
3496                 const char *arg = *ptr;
3497
3498                 if (str_begins_with (arg, "outfile=")) {
3499                         opts->outfile = g_strdup (arg + strlen ("outfile="));
3500                 } else if (str_begins_with (arg, "save-temps")) {
3501                         opts->save_temps = TRUE;
3502                 } else if (str_begins_with (arg, "keep-temps")) {
3503                         opts->save_temps = TRUE;
3504                 } else if (str_begins_with (arg, "write-symbols")) {
3505                         opts->write_symbols = TRUE;
3506                 } else if (str_begins_with (arg, "metadata-only")) {
3507                         opts->metadata_only = TRUE;
3508                 } else if (str_begins_with (arg, "bind-to-runtime-version")) {
3509                         opts->bind_to_runtime_version = TRUE;
3510                 } else if (str_begins_with (arg, "full")) {
3511                         opts->full_aot = TRUE;
3512                 } else if (str_begins_with (arg, "threads=")) {
3513                         opts->nthreads = atoi (arg + strlen ("threads="));
3514                 } else if (str_begins_with (arg, "static")) {
3515                         opts->static_link = TRUE;
3516                         opts->no_dlsym = TRUE;
3517                 } else if (str_begins_with (arg, "asmonly")) {
3518                         opts->asm_only = TRUE;
3519                 } else if (str_begins_with (arg, "asmwriter")) {
3520                         opts->asm_writer = TRUE;
3521                 } else if (str_begins_with (arg, "nodebug")) {
3522                         opts->nodebug = TRUE;
3523                 } else if (str_begins_with (arg, "ntrampolines=")) {
3524                         opts->ntrampolines = atoi (arg + strlen ("ntrampolines="));
3525                 } else if (str_begins_with (arg, "tool-prefix=")) {
3526                         opts->tool_prefix = g_strdup (arg + strlen ("tool-prefix="));
3527                 } else {
3528                         fprintf (stderr, "AOT : Unknown argument '%s'.\n", arg);
3529                         exit (1);
3530                 }
3531         }
3532
3533         g_strfreev (args);
3534 }
3535
3536 static void
3537 add_token_info_hash (gpointer key, gpointer value, gpointer user_data)
3538 {
3539         MonoMethod *method = (MonoMethod*)key;
3540         MonoJumpInfoToken *ji = (MonoJumpInfoToken*)value;
3541         MonoJumpInfoToken *new_ji = g_new0 (MonoJumpInfoToken, 1);
3542         MonoAotCompile *acfg = user_data;
3543
3544         new_ji->image = ji->image;
3545         new_ji->token = ji->token;
3546         g_hash_table_insert (acfg->token_info_hash, method, new_ji);
3547 }
3548
3549 static gboolean
3550 can_encode_class (MonoAotCompile *acfg, MonoClass *klass)
3551 {
3552         if (klass->type_token)
3553                 return TRUE;
3554         if ((klass->byval_arg.type == MONO_TYPE_VAR) || (klass->byval_arg.type == MONO_TYPE_MVAR))
3555                 return TRUE;
3556         if (klass->rank)
3557                 return can_encode_class (acfg, klass->element_class);
3558         return FALSE;
3559 }
3560
3561 static gboolean
3562 can_encode_patch (MonoAotCompile *acfg, MonoJumpInfo *patch_info)
3563 {
3564         switch (patch_info->type) {
3565         case MONO_PATCH_INFO_METHOD:
3566         case MONO_PATCH_INFO_METHODCONST: {
3567                 MonoMethod *method = patch_info->data.method;
3568
3569                 if (method->wrapper_type) {
3570                         switch (method->wrapper_type) {
3571                         case MONO_WRAPPER_NONE:
3572                         case MONO_WRAPPER_REMOTING_INVOKE_WITH_CHECK:
3573                         case MONO_WRAPPER_XDOMAIN_INVOKE:
3574                         case MONO_WRAPPER_STFLD:
3575                         case MONO_WRAPPER_LDFLD:
3576                         case MONO_WRAPPER_LDFLDA:
3577                         case MONO_WRAPPER_LDFLD_REMOTE:
3578                         case MONO_WRAPPER_STFLD_REMOTE:
3579                         case MONO_WRAPPER_STELEMREF:
3580                         case MONO_WRAPPER_ISINST:
3581                         case MONO_WRAPPER_PROXY_ISINST:
3582                         case MONO_WRAPPER_ALLOC:
3583                         case MONO_WRAPPER_REMOTING_INVOKE:
3584                         case MONO_WRAPPER_UNKNOWN:
3585                                 break;
3586                         default:
3587                                 //printf ("Skip (wrapper call): %d -> %s\n", patch_info->type, mono_method_full_name (patch_info->data.method, TRUE));
3588                                 return FALSE;
3589                         }
3590                 } else {
3591                         if (!method->token) {
3592                                 /* The method is part of a constructed type like Int[,].Set (). */
3593                                 if (!g_hash_table_lookup (acfg->token_info_hash, method)) {
3594                                         if (method->klass->rank)
3595                                                 return TRUE;
3596                                         return FALSE;
3597                                 }
3598                         }
3599                 }
3600                 break;
3601         }
3602         case MONO_PATCH_INFO_VTABLE:
3603         case MONO_PATCH_INFO_CLASS_INIT:
3604         case MONO_PATCH_INFO_DELEGATE_TRAMPOLINE:
3605         case MONO_PATCH_INFO_CLASS:
3606         case MONO_PATCH_INFO_IID:
3607         case MONO_PATCH_INFO_ADJUSTED_IID:
3608                 if (!can_encode_class (acfg, patch_info->data.klass)) {
3609                         //printf ("Skip: %s\n", mono_type_full_name (&patch_info->data.klass->byval_arg));
3610                         return FALSE;
3611                 }
3612                 break;
3613         case MONO_PATCH_INFO_RGCTX_FETCH: {
3614                 MonoJumpInfoRgctxEntry *entry = patch_info->data.rgctx_entry;
3615
3616                 if (!can_encode_patch (acfg, entry->data))
3617                         return FALSE;
3618                 break;
3619         }
3620         default:
3621                 break;
3622         }
3623
3624         return TRUE;
3625 }
3626
3627 static void
3628 add_generic_class (MonoAotCompile *acfg, MonoClass *klass);
3629
3630 /*
3631  * compile_method:
3632  *
3633  *   AOT compile a given method.
3634  * This function might be called by multiple threads, so it must be thread-safe.
3635  */
3636 static void
3637 compile_method (MonoAotCompile *acfg, MonoMethod *method)
3638 {
3639         MonoCompile *cfg;
3640         MonoJumpInfo *patch_info;
3641         gboolean skip;
3642         int index;
3643         MonoMethod *wrapped;
3644
3645         if (acfg->aot_opts.metadata_only)
3646                 return;
3647
3648         mono_acfg_lock (acfg);
3649         index = get_method_index (acfg, method);
3650         mono_acfg_unlock (acfg);
3651
3652         /* fixme: maybe we can also precompile wrapper methods */
3653         if ((method->flags & METHOD_ATTRIBUTE_PINVOKE_IMPL) ||
3654                 (method->iflags & METHOD_IMPL_ATTRIBUTE_RUNTIME) ||
3655                 (method->flags & METHOD_ATTRIBUTE_ABSTRACT)) {
3656                 //printf ("Skip (impossible): %s\n", mono_method_full_name (method, TRUE));
3657                 return;
3658         }
3659
3660         if (method->iflags & METHOD_IMPL_ATTRIBUTE_INTERNAL_CALL)
3661                 return;
3662
3663         wrapped = mono_marshal_method_from_wrapper (method);
3664         if (wrapped && (wrapped->iflags & METHOD_IMPL_ATTRIBUTE_INTERNAL_CALL) && wrapped->is_generic)
3665                 // FIXME: The wrapper should be generic too, but it is not
3666                 return;
3667
3668         InterlockedIncrement (&acfg->stats.mcount);
3669
3670 #if 0
3671         if (method->is_generic || method->klass->generic_container) {
3672                 InterlockedIncrement (&acfg->stats.genericcount);
3673                 return;
3674         }
3675 #endif
3676
3677         //acfg->aot_opts.print_skipped_methods = TRUE;
3678
3679         /*
3680          * Since these methods are the only ones which are compiled with
3681          * AOT support, and they are not used by runtime startup/shutdown code,
3682          * the runtime will not see AOT methods during AOT compilation,so it
3683          * does not need to support them by creating a fake GOT etc.
3684          */
3685         cfg = mini_method_compile (method, acfg->opts, mono_get_root_domain (), FALSE, TRUE, 0);
3686         if (cfg->exception_type == MONO_EXCEPTION_GENERIC_SHARING_FAILED) {
3687                 //printf ("F: %s\n", mono_method_full_name (method, TRUE));
3688                 InterlockedIncrement (&acfg->stats.genericcount);
3689                 return;
3690         }
3691         if (cfg->exception_type != MONO_EXCEPTION_NONE) {
3692                 /* Let the exception happen at runtime */
3693                 return;
3694         }
3695
3696         if (cfg->disable_aot) {
3697                 if (acfg->aot_opts.print_skipped_methods)
3698                         printf ("Skip (disabled): %s\n", mono_method_full_name (method, TRUE));
3699                 InterlockedIncrement (&acfg->stats.ocount);
3700                 mono_destroy_compile (cfg);
3701                 return;
3702         }
3703
3704         /* Nullify patches which need no aot processing */
3705         for (patch_info = cfg->patch_info; patch_info; patch_info = patch_info->next) {
3706                 switch (patch_info->type) {
3707                 case MONO_PATCH_INFO_LABEL:
3708                 case MONO_PATCH_INFO_BB:
3709                         patch_info->type = MONO_PATCH_INFO_NONE;
3710                         break;
3711                 default:
3712                         break;
3713                 }
3714         }
3715
3716         /* Collect method->token associations from the cfg */
3717         mono_acfg_lock (acfg);
3718         g_hash_table_foreach (cfg->token_info_hash, add_token_info_hash, acfg);
3719         mono_acfg_unlock (acfg);
3720
3721         /*
3722          * Check for absolute addresses.
3723          */
3724         skip = FALSE;
3725         for (patch_info = cfg->patch_info; patch_info; patch_info = patch_info->next) {
3726                 switch (patch_info->type) {
3727                 case MONO_PATCH_INFO_ABS:
3728                         /* unable to handle this */
3729                         skip = TRUE;    
3730                         break;
3731                 default:
3732                         break;
3733                 }
3734         }
3735
3736         if (skip) {
3737                 if (acfg->aot_opts.print_skipped_methods)
3738                         printf ("Skip (abs call): %s\n", mono_method_full_name (method, TRUE));
3739                 InterlockedIncrement (&acfg->stats.abscount);
3740                 mono_destroy_compile (cfg);
3741                 return;
3742         }
3743
3744         /* Lock for the rest of the code */
3745         mono_acfg_lock (acfg);
3746
3747         /*
3748          * Check for methods/klasses we can't encode.
3749          */
3750         skip = FALSE;
3751         for (patch_info = cfg->patch_info; patch_info; patch_info = patch_info->next) {
3752                 if (!can_encode_patch (acfg, patch_info))
3753                         skip = TRUE;
3754         }
3755
3756         if (skip) {
3757                 if (acfg->aot_opts.print_skipped_methods)
3758                         printf ("Skip (patches): %s\n", mono_method_full_name (method, TRUE));
3759                 acfg->stats.ocount++;
3760                 mono_destroy_compile (cfg);
3761                 mono_acfg_unlock (acfg);
3762                 return;
3763         }
3764
3765         /* Adds generic instances referenced by this method */
3766         for (patch_info = cfg->patch_info; patch_info; patch_info = patch_info->next) {
3767                 switch (patch_info->type) {
3768                 case MONO_PATCH_INFO_METHOD: {
3769                         MonoMethod *m = patch_info->data.method;
3770                         if (m->is_inflated) {
3771                                 if (!(mono_class_generic_sharing_enabled (m->klass) &&
3772                                           mono_method_is_generic_sharable_impl (m, FALSE)) &&
3773                                         !method_has_type_vars (m)) {
3774                                         if (m->iflags & METHOD_IMPL_ATTRIBUTE_INTERNAL_CALL) {
3775                                                 if (acfg->aot_opts.full_aot)
3776                                                         add_extra_method (acfg, mono_marshal_get_native_wrapper (m, TRUE, TRUE));
3777                                         } else {
3778                                                 add_extra_method (acfg, m);
3779                                         }
3780                                 }
3781                                 add_generic_class (acfg, m->klass);
3782                         }
3783                         break;
3784                 }
3785                 case MONO_PATCH_INFO_VTABLE: {
3786                         MonoClass *klass = patch_info->data.klass;
3787
3788                         if (klass->generic_class && !mono_generic_context_is_sharable (&klass->generic_class->context, FALSE))
3789                                 add_generic_class (acfg, klass);
3790                         break;
3791                 }
3792                 default:
3793                         break;
3794                 }
3795         }
3796
3797         /* Determine whenever the method has GOT slots */
3798         for (patch_info = cfg->patch_info; patch_info; patch_info = patch_info->next) {
3799                 switch (patch_info->type) {
3800                 case MONO_PATCH_INFO_GOT_OFFSET:
3801                 case MONO_PATCH_INFO_NONE:
3802                         break;
3803                 case MONO_PATCH_INFO_IMAGE:
3804                         /* The assembly is stored in GOT slot 0 */
3805                         if (patch_info->data.image != acfg->image)
3806                                 cfg->has_got_slots = TRUE;
3807                         break;
3808                 default:
3809                         if (!is_plt_patch (patch_info))
3810                                 cfg->has_got_slots = TRUE;
3811                         break;
3812                 }
3813         }
3814
3815         if (!cfg->has_got_slots)
3816                 InterlockedIncrement (&acfg->stats.methods_without_got_slots);
3817
3818         /* Make a copy of the patch info which is in the mempool */
3819         {
3820                 MonoJumpInfo *patches = NULL, *patches_end = NULL;
3821
3822                 for (patch_info = cfg->patch_info; patch_info; patch_info = patch_info->next) {
3823                         MonoJumpInfo *new_patch_info = mono_patch_info_dup_mp (acfg->mempool, patch_info);
3824
3825                         if (!patches)
3826                                 patches = new_patch_info;
3827                         else
3828                                 patches_end->next = new_patch_info;
3829                         patches_end = new_patch_info;
3830                 }
3831                 cfg->patch_info = patches;
3832         }
3833         /* Make a copy of the unwind info */
3834         {
3835                 GSList *l, *unwind_ops;
3836                 MonoUnwindOp *op;
3837
3838                 unwind_ops = NULL;
3839                 for (l = cfg->unwind_ops; l; l = l->next) {
3840                         op = mono_mempool_alloc (acfg->mempool, sizeof (MonoUnwindOp));
3841                         memcpy (op, l->data, sizeof (MonoUnwindOp));
3842                         unwind_ops = g_slist_prepend_mempool (acfg->mempool, unwind_ops, op);
3843                 }
3844                 cfg->unwind_ops = g_slist_reverse (unwind_ops);
3845         }
3846         /* Make a copy of the argument/local info */
3847         {
3848                 MonoInst **args, **locals;
3849                 MonoMethodSignature *sig;
3850                 MonoMethodHeader *header;
3851                 int i;
3852                 
3853                 sig = mono_method_signature (method);
3854                 args = mono_mempool_alloc (acfg->mempool, sizeof (MonoInst*) * (sig->param_count + sig->hasthis));
3855                 for (i = 0; i < sig->param_count + sig->hasthis; ++i) {
3856                         args [i] = mono_mempool_alloc (acfg->mempool, sizeof (MonoInst));
3857                         memcpy (args [i], cfg->args [i], sizeof (MonoInst));
3858                 }
3859                 cfg->args = args;
3860
3861                 header = mono_method_get_header (method);
3862                 locals = mono_mempool_alloc (acfg->mempool, sizeof (MonoInst*) * header->num_locals);
3863                 for (i = 0; i < header->num_locals; ++i) {
3864                         locals [i] = mono_mempool_alloc (acfg->mempool, sizeof (MonoInst));
3865                         memcpy (locals [i], cfg->locals [i], sizeof (MonoInst));
3866                 }
3867                 cfg->locals = locals;
3868         }
3869
3870         /* Free some fields used by cfg to conserve memory */
3871         mono_mempool_destroy (cfg->mempool);
3872         cfg->mempool = NULL;
3873         g_free (cfg->varinfo);
3874         cfg->varinfo = NULL;
3875         g_free (cfg->vars);
3876         cfg->vars = NULL;
3877         if (cfg->rs) {
3878                 mono_regstate_free (cfg->rs);
3879                 cfg->rs = NULL;
3880         }
3881
3882         //printf ("Compile:           %s\n", mono_method_full_name (method, TRUE));
3883
3884         while (index >= acfg->cfgs_size) {
3885                 MonoCompile **new_cfgs;
3886                 int new_size;
3887
3888                 new_size = acfg->cfgs_size * 2;
3889                 new_cfgs = g_new0 (MonoCompile*, new_size);
3890                 memcpy (new_cfgs, acfg->cfgs, sizeof (MonoCompile*) * acfg->cfgs_size);
3891                 g_free (acfg->cfgs);
3892                 acfg->cfgs = new_cfgs;
3893                 acfg->cfgs_size = new_size;
3894         }
3895         acfg->cfgs [index] = cfg;
3896
3897         g_hash_table_insert (acfg->method_to_cfg, cfg->orig_method, cfg);
3898
3899         /*
3900         if (cfg->orig_method->wrapper_type)
3901                 g_ptr_array_add (acfg->extra_methods, cfg->orig_method);
3902         */
3903
3904         mono_acfg_unlock (acfg);
3905
3906         InterlockedIncrement (&acfg->stats.ccount);
3907 }
3908  
3909 static void
3910 compile_thread_main (gpointer *user_data)
3911 {
3912         MonoDomain *domain = user_data [0];
3913         MonoAotCompile *acfg = user_data [1];
3914         GPtrArray *methods = user_data [2];
3915         int i;
3916
3917         mono_thread_attach (domain);
3918
3919         for (i = 0; i < methods->len; ++i)
3920                 compile_method (acfg, g_ptr_array_index (methods, i));
3921 }
3922
3923 static void
3924 load_profile_files (MonoAotCompile *acfg)
3925 {
3926         FILE *infile;
3927         char *tmp;
3928         int file_index, res, method_index, i;
3929         char ver [256];
3930         guint32 token;
3931         GList *unordered;
3932
3933         file_index = 0;
3934         while (TRUE) {
3935                 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);
3936
3937                 if (!g_file_test (tmp, G_FILE_TEST_IS_REGULAR)) {
3938                         g_free (tmp);
3939                         break;
3940                 }
3941
3942                 infile = fopen (tmp, "r");
3943                 g_assert (infile);
3944
3945                 printf ("Using profile data file '%s'\n", tmp);
3946                 g_free (tmp);
3947
3948                 file_index ++;
3949
3950                 res = fscanf (infile, "%32s\n", ver);
3951                 if ((res != 1) || strcmp (ver, "#VER:1") != 0) {
3952                         printf ("Profile file has wrong version or invalid.\n");
3953                         fclose (infile);
3954                         continue;
3955                 }
3956
3957                 while (TRUE) {
3958                         res = fscanf (infile, "%d\n", &token);
3959                         if (res < 1)
3960                                 break;
3961
3962                         method_index = mono_metadata_token_index (token) - 1;
3963
3964                         if (!g_list_find (acfg->method_order, GUINT_TO_POINTER (method_index)))
3965                                 acfg->method_order = g_list_append (acfg->method_order, GUINT_TO_POINTER (method_index));
3966                 }
3967                 fclose (infile);
3968         }
3969
3970         /* Add missing methods */
3971         unordered = NULL;
3972         for (i = 0; i < acfg->image->tables [MONO_TABLE_METHOD].rows; ++i) {
3973                 if (!g_list_find (acfg->method_order, GUINT_TO_POINTER (i)))
3974                         unordered = g_list_prepend (unordered, GUINT_TO_POINTER (i));
3975         }
3976         unordered = g_list_reverse (unordered);
3977         if (acfg->method_order)
3978                 g_list_last (acfg->method_order)->next = unordered;
3979         else
3980                 acfg->method_order = unordered;
3981 }
3982
3983 static void
3984 emit_code (MonoAotCompile *acfg)
3985 {
3986         int i;
3987         char symbol [256];
3988         GList *l;
3989
3990 #if defined(TARGET_POWERPC64)
3991         sprintf (symbol, ".Lgot_addr");
3992         emit_section_change (acfg, ".text", 0);
3993         emit_alignment (acfg, 8);
3994         emit_label (acfg, symbol);
3995         emit_pointer (acfg, acfg->got_symbol);
3996 #endif
3997
3998         sprintf (symbol, "methods");
3999         emit_section_change (acfg, ".text", 0);
4000         emit_global (acfg, symbol, TRUE);
4001         emit_alignment (acfg, 8);
4002         emit_label (acfg, symbol);
4003
4004         /* 
4005          * Emit some padding so the local symbol for the first method doesn't have the
4006          * same address as 'methods'.
4007          */
4008         emit_zero_bytes (acfg, 16);
4009
4010         for (l = acfg->method_order; l != NULL; l = l->next) {
4011                 i = GPOINTER_TO_UINT (l->data);
4012
4013                 if (acfg->cfgs [i])
4014                         emit_method_code (acfg, acfg->cfgs [i]);
4015         }
4016
4017         sprintf (symbol, "methods_end");
4018         emit_section_change (acfg, ".text", 0);
4019         emit_global (acfg, symbol, FALSE);
4020         emit_alignment (acfg, 8);
4021         emit_label (acfg, symbol);
4022
4023         sprintf (symbol, "method_offsets");
4024         emit_section_change (acfg, ".text", 1);
4025         emit_global (acfg, symbol, FALSE);
4026         emit_alignment (acfg, 8);
4027         emit_label (acfg, symbol);
4028
4029         for (i = 0; i < acfg->nmethods; ++i) {
4030                 if (acfg->cfgs [i]) {
4031                         sprintf (symbol, "%sm_%x", acfg->temp_prefix, i);
4032                         emit_symbol_diff (acfg, symbol, "methods", 0);
4033                 } else {
4034                         emit_int32 (acfg, 0xffffffff);
4035                 }
4036         }
4037         emit_line (acfg);
4038 }
4039
4040 static void
4041 emit_info (MonoAotCompile *acfg)
4042 {
4043         int i;
4044         char symbol [256];
4045         GList *l;
4046
4047         /* Emit method info */
4048         sprintf (symbol, "method_info");
4049         emit_section_change (acfg, ".text", 1);
4050         emit_global (acfg, symbol, FALSE);
4051         emit_alignment (acfg, 8);
4052         emit_label (acfg, symbol);
4053
4054         /* To reduce size of generated assembly code */
4055         sprintf (symbol, "mi");
4056         emit_label (acfg, symbol);
4057
4058         for (l = acfg->method_order; l != NULL; l = l->next) {
4059                 i = GPOINTER_TO_UINT (l->data);
4060
4061                 if (acfg->cfgs [i])
4062                         emit_method_info (acfg, acfg->cfgs [i]);
4063         }
4064
4065         sprintf (symbol, "method_info_offsets");
4066         emit_section_change (acfg, ".text", 1);
4067         emit_global (acfg, symbol, FALSE);
4068         emit_alignment (acfg, 8);
4069         emit_label (acfg, symbol);
4070
4071         for (i = 0; i < acfg->nmethods; ++i) {
4072                 if (acfg->cfgs [i]) {
4073                         sprintf (symbol, "%sm_%x_p", acfg->temp_prefix, i);
4074                         emit_symbol_diff (acfg, symbol, "mi", 0);
4075                 } else {
4076                         emit_int32 (acfg, 0);
4077                 }
4078         }
4079         emit_line (acfg);
4080 }
4081
4082 #endif /* #if !defined(DISABLE_AOT) && !defined(DISABLE_JIT) */
4083
4084 /*
4085  * mono_aot_str_hash:
4086  *
4087  * Hash function for strings which we use to hash strings for things which are
4088  * saved in the AOT image, since g_str_hash () can change.
4089  */
4090 guint
4091 mono_aot_str_hash (gconstpointer v1)
4092 {
4093         /* Same as g_str_hash () in glib */
4094         char *p = (char *) v1;
4095         guint hash = *p;
4096
4097         while (*p++) {
4098                 if (*p)
4099                         hash = (hash << 5) - hash + *p;
4100         }
4101
4102         return hash;
4103
4104
4105 #define rot(x,k) (((x)<<(k)) | ((x)>>(32-(k))))
4106 #define mix(a,b,c) { \
4107         a -= c;  a ^= rot(c, 4);  c += b; \
4108         b -= a;  b ^= rot(a, 6);  a += c; \
4109         c -= b;  c ^= rot(b, 8);  b += a; \
4110         a -= c;  a ^= rot(c,16);  c += b; \
4111         b -= a;  b ^= rot(a,19);  a += c; \
4112         c -= b;  c ^= rot(b, 4);  b += a; \
4113 }
4114 #define final(a,b,c) { \
4115         c ^= b; c -= rot(b,14); \
4116         a ^= c; a -= rot(c,11); \
4117         b ^= a; b -= rot(a,25); \
4118         c ^= b; c -= rot(b,16); \
4119         a ^= c; a -= rot(c,4);  \
4120         b ^= a; b -= rot(a,14); \
4121         c ^= b; c -= rot(b,24); \
4122 }
4123
4124 static guint
4125 mono_aot_type_hash (MonoType *t1)
4126 {
4127         guint hash = t1->type;
4128
4129         hash |= t1->byref << 6; /* do not collide with t1->type values */
4130         switch (t1->type) {
4131         case MONO_TYPE_VALUETYPE:
4132         case MONO_TYPE_CLASS:
4133         case MONO_TYPE_SZARRAY:
4134                 /* check if the distribution is good enough */
4135                 return ((hash << 5) - hash) ^ mono_aot_str_hash (t1->data.klass->name);
4136         case MONO_TYPE_PTR:
4137                 return ((hash << 5) - hash) ^ mono_aot_type_hash (t1->data.type);
4138         case MONO_TYPE_ARRAY:
4139                 return ((hash << 5) - hash) ^ mono_aot_type_hash (&t1->data.array->eklass->byval_arg);
4140         case MONO_TYPE_GENERICINST:
4141                 return ((hash << 5) - hash) ^ 0;
4142         }
4143         return hash;
4144 }
4145
4146 /*
4147  * mono_aot_method_hash:
4148  *
4149  *   Return a hash code for methods which only depends on metadata.
4150  */
4151 guint32
4152 mono_aot_method_hash (MonoMethod *method)
4153 {
4154         MonoMethodSignature *sig;
4155         MonoClass *klass;
4156         int i;
4157         int hashes_count;
4158         guint32 *hashes_start, *hashes;
4159         guint32 a, b, c;
4160
4161         /* Similar to the hash in mono_method_get_imt_slot () */
4162
4163         sig = mono_method_signature (method);
4164
4165         hashes_count = sig->param_count + 5;
4166         hashes_start = malloc (hashes_count * sizeof (guint32));
4167         hashes = hashes_start;
4168
4169         /* Some wrappers are assigned to random classes */
4170         if (!method->wrapper_type || method->wrapper_type == MONO_WRAPPER_REMOTING_INVOKE_WITH_CHECK)
4171                 klass = method->klass;
4172         else
4173                 klass = mono_defaults.object_class;
4174
4175         if (!method->wrapper_type) {
4176                 char *full_name = mono_type_full_name (&klass->byval_arg);
4177
4178                 hashes [0] = mono_aot_str_hash (full_name);
4179                 hashes [1] = 0;
4180                 g_free (full_name);
4181         } else {
4182                 hashes [0] = mono_aot_str_hash (klass->name);
4183                 hashes [1] = mono_aot_str_hash (klass->name_space);
4184         }
4185         hashes [2] = mono_aot_str_hash (method->name);
4186         hashes [3] = method->wrapper_type;
4187         hashes [4] = mono_aot_type_hash (sig->ret);
4188         for (i = 0; i < sig->param_count; i++) {
4189                 hashes [5 + i] = mono_aot_type_hash (sig->params [i]);
4190         }
4191         
4192         /* Setup internal state */
4193         a = b = c = 0xdeadbeef + (((guint32)hashes_count)<<2);
4194
4195         /* Handle most of the hashes */
4196         while (hashes_count > 3) {
4197                 a += hashes [0];
4198                 b += hashes [1];
4199                 c += hashes [2];
4200                 mix (a,b,c);
4201                 hashes_count -= 3;
4202                 hashes += 3;
4203         }
4204
4205         /* Handle the last 3 hashes (all the case statements fall through) */
4206         switch (hashes_count) { 
4207         case 3 : c += hashes [2];
4208         case 2 : b += hashes [1];
4209         case 1 : a += hashes [0];
4210                 final (a,b,c);
4211         case 0: /* nothing left to add */
4212                 break;
4213         }
4214         
4215         free (hashes_start);
4216         
4217         return c;
4218 }
4219 #undef rot
4220 #undef mix
4221 #undef final
4222
4223 /*
4224  * mono_aot_wrapper_name:
4225  *
4226  *   Return a string which uniqely identifies the given wrapper method.
4227  */
4228 char*
4229 mono_aot_wrapper_name (MonoMethod *method)
4230 {
4231         char *name, *tmpsig, *klass_desc;
4232
4233         tmpsig = mono_signature_get_desc (mono_method_signature (method), TRUE);
4234
4235         switch (method->wrapper_type) {
4236         case MONO_WRAPPER_RUNTIME_INVOKE:
4237                 if (!strcmp (method->name, "runtime_invoke_dynamic"))
4238                         name = g_strdup_printf ("(wrapper runtime-invoke-dynamic)");
4239                 else
4240                         name = g_strdup_printf ("%s (%s)", method->name, tmpsig);
4241                 break;
4242         case MONO_WRAPPER_DELEGATE_INVOKE:
4243         case MONO_WRAPPER_DELEGATE_BEGIN_INVOKE:
4244         case MONO_WRAPPER_DELEGATE_END_INVOKE:
4245                 /* This is a hack to work around the fact that these wrappers get assigned to some random class */
4246                 name = g_strdup_printf ("%s (%s)", method->name, tmpsig);
4247                 break;
4248         default:
4249                 klass_desc = mono_type_full_name (&method->klass->byval_arg);
4250
4251                 name = g_strdup_printf ("%s:%s (%s)", klass_desc, method->name, tmpsig);
4252                 break;
4253         }
4254
4255         g_free (tmpsig);
4256
4257         return name;
4258 }
4259
4260 /*
4261  * mono_aot_tramp_info_create:
4262  *
4263  *   Create a MonoAotTrampInfo structure from the arguments.
4264  */
4265 MonoAotTrampInfo*
4266 mono_aot_tramp_info_create (const char *name, guint8 *code, guint32 code_size)
4267 {
4268         MonoAotTrampInfo *info = g_new0 (MonoAotTrampInfo, 1);
4269
4270         info->name = (char*)name;
4271         info->code = code;
4272         info->code_size = code_size;
4273
4274         return info;
4275 }
4276
4277 #if !defined(DISABLE_AOT) && !defined(DISABLE_JIT)
4278
4279 typedef struct HashEntry {
4280     guint32 key, value, index;
4281         struct HashEntry *next;
4282 } HashEntry;
4283
4284 /*
4285  * emit_extra_methods:
4286  *
4287  * Emit methods which are not in the METHOD table, like wrappers.
4288  */
4289 static void
4290 emit_extra_methods (MonoAotCompile *acfg)
4291 {
4292         int i, table_size, buf_size;
4293         char symbol [256];
4294         guint8 *p, *buf;
4295         guint32 *info_offsets;
4296         guint32 hash;
4297         GPtrArray *table;
4298         HashEntry *entry, *new_entry;
4299         int nmethods, max_chain_length;
4300         int *chain_lengths;
4301
4302         info_offsets = g_new0 (guint32, acfg->extra_methods->len);
4303
4304         buf_size = acfg->extra_methods->len * 256 + 256;
4305         p = buf = g_malloc (buf_size);
4306
4307         /* Encode method info */
4308         nmethods = 0;
4309         /* So offsets are > 0 */
4310         *p = 0;
4311         p++;
4312         for (i = 0; i < acfg->extra_methods->len; ++i) {
4313                 MonoMethod *method = g_ptr_array_index (acfg->extra_methods, i);
4314                 MonoCompile *cfg = g_hash_table_lookup (acfg->method_to_cfg, method);
4315                 char *name;
4316
4317                 if (!cfg)
4318                         continue;
4319
4320                 nmethods ++;
4321                 info_offsets [i] = p - buf;
4322
4323                 name = NULL;
4324                 if (method->wrapper_type) {
4325                         /* 
4326                          * We encode some wrappers using their name, since encoding them
4327                          * directly would be difficult. This also avoids creating the wrapper
4328                          * methods at runtime, since they are not needed anyway.
4329                          */
4330                         switch (method->wrapper_type) {
4331                         case MONO_WRAPPER_REMOTING_INVOKE_WITH_CHECK:
4332                         case MONO_WRAPPER_SYNCHRONIZED:
4333                                 /* encode_method_ref () can handle these */
4334                                 break;
4335                         case MONO_WRAPPER_RUNTIME_INVOKE:
4336                                 if (mono_marshal_method_from_wrapper (method) != method && !strstr (method->name, "virtual"))
4337                                         /* Direct wrapper, encode normally */
4338                                         break;
4339                                 /* Fall through */
4340                         default:
4341                                 name = mono_aot_wrapper_name (method);
4342                                 break;
4343                         }
4344                 }
4345
4346                 if (name) {
4347                         encode_value (1, p, &p);
4348                         encode_value (method->wrapper_type, p, &p);
4349                         strcpy ((char*)p, name);
4350                         p += strlen (name ) + 1;
4351                         g_free (name);
4352                 } else {
4353                         encode_value (0, p, &p);
4354                         encode_method_ref (acfg, method, p, &p);
4355                 }
4356
4357                 g_assert ((p - buf) < buf_size);
4358         }
4359
4360         g_assert ((p - buf) < buf_size);
4361
4362         /* Emit method info */
4363         sprintf (symbol, "extra_method_info");
4364         emit_section_change (acfg, ".text", 1);
4365         emit_global (acfg, symbol, FALSE);
4366         emit_alignment (acfg, 8);
4367         emit_label (acfg, symbol);
4368
4369         emit_bytes (acfg, buf, p - buf);
4370
4371         emit_line (acfg);
4372
4373         /*
4374          * Construct a chained hash table for mapping indexes in extra_method_info to
4375          * method indexes.
4376          */
4377         table_size = g_spaced_primes_closest ((int)(nmethods * 1.5));
4378         table = g_ptr_array_sized_new (table_size);
4379         for (i = 0; i < table_size; ++i)
4380                 g_ptr_array_add (table, NULL);
4381         chain_lengths = g_new0 (int, table_size);
4382         max_chain_length = 0;
4383         for (i = 0; i < acfg->extra_methods->len; ++i) {
4384                 MonoMethod *method = g_ptr_array_index (acfg->extra_methods, i);
4385                 MonoCompile *cfg = g_hash_table_lookup (acfg->method_to_cfg, method);
4386                 guint32 key, value;
4387
4388                 if (!cfg)
4389                         continue;
4390
4391                 key = info_offsets [i];
4392                 value = get_method_index (acfg, method);
4393
4394                 hash = mono_aot_method_hash (method) % table_size;
4395
4396                 chain_lengths [hash] ++;
4397                 max_chain_length = MAX (max_chain_length, chain_lengths [hash]);
4398
4399                 /* FIXME: Allocate from the mempool */
4400                 new_entry = g_new0 (HashEntry, 1);
4401                 new_entry->key = key;
4402                 new_entry->value = value;
4403
4404                 entry = g_ptr_array_index (table, hash);
4405                 if (entry == NULL) {
4406                         new_entry->index = hash;
4407                         g_ptr_array_index (table, hash) = new_entry;
4408                 } else {
4409                         while (entry->next)
4410                                 entry = entry->next;
4411                         
4412                         entry->next = new_entry;
4413                         new_entry->index = table->len;
4414                         g_ptr_array_add (table, new_entry);
4415                 }
4416         }
4417
4418         //printf ("MAX: %d\n", max_chain_length);
4419
4420         /* Emit the table */
4421         sprintf (symbol, "extra_method_table");
4422         emit_section_change (acfg, ".text", 0);
4423         emit_global (acfg, symbol, FALSE);
4424         emit_alignment (acfg, 8);
4425         emit_label (acfg, symbol);
4426
4427         g_assert (table_size < 65000);
4428         emit_int32 (acfg, table_size);
4429         g_assert (table->len < 65000);
4430         for (i = 0; i < table->len; ++i) {
4431                 HashEntry *entry = g_ptr_array_index (table, i);
4432
4433                 if (entry == NULL) {
4434                         emit_int32 (acfg, 0);
4435                         emit_int32 (acfg, 0);
4436                         emit_int32 (acfg, 0);
4437                 } else {
4438                         g_assert (entry->key > 0);
4439                         emit_int32 (acfg, entry->key);
4440                         emit_int32 (acfg, entry->value);
4441                         if (entry->next)
4442                                 emit_int32 (acfg, entry->next->index);
4443                         else
4444                                 emit_int32 (acfg, 0);
4445                 }
4446         }
4447
4448         /* 
4449          * Emit a table reverse mapping method indexes to their index in extra_method_info.
4450          * This is used by mono_aot_find_jit_info ().
4451          */
4452         sprintf (symbol, "extra_method_info_offsets");
4453         emit_section_change (acfg, ".text", 0);
4454         emit_global (acfg, symbol, FALSE);
4455         emit_alignment (acfg, 8);
4456         emit_label (acfg, symbol);
4457
4458         emit_int32 (acfg, acfg->extra_methods->len);
4459         for (i = 0; i < acfg->extra_methods->len; ++i) {
4460                 MonoMethod *method = g_ptr_array_index (acfg->extra_methods, i);
4461
4462                 emit_int32 (acfg, get_method_index (acfg, method));
4463                 emit_int32 (acfg, info_offsets [i]);
4464         }
4465 }       
4466
4467 static void
4468 emit_method_order (MonoAotCompile *acfg)
4469 {
4470         int i, index, len;
4471         char symbol [256];
4472         GList *l;
4473
4474         sprintf (symbol, "method_order");
4475         emit_section_change (acfg, ".text", 1);
4476         emit_global (acfg, symbol, FALSE);
4477         emit_alignment (acfg, 8);
4478         emit_label (acfg, symbol);
4479
4480         /* First emit an index table */
4481         index = 0;
4482         len = 0;
4483         for (l = acfg->method_order; l != NULL; l = l->next) {
4484                 i = GPOINTER_TO_UINT (l->data);
4485
4486                 if (acfg->cfgs [i]) {
4487                         if ((index % 1024) == 0) {
4488                                 emit_int32 (acfg, i);
4489                         }
4490
4491                         index ++;
4492                 }
4493
4494                 len ++;
4495         }
4496         emit_int32 (acfg, 0xffffff);
4497
4498         /* Then emit the whole method order */
4499         for (l = acfg->method_order; l != NULL; l = l->next) {
4500                 i = GPOINTER_TO_UINT (l->data);
4501
4502                 if (acfg->cfgs [i]) {
4503                         emit_int32 (acfg, i);
4504                 }
4505         }       
4506         emit_line (acfg);
4507
4508         sprintf (symbol, "method_order_end");
4509         emit_section_change (acfg, ".text", 1);
4510         emit_global (acfg, symbol, FALSE);
4511         emit_label (acfg, symbol);
4512 }
4513
4514 static void
4515 emit_exception_info (MonoAotCompile *acfg)
4516 {
4517         int i;
4518         char symbol [256];
4519
4520         sprintf (symbol, "ex_info");
4521         emit_section_change (acfg, ".text", 1);
4522         emit_global (acfg, symbol, FALSE);
4523         emit_alignment (acfg, 8);
4524         emit_label (acfg, symbol);
4525
4526         /* To reduce size of generated assembly */
4527         sprintf (symbol, "ex");
4528         emit_label (acfg, symbol);
4529
4530         for (i = 0; i < acfg->nmethods; ++i) {
4531                 if (acfg->cfgs [i])
4532                         emit_exception_debug_info (acfg, acfg->cfgs [i]);
4533         }
4534
4535         sprintf (symbol, "ex_info_offsets");
4536         emit_section_change (acfg, ".text", 1);
4537         emit_global (acfg, symbol, FALSE);
4538         emit_alignment (acfg, 8);
4539         emit_label (acfg, symbol);
4540
4541         for (i = 0; i < acfg->nmethods; ++i) {
4542                 if (acfg->cfgs [i]) {
4543                         sprintf (symbol, "%se_%x_p", acfg->temp_prefix, i);
4544                         emit_symbol_diff (acfg, symbol, "ex", 0);
4545                 } else {
4546                         emit_int32 (acfg, 0);
4547                 }
4548         }
4549         emit_line (acfg);
4550 }
4551
4552 static void
4553 emit_unwind_info (MonoAotCompile *acfg)
4554 {
4555         int i;
4556         char symbol [128];
4557
4558         /* 
4559          * The unwind info contains a lot of duplicates so we emit each unique
4560          * entry once, and only store the offset from the start of the table in the
4561          * exception info.
4562          */
4563
4564         sprintf (symbol, "unwind_info");
4565         emit_section_change (acfg, ".text", 1);
4566         emit_alignment (acfg, 8);
4567         emit_label (acfg, symbol);
4568         emit_global (acfg, symbol, FALSE);
4569
4570         for (i = 0; i < acfg->unwind_ops->len; ++i) {
4571                 guint32 index = GPOINTER_TO_UINT (g_ptr_array_index (acfg->unwind_ops, i));
4572                 guint8 *unwind_info;
4573                 guint32 unwind_info_len;
4574                 guint8 buf [16];
4575                 guint8 *p;
4576
4577                 unwind_info = mono_get_cached_unwind_info (index, &unwind_info_len);
4578
4579                 p = buf;
4580                 encode_value (unwind_info_len, p, &p);
4581                 emit_bytes (acfg, buf, p - buf);
4582                 emit_bytes (acfg, unwind_info, unwind_info_len);
4583
4584                 acfg->stats.unwind_info_size += (p - buf) + unwind_info_len;
4585         }
4586 }
4587
4588 static void
4589 emit_class_info (MonoAotCompile *acfg)
4590 {
4591         int i;
4592         char symbol [256];
4593
4594         sprintf (symbol, "class_info");
4595         emit_section_change (acfg, ".text", 1);
4596         emit_global (acfg, symbol, FALSE);
4597         emit_alignment (acfg, 8);
4598         emit_label (acfg, symbol);
4599
4600         for (i = 0; i < acfg->image->tables [MONO_TABLE_TYPEDEF].rows; ++i)
4601                 emit_klass_info (acfg, MONO_TOKEN_TYPE_DEF | (i + 1));
4602
4603         sprintf (symbol, "class_info_offsets");
4604         emit_section_change (acfg, ".text", 1);
4605         emit_global (acfg, symbol, FALSE);
4606         emit_alignment (acfg, 8);
4607         emit_label (acfg, symbol);
4608
4609         for (i = 0; i < acfg->image->tables [MONO_TABLE_TYPEDEF].rows; ++i) {
4610                 sprintf (symbol, "%sK_I_%x", acfg->temp_prefix, i);
4611                 emit_symbol_diff (acfg, symbol, "class_info", 0);
4612         }
4613         emit_line (acfg);
4614 }
4615
4616 typedef struct ClassNameTableEntry {
4617         guint32 token, index;
4618         struct ClassNameTableEntry *next;
4619 } ClassNameTableEntry;
4620
4621 static void
4622 emit_class_name_table (MonoAotCompile *acfg)
4623 {
4624         int i, table_size;
4625         guint32 token, hash;
4626         MonoClass *klass;
4627         GPtrArray *table;
4628         char *full_name;
4629         char symbol [256];
4630         ClassNameTableEntry *entry, *new_entry;
4631
4632         /*
4633          * Construct a chained hash table for mapping class names to typedef tokens.
4634          */
4635         table_size = g_spaced_primes_closest ((int)(acfg->image->tables [MONO_TABLE_TYPEDEF].rows * 1.5));
4636         table = g_ptr_array_sized_new (table_size);
4637         for (i = 0; i < table_size; ++i)
4638                 g_ptr_array_add (table, NULL);
4639         for (i = 0; i < acfg->image->tables [MONO_TABLE_TYPEDEF].rows; ++i) {
4640                 token = MONO_TOKEN_TYPE_DEF | (i + 1);
4641                 klass = mono_class_get (acfg->image, token);
4642                 full_name = mono_type_get_name_full (mono_class_get_type (klass), MONO_TYPE_NAME_FORMAT_FULL_NAME);
4643                 hash = mono_aot_str_hash (full_name) % table_size;
4644                 g_free (full_name);
4645
4646                 /* FIXME: Allocate from the mempool */
4647                 new_entry = g_new0 (ClassNameTableEntry, 1);
4648                 new_entry->token = token;
4649
4650                 entry = g_ptr_array_index (table, hash);
4651                 if (entry == NULL) {
4652                         new_entry->index = hash;
4653                         g_ptr_array_index (table, hash) = new_entry;
4654                 } else {
4655                         while (entry->next)
4656                                 entry = entry->next;
4657                         
4658                         entry->next = new_entry;
4659                         new_entry->index = table->len;
4660                         g_ptr_array_add (table, new_entry);
4661                 }
4662         }
4663
4664         /* Emit the table */
4665         sprintf (symbol, "class_name_table");
4666         emit_section_change (acfg, ".text", 0);
4667         emit_global (acfg, symbol, FALSE);
4668         emit_alignment (acfg, 8);
4669         emit_label (acfg, symbol);
4670
4671         /* FIXME: Optimize memory usage */
4672         g_assert (table_size < 65000);
4673         emit_int16 (acfg, table_size);
4674         g_assert (table->len < 65000);
4675         for (i = 0; i < table->len; ++i) {
4676                 ClassNameTableEntry *entry = g_ptr_array_index (table, i);
4677
4678                 if (entry == NULL) {
4679                         emit_int16 (acfg, 0);
4680                         emit_int16 (acfg, 0);
4681                 } else {
4682                         emit_int16 (acfg, mono_metadata_token_index (entry->token));
4683                         if (entry->next)
4684                                 emit_int16 (acfg, entry->next->index);
4685                         else
4686                                 emit_int16 (acfg, 0);
4687                 }
4688         }
4689 }
4690
4691 static void
4692 emit_image_table (MonoAotCompile *acfg)
4693 {
4694         int i;
4695         char symbol [256];
4696
4697         /*
4698          * The image table is small but referenced in a lot of places.
4699          * So we emit it at once, and reference its elements by an index.
4700          */
4701
4702         sprintf (symbol, "mono_image_table");
4703         emit_section_change (acfg, ".text", 1);
4704         emit_global (acfg, symbol, FALSE);
4705         emit_alignment (acfg, 8);
4706         emit_label (acfg, symbol);
4707
4708         emit_int32 (acfg, acfg->image_table->len);
4709         for (i = 0; i < acfg->image_table->len; i++) {
4710                 MonoImage *image = (MonoImage*)g_ptr_array_index (acfg->image_table, i);
4711                 MonoAssemblyName *aname = &image->assembly->aname;
4712
4713                 /* FIXME: Support multi-module assemblies */
4714                 g_assert (image->assembly->image == image);
4715
4716                 emit_string (acfg, image->assembly_name);
4717                 emit_string (acfg, image->guid);
4718                 emit_string (acfg, aname->culture ? aname->culture : "");
4719                 emit_string (acfg, (const char*)aname->public_key_token);
4720
4721                 emit_alignment (acfg, 8);
4722                 emit_int32 (acfg, aname->flags);
4723                 emit_int32 (acfg, aname->major);
4724                 emit_int32 (acfg, aname->minor);
4725                 emit_int32 (acfg, aname->build);
4726                 emit_int32 (acfg, aname->revision);
4727         }
4728 }
4729
4730 static void
4731 emit_got_info (MonoAotCompile *acfg)
4732 {
4733         char symbol [256];
4734         int i, first_plt_got_patch, buf_size;
4735         guint8 *p, *buf;
4736         guint32 *got_info_offsets;
4737
4738         /* Add the patches needed by the PLT to the GOT */
4739         acfg->plt_got_offset_base = acfg->got_offset;
4740         first_plt_got_patch = acfg->got_patches->len;
4741         for (i = 1; i < acfg->plt_offset; ++i) {
4742                 MonoJumpInfo *patch_info = g_hash_table_lookup (acfg->plt_offset_to_patch, GUINT_TO_POINTER (i));
4743
4744                 g_ptr_array_add (acfg->got_patches, patch_info);
4745         }
4746
4747         acfg->got_offset += acfg->plt_offset;
4748
4749         /**
4750          * FIXME: 
4751          * - optimize offsets table.
4752          * - reduce number of exported symbols.
4753          * - emit info for a klass only once.
4754          * - determine when a method uses a GOT slot which is guaranteed to be already 
4755          *   initialized.
4756          * - clean up and document the code.
4757          * - use String.Empty in class libs.
4758          */
4759
4760         /* Encode info required to decode shared GOT entries */
4761         buf_size = acfg->got_patches->len * 64;
4762         p = buf = mono_mempool_alloc (acfg->mempool, buf_size);
4763         got_info_offsets = mono_mempool_alloc (acfg->mempool, acfg->got_patches->len * sizeof (guint32));
4764         acfg->plt_got_info_offsets = mono_mempool_alloc (acfg->mempool, acfg->plt_offset * sizeof (guint32));
4765         /* Unused */
4766         if (acfg->plt_offset)
4767                 acfg->plt_got_info_offsets [0] = 0;
4768         for (i = 0; i < acfg->got_patches->len; ++i) {
4769                 MonoJumpInfo *ji = g_ptr_array_index (acfg->got_patches, i);
4770
4771                 got_info_offsets [i] = p - buf;
4772                 if (i >= first_plt_got_patch)
4773                         acfg->plt_got_info_offsets [i - first_plt_got_patch + 1] = got_info_offsets [i];
4774                 encode_value (ji->type, p, &p);
4775                 encode_patch (acfg, ji, p, &p);
4776         }
4777
4778         g_assert (p - buf <= buf_size);
4779
4780         acfg->stats.got_info_size = p - buf;
4781
4782         /* Emit got_info table */
4783         sprintf (symbol, "got_info");
4784         emit_section_change (acfg, ".text", 1);
4785         emit_global (acfg, symbol, FALSE);
4786         emit_alignment (acfg, 8);
4787         emit_label (acfg, symbol);
4788
4789         emit_bytes (acfg, buf, p - buf);
4790
4791         /* Emit got_info_offsets table */
4792         sprintf (symbol, "got_info_offsets");
4793         emit_section_change (acfg, ".text", 1);
4794         emit_global (acfg, symbol, FALSE);
4795         emit_alignment (acfg, 8);
4796         emit_label (acfg, symbol);
4797
4798         /* No need to emit offsets for the got plt entries, the plt embeds them directly */
4799         for (i = 0; i < first_plt_got_patch; ++i)
4800                 emit_int32 (acfg, got_info_offsets [i]);
4801
4802         acfg->stats.got_info_offsets_size = acfg->got_patches->len * 4;
4803 }
4804
4805 static void
4806 emit_got (MonoAotCompile *acfg)
4807 {
4808         char symbol [256];
4809
4810         /* Don't make GOT global so accesses to it don't need relocations */
4811         sprintf (symbol, "%s", acfg->got_symbol);
4812         emit_section_change (acfg, ".bss", 0);
4813         emit_alignment (acfg, 8);
4814         emit_local_symbol (acfg, symbol, "got_end", FALSE);
4815         emit_label (acfg, symbol);
4816         if (acfg->got_offset > 0)
4817                 emit_zero_bytes (acfg, (int)(acfg->got_offset * sizeof (gpointer)));
4818
4819         sprintf (symbol, "got_end");
4820         emit_label (acfg, symbol);
4821
4822         sprintf (symbol, "mono_aot_got_addr");
4823         emit_section_change (acfg, ".data", 0);
4824         emit_global (acfg, symbol, FALSE);
4825         emit_alignment (acfg, 8);
4826         emit_label (acfg, symbol);
4827         emit_pointer (acfg, acfg->got_symbol);
4828 }
4829
4830 static void
4831 emit_globals (MonoAotCompile *acfg)
4832 {
4833         char *opts_str;
4834         char *build_info;
4835
4836         emit_string_symbol (acfg, "mono_assembly_guid" , acfg->image->guid);
4837
4838         emit_string_symbol (acfg, "mono_aot_version", MONO_AOT_FILE_VERSION);
4839
4840         opts_str = g_strdup_printf ("%d", acfg->opts);
4841         emit_string_symbol (acfg, "mono_aot_opt_flags", opts_str);
4842         g_free (opts_str);
4843
4844         emit_string_symbol (acfg, "mono_aot_full_aot", acfg->aot_opts.full_aot ? "TRUE" : "FALSE");
4845
4846         if (acfg->aot_opts.bind_to_runtime_version) {
4847                 build_info = mono_get_runtime_build_info ();
4848                 emit_string_symbol (acfg, "mono_runtime_version", build_info);
4849                 g_free (build_info);
4850         } else {
4851                 emit_string_symbol (acfg, "mono_runtime_version", "");
4852         }
4853
4854         /* 
4855          * When static linking, we emit a global which will point to the symbol table.
4856          */
4857         if (acfg->aot_opts.static_link) {
4858                 int i;
4859                 char symbol [256];
4860                 char *p;
4861
4862                 /* Emit a string holding the assembly name */
4863                 emit_string_symbol (acfg, "mono_aot_assembly_name", acfg->image->assembly->aname.name);
4864
4865                 /* Emit the names */
4866                 for (i = 0; i < acfg->globals->len; ++i) {
4867                         char *name = g_ptr_array_index (acfg->globals, i);
4868
4869                         sprintf (symbol, "name_%d", i);
4870                         emit_section_change (acfg, ".text", 1);
4871                         emit_label (acfg, symbol);
4872                         emit_string (acfg, name);
4873                 }
4874
4875                 /* Emit the globals table */
4876                 sprintf (symbol, "globals");
4877                 emit_section_change (acfg, ".data", 0);
4878                 /* This is not a global, since it is accessed by the init function */
4879                 emit_alignment (acfg, 8);
4880                 emit_label (acfg, symbol);
4881
4882                 for (i = 0; i < acfg->globals->len; ++i) {
4883                         char *name = g_ptr_array_index (acfg->globals, i);
4884
4885                         sprintf (symbol, "name_%d", i);
4886                         emit_pointer (acfg, symbol);
4887
4888                         sprintf (symbol, "%s", name);
4889                         emit_pointer (acfg, symbol);
4890                 }
4891                 /* Null terminate the table */
4892                 emit_int32 (acfg, 0);
4893                 emit_int32 (acfg, 0);
4894
4895                 /* 
4896                  * Emit a global symbol which can be passed by an embedding app to
4897                  * mono_aot_register_module ().
4898                  */
4899 #if defined(__MACH__)
4900                 sprintf (symbol, "_mono_aot_module_%s_info", acfg->image->assembly->aname.name);
4901 #else
4902                 sprintf (symbol, "mono_aot_module_%s_info", acfg->image->assembly->aname.name);
4903 #endif
4904
4905                 /* Get rid of characters which cannot occur in symbols */
4906                 p = symbol;
4907                 for (p = symbol; *p; ++p) {
4908                         if (!(isalnum (*p) || *p == '_'))
4909                                 *p = '_';
4910                 }
4911                 acfg->static_linking_symbol = g_strdup (symbol);
4912                 emit_global_inner (acfg, symbol, FALSE);
4913                 emit_alignment (acfg, 8);
4914                 emit_label (acfg, symbol);
4915                 emit_pointer (acfg, "globals");
4916         }
4917 }
4918
4919 static void
4920 emit_mem_end (MonoAotCompile *acfg)
4921 {
4922         char symbol [128];
4923
4924         sprintf (symbol, "mem_end");
4925         emit_section_change (acfg, ".text", 1);
4926         emit_global (acfg, symbol, FALSE);
4927         emit_alignment (acfg, 8);
4928         emit_label (acfg, symbol);
4929 }
4930
4931 /*
4932  * Emit a structure containing all the information not stored elsewhere.
4933  */
4934 static void
4935 emit_file_info (MonoAotCompile *acfg)
4936 {
4937         char symbol [128];
4938         int i;
4939
4940         sprintf (symbol, "mono_aot_file_info");
4941         emit_section_change (acfg, ".data", 0);
4942         emit_alignment (acfg, 8);
4943         emit_label (acfg, symbol);
4944         emit_global (acfg, symbol, FALSE);
4945
4946         /* The data emitted here must match MonoAotFileInfo in aot-runtime.c. */
4947         emit_int32 (acfg, acfg->plt_got_offset_base);
4948         emit_int32 (acfg, (int)(acfg->got_offset * sizeof (gpointer)));
4949         emit_int32 (acfg, acfg->plt_offset);
4950         emit_int32 (acfg, acfg->nmethods);
4951
4952         for (i = 0; i < MONO_AOT_TRAMP_NUM; ++i)
4953                 emit_int32 (acfg, acfg->num_trampolines [i]);
4954         for (i = 0; i < MONO_AOT_TRAMP_NUM; ++i)
4955                 emit_int32 (acfg, acfg->trampoline_got_offset_base [i]);
4956         for (i = 0; i < MONO_AOT_TRAMP_NUM; ++i)
4957                 emit_int32 (acfg, acfg->trampoline_size [i]);
4958 }
4959
4960 static void
4961 emit_dwarf_info (MonoAotCompile *acfg)
4962 {
4963 #ifdef EMIT_DWARF_INFO
4964         int i;
4965         char symbol [128], symbol2 [128];
4966
4967         /* DIEs for methods */
4968         for (i = 0; i < acfg->nmethods; ++i) {
4969                 MonoCompile *cfg = acfg->cfgs [i];
4970
4971                 if (!cfg)
4972                         continue;
4973
4974                 sprintf (symbol, "%sm_%x", acfg->temp_prefix, i);
4975                 sprintf (symbol2, "%sme_%x", acfg->temp_prefix, i);
4976
4977                 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 ()));
4978         }
4979 #endif
4980 }
4981
4982 static void
4983 collect_methods (MonoAotCompile *acfg)
4984 {
4985         int i;
4986         MonoImage *image = acfg->image;
4987
4988         /* Collect methods */
4989         for (i = 0; i < image->tables [MONO_TABLE_METHOD].rows; ++i) {
4990                 MonoMethod *method;
4991                 guint32 token = MONO_TOKEN_METHOD_DEF | (i + 1);
4992
4993                 method = mono_get_method (acfg->image, token, NULL);
4994
4995                 if (!method) {
4996                         printf ("Failed to load method 0x%x from '%s'.\n", token, image->name);
4997                         exit (1);
4998                 }
4999                         
5000                 /* Load all methods eagerly to skip the slower lazy loading code */
5001                 mono_class_setup_methods (method->klass);
5002
5003                 if (acfg->aot_opts.full_aot && method->iflags & METHOD_IMPL_ATTRIBUTE_INTERNAL_CALL) {
5004                         /* Compile the wrapper instead */
5005                         /* We do this here instead of add_wrappers () because it is easy to do it here */
5006                         MonoMethod *wrapper = mono_marshal_get_native_wrapper (method, check_for_pending_exc, TRUE);
5007                         method = wrapper;
5008                 }
5009
5010                 /* Since we add the normal methods first, their index will be equal to their zero based token index */
5011                 add_method_with_index (acfg, method, i, FALSE);
5012                 acfg->method_index ++;
5013         }
5014
5015         add_generic_instances (acfg);
5016
5017         if (acfg->aot_opts.full_aot)
5018                 add_wrappers (acfg);
5019 }
5020
5021 static void
5022 compile_methods (MonoAotCompile *acfg)
5023 {
5024         int i, methods_len;
5025
5026         if (acfg->aot_opts.nthreads > 0) {
5027                 GPtrArray *frag;
5028                 int len, j;
5029                 GPtrArray *threads;
5030                 HANDLE handle;
5031                 gpointer *user_data;
5032                 MonoMethod **methods;
5033
5034                 methods_len = acfg->methods->len;
5035
5036                 len = acfg->methods->len / acfg->aot_opts.nthreads;
5037                 g_assert (len > 0);
5038                 /* 
5039                  * Partition the list of methods into fragments, and hand it to threads to
5040                  * process.
5041                  */
5042                 threads = g_ptr_array_new ();
5043                 /* Make a copy since acfg->methods is modified by compile_method () */
5044                 methods = g_new0 (MonoMethod*, methods_len);
5045                 //memcpy (methods, g_ptr_array_index (acfg->methods, 0), sizeof (MonoMethod*) * methods_len);
5046                 for (i = 0; i < methods_len; ++i)
5047                         methods [i] = g_ptr_array_index (acfg->methods, i);
5048                 i = 0;
5049                 while (i < methods_len) {
5050                         frag = g_ptr_array_new ();
5051                         for (j = 0; j < len; ++j) {
5052                                 if (i < methods_len) {
5053                                         g_ptr_array_add (frag, methods [i]);
5054                                         i ++;
5055                                 }
5056                         }
5057
5058                         user_data = g_new0 (gpointer, 3);
5059                         user_data [0] = mono_domain_get ();
5060                         user_data [1] = acfg;
5061                         user_data [2] = frag;
5062                         
5063                         handle = mono_create_thread (NULL, 0, (gpointer)compile_thread_main, user_data, 0, NULL);
5064                         g_ptr_array_add (threads, handle);
5065                 }
5066                 g_free (methods);
5067
5068                 for (i = 0; i < threads->len; ++i) {
5069                         WaitForSingleObjectEx (g_ptr_array_index (threads, i), INFINITE, FALSE);
5070                 }
5071         } else {
5072                 methods_len = 0;
5073         }
5074
5075         /* Compile methods added by compile_method () or all methods if nthreads == 0 */
5076         for (i = methods_len; i < acfg->methods->len; ++i) {
5077                 /* This can new methods to acfg->methods */
5078                 compile_method (acfg, g_ptr_array_index (acfg->methods, i));
5079         }
5080 }
5081
5082 static int
5083 compile_asm (MonoAotCompile *acfg)
5084 {
5085         char *command, *objfile;
5086         char *outfile_name, *tmp_outfile_name;
5087         const char *tool_prefix = acfg->aot_opts.tool_prefix ? acfg->aot_opts.tool_prefix : "";
5088
5089 #if defined(TARGET_AMD64)
5090 #define AS_OPTIONS "--64"
5091 #elif defined(TARGET_POWERPC64)
5092 #define AS_OPTIONS "-a64 -mppc64"
5093 #define LD_OPTIONS "-m elf64ppc"
5094 #elif defined(sparc) && SIZEOF_VOID_P == 8
5095 #define AS_OPTIONS "-xarch=v9"
5096 #else
5097 #define AS_OPTIONS ""
5098 #endif
5099
5100 #ifndef LD_OPTIONS
5101 #define LD_OPTIONS ""
5102 #endif
5103
5104         if (acfg->aot_opts.asm_only) {
5105                 printf ("Output file: '%s'.\n", acfg->tmpfname);
5106                 if (acfg->aot_opts.static_link)
5107                         printf ("Linking symbol: '%s'.\n", acfg->static_linking_symbol);
5108                 return 0;
5109         }
5110
5111         if (acfg->aot_opts.static_link) {
5112                 if (acfg->aot_opts.outfile)
5113                         objfile = g_strdup_printf ("%s", acfg->aot_opts.outfile);
5114                 else
5115                         objfile = g_strdup_printf ("%s.o", acfg->image->name);
5116         } else {
5117                 objfile = g_strdup_printf ("%s.o", acfg->tmpfname);
5118         }
5119         command = g_strdup_printf ("%sas %s %s -o %s", tool_prefix, AS_OPTIONS, acfg->tmpfname, objfile);
5120         printf ("Executing the native assembler: %s\n", command);
5121         if (system (command) != 0) {
5122                 g_free (command);
5123                 g_free (objfile);
5124                 return 1;
5125         }
5126
5127         g_free (command);
5128
5129         if (acfg->aot_opts.static_link) {
5130                 printf ("Output file: '%s'.\n", objfile);
5131                 printf ("Linking symbol: '%s'.\n", acfg->static_linking_symbol);
5132                 g_free (objfile);
5133                 return 0;
5134         }
5135
5136         if (acfg->aot_opts.outfile)
5137                 outfile_name = g_strdup_printf ("%s", acfg->aot_opts.outfile);
5138         else
5139                 outfile_name = g_strdup_printf ("%s%s", acfg->image->name, SHARED_EXT);
5140
5141         tmp_outfile_name = g_strdup_printf ("%s.tmp", outfile_name);
5142
5143 #if defined(sparc)
5144         command = g_strdup_printf ("ld -shared -G -o %s %s.o", tmp_outfile_name, acfg->tmpfname);
5145 #elif defined(__ppc__) && defined(__MACH__)
5146         command = g_strdup_printf ("gcc -dynamiclib -o %s %s.o", tmp_outfile_name, acfg->tmpfname);
5147 #elif defined(PLATFORM_WIN32)
5148         command = g_strdup_printf ("gcc -shared --dll -mno-cygwin -o %s %s.o", tmp_outfile_name, acfg->tmpfname);
5149 #else
5150         command = g_strdup_printf ("%sld %s -shared -o %s %s.o", tool_prefix, LD_OPTIONS, tmp_outfile_name, acfg->tmpfname);
5151 #endif
5152         printf ("Executing the native linker: %s\n", command);
5153         if (system (command) != 0) {
5154                 g_free (tmp_outfile_name);
5155                 g_free (outfile_name);
5156                 g_free (command);
5157                 g_free (objfile);
5158                 return 1;
5159         }
5160
5161         g_free (command);
5162         unlink (objfile);
5163         /*com = g_strdup_printf ("strip --strip-unneeded %s%s", acfg->image->name, SHARED_EXT);
5164         printf ("Stripping the binary: %s\n", com);
5165         system (com);
5166         g_free (com);*/
5167
5168 #if defined(TARGET_ARM) && !defined(__MACH__)
5169         /* 
5170          * gas generates 'mapping symbols' each time code and data is mixed, which 
5171          * happens a lot in emit_and_reloc_code (), so we need to get rid of them.
5172          */
5173         command = g_strdup_printf ("%sstrip --strip-symbol=\\$a --strip-symbol=\\$d %s", tool_prefix, tmp_outfile_name);
5174         printf ("Stripping the binary: %s\n", command);
5175         if (system (command) != 0) {
5176                 g_free (tmp_outfile_name);
5177                 g_free (outfile_name);
5178                 g_free (command);
5179                 g_free (objfile);
5180                 return 1;
5181         }
5182 #endif
5183
5184         rename (tmp_outfile_name, outfile_name);
5185
5186         g_free (tmp_outfile_name);
5187         g_free (outfile_name);
5188         g_free (objfile);
5189
5190         if (acfg->aot_opts.save_temps)
5191                 printf ("Retained input file.\n");
5192         else
5193                 unlink (acfg->tmpfname);
5194
5195         return 0;
5196 }
5197
5198 static MonoAotCompile*
5199 acfg_create (MonoAssembly *ass, guint32 opts)
5200 {
5201         MonoImage *image = ass->image;
5202         MonoAotCompile *acfg;
5203
5204         acfg = g_new0 (MonoAotCompile, 1);
5205         acfg->methods = g_ptr_array_new ();
5206         acfg->method_indexes = g_hash_table_new (NULL, NULL);
5207         acfg->plt_offset_to_patch = g_hash_table_new (NULL, NULL);
5208         acfg->patch_to_plt_offset = g_hash_table_new (mono_patch_info_hash, mono_patch_info_equal);
5209         acfg->patch_to_got_offset = g_hash_table_new (mono_patch_info_hash, mono_patch_info_equal);
5210         acfg->got_patches = g_ptr_array_new ();
5211         acfg->method_to_cfg = g_hash_table_new (NULL, NULL);
5212         acfg->token_info_hash = g_hash_table_new_full (NULL, NULL, NULL, g_free);
5213         acfg->image_hash = g_hash_table_new (NULL, NULL);
5214         acfg->image_table = g_ptr_array_new ();
5215         acfg->globals = g_ptr_array_new ();
5216         acfg->image = image;
5217         acfg->opts = opts;
5218         acfg->mempool = mono_mempool_new ();
5219         acfg->extra_methods = g_ptr_array_new ();
5220         acfg->unwind_info_offsets = g_hash_table_new (NULL, NULL);
5221         acfg->unwind_ops = g_ptr_array_new ();
5222         acfg->method_label_hash = g_hash_table_new_full (g_str_hash, g_str_equal, g_free, NULL);
5223         InitializeCriticalSection (&acfg->mutex);
5224
5225         return acfg;
5226 }
5227
5228 static void
5229 acfg_free (MonoAotCompile *acfg)
5230 {
5231         int i;
5232
5233         img_writer_destroy (acfg->w);
5234         for (i = 0; i < acfg->nmethods; ++i)
5235                 if (acfg->cfgs [i])
5236                         g_free (acfg->cfgs [i]);
5237         g_free (acfg->cfgs);
5238         g_free (acfg->static_linking_symbol);
5239         g_free (acfg->got_symbol);
5240         g_free (acfg->plt_symbol);
5241         g_ptr_array_free (acfg->methods, TRUE);
5242         g_ptr_array_free (acfg->got_patches, TRUE);
5243         g_ptr_array_free (acfg->image_table, TRUE);
5244         g_ptr_array_free (acfg->globals, TRUE);
5245         g_ptr_array_free (acfg->unwind_ops, TRUE);
5246         g_hash_table_destroy (acfg->method_indexes);
5247         g_hash_table_destroy (acfg->plt_offset_to_patch);
5248         g_hash_table_destroy (acfg->patch_to_plt_offset);
5249         g_hash_table_destroy (acfg->patch_to_got_offset);
5250         g_hash_table_destroy (acfg->method_to_cfg);
5251         g_hash_table_destroy (acfg->token_info_hash);
5252         g_hash_table_destroy (acfg->image_hash);
5253         g_hash_table_destroy (acfg->unwind_info_offsets);
5254         g_hash_table_destroy (acfg->method_label_hash);
5255         mono_mempool_destroy (acfg->mempool);
5256         g_free (acfg);
5257 }
5258
5259 int
5260 mono_compile_assembly (MonoAssembly *ass, guint32 opts, const char *aot_options)
5261 {
5262         MonoImage *image = ass->image;
5263         int res;
5264         MonoAotCompile *acfg;
5265         char *outfile_name, *tmp_outfile_name, *p;
5266         TV_DECLARE (atv);
5267         TV_DECLARE (btv);
5268
5269         printf ("Mono Ahead of Time compiler - compiling assembly %s\n", image->name);
5270
5271         acfg = acfg_create (ass, opts);
5272
5273         memset (&acfg->aot_opts, 0, sizeof (acfg->aot_opts));
5274         acfg->aot_opts.write_symbols = TRUE;
5275         acfg->aot_opts.ntrampolines = 1024;
5276
5277         mono_aot_parse_options (aot_options, &acfg->aot_opts);
5278
5279         //acfg->aot_opts.print_skipped_methods = TRUE;
5280
5281 #ifndef MONO_ARCH_HAVE_FULL_AOT_TRAMPOLINES
5282         if (acfg->aot_opts.full_aot) {
5283                 printf ("--aot=full is not supported on this platform.\n");
5284                 return 1;
5285         }
5286 #endif
5287
5288         if (acfg->aot_opts.static_link)
5289                 acfg->aot_opts.asm_writer = TRUE;
5290
5291         load_profile_files (acfg);
5292
5293         acfg->num_trampolines [MONO_AOT_TRAMP_SPECIFIC] = acfg->aot_opts.full_aot ? acfg->aot_opts.ntrampolines : 0;
5294 #ifdef MONO_ARCH_HAVE_STATIC_RGCTX_TRAMPOLINE
5295         acfg->num_trampolines [MONO_AOT_TRAMP_STATIC_RGCTX] = acfg->aot_opts.full_aot ? 1024 : 0;
5296 #endif
5297         acfg->num_trampolines [MONO_AOT_TRAMP_IMT_THUNK] = acfg->aot_opts.full_aot ? 128 : 0;
5298
5299         acfg->got_symbol = g_strdup_printf ("mono_aot_%s_got", acfg->image->assembly->aname.name);
5300         acfg->plt_symbol = g_strdup_printf ("mono_aot_%s_plt", acfg->image->assembly->aname.name);
5301
5302         /* Get rid of characters which cannot occur in symbols */
5303         for (p = acfg->got_symbol; *p; ++p) {
5304                 if (!(isalnum (*p) || *p == '_'))
5305                         *p = '_';
5306         }
5307         for (p = acfg->plt_symbol; *p; ++p) {
5308                 if (!(isalnum (*p) || *p == '_'))
5309                         *p = '_';
5310         }
5311
5312         acfg->method_index = 1;
5313
5314         collect_methods (acfg);
5315
5316         acfg->cfgs_size = acfg->methods->len + 32;
5317         acfg->cfgs = g_new0 (MonoCompile*, acfg->cfgs_size);
5318
5319         /* PLT offset 0 is reserved for the PLT trampoline */
5320         acfg->plt_offset = 1;
5321
5322         /* GOT offset 0 is reserved for the address of the current assembly */
5323         {
5324                 MonoJumpInfo *ji;
5325
5326                 ji = mono_mempool_alloc0 (acfg->mempool, sizeof (MonoAotCompile));
5327                 ji->type = MONO_PATCH_INFO_IMAGE;
5328                 ji->data.image = acfg->image;
5329
5330                 get_got_offset (acfg, ji);
5331
5332                 /* Slot 1 is reserved for the mscorlib got addr */
5333                 ji = mono_mempool_alloc0 (acfg->mempool, sizeof (MonoAotCompile));
5334                 ji->type = MONO_PATCH_INFO_MSCORLIB_GOT_ADDR;
5335                 get_got_offset (acfg, ji);
5336         }
5337
5338         TV_GETTIME (atv);
5339
5340         compile_methods (acfg);
5341
5342         TV_GETTIME (btv);
5343
5344         acfg->stats.jit_time = TV_ELAPSED (atv, btv);
5345
5346         TV_GETTIME (atv);
5347
5348         if (!acfg->aot_opts.asm_only && !acfg->aot_opts.asm_writer && bin_writer_supported ()) {
5349                 if (acfg->aot_opts.outfile)
5350                         outfile_name = g_strdup_printf ("%s", acfg->aot_opts.outfile);
5351                 else
5352                         outfile_name = g_strdup_printf ("%s%s", acfg->image->name, SHARED_EXT);
5353
5354                 /* 
5355                  * Can't use g_file_open_tmp () as it will be deleted at exit, and
5356                  * it might be in another file system so the rename () won't work.
5357                  */
5358                 tmp_outfile_name = g_strdup_printf ("%s.tmp", outfile_name);
5359
5360                 acfg->fp = fopen (tmp_outfile_name, "w");
5361                 if (!acfg->fp) {
5362                         printf ("Unable to create temporary file '%s': %s\n", tmp_outfile_name, strerror (errno));
5363                         return 1;
5364                 }
5365
5366                 acfg->w = img_writer_create (acfg->fp, TRUE);
5367                 acfg->use_bin_writer = TRUE;
5368         } else {
5369                 if (acfg->aot_opts.asm_only) {
5370                         if (acfg->aot_opts.outfile)
5371                                 acfg->tmpfname = g_strdup_printf ("%s", acfg->aot_opts.outfile);
5372                         else
5373                                 acfg->tmpfname = g_strdup_printf ("%s.s", acfg->image->name);
5374                         acfg->fp = fopen (acfg->tmpfname, "w+");
5375                 } else {
5376                         int i = g_file_open_tmp ("mono_aot_XXXXXX", &acfg->tmpfname, NULL);
5377                         acfg->fp = fdopen (i, "w+");
5378                 }
5379                 g_assert (acfg->fp);
5380
5381                 acfg->w = img_writer_create (acfg->fp, FALSE);
5382                 
5383                 tmp_outfile_name = NULL;
5384                 outfile_name = NULL;
5385         }
5386
5387         acfg->temp_prefix = img_writer_get_temp_label_prefix (acfg->w);
5388
5389         if (!acfg->aot_opts.nodebug)
5390                 acfg->dwarf = mono_dwarf_writer_create (acfg->w, NULL, FALSE);
5391
5392         img_writer_emit_start (acfg->w);
5393
5394         if (acfg->dwarf)
5395                 mono_dwarf_writer_emit_base_info (acfg->dwarf, arch_get_cie_program ());
5396
5397         emit_code (acfg);
5398
5399         emit_info (acfg);
5400
5401         emit_extra_methods (acfg);
5402
5403         emit_method_order (acfg);
5404
5405         emit_trampolines (acfg);
5406
5407         emit_class_name_table (acfg);
5408
5409         emit_got_info (acfg);
5410
5411         emit_exception_info (acfg);
5412
5413         emit_unwind_info (acfg);
5414
5415         emit_class_info (acfg);
5416
5417         emit_plt (acfg);
5418
5419         emit_image_table (acfg);
5420
5421         emit_got (acfg);
5422
5423         emit_file_info (acfg);
5424
5425         emit_globals (acfg);
5426
5427         if (acfg->dwarf) {
5428                 emit_dwarf_info (acfg);
5429                 mono_dwarf_writer_close (acfg->dwarf);
5430         }
5431
5432         emit_mem_end (acfg);
5433
5434         TV_GETTIME (btv);
5435
5436         acfg->stats.gen_time = TV_ELAPSED (atv, btv);
5437
5438         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)));
5439
5440         TV_GETTIME (atv);
5441         res = img_writer_emit_writeout (acfg->w);
5442         if (res != 0) {
5443                 acfg_free (acfg);
5444                 return res;
5445         }
5446         if (acfg->use_bin_writer) {
5447                 int err = rename (tmp_outfile_name, outfile_name);
5448
5449                 if (err) {
5450                         printf ("Unable to rename '%s' to '%s': %s\n", tmp_outfile_name, outfile_name, strerror (errno));
5451                         return 1;
5452                 }
5453         } else {
5454                 res = compile_asm (acfg);
5455                 if (res != 0) {
5456                         acfg_free (acfg);
5457                         return res;
5458                 }
5459         }
5460         TV_GETTIME (btv);
5461         acfg->stats.link_time = TV_ELAPSED (atv, btv);
5462
5463         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);
5464         if (acfg->stats.genericcount)
5465                 printf ("%d methods are generic (%d%%)\n", acfg->stats.genericcount, acfg->stats.mcount ? (acfg->stats.genericcount * 100) / acfg->stats.mcount : 100);
5466         if (acfg->stats.abscount)
5467                 printf ("%d methods contain absolute addresses (%d%%)\n", acfg->stats.abscount, acfg->stats.mcount ? (acfg->stats.abscount * 100) / acfg->stats.mcount : 100);
5468         if (acfg->stats.lmfcount)
5469                 printf ("%d methods contain lmf pointers (%d%%)\n", acfg->stats.lmfcount, acfg->stats.mcount ? (acfg->stats.lmfcount * 100) / acfg->stats.mcount : 100);
5470         if (acfg->stats.ocount)
5471                 printf ("%d methods have other problems (%d%%)\n", acfg->stats.ocount, acfg->stats.mcount ? (acfg->stats.ocount * 100) / acfg->stats.mcount : 100);
5472         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);
5473         printf ("Direct calls: %d (%d%%)\n", acfg->stats.direct_calls, acfg->stats.all_calls ? (acfg->stats.direct_calls * 100) / acfg->stats.all_calls : 100);
5474
5475         /*
5476         printf ("GOT slot distribution:\n");
5477         for (i = 0; i < MONO_PATCH_INFO_NONE; ++i)
5478                 if (acfg->stats.got_slot_types [i])
5479                         printf ("\t%s: %d\n", get_patch_name (i), acfg->stats.got_slot_types [i]);
5480         */
5481
5482         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);
5483
5484         acfg_free (acfg);
5485         
5486         return 0;
5487 }
5488  
5489 /*
5490  * Support for emitting debug info for JITted code.
5491  *
5492  *   This works as follows:
5493  * - the runtime writes out an xdb.s file containing DWARF debug info.
5494  * - the user calls a gdb macro
5495  * - the macro compiles and loads this shared library using add-symbol-file.
5496  *
5497  * This is based on the xdebug functionality in the Kaffe Java VM.
5498  * 
5499  * We emit assembly code instead of using the ELF writer, so we can emit debug info
5500  * incrementally as each method is JITted, and the debugger doesn't have to call
5501  * into the runtime to emit the shared library, which would cause all kinds of
5502  * complications, like threading issues, and the fact that the ELF writer's
5503  * emit_writeout () function cannot be called more than once.
5504  */
5505
5506 /* The recommended gdb macro is: */
5507 /*
5508   define xdb
5509   shell rm -f xdb.so && as --64 -o xdb.o xdb.s && ld -shared -o xdb.so xdb.o
5510   add-symbol-file xdb.so 0
5511   end
5512 */
5513
5514 static MonoDwarfWriter *xdebug_writer;
5515 static FILE *xdebug_fp;
5516
5517 void
5518 mono_xdebug_init (void)
5519 {
5520         FILE *il_file;
5521         MonoImageWriter *w;
5522
5523         unlink ("xdb.s");
5524         xdebug_fp = fopen ("xdb.s", "w");
5525
5526         w = img_writer_create (xdebug_fp, FALSE);
5527
5528         img_writer_emit_start (w);
5529
5530         /* This file will contain the IL code for methods which don't have debug info */
5531         il_file = fopen ("xdb.il", "w");
5532
5533         xdebug_writer = mono_dwarf_writer_create (w, il_file, TRUE);
5534
5535         /* Emit something so the file has a text segment */
5536         img_writer_emit_section_change (w, ".text", 0);
5537         img_writer_emit_string (w, "");
5538
5539         mono_dwarf_writer_emit_base_info (xdebug_writer, arch_get_cie_program ());
5540 }
5541
5542 /*
5543  * mono_save_xdebug_info:
5544  *
5545  *   Emit debugging info for METHOD into an assembly file which can be assembled
5546  * and loaded into gdb to provide debugging info for JITted code.
5547  * LOCKING: Acquires the loader lock.
5548  */
5549 void
5550 mono_save_xdebug_info (MonoCompile *cfg)
5551 {
5552         if (!xdebug_writer)
5553                 return;
5554
5555         mono_loader_lock ();
5556         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 ()));
5557         fflush (xdebug_fp);
5558         mono_loader_unlock ();
5559 }
5560
5561 /*
5562  * mono_save_trampoline_xdebug_info:
5563  *
5564  *   Same as mono_save_xdebug_info, but for trampolines.
5565  * LOCKING: Acquires the loader lock.
5566  */
5567 void
5568 mono_save_trampoline_xdebug_info (const char *tramp_name, guint8 *code, guint32 code_size, GSList *unwind_info)
5569 {
5570         if (!xdebug_writer)
5571                 return;
5572
5573         mono_loader_lock ();
5574         mono_dwarf_writer_emit_trampoline (xdebug_writer, tramp_name, NULL, NULL, code, code_size, unwind_info);
5575         fflush (xdebug_fp);
5576         mono_loader_unlock ();
5577 }
5578
5579 #else
5580
5581 /* AOT disabled */
5582
5583 int
5584 mono_compile_assembly (MonoAssembly *ass, guint32 opts, const char *aot_options)
5585 {
5586         return 0;
5587 }
5588
5589 void
5590 mono_xdebug_init (void)
5591 {
5592 }
5593
5594 void
5595 mono_save_xdebug_info (MonoCompile *cfg)
5596 {
5597 }
5598
5599 void
5600 mono_save_trampoline_xdebug_info (const char *tramp_name, guint8 *code, guint32 code_size, GSList *unwind_info)
5601 {
5602 }
5603
5604 #endif