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