Minor reformatting.
[official-gcc.git] / gcc / profile.c
blob39c81d4fbafeb8bd9e6cc1144a1a992bb5fd3ce4
1 /* Calculate branch probabilities, and basic block execution counts.
2 Copyright (C) 1990-2016 Free Software Foundation, Inc.
3 Contributed by James E. Wilson, UC Berkeley/Cygnus Support;
4 based on some ideas from Dain Samples of UC Berkeley.
5 Further mangling by Bob Manson, Cygnus Support.
7 This file is part of GCC.
9 GCC is free software; you can redistribute it and/or modify it under
10 the terms of the GNU General Public License as published by the Free
11 Software Foundation; either version 3, or (at your option) any later
12 version.
14 GCC is distributed in the hope that it will be useful, but WITHOUT ANY
15 WARRANTY; without even the implied warranty of MERCHANTABILITY or
16 FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
17 for more details.
19 You should have received a copy of the GNU General Public License
20 along with GCC; see the file COPYING3. If not see
21 <http://www.gnu.org/licenses/>. */
23 /* Generate basic block profile instrumentation and auxiliary files.
24 Profile generation is optimized, so that not all arcs in the basic
25 block graph need instrumenting. First, the BB graph is closed with
26 one entry (function start), and one exit (function exit). Any
27 ABNORMAL_EDGE cannot be instrumented (because there is no control
28 path to place the code). We close the graph by inserting fake
29 EDGE_FAKE edges to the EXIT_BLOCK, from the sources of abnormal
30 edges that do not go to the exit_block. We ignore such abnormal
31 edges. Naturally these fake edges are never directly traversed,
32 and so *cannot* be directly instrumented. Some other graph
33 massaging is done. To optimize the instrumentation we generate the
34 BB minimal span tree, only edges that are not on the span tree
35 (plus the entry point) need instrumenting. From that information
36 all other edge counts can be deduced. By construction all fake
37 edges must be on the spanning tree. We also attempt to place
38 EDGE_CRITICAL edges on the spanning tree.
40 The auxiliary files generated are <dumpbase>.gcno (at compile time)
41 and <dumpbase>.gcda (at run time). The format is
42 described in full in gcov-io.h. */
44 /* ??? Register allocation should use basic block execution counts to
45 give preference to the most commonly executed blocks. */
47 /* ??? Should calculate branch probabilities before instrumenting code, since
48 then we can use arc counts to help decide which arcs to instrument. */
50 #include "config.h"
51 #include "system.h"
52 #include "coretypes.h"
53 #include "backend.h"
54 #include "rtl.h"
55 #include "tree.h"
56 #include "gimple.h"
57 #include "cfghooks.h"
58 #include "cgraph.h"
59 #include "coverage.h"
60 #include "diagnostic-core.h"
61 #include "cfganal.h"
62 #include "value-prof.h"
63 #include "gimple-iterator.h"
64 #include "tree-cfg.h"
65 #include "dumpfile.h"
67 #include "profile.h"
69 struct bb_profile_info {
70 unsigned int count_valid : 1;
72 /* Number of successor and predecessor edges. */
73 gcov_type succ_count;
74 gcov_type pred_count;
77 #define BB_INFO(b) ((struct bb_profile_info *) (b)->aux)
80 /* Counter summary from the last set of coverage counts read. */
82 const struct gcov_ctr_summary *profile_info;
84 /* Counter working set information computed from the current counter
85 summary. Not initialized unless profile_info summary is non-NULL. */
86 static gcov_working_set_t gcov_working_sets[NUM_GCOV_WORKING_SETS];
88 /* Collect statistics on the performance of this pass for the entire source
89 file. */
91 static int total_num_blocks;
92 static int total_num_edges;
93 static int total_num_edges_ignored;
94 static int total_num_edges_instrumented;
95 static int total_num_blocks_created;
96 static int total_num_passes;
97 static int total_num_times_called;
98 static int total_hist_br_prob[20];
99 static int total_num_branches;
101 /* Helper function to update gcov_working_sets. */
103 void add_working_set (gcov_working_set_t *set) {
104 int i = 0;
105 for (; i < NUM_GCOV_WORKING_SETS; i++)
106 gcov_working_sets[i] = set[i];
109 /* Forward declarations. */
110 static void find_spanning_tree (struct edge_list *);
112 /* Add edge instrumentation code to the entire insn chain.
114 F is the first insn of the chain.
115 NUM_BLOCKS is the number of basic blocks found in F. */
117 static unsigned
118 instrument_edges (struct edge_list *el)
120 unsigned num_instr_edges = 0;
121 int num_edges = NUM_EDGES (el);
122 basic_block bb;
124 FOR_BB_BETWEEN (bb, ENTRY_BLOCK_PTR_FOR_FN (cfun), NULL, next_bb)
126 edge e;
127 edge_iterator ei;
129 FOR_EACH_EDGE (e, ei, bb->succs)
131 struct edge_profile_info *inf = EDGE_INFO (e);
133 if (!inf->ignore && !inf->on_tree)
135 gcc_assert (!(e->flags & EDGE_ABNORMAL));
136 if (dump_file)
137 fprintf (dump_file, "Edge %d to %d instrumented%s\n",
138 e->src->index, e->dest->index,
139 EDGE_CRITICAL_P (e) ? " (and split)" : "");
140 gimple_gen_edge_profiler (num_instr_edges++, e);
145 total_num_blocks_created += num_edges;
146 if (dump_file)
147 fprintf (dump_file, "%d edges instrumented\n", num_instr_edges);
148 return num_instr_edges;
151 /* Add code to measure histograms for values in list VALUES. */
152 static void
153 instrument_values (histogram_values values)
155 unsigned i;
157 /* Emit code to generate the histograms before the insns. */
159 for (i = 0; i < values.length (); i++)
161 histogram_value hist = values[i];
162 unsigned t = COUNTER_FOR_HIST_TYPE (hist->type);
164 if (!coverage_counter_alloc (t, hist->n_counters))
165 continue;
167 switch (hist->type)
169 case HIST_TYPE_INTERVAL:
170 gimple_gen_interval_profiler (hist, t, 0);
171 break;
173 case HIST_TYPE_POW2:
174 gimple_gen_pow2_profiler (hist, t, 0);
175 break;
177 case HIST_TYPE_SINGLE_VALUE:
178 gimple_gen_one_value_profiler (hist, t, 0);
179 break;
181 case HIST_TYPE_CONST_DELTA:
182 gimple_gen_const_delta_profiler (hist, t, 0);
183 break;
185 case HIST_TYPE_INDIR_CALL:
186 case HIST_TYPE_INDIR_CALL_TOPN:
187 gimple_gen_ic_profiler (hist, t, 0);
188 break;
190 case HIST_TYPE_AVERAGE:
191 gimple_gen_average_profiler (hist, t, 0);
192 break;
194 case HIST_TYPE_IOR:
195 gimple_gen_ior_profiler (hist, t, 0);
196 break;
198 case HIST_TYPE_TIME_PROFILE:
200 basic_block bb =
201 split_edge (single_succ_edge (ENTRY_BLOCK_PTR_FOR_FN (cfun)));
202 gimple_stmt_iterator gsi = gsi_start_bb (bb);
204 gimple_gen_time_profiler (t, 0, gsi);
205 break;
208 default:
209 gcc_unreachable ();
215 /* Fill the working set information into the profile_info structure. */
217 void
218 get_working_sets (void)
220 unsigned ws_ix, pctinc, pct;
221 gcov_working_set_t *ws_info;
223 if (!profile_info)
224 return;
226 compute_working_sets (profile_info, gcov_working_sets);
228 if (dump_file)
230 fprintf (dump_file, "Counter working sets:\n");
231 /* Multiply the percentage by 100 to avoid float. */
232 pctinc = 100 * 100 / NUM_GCOV_WORKING_SETS;
233 for (ws_ix = 0, pct = pctinc; ws_ix < NUM_GCOV_WORKING_SETS;
234 ws_ix++, pct += pctinc)
236 if (ws_ix == NUM_GCOV_WORKING_SETS - 1)
237 pct = 9990;
238 ws_info = &gcov_working_sets[ws_ix];
239 /* Print out the percentage using int arithmatic to avoid float. */
240 fprintf (dump_file, "\t\t%u.%02u%%: num counts=%u, min counter="
241 "%" PRId64 "\n",
242 pct / 100, pct - (pct / 100 * 100),
243 ws_info->num_counters,
244 (int64_t)ws_info->min_counter);
249 /* Given a the desired percentage of the full profile (sum_all from the
250 summary), multiplied by 10 to avoid float in PCT_TIMES_10, returns
251 the corresponding working set information. If an exact match for
252 the percentage isn't found, the closest value is used. */
254 gcov_working_set_t *
255 find_working_set (unsigned pct_times_10)
257 unsigned i;
258 if (!profile_info)
259 return NULL;
260 gcc_assert (pct_times_10 <= 1000);
261 if (pct_times_10 >= 999)
262 return &gcov_working_sets[NUM_GCOV_WORKING_SETS - 1];
263 i = pct_times_10 * NUM_GCOV_WORKING_SETS / 1000;
264 if (!i)
265 return &gcov_working_sets[0];
266 return &gcov_working_sets[i - 1];
269 /* Computes hybrid profile for all matching entries in da_file.
271 CFG_CHECKSUM is the precomputed checksum for the CFG. */
273 static gcov_type *
274 get_exec_counts (unsigned cfg_checksum, unsigned lineno_checksum)
276 unsigned num_edges = 0;
277 basic_block bb;
278 gcov_type *counts;
280 /* Count the edges to be (possibly) instrumented. */
281 FOR_BB_BETWEEN (bb, ENTRY_BLOCK_PTR_FOR_FN (cfun), NULL, next_bb)
283 edge e;
284 edge_iterator ei;
286 FOR_EACH_EDGE (e, ei, bb->succs)
287 if (!EDGE_INFO (e)->ignore && !EDGE_INFO (e)->on_tree)
288 num_edges++;
291 counts = get_coverage_counts (GCOV_COUNTER_ARCS, num_edges, cfg_checksum,
292 lineno_checksum, &profile_info);
293 if (!counts)
294 return NULL;
296 get_working_sets ();
298 if (dump_file && profile_info)
299 fprintf (dump_file, "Merged %u profiles with maximal count %u.\n",
300 profile_info->runs, (unsigned) profile_info->sum_max);
302 return counts;
306 static bool
307 is_edge_inconsistent (vec<edge, va_gc> *edges)
309 edge e;
310 edge_iterator ei;
311 FOR_EACH_EDGE (e, ei, edges)
313 if (!EDGE_INFO (e)->ignore)
315 if (e->count < 0
316 && (!(e->flags & EDGE_FAKE)
317 || !block_ends_with_call_p (e->src)))
319 if (dump_file)
321 fprintf (dump_file,
322 "Edge %i->%i is inconsistent, count%" PRId64,
323 e->src->index, e->dest->index, e->count);
324 dump_bb (dump_file, e->src, 0, TDF_DETAILS);
325 dump_bb (dump_file, e->dest, 0, TDF_DETAILS);
327 return true;
331 return false;
334 static void
335 correct_negative_edge_counts (void)
337 basic_block bb;
338 edge e;
339 edge_iterator ei;
341 FOR_BB_BETWEEN (bb, ENTRY_BLOCK_PTR_FOR_FN (cfun), NULL, next_bb)
343 FOR_EACH_EDGE (e, ei, bb->succs)
345 if (e->count < 0)
346 e->count = 0;
351 /* Check consistency.
352 Return true if inconsistency is found. */
353 static bool
354 is_inconsistent (void)
356 basic_block bb;
357 bool inconsistent = false;
358 FOR_EACH_BB_FN (bb, cfun)
360 inconsistent |= is_edge_inconsistent (bb->preds);
361 if (!dump_file && inconsistent)
362 return true;
363 inconsistent |= is_edge_inconsistent (bb->succs);
364 if (!dump_file && inconsistent)
365 return true;
366 if (bb->count < 0)
368 if (dump_file)
370 fprintf (dump_file, "BB %i count is negative "
371 "%" PRId64,
372 bb->index,
373 bb->count);
374 dump_bb (dump_file, bb, 0, TDF_DETAILS);
376 inconsistent = true;
378 if (bb->count != sum_edge_counts (bb->preds))
380 if (dump_file)
382 fprintf (dump_file, "BB %i count does not match sum of incoming edges "
383 "%" PRId64" should be %" PRId64,
384 bb->index,
385 bb->count,
386 sum_edge_counts (bb->preds));
387 dump_bb (dump_file, bb, 0, TDF_DETAILS);
389 inconsistent = true;
391 if (bb->count != sum_edge_counts (bb->succs) &&
392 ! (find_edge (bb, EXIT_BLOCK_PTR_FOR_FN (cfun)) != NULL
393 && block_ends_with_call_p (bb)))
395 if (dump_file)
397 fprintf (dump_file, "BB %i count does not match sum of outgoing edges "
398 "%" PRId64" should be %" PRId64,
399 bb->index,
400 bb->count,
401 sum_edge_counts (bb->succs));
402 dump_bb (dump_file, bb, 0, TDF_DETAILS);
404 inconsistent = true;
406 if (!dump_file && inconsistent)
407 return true;
410 return inconsistent;
413 /* Set each basic block count to the sum of its outgoing edge counts */
414 static void
415 set_bb_counts (void)
417 basic_block bb;
418 FOR_BB_BETWEEN (bb, ENTRY_BLOCK_PTR_FOR_FN (cfun), NULL, next_bb)
420 bb->count = sum_edge_counts (bb->succs);
421 gcc_assert (bb->count >= 0);
425 /* Reads profile data and returns total number of edge counts read */
426 static int
427 read_profile_edge_counts (gcov_type *exec_counts)
429 basic_block bb;
430 int num_edges = 0;
431 int exec_counts_pos = 0;
432 /* For each edge not on the spanning tree, set its execution count from
433 the .da file. */
434 /* The first count in the .da file is the number of times that the function
435 was entered. This is the exec_count for block zero. */
437 FOR_BB_BETWEEN (bb, ENTRY_BLOCK_PTR_FOR_FN (cfun), NULL, next_bb)
439 edge e;
440 edge_iterator ei;
442 FOR_EACH_EDGE (e, ei, bb->succs)
443 if (!EDGE_INFO (e)->ignore && !EDGE_INFO (e)->on_tree)
445 num_edges++;
446 if (exec_counts)
448 e->count = exec_counts[exec_counts_pos++];
449 if (e->count > profile_info->sum_max)
451 if (flag_profile_correction)
453 static bool informed = 0;
454 if (dump_enabled_p () && !informed)
455 dump_printf_loc (MSG_NOTE, input_location,
456 "corrupted profile info: edge count"
457 " exceeds maximal count\n");
458 informed = 1;
460 else
461 error ("corrupted profile info: edge from %i to %i exceeds maximal count",
462 bb->index, e->dest->index);
465 else
466 e->count = 0;
468 EDGE_INFO (e)->count_valid = 1;
469 BB_INFO (bb)->succ_count--;
470 BB_INFO (e->dest)->pred_count--;
471 if (dump_file)
473 fprintf (dump_file, "\nRead edge from %i to %i, count:",
474 bb->index, e->dest->index);
475 fprintf (dump_file, "%" PRId64,
476 (int64_t) e->count);
481 return num_edges;
484 #define OVERLAP_BASE 10000
486 /* Compare the static estimated profile to the actual profile, and
487 return the "degree of overlap" measure between them.
489 Degree of overlap is a number between 0 and OVERLAP_BASE. It is
490 the sum of each basic block's minimum relative weights between
491 two profiles. And overlap of OVERLAP_BASE means two profiles are
492 identical. */
494 static int
495 compute_frequency_overlap (void)
497 gcov_type count_total = 0, freq_total = 0;
498 int overlap = 0;
499 basic_block bb;
501 FOR_BB_BETWEEN (bb, ENTRY_BLOCK_PTR_FOR_FN (cfun), NULL, next_bb)
503 count_total += bb->count;
504 freq_total += bb->frequency;
507 if (count_total == 0 || freq_total == 0)
508 return 0;
510 FOR_BB_BETWEEN (bb, ENTRY_BLOCK_PTR_FOR_FN (cfun), NULL, next_bb)
511 overlap += MIN (bb->count * OVERLAP_BASE / count_total,
512 bb->frequency * OVERLAP_BASE / freq_total);
514 return overlap;
517 /* Compute the branch probabilities for the various branches.
518 Annotate them accordingly.
520 CFG_CHECKSUM is the precomputed checksum for the CFG. */
522 static void
523 compute_branch_probabilities (unsigned cfg_checksum, unsigned lineno_checksum)
525 basic_block bb;
526 int i;
527 int num_edges = 0;
528 int changes;
529 int passes;
530 int hist_br_prob[20];
531 int num_branches;
532 gcov_type *exec_counts = get_exec_counts (cfg_checksum, lineno_checksum);
533 int inconsistent = 0;
535 /* Very simple sanity checks so we catch bugs in our profiling code. */
536 if (!profile_info)
537 return;
539 if (profile_info->sum_all < profile_info->sum_max)
541 error ("corrupted profile info: sum_all is smaller than sum_max");
542 exec_counts = NULL;
545 /* Attach extra info block to each bb. */
546 alloc_aux_for_blocks (sizeof (struct bb_profile_info));
547 FOR_BB_BETWEEN (bb, ENTRY_BLOCK_PTR_FOR_FN (cfun), NULL, next_bb)
549 edge e;
550 edge_iterator ei;
552 FOR_EACH_EDGE (e, ei, bb->succs)
553 if (!EDGE_INFO (e)->ignore)
554 BB_INFO (bb)->succ_count++;
555 FOR_EACH_EDGE (e, ei, bb->preds)
556 if (!EDGE_INFO (e)->ignore)
557 BB_INFO (bb)->pred_count++;
560 /* Avoid predicting entry on exit nodes. */
561 BB_INFO (EXIT_BLOCK_PTR_FOR_FN (cfun))->succ_count = 2;
562 BB_INFO (ENTRY_BLOCK_PTR_FOR_FN (cfun))->pred_count = 2;
564 num_edges = read_profile_edge_counts (exec_counts);
566 if (dump_file)
567 fprintf (dump_file, "\n%d edge counts read\n", num_edges);
569 /* For every block in the file,
570 - if every exit/entrance edge has a known count, then set the block count
571 - if the block count is known, and every exit/entrance edge but one has
572 a known execution count, then set the count of the remaining edge
574 As edge counts are set, decrement the succ/pred count, but don't delete
575 the edge, that way we can easily tell when all edges are known, or only
576 one edge is unknown. */
578 /* The order that the basic blocks are iterated through is important.
579 Since the code that finds spanning trees starts with block 0, low numbered
580 edges are put on the spanning tree in preference to high numbered edges.
581 Hence, most instrumented edges are at the end. Graph solving works much
582 faster if we propagate numbers from the end to the start.
584 This takes an average of slightly more than 3 passes. */
586 changes = 1;
587 passes = 0;
588 while (changes)
590 passes++;
591 changes = 0;
592 FOR_BB_BETWEEN (bb, EXIT_BLOCK_PTR_FOR_FN (cfun), NULL, prev_bb)
594 struct bb_profile_info *bi = BB_INFO (bb);
595 if (! bi->count_valid)
597 if (bi->succ_count == 0)
599 edge e;
600 edge_iterator ei;
601 gcov_type total = 0;
603 FOR_EACH_EDGE (e, ei, bb->succs)
604 total += e->count;
605 bb->count = total;
606 bi->count_valid = 1;
607 changes = 1;
609 else if (bi->pred_count == 0)
611 edge e;
612 edge_iterator ei;
613 gcov_type total = 0;
615 FOR_EACH_EDGE (e, ei, bb->preds)
616 total += e->count;
617 bb->count = total;
618 bi->count_valid = 1;
619 changes = 1;
622 if (bi->count_valid)
624 if (bi->succ_count == 1)
626 edge e;
627 edge_iterator ei;
628 gcov_type total = 0;
630 /* One of the counts will be invalid, but it is zero,
631 so adding it in also doesn't hurt. */
632 FOR_EACH_EDGE (e, ei, bb->succs)
633 total += e->count;
635 /* Search for the invalid edge, and set its count. */
636 FOR_EACH_EDGE (e, ei, bb->succs)
637 if (! EDGE_INFO (e)->count_valid && ! EDGE_INFO (e)->ignore)
638 break;
640 /* Calculate count for remaining edge by conservation. */
641 total = bb->count - total;
643 gcc_assert (e);
644 EDGE_INFO (e)->count_valid = 1;
645 e->count = total;
646 bi->succ_count--;
648 BB_INFO (e->dest)->pred_count--;
649 changes = 1;
651 if (bi->pred_count == 1)
653 edge e;
654 edge_iterator ei;
655 gcov_type total = 0;
657 /* One of the counts will be invalid, but it is zero,
658 so adding it in also doesn't hurt. */
659 FOR_EACH_EDGE (e, ei, bb->preds)
660 total += e->count;
662 /* Search for the invalid edge, and set its count. */
663 FOR_EACH_EDGE (e, ei, bb->preds)
664 if (!EDGE_INFO (e)->count_valid && !EDGE_INFO (e)->ignore)
665 break;
667 /* Calculate count for remaining edge by conservation. */
668 total = bb->count - total + e->count;
670 gcc_assert (e);
671 EDGE_INFO (e)->count_valid = 1;
672 e->count = total;
673 bi->pred_count--;
675 BB_INFO (e->src)->succ_count--;
676 changes = 1;
681 if (dump_file)
683 int overlap = compute_frequency_overlap ();
684 gimple_dump_cfg (dump_file, dump_flags);
685 fprintf (dump_file, "Static profile overlap: %d.%d%%\n",
686 overlap / (OVERLAP_BASE / 100),
687 overlap % (OVERLAP_BASE / 100));
690 total_num_passes += passes;
691 if (dump_file)
692 fprintf (dump_file, "Graph solving took %d passes.\n\n", passes);
694 /* If the graph has been correctly solved, every block will have a
695 succ and pred count of zero. */
696 FOR_EACH_BB_FN (bb, cfun)
698 gcc_assert (!BB_INFO (bb)->succ_count && !BB_INFO (bb)->pred_count);
701 /* Check for inconsistent basic block counts */
702 inconsistent = is_inconsistent ();
704 if (inconsistent)
706 if (flag_profile_correction)
708 /* Inconsistency detected. Make it flow-consistent. */
709 static int informed = 0;
710 if (dump_enabled_p () && informed == 0)
712 informed = 1;
713 dump_printf_loc (MSG_NOTE, input_location,
714 "correcting inconsistent profile data\n");
716 correct_negative_edge_counts ();
717 /* Set bb counts to the sum of the outgoing edge counts */
718 set_bb_counts ();
719 if (dump_file)
720 fprintf (dump_file, "\nCalling mcf_smooth_cfg\n");
721 mcf_smooth_cfg ();
723 else
724 error ("corrupted profile info: profile data is not flow-consistent");
727 /* For every edge, calculate its branch probability and add a reg_note
728 to the branch insn to indicate this. */
730 for (i = 0; i < 20; i++)
731 hist_br_prob[i] = 0;
732 num_branches = 0;
734 FOR_BB_BETWEEN (bb, ENTRY_BLOCK_PTR_FOR_FN (cfun), NULL, next_bb)
736 edge e;
737 edge_iterator ei;
739 if (bb->count < 0)
741 error ("corrupted profile info: number of iterations for basic block %d thought to be %i",
742 bb->index, (int)bb->count);
743 bb->count = 0;
745 FOR_EACH_EDGE (e, ei, bb->succs)
747 /* Function may return twice in the cased the called function is
748 setjmp or calls fork, but we can't represent this by extra
749 edge from the entry, since extra edge from the exit is
750 already present. We get negative frequency from the entry
751 point. */
752 if ((e->count < 0
753 && e->dest == EXIT_BLOCK_PTR_FOR_FN (cfun))
754 || (e->count > bb->count
755 && e->dest != EXIT_BLOCK_PTR_FOR_FN (cfun)))
757 if (block_ends_with_call_p (bb))
758 e->count = e->count < 0 ? 0 : bb->count;
760 if (e->count < 0 || e->count > bb->count)
762 error ("corrupted profile info: number of executions for edge %d-%d thought to be %i",
763 e->src->index, e->dest->index,
764 (int)e->count);
765 e->count = bb->count / 2;
768 if (bb->count)
770 FOR_EACH_EDGE (e, ei, bb->succs)
771 e->probability = GCOV_COMPUTE_SCALE (e->count, bb->count);
772 if (bb->index >= NUM_FIXED_BLOCKS
773 && block_ends_with_condjump_p (bb)
774 && EDGE_COUNT (bb->succs) >= 2)
776 int prob;
777 edge e;
778 int index;
780 /* Find the branch edge. It is possible that we do have fake
781 edges here. */
782 FOR_EACH_EDGE (e, ei, bb->succs)
783 if (!(e->flags & (EDGE_FAKE | EDGE_FALLTHRU)))
784 break;
786 prob = e->probability;
787 index = prob * 20 / REG_BR_PROB_BASE;
789 if (index == 20)
790 index = 19;
791 hist_br_prob[index]++;
793 num_branches++;
796 /* As a last resort, distribute the probabilities evenly.
797 Use simple heuristics that if there are normal edges,
798 give all abnormals frequency of 0, otherwise distribute the
799 frequency over abnormals (this is the case of noreturn
800 calls). */
801 else if (profile_status_for_fn (cfun) == PROFILE_ABSENT)
803 int total = 0;
805 FOR_EACH_EDGE (e, ei, bb->succs)
806 if (!(e->flags & (EDGE_COMPLEX | EDGE_FAKE)))
807 total ++;
808 if (total)
810 FOR_EACH_EDGE (e, ei, bb->succs)
811 if (!(e->flags & (EDGE_COMPLEX | EDGE_FAKE)))
812 e->probability = REG_BR_PROB_BASE / total;
813 else
814 e->probability = 0;
816 else
818 total += EDGE_COUNT (bb->succs);
819 FOR_EACH_EDGE (e, ei, bb->succs)
820 e->probability = REG_BR_PROB_BASE / total;
822 if (bb->index >= NUM_FIXED_BLOCKS
823 && block_ends_with_condjump_p (bb)
824 && EDGE_COUNT (bb->succs) >= 2)
825 num_branches++;
828 counts_to_freqs ();
829 profile_status_for_fn (cfun) = PROFILE_READ;
830 compute_function_frequency ();
832 if (dump_file)
834 fprintf (dump_file, "%d branches\n", num_branches);
835 if (num_branches)
836 for (i = 0; i < 10; i++)
837 fprintf (dump_file, "%d%% branches in range %d-%d%%\n",
838 (hist_br_prob[i] + hist_br_prob[19-i]) * 100 / num_branches,
839 5 * i, 5 * i + 5);
841 total_num_branches += num_branches;
842 for (i = 0; i < 20; i++)
843 total_hist_br_prob[i] += hist_br_prob[i];
845 fputc ('\n', dump_file);
846 fputc ('\n', dump_file);
848 if (dump_file && (dump_flags & TDF_DETAILS))
849 report_predictor_hitrates ();
851 free_aux_for_blocks ();
854 /* Load value histograms values whose description is stored in VALUES array
855 from .gcda file.
857 CFG_CHECKSUM is the precomputed checksum for the CFG. */
859 static void
860 compute_value_histograms (histogram_values values, unsigned cfg_checksum,
861 unsigned lineno_checksum)
863 unsigned i, j, t, any;
864 unsigned n_histogram_counters[GCOV_N_VALUE_COUNTERS];
865 gcov_type *histogram_counts[GCOV_N_VALUE_COUNTERS];
866 gcov_type *act_count[GCOV_N_VALUE_COUNTERS];
867 gcov_type *aact_count;
868 struct cgraph_node *node;
870 for (t = 0; t < GCOV_N_VALUE_COUNTERS; t++)
871 n_histogram_counters[t] = 0;
873 for (i = 0; i < values.length (); i++)
875 histogram_value hist = values[i];
876 n_histogram_counters[(int) hist->type] += hist->n_counters;
879 any = 0;
880 for (t = 0; t < GCOV_N_VALUE_COUNTERS; t++)
882 if (!n_histogram_counters[t])
884 histogram_counts[t] = NULL;
885 continue;
888 histogram_counts[t] =
889 get_coverage_counts (COUNTER_FOR_HIST_TYPE (t),
890 n_histogram_counters[t], cfg_checksum,
891 lineno_checksum, NULL);
892 if (histogram_counts[t])
893 any = 1;
894 act_count[t] = histogram_counts[t];
896 if (!any)
897 return;
899 for (i = 0; i < values.length (); i++)
901 histogram_value hist = values[i];
902 gimple *stmt = hist->hvalue.stmt;
904 t = (int) hist->type;
906 aact_count = act_count[t];
908 if (act_count[t])
909 act_count[t] += hist->n_counters;
911 gimple_add_histogram_value (cfun, stmt, hist);
912 hist->hvalue.counters = XNEWVEC (gcov_type, hist->n_counters);
913 for (j = 0; j < hist->n_counters; j++)
914 if (aact_count)
915 hist->hvalue.counters[j] = aact_count[j];
916 else
917 hist->hvalue.counters[j] = 0;
919 /* Time profiler counter is not related to any statement,
920 so that we have to read the counter and set the value to
921 the corresponding call graph node. */
922 if (hist->type == HIST_TYPE_TIME_PROFILE)
924 node = cgraph_node::get (hist->fun->decl);
925 node->tp_first_run = hist->hvalue.counters[0];
927 if (dump_file)
928 fprintf (dump_file, "Read tp_first_run: %d\n", node->tp_first_run);
932 for (t = 0; t < GCOV_N_VALUE_COUNTERS; t++)
933 free (histogram_counts[t]);
936 /* When passed NULL as file_name, initialize.
937 When passed something else, output the necessary commands to change
938 line to LINE and offset to FILE_NAME. */
939 static void
940 output_location (char const *file_name, int line,
941 gcov_position_t *offset, basic_block bb)
943 static char const *prev_file_name;
944 static int prev_line;
945 bool name_differs, line_differs;
947 if (!file_name)
949 prev_file_name = NULL;
950 prev_line = -1;
951 return;
954 name_differs = !prev_file_name || filename_cmp (file_name, prev_file_name);
955 line_differs = prev_line != line;
957 if (name_differs || line_differs)
959 if (!*offset)
961 *offset = gcov_write_tag (GCOV_TAG_LINES);
962 gcov_write_unsigned (bb->index);
963 name_differs = line_differs=true;
966 /* If this is a new source file, then output the
967 file's name to the .bb file. */
968 if (name_differs)
970 prev_file_name = file_name;
971 gcov_write_unsigned (0);
972 gcov_write_string (prev_file_name);
974 if (line_differs)
976 gcov_write_unsigned (line);
977 prev_line = line;
982 /* Instrument and/or analyze program behavior based on program the CFG.
984 This function creates a representation of the control flow graph (of
985 the function being compiled) that is suitable for the instrumentation
986 of edges and/or converting measured edge counts to counts on the
987 complete CFG.
989 When FLAG_PROFILE_ARCS is nonzero, this function instruments the edges in
990 the flow graph that are needed to reconstruct the dynamic behavior of the
991 flow graph. This data is written to the gcno file for gcov.
993 When FLAG_BRANCH_PROBABILITIES is nonzero, this function reads auxiliary
994 information from the gcda file containing edge count information from
995 previous executions of the function being compiled. In this case, the
996 control flow graph is annotated with actual execution counts by
997 compute_branch_probabilities().
999 Main entry point of this file. */
1001 void
1002 branch_prob (void)
1004 basic_block bb;
1005 unsigned i;
1006 unsigned num_edges, ignored_edges;
1007 unsigned num_instrumented;
1008 struct edge_list *el;
1009 histogram_values values = histogram_values ();
1010 unsigned cfg_checksum, lineno_checksum;
1012 total_num_times_called++;
1014 flow_call_edges_add (NULL);
1015 add_noreturn_fake_exit_edges ();
1017 /* We can't handle cyclic regions constructed using abnormal edges.
1018 To avoid these we replace every source of abnormal edge by a fake
1019 edge from entry node and every destination by fake edge to exit.
1020 This keeps graph acyclic and our calculation exact for all normal
1021 edges except for exit and entrance ones.
1023 We also add fake exit edges for each call and asm statement in the
1024 basic, since it may not return. */
1026 FOR_EACH_BB_FN (bb, cfun)
1028 int need_exit_edge = 0, need_entry_edge = 0;
1029 int have_exit_edge = 0, have_entry_edge = 0;
1030 edge e;
1031 edge_iterator ei;
1033 /* Functions returning multiple times are not handled by extra edges.
1034 Instead we simply allow negative counts on edges from exit to the
1035 block past call and corresponding probabilities. We can't go
1036 with the extra edges because that would result in flowgraph that
1037 needs to have fake edges outside the spanning tree. */
1039 FOR_EACH_EDGE (e, ei, bb->succs)
1041 gimple_stmt_iterator gsi;
1042 gimple *last = NULL;
1044 /* It may happen that there are compiler generated statements
1045 without a locus at all. Go through the basic block from the
1046 last to the first statement looking for a locus. */
1047 for (gsi = gsi_last_nondebug_bb (bb);
1048 !gsi_end_p (gsi);
1049 gsi_prev_nondebug (&gsi))
1051 last = gsi_stmt (gsi);
1052 if (gimple_has_location (last))
1053 break;
1056 /* Edge with goto locus might get wrong coverage info unless
1057 it is the only edge out of BB.
1058 Don't do that when the locuses match, so
1059 if (blah) goto something;
1060 is not computed twice. */
1061 if (last
1062 && gimple_has_location (last)
1063 && LOCATION_LOCUS (e->goto_locus) != UNKNOWN_LOCATION
1064 && !single_succ_p (bb)
1065 && (LOCATION_FILE (e->goto_locus)
1066 != LOCATION_FILE (gimple_location (last))
1067 || (LOCATION_LINE (e->goto_locus)
1068 != LOCATION_LINE (gimple_location (last)))))
1070 basic_block new_bb = split_edge (e);
1071 edge ne = single_succ_edge (new_bb);
1072 ne->goto_locus = e->goto_locus;
1074 if ((e->flags & (EDGE_ABNORMAL | EDGE_ABNORMAL_CALL))
1075 && e->dest != EXIT_BLOCK_PTR_FOR_FN (cfun))
1076 need_exit_edge = 1;
1077 if (e->dest == EXIT_BLOCK_PTR_FOR_FN (cfun))
1078 have_exit_edge = 1;
1080 FOR_EACH_EDGE (e, ei, bb->preds)
1082 if ((e->flags & (EDGE_ABNORMAL | EDGE_ABNORMAL_CALL))
1083 && e->src != ENTRY_BLOCK_PTR_FOR_FN (cfun))
1084 need_entry_edge = 1;
1085 if (e->src == ENTRY_BLOCK_PTR_FOR_FN (cfun))
1086 have_entry_edge = 1;
1089 if (need_exit_edge && !have_exit_edge)
1091 if (dump_file)
1092 fprintf (dump_file, "Adding fake exit edge to bb %i\n",
1093 bb->index);
1094 make_edge (bb, EXIT_BLOCK_PTR_FOR_FN (cfun), EDGE_FAKE);
1096 if (need_entry_edge && !have_entry_edge)
1098 if (dump_file)
1099 fprintf (dump_file, "Adding fake entry edge to bb %i\n",
1100 bb->index);
1101 make_edge (ENTRY_BLOCK_PTR_FOR_FN (cfun), bb, EDGE_FAKE);
1102 /* Avoid bbs that have both fake entry edge and also some
1103 exit edge. One of those edges wouldn't be added to the
1104 spanning tree, but we can't instrument any of them. */
1105 if (have_exit_edge || need_exit_edge)
1107 gimple_stmt_iterator gsi;
1108 gimple *first;
1110 gsi = gsi_start_nondebug_after_labels_bb (bb);
1111 gcc_checking_assert (!gsi_end_p (gsi));
1112 first = gsi_stmt (gsi);
1113 /* Don't split the bbs containing __builtin_setjmp_receiver
1114 or ABNORMAL_DISPATCHER calls. These are very
1115 special and don't expect anything to be inserted before
1116 them. */
1117 if (is_gimple_call (first)
1118 && (gimple_call_builtin_p (first, BUILT_IN_SETJMP_RECEIVER)
1119 || (gimple_call_flags (first) & ECF_RETURNS_TWICE)
1120 || (gimple_call_internal_p (first)
1121 && (gimple_call_internal_fn (first)
1122 == IFN_ABNORMAL_DISPATCHER))))
1123 continue;
1125 if (dump_file)
1126 fprintf (dump_file, "Splitting bb %i after labels\n",
1127 bb->index);
1128 split_block_after_labels (bb);
1133 el = create_edge_list ();
1134 num_edges = NUM_EDGES (el);
1135 alloc_aux_for_edges (sizeof (struct edge_profile_info));
1137 /* The basic blocks are expected to be numbered sequentially. */
1138 compact_blocks ();
1140 ignored_edges = 0;
1141 for (i = 0 ; i < num_edges ; i++)
1143 edge e = INDEX_EDGE (el, i);
1144 e->count = 0;
1146 /* Mark edges we've replaced by fake edges above as ignored. */
1147 if ((e->flags & (EDGE_ABNORMAL | EDGE_ABNORMAL_CALL))
1148 && e->src != ENTRY_BLOCK_PTR_FOR_FN (cfun)
1149 && e->dest != EXIT_BLOCK_PTR_FOR_FN (cfun))
1151 EDGE_INFO (e)->ignore = 1;
1152 ignored_edges++;
1156 /* Create spanning tree from basic block graph, mark each edge that is
1157 on the spanning tree. We insert as many abnormal and critical edges
1158 as possible to minimize number of edge splits necessary. */
1160 find_spanning_tree (el);
1162 /* Fake edges that are not on the tree will not be instrumented, so
1163 mark them ignored. */
1164 for (num_instrumented = i = 0; i < num_edges; i++)
1166 edge e = INDEX_EDGE (el, i);
1167 struct edge_profile_info *inf = EDGE_INFO (e);
1169 if (inf->ignore || inf->on_tree)
1170 /*NOP*/;
1171 else if (e->flags & EDGE_FAKE)
1173 inf->ignore = 1;
1174 ignored_edges++;
1176 else
1177 num_instrumented++;
1180 total_num_blocks += n_basic_blocks_for_fn (cfun);
1181 if (dump_file)
1182 fprintf (dump_file, "%d basic blocks\n", n_basic_blocks_for_fn (cfun));
1184 total_num_edges += num_edges;
1185 if (dump_file)
1186 fprintf (dump_file, "%d edges\n", num_edges);
1188 total_num_edges_ignored += ignored_edges;
1189 if (dump_file)
1190 fprintf (dump_file, "%d ignored edges\n", ignored_edges);
1192 total_num_edges_instrumented += num_instrumented;
1193 if (dump_file)
1194 fprintf (dump_file, "%d instrumentation edges\n", num_instrumented);
1196 /* Compute two different checksums. Note that we want to compute
1197 the checksum in only once place, since it depends on the shape
1198 of the control flow which can change during
1199 various transformations. */
1200 cfg_checksum = coverage_compute_cfg_checksum (cfun);
1201 lineno_checksum = coverage_compute_lineno_checksum ();
1203 /* Write the data from which gcov can reconstruct the basic block
1204 graph and function line numbers (the gcno file). */
1205 if (coverage_begin_function (lineno_checksum, cfg_checksum))
1207 gcov_position_t offset;
1209 /* Basic block flags */
1210 offset = gcov_write_tag (GCOV_TAG_BLOCKS);
1211 for (i = 0; i != (unsigned) (n_basic_blocks_for_fn (cfun)); i++)
1212 gcov_write_unsigned (0);
1213 gcov_write_length (offset);
1215 /* Arcs */
1216 FOR_BB_BETWEEN (bb, ENTRY_BLOCK_PTR_FOR_FN (cfun),
1217 EXIT_BLOCK_PTR_FOR_FN (cfun), next_bb)
1219 edge e;
1220 edge_iterator ei;
1222 offset = gcov_write_tag (GCOV_TAG_ARCS);
1223 gcov_write_unsigned (bb->index);
1225 FOR_EACH_EDGE (e, ei, bb->succs)
1227 struct edge_profile_info *i = EDGE_INFO (e);
1228 if (!i->ignore)
1230 unsigned flag_bits = 0;
1232 if (i->on_tree)
1233 flag_bits |= GCOV_ARC_ON_TREE;
1234 if (e->flags & EDGE_FAKE)
1235 flag_bits |= GCOV_ARC_FAKE;
1236 if (e->flags & EDGE_FALLTHRU)
1237 flag_bits |= GCOV_ARC_FALLTHROUGH;
1238 /* On trees we don't have fallthru flags, but we can
1239 recompute them from CFG shape. */
1240 if (e->flags & (EDGE_TRUE_VALUE | EDGE_FALSE_VALUE)
1241 && e->src->next_bb == e->dest)
1242 flag_bits |= GCOV_ARC_FALLTHROUGH;
1244 gcov_write_unsigned (e->dest->index);
1245 gcov_write_unsigned (flag_bits);
1249 gcov_write_length (offset);
1252 /* Line numbers. */
1253 /* Initialize the output. */
1254 output_location (NULL, 0, NULL, NULL);
1256 FOR_EACH_BB_FN (bb, cfun)
1258 gimple_stmt_iterator gsi;
1259 gcov_position_t offset = 0;
1261 if (bb == ENTRY_BLOCK_PTR_FOR_FN (cfun)->next_bb)
1263 expanded_location curr_location =
1264 expand_location (DECL_SOURCE_LOCATION (current_function_decl));
1265 output_location (curr_location.file, curr_location.line,
1266 &offset, bb);
1269 for (gsi = gsi_start_bb (bb); !gsi_end_p (gsi); gsi_next (&gsi))
1271 gimple *stmt = gsi_stmt (gsi);
1272 if (gimple_has_location (stmt))
1273 output_location (gimple_filename (stmt), gimple_lineno (stmt),
1274 &offset, bb);
1277 /* Notice GOTO expressions eliminated while constructing the CFG. */
1278 if (single_succ_p (bb)
1279 && LOCATION_LOCUS (single_succ_edge (bb)->goto_locus)
1280 != UNKNOWN_LOCATION)
1282 expanded_location curr_location
1283 = expand_location (single_succ_edge (bb)->goto_locus);
1284 output_location (curr_location.file, curr_location.line,
1285 &offset, bb);
1288 if (offset)
1290 /* A file of NULL indicates the end of run. */
1291 gcov_write_unsigned (0);
1292 gcov_write_string (NULL);
1293 gcov_write_length (offset);
1298 if (flag_profile_values)
1299 gimple_find_values_to_profile (&values);
1301 if (flag_branch_probabilities)
1303 compute_branch_probabilities (cfg_checksum, lineno_checksum);
1304 if (flag_profile_values)
1305 compute_value_histograms (values, cfg_checksum, lineno_checksum);
1308 remove_fake_edges ();
1310 /* For each edge not on the spanning tree, add counting code. */
1311 if (profile_arc_flag
1312 && coverage_counter_alloc (GCOV_COUNTER_ARCS, num_instrumented))
1314 unsigned n_instrumented;
1316 gimple_init_edge_profiler ();
1318 n_instrumented = instrument_edges (el);
1320 gcc_assert (n_instrumented == num_instrumented);
1322 if (flag_profile_values)
1323 instrument_values (values);
1325 /* Commit changes done by instrumentation. */
1326 gsi_commit_edge_inserts ();
1329 free_aux_for_edges ();
1331 values.release ();
1332 free_edge_list (el);
1333 coverage_end_function (lineno_checksum, cfg_checksum);
1336 /* Union find algorithm implementation for the basic blocks using
1337 aux fields. */
1339 static basic_block
1340 find_group (basic_block bb)
1342 basic_block group = bb, bb1;
1344 while ((basic_block) group->aux != group)
1345 group = (basic_block) group->aux;
1347 /* Compress path. */
1348 while ((basic_block) bb->aux != group)
1350 bb1 = (basic_block) bb->aux;
1351 bb->aux = (void *) group;
1352 bb = bb1;
1354 return group;
1357 static void
1358 union_groups (basic_block bb1, basic_block bb2)
1360 basic_block bb1g = find_group (bb1);
1361 basic_block bb2g = find_group (bb2);
1363 /* ??? I don't have a place for the rank field. OK. Lets go w/o it,
1364 this code is unlikely going to be performance problem anyway. */
1365 gcc_assert (bb1g != bb2g);
1367 bb1g->aux = bb2g;
1370 /* This function searches all of the edges in the program flow graph, and puts
1371 as many bad edges as possible onto the spanning tree. Bad edges include
1372 abnormals edges, which can't be instrumented at the moment. Since it is
1373 possible for fake edges to form a cycle, we will have to develop some
1374 better way in the future. Also put critical edges to the tree, since they
1375 are more expensive to instrument. */
1377 static void
1378 find_spanning_tree (struct edge_list *el)
1380 int i;
1381 int num_edges = NUM_EDGES (el);
1382 basic_block bb;
1384 /* We use aux field for standard union-find algorithm. */
1385 FOR_BB_BETWEEN (bb, ENTRY_BLOCK_PTR_FOR_FN (cfun), NULL, next_bb)
1386 bb->aux = bb;
1388 /* Add fake edge exit to entry we can't instrument. */
1389 union_groups (EXIT_BLOCK_PTR_FOR_FN (cfun), ENTRY_BLOCK_PTR_FOR_FN (cfun));
1391 /* First add all abnormal edges to the tree unless they form a cycle. Also
1392 add all edges to the exit block to avoid inserting profiling code behind
1393 setting return value from function. */
1394 for (i = 0; i < num_edges; i++)
1396 edge e = INDEX_EDGE (el, i);
1397 if (((e->flags & (EDGE_ABNORMAL | EDGE_ABNORMAL_CALL | EDGE_FAKE))
1398 || e->dest == EXIT_BLOCK_PTR_FOR_FN (cfun))
1399 && !EDGE_INFO (e)->ignore
1400 && (find_group (e->src) != find_group (e->dest)))
1402 if (dump_file)
1403 fprintf (dump_file, "Abnormal edge %d to %d put to tree\n",
1404 e->src->index, e->dest->index);
1405 EDGE_INFO (e)->on_tree = 1;
1406 union_groups (e->src, e->dest);
1410 /* Now insert all critical edges to the tree unless they form a cycle. */
1411 for (i = 0; i < num_edges; i++)
1413 edge e = INDEX_EDGE (el, i);
1414 if (EDGE_CRITICAL_P (e) && !EDGE_INFO (e)->ignore
1415 && find_group (e->src) != find_group (e->dest))
1417 if (dump_file)
1418 fprintf (dump_file, "Critical edge %d to %d put to tree\n",
1419 e->src->index, e->dest->index);
1420 EDGE_INFO (e)->on_tree = 1;
1421 union_groups (e->src, e->dest);
1425 /* And now the rest. */
1426 for (i = 0; i < num_edges; i++)
1428 edge e = INDEX_EDGE (el, i);
1429 if (!EDGE_INFO (e)->ignore
1430 && find_group (e->src) != find_group (e->dest))
1432 if (dump_file)
1433 fprintf (dump_file, "Normal edge %d to %d put to tree\n",
1434 e->src->index, e->dest->index);
1435 EDGE_INFO (e)->on_tree = 1;
1436 union_groups (e->src, e->dest);
1440 clear_aux_for_blocks ();
1443 /* Perform file-level initialization for branch-prob processing. */
1445 void
1446 init_branch_prob (void)
1448 int i;
1450 total_num_blocks = 0;
1451 total_num_edges = 0;
1452 total_num_edges_ignored = 0;
1453 total_num_edges_instrumented = 0;
1454 total_num_blocks_created = 0;
1455 total_num_passes = 0;
1456 total_num_times_called = 0;
1457 total_num_branches = 0;
1458 for (i = 0; i < 20; i++)
1459 total_hist_br_prob[i] = 0;
1462 /* Performs file-level cleanup after branch-prob processing
1463 is completed. */
1465 void
1466 end_branch_prob (void)
1468 if (dump_file)
1470 fprintf (dump_file, "\n");
1471 fprintf (dump_file, "Total number of blocks: %d\n",
1472 total_num_blocks);
1473 fprintf (dump_file, "Total number of edges: %d\n", total_num_edges);
1474 fprintf (dump_file, "Total number of ignored edges: %d\n",
1475 total_num_edges_ignored);
1476 fprintf (dump_file, "Total number of instrumented edges: %d\n",
1477 total_num_edges_instrumented);
1478 fprintf (dump_file, "Total number of blocks created: %d\n",
1479 total_num_blocks_created);
1480 fprintf (dump_file, "Total number of graph solution passes: %d\n",
1481 total_num_passes);
1482 if (total_num_times_called != 0)
1483 fprintf (dump_file, "Average number of graph solution passes: %d\n",
1484 (total_num_passes + (total_num_times_called >> 1))
1485 / total_num_times_called);
1486 fprintf (dump_file, "Total number of branches: %d\n",
1487 total_num_branches);
1488 if (total_num_branches)
1490 int i;
1492 for (i = 0; i < 10; i++)
1493 fprintf (dump_file, "%d%% branches in range %d-%d%%\n",
1494 (total_hist_br_prob[i] + total_hist_br_prob[19-i]) * 100
1495 / total_num_branches, 5*i, 5*i+5);