Initial parallel GC support
[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               ACQUIRE_SPIN_LOCK(&static_objects_sync);
406               if (*THUNK_STATIC_LINK((StgClosure *)q) == NULL) {
407                   *THUNK_STATIC_LINK((StgClosure *)q) = static_objects;
408                   static_objects = (StgClosure *)q;
409               }
410               RELEASE_SPIN_LOCK(&static_objects_sync);
411           }
412           return q;
413           
414       case FUN_STATIC:
415           if (info->srt_bitmap != 0) {
416               ACQUIRE_SPIN_LOCK(&static_objects_sync);
417               if (*FUN_STATIC_LINK((StgClosure *)q) == NULL) {
418                   *FUN_STATIC_LINK((StgClosure *)q) = static_objects;
419                   static_objects = (StgClosure *)q;
420               }
421               RELEASE_SPIN_LOCK(&static_objects_sync);
422           }
423           return q;
424           
425       case IND_STATIC:
426           /* If q->saved_info != NULL, then it's a revertible CAF - it'll be
427            * on the CAF list, so don't do anything with it here (we'll
428            * scavenge it later).
429            */
430           if (((StgIndStatic *)q)->saved_info == NULL) {
431               ACQUIRE_SPIN_LOCK(&static_objects_sync);
432               if (*IND_STATIC_LINK((StgClosure *)q) == NULL) {
433                   *IND_STATIC_LINK((StgClosure *)q) = static_objects;
434                   static_objects = (StgClosure *)q;
435               }
436               RELEASE_SPIN_LOCK(&static_objects_sync);
437           }
438           return q;
439           
440       case CONSTR_STATIC:
441           if (*STATIC_LINK(info,(StgClosure *)q) == NULL) {
442               ACQUIRE_SPIN_LOCK(&static_objects_sync);
443               // re-test, after acquiring lock
444               if (*STATIC_LINK(info,(StgClosure *)q) == NULL) {
445                   *STATIC_LINK(info,(StgClosure *)q) = static_objects;
446                   static_objects = (StgClosure *)q;
447               }
448               RELEASE_SPIN_LOCK(&static_objects_sync);
449                 /* I am assuming that static_objects pointers are not
450                  * written to other objects, and thus, no need to retag. */
451           }
452           return TAG_CLOSURE(tag,q);
453           
454       case CONSTR_NOCAF_STATIC:
455           /* no need to put these on the static linked list, they don't need
456            * to be scavenged.
457            */
458           return TAG_CLOSURE(tag,q);
459           
460       default:
461           barf("evacuate(static): strange closure type %d", (int)(info->type));
462       }
463   }
464
465   bd = Bdescr((P_)q);
466
467   if (bd->gen_no > N) {
468       /* Can't evacuate this object, because it's in a generation
469        * older than the ones we're collecting.  Let's hope that it's
470        * in gct->evac_gen or older, or we will have to arrange to track
471        * this pointer using the mutable list.
472        */
473       if (bd->gen_no < gct->evac_gen) {
474           // nope 
475           gct->failed_to_evac = rtsTrue;
476           TICK_GC_FAILED_PROMOTION();
477       }
478       return TAG_CLOSURE(tag,q);
479   }
480
481   if ((bd->flags & (BF_LARGE | BF_COMPACTED | BF_EVACUATED)) != 0) {
482
483       /* pointer into to-space: just return it.  This normally
484        * shouldn't happen, but alllowing it makes certain things
485        * slightly easier (eg. the mutable list can contain the same
486        * object twice, for example).
487        */
488       if (bd->flags & BF_EVACUATED) {
489           if (bd->gen_no < gct->evac_gen) {
490               gct->failed_to_evac = rtsTrue;
491               TICK_GC_FAILED_PROMOTION();
492           }
493           return TAG_CLOSURE(tag,q);
494       }
495
496       /* evacuate large objects by re-linking them onto a different list.
497        */
498       if (bd->flags & BF_LARGE) {
499           info = get_itbl(q);
500           if (info->type == TSO && 
501               ((StgTSO *)q)->what_next == ThreadRelocated) {
502               q = (StgClosure *)((StgTSO *)q)->link;
503               goto loop;
504           }
505           evacuate_large((P_)q);
506           return TAG_CLOSURE(tag,q);
507       }
508       
509       /* If the object is in a step that we're compacting, then we
510        * need to use an alternative evacuate procedure.
511        */
512       if (bd->flags & BF_COMPACTED) {
513           if (!is_marked((P_)q,bd)) {
514               mark((P_)q,bd);
515               if (mark_stack_full()) {
516                   mark_stack_overflowed = rtsTrue;
517                   reset_mark_stack();
518               }
519               push_mark_stack((P_)q);
520           }
521           return TAG_CLOSURE(tag,q);
522       }
523   }
524       
525   stp = bd->step->to;
526
527   info = get_itbl(q);
528   
529   switch (info->type) {
530
531   case WHITEHOLE:
532       goto loop;
533
534   case MUT_VAR_CLEAN:
535   case MUT_VAR_DIRTY:
536   case MVAR_CLEAN:
537   case MVAR_DIRTY:
538       return copy(q,sizeW_fromITBL(info),stp);
539
540   case CONSTR_0_1:
541   { 
542       StgWord w = (StgWord)q->payload[0];
543       if (q->header.info == Czh_con_info &&
544           // unsigned, so always true:  (StgChar)w >= MIN_CHARLIKE &&  
545           (StgChar)w <= MAX_CHARLIKE) {
546           return TAG_CLOSURE(tag,
547                              (StgClosure *)CHARLIKE_CLOSURE((StgChar)w)
548                              );
549       }
550       if (q->header.info == Izh_con_info &&
551           (StgInt)w >= MIN_INTLIKE && (StgInt)w <= MAX_INTLIKE) {
552           return TAG_CLOSURE(tag,
553                              (StgClosure *)INTLIKE_CLOSURE((StgInt)w)
554                              );
555       }
556       // else
557       return copy_noscav_tag(q,sizeofW(StgHeader)+1,stp,tag);
558   }
559
560   case FUN_0_1:
561   case FUN_1_0:
562   case CONSTR_1_0:
563     return copy_tag(q,sizeofW(StgHeader)+1,stp,tag);
564
565   case THUNK_1_0:
566   case THUNK_0_1:
567     return copy(q,sizeofW(StgThunk)+1,stp);
568
569   case THUNK_1_1:
570   case THUNK_2_0:
571   case THUNK_0_2:
572 #ifdef NO_PROMOTE_THUNKS
573     if (bd->gen_no == 0 && 
574         bd->step->no != 0 &&
575         bd->step->no == generations[bd->gen_no].n_steps-1) {
576       stp = bd->step;
577     }
578 #endif
579     return copy(q,sizeofW(StgThunk)+2,stp);
580
581   case FUN_1_1:
582   case FUN_2_0:
583   case FUN_0_2:
584   case CONSTR_1_1:
585   case CONSTR_2_0:
586     return copy_tag(q,sizeofW(StgHeader)+2,stp,tag);
587
588   case CONSTR_0_2:
589     return copy_noscav_tag(q,sizeofW(StgHeader)+2,stp,tag);
590
591   case THUNK:
592     return copy(q,thunk_sizeW_fromITBL(info),stp);
593
594   case FUN:
595   case IND_PERM:
596   case IND_OLDGEN_PERM:
597   case WEAK:
598   case STABLE_NAME:
599   case CONSTR:
600     return copy_tag(q,sizeW_fromITBL(info),stp,tag);
601
602   case BCO:
603     return copy(q,bco_sizeW((StgBCO *)q),stp);
604
605   case CAF_BLACKHOLE:
606   case SE_CAF_BLACKHOLE:
607   case SE_BLACKHOLE:
608   case BLACKHOLE:
609     return copyPart(q,BLACKHOLE_sizeW(),sizeofW(StgHeader),stp);
610
611   case THUNK_SELECTOR:
612     return eval_thunk_selector((StgSelector *)q, rtsTrue);
613
614   case IND:
615   case IND_OLDGEN:
616     // follow chains of indirections, don't evacuate them 
617     q = ((StgInd*)q)->indirectee;
618     goto loop;
619
620   case RET_BCO:
621   case RET_SMALL:
622   case RET_BIG:
623   case RET_DYN:
624   case UPDATE_FRAME:
625   case STOP_FRAME:
626   case CATCH_FRAME:
627   case CATCH_STM_FRAME:
628   case CATCH_RETRY_FRAME:
629   case ATOMICALLY_FRAME:
630     // shouldn't see these 
631     barf("evacuate: stack frame at %p\n", q);
632
633   case PAP:
634       return copy(q,pap_sizeW((StgPAP*)q),stp);
635
636   case AP:
637       return copy(q,ap_sizeW((StgAP*)q),stp);
638
639   case AP_STACK:
640       return copy(q,ap_stack_sizeW((StgAP_STACK*)q),stp);
641
642   case EVACUATED:
643     /* Already evacuated, just return the forwarding address.
644      * HOWEVER: if the requested destination generation (gct->evac_gen) is
645      * older than the actual generation (because the object was
646      * already evacuated to a younger generation) then we have to
647      * set the gct->failed_to_evac flag to indicate that we couldn't 
648      * manage to promote the object to the desired generation.
649      */
650     /* 
651      * Optimisation: the check is fairly expensive, but we can often
652      * shortcut it if either the required generation is 0, or the
653      * current object (the EVACUATED) is in a high enough generation.
654      * We know that an EVACUATED always points to an object in the
655      * same or an older generation.  stp is the lowest step that the
656      * current object would be evacuated to, so we only do the full
657      * check if stp is too low.
658      */
659     if (gct->evac_gen > 0 && stp->gen_no < gct->evac_gen) {  // optimisation 
660       StgClosure *p = ((StgEvacuated*)q)->evacuee;
661       if (HEAP_ALLOCED(p) && Bdescr((P_)p)->gen_no < gct->evac_gen) {
662         gct->failed_to_evac = rtsTrue;
663         TICK_GC_FAILED_PROMOTION();
664       }
665     }
666     return ((StgEvacuated*)q)->evacuee;
667
668   case ARR_WORDS:
669       // just copy the block 
670       return copy_noscav(q,arr_words_sizeW((StgArrWords *)q),stp);
671
672   case MUT_ARR_PTRS_CLEAN:
673   case MUT_ARR_PTRS_DIRTY:
674   case MUT_ARR_PTRS_FROZEN:
675   case MUT_ARR_PTRS_FROZEN0:
676       // just copy the block 
677       return copy(q,mut_arr_ptrs_sizeW((StgMutArrPtrs *)q),stp);
678
679   case TSO:
680     {
681       StgTSO *tso = (StgTSO *)q;
682
683       /* Deal with redirected TSOs (a TSO that's had its stack enlarged).
684        */
685       if (tso->what_next == ThreadRelocated) {
686         q = (StgClosure *)tso->link;
687         goto loop;
688       }
689
690       /* To evacuate a small TSO, we need to relocate the update frame
691        * list it contains.  
692        */
693       {
694           StgTSO *new_tso;
695           StgPtr p, q;
696
697           new_tso = (StgTSO *)copyPart((StgClosure *)tso,
698                                        tso_sizeW(tso),
699                                        sizeofW(StgTSO), stp);
700           move_TSO(tso, new_tso);
701           for (p = tso->sp, q = new_tso->sp;
702                p < tso->stack+tso->stack_size;) {
703               *q++ = *p++;
704           }
705           
706           return (StgClosure *)new_tso;
707       }
708     }
709
710   case TREC_HEADER: 
711     return copy(q,sizeofW(StgTRecHeader),stp);
712
713   case TVAR_WATCH_QUEUE:
714     return copy(q,sizeofW(StgTVarWatchQueue),stp);
715
716   case TVAR:
717     return copy(q,sizeofW(StgTVar),stp);
718     
719   case TREC_CHUNK:
720     return copy(q,sizeofW(StgTRecChunk),stp);
721
722   case ATOMIC_INVARIANT:
723     return copy(q,sizeofW(StgAtomicInvariant),stp);
724
725   case INVARIANT_CHECK_QUEUE:
726     return copy(q,sizeofW(StgInvariantCheckQueue),stp);
727
728   default:
729     barf("evacuate: strange closure type %d", (int)(info->type));
730   }
731
732   barf("evacuate");
733 }
734
735 static void
736 unchain_thunk_selectors(StgSelector *p, StgClosure *val)
737 {
738     StgSelector *prev;
739
740     prev = NULL;
741     while (p)
742     {
743         ASSERT(p->header.info == &stg_BLACKHOLE_info);
744         prev = (StgSelector*)((StgClosure *)p)->payload[0];
745
746         // Update the THUNK_SELECTOR with an indirection to the
747         // EVACUATED closure now at p.  Why do this rather than
748         // upd_evacuee(q,p)?  Because we have an invariant that an
749         // EVACUATED closure always points to an object in the
750         // same or an older generation (required by the short-cut
751         // test in the EVACUATED case, below).
752         SET_INFO(p, &stg_IND_info);
753         ((StgInd *)p)->indirectee = val;
754
755         // For the purposes of LDV profiling, we have created an
756         // indirection.
757         LDV_RECORD_CREATE(p);
758
759         p = prev;
760     }
761 }
762
763 /* -----------------------------------------------------------------------------
764    Evaluate a THUNK_SELECTOR if possible.
765
766    p points to a THUNK_SELECTOR that we want to evaluate.  The
767    result of "evaluating" it will be evacuated and a pointer to the
768    to-space closure will be returned.
769
770    If the THUNK_SELECTOR could not be evaluated (its selectee is still
771    a THUNK, for example), then the THUNK_SELECTOR itself will be
772    evacuated.
773    -------------------------------------------------------------------------- */
774
775 static StgClosure *
776 eval_thunk_selector (StgSelector * p, rtsBool evac)
777 {
778     nat field;
779     StgInfoTable *info;
780     const StgInfoTable *info_ptr;
781     StgClosure *selectee;
782     StgSelector *prev_thunk_selector;
783     bdescr *bd;
784     StgClosure *val;
785     
786     prev_thunk_selector = NULL;
787     // this is a chain of THUNK_SELECTORs that we are going to update
788     // to point to the value of the current THUNK_SELECTOR.  Each
789     // closure on the chain is a BLACKHOLE, and points to the next in the
790     // chain with payload[0].
791
792 selector_chain:
793
794     // The selectee might be a constructor closure,
795     // so we untag the pointer.
796     selectee = UNTAG_CLOSURE(p->selectee);
797
798     // Save the real info pointer (NOTE: not the same as get_itbl()).
799     info_ptr = p->header.info;
800     field = get_itbl(p)->layout.selector_offset;
801
802     bd = Bdescr((StgPtr)p);
803     if (HEAP_ALLOCED(p)) {
804         // If the THUNK_SELECTOR is in to-space or in a generation that we
805         // are not collecting, then bale out early.  We won't be able to
806         // save any space in any case, and updating with an indirection is
807         // trickier in a non-collected gen: we would have to update the
808         // mutable list.
809         if ((bd->gen_no > N) || (bd->flags & BF_EVACUATED)) {
810             unchain_thunk_selectors(prev_thunk_selector, (StgClosure *)p);
811             return (StgClosure *)p;
812         }
813         // we don't update THUNK_SELECTORS in the compacted
814         // generation, because compaction does not remove the INDs
815         // that result, this causes confusion later
816         // (scavenge_mark_stack doesn't deal with IND).  BEWARE!  This
817         // bit is very tricky to get right.  If you make changes
818         // around here, test by compiling stage 3 with +RTS -c -RTS.
819         if (bd->flags & BF_COMPACTED) {
820             // must call evacuate() to mark this closure if evac==rtsTrue
821             if (evac) p = (StgSelector *)evacuate((StgClosure *)p);
822             unchain_thunk_selectors(prev_thunk_selector, (StgClosure *)p);
823             return (StgClosure *)p;
824         }
825     }
826
827     // BLACKHOLE the selector thunk, since it is now under evaluation.
828     // This is important to stop us going into an infinite loop if
829     // this selector thunk eventually refers to itself.
830     SET_INFO(p,&stg_BLACKHOLE_info);
831
832 selector_loop:
833     // selectee now points to the closure that we're trying to select
834     // a field from.  It may or may not be in to-space: we try not to
835     // end up in to-space, but it's impractical to avoid it in
836     // general.  The compacting GC scatters to-space pointers in
837     // from-space during marking, for example.  We rely on the property
838     // that evacuate() doesn't mind if it gets passed a to-space pointer.
839
840     info = get_itbl(selectee);
841     switch (info->type) {
842       case CONSTR:
843       case CONSTR_1_0:
844       case CONSTR_0_1:
845       case CONSTR_2_0:
846       case CONSTR_1_1:
847       case CONSTR_0_2:
848       case CONSTR_STATIC:
849       case CONSTR_NOCAF_STATIC:
850           {
851               // check that the size is in range 
852               ASSERT(field <  (StgWord32)(info->layout.payload.ptrs + 
853                                           info->layout.payload.nptrs));
854           
855               // Select the right field from the constructor
856               val = selectee->payload[field];
857               
858 #ifdef PROFILING
859               // For the purposes of LDV profiling, we have destroyed
860               // the original selector thunk, p.
861               SET_INFO(p, info_ptr);
862               LDV_RECORD_DEAD_FILL_SLOP_DYNAMIC((StgClosure *)p);
863               SET_INFO(p, &stg_BLACKHOLE_info);
864 #endif
865
866               // the closure in val is now the "value" of the
867               // THUNK_SELECTOR in p.  However, val may itself be a
868               // THUNK_SELECTOR, in which case we want to continue
869               // evaluating until we find the real value, and then
870               // update the whole chain to point to the value.
871           val_loop:
872               info = get_itbl(UNTAG_CLOSURE(val));
873               switch (info->type) {
874               case IND:
875               case IND_PERM:
876               case IND_OLDGEN:
877               case IND_OLDGEN_PERM:
878               case IND_STATIC:
879                   val = ((StgInd *)val)->indirectee;
880                   goto val_loop;
881               case THUNK_SELECTOR:
882                   ((StgClosure*)p)->payload[0] = (StgClosure *)prev_thunk_selector;
883                   prev_thunk_selector = p;
884                   p = (StgSelector*)val;
885                   goto selector_chain;
886               default:
887                   ((StgClosure*)p)->payload[0] = (StgClosure *)prev_thunk_selector;
888                   prev_thunk_selector = p;
889
890                   if (evac) val = evacuate(val);
891                   // evacuate() cannot recurse through
892                   // eval_thunk_selector(), because we know val is not
893                   // a THUNK_SELECTOR.
894                   unchain_thunk_selectors(prev_thunk_selector, val);
895                   return val;
896               }
897           }
898
899       case IND:
900       case IND_PERM:
901       case IND_OLDGEN:
902       case IND_OLDGEN_PERM:
903       case IND_STATIC:
904           // Again, we might need to untag a constructor.
905           selectee = UNTAG_CLOSURE( ((StgInd *)selectee)->indirectee );
906           goto selector_loop;
907
908       case EVACUATED:
909           // We don't follow pointers into to-space; the constructor
910           // has already been evacuated, so we won't save any space
911           // leaks by evaluating this selector thunk anyhow.
912           goto bale_out;
913
914       case THUNK_SELECTOR:
915       {
916           StgClosure *val;
917
918           // recursively evaluate this selector.  We don't want to
919           // recurse indefinitely, so we impose a depth bound.
920           if (gct->thunk_selector_depth >= MAX_THUNK_SELECTOR_DEPTH) {
921               goto bale_out;
922           }
923
924           gct->thunk_selector_depth++;
925           // rtsFalse says "don't evacuate the result".  It will,
926           // however, update any THUNK_SELECTORs that are evaluated
927           // along the way.
928           val = eval_thunk_selector((StgSelector *)selectee, rtsFalse);
929           gct->thunk_selector_depth--;
930
931           // did we actually manage to evaluate it?
932           if (val == selectee) goto bale_out;
933
934           // Of course this pointer might be tagged...
935           selectee = UNTAG_CLOSURE(val);
936           goto selector_loop;
937       }
938
939       case AP:
940       case AP_STACK:
941       case THUNK:
942       case THUNK_1_0:
943       case THUNK_0_1:
944       case THUNK_2_0:
945       case THUNK_1_1:
946       case THUNK_0_2:
947       case THUNK_STATIC:
948       case CAF_BLACKHOLE:
949       case SE_CAF_BLACKHOLE:
950       case SE_BLACKHOLE:
951       case BLACKHOLE:
952           // not evaluated yet 
953           goto bale_out;
954     
955       default:
956         barf("eval_thunk_selector: strange selectee %d",
957              (int)(info->type));
958     }
959
960 bale_out:
961     // We didn't manage to evaluate this thunk; restore the old info
962     // pointer.  But don't forget: we still need to evacuate the thunk itself.
963     SET_INFO(p, info_ptr);
964     if (evac) {
965         val = copy((StgClosure *)p,THUNK_SELECTOR_sizeW(),bd->step->to);
966     } else {
967         val = (StgClosure *)p;
968     }
969     unchain_thunk_selectors(prev_thunk_selector, val);
970     return val;
971 }
972
973 /* -----------------------------------------------------------------------------
974    move_TSO is called to update the TSO structure after it has been
975    moved from one place to another.
976    -------------------------------------------------------------------------- */
977
978 void
979 move_TSO (StgTSO *src, StgTSO *dest)
980 {
981     ptrdiff_t diff;
982
983     // relocate the stack pointer... 
984     diff = (StgPtr)dest - (StgPtr)src; // In *words* 
985     dest->sp = (StgPtr)dest->sp + diff;
986 }
987