[project @ 2002-07-18 09:12:34 by simonmar]
[ghc-hetmet.git] / ghc / rts / ProfHeap.c
1 /* -----------------------------------------------------------------------------
2  * $Id: ProfHeap.c,v 1.37 2002/07/18 09:12:34 simonmar Exp $
3  *
4  * (c) The GHC Team, 1998-2000
5  *
6  * Support for heap profiling
7  *
8  * ---------------------------------------------------------------------------*/
9
10 #if defined(DEBUG) && !defined(PROFILING)
11 #define DEBUG_HEAP_PROF
12 #else
13 #undef DEBUG_HEAP_PROF
14 #endif
15
16 #if defined(PROFILING) || defined(DEBUG_HEAP_PROF)
17
18 #include "PosixSource.h"
19 #include "Rts.h"
20 #include "RtsUtils.h"
21 #include "RtsFlags.h"
22 #include "Profiling.h"
23 #include "Storage.h"
24 #include "ProfHeap.h"
25 #include "Stats.h"
26 #include "Hash.h"
27 #include "StrHash.h"
28 #include "RetainerProfile.h"
29 #include "LdvProfile.h"
30 #include "Arena.h"
31 #include "Printer.h"
32
33 #include <string.h>
34
35 /* -----------------------------------------------------------------------------
36  * era stores the current time period.  It is the same as the
37  * number of censuses that have been performed.
38  *
39  * RESTRICTION:
40  *   era must be no longer than LDV_SHIFT (15 or 30) bits.
41  * Invariants:
42  *   era is initialized to 1 in initHeapProfiling().
43  *
44  * max_era is initialized to 2^LDV_SHIFT in initHeapProfiling().
45  * When era reaches max_era, the profiling stops because a closure can
46  * store only up to (max_era - 1) as its creation or last use time.
47  * -------------------------------------------------------------------------- */
48 nat era;
49 static nat max_era;
50
51 /* -----------------------------------------------------------------------------
52  * Counters
53  *
54  * For most heap profiles each closure identity gets a simple count
55  * of live words in the heap at each census.  However, if we're
56  * selecting by biography, then we have to keep the various
57  * lag/drag/void counters for each identity.
58  * -------------------------------------------------------------------------- */
59 typedef struct _counter {
60     void *identity;
61     union {
62         nat resid;
63         struct {
64             int prim;     // total size of 'inherently used' closures
65             int not_used; // total size of 'never used' closures
66             int used;     // total size of 'used at least once' closures
67             int void_total;  // current total size of 'destroyed without being used' closures
68             int drag_total;  // current total size of 'used at least once and waiting to die'
69         } ldv;
70     } c;
71     struct _counter *next;
72 } counter;
73
74 static inline void
75 initLDVCtr( counter *ctr )
76 {
77     ctr->c.ldv.prim = 0;
78     ctr->c.ldv.not_used = 0;
79     ctr->c.ldv.used = 0;
80     ctr->c.ldv.void_total = 0;
81     ctr->c.ldv.drag_total = 0;
82 }
83
84 typedef struct {
85     double      time;    // the time in MUT time when the census is made
86     HashTable * hash;
87     counter   * ctrs;
88     Arena     * arena;
89
90     // for LDV profiling, when just displaying by LDV
91     int       prim;
92     int       not_used;
93     int       used;
94     int       void_total;
95     int       drag_total;
96 } Census;
97
98 Census *censuses = NULL;
99 nat n_censuses = 0;
100
101 #ifdef PROFILING
102 static void aggregateCensusInfo( void );
103 #endif
104
105 static void dumpCensus( Census *census );
106
107 /* -----------------------------------------------------------------------------
108    Closure Type Profiling;
109
110    PROBABLY TOTALLY OUT OF DATE -- ToDo (SDM)
111    -------------------------------------------------------------------------- */
112
113 #ifdef DEBUG_HEAP_PROF
114 static char *type_names[] = {
115       "INVALID_OBJECT"
116     , "CONSTR"
117     , "CONSTR_INTLIKE"
118     , "CONSTR_CHARLIKE"
119     , "CONSTR_STATIC"
120     , "CONSTR_NOCAF_STATIC"
121
122     , "FUN"
123     , "FUN_STATIC"
124
125     , "THUNK"
126     , "THUNK_STATIC"
127     , "THUNK_SELECTOR"
128
129     , "BCO"
130     , "AP_UPD"
131
132     , "PAP"
133
134     , "IND"
135     , "IND_OLDGEN"
136     , "IND_PERM"
137     , "IND_OLDGEN_PERM"
138     , "IND_STATIC"
139
140     , "RET_BCO"
141     , "RET_SMALL"
142     , "RET_VEC_SMALL"
143     , "RET_BIG"
144     , "RET_VEC_BIG"
145     , "RET_DYN"
146     , "UPDATE_FRAME"
147     , "CATCH_FRAME"
148     , "STOP_FRAME"
149     , "SEQ_FRAME"
150
151     , "BLACKHOLE"
152     , "BLACKHOLE_BQ"
153     , "MVAR"
154
155     , "ARR_WORDS"
156
157     , "MUT_ARR_PTRS"
158     , "MUT_ARR_PTRS_FROZEN"
159     , "MUT_VAR"
160
161     , "WEAK"
162     , "FOREIGN"
163   
164     , "TSO"
165
166     , "BLOCKED_FETCH"
167     , "FETCH_ME"
168
169     , "EVACUATED"
170 };
171
172 #endif /* DEBUG_HEAP_PROF */
173
174 /* -----------------------------------------------------------------------------
175  * Find the "closure identity", which is a unique pointer reresenting
176  * the band to which this closure's heap space is attributed in the
177  * heap profile.
178  * ------------------------------------------------------------------------- */
179 static inline void *
180 closureIdentity( StgClosure *p )
181 {
182     switch (RtsFlags.ProfFlags.doHeapProfile) {
183
184 #ifdef PROFILING
185     case HEAP_BY_CCS:
186         return p->header.prof.ccs;
187     case HEAP_BY_MOD:
188         return p->header.prof.ccs->cc->module;
189     case HEAP_BY_DESCR:
190         return get_itbl(p)->prof.closure_desc;
191     case HEAP_BY_TYPE:
192         return get_itbl(p)->prof.closure_type;
193     case HEAP_BY_RETAINER:
194         // AFAIK, the only closures in the heap which might not have a
195         // valid retainer set are DEAD_WEAK closures.
196         if (isRetainerSetFieldValid(p))
197             return retainerSetOf(p);
198         else
199             return NULL;
200
201 #else // DEBUG
202     case HEAP_BY_INFOPTR:
203         return (void *)((StgClosure *)p)->header.info; 
204     case HEAP_BY_CLOSURE_TYPE:
205         return type_names[get_itbl(p)->type];
206
207 #endif
208     default:
209         barf("closureIdentity");
210     }
211 }
212
213 /* --------------------------------------------------------------------------
214  * Profiling type predicates
215  * ----------------------------------------------------------------------- */
216 #ifdef PROFILING
217 static inline rtsBool
218 doingLDVProfiling( void )
219 {
220     return (RtsFlags.ProfFlags.doHeapProfile == HEAP_BY_LDV 
221             || RtsFlags.ProfFlags.bioSelector != NULL);
222 }
223
224 static inline rtsBool
225 doingRetainerProfiling( void )
226 {
227     return (RtsFlags.ProfFlags.doHeapProfile == HEAP_BY_RETAINER
228             || RtsFlags.ProfFlags.retainerSelector != NULL);
229 }
230 #endif // PROFILING
231
232 // Precesses a closure 'c' being destroyed whose size is 'size'.
233 // Make sure that LDV_recordDead() is not invoked on 'inherently used' closures
234 // such as TSO; they should not be involved in computing dragNew or voidNew.
235 // 
236 // Even though era is checked in both LdvCensusForDead() and 
237 // LdvCensusKillAll(), we still need to make sure that era is > 0 because 
238 // LDV_recordDead() may be called from elsewhere in the runtime system. E.g., 
239 // when a thunk is replaced by an indirection object.
240
241 #ifdef PROFILING
242 void
243 LDV_recordDead( StgClosure *c, nat size )
244 {
245     void *id;
246     nat t;
247     counter *ctr;
248
249     if (era > 0 && closureSatisfiesConstraints(c)) {
250         size -= sizeofW(StgProfHeader);
251         if ((LDVW((c)) & LDV_STATE_MASK) == LDV_STATE_CREATE) {
252             t = (LDVW((c)) & LDV_CREATE_MASK) >> LDV_SHIFT;
253             if (t < era) {
254                 if (RtsFlags.ProfFlags.bioSelector == NULL) {
255                     censuses[t].void_total   += (int)size;
256                     censuses[era].void_total -= (int)size;
257                 } else {
258                     id = closureIdentity(c);
259                     ctr = lookupHashTable(censuses[t].hash, (StgWord)id);
260                     ASSERT( ctr != NULL );
261                     ctr->c.ldv.void_total += (int)size;
262                     ctr = lookupHashTable(censuses[era].hash, (StgWord)id);
263                     if (ctr == NULL) {
264                         ctr = arenaAlloc(censuses[era].arena, sizeof(counter));
265                         initLDVCtr(ctr);
266                         insertHashTable(censuses[era].hash, (StgWord)id, ctr);
267                         ctr->identity = id;
268                         ctr->next = censuses[era].ctrs;
269                         censuses[era].ctrs = ctr;
270                     }
271                     ctr->c.ldv.void_total -= (int)size;
272                 }
273             }
274         } else {
275             t = LDVW((c)) & LDV_LAST_MASK;
276             if (t + 1 < era) {
277                 if (RtsFlags.ProfFlags.bioSelector == NULL) {
278                     censuses[t+1].drag_total += size;
279                     censuses[era].drag_total -= size;
280                 } else {
281                     void *id;
282                     id = closureIdentity(c);
283                     ctr = lookupHashTable(censuses[t+1].hash, (StgWord)id);
284                     ASSERT( ctr != NULL );
285                     ctr->c.ldv.drag_total += (int)size;
286                     ctr = lookupHashTable(censuses[era].hash, (StgWord)id);
287                     if (ctr == NULL) {
288                         ctr = arenaAlloc(censuses[era].arena, sizeof(counter));
289                         initLDVCtr(ctr);
290                         insertHashTable(censuses[era].hash, (StgWord)id, ctr);
291                         ctr->identity = id;
292                         ctr->next = censuses[era].ctrs;
293                         censuses[era].ctrs = ctr;
294                     }
295                     ctr->c.ldv.drag_total -= (int)size;
296                 }
297             }
298         }
299     }
300 }
301 #endif
302
303 /* --------------------------------------------------------------------------
304  * Initialize censuses[era];
305  * ----------------------------------------------------------------------- */
306 static inline void
307 initEra(Census *census)
308 {
309     census->hash  = allocHashTable();
310     census->ctrs  = NULL;
311     census->arena = newArena();
312
313     census->not_used   = 0;
314     census->used       = 0;
315     census->prim       = 0;
316     census->void_total = 0;
317     census->drag_total = 0;
318 }
319
320 /* --------------------------------------------------------------------------
321  * Increases era by 1 and initialize census[era].
322  * Reallocates gi[] and increases its size if needed.
323  * ----------------------------------------------------------------------- */
324 static void
325 nextEra( void )
326 {
327 #ifdef PROFILING
328     if (doingLDVProfiling()) { 
329         era++;
330
331         if (era == max_era) {
332             barf("maximum number of censuses reached; use +RTS -i to reduce");
333         }
334         
335         if (era == n_censuses) {
336             n_censuses *= 2;
337             censuses = stgReallocBytes(censuses, sizeof(Census) * n_censuses,
338                                        "nextEra");
339         }
340     }
341 #endif // PROFILING
342         
343     initEra( &censuses[era] );
344 }
345
346 /* -----------------------------------------------------------------------------
347  * DEBUG heap profiling, by info table
348  * -------------------------------------------------------------------------- */
349
350 #ifdef DEBUG_HEAP_PROF
351 FILE *hp_file;
352
353 void initProfiling1( void )
354 {
355 }
356
357 void initProfiling2( void )
358 {
359   initHeapProfiling();
360 }
361
362 void endProfiling( void )
363 {
364   endHeapProfiling();
365 }
366 #endif /* DEBUG_HEAP_PROF */
367
368 /* --------------------------------------------------------------------------
369  * Initialize the heap profilier
370  * ----------------------------------------------------------------------- */
371 nat
372 initHeapProfiling(void)
373 {
374     if (! RtsFlags.ProfFlags.doHeapProfile) {
375         return 0;
376     }
377
378 #ifdef PROFILING
379     if (doingLDVProfiling() && doingRetainerProfiling()) {
380         prog_belch("cannot mix -hb and -hr");
381         stg_exit(1);
382     }
383 #endif
384
385     // we only count eras if we're doing LDV profiling.  Otherwise era
386     // is fixed at zero.
387 #ifdef PROFILING
388     if (doingLDVProfiling()) {
389         era = 1;
390     } else
391 #endif
392     {
393         era = 0;
394     }
395
396     {   // max_era = 2^LDV_SHIFT
397         nat p;
398         max_era = 1;
399         for (p = 0; p < LDV_SHIFT; p++)
400             max_era *= 2;
401     }
402
403     n_censuses = 32;
404     censuses = stgMallocBytes(sizeof(Census) * n_censuses, "initHeapProfiling");
405
406     initEra( &censuses[era] );
407
408     fprintf(hp_file, "JOB \"%s", prog_argv[0]);
409
410 #ifdef PROFILING
411     {
412         int count;
413         for(count = 1; count < prog_argc; count++)
414             fprintf(hp_file, " %s", prog_argv[count]);
415         fprintf(hp_file, " +RTS ");
416         for(count = 0; count < rts_argc; count++)
417             fprintf(hp_file, "%s ", rts_argv[count]);
418         fprintf(hp_file, "\n");
419     }
420 #endif /* PROFILING */
421
422     fprintf(hp_file, "\"\n" );
423
424     fprintf(hp_file, "DATE \"%s\"\n", time_str());
425
426     fprintf(hp_file, "SAMPLE_UNIT \"seconds\"\n");
427     fprintf(hp_file, "VALUE_UNIT \"bytes\"\n");
428
429     fprintf(hp_file, "BEGIN_SAMPLE 0.00\n");
430     fprintf(hp_file, "END_SAMPLE 0.00\n");
431
432 #ifdef DEBUG_HEAP_PROF
433     DEBUG_LoadSymbols(prog_argv[0]);
434 #endif
435
436 #ifdef PROFILING
437     if (doingRetainerProfiling()) {
438         initRetainerProfiling();
439     }
440 #endif
441
442     return 0;
443 }
444
445 void
446 endHeapProfiling(void)
447 {
448     StgDouble seconds;
449
450     if (! RtsFlags.ProfFlags.doHeapProfile) {
451         return;
452     }
453
454 #ifdef PROFILING
455     if (doingRetainerProfiling()) {
456         endRetainerProfiling();
457     }
458 #endif
459
460 #ifdef PROFILING
461     if (doingLDVProfiling()) {
462         nat t;
463         LdvCensusKillAll();
464         aggregateCensusInfo();
465         for (t = 1; t < era; t++) {
466             dumpCensus( &censuses[t] );
467         }
468     }
469 #endif
470
471     seconds = mut_user_time();
472     fprintf(hp_file, "BEGIN_SAMPLE %0.2f\n", seconds);
473     fprintf(hp_file, "END_SAMPLE %0.2f\n", seconds);
474     fclose(hp_file);
475 }
476
477
478
479 #ifdef PROFILING
480 static void
481 fprint_ccs(FILE *fp, CostCentreStack *ccs, nat max_length)
482 {
483     char buf[max_length+1];
484     nat next_offset = 0;
485     nat written;
486     char *template;
487
488     // MAIN on its own gets printed as "MAIN", otherwise we ignore MAIN.
489     if (ccs == CCS_MAIN) {
490         fprintf(fp, "MAIN");
491         return;
492     }
493
494     fprintf(fp, "(%d)", ccs->ccsID);
495
496     // keep printing components of the stack until we run out of space
497     // in the buffer.  If we run out of space, end with "...".
498     for (; ccs != NULL && ccs != CCS_MAIN; ccs = ccs->prevStack) {
499
500         // CAF cost centres print as M.CAF, but we leave the module
501         // name out of all the others to save space.
502         if (!strcmp(ccs->cc->label,"CAF")) {
503 #ifdef HAVE_SNPRINTF
504             written = snprintf(buf+next_offset, 
505                                (int)max_length-3-(int)next_offset,
506                                "%s.CAF", ccs->cc->module);
507 #else
508             written = sprintf(buf+next_offset, 
509                                "%s.CAF", ccs->cc->module);
510 #endif
511         } else {
512             if (ccs->prevStack != NULL && ccs->prevStack != CCS_MAIN) {
513                 template = "%s/";
514             } else {
515                 template = "%s";
516             }
517 #ifdef HAVE_SNPRINTF
518             written = snprintf(buf+next_offset, 
519                                (int)max_length-3-(int)next_offset,
520                                template, ccs->cc->label);
521 #else
522             written = sprintf(buf+next_offset, 
523                                template, ccs->cc->label);
524 #endif
525         }
526
527         if (next_offset+written >= max_length-4) {
528             sprintf(buf+max_length-4, "...");
529             break;
530         } else {
531             next_offset += written;
532         }
533     }
534     fprintf(fp, "%s", buf);
535 }
536 #endif // PROFILING
537
538 rtsBool
539 strMatchesSelector( char* str, char* sel )
540 {
541    char* p;
542    // fprintf(stderr, "str_matches_selector %s %s\n", str, sel);
543    while (1) {
544        // Compare str against wherever we've got to in sel.
545        p = str;
546        while (*p != '\0' && *sel != ',' && *sel != '\0' && *p == *sel) {
547            p++; sel++;
548        }
549        // Match if all of str used and have reached the end of a sel fragment.
550        if (*p == '\0' && (*sel == ',' || *sel == '\0'))
551            return rtsTrue;
552        
553        // No match.  Advance sel to the start of the next elem.
554        while (*sel != ',' && *sel != '\0') sel++;
555        if (*sel == ',') sel++;
556        
557        /* Run out of sel ?? */
558        if (*sel == '\0') return rtsFalse;
559    }
560 }
561
562 /* -----------------------------------------------------------------------------
563  * Figure out whether a closure should be counted in this census, by
564  * testing against all the specified constraints.
565  * -------------------------------------------------------------------------- */
566 rtsBool
567 closureSatisfiesConstraints( StgClosure* p )
568 {
569 #ifdef DEBUG_HEAP_PROF
570     return rtsTrue;
571 #else
572    rtsBool b;
573
574    // The CCS has a selected field to indicate whether this closure is
575    // deselected by not being mentioned in the module, CC, or CCS
576    // selectors.
577    if (!p->header.prof.ccs->selected) {
578        return rtsFalse;
579    }
580
581    if (RtsFlags.ProfFlags.descrSelector) {
582        b = strMatchesSelector( (get_itbl((StgClosure *)p))->prof.closure_desc,
583                                  RtsFlags.ProfFlags.descrSelector );
584        if (!b) return rtsFalse;
585    }
586    if (RtsFlags.ProfFlags.typeSelector) {
587        b = strMatchesSelector( (get_itbl((StgClosure *)p))->prof.closure_type,
588                                 RtsFlags.ProfFlags.typeSelector );
589        if (!b) return rtsFalse;
590    }
591    if (RtsFlags.ProfFlags.retainerSelector) {
592        RetainerSet *rs;
593        nat i;
594        rs = retainerSetOf((StgClosure *)p);
595        if (rs != NULL) {
596            for (i = 0; i < rs->num; i++) {
597                b = strMatchesSelector( rs->element[i]->cc->label,
598                                          RtsFlags.ProfFlags.retainerSelector );
599                if (b) return rtsTrue;
600            }
601        }
602        return rtsFalse;
603    }
604    return rtsTrue;
605 #endif /* PROFILING */
606 }
607
608 /* -----------------------------------------------------------------------------
609  * Aggregate the heap census info for biographical profiling
610  * -------------------------------------------------------------------------- */
611 #ifdef PROFILING
612 static void
613 aggregateCensusInfo( void )
614 {
615     HashTable *acc;
616     nat t;
617     counter *c, *d, *ctrs;
618     Arena *arena;
619
620     if (!doingLDVProfiling()) return;
621
622     // Aggregate the LDV counters when displaying by biography.
623     if (RtsFlags.ProfFlags.doHeapProfile == HEAP_BY_LDV) {
624         int void_total, drag_total;
625
626         // Now we compute void_total and drag_total for each census
627         void_total = 0;
628         drag_total = 0;
629         for (t = 1; t < era; t++) { // note: start at 1, not 0
630             void_total += censuses[t].void_total;
631             drag_total += censuses[t].drag_total;
632             censuses[t].void_total = void_total;
633             censuses[t].drag_total = drag_total;
634             ASSERT( censuses[t].void_total <= censuses[t].not_used );
635             ASSERT( censuses[t].drag_total <= censuses[t].used );
636         }
637         
638         return;
639     }
640
641     // otherwise... we're doing a heap profile that is restricted to
642     // some combination of lag, drag, void or use.  We've kept all the
643     // census info for all censuses so far, but we still need to
644     // aggregate the counters forwards.
645
646     arena = newArena();
647     acc = allocHashTable();
648     ctrs = NULL;
649
650     for (t = 1; t < era; t++) {
651
652         // first look through all the counters we're aggregating
653         for (c = ctrs; c != NULL; c = c->next) {
654             // if one of the totals is non-zero, then this closure
655             // type must be present in the heap at this census time...
656             d = lookupHashTable(censuses[t].hash, (StgWord)c->identity);
657
658             if (d == NULL) {
659                 // if this closure identity isn't present in the
660                 // census for this time period, then our running
661                 // totals *must* be zero.
662                 ASSERT(c->c.ldv.void_total == 0 && c->c.ldv.drag_total == 0);
663
664                 // fprintCCS(stderr,c->identity);
665                 // fprintf(stderr," census=%d void_total=%d drag_total=%d\n",
666                 //         t, c->c.ldv.void_total, c->c.ldv.drag_total);
667             } else {
668                 d->c.ldv.void_total += c->c.ldv.void_total;
669                 d->c.ldv.drag_total += c->c.ldv.drag_total;
670                 c->c.ldv.void_total =  d->c.ldv.void_total;
671                 c->c.ldv.drag_total =  d->c.ldv.drag_total;
672
673                 ASSERT( c->c.ldv.void_total >= 0 );
674                 ASSERT( c->c.ldv.drag_total >= 0 );
675             }
676         }
677
678         // now look through the counters in this census to find new ones
679         for (c = censuses[t].ctrs; c != NULL; c = c->next) {
680             d = lookupHashTable(acc, (StgWord)c->identity);
681             if (d == NULL) {
682                 d = arenaAlloc( arena, sizeof(counter) );
683                 initLDVCtr(d);
684                 insertHashTable( acc, (StgWord)c->identity, d );
685                 d->identity = c->identity;
686                 d->next = ctrs;
687                 ctrs = d;
688                 d->c.ldv.void_total = c->c.ldv.void_total;
689                 d->c.ldv.drag_total = c->c.ldv.drag_total;
690             }
691             ASSERT( c->c.ldv.void_total >= 0 );
692             ASSERT( c->c.ldv.drag_total >= 0 );
693         }
694     }
695
696     freeHashTable(acc, NULL);
697     arenaFree(arena);
698 }
699 #endif
700
701 /* -----------------------------------------------------------------------------
702  * Print out the results of a heap census.
703  * -------------------------------------------------------------------------- */
704 static void
705 dumpCensus( Census *census )
706 {
707     counter *ctr;
708     int count;
709
710     fprintf(hp_file, "BEGIN_SAMPLE %0.2f\n", census->time);
711
712 #ifdef PROFILING
713     if (RtsFlags.ProfFlags.doHeapProfile == HEAP_BY_LDV) {
714         fprintf(hp_file, "VOID\t%u\n", census->void_total * sizeof(W_));
715         fprintf(hp_file, "LAG\t%u\n", 
716                 (census->not_used - census->void_total) * sizeof(W_));
717         fprintf(hp_file, "USE\t%u\n", 
718                 (census->used - census->drag_total) * sizeof(W_));
719         fprintf(hp_file, "INHERENT_USE\t%u\n", 
720                 census->prim * sizeof(W_));
721         fprintf(hp_file, "DRAG\t%u\n", census->drag_total *
722                 sizeof(W_));
723         fprintf(hp_file, "END_SAMPLE %0.2f\n", census->time);
724         return;
725     }
726 #endif
727
728     for (ctr = census->ctrs; ctr != NULL; ctr = ctr->next) {
729
730 #ifdef PROFILING
731         if (RtsFlags.ProfFlags.bioSelector != NULL) {
732             count = 0;
733             if (strMatchesSelector("lag", RtsFlags.ProfFlags.bioSelector))
734                 count += ctr->c.ldv.not_used - ctr->c.ldv.void_total;
735             if (strMatchesSelector("drag", RtsFlags.ProfFlags.bioSelector))
736                 count += ctr->c.ldv.drag_total;
737             if (strMatchesSelector("void", RtsFlags.ProfFlags.bioSelector))
738                 count += ctr->c.ldv.void_total;
739             if (strMatchesSelector("use", RtsFlags.ProfFlags.bioSelector))
740                 count += ctr->c.ldv.used - ctr->c.ldv.drag_total;
741         } else
742 #endif
743         {
744             count = ctr->c.resid;
745         }
746
747         ASSERT( count >= 0 );
748
749         if (count == 0) continue;
750
751 #ifdef DEBUG_HEAP_PROF
752         switch (RtsFlags.ProfFlags.doHeapProfile) {
753         case HEAP_BY_INFOPTR:
754             fprintf(hp_file, "%s", lookupGHCName(ctr->identity));
755             break;
756         case HEAP_BY_CLOSURE_TYPE:
757             fprintf(hp_file, "%s", (char *)ctr->identity);
758             break;
759         }
760 #endif
761         
762 #ifdef PROFILING
763         switch (RtsFlags.ProfFlags.doHeapProfile) {
764         case HEAP_BY_CCS:
765             fprint_ccs(hp_file, (CostCentreStack *)ctr->identity, 25);
766             break;
767         case HEAP_BY_MOD:
768         case HEAP_BY_DESCR:
769         case HEAP_BY_TYPE:
770             fprintf(hp_file, "%s", (char *)ctr->identity);
771             break;
772         case HEAP_BY_RETAINER:
773         {
774             RetainerSet *rs = (RetainerSet *)ctr->identity;
775
776             // it might be the distinguished retainer set rs_MANY:
777             if (rs == &rs_MANY) {
778                 fprintf(hp_file, "MANY");
779                 break;
780             }
781
782             // Mark this retainer set by negating its id, because it
783             // has appeared in at least one census.  We print the
784             // values of all such retainer sets into the log file at
785             // the end.  A retainer set may exist but not feature in
786             // any censuses if it arose as the intermediate retainer
787             // set for some closure during retainer set calculation.
788             if (rs->id > 0)
789                 rs->id = -(rs->id);
790
791             // report in the unit of bytes: * sizeof(StgWord)
792             printRetainerSetShort(hp_file, rs);
793             break;
794         }
795         default:
796             barf("dumpCensus; doHeapProfile");
797         }
798 #endif
799
800         fprintf(hp_file, "\t%d\n", count * sizeof(W_));
801     }
802
803     fprintf(hp_file, "END_SAMPLE %0.2f\n", census->time);
804 }
805
806 /* -----------------------------------------------------------------------------
807  * Code to perform a heap census.
808  * -------------------------------------------------------------------------- */
809 static void
810 heapCensusChain( Census *census, bdescr *bd )
811 {
812     StgPtr p;
813     StgInfoTable *info;
814     void *identity;
815     nat size;
816     counter *ctr;
817     nat real_size;
818     rtsBool prim;
819
820     for (; bd != NULL; bd = bd->link) {
821         p = bd->start;
822         while (p < bd->free) {
823             info = get_itbl((StgClosure *)p);
824             prim = rtsFalse;
825             
826             switch (info->type) {
827
828             case CONSTR:
829             case FUN:
830             case THUNK:
831             case IND_PERM:
832             case IND_OLDGEN_PERM:
833             case CAF_BLACKHOLE:
834             case SE_CAF_BLACKHOLE:
835             case SE_BLACKHOLE:
836             case BLACKHOLE:
837             case BLACKHOLE_BQ:
838             case CONSTR_INTLIKE:
839             case CONSTR_CHARLIKE:
840             case FUN_1_0:
841             case FUN_0_1:
842             case FUN_1_1:
843             case FUN_0_2:
844             case FUN_2_0:
845             case THUNK_1_1:
846             case THUNK_0_2:
847             case THUNK_2_0:
848             case CONSTR_1_0:
849             case CONSTR_0_1:
850             case CONSTR_1_1:
851             case CONSTR_0_2:
852             case CONSTR_2_0:
853                 size = sizeW_fromITBL(info);
854                 break;
855                 
856             case BCO:
857             case MVAR:
858             case WEAK:
859             case FOREIGN:
860             case STABLE_NAME:
861             case MUT_VAR:
862             case MUT_CONS:
863                 prim = rtsTrue;
864                 size = sizeW_fromITBL(info);
865                 break;
866
867             case THUNK_1_0:             /* ToDo - shouldn't be here */
868             case THUNK_0_1:             /* "  ditto  " */
869             case THUNK_SELECTOR:
870                 size = sizeofW(StgHeader) + MIN_UPD_SIZE;
871                 break;
872
873             case PAP:
874             case AP_UPD:
875                 size = pap_sizeW((StgPAP *)p);
876                 break;
877                 
878             case ARR_WORDS:
879                 prim = rtsTrue;
880                 size = arr_words_sizeW(stgCast(StgArrWords*,p));
881                 break;
882                 
883             case MUT_ARR_PTRS:
884             case MUT_ARR_PTRS_FROZEN:
885                 prim = rtsTrue;
886                 size = mut_arr_ptrs_sizeW((StgMutArrPtrs *)p);
887                 break;
888                 
889             case TSO:
890                 prim = rtsTrue;
891                 size = tso_sizeW((StgTSO *)p);
892                 break;
893                 
894             default:
895                 barf("heapCensus");
896             }
897             
898             identity = NULL;
899
900 #ifdef DEBUG_HEAP_PROF
901             real_size = size;
902 #else
903             // subtract the profiling overhead
904             real_size = size - sizeofW(StgProfHeader);
905 #endif
906
907             if (closureSatisfiesConstraints((StgClosure*)p)) {
908 #ifdef PROFILING
909                 if (RtsFlags.ProfFlags.doHeapProfile == HEAP_BY_LDV) {
910                     if (prim)
911                         census->prim += real_size;
912                     else if ((LDVW(p) & LDV_STATE_MASK) == LDV_STATE_CREATE)
913                         census->not_used += real_size;
914                     else
915                         census->used += real_size;
916                 } else
917 #endif
918                 {
919                     identity = closureIdentity((StgClosure *)p);
920
921                     if (identity != NULL) {
922                         ctr = lookupHashTable( census->hash, (StgWord)identity );
923                         if (ctr != NULL) {
924 #ifdef PROFILING
925                             if (RtsFlags.ProfFlags.bioSelector != NULL) {
926                                 if (prim)
927                                     ctr->c.ldv.prim += real_size;
928                                 else if ((LDVW(p) & LDV_STATE_MASK) == LDV_STATE_CREATE)
929                                     ctr->c.ldv.not_used += real_size;
930                                 else
931                                     ctr->c.ldv.used += real_size;
932                             } else
933 #endif
934                             {
935                                 ctr->c.resid += real_size;
936                             }
937                         } else {
938                             ctr = arenaAlloc( census->arena, sizeof(counter) );
939                             initLDVCtr(ctr);
940                             insertHashTable( census->hash, (StgWord)identity, ctr );
941                             ctr->identity = identity;
942                             ctr->next = census->ctrs;
943                             census->ctrs = ctr;
944
945 #ifdef PROFILING
946                             if (RtsFlags.ProfFlags.bioSelector != NULL) {
947                                 if (prim)
948                                     ctr->c.ldv.prim = real_size;
949                                 else if ((LDVW(p) & LDV_STATE_MASK) == LDV_STATE_CREATE)
950                                     ctr->c.ldv.not_used = real_size;
951                                 else
952                                     ctr->c.ldv.used = real_size;
953                             } else
954 #endif
955                             {
956                                 ctr->c.resid = real_size;
957                             }
958                         }
959                     }
960                 }
961             }
962
963             p += size;
964         }
965     }
966 }
967
968 void
969 heapCensus( void )
970 {
971   nat g, s;
972   Census *census;
973
974   census = &censuses[era];
975   census->time  = mut_user_time();
976     
977   // calculate retainer sets if necessary
978 #ifdef PROFILING
979   if (doingRetainerProfiling()) {
980       retainerProfile();
981   }
982 #endif
983
984 #ifdef PROFILING
985   stat_startHeapCensus();
986 #endif
987
988   // traverse the heap, collecting the census info
989   heapCensusChain( census, small_alloc_list );
990   if (RtsFlags.GcFlags.generations == 1) {
991       heapCensusChain( census, g0s0->to_blocks );
992   } else {
993       for (g = 0; g < RtsFlags.GcFlags.generations; g++) {
994           for (s = 0; s < generations[g].n_steps; s++) {
995               heapCensusChain( census, generations[g].steps[s].blocks );
996               // Are we interested in large objects?  might be
997               // confusing to include the stack in a heap profile.
998               // heapCensusChain( census, generations[g].steps[s].large_objects );
999           }
1000       }
1001   }
1002
1003   // dump out the census info
1004 #ifdef PROFILING
1005     // We can't generate any info for LDV profiling until
1006     // the end of the run...
1007     if (!doingLDVProfiling())
1008         dumpCensus( census );
1009 #else
1010     dumpCensus( census );
1011 #endif
1012
1013
1014   // free our storage, unless we're keeping all the census info for
1015   // future restriction by biography.
1016 #ifdef PROFILING
1017   if (RtsFlags.ProfFlags.bioSelector == NULL)
1018 #endif
1019   {
1020       freeHashTable( census->hash, NULL/* don't free the elements */ );
1021       arenaFree( census->arena );
1022       census->hash = NULL;
1023       census->arena = NULL;
1024   }
1025
1026   // we're into the next time period now
1027   nextEra();
1028
1029 #ifdef PROFILING
1030   stat_endHeapCensus();
1031 #endif
1032 }    
1033
1034 #endif /* PROFILING || DEBUG_HEAP_PROF */
1035