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