fix an assertion
[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 void eval_thunk_selector (StgClosure **q, StgSelector * p, rtsBool);
29 STATIC_INLINE void evacuate_large(StgPtr p);
30
31 /* -----------------------------------------------------------------------------
32    Allocate some space in which to copy an object.
33    -------------------------------------------------------------------------- */
34
35 STATIC_INLINE StgPtr
36 alloc_for_copy (nat size, step *stp)
37 {
38     StgPtr to;
39     step_workspace *ws;
40
41     /* Find out where we're going, using the handy "to" pointer in 
42      * the step of the source object.  If it turns out we need to
43      * evacuate to an older generation, adjust it here (see comment
44      * by evacuate()).
45      */
46     if (stp < gct->evac_step) {
47         if (gct->eager_promotion) {
48             stp = gct->evac_step;
49         } else {
50             gct->failed_to_evac = rtsTrue;
51         }
52     }
53     
54     ws = &gct->steps[stp->gen_no][stp->no];
55     
56     /* chain a new block onto the to-space for the destination step if
57      * necessary.
58      */
59     
60     ASSERT(ws->todo_free >= ws->todo_bd->free && ws->todo_free <= ws->todo_lim);
61     to = ws->todo_free;
62     if (to + size >= ws->todo_lim) {
63         to = gc_alloc_todo_block(ws);
64     }
65     ws->todo_free = to + size;
66     ASSERT(ws->todo_free >= ws->todo_bd->free && ws->todo_free <= ws->todo_lim);
67
68     return to;
69 }
70
71 /* -----------------------------------------------------------------------------
72    The evacuate() code
73    -------------------------------------------------------------------------- */
74
75 #define MINOR_GC
76 #include "Evac.c-inc"
77
78 #undef MINOR_GC
79 #include "Evac.c-inc"
80
81 /* -----------------------------------------------------------------------------
82    Evacuate a large object
83
84    This just consists of removing the object from the (doubly-linked)
85    step->large_objects list, and linking it on to the (singly-linked)
86    step->new_large_objects list, from where it will be scavenged later.
87
88    Convention: bd->flags has BF_EVACUATED set for a large object
89    that has been evacuated, or unset otherwise.
90    -------------------------------------------------------------------------- */
91
92 STATIC_INLINE void
93 evacuate_large(StgPtr p)
94 {
95   bdescr *bd = Bdescr(p);
96   step *stp;
97   step_workspace *ws;
98
99   // object must be at the beginning of the block (or be a ByteArray)
100   ASSERT(get_itbl((StgClosure *)p)->type == ARR_WORDS ||
101          (((W_)p & BLOCK_MASK) == 0));
102
103   // already evacuated? 
104   if (bd->flags & BF_EVACUATED) { 
105     /* Don't forget to set the gct->failed_to_evac flag if we didn't get
106      * the desired destination (see comments in evacuate()).
107      */
108     if (bd->step < gct->evac_step) {
109       gct->failed_to_evac = rtsTrue;
110       TICK_GC_FAILED_PROMOTION();
111     }
112     return;
113   }
114
115   stp = bd->step;
116
117   ACQUIRE_SPIN_LOCK(&stp->sync_large_objects);
118   // remove from large_object list 
119   if (bd->u.back) {
120     bd->u.back->link = bd->link;
121   } else { // first object in the list 
122     stp->large_objects = bd->link;
123   }
124   if (bd->link) {
125     bd->link->u.back = bd->u.back;
126   }
127   RELEASE_SPIN_LOCK(&stp->sync_large_objects);
128   
129   /* link it on to the evacuated large object list of the destination step
130    */
131   stp = bd->step->to;
132   if (stp < gct->evac_step) {
133       if (gct->eager_promotion) {
134           stp = gct->evac_step;
135       } else {
136           gct->failed_to_evac = rtsTrue;
137       }
138   }
139
140   ws = &gct->steps[stp->gen_no][stp->no];
141   bd->step = stp;
142   bd->gen_no = stp->gen_no;
143   bd->link = ws->todo_large_objects;
144   ws->todo_large_objects = bd;
145   bd->flags |= BF_EVACUATED;
146 }
147
148 /* -----------------------------------------------------------------------------
149    Evaluate a THUNK_SELECTOR if possible.
150
151    p points to a THUNK_SELECTOR that we want to evaluate.  The
152    result of "evaluating" it will be evacuated and a pointer to the
153    to-space closure will be returned.
154
155    If the THUNK_SELECTOR could not be evaluated (its selectee is still
156    a THUNK, for example), then the THUNK_SELECTOR itself will be
157    evacuated.
158    -------------------------------------------------------------------------- */
159 static void
160 unchain_thunk_selectors(StgSelector *p, StgClosure *val)
161 {
162     StgSelector *prev;
163
164     prev = NULL;
165     while (p)
166     {
167 #ifdef THREADED_RTS
168         ASSERT(p->header.info == &stg_WHITEHOLE_info);
169 #else
170         ASSERT(p->header.info == &stg_BLACKHOLE_info);
171 #endif
172         // val must be in to-space.
173         ASSERT(!HEAP_ALLOCED(val) || Bdescr((P_)val)->gen_no > N || (Bdescr((P_)val)->flags & BF_EVACUATED));
174
175         prev = (StgSelector*)((StgClosure *)p)->payload[0];
176
177         // Update the THUNK_SELECTOR with an indirection to the
178         // EVACUATED closure now at p.  Why do this rather than
179         // upd_evacuee(q,p)?  Because we have an invariant that an
180         // EVACUATED closure always points to an object in the
181         // same or an older generation (required by the short-cut
182         // test in the EVACUATED case, below).
183         ((StgInd *)p)->indirectee = val;
184         write_barrier();
185         SET_INFO(p, &stg_IND_info);
186
187         // For the purposes of LDV profiling, we have created an
188         // indirection.
189         LDV_RECORD_CREATE(p);
190
191         p = prev;
192     }
193 }
194
195 static void
196 eval_thunk_selector (StgClosure **q, StgSelector * p, rtsBool evac)
197                  // NB. for legacy reasons, p & q are swapped around :(
198 {
199     nat field;
200     StgInfoTable *info;
201     StgWord info_ptr;
202     StgClosure *selectee;
203     StgSelector *prev_thunk_selector;
204     bdescr *bd;
205     StgClosure *val;
206     
207     prev_thunk_selector = NULL;
208     // this is a chain of THUNK_SELECTORs that we are going to update
209     // to point to the value of the current THUNK_SELECTOR.  Each
210     // closure on the chain is a BLACKHOLE, and points to the next in the
211     // chain with payload[0].
212
213 selector_chain:
214
215     bd = Bdescr((StgPtr)p);
216     if (HEAP_ALLOCED(p)) {
217         // If the THUNK_SELECTOR is in to-space or in a generation that we
218         // are not collecting, then bale out early.  We won't be able to
219         // save any space in any case, and updating with an indirection is
220         // trickier in a non-collected gen: we would have to update the
221         // mutable list.
222         if ((bd->gen_no > N) || (bd->flags & BF_EVACUATED)) {
223             unchain_thunk_selectors(prev_thunk_selector, (StgClosure *)p);
224             *q = (StgClosure *)p;
225             return;
226         }
227         // we don't update THUNK_SELECTORS in the compacted
228         // generation, because compaction does not remove the INDs
229         // that result, this causes confusion later
230         // (scavenge_mark_stack doesn't deal with IND).  BEWARE!  This
231         // bit is very tricky to get right.  If you make changes
232         // around here, test by compiling stage 3 with +RTS -c -RTS.
233         if (bd->flags & BF_COMPACTED) {
234             // must call evacuate() to mark this closure if evac==rtsTrue
235             *q = (StgClosure *)p;
236             if (evac) evacuate(q);
237             unchain_thunk_selectors(prev_thunk_selector, (StgClosure *)p);
238             return;
239         }
240     }
241
242
243     // BLACKHOLE the selector thunk, since it is now under evaluation.
244     // This is important to stop us going into an infinite loop if
245     // this selector thunk eventually refers to itself.
246 #if defined(THREADED_RTS)
247     // In threaded mode, we'll use WHITEHOLE to lock the selector
248     // thunk while we evaluate it.
249     {
250         do {
251             info_ptr = xchg((StgPtr)&p->header.info, (W_)&stg_WHITEHOLE_info);
252         } while (info_ptr == (W_)&stg_WHITEHOLE_info);
253
254         // make sure someone else didn't get here first...
255         if (INFO_PTR_TO_STRUCT(info_ptr)->type != THUNK_SELECTOR) {
256             // v. tricky now.  The THUNK_SELECTOR has been evacuated
257             // by another thread, and is now either EVACUATED or IND.
258             // We need to extract ourselves from the current situation
259             // as cleanly as possible.
260             //   - unlock the closure
261             //   - update *q, we may have done *some* evaluation
262             //   - if evac, we need to call evacuate(), because we
263             //     need the write-barrier stuff.
264             //   - undo the chain we've built to point to p.
265             SET_INFO(p, (const StgInfoTable *)info_ptr);
266             *q = (StgClosure *)p;
267             if (evac) evacuate(q);
268             unchain_thunk_selectors(prev_thunk_selector, (StgClosure *)p);
269             return;
270         }
271     }
272 #else
273     // Save the real info pointer (NOTE: not the same as get_itbl()).
274     info_ptr = (StgWord)p->header.info;
275     SET_INFO(p,&stg_BLACKHOLE_info);
276 #endif
277
278     field = INFO_PTR_TO_STRUCT(info_ptr)->layout.selector_offset;
279
280     // The selectee might be a constructor closure,
281     // so we untag the pointer.
282     selectee = UNTAG_CLOSURE(p->selectee);
283
284 selector_loop:
285     // selectee now points to the closure that we're trying to select
286     // a field from.  It may or may not be in to-space: we try not to
287     // end up in to-space, but it's impractical to avoid it in
288     // general.  The compacting GC scatters to-space pointers in
289     // from-space during marking, for example.  We rely on the property
290     // that evacuate() doesn't mind if it gets passed a to-space pointer.
291
292     info = get_itbl(selectee);
293     switch (info->type) {
294       case WHITEHOLE:
295           goto bale_out; // about to be evacuated by another thread (or a loop).
296         
297       case CONSTR:
298       case CONSTR_1_0:
299       case CONSTR_0_1:
300       case CONSTR_2_0:
301       case CONSTR_1_1:
302       case CONSTR_0_2:
303       case CONSTR_STATIC:
304       case CONSTR_NOCAF_STATIC:
305           {
306               // check that the size is in range 
307               ASSERT(field <  (StgWord32)(info->layout.payload.ptrs + 
308                                           info->layout.payload.nptrs));
309           
310               // Select the right field from the constructor
311               val = selectee->payload[field];
312               
313 #ifdef PROFILING
314               // For the purposes of LDV profiling, we have destroyed
315               // the original selector thunk, p.
316               SET_INFO(p, (StgInfoTable *)info_ptr);
317               LDV_RECORD_DEAD_FILL_SLOP_DYNAMIC((StgClosure *)p);
318               SET_INFO(p, &stg_BLACKHOLE_info);
319 #endif
320
321               // the closure in val is now the "value" of the
322               // THUNK_SELECTOR in p.  However, val may itself be a
323               // THUNK_SELECTOR, in which case we want to continue
324               // evaluating until we find the real value, and then
325               // update the whole chain to point to the value.
326           val_loop:
327               info = get_itbl(UNTAG_CLOSURE(val));
328               switch (info->type) {
329               case IND:
330               case IND_PERM:
331               case IND_OLDGEN:
332               case IND_OLDGEN_PERM:
333               case IND_STATIC:
334                   val = ((StgInd *)val)->indirectee;
335                   goto val_loop;
336               case THUNK_SELECTOR:
337                   ((StgClosure*)p)->payload[0] = (StgClosure *)prev_thunk_selector;
338                   prev_thunk_selector = p;
339                   p = (StgSelector*)val;
340                   goto selector_chain;
341               default:
342                   ((StgClosure*)p)->payload[0] = (StgClosure *)prev_thunk_selector;
343                   prev_thunk_selector = p;
344
345                   *q = val;
346                   if (evac) evacuate(q);
347                   val = *q;
348                   // evacuate() cannot recurse through
349                   // eval_thunk_selector(), because we know val is not
350                   // a THUNK_SELECTOR.
351                   unchain_thunk_selectors(prev_thunk_selector, val);
352                   return;
353               }
354           }
355
356       case IND:
357       case IND_PERM:
358       case IND_OLDGEN:
359       case IND_OLDGEN_PERM:
360       case IND_STATIC:
361           // Again, we might need to untag a constructor.
362           selectee = UNTAG_CLOSURE( ((StgInd *)selectee)->indirectee );
363           goto selector_loop;
364
365       case EVACUATED:
366           // We don't follow pointers into to-space; the constructor
367           // has already been evacuated, so we won't save any space
368           // leaks by evaluating this selector thunk anyhow.
369           goto bale_out;
370
371       case THUNK_SELECTOR:
372       {
373           StgClosure *val;
374
375           // recursively evaluate this selector.  We don't want to
376           // recurse indefinitely, so we impose a depth bound.
377           if (gct->thunk_selector_depth >= MAX_THUNK_SELECTOR_DEPTH) {
378               goto bale_out;
379           }
380
381           gct->thunk_selector_depth++;
382           // rtsFalse says "don't evacuate the result".  It will,
383           // however, update any THUNK_SELECTORs that are evaluated
384           // along the way.
385           eval_thunk_selector(&val, (StgSelector*)selectee, rtsFalse);
386           gct->thunk_selector_depth--;
387
388           // did we actually manage to evaluate it?
389           if (val == selectee) goto bale_out;
390
391           // Of course this pointer might be tagged...
392           selectee = UNTAG_CLOSURE(val);
393           goto selector_loop;
394       }
395
396       case AP:
397       case AP_STACK:
398       case THUNK:
399       case THUNK_1_0:
400       case THUNK_0_1:
401       case THUNK_2_0:
402       case THUNK_1_1:
403       case THUNK_0_2:
404       case THUNK_STATIC:
405       case CAF_BLACKHOLE:
406       case SE_CAF_BLACKHOLE:
407       case SE_BLACKHOLE:
408       case BLACKHOLE:
409           // not evaluated yet 
410           goto bale_out;
411     
412       default:
413         barf("eval_thunk_selector: strange selectee %d",
414              (int)(info->type));
415     }
416
417 bale_out:
418     // We didn't manage to evaluate this thunk; restore the old info
419     // pointer.  But don't forget: we still need to evacuate the thunk itself.
420     SET_INFO(p, (const StgInfoTable *)info_ptr);
421     // THREADED_RTS: we just unlocked the thunk, so another thread
422     // might get in and update it.  copy() will lock it again and
423     // check whether it was updated in the meantime.
424     *q = (StgClosure *)p;
425     if (evac) {
426         copy(q,(StgClosure *)p,THUNK_SELECTOR_sizeW(),bd->step->to);
427     }
428     unchain_thunk_selectors(prev_thunk_selector, *q);
429     return;
430 }
431
432 /* -----------------------------------------------------------------------------
433    move_TSO is called to update the TSO structure after it has been
434    moved from one place to another.
435    -------------------------------------------------------------------------- */
436
437 void
438 move_TSO (StgTSO *src, StgTSO *dest)
439 {
440     ptrdiff_t diff;
441
442     // relocate the stack pointer... 
443     diff = (StgPtr)dest - (StgPtr)src; // In *words* 
444     dest->sp = (StgPtr)dest->sp + diff;
445 }
446