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