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