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