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