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