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