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