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