2009-05-14 Zoltan Varga <vargaz@gmail.com>
[mono.git] / mono / mini / aot-compiler.c
index 59d6e771f6604cf7556238e81a9804a1f78cfe79..d3918ad382477675cdf3dd84a7fcc5c9137a7277 100644 (file)
@@ -1,5 +1,5 @@
 /*
- * aot.c: mono Ahead of Time compiler
+ * aot-compiler.c: mono Ahead of Time compiler
  *
  * Author:
  *   Dietmar Maurer (dietmar@ximian.com)
 #ifdef HAVE_UNISTD_H
 #include <unistd.h>
 #endif
+#ifdef HAVE_STDINT_H
+#include <stdint.h>
+#endif
 #include <fcntl.h>
 #include <ctype.h>
 #include <string.h>
 #ifndef PLATFORM_WIN32
-#include <sys/mman.h>
 #include <sys/time.h>
 #else
 #include <winsock2.h>
 
 #include <errno.h>
 #include <sys/stat.h>
-#include <limits.h>    /* for PAGESIZE */
-#ifndef PAGESIZE
-#define PAGESIZE 4096
-#endif
 
 #include <mono/metadata/tabledefs.h>
 #include <mono/metadata/class.h>
 #include <mono/metadata/metadata-internals.h>
 #include <mono/metadata/marshal.h>
 #include <mono/metadata/gc-internal.h>
-#include <mono/metadata/method-builder.h>
 #include <mono/metadata/monitor.h>
+#include <mono/metadata/mempool-internals.h>
+#include <mono/metadata/mono-endian.h>
+#include <mono/metadata/threads-types.h>
 #include <mono/utils/mono-logger.h>
 #include <mono/utils/mono-compiler.h>
 #include <mono/utils/mono-time.h>
-
-#ifndef PLATFORM_WIN32
-#include <mono/utils/freebsd-elf32.h>
-#include <mono/utils/freebsd-elf64.h>
-#endif
+#include <mono/utils/mono-mmap.h>
 
 #include "mini.h"
-#include "version.h"
+#include "image-writer.h"
+#include "dwarfwriter.h"
 
-#ifndef DISABLE_AOT
+#if !defined(DISABLE_AOT) && !defined(DISABLE_JIT)
 
 #define TV_DECLARE(name) gint64 name
 #define TV_GETTIME(tv) tv = mono_100ns_ticks ()
 #define SHARED_EXT ".so"
 #endif
 
-#if defined(sparc) || defined(__ppc__) || defined(__powerpc__) || defined(__MACH__)
-#define AS_STRING_DIRECTIVE ".asciz"
-#else
-/* GNU as */
-#define AS_STRING_DIRECTIVE ".string"
-#endif
-
-
-// __MACH__
-// .byte generates 1 byte per expression.
-// .short generates 2 bytes per expression.
-// .long generates 4 bytes per expression.
-// .quad generates 8 bytes per expression.
-
+#define ALIGN_TO(val,align) ((((guint64)val) + ((align) - 1)) & ~((align) - 1))
 #define ALIGN_PTR_TO(ptr,align) (gpointer)((((gssize)(ptr)) + (align - 1)) & (~(align - 1)))
 #define ROUND_DOWN(VALUE,SIZE) ((VALUE) & ~((SIZE) - 1))
 
@@ -112,47 +96,22 @@ typedef struct MonoAotOptions {
        gboolean no_dlsym;
        gboolean static_link;
        gboolean asm_only;
+       gboolean asm_writer;
+       gboolean nodebug;
        int nthreads;
+       int ntrampolines;
+       gboolean print_skipped_methods;
 } MonoAotOptions;
 
 typedef struct MonoAotStats {
-       int ccount, mcount, lmfcount, abscount, wrappercount, gcount, ocount, genericcount;
-       int code_size, info_size, ex_info_size, got_size, class_info_size, got_info_size, got_info_offsets_size;
+       int ccount, mcount, lmfcount, abscount, gcount, ocount, genericcount;
+       int code_size, info_size, ex_info_size, unwind_info_size, got_size, class_info_size, got_info_size, got_info_offsets_size;
        int methods_without_got_slots, direct_calls, all_calls;
        int got_slots;
        int got_slot_types [MONO_PATCH_INFO_NONE];
        int jit_time, gen_time, link_time;
 } MonoAotStats;
 
-#if defined(__x86_64__) && defined(HAVE_ELF_H)
-//#define USE_ELF_WRITER 1
-#define USE_ELF_RELA 1
-#endif
-
-//#define USE_ELF_WRITER 1
-
-#if defined(USE_ELF_WRITER)
-#define USE_BIN_WRITER 1
-#endif
-
-#ifdef USE_BIN_WRITER
-
-typedef struct _BinSymbol BinSymbol;
-typedef struct _BinReloc BinReloc;
-typedef struct _BinSection BinSection;
-
-#else
-
-/* emit mode */
-enum {
-       EMIT_NONE,
-       EMIT_BYTE,
-       EMIT_WORD,
-       EMIT_LONG
-};
-
-#endif
-
 typedef struct MonoAotCompile {
        MonoImage *image;
        GPtrArray *methods;
@@ -170,11 +129,15 @@ typedef struct MonoAotCompile {
        GPtrArray *image_table;
        GPtrArray *globals;
        GList *method_order;
-       /* Number of trampolines emitted into the AOT file */
-       guint32 num_aot_trampolines;
-       guint32 got_offset, plt_offset;
+       guint32 *plt_got_info_offsets;
+       guint32 got_offset, plt_offset, plt_got_offset_base;
        /* Number of GOT entries reserved for trampolines */
        guint32 num_trampoline_got_entries;
+
+       guint32 num_trampolines [MONO_AOT_TRAMP_NUM];
+       guint32 trampoline_got_offset_base [MONO_AOT_TRAMP_NUM];
+       guint32 trampoline_size [MONO_AOT_TRAMP_NUM];
+
        MonoAotOptions aot_opts;
        guint32 nmethods;
        guint32 opts;
@@ -183,19 +146,15 @@ typedef struct MonoAotCompile {
        int method_index;
        char *static_linking_symbol;
        CRITICAL_SECTION mutex;
-#ifdef USE_BIN_WRITER
-       BinSymbol *symbols;
-       BinSection *sections;
-       BinSection *cur_section;
-       BinReloc *relocations;
-       GHashTable *labels;
-       int num_relocs;
-#else
+       gboolean use_bin_writer;
+       MonoImageWriter *w;
+       MonoDwarfWriter *dwarf;
        FILE *fp;
        char *tmpfname;
-       int mode; /* emit mode */
-       int col_count; /* bytes emitted per .byte line */
-#endif
+       GSList *cie_program;
+       GHashTable *unwind_info_offsets;
+       GPtrArray *unwind_ops;
+       guint32 unwind_info_offset;
 } MonoAotCompile;
 
 #define mono_acfg_lock(acfg) EnterCriticalSection (&((acfg)->mutex))
@@ -219,7 +178,7 @@ static const gint16 opidx [] = {
 #undef PATCH_INFO
 };
 
-static const char*
+static G_GNUC_UNUSED const char*
 get_patch_name (int info)
 {
        return (const char*)&opstr + opidx [info];
@@ -241,1419 +200,669 @@ get_patch_name (int info)
 
 #endif
 
-static void
-emit_global (MonoAotCompile *acfg, const char *name, gboolean func);
+/* Wrappers around the image writer functions */
 
-static gboolean 
-is_got_patch (MonoJumpInfoType patch_type)
+static inline void
+emit_section_change (MonoAotCompile *acfg, const char *section_name, int subsection_index)
 {
-       return TRUE;
+       img_writer_emit_section_change (acfg->w, section_name, subsection_index);
 }
 
-static G_GNUC_UNUSED int
-ilog2(register int value)
+static inline void
+emit_push_section (MonoAotCompile *acfg, const char *section_name, int subsection)
 {
-       int count = -1;
-       while (value & ~0xf) count += 4, value >>= 4;
-       while (value) count++, value >>= 1;
-       return count;
+       img_writer_emit_push_section (acfg->w, section_name, subsection);
 }
 
-#ifdef USE_BIN_WRITER
+static inline void
+emit_pop_section (MonoAotCompile *acfg)
+{
+       img_writer_emit_pop_section (acfg->w);
+}
 
-typedef struct _BinLabel BinLabel;
-struct _BinLabel {
-       char *name;
-       BinSection *section;
-       int offset;
-};
+static inline void
+emit_local_symbol (MonoAotCompile *acfg, const char *name, const char *end_label, gboolean func) 
+{ 
+       img_writer_emit_local_symbol (acfg->w, name, end_label, func); 
+}
 
-struct _BinReloc {
-       BinReloc *next;
-       char *val1;
-       char *val2;
-       BinSection *val2_section;
-       int val2_offset;
-       int offset;
-       BinSection *section;
-       int section_offset;
-};
+static inline void
+emit_label (MonoAotCompile *acfg, const char *name) 
+{ 
+       img_writer_emit_label (acfg->w, name); 
+}
 
-struct _BinSymbol {
-       BinSymbol *next;
-       char *name;
-       BinSection *section;
-       int offset;
-       gboolean is_function;
-       gboolean is_global;
-};
+static inline void
+emit_bytes (MonoAotCompile *acfg, const guint8* buf, int size) 
+{ 
+       img_writer_emit_bytes (acfg->w, buf, size); 
+}
 
-struct _BinSection {
-       BinSection *next;
-       BinSection *parent;
-       char *name;
-       int subsection;
-       guint8 *data;
-       int data_len;
-       int cur_offset;
-       int file_offset;
-       int virt_offset;
-       int shidx;
-};
+static inline void
+emit_string (MonoAotCompile *acfg, const char *value) 
+{ 
+       img_writer_emit_string (acfg->w, value); 
+}
 
-static void
-emit_start (MonoAotCompile *acfg)
-{
-       acfg->labels = g_hash_table_new (g_str_hash, g_str_equal);
+static inline void
+emit_line (MonoAotCompile *acfg) 
+{ 
+       img_writer_emit_line (acfg->w); 
 }
 
-static void
-emit_section_change (MonoAotCompile *acfg, const char *section_name, int subsection_index)
-{
-       BinSection *section;
+static inline void
+emit_alignment (MonoAotCompile *acfg, int size) 
+{ 
+       img_writer_emit_alignment (acfg->w, size); 
+}
 
-       if (acfg->cur_section && acfg->cur_section->subsection == subsection_index
-                       && strcmp (acfg->cur_section->name, section_name) == 0)
-               return;
-       for (section = acfg->sections; section; section = section->next) {
-               if (section->subsection == subsection_index && strcmp (section->name, section_name) == 0) {
-                       acfg->cur_section = section;
-                       return;
-               }
-       }
-       if (!section) {
-               section = g_new0 (BinSection, 1);
-               section->name = g_strdup (section_name);
-               section->subsection = subsection_index;
-               section->next = acfg->sections;
-               acfg->sections = section;
-               acfg->cur_section = section;
-       }
+static inline void
+emit_pointer_unaligned (MonoAotCompile *acfg, const char *target) 
+{ 
+       img_writer_emit_pointer_unaligned (acfg->w, target); 
 }
 
-static void
-emit_global_inner (MonoAotCompile *acfg, const char *name, gboolean func)
-{
-       BinSymbol *symbol = g_new0 (BinSymbol, 1);
-       symbol->name = g_strdup (name);
-       symbol->is_function = func;
-       symbol->is_global = TRUE;
-       symbol->section = acfg->cur_section;
-       /* FIXME: we align after this call... */
-       symbol->offset = symbol->section->cur_offset;
-       symbol->next = acfg->symbols;
-       acfg->symbols = symbol;
+static inline void
+emit_pointer (MonoAotCompile *acfg, const char *target) 
+{ 
+       img_writer_emit_pointer (acfg->w, target); 
 }
 
-static void
-emit_label (MonoAotCompile *acfg, const char *name)
-{
-       BinLabel *label = g_new0 (BinLabel, 1);
-       label->name = g_strdup (name);
-       label->section = acfg->cur_section;
-       label->offset = acfg->cur_section->cur_offset;
-       g_hash_table_insert (acfg->labels, label->name, label);
+static inline void
+emit_int16 (MonoAotCompile *acfg, int value) 
+{ 
+       img_writer_emit_int16 (acfg->w, value); 
 }
 
-static void
-emit_ensure_buffer (BinSection *section, int size)
-{
-       int new_offset = section->cur_offset + size;
-       if (new_offset >= section->data_len) {
-               int new_size = section->data_len? section->data_len * 2: 256;
-               guint8 *data;
-               while (new_size <= new_offset)
-                       new_size *= 2;
-               data = g_malloc0 (new_size);
-               memcpy (data, section->data, section->data_len);
-               g_free (section->data);
-               section->data = data;
-               section->data_len = new_size;
-       }
+static inline void
+emit_int32 (MonoAotCompile *acfg, int value) 
+{ 
+       img_writer_emit_int32 (acfg->w, value); 
 }
 
-static void
-emit_bytes (MonoAotCompile *acfg, const guint8* buf, int size)
-{
-       emit_ensure_buffer (acfg->cur_section, size);
-       memcpy (acfg->cur_section->data + acfg->cur_section->cur_offset, buf, size);
-       acfg->cur_section->cur_offset += size;
+static inline void
+emit_symbol_diff (MonoAotCompile *acfg, const char *end, const char* start, int offset) 
+{ 
+       img_writer_emit_symbol_diff (acfg->w, end, start, offset); 
 }
 
-static void
-emit_string (MonoAotCompile *acfg, const char *value)
+static inline void
+emit_zero_bytes (MonoAotCompile *acfg, int num) 
+{ 
+       img_writer_emit_zero_bytes (acfg->w, num); 
+}
+
+static inline void
+emit_byte (MonoAotCompile *acfg, guint8 val) 
+{ 
+       img_writer_emit_byte (acfg->w, val); 
+}
+
+static G_GNUC_UNUSED void
+emit_global_inner (MonoAotCompile *acfg, const char *name, gboolean func)
 {
-       int size = strlen (value) + 1;
-       emit_bytes (acfg, (const guint8*)value, size);
+       img_writer_emit_global (acfg->w, name, func);
 }
 
 static void
-emit_line (MonoAotCompile *acfg)
+emit_global (MonoAotCompile *acfg, const char *name, gboolean func)
 {
-       /* Nothing to do in binary writer */
+       if (acfg->aot_opts.no_dlsym) {
+               g_ptr_array_add (acfg->globals, g_strdup (name));
+       } else {
+               img_writer_emit_global (acfg->w, name, func);
+       }
 }
 
 static void
 emit_string_symbol (MonoAotCompile *acfg, const char *name, const char *value)
 {
-       emit_section_change (acfg, ".text", 1);
+       img_writer_emit_section_change (acfg->w, ".text", 1);
        emit_global (acfg, name, FALSE);
-       emit_label (acfg, name);
-       emit_string (acfg, value);
+       img_writer_emit_label (acfg->w, name);
+       img_writer_emit_string (acfg->w, value);
 }
 
-static void 
-emit_alignment (MonoAotCompile *acfg, int size)
+static G_GNUC_UNUSED void
+emit_uleb128 (MonoAotCompile *acfg, guint32 value)
 {
-       int offset = acfg->cur_section->cur_offset;
-       int add;
-       offset += (size - 1);
-       offset &= ~(size - 1);
-       add = offset - acfg->cur_section->cur_offset;
-       if (add) {
-               emit_ensure_buffer (acfg->cur_section, add);
-               acfg->cur_section->cur_offset += add;
-       }
+       do {
+               guint8 b = value & 0x7f;
+               value >>= 7;
+               if (value != 0) /* more bytes to come */
+                       b |= 0x80;
+               emit_byte (acfg, b);
+       } while (value);
 }
 
-static void
-emit_pointer (MonoAotCompile *acfg, const char *target)
+static G_GNUC_UNUSED void
+emit_sleb128 (MonoAotCompile *acfg, gint64 value)
 {
-       BinReloc *reloc;
-
-       if (!target)
-               // FIXME:
-               g_assert_not_reached ();
-       emit_alignment (acfg, sizeof (gpointer));
-       reloc = g_new0 (BinReloc, 1);
-       reloc->val1 = g_strdup (target);
-       reloc->section = acfg->cur_section;
-       reloc->section_offset = acfg->cur_section->cur_offset;
-       reloc->next = acfg->relocations;
-       acfg->relocations = reloc;
-       if (strcmp (reloc->section->name, ".data") == 0) {
-               acfg->num_relocs++;
-               g_print ("reloc: %s at %d\n", target, acfg->cur_section->cur_offset);
+       gboolean more = 1;
+       gboolean negative = (value < 0);
+       guint32 size = 64;
+       guint8 byte;
+
+       while (more) {
+               byte = value & 0x7f;
+               value >>= 7;
+               /* the following is unnecessary if the
+                * implementation of >>= uses an arithmetic rather
+                * than logical shift for a signed left operand
+                */
+               if (negative)
+                       /* sign extend */
+                       value |= - ((gint64)1 <<(size - 7));
+               /* sign bit of byte is second high order bit (0x40) */
+               if ((value == 0 && !(byte & 0x40)) ||
+                       (value == -1 && (byte & 0x40)))
+                       more = 0;
+               else
+                       byte |= 0x80;
+               emit_byte (acfg, byte);
        }
-       acfg->cur_section->cur_offset += sizeof (gpointer);
 }
 
-static void
-emit_int16 (MonoAotCompile *acfg, int value)
+static G_GNUC_UNUSED void
+encode_uleb128 (guint32 value, guint8 *buf, guint8 **endbuf)
 {
-       guint8 *data;
-       emit_ensure_buffer (acfg->cur_section, 2);
-       data = acfg->cur_section->data + acfg->cur_section->cur_offset;
-       acfg->cur_section->cur_offset += 2;
-       /* FIXME: little endian */
-       data [0] = value;
-       data [1] = value >> 8;
+       guint8 *p = buf;
+
+       do {
+               guint8 b = value & 0x7f;
+               value >>= 7;
+               if (value != 0) /* more bytes to come */
+                       b |= 0x80;
+               *p ++ = b;
+       } while (value);
+
+       *endbuf = p;
 }
 
-static void
-emit_int32 (MonoAotCompile *acfg, int value)
+static G_GNUC_UNUSED void
+encode_sleb128 (gint32 value, guint8 *buf, guint8 **endbuf)
 {
-       guint8 *data;
-       emit_ensure_buffer (acfg->cur_section, 4);
-       data = acfg->cur_section->data + acfg->cur_section->cur_offset;
-       acfg->cur_section->cur_offset += 4;
-       /* FIXME: little endian */
-       data [0] = value;
-       data [1] = value >> 8;
-       data [2] = value >> 16;
-       data [3] = value >> 24;
+       gboolean more = 1;
+       gboolean negative = (value < 0);
+       guint32 size = 32;
+       guint8 byte;
+       guint8 *p = buf;
+
+       while (more) {
+               byte = value & 0x7f;
+               value >>= 7;
+               /* the following is unnecessary if the
+                * implementation of >>= uses an arithmetic rather
+                * than logical shift for a signed left operand
+                */
+               if (negative)
+                       /* sign extend */
+                       value |= - (1 <<(size - 7));
+               /* sign bit of byte is second high order bit (0x40) */
+               if ((value == 0 && !(byte & 0x40)) ||
+                       (value == -1 && (byte & 0x40)))
+                       more = 0;
+               else
+                       byte |= 0x80;
+               *p ++= byte;
+       }
+
+       *endbuf = p;
 }
 
+/* ARCHITECTURE SPECIFIC CODE */
+
+#if defined(TARGET_X86) || defined(TARGET_AMD64) || defined(TARGET_ARM)
+#define EMIT_DWARF_INFO 1
+#endif
+
+/*
+ * arch_emit_direct_call:
+ *
+ *   Emit a direct call to the symbol TARGET. CALL_SIZE is set to the size of the
+ * calling code.
+ */
 static void
-emit_symbol_diff (MonoAotCompile *acfg, const char *end, const char* start, int offset)
+arch_emit_direct_call (MonoAotCompile *acfg, const char *target, int *call_size)
 {
-       BinReloc *reloc;
-       reloc = mono_mempool_alloc0 (acfg->mempool, sizeof (BinReloc));
-       reloc->val1 = mono_mempool_strdup (acfg->mempool, end);
-       if (strcmp (start, ".") == 0) {
-               reloc->val2_section = acfg->cur_section;
-               reloc->val2_offset = acfg->cur_section->cur_offset;
+#if defined(TARGET_X86) || defined(TARGET_AMD64)
+       /* Need to make sure this is exactly 5 bytes long */
+       emit_byte (acfg, '\xe8');
+       emit_symbol_diff (acfg, target, ".", -4);
+       *call_size = 5;
+#elif defined(TARGET_ARM)
+       if (acfg->use_bin_writer) {
+               guint8 buf [4];
+               guint8 *code;
+
+               code = buf;
+               ARM_BL (code, 0);
+
+               img_writer_emit_reloc (acfg->w, R_ARM_CALL, target, -8);
+               emit_bytes (acfg, buf, 4);
        } else {
-               reloc->val2 = mono_mempool_strdup (acfg->mempool, start);
+               img_writer_emit_unset_mode (acfg->w);
+               fprintf (acfg->fp, "bl %s\n", target);
        }
-       reloc->offset = offset;
-       reloc->section = acfg->cur_section;
-       reloc->section_offset = acfg->cur_section->cur_offset;
-       reloc->next = acfg->relocations;
-       acfg->relocations = reloc;
-       acfg->cur_section->cur_offset += 4;
-       /*if (strcmp (reloc->section->name, ".data") == 0) {
-               acfg->num_relocs++;
-               g_print ("reloc: %s - %s + %d at %d\n", end, start, offset, acfg->cur_section->cur_offset - 4);
-       }*/
+       *call_size = 4;
+#else
+       g_assert_not_reached ();
+#endif
 }
 
+#ifdef MONO_ARCH_AOT_SUPPORTED
+/*
+ * arch_emit_got_offset:
+ *
+ *   The memory pointed to by CODE should hold native code for computing the GOT
+ * address. Emit this code while patching it with the offset between code and
+ * the GOT. CODE_SIZE is set to the number of bytes emitted.
+ */
 static void
-emit_zero_bytes (MonoAotCompile *acfg, int num)
+arch_emit_got_offset (MonoAotCompile *acfg, guint8 *code, int *code_size)
 {
-       emit_ensure_buffer (acfg->cur_section, num);
-       acfg->cur_section->cur_offset += num;
-}
-
-#ifdef USE_ELF_WRITER
-
-enum {
-       SECT_NULL,
-       SECT_HASH,
-       SECT_DYNSYM,
-       SECT_DYNSTR,
-       SECT_REL_DYN,
-       SECT_RELA_DYN,
-       SECT_TEXT,
-       SECT_DYNAMIC,
-       SECT_GOT_PLT,
-       SECT_DATA,
-       SECT_BSS,
-       SECT_SHSTRTAB,
-       SECT_SYMTAB,
-       SECT_STRTAB,
-       SECT_NUM
-};
+       guint32 offset = mono_arch_get_patch_offset (code);
+       emit_bytes (acfg, code, offset);
+       emit_symbol_diff (acfg, "got", ".", offset);
 
-#if SIZEOF_VOID_P == 4
-
-typedef Elf32_Ehdr ElfHeader;
-typedef Elf32_Shdr ElfSectHeader;
-typedef Elf32_Phdr ElfProgHeader;
-typedef Elf32_Sym ElfSymbol;
-typedef Elf32_Rel ElfReloc;
-typedef Elf32_Rela ElfRelocA;
-typedef Elf32_Dyn ElfDynamic;
+       *code_size = offset + 4;
+}
 
+/*
+ * arch_emit_got_access:
+ *
+ *   The memory pointed to by CODE should hold native code for loading a GOT
+ * slot. Emit this code while patching it so it accesses the GOT slot GOT_SLOT.
+ * CODE_SIZE is set to the number of bytes emitted.
+ */
+static void
+arch_emit_got_access (MonoAotCompile *acfg, guint8 *code, int got_slot, int *code_size)
+{
+       /* Emit beginning of instruction */
+       emit_bytes (acfg, code, mono_arch_get_patch_offset (code));
+
+       /* Emit the offset */
+#ifdef TARGET_AMD64
+       emit_symbol_diff (acfg, "got", ".", (unsigned int) ((got_slot * sizeof (gpointer)) - 4));
+#elif defined(TARGET_X86)
+       emit_int32 (acfg, (unsigned int) ((got_slot * sizeof (gpointer))));
+#elif defined(TARGET_ARM)
+       emit_symbol_diff (acfg, "got", ".", (unsigned int) ((got_slot * sizeof (gpointer))) - 12);
 #else
-
-typedef Elf64_Ehdr ElfHeader;
-typedef Elf64_Shdr ElfSectHeader;
-typedef Elf64_Phdr ElfProgHeader;
-typedef Elf64_Sym ElfSymbol;
-typedef Elf64_Rel ElfReloc;
-typedef Elf64_Rela ElfRelocA;
-typedef Elf64_Dyn ElfDynamic;
-
+       g_assert_not_reached ();
 #endif
 
-typedef struct {
-       const char *name;
-       int type;
-       int esize;
-       int flags;
-       int align;
-} SectInfo;
-
-static SectInfo section_info [] = {
-       {"", 0, 0, 0, 0},
-       {".hash", SHT_HASH, 4, 2, SIZEOF_VOID_P},
-       {".dynsym", SHT_DYNSYM, sizeof (ElfSymbol), 2, SIZEOF_VOID_P},
-       {".dynstr", SHT_STRTAB, 0, 2, 1},
-       {".rel.dyn", SHT_REL, sizeof (ElfReloc), 2, SIZEOF_VOID_P},
-       {".rela.dyn", SHT_RELA, sizeof (ElfRelocA), 2, SIZEOF_VOID_P},
-       {".text", SHT_PROGBITS, 0, 6, 4096},
-       {".dynamic", SHT_DYNAMIC, sizeof (ElfDynamic), 3, SIZEOF_VOID_P},
-       {".got.plt", SHT_PROGBITS, SIZEOF_VOID_P, 3, SIZEOF_VOID_P},
-       {".data", SHT_PROGBITS, 0, 3, 8},
-       {".bss", SHT_NOBITS, 0, 3, 8},
-       {".shstrtab", SHT_STRTAB, 0, 0, 1},
-       {".symtab", SHT_SYMTAB, sizeof (ElfSymbol), 0, SIZEOF_VOID_P},
-       {".strtab", SHT_STRTAB, 0, 0, 1}
-};
-
-typedef struct {
-       GString *data;
-       GHashTable *hash;
-} ElfStrTable;
-
-static int
-str_table_add (ElfStrTable *table, const char* value)
-{
-       int idx;
-       if (!table->data) {
-               table->data = g_string_new_len ("", 1);
-               table->hash = g_hash_table_new (g_str_hash, g_str_equal);
-       }
-       idx = GPOINTER_TO_UINT (g_hash_table_lookup (table->hash, value));
-       if (idx)
-               return idx;
-       idx = table->data->len;
-       g_string_append (table->data, value);
-       g_string_append_c (table->data, 0);
-       g_hash_table_insert (table->hash, (void*)value, GUINT_TO_POINTER (idx));
-       return idx;
+       *code_size = mono_arch_get_patch_offset (code) + 4;
 }
 
-static void
-append_subsection (MonoAotCompile *acfg, ElfSectHeader *sheaders, BinSection *sect, BinSection *add)
-{
-       int offset = sect->cur_offset;
-       /*offset += (sheaders [sect->shidx].sh_addralign - 1);
-       offset &= ~(sheaders [sect->shidx].sh_addralign - 1);*/
-       offset += (8 - 1);
-       offset &= ~(8 - 1);
-       emit_ensure_buffer (sect, offset);
-       g_print ("section %s aligned to %d from %d\n", sect->name, offset, sect->cur_offset);
-       sect->cur_offset = offset;
-
-       emit_ensure_buffer (sect, add->cur_offset);
-       memcpy (sect->data + sect->cur_offset, add->data, add->cur_offset);
-       add->parent = sect;
-       sect->cur_offset += add->cur_offset;
-       add->cur_offset = offset; /* it becomes the offset in the parent section */
-       g_print ("subsection %d of %s added at offset %d (align: %d)\n", add->subsection, sect->name, add->cur_offset, (int)sheaders [sect->shidx].sh_addralign);
-       add->data = NULL;
-       add->data_len = 0;
-}
+#endif
 
-/* merge the subsections */
-static int
-collect_sections (MonoAotCompile *acfg, ElfSectHeader *sheaders, BinSection **out, int num)
+/*
+ * arch_emit_plt_entry:
+ *
+ *   Emit code for the PLT entry with index INDEX.
+ */
+static void
+arch_emit_plt_entry (MonoAotCompile *acfg, int index)
 {
-       int i, j, maxs, num_sections;
-       BinSection *sect;
-
-       num_sections = 0;
-       maxs = 0;
-       for (sect = acfg->sections; sect; sect = sect->next) {
-               if (sect->subsection == 0) {
-                       out [num_sections++] = sect;
-                       g_assert (num_sections < num);
-                       if (strcmp (sect->name, ".text") == 0) {
-                               sect->shidx = SECT_TEXT;
-                       } else if (strcmp (sect->name, ".data") == 0) {
-                               sect->shidx = SECT_DATA;
-                       } else if (strcmp (sect->name, ".bss") == 0) {
-                               sect->shidx = SECT_BSS;
-                       }
+#if defined(TARGET_X86)
+               if (index == 0) {
+                       /* It is filled up during loading by the AOT loader. */
+                       emit_zero_bytes (acfg, 16);
+               } else {
+                       /* Need to make sure this is 9 bytes long */
+                       emit_byte (acfg, '\xe9');
+                       emit_symbol_diff (acfg, "plt", ".", -4);
+                       emit_int32 (acfg, acfg->plt_got_info_offsets [index]);
                }
-               maxs = MAX (maxs, sect->subsection);
-       }
-       for (i = 0; i < num_sections; i++) {
-               for (j = 1; j <= maxs; ++j) {
-                       for (sect = acfg->sections; sect; sect = sect->next) {
-                               if (sect->subsection == j && strcmp (out [i]->name, sect->name) == 0) {
-                                       append_subsection (acfg, sheaders, out [i], sect);
-                               }
-                       }
+#elif defined(TARGET_AMD64)
+               /*
+                * We can't emit jumps because they are 32 bits only so they can't be patched.
+                * So we make indirect calls through GOT entries which are patched by the AOT 
+                * loader to point to .Lpd entries. 
+                * An x86_64 plt entry is 10 bytes long, init_plt () depends on this.
+                */
+               /* jmpq *<offset>(%rip) */
+               emit_byte (acfg, '\xff');
+               emit_byte (acfg, '\x25');
+               emit_symbol_diff (acfg, "got", ".", ((acfg->plt_got_offset_base + index) * sizeof (gpointer)) -4);
+               /* Used by mono_aot_get_plt_info_offset */
+               emit_int32 (acfg, acfg->plt_got_info_offsets [index]);
+#elif defined(TARGET_ARM)
+               guint8 buf [256];
+               guint8 *code;
+
+               /* FIXME:
+                * - optimize OP_AOTCONST implementation
+                * - optimize the PLT entries
+                * - optimize SWITCH AOT implementation
+                * - implement IMT support
+                */
+               code = buf;
+               if (acfg->use_bin_writer) {
+                       /* We only emit 1 relocation since we implement it ourselves anyway */
+                       img_writer_emit_reloc (acfg->w, R_ARM_ALU_PC_G0_NC, "got", ((acfg->plt_got_offset_base + index) * sizeof (gpointer)) - 8);
+                       /* FIXME: A 2 instruction encoding is sufficient in most cases */
+                       ARM_ADD_REG_IMM (code, ARMREG_IP, ARMREG_PC, 0, 0);
+                       ARM_ADD_REG_IMM (code, ARMREG_IP, ARMREG_IP, 0, 0);
+                       ARM_LDR_IMM (code, ARMREG_PC, ARMREG_IP, 0);
+                       emit_bytes (acfg, buf, code - buf);
+                       /* FIXME: Get rid of this */
+                       emit_symbol_diff (acfg, "got", ".", ((acfg->plt_got_offset_base + index) * sizeof (gpointer)));
+                       /* Used by mono_aot_get_plt_info_offset */
+                       emit_int32 (acfg, acfg->plt_got_info_offsets [index]);
+               } else {
+                       ARM_LDR_IMM (code, ARMREG_IP, ARMREG_PC, 4);
+                       ARM_ADD_REG_REG (code, ARMREG_IP, ARMREG_PC, ARMREG_IP);
+                       ARM_LDR_IMM (code, ARMREG_PC, ARMREG_IP, 0);
+                       emit_bytes (acfg, buf, code - buf);
+                       emit_symbol_diff (acfg, "got", ".", ((acfg->plt_got_offset_base + index) * sizeof (gpointer)));
+                       /* Used by mono_aot_get_plt_info_offset */
+                       emit_int32 (acfg, acfg->plt_got_info_offsets [index]);
                }
-       }
-       return num_sections;
+#else
+               g_assert_not_reached ();
+#endif
 }
 
-static unsigned long
-elf_hash (const unsigned char *name)
+/*
+ * arch_emit_specific_trampoline:
+ *
+ *   Emit code for a specific trampoline. OFFSET is the offset of the first of
+ * two GOT slots which contain the generic trampoline address and the trampoline
+ * argument. TRAMP_SIZE is set to the size of the emitted trampoline.
+ */
+static void
+arch_emit_specific_trampoline (MonoAotCompile *acfg, int offset, int *tramp_size)
 {
-       unsigned long h = 0, g;
-       while (*name) {
-               h = (h << 4) + *name++;
-               if ((g = h & 0xf0000000))
-                       h ^= g >> 24;
-               h &= ~g;
-       }
-       return h;
-}
+       /*
+        * The trampolines created here are variations of the specific 
+        * trampolines created in mono_arch_create_specific_trampoline (). The 
+        * differences are:
+        * - the generic trampoline address is taken from a got slot.
+        * - the offset of the got slot where the trampoline argument is stored
+        *   is embedded in the instruction stream, and the generic trampoline
+        *   can load the argument by loading the offset, adding it to the
+        *   address of the trampoline to get the address of the got slot, and
+        *   loading the argument from there.
+        * - all the trampolines should be of the same length.
+        */
+#if defined(TARGET_AMD64)
+       /* This should be exactly 16 bytes long */
+       *tramp_size = 16;
+       /* call *<offset>(%rip) */
+       emit_byte (acfg, '\x41');
+       emit_byte (acfg, '\xff');
+       emit_byte (acfg, '\x15');
+       emit_symbol_diff (acfg, "got", ".", (offset * sizeof (gpointer)) - 4);
+       /* This should be relative to the start of the trampoline */
+       emit_symbol_diff (acfg, "got", ".", (offset * sizeof (gpointer)) - 4 + 19);
+       emit_zero_bytes (acfg, 5);
+#elif defined(TARGET_ARM)
+       guint8 buf [128];
+       guint8 *code;
 
-#define NUM_BUCKETS 17
+       /* This should be exactly 28 bytes long */
+       *tramp_size = 28;
+       code = buf;
+       ARM_PUSH (code, 0x5fff);
+       ARM_LDR_IMM (code, ARMREG_R1, ARMREG_PC, 8);
+       /* Load the value from the GOT */
+       ARM_LDR_REG_REG (code, ARMREG_R1, ARMREG_PC, ARMREG_R1);
+       /* Branch to it */
+       ARM_MOV_REG_REG (code, ARMREG_LR, ARMREG_PC);
+       ARM_MOV_REG_REG (code, ARMREG_PC, ARMREG_R1);
+
+       g_assert (code - buf == 20);
+
+       /* Emit it */
+       emit_bytes (acfg, buf, code - buf);
+       emit_symbol_diff (acfg, "got", ".", (offset * sizeof (gpointer)) - 4 + 8);
+       emit_symbol_diff (acfg, "got", ".", ((offset + 1) * sizeof (gpointer)) - 4 + 8);
+#else
+       g_assert_not_reached ();
+#endif
+}
 
-static int*
-build_hash (MonoAotCompile *acfg, int num_sections, ElfStrTable *dynstr)
+/*
+ * arch_emit_unbox_trampoline:
+ *
+ *   Emit code for the unbox trampoline for METHOD used in the full-aot case.
+ * CALL_TARGET is the symbol pointing to the native code of METHOD.
+ */
+static void
+arch_emit_unbox_trampoline (MonoAotCompile *acfg, MonoMethod *method, MonoGenericSharingContext *gsctx, const char *call_target)
 {
-       int *data;
-       int num_symbols = 1 + num_sections + 3;
-       BinSymbol *symbol;
-
-       for (symbol = acfg->symbols; symbol; symbol = symbol->next) {
-               if (!symbol->is_global)
-                       continue;
-               num_symbols++;
-               str_table_add (dynstr, symbol->name);
-               /*g_print ("adding sym: %s\n", symbol->name);*/
-       }
-       str_table_add (dynstr, "__bss_start");
-       str_table_add (dynstr, "_edata");
-       str_table_add (dynstr, "_end");
+#if defined(TARGET_AMD64)
+       guint8 buf [32];
+       guint8 *code;
+       int this_reg;
+
+       this_reg = mono_arch_get_this_arg_reg (mono_method_signature (method), gsctx, NULL);
+       code = buf;
+       amd64_alu_reg_imm (code, X86_ADD, this_reg, sizeof (MonoObject));
+
+       emit_bytes (acfg, buf, code - buf);
+       /* jump <method> */
+       emit_byte (acfg, '\xe9');
+       emit_symbol_diff (acfg, call_target, ".", -4);
+#elif defined(TARGET_ARM)
+       guint8 buf [128];
+       guint8 *code;
+       int this_pos = 0;
 
-       data = g_new0 (int, num_symbols + 2 + NUM_BUCKETS);
-       data [0] = NUM_BUCKETS;
-       data [1] = num_symbols;
+       code = buf;
 
-       return data;
-}
+       if (MONO_TYPE_ISSTRUCT (mono_method_signature (method)->ret))
+               this_pos = 1;
 
-static gsize
-get_label_addr (MonoAotCompile *acfg, const char *name)
-{
-       int offset;
-       BinLabel *lab;
-       BinSection *section;
-       gsize value;
-
-       lab = g_hash_table_lookup (acfg->labels, name);
-       section = lab->section;
-       offset = lab->offset;
-       if (section->parent) {
-               value = section->parent->virt_offset + section->cur_offset + offset;
-       } else {
-               value = section->virt_offset + offset;
-       }
-       return value;
-}
+       ARM_ADD_REG_IMM8 (code, this_pos, this_pos, sizeof (MonoObject));
 
-static ElfSymbol*
-collect_syms (MonoAotCompile *acfg, int *hash, ElfStrTable *strtab, ElfSectHeader *sheaders, int *num_syms)
-{
-       ElfSymbol *symbols;
-       BinSymbol *symbol;
-       BinSection *section;
-       int i;
-       int *bucket;
-       int *chain;
-       unsigned long hashc;
+       emit_bytes (acfg, buf, code - buf);
+       /* jump to method */
+       if (acfg->use_bin_writer) {
+               guint8 buf [4];
+               guint8 *code;
 
-       if (hash)
-               symbols = g_new0 (ElfSymbol, hash [1]);
-       else
-               symbols = g_new0 (ElfSymbol, *num_syms + SECT_NUM + 10); /* FIXME */
+               code = buf;
+               ARM_B (code, 0);
 
-       /* the first symbol is undef, all zeroes */
-       i = 1;
-       if (sheaders) {
-               int j;
-               for (j = 1; j < SECT_NUM; ++j) {
-                       symbols [i].st_info = ELF32_ST_INFO (STB_LOCAL, STT_SECTION);
-                       symbols [i].st_shndx = j;
-                       symbols [i].st_value = sheaders [j].sh_addr;
-                       ++i;
-               }
+               img_writer_emit_reloc (acfg->w, R_ARM_JUMP24, call_target, -8);
+               emit_bytes (acfg, buf, 4);
        } else {
-               for (section = acfg->sections; section; section = section->next) {
-                       if (section->parent)
-                               continue;
-                       symbols [i].st_info = ELF32_ST_INFO (STB_LOCAL, STT_SECTION);
-                       if (strcmp (section->name, ".text") == 0) {
-                               symbols [i].st_shndx = SECT_TEXT;
-                               section->shidx = SECT_TEXT;
-                               section->file_offset = 4096;
-                               symbols [i].st_value = section->virt_offset;
-                       } else if (strcmp (section->name, ".data") == 0) {
-                               symbols [i].st_shndx = SECT_DATA;
-                               section->shidx = SECT_DATA;
-                               section->file_offset = 4096 + 28; /* FIXME */
-                               symbols [i].st_value = section->virt_offset;
-                       } else if (strcmp (section->name, ".bss") == 0) {
-                               symbols [i].st_shndx = SECT_BSS;
-                               section->shidx = SECT_BSS;
-                               section->file_offset = 4096 + 28 + 8; /* FIXME */
-                               symbols [i].st_value = section->virt_offset;
-                       }
-                       ++i;
-               }
-       }
-       for (symbol = acfg->symbols; symbol; symbol = symbol->next) {
-               int offset;
-               BinLabel *lab;
-               if (!symbol->is_global)
-                       continue;
-               symbols [i].st_info = ELF32_ST_INFO (STB_GLOBAL, symbol->is_function? STT_FUNC : STT_OBJECT);
-               symbols [i].st_name = str_table_add (strtab, symbol->name);
-               /*g_print ("sym name %s tabled to %d\n", symbol->name, symbols [i].st_name);*/
-               section = symbol->section;
-               symbols [i].st_shndx = section->parent? section->parent->shidx: section->shidx;
-               lab = g_hash_table_lookup (acfg->labels, symbol->name);
-               offset = lab->offset;
-               if (section->parent) {
-                       symbols [i].st_value = section->parent->virt_offset + section->cur_offset + offset;
-               } else {
-                       symbols [i].st_value = section->virt_offset + offset;
-               }
-               ++i;
-       }
-       /* add special symbols */
-       symbols [i].st_name = str_table_add (strtab, "__bss_start");
-       symbols [i].st_shndx = 0xfff1;
-       symbols [i].st_info = ELF32_ST_INFO (STB_GLOBAL, 0);
-       ++i;
-       symbols [i].st_name = str_table_add (strtab, "_edata");
-       symbols [i].st_shndx = 0xfff1;
-       symbols [i].st_info = ELF32_ST_INFO (STB_GLOBAL, 0);
-       ++i;
-       symbols [i].st_name = str_table_add (strtab, "_end");
-       symbols [i].st_shndx = 0xfff1;
-       symbols [i].st_info = ELF32_ST_INFO (STB_GLOBAL, 0);
-       ++i;
-
-       if (num_syms)
-               *num_syms = i;
-
-       /* add to hash table */
-       if (hash) {
-               bucket = hash + 2;
-               chain = hash + 2 + hash [0];
-               for (i = 0; i < hash [1]; ++i) {
-                       int slot;
-                       /*g_print ("checking %d '%s' (sym %d)\n", symbols [i].st_name, strtab->data->str + symbols [i].st_name, i);*/
-                       if (!symbols [i].st_name)
-                               continue;
-                       hashc = elf_hash ((guint8*)strtab->data->str + symbols [i].st_name);
-                       slot = hashc % hash [0];
-                       /*g_print ("hashing '%s' at slot %d (sym %d)\n", strtab->data->str + symbols [i].st_name, slot, i);*/
-                       if (bucket [slot]) {
-                               chain [i] = bucket [slot];
-                               bucket [slot] = i;
-                       } else {
-                               bucket [slot] = i;
-                       }
-               }
+               fprintf (acfg->fp, "\n\tb %s\n", call_target);
        }
-       return symbols;
+#else
+       g_assert_not_reached ();
+#endif
 }
 
+/*
+ * arch_emit_static_rgctx_trampoline:
+ *
+ *   Emit code for a static rgctx trampoline. OFFSET is the offset of the first of
+ * two GOT slots which contain the rgctx argument, and the method to jump to.
+ * TRAMP_SIZE is set to the size of the emitted trampoline.
+ * These kinds of trampolines cannot be enumerated statically, since there could
+ * be one trampoline per method instantiation, so we emit the same code for all
+ * trampolines, and parameterize them using two GOT slots.
+ */
 static void
-reloc_symbols (MonoAotCompile *acfg, ElfSymbol *symbols, ElfSectHeader *sheaders, ElfStrTable *strtab, gboolean dynamic)
+arch_emit_static_rgctx_trampoline (MonoAotCompile *acfg, int offset, int *tramp_size)
 {
-       BinSection *section;
-       BinSymbol *symbol;
-       int i;
+#if defined(TARGET_AMD64)
+       /* This should be exactly 13 bytes long */
+       *tramp_size = 13;
+
+       /* mov <OFFSET>(%rip), %r10 */
+       emit_byte (acfg, '\x4d');
+       emit_byte (acfg, '\x8b');
+       emit_byte (acfg, '\x15');
+       emit_symbol_diff (acfg, "got", ".", (offset * sizeof (gpointer)) - 4);
+
+       /* jmp *<offset>(%rip) */
+       emit_byte (acfg, '\xff');
+       emit_byte (acfg, '\x25');
+       emit_symbol_diff (acfg, "got", ".", ((offset + 1) * sizeof (gpointer)) - 4);
+#elif defined(TARGET_ARM)
+       guint8 buf [128];
+       guint8 *code;
 
-       i = 1;
-       if (dynamic) {
-               for (section = acfg->sections; section; section = section->next) {
-                       if (section->parent)
-                               continue;
-                       symbols [i].st_value = sheaders [section->shidx].sh_addr;
-                       ++i;
-               }
-       } else {
-               for (i = 1; i < SECT_NUM; ++i) {
-                       symbols [i].st_value = sheaders [i].sh_addr;
-               }
-       }
-       for (symbol = acfg->symbols; symbol; symbol = symbol->next) {
-               int offset;
-               BinLabel *lab;
-               if (dynamic && !symbol->is_global)
-                       continue;
-               section = symbol->section;
-               lab = g_hash_table_lookup (acfg->labels, symbol->name);
-               offset = lab->offset;
-               if (section->parent) {
-                       symbols [i].st_value = sheaders [section->parent->shidx].sh_addr + section->cur_offset + offset;
-               } else {
-                       symbols [i].st_value = sheaders [section->shidx].sh_addr + offset;
-               }
-               ++i;
-       }
-       /* __bss_start */
-       symbols [i].st_value = sheaders [SECT_BSS].sh_addr;
-       ++i;
-       /* _edata */
-       symbols [i].st_value = sheaders [SECT_DATA].sh_addr + sheaders [SECT_DATA].sh_size;
-       ++i;
-       /* _end */
-       symbols [i].st_value = sheaders [SECT_BSS].sh_addr + sheaders [SECT_BSS].sh_size;
-       ++i;
-}
+       /* This should be exactly 24 bytes long */
+       *tramp_size = 24;
+       code = buf;
+       /* Load rgctx value */
+       ARM_LDR_IMM (code, ARMREG_R1, ARMREG_PC, 8);
+       ARM_LDR_REG_REG (code, MONO_ARCH_RGCTX_REG, ARMREG_PC, ARMREG_R1);
+       /* Load branch addr + branch */
+       ARM_LDR_IMM (code, ARMREG_R1, ARMREG_PC, 4);
+       ARM_LDR_REG_REG (code, ARMREG_PC, ARMREG_PC, ARMREG_R1);
+
+       g_assert (code - buf == 16);
+
+       /* Emit it */
+       emit_bytes (acfg, buf, code - buf);
+       emit_symbol_diff (acfg, "got", ".", (offset * sizeof (gpointer)) - 4 + 8);
+       emit_symbol_diff (acfg, "got", ".", ((offset + 1) * sizeof (gpointer)) - 4 + 4);
+#else
+       g_assert_not_reached ();
+#endif
+}      
 
+/*
+ * arch_emit_imt_thunk:
+ *
+ *   Emit an IMT thunk usable in full-aot mode. The thunk uses 1 got slot which
+ * points to an array of pointer pairs. The pairs of the form [key, ptr], where
+ * key is the IMT key, and ptr holds the address of a memory location holding
+ * the address to branch to if the IMT arg matches the key. The array is 
+ * terminated by a pair whose key is NULL, and whose ptr is the address of the 
+ * fail_tramp.
+ * TRAMP_SIZE is set to the size of the emitted trampoline.
+ */
 static void
-resolve_reloc (MonoAotCompile *acfg, BinReloc *reloc, guint8 **out_data, gsize *out_vaddr, gsize *out_start_val, gsize *out_end_val)
+arch_emit_imt_thunk (MonoAotCompile *acfg, int offset, int *tramp_size)
 {
-       guint8 *data;
-       gsize end_val, start_val;
-       gsize vaddr;
-
-       end_val = get_label_addr (acfg, reloc->val1);
-       if (reloc->val2) {
-               start_val = get_label_addr (acfg, reloc->val2);
-       } else if (reloc->val2_section) {
-               start_val = reloc->val2_offset;
-               if (reloc->val2_section->parent)
-                       start_val += reloc->val2_section->parent->virt_offset + reloc->val2_section->cur_offset;
-               else
-                       start_val += reloc->val2_section->virt_offset;
-       } else {
-               start_val = 0;
-       }
-       end_val = end_val - start_val + reloc->offset;
-       if (reloc->section->parent) {
-               data = reloc->section->parent->data;
-               data += reloc->section->cur_offset;
-               data += reloc->section_offset;
-               vaddr = reloc->section->parent->virt_offset;
-               vaddr += reloc->section->cur_offset;
-               vaddr += reloc->section_offset;
-       } else {
-               data = reloc->section->data;
-               data += reloc->section_offset;
-               vaddr = reloc->section->virt_offset;
-               vaddr += reloc->section_offset;
-       }
+#if defined(TARGET_AMD64)
+       guint8 *buf, *code;
+       guint8 *labels [3];
 
-       *out_start_val = start_val;
-       *out_end_val = end_val;
-       *out_data = data;
-       *out_vaddr = vaddr;
-}
+       code = buf = g_malloc (256);
 
-#ifdef USE_ELF_RELA
+       /* FIXME: Optimize this, i.e. use binary search etc. */
+       /* Maybe move the body into a separate function (slower, but much smaller) */
 
-static ElfRelocA*
-resolve_relocations (MonoAotCompile *acfg)
-{
-       BinReloc *reloc;
-       guint8 *data;
-       gsize end_val, start_val;
-       ElfRelocA *rr;
-       int i;
-       gsize vaddr;
-
-       rr = g_new0 (ElfRelocA, acfg->num_relocs);
-       i = 0;
-
-       for (reloc = acfg->relocations; reloc; reloc = reloc->next) {
-               resolve_reloc (acfg, reloc, &data, &vaddr, &start_val, &end_val);
-               /* FIXME: little endian */
-               data [0] = end_val;
-               data [1] = end_val >> 8;
-               data [2] = end_val >> 16;
-               data [3] = end_val >> 24;
-               if (start_val == 0) {
-                       rr [i].r_offset = vaddr;
-                       rr [i].r_info = R_X86_64_RELATIVE;
-                       rr [i].r_addend = end_val;
-                       ++i;
-                       g_assert (i <= acfg->num_relocs);
-               }
-       }
-       return rr;
-}
+       /* R10 is a free register */
 
-#else /* USE_ELF_RELA */
+       labels [0] = code;
+       amd64_alu_membase_imm (code, X86_CMP, AMD64_R10, 0, 0);
+       labels [1] = code;
+       amd64_branch8 (code, X86_CC_Z, FALSE, 0);
 
-static ElfReloc*
-resolve_relocations (MonoAotCompile *acfg)
-{
-       BinReloc *reloc;
-       guint8 *data;
-       gsize end_val, start_val;
-       ElfReloc *rr;
-       int i;
-       gsize vaddr;
-
-       rr = g_new0 (ElfReloc, acfg->num_relocs);
-       i = 0;
-
-       for (reloc = acfg->relocations; reloc; reloc = reloc->next) {
-               resolve_reloc (acfg, reloc, &data, &vaddr, &start_val, &end_val);
-               /* FIXME: little endian */
-               data [0] = end_val;
-               data [1] = end_val >> 8;
-               data [2] = end_val >> 16;
-               data [3] = end_val >> 24;
-               if (start_val == 0) {
-                       rr [i].r_offset = vaddr;
-                       rr [i].r_info = R_386_RELATIVE;
-                       ++i;
-                       g_assert (i <= acfg->num_relocs);
-               }
-       }
-       return rr;
-}
-
-#endif /* USE_ELF_RELA */
-
-static int
-emit_writeout (MonoAotCompile *acfg)
-{
-       char *outfile_name, *tmp_outfile_name;
-       FILE *file;
-       ElfHeader header;
-       ElfProgHeader progh [3];
-       ElfSectHeader secth [SECT_NUM];
-#ifdef USE_ELF_RELA
-       ElfRelocA *relocs;
-#else
-       ElfReloc *relocs;
-#endif
-       ElfStrTable str_table = {NULL, NULL};
-       ElfStrTable sh_str_table = {NULL, NULL};
-       ElfStrTable dyn_str_table = {NULL, NULL};
-       BinSection* sections [6];
-       BinSection *text_section = NULL, *data_section = NULL, *bss_section = NULL;
-       ElfSymbol *dynsym;
-       ElfSymbol *symtab;
-       ElfDynamic dynamic [14];
-       int *hash;
-       int i, num_sections, file_offset, virt_offset, size, num_symtab;
-       int num_local_syms;
-
-       g_assert (!acfg->aot_opts.asm_only);
+       /* Check key */
+       amd64_alu_membase_reg (code, X86_CMP, AMD64_R10, 0, MONO_ARCH_IMT_REG);
+       labels [2] = code;
+       amd64_branch8 (code, X86_CC_Z, FALSE, 0);
 
-       if (acfg->aot_opts.outfile)
-               outfile_name = g_strdup_printf ("%s", acfg->aot_opts.outfile);
-       else
-               outfile_name = g_strdup_printf ("%s%s", acfg->image->name, SHARED_EXT);
+       /* Loop footer */
+       amd64_alu_reg_imm (code, X86_ADD, AMD64_R10, 2 * sizeof (gpointer));
+       amd64_jump_code (code, labels [0]);
 
-       tmp_outfile_name = g_strdup_printf ("%s.tmp", outfile_name);
+       /* Match */
+       mono_amd64_patch (labels [2], code);
+       amd64_mov_reg_membase (code, AMD64_R10, AMD64_R10, sizeof (gpointer), 8);
+       amd64_jump_membase (code, AMD64_R10, 0);
 
-       unlink (tmp_outfile_name);
-       file = fopen (tmp_outfile_name, "w");
-       g_assert (file);
-
-       /* Section headers */
-       memset (&secth, 0, sizeof (secth));
-       memset (&dynamic, 0, sizeof (dynamic));
-       memset (&header, 0, sizeof (header));
-
-       for (i = 1; i < SECT_NUM; ++i) {
-               secth [i].sh_name = str_table_add (&sh_str_table, section_info [i].name);
-               secth [i].sh_type = section_info [i].type;
-               secth [i].sh_addralign = section_info [i].align;
-               secth [i].sh_flags = section_info [i].flags;
-               secth [i].sh_entsize = section_info [i].esize;
-       }
-       secth [SECT_DYNSYM].sh_info = SIZEOF_VOID_P == 4 ? 4 : 2;
-       secth [SECT_SYMTAB].sh_info = SIZEOF_VOID_P == 4 ? 20 : 17;
-       secth [SECT_HASH].sh_link = SECT_DYNSYM;
-       secth [SECT_DYNSYM].sh_link = SECT_DYNSTR;
-       secth [SECT_REL_DYN].sh_link = SECT_DYNSYM;
-       secth [SECT_RELA_DYN].sh_link = SECT_DYNSYM;
-       secth [SECT_DYNAMIC].sh_link = SECT_DYNSTR;
-       secth [SECT_SYMTAB].sh_link = SECT_STRTAB;
-
-       num_sections = collect_sections (acfg, secth, sections, 6);
-       hash = build_hash (acfg, num_sections, &dyn_str_table);
-       num_symtab = hash [1]; /* FIXME */
-       g_print ("num_sections: %d\n", num_sections);
-       g_print ("dynsym: %d, dynstr size: %d\n", hash [1], (int)dyn_str_table.data->len);
-       for (i = 0; i < num_sections; ++i) {
-               g_print ("section %s, size: %d, %x\n", sections [i]->name, sections [i]->cur_offset, sections [i]->cur_offset);
-       }
+       /* No match */
+       /* FIXME: */
+       mono_amd64_patch (labels [1], code);
+       x86_breakpoint (code);
 
-       /* at this point we know where in the file the first segment sections go */
-       dynsym = collect_syms (acfg, hash, &dyn_str_table, NULL, NULL);
-       num_local_syms = hash [1];
-       symtab = collect_syms (acfg, NULL, &str_table, secth, &num_local_syms);
-
-       for (i = 0; i < num_sections; ++i) {
-               if (sections [i]->shidx == SECT_TEXT) {
-                       text_section = sections [i];
-               } else if (sections [i]->shidx == SECT_DATA) {
-                       data_section = sections [i];
-               } else if (sections [i]->shidx == SECT_BSS) {
-                       bss_section = sections [i];
-               }
-       }
+       /* mov <OFFSET>(%rip), %r10 */
+       emit_byte (acfg, '\x4d');
+       emit_byte (acfg, '\x8b');
+       emit_byte (acfg, '\x15');
+       emit_symbol_diff (acfg, "got", ".", (offset * sizeof (gpointer)) - 4);
 
-       file_offset = virt_offset = sizeof (header) + sizeof (progh);
-       secth [SECT_HASH].sh_addr = secth [SECT_HASH].sh_offset = file_offset;
-       size = sizeof (int) * (2 + hash [0] + hash [1]);
-       virt_offset = (file_offset += size);
-       secth [SECT_HASH].sh_size = size;
-       secth [SECT_DYNSYM].sh_addr = secth [SECT_DYNSYM].sh_offset = file_offset;
-       size = sizeof (ElfSymbol) * hash [1];
-       virt_offset = (file_offset += size);
-       secth [SECT_DYNSYM].sh_size = size;
-       secth [SECT_DYNSTR].sh_addr = secth [SECT_DYNSTR].sh_offset = file_offset;
-       size = dyn_str_table.data->len;
-       virt_offset = (file_offset += size);
-       secth [SECT_DYNSTR].sh_size = size;
-       file_offset += 4-1;
-       file_offset &= ~(4-1);
-       secth [SECT_REL_DYN].sh_addr = secth [SECT_REL_DYN].sh_offset = file_offset;
-#ifndef USE_ELF_RELA
-       size = sizeof (ElfReloc) * acfg->num_relocs;
-#else
-       size = 0;
-#endif
-       virt_offset = (file_offset += size);
-       secth [SECT_REL_DYN].sh_size = size;
-       secth [SECT_RELA_DYN].sh_addr = secth [SECT_RELA_DYN].sh_offset = file_offset;
-#ifdef USE_ELF_RELA
-       size = sizeof (ElfRelocA) * acfg->num_relocs;
-#else
-       size = 0;
-#endif
-       virt_offset = (file_offset += size);
-       secth [SECT_RELA_DYN].sh_size = size;
-       file_offset += 4096-1;
-       file_offset &= ~(4096-1);
-       virt_offset = file_offset;
-       secth [SECT_TEXT].sh_addr = secth [SECT_TEXT].sh_offset = file_offset;
-       size = text_section->cur_offset;
-       secth [SECT_TEXT].sh_size = size;
-       file_offset += size;
-       file_offset += 4-1;
-       file_offset &= ~(4-1);
-       virt_offset = file_offset;
-       /* .dynamic, .got.plt, .data, .bss here */
-       /* Have to increase the virt offset since these go to a separate segment */
-       virt_offset += PAGESIZE;
-       secth [SECT_DYNAMIC].sh_addr = virt_offset;
-       secth [SECT_DYNAMIC].sh_offset = file_offset;
-       size = sizeof (dynamic);
-       secth [SECT_DYNAMIC].sh_size = size;
-       size += 4-1;
-       size &= ~(4-1);
-       file_offset += size;
-       virt_offset += size;
-       secth [SECT_GOT_PLT].sh_addr = virt_offset;
-       secth [SECT_GOT_PLT].sh_offset = file_offset;
-       size = 12;
-       secth [SECT_GOT_PLT].sh_size = size;
-       size += 8-1;
-       size &= ~(8-1);
-       file_offset += size;
-       virt_offset += size;
-       secth [SECT_DATA].sh_addr = virt_offset;
-       secth [SECT_DATA].sh_offset = file_offset;
-       size = data_section->cur_offset;
-       secth [SECT_DATA].sh_size = size;
-       size += 8-1;
-       size &= ~(8-1);
-       file_offset += size;
-       virt_offset += size;
-       secth [SECT_BSS].sh_addr = virt_offset;
-       secth [SECT_BSS].sh_offset = file_offset;
-       size = bss_section->cur_offset;
-       secth [SECT_BSS].sh_size = size;
-
-       /* virtual doesn't matter anymore */
-       secth [SECT_SHSTRTAB].sh_offset = file_offset;
-       size = sh_str_table.data->len;
-       secth [SECT_SHSTRTAB].sh_size = size;
-       size += SIZEOF_VOID_P-1;
-       size &= ~(SIZEOF_VOID_P-1);
-       file_offset += size;
-       secth [SECT_SYMTAB].sh_offset = file_offset;
-       size = sizeof (ElfSymbol) * num_local_syms;
-       secth [SECT_SYMTAB].sh_size = size;
-       file_offset += size;
-       secth [SECT_STRTAB].sh_offset = file_offset;
-       size = str_table.data->len;
-       secth [SECT_STRTAB].sh_size = size;
-       file_offset += size;
-       file_offset += 4-1;
-       file_offset &= ~(4-1);
-
-       text_section->file_offset = secth [SECT_TEXT].sh_offset;
-       text_section->virt_offset = secth [SECT_TEXT].sh_addr;
-       data_section->file_offset = secth [SECT_DATA].sh_offset;
-       data_section->virt_offset = secth [SECT_DATA].sh_addr;
-       bss_section->file_offset = secth [SECT_BSS].sh_offset;
-       bss_section->virt_offset = secth [SECT_BSS].sh_addr;
-
-       header.e_ident [EI_MAG0] = ELFMAG0;
-       header.e_ident [EI_MAG1] = ELFMAG1;
-       header.e_ident [EI_MAG2] = ELFMAG2;
-       header.e_ident [EI_MAG3] = ELFMAG3;
-       header.e_ident [EI_CLASS] = SIZEOF_VOID_P == 4 ? ELFCLASS32 : ELFCLASS64;
-       header.e_ident [EI_DATA] = ELFDATA2LSB;
-       header.e_ident [EI_VERSION] = EV_CURRENT;
-       header.e_ident [EI_OSABI] = ELFOSABI_NONE;
-       header.e_ident [EI_ABIVERSION] = 0;
-       for (i = EI_PAD; i < EI_NIDENT; ++i)
-               header.e_ident [i] = 0;
-
-       header.e_type = ET_DYN;
-#if defined(__i386__)
-       header.e_machine = EM_386;
-#elif defined(__x86_64__)
-       header.e_machine = EM_X86_64;
+       emit_bytes (acfg, buf, code - buf);
+       
+       *tramp_size = code - buf + 7;
+#elif defined(TARGET_ARM)
+       guint8 buf [128];
+       guint8 *code, *code2, *labels [16];
+
+       code = buf;
+
+       /* The IMT method is in v5 */
+
+       /* Only IP is available, but we need at least two free registers */
+       ARM_PUSH1 (code, ARMREG_R1);
+       labels [0] = code;
+       /* Load the parameter from the GOT */
+       ARM_LDR_IMM (code, ARMREG_IP, ARMREG_PC, 0);
+       ARM_LDR_REG_REG (code, ARMREG_IP, ARMREG_PC, ARMREG_IP);
+
+       labels [1] = code;
+       ARM_LDR_IMM (code, ARMREG_R1, ARMREG_IP, 0);
+       ARM_CMP_REG_REG (code, ARMREG_R1, ARMREG_V5);
+       labels [2] = code;
+       ARM_B_COND (code, ARMCOND_EQ, 0);
+
+       /* End-of-loop check */
+       ARM_CMP_REG_IMM (code, ARMREG_R1, 0, 0);
+       labels [3] = code;
+       ARM_B_COND (code, ARMCOND_EQ, 0);
+
+       /* Loop footer */
+       ARM_ADD_REG_IMM8 (code, ARMREG_IP, ARMREG_IP, sizeof (gpointer) * 2);
+       labels [4] = code;
+       ARM_B (code, 0);
+       arm_patch (labels [4], labels [1]);
+
+       /* Match */
+       arm_patch (labels [2], code);
+       ARM_POP1 (code, ARMREG_R1);
+       ARM_LDR_IMM (code, ARMREG_IP, ARMREG_IP, 4);
+       ARM_LDR_IMM (code, ARMREG_PC, ARMREG_IP, 0);
+
+       /* No match */
+       arm_patch (labels [3], code);
+       ARM_DBRK (code);
+
+       /* Fixup offset */
+       code2 = labels [0];
+       ARM_LDR_IMM (code2, ARMREG_IP, ARMREG_PC, (code - (labels [0] + 8)));
+
+       emit_bytes (acfg, buf, code - buf);
+       emit_symbol_diff (acfg, "got", ".", (offset * sizeof (gpointer)) + (code - (labels [0] + 8)) - 4);
+
+       *tramp_size = code - buf + 4;
 #else
        g_assert_not_reached ();
-#endif
-       header.e_version = 1;
-
-       header.e_phoff = sizeof (header);
-       header.e_ehsize = sizeof (header);
-       header.e_phentsize = sizeof (ElfProgHeader);
-       header.e_phnum = 3;
-       header.e_entry = secth [SECT_TEXT].sh_addr;
-       header.e_shstrndx = SECT_SHSTRTAB;
-       header.e_shentsize = sizeof (ElfSectHeader);
-       header.e_shnum = SECT_NUM;
-       header.e_shoff = file_offset;
-
-       /* dynamic data */
-       i = 0;
-       dynamic [i].d_tag = DT_HASH;
-       dynamic [i].d_un.d_val = secth [SECT_HASH].sh_offset;
-       ++i;
-       dynamic [i].d_tag = DT_STRTAB;
-       dynamic [i].d_un.d_val = secth [SECT_DYNSTR].sh_offset;
-       ++i;
-       dynamic [i].d_tag = DT_SYMTAB;
-       dynamic [i].d_un.d_val = secth [SECT_DYNSYM].sh_offset;
-       ++i;
-       dynamic [i].d_tag = DT_STRSZ;
-       dynamic [i].d_un.d_val = dyn_str_table.data->len;
-       ++i;
-       dynamic [i].d_tag = DT_SYMENT;
-       dynamic [i].d_un.d_val = sizeof (ElfSymbol);
-       ++i;
-#ifdef USE_ELF_RELA
-       dynamic [i].d_tag = DT_RELA;
-       dynamic [i].d_un.d_val = secth [SECT_RELA_DYN].sh_offset;
-       ++i;
-       dynamic [i].d_tag = DT_RELASZ;
-       dynamic [i].d_un.d_val = secth [SECT_RELA_DYN].sh_size;
-       ++i;
-       dynamic [i].d_tag = DT_RELAENT;
-       dynamic [i].d_un.d_val = sizeof (ElfRelocA);
-       ++i;
-#else
-       dynamic [i].d_tag = DT_REL;
-       dynamic [i].d_un.d_val = secth [SECT_REL_DYN].sh_offset;
-       ++i;
-       dynamic [i].d_tag = DT_RELSZ;
-       dynamic [i].d_un.d_val = secth [SECT_REL_DYN].sh_size;
-       ++i;
-       dynamic [i].d_tag = DT_RELENT;
-       dynamic [i].d_un.d_val = sizeof (ElfReloc);
-       ++i;
-#endif
-       dynamic [i].d_tag = DT_RELCOUNT;
-       dynamic [i].d_un.d_val = acfg->num_relocs;
-       ++i;
-
-       /* Program header */
-       memset (&progh, 0, sizeof (progh));
-       progh [0].p_type = PT_LOAD;
-       progh [0].p_filesz = progh [0].p_memsz = secth [SECT_DYNAMIC].sh_offset;
-       progh [0].p_align = 4096;
-       progh [0].p_flags = 5;
-
-       progh [1].p_type = PT_LOAD;
-       progh [1].p_offset = secth [SECT_DYNAMIC].sh_offset;
-       progh [1].p_vaddr = progh [1].p_paddr = secth [SECT_DYNAMIC].sh_addr;
-       progh [1].p_filesz = secth [SECT_BSS].sh_offset  - secth [SECT_DYNAMIC].sh_offset;
-       progh [1].p_memsz = secth [SECT_BSS].sh_addr + secth [SECT_BSS].sh_size - secth [SECT_DYNAMIC].sh_addr;
-       progh [1].p_align = 4096;
-       progh [1].p_flags = 6;
-
-       progh [2].p_type = PT_DYNAMIC;
-       progh [2].p_offset = secth [SECT_DYNAMIC].sh_offset;
-       progh [2].p_vaddr = progh [2].p_paddr = secth [SECT_DYNAMIC].sh_addr;
-       progh [2].p_filesz = progh [2].p_memsz = secth [SECT_DYNAMIC].sh_size;
-       progh [2].p_align = SIZEOF_VOID_P;
-       progh [2].p_flags = 6;
-
-       reloc_symbols (acfg, dynsym, secth, &dyn_str_table, TRUE);
-       reloc_symbols (acfg, symtab, secth, &str_table, FALSE);
-       relocs = resolve_relocations (acfg);
-
-       fwrite (&header, sizeof (header), 1, file);
-       fwrite (&progh, sizeof (progh), 1, file);
-       fwrite (hash, sizeof (int) * (hash [0] + hash [1] + 2), 1, file);
-       fwrite (dynsym, sizeof (ElfSymbol) * hash [1], 1, file);
-       fwrite (dyn_str_table.data->str, dyn_str_table.data->len, 1, file);
-       /* .rel.dyn */
-       fseek (file, secth [SECT_REL_DYN].sh_offset, SEEK_SET);
-       fwrite (relocs, sizeof (ElfReloc), acfg->num_relocs, file);
-
-       /* .rela.dyn */
-       fseek (file, secth [SECT_RELA_DYN].sh_offset, SEEK_SET);
-       fwrite (relocs, secth [SECT_RELA_DYN].sh_size, 1, file);
-
-       fseek (file, secth [SECT_TEXT].sh_offset, SEEK_SET);
-       /* write .text, .data, .bss sections */
-       fwrite (text_section->data, text_section->cur_offset, 1, file);
-
-       /* .dynamic */
-       fwrite (dynamic, sizeof (dynamic), 1, file);
-       /* .got.plt */
-       size = secth [SECT_DYNAMIC].sh_addr;
-       fwrite (&size, sizeof (size), 1, file);
-       fseek (file, secth [SECT_DATA].sh_offset, SEEK_SET);
-       fwrite (data_section->data, data_section->cur_offset, 1, file);
-
-       fseek (file, secth [SECT_SHSTRTAB].sh_offset, SEEK_SET);
-       fwrite (sh_str_table.data->str, sh_str_table.data->len, 1, file);
-       fseek (file, secth [SECT_SYMTAB].sh_offset, SEEK_SET);
-       fwrite (symtab, sizeof (ElfSymbol) * num_local_syms, 1, file);
-       fseek (file, secth [SECT_STRTAB].sh_offset, SEEK_SET);
-       fwrite (str_table.data->str, str_table.data->len, 1, file);
-       /*g_print ("file_offset %d vs %d\n", file_offset, ftell (file));*/
-       /*g_assert (file_offset >= ftell (file));*/
-       fseek (file, file_offset, SEEK_SET);
-       fwrite (&secth, sizeof (secth), 1, file);
-       fclose (file);
-       rename (tmp_outfile_name, outfile_name);
-
-       g_free (tmp_outfile_name);
-       g_free (outfile_name);
-
-       return 0;
-}
-
-#endif /* USE_ELF_WRITER */
-
-#else
-
-static void
-emit_start (MonoAotCompile *acfg)
-{
-       if (acfg->aot_opts.asm_only) {
-               if (acfg->aot_opts.outfile)
-                       acfg->tmpfname = g_strdup_printf ("%s", acfg->aot_opts.outfile);
-               else
-                       acfg->tmpfname = g_strdup_printf ("%s.s", acfg->image->name);
-               acfg->fp = fopen (acfg->tmpfname, "w+");
-       } else {
-               int i = g_file_open_tmp ("mono_aot_XXXXXX", &acfg->tmpfname, NULL);
-               acfg->fp = fdopen (i, "w+");
-       }
-       g_assert (acfg->fp);
-}
-
-static void
-emit_unset_mode (MonoAotCompile *acfg)
-{
-       if (acfg->mode == EMIT_NONE)
-               return;
-       fprintf (acfg->fp, "\n");
-       acfg->mode = EMIT_NONE;
-}
-
-static void
-emit_section_change (MonoAotCompile *acfg, const char *section_name, int subsection_index)
-{
-       emit_unset_mode (acfg);
-#if defined(PLATFORM_WIN32)
-       fprintf (acfg->fp, ".section %s\n", section_name);
-#elif defined(__MACH__)
-       if (strcmp(section_name, ".bss") == 0)
-               fprintf (acfg->fp, "%s\n", ".data");
-       else
-               fprintf (acfg->fp, "%s\n", section_name);
-#elif defined(sparc) || defined(__arm__)
-       /* For solaris as, GNU as should accept the same */
-       fprintf (acfg->fp, ".section \"%s\"\n", section_name);
-#else
-       fprintf (acfg->fp, "%s %d\n", section_name, subsection_index);
-#endif
-}
-
-static void
-emit_symbol_type (MonoAotCompile *acfg, const char *name, gboolean func)
-{
-       const char *stype;
-
-       if (func)
-               stype = "function";
-       else
-               stype = "object";
-
-       emit_unset_mode (acfg);
-#if defined(__MACH__)
-
-#elif defined(sparc) || defined(__arm__)
-       fprintf (acfg->fp, "\t.type %s,#%s\n", name, stype);
-#elif defined(PLATFORM_WIN32)
-
-#elif defined(__x86_64__) || defined(__i386__)
-       fprintf (acfg->fp, "\t.type %s,@%s\n", name, stype);
-#else
-       fprintf (acfg->fp, "\t.type %s,@%s\n", name, stype);
-#endif
-}
-
-static void
-emit_global_inner (MonoAotCompile *acfg, const char *name, gboolean func)
-{
-       emit_unset_mode (acfg);
-#if  (defined(__ppc__) && defined(__MACH__)) || defined(PLATFORM_WIN32)
-    // mach-o always uses a '_' prefix.
-       fprintf (acfg->fp, "\t.globl _%s\n", name);
-#else
-       fprintf (acfg->fp, "\t.globl %s\n", name);
-#endif
-
-       emit_symbol_type (acfg, name, func);
-}
-
-static void
-emit_label (MonoAotCompile *acfg, const char *name)
-{
-       emit_unset_mode (acfg);
-#if (defined(__ppc__) && defined(__MACH__)) || defined(PLATFORM_WIN32)
-    // mach-o always uses a '_' prefix.
-       fprintf (acfg->fp, "_%s:\n", name);
-#else
-       fprintf (acfg->fp, "%s:\n", name);
-#endif
-
-#if defined(PLATFORM_WIN32)
-       /* Emit a normal label too */
-       fprintf (acfg->fp, "%s:\n", name);
 #endif
 }
 
-static void
-emit_string (MonoAotCompile *acfg, const char *value)
-{
-       emit_unset_mode (acfg);
-       fprintf (acfg->fp, "\t%s \"%s\"\n", AS_STRING_DIRECTIVE, value);
-}
-
-static void
-emit_line (MonoAotCompile *acfg)
-{
-       emit_unset_mode (acfg);
-       fprintf (acfg->fp, "\n");
-}
-
-static void
-emit_string_symbol (MonoAotCompile *acfg, const char *name, const char *value)
-{
-       emit_unset_mode (acfg);
-       emit_section_change (acfg, ".text", 1);
-       emit_global (acfg, name, FALSE);
-       emit_label (acfg, name);
-       emit_string (acfg, value);
-}
-
-static void 
-emit_alignment (MonoAotCompile *acfg, int size)
-{
-       emit_unset_mode (acfg);
-#if defined(__arm__)
-       fprintf (acfg->fp, "\t.align %d\n", ilog2 (size));
-#elif defined(__ppc__) && defined(__MACH__)
-       // the mach-o assembler specifies alignments as powers of 2.
-       fprintf (acfg->fp, "\t.align %d\t; ilog2\n", ilog2(size));
-#elif defined(__powerpc__)
-       /* ignore on linux/ppc */
-#else
-       fprintf (acfg->fp, "\t.align %d\n", size);
-#endif
-}
-
-static void
-emit_pointer (MonoAotCompile *acfg, const char *target)
-{
-       emit_unset_mode (acfg);
-       emit_alignment (acfg, sizeof (gpointer));
-#if defined(__x86_64__)
-       fprintf (acfg->fp, "\t.quad %s\n", target ? target : "0");
-#elif defined(sparc) && SIZEOF_VOID_P == 8
-       fprintf (acfg->fp, "\t.xword %s\n", target ? target : "0");
-#else
-       fprintf (acfg->fp, "\t.long %s\n", target ? target : "0");
-#endif
-}
-
-static char *byte_to_str;
-
-static void
-emit_bytes (MonoAotCompile *acfg, const guint8* buf, int size)
-{
-       int i;
-       if (acfg->mode != EMIT_BYTE) {
-               acfg->mode = EMIT_BYTE;
-               acfg->col_count = 0;
-       }
-
-       if (byte_to_str == NULL) {
-               byte_to_str = g_new0 (char, 256 * 8);
-               for (i = 0; i < 256; ++i) {
-                       sprintf (byte_to_str + (i * 8), ",%d", i);
-               }
-       }
-
-       for (i = 0; i < size; ++i, ++acfg->col_count) {
-               if ((acfg->col_count % 32) == 0)
-                       fprintf (acfg->fp, "\n\t.byte %d", buf [i]);
-               else
-                       fputs (byte_to_str + (buf [i] * 8), acfg->fp);
-       }
-}
-
-static inline void
-emit_int16 (MonoAotCompile *acfg, int value)
-{
-       if (acfg->mode != EMIT_WORD) {
-               acfg->mode = EMIT_WORD;
-               acfg->col_count = 0;
-       }
-       if ((acfg->col_count++ % 8) == 0)
-#if defined(__MACH__)
-               fprintf (acfg->fp, "\n\t.short ");
-#elif defined(__arm__)
-               /* FIXME: Use .hword on other archs as well */
-               fprintf (acfg->fp, "\n\t.hword ");
-#else
-               fprintf (acfg->fp, "\n\t.word ");
-#endif
-       else
-               fprintf (acfg->fp, ", ");
-       fprintf (acfg->fp, "%d", value);
-}
-
-static inline void
-emit_int32 (MonoAotCompile *acfg, int value)
-{
-       if (acfg->mode != EMIT_LONG) {
-               acfg->mode = EMIT_LONG;
-               acfg->col_count = 0;
-       }
-       if ((acfg->col_count++ % 8) == 0)
-               fprintf (acfg->fp, "\n\t.long ");
-       else
-               fprintf (acfg->fp, ",");
-       fprintf (acfg->fp, "%d", value);
-}
-
-static void
-emit_symbol_diff (MonoAotCompile *acfg, const char *end, const char* start, int offset)
-{
-       if (acfg->mode != EMIT_LONG) {
-               acfg->mode = EMIT_LONG;
-               acfg->col_count = 0;
-       }
-       if ((acfg->col_count++ % 8) == 0)
-               fprintf (acfg->fp, "\n\t.long ");
-       else
-               fprintf (acfg->fp, ",");
-       if (offset > 0)
-               fprintf (acfg->fp, "%s - %s + %d", end, start, offset);
-       else if (offset < 0)
-               fprintf (acfg->fp, "%s - %s %d", end, start, offset);
-       else
-               fprintf (acfg->fp, "%s - %s", end, start);
-}
-
-static void
-emit_zero_bytes (MonoAotCompile *acfg, int num)
-{
-       emit_unset_mode (acfg);
-#if defined(__MACH__)
-       fprintf (acfg->fp, "\t.space %d\n", num);
-#else
-       fprintf (acfg->fp, "\t.skip %d\n", num);
-#endif
-}
-
-static int
-emit_writeout (MonoAotCompile *acfg)
+/*
+ * arch_get_cie_program:
+ *
+ *   Get the unwind bytecode for the DWARF CIE.
+ */
+static GSList*
+arch_get_cie_program (void)
 {
-       char *command, *objfile;
-       char *outfile_name, *tmp_outfile_name;
-
-       fclose (acfg->fp);
-
-#if defined(__x86_64__)
-#define AS_OPTIONS "--64"
-#elif defined(sparc) && SIZEOF_VOID_P == 8
-#define AS_OPTIONS "-xarch=v9"
-#else
-#define AS_OPTIONS ""
-#endif
-
-       if (acfg->aot_opts.asm_only) {
-               printf ("Output file: '%s'.\n", acfg->tmpfname);
-               if (acfg->aot_opts.static_link)
-                       printf ("Linking symbol: '%s'.\n", acfg->static_linking_symbol);
-               return 0;
-       }
-
-       if (acfg->aot_opts.static_link) {
-               if (acfg->aot_opts.outfile)
-                       objfile = g_strdup_printf ("%s", acfg->aot_opts.outfile);
-               else
-                       objfile = g_strdup_printf ("%s.o", acfg->image->name);
-       } else {
-               objfile = g_strdup_printf ("%s.o", acfg->tmpfname);
-       }
-       command = g_strdup_printf ("as %s %s -o %s", AS_OPTIONS, acfg->tmpfname, objfile);
-       printf ("Executing the native assembler: %s\n", command);
-       if (system (command) != 0) {
-               g_free (command);
-               g_free (objfile);
-               return 1;
-       }
+#ifdef TARGET_AMD64
+       GSList *l = NULL;
 
-       g_free (command);
+       mono_add_unwind_op_def_cfa (l, (guint8*)NULL, (guint8*)NULL, AMD64_RSP, 8);
+       mono_add_unwind_op_offset (l, (guint8*)NULL, (guint8*)NULL, AMD64_RIP, -8);
 
-       if (acfg->aot_opts.static_link) {
-               printf ("Output file: '%s'.\n", objfile);
-               printf ("Linking symbol: '%s'.\n", acfg->static_linking_symbol);
-               g_free (objfile);
-               return 0;
-       }
-
-       if (acfg->aot_opts.outfile)
-               outfile_name = g_strdup_printf ("%s", acfg->aot_opts.outfile);
-       else
-               outfile_name = g_strdup_printf ("%s%s", acfg->image->name, SHARED_EXT);
-
-       tmp_outfile_name = g_strdup_printf ("%s.tmp", outfile_name);
-
-#if defined(sparc)
-       command = g_strdup_printf ("ld -shared -G -o %s %s.o", outfile_name, acfg->tmpfname);
-#elif defined(__ppc__) && defined(__MACH__)
-       command = g_strdup_printf ("gcc -dynamiclib -o %s %s.o", outfile_name, acfg->tmpfname);
-#elif defined(PLATFORM_WIN32)
-       command = g_strdup_printf ("gcc -shared --dll -mno-cygwin -o %s %s.o", outfile_name, acfg->tmpfname);
+       return l;
 #else
-       if (acfg->aot_opts.no_dlsym) {
-               /* 
-                * Need to link using gcc so our ctor function gets called.
-                */
-               command = g_strdup_printf ("gcc -shared -o %s %s.o", outfile_name, acfg->tmpfname);
-       } else {
-               command = g_strdup_printf ("ld -shared -o %s %s.o", outfile_name, acfg->tmpfname);
-       }
+       return NULL;
 #endif
-       printf ("Executing the native linker: %s\n", command);
-       if (system (command) != 0) {
-               g_free (tmp_outfile_name);
-               g_free (outfile_name);
-               g_free (command);
-               g_free (objfile);
-               return 1;
-       }
-
-       g_free (command);
-       unlink (objfile);
-       /*com = g_strdup_printf ("strip --strip-unneeded %s%s", acfg->image->name, SHARED_EXT);
-       printf ("Stripping the binary: %s\n", com);
-       system (com);
-       g_free (com);*/
-
-       rename (tmp_outfile_name, outfile_name);
-
-       g_free (tmp_outfile_name);
-       g_free (outfile_name);
-       g_free (objfile);
-
-       if (acfg->aot_opts.save_temps)
-               printf ("Retained input file.\n");
-       else
-               unlink (acfg->tmpfname);
-
-       return 0;
 }
 
-#endif /* ASM_WRITER */
-
-static void
-emit_global (MonoAotCompile *acfg, const char *name, gboolean func)
-{
-       if (acfg->aot_opts.no_dlsym) {
-               g_ptr_array_add (acfg->globals, g_strdup (name));
-       } else {
-               emit_global_inner (acfg, name, func);
-       }
-}
-
-static void
-emit_byte (MonoAotCompile *acfg, guint8 val)
-{
-       emit_bytes (acfg, &val, 1);
-}
+/* END OF ARCH SPECIFIC CODE */
 
 static guint32
 mono_get_field_token (MonoClassField *field) 
@@ -1783,20 +992,20 @@ encode_klass_ref (MonoAotCompile *acfg, MonoClass *klass, guint8 *buf, guint8 **
                encode_value (klass->type_token - MONO_TOKEN_TYPE_DEF, p, &p);
                encode_value (get_image_index (acfg, klass->image), p, &p);
        } else if ((klass->byval_arg.type == MONO_TYPE_VAR) || (klass->byval_arg.type == MONO_TYPE_MVAR)) {
-               MonoGenericParam *param = klass->byval_arg.data.generic_param;
+               MonoGenericContainer *container = mono_type_get_generic_param_owner (&klass->byval_arg);
+               g_assert (container);
 
                /* Marker */
                encode_value (MONO_TOKEN_TYPE_SPEC, p, &p);
                encode_value (klass->byval_arg.type, p, &p);
 
-               encode_value (param->num, p, &p);
+               encode_value (mono_type_get_generic_param_num (&klass->byval_arg), p, &p);
                
-               g_assert (param->owner);
-               encode_value (param->owner->is_method, p, &p);
-               if (param->owner->is_method)
-                       encode_method_ref (acfg, param->owner->owner.method, p, &p);
+               encode_value (container->is_method, p, &p);
+               if (container->is_method)
+                       encode_method_ref (acfg, container->owner.method, p, &p);
                else
-                       encode_klass_ref (acfg, param->owner->owner.klass, p, &p);
+                       encode_klass_ref (acfg, container->owner.klass, p, &p);
        } else {
                /* Array class */
                g_assert (klass->rank > 0);
@@ -1855,18 +1064,58 @@ encode_method_ref (MonoAotCompile *acfg, MonoMethod *method, guint8 *buf, guint8
        guint32 token = method->token;
        MonoJumpInfoToken *ji;
        guint8 *p = buf;
+       char *name;
 
-       g_assert (image_index < MAX_IMAGE_INDEX);
+       /*
+        * The encoding for most methods is as follows:
+        * - image index encoded as a leb128
+        * - token index encoded as a leb128
+        * Values of image index >= MONO_AOT_METHODREF_MIN are used to mark additional
+        * types of method encodings.
+        */
+
+       g_assert (image_index < MONO_AOT_METHODREF_MIN);
 
        /* Mark methods which can't use aot trampolines because they need the further 
         * processing in mono_magic_trampoline () which requires a MonoMethod*.
         */
-       if (method->is_generic && (method->flags & METHOD_ATTRIBUTE_VIRTUAL))
-               encode_value ((252 << 24), p, &p);
+       if ((method->is_generic && (method->flags & METHOD_ATTRIBUTE_VIRTUAL)) ||
+               (method->iflags & METHOD_IMPL_ATTRIBUTE_SYNCHRONIZED))
+               encode_value ((MONO_AOT_METHODREF_NO_AOT_TRAMPOLINE << 24), p, &p);
 
+       /* 
+        * Some wrapper methods are shared using their signature, encode their 
+        * stringified signature instead.
+        * FIXME: Optimize disk usage
+        */
+       name = NULL;
        if (method->wrapper_type) {
-               /* Marker */
-               encode_value ((253 << 24), p, &p);
+               if (method->wrapper_type == MONO_WRAPPER_RUNTIME_INVOKE) {
+                       char *tmpsig = mono_signature_get_desc (mono_method_signature (method), TRUE);
+                       name = g_strdup_printf ("(wrapper runtime-invoke):%s (%s)", method->name, tmpsig);
+                       g_free (tmpsig);
+               } else if (method->wrapper_type == MONO_WRAPPER_DELEGATE_INVOKE) {
+                       char *tmpsig = mono_signature_get_desc (mono_method_signature (method), TRUE);
+                       name = g_strdup_printf ("(wrapper delegate-invoke):%s (%s)", method->name, tmpsig);
+                       g_free (tmpsig);
+               } else if (method->wrapper_type == MONO_WRAPPER_DELEGATE_BEGIN_INVOKE) {
+                       char *tmpsig = mono_signature_get_desc (mono_method_signature (method), TRUE);
+                       name = g_strdup_printf ("(wrapper delegate-begin-invoke):%s (%s)", method->name, tmpsig);
+                       g_free (tmpsig);
+               } else if (method->wrapper_type == MONO_WRAPPER_DELEGATE_END_INVOKE) {
+                       char *tmpsig = mono_signature_get_desc (mono_method_signature (method), TRUE);
+                       name = g_strdup_printf ("(wrapper delegate-end-invoke):%s (%s)", method->name, tmpsig);
+                       g_free (tmpsig);
+               }
+       }
+
+       if (name) {
+               encode_value ((MONO_AOT_METHODREF_WRAPPER_NAME << 24), p, &p);
+               strcpy ((char*)p, name);
+               p += strlen (name) + 1;
+               g_free (name);
+       } else if (method->wrapper_type) {
+               encode_value ((MONO_AOT_METHODREF_WRAPPER << 24), p, &p);
 
                encode_value (method->wrapper_type, p, &p);
 
@@ -1900,14 +1149,23 @@ encode_method_ref (MonoAotCompile *acfg, MonoMethod *method, guint8 *buf, guint8
                        break;
                }
                case MONO_WRAPPER_STELEMREF:
-               case MONO_WRAPPER_MONITOR_FAST_ENTER:
-               case MONO_WRAPPER_MONITOR_FAST_EXIT:
                        break;
-               case MONO_WRAPPER_STATIC_RGCTX_INVOKE: {
+               case MONO_WRAPPER_UNKNOWN:
+                       if (strcmp (method->name, "FastMonitorEnter") == 0)
+                               encode_value (MONO_AOT_WRAPPER_MONO_ENTER, p, &p);
+                       else if (strcmp (method->name, "FastMonitorExit") == 0)
+                               encode_value (MONO_AOT_WRAPPER_MONO_EXIT, p, &p);
+                       else
+                               g_assert_not_reached ();
+                       break;
+               case MONO_WRAPPER_STATIC_RGCTX_INVOKE:
+               case MONO_WRAPPER_SYNCHRONIZED:
+               case MONO_WRAPPER_MANAGED_TO_NATIVE: {
                        MonoMethod *m;
 
                        m = mono_marshal_method_from_wrapper (method);
                        g_assert (m);
+                       g_assert (m != method);
                        encode_method_ref (acfg, m, p, &p);
                        break;
                }
@@ -1926,8 +1184,7 @@ encode_method_ref (MonoAotCompile *acfg, MonoMethod *method, guint8 *buf, guint8
                        g_assert (image_index < MAX_IMAGE_INDEX);
                        token = ji->token;
 
-                       /* Marker */
-                       encode_value ((255 << 24), p, &p);
+                       encode_value ((MONO_AOT_METHODREF_METHODSPEC << 24), p, &p);
                        encode_value (image_index, p, &p);
                        encode_value (token, p, &p);
                } else {
@@ -1943,8 +1200,7 @@ encode_method_ref (MonoAotCompile *acfg, MonoMethod *method, guint8 *buf, guint8
                         * like Nullable:Box/Unbox, or by generic sharing.
                         */
 
-                       /* Marker */
-                       encode_value ((254 << 24), p, &p);
+                       encode_value ((MONO_AOT_METHODREF_GINST << 24), p, &p);
                        /* Encode the klass */
                        encode_klass_ref (acfg, method->klass, p, &p);
                        /* Encode the method */
@@ -1961,15 +1217,34 @@ encode_method_ref (MonoAotCompile *acfg, MonoMethod *method, guint8 *buf, guint8
                /* This might be a method of a constructed type like int[,].Set */
                /* Obtain the token from information recorded by the JIT */
                ji = g_hash_table_lookup (acfg->token_info_hash, method);
-               g_assert (ji);
-               image_index = get_image_index (acfg, ji->image);
-               g_assert (image_index < MAX_IMAGE_INDEX);
-               token = ji->token;
+               if (ji) {
+                       image_index = get_image_index (acfg, ji->image);
+                       g_assert (image_index < MAX_IMAGE_INDEX);
+                       token = ji->token;
 
-               /* Marker */
-               encode_value ((255 << 24), p, &p);
-               encode_value (image_index, p, &p);
-               encode_value (token, p, &p);
+                       encode_value ((MONO_AOT_METHODREF_METHODSPEC << 24), p, &p);
+                       encode_value (image_index, p, &p);
+                       encode_value (token, p, &p);
+               } else {
+                       /* Array methods */
+                       g_assert (method->klass->rank);
+
+                       /* Encode directly */
+                       encode_value ((MONO_AOT_METHODREF_ARRAY << 24), p, &p);
+                       encode_klass_ref (acfg, method->klass, p, &p);
+                       if (!strcmp (method->name, ".ctor") && mono_method_signature (method)->param_count == method->klass->rank)
+                               encode_value (0, p, &p);
+                       else if (!strcmp (method->name, ".ctor") && mono_method_signature (method)->param_count == method->klass->rank * 2)
+                               encode_value (1, p, &p);
+                       else if (!strcmp (method->name, "Get"))
+                               encode_value (2, p, &p);
+                       else if (!strcmp (method->name, "Address"))
+                               encode_value (3, p, &p);
+                       else if (!strcmp (method->name, "Set"))
+                               encode_value (4, p, &p);
+                       else
+                               g_assert_not_reached ();
+               }
        } else {
                g_assert (mono_metadata_token_table (token) == MONO_TABLE_METHOD);
                encode_value ((image_index << 24) | mono_metadata_token_index (token), p, &p);
@@ -2007,6 +1282,7 @@ is_plt_patch (MonoJumpInfo *patch_info)
        case MONO_PATCH_INFO_METHOD:
        case MONO_PATCH_INFO_INTERNAL_METHOD:
        case MONO_PATCH_INFO_JIT_ICALL_ADDR:
+       case MONO_PATCH_INFO_ICALL_ADDR:
        case MONO_PATCH_INFO_CLASS_INIT:
        case MONO_PATCH_INFO_RGCTX_FETCH:
        case MONO_PATCH_INFO_GENERIC_CLASS_INIT:
@@ -2018,34 +1294,6 @@ is_plt_patch (MonoJumpInfo *patch_info)
        }
 }
 
-/*
- * is_shared_got_patch:
- *
- *   Return whenever PATCH_INFO refers to a patch which needs a shared GOT
- * entry.
- * Keep it in sync with the version in aot-runtime.c.
- */
-static inline gboolean
-is_shared_got_patch (MonoJumpInfo *patch_info)
-{
-       switch (patch_info->type) {
-       case MONO_PATCH_INFO_VTABLE:
-       case MONO_PATCH_INFO_CLASS:
-       case MONO_PATCH_INFO_IID:
-       case MONO_PATCH_INFO_ADJUSTED_IID:
-       case MONO_PATCH_INFO_FIELD:
-       case MONO_PATCH_INFO_SFLDA:
-       case MONO_PATCH_INFO_DECLSEC:
-       case MONO_PATCH_INFO_LDTOKEN:
-       case MONO_PATCH_INFO_TYPE_FROM_HANDLE:
-       case MONO_PATCH_INFO_RVA:
-       case MONO_PATCH_INFO_METHODCONST:
-               return TRUE;
-       default:
-               return FALSE;
-       }
-}
-
 static int
 get_plt_offset (MonoAotCompile *acfg, MonoJumpInfo *patch_info)
 {
@@ -2054,6 +1302,15 @@ get_plt_offset (MonoAotCompile *acfg, MonoJumpInfo *patch_info)
        if (is_plt_patch (patch_info)) {
                int idx = GPOINTER_TO_UINT (g_hash_table_lookup (acfg->patch_to_plt_offset, patch_info));
 
+               if (patch_info->type == MONO_PATCH_INFO_METHOD && (patch_info->data.method->iflags & METHOD_IMPL_ATTRIBUTE_SYNCHRONIZED)) {
+                       /* 
+                        * Allocate a separate PLT slot for each such patch, since some plt
+                        * entries will refer to the method itself, and some will refer to
+                        * wrapper.
+                        */
+                       idx = 0;
+               }
+
                if (idx) {
                        res = idx;
                } else {
@@ -2113,6 +1370,7 @@ get_shared_got_offset (MonoAotCompile *acfg, MonoJumpInfo *ji)
 static void
 add_method_with_index (MonoAotCompile *acfg, MonoMethod *method, int index)
 {
+       g_assert (method);
        if (!g_hash_table_lookup (acfg->method_indexes, method)) {
                g_ptr_array_add (acfg->methods, method);
                g_hash_table_insert (acfg->method_indexes, method, GUINT_TO_POINTER (index + 1));
@@ -2188,7 +1446,7 @@ get_runtime_invoke_sig (MonoMethodSignature *sig)
 
        mb = mono_mb_new (mono_defaults.object_class, "FOO", MONO_WRAPPER_NONE);
        m = mono_mb_create_method (mb, sig, 16);
-       return mono_marshal_get_runtime_invoke (m);
+       return mono_marshal_get_runtime_invoke (m, FALSE);
 }
 
 static void
@@ -2263,6 +1521,9 @@ add_wrappers (MonoAotCompile *acfg)
        csig->params [1] = &mono_defaults.boolean_class->byval_arg;
        add_method (acfg, get_runtime_invoke_sig (csig));
 
+       /* runtime-invoke used by finalizers */
+       add_method (acfg, mono_marshal_get_runtime_invoke (mono_class_get_method_from_name_flags (mono_defaults.object_class, "Finalize", 0, 0), TRUE));
+
        for (i = 0; i < acfg->image->tables [MONO_TABLE_METHOD].rows; ++i) {
                MonoMethod *method;
                guint32 token = MONO_TOKEN_METHOD_DEF | (i + 1);
@@ -2290,7 +1551,7 @@ add_wrappers (MonoAotCompile *acfg)
                }
 
                if (!skip)
-                       add_method (acfg, mono_marshal_get_runtime_invoke (method));
+                       add_method (acfg, mono_marshal_get_runtime_invoke (method, FALSE));
        }
 
        if (strcmp (acfg->image->assembly->aname.name, "mscorlib") == 0) {
@@ -2317,13 +1578,17 @@ add_wrappers (MonoAotCompile *acfg)
                orig_method = mono_method_desc_search_in_class (desc, mono_defaults.monitor_class);
                g_assert (orig_method);
                mono_method_desc_free (desc);
-               add_method (acfg, mono_monitor_get_fast_path (orig_method));
+               method = mono_monitor_get_fast_path (orig_method);
+               if (method)
+                       add_method (acfg, method);
 
                desc = mono_method_desc_new ("Monitor:Exit", FALSE);
                orig_method = mono_method_desc_search_in_class (desc, mono_defaults.monitor_class);
                g_assert (orig_method);
                mono_method_desc_free (desc);
-               add_method (acfg, mono_monitor_get_fast_path (orig_method));
+               method = mono_monitor_get_fast_path (orig_method);
+               if (method)
+                       add_method (acfg, method);
        }
 
        /* remoting-invoke wrappers */
@@ -2335,8 +1600,7 @@ add_wrappers (MonoAotCompile *acfg)
 
                sig = mono_method_signature (method);
 
-               if (sig->hasthis && (method->klass->marshalbyref || method->klass == mono_defaults.object_class) && 
-                       !(method->flags & METHOD_ATTRIBUTE_VIRTUAL)) {
+               if (sig->hasthis && (method->klass->marshalbyref || method->klass == mono_defaults.object_class)) {
                        m = mono_marshal_get_remoting_invoke_with_check (method);
 
                        add_method (acfg, m);
@@ -2356,25 +1620,36 @@ add_wrappers (MonoAotCompile *acfg)
                        m = mono_marshal_get_delegate_invoke (method, NULL);
 
                        add_method (acfg, m);
+
+                       method = mono_class_get_method_from_name_flags (klass, "BeginInvoke", -1, 0);
+                       add_method (acfg, mono_marshal_get_delegate_begin_invoke (method));
+
+                       method = mono_class_get_method_from_name_flags (klass, "EndInvoke", -1, 0);
+                       add_method (acfg, mono_marshal_get_delegate_end_invoke (method));
                }
        }
 
-#if 0
-       /* static rgctx wrappers */
-       /* FIXME: Each wrapper belongs to a given instantiation of a generic method */
+       /* Synchronized wrappers */
        for (i = 0; i < acfg->image->tables [MONO_TABLE_METHOD].rows; ++i) {
                token = MONO_TOKEN_METHOD_DEF | (i + 1);
                method = mono_get_method (acfg->image, token, NULL);
 
-               if (((method->flags & METHOD_ATTRIBUTE_STATIC) ||
-                        (method->is_inflated && mono_method_get_context (method)->method_inst)) &&
-                       mono_class_generic_sharing_enabled (method->klass) &&
-                       mono_method_is_generic_sharable_impl (method, FALSE)) {
-                       m = mono_marshal_get_static_rgctx_invoke (method);
-                       add_method (acfg, m);
+               if (method->iflags & METHOD_IMPL_ATTRIBUTE_SYNCHRONIZED)
+                       add_method (acfg, mono_marshal_get_synchronized_wrapper (method));
+       }
+
+       /* pinvoke wrappers */
+       for (i = 0; i < acfg->image->tables [MONO_TABLE_METHOD].rows; ++i) {
+               MonoMethod *method;
+               guint32 token = MONO_TOKEN_METHOD_DEF | (i + 1);
+
+               method = mono_get_method (acfg->image, token, NULL);
+
+               if ((method->flags & METHOD_ATTRIBUTE_PINVOKE_IMPL) ||
+                       (method->iflags & METHOD_IMPL_ATTRIBUTE_INTERNAL_CALL)) {
+                       add_method (acfg, mono_marshal_get_native_wrapper (method, TRUE, TRUE));
                }
        }
-#endif
 }
 
 static gboolean
@@ -2394,26 +1669,115 @@ has_type_vars (MonoClass *klass)
                                        return TRUE;
                }
        }
-       return FALSE;
-}
+       return FALSE;
+}
+
+static gboolean
+method_has_type_vars (MonoMethod *method)
+{
+       if (has_type_vars (method->klass))
+               return TRUE;
+
+       if (method->is_inflated) {
+               MonoGenericContext *context = mono_method_get_context (method);
+               if (context->method_inst) {
+                       int i;
+
+                       for (i = 0; i < context->method_inst->type_argc; ++i)
+                               if (has_type_vars (mono_class_from_mono_type (context->method_inst->type_argv [i])))
+                                       return TRUE;
+               }
+       }
+       return FALSE;
+}
+
+/*
+ * add_generic_class:
+ *
+ *   Add all methods of a generic class.
+ */
+static void
+add_generic_class (MonoAotCompile *acfg, MonoClass *klass)
+{
+       MonoMethod *method;
+       gpointer iter;
+
+       mono_class_init (klass);
+
+       if (klass->generic_class && klass->generic_class->context.class_inst->is_open)
+               return;
+
+       if (has_type_vars (klass))
+               return;
+
+       if (!klass->generic_class && !klass->rank)
+               return;
+
+       /* 
+        * Add rgctx wrappers for cctors since those are called by the runtime, so 
+        * there is no methodspec for them. This is needed even for shared classes,
+        * since rgctx wrappers belong to inflated methods.
+        */
+       method = mono_class_get_cctor (klass);
+       if (method && mono_method_needs_static_rgctx_invoke (method, FALSE))
+               add_extra_method (acfg, mono_marshal_get_static_rgctx_invoke (method));
+
+       iter = NULL;
+       while ((method = mono_class_get_methods (klass, &iter))) {
+               if (mono_method_is_generic_sharable_impl (method, FALSE))
+                       /* Already added */
+                       continue;
+
+               if (method->is_generic)
+                       /* FIXME: */
+                       continue;
+
+               /*
+                * FIXME: Instances which are referenced by these methods are not added,
+                * for example Array.Resize<int> for List<int>.Add ().
+                */
+               add_extra_method (acfg, method);
+       }
 
-static gboolean
-method_has_type_vars (MonoMethod *method)
-{
-       if (has_type_vars (method->klass))
-               return TRUE;
+       /* 
+        * For ICollection<T>, where T is a vtype, add instances of the helper methods
+        * in Array, since a T[] could be cast to ICollection<T>.
+        */
+       if (klass->image == mono_defaults.corlib && !strcmp (klass->name_space, "System.Collections.Generic") &&
+               (!strcmp(klass->name, "ICollection`1") || !strcmp (klass->name, "IEnumerable`1") || !strcmp (klass->name, "IList`1") || !strcmp (klass->name, "IEnumerator`1")) &&
+               MONO_TYPE_ISSTRUCT (klass->generic_class->context.class_inst->type_argv [0])) {
+               MonoClass *tclass = mono_class_from_mono_type (klass->generic_class->context.class_inst->type_argv [0]);
+               MonoClass *array_class = mono_bounded_array_class_get (tclass, 1, FALSE);
+               gpointer iter;
+               char *name_prefix;
 
-       if (method->is_inflated) {
-               MonoGenericContext *context = mono_method_get_context (method);
-               if (context->method_inst) {
-                       int i;
+               if (!strcmp (klass->name, "IEnumerator`1"))
+                       name_prefix = g_strdup_printf ("%s.%s", klass->name_space, "IEnumerable`1");
+               else
+                       name_prefix = g_strdup_printf ("%s.%s", klass->name_space, klass->name);
 
-                       for (i = 0; i < context->method_inst->type_argc; ++i)
-                               if (has_type_vars (mono_class_from_mono_type (context->method_inst->type_argv [i])))
-                                       return TRUE;
+               /* Add the T[]/InternalEnumerator class */
+               if (!strcmp (klass->name, "IEnumerable`1") || !strcmp (klass->name, "IEnumerator`1")) {
+                       MonoClass *nclass;
+
+                       iter = NULL;
+                       while ((nclass = mono_class_get_nested_types (array_class->parent, &iter))) {
+                               if (!strcmp (nclass->name, "InternalEnumerator`1"))
+                                       break;
+                       }
+                       g_assert (nclass);
+                       nclass = mono_class_inflate_generic_class (nclass, mono_generic_class_get_context (klass->generic_class));
+                       add_generic_class (acfg, nclass);
+               }
+
+               iter = NULL;
+               while ((method = mono_class_get_methods (array_class, &iter))) {
+                       if (strstr (method->name, name_prefix))
+                               add_extra_method (acfg, method);
                }
+
+               g_free (name_prefix);
        }
-       return FALSE;
 }
 
 /*
@@ -2427,6 +1791,8 @@ add_generic_instances (MonoAotCompile *acfg)
        int i;
        guint32 token;
        MonoMethod *method;
+       MonoMethodHeader *header;
+       MonoMethodSignature *sig;
        MonoGenericContext *context;
 
        for (i = 0; i < acfg->image->tables [MONO_TABLE_METHODSPEC].rows; ++i) {
@@ -2450,49 +1816,48 @@ add_generic_instances (MonoAotCompile *acfg)
 
        for (i = 0; i < acfg->image->tables [MONO_TABLE_TYPESPEC].rows; ++i) {
                MonoClass *klass;
-               gpointer iter;
 
                token = MONO_TOKEN_TYPE_SPEC | (i + 1);
 
                klass = mono_class_get (acfg->image, token);
                if (!klass)
                        continue;
-               mono_class_init (klass);
 
-               if (klass->generic_class && klass->generic_class->context.class_inst->is_open)
-                       continue;
+               add_generic_class (acfg, klass);
+       }
 
-               if (has_type_vars (klass))
-                       continue;
+       /* Add types of args/locals */
+       for (i = 0; i < acfg->methods->len; ++i) {
+               int j;
 
-               /* 
-                * Add rgctx wrappers for cctors since those are called by the runtime, so 
-                * there is no methodspec for them. This is needed even for shared classes,
-                * since rgctx wrappers belong to inflated methods.
-                */
-               method = mono_class_get_cctor (klass);
-               if (method)
-                       add_extra_method (acfg, mono_marshal_get_static_rgctx_invoke (method));
+               method = g_ptr_array_index (acfg->methods, i);
 
-               iter = NULL;
-               while ((method = mono_class_get_methods (klass, &iter))) {
-                       if (mono_method_is_generic_sharable_impl (method, FALSE))
-                               /* Already added */
-                               continue;
+               sig = mono_method_signature (method);
 
-                       if (method->is_generic)
-                               /* FIXME: */
-                               continue;
+               if (sig) {
+                       for (j = 0; j < sig->param_count; ++j)
+                               if (sig->params [j]->type == MONO_TYPE_GENERICINST)
+                                       add_generic_class (acfg, mono_class_from_mono_type (sig->params [j]));
+               }
 
-                       /*
-                        * FIXME: Instances which are referenced by these methods are not added,
-                        * for example Array.Resize<int> for List<int>.Add ().
-                        */
-                       add_extra_method (acfg, method);
+               header = mono_method_get_header (method);
+
+               if (header) {
+                       for (j = 0; j < header->num_locals; ++j)
+                               if (header->locals [j]->type == MONO_TYPE_GENERICINST)
+                                       add_generic_class (acfg, mono_class_from_mono_type (header->locals [j]));
                }
        }
 }
 
+/*
+ * emit_and_reloc_code:
+ *
+ *   Emit the native code in CODE, handling relocations along the way. If GOT_ONLY
+ * is true, calls are made through the GOT too. This is used for emitting trampolines
+ * in full-aot mode, since calls made from trampolines couldn't go through the PLT,
+ * since trampolines are needed to make PTL work.
+ */
 static void
 emit_and_reloc_code (MonoAotCompile *acfg, MonoMethod *method, guint8 *code, guint32 code_len, MonoJumpInfo *relocs, gboolean got_only)
 {
@@ -2534,18 +1899,14 @@ emit_and_reloc_code (MonoAotCompile *acfg, MonoMethod *method, guint8 *code, gui
                        case MONO_PATCH_INFO_NONE:
                                break;
                        case MONO_PATCH_INFO_GOT_OFFSET: {
-                               guint32 offset = mono_arch_get_patch_offset (code + i);
-                               emit_bytes (acfg, code + i, offset);
-                               emit_symbol_diff (acfg, "got", ".", offset);
-
-                               i += offset + 4 - 1;
+                               int code_size;
+                               arch_emit_got_offset (acfg, code + i, &code_size);
+                               i += code_size - 1;
                                skip = TRUE;
                                break;
                        }
                        default: {
-                               if (!is_got_patch (patch_info->type))
-                                       break;
-
                                /*
                                 * If this patch is a call, try emitting a direct call instead of
                                 * through a PLT entry. This is possible if the called method is in
@@ -2559,6 +1920,9 @@ emit_and_reloc_code (MonoAotCompile *acfg, MonoMethod *method, guint8 *code, gui
 
                                                if (direct_callable && !(!callee_cfg->has_got_slots && (callee_cfg->method->klass->flags & TYPE_ATTRIBUTE_BEFORE_FIELD_INIT)))
                                                        direct_callable = FALSE;
+                                               if ((callee_cfg->method->iflags & METHOD_IMPL_ATTRIBUTE_SYNCHRONIZED) && method->wrapper_type != MONO_WRAPPER_SYNCHRONIZED)
+                                                       // FIXME: Maybe call the wrapper directly ?
+                                                       direct_callable = FALSE;
                                                if (direct_callable) {
                                                        //printf ("DIRECT: %s %s\n", method ? mono_method_full_name (method, TRUE) : "", mono_method_full_name (callee_cfg->method, TRUE));
                                                        direct_call = TRUE;
@@ -2584,37 +1948,17 @@ emit_and_reloc_code (MonoAotCompile *acfg, MonoMethod *method, guint8 *code, gui
                                }
 
                                if (direct_call) {
-#if defined(__i386__) || defined(__x86_64__)
-                                       g_assert (code [i] == 0xe8);
-                                       /* Need to make sure this is exactly 5 bytes long */
-                                       emit_byte (acfg, '\xe8');
-                                       emit_symbol_diff (acfg, direct_call_target, ".", -4);
-                                       i += 4;
-#elif defined(__arm__)
-#ifdef USE_BIN_WRITER
-                                       /* FIXME: Can't encode this using the current symbol writer functions */
-                                       g_assert_not_reached ();
-#else
-                                       emit_unset_mode (acfg);
-                                       fprintf (acfg->fp, "bl %s\n", direct_call_target);
-                                       i += 4 - 1;
-#endif
-#endif
+                                       int call_size;
+
+                                       arch_emit_direct_call (acfg, direct_call_target, &call_size);
+                                       i += call_size - 1;
                                } else {
+                                       int code_size;
+
                                        got_slot = get_got_offset (acfg, patch_info);
 
-                                       emit_bytes (acfg, code + i, mono_arch_get_patch_offset (code + i));
-#ifdef __x86_64__
-                                       emit_symbol_diff (acfg, "got", ".", (unsigned int) ((got_slot * sizeof (gpointer)) - 4));
-#elif defined(__i386__)
-                                       emit_int32 (acfg, (unsigned int) ((got_slot * sizeof (gpointer))));
-#elif defined(__arm__)
-                                       emit_symbol_diff (acfg, "got", ".", (unsigned int) ((got_slot * sizeof (gpointer))) - 12);
-#else
-                                       g_assert_not_reached ();
-#endif
-                                       
-                                       i += mono_arch_get_patch_offset (code + i) + 4 - 1;
+                                       arch_emit_got_access (acfg, code + i, got_slot, &code_size);
+                                       i += code_size - 1;
                                }
                                skip = TRUE;
                        }
@@ -2663,8 +2007,31 @@ emit_method_code (MonoAotCompile *acfg, MonoCompile *cfg)
 
        emit_alignment (acfg, func_alignment);
        emit_label (acfg, symbol);
-       if (acfg->aot_opts.write_symbols)
-               emit_global (acfg, symbol, TRUE);
+
+       if (acfg->aot_opts.write_symbols && !acfg->aot_opts.nodebug) {
+               char *name1, *name2;
+               int i, j, len;
+
+               name1 = mono_method_full_name (method, TRUE);
+               len = strlen (name1);
+               name2 = malloc (len + 1);
+               j = 0;
+               for (i = 0; i < len; ++i) {
+                       if (isalnum (name1 [i])) {
+                               name2 [j ++] = name1 [i];
+                       } else if (name1 [i] == ' ' && name1 [i + 1] == '(' && name1 [i + 2] == ')') {
+                               i += 2;
+                       } else if (name1 [i] == '(' || name1 [i] == ')') {
+                       } else
+                               name2 [j ++] = '_';
+               }
+               name2 [j] = '\0';
+               sprintf (symbol, ".Lme_%x", method_index);
+               emit_local_symbol (acfg, name2, symbol, TRUE);
+               emit_label (acfg, name2);
+               g_free (name1);
+               g_free (name2);
+       }
 
        if (cfg->verbose_level > 0)
                g_print ("Method %s emitted as %s\n", mono_method_full_name (method, TRUE), symbol);
@@ -2676,6 +2043,9 @@ emit_method_code (MonoAotCompile *acfg, MonoCompile *cfg)
        emit_and_reloc_code (acfg, method, code, cfg->code_len, cfg->patch_info, FALSE);
 
        emit_line (acfg);
+
+       sprintf (symbol, ".Lme_%x", method_index);
+       emit_label (acfg, symbol);
 }
 
 /**
@@ -2801,7 +2171,7 @@ static void
 encode_patch_list (MonoAotCompile *acfg, GPtrArray *patches, int n_patches, int first_got_offset, guint8 *buf, guint8 **endbuf)
 {
        guint8 *p = buf;
-       guint32 last_offset, j, pindex;
+       guint32 pindex;
        MonoJumpInfo *patch_info;
 
        encode_value (n_patches, p, &p);
@@ -2809,32 +2179,15 @@ encode_patch_list (MonoAotCompile *acfg, GPtrArray *patches, int n_patches, int
        if (n_patches)
                encode_value (first_got_offset, p, &p);
 
-       /* First encode the type+position table */
-       last_offset = 0;
-       j = 0;
        for (pindex = 0; pindex < patches->len; ++pindex) {
-               guint32 offset;
                patch_info = g_ptr_array_index (patches, pindex);
-               
+
                if (patch_info->type == MONO_PATCH_INFO_NONE)
                        /* Nothing to do */
                        continue;
 
-               j ++;
-               //printf ("T: %d O: %d.\n", patch_info->type, patch_info->ip.i);
-               offset = patch_info->ip.i - last_offset;
-               last_offset = patch_info->ip.i;
-
-               /* Only the type is needed */
-               *p = patch_info->type;
-               p++;
-       }
-
-       /* Then encode the other info */
-       for (pindex = 0; pindex < patches->len; ++pindex) {
-               patch_info = g_ptr_array_index (patches, pindex);
-
-               if (is_shared_got_patch (patch_info)) {
+               encode_value (patch_info->type, p, &p);
+               if (mono_aot_is_shared_got_patch (patch_info)) {
                        guint32 offset = get_got_offset (acfg, patch_info);
                        encode_value (offset, p, &p);
                } else {
@@ -2943,6 +2296,39 @@ emit_method_info (MonoAotCompile *acfg, MonoCompile *cfg)
        g_free (buf);
 }
 
+static guint32
+get_unwind_info_offset (MonoAotCompile *acfg, guint8 *encoded, guint32 encoded_len)
+{
+       guint32 cache_index;
+       guint32 offset;
+
+       /* Reuse the unwind module to canonize and store unwind info entries */
+       cache_index = mono_cache_unwind_info (encoded, encoded_len);
+
+       /* Use +/- 1 to distinguish 0s from missing entries */
+       offset = GPOINTER_TO_UINT (g_hash_table_lookup (acfg->unwind_info_offsets, GUINT_TO_POINTER (cache_index + 1)));
+       if (offset)
+               return offset - 1;
+       else {
+               guint8 buf [16];
+               guint8 *p;
+
+               /* 
+                * It would be easier to use assembler symbols, but the caller needs an
+                * offset now.
+                */
+               offset = acfg->unwind_info_offset;
+               g_hash_table_insert (acfg->unwind_info_offsets, GUINT_TO_POINTER (cache_index + 1), GUINT_TO_POINTER (offset + 1));
+               g_ptr_array_add (acfg->unwind_ops, GUINT_TO_POINTER (cache_index));
+
+               p = buf;
+               encode_value (encoded_len, p, &p);
+
+               acfg->unwind_info_offset += encoded_len + (p - buf);
+               return offset;
+       }
+}
+
 static void
 emit_exception_debug_info (MonoAotCompile *acfg, MonoCompile *cfg)
 {
@@ -2954,6 +2340,8 @@ emit_exception_debug_info (MonoAotCompile *acfg, MonoCompile *cfg)
        MonoMethodHeader *header;
        guint8 *p, *buf, *debug_info;
        MonoJitInfo *jinfo = cfg->jit_info;
+       guint32 flags;
+       gboolean use_unwind_ops = FALSE;
 
        method = cfg->orig_method;
        code = cfg->native_code;
@@ -2964,14 +2352,39 @@ emit_exception_debug_info (MonoAotCompile *acfg, MonoCompile *cfg)
        /* Make the labels local */
        sprintf (symbol, ".Le_%x_p", method_index);
 
-       mono_debug_serialize_debug_info (cfg, &debug_info, &debug_info_size);
+       if (!acfg->aot_opts.nodebug) {
+               mono_debug_serialize_debug_info (cfg, &debug_info, &debug_info_size);
+       } else {
+               debug_info = NULL;
+               debug_info_size = 0;
+       }
 
-       buf_size = header->num_clauses * 256 + debug_info_size + 128;
+       buf_size = header->num_clauses * 256 + debug_info_size + 1024;
        p = buf = g_malloc (buf_size);
 
+#ifdef MONO_ARCH_HAVE_XP_UNWIND
+       use_unwind_ops = cfg->unwind_ops != NULL;
+#endif
+
+       flags = (jinfo->has_generic_jit_info ? 1 : 0) | (use_unwind_ops ? 2 : 0);
+
        encode_value (jinfo->code_size, p, &p);
-       encode_value (jinfo->used_regs, p, &p);
-       encode_value (jinfo->has_generic_jit_info, p, &p);
+       encode_value (flags, p, &p);
+
+       if (use_unwind_ops) {
+               guint32 encoded_len;
+               guint8 *encoded;
+
+               /* 
+                * This is a duplicate of the data in the .debug_frame section, but that
+                * section cannot be accessed using the dl interface.
+                */
+               encoded = mono_unwind_ops_encode (cfg->unwind_ops, &encoded_len);
+               encode_value (get_unwind_info_offset (acfg, encoded, encoded_len), p, &p);
+               g_free (encoded);
+       } else {
+               encode_value (jinfo->used_regs, p, &p);
+       }
 
        /* Exception table */
        if (header->num_clauses) {
@@ -3066,7 +2479,7 @@ emit_klass_info (MonoAotCompile *acfg, guint32 token)
                encode_value (-1, p, &p);
        } else {
                encode_value (klass->vtable_size, p, &p);
-               encode_value ((no_special_static << 7) | (klass->has_static_refs << 6) | (klass->has_references << 5) | ((klass->blittable << 4) | (klass->nested_classes ? 1 : 0) << 3) | (klass->has_cctor << 2) | (klass->has_finalize << 1) | klass->ghcimpl, p, &p);
+               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);
                if (klass->has_cctor)
                        encode_method_ref (acfg, mono_class_get_cctor (klass), p, &p);
                if (klass->has_finalize)
@@ -3111,42 +2524,21 @@ static void
 emit_plt (MonoAotCompile *acfg)
 {
        char symbol [128];
-       int i, buf_size;
-       guint8 *p, *buf;
-       guint32 *plt_info_offsets;
-
-       /*
-        * Encode info need to resolve PLT entries.
-        */
-       buf_size = acfg->plt_offset * 128;
-       p = buf = g_malloc (buf_size);
-
-       plt_info_offsets = g_new0 (guint32, acfg->plt_offset);
-
-       for (i = 1; i < acfg->plt_offset; ++i) {
-               MonoJumpInfo *patch_info = g_hash_table_lookup (acfg->plt_offset_to_patch, GUINT_TO_POINTER (i));
-
-               plt_info_offsets [i] = p - buf;
-               encode_value (patch_info->type, p, &p);
-               encode_patch (acfg, patch_info, p, &p);
-       }
+       int i;
 
        emit_line (acfg);
        sprintf (symbol, "plt");
 
        emit_section_change (acfg, ".text", 0);
        emit_global (acfg, symbol, TRUE);
-#ifdef __i386__
+#ifdef TARGET_X86
        /* This section will be made read-write by the AOT loader */
-       emit_alignment (acfg, PAGESIZE);
+       emit_alignment (acfg, mono_pagesize ());
+#else
+       emit_alignment (acfg, 16);
 #endif
        emit_label (acfg, symbol);
 
-#if defined(USE_BIN_WRITER) && defined(__arm__)
-       /* FIXME: */
-       g_assert_not_reached ();
-#endif
-
        for (i = 0; i < acfg->plt_offset; ++i) {
                char label [128];
 
@@ -3156,101 +2548,17 @@ emit_plt (MonoAotCompile *acfg)
                /* 
                 * The first plt entry is used to transfer code to the AOT loader. 
                 */
-
-#if defined(__i386__)
-               if (i == 0) {
-                       /* It is filled up during loading by the AOT loader. */
-                       emit_zero_bytes (acfg, 16);
-               } else {
-                       /* Need to make sure this is 9 bytes long */
-                       emit_byte (acfg, '\xe9');
-                       emit_symbol_diff (acfg, "plt", ".", -4);
-                       emit_int32 (acfg, plt_info_offsets [i]);
-               }
-#elif defined(__x86_64__)
-               /*
-                * We can't emit jumps because they are 32 bits only so they can't be patched.
-                * So we emit a jump table instead whose entries are patched by the AOT loader to
-                * point to .Lpd entries. ELF stores these in the GOT too, but we don't, since
-                * methods with GOT entries can't be called directly.
-                * We also emit the default PLT code here since the PLT code will not be patched.
-                * An x86_64 plt entry is 10 bytes long, init_plt () depends on this.
-                */
-               /* jmpq *<offset>(%rip) */
-               emit_byte (acfg, '\xff');
-               emit_byte (acfg, '\x25');
-               emit_symbol_diff (acfg, "plt_jump_table", ".", (i * sizeof (gpointer)) -4);
-               /* Used by mono_aot_get_plt_info_offset */
-               emit_int32 (acfg, plt_info_offsets [i]);
-#elif defined(__arm__)
-               /* FIXME:
-                * - optimize OP_AOTCONST implementation
-                * - optimize the PLT entries
-                * - optimize SWITCH AOT implementation
-                * - implement IMT support
-                */
-               emit_unset_mode (acfg);
-               fprintf (acfg->fp, "\tldr ip, [pc, #4]\n");
-               fprintf (acfg->fp, "\tadd ip, pc, ip\n");
-               fprintf (acfg->fp, "\tldr pc, [ip, #0]\n");
-               emit_symbol_diff (acfg, "plt_jump_table", ".", (i * sizeof (gpointer)));
-               /* Used by mono_aot_get_plt_info_offset */
-    #if defined(__MACH__)
-               fprintf (acfg->fp, "\n\t.long %d\n", plt_info_offsets [i]);
-    #else
-               fprintf (acfg->fp, "\n\t.word %d\n", plt_info_offsets [i]);
-    #endif
-
-#else
-               g_assert_not_reached ();
-#endif
+               arch_emit_plt_entry (acfg, i);
        }
 
-       g_free (plt_info_offsets);
-
        sprintf (symbol, "plt_end");
        emit_global (acfg, symbol, TRUE);
        emit_label (acfg, symbol);
-
-       /* Emit PLT info */
-       sprintf (symbol, "plt_info");
-       emit_global (acfg, symbol, FALSE);
-       emit_label (acfg, symbol);
-
-       g_assert (p - buf < buf_size);
-       emit_bytes (acfg, buf, p - buf);
-       g_free (buf);
-
-       sprintf (symbol, "plt_jump_table_addr");
-       emit_section_change (acfg, ".data", 0);
-       emit_global (acfg, symbol, FALSE);
-       emit_alignment (acfg, 8);
-       emit_label (acfg, symbol);
-       emit_pointer (acfg, "plt_jump_table");
-
-       sprintf (symbol, "plt_jump_table_size");
-       emit_section_change (acfg, ".data", 0);
-       emit_global (acfg, symbol, FALSE);
-       emit_alignment (acfg, 8);
-       emit_label (acfg, symbol);
-       emit_symbol_diff (acfg, "plt_jump_table_end", "plt_jump_table", 0);
-
-       /* Don't make this a global so accesses don't need relocations */
-       sprintf (symbol, "plt_jump_table");
-       emit_section_change (acfg, ".bss", 0);
-       emit_label (acfg, symbol);
-
-#if defined(__x86_64__) || defined(__arm__)
-       emit_zero_bytes (acfg, (int)(acfg->plt_offset * sizeof (gpointer)));
-#endif 
-
-       sprintf (symbol, "plt_jump_table_end");
-       emit_label (acfg, symbol);
 }
 
 static G_GNUC_UNUSED void
-emit_named_code (MonoAotCompile *acfg, const char *name, guint8 *code, 
-                                guint32 code_size, int got_offset, MonoJumpInfo *ji)
+emit_trampoline (MonoAotCompile *acfg, const char *name, guint8 *code, 
+                                guint32 code_size, int got_offset, MonoJumpInfo *ji, GSList *unwind_ops)
 {
        char symbol [256];
        guint32 buf_size;
@@ -3267,6 +2575,9 @@ emit_named_code (MonoAotCompile *acfg, const char *name, guint8 *code,
        emit_alignment (acfg, 16);
        emit_label (acfg, symbol);
 
+       sprintf (symbol, ".Lnamed_%s", name);
+       emit_label (acfg, symbol);
+
        /* 
         * The code should access everything through the GOT, so we pass
         * TRUE here.
@@ -3295,28 +2606,31 @@ emit_named_code (MonoAotCompile *acfg, const char *name, guint8 *code,
        emit_label (acfg, symbol);
                
        emit_bytes (acfg, buf, p - buf);
+
+       /* Emit debug info */
+       if (unwind_ops) {
+               char symbol2 [256];
+
+               sprintf (symbol, "%s", name);
+               sprintf (symbol2, ".Lnamed_%s", name);
+
+               if (acfg->dwarf)
+                       mono_dwarf_writer_emit_trampoline (acfg->dwarf, symbol, symbol2, NULL, NULL, code_size, unwind_ops);
+       }
 }
 
-/*
- * When running in aot-only mode, we can't create trampolines at runtime, so we create 
- * a few, and save them in the AOT file. Normal trampolines embed their argument as a 
- * literal inside the trampoline code, we can't do that here, so instead we embed an offset
- * which needs to be added to the trampoline address to get the address of the GOT slot
- * which contains the argument value.
- * The generated trampolines jump to the generic trampolines using another GOT slot, which
- * will be setup by the AOT loader to point to the generic trampoline code of the given 
- * type.
- */
 static void
 emit_trampolines (MonoAotCompile *acfg)
 {
        char symbol [256];
-       int i, offset;
+       int i, tramp_got_offset;
+       MonoAotTrampoline ntype;
 #ifdef MONO_ARCH_HAVE_FULL_AOT_TRAMPOLINES
        int tramp_type;
        guint32 code_size;
        MonoJumpInfo *ji;
        guint8 *code;
+       GSList *unwind_ops;
 #endif
 
        if (!acfg->aot_opts.full_aot)
@@ -3335,133 +2649,181 @@ emit_trampolines (MonoAotCompile *acfg)
                 * method.
                 */
                for (tramp_type = 0; tramp_type < MONO_TRAMPOLINE_NUM; ++tramp_type) {
-                       code = mono_arch_create_trampoline_code_full (tramp_type, &code_size, &ji, TRUE);
+                       code = mono_arch_create_trampoline_code_full (tramp_type, &code_size, &ji, &unwind_ops, TRUE);
 
                        /* Emit trampoline code */
 
                        sprintf (symbol, "generic_trampoline_%d", tramp_type);
 
-                       emit_named_code (acfg, symbol, code, code_size, acfg->got_offset, ji);
+                       emit_trampoline (acfg, symbol, code, code_size, acfg->got_offset, ji, unwind_ops);
                }
 
                code = mono_arch_get_nullified_class_init_trampoline (&code_size);
-               emit_named_code (acfg, "nullified_class_init_trampoline", code, code_size, acfg->got_offset, NULL);
+               emit_trampoline (acfg, "nullified_class_init_trampoline", code, code_size, acfg->got_offset, NULL, NULL);
+#if defined(TARGET_AMD64) && defined(MONO_ARCH_MONITOR_OBJECT_REG)
+               code = mono_arch_create_monitor_enter_trampoline_full (&code_size, &ji, TRUE);
+               emit_trampoline (acfg, "monitor_enter_trampoline", code, code_size, acfg->got_offset, ji, NULL);
+               code = mono_arch_create_monitor_exit_trampoline_full (&code_size, &ji, TRUE);
+               emit_trampoline (acfg, "monitor_exit_trampoline", code, code_size, acfg->got_offset, ji, NULL);
+#endif
+
+               code = mono_arch_create_generic_class_init_trampoline_full (&code_size, &ji, TRUE);
+               emit_trampoline (acfg, "generic_class_init_trampoline", code, code_size, acfg->got_offset, ji, NULL);
 
                /* Emit the exception related code pieces */
                code = mono_arch_get_restore_context_full (&code_size, &ji, TRUE);
-               emit_named_code (acfg, "restore_context", code, code_size, acfg->got_offset, ji);
+               emit_trampoline (acfg, "restore_context", code, code_size, acfg->got_offset, ji, NULL);
                code = mono_arch_get_call_filter_full (&code_size, &ji, TRUE);
-               emit_named_code (acfg, "call_filter", code, code_size, acfg->got_offset, ji);
+               emit_trampoline (acfg, "call_filter", code, code_size, acfg->got_offset, ji, NULL);
                code = mono_arch_get_throw_exception_full (&code_size, &ji, TRUE);
-               emit_named_code (acfg, "throw_exception", code, code_size, acfg->got_offset, ji);
+               emit_trampoline (acfg, "throw_exception", code, code_size, acfg->got_offset, ji, NULL);
                code = mono_arch_get_rethrow_exception_full (&code_size, &ji, TRUE);
-               emit_named_code (acfg, "rethrow_exception", code, code_size, acfg->got_offset, ji);
+               emit_trampoline (acfg, "rethrow_exception", code, code_size, acfg->got_offset, ji, NULL);
                code = mono_arch_get_throw_exception_by_name_full (&code_size, &ji, TRUE);
-               emit_named_code (acfg, "throw_exception_by_name", code, code_size, acfg->got_offset, ji);
+               emit_trampoline (acfg, "throw_exception_by_name", code, code_size, acfg->got_offset, ji, NULL);
                code = mono_arch_get_throw_corlib_exception_full (&code_size, &ji, TRUE);
-               emit_named_code (acfg, "throw_corlib_exception", code, code_size, acfg->got_offset, ji);
+               emit_trampoline (acfg, "throw_corlib_exception", code, code_size, acfg->got_offset, ji, NULL);
+
+#if defined(TARGET_AMD64)
+               code = mono_arch_get_throw_pending_exception_full (&code_size, &ji, TRUE);
+               emit_trampoline (acfg, "throw_pending_exception", code, code_size, acfg->got_offset, ji, NULL);
+#endif
 
-#ifdef __x86_64__
+#if defined(TARGET_AMD64) || defined(TARGET_ARM)
                for (i = 0; i < 128; ++i) {
                        int offset;
 
                        offset = MONO_RGCTX_SLOT_MAKE_RGCTX (i);
                        code = mono_arch_create_rgctx_lazy_fetch_trampoline_full (offset, &code_size, &ji, TRUE);
                        sprintf (symbol, "rgctx_fetch_trampoline_%u", offset);
-                       emit_named_code (acfg, symbol, code, code_size, acfg->got_offset, ji);
+                       emit_trampoline (acfg, symbol, code, code_size, acfg->got_offset, ji, NULL);
 
                        offset = MONO_RGCTX_SLOT_MAKE_MRGCTX (i);
                        code = mono_arch_create_rgctx_lazy_fetch_trampoline_full (offset, &code_size, &ji, TRUE);
                        sprintf (symbol, "rgctx_fetch_trampoline_%u", offset);
-                       emit_named_code (acfg, symbol, code, code_size, acfg->got_offset, ji);
+                       emit_trampoline (acfg, symbol, code, code_size, acfg->got_offset, ji, NULL);
                }
 #endif
+
+#if defined(TARGET_AMD64) || defined(TARGET_ARM)
+               {
+                       GSList *l;
+
+                       /* delegate_invoke_impl trampolines */
+                       l = mono_arch_get_delegate_invoke_impls ();
+                       while (l) {
+                               MonoAotTrampInfo *info = l->data;
+
+                               emit_trampoline (acfg, info->name, info->code, info->code_size, acfg->got_offset, NULL, NULL);
+                               l = l->next;
+                       }
+               }
 #endif
 
+#endif /* #ifdef MONO_ARCH_HAVE_FULL_AOT_TRAMPOLINES */
+
+               /* Emit trampolines which are numerous */
+
+               /*
+                * These include the following:
+                * - specific trampolines
+                * - static rgctx invoke trampolines
+                * - imt thunks
+                * These trampolines have the same code, they are parameterized by GOT 
+                * slots. 
+                * They are defined in this file, in the arch_... routines instead of
+                * in tramp-<ARCH>.c, since it is easier to do it this way.
+                */
+
+               /*
+                * When running in aot-only mode, we can't create specific trampolines at 
+                * runtime, so we create a few, and save them in the AOT file. 
+                * Normal trampolines embed their argument as a literal inside the 
+                * trampoline code, we can't do that here, so instead we embed an offset
+                * which needs to be added to the trampoline address to get the address of
+                * the GOT slot which contains the argument value.
+                * The generated trampolines jump to the generic trampolines using another
+                * GOT slot, which will be setup by the AOT loader to point to the 
+                * generic trampoline code of the given type.
+                */
+
                /*
                 * FIXME: Maybe we should use more specific trampolines (i.e. one class init for
                 * each class).
                 */
 
-               /* Reserve some entries at the end of the GOT for our use */
-               acfg->num_trampoline_got_entries = acfg->num_aot_trampolines * 2;
+               emit_section_change (acfg, ".text", 0);
 
-               sprintf (symbol, "trampolines");
+               tramp_got_offset = acfg->got_offset;
 
-               emit_section_change (acfg, ".text", 0);
-               emit_global (acfg, symbol, TRUE);
-               emit_alignment (acfg, 16);
-               emit_label (acfg, symbol);
+               for (ntype = 0; ntype < MONO_AOT_TRAMP_NUM; ++ntype) {
+                       switch (ntype) {
+                       case MONO_AOT_TRAMP_SPECIFIC:
+                               sprintf (symbol, "specific_trampolines");
+                               break;
+                       case MONO_AOT_TRAMP_STATIC_RGCTX:
+                               sprintf (symbol, "static_rgctx_trampolines");
+                               break;
+                       case MONO_AOT_TRAMP_IMT_THUNK:
+                               sprintf (symbol, "imt_thunks");
+                               break;
+                       default:
+                               g_assert_not_reached ();
+                       }
 
-               for (i = 0; i < acfg->num_aot_trampolines; ++i) {
-                       offset = acfg->got_offset + (i * 2);
+                       emit_global (acfg, symbol, TRUE);
+                       emit_alignment (acfg, 16);
+                       emit_label (acfg, symbol);
 
-                       /*
-                        * The trampolines created here are variations of the specific 
-                        * trampolines created in mono_arch_create_specific_trampoline (). The 
-                        * differences are:
-                        * - the generic trampoline address is taken from a got slot.
-                        * - the offset of the got slot where the trampoline argument is stored
-                        *   is embedded in the instruction stream, and the generic trampoline
-                        *   can load the argument by loading the offset, adding it to the
-                        *   address of the trampoline to get the address of the got slot, and
-                        *   loading the argument from the there.
-                        */
-#if defined(__x86_64__)
-                       /* This should be exactly 16 bytes long */
-                       /* It should work together with the generic trampoline code in tramp-amd64.c */
-                       /* call *<offset>(%rip) */
-                       emit_byte (acfg, '\x41');
-                       emit_byte (acfg, '\xff');
-                       emit_byte (acfg, '\x15');
-                       emit_symbol_diff (acfg, "got", ".", (offset * sizeof (gpointer)) - 4);
-                       /* This should be relative to the start of the trampoline */
-                       emit_symbol_diff (acfg, "got", ".", (offset * sizeof (gpointer)) - 4 + 19);
-                       emit_zero_bytes (acfg, 5);
-#elif defined(__arm__)
-                       {
-                               guint8 buf [128];
-
-                               /* Generate the trampoline code */
-                               /* This should be exactly 28 bytes long */
-
-                               code = buf;
-                               ARM_PUSH (code, 0x5fff);
-                               ARM_LDR_IMM (code, ARMREG_R1, ARMREG_PC, 8);
-                               /* Load the value from the GOT */
-                               ARM_LDR_REG_REG (code, ARMREG_R1, ARMREG_PC, ARMREG_R1);
-                               /* Branch to it */
-                               ARM_MOV_REG_REG (code, ARMREG_LR, ARMREG_PC);
-                               ARM_MOV_REG_REG (code, ARMREG_PC, ARMREG_R1);
-
-                               g_assert (code - buf == 20);
-
-                               /* Emit it */
-                               emit_bytes (acfg, buf, code - buf);
-                               emit_symbol_diff (acfg, "got", ".", (offset * sizeof (gpointer)) - 4 + 8);
-                               emit_symbol_diff (acfg, "got", ".", ((offset + 1) * sizeof (gpointer)) - 4 + 8);
+                       acfg->trampoline_got_offset_base [ntype] = tramp_got_offset;
+
+                       for (i = 0; i < acfg->num_trampolines [ntype]; ++i) {
+                               int tramp_size = 0;
+
+                               switch (ntype) {
+                               case MONO_AOT_TRAMP_SPECIFIC:
+                                       arch_emit_specific_trampoline (acfg, tramp_got_offset, &tramp_size);
+                                       tramp_got_offset += 2;
+                               break;
+                               case MONO_AOT_TRAMP_STATIC_RGCTX:
+                                       arch_emit_static_rgctx_trampoline (acfg, tramp_got_offset, &tramp_size);                                
+                                       tramp_got_offset += 2;
+                                       break;
+                               case MONO_AOT_TRAMP_IMT_THUNK:
+                                       arch_emit_imt_thunk (acfg, tramp_got_offset, &tramp_size);
+                                       tramp_got_offset += 1;
+                                       break;
+                               default:
+                                       g_assert_not_reached ();
+                               }
+
+                               if (!acfg->trampoline_size [ntype]) {
+                                       g_assert (tramp_size);
+                                       acfg->trampoline_size [ntype] = tramp_size;
+                               }
                        }
-#else
-                       g_assert_not_reached ();
-#endif
                }
+
+               /* Reserve some entries at the end of the GOT for our use */
+               acfg->num_trampoline_got_entries = tramp_got_offset - acfg->got_offset;
        }
 
        /* Unbox trampolines */
-
-       for (i = 0; i < acfg->image->tables [MONO_TABLE_METHOD].rows; ++i) {
-               MonoMethod *method;
-               guint32 token = MONO_TOKEN_METHOD_DEF | (i + 1);
+       for (i = 0; i < acfg->methods->len; ++i) {
+               MonoMethod *method = g_ptr_array_index (acfg->methods, i);
                MonoCompile *cfg;
                char call_target [256];
 
-               method = mono_get_method (acfg->image, token, NULL);
-
                cfg = g_hash_table_lookup (acfg->method_to_cfg, method);
                if (!cfg || !cfg->orig_method->klass->valuetype || !(method->flags & METHOD_ATTRIBUTE_VIRTUAL))
                        continue;
 
-               sprintf (symbol, "unbox_trampoline_%d", i);
+               if (!method->wrapper_type && !method->is_inflated) {
+                       g_assert (method->token);
+                       sprintf (symbol, "ut_%d", mono_metadata_token_index (method->token) - 1);
+               } else {
+                       sprintf (symbol, "ut_e_%d", get_method_index (acfg, method));
+               }
 
                emit_section_change (acfg, ".text", 0);
                emit_global (acfg, symbol, TRUE);
@@ -3469,54 +2831,10 @@ emit_trampolines (MonoAotCompile *acfg)
 
                sprintf (call_target, ".Lm_%x", get_method_index (acfg, cfg->orig_method));
 
-#if defined(__x86_64__)
-               {
-                       guint8 buf [32];
-                       int this_reg;
-
-                       this_reg = mono_arch_get_this_arg_reg (mono_method_signature (cfg->orig_method), cfg->generic_sharing_context, NULL);
-                       code = buf;
-                       amd64_alu_reg_imm (code, X86_ADD, this_reg, sizeof (MonoObject));
-
-                       emit_bytes (acfg, buf, code - buf);
-                       /* jump <method> */
-                       emit_byte (acfg, '\xe9');
-                       emit_symbol_diff (acfg, call_target, ".", -4);
-               }
-#elif defined(__arm__)
-               {
-                       guint8 buf [128];
-                       int this_pos = 0;
-
-                       code = buf;
-
-                       if (MONO_TYPE_ISSTRUCT (mono_method_signature (cfg->orig_method)->ret))
-                               this_pos = 1;
-
-                       ARM_ADD_REG_IMM8 (code, this_pos, this_pos, sizeof (MonoObject));
-
-                       emit_bytes (acfg, buf, code - buf);
-                       /* jump to method */
-#if defined(USE_BIN_WRITER)
-                       /* FIXME: */
-                       g_assert_not_reached ();
-#endif
-                       fprintf (acfg->fp, "\n\tb %s\n", call_target);
-               }
-#else
-               g_assert_not_reached ();
-#endif
-       }
-
-       sprintf (symbol, "trampolines_info");
-
-       emit_section_change (acfg, ".text", 0);
-       emit_global (acfg, symbol, TRUE);
-       emit_alignment (acfg, PAGESIZE);
-       emit_label (acfg, symbol);
+               arch_emit_unbox_trampoline (acfg, cfg->orig_method, cfg->generic_sharing_context, call_target);
+       }
 
-       emit_int32 (acfg, acfg->num_aot_trampolines);
-       emit_int32 (acfg, acfg->got_offset);
+       acfg->got_offset += acfg->num_trampoline_got_entries;
 }
 
 static gboolean
@@ -3531,8 +2849,6 @@ mono_aot_parse_options (const char *aot_options, MonoAotOptions *opts)
 {
        gchar **args, **ptr;
 
-       memset (opts, 0, sizeof (*opts));
-
        args = g_strsplit (aot_options ? aot_options : "", ",", -1);
        for (ptr = args; ptr && *ptr; ptr ++) {
                const char *arg = *ptr;
@@ -3551,15 +2867,6 @@ mono_aot_parse_options (const char *aot_options, MonoAotOptions *opts)
                        opts->bind_to_runtime_version = TRUE;
                } else if (str_begins_with (arg, "full")) {
                        opts->full_aot = TRUE;
-                       /*
-                        * The no-dlsym option is only useful on the iphone, and even there,
-                        * do to other limitations of the dynamic linker, it doesn't seem to
-                        * work. So disable it for now so we don't have to support it.
-                        */
-                       /*
-               } else if (str_begins_with (arg, "no-dlsym")) {
-                       opts->no_dlsym = TRUE;
-                       */
                } else if (str_begins_with (arg, "threads=")) {
                        opts->nthreads = atoi (arg + strlen ("threads="));
                } else if (str_begins_with (arg, "static")) {
@@ -3567,6 +2874,12 @@ mono_aot_parse_options (const char *aot_options, MonoAotOptions *opts)
                        opts->no_dlsym = TRUE;
                } else if (str_begins_with (arg, "asmonly")) {
                        opts->asm_only = TRUE;
+               } else if (str_begins_with (arg, "asmwriter")) {
+                       opts->asm_writer = TRUE;
+               } else if (str_begins_with (arg, "nodebug")) {
+                       opts->nodebug = TRUE;
+               } else if (str_begins_with (arg, "ntrampolines=")) {
+                       opts->ntrampolines = atoi (arg + strlen ("ntrampolines="));
                } else {
                        fprintf (stderr, "AOT : Unknown argument '%s'.\n", arg);
                        exit (1);
@@ -3589,6 +2902,88 @@ add_token_info_hash (gpointer key, gpointer value, gpointer user_data)
        g_hash_table_insert (acfg->token_info_hash, method, new_ji);
 }
 
+static gboolean
+can_encode_class (MonoAotCompile *acfg, MonoClass *klass)
+{
+       if (klass->type_token)
+               return TRUE;
+       if ((klass->byval_arg.type == MONO_TYPE_VAR) || (klass->byval_arg.type == MONO_TYPE_MVAR))
+               return TRUE;
+       if (klass->rank)
+               return can_encode_class (acfg, klass->element_class);
+       return FALSE;
+}
+
+static gboolean
+can_encode_patch (MonoAotCompile *acfg, MonoJumpInfo *patch_info)
+{
+       switch (patch_info->type) {
+       case MONO_PATCH_INFO_METHOD:
+       case MONO_PATCH_INFO_METHODCONST: {
+               MonoMethod *method = patch_info->data.method;
+
+               if (method->wrapper_type) {
+                       switch (method->wrapper_type) {
+                       case MONO_WRAPPER_NONE:
+                       case MONO_WRAPPER_REMOTING_INVOKE_WITH_CHECK:
+                       case MONO_WRAPPER_XDOMAIN_INVOKE:
+                       case MONO_WRAPPER_STFLD:
+                       case MONO_WRAPPER_LDFLD:
+                       case MONO_WRAPPER_LDFLDA:
+                       case MONO_WRAPPER_LDFLD_REMOTE:
+                       case MONO_WRAPPER_STFLD_REMOTE:
+                       case MONO_WRAPPER_STELEMREF:
+                       case MONO_WRAPPER_ISINST:
+                       case MONO_WRAPPER_PROXY_ISINST:
+                       case MONO_WRAPPER_ALLOC:
+                       case MONO_WRAPPER_REMOTING_INVOKE:
+                       case MONO_WRAPPER_STATIC_RGCTX_INVOKE:
+                       case MONO_WRAPPER_UNKNOWN:
+                               break;
+                       default:
+                               //printf ("Skip (wrapper call): %d -> %s\n", patch_info->type, mono_method_full_name (patch_info->data.method, TRUE));
+                               return FALSE;
+                       }
+               } else {
+                       if (!method->token) {
+                               /* The method is part of a constructed type like Int[,].Set (). */
+                               if (!g_hash_table_lookup (acfg->token_info_hash, method)) {
+                                       if (method->klass->rank)
+                                               return TRUE;
+                                       return FALSE;
+                               }
+                       }
+               }
+               break;
+       }
+       case MONO_PATCH_INFO_VTABLE:
+       case MONO_PATCH_INFO_CLASS_INIT:
+       case MONO_PATCH_INFO_DELEGATE_TRAMPOLINE:
+       case MONO_PATCH_INFO_CLASS:
+       case MONO_PATCH_INFO_IID:
+       case MONO_PATCH_INFO_ADJUSTED_IID:
+               if (!can_encode_class (acfg, patch_info->data.klass)) {
+                       //printf ("Skip: %s\n", mono_type_full_name (&patch_info->data.klass->byval_arg));
+                       return FALSE;
+               }
+               break;
+       case MONO_PATCH_INFO_RGCTX_FETCH: {
+               MonoJumpInfoRgctxEntry *entry = patch_info->data.rgctx_entry;
+
+               if (!can_encode_patch (acfg, entry->data))
+                       return FALSE;
+               break;
+       }
+       default:
+               break;
+       }
+
+       return TRUE;
+}
+
+static void
+add_generic_class (MonoAotCompile *acfg, MonoClass *klass);
+
 /*
  * compile_method:
  *
@@ -3629,14 +3024,6 @@ compile_method (MonoAotCompile *acfg, MonoMethod *method)
 
        InterlockedIncrement (&acfg->stats.mcount);
 
-       if (method->iflags & METHOD_IMPL_ATTRIBUTE_SYNCHRONIZED) {
-               /* 
-                * FIXME: Enabling this causes virtual-sync.exe to fail, since the trampoline
-                * code can't determine that it needs to insert a sync wrapper in the AOT case.
-                */
-               return;
-       }
-
 #if 0
        if (method->is_generic || method->klass->generic_container) {
                InterlockedIncrement (&acfg->stats.genericcount);
@@ -3644,8 +3031,7 @@ compile_method (MonoAotCompile *acfg, MonoMethod *method)
        }
 #endif
 
-       if (acfg->aot_opts.full_aot)
-               mono_use_imt = FALSE;
+       //acfg->aot_opts.print_skipped_methods = TRUE;
 
        /*
         * Since these methods are the only ones which are compiled with
@@ -3665,7 +3051,8 @@ compile_method (MonoAotCompile *acfg, MonoMethod *method)
        }
 
        if (cfg->disable_aot) {
-               //printf ("Skip (other): %s\n", mono_method_full_name (method, TRUE));
+               if (acfg->aot_opts.print_skipped_methods)
+                       printf ("Skip (disabled): %s\n", mono_method_full_name (method, TRUE));
                InterlockedIncrement (&acfg->stats.ocount);
                mono_destroy_compile (cfg);
                return;
@@ -3696,7 +3083,6 @@ compile_method (MonoAotCompile *acfg, MonoMethod *method)
                switch (patch_info->type) {
                case MONO_PATCH_INFO_ABS:
                        /* unable to handle this */
-                       //printf ("Skip (abs addr):   %s %d\n", mono_method_full_name (method, TRUE), patch_info->type);
                        skip = TRUE;    
                        break;
                default:
@@ -3705,62 +3091,13 @@ compile_method (MonoAotCompile *acfg, MonoMethod *method)
        }
 
        if (skip) {
+               if (acfg->aot_opts.print_skipped_methods)
+                       printf ("Skip (abs call): %s\n", mono_method_full_name (method, TRUE));
                InterlockedIncrement (&acfg->stats.abscount);
                mono_destroy_compile (cfg);
                return;
        }
 
-       /*
-        * Check for wrapper methods we can't encode.
-        */
-       skip = FALSE;
-       for (patch_info = cfg->patch_info; patch_info; patch_info = patch_info->next) {
-               if ((patch_info->type == MONO_PATCH_INFO_METHODCONST) || (patch_info->type == MONO_PATCH_INFO_METHOD)) {
-                       switch (patch_info->data.method->wrapper_type) {
-                       case MONO_WRAPPER_NONE:
-                       case MONO_WRAPPER_REMOTING_INVOKE_WITH_CHECK:
-                       case MONO_WRAPPER_XDOMAIN_INVOKE:
-                       case MONO_WRAPPER_STFLD:
-                       case MONO_WRAPPER_LDFLD:
-                       case MONO_WRAPPER_LDFLDA:
-                       case MONO_WRAPPER_LDFLD_REMOTE:
-                       case MONO_WRAPPER_STFLD_REMOTE:
-                       case MONO_WRAPPER_STELEMREF:
-                       case MONO_WRAPPER_ISINST:
-                       case MONO_WRAPPER_PROXY_ISINST:
-                       case MONO_WRAPPER_ALLOC:
-                       case MONO_WRAPPER_REMOTING_INVOKE:
-                       case MONO_WRAPPER_STATIC_RGCTX_INVOKE:
-                       case MONO_WRAPPER_MONITOR_FAST_ENTER:
-                       case MONO_WRAPPER_MONITOR_FAST_EXIT:
-                               break;
-                       default:
-                               /* unable to handle this */
-                               //printf ("Skip (wrapper call):   %s %d -> %s\n", mono_method_full_name (method, TRUE), patch_info->type, mono_method_full_name (patch_info->data.method, TRUE));
-                               skip = TRUE;
-                               break;
-                       }
-               } else if (patch_info->type == MONO_PATCH_INFO_RGCTX_FETCH) {
-                       MonoJumpInfo *child = patch_info->data.rgctx_entry->data;
-
-                       if (child->type == MONO_PATCH_INFO_METHODCONST) {
-                               switch (child->data.method->wrapper_type) {
-                               case MONO_WRAPPER_NONE:
-                               case MONO_WRAPPER_STATIC_RGCTX_INVOKE:
-                                       break;
-                               default:
-                                       skip = TRUE;
-                               }
-                       }
-               }
-       }
-
-       if (skip) {
-               InterlockedIncrement (&acfg->stats.wrappercount);
-               mono_destroy_compile (cfg);
-               return;
-       }
-
        /* Lock for the rest of the code */
        mono_acfg_lock (acfg);
 
@@ -3769,33 +3106,13 @@ compile_method (MonoAotCompile *acfg, MonoMethod *method)
         */
        skip = FALSE;
        for (patch_info = cfg->patch_info; patch_info; patch_info = patch_info->next) {
-               switch (patch_info->type) {
-               case MONO_PATCH_INFO_METHOD:
-               case MONO_PATCH_INFO_METHODCONST:
-                       if (patch_info->data.method->wrapper_type)
-                               break;
-                       if (!patch_info->data.method->token) {
-                               /* The method is part of a constructed type like Int[,].Set (). */
-                               if (!g_hash_table_lookup (acfg->token_info_hash, patch_info->data.method))
-                                       skip = TRUE;
-                       }
-                       break;
-               case MONO_PATCH_INFO_VTABLE:
-               case MONO_PATCH_INFO_CLASS_INIT:
-               case MONO_PATCH_INFO_DELEGATE_TRAMPOLINE:
-               case MONO_PATCH_INFO_CLASS:
-               case MONO_PATCH_INFO_IID:
-               case MONO_PATCH_INFO_ADJUSTED_IID:
-                       if (!patch_info->data.klass->type_token)
-                               if (!patch_info->data.klass->element_class->type_token && !(patch_info->data.klass->element_class->rank && patch_info->data.klass->element_class->element_class->type_token))
-                                       skip = TRUE;
-                       break;
-               default:
-                       break;
-               }
+               if (!can_encode_patch (acfg, patch_info))
+                       skip = TRUE;
        }
 
        if (skip) {
+               if (acfg->aot_opts.print_skipped_methods)
+                       printf ("Skip (patches): %s\n", mono_method_full_name (method, TRUE));
                acfg->stats.ocount++;
                mono_destroy_compile (cfg);
                mono_acfg_unlock (acfg);
@@ -3810,8 +3127,15 @@ compile_method (MonoAotCompile *acfg, MonoMethod *method)
                        if (m->is_inflated) {
                                if (!(mono_class_generic_sharing_enabled (m->klass) &&
                                          mono_method_is_generic_sharable_impl (m, FALSE)) &&
-                                       !method_has_type_vars (m))
-                                       add_extra_method (acfg, m);
+                                       !method_has_type_vars (m)) {
+                                       if (m->iflags & METHOD_IMPL_ATTRIBUTE_INTERNAL_CALL) {
+                                               if (acfg->aot_opts.full_aot)
+                                                       add_extra_method (acfg, mono_marshal_get_native_wrapper (m, TRUE, TRUE));
+                                       } else {
+                                               add_extra_method (acfg, m);
+                                       }
+                               }
+                               add_generic_class (acfg, m->klass);
                        }
                        break;
                }
@@ -3856,6 +3180,42 @@ compile_method (MonoAotCompile *acfg, MonoMethod *method)
                }
                cfg->patch_info = patches;
        }
+       /* Make a copy of the unwind info */
+       {
+               GSList *l, *unwind_ops;
+               MonoUnwindOp *op;
+
+               unwind_ops = NULL;
+               for (l = cfg->unwind_ops; l; l = l->next) {
+                       op = mono_mempool_alloc (acfg->mempool, sizeof (MonoUnwindOp));
+                       memcpy (op, l->data, sizeof (MonoUnwindOp));
+                       unwind_ops = g_slist_prepend_mempool (acfg->mempool, unwind_ops, op);
+               }
+               cfg->unwind_ops = g_slist_reverse (unwind_ops);
+       }
+       /* Make a copy of the argument/local info */
+       {
+               MonoInst **args, **locals;
+               MonoMethodSignature *sig;
+               MonoMethodHeader *header;
+               int i;
+               
+               sig = mono_method_signature (method);
+               args = mono_mempool_alloc (acfg->mempool, sizeof (MonoInst*) * (sig->param_count + sig->hasthis));
+               for (i = 0; i < sig->param_count + sig->hasthis; ++i) {
+                       args [i] = mono_mempool_alloc (acfg->mempool, sizeof (MonoInst));
+                       memcpy (args [i], cfg->args [i], sizeof (MonoInst));
+               }
+               cfg->args = args;
+
+               header = mono_method_get_header (method);
+               locals = mono_mempool_alloc (acfg->mempool, sizeof (MonoInst*) * header->num_locals);
+               for (i = 0; i < header->num_locals; ++i) {
+                       locals [i] = mono_mempool_alloc (acfg->mempool, sizeof (MonoInst));
+                       memcpy (locals [i], cfg->locals [i], sizeof (MonoInst));
+               }
+               cfg->locals = locals;
+       }
 
        /* Free some fields used by cfg to conserve memory */
        mono_mempool_destroy (cfg->mempool);
@@ -3995,7 +3355,7 @@ alloc_got_slots (MonoAotCompile *acfg)
                        MonoCompile *cfg = acfg->cfgs [i];
 
                        for (ji = cfg->patch_info; ji; ji = ji->next) {
-                               if (is_shared_got_patch (ji))
+                               if (mono_aot_is_shared_got_patch (ji))
                                        get_shared_got_offset (acfg, ji);
                        }
                }
@@ -4015,6 +3375,12 @@ emit_code (MonoAotCompile *acfg)
        emit_alignment (acfg, 8);
        emit_label (acfg, symbol);
 
+       /* 
+        * Emit some padding so the local symbol for the first method doesn't have the
+        * same address as 'methods'.
+        */
+       emit_zero_bytes (acfg, 16);
+
        for (l = acfg->method_order; l != NULL; l = l->next) {
                i = GPOINTER_TO_UINT (l->data);
 
@@ -4086,7 +3452,209 @@ emit_info (MonoAotCompile *acfg)
        }
        emit_line (acfg);
 }
+
+#endif /* #if !defined(DISABLE_AOT) && !defined(DISABLE_JIT) */
+
+/*
+ * mono_aot_str_hash:
+ *
+ * Hash function for strings which we use to hash strings for things which are
+ * saved in the AOT image, since g_str_hash () can change.
+ */
+guint
+mono_aot_str_hash (gconstpointer v1)
+{
+       /* Same as g_str_hash () in glib */
+       char *p = (char *) v1;
+       guint hash = *p;
+
+       while (*p++) {
+               if (*p)
+                       hash = (hash << 5) - hash + *p;
+       }
+
+       return hash;
+} 
+
+#define rot(x,k) (((x)<<(k)) | ((x)>>(32-(k))))
+#define mix(a,b,c) { \
+       a -= c;  a ^= rot(c, 4);  c += b; \
+       b -= a;  b ^= rot(a, 6);  a += c; \
+       c -= b;  c ^= rot(b, 8);  b += a; \
+       a -= c;  a ^= rot(c,16);  c += b; \
+       b -= a;  b ^= rot(a,19);  a += c; \
+       c -= b;  c ^= rot(b, 4);  b += a; \
+}
+#define final(a,b,c) { \
+       c ^= b; c -= rot(b,14); \
+       a ^= c; a -= rot(c,11); \
+       b ^= a; b -= rot(a,25); \
+       c ^= b; c -= rot(b,16); \
+       a ^= c; a -= rot(c,4);  \
+       b ^= a; b -= rot(a,14); \
+       c ^= b; c -= rot(b,24); \
+}
+
+/*
+ * mono_aot_method_hash:
+ *
+ *   Return a hash code for methods which only depends on metadata.
+ */
+guint32
+mono_aot_method_hash (MonoMethod *method)
+{
+       MonoMethodSignature *sig;
+       MonoClass *klass;
+       int i;
+       int hashes_count;
+       guint32 *hashes_start, *hashes;
+       guint32 a, b, c;
+
+       /* Similar to the hash in mono_method_get_imt_slot () */
+
+       sig = mono_method_signature (method);
+
+       hashes_count = sig->param_count + 5;
+       hashes_start = malloc (hashes_count * sizeof (guint32));
+       hashes = hashes_start;
+
+       /* Some wrappers are assigned to random classes */
+       if (!method->wrapper_type || method->wrapper_type == MONO_WRAPPER_REMOTING_INVOKE_WITH_CHECK)
+               klass = method->klass;
+       else
+               klass = mono_defaults.object_class;
+
+       if (!method->wrapper_type) {
+               char *full_name = mono_type_full_name (&klass->byval_arg);
+
+               hashes [0] = mono_aot_str_hash (full_name);
+               hashes [1] = 0;
+               g_free (full_name);
+       } else {
+               hashes [0] = mono_aot_str_hash (klass->name);
+               hashes [1] = mono_aot_str_hash (klass->name_space);
+       }
+       hashes [2] = mono_aot_str_hash (method->name);
+       hashes [3] = method->wrapper_type;
+       hashes [4] = mono_metadata_type_hash (sig->ret);
+       for (i = 0; i < sig->param_count; i++) {
+               /* This is needed for some reason */
+               if (method->wrapper_type && sig->params [i]->type == MONO_TYPE_GENERICINST)
+                       hashes [5 + i] = MONO_TYPE_GENERICINST;
+               else
+                       hashes [5 + i] = mono_metadata_type_hash (sig->params [i]);
+       }
+       
+       /* Setup internal state */
+       a = b = c = 0xdeadbeef + (((guint32)hashes_count)<<2);
+
+       /* Handle most of the hashes */
+       while (hashes_count > 3) {
+               a += hashes [0];
+               b += hashes [1];
+               c += hashes [2];
+               mix (a,b,c);
+               hashes_count -= 3;
+               hashes += 3;
+       }
+
+       /* Handle the last 3 hashes (all the case statements fall through) */
+       switch (hashes_count) { 
+       case 3 : c += hashes [2];
+       case 2 : b += hashes [1];
+       case 1 : a += hashes [0];
+               final (a,b,c);
+       case 0: /* nothing left to add */
+               break;
+       }
+       
+       free (hashes_start);
+       
+       return c;
+}
+#undef rot
+#undef mix
+#undef final
+
+/*
+ * mono_aot_wrapper_name:
+ *
+ *   Return a string which uniqely identifies the given wrapper method.
+ */
+char*
+mono_aot_wrapper_name (MonoMethod *method)
+{
+       char *name, *tmpsig, *klass_desc;
+
+       tmpsig = mono_signature_get_desc (mono_method_signature (method), TRUE);
+
+       switch (method->wrapper_type) {
+       case MONO_WRAPPER_RUNTIME_INVOKE:
+       case MONO_WRAPPER_DELEGATE_INVOKE:
+       case MONO_WRAPPER_DELEGATE_BEGIN_INVOKE:
+       case MONO_WRAPPER_DELEGATE_END_INVOKE:
+               /* This is a hack to work around the fact that runtime invoke wrappers get assigned to some random class */
+               name = g_strdup_printf ("%s (%s)", method->name, tmpsig);
+               break;
+       default:
+               klass_desc = mono_type_full_name (&method->klass->byval_arg);
+
+               name = g_strdup_printf ("%s:%s (%s)", klass_desc, method->name, tmpsig);
+               break;
+       }
+
+       g_free (tmpsig);
+
+       return name;
+}
+
+/*
+ * mono_aot_tramp_info_create:
+ *
+ *   Create a MonoAotTrampInfo structure from the arguments.
+ */
+MonoAotTrampInfo*
+mono_aot_tramp_info_create (const char *name, guint8 *code, guint32 code_size)
+{
+       MonoAotTrampInfo *info = g_new0 (MonoAotTrampInfo, 1);
+
+       info->name = (char*)name;
+       info->code = code;
+       info->code_size = code_size;
+
+       return info;
+}
+
+/*
+ * mono_is_shared_got_patch:
+ *
+ *   Return whenever PATCH_INFO refers to a patch which needs a shared GOT
+ * entry.
+ */
+gboolean
+mono_aot_is_shared_got_patch (MonoJumpInfo *patch_info)
+{
+       switch (patch_info->type) {
+       case MONO_PATCH_INFO_VTABLE:
+       case MONO_PATCH_INFO_CLASS:
+       case MONO_PATCH_INFO_IID:
+       case MONO_PATCH_INFO_ADJUSTED_IID:
+       case MONO_PATCH_INFO_FIELD:
+       case MONO_PATCH_INFO_SFLDA:
+       case MONO_PATCH_INFO_DECLSEC:
+       case MONO_PATCH_INFO_LDTOKEN:
+       case MONO_PATCH_INFO_TYPE_FROM_HANDLE:
+       case MONO_PATCH_INFO_RVA:
+       case MONO_PATCH_INFO_METHODCONST:
+       case MONO_PATCH_INFO_IMAGE:
+               return TRUE;
+       default:
+               return FALSE;
+       }
+}
+
+#if !defined(DISABLE_AOT) && !defined(DISABLE_JIT)
+
 typedef struct HashEntry {
     guint32 key, value, index;
        struct HashEntry *next;
@@ -4107,7 +3675,8 @@ emit_extra_methods (MonoAotCompile *acfg)
        guint32 hash;
        GPtrArray *table;
        HashEntry *entry, *new_entry;
-       int nmethods;
+       int nmethods, max_chain_length;
+       int *chain_lengths;
 
        info_offsets = g_new0 (guint32, acfg->extra_methods->len);
 
@@ -4122,6 +3691,7 @@ emit_extra_methods (MonoAotCompile *acfg)
        for (i = 0; i < acfg->extra_methods->len; ++i) {
                MonoMethod *method = g_ptr_array_index (acfg->extra_methods, i);
                MonoCompile *cfg = g_hash_table_lookup (acfg->method_to_cfg, method);
+               char *name;
 
                if (!cfg)
                        continue;
@@ -4129,19 +3699,27 @@ emit_extra_methods (MonoAotCompile *acfg)
                nmethods ++;
                info_offsets [i] = p - buf;
 
+               name = NULL;
                if (method->wrapper_type) {
-                       char *name;
-
-                       // FIXME: Optimize disk usage
-                       if (method->wrapper_type == MONO_WRAPPER_RUNTIME_INVOKE) {
-                               char *tmpsig = mono_signature_get_desc (mono_method_signature (method), TRUE);
-                               name = g_strdup_printf ("(wrapper runtime-invoke):%s (%s)", method->name, tmpsig);
-                               g_free (tmpsig);
-                       } else {
-                               name = mono_method_full_name (cfg->orig_method, TRUE);
+                       /* 
+                        * We encode some wrappers using their name, since encoding them
+                        * directly would be difficult. This also avoids creating the wrapper
+                        * methods at runtime, since they are not needed anyway.
+                        */
+                       switch (method->wrapper_type) {
+                       case MONO_WRAPPER_REMOTING_INVOKE_WITH_CHECK:
+                       case MONO_WRAPPER_SYNCHRONIZED:
+                               /* encode_method_ref () can handle these */
+                               break;
+                       default:
+                               name = mono_aot_wrapper_name (method);
+                               break;
                        }
+               }
 
+               if (name) {
                        encode_value (1, p, &p);
+                       encode_value (method->wrapper_type, p, &p);
                        strcpy ((char*)p, name);
                        p += strlen (name ) + 1;
                        g_free (name);
@@ -4174,6 +3752,8 @@ emit_extra_methods (MonoAotCompile *acfg)
        table = g_ptr_array_sized_new (table_size);
        for (i = 0; i < table_size; ++i)
                g_ptr_array_add (table, NULL);
+       chain_lengths = g_new0 (int, table_size);
+       max_chain_length = 0;
        for (i = 0; i < acfg->extra_methods->len; ++i) {
                MonoMethod *method = g_ptr_array_index (acfg->extra_methods, i);
                MonoCompile *cfg = g_hash_table_lookup (acfg->method_to_cfg, method);
@@ -4185,12 +3765,10 @@ emit_extra_methods (MonoAotCompile *acfg)
                key = info_offsets [i];
                value = get_method_index (acfg, method);
 
-               if (method->wrapper_type) {
-                       hash = g_str_hash (method->name) % table_size;
-               } else {
-                       // FIXME:
-                       hash = 0 % table_size;
-               }
+               hash = mono_aot_method_hash (method) % table_size;
+
+               chain_lengths [hash] ++;
+               max_chain_length = MAX (max_chain_length, chain_lengths [hash]);
 
                /* FIXME: Allocate from the mempool */
                new_entry = g_new0 (HashEntry, 1);
@@ -4211,6 +3789,8 @@ emit_extra_methods (MonoAotCompile *acfg)
                }
        }
 
+       //printf ("MAX: %d\n", max_chain_length);
+
        /* Emit the table */
        sprintf (symbol, "extra_method_table");
        emit_section_change (acfg, ".text", 0);
@@ -4340,7 +3920,43 @@ emit_exception_info (MonoAotCompile *acfg)
                        emit_int32 (acfg, 0);
                }
        }
-       emit_line (acfg);
+       emit_line (acfg);
+}
+
+static void
+emit_unwind_info (MonoAotCompile *acfg)
+{
+       int i;
+       char symbol [128];
+
+       /* 
+        * The unwind info contains a lot of duplicates so we emit each unique
+        * entry once, and only store the offset from the start of the table in the
+        * exception info.
+        */
+
+       sprintf (symbol, "unwind_info");
+       emit_section_change (acfg, ".text", 1);
+       emit_alignment (acfg, 8);
+       emit_label (acfg, symbol);
+       emit_global (acfg, symbol, FALSE);
+
+       for (i = 0; i < acfg->unwind_ops->len; ++i) {
+               guint32 index = GPOINTER_TO_UINT (g_ptr_array_index (acfg->unwind_ops, i));
+               guint8 *unwind_info;
+               guint32 unwind_info_len;
+               guint8 buf [16];
+               guint8 *p;
+
+               unwind_info = mono_get_cached_unwind_info (index, &unwind_info_len);
+
+               p = buf;
+               encode_value (unwind_info_len, p, &p);
+               emit_bytes (acfg, buf, p - buf);
+               emit_bytes (acfg, unwind_info, unwind_info_len);
+
+               acfg->stats.unwind_info_size += (p - buf) + unwind_info_len;
+       }
 }
 
 static void
@@ -4398,7 +4014,7 @@ emit_class_name_table (MonoAotCompile *acfg)
                token = MONO_TOKEN_TYPE_DEF | (i + 1);
                klass = mono_class_get (acfg->image, token);
                full_name = mono_type_get_name_full (mono_class_get_type (klass), MONO_TYPE_NAME_FORMAT_FULL_NAME);
-               hash = g_str_hash (full_name) % table_size;
+               hash = mono_aot_str_hash (full_name) % table_size;
                g_free (full_name);
 
                /* FIXME: Allocate from the mempool */
@@ -4489,10 +4105,21 @@ static void
 emit_got_info (MonoAotCompile *acfg)
 {
        char symbol [256];
-       int i, buf_size;
+       int i, first_plt_got_patch, buf_size;
        guint8 *p, *buf;
        guint32 *got_info_offsets;
 
+       /* Add the patches needed by the PLT to the GOT */
+       acfg->plt_got_offset_base = acfg->got_offset;
+       first_plt_got_patch = acfg->shared_patches->len;
+       for (i = 1; i < acfg->plt_offset; ++i) {
+               MonoJumpInfo *patch_info = g_hash_table_lookup (acfg->plt_offset_to_patch, GUINT_TO_POINTER (i));
+
+               g_ptr_array_add (acfg->shared_patches, patch_info);
+       }
+
+       acfg->got_offset += acfg->plt_offset;
+
        /**
         * FIXME: 
         * - optimize offsets table.
@@ -4508,11 +4135,16 @@ emit_got_info (MonoAotCompile *acfg)
        buf_size = acfg->shared_patches->len * 64;
        p = buf = mono_mempool_alloc (acfg->mempool, buf_size);
        got_info_offsets = mono_mempool_alloc (acfg->mempool, acfg->shared_patches->len * sizeof (guint32));
+       acfg->plt_got_info_offsets = mono_mempool_alloc (acfg->mempool, acfg->plt_offset * sizeof (guint32));
        for (i = 0; i < acfg->shared_patches->len; ++i) {
                MonoJumpInfo *ji = g_ptr_array_index (acfg->shared_patches, i);
 
-               /* No need to encode the patch type */
                got_info_offsets [i] = p - buf;
+               /* No need to encode the patch type for non-PLT patches */
+               if (i >= first_plt_got_patch) {
+                       acfg->plt_got_info_offsets [i - first_plt_got_patch + 1] = got_info_offsets [i];
+                       encode_value (ji->type, p, &p);
+               }
                encode_patch (acfg, ji, p, &p);
        }
 
@@ -4549,31 +4181,25 @@ emit_got (MonoAotCompile *acfg)
 
        /* Don't make GOT global so accesses to it don't need relocations */
        sprintf (symbol, "got");
-       emit_section_change (acfg, ".bss", 1);
+       emit_section_change (acfg, ".bss", 0);
        emit_alignment (acfg, 8);
        emit_label (acfg, symbol);
-       if ((acfg->got_offset + acfg->num_trampoline_got_entries) > 0)
-               emit_zero_bytes (acfg, (int)((acfg->got_offset + acfg->num_trampoline_got_entries) * sizeof (gpointer)));
+       if (acfg->got_offset > 0)
+               emit_zero_bytes (acfg, (int)(acfg->got_offset * sizeof (gpointer)));
 
-       sprintf (symbol, "got_addr");
-       emit_section_change (acfg, ".data", 1);
+       sprintf (symbol, "mono_aot_got_addr");
+       emit_section_change (acfg, ".data", 0);
        emit_global (acfg, symbol, FALSE);
        emit_alignment (acfg, 8);
        emit_label (acfg, symbol);
        emit_pointer (acfg, "got");
-
-       sprintf (symbol, "got_size");
-       emit_section_change (acfg, ".data", 1);
-       emit_global (acfg, symbol, FALSE);
-       emit_alignment (acfg, 8);
-       emit_label (acfg, symbol);
-       emit_int32 (acfg, (int)(acfg->got_offset * sizeof (gpointer)));
 }
 
 static void
 emit_globals (MonoAotCompile *acfg)
 {
        char *opts_str;
+       char *build_info;
 
        emit_string_symbol (acfg, "mono_assembly_guid" , acfg->image->guid);
 
@@ -4585,25 +4211,24 @@ emit_globals (MonoAotCompile *acfg)
 
        emit_string_symbol (acfg, "mono_aot_full_aot", acfg->aot_opts.full_aot ? "TRUE" : "FALSE");
 
-       if (acfg->aot_opts.bind_to_runtime_version)
-               emit_string_symbol (acfg, "mono_runtime_version", FULL_VERSION);
-       else
+       if (acfg->aot_opts.bind_to_runtime_version) {
+               build_info = mono_get_runtime_build_info ();
+               emit_string_symbol (acfg, "mono_runtime_version", build_info);
+               g_free (build_info);
+       } else {
                emit_string_symbol (acfg, "mono_runtime_version", "");
+       }
 
-       /*
-        * Some platforms like the iphone have no working dlsym (). To work around this,
-        * we create an ELF ctor function which will be invoked by dlopen, and which
-        * will call a function in the AOT loader to register the symbols used by the
-        * image.
+       /* 
         * When static linking, we emit a global which will point to the symbol table.
         */
-       if (acfg->aot_opts.no_dlsym) {
+       if (acfg->aot_opts.static_link) {
                int i;
                char symbol [256];
+               char *p;
 
-               if (acfg->aot_opts.static_link)
-                       /* Emit a string holding the assembly name */
-                       emit_string_symbol (acfg, "mono_aot_assembly_name", acfg->image->assembly->aname.name);
+               /* Emit a string holding the assembly name */
+               emit_string_symbol (acfg, "mono_aot_assembly_name", acfg->image->assembly->aname.name);
 
                /* Emit the names */
                for (i = 0; i < acfg->globals->len; ++i) {
@@ -4615,116 +4240,347 @@ emit_globals (MonoAotCompile *acfg)
                        emit_string (acfg, name);
                }
 
-               /* Emit the globals table */
-               sprintf (symbol, "globals");
-               emit_section_change (acfg, ".data", 0);
-               /* This is not a global, since it is accessed by the init function */
-               emit_alignment (acfg, 8);
-               emit_label (acfg, symbol);
+               /* Emit the globals table */
+               sprintf (symbol, "globals");
+               emit_section_change (acfg, ".data", 0);
+               /* This is not a global, since it is accessed by the init function */
+               emit_alignment (acfg, 8);
+               emit_label (acfg, symbol);
+
+               for (i = 0; i < acfg->globals->len; ++i) {
+                       char *name = g_ptr_array_index (acfg->globals, i);
+
+                       sprintf (symbol, "name_%d", i);
+                       emit_pointer (acfg, symbol);
+
+                       sprintf (symbol, "%s", name);
+                       emit_pointer (acfg, symbol);
+               }
+               /* Null terminate the table */
+               emit_int32 (acfg, 0);
+               emit_int32 (acfg, 0);
+
+               /* 
+                * Emit a global symbol which can be passed by an embedding app to
+                * mono_aot_register_module ().
+                */
+#if defined(__MACH__)
+               sprintf (symbol, "_mono_aot_module_%s_info", acfg->image->assembly->aname.name);
+#else
+               sprintf (symbol, "mono_aot_module_%s_info", acfg->image->assembly->aname.name);
+#endif
+
+               /* Get rid of characters which cannot occur in symbols */
+               p = symbol;
+               for (p = symbol; *p; ++p) {
+                       if (!(isalnum (*p) || *p == '_'))
+                               *p = '_';
+               }
+               acfg->static_linking_symbol = g_strdup (symbol);
+               emit_global_inner (acfg, symbol, FALSE);
+               emit_alignment (acfg, 8);
+               emit_label (acfg, symbol);
+               emit_pointer (acfg, "globals");
+       }
+}
+
+static void
+emit_mem_end (MonoAotCompile *acfg)
+{
+       char symbol [128];
+
+       sprintf (symbol, "mem_end");
+       emit_section_change (acfg, ".text", 1);
+       emit_global (acfg, symbol, FALSE);
+       emit_alignment (acfg, 8);
+       emit_label (acfg, symbol);
+}
+
+/*
+ * Emit a structure containing all the information not stored elsewhere.
+ */
+static void
+emit_file_info (MonoAotCompile *acfg)
+{
+       char symbol [128];
+       int i;
+
+       sprintf (symbol, "mono_aot_file_info");
+       emit_section_change (acfg, ".data", 0);
+       emit_alignment (acfg, 8);
+       emit_label (acfg, symbol);
+       emit_global (acfg, symbol, FALSE);
+
+       /* The data emitted here must match MonoAotFileInfo in aot-runtime.c. */
+       emit_int32 (acfg, acfg->plt_got_offset_base);
+       emit_int32 (acfg, (int)(acfg->got_offset * sizeof (gpointer)));
+       emit_int32 (acfg, acfg->plt_offset);
+
+       for (i = 0; i < MONO_AOT_TRAMP_NUM; ++i)
+               emit_int32 (acfg, acfg->num_trampolines [i]);
+       for (i = 0; i < MONO_AOT_TRAMP_NUM; ++i)
+               emit_int32 (acfg, acfg->trampoline_got_offset_base [i]);
+       for (i = 0; i < MONO_AOT_TRAMP_NUM; ++i)
+               emit_int32 (acfg, acfg->trampoline_size [i]);
+}
+
+static void
+emit_dwarf_info (MonoAotCompile *acfg)
+{
+#ifdef EMIT_DWARF_INFO
+       int i;
+       char symbol [128], symbol2 [128];
+
+       /* DIEs for methods */
+       for (i = 0; i < acfg->nmethods; ++i) {
+               MonoCompile *cfg = acfg->cfgs [i];
+
+               if (!cfg)
+                       continue;
+
+               sprintf (symbol, ".Lm_%x", i);
+               sprintf (symbol2, ".Lme_%x", i);
+
+               mono_dwarf_writer_emit_method (acfg->dwarf, cfg, cfg->method, symbol, symbol2, NULL, 0, cfg->args, cfg->locals, cfg->unwind_ops, NULL);
+       }
+#endif
+}
+
+static void
+collect_methods (MonoAotCompile *acfg)
+{
+       int i;
+       MonoImage *image = acfg->image;
+
+       /* Collect methods */
+       for (i = 0; i < image->tables [MONO_TABLE_METHOD].rows; ++i) {
+               MonoMethod *method;
+               guint32 token = MONO_TOKEN_METHOD_DEF | (i + 1);
+
+               method = mono_get_method (acfg->image, token, NULL);
+
+               if (!method) {
+                       printf ("Failed to load method 0x%x from '%s'.\n", token, image->name);
+                       exit (1);
+               }
+                       
+               /* Load all methods eagerly to skip the slower lazy loading code */
+               mono_class_setup_methods (method->klass);
+
+               if (acfg->aot_opts.full_aot && method->iflags & METHOD_IMPL_ATTRIBUTE_INTERNAL_CALL) {
+                       /* Compile the wrapper instead */
+                       /* We do this here instead of add_wrappers () because it is easy to do it here */
+                       MonoMethod *wrapper = mono_marshal_get_native_wrapper (method, check_for_pending_exc, TRUE);
+                       method = wrapper;
+               }
+
+               /* Since we add the normal methods first, their index will be equal to their zero based token index */
+               add_method_with_index (acfg, method, i);
+               acfg->method_index ++;
+       }
+
+       add_generic_instances (acfg);
+
+       if (acfg->aot_opts.full_aot)
+               add_wrappers (acfg);
+}
+
+static void
+compile_methods (MonoAotCompile *acfg)
+{
+       int i, methods_len;
+
+       if (acfg->aot_opts.nthreads > 0) {
+               GPtrArray *frag;
+               int len, j;
+               GPtrArray *threads;
+               HANDLE handle;
+               gpointer *user_data;
+               MonoMethod **methods;
+
+               methods_len = acfg->methods->len;
+
+               len = acfg->methods->len / acfg->aot_opts.nthreads;
+               g_assert (len > 0);
+               /* 
+                * Partition the list of methods into fragments, and hand it to threads to
+                * process.
+                */
+               threads = g_ptr_array_new ();
+               /* Make a copy since acfg->methods is modified by compile_method () */
+               methods = g_new0 (MonoMethod*, methods_len);
+               //memcpy (methods, g_ptr_array_index (acfg->methods, 0), sizeof (MonoMethod*) * methods_len);
+               for (i = 0; i < methods_len; ++i)
+                       methods [i] = g_ptr_array_index (acfg->methods, i);
+               i = 0;
+               while (i < methods_len) {
+                       frag = g_ptr_array_new ();
+                       for (j = 0; j < len; ++j) {
+                               if (i < methods_len) {
+                                       g_ptr_array_add (frag, methods [i]);
+                                       i ++;
+                               }
+                       }
+
+                       user_data = g_new0 (gpointer, 3);
+                       user_data [0] = mono_domain_get ();
+                       user_data [1] = acfg;
+                       user_data [2] = frag;
+                       
+                       handle = mono_create_thread (NULL, 0, (gpointer)compile_thread_main, user_data, 0, NULL);
+                       g_ptr_array_add (threads, handle);
+               }
+               g_free (methods);
+
+               for (i = 0; i < threads->len; ++i) {
+                       WaitForSingleObjectEx (g_ptr_array_index (threads, i), INFINITE, FALSE);
+               }
+       } else {
+               methods_len = 0;
+       }
+
+       /* Compile methods added by compile_method () or all methods if nthreads == 0 */
+       for (i = methods_len; i < acfg->methods->len; ++i) {
+               /* This can new methods to acfg->methods */
+               compile_method (acfg, g_ptr_array_index (acfg->methods, i));
+       }
+}
+
+static int
+compile_asm (MonoAotCompile *acfg)
+{
+       char *command, *objfile;
+       char *outfile_name, *tmp_outfile_name;
+
+#if defined(TARGET_AMD64)
+#define AS_OPTIONS "--64"
+#elif defined(sparc) && SIZEOF_VOID_P == 8
+#define AS_OPTIONS "-xarch=v9"
+#else
+#define AS_OPTIONS ""
+#endif
+
+       if (acfg->aot_opts.asm_only) {
+               printf ("Output file: '%s'.\n", acfg->tmpfname);
+               if (acfg->aot_opts.static_link)
+                       printf ("Linking symbol: '%s'.\n", acfg->static_linking_symbol);
+               return 0;
+       }
+
+       if (acfg->aot_opts.static_link) {
+               if (acfg->aot_opts.outfile)
+                       objfile = g_strdup_printf ("%s", acfg->aot_opts.outfile);
+               else
+                       objfile = g_strdup_printf ("%s.o", acfg->image->name);
+       } else {
+               objfile = g_strdup_printf ("%s.o", acfg->tmpfname);
+       }
+       command = g_strdup_printf ("as %s %s -o %s", AS_OPTIONS, acfg->tmpfname, objfile);
+       printf ("Executing the native assembler: %s\n", command);
+       if (system (command) != 0) {
+               g_free (command);
+               g_free (objfile);
+               return 1;
+       }
+
+       g_free (command);
+
+       if (acfg->aot_opts.static_link) {
+               printf ("Output file: '%s'.\n", objfile);
+               printf ("Linking symbol: '%s'.\n", acfg->static_linking_symbol);
+               g_free (objfile);
+               return 0;
+       }
+
+       if (acfg->aot_opts.outfile)
+               outfile_name = g_strdup_printf ("%s", acfg->aot_opts.outfile);
+       else
+               outfile_name = g_strdup_printf ("%s%s", acfg->image->name, SHARED_EXT);
+
+       tmp_outfile_name = g_strdup_printf ("%s.tmp", outfile_name);
+
+#if defined(sparc)
+       command = g_strdup_printf ("ld -shared -G -o %s %s.o", tmp_outfile_name, acfg->tmpfname);
+#elif defined(__ppc__) && defined(__MACH__)
+       command = g_strdup_printf ("gcc -dynamiclib -o %s %s.o", tmp_outfile_name, acfg->tmpfname);
+#elif defined(PLATFORM_WIN32)
+       command = g_strdup_printf ("gcc -shared --dll -mno-cygwin -o %s %s.o", tmp_outfile_name, acfg->tmpfname);
+#else
+       command = g_strdup_printf ("ld -shared -o %s %s.o", tmp_outfile_name, acfg->tmpfname);
+#endif
+       printf ("Executing the native linker: %s\n", command);
+       if (system (command) != 0) {
+               g_free (tmp_outfile_name);
+               g_free (outfile_name);
+               g_free (command);
+               g_free (objfile);
+               return 1;
+       }
+
+       g_free (command);
+       unlink (objfile);
+       /*com = g_strdup_printf ("strip --strip-unneeded %s%s", acfg->image->name, SHARED_EXT);
+       printf ("Stripping the binary: %s\n", com);
+       system (com);
+       g_free (com);*/
 
-               for (i = 0; i < acfg->globals->len; ++i) {
-                       char *name = g_ptr_array_index (acfg->globals, i);
+#if defined(TARGET_ARM) && !defined(__MACH__)
+       /* 
+        * gas generates 'mapping symbols' each time code and data is mixed, which 
+        * happens a lot in emit_and_reloc_code (), so we need to get rid of them.
+        */
+       command = g_strdup_printf ("strip --strip-symbol=\\$a --strip-symbol=\\$d %s", tmp_outfile_name);
+       printf ("Stripping the binary: %s\n", command);
+       if (system (command) != 0) {
+               g_free (tmp_outfile_name);
+               g_free (outfile_name);
+               g_free (command);
+               g_free (objfile);
+               return 1;
+       }
+#endif
 
-                       sprintf (symbol, "name_%d", i);
-                       emit_pointer (acfg, symbol);
+       rename (tmp_outfile_name, outfile_name);
 
-                       sprintf (symbol, "%s", name);
-                       emit_pointer (acfg, symbol);
-               }
-               /* Null terminate the table */
-               emit_pointer (acfg, NULL);
-               emit_pointer (acfg, NULL);
+       g_free (tmp_outfile_name);
+       g_free (outfile_name);
+       g_free (objfile);
 
-               if (acfg->aot_opts.static_link) {
-                       char *p;
+       if (acfg->aot_opts.save_temps)
+               printf ("Retained input file.\n");
+       else
+               unlink (acfg->tmpfname);
 
-                       /* 
-                        * Emit a global symbol which can be passed by an embedding app to
-                        * mono_aot_register_module ().
-                        */
-#if defined(__MACH__)
-                       sprintf (symbol, "_mono_aot_module_%s_info", acfg->image->assembly->aname.name);
-#else
-                       sprintf (symbol, "mono_aot_module_%s_info", acfg->image->assembly->aname.name);
-#endif
+       return 0;
+}
 
-                       /* Get rid of characters which cannot occur in symbols */
-                       p = symbol;
-                       for (p = symbol; *p; ++p) {
-                               if (!(isalnum (*p) || *p == '_'))
-                                       *p = '_';
-                       }
-                       acfg->static_linking_symbol = g_strdup (symbol);
-                       emit_global_inner (acfg, symbol, FALSE);
-                       emit_alignment (acfg, 8);
-                       emit_label (acfg, symbol);
-                       emit_pointer (acfg, "globals");
-               } else {
-                       sprintf (symbol, "init_%s", acfg->image->assembly->aname.name);
-                       emit_section_change (acfg, ".text", 1);
-                       emit_alignment (acfg, 8);
-                       emit_label (acfg, symbol);
-#ifdef USE_BIN_WRITER
-                       g_assert_not_reached ();
-#else
-#ifdef __x86_64__
-                       fprintf (acfg->fp, "leaq globals(%%rip), %%rdi\n");
-                       fprintf (acfg->fp, "call mono_aot_register_globals@PLT\n");
-                       fprintf (acfg->fp, "ret\n");
-                       fprintf (acfg->fp, ".section .ctors,\"aw\",@progbits\n");
-                       emit_alignment (acfg, 8);
-                       emit_pointer (acfg, symbol);
-#elif defined(__arm__) && defined(__MACH__)
-                               
-                       fprintf (acfg->fp, ".text\n");
-                       fprintf (acfg->fp, ".align   3\n");
-               
-                       fprintf (acfg->fp, "ldr r0, .L5\n");
-                       fprintf (acfg->fp, ".LPIC0:\n");
-                       fprintf (acfg->fp, "add r0, pc, r0\n");
-                       fprintf (acfg->fp, "ldr r0, [r0]\n");
-                       fprintf (acfg->fp, "b   _mono_aot_register_globals@PLT\n");
-                       fprintf (acfg->fp, ".align 2\n");
-
-                       fprintf (acfg->fp, ".L5:\n");
-                       fprintf (acfg->fp, ".long       globals_ptr-(.LPIC0+8)\n");
-                       
-                       fprintf (acfg->fp, ".data\n");
-                       fprintf (acfg->fp, ".align      2\n");
-                       fprintf (acfg->fp, "globals_ptr:\n");
-                       fprintf (acfg->fp, ".long       globals\n");
-                       
-                       fprintf (acfg->fp, ".mod_init_func\n");
-                       fprintf (acfg->fp, ".align      2\n");
-                       fprintf (acfg->fp, ".long       %s@target1\n", symbol);
+static MonoAotCompile*
+acfg_create (MonoAssembly *ass, guint32 opts)
+{
+       MonoImage *image = ass->image;
+       MonoAotCompile *acfg;
 
-#elif defined(__arm__)
-                       /* 
-                        * Taken from gcc generated code for:
-                        * static int i;
-                        * void foo () { bar (&i); }
-                        * gcc --shared -fPIC -O2
-                        */
-                       fprintf (acfg->fp, "ldr r3, .L5\n");
-                       fprintf (acfg->fp, "ldr r0, .L5+4\n");
-                       fprintf (acfg->fp, ".LPIC0:\n");
-                       fprintf (acfg->fp, "add r3, pc, r3\n");
-                       fprintf (acfg->fp, "add r0, r3, r0\n");
-                       fprintf (acfg->fp, "b   mono_aot_register_globals(PLT)\n");
-
-                       fprintf (acfg->fp, ".L5:\n");
-                       fprintf (acfg->fp, ".word       _GLOBAL_OFFSET_TABLE_-(.LPIC0+8)\n");
-                       fprintf (acfg->fp, ".word       globals(GOTOFF)\n");
-
-                       fprintf (acfg->fp, ".section    .init_array,\"aw\",%%init_array\n");
-                       fprintf (acfg->fp, ".align      2\n");
-                       fprintf (acfg->fp, ".word       %s(target1)\n", symbol);
-#else
-                       g_assert_not_reached ();
-#endif
-#endif
-               }
-       }
+       acfg = g_new0 (MonoAotCompile, 1);
+       acfg->methods = g_ptr_array_new ();
+       acfg->method_indexes = g_hash_table_new (NULL, NULL);
+       acfg->plt_offset_to_patch = g_hash_table_new (NULL, NULL);
+       acfg->patch_to_plt_offset = g_hash_table_new (mono_patch_info_hash, mono_patch_info_equal);
+       acfg->patch_to_shared_got_offset = g_hash_table_new (mono_patch_info_hash, mono_patch_info_equal);
+       acfg->shared_patches = g_ptr_array_new ();
+       acfg->method_to_cfg = g_hash_table_new (NULL, NULL);
+       acfg->token_info_hash = g_hash_table_new_full (NULL, NULL, NULL, g_free);
+       acfg->image_hash = g_hash_table_new (NULL, NULL);
+       acfg->image_table = g_ptr_array_new ();
+       acfg->globals = g_ptr_array_new ();
+       acfg->image = image;
+       acfg->opts = opts;
+       acfg->mempool = mono_mempool_new ();
+       acfg->extra_methods = g_ptr_array_new ();
+       acfg->unwind_info_offsets = g_hash_table_new (NULL, NULL);
+       acfg->unwind_ops = g_ptr_array_new ();
+       InitializeCriticalSection (&acfg->mutex);
+
+       return acfg;
 }
 
 static void
@@ -4732,6 +4588,7 @@ acfg_free (MonoAotCompile *acfg)
 {
        int i;
 
+       img_writer_destroy (acfg->w);
        for (i = 0; i < acfg->nmethods; ++i)
                if (acfg->cfgs [i])
                        g_free (acfg->cfgs [i]);
@@ -4741,6 +4598,7 @@ acfg_free (MonoAotCompile *acfg)
        g_ptr_array_free (acfg->shared_patches, TRUE);
        g_ptr_array_free (acfg->image_table, TRUE);
        g_ptr_array_free (acfg->globals, TRUE);
+       g_ptr_array_free (acfg->unwind_ops, TRUE);
        g_hash_table_destroy (acfg->method_indexes);
        g_hash_table_destroy (acfg->plt_offset_to_patch);
        g_hash_table_destroy (acfg->patch_to_plt_offset);
@@ -4748,6 +4606,7 @@ acfg_free (MonoAotCompile *acfg)
        g_hash_table_destroy (acfg->method_to_cfg);
        g_hash_table_destroy (acfg->token_info_hash);
        g_hash_table_destroy (acfg->image_hash);
+       g_hash_table_destroy (acfg->unwind_info_offsets);
        mono_mempool_destroy (acfg->mempool);
        g_free (acfg);
 }
@@ -4756,68 +4615,80 @@ int
 mono_compile_assembly (MonoAssembly *ass, guint32 opts, const char *aot_options)
 {
        MonoImage *image = ass->image;
-       char symbol [256];
-       int i, res, methods_len;
+       int res;
        MonoAotCompile *acfg;
+       char *outfile_name, *tmp_outfile_name;
        TV_DECLARE (atv);
        TV_DECLARE (btv);
 
        printf ("Mono Ahead of Time compiler - compiling assembly %s\n", image->name);
 
-       acfg = g_new0 (MonoAotCompile, 1);
-       acfg->methods = g_ptr_array_new ();
-       acfg->method_indexes = g_hash_table_new (NULL, NULL);
-       acfg->plt_offset_to_patch = g_hash_table_new (NULL, NULL);
-       acfg->patch_to_plt_offset = g_hash_table_new (mono_patch_info_hash, mono_patch_info_equal);
-       acfg->patch_to_shared_got_offset = g_hash_table_new (mono_patch_info_hash, mono_patch_info_equal);
-       acfg->shared_patches = g_ptr_array_new ();
-       acfg->method_to_cfg = g_hash_table_new (NULL, NULL);
-       acfg->token_info_hash = g_hash_table_new_full (NULL, NULL, NULL, g_free);
-       acfg->image_hash = g_hash_table_new (NULL, NULL);
-       acfg->image_table = g_ptr_array_new ();
-       acfg->globals = g_ptr_array_new ();
-       acfg->image = image;
-       acfg->opts = opts;
-       acfg->mempool = mono_mempool_new ();
-       acfg->extra_methods = g_ptr_array_new ();
-       InitializeCriticalSection (&acfg->mutex);
+       acfg = acfg_create (ass, opts);
 
-       mono_aot_parse_options (aot_options, &acfg->aot_opts);
+       memset (&acfg->aot_opts, 0, sizeof (acfg->aot_opts));
+       acfg->aot_opts.write_symbols = TRUE;
+       acfg->aot_opts.ntrampolines = 10240;
 
-       load_profile_files (acfg);
+       mono_aot_parse_options (aot_options, &acfg->aot_opts);
 
-       emit_start (acfg);
+       //acfg->aot_opts.print_skipped_methods = TRUE;
 
-       acfg->num_aot_trampolines = acfg->aot_opts.full_aot ? 10240 : 0;
+#ifndef MONO_ARCH_HAVE_FULL_AOT_TRAMPOLINES
+       if (acfg->aot_opts.full_aot) {
+               printf ("--aot=full is not supported on this platform.\n");
+               return 1;
+       }
+#endif
 
-       acfg->method_index = 1;
+       if (acfg->aot_opts.static_link)
+               acfg->aot_opts.asm_writer = TRUE;
 
-       /* Collect methods */
-       for (i = 0; i < image->tables [MONO_TABLE_METHOD].rows; ++i) {
-               MonoMethod *method;
-               guint32 token = MONO_TOKEN_METHOD_DEF | (i + 1);
+       if (!acfg->aot_opts.asm_only && !acfg->aot_opts.asm_writer && bin_writer_supported ()) {
+               if (acfg->aot_opts.outfile)
+                       outfile_name = g_strdup_printf ("%s", acfg->aot_opts.outfile);
+               else
+                       outfile_name = g_strdup_printf ("%s%s", acfg->image->name, SHARED_EXT);
 
-               method = mono_get_method (acfg->image, token, NULL);
+               tmp_outfile_name = g_strdup_printf ("%s.tmp", outfile_name);
 
-               /* Load all methods eagerly to skip the slower lazy loading code */
-               mono_class_setup_methods (method->klass);
+               acfg->fp = fopen (tmp_outfile_name, "w");
+               g_assert (acfg->fp);
 
-               if (acfg->aot_opts.full_aot && method->iflags & METHOD_IMPL_ATTRIBUTE_INTERNAL_CALL) {
-                       /* Compile the wrapper instead */
-                       /* We do this here instead of add_wrappers () because it is easy to do it here */
-                       MonoMethod *wrapper = mono_marshal_get_native_wrapper (method, check_for_pending_exc, TRUE);
-                       method = wrapper;
+               acfg->w = img_writer_create (acfg->fp, TRUE);
+               acfg->use_bin_writer = TRUE;
+       } else {
+               if (acfg->aot_opts.asm_only) {
+                       if (acfg->aot_opts.outfile)
+                               acfg->tmpfname = g_strdup_printf ("%s", acfg->aot_opts.outfile);
+                       else
+                               acfg->tmpfname = g_strdup_printf ("%s.s", acfg->image->name);
+                       acfg->fp = fopen (acfg->tmpfname, "w+");
+               } else {
+                       int i = g_file_open_tmp ("mono_aot_XXXXXX", &acfg->tmpfname, NULL);
+                       acfg->fp = fdopen (i, "w+");
                }
+               g_assert (acfg->fp);
 
-               /* Since we add the normal methods first, their index will be equal to their zero based token index */
-               add_method_with_index (acfg, method, i);
-               acfg->method_index ++;
+               acfg->w = img_writer_create (acfg->fp, FALSE);
+               
+               tmp_outfile_name = NULL;
+               outfile_name = NULL;
        }
 
-       add_generic_instances (acfg);
+       load_profile_files (acfg);
 
-       if (acfg->aot_opts.full_aot)
-               add_wrappers (acfg);
+       if (!acfg->aot_opts.nodebug)
+               acfg->dwarf = mono_dwarf_writer_create (acfg->w, NULL);
+
+       acfg->num_trampolines [MONO_AOT_TRAMP_SPECIFIC] = acfg->aot_opts.full_aot ? acfg->aot_opts.ntrampolines : 0;
+#ifdef MONO_ARCH_HAVE_STATIC_RGCTX_TRAMPOLINE
+       acfg->num_trampolines [MONO_AOT_TRAMP_STATIC_RGCTX] = acfg->aot_opts.full_aot ? 1024 : 0;
+#endif
+       acfg->num_trampolines [MONO_AOT_TRAMP_IMT_THUNK] = acfg->aot_opts.full_aot ? 128 : 0;
+
+       acfg->method_index = 1;
+
+       collect_methods (acfg);
 
        acfg->cfgs_size = acfg->methods->len + 32;
        acfg->cfgs = g_new0 (MonoCompile*, acfg->cfgs_size);
@@ -4825,72 +4696,23 @@ mono_compile_assembly (MonoAssembly *ass, guint32 opts, const char *aot_options)
        /* PLT offset 0 is reserved for the PLT trampoline */
        acfg->plt_offset = 1;
 
-       /* Compile methods */
        TV_GETTIME (atv);
 
-       if (acfg->aot_opts.nthreads > 0) {
-               GPtrArray *frag;
-               int len, j;
-               GPtrArray *threads;
-               HANDLE handle;
-               gpointer *user_data;
-               MonoMethod **methods;
-
-               methods_len = acfg->methods->len;
-
-               len = acfg->methods->len / acfg->aot_opts.nthreads;
-               g_assert (len > 0);
-               /* 
-                * Partition the list of methods into fragments, and hand it to threads to
-                * process.
-                */
-               threads = g_ptr_array_new ();
-               /* Make a copy since acfg->methods is modified by compile_method () */
-               methods = g_new0 (MonoMethod*, methods_len);
-               //memcpy (methods, g_ptr_array_index (acfg->methods, 0), sizeof (MonoMethod*) * methods_len);
-               for (i = 0; i < methods_len; ++i)
-                       methods [i] = g_ptr_array_index (acfg->methods, i);
-               i = 0;
-               while (i < methods_len) {
-                       frag = g_ptr_array_new ();
-                       for (j = 0; j < len; ++j) {
-                               if (i < methods_len) {
-                                       g_ptr_array_add (frag, methods [i]);
-                                       i ++;
-                               }
-                       }
-
-                       user_data = g_new0 (gpointer, 3);
-                       user_data [0] = mono_domain_get ();
-                       user_data [1] = acfg;
-                       user_data [2] = frag;
-                       
-                       handle = CreateThread (NULL, 0, (gpointer)compile_thread_main, user_data, 0, NULL);
-                       g_ptr_array_add (threads, handle);
-               }
-               g_free (methods);
-
-               for (i = 0; i < threads->len; ++i) {
-                       WaitForSingleObjectEx (g_ptr_array_index (threads, i), INFINITE, FALSE);
-               }
-       } else {
-               methods_len = 0;
-       }
-
-       /* Compile methods added by compile_method () or all methods if nthreads == 0 */
-       for (i = methods_len; i < acfg->methods->len; ++i) {
-               /* This can new methods to acfg->methods */
-               compile_method (acfg, g_ptr_array_index (acfg->methods, i));
-       }
+       compile_methods (acfg);
 
        TV_GETTIME (btv);
+
        acfg->stats.jit_time = TV_ELAPSED (atv, btv);
 
        TV_GETTIME (atv);
 
        alloc_got_slots (acfg);
 
+       img_writer_emit_start (acfg->w);
+
+       if (acfg->dwarf)
+               mono_dwarf_writer_emit_base_info (acfg->dwarf, arch_get_cie_program ());
+
        emit_code (acfg);
 
        emit_info (acfg);
@@ -4907,6 +4729,8 @@ mono_compile_assembly (MonoAssembly *ass, guint32 opts, const char *aot_options)
 
        emit_exception_info (acfg);
 
+       emit_unwind_info (acfg);
+
        emit_class_info (acfg);
 
        emit_plt (acfg);
@@ -4915,26 +4739,36 @@ mono_compile_assembly (MonoAssembly *ass, guint32 opts, const char *aot_options)
 
        emit_got (acfg);
 
+       emit_file_info (acfg);
+
        emit_globals (acfg);
 
-       sprintf (symbol, "mem_end");
-       emit_section_change (acfg, ".text", 1);
-       emit_global (acfg, symbol, FALSE);
-       emit_alignment (acfg, 8);
-       emit_label (acfg, symbol);
+       if (acfg->dwarf)
+               emit_dwarf_info (acfg);
+
+       emit_mem_end (acfg);
 
        TV_GETTIME (btv);
 
        acfg->stats.gen_time = TV_ELAPSED (atv, btv);
 
-       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)));
+       printf ("Code: %d Info: %d Ex Info: %d Unwind Info: %d Class Info: %d PLT: %d GOT Info: %d GOT Info Offsets: %d GOT: %d\n", acfg->stats.code_size, acfg->stats.info_size, acfg->stats.ex_info_size, acfg->stats.unwind_info_size, acfg->stats.class_info_size, acfg->plt_offset, acfg->stats.got_info_size, acfg->stats.got_info_offsets_size, (int)(acfg->got_offset * sizeof (gpointer)));
 
        TV_GETTIME (atv);
-       res = emit_writeout (acfg);
+       res = img_writer_emit_writeout (acfg->w);
        if (res != 0) {
                acfg_free (acfg);
                return res;
        }
+       if (acfg->use_bin_writer) {
+               rename (tmp_outfile_name, outfile_name);
+       } else {
+               res = compile_asm (acfg);
+               if (res != 0) {
+                       acfg_free (acfg);
+                       return res;
+               }
+       }
        TV_GETTIME (btv);
        acfg->stats.link_time = TV_ELAPSED (atv, btv);
 
@@ -4943,25 +4777,116 @@ mono_compile_assembly (MonoAssembly *ass, guint32 opts, const char *aot_options)
                printf ("%d methods are generic (%d%%)\n", acfg->stats.genericcount, acfg->stats.mcount ? (acfg->stats.genericcount * 100) / acfg->stats.mcount : 100);
        if (acfg->stats.abscount)
                printf ("%d methods contain absolute addresses (%d%%)\n", acfg->stats.abscount, acfg->stats.mcount ? (acfg->stats.abscount * 100) / acfg->stats.mcount : 100);
-       if (acfg->stats.wrappercount)
-               printf ("%d methods contain wrapper references (%d%%)\n", acfg->stats.wrappercount, acfg->stats.mcount ? (acfg->stats.wrappercount * 100) / acfg->stats.mcount : 100);
        if (acfg->stats.lmfcount)
                printf ("%d methods contain lmf pointers (%d%%)\n", acfg->stats.lmfcount, acfg->stats.mcount ? (acfg->stats.lmfcount * 100) / acfg->stats.mcount : 100);
        if (acfg->stats.ocount)
                printf ("%d methods have other problems (%d%%)\n", acfg->stats.ocount, acfg->stats.mcount ? (acfg->stats.ocount * 100) / acfg->stats.mcount : 100);
        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);
        printf ("Direct calls: %d (%d%%)\n", acfg->stats.direct_calls, acfg->stats.all_calls ? (acfg->stats.direct_calls * 100) / acfg->stats.all_calls : 100);
-       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);
 
+       /*
        printf ("GOT slot distribution:\n");
        for (i = 0; i < MONO_PATCH_INFO_NONE; ++i)
                if (acfg->stats.got_slot_types [i])
                        printf ("\t%s: %d\n", get_patch_name (i), acfg->stats.got_slot_types [i]);
+       */
+
+       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);
 
        acfg_free (acfg);
        
        return 0;
 }
+/*
+ * Support for emitting debug info for JITted code.
+ *
+ *   This works as follows:
+ * - the runtime writes out an xdb.s file containing DWARF debug info.
+ * - the user calls a gdb macro
+ * - the macro compiles and loads this shared library using add-symbol-file.
+ *
+ * This is based on the xdebug functionality in the Kaffe Java VM.
+ * 
+ * We emit assembly code instead of using the ELF writer, so we can emit debug info
+ * incrementally as each method is JITted, and the debugger doesn't have to call
+ * into the runtime to emit the shared library, which would cause all kinds of
+ * complications, like threading issues, and the fact that the ELF writer's
+ * emit_writeout () function cannot be called more than once.
+ */
+
+/* The recommended gdb macro is: */
+/*
+  define xdb
+  shell rm -f xdb.so && as --64 -o xdb.o xdb.s && ld -shared -o xdb.so xdb.o
+  add-symbol-file xdb.so 0
+  end
+*/
+
+static MonoDwarfWriter *xdebug_writer;
+static FILE *xdebug_fp;
+
+void
+mono_xdebug_init (void)
+{
+       FILE *il_file;
+       MonoImageWriter *w;
+
+       unlink ("xdb.s");
+       xdebug_fp = fopen ("xdb.s", "w");
+
+       w = img_writer_create (xdebug_fp, FALSE);
+
+       img_writer_emit_start (w);
+
+       /* This file will contain the IL code for methods which don't have debug info */
+       il_file = fopen ("xdb.il", "w");
+
+       xdebug_writer = mono_dwarf_writer_create (w, il_file);
+
+       /* Emit something so the file has a text segment */
+       img_writer_emit_section_change (w, ".text", 0);
+       img_writer_emit_string (w, "");
+
+       mono_dwarf_writer_emit_base_info (xdebug_writer, arch_get_cie_program ());
+}
+
+/*
+ * mono_save_xdebug_info:
+ *
+ *   Emit debugging info for METHOD into an assembly file which can be assembled
+ * and loaded into gdb to provide debugging info for JITted code.
+ * LOCKING: Acquires the loader lock.
+ */
+void
+mono_save_xdebug_info (MonoCompile *cfg)
+{
+       if (!xdebug_writer)
+               return;
+
+       mono_loader_lock ();
+       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 ()));
+       fflush (xdebug_fp);
+       mono_loader_unlock ();
+}
+
+/*
+ * mono_save_trampoline_xdebug_info:
+ *
+ *   Same as mono_save_xdebug_info, but for trampolines.
+ * LOCKING: Acquires the loader lock.
+ */
+void
+mono_save_trampoline_xdebug_info (const char *tramp_name, guint8 *code, guint32 code_size, GSList *unwind_info)
+{
+       if (!xdebug_writer)
+               return;
+
+       mono_loader_lock ();
+       mono_dwarf_writer_emit_trampoline (xdebug_writer, tramp_name, NULL, NULL, code, code_size, unwind_info);
+       fflush (xdebug_fp);
+       mono_loader_unlock ();
+}
 
 #else
 
@@ -4973,4 +4898,19 @@ mono_compile_assembly (MonoAssembly *ass, guint32 opts, const char *aot_options)
        return 0;
 }
 
+void
+mono_xdebug_init (void)
+{
+}
+
+void
+mono_save_xdebug_info (MonoCompile *cfg)
+{
+}
+
+void
+mono_save_trampoline_xdebug_info (const char *tramp_name, guint8 *code, guint32 code_size, GSList *unwind_info)
+{
+}
+
 #endif