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