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