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