2009-02-15 Zoltan Varga <vargaz@gmail.com>
[mono.git] / mono / mini / aot-compiler.c
1 /*
2  * aot.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  * - reduce the length of the wrapper names.
13  * - aot IMT tables, so we don't have two kinds of aot code.
14  * - optimize the trampolines, generate more code in the arch files.
15  * - make things more consistent with how elf works, for example, use ELF 
16  *   relocations.
17  * Remaining generics sharing work:
18  * - optimize the size of the data which is encoded.
19  * - optimize the runtime loading of data:
20  *   - the trampoline code calls mono_jit_info_table_find () to find the rgctx, 
21  *     which loads the debugging+exception handling info for the method. This is a 
22  *     huge waste of time and code, since the rgctx structure is currently empty.
23  *   - every shared method has a MonoGenericJitInfo structure which is only really
24  *     used for handling catch clauses with open types, not a very common use case.
25  */
26
27 #include "config.h"
28 #include <sys/types.h>
29 #ifdef HAVE_UNISTD_H
30 #include <unistd.h>
31 #endif
32 #ifdef HAVE_STDINT_H
33 #include <stdint.h>
34 #endif
35 #include <fcntl.h>
36 #include <ctype.h>
37 #include <string.h>
38 #ifndef PLATFORM_WIN32
39 #include <sys/time.h>
40 #else
41 #include <winsock2.h>
42 #include <windows.h>
43 #endif
44
45 #include <errno.h>
46 #include <sys/stat.h>
47 #include <limits.h>    /* for PAGESIZE */
48 #ifndef PAGESIZE
49 #define PAGESIZE 4096
50 #endif
51
52 #include <mono/metadata/tabledefs.h>
53 #include <mono/metadata/class.h>
54 #include <mono/metadata/object.h>
55 #include <mono/metadata/tokentype.h>
56 #include <mono/metadata/appdomain.h>
57 #include <mono/metadata/debug-helpers.h>
58 #include <mono/metadata/assembly.h>
59 #include <mono/metadata/metadata-internals.h>
60 #include <mono/metadata/marshal.h>
61 #include <mono/metadata/gc-internal.h>
62 #include <mono/metadata/method-builder.h>
63 #include <mono/metadata/monitor.h>
64 #include <mono/metadata/mempool-internals.h>
65 #include <mono/metadata/mono-endian.h>
66 #include <mono/metadata/mono-debug.h>
67 #include <mono/metadata/debug-mono-symfile.h>
68 #include <mono/utils/mono-logger.h>
69 #include <mono/utils/mono-compiler.h>
70 #include <mono/utils/mono-time.h>
71
72 #ifndef PLATFORM_WIN32
73 #include <mono/utils/freebsd-elf32.h>
74 #include <mono/utils/freebsd-elf64.h>
75 #endif
76
77 #include <mono/utils/freebsd-dwarf.h>
78
79 #include "mini.h"
80 #include "image-writer.h"
81
82 #ifndef DISABLE_AOT
83
84 #define TV_DECLARE(name) gint64 name
85 #define TV_GETTIME(tv) tv = mono_100ns_ticks ()
86 #define TV_ELAPSED(start,end) (((end) - (start)) / 10)
87
88 #ifdef PLATFORM_WIN32
89 #define SHARED_EXT ".dll"
90 #elif defined(__ppc__) && defined(__MACH__)
91 #define SHARED_EXT ".dylib"
92 #else
93 #define SHARED_EXT ".so"
94 #endif
95
96 #define ALIGN_TO(val,align) ((((guint64)val) + ((align) - 1)) & ~((align) - 1))
97 #define ALIGN_PTR_TO(ptr,align) (gpointer)((((gssize)(ptr)) + (align - 1)) & (~(align - 1)))
98 #define ROUND_DOWN(VALUE,SIZE)  ((VALUE) & ~((SIZE) - 1))
99
100 typedef struct MonoAotOptions {
101         char *outfile;
102         gboolean save_temps;
103         gboolean write_symbols;
104         gboolean metadata_only;
105         gboolean bind_to_runtime_version;
106         gboolean full_aot;
107         gboolean no_dlsym;
108         gboolean static_link;
109         gboolean asm_only;
110         gboolean asm_writer;
111         int nthreads;
112         gboolean print_skipped_methods;
113 } MonoAotOptions;
114
115 typedef struct MonoAotStats {
116         int ccount, mcount, lmfcount, abscount, gcount, ocount, genericcount;
117         int code_size, info_size, ex_info_size, got_size, class_info_size, got_info_size, got_info_offsets_size;
118         int methods_without_got_slots, direct_calls, all_calls;
119         int got_slots;
120         int got_slot_types [MONO_PATCH_INFO_NONE];
121         int jit_time, gen_time, link_time;
122 } MonoAotStats;
123
124 typedef struct MonoAotCompile {
125         MonoImage *image;
126         GPtrArray *methods;
127         GHashTable *method_indexes;
128         MonoCompile **cfgs;
129         int cfgs_size;
130         GHashTable *patch_to_plt_offset;
131         GHashTable *plt_offset_to_patch;
132         GHashTable *patch_to_shared_got_offset;
133         GPtrArray *shared_patches;
134         GHashTable *image_hash;
135         GHashTable *method_to_cfg;
136         GHashTable *token_info_hash;
137         GPtrArray *extra_methods;
138         GPtrArray *image_table;
139         GPtrArray *globals;
140         GList *method_order;
141         guint32 *plt_got_info_offsets;
142         /* Number of trampolines emitted into the AOT file */
143         guint32 num_aot_trampolines;
144         guint32 got_offset, plt_offset, plt_got_offset_base;
145         /* Number of GOT entries reserved for trampolines */
146         guint32 num_trampoline_got_entries;
147         guint32 trampoline_got_offset_base;
148         guint32 specific_trampoline_size;
149         MonoAotOptions aot_opts;
150         guint32 nmethods;
151         guint32 opts;
152         MonoMemPool *mempool;
153         MonoAotStats stats;
154         int method_index;
155         char *static_linking_symbol;
156         CRITICAL_SECTION mutex;
157         gboolean use_bin_writer;
158         MonoImageWriter *w;
159         const char *current_section;
160         int current_subsection;
161         const char *section_stack [16];
162         int subsection_stack [16];
163         int stack_pos;
164         FILE *fp;
165         char *tmpfname;
166         GSList *cie_program;
167         /* xdebug */
168         GHashTable *class_to_die;
169         int fde_index, tdie_index, line_number_file_index, line_number_dir_index;
170         GHashTable *file_to_index, *dir_to_index;
171         FILE *il_file;
172         int il_file_line_index, loclist_index;
173 } MonoAotCompile;
174
175 #define mono_acfg_lock(acfg) EnterCriticalSection (&((acfg)->mutex))
176 #define mono_acfg_unlock(acfg) LeaveCriticalSection (&((acfg)->mutex))
177
178 #ifdef HAVE_ARRAY_ELEM_INIT
179 #define MSGSTRFIELD(line) MSGSTRFIELD1(line)
180 #define MSGSTRFIELD1(line) str##line
181 static const struct msgstr_t {
182 #define PATCH_INFO(a,b) char MSGSTRFIELD(__LINE__) [sizeof (b)];
183 #include "patch-info.h"
184 #undef PATCH_INFO
185 } opstr = {
186 #define PATCH_INFO(a,b) b,
187 #include "patch-info.h"
188 #undef PATCH_INFO
189 };
190 static const gint16 opidx [] = {
191 #define PATCH_INFO(a,b) [MONO_PATCH_INFO_ ## a] = offsetof (struct msgstr_t, MSGSTRFIELD(__LINE__)),
192 #include "patch-info.h"
193 #undef PATCH_INFO
194 };
195
196 static const char*
197 get_patch_name (int info)
198 {
199         return (const char*)&opstr + opidx [info];
200 }
201
202 #else
203 #define PATCH_INFO(a,b) b,
204 static const char* const
205 patch_types [MONO_PATCH_INFO_NUM + 1] = {
206 #include "patch-info.h"
207         NULL
208 };
209
210 static const char*
211 get_patch_name (int info)
212 {
213         return patch_types [info];
214 }
215
216 #endif
217
218 static void
219 emit_global (MonoAotCompile *acfg, const char *name, gboolean func);
220
221 static void
222 emit_trampoline_dwarf_info (MonoAotCompile *acfg, const char *tramp_name, char *start_symbol, char *end_symbol, guint8 *code, guint32 code_size, GSList *unwind_info);
223
224 /* Wrappers around the image writer functions */
225
226 static inline void
227 emit_section_change (MonoAotCompile *acfg, const char *section_name, int subsection_index)
228 {
229         img_writer_emit_section_change (acfg->w, section_name, subsection_index);
230 }
231
232 static inline void
233 emit_push_section (MonoAotCompile *acfg, const char *section_name, int subsection)
234 {
235         img_writer_emit_push_section (acfg->w, section_name, subsection);
236 }
237
238 static inline void
239 emit_pop_section (MonoAotCompile *acfg)
240 {
241         img_writer_emit_pop_section (acfg->w);
242 }
243
244 static inline void
245 emit_local_symbol (MonoAotCompile *acfg, const char *name, const char *end_label, gboolean func) 
246
247         img_writer_emit_local_symbol (acfg->w, name, end_label, func); 
248 }
249
250 static inline void
251 emit_label (MonoAotCompile *acfg, const char *name) 
252
253         img_writer_emit_label (acfg->w, name); 
254 }
255
256 static inline void
257 emit_bytes (MonoAotCompile *acfg, const guint8* buf, int size) 
258
259         img_writer_emit_bytes (acfg->w, buf, size); 
260 }
261
262 static inline void
263 emit_string (MonoAotCompile *acfg, const char *value) 
264
265         img_writer_emit_string (acfg->w, value); 
266 }
267
268 static inline void
269 emit_line (MonoAotCompile *acfg) 
270
271         img_writer_emit_line (acfg->w); 
272 }
273
274 static inline void
275 emit_alignment (MonoAotCompile *acfg, int size) 
276
277         img_writer_emit_alignment (acfg->w, size); 
278 }
279
280 static inline void
281 emit_pointer_unaligned (MonoAotCompile *acfg, const char *target) 
282
283         img_writer_emit_pointer_unaligned (acfg->w, target); 
284 }
285
286 static inline void
287 emit_pointer (MonoAotCompile *acfg, const char *target) 
288
289         img_writer_emit_pointer (acfg->w, target); 
290 }
291
292 static inline void
293 emit_int16 (MonoAotCompile *acfg, int value) 
294
295         img_writer_emit_int16 (acfg->w, value); 
296 }
297
298 static inline void
299 emit_int32 (MonoAotCompile *acfg, int value) 
300
301         img_writer_emit_int32 (acfg->w, value); 
302 }
303
304 static inline void
305 emit_symbol_diff (MonoAotCompile *acfg, const char *end, const char* start, int offset) 
306
307         img_writer_emit_symbol_diff (acfg->w, end, start, offset); 
308 }
309
310 static inline void
311 emit_zero_bytes (MonoAotCompile *acfg, int num) 
312
313         img_writer_emit_zero_bytes (acfg->w, num); 
314 }
315
316 static inline void
317 emit_byte (MonoAotCompile *acfg, guint8 val) 
318
319         img_writer_emit_byte (acfg->w, val); 
320 }
321
322 static G_GNUC_UNUSED void
323 emit_global_inner (MonoAotCompile *acfg, const char *name, gboolean func)
324 {
325         img_writer_emit_global (acfg->w, name, func);
326 }
327
328 static void
329 emit_global (MonoAotCompile *acfg, const char *name, gboolean func)
330 {
331         if (acfg->aot_opts.no_dlsym) {
332                 g_ptr_array_add (acfg->globals, g_strdup (name));
333         } else {
334                 img_writer_emit_global (acfg->w, name, func);
335         }
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(__i386__) || defined(__x86_64__) || defined(__arm__)
437 #define EMIT_DWARF_INFO 1
438 #endif
439
440 /*
441  * arch_emit_direct_call:
442  *
443  *   Emit a direct call to the symbol TARGET. CALL_SIZE is set to the size of the
444  * calling code.
445  */
446 static void
447 arch_emit_direct_call (MonoAotCompile *acfg, const char *target, int *call_size)
448 {
449 #if defined(__i386__) || defined(__x86_64__)
450         /* Need to make sure this is exactly 5 bytes long */
451         emit_byte (acfg, '\xe8');
452         emit_symbol_diff (acfg, target, ".", -4);
453         *call_size = 5;
454 #elif defined(__arm__)
455         if (acfg->use_bin_writer) {
456                 guint8 buf [4];
457                 guint8 *code;
458
459                 code = buf;
460                 ARM_BL (code, 0);
461
462                 img_writer_emit_reloc (acfg->w, R_ARM_CALL, target, -8);
463                 emit_bytes (acfg, buf, 4);
464         } else {
465                 img_writer_emit_unset_mode (acfg->w);
466                 fprintf (acfg->fp, "bl %s\n", target);
467         }
468         *call_size = 4;
469 #else
470         g_assert_not_reached ();
471 #endif
472 }
473
474 /*
475  * arch_emit_got_access:
476  *
477  *   The memory pointed to by CODE should hold native code for loading a GOT
478  * slot. Emit this code while patching it so it accesses the GOT slot GOT_SLOT.
479  * CODE_SIZE is set to the number of bytes emitted.
480  */
481 static void
482 arch_emit_got_access (MonoAotCompile *acfg, guint8 *code, int got_slot, int *code_size)
483 {
484         /* Emit beginning of instruction */
485         emit_bytes (acfg, code, mono_arch_get_patch_offset (code));
486
487         /* Emit the offset */
488 #ifdef __x86_64__
489         emit_symbol_diff (acfg, "got", ".", (unsigned int) ((got_slot * sizeof (gpointer)) - 4));
490 #elif defined(__i386__)
491         emit_int32 (acfg, (unsigned int) ((got_slot * sizeof (gpointer))));
492 #elif defined(__arm__)
493         emit_symbol_diff (acfg, "got", ".", (unsigned int) ((got_slot * sizeof (gpointer))) - 12);
494 #else
495         g_assert_not_reached ();
496 #endif
497
498         *code_size = mono_arch_get_patch_offset (code) + 4;
499 }
500
501 /*
502  * arch_emit_plt_entry:
503  *
504  *   Emit code for the PLT entry with index INDEX.
505  */
506 static void
507 arch_emit_plt_entry (MonoAotCompile *acfg, int index)
508 {
509 #if defined(__i386__)
510                 if (index == 0) {
511                         /* It is filled up during loading by the AOT loader. */
512                         emit_zero_bytes (acfg, 16);
513                 } else {
514                         /* Need to make sure this is 9 bytes long */
515                         emit_byte (acfg, '\xe9');
516                         emit_symbol_diff (acfg, "plt", ".", -4);
517                         emit_int32 (acfg, acfg->plt_got_info_offsets [index]);
518                 }
519 #elif defined(__x86_64__)
520                 /*
521                  * We can't emit jumps because they are 32 bits only so they can't be patched.
522                  * So we make indirect calls through GOT entries which are patched by the AOT 
523                  * loader to point to .Lpd entries. 
524                  * An x86_64 plt entry is 10 bytes long, init_plt () depends on this.
525                  */
526                 /* jmpq *<offset>(%rip) */
527                 emit_byte (acfg, '\xff');
528                 emit_byte (acfg, '\x25');
529                 emit_symbol_diff (acfg, "got", ".", ((acfg->plt_got_offset_base + index) * sizeof (gpointer)) -4);
530                 /* Used by mono_aot_get_plt_info_offset */
531                 emit_int32 (acfg, acfg->plt_got_info_offsets [index]);
532 #elif defined(__arm__)
533                 guint8 buf [256];
534                 guint8 *code;
535
536                 /* FIXME:
537                  * - optimize OP_AOTCONST implementation
538                  * - optimize the PLT entries
539                  * - optimize SWITCH AOT implementation
540                  * - implement IMT support
541                  */
542                 code = buf;
543                 if (acfg->use_bin_writer) {
544                         /* We only emit 1 relocation since we implement it ourselves anyway */
545                         img_writer_emit_reloc (acfg->w, R_ARM_ALU_PC_G0_NC, "got", ((acfg->plt_got_offset_base + index) * sizeof (gpointer)) - 8);
546                         /* FIXME: A 2 instruction encoding is sufficient in most cases */
547                         ARM_ADD_REG_IMM (code, ARMREG_IP, ARMREG_PC, 0, 0);
548                         ARM_ADD_REG_IMM (code, ARMREG_IP, ARMREG_IP, 0, 0);
549                         ARM_LDR_IMM (code, ARMREG_PC, ARMREG_IP, 0);
550                         emit_bytes (acfg, buf, code - buf);
551                         /* FIXME: Get rid of this */
552                         emit_symbol_diff (acfg, "got", ".", ((acfg->plt_got_offset_base + index) * sizeof (gpointer)));
553                         /* Used by mono_aot_get_plt_info_offset */
554                         emit_int32 (acfg, acfg->plt_got_info_offsets [index]);
555                 } else {
556                         ARM_LDR_IMM (code, ARMREG_IP, ARMREG_PC, 4);
557                         ARM_ADD_REG_REG (code, ARMREG_IP, ARMREG_PC, ARMREG_IP);
558                         ARM_LDR_IMM (code, ARMREG_PC, ARMREG_IP, 0);
559                         emit_bytes (acfg, buf, code - buf);
560                         emit_symbol_diff (acfg, "got", ".", ((acfg->plt_got_offset_base + index) * sizeof (gpointer)));
561                         /* Used by mono_aot_get_plt_info_offset */
562                         emit_int32 (acfg, acfg->plt_got_info_offsets [index]);
563                 }
564 #else
565                 g_assert_not_reached ();
566 #endif
567 }
568
569 /*
570  * arch_emit_specific_trampoline:
571  *
572  *   Emit code for a specific trampoline. OFFSET is the offset of the first of
573  * two GOT slots which contain the generic trampoline address and the trampoline
574  * argument. TRAMP_SIZE is set to the size of the emitted trampoline.
575  */
576 static void
577 arch_emit_specific_trampoline (MonoAotCompile *acfg, int offset, int *tramp_size)
578 {
579         /*
580          * The trampolines created here are variations of the specific 
581          * trampolines created in mono_arch_create_specific_trampoline (). The 
582          * differences are:
583          * - the generic trampoline address is taken from a got slot.
584          * - the offset of the got slot where the trampoline argument is stored
585          *   is embedded in the instruction stream, and the generic trampoline
586          *   can load the argument by loading the offset, adding it to the
587          *   address of the trampoline to get the address of the got slot, and
588          *   loading the argument from there.
589          * - all the trampolines should be of the same length.
590          */
591 #if defined(__x86_64__)
592         /* This should be exactly 16 bytes long */
593         *tramp_size = 16;
594         /* call *<offset>(%rip) */
595         emit_byte (acfg, '\x41');
596         emit_byte (acfg, '\xff');
597         emit_byte (acfg, '\x15');
598         emit_symbol_diff (acfg, "got", ".", (offset * sizeof (gpointer)) - 4);
599         /* This should be relative to the start of the trampoline */
600         emit_symbol_diff (acfg, "got", ".", (offset * sizeof (gpointer)) - 4 + 19);
601         emit_zero_bytes (acfg, 5);
602 #elif defined(__arm__)
603         guint8 buf [128];
604         guint8 *code;
605
606         /* This should be exactly 28 bytes long */
607         *tramp_size = 28;
608         code = buf;
609         ARM_PUSH (code, 0x5fff);
610         ARM_LDR_IMM (code, ARMREG_R1, ARMREG_PC, 8);
611         /* Load the value from the GOT */
612         ARM_LDR_REG_REG (code, ARMREG_R1, ARMREG_PC, ARMREG_R1);
613         /* Branch to it */
614         ARM_MOV_REG_REG (code, ARMREG_LR, ARMREG_PC);
615         ARM_MOV_REG_REG (code, ARMREG_PC, ARMREG_R1);
616
617         g_assert (code - buf == 20);
618
619         /* Emit it */
620         emit_bytes (acfg, buf, code - buf);
621         emit_symbol_diff (acfg, "got", ".", (offset * sizeof (gpointer)) - 4 + 8);
622         emit_symbol_diff (acfg, "got", ".", ((offset + 1) * sizeof (gpointer)) - 4 + 8);
623 #else
624         g_assert_not_reached ();
625 #endif
626 }
627
628 /*
629  * arch_emit_unbox_trampoline:
630  *
631  *   Emit code for the unbox trampoline for METHOD used in the full-aot case.
632  * CALL_TARGET is the symbol pointing to the native code of METHOD.
633  */
634 static void
635 arch_emit_unbox_trampoline (MonoAotCompile *acfg, MonoMethod *method, MonoGenericSharingContext *gsctx, const char *call_target)
636 {
637 #if defined(__x86_64__)
638         guint8 buf [32];
639         guint8 *code;
640         int this_reg;
641
642         this_reg = mono_arch_get_this_arg_reg (mono_method_signature (method), gsctx, NULL);
643         code = buf;
644         amd64_alu_reg_imm (code, X86_ADD, this_reg, sizeof (MonoObject));
645
646         emit_bytes (acfg, buf, code - buf);
647         /* jump <method> */
648         emit_byte (acfg, '\xe9');
649         emit_symbol_diff (acfg, call_target, ".", -4);
650 #elif defined(__arm__)
651         guint8 buf [128];
652         guint8 *code;
653         int this_pos = 0;
654
655         code = buf;
656
657         if (MONO_TYPE_ISSTRUCT (mono_method_signature (method)->ret))
658                 this_pos = 1;
659
660         ARM_ADD_REG_IMM8 (code, this_pos, this_pos, sizeof (MonoObject));
661
662         emit_bytes (acfg, buf, code - buf);
663         /* jump to method */
664         if (acfg->use_bin_writer)
665                 g_assert_not_reached ();
666         else
667                 fprintf (acfg->fp, "\n\tb %s\n", call_target);
668 #else
669         g_assert_not_reached ();
670 #endif
671 }
672
673 /*
674  * arch_get_cie_program:
675  *
676  *   Get the unwind bytecode for the DWARF CIE.
677  */
678 static GSList*
679 arch_get_cie_program (MonoAotCompile *acfg)
680 {
681 #ifdef __x86_64__
682         GSList *l = NULL;
683
684         mono_add_unwind_op_def_cfa (l, (guint8*)NULL, (guint8*)NULL, AMD64_RSP, 8);
685         mono_add_unwind_op_offset (l, (guint8*)NULL, (guint8*)NULL, AMD64_RIP, -8);
686
687         return l;
688 #else
689         return NULL;
690 #endif
691 }
692
693 /* END OF ARCH SPECIFIC CODE */
694
695 static guint32
696 mono_get_field_token (MonoClassField *field) 
697 {
698         MonoClass *klass = field->parent;
699         int i;
700
701         for (i = 0; i < klass->field.count; ++i) {
702                 if (field == &klass->fields [i])
703                         return MONO_TOKEN_FIELD_DEF | (klass->field.first + 1 + i);
704         }
705
706         g_assert_not_reached ();
707         return 0;
708 }
709
710 static inline void
711 encode_value (gint32 value, guint8 *buf, guint8 **endbuf)
712 {
713         guint8 *p = buf;
714
715         //printf ("ENCODE: %d 0x%x.\n", value, value);
716
717         /* 
718          * Same encoding as the one used in the metadata, extended to handle values
719          * greater than 0x1fffffff.
720          */
721         if ((value >= 0) && (value <= 127))
722                 *p++ = value;
723         else if ((value >= 0) && (value <= 16383)) {
724                 p [0] = 0x80 | (value >> 8);
725                 p [1] = value & 0xff;
726                 p += 2;
727         } else if ((value >= 0) && (value <= 0x1fffffff)) {
728                 p [0] = (value >> 24) | 0xc0;
729                 p [1] = (value >> 16) & 0xff;
730                 p [2] = (value >> 8) & 0xff;
731                 p [3] = value & 0xff;
732                 p += 4;
733         }
734         else {
735                 p [0] = 0xff;
736                 p [1] = (value >> 24) & 0xff;
737                 p [2] = (value >> 16) & 0xff;
738                 p [3] = (value >> 8) & 0xff;
739                 p [4] = value & 0xff;
740                 p += 5;
741         }
742         if (endbuf)
743                 *endbuf = p;
744 }
745
746 static guint32
747 get_image_index (MonoAotCompile *cfg, MonoImage *image)
748 {
749         guint32 index;
750
751         index = GPOINTER_TO_UINT (g_hash_table_lookup (cfg->image_hash, image));
752         if (index)
753                 return index - 1;
754         else {
755                 index = g_hash_table_size (cfg->image_hash);
756                 g_hash_table_insert (cfg->image_hash, image, GUINT_TO_POINTER (index + 1));
757                 g_ptr_array_add (cfg->image_table, image);
758                 return index;
759         }
760 }
761
762 static guint32
763 find_typespec_for_class (MonoAotCompile *acfg, MonoClass *klass)
764 {
765         int i;
766         MonoClass *k = NULL;
767
768         /* FIXME: Search referenced images as well */
769         for (i = 0; i < acfg->image->tables [MONO_TABLE_TYPESPEC].rows; ++i) {
770                 k = mono_class_get_full (acfg->image, MONO_TOKEN_TYPE_SPEC | (i + 1), NULL);
771                 if (k == klass)
772                         break;
773         }
774
775         if (i < acfg->image->tables [MONO_TABLE_TYPESPEC].rows)
776                 return MONO_TOKEN_TYPE_SPEC | (i + 1);
777         else
778                 return 0;
779 }
780
781 static void
782 encode_method_ref (MonoAotCompile *acfg, MonoMethod *method, guint8 *buf, guint8 **endbuf);
783
784 /*
785  * encode_klass_ref:
786  *
787  *   Encode a reference to KLASS. We use our home-grown encoding instead of the
788  * standard metadata encoding.
789  */
790 static void
791 encode_klass_ref (MonoAotCompile *acfg, MonoClass *klass, guint8 *buf, guint8 **endbuf)
792 {
793         guint8 *p = buf;
794
795         if (klass->generic_class) {
796                 guint32 token;
797                 g_assert (klass->type_token);
798
799                 /* Find a typespec for a class if possible */
800                 token = find_typespec_for_class (acfg, klass);
801                 if (token) {
802                         encode_value (token, p, &p);
803                         encode_value (get_image_index (acfg, acfg->image), p, &p);
804                 } else {
805                         MonoClass *gclass = klass->generic_class->container_class;
806                         MonoGenericInst *inst = klass->generic_class->context.class_inst;
807                         int i;
808
809                         /* Encode it ourselves */
810                         /* Marker */
811                         encode_value (MONO_TOKEN_TYPE_SPEC, p, &p);
812                         encode_value (MONO_TYPE_GENERICINST, p, &p);
813                         encode_klass_ref (acfg, gclass, p, &p);
814                         encode_value (inst->type_argc, p, &p);
815                         for (i = 0; i < inst->type_argc; ++i)
816                                 encode_klass_ref (acfg, mono_class_from_mono_type (inst->type_argv [i]), p, &p);
817                 }
818         } else if (klass->type_token) {
819                 g_assert (mono_metadata_token_code (klass->type_token) == MONO_TOKEN_TYPE_DEF);
820                 encode_value (klass->type_token - MONO_TOKEN_TYPE_DEF, p, &p);
821                 encode_value (get_image_index (acfg, klass->image), p, &p);
822         } else if ((klass->byval_arg.type == MONO_TYPE_VAR) || (klass->byval_arg.type == MONO_TYPE_MVAR)) {
823                 MonoGenericParam *param = klass->byval_arg.data.generic_param;
824
825                 /* Marker */
826                 encode_value (MONO_TOKEN_TYPE_SPEC, p, &p);
827                 encode_value (klass->byval_arg.type, p, &p);
828
829                 encode_value (param->num, p, &p);
830                 
831                 g_assert (param->owner);
832                 encode_value (param->owner->is_method, p, &p);
833                 if (param->owner->is_method)
834                         encode_method_ref (acfg, param->owner->owner.method, p, &p);
835                 else
836                         encode_klass_ref (acfg, param->owner->owner.klass, p, &p);
837         } else {
838                 /* Array class */
839                 g_assert (klass->rank > 0);
840                 encode_value (MONO_TOKEN_TYPE_DEF, p, &p);
841                 encode_value (get_image_index (acfg, klass->image), p, &p);
842                 encode_value (klass->rank, p, &p);
843                 encode_klass_ref (acfg, klass->element_class, p, &p);
844         }
845         *endbuf = p;
846 }
847
848 static void
849 encode_field_info (MonoAotCompile *cfg, MonoClassField *field, guint8 *buf, guint8 **endbuf)
850 {
851         guint32 token = mono_get_field_token (field);
852         guint8 *p = buf;
853
854         encode_klass_ref (cfg, field->parent, p, &p);
855         g_assert (mono_metadata_token_code (token) == MONO_TOKEN_FIELD_DEF);
856         encode_value (token - MONO_TOKEN_FIELD_DEF, p, &p);
857         *endbuf = p;
858 }
859
860 static void
861 encode_generic_context (MonoAotCompile *acfg, MonoGenericContext *context, guint8 *buf, guint8 **endbuf)
862 {
863         guint8 *p = buf;
864         int i;
865         MonoGenericInst *inst;
866
867         /* Encode the context */
868         inst = context->class_inst;
869         encode_value (inst ? 1 : 0, p, &p);
870         if (inst) {
871                 encode_value (inst->type_argc, p, &p);
872                 for (i = 0; i < inst->type_argc; ++i)
873                         encode_klass_ref (acfg, mono_class_from_mono_type (inst->type_argv [i]), p, &p);
874         }
875         inst = context->method_inst;
876         encode_value (inst ? 1 : 0, p, &p);
877         if (inst) {
878                 encode_value (inst->type_argc, p, &p);
879                 for (i = 0; i < inst->type_argc; ++i)
880                         encode_klass_ref (acfg, mono_class_from_mono_type (inst->type_argv [i]), p, &p);
881         }
882
883         *endbuf = p;
884 }
885
886 #define MAX_IMAGE_INDEX 250
887
888 static void
889 encode_method_ref (MonoAotCompile *acfg, MonoMethod *method, guint8 *buf, guint8 **endbuf)
890 {
891         guint32 image_index = get_image_index (acfg, method->klass->image);
892         guint32 token = method->token;
893         MonoJumpInfoToken *ji;
894         guint8 *p = buf;
895         char *name;
896
897         /*
898          * The encoding for most methods is as follows:
899          * - image index encoded as a leb128
900          * - token index encoded as a leb128
901          * Values of image index >= MONO_AOT_METHODREF_MIN are used to mark additional
902          * types of method encodings.
903          */
904
905         g_assert (image_index < MONO_AOT_METHODREF_MIN);
906
907         /* Mark methods which can't use aot trampolines because they need the further 
908          * processing in mono_magic_trampoline () which requires a MonoMethod*.
909          */
910         if ((method->is_generic && (method->flags & METHOD_ATTRIBUTE_VIRTUAL)) ||
911                 (method->iflags & METHOD_IMPL_ATTRIBUTE_SYNCHRONIZED))
912                 encode_value ((MONO_AOT_METHODREF_NO_AOT_TRAMPOLINE << 24), p, &p);
913
914         /* 
915          * Some wrapper methods are shared using their signature, encode their 
916          * stringified signature instead.
917          * FIXME: Optimize disk usage
918          */
919         name = NULL;
920         if (method->wrapper_type) {
921                 if (method->wrapper_type == MONO_WRAPPER_RUNTIME_INVOKE) {
922                         char *tmpsig = mono_signature_get_desc (mono_method_signature (method), TRUE);
923                         name = g_strdup_printf ("(wrapper runtime-invoke):%s (%s)", method->name, tmpsig);
924                         g_free (tmpsig);
925                 } else if (method->wrapper_type == MONO_WRAPPER_DELEGATE_INVOKE) {
926                         char *tmpsig = mono_signature_get_desc (mono_method_signature (method), TRUE);
927                         name = g_strdup_printf ("(wrapper delegate-invoke):%s (%s)", method->name, tmpsig);
928                         g_free (tmpsig);
929                 } else if (method->wrapper_type == MONO_WRAPPER_DELEGATE_BEGIN_INVOKE) {
930                         char *tmpsig = mono_signature_get_desc (mono_method_signature (method), TRUE);
931                         name = g_strdup_printf ("(wrapper delegate-begin-invoke):%s (%s)", method->name, tmpsig);
932                         g_free (tmpsig);
933                 } else if (method->wrapper_type == MONO_WRAPPER_DELEGATE_END_INVOKE) {
934                         char *tmpsig = mono_signature_get_desc (mono_method_signature (method), TRUE);
935                         name = g_strdup_printf ("(wrapper delegate-end-invoke):%s (%s)", method->name, tmpsig);
936                         g_free (tmpsig);
937                 }
938         }
939
940         if (name) {
941                 encode_value ((MONO_AOT_METHODREF_WRAPPER_NAME << 24), p, &p);
942                 strcpy ((char*)p, name);
943                 p += strlen (name) + 1;
944                 g_free (name);
945         } else if (method->wrapper_type) {
946                 encode_value ((MONO_AOT_METHODREF_WRAPPER << 24), p, &p);
947
948                 encode_value (method->wrapper_type, p, &p);
949
950                 switch (method->wrapper_type) {
951                 case MONO_WRAPPER_REMOTING_INVOKE:
952                 case MONO_WRAPPER_REMOTING_INVOKE_WITH_CHECK:
953                 case MONO_WRAPPER_XDOMAIN_INVOKE: {
954                         MonoMethod *m;
955
956                         m = mono_marshal_method_from_wrapper (method);
957                         g_assert (m);
958                         encode_method_ref (acfg, m, p, &p);
959                         break;
960                 }
961                 case MONO_WRAPPER_PROXY_ISINST:
962                 case MONO_WRAPPER_LDFLD:
963                 case MONO_WRAPPER_LDFLDA:
964                 case MONO_WRAPPER_STFLD:
965                 case MONO_WRAPPER_ISINST: {
966                         MonoClass *proxy_class = (MonoClass*)mono_marshal_method_from_wrapper (method);
967                         encode_klass_ref (acfg, proxy_class, p, &p);
968                         break;
969                 }
970                 case MONO_WRAPPER_LDFLD_REMOTE:
971                 case MONO_WRAPPER_STFLD_REMOTE:
972                         break;
973                 case MONO_WRAPPER_ALLOC: {
974                         int alloc_type = mono_gc_get_managed_allocator_type (method);
975                         g_assert (alloc_type != -1);
976                         encode_value (alloc_type, p, &p);
977                         break;
978                 }
979                 case MONO_WRAPPER_STELEMREF:
980                         break;
981                 case MONO_WRAPPER_UNKNOWN:
982                         if (strcmp (method->name, "FastMonitorEnter") == 0)
983                                 encode_value (MONO_AOT_WRAPPER_MONO_ENTER, p, &p);
984                         else if (strcmp (method->name, "FastMonitorExit") == 0)
985                                 encode_value (MONO_AOT_WRAPPER_MONO_EXIT, p, &p);
986                         else
987                                 g_assert_not_reached ();
988                         break;
989                 case MONO_WRAPPER_STATIC_RGCTX_INVOKE:
990                 case MONO_WRAPPER_SYNCHRONIZED: {
991                         MonoMethod *m;
992
993                         m = mono_marshal_method_from_wrapper (method);
994                         g_assert (m);
995                         encode_method_ref (acfg, m, p, &p);
996                         break;
997                 }
998                 default:
999                         g_assert_not_reached ();
1000                 }
1001         } else if (mono_method_signature (method)->is_inflated) {
1002                 /* 
1003                  * This is a generic method, find the original token which referenced it and
1004                  * encode that.
1005                  * Obtain the token from information recorded by the JIT.
1006                  */
1007                 ji = g_hash_table_lookup (acfg->token_info_hash, method);
1008                 if (ji) {
1009                         image_index = get_image_index (acfg, ji->image);
1010                         g_assert (image_index < MAX_IMAGE_INDEX);
1011                         token = ji->token;
1012
1013                         encode_value ((MONO_AOT_METHODREF_METHODSPEC << 24), p, &p);
1014                         encode_value (image_index, p, &p);
1015                         encode_value (token, p, &p);
1016                 } else {
1017                         MonoMethod *declaring;
1018                         MonoGenericContext *context = mono_method_get_context (method);
1019
1020                         g_assert (method->is_inflated);
1021                         declaring = ((MonoMethodInflated*)method)->declaring;
1022
1023                         /*
1024                          * This might be a non-generic method of a generic instance, which 
1025                          * doesn't have a token since the reference is generated by the JIT 
1026                          * like Nullable:Box/Unbox, or by generic sharing.
1027                          */
1028
1029                         encode_value ((MONO_AOT_METHODREF_GINST << 24), p, &p);
1030                         /* Encode the klass */
1031                         encode_klass_ref (acfg, method->klass, p, &p);
1032                         /* Encode the method */
1033                         image_index = get_image_index (acfg, method->klass->image);
1034                         g_assert (image_index < MAX_IMAGE_INDEX);
1035                         g_assert (declaring->token);
1036                         token = declaring->token;
1037                         g_assert (mono_metadata_token_table (token) == MONO_TABLE_METHOD);
1038                         encode_value (image_index, p, &p);
1039                         encode_value (token, p, &p);
1040                         encode_generic_context (acfg, context, p, &p);
1041                 }
1042         } else if (token == 0) {
1043                 /* This might be a method of a constructed type like int[,].Set */
1044                 /* Obtain the token from information recorded by the JIT */
1045                 ji = g_hash_table_lookup (acfg->token_info_hash, method);
1046                 if (ji) {
1047                         image_index = get_image_index (acfg, ji->image);
1048                         g_assert (image_index < MAX_IMAGE_INDEX);
1049                         token = ji->token;
1050
1051                         encode_value ((MONO_AOT_METHODREF_METHODSPEC << 24), p, &p);
1052                         encode_value (image_index, p, &p);
1053                         encode_value (token, p, &p);
1054                 } else {
1055                         /* Array methods */
1056                         g_assert (method->klass->rank);
1057
1058                         /* Encode directly */
1059                         encode_value ((MONO_AOT_METHODREF_ARRAY << 24), p, &p);
1060                         encode_klass_ref (acfg, method->klass, p, &p);
1061                         if (!strcmp (method->name, ".ctor") && mono_method_signature (method)->param_count == method->klass->rank)
1062                                 encode_value (0, p, &p);
1063                         else if (!strcmp (method->name, ".ctor") && mono_method_signature (method)->param_count == method->klass->rank * 2)
1064                                 encode_value (1, p, &p);
1065                         else if (!strcmp (method->name, "Get"))
1066                                 encode_value (2, p, &p);
1067                         else if (!strcmp (method->name, "Address"))
1068                                 encode_value (3, p, &p);
1069                         else if (!strcmp (method->name, "Set"))
1070                                 encode_value (4, p, &p);
1071                         else
1072                                 g_assert_not_reached ();
1073                 }
1074         } else {
1075                 g_assert (mono_metadata_token_table (token) == MONO_TABLE_METHOD);
1076                 encode_value ((image_index << 24) | mono_metadata_token_index (token), p, &p);
1077         }
1078         *endbuf = p;
1079 }
1080
1081 static gint
1082 compare_patches (gconstpointer a, gconstpointer b)
1083 {
1084         int i, j;
1085
1086         i = (*(MonoJumpInfo**)a)->ip.i;
1087         j = (*(MonoJumpInfo**)b)->ip.i;
1088
1089         if (i < j)
1090                 return -1;
1091         else
1092                 if (i > j)
1093                         return 1;
1094         else
1095                 return 0;
1096 }
1097
1098 /*
1099  * is_plt_patch:
1100  *
1101  *   Return whenever PATCH_INFO refers to a direct call, and thus requires a
1102  * PLT entry.
1103  */
1104 static inline gboolean
1105 is_plt_patch (MonoJumpInfo *patch_info)
1106 {
1107         switch (patch_info->type) {
1108         case MONO_PATCH_INFO_METHOD:
1109         case MONO_PATCH_INFO_INTERNAL_METHOD:
1110         case MONO_PATCH_INFO_JIT_ICALL_ADDR:
1111         case MONO_PATCH_INFO_ICALL_ADDR:
1112         case MONO_PATCH_INFO_CLASS_INIT:
1113         case MONO_PATCH_INFO_RGCTX_FETCH:
1114         case MONO_PATCH_INFO_GENERIC_CLASS_INIT:
1115         case MONO_PATCH_INFO_MONITOR_ENTER:
1116         case MONO_PATCH_INFO_MONITOR_EXIT:
1117                 return TRUE;
1118         default:
1119                 return FALSE;
1120         }
1121 }
1122
1123 static gboolean 
1124 is_got_patch (MonoJumpInfoType patch_type)
1125 {
1126         return TRUE;
1127 }
1128
1129 /*
1130  * is_shared_got_patch:
1131  *
1132  *   Return whenever PATCH_INFO refers to a patch which needs a shared GOT
1133  * entry.
1134  * Keep it in sync with the version in aot-runtime.c.
1135  */
1136 static inline gboolean
1137 is_shared_got_patch (MonoJumpInfo *patch_info)
1138 {
1139         switch (patch_info->type) {
1140         case MONO_PATCH_INFO_VTABLE:
1141         case MONO_PATCH_INFO_CLASS:
1142         case MONO_PATCH_INFO_IID:
1143         case MONO_PATCH_INFO_ADJUSTED_IID:
1144         case MONO_PATCH_INFO_FIELD:
1145         case MONO_PATCH_INFO_SFLDA:
1146         case MONO_PATCH_INFO_DECLSEC:
1147         case MONO_PATCH_INFO_LDTOKEN:
1148         case MONO_PATCH_INFO_TYPE_FROM_HANDLE:
1149         case MONO_PATCH_INFO_RVA:
1150         case MONO_PATCH_INFO_METHODCONST:
1151         case MONO_PATCH_INFO_IMAGE:
1152                 return TRUE;
1153         default:
1154                 return FALSE;
1155         }
1156 }
1157
1158 static int
1159 get_plt_offset (MonoAotCompile *acfg, MonoJumpInfo *patch_info)
1160 {
1161         int res = -1;
1162
1163         if (is_plt_patch (patch_info)) {
1164                 int idx = GPOINTER_TO_UINT (g_hash_table_lookup (acfg->patch_to_plt_offset, patch_info));
1165
1166                 if (patch_info->type == MONO_PATCH_INFO_METHOD && (patch_info->data.method->iflags & METHOD_IMPL_ATTRIBUTE_SYNCHRONIZED)) {
1167                         /* 
1168                          * Allocate a separate PLT slot for each such patch, since some plt
1169                          * entries will refer to the method itself, and some will refer to
1170                          * wrapper.
1171                          */
1172                         idx = 0;
1173                 }
1174
1175                 if (idx) {
1176                         res = idx;
1177                 } else {
1178                         MonoJumpInfo *new_ji = mono_patch_info_dup_mp (acfg->mempool, patch_info);
1179
1180                         res = acfg->plt_offset;
1181                         g_hash_table_insert (acfg->plt_offset_to_patch, GUINT_TO_POINTER (res), new_ji);
1182                         g_hash_table_insert (acfg->patch_to_plt_offset, new_ji, GUINT_TO_POINTER (res));
1183                         acfg->plt_offset ++;
1184                 }
1185         }
1186
1187         return res;
1188 }
1189
1190 /**
1191  * get_got_offset:
1192  *
1193  *   Returns the offset of the GOT slot where the runtime object resulting from resolving
1194  * JI could be found if it exists, otherwise allocates a new one.
1195  */
1196 static guint32
1197 get_got_offset (MonoAotCompile *acfg, MonoJumpInfo *ji)
1198 {
1199         guint32 got_offset;
1200
1201         got_offset = GPOINTER_TO_UINT (g_hash_table_lookup (acfg->patch_to_shared_got_offset, ji));
1202         if (got_offset)
1203                 return got_offset - 1;
1204
1205         got_offset = acfg->got_offset;
1206         acfg->got_offset ++;
1207
1208         acfg->stats.got_slots ++;
1209         acfg->stats.got_slot_types [ji->type] ++;
1210
1211         return got_offset;
1212 }
1213
1214 static guint32
1215 get_shared_got_offset (MonoAotCompile *acfg, MonoJumpInfo *ji)
1216 {
1217         MonoJumpInfo *copy;
1218         guint32 got_offset;
1219
1220         if (!g_hash_table_lookup (acfg->patch_to_shared_got_offset, ji)) {
1221                 got_offset = get_got_offset (acfg, ji);
1222                 copy = mono_patch_info_dup_mp (acfg->mempool, ji);
1223                 g_hash_table_insert (acfg->patch_to_shared_got_offset, copy, GUINT_TO_POINTER (got_offset + 1));
1224                 g_ptr_array_add (acfg->shared_patches, copy);
1225         }
1226
1227         return get_got_offset (acfg, ji);
1228 }
1229
1230 /* Add a method to the list of methods which need to be emitted */
1231 static void
1232 add_method_with_index (MonoAotCompile *acfg, MonoMethod *method, int index)
1233 {
1234         g_assert (method);
1235         if (!g_hash_table_lookup (acfg->method_indexes, method)) {
1236                 g_ptr_array_add (acfg->methods, method);
1237                 g_hash_table_insert (acfg->method_indexes, method, GUINT_TO_POINTER (index + 1));
1238                 acfg->nmethods = acfg->methods->len + 1;
1239         }
1240 }
1241
1242 static guint32
1243 get_method_index (MonoAotCompile *acfg, MonoMethod *method)
1244 {
1245         int index = GPOINTER_TO_UINT (g_hash_table_lookup (acfg->method_indexes, method));
1246         
1247         g_assert (index);
1248
1249         return index - 1;
1250 }
1251
1252 static int
1253 add_method (MonoAotCompile *acfg, MonoMethod *method)
1254 {
1255         int index;
1256
1257         index = GPOINTER_TO_UINT (g_hash_table_lookup (acfg->method_indexes, method));
1258         if (index)
1259                 return index - 1;
1260
1261         index = acfg->method_index;
1262         add_method_with_index (acfg, method, index);
1263
1264         /* FIXME: Fix quadratic behavior */
1265         acfg->method_order = g_list_append (acfg->method_order, GUINT_TO_POINTER (index));
1266
1267         acfg->method_index ++;
1268
1269         return index;
1270 }
1271
1272 static void
1273 add_extra_method (MonoAotCompile *acfg, MonoMethod *method)
1274 {
1275         int index;
1276
1277         index = GPOINTER_TO_UINT (g_hash_table_lookup (acfg->method_indexes, method));
1278         if (index)
1279                 return;
1280         add_method (acfg, method);
1281         g_ptr_array_add (acfg->extra_methods, method);
1282 }
1283
1284 static void
1285 add_jit_icall_wrapper (gpointer key, gpointer value, gpointer user_data)
1286 {
1287         MonoAotCompile *acfg = user_data;
1288         MonoJitICallInfo *callinfo = value;
1289         MonoMethod *wrapper;
1290         char *name;
1291
1292         if (!callinfo->sig)
1293                 return;
1294
1295         name = g_strdup_printf ("__icall_wrapper_%s", callinfo->name);
1296         wrapper = mono_marshal_get_icall_wrapper (callinfo->sig, name, callinfo->func, check_for_pending_exc);
1297         g_free (name);
1298
1299         add_method (acfg, wrapper);
1300 }
1301
1302 static MonoMethod*
1303 get_runtime_invoke_sig (MonoMethodSignature *sig)
1304 {
1305         MonoMethodBuilder *mb;
1306         MonoMethod *m;
1307
1308         mb = mono_mb_new (mono_defaults.object_class, "FOO", MONO_WRAPPER_NONE);
1309         m = mono_mb_create_method (mb, sig, 16);
1310         return mono_marshal_get_runtime_invoke (m);
1311 }
1312
1313 static void
1314 add_wrappers (MonoAotCompile *acfg)
1315 {
1316         MonoMethod *method, *m;
1317         int i, j, nallocators;
1318         MonoMethodSignature *sig, *csig;
1319         guint32 token;
1320
1321         /* 
1322          * FIXME: Instead of AOTing all the wrappers, it might be better to redesign them
1323          * so there is only one wrapper of a given type, or inlining their contents into their
1324          * callers.
1325          */
1326
1327         /* 
1328          * FIXME: This depends on the fact that different wrappers have different 
1329          * names.
1330          */
1331
1332         /* FIXME: Collect these automatically */
1333
1334         /* Runtime invoke wrappers */
1335
1336         /* void runtime-invoke () [.cctor] */
1337         csig = mono_metadata_signature_alloc (mono_defaults.corlib, 0);
1338         csig->ret = &mono_defaults.void_class->byval_arg;
1339         add_method (acfg, get_runtime_invoke_sig (csig));
1340
1341         /* void runtime-invoke () [Finalize] */
1342         csig = mono_metadata_signature_alloc (mono_defaults.corlib, 0);
1343         csig->hasthis = 1;
1344         csig->ret = &mono_defaults.void_class->byval_arg;
1345         add_method (acfg, get_runtime_invoke_sig (csig));
1346
1347         /* void runtime-invoke (string) [exception ctor] */
1348         csig = mono_metadata_signature_alloc (mono_defaults.corlib, 1);
1349         csig->hasthis = 1;
1350         csig->ret = &mono_defaults.void_class->byval_arg;
1351         csig->params [0] = &mono_defaults.string_class->byval_arg;
1352         add_method (acfg, get_runtime_invoke_sig (csig));
1353
1354         /* void runtime-invoke (string, string) [exception ctor] */
1355         csig = mono_metadata_signature_alloc (mono_defaults.corlib, 2);
1356         csig->hasthis = 1;
1357         csig->ret = &mono_defaults.void_class->byval_arg;
1358         csig->params [0] = &mono_defaults.string_class->byval_arg;
1359         csig->params [1] = &mono_defaults.string_class->byval_arg;
1360         add_method (acfg, get_runtime_invoke_sig (csig));
1361
1362         /* string runtime-invoke () [Exception.ToString ()] */
1363         csig = mono_metadata_signature_alloc (mono_defaults.corlib, 0);
1364         csig->hasthis = 1;
1365         csig->ret = &mono_defaults.string_class->byval_arg;
1366         add_method (acfg, get_runtime_invoke_sig (csig));
1367
1368         /* void runtime-invoke (string, Exception) [exception ctor] */
1369         csig = mono_metadata_signature_alloc (mono_defaults.corlib, 2);
1370         csig->hasthis = 1;
1371         csig->ret = &mono_defaults.void_class->byval_arg;
1372         csig->params [0] = &mono_defaults.string_class->byval_arg;
1373         csig->params [1] = &mono_defaults.exception_class->byval_arg;
1374         add_method (acfg, get_runtime_invoke_sig (csig));
1375
1376         /* Assembly runtime-invoke (string, bool) [DoAssemblyResolve] */
1377         csig = mono_metadata_signature_alloc (mono_defaults.corlib, 2);
1378         csig->hasthis = 1;
1379         csig->ret = &(mono_class_from_name (
1380                                                                                 mono_defaults.corlib, "System.Reflection", "Assembly"))->byval_arg;
1381         csig->params [0] = &mono_defaults.string_class->byval_arg;
1382         csig->params [1] = &mono_defaults.boolean_class->byval_arg;
1383         add_method (acfg, get_runtime_invoke_sig (csig));
1384
1385         for (i = 0; i < acfg->image->tables [MONO_TABLE_METHOD].rows; ++i) {
1386                 MonoMethod *method;
1387                 guint32 token = MONO_TOKEN_METHOD_DEF | (i + 1);
1388                 gboolean skip = FALSE;
1389
1390                 method = mono_get_method (acfg->image, token, NULL);
1391
1392                 if ((method->flags & METHOD_ATTRIBUTE_PINVOKE_IMPL) ||
1393                         (method->iflags & METHOD_IMPL_ATTRIBUTE_RUNTIME) ||
1394                         (method->flags & METHOD_ATTRIBUTE_ABSTRACT))
1395                         skip = TRUE;
1396
1397                 if (method->is_generic || method->klass->generic_container)
1398                         skip = TRUE;
1399
1400                 /* Skip methods which can not be handled by get_runtime_invoke () */
1401                 sig = mono_method_signature (method);
1402                 if ((sig->ret->type == MONO_TYPE_PTR) ||
1403                         (sig->ret->type == MONO_TYPE_TYPEDBYREF))
1404                         skip = TRUE;
1405
1406                 for (j = 0; j < sig->param_count; j++) {
1407                         if (sig->params [j]->type == MONO_TYPE_TYPEDBYREF)
1408                                 skip = TRUE;
1409                 }
1410
1411                 if (!skip)
1412                         add_method (acfg, mono_marshal_get_runtime_invoke (method));
1413         }
1414
1415         if (strcmp (acfg->image->assembly->aname.name, "mscorlib") == 0) {
1416                 MonoMethodDesc *desc;
1417                 MonoMethod *orig_method;
1418
1419                 /* JIT icall wrappers */
1420                 /* FIXME: locking */
1421                 g_hash_table_foreach (mono_get_jit_icall_info (), add_jit_icall_wrapper, acfg);
1422
1423                 /* Managed Allocators */
1424                 nallocators = mono_gc_get_managed_allocator_types ();
1425                 for (i = 0; i < nallocators; ++i) {
1426                         m = mono_gc_get_managed_allocator_by_type (i);
1427                         if (m)
1428                                 add_method (acfg, m);
1429                 }
1430
1431                 /* stelemref */
1432                 add_method (acfg, mono_marshal_get_stelemref ());
1433
1434                 /* Monitor Enter/Exit */
1435                 desc = mono_method_desc_new ("Monitor:Enter", FALSE);
1436                 orig_method = mono_method_desc_search_in_class (desc, mono_defaults.monitor_class);
1437                 g_assert (orig_method);
1438                 mono_method_desc_free (desc);
1439                 method = mono_monitor_get_fast_path (orig_method);
1440                 if (method)
1441                         add_method (acfg, method);
1442
1443                 desc = mono_method_desc_new ("Monitor:Exit", FALSE);
1444                 orig_method = mono_method_desc_search_in_class (desc, mono_defaults.monitor_class);
1445                 g_assert (orig_method);
1446                 mono_method_desc_free (desc);
1447                 method = mono_monitor_get_fast_path (orig_method);
1448                 if (method)
1449                         add_method (acfg, method);
1450         }
1451
1452         /* remoting-invoke wrappers */
1453         for (i = 0; i < acfg->image->tables [MONO_TABLE_METHOD].rows; ++i) {
1454                 MonoMethodSignature *sig;
1455                 
1456                 token = MONO_TOKEN_METHOD_DEF | (i + 1);
1457                 method = mono_get_method (acfg->image, token, NULL);
1458
1459                 sig = mono_method_signature (method);
1460
1461                 if (sig->hasthis && (method->klass->marshalbyref || method->klass == mono_defaults.object_class) && 
1462                         !(method->flags & METHOD_ATTRIBUTE_VIRTUAL)) {
1463                         m = mono_marshal_get_remoting_invoke_with_check (method);
1464
1465                         add_method (acfg, m);
1466                 }
1467         }
1468
1469         /* delegate-invoke wrappers */
1470         for (i = 0; i < acfg->image->tables [MONO_TABLE_TYPEDEF].rows; ++i) {
1471                 MonoClass *klass;
1472                 
1473                 token = MONO_TOKEN_TYPE_DEF | (i + 1);
1474                 klass = mono_class_get (acfg->image, token);
1475
1476                 if (klass->delegate && klass != mono_defaults.delegate_class && klass != mono_defaults.multicastdelegate_class && !klass->generic_container) {
1477                         method = mono_get_delegate_invoke (klass);
1478
1479                         m = mono_marshal_get_delegate_invoke (method, NULL);
1480
1481                         add_method (acfg, m);
1482
1483                         method = mono_class_get_method_from_name_flags (klass, "BeginInvoke", -1, 0);
1484                         add_method (acfg, mono_marshal_get_delegate_begin_invoke (method));
1485
1486                         method = mono_class_get_method_from_name_flags (klass, "EndInvoke", -1, 0);
1487                         add_method (acfg, mono_marshal_get_delegate_end_invoke (method));
1488                 }
1489         }
1490
1491         /* Synchronized wrappers */
1492         for (i = 0; i < acfg->image->tables [MONO_TABLE_METHOD].rows; ++i) {
1493                 token = MONO_TOKEN_METHOD_DEF | (i + 1);
1494                 method = mono_get_method (acfg->image, token, NULL);
1495
1496                 if (method->iflags & METHOD_IMPL_ATTRIBUTE_SYNCHRONIZED)
1497                         add_method (acfg, mono_marshal_get_synchronized_wrapper (method));
1498         }
1499
1500 #if 0
1501         /* static rgctx wrappers */
1502         /* FIXME: Each wrapper belongs to a given instantiation of a generic method */
1503         for (i = 0; i < acfg->image->tables [MONO_TABLE_METHOD].rows; ++i) {
1504                 token = MONO_TOKEN_METHOD_DEF | (i + 1);
1505                 method = mono_get_method (acfg->image, token, NULL);
1506
1507                 if (((method->flags & METHOD_ATTRIBUTE_STATIC) ||
1508                          (method->is_inflated && mono_method_get_context (method)->method_inst)) &&
1509                         mono_class_generic_sharing_enabled (method->klass) &&
1510                         mono_method_is_generic_sharable_impl (method, FALSE)) {
1511                         m = mono_marshal_get_static_rgctx_invoke (method);
1512                         add_method (acfg, m);
1513                 }
1514         }
1515 #endif
1516
1517         /* pinvoke wrappers */
1518         for (i = 0; i < acfg->image->tables [MONO_TABLE_METHOD].rows; ++i) {
1519                 MonoMethod *method;
1520                 guint32 token = MONO_TOKEN_METHOD_DEF | (i + 1);
1521
1522                 method = mono_get_method (acfg->image, token, NULL);
1523
1524                 if ((method->flags & METHOD_ATTRIBUTE_PINVOKE_IMPL) ||
1525                         (method->iflags & METHOD_IMPL_ATTRIBUTE_INTERNAL_CALL)) {
1526                         add_method (acfg, mono_marshal_get_native_wrapper (method, TRUE, TRUE));
1527                 }
1528         }
1529 }
1530
1531 static gboolean
1532 has_type_vars (MonoClass *klass)
1533 {
1534         if ((klass->byval_arg.type == MONO_TYPE_VAR) || (klass->byval_arg.type == MONO_TYPE_MVAR))
1535                 return TRUE;
1536         if (klass->rank)
1537                 return has_type_vars (klass->element_class);
1538         if (klass->generic_class) {
1539                 MonoGenericContext *context = &klass->generic_class->context;
1540                 if (context->class_inst) {
1541                         int i;
1542
1543                         for (i = 0; i < context->class_inst->type_argc; ++i)
1544                                 if (has_type_vars (mono_class_from_mono_type (context->class_inst->type_argv [i])))
1545                                         return TRUE;
1546                 }
1547         }
1548         return FALSE;
1549 }
1550
1551 static gboolean
1552 method_has_type_vars (MonoMethod *method)
1553 {
1554         if (has_type_vars (method->klass))
1555                 return TRUE;
1556
1557         if (method->is_inflated) {
1558                 MonoGenericContext *context = mono_method_get_context (method);
1559                 if (context->method_inst) {
1560                         int i;
1561
1562                         for (i = 0; i < context->method_inst->type_argc; ++i)
1563                                 if (has_type_vars (mono_class_from_mono_type (context->method_inst->type_argv [i])))
1564                                         return TRUE;
1565                 }
1566         }
1567         return FALSE;
1568 }
1569
1570 /*
1571  * add_generic_class:
1572  *
1573  *   Add all methods of a generic class.
1574  */
1575 static void
1576 add_generic_class (MonoAotCompile *acfg, MonoClass *klass)
1577 {
1578         MonoMethod *method;
1579         gpointer iter;
1580
1581         mono_class_init (klass);
1582
1583         if (klass->generic_class && klass->generic_class->context.class_inst->is_open)
1584                 return;
1585
1586         if (has_type_vars (klass))
1587                 return;
1588
1589         if (!klass->generic_class && !klass->rank)
1590                 return;
1591
1592         /* 
1593          * Add rgctx wrappers for cctors since those are called by the runtime, so 
1594          * there is no methodspec for them. This is needed even for shared classes,
1595          * since rgctx wrappers belong to inflated methods.
1596          */
1597         method = mono_class_get_cctor (klass);
1598         if (method)
1599                 add_extra_method (acfg, mono_marshal_get_static_rgctx_invoke (method));
1600
1601         iter = NULL;
1602         while ((method = mono_class_get_methods (klass, &iter))) {
1603                 if (mono_method_is_generic_sharable_impl (method, FALSE))
1604                         /* Already added */
1605                         continue;
1606
1607                 if (method->is_generic)
1608                         /* FIXME: */
1609                         continue;
1610
1611                 /*
1612                  * FIXME: Instances which are referenced by these methods are not added,
1613                  * for example Array.Resize<int> for List<int>.Add ().
1614                  */
1615                 add_extra_method (acfg, method);
1616         }
1617 }
1618
1619 /*
1620  * add_generic_instances:
1621  *
1622  *   Add instances referenced by the METHODSPEC/TYPESPEC table.
1623  */
1624 static void
1625 add_generic_instances (MonoAotCompile *acfg)
1626 {
1627         int i;
1628         guint32 token;
1629         MonoMethod *method;
1630         MonoGenericContext *context;
1631
1632         for (i = 0; i < acfg->image->tables [MONO_TABLE_METHODSPEC].rows; ++i) {
1633                 token = MONO_TOKEN_METHOD_SPEC | (i + 1);
1634                 method = mono_get_method (acfg->image, token, NULL);
1635
1636                 context = mono_method_get_context (method);
1637                 if (context && ((context->class_inst && context->class_inst->is_open) ||
1638                                                 (context->method_inst && context->method_inst->is_open)))
1639                         continue;
1640
1641                 if (method->klass->image != acfg->image)
1642                         continue;
1643
1644                 if (mono_method_is_generic_sharable_impl (method, FALSE))
1645                         /* Already added */
1646                         continue;
1647
1648                 add_extra_method (acfg, method);
1649         }
1650
1651         for (i = 0; i < acfg->image->tables [MONO_TABLE_TYPESPEC].rows; ++i) {
1652                 MonoClass *klass;
1653
1654                 token = MONO_TOKEN_TYPE_SPEC | (i + 1);
1655
1656                 klass = mono_class_get (acfg->image, token);
1657                 if (!klass)
1658                         continue;
1659
1660                 add_generic_class (acfg, klass);
1661         }
1662 }
1663
1664 /*
1665  * emit_and_reloc_code:
1666  *
1667  *   Emit the native code in CODE, handling relocations along the way. If GOT_ONLY
1668  * is true, calls are made through the GOT too. This is used for emitting trampolines
1669  * in full-aot mode, since calls made from trampolines couldn't go through the PLT,
1670  * since trampolines are needed to make PTL work.
1671  */
1672 static void
1673 emit_and_reloc_code (MonoAotCompile *acfg, MonoMethod *method, guint8 *code, guint32 code_len, MonoJumpInfo *relocs, gboolean got_only)
1674 {
1675         int i, pindex, start_index, method_index;
1676         GPtrArray *patches;
1677         MonoJumpInfo *patch_info;
1678         MonoMethodHeader *header;
1679         gboolean skip, direct_call;
1680         guint32 got_slot;
1681         char direct_call_target [128];
1682
1683         if (method) {
1684                 header = mono_method_get_header (method);
1685
1686                 method_index = get_method_index (acfg, method);
1687         }
1688
1689         /* Collect and sort relocations */
1690         patches = g_ptr_array_new ();
1691         for (patch_info = relocs; patch_info; patch_info = patch_info->next)
1692                 g_ptr_array_add (patches, patch_info);
1693         g_ptr_array_sort (patches, compare_patches);
1694
1695         start_index = 0;
1696         for (i = 0; i < code_len; i++) {
1697                 patch_info = NULL;
1698                 for (pindex = start_index; pindex < patches->len; ++pindex) {
1699                         patch_info = g_ptr_array_index (patches, pindex);
1700                         if (patch_info->ip.i >= i)
1701                                 break;
1702                 }
1703
1704 #ifdef MONO_ARCH_AOT_SUPPORTED
1705                 skip = FALSE;
1706                 if (patch_info && (patch_info->ip.i == i) && (pindex < patches->len)) {
1707                         start_index = pindex;
1708
1709                         switch (patch_info->type) {
1710                         case MONO_PATCH_INFO_NONE:
1711                                 break;
1712                         case MONO_PATCH_INFO_GOT_OFFSET: {
1713                                 guint32 offset = mono_arch_get_patch_offset (code + i);
1714                                 emit_bytes (acfg, code + i, offset);
1715                                 emit_symbol_diff (acfg, "got", ".", offset);
1716
1717                                 i += offset + 4 - 1;
1718                                 skip = TRUE;
1719                                 break;
1720                         }
1721                         default: {
1722                                 if (!is_got_patch (patch_info->type))
1723                                         break;
1724
1725                                 /*
1726                                  * If this patch is a call, try emitting a direct call instead of
1727                                  * through a PLT entry. This is possible if the called method is in
1728                                  * the same assembly and requires no initialization.
1729                                  */
1730                                 direct_call = FALSE;
1731                                 if (!got_only && (patch_info->type == MONO_PATCH_INFO_METHOD) && (patch_info->data.method->klass->image == method->klass->image)) {
1732                                         MonoCompile *callee_cfg = g_hash_table_lookup (acfg->method_to_cfg, patch_info->data.method);
1733                                         if (callee_cfg) {
1734                                                 gboolean direct_callable = TRUE;
1735
1736                                                 if (direct_callable && !(!callee_cfg->has_got_slots && (callee_cfg->method->klass->flags & TYPE_ATTRIBUTE_BEFORE_FIELD_INIT)))
1737                                                         direct_callable = FALSE;
1738                                                 if ((callee_cfg->method->iflags & METHOD_IMPL_ATTRIBUTE_SYNCHRONIZED) && method->wrapper_type != MONO_WRAPPER_SYNCHRONIZED)
1739                                                         // FIXME: Maybe call the wrapper directly ?
1740                                                         direct_callable = FALSE;
1741                                                 if (direct_callable) {
1742                                                         //printf ("DIRECT: %s %s\n", method ? mono_method_full_name (method, TRUE) : "", mono_method_full_name (callee_cfg->method, TRUE));
1743                                                         direct_call = TRUE;
1744                                                         sprintf (direct_call_target, ".Lm_%x", get_method_index (acfg, callee_cfg->orig_method));
1745                                                         patch_info->type = MONO_PATCH_INFO_NONE;
1746                                                         acfg->stats.direct_calls ++;
1747                                                 }
1748                                         }
1749
1750                                         acfg->stats.all_calls ++;
1751                                 }
1752
1753                                 if (!got_only && !direct_call) {
1754                                         int plt_offset = get_plt_offset (acfg, patch_info);
1755                                         if (plt_offset != -1) {
1756                                                 /* This patch has a PLT entry, so we must emit a call to the PLT entry */
1757                                                 direct_call = TRUE;
1758                                                 sprintf (direct_call_target, ".Lp_%d", plt_offset);
1759                 
1760                                                 /* Nullify the patch */
1761                                                 patch_info->type = MONO_PATCH_INFO_NONE;
1762                                         }
1763                                 }
1764
1765                                 if (direct_call) {
1766                                         int call_size;
1767
1768                                         arch_emit_direct_call (acfg, direct_call_target, &call_size);
1769                                         i += call_size - 1;
1770                                 } else {
1771                                         int code_size;
1772
1773                                         got_slot = get_got_offset (acfg, patch_info);
1774
1775                                         arch_emit_got_access (acfg, code + i, got_slot, &code_size);
1776                                         i += code_size - 1;
1777                                 }
1778                                 skip = TRUE;
1779                         }
1780                         }
1781                 }
1782 #endif /* MONO_ARCH_AOT_SUPPORTED */
1783
1784                 if (!skip) {
1785                         /* Find next patch */
1786                         patch_info = NULL;
1787                         for (pindex = start_index; pindex < patches->len; ++pindex) {
1788                                 patch_info = g_ptr_array_index (patches, pindex);
1789                                 if (patch_info->ip.i >= i)
1790                                         break;
1791                         }
1792
1793                         /* Try to emit multiple bytes at once */
1794                         if (pindex < patches->len && patch_info->ip.i > i) {
1795                                 emit_bytes (acfg, code + i, patch_info->ip.i - i);
1796                                 i = patch_info->ip.i - 1;
1797                         } else {
1798                                 emit_bytes (acfg, code + i, 1);
1799                         }
1800                 }
1801         }
1802 }
1803
1804 static void
1805 emit_method_code (MonoAotCompile *acfg, MonoCompile *cfg)
1806 {
1807         MonoMethod *method;
1808         int method_index;
1809         guint8 *code;
1810         char symbol [128];
1811         int func_alignment = 16;
1812         MonoMethodHeader *header;
1813
1814         method = cfg->orig_method;
1815         code = cfg->native_code;
1816         header = mono_method_get_header (method);
1817
1818         method_index = get_method_index (acfg, method);
1819
1820         /* Make the labels local */
1821         sprintf (symbol, ".Lm_%x", method_index);
1822
1823         emit_alignment (acfg, func_alignment);
1824         emit_label (acfg, symbol);
1825
1826         if (acfg->aot_opts.write_symbols && acfg->use_bin_writer) {
1827                 char *full_name;
1828                 /* Emit a local symbol into the symbol table */
1829                 full_name = mono_method_full_name (method, TRUE);
1830                 sprintf (symbol, ".Lme_%x", method_index);
1831                 emit_local_symbol (acfg, full_name, symbol, TRUE);
1832                 emit_label (acfg, full_name);
1833                 g_free (full_name);
1834         }
1835
1836         if (cfg->verbose_level > 0)
1837                 g_print ("Method %s emitted as %s\n", mono_method_full_name (method, TRUE), symbol);
1838
1839         acfg->stats.code_size += cfg->code_len;
1840
1841         acfg->cfgs [method_index]->got_offset = acfg->got_offset;
1842
1843         emit_and_reloc_code (acfg, method, code, cfg->code_len, cfg->patch_info, FALSE);
1844
1845         emit_line (acfg);
1846
1847         sprintf (symbol, ".Lme_%x", method_index);
1848         emit_label (acfg, symbol);
1849 }
1850
1851 /**
1852  * encode_patch:
1853  *
1854  *  Encode PATCH_INFO into its disk representation.
1855  */
1856 static void
1857 encode_patch (MonoAotCompile *acfg, MonoJumpInfo *patch_info, guint8 *buf, guint8 **endbuf)
1858 {
1859         guint8 *p = buf;
1860
1861         switch (patch_info->type) {
1862         case MONO_PATCH_INFO_NONE:
1863                 break;
1864         case MONO_PATCH_INFO_IMAGE:
1865                 encode_value (get_image_index (acfg, patch_info->data.image), p, &p);
1866                 break;
1867         case MONO_PATCH_INFO_METHOD_REL:
1868                 encode_value ((gint)patch_info->data.offset, p, &p);
1869                 break;
1870         case MONO_PATCH_INFO_SWITCH: {
1871                 gpointer *table = (gpointer *)patch_info->data.table->table;
1872                 int k;
1873
1874                 encode_value (patch_info->data.table->table_size, p, &p);
1875                 for (k = 0; k < patch_info->data.table->table_size; k++)
1876                         encode_value ((int)(gssize)table [k], p, &p);
1877                 break;
1878         }
1879         case MONO_PATCH_INFO_METHODCONST:
1880         case MONO_PATCH_INFO_METHOD:
1881         case MONO_PATCH_INFO_METHOD_JUMP:
1882         case MONO_PATCH_INFO_ICALL_ADDR:
1883         case MONO_PATCH_INFO_METHOD_RGCTX:
1884                 encode_method_ref (acfg, patch_info->data.method, p, &p);
1885                 break;
1886         case MONO_PATCH_INFO_INTERNAL_METHOD:
1887         case MONO_PATCH_INFO_JIT_ICALL_ADDR: {
1888                 guint32 len = strlen (patch_info->data.name);
1889
1890                 encode_value (len, p, &p);
1891
1892                 memcpy (p, patch_info->data.name, len);
1893                 p += len;
1894                 *p++ = '\0';
1895                 break;
1896         }
1897         case MONO_PATCH_INFO_LDSTR: {
1898                 guint32 image_index = get_image_index (acfg, patch_info->data.token->image);
1899                 guint32 token = patch_info->data.token->token;
1900                 g_assert (mono_metadata_token_code (token) == MONO_TOKEN_STRING);
1901                 encode_value (image_index, p, &p);
1902                 encode_value (patch_info->data.token->token - MONO_TOKEN_STRING, p, &p);
1903                 break;
1904         }
1905         case MONO_PATCH_INFO_RVA:
1906         case MONO_PATCH_INFO_DECLSEC:
1907         case MONO_PATCH_INFO_LDTOKEN:
1908         case MONO_PATCH_INFO_TYPE_FROM_HANDLE:
1909                 encode_value (get_image_index (acfg, patch_info->data.token->image), p, &p);
1910                 encode_value (patch_info->data.token->token, p, &p);
1911                 encode_value (patch_info->data.token->has_context, p, &p);
1912                 if (patch_info->data.token->has_context)
1913                         encode_generic_context (acfg, &patch_info->data.token->context, p, &p);
1914                 break;
1915         case MONO_PATCH_INFO_EXC_NAME: {
1916                 MonoClass *ex_class;
1917
1918                 ex_class =
1919                         mono_class_from_name (mono_defaults.exception_class->image,
1920                                                                   "System", patch_info->data.target);
1921                 g_assert (ex_class);
1922                 encode_klass_ref (acfg, ex_class, p, &p);
1923                 break;
1924         }
1925         case MONO_PATCH_INFO_R4:
1926                 encode_value (*((guint32 *)patch_info->data.target), p, &p);
1927                 break;
1928         case MONO_PATCH_INFO_R8:
1929                 encode_value (*((guint32 *)patch_info->data.target), p, &p);
1930                 encode_value (*(((guint32 *)patch_info->data.target) + 1), p, &p);
1931                 break;
1932         case MONO_PATCH_INFO_VTABLE:
1933         case MONO_PATCH_INFO_CLASS:
1934         case MONO_PATCH_INFO_IID:
1935         case MONO_PATCH_INFO_ADJUSTED_IID:
1936                 encode_klass_ref (acfg, patch_info->data.klass, p, &p);
1937                 break;
1938         case MONO_PATCH_INFO_CLASS_INIT:
1939         case MONO_PATCH_INFO_DELEGATE_TRAMPOLINE:
1940                 encode_klass_ref (acfg, patch_info->data.klass, p, &p);
1941                 break;
1942         case MONO_PATCH_INFO_FIELD:
1943         case MONO_PATCH_INFO_SFLDA:
1944                 encode_field_info (acfg, patch_info->data.field, p, &p);
1945                 break;
1946         case MONO_PATCH_INFO_INTERRUPTION_REQUEST_FLAG:
1947                 break;
1948         case MONO_PATCH_INFO_RGCTX_FETCH: {
1949                 MonoJumpInfoRgctxEntry *entry = patch_info->data.rgctx_entry;
1950
1951                 encode_method_ref (acfg, entry->method, p, &p);
1952                 encode_value (entry->in_mrgctx, p, &p);
1953                 encode_value (entry->info_type, p, &p);
1954                 encode_value (entry->data->type, p, &p);
1955                 encode_patch (acfg, entry->data, p, &p);
1956                 break;
1957         }
1958         case MONO_PATCH_INFO_GENERIC_CLASS_INIT:
1959         case MONO_PATCH_INFO_MONITOR_ENTER:
1960         case MONO_PATCH_INFO_MONITOR_EXIT:
1961                 break;
1962         default:
1963                 g_warning ("unable to handle jump info %d", patch_info->type);
1964                 g_assert_not_reached ();
1965         }
1966
1967         *endbuf = p;
1968 }
1969
1970 static void
1971 encode_patch_list (MonoAotCompile *acfg, GPtrArray *patches, int n_patches, int first_got_offset, guint8 *buf, guint8 **endbuf)
1972 {
1973         guint8 *p = buf;
1974         guint32 last_offset, j, pindex;
1975         MonoJumpInfo *patch_info;
1976
1977         encode_value (n_patches, p, &p);
1978
1979         if (n_patches)
1980                 encode_value (first_got_offset, p, &p);
1981
1982         /* First encode the type+position table */
1983         last_offset = 0;
1984         j = 0;
1985         for (pindex = 0; pindex < patches->len; ++pindex) {
1986                 guint32 offset;
1987                 patch_info = g_ptr_array_index (patches, pindex);
1988                 
1989                 if (patch_info->type == MONO_PATCH_INFO_NONE)
1990                         /* Nothing to do */
1991                         continue;
1992
1993                 j ++;
1994                 //printf ("T: %d O: %d.\n", patch_info->type, patch_info->ip.i);
1995                 offset = patch_info->ip.i - last_offset;
1996                 last_offset = patch_info->ip.i;
1997
1998                 /* Only the type is needed */
1999                 *p = patch_info->type;
2000                 p++;
2001         }
2002
2003         /* Then encode the other info */
2004         for (pindex = 0; pindex < patches->len; ++pindex) {
2005                 patch_info = g_ptr_array_index (patches, pindex);
2006
2007                 if (is_shared_got_patch (patch_info)) {
2008                         guint32 offset = get_got_offset (acfg, patch_info);
2009                         encode_value (offset, p, &p);
2010                 } else {
2011                         encode_patch (acfg, patch_info, p, &p);
2012                 }
2013         }
2014
2015         *endbuf = p;
2016 }
2017
2018 static void
2019 emit_method_info (MonoAotCompile *acfg, MonoCompile *cfg)
2020 {
2021         MonoMethod *method;
2022         GList *l;
2023         int pindex, buf_size, n_patches;
2024         guint8 *code;
2025         char symbol [128];
2026         GPtrArray *patches;
2027         MonoJumpInfo *patch_info;
2028         MonoMethodHeader *header;
2029         guint32 method_index;
2030         guint8 *p, *buf;
2031         guint32 first_got_offset;
2032
2033         method = cfg->orig_method;
2034         code = cfg->native_code;
2035         header = mono_method_get_header (method);
2036
2037         method_index = get_method_index (acfg, method);
2038
2039         /* Make the labels local */
2040         sprintf (symbol, ".Lm_%x_p", method_index);
2041
2042         /* Sort relocations */
2043         patches = g_ptr_array_new ();
2044         for (patch_info = cfg->patch_info; patch_info; patch_info = patch_info->next)
2045                 g_ptr_array_add (patches, patch_info);
2046         g_ptr_array_sort (patches, compare_patches);
2047
2048         first_got_offset = acfg->cfgs [method_index]->got_offset;
2049
2050         /**********************/
2051         /* Encode method info */
2052         /**********************/
2053
2054         buf_size = (patches->len < 1000) ? 40960 : 40960 + (patches->len * 64);
2055         p = buf = g_malloc (buf_size);
2056
2057         if (mono_class_get_cctor (method->klass))
2058                 encode_klass_ref (acfg, method->klass, p, &p);
2059         else
2060                 /* Not needed when loading the method */
2061                 encode_value (0, p, &p);
2062
2063         /* String table */
2064         if (cfg->opt & MONO_OPT_SHARED) {
2065                 encode_value (g_list_length (cfg->ldstr_list), p, &p);
2066                 for (l = cfg->ldstr_list; l; l = l->next) {
2067                         encode_value ((long)l->data, p, &p);
2068                 }
2069         }
2070         else
2071                 /* Used only in shared mode */
2072                 g_assert (!cfg->ldstr_list);
2073
2074         n_patches = 0;
2075         for (pindex = 0; pindex < patches->len; ++pindex) {
2076                 patch_info = g_ptr_array_index (patches, pindex);
2077                 
2078                 if ((patch_info->type == MONO_PATCH_INFO_GOT_OFFSET) ||
2079                         (patch_info->type == MONO_PATCH_INFO_NONE)) {
2080                         patch_info->type = MONO_PATCH_INFO_NONE;
2081                         /* Nothing to do */
2082                         continue;
2083                 }
2084
2085                 if ((patch_info->type == MONO_PATCH_INFO_IMAGE) && (patch_info->data.image == acfg->image)) {
2086                         /* Stored in a GOT slot initialized at module load time */
2087                         patch_info->type = MONO_PATCH_INFO_NONE;
2088                         continue;
2089                 }
2090
2091                 if (is_plt_patch (patch_info)) {
2092                         /* Calls are made through the PLT */
2093                         patch_info->type = MONO_PATCH_INFO_NONE;
2094                         continue;
2095                 }
2096
2097                 n_patches ++;
2098         }
2099
2100         if (n_patches)
2101                 g_assert (cfg->has_got_slots);
2102
2103         encode_patch_list (acfg, patches, n_patches, first_got_offset, p, &p);
2104
2105         acfg->stats.info_size += p - buf;
2106
2107         /* Emit method info */
2108
2109         emit_label (acfg, symbol);
2110
2111         g_assert (p - buf < buf_size);
2112         emit_bytes (acfg, buf, p - buf);
2113         g_free (buf);
2114 }
2115
2116 static void
2117 emit_exception_debug_info (MonoAotCompile *acfg, MonoCompile *cfg)
2118 {
2119         MonoMethod *method;
2120         int k, buf_size, method_index;
2121         guint32 debug_info_size;
2122         guint8 *code;
2123         char symbol [128];
2124         MonoMethodHeader *header;
2125         guint8 *p, *buf, *debug_info;
2126         MonoJitInfo *jinfo = cfg->jit_info;
2127         guint32 flags;
2128         gboolean use_unwind_ops = FALSE;
2129
2130         method = cfg->orig_method;
2131         code = cfg->native_code;
2132         header = mono_method_get_header (method);
2133
2134         method_index = get_method_index (acfg, method);
2135
2136         /* Make the labels local */
2137         sprintf (symbol, ".Le_%x_p", method_index);
2138
2139         mono_debug_serialize_debug_info (cfg, &debug_info, &debug_info_size);
2140
2141         buf_size = header->num_clauses * 256 + debug_info_size + 256;
2142         p = buf = g_malloc (buf_size);
2143
2144 #ifdef MONO_ARCH_HAVE_XP_UNWIND
2145         use_unwind_ops = cfg->unwind_ops != NULL;
2146 #endif
2147
2148         flags = (jinfo->has_generic_jit_info ? 1 : 0) | (use_unwind_ops ? 2 : 0);
2149
2150         encode_value (jinfo->code_size, p, &p);
2151         encode_value (flags, p, &p);
2152
2153         if (use_unwind_ops) {
2154                 guint32 encoded_len;
2155                 guint8 *encoded;
2156
2157                 /* 
2158                  * This is a duplicate of the data in the .debug_frame section, but that
2159                  * section cannot be accessed using the dl interface.
2160                  */
2161                 encoded = mono_unwind_ops_encode (cfg->unwind_ops, &encoded_len);
2162                 encode_value (encoded_len, p, &p);
2163                 memcpy (p, encoded, encoded_len);
2164                 p += encoded_len;
2165                 g_free (encoded);
2166         } else {
2167                 encode_value (jinfo->used_regs, p, &p);
2168         }
2169
2170         /* Exception table */
2171         if (header->num_clauses) {
2172                 for (k = 0; k < header->num_clauses; ++k) {
2173                         MonoJitExceptionInfo *ei = &jinfo->clauses [k];
2174
2175                         encode_value (ei->exvar_offset, p, &p);
2176
2177                         if (ei->flags == MONO_EXCEPTION_CLAUSE_FILTER)
2178                                 encode_value ((gint)((guint8*)ei->data.filter - code), p, &p);
2179
2180                         encode_value ((gint)((guint8*)ei->try_start - code), p, &p);
2181                         encode_value ((gint)((guint8*)ei->try_end - code), p, &p);
2182                         encode_value ((gint)((guint8*)ei->handler_start - code), p, &p);
2183                 }
2184         }
2185
2186         if (jinfo->has_generic_jit_info) {
2187                 MonoGenericJitInfo *gi = mono_jit_info_get_generic_jit_info (jinfo);
2188
2189                 encode_value (gi->has_this ? 1 : 0, p, &p);
2190                 encode_value (gi->this_reg, p, &p);
2191                 encode_value (gi->this_offset, p, &p);
2192
2193                 /* 
2194                  * Need to encode jinfo->method too, since it is not equal to 'method'
2195                  * when using generic sharing.
2196                  */
2197                 encode_method_ref (acfg, jinfo->method, p, &p);
2198         }
2199
2200         g_assert (debug_info_size < buf_size);
2201
2202         encode_value (debug_info_size, p, &p);
2203         if (debug_info_size) {
2204                 memcpy (p, debug_info, debug_info_size);
2205                 p += debug_info_size;
2206                 g_free (debug_info);
2207         }
2208
2209         acfg->stats.ex_info_size += p - buf;
2210
2211         /* Emit info */
2212
2213         emit_label (acfg, symbol);
2214
2215         g_assert (p - buf < buf_size);
2216         emit_bytes (acfg, buf, p - buf);
2217         g_free (buf);
2218 }
2219
2220 static void
2221 emit_klass_info (MonoAotCompile *acfg, guint32 token)
2222 {
2223         MonoClass *klass = mono_class_get (acfg->image, token);
2224         guint8 *p, *buf;
2225         int i, buf_size;
2226         char symbol [128];
2227         gboolean no_special_static, cant_encode;
2228         gpointer iter = NULL;
2229
2230         buf_size = 10240 + (klass->vtable_size * 16);
2231         p = buf = g_malloc (buf_size);
2232
2233         g_assert (klass);
2234
2235         mono_class_init (klass);
2236
2237         mono_class_get_nested_types (klass, &iter);
2238         g_assert (klass->nested_classes_inited);
2239
2240         mono_class_setup_vtable (klass);
2241
2242         /* 
2243          * Emit all the information which is required for creating vtables so
2244          * the runtime does not need to create the MonoMethod structures which
2245          * take up a lot of space.
2246          */
2247
2248         no_special_static = !mono_class_has_special_static_fields (klass);
2249
2250         /* Check whenever we have enough info to encode the vtable */
2251         cant_encode = FALSE;
2252         for (i = 0; i < klass->vtable_size; ++i) {
2253                 MonoMethod *cm = klass->vtable [i];
2254
2255                 if (cm && mono_method_signature (cm)->is_inflated && !g_hash_table_lookup (acfg->token_info_hash, cm))
2256                         cant_encode = TRUE;
2257         }
2258
2259         if (klass->generic_container || cant_encode) {
2260                 encode_value (-1, p, &p);
2261         } else {
2262                 encode_value (klass->vtable_size, p, &p);
2263                 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);
2264                 if (klass->has_cctor)
2265                         encode_method_ref (acfg, mono_class_get_cctor (klass), p, &p);
2266                 if (klass->has_finalize)
2267                         encode_method_ref (acfg, mono_class_get_finalizer (klass), p, &p);
2268  
2269                 encode_value (klass->instance_size, p, &p);
2270                 encode_value (mono_class_data_size (klass), p, &p);
2271                 encode_value (klass->packing_size, p, &p);
2272                 encode_value (klass->min_align, p, &p);
2273
2274                 for (i = 0; i < klass->vtable_size; ++i) {
2275                         MonoMethod *cm = klass->vtable [i];
2276
2277                         if (cm)
2278                                 encode_method_ref (acfg, cm, p, &p);
2279                         else
2280                                 encode_value (0, p, &p);
2281                 }
2282         }
2283
2284         acfg->stats.class_info_size += p - buf;
2285
2286         /* Emit the info */
2287         sprintf (symbol, ".LK_I_%x", token - MONO_TOKEN_TYPE_DEF - 1);
2288         emit_label (acfg, symbol);
2289
2290         g_assert (p - buf < buf_size);
2291         emit_bytes (acfg, buf, p - buf);
2292         g_free (buf);
2293 }
2294
2295 /*
2296  * Calls made from AOTed code are routed through a table of jumps similar to the
2297  * ELF PLT (Program Linkage Table). The differences are the following:
2298  * - the ELF PLT entries make an indirect jump though the GOT so they expect the
2299  *   GOT pointer to be in EBX. We want to avoid this, so our table contains direct
2300  *   jumps. This means the jumps need to be patched when the address of the callee is
2301  *   known. Initially the PLT entries jump to code which transfers control to the
2302  *   AOT runtime through the first PLT entry.
2303  */
2304 static void
2305 emit_plt (MonoAotCompile *acfg)
2306 {
2307         char symbol [128];
2308         int i;
2309
2310         emit_line (acfg);
2311         sprintf (symbol, "plt");
2312
2313         emit_section_change (acfg, ".text", 0);
2314         emit_global (acfg, symbol, TRUE);
2315 #ifdef __i386__
2316         /* This section will be made read-write by the AOT loader */
2317         emit_alignment (acfg, PAGESIZE);
2318 #else
2319         emit_alignment (acfg, 16);
2320 #endif
2321         emit_label (acfg, symbol);
2322
2323         for (i = 0; i < acfg->plt_offset; ++i) {
2324                 char label [128];
2325
2326                 sprintf (label, ".Lp_%d", i);
2327                 emit_label (acfg, label);
2328
2329                 /* 
2330                  * The first plt entry is used to transfer code to the AOT loader. 
2331                  */
2332                 arch_emit_plt_entry (acfg, i);
2333         }
2334
2335         sprintf (symbol, "plt_end");
2336         emit_global (acfg, symbol, TRUE);
2337         emit_label (acfg, symbol);
2338 }
2339
2340 static G_GNUC_UNUSED void
2341 emit_named_code (MonoAotCompile *acfg, const char *name, guint8 *code, 
2342                                  guint32 code_size, int got_offset, MonoJumpInfo *ji, GSList *unwind_ops)
2343 {
2344         char symbol [256];
2345         guint32 buf_size;
2346         MonoJumpInfo *patch_info;
2347         guint8 *buf, *p;
2348         GPtrArray *patches;
2349
2350         /* Emit code */
2351
2352         sprintf (symbol, "%s", name);
2353
2354         emit_section_change (acfg, ".text", 0);
2355         emit_global (acfg, symbol, TRUE);
2356         emit_alignment (acfg, 16);
2357         emit_label (acfg, symbol);
2358
2359         sprintf (symbol, ".Lnamed_%s", name);
2360         emit_label (acfg, symbol);
2361
2362         /* 
2363          * The code should access everything through the GOT, so we pass
2364          * TRUE here.
2365          */
2366         emit_and_reloc_code (acfg, NULL, code, code_size, ji, TRUE);
2367
2368         /* Emit info */
2369
2370         /* Sort relocations */
2371         patches = g_ptr_array_new ();
2372         for (patch_info = ji; patch_info; patch_info = patch_info->next)
2373                 g_ptr_array_add (patches, patch_info);
2374         g_ptr_array_sort (patches, compare_patches);
2375
2376         buf_size = patches->len * 128 + 128;
2377         buf = g_malloc (buf_size);
2378         p = buf;
2379
2380         encode_patch_list (acfg, patches, patches->len, got_offset, p, &p);
2381         g_assert (p - buf < buf_size);
2382
2383         sprintf (symbol, "%s_p", name);
2384
2385         emit_section_change (acfg, ".text", 0);
2386         emit_global (acfg, symbol, FALSE);
2387         emit_label (acfg, symbol);
2388                 
2389         emit_bytes (acfg, buf, p - buf);
2390
2391         /* Emit debug info */
2392         if (unwind_ops) {
2393                 char symbol2 [256];
2394
2395                 sprintf (symbol, "%s", name);
2396                 sprintf (symbol2, ".Lnamed_%s", name);
2397
2398                 emit_trampoline_dwarf_info (acfg, symbol, symbol2, NULL, NULL, code_size, unwind_ops);
2399         }
2400 }
2401
2402 /*
2403  * When running in aot-only mode, we can't create trampolines at runtime, so we create 
2404  * a few, and save them in the AOT file. Normal trampolines embed their argument as a 
2405  * literal inside the trampoline code, we can't do that here, so instead we embed an offset
2406  * which needs to be added to the trampoline address to get the address of the GOT slot
2407  * which contains the argument value.
2408  * The generated trampolines jump to the generic trampolines using another GOT slot, which
2409  * will be setup by the AOT loader to point to the generic trampoline code of the given 
2410  * type.
2411  */
2412 static void
2413 emit_trampolines (MonoAotCompile *acfg)
2414 {
2415         char symbol [256];
2416         int i, offset;
2417 #ifdef MONO_ARCH_HAVE_FULL_AOT_TRAMPOLINES
2418         int tramp_type;
2419         guint32 code_size;
2420         MonoJumpInfo *ji;
2421         guint8 *code;
2422         GSList *unwind_ops;
2423 #endif
2424
2425         if (!acfg->aot_opts.full_aot)
2426                 return;
2427         
2428         g_assert (acfg->image->assembly);
2429
2430         /* Currently, we only emit most trampolines into the mscorlib AOT image. */
2431         if (strcmp (acfg->image->assembly->aname.name, "mscorlib") == 0) {
2432 #ifdef MONO_ARCH_HAVE_FULL_AOT_TRAMPOLINES
2433                 /*
2434                  * Emit the generic trampolines.
2435                  *
2436                  * We could save some code by treating the generic trampolines as a wrapper
2437                  * method, but that approach has its own complexities, so we choose the simpler
2438                  * method.
2439                  */
2440                 for (tramp_type = 0; tramp_type < MONO_TRAMPOLINE_NUM; ++tramp_type) {
2441                         code = mono_arch_create_trampoline_code_full (tramp_type, &code_size, &ji, &unwind_ops, TRUE);
2442
2443                         /* Emit trampoline code */
2444
2445                         sprintf (symbol, "generic_trampoline_%d", tramp_type);
2446
2447                         emit_named_code (acfg, symbol, code, code_size, acfg->got_offset, ji, unwind_ops);
2448                 }
2449
2450                 code = mono_arch_get_nullified_class_init_trampoline (&code_size);
2451                 emit_named_code (acfg, "nullified_class_init_trampoline", code, code_size, acfg->got_offset, NULL, NULL);
2452 #if defined(__x86_64__) && defined(MONO_ARCH_MONITOR_OBJECT_REG)
2453                 code = mono_arch_create_monitor_enter_trampoline_full (&code_size, &ji, TRUE);
2454                 emit_named_code (acfg, "monitor_enter_trampoline", code, code_size, acfg->got_offset, ji, NULL);
2455                 code = mono_arch_create_monitor_exit_trampoline_full (&code_size, &ji, TRUE);
2456                 emit_named_code (acfg, "monitor_exit_trampoline", code, code_size, acfg->got_offset, ji, NULL);
2457 #endif
2458
2459 #if defined(__x86_64__)
2460                 code = mono_arch_create_generic_class_init_trampoline_full (&code_size, &ji, TRUE);
2461                 emit_named_code (acfg, "generic_class_init_trampoline", code, code_size, acfg->got_offset, ji, NULL);
2462 #endif
2463
2464                 /* Emit the exception related code pieces */
2465                 code = mono_arch_get_restore_context_full (&code_size, &ji, TRUE);
2466                 emit_named_code (acfg, "restore_context", code, code_size, acfg->got_offset, ji, NULL);
2467                 code = mono_arch_get_call_filter_full (&code_size, &ji, TRUE);
2468                 emit_named_code (acfg, "call_filter", code, code_size, acfg->got_offset, ji, NULL);
2469                 code = mono_arch_get_throw_exception_full (&code_size, &ji, TRUE);
2470                 emit_named_code (acfg, "throw_exception", code, code_size, acfg->got_offset, ji, NULL);
2471                 code = mono_arch_get_rethrow_exception_full (&code_size, &ji, TRUE);
2472                 emit_named_code (acfg, "rethrow_exception", code, code_size, acfg->got_offset, ji, NULL);
2473                 code = mono_arch_get_throw_exception_by_name_full (&code_size, &ji, TRUE);
2474                 emit_named_code (acfg, "throw_exception_by_name", code, code_size, acfg->got_offset, ji, NULL);
2475                 code = mono_arch_get_throw_corlib_exception_full (&code_size, &ji, TRUE);
2476                 emit_named_code (acfg, "throw_corlib_exception", code, code_size, acfg->got_offset, ji, NULL);
2477
2478 #if defined(__x86_64__)
2479                 code = mono_arch_get_throw_pending_exception_full (&code_size, &ji, TRUE);
2480                 emit_named_code (acfg, "throw_pending_exception", code, code_size, acfg->got_offset, ji, NULL);
2481 #endif
2482
2483 #if defined(__x86_64__) || defined(__arm__)
2484                 for (i = 0; i < 128; ++i) {
2485                         int offset;
2486
2487                         offset = MONO_RGCTX_SLOT_MAKE_RGCTX (i);
2488                         code = mono_arch_create_rgctx_lazy_fetch_trampoline_full (offset, &code_size, &ji, TRUE);
2489                         sprintf (symbol, "rgctx_fetch_trampoline_%u", offset);
2490                         emit_named_code (acfg, symbol, code, code_size, acfg->got_offset, ji, NULL);
2491
2492                         offset = MONO_RGCTX_SLOT_MAKE_MRGCTX (i);
2493                         code = mono_arch_create_rgctx_lazy_fetch_trampoline_full (offset, &code_size, &ji, TRUE);
2494                         sprintf (symbol, "rgctx_fetch_trampoline_%u", offset);
2495                         emit_named_code (acfg, symbol, code, code_size, acfg->got_offset, ji, NULL);
2496                 }
2497 #endif
2498 #endif
2499
2500                 /*
2501                  * FIXME: Maybe we should use more specific trampolines (i.e. one class init for
2502                  * each class).
2503                  */
2504
2505                 /* Reserve some entries at the end of the GOT for our use */
2506                 acfg->num_trampoline_got_entries = acfg->num_aot_trampolines * 2;
2507
2508                 sprintf (symbol, "trampolines");
2509
2510                 emit_section_change (acfg, ".text", 0);
2511                 emit_global (acfg, symbol, TRUE);
2512                 emit_alignment (acfg, 16);
2513                 emit_label (acfg, symbol);
2514
2515                 for (i = 0; i < acfg->num_aot_trampolines; ++i) {
2516                         int tramp_size = 0;
2517
2518                         offset = acfg->got_offset + (i * 2);
2519
2520                         arch_emit_specific_trampoline (acfg, offset, &tramp_size);
2521                         if (!acfg->specific_trampoline_size) {
2522                                 g_assert (tramp_size);
2523                                 acfg->specific_trampoline_size = tramp_size;
2524                         }
2525                 }
2526         }
2527
2528         /* Unbox trampolines */
2529
2530         for (i = 0; i < acfg->image->tables [MONO_TABLE_METHOD].rows; ++i) {
2531                 MonoMethod *method;
2532                 guint32 token = MONO_TOKEN_METHOD_DEF | (i + 1);
2533                 MonoCompile *cfg;
2534                 char call_target [256];
2535
2536                 method = mono_get_method (acfg->image, token, NULL);
2537
2538                 cfg = g_hash_table_lookup (acfg->method_to_cfg, method);
2539                 if (!cfg || !cfg->orig_method->klass->valuetype || !(method->flags & METHOD_ATTRIBUTE_VIRTUAL))
2540                         continue;
2541
2542                 sprintf (symbol, "unbox_trampoline_%d", i);
2543
2544                 emit_section_change (acfg, ".text", 0);
2545                 emit_global (acfg, symbol, TRUE);
2546                 emit_label (acfg, symbol);
2547
2548                 sprintf (call_target, ".Lm_%x", get_method_index (acfg, cfg->orig_method));
2549
2550                 arch_emit_unbox_trampoline (acfg, cfg->orig_method, cfg->generic_sharing_context, call_target);
2551         }
2552
2553         acfg->trampoline_got_offset_base = acfg->got_offset;
2554
2555         acfg->got_offset += acfg->num_trampoline_got_entries;
2556 }
2557
2558 static gboolean
2559 str_begins_with (const char *str1, const char *str2)
2560 {
2561         int len = strlen (str2);
2562         return strncmp (str1, str2, len) == 0;
2563 }
2564
2565 static void
2566 mono_aot_parse_options (const char *aot_options, MonoAotOptions *opts)
2567 {
2568         gchar **args, **ptr;
2569
2570         args = g_strsplit (aot_options ? aot_options : "", ",", -1);
2571         for (ptr = args; ptr && *ptr; ptr ++) {
2572                 const char *arg = *ptr;
2573
2574                 if (str_begins_with (arg, "outfile=")) {
2575                         opts->outfile = g_strdup (arg + strlen ("outfile="));
2576                 } else if (str_begins_with (arg, "save-temps")) {
2577                         opts->save_temps = TRUE;
2578                 } else if (str_begins_with (arg, "keep-temps")) {
2579                         opts->save_temps = TRUE;
2580                 } else if (str_begins_with (arg, "write-symbols")) {
2581                         opts->write_symbols = TRUE;
2582                 } else if (str_begins_with (arg, "metadata-only")) {
2583                         opts->metadata_only = TRUE;
2584                 } else if (str_begins_with (arg, "bind-to-runtime-version")) {
2585                         opts->bind_to_runtime_version = TRUE;
2586                 } else if (str_begins_with (arg, "full")) {
2587                         opts->full_aot = TRUE;
2588                         /*
2589                          * The no-dlsym option is only useful on the iphone, and even there,
2590                          * do to other limitations of the dynamic linker, it doesn't seem to
2591                          * work. So disable it for now so we don't have to support it.
2592                          */
2593                         /*
2594                 } else if (str_begins_with (arg, "no-dlsym")) {
2595                         opts->no_dlsym = TRUE;
2596                         */
2597                 } else if (str_begins_with (arg, "threads=")) {
2598                         opts->nthreads = atoi (arg + strlen ("threads="));
2599                 } else if (str_begins_with (arg, "static")) {
2600                         opts->static_link = TRUE;
2601                         opts->no_dlsym = TRUE;
2602                 } else if (str_begins_with (arg, "asmonly")) {
2603                         opts->asm_only = TRUE;
2604                 } else if (str_begins_with (arg, "asmwriter")) {
2605                         opts->asm_writer = TRUE;
2606                 } else {
2607                         fprintf (stderr, "AOT : Unknown argument '%s'.\n", arg);
2608                         exit (1);
2609                 }
2610         }
2611
2612         g_strfreev (args);
2613 }
2614
2615 static void
2616 add_token_info_hash (gpointer key, gpointer value, gpointer user_data)
2617 {
2618         MonoMethod *method = (MonoMethod*)key;
2619         MonoJumpInfoToken *ji = (MonoJumpInfoToken*)value;
2620         MonoJumpInfoToken *new_ji = g_new0 (MonoJumpInfoToken, 1);
2621         MonoAotCompile *acfg = user_data;
2622
2623         new_ji->image = ji->image;
2624         new_ji->token = ji->token;
2625         g_hash_table_insert (acfg->token_info_hash, method, new_ji);
2626 }
2627
2628 static gboolean
2629 can_encode_class (MonoAotCompile *acfg, MonoClass *klass)
2630 {
2631         if (klass->type_token)
2632                 return TRUE;
2633         if ((klass->byval_arg.type == MONO_TYPE_VAR) || (klass->byval_arg.type == MONO_TYPE_MVAR))
2634                 return TRUE;
2635         if (klass->rank)
2636                 return can_encode_class (acfg, klass->element_class);
2637         return FALSE;
2638 }
2639
2640 static gboolean
2641 can_encode_patch (MonoAotCompile *acfg, MonoJumpInfo *patch_info)
2642 {
2643         switch (patch_info->type) {
2644         case MONO_PATCH_INFO_METHOD:
2645         case MONO_PATCH_INFO_METHODCONST: {
2646                 MonoMethod *method = patch_info->data.method;
2647
2648                 if (method->wrapper_type) {
2649                         switch (method->wrapper_type) {
2650                         case MONO_WRAPPER_NONE:
2651                         case MONO_WRAPPER_REMOTING_INVOKE_WITH_CHECK:
2652                         case MONO_WRAPPER_XDOMAIN_INVOKE:
2653                         case MONO_WRAPPER_STFLD:
2654                         case MONO_WRAPPER_LDFLD:
2655                         case MONO_WRAPPER_LDFLDA:
2656                         case MONO_WRAPPER_LDFLD_REMOTE:
2657                         case MONO_WRAPPER_STFLD_REMOTE:
2658                         case MONO_WRAPPER_STELEMREF:
2659                         case MONO_WRAPPER_ISINST:
2660                         case MONO_WRAPPER_PROXY_ISINST:
2661                         case MONO_WRAPPER_ALLOC:
2662                         case MONO_WRAPPER_REMOTING_INVOKE:
2663                         case MONO_WRAPPER_STATIC_RGCTX_INVOKE:
2664                         case MONO_WRAPPER_UNKNOWN:
2665                                 break;
2666                         default:
2667                                 //printf ("Skip (wrapper call): %d -> %s\n", patch_info->type, mono_method_full_name (patch_info->data.method, TRUE));
2668                                 return FALSE;
2669                         }
2670                 } else {
2671                         if (!method->token) {
2672                                 /* The method is part of a constructed type like Int[,].Set (). */
2673                                 if (!g_hash_table_lookup (acfg->token_info_hash, method)) {
2674                                         if (method->klass->rank)
2675                                                 return TRUE;
2676                                         return FALSE;
2677                                 }
2678                         }
2679                 }
2680                 break;
2681         }
2682         case MONO_PATCH_INFO_VTABLE:
2683         case MONO_PATCH_INFO_CLASS_INIT:
2684         case MONO_PATCH_INFO_DELEGATE_TRAMPOLINE:
2685         case MONO_PATCH_INFO_CLASS:
2686         case MONO_PATCH_INFO_IID:
2687         case MONO_PATCH_INFO_ADJUSTED_IID:
2688                 if (!can_encode_class (acfg, patch_info->data.klass)) {
2689                         //printf ("Skip: %s\n", mono_type_full_name (&patch_info->data.klass->byval_arg));
2690                         return FALSE;
2691                 }
2692                 break;
2693         case MONO_PATCH_INFO_RGCTX_FETCH: {
2694                 MonoJumpInfoRgctxEntry *entry = patch_info->data.rgctx_entry;
2695
2696                 if (!can_encode_patch (acfg, entry->data))
2697                         return FALSE;
2698                 break;
2699         }
2700         default:
2701                 break;
2702         }
2703
2704         return TRUE;
2705 }
2706
2707 static void
2708 add_generic_class (MonoAotCompile *acfg, MonoClass *klass);
2709
2710 /*
2711  * compile_method:
2712  *
2713  *   AOT compile a given method.
2714  * This function might be called by multiple threads, so it must be thread-safe.
2715  */
2716 static void
2717 compile_method (MonoAotCompile *acfg, MonoMethod *method)
2718 {
2719         MonoCompile *cfg;
2720         MonoJumpInfo *patch_info;
2721         gboolean skip;
2722         int index;
2723         MonoMethod *wrapped;
2724
2725         if (acfg->aot_opts.metadata_only)
2726                 return;
2727
2728         mono_acfg_lock (acfg);
2729         index = get_method_index (acfg, method);
2730         mono_acfg_unlock (acfg);
2731
2732         /* fixme: maybe we can also precompile wrapper methods */
2733         if ((method->flags & METHOD_ATTRIBUTE_PINVOKE_IMPL) ||
2734                 (method->iflags & METHOD_IMPL_ATTRIBUTE_RUNTIME) ||
2735                 (method->flags & METHOD_ATTRIBUTE_ABSTRACT)) {
2736                 //printf ("Skip (impossible): %s\n", mono_method_full_name (method, TRUE));
2737                 return;
2738         }
2739
2740         if (method->iflags & METHOD_IMPL_ATTRIBUTE_INTERNAL_CALL)
2741                 return;
2742
2743         wrapped = mono_marshal_method_from_wrapper (method);
2744         if (wrapped && (wrapped->iflags & METHOD_IMPL_ATTRIBUTE_INTERNAL_CALL) && wrapped->is_generic)
2745                 // FIXME: The wrapper should be generic too, but it is not
2746                 return;
2747
2748         InterlockedIncrement (&acfg->stats.mcount);
2749
2750 #if 0
2751         if (method->is_generic || method->klass->generic_container) {
2752                 InterlockedIncrement (&acfg->stats.genericcount);
2753                 return;
2754         }
2755 #endif
2756
2757         //acfg->aot_opts.print_skipped_methods = TRUE;
2758
2759         if (acfg->aot_opts.full_aot)
2760                 mono_use_imt = FALSE;
2761
2762         /*
2763          * Since these methods are the only ones which are compiled with
2764          * AOT support, and they are not used by runtime startup/shutdown code,
2765          * the runtime will not see AOT methods during AOT compilation,so it
2766          * does not need to support them by creating a fake GOT etc.
2767          */
2768         cfg = mini_method_compile (method, acfg->opts, mono_get_root_domain (), FALSE, TRUE, 0);
2769         if (cfg->exception_type == MONO_EXCEPTION_GENERIC_SHARING_FAILED) {
2770                 //printf ("F: %s\n", mono_method_full_name (method, TRUE));
2771                 InterlockedIncrement (&acfg->stats.genericcount);
2772                 return;
2773         }
2774         if (cfg->exception_type != MONO_EXCEPTION_NONE) {
2775                 /* Let the exception happen at runtime */
2776                 return;
2777         }
2778
2779         if (cfg->disable_aot) {
2780                 if (acfg->aot_opts.print_skipped_methods)
2781                         printf ("Skip (disabled): %s\n", mono_method_full_name (method, TRUE));
2782                 InterlockedIncrement (&acfg->stats.ocount);
2783                 mono_destroy_compile (cfg);
2784                 return;
2785         }
2786
2787         /* Nullify patches which need no aot processing */
2788         for (patch_info = cfg->patch_info; patch_info; patch_info = patch_info->next) {
2789                 switch (patch_info->type) {
2790                 case MONO_PATCH_INFO_LABEL:
2791                 case MONO_PATCH_INFO_BB:
2792                         patch_info->type = MONO_PATCH_INFO_NONE;
2793                         break;
2794                 default:
2795                         break;
2796                 }
2797         }
2798
2799         /* Collect method->token associations from the cfg */
2800         mono_acfg_lock (acfg);
2801         g_hash_table_foreach (cfg->token_info_hash, add_token_info_hash, acfg);
2802         mono_acfg_unlock (acfg);
2803
2804         /*
2805          * Check for absolute addresses.
2806          */
2807         skip = FALSE;
2808         for (patch_info = cfg->patch_info; patch_info; patch_info = patch_info->next) {
2809                 switch (patch_info->type) {
2810                 case MONO_PATCH_INFO_ABS:
2811                         /* unable to handle this */
2812                         skip = TRUE;    
2813                         break;
2814                 default:
2815                         break;
2816                 }
2817         }
2818
2819         if (skip) {
2820                 if (acfg->aot_opts.print_skipped_methods)
2821                         printf ("Skip (abs call): %s\n", mono_method_full_name (method, TRUE));
2822                 InterlockedIncrement (&acfg->stats.abscount);
2823                 mono_destroy_compile (cfg);
2824                 return;
2825         }
2826
2827         /* Lock for the rest of the code */
2828         mono_acfg_lock (acfg);
2829
2830         /*
2831          * Check for methods/klasses we can't encode.
2832          */
2833         skip = FALSE;
2834         for (patch_info = cfg->patch_info; patch_info; patch_info = patch_info->next) {
2835                 if (!can_encode_patch (acfg, patch_info))
2836                         skip = TRUE;
2837         }
2838
2839         if (skip) {
2840                 if (acfg->aot_opts.print_skipped_methods)
2841                         printf ("Skip (patches): %s\n", mono_method_full_name (method, TRUE));
2842                 acfg->stats.ocount++;
2843                 mono_destroy_compile (cfg);
2844                 mono_acfg_unlock (acfg);
2845                 return;
2846         }
2847
2848         /* Adds generic instances referenced by this method */
2849         for (patch_info = cfg->patch_info; patch_info; patch_info = patch_info->next) {
2850                 switch (patch_info->type) {
2851                 case MONO_PATCH_INFO_METHOD: {
2852                         MonoMethod *m = patch_info->data.method;
2853                         if (m->is_inflated) {
2854                                 if (!(mono_class_generic_sharing_enabled (m->klass) &&
2855                                           mono_method_is_generic_sharable_impl (m, FALSE)) &&
2856                                         !method_has_type_vars (m)) {
2857                                         if (m->iflags & METHOD_IMPL_ATTRIBUTE_INTERNAL_CALL)
2858                                                 add_extra_method (acfg, mono_marshal_get_native_wrapper (m, TRUE, TRUE));
2859                                         else
2860                                                 add_extra_method (acfg, m);
2861                                 }
2862                                 add_generic_class (acfg, m->klass);
2863                         }
2864                         break;
2865                 }
2866                 default:
2867                         break;
2868                 }
2869         }
2870
2871         /* Determine whenever the method has GOT slots */
2872         for (patch_info = cfg->patch_info; patch_info; patch_info = patch_info->next) {
2873                 switch (patch_info->type) {
2874                 case MONO_PATCH_INFO_GOT_OFFSET:
2875                 case MONO_PATCH_INFO_NONE:
2876                         break;
2877                 case MONO_PATCH_INFO_IMAGE:
2878                         /* The assembly is stored in GOT slot 0 */
2879                         if (patch_info->data.image != acfg->image)
2880                                 cfg->has_got_slots = TRUE;
2881                         break;
2882                 default:
2883                         if (!is_plt_patch (patch_info))
2884                                 cfg->has_got_slots = TRUE;
2885                         break;
2886                 }
2887         }
2888
2889         if (!cfg->has_got_slots)
2890                 InterlockedIncrement (&acfg->stats.methods_without_got_slots);
2891
2892         /* Make a copy of the patch info which is in the mempool */
2893         {
2894                 MonoJumpInfo *patches = NULL, *patches_end = NULL;
2895
2896                 for (patch_info = cfg->patch_info; patch_info; patch_info = patch_info->next) {
2897                         MonoJumpInfo *new_patch_info = mono_patch_info_dup_mp (acfg->mempool, patch_info);
2898
2899                         if (!patches)
2900                                 patches = new_patch_info;
2901                         else
2902                                 patches_end->next = new_patch_info;
2903                         patches_end = new_patch_info;
2904                 }
2905                 cfg->patch_info = patches;
2906         }
2907         /* Make a copy of the unwind info */
2908         {
2909                 GSList *l, *unwind_ops;
2910                 MonoUnwindOp *op;
2911
2912                 unwind_ops = NULL;
2913                 for (l = cfg->unwind_ops; l; l = l->next) {
2914                         op = mono_mempool_alloc (acfg->mempool, sizeof (MonoUnwindOp));
2915                         memcpy (op, l->data, sizeof (MonoUnwindOp));
2916                         unwind_ops = g_slist_prepend_mempool (acfg->mempool, unwind_ops, op);
2917                 }
2918                 cfg->unwind_ops = g_slist_reverse (unwind_ops);
2919         }
2920         /* Make a copy of the argument/local info */
2921         {
2922                 MonoInst **args, **locals;
2923                 MonoMethodSignature *sig;
2924                 MonoMethodHeader *header;
2925                 int i;
2926                 
2927                 sig = mono_method_signature (method);
2928                 args = mono_mempool_alloc (acfg->mempool, sizeof (MonoInst*) * (sig->param_count + sig->hasthis));
2929                 for (i = 0; i < sig->param_count + sig->hasthis; ++i) {
2930                         args [i] = mono_mempool_alloc (acfg->mempool, sizeof (MonoInst));
2931                         memcpy (args [i], cfg->args [i], sizeof (MonoInst));
2932                 }
2933                 cfg->args = args;
2934
2935                 header = mono_method_get_header (method);
2936                 locals = mono_mempool_alloc (acfg->mempool, sizeof (MonoInst*) * header->num_locals);
2937                 for (i = 0; i < header->num_locals; ++i) {
2938                         locals [i] = mono_mempool_alloc (acfg->mempool, sizeof (MonoInst));
2939                         memcpy (locals [i], cfg->locals [i], sizeof (MonoInst));
2940                 }
2941                 cfg->locals = locals;
2942         }
2943
2944         /* Free some fields used by cfg to conserve memory */
2945         mono_mempool_destroy (cfg->mempool);
2946         cfg->mempool = NULL;
2947         g_free (cfg->varinfo);
2948         cfg->varinfo = NULL;
2949         g_free (cfg->vars);
2950         cfg->vars = NULL;
2951         if (cfg->rs) {
2952                 mono_regstate_free (cfg->rs);
2953                 cfg->rs = NULL;
2954         }
2955
2956         //printf ("Compile:           %s\n", mono_method_full_name (method, TRUE));
2957
2958         while (index >= acfg->cfgs_size) {
2959                 MonoCompile **new_cfgs;
2960                 int new_size;
2961
2962                 new_size = acfg->cfgs_size * 2;
2963                 new_cfgs = g_new0 (MonoCompile*, new_size);
2964                 memcpy (new_cfgs, acfg->cfgs, sizeof (MonoCompile*) * acfg->cfgs_size);
2965                 g_free (acfg->cfgs);
2966                 acfg->cfgs = new_cfgs;
2967                 acfg->cfgs_size = new_size;
2968         }
2969         acfg->cfgs [index] = cfg;
2970
2971         g_hash_table_insert (acfg->method_to_cfg, cfg->orig_method, cfg);
2972
2973         if (cfg->orig_method->wrapper_type)
2974                 g_ptr_array_add (acfg->extra_methods, cfg->orig_method);
2975
2976         mono_acfg_unlock (acfg);
2977
2978         InterlockedIncrement (&acfg->stats.ccount);
2979 }
2980  
2981 static void
2982 compile_thread_main (gpointer *user_data)
2983 {
2984         MonoDomain *domain = user_data [0];
2985         MonoAotCompile *acfg = user_data [1];
2986         GPtrArray *methods = user_data [2];
2987         int i;
2988
2989         mono_thread_attach (domain);
2990
2991         for (i = 0; i < methods->len; ++i)
2992                 compile_method (acfg, g_ptr_array_index (methods, i));
2993 }
2994
2995 static void
2996 load_profile_files (MonoAotCompile *acfg)
2997 {
2998         FILE *infile;
2999         char *tmp;
3000         int file_index, res, method_index, i;
3001         char ver [256];
3002         guint32 token;
3003         GList *unordered;
3004
3005         file_index = 0;
3006         while (TRUE) {
3007                 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);
3008
3009                 if (!g_file_test (tmp, G_FILE_TEST_IS_REGULAR)) {
3010                         g_free (tmp);
3011                         break;
3012                 }
3013
3014                 infile = fopen (tmp, "r");
3015                 g_assert (infile);
3016
3017                 printf ("Using profile data file '%s'\n", tmp);
3018                 g_free (tmp);
3019
3020                 file_index ++;
3021
3022                 res = fscanf (infile, "%32s\n", ver);
3023                 if ((res != 1) || strcmp (ver, "#VER:1") != 0) {
3024                         printf ("Profile file has wrong version or invalid.\n");
3025                         fclose (infile);
3026                         continue;
3027                 }
3028
3029                 while (TRUE) {
3030                         res = fscanf (infile, "%d\n", &token);
3031                         if (res < 1)
3032                                 break;
3033
3034                         method_index = mono_metadata_token_index (token) - 1;
3035
3036                         if (!g_list_find (acfg->method_order, GUINT_TO_POINTER (method_index)))
3037                                 acfg->method_order = g_list_append (acfg->method_order, GUINT_TO_POINTER (method_index));
3038                 }
3039                 fclose (infile);
3040         }
3041
3042         /* Add missing methods */
3043         unordered = NULL;
3044         for (i = 0; i < acfg->image->tables [MONO_TABLE_METHOD].rows; ++i) {
3045                 if (!g_list_find (acfg->method_order, GUINT_TO_POINTER (i)))
3046                         unordered = g_list_prepend (unordered, GUINT_TO_POINTER (i));
3047         }
3048         unordered = g_list_reverse (unordered);
3049         if (acfg->method_order)
3050                 g_list_last (acfg->method_order)->next = unordered;
3051         else
3052                 acfg->method_order = unordered;
3053 }
3054
3055 /**
3056  * alloc_got_slots:
3057  *
3058  *  Collect all patches which have shared GOT entries and alloc entries for them. The
3059  * rest will get entries allocated during emit_code ().
3060  */
3061 static void
3062 alloc_got_slots (MonoAotCompile *acfg)
3063 {
3064         int i;
3065         GList *l;
3066         MonoJumpInfo *ji;
3067
3068         /* Slot 0 is reserved for the address of the current assembly */
3069         ji = mono_mempool_alloc0 (acfg->mempool, sizeof (MonoAotCompile));
3070         ji->type = MONO_PATCH_INFO_IMAGE;
3071         ji->data.image = acfg->image;
3072
3073         get_shared_got_offset (acfg, ji);
3074
3075         for (l = acfg->method_order; l != NULL; l = l->next) {
3076                 i = GPOINTER_TO_UINT (l->data);
3077
3078                 if (acfg->cfgs [i]) {
3079                         MonoCompile *cfg = acfg->cfgs [i];
3080
3081                         for (ji = cfg->patch_info; ji; ji = ji->next) {
3082                                 if (is_shared_got_patch (ji))
3083                                         get_shared_got_offset (acfg, ji);
3084                         }
3085                 }
3086         }
3087 }
3088
3089 static void
3090 emit_code (MonoAotCompile *acfg)
3091 {
3092         int i;
3093         char symbol [256];
3094         GList *l;
3095
3096         sprintf (symbol, "methods");
3097         emit_section_change (acfg, ".text", 0);
3098         emit_global (acfg, symbol, TRUE);
3099         emit_alignment (acfg, 8);
3100         emit_label (acfg, symbol);
3101
3102         /* 
3103          * Emit some padding so the local symbol for the first method doesn't have the
3104          * same address as 'methods'.
3105          */
3106         emit_zero_bytes (acfg, 16);
3107
3108         for (l = acfg->method_order; l != NULL; l = l->next) {
3109                 i = GPOINTER_TO_UINT (l->data);
3110
3111                 if (acfg->cfgs [i])
3112                         emit_method_code (acfg, acfg->cfgs [i]);
3113         }
3114
3115         sprintf (symbol, "methods_end");
3116         emit_section_change (acfg, ".text", 0);
3117         emit_global (acfg, symbol, FALSE);
3118         emit_alignment (acfg, 8);
3119         emit_label (acfg, symbol);
3120
3121         sprintf (symbol, "method_offsets");
3122         emit_section_change (acfg, ".text", 1);
3123         emit_global (acfg, symbol, FALSE);
3124         emit_alignment (acfg, 8);
3125         emit_label (acfg, symbol);
3126
3127         for (i = 0; i < acfg->nmethods; ++i) {
3128                 if (acfg->cfgs [i]) {
3129                         sprintf (symbol, ".Lm_%x", i);
3130                         emit_symbol_diff (acfg, symbol, "methods", 0);
3131                 } else {
3132                         emit_int32 (acfg, 0xffffffff);
3133                 }
3134         }
3135         emit_line (acfg);
3136 }
3137
3138 static void
3139 emit_info (MonoAotCompile *acfg)
3140 {
3141         int i;
3142         char symbol [256];
3143         GList *l;
3144
3145         /* Emit method info */
3146         sprintf (symbol, "method_info");
3147         emit_section_change (acfg, ".text", 1);
3148         emit_global (acfg, symbol, FALSE);
3149         emit_alignment (acfg, 8);
3150         emit_label (acfg, symbol);
3151
3152         /* To reduce size of generated assembly code */
3153         sprintf (symbol, "mi");
3154         emit_label (acfg, symbol);
3155
3156         for (l = acfg->method_order; l != NULL; l = l->next) {
3157                 i = GPOINTER_TO_UINT (l->data);
3158
3159                 if (acfg->cfgs [i])
3160                         emit_method_info (acfg, acfg->cfgs [i]);
3161         }
3162
3163         sprintf (symbol, "method_info_offsets");
3164         emit_section_change (acfg, ".text", 1);
3165         emit_global (acfg, symbol, FALSE);
3166         emit_alignment (acfg, 8);
3167         emit_label (acfg, symbol);
3168
3169         for (i = 0; i < acfg->nmethods; ++i) {
3170                 if (acfg->cfgs [i]) {
3171                         sprintf (symbol, ".Lm_%x_p", i);
3172                         emit_symbol_diff (acfg, symbol, "mi", 0);
3173                 } else {
3174                         emit_int32 (acfg, 0);
3175                 }
3176         }
3177         emit_line (acfg);
3178 }
3179  
3180 typedef struct HashEntry {
3181     guint32 key, value, index;
3182         struct HashEntry *next;
3183 } HashEntry;
3184
3185 /*
3186  * emit_extra_methods:
3187  *
3188  * Emit methods which are not in the METHOD table, like wrappers.
3189  */
3190 static void
3191 emit_extra_methods (MonoAotCompile *acfg)
3192 {
3193         int i, table_size, buf_size;
3194         char symbol [256];
3195         guint8 *p, *buf;
3196         guint32 *info_offsets;
3197         guint32 hash;
3198         GPtrArray *table;
3199         HashEntry *entry, *new_entry;
3200         int nmethods;
3201
3202         info_offsets = g_new0 (guint32, acfg->extra_methods->len);
3203
3204         buf_size = acfg->extra_methods->len * 256 + 256;
3205         p = buf = g_malloc (buf_size);
3206
3207         /* Encode method info */
3208         nmethods = 0;
3209         /* So offsets are > 0 */
3210         *p = 0;
3211         p++;
3212         for (i = 0; i < acfg->extra_methods->len; ++i) {
3213                 MonoMethod *method = g_ptr_array_index (acfg->extra_methods, i);
3214                 MonoCompile *cfg = g_hash_table_lookup (acfg->method_to_cfg, method);
3215
3216                 if (!cfg)
3217                         continue;
3218
3219                 nmethods ++;
3220                 info_offsets [i] = p - buf;
3221
3222                 if (method->wrapper_type) {
3223                         char *name;
3224
3225                         // FIXME: Optimize disk usage
3226                         if (method->wrapper_type == MONO_WRAPPER_RUNTIME_INVOKE) {
3227                                 char *tmpsig = mono_signature_get_desc (mono_method_signature (method), TRUE);
3228                                 name = g_strdup_printf ("(wrapper runtime-invoke):%s (%s)", method->name, tmpsig);
3229                                 g_free (tmpsig);
3230                         } else if (method->wrapper_type == MONO_WRAPPER_DELEGATE_INVOKE) {
3231                                 char *tmpsig = mono_signature_get_desc (mono_method_signature (method), TRUE);
3232                                 name = g_strdup_printf ("(wrapper delegate-invoke):%s (%s)", method->name, tmpsig);
3233                                 g_free (tmpsig);
3234                         } else if (method->wrapper_type == MONO_WRAPPER_DELEGATE_BEGIN_INVOKE) {
3235                                 char *tmpsig = mono_signature_get_desc (mono_method_signature (method), TRUE);
3236                                 name = g_strdup_printf ("(wrapper delegate-begin-invoke):%s (%s)", method->name, tmpsig);
3237                                 g_free (tmpsig);
3238                         } else if (method->wrapper_type == MONO_WRAPPER_DELEGATE_END_INVOKE) {
3239                                 char *tmpsig = mono_signature_get_desc (mono_method_signature (method), TRUE);
3240                                 name = g_strdup_printf ("(wrapper delegate-end-invoke):%s (%s)", method->name, tmpsig);
3241                                 g_free (tmpsig);
3242                         } else {
3243                                 name = mono_method_full_name (cfg->orig_method, TRUE);
3244                         }
3245
3246                         encode_value (1, p, &p);
3247                         strcpy ((char*)p, name);
3248                         p += strlen (name ) + 1;
3249                         g_free (name);
3250                 } else {
3251                         encode_value (0, p, &p);
3252                         encode_method_ref (acfg, method, p, &p);
3253                 }
3254
3255                 g_assert ((p - buf) < buf_size);
3256         }
3257
3258         g_assert ((p - buf) < buf_size);
3259
3260         /* Emit method info */
3261         sprintf (symbol, "extra_method_info");
3262         emit_section_change (acfg, ".text", 1);
3263         emit_global (acfg, symbol, FALSE);
3264         emit_alignment (acfg, 8);
3265         emit_label (acfg, symbol);
3266
3267         emit_bytes (acfg, buf, p - buf);
3268
3269         emit_line (acfg);
3270
3271         /*
3272          * Construct a chained hash table for mapping indexes in extra_method_info to
3273          * method indexes.
3274          */
3275         table_size = g_spaced_primes_closest ((int)(nmethods * 1.5));
3276         table = g_ptr_array_sized_new (table_size);
3277         for (i = 0; i < table_size; ++i)
3278                 g_ptr_array_add (table, NULL);
3279         for (i = 0; i < acfg->extra_methods->len; ++i) {
3280                 MonoMethod *method = g_ptr_array_index (acfg->extra_methods, i);
3281                 MonoCompile *cfg = g_hash_table_lookup (acfg->method_to_cfg, method);
3282                 guint32 key, value;
3283
3284                 if (!cfg)
3285                         continue;
3286
3287                 key = info_offsets [i];
3288                 value = get_method_index (acfg, method);
3289
3290                 if (method->wrapper_type) {
3291                         hash = g_str_hash (method->name) % table_size;
3292                 } else {
3293                         // FIXME:
3294                         hash = 0 % table_size;
3295                 }
3296
3297                 /* FIXME: Allocate from the mempool */
3298                 new_entry = g_new0 (HashEntry, 1);
3299                 new_entry->key = key;
3300                 new_entry->value = value;
3301
3302                 entry = g_ptr_array_index (table, hash);
3303                 if (entry == NULL) {
3304                         new_entry->index = hash;
3305                         g_ptr_array_index (table, hash) = new_entry;
3306                 } else {
3307                         while (entry->next)
3308                                 entry = entry->next;
3309                         
3310                         entry->next = new_entry;
3311                         new_entry->index = table->len;
3312                         g_ptr_array_add (table, new_entry);
3313                 }
3314         }
3315
3316         /* Emit the table */
3317         sprintf (symbol, "extra_method_table");
3318         emit_section_change (acfg, ".text", 0);
3319         emit_global (acfg, symbol, FALSE);
3320         emit_alignment (acfg, 8);
3321         emit_label (acfg, symbol);
3322
3323         g_assert (table_size < 65000);
3324         emit_int32 (acfg, table_size);
3325         g_assert (table->len < 65000);
3326         for (i = 0; i < table->len; ++i) {
3327                 HashEntry *entry = g_ptr_array_index (table, i);
3328
3329                 if (entry == NULL) {
3330                         emit_int32 (acfg, 0);
3331                         emit_int32 (acfg, 0);
3332                         emit_int32 (acfg, 0);
3333                 } else {
3334                         g_assert (entry->key > 0);
3335                         emit_int32 (acfg, entry->key);
3336                         emit_int32 (acfg, entry->value);
3337                         if (entry->next)
3338                                 emit_int32 (acfg, entry->next->index);
3339                         else
3340                                 emit_int32 (acfg, 0);
3341                 }
3342         }
3343
3344         /* 
3345          * Emit a table reverse mapping method indexes to their index in extra_method_info.
3346          * This is used by mono_aot_find_jit_info ().
3347          */
3348         sprintf (symbol, "extra_method_info_offsets");
3349         emit_section_change (acfg, ".text", 0);
3350         emit_global (acfg, symbol, FALSE);
3351         emit_alignment (acfg, 8);
3352         emit_label (acfg, symbol);
3353
3354         emit_int32 (acfg, acfg->extra_methods->len);
3355         for (i = 0; i < acfg->extra_methods->len; ++i) {
3356                 MonoMethod *method = g_ptr_array_index (acfg->extra_methods, i);
3357
3358                 emit_int32 (acfg, get_method_index (acfg, method));
3359                 emit_int32 (acfg, info_offsets [i]);
3360         }
3361 }       
3362
3363 static void
3364 emit_method_order (MonoAotCompile *acfg)
3365 {
3366         int i, index, len;
3367         char symbol [256];
3368         GList *l;
3369
3370         sprintf (symbol, "method_order");
3371         emit_section_change (acfg, ".text", 1);
3372         emit_global (acfg, symbol, FALSE);
3373         emit_alignment (acfg, 8);
3374         emit_label (acfg, symbol);
3375
3376         /* First emit an index table */
3377         index = 0;
3378         len = 0;
3379         for (l = acfg->method_order; l != NULL; l = l->next) {
3380                 i = GPOINTER_TO_UINT (l->data);
3381
3382                 if (acfg->cfgs [i]) {
3383                         if ((index % 1024) == 0) {
3384                                 emit_int32 (acfg, i);
3385                         }
3386
3387                         index ++;
3388                 }
3389
3390                 len ++;
3391         }
3392         emit_int32 (acfg, 0xffffff);
3393
3394         /* Then emit the whole method order */
3395         for (l = acfg->method_order; l != NULL; l = l->next) {
3396                 i = GPOINTER_TO_UINT (l->data);
3397
3398                 if (acfg->cfgs [i]) {
3399                         emit_int32 (acfg, i);
3400                 }
3401         }       
3402         emit_line (acfg);
3403
3404         sprintf (symbol, "method_order_end");
3405         emit_section_change (acfg, ".text", 1);
3406         emit_global (acfg, symbol, FALSE);
3407         emit_label (acfg, symbol);
3408 }
3409
3410 static void
3411 emit_exception_info (MonoAotCompile *acfg)
3412 {
3413         int i;
3414         char symbol [256];
3415
3416         sprintf (symbol, "ex_info");
3417         emit_section_change (acfg, ".text", 1);
3418         emit_global (acfg, symbol, FALSE);
3419         emit_alignment (acfg, 8);
3420         emit_label (acfg, symbol);
3421
3422         /* To reduce size of generated assembly */
3423         sprintf (symbol, "ex");
3424         emit_label (acfg, symbol);
3425
3426         for (i = 0; i < acfg->nmethods; ++i) {
3427                 if (acfg->cfgs [i])
3428                         emit_exception_debug_info (acfg, acfg->cfgs [i]);
3429         }
3430
3431         sprintf (symbol, "ex_info_offsets");
3432         emit_section_change (acfg, ".text", 1);
3433         emit_global (acfg, symbol, FALSE);
3434         emit_alignment (acfg, 8);
3435         emit_label (acfg, symbol);
3436
3437         for (i = 0; i < acfg->nmethods; ++i) {
3438                 if (acfg->cfgs [i]) {
3439                         sprintf (symbol, ".Le_%x_p", i);
3440                         emit_symbol_diff (acfg, symbol, "ex", 0);
3441                 } else {
3442                         emit_int32 (acfg, 0);
3443                 }
3444         }
3445         emit_line (acfg);
3446 }
3447
3448 static void
3449 emit_class_info (MonoAotCompile *acfg)
3450 {
3451         int i;
3452         char symbol [256];
3453
3454         sprintf (symbol, "class_info");
3455         emit_section_change (acfg, ".text", 1);
3456         emit_global (acfg, symbol, FALSE);
3457         emit_alignment (acfg, 8);
3458         emit_label (acfg, symbol);
3459
3460         for (i = 0; i < acfg->image->tables [MONO_TABLE_TYPEDEF].rows; ++i)
3461                 emit_klass_info (acfg, MONO_TOKEN_TYPE_DEF | (i + 1));
3462
3463         sprintf (symbol, "class_info_offsets");
3464         emit_section_change (acfg, ".text", 1);
3465         emit_global (acfg, symbol, FALSE);
3466         emit_alignment (acfg, 8);
3467         emit_label (acfg, symbol);
3468
3469         for (i = 0; i < acfg->image->tables [MONO_TABLE_TYPEDEF].rows; ++i) {
3470                 sprintf (symbol, ".LK_I_%x", i);
3471                 emit_symbol_diff (acfg, symbol, "class_info", 0);
3472         }
3473         emit_line (acfg);
3474 }
3475
3476 typedef struct ClassNameTableEntry {
3477         guint32 token, index;
3478         struct ClassNameTableEntry *next;
3479 } ClassNameTableEntry;
3480
3481 static void
3482 emit_class_name_table (MonoAotCompile *acfg)
3483 {
3484         int i, table_size;
3485         guint32 token, hash;
3486         MonoClass *klass;
3487         GPtrArray *table;
3488         char *full_name;
3489         char symbol [256];
3490         ClassNameTableEntry *entry, *new_entry;
3491
3492         /*
3493          * Construct a chained hash table for mapping class names to typedef tokens.
3494          */
3495         table_size = g_spaced_primes_closest ((int)(acfg->image->tables [MONO_TABLE_TYPEDEF].rows * 1.5));
3496         table = g_ptr_array_sized_new (table_size);
3497         for (i = 0; i < table_size; ++i)
3498                 g_ptr_array_add (table, NULL);
3499         for (i = 0; i < acfg->image->tables [MONO_TABLE_TYPEDEF].rows; ++i) {
3500                 token = MONO_TOKEN_TYPE_DEF | (i + 1);
3501                 klass = mono_class_get (acfg->image, token);
3502                 full_name = mono_type_get_name_full (mono_class_get_type (klass), MONO_TYPE_NAME_FORMAT_FULL_NAME);
3503                 hash = g_str_hash (full_name) % table_size;
3504                 g_free (full_name);
3505
3506                 /* FIXME: Allocate from the mempool */
3507                 new_entry = g_new0 (ClassNameTableEntry, 1);
3508                 new_entry->token = token;
3509
3510                 entry = g_ptr_array_index (table, hash);
3511                 if (entry == NULL) {
3512                         new_entry->index = hash;
3513                         g_ptr_array_index (table, hash) = new_entry;
3514                 } else {
3515                         while (entry->next)
3516                                 entry = entry->next;
3517                         
3518                         entry->next = new_entry;
3519                         new_entry->index = table->len;
3520                         g_ptr_array_add (table, new_entry);
3521                 }
3522         }
3523
3524         /* Emit the table */
3525         sprintf (symbol, "class_name_table");
3526         emit_section_change (acfg, ".text", 0);
3527         emit_global (acfg, symbol, FALSE);
3528         emit_alignment (acfg, 8);
3529         emit_label (acfg, symbol);
3530
3531         /* FIXME: Optimize memory usage */
3532         g_assert (table_size < 65000);
3533         emit_int16 (acfg, table_size);
3534         g_assert (table->len < 65000);
3535         for (i = 0; i < table->len; ++i) {
3536                 ClassNameTableEntry *entry = g_ptr_array_index (table, i);
3537
3538                 if (entry == NULL) {
3539                         emit_int16 (acfg, 0);
3540                         emit_int16 (acfg, 0);
3541                 } else {
3542                         emit_int16 (acfg, mono_metadata_token_index (entry->token));
3543                         if (entry->next)
3544                                 emit_int16 (acfg, entry->next->index);
3545                         else
3546                                 emit_int16 (acfg, 0);
3547                 }
3548         }
3549 }
3550
3551 static void
3552 emit_image_table (MonoAotCompile *acfg)
3553 {
3554         int i;
3555         char symbol [256];
3556
3557         /*
3558          * The image table is small but referenced in a lot of places.
3559          * So we emit it at once, and reference its elements by an index.
3560          */
3561
3562         sprintf (symbol, "mono_image_table");
3563         emit_section_change (acfg, ".text", 1);
3564         emit_global (acfg, symbol, FALSE);
3565         emit_alignment (acfg, 8);
3566         emit_label (acfg, symbol);
3567
3568         emit_int32 (acfg, acfg->image_table->len);
3569         for (i = 0; i < acfg->image_table->len; i++) {
3570                 MonoImage *image = (MonoImage*)g_ptr_array_index (acfg->image_table, i);
3571                 MonoAssemblyName *aname = &image->assembly->aname;
3572
3573                 /* FIXME: Support multi-module assemblies */
3574                 g_assert (image->assembly->image == image);
3575
3576                 emit_string (acfg, image->assembly_name);
3577                 emit_string (acfg, image->guid);
3578                 emit_string (acfg, aname->culture ? aname->culture : "");
3579                 emit_string (acfg, (const char*)aname->public_key_token);
3580
3581                 emit_alignment (acfg, 8);
3582                 emit_int32 (acfg, aname->flags);
3583                 emit_int32 (acfg, aname->major);
3584                 emit_int32 (acfg, aname->minor);
3585                 emit_int32 (acfg, aname->build);
3586                 emit_int32 (acfg, aname->revision);
3587         }
3588 }
3589
3590 static void
3591 emit_got_info (MonoAotCompile *acfg)
3592 {
3593         char symbol [256];
3594         int i, first_plt_got_patch, buf_size;
3595         guint8 *p, *buf;
3596         guint32 *got_info_offsets;
3597
3598         /* Add the patches needed by the PLT to the GOT */
3599         acfg->plt_got_offset_base = acfg->got_offset;
3600         first_plt_got_patch = acfg->shared_patches->len;
3601         for (i = 1; i < acfg->plt_offset; ++i) {
3602                 MonoJumpInfo *patch_info = g_hash_table_lookup (acfg->plt_offset_to_patch, GUINT_TO_POINTER (i));
3603
3604                 g_ptr_array_add (acfg->shared_patches, patch_info);
3605         }
3606
3607         acfg->got_offset += acfg->plt_offset;
3608
3609         /**
3610          * FIXME: 
3611          * - optimize offsets table.
3612          * - reduce number of exported symbols.
3613          * - emit info for a klass only once.
3614          * - determine when a method uses a GOT slot which is guaranteed to be already 
3615          *   initialized.
3616          * - clean up and document the code.
3617          * - use String.Empty in class libs.
3618          */
3619
3620         /* Encode info required to decode shared GOT entries */
3621         buf_size = acfg->shared_patches->len * 64;
3622         p = buf = mono_mempool_alloc (acfg->mempool, buf_size);
3623         got_info_offsets = mono_mempool_alloc (acfg->mempool, acfg->shared_patches->len * sizeof (guint32));
3624         acfg->plt_got_info_offsets = mono_mempool_alloc (acfg->mempool, acfg->plt_offset * sizeof (guint32));
3625         for (i = 0; i < acfg->shared_patches->len; ++i) {
3626                 MonoJumpInfo *ji = g_ptr_array_index (acfg->shared_patches, i);
3627
3628                 got_info_offsets [i] = p - buf;
3629                 /* No need to encode the patch type for non-PLT patches */
3630                 if (i >= first_plt_got_patch) {
3631                         acfg->plt_got_info_offsets [i - first_plt_got_patch + 1] = got_info_offsets [i];
3632                         encode_value (ji->type, p, &p);
3633                 }
3634                 encode_patch (acfg, ji, p, &p);
3635         }
3636
3637         g_assert (p - buf <= buf_size);
3638
3639         acfg->stats.got_info_size = p - buf;
3640
3641         /* Emit got_info table */
3642         sprintf (symbol, "got_info");
3643         emit_section_change (acfg, ".text", 1);
3644         emit_global (acfg, symbol, FALSE);
3645         emit_alignment (acfg, 8);
3646         emit_label (acfg, symbol);
3647
3648         emit_bytes (acfg, buf, p - buf);
3649
3650         /* Emit got_info_offsets table */
3651         sprintf (symbol, "got_info_offsets");
3652         emit_section_change (acfg, ".text", 1);
3653         emit_global (acfg, symbol, FALSE);
3654         emit_alignment (acfg, 8);
3655         emit_label (acfg, symbol);
3656
3657         for (i = 0; i < acfg->shared_patches->len; ++i)
3658                 emit_int32 (acfg, got_info_offsets [i]);
3659
3660         acfg->stats.got_info_offsets_size = acfg->shared_patches->len * 4;
3661 }
3662
3663 static void
3664 emit_got (MonoAotCompile *acfg)
3665 {
3666         char symbol [256];
3667
3668         /* Don't make GOT global so accesses to it don't need relocations */
3669         sprintf (symbol, "got");
3670         emit_section_change (acfg, ".bss", 0);
3671         emit_alignment (acfg, 8);
3672         emit_label (acfg, symbol);
3673         if (acfg->got_offset > 0)
3674                 emit_zero_bytes (acfg, (int)(acfg->got_offset * sizeof (gpointer)));
3675 }
3676
3677 static void
3678 emit_globals (MonoAotCompile *acfg)
3679 {
3680         char *opts_str;
3681         char *build_info;
3682
3683         emit_string_symbol (acfg, "mono_assembly_guid" , acfg->image->guid);
3684
3685         emit_string_symbol (acfg, "mono_aot_version", MONO_AOT_FILE_VERSION);
3686
3687         opts_str = g_strdup_printf ("%d", acfg->opts);
3688         emit_string_symbol (acfg, "mono_aot_opt_flags", opts_str);
3689         g_free (opts_str);
3690
3691         emit_string_symbol (acfg, "mono_aot_full_aot", acfg->aot_opts.full_aot ? "TRUE" : "FALSE");
3692
3693         if (acfg->aot_opts.bind_to_runtime_version) {
3694                 build_info = mono_get_runtime_build_info ();
3695                 emit_string_symbol (acfg, "mono_runtime_version", build_info);
3696                 g_free (build_info);
3697         } else {
3698                 emit_string_symbol (acfg, "mono_runtime_version", "");
3699         }
3700
3701         /*
3702          * Some platforms like the iphone have no working dlsym (). To work around this,
3703          * we create an ELF ctor function which will be invoked by dlopen, and which
3704          * will call a function in the AOT loader to register the symbols used by the
3705          * image.
3706          * When static linking, we emit a global which will point to the symbol table.
3707          */
3708         if (acfg->aot_opts.no_dlsym) {
3709                 int i;
3710                 char symbol [256];
3711
3712                 if (acfg->aot_opts.static_link)
3713                         /* Emit a string holding the assembly name */
3714                         emit_string_symbol (acfg, "mono_aot_assembly_name", acfg->image->assembly->aname.name);
3715
3716                 /* Emit the names */
3717                 for (i = 0; i < acfg->globals->len; ++i) {
3718                         char *name = g_ptr_array_index (acfg->globals, i);
3719
3720                         sprintf (symbol, "name_%d", i);
3721                         emit_section_change (acfg, ".text", 1);
3722                         emit_label (acfg, symbol);
3723                         emit_string (acfg, name);
3724                 }
3725
3726                 /* Emit the globals table */
3727                 sprintf (symbol, "globals");
3728                 emit_section_change (acfg, ".data", 0);
3729                 /* This is not a global, since it is accessed by the init function */
3730                 emit_alignment (acfg, 8);
3731                 emit_label (acfg, symbol);
3732
3733                 for (i = 0; i < acfg->globals->len; ++i) {
3734                         char *name = g_ptr_array_index (acfg->globals, i);
3735
3736                         sprintf (symbol, "name_%d", i);
3737                         emit_pointer (acfg, symbol);
3738
3739                         sprintf (symbol, "%s", name);
3740                         emit_pointer (acfg, symbol);
3741                 }
3742                 /* Null terminate the table */
3743                 emit_pointer (acfg, NULL);
3744                 emit_pointer (acfg, NULL);
3745
3746 #if 0
3747                 if (acfg->aot_opts.static_link) {
3748                         char *p;
3749
3750                         /* 
3751                          * Emit a global symbol which can be passed by an embedding app to
3752                          * mono_aot_register_module ().
3753                          */
3754 #if defined(__MACH__)
3755                         sprintf (symbol, "_mono_aot_module_%s_info", acfg->image->assembly->aname.name);
3756 #else
3757                         sprintf (symbol, "mono_aot_module_%s_info", acfg->image->assembly->aname.name);
3758 #endif
3759
3760                         /* Get rid of characters which cannot occur in symbols */
3761                         p = symbol;
3762                         for (p = symbol; *p; ++p) {
3763                                 if (!(isalnum (*p) || *p == '_'))
3764                                         *p = '_';
3765                         }
3766                         acfg->static_linking_symbol = g_strdup (symbol);
3767                         emit_global_inner (acfg, symbol, FALSE);
3768                         emit_alignment (acfg, 8);
3769                         emit_label (acfg, symbol);
3770                         emit_pointer (acfg, "globals");
3771                 } else {
3772                         sprintf (symbol, "init_%s", acfg->image->assembly->aname.name);
3773                         emit_section_change (acfg, ".text", 1);
3774                         emit_alignment (acfg, 8);
3775                         emit_label (acfg, symbol);
3776                         if (acfg->use_bin_writer)
3777                                 g_assert_not_reached ();
3778 #ifdef __x86_64__
3779                         fprintf (acfg->fp, "leaq globals(%%rip), %%rdi\n");
3780                         fprintf (acfg->fp, "call mono_aot_register_globals@PLT\n");
3781                         fprintf (acfg->fp, "ret\n");
3782                         fprintf (acfg->fp, ".section .ctors,\"aw\",@progbits\n");
3783                         emit_alignment (acfg, 8);
3784                         emit_pointer (acfg, symbol);
3785 #elif defined(__arm__) && defined(__MACH__)
3786                                 
3787                         fprintf (acfg->fp, ".text\n");
3788                         fprintf (acfg->fp, ".align   3\n");
3789                 
3790                         fprintf (acfg->fp, "ldr r0, .L5\n");
3791                         fprintf (acfg->fp, ".LPIC0:\n");
3792                         fprintf (acfg->fp, "add r0, pc, r0\n");
3793                         fprintf (acfg->fp, "ldr r0, [r0]\n");
3794                         fprintf (acfg->fp, "b   _mono_aot_register_globals@PLT\n");
3795                         fprintf (acfg->fp, ".align 2\n");
3796
3797                         fprintf (acfg->fp, ".L5:\n");
3798                         fprintf (acfg->fp, ".long       globals_ptr-(.LPIC0+8)\n");
3799                         
3800                         fprintf (acfg->fp, ".data\n");
3801                         fprintf (acfg->fp, ".align      2\n");
3802                         fprintf (acfg->fp, "globals_ptr:\n");
3803                         fprintf (acfg->fp, ".long       globals\n");
3804                         
3805                         fprintf (acfg->fp, ".mod_init_func\n");
3806                         fprintf (acfg->fp, ".align      2\n");
3807                         fprintf (acfg->fp, ".long       %s@target1\n", symbol);
3808
3809 #elif defined(__arm__)
3810                         /* 
3811                          * Taken from gcc generated code for:
3812                          * static int i;
3813                          * void foo () { bar (&i); }
3814                          * gcc --shared -fPIC -O2
3815                          */
3816                         fprintf (acfg->fp, "ldr r3, .L5\n");
3817                         fprintf (acfg->fp, "ldr r0, .L5+4\n");
3818                         fprintf (acfg->fp, ".LPIC0:\n");
3819                         fprintf (acfg->fp, "add r3, pc, r3\n");
3820                         fprintf (acfg->fp, "add r0, r3, r0\n");
3821                         fprintf (acfg->fp, "b   mono_aot_register_globals(PLT)\n");
3822
3823                         fprintf (acfg->fp, ".L5:\n");
3824                         fprintf (acfg->fp, ".word       _GLOBAL_OFFSET_TABLE_-(.LPIC0+8)\n");
3825                         fprintf (acfg->fp, ".word       globals(GOTOFF)\n");
3826
3827                         fprintf (acfg->fp, ".section    .init_array,\"aw\",%%init_array\n");
3828                         fprintf (acfg->fp, ".align      2\n");
3829                         fprintf (acfg->fp, ".word       %s(target1)\n", symbol);
3830 #else
3831                         g_assert_not_reached ();
3832 #endif
3833                 }
3834 #endif
3835         }
3836 }
3837
3838 /*
3839  * Emit a structure containing all the information not stored elsewhere.
3840  */
3841 static void
3842 emit_file_info (MonoAotCompile *acfg)
3843 {
3844         char symbol [128];
3845
3846         sprintf (symbol, "mono_aot_file_info");
3847         emit_section_change (acfg, ".data", 0);
3848         emit_alignment (acfg, 8);
3849         emit_label (acfg, symbol);
3850         emit_global (acfg, symbol, FALSE);
3851
3852         /* The data emitted here must match MonoAotFileInfo in aot-runtime.c. */
3853         emit_int32 (acfg, acfg->plt_got_offset_base);
3854         emit_int32 (acfg, acfg->trampoline_got_offset_base);
3855         emit_int32 (acfg, acfg->num_aot_trampolines);
3856         emit_int32 (acfg, (int)(acfg->got_offset * sizeof (gpointer)));
3857         emit_int32 (acfg, acfg->plt_offset);
3858         emit_int32 (acfg, acfg->specific_trampoline_size);
3859         emit_pointer (acfg, "got");
3860 }
3861
3862 /*****************************************/
3863 /*   Emitting DWARF debug information    */
3864 /*****************************************/
3865
3866 static void
3867 emit_dwarf_abbrev (MonoAotCompile *acfg, int code, int tag, gboolean has_child,
3868                                    int *attrs, int attrs_len)
3869 {
3870         int i;
3871
3872         emit_uleb128 (acfg, code);
3873         emit_uleb128 (acfg, tag);
3874         emit_byte (acfg, has_child);
3875
3876         for (i = 0; i < attrs_len; i++)
3877                 emit_uleb128 (acfg, attrs [i]);
3878         emit_uleb128 (acfg, 0);
3879         emit_uleb128 (acfg, 0);
3880 }
3881
3882 static void
3883 emit_cie (MonoAotCompile *acfg)
3884 {
3885 #ifdef EMIT_DWARF_INFO
3886         emit_section_change (acfg, ".debug_frame", 0);
3887
3888         emit_alignment (acfg, 8);
3889
3890         /* Emit a CIE */
3891         emit_symbol_diff (acfg, ".Lcie0_end", ".", -4); /* length */
3892         emit_int32 (acfg, 0xffffffff); /* CIE id */
3893         emit_byte (acfg, 3); /* version */
3894         emit_string (acfg, ""); /* augmention */
3895         emit_sleb128 (acfg, 1); /* code alignment factor */
3896         emit_sleb128 (acfg, mono_unwind_get_dwarf_data_align ()); /* data alignment factor */
3897         emit_uleb128 (acfg, mono_unwind_get_dwarf_pc_reg ());
3898
3899         acfg->cie_program = arch_get_cie_program (acfg);
3900         if (acfg->cie_program) {
3901                 guint32 uw_info_len;
3902                 guint8 *uw_info = mono_unwind_ops_encode (acfg->cie_program, &uw_info_len);
3903                 emit_bytes (acfg, uw_info, uw_info_len);
3904                 g_free (uw_info);
3905         }
3906
3907         emit_alignment (acfg, sizeof (gpointer));
3908         emit_label (acfg, ".Lcie0_end");
3909 #endif
3910 }
3911
3912 static void
3913 emit_pointer_value (MonoAotCompile *acfg, gpointer ptr)
3914 {
3915         gssize val = (gssize)ptr;
3916         emit_bytes (acfg, (guint8*)&val, sizeof (gpointer));
3917 }
3918
3919 static void
3920 emit_fde (MonoAotCompile *acfg, int fde_index, char *start_symbol, char *end_symbol,
3921                   guint8 *code, guint32 code_size, GSList *unwind_ops, gboolean use_cie)
3922 {
3923 #ifdef EMIT_DWARF_INFO
3924         char symbol [128];
3925         GSList *l;
3926         guint8 *uw_info;
3927         guint32 uw_info_len;
3928
3929         emit_section_change (acfg, ".debug_frame", 0);
3930
3931         sprintf (symbol, ".Lfde%d_end", fde_index);
3932         emit_symbol_diff (acfg, symbol, ".", -4); /* length */
3933         emit_int32 (acfg, 0); /* CIE_pointer */
3934         if (start_symbol) {
3935                 emit_pointer (acfg, start_symbol); /* initial_location */
3936                 if (end_symbol)
3937                         emit_symbol_diff (acfg, end_symbol, start_symbol, 0); /* address_range */
3938                 else {
3939                         g_assert (code_size);
3940                         emit_int32 (acfg, code_size);
3941                 }
3942         } else {
3943                 emit_pointer_value (acfg, code);
3944                 emit_int32 (acfg, code_size);
3945         }
3946 #if SIZEOF_VOID_P == 8
3947         /* Upper 32 bits of code size */
3948         emit_int32 (acfg, 0);
3949 #endif
3950
3951         l = unwind_ops;
3952         if (acfg->cie_program) {
3953                 // FIXME: Check that the ops really begin with the CIE program */
3954                 int i;
3955
3956                 for (i = 0; i < g_slist_length (acfg->cie_program); ++i)
3957                         l = l->next;
3958         }
3959
3960         /* Convert the list of MonoUnwindOps to the format used by DWARF */     
3961         uw_info = mono_unwind_ops_encode (l, &uw_info_len);
3962         emit_bytes (acfg, uw_info, uw_info_len);
3963         g_free (uw_info);
3964
3965         emit_alignment (acfg, sizeof (gpointer));
3966         sprintf (symbol, ".Lfde%d_end", fde_index);
3967         emit_label (acfg, symbol);
3968 #endif
3969 }
3970
3971 /* Abbrevations */
3972 #define ABBREV_COMPILE_UNIT 1
3973 #define ABBREV_SUBPROGRAM 2
3974 #define ABBREV_PARAM 3
3975 #define ABBREV_BASE_TYPE 4
3976 #define ABBREV_STRUCT_TYPE 5
3977 #define ABBREV_DATA_MEMBER 6
3978 #define ABBREV_TYPEDEF 7
3979 #define ABBREV_ENUM_TYPE 8
3980 #define ABBREV_ENUMERATOR 9
3981 #define ABBREV_NAMESPACE 10
3982 #define ABBREV_VARIABLE 11
3983 #define ABBREV_VARIABLE_LOCLIST 12
3984
3985 static int compile_unit_attr [] = {
3986         DW_AT_producer     ,DW_FORM_string,
3987     DW_AT_name         ,DW_FORM_string,
3988     DW_AT_comp_dir     ,DW_FORM_string,
3989         DW_AT_language     ,DW_FORM_data1,
3990     DW_AT_low_pc       ,DW_FORM_addr,
3991     DW_AT_high_pc      ,DW_FORM_addr,
3992         DW_AT_stmt_list    ,DW_FORM_data4
3993 };
3994
3995 static int subprogram_attr [] = {
3996         DW_AT_name         , DW_FORM_string,
3997     DW_AT_low_pc       , DW_FORM_addr,
3998     DW_AT_high_pc      , DW_FORM_addr,
3999         DW_AT_frame_base   , DW_FORM_block1
4000 };
4001
4002 static int param_attr [] = {
4003         DW_AT_name,     DW_FORM_string,
4004         DW_AT_type,     DW_FORM_ref4,
4005         DW_AT_location, DW_FORM_block1
4006 };
4007
4008 static int base_type_attr [] = {
4009         DW_AT_byte_size,   DW_FORM_data1,
4010         DW_AT_encoding,    DW_FORM_data1,
4011         DW_AT_name,        DW_FORM_string
4012 };
4013
4014 static int struct_type_attr [] = {
4015         DW_AT_name,        DW_FORM_string,
4016         DW_AT_byte_size,   DW_FORM_udata,
4017 };
4018
4019 static int data_member_attr [] = {
4020         DW_AT_name,        DW_FORM_string,
4021         DW_AT_type,        DW_FORM_ref4,
4022         DW_AT_data_member_location, DW_FORM_block1
4023 };
4024
4025 static int typedef_attr [] = {
4026         DW_AT_name,        DW_FORM_string,
4027         DW_AT_type,        DW_FORM_ref4
4028 };
4029
4030 static int enum_type_attr [] = {
4031         DW_AT_name,        DW_FORM_string,
4032         DW_AT_byte_size,   DW_FORM_udata,
4033         DW_AT_type,        DW_FORM_ref4,
4034 };
4035
4036 static int enumerator_attr [] = {
4037         DW_AT_name,        DW_FORM_string,
4038         DW_AT_const_value, DW_FORM_sdata,
4039 };
4040
4041 static int namespace_attr [] = {
4042         DW_AT_name,        DW_FORM_string,
4043 };
4044
4045 static int variable_attr [] = {
4046         DW_AT_name,     DW_FORM_string,
4047         DW_AT_type,     DW_FORM_ref4,
4048         DW_AT_location, DW_FORM_block1
4049 };
4050
4051 static int variable_loclist_attr [] = {
4052         DW_AT_name,     DW_FORM_string,
4053         DW_AT_type,     DW_FORM_ref4,
4054         DW_AT_location, DW_FORM_data4
4055 };
4056
4057 typedef struct DwarfBasicType {
4058         const char *die_name, *name;
4059         int type;
4060         int size;
4061         int encoding;
4062 } DwarfBasicType;
4063
4064 static DwarfBasicType basic_types [] = {
4065         { ".LDIE_I1", "sbyte", MONO_TYPE_I1, 1, DW_ATE_signed },
4066         { ".LDIE_U1", "byte", MONO_TYPE_U1, 1, DW_ATE_unsigned },
4067         { ".LDIE_I2", "short", MONO_TYPE_I2, 2, DW_ATE_signed },
4068         { ".LDIE_U2", "ushort", MONO_TYPE_U2, 2, DW_ATE_unsigned },
4069         { ".LDIE_I4", "int", MONO_TYPE_I4, 4, DW_ATE_signed },
4070         { ".LDIE_U4", "uint", MONO_TYPE_U4, 4, DW_ATE_unsigned },
4071         { ".LDIE_I8", "long", MONO_TYPE_I8, 8, DW_ATE_signed },
4072         { ".LDIE_U8", "ulong", MONO_TYPE_U8, 8, DW_ATE_unsigned },
4073         { ".LDIE_I", "intptr", MONO_TYPE_I, SIZEOF_VOID_P, DW_ATE_signed },
4074         { ".LDIE_U", "uintptr", MONO_TYPE_U, SIZEOF_VOID_P, DW_ATE_unsigned },
4075         { ".LDIE_R4", "float", MONO_TYPE_R4, 4, DW_ATE_float },
4076         { ".LDIE_R8", "double", MONO_TYPE_R8, 8, DW_ATE_float },
4077         { ".LDIE_BOOLEAN", "boolean", MONO_TYPE_BOOLEAN, 1, DW_ATE_boolean },
4078         { ".LDIE_CHAR", "char", MONO_TYPE_CHAR, 2, DW_ATE_unsigned_char },
4079         { ".LDIE_STRING", "string", MONO_TYPE_STRING, sizeof (gpointer), DW_ATE_address },
4080         { ".LDIE_OBJECT", "object", MONO_TYPE_OBJECT, sizeof (gpointer), DW_ATE_address },
4081         { ".LDIE_SZARRAY", "object", MONO_TYPE_SZARRAY, sizeof (gpointer), DW_ATE_address },
4082 };
4083
4084 /* Constants for encoding line number special opcodes */
4085 #define OPCODE_BASE 13
4086 #define LINE_BASE -5
4087 #define LINE_RANGE 14
4088
4089 /* Subsections of the .debug_line section */
4090 #define LINE_SUBSECTION_HEADER 1
4091 #define LINE_SUBSECTION_INCLUDES 2
4092 #define LINE_SUBSECTION_FILES 3
4093 #define LINE_SUBSECTION_DATA 4
4094 #define LINE_SUBSECTION_END 5
4095
4096 static int
4097 emit_line_number_file_name (MonoAotCompile *acfg, const char *name,
4098                                                         gint64 last_mod_time, gint64 file_size)
4099 {
4100         int index;
4101         int dir_index;
4102         char *basename = NULL;
4103
4104         if (!acfg->file_to_index)
4105                 acfg->file_to_index = g_hash_table_new (g_str_hash, g_str_equal);
4106
4107         index = GPOINTER_TO_UINT (g_hash_table_lookup (acfg->file_to_index, name));
4108         if (index > 0)
4109                 return index;
4110
4111         if (g_path_is_absolute (name)) {
4112                 char *dir = g_path_get_dirname (name);
4113
4114                 if (!acfg->dir_to_index)
4115                         acfg->dir_to_index = g_hash_table_new (g_str_hash, g_str_equal);
4116
4117                 dir_index = GPOINTER_TO_UINT (g_hash_table_lookup (acfg->dir_to_index, dir));
4118                 if (dir_index == 0) {
4119                         emit_section_change (acfg, ".debug_line", LINE_SUBSECTION_INCLUDES);
4120                         emit_string (acfg, dir);
4121
4122                         dir_index = ++ acfg->line_number_dir_index;
4123                         g_hash_table_insert (acfg->dir_to_index, g_strdup (dir), GUINT_TO_POINTER (dir_index));
4124                 }
4125
4126                 g_free (dir);
4127
4128                 basename = g_path_get_basename (name);
4129         } else {
4130                 dir_index = 0;
4131         }
4132
4133         emit_section_change (acfg, ".debug_line", LINE_SUBSECTION_FILES);
4134
4135         if (basename)
4136                 emit_string (acfg, basename);
4137         else
4138                 emit_string (acfg, name);
4139         emit_uleb128 (acfg, dir_index);
4140         emit_byte (acfg, 0);
4141         emit_byte (acfg, 0);
4142
4143         emit_section_change (acfg, ".debug_line", LINE_SUBSECTION_DATA);
4144
4145         if (basename)
4146                 g_free (basename);
4147
4148         index = ++ acfg->line_number_file_index;
4149         g_hash_table_insert (acfg->file_to_index, g_strdup (name), GUINT_TO_POINTER (index));
4150
4151         return index;
4152 }
4153
4154 static void
4155 emit_line_number_info_begin (MonoAotCompile *acfg)
4156 {
4157         if (acfg->image) {
4158                 /* FIXME: This doesn't seem to work with !xdebug */
4159                 emit_section_change (acfg, ".debug_line", 0);
4160                 emit_label (acfg, ".Ldebug_line_start");
4161                 emit_label (acfg, ".Ldebug_line_section_start");
4162                 return;
4163         }
4164
4165         /* Line number info header */
4166         /* 
4167          * GAS seems to emit its own data to the end of the first subsection, so we use
4168          * subsections 1, 2 etc:
4169          * 1 - contains the header
4170          * 2 - contains the file names
4171          * 3 - contains the end of the header + the data
4172          * 4 - the end symbol
4173          */
4174         emit_section_change (acfg, ".debug_line", 0);
4175         emit_label (acfg, ".Ldebug_line_section_start");
4176         emit_section_change (acfg, ".debug_line", LINE_SUBSECTION_HEADER);
4177         emit_label (acfg, ".Ldebug_line_start");
4178         emit_symbol_diff (acfg, ".Ldebug_line_end", ".", -4); /* length */
4179         emit_int16 (acfg, 0x2); /* version */
4180         emit_symbol_diff (acfg, ".Ldebug_line_header_end", ".", -4); /* header_length */
4181         emit_byte (acfg, 1); /* minimum_instruction_length */
4182         emit_byte (acfg, 1); /* default_is_stmt */
4183         emit_byte (acfg, LINE_BASE); /* line_base */
4184         emit_byte (acfg, LINE_RANGE); /* line_range */
4185         emit_byte (acfg, OPCODE_BASE); /* opcode_base */
4186         emit_byte (acfg, 0); /* standard_opcode_lengths */
4187         emit_byte (acfg, 1);
4188         emit_byte (acfg, 1);
4189         emit_byte (acfg, 1);
4190         emit_byte (acfg, 1);
4191         emit_byte (acfg, 0);
4192         emit_byte (acfg, 0);
4193         emit_byte (acfg, 0);
4194         emit_byte (acfg, 1);
4195         emit_byte (acfg, 0);
4196         emit_byte (acfg, 0);
4197         emit_byte (acfg, 1);
4198
4199         /* Includes */
4200         emit_section_change (acfg, ".debug_line", LINE_SUBSECTION_INCLUDES);
4201
4202         /* End of Includes */
4203         emit_section_change (acfg, ".debug_line", LINE_SUBSECTION_FILES);
4204         emit_byte (acfg, 0);
4205
4206         /* Files */
4207         emit_line_number_file_name (acfg, "xdb.il", 0, 0);
4208
4209         /* End of Files */
4210         emit_section_change (acfg, ".debug_line", LINE_SUBSECTION_DATA);
4211         emit_byte (acfg, 0);
4212
4213         emit_label (acfg, ".Ldebug_line_header_end");
4214
4215         /* Emit this into a separate subsection so it gets placed at the end */ 
4216         emit_section_change (acfg, ".debug_line", LINE_SUBSECTION_END);
4217
4218         emit_byte (acfg, 0);
4219         emit_byte (acfg, 1);
4220         emit_byte (acfg, DW_LNE_end_sequence);
4221
4222         emit_label (acfg, ".Ldebug_line_end");
4223 }
4224
4225 static void
4226 emit_base_dwarf_info (MonoAotCompile *acfg)
4227 {
4228         char *s, *build_info;
4229         int i;
4230
4231         emit_section_change (acfg, ".debug_abbrev", 0);
4232         emit_dwarf_abbrev (acfg, ABBREV_COMPILE_UNIT, DW_TAG_compile_unit, TRUE, 
4233                                            compile_unit_attr, G_N_ELEMENTS (compile_unit_attr));
4234         emit_dwarf_abbrev (acfg, ABBREV_SUBPROGRAM, DW_TAG_subprogram, TRUE, 
4235                                            subprogram_attr, G_N_ELEMENTS (subprogram_attr));
4236         emit_dwarf_abbrev (acfg, ABBREV_PARAM, DW_TAG_formal_parameter, FALSE, 
4237                                            param_attr, G_N_ELEMENTS (param_attr));
4238         emit_dwarf_abbrev (acfg, ABBREV_BASE_TYPE, DW_TAG_base_type, FALSE, 
4239                                            base_type_attr, G_N_ELEMENTS (base_type_attr));
4240         emit_dwarf_abbrev (acfg, ABBREV_STRUCT_TYPE, DW_TAG_class_type, TRUE, 
4241                                            struct_type_attr, G_N_ELEMENTS (struct_type_attr));
4242         emit_dwarf_abbrev (acfg, ABBREV_DATA_MEMBER, DW_TAG_member, FALSE, 
4243                                            data_member_attr, G_N_ELEMENTS (data_member_attr));
4244         emit_dwarf_abbrev (acfg, ABBREV_TYPEDEF, DW_TAG_typedef, FALSE, 
4245                                            typedef_attr, G_N_ELEMENTS (typedef_attr));
4246         emit_dwarf_abbrev (acfg, ABBREV_ENUM_TYPE, DW_TAG_enumeration_type, TRUE,
4247                                            enum_type_attr, G_N_ELEMENTS (enum_type_attr));
4248         emit_dwarf_abbrev (acfg, ABBREV_ENUMERATOR, DW_TAG_enumerator, FALSE,
4249                                            enumerator_attr, G_N_ELEMENTS (enumerator_attr));
4250         emit_dwarf_abbrev (acfg, ABBREV_NAMESPACE, DW_TAG_namespace, TRUE,
4251                                            namespace_attr, G_N_ELEMENTS (namespace_attr));
4252         emit_dwarf_abbrev (acfg, ABBREV_VARIABLE, DW_TAG_variable, FALSE,
4253                                            variable_attr, G_N_ELEMENTS (variable_attr));
4254         emit_dwarf_abbrev (acfg, ABBREV_VARIABLE_LOCLIST, DW_TAG_variable, FALSE,
4255                                            variable_loclist_attr, G_N_ELEMENTS (variable_loclist_attr));
4256         emit_byte (acfg, 0);
4257
4258         emit_section_change (acfg, ".debug_info", 0);
4259         emit_label (acfg, ".Ldebug_info_start");
4260         emit_symbol_diff (acfg, ".Ldebug_info_end", ".", -4); /* length */
4261         emit_int16 (acfg, 0x3); /* DWARF version 3 */
4262         emit_int32 (acfg, 0); /* .debug_abbrev offset */
4263         emit_byte (acfg, sizeof (gpointer)); /* address size */
4264
4265         /* Emit this into a separate section so it gets placed at the end */
4266         emit_section_change (acfg, ".debug_info", 1);
4267         emit_int32 (acfg, 0); /* close everything */
4268         emit_label (acfg, ".Ldebug_info_end");
4269         emit_section_change (acfg, ".debug_info", 0);
4270
4271         /* Compilation unit */
4272         emit_uleb128 (acfg, ABBREV_COMPILE_UNIT);
4273         build_info = mono_get_runtime_build_info ();
4274         s = g_strdup_printf ("Mono AOT Compiler %s", build_info);
4275         emit_string (acfg, s);
4276         g_free (build_info);
4277         g_free (s);
4278         emit_string (acfg, "JITted code");
4279         emit_string (acfg, "");
4280         emit_byte (acfg, DW_LANG_C);
4281         emit_pointer_value (acfg, 0);
4282         emit_pointer_value (acfg, 0);
4283         /* offset into .debug_line section */
4284         emit_symbol_diff (acfg, ".Ldebug_line_start", ".Ldebug_line_section_start", 0);
4285
4286         /* Base types */
4287         for (i = 0; i < G_N_ELEMENTS (basic_types); ++i) {
4288                 emit_label (acfg, basic_types [i].die_name);
4289                 emit_uleb128 (acfg, ABBREV_BASE_TYPE);
4290                 emit_byte (acfg, basic_types [i].size);
4291                 emit_byte (acfg, basic_types [i].encoding);
4292                 emit_string (acfg, basic_types [i].name);
4293         }
4294
4295         /* debug_loc section */
4296         emit_section_change (acfg, ".debug_loc", 0);
4297         emit_label (acfg, ".Ldebug_loc_start");
4298
4299         /* debug_line section */
4300         emit_line_number_info_begin (acfg);
4301
4302         emit_cie (acfg);
4303 }
4304
4305 /* Returns the local symbol pointing to the emitted debug info */
4306 static char*
4307 emit_class_dwarf_info (MonoAotCompile *acfg, MonoClass *klass)
4308 {
4309         char *die;
4310         char *full_name;
4311         gpointer iter;
4312         MonoClassField *field;
4313         const char *fdie;
4314         int k;
4315         gboolean emit_namespace = FALSE;
4316
4317         // FIXME: Appdomains
4318         if (!acfg->class_to_die)
4319                 acfg->class_to_die = g_hash_table_new (NULL, NULL);
4320
4321         die = g_hash_table_lookup (acfg->class_to_die, klass);
4322         if (die)
4323                 return die;
4324
4325         if (!((klass->byval_arg.type == MONO_TYPE_CLASS) || klass->enumtype))
4326                 return NULL;
4327
4328         /*
4329          * FIXME: gdb can't handle namespaces in languages it doesn't know about.
4330          */
4331         /*
4332         if (klass->name_space && klass->name_space [0] != '\0')
4333                 emit_namespace = TRUE;
4334         */
4335         if (emit_namespace) {
4336                 emit_uleb128 (acfg, ABBREV_NAMESPACE);
4337                 emit_string (acfg, klass->name_space);
4338         }
4339
4340         full_name = g_strdup_printf ("%s%s%s", klass->name_space, klass->name_space ? "." : "", klass->name);
4341
4342         die = g_strdup_printf (".LTDIE_%d", acfg->tdie_index);
4343         emit_label (acfg, die);
4344
4345         if (klass->enumtype) {
4346                 int size = mono_class_value_size (mono_class_from_mono_type (mono_class_enum_basetype (klass)), NULL);
4347
4348                 emit_uleb128 (acfg, ABBREV_ENUM_TYPE);
4349                 emit_string (acfg, full_name);
4350                 emit_uleb128 (acfg, size);
4351                 for (k = 0; k < G_N_ELEMENTS (basic_types); ++k)
4352                         if (basic_types [k].type == mono_class_enum_basetype (klass)->type)
4353                                 break;
4354                 g_assert (k < G_N_ELEMENTS (basic_types));
4355                 emit_symbol_diff (acfg, basic_types [k].die_name, ".Ldebug_info_start", 0);
4356
4357                 /* Emit enum values */
4358                 iter = NULL;
4359                 while ((field = mono_class_get_fields (klass, &iter))) {
4360                         const char *p;
4361                         int len;
4362                         MonoTypeEnum def_type;
4363
4364                         if (strcmp ("value__", mono_field_get_name (field)) == 0)
4365                                 continue;
4366                         if (mono_field_is_deleted (field))
4367                                 continue;
4368
4369                         emit_uleb128 (acfg, ABBREV_ENUMERATOR);
4370                         emit_string (acfg, mono_field_get_name (field));
4371
4372                         p = mono_class_get_field_default_value (field, &def_type);
4373                         len = mono_metadata_decode_blob_size (p, &p);
4374                         switch (mono_class_enum_basetype (klass)->type) {
4375                         case MONO_TYPE_U1:
4376                         case MONO_TYPE_I1:
4377                         case MONO_TYPE_BOOLEAN:
4378                                 emit_sleb128 (acfg, *p);
4379                                 break;
4380                         case MONO_TYPE_U2:
4381                         case MONO_TYPE_I2:
4382                         case MONO_TYPE_CHAR:
4383                                 emit_sleb128 (acfg, read16 (p));
4384                                 break;
4385                         case MONO_TYPE_U4:
4386                         case MONO_TYPE_I4:
4387                                 emit_sleb128 (acfg, read32 (p));
4388                                 break;
4389                         case MONO_TYPE_U8:
4390                         case MONO_TYPE_I8:
4391                                 emit_sleb128 (acfg, read64 (p));
4392                                 break;
4393                         case MONO_TYPE_I:
4394                         case MONO_TYPE_U:
4395 #if SIZEOF_VOID_P == 8
4396                                 emit_sleb128 (acfg, read64 (p));
4397 #else
4398                                 emit_sleb128 (acfg, read32 (p));
4399 #endif
4400                                 break;
4401                         default:
4402                                 g_assert_not_reached ();
4403                         }
4404                 }
4405         } else {
4406                 emit_uleb128 (acfg, ABBREV_STRUCT_TYPE);
4407                 emit_string (acfg, full_name);
4408                 emit_uleb128 (acfg, klass->instance_size);
4409
4410                 /* Emit fields */
4411                 iter = NULL;
4412                 while ((field = mono_class_get_fields (klass, &iter))) {
4413                         guint8 buf [128];
4414                         guint8 *p;
4415
4416                         if (field->type->attrs & FIELD_ATTRIBUTE_STATIC)
4417                                 continue;
4418
4419                         for (k = 0; k < G_N_ELEMENTS (basic_types); ++k)
4420                                 if (basic_types [k].type == field->type->type)
4421                                         break;
4422                         if (k < G_N_ELEMENTS (basic_types) && field->type->type != MONO_TYPE_SZARRAY && field->type->type != MONO_TYPE_CLASS) {
4423                                 fdie = basic_types [k].die_name;
4424
4425                                 emit_uleb128 (acfg, ABBREV_DATA_MEMBER);
4426                                 emit_string (acfg, field->name);
4427                                 emit_symbol_diff (acfg, fdie, ".Ldebug_info_start", 0);
4428                                 /* location */
4429                                 p = buf;
4430                                 *p ++= DW_OP_plus_uconst;
4431                                 encode_uleb128 (field->offset, p, &p);
4432
4433                                 emit_byte (acfg, p - buf);
4434                                 emit_bytes (acfg, buf, p - buf);
4435                         }
4436                 }
4437         }
4438
4439         /* Type end */
4440         emit_uleb128 (acfg, 0x0);
4441
4442         /* Add a typedef, so we can reference the type without a 'struct' in gdb */
4443         emit_uleb128 (acfg, ABBREV_TYPEDEF);
4444         emit_string (acfg, full_name);
4445         emit_symbol_diff (acfg, die, ".Ldebug_info_start", 0);
4446
4447         g_free (full_name);
4448         acfg->tdie_index ++;
4449
4450
4451         if (emit_namespace) {
4452                 /* Namespace end */
4453                 emit_uleb128 (acfg, 0x0);
4454         }
4455
4456         g_hash_table_insert (acfg->class_to_die, klass, die);
4457         return die;
4458 }
4459
4460 static void
4461 emit_var_type (MonoAotCompile *acfg, MonoType *t)
4462 {
4463         MonoClass *klass = mono_class_from_mono_type (t);
4464         int j;
4465         const char *tdie;
4466
4467         for (j = 0; j < G_N_ELEMENTS (basic_types); ++j)
4468                 if (basic_types [j].type == t->type)
4469                         break;
4470         if (j < G_N_ELEMENTS (basic_types))
4471                 tdie = basic_types [j].die_name;
4472         else {
4473                 switch (t->type) {
4474                 case MONO_TYPE_CLASS:
4475                 case MONO_TYPE_ARRAY:
4476                         tdie = ".LDIE_OBJECT";
4477                         break;
4478                 case MONO_TYPE_VALUETYPE:
4479                         if (klass->enumtype)
4480                                 tdie = emit_class_dwarf_info (acfg, klass);
4481                         else
4482                                 tdie = ".LDIE_I4";
4483                         break;
4484                 default:
4485                         tdie = ".LDIE_I4";
4486                         break;
4487                 }
4488         }
4489         if (t->byref)
4490                 // FIXME:
4491                 tdie = ".LDIE_I4";
4492         emit_symbol_diff (acfg, tdie, ".Ldebug_info_start", 0);
4493 }
4494
4495 static void
4496 encode_var_location (MonoAotCompile *acfg, MonoInst *ins, guint8 *p, guint8 **endp)
4497 {
4498         /* location */
4499         /* FIXME: This needs a location list, since the args can go from reg->stack */
4500         if (!ins || ins->flags & MONO_INST_IS_DEAD) {
4501                 /* gdb treats this as optimized out */
4502         } else if (ins->opcode == OP_REGVAR) {
4503                 *p = DW_OP_reg0 + mono_hw_reg_to_dwarf_reg (ins->dreg);
4504                 p ++;
4505         } else if (ins->opcode == OP_REGOFFSET) {
4506                 *p ++= DW_OP_breg0 + mono_hw_reg_to_dwarf_reg (ins->inst_basereg);
4507                 encode_sleb128 (ins->inst_offset, p, &p);
4508         } else {
4509                 // FIXME:
4510                 *p ++ = DW_OP_reg0;
4511         }
4512
4513         *endp = p;
4514 }
4515
4516 static void
4517 emit_loclist (MonoAotCompile *acfg, MonoInst *ins,
4518                           guint8 *loclist_begin_addr, guint8 *loclist_end_addr,
4519                           guint8 *expr, guint32 expr_len)
4520 {
4521         char label [128];
4522
4523         emit_push_section (acfg, ".debug_loc", 0);
4524         sprintf (label, ".Lloclist_%d", acfg->loclist_index ++ );
4525         emit_label (acfg, label);
4526
4527         emit_pointer_value (acfg, loclist_begin_addr);
4528         emit_pointer_value (acfg, loclist_end_addr);
4529         emit_byte (acfg, expr_len % 256);
4530         emit_byte (acfg, expr_len / 256);
4531         emit_bytes (acfg, expr, expr_len);
4532
4533         emit_pointer_value (acfg, NULL);
4534         emit_pointer_value (acfg, NULL);
4535
4536         emit_pop_section (acfg);
4537         emit_symbol_diff (acfg, label, ".Ldebug_loc_start", 0);
4538 }
4539
4540 /* 
4541  * MonoDisHelper->tokener doesn't take an IP argument, and we can't add one since 
4542  * it is a public header.
4543  */
4544 static const guint8 *token_handler_ip;
4545
4546 static char*
4547 token_handler (MonoDisHelper *dh, MonoMethod *method, guint32 token)
4548 {
4549         char *res, *desc;
4550
4551         if (method->wrapper_type) {
4552                 gpointer data = mono_method_get_wrapper_data (method, token);
4553
4554                 switch (*token_handler_ip) {
4555                 case CEE_ISINST:
4556                 case CEE_LDELEMA:
4557                         res = g_strdup_printf ("<%s>", ((MonoClass*)data)->name);
4558                         break;
4559                 case CEE_NEWOBJ:
4560                 case CEE_CALL:
4561                         desc = mono_method_full_name (data, TRUE);
4562                         res = g_strdup_printf ("<%s>", desc);
4563                         g_free (desc);
4564                         break;
4565                 case CEE_CALLI:
4566                         desc = mono_signature_get_desc (data, FALSE);
4567                         res = g_strdup_printf ("<%s>", desc);
4568                         g_free (desc);
4569                         break;
4570                 default:
4571                         res = g_strdup_printf ("<%p>", data);
4572                 }
4573         } else {
4574                 res = g_strdup_printf ("<0x%08x>", token);
4575         }
4576
4577         return res;
4578 }
4579
4580 /*
4581  * disasm_ins:
4582  *
4583  *   Produce a disassembled form of the IL instruction at IP. This is an extension
4584  * of mono_disasm_code_one () which can disasm tokens, handle wrapper methods, and
4585  * CEE_MONO_ opcodes.
4586  */
4587 static char*
4588 disasm_ins (MonoMethod *method, const guchar *ip, const guint8 **endip)
4589 {
4590         char *dis;
4591         MonoDisHelper dh;
4592         MonoMethodHeader *header = mono_method_get_header (method);
4593
4594         memset (&dh, 0, sizeof (dh));
4595         dh.newline = "";
4596         dh.label_format = "IL_%04x: ";
4597         dh.label_target = "IL_%04x";
4598         dh.tokener = token_handler;
4599
4600         token_handler_ip = ip;
4601         if (*ip == MONO_CUSTOM_PREFIX) {
4602                 guint32 token;
4603                 gpointer data;
4604
4605                 switch (ip [1]) {
4606                 case CEE_MONO_ICALL: {
4607                         MonoJitICallInfo *info;
4608
4609                         token = read32 (ip + 2);
4610                         data = mono_method_get_wrapper_data (method, token);
4611                         info = mono_find_jit_icall_by_addr (data);
4612                         g_assert (info);
4613
4614                         dis = g_strdup_printf ("IL_%04x: mono_icall <%s>", (int)(ip - header->code), info->name);
4615                         ip += 6;
4616                         break;
4617                 }
4618                 case CEE_MONO_CLASSCONST: {
4619                         token = read32 (ip + 2);
4620                         data = mono_method_get_wrapper_data (method, token);
4621
4622                         dis = g_strdup_printf ("IL_%04x: mono_classconst <%s>", (int)(ip - header->code), ((MonoClass*)data)->name);
4623                         ip += 6;
4624                         break;
4625                 }
4626                 default:
4627                         dis = mono_disasm_code_one (&dh, method, ip, &ip);
4628                 }
4629         } else {
4630                 dis = mono_disasm_code_one (&dh, method, ip, &ip);
4631         }
4632         token_handler_ip = NULL;
4633
4634         *endip = ip;
4635         return dis;
4636 }
4637
4638 static gint32
4639 il_offset_from_address (MonoMethod *method, MonoDebugMethodJitInfo *jit, 
4640                                                 guint32 native_offset)
4641 {
4642         int i;
4643
4644         if (!jit->line_numbers)
4645                 return -1;
4646
4647         for (i = jit->num_line_numbers - 1; i >= 0; i--) {
4648                 MonoDebugLineNumberEntry lne = jit->line_numbers [i];
4649
4650                 if (lne.native_offset <= native_offset)
4651                         return lne.il_offset;
4652         }
4653
4654         return -1;
4655 }
4656
4657 static int max_special_addr_diff = 0;
4658
4659 static inline void
4660 emit_advance_op (MonoAotCompile *acfg, int line_diff, int addr_diff)
4661 {
4662         gint64 opcode = 0;
4663
4664         /* Use a special opcode if possible */
4665         if (line_diff - LINE_BASE >= 0 && line_diff - LINE_BASE < LINE_RANGE) {
4666                 if (max_special_addr_diff == 0)
4667                         max_special_addr_diff = (255 - OPCODE_BASE) / LINE_RANGE;
4668
4669                 if (addr_diff > max_special_addr_diff && (addr_diff < 2 * max_special_addr_diff)) {
4670                         emit_byte (acfg, DW_LNS_const_add_pc);
4671                         addr_diff -= max_special_addr_diff;
4672                 }
4673
4674                 opcode = (line_diff - LINE_BASE) + (LINE_RANGE * addr_diff) + OPCODE_BASE;
4675                 if (opcode > 255)
4676                         opcode = 0;
4677         }
4678
4679         if (opcode != 0) {
4680                 emit_byte (acfg, opcode);
4681         } else {
4682                 emit_byte (acfg, DW_LNS_advance_line);
4683                 emit_sleb128 (acfg, line_diff);
4684                 emit_byte (acfg, DW_LNS_advance_pc);
4685                 emit_sleb128 (acfg, addr_diff);
4686                 emit_byte (acfg, DW_LNS_copy);
4687         }
4688 }
4689
4690 static void
4691 emit_line_number_info (MonoAotCompile *acfg, MonoMethod *method, guint8 *code,
4692                                            guint32 code_size, MonoDebugMethodJitInfo *debug_info)
4693 {
4694         guint32 prev_line = 0;
4695         guint32 prev_native_offset = 0;
4696         int i, file_index, il_offset, prev_il_offset;
4697         gboolean first = TRUE;
4698         MonoDebugSourceLocation *loc;
4699         char *prev_file_name = NULL;
4700         MonoMethodHeader *header = mono_method_get_header (method);
4701         MonoDebugMethodInfo *minfo;
4702
4703         if (acfg->image)
4704                 // FIXME: The set_address op below only works with xdebug
4705                 return;
4706
4707         minfo = mono_debug_lookup_method (method);
4708
4709         /* FIXME: Avoid quadratic behavior */
4710
4711         prev_line = 1;
4712         prev_il_offset = -1;
4713
4714         for (i = 0; i < code_size; ++i) {
4715                 if (!minfo)
4716                         continue;
4717
4718                 if (!debug_info->line_numbers)
4719                         continue;
4720
4721                 /* 
4722                  * FIXME: Its hard to optimize this, since the line number info is not
4723                  * sorted by il offset or native offset
4724                  */
4725                 il_offset = il_offset_from_address (method, debug_info, i);
4726
4727                 if (il_offset < 0)
4728                         continue;
4729
4730                 if (il_offset == prev_il_offset)
4731                         continue;
4732
4733                 prev_il_offset = il_offset;
4734
4735                 loc = mono_debug_symfile_lookup_location (minfo, il_offset);
4736
4737                 if (loc) {
4738                         int line_diff = (gint32)loc->row - (gint32)prev_line;
4739                         int addr_diff = i - prev_native_offset;
4740
4741                         if (first) {    
4742                                 emit_section_change (acfg, ".debug_line", LINE_SUBSECTION_DATA);
4743
4744                                 emit_byte (acfg, 0);
4745                                 emit_byte (acfg, sizeof (gpointer) + 1);
4746                                 emit_byte (acfg, DW_LNE_set_address);
4747                                 emit_pointer_value (acfg, code);
4748
4749                                 /* 
4750                                  * The prolog+initlocals region does not have a line number, this
4751                                  * makes them belong to the first line of the method.
4752                                  */
4753                                 emit_byte (acfg, DW_LNS_advance_line);
4754                                 emit_sleb128 (acfg, (gint32)loc->row - (gint32)prev_line);
4755                                 prev_line = loc->row;
4756                         }
4757
4758                         if (loc->row != prev_line) {
4759                                 if (!prev_file_name || strcmp (loc->source_file, prev_file_name) != 0) {
4760                                         /* Add an entry to the file table */
4761                                         /* FIXME: Avoid duplicates */
4762                                         file_index = emit_line_number_file_name (acfg, loc->source_file, 0, 0);
4763                                         g_free (prev_file_name);
4764                                         prev_file_name = g_strdup (loc->source_file);
4765
4766                                         emit_byte (acfg, DW_LNS_set_file);
4767                                         emit_uleb128 (acfg, file_index);
4768                                         emit_byte (acfg, DW_LNS_copy);
4769                                 }
4770
4771                                 //printf ("X: %p(+0x%x) %d %s:%d(+%d)\n", code + i, addr_diff, loc->il_offset, loc->source_file, loc->row, line_diff);
4772
4773                                 emit_advance_op (acfg, line_diff, addr_diff);
4774
4775                                 prev_line = loc->row;
4776                                 prev_native_offset = i;
4777                         }
4778
4779                         first = FALSE;
4780                         g_free (loc);
4781                 }
4782         }
4783
4784         g_free (prev_file_name);
4785
4786         if (!first) {
4787                 emit_byte (acfg, DW_LNS_advance_pc);
4788                 emit_sleb128 (acfg, code_size - prev_native_offset);
4789                 emit_byte (acfg, DW_LNS_copy);
4790
4791                 emit_byte (acfg, 0);
4792                 emit_byte (acfg, 1);
4793                 emit_byte (acfg, DW_LNE_end_sequence);
4794         } else if (!acfg->image) {
4795                 /* No debug info, XDEBUG mode */
4796                 char *name, *dis;
4797                 const guint8 *ip = header->code;
4798                 int prev_line, prev_native_offset;
4799                 int *il_to_line;
4800
4801                 /*
4802                  * Emit the IL code into a temporary file and emit line number info
4803                  * referencing that file.
4804                  */
4805
4806                 name = mono_method_full_name (method, TRUE);
4807                 fprintf (acfg->il_file, "// %s\n", name);
4808                 acfg->il_file_line_index ++;
4809                 g_free (name);
4810
4811                 il_to_line = g_new0 (int, header->code_size);
4812
4813                 emit_section_change (acfg, ".debug_line", LINE_SUBSECTION_DATA);
4814                 emit_byte (acfg, 0);
4815                 emit_byte (acfg, sizeof (gpointer) + 1);
4816                 emit_byte (acfg, DW_LNE_set_address);
4817                 emit_pointer_value (acfg, code);
4818
4819                 // FIXME: Optimize this
4820                 while (ip < header->code + header->code_size) {
4821                         int il_offset = ip - header->code;
4822
4823                         /* Emit IL */
4824                         acfg->il_file_line_index ++;
4825
4826                         dis = disasm_ins (method, ip, &ip);
4827                         fprintf (acfg->il_file, "%s\n", dis);
4828                         g_free (dis);
4829
4830                         il_to_line [il_offset] = acfg->il_file_line_index;
4831                 }
4832
4833                 /* Emit line number info */
4834                 prev_line = 0;
4835                 prev_native_offset = 0;
4836                 for (i = 0; i < debug_info->num_line_numbers; ++i) {
4837                         MonoDebugLineNumberEntry *lne = &debug_info->line_numbers [i];
4838                         int line;
4839
4840                         if (lne->il_offset >= header->code_size)
4841                                 continue;
4842                         line = il_to_line [lne->il_offset];
4843                         g_assert (line);
4844
4845                         if (line - prev_line != 0) {
4846                                 emit_advance_op (acfg, line - prev_line, (gint32)lne->native_offset - prev_native_offset);
4847
4848                                 prev_line = line;
4849                                 prev_native_offset = lne->native_offset;
4850                         }
4851                 }
4852
4853                 emit_byte (acfg, DW_LNS_advance_pc);
4854                 emit_sleb128 (acfg, code_size - prev_native_offset);
4855                 emit_byte (acfg, DW_LNS_copy);
4856
4857                 emit_byte (acfg, 0);
4858                 emit_byte (acfg, 1);
4859                 emit_byte (acfg, DW_LNE_end_sequence);
4860
4861                 fflush (acfg->il_file);
4862                 g_free (il_to_line);
4863         }
4864 }
4865
4866 static void
4867 emit_method_dwarf_info (MonoAotCompile *acfg, MonoCompile *cfg, MonoMethod *method, char *start_symbol, char *end_symbol, guint8 *code, guint32 code_size, MonoInst **args, MonoInst **locals, GSList *unwind_info, MonoDebugMethodJitInfo *debug_info)
4868 {
4869         char *name;
4870         MonoMethodSignature *sig;
4871         MonoMethodHeader *header;
4872         char **names, **tdies, **local_tdies;
4873         char **local_names;
4874         int *local_indexes;
4875         int i, num_locals;
4876         guint8 buf [128];
4877         guint8 *p;
4878
4879         emit_section_change (acfg, ".debug_info", 0);
4880
4881         sig = mono_method_signature (method);
4882         header = mono_method_get_header (method);
4883
4884         /* Parameter types */
4885         tdies = g_new0 (char *, sig->param_count + sig->hasthis);
4886         for (i = 0; i < sig->param_count + sig->hasthis; ++i) {
4887                 MonoType *t;
4888
4889                 if (i == 0 && sig->hasthis) {
4890                         t = &method->klass->this_arg;
4891                 } else {
4892                         t = sig->params [i - sig->hasthis];
4893                 }
4894
4895                 emit_class_dwarf_info (acfg, mono_class_from_mono_type (t));
4896         }
4897
4898         /* Local types */
4899         local_tdies = g_new0 (char *, header->num_locals);
4900         for (i = 0; i < header->num_locals; ++i) {
4901                 emit_class_dwarf_info (acfg, mono_class_from_mono_type (header->locals [i]));
4902         }
4903
4904         /* Subprogram */
4905         names = g_new0 (char *, sig->param_count);
4906         mono_method_get_param_names (method, (const char **) names);
4907
4908         emit_uleb128 (acfg, ABBREV_SUBPROGRAM);
4909         name = mono_method_full_name (method, FALSE);
4910         emit_string (acfg, name);
4911         g_free (name);
4912         if (start_symbol) {
4913                 emit_pointer_unaligned (acfg, start_symbol);
4914                 emit_pointer_unaligned (acfg, end_symbol);
4915         } else {
4916                 emit_pointer_value (acfg, code);
4917                 emit_pointer_value (acfg, code + code_size);
4918         }
4919         /* frame_base */
4920         emit_byte (acfg, 2);
4921         emit_byte (acfg, DW_OP_breg6);
4922         emit_byte (acfg, 16);
4923
4924         /* Parameters */
4925         for (i = 0; i < sig->param_count + sig->hasthis; ++i) {
4926                 MonoInst *arg = args ? args [i] : NULL;
4927                 MonoType *t;
4928                 const char *pname;
4929                 char pname_buf [128];
4930
4931                 if (i == 0 && sig->hasthis) {
4932                         t = &mono_defaults.object_class->byval_arg;
4933                         pname = "this";
4934                 } else {
4935                         t = sig->params [i - sig->hasthis];
4936                         pname = names [i - sig->hasthis];
4937                 }
4938                 
4939                 emit_uleb128 (acfg, ABBREV_PARAM);
4940                 /* name */
4941                 if (pname[0] == '\0') {
4942                         sprintf (pname_buf, "param%d", i - sig->hasthis);
4943                         pname = pname_buf;
4944                 }
4945                 emit_string (acfg, pname);
4946                 /* type */
4947                 if (!arg || arg->flags & MONO_INST_IS_DEAD)
4948                         emit_var_type (acfg, &mono_defaults.int32_class->byval_arg);
4949                 else
4950                         emit_var_type (acfg, t);
4951
4952                 p = buf;
4953                 encode_var_location (acfg, arg, p, &p);
4954                 emit_byte (acfg, p - buf);
4955                 emit_bytes (acfg, buf, p - buf);
4956         }               
4957         g_free (names);
4958
4959         /* Locals */
4960         num_locals = mono_debug_lookup_locals (method, &local_names, &local_indexes);
4961
4962         for (i = 0; i < header->num_locals; ++i) {
4963                 MonoInst *ins = locals [i];
4964                 char name_buf [128];
4965                 int j;
4966                 MonoMethodVar *vmv = NULL;
4967                 gboolean need_loclist = FALSE;
4968
4969                 /* ins->dreg no longer contains the original vreg */
4970                 if (cfg->varinfo) {
4971                         for (j = 0; j < cfg->num_varinfo; ++j) {
4972                                 if (cfg->varinfo [j] == ins)
4973                                         break;
4974                         }
4975
4976                         if (code && j < cfg->num_varinfo) {
4977                                 vmv = MONO_VARINFO (cfg, j);
4978                                 if (vmv->live_range_start) {
4979                                         /* This variable has a precise live range */
4980                                         need_loclist = TRUE;
4981                                 }
4982                         }
4983                 }
4984
4985                 if (need_loclist)
4986                         emit_uleb128 (acfg, ABBREV_VARIABLE_LOCLIST);
4987                 else
4988                         emit_uleb128 (acfg, ABBREV_VARIABLE);
4989                 /* name */
4990                 for (j = 0; j < num_locals; ++j)
4991                         if (local_indexes [j] == i)
4992                                 break;
4993                 if (j < num_locals) {
4994                         emit_string (acfg, local_names [j]);
4995                 } else {
4996                         sprintf (name_buf, "V_%d", i);
4997                         emit_string (acfg, name_buf);
4998                 }
4999                 /* type */
5000                 if (!ins || ins->flags & MONO_INST_IS_DEAD)
5001                         emit_var_type (acfg, &mono_defaults.int32_class->byval_arg);
5002                 else
5003                         emit_var_type (acfg, header->locals [i]);
5004
5005                 p = buf;
5006                 encode_var_location (acfg, ins, p, &p);
5007
5008                 if (need_loclist) {
5009                         if (vmv->live_range_end == 0)
5010                                 /* FIXME: Uses made in calls are not recorded */
5011                                 vmv->live_range_end = code_size;
5012                         emit_loclist (acfg, ins, code + vmv->live_range_start, code + vmv->live_range_end, buf, p - buf);
5013                 } else {
5014                         emit_byte (acfg, p - buf);
5015                         emit_bytes (acfg, buf, p - buf);
5016                 }
5017         }
5018
5019         g_free (local_names);
5020         g_free (local_indexes);
5021
5022         /* Subprogram end */
5023         emit_uleb128 (acfg, 0x0);
5024
5025         emit_line (acfg);
5026
5027         /* Emit unwind info */
5028         emit_fde (acfg, acfg->fde_index, start_symbol, end_symbol, code, code_size, unwind_info, TRUE);
5029         acfg->fde_index ++;
5030
5031         /* Emit line number info */
5032         if (code && debug_info)
5033                 emit_line_number_info (acfg, method, code, code_size, debug_info);
5034
5035         emit_line (acfg);
5036 }
5037
5038 static void
5039 emit_trampoline_dwarf_info (MonoAotCompile *acfg, const char *tramp_name, char *start_symbol, char *end_symbol, guint8 *code, guint32 code_size, GSList *unwind_info)
5040 {
5041         emit_section_change (acfg, ".debug_info", 0);
5042
5043         /* Subprogram */
5044         emit_uleb128 (acfg, ABBREV_SUBPROGRAM);
5045         emit_string (acfg, tramp_name);
5046         emit_pointer_value (acfg, code);
5047         emit_pointer_value (acfg, code + code_size);
5048         /* frame_base */
5049         emit_byte (acfg, 2);
5050         emit_byte (acfg, DW_OP_breg6);
5051         emit_byte (acfg, 16);
5052
5053         /* Subprogram end */
5054         emit_uleb128 (acfg, 0x0);
5055
5056         /* Emit unwind info */
5057         emit_fde (acfg, acfg->fde_index, start_symbol, end_symbol, code, code_size, unwind_info, FALSE);
5058         acfg->fde_index ++;
5059 }
5060
5061 static void
5062 emit_dwarf_info (MonoAotCompile *acfg)
5063 {
5064 #ifdef EMIT_DWARF_INFO
5065         int i;
5066         char symbol [128], symbol2 [128];
5067
5068         /* DIEs for methods */
5069         for (i = 0; i < acfg->nmethods; ++i) {
5070                 MonoCompile *cfg = acfg->cfgs [i];
5071
5072                 if (!cfg)
5073                         continue;
5074
5075                 sprintf (symbol, ".Lm_%x", i);
5076                 sprintf (symbol2, ".Lme_%x", i);
5077
5078                 emit_method_dwarf_info (acfg, cfg, cfg->method, symbol, symbol2, NULL, 0, cfg->args, cfg->locals, cfg->unwind_ops, NULL);
5079         }
5080 #endif
5081 }
5082
5083 static int
5084 compile_asm (MonoAotCompile *acfg)
5085 {
5086         char *command, *objfile;
5087         char *outfile_name, *tmp_outfile_name;
5088
5089 #if defined(__x86_64__)
5090 #define AS_OPTIONS "--64"
5091 #elif defined(sparc) && SIZEOF_VOID_P == 8
5092 #define AS_OPTIONS "-xarch=v9"
5093 #else
5094 #define AS_OPTIONS ""
5095 #endif
5096
5097         if (acfg->aot_opts.asm_only) {
5098                 printf ("Output file: '%s'.\n", acfg->tmpfname);
5099                 if (acfg->aot_opts.static_link)
5100                         printf ("Linking symbol: '%s'.\n", acfg->static_linking_symbol);
5101                 return 0;
5102         }
5103
5104         if (acfg->aot_opts.static_link) {
5105                 if (acfg->aot_opts.outfile)
5106                         objfile = g_strdup_printf ("%s", acfg->aot_opts.outfile);
5107                 else
5108                         objfile = g_strdup_printf ("%s.o", acfg->image->name);
5109         } else {
5110                 objfile = g_strdup_printf ("%s.o", acfg->tmpfname);
5111         }
5112         command = g_strdup_printf ("as %s %s -o %s", AS_OPTIONS, acfg->tmpfname, objfile);
5113         printf ("Executing the native assembler: %s\n", command);
5114         if (system (command) != 0) {
5115                 g_free (command);
5116                 g_free (objfile);
5117                 return 1;
5118         }
5119
5120         g_free (command);
5121
5122         if (acfg->aot_opts.static_link) {
5123                 printf ("Output file: '%s'.\n", objfile);
5124                 printf ("Linking symbol: '%s'.\n", acfg->static_linking_symbol);
5125                 g_free (objfile);
5126                 return 0;
5127         }
5128
5129         if (acfg->aot_opts.outfile)
5130                 outfile_name = g_strdup_printf ("%s", acfg->aot_opts.outfile);
5131         else
5132                 outfile_name = g_strdup_printf ("%s%s", acfg->image->name, SHARED_EXT);
5133
5134         tmp_outfile_name = g_strdup_printf ("%s.tmp", outfile_name);
5135
5136 #if defined(sparc)
5137         command = g_strdup_printf ("ld -shared -G -o %s %s.o", outfile_name, acfg->tmpfname);
5138 #elif defined(__ppc__) && defined(__MACH__)
5139         command = g_strdup_printf ("gcc -dynamiclib -o %s %s.o", outfile_name, acfg->tmpfname);
5140 #elif defined(PLATFORM_WIN32)
5141         command = g_strdup_printf ("gcc -shared --dll -mno-cygwin -o %s %s.o", outfile_name, acfg->tmpfname);
5142 #else
5143         if (acfg->aot_opts.no_dlsym) {
5144                 /* 
5145                  * Need to link using gcc so our ctor function gets called.
5146                  */
5147                 command = g_strdup_printf ("gcc -shared -o %s %s.o", outfile_name, acfg->tmpfname);
5148         } else {
5149                 command = g_strdup_printf ("ld -shared -o %s %s.o", outfile_name, acfg->tmpfname);
5150         }
5151 #endif
5152         printf ("Executing the native linker: %s\n", command);
5153         if (system (command) != 0) {
5154                 g_free (tmp_outfile_name);
5155                 g_free (outfile_name);
5156                 g_free (command);
5157                 g_free (objfile);
5158                 return 1;
5159         }
5160
5161         g_free (command);
5162         unlink (objfile);
5163         /*com = g_strdup_printf ("strip --strip-unneeded %s%s", acfg->image->name, SHARED_EXT);
5164         printf ("Stripping the binary: %s\n", com);
5165         system (com);
5166         g_free (com);*/
5167
5168         rename (tmp_outfile_name, outfile_name);
5169
5170         g_free (tmp_outfile_name);
5171         g_free (outfile_name);
5172         g_free (objfile);
5173
5174         if (acfg->aot_opts.save_temps)
5175                 printf ("Retained input file.\n");
5176         else
5177                 unlink (acfg->tmpfname);
5178
5179         return 0;
5180 }
5181
5182 static void
5183 acfg_free (MonoAotCompile *acfg)
5184 {
5185         int i;
5186
5187         img_writer_destroy (acfg->w);
5188         for (i = 0; i < acfg->nmethods; ++i)
5189                 if (acfg->cfgs [i])
5190                         g_free (acfg->cfgs [i]);
5191         g_free (acfg->cfgs);
5192         g_free (acfg->static_linking_symbol);
5193         g_ptr_array_free (acfg->methods, TRUE);
5194         g_ptr_array_free (acfg->shared_patches, TRUE);
5195         g_ptr_array_free (acfg->image_table, TRUE);
5196         g_ptr_array_free (acfg->globals, TRUE);
5197         g_hash_table_destroy (acfg->method_indexes);
5198         g_hash_table_destroy (acfg->plt_offset_to_patch);
5199         g_hash_table_destroy (acfg->patch_to_plt_offset);
5200         g_hash_table_destroy (acfg->patch_to_shared_got_offset);
5201         g_hash_table_destroy (acfg->method_to_cfg);
5202         g_hash_table_destroy (acfg->token_info_hash);
5203         g_hash_table_destroy (acfg->image_hash);
5204         mono_mempool_destroy (acfg->mempool);
5205         g_free (acfg);
5206 }
5207
5208 int
5209 mono_compile_assembly (MonoAssembly *ass, guint32 opts, const char *aot_options)
5210 {
5211         MonoImage *image = ass->image;
5212         char symbol [256];
5213         int i, res, methods_len;
5214         MonoAotCompile *acfg;
5215         char *outfile_name, *tmp_outfile_name;
5216         TV_DECLARE (atv);
5217         TV_DECLARE (btv);
5218
5219         printf ("Mono Ahead of Time compiler - compiling assembly %s\n", image->name);
5220
5221         acfg = g_new0 (MonoAotCompile, 1);
5222         acfg->methods = g_ptr_array_new ();
5223         acfg->method_indexes = g_hash_table_new (NULL, NULL);
5224         acfg->plt_offset_to_patch = g_hash_table_new (NULL, NULL);
5225         acfg->patch_to_plt_offset = g_hash_table_new (mono_patch_info_hash, mono_patch_info_equal);
5226         acfg->patch_to_shared_got_offset = g_hash_table_new (mono_patch_info_hash, mono_patch_info_equal);
5227         acfg->shared_patches = g_ptr_array_new ();
5228         acfg->method_to_cfg = g_hash_table_new (NULL, NULL);
5229         acfg->token_info_hash = g_hash_table_new_full (NULL, NULL, NULL, g_free);
5230         acfg->image_hash = g_hash_table_new (NULL, NULL);
5231         acfg->image_table = g_ptr_array_new ();
5232         acfg->globals = g_ptr_array_new ();
5233         acfg->image = image;
5234         acfg->opts = opts;
5235         acfg->mempool = mono_mempool_new ();
5236         acfg->extra_methods = g_ptr_array_new ();
5237         InitializeCriticalSection (&acfg->mutex);
5238
5239         memset (&acfg->aot_opts, 0, sizeof (acfg->aot_opts));
5240         acfg->aot_opts.write_symbols = TRUE;
5241
5242         mono_aot_parse_options (aot_options, &acfg->aot_opts);
5243
5244         //acfg->aot_opts.print_skipped_methods = TRUE;
5245
5246         if (!acfg->aot_opts.asm_only && !acfg->aot_opts.asm_writer && bin_writer_supported ()) {
5247                 if (acfg->aot_opts.outfile)
5248                         outfile_name = g_strdup_printf ("%s", acfg->aot_opts.outfile);
5249                 else
5250                         outfile_name = g_strdup_printf ("%s%s", acfg->image->name, SHARED_EXT);
5251
5252                 tmp_outfile_name = g_strdup_printf ("%s.tmp", outfile_name);
5253
5254                 acfg->fp = fopen (tmp_outfile_name, "w");
5255                 g_assert (acfg->fp);
5256
5257                 acfg->w = img_writer_create (acfg->fp, TRUE);
5258                 acfg->use_bin_writer = TRUE;
5259         } else {
5260                 if (acfg->aot_opts.asm_only) {
5261                         if (acfg->aot_opts.outfile)
5262                                 acfg->tmpfname = g_strdup_printf ("%s", acfg->aot_opts.outfile);
5263                         else
5264                                 acfg->tmpfname = g_strdup_printf ("%s.s", acfg->image->name);
5265                         acfg->fp = fopen (acfg->tmpfname, "w+");
5266                 } else {
5267                         int i = g_file_open_tmp ("mono_aot_XXXXXX", &acfg->tmpfname, NULL);
5268                         acfg->fp = fdopen (i, "w+");
5269                 }
5270                 g_assert (acfg->fp);
5271
5272                 acfg->w = img_writer_create (acfg->fp, FALSE);
5273                 
5274                 /* hush compiler warnings about these being possibly uninitialized */
5275                 tmp_outfile_name = NULL;
5276                 outfile_name = NULL;
5277         }
5278
5279         load_profile_files (acfg);
5280
5281         img_writer_emit_start (acfg->w);
5282
5283         acfg->num_aot_trampolines = acfg->aot_opts.full_aot ? 10240 : 0;
5284
5285         acfg->method_index = 1;
5286
5287         /* Collect methods */
5288         for (i = 0; i < image->tables [MONO_TABLE_METHOD].rows; ++i) {
5289                 MonoMethod *method;
5290                 guint32 token = MONO_TOKEN_METHOD_DEF | (i + 1);
5291
5292                 method = mono_get_method (acfg->image, token, NULL);
5293
5294                 if (!method) {
5295                         printf ("Failed to load method 0x%x from '%s'.\n", token, image->name);
5296                         exit (1);
5297                 }
5298                         
5299                 /* Load all methods eagerly to skip the slower lazy loading code */
5300                 mono_class_setup_methods (method->klass);
5301
5302                 if (acfg->aot_opts.full_aot && method->iflags & METHOD_IMPL_ATTRIBUTE_INTERNAL_CALL) {
5303                         /* Compile the wrapper instead */
5304                         /* We do this here instead of add_wrappers () because it is easy to do it here */
5305                         MonoMethod *wrapper = mono_marshal_get_native_wrapper (method, check_for_pending_exc, TRUE);
5306                         method = wrapper;
5307                 }
5308
5309                 /* Since we add the normal methods first, their index will be equal to their zero based token index */
5310                 add_method_with_index (acfg, method, i);
5311                 acfg->method_index ++;
5312         }
5313
5314         add_generic_instances (acfg);
5315
5316         if (acfg->aot_opts.full_aot)
5317                 add_wrappers (acfg);
5318
5319         acfg->cfgs_size = acfg->methods->len + 32;
5320         acfg->cfgs = g_new0 (MonoCompile*, acfg->cfgs_size);
5321
5322         /* PLT offset 0 is reserved for the PLT trampoline */
5323         acfg->plt_offset = 1;
5324
5325         /* Compile methods */
5326         TV_GETTIME (atv);
5327
5328         if (acfg->aot_opts.nthreads > 0) {
5329                 GPtrArray *frag;
5330                 int len, j;
5331                 GPtrArray *threads;
5332                 HANDLE handle;
5333                 gpointer *user_data;
5334                 MonoMethod **methods;
5335
5336                 methods_len = acfg->methods->len;
5337
5338                 len = acfg->methods->len / acfg->aot_opts.nthreads;
5339                 g_assert (len > 0);
5340                 /* 
5341                  * Partition the list of methods into fragments, and hand it to threads to
5342                  * process.
5343                  */
5344                 threads = g_ptr_array_new ();
5345                 /* Make a copy since acfg->methods is modified by compile_method () */
5346                 methods = g_new0 (MonoMethod*, methods_len);
5347                 //memcpy (methods, g_ptr_array_index (acfg->methods, 0), sizeof (MonoMethod*) * methods_len);
5348                 for (i = 0; i < methods_len; ++i)
5349                         methods [i] = g_ptr_array_index (acfg->methods, i);
5350                 i = 0;
5351                 while (i < methods_len) {
5352                         frag = g_ptr_array_new ();
5353                         for (j = 0; j < len; ++j) {
5354                                 if (i < methods_len) {
5355                                         g_ptr_array_add (frag, methods [i]);
5356                                         i ++;
5357                                 }
5358                         }
5359
5360                         user_data = g_new0 (gpointer, 3);
5361                         user_data [0] = mono_domain_get ();
5362                         user_data [1] = acfg;
5363                         user_data [2] = frag;
5364                         
5365                         handle = CreateThread (NULL, 0, (gpointer)compile_thread_main, user_data, 0, NULL);
5366                         g_ptr_array_add (threads, handle);
5367                 }
5368                 g_free (methods);
5369
5370                 for (i = 0; i < threads->len; ++i) {
5371                         WaitForSingleObjectEx (g_ptr_array_index (threads, i), INFINITE, FALSE);
5372                 }
5373         } else {
5374                 methods_len = 0;
5375         }
5376
5377         /* Compile methods added by compile_method () or all methods if nthreads == 0 */
5378         for (i = methods_len; i < acfg->methods->len; ++i) {
5379                 /* This can new methods to acfg->methods */
5380                 compile_method (acfg, g_ptr_array_index (acfg->methods, i));
5381         }
5382
5383         TV_GETTIME (btv);
5384  
5385         acfg->stats.jit_time = TV_ELAPSED (atv, btv);
5386
5387         TV_GETTIME (atv);
5388
5389         alloc_got_slots (acfg);
5390
5391         emit_base_dwarf_info (acfg);
5392
5393         emit_code (acfg);
5394
5395         emit_info (acfg);
5396
5397         emit_extra_methods (acfg);
5398
5399         emit_method_order (acfg);
5400
5401         emit_trampolines (acfg);
5402
5403         emit_class_name_table (acfg);
5404
5405         emit_got_info (acfg);
5406
5407         emit_exception_info (acfg);
5408
5409         emit_class_info (acfg);
5410
5411         emit_plt (acfg);
5412
5413         emit_image_table (acfg);
5414
5415         emit_got (acfg);
5416
5417         emit_file_info (acfg);
5418
5419         emit_globals (acfg);
5420
5421         emit_dwarf_info (acfg);
5422
5423         sprintf (symbol, "mem_end");
5424         emit_section_change (acfg, ".text", 1);
5425         emit_global (acfg, symbol, FALSE);
5426         emit_alignment (acfg, 8);
5427         emit_label (acfg, symbol);
5428
5429         TV_GETTIME (btv);
5430
5431         acfg->stats.gen_time = TV_ELAPSED (atv, btv);
5432
5433         printf ("Code: %d Info: %d Ex Info: %d Class Info: %d PLT: %d GOT Info: %d GOT Info Offsets: %d GOT: %d\n", acfg->stats.code_size, acfg->stats.info_size, acfg->stats.ex_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)));
5434
5435         TV_GETTIME (atv);
5436         res = img_writer_emit_writeout (acfg->w);
5437         if (res != 0) {
5438                 acfg_free (acfg);
5439                 return res;
5440         }
5441         if (acfg->use_bin_writer) {
5442                 rename (tmp_outfile_name, outfile_name);
5443         } else {
5444                 compile_asm (acfg);
5445                 if (res != 0) {
5446                         acfg_free (acfg);
5447                         return res;
5448                 }
5449         }
5450         TV_GETTIME (btv);
5451         acfg->stats.link_time = TV_ELAPSED (atv, btv);
5452
5453         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);
5454         if (acfg->stats.genericcount)
5455                 printf ("%d methods are generic (%d%%)\n", acfg->stats.genericcount, acfg->stats.mcount ? (acfg->stats.genericcount * 100) / acfg->stats.mcount : 100);
5456         if (acfg->stats.abscount)
5457                 printf ("%d methods contain absolute addresses (%d%%)\n", acfg->stats.abscount, acfg->stats.mcount ? (acfg->stats.abscount * 100) / acfg->stats.mcount : 100);
5458         if (acfg->stats.lmfcount)
5459                 printf ("%d methods contain lmf pointers (%d%%)\n", acfg->stats.lmfcount, acfg->stats.mcount ? (acfg->stats.lmfcount * 100) / acfg->stats.mcount : 100);
5460         if (acfg->stats.ocount)
5461                 printf ("%d methods have other problems (%d%%)\n", acfg->stats.ocount, acfg->stats.mcount ? (acfg->stats.ocount * 100) / acfg->stats.mcount : 100);
5462         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);
5463         printf ("Direct calls: %d (%d%%)\n", acfg->stats.direct_calls, acfg->stats.all_calls ? (acfg->stats.direct_calls * 100) / acfg->stats.all_calls : 100);
5464         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);
5465
5466         printf ("GOT slot distribution:\n");
5467         for (i = 0; i < MONO_PATCH_INFO_NONE; ++i)
5468                 if (acfg->stats.got_slot_types [i])
5469                         printf ("\t%s: %d\n", get_patch_name (i), acfg->stats.got_slot_types [i]);
5470
5471         acfg_free (acfg);
5472         
5473         return 0;
5474 }
5475  
5476 /*
5477  * Support for emitting debug info for JITted code.
5478  *
5479  *   This works as follows:
5480  * - the runtime writes out an xdb.s file containing DWARF debug info.
5481  * - the user calls a gdb macro
5482  * - the macro compiles and loads this shared library using add-symbol-file.
5483  *
5484  * This is based on the xdebug functionality in the Kaffe Java VM.
5485  * 
5486  * We emit assembly code instead of using the ELF writer, so we can emit debug info
5487  * incrementally as each method is JITted, and the debugger doesn't have to call
5488  * into the runtime to emit the shared library, which would cause all kinds of
5489  * complications, like threading issues, and the fact that the ELF writer's
5490  * emit_writeout () function cannot be called more than once.
5491  */
5492
5493 /* The recommended gdb macro is: */
5494 /*
5495   define xdb
5496   shell rm -f xdb.so && as --64 -o xdb.o xdb.s && ld -shared -o xdb.so xdb.o
5497   add-symbol-file xdb.so 0
5498   end
5499 */
5500
5501 static MonoAotCompile *xdebug_acfg;
5502
5503 void
5504 mono_xdebug_init (void)
5505 {
5506         MonoAotCompile *acfg;
5507
5508         acfg = g_new0 (MonoAotCompile, 1);
5509         acfg->mempool = mono_mempool_new ();
5510         InitializeCriticalSection (&acfg->mutex);
5511         acfg->aot_opts.asm_only = TRUE;
5512         acfg->aot_opts.outfile = g_strdup ("xdb.s");
5513
5514         unlink ("xdb.s");
5515         acfg->fp = fopen ("xdb.s", "w");
5516
5517         acfg->w = img_writer_create (acfg->fp, FALSE);
5518
5519         img_writer_emit_start (acfg->w);
5520
5521         xdebug_acfg = acfg;
5522
5523         /* Emit something so the file has a text segment */
5524         emit_section_change (acfg, ".text", 0);
5525         emit_string (acfg, "");
5526
5527         emit_base_dwarf_info (acfg);
5528
5529         /* This file will contain the IL code for methods which don't have debug info */
5530         acfg->il_file = fopen ("xdb.il", "w");
5531 }
5532
5533 /*
5534  * mono_save_xdebug_info:
5535  *
5536  *   Emit debugging info for METHOD into an assembly file which can be assembled
5537  * and loaded into gdb to provide debugging info for JITted code.
5538  */
5539 void
5540 mono_save_xdebug_info (MonoCompile *cfg)
5541 {
5542         MonoAotCompile *acfg;
5543
5544         if (!xdebug_acfg)
5545                 return;
5546         
5547         acfg = xdebug_acfg;
5548
5549         mono_acfg_lock (acfg);
5550         emit_method_dwarf_info (acfg, 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 ()));
5551         fflush (acfg->fp);
5552         mono_acfg_unlock (acfg);
5553 }
5554
5555 /*
5556  * mono_save_trampoline_xdebug_info:
5557  *
5558  *   Same as mono_save_xdebug_info, but for trampolines.
5559  */
5560 void
5561 mono_save_trampoline_xdebug_info (const char *tramp_name, guint8 *code, guint32 code_size, GSList *unwind_info)
5562 {
5563         MonoAotCompile *acfg;
5564
5565         if (!xdebug_acfg)
5566                 return;
5567
5568         acfg = xdebug_acfg;
5569
5570         mono_acfg_lock (acfg);
5571         emit_trampoline_dwarf_info (acfg, tramp_name, NULL, NULL, code, code_size, unwind_info);
5572         fflush (acfg->fp);
5573         mono_acfg_unlock (acfg);
5574 }
5575
5576 #else
5577
5578 /* AOT disabled */
5579
5580 int
5581 mono_compile_assembly (MonoAssembly *ass, guint32 opts, const char *aot_options)
5582 {
5583         return 0;
5584 }
5585
5586 void
5587 mono_xdebug_init (void)
5588 {
5589 }
5590
5591 void
5592 mono_save_xdebug_info (MonoCompile *cfg)
5593 {
5594 }
5595
5596 void
5597 mono_save_trampoline_xdebug_info (const char *tramp_name, guint8 *code, guint32 code_size, GSList *unwind_info)
5598 {
5599 }
5600
5601 #endif