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