* dwarf2out.c (dwarf2out_finish): Set parent to comp_unit_die
[official-gcc.git] / gcc / predict.c
blob18b6b90814cd8c219cdcf9e816738d39a0ad499b
1 /* Branch prediction routines for the GNU compiler.
2 Copyright (C) 2000, 2001, 2002, 2003, 2004 Free Software Foundation, Inc.
4 This file is part of GCC.
6 GCC is free software; you can redistribute it and/or modify it under
7 the terms of the GNU General Public License as published by the Free
8 Software Foundation; either version 2, or (at your option) any later
9 version.
11 GCC is distributed in the hope that it will be useful, but WITHOUT ANY
12 WARRANTY; without even the implied warranty of MERCHANTABILITY or
13 FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
14 for more details.
16 You should have received a copy of the GNU General Public License
17 along with GCC; see the file COPYING. If not, write to the Free
18 Software Foundation, 59 Temple Place - Suite 330, Boston, MA
19 02111-1307, USA. */
21 /* References:
23 [1] "Branch Prediction for Free"
24 Ball and Larus; PLDI '93.
25 [2] "Static Branch Frequency and Program Profile Analysis"
26 Wu and Larus; MICRO-27.
27 [3] "Corpus-based Static Branch Prediction"
28 Calder, Grunwald, Lindsay, Martin, Mozer, and Zorn; PLDI '95. */
31 #include "config.h"
32 #include "system.h"
33 #include "coretypes.h"
34 #include "tm.h"
35 #include "tree.h"
36 #include "rtl.h"
37 #include "tm_p.h"
38 #include "hard-reg-set.h"
39 #include "basic-block.h"
40 #include "insn-config.h"
41 #include "regs.h"
42 #include "flags.h"
43 #include "output.h"
44 #include "function.h"
45 #include "except.h"
46 #include "toplev.h"
47 #include "recog.h"
48 #include "expr.h"
49 #include "predict.h"
50 #include "coverage.h"
51 #include "sreal.h"
52 #include "params.h"
53 #include "target.h"
54 #include "cfgloop.h"
55 #include "tree-flow.h"
56 #include "ggc.h"
57 #include "tree-dump.h"
58 #include "tree-pass.h"
59 #include "timevar.h"
60 #include "tree-scalar-evolution.h"
61 #include "cfgloop.h"
63 /* real constants: 0, 1, 1-1/REG_BR_PROB_BASE, REG_BR_PROB_BASE,
64 1/REG_BR_PROB_BASE, 0.5, BB_FREQ_MAX. */
65 static sreal real_zero, real_one, real_almost_one, real_br_prob_base,
66 real_inv_br_prob_base, real_one_half, real_bb_freq_max;
68 /* Random guesstimation given names. */
69 #define PROB_VERY_UNLIKELY (REG_BR_PROB_BASE / 10 - 1)
70 #define PROB_EVEN (REG_BR_PROB_BASE / 2)
71 #define PROB_VERY_LIKELY (REG_BR_PROB_BASE - PROB_VERY_UNLIKELY)
72 #define PROB_ALWAYS (REG_BR_PROB_BASE)
74 static void combine_predictions_for_insn (rtx, basic_block);
75 static void dump_prediction (FILE *, enum br_predictor, int, basic_block, int);
76 static void estimate_loops_at_level (struct loop *loop);
77 static void propagate_freq (struct loop *);
78 static void estimate_bb_frequencies (struct loops *);
79 static void predict_paths_leading_to (basic_block, int *, enum br_predictor, enum prediction);
80 static bool last_basic_block_p (basic_block);
81 static void compute_function_frequency (void);
82 static void choose_function_section (void);
83 static bool can_predict_insn_p (rtx);
85 /* Information we hold about each branch predictor.
86 Filled using information from predict.def. */
88 struct predictor_info
90 const char *const name; /* Name used in the debugging dumps. */
91 const int hitrate; /* Expected hitrate used by
92 predict_insn_def call. */
93 const int flags;
96 /* Use given predictor without Dempster-Shaffer theory if it matches
97 using first_match heuristics. */
98 #define PRED_FLAG_FIRST_MATCH 1
100 /* Recompute hitrate in percent to our representation. */
102 #define HITRATE(VAL) ((int) ((VAL) * REG_BR_PROB_BASE + 50) / 100)
104 #define DEF_PREDICTOR(ENUM, NAME, HITRATE, FLAGS) {NAME, HITRATE, FLAGS},
105 static const struct predictor_info predictor_info[]= {
106 #include "predict.def"
108 /* Upper bound on predictors. */
109 {NULL, 0, 0}
111 #undef DEF_PREDICTOR
113 /* Return true in case BB can be CPU intensive and should be optimized
114 for maximal performance. */
116 bool
117 maybe_hot_bb_p (basic_block bb)
119 if (profile_info && flag_branch_probabilities
120 && (bb->count
121 < profile_info->sum_max / PARAM_VALUE (HOT_BB_COUNT_FRACTION)))
122 return false;
123 if (bb->frequency < BB_FREQ_MAX / PARAM_VALUE (HOT_BB_FREQUENCY_FRACTION))
124 return false;
125 return true;
128 /* Return true in case BB is cold and should be optimized for size. */
130 bool
131 probably_cold_bb_p (basic_block bb)
133 if (profile_info && flag_branch_probabilities
134 && (bb->count
135 < profile_info->sum_max / PARAM_VALUE (HOT_BB_COUNT_FRACTION)))
136 return true;
137 if (bb->frequency < BB_FREQ_MAX / PARAM_VALUE (HOT_BB_FREQUENCY_FRACTION))
138 return true;
139 return false;
142 /* Return true in case BB is probably never executed. */
143 bool
144 probably_never_executed_bb_p (basic_block bb)
146 if (profile_info && flag_branch_probabilities)
147 return ((bb->count + profile_info->runs / 2) / profile_info->runs) == 0;
148 return false;
151 /* Return true if the one of outgoing edges is already predicted by
152 PREDICTOR. */
154 bool
155 rtl_predicted_by_p (basic_block bb, enum br_predictor predictor)
157 rtx note;
158 if (!INSN_P (BB_END (bb)))
159 return false;
160 for (note = REG_NOTES (BB_END (bb)); note; note = XEXP (note, 1))
161 if (REG_NOTE_KIND (note) == REG_BR_PRED
162 && INTVAL (XEXP (XEXP (note, 0), 0)) == (int)predictor)
163 return true;
164 return false;
167 /* Return true if the one of outgoing edges is already predicted by
168 PREDICTOR. */
170 bool
171 tree_predicted_by_p (basic_block bb, enum br_predictor predictor)
173 struct edge_prediction *i = bb_ann (bb)->predictions;
174 for (i = bb_ann (bb)->predictions; i; i = i->next)
175 if (i->predictor == predictor)
176 return true;
177 return false;
180 void
181 predict_insn (rtx insn, enum br_predictor predictor, int probability)
183 if (!any_condjump_p (insn))
184 abort ();
185 if (!flag_guess_branch_prob)
186 return;
188 REG_NOTES (insn)
189 = gen_rtx_EXPR_LIST (REG_BR_PRED,
190 gen_rtx_CONCAT (VOIDmode,
191 GEN_INT ((int) predictor),
192 GEN_INT ((int) probability)),
193 REG_NOTES (insn));
196 /* Predict insn by given predictor. */
198 void
199 predict_insn_def (rtx insn, enum br_predictor predictor,
200 enum prediction taken)
202 int probability = predictor_info[(int) predictor].hitrate;
204 if (taken != TAKEN)
205 probability = REG_BR_PROB_BASE - probability;
207 predict_insn (insn, predictor, probability);
210 /* Predict edge E with given probability if possible. */
212 void
213 rtl_predict_edge (edge e, enum br_predictor predictor, int probability)
215 rtx last_insn;
216 last_insn = BB_END (e->src);
218 /* We can store the branch prediction information only about
219 conditional jumps. */
220 if (!any_condjump_p (last_insn))
221 return;
223 /* We always store probability of branching. */
224 if (e->flags & EDGE_FALLTHRU)
225 probability = REG_BR_PROB_BASE - probability;
227 predict_insn (last_insn, predictor, probability);
230 /* Predict edge E with the given PROBABILITY. */
231 void
232 tree_predict_edge (edge e, enum br_predictor predictor, int probability)
234 struct edge_prediction *i = ggc_alloc (sizeof (struct edge_prediction));
236 i->next = bb_ann (e->src)->predictions;
237 bb_ann (e->src)->predictions = i;
238 i->probability = probability;
239 i->predictor = predictor;
240 i->edge = e;
243 /* Return true when we can store prediction on insn INSN.
244 At the moment we represent predictions only on conditional
245 jumps, not at computed jump or other complicated cases. */
246 static bool
247 can_predict_insn_p (rtx insn)
249 return (JUMP_P (insn)
250 && any_condjump_p (insn)
251 && BLOCK_FOR_INSN (insn)->succ->succ_next);
254 /* Predict edge E by given predictor if possible. */
256 void
257 predict_edge_def (edge e, enum br_predictor predictor,
258 enum prediction taken)
260 int probability = predictor_info[(int) predictor].hitrate;
262 if (taken != TAKEN)
263 probability = REG_BR_PROB_BASE - probability;
265 predict_edge (e, predictor, probability);
268 /* Invert all branch predictions or probability notes in the INSN. This needs
269 to be done each time we invert the condition used by the jump. */
271 void
272 invert_br_probabilities (rtx insn)
274 rtx note;
276 for (note = REG_NOTES (insn); note; note = XEXP (note, 1))
277 if (REG_NOTE_KIND (note) == REG_BR_PROB)
278 XEXP (note, 0) = GEN_INT (REG_BR_PROB_BASE - INTVAL (XEXP (note, 0)));
279 else if (REG_NOTE_KIND (note) == REG_BR_PRED)
280 XEXP (XEXP (note, 0), 1)
281 = GEN_INT (REG_BR_PROB_BASE - INTVAL (XEXP (XEXP (note, 0), 1)));
284 /* Dump information about the branch prediction to the output file. */
286 static void
287 dump_prediction (FILE *file, enum br_predictor predictor, int probability,
288 basic_block bb, int used)
290 edge e = bb->succ;
292 if (!file)
293 return;
295 while (e && (e->flags & EDGE_FALLTHRU))
296 e = e->succ_next;
298 fprintf (file, " %s heuristics%s: %.1f%%",
299 predictor_info[predictor].name,
300 used ? "" : " (ignored)", probability * 100.0 / REG_BR_PROB_BASE);
302 if (bb->count)
304 fprintf (file, " exec ");
305 fprintf (file, HOST_WIDEST_INT_PRINT_DEC, bb->count);
306 if (e)
308 fprintf (file, " hit ");
309 fprintf (file, HOST_WIDEST_INT_PRINT_DEC, e->count);
310 fprintf (file, " (%.1f%%)", e->count * 100.0 / bb->count);
314 fprintf (file, "\n");
317 /* We can not predict the probabilities of outgoing edges of bb. Set them
318 evenly and hope for the best. */
319 static void
320 set_even_probabilities (basic_block bb)
322 int nedges = 0;
323 edge e;
325 for (e = bb->succ; e; e = e->succ_next)
326 if (!(e->flags & (EDGE_EH | EDGE_FAKE)))
327 nedges ++;
328 for (e = bb->succ; e; e = e->succ_next)
329 if (!(e->flags & (EDGE_EH | EDGE_FAKE)))
330 e->probability = (REG_BR_PROB_BASE + nedges / 2) / nedges;
331 else
332 e->probability = 0;
335 /* Combine all REG_BR_PRED notes into single probability and attach REG_BR_PROB
336 note if not already present. Remove now useless REG_BR_PRED notes. */
338 static void
339 combine_predictions_for_insn (rtx insn, basic_block bb)
341 rtx prob_note;
342 rtx *pnote;
343 rtx note;
344 int best_probability = PROB_EVEN;
345 int best_predictor = END_PREDICTORS;
346 int combined_probability = REG_BR_PROB_BASE / 2;
347 int d;
348 bool first_match = false;
349 bool found = false;
351 if (!can_predict_insn_p (insn))
353 set_even_probabilities (bb);
354 return;
357 prob_note = find_reg_note (insn, REG_BR_PROB, 0);
358 pnote = &REG_NOTES (insn);
359 if (dump_file)
360 fprintf (dump_file, "Predictions for insn %i bb %i\n", INSN_UID (insn),
361 bb->index);
363 /* We implement "first match" heuristics and use probability guessed
364 by predictor with smallest index. */
365 for (note = REG_NOTES (insn); note; note = XEXP (note, 1))
366 if (REG_NOTE_KIND (note) == REG_BR_PRED)
368 int predictor = INTVAL (XEXP (XEXP (note, 0), 0));
369 int probability = INTVAL (XEXP (XEXP (note, 0), 1));
371 found = true;
372 if (best_predictor > predictor)
373 best_probability = probability, best_predictor = predictor;
375 d = (combined_probability * probability
376 + (REG_BR_PROB_BASE - combined_probability)
377 * (REG_BR_PROB_BASE - probability));
379 /* Use FP math to avoid overflows of 32bit integers. */
380 if (d == 0)
381 /* If one probability is 0% and one 100%, avoid division by zero. */
382 combined_probability = REG_BR_PROB_BASE / 2;
383 else
384 combined_probability = (((double) combined_probability) * probability
385 * REG_BR_PROB_BASE / d + 0.5);
388 /* Decide which heuristic to use. In case we didn't match anything,
389 use no_prediction heuristic, in case we did match, use either
390 first match or Dempster-Shaffer theory depending on the flags. */
392 if (predictor_info [best_predictor].flags & PRED_FLAG_FIRST_MATCH)
393 first_match = true;
395 if (!found)
396 dump_prediction (dump_file, PRED_NO_PREDICTION,
397 combined_probability, bb, true);
398 else
400 dump_prediction (dump_file, PRED_DS_THEORY, combined_probability,
401 bb, !first_match);
402 dump_prediction (dump_file, PRED_FIRST_MATCH, best_probability,
403 bb, first_match);
406 if (first_match)
407 combined_probability = best_probability;
408 dump_prediction (dump_file, PRED_COMBINED, combined_probability, bb, true);
410 while (*pnote)
412 if (REG_NOTE_KIND (*pnote) == REG_BR_PRED)
414 int predictor = INTVAL (XEXP (XEXP (*pnote, 0), 0));
415 int probability = INTVAL (XEXP (XEXP (*pnote, 0), 1));
417 dump_prediction (dump_file, predictor, probability, bb,
418 !first_match || best_predictor == predictor);
419 *pnote = XEXP (*pnote, 1);
421 else
422 pnote = &XEXP (*pnote, 1);
425 if (!prob_note)
427 REG_NOTES (insn)
428 = gen_rtx_EXPR_LIST (REG_BR_PROB,
429 GEN_INT (combined_probability), REG_NOTES (insn));
431 /* Save the prediction into CFG in case we are seeing non-degenerated
432 conditional jump. */
433 if (bb->succ->succ_next)
435 BRANCH_EDGE (bb)->probability = combined_probability;
436 FALLTHRU_EDGE (bb)->probability
437 = REG_BR_PROB_BASE - combined_probability;
440 else if (bb->succ->succ_next)
442 int prob = INTVAL (XEXP (prob_note, 0));
444 BRANCH_EDGE (bb)->probability = prob;
445 FALLTHRU_EDGE (bb)->probability = REG_BR_PROB_BASE - prob;
447 else
448 bb->succ->probability = REG_BR_PROB_BASE;
451 /* Combine predictions into single probability and store them into CFG.
452 Remove now useless prediction entries. */
454 static void
455 combine_predictions_for_bb (FILE *file, basic_block bb)
457 int best_probability = PROB_EVEN;
458 int best_predictor = END_PREDICTORS;
459 int combined_probability = REG_BR_PROB_BASE / 2;
460 int d;
461 bool first_match = false;
462 bool found = false;
463 struct edge_prediction *pred;
464 int nedges = 0;
465 edge e, first = NULL, second = NULL;
467 for (e = bb->succ; e; e = e->succ_next)
468 if (!(e->flags & (EDGE_EH | EDGE_FAKE)))
470 nedges ++;
471 if (first && !second)
472 second = e;
473 if (!first)
474 first = e;
477 /* When there is no successor or only one choice, prediction is easy.
479 We are lazy for now and predict only basic blocks with two outgoing
480 edges. It is possible to predict generic case too, but we have to
481 ignore first match heuristics and do more involved combining. Implement
482 this later. */
483 if (nedges != 2)
485 if (!bb->count)
486 set_even_probabilities (bb);
487 bb_ann (bb)->predictions = NULL;
488 if (file)
489 fprintf (file, "%i edges in bb %i predicted to even probabilities\n",
490 nedges, bb->index);
491 return;
494 if (file)
495 fprintf (file, "Predictions for bb %i\n", bb->index);
497 /* We implement "first match" heuristics and use probability guessed
498 by predictor with smallest index. */
499 for (pred = bb_ann (bb)->predictions; pred; pred = pred->next)
501 int predictor = pred->predictor;
502 int probability = pred->probability;
504 if (pred->edge != first)
505 probability = REG_BR_PROB_BASE - probability;
507 found = true;
508 if (best_predictor > predictor)
509 best_probability = probability, best_predictor = predictor;
511 d = (combined_probability * probability
512 + (REG_BR_PROB_BASE - combined_probability)
513 * (REG_BR_PROB_BASE - probability));
515 /* Use FP math to avoid overflows of 32bit integers. */
516 if (d == 0)
517 /* If one probability is 0% and one 100%, avoid division by zero. */
518 combined_probability = REG_BR_PROB_BASE / 2;
519 else
520 combined_probability = (((double) combined_probability) * probability
521 * REG_BR_PROB_BASE / d + 0.5);
524 /* Decide which heuristic to use. In case we didn't match anything,
525 use no_prediction heuristic, in case we did match, use either
526 first match or Dempster-Shaffer theory depending on the flags. */
528 if (predictor_info [best_predictor].flags & PRED_FLAG_FIRST_MATCH)
529 first_match = true;
531 if (!found)
532 dump_prediction (file, PRED_NO_PREDICTION, combined_probability, bb, true);
533 else
535 dump_prediction (file, PRED_DS_THEORY, combined_probability, bb,
536 !first_match);
537 dump_prediction (file, PRED_FIRST_MATCH, best_probability, bb,
538 first_match);
541 if (first_match)
542 combined_probability = best_probability;
543 dump_prediction (file, PRED_COMBINED, combined_probability, bb, true);
545 for (pred = bb_ann (bb)->predictions; pred; pred = pred->next)
547 int predictor = pred->predictor;
548 int probability = pred->probability;
550 if (pred->edge != bb->succ)
551 probability = REG_BR_PROB_BASE - probability;
552 dump_prediction (file, predictor, probability, bb,
553 !first_match || best_predictor == predictor);
555 bb_ann (bb)->predictions = NULL;
557 if (!bb->count)
559 first->probability = combined_probability;
560 second->probability = REG_BR_PROB_BASE - combined_probability;
564 /* Predict edge probabilities by exploiting loop structure.
565 When RTLSIMPLELOOPS is set, attempt to count number of iterations by analyzing
566 RTL otherwise use tree based approach. */
567 static void
568 predict_loops (struct loops *loops_info, bool rtlsimpleloops)
570 unsigned i;
572 if (!rtlsimpleloops)
573 scev_initialize (loops_info);
575 /* Try to predict out blocks in a loop that are not part of a
576 natural loop. */
577 for (i = 1; i < loops_info->num; i++)
579 basic_block bb, *bbs;
580 unsigned j;
581 int exits;
582 struct loop *loop = loops_info->parray[i];
583 struct niter_desc desc;
584 unsigned HOST_WIDE_INT niter;
586 flow_loop_scan (loop, LOOP_EXIT_EDGES);
587 exits = loop->num_exits;
589 if (rtlsimpleloops)
591 iv_analysis_loop_init (loop);
592 find_simple_exit (loop, &desc);
594 if (desc.simple_p && desc.const_iter)
596 int prob;
597 niter = desc.niter + 1;
598 if (niter == 0) /* We might overflow here. */
599 niter = desc.niter;
601 prob = (REG_BR_PROB_BASE
602 - (REG_BR_PROB_BASE + niter /2) / niter);
603 /* Branch prediction algorithm gives 0 frequency for everything
604 after the end of loop for loop having 0 probability to finish. */
605 if (prob == REG_BR_PROB_BASE)
606 prob = REG_BR_PROB_BASE - 1;
607 predict_edge (desc.in_edge, PRED_LOOP_ITERATIONS,
608 prob);
611 else
613 edge *exits;
614 unsigned j, n_exits;
615 struct tree_niter_desc niter_desc;
617 exits = get_loop_exit_edges (loop, &n_exits);
618 for (j = 0; j < n_exits; j++)
620 tree niter = NULL;
622 if (number_of_iterations_exit (loop, exits[j], &niter_desc))
623 niter = niter_desc.niter;
624 if (!niter || TREE_CODE (niter_desc.niter) != INTEGER_CST)
625 niter = loop_niter_by_eval (loop, exits[j]);
627 if (TREE_CODE (niter) == INTEGER_CST)
629 int probability;
630 if (host_integerp (niter, 1)
631 && tree_int_cst_lt (niter,
632 build_int_cstu (NULL_TREE,
633 REG_BR_PROB_BASE - 1)))
635 HOST_WIDE_INT nitercst = tree_low_cst (niter, 1) + 1;
636 probability = (REG_BR_PROB_BASE + nitercst / 2) / nitercst;
638 else
639 probability = 1;
641 predict_edge (exits[j], PRED_LOOP_ITERATIONS, probability);
645 free (exits);
648 bbs = get_loop_body (loop);
650 for (j = 0; j < loop->num_nodes; j++)
652 int header_found = 0;
653 edge e;
655 bb = bbs[j];
657 /* Bypass loop heuristics on continue statement. These
658 statements construct loops via "non-loop" constructs
659 in the source language and are better to be handled
660 separately. */
661 if ((rtlsimpleloops && !can_predict_insn_p (BB_END (bb)))
662 || predicted_by_p (bb, PRED_CONTINUE))
663 continue;
665 /* Loop branch heuristics - predict an edge back to a
666 loop's head as taken. */
667 for (e = bb->succ; e; e = e->succ_next)
668 if (e->dest == loop->header
669 && e->src == loop->latch)
671 header_found = 1;
672 predict_edge_def (e, PRED_LOOP_BRANCH, TAKEN);
675 /* Loop exit heuristics - predict an edge exiting the loop if the
676 conditional has no loop header successors as not taken. */
677 if (!header_found)
678 for (e = bb->succ; e; e = e->succ_next)
679 if (e->dest->index < 0
680 || !flow_bb_inside_loop_p (loop, e->dest))
681 predict_edge
682 (e, PRED_LOOP_EXIT,
683 (REG_BR_PROB_BASE
684 - predictor_info [(int) PRED_LOOP_EXIT].hitrate)
685 / exits);
688 /* Free basic blocks from get_loop_body. */
689 free (bbs);
692 if (!rtlsimpleloops)
693 scev_reset ();
696 /* Attempt to predict probabilities of BB outgoing edges using local
697 properties. */
698 static void
699 bb_estimate_probability_locally (basic_block bb)
701 rtx last_insn = BB_END (bb);
702 rtx cond;
704 if (! can_predict_insn_p (last_insn))
705 return;
706 cond = get_condition (last_insn, NULL, false, false);
707 if (! cond)
708 return;
710 /* Try "pointer heuristic."
711 A comparison ptr == 0 is predicted as false.
712 Similarly, a comparison ptr1 == ptr2 is predicted as false. */
713 if (COMPARISON_P (cond)
714 && ((REG_P (XEXP (cond, 0)) && REG_POINTER (XEXP (cond, 0)))
715 || (REG_P (XEXP (cond, 1)) && REG_POINTER (XEXP (cond, 1)))))
717 if (GET_CODE (cond) == EQ)
718 predict_insn_def (last_insn, PRED_POINTER, NOT_TAKEN);
719 else if (GET_CODE (cond) == NE)
720 predict_insn_def (last_insn, PRED_POINTER, TAKEN);
722 else
724 /* Try "opcode heuristic."
725 EQ tests are usually false and NE tests are usually true. Also,
726 most quantities are positive, so we can make the appropriate guesses
727 about signed comparisons against zero. */
728 switch (GET_CODE (cond))
730 case CONST_INT:
731 /* Unconditional branch. */
732 predict_insn_def (last_insn, PRED_UNCONDITIONAL,
733 cond == const0_rtx ? NOT_TAKEN : TAKEN);
734 break;
736 case EQ:
737 case UNEQ:
738 /* Floating point comparisons appears to behave in a very
739 unpredictable way because of special role of = tests in
740 FP code. */
741 if (FLOAT_MODE_P (GET_MODE (XEXP (cond, 0))))
743 /* Comparisons with 0 are often used for booleans and there is
744 nothing useful to predict about them. */
745 else if (XEXP (cond, 1) == const0_rtx
746 || XEXP (cond, 0) == const0_rtx)
748 else
749 predict_insn_def (last_insn, PRED_OPCODE_NONEQUAL, NOT_TAKEN);
750 break;
752 case NE:
753 case LTGT:
754 /* Floating point comparisons appears to behave in a very
755 unpredictable way because of special role of = tests in
756 FP code. */
757 if (FLOAT_MODE_P (GET_MODE (XEXP (cond, 0))))
759 /* Comparisons with 0 are often used for booleans and there is
760 nothing useful to predict about them. */
761 else if (XEXP (cond, 1) == const0_rtx
762 || XEXP (cond, 0) == const0_rtx)
764 else
765 predict_insn_def (last_insn, PRED_OPCODE_NONEQUAL, TAKEN);
766 break;
768 case ORDERED:
769 predict_insn_def (last_insn, PRED_FPOPCODE, TAKEN);
770 break;
772 case UNORDERED:
773 predict_insn_def (last_insn, PRED_FPOPCODE, NOT_TAKEN);
774 break;
776 case LE:
777 case LT:
778 if (XEXP (cond, 1) == const0_rtx || XEXP (cond, 1) == const1_rtx
779 || XEXP (cond, 1) == constm1_rtx)
780 predict_insn_def (last_insn, PRED_OPCODE_POSITIVE, NOT_TAKEN);
781 break;
783 case GE:
784 case GT:
785 if (XEXP (cond, 1) == const0_rtx || XEXP (cond, 1) == const1_rtx
786 || XEXP (cond, 1) == constm1_rtx)
787 predict_insn_def (last_insn, PRED_OPCODE_POSITIVE, TAKEN);
788 break;
790 default:
791 break;
795 /* Statically estimate the probability that a branch will be taken and produce
796 estimated profile. When profile feedback is present never executed portions
797 of function gets estimated. */
799 void
800 estimate_probability (struct loops *loops_info)
802 basic_block bb;
804 connect_infinite_loops_to_exit ();
805 calculate_dominance_info (CDI_DOMINATORS);
806 calculate_dominance_info (CDI_POST_DOMINATORS);
808 predict_loops (loops_info, true);
810 iv_analysis_done ();
812 /* Attempt to predict conditional jumps using a number of heuristics. */
813 FOR_EACH_BB (bb)
815 rtx last_insn = BB_END (bb);
816 edge e;
818 if (! can_predict_insn_p (last_insn))
819 continue;
821 for (e = bb->succ; e; e = e->succ_next)
823 /* Predict early returns to be probable, as we've already taken
824 care for error returns and other are often used for fast paths
825 trought function. */
826 if ((e->dest == EXIT_BLOCK_PTR
827 || (e->dest->succ && !e->dest->succ->succ_next
828 && e->dest->succ->dest == EXIT_BLOCK_PTR))
829 && !predicted_by_p (bb, PRED_NULL_RETURN)
830 && !predicted_by_p (bb, PRED_CONST_RETURN)
831 && !predicted_by_p (bb, PRED_NEGATIVE_RETURN)
832 && !last_basic_block_p (e->dest))
833 predict_edge_def (e, PRED_EARLY_RETURN, TAKEN);
835 /* Look for block we are guarding (i.e. we dominate it,
836 but it doesn't postdominate us). */
837 if (e->dest != EXIT_BLOCK_PTR && e->dest != bb
838 && dominated_by_p (CDI_DOMINATORS, e->dest, e->src)
839 && !dominated_by_p (CDI_POST_DOMINATORS, e->src, e->dest))
841 rtx insn;
843 /* The call heuristic claims that a guarded function call
844 is improbable. This is because such calls are often used
845 to signal exceptional situations such as printing error
846 messages. */
847 for (insn = BB_HEAD (e->dest); insn != NEXT_INSN (BB_END (e->dest));
848 insn = NEXT_INSN (insn))
849 if (CALL_P (insn)
850 /* Constant and pure calls are hardly used to signalize
851 something exceptional. */
852 && ! CONST_OR_PURE_CALL_P (insn))
854 predict_edge_def (e, PRED_CALL, NOT_TAKEN);
855 break;
859 bb_estimate_probability_locally (bb);
862 /* Attach the combined probability to each conditional jump. */
863 FOR_EACH_BB (bb)
864 combine_predictions_for_insn (BB_END (bb), bb);
866 remove_fake_edges ();
867 estimate_bb_frequencies (loops_info);
868 free_dominance_info (CDI_POST_DOMINATORS);
869 if (profile_status == PROFILE_ABSENT)
870 profile_status = PROFILE_GUESSED;
873 /* Set edge->probability for each successor edge of BB. */
874 void
875 guess_outgoing_edge_probabilities (basic_block bb)
877 bb_estimate_probability_locally (bb);
878 combine_predictions_for_insn (BB_END (bb), bb);
881 /* Return constant EXPR will likely have at execution time, NULL if unknown.
882 The function is used by builtin_expect branch predictor so the evidence
883 must come from this construct and additional possible constant folding.
885 We may want to implement more involved value guess (such as value range
886 propagation based prediction), but such tricks shall go to new
887 implementation. */
889 static tree
890 expr_expected_value (tree expr, bitmap visited)
892 if (TREE_CONSTANT (expr))
893 return expr;
894 else if (TREE_CODE (expr) == SSA_NAME)
896 tree def = SSA_NAME_DEF_STMT (expr);
898 /* If we were already here, break the infinite cycle. */
899 if (bitmap_bit_p (visited, SSA_NAME_VERSION (expr)))
900 return NULL;
901 bitmap_set_bit (visited, SSA_NAME_VERSION (expr));
903 if (TREE_CODE (def) == PHI_NODE)
905 /* All the arguments of the PHI node must have the same constant
906 length. */
907 int i;
908 tree val = NULL, new_val;
910 for (i = 0; i < PHI_NUM_ARGS (def); i++)
912 tree arg = PHI_ARG_DEF (def, i);
914 /* If this PHI has itself as an argument, we cannot
915 determine the string length of this argument. However,
916 if we can find a expected constant value for the other
917 PHI args then we can still be sure that this is
918 likely a constant. So be optimistic and just
919 continue with the next argument. */
920 if (arg == PHI_RESULT (def))
921 continue;
923 new_val = expr_expected_value (arg, visited);
924 if (!new_val)
925 return NULL;
926 if (!val)
927 val = new_val;
928 else if (!operand_equal_p (val, new_val, false))
929 return NULL;
931 return val;
933 if (TREE_CODE (def) != MODIFY_EXPR || TREE_OPERAND (def, 0) != expr)
934 return NULL;
935 return expr_expected_value (TREE_OPERAND (def, 1), visited);
937 else if (TREE_CODE (expr) == CALL_EXPR)
939 tree decl = get_callee_fndecl (expr);
940 if (!decl)
941 return NULL;
942 if (DECL_BUILT_IN (decl) && DECL_FUNCTION_CODE (decl) == BUILT_IN_EXPECT)
944 tree arglist = TREE_OPERAND (expr, 1);
945 tree val;
947 if (arglist == NULL_TREE
948 || TREE_CHAIN (arglist) == NULL_TREE)
949 return NULL;
950 val = TREE_VALUE (TREE_CHAIN (TREE_OPERAND (expr, 1)));
951 if (TREE_CONSTANT (val))
952 return val;
953 return TREE_VALUE (TREE_CHAIN (TREE_OPERAND (expr, 1)));
956 if (BINARY_CLASS_P (expr) || COMPARISON_CLASS_P (expr))
958 tree op0, op1, res;
959 op0 = expr_expected_value (TREE_OPERAND (expr, 0), visited);
960 if (!op0)
961 return NULL;
962 op1 = expr_expected_value (TREE_OPERAND (expr, 1), visited);
963 if (!op1)
964 return NULL;
965 res = fold (build (TREE_CODE (expr), TREE_TYPE (expr), op0, op1));
966 if (TREE_CONSTANT (res))
967 return res;
968 return NULL;
970 if (UNARY_CLASS_P (expr))
972 tree op0, res;
973 op0 = expr_expected_value (TREE_OPERAND (expr, 0), visited);
974 if (!op0)
975 return NULL;
976 res = fold (build1 (TREE_CODE (expr), TREE_TYPE (expr), op0));
977 if (TREE_CONSTANT (res))
978 return res;
979 return NULL;
981 return NULL;
984 /* Get rid of all builtin_expect calls we no longer need. */
985 static void
986 strip_builtin_expect (void)
988 basic_block bb;
989 FOR_EACH_BB (bb)
991 block_stmt_iterator bi;
992 for (bi = bsi_start (bb); !bsi_end_p (bi); bsi_next (&bi))
994 tree stmt = bsi_stmt (bi);
995 tree fndecl;
996 tree arglist;
998 if (TREE_CODE (stmt) == MODIFY_EXPR
999 && TREE_CODE (TREE_OPERAND (stmt, 1)) == CALL_EXPR
1000 && (fndecl = get_callee_fndecl (TREE_OPERAND (stmt, 1)))
1001 && DECL_BUILT_IN (fndecl)
1002 && DECL_FUNCTION_CODE (fndecl) == BUILT_IN_EXPECT
1003 && (arglist = TREE_OPERAND (TREE_OPERAND (stmt, 1), 1))
1004 && TREE_CHAIN (arglist))
1006 TREE_OPERAND (stmt, 1) = TREE_VALUE (arglist);
1007 modify_stmt (stmt);
1013 /* Predict using opcode of the last statement in basic block. */
1014 static void
1015 tree_predict_by_opcode (basic_block bb)
1017 tree stmt = last_stmt (bb);
1018 edge then_edge;
1019 tree cond;
1020 tree op0;
1021 tree type;
1022 tree val;
1023 bitmap visited;
1025 if (!stmt || TREE_CODE (stmt) != COND_EXPR)
1026 return;
1027 for (then_edge = bb->succ; then_edge; then_edge = then_edge->succ_next)
1028 if (then_edge->flags & EDGE_TRUE_VALUE)
1029 break;
1030 cond = TREE_OPERAND (stmt, 0);
1031 if (!COMPARISON_CLASS_P (cond))
1032 return;
1033 op0 = TREE_OPERAND (cond, 0);
1034 type = TREE_TYPE (op0);
1035 visited = BITMAP_XMALLOC ();
1036 val = expr_expected_value (cond, visited);
1037 BITMAP_XFREE (visited);
1038 if (val)
1040 if (integer_zerop (val))
1041 predict_edge_def (then_edge, PRED_BUILTIN_EXPECT, NOT_TAKEN);
1042 else
1043 predict_edge_def (then_edge, PRED_BUILTIN_EXPECT, TAKEN);
1044 return;
1046 /* Try "pointer heuristic."
1047 A comparison ptr == 0 is predicted as false.
1048 Similarly, a comparison ptr1 == ptr2 is predicted as false. */
1049 if (POINTER_TYPE_P (type))
1051 if (TREE_CODE (cond) == EQ_EXPR)
1052 predict_edge_def (then_edge, PRED_TREE_POINTER, NOT_TAKEN);
1053 else if (TREE_CODE (cond) == NE_EXPR)
1054 predict_edge_def (then_edge, PRED_TREE_POINTER, TAKEN);
1056 else
1058 /* Try "opcode heuristic."
1059 EQ tests are usually false and NE tests are usually true. Also,
1060 most quantities are positive, so we can make the appropriate guesses
1061 about signed comparisons against zero. */
1062 switch (TREE_CODE (cond))
1064 case EQ_EXPR:
1065 case UNEQ_EXPR:
1066 /* Floating point comparisons appears to behave in a very
1067 unpredictable way because of special role of = tests in
1068 FP code. */
1069 if (FLOAT_TYPE_P (type))
1071 /* Comparisons with 0 are often used for booleans and there is
1072 nothing useful to predict about them. */
1073 else if (integer_zerop (op0)
1074 || integer_zerop (TREE_OPERAND (cond, 1)))
1076 else
1077 predict_edge_def (then_edge, PRED_TREE_OPCODE_NONEQUAL, NOT_TAKEN);
1078 break;
1080 case NE_EXPR:
1081 case LTGT_EXPR:
1082 /* Floating point comparisons appears to behave in a very
1083 unpredictable way because of special role of = tests in
1084 FP code. */
1085 if (FLOAT_TYPE_P (type))
1087 /* Comparisons with 0 are often used for booleans and there is
1088 nothing useful to predict about them. */
1089 else if (integer_zerop (op0)
1090 || integer_zerop (TREE_OPERAND (cond, 1)))
1092 else
1093 predict_edge_def (then_edge, PRED_TREE_OPCODE_NONEQUAL, TAKEN);
1094 break;
1096 case ORDERED_EXPR:
1097 predict_edge_def (then_edge, PRED_TREE_FPOPCODE, TAKEN);
1098 break;
1100 case UNORDERED_EXPR:
1101 predict_edge_def (then_edge, PRED_TREE_FPOPCODE, NOT_TAKEN);
1102 break;
1104 case LE_EXPR:
1105 case LT_EXPR:
1106 if (integer_zerop (TREE_OPERAND (cond, 1))
1107 || integer_onep (TREE_OPERAND (cond, 1))
1108 || integer_all_onesp (TREE_OPERAND (cond, 1))
1109 || real_zerop (TREE_OPERAND (cond, 1))
1110 || real_onep (TREE_OPERAND (cond, 1))
1111 || real_minus_onep (TREE_OPERAND (cond, 1)))
1112 predict_edge_def (then_edge, PRED_TREE_OPCODE_POSITIVE, NOT_TAKEN);
1113 break;
1115 case GE_EXPR:
1116 case GT_EXPR:
1117 if (integer_zerop (TREE_OPERAND (cond, 1))
1118 || integer_onep (TREE_OPERAND (cond, 1))
1119 || integer_all_onesp (TREE_OPERAND (cond, 1))
1120 || real_zerop (TREE_OPERAND (cond, 1))
1121 || real_onep (TREE_OPERAND (cond, 1))
1122 || real_minus_onep (TREE_OPERAND (cond, 1)))
1123 predict_edge_def (then_edge, PRED_TREE_OPCODE_POSITIVE, TAKEN);
1124 break;
1126 default:
1127 break;
1131 /* Try to guess whether the value of return means error code. */
1132 static enum br_predictor
1133 return_prediction (tree val, enum prediction *prediction)
1135 /* VOID. */
1136 if (!val)
1137 return PRED_NO_PREDICTION;
1138 /* Different heuristics for pointers and scalars. */
1139 if (POINTER_TYPE_P (TREE_TYPE (val)))
1141 /* NULL is usually not returned. */
1142 if (integer_zerop (val))
1144 *prediction = NOT_TAKEN;
1145 return PRED_NULL_RETURN;
1148 else if (INTEGRAL_TYPE_P (TREE_TYPE (val)))
1150 /* Negative return values are often used to indicate
1151 errors. */
1152 if (TREE_CODE (val) == INTEGER_CST
1153 && tree_int_cst_sgn (val) < 0)
1155 *prediction = NOT_TAKEN;
1156 return PRED_NEGATIVE_RETURN;
1158 /* Constant return values seems to be commonly taken.
1159 Zero/one often represent booleans so exclude them from the
1160 heuristics. */
1161 if (TREE_CONSTANT (val)
1162 && (!integer_zerop (val) && !integer_onep (val)))
1164 *prediction = TAKEN;
1165 return PRED_NEGATIVE_RETURN;
1168 return PRED_NO_PREDICTION;
1171 /* Find the basic block with return expression and look up for possible
1172 return value trying to apply RETURN_PREDICTION heuristics. */
1173 static void
1174 apply_return_prediction (int *heads)
1176 tree return_stmt;
1177 tree return_val;
1178 edge e;
1179 tree phi;
1180 int phi_num_args, i;
1181 enum br_predictor pred;
1182 enum prediction direction;
1184 for (e = EXIT_BLOCK_PTR->pred; e ; e = e->pred_next)
1186 return_stmt = last_stmt (e->src);
1187 if (TREE_CODE (return_stmt) == RETURN_EXPR)
1188 break;
1190 if (!e)
1191 return;
1192 return_val = TREE_OPERAND (return_stmt, 0);
1193 if (!return_val)
1194 return;
1195 if (TREE_CODE (return_val) == MODIFY_EXPR)
1196 return_val = TREE_OPERAND (return_val, 1);
1197 if (TREE_CODE (return_val) != SSA_NAME
1198 || !SSA_NAME_DEF_STMT (return_val)
1199 || TREE_CODE (SSA_NAME_DEF_STMT (return_val)) != PHI_NODE)
1200 return;
1201 phi = SSA_NAME_DEF_STMT (return_val);
1202 while (phi)
1204 tree next = PHI_CHAIN (phi);
1205 if (PHI_RESULT (phi) == return_val)
1206 break;
1207 phi = next;
1209 if (!phi)
1210 return;
1211 phi_num_args = PHI_NUM_ARGS (phi);
1212 pred = return_prediction (PHI_ARG_DEF (phi, 0), &direction);
1214 /* Avoid the degenerate case where all return values form the function
1215 belongs to same category (ie they are all positive constants)
1216 so we can hardly say something about them. */
1217 for (i = 1; i < phi_num_args; i++)
1218 if (pred != return_prediction (PHI_ARG_DEF (phi, i), &direction))
1219 break;
1220 if (i != phi_num_args)
1221 for (i = 0; i < phi_num_args; i++)
1223 pred = return_prediction (PHI_ARG_DEF (phi, i), &direction);
1224 if (pred != PRED_NO_PREDICTION)
1225 predict_paths_leading_to (PHI_ARG_EDGE (phi, i)->src, heads, pred,
1226 direction);
1230 /* Look for basic block that contains unlikely to happen events
1231 (such as noreturn calls) and mark all paths leading to execution
1232 of this basic blocks as unlikely. */
1234 static void
1235 tree_bb_level_predictions (void)
1237 basic_block bb;
1238 int *heads;
1240 heads = xmalloc (sizeof (int) * last_basic_block);
1241 memset (heads, -1, sizeof (int) * last_basic_block);
1242 heads[ENTRY_BLOCK_PTR->next_bb->index] = last_basic_block;
1244 apply_return_prediction (heads);
1246 FOR_EACH_BB (bb)
1248 block_stmt_iterator bsi = bsi_last (bb);
1250 for (bsi = bsi_start (bb); !bsi_end_p (bsi); bsi_next (&bsi))
1252 tree stmt = bsi_stmt (bsi);
1253 switch (TREE_CODE (stmt))
1255 case MODIFY_EXPR:
1256 if (TREE_CODE (TREE_OPERAND (stmt, 1)) == CALL_EXPR)
1258 stmt = TREE_OPERAND (stmt, 1);
1259 goto call_expr;
1261 break;
1262 case CALL_EXPR:
1263 call_expr:;
1264 if (call_expr_flags (stmt) & ECF_NORETURN)
1265 predict_paths_leading_to (bb, heads, PRED_NORETURN,
1266 NOT_TAKEN);
1267 break;
1268 default:
1269 break;
1274 free (heads);
1277 /* Predict branch probabilities and estimate profile of the tree CFG. */
1278 static void
1279 tree_estimate_probability (void)
1281 basic_block bb;
1282 struct loops loops_info;
1284 flow_loops_find (&loops_info, LOOP_TREE);
1285 if (dump_file && (dump_flags & TDF_DETAILS))
1286 flow_loops_dump (&loops_info, dump_file, NULL, 0);
1288 add_noreturn_fake_exit_edges ();
1289 connect_infinite_loops_to_exit ();
1290 calculate_dominance_info (CDI_DOMINATORS);
1291 calculate_dominance_info (CDI_POST_DOMINATORS);
1293 tree_bb_level_predictions ();
1295 predict_loops (&loops_info, false);
1297 FOR_EACH_BB (bb)
1299 edge e;
1301 for (e = bb->succ; e; e = e->succ_next)
1303 /* Predict early returns to be probable, as we've already taken
1304 care for error returns and other cases are often used for
1305 fast paths trought function. */
1306 if (e->dest == EXIT_BLOCK_PTR
1307 && TREE_CODE (last_stmt (bb)) == RETURN_EXPR
1308 && bb->pred && bb->pred->pred_next)
1310 edge e1;
1312 for (e1 = bb->pred; e1; e1 = e1->pred_next)
1313 if (!predicted_by_p (e1->src, PRED_NULL_RETURN)
1314 && !predicted_by_p (e1->src, PRED_CONST_RETURN)
1315 && !predicted_by_p (e1->src, PRED_NEGATIVE_RETURN)
1316 && !last_basic_block_p (e1->src))
1317 predict_edge_def (e1, PRED_TREE_EARLY_RETURN, NOT_TAKEN);
1320 /* Look for block we are guarding (ie we dominate it,
1321 but it doesn't postdominate us). */
1322 if (e->dest != EXIT_BLOCK_PTR && e->dest != bb
1323 && dominated_by_p (CDI_DOMINATORS, e->dest, e->src)
1324 && !dominated_by_p (CDI_POST_DOMINATORS, e->src, e->dest))
1326 block_stmt_iterator bi;
1328 /* The call heuristic claims that a guarded function call
1329 is improbable. This is because such calls are often used
1330 to signal exceptional situations such as printing error
1331 messages. */
1332 for (bi = bsi_start (e->dest); !bsi_end_p (bi);
1333 bsi_next (&bi))
1335 tree stmt = bsi_stmt (bi);
1336 if ((TREE_CODE (stmt) == CALL_EXPR
1337 || (TREE_CODE (stmt) == MODIFY_EXPR
1338 && TREE_CODE (TREE_OPERAND (stmt, 1)) == CALL_EXPR))
1339 /* Constant and pure calls are hardly used to signalize
1340 something exceptional. */
1341 && TREE_SIDE_EFFECTS (stmt))
1343 predict_edge_def (e, PRED_CALL, NOT_TAKEN);
1344 break;
1349 tree_predict_by_opcode (bb);
1351 FOR_EACH_BB (bb)
1352 combine_predictions_for_bb (dump_file, bb);
1354 if (0) /* FIXME: Enable once we are pass down the profile to RTL level. */
1355 strip_builtin_expect ();
1356 estimate_bb_frequencies (&loops_info);
1357 free_dominance_info (CDI_POST_DOMINATORS);
1358 remove_fake_exit_edges ();
1359 flow_loops_free (&loops_info);
1360 if (dump_file && (dump_flags & TDF_DETAILS))
1361 dump_tree_cfg (dump_file, dump_flags);
1362 if (profile_status == PROFILE_ABSENT)
1363 profile_status = PROFILE_GUESSED;
1366 /* __builtin_expect dropped tokens into the insn stream describing expected
1367 values of registers. Generate branch probabilities based off these
1368 values. */
1370 void
1371 expected_value_to_br_prob (void)
1373 rtx insn, cond, ev = NULL_RTX, ev_reg = NULL_RTX;
1375 for (insn = get_insns (); insn ; insn = NEXT_INSN (insn))
1377 switch (GET_CODE (insn))
1379 case NOTE:
1380 /* Look for expected value notes. */
1381 if (NOTE_LINE_NUMBER (insn) == NOTE_INSN_EXPECTED_VALUE)
1383 ev = NOTE_EXPECTED_VALUE (insn);
1384 ev_reg = XEXP (ev, 0);
1385 delete_insn (insn);
1387 continue;
1389 case CODE_LABEL:
1390 /* Never propagate across labels. */
1391 ev = NULL_RTX;
1392 continue;
1394 case JUMP_INSN:
1395 /* Look for simple conditional branches. If we haven't got an
1396 expected value yet, no point going further. */
1397 if (!JUMP_P (insn) || ev == NULL_RTX
1398 || ! any_condjump_p (insn))
1399 continue;
1400 break;
1402 default:
1403 /* Look for insns that clobber the EV register. */
1404 if (ev && reg_set_p (ev_reg, insn))
1405 ev = NULL_RTX;
1406 continue;
1409 /* Collect the branch condition, hopefully relative to EV_REG. */
1410 /* ??? At present we'll miss things like
1411 (expected_value (eq r70 0))
1412 (set r71 -1)
1413 (set r80 (lt r70 r71))
1414 (set pc (if_then_else (ne r80 0) ...))
1415 as canonicalize_condition will render this to us as
1416 (lt r70, r71)
1417 Could use cselib to try and reduce this further. */
1418 cond = XEXP (SET_SRC (pc_set (insn)), 0);
1419 cond = canonicalize_condition (insn, cond, 0, NULL, ev_reg,
1420 false, false);
1421 if (! cond || XEXP (cond, 0) != ev_reg
1422 || GET_CODE (XEXP (cond, 1)) != CONST_INT)
1423 continue;
1425 /* Substitute and simplify. Given that the expression we're
1426 building involves two constants, we should wind up with either
1427 true or false. */
1428 cond = gen_rtx_fmt_ee (GET_CODE (cond), VOIDmode,
1429 XEXP (ev, 1), XEXP (cond, 1));
1430 cond = simplify_rtx (cond);
1432 /* Turn the condition into a scaled branch probability. */
1433 if (cond != const_true_rtx && cond != const0_rtx)
1434 abort ();
1435 predict_insn_def (insn, PRED_BUILTIN_EXPECT,
1436 cond == const_true_rtx ? TAKEN : NOT_TAKEN);
1440 /* Check whether this is the last basic block of function. Commonly
1441 there is one extra common cleanup block. */
1442 static bool
1443 last_basic_block_p (basic_block bb)
1445 if (bb == EXIT_BLOCK_PTR)
1446 return false;
1448 return (bb->next_bb == EXIT_BLOCK_PTR
1449 || (bb->next_bb->next_bb == EXIT_BLOCK_PTR
1450 && bb->succ && !bb->succ->succ_next
1451 && bb->succ->dest->next_bb == EXIT_BLOCK_PTR));
1454 /* Sets branch probabilities according to PREDiction and
1455 FLAGS. HEADS[bb->index] should be index of basic block in that we
1456 need to alter branch predictions (i.e. the first of our dominators
1457 such that we do not post-dominate it) (but we fill this information
1458 on demand, so -1 may be there in case this was not needed yet). */
1460 static void
1461 predict_paths_leading_to (basic_block bb, int *heads, enum br_predictor pred,
1462 enum prediction taken)
1464 edge e;
1465 int y;
1467 if (heads[bb->index] < 0)
1469 /* This is first time we need this field in heads array; so
1470 find first dominator that we do not post-dominate (we are
1471 using already known members of heads array). */
1472 basic_block ai = bb;
1473 basic_block next_ai = get_immediate_dominator (CDI_DOMINATORS, bb);
1474 int head;
1476 while (heads[next_ai->index] < 0)
1478 if (!dominated_by_p (CDI_POST_DOMINATORS, next_ai, bb))
1479 break;
1480 heads[next_ai->index] = ai->index;
1481 ai = next_ai;
1482 next_ai = get_immediate_dominator (CDI_DOMINATORS, next_ai);
1484 if (!dominated_by_p (CDI_POST_DOMINATORS, next_ai, bb))
1485 head = next_ai->index;
1486 else
1487 head = heads[next_ai->index];
1488 while (next_ai != bb)
1490 next_ai = ai;
1491 if (heads[ai->index] == ENTRY_BLOCK)
1492 ai = ENTRY_BLOCK_PTR;
1493 else
1494 ai = BASIC_BLOCK (heads[ai->index]);
1495 heads[next_ai->index] = head;
1498 y = heads[bb->index];
1500 /* Now find the edge that leads to our branch and aply the prediction. */
1502 if (y == last_basic_block)
1503 return;
1504 for (e = BASIC_BLOCK (y)->succ; e; e = e->succ_next)
1505 if (e->dest->index >= 0
1506 && dominated_by_p (CDI_POST_DOMINATORS, e->dest, bb))
1507 predict_edge_def (e, pred, taken);
1510 /* This is used to carry information about basic blocks. It is
1511 attached to the AUX field of the standard CFG block. */
1513 typedef struct block_info_def
1515 /* Estimated frequency of execution of basic_block. */
1516 sreal frequency;
1518 /* To keep queue of basic blocks to process. */
1519 basic_block next;
1521 /* True if block needs to be visited in propagate_freq. */
1522 unsigned int tovisit:1;
1524 /* Number of predecessors we need to visit first. */
1525 int npredecessors;
1526 } *block_info;
1528 /* Similar information for edges. */
1529 typedef struct edge_info_def
1531 /* In case edge is an loopback edge, the probability edge will be reached
1532 in case header is. Estimated number of iterations of the loop can be
1533 then computed as 1 / (1 - back_edge_prob). */
1534 sreal back_edge_prob;
1535 /* True if the edge is an loopback edge in the natural loop. */
1536 unsigned int back_edge:1;
1537 } *edge_info;
1539 #define BLOCK_INFO(B) ((block_info) (B)->aux)
1540 #define EDGE_INFO(E) ((edge_info) (E)->aux)
1542 /* Helper function for estimate_bb_frequencies.
1543 Propagate the frequencies for LOOP. */
1545 static void
1546 propagate_freq (struct loop *loop)
1548 basic_block head = loop->header;
1549 basic_block bb;
1550 basic_block last;
1551 edge e;
1552 basic_block nextbb;
1554 /* For each basic block we need to visit count number of his predecessors
1555 we need to visit first. */
1556 FOR_BB_BETWEEN (bb, ENTRY_BLOCK_PTR, NULL, next_bb)
1558 if (BLOCK_INFO (bb)->tovisit)
1560 int count = 0;
1562 for (e = bb->pred; e; e = e->pred_next)
1563 if (BLOCK_INFO (e->src)->tovisit && !(e->flags & EDGE_DFS_BACK))
1564 count++;
1565 else if (BLOCK_INFO (e->src)->tovisit
1566 && dump_file && !EDGE_INFO (e)->back_edge)
1567 fprintf (dump_file,
1568 "Irreducible region hit, ignoring edge to %i->%i\n",
1569 e->src->index, bb->index);
1570 BLOCK_INFO (bb)->npredecessors = count;
1574 memcpy (&BLOCK_INFO (head)->frequency, &real_one, sizeof (real_one));
1575 last = head;
1576 for (bb = head; bb; bb = nextbb)
1578 sreal cyclic_probability, frequency;
1580 memcpy (&cyclic_probability, &real_zero, sizeof (real_zero));
1581 memcpy (&frequency, &real_zero, sizeof (real_zero));
1583 nextbb = BLOCK_INFO (bb)->next;
1584 BLOCK_INFO (bb)->next = NULL;
1586 /* Compute frequency of basic block. */
1587 if (bb != head)
1589 #ifdef ENABLE_CHECKING
1590 for (e = bb->pred; e; e = e->pred_next)
1591 if (BLOCK_INFO (e->src)->tovisit && !(e->flags & EDGE_DFS_BACK))
1592 abort ();
1593 #endif
1595 for (e = bb->pred; e; e = e->pred_next)
1596 if (EDGE_INFO (e)->back_edge)
1598 sreal_add (&cyclic_probability, &cyclic_probability,
1599 &EDGE_INFO (e)->back_edge_prob);
1601 else if (!(e->flags & EDGE_DFS_BACK))
1603 sreal tmp;
1605 /* frequency += (e->probability
1606 * BLOCK_INFO (e->src)->frequency /
1607 REG_BR_PROB_BASE); */
1609 sreal_init (&tmp, e->probability, 0);
1610 sreal_mul (&tmp, &tmp, &BLOCK_INFO (e->src)->frequency);
1611 sreal_mul (&tmp, &tmp, &real_inv_br_prob_base);
1612 sreal_add (&frequency, &frequency, &tmp);
1615 if (sreal_compare (&cyclic_probability, &real_zero) == 0)
1617 memcpy (&BLOCK_INFO (bb)->frequency, &frequency,
1618 sizeof (frequency));
1620 else
1622 if (sreal_compare (&cyclic_probability, &real_almost_one) > 0)
1624 memcpy (&cyclic_probability, &real_almost_one,
1625 sizeof (real_almost_one));
1628 /* BLOCK_INFO (bb)->frequency = frequency
1629 / (1 - cyclic_probability) */
1631 sreal_sub (&cyclic_probability, &real_one, &cyclic_probability);
1632 sreal_div (&BLOCK_INFO (bb)->frequency,
1633 &frequency, &cyclic_probability);
1637 BLOCK_INFO (bb)->tovisit = 0;
1639 /* Compute back edge frequencies. */
1640 for (e = bb->succ; e; e = e->succ_next)
1641 if (e->dest == head)
1643 sreal tmp;
1645 /* EDGE_INFO (e)->back_edge_prob
1646 = ((e->probability * BLOCK_INFO (bb)->frequency)
1647 / REG_BR_PROB_BASE); */
1649 sreal_init (&tmp, e->probability, 0);
1650 sreal_mul (&tmp, &tmp, &BLOCK_INFO (bb)->frequency);
1651 sreal_mul (&EDGE_INFO (e)->back_edge_prob,
1652 &tmp, &real_inv_br_prob_base);
1655 /* Propagate to successor blocks. */
1656 for (e = bb->succ; e; e = e->succ_next)
1657 if (!(e->flags & EDGE_DFS_BACK)
1658 && BLOCK_INFO (e->dest)->npredecessors)
1660 BLOCK_INFO (e->dest)->npredecessors--;
1661 if (!BLOCK_INFO (e->dest)->npredecessors)
1663 if (!nextbb)
1664 nextbb = e->dest;
1665 else
1666 BLOCK_INFO (last)->next = e->dest;
1668 last = e->dest;
1674 /* Estimate probabilities of loopback edges in loops at same nest level. */
1676 static void
1677 estimate_loops_at_level (struct loop *first_loop)
1679 struct loop *loop;
1681 for (loop = first_loop; loop; loop = loop->next)
1683 edge e;
1684 basic_block *bbs;
1685 unsigned i;
1687 estimate_loops_at_level (loop->inner);
1689 if (loop->latch->succ) /* Do not do this for dummy function loop. */
1691 /* Find current loop back edge and mark it. */
1692 e = loop_latch_edge (loop);
1693 EDGE_INFO (e)->back_edge = 1;
1696 bbs = get_loop_body (loop);
1697 for (i = 0; i < loop->num_nodes; i++)
1698 BLOCK_INFO (bbs[i])->tovisit = 1;
1699 free (bbs);
1700 propagate_freq (loop);
1704 /* Convert counts measured by profile driven feedback to frequencies.
1705 Return nonzero iff there was any nonzero execution count. */
1708 counts_to_freqs (void)
1710 gcov_type count_max, true_count_max = 0;
1711 basic_block bb;
1713 FOR_EACH_BB (bb)
1714 true_count_max = MAX (bb->count, true_count_max);
1716 count_max = MAX (true_count_max, 1);
1717 FOR_BB_BETWEEN (bb, ENTRY_BLOCK_PTR, NULL, next_bb)
1718 bb->frequency = (bb->count * BB_FREQ_MAX + count_max / 2) / count_max;
1719 return true_count_max;
1722 /* Return true if function is likely to be expensive, so there is no point to
1723 optimize performance of prologue, epilogue or do inlining at the expense
1724 of code size growth. THRESHOLD is the limit of number of instructions
1725 function can execute at average to be still considered not expensive. */
1727 bool
1728 expensive_function_p (int threshold)
1730 unsigned int sum = 0;
1731 basic_block bb;
1732 unsigned int limit;
1734 /* We can not compute accurately for large thresholds due to scaled
1735 frequencies. */
1736 if (threshold > BB_FREQ_MAX)
1737 abort ();
1739 /* Frequencies are out of range. This either means that function contains
1740 internal loop executing more than BB_FREQ_MAX times or profile feedback
1741 is available and function has not been executed at all. */
1742 if (ENTRY_BLOCK_PTR->frequency == 0)
1743 return true;
1745 /* Maximally BB_FREQ_MAX^2 so overflow won't happen. */
1746 limit = ENTRY_BLOCK_PTR->frequency * threshold;
1747 FOR_EACH_BB (bb)
1749 rtx insn;
1751 for (insn = BB_HEAD (bb); insn != NEXT_INSN (BB_END (bb));
1752 insn = NEXT_INSN (insn))
1753 if (active_insn_p (insn))
1755 sum += bb->frequency;
1756 if (sum > limit)
1757 return true;
1761 return false;
1764 /* Estimate basic blocks frequency by given branch probabilities. */
1766 static void
1767 estimate_bb_frequencies (struct loops *loops)
1769 basic_block bb;
1770 sreal freq_max;
1772 if (!flag_branch_probabilities || !counts_to_freqs ())
1774 static int real_values_initialized = 0;
1776 if (!real_values_initialized)
1778 real_values_initialized = 1;
1779 sreal_init (&real_zero, 0, 0);
1780 sreal_init (&real_one, 1, 0);
1781 sreal_init (&real_br_prob_base, REG_BR_PROB_BASE, 0);
1782 sreal_init (&real_bb_freq_max, BB_FREQ_MAX, 0);
1783 sreal_init (&real_one_half, 1, -1);
1784 sreal_div (&real_inv_br_prob_base, &real_one, &real_br_prob_base);
1785 sreal_sub (&real_almost_one, &real_one, &real_inv_br_prob_base);
1788 mark_dfs_back_edges ();
1790 ENTRY_BLOCK_PTR->succ->probability = REG_BR_PROB_BASE;
1792 /* Set up block info for each basic block. */
1793 alloc_aux_for_blocks (sizeof (struct block_info_def));
1794 alloc_aux_for_edges (sizeof (struct edge_info_def));
1795 FOR_BB_BETWEEN (bb, ENTRY_BLOCK_PTR, NULL, next_bb)
1797 edge e;
1799 BLOCK_INFO (bb)->tovisit = 0;
1800 for (e = bb->succ; e; e = e->succ_next)
1802 sreal_init (&EDGE_INFO (e)->back_edge_prob, e->probability, 0);
1803 sreal_mul (&EDGE_INFO (e)->back_edge_prob,
1804 &EDGE_INFO (e)->back_edge_prob,
1805 &real_inv_br_prob_base);
1809 /* First compute probabilities locally for each loop from innermost
1810 to outermost to examine probabilities for back edges. */
1811 estimate_loops_at_level (loops->tree_root);
1813 memcpy (&freq_max, &real_zero, sizeof (real_zero));
1814 FOR_EACH_BB (bb)
1815 if (sreal_compare (&freq_max, &BLOCK_INFO (bb)->frequency) < 0)
1816 memcpy (&freq_max, &BLOCK_INFO (bb)->frequency, sizeof (freq_max));
1818 sreal_div (&freq_max, &real_bb_freq_max, &freq_max);
1819 FOR_BB_BETWEEN (bb, ENTRY_BLOCK_PTR, NULL, next_bb)
1821 sreal tmp;
1823 sreal_mul (&tmp, &BLOCK_INFO (bb)->frequency, &freq_max);
1824 sreal_add (&tmp, &tmp, &real_one_half);
1825 bb->frequency = sreal_to_int (&tmp);
1828 free_aux_for_blocks ();
1829 free_aux_for_edges ();
1831 compute_function_frequency ();
1832 if (flag_reorder_functions)
1833 choose_function_section ();
1836 /* Decide whether function is hot, cold or unlikely executed. */
1837 static void
1838 compute_function_frequency (void)
1840 basic_block bb;
1842 if (!profile_info || !flag_branch_probabilities)
1843 return;
1844 cfun->function_frequency = FUNCTION_FREQUENCY_UNLIKELY_EXECUTED;
1845 FOR_EACH_BB (bb)
1847 if (maybe_hot_bb_p (bb))
1849 cfun->function_frequency = FUNCTION_FREQUENCY_HOT;
1850 return;
1852 if (!probably_never_executed_bb_p (bb))
1853 cfun->function_frequency = FUNCTION_FREQUENCY_NORMAL;
1857 /* Choose appropriate section for the function. */
1858 static void
1859 choose_function_section (void)
1861 if (DECL_SECTION_NAME (current_function_decl)
1862 || !targetm.have_named_sections
1863 /* Theoretically we can split the gnu.linkonce text section too,
1864 but this requires more work as the frequency needs to match
1865 for all generated objects so we need to merge the frequency
1866 of all instances. For now just never set frequency for these. */
1867 || DECL_ONE_ONLY (current_function_decl))
1868 return;
1870 /* If we are doing the partitioning optimization, let the optimization
1871 choose the correct section into which to put things. */
1873 if (flag_reorder_blocks_and_partition)
1874 return;
1876 if (cfun->function_frequency == FUNCTION_FREQUENCY_HOT)
1877 DECL_SECTION_NAME (current_function_decl) =
1878 build_string (strlen (HOT_TEXT_SECTION_NAME), HOT_TEXT_SECTION_NAME);
1879 if (cfun->function_frequency == FUNCTION_FREQUENCY_UNLIKELY_EXECUTED)
1880 DECL_SECTION_NAME (current_function_decl) =
1881 build_string (strlen (UNLIKELY_EXECUTED_TEXT_SECTION_NAME),
1882 UNLIKELY_EXECUTED_TEXT_SECTION_NAME);
1886 struct tree_opt_pass pass_profile =
1888 "profile", /* name */
1889 NULL, /* gate */
1890 tree_estimate_probability, /* execute */
1891 NULL, /* sub */
1892 NULL, /* next */
1893 0, /* static_pass_number */
1894 TV_BRANCH_PROB, /* tv_id */
1895 PROP_cfg, /* properties_required */
1896 0, /* properties_provided */
1897 0, /* properties_destroyed */
1898 0, /* todo_flags_start */
1899 TODO_ggc_collect | TODO_verify_ssa, /* todo_flags_finish */
1900 0 /* letter */