Add an assert () to thread_suspend_func ().
[mono.git] / mono / mini / mini-gc.c
1 /*
2  * mini-gc.c: GC interface for the mono JIT
3  *
4  * Author:
5  *   Zoltan Varga (vargaz@gmail.com)
6  *
7  * Copyright 2009 Novell, Inc (http://www.novell.com)
8  * Copyright 2011 Xamarin, Inc (http://www.xamarin.com)
9  */
10
11 #include "config.h"
12 #include "mini-gc.h"
13 #include <mono/metadata/gc-internal.h>
14
15 //#if 0
16 #if defined(MONO_ARCH_GC_MAPS_SUPPORTED)
17
18 #include <mono/metadata/gc-internal.h>
19 #include <mono/utils/mono-counters.h>
20
21 #if SIZEOF_VOID_P == 4
22 typedef guint32 mword;
23 #else
24 typedef guint64 mword;
25 #endif
26
27 #define SIZEOF_SLOT ((int)sizeof (mgreg_t))
28
29 #define GC_BITS_PER_WORD (sizeof (mword) * 8)
30
31 /* Contains state needed by the GC Map construction code */
32 typedef struct {
33         /*
34          * This contains information about stack slots initialized in the prolog, encoded using
35          * (slot_index << 16) | slot_type. The slot_index is relative to the CFA, i.e. 0
36          * means cfa+0, 1 means cfa-4/8, etc.
37          */
38         GSList *stack_slots_from_cfa;
39         /* Same for stack slots relative to the frame pointer */
40         GSList *stack_slots_from_fp;
41
42         /* Number of slots in the map */
43         int nslots;
44         /* The number of registers in the map */
45         int nregs;
46         /* Min and Max offsets of the stack frame relative to fp */
47         int min_offset, max_offset;
48         /* Same for the locals area */
49         int locals_min_offset, locals_max_offset;
50
51         /* The call sites where this frame can be stopped during GC */
52         GCCallSite **callsites;
53         /* The number of call sites */
54         int ncallsites;
55
56         /*
57          * The width of the stack bitmaps in bytes. This is not equal to the bitmap width at
58      * runtime, since it includes columns which are 0.
59          */
60         int stack_bitmap_width;
61         /* 
62          * A bitmap whose width equals nslots, and whose height equals ncallsites.
63          * The bitmap contains a 1 if the corresponding stack slot has type SLOT_REF at the
64          * given callsite.
65          */
66         guint8 *stack_ref_bitmap;
67         /* Same for SLOT_PIN */
68         guint8 *stack_pin_bitmap;
69
70         /*
71          * Similar bitmaps for registers. These have width MONO_MAX_IREGS in bits.
72          */
73         int reg_bitmap_width;
74         guint8 *reg_ref_bitmap;
75         guint8 *reg_pin_bitmap;
76 } MonoCompileGC;
77
78 #define ALIGN_TO(val,align) ((((mgreg_t)val) + ((align) - 1)) & ~((align) - 1))
79
80 #undef DEBUG
81
82 #if 0
83 /* We don't support debug levels, its all-or-nothing */
84 #define DEBUG(s) do { s; fflush (logfile); } while (0)
85 #define DEBUG_ENABLED 1
86 #else
87 #define DEBUG(s)
88 #endif
89
90 #ifdef DEBUG_ENABLED
91 //#if 1
92 #define DEBUG_PRECISE(s) do { s; } while (0)
93 #define DEBUG_PRECISE_ENABLED
94 #else
95 #define DEBUG_PRECISE(s)
96 #endif
97
98 /*
99  * Contains information collected during the conservative stack marking pass,
100  * used during the precise pass. This helps to avoid doing a stack walk twice, which
101  * is expensive.
102  */
103 typedef struct {
104         guint8 *bitmap;
105         int nslots;
106     int frame_start_offset;
107         int nreg_locations;
108         /* Relative to stack_start */
109         int reg_locations [MONO_MAX_IREGS];
110 #ifdef DEBUG_PRECISE_ENABLED
111         MonoJitInfo *ji;
112         gpointer fp;
113         int regs [MONO_MAX_IREGS];
114 #endif
115 } FrameInfo;
116
117 /* Max number of frames stored in the TLS data */
118 #define MAX_FRAMES 50
119
120 /*
121  * Per-thread data kept by this module. This is stored in the GC and passed to us as
122  * parameters, instead of being stored in a TLS variable, since during a collection,
123  * only the collection thread is active.
124  */
125 typedef struct {
126         MonoLMF *lmf;
127         MonoContext ctx;
128         gboolean has_context;
129         MonoJitTlsData *jit_tls;
130         /* For debugging */
131         mgreg_t tid;
132         gpointer ref_to_track;
133         /* Number of frames collected during the !precise pass */
134         int nframes;
135         FrameInfo frames [MAX_FRAMES];
136 } TlsData;
137
138 /* These are constant so don't store them in the GC Maps */
139 /* Number of registers stored in gc maps */
140 #define NREGS MONO_MAX_IREGS
141
142 /* 
143  * The GC Map itself.
144  * Contains information needed to mark a stack frame.
145  * This is a transient structure, created from a compressed representation on-demand.
146  */
147 typedef struct {
148         /*
149          * The offsets of the GC tracked area inside the stack frame relative to the frame pointer.
150          * This includes memory which is NOREF thus doesn't need GC maps.
151          */
152         int start_offset;
153         int end_offset;
154         /*
155          * The offset relative to frame_offset where the the memory described by the GC maps
156          * begins.
157          */
158         int map_offset;
159         /* The number of stack slots in the map */
160         int nslots;
161         /* The frame pointer register */
162         guint8 frame_reg;
163         /* The size of each callsite table entry */
164         guint8 callsite_entry_size;
165         guint has_pin_slots : 1;
166         guint has_ref_slots : 1;
167         guint has_ref_regs : 1;
168         guint has_pin_regs : 1;
169
170         /* The offsets below are into an external bitmaps array */
171
172         /* 
173          * A bitmap whose width is equal to bitmap_width, and whose height is equal to ncallsites.
174          * The bitmap contains a 1 if the corresponding stack slot has type SLOT_REF at the
175          * given callsite.
176          */
177         guint32 stack_ref_bitmap_offset;
178         /*
179          * Same for SLOT_PIN. It is possible that the same bit is set in both bitmaps at
180      * different callsites, if the slot starts out as PIN, and later changes to REF.
181          */
182         guint32 stack_pin_bitmap_offset;
183
184         /*
185          * Corresponding bitmaps for registers
186          * These have width equal to the number of bits set in reg_ref_mask/reg_pin_mask.
187          * FIXME: Merge these with the normal bitmaps, i.e. reserve the first x slots for them ?
188          */
189         guint32 reg_pin_bitmap_offset;
190         guint32 reg_ref_bitmap_offset;
191
192         guint32 used_int_regs, reg_ref_mask, reg_pin_mask;
193
194         /* The number of bits set in the two masks above */
195         guint8 nref_regs, npin_regs;
196
197         /*
198          * A bit array marking slots which contain refs.
199          * This is used only for debugging.
200          */
201         //guint8 *ref_slots;
202
203         /* Callsite offsets */
204         /* These can take up a lot of space, so encode them compactly */
205         union {
206                 guint8 *offsets8;
207                 guint16 *offsets16;
208                 guint32 *offsets32;
209         } callsites;
210         int ncallsites;
211 } GCMap;
212
213 /*
214  * A compressed version of GCMap. This is what gets stored in MonoJitInfo.
215  */
216 typedef struct {
217         //guint8 *ref_slots;
218         //guint8 encoded_size;
219
220         /*
221          * The arrays below are embedded after the struct.
222          * Their address needs to be computed.
223          */
224
225         /* The fixed fields of the GCMap encoded using LEB128 */
226         guint8 encoded [MONO_ZERO_LEN_ARRAY];
227
228         /* An array of ncallsites entries, each entry is callsite_entry_size bytes long */
229         guint8 callsites [MONO_ZERO_LEN_ARRAY];
230
231         /* The GC bitmaps */
232         guint8 bitmaps [MONO_ZERO_LEN_ARRAY];
233 } GCEncodedMap;
234
235 static int precise_frame_count [2], precise_frame_limit = -1;
236 static gboolean precise_frame_limit_inited;
237
238 /* Stats */
239 typedef struct {
240         int scanned_stacks;
241         int scanned;
242         int scanned_precisely;
243         int scanned_conservatively;
244         int scanned_registers;
245         int scanned_native;
246         int scanned_other;
247         
248         int all_slots;
249         int noref_slots;
250         int ref_slots;
251         int pin_slots;
252
253         int gc_maps_size;
254         int gc_callsites_size;
255         int gc_callsites8_size;
256         int gc_callsites16_size;
257         int gc_callsites32_size;
258         int gc_bitmaps_size;
259         int gc_map_struct_size;
260         int tlsdata_size;
261 } JITGCStats;
262
263 static JITGCStats stats;
264
265 static FILE *logfile;
266
267 // FIXME: Move these to a shared place
268
269 static inline void
270 encode_uleb128 (guint32 value, guint8 *buf, guint8 **endbuf)
271 {
272         guint8 *p = buf;
273
274         do {
275                 guint8 b = value & 0x7f;
276                 value >>= 7;
277                 if (value != 0) /* more bytes to come */
278                         b |= 0x80;
279                 *p ++ = b;
280         } while (value);
281
282         *endbuf = p;
283 }
284
285 static G_GNUC_UNUSED void
286 encode_sleb128 (gint32 value, guint8 *buf, guint8 **endbuf)
287 {
288         gboolean more = 1;
289         gboolean negative = (value < 0);
290         guint32 size = 32;
291         guint8 byte;
292         guint8 *p = buf;
293
294         while (more) {
295                 byte = value & 0x7f;
296                 value >>= 7;
297                 /* the following is unnecessary if the
298                  * implementation of >>= uses an arithmetic rather
299                  * than logical shift for a signed left operand
300                  */
301                 if (negative)
302                         /* sign extend */
303                         value |= - (1 <<(size - 7));
304                 /* sign bit of byte is second high order bit (0x40) */
305                 if ((value == 0 && !(byte & 0x40)) ||
306                         (value == -1 && (byte & 0x40)))
307                         more = 0;
308                 else
309                         byte |= 0x80;
310                 *p ++= byte;
311         }
312
313         *endbuf = p;
314 }
315
316 static inline guint32
317 decode_uleb128 (guint8 *buf, guint8 **endbuf)
318 {
319         guint8 *p = buf;
320         guint32 res = 0;
321         int shift = 0;
322
323         while (TRUE) {
324                 guint8 b = *p;
325                 p ++;
326
327                 res = res | (((int)(b & 0x7f)) << shift);
328                 if (!(b & 0x80))
329                         break;
330                 shift += 7;
331         }
332
333         *endbuf = p;
334
335         return res;
336 }
337
338 static inline gint32
339 decode_sleb128 (guint8 *buf, guint8 **endbuf)
340 {
341         guint8 *p = buf;
342         gint32 res = 0;
343         int shift = 0;
344
345         while (TRUE) {
346                 guint8 b = *p;
347                 p ++;
348
349                 res = res | (((int)(b & 0x7f)) << shift);
350                 shift += 7;
351                 if (!(b & 0x80)) {
352                         if (shift < 32 && (b & 0x40))
353                                 res |= - (1 << shift);
354                         break;
355                 }
356         }
357
358         *endbuf = p;
359
360         return res;
361 }
362
363 static int
364 encode_frame_reg (int frame_reg)
365 {
366 #ifdef TARGET_AMD64
367         if (frame_reg == AMD64_RSP)
368                 return 0;
369         else if (frame_reg == AMD64_RBP)
370                 return 1;
371 #elif defined(TARGET_X86)
372         if (frame_reg == X86_EBP)
373                 return 0;
374         else if (frame_reg == X86_ESP)
375                 return 1;
376 #elif defined(TARGET_ARM)
377         if (frame_reg == ARMREG_SP)
378                 return 0;
379         else if (frame_reg == ARMREG_FP)
380                 return 1;
381 #else
382         NOT_IMPLEMENTED;
383 #endif
384         g_assert_not_reached ();
385         return -1;
386 }
387
388 static int
389 decode_frame_reg (int encoded)
390 {
391 #ifdef TARGET_AMD64
392         if (encoded == 0)
393                 return AMD64_RSP;
394         else if (encoded == 1)
395                 return AMD64_RBP;
396 #elif defined(TARGET_X86)
397         if (encoded == 0)
398                 return X86_EBP;
399         else if (encoded == 1)
400                 return X86_ESP;
401 #elif defined(TARGET_ARM)
402         if (encoded == 0)
403                 return ARMREG_SP;
404         else if (encoded == 1)
405                 return ARMREG_FP;
406 #else
407         NOT_IMPLEMENTED;
408 #endif
409         g_assert_not_reached ();
410         return -1;
411 }
412
413 #ifdef TARGET_AMD64
414 #ifdef HOST_WIN32
415 static int callee_saved_regs [] = { AMD64_RBP, AMD64_RBX, AMD64_R12, AMD64_R13, AMD64_R14, AMD64_R15, AMD64_RDI, AMD64_RSI };
416 #else
417 static int callee_saved_regs [] = { AMD64_RBP, AMD64_RBX, AMD64_R12, AMD64_R13, AMD64_R14, AMD64_R15 };
418 #endif
419 #elif defined(TARGET_X86)
420 static int callee_saved_regs [] = { X86_EBX, X86_ESI, X86_EDI };
421 #elif defined(TARGET_ARM)
422 static int callee_saved_regs [] = { ARMREG_V1, ARMREG_V2, ARMREG_V3, ARMREG_V4, ARMREG_V5, ARMREG_V7, ARMREG_FP };
423 #endif
424
425 static guint32
426 encode_regmask (guint32 regmask)
427 {
428         int i;
429         guint32 res;
430
431         res = 0;
432         for (i = 0; i < sizeof (callee_saved_regs) / sizeof (int); ++i) {
433                 if (regmask & (1 << callee_saved_regs [i])) {
434                         res |= (1 << i);
435                         regmask -= (1 << callee_saved_regs [i]);
436                 }
437         }
438         g_assert (regmask == 0);
439         return res;
440 }
441
442 static guint32
443 decode_regmask (guint32 regmask)
444 {
445         int i;
446         guint32 res;
447
448         res = 0;
449         for (i = 0; i < sizeof (callee_saved_regs) / sizeof (int); ++i)
450                 if (regmask & (1 << i))
451                         res |= (1 << callee_saved_regs [i]);
452         return res;
453 }
454
455 /*
456  * encode_gc_map:
457  *
458  *   Encode the fixed fields of MAP into a buffer pointed to by BUF.
459  */
460 static void
461 encode_gc_map (GCMap *map, guint8 *buf, guint8 **endbuf)
462 {
463         guint32 flags, freg;
464
465         encode_sleb128 (map->start_offset / SIZEOF_SLOT, buf, &buf);
466         encode_sleb128 (map->end_offset / SIZEOF_SLOT, buf, &buf);
467         encode_sleb128 (map->map_offset / SIZEOF_SLOT, buf, &buf);
468         encode_uleb128 (map->nslots, buf, &buf);
469         g_assert (map->callsite_entry_size <= 4);
470         freg = encode_frame_reg (map->frame_reg);
471         g_assert (freg < 2);
472         flags = (map->has_ref_slots ? 1 : 0) | (map->has_pin_slots ? 2 : 0) | (map->has_ref_regs ? 4 : 0) | (map->has_pin_regs ? 8 : 0) | ((map->callsite_entry_size - 1) << 4) | (freg << 6);
473         encode_uleb128 (flags, buf, &buf);
474         encode_uleb128 (encode_regmask (map->used_int_regs), buf, &buf);
475         if (map->has_ref_regs)
476                 encode_uleb128 (encode_regmask (map->reg_ref_mask), buf, &buf);
477         if (map->has_pin_regs)
478                 encode_uleb128 (encode_regmask (map->reg_pin_mask), buf, &buf);
479         encode_uleb128 (map->ncallsites, buf, &buf);
480
481         *endbuf = buf;
482 }       
483
484 /*
485  * decode_gc_map:
486  *
487  *   Decode the encoded GC map representation in BUF and store the result into MAP.
488  */
489 static void
490 decode_gc_map (guint8 *buf, GCMap *map, guint8 **endbuf)
491 {
492         guint32 flags;
493         int stack_bitmap_size, reg_ref_bitmap_size, reg_pin_bitmap_size, offset, freg;
494         int i, n;
495
496         map->start_offset = decode_sleb128 (buf, &buf) * SIZEOF_SLOT;
497         map->end_offset = decode_sleb128 (buf, &buf) * SIZEOF_SLOT;
498         map->map_offset = decode_sleb128 (buf, &buf) * SIZEOF_SLOT;
499         map->nslots = decode_uleb128 (buf, &buf);
500         flags = decode_uleb128 (buf, &buf);
501         map->has_ref_slots = (flags & 1) ? 1 : 0;
502         map->has_pin_slots = (flags & 2) ? 1 : 0;
503         map->has_ref_regs = (flags & 4) ? 1 : 0;
504         map->has_pin_regs = (flags & 8) ? 1 : 0;
505         map->callsite_entry_size = ((flags >> 4) & 0x3) + 1;
506         freg = flags >> 6;
507         map->frame_reg = decode_frame_reg (freg);
508         map->used_int_regs = decode_regmask (decode_uleb128 (buf, &buf));
509         if (map->has_ref_regs) {
510                 map->reg_ref_mask = decode_regmask (decode_uleb128 (buf, &buf));
511                 n = 0;
512                 for (i = 0; i < NREGS; ++i)
513                         if (map->reg_ref_mask & (1 << i))
514                                 n ++;
515                 map->nref_regs = n;
516         }
517         if (map->has_pin_regs) {
518                 map->reg_pin_mask = decode_regmask (decode_uleb128 (buf, &buf));
519                 n = 0;
520                 for (i = 0; i < NREGS; ++i)
521                         if (map->reg_pin_mask & (1 << i))
522                                 n ++;
523                 map->npin_regs = n;
524         }
525         map->ncallsites = decode_uleb128 (buf, &buf);
526
527         stack_bitmap_size = (ALIGN_TO (map->nslots, 8) / 8) * map->ncallsites;
528         reg_ref_bitmap_size = (ALIGN_TO (map->nref_regs, 8) / 8) * map->ncallsites;
529         reg_pin_bitmap_size = (ALIGN_TO (map->npin_regs, 8) / 8) * map->ncallsites;
530         offset = 0;
531         map->stack_ref_bitmap_offset = offset;
532         if (map->has_ref_slots)
533                 offset += stack_bitmap_size;
534         map->stack_pin_bitmap_offset = offset;
535         if (map->has_pin_slots)
536                 offset += stack_bitmap_size;
537         map->reg_ref_bitmap_offset = offset;
538         if (map->has_ref_regs)
539                 offset += reg_ref_bitmap_size;
540         map->reg_pin_bitmap_offset = offset;
541         if (map->has_pin_regs)
542                 offset += reg_pin_bitmap_size;
543
544         *endbuf = buf;
545 }
546
547 static gpointer
548 thread_attach_func (void)
549 {
550         TlsData *tls;
551
552         tls = g_new0 (TlsData, 1);
553         tls->tid = GetCurrentThreadId ();
554         stats.tlsdata_size += sizeof (TlsData);
555
556         return tls;
557 }
558
559 static void
560 thread_detach_func (gpointer user_data)
561 {
562         TlsData *tls = user_data;
563
564         g_free (tls);
565 }
566
567 static void
568 thread_suspend_func (gpointer user_data, void *sigctx)
569 {
570         TlsData *tls = user_data;
571
572         if (!tls)
573                 /* Happens during startup */
574                 return;
575
576         // FIXME: This isn't true on osx, and we depend on it for mono_get_lmf ().
577         g_assert (tls->tid == GetCurrentThreadId ());
578
579         tls->lmf = mono_get_lmf ();
580         if (sigctx) {
581                 mono_arch_sigctx_to_monoctx (sigctx, &tls->ctx);
582                 tls->has_context = TRUE;
583         } else {
584                 tls->has_context = FALSE;
585         }
586         tls->jit_tls = mono_native_tls_get_value (mono_jit_tls_id);
587 }
588
589 #define DEAD_REF ((gpointer)(gssize)0x2a2a2a2a2a2a2a2aULL)
590
591 static inline void
592 set_bit (guint8 *bitmap, int width, int y, int x)
593 {
594         bitmap [(width * y) + (x / 8)] |= (1 << (x % 8));
595 }
596
597 static inline void
598 clear_bit (guint8 *bitmap, int width, int y, int x)
599 {
600         bitmap [(width * y) + (x / 8)] &= ~(1 << (x % 8));
601 }
602
603 static inline int
604 get_bit (guint8 *bitmap, int width, int y, int x)
605 {
606         return bitmap [(width * y) + (x / 8)] & (1 << (x % 8));
607 }
608
609 static const char*
610 slot_type_to_string (GCSlotType type)
611 {
612         switch (type) {
613         case SLOT_REF:
614                 return "ref";
615         case SLOT_NOREF:
616                 return "noref";
617         case SLOT_PIN:
618                 return "pin";
619         default:
620                 g_assert_not_reached ();
621                 return NULL;
622         }
623 }
624
625 static inline mgreg_t
626 get_frame_pointer (MonoContext *ctx, int frame_reg)
627 {
628 #if defined(TARGET_AMD64)
629                 if (frame_reg == AMD64_RSP)
630                         return ctx->rsp;
631                 else if (frame_reg == AMD64_RBP)
632                         return ctx->rbp;
633 #elif defined(TARGET_X86)
634                 if (frame_reg == X86_ESP)
635                         return ctx->esp;
636                 else if (frame_reg == X86_EBP)
637                         return ctx->ebp;
638 #elif defined(TARGET_ARM)
639                 if (frame_reg == ARMREG_SP)
640                         return (mgreg_t)MONO_CONTEXT_GET_SP (ctx);
641                 else if (frame_reg == ARMREG_FP)
642                         return (mgreg_t)MONO_CONTEXT_GET_BP (ctx);
643 #endif
644                 g_assert_not_reached ();
645                 return 0;
646 }
647
648 /*
649  * conservatively_pass:
650  *
651  *   Mark a thread stack conservatively and collect information needed by the precise pass.
652  */
653 static void
654 conservative_pass (TlsData *tls, guint8 *stack_start, guint8 *stack_end)
655 {
656         MonoJitInfo *ji;
657         MonoContext ctx, new_ctx;
658         MonoLMF *lmf;
659         guint8 *stack_limit;
660         gboolean last = TRUE;
661         GCMap *map;
662         GCMap map_tmp;
663         GCEncodedMap *emap;
664         guint8* fp, *p, *real_frame_start, *frame_start, *frame_end;
665         int i, pc_offset, cindex, bitmap_width;
666         int scanned = 0, scanned_precisely, scanned_conservatively, scanned_registers;
667         gboolean res;
668         StackFrameInfo frame;
669         mgreg_t *reg_locations [MONO_MAX_IREGS];
670         mgreg_t *new_reg_locations [MONO_MAX_IREGS];
671         guint8 *bitmaps;
672         FrameInfo *fi;
673         guint32 precise_regmask;
674
675         if (tls) {
676                 tls->nframes = 0;
677                 tls->ref_to_track = NULL;
678         }
679
680         /* tls == NULL can happen during startup */
681         if (mono_thread_internal_current () == NULL || !tls) {
682                 mono_gc_conservatively_scan_area (stack_start, stack_end);
683                 stats.scanned_stacks += stack_end - stack_start;
684                 return;
685         }
686
687         lmf = tls->lmf;
688         frame.domain = NULL;
689
690         /* Number of bytes scanned based on GC map data */
691         scanned = 0;
692         /* Number of bytes scanned precisely based on GC map data */
693         scanned_precisely = 0;
694         /* Number of bytes scanned conservatively based on GC map data */
695         scanned_conservatively = 0;
696         /* Number of bytes scanned conservatively in register save areas */
697         scanned_registers = 0;
698
699         /* This is one past the last address which we have scanned */
700         stack_limit = stack_start;
701
702         if (!tls->has_context)
703                 memset (&new_ctx, 0, sizeof (ctx));
704         else
705                 memcpy (&new_ctx, &tls->ctx, sizeof (MonoContext));
706
707         memset (reg_locations, 0, sizeof (reg_locations));
708         memset (new_reg_locations, 0, sizeof (new_reg_locations));
709
710         while (TRUE) {
711                 memcpy (&ctx, &new_ctx, sizeof (ctx));
712
713                 for (i = 0; i < MONO_MAX_IREGS; ++i) {
714                         if (new_reg_locations [i]) {
715                                 /*
716                                  * If the current frame saves the register, it means it might modify its
717                                  * value, thus the old location might not contain the same value, so
718                                  * we have to mark it conservatively.
719                                  */
720                                 if (reg_locations [i]) {
721                                         DEBUG (fprintf (logfile, "\tscan saved reg %s location %p.\n", mono_arch_regname (i), reg_locations [i]));
722                                         mono_gc_conservatively_scan_area (reg_locations [i], (char*)reg_locations [i] + SIZEOF_SLOT);
723                                         scanned_registers += SIZEOF_SLOT;
724                                 }
725
726                                 reg_locations [i] = new_reg_locations [i];
727
728                                 DEBUG (fprintf (logfile, "\treg %s is now at location %p.\n", mono_arch_regname (i), reg_locations [i]));
729                         }
730                 }
731
732                 g_assert ((mgreg_t)stack_limit % SIZEOF_SLOT == 0);
733
734                 res = mono_find_jit_info_ext (frame.domain ? frame.domain : mono_domain_get (), tls->jit_tls, NULL, &ctx, &new_ctx, NULL, &lmf, new_reg_locations, &frame);
735                 if (!res)
736                         break;
737
738                 ji = frame.ji;
739
740                 if (frame.type == FRAME_TYPE_MANAGED_TO_NATIVE) {
741                         /*
742                          * These frames are problematic for several reasons:
743                          * - they are unwound through an LMF, and we have no precise register tracking for those.
744                          * - the LMF might not contain a precise ip, so we can't compute the call site.
745                          * - the LMF only unwinds to the wrapper frame, so we get these methods twice.
746                          */
747                         DEBUG (fprintf (logfile, "Mark(0): <Managed-to-native transition>\n"));
748                         for (i = 0; i < MONO_MAX_IREGS; ++i) {
749                                 if (reg_locations [i]) {
750                                         DEBUG (fprintf (logfile, "\tscan saved reg %s location %p.\n", mono_arch_regname (i), reg_locations [i]));
751                                         mono_gc_conservatively_scan_area (reg_locations [i], (char*)reg_locations [i] + SIZEOF_SLOT);
752                                         scanned_registers += SIZEOF_SLOT;
753                                 }
754                                 reg_locations [i] = NULL;
755                                 new_reg_locations [i] = NULL;
756                         }
757                         ctx = new_ctx;
758                         continue;
759                 }
760
761                 /* The last frame can be in any state so mark conservatively */
762                 if (last) {
763                         if (ji) {
764                                 DEBUG (char *fname = mono_method_full_name (ji->method, TRUE); fprintf (logfile, "Mark(0): %s+0x%x (%p)\n", fname, pc_offset, (gpointer)MONO_CONTEXT_GET_IP (&ctx)); g_free (fname));
765                         }
766                         DEBUG (fprintf (logfile, "\t <Last frame>\n"));
767                         last = FALSE;
768                         continue;
769                 }
770
771                 pc_offset = (guint8*)MONO_CONTEXT_GET_IP (&ctx) - (guint8*)ji->code_start;
772
773                 /* These frames are very problematic */
774                 if (ji->method->wrapper_type == MONO_WRAPPER_MANAGED_TO_NATIVE) {
775                         DEBUG (char *fname = mono_method_full_name (ji->method, TRUE); fprintf (logfile, "Mark(0): %s+0x%x (%p)\n", fname, pc_offset, (gpointer)MONO_CONTEXT_GET_IP (&ctx)); g_free (fname));
776                         DEBUG (fprintf (logfile, "\tSkip.\n"));
777                         continue;
778                 }
779
780                 /* All the other frames are at a call site */
781
782                 if (tls->nframes == MAX_FRAMES) {
783                         /* 
784                          * Can't save information since the array is full. So scan the rest of the
785                          * stack conservatively.
786                          */
787                         DEBUG (fprintf (logfile, "Mark (0): Frame stack full.\n"));
788                         break;
789                 }
790
791                 /* Scan the frame of this method */
792
793                 /*
794                  * A frame contains the following:
795                  * - saved registers
796                  * - saved args
797                  * - locals
798                  * - spill area
799                  * - localloc-ed memory
800                  */
801                 g_assert (pc_offset >= 0);
802
803                 emap = ji->gc_info;
804
805                 if (!emap) {
806                         DEBUG (char *fname = mono_method_full_name (ji->method, TRUE); fprintf (logfile, "Mark(0): %s+0x%x (%p)\n", fname, pc_offset, (gpointer)MONO_CONTEXT_GET_IP (&ctx)); g_free (fname));
807                         DEBUG (fprintf (logfile, "\tNo GC Map.\n"));
808                         continue;
809                 }
810
811                 /* The embedded callsite table requires this */
812                 g_assert (((mgreg_t)emap % 4) == 0);
813
814                 /*
815                  * Debugging aid to control the number of frames scanned precisely
816                  */
817                 if (!precise_frame_limit_inited) {
818                         if (getenv ("MONO_PRECISE_COUNT"))
819                                 precise_frame_limit = atoi (getenv ("MONO_PRECISE_COUNT"));
820                         precise_frame_limit_inited = TRUE;
821                 }
822                                 
823                 if (precise_frame_limit != -1) {
824                         if (precise_frame_count [FALSE] == precise_frame_limit)
825                                 printf ("LAST PRECISE FRAME: %s\n", mono_method_full_name (ji->method, TRUE));
826                         if (precise_frame_count [FALSE] > precise_frame_limit)
827                                 continue;
828                 }
829                 precise_frame_count [FALSE] ++;
830
831                 /* Decode the encoded GC map */
832                 map = &map_tmp;
833                 memset (map, 0, sizeof (GCMap));
834                 decode_gc_map (&emap->encoded [0], map, &p);
835                 p = (guint8*)ALIGN_TO (p, map->callsite_entry_size);
836                 map->callsites.offsets8 = p;
837                 p += map->callsite_entry_size * map->ncallsites;
838                 bitmaps = p;
839
840                 fp = (guint8*)get_frame_pointer (&ctx, map->frame_reg);
841
842                 real_frame_start = fp + map->start_offset;
843                 frame_start = fp + map->start_offset + map->map_offset;
844                 frame_end = fp + map->end_offset;
845
846                 DEBUG (char *fname = mono_method_full_name (ji->method, TRUE); fprintf (logfile, "Mark(0): %s+0x%x (%p) limit=%p fp=%p frame=%p-%p (%d)\n", fname, pc_offset, (gpointer)MONO_CONTEXT_GET_IP (&ctx), stack_limit, fp, frame_start, frame_end, (int)(frame_end - frame_start)); g_free (fname));
847
848                 /* Find the callsite index */
849                 if (map->callsite_entry_size == 1) {
850                         for (i = 0; i < map->ncallsites; ++i)
851                                 /* ip points inside the call instruction */
852                                 if (map->callsites.offsets8 [i] == pc_offset + 1)
853                                         break;
854                 } else if (map->callsite_entry_size == 2) {
855                         // FIXME: Use a binary search
856                         for (i = 0; i < map->ncallsites; ++i)
857                                 /* ip points inside the call instruction */
858                                 if (map->callsites.offsets16 [i] == pc_offset + 1)
859                                         break;
860                 } else {
861                         // FIXME: Use a binary search
862                         for (i = 0; i < map->ncallsites; ++i)
863                                 /* ip points inside the call instruction */
864                                 if (map->callsites.offsets32 [i] == pc_offset + 1)
865                                         break;
866                 }
867                 if (i == map->ncallsites) {
868                         printf ("Unable to find ip offset 0x%x in callsite list of %s.\n", pc_offset + 1, mono_method_full_name (ji->method, TRUE));
869                         g_assert_not_reached ();
870                 }
871                 cindex = i;
872
873                 /* 
874                  * This is not neccessary true on x86 because frames have a different size at each
875                  * call site.
876                  */
877                 //g_assert (real_frame_start >= stack_limit);
878
879                 if (real_frame_start > stack_limit) {
880                         /* This scans the previously skipped frames as well */
881                         DEBUG (fprintf (logfile, "\tscan area %p-%p (%d).\n", stack_limit, real_frame_start, (int)(real_frame_start - stack_limit)));
882                         mono_gc_conservatively_scan_area (stack_limit, real_frame_start);
883                         stats.scanned_other += real_frame_start - stack_limit;
884                 }
885
886                 /* Mark stack slots */
887                 if (map->has_pin_slots) {
888                         int bitmap_width = ALIGN_TO (map->nslots, 8) / 8;
889                         guint8 *pin_bitmap = &bitmaps [map->stack_pin_bitmap_offset + (bitmap_width * cindex)];
890                         guint8 *p;
891                         gboolean pinned;
892
893                         p = frame_start;
894                         for (i = 0; i < map->nslots; ++i) {
895                                 pinned = pin_bitmap [i / 8] & (1 << (i % 8));
896                                 if (pinned) {
897                                         DEBUG (fprintf (logfile, "\tscan slot %s0x%x(fp)=%p.\n", (guint8*)p > (guint8*)fp ? "" : "-", ABS ((int)((gssize)p - (gssize)fp)), p));
898                                         mono_gc_conservatively_scan_area (p, p + SIZEOF_SLOT);
899                                         scanned_conservatively += SIZEOF_SLOT;
900                                 } else {
901                                         scanned_precisely += SIZEOF_SLOT;
902                                 }
903                                 p += SIZEOF_SLOT;
904                         }
905                 } else {
906                         scanned_precisely += (map->nslots * SIZEOF_SLOT);
907                 }
908
909                 /* The area outside of start-end is NOREF */
910                 scanned_precisely += (map->end_offset - map->start_offset) - (map->nslots * SIZEOF_SLOT);
911
912                 /* Mark registers */
913                 precise_regmask = map->used_int_regs | (1 << map->frame_reg);
914                 if (map->has_pin_regs) {
915                         int bitmap_width = ALIGN_TO (map->npin_regs, 8) / 8;
916                         guint8 *pin_bitmap = &bitmaps [map->reg_pin_bitmap_offset + (bitmap_width * cindex)];
917                         int bindex = 0;
918                         for (i = 0; i < NREGS; ++i) {
919                                 if (!(map->used_int_regs & (1 << i)))
920                                         continue;
921                                 
922                                 if (!(map->reg_pin_mask & (1 << i)))
923                                         continue;
924
925                                 if (pin_bitmap [bindex / 8] & (1 << (bindex % 8))) {
926                                         DEBUG (fprintf (logfile, "\treg %s saved at 0x%p is pinning.\n", mono_arch_regname (i), reg_locations [i]));
927                                         precise_regmask &= ~(1 << i);
928                                 }
929                                 bindex ++;
930                         }
931                 }
932
933                 scanned += map->end_offset - map->start_offset;
934
935                 g_assert (scanned == scanned_precisely + scanned_conservatively);
936
937                 stack_limit = frame_end;
938
939                 /* Save information for the precise pass */
940                 fi = &tls->frames [tls->nframes];
941                 fi->nslots = map->nslots;
942                 bitmap_width = ALIGN_TO (map->nslots, 8) / 8;
943                 if (map->has_ref_slots)
944                         fi->bitmap = &bitmaps [map->stack_ref_bitmap_offset + (bitmap_width * cindex)];
945                 else
946                         fi->bitmap = NULL;
947                 fi->frame_start_offset = frame_start - stack_start;
948                 fi->nreg_locations = 0;
949                 DEBUG_PRECISE (fi->ji = ji);
950                 DEBUG_PRECISE (fi->fp = fp);
951
952                 if (map->has_ref_regs) {
953                         int bitmap_width = ALIGN_TO (map->nref_regs, 8) / 8;
954                         guint8 *ref_bitmap = &bitmaps [map->reg_ref_bitmap_offset + (bitmap_width * cindex)];
955                         int bindex = 0;
956                         for (i = 0; i < NREGS; ++i) {
957                                 if (!(map->reg_ref_mask & (1 << i)))
958                                         continue;
959
960                                 if (reg_locations [i] && (ref_bitmap [bindex / 8] & (1 << (bindex % 8)))) {
961                                         DEBUG_PRECISE (fi->regs [fi->nreg_locations] = i);
962                                         DEBUG (fprintf (logfile, "\treg %s saved at 0x%p is ref.\n", mono_arch_regname (i), reg_locations [i]));
963                                         fi->reg_locations [fi->nreg_locations] = (guint8*)reg_locations [i] - stack_start;
964                                         fi->nreg_locations ++;
965                                 }
966                                 bindex ++;
967                         }
968                 }
969
970                 /*
971                  * Clear locations of precisely stacked registers.
972                  */
973                 if (precise_regmask) {
974                         for (i = 0; i < NREGS; ++i) {
975                                 if (precise_regmask & (1 << i)) {
976                                         /*
977                                          * The method uses this register, and we have precise info for it.
978                                          * This means the location will be scanned precisely.
979                                          * Tell the code at the beginning of the loop that this location is
980                                          * processed.
981                                          */
982                                         if (reg_locations [i])
983                                                 DEBUG (fprintf (logfile, "\treg %s at location %p (==%p) is precise.\n", mono_arch_regname (i), reg_locations [i], (gpointer)*reg_locations [i]));
984                                         reg_locations [i] = NULL;
985                                 }
986                         }
987                 }
988
989                 tls->nframes ++;
990         }
991
992         /* Scan the remaining register save locations */
993         for (i = 0; i < MONO_MAX_IREGS; ++i) {
994                 if (reg_locations [i]) {
995                         DEBUG (fprintf (logfile, "\tscan saved reg location %p.\n", reg_locations [i]));
996                         mono_gc_conservatively_scan_area (reg_locations [i], (char*)reg_locations [i] + SIZEOF_SLOT);
997                         scanned_registers += SIZEOF_SLOT;
998                 }
999                 if (new_reg_locations [i]) {
1000                         DEBUG (fprintf (logfile, "\tscan saved reg location %p.\n", new_reg_locations [i]));
1001                         mono_gc_conservatively_scan_area (new_reg_locations [i], (char*)new_reg_locations [i] + SIZEOF_SLOT);
1002                         scanned_registers += SIZEOF_SLOT;
1003                 }
1004         }
1005
1006         if (stack_limit < stack_end) {
1007                 DEBUG (fprintf (logfile, "\tscan remaining stack %p-%p (%d).\n", stack_limit, stack_end, (int)(stack_end - stack_limit)));
1008                 mono_gc_conservatively_scan_area (stack_limit, stack_end);
1009                 stats.scanned_native += stack_end - stack_limit;
1010         }
1011
1012         DEBUG (fprintf (logfile, "Marked %d bytes, p=%d,c=%d out of %d.\n", scanned, scanned_precisely, scanned_conservatively, (int)(stack_end - stack_start)));
1013
1014         stats.scanned_stacks += stack_end - stack_start;
1015         stats.scanned += scanned;
1016         stats.scanned_precisely += scanned_precisely;
1017         stats.scanned_conservatively += scanned_conservatively;
1018         stats.scanned_registers += scanned_registers;
1019
1020         //mono_gc_conservatively_scan_area (stack_start, stack_end);
1021 }
1022
1023 /*
1024  * precise_pass:
1025  *
1026  *   Mark a thread stack precisely based on information saved during the conservative
1027  * pass.
1028  */
1029 static void
1030 precise_pass (TlsData *tls, guint8 *stack_start, guint8 *stack_end)
1031 {
1032         int findex, i;
1033         FrameInfo *fi;
1034         guint8 *frame_start;
1035
1036         if (!tls)
1037                 return;
1038
1039         for (findex = 0; findex < tls->nframes; findex ++) {
1040                 /* Load information saved by the !precise pass */
1041                 fi = &tls->frames [findex];
1042                 frame_start = stack_start + fi->frame_start_offset;
1043
1044                 DEBUG (char *fname = mono_method_full_name (fi->ji->method, TRUE); fprintf (logfile, "Mark(1): %s\n", fname); g_free (fname));
1045
1046                 /* 
1047                  * FIXME: Add a function to mark using a bitmap, to avoid doing a 
1048                  * call for each object.
1049                  */
1050
1051                 /* Mark stack slots */
1052                 if (fi->bitmap) {
1053                         guint8 *ref_bitmap = fi->bitmap;
1054                         gboolean live;
1055
1056                         for (i = 0; i < fi->nslots; ++i) {
1057                                 MonoObject **ptr = (MonoObject**)(frame_start + (i * SIZEOF_SLOT));
1058
1059                                 live = ref_bitmap [i / 8] & (1 << (i % 8));
1060
1061                                 if (live) {
1062                                         MonoObject *obj = *ptr;
1063                                         if (obj) {
1064                                                 DEBUG (fprintf (logfile, "\tref %s0x%x(fp)=%p: %p ->", (guint8*)ptr >= (guint8*)fi->fp ? "" : "-", ABS ((int)((gssize)ptr - (gssize)fi->fp)), ptr, obj));
1065                                                 *ptr = mono_gc_scan_object (obj);
1066                                                 DEBUG (fprintf (logfile, " %p.\n", *ptr));
1067                                         } else {
1068                                                 DEBUG (fprintf (logfile, "\tref %s0x%x(fp)=%p: %p.\n", (guint8*)ptr >= (guint8*)fi->fp ? "" : "-", ABS ((int)((gssize)ptr - (gssize)fi->fp)), ptr, obj));
1069                                         }
1070                                 } else {
1071 #if 0
1072                                         /*
1073                                          * This is disabled because the pointer takes up a lot of space.
1074                                          * Stack slots might be shared between ref and non-ref variables ?
1075                                          */
1076                                         if (map->ref_slots [i / 8] & (1 << (i % 8))) {
1077                                                 DEBUG (fprintf (logfile, "\tref %s0x%x(fp)=%p: dead (%p)\n", (guint8*)ptr >= (guint8*)fi->fp ? "" : "-", ABS ((int)((gssize)ptr - (gssize)fi->fp)), ptr, *ptr));
1078                                                 /*
1079                                                  * Fail fast if the live range is incorrect, and
1080                                                  * the JITted code tries to access this object
1081                                                  */
1082                                                 *ptr = DEAD_REF;
1083                                         }
1084 #endif
1085                                 }
1086                         }
1087                 }
1088
1089                 /* Mark registers */
1090
1091                 /*
1092                  * Registers are different from stack slots, they have no address where they
1093                  * are stored. Instead, some frame below this frame in the stack saves them
1094                  * in its prolog to the stack. We can mark this location precisely.
1095                  */
1096                 for (i = 0; i < fi->nreg_locations; ++i) {
1097                         /*
1098                          * reg_locations [i] contains the address of the stack slot where
1099                          * a reg was last saved, so mark that slot.
1100                          */
1101                         MonoObject **ptr = (MonoObject**)((guint8*)stack_start + fi->reg_locations [i]);
1102                         MonoObject *obj = *ptr;
1103
1104                         if (obj) {
1105                                 DEBUG (fprintf (logfile, "\treg %s saved at %p: %p ->", mono_arch_regname (fi->regs [i]), ptr, obj));
1106                                 *ptr = mono_gc_scan_object (obj);
1107                                 DEBUG (fprintf (logfile, " %p.\n", *ptr));
1108                         } else {
1109                                 DEBUG (fprintf (logfile, "\treg %s saved at %p: %p\n", mono_arch_regname (fi->regs [i]), ptr, obj));
1110                         }
1111                 }       
1112         }
1113
1114         /*
1115          * Debugging aid to check for missed refs.
1116          */
1117         if (tls->ref_to_track) {
1118                 mgreg_t *p;
1119
1120                 for (p = (mgreg_t*)stack_start; p < (mgreg_t*)stack_end; ++p)
1121                         if (*p == (mgreg_t)tls->ref_to_track)
1122                                 printf ("REF AT %p.\n", p);
1123         }
1124 }
1125
1126 /*
1127  * thread_mark_func:
1128  *
1129  *   This is called by the GC twice to mark a thread stack. PRECISE is FALSE at the first
1130  * call, and TRUE at the second. USER_DATA points to a TlsData
1131  * structure filled up by thread_suspend_func. 
1132  */
1133 static void
1134 thread_mark_func (gpointer user_data, guint8 *stack_start, guint8 *stack_end, gboolean precise)
1135 {
1136         TlsData *tls = user_data;
1137
1138         DEBUG (fprintf (logfile, "****************************************\n"));
1139         DEBUG (fprintf (logfile, "*** %s stack marking for thread %p (%p-%p) ***\n", precise ? "Precise" : "Conservative", tls ? GUINT_TO_POINTER (tls->tid) : NULL, stack_start, stack_end));
1140         DEBUG (fprintf (logfile, "****************************************\n"));
1141
1142         if (!precise)
1143                 conservative_pass (tls, stack_start, stack_end);
1144         else
1145                 precise_pass (tls, stack_start, stack_end);
1146 }
1147
1148 static void
1149 mini_gc_init_gc_map (MonoCompile *cfg)
1150 {
1151         if (COMPILE_LLVM (cfg))
1152                 return;
1153
1154         if (!mono_gc_is_moving ())
1155                 return;
1156
1157         if (!cfg->compile_aot && !mono_gc_precise_stack_mark_enabled ())
1158                 return;
1159
1160 #if 1
1161         /* Debugging support */
1162         {
1163                 static int precise_count;
1164
1165                 precise_count ++;
1166                 if (getenv ("MONO_GCMAP_COUNT")) {
1167                         if (precise_count == atoi (getenv ("MONO_GCMAP_COUNT")))
1168                                 printf ("LAST: %s\n", mono_method_full_name (cfg->method, TRUE));
1169                         if (precise_count > atoi (getenv ("MONO_GCMAP_COUNT")))
1170                                 return;
1171                 }
1172         }
1173 #endif
1174
1175         cfg->compute_gc_maps = TRUE;
1176
1177         cfg->gc_info = mono_mempool_alloc0 (cfg->mempool, sizeof (MonoCompileGC));
1178 }
1179
1180 /*
1181  * mini_gc_set_slot_type_from_fp:
1182  *
1183  *   Set the GC slot type of the stack slot identified by SLOT_OFFSET, which should be
1184  * relative to the frame pointer. By default, all stack slots are type PIN, so there is no
1185  * need to call this function for those slots.
1186  */
1187 void
1188 mini_gc_set_slot_type_from_fp (MonoCompile *cfg, int slot_offset, GCSlotType type)
1189 {
1190         MonoCompileGC *gcfg = (MonoCompileGC*)cfg->gc_info;
1191
1192         if (!cfg->compute_gc_maps)
1193                 return;
1194
1195         g_assert (slot_offset % SIZEOF_SLOT == 0);
1196
1197         gcfg->stack_slots_from_fp = g_slist_prepend_mempool (cfg->mempool, gcfg->stack_slots_from_fp, GINT_TO_POINTER (((slot_offset) << 16) | type));
1198 }
1199
1200 /*
1201  * mini_gc_set_slot_type_from_cfa:
1202  *
1203  *   Set the GC slot type of the stack slot identified by SLOT_OFFSET, which should be
1204  * relative to the DWARF CFA value. This should be called from mono_arch_emit_prolog ().
1205  * If type is STACK_REF, the slot is assumed to be live from the end of the prolog until
1206  * the end of the method. By default, all stack slots are type PIN, so there is no need to
1207  * call this function for those slots.
1208  */
1209 void
1210 mini_gc_set_slot_type_from_cfa (MonoCompile *cfg, int slot_offset, GCSlotType type)
1211 {
1212         MonoCompileGC *gcfg = (MonoCompileGC*)cfg->gc_info;
1213         int slot = - (slot_offset / SIZEOF_SLOT);
1214
1215         if (!cfg->compute_gc_maps)
1216                 return;
1217
1218         g_assert (slot_offset <= 0);
1219         g_assert (slot_offset % SIZEOF_SLOT == 0);
1220
1221         gcfg->stack_slots_from_cfa = g_slist_prepend_mempool (cfg->mempool, gcfg->stack_slots_from_cfa, GUINT_TO_POINTER (((slot) << 16) | type));
1222 }
1223
1224 static inline int
1225 fp_offset_to_slot (MonoCompile *cfg, int offset)
1226 {
1227         MonoCompileGC *gcfg = cfg->gc_info;
1228
1229         return (offset - gcfg->min_offset) / SIZEOF_SLOT;
1230 }
1231
1232 static inline int
1233 slot_to_fp_offset (MonoCompile *cfg, int slot)
1234 {
1235         MonoCompileGC *gcfg = cfg->gc_info;
1236
1237         return (slot * SIZEOF_SLOT) + gcfg->min_offset;
1238 }
1239
1240 static inline void
1241 set_slot (MonoCompileGC *gcfg, int slot, int callsite_index, GCSlotType type)
1242 {
1243         g_assert (slot >= 0 && slot < gcfg->nslots);
1244
1245         if (type == SLOT_PIN) {
1246                 clear_bit (gcfg->stack_ref_bitmap, gcfg->stack_bitmap_width, callsite_index, slot);
1247                 set_bit (gcfg->stack_pin_bitmap, gcfg->stack_bitmap_width, callsite_index, slot);
1248         } else if (type == SLOT_REF) {
1249                 set_bit (gcfg->stack_ref_bitmap, gcfg->stack_bitmap_width, callsite_index, slot);
1250                 clear_bit (gcfg->stack_pin_bitmap, gcfg->stack_bitmap_width, callsite_index, slot);
1251         } else if (type == SLOT_NOREF) {
1252                 clear_bit (gcfg->stack_ref_bitmap, gcfg->stack_bitmap_width, callsite_index, slot);
1253                 clear_bit (gcfg->stack_pin_bitmap, gcfg->stack_bitmap_width, callsite_index, slot);
1254         }
1255 }
1256
1257 static inline void
1258 set_slot_everywhere (MonoCompileGC *gcfg, int slot, GCSlotType type)
1259 {
1260         int cindex;
1261
1262         for (cindex = 0; cindex < gcfg->ncallsites; ++cindex)
1263                 set_slot (gcfg, slot, cindex, type);
1264 }
1265
1266 static inline void
1267 set_slot_in_range (MonoCompileGC *gcfg, int slot, int from, int to, GCSlotType type)
1268 {
1269         int cindex;
1270
1271         for (cindex = 0; cindex < gcfg->ncallsites; ++cindex) {
1272                 int callsite_offset = gcfg->callsites [cindex]->pc_offset;
1273                 if (callsite_offset >= from && callsite_offset < to)
1274                         set_slot (gcfg, slot, cindex, type);
1275         }
1276 }
1277
1278 static inline void
1279 set_reg_slot (MonoCompileGC *gcfg, int slot, int callsite_index, GCSlotType type)
1280 {
1281         g_assert (slot >= 0 && slot < gcfg->nregs);
1282
1283         if (type == SLOT_PIN) {
1284                 clear_bit (gcfg->reg_ref_bitmap, gcfg->reg_bitmap_width, callsite_index, slot);
1285                 set_bit (gcfg->reg_pin_bitmap, gcfg->reg_bitmap_width, callsite_index, slot);
1286         } else if (type == SLOT_REF) {
1287                 set_bit (gcfg->reg_ref_bitmap, gcfg->reg_bitmap_width, callsite_index, slot);
1288                 clear_bit (gcfg->reg_pin_bitmap, gcfg->reg_bitmap_width, callsite_index, slot);
1289         } else if (type == SLOT_NOREF) {
1290                 clear_bit (gcfg->reg_ref_bitmap, gcfg->reg_bitmap_width, callsite_index, slot);
1291                 clear_bit (gcfg->reg_pin_bitmap, gcfg->reg_bitmap_width, callsite_index, slot);
1292         }
1293 }
1294
1295 static inline void
1296 set_reg_slot_everywhere (MonoCompileGC *gcfg, int slot, GCSlotType type)
1297 {
1298         int cindex;
1299
1300         for (cindex = 0; cindex < gcfg->ncallsites; ++cindex)
1301                 set_reg_slot (gcfg, slot, cindex, type);
1302 }
1303
1304 static inline void
1305 set_reg_slot_in_range (MonoCompileGC *gcfg, int slot, int from, int to, GCSlotType type)
1306 {
1307         int cindex;
1308
1309         for (cindex = 0; cindex < gcfg->ncallsites; ++cindex) {
1310                 int callsite_offset = gcfg->callsites [cindex]->pc_offset;
1311                 if (callsite_offset >= from && callsite_offset < to)
1312                         set_reg_slot (gcfg, slot, cindex, type);
1313         }
1314 }
1315
1316 static void
1317 process_spill_slots (MonoCompile *cfg)
1318 {
1319         MonoCompileGC *gcfg = cfg->gc_info;
1320         MonoBasicBlock *bb;
1321         GSList *l;
1322         int i;
1323
1324         /* Mark all ref/pin spill slots as NOREF by default outside of their live range */
1325         for (bb = cfg->bb_entry; bb; bb = bb->next_bb) {
1326                 for (l = bb->spill_slot_defs; l; l = l->next) {
1327                         MonoInst *def = l->data;
1328                         int spill_slot = def->inst_c0;
1329                         int bank = def->inst_c1;
1330                         int offset = cfg->spill_info [bank][spill_slot].offset;
1331                         int slot = fp_offset_to_slot (cfg, offset);
1332
1333                         if (bank == MONO_REG_INT_MP || bank == MONO_REG_INT_REF)
1334                                 set_slot_everywhere (gcfg, slot, SLOT_NOREF);
1335                 }
1336         }
1337
1338         for (bb = cfg->bb_entry; bb; bb = bb->next_bb) {
1339                 for (l = bb->spill_slot_defs; l; l = l->next) {
1340                         MonoInst *def = l->data;
1341                         int spill_slot = def->inst_c0;
1342                         int bank = def->inst_c1;
1343                         int offset = cfg->spill_info [bank][spill_slot].offset;
1344                         int slot = fp_offset_to_slot (cfg, offset);
1345                         GCSlotType type;
1346
1347                         if (bank == MONO_REG_INT_MP)
1348                                 type = SLOT_PIN;
1349                         else
1350                                 type = SLOT_REF;
1351
1352                         /*
1353                          * Extend the live interval for the GC tracked spill slots
1354                          * defined in this bblock.
1355                          * FIXME: This is not needed.
1356                          */
1357                         set_slot_in_range (gcfg, slot, def->backend.pc_offset, bb->native_offset + bb->native_length, type);
1358
1359                         if (cfg->verbose_level > 1)
1360                                 printf ("\t%s spill slot at %s0x%x(fp) (slot = %d)\n", slot_type_to_string (type), offset >= 0 ? "" : "-", ABS (offset), slot);
1361                 }
1362         }
1363
1364         /* Set fp spill slots to NOREF */
1365         for (i = 0; i < cfg->spill_info_len [MONO_REG_DOUBLE]; ++i) {
1366                 int offset = cfg->spill_info [MONO_REG_DOUBLE][i].offset;
1367                 int slot;
1368
1369                 if (offset == -1)
1370                         continue;
1371
1372                 slot = fp_offset_to_slot (cfg, offset);
1373
1374                 set_slot_everywhere (gcfg, slot, SLOT_NOREF);
1375                 /* FIXME: 32 bit */
1376                 if (cfg->verbose_level > 1)
1377                         printf ("\tfp spill slot at %s0x%x(fp) (slot = %d)\n", offset >= 0 ? "" : "-", ABS (offset), slot);
1378         }
1379
1380         /* Set int spill slots to NOREF */
1381         for (i = 0; i < cfg->spill_info_len [MONO_REG_INT]; ++i) {
1382                 int offset = cfg->spill_info [MONO_REG_INT][i].offset;
1383                 int slot;
1384
1385                 if (offset == -1)
1386                         continue;
1387
1388                 slot = fp_offset_to_slot (cfg, offset);
1389
1390                 set_slot_everywhere (gcfg, slot, SLOT_NOREF);
1391                 if (cfg->verbose_level > 1)
1392                         printf ("\tint spill slot at %s0x%x(fp) (slot = %d)\n", offset >= 0 ? "" : "-", ABS (offset), slot);
1393         }
1394 }
1395
1396 /*
1397  * process_other_slots:
1398  *
1399  *   Process stack slots registered using mini_gc_set_slot_type_... ().
1400  */
1401 static void
1402 process_other_slots (MonoCompile *cfg)
1403 {
1404         MonoCompileGC *gcfg = cfg->gc_info;
1405         GSList *l;
1406
1407         /* Relative to the CFA */
1408         for (l = gcfg->stack_slots_from_cfa; l; l = l->next) {
1409                 guint data = GPOINTER_TO_UINT (l->data);
1410                 int cfa_slot = data >> 16;
1411                 GCSlotType type = data & 0xff;
1412                 int slot;
1413                 
1414                 /*
1415                  * Map the cfa relative slot to an fp relative slot.
1416                  * slot_addr == cfa - <cfa_slot>*4/8
1417                  * fp + cfa_offset == cfa
1418                  * -> slot_addr == fp + (cfa_offset - <cfa_slot>*4/8)
1419                  */
1420                 slot = (cfg->cfa_offset / SIZEOF_SLOT) - cfa_slot - (gcfg->min_offset / SIZEOF_SLOT);
1421
1422                 set_slot_everywhere (gcfg, slot, type);
1423
1424                 if (cfg->verbose_level > 1) {
1425                         int fp_offset = slot_to_fp_offset (cfg, slot);
1426                         if (type == SLOT_NOREF)
1427                                 printf ("\tnoref slot at %s0x%x(fp) (slot = %d) (cfa - 0x%x)\n", fp_offset >= 0 ? "" : "-", ABS (fp_offset), slot, (int)(cfa_slot * SIZEOF_SLOT));
1428                 }
1429         }
1430
1431         /* Relative to the FP */
1432         for (l = gcfg->stack_slots_from_fp; l; l = l->next) {
1433                 gint data = GPOINTER_TO_INT (l->data);
1434                 int offset = data >> 16;
1435                 GCSlotType type = data & 0xff;
1436                 int slot;
1437                 
1438                 slot = fp_offset_to_slot (cfg, offset);
1439
1440                 set_slot_everywhere (gcfg, slot, type);
1441
1442                 /* Liveness for these slots is handled by process_spill_slots () */
1443
1444                 if (cfg->verbose_level > 1) {
1445                         if (type == SLOT_REF)
1446                                 printf ("\tref slot at fp+0x%x (slot = %d)\n", offset, slot);
1447                         else if (type == SLOT_NOREF)
1448                                 printf ("\tnoref slot at 0x%x(fp) (slot = %d)\n", offset, slot);
1449                 }
1450         }
1451 }
1452
1453 static gsize*
1454 get_vtype_bitmap (MonoType *t, int *numbits)
1455 {
1456         MonoClass *klass = mono_class_from_mono_type (t);
1457
1458         if (klass->generic_container || mono_class_is_open_constructed_type (t)) {
1459                 /* FIXME: Generic sharing */
1460                 return NULL;
1461         } else {
1462                 mono_class_compute_gc_descriptor (klass);
1463
1464                 return mono_gc_get_bitmap_for_descr (klass->gc_descr, numbits);
1465         }
1466 }
1467
1468 static inline const char*
1469 get_offset_sign (int offset)
1470 {
1471         return offset < 0 ? "-" : "+";
1472 }
1473
1474 static inline int
1475 get_offset_val (int offset)
1476 {
1477         return offset < 0 ? (- offset) : offset;
1478 }
1479
1480 static void
1481 process_variables (MonoCompile *cfg)
1482 {
1483         MonoCompileGC *gcfg = cfg->gc_info;
1484         MonoMethodSignature *sig = mono_method_signature (cfg->method);
1485         int i, locals_min_slot, locals_max_slot, cindex;
1486         MonoBasicBlock *bb;
1487         MonoInst *tmp;
1488         int *pc_offsets;
1489         int locals_min_offset = gcfg->locals_min_offset;
1490         int locals_max_offset = gcfg->locals_max_offset;
1491
1492         /* Slots for locals are NOREF by default */
1493         locals_min_slot = (locals_min_offset - gcfg->min_offset) / SIZEOF_SLOT;
1494         locals_max_slot = (locals_max_offset - gcfg->min_offset) / SIZEOF_SLOT;
1495         for (i = locals_min_slot; i < locals_max_slot; ++i) {
1496                 set_slot_everywhere (gcfg, i, SLOT_NOREF);
1497         }
1498
1499         /*
1500          * Compute the offset where variables are initialized in the first bblock, if any.
1501          */
1502         pc_offsets = g_new0 (int, cfg->next_vreg);
1503
1504         bb = cfg->bb_entry->next_bb;
1505         MONO_BB_FOR_EACH_INS (bb, tmp) {
1506                 if (tmp->opcode == OP_GC_LIVENESS_DEF) {
1507                         int vreg = tmp->inst_c1;
1508                         if (pc_offsets [vreg] == 0) {
1509                                 g_assert (tmp->backend.pc_offset > 0);
1510                                 pc_offsets [vreg] = tmp->backend.pc_offset;
1511                         }
1512                 }
1513         }
1514
1515         /*
1516          * Stack slots holding arguments are initialized in the prolog.
1517          * This means we can treat them alive for the whole method.
1518          */
1519         for (i = 0; i < cfg->num_varinfo; i++) {
1520                 MonoInst *ins = cfg->varinfo [i];
1521                 MonoType *t = ins->inst_vtype;
1522                 MonoMethodVar *vmv;
1523                 guint32 pos;
1524                 gboolean byref, is_this = FALSE;
1525                 gboolean is_arg = i < cfg->locals_start;
1526
1527                 if (ins == cfg->ret) {
1528                         if (!(ins->opcode == OP_REGOFFSET && MONO_TYPE_ISSTRUCT (t)))
1529                                 continue;
1530                 }
1531
1532                 vmv = MONO_VARINFO (cfg, i);
1533
1534                 /* For some reason, 'this' is byref */
1535                 if (sig->hasthis && ins == cfg->args [0] && !cfg->method->klass->valuetype) {
1536                         t = &cfg->method->klass->byval_arg;
1537                         is_this = TRUE;
1538                 }
1539
1540                 byref = t->byref;
1541
1542                 if (ins->opcode == OP_REGVAR) {
1543                         int hreg;
1544                         GCSlotType slot_type;
1545
1546                         t = mini_type_get_underlying_type (NULL, t);
1547
1548                         hreg = ins->dreg;
1549                         g_assert (hreg < MONO_MAX_IREGS);
1550
1551                         if (byref)
1552                                 slot_type = SLOT_PIN;
1553                         else
1554                                 slot_type = mini_type_is_reference (cfg, t) ? SLOT_REF : SLOT_NOREF;
1555
1556                         if (slot_type == SLOT_PIN) {
1557                                 /* These have no live interval, be conservative */
1558                                 set_reg_slot_everywhere (gcfg, hreg, slot_type);
1559                         } else {
1560                                 /*
1561                                  * Unlike variables allocated to the stack, we generate liveness info
1562                                  * for noref vars in registers in mono_spill_global_vars (), because
1563                                  * knowing that a register doesn't contain a ref allows us to mark its save
1564                                  * locations precisely.
1565                                  */
1566                                 for (cindex = 0; cindex < gcfg->ncallsites; ++cindex)
1567                                         if (gcfg->callsites [cindex]->liveness [i / 8] & (1 << (i % 8)))
1568                                                 set_reg_slot (gcfg, hreg, cindex, slot_type);
1569                         }
1570
1571                         if (cfg->verbose_level > 1) {
1572                                 printf ("\t%s %sreg %s(R%d)\n", slot_type_to_string (slot_type), is_arg ? "arg " : "", mono_arch_regname (hreg), vmv->vreg);
1573                         }
1574
1575                         continue;
1576                 }
1577
1578                 if (ins->opcode != OP_REGOFFSET)
1579                         continue;
1580
1581                 if (ins->inst_offset % SIZEOF_SLOT != 0)
1582                         continue;
1583
1584                 if (is_arg && ins->inst_offset >= gcfg->max_offset)
1585                         /* In parent frame */
1586                         continue;
1587
1588                 pos = fp_offset_to_slot (cfg, ins->inst_offset);
1589
1590                 if (is_arg && ins->flags & MONO_INST_IS_DEAD) {
1591                         /* These do not get stored in the prolog */
1592                         set_slot_everywhere (gcfg, pos, SLOT_NOREF);
1593
1594                         if (cfg->verbose_level > 1) {
1595                                 printf ("\tdead arg at fp%s0x%x (slot = %d): %s\n", get_offset_sign (ins->inst_offset), get_offset_val (ins->inst_offset), pos, mono_type_full_name (ins->inst_vtype));
1596                         }
1597                         continue;
1598                 }
1599
1600                 if (MONO_TYPE_ISSTRUCT (t)) {
1601                         int numbits = 0, j;
1602                         gsize *bitmap = NULL;
1603                         gboolean pin = FALSE;
1604                         int size;
1605                         int size_in_slots;
1606                         
1607                         if (ins->backend.is_pinvoke)
1608                                 size = mono_class_native_size (ins->klass, NULL);
1609                         else
1610                                 size = mono_class_value_size (ins->klass, NULL);
1611                         size_in_slots = ALIGN_TO (size, SIZEOF_SLOT) / SIZEOF_SLOT;
1612
1613                         if (cfg->verbose_level > 1)
1614                                 printf ("\tvtype R%d at %s0x%x(fp)-%s0x%x(fp) (slot %d-%d): %s\n", vmv->vreg, get_offset_sign (ins->inst_offset), get_offset_val (ins->inst_offset), get_offset_sign (ins->inst_offset), get_offset_val (ins->inst_offset + (size_in_slots * SIZEOF_SLOT)), pos, pos + size_in_slots, mono_type_full_name (ins->inst_vtype));
1615
1616                         if (!ins->klass->has_references) {
1617                                 if (is_arg) {
1618                                         for (j = 0; j < size_in_slots; ++j)
1619                                                 set_slot_everywhere (gcfg, pos + j, SLOT_NOREF);
1620                                 }
1621                                 continue;
1622                         }
1623
1624                         bitmap = get_vtype_bitmap (t, &numbits);
1625                         if (!bitmap)
1626                                 pin = TRUE;
1627
1628                         /*
1629                          * Most vtypes are marked volatile because of the LDADDR instructions,
1630                          * and they have no liveness information since they are decomposed
1631                          * before the liveness pass. We emit OP_GC_LIVENESS_DEF instructions for
1632                          * them during VZERO decomposition.
1633                          */
1634                         if (!pc_offsets [vmv->vreg])
1635                                 pin = TRUE;
1636
1637                         if (ins->backend.is_pinvoke)
1638                                 pin = TRUE;
1639
1640                         if (bitmap) {
1641                                 for (cindex = 0; cindex < gcfg->ncallsites; ++cindex) {
1642                                         if (gcfg->callsites [cindex]->pc_offset > pc_offsets [vmv->vreg]) {
1643                                                 for (j = 0; j < numbits; ++j) {
1644                                                         if (bitmap [j / GC_BITS_PER_WORD] & ((gsize)1 << (j % GC_BITS_PER_WORD))) {
1645                                                                 /* The descriptor is for the boxed object */
1646                                                                 set_slot (gcfg, (pos + j - (sizeof (MonoObject) / SIZEOF_SLOT)), cindex, pin ? SLOT_PIN : SLOT_REF);
1647                                                         }
1648                                                 }
1649                                         }
1650                                 }
1651
1652                                 if (cfg->verbose_level > 1) {
1653                                         for (j = 0; j < numbits; ++j) {
1654                                                 if (bitmap [j / GC_BITS_PER_WORD] & ((gsize)1 << (j % GC_BITS_PER_WORD)))
1655                                                         printf ("\t\t%s slot at 0x%x(fp) (slot = %d)\n", pin ? "pin" : "ref", (int)(ins->inst_offset + (j * SIZEOF_SLOT)), (int)(pos + j - (sizeof (MonoObject) / SIZEOF_SLOT)));
1656                                         }
1657                                 }
1658                         } else {
1659                                 if (cfg->verbose_level > 1)
1660                                         printf ("\t\tpinned\n");
1661                                 for (j = 0; j < size_in_slots; ++j) {
1662                                         set_slot_everywhere (gcfg, pos + j, SLOT_PIN);
1663                                 }
1664                         }
1665
1666                         g_free (bitmap);
1667
1668                         continue;
1669                 }
1670
1671                 if (!is_arg && (ins->inst_offset < gcfg->min_offset || ins->inst_offset >= gcfg->max_offset))
1672                         /* Vret addr etc. */
1673                         continue;
1674
1675                 if (t->byref) {
1676                         if (is_arg) {
1677                                 set_slot_everywhere (gcfg, pos, SLOT_PIN);
1678                         } else {
1679                                 for (cindex = 0; cindex < gcfg->ncallsites; ++cindex)
1680                                         if (gcfg->callsites [cindex]->liveness [i / 8] & (1 << (i % 8)))
1681                                                 set_slot (gcfg, pos, cindex, SLOT_PIN);
1682                         }
1683                         if (cfg->verbose_level > 1)
1684                                 printf ("\tbyref at %s0x%x(fp) (R%d, slot = %d): %s\n", ins->inst_offset < 0 ? "-" : "", (ins->inst_offset < 0) ? -(int)ins->inst_offset : (int)ins->inst_offset, vmv->vreg, pos, mono_type_full_name (ins->inst_vtype));
1685                         continue;
1686                 }
1687
1688                 /*
1689                  * This is currently disabled, but could be enabled to debug crashes.
1690                  */
1691 #if 0
1692                 if (t->type == MONO_TYPE_I) {
1693                         /*
1694                          * Variables created in mono_handle_global_vregs have type I, but they
1695                          * could hold GC refs since the vregs they were created from might not been
1696                          * marked as holding a GC ref. So be conservative.
1697                          */
1698                         set_slot_everywhere (gcfg, pos, SLOT_PIN);
1699                         continue;
1700                 }
1701 #endif
1702
1703                 t = mini_type_get_underlying_type (NULL, t);
1704
1705                 if (!mini_type_is_reference (cfg, t)) {
1706                         set_slot_everywhere (gcfg, pos, SLOT_NOREF);
1707                         if (cfg->verbose_level > 1)
1708                                 printf ("\tnoref at %s0x%x(fp) (R%d, slot = %d): %s\n", ins->inst_offset < 0 ? "-" : "", (ins->inst_offset < 0) ? -(int)ins->inst_offset : (int)ins->inst_offset, vmv->vreg, pos, mono_type_full_name (ins->inst_vtype));
1709                         if (!t->byref && sizeof (mgreg_t) == 4 && (t->type == MONO_TYPE_I8 || t->type == MONO_TYPE_U8 || t->type == MONO_TYPE_R8)) {
1710                                 set_slot_everywhere (gcfg, pos + 1, SLOT_NOREF);
1711                                 if (cfg->verbose_level > 1)
1712                                         printf ("\tnoref at %s0x%x(fp) (R%d, slot = %d): %s\n", ins->inst_offset < 0 ? "-" : "", (ins->inst_offset < 0) ? -(int)(ins->inst_offset + 4) : (int)ins->inst_offset + 4, vmv->vreg, pos + 1, mono_type_full_name (ins->inst_vtype));
1713                         }
1714                         continue;
1715                 }
1716
1717                 /* 'this' is marked INDIRECT for gshared methods */
1718                 if (ins->flags & (MONO_INST_VOLATILE | MONO_INST_INDIRECT) && !is_this) {
1719                         /*
1720                          * For volatile variables, treat them alive from the point they are
1721                          * initialized in the first bblock until the end of the method.
1722                          */
1723                         if (is_arg) {
1724                                 set_slot_everywhere (gcfg, pos, SLOT_REF);
1725                         } else if (pc_offsets [vmv->vreg]) {
1726                                 set_slot_in_range (gcfg, pos, 0, pc_offsets [vmv->vreg], SLOT_PIN);
1727                                 set_slot_in_range (gcfg, pos, pc_offsets [vmv->vreg], cfg->code_size, SLOT_REF);
1728                         } else {
1729                                 set_slot_everywhere (gcfg, pos, SLOT_PIN);
1730                         }
1731                         if (cfg->verbose_level > 1)
1732                                 printf ("\tvolatile ref at %s0x%x(fp) (R%d, slot = %d): %s\n", ins->inst_offset < 0 ? "-" : "", (ins->inst_offset < 0) ? -(int)ins->inst_offset : (int)ins->inst_offset, vmv->vreg, pos, mono_type_full_name (ins->inst_vtype));
1733                         continue;
1734                 }
1735
1736                 if (is_arg) {
1737                         /* Live for the whole method */
1738                         set_slot_everywhere (gcfg, pos, SLOT_REF);
1739                 } else {
1740                         for (cindex = 0; cindex < gcfg->ncallsites; ++cindex)
1741                                 if (gcfg->callsites [cindex]->liveness [i / 8] & (1 << (i % 8)))
1742                                         set_slot (gcfg, pos, cindex, SLOT_REF);
1743                 }
1744
1745                 if (cfg->verbose_level > 1) {
1746                         printf ("\tref at %s0x%x(fp) (R%d, slot = %d): %s\n", ins->inst_offset < 0 ? "-" : "", (ins->inst_offset < 0) ? -(int)ins->inst_offset : (int)ins->inst_offset, vmv->vreg, pos, mono_type_full_name (ins->inst_vtype));
1747                 }
1748         }
1749
1750         g_free (pc_offsets);
1751 }
1752
1753 static int
1754 sp_offset_to_fp_offset (MonoCompile *cfg, int sp_offset)
1755 {
1756         /* 
1757          * Convert a sp relative offset to a slot index. This is
1758          * platform specific.
1759          */
1760 #ifdef TARGET_AMD64
1761         /* fp = sp + offset */
1762         g_assert (cfg->frame_reg == AMD64_RBP);
1763         return (- cfg->arch.sp_fp_offset + sp_offset);
1764 #elif defined(TARGET_X86)
1765         /* The offset is computed from the sp at the start of the call sequence */
1766         g_assert (cfg->frame_reg == X86_EBP);
1767         return (- cfg->arch.sp_fp_offset - sp_offset);  
1768 #else
1769         NOT_IMPLEMENTED;
1770         return -1;
1771 #endif
1772 }
1773
1774 static GCSlotType
1775 type_to_gc_slot_type (MonoCompile *cfg, MonoType *t)
1776 {
1777         if (t->byref)
1778                 return SLOT_PIN;
1779         t = mini_type_get_underlying_type (NULL, t);
1780         if (mini_type_is_reference (cfg, t))
1781                 return SLOT_REF;
1782         else {
1783                 if (MONO_TYPE_ISSTRUCT (t)) {
1784                         MonoClass *klass = mono_class_from_mono_type (t);
1785                         if (!klass->has_references) {
1786                                 return SLOT_NOREF;
1787                         } else {
1788                                 // FIXME:
1789                                 return SLOT_PIN;
1790                         }
1791                 }
1792                 return SLOT_NOREF;
1793         }
1794 }
1795
1796 static void
1797 process_param_area_slots (MonoCompile *cfg)
1798 {
1799         MonoCompileGC *gcfg = cfg->gc_info;
1800         int cindex, i;
1801         gboolean *is_param;
1802
1803         /*
1804          * These slots are used for passing parameters during calls. They are sp relative, not
1805          * fp relative, so they are harder to handle.
1806          */
1807         if (cfg->flags & MONO_CFG_HAS_ALLOCA)
1808                 /* The distance between fp and sp is not constant */
1809                 return;
1810
1811         is_param = mono_mempool_alloc0 (cfg->mempool, gcfg->nslots * sizeof (gboolean));
1812
1813         for (cindex = 0; cindex < gcfg->ncallsites; ++cindex) {
1814                 GCCallSite *callsite = gcfg->callsites [cindex];
1815                 GSList *l;
1816
1817                 for (l = callsite->param_slots; l; l = l->next) {
1818                         MonoInst *def = l->data;
1819                         MonoType *t = def->inst_vtype;
1820                         int sp_offset = def->inst_offset;
1821                         int fp_offset = sp_offset_to_fp_offset (cfg, sp_offset);
1822                         int slot = fp_offset_to_slot (cfg, fp_offset);
1823                         guint32 align;
1824                         guint32 size;
1825
1826                         if (MONO_TYPE_ISSTRUCT (t)) {
1827                                 size = mini_type_stack_size_full (cfg->generic_sharing_context, t, &align, FALSE);
1828                         } else {
1829                                 size = sizeof (mgreg_t);
1830                         }
1831
1832                         for (i = 0; i < size / sizeof (mgreg_t); ++i) {
1833                                 g_assert (slot + i >= 0 && slot + i < gcfg->nslots);
1834                                 is_param [slot + i] = TRUE;
1835                         }
1836                 }
1837         }
1838
1839         /* All param area slots are noref by default */
1840         for (i = 0; i < gcfg->nslots; ++i) {
1841                 if (is_param [i])
1842                         set_slot_everywhere (gcfg, i, SLOT_NOREF);
1843         }
1844
1845         for (cindex = 0; cindex < gcfg->ncallsites; ++cindex) {
1846                 GCCallSite *callsite = gcfg->callsites [cindex];
1847                 GSList *l;
1848
1849                 for (l = callsite->param_slots; l; l = l->next) {
1850                         MonoInst *def = l->data;
1851                         MonoType *t = def->inst_vtype;
1852                         int sp_offset = def->inst_offset;
1853                         int fp_offset = sp_offset_to_fp_offset (cfg, sp_offset);
1854                         int slot = fp_offset_to_slot (cfg, fp_offset);
1855                         GCSlotType type = type_to_gc_slot_type (cfg, t);
1856
1857                         if (MONO_TYPE_ISSTRUCT (t)) {
1858                                 guint32 align;
1859                                 guint32 size;
1860                                 int size_in_slots;
1861                                 gsize *bitmap;
1862                                 int j, numbits;
1863
1864                                 size = mini_type_stack_size_full (cfg->generic_sharing_context, t, &align, FALSE);
1865                                 size_in_slots = ALIGN_TO (size, SIZEOF_SLOT) / SIZEOF_SLOT;
1866
1867                                 bitmap = get_vtype_bitmap (t, &numbits);
1868                                 if (type == SLOT_NOREF || !bitmap) {
1869                                         for (i = 0; i < size_in_slots; ++i) {
1870                                                 set_slot_in_range (gcfg, slot + i, def->backend.pc_offset, callsite->pc_offset + 1, type);
1871                                         }
1872                                         if (cfg->verbose_level > 1)
1873                                                 printf ("\t%s param area slots at %s0x%x(fp)=0x%x(sp) (slot = %d-%d) [0x%x-0x%x]\n", slot_type_to_string (type), get_offset_sign (fp_offset), get_offset_val (fp_offset), sp_offset, slot, slot + (size / (int)sizeof (mgreg_t)), def->backend.pc_offset, callsite->pc_offset + 1);
1874                                 } else {
1875                                         for (j = 0; j < numbits; ++j) {
1876                                                 if (bitmap [j / GC_BITS_PER_WORD] & ((gsize)1 << (j % GC_BITS_PER_WORD))) {
1877                                                         /* The descriptor is for the boxed object */
1878                                                         set_slot (gcfg, (slot + j - (sizeof (MonoObject) / SIZEOF_SLOT)), cindex, SLOT_REF);
1879                                                 }
1880                                         }
1881                                         if (cfg->verbose_level > 1)
1882                                                 printf ("\tvtype param area slots at %s0x%x(fp)=0x%x(sp) (slot = %d-%d) [0x%x-0x%x]\n", get_offset_sign (fp_offset), get_offset_val (fp_offset), sp_offset, slot, slot + (size / (int)sizeof (mgreg_t)), def->backend.pc_offset, callsite->pc_offset + 1);
1883                                 }
1884                                 g_free (bitmap);
1885                         } else {
1886                                 /* The slot is live between the def instruction and the call */
1887                                 set_slot_in_range (gcfg, slot, def->backend.pc_offset, callsite->pc_offset + 1, type);
1888                                 if (cfg->verbose_level > 1)
1889                                         printf ("\t%s param area slot at %s0x%x(fp)=0x%x(sp) (slot = %d) [0x%x-0x%x]\n", slot_type_to_string (type), get_offset_sign (fp_offset), get_offset_val (fp_offset), sp_offset, slot, def->backend.pc_offset, callsite->pc_offset + 1);
1890                         }
1891                 }
1892         }
1893 }
1894
1895 static void
1896 process_finally_clauses (MonoCompile *cfg)
1897 {
1898         MonoCompileGC *gcfg = cfg->gc_info;
1899         GCCallSite **callsites;
1900         int ncallsites;
1901         gboolean has_finally;
1902         int i, j, nslots, nregs;
1903
1904         ncallsites = gcfg->ncallsites;
1905         nslots = gcfg->nslots;
1906         nregs = gcfg->nregs;
1907         callsites = gcfg->callsites;
1908
1909         /*
1910          * The calls to the finally clauses don't show up in the cfg. See
1911          * test_0_liveness_8 ().
1912          * Variables accessed inside the finally clause are already marked VOLATILE by
1913          * mono_liveness_handle_exception_clauses (). Variables not accessed inside the finally clause have
1914          * correct liveness outside the finally clause. So mark them PIN inside the finally clauses.
1915          */
1916         has_finally = FALSE;
1917         for (i = 0; i < cfg->header->num_clauses; ++i) {
1918                 MonoExceptionClause *clause = &cfg->header->clauses [i];
1919
1920                 if (clause->flags == MONO_EXCEPTION_CLAUSE_FINALLY) {
1921                         has_finally = TRUE;
1922                 }
1923         }
1924         if (has_finally) {
1925                 if (cfg->verbose_level > 1)
1926                         printf ("\tMethod has finally clauses, pessimizing live ranges.\n");
1927                 for (j = 0; j < ncallsites; ++j) {
1928                         MonoBasicBlock *bb = callsites [j]->bb;
1929                         MonoExceptionClause *clause;
1930                         gboolean is_in_finally = FALSE;
1931
1932                         for (i = 0; i < cfg->header->num_clauses; ++i) {
1933                                 clause = &cfg->header->clauses [i];
1934                            
1935                                 if (MONO_OFFSET_IN_HANDLER (clause, bb->real_offset)) {
1936                                         if (clause->flags == MONO_EXCEPTION_CLAUSE_FINALLY) {
1937                                                 is_in_finally = TRUE;
1938                                                 break;
1939                                         }
1940                                 }
1941                         }
1942
1943                         if (is_in_finally) {
1944                                 for (i = 0; i < nslots; ++i)
1945                                         set_slot (gcfg, i, j, SLOT_PIN);
1946                                 for (i = 0; i < nregs; ++i)
1947                                         set_reg_slot (gcfg, i, j, SLOT_PIN);
1948                         }
1949                 }
1950         }
1951 }
1952
1953 static void
1954 compute_frame_size (MonoCompile *cfg)
1955 {
1956         int i, locals_min_offset, locals_max_offset, cfa_min_offset, cfa_max_offset;
1957         int min_offset, max_offset;
1958         MonoCompileGC *gcfg = cfg->gc_info;
1959         MonoMethodSignature *sig = mono_method_signature (cfg->method);
1960         GSList *l;
1961
1962         /* Compute min/max offsets from the fp */
1963
1964         /* Locals */
1965 #if defined(TARGET_AMD64) || defined(TARGET_X86) || defined(TARGET_ARM)
1966         locals_min_offset = ALIGN_TO (cfg->locals_min_stack_offset, SIZEOF_SLOT);
1967         locals_max_offset = cfg->locals_max_stack_offset;
1968 #else
1969         /* min/max stack offset needs to be computed in mono_arch_allocate_vars () */
1970         NOT_IMPLEMENTED;
1971 #endif
1972
1973         locals_min_offset = ALIGN_TO (locals_min_offset, SIZEOF_SLOT);
1974         locals_max_offset = ALIGN_TO (locals_max_offset, SIZEOF_SLOT);
1975
1976         min_offset = locals_min_offset;
1977         max_offset = locals_max_offset;
1978
1979         /* Arguments */
1980         for (i = 0; i < sig->param_count + sig->hasthis; ++i) {
1981                 MonoInst *ins = cfg->args [i];
1982
1983                 if (ins->opcode == OP_REGOFFSET)
1984                         min_offset = MIN (min_offset, ins->inst_offset);
1985         }
1986
1987         /* Cfa slots */
1988         g_assert (cfg->frame_reg == cfg->cfa_reg);
1989         g_assert (cfg->cfa_offset > 0);
1990         cfa_min_offset = 0;
1991         cfa_max_offset = cfg->cfa_offset;
1992
1993         min_offset = MIN (min_offset, cfa_min_offset);
1994         max_offset = MAX (max_offset, cfa_max_offset);
1995
1996         /* Fp relative slots */
1997         for (l = gcfg->stack_slots_from_fp; l; l = l->next) {
1998                 gint data = GPOINTER_TO_INT (l->data);
1999                 int offset = data >> 16;
2000
2001                 min_offset = MIN (min_offset, offset);
2002         }
2003
2004         /* Spill slots */
2005         if (!(cfg->flags & MONO_CFG_HAS_SPILLUP)) {
2006                 int stack_offset = ALIGN_TO (cfg->stack_offset, SIZEOF_SLOT);
2007                 min_offset = MIN (min_offset, (-stack_offset));
2008         }
2009
2010         /* Param area slots */
2011 #ifdef TARGET_AMD64
2012         min_offset = MIN (min_offset, -cfg->arch.sp_fp_offset);
2013 #elif defined(TARGET_X86)
2014         min_offset = MIN (min_offset, - (cfg->arch.sp_fp_offset + cfg->arch.param_area_size));
2015 #elif defined(TARGET_ARM)
2016         // FIXME:
2017 #else
2018         NOT_IMPLEMENTED;
2019 #endif
2020
2021         gcfg->min_offset = min_offset;
2022         gcfg->max_offset = max_offset;
2023         gcfg->locals_min_offset = locals_min_offset;
2024         gcfg->locals_max_offset = locals_max_offset;
2025 }
2026
2027 static void
2028 init_gcfg (MonoCompile *cfg)
2029 {
2030         int i, nregs, nslots;
2031         MonoCompileGC *gcfg = cfg->gc_info;
2032         GCCallSite **callsites;
2033         int ncallsites;
2034         MonoBasicBlock *bb;
2035         GSList *l;
2036
2037         /*
2038          * Collect callsites
2039          */
2040         ncallsites = 0;
2041         for (bb = cfg->bb_entry; bb; bb = bb->next_bb) {
2042                 ncallsites += g_slist_length (bb->gc_callsites);
2043         }
2044         callsites = mono_mempool_alloc0 (cfg->mempool, ncallsites * sizeof (GCCallSite*));
2045         i = 0;
2046         for (bb = cfg->bb_entry; bb; bb = bb->next_bb) {
2047                 for (l = bb->gc_callsites; l; l = l->next)
2048                         callsites [i++] = l->data;
2049         }
2050
2051         /* The callsites should already be ordered by pc offset */
2052         for (i = 1; i < ncallsites; ++i)
2053                 g_assert (callsites [i - 1]->pc_offset < callsites [i]->pc_offset);
2054
2055         /*
2056          * The stack frame looks like this:
2057          *
2058          * <fp + max_offset> == cfa ->  <end of previous frame>
2059          *                              <other stack slots>
2060          *                              <locals>
2061          *                              <other stack slots>
2062          * fp + min_offset          ->
2063          * ...
2064          * fp                       ->
2065          */
2066
2067         if (cfg->verbose_level > 1)
2068                 printf ("GC Map for %s: 0x%x-0x%x\n", mono_method_full_name (cfg->method, TRUE), gcfg->min_offset, gcfg->max_offset);
2069
2070         nslots = (gcfg->max_offset - gcfg->min_offset) / SIZEOF_SLOT;
2071         nregs = NREGS;
2072
2073         gcfg->nslots = nslots;
2074         gcfg->nregs = nregs;
2075         gcfg->callsites = callsites;
2076         gcfg->ncallsites = ncallsites;
2077         gcfg->stack_bitmap_width = ALIGN_TO (nslots, 8) / 8;
2078         gcfg->reg_bitmap_width = ALIGN_TO (nregs, 8) / 8;
2079         gcfg->stack_ref_bitmap = mono_mempool_alloc0 (cfg->mempool, gcfg->stack_bitmap_width * ncallsites);
2080         gcfg->stack_pin_bitmap = mono_mempool_alloc0 (cfg->mempool, gcfg->stack_bitmap_width * ncallsites);
2081         gcfg->reg_ref_bitmap = mono_mempool_alloc0 (cfg->mempool, gcfg->reg_bitmap_width * ncallsites);
2082         gcfg->reg_pin_bitmap = mono_mempool_alloc0 (cfg->mempool, gcfg->reg_bitmap_width * ncallsites);
2083
2084         /* All slots start out as PIN */
2085         memset (gcfg->stack_pin_bitmap, 0xff, gcfg->stack_bitmap_width * ncallsites);
2086         for (i = 0; i < nregs; ++i) {
2087                 /*
2088                  * By default, registers are NOREF.
2089                  * It is possible for a callee to save them before being defined in this method,
2090                  * but the saved value is dead too, so it doesn't need to be marked.
2091                  */
2092                 if ((cfg->used_int_regs & (1 << i)))
2093                         set_reg_slot_everywhere (gcfg, i, SLOT_NOREF);
2094         }
2095 }
2096
2097 static void
2098 create_map (MonoCompile *cfg)
2099 {
2100         GCMap *map;
2101         int i, j, nregs, nslots, nref_regs, npin_regs, alloc_size, bitmaps_size, bitmaps_offset;
2102         int ntypes [16];
2103         int stack_bitmap_width, stack_bitmap_size, reg_ref_bitmap_width, reg_ref_bitmap_size;
2104         int reg_pin_bitmap_width, reg_pin_bitmap_size, bindex;
2105         int start, end;
2106         gboolean has_ref_slots, has_pin_slots, has_ref_regs, has_pin_regs;
2107         MonoCompileGC *gcfg = cfg->gc_info;
2108         GCCallSite **callsites;
2109         int ncallsites;
2110         guint8 *bitmap, *bitmaps;
2111         guint32 reg_ref_mask, reg_pin_mask;
2112
2113         ncallsites = gcfg->ncallsites;
2114         nslots = gcfg->nslots;
2115         nregs = gcfg->nregs;
2116         callsites = gcfg->callsites;
2117
2118         /* 
2119          * Compute the real size of the bitmap i.e. ignore NOREF columns at the beginning and at
2120          * the end. Also, compute whenever the map needs ref/pin bitmaps, and collect stats.
2121          */
2122         has_ref_slots = FALSE;
2123         has_pin_slots = FALSE;
2124         start = -1;
2125         end = -1;
2126         memset (ntypes, 0, sizeof (ntypes));
2127         for (i = 0; i < nslots; ++i) {
2128                 gboolean has_ref = FALSE;
2129                 gboolean has_pin = FALSE;
2130
2131                 for (j = 0; j < ncallsites; ++j) {
2132                         if (get_bit (gcfg->stack_pin_bitmap, gcfg->stack_bitmap_width, j, i))
2133                                 has_pin = TRUE;
2134                         if (get_bit (gcfg->stack_ref_bitmap, gcfg->stack_bitmap_width, j, i))
2135                                 has_ref = TRUE;
2136                 }
2137
2138                 if (has_ref)
2139                         has_ref_slots = TRUE;
2140                 if (has_pin)
2141                         has_pin_slots = TRUE;
2142
2143                 if (has_ref)
2144                         ntypes [SLOT_REF] ++;
2145                 else if (has_pin)
2146                         ntypes [SLOT_PIN] ++;
2147                 else
2148                         ntypes [SLOT_NOREF] ++;
2149
2150                 if (has_ref || has_pin) {
2151                         if (start == -1)
2152                                 start = i;
2153                         end = i + 1;
2154                 }
2155         }
2156         if (start == -1) {
2157                 start = end = nslots;
2158         } else {
2159                 g_assert (start != -1);
2160                 g_assert (start < end);
2161         }
2162
2163         has_ref_regs = FALSE;
2164         has_pin_regs = FALSE;
2165         reg_ref_mask = 0;
2166         reg_pin_mask = 0;
2167         nref_regs = 0;
2168         npin_regs = 0;
2169         for (i = 0; i < nregs; ++i) {
2170                 gboolean has_ref = FALSE;
2171                 gboolean has_pin = FALSE;
2172
2173                 if (!(cfg->used_int_regs & (1 << i)))
2174                         continue;
2175
2176                 for (j = 0; j < ncallsites; ++j) {
2177                         if (get_bit (gcfg->reg_ref_bitmap, gcfg->reg_bitmap_width, j, i)) {
2178                                 has_ref = TRUE;
2179                                 break;
2180                         }
2181                 }
2182                 for (j = 0; j < ncallsites; ++j) {
2183                         if (get_bit (gcfg->reg_pin_bitmap, gcfg->reg_bitmap_width, j, i)) {
2184                                 has_pin = TRUE;
2185                                 break;
2186                         }
2187                 }
2188
2189                 if (has_ref) {
2190                         reg_ref_mask |= (1 << i);
2191                         has_ref_regs = TRUE;
2192                         nref_regs ++;
2193                 }
2194                 if (has_pin) {
2195                         reg_pin_mask |= (1 << i);
2196                         has_pin_regs = TRUE;
2197                         npin_regs ++;
2198                 }
2199         }
2200
2201         if (cfg->verbose_level > 1)
2202                 printf ("Slots: %d Start: %d End: %d Refs: %d NoRefs: %d Pin: %d Callsites: %d\n", nslots, start, end, ntypes [SLOT_REF], ntypes [SLOT_NOREF], ntypes [SLOT_PIN], ncallsites);
2203
2204         /* Create the GC Map */
2205
2206         stack_bitmap_width = ALIGN_TO (end - start, 8) / 8;
2207         stack_bitmap_size = stack_bitmap_width * ncallsites;
2208         reg_ref_bitmap_width = ALIGN_TO (nref_regs, 8) / 8;
2209         reg_ref_bitmap_size = reg_ref_bitmap_width * ncallsites;
2210         reg_pin_bitmap_width = ALIGN_TO (npin_regs, 8) / 8;
2211         reg_pin_bitmap_size = reg_pin_bitmap_width * ncallsites;
2212         bitmaps_size = (has_ref_slots ? stack_bitmap_size : 0) + (has_pin_slots ? stack_bitmap_size : 0) + (has_ref_regs ? reg_ref_bitmap_size : 0) + (has_pin_regs ? reg_pin_bitmap_size : 0);
2213         
2214         map = mono_mempool_alloc0 (cfg->mempool, sizeof (GCMap));
2215
2216         map->frame_reg = cfg->frame_reg;
2217         map->start_offset = gcfg->min_offset;
2218         map->end_offset = gcfg->min_offset + (nslots * SIZEOF_SLOT);
2219         map->map_offset = start * SIZEOF_SLOT;
2220         map->nslots = end - start;
2221         map->has_ref_slots = has_ref_slots;
2222         map->has_pin_slots = has_pin_slots;
2223         map->has_ref_regs = has_ref_regs;
2224         map->has_pin_regs = has_pin_regs;
2225         g_assert (nregs < 32);
2226         map->used_int_regs = cfg->used_int_regs;
2227         map->reg_ref_mask = reg_ref_mask;
2228         map->reg_pin_mask = reg_pin_mask;
2229         map->nref_regs = nref_regs;
2230         map->npin_regs = npin_regs;
2231
2232         bitmaps = mono_mempool_alloc0 (cfg->mempool, bitmaps_size);
2233
2234         bitmaps_offset = 0;
2235         if (has_ref_slots) {
2236                 map->stack_ref_bitmap_offset = bitmaps_offset;
2237                 bitmaps_offset += stack_bitmap_size;
2238
2239                 bitmap = &bitmaps [map->stack_ref_bitmap_offset];
2240                 for (i = 0; i < nslots; ++i) {
2241                         for (j = 0; j < ncallsites; ++j) {
2242                                 if (get_bit (gcfg->stack_ref_bitmap, gcfg->stack_bitmap_width, j, i))
2243                                         set_bit (bitmap, stack_bitmap_width, j, i - start);
2244                         }
2245                 }
2246         }
2247         if (has_pin_slots) {
2248                 map->stack_pin_bitmap_offset = bitmaps_offset;
2249                 bitmaps_offset += stack_bitmap_size;
2250
2251                 bitmap = &bitmaps [map->stack_pin_bitmap_offset];
2252                 for (i = 0; i < nslots; ++i) {
2253                         for (j = 0; j < ncallsites; ++j) {
2254                                 if (get_bit (gcfg->stack_pin_bitmap, gcfg->stack_bitmap_width, j, i))
2255                                         set_bit (bitmap, stack_bitmap_width, j, i - start);
2256                         }
2257                 }
2258         }
2259         if (has_ref_regs) {
2260                 map->reg_ref_bitmap_offset = bitmaps_offset;
2261                 bitmaps_offset += reg_ref_bitmap_size;
2262
2263                 bitmap = &bitmaps [map->reg_ref_bitmap_offset];
2264                 bindex = 0;
2265                 for (i = 0; i < nregs; ++i) {
2266                         if (reg_ref_mask & (1 << i)) {
2267                                 for (j = 0; j < ncallsites; ++j) {
2268                                         if (get_bit (gcfg->reg_ref_bitmap, gcfg->reg_bitmap_width, j, i))
2269                                                 set_bit (bitmap, reg_ref_bitmap_width, j, bindex);
2270                                 }
2271                                 bindex ++;
2272                         }
2273                 }
2274         }
2275         if (has_pin_regs) {
2276                 map->reg_pin_bitmap_offset = bitmaps_offset;
2277                 bitmaps_offset += reg_pin_bitmap_size;
2278
2279                 bitmap = &bitmaps [map->reg_pin_bitmap_offset];
2280                 bindex = 0;
2281                 for (i = 0; i < nregs; ++i) {
2282                         if (reg_pin_mask & (1 << i)) {
2283                                 for (j = 0; j < ncallsites; ++j) {
2284                                         if (get_bit (gcfg->reg_pin_bitmap, gcfg->reg_bitmap_width, j, i))
2285                                                 set_bit (bitmap, reg_pin_bitmap_width, j, bindex);
2286                                 }
2287                                 bindex ++;
2288                         }
2289                 }
2290         }
2291
2292         /* Call sites */
2293         map->ncallsites = ncallsites;
2294         if (cfg->code_len < 256)
2295                 map->callsite_entry_size = 1;
2296         else if (cfg->code_len < 65536)
2297                 map->callsite_entry_size = 2;
2298         else
2299                 map->callsite_entry_size = 4;
2300
2301         /* Encode the GC Map */
2302         {
2303                 guint8 buf [256];
2304                 guint8 *endbuf;
2305                 GCEncodedMap *emap;
2306                 int encoded_size;
2307                 guint8 *p;
2308
2309                 encode_gc_map (map, buf, &endbuf);
2310                 g_assert (endbuf - buf < 256);
2311
2312                 encoded_size = endbuf - buf;
2313                 alloc_size = sizeof (GCEncodedMap) + ALIGN_TO (encoded_size, map->callsite_entry_size) + (map->callsite_entry_size * map->ncallsites) + bitmaps_size;
2314
2315                 emap = mono_domain_alloc0 (cfg->domain, alloc_size);
2316                 //emap->ref_slots = map->ref_slots;
2317
2318                 /* Encoded fixed fields */
2319                 p = &emap->encoded [0];
2320                 //emap->encoded_size = encoded_size;
2321                 memcpy (p, buf, encoded_size);
2322                 p += encoded_size;
2323
2324                 /* Callsite table */
2325                 p = (guint8*)ALIGN_TO ((mgreg_t)p, map->callsite_entry_size);
2326                 if (map->callsite_entry_size == 1) {
2327                         guint8 *offsets = p;
2328                         for (i = 0; i < ncallsites; ++i)
2329                                 offsets [i] = callsites [i]->pc_offset;
2330                         stats.gc_callsites8_size += ncallsites * sizeof (guint8);
2331                 } else if (map->callsite_entry_size == 2) {
2332                         guint16 *offsets = (guint16*)p;
2333                         for (i = 0; i < ncallsites; ++i)
2334                                 offsets [i] = callsites [i]->pc_offset;
2335                         stats.gc_callsites16_size += ncallsites * sizeof (guint16);
2336                 } else {
2337                         guint32 *offsets = (guint32*)p;
2338                         for (i = 0; i < ncallsites; ++i)
2339                                 offsets [i] = callsites [i]->pc_offset;
2340                         stats.gc_callsites32_size += ncallsites * sizeof (guint32);
2341                 }
2342                 p += ncallsites * map->callsite_entry_size;
2343
2344                 /* Bitmaps */
2345                 memcpy (p, bitmaps, bitmaps_size);
2346                 p += bitmaps_size;
2347
2348                 g_assert ((guint8*)p - (guint8*)emap <= alloc_size);
2349
2350                 stats.gc_maps_size += alloc_size;
2351                 stats.gc_callsites_size += ncallsites * map->callsite_entry_size;
2352                 stats.gc_bitmaps_size += bitmaps_size;
2353                 stats.gc_map_struct_size += sizeof (GCEncodedMap) + encoded_size;
2354
2355                 cfg->jit_info->gc_info = emap;
2356
2357                 cfg->gc_map = (guint8*)emap;
2358                 cfg->gc_map_size = alloc_size;
2359         }
2360
2361         stats.all_slots += nslots;
2362         stats.ref_slots += ntypes [SLOT_REF];
2363         stats.noref_slots += ntypes [SLOT_NOREF];
2364         stats.pin_slots += ntypes [SLOT_PIN];
2365 }
2366
2367 void
2368 mini_gc_create_gc_map (MonoCompile *cfg)
2369 {
2370         if (!cfg->compute_gc_maps)
2371                 return;
2372
2373         /*
2374          * During marking, all frames except the top frame are at a call site, and we mark the
2375          * top frame conservatively. This means that we only need to compute and record
2376          * GC maps for call sites.
2377          */
2378
2379         if (!(cfg->comp_done & MONO_COMP_LIVENESS))
2380                 /* Without liveness info, the live ranges are not precise enough */
2381                 return;
2382
2383         mono_analyze_liveness_gc (cfg);
2384
2385         compute_frame_size (cfg);
2386
2387         init_gcfg (cfg);
2388
2389         process_spill_slots (cfg);
2390         process_other_slots (cfg);
2391         process_param_area_slots (cfg);
2392         process_variables (cfg);
2393         process_finally_clauses (cfg);
2394
2395         create_map (cfg);
2396 }
2397
2398 static void
2399 parse_debug_options (void)
2400 {
2401         char **opts, **ptr;
2402         char *env;
2403
2404         env = getenv ("MONO_GCMAP_DEBUG");
2405         if (!env)
2406                 return;
2407
2408         opts = g_strsplit (env, ",", -1);
2409         for (ptr = opts; ptr && *ptr; ptr ++) {
2410                 /* No options yet */
2411                 fprintf (stderr, "Invalid format for the MONO_GCMAP_DEBUG env variable: '%s'\n", env);
2412                 exit (1);
2413         }
2414         g_strfreev (opts);
2415 }
2416
2417 void
2418 mini_gc_init (void)
2419 {
2420         MonoGCCallbacks cb;
2421
2422         memset (&cb, 0, sizeof (cb));
2423         cb.thread_attach_func = thread_attach_func;
2424         cb.thread_detach_func = thread_detach_func;
2425         cb.thread_suspend_func = thread_suspend_func;
2426         /* Comment this out to disable precise stack marking */
2427         cb.thread_mark_func = thread_mark_func;
2428         mono_gc_set_gc_callbacks (&cb);
2429
2430         logfile = mono_gc_get_logfile ();
2431
2432         parse_debug_options ();
2433
2434         mono_counters_register ("GC Maps size",
2435                                                         MONO_COUNTER_GC | MONO_COUNTER_INT, &stats.gc_maps_size);
2436         mono_counters_register ("GC Call Sites size",
2437                                                         MONO_COUNTER_GC | MONO_COUNTER_INT, &stats.gc_callsites_size);
2438         mono_counters_register ("GC Bitmaps size",
2439                                                         MONO_COUNTER_GC | MONO_COUNTER_INT, &stats.gc_bitmaps_size);
2440         mono_counters_register ("GC Map struct size",
2441                                                         MONO_COUNTER_GC | MONO_COUNTER_INT, &stats.gc_map_struct_size);
2442         mono_counters_register ("GC Call Sites encoded using 8 bits",
2443                                                         MONO_COUNTER_GC | MONO_COUNTER_INT, &stats.gc_callsites8_size);
2444         mono_counters_register ("GC Call Sites encoded using 16 bits",
2445                                                         MONO_COUNTER_GC | MONO_COUNTER_INT, &stats.gc_callsites16_size);
2446         mono_counters_register ("GC Call Sites encoded using 32 bits",
2447                                                         MONO_COUNTER_GC | MONO_COUNTER_INT, &stats.gc_callsites32_size);
2448
2449         mono_counters_register ("GC Map slots (all)",
2450                                                         MONO_COUNTER_GC | MONO_COUNTER_INT, &stats.all_slots);
2451         mono_counters_register ("GC Map slots (ref)",
2452                                                         MONO_COUNTER_GC | MONO_COUNTER_INT, &stats.ref_slots);
2453         mono_counters_register ("GC Map slots (noref)",
2454                                                         MONO_COUNTER_GC | MONO_COUNTER_INT, &stats.noref_slots);
2455         mono_counters_register ("GC Map slots (pin)",
2456                                                         MONO_COUNTER_GC | MONO_COUNTER_INT, &stats.pin_slots);
2457
2458         mono_counters_register ("GC TLS Data size",
2459                                                         MONO_COUNTER_GC | MONO_COUNTER_INT, &stats.tlsdata_size);
2460
2461         mono_counters_register ("Stack space scanned (all)",
2462                                                         MONO_COUNTER_GC | MONO_COUNTER_INT, &stats.scanned_stacks);
2463         mono_counters_register ("Stack space scanned (native)",
2464                                                         MONO_COUNTER_GC | MONO_COUNTER_INT, &stats.scanned_native);
2465         mono_counters_register ("Stack space scanned (other)",
2466                                                         MONO_COUNTER_GC | MONO_COUNTER_INT, &stats.scanned_other);
2467         mono_counters_register ("Stack space scanned (using GC Maps)",
2468                                                         MONO_COUNTER_GC | MONO_COUNTER_INT, &stats.scanned);
2469         mono_counters_register ("Stack space scanned (precise)",
2470                                                         MONO_COUNTER_GC | MONO_COUNTER_INT, &stats.scanned_precisely);
2471         mono_counters_register ("Stack space scanned (pin)",
2472                                                         MONO_COUNTER_GC | MONO_COUNTER_INT, &stats.scanned_conservatively);
2473         mono_counters_register ("Stack space scanned (pin registers)",
2474                                                         MONO_COUNTER_GC | MONO_COUNTER_INT, &stats.scanned_registers);
2475 }
2476
2477 #else
2478
2479 void
2480 mini_gc_init (void)
2481 {
2482 }
2483
2484 static void
2485 mini_gc_init_gc_map (MonoCompile *cfg)
2486 {
2487 }
2488
2489 void
2490 mini_gc_create_gc_map (MonoCompile *cfg)
2491 {
2492 }
2493
2494 void
2495 mini_gc_set_slot_type_from_fp (MonoCompile *cfg, int slot_offset, GCSlotType type)
2496 {
2497 }
2498
2499 void
2500 mini_gc_set_slot_type_from_cfa (MonoCompile *cfg, int slot_offset, GCSlotType type)
2501 {
2502 }
2503
2504 #endif
2505
2506 /*
2507  * mini_gc_init_cfg:
2508  *
2509  *   Set GC specific options in CFG.
2510  */
2511 void
2512 mini_gc_init_cfg (MonoCompile *cfg)
2513 {
2514         if (mono_gc_is_moving ()) {
2515                 cfg->disable_ref_noref_stack_slot_share = TRUE;
2516                 cfg->gen_write_barriers = TRUE;
2517         }
2518
2519         mini_gc_init_gc_map (cfg);
2520 }
2521
2522 /*
2523  * Problems with the current code:
2524  * - the stack walk is slow
2525  * - vtypes/refs used in EH regions are treated conservatively
2526  * - if the code is finished, less pinning will be done, causing problems because
2527  *   we promote all surviving objects to old-gen.
2528  * - the unwind code can't handle a method stopped inside a finally region, it thinks the caller is
2529  *   another method, but in reality it is either the exception handling code or the CALL_HANDLER opcode.
2530  *   This manifests in "Unable to find ip offset x in callsite list" assertions.
2531  * - the unwind code also can't handle frames which are in the epilog, since the unwind info is not
2532  *   precise there.
2533  */
2534
2535 /*
2536  * Ideas for creating smaller GC maps:
2537  * - remove empty columns from the bitmaps. This requires adding a mask bit array for
2538  *   each bitmap.
2539  * - merge reg and stack slot bitmaps, so the unused bits at the end of the reg bitmap are
2540  *   not wasted.
2541  * - if the bitmap width is not a multiple of 8, the remaining bits are wasted.
2542  * - group ref and non-ref stack slots together in mono_allocate_stack_slots ().
2543  * - add an index for the callsite table so that each entry can be encoded as a 1 byte difference
2544  *   from an index entry.
2545  */