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