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