use cas() to claim the closure in copyPart(), to match copy_tag()
[ghc-hetmet.git] / rts / sm / Evac.c
1 /* -----------------------------------------------------------------------------
2  *
3  * (c) The GHC Team 1998-2008
4  *
5  * Generational garbage collector: evacuation functions
6  *
7  * Documentation on the architecture of the Garbage Collector can be
8  * found in the online commentary:
9  * 
10  *   http://hackage.haskell.org/trac/ghc/wiki/Commentary/Rts/Storage/GC
11  *
12  * ---------------------------------------------------------------------------*/
13
14 #include "PosixSource.h"
15 #include "Rts.h"
16
17 #include "Evac.h"
18 #include "Storage.h"
19 #include "GC.h"
20 #include "GCThread.h"
21 #include "GCUtils.h"
22 #include "Compact.h"
23 #include "Prelude.h"
24 #include "Trace.h"
25 #include "LdvProfile.h"
26
27 #if defined(PROF_SPIN) && defined(THREADED_RTS) && defined(PARALLEL_GC)
28 StgWord64 whitehole_spin = 0;
29 #endif
30
31 #if defined(THREADED_RTS) && !defined(PARALLEL_GC)
32 #define evacuate(p) evacuate1(p)
33 #define HEAP_ALLOCED_GC(p) HEAP_ALLOCED(p)
34 #endif
35
36 #if !defined(PARALLEL_GC)
37 #define copy_tag_nolock(p, info, src, size, stp, tag) \
38         copy_tag(p, info, src, size, stp, tag)
39 #endif
40
41 /* Used to avoid long recursion due to selector thunks
42  */
43 #define MAX_THUNK_SELECTOR_DEPTH 16
44
45 static void eval_thunk_selector (StgClosure **q, StgSelector * p, rtsBool);
46 STATIC_INLINE void evacuate_large(StgPtr p);
47
48 /* -----------------------------------------------------------------------------
49    Allocate some space in which to copy an object.
50    -------------------------------------------------------------------------- */
51
52 STATIC_INLINE StgPtr
53 alloc_for_copy (nat size, step *stp)
54 {
55     StgPtr to;
56     step_workspace *ws;
57
58     /* Find out where we're going, using the handy "to" pointer in 
59      * the step of the source object.  If it turns out we need to
60      * evacuate to an older generation, adjust it here (see comment
61      * by evacuate()).
62      */
63     if (stp < gct->evac_step) {
64         if (gct->eager_promotion) {
65             stp = gct->evac_step;
66         } else {
67             gct->failed_to_evac = rtsTrue;
68         }
69     }
70     
71     ws = &gct->steps[stp->abs_no];
72     // this compiles to a single mem access to stp->abs_no only
73     
74     /* chain a new block onto the to-space for the destination step if
75      * necessary.
76      */
77     to = ws->todo_free;
78     ws->todo_free += size;
79     if (ws->todo_free > ws->todo_lim) {
80         to = todo_block_full(size, ws);
81     }
82     ASSERT(ws->todo_free >= ws->todo_bd->free && ws->todo_free <= ws->todo_lim);
83
84     return to;
85 }
86
87 /* -----------------------------------------------------------------------------
88    The evacuate() code
89    -------------------------------------------------------------------------- */
90
91 STATIC_INLINE GNUC_ATTR_HOT void
92 copy_tag(StgClosure **p, const StgInfoTable *info, 
93          StgClosure *src, nat size, step *stp, StgWord tag)
94 {
95     StgPtr to, from;
96     nat i;
97
98     to = alloc_for_copy(size,stp);
99     
100     TICK_GC_WORDS_COPIED(size);
101
102     from = (StgPtr)src;
103     to[0] = (W_)info;
104     for (i = 1; i < size; i++) { // unroll for small i
105         to[i] = from[i];
106     }
107
108 //  if (to+size+2 < bd->start + BLOCK_SIZE_W) {
109 //      __builtin_prefetch(to + size + 2, 1);
110 //  }
111
112 #if defined(PARALLEL_GC)
113     {
114         const StgInfoTable *new_info;
115         new_info = (const StgInfoTable *)cas((StgPtr)&src->header.info,
116                                              (W_)info, MK_FORWARDING_PTR(to));
117         if (new_info != info) {
118             return evacuate(p); // does the failed_to_evac stuff
119         } else {
120             *p = TAG_CLOSURE(tag,(StgClosure*)to);
121         }
122     }
123 #else
124     src->header.info = (const StgInfoTable *)MK_FORWARDING_PTR(to);
125     *p = TAG_CLOSURE(tag,(StgClosure*)to);
126 #endif
127
128 #ifdef PROFILING
129     // We store the size of the just evacuated object in the LDV word so that
130     // the profiler can guess the position of the next object later.
131     SET_EVACUAEE_FOR_LDV(from, size);
132 #endif
133 }
134
135 #if defined(PARALLEL_GC)
136 STATIC_INLINE void
137 copy_tag_nolock(StgClosure **p, const StgInfoTable *info, 
138          StgClosure *src, nat size, step *stp, StgWord tag)
139 {
140     StgPtr to, from;
141     nat i;
142
143     to = alloc_for_copy(size,stp);
144     *p = TAG_CLOSURE(tag,(StgClosure*)to);
145     src->header.info = (const StgInfoTable *)MK_FORWARDING_PTR(to);
146     
147     TICK_GC_WORDS_COPIED(size);
148
149     from = (StgPtr)src;
150     to[0] = (W_)info;
151     for (i = 1; i < size; i++) { // unroll for small i
152         to[i] = from[i];
153     }
154
155 //  if (to+size+2 < bd->start + BLOCK_SIZE_W) {
156 //      __builtin_prefetch(to + size + 2, 1);
157 //  }
158
159 #ifdef PROFILING
160     // We store the size of the just evacuated object in the LDV word so that
161     // the profiler can guess the position of the next object later.
162     SET_EVACUAEE_FOR_LDV(from, size);
163 #endif
164 }
165 #endif
166
167 /* Special version of copy() for when we only want to copy the info
168  * pointer of an object, but reserve some padding after it.  This is
169  * used to optimise evacuation of BLACKHOLEs.
170  */
171 static rtsBool
172 copyPart(StgClosure **p, const StgInfoTable *info, StgClosure *src, 
173          nat size_to_reserve, nat size_to_copy, step *stp)
174 {
175     StgPtr to, from;
176     nat i;
177     
178     to = alloc_for_copy(size_to_reserve, stp);
179
180     TICK_GC_WORDS_COPIED(size_to_copy);
181
182     from = (StgPtr)src;
183     to[0] = (W_)info;
184     for (i = 1; i < size_to_copy; i++) { // unroll for small i
185         to[i] = from[i];
186     }
187     
188 #if defined(PARALLEL_GC)
189     {
190         const StgInfoTable *new_info;
191         new_info = (const StgInfoTable *)cas((StgPtr)&src->header.info, 
192                                              (W_)info, MK_FORWARDING_PTR(to));
193         if (new_info != info) {
194             evacuate(p); // does the failed_to_evac stuff
195             return rtsFalse;
196         } else {
197             *p = (StgClosure*)to;
198         }
199     }
200 #else
201     src->header.info = (const StgInfoTable *)MK_FORWARDING_PTR(to);
202     *p = (StgClosure*)to;
203 #endif
204
205 #ifdef PROFILING
206     // We store the size of the just evacuated object in the LDV word so that
207     // the profiler can guess the position of the next object later.
208     SET_EVACUAEE_FOR_LDV(from, size_to_reserve);
209     // fill the slop
210     if (size_to_reserve - size_to_copy > 0)
211         LDV_FILL_SLOP(to + size_to_copy, (int)(size_to_reserve - size_to_copy));
212 #endif
213
214     return rtsTrue;
215 }
216
217
218 /* Copy wrappers that don't tag the closure after copying */
219 STATIC_INLINE GNUC_ATTR_HOT void
220 copy(StgClosure **p, const StgInfoTable *info, 
221      StgClosure *src, nat size, step *stp)
222 {
223     copy_tag(p,info,src,size,stp,0);
224 }
225
226 /* -----------------------------------------------------------------------------
227    Evacuate a large object
228
229    This just consists of removing the object from the (doubly-linked)
230    step->large_objects list, and linking it on to the (singly-linked)
231    step->new_large_objects list, from where it will be scavenged later.
232
233    Convention: bd->flags has BF_EVACUATED set for a large object
234    that has been evacuated, or unset otherwise.
235    -------------------------------------------------------------------------- */
236
237 STATIC_INLINE void
238 evacuate_large(StgPtr p)
239 {
240   bdescr *bd = Bdescr(p);
241   step *stp, *new_stp;
242   step_workspace *ws;
243     
244   stp = bd->step;
245   ACQUIRE_SPIN_LOCK(&stp->sync_large_objects);
246
247   // already evacuated? 
248   if (bd->flags & BF_EVACUATED) { 
249     /* Don't forget to set the gct->failed_to_evac flag if we didn't get
250      * the desired destination (see comments in evacuate()).
251      */
252     if (stp < gct->evac_step) {
253         gct->failed_to_evac = rtsTrue;
254         TICK_GC_FAILED_PROMOTION();
255     }
256     RELEASE_SPIN_LOCK(&stp->sync_large_objects);
257     return;
258   }
259
260   // remove from large_object list 
261   if (bd->u.back) {
262     bd->u.back->link = bd->link;
263   } else { // first object in the list 
264     stp->large_objects = bd->link;
265   }
266   if (bd->link) {
267     bd->link->u.back = bd->u.back;
268   }
269   
270   /* link it on to the evacuated large object list of the destination step
271    */
272   new_stp = stp->to;
273   if (new_stp < gct->evac_step) {
274       if (gct->eager_promotion) {
275           new_stp = gct->evac_step;
276       } else {
277           gct->failed_to_evac = rtsTrue;
278       }
279   }
280
281   ws = &gct->steps[new_stp->abs_no];
282
283   bd->flags |= BF_EVACUATED;
284   bd->step = new_stp;
285   bd->gen_no = new_stp->gen_no;
286
287   // If this is a block of pinned objects, we don't have to scan
288   // these objects, because they aren't allowed to contain any
289   // pointers.  For these blocks, we skip the scavenge stage and put
290   // them straight on the scavenged_large_objects list.
291   if (bd->flags & BF_PINNED) {
292       ASSERT(get_itbl((StgClosure *)p)->type == ARR_WORDS);
293       if (new_stp != stp) { ACQUIRE_SPIN_LOCK(&new_stp->sync_large_objects); }
294       dbl_link_onto(bd, &new_stp->scavenged_large_objects);
295       new_stp->n_scavenged_large_blocks += bd->blocks;
296       if (new_stp != stp) { RELEASE_SPIN_LOCK(&new_stp->sync_large_objects); }
297   } else {
298       bd->link = ws->todo_large_objects;
299       ws->todo_large_objects = bd;
300   }
301
302   RELEASE_SPIN_LOCK(&stp->sync_large_objects);
303 }
304
305 /* ----------------------------------------------------------------------------
306    Evacuate
307
308    This is called (eventually) for every live object in the system.
309
310    The caller to evacuate specifies a desired generation in the
311    gct->evac_step thread-local variable.  The following conditions apply to
312    evacuating an object which resides in generation M when we're
313    collecting up to generation N
314
315    if  M >= gct->evac_step 
316            if  M > N     do nothing
317            else          evac to step->to
318
319    if  M < gct->evac_step      evac to gct->evac_step, step 0
320
321    if the object is already evacuated, then we check which generation
322    it now resides in.
323
324    if  M >= gct->evac_step     do nothing
325    if  M <  gct->evac_step     set gct->failed_to_evac flag to indicate that we
326                          didn't manage to evacuate this object into gct->evac_step.
327
328
329    OPTIMISATION NOTES:
330
331    evacuate() is the single most important function performance-wise
332    in the GC.  Various things have been tried to speed it up, but as
333    far as I can tell the code generated by gcc 3.2 with -O2 is about
334    as good as it's going to get.  We pass the argument to evacuate()
335    in a register using the 'regparm' attribute (see the prototype for
336    evacuate() near the top of this file).
337
338    Changing evacuate() to take an (StgClosure **) rather than
339    returning the new pointer seems attractive, because we can avoid
340    writing back the pointer when it hasn't changed (eg. for a static
341    object, or an object in a generation > N).  However, I tried it and
342    it doesn't help.  One reason is that the (StgClosure **) pointer
343    gets spilled to the stack inside evacuate(), resulting in far more
344    extra reads/writes than we save.
345    ------------------------------------------------------------------------- */
346
347 REGPARM1 GNUC_ATTR_HOT void 
348 evacuate(StgClosure **p)
349 {
350   bdescr *bd = NULL;
351   step *stp;
352   StgClosure *q;
353   const StgInfoTable *info;
354   StgWord tag;
355
356   q = *p;
357
358 loop:
359   /* The tag and the pointer are split, to be merged after evacing */
360   tag = GET_CLOSURE_TAG(q);
361   q = UNTAG_CLOSURE(q);
362
363   ASSERT(LOOKS_LIKE_CLOSURE_PTR(q));
364
365   if (!HEAP_ALLOCED_GC(q)) {
366
367       if (!major_gc) return;
368
369       info = get_itbl(q);
370       switch (info->type) {
371
372       case THUNK_STATIC:
373           if (info->srt_bitmap != 0) {
374               if (*THUNK_STATIC_LINK((StgClosure *)q) == NULL) {
375 #ifndef THREADED_RTS
376                   *THUNK_STATIC_LINK((StgClosure *)q) = gct->static_objects;
377                   gct->static_objects = (StgClosure *)q;
378 #else
379                   StgPtr link;
380                   link = (StgPtr)cas((StgPtr)THUNK_STATIC_LINK((StgClosure *)q),
381                                      (StgWord)NULL,
382                                      (StgWord)gct->static_objects);
383                   if (link == NULL) {
384                       gct->static_objects = (StgClosure *)q;
385                   }
386 #endif
387               }
388           }
389           return;
390
391       case FUN_STATIC:
392           if (info->srt_bitmap != 0 &&
393               *FUN_STATIC_LINK((StgClosure *)q) == NULL) {
394 #ifndef THREADED_RTS
395               *FUN_STATIC_LINK((StgClosure *)q) = gct->static_objects;
396               gct->static_objects = (StgClosure *)q;
397 #else
398               StgPtr link;
399               link = (StgPtr)cas((StgPtr)FUN_STATIC_LINK((StgClosure *)q),
400                                  (StgWord)NULL,
401                                  (StgWord)gct->static_objects);
402               if (link == NULL) {
403                   gct->static_objects = (StgClosure *)q;
404               }
405 #endif
406           }
407           return;
408           
409       case IND_STATIC:
410           /* If q->saved_info != NULL, then it's a revertible CAF - it'll be
411            * on the CAF list, so don't do anything with it here (we'll
412            * scavenge it later).
413            */
414           if (((StgIndStatic *)q)->saved_info == NULL) {
415               if (*IND_STATIC_LINK((StgClosure *)q) == NULL) {
416 #ifndef THREADED_RTS
417                   *IND_STATIC_LINK((StgClosure *)q) = gct->static_objects;
418                   gct->static_objects = (StgClosure *)q;
419 #else
420                   StgPtr link;
421                   link = (StgPtr)cas((StgPtr)IND_STATIC_LINK((StgClosure *)q),
422                                      (StgWord)NULL,
423                                      (StgWord)gct->static_objects);
424                   if (link == NULL) {
425                       gct->static_objects = (StgClosure *)q;
426                   }
427 #endif
428               }
429           }
430           return;
431           
432       case CONSTR_STATIC:
433           if (*STATIC_LINK(info,(StgClosure *)q) == NULL) {
434 #ifndef THREADED_RTS
435               *STATIC_LINK(info,(StgClosure *)q) = gct->static_objects;
436               gct->static_objects = (StgClosure *)q;
437 #else
438               StgPtr link;
439               link = (StgPtr)cas((StgPtr)STATIC_LINK(info,(StgClosure *)q),
440                                  (StgWord)NULL,
441                                  (StgWord)gct->static_objects);
442               if (link == NULL) {
443                   gct->static_objects = (StgClosure *)q;
444               }
445 #endif
446           }
447           /* I am assuming that static_objects pointers are not
448            * written to other objects, and thus, no need to retag. */
449           return;
450           
451       case CONSTR_NOCAF_STATIC:
452           /* no need to put these on the static linked list, they don't need
453            * to be scavenged.
454            */
455           return;
456           
457       default:
458           barf("evacuate(static): strange closure type %d", (int)(info->type));
459       }
460   }
461
462   bd = Bdescr((P_)q);
463
464   if ((bd->flags & (BF_LARGE | BF_MARKED | BF_EVACUATED)) != 0) {
465
466       // pointer into to-space: just return it.  It might be a pointer
467       // into a generation that we aren't collecting (> N), or it
468       // might just be a pointer into to-space.  The latter doesn't
469       // happen often, but allowing it makes certain things a bit
470       // easier; e.g. scavenging an object is idempotent, so it's OK to
471       // have an object on the mutable list multiple times.
472       if (bd->flags & BF_EVACUATED) {
473           // We aren't copying this object, so we have to check
474           // whether it is already in the target generation.  (this is
475           // the write barrier).
476           if (bd->step < gct->evac_step) {
477               gct->failed_to_evac = rtsTrue;
478               TICK_GC_FAILED_PROMOTION();
479           }
480           return;
481       }
482
483       /* evacuate large objects by re-linking them onto a different list.
484        */
485       if (bd->flags & BF_LARGE) {
486           info = get_itbl(q);
487           if (info->type == TSO && 
488               ((StgTSO *)q)->what_next == ThreadRelocated) {
489               q = (StgClosure *)((StgTSO *)q)->_link;
490               *p = q;
491               goto loop;
492           }
493           evacuate_large((P_)q);
494           return;
495       }
496       
497       /* If the object is in a step that we're compacting, then we
498        * need to use an alternative evacuate procedure.
499        */
500       if (!is_marked((P_)q,bd)) {
501           mark((P_)q,bd);
502           if (mark_stack_full()) {
503               debugTrace(DEBUG_gc,"mark stack overflowed");
504               mark_stack_overflowed = rtsTrue;
505               reset_mark_stack();
506           }
507           push_mark_stack((P_)q);
508       }
509       return;
510   }
511       
512   stp = bd->step->to;
513
514   info = q->header.info;
515   if (IS_FORWARDING_PTR(info))
516   {
517     /* Already evacuated, just return the forwarding address.
518      * HOWEVER: if the requested destination generation (gct->evac_step) is
519      * older than the actual generation (because the object was
520      * already evacuated to a younger generation) then we have to
521      * set the gct->failed_to_evac flag to indicate that we couldn't 
522      * manage to promote the object to the desired generation.
523      */
524     /* 
525      * Optimisation: the check is fairly expensive, but we can often
526      * shortcut it if either the required generation is 0, or the
527      * current object (the EVACUATED) is in a high enough generation.
528      * We know that an EVACUATED always points to an object in the
529      * same or an older generation.  stp is the lowest step that the
530      * current object would be evacuated to, so we only do the full
531      * check if stp is too low.
532      */
533       StgClosure *e = (StgClosure*)UN_FORWARDING_PTR(info);
534       *p = TAG_CLOSURE(tag,e);
535       if (stp < gct->evac_step) {  // optimisation 
536           if (Bdescr((P_)e)->step < gct->evac_step) {
537               gct->failed_to_evac = rtsTrue;
538               TICK_GC_FAILED_PROMOTION();
539           }
540       }
541       return;
542   }
543
544   switch (INFO_PTR_TO_STRUCT(info)->type) {
545
546   case WHITEHOLE:
547       goto loop;
548
549   case MUT_VAR_CLEAN:
550   case MUT_VAR_DIRTY:
551   case MVAR_CLEAN:
552   case MVAR_DIRTY:
553       copy(p,info,q,sizeW_fromITBL(INFO_PTR_TO_STRUCT(info)),stp);
554       return;
555
556   case CONSTR_0_1:
557   { 
558       StgWord w = (StgWord)q->payload[0];
559       if (info == Czh_con_info &&
560           // unsigned, so always true:  (StgChar)w >= MIN_CHARLIKE &&  
561           (StgChar)w <= MAX_CHARLIKE) {
562           *p =  TAG_CLOSURE(tag,
563                             (StgClosure *)CHARLIKE_CLOSURE((StgChar)w)
564                            );
565       }
566       else if (info == Izh_con_info &&
567           (StgInt)w >= MIN_INTLIKE && (StgInt)w <= MAX_INTLIKE) {
568           *p = TAG_CLOSURE(tag,
569                              (StgClosure *)INTLIKE_CLOSURE((StgInt)w)
570                              );
571       }
572       else {
573           copy_tag_nolock(p,info,q,sizeofW(StgHeader)+1,stp,tag);
574       }
575       return;
576   }
577
578   case FUN_0_1:
579   case FUN_1_0:
580   case CONSTR_1_0:
581       copy_tag_nolock(p,info,q,sizeofW(StgHeader)+1,stp,tag);
582       return;
583
584   case THUNK_1_0:
585   case THUNK_0_1:
586       copy(p,info,q,sizeofW(StgThunk)+1,stp);
587       return;
588
589   case THUNK_1_1:
590   case THUNK_2_0:
591   case THUNK_0_2:
592 #ifdef NO_PROMOTE_THUNKS
593     if (bd->gen_no == 0 && 
594         bd->step->no != 0 &&
595         bd->step->no == generations[bd->gen_no].n_steps-1) {
596       stp = bd->step;
597     }
598 #endif
599     copy(p,info,q,sizeofW(StgThunk)+2,stp);
600     return;
601
602   case FUN_1_1:
603   case FUN_2_0:
604   case FUN_0_2:
605   case CONSTR_1_1:
606   case CONSTR_2_0:
607       copy_tag_nolock(p,info,q,sizeofW(StgHeader)+2,stp,tag);
608       return;
609
610   case CONSTR_0_2:
611       copy_tag_nolock(p,info,q,sizeofW(StgHeader)+2,stp,tag);
612       return;
613
614   case THUNK:
615       copy(p,info,q,thunk_sizeW_fromITBL(INFO_PTR_TO_STRUCT(info)),stp);
616       return;
617
618   case FUN:
619   case IND_PERM:
620   case IND_OLDGEN_PERM:
621   case CONSTR:
622       copy_tag_nolock(p,info,q,sizeW_fromITBL(INFO_PTR_TO_STRUCT(info)),stp,tag);
623       return;
624
625   case WEAK:
626   case STABLE_NAME:
627       copy_tag(p,info,q,sizeW_fromITBL(INFO_PTR_TO_STRUCT(info)),stp,tag);
628       return;
629
630   case BCO:
631       copy(p,info,q,bco_sizeW((StgBCO *)q),stp);
632       return;
633
634   case CAF_BLACKHOLE:
635   case BLACKHOLE:
636       copyPart(p,info,q,BLACKHOLE_sizeW(),sizeofW(StgHeader),stp);
637       return;
638
639   case THUNK_SELECTOR:
640       eval_thunk_selector(p, (StgSelector *)q, rtsTrue);
641       return;
642
643   case IND:
644   case IND_OLDGEN:
645     // follow chains of indirections, don't evacuate them 
646     q = ((StgInd*)q)->indirectee;
647     *p = q;
648     goto loop;
649
650   case RET_BCO:
651   case RET_SMALL:
652   case RET_BIG:
653   case RET_DYN:
654   case UPDATE_FRAME:
655   case STOP_FRAME:
656   case CATCH_FRAME:
657   case CATCH_STM_FRAME:
658   case CATCH_RETRY_FRAME:
659   case ATOMICALLY_FRAME:
660     // shouldn't see these 
661     barf("evacuate: stack frame at %p\n", q);
662
663   case PAP:
664       copy(p,info,q,pap_sizeW((StgPAP*)q),stp);
665       return;
666
667   case AP:
668       copy(p,info,q,ap_sizeW((StgAP*)q),stp);
669       return;
670
671   case AP_STACK:
672       copy(p,info,q,ap_stack_sizeW((StgAP_STACK*)q),stp);
673       return;
674
675   case ARR_WORDS:
676       // just copy the block 
677       copy(p,info,q,arr_words_sizeW((StgArrWords *)q),stp);
678       return;
679
680   case MUT_ARR_PTRS_CLEAN:
681   case MUT_ARR_PTRS_DIRTY:
682   case MUT_ARR_PTRS_FROZEN:
683   case MUT_ARR_PTRS_FROZEN0:
684       // just copy the block 
685       copy(p,info,q,mut_arr_ptrs_sizeW((StgMutArrPtrs *)q),stp);
686       return;
687
688   case TSO:
689     {
690       StgTSO *tso = (StgTSO *)q;
691
692       /* Deal with redirected TSOs (a TSO that's had its stack enlarged).
693        */
694       if (tso->what_next == ThreadRelocated) {
695         q = (StgClosure *)tso->_link;
696         *p = q;
697         goto loop;
698       }
699
700       /* To evacuate a small TSO, we need to relocate the update frame
701        * list it contains.  
702        */
703       {
704           StgTSO *new_tso;
705           StgPtr r, s;
706           rtsBool mine;
707
708           mine = copyPart(p,info,(StgClosure *)tso, tso_sizeW(tso), 
709                           sizeofW(StgTSO), stp);
710           if (mine) {
711               new_tso = (StgTSO *)*p;
712               move_TSO(tso, new_tso);
713               for (r = tso->sp, s = new_tso->sp;
714                    r < tso->stack+tso->stack_size;) {
715                   *s++ = *r++;
716               }
717           }
718           return;
719       }
720     }
721
722   case TREC_HEADER: 
723       copy(p,info,q,sizeofW(StgTRecHeader),stp);
724       return;
725
726   case TVAR_WATCH_QUEUE:
727       copy(p,info,q,sizeofW(StgTVarWatchQueue),stp);
728       return;
729
730   case TVAR:
731       copy(p,info,q,sizeofW(StgTVar),stp);
732       return;
733     
734   case TREC_CHUNK:
735       copy(p,info,q,sizeofW(StgTRecChunk),stp);
736       return;
737
738   case ATOMIC_INVARIANT:
739       copy(p,info,q,sizeofW(StgAtomicInvariant),stp);
740       return;
741
742   case INVARIANT_CHECK_QUEUE:
743       copy(p,info,q,sizeofW(StgInvariantCheckQueue),stp);
744       return;
745
746   default:
747     barf("evacuate: strange closure type %d", (int)(INFO_PTR_TO_STRUCT(info)->type));
748   }
749
750   barf("evacuate");
751 }
752
753 /* -----------------------------------------------------------------------------
754    Evaluate a THUNK_SELECTOR if possible.
755
756    p points to a THUNK_SELECTOR that we want to evaluate.  The
757    result of "evaluating" it will be evacuated and a pointer to the
758    to-space closure will be returned.
759
760    If the THUNK_SELECTOR could not be evaluated (its selectee is still
761    a THUNK, for example), then the THUNK_SELECTOR itself will be
762    evacuated.
763    -------------------------------------------------------------------------- */
764 static void
765 unchain_thunk_selectors(StgSelector *p, StgClosure *val)
766 {
767     StgSelector *prev;
768
769     prev = NULL;
770     while (p)
771     {
772 #ifdef THREADED_RTS
773         ASSERT(p->header.info == &stg_WHITEHOLE_info);
774 #else
775         ASSERT(p->header.info == &stg_BLACKHOLE_info);
776 #endif
777         // val must be in to-space.  Not always: when we recursively
778         // invoke eval_thunk_selector(), the recursive calls will not 
779         // evacuate the value (because we want to select on the value,
780         // not evacuate it), so in this case val is in from-space.
781         // ASSERT(!HEAP_ALLOCED_GC(val) || Bdescr((P_)val)->gen_no > N || (Bdescr((P_)val)->flags & BF_EVACUATED));
782
783         prev = (StgSelector*)((StgClosure *)p)->payload[0];
784
785         // Update the THUNK_SELECTOR with an indirection to the
786         // value.  The value is still in from-space at this stage.
787         //
788         // (old note: Why not do upd_evacuee(q,p)?  Because we have an
789         // invariant that an EVACUATED closure always points to an
790         // object in the same or an older generation (required by
791         // the short-cut test in the EVACUATED case, below).
792         if ((StgClosure *)p == val) {
793             // must be a loop; just leave a BLACKHOLE in place.  This
794             // can happen when we have a chain of selectors that
795             // eventually loops back on itself.  We can't leave an
796             // indirection pointing to itself, and we want the program
797             // to deadlock if it ever enters this closure, so
798             // BLACKHOLE is correct.
799             SET_INFO(p, &stg_BLACKHOLE_info);
800         } else {
801             ((StgInd *)p)->indirectee = val;
802             write_barrier();
803             SET_INFO(p, &stg_IND_info);
804         }
805
806         // For the purposes of LDV profiling, we have created an
807         // indirection.
808         LDV_RECORD_CREATE(p);
809
810         p = prev;
811     }
812 }
813
814 static void
815 eval_thunk_selector (StgClosure **q, StgSelector * p, rtsBool evac)
816                  // NB. for legacy reasons, p & q are swapped around :(
817 {
818     nat field;
819     StgInfoTable *info;
820     StgWord info_ptr;
821     StgClosure *selectee;
822     StgSelector *prev_thunk_selector;
823     bdescr *bd;
824     StgClosure *val;
825     
826     prev_thunk_selector = NULL;
827     // this is a chain of THUNK_SELECTORs that we are going to update
828     // to point to the value of the current THUNK_SELECTOR.  Each
829     // closure on the chain is a BLACKHOLE, and points to the next in the
830     // chain with payload[0].
831
832 selector_chain:
833
834     bd = Bdescr((StgPtr)p);
835     if (HEAP_ALLOCED_GC(p)) {
836         // If the THUNK_SELECTOR is in to-space or in a generation that we
837         // are not collecting, then bale out early.  We won't be able to
838         // save any space in any case, and updating with an indirection is
839         // trickier in a non-collected gen: we would have to update the
840         // mutable list.
841         if (bd->flags & BF_EVACUATED) {
842             unchain_thunk_selectors(prev_thunk_selector, (StgClosure *)p);
843             *q = (StgClosure *)p;
844             // shortcut, behave as for:  if (evac) evacuate(q);
845             if (evac && bd->step < gct->evac_step) {
846                 gct->failed_to_evac = rtsTrue;
847                 TICK_GC_FAILED_PROMOTION();
848             }
849             return;
850         }
851         // we don't update THUNK_SELECTORS in the compacted
852         // generation, because compaction does not remove the INDs
853         // that result, this causes confusion later
854         // (scavenge_mark_stack doesn't deal with IND).  BEWARE!  This
855         // bit is very tricky to get right.  If you make changes
856         // around here, test by compiling stage 3 with +RTS -c -RTS.
857         if (bd->flags & BF_MARKED) {
858             // must call evacuate() to mark this closure if evac==rtsTrue
859             *q = (StgClosure *)p;
860             if (evac) evacuate(q);
861             unchain_thunk_selectors(prev_thunk_selector, (StgClosure *)p);
862             return;
863         }
864     }
865
866
867     // BLACKHOLE the selector thunk, since it is now under evaluation.
868     // This is important to stop us going into an infinite loop if
869     // this selector thunk eventually refers to itself.
870 #if defined(THREADED_RTS)
871     // In threaded mode, we'll use WHITEHOLE to lock the selector
872     // thunk while we evaluate it.
873     {
874         do {
875             info_ptr = xchg((StgPtr)&p->header.info, (W_)&stg_WHITEHOLE_info);
876         } while (info_ptr == (W_)&stg_WHITEHOLE_info);
877
878         // make sure someone else didn't get here first...
879         if (IS_FORWARDING_PTR(p) || 
880             INFO_PTR_TO_STRUCT(info_ptr)->type != THUNK_SELECTOR) {
881             // v. tricky now.  The THUNK_SELECTOR has been evacuated
882             // by another thread, and is now either a forwarding ptr or IND.
883             // We need to extract ourselves from the current situation
884             // as cleanly as possible.
885             //   - unlock the closure
886             //   - update *q, we may have done *some* evaluation
887             //   - if evac, we need to call evacuate(), because we
888             //     need the write-barrier stuff.
889             //   - undo the chain we've built to point to p.
890             SET_INFO(p, (const StgInfoTable *)info_ptr);
891             *q = (StgClosure *)p;
892             if (evac) evacuate(q);
893             unchain_thunk_selectors(prev_thunk_selector, (StgClosure *)p);
894             return;
895         }
896     }
897 #else
898     // Save the real info pointer (NOTE: not the same as get_itbl()).
899     info_ptr = (StgWord)p->header.info;
900     SET_INFO(p,&stg_BLACKHOLE_info);
901 #endif
902
903     field = INFO_PTR_TO_STRUCT(info_ptr)->layout.selector_offset;
904
905     // The selectee might be a constructor closure,
906     // so we untag the pointer.
907     selectee = UNTAG_CLOSURE(p->selectee);
908
909 selector_loop:
910     // selectee now points to the closure that we're trying to select
911     // a field from.  It may or may not be in to-space: we try not to
912     // end up in to-space, but it's impractical to avoid it in
913     // general.  The compacting GC scatters to-space pointers in
914     // from-space during marking, for example.  We rely on the property
915     // that evacuate() doesn't mind if it gets passed a to-space pointer.
916
917     info = (StgInfoTable*)selectee->header.info;
918
919     if (IS_FORWARDING_PTR(info)) {
920         // We don't follow pointers into to-space; the constructor
921         // has already been evacuated, so we won't save any space
922         // leaks by evaluating this selector thunk anyhow.
923         goto bale_out;
924     }
925
926     info = INFO_PTR_TO_STRUCT(info);
927     switch (info->type) {
928       case WHITEHOLE:
929           goto bale_out; // about to be evacuated by another thread (or a loop).
930         
931       case CONSTR:
932       case CONSTR_1_0:
933       case CONSTR_0_1:
934       case CONSTR_2_0:
935       case CONSTR_1_1:
936       case CONSTR_0_2:
937       case CONSTR_STATIC:
938       case CONSTR_NOCAF_STATIC:
939           {
940               // check that the size is in range 
941               ASSERT(field <  (StgWord32)(info->layout.payload.ptrs + 
942                                           info->layout.payload.nptrs));
943           
944               // Select the right field from the constructor
945               val = selectee->payload[field];
946               
947 #ifdef PROFILING
948               // For the purposes of LDV profiling, we have destroyed
949               // the original selector thunk, p.
950               SET_INFO(p, (StgInfoTable *)info_ptr);
951               LDV_RECORD_DEAD_FILL_SLOP_DYNAMIC((StgClosure *)p);
952 #if defined(THREADED_RTS)
953               SET_INFO(p, &stg_WHITEHOLE_info);
954 #else
955               SET_INFO(p, &stg_BLACKHOLE_info);
956 #endif
957 #endif
958
959               // the closure in val is now the "value" of the
960               // THUNK_SELECTOR in p.  However, val may itself be a
961               // THUNK_SELECTOR, in which case we want to continue
962               // evaluating until we find the real value, and then
963               // update the whole chain to point to the value.
964           val_loop:
965               info_ptr = (StgWord)UNTAG_CLOSURE(val)->header.info;
966               if (!IS_FORWARDING_PTR(info_ptr))
967               {
968                   info = INFO_PTR_TO_STRUCT(info_ptr);
969                   switch (info->type) {
970                   case IND:
971                   case IND_PERM:
972                   case IND_OLDGEN:
973                   case IND_OLDGEN_PERM:
974                   case IND_STATIC:
975                       val = ((StgInd *)val)->indirectee;
976                       goto val_loop;
977                   case THUNK_SELECTOR:
978                       ((StgClosure*)p)->payload[0] = (StgClosure *)prev_thunk_selector;
979                       prev_thunk_selector = p;
980                       p = (StgSelector*)val;
981                       goto selector_chain;
982                   default:
983                       break;
984                   }
985               }
986               ((StgClosure*)p)->payload[0] = (StgClosure *)prev_thunk_selector;
987               prev_thunk_selector = p;
988
989               *q = val;
990
991               // update the other selectors in the chain *before*
992               // evacuating the value.  This is necessary in the case
993               // where the value turns out to be one of the selectors
994               // in the chain (i.e. we have a loop), and evacuating it
995               // would corrupt the chain.
996               unchain_thunk_selectors(prev_thunk_selector, val);
997
998               // evacuate() cannot recurse through
999               // eval_thunk_selector(), because we know val is not
1000               // a THUNK_SELECTOR.
1001               if (evac) evacuate(q);
1002               return;
1003           }
1004
1005       case IND:
1006       case IND_PERM:
1007       case IND_OLDGEN:
1008       case IND_OLDGEN_PERM:
1009       case IND_STATIC:
1010           // Again, we might need to untag a constructor.
1011           selectee = UNTAG_CLOSURE( ((StgInd *)selectee)->indirectee );
1012           goto selector_loop;
1013
1014       case THUNK_SELECTOR:
1015       {
1016           StgClosure *val;
1017
1018           // recursively evaluate this selector.  We don't want to
1019           // recurse indefinitely, so we impose a depth bound.
1020           if (gct->thunk_selector_depth >= MAX_THUNK_SELECTOR_DEPTH) {
1021               goto bale_out;
1022           }
1023
1024           gct->thunk_selector_depth++;
1025           // rtsFalse says "don't evacuate the result".  It will,
1026           // however, update any THUNK_SELECTORs that are evaluated
1027           // along the way.
1028           eval_thunk_selector(&val, (StgSelector*)selectee, rtsFalse);
1029           gct->thunk_selector_depth--;
1030
1031           // did we actually manage to evaluate it?
1032           if (val == selectee) goto bale_out;
1033
1034           // Of course this pointer might be tagged...
1035           selectee = UNTAG_CLOSURE(val);
1036           goto selector_loop;
1037       }
1038
1039       case AP:
1040       case AP_STACK:
1041       case THUNK:
1042       case THUNK_1_0:
1043       case THUNK_0_1:
1044       case THUNK_2_0:
1045       case THUNK_1_1:
1046       case THUNK_0_2:
1047       case THUNK_STATIC:
1048       case CAF_BLACKHOLE:
1049       case BLACKHOLE:
1050           // not evaluated yet 
1051           goto bale_out;
1052     
1053       default:
1054         barf("eval_thunk_selector: strange selectee %d",
1055              (int)(info->type));
1056     }
1057
1058 bale_out:
1059     // We didn't manage to evaluate this thunk; restore the old info
1060     // pointer.  But don't forget: we still need to evacuate the thunk itself.
1061     SET_INFO(p, (const StgInfoTable *)info_ptr);
1062     // THREADED_RTS: we just unlocked the thunk, so another thread
1063     // might get in and update it.  copy() will lock it again and
1064     // check whether it was updated in the meantime.
1065     *q = (StgClosure *)p;
1066     if (evac) {
1067         copy(q,(const StgInfoTable *)info_ptr,(StgClosure *)p,THUNK_SELECTOR_sizeW(),bd->step->to);
1068     }
1069     unchain_thunk_selectors(prev_thunk_selector, *q);
1070     return;
1071 }