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