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