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