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