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