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