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