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