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