1 /* -----------------------------------------------------------------------------
3 * (c) The GHC Team 1998-2003
5 * Generational garbage collector
7 * ---------------------------------------------------------------------------*/
9 #include "PosixSource.h"
15 #include "LdvProfile.h"
20 #include "BlockAlloc.h"
26 #include "ParTicky.h" // ToDo: move into Rts.h
27 #include "GCCompact.h"
30 #if defined(GRAN) || defined(PAR)
31 # include "GranSimRts.h"
32 # include "ParallelRts.h"
36 # include "ParallelDebug.h"
41 #if defined(RTS_GTK_FRONTPANEL)
42 #include "FrontPanel.h"
45 #include "RetainerProfile.h"
49 /* STATIC OBJECT LIST.
52 * We maintain a linked list of static objects that are still live.
53 * The requirements for this list are:
55 * - we need to scan the list while adding to it, in order to
56 * scavenge all the static objects (in the same way that
57 * breadth-first scavenging works for dynamic objects).
59 * - we need to be able to tell whether an object is already on
60 * the list, to break loops.
62 * Each static object has a "static link field", which we use for
63 * linking objects on to the list. We use a stack-type list, consing
64 * objects on the front as they are added (this means that the
65 * scavenge phase is depth-first, not breadth-first, but that
68 * A separate list is kept for objects that have been scavenged
69 * already - this is so that we can zero all the marks afterwards.
71 * An object is on the list if its static link field is non-zero; this
72 * means that we have to mark the end of the list with '1', not NULL.
74 * Extra notes for generational GC:
76 * Each generation has a static object list associated with it. When
77 * collecting generations up to N, we treat the static object lists
78 * from generations > N as roots.
80 * We build up a static object list while collecting generations 0..N,
81 * which is then appended to the static object list of generation N+1.
83 static StgClosure* static_objects; // live static objects
84 StgClosure* scavenged_static_objects; // static objects scavenged so far
86 /* N is the oldest generation being collected, where the generations
87 * are numbered starting at 0. A major GC (indicated by the major_gc
88 * flag) is when we're collecting all generations. We only attempt to
89 * deal with static objects and GC CAFs when doing a major GC.
92 static rtsBool major_gc;
94 /* Youngest generation that objects should be evacuated to in
95 * evacuate(). (Logically an argument to evacuate, but it's static
96 * a lot of the time so we optimise it into a global variable).
102 StgWeak *old_weak_ptr_list; // also pending finaliser list
104 /* Which stage of processing various kinds of weak pointer are we at?
105 * (see traverse_weak_ptr_list() below for discussion).
107 typedef enum { WeakPtrs, WeakThreads, WeakDone } WeakStage;
108 static WeakStage weak_stage;
110 /* List of all threads during GC
112 static StgTSO *old_all_threads;
113 StgTSO *resurrected_threads;
115 /* Flag indicating failure to evacuate an object to the desired
118 static rtsBool failed_to_evac;
120 /* Old to-space (used for two-space collector only)
122 static bdescr *old_to_blocks;
124 /* Data used for allocation area sizing.
126 static lnat new_blocks; // blocks allocated during this GC
127 static lnat g0s0_pcnt_kept = 30; // percentage of g0s0 live at last minor GC
129 /* Used to avoid long recursion due to selector thunks
131 static lnat thunk_selector_depth = 0;
132 #define MAX_THUNK_SELECTOR_DEPTH 8
134 /* -----------------------------------------------------------------------------
135 Static function declarations
136 -------------------------------------------------------------------------- */
138 static bdescr * gc_alloc_block ( step *stp );
139 static void mark_root ( StgClosure **root );
141 // Use a register argument for evacuate, if available.
143 #define REGPARM1 __attribute__((regparm(1)))
148 REGPARM1 static StgClosure * evacuate (StgClosure *q);
150 static void zero_static_object_list ( StgClosure* first_static );
152 static rtsBool traverse_weak_ptr_list ( void );
153 static void mark_weak_ptr_list ( StgWeak **list );
155 static StgClosure * eval_thunk_selector ( nat field, StgSelector * p );
158 static void scavenge ( step * );
159 static void scavenge_mark_stack ( void );
160 static void scavenge_stack ( StgPtr p, StgPtr stack_end );
161 static rtsBool scavenge_one ( StgPtr p );
162 static void scavenge_large ( step * );
163 static void scavenge_static ( void );
164 static void scavenge_mutable_list ( generation *g );
166 static void scavenge_large_bitmap ( StgPtr p,
167 StgLargeBitmap *large_bitmap,
170 #if 0 && defined(DEBUG)
171 static void gcCAFs ( void );
174 /* -----------------------------------------------------------------------------
175 inline functions etc. for dealing with the mark bitmap & stack.
176 -------------------------------------------------------------------------- */
178 #define MARK_STACK_BLOCKS 4
180 static bdescr *mark_stack_bdescr;
181 static StgPtr *mark_stack;
182 static StgPtr *mark_sp;
183 static StgPtr *mark_splim;
185 // Flag and pointers used for falling back to a linear scan when the
186 // mark stack overflows.
187 static rtsBool mark_stack_overflowed;
188 static bdescr *oldgen_scan_bd;
189 static StgPtr oldgen_scan;
191 STATIC_INLINE rtsBool
192 mark_stack_empty(void)
194 return mark_sp == mark_stack;
197 STATIC_INLINE rtsBool
198 mark_stack_full(void)
200 return mark_sp >= mark_splim;
204 reset_mark_stack(void)
206 mark_sp = mark_stack;
210 push_mark_stack(StgPtr p)
221 /* -----------------------------------------------------------------------------
222 Allocate a new to-space block in the given step.
223 -------------------------------------------------------------------------- */
226 gc_alloc_block(step *stp)
228 bdescr *bd = allocBlock();
229 bd->gen_no = stp->gen_no;
233 // blocks in to-space in generations up to and including N
234 // get the BF_EVACUATED flag.
235 if (stp->gen_no <= N) {
236 bd->flags = BF_EVACUATED;
241 // Start a new to-space block, chain it on after the previous one.
242 if (stp->hp_bd == NULL) {
245 stp->hp_bd->free = stp->hp;
246 stp->hp_bd->link = bd;
251 stp->hpLim = stp->hp + BLOCK_SIZE_W;
259 /* -----------------------------------------------------------------------------
262 Rough outline of the algorithm: for garbage collecting generation N
263 (and all younger generations):
265 - follow all pointers in the root set. the root set includes all
266 mutable objects in all generations (mutable_list).
268 - for each pointer, evacuate the object it points to into either
270 + to-space of the step given by step->to, which is the next
271 highest step in this generation or the first step in the next
272 generation if this is the last step.
274 + to-space of generations[evac_gen]->steps[0], if evac_gen != 0.
275 When we evacuate an object we attempt to evacuate
276 everything it points to into the same generation - this is
277 achieved by setting evac_gen to the desired generation. If
278 we can't do this, then an entry in the mut list has to
279 be made for the cross-generation pointer.
281 + if the object is already in a generation > N, then leave
284 - repeatedly scavenge to-space from each step in each generation
285 being collected until no more objects can be evacuated.
287 - free from-space in each step, and set from-space = to-space.
289 Locks held: sched_mutex
291 -------------------------------------------------------------------------- */
294 GarbageCollect ( void (*get_roots)(evac_fn), rtsBool force_major_gc )
298 lnat live, allocated, collected = 0, copied = 0;
299 lnat oldgen_saved_blocks = 0;
303 CostCentreStack *prev_CCS;
306 #if defined(DEBUG) && defined(GRAN)
307 IF_DEBUG(gc, debugBelch("@@ Starting garbage collection at %ld (%lx)\n",
311 #if defined(RTS_USER_SIGNALS)
316 // tell the STM to discard any cached closures its hoping to re-use
319 // tell the stats department that we've started a GC
322 // Init stats and print par specific (timing) info
323 PAR_TICKY_PAR_START();
325 // attribute any costs to CCS_GC
331 /* Approximate how much we allocated.
332 * Todo: only when generating stats?
334 allocated = calcAllocated();
336 /* Figure out which generation to collect
338 if (force_major_gc) {
339 N = RtsFlags.GcFlags.generations - 1;
343 for (g = 0; g < RtsFlags.GcFlags.generations; g++) {
344 if (generations[g].steps[0].n_blocks +
345 generations[g].steps[0].n_large_blocks
346 >= generations[g].max_blocks) {
350 major_gc = (N == RtsFlags.GcFlags.generations-1);
353 #ifdef RTS_GTK_FRONTPANEL
354 if (RtsFlags.GcFlags.frontpanel) {
355 updateFrontPanelBeforeGC(N);
359 // check stack sanity *before* GC (ToDo: check all threads)
361 // ToDo!: check sanity IF_DEBUG(sanity, checkTSOsSanity());
363 IF_DEBUG(sanity, checkFreeListSanity());
365 /* Initialise the static object lists
367 static_objects = END_OF_STATIC_LIST;
368 scavenged_static_objects = END_OF_STATIC_LIST;
370 /* Save the old to-space if we're doing a two-space collection
372 if (RtsFlags.GcFlags.generations == 1) {
373 old_to_blocks = g0s0->to_blocks;
374 g0s0->to_blocks = NULL;
375 g0s0->n_to_blocks = 0;
378 /* Keep a count of how many new blocks we allocated during this GC
379 * (used for resizing the allocation area, later).
383 // Initialise to-space in all the generations/steps that we're
386 for (g = 0; g <= N; g++) {
388 // throw away the mutable list. Invariant: the mutable list
389 // always has at least one block; this means we can avoid a check for
390 // NULL in recordMutable().
392 freeChain(generations[g].mut_list);
393 generations[g].mut_list = allocBlock();
396 for (s = 0; s < generations[g].n_steps; s++) {
398 // generation 0, step 0 doesn't need to-space
399 if (g == 0 && s == 0 && RtsFlags.GcFlags.generations > 1) {
403 stp = &generations[g].steps[s];
404 ASSERT(stp->gen_no == g);
406 // start a new to-space for this step.
409 stp->to_blocks = NULL;
411 // allocate the first to-space block; extra blocks will be
412 // chained on as necessary.
413 bd = gc_alloc_block(stp);
415 stp->scan = bd->start;
418 // initialise the large object queues.
419 stp->new_large_objects = NULL;
420 stp->scavenged_large_objects = NULL;
421 stp->n_scavenged_large_blocks = 0;
423 // mark the large objects as not evacuated yet
424 for (bd = stp->large_objects; bd; bd = bd->link) {
425 bd->flags &= ~BF_EVACUATED;
428 // for a compacted step, we need to allocate the bitmap
429 if (stp->is_compacted) {
430 nat bitmap_size; // in bytes
431 bdescr *bitmap_bdescr;
434 bitmap_size = stp->n_blocks * BLOCK_SIZE / (sizeof(W_)*BITS_PER_BYTE);
436 if (bitmap_size > 0) {
437 bitmap_bdescr = allocGroup((nat)BLOCK_ROUND_UP(bitmap_size)
439 stp->bitmap = bitmap_bdescr;
440 bitmap = bitmap_bdescr->start;
442 IF_DEBUG(gc, debugBelch("bitmap_size: %d, bitmap: %p",
443 bitmap_size, bitmap););
445 // don't forget to fill it with zeros!
446 memset(bitmap, 0, bitmap_size);
448 // For each block in this step, point to its bitmap from the
450 for (bd=stp->blocks; bd != NULL; bd = bd->link) {
451 bd->u.bitmap = bitmap;
452 bitmap += BLOCK_SIZE_W / (sizeof(W_)*BITS_PER_BYTE);
454 // Also at this point we set the BF_COMPACTED flag
455 // for this block. The invariant is that
456 // BF_COMPACTED is always unset, except during GC
457 // when it is set on those blocks which will be
459 bd->flags |= BF_COMPACTED;
466 /* make sure the older generations have at least one block to
467 * allocate into (this makes things easier for copy(), see below).
469 for (g = N+1; g < RtsFlags.GcFlags.generations; g++) {
470 for (s = 0; s < generations[g].n_steps; s++) {
471 stp = &generations[g].steps[s];
472 if (stp->hp_bd == NULL) {
473 ASSERT(stp->blocks == NULL);
474 bd = gc_alloc_block(stp);
478 /* Set the scan pointer for older generations: remember we
479 * still have to scavenge objects that have been promoted. */
481 stp->scan_bd = stp->hp_bd;
482 stp->to_blocks = NULL;
483 stp->n_to_blocks = 0;
484 stp->new_large_objects = NULL;
485 stp->scavenged_large_objects = NULL;
486 stp->n_scavenged_large_blocks = 0;
490 /* Allocate a mark stack if we're doing a major collection.
493 mark_stack_bdescr = allocGroup(MARK_STACK_BLOCKS);
494 mark_stack = (StgPtr *)mark_stack_bdescr->start;
495 mark_sp = mark_stack;
496 mark_splim = mark_stack + (MARK_STACK_BLOCKS * BLOCK_SIZE_W);
498 mark_stack_bdescr = NULL;
501 /* -----------------------------------------------------------------------
502 * follow all the roots that we know about:
503 * - mutable lists from each generation > N
504 * we want to *scavenge* these roots, not evacuate them: they're not
505 * going to move in this GC.
506 * Also: do them in reverse generation order. This is because we
507 * often want to promote objects that are pointed to by older
508 * generations early, so we don't have to repeatedly copy them.
509 * Doing the generations in reverse order ensures that we don't end
510 * up in the situation where we want to evac an object to gen 3 and
511 * it has already been evaced to gen 2.
515 for (g = RtsFlags.GcFlags.generations-1; g > N; g--) {
516 generations[g].saved_mut_list = generations[g].mut_list;
517 generations[g].mut_list = allocBlock();
518 // mut_list always has at least one block.
521 for (g = RtsFlags.GcFlags.generations-1; g > N; g--) {
522 IF_PAR_DEBUG(verbose, printMutableList(&generations[g]));
523 scavenge_mutable_list(&generations[g]);
525 for (st = generations[g].n_steps-1; st >= 0; st--) {
526 scavenge(&generations[g].steps[st]);
531 /* follow roots from the CAF list (used by GHCi)
536 /* follow all the roots that the application knows about.
539 get_roots(mark_root);
542 /* And don't forget to mark the TSO if we got here direct from
544 /* Not needed in a seq version?
546 CurrentTSO = (StgTSO *)MarkRoot((StgClosure *)CurrentTSO);
550 // Mark the entries in the GALA table of the parallel system
551 markLocalGAs(major_gc);
552 // Mark all entries on the list of pending fetches
553 markPendingFetches(major_gc);
556 /* Mark the weak pointer list, and prepare to detect dead weak
559 mark_weak_ptr_list(&weak_ptr_list);
560 old_weak_ptr_list = weak_ptr_list;
561 weak_ptr_list = NULL;
562 weak_stage = WeakPtrs;
564 /* The all_threads list is like the weak_ptr_list.
565 * See traverse_weak_ptr_list() for the details.
567 old_all_threads = all_threads;
568 all_threads = END_TSO_QUEUE;
569 resurrected_threads = END_TSO_QUEUE;
571 /* Mark the stable pointer table.
573 markStablePtrTable(mark_root);
575 /* -------------------------------------------------------------------------
576 * Repeatedly scavenge all the areas we know about until there's no
577 * more scavenging to be done.
584 // scavenge static objects
585 if (major_gc && static_objects != END_OF_STATIC_LIST) {
586 IF_DEBUG(sanity, checkStaticObjects(static_objects));
590 /* When scavenging the older generations: Objects may have been
591 * evacuated from generations <= N into older generations, and we
592 * need to scavenge these objects. We're going to try to ensure that
593 * any evacuations that occur move the objects into at least the
594 * same generation as the object being scavenged, otherwise we
595 * have to create new entries on the mutable list for the older
599 // scavenge each step in generations 0..maxgen
605 // scavenge objects in compacted generation
606 if (mark_stack_overflowed || oldgen_scan_bd != NULL ||
607 (mark_stack_bdescr != NULL && !mark_stack_empty())) {
608 scavenge_mark_stack();
612 for (gen = RtsFlags.GcFlags.generations; --gen >= 0; ) {
613 for (st = generations[gen].n_steps; --st >= 0; ) {
614 if (gen == 0 && st == 0 && RtsFlags.GcFlags.generations > 1) {
617 stp = &generations[gen].steps[st];
619 if (stp->hp_bd != stp->scan_bd || stp->scan < stp->hp) {
624 if (stp->new_large_objects != NULL) {
633 if (flag) { goto loop; }
635 // must be last... invariant is that everything is fully
636 // scavenged at this point.
637 if (traverse_weak_ptr_list()) { // returns rtsTrue if evaced something
642 /* Update the pointers from the "main thread" list - these are
643 * treated as weak pointers because we want to allow a main thread
644 * to get a BlockedOnDeadMVar exception in the same way as any other
645 * thread. Note that the threads should all have been retained by
646 * GC by virtue of being on the all_threads list, we're just
647 * updating pointers here.
652 for (m = main_threads; m != NULL; m = m->link) {
653 tso = (StgTSO *) isAlive((StgClosure *)m->tso);
655 barf("main thread has been GC'd");
662 // Reconstruct the Global Address tables used in GUM
663 rebuildGAtables(major_gc);
664 IF_DEBUG(sanity, checkLAGAtable(rtsTrue/*check closures, too*/));
667 // Now see which stable names are still alive.
670 // Tidy the end of the to-space chains
671 for (g = 0; g < RtsFlags.GcFlags.generations; g++) {
672 for (s = 0; s < generations[g].n_steps; s++) {
673 stp = &generations[g].steps[s];
674 if (!(g == 0 && s == 0 && RtsFlags.GcFlags.generations > 1)) {
675 ASSERT(Bdescr(stp->hp) == stp->hp_bd);
676 stp->hp_bd->free = stp->hp;
682 // We call processHeapClosureForDead() on every closure destroyed during
683 // the current garbage collection, so we invoke LdvCensusForDead().
684 if (RtsFlags.ProfFlags.doHeapProfile == HEAP_BY_LDV
685 || RtsFlags.ProfFlags.bioSelector != NULL)
689 // NO MORE EVACUATION AFTER THIS POINT!
690 // Finally: compaction of the oldest generation.
691 if (major_gc && oldest_gen->steps[0].is_compacted) {
692 // save number of blocks for stats
693 oldgen_saved_blocks = oldest_gen->steps[0].n_blocks;
697 IF_DEBUG(sanity, checkGlobalTSOList(rtsFalse));
699 /* run through all the generations/steps and tidy up
701 copied = new_blocks * BLOCK_SIZE_W;
702 for (g = 0; g < RtsFlags.GcFlags.generations; g++) {
705 generations[g].collections++; // for stats
708 // Count the mutable list as bytes "copied" for the purposes of
709 // stats. Every mutable list is copied during every GC.
711 for (bd = generations[g].mut_list; bd != NULL; bd = bd->link) {
712 copied += (bd->free - bd->start) * sizeof(StgWord);
716 for (s = 0; s < generations[g].n_steps; s++) {
718 stp = &generations[g].steps[s];
720 if (!(g == 0 && s == 0 && RtsFlags.GcFlags.generations > 1)) {
721 // stats information: how much we copied
723 copied -= stp->hp_bd->start + BLOCK_SIZE_W -
728 // for generations we collected...
731 // rough calculation of garbage collected, for stats output
732 if (stp->is_compacted) {
733 collected += (oldgen_saved_blocks - stp->n_blocks) * BLOCK_SIZE_W;
735 collected += stp->n_blocks * BLOCK_SIZE_W;
738 /* free old memory and shift to-space into from-space for all
739 * the collected steps (except the allocation area). These
740 * freed blocks will probaby be quickly recycled.
742 if (!(g == 0 && s == 0)) {
743 if (stp->is_compacted) {
744 // for a compacted step, just shift the new to-space
745 // onto the front of the now-compacted existing blocks.
746 for (bd = stp->to_blocks; bd != NULL; bd = bd->link) {
747 bd->flags &= ~BF_EVACUATED; // now from-space
749 // tack the new blocks on the end of the existing blocks
750 if (stp->blocks == NULL) {
751 stp->blocks = stp->to_blocks;
753 for (bd = stp->blocks; bd != NULL; bd = next) {
756 bd->link = stp->to_blocks;
758 // NB. this step might not be compacted next
759 // time, so reset the BF_COMPACTED flags.
760 // They are set before GC if we're going to
761 // compact. (search for BF_COMPACTED above).
762 bd->flags &= ~BF_COMPACTED;
765 // add the new blocks to the block tally
766 stp->n_blocks += stp->n_to_blocks;
768 freeChain(stp->blocks);
769 stp->blocks = stp->to_blocks;
770 stp->n_blocks = stp->n_to_blocks;
771 for (bd = stp->blocks; bd != NULL; bd = bd->link) {
772 bd->flags &= ~BF_EVACUATED; // now from-space
775 stp->to_blocks = NULL;
776 stp->n_to_blocks = 0;
779 /* LARGE OBJECTS. The current live large objects are chained on
780 * scavenged_large, having been moved during garbage
781 * collection from large_objects. Any objects left on
782 * large_objects list are therefore dead, so we free them here.
784 for (bd = stp->large_objects; bd != NULL; bd = next) {
790 // update the count of blocks used by large objects
791 for (bd = stp->scavenged_large_objects; bd != NULL; bd = bd->link) {
792 bd->flags &= ~BF_EVACUATED;
794 stp->large_objects = stp->scavenged_large_objects;
795 stp->n_large_blocks = stp->n_scavenged_large_blocks;
798 // for older generations...
800 /* For older generations, we need to append the
801 * scavenged_large_object list (i.e. large objects that have been
802 * promoted during this GC) to the large_object list for that step.
804 for (bd = stp->scavenged_large_objects; bd; bd = next) {
806 bd->flags &= ~BF_EVACUATED;
807 dbl_link_onto(bd, &stp->large_objects);
810 // add the new blocks we promoted during this GC
811 stp->n_blocks += stp->n_to_blocks;
812 stp->n_to_blocks = 0;
813 stp->n_large_blocks += stp->n_scavenged_large_blocks;
818 /* Reset the sizes of the older generations when we do a major
821 * CURRENT STRATEGY: make all generations except zero the same size.
822 * We have to stay within the maximum heap size, and leave a certain
823 * percentage of the maximum heap size available to allocate into.
825 if (major_gc && RtsFlags.GcFlags.generations > 1) {
826 nat live, size, min_alloc;
827 nat max = RtsFlags.GcFlags.maxHeapSize;
828 nat gens = RtsFlags.GcFlags.generations;
830 // live in the oldest generations
831 live = oldest_gen->steps[0].n_blocks +
832 oldest_gen->steps[0].n_large_blocks;
834 // default max size for all generations except zero
835 size = stg_max(live * RtsFlags.GcFlags.oldGenFactor,
836 RtsFlags.GcFlags.minOldGenSize);
838 // minimum size for generation zero
839 min_alloc = stg_max((RtsFlags.GcFlags.pcFreeHeap * max) / 200,
840 RtsFlags.GcFlags.minAllocAreaSize);
842 // Auto-enable compaction when the residency reaches a
843 // certain percentage of the maximum heap size (default: 30%).
844 if (RtsFlags.GcFlags.generations > 1 &&
845 (RtsFlags.GcFlags.compact ||
847 oldest_gen->steps[0].n_blocks >
848 (RtsFlags.GcFlags.compactThreshold * max) / 100))) {
849 oldest_gen->steps[0].is_compacted = 1;
850 // debugBelch("compaction: on\n", live);
852 oldest_gen->steps[0].is_compacted = 0;
853 // debugBelch("compaction: off\n", live);
856 // if we're going to go over the maximum heap size, reduce the
857 // size of the generations accordingly. The calculation is
858 // different if compaction is turned on, because we don't need
859 // to double the space required to collect the old generation.
862 // this test is necessary to ensure that the calculations
863 // below don't have any negative results - we're working
864 // with unsigned values here.
865 if (max < min_alloc) {
869 if (oldest_gen->steps[0].is_compacted) {
870 if ( (size + (size - 1) * (gens - 2) * 2) + min_alloc > max ) {
871 size = (max - min_alloc) / ((gens - 1) * 2 - 1);
874 if ( (size * (gens - 1) * 2) + min_alloc > max ) {
875 size = (max - min_alloc) / ((gens - 1) * 2);
885 debugBelch("live: %d, min_alloc: %d, size : %d, max = %d\n", live,
886 min_alloc, size, max);
889 for (g = 0; g < gens; g++) {
890 generations[g].max_blocks = size;
894 // Guess the amount of live data for stats.
897 /* Free the small objects allocated via allocate(), since this will
898 * all have been copied into G0S1 now.
900 if (small_alloc_list != NULL) {
901 freeChain(small_alloc_list);
903 small_alloc_list = NULL;
907 alloc_blocks_lim = RtsFlags.GcFlags.minAllocAreaSize;
909 // Start a new pinned_object_block
910 pinned_object_block = NULL;
912 /* Free the mark stack.
914 if (mark_stack_bdescr != NULL) {
915 freeGroup(mark_stack_bdescr);
920 for (g = 0; g <= N; g++) {
921 for (s = 0; s < generations[g].n_steps; s++) {
922 stp = &generations[g].steps[s];
923 if (stp->is_compacted && stp->bitmap != NULL) {
924 freeGroup(stp->bitmap);
929 /* Two-space collector:
930 * Free the old to-space, and estimate the amount of live data.
932 if (RtsFlags.GcFlags.generations == 1) {
935 if (old_to_blocks != NULL) {
936 freeChain(old_to_blocks);
938 for (bd = g0s0->to_blocks; bd != NULL; bd = bd->link) {
939 bd->flags = 0; // now from-space
942 /* For a two-space collector, we need to resize the nursery. */
944 /* set up a new nursery. Allocate a nursery size based on a
945 * function of the amount of live data (by default a factor of 2)
946 * Use the blocks from the old nursery if possible, freeing up any
949 * If we get near the maximum heap size, then adjust our nursery
950 * size accordingly. If the nursery is the same size as the live
951 * data (L), then we need 3L bytes. We can reduce the size of the
952 * nursery to bring the required memory down near 2L bytes.
954 * A normal 2-space collector would need 4L bytes to give the same
955 * performance we get from 3L bytes, reducing to the same
956 * performance at 2L bytes.
958 blocks = g0s0->n_to_blocks;
960 if ( RtsFlags.GcFlags.maxHeapSize != 0 &&
961 blocks * RtsFlags.GcFlags.oldGenFactor * 2 >
962 RtsFlags.GcFlags.maxHeapSize ) {
963 long adjusted_blocks; // signed on purpose
966 adjusted_blocks = (RtsFlags.GcFlags.maxHeapSize - 2 * blocks);
967 IF_DEBUG(gc, debugBelch("@@ Near maximum heap size of 0x%x blocks, blocks = %d, adjusted to %ld", RtsFlags.GcFlags.maxHeapSize, blocks, adjusted_blocks));
968 pc_free = adjusted_blocks * 100 / RtsFlags.GcFlags.maxHeapSize;
969 if (pc_free < RtsFlags.GcFlags.pcFreeHeap) /* might even be < 0 */ {
972 blocks = adjusted_blocks;
975 blocks *= RtsFlags.GcFlags.oldGenFactor;
976 if (blocks < RtsFlags.GcFlags.minAllocAreaSize) {
977 blocks = RtsFlags.GcFlags.minAllocAreaSize;
980 resizeNursery(blocks);
983 /* Generational collector:
984 * If the user has given us a suggested heap size, adjust our
985 * allocation area to make best use of the memory available.
988 if (RtsFlags.GcFlags.heapSizeSuggestion) {
990 nat needed = calcNeeded(); // approx blocks needed at next GC
992 /* Guess how much will be live in generation 0 step 0 next time.
993 * A good approximation is obtained by finding the
994 * percentage of g0s0 that was live at the last minor GC.
997 g0s0_pcnt_kept = (new_blocks * 100) / g0s0->n_blocks;
1000 /* Estimate a size for the allocation area based on the
1001 * information available. We might end up going slightly under
1002 * or over the suggested heap size, but we should be pretty
1005 * Formula: suggested - needed
1006 * ----------------------------
1007 * 1 + g0s0_pcnt_kept/100
1009 * where 'needed' is the amount of memory needed at the next
1010 * collection for collecting all steps except g0s0.
1013 (((long)RtsFlags.GcFlags.heapSizeSuggestion - (long)needed) * 100) /
1014 (100 + (long)g0s0_pcnt_kept);
1016 if (blocks < (long)RtsFlags.GcFlags.minAllocAreaSize) {
1017 blocks = RtsFlags.GcFlags.minAllocAreaSize;
1020 resizeNursery((nat)blocks);
1023 // we might have added extra large blocks to the nursery, so
1024 // resize back to minAllocAreaSize again.
1025 resizeNursery(RtsFlags.GcFlags.minAllocAreaSize);
1029 // mark the garbage collected CAFs as dead
1030 #if 0 && defined(DEBUG) // doesn't work at the moment
1031 if (major_gc) { gcCAFs(); }
1035 // resetStaticObjectForRetainerProfiling() must be called before
1037 resetStaticObjectForRetainerProfiling();
1040 // zero the scavenged static object list
1042 zero_static_object_list(scavenged_static_objects);
1045 // Reset the nursery
1048 RELEASE_LOCK(&sched_mutex);
1050 // start any pending finalizers
1051 scheduleFinalizers(old_weak_ptr_list);
1053 // send exceptions to any threads which were about to die
1054 resurrectThreads(resurrected_threads);
1056 ACQUIRE_LOCK(&sched_mutex);
1058 // Update the stable pointer hash table.
1059 updateStablePtrTable(major_gc);
1061 // check sanity after GC
1062 IF_DEBUG(sanity, checkSanity());
1064 // extra GC trace info
1065 IF_DEBUG(gc, statDescribeGens());
1068 // symbol-table based profiling
1069 /* heapCensus(to_blocks); */ /* ToDo */
1072 // restore enclosing cost centre
1077 // check for memory leaks if sanity checking is on
1078 IF_DEBUG(sanity, memInventory());
1080 #ifdef RTS_GTK_FRONTPANEL
1081 if (RtsFlags.GcFlags.frontpanel) {
1082 updateFrontPanelAfterGC( N, live );
1086 // ok, GC over: tell the stats department what happened.
1087 stat_endGC(allocated, collected, live, copied, N);
1089 #if defined(RTS_USER_SIGNALS)
1090 // unblock signals again
1091 unblockUserSignals();
1098 /* -----------------------------------------------------------------------------
1101 traverse_weak_ptr_list is called possibly many times during garbage
1102 collection. It returns a flag indicating whether it did any work
1103 (i.e. called evacuate on any live pointers).
1105 Invariant: traverse_weak_ptr_list is called when the heap is in an
1106 idempotent state. That means that there are no pending
1107 evacuate/scavenge operations. This invariant helps the weak
1108 pointer code decide which weak pointers are dead - if there are no
1109 new live weak pointers, then all the currently unreachable ones are
1112 For generational GC: we just don't try to finalize weak pointers in
1113 older generations than the one we're collecting. This could
1114 probably be optimised by keeping per-generation lists of weak
1115 pointers, but for a few weak pointers this scheme will work.
1117 There are three distinct stages to processing weak pointers:
1119 - weak_stage == WeakPtrs
1121 We process all the weak pointers whos keys are alive (evacuate
1122 their values and finalizers), and repeat until we can find no new
1123 live keys. If no live keys are found in this pass, then we
1124 evacuate the finalizers of all the dead weak pointers in order to
1127 - weak_stage == WeakThreads
1129 Now, we discover which *threads* are still alive. Pointers to
1130 threads from the all_threads and main thread lists are the
1131 weakest of all: a pointers from the finalizer of a dead weak
1132 pointer can keep a thread alive. Any threads found to be unreachable
1133 are evacuated and placed on the resurrected_threads list so we
1134 can send them a signal later.
1136 - weak_stage == WeakDone
1138 No more evacuation is done.
1140 -------------------------------------------------------------------------- */
1143 traverse_weak_ptr_list(void)
1145 StgWeak *w, **last_w, *next_w;
1147 rtsBool flag = rtsFalse;
1149 switch (weak_stage) {
1155 /* doesn't matter where we evacuate values/finalizers to, since
1156 * these pointers are treated as roots (iff the keys are alive).
1160 last_w = &old_weak_ptr_list;
1161 for (w = old_weak_ptr_list; w != NULL; w = next_w) {
1163 /* There might be a DEAD_WEAK on the list if finalizeWeak# was
1164 * called on a live weak pointer object. Just remove it.
1166 if (w->header.info == &stg_DEAD_WEAK_info) {
1167 next_w = ((StgDeadWeak *)w)->link;
1172 switch (get_itbl(w)->type) {
1175 next_w = (StgWeak *)((StgEvacuated *)w)->evacuee;
1180 /* Now, check whether the key is reachable.
1182 new = isAlive(w->key);
1185 // evacuate the value and finalizer
1186 w->value = evacuate(w->value);
1187 w->finalizer = evacuate(w->finalizer);
1188 // remove this weak ptr from the old_weak_ptr list
1190 // and put it on the new weak ptr list
1192 w->link = weak_ptr_list;
1195 IF_DEBUG(weak, debugBelch("Weak pointer still alive at %p -> %p",
1200 last_w = &(w->link);
1206 barf("traverse_weak_ptr_list: not WEAK");
1210 /* If we didn't make any changes, then we can go round and kill all
1211 * the dead weak pointers. The old_weak_ptr list is used as a list
1212 * of pending finalizers later on.
1214 if (flag == rtsFalse) {
1215 for (w = old_weak_ptr_list; w; w = w->link) {
1216 w->finalizer = evacuate(w->finalizer);
1219 // Next, move to the WeakThreads stage after fully
1220 // scavenging the finalizers we've just evacuated.
1221 weak_stage = WeakThreads;
1227 /* Now deal with the all_threads list, which behaves somewhat like
1228 * the weak ptr list. If we discover any threads that are about to
1229 * become garbage, we wake them up and administer an exception.
1232 StgTSO *t, *tmp, *next, **prev;
1234 prev = &old_all_threads;
1235 for (t = old_all_threads; t != END_TSO_QUEUE; t = next) {
1237 tmp = (StgTSO *)isAlive((StgClosure *)t);
1243 ASSERT(get_itbl(t)->type == TSO);
1244 switch (t->what_next) {
1245 case ThreadRelocated:
1250 case ThreadComplete:
1251 // finshed or died. The thread might still be alive, but we
1252 // don't keep it on the all_threads list. Don't forget to
1253 // stub out its global_link field.
1254 next = t->global_link;
1255 t->global_link = END_TSO_QUEUE;
1263 // not alive (yet): leave this thread on the
1264 // old_all_threads list.
1265 prev = &(t->global_link);
1266 next = t->global_link;
1269 // alive: move this thread onto the all_threads list.
1270 next = t->global_link;
1271 t->global_link = all_threads;
1278 /* And resurrect any threads which were about to become garbage.
1281 StgTSO *t, *tmp, *next;
1282 for (t = old_all_threads; t != END_TSO_QUEUE; t = next) {
1283 next = t->global_link;
1284 tmp = (StgTSO *)evacuate((StgClosure *)t);
1285 tmp->global_link = resurrected_threads;
1286 resurrected_threads = tmp;
1290 weak_stage = WeakDone; // *now* we're done,
1291 return rtsTrue; // but one more round of scavenging, please
1294 barf("traverse_weak_ptr_list");
1300 /* -----------------------------------------------------------------------------
1301 After GC, the live weak pointer list may have forwarding pointers
1302 on it, because a weak pointer object was evacuated after being
1303 moved to the live weak pointer list. We remove those forwarding
1306 Also, we don't consider weak pointer objects to be reachable, but
1307 we must nevertheless consider them to be "live" and retain them.
1308 Therefore any weak pointer objects which haven't as yet been
1309 evacuated need to be evacuated now.
1310 -------------------------------------------------------------------------- */
1314 mark_weak_ptr_list ( StgWeak **list )
1316 StgWeak *w, **last_w;
1319 for (w = *list; w; w = w->link) {
1320 // w might be WEAK, EVACUATED, or DEAD_WEAK (actually CON_STATIC) here
1321 ASSERT(w->header.info == &stg_DEAD_WEAK_info
1322 || get_itbl(w)->type == WEAK || get_itbl(w)->type == EVACUATED);
1323 w = (StgWeak *)evacuate((StgClosure *)w);
1325 last_w = &(w->link);
1329 /* -----------------------------------------------------------------------------
1330 isAlive determines whether the given closure is still alive (after
1331 a garbage collection) or not. It returns the new address of the
1332 closure if it is alive, or NULL otherwise.
1334 NOTE: Use it before compaction only!
1335 -------------------------------------------------------------------------- */
1339 isAlive(StgClosure *p)
1341 const StgInfoTable *info;
1346 ASSERT(LOOKS_LIKE_CLOSURE_PTR(p));
1349 // ignore static closures
1351 // ToDo: for static closures, check the static link field.
1352 // Problem here is that we sometimes don't set the link field, eg.
1353 // for static closures with an empty SRT or CONSTR_STATIC_NOCAFs.
1355 if (!HEAP_ALLOCED(p)) {
1359 // ignore closures in generations that we're not collecting.
1361 if (bd->gen_no > N) {
1365 // if it's a pointer into to-space, then we're done
1366 if (bd->flags & BF_EVACUATED) {
1370 // large objects use the evacuated flag
1371 if (bd->flags & BF_LARGE) {
1375 // check the mark bit for compacted steps
1376 if ((bd->flags & BF_COMPACTED) && is_marked((P_)p,bd)) {
1380 switch (info->type) {
1385 case IND_OLDGEN: // rely on compatible layout with StgInd
1386 case IND_OLDGEN_PERM:
1387 // follow indirections
1388 p = ((StgInd *)p)->indirectee;
1393 return ((StgEvacuated *)p)->evacuee;
1396 if (((StgTSO *)p)->what_next == ThreadRelocated) {
1397 p = (StgClosure *)((StgTSO *)p)->link;
1410 mark_root(StgClosure **root)
1412 *root = evacuate(*root);
1416 upd_evacuee(StgClosure *p, StgClosure *dest)
1418 // Source object must be in from-space:
1419 ASSERT((Bdescr((P_)p)->flags & BF_EVACUATED) == 0);
1420 // not true: (ToDo: perhaps it should be)
1421 // ASSERT(Bdescr((P_)dest)->flags & BF_EVACUATED);
1422 SET_INFO(p, &stg_EVACUATED_info);
1423 ((StgEvacuated *)p)->evacuee = dest;
1427 STATIC_INLINE StgClosure *
1428 copy(StgClosure *src, nat size, step *stp)
1433 nat size_org = size;
1436 TICK_GC_WORDS_COPIED(size);
1437 /* Find out where we're going, using the handy "to" pointer in
1438 * the step of the source object. If it turns out we need to
1439 * evacuate to an older generation, adjust it here (see comment
1442 if (stp->gen_no < evac_gen) {
1443 #ifdef NO_EAGER_PROMOTION
1444 failed_to_evac = rtsTrue;
1446 stp = &generations[evac_gen].steps[0];
1450 /* chain a new block onto the to-space for the destination step if
1453 if (stp->hp + size >= stp->hpLim) {
1454 gc_alloc_block(stp);
1457 for(to = stp->hp, from = (P_)src; size>0; --size) {
1463 upd_evacuee(src,(StgClosure *)dest);
1465 // We store the size of the just evacuated object in the LDV word so that
1466 // the profiler can guess the position of the next object later.
1467 SET_EVACUAEE_FOR_LDV(src, size_org);
1469 return (StgClosure *)dest;
1472 /* Special version of copy() for when we only want to copy the info
1473 * pointer of an object, but reserve some padding after it. This is
1474 * used to optimise evacuation of BLACKHOLEs.
1479 copyPart(StgClosure *src, nat size_to_reserve, nat size_to_copy, step *stp)
1484 nat size_to_copy_org = size_to_copy;
1487 TICK_GC_WORDS_COPIED(size_to_copy);
1488 if (stp->gen_no < evac_gen) {
1489 #ifdef NO_EAGER_PROMOTION
1490 failed_to_evac = rtsTrue;
1492 stp = &generations[evac_gen].steps[0];
1496 if (stp->hp + size_to_reserve >= stp->hpLim) {
1497 gc_alloc_block(stp);
1500 for(to = stp->hp, from = (P_)src; size_to_copy>0; --size_to_copy) {
1505 stp->hp += size_to_reserve;
1506 upd_evacuee(src,(StgClosure *)dest);
1508 // We store the size of the just evacuated object in the LDV word so that
1509 // the profiler can guess the position of the next object later.
1510 // size_to_copy_org is wrong because the closure already occupies size_to_reserve
1512 SET_EVACUAEE_FOR_LDV(src, size_to_reserve);
1514 if (size_to_reserve - size_to_copy_org > 0)
1515 FILL_SLOP(stp->hp - 1, (int)(size_to_reserve - size_to_copy_org));
1517 return (StgClosure *)dest;
1521 /* -----------------------------------------------------------------------------
1522 Evacuate a large object
1524 This just consists of removing the object from the (doubly-linked)
1525 step->large_objects list, and linking it on to the (singly-linked)
1526 step->new_large_objects list, from where it will be scavenged later.
1528 Convention: bd->flags has BF_EVACUATED set for a large object
1529 that has been evacuated, or unset otherwise.
1530 -------------------------------------------------------------------------- */
1534 evacuate_large(StgPtr p)
1536 bdescr *bd = Bdescr(p);
1539 // object must be at the beginning of the block (or be a ByteArray)
1540 ASSERT(get_itbl((StgClosure *)p)->type == ARR_WORDS ||
1541 (((W_)p & BLOCK_MASK) == 0));
1543 // already evacuated?
1544 if (bd->flags & BF_EVACUATED) {
1545 /* Don't forget to set the failed_to_evac flag if we didn't get
1546 * the desired destination (see comments in evacuate()).
1548 if (bd->gen_no < evac_gen) {
1549 failed_to_evac = rtsTrue;
1550 TICK_GC_FAILED_PROMOTION();
1556 // remove from large_object list
1558 bd->u.back->link = bd->link;
1559 } else { // first object in the list
1560 stp->large_objects = bd->link;
1563 bd->link->u.back = bd->u.back;
1566 /* link it on to the evacuated large object list of the destination step
1569 if (stp->gen_no < evac_gen) {
1570 #ifdef NO_EAGER_PROMOTION
1571 failed_to_evac = rtsTrue;
1573 stp = &generations[evac_gen].steps[0];
1578 bd->gen_no = stp->gen_no;
1579 bd->link = stp->new_large_objects;
1580 stp->new_large_objects = bd;
1581 bd->flags |= BF_EVACUATED;
1584 /* -----------------------------------------------------------------------------
1587 This is called (eventually) for every live object in the system.
1589 The caller to evacuate specifies a desired generation in the
1590 evac_gen global variable. The following conditions apply to
1591 evacuating an object which resides in generation M when we're
1592 collecting up to generation N
1596 else evac to step->to
1598 if M < evac_gen evac to evac_gen, step 0
1600 if the object is already evacuated, then we check which generation
1603 if M >= evac_gen do nothing
1604 if M < evac_gen set failed_to_evac flag to indicate that we
1605 didn't manage to evacuate this object into evac_gen.
1610 evacuate() is the single most important function performance-wise
1611 in the GC. Various things have been tried to speed it up, but as
1612 far as I can tell the code generated by gcc 3.2 with -O2 is about
1613 as good as it's going to get. We pass the argument to evacuate()
1614 in a register using the 'regparm' attribute (see the prototype for
1615 evacuate() near the top of this file).
1617 Changing evacuate() to take an (StgClosure **) rather than
1618 returning the new pointer seems attractive, because we can avoid
1619 writing back the pointer when it hasn't changed (eg. for a static
1620 object, or an object in a generation > N). However, I tried it and
1621 it doesn't help. One reason is that the (StgClosure **) pointer
1622 gets spilled to the stack inside evacuate(), resulting in far more
1623 extra reads/writes than we save.
1624 -------------------------------------------------------------------------- */
1626 REGPARM1 static StgClosure *
1627 evacuate(StgClosure *q)
1632 const StgInfoTable *info;
1635 if (HEAP_ALLOCED(q)) {
1638 if (bd->gen_no > N) {
1639 /* Can't evacuate this object, because it's in a generation
1640 * older than the ones we're collecting. Let's hope that it's
1641 * in evac_gen or older, or we will have to arrange to track
1642 * this pointer using the mutable list.
1644 if (bd->gen_no < evac_gen) {
1646 failed_to_evac = rtsTrue;
1647 TICK_GC_FAILED_PROMOTION();
1652 /* evacuate large objects by re-linking them onto a different list.
1654 if (bd->flags & BF_LARGE) {
1656 if (info->type == TSO &&
1657 ((StgTSO *)q)->what_next == ThreadRelocated) {
1658 q = (StgClosure *)((StgTSO *)q)->link;
1661 evacuate_large((P_)q);
1665 /* If the object is in a step that we're compacting, then we
1666 * need to use an alternative evacuate procedure.
1668 if (bd->flags & BF_COMPACTED) {
1669 if (!is_marked((P_)q,bd)) {
1671 if (mark_stack_full()) {
1672 mark_stack_overflowed = rtsTrue;
1675 push_mark_stack((P_)q);
1683 else stp = NULL; // make sure copy() will crash if HEAP_ALLOCED is wrong
1686 // make sure the info pointer is into text space
1687 ASSERT(LOOKS_LIKE_CLOSURE_PTR(q));
1690 switch (info -> type) {
1694 return copy(q,sizeW_fromITBL(info),stp);
1698 StgWord w = (StgWord)q->payload[0];
1699 if (q->header.info == Czh_con_info &&
1700 // unsigned, so always true: (StgChar)w >= MIN_CHARLIKE &&
1701 (StgChar)w <= MAX_CHARLIKE) {
1702 return (StgClosure *)CHARLIKE_CLOSURE((StgChar)w);
1704 if (q->header.info == Izh_con_info &&
1705 (StgInt)w >= MIN_INTLIKE && (StgInt)w <= MAX_INTLIKE) {
1706 return (StgClosure *)INTLIKE_CLOSURE((StgInt)w);
1708 // else, fall through ...
1716 return copy(q,sizeofW(StgHeader)+1,stp);
1721 #ifdef NO_PROMOTE_THUNKS
1722 if (bd->gen_no == 0 &&
1723 bd->step->no != 0 &&
1724 bd->step->no == generations[bd->gen_no].n_steps-1) {
1728 return copy(q,sizeofW(StgHeader)+2,stp);
1736 return copy(q,sizeofW(StgHeader)+2,stp);
1742 case IND_OLDGEN_PERM:
1746 return copy(q,sizeW_fromITBL(info),stp);
1749 return copy(q,bco_sizeW((StgBCO *)q),stp);
1752 case SE_CAF_BLACKHOLE:
1755 return copyPart(q,BLACKHOLE_sizeW(),sizeofW(StgHeader),stp);
1758 to = copy(q,BLACKHOLE_sizeW(),stp);
1761 case THUNK_SELECTOR:
1765 if (thunk_selector_depth > MAX_THUNK_SELECTOR_DEPTH) {
1766 return copy(q,THUNK_SELECTOR_sizeW(),stp);
1769 p = eval_thunk_selector(info->layout.selector_offset,
1773 return copy(q,THUNK_SELECTOR_sizeW(),stp);
1775 // q is still BLACKHOLE'd.
1776 thunk_selector_depth++;
1778 thunk_selector_depth--;
1781 // We store the size of the just evacuated object in the
1782 // LDV word so that the profiler can guess the position of
1783 // the next object later.
1784 SET_EVACUAEE_FOR_LDV(q, THUNK_SELECTOR_sizeW());
1792 // follow chains of indirections, don't evacuate them
1793 q = ((StgInd*)q)->indirectee;
1797 if (info->srt_bitmap != 0 && major_gc &&
1798 THUNK_STATIC_LINK((StgClosure *)q) == NULL) {
1799 THUNK_STATIC_LINK((StgClosure *)q) = static_objects;
1800 static_objects = (StgClosure *)q;
1805 if (info->srt_bitmap != 0 && major_gc &&
1806 FUN_STATIC_LINK((StgClosure *)q) == NULL) {
1807 FUN_STATIC_LINK((StgClosure *)q) = static_objects;
1808 static_objects = (StgClosure *)q;
1813 /* If q->saved_info != NULL, then it's a revertible CAF - it'll be
1814 * on the CAF list, so don't do anything with it here (we'll
1815 * scavenge it later).
1818 && ((StgIndStatic *)q)->saved_info == NULL
1819 && IND_STATIC_LINK((StgClosure *)q) == NULL) {
1820 IND_STATIC_LINK((StgClosure *)q) = static_objects;
1821 static_objects = (StgClosure *)q;
1826 if (major_gc && STATIC_LINK(info,(StgClosure *)q) == NULL) {
1827 STATIC_LINK(info,(StgClosure *)q) = static_objects;
1828 static_objects = (StgClosure *)q;
1832 case CONSTR_INTLIKE:
1833 case CONSTR_CHARLIKE:
1834 case CONSTR_NOCAF_STATIC:
1835 /* no need to put these on the static linked list, they don't need
1849 case CATCH_STM_FRAME:
1850 case CATCH_RETRY_FRAME:
1851 case ATOMICALLY_FRAME:
1852 // shouldn't see these
1853 barf("evacuate: stack frame at %p\n", q);
1857 return copy(q,pap_sizeW((StgPAP*)q),stp);
1860 return copy(q,ap_stack_sizeW((StgAP_STACK*)q),stp);
1863 /* Already evacuated, just return the forwarding address.
1864 * HOWEVER: if the requested destination generation (evac_gen) is
1865 * older than the actual generation (because the object was
1866 * already evacuated to a younger generation) then we have to
1867 * set the failed_to_evac flag to indicate that we couldn't
1868 * manage to promote the object to the desired generation.
1870 if (evac_gen > 0) { // optimisation
1871 StgClosure *p = ((StgEvacuated*)q)->evacuee;
1872 if (HEAP_ALLOCED(p) && Bdescr((P_)p)->gen_no < evac_gen) {
1873 failed_to_evac = rtsTrue;
1874 TICK_GC_FAILED_PROMOTION();
1877 return ((StgEvacuated*)q)->evacuee;
1880 // just copy the block
1881 return copy(q,arr_words_sizeW((StgArrWords *)q),stp);
1884 case MUT_ARR_PTRS_FROZEN:
1885 case MUT_ARR_PTRS_FROZEN0:
1886 // just copy the block
1887 return copy(q,mut_arr_ptrs_sizeW((StgMutArrPtrs *)q),stp);
1891 StgTSO *tso = (StgTSO *)q;
1893 /* Deal with redirected TSOs (a TSO that's had its stack enlarged).
1895 if (tso->what_next == ThreadRelocated) {
1896 q = (StgClosure *)tso->link;
1900 /* To evacuate a small TSO, we need to relocate the update frame
1907 new_tso = (StgTSO *)copyPart((StgClosure *)tso,
1909 sizeofW(StgTSO), stp);
1910 move_TSO(tso, new_tso);
1911 for (p = tso->sp, q = new_tso->sp;
1912 p < tso->stack+tso->stack_size;) {
1916 return (StgClosure *)new_tso;
1921 case RBH: // cf. BLACKHOLE_BQ
1923 //StgInfoTable *rip = get_closure_info(q, &size, &ptrs, &nonptrs, &vhs, str);
1924 to = copy(q,BLACKHOLE_sizeW(),stp);
1925 //ToDo: derive size etc from reverted IP
1926 //to = copy(q,size,stp);
1928 debugBelch("@@ evacuate: RBH %p (%s) to %p (%s)",
1929 q, info_type(q), to, info_type(to)));
1934 ASSERT(sizeofW(StgBlockedFetch) >= MIN_NONUPD_SIZE);
1935 to = copy(q,sizeofW(StgBlockedFetch),stp);
1937 debugBelch("@@ evacuate: %p (%s) to %p (%s)",
1938 q, info_type(q), to, info_type(to)));
1945 ASSERT(sizeofW(StgBlockedFetch) >= MIN_UPD_SIZE);
1946 to = copy(q,sizeofW(StgFetchMe),stp);
1948 debugBelch("@@ evacuate: %p (%s) to %p (%s)",
1949 q, info_type(q), to, info_type(to)));
1953 ASSERT(sizeofW(StgBlockedFetch) >= MIN_UPD_SIZE);
1954 to = copy(q,sizeofW(StgFetchMeBlockingQueue),stp);
1956 debugBelch("@@ evacuate: %p (%s) to %p (%s)",
1957 q, info_type(q), to, info_type(to)));
1962 return copy(q,sizeofW(StgTRecHeader),stp);
1964 case TVAR_WAIT_QUEUE:
1965 return copy(q,sizeofW(StgTVarWaitQueue),stp);
1968 return copy(q,sizeofW(StgTVar),stp);
1971 return copy(q,sizeofW(StgTRecChunk),stp);
1974 barf("evacuate: strange closure type %d", (int)(info->type));
1980 /* -----------------------------------------------------------------------------
1981 Evaluate a THUNK_SELECTOR if possible.
1983 returns: NULL if we couldn't evaluate this THUNK_SELECTOR, or
1984 a closure pointer if we evaluated it and this is the result. Note
1985 that "evaluating" the THUNK_SELECTOR doesn't necessarily mean
1986 reducing it to HNF, just that we have eliminated the selection.
1987 The result might be another thunk, or even another THUNK_SELECTOR.
1989 If the return value is non-NULL, the original selector thunk has
1990 been BLACKHOLE'd, and should be updated with an indirection or a
1991 forwarding pointer. If the return value is NULL, then the selector
1993 -------------------------------------------------------------------------- */
1995 static inline rtsBool
1996 is_to_space ( StgClosure *p )
2000 bd = Bdescr((StgPtr)p);
2001 if (HEAP_ALLOCED(p) &&
2002 ((bd->flags & BF_EVACUATED)
2003 || ((bd->flags & BF_COMPACTED) &&
2004 is_marked((P_)p,bd)))) {
2012 eval_thunk_selector( nat field, StgSelector * p )
2015 const StgInfoTable *info_ptr;
2016 StgClosure *selectee;
2018 selectee = p->selectee;
2020 // Save the real info pointer (NOTE: not the same as get_itbl()).
2021 info_ptr = p->header.info;
2023 // If the THUNK_SELECTOR is in a generation that we are not
2024 // collecting, then bail out early. We won't be able to save any
2025 // space in any case, and updating with an indirection is trickier
2027 if (Bdescr((StgPtr)p)->gen_no > N) {
2031 // BLACKHOLE the selector thunk, since it is now under evaluation.
2032 // This is important to stop us going into an infinite loop if
2033 // this selector thunk eventually refers to itself.
2034 SET_INFO(p,&stg_BLACKHOLE_info);
2038 // We don't want to end up in to-space, because this causes
2039 // problems when the GC later tries to evacuate the result of
2040 // eval_thunk_selector(). There are various ways this could
2043 // 1. following an IND_STATIC
2045 // 2. when the old generation is compacted, the mark phase updates
2046 // from-space pointers to be to-space pointers, and we can't
2047 // reliably tell which we're following (eg. from an IND_STATIC).
2049 // 3. compacting GC again: if we're looking at a constructor in
2050 // the compacted generation, it might point directly to objects
2051 // in to-space. We must bale out here, otherwise doing the selection
2052 // will result in a to-space pointer being returned.
2054 // (1) is dealt with using a BF_EVACUATED test on the
2055 // selectee. (2) and (3): we can tell if we're looking at an
2056 // object in the compacted generation that might point to
2057 // to-space objects by testing that (a) it is BF_COMPACTED, (b)
2058 // the compacted generation is being collected, and (c) the
2059 // object is marked. Only a marked object may have pointers that
2060 // point to to-space objects, because that happens when
2063 // The to-space test is now embodied in the in_to_space() inline
2064 // function, as it is re-used below.
2066 if (is_to_space(selectee)) {
2070 info = get_itbl(selectee);
2071 switch (info->type) {
2079 case CONSTR_NOCAF_STATIC:
2080 // check that the size is in range
2081 ASSERT(field < (StgWord32)(info->layout.payload.ptrs +
2082 info->layout.payload.nptrs));
2084 // Select the right field from the constructor, and check
2085 // that the result isn't in to-space. It might be in
2086 // to-space if, for example, this constructor contains
2087 // pointers to younger-gen objects (and is on the mut-once
2092 q = selectee->payload[field];
2093 if (is_to_space(q)) {
2103 case IND_OLDGEN_PERM:
2105 selectee = ((StgInd *)selectee)->indirectee;
2109 // We don't follow pointers into to-space; the constructor
2110 // has already been evacuated, so we won't save any space
2111 // leaks by evaluating this selector thunk anyhow.
2114 case THUNK_SELECTOR:
2118 // check that we don't recurse too much, re-using the
2119 // depth bound also used in evacuate().
2120 if (thunk_selector_depth >= MAX_THUNK_SELECTOR_DEPTH) {
2123 thunk_selector_depth++;
2125 val = eval_thunk_selector(info->layout.selector_offset,
2126 (StgSelector *)selectee);
2128 thunk_selector_depth--;
2133 // We evaluated this selector thunk, so update it with
2134 // an indirection. NOTE: we don't use UPD_IND here,
2135 // because we are guaranteed that p is in a generation
2136 // that we are collecting, and we never want to put the
2137 // indirection on a mutable list.
2139 // For the purposes of LDV profiling, we have destroyed
2140 // the original selector thunk.
2141 SET_INFO(p, info_ptr);
2142 LDV_RECORD_DEAD_FILL_SLOP_DYNAMIC(selectee);
2144 ((StgInd *)selectee)->indirectee = val;
2145 SET_INFO(selectee,&stg_IND_info);
2147 // For the purposes of LDV profiling, we have created an
2149 LDV_RECORD_CREATE(selectee);
2166 case SE_CAF_BLACKHOLE:
2179 // not evaluated yet
2183 barf("eval_thunk_selector: strange selectee %d",
2188 // We didn't manage to evaluate this thunk; restore the old info pointer
2189 SET_INFO(p, info_ptr);
2193 /* -----------------------------------------------------------------------------
2194 move_TSO is called to update the TSO structure after it has been
2195 moved from one place to another.
2196 -------------------------------------------------------------------------- */
2199 move_TSO (StgTSO *src, StgTSO *dest)
2203 // relocate the stack pointer...
2204 diff = (StgPtr)dest - (StgPtr)src; // In *words*
2205 dest->sp = (StgPtr)dest->sp + diff;
2208 /* Similar to scavenge_large_bitmap(), but we don't write back the
2209 * pointers we get back from evacuate().
2212 scavenge_large_srt_bitmap( StgLargeSRT *large_srt )
2219 bitmap = large_srt->l.bitmap[b];
2220 size = (nat)large_srt->l.size;
2221 p = (StgClosure **)large_srt->srt;
2222 for (i = 0; i < size; ) {
2223 if ((bitmap & 1) != 0) {
2228 if (i % BITS_IN(W_) == 0) {
2230 bitmap = large_srt->l.bitmap[b];
2232 bitmap = bitmap >> 1;
2237 /* evacuate the SRT. If srt_bitmap is zero, then there isn't an
2238 * srt field in the info table. That's ok, because we'll
2239 * never dereference it.
2242 scavenge_srt (StgClosure **srt, nat srt_bitmap)
2247 bitmap = srt_bitmap;
2250 if (bitmap == (StgHalfWord)(-1)) {
2251 scavenge_large_srt_bitmap( (StgLargeSRT *)srt );
2255 while (bitmap != 0) {
2256 if ((bitmap & 1) != 0) {
2257 #ifdef ENABLE_WIN32_DLL_SUPPORT
2258 // Special-case to handle references to closures hiding out in DLLs, since
2259 // double indirections required to get at those. The code generator knows
2260 // which is which when generating the SRT, so it stores the (indirect)
2261 // reference to the DLL closure in the table by first adding one to it.
2262 // We check for this here, and undo the addition before evacuating it.
2264 // If the SRT entry hasn't got bit 0 set, the SRT entry points to a
2265 // closure that's fixed at link-time, and no extra magic is required.
2266 if ( (unsigned long)(*srt) & 0x1 ) {
2267 evacuate(*stgCast(StgClosure**,(stgCast(unsigned long, *srt) & ~0x1)));
2276 bitmap = bitmap >> 1;
2282 scavenge_thunk_srt(const StgInfoTable *info)
2284 StgThunkInfoTable *thunk_info;
2286 thunk_info = itbl_to_thunk_itbl(info);
2287 scavenge_srt((StgClosure **)GET_SRT(thunk_info), thunk_info->i.srt_bitmap);
2291 scavenge_fun_srt(const StgInfoTable *info)
2293 StgFunInfoTable *fun_info;
2295 fun_info = itbl_to_fun_itbl(info);
2296 scavenge_srt((StgClosure **)GET_FUN_SRT(fun_info), fun_info->i.srt_bitmap);
2300 scavenge_ret_srt(const StgInfoTable *info)
2302 StgRetInfoTable *ret_info;
2304 ret_info = itbl_to_ret_itbl(info);
2305 scavenge_srt((StgClosure **)GET_SRT(ret_info), ret_info->i.srt_bitmap);
2308 /* -----------------------------------------------------------------------------
2310 -------------------------------------------------------------------------- */
2313 scavengeTSO (StgTSO *tso)
2315 // chase the link field for any TSOs on the same queue
2316 tso->link = (StgTSO *)evacuate((StgClosure *)tso->link);
2317 if ( tso->why_blocked == BlockedOnMVar
2318 || tso->why_blocked == BlockedOnBlackHole
2319 || tso->why_blocked == BlockedOnException
2321 || tso->why_blocked == BlockedOnGA
2322 || tso->why_blocked == BlockedOnGA_NoSend
2325 tso->block_info.closure = evacuate(tso->block_info.closure);
2327 if ( tso->blocked_exceptions != NULL ) {
2328 tso->blocked_exceptions =
2329 (StgTSO *)evacuate((StgClosure *)tso->blocked_exceptions);
2332 // scavange current transaction record
2333 tso->trec = (StgTRecHeader *)evacuate((StgClosure *)tso->trec);
2335 // scavenge this thread's stack
2336 scavenge_stack(tso->sp, &(tso->stack[tso->stack_size]));
2339 /* -----------------------------------------------------------------------------
2340 Blocks of function args occur on the stack (at the top) and
2342 -------------------------------------------------------------------------- */
2344 STATIC_INLINE StgPtr
2345 scavenge_arg_block (StgFunInfoTable *fun_info, StgClosure **args)
2352 switch (fun_info->f.fun_type) {
2354 bitmap = BITMAP_BITS(fun_info->f.bitmap);
2355 size = BITMAP_SIZE(fun_info->f.bitmap);
2358 size = GET_FUN_LARGE_BITMAP(fun_info)->size;
2359 scavenge_large_bitmap(p, GET_FUN_LARGE_BITMAP(fun_info), size);
2363 bitmap = BITMAP_BITS(stg_arg_bitmaps[fun_info->f.fun_type]);
2364 size = BITMAP_SIZE(stg_arg_bitmaps[fun_info->f.fun_type]);
2367 if ((bitmap & 1) == 0) {
2368 *p = (StgWord)(StgPtr)evacuate((StgClosure *)*p);
2371 bitmap = bitmap >> 1;
2379 STATIC_INLINE StgPtr
2380 scavenge_PAP (StgPAP *pap)
2383 StgWord bitmap, size;
2384 StgFunInfoTable *fun_info;
2386 pap->fun = evacuate(pap->fun);
2387 fun_info = get_fun_itbl(pap->fun);
2388 ASSERT(fun_info->i.type != PAP);
2390 p = (StgPtr)pap->payload;
2393 switch (fun_info->f.fun_type) {
2395 bitmap = BITMAP_BITS(fun_info->f.bitmap);
2398 scavenge_large_bitmap(p, GET_FUN_LARGE_BITMAP(fun_info), size);
2402 scavenge_large_bitmap((StgPtr)pap->payload, BCO_BITMAP(pap->fun), size);
2406 bitmap = BITMAP_BITS(stg_arg_bitmaps[fun_info->f.fun_type]);
2410 if ((bitmap & 1) == 0) {
2411 *p = (StgWord)(StgPtr)evacuate((StgClosure *)*p);
2414 bitmap = bitmap >> 1;
2422 /* -----------------------------------------------------------------------------
2423 Scavenge a given step until there are no more objects in this step
2426 evac_gen is set by the caller to be either zero (for a step in a
2427 generation < N) or G where G is the generation of the step being
2430 We sometimes temporarily change evac_gen back to zero if we're
2431 scavenging a mutable object where early promotion isn't such a good
2433 -------------------------------------------------------------------------- */
2441 nat saved_evac_gen = evac_gen;
2446 failed_to_evac = rtsFalse;
2448 /* scavenge phase - standard breadth-first scavenging of the
2452 while (bd != stp->hp_bd || p < stp->hp) {
2454 // If we're at the end of this block, move on to the next block
2455 if (bd != stp->hp_bd && p == bd->free) {
2461 ASSERT(LOOKS_LIKE_CLOSURE_PTR(p));
2462 info = get_itbl((StgClosure *)p);
2464 ASSERT(thunk_selector_depth == 0);
2467 switch (info->type) {
2471 StgMVar *mvar = ((StgMVar *)p);
2473 mvar->head = (StgTSO *)evacuate((StgClosure *)mvar->head);
2474 mvar->tail = (StgTSO *)evacuate((StgClosure *)mvar->tail);
2475 mvar->value = evacuate((StgClosure *)mvar->value);
2476 evac_gen = saved_evac_gen;
2477 failed_to_evac = rtsTrue; // mutable.
2478 p += sizeofW(StgMVar);
2483 scavenge_fun_srt(info);
2484 ((StgClosure *)p)->payload[1] = evacuate(((StgClosure *)p)->payload[1]);
2485 ((StgClosure *)p)->payload[0] = evacuate(((StgClosure *)p)->payload[0]);
2486 p += sizeofW(StgHeader) + 2;
2490 scavenge_thunk_srt(info);
2492 ((StgClosure *)p)->payload[1] = evacuate(((StgClosure *)p)->payload[1]);
2493 ((StgClosure *)p)->payload[0] = evacuate(((StgClosure *)p)->payload[0]);
2494 p += sizeofW(StgHeader) + 2;
2498 scavenge_thunk_srt(info);
2499 ((StgClosure *)p)->payload[0] = evacuate(((StgClosure *)p)->payload[0]);
2500 p += sizeofW(StgHeader) + 1;
2504 scavenge_fun_srt(info);
2506 ((StgClosure *)p)->payload[0] = evacuate(((StgClosure *)p)->payload[0]);
2507 p += sizeofW(StgHeader) + 1;
2511 scavenge_thunk_srt(info);
2512 p += sizeofW(StgHeader) + 1;
2516 scavenge_fun_srt(info);
2518 p += sizeofW(StgHeader) + 1;
2522 scavenge_thunk_srt(info);
2523 p += sizeofW(StgHeader) + 2;
2527 scavenge_fun_srt(info);
2529 p += sizeofW(StgHeader) + 2;
2533 scavenge_thunk_srt(info);
2534 ((StgClosure *)p)->payload[0] = evacuate(((StgClosure *)p)->payload[0]);
2535 p += sizeofW(StgHeader) + 2;
2539 scavenge_fun_srt(info);
2541 ((StgClosure *)p)->payload[0] = evacuate(((StgClosure *)p)->payload[0]);
2542 p += sizeofW(StgHeader) + 2;
2546 scavenge_fun_srt(info);
2550 scavenge_thunk_srt(info);
2561 end = (P_)((StgClosure *)p)->payload + info->layout.payload.ptrs;
2562 for (p = (P_)((StgClosure *)p)->payload; p < end; p++) {
2563 *p = (StgWord)(StgPtr)evacuate((StgClosure *)*p);
2565 p += info->layout.payload.nptrs;
2570 StgBCO *bco = (StgBCO *)p;
2571 bco->instrs = (StgArrWords *)evacuate((StgClosure *)bco->instrs);
2572 bco->literals = (StgArrWords *)evacuate((StgClosure *)bco->literals);
2573 bco->ptrs = (StgMutArrPtrs *)evacuate((StgClosure *)bco->ptrs);
2574 bco->itbls = (StgArrWords *)evacuate((StgClosure *)bco->itbls);
2575 p += bco_sizeW(bco);
2580 if (stp->gen->no != 0) {
2583 // No need to call LDV_recordDead_FILL_SLOP_DYNAMIC() because an
2584 // IND_OLDGEN_PERM closure is larger than an IND_PERM closure.
2585 LDV_recordDead((StgClosure *)p, sizeofW(StgInd));
2588 // Todo: maybe use SET_HDR() and remove LDV_RECORD_CREATE()?
2590 SET_INFO(((StgClosure *)p), &stg_IND_OLDGEN_PERM_info);
2592 // We pretend that p has just been created.
2593 LDV_RECORD_CREATE((StgClosure *)p);
2596 case IND_OLDGEN_PERM:
2597 ((StgInd *)p)->indirectee = evacuate(((StgInd *)p)->indirectee);
2598 p += sizeofW(StgInd);
2603 ((StgMutVar *)p)->var = evacuate(((StgMutVar *)p)->var);
2604 evac_gen = saved_evac_gen;
2605 failed_to_evac = rtsTrue; // mutable anyhow
2606 p += sizeofW(StgMutVar);
2610 case SE_CAF_BLACKHOLE:
2613 p += BLACKHOLE_sizeW();
2618 StgBlockingQueue *bh = (StgBlockingQueue *)p;
2619 bh->blocking_queue =
2620 (StgTSO *)evacuate((StgClosure *)bh->blocking_queue);
2621 failed_to_evac = rtsTrue;
2622 p += BLACKHOLE_sizeW();
2626 case THUNK_SELECTOR:
2628 StgSelector *s = (StgSelector *)p;
2629 s->selectee = evacuate(s->selectee);
2630 p += THUNK_SELECTOR_sizeW();
2634 // A chunk of stack saved in a heap object
2637 StgAP_STACK *ap = (StgAP_STACK *)p;
2639 ap->fun = evacuate(ap->fun);
2640 scavenge_stack((StgPtr)ap->payload, (StgPtr)ap->payload + ap->size);
2641 p = (StgPtr)ap->payload + ap->size;
2647 p = scavenge_PAP((StgPAP *)p);
2651 // nothing to follow
2652 p += arr_words_sizeW((StgArrWords *)p);
2656 // follow everything
2660 evac_gen = 0; // repeatedly mutable
2661 next = p + mut_arr_ptrs_sizeW((StgMutArrPtrs*)p);
2662 for (p = (P_)((StgMutArrPtrs *)p)->payload; p < next; p++) {
2663 *p = (StgWord)(StgPtr)evacuate((StgClosure *)*p);
2665 evac_gen = saved_evac_gen;
2666 failed_to_evac = rtsTrue; // mutable anyhow.
2670 case MUT_ARR_PTRS_FROZEN:
2671 case MUT_ARR_PTRS_FROZEN0:
2672 // follow everything
2676 next = p + mut_arr_ptrs_sizeW((StgMutArrPtrs*)p);
2677 for (p = (P_)((StgMutArrPtrs *)p)->payload; p < next; p++) {
2678 *p = (StgWord)(StgPtr)evacuate((StgClosure *)*p);
2680 // it's tempting to recordMutable() if failed_to_evac is
2681 // false, but that breaks some assumptions (eg. every
2682 // closure on the mutable list is supposed to have the MUT
2683 // flag set, and MUT_ARR_PTRS_FROZEN doesn't).
2689 StgTSO *tso = (StgTSO *)p;
2692 evac_gen = saved_evac_gen;
2693 failed_to_evac = rtsTrue; // mutable anyhow.
2694 p += tso_sizeW(tso);
2699 case RBH: // cf. BLACKHOLE_BQ
2702 nat size, ptrs, nonptrs, vhs;
2704 StgInfoTable *rip = get_closure_info(p, &size, &ptrs, &nonptrs, &vhs, str);
2706 StgRBH *rbh = (StgRBH *)p;
2707 (StgClosure *)rbh->blocking_queue =
2708 evacuate((StgClosure *)rbh->blocking_queue);
2709 failed_to_evac = rtsTrue; // mutable anyhow.
2711 debugBelch("@@ scavenge: RBH %p (%s) (new blocking_queue link=%p)",
2712 p, info_type(p), (StgClosure *)rbh->blocking_queue));
2713 // ToDo: use size of reverted closure here!
2714 p += BLACKHOLE_sizeW();
2720 StgBlockedFetch *bf = (StgBlockedFetch *)p;
2721 // follow the pointer to the node which is being demanded
2722 (StgClosure *)bf->node =
2723 evacuate((StgClosure *)bf->node);
2724 // follow the link to the rest of the blocking queue
2725 (StgClosure *)bf->link =
2726 evacuate((StgClosure *)bf->link);
2728 debugBelch("@@ scavenge: %p (%s); node is now %p; exciting, isn't it",
2729 bf, info_type((StgClosure *)bf),
2730 bf->node, info_type(bf->node)));
2731 p += sizeofW(StgBlockedFetch);
2739 p += sizeofW(StgFetchMe);
2740 break; // nothing to do in this case
2742 case FETCH_ME_BQ: // cf. BLACKHOLE_BQ
2744 StgFetchMeBlockingQueue *fmbq = (StgFetchMeBlockingQueue *)p;
2745 (StgClosure *)fmbq->blocking_queue =
2746 evacuate((StgClosure *)fmbq->blocking_queue);
2748 debugBelch("@@ scavenge: %p (%s) exciting, isn't it",
2749 p, info_type((StgClosure *)p)));
2750 p += sizeofW(StgFetchMeBlockingQueue);
2755 case TVAR_WAIT_QUEUE:
2757 StgTVarWaitQueue *wq = ((StgTVarWaitQueue *) p);
2759 wq->waiting_tso = (StgTSO *)evacuate((StgClosure*)wq->waiting_tso);
2760 wq->next_queue_entry = (StgTVarWaitQueue *)evacuate((StgClosure*)wq->next_queue_entry);
2761 wq->prev_queue_entry = (StgTVarWaitQueue *)evacuate((StgClosure*)wq->prev_queue_entry);
2762 evac_gen = saved_evac_gen;
2763 failed_to_evac = rtsTrue; // mutable
2764 p += sizeofW(StgTVarWaitQueue);
2770 StgTVar *tvar = ((StgTVar *) p);
2772 tvar->current_value = evacuate((StgClosure*)tvar->current_value);
2773 tvar->first_wait_queue_entry = (StgTVarWaitQueue *)evacuate((StgClosure*)tvar->first_wait_queue_entry);
2774 evac_gen = saved_evac_gen;
2775 failed_to_evac = rtsTrue; // mutable
2776 p += sizeofW(StgTVar);
2782 StgTRecHeader *trec = ((StgTRecHeader *) p);
2784 trec->enclosing_trec = (StgTRecHeader *)evacuate((StgClosure*)trec->enclosing_trec);
2785 trec->current_chunk = (StgTRecChunk *)evacuate((StgClosure*)trec->current_chunk);
2786 evac_gen = saved_evac_gen;
2787 failed_to_evac = rtsTrue; // mutable
2788 p += sizeofW(StgTRecHeader);
2795 StgTRecChunk *tc = ((StgTRecChunk *) p);
2796 TRecEntry *e = &(tc -> entries[0]);
2798 tc->prev_chunk = (StgTRecChunk *)evacuate((StgClosure*)tc->prev_chunk);
2799 for (i = 0; i < tc -> next_entry_idx; i ++, e++ ) {
2800 e->tvar = (StgTVar *)evacuate((StgClosure*)e->tvar);
2801 e->expected_value = evacuate((StgClosure*)e->expected_value);
2802 e->new_value = evacuate((StgClosure*)e->new_value);
2804 evac_gen = saved_evac_gen;
2805 failed_to_evac = rtsTrue; // mutable
2806 p += sizeofW(StgTRecChunk);
2811 barf("scavenge: unimplemented/strange closure type %d @ %p",
2816 * We need to record the current object on the mutable list if
2817 * (a) It is actually mutable, or
2818 * (b) It contains pointers to a younger generation.
2819 * Case (b) arises if we didn't manage to promote everything that
2820 * the current object points to into the current generation.
2822 if (failed_to_evac) {
2823 failed_to_evac = rtsFalse;
2824 recordMutableGen((StgClosure *)q, stp->gen);
2832 /* -----------------------------------------------------------------------------
2833 Scavenge everything on the mark stack.
2835 This is slightly different from scavenge():
2836 - we don't walk linearly through the objects, so the scavenger
2837 doesn't need to advance the pointer on to the next object.
2838 -------------------------------------------------------------------------- */
2841 scavenge_mark_stack(void)
2847 evac_gen = oldest_gen->no;
2848 saved_evac_gen = evac_gen;
2851 while (!mark_stack_empty()) {
2852 p = pop_mark_stack();
2854 ASSERT(LOOKS_LIKE_CLOSURE_PTR(p));
2855 info = get_itbl((StgClosure *)p);
2858 switch (info->type) {
2862 StgMVar *mvar = ((StgMVar *)p);
2864 mvar->head = (StgTSO *)evacuate((StgClosure *)mvar->head);
2865 mvar->tail = (StgTSO *)evacuate((StgClosure *)mvar->tail);
2866 mvar->value = evacuate((StgClosure *)mvar->value);
2867 evac_gen = saved_evac_gen;
2868 failed_to_evac = rtsTrue; // mutable.
2873 scavenge_fun_srt(info);
2874 ((StgClosure *)p)->payload[1] = evacuate(((StgClosure *)p)->payload[1]);
2875 ((StgClosure *)p)->payload[0] = evacuate(((StgClosure *)p)->payload[0]);
2879 scavenge_thunk_srt(info);
2881 ((StgClosure *)p)->payload[1] = evacuate(((StgClosure *)p)->payload[1]);
2882 ((StgClosure *)p)->payload[0] = evacuate(((StgClosure *)p)->payload[0]);
2887 scavenge_fun_srt(info);
2888 ((StgClosure *)p)->payload[0] = evacuate(((StgClosure *)p)->payload[0]);
2893 scavenge_thunk_srt(info);
2896 ((StgClosure *)p)->payload[0] = evacuate(((StgClosure *)p)->payload[0]);
2901 scavenge_fun_srt(info);
2906 scavenge_thunk_srt(info);
2914 scavenge_fun_srt(info);
2918 scavenge_thunk_srt(info);
2929 end = (P_)((StgClosure *)p)->payload + info->layout.payload.ptrs;
2930 for (p = (P_)((StgClosure *)p)->payload; p < end; p++) {
2931 *p = (StgWord)(StgPtr)evacuate((StgClosure *)*p);
2937 StgBCO *bco = (StgBCO *)p;
2938 bco->instrs = (StgArrWords *)evacuate((StgClosure *)bco->instrs);
2939 bco->literals = (StgArrWords *)evacuate((StgClosure *)bco->literals);
2940 bco->ptrs = (StgMutArrPtrs *)evacuate((StgClosure *)bco->ptrs);
2941 bco->itbls = (StgArrWords *)evacuate((StgClosure *)bco->itbls);
2946 // don't need to do anything here: the only possible case
2947 // is that we're in a 1-space compacting collector, with
2948 // no "old" generation.
2952 case IND_OLDGEN_PERM:
2953 ((StgInd *)p)->indirectee =
2954 evacuate(((StgInd *)p)->indirectee);
2959 ((StgMutVar *)p)->var = evacuate(((StgMutVar *)p)->var);
2960 evac_gen = saved_evac_gen;
2961 failed_to_evac = rtsTrue;
2965 case SE_CAF_BLACKHOLE:
2973 StgBlockingQueue *bh = (StgBlockingQueue *)p;
2974 bh->blocking_queue =
2975 (StgTSO *)evacuate((StgClosure *)bh->blocking_queue);
2976 failed_to_evac = rtsTrue;
2980 case THUNK_SELECTOR:
2982 StgSelector *s = (StgSelector *)p;
2983 s->selectee = evacuate(s->selectee);
2987 // A chunk of stack saved in a heap object
2990 StgAP_STACK *ap = (StgAP_STACK *)p;
2992 ap->fun = evacuate(ap->fun);
2993 scavenge_stack((StgPtr)ap->payload, (StgPtr)ap->payload + ap->size);
2999 scavenge_PAP((StgPAP *)p);
3003 // follow everything
3007 evac_gen = 0; // repeatedly mutable
3008 next = p + mut_arr_ptrs_sizeW((StgMutArrPtrs*)p);
3009 for (p = (P_)((StgMutArrPtrs *)p)->payload; p < next; p++) {
3010 *p = (StgWord)(StgPtr)evacuate((StgClosure *)*p);
3012 evac_gen = saved_evac_gen;
3013 failed_to_evac = rtsTrue; // mutable anyhow.
3017 case MUT_ARR_PTRS_FROZEN:
3018 case MUT_ARR_PTRS_FROZEN0:
3019 // follow everything
3023 next = p + mut_arr_ptrs_sizeW((StgMutArrPtrs*)p);
3024 for (p = (P_)((StgMutArrPtrs *)p)->payload; p < next; p++) {
3025 *p = (StgWord)(StgPtr)evacuate((StgClosure *)*p);
3032 StgTSO *tso = (StgTSO *)p;
3035 evac_gen = saved_evac_gen;
3036 failed_to_evac = rtsTrue;
3041 case RBH: // cf. BLACKHOLE_BQ
3044 nat size, ptrs, nonptrs, vhs;
3046 StgInfoTable *rip = get_closure_info(p, &size, &ptrs, &nonptrs, &vhs, str);
3048 StgRBH *rbh = (StgRBH *)p;
3049 bh->blocking_queue =
3050 (StgTSO *)evacuate((StgClosure *)bh->blocking_queue);
3051 failed_to_evac = rtsTrue; // mutable anyhow.
3053 debugBelch("@@ scavenge: RBH %p (%s) (new blocking_queue link=%p)",
3054 p, info_type(p), (StgClosure *)rbh->blocking_queue));
3060 StgBlockedFetch *bf = (StgBlockedFetch *)p;
3061 // follow the pointer to the node which is being demanded
3062 (StgClosure *)bf->node =
3063 evacuate((StgClosure *)bf->node);
3064 // follow the link to the rest of the blocking queue
3065 (StgClosure *)bf->link =
3066 evacuate((StgClosure *)bf->link);
3068 debugBelch("@@ scavenge: %p (%s); node is now %p; exciting, isn't it",
3069 bf, info_type((StgClosure *)bf),
3070 bf->node, info_type(bf->node)));
3078 break; // nothing to do in this case
3080 case FETCH_ME_BQ: // cf. BLACKHOLE_BQ
3082 StgFetchMeBlockingQueue *fmbq = (StgFetchMeBlockingQueue *)p;
3083 (StgClosure *)fmbq->blocking_queue =
3084 evacuate((StgClosure *)fmbq->blocking_queue);
3086 debugBelch("@@ scavenge: %p (%s) exciting, isn't it",
3087 p, info_type((StgClosure *)p)));
3092 case TVAR_WAIT_QUEUE:
3094 StgTVarWaitQueue *wq = ((StgTVarWaitQueue *) p);
3096 wq->waiting_tso = (StgTSO *)evacuate((StgClosure*)wq->waiting_tso);
3097 wq->next_queue_entry = (StgTVarWaitQueue *)evacuate((StgClosure*)wq->next_queue_entry);
3098 wq->prev_queue_entry = (StgTVarWaitQueue *)evacuate((StgClosure*)wq->prev_queue_entry);
3099 evac_gen = saved_evac_gen;
3100 failed_to_evac = rtsTrue; // mutable
3106 StgTVar *tvar = ((StgTVar *) p);
3108 tvar->current_value = evacuate((StgClosure*)tvar->current_value);
3109 tvar->first_wait_queue_entry = (StgTVarWaitQueue *)evacuate((StgClosure*)tvar->first_wait_queue_entry);
3110 evac_gen = saved_evac_gen;
3111 failed_to_evac = rtsTrue; // mutable
3118 StgTRecChunk *tc = ((StgTRecChunk *) p);
3119 TRecEntry *e = &(tc -> entries[0]);
3121 tc->prev_chunk = (StgTRecChunk *)evacuate((StgClosure*)tc->prev_chunk);
3122 for (i = 0; i < tc -> next_entry_idx; i ++, e++ ) {
3123 e->tvar = (StgTVar *)evacuate((StgClosure*)e->tvar);
3124 e->expected_value = evacuate((StgClosure*)e->expected_value);
3125 e->new_value = evacuate((StgClosure*)e->new_value);
3127 evac_gen = saved_evac_gen;
3128 failed_to_evac = rtsTrue; // mutable
3134 StgTRecHeader *trec = ((StgTRecHeader *) p);
3136 trec->enclosing_trec = (StgTRecHeader *)evacuate((StgClosure*)trec->enclosing_trec);
3137 trec->current_chunk = (StgTRecChunk *)evacuate((StgClosure*)trec->current_chunk);
3138 evac_gen = saved_evac_gen;
3139 failed_to_evac = rtsTrue; // mutable
3144 barf("scavenge_mark_stack: unimplemented/strange closure type %d @ %p",
3148 if (failed_to_evac) {
3149 failed_to_evac = rtsFalse;
3150 recordMutableGen((StgClosure *)q, &generations[evac_gen]);
3153 // mark the next bit to indicate "scavenged"
3154 mark(q+1, Bdescr(q));
3156 } // while (!mark_stack_empty())
3158 // start a new linear scan if the mark stack overflowed at some point
3159 if (mark_stack_overflowed && oldgen_scan_bd == NULL) {
3160 IF_DEBUG(gc, debugBelch("scavenge_mark_stack: starting linear scan"));
3161 mark_stack_overflowed = rtsFalse;
3162 oldgen_scan_bd = oldest_gen->steps[0].blocks;
3163 oldgen_scan = oldgen_scan_bd->start;
3166 if (oldgen_scan_bd) {
3167 // push a new thing on the mark stack
3169 // find a closure that is marked but not scavenged, and start
3171 while (oldgen_scan < oldgen_scan_bd->free
3172 && !is_marked(oldgen_scan,oldgen_scan_bd)) {
3176 if (oldgen_scan < oldgen_scan_bd->free) {
3178 // already scavenged?
3179 if (is_marked(oldgen_scan+1,oldgen_scan_bd)) {
3180 oldgen_scan += sizeofW(StgHeader) + MIN_NONUPD_SIZE;
3183 push_mark_stack(oldgen_scan);
3184 // ToDo: bump the linear scan by the actual size of the object
3185 oldgen_scan += sizeofW(StgHeader) + MIN_NONUPD_SIZE;
3189 oldgen_scan_bd = oldgen_scan_bd->link;
3190 if (oldgen_scan_bd != NULL) {
3191 oldgen_scan = oldgen_scan_bd->start;
3197 /* -----------------------------------------------------------------------------
3198 Scavenge one object.
3200 This is used for objects that are temporarily marked as mutable
3201 because they contain old-to-new generation pointers. Only certain
3202 objects can have this property.
3203 -------------------------------------------------------------------------- */
3206 scavenge_one(StgPtr p)
3208 const StgInfoTable *info;
3209 nat saved_evac_gen = evac_gen;
3212 ASSERT(LOOKS_LIKE_CLOSURE_PTR(p));
3213 info = get_itbl((StgClosure *)p);
3215 switch (info->type) {
3219 StgMVar *mvar = ((StgMVar *)p);
3221 mvar->head = (StgTSO *)evacuate((StgClosure *)mvar->head);
3222 mvar->tail = (StgTSO *)evacuate((StgClosure *)mvar->tail);
3223 mvar->value = evacuate((StgClosure *)mvar->value);
3224 evac_gen = saved_evac_gen;
3225 failed_to_evac = rtsTrue; // mutable.
3230 case FUN_1_0: // hardly worth specialising these guys
3253 end = (StgPtr)((StgClosure *)p)->payload + info->layout.payload.ptrs;
3254 for (q = (StgPtr)((StgClosure *)p)->payload; q < end; q++) {
3255 *q = (StgWord)(StgPtr)evacuate((StgClosure *)*q);
3262 ((StgMutVar *)p)->var = evacuate(((StgMutVar *)p)->var);
3263 evac_gen = saved_evac_gen;
3264 failed_to_evac = rtsTrue; // mutable anyhow
3268 case SE_CAF_BLACKHOLE:
3275 StgBlockingQueue *bh = (StgBlockingQueue *)p;
3276 evac_gen = 0; // repeatedly mutable
3277 bh->blocking_queue =
3278 (StgTSO *)evacuate((StgClosure *)bh->blocking_queue);
3279 failed_to_evac = rtsTrue;
3283 case THUNK_SELECTOR:
3285 StgSelector *s = (StgSelector *)p;
3286 s->selectee = evacuate(s->selectee);
3292 StgAP_STACK *ap = (StgAP_STACK *)p;
3294 ap->fun = evacuate(ap->fun);
3295 scavenge_stack((StgPtr)ap->payload, (StgPtr)ap->payload + ap->size);
3296 p = (StgPtr)ap->payload + ap->size;
3302 p = scavenge_PAP((StgPAP *)p);
3306 // nothing to follow
3311 // follow everything
3314 evac_gen = 0; // repeatedly mutable
3315 next = p + mut_arr_ptrs_sizeW((StgMutArrPtrs*)p);
3316 for (p = (P_)((StgMutArrPtrs *)p)->payload; p < next; p++) {
3317 *p = (StgWord)(StgPtr)evacuate((StgClosure *)*p);
3319 evac_gen = saved_evac_gen;
3320 failed_to_evac = rtsTrue;
3324 case MUT_ARR_PTRS_FROZEN:
3325 case MUT_ARR_PTRS_FROZEN0:
3327 // follow everything
3330 next = p + mut_arr_ptrs_sizeW((StgMutArrPtrs*)p);
3331 for (p = (P_)((StgMutArrPtrs *)p)->payload; p < next; p++) {
3332 *p = (StgWord)(StgPtr)evacuate((StgClosure *)*p);
3339 StgTSO *tso = (StgTSO *)p;
3341 evac_gen = 0; // repeatedly mutable
3343 evac_gen = saved_evac_gen;
3344 failed_to_evac = rtsTrue;
3349 case RBH: // cf. BLACKHOLE_BQ
3352 nat size, ptrs, nonptrs, vhs;
3354 StgInfoTable *rip = get_closure_info(p, &size, &ptrs, &nonptrs, &vhs, str);
3356 StgRBH *rbh = (StgRBH *)p;
3357 (StgClosure *)rbh->blocking_queue =
3358 evacuate((StgClosure *)rbh->blocking_queue);
3359 failed_to_evac = rtsTrue; // mutable anyhow.
3361 debugBelch("@@ scavenge: RBH %p (%s) (new blocking_queue link=%p)",
3362 p, info_type(p), (StgClosure *)rbh->blocking_queue));
3363 // ToDo: use size of reverted closure here!
3369 StgBlockedFetch *bf = (StgBlockedFetch *)p;
3370 // follow the pointer to the node which is being demanded
3371 (StgClosure *)bf->node =
3372 evacuate((StgClosure *)bf->node);
3373 // follow the link to the rest of the blocking queue
3374 (StgClosure *)bf->link =
3375 evacuate((StgClosure *)bf->link);
3377 debugBelch("@@ scavenge: %p (%s); node is now %p; exciting, isn't it",
3378 bf, info_type((StgClosure *)bf),
3379 bf->node, info_type(bf->node)));
3387 break; // nothing to do in this case
3389 case FETCH_ME_BQ: // cf. BLACKHOLE_BQ
3391 StgFetchMeBlockingQueue *fmbq = (StgFetchMeBlockingQueue *)p;
3392 (StgClosure *)fmbq->blocking_queue =
3393 evacuate((StgClosure *)fmbq->blocking_queue);
3395 debugBelch("@@ scavenge: %p (%s) exciting, isn't it",
3396 p, info_type((StgClosure *)p)));
3401 case TVAR_WAIT_QUEUE:
3403 StgTVarWaitQueue *wq = ((StgTVarWaitQueue *) p);
3405 wq->waiting_tso = (StgTSO *)evacuate((StgClosure*)wq->waiting_tso);
3406 wq->next_queue_entry = (StgTVarWaitQueue *)evacuate((StgClosure*)wq->next_queue_entry);
3407 wq->prev_queue_entry = (StgTVarWaitQueue *)evacuate((StgClosure*)wq->prev_queue_entry);
3408 evac_gen = saved_evac_gen;
3409 failed_to_evac = rtsTrue; // mutable
3415 StgTVar *tvar = ((StgTVar *) p);
3417 tvar->current_value = evacuate((StgClosure*)tvar->current_value);
3418 tvar->first_wait_queue_entry = (StgTVarWaitQueue *)evacuate((StgClosure*)tvar->first_wait_queue_entry);
3419 evac_gen = saved_evac_gen;
3420 failed_to_evac = rtsTrue; // mutable
3426 StgTRecHeader *trec = ((StgTRecHeader *) p);
3428 trec->enclosing_trec = (StgTRecHeader *)evacuate((StgClosure*)trec->enclosing_trec);
3429 trec->current_chunk = (StgTRecChunk *)evacuate((StgClosure*)trec->current_chunk);
3430 evac_gen = saved_evac_gen;
3431 failed_to_evac = rtsTrue; // mutable
3438 StgTRecChunk *tc = ((StgTRecChunk *) p);
3439 TRecEntry *e = &(tc -> entries[0]);
3441 tc->prev_chunk = (StgTRecChunk *)evacuate((StgClosure*)tc->prev_chunk);
3442 for (i = 0; i < tc -> next_entry_idx; i ++, e++ ) {
3443 e->tvar = (StgTVar *)evacuate((StgClosure*)e->tvar);
3444 e->expected_value = evacuate((StgClosure*)e->expected_value);
3445 e->new_value = evacuate((StgClosure*)e->new_value);
3447 evac_gen = saved_evac_gen;
3448 failed_to_evac = rtsTrue; // mutable
3453 case IND_OLDGEN_PERM:
3455 /* Try to pull the indirectee into this generation, so we can
3456 * remove the indirection from the mutable list.
3458 ((StgInd *)p)->indirectee = evacuate(((StgInd *)p)->indirectee);
3460 #if 0 && defined(DEBUG)
3461 if (RtsFlags.DebugFlags.gc)
3462 /* Debugging code to print out the size of the thing we just
3466 StgPtr start = gen->steps[0].scan;
3467 bdescr *start_bd = gen->steps[0].scan_bd;
3469 scavenge(&gen->steps[0]);
3470 if (start_bd != gen->steps[0].scan_bd) {
3471 size += (P_)BLOCK_ROUND_UP(start) - start;
3472 start_bd = start_bd->link;
3473 while (start_bd != gen->steps[0].scan_bd) {
3474 size += BLOCK_SIZE_W;
3475 start_bd = start_bd->link;
3477 size += gen->steps[0].scan -
3478 (P_)BLOCK_ROUND_DOWN(gen->steps[0].scan);
3480 size = gen->steps[0].scan - start;
3482 debugBelch("evac IND_OLDGEN: %ld bytes", size * sizeof(W_));
3488 barf("scavenge_one: strange object %d", (int)(info->type));
3491 no_luck = failed_to_evac;
3492 failed_to_evac = rtsFalse;
3496 /* -----------------------------------------------------------------------------
3497 Scavenging mutable lists.
3499 We treat the mutable list of each generation > N (i.e. all the
3500 generations older than the one being collected) as roots. We also
3501 remove non-mutable objects from the mutable list at this point.
3502 -------------------------------------------------------------------------- */
3505 scavenge_mutable_list(generation *gen)
3510 bd = gen->saved_mut_list;
3513 for (; bd != NULL; bd = bd->link) {
3514 for (q = bd->start; q < bd->free; q++) {
3516 ASSERT(LOOKS_LIKE_CLOSURE_PTR(p));
3517 if (scavenge_one(p)) {
3518 /* didn't manage to promote everything, so put the
3519 * object back on the list.
3521 recordMutableGen((StgClosure *)p,gen);
3526 // free the old mut_list
3527 freeChain(gen->saved_mut_list);
3528 gen->saved_mut_list = NULL;
3533 scavenge_static(void)
3535 StgClosure* p = static_objects;
3536 const StgInfoTable *info;
3538 /* Always evacuate straight to the oldest generation for static
3540 evac_gen = oldest_gen->no;
3542 /* keep going until we've scavenged all the objects on the linked
3544 while (p != END_OF_STATIC_LIST) {
3546 ASSERT(LOOKS_LIKE_CLOSURE_PTR(p));
3549 if (info->type==RBH)
3550 info = REVERT_INFOPTR(info); // if it's an RBH, look at the orig closure
3552 // make sure the info pointer is into text space
3554 /* Take this object *off* the static_objects list,
3555 * and put it on the scavenged_static_objects list.
3557 static_objects = STATIC_LINK(info,p);
3558 STATIC_LINK(info,p) = scavenged_static_objects;
3559 scavenged_static_objects = p;
3561 switch (info -> type) {
3565 StgInd *ind = (StgInd *)p;
3566 ind->indirectee = evacuate(ind->indirectee);
3568 /* might fail to evacuate it, in which case we have to pop it
3569 * back on the mutable list of the oldest generation. We
3570 * leave it *on* the scavenged_static_objects list, though,
3571 * in case we visit this object again.
3573 if (failed_to_evac) {
3574 failed_to_evac = rtsFalse;
3575 recordMutableGen((StgClosure *)p,oldest_gen);
3581 scavenge_thunk_srt(info);
3585 scavenge_fun_srt(info);
3592 next = (P_)p->payload + info->layout.payload.ptrs;
3593 // evacuate the pointers
3594 for (q = (P_)p->payload; q < next; q++) {
3595 *q = (StgWord)(StgPtr)evacuate((StgClosure *)*q);
3601 barf("scavenge_static: strange closure %d", (int)(info->type));
3604 ASSERT(failed_to_evac == rtsFalse);
3606 /* get the next static object from the list. Remember, there might
3607 * be more stuff on this list now that we've done some evacuating!
3608 * (static_objects is a global)
3614 /* -----------------------------------------------------------------------------
3615 scavenge a chunk of memory described by a bitmap
3616 -------------------------------------------------------------------------- */
3619 scavenge_large_bitmap( StgPtr p, StgLargeBitmap *large_bitmap, nat size )
3625 bitmap = large_bitmap->bitmap[b];
3626 for (i = 0; i < size; ) {
3627 if ((bitmap & 1) == 0) {
3628 *p = (StgWord)(StgPtr)evacuate((StgClosure *)*p);
3632 if (i % BITS_IN(W_) == 0) {
3634 bitmap = large_bitmap->bitmap[b];
3636 bitmap = bitmap >> 1;
3641 STATIC_INLINE StgPtr
3642 scavenge_small_bitmap (StgPtr p, nat size, StgWord bitmap)
3645 if ((bitmap & 1) == 0) {
3646 *p = (StgWord)(StgPtr)evacuate((StgClosure *)*p);
3649 bitmap = bitmap >> 1;
3655 /* -----------------------------------------------------------------------------
3656 scavenge_stack walks over a section of stack and evacuates all the
3657 objects pointed to by it. We can use the same code for walking
3658 AP_STACK_UPDs, since these are just sections of copied stack.
3659 -------------------------------------------------------------------------- */
3663 scavenge_stack(StgPtr p, StgPtr stack_end)
3665 const StgRetInfoTable* info;
3669 //IF_DEBUG(sanity, debugBelch(" scavenging stack between %p and %p", p, stack_end));
3672 * Each time around this loop, we are looking at a chunk of stack
3673 * that starts with an activation record.
3676 while (p < stack_end) {
3677 info = get_ret_itbl((StgClosure *)p);
3679 switch (info->i.type) {
3682 ((StgUpdateFrame *)p)->updatee
3683 = evacuate(((StgUpdateFrame *)p)->updatee);
3684 p += sizeofW(StgUpdateFrame);
3687 // small bitmap (< 32 entries, or 64 on a 64-bit machine)
3688 case CATCH_STM_FRAME:
3689 case CATCH_RETRY_FRAME:
3690 case ATOMICALLY_FRAME:
3695 bitmap = BITMAP_BITS(info->i.layout.bitmap);
3696 size = BITMAP_SIZE(info->i.layout.bitmap);
3697 // NOTE: the payload starts immediately after the info-ptr, we
3698 // don't have an StgHeader in the same sense as a heap closure.
3700 p = scavenge_small_bitmap(p, size, bitmap);
3703 scavenge_srt((StgClosure **)GET_SRT(info), info->i.srt_bitmap);
3711 *p = (StgWord)(StgPtr)evacuate((StgClosure *)*p);
3714 size = BCO_BITMAP_SIZE(bco);
3715 scavenge_large_bitmap(p, BCO_BITMAP(bco), size);
3720 // large bitmap (> 32 entries, or > 64 on a 64-bit machine)
3726 size = GET_LARGE_BITMAP(&info->i)->size;
3728 scavenge_large_bitmap(p, GET_LARGE_BITMAP(&info->i), size);
3730 // and don't forget to follow the SRT
3734 // Dynamic bitmap: the mask is stored on the stack, and
3735 // there are a number of non-pointers followed by a number
3736 // of pointers above the bitmapped area. (see StgMacros.h,
3741 dyn = ((StgRetDyn *)p)->liveness;
3743 // traverse the bitmap first
3744 bitmap = RET_DYN_LIVENESS(dyn);
3745 p = (P_)&((StgRetDyn *)p)->payload[0];
3746 size = RET_DYN_BITMAP_SIZE;
3747 p = scavenge_small_bitmap(p, size, bitmap);
3749 // skip over the non-ptr words
3750 p += RET_DYN_NONPTRS(dyn) + RET_DYN_NONPTR_REGS_SIZE;
3752 // follow the ptr words
3753 for (size = RET_DYN_PTRS(dyn); size > 0; size--) {
3754 *p = (StgWord)(StgPtr)evacuate((StgClosure *)*p);
3762 StgRetFun *ret_fun = (StgRetFun *)p;
3763 StgFunInfoTable *fun_info;
3765 ret_fun->fun = evacuate(ret_fun->fun);
3766 fun_info = get_fun_itbl(ret_fun->fun);
3767 p = scavenge_arg_block(fun_info, ret_fun->payload);
3772 barf("scavenge_stack: weird activation record found on stack: %d", (int)(info->i.type));
3777 /*-----------------------------------------------------------------------------
3778 scavenge the large object list.
3780 evac_gen set by caller; similar games played with evac_gen as with
3781 scavenge() - see comment at the top of scavenge(). Most large
3782 objects are (repeatedly) mutable, so most of the time evac_gen will
3784 --------------------------------------------------------------------------- */
3787 scavenge_large(step *stp)
3792 bd = stp->new_large_objects;
3794 for (; bd != NULL; bd = stp->new_large_objects) {
3796 /* take this object *off* the large objects list and put it on
3797 * the scavenged large objects list. This is so that we can
3798 * treat new_large_objects as a stack and push new objects on
3799 * the front when evacuating.
3801 stp->new_large_objects = bd->link;
3802 dbl_link_onto(bd, &stp->scavenged_large_objects);
3804 // update the block count in this step.
3805 stp->n_scavenged_large_blocks += bd->blocks;
3808 if (scavenge_one(p)) {
3809 recordMutableGen((StgClosure *)p, stp->gen);
3814 /* -----------------------------------------------------------------------------
3815 Initialising the static object & mutable lists
3816 -------------------------------------------------------------------------- */
3819 zero_static_object_list(StgClosure* first_static)
3823 const StgInfoTable *info;
3825 for (p = first_static; p != END_OF_STATIC_LIST; p = link) {
3827 link = STATIC_LINK(info, p);
3828 STATIC_LINK(info,p) = NULL;
3832 /* -----------------------------------------------------------------------------
3834 -------------------------------------------------------------------------- */
3841 for (c = (StgIndStatic *)caf_list; c != NULL;
3842 c = (StgIndStatic *)c->static_link)
3844 SET_INFO(c, c->saved_info);
3845 c->saved_info = NULL;
3846 // could, but not necessary: c->static_link = NULL;
3852 markCAFs( evac_fn evac )
3856 for (c = (StgIndStatic *)caf_list; c != NULL;
3857 c = (StgIndStatic *)c->static_link)
3859 evac(&c->indirectee);
3863 /* -----------------------------------------------------------------------------
3864 Sanity code for CAF garbage collection.
3866 With DEBUG turned on, we manage a CAF list in addition to the SRT
3867 mechanism. After GC, we run down the CAF list and blackhole any
3868 CAFs which have been garbage collected. This means we get an error
3869 whenever the program tries to enter a garbage collected CAF.
3871 Any garbage collected CAFs are taken off the CAF list at the same
3873 -------------------------------------------------------------------------- */
3875 #if 0 && defined(DEBUG)
3882 const StgInfoTable *info;
3893 ASSERT(info->type == IND_STATIC);
3895 if (STATIC_LINK(info,p) == NULL) {
3896 IF_DEBUG(gccafs, debugBelch("CAF gc'd at 0x%04lx", (long)p));
3898 SET_INFO(p,&stg_BLACKHOLE_info);
3899 p = STATIC_LINK2(info,p);
3903 pp = &STATIC_LINK2(info,p);
3910 // debugBelch("%d CAFs live", i);
3915 /* -----------------------------------------------------------------------------
3918 Whenever a thread returns to the scheduler after possibly doing
3919 some work, we have to run down the stack and black-hole all the
3920 closures referred to by update frames.
3921 -------------------------------------------------------------------------- */
3924 threadLazyBlackHole(StgTSO *tso)
3927 StgRetInfoTable *info;
3928 StgBlockingQueue *bh;
3931 stack_end = &tso->stack[tso->stack_size];
3933 frame = (StgClosure *)tso->sp;
3936 info = get_ret_itbl(frame);
3938 switch (info->i.type) {
3941 bh = (StgBlockingQueue *)((StgUpdateFrame *)frame)->updatee;
3943 /* if the thunk is already blackholed, it means we've also
3944 * already blackholed the rest of the thunks on this stack,
3945 * so we can stop early.
3947 * The blackhole made for a CAF is a CAF_BLACKHOLE, so they
3948 * don't interfere with this optimisation.
3950 if (bh->header.info == &stg_BLACKHOLE_info) {
3954 if (bh->header.info != &stg_BLACKHOLE_BQ_info &&
3955 bh->header.info != &stg_CAF_BLACKHOLE_info) {
3956 #if (!defined(LAZY_BLACKHOLING)) && defined(DEBUG)
3957 debugBelch("Unexpected lazy BHing required at 0x%04x",(int)bh);
3961 // We pretend that bh is now dead.
3962 LDV_recordDead_FILL_SLOP_DYNAMIC((StgClosure *)bh);
3964 SET_INFO(bh,&stg_BLACKHOLE_info);
3966 // We pretend that bh has just been created.
3967 LDV_RECORD_CREATE(bh);
3970 frame = (StgClosure *) ((StgUpdateFrame *)frame + 1);
3976 // normal stack frames; do nothing except advance the pointer
3978 frame = (StgClosure *)((StgPtr)frame + stack_frame_sizeW(frame));
3984 /* -----------------------------------------------------------------------------
3987 * Code largely pinched from old RTS, then hacked to bits. We also do
3988 * lazy black holing here.
3990 * -------------------------------------------------------------------------- */
3992 struct stack_gap { StgWord gap_size; struct stack_gap *next_gap; };
3995 threadSqueezeStack(StgTSO *tso)
3998 rtsBool prev_was_update_frame;
3999 StgClosure *updatee = NULL;
4001 StgRetInfoTable *info;
4002 StgWord current_gap_size;
4003 struct stack_gap *gap;
4006 // Traverse the stack upwards, replacing adjacent update frames
4007 // with a single update frame and a "stack gap". A stack gap
4008 // contains two values: the size of the gap, and the distance
4009 // to the next gap (or the stack top).
4011 bottom = &(tso->stack[tso->stack_size]);
4015 ASSERT(frame < bottom);
4017 prev_was_update_frame = rtsFalse;
4018 current_gap_size = 0;
4019 gap = (struct stack_gap *) (tso->sp - sizeofW(StgUpdateFrame));
4021 while (frame < bottom) {
4023 info = get_ret_itbl((StgClosure *)frame);
4024 switch (info->i.type) {
4028 StgUpdateFrame *upd = (StgUpdateFrame *)frame;
4030 if (upd->updatee->header.info == &stg_BLACKHOLE_info) {
4032 // found a BLACKHOLE'd update frame; we've been here
4033 // before, in a previous GC, so just break out.
4035 // Mark the end of the gap, if we're in one.
4036 if (current_gap_size != 0) {
4037 gap = (struct stack_gap *)(frame-sizeofW(StgUpdateFrame));
4040 frame += sizeofW(StgUpdateFrame);
4041 goto done_traversing;
4044 if (prev_was_update_frame) {
4046 TICK_UPD_SQUEEZED();
4047 /* wasn't there something about update squeezing and ticky to be
4048 * sorted out? oh yes: we aren't counting each enter properly
4049 * in this case. See the log somewhere. KSW 1999-04-21
4051 * Check two things: that the two update frames don't point to
4052 * the same object, and that the updatee_bypass isn't already an
4053 * indirection. Both of these cases only happen when we're in a
4054 * block hole-style loop (and there are multiple update frames
4055 * on the stack pointing to the same closure), but they can both
4056 * screw us up if we don't check.
4058 if (upd->updatee != updatee && !closure_IND(upd->updatee)) {
4059 // this wakes the threads up
4060 UPD_IND_NOLOCK(upd->updatee, updatee);
4063 // now mark this update frame as a stack gap. The gap
4064 // marker resides in the bottom-most update frame of
4065 // the series of adjacent frames, and covers all the
4066 // frames in this series.
4067 current_gap_size += sizeofW(StgUpdateFrame);
4068 ((struct stack_gap *)frame)->gap_size = current_gap_size;
4069 ((struct stack_gap *)frame)->next_gap = gap;
4071 frame += sizeofW(StgUpdateFrame);
4075 // single update frame, or the topmost update frame in a series
4077 StgBlockingQueue *bh = (StgBlockingQueue *)upd->updatee;
4079 // Do lazy black-holing
4080 if (bh->header.info != &stg_BLACKHOLE_info &&
4081 bh->header.info != &stg_BLACKHOLE_BQ_info &&
4082 bh->header.info != &stg_CAF_BLACKHOLE_info) {
4083 #if (!defined(LAZY_BLACKHOLING)) && defined(DEBUG)
4084 debugBelch("Unexpected lazy BHing required at 0x%04x",(int)bh);
4087 /* zero out the slop so that the sanity checker can tell
4088 * where the next closure is.
4091 StgInfoTable *bh_info = get_itbl(bh);
4092 nat np = bh_info->layout.payload.ptrs,
4093 nw = bh_info->layout.payload.nptrs, i;
4094 /* don't zero out slop for a THUNK_SELECTOR,
4095 * because its layout info is used for a
4096 * different purpose, and it's exactly the
4097 * same size as a BLACKHOLE in any case.
4099 if (bh_info->type != THUNK_SELECTOR) {
4100 for (i = 0; i < np + nw; i++) {
4101 ((StgClosure *)bh)->payload[i] = INVALID_OBJECT;
4107 // We pretend that bh is now dead.
4108 LDV_recordDead_FILL_SLOP_DYNAMIC((StgClosure *)bh);
4110 // Todo: maybe use SET_HDR() and remove LDV_RECORD_CREATE()?
4111 SET_INFO(bh,&stg_BLACKHOLE_info);
4113 // We pretend that bh has just been created.
4114 LDV_RECORD_CREATE(bh);
4117 prev_was_update_frame = rtsTrue;
4118 updatee = upd->updatee;
4119 frame += sizeofW(StgUpdateFrame);
4125 prev_was_update_frame = rtsFalse;
4127 // we're not in a gap... check whether this is the end of a gap
4128 // (an update frame can't be the end of a gap).
4129 if (current_gap_size != 0) {
4130 gap = (struct stack_gap *) (frame - sizeofW(StgUpdateFrame));
4132 current_gap_size = 0;
4134 frame += stack_frame_sizeW((StgClosure *)frame);
4141 // Now we have a stack with gaps in it, and we have to walk down
4142 // shoving the stack up to fill in the gaps. A diagram might
4146 // | ********* | <- sp
4150 // | stack_gap | <- gap | chunk_size
4152 // | ......... | <- gap_end v
4158 // 'sp' points the the current top-of-stack
4159 // 'gap' points to the stack_gap structure inside the gap
4160 // ***** indicates real stack data
4161 // ..... indicates gap
4162 // <empty> indicates unused
4166 void *gap_start, *next_gap_start, *gap_end;
4169 next_gap_start = (void *)((unsigned char*)gap + sizeof(StgUpdateFrame));
4170 sp = next_gap_start;
4172 while ((StgPtr)gap > tso->sp) {
4174 // we're working in *bytes* now...
4175 gap_start = next_gap_start;
4176 gap_end = (void*) ((unsigned char*)gap_start - gap->gap_size * sizeof(W_));
4178 gap = gap->next_gap;
4179 next_gap_start = (void *)((unsigned char*)gap + sizeof(StgUpdateFrame));
4181 chunk_size = (unsigned char*)gap_end - (unsigned char*)next_gap_start;
4183 memmove(sp, next_gap_start, chunk_size);
4186 tso->sp = (StgPtr)sp;
4190 /* -----------------------------------------------------------------------------
4193 * We have to prepare for GC - this means doing lazy black holing
4194 * here. We also take the opportunity to do stack squeezing if it's
4196 * -------------------------------------------------------------------------- */
4198 threadPaused(StgTSO *tso)
4200 if ( RtsFlags.GcFlags.squeezeUpdFrames == rtsTrue )
4201 threadSqueezeStack(tso); // does black holing too
4203 threadLazyBlackHole(tso);
4206 /* -----------------------------------------------------------------------------
4208 * -------------------------------------------------------------------------- */
4212 printMutableList(generation *gen)
4217 debugBelch("@@ Mutable list %p: ", gen->mut_list);
4219 for (bd = gen->mut_list; bd != NULL; bd = bd->link) {
4220 for (p = bd->start; p < bd->free; p++) {
4221 debugBelch("%p (%s), ", (void *)*p, info_type((StgClosure *)*p));
4227 STATIC_INLINE rtsBool
4228 maybeLarge(StgClosure *closure)
4230 StgInfoTable *info = get_itbl(closure);
4232 /* closure types that may be found on the new_large_objects list;
4233 see scavenge_large */
4234 return (info->type == MUT_ARR_PTRS ||
4235 info->type == MUT_ARR_PTRS_FROZEN ||
4236 info->type == MUT_ARR_PTRS_FROZEN0 ||
4237 info->type == TSO ||
4238 info->type == ARR_WORDS);