[project @ 2006-01-17 16:13:18 by simonmar]
[ghc-hetmet.git] / ghc / 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 "Storage.h"
23 #include "ProfHeap.h"
24 #include "Stats.h"
25 #include "Hash.h"
26 #include "RetainerProfile.h"
27 #include "LdvProfile.h"
28 #include "Arena.h"
29 #include "Printer.h"
30
31 #include <string.h>
32 #include <stdlib.h>
33 #include <math.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 unsigned int 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 static Census *censuses = NULL;
99 static 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_STACK"
131     , "AP"
132
133     , "PAP"
134
135     , "IND"
136     , "IND_OLDGEN"
137     , "IND_PERM"
138     , "IND_OLDGEN_PERM"
139     , "IND_STATIC"
140
141     , "RET_BCO"
142     , "RET_SMALL"
143     , "RET_VEC_SMALL"
144     , "RET_BIG"
145     , "RET_VEC_BIG"
146     , "RET_DYN"
147     , "UPDATE_FRAME"
148     , "CATCH_FRAME"
149     , "STOP_FRAME"
150
151     , "BLACKHOLE"
152     , "MVAR"
153
154     , "ARR_WORDS"
155
156     , "MUT_ARR_PTRS_CLEAN"
157     , "MUT_ARR_PTRS_DIRTY"
158     , "MUT_ARR_PTRS_FROZEN"
159     , "MUT_VAR_CLEAN"
160     , "MUT_VAR_DIRTY"
161
162     , "WEAK"
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         ASSERT(LDVW(c) != 0);
252         if ((LDVW((c)) & LDV_STATE_MASK) == LDV_STATE_CREATE) {
253             t = (LDVW((c)) & LDV_CREATE_MASK) >> LDV_SHIFT;
254             if (t < era) {
255                 if (RtsFlags.ProfFlags.bioSelector == NULL) {
256                     censuses[t].void_total   += (int)size;
257                     censuses[era].void_total -= (int)size;
258                 } else {
259                     id = closureIdentity(c);
260                     ctr = lookupHashTable(censuses[t].hash, (StgWord)id);
261                     ASSERT( ctr != NULL );
262                     ctr->c.ldv.void_total += (int)size;
263                     ctr = lookupHashTable(censuses[era].hash, (StgWord)id);
264                     if (ctr == NULL) {
265                         ctr = arenaAlloc(censuses[era].arena, sizeof(counter));
266                         initLDVCtr(ctr);
267                         insertHashTable(censuses[era].hash, (StgWord)id, ctr);
268                         ctr->identity = id;
269                         ctr->next = censuses[era].ctrs;
270                         censuses[era].ctrs = ctr;
271                     }
272                     ctr->c.ldv.void_total -= (int)size;
273                 }
274             }
275         } else {
276             t = LDVW((c)) & LDV_LAST_MASK;
277             if (t + 1 < era) {
278                 if (RtsFlags.ProfFlags.bioSelector == NULL) {
279                     censuses[t+1].drag_total += size;
280                     censuses[era].drag_total -= size;
281                 } else {
282                     void *id;
283                     id = closureIdentity(c);
284                     ctr = lookupHashTable(censuses[t+1].hash, (StgWord)id);
285                     ASSERT( ctr != NULL );
286                     ctr->c.ldv.drag_total += (int)size;
287                     ctr = lookupHashTable(censuses[era].hash, (StgWord)id);
288                     if (ctr == NULL) {
289                         ctr = arenaAlloc(censuses[era].arena, sizeof(counter));
290                         initLDVCtr(ctr);
291                         insertHashTable(censuses[era].hash, (StgWord)id, ctr);
292                         ctr->identity = id;
293                         ctr->next = censuses[era].ctrs;
294                         censuses[era].ctrs = ctr;
295                     }
296                     ctr->c.ldv.drag_total -= (int)size;
297                 }
298             }
299         }
300     }
301 }
302 #endif
303
304 /* --------------------------------------------------------------------------
305  * Initialize censuses[era];
306  * ----------------------------------------------------------------------- */
307 STATIC_INLINE void
308 initEra(Census *census)
309 {
310     census->hash  = allocHashTable();
311     census->ctrs  = NULL;
312     census->arena = newArena();
313
314     census->not_used   = 0;
315     census->used       = 0;
316     census->prim       = 0;
317     census->void_total = 0;
318     census->drag_total = 0;
319 }
320
321 /* --------------------------------------------------------------------------
322  * Increases era by 1 and initialize census[era].
323  * Reallocates gi[] and increases its size if needed.
324  * ----------------------------------------------------------------------- */
325 static void
326 nextEra( void )
327 {
328 #ifdef PROFILING
329     if (doingLDVProfiling()) { 
330         era++;
331
332         if (era == max_era) {
333             errorBelch("maximum number of censuses reached; use +RTS -i to reduce");
334             stg_exit(EXIT_FAILURE);
335         }
336         
337         if (era == n_censuses) {
338             n_censuses *= 2;
339             censuses = stgReallocBytes(censuses, sizeof(Census) * n_censuses,
340                                        "nextEra");
341         }
342     }
343 #endif /* PROFILING */
344
345     initEra( &censuses[era] );
346 }
347
348 /* -----------------------------------------------------------------------------
349  * DEBUG heap profiling, by info table
350  * -------------------------------------------------------------------------- */
351
352 #ifdef DEBUG_HEAP_PROF
353 FILE *hp_file;
354 static char *hp_filename;
355
356 void initProfiling1( void )
357 {
358 }
359
360 void initProfiling2( void )
361 {
362   if (RtsFlags.ProfFlags.doHeapProfile) {
363     /* Initialise the log file name */
364     hp_filename = stgMallocBytes(strlen(prog_name) + 6, "hpFileName");
365     sprintf(hp_filename, "%s.hp", prog_name);
366     
367     /* open the log file */
368     if ((hp_file = fopen(hp_filename, "w")) == NULL) {
369       debugBelch("Can't open profiling report file %s\n", 
370               hp_filename);
371       RtsFlags.ProfFlags.doHeapProfile = 0;
372       return;
373     }
374   }
375   
376   initHeapProfiling();
377 }
378
379 void endProfiling( void )
380 {
381   endHeapProfiling();
382 }
383 #endif /* DEBUG_HEAP_PROF */
384
385 static void
386 printSample(rtsBool beginSample, StgDouble sampleValue)
387 {
388     StgDouble fractionalPart, integralPart;
389     fractionalPart = modf(sampleValue, &integralPart);
390     fprintf(hp_file, "%s %d.%02d\n",
391             (beginSample ? "BEGIN_SAMPLE" : "END_SAMPLE"),
392             (int)integralPart, (int)(fractionalPart * 100 + 0.5));
393 }
394
395 /* --------------------------------------------------------------------------
396  * Initialize the heap profilier
397  * ----------------------------------------------------------------------- */
398 nat
399 initHeapProfiling(void)
400 {
401     if (! RtsFlags.ProfFlags.doHeapProfile) {
402         return 0;
403     }
404
405 #ifdef PROFILING
406     if (doingLDVProfiling() && doingRetainerProfiling()) {
407         errorBelch("cannot mix -hb and -hr");
408         stg_exit(EXIT_FAILURE);
409     }
410 #endif
411
412     // we only count eras if we're doing LDV profiling.  Otherwise era
413     // is fixed at zero.
414 #ifdef PROFILING
415     if (doingLDVProfiling()) {
416         era = 1;
417     } else
418 #endif
419     {
420         era = 0;
421     }
422
423     {   // max_era = 2^LDV_SHIFT
424         nat p;
425         max_era = 1;
426         for (p = 0; p < LDV_SHIFT; p++)
427             max_era *= 2;
428     }
429
430     n_censuses = 32;
431     censuses = stgMallocBytes(sizeof(Census) * n_censuses, "initHeapProfiling");
432
433     initEra( &censuses[era] );
434
435     /* initProfilingLogFile(); */
436     fprintf(hp_file, "JOB \"%s", prog_name);
437
438 #ifdef PROFILING
439     {
440         int count;
441         for(count = 1; count < prog_argc; count++)
442             fprintf(hp_file, " %s", prog_argv[count]);
443         fprintf(hp_file, " +RTS");
444         for(count = 0; count < rts_argc; count++)
445             fprintf(hp_file, " %s", rts_argv[count]);
446     }
447 #endif /* PROFILING */
448
449     fprintf(hp_file, "\"\n" );
450
451     fprintf(hp_file, "DATE \"%s\"\n", time_str());
452
453     fprintf(hp_file, "SAMPLE_UNIT \"seconds\"\n");
454     fprintf(hp_file, "VALUE_UNIT \"bytes\"\n");
455
456     printSample(rtsTrue, 0);
457     printSample(rtsFalse, 0);
458
459 #ifdef DEBUG_HEAP_PROF
460     DEBUG_LoadSymbols(prog_name);
461 #endif
462
463 #ifdef PROFILING
464     if (doingRetainerProfiling()) {
465         initRetainerProfiling();
466     }
467 #endif
468
469     return 0;
470 }
471
472 void
473 endHeapProfiling(void)
474 {
475     StgDouble seconds;
476
477     if (! RtsFlags.ProfFlags.doHeapProfile) {
478         return;
479     }
480
481 #ifdef PROFILING
482     if (doingRetainerProfiling()) {
483         endRetainerProfiling();
484     }
485 #endif
486
487 #ifdef PROFILING
488     if (doingLDVProfiling()) {
489         nat t;
490         LdvCensusKillAll();
491         aggregateCensusInfo();
492         for (t = 1; t < era; t++) {
493             dumpCensus( &censuses[t] );
494         }
495     }
496 #endif
497
498     seconds = mut_user_time();
499     printSample(rtsTrue, seconds);
500     printSample(rtsFalse, seconds);
501     fclose(hp_file);
502 }
503
504
505
506 #ifdef PROFILING
507 static size_t
508 buf_append(char *p, const char *q, char *end)
509 {
510     int m;
511
512     for (m = 0; p < end; p++, q++, m++) {
513         *p = *q;
514         if (*q == '\0') { break; }
515     }
516     return m;
517 }
518
519 static void
520 fprint_ccs(FILE *fp, CostCentreStack *ccs, nat max_length)
521 {
522     char buf[max_length+1], *p, *buf_end;
523     nat next_offset = 0;
524     nat written;
525
526     // MAIN on its own gets printed as "MAIN", otherwise we ignore MAIN.
527     if (ccs == CCS_MAIN) {
528         fprintf(fp, "MAIN");
529         return;
530     }
531
532     fprintf(fp, "(%ld)", ccs->ccsID);
533
534     p = buf;
535     buf_end = buf + max_length + 1;
536
537     // keep printing components of the stack until we run out of space
538     // in the buffer.  If we run out of space, end with "...".
539     for (; ccs != NULL && ccs != CCS_MAIN; ccs = ccs->prevStack) {
540
541         // CAF cost centres print as M.CAF, but we leave the module
542         // name out of all the others to save space.
543         if (!strcmp(ccs->cc->label,"CAF")) {
544             p += buf_append(p, ccs->cc->module, buf_end);
545             p += buf_append(p, ".CAF", buf_end);
546         } else {
547             if (ccs->prevStack != NULL && ccs->prevStack != CCS_MAIN) {
548                 p += buf_append(p, "/", buf_end);
549             }
550             p += buf_append(p, ccs->cc->label, buf_end);
551         }
552         
553         if (p >= buf_end) {
554             sprintf(buf+max_length-4, "...");
555             break;
556         } else {
557             next_offset += written;
558         }
559     }
560     fprintf(fp, "%s", buf);
561 }
562 #endif /* PROFILING */
563
564 rtsBool
565 strMatchesSelector( char* str, char* sel )
566 {
567    char* p;
568    // debugBelch("str_matches_selector %s %s\n", str, sel);
569    while (1) {
570        // Compare str against wherever we've got to in sel.
571        p = str;
572        while (*p != '\0' && *sel != ',' && *sel != '\0' && *p == *sel) {
573            p++; sel++;
574        }
575        // Match if all of str used and have reached the end of a sel fragment.
576        if (*p == '\0' && (*sel == ',' || *sel == '\0'))
577            return rtsTrue;
578        
579        // No match.  Advance sel to the start of the next elem.
580        while (*sel != ',' && *sel != '\0') sel++;
581        if (*sel == ',') sel++;
582        
583        /* Run out of sel ?? */
584        if (*sel == '\0') return rtsFalse;
585    }
586 }
587
588 /* -----------------------------------------------------------------------------
589  * Figure out whether a closure should be counted in this census, by
590  * testing against all the specified constraints.
591  * -------------------------------------------------------------------------- */
592 rtsBool
593 closureSatisfiesConstraints( StgClosure* p )
594 {
595 #ifdef DEBUG_HEAP_PROF
596     (void)p;   /* keep gcc -Wall happy */
597     return rtsTrue;
598 #else
599    rtsBool b;
600
601    // The CCS has a selected field to indicate whether this closure is
602    // deselected by not being mentioned in the module, CC, or CCS
603    // selectors.
604    if (!p->header.prof.ccs->selected) {
605        return rtsFalse;
606    }
607
608    if (RtsFlags.ProfFlags.descrSelector) {
609        b = strMatchesSelector( (get_itbl((StgClosure *)p))->prof.closure_desc,
610                                  RtsFlags.ProfFlags.descrSelector );
611        if (!b) return rtsFalse;
612    }
613    if (RtsFlags.ProfFlags.typeSelector) {
614        b = strMatchesSelector( (get_itbl((StgClosure *)p))->prof.closure_type,
615                                 RtsFlags.ProfFlags.typeSelector );
616        if (!b) return rtsFalse;
617    }
618    if (RtsFlags.ProfFlags.retainerSelector) {
619        RetainerSet *rs;
620        nat i;
621        // We must check that the retainer set is valid here.  One
622        // reason it might not be valid is if this closure is a
623        // a newly deceased weak pointer (i.e. a DEAD_WEAK), since
624        // these aren't reached by the retainer profiler's traversal.
625        if (isRetainerSetFieldValid((StgClosure *)p)) {
626            rs = retainerSetOf((StgClosure *)p);
627            if (rs != NULL) {
628                for (i = 0; i < rs->num; i++) {
629                    b = strMatchesSelector( rs->element[i]->cc->label,
630                                            RtsFlags.ProfFlags.retainerSelector );
631                    if (b) return rtsTrue;
632                }
633            }
634        }
635        return rtsFalse;
636    }
637    return rtsTrue;
638 #endif /* PROFILING */
639 }
640
641 /* -----------------------------------------------------------------------------
642  * Aggregate the heap census info for biographical profiling
643  * -------------------------------------------------------------------------- */
644 #ifdef PROFILING
645 static void
646 aggregateCensusInfo( void )
647 {
648     HashTable *acc;
649     nat t;
650     counter *c, *d, *ctrs;
651     Arena *arena;
652
653     if (!doingLDVProfiling()) return;
654
655     // Aggregate the LDV counters when displaying by biography.
656     if (RtsFlags.ProfFlags.doHeapProfile == HEAP_BY_LDV) {
657         int void_total, drag_total;
658
659         // Now we compute void_total and drag_total for each census
660         void_total = 0;
661         drag_total = 0;
662         for (t = 1; t < era; t++) { // note: start at 1, not 0
663             void_total += censuses[t].void_total;
664             drag_total += censuses[t].drag_total;
665             censuses[t].void_total = void_total;
666             censuses[t].drag_total = drag_total;
667             ASSERT( censuses[t].void_total <= censuses[t].not_used );
668             ASSERT( censuses[t].drag_total <= censuses[t].used );
669         }
670         
671         return;
672     }
673
674     // otherwise... we're doing a heap profile that is restricted to
675     // some combination of lag, drag, void or use.  We've kept all the
676     // census info for all censuses so far, but we still need to
677     // aggregate the counters forwards.
678
679     arena = newArena();
680     acc = allocHashTable();
681     ctrs = NULL;
682
683     for (t = 1; t < era; t++) {
684
685         // first look through all the counters we're aggregating
686         for (c = ctrs; c != NULL; c = c->next) {
687             // if one of the totals is non-zero, then this closure
688             // type must be present in the heap at this census time...
689             d = lookupHashTable(censuses[t].hash, (StgWord)c->identity);
690
691             if (d == NULL) {
692                 // if this closure identity isn't present in the
693                 // census for this time period, then our running
694                 // totals *must* be zero.
695                 ASSERT(c->c.ldv.void_total == 0 && c->c.ldv.drag_total == 0);
696
697                 // debugCCS(c->identity);
698                 // debugBelch(" census=%d void_total=%d drag_total=%d\n",
699                 //         t, c->c.ldv.void_total, c->c.ldv.drag_total);
700             } else {
701                 d->c.ldv.void_total += c->c.ldv.void_total;
702                 d->c.ldv.drag_total += c->c.ldv.drag_total;
703                 c->c.ldv.void_total =  d->c.ldv.void_total;
704                 c->c.ldv.drag_total =  d->c.ldv.drag_total;
705
706                 ASSERT( c->c.ldv.void_total >= 0 );
707                 ASSERT( c->c.ldv.drag_total >= 0 );
708             }
709         }
710
711         // now look through the counters in this census to find new ones
712         for (c = censuses[t].ctrs; c != NULL; c = c->next) {
713             d = lookupHashTable(acc, (StgWord)c->identity);
714             if (d == NULL) {
715                 d = arenaAlloc( arena, sizeof(counter) );
716                 initLDVCtr(d);
717                 insertHashTable( acc, (StgWord)c->identity, d );
718                 d->identity = c->identity;
719                 d->next = ctrs;
720                 ctrs = d;
721                 d->c.ldv.void_total = c->c.ldv.void_total;
722                 d->c.ldv.drag_total = c->c.ldv.drag_total;
723             }
724             ASSERT( c->c.ldv.void_total >= 0 );
725             ASSERT( c->c.ldv.drag_total >= 0 );
726         }
727     }
728
729     freeHashTable(acc, NULL);
730     arenaFree(arena);
731 }
732 #endif
733
734 /* -----------------------------------------------------------------------------
735  * Print out the results of a heap census.
736  * -------------------------------------------------------------------------- */
737 static void
738 dumpCensus( Census *census )
739 {
740     counter *ctr;
741     int count;
742
743     printSample(rtsTrue, census->time);
744
745 #ifdef PROFILING
746     if (RtsFlags.ProfFlags.doHeapProfile == HEAP_BY_LDV) {
747       fprintf(hp_file, "VOID\t%lu\n", (unsigned long)(census->void_total) * sizeof(W_));
748         fprintf(hp_file, "LAG\t%lu\n", 
749                 (unsigned long)(census->not_used - census->void_total) * sizeof(W_));
750         fprintf(hp_file, "USE\t%lu\n", 
751                 (unsigned long)(census->used - census->drag_total) * sizeof(W_));
752         fprintf(hp_file, "INHERENT_USE\t%lu\n", 
753                 (unsigned long)(census->prim) * sizeof(W_));
754         fprintf(hp_file, "DRAG\t%lu\n",
755                 (unsigned long)(census->drag_total) * sizeof(W_));
756         printSample(rtsFalse, census->time);
757         return;
758     }
759 #endif
760
761     for (ctr = census->ctrs; ctr != NULL; ctr = ctr->next) {
762
763 #ifdef PROFILING
764         if (RtsFlags.ProfFlags.bioSelector != NULL) {
765             count = 0;
766             if (strMatchesSelector("lag", RtsFlags.ProfFlags.bioSelector))
767                 count += ctr->c.ldv.not_used - ctr->c.ldv.void_total;
768             if (strMatchesSelector("drag", RtsFlags.ProfFlags.bioSelector))
769                 count += ctr->c.ldv.drag_total;
770             if (strMatchesSelector("void", RtsFlags.ProfFlags.bioSelector))
771                 count += ctr->c.ldv.void_total;
772             if (strMatchesSelector("use", RtsFlags.ProfFlags.bioSelector))
773                 count += ctr->c.ldv.used - ctr->c.ldv.drag_total;
774         } else
775 #endif
776         {
777             count = ctr->c.resid;
778         }
779
780         ASSERT( count >= 0 );
781
782         if (count == 0) continue;
783
784 #ifdef DEBUG_HEAP_PROF
785         switch (RtsFlags.ProfFlags.doHeapProfile) {
786         case HEAP_BY_INFOPTR:
787             fprintf(hp_file, "%s", lookupGHCName(ctr->identity));
788             break;
789         case HEAP_BY_CLOSURE_TYPE:
790             fprintf(hp_file, "%s", (char *)ctr->identity);
791             break;
792         }
793 #endif
794         
795 #ifdef PROFILING
796         switch (RtsFlags.ProfFlags.doHeapProfile) {
797         case HEAP_BY_CCS:
798             fprint_ccs(hp_file, (CostCentreStack *)ctr->identity, 25);
799             break;
800         case HEAP_BY_MOD:
801         case HEAP_BY_DESCR:
802         case HEAP_BY_TYPE:
803             fprintf(hp_file, "%s", (char *)ctr->identity);
804             break;
805         case HEAP_BY_RETAINER:
806         {
807             RetainerSet *rs = (RetainerSet *)ctr->identity;
808
809             // it might be the distinguished retainer set rs_MANY:
810             if (rs == &rs_MANY) {
811                 fprintf(hp_file, "MANY");
812                 break;
813             }
814
815             // Mark this retainer set by negating its id, because it
816             // has appeared in at least one census.  We print the
817             // values of all such retainer sets into the log file at
818             // the end.  A retainer set may exist but not feature in
819             // any censuses if it arose as the intermediate retainer
820             // set for some closure during retainer set calculation.
821             if (rs->id > 0)
822                 rs->id = -(rs->id);
823
824             // report in the unit of bytes: * sizeof(StgWord)
825             printRetainerSetShort(hp_file, rs);
826             break;
827         }
828         default:
829             barf("dumpCensus; doHeapProfile");
830         }
831 #endif
832
833         fprintf(hp_file, "\t%lu\n", (unsigned long)count * sizeof(W_));
834     }
835
836     printSample(rtsFalse, census->time);
837 }
838
839 /* -----------------------------------------------------------------------------
840  * Code to perform a heap census.
841  * -------------------------------------------------------------------------- */
842 static void
843 heapCensusChain( Census *census, bdescr *bd )
844 {
845     StgPtr p;
846     StgInfoTable *info;
847     void *identity;
848     nat size;
849     counter *ctr;
850     nat real_size;
851     rtsBool prim;
852
853     for (; bd != NULL; bd = bd->link) {
854
855         // HACK: ignore pinned blocks, because they contain gaps.
856         // It's not clear exactly what we'd like to do here, since we
857         // can't tell which objects in the block are actually alive.
858         // Perhaps the whole block should be counted as SYSTEM memory.
859         if (bd->flags & BF_PINNED) {
860             continue;
861         }
862
863         p = bd->start;
864         while (p < bd->free) {
865             info = get_itbl((StgClosure *)p);
866             prim = rtsFalse;
867             
868             switch (info->type) {
869
870             case THUNK:
871                 size = thunk_sizeW_fromITBL(info);
872                 break;
873
874             case THUNK_1_1:
875             case THUNK_0_2:
876             case THUNK_2_0:
877                 size = sizeofW(StgHeader) + stg_max(MIN_UPD_SIZE,2);
878                 break;
879
880             case THUNK_1_0:
881             case THUNK_0_1:
882             case THUNK_SELECTOR:
883                 size = sizeofW(StgHeader) + stg_max(MIN_UPD_SIZE,1);
884                 break;
885
886             case CONSTR:
887             case FUN:
888             case IND_PERM:
889             case IND_OLDGEN:
890             case IND_OLDGEN_PERM:
891             case CAF_BLACKHOLE:
892             case SE_CAF_BLACKHOLE:
893             case SE_BLACKHOLE:
894             case BLACKHOLE:
895             case CONSTR_INTLIKE:
896             case CONSTR_CHARLIKE:
897             case FUN_1_0:
898             case FUN_0_1:
899             case FUN_1_1:
900             case FUN_0_2:
901             case FUN_2_0:
902             case CONSTR_1_0:
903             case CONSTR_0_1:
904             case CONSTR_1_1:
905             case CONSTR_0_2:
906             case CONSTR_2_0:
907                 size = sizeW_fromITBL(info);
908                 break;
909                 
910             case IND:
911                 // Special case/Delicate Hack: INDs don't normally
912                 // appear, since we're doing this heap census right
913                 // after GC.  However, GarbageCollect() also does
914                 // resurrectThreads(), which can update some
915                 // blackholes when it calls raiseAsync() on the
916                 // resurrected threads.  So we know that any IND will
917                 // be the size of a BLACKHOLE.
918                 size = BLACKHOLE_sizeW();
919                 break;
920
921             case BCO:
922                 prim = rtsTrue;
923                 size = bco_sizeW((StgBCO *)p);
924                 break;
925
926             case MVAR:
927             case WEAK:
928             case STABLE_NAME:
929             case MUT_VAR_CLEAN:
930             case MUT_VAR_DIRTY:
931                 prim = rtsTrue;
932                 size = sizeW_fromITBL(info);
933                 break;
934
935             case AP:
936                 size = ap_sizeW((StgAP *)p);
937                 break;
938
939             case PAP:
940                 size = pap_sizeW((StgPAP *)p);
941                 break;
942
943             case AP_STACK:
944                 size = ap_stack_sizeW((StgAP_STACK *)p);
945                 break;
946                 
947             case ARR_WORDS:
948                 prim = rtsTrue;
949                 size = arr_words_sizeW(stgCast(StgArrWords*,p));
950                 break;
951                 
952             case MUT_ARR_PTRS_CLEAN:
953             case MUT_ARR_PTRS_DIRTY:
954             case MUT_ARR_PTRS_FROZEN:
955             case MUT_ARR_PTRS_FROZEN0:
956                 prim = rtsTrue;
957                 size = mut_arr_ptrs_sizeW((StgMutArrPtrs *)p);
958                 break;
959                 
960             case TSO:
961                 prim = rtsTrue;
962 #ifdef DEBUG_HEAP_PROF
963                 size = tso_sizeW((StgTSO *)p);
964                 break;
965 #else
966                 if (RtsFlags.ProfFlags.includeTSOs) {
967                     size = tso_sizeW((StgTSO *)p);
968                     break;
969                 } else {
970                     // Skip this TSO and move on to the next object
971                     p += tso_sizeW((StgTSO *)p);
972                     continue;
973                 }
974 #endif
975
976             case TREC_HEADER: 
977                 prim = rtsTrue;
978                 size = sizeofW(StgTRecHeader);
979                 break;
980
981             case TVAR_WAIT_QUEUE:
982                 prim = rtsTrue;
983                 size = sizeofW(StgTVarWaitQueue);
984                 break;
985                 
986             case TVAR:
987                 prim = rtsTrue;
988                 size = sizeofW(StgTVar);
989                 break;
990                 
991             case TREC_CHUNK:
992                 prim = rtsTrue;
993                 size = sizeofW(StgTRecChunk);
994                 break;
995
996             default:
997                 barf("heapCensus, unknown object: %d", info->type);
998             }
999             
1000             identity = NULL;
1001
1002 #ifdef DEBUG_HEAP_PROF
1003             real_size = size;
1004 #else
1005             // subtract the profiling overhead
1006             real_size = size - sizeofW(StgProfHeader);
1007 #endif
1008
1009             if (closureSatisfiesConstraints((StgClosure*)p)) {
1010 #ifdef PROFILING
1011                 if (RtsFlags.ProfFlags.doHeapProfile == HEAP_BY_LDV) {
1012                     if (prim)
1013                         census->prim += real_size;
1014                     else if ((LDVW(p) & LDV_STATE_MASK) == LDV_STATE_CREATE)
1015                         census->not_used += real_size;
1016                     else
1017                         census->used += real_size;
1018                 } else
1019 #endif
1020                 {
1021                     identity = closureIdentity((StgClosure *)p);
1022
1023                     if (identity != NULL) {
1024                         ctr = lookupHashTable( census->hash, (StgWord)identity );
1025                         if (ctr != NULL) {
1026 #ifdef PROFILING
1027                             if (RtsFlags.ProfFlags.bioSelector != NULL) {
1028                                 if (prim)
1029                                     ctr->c.ldv.prim += real_size;
1030                                 else if ((LDVW(p) & LDV_STATE_MASK) == LDV_STATE_CREATE)
1031                                     ctr->c.ldv.not_used += real_size;
1032                                 else
1033                                     ctr->c.ldv.used += real_size;
1034                             } else
1035 #endif
1036                             {
1037                                 ctr->c.resid += real_size;
1038                             }
1039                         } else {
1040                             ctr = arenaAlloc( census->arena, sizeof(counter) );
1041                             initLDVCtr(ctr);
1042                             insertHashTable( census->hash, (StgWord)identity, ctr );
1043                             ctr->identity = identity;
1044                             ctr->next = census->ctrs;
1045                             census->ctrs = ctr;
1046
1047 #ifdef PROFILING
1048                             if (RtsFlags.ProfFlags.bioSelector != NULL) {
1049                                 if (prim)
1050                                     ctr->c.ldv.prim = real_size;
1051                                 else if ((LDVW(p) & LDV_STATE_MASK) == LDV_STATE_CREATE)
1052                                     ctr->c.ldv.not_used = real_size;
1053                                 else
1054                                     ctr->c.ldv.used = real_size;
1055                             } else
1056 #endif
1057                             {
1058                                 ctr->c.resid = real_size;
1059                             }
1060                         }
1061                     }
1062                 }
1063             }
1064
1065             p += size;
1066         }
1067     }
1068 }
1069
1070 void
1071 heapCensus( void )
1072 {
1073   nat g, s;
1074   Census *census;
1075
1076   census = &censuses[era];
1077   census->time  = mut_user_time();
1078     
1079   // calculate retainer sets if necessary
1080 #ifdef PROFILING
1081   if (doingRetainerProfiling()) {
1082       retainerProfile();
1083   }
1084 #endif
1085
1086 #ifdef PROFILING
1087   stat_startHeapCensus();
1088 #endif
1089
1090   // Traverse the heap, collecting the census info
1091
1092   // First the small_alloc_list: we have to fix the free pointer at
1093   // the end by calling tidyAllocatedLists() first.
1094   tidyAllocateLists();
1095   heapCensusChain( census, small_alloc_list );
1096
1097   // Now traverse the heap in each generation/step.
1098   if (RtsFlags.GcFlags.generations == 1) {
1099       heapCensusChain( census, g0s0->blocks );
1100   } else {
1101       for (g = 0; g < RtsFlags.GcFlags.generations; g++) {
1102           for (s = 0; s < generations[g].n_steps; s++) {
1103               heapCensusChain( census, generations[g].steps[s].blocks );
1104               // Are we interested in large objects?  might be
1105               // confusing to include the stack in a heap profile.
1106               heapCensusChain( census, generations[g].steps[s].large_objects );
1107           }
1108       }
1109   }
1110
1111   // dump out the census info
1112 #ifdef PROFILING
1113     // We can't generate any info for LDV profiling until
1114     // the end of the run...
1115     if (!doingLDVProfiling())
1116         dumpCensus( census );
1117 #else
1118     dumpCensus( census );
1119 #endif
1120
1121
1122   // free our storage, unless we're keeping all the census info for
1123   // future restriction by biography.
1124 #ifdef PROFILING
1125   if (RtsFlags.ProfFlags.bioSelector == NULL)
1126 #endif
1127   {
1128       freeHashTable( census->hash, NULL/* don't free the elements */ );
1129       arenaFree( census->arena );
1130       census->hash = NULL;
1131       census->arena = NULL;
1132   }
1133
1134   // we're into the next time period now
1135   nextEra();
1136
1137 #ifdef PROFILING
1138   stat_endHeapCensus();
1139 #endif
1140 }    
1141
1142 #endif /* PROFILING || DEBUG_HEAP_PROF */
1143