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