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