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