2 ##--------------------------------------------------------------------##
3 ##--- The cache simulation framework: instrumentation, recording ---##
4 ##--- and results printing. ---##
5 ##--- callgrind_annotate ---##
6 ##--------------------------------------------------------------------##
8 # This file is part of Callgrind, a cache-simulator and call graph
9 # tracer built on Valgrind.
11 # Copyright (C) 2003-2017 Josef Weidendorfer
12 # Josef.Weidendorfer@gmx.de
14 # This file is based heavily on cg_annotate, part of Valgrind.
15 # Copyright (C) 2002-2017 Nicholas Nethercote
18 # This program is free software; you can redistribute it and/or
19 # modify it under the terms of the GNU General Public License as
20 # published by the Free Software Foundation; either version 2 of the
21 # License, or (at your option) any later version.
23 # This program is distributed in the hope that it will be useful, but
24 # WITHOUT ANY WARRANTY; without even the implied warranty of
25 # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
26 # General Public License for more details.
28 # You should have received a copy of the GNU General Public License
29 # along with this program; if not, write to the Free Software
30 # Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA
33 # The GNU General Public License is contained in the file COPYING.
35 #----------------------------------------------------------------------------
36 # Annotator for cachegrind/callgrind.
38 # File format is described in /docs/techdocs.html.
40 # Performance improvements record, using cachegrind.out for cacheprof, doing no
41 # source annotation (irrelevant ones removed):
43 # 1. turned off warnings in add_hash_a_to_b() 3.81 --> 3.48s
44 # [now add_array_a_to_b()]
45 # 6. make line_to_CC() return a ref instead of a hash 3.01 --> 2.77s
47 #10. changed file format to avoid file/fn name repetition 2.40s
48 # (not sure why higher; maybe due to new '.' entries?)
49 #11. changed file format to drop unnecessary end-line "."s 2.36s
50 # (shrunk file by about 37%)
51 #12. switched from hash CCs to array CCs 1.61s
52 #13. only adding b[i] to a[i] if b[i] defined (was doing it if
53 # either a[i] or b[i] was defined, but if b[i] was undefined
54 # it just added 0) 1.48s
55 #14. Stopped converting "." entries to undef and then back 1.16s
56 #15. Using foreach $i (x..y) instead of for ($i = 0...) in
57 # add_array_a_to_b() 1.11s
59 # Auto-annotating primes:
60 #16. Finding count lengths by int((length-1)/3), not by
61 # commifying (halves the number of commify calls) 1.68s --> 1.47s
65 #----------------------------------------------------------------------------
66 # Overview: the running example in the comments is for:
70 #----------------------------------------------------------------------------
72 #----------------------------------------------------------------------------
73 # Global variables, main data structures
74 #----------------------------------------------------------------------------
75 # CCs are arrays, the counts corresponding to @events, with 'undef'
76 # representing '.'. This makes things fast (faster than using hashes for CCs)
77 # but we have to use @sort_order and @show_order below to handle the --sort and
78 # --show options, which is a bit tricky.
79 #----------------------------------------------------------------------------
81 # Total counts for summary (an array reference).
84 my $summary_calculated = 0;
86 # Totals for each function, for overall summary.
87 # hash(filename:fn_name => CC array)
90 # Individual CCs, organised by filename and line_num for easy annotation.
91 # hash(filename => hash(line_num => CC array))
94 # Files chosen for annotation on the command line.
95 # key = basename (trimmed of any directory), value = full filename
98 # Generic description string.
101 # Command line of profiled program.
104 # Info on the profiled process.
110 # Positions used for cost lines; default: line numbers
114 # Events in input file, eg. (A,B,C,D)
118 # Events to show, from command line, eg. (C,A,D)
121 # Map from @show_events indices to @events indices, eg. (2,0,3). Gives the
122 # order in which we must traverse @events in order to show the @show_events,
123 # eg. (@events[$show_order[1]], @events[$show_order[2]]...) = @show_events.
124 # (Might help to think of it like a hash (0 => 2, 1 => 0, 2 => 3).)
127 # Print out the function totals sorted by these events, eg. (D,C).
130 # Map from @sort_events indices to @events indices, eg. (3,2). Same idea as
134 # Thresholds, one for each sort event (or default to 1 if no sort events
135 # specified). We print out functions and do auto-annotations until we've
136 # handled this proportion of all the events thresholded.
139 my $default_threshold = 99;
141 my $single_threshold = $default_threshold;
143 # If on, show a percentage for each non-zero count.
146 # If on, automatically annotates all files that are involved in getting over
147 # all the threshold counts.
148 my $auto_annotate = 0;
150 # Number of lines to show around each annotated line.
153 # Directories in which to look for annotation files.
154 my @include_dirs = ("");
159 # Inclusive statistics (with subroutine events)
162 # Inclusive totals for each function, for overall summary.
163 # hash(filename:fn_name => CC array)
166 # hash( file:func => [ called file:func ])
169 # hash( file:func => [ calling file:func ])
172 # hash( file:func,line => [called file:func ])
173 my $called_from_line;
175 # hash( file:func,line => file:func
178 # hash (file:func => object name)
181 # Print out the callers of a function
184 # Print out the called functions
185 my $tree_calling = 0;
187 # hash( file:func,cfile:cfunc => call CC[])
190 # hash( file:func,cfile:cfunc => call counter)
193 # hash(context, index) => realname for compressed traces
196 # Input file name, will be set in process_cmd_line
200 my $version = "@VERSION@";
204 usage: callgrind_annotate [options] [callgrind-out-file [source-files...]]
206 options for the user, with defaults in [ ], are:
207 -h --help show this message
208 --version show version
209 --show=A,B,C only show figures for events A,B,C [all]
210 --sort=A,B,C sort columns by events A,B,C [event column order]
211 --threshold=<0--100> percentage of counts (of primary sort event) we
212 are interested in [$default_threshold%]
213 --show-percs=yes|no show a percentage for each non-zero count
214 --auto=yes|no annotate all source files containing functions
215 that helped reach the event count threshold [no]
216 --context=N print N lines of context before and after
218 --inclusive=yes|no add subroutine costs to functions calls [no]
219 --tree=none|caller| print for each function their callers,
220 calling|both the called functions or both [none]
221 -I --include=<dir> add <dir> to list of directories to search for
227 # Used in various places of output.
228 my $fancy = '-' x
80 . "\n";
233 return ($y == 0 ?
0 : $x / $y);
236 #-----------------------------------------------------------------------------
237 # Argument and option handling
238 #-----------------------------------------------------------------------------
239 sub process_cmd_line
()
241 for my $arg (@ARGV) {
247 if ($arg =~ /^--version$/) {
248 die("callgrind_annotate-$version\n");
251 } elsif ($arg =~ /^--show=(.*)$/) {
252 @show_events = split(/,/, $1);
255 } elsif ($arg =~ /^--sort=(.*)$/) {
256 @sort_events = split(/,/, $1);
257 my $th_specified = 0;
258 foreach my $i (0 .. scalar @sort_events - 1) {
259 if ($sort_events[$i] =~ /.*:([\d\.]+)%?$/) {
261 ($th >= 0 && $th <= 100) or die($usage);
262 $sort_events[$i] =~ s/:.*//;
263 $thresholds[$i] = $th;
269 if (not $th_specified) {
273 # --threshold=X (tolerates a trailing '%')
274 } elsif ($arg =~ /^--threshold=([\d\.]+)%?$/) {
275 $single_threshold = $1;
276 ($1 >= 0 && $1 <= 100) or die($usage);
278 # --show-percs=yes|no
279 } elsif ($arg =~ /^--show-percs=yes$/) {
281 } elsif ($arg =~ /^--show-percs=no$/) {
285 } elsif ($arg =~ /^--auto=(yes|no)$/) {
286 $auto_annotate = 1 if ($1 eq "yes");
287 $auto_annotate = 0 if ($1 eq "no");
290 } elsif ($arg =~ /^--context=([\d\.]+)$/) {
297 } elsif ($arg =~ /^--inclusive=(yes|no)$/) {
298 $inclusive = 1 if ($1 eq "yes");
299 $inclusive = 0 if ($1 eq "no");
301 # --tree=none|caller|calling|both
302 } elsif ($arg =~ /^--tree=(none|caller|calling|both)$/) {
303 $tree_caller = 1 if ($1 eq "caller" || $1 eq "both");
304 $tree_calling = 1 if ($1 eq "calling" || $1 eq "both");
307 } elsif ($arg =~ /^(-I|--include)=(.*)$/) {
309 $inc =~ s
|/$||; # trim trailing '/'
310 push(@include_dirs, "$inc/");
312 } else { # -h and --help fall under this case
316 # Argument handling -- annotation file checking and selection.
317 # Stick filenames into a hash for quick 'n easy lookup throughout
319 if ($input_file eq "") {
324 foreach my $include_dir (@include_dirs) {
325 if (-r
$include_dir . $arg) {
329 $readable or die("File $arg not found in any of: @include_dirs\n");
330 $user_ann_files{$arg} = 1;
335 if ($input_file eq "") {
336 $input_file = (<callgrind
.out
*>)[0];
337 if (!defined $input_file) {
338 $input_file = (<cachegrind
.out
*>)[0];
341 (defined $input_file) or die($usage);
342 print "Reading data from '$input_file'...\n";
346 #-----------------------------------------------------------------------------
347 # Reading of input file
348 #-----------------------------------------------------------------------------
352 return ($x > $y ?
$x : $y);
355 # Add the two arrays; any '.' entries are ignored. Two tricky things:
356 # 1. If $a2->[$i] is undefined, it defaults to 0 which is what we want; we turn
357 # off warnings to allow this. This makes things about 10% faster than
358 # checking for definedness ourselves.
359 # 2. We don't add an undefined count or a ".", even though it's value is 0,
360 # because we don't want to make an $a2->[$i] that is undef become 0
362 sub add_array_a_to_b
($$)
366 my $n = max
(scalar @
$a1, scalar @
$a2);
368 foreach my $i (0 .. $n-1) {
369 $a2->[$i] += $a1->[$i] if (defined $a1->[$i] && "." ne $a1->[$i]);
374 # Is this a line with all events zero?
379 foreach my $i (0 .. (scalar @
$CC)-1) {
380 $isZero = 0 if ($CC->[$i] >0);
385 # Add each event count to the CC array. '.' counts become undef, as do
386 # missing entries (implicitly).
389 my @CC = (split /\s+/, $_[0]);
390 (@CC <= @events) or die("Line $.: too many event counts\n");
394 sub uncompressed_name
($$)
396 my ($context, $name) = @_;
398 if ($name =~ /^\((\d+)\)\s*(.*)$/) {
402 if ($realname eq "") {
403 $realname = $compressed{$context,$index};
406 $compressed{$context,$index} = $realname;
413 sub read_input_file
()
415 open(INPUTFILE
, "< $input_file") || die "File $input_file not opened\n";
427 elsif (/^version:\s*(\d+)/) {
428 # Can't read format with major version > 1
429 ($1<2) or die("Can't read format with major version $1.\n");
432 elsif (/^pid:\s+(.*)$/) { $pid = $1; }
433 elsif (/^thread:\s+(.*)$/) { $thread = $1; }
434 elsif (/^part:\s+(.*)$/) { $part = $1; }
435 elsif (/^desc:\s+(.*)$/) {
437 # suppress profile options in description output
438 if ($dline =~ /^Option:/) {;}
439 else { $desc .= "$dline\n"; }
441 elsif (/^cmd:\s+(.*)$/) { $cmd = $1; }
442 elsif (/^creator:\s+(.*)$/) { $creator = $1; }
443 elsif (/^positions:\s+(.*)$/) {
445 $has_line = ($positions =~ /line/);
446 $has_addr = ($positions =~ /(addr|instr)/);
448 elsif (/^event:\s+.*$/) {
449 # ignore lines giving a long name to an event
451 elsif (/^events:\s+(.*)$/) {
454 # events line is last in header
458 warn("WARNING: header line $. malformed, ignoring\n");
459 if ($verbose) { chomp; warn(" line: '$_'\n"); }
463 # Read "events:" line. We make a temporary hash in which the Nth event's
464 # value is N, which is useful for handling --show/--sort options below.
465 ($events ne "") or die("Line $.: missing events line\n");
466 @events = split(/\s+/, $events);
469 foreach my $event (@events) {
470 $events{$event} = $n;
474 # If no --show arg give, default to showing all events in the file.
475 # If --show option is used, check all specified events appeared in the
476 # "events:" line. Then initialise @show_order.
478 foreach my $show_event (@show_events) {
479 (defined $events{$show_event}) or
480 die("--show event `$show_event' did not appear in input\n");
483 @show_events = @events;
485 foreach my $show_event (@show_events) {
486 push(@show_order, $events{$show_event});
489 # Do as for --show, but if no --sort arg given, default to sorting by
490 # column order (ie. first column event is primary sort key, 2nd column is
493 foreach my $sort_event (@sort_events) {
494 (defined $events{$sort_event}) or
495 die("--sort event `$sort_event' did not appear in input\n");
498 @sort_events = @events;
500 foreach my $sort_event (@sort_events) {
501 push(@sort_order, $events{$sort_event});
504 # If multiple threshold args weren't given via --sort, stick in the single
505 # threshold (either from --threshold if used, or the default otherwise) for
506 # the primary sort event, and 0% for the rest.
507 if (not @thresholds) {
508 foreach my $e (@sort_order) {
509 push(@thresholds, 0);
511 $thresholds[0] = $single_threshold;
514 # Current directory, used to strip from file names if absolute
523 my $curr_line_num = 0;
524 my $prev_line_num = 0;
530 my $curr_call_counter = 0;
531 my $curr_cfn_CC = [];
534 my $curr_file_ind_CCs = {}; # hash(line_num => CC)
536 # Read body of input file.
537 while (<INPUTFILE
>) {
538 $prev_line_num = $curr_line_num;
540 s/#.*$//; # remove comments
541 s/^\+(\d+)/$prev_line_num+$1/e;
542 s/^\-(\d+)/$prev_line_num-$1/e;
543 s/^\*/$prev_line_num/e;
544 if (s/^(-?\d+|0x\w+)\s+//) {
548 s/^\+(\d+)/$prev_line_num+$1/e;
549 s/^\-(\d+)/$prev_line_num-$1/e;
550 s/^\*/$prev_line_num/e;
552 if (s/^(\d+)\s+//) { $curr_line_num = $1; }
554 else { $curr_line_num = 0; }
556 my $CC = line_to_CC
($_);
558 if ($curr_call_counter>0) {
559 # print "Read ($curr_name => $curr_cname) $curr_call_counter\n";
561 if (!defined $call_CCs{$curr_name,$curr_cname}) {
562 $call_CCs{$curr_name,$curr_cname} = [];
563 $call_counter{$curr_name,$curr_cname} = 0;
565 add_array_a_to_b
($CC, $call_CCs{$curr_name,$curr_cname});
566 $call_counter{$curr_name,$curr_cname} += $curr_call_counter;
568 my $tmp = $called_from_line->{$curr_file,$curr_line_num};
570 $func_of_line{$curr_file,$curr_line_num} = $curr_name;
572 $tmp = {} unless defined $tmp;
573 $$tmp{$curr_cname} = 1;
574 $called_from_line->{$curr_file,$curr_line_num} = $tmp;
575 if (!defined $call_CCs{$curr_name,$curr_cname,$curr_line_num}) {
576 $call_CCs{$curr_name,$curr_cname,$curr_line_num} = [];
577 $call_counter{$curr_name,$curr_cname,$curr_line_num} = 0;
579 add_array_a_to_b
($CC, $call_CCs{$curr_name,$curr_cname,$curr_line_num});
580 $call_counter{$curr_name,$curr_cname,$curr_line_num} += $curr_call_counter;
582 $curr_call_counter = 0;
585 $curr_cfn_CC = $cfn_totals{$curr_cname};
586 $curr_cfn_CC = [] unless (defined $curr_cfn_CC);
587 add_array_a_to_b
($CC, $curr_cfn_CC);
588 $cfn_totals{$curr_cname} = $curr_cfn_CC;
591 add_array_a_to_b
($CC, $curr_fn_CC);
596 add_array_a_to_b
($CC, $curr_fn_CC);
598 # If curr_file is selected, add CC to curr_file list. We look for
599 # full filename matches; or, if auto-annotating, we have to
600 # remember everything -- we won't know until the end what's needed.
601 if ($auto_annotate || defined $user_ann_files{$curr_file}) {
602 my $tmp = $curr_file_ind_CCs->{$curr_line_num};
603 $tmp = [] unless defined $tmp;
604 add_array_a_to_b
($CC, $tmp);
605 $curr_file_ind_CCs->{$curr_line_num} = $tmp;
608 } elsif (s/^fn=(.*)$//) {
609 # Commit result from previous function
610 $fn_totals{$curr_name} = $curr_fn_CC if (defined $curr_name);
613 $curr_fn = uncompressed_name
("fn",$1);
614 $curr_name = "$curr_file:$curr_fn";
615 $obj_name{$curr_name} = $curr_obj;
616 $curr_fn_CC = $fn_totals{$curr_name};
617 $curr_fn_CC = [] unless (defined $curr_fn_CC);
619 } elsif (s/^ob=(.*)$//) {
620 $curr_obj = uncompressed_name
("ob",$1);
622 } elsif (s/^fl=(.*)$//) {
623 $all_ind_CCs{$curr_file} = $curr_file_ind_CCs
624 if (defined $curr_file);
626 $curr_file = uncompressed_name
("fl",$1);
627 $curr_file =~ s/^\Q$pwd\E//;
628 $curr_file_ind_CCs = $all_ind_CCs{$curr_file};
629 $curr_file_ind_CCs = {} unless (defined $curr_file_ind_CCs);
631 } elsif (s/^(fi|fe)=(.*)$//) {
632 (defined $curr_name) or die("Line $.: Unexpected fi/fe line\n");
633 $fn_totals{$curr_name} = $curr_fn_CC;
634 $all_ind_CCs{$curr_file} = $curr_file_ind_CCs;
636 $curr_file = uncompressed_name
("fl",$2);
637 $curr_file =~ s/^\Q$pwd\E//;
638 $curr_name = "$curr_file:$curr_fn";
639 $curr_file_ind_CCs = $all_ind_CCs{$curr_file};
640 $curr_file_ind_CCs = {} unless (defined $curr_file_ind_CCs);
641 $curr_fn_CC = $fn_totals{$curr_name};
642 $curr_fn_CC = [] unless (defined $curr_fn_CC);
644 } elsif (s/^\s*$//) {
647 } elsif (s/^cob=(.*)$//) {
648 $curr_cobj = uncompressed_name
("ob",$1);
650 } elsif (s/^cf[il]=(.*)$//) {
651 $curr_cfile = uncompressed_name
("fl",$1);
653 } elsif (s/^cfn=(.*)$//) {
654 $curr_cfunc = uncompressed_name
("fn",$1);
655 if ($curr_cfile eq "") {
656 $curr_cname = "$curr_file:$curr_cfunc";
659 $curr_cname = "$curr_cfile:$curr_cfunc";
663 my $tmp = $calling_funcs->{$curr_cname};
664 $tmp = {} unless defined $tmp;
665 $$tmp{$curr_name} = 1;
666 $calling_funcs->{$curr_cname} = $tmp;
668 my $tmp2 = $called_funcs->{$curr_name};
669 $tmp2 = {} unless defined $tmp2;
670 $$tmp2{$curr_cname} = 1;
671 $called_funcs->{$curr_name} = $tmp2;
673 } elsif (s/^calls=(\d+)//) {
674 $curr_call_counter = $1;
676 } elsif (s/^(jump|jcnd)=//) {
677 #ignore jump information
679 } elsif (s/^jfi=(.*)$//) {
680 # side effect needed: possibly add compression mapping
681 uncompressed_name
("fl",$1);
682 # ignore jump information
684 } elsif (s/^jfn=(.*)$//) {
685 # side effect needed: possibly add compression mapping
686 uncompressed_name
("fn",$1);
687 # ignore jump information
689 } elsif (s/^totals:\s+//) {
690 $totals_CC = line_to_CC
($_);
692 } elsif (s/^summary:\s+//) {
693 $summary_CC = line_to_CC
($_);
696 warn("WARNING: line $. malformed, ignoring\n");
697 if ($verbose) { chomp; warn(" line: '$_'\n"); }
701 # Finish up handling final filename/fn_name counts
702 $fn_totals{"$curr_file:$curr_fn"} = $curr_fn_CC
703 if (defined $curr_file && defined $curr_fn);
704 $all_ind_CCs{$curr_file} =
705 $curr_file_ind_CCs if (defined $curr_file);
707 # Correct inclusive totals
709 foreach my $name (keys %cfn_totals) {
710 $fn_totals{$name} = $cfn_totals{$name};
716 if ((not defined $summary_CC) || is_zero
($summary_CC)) {
717 $summary_CC = $totals_CC;
719 # if neither 'summary:' nor 'totals:' line is given,
720 # calculate summary from fn_totals hash
721 if ((not defined $summary_CC) || is_zero
($summary_CC)) {
722 $summary_calculated = 1;
724 foreach my $name (keys %fn_totals) {
725 add_array_a_to_b
($fn_totals{$name}, $summary_CC);
731 #-----------------------------------------------------------------------------
733 #-----------------------------------------------------------------------------
737 print "Profile data file '$input_file'";
738 if ($creator ne "") { print " (creator: $creator)"; }
744 if ($target eq "") { $target = "(unknown)"; }
746 $target .= " (PID $pid";
747 if ($part ne "") { $target .= ", part $part"; }
748 if ($thread ne "") { $target .= ", thread $thread"; }
751 print("Profiled target: $target\n");
752 print("Events recorded: @events\n");
753 print("Events shown: @show_events\n");
754 print("Event sort order: @sort_events\n");
755 print("Thresholds: @thresholds\n");
757 my @include_dirs2 = @include_dirs; # copy @include_dirs
758 shift(@include_dirs2); # remove "" entry, which is always the first
759 unshift(@include_dirs2, "") if (0 == @include_dirs2);
760 my $include_dir = shift(@include_dirs2);
761 print("Include dirs: $include_dir\n");
762 foreach my $include_dir (@include_dirs2) {
763 print(" $include_dir\n");
766 my @user_ann_files = keys %user_ann_files;
767 unshift(@user_ann_files, "") if (0 == @user_ann_files);
768 my $user_ann_file = shift(@user_ann_files);
769 print("User annotated: $user_ann_file\n");
770 foreach $user_ann_file (@user_ann_files) {
771 print(" $user_ann_file\n");
774 my $is_on = ($auto_annotate ?
"on" : "off");
775 print("Auto-annotation: $is_on\n");
779 #-----------------------------------------------------------------------------
780 # Print summary and sorted function totals
781 #-----------------------------------------------------------------------------
786 # Iterate through sort events (eg. 3,2); return result if two are different
787 foreach my $i (@sort_order) {
791 $x = -1 unless defined $x;
792 $y = -1 unless defined $y;
794 my $cmp = $y <=> $x; # reverse sort
799 # Exhausted events, equal
805 1 while ($val =~ s/^(\d+)(\d{3})/$1,$2/);
809 # Because the counts can get very big, and we don't want to waste screen space
810 # and make lines too long, we compute exactly how wide each column needs to be
811 # by finding the widest entry for each one.
812 sub compute_CC_col_widths
(@
)
815 my $CC_col_widths = [];
817 # Initialise with minimum widths (from event names)
818 foreach my $event (@events) {
819 push(@
$CC_col_widths, length($event));
822 # Find maximum width count for each column. @CC_col_width positions
823 # correspond to @CC positions.
824 foreach my $CC (@CCs) {
825 foreach my $i (0 .. scalar(@
$CC)-1) {
826 if (defined $CC->[$i]) {
827 # Find length, accounting for commas that will be added, and
828 # possibly a percentage.
829 my $length = length $CC->[$i];
830 my $width = $length + int(($length - 1) / 3);
832 $width += 9; # e.g. " (12.34%)" is 9 chars
834 $CC_col_widths->[$i] = max
($CC_col_widths->[$i], $width);
838 return $CC_col_widths;
841 # Print the CC with each column's size dictated by $CC_col_widths.
844 my ($CC, $CC_col_widths) = @_;
846 foreach my $i (@show_order) {
847 my $count = (defined $CC->[$i] ? commify
($CC->[$i]) : ".");
851 if (defined $CC->[$i] && $CC->[$i] != 0) {
852 # Try our best to keep the number fitting into 5 chars. This
853 # requires dropping a digit after the decimal place if it's
854 # sufficiently negative (e.g. "-10.0") or positive (e.g.
855 # "100.0"). Thanks to diffs it's possible to have even more
856 # extreme values, like "-100.0" or "1000.0"; those rare case
857 # will end up with slightly wrong indenting, oh well.
858 $perc = safe_div
($CC->[$i] * 100, $summary_CC->[$i]);
859 $perc = (-9.995 < $perc && $perc < 99.995)
860 ?
sprintf(" (%5.2f%%)", $perc)
861 : sprintf(" (%5.1f%%)", $perc);
863 # Don't show percentages for "." and "0" entries.
868 # $reps will be negative for the extreme values mentioned above. The
869 # use of max() avoids a possible warning about a negative repeat count.
870 my $text = $count . $perc;
871 my $len = length($text);
872 my $reps = $CC_col_widths->[$i] - length($text);
873 my $space = ' ' x max
($reps, 0);
874 print("$space$text ");
880 my ($CC_col_widths) = @_;
882 foreach my $i (@show_order) {
883 my $event = $events[$i];
884 my $event_width = length($event);
885 my $col_width = $CC_col_widths->[$i];
886 my $space = ' ' x
($col_width - $event_width);
887 print("$event$space ");
891 # Prints summary and function totals (with separate column widths, so that
892 # function names aren't pushed over unnecessarily by huge summary figures).
893 # Also returns a hash containing all the files that are involved in getting the
894 # events count above the thresholds (ie. all the interesting ones).
895 sub print_summary_and_fn_totals
()
897 my @fn_fullnames = keys %fn_totals;
899 # Work out the size of each column for printing (summary and functions
901 my $summary_CC_col_widths = compute_CC_col_widths
($summary_CC);
902 my $fn_CC_col_widths = compute_CC_col_widths
(values %fn_totals);
904 # Header and counts for summary
906 print_events
($summary_CC_col_widths);
909 print_CC
($summary_CC, $summary_CC_col_widths);
910 print(" PROGRAM TOTALS");
911 if ($summary_calculated) {
912 print(" (calculated)");
916 # Header for functions
918 print_events
($fn_CC_col_widths);
919 print(" file:function\n");
922 # Sort function names into order dictated by --sort option.
923 @fn_fullnames = sort {
924 mycmp
($fn_totals{$a}, $fn_totals{$b})
929 (scalar @sort_order == scalar @thresholds) or
930 die("sort_order length != thresholds length:\n",
931 " @sort_order\n @thresholds\n");
933 my $threshold_files = {};
934 # @curr_totals has the same shape as @sort_order and @thresholds
935 my @curr_totals = ();
936 foreach my $e (@thresholds) {
937 push(@curr_totals, 0);
940 # Print functions, stopping when the threshold has been reached.
941 foreach my $fn_name (@fn_fullnames) {
943 # Stop when we've reached all the thresholds
944 my $reached_all_thresholds = 1;
945 foreach my $i (0 .. scalar @thresholds - 1) {
946 my $prop = $curr_totals[$i] * 100;
947 if ($summary_CC->[$sort_order[$i]] >0) {
948 $prop = $prop / $summary_CC->[$sort_order[$i]];
950 $reached_all_thresholds &&= ($prop >= $thresholds[$i]);
952 last if $reached_all_thresholds;
954 if ($tree_caller || $tree_calling) { print "\n"; }
956 if ($tree_caller && ($fn_name ne "???:???")) {
957 # Print function callers
958 my $tmp1 = $calling_funcs->{$fn_name};
960 # Sort calling functions into order dictated by --sort option.
961 my @callings = sort {
962 mycmp
($call_CCs{$a,$fn_name}, $call_CCs{$b,$fn_name})
964 foreach my $calling (@callings) {
965 if (defined $call_counter{$calling,$fn_name}) {
966 print_CC
($call_CCs{$calling,$fn_name}, $fn_CC_col_widths);
967 print" < $calling (";
968 print commify
($call_counter{$calling,$fn_name}) . "x)";
969 if (defined $obj_name{$calling}) {
970 print " [$obj_name{$calling}]";
978 # Print function results
979 my $fn_CC = $fn_totals{$fn_name};
980 print_CC
($fn_CC, $fn_CC_col_widths);
981 if ($tree_caller || $tree_calling) { print " * "; }
983 if ((defined $obj_name{$fn_name}) &&
984 ($obj_name{$fn_name} ne "")) {
985 print " [$obj_name{$fn_name}]";
989 if ($tree_calling && ($fn_name ne "???:???")) {
990 # Print called functions
991 my $tmp2 = $called_funcs->{$fn_name};
993 # Sort called functions into order dictated by --sort option.
995 mycmp
($call_CCs{$fn_name,$a}, $call_CCs{$fn_name,$b})
997 foreach my $called (@calleds) {
998 if (defined $call_counter{$fn_name,$called}) {
999 print_CC
($call_CCs{$fn_name,$called}, $fn_CC_col_widths);
1000 print" > $called (";
1001 print commify
($call_counter{$fn_name,$called}) . "x)";
1002 if (defined $obj_name{$called}) {
1003 print " [$obj_name{$called}]";
1011 # Update the threshold counts
1012 my $filename = $fn_name;
1013 $filename =~ s/:.+$//; # remove function name
1014 $threshold_files->{$filename} = 1;
1015 foreach my $i (0 .. scalar @sort_order - 1) {
1017 $curr_totals[$i] = $summary_CC->[$sort_order[$i]] -
1018 $fn_CC->[$sort_order[$i]]
1019 if (defined $fn_CC->[$sort_order[$i]]);
1021 $curr_totals[$i] += $fn_CC->[$sort_order[$i]]
1022 if (defined $fn_CC->[$sort_order[$i]]);
1028 return $threshold_files;
1031 #-----------------------------------------------------------------------------
1032 # Annotate selected files
1033 #-----------------------------------------------------------------------------
1035 # Issue a warning that the source file is more recent than the input file.
1036 sub warning_on_src_more_recent_than_inputfile
($)
1038 my $src_file = $_[0];
1041 @@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@
1042 @@ WARNING @@ WARNING @@ WARNING @@ WARNING @@ WARNING @@ WARNING @@ WARNING @@
1043 @@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@
1044 @ Source file '$src_file' is more recent than input file '$input_file'.
1045 @ Annotations may not be correct.
1046 @@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@
1053 # If there is information about lines not in the file, issue a warning
1054 # explaining possible causes.
1055 sub warning_on_nonexistent_lines
($$$)
1057 my ($src_more_recent_than_inputfile, $src_file, $excess_line_nums) = @_;
1058 my $cause_and_solution;
1060 if ($src_more_recent_than_inputfile) {
1061 $cause_and_solution = <<END
1062 @@ cause: '$src_file' has changed since information was gathered.
1063 @@ If so, a warning will have already been issued about this.
1064 @@ solution: Recompile program and rerun under "valgrind --cachesim=yes" to
1065 @@ gather new information.
1067 # We suppress warnings about .h files
1068 } elsif ($src_file =~ /\.h$/) {
1069 $cause_and_solution = <<END
1070 @@ cause: bug in the Valgrind's debug info reader that screws up with .h
1072 @@ solution: none, sorry
1075 $cause_and_solution = <<END
1076 @@ cause: not sure, sorry
1081 @@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@
1082 @@ WARNING @@ WARNING @@ WARNING @@ WARNING @@ WARNING @@ WARNING @@ WARNING @@
1083 @@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@
1085 @@ Information recorded about lines past the end of '$src_file'.
1087 @@ Probable cause and solution:
1088 $cause_and_solution@@
1089 @@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@
1095 sub annotate_ann_files
($)
1097 my ($threshold_files) = @_;
1100 my @unfound_auto_annotate_files;
1101 my $printed_totals_CC = [];
1103 # If auto-annotating, add interesting files (but not "???")
1104 if ($auto_annotate) {
1105 delete $threshold_files->{"???"};
1106 %all_ann_files = (%user_ann_files, %$threshold_files)
1108 %all_ann_files = %user_ann_files;
1111 # Track if we did any annotations.
1112 my $did_annotations = 0;
1115 foreach my $src_file (keys %all_ann_files) {
1117 my $opened_file = "";
1118 my $full_file_name = "";
1119 foreach my $include_dir (@include_dirs) {
1120 my $try_name = $include_dir . $src_file;
1121 if (open(INPUTFILE
, "< $try_name")) {
1122 $opened_file = $try_name;
1123 $full_file_name = ($include_dir eq ""
1125 : "$include_dir + $src_file");
1130 if (not $opened_file) {
1131 # Failed to open the file. If chosen on the command line, die.
1132 # If arose from auto-annotation, print a little message.
1133 if (defined $user_ann_files{$src_file}) {
1134 die("File $src_file not opened in any of: @include_dirs\n");
1137 push(@unfound_auto_annotate_files, $src_file);
1141 # File header (distinguish between user- and auto-selected files).
1144 (defined $user_ann_files{$src_file} ?
"User" : "Auto");
1145 print("-- $ann_type-annotated source: $full_file_name\n");
1149 my $src_file_CCs = $all_ind_CCs{$src_file};
1150 if (!defined $src_file_CCs) {
1151 print(" No information has been collected for $src_file\n\n");
1155 $did_annotations = 1;
1157 # Numeric, not lexicographic sort!
1158 my @line_nums = sort {$a <=> $b} keys %$src_file_CCs;
1160 # If $src_file more recent than cachegrind.out, issue warning
1161 my $src_more_recent_than_inputfile = 0;
1162 if ((stat $opened_file)[9] > (stat $input_file)[9]) {
1163 $src_more_recent_than_inputfile = 1;
1164 warning_on_src_more_recent_than_inputfile
($src_file);
1167 # Work out the size of each column for printing
1168 my $CC_col_widths = compute_CC_col_widths
(values %$src_file_CCs);
1171 print_events
($CC_col_widths);
1174 # Shift out 0 if it's in the line numbers (from unknown entries,
1175 # likely due to bugs in Valgrind's stabs debug info reader)
1176 shift(@line_nums) if (0 == $line_nums[0]);
1178 # Finds interesting line ranges -- all lines with a CC, and all
1179 # lines within $context lines of a line with a CC.
1182 for (my $i = 0; $i < $n; $i++) {
1183 push(@pairs, $line_nums[$i] - $context); # lower marker
1185 $line_nums[$i] + 2*$context >= $line_nums[$i+1]) {
1188 push(@pairs, $line_nums[$i] + $context); # upper marker
1191 # Annotate chosen lines, tracking total counts of lines printed
1192 $pairs[0] = 1 if ($pairs[0] < 1);
1194 my $low = shift @pairs;
1195 my $high = shift @pairs;
1196 while ($. < $low-1) {
1197 my $tmp = <INPUTFILE
>;
1198 last unless (defined $tmp); # hack to detect EOF
1201 # Print line number, unless start of file
1202 print("-- line $low " . '-' x
40 . "\n") if ($low != 1);
1203 while (($. < $high) && ($src_line = <INPUTFILE
>)) {
1204 if (defined $line_nums[0] && $. == $line_nums[0]) {
1205 print_CC
($src_file_CCs->{$.}, $CC_col_widths);
1206 add_array_a_to_b
($src_file_CCs->{$.},
1207 $printed_totals_CC);
1211 print_CC
([], $CC_col_widths);
1214 print(" $src_line");
1216 my $tmp = $called_from_line->{$src_file,$.};
1217 my $func = $func_of_line{$src_file,$.};
1219 # Sort called functions into order dictated by --sort option.
1220 my @calleds = sort {
1221 mycmp
($call_CCs{$func,$a}, $call_CCs{$func,$b})
1223 foreach my $called (@calleds) {
1224 if (defined $call_CCs{$func,$called,$.}) {
1225 print_CC
($call_CCs{$func,$called,$.}, $CC_col_widths);
1226 print " => $called (";
1227 print commify
($call_counter{$func,$called,$.}) . "x)\n";
1232 # Print line number, unless EOF
1234 print("-- line $high " . '-' x
40 . "\n");
1240 # If there was info on lines past the end of the file...
1242 foreach my $line_num (@line_nums) {
1243 print_CC
($src_file_CCs->{$line_num}, $CC_col_widths);
1244 print(" <bogus line $line_num>\n");
1247 warning_on_nonexistent_lines
($src_more_recent_than_inputfile,
1248 $src_file, \
@line_nums);
1252 # Print summary of counts attributed to file but not to any
1253 # particular line (due to incomplete debug info).
1254 if ($src_file_CCs->{0}) {
1255 print_CC
($src_file_CCs->{0}, $CC_col_widths);
1256 print(" <counts for unidentified lines in $src_file>\n\n");
1263 # Print list of unfound auto-annotate selected files.
1264 if (@unfound_auto_annotate_files) {
1266 print("The following files chosen for auto-annotation could not be found:\n");
1268 foreach my $f (sort @unfound_auto_annotate_files) {
1274 # If we did any annotating, show how many events were covered by annotated
1276 if ($did_annotations) {
1277 foreach (my $i = 0; $i < @
$summary_CC; $i++) {
1278 # Some files (in particular the files produced by --xtree-memory)
1279 # have non additive self costs, so have a special case for these
1280 # to print all functions and also to avoid a division by 0.
1281 if ($summary_CC->[$i] == 0
1282 || $printed_totals_CC->[$i] > $summary_CC->[$i]) {
1283 # Set the summary_CC value equal to the printed_totals_CC value
1284 # so that the percentage printed by the print_CC call below is
1285 # 100%. This is ok because the summary_CC value is not used
1287 $summary_CC->[$i] = $printed_totals_CC->[$i];
1290 my $CC_col_widths = compute_CC_col_widths
($printed_totals_CC);
1292 print_events
($CC_col_widths);
1295 print_CC
($printed_totals_CC, $CC_col_widths);
1296 print(" events annotated\n\n");
1300 #----------------------------------------------------------------------------
1302 #----------------------------------------------------------------------------
1306 my $threshold_files = print_summary_and_fn_totals
();
1307 annotate_ann_files
($threshold_files);
1309 ##--------------------------------------------------------------------##
1310 ##--- end vg_annotate.in ---##
1311 ##--------------------------------------------------------------------##