1 /* -----------------------------------------------------------------------------
2 * $Id: ProfHeap.c,v 1.32 2001/11/29 16:38:13 simonmar Exp $
4 * (c) The GHC Team, 1998-2000
6 * Support for heap profiling
8 * ---------------------------------------------------------------------------*/
10 #if defined(DEBUG) && !defined(PROFILING)
11 #define DEBUG_HEAP_PROF
13 #undef DEBUG_HEAP_PROF
16 #if defined(PROFILING) || defined(DEBUG_HEAP_PROF)
18 #include "PosixSource.h"
22 #include "Profiling.h"
28 #include "RetainerProfile.h"
29 #include "LdvProfile.h"
33 /* -----------------------------------------------------------------------------
34 * era stores the current time period. It is the same as the
35 * number of censuses that have been performed.
38 * era must be no longer than LDV_SHIFT (15 or 30) bits.
40 * era is initialized to 0 in initHeapProfiling().
42 * max_era is initialized to 2^LDV_SHIFT in initHeapProfiling().
43 * When era reaches max_era, the profiling stops because a closure can
44 * store only up to (max_era - 1) as its creation or last use time.
45 * -------------------------------------------------------------------------- */
49 /* -----------------------------------------------------------------------------
52 * For most heap profiles each closure identity gets a simple count
53 * of live words in the heap at each census. However, if we're
54 * selecting by biography, then we have to keep the various
55 * lag/drag/void counters for each identity.
56 * -------------------------------------------------------------------------- */
57 typedef struct _counter {
62 int prim; // total size of 'inherently used' closures
63 int not_used; // total size of 'never used' closures
64 int used; // total size of 'used at least once' closures
65 int void_total; // current total size of 'destroyed without being used' closures
66 int drag_total; // current total size of 'used at least once and waiting to die'
69 struct _counter *next;
73 initLDVCtr( counter *ctr )
76 ctr->c.ldv.not_used = 0;
78 ctr->c.ldv.void_total = 0;
79 ctr->c.ldv.drag_total = 0;
83 double time; // the time in MUT time when the census is made
88 // for LDV profiling, when just displaying by LDV
96 Census *censuses = NULL;
100 static void aggregateCensusInfo( void );
103 static void dumpCensus( Census *census );
105 /* -----------------------------------------------------------------------------
106 Closure Type Profiling;
108 PROBABLY TOTALLY OUT OF DATE -- ToDo (SDM)
109 -------------------------------------------------------------------------- */
111 #ifdef DEBUG_HEAP_PROF
112 static char *type_names[] = {
118 , "CONSTR_NOCAF_STATIC"
156 , "MUT_ARR_PTRS_FROZEN"
170 #endif /* DEBUG_HEAP_PROF */
172 /* -----------------------------------------------------------------------------
173 * Find the "closure identity", which is a unique pointer reresenting
174 * the band to which this closure's heap space is attributed in the
176 * ------------------------------------------------------------------------- */
178 closureIdentity( StgClosure *p )
180 switch (RtsFlags.ProfFlags.doHeapProfile) {
184 return ((StgClosure *)p)->header.prof.ccs;
186 return ((StgClosure *)p)->header.prof.ccs->cc->module;
188 return (get_itbl((StgClosure *)p))->prof.closure_desc;
190 return (get_itbl((StgClosure *)p))->prof.closure_type;
191 case HEAP_BY_RETAINER:
192 return retainerSetOf((StgClosure *)p);
194 case HEAP_BY_INFOPTR:
195 return (void *)((StgClosure *)p)->header.info;
196 case HEAP_BY_CLOSURE_TYPE:
197 return type_names[get_itbl(p)->type];
200 barf("closureIdentity");
204 /* --------------------------------------------------------------------------
205 * Profiling type predicates
206 * ----------------------------------------------------------------------- */
208 static inline rtsBool
209 doingLDVProfiling( void )
211 return (RtsFlags.ProfFlags.doHeapProfile == HEAP_BY_LDV
212 || RtsFlags.ProfFlags.bioSelector != NULL);
215 static inline rtsBool
216 doingRetainerProfiling( void )
218 return (RtsFlags.ProfFlags.doHeapProfile == HEAP_BY_RETAINER
219 || RtsFlags.ProfFlags.retainerSelector != NULL);
223 // Precesses a closure 'c' being destroyed whose size is 'size'.
224 // Make sure that LDV_recordDead() is not invoked on 'inherently used' closures
225 // such as TSO; they should not be involved in computing dragNew or voidNew.
227 // Even though era is checked in both LdvCensusForDead() and
228 // LdvCensusKillAll(), we still need to make sure that era is > 0 because
229 // LDV_recordDead() may be called from elsewhere in the runtime system. E.g.,
230 // when a thunk is replaced by an indirection object.
234 LDV_recordDead( StgClosure *c, nat size )
240 if (era > 0 && closureSatisfiesConstraints(c)) {
241 size -= sizeofW(StgProfHeader);
242 if ((LDVW((c)) & LDV_STATE_MASK) == LDV_STATE_CREATE) {
243 t = (LDVW((c)) & LDV_CREATE_MASK) >> LDV_SHIFT;
245 if (RtsFlags.ProfFlags.bioSelector == NULL) {
246 censuses[t].void_total += (int)size;
247 censuses[era].void_total -= (int)size;
249 id = closureIdentity(c);
250 ctr = lookupHashTable(censuses[t].hash, (StgWord)id);
251 ASSERT( ctr != NULL );
252 ctr->c.ldv.void_total += (int)size;
253 ctr = lookupHashTable(censuses[era].hash, (StgWord)id);
255 ctr = arenaAlloc(censuses[era].arena, sizeof(counter));
257 insertHashTable(censuses[era].hash, (StgWord)id, ctr);
259 ctr->next = censuses[era].ctrs;
260 censuses[era].ctrs = ctr;
262 ctr->c.ldv.void_total -= (int)size;
266 t = LDVW((c)) & LDV_LAST_MASK;
268 if (RtsFlags.ProfFlags.bioSelector == NULL) {
269 censuses[t+1].drag_total += size;
270 censuses[era].drag_total -= size;
273 id = closureIdentity(c);
274 ctr = lookupHashTable(censuses[t+1].hash, (StgWord)id);
275 ASSERT( ctr != NULL );
276 ctr->c.ldv.drag_total += (int)size;
277 ctr = lookupHashTable(censuses[era].hash, (StgWord)id);
279 ctr = arenaAlloc(censuses[era].arena, sizeof(counter));
281 insertHashTable(censuses[era].hash, (StgWord)id, ctr);
283 ctr->next = censuses[era].ctrs;
284 censuses[era].ctrs = ctr;
286 ctr->c.ldv.drag_total -= (int)size;
294 /* --------------------------------------------------------------------------
295 * Initialize censuses[era];
296 * ----------------------------------------------------------------------- */
298 initEra(Census *census)
300 census->hash = allocHashTable();
302 census->arena = newArena();
304 census->not_used = 0;
307 census->void_total = 0;
308 census->drag_total = 0;
311 /* --------------------------------------------------------------------------
312 * Increases era by 1 and initialize census[era].
313 * Reallocates gi[] and increases its size if needed.
314 * ----------------------------------------------------------------------- */
319 if (doingLDVProfiling()) {
322 if (era == max_era) {
323 barf("maximum number of censuses reached; use +RTS -i to reduce");
326 if (era == n_censuses) {
328 censuses = stgReallocBytes(censuses, sizeof(Census) * n_censuses,
334 initEra( &censuses[era] );
337 /* -----------------------------------------------------------------------------
338 * DEBUG heap profiling, by info table
339 * -------------------------------------------------------------------------- */
341 #ifdef DEBUG_HEAP_PROF
344 void initProfiling1( void )
348 void initProfiling2( void )
353 void endProfiling( void )
357 #endif /* DEBUG_HEAP_PROF */
359 /* --------------------------------------------------------------------------
360 * Initialize the heap profilier
361 * ----------------------------------------------------------------------- */
363 initHeapProfiling(void)
365 if (! RtsFlags.ProfFlags.doHeapProfile) {
369 // we only count eras if we're doing LDV profiling. Otherwise era
372 if (doingLDVProfiling()) {
380 { // max_era = 2^LDV_SHIFT
383 for (p = 0; p < LDV_SHIFT; p++)
388 censuses = stgMallocBytes(sizeof(Census) * n_censuses, "initHeapProfiling");
390 initEra( &censuses[era] );
392 fprintf(hp_file, "JOB \"%s", prog_argv[0]);
397 for(count = 1; count < prog_argc; count++)
398 fprintf(hp_file, " %s", prog_argv[count]);
399 fprintf(hp_file, " +RTS ");
400 for(count = 0; count < rts_argc; count++)
401 fprintf(hp_file, "%s ", rts_argv[count]);
402 fprintf(hp_file, "\n");
404 #endif /* PROFILING */
406 fprintf(hp_file, "\"\n" );
408 fprintf(hp_file, "DATE \"%s\"\n", time_str());
410 fprintf(hp_file, "SAMPLE_UNIT \"seconds\"\n");
411 fprintf(hp_file, "VALUE_UNIT \"bytes\"\n");
413 fprintf(hp_file, "BEGIN_SAMPLE 0.00\n");
414 fprintf(hp_file, "END_SAMPLE 0.00\n");
416 #ifdef DEBUG_HEAP_PROF
417 DEBUG_LoadSymbols(prog_argv[0]);
421 if (doingRetainerProfiling()) {
422 initRetainerProfiling();
430 endHeapProfiling(void)
434 if (! RtsFlags.ProfFlags.doHeapProfile) {
439 if (doingRetainerProfiling()) {
440 endRetainerProfiling();
445 if (doingLDVProfiling()) {
448 aggregateCensusInfo();
449 for (t = 1; t < era; t++) {
450 dumpCensus( &censuses[t] );
455 seconds = mut_user_time();
456 fprintf(hp_file, "BEGIN_SAMPLE %0.2f\n", seconds);
457 fprintf(hp_file, "END_SAMPLE %0.2f\n", seconds);
465 fprint_ccs(FILE *fp, CostCentreStack *ccs, nat max_length)
467 char buf[max_length+1];
472 // MAIN on its own gets printed as "MAIN", otherwise we ignore MAIN.
473 if (ccs == CCS_MAIN) {
478 // keep printing components of the stack until we run out of space
479 // in the buffer. If we run out of space, end with "...".
480 for (; ccs != NULL && ccs != CCS_MAIN; ccs = ccs->prevStack) {
482 // CAF cost centres print as M.CAF, but we leave the module
483 // name out of all the others to save space.
484 if (!strcmp(ccs->cc->label,"CAF")) {
485 written = snprintf(buf+next_offset,
486 (int)max_length-3-(int)next_offset,
487 "%s.CAF", ccs->cc->module);
489 if (ccs->prevStack != NULL && ccs->prevStack != CCS_MAIN) {
494 written = snprintf(buf+next_offset,
495 (int)max_length-3-(int)next_offset,
496 template, ccs->cc->label);
499 if (next_offset+written >= max_length-4) {
500 sprintf(buf+max_length-4, "...");
503 next_offset += written;
506 fprintf(fp, "%s", buf);
510 str_matches_selector( char* str, char* sel )
513 // fprintf(stderr, "str_matches_selector %s %s\n", str, sel);
515 // Compare str against wherever we've got to in sel.
517 while (*p != '\0' && *sel != ',' && *sel != '\0' && *p == *sel) {
520 // Match if all of str used and have reached the end of a sel fragment.
521 if (*p == '\0' && (*sel == ',' || *sel == '\0'))
524 // No match. Advance sel to the start of the next elem.
525 while (*sel != ',' && *sel != '\0') sel++;
526 if (*sel == ',') sel++;
528 /* Run out of sel ?? */
529 if (*sel == '\0') return rtsFalse;
534 /* -----------------------------------------------------------------------------
535 * Figure out whether a closure should be counted in this census, by
536 * testing against all the specified constraints.
537 * -------------------------------------------------------------------------- */
539 closureSatisfiesConstraints( StgClosure* p )
541 #ifdef DEBUG_HEAP_PROF
545 if (RtsFlags.ProfFlags.modSelector) {
546 b = str_matches_selector( ((StgClosure *)p)->header.prof.ccs->cc->module,
547 RtsFlags.ProfFlags.modSelector );
548 if (!b) return rtsFalse;
550 if (RtsFlags.ProfFlags.descrSelector) {
551 b = str_matches_selector( (get_itbl((StgClosure *)p))->prof.closure_desc,
552 RtsFlags.ProfFlags.descrSelector );
553 if (!b) return rtsFalse;
555 if (RtsFlags.ProfFlags.typeSelector) {
556 b = str_matches_selector( (get_itbl((StgClosure *)p))->prof.closure_type,
557 RtsFlags.ProfFlags.typeSelector );
558 if (!b) return rtsFalse;
560 if (RtsFlags.ProfFlags.ccSelector) {
561 b = str_matches_selector( ((StgClosure *)p)->header.prof.ccs->cc->label,
562 RtsFlags.ProfFlags.ccSelector );
563 if (!b) return rtsFalse;
565 if (RtsFlags.ProfFlags.retainerSelector) {
568 rs = retainerSetOf((StgClosure *)p);
570 for (i = 0; i < rs->num; i++) {
571 b = str_matches_selector( rs->element[i]->cc->label,
572 RtsFlags.ProfFlags.retainerSelector );
573 if (b) return rtsTrue;
579 #endif /* PROFILING */
582 /* -----------------------------------------------------------------------------
583 * Aggregate the heap census info for biographical profiling
584 * -------------------------------------------------------------------------- */
587 aggregateCensusInfo( void )
591 counter *c, *d, *ctrs;
594 if (!doingLDVProfiling()) return;
596 // Aggregate the LDV counters when displaying by biography.
597 if (RtsFlags.ProfFlags.doHeapProfile == HEAP_BY_LDV) {
598 int void_total, drag_total;
600 // Now we compute void_total and drag_total for each census
603 for (t = 1; t < era; t++) { // note: start at 1, not 0
604 void_total += censuses[t].void_total;
605 drag_total += censuses[t].drag_total;
606 censuses[t].void_total = void_total;
607 censuses[t].drag_total = drag_total;
608 ASSERT( censuses[t].void_total < censuses[t].not_used );
609 ASSERT( censuses[t].drag_total < censuses[t].used );
615 // otherwise... we're doing a heap profile that is restricted to
616 // some combination of lag, drag, void or use. We've kept all the
617 // census info for all censuses so far, but we still need to
618 // aggregate the counters forwards.
621 acc = allocHashTable();
624 for (t = 1; t < era; t++) {
626 // first look through all the counters we're aggregating
627 for (c = ctrs; c != NULL; c = c->next) {
628 // if one of the totals is non-zero, then this closure
629 // type must be present in the heap at this census time...
630 d = lookupHashTable(censuses[t].hash, (StgWord)c->identity);
633 // if this closure identity isn't present in the
634 // census for this time period, then our running
635 // totals *must* be zero.
636 ASSERT(c->c.ldv.void_total == 0 && c->c.ldv.drag_total == 0);
638 // fprintCCS(stderr,c->identity);
639 // fprintf(stderr," census=%d void_total=%d drag_total=%d\n",
640 // t, c->c.ldv.void_total, c->c.ldv.drag_total);
642 d->c.ldv.void_total += c->c.ldv.void_total;
643 d->c.ldv.drag_total += c->c.ldv.drag_total;
644 c->c.ldv.void_total = d->c.ldv.void_total;
645 c->c.ldv.drag_total = d->c.ldv.drag_total;
647 ASSERT( c->c.ldv.void_total >= 0 );
648 ASSERT( c->c.ldv.drag_total >= 0 );
652 // now look through the counters in this census to find new ones
653 for (c = censuses[t].ctrs; c != NULL; c = c->next) {
654 d = lookupHashTable(acc, (StgWord)c->identity);
656 d = arenaAlloc( arena, sizeof(counter) );
658 insertHashTable( acc, (StgWord)c->identity, d );
659 d->identity = c->identity;
662 d->c.ldv.void_total = c->c.ldv.void_total;
663 d->c.ldv.drag_total = c->c.ldv.drag_total;
665 ASSERT( c->c.ldv.void_total >= 0 );
666 ASSERT( c->c.ldv.drag_total >= 0 );
670 freeHashTable(acc, NULL);
675 /* -----------------------------------------------------------------------------
676 * Print out the results of a heap census.
677 * -------------------------------------------------------------------------- */
679 dumpCensus( Census *census )
684 fprintf(hp_file, "BEGIN_SAMPLE %0.2f\n", census->time);
687 if (RtsFlags.ProfFlags.doHeapProfile == HEAP_BY_LDV) {
688 fprintf(hp_file, "VOID\t%u\n", census->void_total * sizeof(W_));
689 fprintf(hp_file, "LAG\t%u\n",
690 (census->not_used - census->void_total) * sizeof(W_));
691 fprintf(hp_file, "USE\t%u\n",
692 (census->used - census->drag_total) * sizeof(W_));
693 fprintf(hp_file, "INHERENT_USE\t%u\n",
694 census->prim * sizeof(W_));
695 fprintf(hp_file, "DRAG\t%u\n", census->drag_total *
697 fprintf(hp_file, "END_SAMPLE %0.2f\n", census->time);
702 for (ctr = census->ctrs; ctr != NULL; ctr = ctr->next) {
705 if (RtsFlags.ProfFlags.bioSelector != NULL) {
707 if (str_matches_selector("lag", RtsFlags.ProfFlags.bioSelector))
708 count += ctr->c.ldv.not_used - ctr->c.ldv.void_total;
709 if (str_matches_selector("drag", RtsFlags.ProfFlags.bioSelector))
710 count += ctr->c.ldv.drag_total;
711 if (str_matches_selector("void", RtsFlags.ProfFlags.bioSelector))
712 count += ctr->c.ldv.void_total;
713 if (str_matches_selector("use", RtsFlags.ProfFlags.bioSelector))
714 count += ctr->c.ldv.used - ctr->c.ldv.drag_total;
718 count = ctr->c.resid;
721 ASSERT( count >= 0 );
723 if (count == 0) continue;
725 #ifdef DEBUG_HEAP_PROF
726 switch (RtsFlags.ProfFlags.doHeapProfile) {
727 case HEAP_BY_INFOPTR:
728 fprintf(hp_file, "%s", lookupGHCName(ctr->identity));
730 case HEAP_BY_CLOSURE_TYPE:
731 fprintf(hp_file, "%s", (char *)ctr->identity);
737 switch (RtsFlags.ProfFlags.doHeapProfile) {
739 fprint_ccs(hp_file, (CostCentreStack *)ctr->identity, 30);
744 fprintf(hp_file, "%s", (char *)ctr->identity);
746 case HEAP_BY_RETAINER:
748 RetainerSet *rs = (RetainerSet *)ctr->identity;
750 // it might be the distinguished retainer set rs_MANY:
751 if (rs == &rs_MANY) {
752 fprintf(hp_file, "MANY");
756 // Mark this retainer set by negating its id, because it
757 // has appeared in at least one census. We print the
758 // values of all such retainer sets into the log file at
759 // the end. A retainer set may exist but not feature in
760 // any censuses if it arose as the intermediate retainer
761 // set for some closure during retainer set calculation.
765 // report in the unit of bytes: * sizeof(StgWord)
766 printRetainerSetShort(hp_file, rs);
770 barf("dumpCensus; doHeapProfile");
774 fprintf(hp_file, "\t%d\n", count * sizeof(W_));
777 fprintf(hp_file, "END_SAMPLE %0.2f\n", census->time);
780 /* -----------------------------------------------------------------------------
781 * Code to perform a heap census.
782 * -------------------------------------------------------------------------- */
784 heapCensusChain( Census *census, bdescr *bd )
794 for (; bd != NULL; bd = bd->link) {
796 while (p < bd->free) {
797 info = get_itbl((StgClosure *)p);
800 switch (info->type) {
806 case IND_OLDGEN_PERM:
808 case SE_CAF_BLACKHOLE:
813 case CONSTR_CHARLIKE:
827 size = sizeW_fromITBL(info);
838 size = sizeW_fromITBL(info);
841 case THUNK_1_0: /* ToDo - shouldn't be here */
842 case THUNK_0_1: /* " ditto " */
844 size = sizeofW(StgHeader) + MIN_UPD_SIZE;
849 size = pap_sizeW((StgPAP *)p);
854 size = arr_words_sizeW(stgCast(StgArrWords*,p));
858 case MUT_ARR_PTRS_FROZEN:
860 size = mut_arr_ptrs_sizeW((StgMutArrPtrs *)p);
865 size = tso_sizeW((StgTSO *)p);
874 #ifdef DEBUG_HEAP_PROF
877 // subtract the profiling overhead
878 real_size = size - sizeofW(StgProfHeader);
881 if (closureSatisfiesConstraints((StgClosure*)p)) {
883 if (RtsFlags.ProfFlags.doHeapProfile == HEAP_BY_LDV) {
885 census->prim += real_size;
886 else if ((LDVW(p) & LDV_STATE_MASK) == LDV_STATE_CREATE)
887 census->not_used += real_size;
889 census->used += real_size;
893 identity = closureIdentity((StgClosure *)p);
895 if (identity != NULL) {
896 ctr = lookupHashTable( census->hash, (StgWord)identity );
899 if (RtsFlags.ProfFlags.bioSelector != NULL) {
901 ctr->c.ldv.prim += real_size;
902 else if ((LDVW(p) & LDV_STATE_MASK) == LDV_STATE_CREATE)
903 ctr->c.ldv.not_used += real_size;
905 ctr->c.ldv.used += real_size;
909 ctr->c.resid += real_size;
912 ctr = arenaAlloc( census->arena, sizeof(counter) );
914 insertHashTable( census->hash, (StgWord)identity, ctr );
915 ctr->identity = identity;
916 ctr->next = census->ctrs;
920 if (RtsFlags.ProfFlags.bioSelector != NULL) {
922 ctr->c.ldv.prim = real_size;
923 else if ((LDVW(p) & LDV_STATE_MASK) == LDV_STATE_CREATE)
924 ctr->c.ldv.not_used = real_size;
926 ctr->c.ldv.used = real_size;
930 ctr->c.resid = real_size;
948 census = &censuses[era];
949 census->time = mut_user_time();
951 // calculate retainer sets if necessary
953 if (doingRetainerProfiling()) {
959 stat_startHeapCensus();
962 // traverse the heap, collecting the census info
963 heapCensusChain( census, small_alloc_list );
964 if (RtsFlags.GcFlags.generations == 1) {
965 heapCensusChain( census, g0s0->to_blocks );
967 for (g = 0; g < RtsFlags.GcFlags.generations; g++) {
968 for (s = 0; s < generations[g].n_steps; s++) {
969 heapCensusChain( census, generations[g].steps[s].blocks );
970 // Are we interested in large objects? might be
971 // confusing to include the stack in a heap profile.
972 // heapCensusChain( census, generations[g].steps[s].large_objects );
977 // dump out the census info
979 // We can't generate any info for LDV profiling until
980 // the end of the run...
981 if (!doingLDVProfiling())
982 dumpCensus( census );
984 dumpCensus( census );
988 // free our storage, unless we're keeping all the census info for
989 // future restriction by biography.
991 if (RtsFlags.ProfFlags.bioSelector == NULL)
994 freeHashTable( census->hash, NULL/* don't free the elements */ );
995 arenaFree( census->arena );
997 census->arena = NULL;
1000 // we're into the next time period now
1004 stat_endHeapCensus();
1008 #endif /* PROFILING || DEBUG_HEAP_PROF */