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